blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
20d323ff9fa25cef89c65f67e3514a0c6eb7241f | e96656f1032e7ba7e23693f010e74b4da90a48ca | /C++/Arrays/Check if given points form a square.cpp | 692dcd6a4462194847e536eb5b532288fe27aaaa | [] | no_license | SelvaBalasubramanian/GeeksForGeeks | 1d1c7f32cdff62e380020fd9ec84d6eb9dbc3180 | 13f28ad42b03befc4aa5840761b9f14969bf127a | refs/heads/master | 2020-03-16T17:45:47.663647 | 2019-08-21T06:20:14 | 2019-08-21T06:20:14 | 132,846,083 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 516 | cpp | #include<iostream>
using namespace std;
typedef struct{
int x;
int y;
}point;
int dist(point a, point b){
return (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y);
}
int main(){
point a = {1,2}, b = {1,0} ,c = {3,0} , d = {3,2};
int d1 = dist(a,b);
int d2 = dist(a,c);
int d3 = dist(a,d);
if(d1 == d2 && 2*d1 == d3)cout<<"is square\n";
else if(d2 == d3 && 2*d2 == d1)cout<<"is square\n";
else if(d1 == d3 && 2*d1 == d2)cout<<"is square\n";
else{
cout<<"is not a square\n";
}
return 0;
} | [
"selva6101996@gmail.com"
] | selva6101996@gmail.com |
4371c7019c44ae841b57ded1cdf79c104c591b2e | ac4d0f3e861d2c042fe2c350603958134a8dd400 | /Dx11.Luna/ShapesApp.cpp | 1520a12f5a702610890c985375d17ac523f526be | [] | no_license | AndreaFloro/Dx11.Luna | c896263938d3550a1f13a61c1994635b5954a485 | d7a864b8bb0043d87269dd931cc72996df44d973 | refs/heads/master | 2021-01-13T00:30:34.888649 | 2017-01-30T21:32:53 | 2017-01-30T21:32:53 | 81,385,632 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,303 | cpp |
#include "ShapesApp.h"
using namespace DirectX;
ShapesApp::ShapesApp(HINSTANCE hInstance)
: D3DApp(hInstance), mVB(0), mIB(0), mFX(0), mTech(0),
mfxWorldViewProj(0), mInputLayout(0), mWireframeRS(0),
mTheta(1.5f*MathHelper::Pi), mPhi(0.1f*MathHelper::Pi), mRadius(15.0f)
{
mMainWndCaption = L"Shapes Demo";
mLastMousePos.x = 0;
mLastMousePos.y = 0;
XMMATRIX I = XMMatrixIdentity();
XMStoreFloat4x4(&mGridWorld, I);
XMStoreFloat4x4(&mView, I);
XMStoreFloat4x4(&mProj, I);
XMMATRIX boxScale = XMMatrixScaling(2.0f, 1.0f, 2.0f);
XMMATRIX boxOffset = XMMatrixTranslation(0.0f, 0.5f, 0.0f);
XMStoreFloat4x4(&mBoxWorld, XMMatrixMultiply(boxScale, boxOffset));
XMMATRIX centerSphereScale = XMMatrixScaling(2.0f, 2.0f, 2.0f);
XMMATRIX centerSphereOffset = XMMatrixTranslation(0.0f, 2.0f, 0.0f);
XMStoreFloat4x4(&mCenterSphere, XMMatrixMultiply(centerSphereScale, centerSphereOffset));
for (int i = 0; i < 5; ++i)
{
XMStoreFloat4x4(&mCylWorld[i * 2 + 0], XMMatrixTranslation(-5.0f, 1.5f, -10.0f + i*5.0f));
XMStoreFloat4x4(&mCylWorld[i * 2 + 1], XMMatrixTranslation(+5.0f, 1.5f, -10.0f + i*5.0f));
XMStoreFloat4x4(&mSphereWorld[i * 2 + 0], XMMatrixTranslation(-5.0f, 3.5f, -10.0f + i*5.0f));
XMStoreFloat4x4(&mSphereWorld[i * 2 + 1], XMMatrixTranslation(+5.0f, 3.5f, -10.0f + i*5.0f));
}
}
ShapesApp::~ShapesApp()
{
ReleaseCOM(mVB);
ReleaseCOM(mIB);
ReleaseCOM(mFX);
ReleaseCOM(mInputLayout);
ReleaseCOM(mWireframeRS);
}
bool ShapesApp::Init()
{
if (!D3DApp::Init())
return false;
BuildGeometryBuffers();
BuildFX();
BuildVertexLayout();
D3D11_RASTERIZER_DESC wireframeDesc;
ZeroMemory(&wireframeDesc, sizeof(D3D11_RASTERIZER_DESC));
wireframeDesc.FillMode = D3D11_FILL_WIREFRAME;
wireframeDesc.CullMode = D3D11_CULL_BACK;
wireframeDesc.FrontCounterClockwise = false;
wireframeDesc.DepthClipEnable = true;
HR(md3dDevice->CreateRasterizerState(&wireframeDesc, &mWireframeRS));
return true;
}
void ShapesApp::OnResize()
{
D3DApp::OnResize();
XMMATRIX P = XMMatrixPerspectiveFovLH(0.25f*MathHelper::Pi, AspectRatio(), 1.0f, 1000.0f);
XMStoreFloat4x4(&mProj, P);
}
void ShapesApp::UpdateScene(float dt)
{
// Convert Spherical to Cartesian coordinates.
float x = mRadius*sinf(mPhi)*cosf(mTheta);
float z = mRadius*sinf(mPhi)*sinf(mTheta);
float y = mRadius*cosf(mPhi);
// Build the view matrix.
XMVECTOR pos = XMVectorSet(x, y, z, 1.0f);
XMVECTOR target = XMVectorZero();
XMVECTOR up = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);
XMMATRIX V = XMMatrixLookAtLH(pos, target, up);
XMStoreFloat4x4(&mView, V);
}
void ShapesApp::DrawScene()
{
md3dImmediateContext->ClearRenderTargetView(mRenderTargetView, reinterpret_cast<const float*>(&Colors::LightSteelBlue));
md3dImmediateContext->ClearDepthStencilView(mDepthStencilView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);
md3dImmediateContext->IASetInputLayout(mInputLayout);
md3dImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
md3dImmediateContext->RSSetState(mWireframeRS);
UINT stride = sizeof(Vertex);
UINT offset = 0;
md3dImmediateContext->IASetVertexBuffers(0, 1, &mVB, &stride, &offset);
md3dImmediateContext->IASetIndexBuffer(mIB, DXGI_FORMAT_R32_UINT, 0);
// Set constants
XMMATRIX view = XMLoadFloat4x4(&mView);
XMMATRIX proj = XMLoadFloat4x4(&mProj);
XMMATRIX viewProj = view*proj;
D3DX11_TECHNIQUE_DESC techDesc;
mTech->GetDesc(&techDesc);
for (UINT p = 0; p < techDesc.Passes; ++p)
{
// Draw the grid.
XMMATRIX world = XMLoadFloat4x4(&mGridWorld);
mfxWorldViewProj->SetMatrix(reinterpret_cast<float*>(&(world*viewProj)));
mTech->GetPassByIndex(p)->Apply(0, md3dImmediateContext);
md3dImmediateContext->DrawIndexed(mGridIndexCount, mGridIndexOffset, mGridVertexOffset);
// Draw the box.
world = XMLoadFloat4x4(&mBoxWorld);
mfxWorldViewProj->SetMatrix(reinterpret_cast<float*>(&(world*viewProj)));
mTech->GetPassByIndex(p)->Apply(0, md3dImmediateContext);
md3dImmediateContext->DrawIndexed(mBoxIndexCount, mBoxIndexOffset, mBoxVertexOffset);
// Draw center sphere.
world = XMLoadFloat4x4(&mCenterSphere);
mfxWorldViewProj->SetMatrix(reinterpret_cast<float*>(&(world*viewProj)));
mTech->GetPassByIndex(p)->Apply(0, md3dImmediateContext);
md3dImmediateContext->DrawIndexed(mSphereIndexCount, mSphereIndexOffset, mSphereVertexOffset);
// Draw the cylinders.
for (int i = 0; i < 10; ++i)
{
world = XMLoadFloat4x4(&mCylWorld[i]);
mfxWorldViewProj->SetMatrix(reinterpret_cast<float*>(&(world*viewProj)));
mTech->GetPassByIndex(p)->Apply(0, md3dImmediateContext);
md3dImmediateContext->DrawIndexed(mCylinderIndexCount, mCylinderIndexOffset, mCylinderVertexOffset);
}
// Draw the spheres.
for (int i = 0; i < 10; ++i)
{
world = XMLoadFloat4x4(&mSphereWorld[i]);
mfxWorldViewProj->SetMatrix(reinterpret_cast<float*>(&(world*viewProj)));
mTech->GetPassByIndex(p)->Apply(0, md3dImmediateContext);
md3dImmediateContext->DrawIndexed(mSphereIndexCount, mSphereIndexOffset, mSphereVertexOffset);
}
}
HR(mSwapChain->Present(0, 0));
}
void ShapesApp::OnMouseDown(WPARAM btnState, int x, int y)
{
mLastMousePos.x = x;
mLastMousePos.y = y;
SetCapture(mhMainWnd);
}
void ShapesApp::OnMouseUp(WPARAM btnState, int x, int y)
{
ReleaseCapture();
}
void ShapesApp::OnMouseMove(WPARAM btnState, int x, int y)
{
if ((btnState & MK_LBUTTON) != 0)
{
// Make each pixel correspond to a quarter of a degree.
float dx = XMConvertToRadians(0.25f*static_cast<float>(x - mLastMousePos.x));
float dy = XMConvertToRadians(0.25f*static_cast<float>(y - mLastMousePos.y));
// Update angles based on input to orbit camera around box.
mTheta += dx;
mPhi += dy;
// Restrict the angle mPhi.
mPhi = MathHelper::Clamp(mPhi, 0.1f, MathHelper::Pi - 0.1f);
}
else if ((btnState & MK_RBUTTON) != 0)
{
// Make each pixel correspond to 0.01 unit in the scene.
float dx = 0.01f*static_cast<float>(x - mLastMousePos.x);
float dy = 0.01f*static_cast<float>(y - mLastMousePos.y);
// Update the camera radius based on input.
mRadius += dx - dy;
// Restrict the radius.
mRadius = MathHelper::Clamp(mRadius, 3.0f, 200.0f);
}
mLastMousePos.x = x;
mLastMousePos.y = y;
}
void ShapesApp::BuildGeometryBuffers()
{
GeometryGenerator::MeshData box;
GeometryGenerator::MeshData grid;
GeometryGenerator::MeshData sphere;
GeometryGenerator::MeshData cylinder;
GeometryGenerator geoGen;
geoGen.CreateBox(1.0f, 1.0f, 1.0f, box);
geoGen.CreateGrid(20.0f, 30.0f, 60, 40, grid);
geoGen.CreateSphere(0.5f, 20, 20, sphere);
//geoGen.CreateGeosphere(0.5f, 2, sphere);
geoGen.CreateCylinder(0.5f, 0.3f, 3.0f, 20, 20, cylinder);
// Cache the vertex offsets to each object in the concatenated vertex buffer.
mBoxVertexOffset = 0;
mGridVertexOffset = box.Vertices.size();
mSphereVertexOffset = mGridVertexOffset + grid.Vertices.size();
mCylinderVertexOffset = mSphereVertexOffset + sphere.Vertices.size();
// Cache the index count of each object.
mBoxIndexCount = box.Indices.size();
mGridIndexCount = grid.Indices.size();
mSphereIndexCount = sphere.Indices.size();
mCylinderIndexCount = cylinder.Indices.size();
// Cache the starting index for each object in the concatenated index buffer.
mBoxIndexOffset = 0;
mGridIndexOffset = mBoxIndexCount;
mSphereIndexOffset = mGridIndexOffset + mGridIndexCount;
mCylinderIndexOffset = mSphereIndexOffset + mSphereIndexCount;
UINT totalVertexCount =
box.Vertices.size() +
grid.Vertices.size() +
sphere.Vertices.size() +
cylinder.Vertices.size();
UINT totalIndexCount =
mBoxIndexCount +
mGridIndexCount +
mSphereIndexCount +
mCylinderIndexCount;
//
// Extract the vertex elements we are interested in and pack the
// vertices of all the meshes into one vertex buffer.
//
std::vector<Vertex> vertices(totalVertexCount);
XMFLOAT4 black(0.0f, 0.0f, 0.0f, 1.0f);
UINT k = 0;
for (size_t i = 0; i < box.Vertices.size(); ++i, ++k)
{
vertices[k].Pos = box.Vertices[i].Position;
vertices[k].Color = black;
}
for (size_t i = 0; i < grid.Vertices.size(); ++i, ++k)
{
vertices[k].Pos = grid.Vertices[i].Position;
vertices[k].Color = black;
}
for (size_t i = 0; i < sphere.Vertices.size(); ++i, ++k)
{
vertices[k].Pos = sphere.Vertices[i].Position;
vertices[k].Color = black;
}
for (size_t i = 0; i < cylinder.Vertices.size(); ++i, ++k)
{
vertices[k].Pos = cylinder.Vertices[i].Position;
vertices[k].Color = black;
}
D3D11_BUFFER_DESC vbd;
vbd.Usage = D3D11_USAGE_IMMUTABLE;
vbd.ByteWidth = sizeof(Vertex) * totalVertexCount;
vbd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vbd.CPUAccessFlags = 0;
vbd.MiscFlags = 0;
D3D11_SUBRESOURCE_DATA vinitData;
vinitData.pSysMem = &vertices[0];
HR(md3dDevice->CreateBuffer(&vbd, &vinitData, &mVB));
//
// Pack the indices of all the meshes into one index buffer.
//
std::vector<UINT> indices;
indices.insert(indices.end(), box.Indices.begin(), box.Indices.end());
indices.insert(indices.end(), grid.Indices.begin(), grid.Indices.end());
indices.insert(indices.end(), sphere.Indices.begin(), sphere.Indices.end());
indices.insert(indices.end(), cylinder.Indices.begin(), cylinder.Indices.end());
D3D11_BUFFER_DESC ibd;
ibd.Usage = D3D11_USAGE_IMMUTABLE;
ibd.ByteWidth = sizeof(UINT) * totalIndexCount;
ibd.BindFlags = D3D11_BIND_INDEX_BUFFER;
ibd.CPUAccessFlags = 0;
ibd.MiscFlags = 0;
D3D11_SUBRESOURCE_DATA iinitData;
iinitData.pSysMem = &indices[0];
HR(md3dDevice->CreateBuffer(&ibd, &iinitData, &mIB));
}
void ShapesApp::BuildFX()
{
/*std::ifstream fin("D:/Source/Repository/Dx11.Luna/Content/FX/color.fx", std::ios::binary);
fin.seekg(0, std::ios_base::end);
int size = (int)fin.tellg();
fin.seekg(0, std::ios_base::beg);
std::vector<char> compiledShader(size);
fin.read(&compiledShader[0], size);
fin.close();
HR(D3DX11CreateEffectFromMemory(&compiledShader[0], size,
0, md3dDevice, &mFX));
mTech = mFX->GetTechniqueByName("ColorTech");
mfxWorldViewProj = mFX->GetVariableByName("gWorldViewProj")->AsMatrix();*/
DWORD shaderFlags = 0;
#if defined(DEBUG) || defined(_DEBUG)
shaderFlags |= D3D10_SHADER_DEBUG;
shaderFlags |= D3D10_SHADER_SKIP_OPTIMIZATION;
#endif
ID3D10Blob* compilationMsgs = nullptr;
HRESULT hr = D3DX11CompileEffectFromFile(L"D:/Source/Repository/Dx11.Luna/Content/FX/color.fx", nullptr, nullptr, shaderFlags, 0, md3dDevice, &mFX, &compilationMsgs);
if (compilationMsgs != 0)
{
MessageBoxA(0, (char*)compilationMsgs->GetBufferPointer(), 0, 0);
ReleaseCOM(compilationMsgs);
}
if (FAILED(hr))
{
DXTrace(__FILEW__, (DWORD)__LINE__, hr, L"D3DX11CompileEffectFromFile", true);
}
mTech = mFX->GetTechniqueByName("ColorTech");
mfxWorldViewProj = mFX->GetVariableByName("gWorldViewProj")->AsMatrix();
}
void ShapesApp::BuildVertexLayout()
{
// Create the vertex input layout.
D3D11_INPUT_ELEMENT_DESC vertexDesc[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }
};
// Create the input layout
D3DX11_PASS_DESC passDesc;
mTech->GetPassByIndex(0)->GetDesc(&passDesc);
HR(md3dDevice->CreateInputLayout(vertexDesc, 2, passDesc.pIAInputSignature,
passDesc.IAInputSignatureSize, &mInputLayout));
} | [
"andreafloro@outlook.it"
] | andreafloro@outlook.it |
55bf12b30af90918a2f98baac765f4b76b742aeb | bab49a0d302432317033a70e06870d18513ad72e | /includes/interface/Interface.h | f71b39af3a0eca68476ba05776699647ebace020 | [] | no_license | hamaliao/SimulationStack | 296eeb42f2c3f825badf18193ea54b54f3edee42 | e48b545de278857c2aaab9d0876ddd239c30a253 | refs/heads/master | 2020-03-18T23:26:57.925652 | 2018-06-02T22:49:39 | 2018-06-02T22:49:39 | 135,403,475 | 0 | 0 | null | 2018-06-03T10:18:53 | 2018-05-30T07:14:49 | C++ | UTF-8 | C++ | false | false | 677 | h | #pragma once
#include <memory>
#include "Protocol.h"
using SharedPtrType = std::shared_ptr<Protocol>;
class Interface
{
protected:
std::vector<SharedPtrType> protocolStack;
public:
Interface() = default;
bool sendData(Packet &userData) const;
bool receiveData(Packet &userData) const;
};
bool Interface::sendData(Packet &userData) const
{
for (auto index = protocolStack.begin(); index != protocolStack.end(); ++index)
{
(*index)->encode(userData);
}
return true;
}
bool Interface::receiveData(Packet &userData) const
{
for (auto index = protocolStack.end()-1; index != protocolStack.begin()-1; --index)
{
(*index)->decode(userData);
}
return true;
}
| [
"liaowei1010@126.com"
] | liaowei1010@126.com |
1d724a8b14c69c9a03e870a96990d05eccaf9e51 | 189f52bf5454e724d5acc97a2fa000ea54d0e102 | /ras/fluidisedBed/1.23/p | e28342be37846156550e8201016d0cfcbb997683 | [] | no_license | pyotr777/openfoam_samples | 5399721dd2ef57545ffce68215d09c49ebfe749d | 79c70ac5795decff086dd16637d2d063fde6ed0d | refs/heads/master | 2021-01-12T16:52:18.126648 | 2016-11-05T08:30:29 | 2016-11-05T08:30:29 | 71,456,654 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 46,370 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: v1606+ |
| \\ / A nd | Web: www.OpenFOAM.com |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "1.23";
object p;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [1 -1 -2 0 0 0 0];
internalField nonuniform List<scalar>
6000
(
106345
106346
106345
106345
106350
106356
106359
106358
106355
106350
106345
106340
106334
106329
106326
106324
106325
106326
106327
106329
106328
106324
106319
106314
106311
106313
106319
106326
106332
106335
106299
106295
106287
106279
106273
106271
106270
106266
106263
106260
106256
106250
106242
106236
106231
106230
106230
106231
106232
106233
106234
106234
106235
106239
106247
106257
106269
106280
106289
106293
106272
106267
106257
106244
106231
106221
106212
106204
106201
106200
106197
106192
106187
106183
106180
106179
106179
106179
106180
106182
106184
106188
106193
106202
106214
106227
106242
106257
106269
106274
106241
106236
106223
106207
106190
106174
106162
106155
106152
106151
106152
106152
106151
106150
106150
106149
106149
106149
106150
106150
106153
106157
106163
106171
106183
106197
106212
106227
106239
106243
106201
106198
106191
106176
106158
106143
106135
106130
106127
106127
106128
106130
106130
106130
106130
106130
106130
106130
106130
106131
106132
106135
106139
106146
106157
106170
106183
106192
106193
106196
106149
106149
106149
106145
106132
106120
106115
106111
106110
106110
106111
106112
106113
106112
106112
106111
106111
106112
106112
106113
106113
106113
106116
106121
106130
106139
106143
106136
106129
106128
106089
106092
106099
106108
106106
106099
106093
106091
106092
106093
106094
106093
106093
106093
106092
106092
106093
106093
106094
106094
106093
106091
106091
106094
106099
106097
106084
106067
106056
106051
106024
106030
106044
106063
106077
106075
106071
106070
106072
106074
106071
106068
106066
106065
106065
106065
106067
106069
106073
106075
106073
106069
106066
106064
106057
106039
106014
105992
105974
105964
105950
105960
105981
106010
106039
106047
106047
106048
106050
106046
106036
106028
106022
106020
106020
106022
106025
106031
106038
106046
106049
106044
106037
106025
106001
105971
105939
105910
105882
105868
105863
105878
105909
105948
105987
106008
106018
106020
106016
106001
105984
105970
105962
105957
105956
105958
105964
105971
105980
105991
106003
106004
105992
105967
105929
105891
105857
105824
105794
105781
105785
105798
105829
105874
105915
105951
105973
105977
105961
105935
105912
105896
105886
105880
105877
105879
105884
105887
105887
105886
105895
105913
105908
105879
105839
105800
105766
105737
105720
105717
105733
105737
105753
105790
105827
105869
105896
105897
105871
105842
105820
105804
105796
105793
105791
105791
105788
105777
105759
105740
105737
105755
105763
105753
105734
105704
105671
105653
105654
105660
105690
105687
105686
105704
105739
105771
105783
105775
105751
105727
105707
105693
105690
105694
105697
105694
105682
105657
105618
105582
105580
105593
105607
105615
105619
105606
105588
105587
105593
105601
105642
105636
105631
105633
105656
105669
105664
105646
105626
105605
105583
105565
105570
105584
105595
105592
105575
105540
105485
105446
105445
105454
105466
105484
105507
105520
105527
105536
105541
105547
105591
105585
105583
105579
105584
105580
105554
105526
105506
105484
105453
105425
105437
105469
105491
105495
105479
105436
105393
105371
105364
105364
105373
105391
105423
105456
105480
105494
105500
105505
105545
105541
105539
105532
105519
105500
105449
105412
105393
105370
105340
105327
105333
105367
105400
105413
105400
105368
105347
105335
105330
105329
105334
105347
105374
105410
105442
105459
105467
105470
105504
105503
105499
105486
105458
105415
105359
105321
105305
105293
105287
105289
105291
105307
105333
105349
105340
105325
105318
105314
105311
105312
105315
105323
105342
105372
105404
105424
105433
105434
105461
105462
105455
105435
105396
105342
105297
105275
105269
105266
105269
105273
105277
105285
105293
105300
105291
105283
105288
105291
105291
105293
105295
105300
105310
105328
105354
105375
105387
105388
105406
105404
105389
105360
105319
105278
105260
105254
105253
105254
105258
105262
105266
105273
105267
105260
105246
105245
105251
105261
105265
105267
105269
105269
105265
105267
105287
105313
105330
105334
105338
105328
105301
105265
105240
105232
105234
105237
105239
105242
105245
105247
105250
105246
105237
105230
105223
105222
105226
105232
105236
105238
105238
105234
105226
105224
105230
105247
105273
105282
105274
105253
105229
105219
105214
105213
105215
105221
105223
105224
105226
105227
105225
105218
105217
105214
105213
105213
105214
105216
105217
105217
105217
105214
105210
105209
105210
105215
105229
105242
105226
105213
105208
105206
105206
105205
105204
105205
105205
105206
105206
105206
105204
105204
105206
105206
105206
105207
105207
105207
105207
105207
105206
105205
105204
105204
105204
105205
105209
105219
105205
105202
105201
105201
105200
105199
105198
105196
105195
105194
105194
105194
105195
105197
105199
105200
105200
105200
105200
105200
105200
105200
105199
105199
105198
105198
105199
105199
105201
105207
105197
105196
105196
105196
105195
105194
105193
105191
105190
105189
105189
105189
105190
105191
105193
105193
105193
105194
105193
105193
105193
105193
105192
105192
105192
105193
105193
105194
105195
105197
105190
105191
105190
105190
105189
105189
105188
105187
105186
105185
105185
105185
105185
105186
105187
105187
105187
105187
105187
105186
105186
105186
105186
105186
105187
105187
105188
105188
105189
105190
105183
105184
105183
105183
105183
105183
105183
105182
105181
105180
105180
105180
105180
105180
105181
105180
105180
105180
105180
105180
105180
105180
105180
105180
105181
105181
105181
105181
105182
105183
105174
105175
105176
105176
105176
105177
105177
105177
105176
105176
105175
105175
105175
105175
105174
105173
105173
105173
105174
105174
105174
105174
105174
105174
105175
105175
105174
105174
105174
105174
105163
105165
105167
105168
105169
105170
105170
105171
105171
105170
105170
105170
105170
105169
105167
105166
105165
105166
105166
105167
105167
105167
105167
105167
105167
105167
105167
105166
105164
105162
105147
105151
105155
105158
105161
105162
105163
105164
105164
105164
105163
105163
105163
105162
105160
105158
105157
105157
105158
105158
105159
105159
105159
105159
105159
105158
105158
105155
105151
105147
105127
105131
105138
105144
105149
105153
105155
105155
105156
105156
105156
105155
105154
105153
105151
105149
105148
105148
105148
105149
105149
105149
105150
105150
105149
105148
105145
105139
105131
105125
105101
105107
105116
105125
105134
105140
105144
105145
105146
105146
105146
105146
105145
105143
105140
105138
105138
105138
105138
105138
105138
105139
105139
105138
105136
105133
105125
105115
105103
105096
105070
105076
105087
105100
105112
105122
105128
105132
105134
105135
105135
105135
105134
105132
105128
105126
105126
105126
105126
105126
105126
105126
105124
105122
105117
105108
105095
105079
105065
105058
105036
105041
105052
105065
105080
105095
105107
105115
105120
105122
105123
105122
105121
105117
105112
105109
105109
105109
105109
105108
105108
105106
105102
105096
105085
105069
105050
105032
105018
105011
104995
104999
105008
105020
105038
105058
105078
105094
105104
105108
105109
105109
105105
105098
105091
105086
105084
105084
105083
105081
105079
105074
105066
105053
105035
105014
104993
104975
104963
104957
104946
104948
104954
104967
104986
105013
105042
105066
105083
105092
105094
105091
105083
105072
105060
105053
105048
105045
105042
105038
105032
105023
105008
104989
104968
104946
104927
104912
104901
104895
104886
104887
104893
104905
104927
104957
104993
105028
105054
105068
105071
105064
105051
105033
105016
105004
104996
104989
104982
104974
104963
104949
104931
104911
104891
104872
104855
104842
104833
104828
104819
104820
104827
104840
104861
104888
104925
104961
104991
105011
105019
105013
104996
104974
104955
104938
104925
104914
104902
104891
104877
104861
104844
104826
104809
104792
104778
104767
104759
104755
104750
104751
104759
104771
104789
104811
104839
104864
104881
104893
104903
104906
104899
104886
104871
104855
104840
104826
104812
104799
104784
104769
104753
104738
104723
104709
104697
104687
104680
104677
104681
104684
104689
104699
104713
104730
104742
104747
104752
104759
104768
104774
104776
104772
104765
104755
104743
104730
104716
104702
104689
104674
104660
104646
104633
104621
104611
104603
104597
104595
104614
104615
104617
104624
104633
104637
104625
104616
104615
104621
104630
104638
104645
104648
104647
104644
104636
104627
104615
104603
104590
104577
104565
104552
104541
104531
104522
104516
104511
104509
104542
104545
104545
104544
104536
104510
104485
104472
104470
104477
104487
104498
104509
104517
104523
104525
104523
104518
104509
104499
104489
104477
104466
104456
104446
104438
104430
104425
104421
104419
104452
104459
104459
104436
104393
104353
104326
104314
104316
104325
104338
104354
104369
104382
104393
104401
104404
104404
104400
104393
104385
104375
104366
104357
104349
104342
104336
104331
104328
104327
104330
104334
104316
104269
104218
104175
104150
104144
104150
104165
104184
104205
104226
104245
104261
104274
104283
104287
104287
104284
104278
104271
104264
104257
104250
104244
104239
104235
104233
104232
104171
104162
104127
104077
104024
103980
103961
103961
103976
103999
104027
104055
104082
104107
104129
104146
104159
104168
104172
104172
104170
104165
104160
104154
104149
104144
104140
104137
104135
104135
103998
103975
103933
103878
103817
103774
103764
103773
103798
103832
103870
103906
103940
103971
103997
104018
104036
104048
104056
104059
104060
104057
104054
104050
104046
104042
104038
104036
104035
104035
103819
103792
103745
103678
103614
103585
103588
103605
103634
103675
103720
103764
103804
103839
103868
103893
103913
103929
103939
103946
103949
103949
103947
103944
103941
103938
103936
103934
103933
103933
103652
103624
103568
103501
103465
103460
103469
103485
103507
103541
103585
103632
103675
103713
103745
103772
103794
103811
103824
103832
103837
103839
103839
103837
103835
103833
103831
103830
103829
103830
103507
103474
103423
103393
103389
103391
103396
103406
103421
103441
103474
103515
103557
103595
103628
103656
103678
103696
103710
103720
103726
103729
103730
103729
103728
103726
103725
103724
103724
103724
103388
103360
103339
103336
103340
103343
103344
103348
103356
103367
103385
103416
103452
103487
103518
103545
103567
103584
103598
103608
103615
103619
103621
103621
103620
103619
103617
103617
103616
103617
103309
103296
103294
103296
103298
103300
103300
103300
103301
103305
103313
103331
103358
103388
103416
103440
103460
103476
103489
103499
103506
103510
103511
103512
103511
103510
103508
103508
103507
103507
103265
103262
103264
103264
103264
103262
103260
103257
103253
103251
103250
103258
103275
103297
103320
103341
103358
103372
103383
103391
103397
103401
103402
103402
103401
103399
103398
103397
103396
103396
103235
103238
103241
103239
103234
103228
103223
103216
103209
103201
103194
103193
103200
103214
103230
103246
103260
103271
103280
103286
103290
103292
103293
103292
103290
103288
103286
103284
103283
103282
103205
103212
103220
103216
103205
103194
103184
103174
103164
103152
103140
103133
103131
103136
103146
103157
103166
103174
103179
103183
103185
103185
103184
103181
103178
103175
103172
103169
103167
103166
103172
103181
103191
103190
103173
103154
103140
103128
103114
103100
103084
103073
103066
103062
103065
103070
103076
103079
103081
103082
103081
103078
103075
103070
103065
103060
103055
103052
103049
103047
103136
103145
103136
103129
103119
103100
103082
103068
103055
103041
103024
103009
102998
102988
102986
102987
102988
102987
102986
102982
102978
102972
102966
102959
102951
102943
102937
102931
102927
102925
103085
103077
103053
103035
103030
103021
103003
102989
102980
102968
102954
102935
102925
102913
102909
102906
102903
102898
102892
102885
102876
102867
102857
102847
102836
102825
102815
102807
102801
102798
102992
102979
102946
102922
102923
102921
102907
102897
102892
102885
102873
102852
102844
102840
102835
102828
102820
102810
102800
102789
102776
102763
102749
102734
102719
102704
102690
102678
102670
102665
102884
102865
102823
102807
102811
102813
102806
102801
102801
102799
102791
102776
102769
102771
102765
102753
102739
102725
102710
102694
102677
102660
102641
102621
102600
102580
102561
102544
102533
102526
102775
102745
102711
102705
102705
102704
102703
102707
102713
102719
102718
102713
102709
102709
102697
102679
102660
102640
102621
102600
102579
102557
102533
102508
102480
102453
102427
102404
102388
102379
102665
102648
102633
102624
102616
102611
102613
102622
102632
102645
102653
102654
102653
102649
102631
102605
102580
102556
102532
102508
102483
102456
102427
102394
102359
102323
102287
102257
102234
102221
102579
102579
102583
102570
102559
102553
102551
102553
102562
102576
102589
102598
102599
102589
102560
102528
102499
102472
102445
102418
102389
102358
102323
102282
102237
102190
102143
102102
102066
102043
102519
102532
102548
102533
102519
102510
102504
102501
102505
102514
102526
102539
102539
102516
102479
102445
102415
102388
102360
102330
102300
102265
102222
102172
102116
102054
101998
101942
101889
101845
102454
102480
102511
102499
102479
102467
102461
102458
102457
102459
102464
102467
102454
102422
102388
102357
102330
102305
102278
102248
102216
102177
102126
102065
101993
101921
101859
101790
101721
101675
102396
102419
102440
102449
102435
102425
102421
102418
102410
102398
102386
102370
102345
102318
102290
102266
102246
102225
102202
102174
102142
102098
102037
101963
101878
101805
101744
101668
101605
101588
102338
102349
102357
102371
102378
102375
102373
102364
102345
102314
102288
102262
102231
102207
102190
102176
102163
102151
102135
102110
102076
102028
101958
101873
101781
101707
101649
101591
101560
101554
102256
102260
102261
102276
102296
102300
102297
102279
102246
102210
102181
102157
102119
102087
102092
102086
102083
102083
102076
102054
102020
101970
101894
101804
101713
101643
101589
101554
101543
101542
102157
102159
102164
102178
102193
102198
102184
102160
102131
102102
102075
102067
102048
102026
102018
102017
102028
102030
102028
102009
101976
101927
101846
101753
101665
101600
101557
101539
101535
101536
102043
102046
102068
102085
102094
102084
102068
102060
102051
102039
102020
102005
101997
101992
101988
101986
101987
101998
101993
101983
101947
101894
101809
101716
101632
101572
101541
101532
101531
101532
101984
101985
101993
102000
102001
101997
101993
101992
101990
101987
101983
101978
101976
101974
101973
101971
101968
101967
101977
101969
101935
101871
101780
101687
101607
101554
101532
101527
101528
101528
101957
101957
101958
101960
101961
101963
101965
101966
101966
101965
101964
101963
101961
101959
101958
101956
101954
101952
101954
101951
101926
101854
101758
101665
101587
101542
101526
101524
101525
101525
101946
101946
101946
101947
101949
101951
101952
101953
101952
101951
101949
101947
101945
101944
101942
101941
101940
101939
101938
101935
101913
101838
101739
101646
101572
101533
101522
101521
101521
101522
101937
101937
101937
101938
101938
101939
101939
101938
101937
101935
101934
101931
101929
101928
101926
101926
101925
101925
101924
101920
101899
101820
101719
101628
101560
101527
101518
101518
101518
101519
101927
101927
101927
101927
101926
101926
101925
101924
101922
101920
101917
101915
101913
101911
101910
101910
101910
101910
101910
101905
101882
101796
101693
101609
101548
101520
101514
101515
101516
101516
101916
101915
101915
101915
101914
101912
101911
101908
101906
101903
101900
101897
101895
101894
101893
101892
101893
101894
101894
101888
101856
101760
101660
101585
101535
101514
101511
101512
101513
101513
101904
101903
101903
101902
101900
101898
101896
101893
101889
101886
101882
101879
101876
101874
101873
101872
101872
101874
101876
101866
101808
101708
101620
101558
101521
101509
101509
101511
101511
101511
101891
101890
101889
101888
101886
101883
101880
101876
101872
101867
101863
101859
101855
101852
101850
101848
101847
101848
101850
101824
101740
101647
101575
101529
101510
101507
101508
101509
101510
101510
101877
101877
101875
101874
101871
101868
101863
101859
101853
101848
101842
101837
101832
101826
101822
101817
101813
101812
101808
101748
101655
101580
101531
101511
101506
101506
101507
101508
101508
101508
101863
101862
101861
101859
101855
101851
101846
101840
101833
101826
101819
101811
101804
101796
101789
101779
101768
101754
101726
101652
101569
101528
101510
101505
101505
101506
101507
101507
101507
101507
101848
101847
101846
101843
101839
101834
101828
101820
101812
101804
101794
101784
101773
101762
101749
101732
101709
101677
101625
101567
101527
101511
101506
101505
101506
101506
101506
101507
101507
101507
101833
101832
101830
101827
101822
101816
101809
101801
101792
101780
101766
101751
101735
101718
101697
101672
101640
101600
101557
101530
101516
101509
101507
101506
101505
101506
101506
101506
101506
101506
101817
101816
101814
101810
101806
101799
101791
101780
101766
101748
101728
101707
101684
101661
101635
101605
101574
101548
101531
101522
101514
101509
101506
101505
101505
101505
101505
101505
101505
101505
101801
101800
101798
101795
101790
101781
101769
101752
101730
101703
101676
101648
101622
101596
101572
101551
101535
101527
101523
101518
101512
101507
101504
101504
101504
101504
101504
101504
101504
101504
101787
101785
101783
101779
101772
101759
101739
101711
101678
101643
101611
101582
101561
101544
101532
101525
101522
101520
101518
101514
101509
101505
101503
101503
101503
101503
101503
101503
101503
101503
101772
101771
101768
101761
101748
101726
101694
101654
101612
101576
101550
101534
101525
101520
101518
101517
101516
101515
101513
101511
101507
101503
101502
101502
101502
101502
101502
101502
101502
101502
101755
101754
101749
101737
101715
101680
101634
101586
101547
101526
101517
101514
101513
101512
101512
101512
101511
101510
101509
101507
101505
101502
101501
101501
101501
101501
101501
101501
101501
101502
101735
101732
101723
101703
101669
101622
101568
101528
101512
101507
101507
101508
101508
101508
101508
101508
101507
101506
101505
101504
101503
101501
101500
101501
101501
101501
101501
101501
101501
101501
101709
101703
101689
101659
101615
101559
101518
101504
101502
101502
101503
101504
101504
101504
101504
101503
101503
101502
101501
101500
101501
101500
101500
101500
101500
101500
101500
101500
101500
101500
101676
101667
101647
101610
101560
101514
101499
101498
101499
101500
101500
101500
101500
101500
101500
101499
101498
101498
101497
101496
101498
101498
101499
101500
101500
101500
101499
101499
101499
101499
101638
101626
101602
101564
101518
101498
101495
101496
101496
101497
101497
101497
101497
101497
101496
101495
101494
101493
101492
101492
101493
101495
101497
101498
101499
101499
101498
101498
101498
101498
101598
101585
101563
101528
101501
101493
101493
101493
101494
101494
101494
101494
101494
101493
101493
101491
101490
101489
101488
101487
101486
101489
101491
101493
101495
101496
101497
101497
101496
101496
101564
101552
101534
101507
101493
101490
101491
101491
101491
101491
101491
101491
101491
101490
101489
101487
101485
101484
101483
101482
101481
101481
101483
101486
101489
101491
101493
101494
101494
101494
101539
101530
101516
101497
101489
101489
101488
101488
101488
101488
101488
101488
101487
101486
101484
101483
101481
101479
101478
101477
101477
101476
101476
101478
101480
101484
101487
101489
101490
101491
101523
101516
101505
101491
101487
101486
101486
101486
101485
101485
101485
101485
101483
101482
101480
101478
101476
101475
101474
101473
101473
101472
101472
101472
101473
101476
101479
101482
101484
101485
101513
101509
101498
101487
101484
101484
101483
101483
101482
101482
101482
101481
101479
101477
101475
101473
101471
101470
101470
101469
101469
101468
101468
101468
101468
101469
101471
101473
101476
101477
101504
101504
101492
101483
101481
101481
101480
101480
101479
101479
101479
101477
101475
101473
101471
101469
101467
101466
101466
101465
101465
101465
101465
101464
101464
101464
101464
101465
101466
101468
101494
101496
101484
101478
101477
101477
101477
101476
101476
101476
101475
101473
101471
101469
101466
101465
101464
101463
101463
101462
101462
101461
101461
101461
101460
101460
101459
101459
101459
101460
101483
101481
101474
101472
101473
101474
101474
101473
101473
101473
101471
101469
101467
101464
101462
101461
101460
101460
101459
101459
101459
101458
101458
101457
101457
101456
101456
101455
101455
101455
101472
101468
101465
101465
101468
101470
101470
101470
101470
101469
101468
101465
101463
101461
101459
101458
101457
101457
101456
101456
101455
101455
101455
101454
101454
101453
101453
101452
101452
101451
101462
101459
101458
101459
101462
101465
101467
101466
101466
101465
101464
101462
101459
101457
101456
101455
101455
101454
101453
101453
101452
101452
101451
101451
101451
101450
101450
101449
101449
101449
101454
101452
101452
101453
101456
101461
101463
101463
101463
101462
101460
101458
101456
101454
101453
101452
101452
101451
101450
101450
101449
101449
101448
101448
101448
101447
101447
101447
101447
101447
101446
101446
101446
101448
101451
101456
101459
101459
101459
101458
101457
101455
101453
101451
101450
101450
101449
101448
101447
101447
101446
101446
101445
101445
101445
101445
101444
101444
101444
101444
101440
101440
101441
101443
101446
101451
101456
101456
101456
101455
101454
101452
101450
101449
101447
101447
101446
101445
101444
101444
101443
101443
101442
101442
101442
101442
101442
101442
101442
101442
101436
101435
101436
101437
101441
101446
101452
101454
101453
101452
101451
101449
101447
101446
101445
101444
101443
101442
101441
101441
101440
101440
101440
101440
101439
101439
101439
101439
101439
101439
101433
101432
101432
101433
101436
101441
101449
101451
101450
101450
101448
101446
101444
101443
101442
101441
101440
101439
101438
101438
101437
101437
101437
101437
101437
101437
101437
101437
101437
101437
101434
101430
101430
101430
101432
101436
101445
101449
101448
101447
101445
101443
101442
101440
101439
101438
101437
101436
101435
101435
101435
101435
101435
101435
101434
101434
101435
101435
101435
101435
101435
101428
101426
101427
101428
101431
101441
101447
101446
101445
101443
101441
101439
101437
101436
101435
101434
101433
101433
101432
101432
101432
101432
101432
101432
101432
101432
101432
101432
101432
101432
101430
101423
101422
101424
101426
101434
101446
101445
101443
101441
101438
101436
101434
101433
101432
101431
101431
101430
101430
101430
101430
101430
101430
101430
101430
101430
101430
101430
101430
101432
101435
101426
101420
101420
101422
101428
101444
101444
101441
101438
101436
101433
101432
101430
101429
101428
101428
101427
101427
101427
101427
101427
101427
101428
101428
101428
101428
101428
101428
101434
101436
101430
101422
101418
101419
101424
101442
101443
101439
101436
101433
101431
101429
101427
101426
101426
101425
101425
101425
101425
101425
101425
101425
101425
101425
101426
101426
101426
101426
101437
101440
101434
101426
101421
101419
101422
101437
101443
101436
101433
101430
101428
101426
101425
101424
101423
101423
101422
101422
101422
101422
101422
101423
101423
101423
101424
101424
101424
101424
101440
101443
101438
101431
101425
101421
101421
101432
101442
101434
101430
101427
101425
101423
101422
101421
101420
101420
101420
101420
101420
101420
101420
101420
101420
101421
101421
101422
101422
101422
101437
101442
101442
101436
101431
101425
101421
101428
101440
101430
101426
101424
101422
101420
101419
101418
101418
101417
101417
101417
101417
101417
101417
101418
101418
101418
101418
101419
101419
101420
101429
101431
101432
101430
101430
101426
101420
101424
101434
101426
101422
101420
101418
101417
101416
101415
101415
101415
101415
101415
101415
101415
101415
101415
101415
101415
101415
101416
101416
101416
101416
101414
101416
101415
101416
101417
101415
101421
101423
101420
101417
101415
101414
101413
101412
101412
101412
101412
101412
101412
101412
101412
101412
101412
101412
101412
101412
101412
101413
101413
101403
101400
101401
101400
101404
101408
101410
101415
101413
101412
101411
101410
101409
101409
101409
101409
101409
101409
101409
101409
101409
101410
101410
101410
101409
101409
101409
101409
101409
101409
101389
101387
101389
101389
101394
101401
101406
101404
101404
101404
101404
101404
101404
101404
101405
101405
101405
101406
101406
101406
101407
101407
101407
101407
101407
101406
101406
101406
101406
101406
101370
101373
101375
101378
101384
101394
101400
101397
101396
101397
101397
101398
101399
101400
101400
101401
101402
101402
101403
101404
101404
101404
101404
101404
101404
101404
101403
101403
101403
101403
101346
101351
101359
101366
101374
101385
101389
101389
101388
101388
101389
101391
101393
101395
101396
101397
101398
101399
101400
101400
101401
101401
101402
101401
101401
101401
101400
101400
101400
101400
101331
101332
101338
101346
101356
101370
101379
101381
101378
101378
101380
101383
101387
101389
101391
101393
101394
101395
101396
101397
101398
101398
101398
101399
101398
101398
101398
101397
101397
101397
101320
101319
101322
101327
101335
101349
101366
101371
101367
101366
101369
101374
101379
101383
101386
101388
101389
101391
101392
101393
101394
101394
101395
101395
101395
101395
101394
101394
101394
101394
101306
101304
101307
101311
101318
101330
101348
101358
101354
101353
101355
101362
101370
101376
101380
101383
101384
101386
101387
101388
101389
101390
101391
101392
101392
101392
101391
101391
101391
101390
101294
101291
101293
101297
101304
101314
101331
101341
101340
101338
101340
101348
101359
101368
101373
101377
101379
101381
101382
101383
101384
101385
101387
101387
101388
101388
101388
101388
101387
101387
101287
101283
101284
101287
101293
101301
101316
101325
101325
101324
101325
101333
101347
101359
101366
101370
101373
101375
101376
101377
101379
101380
101381
101383
101384
101384
101384
101384
101384
101383
101283
101279
101278
101281
101285
101291
101303
101312
101312
101311
101311
101318
101333
101348
101358
101363
101366
101368
101370
101371
101373
101374
101376
101377
101379
101380
101380
101380
101380
101380
101276
101275
101273
101275
101279
101283
101293
101300
101300
101299
101299
101305
101319
101336
101349
101355
101359
101362
101363
101365
101366
101368
101370
101372
101373
101375
101376
101376
101376
101376
101268
101271
101269
101269
101272
101277
101286
101291
101291
101291
101290
101293
101305
101324
101339
101347
101352
101355
101357
101359
101360
101362
101363
101365
101367
101369
101370
101371
101372
101371
101258
101265
101267
101265
101267
101271
101279
101284
101283
101283
101282
101284
101293
101311
101328
101339
101345
101348
101351
101352
101354
101355
101357
101359
101361
101363
101364
101366
101367
101367
101252
101262
101264
101262
101263
101266
101274
101277
101277
101277
101276
101276
101283
101299
101318
101331
101338
101342
101344
101346
101348
101349
101351
101353
101354
101356
101358
101360
101361
101361
101254
101260
101261
101260
101260
101262
101268
101271
101271
101271
101270
101270
101274
101288
101307
101322
101331
101336
101339
101341
101342
101344
101345
101347
101348
101350
101351
101353
101354
101354
101260
101260
101260
101259
101258
101259
101264
101266
101265
101265
101265
101264
101266
101277
101296
101313
101324
101330
101333
101335
101337
101338
101339
101341
101342
101343
101345
101346
101347
101347
101267
101266
101263
101261
101259
101257
101260
101260
101260
101260
101260
101259
101260
101267
101284
101304
101316
101323
101327
101329
101331
101333
101334
101335
101336
101337
101338
101339
101340
101340
101266
101268
101265
101263
101260
101257
101259
101255
101255
101255
101255
101254
101254
101259
101274
101294
101309
101317
101321
101324
101326
101328
101329
101330
101331
101332
101333
101333
101334
101334
101254
101253
101255
101255
101254
101255
101254
101251
101251
101251
101251
101250
101249
101251
101262
101283
101302
101311
101316
101319
101321
101322
101324
101325
101326
101327
101327
101327
101328
101328
101238
101238
101242
101244
101246
101249
101247
101247
101247
101246
101246
101246
101245
101245
101252
101271
101293
101305
101310
101313
101315
101317
101319
101320
101321
101322
101322
101322
101322
101322
101224
101225
101228
101232
101236
101241
101242
101243
101243
101242
101242
101242
101241
101241
101244
101259
101282
101298
101304
101308
101310
101312
101314
101315
101316
101317
101317
101317
101317
101317
101210
101211
101215
101221
101227
101234
101238
101239
101238
101238
101238
101238
101238
101237
101238
101247
101270
101290
101299
101302
101305
101307
101309
101311
101312
101312
101312
101312
101312
101312
101197
101197
101202
101209
101218
101227
101233
101235
101234
101234
101234
101234
101234
101233
101233
101238
101257
101280
101292
101297
101300
101302
101304
101306
101307
101307
101308
101308
101307
101307
101183
101184
101190
101198
101208
101220
101229
101231
101230
101230
101230
101230
101230
101230
101230
101231
101244
101269
101285
101291
101294
101296
101299
101301
101302
101303
101303
101303
101303
101303
101171
101172
101178
101187
101199
101212
101224
101227
101227
101226
101226
101226
101226
101226
101226
101227
101234
101255
101275
101284
101288
101291
101293
101295
101297
101298
101298
101299
101299
101298
101159
101161
101167
101177
101190
101205
101219
101223
101223
101223
101223
101223
101223
101223
101223
101223
101227
101242
101264
101275
101280
101284
101287
101289
101291
101293
101294
101294
101294
101294
101148
101150
101157
101167
101181
101199
101215
101220
101219
101219
101219
101219
101219
101219
101220
101220
101222
101232
101252
101264
101271
101275
101279
101283
101285
101287
101288
101289
101290
101289
101135
101138
101145
101157
101173
101192
101211
101216
101216
101215
101215
101216
101216
101216
101216
101217
101218
101224
101239
101251
101259
101264
101269
101273
101277
101280
101282
101283
101284
101284
101118
101122
101131
101145
101163
101184
101206
101213
101212
101212
101212
101212
101212
101212
101212
101213
101214
101217
101227
101236
101243
101249
101255
101260
101266
101270
101274
101275
101276
101277
101093
101099
101111
101128
101150
101176
101201
101209
101209
101208
101208
101208
101208
101208
101208
101208
101209
101210
101213
101219
101225
101230
101235
101241
101248
101255
101260
101264
101266
101266
101054
101065
101084
101107
101134
101164
101195
101205
101205
101205
101204
101204
101203
101203
101203
101202
101202
101201
101200
101201
101203
101206
101210
101215
101222
101231
101239
101246
101250
101251
101024
101033
101052
101080
101112
101149
101187
101199
101200
101200
101200
101199
101198
101197
101197
101196
101194
101190
101185
101180
101179
101179
101181
101185
101190
101198
101207
101218
101226
101230
101009
101011
101023
101049
101084
101127
101172
101191
101194
101194
101194
101193
101192
101191
101189
101188
101184
101176
101166
101157
101153
101151
101152
101154
101156
101161
101169
101179
101189
101194
100999
100998
101002
101019
101051
101097
101149
101178
101185
101187
101186
101185
101184
101183
101181
101177
101171
101158
101143
101132
101126
101124
101122
101122
101123
101123
101127
101133
101140
101145
100989
100989
100990
100997
101018
101059
101114
101155
101172
101176
101176
101175
101175
101172
101170
101164
101153
101136
101117
101106
101100
101098
101096
101093
101090
101087
101086
101087
101089
101089
100979
100980
100982
100985
100995
101019
101064
101118
101150
101160
101162
101162
101162
101160
101155
101146
101130
101107
101087
101076
101072
101069
101064
101058
101055
101051
101046
101043
101039
101036
100970
100971
100973
100975
100981
100993
101019
101065
101112
101136
101143
101146
101146
101143
101136
101121
101098
101071
101051
101039
101034
101026
101015
101008
101004
101003
101002
100997
100992
100987
100959
100959
100961
100963
100967
100976
100991
101018
101060
101097
101116
101123
101123
101118
101106
101084
101054
101026
101005
100992
100983
100971
100957
100947
100942
100940
100939
100936
100934
100934
100943
100943
100944
100946
100950
100957
100967
100984
101011
101046
101074
101087
101088
101079
101060
101032
101002
100975
100953
100937
100924
100909
100893
100882
100876
100871
100867
100865
100863
100865
100921
100921
100922
100924
100928
100934
100943
100955
100972
100996
101020
101034
101033
101019
100997
100969
100942
100918
100896
100878
100862
100844
100829
100817
100810
100801
100793
100787
100784
100782
100893
100894
100895
100897
100901
100908
100916
100926
100937
100949
100960
100964
100958
100944
100923
100901
100878
100856
100837
100818
100800
100782
100766
100754
100747
100733
100717
100704
100697
100692
100859
100860
100861
100865
100870
100877
100885
100892
100896
100897
100893
100887
100877
100863
100846
100828
100809
100791
100774
100757
100740
100722
100706
100695
100685
100665
100641
100621
100600
100583
100819
100821
100824
100829
100834
100840
100844
100844
100840
100830
100818
100807
100795
100782
100767
100752
100737
100722
100708
100695
100680
100664
100649
100636
100624
100599
100569
100540
100504
100481
100776
100778
100783
100787
100791
100791
100788
100779
100766
100752
100738
100725
100712
100699
100686
100673
100661
100650
100640
100630
100620
100607
100593
100578
100562
100538
100505
100472
100444
100436
100731
100733
100737
100738
100736
100728
100716
100702
100687
100672
100657
100642
100628
100615
100602
100591
100582
100575
100569
100563
100557
100550
100540
100524
100505
100482
100451
100427
100420
100418
100682
100683
100683
100678
100668
100654
100639
100623
100607
100591
100575
100559
100543
100529
100516
100506
100500
100497
100496
100495
100494
100493
100487
100475
100456
100434
100415
100408
100408
100408
100626
100624
100618
100606
100591
100576
100560
100545
100528
100511
100493
100475
100457
100440
100426
100417
100414
100416
100421
100427
100432
100436
100437
100432
100419
100406
100399
100398
100398
100398
100558
100552
100541
100527
100512
100497
100483
100467
100450
100432
100412
100390
100369
100349
100331
100321
100322
100332
100345
100358
100370
100381
100390
100395
100395
100390
100389
100387
100387
100387
100477
100470
100458
100445
100433
100420
100406
100391
100374
100355
100332
100307
100281
100255
100231
100215
100220
100242
100267
100289
100309
100328
100345
100361
100375
100377
100377
100376
100375
100375
100389
100383
100374
100364
100354
100344
100333
100319
100302
100282
100257
100227
100195
100164
100138
100124
100129
100155
100190
100222
100250
100274
100299
100324
100349
100360
100362
100362
100362
100362
100300
100295
100289
100283
100277
100271
100263
100251
100236
100214
100186
100150
100118
100095
100086
100083
100084
100093
100121
100159
100193
100222
100251
100280
100311
100334
100340
100343
100346
100346
100210
100206
100205
100204
100204
100202
100197
100189
100175
100154
100121
100090
100075
100068
100067
100067
100067
100068
100077
100104
100141
100173
100202
100232
100262
100291
100305
100314
100321
100323
100122
100117
100124
100130
100134
100137
100137
100133
100122
100103
100076
100064
100060
100059
100059
100060
100060
100059
100060
100069
100096
100127
100154
100180
100207
100232
100253
100268
100279
100285
100041
100040
100050
100062
100071
100078
100083
100084
100079
100069
100056
100053
100053
100053
100053
100053
100053
100053
100052
100053
100064
100087
100109
100130
100149
100167
100187
100200
100210
100222
100008
100008
100011
100016
100022
100029
100035
100041
100047
100047
100043
100044
100045
100046
100046
100046
100046
100046
100045
100044
100046
100058
100069
100081
100091
100103
100115
100120
100122
100137
100001
100001
100002
100002
100004
100006
100008
100011
100016
100020
100026
100030
100033
100035
100036
100036
100036
100036
100035
100033
100032
100033
100031
100034
100038
100044
100045
100042
100038
100050
100001
100001
100001
100001
100001
100001
100001
100002
100003
100005
100009
100013
100017
100020
100021
100022
100022
100022
100020
100019
100015
100011
100009
100007
100008
100008
100008
100007
100007
100009
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100002
100003
100004
100006
100007
100008
100008
100008
100007
100005
100003
100002
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100000
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
)
;
boundaryField
{
inlet
{
type calculated;
value nonuniform List<scalar>
30
(
106345
106346
106345
106345
106350
106356
106359
106358
106355
106350
106346
106340
106334
106329
106326
106325
106325
106326
106327
106329
106328
106324
106319
106314
106311
106313
106319
106326
106333
106335
)
;
}
outlet
{
type calculated;
value uniform 100000;
}
walls
{
type calculated;
value nonuniform List<scalar>
400
(
106345
106299
106272
106241
106201
106149
106089
106024
105950
105863
105785
105733
105690
105642
105591
105545
105504
105461
105406
105338
105274
105226
105205
105197
105190
105183
105174
105163
105147
105127
105101
105070
105036
104995
104946
104886
104819
104750
104681
104614
104542
104452
104330
104171
103998
103819
103652
103507
103388
103309
103265
103235
103205
103172
103136
103085
102992
102884
102775
102665
102579
102519
102454
102396
102338
102256
102157
102043
101984
101957
101946
101937
101927
101916
101904
101891
101877
101863
101848
101833
101817
101801
101787
101772
101755
101735
101709
101676
101638
101598
101564
101539
101523
101513
101504
101494
101483
101472
101462
101454
101446
101440
101436
101433
101434
101435
101432
101432
101434
101437
101440
101437
101429
101416
101403
101389
101370
101346
101331
101320
101306
101294
101287
101283
101276
101268
101258
101252
101254
101260
101267
101266
101254
101238
101224
101210
101197
101183
101171
101159
101148
101135
101118
101093
101054
101024
101009
100999
100989
100979
100970
100959
100943
100921
100893
100859
100819
100776
100731
100682
100626
100558
100477
100389
100300
100210
100122
100041
100008
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
106335
106293
106274
106243
106196
106128
106051
105964
105868
105781
105717
105660
105601
105547
105505
105470
105434
105388
105334
105282
105242
105219
105207
105197
105190
105183
105174
105162
105147
105125
105096
105058
105011
104957
104895
104828
104755
104677
104595
104509
104419
104327
104232
104135
104035
103933
103830
103724
103617
103507
103396
103282
103166
103047
102925
102798
102665
102526
102379
102221
102043
101845
101675
101588
101554
101542
101536
101532
101528
101525
101522
101519
101516
101513
101511
101510
101508
101507
101507
101506
101505
101504
101503
101502
101502
101501
101500
101499
101498
101496
101494
101491
101485
101477
101468
101460
101455
101451
101449
101447
101444
101442
101439
101437
101435
101432
101430
101428
101426
101424
101422
101420
101416
101413
101409
101406
101403
101400
101397
101394
101390
101387
101383
101380
101376
101371
101367
101361
101354
101347
101340
101334
101328
101322
101317
101312
101307
101303
101298
101294
101289
101284
101277
101266
101251
101230
101194
101145
101089
101036
100987
100934
100865
100782
100692
100583
100481
100436
100418
100408
100398
100387
100375
100362
100346
100323
100285
100222
100137
100050
100009
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
)
;
}
frontAndBackPlanes
{
type empty;
}
}
// ************************************************************************* //
| [
"peterbryz@yahoo.com"
] | peterbryz@yahoo.com | |
c48e62edba456a4449877b3c42f747c41cc5ca20 | 4474ebbb934a1ab14cff3700c569281d942fb45d | /ofApp.cpp | 0bd999723817c2e9992662f6332e3e370f003199 | [] | no_license | junkiyoshi/Insta20190204 | 24b6fb657e8bb5f861de53e4968c68c0e4d25f34 | a05457832b96ede92aaff6f8b5cee23bba7bde66 | refs/heads/master | 2020-04-20T19:31:29.181028 | 2019-02-04T09:04:01 | 2019-02-04T09:04:01 | 169,051,667 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,135 | cpp | #include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup() {
ofSetFrameRate(60);
ofSetWindowTitle("openframeworks");
ofBackground(39);
ofEnableDepthTest();
ofSetLineWidth(2);
}
//--------------------------------------------------------------
void ofApp::update() {
ofSeedRandom(39);
}
//--------------------------------------------------------------
void ofApp::draw() {
this->cam.begin();
int deg_span = 15;
float noise_seed_x = ofRandom(300, 1000);
float noise_seed_y = ofRandom(300, 1000);
float noise_seed_z = ofRandom(300, 1000);
ofFill();
ofDrawSphere(glm::vec3(), 10);
for (int radius = 30; radius <= 300; radius += 30) {
ofPushMatrix();
ofRotateX(ofMap(ofNoise(noise_seed_x - radius * 0.0015 + ofGetFrameNum() * 0.005), 0, 1, -360, 360));
ofRotateZ(ofMap(ofNoise(noise_seed_y - radius * 0.0015 + ofGetFrameNum() * 0.005), 0, 1, -360, 360));
ofRotateY(ofMap(ofNoise(noise_seed_z - radius * 0.0015 + ofGetFrameNum() * 0.005), 0, 1, -360, 360));
for (int deg = 0; deg < 360; deg += deg_span) {
vector<glm::vec3> vertices;
vertices.push_back(glm::vec3(radius * cos((deg + deg_span * 0.5) *DEG_TO_RAD), radius * sin((deg + deg_span * 0.5) * DEG_TO_RAD), 10));
vertices.push_back(glm::vec3(radius * cos((deg + deg_span * 0.5) *DEG_TO_RAD), radius * sin((deg + deg_span * 0.5) * DEG_TO_RAD), -10));
vertices.push_back(glm::vec3(radius * cos((deg - deg_span * 0.5) *DEG_TO_RAD), radius * sin((deg - deg_span * 0.5) * DEG_TO_RAD), -10));
vertices.push_back(glm::vec3(radius * cos((deg - deg_span * 0.5) *DEG_TO_RAD), radius * sin((deg - deg_span * 0.5) * DEG_TO_RAD), 10));
ofFill();
ofSetColor(39);
ofBeginShape();
ofVertices(vertices);
ofEndShape(true);
ofNoFill();
ofSetColor(239);
ofBeginShape();
ofVertices(vertices);
ofEndShape(true);
}
ofPopMatrix();
}
this->cam.end();
}
//--------------------------------------------------------------
int main() {
ofGLWindowSettings settings;
settings.setGLVersion(3, 2);
settings.setSize(720, 720);
ofCreateWindow(settings);
ofRunApp(new ofApp());
} | [
"nakauchi.k@g-hits.co.jp"
] | nakauchi.k@g-hits.co.jp |
9ef3cf59f79fe4b4c577bef0cd6eda99c86a80f6 | ce169f02601eb3e5542669a4e6b6154bee32a7e6 | /chap8/10132.cc | 663331f904ae23e93d67d124654b522d58147009 | [] | no_license | nanAdair/aoapc | 6b738708c87b4c0d8ad842febb69be2e92b4e319 | 18eed04e82769e3545e9203df8115e1d232de5d5 | refs/heads/master | 2020-05-17T16:30:10.013779 | 2014-12-24T08:08:24 | 2014-12-24T08:08:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,168 | cc | /* Title: 10132
* 考察点:用最短的和最长的构成串,然后去验证每一个字符串是否能找到另一半*/
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
void init(map<string, int> &m, const vector<string> &snippets);
bool comp(const string &s1, const string &s2);
bool is_res(map<string, int> &m, const string res, int number);
int main()
{
int num;
cin >> num;
string temp;
getline(cin, temp);
getline(cin, temp);
for (int n = 0; n < num; n++) {
vector<string> snippets;
while (getline(cin, temp)) {
if (temp[0] != '0' && temp[0] != '1')
break;
snippets.push_back(temp);
}
sort(snippets.begin(), snippets.end(), comp);
int min_length, max_length;
min_length = snippets[0].length();
max_length = snippets[snippets.size()-1].length();
vector<string> l, r;
for (int i = 0; i < snippets.size(); i++) {
if (snippets[i].length() == min_length)
l.push_back(snippets[i]);
if (snippets[i].length() == max_length)
r.push_back(snippets[i]);
}
bool flag = 0;
map<string, int> visit;
string res;
for (int i = 0; i < l.size(); i++) {
if (flag)
break;
for (int j = 0; j < r.size(); j++) {
res = l[i] + r[j];
init(visit, snippets);
if (is_res(visit, res, snippets.size())) {
flag = 1;
break;
}
res = r[j] + l[i];
init(visit, snippets);
if (is_res(visit, res, snippets.size())) {
flag = 1;
break;
}
}
}
cout << res << endl;
if (n != num-1)
cout << endl;
}
}
bool is_res(map<string, int> &m, const string res, int number)
{
int n = 0;
for (map<string, int>::iterator it = m.begin(); it != m.end(); it++) {
if (it->second == 0)
continue;
bool flag = 0;
string sub1 = it->first;
string left(res.begin(), res.begin()+sub1.size());
string right(res.begin()+sub1.size(), res.end());
if (sub1 == left) {
if (m.find(right) != m.end() && m[right] != 0) {
if (left == right && m[left] < 2)
flag = 0;
else
flag = 1;
}
}
if (flag) {
n++;
m[left] -= 1;
m[right] -= 1;
}
if (flag && m[left] > 0)
it--;
}
if (2 * n == number)
return 1;
else
return 0;
}
bool comp(const string &s1, const string &s2)
{
return s1.length() < s2.length();
}
void init(map<string, int> &m, const vector<string> &snippets)
{
m.clear();
for (int i = 0; i < snippets.size(); i++) {
if (m.find(snippets[i]) == m.end())
m[snippets[i]] = 1;
else
m[snippets[i]] += 1;
}
}
| [
"wangbn15@gmail.com"
] | wangbn15@gmail.com |
119ac6eed4d62133dd1ef4d2484f4f8509649d3c | 11193416fbc536f22ee70bb44d8303d86df055b0 | /Restaurant/Rest/Load.h | 00ed62b7277bdc06809cb491ca3e2a90fba3828a | [] | no_license | MoemenGaafar/Restaurant-Simulator | 69cf136a519e53461a128097ade0f0f60c35921c | 43776a10167eef18eed9fc7884ae6f1e54211861 | refs/heads/master | 2022-05-07T23:41:32.581349 | 2020-04-24T02:18:18 | 2020-04-24T02:18:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 754 | h | #ifndef LOAD
#define LOAD
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
class Restaurant; //Forward class declaration
class Load
{
//Load class loads the events, cooks, and information
//from a text file entered by the user to an owner Restaurant object.
public:
Load(Restaurant* Rest);
~Load();
void Excuete(); //Takes text file from user and loads data to restaurant
private:
string filename; //Text file name to be taken from user
int N, G, V,
SN, SG, SV,
BO, BN, BG, BV,
AutoP, numOfEvents, eventtype, ordertype,
TS, ID, SIZE, MONEY, EXMONEY; //Variables to be extracted from file
char event, order;
Restaurant* pRest; //Pointer to restaurant where file loading occurs
};
#endif
| [
"s-alaaalagami@zewailcity.edu.eg"
] | s-alaaalagami@zewailcity.edu.eg |
88cd7b41ed73c57bdedb36b6d1d43e9779e656fc | 872ee143626405cc285aa99066f968aae1cd551f | /野田 悠介/ソース/SRC/MeshLei/meshLei.cpp | 5f21d0749dfcdcf0e5b2515d6c07c182b9101b31 | [] | no_license | NodaYusuke/- | 67bc9b21c4333ea3a7689028c69a437187f98d3c | bc75c124f534306f42c671a6bc6d77459624ff46 | refs/heads/master | 2022-10-15T15:49:26.521881 | 2020-06-12T03:18:31 | 2020-06-12T03:18:31 | 271,691,539 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 2,065 | cpp | #include"meshLei.h"
C_MeshLei::C_MeshLei()
{
}
C_MeshLei::~C_MeshLei()
{
}
//メッシュのレイ判定を行う関数======================================================================
//LPD3DXMESH lpMesh; /*メッシュの形状*/
//D3DXMATRIX meshMat;/*メッシュの行列*/
//D3DXVECTOR3 nowPos;/*現在の位置*/
//D3DXMATRIX rotMat;/*発射位置の回転行列*/
//D3DXVECTOR3 vec; /*ワールド座標のレイ発射方向*/
float C_MeshLei::update(LPD3DXMESH lpMesh, D3DXMATRIX meshMat, D3DXVECTOR3 nowPos, D3DXVECTOR3 vec,D3DXMATRIX rotMat)
{
//行列でベクトルを加工---------------------------------------
/*ワールド座標のレイ発射方向を求める*/
D3DXVec3TransformCoord(&vec , &vec, &rotMat);
//-----------------------------------------------------------
D3DXMATRIX InvMat; /*メッシュの逆行列*/
//逆行列の作成------------------------------
D3DXMatrixInverse(&InvMat, NULL, &meshMat);
//------------------------------------------
D3DXVECTOR3 localPos ;/*計算上のレイ発射位置 */
D3DXVECTOR3 localVec ;/*計算上のレイ発射方向 */
//行列でベクトルを加工------------------------------
/*ローカル座標のレイ発射位置を求める*/
D3DXVec3TransformCoord(&localPos, &nowPos, &InvMat);
//--------------------------------------------------
//行列でベクトルを加工----------------------------
/*ローカル座標のレイ発射方向を求める*/
D3DXVec3TransformNormal(&localVec , &vec , &InvMat);
//------------------------------------------------
BOOL Hit; /*当たったかどうか*/
float meshDis;/*レイがあったた距離(true,false)*/
//メッシュとのレイ判定--------------------------------------------------------------------
D3DXIntersect(lpMesh, &localPos, &localVec, &Hit, NULL, NULL, NULL, &meshDis, NULL, NULL);
if (Hit == TRUE)
{
return meshDis;
}
else
{
return -1;
}
}
//================================================================================================== | [
"kd1227649@st.kobedenshi.ac.jp"
] | kd1227649@st.kobedenshi.ac.jp |
e1c196971800411b924564170f0d31263bf89ae7 | fa3050f5e5ee850ba39ccb602804c001d9b4dede | /ash/webui/shimless_rma/backend/shimless_rma_service.h | defc8c9b3b165d52f58973c49e5c176c06ed5a00 | [
"BSD-3-Clause"
] | permissive | wayou/chromium | a64c9df7d9c6190f8f9f730e7f68a998ffcabfc9 | f5f51fc460df28cef915df71b4161aaa6b668004 | refs/heads/main | 2023-06-27T18:09:41.425496 | 2021-09-08T23:02:28 | 2021-09-08T23:02:28 | 404,525,907 | 1 | 0 | BSD-3-Clause | 2021-09-08T23:38:08 | 2021-09-08T23:38:08 | null | UTF-8 | C++ | false | false | 7,454 | h | // Copyright 2021 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.
#ifndef ASH_WEBUI_SHIMLESS_RMA_BACKEND_SHIMLESS_RMA_SERVICE_H_
#define ASH_WEBUI_SHIMLESS_RMA_BACKEND_SHIMLESS_RMA_SERVICE_H_
#include <string>
#include "ash/webui/shimless_rma/backend/version_updater.h"
#include "ash/webui/shimless_rma/mojom/shimless_rma.mojom.h"
#include "chromeos/dbus/rmad/rmad.pb.h"
#include "chromeos/dbus/rmad/rmad_client.h"
#include "chromeos/dbus/update_engine/update_engine.pb.h"
#include "chromeos/services/network_config/public/mojom/cros_network_config.mojom.h"
#include "chromeos/services/network_config/public/mojom/network_types.mojom-forward.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/receiver.h"
#include "mojo/public/cpp/bindings/remote_set.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
namespace ash {
namespace shimless_rma {
class ShimlessRmaService : public mojom::ShimlessRmaService,
public chromeos::RmadClient::Observer {
public:
ShimlessRmaService();
ShimlessRmaService(const ShimlessRmaService&) = delete;
ShimlessRmaService& operator=(const ShimlessRmaService&) = delete;
~ShimlessRmaService() override;
void GetCurrentState(GetCurrentStateCallback callback) override;
void TransitionNextState(TransitionNextStateCallback callback) override;
void TransitionPreviousState(
TransitionPreviousStateCallback callback) override;
void AbortRma(AbortRmaCallback callback) override;
void BeginFinalization(BeginFinalizationCallback callback) override;
void NetworkSelectionComplete(
NetworkSelectionCompleteCallback callback) override;
void GetCurrentOsVersion(GetCurrentOsVersionCallback callback) override;
void CheckForOsUpdates(CheckForOsUpdatesCallback callback) override;
void UpdateOs(UpdateOsCallback callback) override;
void UpdateOsSkipped(UpdateOsSkippedCallback callback) override;
void SetSameOwner(SetSameOwnerCallback callback) override;
void SetDifferentOwner(SetDifferentOwnerCallback callback) override;
void ChooseManuallyDisableWriteProtect(
ChooseManuallyDisableWriteProtectCallback callback) override;
void ChooseRsuDisableWriteProtect(
ChooseRsuDisableWriteProtectCallback callback) override;
void GetRsuDisableWriteProtectChallenge(
GetRsuDisableWriteProtectChallengeCallback callback) override;
void GetRsuDisableWriteProtectChallengeQrCode(
GetRsuDisableWriteProtectChallengeQrCodeCallback callback) override;
void SetRsuDisableWriteProtectCode(
const std::string& code,
SetRsuDisableWriteProtectCodeCallback callback) override;
void GetComponentList(GetComponentListCallback callback) override;
void SetComponentList(
const std::vector<::rmad::ComponentsRepairState_ComponentRepairStatus>&
component_list,
SetComponentListCallback callback) override;
void ReworkMainboard(ReworkMainboardCallback callback) override;
void ReimageRequired(ReimageRequiredCallback callback) override;
void ReimageSkipped(ReimageSkippedCallback callback) override;
void ReimageFromDownload(ReimageFromDownloadCallback callback) override;
void ReimageFromUsb(ReimageFromUsbCallback callback) override;
void ShutdownForRestock(ShutdownForRestockCallback callback) override;
void ContinueFinalizationAfterRestock(
ContinueFinalizationAfterRestockCallback callback) override;
void GetRegionList(GetRegionListCallback callback) override;
void GetSkuList(GetSkuListCallback callback) override;
void GetOriginalSerialNumber(
GetOriginalSerialNumberCallback callback) override;
void GetOriginalRegion(GetOriginalRegionCallback callback) override;
void GetOriginalSku(GetOriginalSkuCallback callback) override;
void SetDeviceInformation(const std::string& serial_number,
uint8_t region_index,
uint8_t sku_index,
SetDeviceInformationCallback callback) override;
void FinalizeAndReboot(FinalizeAndRebootCallback callback) override;
void FinalizeAndShutdown(FinalizeAndShutdownCallback callback) override;
void CutoffBattery(CutoffBatteryCallback callback) override;
void ObserveError(
::mojo::PendingRemote<mojom::ErrorObserver> observer) override;
void ObserveOsUpdateProgress(
::mojo::PendingRemote<mojom::OsUpdateObserver> observer) override;
void ObserveCalibrationProgress(
::mojo::PendingRemote<mojom::CalibrationObserver> observer) override;
void ObserveProvisioningProgress(
::mojo::PendingRemote<mojom::ProvisioningObserver> observer) override;
void ObserveHardwareWriteProtectionState(
::mojo::PendingRemote<mojom::HardwareWriteProtectionStateObserver>
observer) override;
void ObservePowerCableState(
::mojo::PendingRemote<mojom::PowerCableStateObserver> observer) override;
void BindInterface(
mojo::PendingReceiver<mojom::ShimlessRmaService> pending_receiver);
// RmadClient::Observer interface.
void Error(rmad::RmadErrorCode error) override;
void CalibrationProgress(rmad::RmadComponent component,
double progress) override;
void ProvisioningProgress(rmad::ProvisionDeviceState::ProvisioningStep step,
double progress) override;
void HardwareWriteProtectionState(bool enabled) override;
void PowerCableState(bool plugged_in) override;
void OsUpdateProgress(update_engine::Operation operation, double progress);
private:
template <class Callback>
void TransitionNextStateGeneric(Callback callback);
template <class Callback>
void OnGetStateResponse(Callback callback,
absl::optional<rmad::GetStateReply> response);
void OnAbortRmaResponse(AbortRmaCallback callback,
absl::optional<rmad::AbortRmaReply> response);
void OnNetworkListResponse(
BeginFinalizationCallback callback,
std::vector<chromeos::network_config::mojom::NetworkStatePropertiesPtr>
response);
void OnOsUpdateStatusCallback(update_engine::Operation operation,
double progress,
bool rollback,
bool powerwash,
const std::string& version,
int64_t update_size);
rmad::RmadState state_proto_;
mojo::Remote<mojom::ErrorObserver> error_observer_;
mojo::Remote<mojom::OsUpdateObserver> os_update_observer_;
mojo::Remote<mojom::CalibrationObserver> calibration_observer_;
mojo::Remote<mojom::ProvisioningObserver> provisioning_observer_;
mojo::Remote<mojom::HardwareWriteProtectionStateObserver>
hwwp_state_observer_;
mojo::Remote<mojom::PowerCableStateObserver> power_cable_observer_;
mojo::Receiver<mojom::ShimlessRmaService> receiver_{this};
mojo::Remote<chromeos::network_config::mojom::CrosNetworkConfig>
remote_cros_network_config_;
VersionUpdater version_updater_;
// Note: This should remain the last member so it'll be destroyed and
// invalidate its weak pointers before any other members are destroyed.
base::WeakPtrFactory<ShimlessRmaService> weak_ptr_factory_{this};
};
} // namespace shimless_rma
} // namespace ash
#endif // ASH_WEBUI_SHIMLESS_RMA_BACKEND_SHIMLESS_RMA_SERVICE_H_
| [
"chromium-scoped@luci-project-accounts.iam.gserviceaccount.com"
] | chromium-scoped@luci-project-accounts.iam.gserviceaccount.com |
0e5ae6a14ae350dde102f7cb33f7e04f769367c6 | 3a4c99444cdc438c794a661890fb99e39bababbe | /inc/vk_mem_alloc.h | d0ce578868fe1b4e121cdd4c1340885821a43378 | [] | no_license | JackErb/wayward-vulkan-engine | e25689e7cbceea829ab959b0131310ca4ae5e28c | 708c7240cd3a852286120910d56d0c0543ac820b | refs/heads/main | 2023-07-17T07:22:01.294812 | 2021-09-02T02:51:19 | 2021-09-02T02:51:19 | 378,731,260 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 315,335 | h | //
// Copyright (c) 2017-2018 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#ifndef AMD_VULKAN_MEMORY_ALLOCATOR_H
#define AMD_VULKAN_MEMORY_ALLOCATOR_H
#ifdef __cplusplus
extern "C" {
#endif
/** \mainpage Vulkan Memory Allocator
<b>Version 2.0.0</b> (2018-03-19)
Copyright (c) 2017-2018 Advanced Micro Devices, Inc. All rights reserved. \n
License: MIT
Documentation of all members: vk_mem_alloc.h
\section main_table_of_contents Table of contents
- <b>User guide</b>
- \subpage quick_start
- [Project setup](@ref quick_start_project_setup)
- [Initialization](@ref quick_start_initialization)
- [Resource allocation](@ref quick_start_resource_allocation)
- \subpage choosing_memory_type
- [Usage](@ref choosing_memory_type_usage)
- [Required and preferred flags](@ref choosing_memory_type_required_preferred_flags)
- [Explicit memory types](@ref choosing_memory_type_explicit_memory_types)
- [Custom memory pools](@ref choosing_memory_type_custom_memory_pools)
- \subpage memory_mapping
- [Mapping functions](@ref memory_mapping_mapping_functions)
- [Persistently mapped memory](@ref memory_mapping_persistently_mapped_memory)
- [Cache control](@ref memory_mapping_cache_control)
- [Finding out if memory is mappable](@ref memory_mapping_finding_if_memory_mappable)
- \subpage custom_memory_pools
- [Choosing memory type index](@ref custom_memory_pools_MemTypeIndex)
- \subpage defragmentation
- \subpage lost_allocations
- \subpage statistics
- [Numeric statistics](@ref statistics_numeric_statistics)
- [JSON dump](@ref statistics_json_dump)
- \subpage allocation_annotation
- [Allocation user data](@ref allocation_user_data)
- [Allocation names](@ref allocation_names)
- \subpage usage_patterns
- [Simple patterns](@ref usage_patterns_simple)
- [Advanced patterns](@ref usage_patterns_advanced)
- \subpage configuration
- [Pointers to Vulkan functions](@ref config_Vulkan_functions)
- [Custom host memory allocator](@ref custom_memory_allocator)
- [Device memory allocation callbacks](@ref allocation_callbacks)
- [Device heap memory limit](@ref heap_memory_limit)
- \subpage vk_khr_dedicated_allocation
- \subpage general_considerations
- [Thread safety](@ref general_considerations_thread_safety)
- [Allocation algorithm](@ref general_considerations_allocation_algorithm)
- [Features not supported](@ref general_considerations_features_not_supported)
\section main_see_also See also
- [Product page on GPUOpen](https://gpuopen.com/gaming-product/vulkan-memory-allocator/)
- [Source repository on GitHub](https://github.com/GPUOpen-LibrariesAndSDKs/VulkanMemoryAllocator)
\page quick_start Quick start
\section quick_start_project_setup Project setup
Vulkan Memory Allocator comes in form of a single header file.
You don't need to build it as a separate library project.
You can add this file directly to your project and submit it to code repository next to your other source files.
"Single header" doesn't mean that everything is contained in C/C++ declarations,
like it tends to be in case of inline functions or C++ templates.
It means that implementation is bundled with interface in a single file and needs to be extracted using preprocessor macro.
If you don't do it properly, you will get linker errors.
To do it properly:
-# Include "vk_mem_alloc.h" file in each CPP file where you want to use the library.
This includes declarations of all members of the library.
-# In exacly one CPP file define following macro before this include.
It enables also internal definitions.
\code
#define VMA_IMPLEMENTATION
#include "vk_mem_alloc.h"
\endcode
It may be a good idea to create dedicated CPP file just for this purpose.
\section quick_start_initialization Initialization
At program startup:
-# Initialize Vulkan to have `VkPhysicalDevice` and `VkDevice` object.
-# Fill VmaAllocatorCreateInfo structure and create #VmaAllocator object by
calling vmaCreateAllocator().
\code
VmaAllocatorCreateInfo allocatorInfo = {};
allocatorInfo.physicalDevice = physicalDevice;
allocatorInfo.device = device;
VmaAllocator allocator;
vmaCreateAllocator(&allocatorInfo, &allocator);
\endcode
\section quick_start_resource_allocation Resource allocation
When you want to create a buffer or image:
-# Fill `VkBufferCreateInfo` / `VkImageCreateInfo` structure.
-# Fill VmaAllocationCreateInfo structure.
-# Call vmaCreateBuffer() / vmaCreateImage() to get `VkBuffer`/`VkImage` with memory
already allocated and bound to it.
\code
VkBufferCreateInfo bufferInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
bufferInfo.size = 65536;
bufferInfo.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
VmaAllocationCreateInfo allocInfo = {};
allocInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY;
VkBuffer buffer;
VmaAllocation allocation;
vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, &buffer, &allocation, nullptr);
\endcode
Don't forget to destroy your objects when no longer needed:
\code
vmaDestroyBuffer(allocator, buffer, allocation);
vmaDestroyAllocator(allocator);
\endcode
\page choosing_memory_type Choosing memory type
Physical devices in Vulkan support various combinations of memory heaps and
types. Help with choosing correct and optimal memory type for your specific
resource is one of the key features of this library. You can use it by filling
appropriate members of VmaAllocationCreateInfo structure, as described below.
You can also combine multiple methods.
-# If you just want to find memory type index that meets your requirements, you
can use function vmaFindMemoryTypeIndex().
-# If you want to allocate a region of device memory without association with any
specific image or buffer, you can use function vmaAllocateMemory(). Usage of
this function is not recommended and usually not needed.
-# If you already have a buffer or an image created, you want to allocate memory
for it and then you will bind it yourself, you can use function
vmaAllocateMemoryForBuffer(), vmaAllocateMemoryForImage().
For binding you should use functions: vmaBindBufferMemory(), vmaBindImageMemory().
-# If you want to create a buffer or an image, allocate memory for it and bind
them together, all in one call, you can use function vmaCreateBuffer(),
vmaCreateImage(). This is the recommended way to use this library.
When using 3. or 4., the library internally queries Vulkan for memory types
supported for that buffer or image (function `vkGetBufferMemoryRequirements()`)
and uses only one of these types.
If no memory type can be found that meets all the requirements, these functions
return `VK_ERROR_FEATURE_NOT_PRESENT`.
You can leave VmaAllocationCreateInfo structure completely filled with zeros.
It means no requirements are specified for memory type.
It is valid, although not very useful.
\section choosing_memory_type_usage Usage
The easiest way to specify memory requirements is to fill member
VmaAllocationCreateInfo::usage using one of the values of enum #VmaMemoryUsage.
It defines high level, common usage types.
For more details, see description of this enum.
For example, if you want to create a uniform buffer that will be filled using
transfer only once or infrequently and used for rendering every frame, you can
do it using following code:
\code
VkBufferCreateInfo bufferInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
bufferInfo.size = 65536;
bufferInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
VmaAllocationCreateInfo allocInfo = {};
allocInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY;
VkBuffer buffer;
VmaAllocation allocation;
vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, &buffer, &allocation, nullptr);
\endcode
\section choosing_memory_type_required_preferred_flags Required and preferred flags
You can specify more detailed requirements by filling members
VmaAllocationCreateInfo::requiredFlags and VmaAllocationCreateInfo::preferredFlags
with a combination of bits from enum `VkMemoryPropertyFlags`. For example,
if you want to create a buffer that will be persistently mapped on host (so it
must be `HOST_VISIBLE`) and preferably will also be `HOST_COHERENT` and `HOST_CACHED`,
use following code:
\code
VmaAllocationCreateInfo allocInfo = {};
allocInfo.requiredFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
allocInfo.preferredFlags = VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | VK_MEMORY_PROPERTY_HOST_CACHED_BIT;
allocInfo.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT;
VkBuffer buffer;
VmaAllocation allocation;
vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, &buffer, &allocation, nullptr);
\endcode
A memory type is chosen that has all the required flags and as many preferred
flags set as possible.
If you use VmaAllocationCreateInfo::usage, it is just internally converted to
a set of required and preferred flags.
\section choosing_memory_type_explicit_memory_types Explicit memory types
If you inspected memory types available on the physical device and you have
a preference for memory types that you want to use, you can fill member
VmaAllocationCreateInfo::memoryTypeBits. It is a bit mask, where each bit set
means that a memory type with that index is allowed to be used for the
allocation. Special value 0, just like `UINT32_MAX`, means there are no
restrictions to memory type index.
Please note that this member is NOT just a memory type index.
Still you can use it to choose just one, specific memory type.
For example, if you already determined that your buffer should be created in
memory type 2, use following code:
\code
uint32_t memoryTypeIndex = 2;
VmaAllocationCreateInfo allocInfo = {};
allocInfo.memoryTypeBits = 1u << memoryTypeIndex;
VkBuffer buffer;
VmaAllocation allocation;
vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, &buffer, &allocation, nullptr);
\endcode
\section choosing_memory_type_custom_memory_pools Custom memory pools
If you allocate from custom memory pool, all the ways of specifying memory
requirements described above are not applicable and the aforementioned members
of VmaAllocationCreateInfo structure are ignored. Memory type is selected
explicitly when creating the pool and then used to make all the allocations from
that pool. For further details, see \ref custom_memory_pools.
\page memory_mapping Memory mapping
To "map memory" in Vulkan means to obtain a CPU pointer to `VkDeviceMemory`,
to be able to read from it or write to it in CPU code.
Mapping is possible only of memory allocated from a memory type that has
`VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT` flag.
Functions `vkMapMemory()`, `vkUnmapMemory()` are designed for this purpose.
You can use them directly with memory allocated by this library,
but it is not recommended because of following issue:
Mapping the same `VkDeviceMemory` block multiple times is illegal - only one mapping at a time is allowed.
This includes mapping disjoint regions. Mapping is not reference-counted internally by Vulkan.
Because of this, Vulkan Memory Allocator provides following facilities:
\section memory_mapping_mapping_functions Mapping functions
The library provides following functions for mapping of a specific #VmaAllocation: vmaMapMemory(), vmaUnmapMemory().
They are safer and more convenient to use than standard Vulkan functions.
You can map an allocation multiple times simultaneously - mapping is reference-counted internally.
You can also map different allocations simultaneously regardless of whether they use the same `VkDeviceMemory` block.
They way it's implemented is that the library always maps entire memory block, not just region of the allocation.
For further details, see description of vmaMapMemory() function.
Example:
\code
// Having these objects initialized:
struct ConstantBuffer
{
...
};
ConstantBuffer constantBufferData;
VmaAllocator allocator;
VmaBuffer constantBuffer;
VmaAllocation constantBufferAllocation;
// You can map and fill your buffer using following code:
void* mappedData;
vmaMapMemory(allocator, constantBufferAllocation, &mappedData);
memcpy(mappedData, &constantBufferData, sizeof(constantBufferData));
vmaUnmapMemory(allocator, constantBufferAllocation);
\endcode
\section memory_mapping_persistently_mapped_memory Persistently mapped memory
Kepping your memory persistently mapped is generally OK in Vulkan.
You don't need to unmap it before using its data on the GPU.
The library provides a special feature designed for that:
Allocations made with #VMA_ALLOCATION_CREATE_MAPPED_BIT flag set in
VmaAllocationCreateInfo::flags stay mapped all the time,
so you can just access CPU pointer to it any time
without a need to call any "map" or "unmap" function.
Example:
\code
VkBufferCreateInfo bufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
bufCreateInfo.size = sizeof(ConstantBuffer);
bufCreateInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
VmaAllocationCreateInfo allocCreateInfo = {};
allocCreateInfo.usage = VMA_MEMORY_USAGE_CPU_ONLY;
allocCreateInfo.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT;
VkBuffer buf;
VmaAllocation alloc;
VmaAllocationInfo allocInfo;
vmaCreateBuffer(allocator, &bufCreateInfo, &allocCreateInfo, &buf, &alloc, &allocInfo);
// Buffer is already mapped. You can access its memory.
memcpy(allocInfo.pMappedData, &constantBufferData, sizeof(constantBufferData));
\endcode
There are some exceptions though, when you should consider mapping memory only for a short period of time:
- When operating system is Windows 7 or 8.x (Windows 10 is not affected because it uses WDDM2),
device is discrete AMD GPU,
and memory type is the special 256 MiB pool of `DEVICE_LOCAL + HOST_VISIBLE` memory
(selected when you use #VMA_MEMORY_USAGE_CPU_TO_GPU),
then whenever a memory block allocated from this memory type stays mapped
for the time of any call to `vkQueueSubmit()` or `vkQueuePresentKHR()`, this
block is migrated by WDDM to system RAM, which degrades performance. It doesn't
matter if that particular memory block is actually used by the command buffer
being submitted.
- Keeping many large memory blocks mapped may impact performance or stability of some debugging tools.
\section memory_mapping_cache_control Cache control
Memory in Vulkan doesn't need to be unmapped before using it on GPU,
but unless a memory types has `VK_MEMORY_PROPERTY_HOST_COHERENT_BIT` flag set,
you need to manually invalidate cache before reading of mapped pointer
using function `vkvkInvalidateMappedMemoryRanges()`
and flush cache after writing to mapped pointer
using function `vkFlushMappedMemoryRanges()`.
Example:
\code
memcpy(allocInfo.pMappedData, &constantBufferData, sizeof(constantBufferData));
VkMemoryPropertyFlags memFlags;
vmaGetMemoryTypeProperties(allocator, allocInfo.memoryType, &memFlags);
if((memFlags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) == 0)
{
VkMappedMemoryRange memRange = { VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE };
memRange.memory = allocInfo.deviceMemory;
memRange.offset = allocInfo.offset;
memRange.size = allocInfo.size;
vkFlushMappedMemoryRanges(device, 1, &memRange);
}
\endcode
Please note that memory allocated with #VMA_MEMORY_USAGE_CPU_ONLY is guaranteed to be host coherent.
Also, Windows drivers from all 3 PC GPU vendors (AMD, Intel, NVIDIA)
currently provide `VK_MEMORY_PROPERTY_HOST_COHERENT_BIT` flag on all memory types that are
`VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT`, so on this platform you may not need to bother.
\section memory_mapping_finding_if_memory_mappable Finding out if memory is mappable
It may happen that your allocation ends up in memory that is `HOST_VISIBLE` (available for mapping)
despite it wasn't explicitly requested.
For example, application may work on integrated graphics with unified memory (like Intel) or
allocation from video memory might have failed, so the library chose system memory as fallback.
You can detect this case and map such allocation to access its memory on CPU directly,
instead of launching a transfer operation.
In order to do that: inspect `allocInfo.memoryType`, call vmaGetMemoryTypeProperties(),
and look for `VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT` flag in properties of that memory type.
\code
VkBufferCreateInfo bufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
bufCreateInfo.size = sizeof(ConstantBuffer);
bufCreateInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
VmaAllocationCreateInfo allocCreateInfo = {};
allocCreateInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY;
VkBuffer buf;
VmaAllocation alloc;
VmaAllocationInfo allocInfo;
vmaCreateBuffer(allocator, &bufCreateInfo, &allocCreateInfo, &buf, &alloc, &allocInfo);
VkMemoryPropertyFlags memFlags;
vmaGetMemoryTypeProperties(allocator, allocInfo.memoryType, &memFlags);
if((memFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) == 0)
{
// Allocation ended up in mappable memory. You can map it and access it directly.
void* mappedData;
vmaMapMemory(allocator, alloc, &mappedData);
memcpy(mappedData, &constantBufferData, sizeof(constantBufferData));
vmaUnmapMemory(allocator, alloc);
}
else
{
// Allocation ended up in non-mappable memory.
// You need to create CPU-side buffer in VMA_MEMORY_USAGE_CPU_ONLY and make a transfer.
}
\endcode
You can even use #VMA_ALLOCATION_CREATE_MAPPED_BIT flag while creating allocations
that are not necessarily `HOST_VISIBLE` (e.g. using #VMA_MEMORY_USAGE_GPU_ONLY).
If the allocation ends up in memory type that is `HOST_VISIBLE`, it will be persistently mapped and you can use it directly.
If not, the flag is just ignored.
Example:
\code
VkBufferCreateInfo bufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
bufCreateInfo.size = sizeof(ConstantBuffer);
bufCreateInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
VmaAllocationCreateInfo allocCreateInfo = {};
allocCreateInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY;
allocCreateInfo.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT;
VkBuffer buf;
VmaAllocation alloc;
VmaAllocationInfo allocInfo;
vmaCreateBuffer(allocator, &bufCreateInfo, &allocCreateInfo, &buf, &alloc, &allocInfo);
if(allocInfo.pUserData != nullptr)
{
// Allocation ended up in mappable memory.
// It's persistently mapped. You can access it directly.
memcpy(allocInfo.pMappedData, &constantBufferData, sizeof(constantBufferData));
}
else
{
// Allocation ended up in non-mappable memory.
// You need to create CPU-side buffer in VMA_MEMORY_USAGE_CPU_ONLY and make a transfer.
}
\endcode
\page custom_memory_pools Custom memory pools
A memory pool contains a number of `VkDeviceMemory` blocks.
The library automatically creates and manages default pool for each memory type available on the device.
Default memory pool automatically grows in size.
Size of allocated blocks is also variable and managed automatically.
You can create custom pool and allocate memory out of it.
It can be useful if you want to:
- Keep certain kind of allocations separate from others.
- Enforce particular, fixed size of Vulkan memory blocks.
- Limit maximum amount of Vulkan memory allocated for that pool.
- Reserve minimum or fixed amount of Vulkan memory always preallocated for that pool.
To use custom memory pools:
-# Fill VmaPoolCreateInfo structure.
-# Call vmaCreatePool() to obtain #VmaPool handle.
-# When making an allocation, set VmaAllocationCreateInfo::pool to this handle.
You don't need to specify any other parameters of this structure, like usage.
Example:
\code
// Create a pool that can have at most 2 blocks, 128 MiB each.
VmaPoolCreateInfo poolCreateInfo = {};
poolCreateInfo.memoryTypeIndex = ...
poolCreateInfo.blockSize = 128ull * 1024 * 1024;
poolCreateInfo.maxBlockCount = 2;
VmaPool pool;
vmaCreatePool(allocator, &poolCreateInfo, &pool);
// Allocate a buffer out of it.
VkBufferCreateInfo bufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
bufCreateInfo.size = 1024;
bufCreateInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
VmaAllocationCreateInfo allocCreateInfo = {};
allocCreateInfo.pool = pool;
VkBuffer buf;
VmaAllocation alloc;
VmaAllocationInfo allocInfo;
vmaCreateBuffer(allocator, &bufCreateInfo, &allocCreateInfo, &buf, &alloc, &allocInfo);
\endcode
You have to free all allocations made from this pool before destroying it.
\code
vmaDestroyBuffer(allocator, buf, alloc);
vmaDestroyPool(allocator, pool);
\endcode
\section custom_memory_pools_MemTypeIndex Choosing memory type index
When creating a pool, you must explicitly specify memory type index.
To find the one suitable for your buffers or images, you can use helper functions
vmaFindMemoryTypeIndexForBufferInfo(), vmaFindMemoryTypeIndexForImageInfo().
You need to provide structures with example parameters of buffers or images
that you are going to create in that pool.
\code
VkBufferCreateInfo exampleBufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
exampleBufCreateInfo.size = 1024; // Whatever.
exampleBufCreateInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; // Change if needed.
VmaAllocationCreateInfo allocCreateInfo = {};
allocCreateInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY; // Change if needed.
uint32_t memTypeIndex;
vmaFindMemoryTypeIndexForBufferInfo(allocator, &exampleBufCreateInfo, &allocCreateInfo, &memTypeIndex);
VmaPoolCreateInfo poolCreateInfo = {};
poolCreateInfo.memoryTypeIndex = memTypeIndex;
// ...
\endcode
When creating buffers/images allocated in that pool, provide following parameters:
- `VkBufferCreateInfo`: Prefer to pass same parameters as above.
Otherwise you risk creating resources in a memory type that is not suitable for them, which may result in undefined behavior.
Using different `VK_BUFFER_USAGE_` flags may work, but you shouldn't create images in a pool intended for buffers
or the other way around.
- VmaAllocationCreateInfo: You don't need to pass same parameters. Fill only `pool` member.
Other members are ignored anyway.
\page defragmentation Defragmentation
Interleaved allocations and deallocations of many objects of varying size can
cause fragmentation, which can lead to a situation where the library is unable
to find a continuous range of free memory for a new allocation despite there is
enough free space, just scattered across many small free ranges between existing
allocations.
To mitigate this problem, you can use vmaDefragment(). Given set of allocations,
this function can move them to compact used memory, ensure more continuous free
space and possibly also free some `VkDeviceMemory`. It can work only on
allocations made from memory type that is `HOST_VISIBLE`. Allocations are
modified to point to the new `VkDeviceMemory` and offset. Data in this memory is
also `memmove`-ed to the new place. However, if you have images or buffers bound
to these allocations (and you certainly do), you need to destroy, recreate, and
bind them to the new place in memory.
For further details and example code, see documentation of function
vmaDefragment().
\page lost_allocations Lost allocations
If your game oversubscribes video memory, if may work OK in previous-generation
graphics APIs (DirectX 9, 10, 11, OpenGL) because resources are automatically
paged to system RAM. In Vulkan you can't do it because when you run out of
memory, an allocation just fails. If you have more data (e.g. textures) that can
fit into VRAM and you don't need it all at once, you may want to upload them to
GPU on demand and "push out" ones that are not used for a long time to make room
for the new ones, effectively using VRAM (or a cartain memory pool) as a form of
cache. Vulkan Memory Allocator can help you with that by supporting a concept of
"lost allocations".
To create an allocation that can become lost, include #VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT
flag in VmaAllocationCreateInfo::flags. Before using a buffer or image bound to
such allocation in every new frame, you need to query it if it's not lost.
To check it, call vmaTouchAllocation().
If the allocation is lost, you should not use it or buffer/image bound to it.
You mustn't forget to destroy this allocation and this buffer/image.
vmaGetAllocationInfo() can also be used for checking status of the allocation.
Allocation is lost when returned VmaAllocationInfo::deviceMemory == `VK_NULL_HANDLE`.
To create an allocation that can make some other allocations lost to make room
for it, use #VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT flag. You will
usually use both flags #VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT and
#VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT at the same time.
Warning! Current implementation uses quite naive, brute force algorithm,
which can make allocation calls that use #VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT
flag quite slow. A new, more optimal algorithm and data structure to speed this
up is planned for the future.
<b>Q: When interleaving creation of new allocations with usage of existing ones,
how do you make sure that an allocation won't become lost while it's used in the
current frame?</b>
It is ensured because vmaTouchAllocation() / vmaGetAllocationInfo() not only returns allocation
status/parameters and checks whether it's not lost, but when it's not, it also
atomically marks it as used in the current frame, which makes it impossible to
become lost in that frame. It uses lockless algorithm, so it works fast and
doesn't involve locking any internal mutex.
<b>Q: What if my allocation may still be in use by the GPU when it's rendering a
previous frame while I already submit new frame on the CPU?</b>
You can make sure that allocations "touched" by vmaTouchAllocation() / vmaGetAllocationInfo() will not
become lost for a number of additional frames back from the current one by
specifying this number as VmaAllocatorCreateInfo::frameInUseCount (for default
memory pool) and VmaPoolCreateInfo::frameInUseCount (for custom pool).
<b>Q: How do you inform the library when new frame starts?</b>
You need to call function vmaSetCurrentFrameIndex().
Example code:
\code
struct MyBuffer
{
VkBuffer m_Buf = nullptr;
VmaAllocation m_Alloc = nullptr;
// Called when the buffer is really needed in the current frame.
void EnsureBuffer();
};
void MyBuffer::EnsureBuffer()
{
// Buffer has been created.
if(m_Buf != VK_NULL_HANDLE)
{
// Check if its allocation is not lost + mark it as used in current frame.
if(vmaTouchAllocation(allocator, m_Alloc))
{
// It's all OK - safe to use m_Buf.
return;
}
}
// Buffer not yet exists or lost - destroy and recreate it.
vmaDestroyBuffer(allocator, m_Buf, m_Alloc);
VkBufferCreateInfo bufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
bufCreateInfo.size = 1024;
bufCreateInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
VmaAllocationCreateInfo allocCreateInfo = {};
allocCreateInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY;
allocCreateInfo.flags = VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT |
VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT;
vmaCreateBuffer(allocator, &bufCreateInfo, &allocCreateInfo, &m_Buf, &m_Alloc, nullptr);
}
\endcode
When using lost allocations, you may see some Vulkan validation layer warnings
about overlapping regions of memory bound to different kinds of buffers and
images. This is still valid as long as you implement proper handling of lost
allocations (like in the example above) and don't use them.
You can create an allocation that is already in lost state from the beginning using function
vmaCreateLostAllocation(). It may be useful if you need a "dummy" allocation that is not null.
You can call function vmaMakePoolAllocationsLost() to set all eligible allocations
in a specified custom pool to lost state.
Allocations that have been "touched" in current frame or VmaPoolCreateInfo::frameInUseCount frames back
cannot become lost.
\page statistics Statistics
This library contains functions that return information about its internal state,
especially the amount of memory allocated from Vulkan.
Please keep in mind that these functions need to traverse all internal data structures
to gather these information, so they may be quite time-consuming.
Don't call them too often.
\section statistics_numeric_statistics Numeric statistics
You can query for overall statistics of the allocator using function vmaCalculateStats().
Information are returned using structure #VmaStats.
It contains #VmaStatInfo - number of allocated blocks, number of allocations
(occupied ranges in these blocks), number of unused (free) ranges in these blocks,
number of bytes used and unused (but still allocated from Vulkan) and other information.
They are summed across memory heaps, memory types and total for whole allocator.
You can query for statistics of a custom pool using function vmaGetPoolStats().
Information are returned using structure #VmaPoolStats.
You can query for information about specific allocation using function vmaGetAllocationInfo().
It fill structure #VmaAllocationInfo.
\section statistics_json_dump JSON dump
You can dump internal state of the allocator to a string in JSON format using function vmaBuildStatsString().
The result is guaranteed to be correct JSON.
It uses ANSI encoding.
Any strings provided by user (see [Allocation names](@ref allocation_names))
are copied as-is and properly escaped for JSON, so if they use UTF-8, ISO-8859-2 or any other encoding,
this JSON string can be treated as using this encoding.
It must be freed using function vmaFreeStatsString().
The format of this JSON string is not part of official documentation of the library,
but it will not change in backward-incompatible way without increasing library major version number
and appropriate mention in changelog.
The JSON string contains all the data that can be obtained using vmaCalculateStats().
It can also contain detailed map of allocated memory blocks and their regions -
free and occupied by allocations.
This allows e.g. to visualize the memory or assess fragmentation.
\page allocation_annotation Allocation names and user data
\section allocation_user_data Allocation user data
You can annotate allocations with your own information, e.g. for debugging purposes.
To do that, fill VmaAllocationCreateInfo::pUserData field when creating
an allocation. It's an opaque `void*` pointer. You can use it e.g. as a pointer,
some handle, index, key, ordinal number or any other value that would associate
the allocation with your custom metadata.
\code
VkBufferCreateInfo bufferInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
// Fill bufferInfo...
MyBufferMetadata* pMetadata = CreateBufferMetadata();
VmaAllocationCreateInfo allocCreateInfo = {};
allocCreateInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY;
allocCreateInfo.pUserData = pMetadata;
VkBuffer buffer;
VmaAllocation allocation;
vmaCreateBuffer(allocator, &bufferInfo, &allocCreateInfo, &buffer, &allocation, nullptr);
\endcode
The pointer may be later retrieved as VmaAllocationInfo::pUserData:
\code
VmaAllocationInfo allocInfo;
vmaGetAllocationInfo(allocator, allocation, &allocInfo);
MyBufferMetadata* pMetadata = (MyBufferMetadata*)allocInfo.pUserData;
\endcode
It can also be changed using function vmaSetAllocationUserData().
Values of (non-zero) allocations' `pUserData` are printed in JSON report created by
vmaBuildStatsString(), in hexadecimal form.
\section allocation_names Allocation names
There is alternative mode available where `pUserData` pointer is used to point to
a null-terminated string, giving a name to the allocation. To use this mode,
set #VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT flag in VmaAllocationCreateInfo::flags.
Then `pUserData` passed as VmaAllocationCreateInfo::pUserData or argument to
vmaSetAllocationUserData() must be either null or pointer to a null-terminated string.
The library creates internal copy of the string, so the pointer you pass doesn't need
to be valid for whole lifetime of the allocation. You can free it after the call.
\code
VkImageCreateInfo imageInfo = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO };
// Fill imageInfo...
std::string imageName = "Texture: ";
imageName += fileName;
VmaAllocationCreateInfo allocCreateInfo = {};
allocCreateInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY;
allocCreateInfo.flags = VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT;
allocCreateInfo.pUserData = imageName.c_str();
VkImage image;
VmaAllocation allocation;
vmaCreateImage(allocator, &imageInfo, &allocCreateInfo, &image, &allocation, nullptr);
\endcode
The value of `pUserData` pointer of the allocation will be different than the one
you passed when setting allocation's name - pointing to a buffer managed
internally that holds copy of the string.
\code
VmaAllocationInfo allocInfo;
vmaGetAllocationInfo(allocator, allocation, &allocInfo);
const char* imageName = (const char*)allocInfo.pUserData;
printf("Image name: %s\n", imageName);
\endcode
That string is also printed in JSON report created by vmaBuildStatsString().
\page usage_patterns Recommended usage patterns
\section usage_patterns_simple Simple patterns
\subsection usage_patterns_simple_render_targets Render targets
<b>When:</b>
Any resources that you frequently write and read on GPU,
e.g. images used as color attachments (aka "render targets"), depth-stencil attachments,
images/buffers used as storage image/buffer (aka "Unordered Access View (UAV)").
<b>What to do:</b>
Create them in video memory that is fastest to access from GPU using
#VMA_MEMORY_USAGE_GPU_ONLY.
Consider using [VK_KHR_dedicated_allocation](@ref vk_khr_dedicated_allocation) extension
and/or manually creating them as dedicated allocations using #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT,
especially if they are large or if you plan to destroy and recreate them e.g. when
display resolution changes.
Prefer to create such resources first and all other GPU resources (like textures and vertex buffers) later.
\subsection usage_patterns_simple_immutable_resources Immutable resources
<b>When:</b>
Any resources that you fill on CPU only once (aka "immutable") or infrequently
and then read frequently on GPU,
e.g. textures, vertex and index buffers, constant buffers that don't change often.
<b>What to do:</b>
Create them in video memory that is fastest to access from GPU using
#VMA_MEMORY_USAGE_GPU_ONLY.
To initialize content of such resource, create a CPU-side (aka "staging") copy of it
in system memory - #VMA_MEMORY_USAGE_CPU_ONLY, map it, fill it,
and submit a transfer from it to the GPU resource.
You can keep the staging copy if you need it for another upload transfer in the future.
If you don't, you can destroy it or reuse this buffer for uploading different resource
after the transfer finishes.
Prefer to create just buffers in system memory rather than images, even for uploading textures.
Use `vkCmdCopyBufferToImage()`.
Dont use images with `VK_IMAGE_TILING_LINEAR`.
\subsection usage_patterns_dynamic_resources Dynamic resources
<b>When:</b>
Any resources that change frequently (aka "dynamic"), e.g. every frame or every draw call,
written on CPU, read on GPU.
<b>What to do:</b>
Create them using #VMA_MEMORY_USAGE_CPU_TO_GPU.
You can map it and write to it directly on CPU, as well as read from it on GPU.
This is a more complex situation. Different solutions are possible,
and the best one depends on specific GPU type, but you can use this simple approach for the start.
Prefer to write to such resource sequentially (e.g. using `memcpy`).
Don't perform random access or any reads from it, as it may be very slow.
\subsection usage_patterns_readback Readback
<b>When:</b>
Resources that contain data written by GPU that you want to read back on CPU,
e.g. results of some computations.
<b>What to do:</b>
Create them using #VMA_MEMORY_USAGE_GPU_TO_CPU.
You can write to them directly on GPU, as well as map and read them on CPU.
\section usage_patterns_advanced Advanced patterns
\subsection usage_patterns_integrated_graphics Detecting integrated graphics
You can support integrated graphics (like Intel HD Graphics, AMD APU) better
by detecting it in Vulkan.
To do it, call `vkGetPhysicalDeviceProperties()`, inspect
`VkPhysicalDeviceProperties::deviceType` and look for `VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU`.
When you find it, you can assume that memory is unified and all memory types are equally fast
to access from GPU, regardless of `VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT`.
You can then sum up sizes of all available memory heaps and treat them as useful for
your GPU resources, instead of only `DEVICE_LOCAL` ones.
You can also prefer to create your resources in memory types that are `HOST_VISIBLE` to map them
directly instead of submitting explicit transfer (see below).
\subsection usage_patterns_direct_vs_transfer Direct access versus transfer
For resources that you frequently write on CPU and read on GPU, many solutions are possible:
-# Create one copy in video memory using #VMA_MEMORY_USAGE_GPU_ONLY,
second copy in system memory using #VMA_MEMORY_USAGE_CPU_ONLY and submit explicit tranfer each time.
-# Create just single copy using #VMA_MEMORY_USAGE_CPU_TO_GPU, map it and fill it on CPU,
read it directly on GPU.
-# Create just single copy using #VMA_MEMORY_USAGE_CPU_ONLY, map it and fill it on CPU,
read it directly on GPU.
Which solution is the most efficient depends on your resource and especially on the GPU.
It is best to measure it and then make the decision.
Some general recommendations:
- On integrated graphics use (2) or (3) to avoid unnecesary time and memory overhead
related to using a second copy.
- For small resources (e.g. constant buffers) use (2).
Discrete AMD cards have special 256 MiB pool of video memory that is directly mappable.
Even if the resource ends up in system memory, its data may be cached on GPU after first
fetch over PCIe bus.
- For larger resources (e.g. textures), decide between (1) and (2).
You may want to differentiate NVIDIA and AMD, e.g. by looking for memory type that is
both `DEVICE_LOCAL` and `HOST_VISIBLE`. When you find it, use (2), otherwise use (1).
Similarly, for resources that you frequently write on GPU and read on CPU, multiple
solutions are possible:
-# Create one copy in video memory using #VMA_MEMORY_USAGE_GPU_ONLY,
second copy in system memory using #VMA_MEMORY_USAGE_GPU_TO_CPU and submit explicit tranfer each time.
-# Create just single copy using #VMA_MEMORY_USAGE_GPU_TO_CPU, write to it directly on GPU,
map it and read it on CPU.
You should take some measurements to decide which option is faster in case of your specific
resource.
If you don't want to specialize your code for specific types of GPUs, yon can still make
an simple optimization for cases when your resource ends up in mappable memory to use it
directly in this case instead of creating CPU-side staging copy.
For details see [Finding out if memory is mappable](@ref memory_mapping_finding_if_memory_mappable).
\page configuration Configuration
Please check "CONFIGURATION SECTION" in the code to find macros that you can define
before each include of this file or change directly in this file to provide
your own implementation of basic facilities like assert, `min()` and `max()` functions,
mutex, atomic etc.
The library uses its own implementation of containers by default, but you can switch to using
STL containers instead.
\section config_Vulkan_functions Pointers to Vulkan functions
The library uses Vulkan functions straight from the `vulkan.h` header by default.
If you want to provide your own pointers to these functions, e.g. fetched using
`vkGetInstanceProcAddr()` and `vkGetDeviceProcAddr()`:
-# Define `VMA_STATIC_VULKAN_FUNCTIONS 0`.
-# Provide valid pointers through VmaAllocatorCreateInfo::pVulkanFunctions.
\section custom_memory_allocator Custom host memory allocator
If you use custom allocator for CPU memory rather than default operator `new`
and `delete` from C++, you can make this library using your allocator as well
by filling optional member VmaAllocatorCreateInfo::pAllocationCallbacks. These
functions will be passed to Vulkan, as well as used by the library itself to
make any CPU-side allocations.
\section allocation_callbacks Device memory allocation callbacks
The library makes calls to `vkAllocateMemory()` and `vkFreeMemory()` internally.
You can setup callbacks to be informed about these calls, e.g. for the purpose
of gathering some statistics. To do it, fill optional member
VmaAllocatorCreateInfo::pDeviceMemoryCallbacks.
\section heap_memory_limit Device heap memory limit
If you want to test how your program behaves with limited amount of Vulkan device
memory available without switching your graphics card to one that really has
smaller VRAM, you can use a feature of this library intended for this purpose.
To do it, fill optional member VmaAllocatorCreateInfo::pHeapSizeLimit.
\page vk_khr_dedicated_allocation VK_KHR_dedicated_allocation
VK_KHR_dedicated_allocation is a Vulkan extension which can be used to improve
performance on some GPUs. It augments Vulkan API with possibility to query
driver whether it prefers particular buffer or image to have its own, dedicated
allocation (separate `VkDeviceMemory` block) for better efficiency - to be able
to do some internal optimizations.
The extension is supported by this library. It will be used automatically when
enabled. To enable it:
1 . When creating Vulkan device, check if following 2 device extensions are
supported (call `vkEnumerateDeviceExtensionProperties()`).
If yes, enable them (fill `VkDeviceCreateInfo::ppEnabledExtensionNames`).
- VK_KHR_get_memory_requirements2
- VK_KHR_dedicated_allocation
If you enabled these extensions:
2 . Use #VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT flag when creating
your #VmaAllocator`to inform the library that you enabled required extensions
and you want the library to use them.
\code
allocatorInfo.flags |= VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT;
vmaCreateAllocator(&allocatorInfo, &allocator);
\endcode
That's all. The extension will be automatically used whenever you create a
buffer using vmaCreateBuffer() or image using vmaCreateImage().
When using the extension together with Vulkan Validation Layer, you will receive
warnings like this:
vkBindBufferMemory(): Binding memory to buffer 0x33 but vkGetBufferMemoryRequirements() has not been called on that buffer.
It is OK, you should just ignore it. It happens because you use function
`vkGetBufferMemoryRequirements2KHR()` instead of standard
`vkGetBufferMemoryRequirements()`, while the validation layer seems to be
unaware of it.
To learn more about this extension, see:
- [VK_KHR_dedicated_allocation in Vulkan specification](https://www.khronos.org/registry/vulkan/specs/1.0-extensions/html/vkspec.html#VK_KHR_dedicated_allocation)
- [VK_KHR_dedicated_allocation unofficial manual](http://asawicki.info/articles/VK_KHR_dedicated_allocation.php5)
\page general_considerations General considerations
\section general_considerations_thread_safety Thread safety
- The library has no global state, so separate #VmaAllocator objects can be used
independently.
There should be no need to create multiple such objects though - one per `VkDevice` is enough.
- By default, all calls to functions that take #VmaAllocator as first parameter
are safe to call from multiple threads simultaneously because they are
synchronized internally when needed.
- When the allocator is created with #VMA_ALLOCATOR_CREATE_EXTERNALLY_SYNCHRONIZED_BIT
flag, calls to functions that take such #VmaAllocator object must be
synchronized externally.
- Access to a #VmaAllocation object must be externally synchronized. For example,
you must not call vmaGetAllocationInfo() and vmaMapMemory() from different
threads at the same time if you pass the same #VmaAllocation object to these
functions.
\section general_considerations_allocation_algorithm Allocation algorithm
The library uses following algorithm for allocation, in order:
-# Try to find free range of memory in existing blocks.
-# If failed, try to create a new block of `VkDeviceMemory`, with preferred block size.
-# If failed, try to create such block with size/2, size/4, size/8.
-# If failed and #VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT flag was
specified, try to find space in existing blocks, possilby making some other
allocations lost.
-# If failed, try to allocate separate `VkDeviceMemory` for this allocation,
just like when you use #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT.
-# If failed, choose other memory type that meets the requirements specified in
VmaAllocationCreateInfo and go to point 1.
-# If failed, return `VK_ERROR_OUT_OF_DEVICE_MEMORY`.
\section general_considerations_features_not_supported Features not supported
Features deliberately excluded from the scope of this library:
- Data transfer - issuing commands that transfer data between buffers or images, any usage of
`VkCommandList` or `VkCommandQueue` and related synchronization is responsibility of the user.
- Support for any programming languages other than C/C++.
Bindings to other languages are welcomed as external projects.
*/
#include <vulkan/vulkan.h>
/** \struct VmaAllocator
\brief Represents main object of this library initialized.
Fill structure VmaAllocatorCreateInfo and call function vmaCreateAllocator() to create it.
Call function vmaDestroyAllocator() to destroy it.
It is recommended to create just one object of this type per `VkDevice` object,
right after Vulkan is initialized and keep it alive until before Vulkan device is destroyed.
*/
VK_DEFINE_HANDLE(VmaAllocator)
/// Callback function called after successful vkAllocateMemory.
typedef void (VKAPI_PTR *PFN_vmaAllocateDeviceMemoryFunction)(
VmaAllocator allocator,
uint32_t memoryType,
VkDeviceMemory memory,
VkDeviceSize size);
/// Callback function called before vkFreeMemory.
typedef void (VKAPI_PTR *PFN_vmaFreeDeviceMemoryFunction)(
VmaAllocator allocator,
uint32_t memoryType,
VkDeviceMemory memory,
VkDeviceSize size);
/** \brief Set of callbacks that the library will call for `vkAllocateMemory` and `vkFreeMemory`.
Provided for informative purpose, e.g. to gather statistics about number of
allocations or total amount of memory allocated in Vulkan.
Used in VmaAllocatorCreateInfo::pDeviceMemoryCallbacks.
*/
typedef struct VmaDeviceMemoryCallbacks {
/// Optional, can be null.
PFN_vmaAllocateDeviceMemoryFunction pfnAllocate;
/// Optional, can be null.
PFN_vmaFreeDeviceMemoryFunction pfnFree;
} VmaDeviceMemoryCallbacks;
/// Flags for created #VmaAllocator.
typedef enum VmaAllocatorCreateFlagBits {
/** \brief Allocator and all objects created from it will not be synchronized internally, so you must guarantee they are used from only one thread at a time or synchronized externally by you.
Using this flag may increase performance because internal mutexes are not used.
*/
VMA_ALLOCATOR_CREATE_EXTERNALLY_SYNCHRONIZED_BIT = 0x00000001,
/** \brief Enables usage of VK_KHR_dedicated_allocation extension.
Using this extenion will automatically allocate dedicated blocks of memory for
some buffers and images instead of suballocating place for them out of bigger
memory blocks (as if you explicitly used #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT
flag) when it is recommended by the driver. It may improve performance on some
GPUs.
You may set this flag only if you found out that following device extensions are
supported, you enabled them while creating Vulkan device passed as
VmaAllocatorCreateInfo::device, and you want them to be used internally by this
library:
- VK_KHR_get_memory_requirements2
- VK_KHR_dedicated_allocation
When this flag is set, you can experience following warnings reported by Vulkan
validation layer. You can ignore them.
> vkBindBufferMemory(): Binding memory to buffer 0x2d but vkGetBufferMemoryRequirements() has not been called on that buffer.
*/
VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT = 0x00000002,
VMA_ALLOCATOR_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
} VmaAllocatorCreateFlagBits;
typedef VkFlags VmaAllocatorCreateFlags;
/** \brief Pointers to some Vulkan functions - a subset used by the library.
Used in VmaAllocatorCreateInfo::pVulkanFunctions.
*/
typedef struct VmaVulkanFunctions {
PFN_vkGetPhysicalDeviceProperties vkGetPhysicalDeviceProperties;
PFN_vkGetPhysicalDeviceMemoryProperties vkGetPhysicalDeviceMemoryProperties;
PFN_vkAllocateMemory vkAllocateMemory;
PFN_vkFreeMemory vkFreeMemory;
PFN_vkMapMemory vkMapMemory;
PFN_vkUnmapMemory vkUnmapMemory;
PFN_vkBindBufferMemory vkBindBufferMemory;
PFN_vkBindImageMemory vkBindImageMemory;
PFN_vkGetBufferMemoryRequirements vkGetBufferMemoryRequirements;
PFN_vkGetImageMemoryRequirements vkGetImageMemoryRequirements;
PFN_vkCreateBuffer vkCreateBuffer;
PFN_vkDestroyBuffer vkDestroyBuffer;
PFN_vkCreateImage vkCreateImage;
PFN_vkDestroyImage vkDestroyImage;
PFN_vkGetBufferMemoryRequirements2KHR vkGetBufferMemoryRequirements2KHR;
PFN_vkGetImageMemoryRequirements2KHR vkGetImageMemoryRequirements2KHR;
} VmaVulkanFunctions;
/// Description of a Allocator to be created.
typedef struct VmaAllocatorCreateInfo
{
/// Flags for created allocator. Use #VmaAllocatorCreateFlagBits enum.
VmaAllocatorCreateFlags flags;
/// Vulkan physical device.
/** It must be valid throughout whole lifetime of created allocator. */
VkPhysicalDevice physicalDevice;
/// Vulkan device.
/** It must be valid throughout whole lifetime of created allocator. */
VkDevice device;
/// Preferred size of a single `VkDeviceMemory` block to be allocated from large heaps > 1 GiB. Optional.
/** Set to 0 to use default, which is currently 256 MiB. */
VkDeviceSize preferredLargeHeapBlockSize;
/// Custom CPU memory allocation callbacks. Optional.
/** Optional, can be null. When specified, will also be used for all CPU-side memory allocations. */
const VkAllocationCallbacks* pAllocationCallbacks;
/// Informative callbacks for `vkAllocateMemory`, `vkFreeMemory`. Optional.
/** Optional, can be null. */
const VmaDeviceMemoryCallbacks* pDeviceMemoryCallbacks;
/** \brief Maximum number of additional frames that are in use at the same time as current frame.
This value is used only when you make allocations with
VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT flag. Such allocation cannot become
lost if allocation.lastUseFrameIndex >= allocator.currentFrameIndex - frameInUseCount.
For example, if you double-buffer your command buffers, so resources used for
rendering in previous frame may still be in use by the GPU at the moment you
allocate resources needed for the current frame, set this value to 1.
If you want to allow any allocations other than used in the current frame to
become lost, set this value to 0.
*/
uint32_t frameInUseCount;
/** \brief Either null or a pointer to an array of limits on maximum number of bytes that can be allocated out of particular Vulkan memory heap.
If not NULL, it must be a pointer to an array of
`VkPhysicalDeviceMemoryProperties::memoryHeapCount` elements, defining limit on
maximum number of bytes that can be allocated out of particular Vulkan memory
heap.
Any of the elements may be equal to `VK_WHOLE_SIZE`, which means no limit on that
heap. This is also the default in case of `pHeapSizeLimit` = NULL.
If there is a limit defined for a heap:
- If user tries to allocate more memory from that heap using this allocator,
the allocation fails with `VK_ERROR_OUT_OF_DEVICE_MEMORY`.
- If the limit is smaller than heap size reported in `VkMemoryHeap::size`, the
value of this limit will be reported instead when using vmaGetMemoryProperties().
Warning! Using this feature may not be equivalent to installing a GPU with
smaller amount of memory, because graphics driver doesn't necessary fail new
allocations with `VK_ERROR_OUT_OF_DEVICE_MEMORY` result when memory capacity is
exceeded. It may return success and just silently migrate some device memory
blocks to system RAM.
*/
const VkDeviceSize* pHeapSizeLimit;
/** \brief Pointers to Vulkan functions. Can be null if you leave define `VMA_STATIC_VULKAN_FUNCTIONS 1`.
If you leave define `VMA_STATIC_VULKAN_FUNCTIONS 1` in configuration section,
you can pass null as this member, because the library will fetch pointers to
Vulkan functions internally in a static way, like:
vulkanFunctions.vkAllocateMemory = &vkAllocateMemory;
Fill this member if you want to provide your own pointers to Vulkan functions,
e.g. fetched using `vkGetInstanceProcAddr()` and `vkGetDeviceProcAddr()`.
*/
const VmaVulkanFunctions* pVulkanFunctions;
} VmaAllocatorCreateInfo;
/// Creates Allocator object.
VkResult vmaCreateAllocator(
const VmaAllocatorCreateInfo* pCreateInfo,
VmaAllocator* pAllocator);
/// Destroys allocator object.
void vmaDestroyAllocator(
VmaAllocator allocator);
/**
PhysicalDeviceProperties are fetched from physicalDevice by the allocator.
You can access it here, without fetching it again on your own.
*/
void vmaGetPhysicalDeviceProperties(
VmaAllocator allocator,
const VkPhysicalDeviceProperties** ppPhysicalDeviceProperties);
/**
PhysicalDeviceMemoryProperties are fetched from physicalDevice by the allocator.
You can access it here, without fetching it again on your own.
*/
void vmaGetMemoryProperties(
VmaAllocator allocator,
const VkPhysicalDeviceMemoryProperties** ppPhysicalDeviceMemoryProperties);
/**
\brief Given Memory Type Index, returns Property Flags of this memory type.
This is just a convenience function. Same information can be obtained using
vmaGetMemoryProperties().
*/
void vmaGetMemoryTypeProperties(
VmaAllocator allocator,
uint32_t memoryTypeIndex,
VkMemoryPropertyFlags* pFlags);
/** \brief Sets index of the current frame.
This function must be used if you make allocations with
#VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT and
#VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT flags to inform the allocator
when a new frame begins. Allocations queried using vmaGetAllocationInfo() cannot
become lost in the current frame.
*/
void vmaSetCurrentFrameIndex(
VmaAllocator allocator,
uint32_t frameIndex);
/** \brief Calculated statistics of memory usage in entire allocator.
*/
typedef struct VmaStatInfo
{
/// Number of `VkDeviceMemory` Vulkan memory blocks allocated.
uint32_t blockCount;
/// Number of #VmaAllocation allocation objects allocated.
uint32_t allocationCount;
/// Number of free ranges of memory between allocations.
uint32_t unusedRangeCount;
/// Total number of bytes occupied by all allocations.
VkDeviceSize usedBytes;
/// Total number of bytes occupied by unused ranges.
VkDeviceSize unusedBytes;
VkDeviceSize allocationSizeMin, allocationSizeAvg, allocationSizeMax;
VkDeviceSize unusedRangeSizeMin, unusedRangeSizeAvg, unusedRangeSizeMax;
} VmaStatInfo;
/// General statistics from current state of Allocator.
typedef struct VmaStats
{
VmaStatInfo memoryType[VK_MAX_MEMORY_TYPES];
VmaStatInfo memoryHeap[VK_MAX_MEMORY_HEAPS];
VmaStatInfo total;
} VmaStats;
/// Retrieves statistics from current state of the Allocator.
void vmaCalculateStats(
VmaAllocator allocator,
VmaStats* pStats);
#define VMA_STATS_STRING_ENABLED 1
#if VMA_STATS_STRING_ENABLED
/// Builds and returns statistics as string in JSON format.
/** @param[out] ppStatsString Must be freed using vmaFreeStatsString() function.
*/
void vmaBuildStatsString(
VmaAllocator allocator,
char** ppStatsString,
VkBool32 detailedMap);
void vmaFreeStatsString(
VmaAllocator allocator,
char* pStatsString);
#endif // #if VMA_STATS_STRING_ENABLED
/** \struct VmaPool
\brief Represents custom memory pool
Fill structure VmaPoolCreateInfo and call function vmaCreatePool() to create it.
Call function vmaDestroyPool() to destroy it.
For more information see [Custom memory pools](@ref choosing_memory_type_custom_memory_pools).
*/
VK_DEFINE_HANDLE(VmaPool)
typedef enum VmaMemoryUsage
{
/** No intended memory usage specified.
Use other members of VmaAllocationCreateInfo to specify your requirements.
*/
VMA_MEMORY_USAGE_UNKNOWN = 0,
/** Memory will be used on device only, so fast access from the device is preferred.
It usually means device-local GPU (video) memory.
No need to be mappable on host.
It is roughly equivalent of `D3D12_HEAP_TYPE_DEFAULT`.
Usage:
- Resources written and read by device, e.g. images used as attachments.
- Resources transferred from host once (immutable) or infrequently and read by
device multiple times, e.g. textures to be sampled, vertex buffers, uniform
(constant) buffers, and majority of other types of resources used by device.
Allocation may still end up in `HOST_VISIBLE` memory on some implementations.
In such case, you are free to map it.
You can use #VMA_ALLOCATION_CREATE_MAPPED_BIT with this usage type.
*/
VMA_MEMORY_USAGE_GPU_ONLY = 1,
/** Memory will be mappable on host.
It usually means CPU (system) memory.
Resources created in this pool may still be accessible to the device, but access to them can be slower.
Guarantees to be `HOST_VISIBLE` and `HOST_COHERENT`.
CPU read may be uncached.
It is roughly equivalent of `D3D12_HEAP_TYPE_UPLOAD`.
Usage: Staging copy of resources used as transfer source.
*/
VMA_MEMORY_USAGE_CPU_ONLY = 2,
/**
Memory that is both mappable on host (guarantees to be `HOST_VISIBLE`) and preferably fast to access by GPU.
CPU reads may be uncached and very slow.
Usage: Resources written frequently by host (dynamic), read by device. E.g. textures, vertex buffers, uniform buffers updated every frame or every draw call.
*/
VMA_MEMORY_USAGE_CPU_TO_GPU = 3,
/** Memory mappable on host (guarantees to be `HOST_VISIBLE`) and cached.
It is roughly equivalent of `D3D12_HEAP_TYPE_READBACK`.
Usage:
- Resources written by device, read by host - results of some computations, e.g. screen capture, average scene luminance for HDR tone mapping.
- Any resources read or accessed randomly on host, e.g. CPU-side copy of vertex buffer used as source of transfer, but also used for collision detection.
*/
VMA_MEMORY_USAGE_GPU_TO_CPU = 4,
VMA_MEMORY_USAGE_MAX_ENUM = 0x7FFFFFFF
} VmaMemoryUsage;
/// Flags to be passed as VmaAllocationCreateInfo::flags.
typedef enum VmaAllocationCreateFlagBits {
/** \brief Set this flag if the allocation should have its own memory block.
Use it for special, big resources, like fullscreen images used as attachments.
This flag must also be used for host visible resources that you want to map
simultaneously because otherwise they might end up as regions of the same
`VkDeviceMemory`, while mapping same `VkDeviceMemory` multiple times
simultaneously is illegal.
You should not use this flag if VmaAllocationCreateInfo::pool is not null.
*/
VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT = 0x00000001,
/** \brief Set this flag to only try to allocate from existing `VkDeviceMemory` blocks and never create new such block.
If new allocation cannot be placed in any of the existing blocks, allocation
fails with `VK_ERROR_OUT_OF_DEVICE_MEMORY` error.
You should not use #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT and
#VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT at the same time. It makes no sense.
If VmaAllocationCreateInfo::pool is not null, this flag is implied and ignored. */
VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT = 0x00000002,
/** \brief Set this flag to use a memory that will be persistently mapped and retrieve pointer to it.
Pointer to mapped memory will be returned through VmaAllocationInfo::pMappedData.
Is it valid to use this flag for allocation made from memory type that is not
`HOST_VISIBLE`. This flag is then ignored and memory is not mapped. This is
useful if you need an allocation that is efficient to use on GPU
(`DEVICE_LOCAL`) and still want to map it directly if possible on platforms that
support it (e.g. Intel GPU).
You should not use this flag together with #VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT.
*/
VMA_ALLOCATION_CREATE_MAPPED_BIT = 0x00000004,
/** Allocation created with this flag can become lost as a result of another
allocation with #VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT flag, so you
must check it before use.
To check if allocation is not lost, call vmaGetAllocationInfo() and check if
VmaAllocationInfo::deviceMemory is not `VK_NULL_HANDLE`.
For details about supporting lost allocations, see Lost Allocations
chapter of User Guide on Main Page.
You should not use this flag together with #VMA_ALLOCATION_CREATE_MAPPED_BIT.
*/
VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT = 0x00000008,
/** While creating allocation using this flag, other allocations that were
created with flag #VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT can become lost.
For details about supporting lost allocations, see Lost Allocations
chapter of User Guide on Main Page.
*/
VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT = 0x00000010,
/** Set this flag to treat VmaAllocationCreateInfo::pUserData as pointer to a
null-terminated string. Instead of copying pointer value, a local copy of the
string is made and stored in allocation's `pUserData`. The string is automatically
freed together with the allocation. It is also used in vmaBuildStatsString().
*/
VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT = 0x00000020,
VMA_ALLOCATION_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
} VmaAllocationCreateFlagBits;
typedef VkFlags VmaAllocationCreateFlags;
typedef struct VmaAllocationCreateInfo
{
/// Use #VmaAllocationCreateFlagBits enum.
VmaAllocationCreateFlags flags;
/** \brief Intended usage of memory.
You can leave #VMA_MEMORY_USAGE_UNKNOWN if you specify memory requirements in other way. \n
If `pool` is not null, this member is ignored.
*/
VmaMemoryUsage usage;
/** \brief Flags that must be set in a Memory Type chosen for an allocation.
Leave 0 if you specify memory requirements in other way. \n
If `pool` is not null, this member is ignored.*/
VkMemoryPropertyFlags requiredFlags;
/** \brief Flags that preferably should be set in a memory type chosen for an allocation.
Set to 0 if no additional flags are prefered. \n
If `pool` is not null, this member is ignored. */
VkMemoryPropertyFlags preferredFlags;
/** \brief Bitmask containing one bit set for every memory type acceptable for this allocation.
Value 0 is equivalent to `UINT32_MAX` - it means any memory type is accepted if
it meets other requirements specified by this structure, with no further
restrictions on memory type index. \n
If `pool` is not null, this member is ignored.
*/
uint32_t memoryTypeBits;
/** \brief Pool that this allocation should be created in.
Leave `VK_NULL_HANDLE` to allocate from default pool. If not null, members:
`usage`, `requiredFlags`, `preferredFlags`, `memoryTypeBits` are ignored.
*/
VmaPool pool;
/** \brief Custom general-purpose pointer that will be stored in #VmaAllocation, can be read as VmaAllocationInfo::pUserData and changed using vmaSetAllocationUserData().
If #VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT is used, it must be either
null or pointer to a null-terminated string. The string will be then copied to
internal buffer, so it doesn't need to be valid after allocation call.
*/
void* pUserData;
} VmaAllocationCreateInfo;
/**
\brief Helps to find memoryTypeIndex, given memoryTypeBits and VmaAllocationCreateInfo.
This algorithm tries to find a memory type that:
- Is allowed by memoryTypeBits.
- Contains all the flags from pAllocationCreateInfo->requiredFlags.
- Matches intended usage.
- Has as many flags from pAllocationCreateInfo->preferredFlags as possible.
\return Returns VK_ERROR_FEATURE_NOT_PRESENT if not found. Receiving such result
from this function or any other allocating function probably means that your
device doesn't support any memory type with requested features for the specific
type of resource you want to use it for. Please check parameters of your
resource, like image layout (OPTIMAL versus LINEAR) or mip level count.
*/
VkResult vmaFindMemoryTypeIndex(
VmaAllocator allocator,
uint32_t memoryTypeBits,
const VmaAllocationCreateInfo* pAllocationCreateInfo,
uint32_t* pMemoryTypeIndex);
/**
\brief Helps to find memoryTypeIndex, given VkBufferCreateInfo and VmaAllocationCreateInfo.
It can be useful e.g. to determine value to be used as VmaPoolCreateInfo::memoryTypeIndex.
It internally creates a temporary, dummy buffer that never has memory bound.
It is just a convenience function, equivalent to calling:
- `vkCreateBuffer`
- `vkGetBufferMemoryRequirements`
- `vmaFindMemoryTypeIndex`
- `vkDestroyBuffer`
*/
VkResult vmaFindMemoryTypeIndexForBufferInfo(
VmaAllocator allocator,
const VkBufferCreateInfo* pBufferCreateInfo,
const VmaAllocationCreateInfo* pAllocationCreateInfo,
uint32_t* pMemoryTypeIndex);
/**
\brief Helps to find memoryTypeIndex, given VkImageCreateInfo and VmaAllocationCreateInfo.
It can be useful e.g. to determine value to be used as VmaPoolCreateInfo::memoryTypeIndex.
It internally creates a temporary, dummy image that never has memory bound.
It is just a convenience function, equivalent to calling:
- `vkCreateImage`
- `vkGetImageMemoryRequirements`
- `vmaFindMemoryTypeIndex`
- `vkDestroyImage`
*/
VkResult vmaFindMemoryTypeIndexForImageInfo(
VmaAllocator allocator,
const VkImageCreateInfo* pImageCreateInfo,
const VmaAllocationCreateInfo* pAllocationCreateInfo,
uint32_t* pMemoryTypeIndex);
/// Flags to be passed as VmaPoolCreateInfo::flags.
typedef enum VmaPoolCreateFlagBits {
/** \brief Use this flag if you always allocate only buffers and linear images or only optimal images out of this pool and so Buffer-Image Granularity can be ignored.
This is na optional optimization flag.
If you always allocate using vmaCreateBuffer(), vmaCreateImage(),
vmaAllocateMemoryForBuffer(), then you don't need to use it because allocator
knows exact type of your allocations so it can handle Buffer-Image Granularity
in the optimal way.
If you also allocate using vmaAllocateMemoryForImage() or vmaAllocateMemory(),
exact type of such allocations is not known, so allocator must be conservative
in handling Buffer-Image Granularity, which can lead to suboptimal allocation
(wasted memory). In that case, if you can make sure you always allocate only
buffers and linear images or only optimal images out of this pool, use this flag
to make allocator disregard Buffer-Image Granularity and so make allocations
more optimal.
*/
VMA_POOL_CREATE_IGNORE_BUFFER_IMAGE_GRANULARITY_BIT = 0x00000002,
VMA_POOL_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
} VmaPoolCreateFlagBits;
typedef VkFlags VmaPoolCreateFlags;
/** \brief Describes parameter of created #VmaPool.
*/
typedef struct VmaPoolCreateInfo {
/** \brief Vulkan memory type index to allocate this pool from.
*/
uint32_t memoryTypeIndex;
/** \brief Use combination of #VmaPoolCreateFlagBits.
*/
VmaPoolCreateFlags flags;
/** \brief Size of a single `VkDeviceMemory` block to be allocated as part of this pool, in bytes.
Optional. Leave 0 to use default.
*/
VkDeviceSize blockSize;
/** \brief Minimum number of blocks to be always allocated in this pool, even if they stay empty.
Set to 0 to have no preallocated blocks and let the pool be completely empty.
*/
size_t minBlockCount;
/** \brief Maximum number of blocks that can be allocated in this pool. Optional.
Optional. Set to 0 to use `SIZE_MAX`, which means no limit.
Set to same value as minBlockCount to have fixed amount of memory allocated
throuout whole lifetime of this pool.
*/
size_t maxBlockCount;
/** \brief Maximum number of additional frames that are in use at the same time as current frame.
This value is used only when you make allocations with
#VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT flag. Such allocation cannot become
lost if allocation.lastUseFrameIndex >= allocator.currentFrameIndex - frameInUseCount.
For example, if you double-buffer your command buffers, so resources used for
rendering in previous frame may still be in use by the GPU at the moment you
allocate resources needed for the current frame, set this value to 1.
If you want to allow any allocations other than used in the current frame to
become lost, set this value to 0.
*/
uint32_t frameInUseCount;
} VmaPoolCreateInfo;
/** \brief Describes parameter of existing #VmaPool.
*/
typedef struct VmaPoolStats {
/** \brief Total amount of `VkDeviceMemory` allocated from Vulkan for this pool, in bytes.
*/
VkDeviceSize size;
/** \brief Total number of bytes in the pool not used by any #VmaAllocation.
*/
VkDeviceSize unusedSize;
/** \brief Number of #VmaAllocation objects created from this pool that were not destroyed or lost.
*/
size_t allocationCount;
/** \brief Number of continuous memory ranges in the pool not used by any #VmaAllocation.
*/
size_t unusedRangeCount;
/** \brief Size of the largest continuous free memory region.
Making a new allocation of that size is not guaranteed to succeed because of
possible additional margin required to respect alignment and buffer/image
granularity.
*/
VkDeviceSize unusedRangeSizeMax;
} VmaPoolStats;
/** \brief Allocates Vulkan device memory and creates #VmaPool object.
@param allocator Allocator object.
@param pCreateInfo Parameters of pool to create.
@param[out] pPool Handle to created pool.
*/
VkResult vmaCreatePool(
VmaAllocator allocator,
const VmaPoolCreateInfo* pCreateInfo,
VmaPool* pPool);
/** \brief Destroys #VmaPool object and frees Vulkan device memory.
*/
void vmaDestroyPool(
VmaAllocator allocator,
VmaPool pool);
/** \brief Retrieves statistics of existing #VmaPool object.
@param allocator Allocator object.
@param pool Pool object.
@param[out] pPoolStats Statistics of specified pool.
*/
void vmaGetPoolStats(
VmaAllocator allocator,
VmaPool pool,
VmaPoolStats* pPoolStats);
/** \brief Marks all allocations in given pool as lost if they are not used in current frame or VmaPoolCreateInfo::frameInUseCount back from now.
@param allocator Allocator object.
@param pool Pool.
@param[out] pLostAllocationCount Number of allocations marked as lost. Optional - pass null if you don't need this information.
*/
void vmaMakePoolAllocationsLost(
VmaAllocator allocator,
VmaPool pool,
size_t* pLostAllocationCount);
/** \struct VmaAllocation
\brief Represents single memory allocation.
It may be either dedicated block of `VkDeviceMemory` or a specific region of a bigger block of this type
plus unique offset.
There are multiple ways to create such object.
You need to fill structure VmaAllocationCreateInfo.
For more information see [Choosing memory type](@ref choosing_memory_type).
Although the library provides convenience functions that create Vulkan buffer or image,
allocate memory for it and bind them together,
binding of the allocation to a buffer or an image is out of scope of the allocation itself.
Allocation object can exist without buffer/image bound,
binding can be done manually by the user, and destruction of it can be done
independently of destruction of the allocation.
The object also remembers its size and some other information.
To retrieve this information, use function vmaGetAllocationInfo() and inspect
returned structure VmaAllocationInfo.
Some kinds allocations can be in lost state.
For more information, see [Lost allocations](@ref lost_allocations).
*/
VK_DEFINE_HANDLE(VmaAllocation)
/** \brief Parameters of #VmaAllocation objects, that can be retrieved using function vmaGetAllocationInfo().
*/
typedef struct VmaAllocationInfo {
/** \brief Memory type index that this allocation was allocated from.
It never changes.
*/
uint32_t memoryType;
/** \brief Handle to Vulkan memory object.
Same memory object can be shared by multiple allocations.
It can change after call to vmaDefragment() if this allocation is passed to the function, or if allocation is lost.
If the allocation is lost, it is equal to `VK_NULL_HANDLE`.
*/
VkDeviceMemory deviceMemory;
/** \brief Offset into deviceMemory object to the beginning of this allocation, in bytes. (deviceMemory, offset) pair is unique to this allocation.
It can change after call to vmaDefragment() if this allocation is passed to the function, or if allocation is lost.
*/
VkDeviceSize offset;
/** \brief Size of this allocation, in bytes.
It never changes, unless allocation is lost.
*/
VkDeviceSize size;
/** \brief Pointer to the beginning of this allocation as mapped data.
If the allocation hasn't been mapped using vmaMapMemory() and hasn't been
created with #VMA_ALLOCATION_CREATE_MAPPED_BIT flag, this value null.
It can change after call to vmaMapMemory(), vmaUnmapMemory().
It can also change after call to vmaDefragment() if this allocation is passed to the function.
*/
void* pMappedData;
/** \brief Custom general-purpose pointer that was passed as VmaAllocationCreateInfo::pUserData or set using vmaSetAllocationUserData().
It can change after call to vmaSetAllocationUserData() for this allocation.
*/
void* pUserData;
} VmaAllocationInfo;
/** \brief General purpose memory allocation.
@param[out] pAllocation Handle to allocated memory.
@param[out] pAllocationInfo Optional. Information about allocated memory. It can be later fetched using function vmaGetAllocationInfo().
You should free the memory using vmaFreeMemory().
It is recommended to use vmaAllocateMemoryForBuffer(), vmaAllocateMemoryForImage(),
vmaCreateBuffer(), vmaCreateImage() instead whenever possible.
*/
VkResult vmaAllocateMemory(
VmaAllocator allocator,
const VkMemoryRequirements* pVkMemoryRequirements,
const VmaAllocationCreateInfo* pCreateInfo,
VmaAllocation* pAllocation,
VmaAllocationInfo* pAllocationInfo);
/**
@param[out] pAllocation Handle to allocated memory.
@param[out] pAllocationInfo Optional. Information about allocated memory. It can be later fetched using function vmaGetAllocationInfo().
You should free the memory using vmaFreeMemory().
*/
VkResult vmaAllocateMemoryForBuffer(
VmaAllocator allocator,
VkBuffer buffer,
const VmaAllocationCreateInfo* pCreateInfo,
VmaAllocation* pAllocation,
VmaAllocationInfo* pAllocationInfo);
/// Function similar to vmaAllocateMemoryForBuffer().
VkResult vmaAllocateMemoryForImage(
VmaAllocator allocator,
VkImage image,
const VmaAllocationCreateInfo* pCreateInfo,
VmaAllocation* pAllocation,
VmaAllocationInfo* pAllocationInfo);
/// Frees memory previously allocated using vmaAllocateMemory(), vmaAllocateMemoryForBuffer(), or vmaAllocateMemoryForImage().
void vmaFreeMemory(
VmaAllocator allocator,
VmaAllocation allocation);
/** \brief Returns current information about specified allocation and atomically marks it as used in current frame.
Current paramters of given allocation are returned in `pAllocationInfo`.
This function also atomically "touches" allocation - marks it as used in current frame,
just like vmaTouchAllocation().
If the allocation is in lost state, `pAllocationInfo->deviceMemory == VK_NULL_HANDLE`.
Although this function uses atomics and doesn't lock any mutex, so it should be quite efficient,
you can avoid calling it too often.
- You can retrieve same VmaAllocationInfo structure while creating your resource, from function
vmaCreateBuffer(), vmaCreateImage(). You can remember it if you are sure parameters don't change
(e.g. due to defragmentation or allocation becoming lost).
- If you just want to check if allocation is not lost, vmaTouchAllocation() will work faster.
*/
void vmaGetAllocationInfo(
VmaAllocator allocator,
VmaAllocation allocation,
VmaAllocationInfo* pAllocationInfo);
/** \brief Returns `VK_TRUE` if allocation is not lost and atomically marks it as used in current frame.
If the allocation has been created with #VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT flag,
this function returns `VK_TRUE` if it's not in lost state, so it can still be used.
It then also atomically "touches" the allocation - marks it as used in current frame,
so that you can be sure it won't become lost in current frame or next `frameInUseCount` frames.
If the allocation is in lost state, the function returns `VK_FALSE`.
Memory of such allocation, as well as buffer or image bound to it, should not be used.
Lost allocation and the buffer/image still need to be destroyed.
If the allocation has been created without #VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT flag,
this function always returns `VK_TRUE`.
*/
VkBool32 vmaTouchAllocation(
VmaAllocator allocator,
VmaAllocation allocation);
/** \brief Sets pUserData in given allocation to new value.
If the allocation was created with VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT,
pUserData must be either null, or pointer to a null-terminated string. The function
makes local copy of the string and sets it as allocation's `pUserData`. String
passed as pUserData doesn't need to be valid for whole lifetime of the allocation -
you can free it after this call. String previously pointed by allocation's
pUserData is freed from memory.
If the flag was not used, the value of pointer `pUserData` is just copied to
allocation's `pUserData`. It is opaque, so you can use it however you want - e.g.
as a pointer, ordinal number or some handle to you own data.
*/
void vmaSetAllocationUserData(
VmaAllocator allocator,
VmaAllocation allocation,
void* pUserData);
/** \brief Creates new allocation that is in lost state from the beginning.
It can be useful if you need a dummy, non-null allocation.
You still need to destroy created object using vmaFreeMemory().
Returned allocation is not tied to any specific memory pool or memory type and
not bound to any image or buffer. It has size = 0. It cannot be turned into
a real, non-empty allocation.
*/
void vmaCreateLostAllocation(
VmaAllocator allocator,
VmaAllocation* pAllocation);
/** \brief Maps memory represented by given allocation and returns pointer to it.
Maps memory represented by given allocation to make it accessible to CPU code.
When succeeded, `*ppData` contains pointer to first byte of this memory.
If the allocation is part of bigger `VkDeviceMemory` block, the pointer is
correctly offseted to the beginning of region assigned to this particular
allocation.
Mapping is internally reference-counted and synchronized, so despite raw Vulkan
function `vkMapMemory()` cannot be used to map same block of `VkDeviceMemory`
multiple times simultaneously, it is safe to call this function on allocations
assigned to the same memory block. Actual Vulkan memory will be mapped on first
mapping and unmapped on last unmapping.
If the function succeeded, you must call vmaUnmapMemory() to unmap the
allocation when mapping is no longer needed or before freeing the allocation, at
the latest.
It also safe to call this function multiple times on the same allocation. You
must call vmaUnmapMemory() same number of times as you called vmaMapMemory().
It is also safe to call this function on allocation created with
#VMA_ALLOCATION_CREATE_MAPPED_BIT flag. Its memory stays mapped all the time.
You must still call vmaUnmapMemory() same number of times as you called
vmaMapMemory(). You must not call vmaUnmapMemory() additional time to free the
"0-th" mapping made automatically due to #VMA_ALLOCATION_CREATE_MAPPED_BIT flag.
This function fails when used on allocation made in memory type that is not
`HOST_VISIBLE`.
This function always fails when called for allocation that was created with
#VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT flag. Such allocations cannot be
mapped.
*/
VkResult vmaMapMemory(
VmaAllocator allocator,
VmaAllocation allocation,
void** ppData);
/** \brief Unmaps memory represented by given allocation, mapped previously using vmaMapMemory().
For details, see description of vmaMapMemory().
*/
void vmaUnmapMemory(
VmaAllocator allocator,
VmaAllocation allocation);
/** \brief Optional configuration parameters to be passed to function vmaDefragment(). */
typedef struct VmaDefragmentationInfo {
/** \brief Maximum total numbers of bytes that can be copied while moving allocations to different places.
Default is `VK_WHOLE_SIZE`, which means no limit.
*/
VkDeviceSize maxBytesToMove;
/** \brief Maximum number of allocations that can be moved to different place.
Default is `UINT32_MAX`, which means no limit.
*/
uint32_t maxAllocationsToMove;
} VmaDefragmentationInfo;
/** \brief Statistics returned by function vmaDefragment(). */
typedef struct VmaDefragmentationStats {
/// Total number of bytes that have been copied while moving allocations to different places.
VkDeviceSize bytesMoved;
/// Total number of bytes that have been released to the system by freeing empty `VkDeviceMemory` objects.
VkDeviceSize bytesFreed;
/// Number of allocations that have been moved to different places.
uint32_t allocationsMoved;
/// Number of empty `VkDeviceMemory` objects that have been released to the system.
uint32_t deviceMemoryBlocksFreed;
} VmaDefragmentationStats;
/** \brief Compacts memory by moving allocations.
@param pAllocations Array of allocations that can be moved during this compation.
@param allocationCount Number of elements in pAllocations and pAllocationsChanged arrays.
@param[out] pAllocationsChanged Array of boolean values that will indicate whether matching allocation in pAllocations array has been moved. This parameter is optional. Pass null if you don't need this information.
@param pDefragmentationInfo Configuration parameters. Optional - pass null to use default values.
@param[out] pDefragmentationStats Statistics returned by the function. Optional - pass null if you don't need this information.
@return VK_SUCCESS if completed, VK_INCOMPLETE if succeeded but didn't make all possible optimizations because limits specified in pDefragmentationInfo have been reached, negative error code in case of error.
This function works by moving allocations to different places (different
`VkDeviceMemory` objects and/or different offsets) in order to optimize memory
usage. Only allocations that are in pAllocations array can be moved. All other
allocations are considered nonmovable in this call. Basic rules:
- Only allocations made in memory types that have
`VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT` flag can be compacted. You may pass other
allocations but it makes no sense - these will never be moved.
- You may pass allocations made with #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT but
it makes no sense - they will never be moved.
- Both allocations made with or without #VMA_ALLOCATION_CREATE_MAPPED_BIT
flag can be compacted. If not persistently mapped, memory will be mapped
temporarily inside this function if needed.
- You must not pass same #VmaAllocation object multiple times in pAllocations array.
The function also frees empty `VkDeviceMemory` blocks.
After allocation has been moved, its VmaAllocationInfo::deviceMemory and/or
VmaAllocationInfo::offset changes. You must query them again using
vmaGetAllocationInfo() if you need them.
If an allocation has been moved, data in memory is copied to new place
automatically, but if it was bound to a buffer or an image, you must destroy
that object yourself, create new one and bind it to the new memory pointed by
the allocation. You must use `vkDestroyBuffer()`, `vkDestroyImage()`,
`vkCreateBuffer()`, `vkCreateImage()` for that purpose and NOT vmaDestroyBuffer(),
vmaDestroyImage(), vmaCreateBuffer(), vmaCreateImage()! Example:
\code
VkDevice device = ...;
VmaAllocator allocator = ...;
std::vector<VkBuffer> buffers = ...;
std::vector<VmaAllocation> allocations = ...;
std::vector<VkBool32> allocationsChanged(allocations.size());
vmaDefragment(allocator, allocations.data(), allocations.size(), allocationsChanged.data(), nullptr, nullptr);
for(size_t i = 0; i < allocations.size(); ++i)
{
if(allocationsChanged[i])
{
VmaAllocationInfo allocInfo;
vmaGetAllocationInfo(allocator, allocations[i], &allocInfo);
vkDestroyBuffer(device, buffers[i], nullptr);
VkBufferCreateInfo bufferInfo = ...;
vkCreateBuffer(device, &bufferInfo, nullptr, &buffers[i]);
// You can make dummy call to vkGetBufferMemoryRequirements here to silence validation layer warning.
vkBindBufferMemory(device, buffers[i], allocInfo.deviceMemory, allocInfo.offset);
}
}
\endcode
Note: Please don't expect memory to be fully compacted after this call.
Algorithms inside are based on some heuristics that try to maximize number of Vulkan
memory blocks to make totally empty to release them, as well as to maximimze continuous
empty space inside remaining blocks, while minimizing the number and size of data that
needs to be moved. Some fragmentation still remains after this call. This is normal.
Warning: This function is not 100% correct according to Vulkan specification. Use it
at your own risk. That's because Vulkan doesn't guarantee that memory
requirements (size and alignment) for a new buffer or image are consistent. They
may be different even for subsequent calls with the same parameters. It really
does happen on some platforms, especially with images.
Warning: This function may be time-consuming, so you shouldn't call it too often
(like every frame or after every resource creation/destruction).
You can call it on special occasions (like when reloading a game level or
when you just destroyed a lot of objects).
*/
VkResult vmaDefragment(
VmaAllocator allocator,
VmaAllocation* pAllocations,
size_t allocationCount,
VkBool32* pAllocationsChanged,
const VmaDefragmentationInfo *pDefragmentationInfo,
VmaDefragmentationStats* pDefragmentationStats);
/** \brief Binds buffer to allocation.
Binds specified buffer to region of memory represented by specified allocation.
Gets `VkDeviceMemory` handle and offset from the allocation.
If you want to create a buffer, allocate memory for it and bind them together separately,
you should use this function for binding instead of standard `vkBindBufferMemory()`,
because it ensures proper synchronization so that when a `VkDeviceMemory` object is used by multiple
allocations, calls to `vkBind*Memory()` or `vkMapMemory()` won't happen from multiple threads simultaneously
(which is illegal in Vulkan).
It is recommended to use function vmaCreateBuffer() instead of this one.
*/
VkResult vmaBindBufferMemory(
VmaAllocator allocator,
VmaAllocation allocation,
VkBuffer buffer);
/** \brief Binds image to allocation.
Binds specified image to region of memory represented by specified allocation.
Gets `VkDeviceMemory` handle and offset from the allocation.
If you want to create an image, allocate memory for it and bind them together separately,
you should use this function for binding instead of standard `vkBindImageMemory()`,
because it ensures proper synchronization so that when a `VkDeviceMemory` object is used by multiple
allocations, calls to `vkBind*Memory()` or `vkMapMemory()` won't happen from multiple threads simultaneously
(which is illegal in Vulkan).
It is recommended to use function vmaCreateImage() instead of this one.
*/
VkResult vmaBindImageMemory(
VmaAllocator allocator,
VmaAllocation allocation,
VkImage image);
/**
@param[out] pBuffer Buffer that was created.
@param[out] pAllocation Allocation that was created.
@param[out] pAllocationInfo Optional. Information about allocated memory. It can be later fetched using function vmaGetAllocationInfo().
This function automatically:
-# Creates buffer.
-# Allocates appropriate memory for it.
-# Binds the buffer with the memory.
If any of these operations fail, buffer and allocation are not created,
returned value is negative error code, *pBuffer and *pAllocation are null.
If the function succeeded, you must destroy both buffer and allocation when you
no longer need them using either convenience function vmaDestroyBuffer() or
separately, using `vkDestroyBuffer()` and vmaFreeMemory().
If VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT flag was used,
VK_KHR_dedicated_allocation extension is used internally to query driver whether
it requires or prefers the new buffer to have dedicated allocation. If yes,
and if dedicated allocation is possible (VmaAllocationCreateInfo::pool is null
and VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT is not used), it creates dedicated
allocation for this buffer, just like when using
VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT.
*/
VkResult vmaCreateBuffer(
VmaAllocator allocator,
const VkBufferCreateInfo* pBufferCreateInfo,
const VmaAllocationCreateInfo* pAllocationCreateInfo,
VkBuffer* pBuffer,
VmaAllocation* pAllocation,
VmaAllocationInfo* pAllocationInfo);
/** \brief Destroys Vulkan buffer and frees allocated memory.
This is just a convenience function equivalent to:
\code
vkDestroyBuffer(device, buffer, allocationCallbacks);
vmaFreeMemory(allocator, allocation);
\endcode
It it safe to pass null as buffer and/or allocation.
*/
void vmaDestroyBuffer(
VmaAllocator allocator,
VkBuffer buffer,
VmaAllocation allocation);
/// Function similar to vmaCreateBuffer().
VkResult vmaCreateImage(
VmaAllocator allocator,
const VkImageCreateInfo* pImageCreateInfo,
const VmaAllocationCreateInfo* pAllocationCreateInfo,
VkImage* pImage,
VmaAllocation* pAllocation,
VmaAllocationInfo* pAllocationInfo);
/** \brief Destroys Vulkan image and frees allocated memory.
This is just a convenience function equivalent to:
\code
vkDestroyImage(device, image, allocationCallbacks);
vmaFreeMemory(allocator, allocation);
\endcode
It it safe to pass null as image and/or allocation.
*/
void vmaDestroyImage(
VmaAllocator allocator,
VkImage image,
VmaAllocation allocation);
#ifdef __cplusplus
}
#endif
#endif // AMD_VULKAN_MEMORY_ALLOCATOR_H
// For Visual Studio IntelliSense.
#ifdef __INTELLISENSE__
#define VMA_IMPLEMENTATION
#endif
#ifdef VMA_IMPLEMENTATION
#undef VMA_IMPLEMENTATION
#include <cstdint>
#include <cstdlib>
#include <cstring>
/*******************************************************************************
CONFIGURATION SECTION
Define some of these macros before each #include of this header or change them
here if you need other then default behavior depending on your environment.
*/
/*
Define this macro to 1 to make the library fetch pointers to Vulkan functions
internally, like:
vulkanFunctions.vkAllocateMemory = &vkAllocateMemory;
Define to 0 if you are going to provide you own pointers to Vulkan functions via
VmaAllocatorCreateInfo::pVulkanFunctions.
*/
#if !defined(VMA_STATIC_VULKAN_FUNCTIONS) && !defined(VK_NO_PROTOTYPES)
#define VMA_STATIC_VULKAN_FUNCTIONS 1
#endif
// Define this macro to 1 to make the library use STL containers instead of its own implementation.
//#define VMA_USE_STL_CONTAINERS 1
/* Set this macro to 1 to make the library including and using STL containers:
std::pair, std::vector, std::list, std::unordered_map.
Set it to 0 or undefined to make the library using its own implementation of
the containers.
*/
#if VMA_USE_STL_CONTAINERS
#define VMA_USE_STL_VECTOR 1
#define VMA_USE_STL_UNORDERED_MAP 1
#define VMA_USE_STL_LIST 1
#endif
#if VMA_USE_STL_VECTOR
#include <vector>
#endif
#if VMA_USE_STL_UNORDERED_MAP
#include <unordered_map>
#endif
#if VMA_USE_STL_LIST
#include <list>
#endif
/*
Following headers are used in this CONFIGURATION section only, so feel free to
remove them if not needed.
*/
#include <cassert> // for assert
#include <algorithm> // for min, max
#include <mutex> // for std::mutex
#include <atomic> // for std::atomic
#if !defined(_WIN32) && !defined(__APPLE__)
#include <malloc.h> // for aligned_alloc()
#endif
#ifndef VMA_NULL
// Value used as null pointer. Define it to e.g.: nullptr, NULL, 0, (void*)0.
#define VMA_NULL nullptr
#endif
#if defined(__APPLE__) || defined(__ANDROID__)
#include <cstdlib>
void *aligned_alloc(size_t alignment, size_t size)
{
// alignment must be >= sizeof(void*)
if(alignment < sizeof(void*))
{
alignment = sizeof(void*);
}
void *pointer;
if(posix_memalign(&pointer, alignment, size) == 0)
return pointer;
return VMA_NULL;
}
#endif
// Normal assert to check for programmer's errors, especially in Debug configuration.
#ifndef VMA_ASSERT
#ifdef _DEBUG
#define VMA_ASSERT(expr) assert(expr)
#else
#define VMA_ASSERT(expr)
#endif
#endif
// Assert that will be called very often, like inside data structures e.g. operator[].
// Making it non-empty can make program slow.
#ifndef VMA_HEAVY_ASSERT
#ifdef _DEBUG
#define VMA_HEAVY_ASSERT(expr) //VMA_ASSERT(expr)
#else
#define VMA_HEAVY_ASSERT(expr)
#endif
#endif
#ifndef VMA_ALIGN_OF
#define VMA_ALIGN_OF(type) (__alignof(type))
#endif
#ifndef VMA_SYSTEM_ALIGNED_MALLOC
#if defined(_WIN32)
#define VMA_SYSTEM_ALIGNED_MALLOC(size, alignment) (_aligned_malloc((size), (alignment)))
#else
#define VMA_SYSTEM_ALIGNED_MALLOC(size, alignment) (aligned_alloc((alignment), (size) ))
#endif
#endif
#ifndef VMA_SYSTEM_FREE
#if defined(_WIN32)
#define VMA_SYSTEM_FREE(ptr) _aligned_free(ptr)
#else
#define VMA_SYSTEM_FREE(ptr) free(ptr)
#endif
#endif
#ifndef VMA_MIN
#define VMA_MIN(v1, v2) (std::min((v1), (v2)))
#endif
#ifndef VMA_MAX
#define VMA_MAX(v1, v2) (std::max((v1), (v2)))
#endif
#ifndef VMA_SWAP
#define VMA_SWAP(v1, v2) std::swap((v1), (v2))
#endif
#ifndef VMA_SORT
#define VMA_SORT(beg, end, cmp) std::sort(beg, end, cmp)
#endif
#ifndef VMA_DEBUG_LOG
#define VMA_DEBUG_LOG(format, ...)
/*
#define VMA_DEBUG_LOG(format, ...) do { \
printf(format, __VA_ARGS__); \
printf("\n"); \
} while(false)
*/
#endif
// Define this macro to 1 to enable functions: vmaBuildStatsString, vmaFreeStatsString.
#if VMA_STATS_STRING_ENABLED
static inline void VmaUint32ToStr(char* outStr, size_t strLen, uint32_t num)
{
snprintf(outStr, strLen, "%u", static_cast<unsigned int>(num));
}
static inline void VmaUint64ToStr(char* outStr, size_t strLen, uint64_t num)
{
snprintf(outStr, strLen, "%llu", static_cast<unsigned long long>(num));
}
static inline void VmaPtrToStr(char* outStr, size_t strLen, const void* ptr)
{
snprintf(outStr, strLen, "%p", ptr);
}
#endif
#ifndef VMA_MUTEX
class VmaMutex
{
public:
VmaMutex() { }
~VmaMutex() { }
void Lock() { m_Mutex.lock(); }
void Unlock() { m_Mutex.unlock(); }
private:
std::mutex m_Mutex;
};
#define VMA_MUTEX VmaMutex
#endif
/*
If providing your own implementation, you need to implement a subset of std::atomic:
- Constructor(uint32_t desired)
- uint32_t load() const
- void store(uint32_t desired)
- bool compare_exchange_weak(uint32_t& expected, uint32_t desired)
*/
#ifndef VMA_ATOMIC_UINT32
#define VMA_ATOMIC_UINT32 std::atomic<uint32_t>
#endif
#ifndef VMA_BEST_FIT
/**
Main parameter for function assessing how good is a free suballocation for a new
allocation request.
- Set to 1 to use Best-Fit algorithm - prefer smaller blocks, as close to the
size of requested allocations as possible.
- Set to 0 to use Worst-Fit algorithm - prefer larger blocks, as large as
possible.
Experiments in special testing environment showed that Best-Fit algorithm is
better.
*/
#define VMA_BEST_FIT (1)
#endif
#ifndef VMA_DEBUG_ALWAYS_DEDICATED_MEMORY
/**
Every allocation will have its own memory block.
Define to 1 for debugging purposes only.
*/
#define VMA_DEBUG_ALWAYS_DEDICATED_MEMORY (0)
#endif
#ifndef VMA_DEBUG_ALIGNMENT
/**
Minimum alignment of all suballocations, in bytes.
Set to more than 1 for debugging purposes only. Must be power of two.
*/
#define VMA_DEBUG_ALIGNMENT (1)
#endif
#ifndef VMA_DEBUG_MARGIN
/**
Minimum margin between suballocations, in bytes.
Set nonzero for debugging purposes only.
*/
#define VMA_DEBUG_MARGIN (0)
#endif
#ifndef VMA_DEBUG_GLOBAL_MUTEX
/**
Set this to 1 for debugging purposes only, to enable single mutex protecting all
entry calls to the library. Can be useful for debugging multithreading issues.
*/
#define VMA_DEBUG_GLOBAL_MUTEX (0)
#endif
#ifndef VMA_DEBUG_MIN_BUFFER_IMAGE_GRANULARITY
/**
Minimum value for VkPhysicalDeviceLimits::bufferImageGranularity.
Set to more than 1 for debugging purposes only. Must be power of two.
*/
#define VMA_DEBUG_MIN_BUFFER_IMAGE_GRANULARITY (1)
#endif
#ifndef VMA_SMALL_HEAP_MAX_SIZE
/// Maximum size of a memory heap in Vulkan to consider it "small".
#define VMA_SMALL_HEAP_MAX_SIZE (1024ull * 1024 * 1024)
#endif
#ifndef VMA_DEFAULT_LARGE_HEAP_BLOCK_SIZE
/// Default size of a block allocated as single VkDeviceMemory from a "large" heap.
#define VMA_DEFAULT_LARGE_HEAP_BLOCK_SIZE (256ull * 1024 * 1024)
#endif
static const uint32_t VMA_FRAME_INDEX_LOST = UINT32_MAX;
/*******************************************************************************
END OF CONFIGURATION
*/
static VkAllocationCallbacks VmaEmptyAllocationCallbacks = {
VMA_NULL, VMA_NULL, VMA_NULL, VMA_NULL, VMA_NULL, VMA_NULL };
// Returns number of bits set to 1 in (v).
static inline uint32_t VmaCountBitsSet(uint32_t v)
{
uint32_t c = v - ((v >> 1) & 0x55555555);
c = ((c >> 2) & 0x33333333) + (c & 0x33333333);
c = ((c >> 4) + c) & 0x0F0F0F0F;
c = ((c >> 8) + c) & 0x00FF00FF;
c = ((c >> 16) + c) & 0x0000FFFF;
return c;
}
// Aligns given value up to nearest multiply of align value. For example: VmaAlignUp(11, 8) = 16.
// Use types like uint32_t, uint64_t as T.
template <typename T>
static inline T VmaAlignUp(T val, T align)
{
return (val + align - 1) / align * align;
}
// Division with mathematical rounding to nearest number.
template <typename T>
inline T VmaRoundDiv(T x, T y)
{
return (x + (y / (T)2)) / y;
}
#ifndef VMA_SORT
template<typename Iterator, typename Compare>
Iterator VmaQuickSortPartition(Iterator beg, Iterator end, Compare cmp)
{
Iterator centerValue = end; --centerValue;
Iterator insertIndex = beg;
for(Iterator memTypeIndex = beg; memTypeIndex < centerValue; ++memTypeIndex)
{
if(cmp(*memTypeIndex, *centerValue))
{
if(insertIndex != memTypeIndex)
{
VMA_SWAP(*memTypeIndex, *insertIndex);
}
++insertIndex;
}
}
if(insertIndex != centerValue)
{
VMA_SWAP(*insertIndex, *centerValue);
}
return insertIndex;
}
template<typename Iterator, typename Compare>
void VmaQuickSort(Iterator beg, Iterator end, Compare cmp)
{
if(beg < end)
{
Iterator it = VmaQuickSortPartition<Iterator, Compare>(beg, end, cmp);
VmaQuickSort<Iterator, Compare>(beg, it, cmp);
VmaQuickSort<Iterator, Compare>(it + 1, end, cmp);
}
}
#define VMA_SORT(beg, end, cmp) VmaQuickSort(beg, end, cmp)
#endif // #ifndef VMA_SORT
/*
Returns true if two memory blocks occupy overlapping pages.
ResourceA must be in less memory offset than ResourceB.
Algorithm is based on "Vulkan 1.0.39 - A Specification (with all registered Vulkan extensions)"
chapter 11.6 "Resource Memory Association", paragraph "Buffer-Image Granularity".
*/
static inline bool VmaBlocksOnSamePage(
VkDeviceSize resourceAOffset,
VkDeviceSize resourceASize,
VkDeviceSize resourceBOffset,
VkDeviceSize pageSize)
{
VMA_ASSERT(resourceAOffset + resourceASize <= resourceBOffset && resourceASize > 0 && pageSize > 0);
VkDeviceSize resourceAEnd = resourceAOffset + resourceASize - 1;
VkDeviceSize resourceAEndPage = resourceAEnd & ~(pageSize - 1);
VkDeviceSize resourceBStart = resourceBOffset;
VkDeviceSize resourceBStartPage = resourceBStart & ~(pageSize - 1);
return resourceAEndPage == resourceBStartPage;
}
enum VmaSuballocationType
{
VMA_SUBALLOCATION_TYPE_FREE = 0,
VMA_SUBALLOCATION_TYPE_UNKNOWN = 1,
VMA_SUBALLOCATION_TYPE_BUFFER = 2,
VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN = 3,
VMA_SUBALLOCATION_TYPE_IMAGE_LINEAR = 4,
VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL = 5,
VMA_SUBALLOCATION_TYPE_MAX_ENUM = 0x7FFFFFFF
};
/*
Returns true if given suballocation types could conflict and must respect
VkPhysicalDeviceLimits::bufferImageGranularity. They conflict if one is buffer
or linear image and another one is optimal image. If type is unknown, behave
conservatively.
*/
static inline bool VmaIsBufferImageGranularityConflict(
VmaSuballocationType suballocType1,
VmaSuballocationType suballocType2)
{
if(suballocType1 > suballocType2)
{
VMA_SWAP(suballocType1, suballocType2);
}
switch(suballocType1)
{
case VMA_SUBALLOCATION_TYPE_FREE:
return false;
case VMA_SUBALLOCATION_TYPE_UNKNOWN:
return true;
case VMA_SUBALLOCATION_TYPE_BUFFER:
return
suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN ||
suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL;
case VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN:
return
suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN ||
suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_LINEAR ||
suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL;
case VMA_SUBALLOCATION_TYPE_IMAGE_LINEAR:
return
suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL;
case VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL:
return false;
default:
VMA_ASSERT(0);
return true;
}
}
// Helper RAII class to lock a mutex in constructor and unlock it in destructor (at the end of scope).
struct VmaMutexLock
{
public:
VmaMutexLock(VMA_MUTEX& mutex, bool useMutex) :
m_pMutex(useMutex ? &mutex : VMA_NULL)
{
if(m_pMutex)
{
m_pMutex->Lock();
}
}
~VmaMutexLock()
{
if(m_pMutex)
{
m_pMutex->Unlock();
}
}
private:
VMA_MUTEX* m_pMutex;
};
#if VMA_DEBUG_GLOBAL_MUTEX
static VMA_MUTEX gDebugGlobalMutex;
#define VMA_DEBUG_GLOBAL_MUTEX_LOCK VmaMutexLock debugGlobalMutexLock(gDebugGlobalMutex, true);
#else
#define VMA_DEBUG_GLOBAL_MUTEX_LOCK
#endif
// Minimum size of a free suballocation to register it in the free suballocation collection.
static const VkDeviceSize VMA_MIN_FREE_SUBALLOCATION_SIZE_TO_REGISTER = 16;
/*
Performs binary search and returns iterator to first element that is greater or
equal to (key), according to comparison (cmp).
Cmp should return true if first argument is less than second argument.
Returned value is the found element, if present in the collection or place where
new element with value (key) should be inserted.
*/
template <typename IterT, typename KeyT, typename CmpT>
static IterT VmaBinaryFindFirstNotLess(IterT beg, IterT end, const KeyT &key, CmpT cmp)
{
size_t down = 0, up = (end - beg);
while(down < up)
{
const size_t mid = (down + up) / 2;
if(cmp(*(beg+mid), key))
{
down = mid + 1;
}
else
{
up = mid;
}
}
return beg + down;
}
////////////////////////////////////////////////////////////////////////////////
// Memory allocation
static void* VmaMalloc(const VkAllocationCallbacks* pAllocationCallbacks, size_t size, size_t alignment)
{
if((pAllocationCallbacks != VMA_NULL) &&
(pAllocationCallbacks->pfnAllocation != VMA_NULL))
{
return (*pAllocationCallbacks->pfnAllocation)(
pAllocationCallbacks->pUserData,
size,
alignment,
VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
}
else
{
return VMA_SYSTEM_ALIGNED_MALLOC(size, alignment);
}
}
static void VmaFree(const VkAllocationCallbacks* pAllocationCallbacks, void* ptr)
{
if((pAllocationCallbacks != VMA_NULL) &&
(pAllocationCallbacks->pfnFree != VMA_NULL))
{
(*pAllocationCallbacks->pfnFree)(pAllocationCallbacks->pUserData, ptr);
}
else
{
VMA_SYSTEM_FREE(ptr);
}
}
template<typename T>
static T* VmaAllocate(const VkAllocationCallbacks* pAllocationCallbacks)
{
return (T*)VmaMalloc(pAllocationCallbacks, sizeof(T), VMA_ALIGN_OF(T));
}
template<typename T>
static T* VmaAllocateArray(const VkAllocationCallbacks* pAllocationCallbacks, size_t count)
{
return (T*)VmaMalloc(pAllocationCallbacks, sizeof(T) * count, VMA_ALIGN_OF(T));
}
#define vma_new(allocator, type) new(VmaAllocate<type>(allocator))(type)
#define vma_new_array(allocator, type, count) new(VmaAllocateArray<type>((allocator), (count)))(type)
template<typename T>
static void vma_delete(const VkAllocationCallbacks* pAllocationCallbacks, T* ptr)
{
ptr->~T();
VmaFree(pAllocationCallbacks, ptr);
}
template<typename T>
static void vma_delete_array(const VkAllocationCallbacks* pAllocationCallbacks, T* ptr, size_t count)
{
if(ptr != VMA_NULL)
{
for(size_t i = count; i--; )
{
ptr[i].~T();
}
VmaFree(pAllocationCallbacks, ptr);
}
}
// STL-compatible allocator.
template<typename T>
class VmaStlAllocator
{
public:
const VkAllocationCallbacks* const m_pCallbacks;
typedef T value_type;
VmaStlAllocator(const VkAllocationCallbacks* pCallbacks) : m_pCallbacks(pCallbacks) { }
template<typename U> VmaStlAllocator(const VmaStlAllocator<U>& src) : m_pCallbacks(src.m_pCallbacks) { }
T* allocate(size_t n) { return VmaAllocateArray<T>(m_pCallbacks, n); }
void deallocate(T* p, size_t n) { VmaFree(m_pCallbacks, p); }
template<typename U>
bool operator==(const VmaStlAllocator<U>& rhs) const
{
return m_pCallbacks == rhs.m_pCallbacks;
}
template<typename U>
bool operator!=(const VmaStlAllocator<U>& rhs) const
{
return m_pCallbacks != rhs.m_pCallbacks;
}
VmaStlAllocator& operator=(const VmaStlAllocator& x) = delete;
};
#if VMA_USE_STL_VECTOR
#define VmaVector std::vector
template<typename T, typename allocatorT>
static void VmaVectorInsert(std::vector<T, allocatorT>& vec, size_t index, const T& item)
{
vec.insert(vec.begin() + index, item);
}
template<typename T, typename allocatorT>
static void VmaVectorRemove(std::vector<T, allocatorT>& vec, size_t index)
{
vec.erase(vec.begin() + index);
}
#else // #if VMA_USE_STL_VECTOR
/* Class with interface compatible with subset of std::vector.
T must be POD because constructors and destructors are not called and memcpy is
used for these objects. */
template<typename T, typename AllocatorT>
class VmaVector
{
public:
typedef T value_type;
VmaVector(const AllocatorT& allocator) :
m_Allocator(allocator),
m_pArray(VMA_NULL),
m_Count(0),
m_Capacity(0)
{
}
VmaVector(size_t count, const AllocatorT& allocator) :
m_Allocator(allocator),
m_pArray(count ? (T*)VmaAllocateArray<T>(allocator.m_pCallbacks, count) : VMA_NULL),
m_Count(count),
m_Capacity(count)
{
}
VmaVector(const VmaVector<T, AllocatorT>& src) :
m_Allocator(src.m_Allocator),
m_pArray(src.m_Count ? (T*)VmaAllocateArray<T>(src.m_Allocator.m_pCallbacks, src.m_Count) : VMA_NULL),
m_Count(src.m_Count),
m_Capacity(src.m_Count)
{
if(m_Count != 0)
{
memcpy(m_pArray, src.m_pArray, m_Count * sizeof(T));
}
}
~VmaVector()
{
VmaFree(m_Allocator.m_pCallbacks, m_pArray);
}
VmaVector& operator=(const VmaVector<T, AllocatorT>& rhs)
{
if(&rhs != this)
{
resize(rhs.m_Count);
if(m_Count != 0)
{
memcpy(m_pArray, rhs.m_pArray, m_Count * sizeof(T));
}
}
return *this;
}
bool empty() const { return m_Count == 0; }
size_t size() const { return m_Count; }
T* data() { return m_pArray; }
const T* data() const { return m_pArray; }
T& operator[](size_t index)
{
VMA_HEAVY_ASSERT(index < m_Count);
return m_pArray[index];
}
const T& operator[](size_t index) const
{
VMA_HEAVY_ASSERT(index < m_Count);
return m_pArray[index];
}
T& front()
{
VMA_HEAVY_ASSERT(m_Count > 0);
return m_pArray[0];
}
const T& front() const
{
VMA_HEAVY_ASSERT(m_Count > 0);
return m_pArray[0];
}
T& back()
{
VMA_HEAVY_ASSERT(m_Count > 0);
return m_pArray[m_Count - 1];
}
const T& back() const
{
VMA_HEAVY_ASSERT(m_Count > 0);
return m_pArray[m_Count - 1];
}
void reserve(size_t newCapacity, bool freeMemory = false)
{
newCapacity = VMA_MAX(newCapacity, m_Count);
if((newCapacity < m_Capacity) && !freeMemory)
{
newCapacity = m_Capacity;
}
if(newCapacity != m_Capacity)
{
T* const newArray = newCapacity ? VmaAllocateArray<T>(m_Allocator, newCapacity) : VMA_NULL;
if(m_Count != 0)
{
memcpy(newArray, m_pArray, m_Count * sizeof(T));
}
VmaFree(m_Allocator.m_pCallbacks, m_pArray);
m_Capacity = newCapacity;
m_pArray = newArray;
}
}
void resize(size_t newCount, bool freeMemory = false)
{
size_t newCapacity = m_Capacity;
if(newCount > m_Capacity)
{
newCapacity = VMA_MAX(newCount, VMA_MAX(m_Capacity * 3 / 2, (size_t)8));
}
else if(freeMemory)
{
newCapacity = newCount;
}
if(newCapacity != m_Capacity)
{
T* const newArray = newCapacity ? VmaAllocateArray<T>(m_Allocator.m_pCallbacks, newCapacity) : VMA_NULL;
const size_t elementsToCopy = VMA_MIN(m_Count, newCount);
if(elementsToCopy != 0)
{
memcpy(newArray, m_pArray, elementsToCopy * sizeof(T));
}
VmaFree(m_Allocator.m_pCallbacks, m_pArray);
m_Capacity = newCapacity;
m_pArray = newArray;
}
m_Count = newCount;
}
void clear(bool freeMemory = false)
{
resize(0, freeMemory);
}
void insert(size_t index, const T& src)
{
VMA_HEAVY_ASSERT(index <= m_Count);
const size_t oldCount = size();
resize(oldCount + 1);
if(index < oldCount)
{
memmove(m_pArray + (index + 1), m_pArray + index, (oldCount - index) * sizeof(T));
}
m_pArray[index] = src;
}
void remove(size_t index)
{
VMA_HEAVY_ASSERT(index < m_Count);
const size_t oldCount = size();
if(index < oldCount - 1)
{
memmove(m_pArray + index, m_pArray + (index + 1), (oldCount - index - 1) * sizeof(T));
}
resize(oldCount - 1);
}
void push_back(const T& src)
{
const size_t newIndex = size();
resize(newIndex + 1);
m_pArray[newIndex] = src;
}
void pop_back()
{
VMA_HEAVY_ASSERT(m_Count > 0);
resize(size() - 1);
}
void push_front(const T& src)
{
insert(0, src);
}
void pop_front()
{
VMA_HEAVY_ASSERT(m_Count > 0);
remove(0);
}
typedef T* iterator;
iterator begin() { return m_pArray; }
iterator end() { return m_pArray + m_Count; }
private:
AllocatorT m_Allocator;
T* m_pArray;
size_t m_Count;
size_t m_Capacity;
};
template<typename T, typename allocatorT>
static void VmaVectorInsert(VmaVector<T, allocatorT>& vec, size_t index, const T& item)
{
vec.insert(index, item);
}
template<typename T, typename allocatorT>
static void VmaVectorRemove(VmaVector<T, allocatorT>& vec, size_t index)
{
vec.remove(index);
}
#endif // #if VMA_USE_STL_VECTOR
template<typename CmpLess, typename VectorT>
size_t VmaVectorInsertSorted(VectorT& vector, const typename VectorT::value_type& value)
{
const size_t indexToInsert = VmaBinaryFindFirstNotLess(
vector.data(),
vector.data() + vector.size(),
value,
CmpLess()) - vector.data();
VmaVectorInsert(vector, indexToInsert, value);
return indexToInsert;
}
template<typename CmpLess, typename VectorT>
bool VmaVectorRemoveSorted(VectorT& vector, const typename VectorT::value_type& value)
{
CmpLess comparator;
typename VectorT::iterator it = VmaBinaryFindFirstNotLess(
vector.begin(),
vector.end(),
value,
comparator);
if((it != vector.end()) && !comparator(*it, value) && !comparator(value, *it))
{
size_t indexToRemove = it - vector.begin();
VmaVectorRemove(vector, indexToRemove);
return true;
}
return false;
}
template<typename CmpLess, typename VectorT>
size_t VmaVectorFindSorted(const VectorT& vector, const typename VectorT::value_type& value)
{
CmpLess comparator;
typename VectorT::iterator it = VmaBinaryFindFirstNotLess(
vector.data(),
vector.data() + vector.size(),
value,
comparator);
if(it != vector.size() && !comparator(*it, value) && !comparator(value, *it))
{
return it - vector.begin();
}
else
{
return vector.size();
}
}
////////////////////////////////////////////////////////////////////////////////
// class VmaPoolAllocator
/*
Allocator for objects of type T using a list of arrays (pools) to speed up
allocation. Number of elements that can be allocated is not bounded because
allocator can create multiple blocks.
*/
template<typename T>
class VmaPoolAllocator
{
public:
VmaPoolAllocator(const VkAllocationCallbacks* pAllocationCallbacks, size_t itemsPerBlock);
~VmaPoolAllocator();
void Clear();
T* Alloc();
void Free(T* ptr);
private:
union Item
{
uint32_t NextFreeIndex;
T Value;
};
struct ItemBlock
{
Item* pItems;
uint32_t FirstFreeIndex;
};
const VkAllocationCallbacks* m_pAllocationCallbacks;
size_t m_ItemsPerBlock;
VmaVector< ItemBlock, VmaStlAllocator<ItemBlock> > m_ItemBlocks;
ItemBlock& CreateNewBlock();
};
template<typename T>
VmaPoolAllocator<T>::VmaPoolAllocator(const VkAllocationCallbacks* pAllocationCallbacks, size_t itemsPerBlock) :
m_pAllocationCallbacks(pAllocationCallbacks),
m_ItemsPerBlock(itemsPerBlock),
m_ItemBlocks(VmaStlAllocator<ItemBlock>(pAllocationCallbacks))
{
VMA_ASSERT(itemsPerBlock > 0);
}
template<typename T>
VmaPoolAllocator<T>::~VmaPoolAllocator()
{
Clear();
}
template<typename T>
void VmaPoolAllocator<T>::Clear()
{
for(size_t i = m_ItemBlocks.size(); i--; )
vma_delete_array(m_pAllocationCallbacks, m_ItemBlocks[i].pItems, m_ItemsPerBlock);
m_ItemBlocks.clear();
}
template<typename T>
T* VmaPoolAllocator<T>::Alloc()
{
for(size_t i = m_ItemBlocks.size(); i--; )
{
ItemBlock& block = m_ItemBlocks[i];
// This block has some free items: Use first one.
if(block.FirstFreeIndex != UINT32_MAX)
{
Item* const pItem = &block.pItems[block.FirstFreeIndex];
block.FirstFreeIndex = pItem->NextFreeIndex;
return &pItem->Value;
}
}
// No block has free item: Create new one and use it.
ItemBlock& newBlock = CreateNewBlock();
Item* const pItem = &newBlock.pItems[0];
newBlock.FirstFreeIndex = pItem->NextFreeIndex;
return &pItem->Value;
}
template<typename T>
void VmaPoolAllocator<T>::Free(T* ptr)
{
// Search all memory blocks to find ptr.
for(size_t i = 0; i < m_ItemBlocks.size(); ++i)
{
ItemBlock& block = m_ItemBlocks[i];
// Casting to union.
Item* pItemPtr;
memcpy(&pItemPtr, &ptr, sizeof(pItemPtr));
// Check if pItemPtr is in address range of this block.
if((pItemPtr >= block.pItems) && (pItemPtr < block.pItems + m_ItemsPerBlock))
{
const uint32_t index = static_cast<uint32_t>(pItemPtr - block.pItems);
pItemPtr->NextFreeIndex = block.FirstFreeIndex;
block.FirstFreeIndex = index;
return;
}
}
VMA_ASSERT(0 && "Pointer doesn't belong to this memory pool.");
}
template<typename T>
typename VmaPoolAllocator<T>::ItemBlock& VmaPoolAllocator<T>::CreateNewBlock()
{
ItemBlock newBlock = {
vma_new_array(m_pAllocationCallbacks, Item, m_ItemsPerBlock), 0 };
m_ItemBlocks.push_back(newBlock);
// Setup singly-linked list of all free items in this block.
for(uint32_t i = 0; i < m_ItemsPerBlock - 1; ++i)
newBlock.pItems[i].NextFreeIndex = i + 1;
newBlock.pItems[m_ItemsPerBlock - 1].NextFreeIndex = UINT32_MAX;
return m_ItemBlocks.back();
}
////////////////////////////////////////////////////////////////////////////////
// class VmaRawList, VmaList
#if VMA_USE_STL_LIST
#define VmaList std::list
#else // #if VMA_USE_STL_LIST
template<typename T>
struct VmaListItem
{
VmaListItem* pPrev;
VmaListItem* pNext;
T Value;
};
// Doubly linked list.
template<typename T>
class VmaRawList
{
public:
typedef VmaListItem<T> ItemType;
VmaRawList(const VkAllocationCallbacks* pAllocationCallbacks);
~VmaRawList();
void Clear();
size_t GetCount() const { return m_Count; }
bool IsEmpty() const { return m_Count == 0; }
ItemType* Front() { return m_pFront; }
const ItemType* Front() const { return m_pFront; }
ItemType* Back() { return m_pBack; }
const ItemType* Back() const { return m_pBack; }
ItemType* PushBack();
ItemType* PushFront();
ItemType* PushBack(const T& value);
ItemType* PushFront(const T& value);
void PopBack();
void PopFront();
// Item can be null - it means PushBack.
ItemType* InsertBefore(ItemType* pItem);
// Item can be null - it means PushFront.
ItemType* InsertAfter(ItemType* pItem);
ItemType* InsertBefore(ItemType* pItem, const T& value);
ItemType* InsertAfter(ItemType* pItem, const T& value);
void Remove(ItemType* pItem);
private:
const VkAllocationCallbacks* const m_pAllocationCallbacks;
VmaPoolAllocator<ItemType> m_ItemAllocator;
ItemType* m_pFront;
ItemType* m_pBack;
size_t m_Count;
// Declared not defined, to block copy constructor and assignment operator.
VmaRawList(const VmaRawList<T>& src);
VmaRawList<T>& operator=(const VmaRawList<T>& rhs);
};
template<typename T>
VmaRawList<T>::VmaRawList(const VkAllocationCallbacks* pAllocationCallbacks) :
m_pAllocationCallbacks(pAllocationCallbacks),
m_ItemAllocator(pAllocationCallbacks, 128),
m_pFront(VMA_NULL),
m_pBack(VMA_NULL),
m_Count(0)
{
}
template<typename T>
VmaRawList<T>::~VmaRawList()
{
// Intentionally not calling Clear, because that would be unnecessary
// computations to return all items to m_ItemAllocator as free.
}
template<typename T>
void VmaRawList<T>::Clear()
{
if(IsEmpty() == false)
{
ItemType* pItem = m_pBack;
while(pItem != VMA_NULL)
{
ItemType* const pPrevItem = pItem->pPrev;
m_ItemAllocator.Free(pItem);
pItem = pPrevItem;
}
m_pFront = VMA_NULL;
m_pBack = VMA_NULL;
m_Count = 0;
}
}
template<typename T>
VmaListItem<T>* VmaRawList<T>::PushBack()
{
ItemType* const pNewItem = m_ItemAllocator.Alloc();
pNewItem->pNext = VMA_NULL;
if(IsEmpty())
{
pNewItem->pPrev = VMA_NULL;
m_pFront = pNewItem;
m_pBack = pNewItem;
m_Count = 1;
}
else
{
pNewItem->pPrev = m_pBack;
m_pBack->pNext = pNewItem;
m_pBack = pNewItem;
++m_Count;
}
return pNewItem;
}
template<typename T>
VmaListItem<T>* VmaRawList<T>::PushFront()
{
ItemType* const pNewItem = m_ItemAllocator.Alloc();
pNewItem->pPrev = VMA_NULL;
if(IsEmpty())
{
pNewItem->pNext = VMA_NULL;
m_pFront = pNewItem;
m_pBack = pNewItem;
m_Count = 1;
}
else
{
pNewItem->pNext = m_pFront;
m_pFront->pPrev = pNewItem;
m_pFront = pNewItem;
++m_Count;
}
return pNewItem;
}
template<typename T>
VmaListItem<T>* VmaRawList<T>::PushBack(const T& value)
{
ItemType* const pNewItem = PushBack();
pNewItem->Value = value;
return pNewItem;
}
template<typename T>
VmaListItem<T>* VmaRawList<T>::PushFront(const T& value)
{
ItemType* const pNewItem = PushFront();
pNewItem->Value = value;
return pNewItem;
}
template<typename T>
void VmaRawList<T>::PopBack()
{
VMA_HEAVY_ASSERT(m_Count > 0);
ItemType* const pBackItem = m_pBack;
ItemType* const pPrevItem = pBackItem->pPrev;
if(pPrevItem != VMA_NULL)
{
pPrevItem->pNext = VMA_NULL;
}
m_pBack = pPrevItem;
m_ItemAllocator.Free(pBackItem);
--m_Count;
}
template<typename T>
void VmaRawList<T>::PopFront()
{
VMA_HEAVY_ASSERT(m_Count > 0);
ItemType* const pFrontItem = m_pFront;
ItemType* const pNextItem = pFrontItem->pNext;
if(pNextItem != VMA_NULL)
{
pNextItem->pPrev = VMA_NULL;
}
m_pFront = pNextItem;
m_ItemAllocator.Free(pFrontItem);
--m_Count;
}
template<typename T>
void VmaRawList<T>::Remove(ItemType* pItem)
{
VMA_HEAVY_ASSERT(pItem != VMA_NULL);
VMA_HEAVY_ASSERT(m_Count > 0);
if(pItem->pPrev != VMA_NULL)
{
pItem->pPrev->pNext = pItem->pNext;
}
else
{
VMA_HEAVY_ASSERT(m_pFront == pItem);
m_pFront = pItem->pNext;
}
if(pItem->pNext != VMA_NULL)
{
pItem->pNext->pPrev = pItem->pPrev;
}
else
{
VMA_HEAVY_ASSERT(m_pBack == pItem);
m_pBack = pItem->pPrev;
}
m_ItemAllocator.Free(pItem);
--m_Count;
}
template<typename T>
VmaListItem<T>* VmaRawList<T>::InsertBefore(ItemType* pItem)
{
if(pItem != VMA_NULL)
{
ItemType* const prevItem = pItem->pPrev;
ItemType* const newItem = m_ItemAllocator.Alloc();
newItem->pPrev = prevItem;
newItem->pNext = pItem;
pItem->pPrev = newItem;
if(prevItem != VMA_NULL)
{
prevItem->pNext = newItem;
}
else
{
VMA_HEAVY_ASSERT(m_pFront == pItem);
m_pFront = newItem;
}
++m_Count;
return newItem;
}
else
return PushBack();
}
template<typename T>
VmaListItem<T>* VmaRawList<T>::InsertAfter(ItemType* pItem)
{
if(pItem != VMA_NULL)
{
ItemType* const nextItem = pItem->pNext;
ItemType* const newItem = m_ItemAllocator.Alloc();
newItem->pNext = nextItem;
newItem->pPrev = pItem;
pItem->pNext = newItem;
if(nextItem != VMA_NULL)
{
nextItem->pPrev = newItem;
}
else
{
VMA_HEAVY_ASSERT(m_pBack == pItem);
m_pBack = newItem;
}
++m_Count;
return newItem;
}
else
return PushFront();
}
template<typename T>
VmaListItem<T>* VmaRawList<T>::InsertBefore(ItemType* pItem, const T& value)
{
ItemType* const newItem = InsertBefore(pItem);
newItem->Value = value;
return newItem;
}
template<typename T>
VmaListItem<T>* VmaRawList<T>::InsertAfter(ItemType* pItem, const T& value)
{
ItemType* const newItem = InsertAfter(pItem);
newItem->Value = value;
return newItem;
}
template<typename T, typename AllocatorT>
class VmaList
{
public:
class iterator
{
public:
iterator() :
m_pList(VMA_NULL),
m_pItem(VMA_NULL)
{
}
T& operator*() const
{
VMA_HEAVY_ASSERT(m_pItem != VMA_NULL);
return m_pItem->Value;
}
T* operator->() const
{
VMA_HEAVY_ASSERT(m_pItem != VMA_NULL);
return &m_pItem->Value;
}
iterator& operator++()
{
VMA_HEAVY_ASSERT(m_pItem != VMA_NULL);
m_pItem = m_pItem->pNext;
return *this;
}
iterator& operator--()
{
if(m_pItem != VMA_NULL)
{
m_pItem = m_pItem->pPrev;
}
else
{
VMA_HEAVY_ASSERT(!m_pList->IsEmpty());
m_pItem = m_pList->Back();
}
return *this;
}
iterator operator++(int)
{
iterator result = *this;
++*this;
return result;
}
iterator operator--(int)
{
iterator result = *this;
--*this;
return result;
}
bool operator==(const iterator& rhs) const
{
VMA_HEAVY_ASSERT(m_pList == rhs.m_pList);
return m_pItem == rhs.m_pItem;
}
bool operator!=(const iterator& rhs) const
{
VMA_HEAVY_ASSERT(m_pList == rhs.m_pList);
return m_pItem != rhs.m_pItem;
}
private:
VmaRawList<T>* m_pList;
VmaListItem<T>* m_pItem;
iterator(VmaRawList<T>* pList, VmaListItem<T>* pItem) :
m_pList(pList),
m_pItem(pItem)
{
}
friend class VmaList<T, AllocatorT>;
};
class const_iterator
{
public:
const_iterator() :
m_pList(VMA_NULL),
m_pItem(VMA_NULL)
{
}
const_iterator(const iterator& src) :
m_pList(src.m_pList),
m_pItem(src.m_pItem)
{
}
const T& operator*() const
{
VMA_HEAVY_ASSERT(m_pItem != VMA_NULL);
return m_pItem->Value;
}
const T* operator->() const
{
VMA_HEAVY_ASSERT(m_pItem != VMA_NULL);
return &m_pItem->Value;
}
const_iterator& operator++()
{
VMA_HEAVY_ASSERT(m_pItem != VMA_NULL);
m_pItem = m_pItem->pNext;
return *this;
}
const_iterator& operator--()
{
if(m_pItem != VMA_NULL)
{
m_pItem = m_pItem->pPrev;
}
else
{
VMA_HEAVY_ASSERT(!m_pList->IsEmpty());
m_pItem = m_pList->Back();
}
return *this;
}
const_iterator operator++(int)
{
const_iterator result = *this;
++*this;
return result;
}
const_iterator operator--(int)
{
const_iterator result = *this;
--*this;
return result;
}
bool operator==(const const_iterator& rhs) const
{
VMA_HEAVY_ASSERT(m_pList == rhs.m_pList);
return m_pItem == rhs.m_pItem;
}
bool operator!=(const const_iterator& rhs) const
{
VMA_HEAVY_ASSERT(m_pList == rhs.m_pList);
return m_pItem != rhs.m_pItem;
}
private:
const_iterator(const VmaRawList<T>* pList, const VmaListItem<T>* pItem) :
m_pList(pList),
m_pItem(pItem)
{
}
const VmaRawList<T>* m_pList;
const VmaListItem<T>* m_pItem;
friend class VmaList<T, AllocatorT>;
};
VmaList(const AllocatorT& allocator) : m_RawList(allocator.m_pCallbacks) { }
bool empty() const { return m_RawList.IsEmpty(); }
size_t size() const { return m_RawList.GetCount(); }
iterator begin() { return iterator(&m_RawList, m_RawList.Front()); }
iterator end() { return iterator(&m_RawList, VMA_NULL); }
const_iterator cbegin() const { return const_iterator(&m_RawList, m_RawList.Front()); }
const_iterator cend() const { return const_iterator(&m_RawList, VMA_NULL); }
void clear() { m_RawList.Clear(); }
void push_back(const T& value) { m_RawList.PushBack(value); }
void erase(iterator it) { m_RawList.Remove(it.m_pItem); }
iterator insert(iterator it, const T& value) { return iterator(&m_RawList, m_RawList.InsertBefore(it.m_pItem, value)); }
private:
VmaRawList<T> m_RawList;
};
#endif // #if VMA_USE_STL_LIST
////////////////////////////////////////////////////////////////////////////////
// class VmaMap
// Unused in this version.
#if 0
#if VMA_USE_STL_UNORDERED_MAP
#define VmaPair std::pair
#define VMA_MAP_TYPE(KeyT, ValueT) \
std::unordered_map< KeyT, ValueT, std::hash<KeyT>, std::equal_to<KeyT>, VmaStlAllocator< std::pair<KeyT, ValueT> > >
#else // #if VMA_USE_STL_UNORDERED_MAP
template<typename T1, typename T2>
struct VmaPair
{
T1 first;
T2 second;
VmaPair() : first(), second() { }
VmaPair(const T1& firstSrc, const T2& secondSrc) : first(firstSrc), second(secondSrc) { }
};
/* Class compatible with subset of interface of std::unordered_map.
KeyT, ValueT must be POD because they will be stored in VmaVector.
*/
template<typename KeyT, typename ValueT>
class VmaMap
{
public:
typedef VmaPair<KeyT, ValueT> PairType;
typedef PairType* iterator;
VmaMap(const VmaStlAllocator<PairType>& allocator) : m_Vector(allocator) { }
iterator begin() { return m_Vector.begin(); }
iterator end() { return m_Vector.end(); }
void insert(const PairType& pair);
iterator find(const KeyT& key);
void erase(iterator it);
private:
VmaVector< PairType, VmaStlAllocator<PairType> > m_Vector;
};
#define VMA_MAP_TYPE(KeyT, ValueT) VmaMap<KeyT, ValueT>
template<typename FirstT, typename SecondT>
struct VmaPairFirstLess
{
bool operator()(const VmaPair<FirstT, SecondT>& lhs, const VmaPair<FirstT, SecondT>& rhs) const
{
return lhs.first < rhs.first;
}
bool operator()(const VmaPair<FirstT, SecondT>& lhs, const FirstT& rhsFirst) const
{
return lhs.first < rhsFirst;
}
};
template<typename KeyT, typename ValueT>
void VmaMap<KeyT, ValueT>::insert(const PairType& pair)
{
const size_t indexToInsert = VmaBinaryFindFirstNotLess(
m_Vector.data(),
m_Vector.data() + m_Vector.size(),
pair,
VmaPairFirstLess<KeyT, ValueT>()) - m_Vector.data();
VmaVectorInsert(m_Vector, indexToInsert, pair);
}
template<typename KeyT, typename ValueT>
VmaPair<KeyT, ValueT>* VmaMap<KeyT, ValueT>::find(const KeyT& key)
{
PairType* it = VmaBinaryFindFirstNotLess(
m_Vector.data(),
m_Vector.data() + m_Vector.size(),
key,
VmaPairFirstLess<KeyT, ValueT>());
if((it != m_Vector.end()) && (it->first == key))
{
return it;
}
else
{
return m_Vector.end();
}
}
template<typename KeyT, typename ValueT>
void VmaMap<KeyT, ValueT>::erase(iterator it)
{
VmaVectorRemove(m_Vector, it - m_Vector.begin());
}
#endif // #if VMA_USE_STL_UNORDERED_MAP
#endif // #if 0
////////////////////////////////////////////////////////////////////////////////
class VmaDeviceMemoryBlock;
struct VmaAllocation_T
{
private:
static const uint8_t MAP_COUNT_FLAG_PERSISTENT_MAP = 0x80;
enum FLAGS
{
FLAG_USER_DATA_STRING = 0x01,
};
public:
enum ALLOCATION_TYPE
{
ALLOCATION_TYPE_NONE,
ALLOCATION_TYPE_BLOCK,
ALLOCATION_TYPE_DEDICATED,
};
VmaAllocation_T(uint32_t currentFrameIndex, bool userDataString) :
m_Alignment(1),
m_Size(0),
m_pUserData(VMA_NULL),
m_LastUseFrameIndex(currentFrameIndex),
m_Type((uint8_t)ALLOCATION_TYPE_NONE),
m_SuballocationType((uint8_t)VMA_SUBALLOCATION_TYPE_UNKNOWN),
m_MapCount(0),
m_Flags(userDataString ? (uint8_t)FLAG_USER_DATA_STRING : 0)
{
}
~VmaAllocation_T()
{
VMA_ASSERT((m_MapCount & ~MAP_COUNT_FLAG_PERSISTENT_MAP) == 0 && "Allocation was not unmapped before destruction.");
// Check if owned string was freed.
VMA_ASSERT(m_pUserData == VMA_NULL);
}
void InitBlockAllocation(
VmaPool hPool,
VmaDeviceMemoryBlock* block,
VkDeviceSize offset,
VkDeviceSize alignment,
VkDeviceSize size,
VmaSuballocationType suballocationType,
bool mapped,
bool canBecomeLost)
{
VMA_ASSERT(m_Type == ALLOCATION_TYPE_NONE);
VMA_ASSERT(block != VMA_NULL);
m_Type = (uint8_t)ALLOCATION_TYPE_BLOCK;
m_Alignment = alignment;
m_Size = size;
m_MapCount = mapped ? MAP_COUNT_FLAG_PERSISTENT_MAP : 0;
m_SuballocationType = (uint8_t)suballocationType;
m_BlockAllocation.m_hPool = hPool;
m_BlockAllocation.m_Block = block;
m_BlockAllocation.m_Offset = offset;
m_BlockAllocation.m_CanBecomeLost = canBecomeLost;
}
void InitLost()
{
VMA_ASSERT(m_Type == ALLOCATION_TYPE_NONE);
VMA_ASSERT(m_LastUseFrameIndex.load() == VMA_FRAME_INDEX_LOST);
m_Type = (uint8_t)ALLOCATION_TYPE_BLOCK;
m_BlockAllocation.m_hPool = VK_NULL_HANDLE;
m_BlockAllocation.m_Block = VMA_NULL;
m_BlockAllocation.m_Offset = 0;
m_BlockAllocation.m_CanBecomeLost = true;
}
void ChangeBlockAllocation(
VmaAllocator hAllocator,
VmaDeviceMemoryBlock* block,
VkDeviceSize offset);
// pMappedData not null means allocation is created with MAPPED flag.
void InitDedicatedAllocation(
uint32_t memoryTypeIndex,
VkDeviceMemory hMemory,
VmaSuballocationType suballocationType,
void* pMappedData,
VkDeviceSize size)
{
VMA_ASSERT(m_Type == ALLOCATION_TYPE_NONE);
VMA_ASSERT(hMemory != VK_NULL_HANDLE);
m_Type = (uint8_t)ALLOCATION_TYPE_DEDICATED;
m_Alignment = 0;
m_Size = size;
m_SuballocationType = (uint8_t)suballocationType;
m_MapCount = (pMappedData != VMA_NULL) ? MAP_COUNT_FLAG_PERSISTENT_MAP : 0;
m_DedicatedAllocation.m_MemoryTypeIndex = memoryTypeIndex;
m_DedicatedAllocation.m_hMemory = hMemory;
m_DedicatedAllocation.m_pMappedData = pMappedData;
}
ALLOCATION_TYPE GetType() const { return (ALLOCATION_TYPE)m_Type; }
VkDeviceSize GetAlignment() const { return m_Alignment; }
VkDeviceSize GetSize() const { return m_Size; }
bool IsUserDataString() const { return (m_Flags & FLAG_USER_DATA_STRING) != 0; }
void* GetUserData() const { return m_pUserData; }
void SetUserData(VmaAllocator hAllocator, void* pUserData);
VmaSuballocationType GetSuballocationType() const { return (VmaSuballocationType)m_SuballocationType; }
VmaDeviceMemoryBlock* GetBlock() const
{
VMA_ASSERT(m_Type == ALLOCATION_TYPE_BLOCK);
return m_BlockAllocation.m_Block;
}
VkDeviceSize GetOffset() const;
VkDeviceMemory GetMemory() const;
uint32_t GetMemoryTypeIndex() const;
bool IsPersistentMap() const { return (m_MapCount & MAP_COUNT_FLAG_PERSISTENT_MAP) != 0; }
void* GetMappedData() const;
bool CanBecomeLost() const;
VmaPool GetPool() const;
uint32_t GetLastUseFrameIndex() const
{
return m_LastUseFrameIndex.load();
}
bool CompareExchangeLastUseFrameIndex(uint32_t& expected, uint32_t desired)
{
return m_LastUseFrameIndex.compare_exchange_weak(expected, desired);
}
/*
- If hAllocation.LastUseFrameIndex + frameInUseCount < allocator.CurrentFrameIndex,
makes it lost by setting LastUseFrameIndex = VMA_FRAME_INDEX_LOST and returns true.
- Else, returns false.
If hAllocation is already lost, assert - you should not call it then.
If hAllocation was not created with CAN_BECOME_LOST_BIT, assert.
*/
bool MakeLost(uint32_t currentFrameIndex, uint32_t frameInUseCount);
void DedicatedAllocCalcStatsInfo(VmaStatInfo& outInfo)
{
VMA_ASSERT(m_Type == ALLOCATION_TYPE_DEDICATED);
outInfo.blockCount = 1;
outInfo.allocationCount = 1;
outInfo.unusedRangeCount = 0;
outInfo.usedBytes = m_Size;
outInfo.unusedBytes = 0;
outInfo.allocationSizeMin = outInfo.allocationSizeMax = m_Size;
outInfo.unusedRangeSizeMin = UINT64_MAX;
outInfo.unusedRangeSizeMax = 0;
}
void BlockAllocMap();
void BlockAllocUnmap();
VkResult DedicatedAllocMap(VmaAllocator hAllocator, void** ppData);
void DedicatedAllocUnmap(VmaAllocator hAllocator);
private:
VkDeviceSize m_Alignment;
VkDeviceSize m_Size;
void* m_pUserData;
VMA_ATOMIC_UINT32 m_LastUseFrameIndex;
uint8_t m_Type; // ALLOCATION_TYPE
uint8_t m_SuballocationType; // VmaSuballocationType
// Bit 0x80 is set when allocation was created with VMA_ALLOCATION_CREATE_MAPPED_BIT.
// Bits with mask 0x7F are reference counter for vmaMapMemory()/vmaUnmapMemory().
uint8_t m_MapCount;
uint8_t m_Flags; // enum FLAGS
// Allocation out of VmaDeviceMemoryBlock.
struct BlockAllocation
{
VmaPool m_hPool; // Null if belongs to general memory.
VmaDeviceMemoryBlock* m_Block;
VkDeviceSize m_Offset;
bool m_CanBecomeLost;
};
// Allocation for an object that has its own private VkDeviceMemory.
struct DedicatedAllocation
{
uint32_t m_MemoryTypeIndex;
VkDeviceMemory m_hMemory;
void* m_pMappedData; // Not null means memory is mapped.
};
union
{
// Allocation out of VmaDeviceMemoryBlock.
BlockAllocation m_BlockAllocation;
// Allocation for an object that has its own private VkDeviceMemory.
DedicatedAllocation m_DedicatedAllocation;
};
void FreeUserDataString(VmaAllocator hAllocator);
};
/*
Represents a region of VmaDeviceMemoryBlock that is either assigned and returned as
allocated memory block or free.
*/
struct VmaSuballocation
{
VkDeviceSize offset;
VkDeviceSize size;
VmaAllocation hAllocation;
VmaSuballocationType type;
};
typedef VmaList< VmaSuballocation, VmaStlAllocator<VmaSuballocation> > VmaSuballocationList;
// Cost of one additional allocation lost, as equivalent in bytes.
static const VkDeviceSize VMA_LOST_ALLOCATION_COST = 1048576;
/*
Parameters of planned allocation inside a VmaDeviceMemoryBlock.
If canMakeOtherLost was false:
- item points to a FREE suballocation.
- itemsToMakeLostCount is 0.
If canMakeOtherLost was true:
- item points to first of sequence of suballocations, which are either FREE,
or point to VmaAllocations that can become lost.
- itemsToMakeLostCount is the number of VmaAllocations that need to be made lost for
the requested allocation to succeed.
*/
struct VmaAllocationRequest
{
VkDeviceSize offset;
VkDeviceSize sumFreeSize; // Sum size of free items that overlap with proposed allocation.
VkDeviceSize sumItemSize; // Sum size of items to make lost that overlap with proposed allocation.
VmaSuballocationList::iterator item;
size_t itemsToMakeLostCount;
VkDeviceSize CalcCost() const
{
return sumItemSize + itemsToMakeLostCount * VMA_LOST_ALLOCATION_COST;
}
};
/*
Data structure used for bookkeeping of allocations and unused ranges of memory
in a single VkDeviceMemory block.
*/
class VmaBlockMetadata
{
public:
VmaBlockMetadata(VmaAllocator hAllocator);
~VmaBlockMetadata();
void Init(VkDeviceSize size);
// Validates all data structures inside this object. If not valid, returns false.
bool Validate() const;
VkDeviceSize GetSize() const { return m_Size; }
size_t GetAllocationCount() const { return m_Suballocations.size() - m_FreeCount; }
VkDeviceSize GetSumFreeSize() const { return m_SumFreeSize; }
VkDeviceSize GetUnusedRangeSizeMax() const;
// Returns true if this block is empty - contains only single free suballocation.
bool IsEmpty() const;
void CalcAllocationStatInfo(VmaStatInfo& outInfo) const;
void AddPoolStats(VmaPoolStats& inoutStats) const;
#if VMA_STATS_STRING_ENABLED
void PrintDetailedMap(class VmaJsonWriter& json) const;
#endif
// Creates trivial request for case when block is empty.
void CreateFirstAllocationRequest(VmaAllocationRequest* pAllocationRequest);
// Tries to find a place for suballocation with given parameters inside this block.
// If succeeded, fills pAllocationRequest and returns true.
// If failed, returns false.
bool CreateAllocationRequest(
uint32_t currentFrameIndex,
uint32_t frameInUseCount,
VkDeviceSize bufferImageGranularity,
VkDeviceSize allocSize,
VkDeviceSize allocAlignment,
VmaSuballocationType allocType,
bool canMakeOtherLost,
VmaAllocationRequest* pAllocationRequest);
bool MakeRequestedAllocationsLost(
uint32_t currentFrameIndex,
uint32_t frameInUseCount,
VmaAllocationRequest* pAllocationRequest);
uint32_t MakeAllocationsLost(uint32_t currentFrameIndex, uint32_t frameInUseCount);
// Makes actual allocation based on request. Request must already be checked and valid.
void Alloc(
const VmaAllocationRequest& request,
VmaSuballocationType type,
VkDeviceSize allocSize,
VmaAllocation hAllocation);
// Frees suballocation assigned to given memory region.
void Free(const VmaAllocation allocation);
void FreeAtOffset(VkDeviceSize offset);
private:
VkDeviceSize m_Size;
uint32_t m_FreeCount;
VkDeviceSize m_SumFreeSize;
VmaSuballocationList m_Suballocations;
// Suballocations that are free and have size greater than certain threshold.
// Sorted by size, ascending.
VmaVector< VmaSuballocationList::iterator, VmaStlAllocator< VmaSuballocationList::iterator > > m_FreeSuballocationsBySize;
bool ValidateFreeSuballocationList() const;
// Checks if requested suballocation with given parameters can be placed in given pFreeSuballocItem.
// If yes, fills pOffset and returns true. If no, returns false.
bool CheckAllocation(
uint32_t currentFrameIndex,
uint32_t frameInUseCount,
VkDeviceSize bufferImageGranularity,
VkDeviceSize allocSize,
VkDeviceSize allocAlignment,
VmaSuballocationType allocType,
VmaSuballocationList::const_iterator suballocItem,
bool canMakeOtherLost,
VkDeviceSize* pOffset,
size_t* itemsToMakeLostCount,
VkDeviceSize* pSumFreeSize,
VkDeviceSize* pSumItemSize) const;
// Given free suballocation, it merges it with following one, which must also be free.
void MergeFreeWithNext(VmaSuballocationList::iterator item);
// Releases given suballocation, making it free.
// Merges it with adjacent free suballocations if applicable.
// Returns iterator to new free suballocation at this place.
VmaSuballocationList::iterator FreeSuballocation(VmaSuballocationList::iterator suballocItem);
// Given free suballocation, it inserts it into sorted list of
// m_FreeSuballocationsBySize if it's suitable.
void RegisterFreeSuballocation(VmaSuballocationList::iterator item);
// Given free suballocation, it removes it from sorted list of
// m_FreeSuballocationsBySize if it's suitable.
void UnregisterFreeSuballocation(VmaSuballocationList::iterator item);
};
/*
Represents a single block of device memory (`VkDeviceMemory`) with all the
data about its regions (aka suballocations, #VmaAllocation), assigned and free.
Thread-safety: This class must be externally synchronized.
*/
class VmaDeviceMemoryBlock
{
public:
VmaBlockMetadata m_Metadata;
VmaDeviceMemoryBlock(VmaAllocator hAllocator);
~VmaDeviceMemoryBlock()
{
VMA_ASSERT(m_MapCount == 0 && "VkDeviceMemory block is being destroyed while it is still mapped.");
VMA_ASSERT(m_hMemory == VK_NULL_HANDLE);
}
// Always call after construction.
void Init(
uint32_t newMemoryTypeIndex,
VkDeviceMemory newMemory,
VkDeviceSize newSize);
// Always call before destruction.
void Destroy(VmaAllocator allocator);
VkDeviceMemory GetDeviceMemory() const { return m_hMemory; }
uint32_t GetMemoryTypeIndex() const { return m_MemoryTypeIndex; }
void* GetMappedData() const { return m_pMappedData; }
// Validates all data structures inside this object. If not valid, returns false.
bool Validate() const;
// ppData can be null.
VkResult Map(VmaAllocator hAllocator, uint32_t count, void** ppData);
void Unmap(VmaAllocator hAllocator, uint32_t count);
VkResult BindBufferMemory(
const VmaAllocator hAllocator,
const VmaAllocation hAllocation,
VkBuffer hBuffer);
VkResult BindImageMemory(
const VmaAllocator hAllocator,
const VmaAllocation hAllocation,
VkImage hImage);
private:
uint32_t m_MemoryTypeIndex;
VkDeviceMemory m_hMemory;
// Protects access to m_hMemory so it's not used by multiple threads simultaneously, e.g. vkMapMemory, vkBindBufferMemory.
// Also protects m_MapCount, m_pMappedData.
VMA_MUTEX m_Mutex;
uint32_t m_MapCount;
void* m_pMappedData;
};
struct VmaPointerLess
{
bool operator()(const void* lhs, const void* rhs) const
{
return lhs < rhs;
}
};
class VmaDefragmentator;
/*
Sequence of VmaDeviceMemoryBlock. Represents memory blocks allocated for a specific
Vulkan memory type.
Synchronized internally with a mutex.
*/
struct VmaBlockVector
{
VmaBlockVector(
VmaAllocator hAllocator,
uint32_t memoryTypeIndex,
VkDeviceSize preferredBlockSize,
size_t minBlockCount,
size_t maxBlockCount,
VkDeviceSize bufferImageGranularity,
uint32_t frameInUseCount,
bool isCustomPool);
~VmaBlockVector();
VkResult CreateMinBlocks();
uint32_t GetMemoryTypeIndex() const { return m_MemoryTypeIndex; }
VkDeviceSize GetPreferredBlockSize() const { return m_PreferredBlockSize; }
VkDeviceSize GetBufferImageGranularity() const { return m_BufferImageGranularity; }
uint32_t GetFrameInUseCount() const { return m_FrameInUseCount; }
void GetPoolStats(VmaPoolStats* pStats);
bool IsEmpty() const { return m_Blocks.empty(); }
VkResult Allocate(
VmaPool hCurrentPool,
uint32_t currentFrameIndex,
const VkMemoryRequirements& vkMemReq,
const VmaAllocationCreateInfo& createInfo,
VmaSuballocationType suballocType,
VmaAllocation* pAllocation);
void Free(
VmaAllocation hAllocation);
// Adds statistics of this BlockVector to pStats.
void AddStats(VmaStats* pStats);
#if VMA_STATS_STRING_ENABLED
void PrintDetailedMap(class VmaJsonWriter& json);
#endif
void MakePoolAllocationsLost(
uint32_t currentFrameIndex,
size_t* pLostAllocationCount);
VmaDefragmentator* EnsureDefragmentator(
VmaAllocator hAllocator,
uint32_t currentFrameIndex);
VkResult Defragment(
VmaDefragmentationStats* pDefragmentationStats,
VkDeviceSize& maxBytesToMove,
uint32_t& maxAllocationsToMove);
void DestroyDefragmentator();
private:
friend class VmaDefragmentator;
const VmaAllocator m_hAllocator;
const uint32_t m_MemoryTypeIndex;
const VkDeviceSize m_PreferredBlockSize;
const size_t m_MinBlockCount;
const size_t m_MaxBlockCount;
const VkDeviceSize m_BufferImageGranularity;
const uint32_t m_FrameInUseCount;
const bool m_IsCustomPool;
VMA_MUTEX m_Mutex;
// Incrementally sorted by sumFreeSize, ascending.
VmaVector< VmaDeviceMemoryBlock*, VmaStlAllocator<VmaDeviceMemoryBlock*> > m_Blocks;
/* There can be at most one allocation that is completely empty - a
hysteresis to avoid pessimistic case of alternating creation and destruction
of a VkDeviceMemory. */
bool m_HasEmptyBlock;
VmaDefragmentator* m_pDefragmentator;
size_t CalcMaxBlockSize() const;
// Finds and removes given block from vector.
void Remove(VmaDeviceMemoryBlock* pBlock);
// Performs single step in sorting m_Blocks. They may not be fully sorted
// after this call.
void IncrementallySortBlocks();
VkResult CreateBlock(VkDeviceSize blockSize, size_t* pNewBlockIndex);
};
struct VmaPool_T
{
public:
VmaBlockVector m_BlockVector;
// Takes ownership.
VmaPool_T(
VmaAllocator hAllocator,
const VmaPoolCreateInfo& createInfo);
~VmaPool_T();
VmaBlockVector& GetBlockVector() { return m_BlockVector; }
#if VMA_STATS_STRING_ENABLED
//void PrintDetailedMap(class VmaStringBuilder& sb);
#endif
};
class VmaDefragmentator
{
const VmaAllocator m_hAllocator;
VmaBlockVector* const m_pBlockVector;
uint32_t m_CurrentFrameIndex;
VkDeviceSize m_BytesMoved;
uint32_t m_AllocationsMoved;
struct AllocationInfo
{
VmaAllocation m_hAllocation;
VkBool32* m_pChanged;
AllocationInfo() :
m_hAllocation(VK_NULL_HANDLE),
m_pChanged(VMA_NULL)
{
}
};
struct AllocationInfoSizeGreater
{
bool operator()(const AllocationInfo& lhs, const AllocationInfo& rhs) const
{
return lhs.m_hAllocation->GetSize() > rhs.m_hAllocation->GetSize();
}
};
// Used between AddAllocation and Defragment.
VmaVector< AllocationInfo, VmaStlAllocator<AllocationInfo> > m_Allocations;
struct BlockInfo
{
VmaDeviceMemoryBlock* m_pBlock;
bool m_HasNonMovableAllocations;
VmaVector< AllocationInfo, VmaStlAllocator<AllocationInfo> > m_Allocations;
BlockInfo(const VkAllocationCallbacks* pAllocationCallbacks) :
m_pBlock(VMA_NULL),
m_HasNonMovableAllocations(true),
m_Allocations(pAllocationCallbacks),
m_pMappedDataForDefragmentation(VMA_NULL)
{
}
void CalcHasNonMovableAllocations()
{
const size_t blockAllocCount = m_pBlock->m_Metadata.GetAllocationCount();
const size_t defragmentAllocCount = m_Allocations.size();
m_HasNonMovableAllocations = blockAllocCount != defragmentAllocCount;
}
void SortAllocationsBySizeDescecnding()
{
VMA_SORT(m_Allocations.begin(), m_Allocations.end(), AllocationInfoSizeGreater());
}
VkResult EnsureMapping(VmaAllocator hAllocator, void** ppMappedData);
void Unmap(VmaAllocator hAllocator);
private:
// Not null if mapped for defragmentation only, not originally mapped.
void* m_pMappedDataForDefragmentation;
};
struct BlockPointerLess
{
bool operator()(const BlockInfo* pLhsBlockInfo, const VmaDeviceMemoryBlock* pRhsBlock) const
{
return pLhsBlockInfo->m_pBlock < pRhsBlock;
}
bool operator()(const BlockInfo* pLhsBlockInfo, const BlockInfo* pRhsBlockInfo) const
{
return pLhsBlockInfo->m_pBlock < pRhsBlockInfo->m_pBlock;
}
};
// 1. Blocks with some non-movable allocations go first.
// 2. Blocks with smaller sumFreeSize go first.
struct BlockInfoCompareMoveDestination
{
bool operator()(const BlockInfo* pLhsBlockInfo, const BlockInfo* pRhsBlockInfo) const
{
if(pLhsBlockInfo->m_HasNonMovableAllocations && !pRhsBlockInfo->m_HasNonMovableAllocations)
{
return true;
}
if(!pLhsBlockInfo->m_HasNonMovableAllocations && pRhsBlockInfo->m_HasNonMovableAllocations)
{
return false;
}
if(pLhsBlockInfo->m_pBlock->m_Metadata.GetSumFreeSize() < pRhsBlockInfo->m_pBlock->m_Metadata.GetSumFreeSize())
{
return true;
}
return false;
}
};
typedef VmaVector< BlockInfo*, VmaStlAllocator<BlockInfo*> > BlockInfoVector;
BlockInfoVector m_Blocks;
VkResult DefragmentRound(
VkDeviceSize maxBytesToMove,
uint32_t maxAllocationsToMove);
static bool MoveMakesSense(
size_t dstBlockIndex, VkDeviceSize dstOffset,
size_t srcBlockIndex, VkDeviceSize srcOffset);
public:
VmaDefragmentator(
VmaAllocator hAllocator,
VmaBlockVector* pBlockVector,
uint32_t currentFrameIndex);
~VmaDefragmentator();
VkDeviceSize GetBytesMoved() const { return m_BytesMoved; }
uint32_t GetAllocationsMoved() const { return m_AllocationsMoved; }
void AddAllocation(VmaAllocation hAlloc, VkBool32* pChanged);
VkResult Defragment(
VkDeviceSize maxBytesToMove,
uint32_t maxAllocationsToMove);
};
// Main allocator object.
struct VmaAllocator_T
{
bool m_UseMutex;
bool m_UseKhrDedicatedAllocation;
VkDevice m_hDevice;
bool m_AllocationCallbacksSpecified;
VkAllocationCallbacks m_AllocationCallbacks;
VmaDeviceMemoryCallbacks m_DeviceMemoryCallbacks;
// Number of bytes free out of limit, or VK_WHOLE_SIZE if not limit for that heap.
VkDeviceSize m_HeapSizeLimit[VK_MAX_MEMORY_HEAPS];
VMA_MUTEX m_HeapSizeLimitMutex;
VkPhysicalDeviceProperties m_PhysicalDeviceProperties;
VkPhysicalDeviceMemoryProperties m_MemProps;
// Default pools.
VmaBlockVector* m_pBlockVectors[VK_MAX_MEMORY_TYPES];
// Each vector is sorted by memory (handle value).
typedef VmaVector< VmaAllocation, VmaStlAllocator<VmaAllocation> > AllocationVectorType;
AllocationVectorType* m_pDedicatedAllocations[VK_MAX_MEMORY_TYPES];
VMA_MUTEX m_DedicatedAllocationsMutex[VK_MAX_MEMORY_TYPES];
VmaAllocator_T(const VmaAllocatorCreateInfo* pCreateInfo);
~VmaAllocator_T();
const VkAllocationCallbacks* GetAllocationCallbacks() const
{
return m_AllocationCallbacksSpecified ? &m_AllocationCallbacks : 0;
}
const VmaVulkanFunctions& GetVulkanFunctions() const
{
return m_VulkanFunctions;
}
VkDeviceSize GetBufferImageGranularity() const
{
return VMA_MAX(
static_cast<VkDeviceSize>(VMA_DEBUG_MIN_BUFFER_IMAGE_GRANULARITY),
m_PhysicalDeviceProperties.limits.bufferImageGranularity);
}
uint32_t GetMemoryHeapCount() const { return m_MemProps.memoryHeapCount; }
uint32_t GetMemoryTypeCount() const { return m_MemProps.memoryTypeCount; }
uint32_t MemoryTypeIndexToHeapIndex(uint32_t memTypeIndex) const
{
VMA_ASSERT(memTypeIndex < m_MemProps.memoryTypeCount);
return m_MemProps.memoryTypes[memTypeIndex].heapIndex;
}
void GetBufferMemoryRequirements(
VkBuffer hBuffer,
VkMemoryRequirements& memReq,
bool& requiresDedicatedAllocation,
bool& prefersDedicatedAllocation) const;
void GetImageMemoryRequirements(
VkImage hImage,
VkMemoryRequirements& memReq,
bool& requiresDedicatedAllocation,
bool& prefersDedicatedAllocation) const;
// Main allocation function.
VkResult AllocateMemory(
const VkMemoryRequirements& vkMemReq,
bool requiresDedicatedAllocation,
bool prefersDedicatedAllocation,
VkBuffer dedicatedBuffer,
VkImage dedicatedImage,
const VmaAllocationCreateInfo& createInfo,
VmaSuballocationType suballocType,
VmaAllocation* pAllocation);
// Main deallocation function.
void FreeMemory(const VmaAllocation allocation);
void CalculateStats(VmaStats* pStats);
#if VMA_STATS_STRING_ENABLED
void PrintDetailedMap(class VmaJsonWriter& json);
#endif
VkResult Defragment(
VmaAllocation* pAllocations,
size_t allocationCount,
VkBool32* pAllocationsChanged,
const VmaDefragmentationInfo* pDefragmentationInfo,
VmaDefragmentationStats* pDefragmentationStats);
void GetAllocationInfo(VmaAllocation hAllocation, VmaAllocationInfo* pAllocationInfo);
bool TouchAllocation(VmaAllocation hAllocation);
VkResult CreatePool(const VmaPoolCreateInfo* pCreateInfo, VmaPool* pPool);
void DestroyPool(VmaPool pool);
void GetPoolStats(VmaPool pool, VmaPoolStats* pPoolStats);
void SetCurrentFrameIndex(uint32_t frameIndex);
void MakePoolAllocationsLost(
VmaPool hPool,
size_t* pLostAllocationCount);
void CreateLostAllocation(VmaAllocation* pAllocation);
VkResult AllocateVulkanMemory(const VkMemoryAllocateInfo* pAllocateInfo, VkDeviceMemory* pMemory);
void FreeVulkanMemory(uint32_t memoryType, VkDeviceSize size, VkDeviceMemory hMemory);
VkResult Map(VmaAllocation hAllocation, void** ppData);
void Unmap(VmaAllocation hAllocation);
VkResult BindBufferMemory(VmaAllocation hAllocation, VkBuffer hBuffer);
VkResult BindImageMemory(VmaAllocation hAllocation, VkImage hImage);
private:
VkDeviceSize m_PreferredLargeHeapBlockSize;
VkPhysicalDevice m_PhysicalDevice;
VMA_ATOMIC_UINT32 m_CurrentFrameIndex;
VMA_MUTEX m_PoolsMutex;
// Protected by m_PoolsMutex. Sorted by pointer value.
VmaVector<VmaPool, VmaStlAllocator<VmaPool> > m_Pools;
VmaVulkanFunctions m_VulkanFunctions;
void ImportVulkanFunctions(const VmaVulkanFunctions* pVulkanFunctions);
VkDeviceSize CalcPreferredBlockSize(uint32_t memTypeIndex);
VkResult AllocateMemoryOfType(
const VkMemoryRequirements& vkMemReq,
bool dedicatedAllocation,
VkBuffer dedicatedBuffer,
VkImage dedicatedImage,
const VmaAllocationCreateInfo& createInfo,
uint32_t memTypeIndex,
VmaSuballocationType suballocType,
VmaAllocation* pAllocation);
// Allocates and registers new VkDeviceMemory specifically for single allocation.
VkResult AllocateDedicatedMemory(
VkDeviceSize size,
VmaSuballocationType suballocType,
uint32_t memTypeIndex,
bool map,
bool isUserDataString,
void* pUserData,
VkBuffer dedicatedBuffer,
VkImage dedicatedImage,
VmaAllocation* pAllocation);
// Tries to free pMemory as Dedicated Memory. Returns true if found and freed.
void FreeDedicatedMemory(VmaAllocation allocation);
};
////////////////////////////////////////////////////////////////////////////////
// Memory allocation #2 after VmaAllocator_T definition
static void* VmaMalloc(VmaAllocator hAllocator, size_t size, size_t alignment)
{
return VmaMalloc(&hAllocator->m_AllocationCallbacks, size, alignment);
}
static void VmaFree(VmaAllocator hAllocator, void* ptr)
{
VmaFree(&hAllocator->m_AllocationCallbacks, ptr);
}
template<typename T>
static T* VmaAllocate(VmaAllocator hAllocator)
{
return (T*)VmaMalloc(hAllocator, sizeof(T), VMA_ALIGN_OF(T));
}
template<typename T>
static T* VmaAllocateArray(VmaAllocator hAllocator, size_t count)
{
return (T*)VmaMalloc(hAllocator, sizeof(T) * count, VMA_ALIGN_OF(T));
}
template<typename T>
static void vma_delete(VmaAllocator hAllocator, T* ptr)
{
if(ptr != VMA_NULL)
{
ptr->~T();
VmaFree(hAllocator, ptr);
}
}
template<typename T>
static void vma_delete_array(VmaAllocator hAllocator, T* ptr, size_t count)
{
if(ptr != VMA_NULL)
{
for(size_t i = count; i--; )
ptr[i].~T();
VmaFree(hAllocator, ptr);
}
}
////////////////////////////////////////////////////////////////////////////////
// VmaStringBuilder
#if VMA_STATS_STRING_ENABLED
class VmaStringBuilder
{
public:
VmaStringBuilder(VmaAllocator alloc) : m_Data(VmaStlAllocator<char>(alloc->GetAllocationCallbacks())) { }
size_t GetLength() const { return m_Data.size(); }
const char* GetData() const { return m_Data.data(); }
void Add(char ch) { m_Data.push_back(ch); }
void Add(const char* pStr);
void AddNewLine() { Add('\n'); }
void AddNumber(uint32_t num);
void AddNumber(uint64_t num);
void AddPointer(const void* ptr);
private:
VmaVector< char, VmaStlAllocator<char> > m_Data;
};
void VmaStringBuilder::Add(const char* pStr)
{
const size_t strLen = strlen(pStr);
if(strLen > 0)
{
const size_t oldCount = m_Data.size();
m_Data.resize(oldCount + strLen);
memcpy(m_Data.data() + oldCount, pStr, strLen);
}
}
void VmaStringBuilder::AddNumber(uint32_t num)
{
char buf[11];
VmaUint32ToStr(buf, sizeof(buf), num);
Add(buf);
}
void VmaStringBuilder::AddNumber(uint64_t num)
{
char buf[21];
VmaUint64ToStr(buf, sizeof(buf), num);
Add(buf);
}
void VmaStringBuilder::AddPointer(const void* ptr)
{
char buf[21];
VmaPtrToStr(buf, sizeof(buf), ptr);
Add(buf);
}
#endif // #if VMA_STATS_STRING_ENABLED
////////////////////////////////////////////////////////////////////////////////
// VmaJsonWriter
#if VMA_STATS_STRING_ENABLED
class VmaJsonWriter
{
public:
VmaJsonWriter(const VkAllocationCallbacks* pAllocationCallbacks, VmaStringBuilder& sb);
~VmaJsonWriter();
void BeginObject(bool singleLine = false);
void EndObject();
void BeginArray(bool singleLine = false);
void EndArray();
void WriteString(const char* pStr);
void BeginString(const char* pStr = VMA_NULL);
void ContinueString(const char* pStr);
void ContinueString(uint32_t n);
void ContinueString(uint64_t n);
void ContinueString_Pointer(const void* ptr);
void EndString(const char* pStr = VMA_NULL);
void WriteNumber(uint32_t n);
void WriteNumber(uint64_t n);
void WriteBool(bool b);
void WriteNull();
private:
static const char* const INDENT;
enum COLLECTION_TYPE
{
COLLECTION_TYPE_OBJECT,
COLLECTION_TYPE_ARRAY,
};
struct StackItem
{
COLLECTION_TYPE type;
uint32_t valueCount;
bool singleLineMode;
};
VmaStringBuilder& m_SB;
VmaVector< StackItem, VmaStlAllocator<StackItem> > m_Stack;
bool m_InsideString;
void BeginValue(bool isString);
void WriteIndent(bool oneLess = false);
};
const char* const VmaJsonWriter::INDENT = " ";
VmaJsonWriter::VmaJsonWriter(const VkAllocationCallbacks* pAllocationCallbacks, VmaStringBuilder& sb) :
m_SB(sb),
m_Stack(VmaStlAllocator<StackItem>(pAllocationCallbacks)),
m_InsideString(false)
{
}
VmaJsonWriter::~VmaJsonWriter()
{
VMA_ASSERT(!m_InsideString);
VMA_ASSERT(m_Stack.empty());
}
void VmaJsonWriter::BeginObject(bool singleLine)
{
VMA_ASSERT(!m_InsideString);
BeginValue(false);
m_SB.Add('{');
StackItem item;
item.type = COLLECTION_TYPE_OBJECT;
item.valueCount = 0;
item.singleLineMode = singleLine;
m_Stack.push_back(item);
}
void VmaJsonWriter::EndObject()
{
VMA_ASSERT(!m_InsideString);
WriteIndent(true);
m_SB.Add('}');
VMA_ASSERT(!m_Stack.empty() && m_Stack.back().type == COLLECTION_TYPE_OBJECT);
m_Stack.pop_back();
}
void VmaJsonWriter::BeginArray(bool singleLine)
{
VMA_ASSERT(!m_InsideString);
BeginValue(false);
m_SB.Add('[');
StackItem item;
item.type = COLLECTION_TYPE_ARRAY;
item.valueCount = 0;
item.singleLineMode = singleLine;
m_Stack.push_back(item);
}
void VmaJsonWriter::EndArray()
{
VMA_ASSERT(!m_InsideString);
WriteIndent(true);
m_SB.Add(']');
VMA_ASSERT(!m_Stack.empty() && m_Stack.back().type == COLLECTION_TYPE_ARRAY);
m_Stack.pop_back();
}
void VmaJsonWriter::WriteString(const char* pStr)
{
BeginString(pStr);
EndString();
}
void VmaJsonWriter::BeginString(const char* pStr)
{
VMA_ASSERT(!m_InsideString);
BeginValue(true);
m_SB.Add('"');
m_InsideString = true;
if(pStr != VMA_NULL && pStr[0] != '\0')
{
ContinueString(pStr);
}
}
void VmaJsonWriter::ContinueString(const char* pStr)
{
VMA_ASSERT(m_InsideString);
const size_t strLen = strlen(pStr);
for(size_t i = 0; i < strLen; ++i)
{
char ch = pStr[i];
if(ch == '\'')
{
m_SB.Add("\\\\");
}
else if(ch == '"')
{
m_SB.Add("\\\"");
}
else if(ch >= 32)
{
m_SB.Add(ch);
}
else switch(ch)
{
case '\b':
m_SB.Add("\\b");
break;
case '\f':
m_SB.Add("\\f");
break;
case '\n':
m_SB.Add("\\n");
break;
case '\r':
m_SB.Add("\\r");
break;
case '\t':
m_SB.Add("\\t");
break;
default:
VMA_ASSERT(0 && "Character not currently supported.");
break;
}
}
}
void VmaJsonWriter::ContinueString(uint32_t n)
{
VMA_ASSERT(m_InsideString);
m_SB.AddNumber(n);
}
void VmaJsonWriter::ContinueString(uint64_t n)
{
VMA_ASSERT(m_InsideString);
m_SB.AddNumber(n);
}
void VmaJsonWriter::ContinueString_Pointer(const void* ptr)
{
VMA_ASSERT(m_InsideString);
m_SB.AddPointer(ptr);
}
void VmaJsonWriter::EndString(const char* pStr)
{
VMA_ASSERT(m_InsideString);
if(pStr != VMA_NULL && pStr[0] != '\0')
{
ContinueString(pStr);
}
m_SB.Add('"');
m_InsideString = false;
}
void VmaJsonWriter::WriteNumber(uint32_t n)
{
VMA_ASSERT(!m_InsideString);
BeginValue(false);
m_SB.AddNumber(n);
}
void VmaJsonWriter::WriteNumber(uint64_t n)
{
VMA_ASSERT(!m_InsideString);
BeginValue(false);
m_SB.AddNumber(n);
}
void VmaJsonWriter::WriteBool(bool b)
{
VMA_ASSERT(!m_InsideString);
BeginValue(false);
m_SB.Add(b ? "true" : "false");
}
void VmaJsonWriter::WriteNull()
{
VMA_ASSERT(!m_InsideString);
BeginValue(false);
m_SB.Add("null");
}
void VmaJsonWriter::BeginValue(bool isString)
{
if(!m_Stack.empty())
{
StackItem& currItem = m_Stack.back();
if(currItem.type == COLLECTION_TYPE_OBJECT &&
currItem.valueCount % 2 == 0)
{
VMA_ASSERT(isString);
}
if(currItem.type == COLLECTION_TYPE_OBJECT &&
currItem.valueCount % 2 != 0)
{
m_SB.Add(": ");
}
else if(currItem.valueCount > 0)
{
m_SB.Add(", ");
WriteIndent();
}
else
{
WriteIndent();
}
++currItem.valueCount;
}
}
void VmaJsonWriter::WriteIndent(bool oneLess)
{
if(!m_Stack.empty() && !m_Stack.back().singleLineMode)
{
m_SB.AddNewLine();
size_t count = m_Stack.size();
if(count > 0 && oneLess)
{
--count;
}
for(size_t i = 0; i < count; ++i)
{
m_SB.Add(INDENT);
}
}
}
#endif // #if VMA_STATS_STRING_ENABLED
////////////////////////////////////////////////////////////////////////////////
void VmaAllocation_T::SetUserData(VmaAllocator hAllocator, void* pUserData)
{
if(IsUserDataString())
{
VMA_ASSERT(pUserData == VMA_NULL || pUserData != m_pUserData);
FreeUserDataString(hAllocator);
if(pUserData != VMA_NULL)
{
const char* const newStrSrc = (char*)pUserData;
const size_t newStrLen = strlen(newStrSrc);
char* const newStrDst = vma_new_array(hAllocator, char, newStrLen + 1);
memcpy(newStrDst, newStrSrc, newStrLen + 1);
m_pUserData = newStrDst;
}
}
else
{
m_pUserData = pUserData;
}
}
void VmaAllocation_T::ChangeBlockAllocation(
VmaAllocator hAllocator,
VmaDeviceMemoryBlock* block,
VkDeviceSize offset)
{
VMA_ASSERT(block != VMA_NULL);
VMA_ASSERT(m_Type == ALLOCATION_TYPE_BLOCK);
// Move mapping reference counter from old block to new block.
if(block != m_BlockAllocation.m_Block)
{
uint32_t mapRefCount = m_MapCount & ~MAP_COUNT_FLAG_PERSISTENT_MAP;
if(IsPersistentMap())
++mapRefCount;
m_BlockAllocation.m_Block->Unmap(hAllocator, mapRefCount);
block->Map(hAllocator, mapRefCount, VMA_NULL);
}
m_BlockAllocation.m_Block = block;
m_BlockAllocation.m_Offset = offset;
}
VkDeviceSize VmaAllocation_T::GetOffset() const
{
switch(m_Type)
{
case ALLOCATION_TYPE_BLOCK:
return m_BlockAllocation.m_Offset;
case ALLOCATION_TYPE_DEDICATED:
return 0;
default:
VMA_ASSERT(0);
return 0;
}
}
VkDeviceMemory VmaAllocation_T::GetMemory() const
{
switch(m_Type)
{
case ALLOCATION_TYPE_BLOCK:
return m_BlockAllocation.m_Block->GetDeviceMemory();
case ALLOCATION_TYPE_DEDICATED:
return m_DedicatedAllocation.m_hMemory;
default:
VMA_ASSERT(0);
return VK_NULL_HANDLE;
}
}
uint32_t VmaAllocation_T::GetMemoryTypeIndex() const
{
switch(m_Type)
{
case ALLOCATION_TYPE_BLOCK:
return m_BlockAllocation.m_Block->GetMemoryTypeIndex();
case ALLOCATION_TYPE_DEDICATED:
return m_DedicatedAllocation.m_MemoryTypeIndex;
default:
VMA_ASSERT(0);
return UINT32_MAX;
}
}
void* VmaAllocation_T::GetMappedData() const
{
switch(m_Type)
{
case ALLOCATION_TYPE_BLOCK:
if(m_MapCount != 0)
{
void* pBlockData = m_BlockAllocation.m_Block->GetMappedData();
VMA_ASSERT(pBlockData != VMA_NULL);
return (char*)pBlockData + m_BlockAllocation.m_Offset;
}
else
{
return VMA_NULL;
}
break;
case ALLOCATION_TYPE_DEDICATED:
VMA_ASSERT((m_DedicatedAllocation.m_pMappedData != VMA_NULL) == (m_MapCount != 0));
return m_DedicatedAllocation.m_pMappedData;
default:
VMA_ASSERT(0);
return VMA_NULL;
}
}
bool VmaAllocation_T::CanBecomeLost() const
{
switch(m_Type)
{
case ALLOCATION_TYPE_BLOCK:
return m_BlockAllocation.m_CanBecomeLost;
case ALLOCATION_TYPE_DEDICATED:
return false;
default:
VMA_ASSERT(0);
return false;
}
}
VmaPool VmaAllocation_T::GetPool() const
{
VMA_ASSERT(m_Type == ALLOCATION_TYPE_BLOCK);
return m_BlockAllocation.m_hPool;
}
bool VmaAllocation_T::MakeLost(uint32_t currentFrameIndex, uint32_t frameInUseCount)
{
VMA_ASSERT(CanBecomeLost());
/*
Warning: This is a carefully designed algorithm.
Do not modify unless you really know what you're doing :)
*/
uint32_t localLastUseFrameIndex = GetLastUseFrameIndex();
for(;;)
{
if(localLastUseFrameIndex == VMA_FRAME_INDEX_LOST)
{
VMA_ASSERT(0);
return false;
}
else if(localLastUseFrameIndex + frameInUseCount >= currentFrameIndex)
{
return false;
}
else // Last use time earlier than current time.
{
if(CompareExchangeLastUseFrameIndex(localLastUseFrameIndex, VMA_FRAME_INDEX_LOST))
{
// Setting hAllocation.LastUseFrameIndex atomic to VMA_FRAME_INDEX_LOST is enough to mark it as LOST.
// Calling code just needs to unregister this allocation in owning VmaDeviceMemoryBlock.
return true;
}
}
}
}
void VmaAllocation_T::FreeUserDataString(VmaAllocator hAllocator)
{
VMA_ASSERT(IsUserDataString());
if(m_pUserData != VMA_NULL)
{
char* const oldStr = (char*)m_pUserData;
const size_t oldStrLen = strlen(oldStr);
vma_delete_array(hAllocator, oldStr, oldStrLen + 1);
m_pUserData = VMA_NULL;
}
}
void VmaAllocation_T::BlockAllocMap()
{
VMA_ASSERT(GetType() == ALLOCATION_TYPE_BLOCK);
if((m_MapCount & ~MAP_COUNT_FLAG_PERSISTENT_MAP) < 0x7F)
{
++m_MapCount;
}
else
{
VMA_ASSERT(0 && "Allocation mapped too many times simultaneously.");
}
}
void VmaAllocation_T::BlockAllocUnmap()
{
VMA_ASSERT(GetType() == ALLOCATION_TYPE_BLOCK);
if((m_MapCount & ~MAP_COUNT_FLAG_PERSISTENT_MAP) != 0)
{
--m_MapCount;
}
else
{
VMA_ASSERT(0 && "Unmapping allocation not previously mapped.");
}
}
VkResult VmaAllocation_T::DedicatedAllocMap(VmaAllocator hAllocator, void** ppData)
{
VMA_ASSERT(GetType() == ALLOCATION_TYPE_DEDICATED);
if(m_MapCount != 0)
{
if((m_MapCount & ~MAP_COUNT_FLAG_PERSISTENT_MAP) < 0x7F)
{
VMA_ASSERT(m_DedicatedAllocation.m_pMappedData != VMA_NULL);
*ppData = m_DedicatedAllocation.m_pMappedData;
++m_MapCount;
return VK_SUCCESS;
}
else
{
VMA_ASSERT(0 && "Dedicated allocation mapped too many times simultaneously.");
return VK_ERROR_MEMORY_MAP_FAILED;
}
}
else
{
VkResult result = (*hAllocator->GetVulkanFunctions().vkMapMemory)(
hAllocator->m_hDevice,
m_DedicatedAllocation.m_hMemory,
0, // offset
VK_WHOLE_SIZE,
0, // flags
ppData);
if(result == VK_SUCCESS)
{
m_DedicatedAllocation.m_pMappedData = *ppData;
m_MapCount = 1;
}
return result;
}
}
void VmaAllocation_T::DedicatedAllocUnmap(VmaAllocator hAllocator)
{
VMA_ASSERT(GetType() == ALLOCATION_TYPE_DEDICATED);
if((m_MapCount & ~MAP_COUNT_FLAG_PERSISTENT_MAP) != 0)
{
--m_MapCount;
if(m_MapCount == 0)
{
m_DedicatedAllocation.m_pMappedData = VMA_NULL;
(*hAllocator->GetVulkanFunctions().vkUnmapMemory)(
hAllocator->m_hDevice,
m_DedicatedAllocation.m_hMemory);
}
}
else
{
VMA_ASSERT(0 && "Unmapping dedicated allocation not previously mapped.");
}
}
#if VMA_STATS_STRING_ENABLED
// Correspond to values of enum VmaSuballocationType.
static const char* VMA_SUBALLOCATION_TYPE_NAMES[] = {
"FREE",
"UNKNOWN",
"BUFFER",
"IMAGE_UNKNOWN",
"IMAGE_LINEAR",
"IMAGE_OPTIMAL",
};
static void VmaPrintStatInfo(VmaJsonWriter& json, const VmaStatInfo& stat)
{
json.BeginObject();
json.WriteString("Blocks");
json.WriteNumber(stat.blockCount);
json.WriteString("Allocations");
json.WriteNumber(stat.allocationCount);
json.WriteString("UnusedRanges");
json.WriteNumber(stat.unusedRangeCount);
json.WriteString("UsedBytes");
json.WriteNumber(stat.usedBytes);
json.WriteString("UnusedBytes");
json.WriteNumber(stat.unusedBytes);
if(stat.allocationCount > 1)
{
json.WriteString("AllocationSize");
json.BeginObject(true);
json.WriteString("Min");
json.WriteNumber(stat.allocationSizeMin);
json.WriteString("Avg");
json.WriteNumber(stat.allocationSizeAvg);
json.WriteString("Max");
json.WriteNumber(stat.allocationSizeMax);
json.EndObject();
}
if(stat.unusedRangeCount > 1)
{
json.WriteString("UnusedRangeSize");
json.BeginObject(true);
json.WriteString("Min");
json.WriteNumber(stat.unusedRangeSizeMin);
json.WriteString("Avg");
json.WriteNumber(stat.unusedRangeSizeAvg);
json.WriteString("Max");
json.WriteNumber(stat.unusedRangeSizeMax);
json.EndObject();
}
json.EndObject();
}
#endif // #if VMA_STATS_STRING_ENABLED
struct VmaSuballocationItemSizeLess
{
bool operator()(
const VmaSuballocationList::iterator lhs,
const VmaSuballocationList::iterator rhs) const
{
return lhs->size < rhs->size;
}
bool operator()(
const VmaSuballocationList::iterator lhs,
VkDeviceSize rhsSize) const
{
return lhs->size < rhsSize;
}
};
////////////////////////////////////////////////////////////////////////////////
// class VmaBlockMetadata
VmaBlockMetadata::VmaBlockMetadata(VmaAllocator hAllocator) :
m_Size(0),
m_FreeCount(0),
m_SumFreeSize(0),
m_Suballocations(VmaStlAllocator<VmaSuballocation>(hAllocator->GetAllocationCallbacks())),
m_FreeSuballocationsBySize(VmaStlAllocator<VmaSuballocationList::iterator>(hAllocator->GetAllocationCallbacks()))
{
}
VmaBlockMetadata::~VmaBlockMetadata()
{
}
void VmaBlockMetadata::Init(VkDeviceSize size)
{
m_Size = size;
m_FreeCount = 1;
m_SumFreeSize = size;
VmaSuballocation suballoc = {};
suballoc.offset = 0;
suballoc.size = size;
suballoc.type = VMA_SUBALLOCATION_TYPE_FREE;
suballoc.hAllocation = VK_NULL_HANDLE;
m_Suballocations.push_back(suballoc);
VmaSuballocationList::iterator suballocItem = m_Suballocations.end();
--suballocItem;
m_FreeSuballocationsBySize.push_back(suballocItem);
}
bool VmaBlockMetadata::Validate() const
{
if(m_Suballocations.empty())
{
return false;
}
// Expected offset of new suballocation as calculates from previous ones.
VkDeviceSize calculatedOffset = 0;
// Expected number of free suballocations as calculated from traversing their list.
uint32_t calculatedFreeCount = 0;
// Expected sum size of free suballocations as calculated from traversing their list.
VkDeviceSize calculatedSumFreeSize = 0;
// Expected number of free suballocations that should be registered in
// m_FreeSuballocationsBySize calculated from traversing their list.
size_t freeSuballocationsToRegister = 0;
// True if previous visisted suballocation was free.
bool prevFree = false;
for(VmaSuballocationList::const_iterator suballocItem = m_Suballocations.cbegin();
suballocItem != m_Suballocations.cend();
++suballocItem)
{
const VmaSuballocation& subAlloc = *suballocItem;
// Actual offset of this suballocation doesn't match expected one.
if(subAlloc.offset != calculatedOffset)
{
return false;
}
const bool currFree = (subAlloc.type == VMA_SUBALLOCATION_TYPE_FREE);
// Two adjacent free suballocations are invalid. They should be merged.
if(prevFree && currFree)
{
return false;
}
if(currFree != (subAlloc.hAllocation == VK_NULL_HANDLE))
{
return false;
}
if(currFree)
{
calculatedSumFreeSize += subAlloc.size;
++calculatedFreeCount;
if(subAlloc.size >= VMA_MIN_FREE_SUBALLOCATION_SIZE_TO_REGISTER)
{
++freeSuballocationsToRegister;
}
}
else
{
if(subAlloc.hAllocation->GetOffset() != subAlloc.offset)
{
return false;
}
if(subAlloc.hAllocation->GetSize() != subAlloc.size)
{
return false;
}
}
calculatedOffset += subAlloc.size;
prevFree = currFree;
}
// Number of free suballocations registered in m_FreeSuballocationsBySize doesn't
// match expected one.
if(m_FreeSuballocationsBySize.size() != freeSuballocationsToRegister)
{
return false;
}
VkDeviceSize lastSize = 0;
for(size_t i = 0; i < m_FreeSuballocationsBySize.size(); ++i)
{
VmaSuballocationList::iterator suballocItem = m_FreeSuballocationsBySize[i];
// Only free suballocations can be registered in m_FreeSuballocationsBySize.
if(suballocItem->type != VMA_SUBALLOCATION_TYPE_FREE)
{
return false;
}
// They must be sorted by size ascending.
if(suballocItem->size < lastSize)
{
return false;
}
lastSize = suballocItem->size;
}
// Check if totals match calculacted values.
if(!ValidateFreeSuballocationList() ||
(calculatedOffset != m_Size) ||
(calculatedSumFreeSize != m_SumFreeSize) ||
(calculatedFreeCount != m_FreeCount))
{
return false;
}
return true;
}
VkDeviceSize VmaBlockMetadata::GetUnusedRangeSizeMax() const
{
if(!m_FreeSuballocationsBySize.empty())
{
return m_FreeSuballocationsBySize.back()->size;
}
else
{
return 0;
}
}
bool VmaBlockMetadata::IsEmpty() const
{
return (m_Suballocations.size() == 1) && (m_FreeCount == 1);
}
void VmaBlockMetadata::CalcAllocationStatInfo(VmaStatInfo& outInfo) const
{
outInfo.blockCount = 1;
const uint32_t rangeCount = (uint32_t)m_Suballocations.size();
outInfo.allocationCount = rangeCount - m_FreeCount;
outInfo.unusedRangeCount = m_FreeCount;
outInfo.unusedBytes = m_SumFreeSize;
outInfo.usedBytes = m_Size - outInfo.unusedBytes;
outInfo.allocationSizeMin = UINT64_MAX;
outInfo.allocationSizeMax = 0;
outInfo.unusedRangeSizeMin = UINT64_MAX;
outInfo.unusedRangeSizeMax = 0;
for(VmaSuballocationList::const_iterator suballocItem = m_Suballocations.cbegin();
suballocItem != m_Suballocations.cend();
++suballocItem)
{
const VmaSuballocation& suballoc = *suballocItem;
if(suballoc.type != VMA_SUBALLOCATION_TYPE_FREE)
{
outInfo.allocationSizeMin = VMA_MIN(outInfo.allocationSizeMin, suballoc.size);
outInfo.allocationSizeMax = VMA_MAX(outInfo.allocationSizeMax, suballoc.size);
}
else
{
outInfo.unusedRangeSizeMin = VMA_MIN(outInfo.unusedRangeSizeMin, suballoc.size);
outInfo.unusedRangeSizeMax = VMA_MAX(outInfo.unusedRangeSizeMax, suballoc.size);
}
}
}
void VmaBlockMetadata::AddPoolStats(VmaPoolStats& inoutStats) const
{
const uint32_t rangeCount = (uint32_t)m_Suballocations.size();
inoutStats.size += m_Size;
inoutStats.unusedSize += m_SumFreeSize;
inoutStats.allocationCount += rangeCount - m_FreeCount;
inoutStats.unusedRangeCount += m_FreeCount;
inoutStats.unusedRangeSizeMax = VMA_MAX(inoutStats.unusedRangeSizeMax, GetUnusedRangeSizeMax());
}
#if VMA_STATS_STRING_ENABLED
void VmaBlockMetadata::PrintDetailedMap(class VmaJsonWriter& json) const
{
json.BeginObject();
json.WriteString("TotalBytes");
json.WriteNumber(m_Size);
json.WriteString("UnusedBytes");
json.WriteNumber(m_SumFreeSize);
json.WriteString("Allocations");
json.WriteNumber((uint64_t)m_Suballocations.size() - m_FreeCount);
json.WriteString("UnusedRanges");
json.WriteNumber(m_FreeCount);
json.WriteString("Suballocations");
json.BeginArray();
size_t i = 0;
for(VmaSuballocationList::const_iterator suballocItem = m_Suballocations.cbegin();
suballocItem != m_Suballocations.cend();
++suballocItem, ++i)
{
json.BeginObject(true);
json.WriteString("Type");
json.WriteString(VMA_SUBALLOCATION_TYPE_NAMES[suballocItem->type]);
json.WriteString("Size");
json.WriteNumber(suballocItem->size);
json.WriteString("Offset");
json.WriteNumber(suballocItem->offset);
if(suballocItem->type != VMA_SUBALLOCATION_TYPE_FREE)
{
const void* pUserData = suballocItem->hAllocation->GetUserData();
if(pUserData != VMA_NULL)
{
json.WriteString("UserData");
if(suballocItem->hAllocation->IsUserDataString())
{
json.WriteString((const char*)pUserData);
}
else
{
json.BeginString();
json.ContinueString_Pointer(pUserData);
json.EndString();
}
}
}
json.EndObject();
}
json.EndArray();
json.EndObject();
}
#endif // #if VMA_STATS_STRING_ENABLED
/*
How many suitable free suballocations to analyze before choosing best one.
- Set to 1 to use First-Fit algorithm - first suitable free suballocation will
be chosen.
- Set to UINT32_MAX to use Best-Fit/Worst-Fit algorithm - all suitable free
suballocations will be analized and best one will be chosen.
- Any other value is also acceptable.
*/
//static const uint32_t MAX_SUITABLE_SUBALLOCATIONS_TO_CHECK = 8;
void VmaBlockMetadata::CreateFirstAllocationRequest(VmaAllocationRequest* pAllocationRequest)
{
VMA_ASSERT(IsEmpty());
pAllocationRequest->offset = 0;
pAllocationRequest->sumFreeSize = m_SumFreeSize;
pAllocationRequest->sumItemSize = 0;
pAllocationRequest->item = m_Suballocations.begin();
pAllocationRequest->itemsToMakeLostCount = 0;
}
bool VmaBlockMetadata::CreateAllocationRequest(
uint32_t currentFrameIndex,
uint32_t frameInUseCount,
VkDeviceSize bufferImageGranularity,
VkDeviceSize allocSize,
VkDeviceSize allocAlignment,
VmaSuballocationType allocType,
bool canMakeOtherLost,
VmaAllocationRequest* pAllocationRequest)
{
VMA_ASSERT(allocSize > 0);
VMA_ASSERT(allocType != VMA_SUBALLOCATION_TYPE_FREE);
VMA_ASSERT(pAllocationRequest != VMA_NULL);
VMA_HEAVY_ASSERT(Validate());
// There is not enough total free space in this block to fullfill the request: Early return.
if(canMakeOtherLost == false && m_SumFreeSize < allocSize)
{
return false;
}
// New algorithm, efficiently searching freeSuballocationsBySize.
const size_t freeSuballocCount = m_FreeSuballocationsBySize.size();
if(freeSuballocCount > 0)
{
if(VMA_BEST_FIT)
{
// Find first free suballocation with size not less than allocSize.
VmaSuballocationList::iterator* const it = VmaBinaryFindFirstNotLess(
m_FreeSuballocationsBySize.data(),
m_FreeSuballocationsBySize.data() + freeSuballocCount,
allocSize,
VmaSuballocationItemSizeLess());
size_t index = it - m_FreeSuballocationsBySize.data();
for(; index < freeSuballocCount; ++index)
{
if(CheckAllocation(
currentFrameIndex,
frameInUseCount,
bufferImageGranularity,
allocSize,
allocAlignment,
allocType,
m_FreeSuballocationsBySize[index],
false, // canMakeOtherLost
&pAllocationRequest->offset,
&pAllocationRequest->itemsToMakeLostCount,
&pAllocationRequest->sumFreeSize,
&pAllocationRequest->sumItemSize))
{
pAllocationRequest->item = m_FreeSuballocationsBySize[index];
return true;
}
}
}
else
{
// Search staring from biggest suballocations.
for(size_t index = freeSuballocCount; index--; )
{
if(CheckAllocation(
currentFrameIndex,
frameInUseCount,
bufferImageGranularity,
allocSize,
allocAlignment,
allocType,
m_FreeSuballocationsBySize[index],
false, // canMakeOtherLost
&pAllocationRequest->offset,
&pAllocationRequest->itemsToMakeLostCount,
&pAllocationRequest->sumFreeSize,
&pAllocationRequest->sumItemSize))
{
pAllocationRequest->item = m_FreeSuballocationsBySize[index];
return true;
}
}
}
}
if(canMakeOtherLost)
{
// Brute-force algorithm. TODO: Come up with something better.
pAllocationRequest->sumFreeSize = VK_WHOLE_SIZE;
pAllocationRequest->sumItemSize = VK_WHOLE_SIZE;
VmaAllocationRequest tmpAllocRequest = {};
for(VmaSuballocationList::iterator suballocIt = m_Suballocations.begin();
suballocIt != m_Suballocations.end();
++suballocIt)
{
if(suballocIt->type == VMA_SUBALLOCATION_TYPE_FREE ||
suballocIt->hAllocation->CanBecomeLost())
{
if(CheckAllocation(
currentFrameIndex,
frameInUseCount,
bufferImageGranularity,
allocSize,
allocAlignment,
allocType,
suballocIt,
canMakeOtherLost,
&tmpAllocRequest.offset,
&tmpAllocRequest.itemsToMakeLostCount,
&tmpAllocRequest.sumFreeSize,
&tmpAllocRequest.sumItemSize))
{
tmpAllocRequest.item = suballocIt;
if(tmpAllocRequest.CalcCost() < pAllocationRequest->CalcCost())
{
*pAllocationRequest = tmpAllocRequest;
}
}
}
}
if(pAllocationRequest->sumItemSize != VK_WHOLE_SIZE)
{
return true;
}
}
return false;
}
bool VmaBlockMetadata::MakeRequestedAllocationsLost(
uint32_t currentFrameIndex,
uint32_t frameInUseCount,
VmaAllocationRequest* pAllocationRequest)
{
while(pAllocationRequest->itemsToMakeLostCount > 0)
{
if(pAllocationRequest->item->type == VMA_SUBALLOCATION_TYPE_FREE)
{
++pAllocationRequest->item;
}
VMA_ASSERT(pAllocationRequest->item != m_Suballocations.end());
VMA_ASSERT(pAllocationRequest->item->hAllocation != VK_NULL_HANDLE);
VMA_ASSERT(pAllocationRequest->item->hAllocation->CanBecomeLost());
if(pAllocationRequest->item->hAllocation->MakeLost(currentFrameIndex, frameInUseCount))
{
pAllocationRequest->item = FreeSuballocation(pAllocationRequest->item);
--pAllocationRequest->itemsToMakeLostCount;
}
else
{
return false;
}
}
VMA_HEAVY_ASSERT(Validate());
VMA_ASSERT(pAllocationRequest->item != m_Suballocations.end());
VMA_ASSERT(pAllocationRequest->item->type == VMA_SUBALLOCATION_TYPE_FREE);
return true;
}
uint32_t VmaBlockMetadata::MakeAllocationsLost(uint32_t currentFrameIndex, uint32_t frameInUseCount)
{
uint32_t lostAllocationCount = 0;
for(VmaSuballocationList::iterator it = m_Suballocations.begin();
it != m_Suballocations.end();
++it)
{
if(it->type != VMA_SUBALLOCATION_TYPE_FREE &&
it->hAllocation->CanBecomeLost() &&
it->hAllocation->MakeLost(currentFrameIndex, frameInUseCount))
{
it = FreeSuballocation(it);
++lostAllocationCount;
}
}
return lostAllocationCount;
}
void VmaBlockMetadata::Alloc(
const VmaAllocationRequest& request,
VmaSuballocationType type,
VkDeviceSize allocSize,
VmaAllocation hAllocation)
{
VMA_ASSERT(request.item != m_Suballocations.end());
VmaSuballocation& suballoc = *request.item;
// Given suballocation is a free block.
VMA_ASSERT(suballoc.type == VMA_SUBALLOCATION_TYPE_FREE);
// Given offset is inside this suballocation.
VMA_ASSERT(request.offset >= suballoc.offset);
const VkDeviceSize paddingBegin = request.offset - suballoc.offset;
VMA_ASSERT(suballoc.size >= paddingBegin + allocSize);
const VkDeviceSize paddingEnd = suballoc.size - paddingBegin - allocSize;
// Unregister this free suballocation from m_FreeSuballocationsBySize and update
// it to become used.
UnregisterFreeSuballocation(request.item);
suballoc.offset = request.offset;
suballoc.size = allocSize;
suballoc.type = type;
suballoc.hAllocation = hAllocation;
// If there are any free bytes remaining at the end, insert new free suballocation after current one.
if(paddingEnd)
{
VmaSuballocation paddingSuballoc = {};
paddingSuballoc.offset = request.offset + allocSize;
paddingSuballoc.size = paddingEnd;
paddingSuballoc.type = VMA_SUBALLOCATION_TYPE_FREE;
VmaSuballocationList::iterator next = request.item;
++next;
const VmaSuballocationList::iterator paddingEndItem =
m_Suballocations.insert(next, paddingSuballoc);
RegisterFreeSuballocation(paddingEndItem);
}
// If there are any free bytes remaining at the beginning, insert new free suballocation before current one.
if(paddingBegin)
{
VmaSuballocation paddingSuballoc = {};
paddingSuballoc.offset = request.offset - paddingBegin;
paddingSuballoc.size = paddingBegin;
paddingSuballoc.type = VMA_SUBALLOCATION_TYPE_FREE;
const VmaSuballocationList::iterator paddingBeginItem =
m_Suballocations.insert(request.item, paddingSuballoc);
RegisterFreeSuballocation(paddingBeginItem);
}
// Update totals.
m_FreeCount = m_FreeCount - 1;
if(paddingBegin > 0)
{
++m_FreeCount;
}
if(paddingEnd > 0)
{
++m_FreeCount;
}
m_SumFreeSize -= allocSize;
}
void VmaBlockMetadata::Free(const VmaAllocation allocation)
{
for(VmaSuballocationList::iterator suballocItem = m_Suballocations.begin();
suballocItem != m_Suballocations.end();
++suballocItem)
{
VmaSuballocation& suballoc = *suballocItem;
if(suballoc.hAllocation == allocation)
{
FreeSuballocation(suballocItem);
VMA_HEAVY_ASSERT(Validate());
return;
}
}
VMA_ASSERT(0 && "Not found!");
}
void VmaBlockMetadata::FreeAtOffset(VkDeviceSize offset)
{
for(VmaSuballocationList::iterator suballocItem = m_Suballocations.begin();
suballocItem != m_Suballocations.end();
++suballocItem)
{
VmaSuballocation& suballoc = *suballocItem;
if(suballoc.offset == offset)
{
FreeSuballocation(suballocItem);
return;
}
}
VMA_ASSERT(0 && "Not found!");
}
bool VmaBlockMetadata::ValidateFreeSuballocationList() const
{
VkDeviceSize lastSize = 0;
for(size_t i = 0, count = m_FreeSuballocationsBySize.size(); i < count; ++i)
{
const VmaSuballocationList::iterator it = m_FreeSuballocationsBySize[i];
if(it->type != VMA_SUBALLOCATION_TYPE_FREE)
{
VMA_ASSERT(0);
return false;
}
if(it->size < VMA_MIN_FREE_SUBALLOCATION_SIZE_TO_REGISTER)
{
VMA_ASSERT(0);
return false;
}
if(it->size < lastSize)
{
VMA_ASSERT(0);
return false;
}
lastSize = it->size;
}
return true;
}
bool VmaBlockMetadata::CheckAllocation(
uint32_t currentFrameIndex,
uint32_t frameInUseCount,
VkDeviceSize bufferImageGranularity,
VkDeviceSize allocSize,
VkDeviceSize allocAlignment,
VmaSuballocationType allocType,
VmaSuballocationList::const_iterator suballocItem,
bool canMakeOtherLost,
VkDeviceSize* pOffset,
size_t* itemsToMakeLostCount,
VkDeviceSize* pSumFreeSize,
VkDeviceSize* pSumItemSize) const
{
VMA_ASSERT(allocSize > 0);
VMA_ASSERT(allocType != VMA_SUBALLOCATION_TYPE_FREE);
VMA_ASSERT(suballocItem != m_Suballocations.cend());
VMA_ASSERT(pOffset != VMA_NULL);
*itemsToMakeLostCount = 0;
*pSumFreeSize = 0;
*pSumItemSize = 0;
if(canMakeOtherLost)
{
if(suballocItem->type == VMA_SUBALLOCATION_TYPE_FREE)
{
*pSumFreeSize = suballocItem->size;
}
else
{
if(suballocItem->hAllocation->CanBecomeLost() &&
suballocItem->hAllocation->GetLastUseFrameIndex() + frameInUseCount < currentFrameIndex)
{
++*itemsToMakeLostCount;
*pSumItemSize = suballocItem->size;
}
else
{
return false;
}
}
// Remaining size is too small for this request: Early return.
if(m_Size - suballocItem->offset < allocSize)
{
return false;
}
// Start from offset equal to beginning of this suballocation.
*pOffset = suballocItem->offset;
// Apply VMA_DEBUG_MARGIN at the beginning.
if((VMA_DEBUG_MARGIN > 0) && suballocItem != m_Suballocations.cbegin())
{
*pOffset += VMA_DEBUG_MARGIN;
}
// Apply alignment.
const VkDeviceSize alignment = VMA_MAX(allocAlignment, static_cast<VkDeviceSize>(VMA_DEBUG_ALIGNMENT));
*pOffset = VmaAlignUp(*pOffset, alignment);
// Check previous suballocations for BufferImageGranularity conflicts.
// Make bigger alignment if necessary.
if(bufferImageGranularity > 1)
{
bool bufferImageGranularityConflict = false;
VmaSuballocationList::const_iterator prevSuballocItem = suballocItem;
while(prevSuballocItem != m_Suballocations.cbegin())
{
--prevSuballocItem;
const VmaSuballocation& prevSuballoc = *prevSuballocItem;
if(VmaBlocksOnSamePage(prevSuballoc.offset, prevSuballoc.size, *pOffset, bufferImageGranularity))
{
if(VmaIsBufferImageGranularityConflict(prevSuballoc.type, allocType))
{
bufferImageGranularityConflict = true;
break;
}
}
else
// Already on previous page.
break;
}
if(bufferImageGranularityConflict)
{
*pOffset = VmaAlignUp(*pOffset, bufferImageGranularity);
}
}
// Now that we have final *pOffset, check if we are past suballocItem.
// If yes, return false - this function should be called for another suballocItem as starting point.
if(*pOffset >= suballocItem->offset + suballocItem->size)
{
return false;
}
// Calculate padding at the beginning based on current offset.
const VkDeviceSize paddingBegin = *pOffset - suballocItem->offset;
// Calculate required margin at the end if this is not last suballocation.
VmaSuballocationList::const_iterator next = suballocItem;
++next;
const VkDeviceSize requiredEndMargin =
(next != m_Suballocations.cend()) ? VMA_DEBUG_MARGIN : 0;
const VkDeviceSize totalSize = paddingBegin + allocSize + requiredEndMargin;
// Another early return check.
if(suballocItem->offset + totalSize > m_Size)
{
return false;
}
// Advance lastSuballocItem until desired size is reached.
// Update itemsToMakeLostCount.
VmaSuballocationList::const_iterator lastSuballocItem = suballocItem;
if(totalSize > suballocItem->size)
{
VkDeviceSize remainingSize = totalSize - suballocItem->size;
while(remainingSize > 0)
{
++lastSuballocItem;
if(lastSuballocItem == m_Suballocations.cend())
{
return false;
}
if(lastSuballocItem->type == VMA_SUBALLOCATION_TYPE_FREE)
{
*pSumFreeSize += lastSuballocItem->size;
}
else
{
VMA_ASSERT(lastSuballocItem->hAllocation != VK_NULL_HANDLE);
if(lastSuballocItem->hAllocation->CanBecomeLost() &&
lastSuballocItem->hAllocation->GetLastUseFrameIndex() + frameInUseCount < currentFrameIndex)
{
++*itemsToMakeLostCount;
*pSumItemSize += lastSuballocItem->size;
}
else
{
return false;
}
}
remainingSize = (lastSuballocItem->size < remainingSize) ?
remainingSize - lastSuballocItem->size : 0;
}
}
// Check next suballocations for BufferImageGranularity conflicts.
// If conflict exists, we must mark more allocations lost or fail.
if(bufferImageGranularity > 1)
{
VmaSuballocationList::const_iterator nextSuballocItem = lastSuballocItem;
++nextSuballocItem;
while(nextSuballocItem != m_Suballocations.cend())
{
const VmaSuballocation& nextSuballoc = *nextSuballocItem;
if(VmaBlocksOnSamePage(*pOffset, allocSize, nextSuballoc.offset, bufferImageGranularity))
{
if(VmaIsBufferImageGranularityConflict(allocType, nextSuballoc.type))
{
VMA_ASSERT(nextSuballoc.hAllocation != VK_NULL_HANDLE);
if(nextSuballoc.hAllocation->CanBecomeLost() &&
nextSuballoc.hAllocation->GetLastUseFrameIndex() + frameInUseCount < currentFrameIndex)
{
++*itemsToMakeLostCount;
}
else
{
return false;
}
}
}
else
{
// Already on next page.
break;
}
++nextSuballocItem;
}
}
}
else
{
const VmaSuballocation& suballoc = *suballocItem;
VMA_ASSERT(suballoc.type == VMA_SUBALLOCATION_TYPE_FREE);
*pSumFreeSize = suballoc.size;
// Size of this suballocation is too small for this request: Early return.
if(suballoc.size < allocSize)
{
return false;
}
// Start from offset equal to beginning of this suballocation.
*pOffset = suballoc.offset;
// Apply VMA_DEBUG_MARGIN at the beginning.
if((VMA_DEBUG_MARGIN > 0) && suballocItem != m_Suballocations.cbegin())
{
*pOffset += VMA_DEBUG_MARGIN;
}
// Apply alignment.
const VkDeviceSize alignment = VMA_MAX(allocAlignment, static_cast<VkDeviceSize>(VMA_DEBUG_ALIGNMENT));
*pOffset = VmaAlignUp(*pOffset, alignment);
// Check previous suballocations for BufferImageGranularity conflicts.
// Make bigger alignment if necessary.
if(bufferImageGranularity > 1)
{
bool bufferImageGranularityConflict = false;
VmaSuballocationList::const_iterator prevSuballocItem = suballocItem;
while(prevSuballocItem != m_Suballocations.cbegin())
{
--prevSuballocItem;
const VmaSuballocation& prevSuballoc = *prevSuballocItem;
if(VmaBlocksOnSamePage(prevSuballoc.offset, prevSuballoc.size, *pOffset, bufferImageGranularity))
{
if(VmaIsBufferImageGranularityConflict(prevSuballoc.type, allocType))
{
bufferImageGranularityConflict = true;
break;
}
}
else
// Already on previous page.
break;
}
if(bufferImageGranularityConflict)
{
*pOffset = VmaAlignUp(*pOffset, bufferImageGranularity);
}
}
// Calculate padding at the beginning based on current offset.
const VkDeviceSize paddingBegin = *pOffset - suballoc.offset;
// Calculate required margin at the end if this is not last suballocation.
VmaSuballocationList::const_iterator next = suballocItem;
++next;
const VkDeviceSize requiredEndMargin =
(next != m_Suballocations.cend()) ? VMA_DEBUG_MARGIN : 0;
// Fail if requested size plus margin before and after is bigger than size of this suballocation.
if(paddingBegin + allocSize + requiredEndMargin > suballoc.size)
{
return false;
}
// Check next suballocations for BufferImageGranularity conflicts.
// If conflict exists, allocation cannot be made here.
if(bufferImageGranularity > 1)
{
VmaSuballocationList::const_iterator nextSuballocItem = suballocItem;
++nextSuballocItem;
while(nextSuballocItem != m_Suballocations.cend())
{
const VmaSuballocation& nextSuballoc = *nextSuballocItem;
if(VmaBlocksOnSamePage(*pOffset, allocSize, nextSuballoc.offset, bufferImageGranularity))
{
if(VmaIsBufferImageGranularityConflict(allocType, nextSuballoc.type))
{
return false;
}
}
else
{
// Already on next page.
break;
}
++nextSuballocItem;
}
}
}
// All tests passed: Success. pOffset is already filled.
return true;
}
void VmaBlockMetadata::MergeFreeWithNext(VmaSuballocationList::iterator item)
{
VMA_ASSERT(item != m_Suballocations.end());
VMA_ASSERT(item->type == VMA_SUBALLOCATION_TYPE_FREE);
VmaSuballocationList::iterator nextItem = item;
++nextItem;
VMA_ASSERT(nextItem != m_Suballocations.end());
VMA_ASSERT(nextItem->type == VMA_SUBALLOCATION_TYPE_FREE);
item->size += nextItem->size;
--m_FreeCount;
m_Suballocations.erase(nextItem);
}
VmaSuballocationList::iterator VmaBlockMetadata::FreeSuballocation(VmaSuballocationList::iterator suballocItem)
{
// Change this suballocation to be marked as free.
VmaSuballocation& suballoc = *suballocItem;
suballoc.type = VMA_SUBALLOCATION_TYPE_FREE;
suballoc.hAllocation = VK_NULL_HANDLE;
// Update totals.
++m_FreeCount;
m_SumFreeSize += suballoc.size;
// Merge with previous and/or next suballocation if it's also free.
bool mergeWithNext = false;
bool mergeWithPrev = false;
VmaSuballocationList::iterator nextItem = suballocItem;
++nextItem;
if((nextItem != m_Suballocations.end()) && (nextItem->type == VMA_SUBALLOCATION_TYPE_FREE))
{
mergeWithNext = true;
}
VmaSuballocationList::iterator prevItem = suballocItem;
if(suballocItem != m_Suballocations.begin())
{
--prevItem;
if(prevItem->type == VMA_SUBALLOCATION_TYPE_FREE)
{
mergeWithPrev = true;
}
}
if(mergeWithNext)
{
UnregisterFreeSuballocation(nextItem);
MergeFreeWithNext(suballocItem);
}
if(mergeWithPrev)
{
UnregisterFreeSuballocation(prevItem);
MergeFreeWithNext(prevItem);
RegisterFreeSuballocation(prevItem);
return prevItem;
}
else
{
RegisterFreeSuballocation(suballocItem);
return suballocItem;
}
}
void VmaBlockMetadata::RegisterFreeSuballocation(VmaSuballocationList::iterator item)
{
VMA_ASSERT(item->type == VMA_SUBALLOCATION_TYPE_FREE);
VMA_ASSERT(item->size > 0);
// You may want to enable this validation at the beginning or at the end of
// this function, depending on what do you want to check.
VMA_HEAVY_ASSERT(ValidateFreeSuballocationList());
if(item->size >= VMA_MIN_FREE_SUBALLOCATION_SIZE_TO_REGISTER)
{
if(m_FreeSuballocationsBySize.empty())
{
m_FreeSuballocationsBySize.push_back(item);
}
else
{
VmaVectorInsertSorted<VmaSuballocationItemSizeLess>(m_FreeSuballocationsBySize, item);
}
}
//VMA_HEAVY_ASSERT(ValidateFreeSuballocationList());
}
void VmaBlockMetadata::UnregisterFreeSuballocation(VmaSuballocationList::iterator item)
{
VMA_ASSERT(item->type == VMA_SUBALLOCATION_TYPE_FREE);
VMA_ASSERT(item->size > 0);
// You may want to enable this validation at the beginning or at the end of
// this function, depending on what do you want to check.
VMA_HEAVY_ASSERT(ValidateFreeSuballocationList());
if(item->size >= VMA_MIN_FREE_SUBALLOCATION_SIZE_TO_REGISTER)
{
VmaSuballocationList::iterator* const it = VmaBinaryFindFirstNotLess(
m_FreeSuballocationsBySize.data(),
m_FreeSuballocationsBySize.data() + m_FreeSuballocationsBySize.size(),
item,
VmaSuballocationItemSizeLess());
for(size_t index = it - m_FreeSuballocationsBySize.data();
index < m_FreeSuballocationsBySize.size();
++index)
{
if(m_FreeSuballocationsBySize[index] == item)
{
VmaVectorRemove(m_FreeSuballocationsBySize, index);
return;
}
VMA_ASSERT((m_FreeSuballocationsBySize[index]->size == item->size) && "Not found.");
}
VMA_ASSERT(0 && "Not found.");
}
//VMA_HEAVY_ASSERT(ValidateFreeSuballocationList());
}
////////////////////////////////////////////////////////////////////////////////
// class VmaDeviceMemoryBlock
VmaDeviceMemoryBlock::VmaDeviceMemoryBlock(VmaAllocator hAllocator) :
m_Metadata(hAllocator),
m_MemoryTypeIndex(UINT32_MAX),
m_hMemory(VK_NULL_HANDLE),
m_MapCount(0),
m_pMappedData(VMA_NULL)
{
}
void VmaDeviceMemoryBlock::Init(
uint32_t newMemoryTypeIndex,
VkDeviceMemory newMemory,
VkDeviceSize newSize)
{
VMA_ASSERT(m_hMemory == VK_NULL_HANDLE);
m_MemoryTypeIndex = newMemoryTypeIndex;
m_hMemory = newMemory;
m_Metadata.Init(newSize);
}
void VmaDeviceMemoryBlock::Destroy(VmaAllocator allocator)
{
// This is the most important assert in the entire library.
// Hitting it means you have some memory leak - unreleased VmaAllocation objects.
VMA_ASSERT(m_Metadata.IsEmpty() && "Some allocations were not freed before destruction of this memory block!");
VMA_ASSERT(m_hMemory != VK_NULL_HANDLE);
allocator->FreeVulkanMemory(m_MemoryTypeIndex, m_Metadata.GetSize(), m_hMemory);
m_hMemory = VK_NULL_HANDLE;
}
bool VmaDeviceMemoryBlock::Validate() const
{
if((m_hMemory == VK_NULL_HANDLE) ||
(m_Metadata.GetSize() == 0))
{
return false;
}
return m_Metadata.Validate();
}
VkResult VmaDeviceMemoryBlock::Map(VmaAllocator hAllocator, uint32_t count, void** ppData)
{
if(count == 0)
{
return VK_SUCCESS;
}
VmaMutexLock lock(m_Mutex, hAllocator->m_UseMutex);
if(m_MapCount != 0)
{
m_MapCount += count;
VMA_ASSERT(m_pMappedData != VMA_NULL);
if(ppData != VMA_NULL)
{
*ppData = m_pMappedData;
}
return VK_SUCCESS;
}
else
{
VkResult result = (*hAllocator->GetVulkanFunctions().vkMapMemory)(
hAllocator->m_hDevice,
m_hMemory,
0, // offset
VK_WHOLE_SIZE,
0, // flags
&m_pMappedData);
if(result == VK_SUCCESS)
{
if(ppData != VMA_NULL)
{
*ppData = m_pMappedData;
}
m_MapCount = count;
}
return result;
}
}
void VmaDeviceMemoryBlock::Unmap(VmaAllocator hAllocator, uint32_t count)
{
if(count == 0)
{
return;
}
VmaMutexLock lock(m_Mutex, hAllocator->m_UseMutex);
if(m_MapCount >= count)
{
m_MapCount -= count;
if(m_MapCount == 0)
{
m_pMappedData = VMA_NULL;
(*hAllocator->GetVulkanFunctions().vkUnmapMemory)(hAllocator->m_hDevice, m_hMemory);
}
}
else
{
VMA_ASSERT(0 && "VkDeviceMemory block is being unmapped while it was not previously mapped.");
}
}
VkResult VmaDeviceMemoryBlock::BindBufferMemory(
const VmaAllocator hAllocator,
const VmaAllocation hAllocation,
VkBuffer hBuffer)
{
VMA_ASSERT(hAllocation->GetType() == VmaAllocation_T::ALLOCATION_TYPE_BLOCK &&
hAllocation->GetBlock() == this);
// This lock is important so that we don't call vkBind... and/or vkMap... simultaneously on the same VkDeviceMemory from multiple threads.
VmaMutexLock lock(m_Mutex, hAllocator->m_UseMutex);
return hAllocator->GetVulkanFunctions().vkBindBufferMemory(
hAllocator->m_hDevice,
hBuffer,
m_hMemory,
hAllocation->GetOffset());
}
VkResult VmaDeviceMemoryBlock::BindImageMemory(
const VmaAllocator hAllocator,
const VmaAllocation hAllocation,
VkImage hImage)
{
VMA_ASSERT(hAllocation->GetType() == VmaAllocation_T::ALLOCATION_TYPE_BLOCK &&
hAllocation->GetBlock() == this);
// This lock is important so that we don't call vkBind... and/or vkMap... simultaneously on the same VkDeviceMemory from multiple threads.
VmaMutexLock lock(m_Mutex, hAllocator->m_UseMutex);
return hAllocator->GetVulkanFunctions().vkBindImageMemory(
hAllocator->m_hDevice,
hImage,
m_hMemory,
hAllocation->GetOffset());
}
static void InitStatInfo(VmaStatInfo& outInfo)
{
memset(&outInfo, 0, sizeof(outInfo));
outInfo.allocationSizeMin = UINT64_MAX;
outInfo.unusedRangeSizeMin = UINT64_MAX;
}
// Adds statistics srcInfo into inoutInfo, like: inoutInfo += srcInfo.
static void VmaAddStatInfo(VmaStatInfo& inoutInfo, const VmaStatInfo& srcInfo)
{
inoutInfo.blockCount += srcInfo.blockCount;
inoutInfo.allocationCount += srcInfo.allocationCount;
inoutInfo.unusedRangeCount += srcInfo.unusedRangeCount;
inoutInfo.usedBytes += srcInfo.usedBytes;
inoutInfo.unusedBytes += srcInfo.unusedBytes;
inoutInfo.allocationSizeMin = VMA_MIN(inoutInfo.allocationSizeMin, srcInfo.allocationSizeMin);
inoutInfo.allocationSizeMax = VMA_MAX(inoutInfo.allocationSizeMax, srcInfo.allocationSizeMax);
inoutInfo.unusedRangeSizeMin = VMA_MIN(inoutInfo.unusedRangeSizeMin, srcInfo.unusedRangeSizeMin);
inoutInfo.unusedRangeSizeMax = VMA_MAX(inoutInfo.unusedRangeSizeMax, srcInfo.unusedRangeSizeMax);
}
static void VmaPostprocessCalcStatInfo(VmaStatInfo& inoutInfo)
{
inoutInfo.allocationSizeAvg = (inoutInfo.allocationCount > 0) ?
VmaRoundDiv<VkDeviceSize>(inoutInfo.usedBytes, inoutInfo.allocationCount) : 0;
inoutInfo.unusedRangeSizeAvg = (inoutInfo.unusedRangeCount > 0) ?
VmaRoundDiv<VkDeviceSize>(inoutInfo.unusedBytes, inoutInfo.unusedRangeCount) : 0;
}
VmaPool_T::VmaPool_T(
VmaAllocator hAllocator,
const VmaPoolCreateInfo& createInfo) :
m_BlockVector(
hAllocator,
createInfo.memoryTypeIndex,
createInfo.blockSize,
createInfo.minBlockCount,
createInfo.maxBlockCount,
(createInfo.flags & VMA_POOL_CREATE_IGNORE_BUFFER_IMAGE_GRANULARITY_BIT) != 0 ? 1 : hAllocator->GetBufferImageGranularity(),
createInfo.frameInUseCount,
true) // isCustomPool
{
}
VmaPool_T::~VmaPool_T()
{
}
#if VMA_STATS_STRING_ENABLED
#endif // #if VMA_STATS_STRING_ENABLED
VmaBlockVector::VmaBlockVector(
VmaAllocator hAllocator,
uint32_t memoryTypeIndex,
VkDeviceSize preferredBlockSize,
size_t minBlockCount,
size_t maxBlockCount,
VkDeviceSize bufferImageGranularity,
uint32_t frameInUseCount,
bool isCustomPool) :
m_hAllocator(hAllocator),
m_MemoryTypeIndex(memoryTypeIndex),
m_PreferredBlockSize(preferredBlockSize),
m_MinBlockCount(minBlockCount),
m_MaxBlockCount(maxBlockCount),
m_BufferImageGranularity(bufferImageGranularity),
m_FrameInUseCount(frameInUseCount),
m_IsCustomPool(isCustomPool),
m_Blocks(VmaStlAllocator<VmaDeviceMemoryBlock*>(hAllocator->GetAllocationCallbacks())),
m_HasEmptyBlock(false),
m_pDefragmentator(VMA_NULL)
{
}
VmaBlockVector::~VmaBlockVector()
{
VMA_ASSERT(m_pDefragmentator == VMA_NULL);
for(size_t i = m_Blocks.size(); i--; )
{
m_Blocks[i]->Destroy(m_hAllocator);
vma_delete(m_hAllocator, m_Blocks[i]);
}
}
VkResult VmaBlockVector::CreateMinBlocks()
{
for(size_t i = 0; i < m_MinBlockCount; ++i)
{
VkResult res = CreateBlock(m_PreferredBlockSize, VMA_NULL);
if(res != VK_SUCCESS)
{
return res;
}
}
return VK_SUCCESS;
}
void VmaBlockVector::GetPoolStats(VmaPoolStats* pStats)
{
pStats->size = 0;
pStats->unusedSize = 0;
pStats->allocationCount = 0;
pStats->unusedRangeCount = 0;
pStats->unusedRangeSizeMax = 0;
VmaMutexLock lock(m_Mutex, m_hAllocator->m_UseMutex);
for(uint32_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex)
{
const VmaDeviceMemoryBlock* const pBlock = m_Blocks[blockIndex];
VMA_ASSERT(pBlock);
VMA_HEAVY_ASSERT(pBlock->Validate());
pBlock->m_Metadata.AddPoolStats(*pStats);
}
}
static const uint32_t VMA_ALLOCATION_TRY_COUNT = 32;
VkResult VmaBlockVector::Allocate(
VmaPool hCurrentPool,
uint32_t currentFrameIndex,
const VkMemoryRequirements& vkMemReq,
const VmaAllocationCreateInfo& createInfo,
VmaSuballocationType suballocType,
VmaAllocation* pAllocation)
{
const bool mapped = (createInfo.flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0;
const bool isUserDataString = (createInfo.flags & VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT) != 0;
VmaMutexLock lock(m_Mutex, m_hAllocator->m_UseMutex);
// 1. Search existing allocations. Try to allocate without making other allocations lost.
// Forward order in m_Blocks - prefer blocks with smallest amount of free space.
for(size_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex )
{
VmaDeviceMemoryBlock* const pCurrBlock = m_Blocks[blockIndex];
VMA_ASSERT(pCurrBlock);
VmaAllocationRequest currRequest = {};
if(pCurrBlock->m_Metadata.CreateAllocationRequest(
currentFrameIndex,
m_FrameInUseCount,
m_BufferImageGranularity,
vkMemReq.size,
vkMemReq.alignment,
suballocType,
false, // canMakeOtherLost
&currRequest))
{
// Allocate from pCurrBlock.
VMA_ASSERT(currRequest.itemsToMakeLostCount == 0);
if(mapped)
{
VkResult res = pCurrBlock->Map(m_hAllocator, 1, VMA_NULL);
if(res != VK_SUCCESS)
{
return res;
}
}
// We no longer have an empty Allocation.
if(pCurrBlock->m_Metadata.IsEmpty())
{
m_HasEmptyBlock = false;
}
*pAllocation = vma_new(m_hAllocator, VmaAllocation_T)(currentFrameIndex, isUserDataString);
pCurrBlock->m_Metadata.Alloc(currRequest, suballocType, vkMemReq.size, *pAllocation);
(*pAllocation)->InitBlockAllocation(
hCurrentPool,
pCurrBlock,
currRequest.offset,
vkMemReq.alignment,
vkMemReq.size,
suballocType,
mapped,
(createInfo.flags & VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT) != 0);
VMA_HEAVY_ASSERT(pCurrBlock->Validate());
VMA_DEBUG_LOG(" Returned from existing allocation #%u", (uint32_t)blockIndex);
(*pAllocation)->SetUserData(m_hAllocator, createInfo.pUserData);
return VK_SUCCESS;
}
}
const bool canCreateNewBlock =
((createInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) == 0) &&
(m_Blocks.size() < m_MaxBlockCount);
// 2. Try to create new block.
if(canCreateNewBlock)
{
// Calculate optimal size for new block.
VkDeviceSize newBlockSize = m_PreferredBlockSize;
uint32_t newBlockSizeShift = 0;
const uint32_t NEW_BLOCK_SIZE_SHIFT_MAX = 3;
// Allocating blocks of other sizes is allowed only in default pools.
// In custom pools block size is fixed.
if(m_IsCustomPool == false)
{
// Allocate 1/8, 1/4, 1/2 as first blocks.
const VkDeviceSize maxExistingBlockSize = CalcMaxBlockSize();
for(uint32_t i = 0; i < NEW_BLOCK_SIZE_SHIFT_MAX; ++i)
{
const VkDeviceSize smallerNewBlockSize = newBlockSize / 2;
if(smallerNewBlockSize > maxExistingBlockSize && smallerNewBlockSize >= vkMemReq.size * 2)
{
newBlockSize = smallerNewBlockSize;
++newBlockSizeShift;
}
else
{
break;
}
}
}
size_t newBlockIndex = 0;
VkResult res = CreateBlock(newBlockSize, &newBlockIndex);
// Allocation of this size failed? Try 1/2, 1/4, 1/8 of m_PreferredBlockSize.
if(m_IsCustomPool == false)
{
while(res < 0 && newBlockSizeShift < NEW_BLOCK_SIZE_SHIFT_MAX)
{
const VkDeviceSize smallerNewBlockSize = newBlockSize / 2;
if(smallerNewBlockSize >= vkMemReq.size)
{
newBlockSize = smallerNewBlockSize;
++newBlockSizeShift;
res = CreateBlock(newBlockSize, &newBlockIndex);
}
else
{
break;
}
}
}
if(res == VK_SUCCESS)
{
VmaDeviceMemoryBlock* const pBlock = m_Blocks[newBlockIndex];
VMA_ASSERT(pBlock->m_Metadata.GetSize() >= vkMemReq.size);
if(mapped)
{
res = pBlock->Map(m_hAllocator, 1, VMA_NULL);
if(res != VK_SUCCESS)
{
return res;
}
}
// Allocate from pBlock. Because it is empty, dstAllocRequest can be trivially filled.
VmaAllocationRequest allocRequest;
pBlock->m_Metadata.CreateFirstAllocationRequest(&allocRequest);
*pAllocation = vma_new(m_hAllocator, VmaAllocation_T)(currentFrameIndex, isUserDataString);
pBlock->m_Metadata.Alloc(allocRequest, suballocType, vkMemReq.size, *pAllocation);
(*pAllocation)->InitBlockAllocation(
hCurrentPool,
pBlock,
allocRequest.offset,
vkMemReq.alignment,
vkMemReq.size,
suballocType,
mapped,
(createInfo.flags & VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT) != 0);
VMA_HEAVY_ASSERT(pBlock->Validate());
VMA_DEBUG_LOG(" Created new allocation Size=%llu", allocInfo.allocationSize);
(*pAllocation)->SetUserData(m_hAllocator, createInfo.pUserData);
return VK_SUCCESS;
}
}
const bool canMakeOtherLost = (createInfo.flags & VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT) != 0;
// 3. Try to allocate from existing blocks with making other allocations lost.
if(canMakeOtherLost)
{
uint32_t tryIndex = 0;
for(; tryIndex < VMA_ALLOCATION_TRY_COUNT; ++tryIndex)
{
VmaDeviceMemoryBlock* pBestRequestBlock = VMA_NULL;
VmaAllocationRequest bestRequest = {};
VkDeviceSize bestRequestCost = VK_WHOLE_SIZE;
// 1. Search existing allocations.
// Forward order in m_Blocks - prefer blocks with smallest amount of free space.
for(size_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex )
{
VmaDeviceMemoryBlock* const pCurrBlock = m_Blocks[blockIndex];
VMA_ASSERT(pCurrBlock);
VmaAllocationRequest currRequest = {};
if(pCurrBlock->m_Metadata.CreateAllocationRequest(
currentFrameIndex,
m_FrameInUseCount,
m_BufferImageGranularity,
vkMemReq.size,
vkMemReq.alignment,
suballocType,
canMakeOtherLost,
&currRequest))
{
const VkDeviceSize currRequestCost = currRequest.CalcCost();
if(pBestRequestBlock == VMA_NULL ||
currRequestCost < bestRequestCost)
{
pBestRequestBlock = pCurrBlock;
bestRequest = currRequest;
bestRequestCost = currRequestCost;
if(bestRequestCost == 0)
{
break;
}
}
}
}
if(pBestRequestBlock != VMA_NULL)
{
if(mapped)
{
VkResult res = pBestRequestBlock->Map(m_hAllocator, 1, VMA_NULL);
if(res != VK_SUCCESS)
{
return res;
}
}
if(pBestRequestBlock->m_Metadata.MakeRequestedAllocationsLost(
currentFrameIndex,
m_FrameInUseCount,
&bestRequest))
{
// We no longer have an empty Allocation.
if(pBestRequestBlock->m_Metadata.IsEmpty())
{
m_HasEmptyBlock = false;
}
// Allocate from this pBlock.
*pAllocation = vma_new(m_hAllocator, VmaAllocation_T)(currentFrameIndex, isUserDataString);
pBestRequestBlock->m_Metadata.Alloc(bestRequest, suballocType, vkMemReq.size, *pAllocation);
(*pAllocation)->InitBlockAllocation(
hCurrentPool,
pBestRequestBlock,
bestRequest.offset,
vkMemReq.alignment,
vkMemReq.size,
suballocType,
mapped,
(createInfo.flags & VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT) != 0);
VMA_HEAVY_ASSERT(pBestRequestBlock->Validate());
VMA_DEBUG_LOG(" Returned from existing allocation #%u", (uint32_t)blockIndex);
(*pAllocation)->SetUserData(m_hAllocator, createInfo.pUserData);
return VK_SUCCESS;
}
// else: Some allocations must have been touched while we are here. Next try.
}
else
{
// Could not find place in any of the blocks - break outer loop.
break;
}
}
/* Maximum number of tries exceeded - a very unlike event when many other
threads are simultaneously touching allocations making it impossible to make
lost at the same time as we try to allocate. */
if(tryIndex == VMA_ALLOCATION_TRY_COUNT)
{
return VK_ERROR_TOO_MANY_OBJECTS;
}
}
return VK_ERROR_OUT_OF_DEVICE_MEMORY;
}
void VmaBlockVector::Free(
VmaAllocation hAllocation)
{
VmaDeviceMemoryBlock* pBlockToDelete = VMA_NULL;
// Scope for lock.
{
VmaMutexLock lock(m_Mutex, m_hAllocator->m_UseMutex);
VmaDeviceMemoryBlock* pBlock = hAllocation->GetBlock();
if(hAllocation->IsPersistentMap())
{
pBlock->Unmap(m_hAllocator, 1);
}
pBlock->m_Metadata.Free(hAllocation);
VMA_HEAVY_ASSERT(pBlock->Validate());
VMA_DEBUG_LOG(" Freed from MemoryTypeIndex=%u", memTypeIndex);
// pBlock became empty after this deallocation.
if(pBlock->m_Metadata.IsEmpty())
{
// Already has empty Allocation. We don't want to have two, so delete this one.
if(m_HasEmptyBlock && m_Blocks.size() > m_MinBlockCount)
{
pBlockToDelete = pBlock;
Remove(pBlock);
}
// We now have first empty Allocation.
else
{
m_HasEmptyBlock = true;
}
}
// pBlock didn't become empty, but we have another empty block - find and free that one.
// (This is optional, heuristics.)
else if(m_HasEmptyBlock)
{
VmaDeviceMemoryBlock* pLastBlock = m_Blocks.back();
if(pLastBlock->m_Metadata.IsEmpty() && m_Blocks.size() > m_MinBlockCount)
{
pBlockToDelete = pLastBlock;
m_Blocks.pop_back();
m_HasEmptyBlock = false;
}
}
IncrementallySortBlocks();
}
// Destruction of a free Allocation. Deferred until this point, outside of mutex
// lock, for performance reason.
if(pBlockToDelete != VMA_NULL)
{
VMA_DEBUG_LOG(" Deleted empty allocation");
pBlockToDelete->Destroy(m_hAllocator);
vma_delete(m_hAllocator, pBlockToDelete);
}
}
size_t VmaBlockVector::CalcMaxBlockSize() const
{
size_t result = 0;
for(size_t i = m_Blocks.size(); i--; )
{
result = VMA_MAX((uint64_t)result, (uint64_t)m_Blocks[i]->m_Metadata.GetSize());
if(result >= m_PreferredBlockSize)
{
break;
}
}
return result;
}
void VmaBlockVector::Remove(VmaDeviceMemoryBlock* pBlock)
{
for(uint32_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex)
{
if(m_Blocks[blockIndex] == pBlock)
{
VmaVectorRemove(m_Blocks, blockIndex);
return;
}
}
VMA_ASSERT(0);
}
void VmaBlockVector::IncrementallySortBlocks()
{
// Bubble sort only until first swap.
for(size_t i = 1; i < m_Blocks.size(); ++i)
{
if(m_Blocks[i - 1]->m_Metadata.GetSumFreeSize() > m_Blocks[i]->m_Metadata.GetSumFreeSize())
{
VMA_SWAP(m_Blocks[i - 1], m_Blocks[i]);
return;
}
}
}
VkResult VmaBlockVector::CreateBlock(VkDeviceSize blockSize, size_t* pNewBlockIndex)
{
VkMemoryAllocateInfo allocInfo = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO };
allocInfo.memoryTypeIndex = m_MemoryTypeIndex;
allocInfo.allocationSize = blockSize;
VkDeviceMemory mem = VK_NULL_HANDLE;
VkResult res = m_hAllocator->AllocateVulkanMemory(&allocInfo, &mem);
if(res < 0)
{
return res;
}
// New VkDeviceMemory successfully created.
// Create new Allocation for it.
VmaDeviceMemoryBlock* const pBlock = vma_new(m_hAllocator, VmaDeviceMemoryBlock)(m_hAllocator);
pBlock->Init(
m_MemoryTypeIndex,
mem,
allocInfo.allocationSize);
m_Blocks.push_back(pBlock);
if(pNewBlockIndex != VMA_NULL)
{
*pNewBlockIndex = m_Blocks.size() - 1;
}
return VK_SUCCESS;
}
#if VMA_STATS_STRING_ENABLED
void VmaBlockVector::PrintDetailedMap(class VmaJsonWriter& json)
{
VmaMutexLock lock(m_Mutex, m_hAllocator->m_UseMutex);
json.BeginObject();
if(m_IsCustomPool)
{
json.WriteString("MemoryTypeIndex");
json.WriteNumber(m_MemoryTypeIndex);
json.WriteString("BlockSize");
json.WriteNumber(m_PreferredBlockSize);
json.WriteString("BlockCount");
json.BeginObject(true);
if(m_MinBlockCount > 0)
{
json.WriteString("Min");
json.WriteNumber((uint64_t)m_MinBlockCount);
}
if(m_MaxBlockCount < SIZE_MAX)
{
json.WriteString("Max");
json.WriteNumber((uint64_t)m_MaxBlockCount);
}
json.WriteString("Cur");
json.WriteNumber((uint64_t)m_Blocks.size());
json.EndObject();
if(m_FrameInUseCount > 0)
{
json.WriteString("FrameInUseCount");
json.WriteNumber(m_FrameInUseCount);
}
}
else
{
json.WriteString("PreferredBlockSize");
json.WriteNumber(m_PreferredBlockSize);
}
json.WriteString("Blocks");
json.BeginArray();
for(size_t i = 0; i < m_Blocks.size(); ++i)
{
m_Blocks[i]->m_Metadata.PrintDetailedMap(json);
}
json.EndArray();
json.EndObject();
}
#endif // #if VMA_STATS_STRING_ENABLED
VmaDefragmentator* VmaBlockVector::EnsureDefragmentator(
VmaAllocator hAllocator,
uint32_t currentFrameIndex)
{
if(m_pDefragmentator == VMA_NULL)
{
m_pDefragmentator = vma_new(m_hAllocator, VmaDefragmentator)(
hAllocator,
this,
currentFrameIndex);
}
return m_pDefragmentator;
}
VkResult VmaBlockVector::Defragment(
VmaDefragmentationStats* pDefragmentationStats,
VkDeviceSize& maxBytesToMove,
uint32_t& maxAllocationsToMove)
{
if(m_pDefragmentator == VMA_NULL)
{
return VK_SUCCESS;
}
VmaMutexLock lock(m_Mutex, m_hAllocator->m_UseMutex);
// Defragment.
VkResult result = m_pDefragmentator->Defragment(maxBytesToMove, maxAllocationsToMove);
// Accumulate statistics.
if(pDefragmentationStats != VMA_NULL)
{
const VkDeviceSize bytesMoved = m_pDefragmentator->GetBytesMoved();
const uint32_t allocationsMoved = m_pDefragmentator->GetAllocationsMoved();
pDefragmentationStats->bytesMoved += bytesMoved;
pDefragmentationStats->allocationsMoved += allocationsMoved;
VMA_ASSERT(bytesMoved <= maxBytesToMove);
VMA_ASSERT(allocationsMoved <= maxAllocationsToMove);
maxBytesToMove -= bytesMoved;
maxAllocationsToMove -= allocationsMoved;
}
// Free empty blocks.
m_HasEmptyBlock = false;
for(size_t blockIndex = m_Blocks.size(); blockIndex--; )
{
VmaDeviceMemoryBlock* pBlock = m_Blocks[blockIndex];
if(pBlock->m_Metadata.IsEmpty())
{
if(m_Blocks.size() > m_MinBlockCount)
{
if(pDefragmentationStats != VMA_NULL)
{
++pDefragmentationStats->deviceMemoryBlocksFreed;
pDefragmentationStats->bytesFreed += pBlock->m_Metadata.GetSize();
}
VmaVectorRemove(m_Blocks, blockIndex);
pBlock->Destroy(m_hAllocator);
vma_delete(m_hAllocator, pBlock);
}
else
{
m_HasEmptyBlock = true;
}
}
}
return result;
}
void VmaBlockVector::DestroyDefragmentator()
{
if(m_pDefragmentator != VMA_NULL)
{
vma_delete(m_hAllocator, m_pDefragmentator);
m_pDefragmentator = VMA_NULL;
}
}
void VmaBlockVector::MakePoolAllocationsLost(
uint32_t currentFrameIndex,
size_t* pLostAllocationCount)
{
VmaMutexLock lock(m_Mutex, m_hAllocator->m_UseMutex);
size_t lostAllocationCount = 0;
for(uint32_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex)
{
VmaDeviceMemoryBlock* const pBlock = m_Blocks[blockIndex];
VMA_ASSERT(pBlock);
lostAllocationCount += pBlock->m_Metadata.MakeAllocationsLost(currentFrameIndex, m_FrameInUseCount);
}
if(pLostAllocationCount != VMA_NULL)
{
*pLostAllocationCount = lostAllocationCount;
}
}
void VmaBlockVector::AddStats(VmaStats* pStats)
{
const uint32_t memTypeIndex = m_MemoryTypeIndex;
const uint32_t memHeapIndex = m_hAllocator->MemoryTypeIndexToHeapIndex(memTypeIndex);
VmaMutexLock lock(m_Mutex, m_hAllocator->m_UseMutex);
for(uint32_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex)
{
const VmaDeviceMemoryBlock* const pBlock = m_Blocks[blockIndex];
VMA_ASSERT(pBlock);
VMA_HEAVY_ASSERT(pBlock->Validate());
VmaStatInfo allocationStatInfo;
pBlock->m_Metadata.CalcAllocationStatInfo(allocationStatInfo);
VmaAddStatInfo(pStats->total, allocationStatInfo);
VmaAddStatInfo(pStats->memoryType[memTypeIndex], allocationStatInfo);
VmaAddStatInfo(pStats->memoryHeap[memHeapIndex], allocationStatInfo);
}
}
////////////////////////////////////////////////////////////////////////////////
// VmaDefragmentator members definition
VmaDefragmentator::VmaDefragmentator(
VmaAllocator hAllocator,
VmaBlockVector* pBlockVector,
uint32_t currentFrameIndex) :
m_hAllocator(hAllocator),
m_pBlockVector(pBlockVector),
m_CurrentFrameIndex(currentFrameIndex),
m_BytesMoved(0),
m_AllocationsMoved(0),
m_Allocations(VmaStlAllocator<AllocationInfo>(hAllocator->GetAllocationCallbacks())),
m_Blocks(VmaStlAllocator<BlockInfo*>(hAllocator->GetAllocationCallbacks()))
{
}
VmaDefragmentator::~VmaDefragmentator()
{
for(size_t i = m_Blocks.size(); i--; )
{
vma_delete(m_hAllocator, m_Blocks[i]);
}
}
void VmaDefragmentator::AddAllocation(VmaAllocation hAlloc, VkBool32* pChanged)
{
AllocationInfo allocInfo;
allocInfo.m_hAllocation = hAlloc;
allocInfo.m_pChanged = pChanged;
m_Allocations.push_back(allocInfo);
}
VkResult VmaDefragmentator::BlockInfo::EnsureMapping(VmaAllocator hAllocator, void** ppMappedData)
{
// It has already been mapped for defragmentation.
if(m_pMappedDataForDefragmentation)
{
*ppMappedData = m_pMappedDataForDefragmentation;
return VK_SUCCESS;
}
// It is originally mapped.
if(m_pBlock->GetMappedData())
{
*ppMappedData = m_pBlock->GetMappedData();
return VK_SUCCESS;
}
// Map on first usage.
VkResult res = m_pBlock->Map(hAllocator, 1, &m_pMappedDataForDefragmentation);
*ppMappedData = m_pMappedDataForDefragmentation;
return res;
}
void VmaDefragmentator::BlockInfo::Unmap(VmaAllocator hAllocator)
{
if(m_pMappedDataForDefragmentation != VMA_NULL)
{
m_pBlock->Unmap(hAllocator, 1);
}
}
VkResult VmaDefragmentator::DefragmentRound(
VkDeviceSize maxBytesToMove,
uint32_t maxAllocationsToMove)
{
if(m_Blocks.empty())
{
return VK_SUCCESS;
}
size_t srcBlockIndex = m_Blocks.size() - 1;
size_t srcAllocIndex = SIZE_MAX;
for(;;)
{
// 1. Find next allocation to move.
// 1.1. Start from last to first m_Blocks - they are sorted from most "destination" to most "source".
// 1.2. Then start from last to first m_Allocations - they are sorted from largest to smallest.
while(srcAllocIndex >= m_Blocks[srcBlockIndex]->m_Allocations.size())
{
if(m_Blocks[srcBlockIndex]->m_Allocations.empty())
{
// Finished: no more allocations to process.
if(srcBlockIndex == 0)
{
return VK_SUCCESS;
}
else
{
--srcBlockIndex;
srcAllocIndex = SIZE_MAX;
}
}
else
{
srcAllocIndex = m_Blocks[srcBlockIndex]->m_Allocations.size() - 1;
}
}
BlockInfo* pSrcBlockInfo = m_Blocks[srcBlockIndex];
AllocationInfo& allocInfo = pSrcBlockInfo->m_Allocations[srcAllocIndex];
const VkDeviceSize size = allocInfo.m_hAllocation->GetSize();
const VkDeviceSize srcOffset = allocInfo.m_hAllocation->GetOffset();
const VkDeviceSize alignment = allocInfo.m_hAllocation->GetAlignment();
const VmaSuballocationType suballocType = allocInfo.m_hAllocation->GetSuballocationType();
// 2. Try to find new place for this allocation in preceding or current block.
for(size_t dstBlockIndex = 0; dstBlockIndex <= srcBlockIndex; ++dstBlockIndex)
{
BlockInfo* pDstBlockInfo = m_Blocks[dstBlockIndex];
VmaAllocationRequest dstAllocRequest;
if(pDstBlockInfo->m_pBlock->m_Metadata.CreateAllocationRequest(
m_CurrentFrameIndex,
m_pBlockVector->GetFrameInUseCount(),
m_pBlockVector->GetBufferImageGranularity(),
size,
alignment,
suballocType,
false, // canMakeOtherLost
&dstAllocRequest) &&
MoveMakesSense(
dstBlockIndex, dstAllocRequest.offset, srcBlockIndex, srcOffset))
{
VMA_ASSERT(dstAllocRequest.itemsToMakeLostCount == 0);
// Reached limit on number of allocations or bytes to move.
if((m_AllocationsMoved + 1 > maxAllocationsToMove) ||
(m_BytesMoved + size > maxBytesToMove))
{
return VK_INCOMPLETE;
}
void* pDstMappedData = VMA_NULL;
VkResult res = pDstBlockInfo->EnsureMapping(m_hAllocator, &pDstMappedData);
if(res != VK_SUCCESS)
{
return res;
}
void* pSrcMappedData = VMA_NULL;
res = pSrcBlockInfo->EnsureMapping(m_hAllocator, &pSrcMappedData);
if(res != VK_SUCCESS)
{
return res;
}
// THE PLACE WHERE ACTUAL DATA COPY HAPPENS.
memcpy(
reinterpret_cast<char*>(pDstMappedData) + dstAllocRequest.offset,
reinterpret_cast<char*>(pSrcMappedData) + srcOffset,
static_cast<size_t>(size));
pDstBlockInfo->m_pBlock->m_Metadata.Alloc(dstAllocRequest, suballocType, size, allocInfo.m_hAllocation);
pSrcBlockInfo->m_pBlock->m_Metadata.FreeAtOffset(srcOffset);
allocInfo.m_hAllocation->ChangeBlockAllocation(m_hAllocator, pDstBlockInfo->m_pBlock, dstAllocRequest.offset);
if(allocInfo.m_pChanged != VMA_NULL)
{
*allocInfo.m_pChanged = VK_TRUE;
}
++m_AllocationsMoved;
m_BytesMoved += size;
VmaVectorRemove(pSrcBlockInfo->m_Allocations, srcAllocIndex);
break;
}
}
// If not processed, this allocInfo remains in pBlockInfo->m_Allocations for next round.
if(srcAllocIndex > 0)
{
--srcAllocIndex;
}
else
{
if(srcBlockIndex > 0)
{
--srcBlockIndex;
srcAllocIndex = SIZE_MAX;
}
else
{
return VK_SUCCESS;
}
}
}
}
VkResult VmaDefragmentator::Defragment(
VkDeviceSize maxBytesToMove,
uint32_t maxAllocationsToMove)
{
if(m_Allocations.empty())
{
return VK_SUCCESS;
}
// Create block info for each block.
const size_t blockCount = m_pBlockVector->m_Blocks.size();
for(size_t blockIndex = 0; blockIndex < blockCount; ++blockIndex)
{
BlockInfo* pBlockInfo = vma_new(m_hAllocator, BlockInfo)(m_hAllocator->GetAllocationCallbacks());
pBlockInfo->m_pBlock = m_pBlockVector->m_Blocks[blockIndex];
m_Blocks.push_back(pBlockInfo);
}
// Sort them by m_pBlock pointer value.
VMA_SORT(m_Blocks.begin(), m_Blocks.end(), BlockPointerLess());
// Move allocation infos from m_Allocations to appropriate m_Blocks[memTypeIndex].m_Allocations.
for(size_t blockIndex = 0, allocCount = m_Allocations.size(); blockIndex < allocCount; ++blockIndex)
{
AllocationInfo& allocInfo = m_Allocations[blockIndex];
// Now as we are inside VmaBlockVector::m_Mutex, we can make final check if this allocation was not lost.
if(allocInfo.m_hAllocation->GetLastUseFrameIndex() != VMA_FRAME_INDEX_LOST)
{
VmaDeviceMemoryBlock* pBlock = allocInfo.m_hAllocation->GetBlock();
BlockInfoVector::iterator it = VmaBinaryFindFirstNotLess(m_Blocks.begin(), m_Blocks.end(), pBlock, BlockPointerLess());
if(it != m_Blocks.end() && (*it)->m_pBlock == pBlock)
{
(*it)->m_Allocations.push_back(allocInfo);
}
else
{
VMA_ASSERT(0);
}
}
}
m_Allocations.clear();
for(size_t blockIndex = 0; blockIndex < blockCount; ++blockIndex)
{
BlockInfo* pBlockInfo = m_Blocks[blockIndex];
pBlockInfo->CalcHasNonMovableAllocations();
pBlockInfo->SortAllocationsBySizeDescecnding();
}
// Sort m_Blocks this time by the main criterium, from most "destination" to most "source" blocks.
VMA_SORT(m_Blocks.begin(), m_Blocks.end(), BlockInfoCompareMoveDestination());
// Execute defragmentation rounds (the main part).
VkResult result = VK_SUCCESS;
for(size_t round = 0; (round < 2) && (result == VK_SUCCESS); ++round)
{
result = DefragmentRound(maxBytesToMove, maxAllocationsToMove);
}
// Unmap blocks that were mapped for defragmentation.
for(size_t blockIndex = 0; blockIndex < blockCount; ++blockIndex)
{
m_Blocks[blockIndex]->Unmap(m_hAllocator);
}
return result;
}
bool VmaDefragmentator::MoveMakesSense(
size_t dstBlockIndex, VkDeviceSize dstOffset,
size_t srcBlockIndex, VkDeviceSize srcOffset)
{
if(dstBlockIndex < srcBlockIndex)
{
return true;
}
if(dstBlockIndex > srcBlockIndex)
{
return false;
}
if(dstOffset < srcOffset)
{
return true;
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
// VmaAllocator_T
VmaAllocator_T::VmaAllocator_T(const VmaAllocatorCreateInfo* pCreateInfo) :
m_UseMutex((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_EXTERNALLY_SYNCHRONIZED_BIT) == 0),
m_UseKhrDedicatedAllocation((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT) != 0),
m_hDevice(pCreateInfo->device),
m_AllocationCallbacksSpecified(pCreateInfo->pAllocationCallbacks != VMA_NULL),
m_AllocationCallbacks(pCreateInfo->pAllocationCallbacks ?
*pCreateInfo->pAllocationCallbacks : VmaEmptyAllocationCallbacks),
m_PreferredLargeHeapBlockSize(0),
m_PhysicalDevice(pCreateInfo->physicalDevice),
m_CurrentFrameIndex(0),
m_Pools(VmaStlAllocator<VmaPool>(GetAllocationCallbacks()))
{
VMA_ASSERT(pCreateInfo->physicalDevice && pCreateInfo->device);
memset(&m_DeviceMemoryCallbacks, 0 ,sizeof(m_DeviceMemoryCallbacks));
memset(&m_MemProps, 0, sizeof(m_MemProps));
memset(&m_PhysicalDeviceProperties, 0, sizeof(m_PhysicalDeviceProperties));
memset(&m_pBlockVectors, 0, sizeof(m_pBlockVectors));
memset(&m_pDedicatedAllocations, 0, sizeof(m_pDedicatedAllocations));
for(uint32_t i = 0; i < VK_MAX_MEMORY_HEAPS; ++i)
{
m_HeapSizeLimit[i] = VK_WHOLE_SIZE;
}
if(pCreateInfo->pDeviceMemoryCallbacks != VMA_NULL)
{
m_DeviceMemoryCallbacks.pfnAllocate = pCreateInfo->pDeviceMemoryCallbacks->pfnAllocate;
m_DeviceMemoryCallbacks.pfnFree = pCreateInfo->pDeviceMemoryCallbacks->pfnFree;
}
ImportVulkanFunctions(pCreateInfo->pVulkanFunctions);
(*m_VulkanFunctions.vkGetPhysicalDeviceProperties)(m_PhysicalDevice, &m_PhysicalDeviceProperties);
(*m_VulkanFunctions.vkGetPhysicalDeviceMemoryProperties)(m_PhysicalDevice, &m_MemProps);
m_PreferredLargeHeapBlockSize = (pCreateInfo->preferredLargeHeapBlockSize != 0) ?
pCreateInfo->preferredLargeHeapBlockSize : static_cast<VkDeviceSize>(VMA_DEFAULT_LARGE_HEAP_BLOCK_SIZE);
if(pCreateInfo->pHeapSizeLimit != VMA_NULL)
{
for(uint32_t heapIndex = 0; heapIndex < GetMemoryHeapCount(); ++heapIndex)
{
const VkDeviceSize limit = pCreateInfo->pHeapSizeLimit[heapIndex];
if(limit != VK_WHOLE_SIZE)
{
m_HeapSizeLimit[heapIndex] = limit;
if(limit < m_MemProps.memoryHeaps[heapIndex].size)
{
m_MemProps.memoryHeaps[heapIndex].size = limit;
}
}
}
}
for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex)
{
const VkDeviceSize preferredBlockSize = CalcPreferredBlockSize(memTypeIndex);
m_pBlockVectors[memTypeIndex] = vma_new(this, VmaBlockVector)(
this,
memTypeIndex,
preferredBlockSize,
0,
SIZE_MAX,
GetBufferImageGranularity(),
pCreateInfo->frameInUseCount,
false); // isCustomPool
// No need to call m_pBlockVectors[memTypeIndex][blockVectorTypeIndex]->CreateMinBlocks here,
// becase minBlockCount is 0.
m_pDedicatedAllocations[memTypeIndex] = vma_new(this, AllocationVectorType)(VmaStlAllocator<VmaAllocation>(GetAllocationCallbacks()));
}
}
VmaAllocator_T::~VmaAllocator_T()
{
VMA_ASSERT(m_Pools.empty());
for(size_t i = GetMemoryTypeCount(); i--; )
{
vma_delete(this, m_pDedicatedAllocations[i]);
vma_delete(this, m_pBlockVectors[i]);
}
}
void VmaAllocator_T::ImportVulkanFunctions(const VmaVulkanFunctions* pVulkanFunctions)
{
#if VMA_STATIC_VULKAN_FUNCTIONS == 1
m_VulkanFunctions.vkGetPhysicalDeviceProperties = &vkGetPhysicalDeviceProperties;
m_VulkanFunctions.vkGetPhysicalDeviceMemoryProperties = &vkGetPhysicalDeviceMemoryProperties;
m_VulkanFunctions.vkAllocateMemory = &vkAllocateMemory;
m_VulkanFunctions.vkFreeMemory = &vkFreeMemory;
m_VulkanFunctions.vkMapMemory = &vkMapMemory;
m_VulkanFunctions.vkUnmapMemory = &vkUnmapMemory;
m_VulkanFunctions.vkBindBufferMemory = &vkBindBufferMemory;
m_VulkanFunctions.vkBindImageMemory = &vkBindImageMemory;
m_VulkanFunctions.vkGetBufferMemoryRequirements = &vkGetBufferMemoryRequirements;
m_VulkanFunctions.vkGetImageMemoryRequirements = &vkGetImageMemoryRequirements;
m_VulkanFunctions.vkCreateBuffer = &vkCreateBuffer;
m_VulkanFunctions.vkDestroyBuffer = &vkDestroyBuffer;
m_VulkanFunctions.vkCreateImage = &vkCreateImage;
m_VulkanFunctions.vkDestroyImage = &vkDestroyImage;
if(m_UseKhrDedicatedAllocation)
{
m_VulkanFunctions.vkGetBufferMemoryRequirements2KHR =
(PFN_vkGetBufferMemoryRequirements2KHR)vkGetDeviceProcAddr(m_hDevice, "vkGetBufferMemoryRequirements2KHR");
m_VulkanFunctions.vkGetImageMemoryRequirements2KHR =
(PFN_vkGetImageMemoryRequirements2KHR)vkGetDeviceProcAddr(m_hDevice, "vkGetImageMemoryRequirements2KHR");
}
#endif // #if VMA_STATIC_VULKAN_FUNCTIONS == 1
#define VMA_COPY_IF_NOT_NULL(funcName) \
if(pVulkanFunctions->funcName != VMA_NULL) m_VulkanFunctions.funcName = pVulkanFunctions->funcName;
if(pVulkanFunctions != VMA_NULL)
{
VMA_COPY_IF_NOT_NULL(vkGetPhysicalDeviceProperties);
VMA_COPY_IF_NOT_NULL(vkGetPhysicalDeviceMemoryProperties);
VMA_COPY_IF_NOT_NULL(vkAllocateMemory);
VMA_COPY_IF_NOT_NULL(vkFreeMemory);
VMA_COPY_IF_NOT_NULL(vkMapMemory);
VMA_COPY_IF_NOT_NULL(vkUnmapMemory);
VMA_COPY_IF_NOT_NULL(vkBindBufferMemory);
VMA_COPY_IF_NOT_NULL(vkBindImageMemory);
VMA_COPY_IF_NOT_NULL(vkGetBufferMemoryRequirements);
VMA_COPY_IF_NOT_NULL(vkGetImageMemoryRequirements);
VMA_COPY_IF_NOT_NULL(vkCreateBuffer);
VMA_COPY_IF_NOT_NULL(vkDestroyBuffer);
VMA_COPY_IF_NOT_NULL(vkCreateImage);
VMA_COPY_IF_NOT_NULL(vkDestroyImage);
VMA_COPY_IF_NOT_NULL(vkGetBufferMemoryRequirements2KHR);
VMA_COPY_IF_NOT_NULL(vkGetImageMemoryRequirements2KHR);
}
#undef VMA_COPY_IF_NOT_NULL
// If these asserts are hit, you must either #define VMA_STATIC_VULKAN_FUNCTIONS 1
// or pass valid pointers as VmaAllocatorCreateInfo::pVulkanFunctions.
VMA_ASSERT(m_VulkanFunctions.vkGetPhysicalDeviceProperties != VMA_NULL);
VMA_ASSERT(m_VulkanFunctions.vkGetPhysicalDeviceMemoryProperties != VMA_NULL);
VMA_ASSERT(m_VulkanFunctions.vkAllocateMemory != VMA_NULL);
VMA_ASSERT(m_VulkanFunctions.vkFreeMemory != VMA_NULL);
VMA_ASSERT(m_VulkanFunctions.vkMapMemory != VMA_NULL);
VMA_ASSERT(m_VulkanFunctions.vkUnmapMemory != VMA_NULL);
VMA_ASSERT(m_VulkanFunctions.vkBindBufferMemory != VMA_NULL);
VMA_ASSERT(m_VulkanFunctions.vkBindImageMemory != VMA_NULL);
VMA_ASSERT(m_VulkanFunctions.vkGetBufferMemoryRequirements != VMA_NULL);
VMA_ASSERT(m_VulkanFunctions.vkGetImageMemoryRequirements != VMA_NULL);
VMA_ASSERT(m_VulkanFunctions.vkCreateBuffer != VMA_NULL);
VMA_ASSERT(m_VulkanFunctions.vkDestroyBuffer != VMA_NULL);
VMA_ASSERT(m_VulkanFunctions.vkCreateImage != VMA_NULL);
VMA_ASSERT(m_VulkanFunctions.vkDestroyImage != VMA_NULL);
if(m_UseKhrDedicatedAllocation)
{
VMA_ASSERT(m_VulkanFunctions.vkGetBufferMemoryRequirements2KHR != VMA_NULL);
VMA_ASSERT(m_VulkanFunctions.vkGetImageMemoryRequirements2KHR != VMA_NULL);
}
}
VkDeviceSize VmaAllocator_T::CalcPreferredBlockSize(uint32_t memTypeIndex)
{
const uint32_t heapIndex = MemoryTypeIndexToHeapIndex(memTypeIndex);
const VkDeviceSize heapSize = m_MemProps.memoryHeaps[heapIndex].size;
const bool isSmallHeap = heapSize <= VMA_SMALL_HEAP_MAX_SIZE;
return isSmallHeap ? (heapSize / 8) : m_PreferredLargeHeapBlockSize;
}
VkResult VmaAllocator_T::AllocateMemoryOfType(
const VkMemoryRequirements& vkMemReq,
bool dedicatedAllocation,
VkBuffer dedicatedBuffer,
VkImage dedicatedImage,
const VmaAllocationCreateInfo& createInfo,
uint32_t memTypeIndex,
VmaSuballocationType suballocType,
VmaAllocation* pAllocation)
{
VMA_ASSERT(pAllocation != VMA_NULL);
VMA_DEBUG_LOG(" AllocateMemory: MemoryTypeIndex=%u, Size=%llu", memTypeIndex, vkMemReq.size);
VmaAllocationCreateInfo finalCreateInfo = createInfo;
// If memory type is not HOST_VISIBLE, disable MAPPED.
if((finalCreateInfo.flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0 &&
(m_MemProps.memoryTypes[memTypeIndex].propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) == 0)
{
finalCreateInfo.flags &= ~VMA_ALLOCATION_CREATE_MAPPED_BIT;
}
VmaBlockVector* const blockVector = m_pBlockVectors[memTypeIndex];
VMA_ASSERT(blockVector);
const VkDeviceSize preferredBlockSize = blockVector->GetPreferredBlockSize();
bool preferDedicatedMemory =
VMA_DEBUG_ALWAYS_DEDICATED_MEMORY ||
dedicatedAllocation ||
// Heuristics: Allocate dedicated memory if requested size if greater than half of preferred block size.
vkMemReq.size > preferredBlockSize / 2;
if(preferDedicatedMemory &&
(finalCreateInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) == 0 &&
finalCreateInfo.pool == VK_NULL_HANDLE)
{
finalCreateInfo.flags |= VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT;
}
if((finalCreateInfo.flags & VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT) != 0)
{
if((finalCreateInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) != 0)
{
return VK_ERROR_OUT_OF_DEVICE_MEMORY;
}
else
{
return AllocateDedicatedMemory(
vkMemReq.size,
suballocType,
memTypeIndex,
(finalCreateInfo.flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0,
(finalCreateInfo.flags & VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT) != 0,
finalCreateInfo.pUserData,
dedicatedBuffer,
dedicatedImage,
pAllocation);
}
}
else
{
VkResult res = blockVector->Allocate(
VK_NULL_HANDLE, // hCurrentPool
m_CurrentFrameIndex.load(),
vkMemReq,
finalCreateInfo,
suballocType,
pAllocation);
if(res == VK_SUCCESS)
{
return res;
}
// 5. Try dedicated memory.
if((finalCreateInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) != 0)
{
return VK_ERROR_OUT_OF_DEVICE_MEMORY;
}
else
{
res = AllocateDedicatedMemory(
vkMemReq.size,
suballocType,
memTypeIndex,
(finalCreateInfo.flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0,
(finalCreateInfo.flags & VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT) != 0,
finalCreateInfo.pUserData,
dedicatedBuffer,
dedicatedImage,
pAllocation);
if(res == VK_SUCCESS)
{
// Succeeded: AllocateDedicatedMemory function already filld pMemory, nothing more to do here.
VMA_DEBUG_LOG(" Allocated as DedicatedMemory");
return VK_SUCCESS;
}
else
{
// Everything failed: Return error code.
VMA_DEBUG_LOG(" vkAllocateMemory FAILED");
return res;
}
}
}
}
VkResult VmaAllocator_T::AllocateDedicatedMemory(
VkDeviceSize size,
VmaSuballocationType suballocType,
uint32_t memTypeIndex,
bool map,
bool isUserDataString,
void* pUserData,
VkBuffer dedicatedBuffer,
VkImage dedicatedImage,
VmaAllocation* pAllocation)
{
VMA_ASSERT(pAllocation);
VkMemoryAllocateInfo allocInfo = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO };
allocInfo.memoryTypeIndex = memTypeIndex;
allocInfo.allocationSize = size;
VkMemoryDedicatedAllocateInfoKHR dedicatedAllocInfo = { VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO_KHR };
if(m_UseKhrDedicatedAllocation)
{
if(dedicatedBuffer != VK_NULL_HANDLE)
{
VMA_ASSERT(dedicatedImage == VK_NULL_HANDLE);
dedicatedAllocInfo.buffer = dedicatedBuffer;
allocInfo.pNext = &dedicatedAllocInfo;
}
else if(dedicatedImage != VK_NULL_HANDLE)
{
dedicatedAllocInfo.image = dedicatedImage;
allocInfo.pNext = &dedicatedAllocInfo;
}
}
// Allocate VkDeviceMemory.
VkDeviceMemory hMemory = VK_NULL_HANDLE;
VkResult res = AllocateVulkanMemory(&allocInfo, &hMemory);
if(res < 0)
{
VMA_DEBUG_LOG(" vkAllocateMemory FAILED");
return res;
}
void* pMappedData = VMA_NULL;
if(map)
{
res = (*m_VulkanFunctions.vkMapMemory)(
m_hDevice,
hMemory,
0,
VK_WHOLE_SIZE,
0,
&pMappedData);
if(res < 0)
{
VMA_DEBUG_LOG(" vkMapMemory FAILED");
FreeVulkanMemory(memTypeIndex, size, hMemory);
return res;
}
}
*pAllocation = vma_new(this, VmaAllocation_T)(m_CurrentFrameIndex.load(), isUserDataString);
(*pAllocation)->InitDedicatedAllocation(memTypeIndex, hMemory, suballocType, pMappedData, size);
(*pAllocation)->SetUserData(this, pUserData);
// Register it in m_pDedicatedAllocations.
{
VmaMutexLock lock(m_DedicatedAllocationsMutex[memTypeIndex], m_UseMutex);
AllocationVectorType* pDedicatedAllocations = m_pDedicatedAllocations[memTypeIndex];
VMA_ASSERT(pDedicatedAllocations);
VmaVectorInsertSorted<VmaPointerLess>(*pDedicatedAllocations, *pAllocation);
}
VMA_DEBUG_LOG(" Allocated DedicatedMemory MemoryTypeIndex=#%u", memTypeIndex);
return VK_SUCCESS;
}
void VmaAllocator_T::GetBufferMemoryRequirements(
VkBuffer hBuffer,
VkMemoryRequirements& memReq,
bool& requiresDedicatedAllocation,
bool& prefersDedicatedAllocation) const
{
if(m_UseKhrDedicatedAllocation)
{
VkBufferMemoryRequirementsInfo2KHR memReqInfo = { VK_STRUCTURE_TYPE_BUFFER_MEMORY_REQUIREMENTS_INFO_2_KHR };
memReqInfo.buffer = hBuffer;
VkMemoryDedicatedRequirementsKHR memDedicatedReq = { VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS_KHR };
VkMemoryRequirements2KHR memReq2 = { VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2_KHR };
memReq2.pNext = &memDedicatedReq;
(*m_VulkanFunctions.vkGetBufferMemoryRequirements2KHR)(m_hDevice, &memReqInfo, &memReq2);
memReq = memReq2.memoryRequirements;
requiresDedicatedAllocation = (memDedicatedReq.requiresDedicatedAllocation != VK_FALSE);
prefersDedicatedAllocation = (memDedicatedReq.prefersDedicatedAllocation != VK_FALSE);
}
else
{
(*m_VulkanFunctions.vkGetBufferMemoryRequirements)(m_hDevice, hBuffer, &memReq);
requiresDedicatedAllocation = false;
prefersDedicatedAllocation = false;
}
}
void VmaAllocator_T::GetImageMemoryRequirements(
VkImage hImage,
VkMemoryRequirements& memReq,
bool& requiresDedicatedAllocation,
bool& prefersDedicatedAllocation) const
{
if(m_UseKhrDedicatedAllocation)
{
VkImageMemoryRequirementsInfo2KHR memReqInfo = { VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2_KHR };
memReqInfo.image = hImage;
VkMemoryDedicatedRequirementsKHR memDedicatedReq = { VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS_KHR };
VkMemoryRequirements2KHR memReq2 = { VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2_KHR };
memReq2.pNext = &memDedicatedReq;
(*m_VulkanFunctions.vkGetImageMemoryRequirements2KHR)(m_hDevice, &memReqInfo, &memReq2);
memReq = memReq2.memoryRequirements;
requiresDedicatedAllocation = (memDedicatedReq.requiresDedicatedAllocation != VK_FALSE);
prefersDedicatedAllocation = (memDedicatedReq.prefersDedicatedAllocation != VK_FALSE);
}
else
{
(*m_VulkanFunctions.vkGetImageMemoryRequirements)(m_hDevice, hImage, &memReq);
requiresDedicatedAllocation = false;
prefersDedicatedAllocation = false;
}
}
VkResult VmaAllocator_T::AllocateMemory(
const VkMemoryRequirements& vkMemReq,
bool requiresDedicatedAllocation,
bool prefersDedicatedAllocation,
VkBuffer dedicatedBuffer,
VkImage dedicatedImage,
const VmaAllocationCreateInfo& createInfo,
VmaSuballocationType suballocType,
VmaAllocation* pAllocation)
{
if((createInfo.flags & VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT) != 0 &&
(createInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) != 0)
{
VMA_ASSERT(0 && "Specifying VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT together with VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT makes no sense.");
return VK_ERROR_OUT_OF_DEVICE_MEMORY;
}
if((createInfo.flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0 &&
(createInfo.flags & VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT) != 0)
{
VMA_ASSERT(0 && "Specifying VMA_ALLOCATION_CREATE_MAPPED_BIT together with VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT is invalid.");
return VK_ERROR_OUT_OF_DEVICE_MEMORY;
}
if(requiresDedicatedAllocation)
{
if((createInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) != 0)
{
VMA_ASSERT(0 && "VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT specified while dedicated allocation is required.");
return VK_ERROR_OUT_OF_DEVICE_MEMORY;
}
if(createInfo.pool != VK_NULL_HANDLE)
{
VMA_ASSERT(0 && "Pool specified while dedicated allocation is required.");
return VK_ERROR_OUT_OF_DEVICE_MEMORY;
}
}
if((createInfo.pool != VK_NULL_HANDLE) &&
((createInfo.flags & (VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT)) != 0))
{
VMA_ASSERT(0 && "Specifying VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT when pool != null is invalid.");
return VK_ERROR_OUT_OF_DEVICE_MEMORY;
}
if(createInfo.pool != VK_NULL_HANDLE)
{
return createInfo.pool->m_BlockVector.Allocate(
createInfo.pool,
m_CurrentFrameIndex.load(),
vkMemReq,
createInfo,
suballocType,
pAllocation);
}
else
{
// Bit mask of memory Vulkan types acceptable for this allocation.
uint32_t memoryTypeBits = vkMemReq.memoryTypeBits;
uint32_t memTypeIndex = UINT32_MAX;
VkResult res = vmaFindMemoryTypeIndex(this, memoryTypeBits, &createInfo, &memTypeIndex);
if(res == VK_SUCCESS)
{
res = AllocateMemoryOfType(
vkMemReq,
requiresDedicatedAllocation || prefersDedicatedAllocation,
dedicatedBuffer,
dedicatedImage,
createInfo,
memTypeIndex,
suballocType,
pAllocation);
// Succeeded on first try.
if(res == VK_SUCCESS)
{
return res;
}
// Allocation from this memory type failed. Try other compatible memory types.
else
{
for(;;)
{
// Remove old memTypeIndex from list of possibilities.
memoryTypeBits &= ~(1u << memTypeIndex);
// Find alternative memTypeIndex.
res = vmaFindMemoryTypeIndex(this, memoryTypeBits, &createInfo, &memTypeIndex);
if(res == VK_SUCCESS)
{
res = AllocateMemoryOfType(
vkMemReq,
requiresDedicatedAllocation || prefersDedicatedAllocation,
dedicatedBuffer,
dedicatedImage,
createInfo,
memTypeIndex,
suballocType,
pAllocation);
// Allocation from this alternative memory type succeeded.
if(res == VK_SUCCESS)
{
return res;
}
// else: Allocation from this memory type failed. Try next one - next loop iteration.
}
// No other matching memory type index could be found.
else
{
// Not returning res, which is VK_ERROR_FEATURE_NOT_PRESENT, because we already failed to allocate once.
return VK_ERROR_OUT_OF_DEVICE_MEMORY;
}
}
}
}
// Can't find any single memory type maching requirements. res is VK_ERROR_FEATURE_NOT_PRESENT.
else
return res;
}
}
void VmaAllocator_T::FreeMemory(const VmaAllocation allocation)
{
VMA_ASSERT(allocation);
if(allocation->CanBecomeLost() == false ||
allocation->GetLastUseFrameIndex() != VMA_FRAME_INDEX_LOST)
{
switch(allocation->GetType())
{
case VmaAllocation_T::ALLOCATION_TYPE_BLOCK:
{
VmaBlockVector* pBlockVector = VMA_NULL;
VmaPool hPool = allocation->GetPool();
if(hPool != VK_NULL_HANDLE)
{
pBlockVector = &hPool->m_BlockVector;
}
else
{
const uint32_t memTypeIndex = allocation->GetMemoryTypeIndex();
pBlockVector = m_pBlockVectors[memTypeIndex];
}
pBlockVector->Free(allocation);
}
break;
case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED:
FreeDedicatedMemory(allocation);
break;
default:
VMA_ASSERT(0);
}
}
allocation->SetUserData(this, VMA_NULL);
vma_delete(this, allocation);
}
void VmaAllocator_T::CalculateStats(VmaStats* pStats)
{
// Initialize.
InitStatInfo(pStats->total);
for(size_t i = 0; i < VK_MAX_MEMORY_TYPES; ++i)
InitStatInfo(pStats->memoryType[i]);
for(size_t i = 0; i < VK_MAX_MEMORY_HEAPS; ++i)
InitStatInfo(pStats->memoryHeap[i]);
// Process default pools.
for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex)
{
VmaBlockVector* const pBlockVector = m_pBlockVectors[memTypeIndex];
VMA_ASSERT(pBlockVector);
pBlockVector->AddStats(pStats);
}
// Process custom pools.
{
VmaMutexLock lock(m_PoolsMutex, m_UseMutex);
for(size_t poolIndex = 0, poolCount = m_Pools.size(); poolIndex < poolCount; ++poolIndex)
{
m_Pools[poolIndex]->GetBlockVector().AddStats(pStats);
}
}
// Process dedicated allocations.
for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex)
{
const uint32_t memHeapIndex = MemoryTypeIndexToHeapIndex(memTypeIndex);
VmaMutexLock dedicatedAllocationsLock(m_DedicatedAllocationsMutex[memTypeIndex], m_UseMutex);
AllocationVectorType* const pDedicatedAllocVector = m_pDedicatedAllocations[memTypeIndex];
VMA_ASSERT(pDedicatedAllocVector);
for(size_t allocIndex = 0, allocCount = pDedicatedAllocVector->size(); allocIndex < allocCount; ++allocIndex)
{
VmaStatInfo allocationStatInfo;
(*pDedicatedAllocVector)[allocIndex]->DedicatedAllocCalcStatsInfo(allocationStatInfo);
VmaAddStatInfo(pStats->total, allocationStatInfo);
VmaAddStatInfo(pStats->memoryType[memTypeIndex], allocationStatInfo);
VmaAddStatInfo(pStats->memoryHeap[memHeapIndex], allocationStatInfo);
}
}
// Postprocess.
VmaPostprocessCalcStatInfo(pStats->total);
for(size_t i = 0; i < GetMemoryTypeCount(); ++i)
VmaPostprocessCalcStatInfo(pStats->memoryType[i]);
for(size_t i = 0; i < GetMemoryHeapCount(); ++i)
VmaPostprocessCalcStatInfo(pStats->memoryHeap[i]);
}
static const uint32_t VMA_VENDOR_ID_AMD = 4098;
VkResult VmaAllocator_T::Defragment(
VmaAllocation* pAllocations,
size_t allocationCount,
VkBool32* pAllocationsChanged,
const VmaDefragmentationInfo* pDefragmentationInfo,
VmaDefragmentationStats* pDefragmentationStats)
{
if(pAllocationsChanged != VMA_NULL)
{
memset(pAllocationsChanged, 0, sizeof(*pAllocationsChanged));
}
if(pDefragmentationStats != VMA_NULL)
{
memset(pDefragmentationStats, 0, sizeof(*pDefragmentationStats));
}
const uint32_t currentFrameIndex = m_CurrentFrameIndex.load();
VmaMutexLock poolsLock(m_PoolsMutex, m_UseMutex);
const size_t poolCount = m_Pools.size();
// Dispatch pAllocations among defragmentators. Create them in BlockVectors when necessary.
for(size_t allocIndex = 0; allocIndex < allocationCount; ++allocIndex)
{
VmaAllocation hAlloc = pAllocations[allocIndex];
VMA_ASSERT(hAlloc);
const uint32_t memTypeIndex = hAlloc->GetMemoryTypeIndex();
// DedicatedAlloc cannot be defragmented.
if((hAlloc->GetType() == VmaAllocation_T::ALLOCATION_TYPE_BLOCK) &&
// Only HOST_VISIBLE memory types can be defragmented.
((m_MemProps.memoryTypes[memTypeIndex].propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) != 0) &&
// Lost allocation cannot be defragmented.
(hAlloc->GetLastUseFrameIndex() != VMA_FRAME_INDEX_LOST))
{
VmaBlockVector* pAllocBlockVector = VMA_NULL;
const VmaPool hAllocPool = hAlloc->GetPool();
// This allocation belongs to custom pool.
if(hAllocPool != VK_NULL_HANDLE)
{
pAllocBlockVector = &hAllocPool->GetBlockVector();
}
// This allocation belongs to general pool.
else
{
pAllocBlockVector = m_pBlockVectors[memTypeIndex];
}
VmaDefragmentator* const pDefragmentator = pAllocBlockVector->EnsureDefragmentator(this, currentFrameIndex);
VkBool32* const pChanged = (pAllocationsChanged != VMA_NULL) ?
&pAllocationsChanged[allocIndex] : VMA_NULL;
pDefragmentator->AddAllocation(hAlloc, pChanged);
}
}
VkResult result = VK_SUCCESS;
// ======== Main processing.
VkDeviceSize maxBytesToMove = SIZE_MAX;
uint32_t maxAllocationsToMove = UINT32_MAX;
if(pDefragmentationInfo != VMA_NULL)
{
maxBytesToMove = pDefragmentationInfo->maxBytesToMove;
maxAllocationsToMove = pDefragmentationInfo->maxAllocationsToMove;
}
// Process standard memory.
for(uint32_t memTypeIndex = 0;
(memTypeIndex < GetMemoryTypeCount()) && (result == VK_SUCCESS);
++memTypeIndex)
{
// Only HOST_VISIBLE memory types can be defragmented.
if((m_MemProps.memoryTypes[memTypeIndex].propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) != 0)
{
result = m_pBlockVectors[memTypeIndex]->Defragment(
pDefragmentationStats,
maxBytesToMove,
maxAllocationsToMove);
}
}
// Process custom pools.
for(size_t poolIndex = 0; (poolIndex < poolCount) && (result == VK_SUCCESS); ++poolIndex)
{
result = m_Pools[poolIndex]->GetBlockVector().Defragment(
pDefragmentationStats,
maxBytesToMove,
maxAllocationsToMove);
}
// ======== Destroy defragmentators.
// Process custom pools.
for(size_t poolIndex = poolCount; poolIndex--; )
{
m_Pools[poolIndex]->GetBlockVector().DestroyDefragmentator();
}
// Process standard memory.
for(uint32_t memTypeIndex = GetMemoryTypeCount(); memTypeIndex--; )
{
if((m_MemProps.memoryTypes[memTypeIndex].propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) != 0)
{
m_pBlockVectors[memTypeIndex]->DestroyDefragmentator();
}
}
return result;
}
void VmaAllocator_T::GetAllocationInfo(VmaAllocation hAllocation, VmaAllocationInfo* pAllocationInfo)
{
if(hAllocation->CanBecomeLost())
{
/*
Warning: This is a carefully designed algorithm.
Do not modify unless you really know what you're doing :)
*/
uint32_t localCurrFrameIndex = m_CurrentFrameIndex.load();
uint32_t localLastUseFrameIndex = hAllocation->GetLastUseFrameIndex();
for(;;)
{
if(localLastUseFrameIndex == VMA_FRAME_INDEX_LOST)
{
pAllocationInfo->memoryType = UINT32_MAX;
pAllocationInfo->deviceMemory = VK_NULL_HANDLE;
pAllocationInfo->offset = 0;
pAllocationInfo->size = hAllocation->GetSize();
pAllocationInfo->pMappedData = VMA_NULL;
pAllocationInfo->pUserData = hAllocation->GetUserData();
return;
}
else if(localLastUseFrameIndex == localCurrFrameIndex)
{
pAllocationInfo->memoryType = hAllocation->GetMemoryTypeIndex();
pAllocationInfo->deviceMemory = hAllocation->GetMemory();
pAllocationInfo->offset = hAllocation->GetOffset();
pAllocationInfo->size = hAllocation->GetSize();
pAllocationInfo->pMappedData = VMA_NULL;
pAllocationInfo->pUserData = hAllocation->GetUserData();
return;
}
else // Last use time earlier than current time.
{
if(hAllocation->CompareExchangeLastUseFrameIndex(localLastUseFrameIndex, localCurrFrameIndex))
{
localLastUseFrameIndex = localCurrFrameIndex;
}
}
}
}
else
{
pAllocationInfo->memoryType = hAllocation->GetMemoryTypeIndex();
pAllocationInfo->deviceMemory = hAllocation->GetMemory();
pAllocationInfo->offset = hAllocation->GetOffset();
pAllocationInfo->size = hAllocation->GetSize();
pAllocationInfo->pMappedData = hAllocation->GetMappedData();
pAllocationInfo->pUserData = hAllocation->GetUserData();
}
}
bool VmaAllocator_T::TouchAllocation(VmaAllocation hAllocation)
{
// This is a stripped-down version of VmaAllocator_T::GetAllocationInfo.
if(hAllocation->CanBecomeLost())
{
uint32_t localCurrFrameIndex = m_CurrentFrameIndex.load();
uint32_t localLastUseFrameIndex = hAllocation->GetLastUseFrameIndex();
for(;;)
{
if(localLastUseFrameIndex == VMA_FRAME_INDEX_LOST)
{
return false;
}
else if(localLastUseFrameIndex == localCurrFrameIndex)
{
return true;
}
else // Last use time earlier than current time.
{
if(hAllocation->CompareExchangeLastUseFrameIndex(localLastUseFrameIndex, localCurrFrameIndex))
{
localLastUseFrameIndex = localCurrFrameIndex;
}
}
}
}
else
{
return true;
}
}
VkResult VmaAllocator_T::CreatePool(const VmaPoolCreateInfo* pCreateInfo, VmaPool* pPool)
{
VMA_DEBUG_LOG(" CreatePool: MemoryTypeIndex=%u", pCreateInfo->memoryTypeIndex);
VmaPoolCreateInfo newCreateInfo = *pCreateInfo;
if(newCreateInfo.maxBlockCount == 0)
{
newCreateInfo.maxBlockCount = SIZE_MAX;
}
if(newCreateInfo.blockSize == 0)
{
newCreateInfo.blockSize = CalcPreferredBlockSize(newCreateInfo.memoryTypeIndex);
}
*pPool = vma_new(this, VmaPool_T)(this, newCreateInfo);
VkResult res = (*pPool)->m_BlockVector.CreateMinBlocks();
if(res != VK_SUCCESS)
{
vma_delete(this, *pPool);
*pPool = VMA_NULL;
return res;
}
// Add to m_Pools.
{
VmaMutexLock lock(m_PoolsMutex, m_UseMutex);
VmaVectorInsertSorted<VmaPointerLess>(m_Pools, *pPool);
}
return VK_SUCCESS;
}
void VmaAllocator_T::DestroyPool(VmaPool pool)
{
// Remove from m_Pools.
{
VmaMutexLock lock(m_PoolsMutex, m_UseMutex);
LAVA_UNUSED bool success = VmaVectorRemoveSorted<VmaPointerLess>(m_Pools, pool);
VMA_ASSERT(success && "Pool not found in Allocator.");
}
vma_delete(this, pool);
}
void VmaAllocator_T::GetPoolStats(VmaPool pool, VmaPoolStats* pPoolStats)
{
pool->m_BlockVector.GetPoolStats(pPoolStats);
}
void VmaAllocator_T::SetCurrentFrameIndex(uint32_t frameIndex)
{
m_CurrentFrameIndex.store(frameIndex);
}
void VmaAllocator_T::MakePoolAllocationsLost(
VmaPool hPool,
size_t* pLostAllocationCount)
{
hPool->m_BlockVector.MakePoolAllocationsLost(
m_CurrentFrameIndex.load(),
pLostAllocationCount);
}
void VmaAllocator_T::CreateLostAllocation(VmaAllocation* pAllocation)
{
*pAllocation = vma_new(this, VmaAllocation_T)(VMA_FRAME_INDEX_LOST, false);
(*pAllocation)->InitLost();
}
VkResult VmaAllocator_T::AllocateVulkanMemory(const VkMemoryAllocateInfo* pAllocateInfo, VkDeviceMemory* pMemory)
{
const uint32_t heapIndex = MemoryTypeIndexToHeapIndex(pAllocateInfo->memoryTypeIndex);
VkResult res;
if(m_HeapSizeLimit[heapIndex] != VK_WHOLE_SIZE)
{
VmaMutexLock lock(m_HeapSizeLimitMutex, m_UseMutex);
if(m_HeapSizeLimit[heapIndex] >= pAllocateInfo->allocationSize)
{
res = (*m_VulkanFunctions.vkAllocateMemory)(m_hDevice, pAllocateInfo, GetAllocationCallbacks(), pMemory);
if(res == VK_SUCCESS)
{
m_HeapSizeLimit[heapIndex] -= pAllocateInfo->allocationSize;
}
}
else
{
res = VK_ERROR_OUT_OF_DEVICE_MEMORY;
}
}
else
{
res = (*m_VulkanFunctions.vkAllocateMemory)(m_hDevice, pAllocateInfo, GetAllocationCallbacks(), pMemory);
}
if(res == VK_SUCCESS && m_DeviceMemoryCallbacks.pfnAllocate != VMA_NULL)
{
(*m_DeviceMemoryCallbacks.pfnAllocate)(this, pAllocateInfo->memoryTypeIndex, *pMemory, pAllocateInfo->allocationSize);
}
return res;
}
void VmaAllocator_T::FreeVulkanMemory(uint32_t memoryType, VkDeviceSize size, VkDeviceMemory hMemory)
{
if(m_DeviceMemoryCallbacks.pfnFree != VMA_NULL)
{
(*m_DeviceMemoryCallbacks.pfnFree)(this, memoryType, hMemory, size);
}
(*m_VulkanFunctions.vkFreeMemory)(m_hDevice, hMemory, GetAllocationCallbacks());
const uint32_t heapIndex = MemoryTypeIndexToHeapIndex(memoryType);
if(m_HeapSizeLimit[heapIndex] != VK_WHOLE_SIZE)
{
VmaMutexLock lock(m_HeapSizeLimitMutex, m_UseMutex);
m_HeapSizeLimit[heapIndex] += size;
}
}
VkResult VmaAllocator_T::Map(VmaAllocation hAllocation, void** ppData)
{
if(hAllocation->CanBecomeLost())
{
return VK_ERROR_MEMORY_MAP_FAILED;
}
switch(hAllocation->GetType())
{
case VmaAllocation_T::ALLOCATION_TYPE_BLOCK:
{
VmaDeviceMemoryBlock* const pBlock = hAllocation->GetBlock();
char *pBytes = VMA_NULL;
VkResult res = pBlock->Map(this, 1, (void**)&pBytes);
if(res == VK_SUCCESS)
{
*ppData = pBytes + (ptrdiff_t)hAllocation->GetOffset();
hAllocation->BlockAllocMap();
}
return res;
}
case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED:
return hAllocation->DedicatedAllocMap(this, ppData);
default:
VMA_ASSERT(0);
return VK_ERROR_MEMORY_MAP_FAILED;
}
}
void VmaAllocator_T::Unmap(VmaAllocation hAllocation)
{
switch(hAllocation->GetType())
{
case VmaAllocation_T::ALLOCATION_TYPE_BLOCK:
{
VmaDeviceMemoryBlock* const pBlock = hAllocation->GetBlock();
hAllocation->BlockAllocUnmap();
pBlock->Unmap(this, 1);
}
break;
case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED:
hAllocation->DedicatedAllocUnmap(this);
break;
default:
VMA_ASSERT(0);
}
}
VkResult VmaAllocator_T::BindBufferMemory(VmaAllocation hAllocation, VkBuffer hBuffer)
{
VkResult res = VK_SUCCESS;
switch(hAllocation->GetType())
{
case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED:
res = GetVulkanFunctions().vkBindBufferMemory(
m_hDevice,
hBuffer,
hAllocation->GetMemory(),
0); //memoryOffset
break;
case VmaAllocation_T::ALLOCATION_TYPE_BLOCK:
{
VmaDeviceMemoryBlock* pBlock = hAllocation->GetBlock();
VMA_ASSERT(pBlock && "Binding buffer to allocation that doesn't belong to any block. Is the allocation lost?");
res = pBlock->BindBufferMemory(this, hAllocation, hBuffer);
break;
}
default:
VMA_ASSERT(0);
}
return res;
}
VkResult VmaAllocator_T::BindImageMemory(VmaAllocation hAllocation, VkImage hImage)
{
VkResult res = VK_SUCCESS;
switch(hAllocation->GetType())
{
case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED:
res = GetVulkanFunctions().vkBindImageMemory(
m_hDevice,
hImage,
hAllocation->GetMemory(),
0); //memoryOffset
break;
case VmaAllocation_T::ALLOCATION_TYPE_BLOCK:
{
VmaDeviceMemoryBlock* pBlock = hAllocation->GetBlock();
VMA_ASSERT(pBlock && "Binding image to allocation that doesn't belong to any block. Is the allocation lost?");
res = pBlock->BindImageMemory(this, hAllocation, hImage);
break;
}
default:
VMA_ASSERT(0);
}
return res;
}
void VmaAllocator_T::FreeDedicatedMemory(VmaAllocation allocation)
{
VMA_ASSERT(allocation && allocation->GetType() == VmaAllocation_T::ALLOCATION_TYPE_DEDICATED);
const uint32_t memTypeIndex = allocation->GetMemoryTypeIndex();
{
VmaMutexLock lock(m_DedicatedAllocationsMutex[memTypeIndex], m_UseMutex);
AllocationVectorType* const pDedicatedAllocations = m_pDedicatedAllocations[memTypeIndex];
VMA_ASSERT(pDedicatedAllocations);
LAVA_UNUSED bool success = VmaVectorRemoveSorted<VmaPointerLess>(*pDedicatedAllocations, allocation);
VMA_ASSERT(success);
}
VkDeviceMemory hMemory = allocation->GetMemory();
if(allocation->GetMappedData() != VMA_NULL)
{
(*m_VulkanFunctions.vkUnmapMemory)(m_hDevice, hMemory);
}
FreeVulkanMemory(memTypeIndex, allocation->GetSize(), hMemory);
VMA_DEBUG_LOG(" Freed DedicatedMemory MemoryTypeIndex=%u", memTypeIndex);
}
#if VMA_STATS_STRING_ENABLED
void VmaAllocator_T::PrintDetailedMap(VmaJsonWriter& json)
{
bool dedicatedAllocationsStarted = false;
for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex)
{
VmaMutexLock dedicatedAllocationsLock(m_DedicatedAllocationsMutex[memTypeIndex], m_UseMutex);
AllocationVectorType* const pDedicatedAllocVector = m_pDedicatedAllocations[memTypeIndex];
VMA_ASSERT(pDedicatedAllocVector);
if(pDedicatedAllocVector->empty() == false)
{
if(dedicatedAllocationsStarted == false)
{
dedicatedAllocationsStarted = true;
json.WriteString("DedicatedAllocations");
json.BeginObject();
}
json.BeginString("Type ");
json.ContinueString(memTypeIndex);
json.EndString();
json.BeginArray();
for(size_t i = 0; i < pDedicatedAllocVector->size(); ++i)
{
const VmaAllocation hAlloc = (*pDedicatedAllocVector)[i];
json.BeginObject(true);
json.WriteString("Type");
json.WriteString(VMA_SUBALLOCATION_TYPE_NAMES[hAlloc->GetSuballocationType()]);
json.WriteString("Size");
json.WriteNumber(hAlloc->GetSize());
const void* pUserData = hAlloc->GetUserData();
if(pUserData != VMA_NULL)
{
json.WriteString("UserData");
if(hAlloc->IsUserDataString())
{
json.WriteString((const char*)pUserData);
}
else
{
json.BeginString();
json.ContinueString_Pointer(pUserData);
json.EndString();
}
}
json.EndObject();
}
json.EndArray();
}
}
if(dedicatedAllocationsStarted)
{
json.EndObject();
}
{
bool allocationsStarted = false;
for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex)
{
if(m_pBlockVectors[memTypeIndex]->IsEmpty() == false)
{
if(allocationsStarted == false)
{
allocationsStarted = true;
json.WriteString("DefaultPools");
json.BeginObject();
}
json.BeginString("Type ");
json.ContinueString(memTypeIndex);
json.EndString();
m_pBlockVectors[memTypeIndex]->PrintDetailedMap(json);
}
}
if(allocationsStarted)
{
json.EndObject();
}
}
{
VmaMutexLock lock(m_PoolsMutex, m_UseMutex);
const size_t poolCount = m_Pools.size();
if(poolCount > 0)
{
json.WriteString("Pools");
json.BeginArray();
for(size_t poolIndex = 0; poolIndex < poolCount; ++poolIndex)
{
m_Pools[poolIndex]->m_BlockVector.PrintDetailedMap(json);
}
json.EndArray();
}
}
}
#endif // #if VMA_STATS_STRING_ENABLED
static VkResult AllocateMemoryForImage(
VmaAllocator allocator,
VkImage image,
const VmaAllocationCreateInfo* pAllocationCreateInfo,
VmaSuballocationType suballocType,
VmaAllocation* pAllocation)
{
VMA_ASSERT(allocator && (image != VK_NULL_HANDLE) && pAllocationCreateInfo && pAllocation);
VkMemoryRequirements vkMemReq = {};
bool requiresDedicatedAllocation = false;
bool prefersDedicatedAllocation = false;
allocator->GetImageMemoryRequirements(image, vkMemReq,
requiresDedicatedAllocation, prefersDedicatedAllocation);
return allocator->AllocateMemory(
vkMemReq,
requiresDedicatedAllocation,
prefersDedicatedAllocation,
VK_NULL_HANDLE, // dedicatedBuffer
image, // dedicatedImage
*pAllocationCreateInfo,
suballocType,
pAllocation);
}
////////////////////////////////////////////////////////////////////////////////
// Public interface
VkResult vmaCreateAllocator(
const VmaAllocatorCreateInfo* pCreateInfo,
VmaAllocator* pAllocator)
{
VMA_ASSERT(pCreateInfo && pAllocator);
VMA_DEBUG_LOG("vmaCreateAllocator");
*pAllocator = vma_new(pCreateInfo->pAllocationCallbacks, VmaAllocator_T)(pCreateInfo);
return VK_SUCCESS;
}
void vmaDestroyAllocator(
VmaAllocator allocator)
{
if(allocator != VK_NULL_HANDLE)
{
VMA_DEBUG_LOG("vmaDestroyAllocator");
VkAllocationCallbacks allocationCallbacks = allocator->m_AllocationCallbacks;
vma_delete(&allocationCallbacks, allocator);
}
}
void vmaGetPhysicalDeviceProperties(
VmaAllocator allocator,
const VkPhysicalDeviceProperties **ppPhysicalDeviceProperties)
{
VMA_ASSERT(allocator && ppPhysicalDeviceProperties);
*ppPhysicalDeviceProperties = &allocator->m_PhysicalDeviceProperties;
}
void vmaGetMemoryProperties(
VmaAllocator allocator,
const VkPhysicalDeviceMemoryProperties** ppPhysicalDeviceMemoryProperties)
{
VMA_ASSERT(allocator && ppPhysicalDeviceMemoryProperties);
*ppPhysicalDeviceMemoryProperties = &allocator->m_MemProps;
}
void vmaGetMemoryTypeProperties(
VmaAllocator allocator,
uint32_t memoryTypeIndex,
VkMemoryPropertyFlags* pFlags)
{
VMA_ASSERT(allocator && pFlags);
VMA_ASSERT(memoryTypeIndex < allocator->GetMemoryTypeCount());
*pFlags = allocator->m_MemProps.memoryTypes[memoryTypeIndex].propertyFlags;
}
void vmaSetCurrentFrameIndex(
VmaAllocator allocator,
uint32_t frameIndex)
{
VMA_ASSERT(allocator);
VMA_ASSERT(frameIndex != VMA_FRAME_INDEX_LOST);
VMA_DEBUG_GLOBAL_MUTEX_LOCK
allocator->SetCurrentFrameIndex(frameIndex);
}
void vmaCalculateStats(
VmaAllocator allocator,
VmaStats* pStats)
{
VMA_ASSERT(allocator && pStats);
VMA_DEBUG_GLOBAL_MUTEX_LOCK
allocator->CalculateStats(pStats);
}
#if VMA_STATS_STRING_ENABLED
void vmaBuildStatsString(
VmaAllocator allocator,
char** ppStatsString,
VkBool32 detailedMap)
{
VMA_ASSERT(allocator && ppStatsString);
VMA_DEBUG_GLOBAL_MUTEX_LOCK
VmaStringBuilder sb(allocator);
{
VmaJsonWriter json(allocator->GetAllocationCallbacks(), sb);
json.BeginObject();
VmaStats stats;
allocator->CalculateStats(&stats);
json.WriteString("Total");
VmaPrintStatInfo(json, stats.total);
for(uint32_t heapIndex = 0; heapIndex < allocator->GetMemoryHeapCount(); ++heapIndex)
{
json.BeginString("Heap ");
json.ContinueString(heapIndex);
json.EndString();
json.BeginObject();
json.WriteString("Size");
json.WriteNumber(allocator->m_MemProps.memoryHeaps[heapIndex].size);
json.WriteString("Flags");
json.BeginArray(true);
if((allocator->m_MemProps.memoryHeaps[heapIndex].flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) != 0)
{
json.WriteString("DEVICE_LOCAL");
}
json.EndArray();
if(stats.memoryHeap[heapIndex].blockCount > 0)
{
json.WriteString("Stats");
VmaPrintStatInfo(json, stats.memoryHeap[heapIndex]);
}
for(uint32_t typeIndex = 0; typeIndex < allocator->GetMemoryTypeCount(); ++typeIndex)
{
if(allocator->MemoryTypeIndexToHeapIndex(typeIndex) == heapIndex)
{
json.BeginString("Type ");
json.ContinueString(typeIndex);
json.EndString();
json.BeginObject();
json.WriteString("Flags");
json.BeginArray(true);
VkMemoryPropertyFlags flags = allocator->m_MemProps.memoryTypes[typeIndex].propertyFlags;
if((flags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) != 0)
{
json.WriteString("DEVICE_LOCAL");
}
if((flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) != 0)
{
json.WriteString("HOST_VISIBLE");
}
if((flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) != 0)
{
json.WriteString("HOST_COHERENT");
}
if((flags & VK_MEMORY_PROPERTY_HOST_CACHED_BIT) != 0)
{
json.WriteString("HOST_CACHED");
}
if((flags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) != 0)
{
json.WriteString("LAZILY_ALLOCATED");
}
json.EndArray();
if(stats.memoryType[typeIndex].blockCount > 0)
{
json.WriteString("Stats");
VmaPrintStatInfo(json, stats.memoryType[typeIndex]);
}
json.EndObject();
}
}
json.EndObject();
}
if(detailedMap == VK_TRUE)
{
allocator->PrintDetailedMap(json);
}
json.EndObject();
}
const size_t len = sb.GetLength();
char* const pChars = vma_new_array(allocator, char, len + 1);
if(len > 0)
{
memcpy(pChars, sb.GetData(), len);
}
pChars[len] = '\0';
*ppStatsString = pChars;
}
void vmaFreeStatsString(
VmaAllocator allocator,
char* pStatsString)
{
if(pStatsString != VMA_NULL)
{
VMA_ASSERT(allocator);
size_t len = strlen(pStatsString);
vma_delete_array(allocator, pStatsString, len + 1);
}
}
#endif // #if VMA_STATS_STRING_ENABLED
/*
This function is not protected by any mutex because it just reads immutable data.
*/
VkResult vmaFindMemoryTypeIndex(
VmaAllocator allocator,
uint32_t memoryTypeBits,
const VmaAllocationCreateInfo* pAllocationCreateInfo,
uint32_t* pMemoryTypeIndex)
{
VMA_ASSERT(allocator != VK_NULL_HANDLE);
VMA_ASSERT(pAllocationCreateInfo != VMA_NULL);
VMA_ASSERT(pMemoryTypeIndex != VMA_NULL);
if(pAllocationCreateInfo->memoryTypeBits != 0)
{
memoryTypeBits &= pAllocationCreateInfo->memoryTypeBits;
}
uint32_t requiredFlags = pAllocationCreateInfo->requiredFlags;
uint32_t preferredFlags = pAllocationCreateInfo->preferredFlags;
// Convert usage to requiredFlags and preferredFlags.
switch(pAllocationCreateInfo->usage)
{
case VMA_MEMORY_USAGE_UNKNOWN:
break;
case VMA_MEMORY_USAGE_GPU_ONLY:
preferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
break;
case VMA_MEMORY_USAGE_CPU_ONLY:
requiredFlags |= VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
break;
case VMA_MEMORY_USAGE_CPU_TO_GPU:
requiredFlags |= VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
preferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
break;
case VMA_MEMORY_USAGE_GPU_TO_CPU:
requiredFlags |= VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
preferredFlags |= VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | VK_MEMORY_PROPERTY_HOST_CACHED_BIT;
break;
default:
break;
}
*pMemoryTypeIndex = UINT32_MAX;
uint32_t minCost = UINT32_MAX;
for(uint32_t memTypeIndex = 0, memTypeBit = 1;
memTypeIndex < allocator->GetMemoryTypeCount();
++memTypeIndex, memTypeBit <<= 1)
{
// This memory type is acceptable according to memoryTypeBits bitmask.
if((memTypeBit & memoryTypeBits) != 0)
{
const VkMemoryPropertyFlags currFlags =
allocator->m_MemProps.memoryTypes[memTypeIndex].propertyFlags;
// This memory type contains requiredFlags.
if((requiredFlags & ~currFlags) == 0)
{
// Calculate cost as number of bits from preferredFlags not present in this memory type.
uint32_t currCost = VmaCountBitsSet(preferredFlags & ~currFlags);
// Remember memory type with lowest cost.
if(currCost < minCost)
{
*pMemoryTypeIndex = memTypeIndex;
if(currCost == 0)
{
return VK_SUCCESS;
}
minCost = currCost;
}
}
}
}
return (*pMemoryTypeIndex != UINT32_MAX) ? VK_SUCCESS : VK_ERROR_FEATURE_NOT_PRESENT;
}
VkResult vmaFindMemoryTypeIndexForBufferInfo(
VmaAllocator allocator,
const VkBufferCreateInfo* pBufferCreateInfo,
const VmaAllocationCreateInfo* pAllocationCreateInfo,
uint32_t* pMemoryTypeIndex)
{
VMA_ASSERT(allocator != VK_NULL_HANDLE);
VMA_ASSERT(pBufferCreateInfo != VMA_NULL);
VMA_ASSERT(pAllocationCreateInfo != VMA_NULL);
VMA_ASSERT(pMemoryTypeIndex != VMA_NULL);
const VkDevice hDev = allocator->m_hDevice;
VkBuffer hBuffer = VK_NULL_HANDLE;
VkResult res = allocator->GetVulkanFunctions().vkCreateBuffer(
hDev, pBufferCreateInfo, allocator->GetAllocationCallbacks(), &hBuffer);
if(res == VK_SUCCESS)
{
VkMemoryRequirements memReq = {};
allocator->GetVulkanFunctions().vkGetBufferMemoryRequirements(
hDev, hBuffer, &memReq);
res = vmaFindMemoryTypeIndex(
allocator,
memReq.memoryTypeBits,
pAllocationCreateInfo,
pMemoryTypeIndex);
allocator->GetVulkanFunctions().vkDestroyBuffer(
hDev, hBuffer, allocator->GetAllocationCallbacks());
}
return res;
}
VkResult vmaFindMemoryTypeIndexForImageInfo(
VmaAllocator allocator,
const VkImageCreateInfo* pImageCreateInfo,
const VmaAllocationCreateInfo* pAllocationCreateInfo,
uint32_t* pMemoryTypeIndex)
{
VMA_ASSERT(allocator != VK_NULL_HANDLE);
VMA_ASSERT(pImageCreateInfo != VMA_NULL);
VMA_ASSERT(pAllocationCreateInfo != VMA_NULL);
VMA_ASSERT(pMemoryTypeIndex != VMA_NULL);
const VkDevice hDev = allocator->m_hDevice;
VkImage hImage = VK_NULL_HANDLE;
VkResult res = allocator->GetVulkanFunctions().vkCreateImage(
hDev, pImageCreateInfo, allocator->GetAllocationCallbacks(), &hImage);
if(res == VK_SUCCESS)
{
VkMemoryRequirements memReq = {};
allocator->GetVulkanFunctions().vkGetImageMemoryRequirements(
hDev, hImage, &memReq);
res = vmaFindMemoryTypeIndex(
allocator,
memReq.memoryTypeBits,
pAllocationCreateInfo,
pMemoryTypeIndex);
allocator->GetVulkanFunctions().vkDestroyImage(
hDev, hImage, allocator->GetAllocationCallbacks());
}
return res;
}
VkResult vmaCreatePool(
VmaAllocator allocator,
const VmaPoolCreateInfo* pCreateInfo,
VmaPool* pPool)
{
VMA_ASSERT(allocator && pCreateInfo && pPool);
VMA_DEBUG_LOG("vmaCreatePool");
VMA_DEBUG_GLOBAL_MUTEX_LOCK
return allocator->CreatePool(pCreateInfo, pPool);
}
void vmaDestroyPool(
VmaAllocator allocator,
VmaPool pool)
{
VMA_ASSERT(allocator);
if(pool == VK_NULL_HANDLE)
{
return;
}
VMA_DEBUG_LOG("vmaDestroyPool");
VMA_DEBUG_GLOBAL_MUTEX_LOCK
allocator->DestroyPool(pool);
}
void vmaGetPoolStats(
VmaAllocator allocator,
VmaPool pool,
VmaPoolStats* pPoolStats)
{
VMA_ASSERT(allocator && pool && pPoolStats);
VMA_DEBUG_GLOBAL_MUTEX_LOCK
allocator->GetPoolStats(pool, pPoolStats);
}
void vmaMakePoolAllocationsLost(
VmaAllocator allocator,
VmaPool pool,
size_t* pLostAllocationCount)
{
VMA_ASSERT(allocator && pool);
VMA_DEBUG_GLOBAL_MUTEX_LOCK
allocator->MakePoolAllocationsLost(pool, pLostAllocationCount);
}
VkResult vmaAllocateMemory(
VmaAllocator allocator,
const VkMemoryRequirements* pVkMemoryRequirements,
const VmaAllocationCreateInfo* pCreateInfo,
VmaAllocation* pAllocation,
VmaAllocationInfo* pAllocationInfo)
{
VMA_ASSERT(allocator && pVkMemoryRequirements && pCreateInfo && pAllocation);
VMA_DEBUG_LOG("vmaAllocateMemory");
VMA_DEBUG_GLOBAL_MUTEX_LOCK
VkResult result = allocator->AllocateMemory(
*pVkMemoryRequirements,
false, // requiresDedicatedAllocation
false, // prefersDedicatedAllocation
VK_NULL_HANDLE, // dedicatedBuffer
VK_NULL_HANDLE, // dedicatedImage
*pCreateInfo,
VMA_SUBALLOCATION_TYPE_UNKNOWN,
pAllocation);
if(pAllocationInfo && result == VK_SUCCESS)
{
allocator->GetAllocationInfo(*pAllocation, pAllocationInfo);
}
return result;
}
VkResult vmaAllocateMemoryForBuffer(
VmaAllocator allocator,
VkBuffer buffer,
const VmaAllocationCreateInfo* pCreateInfo,
VmaAllocation* pAllocation,
VmaAllocationInfo* pAllocationInfo)
{
VMA_ASSERT(allocator && buffer != VK_NULL_HANDLE && pCreateInfo && pAllocation);
VMA_DEBUG_LOG("vmaAllocateMemoryForBuffer");
VMA_DEBUG_GLOBAL_MUTEX_LOCK
VkMemoryRequirements vkMemReq = {};
bool requiresDedicatedAllocation = false;
bool prefersDedicatedAllocation = false;
allocator->GetBufferMemoryRequirements(buffer, vkMemReq,
requiresDedicatedAllocation,
prefersDedicatedAllocation);
VkResult result = allocator->AllocateMemory(
vkMemReq,
requiresDedicatedAllocation,
prefersDedicatedAllocation,
buffer, // dedicatedBuffer
VK_NULL_HANDLE, // dedicatedImage
*pCreateInfo,
VMA_SUBALLOCATION_TYPE_BUFFER,
pAllocation);
if(pAllocationInfo && result == VK_SUCCESS)
{
allocator->GetAllocationInfo(*pAllocation, pAllocationInfo);
}
return result;
}
VkResult vmaAllocateMemoryForImage(
VmaAllocator allocator,
VkImage image,
const VmaAllocationCreateInfo* pCreateInfo,
VmaAllocation* pAllocation,
VmaAllocationInfo* pAllocationInfo)
{
VMA_ASSERT(allocator && image != VK_NULL_HANDLE && pCreateInfo && pAllocation);
VMA_DEBUG_LOG("vmaAllocateMemoryForImage");
VMA_DEBUG_GLOBAL_MUTEX_LOCK
VkResult result = AllocateMemoryForImage(
allocator,
image,
pCreateInfo,
VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN,
pAllocation);
if(pAllocationInfo && result == VK_SUCCESS)
{
allocator->GetAllocationInfo(*pAllocation, pAllocationInfo);
}
return result;
}
void vmaFreeMemory(
VmaAllocator allocator,
VmaAllocation allocation)
{
VMA_ASSERT(allocator && allocation);
VMA_DEBUG_LOG("vmaFreeMemory");
VMA_DEBUG_GLOBAL_MUTEX_LOCK
allocator->FreeMemory(allocation);
}
void vmaGetAllocationInfo(
VmaAllocator allocator,
VmaAllocation allocation,
VmaAllocationInfo* pAllocationInfo)
{
VMA_ASSERT(allocator && allocation && pAllocationInfo);
VMA_DEBUG_GLOBAL_MUTEX_LOCK
allocator->GetAllocationInfo(allocation, pAllocationInfo);
}
VkBool32 vmaTouchAllocation(
VmaAllocator allocator,
VmaAllocation allocation)
{
VMA_ASSERT(allocator && allocation);
VMA_DEBUG_GLOBAL_MUTEX_LOCK
return allocator->TouchAllocation(allocation);
}
void vmaSetAllocationUserData(
VmaAllocator allocator,
VmaAllocation allocation,
void* pUserData)
{
VMA_ASSERT(allocator && allocation);
VMA_DEBUG_GLOBAL_MUTEX_LOCK
allocation->SetUserData(allocator, pUserData);
}
void vmaCreateLostAllocation(
VmaAllocator allocator,
VmaAllocation* pAllocation)
{
VMA_ASSERT(allocator && pAllocation);
VMA_DEBUG_GLOBAL_MUTEX_LOCK;
allocator->CreateLostAllocation(pAllocation);
}
VkResult vmaMapMemory(
VmaAllocator allocator,
VmaAllocation allocation,
void** ppData)
{
VMA_ASSERT(allocator && allocation && ppData);
VMA_DEBUG_GLOBAL_MUTEX_LOCK
return allocator->Map(allocation, ppData);
}
void vmaUnmapMemory(
VmaAllocator allocator,
VmaAllocation allocation)
{
VMA_ASSERT(allocator && allocation);
VMA_DEBUG_GLOBAL_MUTEX_LOCK
allocator->Unmap(allocation);
}
VkResult vmaDefragment(
VmaAllocator allocator,
VmaAllocation* pAllocations,
size_t allocationCount,
VkBool32* pAllocationsChanged,
const VmaDefragmentationInfo *pDefragmentationInfo,
VmaDefragmentationStats* pDefragmentationStats)
{
VMA_ASSERT(allocator && pAllocations);
VMA_DEBUG_LOG("vmaDefragment");
VMA_DEBUG_GLOBAL_MUTEX_LOCK
return allocator->Defragment(pAllocations, allocationCount, pAllocationsChanged, pDefragmentationInfo, pDefragmentationStats);
}
VkResult vmaBindBufferMemory(
VmaAllocator allocator,
VmaAllocation allocation,
VkBuffer buffer)
{
VMA_ASSERT(allocator && allocation && buffer);
VMA_DEBUG_LOG("vmaBindBufferMemory");
VMA_DEBUG_GLOBAL_MUTEX_LOCK
return allocator->BindBufferMemory(allocation, buffer);
}
VkResult vmaBindImageMemory(
VmaAllocator allocator,
VmaAllocation allocation,
VkImage image)
{
VMA_ASSERT(allocator && allocation && image);
VMA_DEBUG_LOG("vmaBindImageMemory");
VMA_DEBUG_GLOBAL_MUTEX_LOCK
return allocator->BindImageMemory(allocation, image);
}
VkResult vmaCreateBuffer(
VmaAllocator allocator,
const VkBufferCreateInfo* pBufferCreateInfo,
const VmaAllocationCreateInfo* pAllocationCreateInfo,
VkBuffer* pBuffer,
VmaAllocation* pAllocation,
VmaAllocationInfo* pAllocationInfo)
{
VMA_ASSERT(allocator && pBufferCreateInfo && pAllocationCreateInfo && pBuffer && pAllocation);
VMA_DEBUG_LOG("vmaCreateBuffer");
VMA_DEBUG_GLOBAL_MUTEX_LOCK
*pBuffer = VK_NULL_HANDLE;
*pAllocation = VK_NULL_HANDLE;
// 1. Create VkBuffer.
VkResult res = (*allocator->GetVulkanFunctions().vkCreateBuffer)(
allocator->m_hDevice,
pBufferCreateInfo,
allocator->GetAllocationCallbacks(),
pBuffer);
if(res >= 0)
{
// 2. vkGetBufferMemoryRequirements.
VkMemoryRequirements vkMemReq = {};
bool requiresDedicatedAllocation = false;
bool prefersDedicatedAllocation = false;
allocator->GetBufferMemoryRequirements(*pBuffer, vkMemReq,
requiresDedicatedAllocation, prefersDedicatedAllocation);
// Make sure alignment requirements for specific buffer usages reported
// in Physical Device Properties are included in alignment reported by memory requirements.
if((pBufferCreateInfo->usage & VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT) != 0)
{
VMA_ASSERT(vkMemReq.alignment %
allocator->m_PhysicalDeviceProperties.limits.minTexelBufferOffsetAlignment == 0);
}
if((pBufferCreateInfo->usage & VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT) != 0)
{
VMA_ASSERT(vkMemReq.alignment %
allocator->m_PhysicalDeviceProperties.limits.minUniformBufferOffsetAlignment == 0);
}
if((pBufferCreateInfo->usage & VK_BUFFER_USAGE_STORAGE_BUFFER_BIT) != 0)
{
VMA_ASSERT(vkMemReq.alignment %
allocator->m_PhysicalDeviceProperties.limits.minStorageBufferOffsetAlignment == 0);
}
// 3. Allocate memory using allocator.
res = allocator->AllocateMemory(
vkMemReq,
requiresDedicatedAllocation,
prefersDedicatedAllocation,
*pBuffer, // dedicatedBuffer
VK_NULL_HANDLE, // dedicatedImage
*pAllocationCreateInfo,
VMA_SUBALLOCATION_TYPE_BUFFER,
pAllocation);
if(res >= 0)
{
// 3. Bind buffer with memory.
res = allocator->BindBufferMemory(*pAllocation, *pBuffer);
if(res >= 0)
{
// All steps succeeded.
if(pAllocationInfo != VMA_NULL)
{
allocator->GetAllocationInfo(*pAllocation, pAllocationInfo);
}
return VK_SUCCESS;
}
allocator->FreeMemory(*pAllocation);
*pAllocation = VK_NULL_HANDLE;
(*allocator->GetVulkanFunctions().vkDestroyBuffer)(allocator->m_hDevice, *pBuffer, allocator->GetAllocationCallbacks());
*pBuffer = VK_NULL_HANDLE;
return res;
}
(*allocator->GetVulkanFunctions().vkDestroyBuffer)(allocator->m_hDevice, *pBuffer, allocator->GetAllocationCallbacks());
*pBuffer = VK_NULL_HANDLE;
return res;
}
return res;
}
void vmaDestroyBuffer(
VmaAllocator allocator,
VkBuffer buffer,
VmaAllocation allocation)
{
if(buffer != VK_NULL_HANDLE)
{
VMA_ASSERT(allocator);
VMA_DEBUG_LOG("vmaDestroyBuffer");
VMA_DEBUG_GLOBAL_MUTEX_LOCK
(*allocator->GetVulkanFunctions().vkDestroyBuffer)(allocator->m_hDevice, buffer, allocator->GetAllocationCallbacks());
allocator->FreeMemory(allocation);
}
}
VkResult vmaCreateImage(
VmaAllocator allocator,
const VkImageCreateInfo* pImageCreateInfo,
const VmaAllocationCreateInfo* pAllocationCreateInfo,
VkImage* pImage,
VmaAllocation* pAllocation,
VmaAllocationInfo* pAllocationInfo)
{
VMA_ASSERT(allocator && pImageCreateInfo && pAllocationCreateInfo && pImage && pAllocation);
VMA_DEBUG_LOG("vmaCreateImage");
VMA_DEBUG_GLOBAL_MUTEX_LOCK
*pImage = VK_NULL_HANDLE;
*pAllocation = VK_NULL_HANDLE;
// 1. Create VkImage.
VkResult res = (*allocator->GetVulkanFunctions().vkCreateImage)(
allocator->m_hDevice,
pImageCreateInfo,
allocator->GetAllocationCallbacks(),
pImage);
if(res >= 0)
{
VmaSuballocationType suballocType = pImageCreateInfo->tiling == VK_IMAGE_TILING_OPTIMAL ?
VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL :
VMA_SUBALLOCATION_TYPE_IMAGE_LINEAR;
// 2. Allocate memory using allocator.
res = AllocateMemoryForImage(allocator, *pImage, pAllocationCreateInfo, suballocType, pAllocation);
if(res >= 0)
{
// 3. Bind image with memory.
res = allocator->BindImageMemory(*pAllocation, *pImage);
if(res >= 0)
{
// All steps succeeded.
if(pAllocationInfo != VMA_NULL)
{
allocator->GetAllocationInfo(*pAllocation, pAllocationInfo);
}
return VK_SUCCESS;
}
allocator->FreeMemory(*pAllocation);
*pAllocation = VK_NULL_HANDLE;
(*allocator->GetVulkanFunctions().vkDestroyImage)(allocator->m_hDevice, *pImage, allocator->GetAllocationCallbacks());
*pImage = VK_NULL_HANDLE;
return res;
}
(*allocator->GetVulkanFunctions().vkDestroyImage)(allocator->m_hDevice, *pImage, allocator->GetAllocationCallbacks());
*pImage = VK_NULL_HANDLE;
return res;
}
return res;
}
void vmaDestroyImage(
VmaAllocator allocator,
VkImage image,
VmaAllocation allocation)
{
if(image != VK_NULL_HANDLE)
{
VMA_ASSERT(allocator);
VMA_DEBUG_LOG("vmaDestroyImage");
VMA_DEBUG_GLOBAL_MUTEX_LOCK
(*allocator->GetVulkanFunctions().vkDestroyImage)(allocator->m_hDevice, image, allocator->GetAllocationCallbacks());
allocator->FreeMemory(allocation);
}
}
#endif // #ifdef VMA_IMPLEMENTATION
| [
"jackerb@Jacks-MacBook-Pro.local"
] | jackerb@Jacks-MacBook-Pro.local |
924a95ef78ecf474f30d02f02c9082b5719ce13f | 2098c74a59133c985e10f57a901bc5839a6d1333 | /Source/XrGame/CarWeapon.cpp | 672daeb379208c7812519e1cc5ccc517da67484b | [] | no_license | ChuniMuni/XRayEngine | 28672b4c5939e95c6dfb24c9514041dd25cfa306 | cdb13c23552fd86409b6e4e2925ac78064ee8739 | refs/heads/master | 2023-04-02T01:04:01.134317 | 2021-04-10T07:44:41 | 2021-04-10T07:44:41 | 266,738,168 | 1 | 0 | null | 2021-04-10T07:44:41 | 2020-05-25T09:27:11 | C++ | UTF-8 | C++ | false | false | 7,892 | cpp | #include "stdafx.h"
#include "CarWeapon.h"
#include "../xrphysics/PhysicsShell.h"
#include "PhysicsShellHolder.h"
//#include "Kinematics.h"
#include "Kinematics.h"
#include "object_broker.h"
#include "ai_sounds.h"
#include "weaponAmmo.h"
#include "xr_level_controller.h"
#include "game_object_space.h"
void CCarWeapon::BoneCallbackX (CBoneInstance *B)
{
CCarWeapon *P = static_cast<CCarWeapon*>(B->callback_param());
Fmatrix rX; rX.rotateX (P->m_cur_x_rot);
B->mTransform.mulB_43 (rX);
}
void CCarWeapon::BoneCallbackY (CBoneInstance *B)
{
CCarWeapon *P = static_cast<CCarWeapon*>(B->callback_param());
Fmatrix rY; rY.rotateY (P->m_cur_y_rot);
B->mTransform.mulB_43 (rY);
}
CCarWeapon::CCarWeapon(CPhysicsShellHolder* obj)
{
m_bActive = false;
m_bAutoFire = false;
m_object = obj;
m_Ammo = xr_new<CCartridge>();
IKinematics* K = smart_cast<IKinematics*>(m_object->Visual());
CInifile* pUserData = K->LL_UserData();
m_rotate_x_bone = K->LL_BoneID (pUserData->r_string("mounted_weapon_definition","rotate_x_bone"));
m_rotate_y_bone = K->LL_BoneID (pUserData->r_string("mounted_weapon_definition","rotate_y_bone"));
m_fire_bone = K->LL_BoneID (pUserData->r_string("mounted_weapon_definition","fire_bone"));
m_min_gun_speed = pUserData->r_float("mounted_weapon_definition","min_gun_speed");
m_max_gun_speed = pUserData->r_float("mounted_weapon_definition","max_gun_speed");
CBoneData& bdX = K->LL_GetData(m_rotate_x_bone); //VERIFY(bdX.IK_data.type==jtJoint);
m_lim_x_rot.set (bdX.IK_data.limits[0].limit.x,bdX.IK_data.limits[0].limit.y);
CBoneData& bdY = K->LL_GetData(m_rotate_y_bone); //VERIFY(bdY.IK_data.type==jtJoint);
m_lim_y_rot.set (bdY.IK_data.limits[1].limit.x,bdY.IK_data.limits[1].limit.y);
xr_vector<Fmatrix> matrices;
K->LL_GetBindTransform (matrices);
m_i_bind_x_xform.invert (matrices[m_rotate_x_bone]);
m_i_bind_y_xform.invert (matrices[m_rotate_y_bone]);
m_bind_x_rot = matrices[m_rotate_x_bone].k.getP();
m_bind_y_rot = matrices[m_rotate_y_bone].k.getH();
m_bind_x.set (matrices[m_rotate_x_bone].c);
m_bind_y.set (matrices[m_rotate_y_bone].c);
m_cur_x_rot = m_bind_x_rot;
m_cur_y_rot = m_bind_y_rot;
m_destEnemyDir.setHP (m_bind_y_rot,m_bind_x_rot);
m_object->XFORM().transform_dir (m_destEnemyDir);
inheritedShooting::Light_Create ();
Load (pUserData->r_string("mounted_weapon_definition","wpn_section"));
SetBoneCallbacks ();
m_object->processing_activate ();
m_weapon_h = matrices[m_rotate_y_bone].c.y;
m_fire_norm.set (0,1,0);
m_fire_dir.set (0,0,1);
m_fire_pos.set (0,0,0);
}
CCarWeapon::~CCarWeapon()
{
delete_data(m_Ammo);
//. m_object->processing_deactivate ();
}
void CCarWeapon::Load(LPCSTR section)
{
inheritedShooting::Load(section);
HUD_SOUND_ITEM::LoadSound(section,"snd_shoot", m_sndShot, SOUND_TYPE_WEAPON_SHOOTING);
m_Ammo->Load(pSettings->r_string(section, "ammo_class"), 0);
}
void CCarWeapon::UpdateCL()
{
if(!m_bActive) return;
UpdateBarrelDir ();
IKinematics* K = smart_cast<IKinematics*>(m_object->Visual());
K->CalculateBones_Invalidate();
K->CalculateBones (TRUE);
UpdateFire ();
}
void CCarWeapon::UpdateFire()
{
fShotTimeCounter -= Device.fTimeDelta;
inheritedShooting::UpdateFlameParticles();
inheritedShooting::UpdateLight();
if(m_bAutoFire){
if(m_allow_fire){
FireStart();
}else
FireEnd();
};
if(!IsWorking())
{
clamp(fShotTimeCounter, 0.0f, flt_max);
return;
}
if(fShotTimeCounter<=0)
{
OnShot();
fShotTimeCounter += fOneShotTime;
}
}
void CCarWeapon::Render_internal()
{
RenderLight ();
}
void CCarWeapon::SetBoneCallbacks()
{
// m_object->PPhysicsShell()->EnabledCallbacks(FALSE);
CBoneInstance& biX = smart_cast<IKinematics*>(m_object->Visual())->LL_GetBoneInstance(m_rotate_x_bone);
biX.set_callback (bctCustom,BoneCallbackX,this);
CBoneInstance& biY = smart_cast<IKinematics*>(m_object->Visual())->LL_GetBoneInstance(m_rotate_y_bone);
biY.set_callback (bctCustom,BoneCallbackY,this);
}
void CCarWeapon::ResetBoneCallbacks()
{
CBoneInstance& biX = smart_cast<IKinematics*>(m_object->Visual())->LL_GetBoneInstance(m_rotate_x_bone);
biX.reset_callback ();
CBoneInstance& biY = smart_cast<IKinematics*>(m_object->Visual())->LL_GetBoneInstance(m_rotate_y_bone);
biY.reset_callback ();
// m_object->PPhysicsShell()->EnabledCallbacks(TRUE);
}
void CCarWeapon::UpdateBarrelDir()
{
IKinematics* K = smart_cast<IKinematics*>(m_object->Visual());
m_fire_bone_xform = K->LL_GetTransform(m_fire_bone);
m_fire_bone_xform.mulA_43(m_object->XFORM());
m_fire_pos.set(0,0,0);
m_fire_bone_xform.transform_tiny(m_fire_pos);
m_fire_dir.set(0,0,1);
m_fire_bone_xform.transform_dir(m_fire_dir);
m_fire_norm.set(0,1,0);
m_fire_bone_xform.transform_dir(m_fire_norm);
m_allow_fire = true;
Fmatrix XFi;
XFi.invert (m_object->XFORM());
Fvector dep;
XFi.transform_dir (dep,m_destEnemyDir);
{// x angle
m_i_bind_x_xform.transform_dir(dep); dep.normalize();
m_tgt_x_rot = angle_normalize_signed(m_bind_x_rot-dep.getP());
clamp (m_tgt_x_rot,-m_lim_x_rot.y,-m_lim_x_rot.x);
}
{// y angle
m_i_bind_y_xform.transform_dir(dep); dep.normalize();
m_tgt_y_rot = angle_normalize_signed(m_bind_y_rot-dep.getH());
clamp (m_tgt_y_rot,-m_lim_y_rot.y,-m_lim_y_rot.x);
}
m_cur_x_rot = angle_inertion_var(m_cur_x_rot,m_tgt_x_rot,m_min_gun_speed,m_max_gun_speed,PI,Device.fTimeDelta);
m_cur_y_rot = angle_inertion_var(m_cur_y_rot,m_tgt_y_rot,m_min_gun_speed,m_max_gun_speed,PI,Device.fTimeDelta);
static float dir_eps = deg2rad(5.0f);
if( !fsimilar(m_cur_x_rot,m_tgt_x_rot,dir_eps)|| !fsimilar(m_cur_y_rot,m_tgt_y_rot,dir_eps))
m_allow_fire=FALSE;
#if (0)
if(Device.dwFrame%200==0){
Msg("m_cur_x_rot=[%f]",m_cur_x_rot);
Msg("m_cur_y_rot=[%f]",m_cur_y_rot);
}
#endif
}
bool CCarWeapon::AllowFire()
{
return m_allow_fire;
}
float CCarWeapon::FireDirDiff()
{
Fvector d1,d2;
d1.set(m_cur_x_rot,m_cur_y_rot,0).normalize_safe();
d2.set(m_tgt_x_rot,m_tgt_y_rot,0).normalize_safe();
return rad2deg( acos(d1.dotproduct(d2)) );
}
const Fvector& CCarWeapon::get_CurrentFirePoint()
{
return m_fire_pos;
}
const Fmatrix& CCarWeapon::get_ParticlesXFORM ()
{
return m_fire_bone_xform;
}
void CCarWeapon::FireStart()
{
inheritedShooting::FireStart();
}
void CCarWeapon::FireEnd()
{
inheritedShooting::FireEnd();
StopFlameParticles ();
}
void CCarWeapon::OnShot()
{
FireBullet ( m_fire_pos, m_fire_dir, fireDispersionBase, *m_Ammo,
m_object->ID(), m_object->ID(), SendHitAllowed(m_object));
StartShotParticles ();
if(m_bLightShotEnabled)
Light_Start ();
StartFlameParticles ();
StartSmokeParticles (m_fire_pos, zero_vel);
// OnShellDrop (m_fire_pos, zero_vel);
HUD_SOUND_ITEM::PlaySound (m_sndShot, m_fire_pos, m_object, false);
}
void CCarWeapon::Action (u16 id, u32 flags)
{
switch (id){
case eWpnFire:{
if(flags==1) FireStart ();
else FireEnd ();
}break;
case eWpnActivate:{
if(flags==1) m_bActive = true;
else {m_bActive = false; FireEnd();}
}break;
case eWpnAutoFire:{
if(flags==1) m_bAutoFire = true;
else m_bAutoFire = false;
}break;
case eWpnToDefaultDir:{
SetParam(eWpnDesiredDir,Fvector2().set(m_bind_y_rot,m_bind_x_rot));
}break;
}
}
void CCarWeapon::SetParam (int id, Fvector2 val)
{
switch (id){
case eWpnDesiredDir:
m_destEnemyDir.setHP (val.x,val.y);
break;
}
}
void CCarWeapon::SetParam (int id, Fvector val)
{
switch (id){
case eWpnDesiredPos:
m_destEnemyDir.sub(val,m_fire_pos).normalize_safe();
break;
}
}
const Fvector& CCarWeapon::ViewCameraPos()
{
return m_fire_pos;
}
const Fvector& CCarWeapon::ViewCameraDir()
{
return m_fire_dir;
}
const Fvector& CCarWeapon::ViewCameraNorm()
{
return m_fire_norm;
}
| [
"i-sobolevskiy@mail.ru"
] | i-sobolevskiy@mail.ru |
5cab0b4c1e72162147803a8e31e55f0fff80508d | 720fde4499c86b45e651fdba0b9db1280d0ee935 | /src/ui_interface.h | 58c9f4fd8e591430a148e8e488d4df88d325a380 | [
"MIT"
] | permissive | wolfxpack/wolf | 171760e94c2fd2a2e0f7de940f656a756145c7a9 | 47b57381dc93bfb150be76cc6d288daffd1c37e6 | refs/heads/master | 2020-04-21T17:30:14.399335 | 2019-02-25T01:03:50 | 2019-02-25T01:03:50 | 169,737,526 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,964 | h | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2012-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef WOLF_UI_INTERFACE_H
#define WOLF_UI_INTERFACE_H
#include <stdint.h>
#include <string>
#include <boost/signals2/last_value.hpp>
#include <boost/signals2/signal.hpp>
class CBasicKeyStore;
class CWallet;
class uint256;
class CBlockIndex;
/** General change type (added, updated, removed). */
enum ChangeType
{
CT_NEW,
CT_UPDATED,
CT_DELETED
};
/** Signals for UI communication. */
class CClientUIInterface
{
public:
/** Flags for CClientUIInterface::ThreadSafeMessageBox */
enum MessageBoxFlags
{
ICON_INFORMATION = 0,
ICON_WARNING = (1U << 0),
ICON_ERROR = (1U << 1),
/**
* Mask of all available icons in CClientUIInterface::MessageBoxFlags
* This needs to be updated, when icons are changed there!
*/
ICON_MASK = (ICON_INFORMATION | ICON_WARNING | ICON_ERROR),
/** These values are taken from qmessagebox.h "enum StandardButton" to be directly usable */
BTN_OK = 0x00000400U, // QMessageBox::Ok
BTN_YES = 0x00004000U, // QMessageBox::Yes
BTN_NO = 0x00010000U, // QMessageBox::No
BTN_ABORT = 0x00040000U, // QMessageBox::Abort
BTN_RETRY = 0x00080000U, // QMessageBox::Retry
BTN_IGNORE = 0x00100000U, // QMessageBox::Ignore
BTN_CLOSE = 0x00200000U, // QMessageBox::Close
BTN_CANCEL = 0x00400000U, // QMessageBox::Cancel
BTN_DISCARD = 0x00800000U, // QMessageBox::Discard
BTN_HELP = 0x01000000U, // QMessageBox::Help
BTN_APPLY = 0x02000000U, // QMessageBox::Apply
BTN_RESET = 0x04000000U, // QMessageBox::Reset
/**
* Mask of all available buttons in CClientUIInterface::MessageBoxFlags
* This needs to be updated, when buttons are changed there!
*/
BTN_MASK = (BTN_OK | BTN_YES | BTN_NO | BTN_ABORT | BTN_RETRY | BTN_IGNORE |
BTN_CLOSE | BTN_CANCEL | BTN_DISCARD | BTN_HELP | BTN_APPLY | BTN_RESET),
/** Force blocking, modal message box dialog (not just OS notification) */
MODAL = 0x10000000U,
/** Do not print contents of message to debug log */
SECURE = 0x40000000U,
/** Predefined combinations for certain default usage cases */
MSG_INFORMATION = ICON_INFORMATION,
MSG_WARNING = (ICON_WARNING | BTN_OK | MODAL),
MSG_ERROR = (ICON_ERROR | BTN_OK | MODAL)
};
/** Show message box. */
boost::signals2::signal<bool (const std::string& message, const std::string& caption, unsigned int style), boost::signals2::last_value<bool> > ThreadSafeMessageBox;
/** If possible, ask the user a question. If not, falls back to ThreadSafeMessageBox(noninteractive_message, caption, style) and returns false. */
boost::signals2::signal<bool (const std::string& message, const std::string& noninteractive_message, const std::string& caption, unsigned int style), boost::signals2::last_value<bool> > ThreadSafeQuestion;
/** Progress message during initialization. */
boost::signals2::signal<void (const std::string &message)> InitMessage;
/** Number of network connections changed. */
boost::signals2::signal<void (int newNumConnections)> NotifyNumConnectionsChanged;
/** Network activity state changed. */
boost::signals2::signal<void (bool networkActive)> NotifyNetworkActiveChanged;
/** Number of masternodes changed. */
boost::signals2::signal<void (int newNumMasternodes)> NotifyStrMasternodeCountChanged;
/**
* New, updated or cancelled alert.
* @note called with lock cs_mapAlerts held.
*/
boost::signals2::signal<void (const uint256 &hash, ChangeType status)> NotifyAlertChanged;
/** A wallet has been loaded. */
boost::signals2::signal<void (CWallet* wallet)> LoadWallet;
/** Show progress e.g. for verifychain */
boost::signals2::signal<void (const std::string &title, int nProgress)> ShowProgress;
/** Set progress break action (possible "cancel button" triggers that action) */
boost::signals2::signal<void (std::function<void(void)> action)> SetProgressBreakAction;
/** New block has been accepted */
boost::signals2::signal<void (bool, const CBlockIndex *)> NotifyBlockTip;
/** Best header has changed */
boost::signals2::signal<void (bool, const CBlockIndex *)> NotifyHeaderTip;
/** Additional data sync progress changed */
boost::signals2::signal<void (double nSyncProgress)> NotifyAdditionalDataSyncProgressChanged;
/** Banlist did change. */
boost::signals2::signal<void (void)> BannedListChanged;
};
extern CClientUIInterface uiInterface;
#endif // WOLF_UI_INTERFACE_H
| [
"eledger102@gmail.com"
] | eledger102@gmail.com |
b78970e629e0c1ca210ae8b2504227193c7b2469 | 6e5c8cbbf6706851dabb02e7cc5efbff35c0adfc | /PopeShader11_04/ColorShader.cpp | d61df7f9a0ccdf61d96d8dbfcb08e88289c5dc6c | [] | no_license | BrianLee-SKorea/SchoolProject | 911a09b4e8c55b1d2a568fe2bca0f32f61f3092c | 91b11c50a01f07b924ee0e893e5f3c76f6857866 | refs/heads/master | 2023-03-05T09:06:59.594006 | 2021-02-14T11:07:09 | 2021-02-14T11:07:09 | 338,541,453 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,174 | cpp | #include "ColorShader.h"
ColorShader::ColorShader()
{
}
ColorShader::~ColorShader()
{
CleanUp();
}
bool ColorShader::Init( ID3D11Device * pDevice )
{
if( nullptr == pDevice )
return false;
ShaderParam vparam;
vparam.filename = L"ColorShader.fx";
vparam.entry = "vs_main";
vparam.model = "vs_5_0";
m_pVS = new ColorVertexShader( vparam );
if( nullptr == m_pVS )
return false;
if( !m_pVS->Init( pDevice ) )
return false;
ShaderParam pparam;
pparam.filename = L"ColorShader.fx";
pparam.entry = "ps_main";
pparam.model = "ps_5_0";
m_pPS = new ColorPixelShader( pparam );
if( nullptr == m_pPS )
return false;
if( !m_pPS->Init( pDevice ) )
return false;
m_pCB = new ConstantBuffer();
if( nullptr == m_pCB )
return false;
if( !m_pCB->Init( pDevice, sizeof( ColorConstantBuffer ) ) )
return false;
return true;
}
void ColorShader::CleanUp()
{
if( m_pCB )
{
delete m_pCB;
m_pCB = nullptr;
}
if( m_pPS )
{
delete m_pPS;
m_pPS = nullptr;
}
if( m_pVS )
{
delete m_pVS;
m_pVS = nullptr;
}
}
ID3D11VertexShader * ColorShader::GetVS() const
{
return m_pVS->GetShader();
}
ID3D11InputLayout * ColorShader::GetIL() const
{
return m_pVS->GetLayout();
}
ID3D11PixelShader * ColorShader::GetPS() const
{
return m_pPS->GetShader();
}
ConstantBuffer * ColorShader::GetCB()
{
return m_pCB;
}
ColorVertexShader::ColorVertexShader( ShaderParam _param )
: IVertexShader( _param )
{
}
bool ColorVertexShader::InitLayout( ID3D11Device * pDevice, ID3DBlob * pBlob )
{
D3D11_INPUT_ELEMENT_DESC layouts[] = {
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
UINT numLayout = ARRAYSIZE( layouts );
HRESULT hr = pDevice->CreateInputLayout( layouts, numLayout, pBlob->GetBufferPointer(), pBlob->GetBufferSize(), &m_pIL );
if( FAILED( hr ) )
{
std::string error = "Create - InputLayout Fail\t";
error += param.entry + "\n";
OutputDebugStringA( error.c_str() );
return false;
}
return true;
}
ColorPixelShader::ColorPixelShader( ShaderParam _param )
: IPixelShader( _param )
{
}
| [
"78999731+BrianLee-SKorea@users.noreply.github.com"
] | 78999731+BrianLee-SKorea@users.noreply.github.com |
88ab17ce89c924ca48706ea3e5acd02216230a42 | 74b6018e594e5cba71d3e26ef70884c92abde0c0 | /mmCoreAndDevices/DeviceAdapters/ASITiger/ASICRISP.h | 90e38617a5e5acc0a8137670ecd991f696faa152 | [
"BSD-3-Clause"
] | permissive | lwxGitHub123/micro-manager | 4b5caec8f25de2b7a9e92e7883eecc026fdc08b9 | a945fdf550ba880744b5b3695fa2c559505f735b | refs/heads/main | 2023-06-24T13:00:29.082165 | 2021-07-29T07:24:13 | 2021-07-29T07:24:13 | 382,203,845 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,133 | h | ///////////////////////////////////////////////////////////////////////////////
// FILE: ASICRISP.h
// PROJECT: Micro-Manager
// SUBSYSTEM: DeviceAdapters
//-----------------------------------------------------------------------------
// DESCRIPTION: ASI CRISP autofocus device adapter
//
// COPYRIGHT: Applied Scientific Instrumentation, Eugene OR
//
// LICENSE: This file is distributed under the BSD license.
//
// This file 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.
//
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
//
// AUTHOR: Jon Daniels (jon@asiimaging.com) 09/2013
//
// BASED ON: ASIStage.h and others
//
#ifndef _ASICRISP_H_
#define _ASICRISP_H_
#include "ASIPeripheralBase.h"
#include "MMDevice.h"
#include "DeviceBase.h"
class CCRISP : public ASIPeripheralBase<CAutoFocusBase, CCRISP>
{
public:
CCRISP(const char* name);
~CCRISP() { }
// Device API
// ----------
int Initialize();
bool Busy();
// AutoFocus API
// -------------
int SetContinuousFocusing(bool state);
int GetContinuousFocusing(bool& state);
bool IsContinuousFocusLocked();
int FullFocus();
int IncrementalFocus();
int GetLastFocusScore(double& score);
int GetCurrentFocusScore(double& score);
int GetOffset(double& offset);
int SetOffset(double offset);
// action interface
// ----------------
int OnRefreshProperties (MM::PropertyBase* pProp, MM::ActionType eAct);
int OnFocusState (MM::PropertyBase* pProp, MM::ActionType eAct);
int OnWaitAfterLock (MM::PropertyBase* pProp, MM::ActionType eAct);
int OnNA (MM::PropertyBase* pProp, MM::ActionType eAct);
int OnCalGain (MM::PropertyBase* pProp, MM::ActionType eAct);
int OnLockRange (MM::PropertyBase* pProp, MM::ActionType eAct);
int OnLEDIntensity (MM::PropertyBase* pProp, MM::ActionType eAct);
int OnLoopGainMultiplier(MM::PropertyBase* pProp, MM::ActionType eAct);
int OnNumAvg (MM::PropertyBase* pProp, MM::ActionType eAct);
int OnSNR (MM::PropertyBase* pProp, MM::ActionType eAct);
int OnDitherError (MM::PropertyBase* pProp, MM::ActionType eAct);
int OnLogAmpAGC (MM::PropertyBase* pProp, MM::ActionType eAct);
int OnNumSkips (MM::PropertyBase* pProp, MM::ActionType eAct);
int OnInFocusRange (MM::PropertyBase* pProp, MM::ActionType eAct);
int OnSum (MM::PropertyBase* pProp, MM::ActionType eAct);
int OnOffset (MM::PropertyBase* pProp, MM::ActionType eAct);
private:
string axisLetter_;
string focusState_;
long waitAfterLock_;
long sum_;
int UpdateFocusState();
int SetFocusState(string focusState);
int ForceSetFocusState(string focusState);
};
#endif //_ASICRISP_H_
| [
"test@test.com"
] | test@test.com |
1b4938d9ea30dd37d895541cf53fd34622a5c886 | 06c2a221d060076e2f30d4e602a98c2c435dc0bb | /src/Components_Web/PowerSensorV3_Web.h | 505b2e6bd1b67add455a542f95a55028664e347d | [] | no_license | vinistig/Gbox420 | 4804b109fa46f06bb82d7cde485d360de33f013a | beb5f95b912aeb077c5a1d81bcfe7484ab8d99a0 | refs/heads/master | 2022-06-23T14:25:16.367011 | 2020-05-05T13:11:17 | 2020-05-05T13:11:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 898 | h | #pragma once
#define PZEM004_NO_SWSERIAL ///Singals to the PZEM004Tv30 module to use HardwareSerial instead of SoftwareSerial
#include "PZEM004Tv30.h" ///3rd party module for the PZEM004T V3.0 power sensor
#include "420Common_Web.h"
#include "420Module_Web.h"
#include "../Components/PowerSensorV3.h"
///PZEM004T v3.0 power sensor - website component
class PowerSensorV3_Web : public PowerSensorV3, public Common_Web
{
public:
PowerSensorV3_Web(const __FlashStringHelper *Name, Module_Web *Parent, HardwareSerial *SerialPort); ///constructor
void websiteEvent_Refresh(__attribute__((unused)) char *url);
void websiteEvent_Load(__attribute__((unused)) char *url){}; ///Not used
void websiteEvent_Button(__attribute__((unused)) char *Button){}; ///Not used
void websiteEvent_Field(__attribute__((unused)) char *Field){}; ///Not used
private:
protected:
Module_Web *Parent;
}; | [
"growboxguy@gmail.com"
] | growboxguy@gmail.com |
529efeee5aee92bf681459ee024bd3cff7058386 | 95d3344ea7e047b3e6b52a03a27cf277aef137e4 | /Modules/pblib/pblib_pb2cnf.hpp | 93993ae6d2d853ec21d7c9515fef0dc944cef0e7 | [
"MIT"
] | permissive | rjungbeck/pypblib | 75a07fa07bacb948092d0a67d75bf2851b50e4ff | dc0c740e4785da889d18d6ee1e37cb5237407b37 | refs/heads/master | 2023-03-04T12:10:13.777835 | 2023-03-02T11:17:26 | 2023-03-02T11:17:26 | 227,091,944 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 577 | hpp | /*
* PyPB pb2cnf bindings
*/
#ifndef _PBLIB_PB2CNF_HPP_
#define _PBLIB_PB2CNF_HPP_
#include <Python.h>
#include <pb2cnf.h>
#ifdef __cplusplus
extern "C" {
#endif
//Name used as refrence within Python
#define PyPb2cnf_NAME "Pb2cnf"
extern PyTypeObject PyPb2cnf_Type;
typedef struct {
PyObject_HEAD;
PB2CNF pb2cnf;
} PyPb2cnf;
#define PyPb2cnf_Check(x) ((x)->ob_type == &PyPb2cnf_Type)
// *** Prototypes ***
void Build_PyList_Formula(PyObject* py_formula, std::vector<std::vector<int>> &formula);
#ifdef __cplusplus
}
#endif
#endif // _PBLIB_PB2CNF_HPP_
| [
"ruediger.jungbeck@rsj.de"
] | ruediger.jungbeck@rsj.de |
6b81b7ea919253b33ecec9cb5cc023b67cda12e1 | f56e0806111f134b94eb46370e32d6d01ffd102c | /codechef/june2017_cloning.cpp | 4d75dcdae6f6ebb68ab1196e8ffd9fabe8bcbf75 | [] | no_license | ajayhegde96/Competitive-Coding | 9b679d64cae302761d849308fb8499bd96e5debf | ab922c30a472133f508b3cfa111c02a46d526e8c | refs/heads/master | 2021-03-22T00:12:36.806227 | 2017-09-29T15:58:14 | 2017-09-29T15:58:14 | 83,832,623 | 0 | 4 | null | 2018-10-05T07:48:30 | 2017-03-03T19:14:57 | C++ | UTF-8 | C++ | false | false | 854 | cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin>>t;
while(t--){
int n,q;
cin>>n>>q;
int A[n];
for(int i=0;i<n;i++)
cin>>A[i];
while(q--){
int a,b,c,d,k=0,k1=0;
cin>>a>>b>>c>>d;
a=a-1;
b=b;
c=c-1;
d=d;
vector<int>v1(A+a,A+b);
vector<int>v2(A+c,A+d);
sort(v1.begin(),v1.end());
sort(v2.begin(),v2.end());
while(k<v1.size()){
if(v1[k]!=v2[k]){
k1++;
}
if(k1>1)
break;
k++;
}
if(k1<=1)
cout<<"YES"<<endl;
else if(k1>1)
cout<<"NO"<<endl;
}
}
return 0;
}
| [
"ajayhegde97@gmail.com"
] | ajayhegde97@gmail.com |
1dcab5750dd15e6403b57be03da0cda562d00371 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/git/gumtree/git_repos_function_6402_git-2.14.0.cpp | dbb3a79a7ed2694f80495ef6989e6c203099bc7b | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 416 | cpp | static void rollback_packed_refs(struct files_ref_store *refs)
{
struct packed_ref_cache *packed_ref_cache =
get_packed_ref_cache(refs);
files_assert_main_repository(refs, "rollback_packed_refs");
if (!is_lock_file_locked(&refs->packed_refs_lock))
die("BUG: packed-refs not locked");
rollback_lock_file(&refs->packed_refs_lock);
release_packed_ref_cache(packed_ref_cache);
clear_packed_ref_cache(refs);
} | [
"993273596@qq.com"
] | 993273596@qq.com |
ab7567d802afff8498924473e3ef267fc9537bc1 | 153684ec04d15fb9ca5ab4438fcca4dea1a22dc4 | /ACL/src/Transport/PostConnectSynchronizer.cpp | 41b38cfe800a3fd24d53f7aee0b5133c76260313 | [
"Apache-2.0"
] | permissive | nacichan/avs-device-sdk | c7cfeb43bf98d02c6da63d31ef0488f2cd9c8d7d | dbf4374cd1bb8c21282c1b4baa447de40c8949b5 | refs/heads/master | 2021-07-16T03:03:08.376150 | 2017-10-19T21:32:58 | 2017-10-19T21:32:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,716 | cpp | /*
* PostConnectSynchronizer.cpp
*
* Copyright 2016-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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 "ACL/Transport/HTTP2Transport.h"
#include "ACL/Transport/TransportDefines.h"
#include "ACL/Transport/PostConnectSynchronizer.h"
#include <AVSCommon/AVS/EventBuilder.h>
#include <AVSCommon/Utils/Logger/Logger.h>
namespace alexaClientSDK {
namespace acl {
using namespace avsCommon::sdkInterfaces;
/// String to identify log entries originating from this file.
static const std::string TAG("PostConnectSynchronize");
/**
* Create a LogEntry using this file's TAG and the specified event string.
*
* @param event The event string for this @c LogEntry.
*/
#define LX(event) alexaClientSDK::avsCommon::utils::logger::LogEntry(TAG, event)
/// String to identify the AVS namespace of the event we send.
static const std::string STATE_SYNCHRONIZER_NAMESPACE = "System";
/// String to identify the AVS name of the event we send.
static const std::string STATE_SYNCHRONIZER_NAME = "SynchronizeState";
PostConnectSynchronizer::PostConnectSynchronizer() :
m_contextFetchInProgress{false},
m_isPostConnected{false},
m_isStopping{false},
m_postConnectThreadRunning{false} {
}
void PostConnectSynchronizer::doShutdown() {
ACSDK_DEBUG(LX("PostConnectSynchronizer::doShutdown()."));
std::thread localPostConnectThread;
{
std::lock_guard<std::mutex> lock{m_mutex};
if (m_isStopping) {
return;
}
m_isStopping = true;
m_wakeRetryTrigger.notify_one();
m_transport.reset();
std::swap(m_postConnectThread, localPostConnectThread);
}
{
if (localPostConnectThread.joinable()) {
localPostConnectThread.join();
}
}
{
std::lock_guard<std::mutex> lock{m_observerMutex};
m_observers.clear();
}
}
bool PostConnectSynchronizer::doPostConnect(std::shared_ptr<HTTP2Transport> transport) {
if (!transport) {
ACSDK_ERROR(LX("createFailed").d("reason", "nullTransport"));
return false;
}
std::lock_guard<std::mutex> lock{m_mutex};
/*
* To handle cases where shutdown was invoked before the post-connect object is
* called. We do not want to spawn the post-connect thread again which ends up
* waiting forever.
*/
if (m_isStopping) {
return false;
}
// This function spawns a worker thread, so ensure this function is called
// only when the the worker thread is not running.
if (m_postConnectThreadRunning) {
ACSDK_ERROR(LX("postConnectFailed").d("reason", "postConnectThreadAlreadyRunning"));
return false;
}
m_transport = transport;
// Register the post-connect object as a listener to the HTTP m_transport
// observer interface to stop the thread when the m_transport is
// disconnected.
m_transport->addObserver(shared_from_this());
m_postConnectThreadRunning = true;
m_postConnectThread = std::thread(&PostConnectSynchronizer::postConnectLoop, this);
return true;
}
void PostConnectSynchronizer::postConnectLoop() {
int retryCount = 0;
ACSDK_DEBUG9(LX("Entering postConnectLoop thread"));
while (!isStopping() && !isPostConnected()) {
{
std::unique_lock<std::mutex> lock(m_mutex);
if (!m_contextFetchInProgress) {
PostConnectObject::m_contextManager->getContext(shared_from_this());
m_contextFetchInProgress = true;
}
}
auto retryBackoff = TransportDefines::RETRY_TIMER.calculateTimeToRetry(retryCount);
retryCount++;
std::unique_lock<std::mutex> lock(m_mutex);
m_wakeRetryTrigger.wait_for(lock, retryBackoff, [this] { return m_isPostConnected || m_isStopping; });
}
ACSDK_DEBUG9(LX("Exiting postConnectLoop thread"));
{
std::lock_guard<std::mutex> lock{m_mutex};
m_postConnectThreadRunning = false;
}
}
void PostConnectSynchronizer::onContextAvailable(const std::string& jsonContext) {
if (isPostConnected() || isStopping()) {
ACSDK_DEBUG(LX("onContextAvailableIgnored")
.d("reason", "PostConnectSynchronizerDone")
.d("m_isPostConnected", m_isPostConnected)
.d("m_isStopping", m_isStopping));
return;
}
auto msgIdAndJsonEvent = avsCommon::avs::buildJsonEventString(
STATE_SYNCHRONIZER_NAMESPACE, STATE_SYNCHRONIZER_NAME, "", "{}", jsonContext);
auto postConnectMessage = std::make_shared<avsCommon::avs::MessageRequest>(msgIdAndJsonEvent.second);
postConnectMessage->addObserver(shared_from_this());
/*
* If the transport pointer held by the post-connect is still valid - not
* shutdown yet then we send the message through the transport.
*/
std::shared_ptr<HTTP2Transport> localTransport;
{
std::lock_guard<std::mutex> lock{m_mutex};
swap(m_transport, localTransport);
}
if (localTransport) {
ACSDK_DEBUG(LX("onContextAvailable : Send PostConnectMessage to transport"));
localTransport->sendPostConnectMessage(postConnectMessage);
}
}
void PostConnectSynchronizer::onContextFailure(const ContextRequestError error) {
if (isPostConnected() || isStopping()) {
ACSDK_DEBUG(LX("onContextFailureIgnored")
.d("reason", "PostConnectSynchronizerDone")
.d("m_isPostConnected", m_isPostConnected)
.d("m_isStopping", m_isStopping));
return;
}
{
std::lock_guard<std::mutex> lock{m_mutex};
m_contextFetchInProgress = false;
}
ACSDK_ERROR(LX("contextRetrievalFailed").d("reason", "contextRequestErrorOccurred").d("error", error));
}
void PostConnectSynchronizer::onSendCompleted(MessageRequestObserverInterface::Status status) {
ACSDK_DEBUG(LX("onSendCompleted").d("status", avsCommon::avs::MessageRequest::statusToString(status)));
if (status == MessageRequestObserverInterface::Status::SUCCESS) {
{
std::lock_guard<std::mutex> lock{m_mutex};
m_isPostConnected = true;
m_wakeRetryTrigger.notify_one();
}
notifyObservers();
} else {
std::lock_guard<std::mutex> lock{m_mutex};
m_contextFetchInProgress = false;
}
}
void PostConnectSynchronizer::onExceptionReceived(const std::string& exceptionMessage) {
ACSDK_ERROR(LX("onExceptionReceived").d("exception", exceptionMessage));
std::lock_guard<std::mutex> lock{m_mutex};
m_contextFetchInProgress = false;
}
void PostConnectSynchronizer::addObserver(std::shared_ptr<PostConnectObserverInterface> observer) {
if (!observer) {
ACSDK_ERROR(LX("addObserverFailed").d("reason", "nullObserver"));
return;
}
std::lock_guard<std::mutex> lock{m_observerMutex};
m_observers.insert(observer);
}
void PostConnectSynchronizer::removeObserver(std::shared_ptr<PostConnectObserverInterface> observer) {
if (!observer) {
ACSDK_ERROR(LX("removeObserverFailed").d("reason", "nullObserver"));
return;
}
std::lock_guard<std::mutex> lock{m_observerMutex};
m_observers.erase(observer);
}
void PostConnectSynchronizer::notifyObservers() {
std::unique_lock<std::mutex> lock{m_observerMutex};
auto observers = m_observers;
lock.unlock();
for (auto observer : observers) {
observer->onPostConnected();
}
}
void PostConnectSynchronizer::onServerSideDisconnect() {
ACSDK_DEBUG(LX("onServerSideDisconnect()"));
doShutdown();
}
void PostConnectSynchronizer::onConnected() {
ACSDK_DEBUG(LX("onConnected()"));
}
void PostConnectSynchronizer::onDisconnected(ConnectionStatusObserverInterface::ChangedReason reason) {
ACSDK_DEBUG(LX("onDisconnected()"));
doShutdown();
}
bool PostConnectSynchronizer::isStopping() {
std::lock_guard<std::mutex> lock{m_mutex};
return m_isStopping;
}
bool PostConnectSynchronizer::isPostConnected() {
std::lock_guard<std::mutex> lock{m_mutex};
return m_isPostConnected;
}
} // namespace acl
} // namespace alexaClientSDK
| [
"rozenbf@amazon.com"
] | rozenbf@amazon.com |
b1ca81b063bf9c1f3a9ea492ba8bdf51ad9eaaac | ea6d2b821bcb90232cceb36f15abf37f82e7a2ad | /NewAlbumModel.hpp | 9173379905ebee713827eabc5b499f884a732d60 | [
"BSD-3-Clause"
] | permissive | Tronil/CarSpot | f0fc945a936b4fd83ffe21b077690a2a01ee1830 | 911a43ef310263ecb4be2faff401ec31c8e1f250 | refs/heads/master | 2020-06-11T19:12:25.989266 | 2012-11-14T16:35:15 | 2012-11-14T16:35:15 | 6,352,930 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,990 | hpp | /****************************************************************************
**
** Copyright (c) 2012 Troels Nilsson.
** All rights reserved.
** Contact: nilsson.troels@gmail.com
**
** This file is part of the CarSpot project.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions
** are met:
**
** Redistributions of source code must retain the above copyright notice,
** this list of conditions and the following disclaimer.
**
** Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
**
** Neither the name of CarSpot nor the names of its contributors may be
** used to endorse or promote products derived from this software without
** specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
** FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
** TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
****************************************************************************/
#ifndef NEWALBUMMODEL_HPP
#define NEWALBUMMODEL_HPP
#include <QAbstractListModel>
#include <qspotifyalbum.h>
#include <qspotifyalbumbrowse.h>
#include <ListItem.hpp>
class NewAlbumModel : public QAbstractListModel
{
Q_OBJECT
Q_PROPERTY(QSpotifyAlbumBrowse *albumBrowser READ albumBrowser WRITE setAlbumBrowser NOTIFY albumBrowserChanged)
Q_PROPERTY(int count READ count NOTIFY countChanged)
public:
explicit NewAlbumModel(QObject *parent = 0);
~NewAlbumModel();
virtual int rowCount(const QModelIndex & parent = QModelIndex()) const;
virtual QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const;
QSpotifyAlbumBrowse *albumBrowser() const { return m_albumBrowser; }
void setAlbumBrowser(QSpotifyAlbumBrowse *albumBrowser);
int count() const { return m_list.count(); }
Q_SIGNALS:
void countChanged();
void albumBrowserChanged();
private slots:
void itemChanged(int index);
void albumBrowserBusyChanged();
private:
void clear();
void addHeader();
void addAddToPlaylist();
void addTracks();
QSpotifyAlbumBrowse *m_albumBrowser;
QList<ListItem*> m_list;
};
#endif // NEWALBUMMODEL_HPP
| [
"nilsson.troels@gmail.com"
] | nilsson.troels@gmail.com |
c4afdd94d3efa1f3cb22c58cf985857b71c40ca6 | 2e5c75f3a893ae04b5054cecb73dbe929c8cd7c8 | /src/burntool/BurnToolView.h | ffb28bd7f0b4ac0c6049732a30bfa5dba78e43e6 | [] | no_license | amartol/videorec | 385192b1aca0acc42c24c700b93f4b0bc28a483f | a0b2372b27552c6326218799668d773f175cda6b | refs/heads/master | 2022-12-05T01:09:31.291281 | 2020-08-25T08:39:26 | 2020-08-25T08:39:26 | 72,375,362 | 5 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,544 | h | // BurnToolView.h : interface of the CBurnToolView class
//
/////////////////////////////////////////////////////////////////////////////
#if !defined(AFX_BURNTOOLVIEW_H__1B1828DC_A39B_455F_87A0_FEE50D8A9362__INCLUDED_)
#define AFX_BURNTOOLVIEW_H__1B1828DC_A39B_455F_87A0_FEE50D8A9362__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
//状态条颜色
#define COLOR_STAT_INITIAL RGB(100, 100, 100)
#define COLOR_STAT_STANDBY RGB(244, 244, 19)
#define COLOR_STAT_COMPLETE RGB(0, 200, 0)
#define COLOR_STAT_FAIL RGB(255, 0, 0)
#define COLOR_STAT_BURNING RGB(0, 0, 255)
//进度条颜色
#define COLOR_PROG_BACK RGB(236, 233, 236)
#define COLOR_PROG_NORMAL RGB(0, 0, 255)
#define COLOR_PROG_FAIL RGB(255, 0, 0)
#define COLOR_PROG_COMPLETE RGB(0, 200, 0)
class CBurnToolView : public CListView
{
protected: // create from serialization only
CBurnToolView();
DECLARE_DYNCREATE(CBurnToolView)
// Attributes
public:
CBurnToolDoc* GetDocument();
// Operations
public:
int m_cxClient;
COLORREF m_clrText;
COLORREF m_clrTextBk;
COLORREF m_clrBkgnd;
COLORREF m_clrHText;
COLORREF m_clrHBkgnd;
COLORREF m_clrForeProg;
COLORREF m_clrBackProg;
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CBurnToolView)
public:
virtual void OnDraw(CDC* pDC); // overridden to draw this view
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
protected:
virtual void OnInitialUpdate(); // called first time after construct
//}}AFX_VIRTUAL
// Implementation
public:
virtual ~CBurnToolView();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
public:
void SetupListView(UINT count);
void SetNumDesp(UINT nItem, CString sNumDesp);
void SetProgPos(UINT nItem, UINT nProg);
void SetProgColor(UINT nItem, COLORREF color);
void SetStatColor(UINT nItem, COLORREF cColor);
void SetTime(UINT nItem, UINT nTime);
void SetStatDesp(UINT nItem, CString sStatDesp);
void SetCurrentMacAddr(UINT nItem, CString str);
void SetCurrentSequenceAddr(UINT nItem, CString str);
void SetupDisplay();
protected:
virtual void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct);
//attibutes
typedef struct
{
UINT progress;
COLORREF color_stat;
COLORREF color_prog;
UINT time;
}T_ITEM_PROP;
UINT m_item_count;
CArray<T_ITEM_PROP, T_ITEM_PROP> m_itemprop_arrray;
//operations
void DrawBkColor(UINT nItem, BOOL bSelected, CDC *pDC);
void DrawProg(UINT nItem, CRect rcSubItem, BOOL bSelected, CDC *pDC);
void DrawStatColor(UINT nItem, CRect rcSubItem, CDC *pDC);
void DrawItemText(UINT nItem, CRect rcSubItem, CString sItem,
BOOL bSelected, UINT nJustify, CDC *pDC);
//private
void GetTimeString(UINT nTime, CString &sTime);
// Generated message map functions
protected:
//{{AFX_MSG(CBurnToolView)
afx_msg void OnSize(UINT nType, int cx, int cy);
//}}AFX_MSG
afx_msg void MeasureItem(LPMEASUREITEMSTRUCT lpMeasureItemStruct);
DECLARE_MESSAGE_MAP()
};
#ifndef _DEBUG // debug version in BurnToolView.cpp
inline CBurnToolDoc* CBurnToolView::GetDocument()
{ return (CBurnToolDoc*)m_pDocument; }
#endif
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_BURNTOOLVIEW_H__1B1828DC_A39B_455F_87A0_FEE50D8A9362__INCLUDED_)
| [
"li.bin@lamobo.org"
] | li.bin@lamobo.org |
c3ba160e3865c3b3120e6f4b0a32e2ee97cb5bc7 | 41448ed071f23d6dbe6c5cdb67952fc4eb3d78ca | /src/Lights/PointLight.h | 615842a70d07eca6cb0b9ad36d3003dcdee60f4c | [] | no_license | janisozaur/foto-results | 2c4ec433bf5654aa7a4eb581622f61317efeafc7 | 5363c4805e5a09840cd64726eff21faa72547589 | refs/heads/master | 2020-03-27T03:41:27.780006 | 2012-05-22T11:01:41 | 2012-05-22T11:01:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 879 | h | #ifndef POINTLIGHT_H
#define POINTLIGHT_H
#include "AmbientLight.h"
class Scene;
class PointLight : public AmbientLight
{
public:
PointLight();
/**
Constructs point light with given position, color and attenuation parameters
*/
PointLight(Vector3 position, Color color, Vector3 attenuation);
~PointLight();
LightIntensity GetLightIntensity(Vector3 cameraPosition, IntersectionResult *ir,QList<Geometry *> &geometry );
/**
Gets position of light
*/
Vector3 GetPosition() const;
Ray GetPhoton(bool useProjectionMap=false) const;
void CreateProjectionMap(const Scene* scene);
float GetProjectionMapRatio() const;
protected:
bool IsInShadow(IntersectionResult *ir, QList<Geometry *> &geometry);
private:
Vector3 position;
Vector3 attenuation;
Texture* projectionMap;
};
#endif // POINTLIGHT_H
| [
"janisozaur@gmail.com"
] | janisozaur@gmail.com |
a8edafa3c0a1d47ef8ec9696299e2660dcd2f83c | 3c1b9ef66e71779404154b6686c8c5caa1360fe4 | /pid.cpp | 595b8551cbf850e2f4e0e08b26354d17d8b2c36a | [] | no_license | dg-shadow/arduino_sea_control | 99fd6eb2ba9a2bb7c0c46aadd3f3b279b49cec2b | 66a2029070caca547e6185bc0aa0a406e9df1c36 | refs/heads/master | 2021-01-10T21:20:56.264103 | 2013-01-23T17:37:35 | 2013-01-23T17:37:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,122 | cpp | #define D_SMOOTHING 3
int p_array[D_SMOOTHING];
int d_pointer = 0;
int get_next_d_pointer ( int current_d_pointer )
{
return (current_d_pointer + 1) % D_SMOOTHING;
}
void init(void)
{
for (int x = 0; x < D_SMOOTHING; x++)
p_array[x] = 0;
}
int get_force_demand(int position, int target, int stiffness)
{
return (target - position)*stiffness;
}
void main(void)
{
int position = get_position();
int force = get_force();
int target_force = get_target_force(position, target_position, stiffness);
int p = position - target;
p_array[d_pointer] = p;
int next_d_pointer = get_next_d_pointer(d_pointer);
int d = p_array[next_d_pointer] = p_array[p_pointer];
int i += p;
if (i_coeficient)
{
if (i > i_max) i = i_max;
else if (i < -i_max) i = -i_max;
if (i > 0)
{
if (i > i_decay) i -= i_decay;
else i = 0;
}
else if (i > 0)
{
if (i < -i_decay) i += i_decay;
else i = 0;
}
}
output = p * p_coeficient + d * d_coefficient + i * i_coeficient;
}
| [
"dg@shadowrobot.com"
] | dg@shadowrobot.com |
e513d187e97946c2b95258964b631ffb2ba3bfd8 | 88ae8695987ada722184307301e221e1ba3cc2fa | /third_party/tflite/src/tensorflow/compiler/tf2xla/kernels/shape_op.cc | 60b1f5eea3a53b18bc49c26ac178f2c34d7894f8 | [
"Apache-2.0",
"LGPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-generic-cla",
"BSD-2-Clause"
] | permissive | iridium-browser/iridium-browser | 71d9c5ff76e014e6900b825f67389ab0ccd01329 | 5ee297f53dc7f8e70183031cff62f37b0f19d25f | refs/heads/master | 2023-08-03T16:44:16.844552 | 2023-07-20T15:17:00 | 2023-07-23T16:09:30 | 220,016,632 | 341 | 40 | BSD-3-Clause | 2021-08-13T13:54:45 | 2019-11-06T14:32:31 | null | UTF-8 | C++ | false | false | 16,829 | cc | /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// XLA-specific Shape Ops.
#include "absl/strings/str_format.h"
#include "tensorflow/compiler/tf2xla/kernels/shape_util.h"
#include "tensorflow/compiler/tf2xla/kernels/tensor_list_utils.h"
#include "tensorflow/compiler/tf2xla/shape_util.h"
#include "tensorflow/compiler/tf2xla/type_util.h"
#include "tensorflow/compiler/tf2xla/xla_helpers.h"
#include "tensorflow/compiler/tf2xla/xla_op_kernel.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/compiler/xla/client/lib/constants.h"
#include "tensorflow/compiler/xla/client/xla_builder.h"
#include "tensorflow/compiler/xla/literal.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/core/framework/bounds_check.h"
#include "tensorflow/core/framework/kernel_def_builder.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor_shape.h"
namespace tensorflow {
namespace {
class ShapeOp : public XlaOpKernel {
public:
explicit ShapeOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {
OP_REQUIRES_OK(ctx, ctx->GetAttr("out_type", &out_dtype_));
}
void Compile(XlaOpKernelContext* ctx) override {
const TensorShape input_shape = ctx->InputShape(0);
std::vector<xla::XlaOp> operands;
const int rank = input_shape.dims();
if (rank != 0) {
for (int64_t i = 0; i < rank; ++i) {
operands.push_back(xla::Broadcast(
xla::ConvertElementType(xla::GetDimensionSize(ctx->Input(0), i),
ctx->output_xla_type(0)),
{1}));
}
ctx->SetOutput(0, xla::ConcatInDim(ctx->builder(), operands, 0));
} else {
// Rank 0 won't have dynamic size dimension, use constant output.
Tensor shape_constant(out_dtype_, TensorShape({input_shape.dims()}));
OP_REQUIRES_OK(ctx, TensorShapeToConstant(input_shape, &shape_constant));
ctx->SetConstantOutput(0, shape_constant);
}
}
private:
DataType out_dtype_;
};
REGISTER_XLA_OP(Name("Shape").CompilationOnly().IsMetadataOp(), ShapeOp);
class XlaSetBoundOp : public XlaOpKernel {
public:
explicit XlaSetBoundOp(OpKernelConstruction* context)
: XlaOpKernel(context) {}
void Compile(XlaOpKernelContext* ctx) override {
const TensorShape input_shape = ctx->InputShape("input");
const TensorShape bound_shape = ctx->InputShape("bound");
OP_REQUIRES(
ctx,
ctx->InputType("bound") == DT_INT32 &&
ctx->InputType("input") == DT_INT32,
errors::InvalidArgument(
"XlaSetBound can only set bound for int32 scalar value: got",
input_shape.DebugString()));
OP_REQUIRES(
ctx, input_shape.dims() == 0,
errors::InvalidArgument("XlaSetBound should only be used to set a "
"bound to the an int32 scalar value: got",
input_shape.DebugString()));
OP_REQUIRES(
ctx, bound_shape.dims() == 0,
errors::InvalidArgument("XlaSetBound should only be used to set a "
"bound to the an int32 scalar value: got",
bound_shape.DebugString()));
int64_t bound;
OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntScalar("bound", &bound));
xla::Literal bound_literal = xla::LiteralUtil::CreateR0<int32>(bound);
xla::XlaOp result = xla::CustomCall(
ctx->builder(), "SetBound", {ctx->Input("input")},
ctx->InputXlaShape("input").value(), "", false, {}, &bound_literal);
ctx->SetOutput(0, result);
}
};
REGISTER_XLA_OP(Name("XlaSetBound").CompileTimeConstantInput("bound"),
XlaSetBoundOp);
class XlaSetDynamicDimensionSizeOp : public XlaOpKernel {
public:
explicit XlaSetDynamicDimensionSizeOp(OpKernelConstruction* context)
: XlaOpKernel(context) {}
void Compile(XlaOpKernelContext* ctx) override {
const TensorShape dim_index_shape = ctx->InputShape("dim_index");
const TensorShape size_shape = ctx->InputShape("size");
OP_REQUIRES(ctx,
ctx->InputType("dim_index") == DT_INT32 &&
ctx->InputType("size") == DT_INT32,
errors::InvalidArgument("dim_index and size has to be int32 for"
"XlaSetDynamicDimensionSizeOp"));
OP_REQUIRES(
ctx, dim_index_shape.dims() == 0 && size_shape.dims() == 0,
errors::InvalidArgument("XlaSetDynamicDimensionSizeOp's dim_index and "
"size has to be int32 scalar value"));
int64_t dim_index;
OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntScalar("dim_index", &dim_index));
xla::XlaOp result =
xla::SetDimensionSize(ctx->Input(0), ctx->Input("size"), dim_index);
ctx->SetOutput(0, result);
}
};
REGISTER_XLA_OP(
Name("XlaSetDynamicDimensionSize").CompileTimeConstantInput("dim_index"),
XlaSetDynamicDimensionSizeOp);
class XlaRemoveDynamicDimensionSizeOp : public XlaOpKernel {
public:
explicit XlaRemoveDynamicDimensionSizeOp(OpKernelConstruction* context)
: XlaOpKernel(context) {}
void Compile(XlaOpKernelContext* ctx) override {
const TensorShape dim_index_shape = ctx->InputShape("dim_index");
OP_REQUIRES(ctx, ctx->InputType("dim_index") == DT_INT32,
errors::InvalidArgument("dim_index has to be int32 for"
"XlaRemoveDynamicDimensionSizeOp"));
OP_REQUIRES(
ctx, dim_index_shape.dims() == 0,
errors::InvalidArgument("XlaRemoveDynamicDimensionSizeOp's dim_index "
"has to be int32 scalar value"));
int64_t dim_index;
OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntScalar("dim_index", &dim_index));
xla::XlaOp result = xla::RemoveDynamicDimension(ctx->Input(0), dim_index);
ctx->SetOutput(0, result);
}
};
REGISTER_XLA_OP(
Name("XlaRemoveDynamicDimensionSize").CompileTimeConstantInput("dim_index"),
XlaRemoveDynamicDimensionSizeOp);
class ShapeNOp : public XlaOpKernel {
public:
explicit ShapeNOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {
OP_REQUIRES_OK(ctx, ctx->GetAttr("out_type", &out_dtype_));
}
void Compile(XlaOpKernelContext* ctx) override {
for (int i = 0; i < ctx->num_inputs(); ++i) {
const TensorShape input_shape = ctx->InputShape(i);
std::vector<xla::XlaOp> operands;
const int rank = input_shape.dims();
if (rank != 0) {
// Each dimension can be dynamic, so use GetDimensionSize to get the
// runtime dimension.
for (int64_t dim = 0; dim < rank; ++dim) {
operands.push_back(xla::Broadcast(
xla::ConvertElementType(xla::GetDimensionSize(ctx->Input(i), dim),
ctx->output_xla_type(i)),
{1}));
}
ctx->SetOutput(i, xla::ConcatInDim(ctx->builder(), operands, 0));
} else {
// Rank 0 won't have dynamic size dimension, use constant output.
Tensor shape_constant(out_dtype_, TensorShape({input_shape.dims()}));
OP_REQUIRES_OK(ctx,
TensorShapeToConstant(input_shape, &shape_constant));
ctx->SetConstantOutput(i, shape_constant);
}
}
}
bool IsExpensive() override { return false; }
private:
DataType out_dtype_;
};
REGISTER_XLA_OP(Name("ShapeN").CompilationOnly().IsMetadataOp(), ShapeNOp);
class RankOp : public XlaOpKernel {
public:
explicit RankOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {}
void Compile(XlaOpKernelContext* ctx) override {
const TensorShape input_shape = ctx->InputShape(0);
const int rank = input_shape.dims();
Tensor rank_constant(DT_INT32, TensorShape({}));
rank_constant.scalar<int32>()() = rank;
ctx->SetConstantOutput(0, rank_constant);
}
};
REGISTER_XLA_OP(Name("Rank").CompilationOnly().IsMetadataOp(), RankOp);
class SizeOp : public XlaOpKernel {
public:
explicit SizeOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {}
void Compile(XlaOpKernelContext* ctx) override {
const TensorShape input_shape = ctx->InputShape(0);
OP_REQUIRES(ctx,
FastBoundsCheck(input_shape.num_elements(),
std::numeric_limits<int32>::max()),
errors::InvalidArgument("Size does not work for tensors > "
"int32 max."));
Tensor size_constant(DT_INT32, TensorShape({}));
const int rank = input_shape.dims();
xla::XlaBuilder* builder = ctx->builder();
auto size = xla::One(builder, xla::U32);
for (int64_t i = 0; i < rank; ++i) {
size = xla::Mul(
size, xla::ConvertElementType(xla::GetDimensionSize(ctx->Input(0), i),
xla::U32));
}
size = xla::ConvertElementType(size, ctx->output_xla_type(0));
ctx->SetOutput(0, size);
}
};
REGISTER_XLA_OP(Name("Size").CompilationOnly().IsMetadataOp(), SizeOp);
class ExpandDimsOp : public XlaOpKernel {
public:
explicit ExpandDimsOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {}
void Compile(XlaOpKernelContext* ctx) override {
const TensorShape input_shape = ctx->InputShape("input");
const TensorShape dim_shape = ctx->InputShape("dim");
std::vector<int64_t> dims;
OP_REQUIRES_OK(ctx, ctx->ConstantInputReshapedToIntVector("dim", &dims));
OP_REQUIRES(ctx, dims.size() == 1,
errors::InvalidArgument(absl::StrCat(
"dim input to ExpandDims must be a scalar; got ",
dim_shape.DebugString())));
int dim = dims[0];
OP_REQUIRES(ctx,
(dim >= -1 - input_shape.dims() && dim <= input_shape.dims()),
errors::InvalidArgument("Tried to expand dim index ", dim,
" for tensor with ", input_shape.dims(),
" dimensions."));
auto existing_dims = input_shape.dim_sizes();
// Safe - # elements in tensor dims bounded.
const int existing_dims_size = static_cast<int>(existing_dims.size());
std::vector<int64_t> new_shape(existing_dims_size);
for (size_t i = 0; i < new_shape.size(); ++i) {
new_shape[i] = existing_dims[i];
}
// We emulate numpy's interpretation of the dim axis when
// -input.dims() >= dim <= input.dims().
if (dim < 0) {
dim += existing_dims.size() + 1;
}
// Clamp to the end if needed.
dim = std::min<int32>(dim, existing_dims_size);
new_shape.emplace(new_shape.begin() + dim, 1);
ctx->SetOutput(0, xla::Reshape(ctx->Input("input"), new_shape));
}
};
REGISTER_XLA_OP(Name("ExpandDims").CompileTimeConstantInput("dim"),
ExpandDimsOp);
class SqueezeOp : public XlaOpKernel {
public:
explicit SqueezeOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {
std::vector<int32> squeeze_dims;
OP_REQUIRES_OK(ctx, ctx->GetAttr("squeeze_dims", &squeeze_dims));
squeeze_dims_.insert(squeeze_dims.begin(), squeeze_dims.end());
}
void Compile(XlaOpKernelContext* ctx) override {
StatusOr<xla::Shape> input_shape = ctx->builder()->GetShape(ctx->Input(0));
OP_REQUIRES_OK(ctx, input_shape.status());
xla::Shape shape = input_shape.value();
int64_t rank = shape.rank();
std::unordered_set<int32> wrapped_squeeze_dims;
wrapped_squeeze_dims.reserve(squeeze_dims_.size());
std::vector<int64_t> new_shape;
// Validate squeeze dims against the input.
for (int32_t dim : squeeze_dims_) {
OP_REQUIRES(
ctx, (dim >= -rank && dim < rank),
errors::InvalidArgument("Tried to squeeze dim index ", dim,
" for tensor with ", rank, " dimensions."));
// If dim is < 0, we wrap around (-1 means the last element).
if (dim < 0) {
dim = rank + dim;
}
wrapped_squeeze_dims.insert(dim);
}
for (int i = 0; i < rank; ++i) {
auto existing_dim = shape.dimensions(i);
// If squeeze_set is non-empty, only squeeze those dimensions.
if (!wrapped_squeeze_dims.empty()) {
if (wrapped_squeeze_dims.count(i) > 0) {
OP_REQUIRES(ctx, existing_dim == 1,
errors::InvalidArgument(
"Tried to explicitly squeeze dimension ", i,
" but dimension was not 1: ", existing_dim));
} else {
// This dimension is not being squeezed.
new_shape.push_back(existing_dim);
}
} else {
OP_REQUIRES(
ctx, !shape.is_dynamic_dimension(i),
errors::InvalidArgument("Squeeze op does not support bounded "
"dynamic dimensions. Input shape: ",
shape.DebugString()));
// Copy over all non-1-length dimensions.
if (existing_dim != 1) {
new_shape.push_back(existing_dim);
}
}
}
ctx->SetOutput(0, xla::Reshape(ctx->Input(0), new_shape));
}
private:
std::unordered_set<int32> squeeze_dims_;
};
REGISTER_XLA_OP(Name("Squeeze"), SqueezeOp);
class ZerosLikeOp : public XlaOpKernel {
public:
explicit ZerosLikeOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {}
void Compile(XlaOpKernelContext* ctx) override {
if (IsTensorListInput(ctx, 0)) {
// Input is a TensorList.
// Check the TensorList input is initialized.
xla::XlaOp list = ctx->Input(0);
bool is_initialized;
OP_REQUIRES_OK(ctx, IsTensorListInitialized(list, &is_initialized));
OP_REQUIRES(
ctx, is_initialized,
errors::InvalidArgument(
"TensorList input for ZerosLike op is an uninitialized list"));
auto list_shape_or = ctx->builder()->GetShape(list);
OP_REQUIRES_OK(ctx, list_shape_or.status());
const xla::Shape& list_shape = list_shape_or.value();
std::vector<std::vector<xla::XlaOp>> list_dynamic_dims;
list_dynamic_dims.reserve(list_shape.tuple_shapes_size() - 1);
for (int i = 0; i < list_shape.tuple_shapes_size() - 1; ++i) {
// Set dynamic dimension size to 0 for initialization value.
std::vector<xla::XlaOp> dynamic_dims;
const xla::Shape& shape = list_shape.tuple_shapes(i);
auto sub_element = xla::GetTupleElement(list, i);
for (int64_t dim = 0; dim < shape.dimensions_size(); ++dim) {
dynamic_dims.push_back(xla::GetDimensionSize(sub_element, dim));
}
list_dynamic_dims.push_back(dynamic_dims);
}
xla::XlaOp new_list;
OP_REQUIRES_OK(
ctx, CreateZerosTensorListWithShape(ctx->builder(), list_shape,
list_dynamic_dims, &new_list));
xla::XlaOp push_index;
OP_REQUIRES_OK(ctx, GetTensorListPushIndex(list, &push_index));
xla::XlaOp result;
OP_REQUIRES_OK(ctx,
SetTensorListPushIndex(new_list, push_index, &result));
ctx->SetTensorListOutput(0, result);
} else {
auto zero = XlaHelpers::Zero(ctx->builder(), input_type(0));
xla::XlaOp input = ctx->Input(0);
auto input_shape = ctx->InputXlaShape(0).value();
auto result = xla::Broadcast(zero, input_shape.dimensions());
// Setting up dynamic dimensions of the broadcast.
for (int64_t i = 0; i < input_shape.dimensions_size(); ++i) {
if (input_shape.is_dynamic_dimension(i)) {
xla::XlaOp input_dynamic_dim = xla::GetDimensionSize(input, i);
result = xla::SetDimensionSize(result, input_dynamic_dim, i);
}
}
ctx->SetOutput(0, result);
}
}
};
REGISTER_XLA_OP(Name("ZerosLike").AllowVariantTypes(), ZerosLikeOp);
class OnesLikeOp : public XlaOpKernel {
public:
explicit OnesLikeOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {}
void Compile(XlaOpKernelContext* ctx) override {
const TensorShape input_shape = ctx->InputShape(0);
auto one = XlaHelpers::One(ctx->builder(), input_type(0));
ctx->SetOutput(0, xla::Broadcast(one, input_shape.dim_sizes()));
}
};
REGISTER_XLA_OP(Name("OnesLike"), OnesLikeOp);
} // namespace
} // namespace tensorflow
| [
"jengelh@inai.de"
] | jengelh@inai.de |
eb6ea1ad45d6d1e1afe8c49a5ff4b81fbc52860e | 66263a415339473ad1f4f9e32cc102b9d23fdc37 | /CodeChef/Feb Lunchtime 2021/Sed_Max.cpp | 65298588a98cf810f11cd9496396f241dcd25657 | [] | no_license | leetcode-notes/Competitive-Programming-2 | b08b3e4dd437e2d146cb90522713821a4852a5fe | c0efb523340d09a901c53b33b40875d102108768 | refs/heads/master | 2023-04-03T22:31:13.628879 | 2021-04-19T13:34:11 | 2021-04-19T13:34:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,273 | cpp |
//------------------------------------------------------------------------------
#include <iostream>
#include <vector>
// #include <bits/stdc++.h>
// #include <cmath>
// #include <algorithm>
// #include <unordered_map>
// #include <map>
// #include <set>
#include <unordered_set>
#include <stack>
//------------------------------------------------------------------------------
using namespace std;
//------------------------------------------------------------------------------
#define FastIO ios_base::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL);
#define v(Type) vector<Type>
#define w(T) \
int T; \
cin >> T; \
while (T--)
#define int long long int
#define mod 1000000007ll
#define endl "\n"
//------------------------------------------------------------------------------
// Any fucntion can be called using Math.function_name();
//------------------------------------------------------------------------------
class Math
{
public:
//Returns gcd of two numbers
int gcd(int a, int b)
{
return (a % b == 0) ? b : gcd(b, a % b);
}
//Returns lcm of two numbers
int lcm(int a, int b)
{
return a * (b / gcd(a, b));
}
// Returns flag array isPrime
// isPrime[i] = true (if i is Prime)
// isPrime[i] = false (if i is not Prime)
vector<bool> *seiveOfEratosthenes(const int N)
{
vector<bool> *isPrime = new vector<bool>(N + 1, true);
(*isPrime)[0] = (*isPrime)[1] = false;
for (int i = 2; i * i <= N; ++i)
if ((*isPrime)[i])
for (int j = i * i; j <= N; j += i)
(*isPrime)[j] = false;
return isPrime;
}
//Returns (x ^ n)
int pow(const int &x, int n)
{
if (n == 0)
return 1;
int h = pow(x, n / 2);
return (n & 1) ? h * h * x : h * h;
}
//Returns (x ^ n) % M
int pow(const int &x, int n, const int &M)
{
if (n == 0)
return 1;
int h = pow(x, n / 2) % M;
return (n & 1) ? (h * h * x) % M : (h * h) % M;
}
//Returns all Primes <= N
vector<int> *primesUptoN(const int N)
{
vector<bool> *isPrime = seiveOfEratosthenes(N);
vector<int> *Primes = new vector<int>;
if (2 <= N)
(*Primes).push_back(2);
for (int i = 3; i <= N; i += 2)
if ((*isPrime)[i])
(*Primes).push_back(i);
return Primes;
}
} Math;
//------------------------------------------------------------------------------
void solve()
{
int n;
cin >> n;
v(int) A(n);
for (int i = 0; i < n; i++)
cin >> A[i];
stack<int> st;
unordered_set<int> Set;
st.push(A[0]);
for (int i = 1; i < n; i++)
{
while (st.size() > 0 and A[i] > st.top())
{
Set.insert(A[i] - st.top());
st.pop();
}
if (st.size() != 0)
Set.insert(abs(A[i] - st.top()));
st.push(A[i]);
}
cout << Set.size() << endl;
}
//------------------------------------------------------------------------------
int32_t main()
{
FastIO;
w(T)
solve();
return 0;
}
//------------------------------------------------------------------------------
| [
"dhruvpasricha0002@gmail.com"
] | dhruvpasricha0002@gmail.com |
e2c589a9236689f99b6e02fddc258edfe4cae772 | c9cd39d5d477028967adbdb890a0f965c6f0d312 | /Samuel/pointlights/Experiment folder/pointlightsLightHouse/pointlightsLightHouse.ino | f16bb4df88ac27e4f92760bf1c869708de99d14b | [] | no_license | ivarlundin/M2-interactivity | d66a7763c3b01e52861919825a7778341b2b16b0 | 6881996da07afb5033604540eb0aee7bfd04ef82 | refs/heads/master | 2023-01-05T22:51:44.560587 | 2020-10-08T12:30:40 | 2020-10-08T12:30:40 | 297,627,036 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,315 | ino | enum ledStates {INCREASE, DECREASE, STAY, WAVE, OFF, ON}; // Here we make nicknames for the different states our program supports.
enum ledStates ledState; // We define 'ledState' as type ledStates'
enum ledStates previousLedState = ledState;
unsigned long startMillis; //some global variables available anywhere in the program
unsigned long currentMillis;
int brightness = 0; // our main variable for setting the brightness of the LED
float velocity = 1.0; // the speed at which we change the brightness.
int ledPin = 9; // we use pin 9 for PWM
int p = 0; // use to keep track how often we plot
int plotFrequency = 3; // how often we plot, every Nth time.
void setup() {
// put your setup code here, to run once:
pinMode(ledPin, OUTPUT); // set ledPin as an output.
Serial.begin(9600); // initiate the Serial monitor so we can use the Serial Plotter to graph our patterns
}
void loop() {
// put your main code here, to run repeatedly:
compose();
delay(10);
analogWrite(ledPin, brightness);
currentMillis = millis(); //store the current time since the program started
}
void compose() {
// this is a state machine which allows us to decouple the various operations from timed loops.
// instead we just switch from state to state when particular conditions are met.
// we switch states by calling the changeState() function.
switch (ledState){
case INCREASE:
brightness = expInc_brightness(brightness, 1);
plot("INCREASINGEXPONENTIALLY", brightness);
if (brightness > 250){
//ledState = WAVE;
changeState(DECREASE);
}
break;
case DECREASE:
brightness = expDecrease_brightness(brightness, 1);
plot("DECREASING", brightness);
if (brightness == 0){
changeState(OFF);
}
break;
case WAVE:
plot("WAVE", brightness);
brightness = sinewave(1000,100,0); // you can tweak the parameters of the sinewave
analogWrite(ledPin, brightness);
if (currentMillis - startMillis >= 5000){ //change state after 5 secs by comparing the time elapsed since we last change state
changeState(DECREASE);
}
break;
case STAY:
plot("STAY", brightness);
brightness = brightness;
break;
case ON:
plot("ON", brightness);
brightness = 255;
if (currentMillis - startMillis >= 1500){
changeState(OFF);
}
break;
case OFF:
plot("OFF", brightness);
brightness = 0;
if (currentMillis - startMillis >= 2000){
changeState(INCREASE);
}
break;
}
}
void changeState(ledStates newState){
// call to change state, will keep track of time since last state
startMillis = millis();
ledState = newState;
}
void plot(char *state, int brightness){
// use this function to plot a graph.
// it will normalize the auto-scaling plotter
if ((p % plotFrequency) == 0){
Serial.print(state);
Serial.print(", ");
Serial.print(brightness);
Serial.println(", 0, 300");
}
p++;
}
int increase_brightness (int brightness, float velocity){
return brightness = brightness + 1 * velocity;
}
int expInc_brightness (int brightness, float velocity){
return brightness = brightness + brightness/70 + velocity;
// gånger eller plus på Velocity?
}
int decrease_brightness (int brightness, float velocity){
return brightness = brightness - 1 * velocity;
}
int expDecrease_brightness (int brightness, float velocity){
return brightness = (brightness - brightness/70) - velocity;
//vander på velocity, eller hur?
//annan lösning: brightness = brightness - brightness/velocity - 1;
}
int sinewave(float duration, float amplitude, int offset){
// Generate a sine oscillation, return a number.
// In case you are using this for analogWrite, make sure the amplitude does not exceed 256
float period = millis()/duration; // Duration in ms determines the wavelength.
float midpoint = amplitude / 2; // set the midpoint of the wave at half the amplitude so there are no negative numbers
int value = midpoint + midpoint * sin ( period * 2.0 * PI );
value = value + offset; //offset allows you to move the wave up and down on the Y-axis. Should not exceed the value of amplitude to prevent clipping.
return value;
}
| [
"60586489+CaptainSamSE@users.noreply.github.com"
] | 60586489+CaptainSamSE@users.noreply.github.com |
ff37d1c80744502bc614a28bcbccb275f6652fad | ec68c973b7cd3821dd70ed6787497a0f808e18e1 | /Cpp/SDK/CreditsFL_functions.cpp | 3c2f101bb105ac0b22fe77e5591d6a2add80aa54 | [] | no_license | Hengle/zRemnant-SDK | 05be5801567a8cf67e8b03c50010f590d4e2599d | be2d99fb54f44a09ca52abc5f898e665964a24cb | refs/heads/main | 2023-07-16T04:44:43.113226 | 2021-08-27T14:26:40 | 2021-08-27T14:26:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,970 | cpp | // Name: Remnant, Version: 1.0
#include "../pch.h"
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Functions
//---------------------------------------------------------------------------
// Function CreditsFL.CreditsFL_C.Get Override Data for Name
// ()
void UCreditsFL_C::Get_Override_Data_for_Name()
{
static auto fn = UObject::FindObject<UFunction>("Function CreditsFL.CreditsFL_C.Get Override Data for Name");
UCreditsFL_C_Get_Override_Data_for_Name_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function CreditsFL.CreditsFL_C.Get Roles in Section
// ()
void UCreditsFL_C::Get_Roles_in_Section()
{
static auto fn = UObject::FindObject<UFunction>("Function CreditsFL.CreditsFL_C.Get Roles in Section");
UCreditsFL_C_Get_Roles_in_Section_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function CreditsFL.CreditsFL_C.Get Overriden Names
// ()
void UCreditsFL_C::Get_Overriden_Names()
{
static auto fn = UObject::FindObject<UFunction>("Function CreditsFL.CreditsFL_C.Get Overriden Names");
UCreditsFL_C_Get_Overriden_Names_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function CreditsFL.CreditsFL_C.Get Override Data for Role
// ()
void UCreditsFL_C::Get_Override_Data_for_Role()
{
static auto fn = UObject::FindObject<UFunction>("Function CreditsFL.CreditsFL_C.Get Override Data for Role");
UCreditsFL_C_Get_Override_Data_for_Role_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function CreditsFL.CreditsFL_C.Get Overriden Roles
// ()
void UCreditsFL_C::Get_Overriden_Roles()
{
static auto fn = UObject::FindObject<UFunction>("Function CreditsFL.CreditsFL_C.Get Overriden Roles");
UCreditsFL_C_Get_Overriden_Roles_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function CreditsFL.CreditsFL_C.Simple Text Object (Title) to Complex Text Object
// ()
void UCreditsFL_C::Simple_Text_Object__Title__to_Complex_Text_Object()
{
static auto fn = UObject::FindObject<UFunction>("Function CreditsFL.CreditsFL_C.Simple Text Object (Title) to Complex Text Object");
UCreditsFL_C_Simple_Text_Object__Title__to_Complex_Text_Object_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function CreditsFL.CreditsFL_C.Simple Credits Section to Complex Credits Section
// ()
void UCreditsFL_C::Simple_Credits_Section_to_Complex_Credits_Section()
{
static auto fn = UObject::FindObject<UFunction>("Function CreditsFL.CreditsFL_C.Simple Credits Section to Complex Credits Section");
UCreditsFL_C_Simple_Credits_Section_to_Complex_Credits_Section_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function CreditsFL.CreditsFL_C.Simple Played By Names to Complex Played By Names
// ()
void UCreditsFL_C::Simple_Played_By_Names_to_Complex_Played_By_Names()
{
static auto fn = UObject::FindObject<UFunction>("Function CreditsFL.CreditsFL_C.Simple Played By Names to Complex Played By Names");
UCreditsFL_C_Simple_Played_By_Names_to_Complex_Played_By_Names_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function CreditsFL.CreditsFL_C.Simple Text Object (Role) to Complex Text Object
// ()
void UCreditsFL_C::Simple_Text_Object__Role__to_Complex_Text_Object()
{
static auto fn = UObject::FindObject<UFunction>("Function CreditsFL.CreditsFL_C.Simple Text Object (Role) to Complex Text Object");
UCreditsFL_C_Simple_Text_Object__Role__to_Complex_Text_Object_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function CreditsFL.CreditsFL_C.Simple Roles to Complex Roles
// ()
void UCreditsFL_C::Simple_Roles_to_Complex_Roles()
{
static auto fn = UObject::FindObject<UFunction>("Function CreditsFL.CreditsFL_C.Simple Roles to Complex Roles");
UCreditsFL_C_Simple_Roles_to_Complex_Roles_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function CreditsFL.CreditsFL_C.Padding Margin To Margin
// ()
void UCreditsFL_C::Padding_Margin_To_Margin()
{
static auto fn = UObject::FindObject<UFunction>("Function CreditsFL.CreditsFL_C.Padding Margin To Margin");
UCreditsFL_C_Padding_Margin_To_Margin_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"zp2kshield@gmail.com"
] | zp2kshield@gmail.com |
0affb6194b8051aaffa131b032d66b659fbeb521 | 6d54a7b26d0eb82152a549a6a9dfde656687752c | /src/lib/dnssd/MinimalMdnsServer.cpp | 2fbe9fd7e6776b112b3e29814c40838682c2fec9 | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | project-chip/connectedhomeip | 81a123d675cf527773f70047d1ed1c43be5ffe6d | ea3970a7f11cd227ac55917edaa835a2a9bc4fc8 | refs/heads/master | 2023-09-01T11:43:37.546040 | 2023-09-01T08:01:32 | 2023-09-01T08:01:32 | 244,694,174 | 6,409 | 1,789 | Apache-2.0 | 2023-09-14T20:56:31 | 2020-03-03T17:05:10 | C++ | UTF-8 | C++ | false | false | 2,178 | cpp | /*
*
* Copyright (c) 2021 Project CHIP Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "MinimalMdnsServer.h"
#include <lib/dnssd/minimal_mdns/AddressPolicy.h>
#ifndef CHIP_MINMDNS_DEFAULT_POLICY
#define CHIP_MINMDNS_DEFAULT_POLICY 0
#endif
#ifndef CHIP_MINMDNS_LIBNL_POLICY
#define CHIP_MINMDNS_LIBNL_POLICY 0
#endif
#if CHIP_MINMDNS_DEFAULT_POLICY
#include <lib/dnssd/minimal_mdns/AddressPolicy_DefaultImpl.h> // nogncheck
#endif
#if CHIP_MINMDNS_LIBNL_POLICY
#include <lib/dnssd/minimal_mdns/AddressPolicy_LibNlImpl.h> // nogncheck
#endif
namespace chip {
namespace Dnssd {
using namespace mdns::Minimal;
using chip::Platform::UniquePtr;
GlobalMinimalMdnsServer::GlobalMinimalMdnsServer()
{
mServer.SetDelegate(this);
#if CHIP_MINMDNS_DEFAULT_POLICY
mdns::Minimal::SetDefaultAddressPolicy();
#endif
#if CHIP_MINMDNS_LIBNL_POLICY
mdns::Minimal::LibNl::SetAddressPolicy();
#endif
}
GlobalMinimalMdnsServer & GlobalMinimalMdnsServer::Instance()
{
static GlobalMinimalMdnsServer _instance;
return _instance;
}
CHIP_ERROR GlobalMinimalMdnsServer::StartServer(chip::Inet::EndPointManager<chip::Inet::UDPEndPoint> * udpEndPointManager,
uint16_t port)
{
GlobalMinimalMdnsServer::Server().ShutdownEndpoints();
UniquePtr<ListenIterator> endpoints = GetAddressPolicy()->GetListenEndpoints();
return GlobalMinimalMdnsServer::Server().Listen(udpEndPointManager, endpoints.get(), port);
}
void GlobalMinimalMdnsServer::ShutdownServer()
{
GlobalMinimalMdnsServer::Server().Shutdown();
}
} // namespace Dnssd
} // namespace chip
| [
"noreply@github.com"
] | noreply@github.com |
9c460145956ebc6bde0991676cc69312f78576a6 | 68df74deb602f3f1ab270777e615796f10caeaa5 | /5/5_11.cpp | 304d0a703bae7b34ae5791d073168c60821188fd | [] | no_license | nanohaikaros/cpp_learn | 88d726f05a22703426a2910184ab8535203f4f91 | 31a96d6666ceed5f12089fd63174d530798c0b16 | refs/heads/master | 2020-05-30T11:32:48.484164 | 2019-06-21T01:28:52 | 2019-06-21T01:28:52 | 189,705,452 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 400 | cpp | #include <iostream>
using namespace std;
int main() {
cout << "Use sizeof of determine memory occupied by arrays" << endl;
int MyNumbers[100] = {0};
cout << "Bytes occupied by an int: " << sizeof(int) << endl;
cout << "Bytes occupied by array MyNumbers: " << sizeof(MyNumbers) << endl;
cout << "Bytes occupied by each element: " << sizeof(MyNumbers[0]) << endl;
return 0;
} | [
"1371689491@qq.com"
] | 1371689491@qq.com |
6e8d84bc0a3519431a6bf85acaa25947238d461b | 947d8cc7b8c180c765810d48704ffc2d06956841 | /src/plugins/anim/datatypes/polygons.h | 0eb02a48cab7186ee6ba851fcd24e55a7bf641de | [
"MIT"
] | permissive | yangjiang123/possumwood | c82b7a18eabe77aa87f9767336348acf3cf02111 | 91b1844b9fb0e7952a8a9170508ec4c03168b25e | refs/heads/master | 2022-07-01T04:44:35.687225 | 2020-05-10T14:29:22 | 2020-05-10T14:29:22 | 267,554,460 | 1 | 0 | null | 2020-05-28T09:58:17 | 2020-05-28T09:58:16 | null | UTF-8 | C++ | false | false | 690 | h | #pragma once
#include <array>
#include <vector>
namespace anim {
class Polygons {
public:
std::array<std::size_t, 3>& add(std::size_t p1, std::size_t p2, std::size_t p3);
std::array<std::size_t, 3>& operator[](std::size_t index);
const std::array<std::size_t, 3>& operator[](std::size_t index) const;
bool empty() const;
std::size_t size() const;
typedef std::vector<std::array<std::size_t, 3> >::const_iterator const_iterator;
const_iterator begin() const;
const_iterator end() const;
typedef std::vector<std::array<std::size_t, 3> >::iterator iterator;
iterator begin();
iterator end();
private:
std::vector<std::array<std::size_t, 3> > m_polygons;
};
}
| [
"martin.prazak@gmail.com"
] | martin.prazak@gmail.com |
a4d5164dafc5575e34731388972da5bed0af8547 | e3fbad020e213ebcc70164ce278888036a6bbe32 | /traffic-light-mqtt/traffic-light-mqtt.ino | f1fba923d6db0786e4e0f4fdeee38505c51f570d | [] | no_license | cryptocodecg/CG-IoT | 2e04c1cafdad7a2c83907fd0f288688f32a62122 | d126c53f102a7952949f764a340dd830f8c9aa60 | refs/heads/master | 2021-01-24T18:04:30.442387 | 2017-03-20T02:55:34 | 2017-03-20T02:55:34 | 84,385,888 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,432 | ino | #include <Adafruit_NeoPixel.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#define PIN 15
#define NUMPIXELS 1
const char* ssid = "procodecg";
const char* password = "12345678";
//const char* mqtt_server = "broker.mqtt-dashboard.com";
//const char* mqtt_server = "192.168.1.118";
const char* mqtt_server = "192.168.1.101";
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);
int delayval = 1000;
int i=0;
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print("x");
}
randomSeed(micros());
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
// Switch on the LED if an 1 was received as first character
if ((char)payload[0] == '0') {
digitalWrite(BUILTIN_LED, LOW); // Turn the LED on (Note that LOW is the voltage level
// but actually the LED is on; this is because
// it is acive low on the ESP-01)
} else {
digitalWrite(BUILTIN_LED, HIGH); // Turn the LED off by making the voltage HIGH
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = "ESP8266Client-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId.c_str())) {
Serial.println("connected");
// Once connected, publish an announcement...
// client.publish("outTopic", "hello world");
// ... and resubscribe
client.subscribe("led1");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup() {
pixels.begin(); // This initializes the NeoPixel library.
Serial.begin(9600);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
// red
client.publish("led1", "red");
pixels.setPixelColor(0, pixels.Color(63,0,0));
pixels.show();
delay(3000);
client.publish("led1", "yellow");
for (i=0; i<5; i++) {
// yellow
pixels.setPixelColor(0, pixels.Color(63,63,0)); pixels.show(); delay(500);
// blank
pixels.setPixelColor(0, pixels.Color(0,0,0)); pixels.show(); delay(500);
}
// green
client.publish("led1", "green");
pixels.setPixelColor(0, pixels.Color(0,63,0));
pixels.show();
delay(3000);
client.publish("led1", "yellow");
for (i=0; i<3; i++) {
// orange
pixels.setPixelColor(0, pixels.Color(63,40,0)); pixels.show(); delay(500);
// blank
pixels.setPixelColor(0, pixels.Color(0,0,0)); pixels.show(); delay(500);
}
}
| [
"cryptocodecg@gmail.com"
] | cryptocodecg@gmail.com |
c6840885694630d87ea5429a41f258729a657e7b | d0c44dd3da2ef8c0ff835982a437946cbf4d2940 | /cmake-build-debug/programs_tiling/function13760/function13760_schedule_8/function13760_schedule_8_wrapper.cpp | d961a9d1b38eefed3b29772598edbb5f71fa5e3d | [] | no_license | IsraMekki/tiramisu_code_generator | 8b3f1d63cff62ba9f5242c019058d5a3119184a3 | 5a259d8e244af452e5301126683fa4320c2047a3 | refs/heads/master | 2020-04-29T17:27:57.987172 | 2019-04-23T16:50:32 | 2019-04-23T16:50:32 | 176,297,755 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,255 | cpp | #include "Halide.h"
#include "function13760_schedule_8_wrapper.h"
#include "tiramisu/utils.h"
#include <cstdlib>
#include <iostream>
#include <time.h>
#include <fstream>
#include <chrono>
#define MAX_RAND 200
int main(int, char **){
Halide::Buffer<int32_t> buf00(2048);
Halide::Buffer<int32_t> buf01(32768);
Halide::Buffer<int32_t> buf02(2048);
Halide::Buffer<int32_t> buf03(2048);
Halide::Buffer<int32_t> buf04(2048);
Halide::Buffer<int32_t> buf05(2048);
Halide::Buffer<int32_t> buf0(2048, 32768);
init_buffer(buf0, (int32_t)0);
auto t1 = std::chrono::high_resolution_clock::now();
function13760_schedule_8(buf00.raw_buffer(), buf01.raw_buffer(), buf02.raw_buffer(), buf03.raw_buffer(), buf04.raw_buffer(), buf05.raw_buffer(), buf0.raw_buffer());
auto t2 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> diff = t2 - t1;
std::ofstream exec_times_file;
exec_times_file.open("../data/programs/function13760/function13760_schedule_8/exec_times.txt", std::ios_base::app);
if (exec_times_file.is_open()){
exec_times_file << diff.count() * 1000000 << "us" <<std::endl;
exec_times_file.close();
}
return 0;
} | [
"ei_mekki@esi.dz"
] | ei_mekki@esi.dz |
bcd3644af4e39b9c322950d3cf3284da6d65cf6f | 7332bed7e7d3d5f8123940e2e697938fb1fccf82 | /MFCUI/MFCUIDlg.cpp | a9fa7c06617dcb8432309ef09df099e84f6d05ff | [] | no_license | arnold-xiang/Barcode- | 0c3d25128ed4d1d605d5ef75c0b0b7a187b2005d | eb797840b564c52682e98fb4e9eeb418002d56af | refs/heads/master | 2020-04-25T03:11:10.220556 | 2019-03-04T09:49:51 | 2019-03-04T09:49:51 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 18,863 | cpp |
// MFCUIDlg.cpp : 实现文件
//
#include "stdafx.h"
#include "MFCUI.h"
#include "MFCUIDlg.h"
#include "HalconCpp.h"
#include "afxdialogex.h"
#include <iostream>
using namespace std;
using namespace HalconCpp;
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
//全局变量
int MoRow;
int MoCol;
CTime t1;
HObject ho_Image;
CRect rtWindow;
HTuple m_htWindow,hv_Length;
HTuple DirectShow, hv_AcqHandle;
class CAboutDlg : public CDialogEx
{
public:
CAboutDlg();
// 对话框数据
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_ABOUTBOX };
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
// 实现
protected:
DECLARE_MESSAGE_MAP()
public:
// virtual BOOL PreTranslateMessage(MSG* pMsg);
HACCEL hAccel;
};
CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()
// CMFCUIDlg 对话框
CMFCUIDlg::CMFCUIDlg(CWnd* pParent /*=NULL*/)
: CDialogEx(IDD_MFCUI_DIALOG, pParent)
, Row(_T(""))
, Column(_T(""))
, BoxNumber(_T(""))
, SampleType(_T(""))
, BoxDescription(_T(""))
, BoxLocation(_T(""))
, m_ChangeContext(_T(""))
{
m_hIcon = AfxGetApp()->LoadIcon(IDI_ICON1);
}
void CMFCUIDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Text(pDX, IDC_EDIT1_Row, Row);
DDX_Text(pDX, IDC_EDIT2_Column, Column);
DDX_Text(pDX, IDC_EDIT3_BoxNumber, BoxNumber);
DDX_Text(pDX, IDC_EDIT4_SampleType, SampleType);
DDX_Text(pDX, IDC_EDIT5_BoxDescription, BoxDescription);
DDX_Text(pDX, IDC_EDIT6_BoxLocation, BoxLocation);
DDX_Control(pDX, IDC_LIST, m_ListCtrl);
DDX_Text(pDX, IDC_EDIT_ChangeContext, m_ChangeContext);
DDX_Text(pDX, IDC_EDIT1_Total, Bar_Total);
DDX_Text(pDX, IDC_EDIT1_Dealed, Bar_Dealed);
DDX_Control(pDX, IDC_COMBO1, m_Device);
}
BEGIN_MESSAGE_MAP(CMFCUIDlg, CDialogEx)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_BUTTON5_Txt, &CMFCUIDlg::OnBnClickedButton5Txt)
ON_BN_CLICKED(IDC_BUTTON3_Image, &CMFCUIDlg::OnBnClickedButton3Image)
//ON_BN_CLICKED(IDC_BUTTON4_Sql, &CMFCUIDlg::OnBnClickedButton4Sql)
ON_BN_CLICKED(IDC_BUTTON_ChangeContext, &CMFCUIDlg::OnBnClickedButtonChangecontext)
ON_NOTIFY(NM_CLICK, IDC_LIST, &CMFCUIDlg::OnNMClickList)
//ON_BN_CLICKED(IDC_BUTTON2_Start2, &CMFCUIDlg::OnBnClickedButton2Start2)
ON_BN_CLICKED(IDC_BUTTON_Exit, &CMFCUIDlg::OnBnClickedButtonExit)
ON_BN_CLICKED(IDC_BUTTON1_Fresh, &CMFCUIDlg::OnBnClickedButton1Fresh)
ON_BN_CLICKED(IDC_BUTTON2_Deal, &CMFCUIDlg::OnBnClickedButton2Deal)
ON_BN_CLICKED(IDC_BUTTON5_Excel, &CMFCUIDlg::OnBnClickedButton5Excel)
END_MESSAGE_MAP()
// CMFCUIDlg 消息处理程序
BOOL CMFCUIDlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
// 将“关于...”菜单项添加到系统菜单中。
// IDM_ABOUTBOX 必须在系统命令范围内。
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
BOOL bNameValid;
CString strAboutMenu;
bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
ASSERT(bNameValid);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
SetIcon(m_hIcon, TRUE); // 设置大图标
SetIcon(m_hIcon, FALSE); // 设置小图标
//获取当前时间
t1 = CTime::GetCurrentTime();
//初始化
ListControlhwnd = GetDlgItem(IDC_LIST)->m_hWnd;
skinppSetNoSkinHwnd(ListControlhwnd);
init_Register();
init_list_control();
init_StatusBarr();
//获取相机参数
HTuple hv_Information, hv_ValueList, hv_Length1;
InfoFramegrabber("DirectShow", "device", &hv_Information, &hv_ValueList);
TupleLength(hv_ValueList, &hv_Length1);
if (0== hv_Length1)
{
MessageBox("当前无相机设备");
}
//打开相机
OpenFramegrabber("DirectShow", 1, 1, 0, 0, 0, 0, "default", 8, "gray", -1, "false",
"[" + (HTuple)hv_ValueList[1] + " yuv (3264x2448)", hv_ValueList, 0, -1, &hv_AcqHandle);
SetFramegrabberParam(hv_AcqHandle, "brightness", -64);
SetFramegrabberParam(hv_AcqHandle, "gamma", 76);
SetFramegrabberParam(hv_AcqHandle, "white_balance", 5500);
SetFramegrabberParam(hv_AcqHandle, "exposure", -4);
GrabImageStart(hv_AcqHandle, -1);
GrabImage(&ho_Image, hv_AcqHandle);
Sleep(300);
HWND hImgWnd = GetDlgItem(IDC_STATIC_Image)->m_hWnd;
GetDlgItem(IDC_STATIC_Image)->GetClientRect(&rtWindow);
OpenWindow(rtWindow.left, rtWindow.top, rtWindow.Width(), rtWindow.Height(), (Hlong)hImgWnd, "visible", "", &m_htWindow);
return TRUE; // 除非将焦点设置到控件,否则返回 TRUE
}
void CMFCUIDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialogEx::OnSysCommand(nID, lParam);
}
}
// 如果向对话框添加最小化按钮,则需要下面的代码
// 来绘制该图标。 对于使用文档/视图模型的 MFC 应用程序,
// 这将由框架自动完成。
void CMFCUIDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // 用于绘制的设备上下文
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// 使图标在工作区矩形中居中
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// 绘制图标
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialogEx::OnPaint();
}
}
//当用户拖动最小化窗口时系统调用此函数取得光标
//显示。
HCURSOR CMFCUIDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
//注册软件
void CMFCUIDlg::init_Register()
{
unsigned long s1, s2;
CString sCpuID, CPUID1, CPUID2;
__asm {
mov eax, 01h
xor edx, edx
cpuid
mov s1, edx
mov s2, eax
}
CPUID1.Format("%08X%08X", s1, s2);
__asm {
mov eax, 03h
xor ecx, ecx
xor edx, edx
cpuid
mov s1, edx
mov s2, ecx
}
CPUID2.Format("%08X%08X", s1, s2);
sCpuID = CPUID1 + CPUID2;
//SetDlgItemText(IDC_EDIT1, sCpuID);
DWORD ser;
char namebuf[128];
char filebuf[128];
::GetVolumeInformation("c:\\", namebuf, 128, &ser, 0, 0, filebuf, 128);
CString strdisk;
strdisk.Format("%d", ser);
//SetDlgItemText(IDC_EDIT2, strdisk);
CString strmachine;
strmachine = sCpuID.Mid(13, 5); //从MyCpuID的第13位开始取5个
strmachine += strdisk.Mid(3, 5);//从strdisk的第3位开始取5个,合并生成机器码
//SetDlgItemText(IDC_EDIT3, strmachine);
//读取机器码
LONG lValue;
RegQueryValue(HKEY_CURRENT_USER, "Software\\test\\admin", NULL, &lValue);
char *pBuf = new char[lValue];
RegQueryValue(HKEY_CURRENT_USER, "Software\\test\\admin", pBuf, &lValue);
if (pBuf != strmachine)
{
MessageBox("激活失败! 请先使用注册机进行注册");
ExitProcess(0);
}
}
//保存图像
void CMFCUIDlg::OnBnClickedButton3Image()
{
CWnd* bmpShow = GetDlgItem(IDC_STATIC_Image);
CDC *pdc = bmpShow->GetDC();
CImage imag;
CRect rect;
GetClientRect(&rect);
bmpShow->GetWindowRect(&rect);
imag.Create(rect.Width(), rect.Height(), 32);
::BitBlt(imag.GetDC(), 0, 0, rect.Width(), rect.Height(), pdc->m_hDC, 0, 0, SRCCOPY);
TCHAR szFilter[] = _T("jpg file(.jpg)|.jpg|bmp file(.bmp)|.bmp|所有文件(*.*)|*.*||");
CFileDialog fileDlg(FALSE, _T("jpg"), _T(".jpg"), OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, szFilter, this);
fileDlg.m_ofn.lpstrTitle = _T("保存图片");
CString picturePath;
if (IDOK == fileDlg.DoModal())
{
picturePath = fileDlg.GetPathName();
}
HRESULT hResult = imag.Save(picturePath);
ReleaseDC(pdc);
imag.ReleaseDC();
}
//保存为Txt
void CMFCUIDlg::OnBnClickedButton5Txt()
{
CString strFilePath;
CString strFilter = _T("txt文件(*.txt)|*.txt");
CFileDialog dlg(FALSE, _T("txt"), NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, strFilter, this);
dlg.m_ofn.lpstrTitle = _T("保存为TXT");
if (dlg.DoModal() != IDC_BUTTON5_Txt)
{
strFilePath = dlg.GetPathName();
FILE *fp;
const char* fpath = CStringA(strFilePath);
fopen_s(&fp, fpath, "w");
char str[1024];
if (fp == NULL)
{
printf("save error\n");
return;
}
int nHeadNum = m_ListCtrl.GetHeaderCtrl()->GetItemCount();
LVCOLUMN lvcol;
char str_out[256];
int nColNUm;
nColNUm = 0;
lvcol.mask = LVCF_TEXT;
lvcol.pszText = str_out;
lvcol.cchTextMax = 256;
fwrite("[盒子信息]\n", 1, strlen("[盒子信息]\n"), fp);
CString savetime=t1.Format("%Y-%m-%d %X");
fprintf_s(fp, "%s\t", "保存时间="+savetime);
fprintf_s(fp, "\n");
UpdateData(true);
fprintf_s(fp, "%s\t", "盒子编号=" + BoxNumber);
fprintf_s(fp, "\n");
UpdateData(true);
fprintf_s(fp, "%s\t", "标本类型=" + SampleType);
fprintf_s(fp, "\n");
UpdateData(true);
fprintf_s(fp, "%s\t", "盒子描述=" + BoxDescription);
fprintf_s(fp, "\n");
UpdateData(true);
fprintf_s(fp, "%s\t", "盒子位置=" + BoxLocation);
fprintf_s(fp, "\n");
fwrite("[冻存管信息]\n", 1, strlen("[冻存管信息]\n"), fp);
while (m_ListCtrl.GetColumn(nColNUm, &lvcol))
{
nColNUm++;
fprintf_s(fp, "%s\t", lvcol.pszText);
}
/*for ( nColNUm = 0; nColNUm < 4; nColNUm++)
{
m_ListCtrl.GetColumn(nColNUm, &lvcol);
fprintf_s(fp, "%s\t", lvcol.pszText);
}*/
fprintf_s(fp, "\n", lvcol.pszText);
int nRow = m_ListCtrl.GetItemCount();
for (int i = 0; i < nRow; i++)
{
for (int j = 0; j < nColNUm-5; j++)
{
CString str_data = m_ListCtrl.GetItemText(i, j);
fprintf_s(fp, "%s\t", str_data);
}
fprintf_s(fp, "\n");
}
fclose(fp);
}
}
//保存为Excel
void CMFCUIDlg::OnBnClickedButton5Excel()
{
CString strFilePath;
CString Esavetime = t1.Format("%Y-%m-%d %X");
CString strFilter = _T("xls文件(*.xls)|*.xls");
CFileDialog dlg(FALSE, _T(".xls"), NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, strFilter, this);
dlg.m_ofn.lpstrTitle = _T("保存为Excel");
if (dlg.DoModal() != IDC_BUTTON5_Txt)
{
strFilePath = dlg.GetPathName();
FILE *fp;
const char* fpath = CStringA(strFilePath);
fopen_s(&fp, fpath, "w");
char str[1024];
if (fp == NULL)
{
printf("save error\n");
return;
}
int nHeadNum = m_ListCtrl.GetHeaderCtrl()->GetItemCount();
LVCOLUMN lvcol;
char str_out[256];
int nColNUm;
nColNUm = 0;
lvcol.mask = LVCF_TEXT;
lvcol.pszText = str_out;
lvcol.cchTextMax = 256;
while (m_ListCtrl.GetColumn(nColNUm, &lvcol))
{
nColNUm++;
fprintf_s(fp, "%s\t", lvcol.pszText);
}
fprintf_s(fp, "\n", lvcol.pszText);
for (int i = 1; i < hv_Length + 1; i++)
{
UpdateData(true);
m_ListCtrl.SetItemText(i-1, 4, BoxNumber);
UpdateData(true);
m_ListCtrl.SetItemText(i-1, 5, SampleType);
UpdateData(true);
m_ListCtrl.SetItemText(i-1, 6, BoxDescription);
UpdateData(true);
m_ListCtrl.SetItemText(i-1, 7, BoxLocation);
m_ListCtrl.SetItemText(i-1, 8, Esavetime);
}
int nRow = m_ListCtrl.GetItemCount();
for (int i = 0; i < nRow; i++)
{
for (int j = 0; j < nColNUm; j++)
{
CString str_data = m_ListCtrl.GetItemText(i, j);
fprintf_s(fp, "%s\t", str_data);
}
fprintf_s(fp, "\n");
}
fclose(fp);
}
}
//初始化list control
void CMFCUIDlg::init_list_control()
{
//表头
m_ListCtrl.SetItemState(30, LVIS_FOCUSED | LVIS_SELECTED, LVIS_FOCUSED | LVIS_SELECTED);
m_ListCtrl.SetExtendedStyle(LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES);
m_ListCtrl.InsertColumn(0, _T("序号"));
m_ListCtrl.InsertColumn(1, _T("位置"));
m_ListCtrl.InsertColumn(2, _T("条码内容"));
m_ListCtrl.InsertColumn(3, _T("标本内容"));
m_ListCtrl.InsertColumn(4, _T("盒子序号"));
m_ListCtrl.InsertColumn(5, _T("标本类型"));
m_ListCtrl.InsertColumn(6, _T("盒子描述"));
m_ListCtrl.InsertColumn(7, _T("盒子位置"));
m_ListCtrl.InsertColumn(8, _T("保存时间"));
CRect rect;
m_ListCtrl.GetClientRect(rect);
m_ListCtrl.SetColumnWidth(0, 0.2*rect.Width());
m_ListCtrl.SetColumnWidth(1, 0.2*rect.Width());
m_ListCtrl.SetColumnWidth(2, 0.3*rect.Width());
m_ListCtrl.SetColumnWidth(3, 0.3*rect.Width());
}
//初始化state_bar
void CMFCUIDlg::init_StatusBarr()
{
m_bar.Create(this);
m_bar.SetIndicators(indicators, sizeof(indicators) / sizeof(UINT));
CRect rect;
GetWindowRect(rect);
m_bar.SetPaneInfo(0, ID_INDICATOR_COUNT, SBPS_STRETCH, 0.2*rect.Width() );
//m_bar.SetPaneInfo(1, ID_INDICATOR_TIME, SBPS_NORMAL, 0.8*rect.Width());
RepositionBars(AFX_IDW_CONTROLBAR_FIRST,AFX_IDW_CONTROLBAR_LAST, 0);
SetTimer(1, 1000, NULL);
//CString str;
//str = hv_Length.S();
m_bar.SetPaneText(0, t1.Format(" %Y年%m月%d日 "));
////m_bar.SetPaneText(1, " 识别总数 100个 识别 ?个");
}
//Timer
void CMFCUIDlg::OnTimer(UINT_PTR nIDEvent)
{
/*CTime t1;
t1 = CTime::GetCurrentTime();*/
m_bar.SetPaneText(0, t1.Format(" %Y年%m月%d日 星期%w "));
CDialog::OnTimer(nIDEvent);
}
//快捷键虚函数重载
BOOL CMFCUIDlg::PreTranslateMessage(MSG* pMsg)
{
switch (pMsg->wParam)
{
//case VK_F1: {OnBnClickedButton2Start2(); break; }
case VK_F2: {OnBnClickedButton2Deal(); break; }
case VK_F3: {OnBnClickedButton3Image(); break; }
//case VK_F4: {OnBnClickedButton4Sql(); break; }
case VK_F5: {OnBnClickedButton5Txt(); break; }
}
return CDialog::PreTranslateMessage(pMsg);
}
//添加listctrl控件的NM_CLICK消息相应函数,得到单击的CListCtrl的行列号
void CMFCUIDlg::OnNMClickList(NMHDR *pNMHDR, LRESULT *pResult)
{
LPNMITEMACTIVATE pNMItemActivate = reinterpret_cast<LPNMITEMACTIVATE>(pNMHDR);
NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR;
if (pNMListView->iItem != -1)
{
MoRow = pNMListView->iItem;
MoCol = pNMListView->iSubItem;
}
*pResult = 0;
}
//修改条码内容
void CMFCUIDlg::OnBnClickedButtonChangecontext()
{
UpdateData();
CString Mostr = m_ChangeContext;
UpdateData(TRUE);
m_ListCtrl.SetItemText(MoRow, MoCol + 1, _T(Mostr));
}
//item选中高亮
void CMFCUIDlg::OnCustomdrawList(NMHDR *pNMHDR, LRESULT *pResult)
{
NMLVCUSTOMDRAW* pLVCD = reinterpret_cast<NMLVCUSTOMDRAW*>(pNMHDR);
*pResult = CDRF_DODEFAULT;
if (CDDS_PREPAINT == pLVCD->nmcd.dwDrawStage)
{
*pResult = CDRF_NOTIFYITEMDRAW;
}
else if (CDDS_ITEMPREPAINT == pLVCD->nmcd.dwDrawStage)
{
*pResult = CDRF_NOTIFYSUBITEMDRAW;
}
else if ((CDDS_ITEMPREPAINT | CDDS_SUBITEM) == pLVCD->nmcd.dwDrawStage)
{
COLORREF clrNewTextColor, clrNewBkColor;
int nItem = static_cast<int>(pLVCD->nmcd.dwItemSpec);
POSITION pos = m_ListCtrl.GetFirstSelectedItemPosition();
int index = m_ListCtrl.GetNextSelectedItem(pos);
if (index == nItem)//如果要刷新的项为当前选择的项,则将文字设为白色,背景色设为蓝色
{
clrNewTextColor = RGB(255, 255, 255); //Set the text to white
clrNewBkColor = RGB(49, 106, 197); //Set the background color to blue
}
else
{
clrNewTextColor = RGB(0, 0, 0); //set the text black
clrNewBkColor = RGB(255, 255, 255); //leave the background color white
}
pLVCD->clrText = clrNewTextColor;
pLVCD->clrTextBk = clrNewBkColor;
*pResult = CDRF_DODEFAULT;
}
}
//采图
//void CMFCUIDlg::OnBnClickedButton2Start2()
//{
//
// //打开相机
// int indexD = m_Device.GetCurSel();
// CString strDevice;
// m_Device.GetLBText(indexD, strDevice);
// /*CString str;
// str.Format("choose%s", strDevice);
// MessageBox(str);*/
// try
// {
// OpenFramegrabber("DirectShow", 1, 1, 0, 0, 0, 0, "default", 8, "gray", -1, "false",
// "["+ (HTuple)strDevice[1]+" yuv (3264x2448)", (HTuple)strDevice, 0, -1, &hv_AcqHandle);
// SetFramegrabberParam(hv_AcqHandle, "brightness", -64);
// SetFramegrabberParam(hv_AcqHandle, "gamma", 76);
// SetFramegrabberParam(hv_AcqHandle, "white_balance", 5500);
// SetFramegrabberParam(hv_AcqHandle, "exposure", -4);
// GrabImageStart(hv_AcqHandle, -1);
// GrabImage(&ho_Image, hv_AcqHandle);
// Sleep(300);
// MessageBox("相机打开成功");
// //清空数据表中的数据
// //m_ListCtrl.DeleteAllItems();
// }
// catch (const std::exception&)
// {
// MessageBox("相机打开失败");
// }
//
//}
//关闭相机退出
void CMFCUIDlg::OnBnClickedButtonExit()
{
CloseFramegrabber(hv_AcqHandle);
ExitProcess(0);
}
//刷新图片
void CMFCUIDlg::OnBnClickedButton1Fresh()
{
CStatic* pStatic = (CStatic*)GetDlgItem(IDC_STATIC_Image);
pStatic->GetClientRect(&rtWindow);
pStatic->GetDC()->FillSolidRect(rtWindow.left, rtWindow.top, rtWindow.Width(), rtWindow.Height(), RGB(240, 240, 240));
pStatic->GetClientRect(&rtWindow); pStatic->GetDC()->FillSolidRect(rtWindow.left, rtWindow.top, rtWindow.Width(), rtWindow.Height(), RGB(192, 192, 192));
}
//抓图处理
void CMFCUIDlg::OnBnClickedButton2Deal()
{
HObject ho_Circle, ho_ImageReduced;
HObject ho_SymbolXLDs1;
HTuple hv_CircleD, hv_Blank, hv_row, hv_column, hv_index, hv_DataCodeHandle;
HTuple hv_IndexY, hv_IndexX, hv_ResultHandles, hv_DecodedDataStrings1;
HTuple width, height;
hv_CircleD = 200;
hv_Blank = 40;
hv_row = 155;
hv_column = 204;
hv_index = HTuple();
m_ListCtrl.DeleteAllItems();
//GrabImage(&ho_Image, hv_AcqHandle);
ReadImage(&ho_Image, "E:/1.1.jpg");
//WriteImage(ho_Image, "jpg", 0, "E:/1.1.jpg");
GetImageSize(ho_Image, &height, &width);
SetWindowAttr("background_color", "black");
SetPart(m_htWindow, 0, 0, width, height);
if (HDevWindowStack::IsOpen())
HalconCpp::CloseWindow(m_htWindow);
DispObj(ho_Image, m_htWindow);
CreateDataCode2dModel("Data Matrix ECC 200", "default_parameters", "enhanced_recognition",
&hv_DataCodeHandle);
for (hv_IndexY = 0; hv_IndexY <= 9; hv_IndexY += 1)
{
for (hv_IndexX = 0; hv_IndexX <= 9; hv_IndexX += 1)
{
GenCircle(&ho_Circle, hv_row + ((hv_CircleD + hv_Blank)*hv_IndexY), hv_column + ((hv_CircleD + hv_Blank)*hv_IndexX),
hv_CircleD / 2);
SetTposition(m_htWindow, (hv_row - 120) + ((hv_CircleD + hv_Blank)*hv_IndexY),
(hv_column + 40) + ((hv_CircleD + hv_Blank)*hv_IndexX));
WriteString(m_htWindow, (hv_IndexX + (hv_IndexY * 10)) + 1);
ReduceDomain(ho_Image, ho_Circle, &ho_ImageReduced);
FindDataCode2d(ho_ImageReduced, &ho_SymbolXLDs1, hv_DataCodeHandle, HTuple(),
HTuple(), &hv_ResultHandles, &hv_DecodedDataStrings1);
DispObj(ho_SymbolXLDs1, m_htWindow);
TupleConcat(hv_index, hv_DecodedDataStrings1, &hv_index);
TupleLength(hv_index, &hv_Length);
}
}
//显示识别数目
Bar_Total = hv_IndexY*hv_IndexX;
UpdateData(false);
Bar_Dealed = hv_Length;
UpdateData(false);
//给表添加数据
for (int i = 1; i < hv_Length + 1; i++)
{
CString str;
str.Format(_T("%d"), i);
CString temp = (CString)hv_index[i - 1].S();
int nRow = m_ListCtrl.InsertItem(i, str);
m_ListCtrl.SetItemText(nRow, 1, str);
m_ListCtrl.SetItemText(nRow, 2, temp);
m_ListCtrl.SetItemText(nRow, 3, _T(""));
}
}
| [
"18162324791@163.com"
] | 18162324791@163.com |
d763e4fb114c00caf13605fb33081df5d5944f19 | 49f1d82f20dd9f46d53a504baf1de5bfd0993e6e | /main.cpp | bfb4cf5562ccb82b78197ef3a9c95ec352a13be1 | [] | no_license | DejanPopovic1/6502Emulator | eacfa0174d9503fedaddf5675f2f842e0b26faef | 2c6d1308581680d24788aeee4cd75482b031ad58 | refs/heads/master | 2023-04-08T10:09:03.191428 | 2021-04-21T20:45:19 | 2021-04-21T20:45:19 | 355,345,263 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 129 | cpp | #include "Processor.h"
#include "Memory.h"
int main() {
Processor p;
Memory m;
p.connectMemory(&m);
return 0;
}
| [
"dejan.dp.popovic@gmail.com"
] | dejan.dp.popovic@gmail.com |
e002958c39a1c7322312f5e5811764a58b684f99 | f434c4ec57366caa99be48dc49f59393207465c7 | /src/GA.h | 969a248d682d96c4222cebd91e1462aadb2ca89f | [] | no_license | Kajiyu/GATextureSample1 | f39e7c7139196ccee262aa29dfa89fa6eb19248a | 972175da6f666e79a8c6c3cf656bd7349e5f761e | refs/heads/master | 2020-06-29T19:00:07.228419 | 2016-11-21T23:36:02 | 2016-11-21T23:36:02 | 74,414,488 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 592 | h | //
// GA.h
// GATextureSample1
//
// Created by KajiharaYuma on 2016/11/21.
//
//
#pragma once
#include "ofMain.h"
#define SAMPLENUM 10
#define GENENUM 10000
class GA {
public:
float ans[GENENUM];
vector<vector<float>> samples;
float scores[SAMPLENUM];
ofPixels pixels[SAMPLENUM];
float mutationPer = 0.01;
float eliteNum = 1; //エリート選択に使う数
int currentAge = 0;
float currentBestScore = 0;
int eliteindex;
int maxAge = 30000;
void initialize(ofImage &image);
void evaluate();
void selection();
void mutation();
}; | [
"kajimars.uts1@gmail.com"
] | kajimars.uts1@gmail.com |
36f6fd272737cdfab56b9d48e93d1619c1af3275 | 9cff3762b21c811386444684924e2f5b3d716d3c | /Classes/binding-mruby/binding-util.h | 68158f5a48c8b165fc992526e278097f35002b3f | [] | no_license | cjv123/RPGR | 8e43f46773dd1db24ccd5d4a2e0d74a738e2e3a6 | c4242009128072427160dae8bbff6007b6147360 | refs/heads/master | 2020-06-01T19:05:40.018546 | 2014-04-28T07:53:46 | 2014-04-28T07:53:46 | 18,788,101 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 9,012 | h | #ifndef BINDINGUTIL_H
#define BINDINGUTIL_H
#include <mruby.h>
#include <mruby/data.h>
#include <mruby/variable.h>
#include <mruby/class.h>
#include <stdio.h>
#include <pthread.h>
#include "viewport.h"
enum CommonSymbol
{
CSpriv_iv = 0, /* private data */
/* From here on out all symbols
* have implicit '@' prefix */
CSfont,
CSviewport,
CSbitmap,
CScolor,
CStone,
CSrect,
CSsrc_rect,
CStileset,
CSautotiles,
CSmap_data,
CSflash_data,
CSpriorities,
CSwindowskin,
CScontents,
CScursor_rect,
CSpath,
CSarray,
CSdefault_color,
CommonSymbolsMax
};
enum MrbException
{
Shutdown = 0,
RGSS,
PHYSFS,
SDL,
MKXP,
ErrnoE2BIG,
ErrnoEACCES,
ErrnoEAGAIN,
ErrnoEBADF,
ErrnoECHILD,
ErrnoEDEADLOCK,
ErrnoEDOM,
ErrnoEEXIST,
ErrnoEINVAL,
ErrnoEMFILE,
ErrnoENOENT,
ErrnoENOEXEC,
ErrnoENOMEM,
ErrnoENOSPC,
ErrnoERANGE,
ErrnoEXDEV,
IO,
TypeError,
ArgumentError,
MrbExceptionsMax
};
struct MrbData
{
RClass *exc[MrbExceptionsMax];
/* I'll leave the usage of these syms to later,
* so I can measure how much of a speed difference they make */
mrb_sym symbols[CommonSymbolsMax];
MrbData(mrb_state *mrb);
};
struct Exception;
void
raiseMrbExc(mrb_state *mrb, const Exception &exc);
inline MrbData*
getMrbData(mrb_state *mrb)
{
return static_cast<MrbData*>(mrb->ud);
}
#define GUARD_EXC(exp) \
{ try { exp } catch (Exception &exc) { raiseMrbExc(mrb, exc); } }
#define DECL_TYPE(_Type) \
extern const mrb_data_type _Type##Type
#define DEF_TYPE(_Type) \
extern const mrb_data_type _Type##Type = \
{ \
#_Type, \
freeInstance<_Type> \
}
/*freeInstance<_Type> \*/
#define MRB_METHOD_PUB(name) \
mrb_value name(mrb_state *mrb, mrb_value self)
#define MRB_METHOD(name) static MRB_METHOD_PUB(name)
#define MRB_FUNCTION(name) \
static mrb_value name(mrb_state *mrb, mrb_value)
#define MRB_UNUSED_PARAM \
{ (void) mrb; (void) self; }
#define MRB_FUN_UNUSED_PARAM { (void) mrb; }
/* If we're not binding a disposable class,
* we want to #undef DEF_PROP_CHK_DISP */
#define DEF_PROP_CHK_DISP \
checkDisposed(mrb, k, DISP_CLASS_NAME);
#define DEF_PROP_OBJ(Klass, PropKlass, PropName, prop_iv) \
MRB_METHOD(Klass##Get##PropName) \
{ \
Klass *k = getPrivateData<Klass>(mrb, self); (void) k; \
DEF_PROP_CHK_DISP \
return getProperty(mrb, self, prop_iv); \
} \
MRB_METHOD(Klass##Set##PropName) \
{ \
Klass *k = getPrivateData<Klass>(mrb, self); \
mrb_value propObj; \
PropKlass *prop; \
mrb_get_args(mrb, "o", &propObj); \
prop = getPrivateDataCheck<PropKlass>(mrb, propObj, PropKlass##Type); \
GUARD_EXC( k->set##PropName(prop); ) \
setProperty(mrb, self, prop_iv, propObj); \
return propObj; \
}
/* Object property with allowed NIL */
#define DEF_PROP_OBJ_NIL(Klass, PropKlass, PropName, prop_iv) \
MRB_METHOD(Klass##Get##PropName) \
{ \
Klass *k = getPrivateData<Klass>(mrb, self); (void) k; \
DEF_PROP_CHK_DISP \
return getProperty(mrb, self, prop_iv); \
} \
MRB_METHOD(Klass##Set##PropName) \
{ \
Klass *k = getPrivateData<Klass>(mrb, self); \
mrb_value propObj; \
PropKlass *prop; \
mrb_get_args(mrb, "o", &propObj); \
if (mrb_nil_p(propObj)) \
prop = 0; \
else \
prop = getPrivateDataCheck<PropKlass>(mrb, propObj, PropKlass##Type); \
GUARD_EXC( k->set##PropName(prop); ) \
setProperty(mrb, self, prop_iv, propObj); \
return mrb_nil_value(); \
}
#define DEF_PROP(Klass, mrb_type, PropName, arg_type, conv_t) \
MRB_METHOD(Klass##Get##PropName) \
{ \
Klass *k = getPrivateData<Klass>(mrb, self); \
DEF_PROP_CHK_DISP \
return mrb_##conv_t##_value(k->get##PropName()); \
} \
MRB_METHOD(Klass##Set##PropName) \
{ \
Klass *k = getPrivateData<Klass>(mrb, self); \
mrb_type value; \
mrb_get_args(mrb, arg_type, &value); \
GUARD_EXC( k->set##PropName(value); ) \
return mrb_##conv_t##_value(value); \
}
#define DEF_PROP_I(Klass, PropName) \
DEF_PROP(Klass, mrb_int, PropName, "i", fixnum)
#define DEF_PROP_F(Klass, PropName) \
DEF_PROP(Klass, mrb_float, PropName, "f", _float)
#define DEF_PROP_B(Klass, PropName) \
DEF_PROP(Klass, mrb_bool, PropName, "b", bool)
#define CLONE_FUN(Klass) \
MRB_METHOD(Klass##Clone) \
{ \
Klass *k = getPrivateData<Klass>(mrb, self); \
mrb_value dupObj = mrb_obj_clone(mrb, self); \
Klass *dupK = new Klass(*k); \
setPrivateData(mrb, dupObj, dupK, Klass##Type); \
return dupObj; \
}
#define MARSH_LOAD_FUN(Klass) \
MRB_METHOD(Klass##Load) \
{ \
return objectLoad<Klass>(mrb, self, Klass##Type); \
}
#define INIT_PROP_BIND(Klass, PropName, prop_name_s) \
{ \
mrb_define_method(mrb, klass, prop_name_s, Klass##Get##PropName, MRB_ARGS_NONE()); \
mrb_define_method(mrb, klass, prop_name_s "=", Klass##Set##PropName, MRB_ARGS_REQ(1)); \
}
static inline mrb_value
mrb__float_value(mrb_float f)
{
mrb_value v;
MRB_SET_VALUE(v, MRB_TT_FLOAT, value.f, f);
return v;
}
inline mrb_sym
getSym(mrb_state *mrb, CommonSymbol sym)
{
return getMrbData(mrb)->symbols[sym];
}
template<typename T>
inline T *
getPrivateData(mrb_state *mrb, mrb_value self)
{
mrb_value priv = mrb_obj_iv_get(mrb,
mrb_obj_ptr(self),
getSym(mrb, CSpriv_iv));
return static_cast<T*>(DATA_PTR(priv));
}
template<typename T>
inline T *
getPrivateDataCheck(mrb_state *mrb, mrb_value obj, const mrb_data_type &type)
{
static const char mesg[] = "wrong argument type %S (expected %S)";
if (mrb_type(obj) != MRB_TT_OBJECT)
mrb_raisef(mrb, E_TYPE_ERROR, mesg,
mrb_str_new_cstr(mrb, (mrb_class_name(mrb, mrb_class(mrb, obj)))),
mrb_str_new_cstr(mrb, type.struct_name));
RObject *objP = mrb_obj_ptr(obj);
if (!mrb_obj_iv_defined(mrb, objP, getSym(mrb, CSpriv_iv)))
mrb_raisef(mrb, E_TYPE_ERROR, mesg,
mrb_str_new_cstr(mrb, (mrb_class_name(mrb, mrb_class(mrb, obj)))),
mrb_str_new_cstr(mrb, type.struct_name));
mrb_value priv = mrb_obj_iv_get(mrb, objP, getSym(mrb, CSpriv_iv));
void *p = mrb_check_datatype(mrb, priv, &type);
return static_cast<T*>(p);
}
inline void
setPrivateData(mrb_state *mrb, mrb_value self, void *p, const mrb_data_type &type)
{
RData *data =
mrb_data_object_alloc(mrb,
mrb_obj_class(mrb, self),
p,
&type);
mrb_obj_iv_set(mrb,
mrb_obj_ptr(self),
getSym(mrb, CSpriv_iv),
mrb_obj_value(data));
}
inline mrb_value
wrapObject(mrb_state *mrb, void *p, const mrb_data_type &type)
{
RClass *c = mrb_class_get(mrb, type.struct_name);
RObject *o = (RObject*) mrb_obj_alloc(mrb, MRB_TT_OBJECT, c);
mrb_value obj = mrb_obj_value(o);
setPrivateData(mrb, obj, p, type);
return obj;
}
inline void
wrapProperty(mrb_state *mrb, mrb_value self,
void *prop, CommonSymbol iv, const mrb_data_type &type)
{
mrb_value propObj = wrapObject(mrb, prop, type);
mrb_obj_iv_set(mrb,
mrb_obj_ptr(self),
getSym(mrb, iv),
propObj);
}
inline void
wrapNilProperty(mrb_state *mrb, mrb_value self, CommonSymbol iv)
{
mrb_obj_iv_set(mrb,
mrb_obj_ptr(self),
getSym(mrb, iv),
mrb_nil_value());
}
inline mrb_value
getProperty(mrb_state *mrb, mrb_value self, CommonSymbol iv)
{
return mrb_obj_iv_get(mrb,
mrb_obj_ptr(self),
getSym(mrb, iv));
}
inline void
setProperty(mrb_state *mrb, mrb_value self,
CommonSymbol iv, mrb_value propObject)
{
mrb_obj_iv_set(mrb,
mrb_obj_ptr(self),
getSym(mrb, iv),
propObject);
}
template<typename T>
void freeInstance( mrb_state *, void *instance )
{
T* p = static_cast<T*>(instance);
delete p;
}
inline mrb_value
mrb_bool_value(bool value)
{
return value ? mrb_true_value() : mrb_false_value();
}
inline bool
_mrb_bool(mrb_value o)
{
return mrb_test(o);
}
template<class C>
inline mrb_value
objectLoad(mrb_state *mrb, mrb_value self, const mrb_data_type &type)
{
RClass *klass = mrb_class_ptr(self);
char *data;
int data_len;
mrb_get_args(mrb, "s", &data, &data_len);
RObject *obj = (RObject*) mrb_obj_alloc(mrb, MRB_TT_OBJECT, klass);
mrb_value obj_value = mrb_obj_value(obj);
C *c = C::deserialize(data, data_len);
setPrivateData(mrb, obj_value, c, type);
return obj_value;
}
extern const mrb_data_type ViewportType;
template<class C>
C * viewportElementInitialize(mrb_state *mrb, mrb_value self)
{
/* Get parameters */
mrb_value viewportObj = mrb_nil_value();
Viewport *viewport = 0;
mrb_get_args(mrb, "|o", &viewportObj);
if (!mrb_nil_p(viewportObj))
viewport = getPrivateDataCheck<Viewport>(mrb, viewportObj, ViewportType);
/* Construct object */
C *ve = new C(viewport);
/* Set property objects */
setProperty(mrb, self, CSviewport, viewportObj);
return ve;
}
inline float rgss_y_to_cocos_y(int y,int h)
{
return (float)(h - y);
}
MRB_METHOD_PUB(inspectObject);
inline int my_abs(int v)
{
int a = v;
if (a<0)
{
a = -a;
}
return a;
}
#endif // BINDINGUTIL_H
| [
"cjv123@qq.com"
] | cjv123@qq.com |
69d5fdecaf59507fdefcef729a2f59fe1aa29b35 | ccec956c2ad7c1eced7415a827d4cb88260ef5c9 | /NotePad/Controls/TabClosingEventArgs.h | 92ad0d816af8dd23b8eb39c23a1057c699b47fb6 | [] | no_license | Dylan-H/NotePadUWP | b7a7e33edbec0525abdae053a4e83e61455d5b34 | 0af598f9b6d0982374307ffa648190770d3464e9 | refs/heads/master | 2020-05-30T07:34:18.527504 | 2019-05-31T14:09:44 | 2019-05-31T14:09:44 | 189,601,013 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 831 | h | #pragma once
#include "TabClosingEventArgs.g.h"
namespace winrt::NotePad::implementation
{
struct TabClosingEventArgs : TabClosingEventArgsT<TabClosingEventArgs>
{
TabClosingEventArgs() = delete;
TabClosingEventArgs(Windows::Foundation::IInspectable const& obj, NotePad::TabViewItem const& item) { _Item = obj; _Tab = item; };
Windows::Foundation::IInspectable Item() { return _Item; };
NotePad::TabViewItem Tab() { return _Tab; };
bool Cancel() { return _Cancel; };
void Cancel(bool value) { _Cancel = value; };
private:
Windows::Foundation::IInspectable _Item;
NotePad::TabViewItem _Tab;
bool _Cancel;
};
}
namespace winrt::NotePad::factory_implementation
{
struct TabClosingEventArgs : TabClosingEventArgsT<TabClosingEventArgs, implementation::TabClosingEventArgs>
{
};
}
| [
"huangdongdong2008@vip.qq.com"
] | huangdongdong2008@vip.qq.com |
9d61c63bf6d0741eb28dd163371411859be75d16 | c93857ce1fc4b8037b76629e3e37949b9c967ffe | /peopledetect/src/peopledetect.cpp | 6e25e286bc4ed28b784461e75548faadbf03dfc6 | [] | no_license | KUASWoodyLIN/ROS_Opencv_test | de1f8cba73b78a41911986c3337314008b0332ae | dd2bce6bbbd11d7f0a63543a91048a55e8a0413b | refs/heads/master | 2021-01-22T10:37:03.639661 | 2017-04-09T12:10:17 | 2017-04-09T12:10:17 | 82,023,419 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,916 | cpp | #include <opencv2/opencv.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <highgui.h>
#include <stdlib.h>
#include <stdio.h>
#include <opencv2\video\background_segm.hpp>
#include <Windows.h>
using namespace cv;
using namespace std;
/// Global variables
int hist = 0;
int const histMax = 10;
int thresh = 0;
int const threshMax = 5000;
int erosion_elem = 0;
int erosion_size = 0;
int dilation_elem = 0;
int dilation_size = 0;
int const max_elem = 2;
int const max_kernel_size = 21;
int MIN_NUM_OBJECTS = 1;
int MAX_NUM_OBJECTS=100;
int MIN_OBJECT_AREA = 1*1;
int MAX_OBJECT_AREA = 5000*5000;
Mat curVid; // live feed from IP Cam
Mat imgHSV;
Mat erosion_dst;
Mat dilation_dst;
Mat mask; // final filtered image
Mat test; // test for draw objects
/** Function Headers */
void setwindowSettings();
void HSV();
void Erosion( int, void* );
void Dilation( int, void* );
IplImage* GetThresholdedImage(IplImage* imgHSV);
void trackFilteredObject();
void drawObject(int x,int y,Mat &frame);
string intToString(int number);
int main(int argc, char *argv[])
{
// get cam feed and show in new window
VideoCapture cap(0);
if (!cap.isOpened()) // if not success, exit program
{
cout << "Cannot open the video file" << endl;
return -1;
}
setwindowSettings();
// background subtraction init
BackgroundSubtractorMOG2 bg = BackgroundSubtractorMOG2(hist,thresh,false);
cap.read(curVid);
Sleep(5000);
// show images in windows
while(1)
{
// show camera feed
bool bSuccess = cap.read(curVid); // read a new frame from video
if (!bSuccess) // if not success, break loop
{
cout << "Cannot read a frame from video file" << endl;
break;
}
// start morph functions then draw
HSV();
Erosion( 0, 0 );
Dilation( 0, 0 );
// background subtraction
bg(dilation_dst,mask,-1);
imshow("mask",mask);
// draw to curVid
trackFilteredObject();
imshow("test", test);
// escape program with keystroke
if (waitKey(30) == 27) //wait for 'esc' key press for 30ms. If 'esc' key is pressed, break loop
{
cout << "esc key is pressed by user" << endl;
break;
}
}
return 0;
}
void setwindowSettings()
{
namedWindow("Settings", CV_WINDOW_AUTOSIZE);
resizeWindow("Settings",500,600);
namedWindow("mask", CV_WINDOW_AUTOSIZE);
namedWindow("test", CV_WINDOW_AUTOSIZE);
// Create Erosion Trackbar
createTrackbar( "EroElem", "Settings",
&erosion_elem, max_elem,
Erosion );
createTrackbar( "EroSize", "Settings",
&erosion_size, max_kernel_size,
Erosion );
/// Create Dilation Trackbar
createTrackbar( "DialElem", "Settings",
&dilation_elem, max_elem,
Dilation );
createTrackbar( "DialSize", "Settings",
&dilation_size, max_kernel_size,
Dilation );
/*/// Create GaussianBlur Trackbars
createTrackbar( "blurType", "Settings",
&blurType, max_blurType,
Blur );*/
/// Create History Trackbar
createTrackbar( "ImgHist", "Settings",
&hist, histMax );
/// Create Threshold Trackbar
createTrackbar( "Threshold", "Settings",
&thresh, threshMax );
// Create NUM_OBJECTS Trackbar
createTrackbar("MIN_NUM_OBJECTS", "Settings",
&MIN_NUM_OBJECTS, 100);
createTrackbar("MAX_NUM_OBJECTS", "Settings",
&MAX_NUM_OBJECTS, 100);
// Create NUM_OBJECTS Trackbar
createTrackbar("MIN_OBJECT_AREA", "Settings",
&MIN_OBJECT_AREA, 5000*5000);
createTrackbar("MAX_OBJECT_AREA", "Settings",
&MAX_OBJECT_AREA, 5000*5000);
}
/** @function HSV */
void HSV()
{
//cvGetSize(curVid);
//Mat* img_HSV = cvCreateImage(cvGetSize(curVid), IPL_DEPTH_8U, 3);
cvtColor(curVid,imgHSV,CV_BGR2HSV);
//imgHSV = GetThresholdImage(img_HSV);
//imshow("HSV", imgHSV);
}
/** @function Erosion */
void Erosion( int, void* )
{
int erosion_type;
if( erosion_elem == 0 ){ erosion_type = MORPH_RECT; }
else if( erosion_elem == 1 ){ erosion_type = MORPH_CROSS; }
else if( erosion_elem == 2) { erosion_type = MORPH_ELLIPSE; }
Mat element = getStructuringElement( erosion_type,
Size( 2*erosion_size + 1, 2*erosion_size+1 ),
Point( erosion_size, erosion_size ) );
/// Apply the erosion operation
erode( imgHSV, erosion_dst, element );
}
/** @function Dilation */
void Dilation( int, void* )
{
int dilation_type;
if( dilation_elem == 0 ){ dilation_type = MORPH_RECT; }
else if( dilation_elem == 1 ){ dilation_type = MORPH_CROSS; }
else if( dilation_elem == 2) { dilation_type = MORPH_ELLIPSE; }
Mat element = getStructuringElement( dilation_type,
Size( 2*dilation_size + 1, 2*dilation_size+1 ),
Point( dilation_size, dilation_size ) );
/// Apply the dilation operation
dilate( erosion_dst, dilation_dst, element );
}
void trackFilteredObject(){
int x,y;
Mat temp;
mask.copyTo(temp);
//inRange(mask,Scalar(MIN_OBJECT_AREA),Scalar(MAX_OBJECT_AREA),temp);
curVid.copyTo(test);
//these two vectors needed for output of findContours
vector< vector<Point> > contours;
vector<Vec4i> hierarchy;
//find contours of filtered image using openCV findContours function
findContours(temp,contours,hierarchy,CV_RETR_CCOMP,CV_CHAIN_APPROX_SIMPLE );
// iterate through all the top-level contours,
// draw each connected component with its own random color
int idx = 0;
for( ; idx >= 0; idx = hierarchy[idx][0] )
{
Scalar color( rand()&0, rand()&0, rand()&255 );
drawContours( test, contours, idx, color, CV_FILLED, 8, hierarchy );
}
//use moments method to find our filtered object
double refArea = 0;
bool objectFound = false;
cout << hierarchy.size() << endl;
if (hierarchy.size() > 0) {
int numObjects = hierarchy.size();
//if number of objects greater than MAX_NUM_OBJECTS we have a noisy filter
if(numObjects<MAX_NUM_OBJECTS){
for (int index = 0; index >= 0; index = hierarchy[index][0]) {
Moments moment = moments((cv::Mat)contours[index]);
double area = moment.m00;
//if the area is less than 20 px by 20px then it is probably just noise
//if the area is the same as the 3/2 of the image size, probably just a bad filter
//this is setup to get the object with the largest area so we safe a reference area each
//iteration and compare it to the area in the next iteration. DO NOT WANT THIS!
if(area>MIN_OBJECT_AREA){
x = moment.m10/area;
y = moment.m01/area;
objectFound = true;
}else objectFound = false;
}
//let user know you found an object
if(objectFound ==true){
//draw object location on screen
drawObject(x,y,test);}
}else putText(test,"TOO MUCH NOISE! ADJUST FILTER",Point(0,50),1,2,Scalar(0,0,255),2);
}
}
void drawObject(int x,int y,Mat &frame){
circle(frame,cv::Point(x,y),10,cv::Scalar(0,0,255),3);
putText(frame,intToString(x)+ " , " + intToString(y),cv::Point(x,y+20),1,1,Scalar(0,255,0));
}
string intToString(int number){
std::stringstream ss;
ss << number;
return ss.str();
}
| [
"jj7158761@gmail.com"
] | jj7158761@gmail.com |
b3bca7cdaf50b434aaacea58fc878be90e36c6df | ec02c45b6a77c25c55d8dae787e06ab62c170fec | /sbpl-dev/src/utils/utils.cpp | 1b19daa5769d3d46dd441a9dd95591a1cee89a8d | [] | no_license | Beryl-bingqi/footstep_dynamic_planner | 5400d866a74f0ed557dadc9177f18b6ba20cf33f | 99851122d400de0e6ad73f787de0201cb991880e | refs/heads/master | 2020-07-05T05:57:57.885423 | 2013-07-01T14:29:38 | 2013-07-01T14:29:38 | 11,093,592 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 29,977 | cpp | /*
* Copyright (c) 2008, Maxim Likhachev
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the University of Pennsylvania nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <cmath>
#include <iostream>
using namespace std;
#include "../sbpl/headers.h"
#if MEM_CHECK == 1
void DisableMemCheck()
{
// Get the current state of the flag
// and store it in a temporary variable
int tmpFlag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG );
// Turn On (OR) - All freed memory is re-initialized with xDD
tmpFlag |= _CRTDBG_DELAY_FREE_MEM_DF;
// Turn Off (AND) - memory checking is disabled for future allocations
tmpFlag &= ~_CRTDBG_ALLOC_MEM_DF;
// Set the new state for the flag
_CrtSetDbgFlag( tmpFlag );
}
void EnableMemCheck()
{
// Get the current state of the flag
// and store it in a temporary variable
int tmpFlag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG );
// Turn On (OR) - All freed memory is re-initialized with xDD
tmpFlag |= _CRTDBG_DELAY_FREE_MEM_DF;
// Turn On (OR) - memory checking is enabled for future allocations
tmpFlag |= _CRTDBG_ALLOC_MEM_DF;
// Set the new state for the flag
_CrtSetDbgFlag( tmpFlag );
}
#endif
void checkmdpstate(CMDPSTATE* state)
{
#if DEBUG == 0
SBPL_ERROR("ERROR: checkMDPstate is too expensive for not in DEBUG mode\n");
throw new SBPL_Exception();
#endif
for(int aind = 0; aind < (int)state->Actions.size(); aind++)
{
for(int aind1 = 0; aind1 < (int)state->Actions.size(); aind1++)
{
if(state->Actions[aind1]->ActionID == state->Actions[aind]->ActionID &&
aind1 != aind)
{
SBPL_ERROR("ERROR in CheckMDP: multiple actions with the same ID exist\n");
throw new SBPL_Exception();
}
}
for(int sind = 0; sind < (int)state->Actions[aind]->SuccsID.size(); sind++)
{
for(int sind1 = 0; sind1 < (int)state->Actions[aind]->SuccsID.size(); sind1++)
{
if(state->Actions[aind]->SuccsID[sind] == state->Actions[aind]->SuccsID[sind1] &&
sind != sind1)
{
SBPL_ERROR("ERROR in CheckMDP: multiple outcomes with the same ID exist\n");
throw new SBPL_Exception();
}
}
}
}
}
void CheckMDP(CMDP* mdp)
{
for(int i = 0; i < (int)mdp->StateArray.size(); i++)
{
checkmdpstate(mdp->StateArray[i]);
}
}
void PrintMatrix(int** matrix, int rows, int cols, FILE* fOut)
{
for(int r = 0; r < rows; r++)
{
for(int c = 0; c < cols; c++)
{
SBPL_FPRINTF(fOut, "%d ", matrix[r][c]);
}
SBPL_FPRINTF(fOut, "\n");
}
}
//return true if there exists a path from sourcestate to targetstate and false otherwise
bool PathExists(CMDP* pMarkovChain, CMDPSTATE* sourcestate, CMDPSTATE* targetstate)
{
CMDPSTATE* state;
vector<CMDPSTATE*> WorkList;
int i;
bool *bProcessed = new bool [pMarkovChain->StateArray.size()];
bool bFound = false;
//insert the source state
WorkList.push_back(sourcestate);
while((int)WorkList.size() > 0)
{
//get the state and its info
state = WorkList[WorkList.size()-1];
WorkList.pop_back();
//Markov Chain should just contain a single policy
if((int)state->Actions.size() > 1)
{
SBPL_ERROR("ERROR in PathExists: Markov Chain is a general MDP\n");
throw new SBPL_Exception();
}
if(state == targetstate)
{
//path found
bFound = true;
break;
}
//otherwise just insert policy successors into the worklist unless it is a goal state
for(int sind = 0; (int)state->Actions.size() != 0 && sind < (int)state->Actions[0]->SuccsID.size(); sind++)
{
//get a successor
for(i = 0; i < (int)pMarkovChain->StateArray.size(); i++)
{
if(pMarkovChain->StateArray[i]->StateID == state->Actions[0]->SuccsID[sind])
break;
}
if(i == (int)pMarkovChain->StateArray.size())
{
SBPL_ERROR("ERROR in PathExists: successor is not found\n");
throw new SBPL_Exception();
}
CMDPSTATE* SuccState = pMarkovChain->StateArray[i];
//insert at the end of list if not there or processed already
if(!bProcessed[i])
{
bProcessed[i] = true;
WorkList.push_back(SuccState);
}
} //for successors
}//while WorkList is non empty
delete [] bProcessed;
return bFound;
}
int ComputeNumofStochasticActions(CMDP* pMDP)
{
int i;
int nNumofStochActions = 0;
SBPL_PRINTF("ComputeNumofStochasticActions...\n");
for(i = 0; i < (int)pMDP->StateArray.size(); i++)
{
for(int aind = 0; aind < (int)pMDP->StateArray[i]->Actions.size(); aind++)
{
if((int)pMDP->StateArray[i]->Actions[aind]->SuccsID.size() > 1)
nNumofStochActions++;
}
}
SBPL_PRINTF("done\n");
return nNumofStochActions;
}
void EvaluatePolicy(CMDP* PolicyMDP, int StartStateID, int GoalStateID,
double* PolValue, bool *bFullPolicy, double* Pcgoal, int *nMerges,
bool* bCycles)
{
int i, j, startind=-1;
double delta = INFINITECOST;
double mindelta = 0.1;
*Pcgoal = 0;
*nMerges = 0;
SBPL_PRINTF("Evaluating policy...\n");
//create and initialize values
double* vals = new double [PolicyMDP->StateArray.size()];
double* Pcvals = new double [PolicyMDP->StateArray.size()];
for(i = 0; i < (int)PolicyMDP->StateArray.size(); i++)
{
vals[i] = 0;
Pcvals[i] = 0;
//remember the start index
if(PolicyMDP->StateArray[i]->StateID == StartStateID)
{
startind = i;
Pcvals[i] = 1;
}
}
//initially assume full policy
*bFullPolicy = true;
bool bFirstIter = true;
while(delta > mindelta)
{
delta = 0;
for(i = 0; i < (int)PolicyMDP->StateArray.size(); i++)
{
//get the state
CMDPSTATE* state = PolicyMDP->StateArray[i];
//do the backup for values
if(state->StateID == GoalStateID)
{
vals[i] = 0;
}
else if((int)state->Actions.size() == 0)
{
*bFullPolicy = false;
vals[i] = UNKNOWN_COST;
*PolValue = vals[startind];
return;
}
else
{
//normal backup
CMDPACTION* action = state->Actions[0];
//do backup
double Q = 0;
for(int oind = 0; oind < (int)action->SuccsID.size(); oind++)
{
//get the state
for(j = 0; j < (int)PolicyMDP->StateArray.size(); j++)
{
if(PolicyMDP->StateArray[j]->StateID == action->SuccsID[oind])
break;
}
if(j == (int)PolicyMDP->StateArray.size())
{
SBPL_ERROR("ERROR in EvaluatePolicy: incorrect successor %d\n",
action->SuccsID[oind]);
throw new SBPL_Exception();
}
Q += action->SuccsProb[oind]*(vals[j] + action->Costs[oind]);
}
if(vals[i] > Q)
{
SBPL_ERROR("ERROR in EvaluatePolicy: val is decreasing\n");
throw new SBPL_Exception();
}
//update delta
if(delta < Q - vals[i])
delta = Q-vals[i];
//set the value
vals[i] = Q;
}
//iterate through all the predecessors and compute Pc
double Pc = 0;
//go over all predecessor states
int nMerge = 0;
for(j = 0; j < (int)PolicyMDP->StateArray.size(); j++)
{
for(int oind = 0; (int)PolicyMDP->StateArray[j]->Actions.size() > 0 &&
oind < (int)PolicyMDP->StateArray[j]->Actions[0]->SuccsID.size(); oind++)
{
if(PolicyMDP->StateArray[j]->Actions[0]->SuccsID[oind] == state->StateID)
{
//process the predecessor
double PredPc = Pcvals[j];
double OutProb = PolicyMDP->StateArray[j]->Actions[0]->SuccsProb[oind];
//accumulate into Pc
Pc = Pc + OutProb*PredPc;
nMerge++;
//check for cycles
if(bFirstIter && !(*bCycles))
{
if(PathExists(PolicyMDP, state, PolicyMDP->StateArray[j]))
*bCycles = true;
}
}
}
}
if(bFirstIter && state->StateID != GoalStateID && nMerge > 0)
*nMerges += (nMerge-1);
//assign Pc
if(state->StateID != StartStateID)
Pcvals[i] = Pc;
if(state->StateID == GoalStateID)
*Pcgoal = Pcvals[i];
} //over states
bFirstIter = false;
} //until delta small
*PolValue = vals[startind];
SBPL_PRINTF("done\n");
}
void get_bresenham_parameters(int p1x, int p1y, int p2x, int p2y, bresenham_param_t *params)
{
params->UsingYIndex = 0;
if (fabs((double)(p2y-p1y)/(double)(p2x-p1x)) > 1)
(params->UsingYIndex)++;
if (params->UsingYIndex)
{
params->Y1=p1x;
params->X1=p1y;
params->Y2=p2x;
params->X2=p2y;
}
else
{
params->X1=p1x;
params->Y1=p1y;
params->X2=p2x;
params->Y2=p2y;
}
if ((p2x - p1x) * (p2y - p1y) < 0)
{
params->Flipped = 1;
params->Y1 = -params->Y1;
params->Y2 = -params->Y2;
}
else
params->Flipped = 0;
if (params->X2 > params->X1)
params->Increment = 1;
else
params->Increment = -1;
params->DeltaX=params->X2-params->X1;
params->DeltaY=params->Y2-params->Y1;
params->IncrE=2*params->DeltaY*params->Increment;
params->IncrNE=2*(params->DeltaY-params->DeltaX)*params->Increment;
params->DTerm=(2*params->DeltaY-params->DeltaX)*params->Increment;
params->XIndex = params->X1;
params->YIndex = params->Y1;
}
void get_current_point(bresenham_param_t *params, int *x, int *y)
{
if (params->UsingYIndex)
{
*y = params->XIndex;
*x = params->YIndex;
if (params->Flipped)
*x = -*x;
}
else
{
*x = params->XIndex;
*y = params->YIndex;
if (params->Flipped)
*y = -*y;
}
}
int get_next_point(bresenham_param_t *params)
{
if (params->XIndex == params->X2)
{
return 0;
}
params->XIndex += params->Increment;
if (params->DTerm < 0 || (params->Increment < 0 && params->DTerm <= 0))
params->DTerm += params->IncrE;
else
{
params->DTerm += params->IncrNE;
params->YIndex += params->Increment;
}
return 1;
}
//converts discretized version of angle into continuous (radians)
//maps 0->0, 1->delta, 2->2*delta, ...
double DiscTheta2Cont(int nTheta, int NUMOFANGLEVALS)
{
double thetaBinSize = 2.0*PI_CONST/NUMOFANGLEVALS;
return nTheta*thetaBinSize;
}
//converts continuous (radians) version of angle into discrete
//maps 0->0, [delta/2, 3/2*delta)->1, [3/2*delta, 5/2*delta)->2,...
int ContTheta2Disc(double fTheta, int NUMOFANGLEVALS)
{
double thetaBinSize = 2.0*PI_CONST/NUMOFANGLEVALS;
return (int)(normalizeAngle(fTheta+thetaBinSize/2.0)/(2.0*PI_CONST)*(NUMOFANGLEVALS));
}
//input angle should be in radians
//counterclockwise is positive
//output is an angle in the range of from 0 to 2*PI
double normalizeAngle(double angle)
{
double retangle = angle;
//get to the range from -2PI, 2PI
if(fabs(retangle) > 2*PI_CONST)
retangle = retangle - ((int)(retangle/(2*PI_CONST)))*2*PI_CONST;
//get to the range 0, 2PI
if(retangle < 0)
retangle += 2*PI_CONST;
if(retangle < 0 || retangle > 2*PI_CONST)
{
SBPL_ERROR("ERROR: after normalization of angle=%f we get angle=%f\n", angle, retangle);
}
return retangle;
}
/*
* point - the point to test
*
* Function derived from http://ozviz.wasp.uwa.edu.au/~pbourke/geometry/insidepoly/
*/
bool IsInsideFootprint(sbpl_2Dpt_t pt, vector<sbpl_2Dpt_t>* bounding_polygon){
int counter = 0;
int i;
double xinters;
sbpl_2Dpt_t p1;
sbpl_2Dpt_t p2;
int N = bounding_polygon->size();
p1 = bounding_polygon->at(0);
for (i=1;i<=N;i++) {
p2 = bounding_polygon->at(i % N);
if (pt.y > __min(p1.y,p2.y)) {
if (pt.y <= __max(p1.y,p2.y)) {
if (pt.x <= __max(p1.x,p2.x)) {
if (p1.y != p2.y) {
xinters = (pt.y-p1.y)*(p2.x-p1.x)/(p2.y-p1.y)+p1.x;
if (p1.x == p2.x || pt.x <= xinters)
counter++;
}
}
}
}
p1 = p2;
}
if (counter % 2 == 0)
return false;
else
return true;
#if DEBUG
//SBPL_PRINTF("Returning from inside footprint: %d\n", c);
#endif
// return c;
}
double computeMinUnsignedAngleDiff(double angle1, double angle2)
{
//get the angles into 0-2*PI range
angle1 = normalizeAngle(angle1);
angle2 = normalizeAngle(angle2);
double anglediff = fabs(angle1-angle2);
//see if we can take a shorter route
if(anglediff > PI_CONST){
anglediff = fabs(anglediff - 2*PI_CONST);
}
return anglediff;
}
//computes 8-connected distances to obstacles and non-free areas in two linear passes and returns them in disttoObs_incells
//and disttoNonfree_incells arrays. The distances are in terms of the number of cells but are floats. These distances
//can then be converted into the actual distances using the actual discretization values
//areas outside of the map are considered to be obstacles
void computeDistancestoNonfreeAreas(unsigned char** Grid2D, int width_x, int height_y, unsigned char obsthresh, float** disttoObs_incells,
float** disttoNonfree_incells)
{
int x,y,nbrx,nbry;
float mindisttoObs, mindisttoNonfree;
float maxDist = (float)(__min(width_x, height_y));
float disttoObs, disttoNonfree;
int dir;
const int NUMOF2DQUASIDIRS = 4;
// for quasi-Euclidean distance transform
// going left-to-right, top-to-bottom
int dxdownlefttoright_[NUMOF2DQUASIDIRS];
int dydownlefttoright_[NUMOF2DQUASIDIRS];
int dxdownrighttoleft_[NUMOF2DQUASIDIRS];
int dydownrighttoleft_[NUMOF2DQUASIDIRS];
// going right-to-left, bottom-to-top
int dxuprighttoleft_[NUMOF2DQUASIDIRS];
int dyuprighttoleft_[NUMOF2DQUASIDIRS];
int dxuplefttoright_[NUMOF2DQUASIDIRS];
int dyuplefttoright_[NUMOF2DQUASIDIRS];
// distances to the above nbrs
float distdownlefttoright_[NUMOF2DQUASIDIRS];
float distdownrighttoleft_[NUMOF2DQUASIDIRS];
float distuprighttoleft_[NUMOF2DQUASIDIRS];
float distuplefttoright_[NUMOF2DQUASIDIRS];
// and for distance transform:
// increasing x (outer)
// increasing y (inner)
// [2]
// [1][s]
// [0][3]
dxdownlefttoright_[0] = -1; dydownlefttoright_[0] = -1;
dxdownlefttoright_[1] = -1; dydownlefttoright_[1] = 0;
dxdownlefttoright_[2] = -1; dydownlefttoright_[2] = 1;
dxdownlefttoright_[3] = 0; dydownlefttoright_[3] = -1;
// increasing x (outer)
// decreasing y (inner)
// [2][3]
// [1][s]
// [0]
dxdownrighttoleft_[0] = -1; dydownrighttoleft_[0] = -1;
dxdownrighttoleft_[1] = -1; dydownrighttoleft_[1] = 0;
dxdownrighttoleft_[2] = -1; dydownrighttoleft_[2] = 1;
dxdownrighttoleft_[3] = 0; dydownrighttoleft_[3] = 1;
// decreasing x (outer)
// decreasing y (inner)
// [3][2]
// [s][1]
// [0]
dxuprighttoleft_[0] = 1; dyuprighttoleft_[0] = -1;
dxuprighttoleft_[1] = 1; dyuprighttoleft_[1] = 0;
dxuprighttoleft_[2] = 1; dyuprighttoleft_[2] = 1;
dxuprighttoleft_[3] = 0; dyuprighttoleft_[3] = 1;
// decreasing x (outer)
// increasing y (inner)
// [2]
// [s][1]
// [3][0]
dxuplefttoright_[0] = 1; dyuplefttoright_[0] = -1;
dxuplefttoright_[1] = 1; dyuplefttoright_[1] = 0;
dxuplefttoright_[2] = 1; dyuplefttoright_[2] = 1;
dxuplefttoright_[3] = 0; dyuplefttoright_[3] = -1;
// insert the corresponding distances
distdownlefttoright_[0] = (float)1.414;
distdownlefttoright_[1] = (float)1.0;
distdownlefttoright_[2] = (float)1.414;
distdownlefttoright_[3] = (float)1.0;
distdownrighttoleft_[0] = (float)1.414;
distdownrighttoleft_[1] = (float)1.0;
distdownrighttoleft_[2] = (float)1.414;
distdownrighttoleft_[3] = (float)1.0;
distuprighttoleft_[0] = (float)1.414;
distuprighttoleft_[1] = (float)1.0;
distuprighttoleft_[2] = (float)1.414;
distuprighttoleft_[3] = (float)1.0;
distuplefttoright_[0] = (float)1.414;
distuplefttoright_[1] = (float)1.0;
distuplefttoright_[2] = (float)1.414;
distuplefttoright_[3] = (float)1.0;
// step through the map from top to bottom,
// alternating left-to-right then right-to-left
// This order maintains the invariant that the min distance for each
// cell to all previously-visited obstacles is accurate
for(x = 0; x < width_x; x++)
{
// move from left to right
if (x%2 == 0) {
for(y = 0; y < height_y; y++)
{
mindisttoObs = maxDist; // initialize to max distance
mindisttoNonfree = maxDist;
// if cell is an obstacle, set disttoObs to 0 and continue
if (Grid2D[x][y] >= obsthresh){
disttoObs_incells[x][y] = 0;
disttoNonfree_incells[x][y] = 0;
continue;
}
if(Grid2D[x][y] > 0){
mindisttoNonfree = 0;
}
//iterate over predecessors
for(dir = 0; dir < NUMOF2DQUASIDIRS; dir++){
nbrx = x + dxdownlefttoright_[dir];
nbry = y + dydownlefttoright_[dir];
//make sure it is inside the map and has no obstacle
// compute min cost to an obstacle for each cell, using
// *just* the cells already computed this pass for checking distance
if(nbrx < 0 || nbrx >= width_x || nbry < 0 || nbry >= height_y){
disttoObs = distdownlefttoright_[dir];
disttoNonfree = disttoObs;
}
else
{
disttoObs = distdownlefttoright_[dir] + disttoObs_incells[nbrx][nbry];
disttoNonfree = distdownlefttoright_[dir] + disttoNonfree_incells[nbrx][nbry];
}
if (disttoObs < mindisttoObs)
mindisttoObs = disttoObs;
if (disttoNonfree < mindisttoNonfree)
mindisttoNonfree = disttoNonfree;
}//over preds
disttoObs_incells[x][y] = mindisttoObs;
disttoNonfree_incells[x][y] = mindisttoNonfree;
}
} else {
// move from right to left
for(y = height_y-1; y >= 0; y--)
{
mindisttoObs = maxDist; // initialize to max distance
mindisttoNonfree = maxDist;
// if cell is an obstacle, set disttoObs to 0 and continue
if (Grid2D[x][y] >= obsthresh){
disttoObs_incells[x][y] = 0;
disttoNonfree_incells[x][y] = 0;
continue;
}
if(Grid2D[x][y] > 0){
mindisttoNonfree = 0;
}
//iterate over predecessors
for(dir = 0; dir < NUMOF2DQUASIDIRS; dir++)
{
nbrx = x + dxdownrighttoleft_[dir];
nbry = y + dydownrighttoleft_[dir];
//make sure it is inside the map and has no obstacle
// compute min cost to an obstacle for each cell, using
// *just* the cells already computed this pass for checking distance
if(nbrx < 0 || nbrx >= width_x || nbry < 0 || nbry >= height_y){
disttoObs = distdownrighttoleft_[dir];
disttoNonfree = disttoObs;
} else {
disttoObs = distdownrighttoleft_[dir] + disttoObs_incells[nbrx][nbry];
disttoNonfree = distdownrighttoleft_[dir] + disttoNonfree_incells[nbrx][nbry];
}
if (disttoObs < mindisttoObs)
mindisttoObs = disttoObs;
if (disttoNonfree < mindisttoNonfree)
mindisttoNonfree = disttoNonfree;
}
disttoObs_incells[x][y] = mindisttoObs;
disttoNonfree_incells[x][y] = mindisttoNonfree;
}
//SBPL_PRINTF("x=%d\n", x);
}
}
// step through the map from bottom to top
for(x = width_x-1; x >= 0; x--)
{
// move from right to left
if (x%2 == 0) {
for(y = height_y-1; y >= 0; y--)
{
// initialize to current distance
mindisttoObs = disttoObs_incells[x][y];
mindisttoNonfree = disttoNonfree_incells[x][y];
//iterate over predecessors
for(dir = 0; dir < NUMOF2DQUASIDIRS; dir++)
{
nbrx = x + dxuprighttoleft_[dir];
nbry = y + dyuprighttoleft_[dir];
//make sure it is inside the map and has no obstacle
// compute min cost to an obstacle for each cell, using
// *just* the cells already computed this pass for checking distance
if(nbrx < 0 || nbrx >= width_x || nbry < 0 || nbry >= height_y){
disttoObs = distuprighttoleft_[dir];
disttoNonfree = disttoObs;
} else {
disttoObs = distuprighttoleft_[dir] + disttoObs_incells[nbrx][nbry];
disttoNonfree = distuprighttoleft_[dir] + disttoNonfree_incells[nbrx][nbry];
}
if (disttoObs < mindisttoObs)
mindisttoObs = disttoObs;
if (disttoNonfree < mindisttoNonfree)
mindisttoNonfree = disttoNonfree;
}//over preds
disttoObs_incells[x][y] = mindisttoObs;
disttoNonfree_incells[x][y] = mindisttoNonfree;
}//for y
} else {
// move from left to right
for(y = 0; y< height_y; y++)
{
// initialize to current distance
mindisttoObs = disttoObs_incells[x][y];
mindisttoNonfree = disttoNonfree_incells[x][y];
//iterate over predecessors
for(dir = 0; dir < NUMOF2DQUASIDIRS; dir++)
{
nbrx = x + dxuplefttoright_[dir];
nbry = y + dyuplefttoright_[dir];
//make sure it is inside the map and has no obstacle
// compute min cost to an obstacle for each cell, using
// *just* the cells already computed this pass for checking distance
if(nbrx < 0 || nbrx >= width_x || nbry < 0 || nbry >= height_y){
disttoObs = distuplefttoright_[dir];
disttoNonfree = disttoObs;
} else {
disttoObs = distuplefttoright_[dir] + disttoObs_incells[nbrx][nbry];
disttoNonfree = distuplefttoright_[dir] + disttoNonfree_incells[nbrx][nbry];
}
if (disttoObs < mindisttoObs)
mindisttoObs = disttoObs;
if (disttoNonfree < mindisttoNonfree)
mindisttoNonfree = disttoNonfree;
}
disttoObs_incells[x][y] = mindisttoObs;
disttoNonfree_incells[x][y] = mindisttoNonfree;
}//over y
}//direction
}//over x
}
void get_2d_motion_cells(vector<sbpl_2Dpt_t> polygon, vector<sbpl_xy_theta_pt_t> poses, vector<sbpl_2Dcell_t>* cells,
double res)
{
// can't find any motion cells if there are no poses
if (poses.empty()) {
return;
}
//get first footprint set
set<sbpl_2Dcell_t> first_cell_set;
get_2d_footprint_cells(polygon, &first_cell_set, poses[0], res);
//duplicate first footprint set into motion set
set<sbpl_2Dcell_t> cell_set = first_cell_set;
//call get footprint on the rest of the points
for (unsigned int i = 1; i < poses.size(); i++) {
get_2d_footprint_cells(polygon, &cell_set, poses[i], res);
}
//convert the motion set to a vector but don't include the cells in the first footprint set
cells->reserve(cell_set.size() - first_cell_set.size());
for (set<sbpl_2Dcell_t>::iterator it = cell_set.begin(); it != cell_set.end(); it++) {
if (first_cell_set.find(*it) == first_cell_set.end()) {
cells->push_back(*it);
}
}
}
//This function is inefficient and should be avoided if possible (you should use overloaded functions that uses a set for the cells)!
void get_2d_footprint_cells(vector<sbpl_2Dpt_t> polygon, vector<sbpl_2Dcell_t>* cells, sbpl_xy_theta_pt_t pose,
double res)
{
set<sbpl_2Dcell_t> cell_set;
for (unsigned int i = 0; i < cells->size(); i++)
cell_set.insert(cells->at(i));
get_2d_footprint_cells(polygon, &cell_set, pose, res);
cells->clear();
cells->reserve(cell_set.size());
//for(set<sbpl_2Dcell_t>::iterator it; it==cell_set.begin(); it++)
// cells->push_back(*it);
for (set<sbpl_2Dcell_t>::iterator it = cell_set.begin(); it != cell_set.end(); it++) {
cells->push_back(*it);
}
}
void get_2d_footprint_cells(vector<sbpl_2Dpt_t> polygon, set<sbpl_2Dcell_t>* cells, sbpl_xy_theta_pt_t pose, double res)
{
//special case for point robot
if (polygon.size() <= 1) {
sbpl_2Dcell_t cell;
cell.x = CONTXY2DISC(pose.x, res);
cell.y = CONTXY2DISC(pose.y, res);
cells->insert(cell);
return;
}
//run bressenham line algorithm around the polygon (add them to the cells set)
//while doing that find the min and max (x,y) and the average x and y
double cth = cos(pose.theta);
double sth = sin(pose.theta);
vector<pair<int, int> > disc_polygon;
disc_polygon.reserve(polygon.size() + 1);
int minx = INFINITECOST;
int maxx = -INFINITECOST;
int miny = INFINITECOST;
int maxy = -INFINITECOST;
//find the bounding box of the polygon
for (unsigned int i = 0; i < polygon.size(); i++) {
pair<int, int> p;
// p.first = CONTXY2DISC(cth*polygon[i].x - sth*polygon[i].y + pose.x, res);
double cx = (cth*polygon[i].x - sth*polygon[i].y + pose.x);
double cy = (sth*polygon[i].x + cth*polygon[i].y + pose.y);
p.first = (int)(cx > 0 ? cx / res + 0.5 : cx / res - 0.5); //(int)(cx / res + 0.5 * sign(c);
// p.second = CONTXY2DISC(sth*polygon[i].x + cth*polygon[i].y + pose.y, res);
p.second = (int)(cy > 0 ? cy / res + 0.5 : cy / res - 0.5);//(int)(cy / res + 0.5);
disc_polygon.push_back(p);
if (p.first < minx) minx = p.first;
if (p.first > maxx) maxx = p.first;
if (p.second < miny) miny = p.second;
if (p.second > maxy) maxy = p.second;
}
disc_polygon.push_back(disc_polygon.front());
//make a grid big enough for the footprint
int sizex = (maxx - minx + 1) + 2;
int sizey = (maxy - miny + 1) + 2;
int** grid = new int*[sizex];
for (int i = 0; i < sizex; i++) {
grid[i] = new int[sizey];
for (int j = 0; j < sizey; j++)
grid[i][j] = 0;
}
//plot line points on the grid
for (unsigned int i = 1; i < disc_polygon.size(); i++) {
int x0 = disc_polygon[i - 1].first - minx + 1;
int y0 = disc_polygon[i - 1].second - miny + 1;
int x1 = disc_polygon[i].first - minx + 1;
int y1 = disc_polygon[i].second - miny + 1;
//bressenham (add the line cells to the set and to a vector)
bool steep = abs(y1 - y0) > abs(x1 - x0);
if (steep) {
int temp = x0;
x0 = y0;
y0 = temp;
temp = x1;
x1 = y1;
y1 = temp;
}
if (x0 > x1) {
int temp = x0;
x0 = x1;
x1 = temp;
temp = y0;
y0 = y1;
y1 = temp;
}
int deltax = x1 - x0;
int deltay = abs(y1 - y0);
int error = deltax / 2;
int ystep = (y0 < y1 ? 1 : -1);
int y = y0;
for (int x = x0; x <= x1; x++) {
if (steep) {
grid[y][x] = 1;
cells->insert(sbpl_2Dcell_t(y - 1 + minx, x - 1 + miny));
}
else {
grid[x][y] = 1;
cells->insert(sbpl_2Dcell_t(x - 1 + minx, y - 1 + miny));
}
int last_error = error;
error -= deltay;
if (error < 0 && x != x1) {
//make sure we can't have a diagonal line (the 8-connected bfs will leak through)
int tempy = y;
int tempx = x;
if (last_error < -error)
tempy += ystep;
else
tempx += 1;
if (steep) {
grid[tempy][tempx] = 1;
cells->insert(sbpl_2Dcell_t(tempy - 1 + minx, tempx - 1 + miny));
}
else {
grid[tempx][tempy] = 1;
cells->insert(sbpl_2Dcell_t(tempx - 1 + minx, tempy - 1 + miny));
}
y += ystep;
error += deltax;
}
}
}
//run a 2d bfs from the average (x,y)
sbpl_bfs_2d bfs(sizex, sizey, 1);
bfs.compute_distance_from_point(grid, 0, 0);
// for (int i = 0; i < sizex; i++) {
// for (int j = 0; j < sizey; j++) {
// printf("%d ", grid[i][j] != 0);
// }
// printf("\n");
// }
printf("\n");
for (int i = 0; i < sizex; i++)
delete[] grid[i];
delete[] grid;
//add all cells expanded to the cells set
for (int i = 1; i < sizex - 1; i++) {
for (int j = 1; j < sizey - 1; j++) {
if (bfs.get_distance(i, j) < 0) cells->insert(sbpl_2Dcell_t(i - 1 + minx, j - 1 + miny));
// printf("%d ", bfs.get_distance(i, j) < 0);
}
// printf("\n");
}
// printf("\n");
}
void writePlannerStats(vector<PlannerStats> s, FILE* fout){
fprintf(fout,"%%eps time expands cost\n");
for(unsigned int i=0; i<s.size(); i++){
fprintf(fout,"%f %f %d %d\n",s[i].eps,s[i].time,s[i].expands,s[i].cost);
}
}
| [
"icy397@hotmail.com"
] | icy397@hotmail.com |
47a0ba9f71ffdbb44beb342bf586a5387d5929e3 | 1b7db5fe080a8e878323507f801de0771a1fd04a | /784. Letter Case Permutation.cpp | cbf8de6a8a705bd0894465af939cd96db88f87db | [] | no_license | cybercoderbot/lc | 8a4dc647b310d128559d4bd024f7056b690d1f31 | 1e22dbb81e5e1f61eb4e4a5068e664c50f6ddaa7 | refs/heads/master | 2022-08-29T00:18:45.667808 | 2018-06-05T22:26:10 | 2018-06-05T22:26:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 907 | cpp | /*784. Letter Case Permutation
Given a string s, we can transform every letter individually to be lowercase or uppercase to
create another string. Return a list of all possible strings we could create.
Examples:
Input: s = "a1b2"
Output: ["a1b2", "a1B2", "A1b2", "A1B2"]
Input: s = "3z4"
Output: ["3z4", "3Z4"]
Input: s = "12345"
Output: ["12345"]
*/
class Solution {
public:
vector<string> letterCasePermutation(string s) {
vector<string> res;
dfs(s, res, 0);
return res;
}
void dfs(string& s, vector<string>& res, int i){
if(i == s.size()) {
res.push_back(s);
return;
}
if(islower(s[i])){
dfs(s, res, i+1);
s[i] = toupper(s[i]);
}else if(isupper(s[i])){
dfs(s, res, i+1);
s[i] = tolower(s[i]);
}
dfs(s, res, i+1);
}
}; | [
"noreply@github.com"
] | noreply@github.com |
708f51f4d7e4ae35b81108f61c8d7eeebd86bbde | b012b15ec5edf8a52ecf3d2f390adc99633dfb82 | /releases/moos-ivp-13.5/ivp/src/uSimCurrent/USC_Info.cpp | 771be07a4d06c6381e50db04c1b84e362479c19e | [] | no_license | crosslore/moos-ivp-aro | cbe697ba3a842961d08b0664f39511720102342b | cf2f1abe0e27ccedd0bbc66e718be950add71d9b | refs/heads/master | 2022-12-06T08:14:18.641803 | 2020-08-18T06:39:14 | 2020-08-18T06:39:14 | 263,586,714 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,777 | cpp | /*****************************************************************/
/* NAME: Michael Benjamin, Henrik Schmidt, and John Leonard */
/* ORGN: Dept of Mechanical Eng / CSAIL, MIT Cambridge MA */
/* FILE: USC_Info.cpp */
/* DATE: Dec 24th 2011 */
/* */
/* This program is free software; you can redistribute it and/or */
/* modify it under the terms of the GNU General Public License */
/* as published by the Free Software Foundation; either version */
/* 2 of the License, or (at your option) any later version. */
/* */
/* This program is distributed in the hope that it will be */
/* useful, but WITHOUT ANY WARRANTY; without even the implied */
/* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR */
/* PURPOSE. See the GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public */
/* License along with this program; if not, write to the Free */
/* Software Foundation, Inc., 59 Temple Place - Suite 330, */
/* Boston, MA 02111-1307, USA. */
/*****************************************************************/
#include <cstdlib>
#include <iostream>
#include "USC_Info.h"
#include "ColorParse.h"
#include "ReleaseInfo.h"
using namespace std;
//----------------------------------------------------------------
// Procedure: showSynopsis
void showSynopsis()
{
blk("SYNOPSIS: ");
blk("------------------------------------ ");
blk(" The uSimCurrent application is a simple simulator of water ");
blk(" current. Based on local current information from a given file,");
blk(" it repeately reads the vehicle's present position and ");
blk(" publishes a drift vector, presumably consumed by uSimMarine. ");
}
//----------------------------------------------------------------
// Procedure: showHelpAndExit
void showHelpAndExit()
{
blk(" ");
blu("=============================================================== ");
blu("Usage: uSimCurrent file.moos [OPTIONS] ");
blu("=============================================================== ");
blk(" ");
showSynopsis();
blk(" ");
blk("Options: ");
mag(" --alias","=<ProcessName> ");
blk(" Launch uSimCurrent with the given process name rather ");
blk(" than uSimCurrent. ");
mag(" --example, -e ");
blk(" Display example MOOS configuration block. ");
mag(" --help, -h ");
blk(" Display this help message. ");
mag(" --interface, -i ");
blk(" Display MOOS publications and subscriptions. ");
mag(" --version,-v ");
blk(" Display the release version of uSimCurrent. ");
blk(" ");
blk("Note: If argv[2] does not otherwise match a known option, ");
blk(" then it will be interpreted as a run alias. This is ");
blk(" to support pAntler launching conventions. ");
blk(" ");
exit(0);
}
//----------------------------------------------------------------
// Procedure: showExampleConfigAndExit
void showExampleConfigAndExit()
{
blk(" ");
blu("=============================================================== ");
blu("uSimCurrent Example MOOS Configuration ");
blu("=============================================================== ");
blk(" ");
blk("ProcessConfig = uSimCurrent ");
blk("{ ");
blk(" AppTick = 4 ");
blk(" CommsTick = 4 ");
blk(" ");
blk(" CURRENT_FIELD = bravo.cfd ");
blk("} ");
blk(" ");
exit(0);
}
//----------------------------------------------------------------
// Procedure: showInterfaceAndExit
void showInterfaceAndExit()
{
blk(" ");
blu("=============================================================== ");
blu("uSimCurrent INTERFACE ");
blu("=============================================================== ");
blk(" ");
showSynopsis();
blk(" ");
blk("SUBSCRIPTIONS: ");
blk("------------------------------------ ");
blk(" NAV_X = 123.4 ");
blk(" NAV_Y = -987.6 ");
blk(" ");
blk("PUBLICATIONS: ");
blk("------------------------------------ ");
blk(" USC_CFIELD_SUMMARY = field_name=alpha, radius=15, elements=32 ");
blk(" USM_FORCE_VECTOR = 287.42,0.24 ");
blk(" VIEW_VECTOR = xpos=8,ypos=40,mag=2.4,ang=70,label=ak_31");
blk(" ");
exit(0);
}
//----------------------------------------------------------------
// Procedure: showReleaseInfoAndExit
void showReleaseInfoAndExit()
{
showReleaseInfo("uSimCurrent", "gpl");
exit(0);
}
| [
"zouxueson@hotmail.com"
] | zouxueson@hotmail.com |
6f5d74acfa1677d30edc6fba0a756f91704eb7a7 | bc9abf538f5d4093324b2f055f0b090fe4b03247 | /c_cpp/etc/mVicuna/src/xny/file_manip.hpp | 6ad90e30d7c3ec0d45d0a1af19465fde2f9771a8 | [] | no_license | galaxysd/GalaxyCodeBases | 3c8900d0c2ca0ed73e9cf4c30630aca4da6cc971 | 58946261bf72afd6a7287e781a2176cdfaddf50e | refs/heads/master | 2023-09-04T04:59:35.348199 | 2023-08-25T01:04:02 | 2023-08-25T01:04:02 | 33,782,566 | 7 | 6 | null | 2020-09-04T06:06:49 | 2015-04-11T16:12:14 | C | UTF-8 | C++ | false | false | 3,914 | hpp | //============================================================================
// Project : XNY
// Name : file_manip.hpp
// Author : Xiao Yang
// Created on : Aug 22, 2011
// Version :
// Copyright :
// Description :
//============================================================================
#ifndef FILE_MANIP_HPP_
#define FILE_MANIP_HPP_
#include <iostream>
#include <string>
#include <dirent.h>
#include <fstream>
namespace xny{
template <typename Output> bool dir_list(const std::string& name, Output out) {
DIR* dir = opendir(name.c_str());
if (dir == 0) return false;
dirent* entry = readdir(dir);
while (entry != 0) {
*(out++) = entry->d_name;
entry = readdir(dir);
}
closedir(dir);
return true;
} // dir_list
/*
* find the last/first [delim] in [str] if [dir] is set to be true/false
*/
inline std::string get_suffix (const std::string& str, bool last,
const std::string& delim) {
std::string suf = str;
int pos = suf.find_last_of(delim);
if (!last) pos = suf.find_first_of (delim);
if (pos != (int) std::string::npos)
return suf.substr(pos + 1, (int) suf.length() - pos);
else return "";
}
/*
* find the first/last [delim] in [str] if [dir] is set to be true/false
*/
inline std::string get_prefix (const std::string& str, bool first,
const std::string& delim) {
std::string prfx = str;
int pos = prfx.find_last_of(delim);
if (first) pos = prfx.find_first_of(delim);
if (pos!= (int) std::string::npos)
return prfx.substr(0, pos);
else return "";
}
template<typename fs>
void openfile (fs& outfile, const std::string& fileName,
const std::ios_base::openmode& mode = std::ios::out){
if (!outfile.is_open()) {
outfile.open(fileName.c_str(), mode);
//outfile.open(fileName.c_str(), std::fstream::app);
if (! outfile.good() ){
std::cout << "[WARNING] opening file: " << fileName << " failed!\n";
}
}
}
template<typename fs>
void closefile(fs& outfile){
if (outfile.good()) outfile.close();
}
inline void deletefile (const std::string& fname) {
if ( std::remove(fname.c_str()) != 0 ) {
std::cout << "\tcannot remove file " << fname << "\n";
} else {
std::cout << "\tdelete: " << fname << "\n";
}
}
inline void append2file (const std::string& ofname,
const std::vector<std::string>& ifnames) {
std::ofstream outfile(ofname.c_str(), std::ios::app) ;
if (!outfile.is_open()) {
std::cout << "could not open file " << ofname << " to append\n";
}
for (auto& f: ifnames) {
std::cout << "\tappend: " << f << " to " << ofname << "\n";
std::string line;
std::ifstream infile(f.c_str());
if (infile) {
while (infile.good()) {
std::getline (infile, line);
if (!line.empty()) outfile << line << std::endl;
}
infile.close();
} else std::cout << "Can't open file " << f << " !\n";
}
outfile.close();
}
/*
inline std::string get_suf_filename (const std::string& filePath) {
std::string suf = filePath;
int dotPos = suf.find_last_of(".");
if (dotPos != (int) std::string::npos)
return suf.substr(dotPos + 1, (int) suf.length() - dotPos);
return std::string ("");
}
inline std::string get_pref_filename (const std::string& filePath) {
std::string prfx = filePath;
int dotPos = prfx.find_last_of(".");
if (dotPos!= (int) std::string::npos) {
int slashPos = prfx.find_last_of("/");
if (slashPos != (int) std::string::npos){
prfx = prfx.substr(slashPos, dotPos-slashPos);
}
else prfx = prfx.substr(0, dotPos);
}
return prfx;
}
inline std::string get_filename_frompath (const std::string& filePath){
std::string suf = filePath;
int slashPos = filePath.find_last_of("/");
if (slashPos != (int) std::string::npos){
return suf.substr(slashPos + 1, (int) suf.length() - slashPos);
}
return filePath;
}
*/
}
#endif /* FILE_MANIP_HPP_ */
| [
"sye737@gmail.com"
] | sye737@gmail.com |
5d73eae99d9db74b00514570bdfc48d211481c12 | dde7366c4d3dfde911b127d37b8e505e98b8a320 | /Sorting and Searching/subarray_sum_1.cpp | e502c964435dee1ae0b9c94126a30b9227369988 | [
"Apache-2.0"
] | permissive | suvidsahay/CSES-Problem-Set | 38f015a7e28156c5cbcfa33289be9dcc59dc65b7 | 6c426ebb6f974f6c6be6e52041ee2df5fe64a9d8 | refs/heads/master | 2022-12-27T09:29:38.515501 | 2020-10-13T08:34:41 | 2020-10-13T08:34:41 | 300,574,931 | 0 | 10 | Apache-2.0 | 2020-10-13T08:34:42 | 2020-10-02T10:09:16 | C++ | UTF-8 | C++ | false | false | 735 | cpp | #include <bits/stdc++.h>
#define int long long
#define MOD 1000000007
using namespace std;
void solve() {
int n, x;
cin >> n >> x;
int a[n];
for(int i = 0; i < n; i++) {
cin >> a[i];
}
vector<int> pre;
pre.push_back(0);
for(int i = 0; i < n; i++) {
pre.push_back(pre[i] + a[i]);
}
int l = 0, h = 0;
int count = 0;
while(h <= n) {
if(pre[h] - pre[l] < x) {
h++;
}
else if(pre[h] - pre[l] > x) {
l++;
}
else {
count++;
l++; h++;
}
}
cout << count << endl;
}
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
solve();
return 0;
} | [
"sahay.suvid61@gmail.com"
] | sahay.suvid61@gmail.com |
e9fd0167464434ccb613cc0ad38857a0426c87d2 | e74855990d076fdc332c8ee9f25fb9763ab78e4b | /Spectra/Quaternion.cpp | d811ab2eec1d909bb6aa0cc3ce51aafb02f49820 | [] | no_license | vcmiller/Spectra | 78d2d383ceaeff71eb824be84a0bb9d7b0508807 | 9f67d09802303a32647139781b2c06b7bb5a5289 | refs/heads/master | 2021-01-24T09:46:04.068153 | 2018-01-24T19:48:18 | 2018-01-24T19:48:18 | 69,525,205 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,495 | cpp | #include "Quaternion.h"
#include "Log.h"
#include "Math.h"
#include "Time.h"
#include "FMath.h"
namespace spectra {
Quaternion::Quaternion(float w, float x, float y, float z) {
quat = glm::quat(w, x, y, z);
}
Quaternion::Quaternion() {
quat = glm::quat();
}
Quaternion::Quaternion(const Quaternion &q) {
quat = q.quat;
}
void Quaternion::operator=(const Quaternion &q) {
quat = q.quat;
}
Quaternion Quaternion::inverse() const {
Quaternion result;
result.quat = glm::inverse(quat);
return result;
}
Quaternion Quaternion::normalized() const {
Quaternion result;
result.quat = glm::normalize(quat);
return result;
}
Quaternion Quaternion::operator*(const Quaternion &rhs) const {
Quaternion result;
result.quat = quat * rhs.quat;
return result;
}
Vector3 Quaternion::operator*(const Vector3 &rhs) const {
glm::vec3 result = quat * glm::vec3(rhs.x, rhs.y, rhs.z);
return Vector3(result.x, result.y, result.z);
}
void Quaternion::operator *= (const Quaternion &rhs) {
quat *= rhs.quat;
}
bool Quaternion::operator==(const Quaternion &rhs) const {
return quat == rhs.quat;
}
bool Quaternion::operator!=(const Quaternion &rhs) const {
return quat != rhs.quat;
}
float Quaternion::angle(const Quaternion &q1, const Quaternion &q2) {
float f = FMath::acos((q2.quat * glm::inverse(q1.quat)).w) * 2;
if (f > FMath::halfCircle) {
f -= FMath::fullCircle;
f = FMath::abs(f);
}
return f;
}
float Quaternion::dot(const Quaternion &q1, const Quaternion &q2) {
return glm::dot(q1.quat, q2.quat);
}
Quaternion Quaternion::angleAxis(float angle, const Vector3 &axis) {
Quaternion result;
result.quat = glm::angleAxis(angle, glm::vec3(axis.x, axis.y, axis.z));
return result;
}
Quaternion Quaternion::euler(const Vector3 &euler) {
Quaternion result;
result.quat = glm::rotate(result.quat, euler.y, glm::vec3(0, 1, 0));
result.quat = glm::rotate(result.quat, euler.x, glm::vec3(1, 0, 0));
result.quat = glm::rotate(result.quat, euler.z, glm::vec3(0, 0, 1));
return result;
}
Quaternion Quaternion::lerp(const Quaternion &a, const Quaternion &b, float f) {
Quaternion result;
result.quat = glm::lerp(a.quat, b.quat, f);
return result;
}
Quaternion Quaternion::slerp(const Quaternion &a, const Quaternion &b, float f) {
Quaternion result;
result.quat = glm::slerp(a.quat, b.quat, f);
return result;
}
Quaternion Quaternion::rotateTowards(const Quaternion &a, const Quaternion &b, float maxDelta) {
float angle = Quaternion::angle(a, b);
float slerpAmount = 1.0f;
if (angle > maxDelta) {
slerpAmount = maxDelta / angle;
}
return slerp(a, b, slerpAmount);
}
Quaternion Quaternion::fromToRotation(const Vector3 & v1, const Vector3 & v2) {
Vector3 v1c = v1.normalized();
Vector3 v2c = v2.normalized();
Vector3 axis = Vector3::cross(v1c, v2c).normalized();
float angle = Vector3::angle(v1c, v2c);
return angleAxis(angle, axis);
}
Quaternion Quaternion::lookRotation(const Vector3 & direction, const Vector3 & up) {
Vector3 right = Vector3::cross(direction, up).normalized();
Vector3 trueUp = Vector3::cross(right, direction).normalized();
Vector3 forward = direction.normalized();
Quaternion ret;
ret.w = FMath::sqrt(1.0f + right.x + up.y + forward.z) * 0.5f;
float recip = 1.0f / (4.0f * ret.w);
ret.x = (forward.y - trueUp.z) * recip;
ret.y = (right.z - forward.x) * recip;
ret.z = (trueUp.x - right.y) * recip;
return ret;
}
} | [
"vmiller0725@gmail.com"
] | vmiller0725@gmail.com |
d640a2c46b821edee2546ac4b2e33ade29c380de | f58a2eda38471d3d1a6b99338f6f2bf9119d7a15 | /Basic_problems/small_string_inside_a_bigger_string.cpp | cbf53cb039c848734674f7a273e35783c0d85a7a | [] | no_license | MG11/Coding | 8eb2346939bd06f88a6fc9467703d791c4558589 | fb76f6f836f818dce17fdb9b98eb47f945a8cf9c | refs/heads/master | 2021-01-10T16:58:15.754354 | 2016-02-07T04:13:25 | 2016-02-07T04:13:25 | 48,707,905 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 669 | cpp | /*Write a program to find a small string inside a bigger string. If found, return the starting position.*/
#include <iostream>
#include <cstring>
using namespace std;
int main(){
char a[100],b[100],i=0;
a[i] = cin.get();
while(a[i] != '\n'){
a[++i] = cin.get();
}
a[i] = '\0';
cout<<"Enter the small string";
cin>>b;
int x = strlen(b);
int m=0,c=0;
for(int j=0;j<i;j++){
if(a[j] == b[m]){
m++;
}else{
m=0;
}
if(m == x){
cout<<"String found";
return 0;
}
}
cout<<"String not found";
}
| [
"meghagarg1565@gmail.com"
] | meghagarg1565@gmail.com |
fd26f8ee2b28cdcd352a5def1106bfb5ea01cb98 | cb9529ef995a7f4cfa992a4eadd1fba6877970a7 | /Final Code/Lab04/smallSpider.h | 1036cc9493420887ece2045d91c52dfa49e7d21f | [] | no_license | EllenWhelan/CSU44052-Computer-Graphics | f438e5383f8d8f415a9f71f7cdf14ba0367f65cc | 5bd531f116e31f686c96426381845d26f2b14257 | refs/heads/main | 2023-03-07T03:12:33.941399 | 2021-02-24T21:33:36 | 2021-02-24T21:33:36 | 305,643,656 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,664 | h | #pragma region INCLUDES
// Windows includes (For Time, IO, etc.)
#include <windows.h>
#include <mmsystem.h>
#include <iostream>
#include <string>
#include <stdio.h>
#include <math.h>
#include <vector> // STL dynamic memory.
// OpenGL includes
#include <GL/glew.h>
#include <GL/freeglut.h>
// Assimp includes
#include <assimp/cimport.h> // scene importer
#include <assimp/scene.h> // collects data
#include <assimp/postprocess.h> // various extra operations
// Project includes
#include "maths_funcs.h"
#include "Mesh.h"
#include "Shader.h"
#pragma endregion INCLUDES
#pragma once
class smallSpider
{
private:
//animation vars
GLfloat smallSpiUpperAnimation= 0.0f;
GLfloat smallSpiLowerAnimation = 0.0f;
GLfloat smallSpiMiddleAnimation = 0.0f;
//movement andposition
GLfloat smallspiderX;
GLfloat smallspiderY;
GLfloat smallspiderZ;
GLfloat walkingDirOffset;
GLfloat faceRight;
bool smallSpiderForward = true;
vec3 smallSpiderinitialLocation;
//body parts and vaos
int NUM_LEGS = 8;
int TOTAL_PARTS = 25;
ModelData* mesh_data = new ModelData[TOTAL_PARTS];
unsigned int* smallvn_vbo = new unsigned int[TOTAL_PARTS];
unsigned int* smallvp_vbo = new unsigned int[TOTAL_PARTS];
unsigned int* smallvt_vbo = new unsigned int[TOTAL_PARTS];
vec3* smallSpiderTrans = new vec3[TOTAL_PARTS];
public:
smallSpider();
smallSpider(GLfloat x, GLfloat y, GLfloat z, bool forward, bool faceRight, GLfloat offset);
void genSmallSpider();
void draw(Shader shader, int width, int height, unsigned int diffMap);
void updateSceneSmallSpider(float delta, bool moving);
};
| [
"whelane5@tcd.ie"
] | whelane5@tcd.ie |
415efeac2e163014121aef525ef8bdc2a7bcb1d4 | 3f8caee5646880934c729a68ee1ba6c0d27ce082 | /src/filter.cpp | ee517f89d67384a915f64a4a7565087cc3d52bf9 | [] | no_license | AAGrigoriev/Bayan | 36ea69d3379a02ca9dc3d98be5ec43db2a37d1f0 | 706c6eae1ee0256374394c83df054442e04c60e5 | refs/heads/main | 2023-08-24T03:15:23.141053 | 2021-10-18T19:39:26 | 2021-10-18T19:39:26 | 338,801,609 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 845 | cpp | //
// Created by andrei on 22.02.2021.
#include "filter.hpp"
#include <regex>
namespace bayan {
filter_dir::filter_dir(opt_filter&& opt_filter)
: filter_opt_(std::move(opt_filter)) {
for (auto& mask : filter_opt_.mask_to_file) {
filter_mask_.emplace_back(mask);
}
}
bool filter_dir::approach_dir(const fs::path& path) {
return std::any_of(
filter_opt_.exclude_path.begin(), filter_opt_.exclude_path.end(),
[&path](fs::path& filter_path) { return path == filter_path; });
}
bool filter_dir::approach_file(const fs::path& path) {
if (fs::is_regular_file(path) &&
fs::file_size(path) >= filter_opt_.min_file_size) {
return std::any_of(
filter_mask_.begin(), filter_mask_.end(),
[&path](mask& mask_) { return mask_.isValid(path.string()); });
}
return false;
}
} // namespace bayan | [
"grigormaklaud@gmail.com"
] | grigormaklaud@gmail.com |
7305405e3d5b8fc76fd88cf30b2aef2ecd314a62 | 7c5d7fb6a64df1a118a64bdf6087ecf395a3a722 | /data/russia-team-j/sources/114-j-4.cpp | a2e629a5aeeb9687144341a4f8c4b4dfeafec9e2 | [] | no_license | alexhein189/code-plagiarism-detector | e66df71c46cc5043b6825ef76a940b658c0e5015 | 68d21639d4b37bb2c801befe6f7ce0007d7eccc5 | refs/heads/master | 2023-03-18T06:02:45.508614 | 2016-05-04T14:29:57 | 2016-05-04T14:54:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,810 | cpp | #include <iostream>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <string>
#include <vector>
#include <cstdio>
#include <cassert>
#include <ctime>
using namespace std;
typedef long long ll;
typedef long double ld;
#define LLD "%I64d"
#define FILENAME "travel"
struct point
{
int x, y;
};
const int gox[4] = {0, 0, 1, -1};
const int goy[4] = {1, -1, 0, 0};
const int MW = 510;
int w, h, i, j, n, k;
point och[MW*MW], p, beg, too;
int d[MW][MW];
char t[MW][MW];
point from[MW][MW];
int ans, cur;
string s;
bool vis[MW][MW];
bool toq[MW][MW];
void Add(int dx, int dy)
{
if (dx == 0)
{
if (dy == 1)
s += 'E';
else
s += 'W';
}
else if (dx == 1)
s += 'S';
else s += 'N';
}
int Check(int i, int j)
{
int k;
for (k = 0; k < 4; k++)
if ((i + gox[k] >= 0 && j + goy[k] >= 0) && t[i + gox[k]][j + goy[k]] == 'T')
return k;
return k;
}
int main()
{
freopen(FILENAME ".in", "r", stdin);
freopen(FILENAME ".out", "w", stdout);
scanf("%d %d %d", &w, &h, &n);
for (i = 0; i < h; i++) scanf("%s", t[i]);
for (i = 0; i < h; i++)
for (j = 0; j < w; j++)
if (t[i][j] == 'V')
{
beg.y = j;
beg.x = i;
t[i][j] = 'A';
}
och[0] = beg;
i = 0, j = 1;
while (i < j)
{
p = och[i];
vis[p.x][p.y] = 1;
i++;
for (k = 0; k < 4; k++)
{
too.x = p.x + gox[k], too.y = p.y + goy[k];
if (too.x < 0 || too.x >= h) continue;
if (too.y < 0 || too.y >= w) continue;
if (vis[too.x][too.y]) continue;
if (!toq[too.x][too.y])
{
toq[too.x][too.y] = true;
och[j].x = too.x;
och[j].y = too.y;
j++;
}
if (d[too.x][too.y] <= d[p.x][p.y] + (t[too.x][too.y] == 'T'))
{
d[too.x][too.y] = d[p.x][p.y] + (t[too.x][too.y] == 'T');
from[too.x][too.y] = p;
}
}
}
ans = 1e9;
for (i = 0; i < h; i++)
for (j = 0; j < w; j++)
if (t[i][j] == 'T')
{
if (Check(i, j) == 4)
cur = 2*(n - d[i][j]);
else
cur = n - d[i][j];
cur += abs(i - beg.x) + abs(j - beg.y);
if (cur < ans)
{
p.x = i, p.y = j;
ans = cur;
}
}
s = "";
k = Check(p.x, p.y);
n = n - d[p.x][p.y];
if (k == 4)
{
k = 0;
while ((p.x + gox[k] > 0 && p.y + goy[k] > 0) || t[p.x + gox[k]][p.y + goy[k]] != 'A') k++;
for (i = 0; i < n; i++)
{
Add(-gox[k], -goy[k]);
Add(gox[k], goy[k]);
}
}
else
{
if (n % 2 == 1)
Add(gox[k], goy[k]);
for (i = 0; i < n/2; i++)
{
Add(-gox[k], -goy[k]);
Add(gox[k], goy[k]);
}
}
while (p.x != beg.x || p.y != beg.y)
{
too = from[p.x][p.y];
Add(p.x - too.x, p.y - too.y);
p = too;
}
reverse(s.begin(), s.end());
cout << s << "\n";
return 0;
} | [
"shk.slava@gmail.com"
] | shk.slava@gmail.com |
04720e10a04f16c6b325d8c2d459e35efa177d2f | 7391feeb5b8e31f982422bdd74517e954d8c955e | /CppUnit/WinTestRunner/src/ProgressBar.h | 99d17cb775a7b95560ea6501eb94760f2d9d7bf5 | [
"BSL-1.0"
] | permissive | AppAnywhere/agent-sdk | 62d762d0424fc2e8d4a98b79fb150e635adedd4d | c5495c4a1d892f2d3bca5b82a7436db7d8adff71 | refs/heads/master | 2021-01-11T15:22:01.406793 | 2016-09-01T16:36:20 | 2016-09-01T16:36:20 | 80,341,203 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,281 | h | //
// ProgressBar.h
//
// $Id: //poco/1.7/CppUnit/WinTestRunner/src/ProgressBar.h#1 $
//
#ifndef ProgressBar_INCLUDED
#define ProgressBar_INCLUDED
#include "CppUnit/CppUnit.h"
#include <afxwin.h>
namespace CppUnit {
/* A Simple ProgressBar for test execution display
*/
class ProgressBar
{
public:
ProgressBar(CWnd* baseWindow, CRect& bounds);
void step(bool successful);
void paint(CDC& dc);
int scale(int value);
void reset();
void start(int total);
protected:
void paintBackground(CDC& dc);
void paintStatus(CDC& dc);
COLORREF getStatusColor();
void paintStep(int startX, int endX);
CWnd* _baseWindow;
CRect _bounds;
bool _error;
int _total;
int _progress;
int _progressX;
};
// Construct a ProgressBar
inline ProgressBar::ProgressBar(CWnd* baseWindow, CRect& bounds):
_baseWindow(baseWindow),
_bounds(bounds),
_error(false),
_total(0),
_progress(0),
_progressX(0)
{
WINDOWINFO wi;
wi.cbSize = sizeof(WINDOWINFO);
baseWindow->GetWindowInfo(&wi);
_bounds.OffsetRect(-wi.rcClient.left, -wi.rcClient.top);
}
// Get the current color
inline COLORREF ProgressBar::getStatusColor()
{
return _error ? RGB(255, 0, 0) : RGB(0, 255, 0);
}
} // namespace CppUnit
#endif // ProgressBar_INCLUDED
| [
"guenter.obiltschnig@appinf.com"
] | guenter.obiltschnig@appinf.com |
9e0e0c520257064c7fca871a7b2c48e9e25ee6d1 | 5ed9877be4f7552e6bd306983e600ac320700633 | /Stack/Maximum-In-K.cc | 2bb2f50277434b7776fe3cdb19aafe9ed6141ce3 | [] | no_license | ashish25-bit/data-structure-algorithms | 8c31c2026a24af32b05460146203a71bfbba20a5 | e5cb0ed09474e4e557db49c214b92969d78d514b | refs/heads/master | 2023-08-23T05:09:10.086580 | 2021-11-08T07:20:20 | 2021-11-08T07:20:20 | 305,376,215 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 828 | cc | // https://practice.geeksforgeeks.org/problems/maximum-of-all-subarrays-of-size-k3101/1#
#include <bits/stdc++.h>
using namespace std;
vector <int> max_of_subarrays(vector<int> arr, int n, int k) {
deque<int> q(k);
vector<int> res;
for (int i=0; i < k; i++) {
while (!q.empty() && arr[i] >= arr[q.back()])
q.pop_back();
q.push_back(i);
}
for (int i=k; i < n; i++) {
res.push_back(arr[q.front()]);
while (!q.empty() && q.front() <= i - k)
q.pop_front();
while (!q.empty() && arr[i] >= arr[q.back()])
q.pop_back();
q.push_back(i);
}
res.push_back(arr[q.front()]);
return res;
}
int main() {
vector<int> arr = {1, 2, 3, 1, 4, 5, 2, 3, 6};
int k = 3;
vector<int> res = max_of_subarrays(arr, arr.size(), k);
for (int x: res) cout << x << " ";
return 0;
}
| [
"ashishyoel23@gmail.com"
] | ashishyoel23@gmail.com |
7c7977c3929d517934943721a40d86f0e17acaf5 | bc6cd18a13992f425bb97406c5c5e7e3b8d8cb03 | /src/utils/kd_tree.h | 5937a8e73e1a3728ae7b1ef1a604b5e2a1332519 | [
"MIT"
] | permissive | collinej/Vulcan | 4ef1e2fc1b383b2b3a9ee59d78dc3c027d4cae24 | fa314bca7011d81b9b83f44edc5a51b617d68261 | refs/heads/master | 2022-09-19T01:59:45.905392 | 2022-09-18T02:41:22 | 2022-09-18T02:41:22 | 186,317,314 | 3 | 3 | NOASSERTION | 2022-04-29T02:06:12 | 2019-05-13T00:04:38 | C++ | UTF-8 | C++ | false | false | 508 | h | /* Copyright (C) 2010-2019, The Regents of The University of Michigan.
All rights reserved.
This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab
under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an
MIT-style License that can be found at "https://github.com/h2ssh/Vulcan".
*/
#ifndef UTILS_KD_TREE_H
#define UTILS_KD_TREE_H
namespace vulcan
{
namespace utils
{
}
} // namespace vulcan
#endif // UTILS_KD_TREE_H
| [
"collinej@umich.edu"
] | collinej@umich.edu |
96097e1cb4e9e64c1d68e686b77951ba049cb7cc | 6547f14615734ac9239b57a572f7473b7e203f04 | /libmmdpi/vmd/vmd.hpp | 5dd222eb5ad5aa7f82c06508e2e6976d63e335a8 | [
"MIT"
] | permissive | shirobu2400/mmdpi | 93c918e401fa47d7bc5ef20e85b6c67ccebc2377 | 7989d0b37147c5f5de2efd7efacf214cf3869e8e | refs/heads/master | 2023-01-12T00:12:13.957099 | 2022-12-28T08:59:49 | 2022-12-28T08:59:49 | 50,778,540 | 7 | 2 | MIT | 2020-04-13T16:31:34 | 2016-01-31T14:34:27 | Objective-C | UTF-8 | C++ | false | false | 4,872 | hpp |
#include "../model/mmdpi_include.hpp"
#include "../model/mmdpi_bone.hpp"
#include "../model/tools/get_bin.hpp"
#include "../pmx/pmx_struct.hpp"
#include "../pmd/pmd_struct.hpp"
#ifndef __MMDPI__VMD__DEFINES__
#define __MMDPI__VMD__DEFINES__ ( 1 )
#pragma pack( push, 1 ) // アライメント
// 動作
typedef struct tagMMDPI_VMD_MMDPI_PMD_HEADER
{
char vmd_header[ 30 ]; // "Vocaloid Motion Data 0002"
char vmd_model_name[ 20 ];
} MMDPI_VMD_MMDPI_PMD_HEADER;
typedef struct tagMMDPI_VMD_MOTION
{ // 111 Bytes
char bone_name[ 15 ];
dword frame_number;
float vx, vy, vz;
float qx, qy, qz, qw; // Quaternion
char interpolation[ 64 ]; // [4][4][4]
} MMDPI_VMD_MOTION, *MMDPI_VMD_MOTION_PTR;
// 表情
typedef struct tagMMDPI_VMD_SKIN_COUNT
{
dword count;
} MMDPI_VMD_SKIN_COUNT, *MMDPI_VMD_SKIN_COUNT_PTR;
typedef struct tagMMDPI_VMD_SKIN
{ // 23 Bytes
char skin_name[ 15 ];
dword frame_number;
float weight;
} MMDPI_VMD_SKIN, *MMDPI_VMD_SKIN_PTR;
typedef struct tagMMDPI_VMD_INFO
{
MMDPI_VMD_MMDPI_PMD_HEADER header; // ヘッダ
// モーション
dword motion_num; // モーション数
MMDPI_VMD_MOTION_PTR motion; // モーション
// スキン
MMDPI_VMD_SKIN_COUNT skin_num;
MMDPI_VMD_SKIN_PTR skin;
} MMDPI_VMD_INFO, *MMDPI_VMD_INFO_PTR;
#if 0
struct VMD_CAMERA_COUNT {
dword count;
} vmd_camera_count;
struct VMD_CAMERA {
dword FlameNo;
float Length;
float Location[3];
float Rotation[3];
BYTE interpolation[24];
dword ViewingAngle;
BYTE Perspective; // 0:on 1:off
} vmd_camera;
struct VMD_LIGHT_COUNT {
dword count;
} vmd_light_count;
struct VMD_LIGHT { // 28 Bytes //
dword FlameNo;
float RGB[3]; // RGB
float Location[3];
} vmd_light;
struct VMD_SELF_SHADOW_COUNT {
dword count;
} vmd_self_shadow_count;
struct VMD_SELF_SHADOW { // 9 Bytes //
dword FlameNo;
BYTE Mode; // 00-02
float Distance; // 0.1 - (dist * 0.00001)
} vmd_self_shadow;
#endif
#pragma pack( pop ) //
// 内部処理用
typedef struct tagMMDPI_VMD_INFO_LIST
{
tagMMDPI_VMD_INFO_LIST* next; //
tagMMDPI_VMD_INFO_LIST* prev; //
MMDPI_VMD_MOTION_PTR motion; // モーション
} MMDPI_VMD_INFO_LIST, *MMDPI_VMD_INFO_LIST_PTR, **MMDPI_VMD_INFO_LIST_PTR_PTR;
// 内部処理用
typedef struct tagMMDPI_VMD_SKIN_INFO_LIST
{
tagMMDPI_VMD_SKIN_INFO_LIST* next; // 次
tagMMDPI_VMD_SKIN_INFO_LIST* prev; // 前
tagMMDPI_VMD_SKIN_INFO_LIST* brot; // 兄弟
MMDPI_VMD_SKIN_PTR skin; // スキン
dword target_id;
} MMDPI_VMD_SKIN_INFO_LIST, *MMDPI_VMD_SKIN_INFO_LIST_PTR;
// VMD Loader
class mmdpiVmd
{
protected:
MMDPI_VMD_INFO_PTR vmd_info;
int bone_num;
MMDPI_VMD_INFO_LIST_PTR m_list;
std::map<std::string, int> bone_name_to_index;
// モーション
MMDPI_VMD_INFO_LIST_PTR_PTR motion_line; // モーション配列
MMDPI_VMD_INFO_LIST_PTR_PTR now_motion; // 現在のモーション
// 表情
std::map<std::string, int> skin_name_to_index;
MMDPI_VMD_SKIN_INFO_LIST_PTR skin_line;
MMDPI_VMD_SKIN_INFO_LIST_PTR now_skin; // 現在のスキン
int skin_morph_num;
//MMDPI_PMD_SKIN_INFO_PTR skin;
MMDPI_PMX_MORPH_INFO_PTR morph;
dword max_frame;
float motion_time;
int analyze( void );
int insert_motion_list( int bone_index, MMDPI_VMD_MOTION_PTR insert_motion );
int insert_skin( MMDPI_VMD_SKIN_PTR skin );
float interpolate( float x1, float y1, float x2, float y2, float x );
MMDPI_BONE_INFO_PTR bone;
public:
int operator++( void )
{
return this->advance_time();
}
int operator+=( float frame )
{
if( frame < 1e-4f )
return 0;
return this->advance_time( frame );
}
mmdpiVmd* operator=( float frame )
{
if( motion_time < frame )
this->init_motion();
for( ; motion_time < frame; motion_time ++ )
this->advance_time();
this->advance_time( 0 );
return this;
}
float get_motion_time( void )
{
return motion_time;
}
float get_motion_frames( void )
{
return ( float )max_frame;
}
int is_end( void ); // 終了判定
int init_motion( void ); // モーション初期化
int advance_time( float time_scale = 1.0f ); // モーション再生
int set_bone( MMDPI_BONE_INFO_PTR bone );
int create_bone_map( MMDPI_PMD_BONE_INFO_PTR bone, int bone_num );
//int create_morph_map( MMDPI_PMD_SKIN_INFO_PTR skin, int skin_num );
int create_bone_map_pmx( MMDPI_PMX_BONE_INFO_PTR bone, int bone_num );
int create_morph_map_pmx( MMDPI_PMX_MORPH_INFO_PTR morph, int morph_num );
int init_first_motion( void );
int load( const char *filename );
mmdpiVmd();
~mmdpiVmd();
};
#endif // __MMDPI__VMD__DEFINES__
| [
"shirobu_2400kskm@yahoo.co.jp"
] | shirobu_2400kskm@yahoo.co.jp |
9301625a760a932bcf139c3aab1959fed508236a | f33f043b306e91b2bf12cbfe6705aa395f06813d | /YazilimTestiProje/Stock.hpp | 013fec47f4dec5df0cbbb399fafea3f22fefcd14 | [] | no_license | erendgrmnc/SoftwareTestingFinalProject | fc2be0b7047fb133a3162f7362b8a35b36b76b28 | 32e2570c18df5f3ac297c566eb036ac5a200e2ee | refs/heads/master | 2023-05-03T10:08:49.250483 | 2021-05-23T16:02:15 | 2021-05-23T16:02:15 | 370,096,332 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 622 | hpp | #pragma once
#include <string>
#include <iostream>
using namespace std;
namespace StockNameSpace {
class Stock
{
public:
Stock();
Stock(string ID, string Symbol, string Name, float Price);
Stock(string ID, string Symbol, float Price);
~Stock();
string GetID();
void SetID(string ID);
string GetSymbol();
void SetSymbol(string Symbol);
string GetName();
void SetName(string Name);
float GetPrice();
void SetPrice(float Price);
void SetStock(string ID, string Symbol, string Name, float Price);
void PrintStock();
private:
string ID;
string Symbol;
string Name;
float Price;
};
} | [
"erendegirmenci.354@gmail.com"
] | erendegirmenci.354@gmail.com |
bcf659694dc6e5e9e929fb4d4e9bc79463d56fa3 | 07a0780a3ca399ac746751efd588e41b544fc573 | /Surface/build-Surface-Desktop_Qt_5_7_0_MinGW_32bit-Debug/ui_mainwindow.h | 2c012eb881a89aeda5f0e2906b7deb4a8b3dce04 | [] | no_license | ljystone/WindProject | fcea6f4936ffc0c1cb51d1a2ea76d561c2d570e4 | 1d229136f77e0ae27eafcb1d173196fa72654c7c | refs/heads/master | 2020-04-09T04:28:22.084325 | 2018-12-02T12:44:37 | 2018-12-02T12:44:37 | 160,024,444 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,561 | h | /********************************************************************************
** Form generated from reading UI file 'mainwindow.ui'
**
** Created by: Qt User Interface Compiler version 5.7.0
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_MAINWINDOW_H
#define UI_MAINWINDOW_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QMainWindow>
#include <QtWidgets/QMenuBar>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QSpacerItem>
#include <QtWidgets/QStatusBar>
#include <QtWidgets/QToolBar>
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_MainWindow
{
public:
QWidget *centralWidget;
QGridLayout *gridLayout;
QWidget *widget_2;
QHBoxLayout *horizontalLayout_3;
QSpacerItem *horizontalSpacer_5;
QLabel *label_10;
QLineEdit *serialNumber;
QSpacerItem *horizontalSpacer_3;
QPushButton *openSerial;
QSpacerItem *horizontalSpacer_6;
QPushButton *sendData;
QSpacerItem *horizontalSpacer_7;
QWidget *widget_3;
QHBoxLayout *horizontalLayout_4;
QSpacerItem *horizontalSpacer;
QLabel *label_9;
QSpacerItem *horizontalSpacer_2;
QWidget *widget;
QVBoxLayout *verticalLayout;
QHBoxLayout *horizontalLayout_7;
QLabel *label_8;
QLineEdit *holdTimeMin;
QLabel *label_7;
QLineEdit *holdTimeMax;
QSpacerItem *verticalSpacer;
QHBoxLayout *horizontalLayout_6;
QLabel *label_6;
QLineEdit *pressurePWMMin;
QLabel *label_5;
QLineEdit *pressurePWMMax;
QSpacerItem *verticalSpacer_2;
QHBoxLayout *horizontalLayout;
QLabel *label;
QLineEdit *tempertaurePWMMin;
QLabel *label_2;
QLineEdit *tempertaurePWMMax;
QSpacerItem *verticalSpacer_3;
QHBoxLayout *horizontalLayout_2;
QLabel *label_3;
QLineEdit *motorPluseMin;
QLabel *label_4;
QLineEdit *motorPluseMax;
QSpacerItem *verticalSpacer_4;
QLineEdit *response;
QMenuBar *menuBar;
QToolBar *mainToolBar;
QStatusBar *statusBar;
void setupUi(QMainWindow *MainWindow)
{
if (MainWindow->objectName().isEmpty())
MainWindow->setObjectName(QStringLiteral("MainWindow"));
MainWindow->resize(544, 476);
centralWidget = new QWidget(MainWindow);
centralWidget->setObjectName(QStringLiteral("centralWidget"));
gridLayout = new QGridLayout(centralWidget);
gridLayout->setSpacing(6);
gridLayout->setContentsMargins(11, 11, 11, 11);
gridLayout->setObjectName(QStringLiteral("gridLayout"));
widget_2 = new QWidget(centralWidget);
widget_2->setObjectName(QStringLiteral("widget_2"));
QSizePolicy sizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
sizePolicy.setHorizontalStretch(0);
sizePolicy.setVerticalStretch(0);
sizePolicy.setHeightForWidth(widget_2->sizePolicy().hasHeightForWidth());
widget_2->setSizePolicy(sizePolicy);
horizontalLayout_3 = new QHBoxLayout(widget_2);
horizontalLayout_3->setSpacing(6);
horizontalLayout_3->setContentsMargins(11, 11, 11, 11);
horizontalLayout_3->setObjectName(QStringLiteral("horizontalLayout_3"));
horizontalSpacer_5 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
horizontalLayout_3->addItem(horizontalSpacer_5);
label_10 = new QLabel(widget_2);
label_10->setObjectName(QStringLiteral("label_10"));
horizontalLayout_3->addWidget(label_10);
serialNumber = new QLineEdit(widget_2);
serialNumber->setObjectName(QStringLiteral("serialNumber"));
serialNumber->setMaximumSize(QSize(71, 16777215));
horizontalLayout_3->addWidget(serialNumber);
horizontalSpacer_3 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
horizontalLayout_3->addItem(horizontalSpacer_3);
openSerial = new QPushButton(widget_2);
openSerial->setObjectName(QStringLiteral("openSerial"));
horizontalLayout_3->addWidget(openSerial);
horizontalSpacer_6 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
horizontalLayout_3->addItem(horizontalSpacer_6);
sendData = new QPushButton(widget_2);
sendData->setObjectName(QStringLiteral("sendData"));
horizontalLayout_3->addWidget(sendData);
horizontalSpacer_7 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
horizontalLayout_3->addItem(horizontalSpacer_7);
gridLayout->addWidget(widget_2, 2, 0, 1, 1);
widget_3 = new QWidget(centralWidget);
widget_3->setObjectName(QStringLiteral("widget_3"));
sizePolicy.setHeightForWidth(widget_3->sizePolicy().hasHeightForWidth());
widget_3->setSizePolicy(sizePolicy);
horizontalLayout_4 = new QHBoxLayout(widget_3);
horizontalLayout_4->setSpacing(6);
horizontalLayout_4->setContentsMargins(11, 11, 11, 11);
horizontalLayout_4->setObjectName(QStringLiteral("horizontalLayout_4"));
horizontalSpacer = new QSpacerItem(81, 18, QSizePolicy::Preferred, QSizePolicy::Minimum);
horizontalLayout_4->addItem(horizontalSpacer);
label_9 = new QLabel(widget_3);
label_9->setObjectName(QStringLiteral("label_9"));
QSizePolicy sizePolicy1(QSizePolicy::Preferred, QSizePolicy::Preferred);
sizePolicy1.setHorizontalStretch(0);
sizePolicy1.setVerticalStretch(0);
sizePolicy1.setHeightForWidth(label_9->sizePolicy().hasHeightForWidth());
label_9->setSizePolicy(sizePolicy1);
label_9->setMinimumSize(QSize(60, 0));
QFont font;
font.setFamily(QString::fromUtf8("\345\215\216\346\226\207\350\241\214\346\245\267"));
font.setPointSize(16);
label_9->setFont(font);
label_9->setAlignment(Qt::AlignCenter);
horizontalLayout_4->addWidget(label_9);
horizontalSpacer_2 = new QSpacerItem(80, 18, QSizePolicy::Preferred, QSizePolicy::Minimum);
horizontalLayout_4->addItem(horizontalSpacer_2);
gridLayout->addWidget(widget_3, 0, 0, 1, 1);
widget = new QWidget(centralWidget);
widget->setObjectName(QStringLiteral("widget"));
sizePolicy.setHeightForWidth(widget->sizePolicy().hasHeightForWidth());
widget->setSizePolicy(sizePolicy);
verticalLayout = new QVBoxLayout(widget);
verticalLayout->setSpacing(6);
verticalLayout->setContentsMargins(11, 11, 11, 11);
verticalLayout->setObjectName(QStringLiteral("verticalLayout"));
horizontalLayout_7 = new QHBoxLayout();
horizontalLayout_7->setSpacing(6);
horizontalLayout_7->setObjectName(QStringLiteral("horizontalLayout_7"));
label_8 = new QLabel(widget);
label_8->setObjectName(QStringLiteral("label_8"));
horizontalLayout_7->addWidget(label_8);
holdTimeMin = new QLineEdit(widget);
holdTimeMin->setObjectName(QStringLiteral("holdTimeMin"));
holdTimeMin->setMaximumSize(QSize(71, 16777215));
horizontalLayout_7->addWidget(holdTimeMin);
label_7 = new QLabel(widget);
label_7->setObjectName(QStringLiteral("label_7"));
horizontalLayout_7->addWidget(label_7);
holdTimeMax = new QLineEdit(widget);
holdTimeMax->setObjectName(QStringLiteral("holdTimeMax"));
holdTimeMax->setMaximumSize(QSize(71, 16777215));
horizontalLayout_7->addWidget(holdTimeMax);
verticalLayout->addLayout(horizontalLayout_7);
verticalSpacer = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding);
verticalLayout->addItem(verticalSpacer);
horizontalLayout_6 = new QHBoxLayout();
horizontalLayout_6->setSpacing(6);
horizontalLayout_6->setObjectName(QStringLiteral("horizontalLayout_6"));
label_6 = new QLabel(widget);
label_6->setObjectName(QStringLiteral("label_6"));
horizontalLayout_6->addWidget(label_6);
pressurePWMMin = new QLineEdit(widget);
pressurePWMMin->setObjectName(QStringLiteral("pressurePWMMin"));
pressurePWMMin->setMaximumSize(QSize(71, 16777215));
horizontalLayout_6->addWidget(pressurePWMMin);
label_5 = new QLabel(widget);
label_5->setObjectName(QStringLiteral("label_5"));
horizontalLayout_6->addWidget(label_5);
pressurePWMMax = new QLineEdit(widget);
pressurePWMMax->setObjectName(QStringLiteral("pressurePWMMax"));
pressurePWMMax->setMaximumSize(QSize(71, 16777215));
horizontalLayout_6->addWidget(pressurePWMMax);
verticalLayout->addLayout(horizontalLayout_6);
verticalSpacer_2 = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding);
verticalLayout->addItem(verticalSpacer_2);
horizontalLayout = new QHBoxLayout();
horizontalLayout->setSpacing(6);
horizontalLayout->setObjectName(QStringLiteral("horizontalLayout"));
label = new QLabel(widget);
label->setObjectName(QStringLiteral("label"));
horizontalLayout->addWidget(label);
tempertaurePWMMin = new QLineEdit(widget);
tempertaurePWMMin->setObjectName(QStringLiteral("tempertaurePWMMin"));
sizePolicy1.setHeightForWidth(tempertaurePWMMin->sizePolicy().hasHeightForWidth());
tempertaurePWMMin->setSizePolicy(sizePolicy1);
tempertaurePWMMin->setMaximumSize(QSize(71, 16777215));
tempertaurePWMMin->setReadOnly(true);
horizontalLayout->addWidget(tempertaurePWMMin);
label_2 = new QLabel(widget);
label_2->setObjectName(QStringLiteral("label_2"));
horizontalLayout->addWidget(label_2);
tempertaurePWMMax = new QLineEdit(widget);
tempertaurePWMMax->setObjectName(QStringLiteral("tempertaurePWMMax"));
QSizePolicy sizePolicy2(QSizePolicy::Fixed, QSizePolicy::Fixed);
sizePolicy2.setHorizontalStretch(0);
sizePolicy2.setVerticalStretch(0);
sizePolicy2.setHeightForWidth(tempertaurePWMMax->sizePolicy().hasHeightForWidth());
tempertaurePWMMax->setSizePolicy(sizePolicy2);
tempertaurePWMMax->setMaximumSize(QSize(70, 16777215));
tempertaurePWMMax->setReadOnly(true);
horizontalLayout->addWidget(tempertaurePWMMax);
verticalLayout->addLayout(horizontalLayout);
verticalSpacer_3 = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding);
verticalLayout->addItem(verticalSpacer_3);
horizontalLayout_2 = new QHBoxLayout();
horizontalLayout_2->setSpacing(6);
horizontalLayout_2->setObjectName(QStringLiteral("horizontalLayout_2"));
label_3 = new QLabel(widget);
label_3->setObjectName(QStringLiteral("label_3"));
horizontalLayout_2->addWidget(label_3);
motorPluseMin = new QLineEdit(widget);
motorPluseMin->setObjectName(QStringLiteral("motorPluseMin"));
sizePolicy2.setHeightForWidth(motorPluseMin->sizePolicy().hasHeightForWidth());
motorPluseMin->setSizePolicy(sizePolicy2);
motorPluseMin->setMaximumSize(QSize(70, 16777215));
motorPluseMin->setReadOnly(true);
horizontalLayout_2->addWidget(motorPluseMin);
label_4 = new QLabel(widget);
label_4->setObjectName(QStringLiteral("label_4"));
horizontalLayout_2->addWidget(label_4);
motorPluseMax = new QLineEdit(widget);
motorPluseMax->setObjectName(QStringLiteral("motorPluseMax"));
sizePolicy2.setHeightForWidth(motorPluseMax->sizePolicy().hasHeightForWidth());
motorPluseMax->setSizePolicy(sizePolicy2);
motorPluseMax->setMaximumSize(QSize(70, 16777215));
motorPluseMax->setReadOnly(true);
horizontalLayout_2->addWidget(motorPluseMax);
verticalLayout->addLayout(horizontalLayout_2);
verticalSpacer_4 = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding);
verticalLayout->addItem(verticalSpacer_4);
response = new QLineEdit(widget);
response->setObjectName(QStringLiteral("response"));
verticalLayout->addWidget(response);
gridLayout->addWidget(widget, 1, 0, 1, 1);
MainWindow->setCentralWidget(centralWidget);
menuBar = new QMenuBar(MainWindow);
menuBar->setObjectName(QStringLiteral("menuBar"));
menuBar->setGeometry(QRect(0, 0, 544, 23));
MainWindow->setMenuBar(menuBar);
mainToolBar = new QToolBar(MainWindow);
mainToolBar->setObjectName(QStringLiteral("mainToolBar"));
MainWindow->addToolBar(Qt::TopToolBarArea, mainToolBar);
statusBar = new QStatusBar(MainWindow);
statusBar->setObjectName(QStringLiteral("statusBar"));
MainWindow->setStatusBar(statusBar);
retranslateUi(MainWindow);
QMetaObject::connectSlotsByName(MainWindow);
} // setupUi
void retranslateUi(QMainWindow *MainWindow)
{
MainWindow->setWindowTitle(QApplication::translate("MainWindow", "\350\204\212\346\237\261\345\212\237\350\203\275\350\257\204\344\274\260\346\250\241\345\235\227", 0));
label_10->setText(QApplication::translate("MainWindow", "\344\270\262\345\217\243\345\217\267\357\274\232", 0));
openSerial->setText(QApplication::translate("MainWindow", "\346\211\223\345\274\200\344\270\262\345\217\243", 0));
sendData->setText(QApplication::translate("MainWindow", "\344\270\262\345\217\243\345\217\221\351\200\201\346\225\260\346\215\256", 0));
label_9->setText(QApplication::translate("MainWindow", "\345\216\213\345\212\233\344\275\215\347\247\273\346\265\213\351\207\217\347\263\273\347\273\237", 0));
label_8->setText(QApplication::translate("MainWindow", "\347\273\264\346\214\201\346\227\266\351\227\264\357\274\232 min(\344\270\215\344\275\216\344\272\216100ms)", 0));
label_7->setText(QApplication::translate("MainWindow", "max:\344\270\215\350\266\205\350\277\207500ms", 0));
label_6->setText(QApplication::translate("MainWindow", "\345\216\213\345\212\233 min:", 0));
label_5->setText(QApplication::translate("MainWindow", "max:", 0));
label->setText(QApplication::translate("MainWindow", "\346\270\251\345\272\246\345\215\240\347\251\272\346\257\224 min\357\274\232", 0));
tempertaurePWMMin->setText(QApplication::translate("MainWindow", "12", 0));
label_2->setText(QApplication::translate("MainWindow", "max", 0));
tempertaurePWMMax->setText(QApplication::translate("MainWindow", "14", 0));
label_3->setText(QApplication::translate("MainWindow", "\347\224\265\346\234\272\350\204\211\345\206\262 min\357\274\232", 0));
motorPluseMin->setText(QApplication::translate("MainWindow", "35", 0));
label_4->setText(QApplication::translate("MainWindow", "max:\344\270\215\350\266\205\350\277\207300kHz", 0));
motorPluseMax->setText(QApplication::translate("MainWindow", "36", 0));
} // retranslateUi
};
namespace Ui {
class MainWindow: public Ui_MainWindow {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_MAINWINDOW_H
| [
"1137344859@qq.com"
] | 1137344859@qq.com |
7af54aa4377404282de8e9f76913fa16deda5c49 | 9fad4848e43f4487730185e4f50e05a044f865ab | /src/media/capture/video/linux/video_capture_device_linux.cc | f2a1d1d0a47dd48c3017512e6d44fea07d66836b | [
"BSD-3-Clause"
] | permissive | dummas2008/chromium | d1b30da64f0630823cb97f58ec82825998dbb93e | 82d2e84ce3ed8a00dc26c948219192c3229dfdaa | refs/heads/master | 2020-12-31T07:18:45.026190 | 2016-04-14T03:17:45 | 2016-04-14T03:17:45 | 56,194,439 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,757 | cc | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "media/capture/video/linux/video_capture_device_linux.h"
#include <stddef.h>
#include <list>
#include "base/bind.h"
#include "base/strings/stringprintf.h"
#include "build/build_config.h"
#include "media/capture/video/linux/v4l2_capture_delegate.h"
#if defined(OS_OPENBSD)
#include <sys/videoio.h>
#else
#include <linux/videodev2.h>
#endif
namespace media {
// USB VID and PID are both 4 bytes long.
static const size_t kVidPidSize = 4;
// /sys/class/video4linux/video{N}/device is a symlink to the corresponding
// USB device info directory.
static const char kVidPathTemplate[] =
"/sys/class/video4linux/%s/device/../idVendor";
static const char kPidPathTemplate[] =
"/sys/class/video4linux/%s/device/../idProduct";
static bool ReadIdFile(const std::string& path, std::string* id) {
char id_buf[kVidPidSize];
FILE* file = fopen(path.c_str(), "rb");
if (!file)
return false;
const bool success = fread(id_buf, kVidPidSize, 1, file) == 1;
fclose(file);
if (!success)
return false;
id->append(id_buf, kVidPidSize);
return true;
}
// Translates Video4Linux pixel formats to Chromium pixel formats.
// static
VideoPixelFormat VideoCaptureDeviceLinux::V4l2FourCcToChromiumPixelFormat(
uint32_t v4l2_fourcc) {
return V4L2CaptureDelegate::V4l2FourCcToChromiumPixelFormat(v4l2_fourcc);
}
// Gets a list of usable Four CC formats prioritized.
// static
std::list<uint32_t> VideoCaptureDeviceLinux::GetListOfUsableFourCCs(
bool favour_mjpeg) {
return V4L2CaptureDelegate::GetListOfUsableFourCcs(favour_mjpeg);
}
const std::string VideoCaptureDevice::Name::GetModel() const {
// |unique_id| is of the form "/dev/video2". |file_name| is "video2".
const std::string dev_dir = "/dev/";
DCHECK_EQ(0, unique_id_.compare(0, dev_dir.length(), dev_dir));
const std::string file_name =
unique_id_.substr(dev_dir.length(), unique_id_.length());
const std::string vidPath =
base::StringPrintf(kVidPathTemplate, file_name.c_str());
const std::string pidPath =
base::StringPrintf(kPidPathTemplate, file_name.c_str());
std::string usb_id;
if (!ReadIdFile(vidPath, &usb_id))
return "";
usb_id.append(":");
if (!ReadIdFile(pidPath, &usb_id))
return "";
return usb_id;
}
VideoCaptureDeviceLinux::VideoCaptureDeviceLinux(const Name& device_name)
: v4l2_thread_("V4L2CaptureThread"), device_name_(device_name) {}
VideoCaptureDeviceLinux::~VideoCaptureDeviceLinux() {
// Check if the thread is running.
// This means that the device has not been StopAndDeAllocate()d properly.
DCHECK(!v4l2_thread_.IsRunning());
v4l2_thread_.Stop();
}
void VideoCaptureDeviceLinux::AllocateAndStart(
const VideoCaptureParams& params,
scoped_ptr<VideoCaptureDevice::Client> client) {
DCHECK(!capture_impl_);
if (v4l2_thread_.IsRunning())
return; // Wrong state.
v4l2_thread_.Start();
const int line_frequency =
TranslatePowerLineFrequencyToV4L2(GetPowerLineFrequency(params));
capture_impl_ = new V4L2CaptureDelegate(
device_name_, v4l2_thread_.task_runner(), line_frequency);
if (!capture_impl_) {
client->OnError(FROM_HERE, "Failed to create VideoCaptureDelegate");
return;
}
v4l2_thread_.message_loop()->PostTask(
FROM_HERE,
base::Bind(&V4L2CaptureDelegate::AllocateAndStart, capture_impl_,
params.requested_format.frame_size.width(),
params.requested_format.frame_size.height(),
params.requested_format.frame_rate, base::Passed(&client)));
}
void VideoCaptureDeviceLinux::StopAndDeAllocate() {
if (!v4l2_thread_.IsRunning())
return; // Wrong state.
v4l2_thread_.message_loop()->PostTask(
FROM_HERE,
base::Bind(&V4L2CaptureDelegate::StopAndDeAllocate, capture_impl_));
v4l2_thread_.Stop();
capture_impl_ = NULL;
}
void VideoCaptureDeviceLinux::SetRotation(int rotation) {
if (v4l2_thread_.IsRunning()) {
v4l2_thread_.message_loop()->PostTask(
FROM_HERE,
base::Bind(&V4L2CaptureDelegate::SetRotation, capture_impl_, rotation));
}
}
// static
int VideoCaptureDeviceLinux::TranslatePowerLineFrequencyToV4L2(
PowerLineFrequency frequency) {
switch (frequency) {
case media::PowerLineFrequency::FREQUENCY_50HZ:
return V4L2_CID_POWER_LINE_FREQUENCY_50HZ;
case media::PowerLineFrequency::FREQUENCY_60HZ:
return V4L2_CID_POWER_LINE_FREQUENCY_60HZ;
default:
// If we have no idea of the frequency, at least try and set it to AUTO.
return V4L2_CID_POWER_LINE_FREQUENCY_AUTO;
}
}
} // namespace media
| [
"dummas@163.com"
] | dummas@163.com |
e9e25bcfb2e2d459c48790030a6ee33b4d15ccc0 | a9b85381004b077a287459982feb4cd7fc3fe3c6 | /dce-pass-p3/p3/SSA.h | a6a04b36d17a576386496236aedf005ae8700b56 | [] | no_license | shikanai/lastzuera | 7e04e98af3431d408cd8cddd6b48645c85ade371 | 3c2a5d5fe5b7281805fe362362e138e3d082168a | refs/heads/master | 2021-01-10T03:47:49.235362 | 2015-06-10T15:12:38 | 2015-06-10T15:12:38 | 36,334,888 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,191 | h |
#include "llvm/Pass.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Instruction.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/IR/User.h"
#include "llvm/IR/Instructions.h"
#include <set>
#include "llvm/ADT/SmallVector.h"
#include "llvm/Analysis/CFG.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/IR/ValueMap.h"
#include <llvm/IR/IntrinsicInst.h>
using namespace llvm;
namespace llvm {
class SSA: public FunctionPass {
private:
//DenseMap<const Instruction*, LivenessInfo> iLivenessMap;
//DenseMap<const BasicBlock*, LivenessInfo> bbLivenessMap;
//DenseMap<const Instruction*, int> instMap;
public:
static char ID;
SSA() : FunctionPass(ID) {}
virtual bool runOnFunction(Function &F);
//void computeBBDefUse(Function &F);
// void computeBBInOut(Function &F);
//void computeIInOut(Function &F);
// bool isLiveOut(Instruction *I, Value *V);
//void addToMap(Function &F);
/*virtual void getAnalysisUsage(AnalysisUsage &AU) const{
AU.setPreservesAll();
}*/
};
}
| [
"feliperosasd@gmail.com"
] | feliperosasd@gmail.com |
fa6524a054a1fd070f6b0d0809f001db89be05d3 | 69f8386f54d5e7b04af125c9a0bd4732eb7f79ae | /01solved/ABC-D/abc094-d.cpp | 3406ceefb40e81c196b4bb7fb884ac630ae7ddf9 | [] | no_license | satsukisahi/AtCoder | 4a33903265f03f957518ad64fb70319639131628 | b077a842cd78b1a4979944248616a4e863b44241 | refs/heads/master | 2021-07-16T16:07:17.637577 | 2020-06-28T11:26:28 | 2020-06-28T11:26:28 | 183,563,538 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 633 | cpp | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for(ll i = 0; i < (ll)(n); i++)
#define rep1(i, n) for(ll i = 1; i < (ll)(n); i++)
const ll mo=1000000007;
ll ans=0;
ll dp[0][0];
int main()
{
ll n;
cin >> n;
ll table[n]={};
rep(i,n) {
cin >> table [i];
}
sort(table, table+n);
cout << table[n-1] << ' ';
ll te=abs(table[n-1]/2+1-table[0]);
ll tem;
rep1(i,n-1){
if(table[n-1]%2){
tem=abs(table[n-1]/2+1-table[i]);
if(tem<te){te=tem;ans=i;}
}
else{
tem=abs(table[n-1]/2-table[i]);
if(tem<te){te=tem;ans=i;}
}
}
cout << table[ans] << endl;
return 0;
} | [
"lunareclipse3141@gmail.com"
] | lunareclipse3141@gmail.com |
cb0c9104d3d2627343dbb6251b547ffab24b80b5 | bc3615ad05ab631d513832edc437a72603097fae | /MQTTSNAsyncClient/src/lib/SubscribeManager.cpp | ad4e83c96f9090cfdd708153303c3a8642e75680 | [] | no_license | ty4tw/MQTTSNAsyncClient | a8879265a0e1d007f3306066aec97f2cd1b72506 | be40eaa1507651296a3af55bf337d5816ec5eb12 | refs/heads/master | 2021-01-22T17:33:54.866329 | 2016-06-12T12:41:17 | 2016-07-05T07:21:25 | 60,907,588 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,837 | cpp | /*
* SubscribeManager.cpp
* The BSD License
*
* Copyright (c) 2015, tomoaki@tomy-tech.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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 <MqttsnClientApp.h>
#include <MqttsnClient.h>
#include <SubscribeManager.h>
#include <GwProxy.h>
#include <Timer.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
using namespace tomyAsyncClient;
extern void setUint16(uint8_t* pos, uint16_t val);
extern uint16_t getUint16(const uint8_t* pos);
extern MqttsnClient* theClient;
/*========================================
Class SubscribeManager
=======================================*/
SubscribeManager::SubscribeManager(){
_first = 0;
}
SubscribeManager::~SubscribeManager(){
SubElement* elm = _first;
SubElement* sav = 0;
while (elm){
sav = elm->next;
if (elm != 0){
free(elm);
}
elm = sav;
}
}
SubElement* SubscribeManager::add(uint8_t msgType, const char* topicName, uint16_t topicId, uint8_t topicType, uint8_t qos, TopicCallback callback, uint16_t msgId){
SubElement* last = _first;
SubElement* prev = _first;
SubElement* elm = (SubElement*) calloc(1,sizeof(SubElement));
if (elm == 0){
return 0;
}
if (last == 0){
_first = elm;
}
elm->msgType = msgType;
elm->callback = callback;
elm->topicName = topicName;
elm->topicId = topicId;
elm->topicType = topicType;
if (qos == 0){
elm->qos = MQTTSN_FLAG_QOS_0;
/*
}else if ( qos == 1){
elm->qos = MQTTSN_FLAG_QOS_1;
}else if (qos == 2){
elm->qos = MQTTSN_FLAG_QOS_2;
}
*/
}else{
elm->qos = MQTTSN_FLAG_QOS_1;
}
elm->msgId = msgId;
elm->retryCount = MQTTSN_RETRY_COUNT;
elm->sendUTC = 0;
while(last){
prev = last;
if (prev->next != 0){
last = prev->next;
}else{
prev->next = elm;
elm->prev = prev;
elm->next = 0;
last = 0;
}
}
return elm;
}
void SubscribeManager::remove(SubElement* elm){
if (elm){
if (elm->prev == 0){
_first = elm->next;
if (elm->next != 0){
elm->next->prev = 0;
}
free(elm);
}else{
elm->prev->next = elm->next;
free(elm);
}
}
}
bool SubscribeManager::isDone(void){
return _first == 0;
}
void SubscribeManager::send(SubElement* elm){
uint8_t msg[MQTTSN_MAX_MSG_LENGTH + 1];
if (elm->topicType == MQTTSN_TOPIC_TYPE_NORMAL){
msg[0] = 5 + strlen(elm->topicName);
strcpy((char*)msg + 5, elm->topicName);
}else{
msg[0] = 7;
setUint16(msg + 5, elm->topicId);
}
msg[1] = elm->msgType;
msg[2] = elm->qos | elm->topicType;
if ((elm->retryCount < MQTTSN_RETRY_COUNT) && elm->msgType == MQTTSN_TYPE_SUBSCRIBE){
msg[2] = msg[2] | MQTTSN_FLAG_DUP;
}
setUint16(msg + 3, elm->msgId);
theClient->getGwProxy()->writeMsg(msg);
theClient->getGwProxy()->resetPingReqTimer();
elm->sendUTC = Timer::getUnixTime();
elm->retryCount--;
}
SubElement* SubscribeManager::getElement(uint16_t msgId){
SubElement* elm = _first;
while(elm){
if (elm->msgId == msgId){
return elm;
}else{
elm = elm->next;
}
}
return 0;
}
SubElement* SubscribeManager::getElement(const char* topicName){
SubElement* elm = _first;
while(elm){
if (strcmp(elm->topicName, topicName) == 0){
return elm;
}else{
elm = elm->next;
}
}
return 0;
}
SubElement* SubscribeManager::getElement(uint16_t topicId, uint8_t topicType){
SubElement* elm = _first;
while(elm){
if (elm->topicId == topicId && elm->topicType == topicType){
return elm;
}else{
elm = elm->next;
}
}
return 0;
}
void SubscribeManager::subscribe(const char* topicName, TopicCallback onPublish, uint8_t qos){
SubElement* elm = add(MQTTSN_TYPE_SUBSCRIBE, topicName, 0, MQTTSN_TOPIC_TYPE_NORMAL, qos, onPublish, theClient->getGwProxy()->getNextMsgId());
send(elm);
}
void SubscribeManager::subscribe(uint16_t topicId, TopicCallback onPublish, uint8_t qos, uint8_t topicType){
SubElement* elm = add(MQTTSN_TYPE_SUBSCRIBE, 0, topicId, topicType, qos, onPublish, theClient->getGwProxy()->getNextMsgId());
send(elm);
}
void SubscribeManager::unsubscribe(const char* topicName){
SubElement* elm = add(MQTTSN_TYPE_UNSUBSCRIBE, topicName, 0, MQTTSN_TOPIC_TYPE_NORMAL, 0, 0, theClient->getGwProxy()->getNextMsgId());
send(elm);
}
void SubscribeManager::unsubscribe(uint16_t topicId, uint8_t topicType){
SubElement* elm = add(MQTTSN_TYPE_UNSUBSCRIBE, 0, topicId, topicType, 0, 0, theClient->getGwProxy()->getNextMsgId());
send(elm);
}
void SubscribeManager::checkTimeout(void){
SubElement* elm = _first;
SubElement* sav;
while (elm){
if ( elm->sendUTC + MQTTSN_TIME_RETRY < Timer::getUnixTime()){
if (elm->retryCount >= 0){
send(elm);
}else{
if (elm->next){
sav = elm->prev;
remove(elm);
if(sav){
elm = sav;
}else{
break;
}
}else{
remove(elm);
break;
}
}
}
elm = elm->next;
}
}
void SubscribeManager::responce(const uint8_t* msg){
if ( msg[0] == MQTTSN_TYPE_SUBACK){
uint16_t topicId = getUint16(msg + 2);
uint16_t msgId = getUint16(msg + 4);
uint8_t rc = msg[6];
if (rc == 0){
TopicTable* tt = theClient->getGwProxy()->getTopicTable();
SubElement* elm = getElement(msgId);
if (elm){
tt->add((char*)elm->topicName, topicId, elm->topicType, elm->callback);
}
}
remove(getElement(msgId));
}else{
remove(getElement(getUint16(msg + 1)));
}
}
| [
"tomoaki@tomy-tech.com"
] | tomoaki@tomy-tech.com |
edfee412961abfde959a61446af6ac93a1452050 | ece82fc601d615ab2399a8c004058985312a16c6 | /LABS/DEV-ASM/PCI/Teste/stdafx.cpp | 8c0c8e75cbe368eef866029d8bc4995395cf5fc4 | [] | no_license | mostwanteddtm/MicroSO | 324a04c384a8a5f174c9ab5754271412bf8ab3c3 | 5cb857540e5ce35313a4ca6aa0a109b0c57c4480 | refs/heads/master | 2022-01-16T18:45:35.494045 | 2022-01-04T02:23:09 | 2022-01-04T02:23:09 | 42,884,118 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 292 | cpp | // stdafx.cpp : source file that includes just the standard includes
// Teste.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| [
"mostwanted.dtm@gmail.com"
] | mostwanted.dtm@gmail.com |
af51ae0dee7a10e27a1020450959c53808ed3bfd | 7233e8b260354f973c0b031dd869e6f5b6bfd4b7 | /SlidingWindow/978_Longest_Turbulent_Subarray.cpp | 6ff7ed4746b3097bacdfc351755fd6d260235aac | [] | no_license | Shadowmaple/Leetcode | 2a59b812d16e9a544d51762fd6edad4138b2e424 | 2323f5728a08a4e6f289decf481ae187c7f7541e | refs/heads/master | 2021-08-22T14:23:57.507553 | 2021-07-23T11:35:24 | 2021-07-23T11:35:24 | 204,666,583 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 795 | cpp | # include <iostream>
# include <vector>
using namespace std;
class Solution {
public:
int maxTurbulenceSize(vector<int>& A) {
int l = 0, r = 0;
int count = 0;
bool isBiger = true; // 上一次的比较
while (r < A.size()-1) {
if (l == r) {
if (A[r] == A[r+1]) {
l = ++r;
continue;
}
isBiger = A[r] > A[r+1];
++r;
continue;
}
if (!isBiger && A[r] > A[r+1] || isBiger && A[r] < A[r+1]) {
isBiger = !isBiger;
++r;
continue;
}
count = max(count, r - l + 1);
l = r;
}
return max(count, r - l + 1);
}
}; | [
"1142319190@qq.com"
] | 1142319190@qq.com |
b068a16d5b8fd67b2eb19aa852fabad4a4079f87 | a6d04c694c51b9497a2cb086bd22d284ee1be134 | /showdirinfo.cpp | add0e9fcdeefc088200a9378ef8177d56808fd66 | [] | no_license | hanliumaozhi/batchEditAudioTag | 5ce7a19c9adbd62e985d9f7a6df67e30a99684df | da02ce885dc98df2b7333c6d1cd52d19224c7085 | refs/heads/master | 2021-01-01T15:36:57.308984 | 2013-11-11T12:32:36 | 2013-11-11T12:32:36 | 14,300,133 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 384 | cpp | #include "showdirinfo.h"
showDirInfo::showDirInfo(QObject *parent) :
QObject(parent)
{
model = new QFileSystemModel;
model->setRootPath(QDir::currentPath());
splitter = new QSplitter;
tree = new QTreeView(splitter);
tree->setModel(model);
tree->setRootIndex(model->index(QDir::currentPath()));
layout = new QVBoxLayout;
layout->addWidget(tree);
}
| [
"hanliumaozhi@gmail.com"
] | hanliumaozhi@gmail.com |
0ae438a9d78700e095031517260047887f3e8800 | 42d27eab1400524afbd0466213b374d7ba51f2b3 | /GitGud/DSHack.cpp | c44df20a812496315a5decbe047ce2e9c9dc2aaa | [] | no_license | gitDanilo/GitGud | 08b0bbde0ddf36ebb7c7d396feb7ac9ab12b99b3 | 5826b1c98b3f62a01452868586acf9fb10a5930b | refs/heads/master | 2020-04-16T05:45:40.783454 | 2019-01-21T03:33:09 | 2019-01-21T03:33:09 | 165,319,763 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,472 | cpp | #include "DSHack.h"
bool DSHack::ToggleGravity(BYTE* BaseAddr)
{
BYTE byte;
Memory* pProcMem = Memory::GetInstance();
if (pProcMem->ReadProcMem(BaseAddr, BaseAddr) == false)
return false;
BaseAddr += 0x80;
if (pProcMem->ReadProcMem(BaseAddr, BaseAddr) == false)
return false;
BaseAddr += 0x1A08;
if (pProcMem->ReadProcMem(BaseAddr, byte) == false)
return false;
if (GETBIT(byte, 6))
CLBIT(byte, 6);
else
SETBIT(byte, 6);
if (pProcMem->WriteProcMem(BaseAddr, byte) == false)
return false;
return true;
}
bool DSHack::ToggleAI(BYTE* BaseAddr, bool bEnable)
{
BYTE byte;
Memory* pProcMem = Memory::GetInstance();
BaseAddr = BaseAddr + 0x9 + 0x4;
//if (pProcMem->ReadProcMem(BaseAddr, byte) == false)
// return false;
byte = (bEnable ? 0 : 1);
if (pProcMem->WriteProcMem(BaseAddr, byte) == false)
return false;
return true;
}
bool DSHack::IncrementZPos(BYTE* BaseAddr, float fValue)
{
float fBaseValue = 0;
Memory* pProcMem = Memory::GetInstance();
if (pProcMem->ReadProcMem(BaseAddr, BaseAddr) == false)
return false;
BaseAddr += 0x40;
if (pProcMem->ReadProcMem(BaseAddr, BaseAddr) == false)
return false;
BaseAddr += 0x28;
if (pProcMem->ReadProcMem(BaseAddr, BaseAddr) == false)
return false;
BaseAddr += 0x84;
if (pProcMem->ReadProcMem(BaseAddr, fBaseValue) == false)
return false;
fBaseValue += fValue;
if (pProcMem->WriteProcMem(BaseAddr, fBaseValue) == false)
return false;
return true;
}
| [
"danilo_cej@hotmail.com"
] | danilo_cej@hotmail.com |
3597fad6b2a9479fb0a875b1a5435f56e513def3 | 3095db2b8eb39c560c1ea5918492b015a975e2c5 | /data_logger_oshawa_exp20180530/catkin_ws (20180530)/devel/include/dji_sdk/MissionWpGetSpeedRequest.h | 47a068d3628befac3e530a49e2e3ff06f87714a3 | [] | no_license | jungwonkang/qdrone_all | 7a1b689a4576452749eeb971a1a98d9911c4bb48 | 6d3c4e12450c43f427d0203aa3632e83c0085ed2 | refs/heads/master | 2021-06-12T12:41:11.179182 | 2021-03-08T17:42:59 | 2021-03-08T17:42:59 | 157,916,901 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,232 | h | // Generated by gencpp from file dji_sdk/MissionWpGetSpeedRequest.msg
// DO NOT EDIT!
#ifndef DJI_SDK_MESSAGE_MISSIONWPGETSPEEDREQUEST_H
#define DJI_SDK_MESSAGE_MISSIONWPGETSPEEDREQUEST_H
#include <string>
#include <vector>
#include <map>
#include <ros/types.h>
#include <ros/serialization.h>
#include <ros/builtin_message_traits.h>
#include <ros/message_operations.h>
namespace dji_sdk
{
template <class ContainerAllocator>
struct MissionWpGetSpeedRequest_
{
typedef MissionWpGetSpeedRequest_<ContainerAllocator> Type;
MissionWpGetSpeedRequest_()
{
}
MissionWpGetSpeedRequest_(const ContainerAllocator& _alloc)
{
(void)_alloc;
}
typedef boost::shared_ptr< ::dji_sdk::MissionWpGetSpeedRequest_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::dji_sdk::MissionWpGetSpeedRequest_<ContainerAllocator> const> ConstPtr;
}; // struct MissionWpGetSpeedRequest_
typedef ::dji_sdk::MissionWpGetSpeedRequest_<std::allocator<void> > MissionWpGetSpeedRequest;
typedef boost::shared_ptr< ::dji_sdk::MissionWpGetSpeedRequest > MissionWpGetSpeedRequestPtr;
typedef boost::shared_ptr< ::dji_sdk::MissionWpGetSpeedRequest const> MissionWpGetSpeedRequestConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::dji_sdk::MissionWpGetSpeedRequest_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::dji_sdk::MissionWpGetSpeedRequest_<ContainerAllocator> >::stream(s, "", v);
return s;
}
} // namespace dji_sdk
namespace ros
{
namespace message_traits
{
// BOOLTRAITS {'IsFixedSize': True, 'IsMessage': True, 'HasHeader': False}
// {'nav_msgs': ['/opt/ros/kinetic/share/nav_msgs/cmake/../msg'], 'dji_sdk': ['/home/york1/catkin_ws/src/vai_uav0/dji_sdk/msg'], 'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg'], 'actionlib_msgs': ['/opt/ros/kinetic/share/actionlib_msgs/cmake/../msg'], 'sensor_msgs': ['/opt/ros/kinetic/share/sensor_msgs/cmake/../msg'], 'geometry_msgs': ['/opt/ros/kinetic/share/geometry_msgs/cmake/../msg']}
// !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types']
template <class ContainerAllocator>
struct IsFixedSize< ::dji_sdk::MissionWpGetSpeedRequest_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::dji_sdk::MissionWpGetSpeedRequest_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::dji_sdk::MissionWpGetSpeedRequest_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::dji_sdk::MissionWpGetSpeedRequest_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::dji_sdk::MissionWpGetSpeedRequest_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct HasHeader< ::dji_sdk::MissionWpGetSpeedRequest_<ContainerAllocator> const>
: FalseType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::dji_sdk::MissionWpGetSpeedRequest_<ContainerAllocator> >
{
static const char* value()
{
return "d41d8cd98f00b204e9800998ecf8427e";
}
static const char* value(const ::dji_sdk::MissionWpGetSpeedRequest_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0xd41d8cd98f00b204ULL;
static const uint64_t static_value2 = 0xe9800998ecf8427eULL;
};
template<class ContainerAllocator>
struct DataType< ::dji_sdk::MissionWpGetSpeedRequest_<ContainerAllocator> >
{
static const char* value()
{
return "dji_sdk/MissionWpGetSpeedRequest";
}
static const char* value(const ::dji_sdk::MissionWpGetSpeedRequest_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::dji_sdk::MissionWpGetSpeedRequest_<ContainerAllocator> >
{
static const char* value()
{
return "\n\
";
}
static const char* value(const ::dji_sdk::MissionWpGetSpeedRequest_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::dji_sdk::MissionWpGetSpeedRequest_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream&, T)
{}
ROS_DECLARE_ALLINONE_SERIALIZER
}; // struct MissionWpGetSpeedRequest_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::dji_sdk::MissionWpGetSpeedRequest_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream&, const std::string&, const ::dji_sdk::MissionWpGetSpeedRequest_<ContainerAllocator>&)
{}
};
} // namespace message_operations
} // namespace ros
#endif // DJI_SDK_MESSAGE_MISSIONWPGETSPEEDREQUEST_H
| [
"kctown99@gmail.com"
] | kctown99@gmail.com |
9cd81ff95d210270ba2e04933269638a4ec27d5b | 22a3c9eb93158534a9300018a17bb7caa18eb42a | /egen/inc/threading.h | 7404bd57de771185cdeec0051f7817195639563c | [
"Artistic-1.0"
] | permissive | shunyuchu/dbt5-0.1.0 | 38fabd5e55806fc14198a221c1b95d714d783fd8 | 8ebd9787edf448ff2eb7e277257b95b888098860 | refs/heads/master | 2023-05-07T17:11:06.956696 | 2021-05-26T09:52:52 | 2021-05-26T09:52:52 | 370,978,208 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,408 | h | /*
* Legal Notice
*
* This document and associated source code (the "Work") is a part of a
* benchmark specification maintained by the TPC.
*
* The TPC reserves all right, title, and interest to the Work as provided
* under U.S. and international laws, including without limitation all patent
* and trademark rights therein.
*
* No Warranty
*
* 1.1 TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THE INFORMATION
* CONTAINED HEREIN IS PROVIDED "AS IS" AND WITH ALL FAULTS, AND THE
* AUTHORS AND DEVELOPERS OF THE WORK HEREBY DISCLAIM ALL OTHER
* WARRANTIES AND CONDITIONS, EITHER EXPRESS, IMPLIED OR STATUTORY,
* INCLUDING, BUT NOT LIMITED TO, ANY (IF ANY) IMPLIED WARRANTIES,
* DUTIES OR CONDITIONS OF MERCHANTABILITY, OF FITNESS FOR A PARTICULAR
* PURPOSE, OF ACCURACY OR COMPLETENESS OF RESPONSES, OF RESULTS, OF
* WORKMANLIKE EFFORT, OF LACK OF VIRUSES, AND OF LACK OF NEGLIGENCE.
* ALSO, THERE IS NO WARRANTY OR CONDITION OF TITLE, QUIET ENJOYMENT,
* QUIET POSSESSION, CORRESPONDENCE TO DESCRIPTION OR NON-INFRINGEMENT
* WITH REGARD TO THE WORK.
* 1.2 IN NO EVENT WILL ANY AUTHOR OR DEVELOPER OF THE WORK BE LIABLE TO
* ANY OTHER PARTY FOR ANY DAMAGES, INCLUDING BUT NOT LIMITED TO THE
* COST OF PROCURING SUBSTITUTE GOODS OR SERVICES, LOST PROFITS, LOSS
* OF USE, LOSS OF DATA, OR ANY INCIDENTAL, CONSEQUENTIAL, DIRECT,
* INDIRECT, OR SPECIAL DAMAGES WHETHER UNDER CONTRACT, TORT, WARRANTY,
* OR OTHERWISE, ARISING IN ANY WAY OUT OF THIS OR ANY OTHER AGREEMENT
* RELATING TO THE WORK, WHETHER OR NOT SUCH AUTHOR OR DEVELOPER HAD
* ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES.
*
* Contributors
* - Chris Chan-nui, Matt Emmerton
*/
#ifndef THREADING_H_INCLUDED
#define THREADING_H_INCLUDED
#include <memory>
#include <sstream>
#include <stdexcept>
#include <string.h>
#include "EGenStandardTypes.h"
namespace TPCE
{
// Base class to provide a run() method for objects which can be threaded.
// This is required because under pthreads we have to provide an interface
// through a C ABI call, which we can't do with templated classes.
class ThreadBase
{
public:
virtual ~ThreadBase();
virtual void invoke() = 0;
};
// Call the run() method of passed argument. Always returns NULL.
#ifdef WIN32
DWORD WINAPI start_thread(LPVOID arg);
#else
extern "C"
void* start_thread(void *arg);
#endif
// Template to wrap around a class that has a ThreadBase::run() method and
// spawn it in a thread of its own.
template<typename T>
class Thread : public ThreadBase
{
private:
std::auto_ptr<T> obj_;
TThread tid_;
public:
Thread(std::auto_ptr<T> throbj)
: obj_(throbj)
, tid_()
{
}
T* obj() {
return obj_.get();
}
void invoke() {
obj_->run(this);
}
void start();
void stop();
};
//////////////////////////////////////////////////////////
// Windows Implementation
//////////////////////////////////////////////////////////
#ifdef WIN32
template<typename T>
void Thread<T>::start()
{
tid_ = CreateThread(NULL, 0, start_thread, this, NULL, NULL);
if (tid_ == NULL) {
std::ostringstream strm;
strm << "CreateThread error: " << GetLastError();
throw std::runtime_error(strm.str());
}
}
template<typename T>
void Thread<T>::stop()
{
DWORD rc = WaitForSingleObject(tid_, INFINITE);
if (rc != 0) {
std::ostringstream strm;
strm << "WaitForSingleObject error: " << GetLastError();
throw std::runtime_error(strm.str());
}
}
//////////////////////////////////////////////////////////
// Non-Windows (pthread) Implementation
//////////////////////////////////////////////////////////
#else
template<typename T>
void Thread<T>::start()
{
int rc = pthread_create(&tid_, NULL, start_thread, this);
if (rc != 0) {
std::ostringstream strm;
strm << "pthread_create error: " << strerror(rc) << "(" << rc << ")";
throw std::runtime_error(strm.str());
}
}
template<typename T>
void Thread<T>::stop()
{
int rc = pthread_join(tid_, NULL);
if (rc != 0) {
std::ostringstream strm;
strm << "pthread_join error: " << strerror(rc) << "(" << rc << ")";
throw std::runtime_error(strm.str());
}
}
#endif
}
#endif // THREADING_H_INCLUDED
| [
"15773206420@163.com"
] | 15773206420@163.com |
65524a710a7f4170d666cc0fa1e835187279730d | 84d52febd9b12019ae5426e4d80c3f524d772d79 | /test/App.hpp | 5e142f7d532d4a8bfdd46c1b40a31db057736b83 | [
"Apache-2.0"
] | permissive | tcoppex/cudaraster-linux | 0878114422800689b91953afa5a9d33ac9e4ed1e | a0112e1301fca8e5313098f13b27e6f2d7683a7f | refs/heads/master | 2020-05-29T19:19:38.302688 | 2012-05-18T12:00:28 | 2012-05-18T12:00:28 | 4,181,585 | 6 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 2,128 | hpp | #ifndef APP_HPP
#define APP_HPP
#include "engine/Application.hpp"
#include "engine/Camera.hpp"
#include "SceneCR.hpp"
#include "SceneGL.hpp"
/// =========================================
/// Sample application to test the cudaraster
/// port.
/// =========================================
class App : public Application
{
private:
/// Defines the rendering mode
enum Mode
{
MODE_CUDARASTER = 0,
MODE_OPENGL,
NUM_MODE
};
public:
/// Default window's resolution
/// (must be a multiple of CR_TILE_SIZE)
static const int kScreenWidth = 720;
static const int kScreenHeight = 480;
/// Default shaders' path
static const char* kShadersPath;
/// Holds rendering states
static struct RenderState
{
bool bTexturing;
bool bDepth;
bool bBlend;
bool bLerp;
bool bQuads;
int numSamples;
RenderState()
: bTexturing(false),
bDepth(true),
bBlend(false),
bLerp(false),
bQuads(false),
numSamples(1)
{}
} kState;
private:
/// Rendering mode
Mode m_mode;
/// Free-view camera
Camera m_camera;
/// CudaRaster scene handler
SceneCR m_sceneCR;
/// OpenGL scene handler
SceneGL m_sceneGL;
public:
App()
: Application(),
m_mode(MODE_OPENGL)
{}
virtual ~App();
// ++ Overrided Listener methods ++
virtual void reshape(int w, int h);
virtual void display();
virtual void keyboard( unsigned char key, int x, int y);
virtual void special( int key, int x, int y);
virtual void specialUp( int key, int x, int y);
virtual void mouse(int button, int state, int x, int y);
virtual void motion(int x, int y);
virtual void idle();
private:
/// Redefines the context (window + event) creation
virtual void _initContext(int argc, char *argv[]);
/// Redefines the generic datas initialization
virtual void _initObject( int argc, char *argv[]);
};
#endif //APP_HPP
| [
"thibault.coppex@gmail.com"
] | thibault.coppex@gmail.com |
bb029a2b62c01ad1ec2c14ebd6f2b3326b445c2f | 4ec188d31f0b6e89b20302d39dccf02a6c0927af | /tests/application/matchthree/stateerasematches.cpp | c2e6e002c7fb0d79469184945142cf0d8aff9bd6 | [
"Apache-2.0"
] | permissive | huiyugan/gincu | 85ed66099a536228039e7d1d93468fae81aca8d9 | dd9d83cc75561d873fc396d009436ba07219ff4d | refs/heads/master | 2021-09-19T13:15:59.203463 | 2018-07-28T05:46:42 | 2018-07-28T05:46:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,114 | cpp | #include "matchthree/stateerasematches.h"
#include "matchthree/matchthreestates.h"
#include "matchthree/matchthreeboard.h"
#include "matchthree/matchthreechess.h"
#include "matchthree/componentchess.h"
#include "matchthree/scenematchthree.h"
#include "gincu/ecs/gentity.h"
#include "gincu/ecs/gcomponenttransform.h"
#include "gincu/gstatemachine.h"
#include "cpgf/tween/gtweenlist.h"
#include "cpgf/tween/easing/quad.h"
#include "cpgf/accessor/gaccessor.h"
namespace gincu {
StateEraseMatches::StateEraseMatches(SceneMatchThree * scene, const int stateId, const int nextStateId)
: super(stateId, nextStateId), scene(scene)
{
}
StateEraseMatches::~StateEraseMatches()
{
}
void StateEraseMatches::doOnEnter()
{
if(this->doFindAllMatches()) {
this->animateToDisappear();
}
else {
this->finish();
}
}
void StateEraseMatches::doOnExit()
{
this->matchedColumnRows.clear();
}
bool StateEraseMatches::doFindAllMatches()
{
bool hasMatches = false;
MatchThreeBoard * board = this->scene->getBoard();
const int rowCount = board->getRowCount();
const int columnCount = board->getColumnCount();
this->matchedColumnRows.clear();
this->matchedColumnRows.resize(columnCount);
for(int row = 0; row < rowCount; ++row) {
ComponentChess * chess1 = board->getChessAt(RowColumn { row, 0 })->getComponentByType<ComponentChess>();
ComponentChess * chess2 = board->getChessAt(RowColumn { row, 1 })->getComponentByType<ComponentChess>();
bool isFirst = true;
for(int column = 2; column < columnCount; ++column) {
ComponentChess * chess3 = board->getChessAt(RowColumn { row, column })->getComponentByType<ComponentChess>();
if(chess1->getColor() == chess2->getColor() && chess2->getColor() == chess3->getColor()) {
hasMatches = true;
if(isFirst) {
this->matchedColumnRows[column - 1].insert(row);
this->matchedColumnRows[column - 2].insert(row);
isFirst = false;
}
this->matchedColumnRows[column].insert(row);
}
else {
isFirst = true;
}
chess1 = chess2;
chess2 = chess3;
}
}
for(int column = 0; column < columnCount; ++column) {
ComponentChess * chess1 = board->getChessAt(RowColumn { 0, column })->getComponentByType<ComponentChess>();
ComponentChess * chess2 = board->getChessAt(RowColumn { 1, column })->getComponentByType<ComponentChess>();
bool isFirst = true;
for(int row = 2; row < rowCount; ++row) {
ComponentChess * chess3 = board->getChessAt(RowColumn { row, column })->getComponentByType<ComponentChess>();
if(chess1->getColor() == chess2->getColor() && chess2->getColor() == chess3->getColor()) {
hasMatches = true;
if(isFirst) {
this->matchedColumnRows[column].insert(row - 1);
this->matchedColumnRows[column].insert(row - 2);
isFirst = false;
}
this->matchedColumnRows[column].insert(row);
}
else {
isFirst = true;
}
chess1 = chess2;
chess2 = chess3;
}
}
return hasMatches;
}
void StateEraseMatches::finishedMatch()
{
this->getStateMachine()->gotoState(stateCheckEraseMatches);
}
void StateEraseMatches::animateToDisappear()
{
MatchThreeBoard * board = this->scene->getBoard();
cpgf::GTween & tween = this->scene->getTweenList()->tween()
.duration(200)
.ease(cpgf::QuadEase::easeIn())
.onComplete(cpgf::makeCallback(this, &StateEraseMatches::fullfilNewChesses))
;
for(int column = 0; column < (int)this->matchedColumnRows.size(); ++column) {
const std::set<int> & rowSet = this->matchedColumnRows[column];
for(auto it = rowSet.begin(); it != rowSet.end(); ++it) {
const int row = *it;
GEntity * chess = board->getChessAt(RowColumn { row, column });
GComponentTransform * transform = chess->getComponentByType<GComponentTransform>();
tween.target(cpgf::createAccessor(transform, &GComponentTransform::getScale, &GComponentTransform::setScale), GScale { 0.1f, 0.1f });
}
}
}
void StateEraseMatches::fullfilNewChesses()
{
MatchThreeBoard * board = this->scene->getBoard();
const int rowCount = board->getRowCount();
cpgf::GTween & tween = this->scene->getTweenList()->tween()
.duration(300)
.ease(cpgf::QuadEase::easeIn())
.onComplete(cpgf::makeCallback(this, &StateEraseMatches::finishedMatch))
;
int matchedCount = 0;
for(int column = 0; column < (int)this->matchedColumnRows.size(); ++column) {
const std::set<int> & rowSet = this->matchedColumnRows[column];
for(auto it = rowSet.rbegin(); it != rowSet.rend(); ++it) {
++matchedCount;
board->removeChess(RowColumn { *it, column });
}
}
const int score = 20 + (matchedCount - 3) * 10;
scene->gotScore(score);
for(int column = 0; column < (int)this->matchedColumnRows.size(); ++column) {
const std::set<int> & rowSet = this->matchedColumnRows[column];
int previousCheckedRow = rowCount;
for(int row = rowCount - 1; row >= 0; --row) {
const RowColumn currentCell { row, column };
if(board->getChessAt(currentCell) != nullptr) {
continue;
}
if(previousCheckedRow > row) {
previousCheckedRow = row;
}
--previousCheckedRow;
while(previousCheckedRow >= 0) {
if(rowSet.find(previousCheckedRow) == rowSet.end()) {
break;
}
--previousCheckedRow;
}
GEntity * fullfilChess = nullptr;
if(previousCheckedRow >= 0) {
fullfilChess = board->swapChess(RowColumn { previousCheckedRow, column }, nullptr);
board->swapChess(currentCell, fullfilChess);
}
else {
fullfilChess = board->createChessAt(currentCell, randomChessColor());
}
GComponentTransform * transform = fullfilChess->getComponentByType<GComponentTransform>();
if(previousCheckedRow < 0) {
transform->setPosition(board->getChessPositionAt(RowColumn { -1, column }));
}
const GPoint position = board->getChessPositionAt(currentCell);
tween.target(cpgf::createAccessor(transform, &GComponentTransform::getPosition, &GComponentTransform::setPosition), position);
}
}
}
} //namespace gincu
| [
"wqking@outlook.com"
] | wqking@outlook.com |
d2b1aa80165fad97c88849f152979cebb6700281 | 16eb70ea061d94d6de9612444cfb637ded1083cc | /Tree/Convert_inorder+preorder_to_tree.cpp | a956b2b2f19b8e7511452c6dd32c2724416a1944 | [] | no_license | TheDangerD0802/30-Days-Coding-Challenge---WCC | 7e8bfd8db56630a9e7a6f718e8c42f696f377c0e | a61cc7fc0940e42b6b98cdd5c36417e8bc77092a | refs/heads/main | 2023-06-21T00:04:36.070991 | 2021-07-19T12:48:55 | 2021-07-19T12:48:55 | 378,089,850 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 510 | cpp | class Solution{
public:
int search(int in[], int k, int n)
{
for(int i=0;i<n;i++)
{
if(in[i]==k)
return i;
}
}
Node* buildTree(int in[],int pre[], int n)
{
if(n==0)
return NULL;
Node *temp = new Node(pre[0]);
int i = search(in,pre[0],n);
temp->left = buildTree(in,pre+1,i);
temp->right = buildTree(in+i+1,pre+i+1,n-i-1);
return temp;
}
}; | [
"noreply@github.com"
] | noreply@github.com |
875ad20e1b8795e863729e386a804dcc4d38a77b | 888069a1e783463b21b851cda5e58fe47ae2f543 | /CGProyect/Line.cpp | 02a0e7c1912d1f5b8f839c310c85cf1071ae8da2 | [] | no_license | franjaviersans/MyPaint | 0ff02a6f9b70529cc75335fdf67c23c891a7056a | 3deffe7ee2474872f586e4dfdf4066638f516d66 | refs/heads/master | 2016-09-05T19:14:51.804588 | 2014-11-12T20:58:20 | 2014-11-12T20:58:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,038 | cpp | #include "stdafx.h"
#include "Line.h"
#include <iostream>
CLine::CLine()
{
m_p1.x = m_p1.y = 0;
m_p2.x = m_p2.y = 0;
m_id = IM_LINE;
m_bgcolor = 0;
m_linecolor = 0;
m_filled = false;
}
void CLine::DrawLine(POINT p0, POINT p1, CBackBuffer *pDC, COLORREF color, int draw){
if(draw != 0){
bool invert = false;
int dx, dy, x, y, d, IncD1, IncD2, inc1 = 1, inc2 = 0;
if(abs(p1.x - p0.x) < abs(p1.y - p0.y)){
std::swap(p0.x,p0.y);
std::swap(p1.x,p1.y);
invert = true;
}
if(p1.x <= p0.x)
std::swap(p1, p0);
dx = p1.x - p0.x;
dy = p1.y - p0.y;
if(dy <= 0){
dx = -dx;
IncD2 = - (dy << 1);
IncD1 = (dx - dy) << 1;
inc2 = -1;
inc1 = 0;
}else{
d = dx - (dy << 1);
IncD1 = - (dy << 1);
IncD2 = (dx - dy) << 1;
}
d = dx - (dy << 1);
x = p0.x;
y = p0.y;
//Normal draw
if(draw == 2)
if(!invert) pDC->SetPixel(x, y, color);
else pDC->SetPixel(y, x, color);
else //Secure draw
if(!invert) pDC->SetPixelSecured(x, y, color);
else pDC->SetPixelSecured(y, x, color);
while(x < p1.x){
if(d <= 0){
d += IncD2;
y += inc1;
}else{
d += IncD1;
y += inc2;
}
++x;
//Normal draw
if(draw == 2)
if(!invert) pDC->SetPixel(x, y, color);
else pDC->SetPixel(y, x, color);
else //Secure draw
if(!invert) pDC->SetPixelSecured(x, y, color);
else pDC->SetPixelSecured(y, x, color);
}
}
}
void CLine::DrawDottedLine(POINT p0, POINT p1, CBackBuffer *pDC, COLORREF color, int draw){
if(draw != 0){
boolean mask[] = {true,true,true,false,false,false,true,true,true,false,false,false};
int masksize = 12, maskind = 0;
bool invert = false;
int dx, dy, x, y, d, IncD1, IncD2, inc1 = 1, inc2 = 0;
if(abs(p1.x - p0.x) < abs(p1.y - p0.y)){
std::swap(p0.x,p0.y);
std::swap(p1.x,p1.y);
invert = true;
}
if(p1.x <= p0.x)
std::swap(p1, p0);
dx = p1.x - p0.x;
dy = p1.y - p0.y;
if(dy <= 0){
dx = -dx;
IncD2 = - (dy << 1);
IncD1 = (dx - dy) << 1;
inc2 = -1;
inc1 = 0;
}else{
d = dx - (dy << 1);
IncD1 = - (dy << 1);
IncD2 = (dx - dy) << 1;
}
d = dx - (dy << 1);
x = p0.x;
y = p0.y;
//Normal draw
if(draw == 2)
if(!invert) pDC->SetPixel(x, y, color);
else pDC->SetPixel(y, x, color);
else //Secure draw
if(!invert) pDC->SetPixelSecured(x, y, color);
else pDC->SetPixelSecured(y, x, color);
while(x < p1.x){
if(d <= 0){
d += IncD2;
y += inc1;
}else{
d += IncD1;
y += inc2;
}
++x;
if(mask[maskind]){
//Normal draw
if(draw == 2)
if(!invert) pDC->SetPixel(x, y, color);
else pDC->SetPixel(y, x, color);
else //Secure draw
if(!invert) pDC->SetPixelSecured(x, y, color);
else pDC->SetPixelSecured(y, x, color);
}
maskind = (maskind++) % masksize;
}
}
}
void CLine::OnDraw(CBackBuffer *pDC, POINT WindowsSize)
{
POINT p0, p1;
p0.x = (int)m_p1.x;
p0.y = (int)m_p1.y;
p1.x = (int)m_p2.x;
p1.y = (int)m_p2.y;
int draw;
//Check if the figure is inside the drawing area
if(max(p0.x,p1.x) < 0 || min(p0.x,p1.x) >= WindowsSize.x || max(p0.y,p1.y) < 0 || min(p0.y,p1.y) >= WindowsSize.y) draw = 0;
else if(p0.x >= 0 && p0.x < WindowsSize.x && p0.y >= 0 && p0.y < WindowsSize.y && p1.x >= 0 && p1.x < WindowsSize.x && p1.y >= 0 && p1.y < WindowsSize.y) draw = 2;
else draw = 1;
CLine::DrawLine(p0, p1, pDC, m_linecolor, draw);
}
void CLine::Serialize(CArchive& ar)
{
if (ar.IsStoring())
{
ar << m_id;
ar << m_bgcolor;
ar << m_linecolor;
ar << m_filled;
ar << m_p1.x;
ar << m_p1.y;
ar << m_p2.x;
ar << m_p2.y;
}
else
{
ar >> m_bgcolor;
ar >> m_linecolor;
ar >> m_filled;
ar >> m_p1.x;
ar >> m_p1.y;
ar >> m_p2.x;
ar >> m_p2.y;
}
}
void CLine::DrawSelected(CBackBuffer *pDC, POINT WindowsSize){
POINT p0, p1;
p0.x = (int)m_p1.x;
p0.y = (int)m_p1.y;
p1.x = (int)m_p2.x;
p1.y = (int)m_p2.y;
CColor other(255, 100, 0);
pDC->Rectangle(p0.x - 5, p0.y - 5, p0.x + 5, p0.y + 5,other.ToCOLORREF());
pDC->Rectangle(p1.x - 5, p1.y - 5, p1.x + 5, p1.y + 5,other.ToCOLORREF());
}
bool CLine::Intersect(POINT p){
double epsilon = 4;
CPOINT2F p1, p0;
p0.x = min(m_p2.x, m_p1.x);
p0.y = min(m_p2.y, m_p1.y);
p1.x = max(m_p2.x, m_p1.x);
p1.y = max(m_p2.y, m_p1.y);
float dx = m_p2.x - m_p1.x, dy = m_p2.y - m_p1.y;
return (abs((p.x - m_p1.x) * dy - (p.y - m_p1.y) * dx) / sqrt(dx * dx + dy * dy) <= epsilon)
&& (p0.x <= p.x && p.x <= p1.x)
&& (p0.y <= p.y && p.y <= p1.y);
}
CPOINT2F* CLine::IntersectControlPoint(POINT p){
double epsilon = 4;
if(abs(p.x - m_p1.x) <= epsilon && abs(p.y - m_p1.y) <= epsilon)
return &m_p1;
if(abs(p.x - m_p2.x) <= epsilon && abs(p.y - m_p2.y) <= epsilon)
return &m_p2;
return NULL;
}
void CLine::Translate(POINT p){
m_p1.x += p.x;
m_p1.y += p.y;
m_p2.x += p.x;
m_p2.y += p.y;
}
void CLine::ChangeFillColor(COLORREF c){
m_bgcolor = c;
}
void CLine::ChangeLineColor(COLORREF c){
m_linecolor = c;
}
void CLine::ChangeFilled(){
m_filled = !m_filled;
} | [
"franjaviersans@gmail.com"
] | franjaviersans@gmail.com |
7d658089bd62c47a16cedd422bb848e5519185ef | 1e55f7f495a55a1902de2c10d4a763ac3e6ef412 | /rpg/dialogue.hpp | 42f2879d84b259840a6a08353cd6c081393f5b9a | [] | no_license | formula1/graphic_test_cpp | 536a616b2c80861c817a1dc6938b29ed653b8ea0 | 58b04bbf5806ed2c42b9d748ec5cfc0c1e814a3b | refs/heads/master | 2021-01-18T14:57:07.270865 | 2015-07-14T17:40:38 | 2015-07-14T17:40:38 | 39,032,370 | 0 | 0 | null | 2015-07-13T19:19:23 | 2015-07-13T19:19:23 | null | UTF-8 | C++ | false | false | 1,017 | hpp | //
// dialogue.cpp
// rpg
//
// Created by Robert Wilkinson on 12/20/14.
// Copyright (c) 2014 Robert WIlkinson. All rights reserved.
//
#ifndef DIALOGUE_HPP
#define DIALOGUE_HPP
#include <stdio.h>
#include <iostream>
#include <string>
#include <vector>
// Gameplay uses dialogue
class Dialogue
{
private:
std::string description;
std::vector<std::string> choices;
public:
Dialogue(std::string description, std::vector<std::string> choices)
{
this->description = description;
this->choices = choices;
}
int activate()
{
std::cout << description << std::endl;
for (int i = 0; i < this->choices.size(); ++i) {
std::cout << i+1 << ": " << this->choices[i] << std::endl;
}
signed int userInput = -1;
while(true)
{
std::cin >> userInput;
if (userInput >= 0 && userInput <= choices.size()) {
return userInput;
}
}
return 0;
}
};
#endif
| [
"wilkinson.robert.a@gmail.com"
] | wilkinson.robert.a@gmail.com |
3c6a0adf988860bc1525e6fa21965852432c1716 | 77de5ed4ec4b67a20816894c5c1efafe3eae1f3f | /AstarPathfinder/Map.cpp | d52afe8dae6533c617823d1b704881b7f470f51e | [] | no_license | Steelbadger/PathfindingCoursework | 137f37556e8a29867a754ad0418228e315cbc65f | c9dbc16b398b1471b6fdf5ecfaf8e3a95b364919 | refs/heads/master | 2020-05-28T08:33:34.196301 | 2012-11-29T17:12:32 | 2012-11-29T17:12:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,770 | cpp | #include "Map.h"
#include "Node.h"
#include <iostream>
#include <time.h>
#include <queue>
Map::Map(void):
eNode(),
sNode()
{
Initialise(DEFAULT_SIZE, DEFAULT_SIZE);
}
Map::Map(int width, int height)
{
Initialise(width, height);
}
Map::~Map(void)
{
}
void Map::Initialise(int width, int height)
{
mWidth = width;
mHeight = height;
passable.resize(mWidth);
duplicates.resize(mWidth);
pathnodes.resize(mWidth);
nodes.resize(mWidth);
for (int i = 0; i < passable.size(); i++) {
passable[i].resize(mHeight);
duplicates[i].resize(mHeight);
nodes[i].resize(mHeight);
pathnodes[i].resize(mHeight);
}
for (int row = 0; row < height; ++row){
for (int col = 0; col < width; ++col){
passable[row][col] = true;
duplicates[row][col] = false;
nodes[row][col].Initialise(row, col);
pathnodes[row][col] = false;
}
}
}
void Map::SetStart(int x, int y)
{
workinglist.push(nodes[x][y]);
sNode.Initialise(x, y);
duplicates[x][y] = true;
std::cout << "Start at X: " << x << "\tY: " << y << std::endl;
}
void Map::SetEnd(int x, int y)
{
eNode.Initialise(x, y);
std::cout << "End at X: " << x << "\tY: " << y << std::endl;
}
bool Map::CheckDuplicates(int x, int y)
{
if (!duplicates[x][y] && passable[x][y])
return true;
else
return false;
}
void Map::AddToWListM(Node n, Node p)
{
if (CheckDuplicates(n.GetX(), n.GetY())) {
n.SetParent(p);
nodes[n.GetX()][n.GetY()].SetParent(p);
nodes[n.GetX()][n.GetY()].SetGDistance(p.GetGDistance() + 10);
nodes[n.GetX()][n.GetY()].SetHDistanceManhatten(eNode.GetX(), eNode.GetY());
workinglist.push(nodes[n.GetX()][n.GetY()]);
duplicates[n.GetX()][n.GetY()] = true;
}
}
void Map::AddToWListD(Node n, Node p)
{
if (CheckDuplicates(n.GetX(), n.GetY())) {
n.SetParent(p);
nodes[n.GetX()][n.GetY()].SetParent(p);
if (n.GetX() != p.GetX() && n.GetY() != p.GetY()) {
nodes[n.GetX()][n.GetY()].SetGDistance(p.GetGDistance() + 14);
} else {
nodes[n.GetX()][n.GetY()].SetGDistance(p.GetGDistance() + 10);
}
nodes[n.GetX()][n.GetY()].SetHDistanceDiagonal(eNode.GetX(), eNode.GetY());
workinglist.push(nodes[n.GetX()][n.GetY()]);
duplicates[n.GetX()][n.GetY()] = true;
}
}
int Map::FindPath()
{
unsigned long t;
t = clock();
bool foundEnd = false;
Node temp; //temporary value for calculation
if (!workinglist.empty()) { // Ensure the workinglist is not empty.
workinglist.top().SetHDistanceManhatten(eNode.GetX(), eNode.GetY()); // If it is empty then do not attempt to find
} else { // path and
return -3;
}
while(!workinglist.empty() && !foundEnd) //Move through working set checkin each node to see if
{ //it is the end node, if not then add it's neighbours to
temp = workinglist.top(); //the working set.
workinglist.pop();
if (temp == eNode) {
foundEnd = true;
} else {
if (temp.GetX() + 1 < mWidth)
AddToWListM(nodes[temp.GetX() + 1][temp.GetY()], temp);
if (temp.GetX() > 0)
AddToWListM(nodes[temp.GetX() - 1][temp.GetY()], temp);
if (temp.GetY() + 1 < mHeight)
AddToWListM(nodes[temp.GetX()][temp.GetY() + 1], temp);
if (temp.GetY() > 0)
AddToWListM(nodes[temp.GetX()][temp.GetY() - 1], temp);
}
}
if (foundEnd) //Once a route is found track back through parent references
{ //and add to stack for retrieval later, return 0 to indicate success.
while(temp != sNode)
{
path.push(temp);
temp = nodes[temp.ParentX()][temp.ParentY()];
}
seconds = ((double)(clock() - t) * 1000) / CLOCKS_PER_SEC;
return 0;
} else { //If no route is found return -2.
seconds = ((double)(clock() - t) * 1000) / CLOCKS_PER_SEC;
return -2;
}
}
int Map::FindPathUseDiagonals()
{
unsigned long t;
t = clock(); // Start timing the algorithm.
bool foundEnd = false;
Node temp; // Temporary value for calculation.
if (!workinglist.empty()) { // Ensure the workinglist is not empty.
workinglist.top().SetHDistanceDiagonal(eNode.GetX(), eNode.GetY()); // If it is empty then do not attempt to find
} else { // path and
return -3;
}
while(!workinglist.empty() && !foundEnd) // Move through working set checkin each node to see if
{ // it is the end node, if not then add it's neighbours to
temp = workinglist.top(); // the working set.
workinglist.pop();
if (temp == eNode) {
foundEnd = true;
} else {
if (temp.GetX() + 1 < mHeight)
AddToWListD(nodes[temp.GetX() + 1][temp.GetY()], temp);
if (temp.GetX() > 0)
AddToWListD(nodes[temp.GetX() - 1][temp.GetY()], temp);
if (temp.GetY() + 1 < mWidth)
AddToWListD(nodes[temp.GetX()][temp.GetY() + 1], temp);
if (temp.GetY() > 0)
AddToWListD(nodes[temp.GetX()][temp.GetY() - 1], temp);
if (temp.GetX() > 0 && temp.GetY() > 0)
AddToWListD(nodes[temp.GetX() - 1][temp.GetY() - 1], temp);
if (temp.GetX() + 1 < mHeight && temp.GetY() > 0)
AddToWListD(nodes[temp.GetX() + 1][temp.GetY() - 1], temp);
if (temp.GetX() + 1 < mHeight && temp.GetY() + 1 < mWidth)
AddToWListD(nodes[temp.GetX() + 1][temp.GetY() + 1], temp);
if (temp.GetX() > 0 && temp.GetY() + 1 < mWidth)
AddToWListD(nodes[temp.GetX() - 1][temp.GetY() + 1], temp);
}
}
if (foundEnd) // Once a route is found track back through parent references
{ // and add to stack for retrieval later, return 0 to indicate success.
while(temp != sNode)
{
path.push(temp);
temp = nodes[temp.ParentX()][temp.ParentY()];
}
seconds = ((double)(clock() - t)*1000) / CLOCKS_PER_SEC;
return 0;
} else { // If no route is found return -2.
seconds = ((double)(clock() - t)*1000) / CLOCKS_PER_SEC;
return -2;
}
}
void Map::ReturnPath()
{
Node temp;
while(!path.empty())
{
temp = path.top();
pathnodes[temp.GetX()][temp.GetY()] = true;
path.pop();
std::cout << "X: " << temp.GetX() << "\tY: " << temp.GetY() << std::endl;
}
}
void Map::SetImpassable(int x_pos, int y_pos)
{
passable[y_pos][x_pos] = false;
}
void Map::Draw(int size)
{
for (int i = 0; i < mHeight; i++){
for (int q = 0; q < mWidth; q++){
if (nodes[i][q] == sNode) {
std::cout << "S";
} else if (nodes[i][q] == eNode) {
std::cout << "T";
} else if (pathnodes[i][q]) {
std::cout << "P";
} else if (passable[i][q]) {
if (duplicates[i][q] && size < 11) {
std::cout << nodes[i][q].GetFDistance();
} else {
std::cout << " ";
}
} else {
std::cout << "X";
}
if (size < 11) {
std::cout << "\t";
}
}
if (size < 80) {
std::cout << std::endl;
}
}
} | [
"steelbadger@gmail.com"
] | steelbadger@gmail.com |
a629e0fa71493ae7401e9730991322f55dafbd57 | 410de6fc1ef54edbc4e7485a642bdaf69c44ae64 | /tests/DivideTwoIntegersTest.cpp | 33dd9dfe8de7b8128876a35c379618208a253b29 | [] | no_license | SaberQ/leetcode | 322092c03b036bee053c794ebaa3dafef413a5b3 | 63f8abb9c382a2cbcea1e0294746a37fc86a293e | refs/heads/master | 2020-12-11T09:30:23.950830 | 2015-10-13T08:01:24 | 2015-10-13T08:01:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,207 | cpp | #include "catch.hpp"
#include "DivideTwoIntegers.hpp"
#include <climits>
TEST_CASE("Divide Two Integers") {
DivideTwoIntegers s;
SECTION("Normal tests") {
REQUIRE(s.divide(9, 5) == (9 / 5));
REQUIRE(s.divide(10, 5) == (10 / 5));
REQUIRE(s.divide(11, 5) == (11 / 5));
REQUIRE(s.divide(-9, 5) == (-9 / 5));
REQUIRE(s.divide(10, -5) == (10 / -5));
REQUIRE(s.divide(-11, -5) == (-11 / -5));
}
SECTION("Zero tests") {
REQUIRE(s.divide(5, 0) == INT_MAX);
REQUIRE(s.divide(0, 5) == (0 / 5));
REQUIRE(s.divide(0, 0) == INT_MAX);
}
SECTION("Boundary tests") {
REQUIRE(s.divide(INT_MAX, 1) == INT_MAX);
REQUIRE(s.divide(INT_MAX, -1) == -INT_MAX);
REQUIRE(s.divide(1, INT_MAX) == 0);
REQUIRE(s.divide(1, -INT_MAX) == 0);
REQUIRE(s.divide(INT_MIN, 1) == INT_MIN);
REQUIRE(s.divide(INT_MIN, -1) == INT_MAX);
REQUIRE(s.divide(1, INT_MIN) == 0);
REQUIRE(s.divide(-1, INT_MIN) == 0);
}
SECTION("Speed tests") {
REQUIRE(s.divide(INT_MAX, 2) == (INT_MAX / 2));
REQUIRE(s.divide(INT_MAX, -2) == -(INT_MAX / 2));
REQUIRE(s.divide(INT_MIN, 2) == (INT_MIN / 2));
REQUIRE(s.divide(INT_MIN, -2) == (INT_MIN / -2));
}
}
| [
"yanzhe.cn@gmail.com"
] | yanzhe.cn@gmail.com |
dd94fe90cb4ae209f90ffc6c99e71d3426177455 | 743e45e6a5197cedd7381cce997c7fed280c5b3a | /C-examples/C++/mergesort/MergeSort.h | 144e5e0934aa6a3537d150ce3fc548b3abaab8de | [
"MIT"
] | permissive | sharihan/CS253-lab | c44650220c16bf7d9694e075de4b67cb4c5b5272 | e61c0bed6918dc830e7ed6b1703e27127c75e54f | refs/heads/master | 2021-01-18T05:24:14.028475 | 2015-02-25T22:06:51 | 2015-02-25T22:06:51 | 31,515,398 | 1 | 0 | null | 2015-03-01T23:43:39 | 2015-03-01T23:43:39 | null | UTF-8 | C++ | false | false | 2,578 | h |
#include <iostream>
using namespace std;
/**
Sorts an array of integer using mergesort.
*/
class MergeSort
{
public:
/**
Merges two adjacent subranges of an array
@param a the array with entries to be merged
@param from the index of the first element of the
first range
@param mid the index of the last element of the
first range
@param to the index of the last element of the
second range
*/
static void merge(int* a, int from, int mid, int to)
{
int n = to - from + 1;
// size of the range to be merged
// merge both halves into a temporary array b
int *b = new int[n];
int i1 = from;
// next element to consider in the first range
int i2 = mid + 1;
// next element to consider in the second range
int j = 0;
// next open position in b
// as long as neither i1 nor i2 past the end, move
// the smaller element into b
while (i1 <= mid && i2 <= to)
{ if (a[i1] < a[i2])
{ b[j] = a[i1];
i1++;
}
else
{ b[j] = a[i2];
i2++;
}
j++;
}
// note that only one of the two while loops
// below is executed
// copy any remaining entries of the first half
while (i1 <= mid)
{ b[j] = a[i1];
i1++;
j++;
}
// copy any remaining entries of the second half
while (i2 <= to)
{ b[j] = a[i2];
i2++;
j++;
}
// copy back from the temporary array
for (j = 0; j < n; j++)
a[from + j] = b[j];
}
/**
Sorts a range of an array, using the merge sort
algorithm.
@param a the array to sort
@param from the first index of the range to sort
@param to the last index of the range to sort
*/
static void mergeSort(int* a, int from, int to)
{
// return if only one element to sort
if (from == to) return;
int mid = (from + to) / 2;
// sort the first and the second half
mergeSort(a, from, mid);
mergeSort(a, mid + 1, to);
// merge the two sorted halves
merge(a, from, mid, to);
}
/**
Sorts an array, using the merge sort algorithm.
@param a the array to sort
*/
static void sort(int* a, int length)
{
mergeSort(a, 0, length - 1);
}
}; //MergeSort
// set vim: set ts=3:
| [
"shane@foundationcode.com"
] | shane@foundationcode.com |
b85a22f10463a2d7e238c63a6eb76b3a5016bff4 | ff9bdeb2f086e7e0f0dd3a8760334366f71efc2d | /visualstudio2019_Sample/project1/CloneObject/CloneObject.h | 0818b6019c5da803c414160b179cb73296ccd0a0 | [] | no_license | RyuyaMaki/visualstudio2019Practice | 5f9e12942f71bfed4a00456d243f4511125d2aaa | cd665f2eb2464c85bde08f0ae9d347ca8dd81d70 | refs/heads/master | 2022-12-04T23:00:50.616415 | 2020-08-28T05:46:30 | 2020-08-28T05:46:30 | 279,464,158 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 258 | h | #pragma once
#include "../Component/Component.h"
class CloneObject : public Component{
public:
CloneObject(int cloneNum);
void update() override;
void draw() override;
std::shared_ptr<Component> createClone() override;
private:
int m_cloneNumber;
};
| [
"ryuyan1030@gmail.com"
] | ryuyan1030@gmail.com |
94f5e1eb219b5ae41805919a843de0834d33f4f8 | dd6147bf9433298a64bbceb7fdccaa4cc477fba6 | /8304/sanizayyad/codes/headers/Attributes/Armor/mediumarmor.hpp | e661a2653bd27ad1b36d6b54aed0858fc1761e79 | [] | no_license | moevm/oop | 64a89677879341a3e8e91ba6d719ab598dcabb49 | faffa7e14003b13c658ccf8853d6189b51ee30e6 | refs/heads/master | 2023-03-16T15:48:35.226647 | 2020-06-08T16:16:31 | 2020-06-08T16:16:31 | 85,785,460 | 42 | 304 | null | 2023-03-06T23:46:08 | 2017-03-22T04:37:01 | C++ | UTF-8 | C++ | false | false | 467 | hpp |
#ifndef mediumarmor_hpp
#define mediumarmor_hpp
#include "armor.hpp"
#include <stdio.h>
class MediumArmor : public Armor
{
public:
explicit MediumArmor();
MediumArmor(const MediumArmor& armor);
MediumArmor& operator=(const MediumArmor& armor);
virtual std::shared_ptr<Armor> clone() const override;
virtual double getResistance() const override;
virtual std::string getAmorType() const override;
};
#endif /* mediumarmor_hpp */
| [
"sanizayyad99@gmaile.com"
] | sanizayyad99@gmaile.com |
aa65b09496ea2c24154b8b9d1747940dd868273e | dcab97ae22c4b935191dabc56024c657ab0a56e9 | /python code/find_face_landmarks-master/sfl_viewer/sfl_viewer_states.h | 2acc869b67ea92a8355416bc0048525ff3f63901 | [] | no_license | AkashSrivastava/PoseInvariantFaceRecognition | c2654bb006122b779172ad2f980040f443361497 | ad1acb6d08812c14284a50f449d5356eb8a4b126 | refs/heads/master | 2021-05-15T11:20:27.904135 | 2020-04-04T09:33:04 | 2020-04-04T09:33:04 | 108,314,331 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,097 | h | #ifndef __MAIN_WINDOW_STATES_H__
#define __MAIN_WINDOW_STATES_H__
// Boost
#include <boost/statechart/event.hpp>
#include <boost/statechart/state_machine.hpp>
#include <boost/statechart/state.hpp>
#include <boost/statechart/in_state_reaction.hpp>
#include <boost/statechart/transition.hpp>
#include <boost/statechart/custom_reaction.hpp>
#include <boost/mpl/list.hpp>
// Qt
#include <QtWidgets/QWidget>
namespace sc = boost::statechart;
namespace mpl = boost::mpl;
namespace sfl
{
// Forward declarations
struct Inactive;
struct Active;
struct Paused;
struct Playing;
class Viewer;
// State Machine
struct ViewerSM : sc::state_machine< ViewerSM, Inactive >
{
ViewerSM(Viewer* _viewer);
Viewer* viewer;
};
// Events
struct EvPlayPause : sc::event< EvPlayPause > {};
struct EvUpdate : sc::event< EvUpdate > {};
struct EvStart : sc::event< EvStart > {};
struct EvReset : sc::event< EvReset > {};
struct EvTimerTick : sc::event< EvTimerTick > {};
struct EvSeek : sc::event< EvSeek >
{
EvSeek(int _i) : i(_i) {}
int i;
};
// States
struct Inactive : sc::state<Inactive, ViewerSM>
{
Inactive(my_context ctx);
void onUpdate(const EvUpdate& event);
sc::result react(const EvStart&);
typedef mpl::list<
sc::in_state_reaction<EvUpdate, Inactive, (void(Inactive::*)(const EvUpdate&))(&Inactive::onUpdate)>,
sc::custom_reaction< EvStart > > reactions;
Viewer* viewer;
};
struct Active : sc::state<Active, ViewerSM, Paused>
{
Active(my_context ctx);
void onSeek(const EvSeek& event);
void onStart(const EvStart& event);
typedef mpl::list<
sc::in_state_reaction<EvSeek, Active, (void(Active::*)(const EvSeek&))(&Active::onSeek)>,
sc::in_state_reaction<EvStart, Active, (void(Active::*)(const EvStart&))(&Active::onStart)>,
sc::transition< EvReset, Inactive > > reactions;
Viewer* viewer;
};
struct Paused : sc::state<Paused, Active>
{
Paused(my_context ctx);
void onUpdate(const EvUpdate& event);
typedef mpl::list<
sc::in_state_reaction<EvUpdate, Paused, (void(Paused::*)(const EvUpdate&))(&Paused::onUpdate)>,
sc::transition< EvPlayPause, Playing > > reactions;
Viewer* viewer;
};
// States
struct Playing : sc::state<Playing, Active>
{
Playing(my_context ctx);
~Playing();
void onUpdate(const EvUpdate& event);
void onTimerTick(const EvTimerTick& event);
typedef mpl::list<
sc::in_state_reaction<EvUpdate, Playing, (void(Playing::*)(const EvUpdate&))(&Playing::onUpdate)>,
sc::in_state_reaction<EvTimerTick, Playing, (void(Playing::*)(const EvTimerTick&))(&Playing::onTimerTick)>,
sc::transition< EvPlayPause, Paused > > reactions;
Viewer* viewer;
int timer_id = 0;
};
} // namespace sfl
#endif // __MAIN_WINDOW_STATES_H__ | [
"akashsrivastava436@gmail.com"
] | akashsrivastava436@gmail.com |
147789ec16696d862f23d7a8d82bf1b9109d0a88 | 1a6819221332c39db47621bf527c2562f40a5bb5 | /SparCraft/source/deprecated/AlphaBetaSearchResults.hpp | 4bb7b0c2adf905e06bee920b6fc7dcdfac7ddaf0 | [
"MIT"
] | permissive | kant2002/ualbertabot | 6e372468ba686eea3439da14b26bffd0f4c95625 | b4c75be8bf023f289f2e58e49ad600a9bda38fcd | refs/heads/master | 2021-06-04T07:51:16.138136 | 2020-08-10T10:33:59 | 2020-08-10T10:33:59 | 95,999,080 | 2 | 1 | MIT | 2019-08-29T08:11:23 | 2017-07-02T03:02:04 | C++ | UTF-8 | C++ | false | false | 1,746 | hpp | #pragma once
#include <vector>
#include "Action.h"
namespace SparCraft
{
class AlphaBetaSearchResults
{
public:
bool solved, // whether ot not a solution was found
timedOut; // did the search time-out?
unsigned long long nodesExpanded; // number of nodes expanded in the search
double timeElapsed, // time elapsed in milliseconds
avgBranch; // avg branching factor
Move bestMoves;
double abValue;
unsigned long long ttcuts;
size_t maxDepthReached;
size_t ttMoveOrders;
size_t ttFoundButNoMove;
size_t ttFoundNoCut;
size_t ttFoundCheck;
size_t ttFoundLessDepth;
size_t ttSaveAttempts;
std::vector<std::vector<std::string> > _desc; // 2-column description vector
AlphaBetaSearchResults()
: solved(false)
, timedOut(false)
, nodesExpanded(0)
, timeElapsed(0)
, avgBranch(0)
, abValue(0)
, ttcuts(0)
, maxDepthReached(0)
, ttMoveOrders(0)
, ttFoundButNoMove(0)
, ttFoundNoCut(0)
, ttFoundCheck(0)
, ttFoundLessDepth(0)
, ttSaveAttempts(0)
{
}
std::vector<std::vector<std::string> > & getDescription()
{
_desc.clear();
_desc.push_back(std::vector<std::string>());
_desc.push_back(std::vector<std::string>());
std::stringstream ss;
_desc[0].push_back("Nodes Searched: ");
_desc[0].push_back("AB Value: ");
_desc[0].push_back("Max Depth: ");
ss << nodesExpanded; _desc[1].push_back(ss.str()); ss.str(std::string());
ss << abValue; _desc[1].push_back(ss.str()); ss.str(std::string());
ss << maxDepthReached; _desc[1].push_back(ss.str()); ss.str(std::string());
return _desc;
}
};
} | [
"dave.churchill@gmail.com"
] | dave.churchill@gmail.com |
c3ddd5de17dc257155a8f12b4278418b241fa59f | 3fc19c271eca0fbbb423aae28cb0ef53c0c3a291 | /atcoder/abc155/B.cpp | edb25abfd2b283e10215479503526ad9daa26956 | [] | no_license | tstanvir/mySolutionRepo | 09373dccc86ac8a6d1992a6761a81b98035a8977 | 0b635d689424bc8f55f0efd54ed028638d81a0e2 | refs/heads/master | 2023-08-11T01:53:53.320511 | 2021-05-22T18:06:00 | 2021-09-14T15:18:55 | 353,521,176 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,033 | cpp | /// Bismillahir Rahmanir Rahim
//Author: Tanvir Hussain
//ICE,NSTU
#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
const long long MOD = 1000000007;
#define SET(x) memset(x, 0, sizeof(x))
#define SET2d(x,m,n) memset(x, 0, sizeof(x[0][0]) * m * n)
#define SETBOOL(x) memset(x,false,sizeof(x))
#define CLR(x) memset(x, -1, sizeof(x))
#define mp make_pair
#define PII pair<int, int>
#define pf printf
#define sf scanf
#define ALL(x) x.begin(),x.end()
#define pb push_back
#define IOS ios::sync_with_stdio(false); cin.tie(0);
#define np std::string::npos
#define highest(x) numeric_limits<x>::max()
#define lowest(x) numeric_limits<x>::min()
#define Inf INFINITY
#define minv(v) *min_element(v.begin(),v.end())
#define maxv(v) *max_element(v.begin(),v.end())
#define cases(cs,t) for(int cs=1;cs<=t;cs++)
#define PI acos(-1)
#define no1 __builtin_popcount
#define BOUNDARY(i, j) ((i >= 0 && i < row) && (j >= 0 && j < column))
#define uniq(vec) vec.resize(distance(vec.begin(),unique(vec.begin(),vec.end())))
#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
#define sz(a) int(a.size())
#define ff first
#define ss second
#define endl "\n"
#define forch(it,s) for(auto it:s)
#define each(it,s) for(auto it = s.begin(); it != s.end(); ++it)
#define rep(i,a) for(int i=0; i<a;i++)
#define rep1(i,a,b) for(int i=(a);i<=(b);++i)
#define irep(i,b,a) for(int i=(b);i>=(a);--i)
#define bits(n) __builtin_popcount(n)
#define maxpq priority_queue<int>
#define minpq priority_queue<int, vector<int>, greater<int> >
int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a);}
typedef long long ll;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef vector<pair<int,int>> vpii;
typedef tree<pair<int, int>,null_type,less<pair<int, int>>,rb_tree_tag,tree_order_statistics_node_update> ordered_multiset;
int dx8[] = {0, 0, 1, 1, 1, -1, -1, -1};
int dy8[] = {1,-1, 1, -1, 0, 0, -1, 1};
int dx4[] = {0, 0, 1, -1};
int dy4[] = {1, -1, 0, 0};
const int maxx=100005;
//this fuction sorts vector pair according to first element in descending order.
bool sortinrev(const pair<int,int> &a,const pair<int,int> &b)
{
return a.first>b.first;
}
template<typename T>inline T Bigmod(T base, T power, T MOD){
T ret=1;
while(power)
{
if(power & 1)ret=(ret*base)%MOD;
base=(base*base)%MOD;
power>>=1;
}
return ret;
}
double sq(double x) {return x*x;}
void solve(){
int n;
cin>>n;
bool ok=1;
vi vec(n);
rep(i,n){
cin>>vec[i];
if(vec[i]%2==0){
ok&=(vec[i]%3==0 or vec[i]%5==0);
}
}
if(ok) cout<<"APPROVED"<<endl;
else cout<<"DENIED"<<endl;
}
signed main()
{
IOS;
/*#ifndef ONLINE_JUDGE
freopen ("data.in","r",stdin);
freopen ("data.out","w",stdout);
#endif*/
int t;
t=1;
while(t--){
solve();
}
return 0;
}
///Alhamdulillah
| [
"tanvirshossain0@gmail.com"
] | tanvirshossain0@gmail.com |
cc2b2bd2c5faa5bab4edaf32209072336bd4f485 | e6b5d019e565ce55b2febfbe21b82c2a21723385 | /TheWaySoFar-Training/2015-04-12/B.cpp | 990c00424ccf37cabc7c80190e40a6d6214419db | [] | no_license | Sd-Invol/shoka | a628f7e8544d8eb110014316ab16ef3aed7b7433 | 1281cb43501d9ef127a2c67aebfba1905229502b | refs/heads/master | 2023-06-06T07:23:09.496837 | 2023-05-13T14:46:23 | 2023-05-13T14:46:23 | 13,319,608 | 37 | 17 | null | null | null | null | UTF-8 | C++ | false | false | 1,097 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long LL;
int main() {
LL x1 , x2 , y2 , y1;
cin >> x1 >> y1 >> x2 >> y2;
if (x1 > x2) {
swap(x1 , x2);
swap(y1 , y2);
}
LL res = 1LL << 60;
LL dx = abs(x1 - x2);
LL dy = abs(y1 - y2);
res = min(res , max(3LL , dx + 1) + max(3LL , dy + 1) + 3);
if (y2 > y1) {
dx += 2 , dy += 2;
LL z = max(3LL , min(dx , dy) - 3);
LL x = dx - z;
LL y = dy - z;
res = min(res , max(3LL , x) + max(3LL , y) + z);
}
for (int i = 1 ; i <= 100 ; ++ i) {
LL y3 = y2 - i , x3 = x2 - i;
dx = abs(x1 - x3);
dy = abs(y1 - y3);
res = min(res , max(3LL , dx + 1) + max(3LL , dy + 1) + max(i + 1 , 3));
}
swap(x1 , x2);
swap(y1 , y2);
for (int i = 1 ; i <= 100 ; ++ i) {
LL y3 = y2 - i , x3 = x2 - i;
dx = abs(x1 - x3);
dy = abs(y1 - y3);
res = min(res , max(3LL , dx + 1) + max(3LL , dy + 1) + max(i + 1 , 3));
}
cout << res * 3 - 13 << endl;
return 0;
}
| [
"Sd.Invol@gmail.com"
] | Sd.Invol@gmail.com |
3caf6ba9f55652582a3b621f4ffbde76414b1f9e | 8c107970070d5f4708b29db47d828f62827dd0a9 | /CS201-L/Person.h | d7605509dcd04ca8a5b10eb0598b1cb6cd91bcdb | [] | no_license | baw5xc/CS-201-L | e17dabbed503eb3f548b979dd3e1624a52d8471d | 4d4bd581eec02e2fe1175c5c7c25c7bd0f9d50cf | refs/heads/master | 2020-06-03T18:19:28.394244 | 2013-07-30T16:55:18 | 2013-07-30T16:55:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 293 | h | #ifndef PERSON_
#define PERSON_
#include <iostream>
#include <string>
using namespace std;
class Person {
public:
Person(string name, string DOB)
{
name = "";
DOB = "";
}
void setName(string n);
void setDOB(string dob);
~Person();
private:
string name;
string DOB;
};
#endif | [
"baw5xc@KC-SCE462LAB-20.kc.umkc.edu"
] | baw5xc@KC-SCE462LAB-20.kc.umkc.edu |
d2fe0e918c81934b9db352c03bf67c3223e526d4 | f986e6aad322515718989ee337a8c1b5c7778466 | /Baekjoon/5063_TGN.cpp | 514671a8631de6bfad7557589a342f63f2e10c3e | [] | no_license | wh2per/Baekjoon-Algorithm | bf611ae9c87dfc1af3f66b79f0c2d21db75c0df1 | 04f721f59b497f81452216ff0becbc3a620bbd0c | refs/heads/master | 2021-11-24T09:23:31.327854 | 2021-11-11T05:56:54 | 2021-11-11T05:56:54 | 165,788,406 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 497 | cpp | #define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <algorithm>
#include <vector>
#include <climits>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
//freopen("input.txt", "r", stdin);
int n, r, e, c, i;
cin >> n;
while (n--) {
cin >> r >> e >> c;
if ((r + c) < e)
cout << "advertise\n";
else if ((r + c) > e)
cout << "do not advertise\n";
else if ((r + c) == e)
cout << "does not matter\n";
}
return 0;
} | [
"93negaro@gmail.com"
] | 93negaro@gmail.com |
9428d43e367b3375bfb2b8c1af679b2f499c8c9a | eb3736423d134739044e03b39902a06ca938deb9 | /Src/lunaui/lockscreen/LockWindow.cpp | 8e86250dfdaf3102a4058e30dad3e63061e776e8 | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | permissive | penk/luna-sysmgr | 663d46c3c3817908420e3b9c78e67329a523aa91 | 60c7056a734cdb55a718507f3a739839c9d74edf | refs/heads/master | 2021-01-23T21:11:21.070609 | 2012-09-20T23:43:09 | 2012-10-09T21:22:43 | 6,360,119 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 80,713 | cpp | /* @@@LICENSE
*
* Copyright (c) 2008-2012 Hewlett-Packard Development Company, L.P.
*
* 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.
*
* LICENSE@@@ */
#include "Common.h"
#include <string>
#include <cmath>
#include <map>
#include "LockWindow.h"
#include "Settings.h"
#include "HostBase.h"
#include "Localization.h"
#include "Preferences.h"
#include "WindowServerLuna.h"
#include "DashboardWindowManager.h"
#include "DashboardWindowContainer.h"
#include "DashboardWindow.h"
#include "Logging.h"
#include "MenuWindowManager.h"
#include "SystemUiController.h"
#include "SystemService.h"
#include "Security.h"
#include "EASPolicyManager.h"
#include "WebAppMgrProxy.h"
#include "AlertWindow.h"
#include "CardWindow.h"
#include "CoreNaviManager.h"
#include "Time.h"
#include "DisplayStates.h"
#include "DockModeWindowManager.h"
#include "BannerMessageHandler.h"
#include "AnimationSettings.h"
#include "GraphicsItemContainer.h"
#include "Utils.h"
#include "QtUtils.h"
#include "ClockWindow.h"
#include "IMEController.h"
#include "QmlInputItem.h"
#include <QPropertyAnimation>
#include <QTextLayout>
#include <QVector>
#include <QHash>
#include <QGraphicsPixmapItem>
#include <QPainterPath>
#include <QDeclarativeContext>
#include <QDeclarativeEngine>
// includes for the 9tile
#include "pixmaploader.h"
#include "pixmap9tileobject.h"
#define USE_CLIP_PATH // used only for dashboards, popups and banners have padding around them.
#define TOP_LEFT_CORNER 0
#define TOP_RIGHT_CORNER 1
#define BOTTOM_LEFT_CORNER 2
#define BOTTOM_RIGHT_CORNER 3
#define LOCK_BUTTON_OFFSET (0.1)
static unsigned int kTopPadding = 0;
static unsigned int kMaxWidth = 320; // From Larry
static const unsigned int kAlertsFromBottom = 84;
static unsigned int kBannerWidgetHeight = 0;
static const int kSaucerRadiusSquared = 146 * 146;
static const unsigned int kHideHelpTimeoutInMS = 1000;
static const unsigned int kPaintTick = 1000;
// strings used as keys to lookup locale versions
static const char* kUnlockLabel = "Drag up to unlock";
static const char* kAnswerPhoneLabel = "Drag up to answer";
static DashboardWindowManager* getDashboardWindowManager();
static Pixmap9TileObject* gBackground9Tile;
static unsigned int kShadowWidth = 10;
static unsigned int kBackgroundCornerWidth = 9;
class LockButton : public QGraphicsPixmapItem
{
public:
LockButton();
virtual ~LockButton();
enum Type {
ImagePadlock = 0,
ImageIncomingCall = 2
};
void press(bool down);
void setAnchor(int x, int y);
int distanceToAnchorSquared(int x, int y);
bool atRest() const;
void reset();
bool contains(int x, int y) const;
void setImageType(Type type);
bool m_pressed;
private:
Type m_imageType;
QVector<QPixmap> m_buttonImages;
int m_anchorX;
int m_anchorY;
QRect m_hitTarget;
};
// ----------------------------------------------------------------------------------------------
class TransparentNode : public QGraphicsObject
{
Q_OBJECT
public:
TransparentNode(bool _stayVisible = false);
bool stayVisible() const { return m_stayVisible; }
void animateOpacity(qreal newOpacity);
private Q_SLOTS:
void fadeAnimationFinished();
private:
bool m_stayVisible;
QPropertyAnimation m_fadeAnimation;
};
// ------------------------------------------------------------------------------------------------
class HelpWindow : public TransparentNode
{
public:
HelpWindow();
virtual ~HelpWindow();
// QGraphicsItem::boundingRect
QRectF boundingRect() const;
// QGraphicsItem::paint
void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget);
void setLabel(QString label);
private:
std::vector<gunichar2> m_labelUtf16;
std::vector<int> m_labelGlyphOffsets;
unsigned int m_splitIndex;
QFont* m_font;
QPixmap* m_surf;
QTextLayout textLayout;
QRect m_bounds;
};
// -----------------------------------------------------------------------------------------------
class LockBackground : public QGraphicsObject
{
Q_OBJECT
public:
LockBackground();
virtual ~LockBackground();
// QGraphicsItem::boundingRect
QRectF boundingRect() const;
// QGraphicsItem::paint
void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget);
void showBackground(bool visible);
bool isBackgroundShown() { return m_showBackground; }
void setCompositionMode(QPainter::CompositionMode mode);
void resize(int width, int height);
void setStatusBar(StatusBar* ptr) { m_statusBarPtr = ptr; }
private Q_SLOTS:
void slotWallpaperImageChanged(QPixmap* wallpaper, bool fullScreen, int rotationAngle);
private:
StatusBar* m_statusBarPtr;
bool m_wallpaperFullScreen;
QPixmap* m_wallpaperPtr;
int m_wallpaperRotation;
QPixmap m_topMask, m_bottomMask;
QRect m_bounds;
bool m_showBackground;
QPainter::CompositionMode m_compMode;
};
// ------------------------------------------------------------------------------------------------
class DashboardAlerts : public TransparentNode
{
public:
DashboardAlerts();
virtual ~DashboardAlerts();
// QGraphicsItem::boundingRect
QRectF boundingRect() const;
// QGraphicsItem::paint
void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget);
void sendClickAt(int x, int y);
private:
QList<DashboardWindow*> getDashboardWindows() const;
QRect m_bounds;
QPixmap m_scrollFade;
QPixmap m_divider;
int kDashboardItemHeight;
int kDashboardWidgetHeight;
int kMaxDashboardItems;
int kBottomPadding;
int kTopPadding;
float kVisibleDashboard;
friend class LockWindow;
};
// ------------------------------------------------------------------------------------------------
class BannerAlerts : public TransparentNode,
public BannerMessageView
{
public:
BannerAlerts();
virtual ~BannerAlerts();
// QGraphicsItem::boundingRect
QRectF boundingRect() const;
// QGraphicsItem::paint
void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget);
int bmViewGetWidth() const;
void bmViewUpdated();
void bmViewMessageCountUpdated(int count);
void bmViewShowingNonSuppressibleMessage(bool val);
void bmViewAddActiveCallBanner(const std::string& msg, const std::string& icon, uint32_t time);
void bmViewRemoveActiveCallBanner();
void bmViewUpdateActiveCallBanner(const std::string& msg, const std::string& icon, uint32_t time);
QRect m_bounds;
int m_msgCount;
int kPadding;
};
// ------------------------------------------------------------------------------------------------
class PopUpAlert : public TransparentNode
{
public:
PopUpAlert();
virtual ~PopUpAlert();
// QGraphicsItem::boundingRect
QRectF boundingRect() const;
// QGraphicsItem::paint
void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget);
bool hasDisplayableContent() const;
bool hasIncomingCallAlert() const;
void adjustAlertBounds();
private:
const Window* getActiveAlertWin() const;
QRect m_bounds;
int kPadding;
};
// ------------------------------------------------------------------------------------------------
LockWindow::LockWindow(uint32_t maxWidth, uint32_t maxHeight)
: m_paintTimer(HostBase::instance()->masterTimer(), this, &LockWindow::paint)
, m_hideHelpTimer(HostBase::instance()->masterTimer(), this, &LockWindow::hideHelpTimeout)
, m_lastLocked(0)
, m_lockTimeout(0)
, m_popupActive(false)
, m_bannerActive(false)
, m_activeCall(false)
, m_state(StateUnlocked)
, m_lockButtonX(0)
, m_lockButtonY(0)
, m_bgNode(0)
, m_helpWin(0)
, m_lockButton(0)
, m_clockWin(0)
, m_dashboardAlerts(0)
, m_bannerAlerts(0)
, m_popUpAlert(0)
// , m_phoneAppWin(0)
, m_qmlUnlockPanel(0)
, bannerViewRegistered(false)
// , m_phoneAppShownY(0)
// , m_phoneAppHiddenY(0)
, m_elementsShown(true)
, m_statusBar(0)
, m_unlockPanel(0)
, m_unlockDialog(0)
, m_setupNewPin(false)
, m_setupNewPassword(false)
{
m_bounds = QRectF((int)-maxWidth/2, (int)-maxHeight/2, maxWidth, maxHeight);
setOpacity(0.0);
setVisible(false);
connect(SystemUiController::instance(), SIGNAL(signalAlertActivated()), this, SLOT(slotAlertActivated()));
connect(SystemUiController::instance(), SIGNAL(signalAlertDeactivated()), this, SLOT(slotAlertDeactivated()));
connect(SystemUiController::instance(), SIGNAL(signalTransientAlertActivated()), this, SLOT(slotTransientAlertActivated()));
connect(SystemUiController::instance(), SIGNAL(signalTransientAlertDeactivated()), this, SLOT(slotTransientAlertDeactivated()));
connect(SystemUiController::instance(), SIGNAL(signalBannerActivated()), this, SLOT(slotBannerActivated()));
connect(SystemUiController::instance(), SIGNAL(signalBannerDeactivated()), this, SLOT(slotBannerDeactivated()));
connect(SystemUiController::instance(), SIGNAL(signalBannerAboutToUpdate(QRect&)), this, SLOT(slotBannerAboutToUpdate(QRect&)));
connect(SystemUiController::instance(), SIGNAL(signalBootFinished()), this, SLOT(slotBootFinished()));
// connect(SystemService::instance(), SIGNAL(signalDeviceUnlocked()), this, SLOT(slotDeviceUnlocked()));
// connect(SystemService::instance(), SIGNAL(signalCancelPinEntry()), this, SLOT(slotCancelPasswordEntry()));
connect(Preferences::instance(), SIGNAL(signalSetLockTimeout(uint32_t)), this, SLOT(slotSetLockTimeout(uint32_t)));
connect(WindowServer::instance(), SIGNAL(signalWindowUpdated(Window*)), this, SLOT(slotWindowUpdated(Window*)));
connect(this, SIGNAL(visibleChanged()), SLOT(slotVisibilityChanged()));
setLockTimeout(Preferences::instance()->lockTimeout());
}
LockWindow::~LockWindow()
{
}
void LockWindow::init()
{
connect(EASPolicyManager::instance(), SIGNAL(signalPolicyChanged(const EASPolicy* const)),
this, SLOT(slotPolicyChanged(const EASPolicy* const)));
connect(DisplayManager::instance(), SIGNAL(signalDisplayStateChange(int)), this, SLOT(slotDisplayStateChanged(int)));
connect(DisplayManager::instance(), SIGNAL(signalLockStateChange(int, int)), this, SLOT(slotLockStateChanged(int, int)));
connect(SystemUiController::instance(), SIGNAL(signalPositiveSpaceAboutToChange(const QRect&, bool, bool)),
SLOT(slotPositiveSpaceAboutToChange(const QRect&, bool, bool)));
connect(SystemUiController::instance(), SIGNAL(signalPositiveSpaceChanged(const QRect&)),
SLOT(slotPositiveSpaceChanged(const QRect&)));
connect(SystemUiController::instance(), SIGNAL(signalPositiveSpaceChangeFinished(const QRect&)),
SLOT(slotPositiveSpaceChangeFinished(const QRect&)));
connect(SystemUiController::instance(), SIGNAL(signalUiRotationCompleted()),
SLOT(slotUiRotationCompleted()));
Settings* settings = Settings::LunaSettings();
m_windowFadeAnimation.setTargetObject(this);
m_windowFadeAnimation.setPropertyName("opacity");
m_windowFadeAnimation.setDuration(AS(lockWindowFadeDuration));
m_windowFadeAnimation.setEasingCurve(AS_CURVE(lockWindowFadeCurve));
connect(&m_windowFadeAnimation, SIGNAL(finished()), SLOT(slotWindowFadeAnimationFinished()));
kTopPadding = settings->positiveSpaceTopPadding;
kBannerWidgetHeight = BannerMessageHandler::instance()->viewHeight();
if (kBannerWidgetHeight < 20) // DFISH-5147: Total banner height >= 40, shadows are 10 each, so widget height >= 20
kBannerWidgetHeight = 20;
m_statusBar = new StatusBar(StatusBar::TypeLockScreen, m_bounds.width(), settings->positiveSpaceTopPadding);
m_statusBar->init();
m_statusBar->setParentItem(this);
m_statusBar->setPos(0, m_bounds.y() + m_statusBar->boundingRect().height() / 2);
m_statusBar->setZValue(100);
// Background (Status/Wallpaper/Dashboard/Banner/Mask)
m_bgNode = new LockBackground();
m_bgNode->setParentItem(this);
m_bgNode->setPos(0,0);
m_bgNode->setStatusBar(m_statusBar);
// Clock
m_clockWin = new ClockWindow();
m_clockWin->setParentItem(this);
m_clockWin->setPos(0,-(SystemUiController::instance()->currentUiHeight() * 0.35));
m_clockWin->tick();
// Dashboard Alerts
m_dashboardAlerts = new DashboardAlerts();
m_dashboardAlerts->setParentItem(this);
m_dashboardAlerts->setPos(0, 0);
// BannerAlerts
m_bannerAlerts = new BannerAlerts();
m_bannerAlerts->setParentItem(this);
m_bannerAlerts->setPos(0, 0);
// Popup Alert
m_popUpAlert = new PopUpAlert();
m_popUpAlert->setParentItem(this);
m_popUpAlert->setPos(0, 0);
// Help
m_helpWin = new HelpWindow();
m_helpWin->setLabel(fromStdUtf8(LOCALIZED(kUnlockLabel)));
m_helpWin->setParentItem(this);
m_helpWin->setPos(0, boundingRect().bottom() - boundingRect().height() * LOCK_BUTTON_OFFSET - (m_helpWin->boundingRect().height()) / 2);
// Lock Button
m_lockButton = new LockButton();
m_lockButtonX = 0;
m_lockButtonY = boundingRect().bottom() - boundingRect().height()* LOCK_BUTTON_OFFSET - m_lockButton->boundingRect().height()/2;
m_lockButton->setAnchor(m_lockButtonX, m_lockButtonY);
m_lockButton->setParentItem(this);
std::string filePath = Settings::LunaSettings()->lunaSystemResourcesPath + "/popup-bg.png";
gBackground9Tile = PixmapObjectLoader::instance()->quickLoadNineTiled (QString (filePath.c_str()),
(quint32)(kShadowWidth + kBackgroundCornerWidth),
(quint32)(kShadowWidth + kBackgroundCornerWidth),
(quint32)(kShadowWidth + kBackgroundCornerWidth),
(quint32)(kShadowWidth + kBackgroundCornerWidth));
// Unlock Dialog
QDeclarativeEngine* qmlEngine = WindowServer::instance()->declarativeEngine();
if(qmlEngine) {
QDeclarativeContext* context = qmlEngine->rootContext();
std::string qmlPath = settings->lunaQmlUiComponentsPath + "UnlockPanel/UnlockPanel.qml";
QUrl url = QUrl::fromLocalFile(qmlPath.c_str());
qmlRegisterType<InputItem>("CustomComponents", 1, 0, "InputItem");
m_qmlUnlockPanel = new QDeclarativeComponent(qmlEngine, url, this);
if(m_qmlUnlockPanel) {
m_unlockPanel = qobject_cast<InputItem *>(m_qmlUnlockPanel->create());
if(m_unlockPanel) {
m_unlockPanel->setPos (-m_unlockPanel->boundingRect().width()/2, -m_unlockPanel->boundingRect().height()/2);
static_cast<QGraphicsObject*>(m_unlockPanel)->setParentItem(this);
m_unlockPanel->setVisible(false);
m_unlockPanel->setOpacity(0.0);
connect(m_unlockPanel, SIGNAL(entryCanceled()), SLOT(slotCancelPasswordEntry()));
connect(m_unlockPanel, SIGNAL(passwordSubmitted(QString, bool)), SLOT(slotPasswordSubmitted(QString, bool)));
connect(m_unlockPanel, SIGNAL(requestFocusChange(bool)), SLOT(slotPinPanelFocusRequest(bool)));
}
}
qmlPath = settings->lunaQmlUiComponentsPath + "MessageDialog/MessageDialog.qml";
url = QUrl::fromLocalFile(qmlPath.c_str());
m_qmlUnlockDialog = new QDeclarativeComponent(qmlEngine, url, this);
if(m_qmlUnlockDialog) {
m_unlockDialog = qobject_cast<QGraphicsObject *>(m_qmlUnlockDialog->create());
if(m_unlockPanel) {
m_unlockDialog->setPos (-m_unlockDialog->boundingRect().width()/2, -m_unlockDialog->boundingRect().height()/2);
m_unlockDialog->setParentItem(this);
m_unlockDialog->setVisible(false);
m_unlockDialog->setOpacity(0.0);
connect(m_unlockDialog, SIGNAL(button1Pressed()), SLOT(slotDialogButton1Pressed()));
connect(m_unlockDialog, SIGNAL(button2Pressed()), SLOT(slotDialogButton2Pressed()));
connect(m_unlockDialog, SIGNAL(button3Pressed()), SLOT(slotDialogButton3Pressed()));
}
}
}
m_newPasscode.clear();
}
bool LockWindow::okToResize()
{
if(m_lockButton) {
if(!m_lockButton->atRest() || m_lockButton->m_pressed)
return false;
}
if(m_windowFadeAnimation.state() == QAbstractAnimation::Running)
return false;
// if(m_phoneWinAnimation.state() == QAbstractAnimation::Running)
// return false;
return true;
}
void LockWindow::resize(int width, int height)
{
m_bounds = QRectF((int)-width/2, (int)-height/2, width, height);
if(m_bgNode) {
m_bgNode->resize(width,height);
}
if(m_statusBar) {
m_statusBar->resize(width, Settings::LunaSettings()->positiveSpaceTopPadding);
m_statusBar->setPos(0, m_bounds.y() + m_statusBar->boundingRect().height() / 2);
m_statusBar->update();
}
if(m_clockWin) {
m_clockWin->resize(width, height);
m_clockWin->setPos(0,-(height * 0.35));
m_clockWin->tick();
}
if(m_dashboardAlerts)
m_dashboardAlerts->setPos(0,0);
if(m_bannerAlerts)
m_bannerAlerts->setPos(0, 0);
if(m_popUpAlert)
m_popUpAlert->setPos(0,0);
if(m_helpWin)
m_helpWin->setPos(0, boundingRect().bottom() - boundingRect().height() * LOCK_BUTTON_OFFSET - (m_helpWin->boundingRect().height()) / 2);
if(m_lockButton) {
m_lockButtonY = boundingRect().bottom() - boundingRect().height() * LOCK_BUTTON_OFFSET - m_lockButton->boundingRect().height()/2;
m_lockButton->setAnchor(m_lockButtonX, m_lockButtonY);
}
// if(m_phoneAppWin) {
// bool phoneAppWinShown = false;
//
// if(m_state == StateInPhoneCall) {
// phoneAppWinShown = true;
// }
//
// m_phoneAppWin->resizeWindowBufferEvent(width, height, m_bounds.adjusted(0, kTopPadding, 0, 0).toRect());
//
// m_phoneAppShownY = boundingRect().y() + kTopPadding + (height - Settings::LunaSettings()->positiveSpaceTopPadding)/2;
// m_phoneAppHiddenY = boundingRect().height() + (height - Settings::LunaSettings()->positiveSpaceTopPadding)/2;
//
// if(pinWinShown) {
// m_phoneAppWin->setPos(0, m_phoneAppShownY);
// } else {
// m_phoneAppWin->setPos(0, m_phoneAppHiddenY);
// }
// }
if(isVisible())
update();
}
void LockWindow::slotUiRotationCompleted()
{
if(m_state == StatePinEntry) {
static_cast<QGraphicsObject*>(m_unlockPanel)->setFocus(); // make sure the PIN [anel has focus when in PIN entry mode
}
}
bool LockWindow::setLockTimeout(uint32_t timeout)
{
#if !defined (TARGET_DEVICE)
return false;
#endif
const EASPolicy * const policy = EASPolicyManager::instance()->getPolicy();
if (policy == 0 || !policy->validInactivityInSeconds()) {
// make sure we are setting a system supported timeout value
m_lockTimeout = Preferences::roundLockTimeout(timeout);
}
else {
m_lockTimeout = policy->clampInactivityInSeconds(timeout);
}
Preferences::instance()->setLockTimeout(m_lockTimeout);
return true;
}
void LockWindow::slotSetLockTimeout(uint32_t timeout)
{
setLockTimeout(timeout);
}
void LockWindow::slotPolicyChanged(const EASPolicy * const policy)
{
// re-clamp our lock timeout value if needed
setLockTimeout(m_lockTimeout);
}
void LockWindow::addPhoneAppWindow(Window* win)
{
// not supporting Phone App card on Lock screen in Dartfish, so just clsoe this card
static_cast<CardWindow*>(win)->close();
// if (m_phoneAppWin != 0) {
// g_warning("%s: Phone application tried to add more than 1 PIN window!", __PRETTY_FUNCTION__);
// WebAppMgrProxy::instance()->closeWindow(win);
// return;
// }
//
// m_phoneAppWin = static_cast<CardWindow*>(win);
// m_phoneAppWin->setParentItem(this);
// m_phoneAppWin->stackBefore(m_lockButton);
// // set the correct screen position for the pin card
// m_phoneAppWin->setPos(0,boundingRect().height() + m_phoneAppWin->boundingRect().height()/2);
// m_phoneWinAnimation.setTargetObject(m_phoneAppWin);
// m_phoneWinAnimation.setPropertyName("y");
// m_phoneWinAnimation.setDuration(AS(lockPinDuration));
// m_phoneWinAnimation.setEasingCurve(AS_CURVE(lockPinCurve));
// connect(&m_phoneWinAnimation, SIGNAL(finished()), SLOT(slotPhoneWindowAnimationFinished()));
//
// m_phoneAppShownY = boundingRect().y() + kTopPadding + m_phoneAppWin->boundingRect().height()/2;
// m_phoneAppHiddenY = boundingRect().height() + m_phoneAppWin->boundingRect().height()/2;
//
// g_message("%s: PIN/password application was added to the lock screen", __PRETTY_FUNCTION__);
}
void LockWindow::slotBootFinished()
{
// lock automatically on boot if the user has a passcode set
if (requiresPasscode()) {
DisplayManager::instance()->lock();
m_lastLocked = 0;
}
#if !defined(TARGET_DESKTOP)
// If this fails, either the Phone application stopped early due to an uncaught exception before
// the PIN window could be created or someone tried to subvert the locking mechanism
// if (m_phoneAppWin == 0) {
// g_critical("%s: (FATAL) The PIN/password unlock window was not received from the Phone app!", __PRETTY_FUNCTION__);
// exit(-1);
// }
#endif
}
void LockWindow::slotWindowUpdated(Window* win)
{
if (!isLocked() || !win)
return;
switch (win->type()) {
case Window::Type_PopupAlert:
case Window::Type_BannerAlert:
{
AlertWindow* alert = (AlertWindow*)win;
if(!alert->isTransientAlert()) {
if (m_popUpAlert) {
m_popUpAlert->adjustAlertBounds();
}
} else {
// update the Transient alert contents here
}
}
break;
default: break;
}
}
void LockWindow::delayDockModeLocking()
{
m_delayDockModeLocking = true;
}
void LockWindow::performDelayedLock()
{
if(m_delayDockModeLocking) {
g_message("%s: calling lock (NIGHTSTAND) (DELAYED CALL DUE TO DOCK MODE)", __PRETTY_FUNCTION__);
changeState(StateDockMode);
unregisterBannerView();
m_delayDockModeLocking = false;
}
}
void LockWindow::slotLockStateChanged(int event, int displayEvent)
{
switch (event) {
case DISPLAY_LOCK_SCREEN:
g_message("%s: calling lock (NORMAL)", __PRETTY_FUNCTION__);
changeState(StateNormal);
registerBannerView();
break;
case DISPLAY_UNLOCK_SCREEN:
g_message("%s: calling tryUnlock with event %d", __PRETTY_FUNCTION__, displayEvent);
unregisterBannerView();
if (!isLocked())
return;
if (displayEvent == DisplayEventIncomingCall) {
DisplayManager::instance()->lock();
}
else if (requiresPasscode() && displayEvent == DisplayEventApiOn) {
DisplayManager::instance()->lock();
}
else if (!requiresPasscode() ||
((displayEvent != DisplayEventUsbIn &&
displayEvent != DisplayEventOnPuck &&
displayEvent != DisplayEventProximityOff) ||
!m_popUpAlert->hasIncomingCallAlert()))
{
// attempt to unlock the screen if:
// - the user has no pin/password set and there isn't a pending EAS policy update
// - the reason for unlocking is not due to the USB being plugged in or the device
// being removed from the puck unless, there isn't a pending incoming call
tryUnlock();
}
break;
case DISPLAY_DOCK_SCREEN:
g_message("%s: calling lock (DOCK)", __PRETTY_FUNCTION__);
unregisterBannerView();
changeState(StateDockMode);
break;
default: break;
}
}
void LockWindow::slotDisplayStateChanged(int event)
{
switch (event) {
case DISPLAY_SIGNAL_ON:
case DISPLAY_SIGNAL_DIM:
// screen is about to come on
g_debug("%s: power on/dim (%d)", __PRETTY_FUNCTION__, isLocked());
handlePowerOn();
break;
case DISPLAY_SIGNAL_OFF:
// screen has turned off
g_debug ("%s: power off (%d)", __PRETTY_FUNCTION__, isLocked());
handlePowerOff();
break;
default: break;
}
}
void LockWindow::handlePowerOn()
{
if (!isLocked())
return;
// start up the paint timer
m_clockWin->tick();
if (!m_paintTimer.running())
m_paintTimer.start(kPaintTick);
}
void LockWindow::handlePowerOff()
{
if (!isLocked())
return;
m_paintTimer.stop(); // no need to update while off
}
void LockWindow::activatePopUpAlert()
{
// start showing the active popup alert
hideAlert(m_dashboardAlerts);
hideAlert(m_bannerAlerts);
if (m_popUpAlert->hasIncomingCallAlert()) {
m_lockButton->setImageType(LockButton::ImageIncomingCall);
m_helpWin->setLabel(fromStdUtf8(LOCALIZED(kAnswerPhoneLabel)));
showHelp();
}
else {
m_lockButton->setImageType(LockButton::ImagePadlock);
m_helpWin->setLabel(fromStdUtf8(LOCALIZED(kUnlockLabel)));
}
m_popUpAlert->adjustAlertBounds();
showAlert(m_popUpAlert);
}
void LockWindow::registerBannerView()
{
if(bannerViewRegistered) return;
if(m_bannerAlerts)
BannerMessageHandler::instance()->registerView(m_bannerAlerts);
bannerViewRegistered = true;
}
void LockWindow::unregisterBannerView()
{
if(!bannerViewRegistered) return;
if(m_bannerAlerts)
BannerMessageHandler::instance()->unregisterView(m_bannerAlerts);
bannerViewRegistered = false;
}
void LockWindow::activateBannerAlert()
{
// start showing 1 or more banner alerts
showAlert(m_bannerAlerts);
hideAlert(m_dashboardAlerts);
}
void LockWindow::slotAlertActivated()
{
// we don't want to show alerts that have nothing visible
if (!m_popUpAlert->hasDisplayableContent())
return;
g_message("%s: has displayable content", __PRETTY_FUNCTION__);
m_popupActive = true;
// we always track the status of alerts whether we are locked or not.
// this is due to inconsistent ordering of system events
if (!isLocked())
return;
// only incoming call alerts should interrupt pin/password entry
if (m_popUpAlert->hasIncomingCallAlert()) {
DisplayManager::instance()->lock();
}
if(m_state == StatePinEntry)
return;
activatePopUpAlert();
}
void LockWindow::slotAlertDeactivated()
{
// if the popup was never active then there's nothing to clean up
if (!m_popupActive)
return;
g_message("%s: popup alert deactivated", __PRETTY_FUNCTION__);
m_popupActive = false;
// we always track the status of alerts whether we are locked or not.
// this is due to inconsistent ordering of system events
if (!isLocked())
return;
// reset back to initial state
hideAlert(m_popUpAlert);
if (Preferences::instance()->showAlertsWhenLocked() && (m_state == StateNormal)) {
if (m_bannerActive)
showAlert(m_bannerAlerts);
else
showAlert(m_dashboardAlerts);
}
hideHelp();
m_lockButton->setImageType(LockButton::ImagePadlock);
m_helpWin->setLabel(fromStdUtf8(LOCALIZED(kUnlockLabel)));
}
void LockWindow::slotTransientAlertActivated()
{
g_message("%s: has displayable content", __PRETTY_FUNCTION__);
// TODO: handle this for Lock Screen
}
void LockWindow::slotTransientAlertDeactivated()
{
g_message("%s: transient alert deactivated", __PRETTY_FUNCTION__);
// TODO: handle this for Lock Screen
}
void LockWindow::slotBannerActivated()
{
if (!Preferences::instance()->showAlertsWhenLocked())
return;
g_message("%s", __PRETTY_FUNCTION__);
m_bannerActive = true;
// we always track the status of alerts whether we are locked or not.
// this is due to inconsistent ordering of system events
if (!isLocked() || m_popupActive || (m_state == StatePinEntry))
return;
activateBannerAlert();
}
void LockWindow::slotBannerDeactivated()
{
if (!Preferences::instance()->showAlertsWhenLocked())
return;
g_message("%s", __PRETTY_FUNCTION__);
m_bannerActive = false;
// we always track the status of alerts whether we are locked or not.
// this is due to inconsistent ordering of system events
if (!isLocked() || m_popupActive)
return;
// banner has finished showing all messages
hideAlert(m_bannerAlerts);
if(m_state == StateNormal)
showAlert(m_dashboardAlerts);
}
void LockWindow::slotBannerAboutToUpdate(QRect& target)
{
// target is the area of the screen which is about to get invalidated
// to draw the banner.
if (m_state == StateNormal || m_state == StateDockMode) {
target = mapRectFromItem(m_bannerAlerts, m_bannerAlerts->m_bounds).toRect(); // $$$ what is this used for?
}
}
void LockWindow::changeState(State newState)
{
if (newState == m_state)
return;
switch (m_state) {
case StateUnlocked:
// make sure the clock is correct
m_clockWin->updateTimeFormat();
m_clockWin->tick();
// put the unlock button at its resting spot
m_lockButton->reset();
// kick off our timer
m_paintTimer.start(kPaintTick);
// time stamp when the screen was locked
m_lastLocked = Time::curSysTimeMs();
break;
case StateNormal:
case StateDockMode:
// our new state will setup normal vs nightstand
break;
case StatePinEntry:
m_newPasscode.clear();
m_setupNewPin = false;
m_setupNewPassword = false;
if (newState != StateUnlocked)
hidePinPanel();
break;
case StateLastTryDialog:
case StateNewPinDialog:
hideDialog();
break;
// case StateInPhoneCall:
// if (newState != StateUnlocked)
// hidePhoneApp();
// else{
// SystemUiController::instance()->setDirectRenderingForWindow(SystemUiController::TOP_LEVEL_WINDOW_MANAGER, m_phoneAppWin, false);
// if (m_phoneAppWin)
// m_phoneAppWin->setPaintCompositionMode(QPainter::CompositionMode_SourceOver);
// // hide elements under the PIN app for the fade effect
// toggleElemetsVisibleUnderPhoneApp(false);
// }
// break;
default: luna_assert(0);
}
// setup new state
switch (newState) {
case StateUnlocked:
unlock();
break;
case StateNormal:
m_lockButton->reset();
m_lockButton->setVisible(true);
// toggleElemetsVisibleUnderPhoneApp(true);
// if (m_phoneAppWin)
// m_phoneAppWin->setPaintCompositionMode(QPainter::CompositionMode_Source);
hidePinPanel();
m_bgNode->showBackground(newState == StateNormal);
if (m_popupActive) {
activatePopUpAlert();
}
else if (Preferences::instance()->showAlertsWhenLocked()) {
hideAlert(m_popUpAlert);
if (m_bannerActive) {
activateBannerAlert();
}
else {
hideAlert(m_bannerAlerts);
showAlert(m_dashboardAlerts);
}
}
else {
hideAlert(m_bannerAlerts);
hideAlert(m_dashboardAlerts);
hideAlert(m_popUpAlert);
}
// we are now locked
if (m_state == StateUnlocked) {
Q_EMIT signalScreenLocked(ScreenLocking);
}
break;
case StatePinEntry:
// prevent the lock button from showing up on top of the pin app
m_lockButton->setVisible(false);
// make the status bar visible
m_bgNode->showBackground(true);
hideAlert(m_bannerAlerts);
hideAlert(m_dashboardAlerts);
hideAlert(m_popUpAlert);
showPinPanel();
break;
case StateNewPinDialog:
m_lockButton->setVisible(false);
// make the status bar visible
m_bgNode->showBackground(true);
hideAlert(m_bannerAlerts);
hideAlert(m_dashboardAlerts);
hideAlert(m_popUpAlert);
if (EASPolicyManager::instance()->policyPending()
&& EASPolicyManager::instance()->getPolicy()
&& EASPolicyManager::instance()->getPolicy()->requiresAlphaNumeric())
{
QMetaObject::invokeMethod(m_unlockDialog, "setupDialog", Q_ARG(QVariant, fromStdUtf8(LOCALIZED("Password Required"))),
Q_ARG(QVariant, fromStdUtf8(LOCALIZED("Your security requirements have changed. To access your device, you must set a new password. This will automatically turn on Secure Unlock"))),
Q_ARG(QVariant, 3));
QMetaObject::invokeMethod(m_unlockDialog, "setButton1", Q_ARG(QVariant, ""), Q_ARG(QVariant, "disabled"));
QMetaObject::invokeMethod(m_unlockDialog, "setButton2", Q_ARG(QVariant, fromStdUtf8(LOCALIZED("New Password"))), Q_ARG(QVariant, "affirmative"));
QMetaObject::invokeMethod(m_unlockDialog, "setButton3", Q_ARG(QVariant, fromStdUtf8(LOCALIZED("Cancel"))), Q_ARG(QVariant, "normal"));
}
else {
QMetaObject::invokeMethod(m_unlockDialog, "setupDialog", Q_ARG(QVariant, fromStdUtf8(LOCALIZED("PIN Required"))),
Q_ARG(QVariant, fromStdUtf8(LOCALIZED("To access your device, you must first set a PIN or Password for Secure Unlock. This will automatically turn on Secure Unlock"))),
Q_ARG(QVariant, 3));
QMetaObject::invokeMethod(m_unlockDialog, "setButton1", Q_ARG(QVariant, fromStdUtf8(LOCALIZED("New PIN"))), Q_ARG(QVariant, "affirmative"));
QMetaObject::invokeMethod(m_unlockDialog, "setButton2", Q_ARG(QVariant, fromStdUtf8(LOCALIZED("New Password"))), Q_ARG(QVariant, "affirmative"));
QMetaObject::invokeMethod(m_unlockDialog, "setButton3", Q_ARG(QVariant, fromStdUtf8(LOCALIZED("Cancel"))), Q_ARG(QVariant, "normal"));
}
showDialog();
break;
case StateLastTryDialog:
m_lockButton->setVisible(false);
// make the status bar visible
m_bgNode->showBackground(true);
hideAlert(m_bannerAlerts);
hideAlert(m_dashboardAlerts);
hideAlert(m_popUpAlert);
if(0 == Security::instance()->getLockMode().compare("pin")) {
QMetaObject::invokeMethod(m_unlockDialog, "setupDialog", Q_ARG(QVariant, fromStdUtf8(LOCALIZED("Warning"))),
Q_ARG(QVariant, fromStdUtf8(LOCALIZED("PIN incorrect. If you enter an incorrect PIN now your device will be erased"))),
Q_ARG(QVariant, 1));
} else {
QMetaObject::invokeMethod(m_unlockDialog, "setupDialog", Q_ARG(QVariant, fromStdUtf8(LOCALIZED("Warning"))),
Q_ARG(QVariant, fromStdUtf8(LOCALIZED("Password incorrect. If you enter an incorrect Password now your device will be erased"))),
Q_ARG(QVariant, 1));
}
QMetaObject::invokeMethod(m_unlockDialog, "setButton1", Q_ARG(QVariant,fromStdUtf8( LOCALIZED("Ok"))), Q_ARG(QVariant, "normal"));
QMetaObject::invokeMethod(m_unlockDialog, "setButton2", Q_ARG(QVariant, ""), Q_ARG(QVariant, "disabled"));
QMetaObject::invokeMethod(m_unlockDialog, "setButton3", Q_ARG(QVariant, ""), Q_ARG(QVariant, "disabled"));
showDialog();
break;
// case StateInPhoneCall:
// // prevent the lock button from showing up on top of the phone app
// m_lockButton->setVisible(false);
//
// // make the status bar visible
// m_bgNode->showBackground(true);
//
//// if (m_phoneAppWin)
//// m_phoneAppWin->setPaintCompositionMode(QPainter::CompositionMode_Source);
//
// hideAlert(m_bannerAlerts);
// hideAlert(m_dashboardAlerts);
// hideAlert(m_popUpAlert);
//
// showPhoneApp();
// break;
case StateDockMode:
// prevent the lock button from showing up on top of the pin app
m_lockButton->setVisible(false);
// make the status bar visible
m_bgNode->showBackground(false);
// toggleElemetsVisibleUnderPhoneApp(true);
// if (m_phoneAppWin)
// m_phoneAppWin->setPaintCompositionMode(QPainter::CompositionMode_Source);
hidePinPanel();
hideAlert(m_bannerAlerts);
hideAlert(m_dashboardAlerts);
hideAlert(m_popUpAlert);
if (m_state == StateUnlocked)
Q_EMIT signalScreenLocked(ScreenLocking);
break;
default: luna_assert(0);
}
m_state = newState;
update();
}
void LockWindow::mapCoordToWindow(Window* win, int& x, int& y) const
{
if (!win)
return;
// $$$
x = x - win->boundingRect().x();
y = MAX(0, y - win->boundingRect().y());
}
void LockWindow::fadeWindow(bool in)
{
if(m_windowFadeAnimation.state() != QAbstractAnimation::Stopped)
m_windowFadeAnimation.stop();
if(!isVisible() || !DisplayManager::instance()->isDisplayOn()) {
// invisible because the TopLevel WM was set to invisible or the screen is off
// dont animate in this case, just set it to the desired state
if(in) {
setOpacity(1.0);
setVisible(true);
Q_EMIT signalScreenLocked(ScreenLocked);
} else {
setOpacity(0.0);
setVisible(false);
hidePinPanel(false);
}
return;
}
m_windowFadeAnimation.setStartValue(opacity());
if(in) {
// fade in
setVisible(true);
if(m_statusBar && m_bgNode) {
m_statusBar->setVisible(m_bgNode->isBackgroundShown());
}
m_windowFadeAnimation.setEndValue(1.0);
} else{
// fade out
m_windowFadeAnimation.setEndValue(0.0);
if(m_statusBar && !SystemUiController::instance()->isInFullScreenMode()) {
m_statusBar->setVisible(false);
}
}
if(m_bgNode)
m_bgNode->setCompositionMode(QPainter::CompositionMode_SourceOver);
m_windowFadeAnimation.start();
}
void LockWindow::slotWindowFadeAnimationFinished()
{
if(m_bgNode)
m_bgNode->setCompositionMode(QPainter::CompositionMode_Source);
if(opacity() == 0.0) {
setVisible(false);
// if (m_phoneAppWin)
// m_phoneAppWin->setPaintCompositionMode(QPainter::CompositionMode_Source);
hidePinPanel(false);
// toggleElemetsVisibleUnderPhoneApp(true);
m_lockButton->reset();
// make sure we deactivate the PIN app
// if (m_phoneAppWin)
// m_phoneAppWin->focusEvent(false);
} else {
Q_EMIT signalScreenLocked(ScreenLocked);
}
}
//void LockWindow::toggleElemetsVisibleUnderPhoneApp(bool visible)
//{
// if(m_elementsShown == visible)
// return;
//
// m_clockWin->setVisible(visible);
// m_bgNode->setVisible(visible);
// m_dashboardAlerts->setVisible(visible);
// m_bannerAlerts->setVisible(visible);
// m_popUpAlert->setVisible(visible);
//
// // always hide the help window
// hideHelp(false);
//
// m_elementsShown = visible;
//}
void LockWindow::tryUnlock()
{
if (!isLocked())
return;
if (requiresPasscode()) {
if (EASPolicyManager::instance()->policyPending()) {
// User needs to set up a new PIN/Password
changeState(StateNewPinDialog);
} else {
// must enter pin/password to really unlock
g_message ("%s: switching to pin entry", __PRETTY_FUNCTION__);
changeState(StatePinEntry);
// if(!m_popupActive || !m_popUpAlert->hasIncomingCallAlert()) {
// changeState(StatePinEntry);
// } else {
// changeState(StateInPhoneCall);
// }
}
}
else {
// we can finally unlock
g_message ("%s: unlocking without pin entry", __PRETTY_FUNCTION__);
changeState(StateUnlocked);
}
DisplayManager::instance()->unlock();
}
void LockWindow::unlock()
{
if (!isLocked())
return;
g_message("screen unlocked");
// open the dashboard unless we are answering a call or the banner is updating
if (!m_popUpAlert->hasIncomingCallAlert() && !m_bannerActive &&
CoreNaviManager::instance()->numStandbyRequests() > 0)
{
getDashboardWindowManager()->openDashboard();
}
Q_EMIT signalScreenLocked(ScreenUnlocked);
// reset our state
m_helpWin->setLabel(fromStdUtf8(LOCALIZED(kUnlockLabel)));
hideHelp(false); // don't animate the help fade
m_lockButton->setImageType(LockButton::ImagePadlock);
m_paintTimer.stop();
m_lastLocked = 0;
}
bool LockWindow::requiresPasscode() const
{
if (EASPolicyManager::instance()->policyPending())
return true;
if (Security::instance()->passcodeSet()) {
uint32_t timeDiff = (Time::curSysTimeMs() - m_lastLocked) / 1000;
if (timeDiff >= m_lockTimeout)
return true;
}
return false;
}
void LockWindow::slotDeviceUnlocked()
{
// Pin application verified the user's pin, unlock
if (m_state != StatePinEntry)
return;
changeState(StateUnlocked);
// tell display we have unlocked
DisplayManager::instance()->unlock();
}
void LockWindow::slotCancelPasswordEntry()
{
// user wants out of the pin application
if (m_state != StatePinEntry)
return;
m_setupNewPin = false;
m_setupNewPassword = false;
m_newPasscode.clear();
// tell display manager to relock us
DisplayManager::instance()->lock();
}
void LockWindow::slotPasswordSubmitted(QString password, bool isPIN)
{
int minLen = 0;
char hint[30];
std::string hintStr;
if(EASPolicyManager::instance()->getPolicy() && EASPolicyManager::instance()->getPolicy()->validMinLength()) {
minLen = EASPolicyManager::instance()->getPolicy()->minLength();
}
if(!m_setupNewPin && !m_setupNewPassword) {
bool unlocked = false;
int retriesLeft = 0;
bool lockedOut = false;
std::string pass = std::string(password.toUtf8().data());
unlocked = Security::instance()->matchPasscode(pass, retriesLeft, lockedOut);
if(unlocked) {
// Pin application verified the user's pin, unlock
if (m_state != StatePinEntry)
return;
changeState(StateUnlocked);
// tell display we have unlocked
DisplayManager::instance()->unlock();
} else {
bool isPin = true;
std::string title;
std::string message;
retriesLeft = EASPolicyManager::instance()->retriesLeft();
if(retriesLeft > 1) {
char tries[100];
sprintf (tries, LOCALIZED("%d Tries Remaining").c_str(), retriesLeft);
message = tries;
} else if (retriesLeft == 1) {
changeState(StateLastTryDialog);
} else {
if(EASPolicyManager::instance()->getPolicy() && EASPolicyManager::instance()->getPolicy()->validMaxRetries()) {
// Device Will Be Erased
hidePinPanel();
if(0 == Security::instance()->getLockMode().compare("pin")) {
QMetaObject::invokeMethod(m_unlockDialog, "setupDialog", Q_ARG(QVariant, fromStdUtf8(LOCALIZED("PIN Incorrect"))),
Q_ARG(QVariant, fromStdUtf8(LOCALIZED("Your device will now be erased."))),
Q_ARG(QVariant, 0));
} else {
QMetaObject::invokeMethod(m_unlockDialog, "setupDialog", Q_ARG(QVariant, fromStdUtf8(LOCALIZED("Password Incorrect"))),
Q_ARG(QVariant, fromStdUtf8(LOCALIZED("Your device will now be erased."))),
Q_ARG(QVariant, 0));
}
showDialog();
return;
} else {
message = LOCALIZED("Try Again");
}
}
if(0 == Security::instance()->getLockMode().compare("password")) {
isPin = false;
title = LOCALIZED("Password Incorrect");
QMetaObject::invokeMethod(m_unlockPanel, "queueUpTitle", Q_ARG(QVariant, fromStdUtf8(LOCALIZED("Device Locked"))), Q_ARG(QVariant, fromStdUtf8(LOCALIZED("Enter Password"))));
} else {
isPin = true;
title = LOCALIZED("PIN Incorrect");
QMetaObject::invokeMethod(m_unlockPanel, "queueUpTitle", Q_ARG(QVariant, fromStdUtf8(LOCALIZED("Device Locked"))), Q_ARG(QVariant, fromStdUtf8(LOCALIZED("Enter PIN"))));
}
QMetaObject::invokeMethod(m_unlockPanel, "setupDialog", Q_ARG(QVariant, isPin),
Q_ARG(QVariant, fromStdUtf8(title)), Q_ARG(QVariant, fromStdUtf8(message)), Q_ARG(QVariant, false), Q_ARG(QVariant, (int)0));
}
} else if(m_setupNewPin){
if(m_newPasscode.isEmpty()) {
m_newPasscode = password;
QMetaObject::invokeMethod(m_unlockPanel, "setupDialog", Q_ARG(QVariant, true),
Q_ARG(QVariant, fromStdUtf8(LOCALIZED("Enter PIN Again"))),
Q_ARG(QVariant, " "), Q_ARG(QVariant, minLen>0), Q_ARG(QVariant, minLen));
} else {
if(m_newPasscode != password) {
// passwords don't match, force re-entry
m_newPasscode.clear();
QMetaObject::invokeMethod(m_unlockPanel, "setupDialog", Q_ARG(QVariant, true),
Q_ARG(QVariant, fromStdUtf8(LOCALIZED("PIN Doesn't Match"))),
Q_ARG(QVariant, fromStdUtf8(LOCALIZED("Try Again"))), Q_ARG(QVariant, minLen>0), Q_ARG(QVariant, minLen));
if(minLen > 0) {
sprintf(hint, LOCALIZED("Must be at least %d numbers").c_str(), minLen);
} else {
sprintf(hint, " ");
}
hintStr=hint;
QMetaObject::invokeMethod(m_unlockPanel, "queueUpTitle", Q_ARG(QVariant, fromStdUtf8(LOCALIZED("Enter PIN"))), Q_ARG(QVariant, fromStdUtf8(hintStr)));
} else {
// validate and set new PIN
std::string errorText;
int res = Security::instance()->setPasscode("pin", std::string(password.toUtf8().data()), errorText);
if(res == Security::Success) {
changeState(StateUnlocked);
} else {
m_newPasscode.clear();
std::string titleText;
if (res == Security::FailureWeakPasswordRepeat || res == Security::FailureWeakPasswordSequence) {
titleText = LOCALIZED("PIN Not Secure");
}
else {
titleText = LOCALIZED("Enter PIN");
}
QMetaObject::invokeMethod(m_unlockPanel, "setupDialog", Q_ARG(QVariant, true),
Q_ARG(QVariant, fromStdUtf8(titleText)),
Q_ARG(QVariant, fromStdUtf8(errorText)), Q_ARG(QVariant, minLen>0), Q_ARG(QVariant, minLen));
if(minLen > 0) {
sprintf(hint, LOCALIZED("Must be at least %d numbers").c_str(), minLen);
} else {
sprintf(hint, " ");
}
hintStr = hint;
QMetaObject::invokeMethod(m_unlockPanel, "queueUpTitle", Q_ARG(QVariant, fromStdUtf8(LOCALIZED("Enter PIN"))), Q_ARG(QVariant, fromStdUtf8(hintStr)));
}
}
}
} else if(m_setupNewPassword) {
if(m_newPasscode.isEmpty()) {
m_newPasscode = password;
QMetaObject::invokeMethod(m_unlockPanel, "setupDialog", Q_ARG(QVariant, false),
Q_ARG(QVariant, fromStdUtf8(LOCALIZED("Enter Password Again"))),
Q_ARG(QVariant, " "), Q_ARG(QVariant, minLen>0), Q_ARG(QVariant, minLen));
} else {
if(m_newPasscode != password) {
// passwords don't match, force re-entry
m_newPasscode.clear();
QMetaObject::invokeMethod(m_unlockPanel, "setupDialog", Q_ARG(QVariant, false),
Q_ARG(QVariant, fromStdUtf8(LOCALIZED("Password Doesn't Match"))),
Q_ARG(QVariant, fromStdUtf8(LOCALIZED("Try Again"))), Q_ARG(QVariant, minLen>0), Q_ARG(QVariant, minLen));
if(minLen > 0) {
sprintf(hint, LOCALIZED("Must be at least %d characters").c_str(), minLen);
} else {
sprintf(hint, " ");
}
hintStr = hint;
QMetaObject::invokeMethod(m_unlockPanel, "queueUpTitle", Q_ARG(QVariant, fromStdUtf8(LOCALIZED("Enter Password"))), Q_ARG(QVariant, fromStdUtf8(hintStr)));
} else {
// validate and set new PIN
std::string errorText;
int res = Security::instance()->setPasscode("password", std::string(password.toUtf8().data()), errorText);
if(res == Security::Success) {
changeState(StateUnlocked);
} else {
m_newPasscode.clear();
std::string titleText;
if (res == Security::FailureWeakPasswordRepeat || res == Security::FailureWeakPasswordSequence) {
titleText = LOCALIZED("Password Not Secure");
}
else {
titleText = LOCALIZED("Enter Password");
}
QMetaObject::invokeMethod(m_unlockPanel, "setupDialog", Q_ARG(QVariant, false),
Q_ARG(QVariant, fromStdUtf8(titleText)),
Q_ARG(QVariant, fromStdUtf8(errorText)), Q_ARG(QVariant, minLen>0), Q_ARG(QVariant, minLen));
if(minLen > 0) {
sprintf(hint, LOCALIZED("Must be at least %d characters").c_str(), minLen);
} else {
sprintf(hint, " ");
}
hintStr = hint;
QMetaObject::invokeMethod(m_unlockPanel, "queueUpTitle", Q_ARG(QVariant, fromStdUtf8(LOCALIZED("Enter Password"))), Q_ARG(QVariant, fromStdUtf8(hintStr)));
}
}
}
}
}
void LockWindow::slotPinPanelFocusRequest(bool focusRequest)
{
if(focusRequest) {
static_cast<QGraphicsObject*>(m_unlockPanel)->setFocus();
IMEController::instance()->setClient(m_unlockPanel);
IMEController::instance()->notifyInputFocusChange(m_unlockPanel, true);
IMEController::instance()->notifyAutoCapChanged(m_unlockPanel, false);
} else {
m_unlockPanel->clearFocus();
IMEController::instance()->removeClient(m_unlockPanel);
}
}
void LockWindow::slotDialogButton1Pressed()
{
if(m_state == StateNewPinDialog) {
// user pressed Set New PIN
m_setupNewPin = true;
m_setupNewPassword = false;
changeState(StatePinEntry);
} else if(m_state == StateLastTryDialog) {
changeState(StatePinEntry);
}
}
void LockWindow::slotDialogButton2Pressed()
{
if(m_state == StateNewPinDialog) {
// user pressed Set New Password
m_setupNewPin = false;
m_setupNewPassword = true;
changeState(StatePinEntry);
}
}
void LockWindow::slotDialogButton3Pressed()
{
if(m_state == StateNewPinDialog) {
// user pressed CANCEl
// tell display manager to relock us
DisplayManager::instance()->lock();
}
}
bool LockWindow::paint()
{
if (m_clockWin) {
m_clockWin->tick();
}
return true;
}
QRectF LockWindow::boundingRect() const
{
return m_bounds;
}
void LockWindow::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
{
}
static const int kSlopFactorForClicks = 5;
bool LockWindow::handleFilteredSceneEvent(QEvent* event)
{
static QPointF mouseDownPos;
static bool mouseDown = false;
if ((event->type() == QEvent::KeyPress) || (event->type() == QEvent::KeyRelease)) { // filter the key events
if((m_state == StateNormal) || (m_state == StateDockMode) || ((m_state == StateUnlocked) && (isVisible())))
return true; // eat away all keys is the screen is locked
}
// if(m_state == StateInPhoneCall) {
// if(event->type() == QEvent::KeyRelease || event->type() == QEvent::KeyPress) {
// if(static_cast<QKeyEvent*>(event)->key() == Qt::Key_CoreNavi_Home ) {
// if(event->type() == QEvent::KeyRelease)
// changeState(StatePinEntry);;//tryUnlock();
// return true;
// }
// }
// return false;
// }
if((m_state != StateNormal) && (m_state != StateDockMode)) // only get mouse events when locked
return false;
if (event->type() == QEvent::GestureOverride) {
event->accept();
return true;
}
QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
Event ev;
ev.setMainFinger(true);
ev.x = mapFromScene(mouseEvent->pos()).x();
ev.y = mapFromScene(mouseEvent->pos()).y();
ev.modifiers = Event::modifiersFromQt(mouseEvent->modifiers());
switch (mouseEvent->type()) {
case QEvent::MouseButtonPress: {
mouseDown = true;
mouseDownPos = mouseEvent->pos();
ev.type = Event::PenDown;
handlePenDownEvent(&ev);
}
break;
case QEvent::MouseButtonRelease:{
if (mouseDown) {
mouseDown = false;
QPointF diff = mouseEvent->pos() - mouseDownPos;
ev.setClicked(diff.manhattanLength() <= kSlopFactorForClicks);
}
ev.type = Event::PenUp;
handlePenUpEvent(&ev);
}
break;
case QEvent::MouseMove:{
if(!mouseDown)
{
mouseDown = true; // fake the mouse down
mouseDownPos = mouseEvent->pos();
}
ev.type = Event::PenMove;
handlePenMoveEvent(&ev);
}
break;
default:
break;
}
return true;
}
void LockWindow::handlePenDownEvent(Event* event)
{
switch (m_state) {
case StateNormal:
case StateDockMode:
handlePenDownStateNormal(event);
break;
// case StateInPhoneCall:
// if (!event->rejected() && m_phoneAppWin) {
// mapCoordToWindow(m_phoneAppWin, event->x, event->y);
// m_phoneAppWin->inputEvent(event);
// }
// break;
default: break;
}
}
void LockWindow::handlePenDownStateNormal(Event* event)
{
// allow the button to be picked up if it is at rest
if (!m_lockButton->atRest() || !m_lockButton->contains(event->x, event->y))
return;
m_lockButton->press(true);
showHelp();
}
void LockWindow::handlePenMoveEvent(Event* event)
{
switch (m_state) {
case StateNormal:
case StateDockMode:
handlePenMoveStateNormal(event);
break;
// case StateInPhoneCall:
// if (!event->rejected() && m_phoneAppWin) {
// mapCoordToWindow(m_phoneAppWin, event->x, event->y);
// m_phoneAppWin->inputEvent(event);
// }
// break;
default: break;
}
}
void LockWindow::handlePenMoveStateNormal(Event* event)
{
if (!m_lockButton->m_pressed) {
// allow a move to pick up the unlock button
if (!m_lockButton->atRest() || !m_lockButton->contains(event->x, event->y))
return;
m_lockButton->press(true);
}
m_lockButton->setPos(event->x, event->y);
int distanceSquared = m_lockButton->distanceToAnchorSquared(event->x, event->y);
if ((distanceSquared > kSaucerRadiusSquared) && (event->y < m_lockButtonY))
hideHelp();
else
showHelp();
}
void LockWindow::handlePenUpEvent(Event* event)
{
switch (m_state) {
case StateNormal:
case StateDockMode:
handlePenUpStateNormal(event);
break;
// case StateInPhoneCall:
// if (!event->rejected() && m_phoneAppWin) {
// mapCoordToWindow(m_phoneAppWin, event->x, event->y);
// m_phoneAppWin->inputEvent(event);
// }
// break;
default: break;
}
}
void LockWindow::handlePenUpStateNormal(Event* event)
{
if (m_lockButton->m_pressed) {
m_lockButton->press(false);
int distanceSquared = m_lockButton->distanceToAnchorSquared(event->x, event->y);
if ((distanceSquared > kSaucerRadiusSquared) && (event->y < m_lockButtonY)){
tryUnlock();
SystemService::instance()->postLockButtonTriggered();
}
}
if (!isLocked())
return;
if (m_state != StatePinEntry) {
m_lockButton->setPos(m_lockButtonX, m_lockButtonY);
startHideHelpTimer();
}
else {
m_lockButton->reset();
}
// Is the click on a dashboard window?
if (event->clicked()) {
// Dashboard alert not active. Do nothing
if (!m_dashboardAlerts->isVisible())
return;
// Help saucer is visible. Do nothing
if (m_helpWin && m_helpWin->isVisible())
return;
DashboardWindowManager* dashMgr = getDashboardWindowManager();
if (!dashMgr)
return;
QPoint click = m_dashboardAlerts->mapFromParent(QPoint(event->x, event->y)).toPoint();
if (!m_dashboardAlerts->contains(click))
return;
m_dashboardAlerts->sendClickAt(click.x(), click.y());
}
}
void LockWindow::handlePenFlickEvent(Event* event)
{
switch (m_state) {
// case StateInPhoneCall:
// if (!event->rejected() && m_phoneAppWin) {
// mapCoordToWindow(m_phoneAppWin, event->x, event->y);
// m_phoneAppWin->inputEvent(event);
// }
// break;
default: break;
}
}
void LockWindow::handlePenCancelEvent(Event* event)
{
switch (m_state) {
case StateNormal:
case StateDockMode:
handlePenCancelStateNormal(event);
break;
// case StateInPhoneCall:
// if (!event->rejected() && m_phoneAppWin) {
// mapCoordToWindow(m_phoneAppWin, event->x, event->y);
// m_phoneAppWin->inputEvent(event);
// }
// break;
default: break;
}
}
void LockWindow::handlePenCancelStateNormal(Event* event)
{
if (!m_lockButton->m_pressed)
return;
m_lockButton->press(false);
// animate button back to rest location
m_lockButton->setPos(m_lockButtonX, m_lockButtonY);
startHideHelpTimer();
}
bool LockWindow::handleKeyDownEvent(Event* event)
{
switch (event->key) {
// pass through the following keys
case (Event::Key_Ringer):
case (Event::Key_VolumeDown):
case (Event::Key_VolumeUp):
case (Event::Key_MediaPlay):
case (Event::Key_MediaPause):
case (Event::Key_MediaStop):
case (Event::Key_MediaNext):
case (Event::Key_MediaPrevious):
case (Event::Key_MediaRepeatAll):
case (Event::Key_MediaRepeatTrack):
case (Event::Key_MediaRepeatNone):
case (Event::Key_MediaShuffleOn):
case (Event::Key_MediaShuffleOff):
case (Event::Key_HeadsetButton):
case (Event::Key_Headset):
case (Event::Key_HeadsetMic): {
return false;
}
default: break;
}
// don't eat the event unless we are locked
return isLocked();
}
bool LockWindow::handleKeyUpEvent(Event* event)
{
switch (event->key) {
// pass through the following keys
case (Event::Key_Ringer):
case (Event::Key_VolumeDown):
case (Event::Key_VolumeUp):
case (Event::Key_MediaPlay):
case (Event::Key_MediaPause):
case (Event::Key_MediaStop):
case (Event::Key_MediaNext):
case (Event::Key_MediaPrevious):
case (Event::Key_MediaRepeatAll):
case (Event::Key_MediaRepeatTrack):
case (Event::Key_MediaRepeatNone):
case (Event::Key_MediaShuffleOn):
case (Event::Key_MediaShuffleOff):
case (Event::Key_HeadsetButton):
case (Event::Key_Headset):
case (Event::Key_HeadsetMic): {
return false;
}
default: break;
}
// if (m_state == StatePinEntry && !event->rejected() && m_phoneAppWin) {
// m_phoneAppWin->inputEvent(event);
// }
// don't eat the event unless we are locked
return isLocked();
}
void LockWindow::startHideHelpTimer()
{
// prevent the help hint from hiding while a call is incoming
if (!m_popupActive || !m_popUpAlert->hasIncomingCallAlert()) {
m_hideHelpTimer.start(kHideHelpTimeoutInMS, true);
}
}
bool LockWindow::hideHelpTimeout()
{
hideHelp();
return false;
}
void LockWindow::showHelp()
{
if (!m_helpWin)
return;
m_helpWin->animateOpacity(1.0);
m_helpWin->setVisible(true);
m_hideHelpTimer.stop();
}
void LockWindow::hideHelp(bool animate)
{
if (!m_helpWin || !m_helpWin->isVisible())
return;
if (animate) {
m_helpWin->animateOpacity(0.0);
}
else {
m_helpWin->setVisible(false);
m_helpWin->setOpacity(0.0);
}
}
void LockWindow::showPinPanel()
{
if(!m_unlockPanel)
return;
bool isPin = true;
if(!m_setupNewPin && !m_setupNewPassword) {
int retriesLeft = EASPolicyManager::instance()->retriesLeft();
std::string message;
if(0 == Security::instance()->getLockMode().compare("password")) {
isPin = false;
}
if((retriesLeft == 1) && EASPolicyManager::instance()->getPolicy() && EASPolicyManager::instance()->getPolicy()->validMaxRetries()) {
message = LOCALIZED("Final Try");
} else {
if(isPin) {
message = LOCALIZED("Enter PIN");
} else {
message = LOCALIZED("Enter Password");
}
}
if(isPin) {
QMetaObject::invokeMethod(m_unlockPanel, "setupDialog", Q_ARG(QVariant, isPin),
Q_ARG(QVariant, fromStdUtf8(LOCALIZED("Device Locked"))),
Q_ARG(QVariant, fromStdUtf8(message)), Q_ARG(QVariant, false), Q_ARG(QVariant, (int)0));
} else {
QMetaObject::invokeMethod(m_unlockPanel, "setupDialog", Q_ARG(QVariant, isPin),
Q_ARG(QVariant, fromStdUtf8(LOCALIZED("Device Locked"))),
Q_ARG(QVariant, fromStdUtf8(message)), Q_ARG(QVariant, false), Q_ARG(QVariant, (int)0));
}
} else if(m_setupNewPin || m_setupNewPassword) {
int minLen = 0;
char hint[30];
std::string hintStr;
if(EASPolicyManager::instance()->getPolicy() && EASPolicyManager::instance()->getPolicy()->validMinLength()) {
minLen = EASPolicyManager::instance()->getPolicy()->minLength();
}
if(m_setupNewPin) {
if(minLen > 0) {
sprintf(hint, LOCALIZED("Must be at least %d numbers").c_str(), minLen);
} else {
sprintf(hint, " ");
}
hintStr = hint;
isPin = true;
QMetaObject::invokeMethod(m_unlockPanel, "setupDialog", Q_ARG(QVariant, isPin),
Q_ARG(QVariant, fromStdUtf8(LOCALIZED("Enter PIN"))),
Q_ARG(QVariant, fromStdUtf8(hintStr)), Q_ARG(QVariant, minLen>0), Q_ARG(QVariant, (int)minLen));
} else if(m_setupNewPassword) {
if(minLen > 0) {
sprintf(hint, LOCALIZED("Must be at least %d characters").c_str(), minLen);
} else {
sprintf(hint, " ");
}
hintStr = hint;
isPin = false;
QMetaObject::invokeMethod(m_unlockPanel, "setupDialog", Q_ARG(QVariant, isPin),
Q_ARG(QVariant, fromStdUtf8(LOCALIZED("Enter Password"))),
Q_ARG(QVariant, fromStdUtf8(hintStr)), Q_ARG(QVariant, minLen>0), Q_ARG(QVariant, (int)minLen));
}
}
if(isPin)
m_unlockPanel->setPos (-m_unlockPanel->boundingRect().width()/2, -m_unlockPanel->boundingRect().height()/2);
else
m_unlockPanel->setPos (-m_unlockPanel->boundingRect().width()/2, -m_unlockPanel->boundingRect().height());
QMetaObject::invokeMethod(m_unlockPanel, "fade", Q_ARG(QVariant, true), Q_ARG(QVariant, AS(lockFadeDuration)));
}
void LockWindow::hidePinPanel(bool animate)
{
if(!m_unlockPanel)
return;
QMetaObject::invokeMethod(m_unlockPanel, "fade", Q_ARG(QVariant, false), Q_ARG(QVariant, AS(lockFadeDuration)));
}
void LockWindow::showDialog()
{
if(!m_unlockDialog)
return;
m_unlockDialog->setPos (-m_unlockDialog->boundingRect().width()/2, -m_unlockDialog->boundingRect().height());
QMetaObject::invokeMethod(m_unlockDialog, "fade", Q_ARG(QVariant, true), Q_ARG(QVariant, AS(lockFadeDuration)));
}
void LockWindow::hideDialog(bool animate)
{
if(!m_unlockDialog)
return;
QMetaObject::invokeMethod(m_unlockDialog, "fade", Q_ARG(QVariant, false), Q_ARG(QVariant, AS(lockFadeDuration)));
}
//void LockWindow::showPhoneApp()
//{
// if (!m_phoneAppWin)
// return;
//
// m_statusBar->setBarOpaque(true);
//
// // If already there or animating to the right spot, just return
// if(((m_phoneWinAnimation.state() == QAbstractAnimation::Stopped) && (m_phoneAppWin->y() == m_phoneAppShownY)) ||
// ((m_phoneWinAnimation.state() != QAbstractAnimation::Stopped) && (m_phoneWinAnimation.endValue() == m_phoneAppShownY)))
// return;
//
// m_phoneAppWin->focusEvent(true);
//
// if(m_phoneWinAnimation.state() != QAbstractAnimation::Stopped)
// m_phoneWinAnimation.stop();
//
// if(!isVisible() || !DisplayManager::instance()->isDisplayOn()) {
// m_phoneAppWin->setPos(m_phoneAppWin->pos().x(), m_phoneAppShownY);
// SystemUiController::instance()->setDirectRenderingForWindow(SystemUiController::TOP_LEVEL_WINDOW_MANAGER, m_phoneAppWin, true);
// } else {
// m_phoneWinAnimation.setStartValue(m_phoneAppWin->pos().y());
// m_phoneWinAnimation.setEndValue(m_phoneAppShownY);
// m_phoneWinAnimation.start();
// }
//}
//
//void LockWindow::hidePhoneApp(bool animate)
//{
// if(!m_unlockPanel)
// return;
//
// m_unlockPanel->clearFocus();
//
// QMetaObject::invokeMethod(m_unlockPanel, "fade", Q_ARG(QVariant, false), Q_ARG(QVariant, 300));
//
// if (!m_phoneAppWin)
// return;
//
// m_statusBar->setBarOpaque(false);
//
// // If already there or animating to the right spot, just return
// if(((m_phoneWinAnimation.state() == QAbstractAnimation::Stopped) && (m_phoneAppWin->y() == m_phoneAppHiddenY)) ||
// ((m_phoneWinAnimation.state() != QAbstractAnimation::Stopped) && (m_phoneWinAnimation.endValue() == m_phoneAppHiddenY)))
// return;
//
// if (!isLocked())
// m_phoneAppWin->focusEvent(false);
//
// SystemUiController::instance()->setDirectRenderingForWindow(SystemUiController::TOP_LEVEL_WINDOW_MANAGER, m_phoneAppWin, false);
// if(m_phoneWinAnimation.state() != QAbstractAnimation::Stopped)
// m_phoneWinAnimation.stop();
//
// if (animate) {
// m_phoneWinAnimation.setStartValue(m_phoneAppWin->pos().y());
// m_phoneWinAnimation.setEndValue(m_phoneAppHiddenY);
// m_phoneWinAnimation.start();
// }
// else {
// m_phoneAppWin->setY(m_phoneAppHiddenY);
// }
//}
//
//void LockWindow::slotPhoneWindowAnimationFinished()
//{
// if (m_phoneAppWin && m_state == StateInPhoneCall) {
// SystemUiController::instance()->setDirectRenderingForWindow(SystemUiController::TOP_LEVEL_WINDOW_MANAGER, m_phoneAppWin, true);
// }
//}
void LockWindow::slotVisibilityChanged()
{
// if(isVisible() && (m_state == StateInPhoneCall) && m_phoneAppWin) {
// // just became visible again, so refocus the PIN window
// m_phoneAppWin->focusEvent(true);
// }
}
void LockWindow::showAlert(TransparentNode* alertNode)
{
if (!alertNode)
return;
// we will start showing a completely transparent node.
alertNode->setVisible(true);
alertNode->animateOpacity(1.0);
}
void LockWindow::hideAlert(TransparentNode* alertNode)
{
if (!alertNode)
return;
alertNode->animateOpacity(0.0);
}
void LockWindow::slotPositiveSpaceAboutToChange(const QRect& r, bool fullscreen, bool resizing)
{
// lock screen does not support full screen
if (r.y() == (qreal)kTopPadding) {
// if (m_phoneAppWin) {
// m_phoneAppWin->positiveSpaceAboutToChange(r, fullscreen);
// if (m_targetPositiveSpace.height() < r.height()) {
// // suppress a synchronous resize if the user won't see it
// if (m_state == StateInPhoneCall)
// m_phoneAppWin->resizeEventSync(r.width(), r.height());
// else
// m_phoneAppWin->resizeEvent(r.width(), r.height());
// }
// }
m_targetPositiveSpace = r;
}
}
void LockWindow::slotPositiveSpaceChanged(const QRect& r)
{
static bool initialBounds = true;
if (initialBounds) {
m_targetPositiveSpace = r;
initialBounds = false;
}
// if (r.y() == (qreal)kTopPadding) {
//
// if (m_phoneAppWin)
// m_phoneAppWin->positiveSpaceChanged(r);
// }
}
void LockWindow::slotPositiveSpaceChangeFinished(const QRect& r)
{
// if (r.y() == (qreal)kTopPadding && m_phoneAppWin) {
//
// m_phoneAppWin->resizeEvent(r.width(), r.height());
// m_phoneAppWin->positiveSpaceChangeFinished(r);
// }
}
// ------------------------------------------------------------------------------------------------
TransparentNode::TransparentNode(bool _stayVisible)
{
setOpacity(0.0);
setVisible(false);
m_stayVisible = _stayVisible;
m_fadeAnimation.setTargetObject(this);
m_fadeAnimation.setPropertyName("opacity");
m_fadeAnimation.setDuration(AS(lockFadeDuration));
m_fadeAnimation.setEasingCurve(AS_CURVE(lockFadeCurve));
connect(&m_fadeAnimation, SIGNAL(finished()), SLOT(fadeAnimationFinished()));
}
void TransparentNode::fadeAnimationFinished()
{
// nodes which aren't visible should not receive render calls
if(opacity() == 0.0 && !m_stayVisible)
setVisible(false);
}
void TransparentNode::animateOpacity(qreal newOpacity)
{
if(opacity() == newOpacity)
return;
if((m_fadeAnimation.state() == QAbstractAnimation::Running) &&
(m_fadeAnimation.endValue() == newOpacity))
return;
if(m_fadeAnimation.state() != QAbstractAnimation::Stopped)
m_fadeAnimation.stop();
m_fadeAnimation.setStartValue(opacity());
m_fadeAnimation.setEndValue(newOpacity);
m_fadeAnimation.start();
}
// ----------------------------------------------------------------------------------------
LockButton::LockButton()
: m_pressed(false)
, m_imageType(ImagePadlock)
, m_buttonImages(QVector<QPixmap>(4))
{
setVisible(true);
Settings* settings = Settings::LunaSettings();
QString prefix = qFromUtf8Stl(settings->lunaSystemResourcesPath);
// padlock images
QString filePath = prefix + "/screen-lock-padlock-off.png";
m_buttonImages[ImagePadlock] = QPixmap(filePath);
filePath = prefix + "/screen-lock-padlock-on.png";
m_buttonImages[ImagePadlock+1] = QPixmap(filePath);
// incoming call images
filePath = prefix + "/screen-lock-incoming-call-off.png";
m_buttonImages[ImageIncomingCall] = QPixmap(filePath);
filePath = prefix + "/screen-lock-incoming-call-on.png";
m_buttonImages[ImageIncomingCall+1] = QPixmap(filePath);
setPixmap(m_buttonImages[m_imageType + (m_pressed?1:0)]);
setOffset(-boundingRect().width()/2,-boundingRect().height()/2);
if (!m_buttonImages[m_imageType].isNull()) {
// make the unlock button easier to pick up
m_hitTarget = QRect(-(boundingRect().width() * 0.75), -(boundingRect().height() * 0.75),
boundingRect().width() * 1.5, boundingRect().height() * 1.5);
}
}
LockButton::~LockButton()
{
}
void LockButton::press(bool down)
{
m_pressed = down;
setPixmap(m_buttonImages[m_imageType + (m_pressed?1:0)]);
}
void LockButton::setAnchor(int x, int y)
{
m_anchorX = x;
m_anchorY = y;
reset();
}
int LockButton::distanceToAnchorSquared(int x, int y)
{
//return (int)sqrt( pow(m_anchorX - x, 2) + pow(m_anchorY - y, 2) );
int dx = m_anchorX - x;
int dy = m_anchorY - y;
return dx * dx + dy * dy;
}
bool LockButton::atRest() const
{
return pos().x() == m_anchorX && pos().y() == m_anchorY;
}
void LockButton::reset()
{
setPos(m_anchorX, m_anchorY);
press(false);
}
bool LockButton::contains(int x, int y) const
{
return m_hitTarget.contains(mapFromParent(QPoint(x, y)).toPoint());
}
void LockButton::setImageType(Type type)
{
switch (type) {
case ImagePadlock:
case ImageIncomingCall:
break;
default: return;
}
m_imageType = type;
setPixmap(m_buttonImages[m_imageType + (m_pressed?1:0)]);
}
// ------------------------------------------------------------------------------------------------
HelpWindow::HelpWindow()
: TransparentNode(false)
, m_splitIndex(0)
, m_font(0)
, m_surf(0)
{
setVisible(false);
setOpacity(0.0);
std::string filePath = Settings::LunaSettings()->lunaSystemResourcesPath + "/screen-lock-target-scrim.png";
m_surf = new QPixmap(filePath.c_str());
const char* fontName = Settings::LunaSettings()->fontLockWindow.c_str();
m_font = new QFont(fontName, 20); // $$$ font size
m_font->setPixelSize(20);
m_font->setBold(true);
textLayout.setFont(*m_font);
if (m_surf) {
m_bounds = QRect(-m_surf->width()/2, -m_surf->height()/2, m_surf->width(), m_surf->height());
}
}
HelpWindow::~HelpWindow()
{
if (m_font)
delete m_font;
if (m_surf)
delete m_surf;
}
QRectF HelpWindow::boundingRect() const
{
return m_bounds;
}
void HelpWindow::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
{
// draw the saucer
if (m_surf)
painter->drawPixmap(m_bounds, *m_surf);
QPen oldPen = painter->pen();
// draw the label
painter->setPen(QColor(0xFF, 0xFF, 0xFF, 0xFF));
textLayout.draw(painter, QPoint(-textLayout.boundingRect().width()/2,-textLayout.boundingRect().height()/2));
painter->setPen(oldPen);
}
void HelpWindow::setLabel(QString label)
{
textLayout.clearLayout();
textLayout.setText(label);
textLayout.setTextOption(QTextOption(Qt::AlignCenter));
QFontMetrics fontMetrics(*m_font);
// create the text layout for the label
int leading = fontMetrics.leading();
qreal height = 0;
textLayout.beginLayout();
int i = 0;
while (i < 2) {
QTextLine line = textLayout.createLine();
if (!line.isValid())
break;
line.setLineWidth(boundingRect().width());
height += leading;
line.setPosition(QPointF(0, height));
height += line.height();
}
textLayout.endLayout();
update();
}
// ----------------------------------------------------------------------------------------
LockBackground::LockBackground()
: m_showBackground(true)
, m_compMode(QPainter::CompositionMode_Source)
, m_statusBarPtr(0)
, m_wallpaperFullScreen(true)
, m_wallpaperPtr(0)
, m_wallpaperRotation(0)
{
// this covers the whole screen which blocks anything underneath it from being drawn
setOpacity(1.0);
// fill out the entire screen
int width = SystemUiController::instance()->currentUiWidth();
int height = SystemUiController::instance()->currentUiHeight();
m_bounds = QRect(-width/2, -height/2, width, height);
connect(((WindowServerLuna*)WindowServer::instance()), SIGNAL(signalWallpaperImageChanged(QPixmap*, bool, int)),
this, SLOT(slotWallpaperImageChanged(QPixmap*, bool, int)));
// Load mask pixmaps
std::string maskFilePath = Settings::LunaSettings()->lunaSystemResourcesPath + "/screen-lock-wallpaper-mask-bottom.png";
m_bottomMask = QPixmap(qFromUtf8Stl(maskFilePath));
maskFilePath = Settings::LunaSettings()->lunaSystemResourcesPath + "/screen-lock-wallpaper-mask-top.png";
m_topMask = QPixmap(qFromUtf8Stl(maskFilePath));
}
LockBackground::~LockBackground()
{
}
// QGraphicsItem::boundingRect
QRectF LockBackground::boundingRect() const
{
return m_bounds;
}
void LockBackground::resize(int width, int height)
{
m_bounds = QRect(-width/2, -height/2, width, height);
}
void LockBackground::setCompositionMode(QPainter::CompositionMode mode)
{
m_compMode = mode;
}
// QGraphicsItem::paint
void LockBackground::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
{
QPainter::CompositionMode oldMode = painter->compositionMode();
painter->setCompositionMode(m_compMode);
if (m_showBackground && m_wallpaperPtr) {
// blit wallpaper
if (m_wallpaperPtr && !m_wallpaperPtr->isNull()) {
if((m_wallpaperPtr->width() < m_bounds.width()) || (m_wallpaperPtr->height() < m_bounds.height())) {
painter->fillRect(m_bounds, Qt::darkGray);
}
painter->rotate(-m_wallpaperRotation);
painter->drawPixmap(-m_wallpaperPtr->width()/2, -m_wallpaperPtr->height()/2, m_wallpaperPtr->width(), m_wallpaperPtr->height(), *m_wallpaperPtr);
painter->rotate(m_wallpaperRotation);
} else {
// draw a solid gray background if we have not walpaper image
painter->fillRect(m_bounds, Qt::darkGray);
}
painter->setCompositionMode(QPainter::CompositionMode_SourceOver);
if (!m_bottomMask.isNull()) {
painter->drawPixmap(QRectF(m_bounds.x(), m_bounds.y() + m_bounds.height() - m_bottomMask.height(), m_bounds.width(), m_bottomMask.height()), m_bottomMask, m_bottomMask.rect());
}
if (!m_topMask.isNull()) {
painter->drawPixmap(m_bounds.x(), m_bounds.y() + kTopPadding, m_bounds.width(), m_topMask.height(), m_topMask);
}
}
else {
// draw a solid black background
painter->fillRect(m_bounds, QColor(0x0,0x0,0x0,0xff));
}
painter->setCompositionMode(oldMode);
}
void LockBackground::showBackground(bool visible)
{
if(m_statusBarPtr) {
m_statusBarPtr->setVisible(visible);
}
if (m_showBackground != visible) {
m_showBackground = visible;
update();
}
}
void LockBackground::slotWallpaperImageChanged(QPixmap* wallpaper, bool fullScreen, int rotationAngle)
{
m_wallpaperFullScreen = fullScreen;
m_wallpaperPtr = wallpaper;
m_wallpaperRotation = rotationAngle;
if(isVisible())
update();
}
// -------------------------------------------------------------------------------------------
DashboardAlerts::DashboardAlerts()
{
std::string filePath = Settings::LunaSettings()->lunaSystemResourcesPath + "/dashboard-scroll-fade.png";
m_scrollFade = QPixmap (filePath.c_str());
if (m_scrollFade.isNull())
g_warning ("scrollFade image missing");
filePath = Settings::LunaSettings()->lunaSystemResourcesPath + "/menu-divider.png";
m_divider = QPixmap (filePath.c_str());
if (m_divider.isNull())
g_warning ("divider image missing");
kMaxDashboardItems = 6;
kDashboardItemHeight = 52; // max height of the dashboard
kVisibleDashboard = 5.5;
kBottomPadding = 3;
kTopPadding = 1;
kDashboardWidgetHeight = kDashboardItemHeight * kVisibleDashboard + m_divider.height() * (kMaxDashboardItems - 1);
m_bounds = QRect(-(kMaxWidth/2), -(kDashboardWidgetHeight/2), kMaxWidth, kDashboardWidgetHeight);
setVisible(true);
setOpacity(1.0);
}
DashboardAlerts::~DashboardAlerts()
{
}
QRectF DashboardAlerts::boundingRect() const
{
return m_bounds;
}
void DashboardAlerts::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
{
int itemHeight = 0;
QList<DashboardWindow*> dashboardWindows = getDashboardWindows();
int numSurfaces = MIN(dashboardWindows.size(), (int)kMaxDashboardItems);
if (numSurfaces == 0)
return;
qreal dashboardHeight = numSurfaces * kDashboardItemHeight + (numSurfaces - 1) * m_divider.height();
if (numSurfaces == kMaxDashboardItems)
dashboardHeight -= kDashboardItemHeight/2;
m_bounds = QRect(-(kMaxWidth/2), -(dashboardHeight)/2, kMaxWidth, dashboardHeight);
QRect imageBounds = m_bounds.adjusted (-kShadowWidth, -kShadowWidth -kTopPadding, kShadowWidth, kShadowWidth + kBottomPadding);
if (gBackground9Tile) {
gBackground9Tile->resize(imageBounds.width(), imageBounds.height());
gBackground9Tile->paint (painter, imageBounds.topLeft());
}
#if defined(USE_CLIP_PATH)
bool hasClipping = false;
QPainterPath oldClipPath, paintPath;
paintPath.addRoundedRect (m_bounds, 10,10);
if (painter->hasClipping()) {
hasClipping = true;
oldClipPath = painter->clipPath();
}
painter->setClipPath (paintPath);
#endif
int yOffset = m_bounds.top();
for (int i = 0; i < numSurfaces; ++i) {
const QPixmap* pix = dashboardWindows[dashboardWindows.size() - 1 - i]->acquireScreenPixmap();
if (!pix) {
g_critical("%s: Failed to acquireScreenPixmap", __PRETTY_FUNCTION__);
continue;
}
itemHeight = pix->height();
painter->drawPixmap(-m_bounds.width()/2, yOffset, m_bounds.width(), itemHeight, *pix);
yOffset += itemHeight;
if (i != numSurfaces - 1) { // not the last one, draw a divider
painter->drawPixmap(QRect (-m_bounds.width()/2, yOffset, m_bounds.width(), m_divider.height()), m_divider, m_divider.rect());
yOffset += m_divider.height();
}
else {
if (numSurfaces == kMaxDashboardItems) {
painter->drawPixmap (QRect (-m_bounds.width()/2, m_bounds.bottom() - m_scrollFade.height(), m_bounds.width(), m_scrollFade.height()), m_scrollFade);
}
}
}
#if defined(USE_CLIP_PATH)
if (hasClipping)
painter->setClipPath(oldClipPath);
else
painter->setClipping (false);
#endif
}
QList<DashboardWindow*> DashboardAlerts::getDashboardWindows() const
{
QList<DashboardWindow*> windows;
DashboardWindowManager* dashMgr = 0;
DashboardWindowContainer* container = 0;
dashMgr = getDashboardWindowManager();
if(dashMgr)
container = dashMgr->dashboardWindowContainer();
if (container) {
windows = container->windows();
}
return windows;
}
void DashboardAlerts::sendClickAt(int x, int y) // x,y are in this item's coordinate space
{
DashboardWindowManager* dashMgr = getDashboardWindowManager();
if (!dashMgr)
return;
QList<DashboardWindow*> dashboardWindows = getDashboardWindows();
if (dashboardWindows.empty())
return;
int numSurfaces = MIN(dashboardWindows.size(), (int)kMaxDashboardItems);
int surfaceHit = (m_bounds.height()/2 + y) / (kDashboardItemHeight + m_divider.height()); // 0,0 of the m_bounds is set at the center in the paint method
int dashboardIndex = dashboardWindows.size() - 1 - surfaceHit;
if ((dashboardIndex < dashboardWindows.size() - numSurfaces)
|| (dashboardIndex >= dashboardWindows.size()))
return;
y = ((m_bounds.height()/2 + y) % (kDashboardItemHeight + m_divider.height())) - kDashboardItemHeight/2;
dashMgr->sendClicktoDashboardWindow(dashboardIndex, x, y, true);
}
// -------------------------------------------------------------------------------------------
BannerAlerts::BannerAlerts()
: BannerMessageView(BannerMessageView::NoScroll)
{
m_bounds = QRect(-(int)kMaxWidth/2, -(int)kBannerWidgetHeight/2,
kMaxWidth, kBannerWidgetHeight);
kPadding = 10;
}
BannerAlerts::~BannerAlerts()
{
}
QRectF BannerAlerts::boundingRect() const
{
return m_bounds;
}
int BannerAlerts::bmViewGetWidth() const
{
return m_bounds.width();
}
void BannerAlerts::bmViewUpdated()
{
update();
}
void BannerAlerts::bmViewMessageCountUpdated(int count)
{
m_msgCount = count;
}
void BannerAlerts::bmViewShowingNonSuppressibleMessage(bool val)
{
return;
}
void BannerAlerts::bmViewAddActiveCallBanner(const std::string& msg, const std::string& icon, uint32_t time)
{
return;
}
void BannerAlerts::bmViewRemoveActiveCallBanner()
{
return;
}
void BannerAlerts::bmViewUpdateActiveCallBanner(const std::string& msg, const std::string& icon, uint32_t time)
{
return;
}
void BannerAlerts::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
{
QRect imageBounds = m_bounds.adjusted (-kShadowWidth - kPadding, - kShadowWidth - kPadding, kShadowWidth + kPadding, kShadowWidth + kPadding);
if (gBackground9Tile) {
gBackground9Tile->resize(imageBounds.width(), imageBounds.height());
gBackground9Tile->paint (painter, QPointF (-imageBounds.width()/2, -imageBounds.height()/2));
}
else {
painter->fillRect (m_bounds, QColor (0, 0, 0, 0xff));
}
if (m_msgCount) {
int tx = m_bounds.x();
int ty = m_bounds.center().y() - kBannerWidgetHeight/2;
painter->translate(tx, ty);
BannerMessageHandler::instance()->drawView(painter, this);
painter->translate(-tx, -ty);
}
}
// -------------------------------------------------------------------------------------------
PopUpAlert::PopUpAlert()
{
m_bounds = QRect(-(int)kMaxWidth/2, 0, kMaxWidth, 0);
kPadding = 10;
}
PopUpAlert::~PopUpAlert()
{
}
bool PopUpAlert::hasIncomingCallAlert() const
{
const Window* alert = getDashboardWindowManager()->getActiveAlertWin();
return (alert && static_cast<const AlertWindow*>(alert)->isIncomingCallAlert());
}
void PopUpAlert::adjustAlertBounds()
{
const AlertWindow* alertWin = (AlertWindow*)getActiveAlertWin();
const QRect r = (alertWin ? alertWin->contentRect() : QRect(0,0,0,0));
if (r.isEmpty())
return;
if (hasIncomingCallAlert()) {
// FIXME: yet to be resolved, Larry to send visual design
m_bounds.setHeight(SystemUiController::instance()->currentUiHeight() - kTopPadding - kAlertsFromBottom);
m_bounds.moveTop(-m_bounds.height()/2);
setPos(0, parentItem()->boundingRect().y() + kTopPadding + m_bounds.height()/2);
}
else {
m_bounds.setHeight(r.height() + kPadding * 2);
m_bounds.moveTop(-m_bounds.height()/2 - kPadding);
setPos(0, 0);
}
prepareGeometryChange();
}
QRectF PopUpAlert::boundingRect() const
{
return m_bounds;
}
void PopUpAlert::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
{
const AlertWindow* alertWin = (AlertWindow*)getActiveAlertWin();
if (alertWin) {
QRect alertBounds = alertWin->contentRect();
if (!alertBounds.isEmpty()) {
const QPixmap* alertSurf = const_cast<AlertWindow*>(alertWin)->acquireScreenPixmap();
QRect imageBounds = alertBounds.adjusted (-kShadowWidth -kPadding , -kShadowWidth -kPadding, kShadowWidth + kPadding, kShadowWidth + kPadding);
if (gBackground9Tile) {
gBackground9Tile->resize(imageBounds.width(), imageBounds.height());
gBackground9Tile->paint (painter, QPointF (-imageBounds.width()/2, -imageBounds.height()/2));
}
else {
painter->fillRect (m_bounds, QColor (0, 0, 0, 0xff));
}
// render cut-out part of alert
painter->drawPixmap(-alertBounds.width()/2, -alertBounds.height()/2, alertBounds.width(), alertBounds.height(),
*alertSurf,
alertBounds.x(), alertBounds.y(), alertBounds.width(), alertBounds.height());
}
}
}
bool PopUpAlert::hasDisplayableContent() const
{
const AlertWindow* win = (const AlertWindow*)getActiveAlertWin();
if (win) {
return !win->contentRect().isEmpty();
}
return false;
}
const Window* PopUpAlert::getActiveAlertWin() const
{
DashboardWindowManager* dashMgr = getDashboardWindowManager();
return (dashMgr ? dashMgr->getActiveAlertWin() : 0);
}
// -----------------------------------------------------------------------------------------
DashboardWindowManager* getDashboardWindowManager()
{
WindowManagerBase* dashMgr = static_cast<WindowServerLuna*>(WindowServer::instance())->dashboardWindowManager();
return (dashMgr ? static_cast<DashboardWindowManager*>(dashMgr) : 0);
}
#include "LockWindow.moc"
| [
"roger.stringer@palm.com"
] | roger.stringer@palm.com |
a7f6e82063b38b34683df417af682c039f5cd2d8 | e63caeb2dd77b2fc634e383e5df152c21ac66d38 | /DuiLib/DuiLib/src/Control/UILabel.cpp | fe91cf5a562642bb134a4cc643006f1d60e56c41 | [] | no_license | uvbs/myduilib | fde32154943333f412cc7612d71145ba8285016a | a9846c932c8a6e8237d2952f17fe88afcc1824a0 | refs/heads/master | 2021-01-24T03:38:14.104596 | 2015-08-20T01:32:01 | 2015-08-20T01:32:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 26,540 | cpp | #include "StdAfx.h"
#include <atlconv.h>
namespace DuiLib
{
REGIST_DUICLASS(CLabelUI);
Color _MakeRGB(int a, Color cl)
{
return Color(a, cl.GetR(), cl.GetG(), cl.GetB());
}
Color _MakeRGB(int r, int g, int b)
{
return Color(255, r, g, b);
}
CLabelUI::CLabelUI() : m_uTextStyle(DT_VCENTER), m_dwTextColor(0),
m_dwDisabledTextColor(0),
m_iFont(-1),
m_bShowHtml(false),
m_EnableEffect(false),
m_gdiplusToken(0),
m_TextRenderingHintAntiAlias(TextRenderingHintSystemDefault),
m_TransShadow(60),
m_TransText(168),
m_TransShadow1(60),
m_TransText1(168),
m_hAlign(DT_LEFT),
m_vAlign(DT_CENTER),
m_dwTextColor1(-1),
m_dwTextShadowColorA(0xff000000),
m_dwTextShadowColorB(-1),
m_GradientAngle(0),
m_EnabledStroke(false),
m_TransStroke(255),
m_dwStrokeColor(0),
m_EnabledShadow(false),
m_GradientLength(0)
{
m_ShadowOffset.X = 0.0f;
m_ShadowOffset.Y = 0.0f;
m_ShadowOffset.Width = 0.0f;
m_ShadowOffset.Height = 0.0f;
GdiplusStartup( &m_gdiplusToken,&m_gdiplusStartupInput, NULL);
::ZeroMemory(&m_rcTextPadding, sizeof(m_rcTextPadding));
}
//************************************
// Method: ~CLabelUI
// FullName: CLabelUI::~CLabelUI
// Access: public
// Returns:
// Qualifier:
// Note:
//************************************
CLabelUI::~CLabelUI()
{
try
{
GdiplusShutdown( m_gdiplusToken );
}
catch (...)
{
throw "CLabelUI::~CLabelUI";
}
}
LPCTSTR CLabelUI::GetClassName()
{
return _T("LabelUI");
}
LPCTSTR CLabelUI::GetClass() const
{
return _T("LabelUI");
}
LPVOID CLabelUI::GetInterface(LPCTSTR pstrName)
{
if( _tcscmp(pstrName, _T("Label")) == 0 ) return static_cast<CLabelUI*>(this);
return CControlUI::GetInterface(pstrName);
}
void CLabelUI::SetTextStyle(UINT uStyle)
{
m_uTextStyle = uStyle;
Invalidate();
}
UINT CLabelUI::GetTextStyle() const
{
return m_uTextStyle;
}
void CLabelUI::SetTextColor(DWORD dwTextColor)
{
m_dwTextColor = dwTextColor;
Invalidate();
}
DWORD CLabelUI::GetTextColor() const
{
return m_dwTextColor;
}
void CLabelUI::SetDisabledTextColor(DWORD dwTextColor)
{
m_dwDisabledTextColor = dwTextColor;
Invalidate();
}
DWORD CLabelUI::GetDisabledTextColor() const
{
return m_dwDisabledTextColor;
}
void CLabelUI::SetFont(int index)
{
m_iFont = index;
Invalidate();
}
int CLabelUI::GetFont() const
{
return m_iFont;
}
RECT CLabelUI::GetTextPadding() const
{
return m_rcTextPadding;
}
void CLabelUI::SetTextPadding(RECT rc)
{
m_rcTextPadding = rc;
Invalidate();
}
bool CLabelUI::IsShowHtml()
{
return m_bShowHtml;
}
void CLabelUI::SetShowHtml(bool bShowHtml)
{
if( m_bShowHtml == bShowHtml ) return;
m_bShowHtml = bShowHtml;
Invalidate();
}
SIZE CLabelUI::EstimateSize(SIZE szAvailable)
{
if( m_cxyFixed.cy == 0 ) return CSize(m_cxyFixed.cx, m_pManager->GetFontInfo(GetFont())->tm.tmHeight + 4);
return CControlUI::EstimateSize(szAvailable);
}
void CLabelUI::DoEvent(TEventUI& event)
{
if( event.Type == UIEVENT_SETFOCUS )
{
m_bFocused = true;
return;
}
if( event.Type == UIEVENT_KILLFOCUS )
{
m_bFocused = false;
return;
}
if( event.Type == UIEVENT_MOUSEENTER )
{
// return;
}
if( event.Type == UIEVENT_MOUSELEAVE )
{
// return;
}
CControlUI::DoEvent(event);
}
void CLabelUI::SetAttribute(LPCTSTR pstrName, LPCTSTR pstrValue)
{
if( _tcscmp(pstrName, _T("align")) == 0 ) {
if( _tcsstr(pstrValue, _T("left")) != NULL ) {
m_uTextStyle &= ~(DT_CENTER | DT_RIGHT);
m_uTextStyle |= DT_LEFT;
m_hAlign = DT_LEFT;
}
if( _tcsstr(pstrValue, _T("center")) != NULL ) {
m_uTextStyle &= ~(DT_LEFT | DT_RIGHT);
m_uTextStyle |= DT_CENTER;
m_hAlign = DT_CENTER;
}
if( _tcsstr(pstrValue, _T("right")) != NULL ) {
m_uTextStyle &= ~(DT_LEFT | DT_CENTER);
m_uTextStyle |= DT_RIGHT;
m_hAlign = DT_RIGHT;
}
if( _tcsstr(pstrValue, _T("top")) != NULL ) {
m_uTextStyle &= ~(DT_BOTTOM | DT_VCENTER);
m_uTextStyle |= DT_TOP;
m_vAlign = DT_TOP;
}
if( _tcsstr(pstrValue, _T("vcenter")) != NULL ) {
m_uTextStyle &= ~(DT_TOP | DT_BOTTOM);
m_uTextStyle |= DT_VCENTER;
m_vAlign = DT_CENTER;
}
if( _tcsstr(pstrValue, _T("bottom")) != NULL ) {
m_uTextStyle &= ~(DT_TOP | DT_VCENTER);
m_uTextStyle |= DT_BOTTOM;
m_vAlign = DT_RIGHT;
}
}
else if( _tcscmp(pstrName, _T("endellipsis")) == 0 ) {
if( _tcscmp(pstrValue, _T("true")) == 0 ) m_uTextStyle |= DT_END_ELLIPSIS;
else m_uTextStyle &= ~DT_END_ELLIPSIS;
}
else if( _tcscmp(pstrName, _T("font")) == 0 ) SetFont(_ttoi(pstrValue));
else if( _tcscmp(pstrName, _T("textcolor")) == 0 ) {
if( *pstrValue == _T('#')) pstrValue = ::CharNext(pstrValue);
LPTSTR pstr = NULL;
DWORD clrColor = _tcstoul(pstrValue, &pstr, 16);
SetTextColor(clrColor);
}
else if( _tcscmp(pstrName, _T("disabledtextcolor")) == 0 ) {
if( *pstrValue == _T('#')) pstrValue = ::CharNext(pstrValue);
LPTSTR pstr = NULL;
DWORD clrColor = _tcstoul(pstrValue, &pstr, 16);
SetDisabledTextColor(clrColor);
}
else if( _tcscmp(pstrName, _T("textpadding")) == 0 ) {
RECT rcTextPadding = { 0 };
LPTSTR pstr = NULL;
rcTextPadding.left = _tcstol(pstrValue, &pstr, 10); ASSERT(pstr);
rcTextPadding.top = _tcstol(pstr + 1, &pstr, 10); ASSERT(pstr);
rcTextPadding.right = _tcstol(pstr + 1, &pstr, 10); ASSERT(pstr);
rcTextPadding.bottom = _tcstol(pstr + 1, &pstr, 10); ASSERT(pstr);
SetTextPadding(rcTextPadding);
}
else if( _tcscmp(pstrName, _T("showhtml")) == 0 ) SetShowHtml(_tcscmp(pstrValue, _T("true")) == 0);
else if( _tcscmp(pstrName, _T("enabledeffect")) == 0 ) SetEnabledEffect(_tcscmp(pstrValue, _T("true")) == 0);
else if( _tcscmp(pstrName, _T("rhaa")) == 0 ) SetTextRenderingHintAntiAlias(_ttoi(pstrValue));
else if( _tcscmp(pstrName, _T("transshadow")) == 0 ) SetTransShadow(_ttoi(pstrValue));
else if( _tcscmp(pstrName, _T("transtext")) == 0 ) SetTransText(_ttoi(pstrValue));
else if( _tcscmp(pstrName, _T("transshadow1")) == 0 ) SetTransShadow1(_ttoi(pstrValue));
else if( _tcscmp(pstrName, _T("transtext1")) == 0 ) SetTransText1(_ttoi(pstrValue));
else if( _tcscmp(pstrName, _T("gradientangle")) == 0 ) SetGradientAngle(_ttoi(pstrValue));
else if( _tcscmp(pstrName, _T("enabledstroke")) == 0 ) SetEnabledStroke(_tcscmp(pstrValue, _T("true")) == 0);
else if( _tcscmp(pstrName, _T("enabledshadow")) == 0 ) SetEnabledShadow(_tcscmp(pstrValue, _T("true")) == 0);
else if( _tcscmp(pstrName, _T("transstroke")) == 0 ) SetTransStroke(_ttoi(pstrValue));
else if( _tcscmp(pstrName, _T("gradientlength")) == 0 ) SetGradientLength(_ttoi(pstrValue));
else if( _tcscmp(pstrName, _T("shadowoffset")) == 0 ){
LPTSTR pstr = NULL;
int offsetx = _tcstol(pstrValue, &pstr, 10); ASSERT(pstr);
int offsety = _tcstol(pstr + 1, &pstr, 10); ASSERT(pstr);
SetShadowOffset(offsetx,offsety);
}
else if( _tcscmp(pstrName, _T("textcolor1")) == 0 ) {
if( *pstrValue == _T('#')) pstrValue = ::CharNext(pstrValue);
LPTSTR pstr = NULL;
DWORD clrColor = _tcstoul(pstrValue, &pstr, 16);
SetTextColor1(clrColor);
}
else if( _tcscmp(pstrName, _T("textshadowcolora")) == 0 ) {
if( *pstrValue == _T('#')) pstrValue = ::CharNext(pstrValue);
LPTSTR pstr = NULL;
DWORD clrColor = _tcstoul(pstrValue, &pstr, 16);
SetTextShadowColorA(clrColor);
}
else if( _tcscmp(pstrName, _T("textshadowcolorb")) == 0 ) {
if( *pstrValue == _T('#')) pstrValue = ::CharNext(pstrValue);
LPTSTR pstr = NULL;
DWORD clrColor = _tcstoul(pstrValue, &pstr, 16);
SetTextShadowColorB(clrColor);
}
else if( _tcscmp(pstrName, _T("strokecolor")) == 0 ) {
if( *pstrValue == _T('#')) pstrValue = ::CharNext(pstrValue);
LPTSTR pstr = NULL;
DWORD clrColor = _tcstoul(pstrValue, &pstr, 16);
SetStrokeColor(clrColor);
}
else CControlUI::SetAttribute(pstrName, pstrValue);
}
void CLabelUI::PaintText(HDC hDC)
{
if( m_dwTextColor == 0 ) m_dwTextColor = m_pManager->GetDefaultFontColor();
if( m_dwDisabledTextColor == 0 ) m_dwDisabledTextColor = m_pManager->GetDefaultDisabledColor();
RECT rc = m_rcItem;
rc.left += m_rcTextPadding.left;
rc.right -= m_rcTextPadding.right;
rc.top += m_rcTextPadding.top;
rc.bottom -= m_rcTextPadding.bottom;
if(!GetEnabledEffect())
{
if( m_sText.IsEmpty() ) return;
int nLinks = 0;
if( IsEnabled() ) {
if( m_bShowHtml )
CRenderEngine::DrawHtmlText(hDC, m_pManager, rc, m_sText, m_dwTextColor, \
NULL, NULL, nLinks, DT_SINGLELINE | m_uTextStyle);
else
CRenderEngine::DrawText(hDC, m_pManager, rc, m_sText, m_dwTextColor, \
m_iFont, DT_SINGLELINE | m_uTextStyle);
}
else {
if( m_bShowHtml )
CRenderEngine::DrawHtmlText(hDC, m_pManager, rc, m_sText, m_dwDisabledTextColor, \
NULL, NULL, nLinks, DT_SINGLELINE | m_uTextStyle);
else
CRenderEngine::DrawText(hDC, m_pManager, rc, m_sText, m_dwDisabledTextColor, \
m_iFont, DT_SINGLELINE | m_uTextStyle);
}
}
else
{
Font nFont(hDC,m_pManager->GetFont(GetFont()));
Graphics nGraphics(hDC);
nGraphics.SetTextRenderingHint(m_TextRenderingHintAntiAlias);
StringFormat format;
format.SetAlignment((StringAlignment)m_hAlign);
format.SetLineAlignment((StringAlignment)m_vAlign);
RectF nRc((float)rc.left,(float)rc.top,(float)rc.right-rc.left,(float)rc.bottom-rc.top);
RectF nShadowRc = nRc;
nShadowRc.X += m_ShadowOffset.X;
nShadowRc.Y += m_ShadowOffset.Y;
int nGradientLength = GetGradientLength();
if(nGradientLength == 0)
nGradientLength = (rc.bottom-rc.top);
LinearGradientBrush nLineGrBrushA(Point(GetGradientAngle(), 0),Point(0,nGradientLength),_MakeRGB(GetTransShadow(),GetTextShadowColorA()),_MakeRGB(GetTransShadow1(),GetTextShadowColorB() == -1?GetTextShadowColorA():GetTextShadowColorB()));
LinearGradientBrush nLineGrBrushB(Point(GetGradientAngle(), 0),Point(0,nGradientLength),_MakeRGB(GetTransText(),GetTextColor()),_MakeRGB(GetTransText1(),GetTextColor1() == -1?GetTextColor():GetTextColor1()));
if(GetEnabledStroke() && GetStrokeColor() > 0)
{
LinearGradientBrush nLineGrBrushStroke(Point(GetGradientAngle(),0),Point(0,rc.bottom-rc.top+2),_MakeRGB(GetTransStroke(),GetStrokeColor()),_MakeRGB(GetTransStroke(),GetStrokeColor()));
#ifdef _UNICODE
nRc.Offset(-1,0);
nGraphics.DrawString(m_TextValue,m_TextValue.GetLength(),&nFont,nRc,&format,&nLineGrBrushStroke);
nRc.Offset(2,0);
nGraphics.DrawString(m_TextValue,m_TextValue.GetLength(),&nFont,nRc,&format,&nLineGrBrushStroke);
nRc.Offset(-1,-1);
nGraphics.DrawString(m_TextValue,m_TextValue.GetLength(),&nFont,nRc,&format,&nLineGrBrushStroke);
nRc.Offset(0,2);
nGraphics.DrawString(m_TextValue,m_TextValue.GetLength(),&nFont,nRc,&format,&nLineGrBrushStroke);
nRc.Offset(0,-1);
#else
USES_CONVERSION;
wstring mTextValue = A2W(m_TextValue.GetData());
nRc.Offset(-1,0);
nGraphics.DrawString(mTextValue.c_str(),mTextValue.length(),&nFont,nRc,&format,&nLineGrBrushStroke);
nRc.Offset(2,0);
nGraphics.DrawString(mTextValue.c_str(),mTextValue.length(),&nFont,nRc,&format,&nLineGrBrushStroke);
nRc.Offset(-1,-1);
nGraphics.DrawString(mTextValue.c_str(),mTextValue.length(),&nFont,nRc,&format,&nLineGrBrushStroke);
nRc.Offset(0,2);
nGraphics.DrawString(mTextValue.c_str(),mTextValue.length(),&nFont,nRc,&format,&nLineGrBrushStroke);
nRc.Offset(0,-1);
#endif
}
#ifdef _UNICODE
if(GetEnabledShadow() && (GetTextShadowColorA() > 0 || GetTextShadowColorB() > 0))
nGraphics.DrawString(m_TextValue,m_TextValue.GetLength(),&nFont,nShadowRc,&format,&nLineGrBrushA);
nGraphics.DrawString(m_TextValue,m_TextValue.GetLength(),&nFont,nRc,&format,&nLineGrBrushB);
#else
USES_CONVERSION;
wstring mTextValue = A2W(m_TextValue.GetData());
if(GetEnabledShadow() && (GetTextShadowColorA() > 0 || GetTextShadowColorB() > 0))
nGraphics.DrawString(mTextValue.c_str(),mTextValue.length(),&nFont,nShadowRc,&format,&nLineGrBrushA);
nGraphics.DrawString(mTextValue.c_str(),mTextValue.length(),&nFont,nRc,&format,&nLineGrBrushB);
#endif
}
}
//************************************
// Method: SetTransShadow
// FullName: CLabelUI::SetTransShadow
// Access: public
// Returns: void
// Qualifier:
// Parameter: int _TransShadow
// Note:
//************************************
void CLabelUI::SetTransShadow( int _TransShadow )
{
try
{
m_TransShadow = _TransShadow;
}
catch (...)
{
throw "CLabelUI::SetTransShadow";
}
}
//************************************
// Method: GetTransShadow
// FullName: CLabelUI::GetTransShadow
// Access: public
// Returns: int
// Qualifier:
// Note:
//************************************
int CLabelUI::GetTransShadow()
{
try
{
return m_TransShadow;
}
catch (...)
{
throw "CLabelUI::GetTransShadow";
}
}
//************************************
// Method: SetTextRenderingHintAntiAlias
// FullName: CLabelUI::SetTextRenderingHintAntiAlias
// Access: public
// Returns: void
// Qualifier:
// Parameter: int _TextRenderingHintAntiAlias
// Note:
//************************************
void CLabelUI::SetTextRenderingHintAntiAlias( int _TextRenderingHintAntiAlias )
{
try
{
if(_TextRenderingHintAntiAlias < 0 || _TextRenderingHintAntiAlias > 5)
_TextRenderingHintAntiAlias = 0;
m_TextRenderingHintAntiAlias = (TextRenderingHint)_TextRenderingHintAntiAlias;
}
catch (...)
{
throw "CLabelUI::SetTextRenderingHintAntiAlias";
}
}
//************************************
// Method: GetTextRenderingHintAntiAlias
// FullName: CLabelUI::GetTextRenderingHintAntiAlias
// Access: public
// Returns: int
// Qualifier:
// Note:
//************************************
int CLabelUI::GetTextRenderingHintAntiAlias()
{
try
{
return m_TextRenderingHintAntiAlias;
}
catch (...)
{
throw "CLabelUI::GetTextRenderingHintAntiAlias";
}
}
//************************************
// Method: SetShadowOffset
// FullName: CLabelUI::SetShadowOffset
// Access: public
// Returns: void
// Qualifier:
// Parameter: int _offset
// Parameter: int _angle
// Note:
//************************************
void CLabelUI::SetShadowOffset( int _offset,int _angle )
{
try
{
if(_angle > 180 || _angle < -180)
return;
RECT rc = m_rcItem;
if(_angle >= 0 && _angle <= 180)
rc.top -= _offset;
else if(_angle > -180 && _angle < 0)
rc.top += _offset;
if(_angle > -90 && _angle <= 90)
rc.left -= _offset;
else if( _angle > 90 || _angle < -90)
rc.left += _offset;
m_ShadowOffset.X = (float)rc.top;
m_ShadowOffset.Y = (float)rc.left;
}
catch (...)
{
throw "CLabelUI::SetShadowOffset";
}
}
//************************************
// Method: GetShadowOffset
// FullName: CLabelUI::GetShadowOffset
// Access: public
// Returns: RectF
// Qualifier:
// Note:
//************************************
RectF CLabelUI::GetShadowOffset()
{
try
{
return m_ShadowOffset;
}
catch (...)
{
throw "CLabelUI::GetShadowOffset";
}
}
//************************************
// Method: SetText
// FullName: CLabelUI::SetText
// Access: public
// Returns: void
// Qualifier:
// Parameter: LPCTSTR pstrText
// Note:
//************************************
void CLabelUI::SetText( LPCTSTR pstrText )
{
try
{
if(!GetEnabledEffect())
return CControlUI::SetText(pstrText);
m_TextValue = pstrText;
}
catch (...)
{
throw "CLabelUI::SetText";
}
}
//************************************
// Method: GetText
// FullName: CLabelUI::GetText
// Access: public
// Returns: UiLib::CDuiString
// Qualifier: const
// Note:
//************************************
CDuiString CLabelUI::GetText() const
{
try
{
if(!m_EnableEffect)
return CControlUI::GetText();
return m_TextValue;
}
catch (...)
{
throw "CLabelUI::GetText";
}
}
//************************************
// Method: SetEnabledEffect
// FullName: CLabelUI::SetEnabledEffect
// Access: public
// Returns: void
// Qualifier:
// Parameter: bool _EnabledEffect
// Note:
//************************************
void CLabelUI::SetEnabledEffect( bool _EnabledEffect )
{
try
{
m_EnableEffect = _EnabledEffect;
}
catch (...)
{
throw "CLabelUI::SetEnabledEffect";
}
}
//************************************
// Method: GetEnabledEffect
// FullName: CLabelUI::GetEnabledEffect
// Access: public
// Returns: bool
// Qualifier:
// Note:
//************************************
bool CLabelUI::GetEnabledEffect()
{
try
{
return m_EnableEffect;
}
catch (...)
{
throw "CLabelUI::GetEnabledEffect";
}
}
//************************************
// Method: SetTextColor1
// FullName: CLabelUI::SetTextColor1
// Access: public
// Returns: void
// Qualifier:
// Parameter: DWORD _TextColor1
// Note:
//************************************
void CLabelUI::SetTextColor1( DWORD _TextColor1 )
{
try
{
m_dwTextColor1 = _TextColor1;
}
catch (...)
{
throw "CLabelUI::SetTextColor1";
}
}
//************************************
// Method: GetTextColor1
// FullName: CLabelUI::GetTextColor1
// Access: public
// Returns: DWORD
// Qualifier:
// Note:
//************************************
DWORD CLabelUI::GetTextColor1()
{
try
{
return m_dwTextColor1;
}
catch (...)
{
throw "CLabelUI::GetTextColor1";
}
}
//************************************
// Method: SetTextShadowColorA
// FullName: CLabelUI::SetTextShadowColorA
// Access: public
// Returns: void
// Qualifier:
// Parameter: DWORD _TextShadowColorA
// Note:
//************************************
void CLabelUI::SetTextShadowColorA( DWORD _TextShadowColorA )
{
try
{
m_dwTextShadowColorA = _TextShadowColorA;
}
catch (...)
{
throw "CLabelUI::SetTextShadowColorA";
}
}
//************************************
// Method: GetTextShadowColorA
// FullName: CLabelUI::GetTextShadowColorA
// Access: public
// Returns: DWORD
// Qualifier:
// Note:
//************************************
DWORD CLabelUI::GetTextShadowColorA()
{
try
{
return m_dwTextShadowColorA;
}
catch (...)
{
throw "CLabelUI::GetTextShadowColorA";
}
}
//************************************
// Method: SetTextShadowColorB
// FullName: CLabelUI::SetTextShadowColorB
// Access: public
// Returns: void
// Qualifier:
// Parameter: DWORD _TextShadowColorB
// Note:
//************************************
void CLabelUI::SetTextShadowColorB( DWORD _TextShadowColorB )
{
try
{
m_dwTextShadowColorB = _TextShadowColorB;
}
catch (...)
{
throw "CLabelUI::SetTextShadowColorB";
}
}
//************************************
// Method: GetTextShadowColorB
// FullName: CLabelUI::GetTextShadowColorB
// Access: public
// Returns: DWORD
// Qualifier:
// Note:
//************************************
DWORD CLabelUI::GetTextShadowColorB()
{
try
{
return m_dwTextShadowColorB;
}
catch (...)
{
throw "CLabelUI::GetTextShadowColorB";
}
}
//************************************
// Method: SetTransText
// FullName: CLabelUI::SetTransText
// Access: public
// Returns: void
// Qualifier:
// Parameter: int _TransText
// Note:
//************************************
void CLabelUI::SetTransText( int _TransText )
{
try
{
m_TransText = _TransText;
}
catch (...)
{
throw "CLabelUI::SetTransText";
}
}
//************************************
// Method: GetTransText
// FullName: CLabelUI::GetTransText
// Access: public
// Returns: int
// Qualifier:
// Note:
//************************************
int CLabelUI::GetTransText()
{
try
{
return m_TransText;
}
catch (...)
{
throw "CLabelUI::GetTransText";
}
}
//************************************
// Method: SetTransShadow1
// FullName: CLabelUI::SetTransShadow1
// Access: public
// Returns: void
// Qualifier:
// Parameter: int _TransShadow
// Note:
//************************************
void CLabelUI::SetTransShadow1( int _TransShadow )
{
try
{
m_TransShadow1 = _TransShadow;
}
catch (...)
{
throw "CLabelUI::SetTransShadow1";
}
}
//************************************
// Method: GetTransShadow1
// FullName: CLabelUI::GetTransShadow1
// Access: public
// Returns: int
// Qualifier:
// Note:
//************************************
int CLabelUI::GetTransShadow1()
{
try
{
return m_TransShadow1;
}
catch (...)
{
throw "CLabelUI::GetTransShadow1";
}
}
//************************************
// Method: SetTransText1
// FullName: CLabelUI::SetTransText1
// Access: public
// Returns: void
// Qualifier:
// Parameter: int _TransText
// Note:
//************************************
void CLabelUI::SetTransText1( int _TransText )
{
try
{
m_TransText1 = _TransText;
}
catch (...)
{
throw "CLabelUI::SetTransText1";
}
}
//************************************
// Method: GetTransText1
// FullName: CLabelUI::GetTransText1
// Access: public
// Returns: int
// Qualifier:
// Note:
//************************************
int CLabelUI::GetTransText1()
{
try
{
return m_TransText1;
}
catch (...)
{
throw "CLabelUI::GetTransText1";
}
}
//************************************
// Method: SetGradientAngle
// FullName: CLabelUI::SetGradientAngle
// Access: public
// Returns: void
// Qualifier:
// Parameter: float _SetGradientAngle
// Note:
//************************************
void CLabelUI::SetGradientAngle( int _SetGradientAngle )
{
try
{
m_GradientAngle = _SetGradientAngle;
}
catch (...)
{
throw "CLabelUI::SetGradientAngle";
}
}
//************************************
// Method: GetGradientAngle
// FullName: CLabelUI::GetGradientAngle
// Access: public
// Returns: int
// Qualifier:
// Note:
//************************************
int CLabelUI::GetGradientAngle()
{
try
{
return m_GradientAngle;
}
catch (...)
{
throw "CLabelUI::GetGradientAngle";
}
}
//************************************
// Method: SetEnabledStroke
// FullName: CLabelUI::SetEnabledStroke
// Access: public
// Returns: void
// Qualifier:
// Parameter: bool _EnabledStroke
// Note:
//************************************
void CLabelUI::SetEnabledStroke( bool _EnabledStroke )
{
try
{
m_EnabledStroke = _EnabledStroke;
}
catch (...)
{
throw "CLabelUI::SetEnabledStroke";
}
}
//************************************
// Method: GetEnabledStroke
// FullName: CLabelUI::GetEnabledStroke
// Access: public
// Returns: bool
// Qualifier:
// Note:
//************************************
bool CLabelUI::GetEnabledStroke()
{
try
{
return m_EnabledStroke;
}
catch (...)
{
throw "CLabelUI::GetEnabledStroke";
}
}
//************************************
// Method: SetTransStroke
// FullName: CLabelUI::SetTransStroke
// Access: public
// Returns: void
// Qualifier:
// Parameter: int _TransStroke
// Note:
//************************************
void CLabelUI::SetTransStroke( int _TransStroke )
{
try
{
m_TransStroke = _TransStroke;
}
catch (...)
{
throw "CLabelUI::SetTransStroke";
}
}
//************************************
// Method: GetTransStroke
// FullName: CLabelUI::GetTransStroke
// Access: public
// Returns: int
// Qualifier:
// Note:
//************************************
int CLabelUI::GetTransStroke()
{
try
{
return m_TransStroke;
}
catch (...)
{
throw "CLabelUI::GetTransStroke";
}
}
//************************************
// Method: SetStrokeColor
// FullName: CLabelUI::SetStrokeColor
// Access: public
// Returns: void
// Qualifier:
// Parameter: DWORD _StrokeColor
// Note:
//************************************
void CLabelUI::SetStrokeColor( DWORD _StrokeColor )
{
try
{
m_dwStrokeColor = _StrokeColor;
}
catch (...)
{
throw "CLabelUI::SetStrokeColor";
}
}
//************************************
// Method: GetStrokeColor
// FullName: CLabelUI::GetStrokeColor
// Access: public
// Returns: DWORD
// Qualifier:
// Note:
//************************************
DWORD CLabelUI::GetStrokeColor()
{
try
{
return m_dwStrokeColor;
}
catch (...)
{
throw "CLabelUI::GetStrokeColor";
}
}
//************************************
// Method: SetEnabledShadow
// FullName: CLabelUI::SetEnabledShadow
// Access: public
// Returns: void
// Qualifier:
// Parameter: bool _EnabledShadowe
// Note:
//************************************
void CLabelUI::SetEnabledShadow( bool _EnabledShadowe )
{
try
{
m_EnabledShadow = _EnabledShadowe;
}
catch (...)
{
throw "CLabelUI::SetEnabledShadow";
}
}
//************************************
// Method: GetEnabledShadow
// FullName: CLabelUI::GetEnabledShadow
// Access: public
// Returns: bool
// Qualifier:
// Note:
//************************************
bool CLabelUI::GetEnabledShadow()
{
try
{
return m_EnabledShadow;
}
catch (...)
{
throw "CLabelUI::GetEnabledShadow";
}
}
//************************************
// Method: SetGradientLength
// FullName: CLabelUI::SetGradientLength
// Access: public
// Returns: void
// Qualifier:
// Parameter: int _GradientLength
// Note:
//************************************
void CLabelUI::SetGradientLength( int _GradientLength )
{
try
{
m_GradientLength = _GradientLength;
}
catch (...)
{
throw "CLabelUI::SetGradientLength";
}
}
//************************************
// Method: GetGradientLength
// FullName: CLabelUI::GetGradientLength
// Access: public
// Returns: int
// Qualifier:
// Note:
//************************************
int CLabelUI::GetGradientLength()
{
try
{
return m_GradientLength;
}
catch (...)
{
throw "CLabelUI::GetGradientLength";
}
}
} | [
"389465209@qq.com"
] | 389465209@qq.com |
92ae3090f8acf25ae458d82a23df48ce9b6f417d | 798471adab41ea2c6134d5dfd95246790059ee0f | /table/format.cc | 279aa954e5ab8496e5027e5026623d730de68270 | [
"BSD-3-Clause"
] | permissive | m561247/sifrdb | cb70288cc9dcc60398db28a00d5e95e7721e50bc | f744114aefd298d1aa0a23587a0a6f31b45368cf | refs/heads/master | 2023-09-01T09:30:40.763537 | 2018-10-31T00:48:55 | 2018-10-31T00:48:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,673 | cc | // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include "table/format.h"
#include "leveldb/env.h"
#include "port/port.h"
#include "table/block.h"
#include "util/coding.h"
#include "util/crc32c.h"
#include "stdio.h"
namespace leveldb {
void BlockHandle::EncodeTo(std::string* dst) const {
// Sanity check that all fields have been set
assert(offset_ != ~static_cast<uint64_t>(0));
assert(size_ != ~static_cast<uint64_t>(0));
PutVarint64(dst, offset_);
PutVarint64(dst, size_);
}
Status BlockHandle::DecodeFrom(Slice* input) {
if (GetVarint64(input, &offset_) &&
GetVarint64(input, &size_)) {
return Status::OK();
} else {
return Status::Corruption("bad block handle");
}
}
void Footer::EncodeTo(std::string* dst) const {
#ifndef NDEBUG
const size_t original_size = dst->size();
#endif
metaindex_handle_.EncodeTo(dst);
index_handle_.EncodeTo(dst);
dst->resize(2 * BlockHandle::kMaxEncodedLength); // Padding
PutFixed32(dst, static_cast<uint32_t>(kTableMagicNumber & 0xffffffffu));
PutFixed32(dst, static_cast<uint32_t>(kTableMagicNumber >> 32));
assert(dst->size() == original_size + kEncodedLength);
}
Status Footer::DecodeFrom(Slice* input) {
const char* magic_ptr = input->data() + kEncodedLength - 8;
const uint32_t magic_lo = DecodeFixed32(magic_ptr);
const uint32_t magic_hi = DecodeFixed32(magic_ptr + 4);
const uint64_t magic = ((static_cast<uint64_t>(magic_hi) << 32) |
(static_cast<uint64_t>(magic_lo)));
if (magic != kTableMagicNumber) {
return Status::Corruption("not an sstable (bad magic number)");
}
Status result = metaindex_handle_.DecodeFrom(input);
if (result.ok()) {
result = index_handle_.DecodeFrom(input);
}
if (result.ok()) {
// We skip over any leftover data (just padding for now) in "input"
const char* end = magic_ptr + 8;
*input = Slice(end, input->data() + input->size() - end);
}
return result;
}
Status ReadBlock(RandomAccessFile* file,
const ReadOptions& options,
const BlockHandle& handle,
BlockContents* result) {
result->data = Slice();
result->cachable = false;
result->heap_allocated = false;
// Read the block contents as well as the type/crc footer.
// See table_builder.cc for the code that built this structure.
size_t n = static_cast<size_t>(handle.size());
char* buf = new char[n + kBlockTrailerSize];
Slice contents;
Status s = file->Read(handle.offset(), n + kBlockTrailerSize, &contents, buf);
if (!s.ok()) {
delete[] buf;
return s;
}
if (contents.size() != n + kBlockTrailerSize) {
delete[] buf;
return Status::Corruption("truncated block read");
}
// Check the crc of the type and the block contents
const char* data = contents.data(); // Pointer to where Read put the data
if (options.verify_checksums) {
const uint32_t crc = crc32c::Unmask(DecodeFixed32(data + n + 1));
const uint32_t actual = crc32c::Value(data, n + 1);
if (actual != crc) {
delete[] buf;
s = Status::Corruption("block checksum mismatch");
return s;
}
}
switch (data[n]) {
case kNoCompression:
if (data != buf) {
// File implementation gave us pointer to some other data.
// Use it directly under the assumption that it will be live
// while the file is open.
//printf("format.cc, readblock,data!=buf ***********************\n");
delete[] buf;
result->data = Slice(data, n);
result->heap_allocated = false;
result->cachable = false; // Do not double-cache
} else {
result->data = Slice(buf, n);
result->heap_allocated = true;
result->cachable = true;
}
// Ok
break;
case kSnappyCompression: {
size_t ulength = 0;
if (!port::Snappy_GetUncompressedLength(data, n, &ulength)) {
delete[] buf;
return Status::Corruption("corrupted compressed block contents");
}
char* ubuf = new char[ulength];
if (!port::Snappy_Uncompress(data, n, ubuf)) {
delete[] buf;
delete[] ubuf;
return Status::Corruption("corrupted compressed block contents");
}
delete[] buf;
result->data = Slice(ubuf, ulength);
result->heap_allocated = true;
result->cachable = true;
break;
}
default:
delete[] buf;
return Status::Corruption("bad block type");
}
return Status::OK();
}
} // namespace leveldb
| [
"271678682@qq.com"
] | 271678682@qq.com |
f5a50fb889d052bd384402d5a0c74dec7a021dd2 | 329769e87a12229aa24a6bf0e0391f2f86b44e97 | /CUser.cpp | 952ffe37e0d445c389059662f2e223fbff728839 | [] | no_license | SNHU-CETA-CSE/crapsnqt-JasonMcKearney | 20d5a200ec873ad07e6dba8dc0617003753c1a48 | b6e53a9d505639126b8f580c6a4f351af9beff50 | refs/heads/master | 2021-01-26T05:05:05.234747 | 2020-04-20T22:27:26 | 2020-04-20T22:27:26 | 243,319,456 | 0 | 0 | null | 2020-04-10T17:59:53 | 2020-02-26T17:09:47 | C++ | UTF-8 | C++ | false | false | 1,990 | cpp | #include "CUser.h"
#include<iostream>
CUser::CUser(float fBank) {
m_bank = fBank;
}
void CUser::setBet(float betSpinBox) {
m_bet = betSpinBox;
}
float CUser::getBet() {
return m_bet;
}
void CUser::addWin() {
m_wins += 1;
}
int CUser::getWins() {
return m_wins;
}
void CUser::addLoss() {
m_losses += 1;
}
int CUser::getLosses() {
return m_losses;
}
void CUser::changeBank(bool secondRoll, int iSecondRollTotal, bool bWinGame) {
if (bWinGame == false) {
m_bank -= m_bet;
}
else
{
// Base below upon payout:
if (secondRoll == false)
{
// 1:1 payoff:
m_bank += m_bet * 1;
}
else {
switch (iSecondRollTotal) {
case 4:
m_bank += m_bet * 2;
break;
case 5:
m_bank += m_bet * 1.5;
break;
case 6:
m_bank += m_bet * 1.2;
break;
case 8:
m_bank += m_bet * 1.2;
break;
case 9:
m_bank += m_bet * 1.5;
break;
case 10:
m_bank += m_bet * 2;
break;
}
}
}
}
float CUser::getBank() {
return m_bank;
}
void CUser::setFirstRollAmount(int firstRollTotal) {
m_firstRollAmount = firstRollTotal;
}
bool CUser::winLoseGame(bool firstRoll, int iSecondRollTotal, bool& winGame) {
// Done with roll, until next game:
if (firstRoll == true && (m_firstRollAmount == 7 || m_firstRollAmount == 11)) {
winGame = true;
return true;
}
// done with roll, until next game:
else if (firstRoll == true && m_firstRollAmount == 2 || m_firstRollAmount == 3 || m_firstRollAmount == 12) {
winGame = false;
return true;
}
else if (firstRoll == true && m_firstRollAmount == 4 || m_firstRollAmount == 5 || m_firstRollAmount == 6 || m_firstRollAmount == 8 || m_firstRollAmount == 9 || m_firstRollAmount == 10) {
winGame = false;
return false;
}
// roll a second time
if (m_firstRollAmount == iSecondRollTotal) {
winGame = true;
return true;
}
else {
winGame = false;
return false;
}
} | [
"noreply@github.com"
] | noreply@github.com |
cbe1c59a22d4a52b15b395a3ef2d0012fba4c74d | f6fedf4c1c59372f9ba522cec853a80c2c05ea18 | /selection_sort.cpp | 3be9c051377eeb5eeb799d6c100682caa690fe4a | [] | no_license | manisha-jaiswal/Data-Structure-Using-Cpp | 601458f4e1923a28979d1118a35229b0139ee37f | 5747eaff90aade906c46a77d3e50514897878e20 | refs/heads/master | 2020-07-08T10:54:04.361971 | 2019-08-25T08:45:31 | 2019-08-25T08:45:31 | 203,651,059 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 688 | cpp | /* C++ Program - Selection Sort */
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
system("cls");
int size, arr[50], i, j, temp;
cout<<"Enter Array Size : ";
cin>>size;
cout<<"Enter Array Elements : ";
for(i=0; i<size; i++)
{
cin>>arr[i];
}
cout<<"Sorting array using selection sort...\n";
for(i=0; i<size; i++)
{
for(j=i+1; j<size; j++)
{
if(arr[i]>arr[j])
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
for(j=i;j<size;j++)
cout<<arr[j]<<" ";
cout<<endl;
}
cout<<"Now the Array after sorting is :\n";
for(i=0; i<size; i++)
{
cout<<arr[i]<<" ";
}
getch();
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
9bcda0eaf33826405ecb10c598e82c12f843f435 | f8c592e5666fbf2adb6097a5f1117f6228b879e8 | /test/cctest/checks.h | 4b0a70320714027e035c30874d9c3f2ef340a318 | [
"BSD-3-Clause"
] | permissive | google/double-conversion | a3c39185b58933b6ec6e4b2ed6ef927e340298bf | 032fa6a7d2c319b20d3928f5d762648fa4029acf | refs/heads/master | 2023-08-29T14:48:51.262196 | 2023-08-28T09:51:02 | 2023-08-28T09:51:02 | 25,397,114 | 1,086 | 348 | BSD-3-Clause | 2023-09-13T09:23:11 | 2014-10-18T12:48:15 | C++ | UTF-8 | C++ | false | false | 13,134 | h | // Copyright 2006-2008 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef V8_CHECKS_H_
#define V8_CHECKS_H_
#include <string.h>
#include "flags.h"
extern "C" void V8_Fatal(const char* file, int line, const char* format, ...);
void API_Fatal(const char* location, const char* format, ...);
// The FATAL, DOUBLE_CONVERSION_UNREACHABLE and DOUBLE_CONVERSION_UNIMPLEMENTED macros are useful during
// development, but they should not be relied on in the final product.
#ifdef DEBUG
#define FATAL(msg) \
V8_Fatal(__FILE__, __LINE__, "%s", (msg))
#define DOUBLE_CONVERSION_UNIMPLEMENTED() \
V8_Fatal(__FILE__, __LINE__, "unimplemented code")
#define DOUBLE_CONVERSION_UNREACHABLE() \
V8_Fatal(__FILE__, __LINE__, "unreachable code")
#else
#define FATAL(msg) \
V8_Fatal("", 0, "%s", (msg))
#define DOUBLE_CONVERSION_UNIMPLEMENTED() \
V8_Fatal("", 0, "unimplemented code")
#define DOUBLE_CONVERSION_UNREACHABLE() ((void) 0)
#endif
// Used by the CHECK macro -- should not be called directly.
static inline void CheckHelper(const char* file,
int line,
const char* source,
bool condition) {
if (!condition)
V8_Fatal(file, line, "CHECK(%s) failed", source);
}
// The CHECK macro checks that the given condition is true; if not, it
// prints a message to stderr and aborts.
#define CHECK(condition) CheckHelper(__FILE__, __LINE__, #condition, condition)
// Helper function used by the CHECK_EQ function when given int
// arguments. Should not be called directly.
static inline void CheckEqualsHelper(const char* file, int line,
const char* expected_source, int expected,
const char* value_source, int value) {
if (expected != value) {
V8_Fatal(file, line,
"CHECK_EQ(%s, %s) failed\n# Expected: %i\n# Found: %i",
expected_source, value_source, expected, value);
}
}
// Helper function used by the CHECK_EQ function when given int64_t
// arguments. Should not be called directly.
static inline void CheckEqualsHelper(const char* file, int line,
const char* expected_source,
int64_t expected,
const char* value_source,
int64_t value) {
if (expected != value) {
// Print int64_t values in hex, as two int32s,
// to avoid platform-dependencies.
V8_Fatal(file, line,
"CHECK_EQ(%s, %s) failed\n#"
" Expected: 0x%08x%08x\n# Found: 0x%08x%08x",
expected_source, value_source,
static_cast<uint32_t>(expected >> 32),
static_cast<uint32_t>(expected),
static_cast<uint32_t>(value >> 32),
static_cast<uint32_t>(value));
}
}
// Helper function used by the CHECK_NE function when given int
// arguments. Should not be called directly.
static inline void CheckNonEqualsHelper(const char* file,
int line,
const char* unexpected_source,
int unexpected,
const char* value_source,
int value) {
if (unexpected == value) {
V8_Fatal(file, line, "CHECK_NE(%s, %s) failed\n# Value: %i",
unexpected_source, value_source, value);
}
}
// Helper function used by the CHECK function when given string
// arguments. Should not be called directly.
static inline void CheckEqualsHelper(const char* file,
int line,
const char* expected_source,
const char* expected,
const char* value_source,
const char* value) {
if ((expected == NULL && value != NULL) ||
(expected != NULL && value == NULL) ||
(expected != NULL && value != NULL && strcmp(expected, value) != 0)) {
V8_Fatal(file, line,
"CHECK_EQ(%s, %s) failed\n# Expected: %s\n# Found: %s",
expected_source, value_source, expected, value);
}
}
static inline void CheckNonEqualsHelper(const char* file,
int line,
const char* expected_source,
const char* expected,
const char* value_source,
const char* value) {
if (expected == value ||
(expected != NULL && value != NULL && strcmp(expected, value) == 0)) {
V8_Fatal(file, line, "CHECK_NE(%s, %s) failed\n# Value: %s",
expected_source, value_source, value);
}
}
// Helper function used by the CHECK function when given pointer
// arguments. Should not be called directly.
static inline void CheckEqualsHelper(const char* file,
int line,
const char* expected_source,
const void* expected,
const char* value_source,
const void* value) {
if (expected != value) {
V8_Fatal(file, line,
"CHECK_EQ(%s, %s) failed\n# Expected: %p\n# Found: %p",
expected_source, value_source,
expected, value);
}
}
static inline void CheckNonEqualsHelper(const char* file,
int line,
const char* expected_source,
const void* expected,
const char* value_source,
const void* value) {
if (expected == value) {
V8_Fatal(file, line, "CHECK_NE(%s, %s) failed\n# Value: %p",
expected_source, value_source, value);
}
}
// Helper function used by the CHECK function when given floating
// point arguments. Should not be called directly.
static inline void CheckEqualsHelper(const char* file,
int line,
const char* expected_source,
double expected,
const char* value_source,
double value) {
// Force values to 64 bit memory to truncate 80 bit precision on IA32.
volatile double* exp = new double[1];
*exp = expected;
volatile double* val = new double[1];
*val = value;
if (*exp != *val) {
V8_Fatal(file, line,
"CHECK_EQ(%s, %s) failed\n# Expected: %f\n# Found: %f",
expected_source, value_source, *exp, *val);
}
delete[] exp;
delete[] val;
}
static inline void CheckNonEqualsHelper(const char* file,
int line,
const char* expected_source,
double expected,
const char* value_source,
double value) {
// Force values to 64 bit memory to truncate 80 bit precision on IA32.
volatile double* exp = new double[1];
*exp = expected;
volatile double* val = new double[1];
*val = value;
if (*exp == *val) {
V8_Fatal(file, line,
"CHECK_NE(%s, %s) failed\n# Value: %f",
expected_source, value_source, *val);
}
delete[] exp;
delete[] val;
}
namespace v8 {
class Value;
template <class T> class Handle;
}
void CheckNonEqualsHelper(const char* file,
int line,
const char* unexpected_source,
v8::Handle<v8::Value> unexpected,
const char* value_source,
v8::Handle<v8::Value> value);
void CheckEqualsHelper(const char* file,
int line,
const char* expected_source,
v8::Handle<v8::Value> expected,
const char* value_source,
v8::Handle<v8::Value> value);
#define CHECK_EQ(expected, value) CheckEqualsHelper(__FILE__, __LINE__, \
#expected, expected, #value, value)
#define CHECK_NE(unexpected, value) CheckNonEqualsHelper(__FILE__, __LINE__, \
#unexpected, unexpected, #value, value)
#define CHECK_GT(a, b) CHECK((a) > (b))
#define CHECK_GE(a, b) CHECK((a) >= (b))
// This is inspired by the static assertion facility in boost. This
// is pretty magical. If it causes you trouble on a platform you may
// find a fix in the boost code.
template <bool> class StaticAssertion;
template <> class StaticAssertion<true> { };
// This macro joins two tokens. If one of the tokens is a macro the
// helper call causes it to be resolved before joining.
#define SEMI_STATIC_JOIN(a, b) SEMI_STATIC_JOIN_HELPER(a, b)
#define SEMI_STATIC_JOIN_HELPER(a, b) a##b
// Causes an error during compilation of the condition is not
// statically known to be true. It is formulated as a typedef so that
// it can be used wherever a typedef can be used. Beware that this
// actually causes each use to introduce a new defined type with a
// name depending on the source line.
template <int> class StaticAssertionHelper { };
#define STATIC_CHECK(test) \
typedef \
StaticAssertionHelper<sizeof(StaticAssertion<static_cast<bool>(test)>)> \
SEMI_STATIC_JOIN(__StaticAssertTypedef__, __LINE__)
// The DOUBLE_CONVERSION_ASSERT macro is equivalent to CHECK except that it only
// generates code in debug builds.
#ifdef DEBUG
#define DOUBLE_CONVERSION_ASSERT_RESULT(expr) CHECK(expr)
#define DOUBLE_CONVERSION_ASSERT(condition) CHECK(condition)
#define DOUBLE_CONVERSION_ASSERT_EQ(v1, v2) CHECK_EQ(v1, v2)
#define DOUBLE_CONVERSION_ASSERT_NE(v1, v2) CHECK_NE(v1, v2)
#define DOUBLE_CONVERSION_ASSERT_GE(v1, v2) CHECK_GE(v1, v2)
#define SLOW_DOUBLE_CONVERSION_ASSERT(condition) if (FLAG_enable_slow_asserts) CHECK(condition)
#else
#define DOUBLE_CONVERSION_ASSERT_RESULT(expr) (expr)
#define DOUBLE_CONVERSION_ASSERT(condition) ((void) 0)
#define DOUBLE_CONVERSION_ASSERT_EQ(v1, v2) ((void) 0)
#define DOUBLE_CONVERSION_ASSERT_NE(v1, v2) ((void) 0)
#define DOUBLE_CONVERSION_ASSERT_GE(v1, v2) ((void) 0)
#define SLOW_DOUBLE_CONVERSION_ASSERT(condition) ((void) 0)
#endif
// Static asserts has no impact on runtime performance, so they can be
// safely enabled in release mode. Moreover, the ((void) 0) expression
// obeys different syntax rules than typedef's, e.g. it can't appear
// inside class declaration, this leads to inconsistency between debug
// and release compilation modes behaviour.
#define STATIC_DOUBLE_CONVERSION_ASSERT(test) STATIC_CHECK(test)
#define DOUBLE_CONVERSION_ASSERT_TAG_ALIGNED(address) \
DOUBLE_CONVERSION_ASSERT((reinterpret_cast<intptr_t>(address) & kHeapObjectTagMask) == 0)
#define DOUBLE_CONVERSION_ASSERT_SIZE_TAG_ALIGNED(size) DOUBLE_CONVERSION_ASSERT((size & kHeapObjectTagMask) == 0)
#define DOUBLE_CONVERSION_ASSERT_NOT_NULL(p) DOUBLE_CONVERSION_ASSERT_NE(NULL, p)
#endif // V8_CHECKS_H_
| [
"florian@loitsch.com"
] | florian@loitsch.com |
93f0841ae3a4931739b273554e0e3fd8827c8b50 | d0c44dd3da2ef8c0ff835982a437946cbf4d2940 | /cmake-build-debug/programs_tiling/function14771/function14771_schedule_42/function14771_schedule_42_wrapper.cpp | 79f45f453bdcfb2afddbe2c9c4191e3eb0314917 | [] | no_license | IsraMekki/tiramisu_code_generator | 8b3f1d63cff62ba9f5242c019058d5a3119184a3 | 5a259d8e244af452e5301126683fa4320c2047a3 | refs/heads/master | 2020-04-29T17:27:57.987172 | 2019-04-23T16:50:32 | 2019-04-23T16:50:32 | 176,297,755 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,208 | cpp | #include "Halide.h"
#include "function14771_schedule_42_wrapper.h"
#include "tiramisu/utils.h"
#include <cstdlib>
#include <iostream>
#include <time.h>
#include <fstream>
#include <chrono>
#define MAX_RAND 200
int main(int, char **){
Halide::Buffer<int32_t> buf00(1024, 256);
Halide::Buffer<int32_t> buf01(1024, 128);
Halide::Buffer<int32_t> buf02(1024);
Halide::Buffer<int32_t> buf03(1024, 128);
Halide::Buffer<int32_t> buf04(1024);
Halide::Buffer<int32_t> buf0(1024, 256, 128);
init_buffer(buf0, (int32_t)0);
auto t1 = std::chrono::high_resolution_clock::now();
function14771_schedule_42(buf00.raw_buffer(), buf01.raw_buffer(), buf02.raw_buffer(), buf03.raw_buffer(), buf04.raw_buffer(), buf0.raw_buffer());
auto t2 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> diff = t2 - t1;
std::ofstream exec_times_file;
exec_times_file.open("../data/programs/function14771/function14771_schedule_42/exec_times.txt", std::ios_base::app);
if (exec_times_file.is_open()){
exec_times_file << diff.count() * 1000000 << "us" <<std::endl;
exec_times_file.close();
}
return 0;
} | [
"ei_mekki@esi.dz"
] | ei_mekki@esi.dz |
fb9324685a73759156e35949ca4dfaaf9239d272 | 87a03e2f54c48540c6229a5f3cc77b8ab948a849 | /genesis/src/read_phylip.cpp | da1a9ab7245b9c053689c3752df4e30afa19012b | [] | no_license | lczech/genesis-gappa-paper | 14a77176cd47d28e53d1ab4f6b97026a3a85d1fc | eb60c62baf0ed485f339f45c3803dfcf8c06d984 | refs/heads/master | 2020-05-09T22:02:28.714017 | 2020-02-06T12:55:43 | 2020-02-06T12:55:43 | 181,457,252 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,027 | cpp | #include "genesis/genesis.hpp"
#include <chrono>
using namespace genesis;
using namespace genesis::sequence;
using namespace genesis::utils;
int main( int argc, char** argv )
{
// Get input.
if( argc != 2 ) {
throw std::runtime_error( "Need to provide a phylip file." );
}
auto const infile = std::string( argv[1] );
// Start the clock.
std::cout << "Start reading" << utils::current_time() << "\n";
auto const start = std::chrono::steady_clock::now();
// Run, Forrest, Run!
auto const seqs = PhylipReader().read( from_file( infile ));
// Stop the clock
auto const duration = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - start
);
std::cout << "Finished reading " << utils::current_time() << "\n";
double const elapsed_secs = double(duration.count()) / 1000.0;
std::cout << "Internal time: " << elapsed_secs << "\n";
// Check output
std::cout << "Size: " << seqs.size() << "\n";
return 0;
}
| [
"luc@s-cze.ch"
] | luc@s-cze.ch |
037ca89df5cb8f241d37fe08365eab763488a327 | f626465bf4c2fc95cdb6160040fe3a8a20776255 | /src/frame/ProgressFrame.cpp | 949c162a76156833257062c4bedcf0eb480d14b1 | [
"MIT"
] | permissive | FlySkyPie/Wire-Bender-HMI | f59397064e17b09874772dcc50b022f737345a57 | bd4ee7ff59457cf4b26ff12e9eb17114e051df94 | refs/heads/master | 2020-07-23T22:10:11.791810 | 2019-09-11T04:10:06 | 2019-09-11T04:10:06 | 207,720,230 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,951 | cpp | #include "frame/ProgressFrame.h"
#include <wx/sizer.h>
/*
* Initialize the frame, create control components.
*/
ProgressFrame::ProgressFrame() :
wxFrame(NULL, wxID_ANY, "Hello World", wxDefaultPosition, wxSize(400, 400),
wxSYSTEM_MENU | wxCAPTION | wxCLOSE_BOX) {
this->Bind(wxEVT_CLOSE_WINDOW, &ProgressFrame::OnClose, this);
//control components
this->gauge = new wxGauge(this, wxID_ANY, 100, wxPoint(40, 40), wxSize(320, 20));
this->button = new wxButton(this, wxID_ANY, wxT("Stop"), wxPoint(150, 120), wxDefaultSize, 0);
this->textCtrl = new wxTextCtrl(this, wxID_ANY, "",
wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE | wxTE_READONLY | wxHSCROLL);
this->Connect(this->button->GetId(), wxEVT_COMMAND_BUTTON_CLICKED,
wxCommandEventHandler(ProgressFrame::buttonClick));
// typesetting
wxBoxSizer* mainSizer = new wxBoxSizer(wxVERTICAL);
wxBoxSizer* sizer = new wxBoxSizer(wxHORIZONTAL);
sizer->Add(gauge, 0, wxALIGN_CENTER | wxALL, 3);
sizer->Add(button, 0, wxALIGN_CENTER | wxALL, 3);
mainSizer->Add(sizer, 1, wxALL);
mainSizer->Add(textCtrl, 7, wxEXPAND | wxALL, 3);
this->SetSizer(mainSizer);
}
/*
* Set the interface which handle switch frame.
*/
void ProgressFrame::setFrameSwitchHandler(IFrameSwitchHandler* handler) {
this->handler = handler;
}
/*
* Create a Factory which can created ProduceManager.
* Must called this after setFrameSwitchHandler.
*/
void ProgressFrame::createProductFactory(ISerialPortCommunicator * communicator) {
this->factory = new ProduceManagerFactory();
this->factory->setProgressPanel(this);
this->factory->setCommunicator(communicator);
this->factory->setFrameSwitchHandler(this->handler);
}
void ProgressFrame::setExit(IExit * exit) {
this->exit = exit;
}
/*
* Start produce.
*/
void ProgressFrame::startProduce(std::string name, std::string code) {
this->productName = name;
this->update(0);
this->textCtrl->ChangeValue("");
this->produceManager = this->factory->getProduceManager(code);
this->produceManager->startProduce();
}
/*
* Update progress.
*/
void ProgressFrame::update(float progress) {
int progressNumber = ceil(100 * progress);
this->gauge->SetValue(progressNumber);
std::string title = "[" + this->productName + "] Producing...(" + std::to_string(progressNumber) + "%)";
this->SetTitle(title);
}
/*
* Report what command has sending to machine.
*/
void ProgressFrame::reportCommand(std::string command) {
command = "Working on: " + command + " ...";
this->textCtrl->AppendText(command);
}
/*
* The command finished signal has been get,
* report on GUI.
*/
void ProgressFrame::reportCheck() {
this->textCtrl->AppendText("Ok\n");
}
/*
* When the stop button pressed.
*/
void ProgressFrame::buttonClick(wxCommandEvent & event) {
this->produceManager->stopProduce();
this->handler->stopProduce();
}
void ProgressFrame::OnClose(wxCloseEvent &event) {
this->exit->exit();
} | [
"c445dj544@gmail.com"
] | c445dj544@gmail.com |
3fe0af6a1b3cbc2968458ab3b85c3ecaeb48c270 | c511fcc8ac5026b9cd95d35373d8dcd0adb6e0b8 | /C++/map_test.cpp | de49829e4d3a59f66c384fe693771aa59d5bab87 | [] | no_license | HarveyHub/NowCoder | e20f3c5b199d88d14091455f29ad9e2f1c44ca33 | fbfca62ca0518b01a52cbb2638ed48dcda68496c | refs/heads/master | 2021-01-23T13:07:51.236042 | 2019-07-12T08:48:45 | 2019-07-12T08:48:45 | 93,059,803 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,069 | cpp | #include <iostream>
#include <vector>
#include <string>
#include <map>
#include <ctime>
#include <cstdlib>
#include <algorithm>
using namespace std;
bool cmp(map<string, vector<double>>::iterator iter1, map<string, vector<double>>::iterator iter2)
{
return iter1->second[0] > iter2->second[0];
}
map<string, vector<int>> color_map =
{
{"black",{30, 40}},
{"red", {31, 41}},
{"green", {32, 42}},
};
int main()
{
map<string, vector<double>> students;
vector<string> names = {"harvey", "ariel", "bob"};
srand((unsigned)time(NULL));
unsigned cnt = 3;
for(unsigned i = 0; i < names.size(); i++)
{
for(unsigned j = 0; j < cnt; j++)
students[names[i]].push_back(rand() % 100);
}
for(auto iter = students.begin(); iter != students.end(); iter++)
{
cout << iter->first << "\t";
for(auto item : iter->second)
cout << item << "\t";
cout << endl;
}
for(auto iter = color_map.begin(); iter != color_map.end(); iter++)
{
cout << iter->first << "\t";
for(auto item : iter->second)
cout << item << "\t";
cout << endl;
}
return 0;
} | [
"huangwein@foxmail.com"
] | huangwein@foxmail.com |
0abfbaba07865f2bf005299e2c1a035bd962c493 | c888e72116f255367b50780e669f3d0543046b72 | /src/kingfisher_vision/src/position_filter_short.cpp | 104c6efcdd627f1a68de31e30cb0db0d61af084b | [] | no_license | eitan-babcock/Kingfisher_Code | 8af599ae8bb2f79f0b58c5ffe798cb54870abcaf | 639973804801799a20cfcc40768a2201a2db9c5d | refs/heads/master | 2021-01-19T02:21:51.467417 | 2016-07-16T17:55:51 | 2016-07-16T17:55:51 | 63,548,953 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,743 | cpp | #include "ros/ros.h"
#include "std_msgs/Int16.h"
#include "std_msgs/Int32.h"
#include "std_msgs/Float32.h"
#include "std_msgs/Bool.h"
#include "geometry_msgs/Twist.h"
#include "geometry_msgs/Pose2D.h"
#include <cmath>
#include <iostream>
#include <vector>
#include "geometry_msgs/Vector3.h"
float lx_window[7];
std::vector<float> lx_vec (lx_window, lx_window+7);
std::vector<float> sorted_lx_vec;
float ly_window[7];
std::vector<float> ly_vec (ly_window, ly_window+7);
std::vector<float> sorted_ly_vec;
float lz_window[7];
std::vector<float> lz_vec (lz_window, lz_window+7);
std::vector<float> sorted_lz_vec;
float ax_window[7];
std::vector<float> ax_vec (ax_window, ax_window+7);
std::vector<float> sorted_ax_vec;
float ay_window[7];
std::vector<float> ay_vec (ay_window, ay_window+7);
std::vector<float> sorted_ay_vec;
float az_window[7];
std::vector<float> az_vec (az_window, az_window+7);
std::vector<float> sorted_az_vec;
float heading_window[7];
std::vector<float> heading_vec (heading_window, heading_window+7);
std::vector<float> sorted_heading_vec;
class PositionFilterShort
{
// Variable Declarations
std_msgs::Bool filter_flag;
geometry_msgs::Twist unfiltered_cam_pose, filtered_cam_pose, filtered_pose;
/*geometry_msgs::Pose2D unfiltered_heading, filtered_heading; */
std_msgs::Float32 filtered_heading;
std_msgs::Int32 frame_drop_counter;
std_msgs::Int16 gimbal_setting;
float lx, ly, lz, ax, ay, az; //positions and angles of current frame
int avg_size; //size of moving average window, in frames
int avg_index; //initialization of index of moving average window
int heading_index;
int window_fill_count;
float sin_cam_pitch;
float cos_cam_pitch;
float unfiltered_yaw;
float imu_roll, imu_pitch, imu_yaw, mount_angle, quadx, quady, quadz;
ros::NodeHandle n;
// Subscribers
ros::Subscriber filter_flag_sub;
ros::Subscriber unfiltered_cam_pose_sub;
ros::Subscriber unfiltered_heading_sub;
ros::Subscriber gimbal_setting_sub;
ros::Subscriber imu_sub;
// Publishers
ros::Publisher filtered_pose_pub;
ros::Publisher frame_drop_counter_pub;
ros::Publisher filtered_heading_pub;
public:
PositionFilterShort()
: n()
{
filter_flag_sub = n.subscribe("filter_flag", 10, &PositionFilterShort::FilterFlag_Callback, this);
unfiltered_cam_pose_sub = n.subscribe("kingfisher_vision_short/deckPose", 10, &PositionFilterShort::imageCB, this);
unfiltered_heading_sub = n.subscribe("kingfisher_vision_short/unfilteredHeading", 10, &PositionFilterShort::Heading_Callback, this);
imu_sub = n.subscribe("accRPY", 10, &PositionFilterShort::imuCb,this);
filtered_pose_pub = n.advertise<geometry_msgs::Twist>("filtered_pose_short", 10);
frame_drop_counter_pub = n.advertise<std_msgs::Int32>("frame_drop_counter_short", 10);
filtered_heading_pub = n.advertise<std_msgs::Float32>("filtered_heading_short", 10);
avg_size = 7;
avg_index = 0;
heading_index = 0;
frame_drop_counter.data = 0;
}
~PositionFilterShort()
{}
void imageCB(const geometry_msgs::Twist& msg)
{
CamPose_Callback(msg);
//std::cout << "unfiltered_cam_pose: "<< std::endl << unfiltered_cam_pose << std::endl;
filter_flag.data = true;
if (filter_flag.data) {
Orientation_filter();
Transform();
Heading_filter();
filtered_heading_pub.publish(filtered_heading);
filtered_pose_pub.publish(filtered_pose);
}
std::cout << "filtered_cam_pose: "<< std::endl << filtered_cam_pose << std::endl;
std::cout << "filtered_pose: "<< std::endl << filtered_pose << std::endl;
//std::cout << window_fill_count << std::endl;
std::cout << "`Distance to Deck: " << filtered_pose.linear.x << std::endl;
std::cout << "`Height: " << filtered_pose.linear.z << std::endl;
std::cout << "`Lateral Offset: " << filtered_pose.linear.y << std::endl;
//std::cout << "`Lateral Heading: " << filtered_heading.data << " degrees" << std::endl;
frame_drop_counter_pub.publish(frame_drop_counter);
}
// Orientation Filter
void Orientation_filter(void) {
lx = unfiltered_cam_pose.linear.x;
ly = unfiltered_cam_pose.linear.y;
lz = unfiltered_cam_pose.linear.z;
ax = unfiltered_cam_pose.angular.x;
ay = unfiltered_cam_pose.angular.y;
az = unfiltered_cam_pose.angular.z;
if (lz == -1.0){
frame_drop_counter.data++;
}
// Mean Filter
/* else if(
fabs(lx - filtered_cam_pose.linear.x) >= 5 ||
fabs(ly - filtered_cam_pose.linear.y) >= 5 ||
fabs(lz - filtered_cam_pose.linear.z) >= 5 ||
fabs(ax - filtered_cam_pose.angular.x) >= 250 ||
fabs(ay - filtered_cam_pose.angular.y) >= 250 ||
fabs(az - filtered_cam_pose.angular.z) >= 250
) {
frame_drop_counter.data++;
}
else {
filtered_cam_pose.linear.x = (avg_size * filtered_cam_pose.linear.x - lx_window[avg_index] + lx) / avg_size;
lx_window[avg_index] = lx;
filtered_cam_pose.linear.y = (avg_size * filtered_cam_pose.linear.y - ly_window[avg_index] + ly) / avg_size;
ly_window[avg_index] = ly;
filtered_cam_pose.linear.z = (avg_size * filtered_cam_pose.linear.z - lz_window[avg_index] + lz) / avg_size;
lz_window[avg_index] = lz;
filtered_cam_pose.angular.x = (avg_size * filtered_cam_pose.angular.x - ax_window[avg_index] + ax) / avg_size;
ax_window[avg_index] = ax;
filtered_cam_pose.angular.y = (avg_size * filtered_cam_pose.angular.y - ay_window[avg_index] + ay) / avg_size;
ay_window[avg_index] = ay;
filtered_cam_pose.angular.z = (avg_size * filtered_cam_pose.angular.z - az_window[avg_index] + az) / avg_size;
az_window[avg_index] = az;
avg_index++;
avg_index = avg_index % avg_size;
std::cout << "avg_index" << avg_index << std::endl;
frame_drop_counter.data = 0;
} */
// Median Filter
else {
lx_vec[avg_index] = lx;
sorted_lx_vec = lx_vec;
std::sort (sorted_lx_vec.begin(), sorted_lx_vec.end());
filtered_cam_pose.linear.x = sorted_lx_vec[3];
ly_vec[avg_index] = ly;
sorted_ly_vec = ly_vec;
std::sort (sorted_ly_vec.begin(), sorted_ly_vec.end());
filtered_cam_pose.linear.y = sorted_ly_vec[3];
lz_vec[avg_index] = lz;
sorted_lz_vec = lz_vec;
std::sort (sorted_lz_vec.begin(), sorted_lz_vec.end());
filtered_cam_pose.linear.z = sorted_lz_vec[3];
ax_vec[avg_index] = ax;
sorted_ax_vec = ax_vec;
std::sort (sorted_ax_vec.begin(), sorted_ax_vec.end());
filtered_cam_pose.angular.x = sorted_ax_vec[3];
ay_vec[avg_index] = ay;
sorted_ay_vec = ay_vec;
std::sort (sorted_ay_vec.begin(), sorted_ay_vec.end());
filtered_cam_pose.angular.y = sorted_ay_vec[3];
az_vec[avg_index] = az;
sorted_az_vec = az_vec;
std::sort (sorted_az_vec.begin(), sorted_az_vec.end());
filtered_cam_pose.angular.z = sorted_az_vec[3];
//std::cout << "lx: " << lx << std::endl;
//std::cout << "filtered_cam_pose x: " << filtered_cam_pose.linear.x << std::endl;
//std::cout << "sorted data: ";
/*
for (int i = 0; i < 7; ++i)
{
std::cout << " " << sorted_lx_vec[i];
}
*/
//std::cout << std::endl;
//std::cout << "Median: " << sorted_lx_vec[15] << std::endl;
avg_index++;
avg_index = avg_index % avg_size;
}
}
// Transformation from Camera Frame to Quad Frame
void Transform(void) {
//for 30 degree from vertical fixed mount tilt camera
mount_angle = 30*3.14159/180;
quadx = 0.866*filtered_cam_pose.linear.z+0.5*filtered_cam_pose.linear.x;
quady = -1*filtered_cam_pose.linear.y;
quadz = 0.5*filtered_cam_pose.linear.z-0.866*filtered_cam_pose.linear.x;
filtered_pose.linear.x = quadx;
filtered_pose.linear.y = quady;
filtered_pose.linear.z = quadz;
//std::cout << "quadx: " << quadx << std::endl;
//std::cout << "quady: " << quady << std::endl;
//std::cout << "quadz: " << quadz << std::endl;
//filtered_pose.linear.x = cos(imu_yaw)*cos(imu_pitch)*quadx + (cos(imu_yaw)*sin(imu_roll)*sin(imu_pitch) - cos(imu_roll)*sin(imu_yaw))*quady + (sin(imu_roll)*sin(imu_yaw)+cos(imu_roll)*cos(imu_yaw)*sin(imu_pitch))*quadz;
//filtered_pose.linear.y = cos(imu_pitch)*sin(imu_yaw)*quadx + (cos(imu_roll)*cos(imu_yaw)+sin(imu_roll)*sin(imu_yaw)*sin(imu_pitch))*quady + (cos(imu_roll)*sin(imu_yaw)*sin(imu_pitch)-cos(imu_yaw)*sin(imu_roll))*quadz;
//filtered_pose.linear.z = -sin(imu_pitch)*quadx + cos(imu_pitch)*sin(imu_roll)*quady + cos(imu_roll)*cos(imu_pitch)*quadz;
//filtered_pose.linear.x = cos(imu_yaw)*cos(imu_pitch)*quadx + cos(imu_pitch)*sin(imu_yaw)*quady - sin(imu_pitch)*quadz;
//filtered_pose.linear.y = (cos(imu_yaw)*sin(imu_roll)*sin(imu_pitch) - cos(imu_roll)*sin(imu_yaw))*quadx + (cos(imu_roll)*cos(imu_yaw)+sin(imu_roll)*sin(imu_yaw)*sin(imu_pitch))*quady + cos(imu_pitch)*sin(imu_roll)*quadz;
//filtered_pose.linear.z = (sin(imu_roll)*sin(imu_yaw) + cos(imu_roll)*cos(imu_yaw)*sin(imu_pitch))*quadx + (cos(imu_roll)*sin(imu_yaw)*sin(imu_pitch)-cos(imu_yaw)*sin(imu_roll))*quady + cos(imu_roll)*cos(imu_pitch)*quadz;
}
void Heading_Callback(const geometry_msgs::Twist& msg) {
unfiltered_yaw = msg.angular.x;
}
void imuCb(const geometry_msgs::Vector3& msg) {
imu_pitch = -msg.x*3.14159/180;
imu_roll = -msg.y*3.14159/180;
imu_yaw = msg.z*3.14159/180;
}
// Heading Filter
void Heading_filter(void) {
heading_vec[heading_index] = unfiltered_yaw;
sorted_heading_vec = heading_vec;
std::sort (sorted_heading_vec.begin(), sorted_heading_vec.end());
filtered_heading.data = sorted_heading_vec[3];
heading_index++;
heading_index = heading_index % avg_size;
}
// Callbacks
void FilterFlag_Callback(const std_msgs::Bool& msg)
{
filter_flag.data = msg.data;
}
void CamPose_Callback(const geometry_msgs::Twist& msg)
{
unfiltered_cam_pose.linear.x = msg.linear.x;
unfiltered_cam_pose.linear.y = msg.linear.y;
unfiltered_cam_pose.linear.z = msg.linear.z;
unfiltered_cam_pose.angular.x = msg.angular.x;
unfiltered_cam_pose.angular.y = msg.angular.y;
unfiltered_cam_pose.angular.z = msg.angular.z;
}
};
int avg_size = 7;
int avg_index = 0;
int heading_index = 0;
int window_fill_count = 0;
float lx = 0;
float ly = 0;
float lz = 0;
float ax = 0;
float ay = 0;
float az = 0; //positions and angles of current frame
float sin_cam_pitch = 0;
float cos_cam_pitch = 0;
float unfiltered_yaw = 0;
// Main Function
int main(int argc, char **argv)
{
ros::init(argc, argv, "position_filter_short");
PositionFilterShort pfs;
ros::spin(); //<-- this is where publish happens, and when it polls sub
return 0;
} | [
"ebabcock72@gmail.com"
] | ebabcock72@gmail.com |
66e8c1b4bbb68f943a58e153e4f787f6ec69ad80 | fded81a37e53d5fc31cacb9a0be86377825757b3 | /buhg_g/kasothw_m.cpp | e1acadf1be8008c2c0b104dee0d0cefe9665a228 | [] | no_license | iceblinux/iceBw_GTK | 7bf28cba9d994e95bab0f5040fea1a54a477b953 | a4f76e1fee29baa7dce79e8a4a309ae98ba504c2 | refs/heads/main | 2023-04-02T21:45:49.500587 | 2021-04-12T03:51:53 | 2021-04-12T03:51:53 | 356,744,886 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,569 | cpp | /*$Id: kasothw_m.c,v 1.20 2013/09/26 09:46:49 sasa Exp $*/
/*11.07.2015 10.03.2006 Белых А.И. kasothw_m.c
Меню для получения отчёта
*/
#include "buhg_g.h"
#include "kasothw.h"
enum
{
FK2,
FK4,
FK10,
KOL_F_KL
};
enum
{
E_DATAN,
E_DATAK,
E_KODOP,
E_KASSA,
E_SHET,
E_KOD_KONTR,
KOLENTER
};
class kasothw_data
{
public:
kasothw_rr *rk;
GtkWidget *entry[KOLENTER];
GtkWidget *knopka[KOL_F_KL];
GtkWidget *knopka_enter[KOLENTER];
GtkWidget *window;
GtkWidget *opt1;
short kl_shift;
short voz; //0-начать расчёт 1 нет
kasothw_data() //Конструктор
{
kl_shift=0;
voz=1;
}
void read_rek()
{
rk->datan.new_plus(gtk_entry_get_text(GTK_ENTRY(entry[E_DATAN])));
rk->datak.new_plus(gtk_entry_get_text(GTK_ENTRY(entry[E_DATAK])));
rk->kodop.new_plus(gtk_entry_get_text(GTK_ENTRY(entry[E_KODOP])));
rk->kassa.new_plus(gtk_entry_get_text(GTK_ENTRY(entry[E_KASSA])));
rk->shet.new_plus(gtk_entry_get_text(GTK_ENTRY(entry[E_SHET])));
rk->kod_kontr.new_plus(gtk_entry_get_text(GTK_ENTRY(entry[E_KOD_KONTR])));
rk->metka_pr=gtk_combo_box_get_active (GTK_COMBO_BOX(opt1));
}
void clear_rek()
{
for(int i=0; i < KOLENTER; i++)
gtk_entry_set_text(GTK_ENTRY(entry[i]),"");
}
};
gboolean kasothw_v_key_press(GtkWidget *widget,GdkEventKey *event,class kasothw_data *data);
void kasothw_v_vvod(GtkWidget *widget,class kasothw_data *data);
void kasothw_v_knopka(GtkWidget *widget,class kasothw_data *data);
void kasothw_v_e_knopka(GtkWidget *widget,class kasothw_data *data);
extern SQL_baza bd;
int kasothw_m(class kasothw_rr *rek_ras,GtkWidget *wpredok)
{
kasothw_data data;
data.rk=rek_ras;
char strsql[512];
data.window=gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_position( GTK_WINDOW(data.window),ICEB_POS_CENTER);
gtk_window_set_modal(GTK_WINDOW(data.window),TRUE);
sprintf(strsql,"%s %s",iceb_get_namesystem(),data.rk->naim_oth.ravno());
gtk_window_set_title (GTK_WINDOW (data.window),strsql);
gtk_container_set_border_width (GTK_CONTAINER (data.window), 5);
g_signal_connect(data.window,"delete_event",G_CALLBACK(gtk_widget_destroy),NULL);
g_signal_connect(data.window,"destroy",G_CALLBACK(gtk_main_quit),NULL);
g_signal_connect_after(data.window,"key_press_event",G_CALLBACK(kasothw_v_key_press),&data);
if(wpredok != NULL)
{
gdk_window_set_cursor(gtk_widget_get_window(wpredok),gdk_cursor_new_for_display(gtk_widget_get_display(wpredok),ICEB_CURSOR_GDITE));
//Удерживать окно над породившем его окном всегда
gtk_window_set_transient_for(GTK_WINDOW(data.window),GTK_WINDOW(wpredok));
}
//Закрыть окно если окно предок удалено
gtk_window_set_destroy_with_parent(GTK_WINDOW(data.window),TRUE);
class iceb_u_str repl;
repl.plus(gettext("Учёт кассовых ордеров"));
repl.ps_plus(data.rk->naim_oth.ravno());
GtkWidget *label=gtk_label_new(repl.ravno());
GtkWidget *vbox = gtk_box_new (GTK_ORIENTATION_VERTICAL, 0);
gtk_box_set_homogeneous (GTK_BOX(vbox),FALSE); //Устанавливает одинакоый ли размер будут иметь упакованные виджеты-TRUE-одинаковые FALSE-нет
GtkWidget *hbox[KOLENTER];
for(int i=0; i < KOLENTER; i++)
{
hbox[i] = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 0);
gtk_box_set_homogeneous (GTK_BOX( hbox[i]),FALSE); //Устанавливает одинакоый ли размер будут иметь упакованные виджеты-TRUE-одинаковые FALSE-нет
}
GtkWidget *hboxknop = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 0);
gtk_box_set_homogeneous (GTK_BOX(hboxknop),FALSE); //Устанавливает одинакоый ли размер будут иметь упакованные виджеты-TRUE-одинаковые FALSE-нет
GtkWidget *hboxopt1 = gtk_box_new (GTK_ORIENTATION_HORIZONTAL,1);
gtk_box_set_homogeneous (GTK_BOX(hboxopt1),FALSE); //Устанавливает одинакоый ли размер будут иметь упакованные виджеты-TRUE-одинаковые FALSE-нет
gtk_container_add (GTK_CONTAINER (data.window), vbox);
gtk_box_pack_start (GTK_BOX (vbox),label, FALSE, FALSE, 0);
for(int i=0; i < KOLENTER; i++)
gtk_box_pack_start (GTK_BOX (vbox),hbox[i], FALSE, FALSE, 0);
label=gtk_label_new(gettext("Документы"));
gtk_box_pack_start (GTK_BOX (hboxopt1), label, FALSE, FALSE, 1);
class iceb_u_spisok bal_st;
bal_st.plus(gettext("Все документы"));
bal_st.plus(gettext("Только приходные документы"));
bal_st.plus(gettext("Только расходные документы"));
iceb_pm_vibor(&bal_st,&data.opt1,data.rk->metka_pr);
gtk_box_pack_start (GTK_BOX (hboxopt1), data.opt1, TRUE, TRUE,1);
gtk_box_pack_start (GTK_BOX (vbox),hboxopt1, FALSE, FALSE, 0);
gtk_box_pack_start (GTK_BOX (vbox),hboxknop, FALSE, FALSE, 0);
//gtk_container_add (GTK_CONTAINER (vbox), hboxknop);
sprintf(strsql,"%s",gettext("Дата начала"));
data.knopka_enter[E_DATAN]=gtk_button_new_with_label(strsql);
gtk_box_pack_start (GTK_BOX (hbox[E_DATAN]), data.knopka_enter[E_DATAN], FALSE, FALSE, 0);
g_signal_connect(data.knopka_enter[E_DATAN],"clicked",G_CALLBACK(kasothw_v_e_knopka),&data);
gtk_widget_set_name(data.knopka_enter[E_DATAN],iceb_u_inttochar(E_DATAN));
gtk_widget_set_tooltip_text(data.knopka_enter[E_DATAN],gettext("Выбор даты"));
data.entry[E_DATAN] = gtk_entry_new ();
gtk_entry_set_max_length(GTK_ENTRY(data.entry[E_DATAN]),20);
gtk_box_pack_start (GTK_BOX (hbox[E_DATAN]), data.entry[E_DATAN], TRUE, TRUE, 0);
g_signal_connect(data.entry[E_DATAN], "activate",G_CALLBACK(kasothw_v_vvod),&data);
gtk_entry_set_text(GTK_ENTRY(data.entry[E_DATAN]),data.rk->datan.ravno());
gtk_widget_set_name(data.entry[E_DATAN],iceb_u_inttochar(E_DATAN));
sprintf(strsql,"%s",gettext("Дата конца"));
data.knopka_enter[E_DATAK]=gtk_button_new_with_label(strsql);
gtk_box_pack_start (GTK_BOX (hbox[E_DATAK]), data.knopka_enter[E_DATAK], FALSE, FALSE, 0);
g_signal_connect(data.knopka_enter[E_DATAK],"clicked",G_CALLBACK(kasothw_v_e_knopka),&data);
gtk_widget_set_name(data.knopka_enter[E_DATAK],iceb_u_inttochar(E_DATAK));
gtk_widget_set_tooltip_text(data.knopka_enter[E_DATAK],gettext("Выбор даты"));
data.entry[E_DATAK] = gtk_entry_new ();
gtk_entry_set_max_length(GTK_ENTRY(data.entry[E_DATAK]),20);
gtk_box_pack_start (GTK_BOX (hbox[E_DATAK]), data.entry[E_DATAK], TRUE, TRUE, 0);
g_signal_connect(data.entry[E_DATAK], "activate",G_CALLBACK(kasothw_v_vvod),&data);
gtk_entry_set_text(GTK_ENTRY(data.entry[E_DATAK]),data.rk->datak.ravno());
gtk_widget_set_name(data.entry[E_DATAK],iceb_u_inttochar(E_DATAK));
sprintf(strsql,"%s (,,)",gettext("Код операции"));
data.knopka_enter[E_KODOP]=gtk_button_new_with_label(strsql);
gtk_box_pack_start (GTK_BOX (hbox[E_KODOP]), data.knopka_enter[E_KODOP], FALSE, FALSE, 0);
g_signal_connect(data.knopka_enter[E_KODOP],"clicked",G_CALLBACK(kasothw_v_e_knopka),&data);
gtk_widget_set_name(data.knopka_enter[E_KODOP],iceb_u_inttochar(E_KODOP));
gtk_widget_set_tooltip_text(data.knopka_enter[E_KODOP],gettext("Выбор операции"));
data.entry[E_KODOP] = gtk_entry_new();
gtk_box_pack_start (GTK_BOX (hbox[E_KODOP]), data.entry[E_KODOP], TRUE, TRUE, 0);
g_signal_connect(data.entry[E_KODOP], "activate",G_CALLBACK(kasothw_v_vvod),&data);
gtk_entry_set_text(GTK_ENTRY(data.entry[E_KODOP]),data.rk->kodop.ravno());
gtk_widget_set_name(data.entry[E_KODOP],iceb_u_inttochar(E_KODOP));
sprintf(strsql,"%s (,,)",gettext("Код кассы"));
data.knopka_enter[E_KASSA]=gtk_button_new_with_label(strsql);
gtk_box_pack_start (GTK_BOX (hbox[E_KASSA]), data.knopka_enter[E_KASSA], FALSE, FALSE, 0);
g_signal_connect(data.knopka_enter[E_KASSA],"clicked",G_CALLBACK(kasothw_v_e_knopka),&data);
gtk_widget_set_name(data.knopka_enter[E_KASSA],iceb_u_inttochar(E_KASSA));
gtk_widget_set_tooltip_text(data.knopka_enter[E_KASSA],gettext("Выбор кассы"));
data.entry[E_KASSA] = gtk_entry_new();
gtk_box_pack_start (GTK_BOX (hbox[E_KASSA]), data.entry[E_KASSA], TRUE, TRUE, 0);
g_signal_connect(data.entry[E_KASSA], "activate",G_CALLBACK(kasothw_v_vvod),&data);
gtk_entry_set_text(GTK_ENTRY(data.entry[E_KASSA]),data.rk->kassa.ravno());
gtk_widget_set_name(data.entry[E_KASSA],iceb_u_inttochar(E_KASSA));
sprintf(strsql,"%s (,,)",gettext("Счёт"));
data.knopka_enter[E_SHET]=gtk_button_new_with_label(strsql);
gtk_box_pack_start (GTK_BOX (hbox[E_SHET]), data.knopka_enter[E_SHET], FALSE, FALSE, 0);
g_signal_connect(data.knopka_enter[E_SHET],"clicked",G_CALLBACK(kasothw_v_e_knopka),&data);
gtk_widget_set_name(data.knopka_enter[E_SHET],iceb_u_inttochar(E_SHET));
gtk_widget_set_tooltip_text(data.knopka_enter[E_SHET],gettext("Выбор счёта"));
data.entry[E_SHET] = gtk_entry_new();
gtk_box_pack_start (GTK_BOX (hbox[E_SHET]), data.entry[E_SHET], TRUE, TRUE, 0);
g_signal_connect(data.entry[E_SHET], "activate",G_CALLBACK(kasothw_v_vvod),&data);
gtk_entry_set_text(GTK_ENTRY(data.entry[E_SHET]),data.rk->shet.ravno());
gtk_widget_set_name(data.entry[E_SHET],iceb_u_inttochar(E_SHET));
sprintf(strsql,"%s (,,)",gettext("Код контрагента"));
data.knopka_enter[E_KOD_KONTR]=gtk_button_new_with_label(strsql);
gtk_box_pack_start (GTK_BOX (hbox[E_KOD_KONTR]), data.knopka_enter[E_KOD_KONTR], FALSE, FALSE, 0);
g_signal_connect(data.knopka_enter[E_KOD_KONTR],"clicked",G_CALLBACK(kasothw_v_e_knopka),&data);
gtk_widget_set_name(data.knopka_enter[E_KOD_KONTR],iceb_u_inttochar(E_KOD_KONTR));
gtk_widget_set_tooltip_text(data.knopka_enter[E_KOD_KONTR],gettext("Выбор контрагента"));
data.entry[E_KOD_KONTR] = gtk_entry_new();
gtk_box_pack_start (GTK_BOX (hbox[E_KOD_KONTR]), data.entry[E_KOD_KONTR], TRUE, TRUE, 0);
g_signal_connect(data.entry[E_KOD_KONTR], "activate",G_CALLBACK(kasothw_v_vvod),&data);
gtk_entry_set_text(GTK_ENTRY(data.entry[E_KOD_KONTR]),data.rk->kod_kontr.ravno());
gtk_widget_set_name(data.entry[E_KOD_KONTR],iceb_u_inttochar(E_KOD_KONTR));
sprintf(strsql,"F2 %s",gettext("Расчёт"));
data.knopka[FK2]=gtk_button_new_with_label(strsql);
gtk_widget_set_tooltip_text(data.knopka[FK2],gettext("Начать расчёт"));
g_signal_connect(data.knopka[FK2],"clicked",G_CALLBACK(kasothw_v_knopka),&data);
gtk_widget_set_name(data.knopka[FK2],iceb_u_inttochar(FK2));
gtk_box_pack_start(GTK_BOX(hboxknop), data.knopka[FK2], TRUE, TRUE, 0);
sprintf(strsql,"F4 %s",gettext("Очистить"));
data.knopka[FK4]=gtk_button_new_with_label(strsql);
gtk_widget_set_tooltip_text(data.knopka[FK4],gettext("Очистить меню от введенной информации"));
g_signal_connect(data.knopka[FK4],"clicked",G_CALLBACK(kasothw_v_knopka),&data);
gtk_widget_set_name(data.knopka[FK4],iceb_u_inttochar(FK4));
gtk_box_pack_start(GTK_BOX(hboxknop), data.knopka[FK4], TRUE, TRUE, 0);
sprintf(strsql,"F10 %s",gettext("Выход"));
data.knopka[FK10]=gtk_button_new_with_label(strsql);
gtk_widget_set_tooltip_text(data.knopka[FK10],gettext("Завершение работы в этом окне"));
g_signal_connect(data.knopka[FK10],"clicked",G_CALLBACK(kasothw_v_knopka),&data);
gtk_widget_set_name(data.knopka[FK10],iceb_u_inttochar(FK10));
gtk_box_pack_start(GTK_BOX(hboxknop), data.knopka[FK10], TRUE, TRUE, 0);
gtk_widget_grab_focus(data.entry[0]);
gtk_widget_show_all (data.window);
gtk_main();
return(data.voz);
}
/*****************************/
/*Обработчик нажатия enter кнопок */
/*****************************/
void kasothw_v_e_knopka(GtkWidget *widget,class kasothw_data *data)
{
class iceb_u_str kod("");
class iceb_u_str naim("");
int knop=atoi(gtk_widget_get_name(widget));
switch (knop)
{
case E_DATAN:
if(iceb_calendar(&data->rk->datan,data->window) == 0)
gtk_entry_set_text(GTK_ENTRY(data->entry[E_DATAN]),data->rk->datan.ravno());
return;
case E_DATAK:
if(iceb_calendar(&data->rk->datak,data->window) == 0)
gtk_entry_set_text(GTK_ENTRY(data->entry[E_DATAK]),data->rk->datak.ravno());
return;
case E_KODOP:
vib_kodop_kas(&data->rk->kodop,data->window);
gtk_entry_set_text(GTK_ENTRY(data->entry[E_KODOP]),data->rk->kodop.ravno());
return;
case E_KASSA:
if(l_spis_kas(1,&kod,&naim,data->window) == 0)
data->rk->kassa.z_plus(kod.ravno());
gtk_entry_set_text(GTK_ENTRY(data->entry[E_KASSA]),data->rk->kassa.ravno());
return;
case E_SHET:
iceb_vibrek(0,"Plansh",&data->rk->shet,data->window);
gtk_entry_set_text(GTK_ENTRY(data->entry[E_SHET]),data->rk->shet.ravno());
return;
case E_KOD_KONTR:
iceb_vibrek(0,"Kontragent",&data->rk->kod_kontr,data->window);
gtk_entry_set_text(GTK_ENTRY(data->entry[E_KOD_KONTR]),data->rk->kod_kontr.ravno());
return;
}
}
/*********************************/
/*Обработка нажатия клавиш */
/*********************************/
gboolean kasothw_v_key_press(GtkWidget *widget,GdkEventKey *event,class kasothw_data *data)
{
//printf("kasothw_v_key_press\n");
switch(event->keyval)
{
case GDK_KEY_F2:
g_signal_emit_by_name(data->knopka[FK2],"clicked");
return(TRUE);
case GDK_KEY_F4:
g_signal_emit_by_name(data->knopka[FK4],"clicked");
return(TRUE);
case GDK_KEY_Escape:
case GDK_KEY_F10:
g_signal_emit_by_name(data->knopka[FK10],"clicked");
return(FALSE);
case ICEB_REG_L:
case ICEB_REG_R:
// printf("Нажата клавиша Shift\n");
data->kl_shift=1;
return(TRUE);
}
return(TRUE);
}
/*****************************/
/*Обработчик нажатия кнопок */
/*****************************/
void kasothw_v_knopka(GtkWidget *widget,class kasothw_data *data)
{
int knop=atoi(gtk_widget_get_name(widget));
switch (knop)
{
case FK2:
data->read_rek(); //Читаем реквизиты меню
// if(iceb_rsdatp(&dn,&mn,&gn,data->rk->datan.ravno(),&dk,&mk,&gk,data->rk->datak.ravno(),data->window) != 0)
if(iceb_rsdatp_str(&data->rk->datan,&data->rk->datak,data->window) != 0)
return;
gtk_widget_destroy(data->window);
data->window=NULL;
data->voz=0;
return;
case FK4:
data->clear_rek();
return;
case FK10:
data->read_rek(); //Читаем реквизиты меню
gtk_widget_destroy(data->window);
data->window=NULL;
data->voz=1;
return;
}
}
/********************************/
/*Перевод чтение текста и перевод фокуса на следующюю строку ввода*/
/******************************************/
void kasothw_v_vvod(GtkWidget *widget,class kasothw_data *data)
{
//short d,m,g;
int enter=atoi(gtk_widget_get_name(widget));
//g_print("kasothw_v_vvod enter=%d\n",enter);
switch (enter)
{
case E_DATAN:
data->rk->datan.new_plus(gtk_entry_get_text(GTK_ENTRY(widget)));
break;
case E_DATAK:
data->rk->datak.new_plus(gtk_entry_get_text(GTK_ENTRY(widget)));
break;
case E_KODOP:
data->rk->kodop.new_plus(gtk_entry_get_text(GTK_ENTRY(widget)));
break;
case E_KASSA:
data->rk->kassa.new_plus(gtk_entry_get_text(GTK_ENTRY(widget)));
break;
case E_SHET:
data->rk->shet.new_plus(gtk_entry_get_text(GTK_ENTRY(widget)));
break;
}
enter+=1;
if(enter >= KOLENTER)
enter=0;
gtk_widget_grab_focus(data->entry[enter]);
}
| [
"root@calculate.local"
] | root@calculate.local |
660dd230ddbb6f8ff854f91917732b00828b3cb1 | 2d2ee05cdcefbbeb45d87320cea0f1fef8b7638c | /OOP_HW4/test/ut_main.cpp | 8bf34c9fd2de29a92f63993de0fe71b414415d83 | [] | no_license | Holytu/POSD_HW | 15c71de9ff7a2f6b444428f1ac8c50db3552f85e | ccf5a40e23381473f6a585dc45a1eba492649013 | refs/heads/master | 2020-07-30T00:25:30.547765 | 2019-11-15T08:08:12 | 2019-11-15T08:08:12 | 210,017,931 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 182 | cpp | #include <gtest/gtest.h>
#include "../test/ut_node.h"
using namespace std;
int main(int argc, char ** argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| [
"nthuxy12345@gmail.com"
] | nthuxy12345@gmail.com |
10d7d95c5705acde477ddbf72742038142c46c92 | e30fea1b29491b5ce63b51458d1357aff629b6bf | /Game/testGame.cpp | 34373199db4ef7bb3281f39876ef30b4df121bc6 | [] | no_license | imaishunsuke/Game | d847d4318519eeccb368a1cf6cefa46e7b5c490b | d6da986fb5069bbd28a48c7ae38c6f4d002be6f5 | refs/heads/master | 2022-12-06T12:52:57.980612 | 2018-06-29T04:19:55 | 2018-06-29T04:19:55 | 124,839,481 | 0 | 1 | null | null | null | null | SHIFT_JIS | C++ | false | false | 1,736 | cpp | #include "stdafx.h"
#include "testGame.h"
#include "Fade.h"
#include "Title.h"
#include "Mirror.h"
#include "testGameCamera.h"
#include "testBackGround.h"
testGame::testGame()
{
}
testGame::~testGame()
{
}
void testGame::OnDestroy()
{
DeleteGO(m_gameCamera);
DeleteGO(m_skinModelRender);
DeleteGO(m_mirror);
DeleteGO(m_background);
}
bool testGame::Start()
{
m_gameCamera = NewGO<testGameCamera>(0);
m_background = NewGO<testBackGround>(0);
//カメラを設定。
//MainCamera().SetTarget({ 0.0f, 10.0f, 0.0f });
//MainCamera().SetNear(0.1f);
//MainCamera().SetFar(100.0f);
//MainCamera().SetPosition({ 30.0f, 10.0f, 0.0f });
//MainCamera().Update();
//m_skinModelRender = NewGO<prefab::CSkinModelRender>(0);
//m_skinModelRender->Init(L"modelData/unityChan.cmo");
//m_skinModelRender->SetScale({ 0.1f, 0.1f, 0.1f });
m_fade = FindGO<Fade>("Fade");
m_fade->StartFadeIn();
m_state = enState_FadeIn;
m_mirror = NewGO<Mirror>(0, "Mirror");
m_level.Build(L"testLevel/testobj.tks");
return true;
}
void testGame::Update()
{
switch (m_state) {
case enState_FadeIn:
GraphicsEngine().GetTonemap().Reset();
if (!m_fade->IsFade()) {
m_state = enState_InGame;
}
break;
case enState_InGame: {
m_waitTimer += GameTime().GetFrameDeltaTime();
if (m_waitTimer < 0.1f) {
//ゲームが開始して0.1秒経過するまでトーンマップの明暗順応はしない
GraphicsEngine().GetTonemap().Reset();
}
}
break;
}
if (m_isWaitFadeout)
{
if (!m_fade->IsFade()) {
NewGO<Title>(0, nullptr);
DeleteGO(this);
}
}
else {
if (Pad(0).IsTrigger(enButtonStart)) {
m_isWaitFadeout = true;
m_fade->StartFadeOut();
}
}
}
void testGame::Render(CRenderContext& rc)
{
(void)rc;
} | [
"kbc17b02@stu.kawahara.ac.jp"
] | kbc17b02@stu.kawahara.ac.jp |
192385b6585995ae7dae63dde0868289b23e60e6 | f42190636add23ead6a5022d706a124032d66f92 | /src/Microsoft.DotNet.Wpf/src/WpfGfx/core/hw/swfallback.h | 8336e9d66fd2783776f7f63c56ca71ce6c4a82e1 | [
"MIT"
] | permissive | dotnet/wpf | b8f73a99e03f87b4dee5db643e38e2c0704f707a | 2ff355a607d79eef5fea7796de1f29cf9ea4fbed | refs/heads/main | 2023-09-04T09:35:19.355384 | 2023-09-03T02:30:37 | 2023-09-03T02:30:37 | 153,711,945 | 6,927 | 1,397 | MIT | 2023-09-14T17:22:06 | 2018-10-19T01:55:23 | C# | UTF-8 | C++ | false | false | 4,722 | h | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//------------------------------------------------------------------------------
//
//
// Description:
// Contains CHwSoftwareFallback which provides software fallback for the hw
// render target.
//
class CD3DDeviceLevel1;
class CHwSurfaceRenderTarget;
MtExtern(CHwSoftwareFallback);
#define NUM_FALLBACK_TILES 2
//------------------------------------------------------------------------------
//
// Class: CHwSoftwareFallback
//
// Description:
// Provides software fallback for the hw render target. Note that this
// is implemented by creating a small set of tiles in system memory that
// we will render to using the software rasterizer and then draw using
// the d3d device. We need tiling to save memory and deal with
// texture limits.
//
//------------------------------------------------------------------------------
class CHwSoftwareFallback
: public CSpanSink
{
public:
DECLARE_METERHEAP_ALLOC(ProcessHeap, Mt(CHwSoftwareFallback));
//
// CHwSoftwareFallback specific methods
//
CHwSoftwareFallback();
virtual ~CHwSoftwareFallback()
{
// nothing
};
HRESULT Init(
__inout_ecount(1) CD3DDeviceLevel1 *pD3DDevice
);
//
// IRenderTargetInternal methods that need to be exposed
//
// Draw a surface.
HRESULT DrawBitmap(
__in_ecount(1) const CContextState *pContextState,
__inout_ecount(1) IWGXBitmapSource *pIBitmap,
__in_ecount_opt(1) IMILEffectList *pIEffect,
UINT uTargetWidth,
UINT uTargetHeight
);
// Draw a path.
HRESULT FillPath(
__in_ecount(1) const CContextState *pContextState,
__in_ecount_opt(1) const CMatrix<CoordinateSpace::Shape,CoordinateSpace::Device> *pmatShapeToDevice,
__in_ecount(1) const IShapeData *pShape,
__in_ecount(1) CMILBrush *pBrush,
__in_ecount_opt(1) IMILEffectList *pIEffect,
UINT uTargetWidth,
UINT uTargetHeight
);
// Draw a glyph run
HRESULT DrawGlyphs(
__in_ecount(1) DrawGlyphsParameters &pars,
bool fTargetSupportsClearType,
__in_ecount(1) CMILBrush *pBrush,
FLOAT flEffectAlpha,
__in_ecount(1) CGlyphPainterMemory *pGlyphPainterMemory,
UINT uTargetWidth,
UINT uTargetHeight
);
// CSpanSink interface
override void OutputSpan(INT y, INT xMin, INT xMax);
override void AddDirtyRect(__in_ecount(1) const MilPointAndSizeL *prcDirty);
override HRESULT SetupPipeline(
MilPixelFormat::Enum fmtColorData,
__in_ecount(1) CColorSource *pColorSource,
BOOL fPPAA,
bool fComplementAlpha,
MilCompositingMode::Enum eCompositingMode,
__in_ecount(1) CSpanClipper *pSpanClipper,
__in_ecount_opt(1) IMILEffectList *pIEffectList,
__in_ecount_opt(1) const CMatrix<CoordinateSpace::Effect,CoordinateSpace::Device> *pmatEffectToDevice,
__in_ecount(1) const CContextState *pContextState
);
override HRESULT SetupPipelineForText(
__in_ecount(1) CColorSource *pColorSource,
MilCompositingMode::Enum eCompositingMode,
__in_ecount(1) CSWGlyphRunPainter &painter,
bool fNeedsAA
);
override VOID ReleaseExpensiveResources();
override VOID SetAntialiasedFiller(
__in_ecount(1) CAntialiasedFiller *pFiller
);
private:
HRESULT InitAlphaTextures();
UINT CalculateScanlineOffset(INT x, INT y, UINT nWidth) const;
BOOL ComputeFirstTile(UINT uTargetWidth, UINT uTargetHeight );
BOOL ComputeNextTile();
HRESULT DrawCurrentTile(bool fUseAux = false);
private:
//
// D3D objects
//
CD3DDeviceLevel1 *m_pD3DDevice;
//
// Tile data
//
UINT m_uMaxTileWidth;
UINT m_uMaxTileHeight;
MilPointAndSizeL m_rcShapeBounds;
MilPointAndSizeL m_rcCurrentTile;
CD3DLockableTexturePair m_tiles[NUM_FALLBACK_TILES];
CD3DLockableTexturePair *m_pCurrentTile; // points to one of m_tiles
CD3DLockableTexturePairLock::LockData m_lockData;
//
// Software rasterizer buffers
//
CSPIntermediateBuffers m_IntermediateBuffers;
//
// Data used for the scan pipeline
//
CScanPipelineRendering m_ScanPipeline;
// Software rasterizer class itself
CSoftwareRasterizer m_sr;
// Flags for clear type text rendering
BOOL m_fAlphaTexturesInited;
};
| [
"vatsan.madhavan@microsoft.com"
] | vatsan.madhavan@microsoft.com |
a511af48cfede7020d60becaeb7b03ad4abe27a6 | 39daf3621dbff334c46fd7a591a018642a738943 | /include/rapidjson/internal/pow10.h | 0252edfe582da7756f5708fbe42f0ff81e9cff33 | [
"Apache-2.0"
] | permissive | hecor/freeCTP | 42b5aa35b1b056b4b125d4e271f9ce55e3311d9a | f9300b225174dcb8386225139afcea034f431dc1 | refs/heads/master | 2021-01-02T08:21:28.394453 | 2015-03-28T02:23:37 | 2015-03-28T02:23:37 | 16,941,298 | 8 | 6 | Apache-2.0 | 2020-10-02T05:21:52 | 2014-02-18T08:01:18 | C++ | UTF-8 | C++ | false | false | 4,019 | h | // Copyright (C) 2011 Milo Yip
//
// 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 RAPIDJSON_POW10_
#define RAPIDJSON_POW10_
RAPIDJSON_NAMESPACE_BEGIN
namespace internal {
//! Computes integer powers of 10 in double (10.0^n).
/*! This function uses lookup table for fast and accurate results.
\param n non-negative exponent. Must <= 308.
\return 10.0^n
*/
inline double Pow10(int n) {
static const double e[] = { // 1e-0...1e308: 309 * 8 bytes = 2472 bytes
1e+0,
1e+1, 1e+2, 1e+3, 1e+4, 1e+5, 1e+6, 1e+7, 1e+8, 1e+9, 1e+10, 1e+11, 1e+12, 1e+13, 1e+14, 1e+15, 1e+16, 1e+17, 1e+18, 1e+19, 1e+20,
1e+21, 1e+22, 1e+23, 1e+24, 1e+25, 1e+26, 1e+27, 1e+28, 1e+29, 1e+30, 1e+31, 1e+32, 1e+33, 1e+34, 1e+35, 1e+36, 1e+37, 1e+38, 1e+39, 1e+40,
1e+41, 1e+42, 1e+43, 1e+44, 1e+45, 1e+46, 1e+47, 1e+48, 1e+49, 1e+50, 1e+51, 1e+52, 1e+53, 1e+54, 1e+55, 1e+56, 1e+57, 1e+58, 1e+59, 1e+60,
1e+61, 1e+62, 1e+63, 1e+64, 1e+65, 1e+66, 1e+67, 1e+68, 1e+69, 1e+70, 1e+71, 1e+72, 1e+73, 1e+74, 1e+75, 1e+76, 1e+77, 1e+78, 1e+79, 1e+80,
1e+81, 1e+82, 1e+83, 1e+84, 1e+85, 1e+86, 1e+87, 1e+88, 1e+89, 1e+90, 1e+91, 1e+92, 1e+93, 1e+94, 1e+95, 1e+96, 1e+97, 1e+98, 1e+99, 1e+100,
1e+101,1e+102,1e+103,1e+104,1e+105,1e+106,1e+107,1e+108,1e+109,1e+110,1e+111,1e+112,1e+113,1e+114,1e+115,1e+116,1e+117,1e+118,1e+119,1e+120,
1e+121,1e+122,1e+123,1e+124,1e+125,1e+126,1e+127,1e+128,1e+129,1e+130,1e+131,1e+132,1e+133,1e+134,1e+135,1e+136,1e+137,1e+138,1e+139,1e+140,
1e+141,1e+142,1e+143,1e+144,1e+145,1e+146,1e+147,1e+148,1e+149,1e+150,1e+151,1e+152,1e+153,1e+154,1e+155,1e+156,1e+157,1e+158,1e+159,1e+160,
1e+161,1e+162,1e+163,1e+164,1e+165,1e+166,1e+167,1e+168,1e+169,1e+170,1e+171,1e+172,1e+173,1e+174,1e+175,1e+176,1e+177,1e+178,1e+179,1e+180,
1e+181,1e+182,1e+183,1e+184,1e+185,1e+186,1e+187,1e+188,1e+189,1e+190,1e+191,1e+192,1e+193,1e+194,1e+195,1e+196,1e+197,1e+198,1e+199,1e+200,
1e+201,1e+202,1e+203,1e+204,1e+205,1e+206,1e+207,1e+208,1e+209,1e+210,1e+211,1e+212,1e+213,1e+214,1e+215,1e+216,1e+217,1e+218,1e+219,1e+220,
1e+221,1e+222,1e+223,1e+224,1e+225,1e+226,1e+227,1e+228,1e+229,1e+230,1e+231,1e+232,1e+233,1e+234,1e+235,1e+236,1e+237,1e+238,1e+239,1e+240,
1e+241,1e+242,1e+243,1e+244,1e+245,1e+246,1e+247,1e+248,1e+249,1e+250,1e+251,1e+252,1e+253,1e+254,1e+255,1e+256,1e+257,1e+258,1e+259,1e+260,
1e+261,1e+262,1e+263,1e+264,1e+265,1e+266,1e+267,1e+268,1e+269,1e+270,1e+271,1e+272,1e+273,1e+274,1e+275,1e+276,1e+277,1e+278,1e+279,1e+280,
1e+281,1e+282,1e+283,1e+284,1e+285,1e+286,1e+287,1e+288,1e+289,1e+290,1e+291,1e+292,1e+293,1e+294,1e+295,1e+296,1e+297,1e+298,1e+299,1e+300,
1e+301,1e+302,1e+303,1e+304,1e+305,1e+306,1e+307,1e+308
};
RAPIDJSON_ASSERT(n >= 0 && n <= 308);
return e[n];
}
} // namespace internal
RAPIDJSON_NAMESPACE_END
#endif // RAPIDJSON_POW10_
| [
"husthecor@gmail.com"
] | husthecor@gmail.com |
6a296e78777cee684347bd87743597b2cad688f1 | 927077b0100ccdd4f6962256330d1d049f74427a | /devel/include/dji_sdk_web_groundstation/WebWaypointReceiveActionFeedback.h | 44c6e6329574a3dd1c2020a35e1b0087af6a1e9c | [] | no_license | Aswath93/ros | d883474125702d79ca3f21cea4c4b65352c2d718 | 61952bc47542fff33564c367bb83f4e69cbfb18c | refs/heads/master | 2021-01-16T19:57:07.349378 | 2017-08-13T15:51:54 | 2017-08-13T15:51:54 | 100,187,737 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,055 | h | // Generated by gencpp from file dji_sdk_web_groundstation/WebWaypointReceiveActionFeedback.msg
// DO NOT EDIT!
#ifndef DJI_SDK_WEB_GROUNDSTATION_MESSAGE_WEBWAYPOINTRECEIVEACTIONFEEDBACK_H
#define DJI_SDK_WEB_GROUNDSTATION_MESSAGE_WEBWAYPOINTRECEIVEACTIONFEEDBACK_H
#include <string>
#include <vector>
#include <map>
#include <ros/types.h>
#include <ros/serialization.h>
#include <ros/builtin_message_traits.h>
#include <ros/message_operations.h>
#include <std_msgs/Header.h>
#include <actionlib_msgs/GoalStatus.h>
#include <dji_sdk_web_groundstation/WebWaypointReceiveFeedback.h>
namespace dji_sdk_web_groundstation
{
template <class ContainerAllocator>
struct WebWaypointReceiveActionFeedback_
{
typedef WebWaypointReceiveActionFeedback_<ContainerAllocator> Type;
WebWaypointReceiveActionFeedback_()
: header()
, status()
, feedback() {
}
WebWaypointReceiveActionFeedback_(const ContainerAllocator& _alloc)
: header(_alloc)
, status(_alloc)
, feedback(_alloc) {
(void)_alloc;
}
typedef ::std_msgs::Header_<ContainerAllocator> _header_type;
_header_type header;
typedef ::actionlib_msgs::GoalStatus_<ContainerAllocator> _status_type;
_status_type status;
typedef ::dji_sdk_web_groundstation::WebWaypointReceiveFeedback_<ContainerAllocator> _feedback_type;
_feedback_type feedback;
typedef boost::shared_ptr< ::dji_sdk_web_groundstation::WebWaypointReceiveActionFeedback_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::dji_sdk_web_groundstation::WebWaypointReceiveActionFeedback_<ContainerAllocator> const> ConstPtr;
}; // struct WebWaypointReceiveActionFeedback_
typedef ::dji_sdk_web_groundstation::WebWaypointReceiveActionFeedback_<std::allocator<void> > WebWaypointReceiveActionFeedback;
typedef boost::shared_ptr< ::dji_sdk_web_groundstation::WebWaypointReceiveActionFeedback > WebWaypointReceiveActionFeedbackPtr;
typedef boost::shared_ptr< ::dji_sdk_web_groundstation::WebWaypointReceiveActionFeedback const> WebWaypointReceiveActionFeedbackConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::dji_sdk_web_groundstation::WebWaypointReceiveActionFeedback_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::dji_sdk_web_groundstation::WebWaypointReceiveActionFeedback_<ContainerAllocator> >::stream(s, "", v);
return s;
}
} // namespace dji_sdk_web_groundstation
namespace ros
{
namespace message_traits
{
// BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': True}
// {'nav_msgs': ['/opt/ros/indigo/share/nav_msgs/cmake/../msg'], 'dji_sdk': ['/home/aswath/ros/src/Onboard-SDK-ROS/dji_sdk/msg', '/home/aswath/ros/devel/share/dji_sdk/msg'], 'dji_sdk_web_groundstation': ['/home/aswath/ros/src/Onboard-SDK-ROS/dji_sdk_web_groundstation/msg', '/home/aswath/ros/devel/share/dji_sdk_web_groundstation/msg'], 'std_msgs': ['/opt/ros/indigo/share/std_msgs/cmake/../msg'], 'geometry_msgs': ['/opt/ros/indigo/share/geometry_msgs/cmake/../msg'], 'actionlib_msgs': ['/opt/ros/indigo/share/actionlib_msgs/cmake/../msg']}
// !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types']
template <class ContainerAllocator>
struct IsFixedSize< ::dji_sdk_web_groundstation::WebWaypointReceiveActionFeedback_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::dji_sdk_web_groundstation::WebWaypointReceiveActionFeedback_<ContainerAllocator> const>
: FalseType
{ };
template <class ContainerAllocator>
struct IsMessage< ::dji_sdk_web_groundstation::WebWaypointReceiveActionFeedback_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::dji_sdk_web_groundstation::WebWaypointReceiveActionFeedback_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::dji_sdk_web_groundstation::WebWaypointReceiveActionFeedback_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::dji_sdk_web_groundstation::WebWaypointReceiveActionFeedback_<ContainerAllocator> const>
: TrueType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::dji_sdk_web_groundstation::WebWaypointReceiveActionFeedback_<ContainerAllocator> >
{
static const char* value()
{
return "79bb17b55445d74a0c0e24476d76d979";
}
static const char* value(const ::dji_sdk_web_groundstation::WebWaypointReceiveActionFeedback_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0x79bb17b55445d74aULL;
static const uint64_t static_value2 = 0x0c0e24476d76d979ULL;
};
template<class ContainerAllocator>
struct DataType< ::dji_sdk_web_groundstation::WebWaypointReceiveActionFeedback_<ContainerAllocator> >
{
static const char* value()
{
return "dji_sdk_web_groundstation/WebWaypointReceiveActionFeedback";
}
static const char* value(const ::dji_sdk_web_groundstation::WebWaypointReceiveActionFeedback_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::dji_sdk_web_groundstation::WebWaypointReceiveActionFeedback_<ContainerAllocator> >
{
static const char* value()
{
return "# ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ======\n\
\n\
Header header\n\
actionlib_msgs/GoalStatus status\n\
WebWaypointReceiveFeedback feedback\n\
\n\
================================================================================\n\
MSG: std_msgs/Header\n\
# Standard metadata for higher-level stamped data types.\n\
# This is generally used to communicate timestamped data \n\
# in a particular coordinate frame.\n\
# \n\
# sequence ID: consecutively increasing ID \n\
uint32 seq\n\
#Two-integer timestamp that is expressed as:\n\
# * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')\n\
# * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')\n\
# time-handling sugar is provided by the client library\n\
time stamp\n\
#Frame this data is associated with\n\
# 0: no frame\n\
# 1: global frame\n\
string frame_id\n\
\n\
================================================================================\n\
MSG: actionlib_msgs/GoalStatus\n\
GoalID goal_id\n\
uint8 status\n\
uint8 PENDING = 0 # The goal has yet to be processed by the action server\n\
uint8 ACTIVE = 1 # The goal is currently being processed by the action server\n\
uint8 PREEMPTED = 2 # The goal received a cancel request after it started executing\n\
# and has since completed its execution (Terminal State)\n\
uint8 SUCCEEDED = 3 # The goal was achieved successfully by the action server (Terminal State)\n\
uint8 ABORTED = 4 # The goal was aborted during execution by the action server due\n\
# to some failure (Terminal State)\n\
uint8 REJECTED = 5 # The goal was rejected by the action server without being processed,\n\
# because the goal was unattainable or invalid (Terminal State)\n\
uint8 PREEMPTING = 6 # The goal received a cancel request after it started executing\n\
# and has not yet completed execution\n\
uint8 RECALLING = 7 # The goal received a cancel request before it started executing,\n\
# but the action server has not yet confirmed that the goal is canceled\n\
uint8 RECALLED = 8 # The goal received a cancel request before it started executing\n\
# and was successfully cancelled (Terminal State)\n\
uint8 LOST = 9 # An action client can determine that a goal is LOST. This should not be\n\
# sent over the wire by an action server\n\
\n\
#Allow for the user to associate a string with GoalStatus for debugging\n\
string text\n\
\n\
\n\
================================================================================\n\
MSG: actionlib_msgs/GoalID\n\
# The stamp should store the time at which this goal was requested.\n\
# It is used by an action server when it tries to preempt all\n\
# goals that were requested before a certain time\n\
time stamp\n\
\n\
# The id provides a way to associate feedback and\n\
# result message with specific goal requests. The id\n\
# specified must be unique.\n\
string id\n\
\n\
\n\
================================================================================\n\
MSG: dji_sdk_web_groundstation/WebWaypointReceiveFeedback\n\
# ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ======\n\
#progress is in percent\n\
uint8 latitude_progress\n\
uint8 longitude_progress\n\
uint8 altitude_progress\n\
uint8 index_progress\n\
#stage code:\n\
# 0: waiting for waypoint_list\n\
# 1: waiting for start\n\
# 2: in progress\n\
# 3: paused\n\
# 4: canceled\n\
uint8 stage\n\
\n\
";
}
static const char* value(const ::dji_sdk_web_groundstation::WebWaypointReceiveActionFeedback_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::dji_sdk_web_groundstation::WebWaypointReceiveActionFeedback_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)
{
stream.next(m.header);
stream.next(m.status);
stream.next(m.feedback);
}
ROS_DECLARE_ALLINONE_SERIALIZER
}; // struct WebWaypointReceiveActionFeedback_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::dji_sdk_web_groundstation::WebWaypointReceiveActionFeedback_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::dji_sdk_web_groundstation::WebWaypointReceiveActionFeedback_<ContainerAllocator>& v)
{
s << indent << "header: ";
s << std::endl;
Printer< ::std_msgs::Header_<ContainerAllocator> >::stream(s, indent + " ", v.header);
s << indent << "status: ";
s << std::endl;
Printer< ::actionlib_msgs::GoalStatus_<ContainerAllocator> >::stream(s, indent + " ", v.status);
s << indent << "feedback: ";
s << std::endl;
Printer< ::dji_sdk_web_groundstation::WebWaypointReceiveFeedback_<ContainerAllocator> >::stream(s, indent + " ", v.feedback);
}
};
} // namespace message_operations
} // namespace ros
#endif // DJI_SDK_WEB_GROUNDSTATION_MESSAGE_WEBWAYPOINTRECEIVEACTIONFEEDBACK_H
| [
"aswath93@gmail.com"
] | aswath93@gmail.com |
a7fdc3d01bf061388978ce3fd0b8455f2af8c6be | 379dc81d5162d36514468859b4eec8124c2ff65c | /benchmarks/b5/b5_simple.cpp | 7f928568a1b35e122f5088b53c49b7f826f04c09 | [
"MIT"
] | permissive | SunghoLee/c-summary | 5fba42facd5a2137ae22202841de9a12352f3e39 | a7fea7bf57138866f0eede0b3a22f41612d6bf94 | refs/heads/master | 2023-03-07T14:22:41.909684 | 2021-02-10T12:31:37 | 2021-02-10T12:31:37 | 169,503,055 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,238 | cpp | //
// Created by Xingwei Lin on 6/12/17.
//
#include <android/log.h>
#include <jni.h>
#include <stddef.h>
#include <assert.h>
#define LOG_TAG "dynamic_register_multiple"
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
#define JNIREG_CLASS "org/arguslab/native_dynamic_register_multiple/MainActivity"
extern "C" {
JNIEXPORT void JNICALL native_send(JNIEnv *env, jobject thisObj, jstring data);
JNIEXPORT void JNICALL native_sendFoo(JNIEnv *env, jobject thisObj, jint index, jstring data);
JNIEXPORT void JNICALL native_sendBar(JNIEnv *env, jobject thisObj, jdouble dw, jstring data);
}
JNIEXPORT void JNICALL native_send(JNIEnv *env, jobject thisObj, jstring data) {
}
JNIEXPORT void JNICALL native_sendFoo(JNIEnv *env, jobject thisObj, jint index, jstring data) {
}
JNIEXPORT void JNICALL native_sendBar(JNIEnv *env, jobject thisObj, jdouble dw, jstring data) {
}
/**
* Table of methods associated with a single class.
*/
static JNINativeMethod gMethods[] = {
{"send", "(Ljava/lang/String;)V", (void *) native_send},
{"sendFoo", "(ILjava/lang/String;)V", (void *) native_sendFoo},
{"sendBar", "(DLjava/lang/String;)V", (void *) native_sendBar},
};
/*
* Register several native methods for one class.
*/
static int registerNativeMethods(JNIEnv *env, const char *className,
JNINativeMethod *locals, int numMethods) {
jclass clazz = (jclass)env->FindClass(className);
env->RegisterNatives(clazz, locals, numMethods);
return JNI_TRUE;
}
/*
* Register native methods for all classes we know about.
*/
static int registerNatives(JNIEnv *env) {
JNINativeMethod foolocs[] = {
{"send", "(Ljava/lang/String;)V", (void *) native_send},
{"sendFoo", "(ILjava/lang/String;)V", (void *) native_sendFoo},
{"sendBar", "(DLjava/lang/String;)V", (void *) native_sendBar},
};
registerNativeMethods(env, JNIREG_CLASS, gMethods,
sizeof(gMethods) / sizeof(gMethods[0]));
return JNI_FALSE;
}
| [
"eshaj@kaist.ac.kr"
] | eshaj@kaist.ac.kr |
e5e55eef2a80bf7781a48ec6610ce09112004fa6 | 419276d2ed283ef2b8405ec66962fccb43491a63 | /sem4/ООП/lab_1/output.cpp | 103414ae7d65e8dd72d64351774d1356ddfdf044 | [] | no_license | H0uston/bmstu | 6231edb99effc556b93c7320b471cc15d17e3c75 | cbb44d0f9cdbe6ced360c01b04365ae7329d29c8 | refs/heads/main | 2023-06-23T12:36:51.543458 | 2021-07-19T19:40:04 | 2021-07-19T19:40:04 | 377,950,950 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,628 | cpp | #include "output.h"
// Функция обертка для fscanf (запись)
static void print_counts(FILE *file, int count_of_points, int count_of_edges)
{
fprintf(file, "%d %d\n", count_of_points, count_of_edges);
}
// Функция обертка для fscanf (запись)
static void print_points(shape_t &shape, FILE *file, int i)
{
fprintf(file, "%lf %lf %lf\n", get_x_index_point(shape, i), get_y_index_point(shape, i), get_z_index_point(shape, i));
}
// Функция обертка для fscanf (запись)
static void print_edges(shape_t &shape, FILE *file, int i)
{
fprintf(file, "%d->%d\n", get_first_index_edge(shape, i), get_second_index_edge(shape, i));
}
// Функция сохранения модели в файл
int save_shape(shape_t &shape, parameters_t ¶meters)
{
int code_error = OK;
if (!shape.points || !shape.edges)
{
code_error = ERR_SAVE;
return code_error;
}
stream_t stream = stream_init();
code_error = file_openning_save(stream, parameters.filename);
if (code_error == OK)
{
int n = get_count_of_points(shape);
int m = get_count_of_edges(shape);
print_counts(get_file_from_stream_t(stream), n, m);
for (int i = 0; i < n; i++)
{
print_points(shape, get_file_from_stream_t(stream), i);
}
for (int i = 0; i < m; i++)
{
print_edges(shape, get_file_from_stream_t(stream), i);
}
close_stream(stream);
}
else
{
code_error = ERR_SAVE;
return code_error;
}
return code_error;
}
| [
"HoustonEU@gmail.com"
] | HoustonEU@gmail.com |
e0acfcbc4b850af2f4e6789754adce662729c568 | 04b1803adb6653ecb7cb827c4f4aa616afacf629 | /ui/events/test/test_event_targeter.cc | 0794d45116ba708322408c2bae54426746770bb9 | [
"BSD-3-Clause"
] | permissive | Samsung/Castanets | 240d9338e097b75b3f669604315b06f7cf129d64 | 4896f732fc747dfdcfcbac3d442f2d2d42df264a | refs/heads/castanets_76_dev | 2023-08-31T09:01:04.744346 | 2021-07-30T04:56:25 | 2021-08-11T05:45:21 | 125,484,161 | 58 | 49 | BSD-3-Clause | 2022-10-16T19:31:26 | 2018-03-16T08:07:37 | null | UTF-8 | C++ | false | false | 1,055 | cc | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/events/test/test_event_targeter.h"
#include "ui/events/test/test_event_target.h"
namespace ui {
namespace test {
TestEventTargeter::TestEventTargeter(TestEventTarget* initial_target,
bool should_bubble)
: target_(initial_target), should_bubble_(should_bubble) {
}
TestEventTargeter::~TestEventTargeter() {
}
void TestEventTargeter::set_target(TestEventTarget* target) {
target_ = target;
}
EventTarget* TestEventTargeter::FindTargetForEvent(EventTarget* root,
Event* event) {
return target_;
}
EventTarget* TestEventTargeter::FindNextBestTarget(EventTarget* previous_target,
Event* event) {
if (!should_bubble_)
return nullptr;
return previous_target->GetParentTarget();
}
} // namespace test
} // namespace ui
| [
"sunny.nam@samsung.com"
] | sunny.nam@samsung.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.