hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
616c1264e2cad514d567e17c12d32c22534a13d7
781
cpp
C++
advanced/1157 Anniversary (25).cpp
niedong/PAT
dcdde06618154f67d91c01aefe54274b732768d3
[ "MIT" ]
1
2021-12-19T08:55:14.000Z
2021-12-19T08:55:14.000Z
advanced/1157 Anniversary (25).cpp
niedong/PAT
dcdde06618154f67d91c01aefe54274b732768d3
[ "MIT" ]
null
null
null
advanced/1157 Anniversary (25).cpp
niedong/PAT
dcdde06618154f67d91c01aefe54274b732768d3
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; bool comp(const string& lhs, const string& rhs) { return lhs.substr(6, 8) < rhs.substr(6, 8); } int main() { int n, m, res = 0; vector<string> v, g; unordered_map<string, bool> hashmap; cin >> n; for (int i = 0; i < n; ++i) { string s; cin >> s; hashmap[s] = true; } cin >> m; for (int i = 0; i < m; ++i) { string s; cin >> s; if (hashmap[s]) { ++res; v.push_back(s); } g.push_back(s); } cout << res << endl; if (res) { sort(v.begin(), v.end(), comp); cout << v.front() << endl; } else { sort(g.begin(), g.end(), comp); cout << g.front() << endl; } }
19.525
49
0.435339
niedong
616c56f6d7ed788472eb4b259a29ef6a78b191bc
1,227
hpp
C++
MC_functions.hpp
CaryRock/Phys642_Final_Project
fb1e49b84efb0585857bb16379fbc6ac39074c5c
[ "Unlicense" ]
null
null
null
MC_functions.hpp
CaryRock/Phys642_Final_Project
fb1e49b84efb0585857bb16379fbc6ac39074c5c
[ "Unlicense" ]
null
null
null
MC_functions.hpp
CaryRock/Phys642_Final_Project
fb1e49b84efb0585857bb16379fbc6ac39074c5c
[ "Unlicense" ]
null
null
null
#define MC_FUNCTIONS_H #ifndef COMMON_HEADERS_H #include "common_headers.hpp" #endif namespace br = boost::random; namespace bu = boost::uuids; struct Params { size_t L; // size_t Lx; // size_t Ly; size_t N; size_t numSamp; uint64_t numEqSteps; // double beta; double temp; std::string baseName; bu::uuid uid; br::mt19937_64 rng; br::uniform_real_distribution<double> dist01; Params(size_t, size_t, size_t, uint64_t, double, std::string, bu::uuid, br::mt19937_64, br::uniform_real_distribution<double>); ~Params(){}; double GetRNG01(); }; // I know the names aren't necessary, but they're convenient bookkeeping // GetOptions.cpp template<class T> std::ostream &operator<<(std::ostream &os, const std::vector<T> &v); int64_t GetOptions(int64_t ac, char **av, size_t *L, double *T, size_t *numSamp, uint64_t *numEqSteps); // MC_functions.cpp double GetProperties(int64_t *sigma, int64_t *plus1, int64_t *minus1, size_t L); double Update(Params Pars, int64_t *sigma, br::uniform_int_distribution<size_t> *dist0L, int64_t *plus1, int64_t *minus1); double GetCurrentMagnetization(int64_t *sigma, size_t L); void MonteCarlo(Params Pars);
27.886364
87
0.700081
CaryRock
6170db82ada3885d49bd527ca1b48d8480c3b304
499
cpp
C++
Tools/chrono/system_clock.cpp
liangjisheng/C-Cpp
8b33ba1f43580a7bdded8bb4ce3d92983ccedb81
[ "MIT" ]
5
2019-09-17T09:12:15.000Z
2021-05-29T10:54:39.000Z
Tools/chrono/system_clock.cpp
liangjisheng/C-Cpp
8b33ba1f43580a7bdded8bb4ce3d92983ccedb81
[ "MIT" ]
null
null
null
Tools/chrono/system_clock.cpp
liangjisheng/C-Cpp
8b33ba1f43580a7bdded8bb4ce3d92983ccedb81
[ "MIT" ]
2
2021-07-26T06:36:12.000Z
2022-01-23T15:20:30.000Z
#include <iostream> #include <chrono> #include <ctime> #include <iomanip> // for put_time() using namespace std; using namespace std::chrono; int main() { // Get current time as a time_point system_clock::time_point tpoint = system_clock::now(); // Convert to a time_t time_t tt = system_clock::to_time_t(tpoint); // Convert to local time tm* t = localtime(&tt); // Write the time to the console cout << std::put_time(t, "%H:%M:%S") << endl; return 0; }
21.695652
58
0.639279
liangjisheng
6170e8703be71442df62d2072c8408efc4a59921
32,064
cpp
C++
Source/Model/COM/NMR_COMInterface_ModelPropertyHandler.cpp
PolygonalSun/lib3mf
66b55847ae76a814da3eb67e1188880ffe149cce
[ "BSD-2-Clause" ]
2
2017-04-18T05:56:37.000Z
2018-06-27T21:52:03.000Z
Source/Model/COM/NMR_COMInterface_ModelPropertyHandler.cpp
PolygonalSun/lib3mf
66b55847ae76a814da3eb67e1188880ffe149cce
[ "BSD-2-Clause" ]
null
null
null
Source/Model/COM/NMR_COMInterface_ModelPropertyHandler.cpp
PolygonalSun/lib3mf
66b55847ae76a814da3eb67e1188880ffe149cce
[ "BSD-2-Clause" ]
null
null
null
/*++ Copyright (C) 2015 netfabb GmbH 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. Abstract: COM Interface Implementation for Model Property Handler --*/ #include "Model/COM/NMR_COMInterface_ModelPropertyHandler.h" #include "Common/NMR_Exception_Windows.h" #include "Common/Platform/NMR_Platform.h" #include "Common/NMR_StringUtils.h" #include "Common/MeshInformation/NMR_MeshInformation_BaseMaterials.h" #include "Common/MeshInformation/NMR_MeshInformation_NodeColors.h" #include "Common/MeshInformation/NMR_MeshInformation_TexCoords.h" #include <cmath> namespace NMR { CCOMModelPropertyHandler::CCOMModelPropertyHandler() { m_nChannel = 0; m_nErrorCode = NMR_SUCCESS; } void CCOMModelPropertyHandler::setMesh(_In_ PModelResource pResource) { m_pModelMeshResource = pResource; } void CCOMModelPropertyHandler::setChannel(_In_ DWORD nChannel) { m_nChannel = nChannel; } _Ret_notnull_ CMesh * CCOMModelPropertyHandler::getMesh() { CMesh * pMesh = nullptr; CModelMeshObject * pMeshObject = dynamic_cast<CModelMeshObject *> (m_pModelMeshResource.get()); if (pMeshObject != nullptr) { pMesh = pMeshObject->getMesh (); } if (pMesh == nullptr) throw CNMRException(NMR_ERROR_INVALIDMESH); return pMesh; } _Ret_notnull_ CModelMeshObject * CCOMModelPropertyHandler::getMeshObject() { CModelMeshObject * pMeshObject = dynamic_cast<CModelMeshObject *> (m_pModelMeshResource.get()); if (pMeshObject == nullptr) throw CNMRException(NMR_ERROR_INVALIDMESH); return pMeshObject; } LIB3MFRESULT CCOMModelPropertyHandler::handleSuccess() { m_nErrorCode = NMR_SUCCESS; return LIB3MF_OK; } LIB3MFRESULT CCOMModelPropertyHandler::handleNMRException(_In_ CNMRException * pException) { __NMRASSERT(pException); m_nErrorCode = pException->getErrorCode(); m_sErrorMessage = std::string(pException->what()); CNMRException_Windows * pWinException = dynamic_cast<CNMRException_Windows *> (pException); if (pWinException != nullptr) { return pWinException->getHResult(); } else { return LIB3MF_FAIL; } } LIB3MFRESULT CCOMModelPropertyHandler::handleGenericException() { m_nErrorCode = NMR_ERROR_GENERICEXCEPTION; m_sErrorMessage = NMR_GENERICEXCEPTIONSTRING; return LIB3MF_FAIL; } LIB3MFMETHODIMP CCOMModelPropertyHandler::GetLastError(_Out_ DWORD * pErrorCode, _Outptr_opt_ LPCSTR * pErrorMessage) { if (!pErrorCode) return LIB3MF_POINTER; *pErrorCode = m_nErrorCode; if (pErrorMessage) { if (m_nErrorCode != NMR_SUCCESS) { *pErrorMessage = m_sErrorMessage.c_str(); } else { *pErrorMessage = nullptr; } } return LIB3MF_OK; } LIB3MFMETHODIMP CCOMModelPropertyHandler::RemoveProperty(_In_ DWORD nIndex) { try { CMesh * pMesh = getMesh(); CMeshInformationHandler * pInfoHandler = pMesh->getMeshInformationHandler(); if (pInfoHandler) { pInfoHandler->resetFaceInformation(nIndex); } return handleSuccess(); } catch (CNMRException & Exception) { return handleNMRException(&Exception); } catch (...) { return handleGenericException(); } } LIB3MFMETHODIMP CCOMModelPropertyHandler::RemoveAllProperties() { try { CMesh * pMesh = getMesh(); pMesh->clearMeshInformationHandler(); return handleSuccess(); } catch (CNMRException & Exception) { return handleNMRException(&Exception); } catch (...) { return handleGenericException(); } } LIB3MFMETHODIMP CCOMModelPropertyHandler::GetPropertyType(_In_ DWORD nIndex, _Out_ eModelPropertyType * pnPropertyType) { try { if (!pnPropertyType) throw CNMRException(NMR_ERROR_INVALIDPOINTER); CMesh * pMesh = getMesh(); *pnPropertyType = MODELPROPERTYTYPE_NONE; CMeshInformationHandler * pInfoHandler = pMesh->getMeshInformationHandler(); if (pInfoHandler) { CMeshInformation * pInformation; pInformation = pInfoHandler->getInformationByType(m_nChannel, emiBaseMaterials); if (pInformation != nullptr) { if (pInformation->faceHasData(nIndex)) *pnPropertyType = MODELPROPERTYTYPE_BASEMATERIALS; } pInformation = pInfoHandler->getInformationByType(m_nChannel, emiNodeColors); if (pInformation != nullptr) { if (pInformation->faceHasData(nIndex)) *pnPropertyType = MODELPROPERTYTYPE_COLOR; } pInformation = pInfoHandler->getInformationByType(m_nChannel, emiTexCoords); if (pInformation != nullptr) { if (pInformation->faceHasData(nIndex)) *pnPropertyType = MODELPROPERTYTYPE_TEXCOORD2D; } pInformation = pInfoHandler->getInformationByType(m_nChannel, emiCompositeMaterials); if (pInformation != nullptr) { if (pInformation->faceHasData(nIndex)) *pnPropertyType = MODELPROPERTYTYPE_COMPOSITE; } } return handleSuccess(); } catch (CNMRException & Exception) { return handleNMRException(&Exception); } catch (...) { return handleGenericException(); } } LIB3MFMETHODIMP CCOMModelPropertyHandler::GetBaseMaterial(_In_ DWORD nIndex, _Out_ DWORD * pnMaterialGroupID, _Out_ DWORD * pnMaterialIndex) { try { if (!pnMaterialGroupID) throw CNMRException(NMR_ERROR_INVALIDPOINTER); if (!pnMaterialIndex) throw CNMRException(NMR_ERROR_INVALIDPOINTER); CMesh * pMesh = getMesh(); *pnMaterialGroupID = 0; *pnMaterialIndex = 0; CMeshInformationHandler * pInfoHandler = pMesh->getMeshInformationHandler(); if (pInfoHandler) { CMeshInformation * pInformation; CMeshInformation_BaseMaterials * pBaseMaterialInformation; pInformation = pInfoHandler->getInformationByType(m_nChannel, emiBaseMaterials); if (pInformation != nullptr) { pBaseMaterialInformation = dynamic_cast<CMeshInformation_BaseMaterials *> (pInformation); if (pBaseMaterialInformation != nullptr) { MESHINFORMATION_BASEMATERIAL * pFaceData = (MESHINFORMATION_BASEMATERIAL *)pBaseMaterialInformation->getFaceData(nIndex); *pnMaterialGroupID = pFaceData->m_nMaterialGroupID; *pnMaterialIndex = pFaceData->m_nMaterialIndex; } } } return handleSuccess(); } catch (CNMRException & Exception) { return handleNMRException(&Exception); } catch (...) { return handleGenericException(); } } LIB3MFMETHODIMP CCOMModelPropertyHandler::GetBaseMaterialArray(_Out_ DWORD * pnMaterialGroupIDs, _Out_ DWORD * pnMaterialIndices) { try { if (!pnMaterialGroupIDs) throw CNMRException(NMR_ERROR_INVALIDPOINTER); if (!pnMaterialIndices) throw CNMRException(NMR_ERROR_INVALIDPOINTER); CMesh * pMesh = getMesh(); DWORD * pnGroupID = pnMaterialGroupIDs; DWORD * pnIndex = pnMaterialIndices; CMeshInformationHandler * pInfoHandler = pMesh->getMeshInformationHandler(); if (pInfoHandler) { CMeshInformation * pInformation; CMeshInformation_BaseMaterials * pBaseMaterialInformation; pInformation = pInfoHandler->getInformationByType(m_nChannel, emiBaseMaterials); if (pInformation != nullptr) { pBaseMaterialInformation = dynamic_cast<CMeshInformation_BaseMaterials *> (pInformation); if (pBaseMaterialInformation != nullptr) { nfUint32 nFaceIndex; nfUint32 nFaceCount = pMesh->getFaceCount(); for (nFaceIndex = 0; nFaceIndex < nFaceCount; nFaceIndex++) { MESHINFORMATION_BASEMATERIAL * pFaceData = (MESHINFORMATION_BASEMATERIAL *)pBaseMaterialInformation->getFaceData(nFaceIndex); *pnGroupID = pFaceData->m_nMaterialGroupID; *pnIndex = pFaceData->m_nMaterialIndex; pnGroupID++; pnIndex++; } } } } return handleSuccess(); } catch (CNMRException & Exception) { return handleNMRException(&Exception); } catch (...) { return handleGenericException(); } } LIB3MFMETHODIMP CCOMModelPropertyHandler::SetBaseMaterial(_In_ DWORD nIndex, _In_ ModelResourceID nMaterialGroupID, _In_ DWORD nMaterialIndex) { try { CMesh * pMesh = getMesh(); CMeshInformationHandler * pInfoHandler = pMesh->createMeshInformationHandler(); if (pInfoHandler) { CMeshInformation * pInformation; CMeshInformation_BaseMaterials * pBaseMaterialInformation; // Remove all other information types pInfoHandler->resetFaceInformation(nIndex); // Get Information type and create new, if not existing pInformation = pInfoHandler->getInformationByType(m_nChannel, emiBaseMaterials); if (pInformation == nullptr) { PMeshInformation pNewInformation = std::make_shared<CMeshInformation_BaseMaterials>(pMesh->getFaceCount()); pInfoHandler->addInformation(pNewInformation); pInformation = pNewInformation.get(); } // Set Face Data pBaseMaterialInformation = dynamic_cast<CMeshInformation_BaseMaterials *> (pInformation); if (pBaseMaterialInformation != nullptr) { MESHINFORMATION_BASEMATERIAL * pFaceData = (MESHINFORMATION_BASEMATERIAL *)pBaseMaterialInformation->getFaceData(nIndex); pFaceData->m_nMaterialGroupID = nMaterialGroupID; pFaceData->m_nMaterialIndex = nMaterialIndex; } } return handleSuccess(); } catch (CNMRException & Exception) { return handleNMRException(&Exception); } catch (...) { return handleGenericException(); } } LIB3MFMETHODIMP CCOMModelPropertyHandler::SetBaseMaterialArray(_In_ ModelResourceID * pnMaterialGroupIDs, _In_ DWORD * pnMaterialIndices) { try { if (!pnMaterialGroupIDs) throw CNMRException(NMR_ERROR_INVALIDPOINTER); if (!pnMaterialIndices) throw CNMRException(NMR_ERROR_INVALIDPOINTER); CMesh * pMesh = getMesh(); CMeshInformationHandler * pInfoHandler = pMesh->createMeshInformationHandler(); if (pInfoHandler) { CMeshInformation * pInformation; CMeshInformation_BaseMaterials * pBaseMaterialInformation; nfUint32 nFaceCount = pMesh->getFaceCount(); // Get Information type and create new, if not existing pInformation = pInfoHandler->getInformationByType(m_nChannel, emiBaseMaterials); if (pInformation == nullptr) { PMeshInformation pNewInformation = std::make_shared<CMeshInformation_BaseMaterials>(nFaceCount); pInfoHandler->addInformation(pNewInformation); pInformation = pNewInformation.get(); } DWORD * pnGroupID = pnMaterialGroupIDs; DWORD * pnIndex = pnMaterialIndices; // Set Face Data pBaseMaterialInformation = dynamic_cast<CMeshInformation_BaseMaterials *> (pInformation); if (pBaseMaterialInformation != nullptr) { nfUint32 nFaceIndex; for (nFaceIndex = 0; nFaceIndex < nFaceCount; nFaceIndex++){ if (*pnGroupID != 0) { pInfoHandler->resetFaceInformation(nFaceIndex); MESHINFORMATION_BASEMATERIAL * pFaceData = (MESHINFORMATION_BASEMATERIAL *)pBaseMaterialInformation->getFaceData(nFaceIndex); pFaceData->m_nMaterialGroupID = *pnGroupID; pFaceData->m_nMaterialIndex = *pnIndex; } pnGroupID++; pnIndex++; } } } return handleSuccess(); } catch (CNMRException & Exception) { return handleNMRException(&Exception); } catch (...) { return handleGenericException(); } } LIB3MFMETHODIMP CCOMModelPropertyHandler::GetColor(_In_ DWORD nIndex, _Out_ MODELMESH_TRIANGLECOLOR_SRGB * pColor) { try { if (!pColor) throw CNMRException(NMR_ERROR_INVALIDPOINTER); CMesh * pMesh = getMesh(); nfInt32 j; for (j = 0; j < 3; j++) { pColor->m_Colors[j].m_Red = 0; pColor->m_Colors[j].m_Green = 0; pColor->m_Colors[j].m_Blue = 0; pColor->m_Colors[j].m_Alpha = 0; } CMeshInformationHandler * pInfoHandler = pMesh->getMeshInformationHandler(); if (pInfoHandler) { CMeshInformation * pInformation; CMeshInformation_NodeColors * pNodeColorInformation; pInformation = pInfoHandler->getInformationByType(m_nChannel, emiNodeColors); if (pInformation != nullptr) { pNodeColorInformation = dynamic_cast<CMeshInformation_NodeColors *> (pInformation); if (pNodeColorInformation != nullptr) { MESHINFORMATION_NODECOLOR * pFaceData = (MESHINFORMATION_NODECOLOR *)pNodeColorInformation->getFaceData(nIndex); for (j = 0; j < 3; j++) { pColor->m_Colors[j].m_Red = pFaceData->m_cColors[j] & 0xff; pColor->m_Colors[j].m_Green = (pFaceData->m_cColors[j] >> 8) & 0xff; pColor->m_Colors[j].m_Blue = (pFaceData->m_cColors[j] >> 16) & 0xff; pColor->m_Colors[j].m_Alpha = (pFaceData->m_cColors[j] >> 24) & 0xff; } } } } return handleSuccess(); } catch (CNMRException & Exception) { return handleNMRException(&Exception); } catch (...) { return handleGenericException(); } } LIB3MFMETHODIMP CCOMModelPropertyHandler::GetColorArray(_Out_ MODELMESH_TRIANGLECOLOR_SRGB * pColors) { try { if (!pColors) throw CNMRException(NMR_ERROR_INVALIDPOINTER); CMesh * pMesh = getMesh(); MODELMESH_TRIANGLECOLOR_SRGB * pnColor = pColors; CMeshInformationHandler * pInfoHandler = pMesh->getMeshInformationHandler(); if (pInfoHandler) { CMeshInformation * pInformation; CMeshInformation_NodeColors * pNodeColorInformation; pInformation = pInfoHandler->getInformationByType(m_nChannel, emiNodeColors); if (pInformation != nullptr) { pNodeColorInformation = dynamic_cast<CMeshInformation_NodeColors *> (pInformation); if (pNodeColorInformation != nullptr) { nfUint32 nFaceIndex; nfUint32 nFaceCount = pMesh->getFaceCount(); for (nFaceIndex = 0; nFaceIndex < nFaceCount; nFaceIndex++) { MESHINFORMATION_NODECOLOR * pFaceData = (MESHINFORMATION_NODECOLOR *)pNodeColorInformation->getFaceData(nFaceIndex); nfInt32 j; for (j = 0; j < 3; j++) { pnColor->m_Colors[j].m_Red = pFaceData->m_cColors[j] & 0xff; pnColor->m_Colors[j].m_Green = (pFaceData->m_cColors[j] >> 8) & 0xff; pnColor->m_Colors[j].m_Blue = (pFaceData->m_cColors[j] >> 16) & 0xff; pnColor->m_Colors[j].m_Alpha = (pFaceData->m_cColors[j] >> 24) & 0xff; } pnColor++; } } } } return handleSuccess(); } catch (CNMRException & Exception) { return handleNMRException(&Exception); } catch (...) { return handleGenericException(); } } LIB3MFMETHODIMP CCOMModelPropertyHandler::SetSingleColor(_In_ DWORD nIndex, _Out_ MODELMESHCOLOR_SRGB * pColor) { try { if (!pColor) throw CNMRException(NMR_ERROR_INVALIDPOINTER); CMesh * pMesh = getMesh(); CMeshInformationHandler * pInfoHandler = pMesh->createMeshInformationHandler(); if (pInfoHandler) { CMeshInformation * pInformation; CMeshInformation_NodeColors * pNodeColorInformation; // Remove all other information types pInfoHandler->resetFaceInformation(nIndex); // Get Information type and create new, if not existing pInformation = pInfoHandler->getInformationByType(m_nChannel, emiNodeColors); if (pInformation == nullptr) { PMeshInformation pNewInformation = std::make_shared<CMeshInformation_NodeColors>(pMesh->getFaceCount()); pInfoHandler->addInformation(pNewInformation); pInformation = pNewInformation.get(); } // Set Face Data pNodeColorInformation = dynamic_cast<CMeshInformation_NodeColors *> (pInformation); if (pNodeColorInformation != nullptr) { MESHINFORMATION_NODECOLOR * pFaceData = (MESHINFORMATION_NODECOLOR *)pNodeColorInformation->getFaceData(nIndex); nfInt32 j; for (j = 0; j < 3; j++) { nfUint32 nRed = pColor->m_Red; nfUint32 nBlue = pColor->m_Blue; nfUint32 nGreen = pColor->m_Green; nfUint32 nAlpha = pColor->m_Alpha; pFaceData->m_cColors[j] = nRed | (nGreen << 8) | (nBlue << 16) | (nAlpha << 24); } } } return handleSuccess(); } catch (CNMRException & Exception) { return handleNMRException(&Exception); } catch (...) { return handleGenericException(); } } LIB3MFMETHODIMP CCOMModelPropertyHandler::SetSingleColorRGB(_In_ DWORD nIndex, _In_ BYTE bRed, _In_ BYTE bGreen, _In_ BYTE bBlue) { MODELMESHCOLOR_SRGB Color; Color.m_Red = bRed; Color.m_Green = bGreen; Color.m_Blue = bBlue; Color.m_Alpha = 255; return SetSingleColor(nIndex, &Color); } LIB3MFMETHODIMP CCOMModelPropertyHandler::SetSingleColorRGBA(_In_ DWORD nIndex, _In_ BYTE bRed, _In_ BYTE bGreen, _In_ BYTE bBlue, _In_ BYTE bAlpha) { MODELMESHCOLOR_SRGB Color; Color.m_Red = bRed; Color.m_Green = bGreen; Color.m_Blue = bBlue; Color.m_Alpha = bAlpha; return SetSingleColor(nIndex, &Color); } LIB3MFMETHODIMP CCOMModelPropertyHandler::SetSingleColorFloatRGB(_In_ DWORD nIndex, _In_ FLOAT fRed, _In_ FLOAT fGreen, _In_ FLOAT fBlue) { try { MODELMESHCOLOR_SRGB Color; nfInt32 nRed = (nfInt32) round(fRed * 255.0f); nfInt32 nGreen = (nfInt32)round(fGreen * 255.0f); nfInt32 nBlue = (nfInt32)round(fBlue * 255.0f); if ((nRed < 0) || (nRed > 255)) throw CNMRException(NMR_ERROR_INVALIDPARAM); if ((nGreen < 0) || (nGreen > 255)) throw CNMRException(NMR_ERROR_INVALIDPARAM); if ((nBlue < 0) || (nBlue > 255)) throw CNMRException(NMR_ERROR_INVALIDPARAM); Color.m_Red = nRed; Color.m_Green = nGreen; Color.m_Blue = nBlue; Color.m_Alpha = 255; return SetSingleColor(nIndex, &Color); } catch (CNMRException & Exception) { return handleNMRException(&Exception); } catch (...) { return handleGenericException(); } } LIB3MFMETHODIMP CCOMModelPropertyHandler::SetSingleColorFloatRGBA(_In_ DWORD nIndex, _In_ FLOAT fRed, _In_ FLOAT fGreen, _In_ FLOAT fBlue, _In_ FLOAT fAlpha) { try { MODELMESHCOLOR_SRGB Color; nfInt32 nRed = (nfInt32)round(fRed * 255.0f); nfInt32 nGreen = (nfInt32)round(fGreen * 255.0f); nfInt32 nBlue = (nfInt32)round(fBlue * 255.0f); nfInt32 nAlpha = (nfInt32)round(fAlpha * 255.0f); if ((nRed < 0) || (nRed > 255)) throw CNMRException(NMR_ERROR_INVALIDPARAM); if ((nGreen < 0) || (nGreen > 255)) throw CNMRException(NMR_ERROR_INVALIDPARAM); if ((nBlue < 0) || (nBlue > 255)) throw CNMRException(NMR_ERROR_INVALIDPARAM); if ((nAlpha < 0) || (nAlpha > 255)) throw CNMRException(NMR_ERROR_INVALIDPARAM); Color.m_Red = nRed; Color.m_Green = nGreen; Color.m_Blue = nBlue; Color.m_Alpha = nAlpha; return SetSingleColor(nIndex, &Color); } catch (CNMRException & Exception) { return handleNMRException(&Exception); } catch (...) { return handleGenericException(); } } LIB3MFMETHODIMP CCOMModelPropertyHandler::SetSingleColorArray(_Out_ MODELMESHCOLOR_SRGB * pColors) { try { if (!pColors) throw CNMRException(NMR_ERROR_INVALIDPOINTER); CMesh * pMesh = getMesh(); CMeshInformationHandler * pInfoHandler = pMesh->createMeshInformationHandler(); if (pInfoHandler) { CMeshInformation * pInformation; CMeshInformation_NodeColors * pNodeColorInformation; nfUint32 nFaceCount = pMesh->getFaceCount(); // Get Information type and create new, if not existing pInformation = pInfoHandler->getInformationByType(m_nChannel, emiNodeColors); if (pInformation == nullptr) { PMeshInformation pNewInformation = std::make_shared<CMeshInformation_NodeColors>(nFaceCount); pInfoHandler->addInformation(pNewInformation); pInformation = pNewInformation.get(); } MODELMESHCOLOR_SRGB * pnColor = pColors; // Set Face Data pNodeColorInformation = dynamic_cast<CMeshInformation_NodeColors *> (pInformation); if (pNodeColorInformation != nullptr) { nfUint32 nFaceIndex; for (nFaceIndex = 0; nFaceIndex < nFaceCount; nFaceIndex++){ if ((pnColor->m_Red != 0) || (pnColor->m_Green != 0) || (pnColor->m_Blue != 0) || (pnColor->m_Alpha != 0)) { pInfoHandler->resetFaceInformation(nFaceIndex); MESHINFORMATION_NODECOLOR * pFaceData = (MESHINFORMATION_NODECOLOR *)pNodeColorInformation->getFaceData(nFaceIndex); nfInt32 j; for (j = 0; j < 3; j++) { nfUint32 nRed = pnColor->m_Red; nfUint32 nBlue = pnColor->m_Blue; nfUint32 nGreen = pnColor->m_Green; nfUint32 nAlpha = pnColor->m_Alpha; pFaceData->m_cColors[j] = nRed | (nGreen << 8) | (nBlue << 16) | (nAlpha << 24); } } pnColor++; } } } return handleSuccess(); } catch (CNMRException & Exception) { return handleNMRException(&Exception); } catch (...) { return handleGenericException(); } } LIB3MFMETHODIMP CCOMModelPropertyHandler::SetGradientColor(_In_ DWORD nIndex, _Out_ MODELMESH_TRIANGLECOLOR_SRGB * pColor) { try { if (!pColor) throw CNMRException(NMR_ERROR_INVALIDPOINTER); CMesh * pMesh = getMesh(); CMeshInformationHandler * pInfoHandler = pMesh->createMeshInformationHandler(); if (pInfoHandler) { CMeshInformation * pInformation; CMeshInformation_NodeColors * pNodeColorInformation; // Remove all other information types pInfoHandler->resetFaceInformation(nIndex); // Get Information type and create new, if not existing pInformation = pInfoHandler->getInformationByType(m_nChannel, emiNodeColors); if (pInformation == nullptr) { PMeshInformation pNewInformation = std::make_shared<CMeshInformation_NodeColors>(pMesh->getFaceCount()); pInfoHandler->addInformation(pNewInformation); pInformation = pNewInformation.get(); } // Set Face Data pNodeColorInformation = dynamic_cast<CMeshInformation_NodeColors *> (pInformation); if (pNodeColorInformation != nullptr) { MESHINFORMATION_NODECOLOR * pFaceData = (MESHINFORMATION_NODECOLOR *)pNodeColorInformation->getFaceData(nIndex); nfInt32 j; for (j = 0; j < 3; j++) { nfUint32 nRed = pColor->m_Colors[j].m_Red; nfUint32 nBlue = pColor->m_Colors[j].m_Blue; nfUint32 nGreen = pColor->m_Colors[j].m_Green; nfUint32 nAlpha = pColor->m_Colors[j].m_Alpha; pFaceData->m_cColors[j] = nRed | (nGreen << 8) | (nBlue << 16) | (nAlpha << 24); } } } return handleSuccess(); } catch (CNMRException & Exception) { return handleNMRException(&Exception); } catch (...) { return handleGenericException(); } } LIB3MFMETHODIMP CCOMModelPropertyHandler::SetGradientColorArray(_Out_ MODELMESH_TRIANGLECOLOR_SRGB * pColors) { try { if (!pColors) throw CNMRException(NMR_ERROR_INVALIDPOINTER); CMesh * pMesh = getMesh(); CMeshInformationHandler * pInfoHandler = pMesh->createMeshInformationHandler(); if (pInfoHandler) { CMeshInformation * pInformation; CMeshInformation_NodeColors * pNodeColorInformation; nfUint32 nFaceCount = pMesh->getFaceCount(); // Get Information type and create new, if not existing pInformation = pInfoHandler->getInformationByType(m_nChannel, emiNodeColors); if (pInformation == nullptr) { PMeshInformation pNewInformation = std::make_shared<CMeshInformation_NodeColors>(nFaceCount); pInfoHandler->addInformation(pNewInformation); pInformation = pNewInformation.get(); } MODELMESH_TRIANGLECOLOR_SRGB * pnColor = pColors; // Set Face Data pNodeColorInformation = dynamic_cast<CMeshInformation_NodeColors *> (pInformation); if (pNodeColorInformation != nullptr) { nfUint32 nFaceIndex; for (nFaceIndex = 0; nFaceIndex < nFaceCount; nFaceIndex++){ if ((pnColor->m_Colors[0].m_Red != 0) || (pnColor->m_Colors[0].m_Green != 0) || (pnColor->m_Colors[0].m_Blue != 0) || (pnColor->m_Colors[0].m_Alpha != 0) || (pnColor->m_Colors[1].m_Red != 0) || (pnColor->m_Colors[1].m_Green != 0) || (pnColor->m_Colors[1].m_Blue != 0) || (pnColor->m_Colors[1].m_Alpha != 0) || (pnColor->m_Colors[2].m_Red != 0) || (pnColor->m_Colors[2].m_Green != 0) || (pnColor->m_Colors[2].m_Blue != 0) || (pnColor->m_Colors[2].m_Alpha != 0) || (pnColor->m_Colors[3].m_Red != 0) || (pnColor->m_Colors[3].m_Green != 0) || (pnColor->m_Colors[3].m_Blue != 0) || (pnColor->m_Colors[3].m_Alpha != 0)) { pInfoHandler->resetFaceInformation(nFaceIndex); MESHINFORMATION_NODECOLOR * pFaceData = (MESHINFORMATION_NODECOLOR *)pNodeColorInformation->getFaceData(nFaceIndex); nfInt32 j; for (j = 0; j < 3; j++) { nfUint32 nRed = pnColor->m_Colors[j].m_Red; nfUint32 nBlue = pnColor->m_Colors[j].m_Blue; nfUint32 nGreen = pnColor->m_Colors[j].m_Green; nfUint32 nAlpha = pnColor->m_Colors[j].m_Alpha; pFaceData->m_cColors[j] = nRed | (nGreen << 8) | (nBlue << 16) | (nAlpha << 24); } } pnColor++; } } } return handleSuccess(); } catch (CNMRException & Exception) { return handleNMRException(&Exception); } catch (...) { return handleGenericException(); } } LIB3MFMETHODIMP CCOMModelPropertyHandler::GetTexture(_In_ DWORD nIndex, _Out_ MODELMESHTEXTURE2D * pTexture) { try { if (!pTexture) throw CNMRException(NMR_ERROR_INVALIDPOINTER); CMesh * pMesh = getMesh(); nfInt32 j; for (j = 0; j < 3; j++) { pTexture->m_fU[j] = 0.0f; pTexture->m_fV[j] = 0.0f; } pTexture->m_nTextureID = 0; CMeshInformationHandler * pInfoHandler = pMesh->getMeshInformationHandler(); if (pInfoHandler) { CMeshInformation * pInformation; CMeshInformation_TexCoords * pTexCoordsInformation; pInformation = pInfoHandler->getInformationByType(m_nChannel, emiTexCoords); if (pInformation != nullptr) { pTexCoordsInformation = dynamic_cast<CMeshInformation_TexCoords *> (pInformation); if (pTexCoordsInformation != nullptr) { MESHINFORMATION_TEXCOORDS * pFaceData = (MESHINFORMATION_TEXCOORDS *)pTexCoordsInformation->getFaceData(nIndex); for (j = 0; j < 3; j++) { pTexture->m_fU[j] = pFaceData->m_vCoords[j].m_fields[0]; pTexture->m_fV[j] = pFaceData->m_vCoords[j].m_fields[1]; } pTexture->m_nTextureID = pFaceData->m_TextureID; } } } return handleSuccess(); } catch (CNMRException & Exception) { return handleNMRException(&Exception); } catch (...) { return handleGenericException(); } } LIB3MFMETHODIMP CCOMModelPropertyHandler::GetTextureArray(_Out_ MODELMESHTEXTURE2D * pTextures) { try { if (!pTextures) throw CNMRException(NMR_ERROR_INVALIDPOINTER); CMesh * pMesh = getMesh(); MODELMESHTEXTURE2D * pnTexture = pTextures; CMeshInformationHandler * pInfoHandler = pMesh->getMeshInformationHandler(); if (pInfoHandler) { CMeshInformation * pInformation; CMeshInformation_TexCoords * pTexCoordInformation; pInformation = pInfoHandler->getInformationByType(m_nChannel, emiTexCoords); if (pInformation != nullptr) { pTexCoordInformation = dynamic_cast<CMeshInformation_TexCoords *> (pInformation); if (pTexCoordInformation != nullptr) { nfUint32 nFaceIndex; nfUint32 nFaceCount = pMesh->getFaceCount(); for (nFaceIndex = 0; nFaceIndex < nFaceCount; nFaceIndex++) { MESHINFORMATION_TEXCOORDS * pFaceData = (MESHINFORMATION_TEXCOORDS *)pTexCoordInformation->getFaceData(nFaceIndex); nfInt32 j; for (j = 0; j < 3; j++) { pnTexture->m_fU[j] = pFaceData->m_vCoords[j].m_fields[0]; pnTexture->m_fV[j] = pFaceData->m_vCoords[j].m_fields[1]; } pnTexture->m_nTextureID = pFaceData->m_TextureID; pnTexture++; } } } } return handleSuccess(); } catch (CNMRException & Exception) { return handleNMRException(&Exception); } catch (...) { return handleGenericException(); } } LIB3MFMETHODIMP CCOMModelPropertyHandler::SetTexture(_In_ DWORD nIndex, _In_ MODELMESHTEXTURE2D * pTexture) { try { if (!pTexture) throw CNMRException(NMR_ERROR_INVALIDPOINTER); CMesh * pMesh = getMesh(); CMeshInformationHandler * pInfoHandler = pMesh->createMeshInformationHandler(); if (pInfoHandler) { CMeshInformation * pInformation; CMeshInformation_TexCoords * pTexCoordInformation; // Remove all other information types pInfoHandler->resetFaceInformation(nIndex); // Get Information type and create new, if not existing pInformation = pInfoHandler->getInformationByType(m_nChannel, emiTexCoords); if (pInformation == nullptr) { PMeshInformation pNewInformation = std::make_shared<CMeshInformation_TexCoords>(pMesh->getFaceCount()); pInfoHandler->addInformation(pNewInformation); pInformation = pNewInformation.get(); } // Set Face Data pTexCoordInformation = dynamic_cast<CMeshInformation_TexCoords *> (pInformation); if (pTexCoordInformation != nullptr) { MESHINFORMATION_TEXCOORDS * pFaceData = (MESHINFORMATION_TEXCOORDS *)pTexCoordInformation->getFaceData(nIndex); nfInt32 j; for (j = 0; j < 3; j++) { pFaceData->m_vCoords[j].m_fields[0] = pTexture->m_fU[j]; pFaceData->m_vCoords[j].m_fields[1] = pTexture->m_fV[j]; } pFaceData->m_TextureID = pTexture->m_nTextureID; } } return handleSuccess(); } catch (CNMRException & Exception) { return handleNMRException(&Exception); } catch (...) { return handleGenericException(); } } LIB3MFMETHODIMP CCOMModelPropertyHandler::SetTextureArray(_In_ MODELMESHTEXTURE2D * pTextures) { try { if (!pTextures) throw CNMRException(NMR_ERROR_INVALIDPOINTER); CMesh * pMesh = getMesh(); CMeshInformationHandler * pInfoHandler = pMesh->createMeshInformationHandler(); if (pInfoHandler) { CMeshInformation * pInformation; CMeshInformation_TexCoords * pTexCoordInformation; nfUint32 nFaceCount = pMesh->getFaceCount(); // Get Information type and create new, if not existing pInformation = pInfoHandler->getInformationByType(m_nChannel, emiTexCoords); if (pInformation == nullptr) { PMeshInformation pNewInformation = std::make_shared<CMeshInformation_TexCoords>(nFaceCount); pInfoHandler->addInformation(pNewInformation); pInformation = pNewInformation.get(); } MODELMESHTEXTURE2D * pnTexture = pTextures; // Set Face Data pTexCoordInformation = dynamic_cast<CMeshInformation_TexCoords *> (pInformation); if (pTexCoordInformation != nullptr) { nfUint32 nFaceIndex; for (nFaceIndex = 0; nFaceIndex < nFaceCount; nFaceIndex++){ if (pnTexture->m_nTextureID != 0) { pInfoHandler->resetFaceInformation(nFaceIndex); MESHINFORMATION_TEXCOORDS * pFaceData = (MESHINFORMATION_TEXCOORDS *)pTexCoordInformation->getFaceData(nFaceIndex); nfInt32 j; for (j = 0; j < 3; j++) { pFaceData->m_vCoords[j].m_fields[0] = pnTexture->m_fU[j]; pFaceData->m_vCoords[j].m_fields[1] = pnTexture->m_fV[j]; } pFaceData->m_TextureID = pnTexture->m_nTextureID; } pnTexture++; } } } return handleSuccess(); } catch (CNMRException & Exception) { return handleNMRException(&Exception); } catch (...) { return handleGenericException(); } } }
30.97971
162
0.70983
PolygonalSun
61765f8517b4c84f4ba5548fd30f0175f1bb2efa
17,937
cpp
C++
libnd4j/include/ops/declarable/impl/LegacyRandomOp.cpp
nutonchain/Deeplearning
20f222c1eff95205c6c9c9b666b04402405e4442
[ "Apache-2.0" ]
2
2018-11-26T15:30:37.000Z
2018-11-26T15:30:39.000Z
libnd4j/include/ops/declarable/impl/LegacyRandomOp.cpp
nutonchain/Deeplearning
20f222c1eff95205c6c9c9b666b04402405e4442
[ "Apache-2.0" ]
16
2018-12-03T11:37:19.000Z
2018-12-03T19:47:25.000Z
libnd4j/include/ops/declarable/impl/LegacyRandomOp.cpp
nutonchain/Deeplearning
20f222c1eff95205c6c9c9b666b04402405e4442
[ "Apache-2.0" ]
2
2021-03-01T07:46:24.000Z
2021-09-26T17:08:40.000Z
/******************************************************************************* * Copyright (c) 2015-2018 Skymind, Inc. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://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. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ // // Created by raver119 on 16.10.2017. // #include <ops/declarable/LegacyRandomOp.h> #include <helpers/RandomLauncher.h> #include <NativeOpExcutioner.h> namespace nd4j { namespace ops { template <typename T> LegacyRandomOp<T>::LegacyRandomOp() : LegacyOp<T>::LegacyOp(1) { // just a no-op } template <typename T> LegacyRandomOp<T>::LegacyRandomOp(int opNum) : LegacyOp<T>::LegacyOp(1, opNum) { // just a no-op } template <typename T> LegacyOp<T>* LegacyRandomOp<T>::clone() { return new LegacyRandomOp(this->_opNum); } template <typename T> Nd4jStatus LegacyRandomOp<T>::validateAndExecute(Context<T> &block) { REQUIRE_TRUE(block.getRNG() != nullptr, 0, "RNG should be provided for LegacyRandomOp, but got NULL instead at node_%i", block.nodeId()) auto input = INPUT_VARIABLE(0); int opNum = block.opNum() < 0 ? this->_opNum : block.opNum(); /* (0, randomOps::UniformDistribution) ,\ (1, randomOps::DropOut) ,\ (2, randomOps::DropOutInverted) ,\ (3, randomOps::ProbablisticMerge) ,\ (4, randomOps::Linspace) ,\ (5, randomOps::Choice) ,\ (6, randomOps::GaussianDistribution) ,\ (7, randomOps::BernoulliDistribution) ,\ (8, randomOps::BinomialDistribution),\ (9, randomOps::BinomialDistributionEx),\ (10, randomOps::LogNormalDistribution) ,\ (11, randomOps::TruncatedNormalDistribution) ,\ (12, randomOps::AlphaDropOut) */ switch(opNum) { case 0: { // uniform distribution T from, to; if (block.width() > 2) { auto arg1 = INPUT_VARIABLE(1); auto arg2 = INPUT_VARIABLE(2); REQUIRE_TRUE(arg1->isScalar(), 0, "Uniform: Second argument must be scalar"); REQUIRE_TRUE(arg2->isScalar(), 0, "Uniform: Third argument must be scalar"); from = arg1->getScalar(0); to = arg2->getScalar(0); } else if (block.getTArguments()->size() == 2) { from = T_ARG(0); to = T_ARG(1); } else { REQUIRE_TRUE(false, 0, "Uniform requires either TArgs or 3 arguments to be present"); } REQUIRE_TRUE(input->isVector(), 0, "Uniform requires pure shape as first argument"); std::vector<Nd4jLong> shape(input->lengthOf()); for (int e = 0; e < input->lengthOf(); e++) shape[e] = (Nd4jLong) input->getScalar(e); auto z = new NDArray<T>('c', shape, block.getWorkspace()); RandomLauncher<T>::fillUniform(block.getRNG(), z, from, to); OVERWRITE_RESULT(z); } break; case 1: { auto z = OUTPUT_VARIABLE(0); T prob; if (block.width() > 1) { auto arg = INPUT_VARIABLE(1); REQUIRE_TRUE(arg->isScalar(), 0, "DropOut: Second argument must be scalar"); prob = arg->getScalar(0); } else if (block.getTArguments()->size() > 0) { prob = T_ARG(0); } else { REQUIRE_TRUE(false, 0, "DropOut requires either TArgs or second argument to be present"); } if (!block.isInplace()) z->assign(input); RandomLauncher<T>::applyDropOut(block.getRNG(), z, prob); } break; case 2: { auto z = OUTPUT_VARIABLE(0); T prob; if (block.width() > 1) { auto arg = INPUT_VARIABLE(1); REQUIRE_TRUE(arg->isScalar(), 0, "InvertedDropOut: Second argument must be scalar"); prob = arg->getScalar(0); } else if (block.getTArguments()->size() == 1) { prob = T_ARG(0); } else { REQUIRE_TRUE(false, 0, "InvertedDropOut requires either TArgs or second argument to be present"); } if (!block.isInplace()) z->assign(input); RandomLauncher<T>::applyInvertedDropOut(block.getRNG(), z, prob); } break; case 6: { // gaussian distribution T mean, stdev; if (block.width() > 2) { auto arg1 = INPUT_VARIABLE(1); auto arg2 = INPUT_VARIABLE(2); REQUIRE_TRUE(arg1->isScalar(), 0, "Gaussian: Second argument must be scalar"); REQUIRE_TRUE(arg2->isScalar(), 0, "Gaussian: Third argument must be scalar"); mean = arg1->getScalar(0); stdev = arg2->getScalar(0); } else if (block.getTArguments()->size() == 2) { mean = T_ARG(0); stdev = T_ARG(1); } else { REQUIRE_TRUE(false, 0, "Gaussian requires either TArgs or 3 arguments to be present"); } REQUIRE_TRUE(input->isVector(), 0, "Gaussian requires pure shape as first argument"); std::vector<Nd4jLong> shape(input->lengthOf()); for (int e = 0; e < input->lengthOf(); e++) shape[e] = (Nd4jLong) input->getScalar(e); auto z = new NDArray<T>('c', shape, block.getWorkspace()); RandomLauncher<T>::fillGaussian(block.getRNG(), z, mean, stdev); OVERWRITE_RESULT(z); } break; case 7: { // bernoulli distribution T prob; if (block.width() > 1) { auto arg1 = INPUT_VARIABLE(1); REQUIRE_TRUE(arg1->isScalar(), 0, "Bernoulli: Second argument must be scalar"); prob = arg1->getScalar(0); } else if (block.getTArguments()->size() > 0) { prob = T_ARG(0); } else { REQUIRE_TRUE(false, 0, "Bernoulli requires either 1 TArg or 2 arguments to be present"); } REQUIRE_TRUE(input->isVector(), 0, "Bernoulli requires pure shape as first argument"); std::vector<Nd4jLong> shape(input->lengthOf()); for (int e = 0; e < input->lengthOf(); e++) shape[e] = (Nd4jLong) input->getScalar(e); auto z = new NDArray<T>('c', shape, block.getWorkspace()); RandomLauncher<T>::fillBernoulli(block.getRNG(), z, prob); OVERWRITE_RESULT(z); } break; case 9: { // BinomialEx distribution T prob; int trials; if (block.width() > 2) { auto arg1 = INPUT_VARIABLE(1); auto arg2 = INPUT_VARIABLE(2); REQUIRE_TRUE(arg1->isScalar(), 0, "Binomial: Second argument must be scalar"); REQUIRE_TRUE(arg2->isScalar(), 0, "Binomial: Third argument must be scalar"); trials = (int) arg1->getScalar(0); prob = arg2->getScalar(0); } else if (block.getTArguments()->size() == 1 && block.getIArguments()->size() == 1) { trials = INT_ARG(0); prob = T_ARG(0); } else { REQUIRE_TRUE(false, 0, "Binomial requires either TArgs/IArgs or 3 arguments to be present"); } REQUIRE_TRUE(input->isVector(), 0, "Binomial requires pure shape as first argument"); std::vector<Nd4jLong> shape(input->lengthOf()); for (int e = 0; e < input->lengthOf(); e++) shape[e] = (Nd4jLong) input->getScalar(e); auto z = new NDArray<T>('c', shape, block.getWorkspace()); RandomLauncher<T>::fillBinomial(block.getRNG(), z, trials, prob); OVERWRITE_RESULT(z); } break; case 10: { // lognorm distribution T mean, stdev; if (block.width() > 2) { auto arg1 = INPUT_VARIABLE(1); auto arg2 = INPUT_VARIABLE(2); REQUIRE_TRUE(arg1->isScalar(), 0, "LogNormal: Second argument must be scalar"); REQUIRE_TRUE(arg2->isScalar(), 0, "LogNormal: Third argument must be scalar"); mean = arg1->getScalar(0); stdev = arg2->getScalar(0); } else if (block.getTArguments()->size() == 2) { mean = T_ARG(0); stdev = T_ARG(1); } else { REQUIRE_TRUE(false, 0, "LogNormal requires either TArgs or 3 arguments to be present"); } REQUIRE_TRUE(input->isVector(), 0, "LogNormal requires pure shape as first argument"); std::vector<Nd4jLong> shape(input->lengthOf()); for (int e = 0; e < input->lengthOf(); e++) shape[e] = (Nd4jLong) input->getScalar(e); auto z = new NDArray<T>('c', shape, block.getWorkspace()); RandomLauncher<T>::fillLogNormal(block.getRNG(), z, mean, stdev); OVERWRITE_RESULT(z); } break; case 11: { // truncated norm distribution T mean, stdev; if (block.width() > 2) { auto arg1 = INPUT_VARIABLE(1); auto arg2 = INPUT_VARIABLE(2); REQUIRE_TRUE(arg1->isScalar(), 0, "TruncatedNormal: Second argument must be scalar"); REQUIRE_TRUE(arg2->isScalar(), 0, "TruncatedNormal: Third argument must be scalar"); mean = arg1->getScalar(0); stdev = arg2->getScalar(0); } else if (block.getTArguments()->size() == 2) { mean = T_ARG(0); stdev = T_ARG(1); } else { REQUIRE_TRUE(false, 0, "TruncatedNormal requires either TArgs or 3 arguments to be present"); } REQUIRE_TRUE(input->isVector(), 0, "TruncatedNormal requires pure shape as first argument"); std::vector<Nd4jLong> shape(input->lengthOf()); for (int e = 0; e < input->lengthOf(); e++) shape[e] = (Nd4jLong) input->getScalar(e); auto z = new NDArray<T>('c', shape, block.getWorkspace()); RandomLauncher<T>::fillTruncatedNormal(block.getRNG(), z, mean, stdev); OVERWRITE_RESULT(z); } break; case 12: { auto z = OUTPUT_VARIABLE(0); T prob, a, b, pa; if (block.width() > 4) { auto arg1 = INPUT_VARIABLE(1); auto arg2 = INPUT_VARIABLE(2); auto arg3 = INPUT_VARIABLE(3); auto arg4 = INPUT_VARIABLE(4); REQUIRE_TRUE(arg1->isScalar(), 0, "AlphaDropOut: Second argument must be scalar"); REQUIRE_TRUE(arg2->isScalar(), 0, "AlphaDropOut: Third argument must be scalar"); REQUIRE_TRUE(arg3->isScalar(), 0, "AlphaDropOut: Fourth argument must be scalar"); REQUIRE_TRUE(arg4->isScalar(), 0, "AlphaDropOut: Fifth argument must be scalar"); prob = arg1->getScalar(0); a = arg2->getScalar(0); b = arg3->getScalar(0); pa = arg4->getScalar(0); } else if (block.getTArguments()->size() == 4) { prob = T_ARG(0); a = T_ARG(1); b = T_ARG(2); pa = T_ARG(3); } else { REQUIRE_TRUE(false, 0, "AlphaDropOut requires either TArgs or 5 arguments to be present"); } if (!block.isInplace()) z->assign(input); RandomLauncher<T>::applyAlphaDropOut(block.getRNG(), z, prob, a, b, pa); } break; default: { nd4j_printf("Unknown random op requested: [%i]\n", opNum); return ND4J_STATUS_KERNEL_FAILURE; } } return ND4J_STATUS_OK; } /** * For transform operations, output shape always equals to input shape. With just a few exclusions, like im2col and col2im. * But these ops already have CustomOp implementations. * */ template <typename T> ShapeList *LegacyRandomOp<T>::calculateOutputShape(ShapeList *inputShape, nd4j::graph::Context<T> &block) { auto inShape = inputShape->at(0); Nd4jLong *newShape; COPY_SHAPE(inShape, newShape); return SHAPELIST(newShape); } template <typename T> Nd4jStatus LegacyRandomOp<T>::execute(Context<T>* block) { return DeclarableOp<T>::execute(block); } template <typename T> nd4j::ResultSet<T>* LegacyRandomOp<T>::execute(nd4j::random::RandomBuffer* rng, std::initializer_list<NDArray<T>*> inputs, std::initializer_list<T> tArgs, std::initializer_list<int> iArgs, bool isInplace) { std::vector<NDArray<T>*> ins(inputs); std::vector<T> tas(tArgs); std::vector<int> ias(iArgs); return this->execute(rng, ins, tas, ias, isInplace); } template <typename T> nd4j::ResultSet<T>* LegacyRandomOp<T>::execute(nd4j::random::RandomBuffer* rng, std::vector<NDArray<T>*>& inputs, std::vector<T>& tArgs, std::vector<int>& iArgs, bool isInplace) { VariableSpace<T> variableSpace; auto arrayList = new ResultSet<T>(); //ResultSet<T> arrayList; if (isInplace) arrayList->setNonRemovable(); int cnt = -1; std::vector<int> in; for (auto v: inputs) { if (v == nullptr) continue; auto var = new Variable<T>(v); var->markRemovable(false); in.push_back(cnt); variableSpace.putVariable(cnt--, var); } Context<T> block(1, &variableSpace, false); block.setRNG(rng); block.fillInputs(in); block.markInplace(isInplace); for (int e = 0; e < tArgs.size(); e++) block.getTArguments()->emplace_back(tArgs.at(e)); for (int e = 0; e < iArgs.size(); e++) block.getIArguments()->emplace_back(iArgs.at(e)); Nd4jStatus status = this->execute(&block); arrayList->setStatus(status); if (status != ND4J_STATUS_OK) return arrayList; for (int e = 0; e < 65536; e++) { std::pair<int,int> pair(1, e); if (variableSpace.hasVariable(pair)) { auto var = variableSpace.getVariable(pair); auto arr = var->getNDArray(); if (!arr->isAttached()) { var->markRemovable(false); arrayList->push_back(arr); } else { arrayList->push_back(arr->detach()); } } else break; } return arrayList; } template class ND4J_EXPORT LegacyRandomOp<float>; template class ND4J_EXPORT LegacyRandomOp<double>; template class ND4J_EXPORT LegacyRandomOp<float16>; } }
42.504739
215
0.467971
nutonchain
6179ae37de75c21d7022dee345ed5a43f3aa7c81
1,111
hpp
C++
bst.hpp
rxnew/bst
0edbf3719db378398a7827a518cc1e9d7b7a7b23
[ "MIT" ]
null
null
null
bst.hpp
rxnew/bst
0edbf3719db378398a7827a518cc1e9d7b7a7b23
[ "MIT" ]
null
null
null
bst.hpp
rxnew/bst
0edbf3719db378398a7827a518cc1e9d7b7a7b23
[ "MIT" ]
null
null
null
#pragma once #include <memory> #include <iostream> namespace bst { template <class T> class Tree { public: Tree(); Tree(std::initializer_list<T> list); template <template <class...> class Container> explicit Tree(const Container<T>& vals); Tree(const Tree& other); Tree(Tree&&) noexcept = default; ~Tree() = default; auto operator=(const Tree& other) -> Tree&; auto operator=(Tree&&) noexcept -> Tree& = default; auto operator=(std::initializer_list<T> list) -> Tree&; auto operator==(const Tree& other) const -> bool; auto operator!=(const Tree& other) const -> bool; auto size() const -> size_t; auto empty() const -> bool; auto exists(const T& val) const -> bool; template <class U> auto insert(U&& val) -> void; auto insert(std::initializer_list<T> list) -> void; template <template <class...> class Container> auto insert(const Container<T>& vals) -> void; auto remove(const T& val) -> void; auto clear() -> void; auto print(std::ostream& os = std::cout) const -> void; private: class Impl; std::unique_ptr<Impl> impl; }; } #include "bst_impl.hpp"
25.837209
57
0.661566
rxnew
617dfca3d69cf833fca2c3e8e06e97d787a0e937
1,786
cpp
C++
nnapi/neuralnetworks/1.2/ABurstCallback.cpp
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
4
2020-07-24T06:54:16.000Z
2021-06-16T17:13:53.000Z
nnapi/neuralnetworks/1.2/ABurstCallback.cpp
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
1
2021-04-02T17:35:07.000Z
2021-04-02T17:35:07.000Z
nnapi/neuralnetworks/1.2/ABurstCallback.cpp
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
1
2020-11-04T22:31:45.000Z
2020-11-04T22:31:45.000Z
// Copyright 2020 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This is the boilerplate implementation of the IAllocator HAL interface, // generated by the hidl-gen tool and then modified for use on Chrome OS. // Modifications include: // - Removal of non boiler plate client and server related code. // - Reformatting to meet the Chrome OS coding standards. // // Originally generated with the command: // $ hidl-gen -o output -L c++-adapter -r android.hardware:hardware/interfaces \ // android.hardware.neuralnetworks@1.2 #include <android/hardware/neuralnetworks/1.2/ABurstCallback.h> #include <android/hardware/neuralnetworks/1.2/IBurstCallback.h> #include <hidladapter/HidlBinderAdapter.h> namespace android { namespace hardware { namespace neuralnetworks { namespace V1_2 { ABurstCallback::ABurstCallback( const ::android::sp< ::android::hardware::neuralnetworks::V1_2::IBurstCallback>& impl) : mImpl(impl) { } // Methods from ::android::hardware::neuralnetworks::V1_2::IBurstCallback // follow. ::android::hardware::Return<void> ABurstCallback::getMemories( const ::android::hardware::hidl_vec<int32_t>& slots, getMemories_cb _hidl_cb) { getMemories_cb _hidl_cb_wrapped = [&](::android::hardware::neuralnetworks::V1_0::ErrorStatus status, const ::android::hardware::hidl_vec<::android::hardware::hidl_memory>& buffers) { return _hidl_cb(status, buffers); }; auto _hidl_out = mImpl->getMemories(slots, _hidl_cb_wrapped); return _hidl_out; } // Methods from ::android::hidl::base::V1_0::IBase follow. } // namespace V1_2 } // namespace neuralnetworks } // namespace hardware } // namespace android
38
80
0.733483
strassek
61804e3e6b38cfb45b10d3a70fb10cc4301015e6
1,600
cpp
C++
cli/sender/sender_utils.cpp
microsoft/APSI
39b45ceff89ca07d0e9481fac894252765989fcc
[ "MIT" ]
72
2021-05-04T11:25:58.000Z
2022-03-31T07:32:57.000Z
cli/sender/sender_utils.cpp
microsoft/APSI
39b45ceff89ca07d0e9481fac894252765989fcc
[ "MIT" ]
16
2021-05-06T07:58:34.000Z
2022-03-28T22:54:51.000Z
cli/sender/sender_utils.cpp
microsoft/APSI
39b45ceff89ca07d0e9481fac894252765989fcc
[ "MIT" ]
13
2021-05-04T06:44:40.000Z
2022-03-16T03:12:54.000Z
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. // STD #include <fstream> #include <utility> #include <vector> // APSI #include "apsi/log.h" #include "common/common_utils.h" #include "sender/sender_utils.h" // SEAL #include "seal/modulus.h" using namespace std; using namespace seal; using namespace apsi; unique_ptr<PSIParams> build_psi_params(const CLP &cmd) { string params_json; try { throw_if_file_invalid(cmd.params_file()); fstream input_file(cmd.params_file(), ios_base::in); if (!input_file.is_open()) { APSI_LOG_ERROR("File " << cmd.params_file() << " could not be open for reading."); throw runtime_error("Could not open params file"); } string line; while (getline(input_file, line)) { params_json.append(line); params_json.append("\n"); } input_file.close(); } catch (const exception &ex) { APSI_LOG_ERROR( "Error trying to read input file " << cmd.params_file() << ": " << ex.what()); return nullptr; } unique_ptr<PSIParams> params; try { params = make_unique<PSIParams>(PSIParams::Load(params_json)); } catch (const exception &ex) { APSI_LOG_ERROR("APSI threw an exception creating PSIParams: " << ex.what()); return nullptr; } APSI_LOG_INFO( "PSIParams have false-positive probability 2^(" << params->log2_fpp() << ") per receiver item"); return params; }
26.229508
94
0.60375
microsoft
6180cbdaf064eba47393b07bd80fee5acd26bdb0
14,224
cpp
C++
lib/io.cpp
codemonkey85/LibPKMN
96a1800a24bf3861da405cf56daa2d7afd6c850d
[ "MIT" ]
null
null
null
lib/io.cpp
codemonkey85/LibPKMN
96a1800a24bf3861da405cf56daa2d7afd6c850d
[ "MIT" ]
null
null
null
lib/io.cpp
codemonkey85/LibPKMN
96a1800a24bf3861da405cf56daa2d7afd6c850d
[ "MIT" ]
1
2019-07-08T20:43:57.000Z
2019-07-08T20:43:57.000Z
/* * Copyright (c) 2013-2014 Nicholas Corgan (n.corgan@gmail.com) * * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt * or copy at http://opensource.org/licenses/MIT) */ #include <cstdint> #include <fstream> #include <cstring> #include <boost/format.hpp> #include <pkmn/enums.hpp> #include <pkmn/io.hpp> #include <pkmds/pkmds_g5.h> #include <pkmds/pkmds_g5_sqlite.h> #include "libspec/game_gba.h" #include "library_bridge.hpp" #include "conversions/pokemon.hpp" #include "SQLiteCpp/SQLiteC++.h" namespace pkmn { namespace io { static void get_gen3_savetype(unsigned int libpkmn_id, gba_savetype_t &save_type) { switch(libpkmn_id) { case Versions::RUBY: case Versions::SAPPHIRE: save_type = GBA_TYPE_RS; break; case Versions::EMERALD: save_type = GBA_TYPE_E; break; case Versions::FIRERED: case Versions::LEAFGREEN: save_type = GBA_TYPE_FRLG; break; default: save_type = GBA_TYPE_RS; break; } } void export_to_3gpkm(team_pokemon::sptr t_pkmn, std::string filename) { //Check to see if t_pkmn is compatible with the .3gpkm format unsigned int generation = t_pkmn->get_generation(); if(generation != 3) { throw std::runtime_error("Only Pokemon of generation III can be exported to .3gpkm!"); } pk3_t pk3; uint8_t pk3_raw[sizeof(pk3_t)]; gba_savetype_t save_type; get_gen3_savetype(t_pkmn->get_game_id(), save_type); conversions::export_gen3_pokemon(t_pkmn, &pk3, save_type); } team_pokemon::sptr import_from_3gpkm(std::string filename) { std::ifstream ifile; ifile.open(filename.c_str(), std::ifstream::in | std::ifstream::binary); //Check to see if this is a valid .3gpkm file ifile.seekg(0, std::ios::end); unsigned int file_size = ifile.tellg(); if(file_size == sizeof(pk3_t)) { pk3_t pk3; ifile.seekg(0, std::ios::beg); ifile.read((char*)&pk3, sizeof(pk3_t)); ifile.close(); uint16_t* game_int = reinterpret_cast<uint16_t*>(&(pk3.box.met_loc)+1); uint8_t libpkmn_id = hometown_to_libpkmn_game((*game_int & 0x1E) >> 1); gba_savetype_t save_type; get_gen3_savetype(libpkmn_id, save_type); return conversions::import_gen3_pokemon(&pk3, save_type); } else if(file_size == sizeof(pk3_box_t)) { pk3_box_t pk3; ifile.seekg(0, std::ios::beg); ifile.read((char*)&pk3, sizeof(pk3_box_t)); ifile.close(); uint16_t* game_int = reinterpret_cast<uint16_t*>(&(pk3.met_loc)+1); uint8_t libpkmn_id = hometown_to_libpkmn_game((*game_int & 0x1E) >> 1); gba_savetype_t save_type; get_gen3_savetype(libpkmn_id, save_type); return conversions::import_gen3_pokemon(&pk3, save_type); } else { ifile.close(); throw std::runtime_error("This is not a valid .3gpkm file!"); } } void export_to_pkm(team_pokemon::sptr t_pkmn, std::string filename) { party_pkm* p_pkm = new party_pkm; conversions::export_gen5_pokemon(t_pkmn, p_pkm); uint8_t pkm_contents[sizeof(pokemon_obj)]; memcpy(&pkm_contents, p_pkm, sizeof(pokemon_obj)); std::ofstream ofile; ofile.open(filename.c_str(), std::ofstream::out | std::ofstream::binary); ofile.write((char*)pkm_contents, sizeof(pokemon_obj)); ofile.close(); } team_pokemon::sptr import_from_pkm(std::string filename) { party_pkm* p_pkm = new party_pkm; pokemon_obj* pkmn_obj = new pokemon_obj; uint8_t pkm_contents[sizeof(pokemon_obj)]; memset(pkm_contents, 0, sizeof(pokemon_obj)); std::ifstream ifile; ifile.open(filename.c_str(), std::ifstream::in | std::ifstream::binary); ifile.read((char*)pkm_contents, sizeof(pokemon_obj)); ifile.close(); memcpy(pkmn_obj, pkm_contents, sizeof(pokemon_obj)); libpkmn_pctoparty(p_pkm, pkmn_obj); return conversions::import_gen5_pokemon(p_pkm); } void export_to_pkx(team_pokemon::sptr t_pkmn, std::string filename) { party_pkx* p_pkx = new party_pkx; conversions::export_gen6_pokemon(t_pkmn, p_pkx); uint8_t pkx_contents[sizeof(pokemonx_obj)]; memcpy(&pkx_contents, p_pkx, sizeof(pokemonx_obj)); std::ofstream ofile; ofile.open(filename.c_str(), std::ofstream::out | std::ofstream::binary); ofile.write((char*)pkx_contents, sizeof(pokemonx_obj)); ofile.close(); } team_pokemon::sptr import_from_pkx(std::string filename) { party_pkx* p_pkm = new party_pkx; pokemonx_obj* pkmn_obj = new pokemonx_obj; uint8_t pkx_contents[sizeof(pokemonx_obj)]; memset(pkx_contents, 0, sizeof(pokemonx_obj)); std::ifstream ifile; ifile.open(filename.c_str(), std::ifstream::in | std::ifstream::binary); ifile.read((char*)pkx_contents, sizeof(pokemonx_obj)); ifile.close(); memcpy(pkmn_obj, pkx_contents, sizeof(pokemonx_obj)); libpkmn_pctopartyx(p_pkm, pkmn_obj); return conversions::import_gen6_pokemon(p_pkm); } void export_to_pksql(team_pokemon::sptr t_pkmn, std::string filename, std::string title) { dict<std::string, unsigned int> stats = t_pkmn->get_stats(); dict<std::string, unsigned int> EVs = t_pkmn->get_EVs(); dict<std::string, unsigned int> IVs = t_pkmn->get_IVs(); moveset_t moves; t_pkmn->get_moves(moves); SQLite::Database pksql_db(filename.c_str(), (SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE)); //TODO: attributes std::string create_table = "BEGIN TRANSACTION;\n" "CREATE TABLE pokemon (\n" " id INTEGER NOT NULL,\n" " title VARCHAR(50) NOT NULL,\n" " species_id INTEGER NOT NULL,\n" " game_id INTEGER NOT NULL,\n" " nickname VARCHAR(20) NOT NULL,\n" " otname VARCHAR(20) NOT NULL,\n" " held_item INTEGER NOT NULL,\n" " ball INTEGER NOT NULL,\n" " level INTEGER NOT NULL,\n" " met_level INTEGER NOT NULL,\n" " ability INTEGER NOT NULL,\n" " nature INTEGER NOT NULL,\n" " personality INTEGER NOT NULL,\n" " trainer_id INTEGER NOT NULL,\n" " ev_hp INTEGER NOT NULL,\n" " ev_attack INTEGER NOT NULL,\n" " ev_defense INTEGER NOT NULL,\n" " ev_speed INTEGER NOT NULL,\n" " ev_special INTEGER NOT NULL,\n" " ev_spatk INTEGER NOT NULL,\n" " ev_spdef INTEGER NOT NULL,\n" " iv_hp INTEGER NOT NULL,\n" " iv_attack INTEGER NOT NULL,\n" " iv_defense INTEGER NOT NULL,\n" " iv_speed INTEGER NOT NULL,\n" " iv_special INTEGER NOT NULL,\n" " iv_spatk INTEGER NOT NULL,\n" " iv_spdef INTEGER NOT NULL,\n" " move1 INTEGER NOT NULL,\n" " move2 INTEGER NOT NULL,\n" " move3 INTEGER NOT NULL,\n" " move4 INTEGER NOT NULL,\n" " ot_is_female INTEGER NOT NULL\n" ");\n" "COMMIT;"; std::string pokemon_export = str(boost::format("INSERT INTO \"pokemon\" VALUES(0,'%s',%d,%d,'%s','%s',%d,%d,%d,%d,'%s',%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d);") % title % t_pkmn->get_species_id() % t_pkmn->get_game_id() % t_pkmn->get_nickname().const_char() % t_pkmn->get_trainer_name().const_char() % t_pkmn->get_held_item()->get_item_id() % t_pkmn->get_ball() % t_pkmn->get_level() % t_pkmn->get_met_level() % t_pkmn->get_ability() % t_pkmn->get_nature().get_nature_id() % t_pkmn->get_personality() % t_pkmn->get_trainer_id() % EVs["HP"] % EVs["Attack"] % EVs["Defense"] % EVs["Speed"] % EVs.at("Special", 0) % EVs.at("Special Attack", 0) % EVs.at("Special Defense", 0) % IVs["HP"] % IVs["Attack"] % IVs["Defense"] % IVs["Speed"] % IVs.at("Special", 0) % IVs.at("Special Attack", 0) % IVs.at("Special Defense", 0) % moves[0]->get_move_id() % moves[1]->get_move_id() % moves[2]->get_move_id() % moves[3]->get_move_id() % ((t_pkmn->get_trainer_gender().std_string() == "Female") ? 1 : 0) ); pksql_db.exec(create_table.c_str()); pksql_db.exec(pokemon_export.c_str()); } team_pokemon::sptr import_from_pksql(std::string filename) { SQLite::Database pksql_db(filename.c_str()); //TODO: check for valid database before attempting to read SQLite::Statement query(pksql_db, "SELECT * FROM pokemon"); query.executeStep(); team_pokemon::sptr t_pkmn = team_pokemon::make(int(query.getColumn(2)), //species_id int(query.getColumn(3)), //game_id int(query.getColumn(8)), //level int(query.getColumn(28)), //move1 int(query.getColumn(29)), //move2 int(query.getColumn(30)), //move3 int(query.getColumn(31))); //move4 t_pkmn->set_nickname((const char*)(query.getColumn(4))); t_pkmn->set_trainer_name((const char*)(query.getColumn(5))); t_pkmn->set_held_item((const char*)(query.getColumn(6))); t_pkmn->set_ball((const char*)(query.getColumn(7))); t_pkmn->set_met_level(int(query.getColumn(9))); t_pkmn->set_ability((const char*)(query.getColumn(10))); t_pkmn->set_nature((const char*)(query.getColumn(11))); t_pkmn->set_personality(int(query.getColumn(12))); t_pkmn->set_trainer_id(int(query.getColumn(13))); t_pkmn->set_EV("HP", int(query.getColumn(14))); t_pkmn->set_EV("Attack", int(query.getColumn(15))); t_pkmn->set_EV("Defense", int(query.getColumn(16))); t_pkmn->set_EV("Speed", int(query.getColumn(17))); if(t_pkmn->get_generation() == 1) t_pkmn->set_EV("Special", int(query.getColumn(18))); else { t_pkmn->set_EV("Special Attack", int(query.getColumn(19))); t_pkmn->set_EV("Special Defense", int(query.getColumn(20))); } t_pkmn->set_IV("HP", int(query.getColumn(21))); t_pkmn->set_IV("Attack", int(query.getColumn(22))); t_pkmn->set_IV("Defense", int(query.getColumn(23))); t_pkmn->set_IV("Speed", int(query.getColumn(24))); if(t_pkmn->get_generation() < 3) t_pkmn->set_IV("Special", int(query.getColumn(25))); else { t_pkmn->set_IV("Special Attack", int(query.getColumn(26))); t_pkmn->set_IV("Special Defense", int(query.getColumn(27))); } t_pkmn->set_move(int(query.getColumn(28)), 1); t_pkmn->set_move(int(query.getColumn(29)), 2); t_pkmn->set_move(int(query.getColumn(30)), 3); t_pkmn->set_move(int(query.getColumn(31)), 4); t_pkmn->set_trainer_gender((int(query.getColumn(32)) ? "Female" : "Male")); return t_pkmn; } } }
44.45
175
0.480104
codemonkey85
61822a3036886bb00bbec9effe8978e5f61def1e
19,349
cpp
C++
src/txmgr.cpp
affinitydb/kernel
c1b39dd2f8a259b7f46db12787947e091efe86b7
[ "Apache-2.0", "CC0-1.0" ]
19
2015-01-08T05:16:16.000Z
2022-03-18T12:22:33.000Z
src/txmgr.cpp
affinitydb/kernel
c1b39dd2f8a259b7f46db12787947e091efe86b7
[ "Apache-2.0", "CC0-1.0" ]
null
null
null
src/txmgr.cpp
affinitydb/kernel
c1b39dd2f8a259b7f46db12787947e091efe86b7
[ "Apache-2.0", "CC0-1.0" ]
2
2015-03-12T07:05:09.000Z
2020-06-18T23:18:00.000Z
/************************************************************************************** Copyright © 2004-2014 GoPivotal, Inc. 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. Written by Mark Venguerov 2004-2014 **************************************************************************************/ #include "logmgr.h" #include "session.h" #include "logchkp.h" #include "lock.h" #include "queryprc.h" #include "startup.h" #include "fsmgr.h" #include "dataevent.h" using namespace Afy; using namespace AfyKernel; TxMgr::TxMgr(StoreCtx *cx,TXID startTXID,IStoreNotification *notItf,unsigned xSnap) : ctx(cx),notification(notItf),nextTXID(startTXID),nActive(0),lastTXCID(0),snapshots(NULL),nSS(0),xSS(xSnap) { } void TxMgr::setTXID(TXID txid) { nextTXID = txid; } //--------------------------------------------------------------------------------- inline static unsigned txiFlags(unsigned txl,bool fRO) { unsigned flags=fRO?TX_READONLY:0; switch (txl) { case TXI_READ_UNCOMMITTED: flags|=TX_UNCOMMITTED; break; case TXI_READ_COMMITTED: break; case TXI_SERIALIZABLE: //... case TXI_DEFAULT: case TXI_REPEATABLE_READ: if (!fRO) flags|=TX_READLOCKS; break; } return flags; } RC TxMgr::startTx(Session *ses,unsigned txt,unsigned txl) { assert(ses!=NULL); RC rc; if (ses->getStore()->theCB->state==SST_SHUTDOWN_IN_PROGRESS) return RC_SHUTDOWN; switch (ses->getTxState()) { default: break; // ??? case TX_ABORTING: if ((rc=abort(ses))!=RC_OK) return rc; case TX_NOTRAN: if (txt==TXT_MODIFYCLASS) ses->lockClass(RW_X_LOCK); else if (txt==TXT_READONLY && (txl==TXI_DEFAULT||txl>=TXI_REPEATABLE_READ)) ses->txcid=assignSnapshot(); return start(ses,txiFlags(txl,txt==TXT_READONLY)); } if (txt==TXT_MODIFYCLASS && ses->classLocked!=RW_X_LOCK) return RC_DEADLOCK; if ((rc=ses->pushTx())!=RC_OK) return rc; ses->tx.subTxID=++ses->subTxCnt; return RC_OK; } RC TxMgr::commitTx(Session *ses,bool fAll) { assert(ses!=NULL); switch (ses->getTxState()) { case TX_NOTRAN: return RC_OK; case TX_ABORTING: return abort(ses); default: break; } return commit(ses,fAll); } RC TxMgr::abortTx(Session *ses,AbortType at) { // check TX_ABORTING, distinguish between explicit rollback and internal assert(ses!=NULL); return ses->getTxState()==TX_NOTRAN ? RC_OK : abort(ses,at); } TXCID TxMgr::assignSnapshot() { Snapshot *ss=NULL; MutexP lck(&lock); if (nSS!=0 && snapshots!=NULL && (snapshots->txcid==lastTXCID||nSS>=xSS)) ss=snapshots; else if ((ss=new(ctx) Snapshot(lastTXCID,snapshots))!=NULL) {++nSS; snapshots=ss;} else return NO_TXCID; ss->txCnt++; return ss->txcid; } void TxMgr::releaseSnapshot(TXCID txcid) { MutexP lck(&lock); assert(txcid!=NO_TXCID); for (Snapshot **pss=&snapshots,*ss; (ss=*pss)!=NULL; pss=&ss->next) if (ss->txcid==txcid) { if (--ss->txCnt==0) { *pss=ss->next; nSS--; if (ss->next!=NULL) { //copy data to ss->next lck.set(NULL); } else { lck.set(NULL); //free data } ctx->free(ss); } break; } } //-------------------------------------------------------------------------------------------------------- RC TxMgr::start(Session *ses,unsigned flags) { lock.lock(); ses->txid=++nextTXID; ses->txState=TX_START|flags; ses->nLogRecs=0; if ((flags&TX_READONLY)==0) { assert(!ses->list.isInList()); activeList.insertFirst(&ses->list); nActive++; } lock.unlock(); if ((flags&TX_READONLY)==0) { RC rc=ctx->logMgr->init(); if (rc!=RC_OK) return rc; ses->tx.lastLSN=ses->firstLSN=ses->undoNextLSN=LSN(0); } ses->txState=TX_ACTIVE|flags; return RC_OK; } RC TxMgr::commit(Session *ses,bool fAll,bool fFlush) { RC rc; LSN commitLSN(0); assert(ses->getTxState()==TX_ACTIVE||ses->getTxState()==TX_ABORTING); if (ses->tx.next==NULL) fAll=true; else if ((rc=ses->popTx(true,fAll))!=RC_OK) return rc; if (fAll) { assert(ses->tx.next==NULL); if ((ses->txState&TX_READONLY)==0 && ses->getTxState()!=TX_ABORTING) { while (ses->tx.onCommit.head!=NULL) { OnCommit *oc=ses->tx.onCommit.head; ses->tx.onCommit.head=oc->next; ses->tx.onCommit.count--; rc=oc->process(ses); oc->destroy(ses); if (rc!=RC_OK) {abort(ses); return rc;} // message??? } ses->txState=ses->txState&~0xFFFFul|TX_COMMITTING; ses->tx.onCommit.count=0; uint32_t nPurge=0; TxPurge *tpa=ses->tx.txPurge.get(nPurge); rc=RC_OK; if (tpa!=NULL) { for (unsigned i=0; i<nPurge; i++) {if (rc==RC_OK) rc=tpa[i].purge(ses); ses->free(tpa[i].bmp); tpa[i].bmp=NULL;} ses->free(tpa); if (rc!=RC_OK) {cleanup(ses); return rc;} // rollback? } if ((unsigned)ses->tx.defHeap!=0) { if ((rc=ctx->heapMgr->addPagesToMap(ses->tx.defHeap,ses))!=RC_OK) {cleanup(ses); return rc;} // rollback? ses->tx.defHeap.cleanup(); assert(!ses->firstLSN.isNull() || (ctx->mode&STARTUP_NO_RECOVERY)!=0); if ((unsigned)ses->tx.defClass!=0) { if ((rc=ctx->heapMgr->addPagesToMap(ses->tx.defClass,ses,true))!=RC_OK) {cleanup(ses); return rc;} // rollback? ses->tx.defClass.cleanup(); assert(!ses->firstLSN.isNull() || (ctx->mode&STARTUP_NO_RECOVERY)!=0); } } bool fUnlock=false; if ((unsigned)ses->tx.defFree!=0) { if ((rc=ctx->fsMgr->freeTxPages(ses->tx.defFree))!=RC_OK) {cleanup(ses); return rc;} // rollback? ses->tx.defFree.cleanup(); fUnlock=true; assert(!ses->firstLSN.isNull() || (ctx->mode&STARTUP_NO_RECOVERY)!=0); } if (ses->tx.txIndex!=NULL) { // commit index changes!!! } if (!ses->firstLSN.isNull()) commitLSN=ctx->logMgr->insert(ses,LR_COMMIT); if (fUnlock) ctx->fsMgr->txUnlock(); // unlock dirHeap if (ses->reuse.pinPages!=NULL) for (unsigned i=0; i<ses->reuse.nPINPages; i++) ctx->heapMgr->HeapPageMgr::reuse(ses->reuse.pinPages[i].pid,ses->reuse.pinPages[i].space,ctx); if (ses->reuse.ssvPages!=NULL) for (unsigned i=0; i<ses->reuse.nSSVPages; i++) ctx->ssvMgr->HeapPageMgr::reuse(ses->reuse.ssvPages[i].pid,ses->reuse.ssvPages[i].space,ctx); ses->txState=ses->txState&~0xFFFFul|TX_COMMITTED; if (ses->repl!=NULL) { // pass replication stream to ctx->queryMgr->replication } } cleanup(ses); } if (fFlush && !commitLSN.isNull() && (ctx->mode&STARTUP_REDUCED_DURABILITY)==0) ctx->logMgr->flushTo(commitLSN); // check rc? return RC_OK; } RC TxMgr::abort(Session *ses,AbortType at) { RC rc; unsigned save; LSN abortLSN(0); assert(ses->getTxState()!=TX_NOTRAN); do { save=ses->txState; if ((save&TX_READONLY)==0) { ses->txState=ses->txState&~0xFFFFul|TX_ABORTING; if (!ses->firstLSN.isNull() && (rc=ctx->logMgr->rollback(ses,at!=TXA_ALL && ses->tx.next!=NULL))!=RC_OK) { report(MSG_ERROR,"Couldn't rollback transaction " _LX_FM "\n",ses->txid); cleanup(ses); return rc; } } if (ses->tx.next==NULL) at=TXA_ALL; else if ((rc=ses->popTx(false,at==TXA_ALL))!=RC_OK) return rc; else if (at!=TXA_ALL) ses->txState=save; } while (at==TXA_EXTERNAL && (save&TX_INTERNAL)!=0); if (at==TXA_ALL) { assert(ses->tx.next==NULL); if ((ses->txState&TX_READONLY)==0 && !ses->firstLSN.isNull()) abortLSN=ctx->logMgr->insert(ses,LR_ABORT); ses->txState=ses->txState&~0xFFFFul|TX_ABORTED; cleanup(ses,true); } if (!abortLSN.isNull() && (ctx->mode&STARTUP_REDUCED_DURABILITY)==0) ctx->logMgr->flushTo(abortLSN); //check rc? return RC_OK; } void TxMgr::cleanup(Session *ses,bool fAbort) { if (ses->heldLocks!=NULL) ctx->lockMgr->releaseLocks(ses,0,fAbort); ses->unlockClass(); if (ses->tx.next!=NULL) ses->popTx(false,true); ses->tx.defFree.cleanup(); ses->tx.cleanup(); ses->reuse.cleanup(); ses->xHeapPage=INVALID_PAGEID; ses->nTotalIns=0; delete ses->repl; ses->repl=NULL; if (ses->getTxState()!=TX_NOTRAN) { if ((ses->txState&TX_READONLY)==0) { MutexP lck(&lock); assert(ses->txcid==NO_TXCID); assert(nActive>0 && ses->list.isInList()); ses->list.remove(); nActive--; if ((ses->txState&TX_SYS)!=0) {ses->mini->cleanup(this); return;} } else if (ses->txcid!=NO_TXCID) releaseSnapshot(ses->txcid); } assert(!ses->list.isInList()); ses->txid=INVALID_TXID; ses->txState=TX_NOTRAN; ses->txcid=NO_TXCID; ses->subTxCnt=ses->nLogRecs=0; ses->nSyncStack=ses->tx.onCommit.count=0; ses->xSyncStack=ses->ctx!=NULL?ses->ctx->theCB->xSyncStack:DEFAULT_MAX_SYNC_ACTION; ses->xOnCommit=ses->ctx!=NULL?ses->ctx->theCB->xOnCommit:DEFAULT_MAX_ON_COMMIT; } LogActiveTransactions *TxMgr::getActiveTx(LSN& start) { lock.lock(); LogActiveTransactions *pActive = (LogActiveTransactions*)ctx->malloc(sizeof(LogActiveTransactions) + int(nActive-1)*sizeof(LogActiveTransactions::LogActiveTx)); // ??? if (pActive!=NULL) { unsigned cnt = 0; for (HChain<Session>::it it(&activeList); ++it; ) { Session *ses=it.get(); assert(ses->getTxState()!=TX_NOTRAN && ses->txid!=INVALID_TXID); if (ses->getTxState()!=TX_COMMITTED) { pActive->transactions[cnt].txid=ses->txid; pActive->transactions[cnt].lastLSN=ses->tx.lastLSN; pActive->transactions[cnt].firstLSN=ses->firstLSN; if (ses->firstLSN<start) start=ses->firstLSN; cnt++; assert(cnt<=nActive); } for (MiniTx *mtx=ses->mini; mtx!=NULL; mtx=mtx->next) { if ((mtx->state&TX_WASINLIST)!=0 && (mtx->state&0xFFFF)!=TX_COMMITTED) { pActive->transactions[cnt].txid=mtx->oldId; pActive->transactions[cnt].lastLSN=mtx->tx.lastLSN; pActive->transactions[cnt].firstLSN=mtx->firstLSN; if (mtx->firstLSN<start) start=mtx->firstLSN; cnt++; assert(cnt<=nActive); } } } pActive->nTransactions=cnt; } lock.unlock(); return pActive; } //--------------------------------------------------------------------------------- RC TxMgr::update(PBlock *pb,PageMgr *pageMgr,unsigned info,const byte *rec,size_t lrec,uint32_t flags,PBlock *newp) const { if (pageMgr==NULL) return RC_NOTFOUND; Session *ses=Session::getSession(); if (ses!=NULL && (ses->txState&TX_READONLY)!=0) return RC_READTX; if (pb->isULocked()) pb->upgradeLock(); assert(pb->isWritable() && (newp==NULL||newp->isXLocked())); RC rc=pageMgr->update(pb,ctx->bufMgr->getPageSize(),info,rec,(unsigned)lrec,0,newp); // size_t? if (rc==RC_OK) { if (ctx->memory!=NULL && pb->isFirstPageOp()) {pb->resetNewPage(); assert(newp==NULL);} else { if (ctx->memory!=NULL && newp!=NULL && newp->isFirstPageOp()) {newp->resetNewPage(); /* ???? */} ctx->logMgr->insert(ses,pb->isFirstPageOp()?LR_CREATE:LR_UPDATE,info<<PGID_SHIFT|pageMgr->getPGID(), pb->getPageID(),NULL,rec,lrec,flags,pb,newp); } } #ifdef STRICT_UPDATE_CHECK else report(MSG_ERROR,"TxMgr::update: page %08X, pageMgr %d, error %d\n",pb->getPageID(),pageMgr->getPGID(),rc); #endif return rc; } //---------------------------------------------------------------------------------- MiniTx::MiniTx(Session *s,unsigned mtxf) : ses(s),mtxFlags(mtxf&MTX_FLUSH),tx(s) { StoreCtx *ctx; if ((mtxf&MTX_SKIP)==0 && ses!=NULL && (ses->txState&TX_GSYS)==0 && (ctx=ses->getStore())->logMgr->init()==RC_OK) { oldId=ses->txid; txcid=ses->txcid; state=ses->txState|(ses->list.isInList()?TX_WASINLIST:0); identity=ses->identity; memcpy(&tx,&s->tx,sizeof(SubTx)); firstLSN=ses->firstLSN; undoNextLSN=ses->undoNextLSN; classLocked=ses->classLocked; reuse=ses->reuse; locks=ses->heldLocks; next=ses->mini; ctx->txMgr->lock.lock(); ses->mini=this; newId=ses->txid=++ctx->txMgr->nextTXID; ses->txcid=NO_TXCID; ses->classLocked=RW_NO_LOCK; ses->txState=TX_START; ses->firstLSN=ses->tx.lastLSN=ses->undoNextLSN=LSN(0); ses->tx.next=NULL; ses->heldLocks=NULL; ses->identity=0; new(&s->tx) SubTx(s); if (!ses->list.isInList()) ctx->txMgr->activeList.insertFirst(&ses->list); ctx->txMgr->nActive++; ctx->txMgr->lock.unlock(); ses->txState=TX_ACTIVE|TX_SYS|((mtxFlags&MTX_GLOB)!=0?TX_GSYS:0); mtxFlags|=MTX_STARTED; } } MiniTx::~MiniTx() { if ((mtxFlags&MTX_STARTED)!=0) { assert(ses!=NULL && ses->txid==newId && ses->getTxState()!=TX_NOTRAN && ses->list.isInList()); if ((mtxFlags&MTX_OK)==0) ses->getStore()->txMgr->abort(ses); // if failed??? else ses->getStore()->txMgr->commit(ses,false,(mtxFlags&MTX_FLUSH)!=0); // if failed??? } mtxFlags=0; } void MiniTx::cleanup(TxMgr *txMgr) { if (ses->mini==this) ses->mini=next; assert(!ses->list.isInList()); ses->txid=oldId; ses->txcid=txcid; ses->txState=state&~TX_WASINLIST; ses->identity=identity; ses->tx.cleanup(); memcpy(&ses->tx,&tx,sizeof(SubTx)); new(&tx) SubTx(ses); ses->reuse.cleanup(); ses->reuse=reuse; ses->firstLSN=firstLSN; ses->undoNextLSN=undoNextLSN; ses->classLocked=classLocked; ses->heldLocks=locks; if ((state&TX_WASINLIST)!=0) txMgr->activeList.insertFirst(&ses->list); } TxSP::~TxSP() { if ((flags&MTX_STARTED)!=0) { if (ses->getTxState()!=TX_NOTRAN && ses->tx.subTxID==subTxID) { assert(ses->list.isInList()); if ((flags&MTX_OK)==0) ses->getStore()->txMgr->abort(ses); else ses->getStore()->txMgr->commit(ses); // if failed ??? } flags=0; } } RC TxSP::start() { return start(TXI_DEFAULT,0); } RC TxSP::start(unsigned txl,unsigned txf) { if ((flags&MTX_STARTED)==0) { StoreCtx *ctx=ses->getStore(); RC rc; if (ctx->theCB->state==SST_SHUTDOWN_IN_PROGRESS) return RC_SHUTDOWN; if (ses->getTxState()!=TX_NOTRAN) {if ((rc=ses->pushTx())!=RC_OK) return rc; ses->tx.subTxID=++ses->subTxCnt;} else if ((rc=ctx->txMgr->start(ses,txiFlags(txl,false)|txf))!=RC_OK) return rc; flags|=MTX_STARTED; subTxID=ses->tx.subTxID; } return RC_OK; } //---------------------------------------------------------------------------------------- CreateDataEvent *OnCommit::getDataEvent() { return NULL; } RC Session::pushTx() { SubTx *st=new(this) SubTx(this); if (st==NULL) return RC_NOMEM; memcpy(st,&tx,sizeof(SubTx)); new(&tx) SubTx(this); tx.next=st; tx.lastLSN=st->lastLSN; tx.subTxID=++subTxCnt; if (repl!=NULL) repl->mark(tx.rmark); return RC_OK; } RC Session::popTx(bool fCommit,bool fAll) { for (SubTx *st=tx.next; st!=NULL; st=tx.next) { if (fCommit) { st->defHeap+=tx.defHeap; st->defClass+=tx.defClass; st->defFree+=tx.defFree; st->nInserted+=tx.nInserted; if (tx.txPurge!=0) {RC rc=st->txPurge.merge(tx.txPurge); if (rc!=RC_OK) return rc;} if (tx.onCommit.head!=NULL) {st->onCommit+=tx.onCommit; tx.onCommit.reset();} if (tx.txIndex!=NULL) { // txIndex!!! merge to st tx.txIndex=NULL; } } else if (fAll) st->nInserted=nTotalIns=0; else { ctx->lockMgr->releaseLocks(this,tx.subTxID,true); st->nInserted-=tx.nInserted; nTotalIns-=tx.nInserted; if (repl!=NULL) repl->truncate(TR_REL_ALL,&tx.rmark); } st->lastLSN=tx.lastLSN; //??? tx.next=NULL; tx.~SubTx(); memcpy(&tx,st,sizeof(SubTx)); free(st); if (!fAll) break; } return RC_OK; } SubTx::SubTx(Session *s) : next(NULL),ses(s),subTxID(0),lastLSN(0),txIndex(NULL),txPurge((MemAlloc*)s),defHeap(s),defClass(s),defFree(s),nInserted(0) { } SubTx::~SubTx() { for (unsigned i=0,j=(unsigned)txPurge; i<j; i++) if (txPurge[i].bmp!=NULL) ses->free(txPurge[i].bmp); for (OnCommit *oc=onCommit.head,*oc2; oc!=NULL; oc=oc2) {oc2=oc->next; oc->destroy(ses);} //delete txIndex; } void SubTx::cleanup() { if (next!=NULL) {next->cleanup(); next->~SubTx(); ses->free(next); next=NULL;} for (OnCommit *oc=onCommit.head,*oc2; oc!=NULL; oc=oc2) {oc2=oc->next; oc->destroy(ses);} for (unsigned i=0,j=(unsigned)txPurge; i<j; i++) if (txPurge[i].bmp!=NULL) ses->free(txPurge[i].bmp); txPurge.clear(); onCommit.reset(); if (txIndex!=NULL) { //... } if ((unsigned)defHeap!=0) { //??? defHeap.cleanup(); } if ((unsigned)defClass!=0) { //??? defClass.cleanup(); } if ((unsigned)defFree!=0) { if (ses->getStore()->fsMgr->freeTxPages(defFree)==RC_OK) ses->getStore()->fsMgr->txUnlock(); defFree.cleanup(); } lastLSN=LSN(0); } RC SubTx::queueForPurge(const PageAddr& addr,PurgeType pt,const void *data) { TxPurge prg={addr.pageID,0,NULL},*tp=NULL; RC rc=txPurge.add(prg,&tp); uint32_t flg=pt==TXP_SSV?0x80000000:0; if (rc==RC_FALSE) { if (data!=NULL || (tp->range&0x80000000)!=flg || tp->range==uint32_t(~0u)) return RC_CORRUPTED; // report error ushort idx=addr.idx/(sizeof(uint32_t)*8),l=tp->range>>16&0x3fff; assert(tp->bmp!=NULL); if (idx<ushort(tp->range)) { ushort d=ushort(tp->range)-idx; if ((tp->bmp=(uint32_t*)ses->realloc(tp->bmp,(l+d)*sizeof(uint32_t)))==NULL) return RC_NOMEM; memmove(tp->bmp+d,tp->bmp,l*sizeof(uint32_t)); if (d==1) tp->bmp[0]=0; else memset(tp->bmp,0,d*sizeof(uint32_t)); tp->range=(tp->range&0x80000000)+(uint32_t(l+d)<<16)+idx; } else if (idx>=ushort(tp->range)+l) { ushort d=idx+1-ushort(tp->range)-l; if ((tp->bmp=(uint32_t*)ses->realloc(tp->bmp,(l+d)*sizeof(uint32_t)))==NULL) return RC_NOMEM; if (d==1) tp->bmp[l]=0; else memset(tp->bmp+l,0,d*sizeof(uint32_t)); tp->range+=uint32_t(d)<<16; } tp->bmp[idx-ushort(tp->range)]|=1<<addr.idx%(sizeof(uint32_t)*8); rc=RC_OK; } else if (rc==RC_OK) { if (data!=NULL) { ushort l=HeapPageMgr::collDescrSize((HeapPageMgr::HeapExtCollection*)data); if ((tp->bmp=(uint32_t*)ses->malloc(l))==NULL) return RC_NOMEM; memcpy(tp->bmp,data,l); tp->range=uint32_t(~0u); } else { tp->range=(addr.idx/(sizeof(uint32_t)*8))|flg|0x00010000; if ((tp->bmp=new(ses) uint32_t)==NULL) return RC_NOMEM; tp->bmp[0]=1<<addr.idx%(sizeof(uint32_t)*8); } } return rc; } RC TxPurge::purge(Session *ses) { return ses->getStore()->queryMgr->purge(pageID,range&0xFFFF,range>>16&0x3FFF,bmp,(range&0x80000000)!=0?TXP_SSV:TXP_PIN,ses); } RC TxPurge::Cmp::merge(TxPurge& dst,TxPurge& src,MemAlloc *ma) { unsigned ss=src.range&0xFFFF,ds=dst.range&0xFFFF; assert(src.pageID==dst.pageID); if (ds==0xFFFF) {ma->free(src.bmp); src.bmp=NULL; return ss==0xFFFF?RC_OK:RC_CORRUPTED;} unsigned si=ss+(src.range>>16&0x3FFF),di=ds+(dst.range>>16&0x3FFF); if (ss<ds) {unsigned t=ss; ss=ds; ds=t; t=si; si=di; di=t; uint32_t *p=src.bmp; src.bmp=dst.bmp; dst.bmp=p;} if (di<si) { if ((dst.bmp=(uint32_t*)ma->realloc(dst.bmp,(si-ds)*sizeof(uint32_t)))==NULL) return RC_OK; if (ss<=di) memcpy(dst.bmp+di-ds,src.bmp+di-ss,(si-di)*sizeof(uint32_t)); else {memset(dst.bmp+di-ds,0,(ss-di)*sizeof(uint32_t)); memcpy(dst.bmp+ss-ds,src.bmp,(si-ss)*sizeof(uint32_t));} } for (unsigned i=ss,end=min(si,di); i<end; i++) dst.bmp[i-ds]|=src.bmp[i-ss]; ma->free(src.bmp); src.bmp=NULL; dst.range=(dst.range&0x80000000)|(max(di,si)-ds)<<16|ds; return RC_OK; } TxGuard::~TxGuard() { assert(ses!=NULL); if (ses->getTxState()==TX_ABORTING) ses->ctx->txMgr->abortTx(ses,TXA_ALL); }
39.812757
169
0.63626
affinitydb
618589217aae6b175e1a6b8922e1fc08bd9c2676
1,196
cpp
C++
code/cpplearn/dp-factory.cpp
iusyu/c_practic
7428b8d37df09cb27bc9d66d1e34c81a973b6119
[ "MIT" ]
null
null
null
code/cpplearn/dp-factory.cpp
iusyu/c_practic
7428b8d37df09cb27bc9d66d1e34c81a973b6119
[ "MIT" ]
null
null
null
code/cpplearn/dp-factory.cpp
iusyu/c_practic
7428b8d37df09cb27bc9d66d1e34c81a973b6119
[ "MIT" ]
null
null
null
#include<iostream> #include<string> #include <memory> class HtmlRender{ public: HtmlRender() {} virtual std::string rendering(){ return ""; } virtual ~HtmlRender(){ } }; class MainPageRender:public HtmlRender{ public: MainPageRender(){} virtual std::string rendering() override { return "this is Main Page Html Render"; } virtual ~MainPageRender(){ } }; class HtmlRenderFactory{ public: HtmlRenderFactory() {} virtual HtmlRender* getRender(){ } virtual ~HtmlRenderFactory(){ } }; class MainPageRenderFactory:public HtmlRenderFactory{ public: MainPageRenderFactory() {} virtual HtmlRender* getRender() override{ return new MainPageRender(); } virtual ~MainPageRenderFactory(){ } }; class Triger{ public: Triger() = default; Triger(HtmlRenderFactory* hrf):renderfactory(hrf) {} virtual int main(){ // get render html std::shared_ptr<HtmlRender> prender (renderfactory->getRender()); std::cout<< (*prender).rendering() <<std::endl; return 0; } virtual ~Triger(){ } private: HtmlRenderFactory *renderfactory; }; int main(int argc, char* argv[]) { MainPageRenderFactory mainpageFact; Triger triger(&mainpageFact); return triger.main(); }
15.736842
67
0.70903
iusyu
61870672fe3cce2b87e59d9a2cc6eeffd8a5dde3
558
cpp
C++
universal-problems/1566.cpp
Galaxies99/leetcode
8099cf93fa1c61032449e67032eac1ea66bcc8fc
[ "MIT" ]
1
2020-07-19T15:37:01.000Z
2020-07-19T15:37:01.000Z
universal-problems/1566.cpp
Galaxies99/leetcode
8099cf93fa1c61032449e67032eac1ea66bcc8fc
[ "MIT" ]
null
null
null
universal-problems/1566.cpp
Galaxies99/leetcode
8099cf93fa1c61032449e67032eac1ea66bcc8fc
[ "MIT" ]
null
null
null
class Solution { public: bool containsPattern(vector<int>& arr, int m, int k) { for (int i = 0; i < (int)arr.size() - m * k + 1; ++ i) { bool flag = true; for (int j = 1; j < k; ++ j) { for (int l = 0; l < m; ++ l) if (arr[i + l] != arr[i + l + j * m]) { flag = false; break; } if (flag == false) break; } if (flag == true) return true; } return false; } };
29.368421
64
0.340502
Galaxies99
618707a12e2d07474b76c242e83463eb2e3f7a4a
5,552
cpp
C++
src/app/impl/tracker/tracker_grid.cpp
nomadsinteractive/ark
52f84c6dbd5ca6bdd07d450b3911be1ffd995922
[ "Apache-2.0" ]
5
2018-03-28T09:14:55.000Z
2018-04-02T11:54:33.000Z
src/app/impl/tracker/tracker_grid.cpp
nomadsinteractive/ark
52f84c6dbd5ca6bdd07d450b3911be1ffd995922
[ "Apache-2.0" ]
null
null
null
src/app/impl/tracker/tracker_grid.cpp
nomadsinteractive/ark
52f84c6dbd5ca6bdd07d450b3911be1ffd995922
[ "Apache-2.0" ]
null
null
null
#include "app/impl/tracker/tracker_grid.h" #include "core/base/bean_factory.h" #include "core/util/math.h" namespace ark { TrackerGrid::TrackerGrid(uint32_t dimension, const V3& cell) : _stub(sp<Stub>::make(dimension, cell)) { } sp<Vec3> TrackerGrid::create(int32_t id, const sp<Vec3>& position, const sp<Vec3>& size) { return sp<TrackedPosition>::make(id, _stub, position, size); } void TrackerGrid::remove(int32_t id) { _stub->remove(id); } std::unordered_set<int32_t> TrackerGrid::search(const V3& position, const V3& size) { return _stub->search(position, size); } TrackerGrid::Stub::Stub(uint32_t dimension, const V3& cell) : _dimension(dimension), _axes(new Axis[dimension]) { DCHECK(_dimension < 4, "Dimension should be either 2(V2) or 3(V3)"); for(uint32_t i = 0; i < _dimension; i++) { _axes[i]._stride = static_cast<int32_t>(cell[i]); DASSERT(_axes[i]._stride > 0); } } TrackerGrid::Stub::~Stub() { delete[] _axes; } void TrackerGrid::Stub::remove(int32_t id) { for(uint32_t i = 0; i < _dimension; i++) _axes[i].remove(id); } void TrackerGrid::Stub::create(int32_t id, const V3& position, const V3& size) { for(uint32_t i = 0; i < _dimension; i++) { float p = position[i]; float s = size[i]; _axes[i].create(id, p, p - s / 2.0f, p + s / 2.0f); } } void TrackerGrid::Stub::update(int32_t id, const V3& position, const V3& size) { for(uint32_t i = 0; i < _dimension; i++) { float p = position[i]; float s = size[i]; _axes[i].update(id, p, p - s / 2.0f, p + s / 2.0f); } } std::unordered_set<int32_t> TrackerGrid::Stub::search(const V3& position, const V3& size) const { std::unordered_set<int32_t> candidates = _axes[0].search(position[0] - size[0] / 2.0f, position[0] + size[0] / 2.0f); for(uint32_t i = 1; i < _dimension && !candidates.empty(); i++) { const std::unordered_set<int32_t> s1 = std::move(candidates); const std::unordered_set<int32_t> s2 = _axes[i].search(position[i] - size[i] / 2.0f, position[i] + size[i] / 2.0f); for(int32_t i : s1) if(s2.find(i) != s2.end()) candidates.insert(i); } return candidates; } void TrackerGrid::Axis::create(int32_t id, float position, float low, float high) { int32_t mp = Math::modFloor<int32_t>(static_cast<int32_t>(position), _stride); int32_t remainder; int32_t begin = Math::divmod(static_cast<int32_t>(low), _stride, remainder); int32_t end = Math::divmod(static_cast<int32_t>(high), _stride, remainder) + 1; const Range cur(mp, begin, end); updateRange(id, cur, Range()); } void TrackerGrid::Axis::update(int32_t id, float position, float low, float high) { int32_t mp = Math::modFloor<int32_t>(static_cast<int32_t>(position), _stride); const auto iter = _trackee_ranges.find(id); if(iter != _trackee_ranges.end() && iter->second._position != mp) { int32_t remainder; int32_t begin = Math::divmod(static_cast<int32_t>(low), _stride, remainder); int32_t end = Math::divmod(static_cast<int32_t>(high), _stride, remainder) + 1; const Range cur(mp, begin, end); const Range prev = iter->second; updateRange(id, cur, prev); } } void TrackerGrid::Axis::updateRange(int32_t id, const Range& cur, const Range& prev) { for(int32_t i = prev._begin; i < prev._end; i++) if(!cur.within(i)) remove(id, i); for(int32_t i = cur._begin; i < cur._end; i++) if(!prev.within(i)) _trackee_range_ids.insert(std::make_pair(i, id)); _trackee_ranges[id] = cur; } std::unordered_set<int32_t> TrackerGrid::Axis::search(float low, float high) const { std::unordered_set<int32_t> candidates; int32_t remainder; int32_t begin = Math::divmod(static_cast<int32_t>(low), _stride, remainder); int32_t end = Math::divmod(static_cast<int32_t>(high), _stride, remainder) + 1; for(int32_t i = begin; i < end; i++) { const auto range = _trackee_range_ids.equal_range(i); for(auto iter = range.first; iter != range.second; ++iter) candidates.insert(iter->second); } return candidates; } void TrackerGrid::Axis::remove(int32_t id) { const auto it1 = _trackee_ranges.find(id); if(it1 != _trackee_ranges.end()) { const Range& p = it1->second; for(int32_t i = p._begin; i < p._end; i++) remove(id, i); _trackee_ranges.erase(it1); } } void TrackerGrid::Axis::remove(int32_t id, int32_t rangeId) { const auto range = _trackee_range_ids.equal_range(rangeId); for(auto iter = range.first; iter != range.second; ++iter) if(id == iter->second) { iter = _trackee_range_ids.erase(iter); if(iter == range.second) break; } } TrackerGrid::BUILDER::BUILDER(BeanFactory& factory, const document& manifest) : _dimension(Documents::getAttribute(manifest, "dimension", 2)), _cell(factory.ensureBuilder<Vec3>(manifest, "cell")) { } sp<Tracker> TrackerGrid::BUILDER::build(const Scope& args) { return sp<TrackerGrid>::make(_dimension, _cell->build(args)->val()); } TrackerGrid::Axis::Range::Range() : _position(0), _begin(0), _end(0) { } TrackerGrid::Axis::Range::Range(int32_t position, int32_t begin, int32_t end) : _position(position), _begin(begin), _end(end) { } bool TrackerGrid::Axis::Range::within(int32_t r) const { return r >= _begin && r < _end; } }
29.221053
123
0.634906
nomadsinteractive
618793825384fbb6864c087284a273bdc8dc8136
4,173
cpp
C++
Dependencies/Build/mac/share/faust/oscio-qt.cpp
SKyzZz/test
9b03adce666adb85e5ae2d8af5262e0acb4b91e1
[ "Zlib" ]
2
2020-10-25T09:03:03.000Z
2021-06-24T13:20:01.000Z
Dependencies/Build/mac/share/faust/oscio-qt.cpp
SKyzZz/test
9b03adce666adb85e5ae2d8af5262e0acb4b91e1
[ "Zlib" ]
null
null
null
Dependencies/Build/mac/share/faust/oscio-qt.cpp
SKyzZz/test
9b03adce666adb85e5ae2d8af5262e0acb4b91e1
[ "Zlib" ]
null
null
null
/************************************************************************ IMPORTANT NOTE : this file contains two clearly delimited sections : the ARCHITECTURE section (in two parts) and the USER section. Each section is governed by its own copyright and license. Please check individually each section for license and copyright information. *************************************************************************/ /*******************BEGIN ARCHITECTURE SECTION (part 1/2)****************/ /************************************************************************ FAUST Architecture File Copyright (C) 2003-2019 GRAME, Centre National de Creation Musicale --------------------------------------------------------------------- This Architecture section is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; If not, see <http://www.gnu.org/licenses/>. EXCEPTION : As a special exception, you may create a larger work that contains this FAUST architecture section and distribute that work under terms of your choice, so long as this FAUST architecture section is not modified. ************************************************************************ ************************************************************************/ #include <libgen.h> #include <iostream> #include "faust/gui/FUI.h" #include "faust/gui/QTUI.h" #include "faust/gui/OSCUI.h" #include "faust/misc.h" #include "faust/audio/osc-dsp.h" /****************************************************************************** ******************************************************************************* VECTOR INTRINSICS ******************************************************************************* *******************************************************************************/ <<includeIntrinsic>> /********************END ARCHITECTURE SECTION (part 1/2)****************/ /**************************BEGIN USER SECTION **************************/ <<includeclass>> /***************************END USER SECTION ***************************/ /*******************BEGIN ARCHITECTURE SECTION (part 2/2)***************/ mydsp DSP; std::list<GUI*> GUI::fGuiList; ztimedmap GUI::gTimedZoneMap; /****************************************************************************** ******************************************************************************* MAIN PLAY THREAD ******************************************************************************* *******************************************************************************/ int main(int argc, char* argv[]) { char name[256], dst[258]; char rcfilename[256]; char* home = getenv("HOME"); snprintf(name, 256, "%s", basename(argv[0])); snprintf(dst, 258, "/%s/", name); snprintf(rcfilename, 256, "%s/.%src", home, name); QApplication myApp(argc, argv); QTGUI* interface = new QTGUI(); FUI* finterface = new FUI(); DSP.buildUserInterface(interface); DSP.buildUserInterface(finterface); oscdsp osca (dst, argc, argv); OSCUI* oscinterface = new OSCUI(name, argc, argv, &osca); DSP.buildUserInterface(oscinterface); snprintf(dst, 258, "/%s/", oscinterface->getRootName()); osca.setDest (dst); osca.init(name, &DSP); finterface->recallState(rcfilename); osca.start(); oscinterface->run(); interface->run(); myApp.setStyleSheet(interface->styleSheet()); myApp.exec(); interface->stop(); osca.stop(); finterface->saveState(rcfilename); // desallocation delete interface; delete finterface; delete oscinterface; return 0; } /********************END ARCHITECTURE SECTION (part 2/2)****************/
33.926829
81
0.489097
SKyzZz
6189ba2be2ae48c556114c67be211de4b3d999af
451
cpp
C++
cli/autobeam.cpp
johnnymac647/humlib
c67954045fb5570915d6a1c75d9a1e36cc9bdf93
[ "BSD-2-Clause" ]
19
2016-06-18T02:03:56.000Z
2022-02-23T17:26:32.000Z
cli/autobeam.cpp
johnnymac647/humlib
c67954045fb5570915d6a1c75d9a1e36cc9bdf93
[ "BSD-2-Clause" ]
43
2017-03-09T07:32:12.000Z
2022-03-23T20:18:35.000Z
cli/autobeam.cpp
johnnymac647/humlib
c67954045fb5570915d6a1c75d9a1e36cc9bdf93
[ "BSD-2-Clause" ]
5
2019-11-14T22:24:02.000Z
2021-09-07T18:27:21.000Z
// // Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu> // Creation Date: Wed Nov 30 20:35:56 PST 2016 // Last Modified: Fri Dec 2 03:44:55 PST 2016 // Filename: autobeam.cpp // URL: https://github.com/craigsapp/humlib/blob/master/cli/autobeam.cpp // Syntax: C++11 // vim: ts=3 noexpandtab nowrap // // Description: Add beams to Humdrum file(s). // #include "humlib.h" STREAM_INTERFACE(Tool_autobeam)
23.736842
82
0.651885
johnnymac647
618ad9434854a8b214d96b6980918e52f3867409
128
cpp
C++
greet_ext.cpp
ab300819/py-ext
306fd388f3bd5921436d857ff0da60fd1a9df06a
[ "Apache-2.0" ]
null
null
null
greet_ext.cpp
ab300819/py-ext
306fd388f3bd5921436d857ff0da60fd1a9df06a
[ "Apache-2.0" ]
null
null
null
greet_ext.cpp
ab300819/py-ext
306fd388f3bd5921436d857ff0da60fd1a9df06a
[ "Apache-2.0" ]
null
null
null
#include <boost/python.hpp> #include "greet.h" BOOST_PYTHON_MODULE(greet_ext) { boost::python::def("say_hello", say_hello); }
21.333333
78
0.734375
ab300819
618d7fa91ff0e45fca17b1554d3f3a84b2458953
679
cpp
C++
sprime/sprime.cpp
chenhongqiao/OI-Solutions
009a3c4b713b62658b835b52e0f61f882b5a6ffe
[ "MIT" ]
1
2020-12-15T20:25:21.000Z
2020-12-15T20:25:21.000Z
sprime/sprime.cpp
chenhongqiao/OI-Solutions
009a3c4b713b62658b835b52e0f61f882b5a6ffe
[ "MIT" ]
null
null
null
sprime/sprime.cpp
chenhongqiao/OI-Solutions
009a3c4b713b62658b835b52e0f61f882b5a6ffe
[ "MIT" ]
null
null
null
#include <iostream> #include <cmath> #include <chrono> using namespace std; int n; bool is_prime(long long n) { if (n == 1) { return false; } if (n == 2) { return true; } for (int i = 2; i <= sqrt(n) + 1; i++) { if (n % i == 0) { return false; } } return true; } void dfs(int dep, long long v) { if (dep >= n) { cout << v << endl; return; } for (int i = 1; i < 10; i++) { long long tmp = v * 10 + i; if (is_prime(tmp)) { dfs(dep + 1, tmp); } } } int main() { cin >> n; dfs(0, 0); return 0; }
14.76087
42
0.396171
chenhongqiao
618dcad59a8388f2bcf7ef691a5aec1fcebb18eb
7,032
cpp
C++
openstudiocore/src/model/test/PlantLoop_GTest.cpp
bobzabcik/OpenStudio
858321dc0ad8d572de15858d2ae487b029a8d847
[ "blessing" ]
null
null
null
openstudiocore/src/model/test/PlantLoop_GTest.cpp
bobzabcik/OpenStudio
858321dc0ad8d572de15858d2ae487b029a8d847
[ "blessing" ]
null
null
null
openstudiocore/src/model/test/PlantLoop_GTest.cpp
bobzabcik/OpenStudio
858321dc0ad8d572de15858d2ae487b029a8d847
[ "blessing" ]
null
null
null
/********************************************************************** * Copyright (c) 2008-2013, Alliance for Sustainable Energy. * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********************************************************************/ #include <gtest/gtest.h> #include <model/PlantLoop.hpp> #include <model/Model.hpp> #include <model/Node.hpp> #include <model/Node_Impl.hpp> #include <model/Loop.hpp> #include <model/Loop_Impl.hpp> #include <model/ConnectorSplitter.hpp> #include <model/ConnectorSplitter_Impl.hpp> #include <model/ConnectorMixer.hpp> #include <model/ConnectorMixer_Impl.hpp> #include <model/ChillerElectricEIR.hpp> #include <model/ChillerElectricEIR_Impl.hpp> #include <model/CurveBiquadratic.hpp> #include <model/CurveQuadratic.hpp> #include <model/CoilHeatingWater.hpp> #include <model/CoilCoolingWater.hpp> #include <model/ScheduleCompact.hpp> #include <model/LifeCycleCost.hpp> //#include <utilities/idd/IddEnums.hxx> using namespace openstudio; TEST(PlantLoop,PlantLoop_PlantLoop) { ::testing::FLAGS_gtest_death_test_style = "threadsafe"; ASSERT_EXIT ( { model::Model m; model::PlantLoop plantLoop(m); exit(0); } , ::testing::ExitedWithCode(0), "" ); } TEST(PlantLoop,PlantLoop_supplyComponents) { model::Model m; // Empty Plant Loop model::PlantLoop plantLoop(m); ASSERT_EQ( 5u,plantLoop.supplyComponents().size() ); boost::optional<model::ModelObject> comp; comp = plantLoop.supplyComponents()[1]; ASSERT_TRUE(comp); ASSERT_EQ(IddObjectType::OS_Connector_Splitter,comp->iddObjectType().value()); model::ConnectorSplitter splitter = comp->cast<model::ConnectorSplitter>(); comp = splitter.lastOutletModelObject(); ASSERT_TRUE(comp); ASSERT_EQ(IddObjectType::OS_Node,comp->iddObjectType().value()); model::Node connectorNode = comp->cast<model::Node>(); comp = connectorNode.outletModelObject(); ASSERT_TRUE(comp); ASSERT_EQ(IddObjectType::OS_Connector_Mixer,comp->iddObjectType().value()); model::ConnectorMixer mixer = comp->cast<model::ConnectorMixer>(); comp = mixer.outletModelObject(); ASSERT_TRUE(comp); model::Node supplyOutletNode = plantLoop.supplyOutletNode(); ASSERT_EQ(comp->handle(),supplyOutletNode.handle()); // Add a new component model::CurveBiquadratic ccFofT(m); model::CurveBiquadratic eirToCorfOfT(m); model::CurveQuadratic eiToCorfOfPlr(m); model::ChillerElectricEIR chiller(m,ccFofT,eirToCorfOfT,eiToCorfOfPlr); ASSERT_TRUE(chiller.addToNode(supplyOutletNode)); ASSERT_EQ( 7u,plantLoop.supplyComponents().size() ); // Add a new supply branch model::ChillerElectricEIR chiller2 = chiller.clone(m).cast<model::ChillerElectricEIR>(); ASSERT_EQ( 1u,splitter.nextBranchIndex() ); ASSERT_EQ( 1u,mixer.nextBranchIndex() ); ASSERT_TRUE(plantLoop.addSupplyBranchForComponent(chiller2)); ASSERT_EQ( 1u,splitter.nextBranchIndex() ); ASSERT_EQ( 1u,mixer.nextBranchIndex() ); ASSERT_EQ( 1u,splitter.outletModelObjects().size() ); ASSERT_EQ( 9u,plantLoop.supplyComponents().size() ); // Remove the new supply branch ASSERT_TRUE(plantLoop.removeSupplyBranchWithComponent(chiller2)); ASSERT_EQ( 7u,plantLoop.supplyComponents().size() ); } TEST(PlantLoop,PlantLoop_demandComponents) { model::Model m; model::PlantLoop plantLoop(m); ASSERT_EQ( 5u,plantLoop.demandComponents().size() ); } TEST(PlantLoop,PlantLoop_addDemandBranchForComponent) { model::Model m; model::ScheduleCompact s(m); model::PlantLoop plantLoop(m); model::CoilHeatingWater heatingCoil(m,s); model::CoilHeatingWater heatingCoil2(m,s); model::CoilCoolingWater coolingCoil(m,s); EXPECT_TRUE(plantLoop.addDemandBranchForComponent(heatingCoil)); boost::optional<model::ModelObject> inletModelObject = heatingCoil.waterInletModelObject(); boost::optional<model::ModelObject> outletModelObject = heatingCoil.waterOutletModelObject(); ASSERT_TRUE( inletModelObject ); ASSERT_TRUE( outletModelObject ); boost::optional<model::Node> inletNode = inletModelObject->optionalCast<model::Node>(); boost::optional<model::Node> outletNode = outletModelObject->optionalCast<model::Node>(); ASSERT_TRUE( inletNode ); ASSERT_TRUE( outletNode ); boost::optional<model::ModelObject> inletModelObject2 = inletNode->inletModelObject(); boost::optional<model::ModelObject> outletModelObject2 = outletNode->outletModelObject(); ASSERT_TRUE( inletModelObject2 ); ASSERT_TRUE( outletModelObject2 ); ASSERT_EQ( (unsigned)7,plantLoop.demandComponents().size() ); EXPECT_TRUE(plantLoop.addDemandBranchForComponent(heatingCoil2)); ASSERT_EQ( (unsigned)10,plantLoop.demandComponents().size() ); EXPECT_TRUE(plantLoop.addDemandBranchForComponent(coolingCoil)); ASSERT_EQ( (unsigned)13,plantLoop.demandComponents().size() ); } TEST(PlantLoop,PlantLoop_removeDemandBranchWithComponent) { model::Model m; model::PlantLoop plantLoop(m); model::ScheduleCompact s(m); model::CoilHeatingWater heatingCoil(m,s); EXPECT_TRUE(plantLoop.addDemandBranchForComponent(heatingCoil)); ASSERT_EQ( (unsigned)7,plantLoop.demandComponents().size() ); model::CoilHeatingWater heatingCoil2(m,s); EXPECT_TRUE(plantLoop.addDemandBranchForComponent(heatingCoil2)); ASSERT_EQ( (unsigned)10,plantLoop.demandComponents().size() ); model::Splitter splitter = plantLoop.demandSplitter(); ASSERT_EQ( (unsigned)2,splitter.nextBranchIndex() ); std::vector<model::ModelObject> modelObjects = plantLoop.demandComponents(splitter,heatingCoil2); ASSERT_EQ( (unsigned)3,modelObjects.size() ); EXPECT_TRUE(plantLoop.removeDemandBranchWithComponent(heatingCoil2)); ASSERT_EQ( (unsigned)1,splitter.nextBranchIndex() ); } TEST(PlantLoop,PlantLoop_Cost) { model::Model m; model::PlantLoop plantLoop(m); boost::optional<model::LifeCycleCost> cost = model::LifeCycleCost::createLifeCycleCost("Install", plantLoop, 1000.0, "CostPerEach", "Construction"); ASSERT_TRUE(cost); EXPECT_DOUBLE_EQ(1000.0, cost->totalCost()); }
29.178423
151
0.713311
bobzabcik
6190b65052ee23e0c319f5a0525ba42395867263
47,430
cpp
C++
src/projection/ossimMapProjection.cpp
eleaver/ossim
1e648adf31128b5be619b30d54d35ad0a5aa5606
[ "MIT" ]
null
null
null
src/projection/ossimMapProjection.cpp
eleaver/ossim
1e648adf31128b5be619b30d54d35ad0a5aa5606
[ "MIT" ]
null
null
null
src/projection/ossimMapProjection.cpp
eleaver/ossim
1e648adf31128b5be619b30d54d35ad0a5aa5606
[ "MIT" ]
null
null
null
//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: // // Base class for all map projections. // //******************************************************************* // $Id: ossimMapProjection.cpp 23418 2015-07-09 18:46:41Z gpotts $ #include <iostream> #include <cstdlib> #include <iomanip> #include <sstream> #include <ossim/projection/ossimMapProjection.h> #include <ossim/projection/ossimEpsgProjectionFactory.h> #include <ossim/base/ossimKeywordNames.h> #include <ossim/base/ossimKeywordlist.h> #include <ossim/base/ossimDatumFactoryRegistry.h> #include <ossim/base/ossimDpt.h> #include <ossim/base/ossimGpt.h> #include <ossim/base/ossimDatum.h> #include <ossim/base/ossimEllipsoid.h> #include <ossim/base/ossimString.h> #include <ossim/elevation/ossimElevManager.h> #include <ossim/base/ossimMatrix3x3.h> #include <ossim/base/ossimUnitConversionTool.h> #include <ossim/base/ossimUnitTypeLut.h> #include <ossim/base/ossimTrace.h> using namespace std; #define USE_MODEL_TRANSFORM 1 static ossimTrace traceDebug("ossimMapProjection:debug"); // RTTI information for the ossimMapProjection RTTI_DEF1(ossimMapProjection, "ossimMapProjection" , ossimProjection); ossimMapProjection::ossimMapProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin) :theEllipsoid(ellipsoid), theOrigin(origin), theDatum(origin.datum()), // force no shifting theUlGpt(0, 0), theUlEastingNorthing(0, 0), theFalseEastingNorthing(0, 0), thePcsCode(0), theElevationLookupFlag(false), theModelTransform(), theInverseModelTransform(), theProjectionUnits(OSSIM_METERS), theImageToModelAzimuth(0) { theModelTransform.setIdentity(); theInverseModelTransform.setIdentity(); theUlGpt = theOrigin; theUlEastingNorthing.makeNan(); theMetersPerPixel.makeNan(); theDegreesPerPixel.makeNan(); } ossimMapProjection::ossimMapProjection(const ossimMapProjection& src) : ossimProjection(src), theEllipsoid(src.theEllipsoid), theOrigin(src.theOrigin), theDatum(src.theDatum), theMetersPerPixel(src.theMetersPerPixel), theDegreesPerPixel(src.theDegreesPerPixel), theUlGpt(src.theUlGpt), theUlEastingNorthing(src.theUlEastingNorthing), theFalseEastingNorthing(src.theFalseEastingNorthing), thePcsCode(src.thePcsCode), theElevationLookupFlag(false), theModelTransform(src.theModelTransform), theInverseModelTransform(src.theInverseModelTransform), theProjectionUnits(src.theProjectionUnits), theImageToModelAzimuth(src.theImageToModelAzimuth) { } ossimMapProjection::~ossimMapProjection() { } ossimGpt ossimMapProjection::origin()const { return theOrigin; } void ossimMapProjection::setPcsCode(ossim_uint32 pcsCode) { thePcsCode = pcsCode; } ossim_uint32 ossimMapProjection::getPcsCode() const { // The PCS code is not always set when the projection is instantiated with explicit parameters, // since the code is only necessary when looking up those parameters in a database. However, it // is still necessary to recognize when an explicit projection coincides with an EPSG-specified // projection, and assign our PCS code to match it. So let's take this opportunity now to make // sure the PCS code is properly initialized. if (thePcsCode == 0) { thePcsCode = ossimEpsgProjectionDatabase::instance()->findProjectionCode(*this); if (thePcsCode == 0) thePcsCode = 32767; // user-defined (non-EPSG) projection } if (thePcsCode == 32767) return 0; // 32767 only used internally. To the rest of OSSIM, the PCS=0 is undefined return thePcsCode; } ossimString ossimMapProjection::getProjectionName() const { return getClassName(); } double ossimMapProjection::getA() const { return theEllipsoid.getA(); } double ossimMapProjection::getB() const { return theEllipsoid.getB(); } double ossimMapProjection::getF() const { return theEllipsoid.getFlattening(); } ossimDpt ossimMapProjection::getMetersPerPixel() const { return theMetersPerPixel; } const ossimDpt& ossimMapProjection::getDecimalDegreesPerPixel() const { return theDegreesPerPixel; } const ossimDpt& ossimMapProjection::getUlEastingNorthing() const { return theUlEastingNorthing; } const ossimGpt& ossimMapProjection::getUlGpt() const { return theUlGpt; } const ossimGpt& ossimMapProjection::getOrigin() const { return theOrigin; } const ossimDatum* ossimMapProjection::getDatum() const { return theDatum; } bool ossimMapProjection::isGeographic()const { return false; } void ossimMapProjection::setEllipsoid(const ossimEllipsoid& ellipsoid) { theEllipsoid = ellipsoid; update(); } void ossimMapProjection::setAB(double a, double b) { theEllipsoid.setA(a); theEllipsoid.setB(b); update(); } void ossimMapProjection::setDatum(const ossimDatum* datum) { if (!datum || (*theDatum == *datum)) return; theDatum = datum; theEllipsoid = *(theDatum->ellipsoid()); // Change the datum of the ossimGpt data members: theOrigin.changeDatum(theDatum); theUlGpt.changeDatum(theDatum); update(); // A change of datum usually implies a change of EPSG codes. Reset the PCS code. It will be // reestablished as needed in the getPcsCode() method: thePcsCode = 0; } void ossimMapProjection::setOrigin(const ossimGpt& origin) { // Set the origin and since the origin has a datum which in turn has // an ellipsoid, sync them up. // NOTE: Or perhaps we need to change the datum of the input origin to that of theDatum? (OLK 05/11) theOrigin = origin; theOrigin.changeDatum(theDatum); update(); } void ossimMapProjection::assign(const ossimProjection &aProjection) { if(&aProjection!=this) { ossimKeywordlist kwl; aProjection.saveState(kwl); loadState(kwl); } } void ossimMapProjection::update() { // if the delta lat and lon per pixel is set then // check to see if the meters were set. // if (!theDegreesPerPixel.hasNans() && theMetersPerPixel.hasNans()) { computeMetersPerPixel(); } else if (!theMetersPerPixel.hasNans()) { computeDegreesPerPixel(); } // compute the tie points if not already computed // // The tiepoint was specified either as easting/northing or lat/lon. Need to initialize the one // that has not been assigned yet: if (theUlEastingNorthing.hasNans() && !theUlGpt.hasNans()) theUlEastingNorthing = forward(theUlGpt); else if (theUlGpt.hasNans() && !theUlEastingNorthing.hasNans()) theUlGpt = inverse(theUlEastingNorthing); else if (theUlGpt.hasNans() && theUlEastingNorthing.hasNans()) { theUlGpt = theOrigin; theUlEastingNorthing = forward(theUlGpt); } if (theMetersPerPixel.hasNans() && theDegreesPerPixel.hasNans()) { ossimDpt mpd = ossimGpt().metersPerDegree(); if (isGeographic()) { theDegreesPerPixel.lat = 1.0 / mpd.y; theDegreesPerPixel.lon = 1.0 / mpd.x; computeMetersPerPixel(); } else { theMetersPerPixel.x = 1.0; theMetersPerPixel.y = 1.0; computeDegreesPerPixel(); } } // The last bit to do is the most important: Update the model transform so that we properly // convert between E, N and line, sample: updateTransform(); } void ossimMapProjection::setModelTransform (const ossimMatrix4x4& transform) { theModelTransform = transform; theInverseModelTransform = theModelTransform; theInverseModelTransform.i(); updateFromTransform(); } void ossimMapProjection::updateTransform() { // The transform contains the map rotation, GSD, and tiepoint. These individual parameters are // also saved in members theImageToModelAzimuth, theMetersPerPixel, and theUlEastingNorthing. // Any one of those may have changed requiring a new transform to be computed from the new // values. All calls to update() will also call this, so the rotation, scale and offset need // to be preserved to avoid blowing them away by resetting theModelTransform to identity. // Assumes model coordinates in meters: theModelTransform.setIdentity(); NEWMAT::Matrix& m = theModelTransform.getData(); double cosAz = 1.0, sinAz = 0.0; if (theImageToModelAzimuth != 0) { cosAz = ossim::cosd(theImageToModelAzimuth); sinAz = ossim::sind(theImageToModelAzimuth); } // Note that northing in the map projection is positive up, while in image space the y-axis // is positive is down, so apply that inversion by forcing theMetersPerPixel.y to be negative: // Scale and rotation: m[0][0] = theMetersPerPixel.x * cosAz; m[0][1] = -theMetersPerPixel.y * sinAz; m[1][0] = -theMetersPerPixel.x * sinAz; m[1][1] = -theMetersPerPixel.y * cosAz; // Offset: m[0][3] = theUlEastingNorthing.x; m[1][3] = theUlEastingNorthing.y; theInverseModelTransform = theModelTransform; theInverseModelTransform.i(); } void ossimMapProjection::updateFromTransform() { // Extract scale, rotation and offset from the transform matrix. Note that with scale, rotation, // and offset preserved in theMetersPerPixel, theImageToModelAzimuth, and theUlEastingNorthing, // respectively, the transform can be regenerated with a call to update(). const NEWMAT::Matrix& m = theModelTransform.getData(); theMetersPerPixel.x = sqrt(m[0][0]*m[0][0] + m[1][0]*m[1][0]); theMetersPerPixel.y = sqrt(m[0][1]*m[0][1] + m[1][1]*m[1][1]); theUlEastingNorthing.x = m[0][3]; theUlEastingNorthing.y = m[1][3]; theImageToModelAzimuth = ossim::acosd(m[0][0]/theMetersPerPixel.x); // The remaining code here could be a problem since concrete projection may not be fully // initialized! Override this method if needed. See ossimEquiDistCylProjection (OLK 01/20) if (theUlGpt.hasNans()) theUlGpt = inverse(theUlEastingNorthing); computeDegreesPerPixel(); } void ossimMapProjection::applyScale(const ossimDpt& scale, bool recenterTiePoint) { ossimDpt mapTieDpt; ossimGpt mapTieGpt; if (recenterTiePoint) { if (isGeographic()) { mapTieGpt = getUlGpt(); mapTieGpt.lat += theDegreesPerPixel.lat/2.0; mapTieGpt.lon -= theDegreesPerPixel.lon/2.0; } else { mapTieDpt = getUlEastingNorthing(); mapTieDpt.x -= theMetersPerPixel.x/2.0; mapTieDpt.y += theMetersPerPixel.y/2.0; } } theDegreesPerPixel.x *= scale.x; theDegreesPerPixel.y *= scale.y; theMetersPerPixel.x *= scale.x; theMetersPerPixel.y *= scale.y; if ( recenterTiePoint ) { if (isGeographic()) { mapTieGpt.lat -= theDegreesPerPixel.lat/2.0; mapTieGpt.lon += theDegreesPerPixel.lon/2.0; setUlTiePoints(mapTieGpt); } else { mapTieDpt.x += theMetersPerPixel.x/2.0; mapTieDpt.y -= theMetersPerPixel.y/2.0; setUlTiePoints(mapTieDpt); } } updateTransform(); } void ossimMapProjection::applyRotation(const double& azimuthDeg) { theImageToModelAzimuth += azimuthDeg; if (theImageToModelAzimuth >= 360.0) theImageToModelAzimuth -= 360.0; updateTransform(); } ossimDpt ossimMapProjection::worldToLineSample(const ossimGpt &worldPoint)const { ossimDpt result; worldToLineSample(worldPoint, result); return result; } ossimGpt ossimMapProjection::lineSampleToWorld(const ossimDpt &lineSample)const { ossimGpt result; lineSampleToWorld(lineSample, result); return result; } void ossimMapProjection::worldToLineSample(const ossimGpt &worldPoint, ossimDpt& lineSample) const { lineSample.makeNan(); if(worldPoint.isLatLonNan()) return; // Shift the world point to the datum being used by this projection, if defined: ossimGpt gpt = worldPoint; if ( theDatum ) gpt.changeDatum(theDatum); // Transform world point to model coordinates using the concrete map projection equations: ossimDpt modelPoint = forward(gpt); // Now convert map model coordinates to image line/sample space: eastingNorthingToLineSample(modelPoint, lineSample); } void ossimMapProjection::lineSampleHeightToWorld(const ossimDpt &lineSample, const double& hgtEllipsoid, ossimGpt& gpt)const { gpt.makeNan(); // make sure that the passed in lineSample is good and // check to make sure our easting northing is good so // we can compute the line sample. if(lineSample.hasNans()) return; // Transform image coordinates (line, sample) to model coordinates (easting, northing): ossimDpt modelPoint; lineSampleToEastingNorthing(lineSample, modelPoint); // Transform model coordinates to world point using concrete map projection equations: gpt = inverse(modelPoint); gpt.hgt = hgtEllipsoid; } void ossimMapProjection::lineSampleToWorld (const ossimDpt& lineSampPt, ossimGpt& worldPt) const { lineSampleHeightToWorld(lineSampPt, ossim::nan(), worldPt); if(theElevationLookupFlag) worldPt.hgt = ossimElevManager::instance()->getHeightAboveEllipsoid(worldPt); } void ossimMapProjection::lineSampleToEastingNorthing(const ossimDpt& lineSample, ossimDpt& eastingNorthing)const { #ifdef USE_MODEL_TRANSFORM // Transform according to 4x4 transform embedded in the projection: const NEWMAT::Matrix& m = theModelTransform.getData(); eastingNorthing.x = m[0][0]*lineSample.x + m[0][1]*lineSample.y + m[0][3]; eastingNorthing.y = m[1][0]*lineSample.x + m[1][1]*lineSample.y + m[1][3]; #else /** Performs image to model coordinate transformation. This implementation bypasses * theModelTransform. Probably should eventually switch to use theModelTransform * because this cannot handle map rotation. */ // make sure that the passed in lineSample is good and // check to make sure our easting northing is good so // we can compute the line sample. // if(lineSample.hasNans()||theUlEastingNorthing.hasNans()) { eastingNorthing.makeNan(); return; } ossimDpt deltaPoint = lineSample; eastingNorthing.x = theUlEastingNorthing.x + deltaPoint.x*theMetersPerPixel.x; eastingNorthing.y = theUlEastingNorthing.y + (-deltaPoint.y)*theMetersPerPixel.y ; // eastingNorthing.x += (lineSample.x*theMetersPerPixel.x); // Note: the Northing is positive up. In image space // the positive axis is down so we must multiply by // -1 // eastingNorthing.y += (-lineSample.y*theMetersPerPixel.y); #endif } void ossimMapProjection::eastingNorthingToLineSample(const ossimDpt& eastingNorthing, ossimDpt& lineSample)const { #ifdef USE_MODEL_TRANSFORM // Transform according to 4x4 transform embedded in the projection: const NEWMAT::Matrix& m = theInverseModelTransform.getData(); lineSample.x = m[0][0]*eastingNorthing.x + m[0][1]*eastingNorthing.y + m[0][3]; lineSample.y = m[1][0]*eastingNorthing.x + m[1][1]*eastingNorthing.y + m[1][3]; #else /** Performs model to image coordinate transformation. This implementation bypasses * theModelTransform. Probably should eventually switch to use equivalent theModelTransform * because this cannot handle map rotation. */ if(eastingNorthing.hasNans()) { lineSample.makeNan(); return; } // check the final result to make sure there were no // problems. // lineSample.x = (eastingNorthing.x - theUlEastingNorthing.x)/theMetersPerPixel.x; // We must remember that the Northing is negative since the positive // axis for an image is assumed to go down since it's image space. lineSample.y = (-(eastingNorthing.y-theUlEastingNorthing.y))/theMetersPerPixel.y; #endif } void ossimMapProjection::eastingNorthingToWorld(const ossimDpt& eastingNorthing, ossimGpt& worldPt)const { ossimDpt lineSample; eastingNorthingToLineSample(eastingNorthing, lineSample); lineSampleToWorld(lineSample, worldPt); } void ossimMapProjection::setMetersPerPixel(const ossimDpt& resolution) { theMetersPerPixel = resolution; computeDegreesPerPixel(); updateTransform(); } void ossimMapProjection::setDecimalDegreesPerPixel(const ossimDpt& resolution) { theDegreesPerPixel = resolution; computeMetersPerPixel(); // this method will update the transform updateTransform(); } void ossimMapProjection::setUlTiePoints(const ossimGpt& gpt) { setUlGpt(gpt); } void ossimMapProjection::setUlTiePoints(const ossimDpt& eastingNorthing) { setUlEastingNorthing(eastingNorthing); } void ossimMapProjection::setUlEastingNorthing(const ossimDpt& ulEastingNorthing) { theUlEastingNorthing = ulEastingNorthing; theUlGpt = inverse(ulEastingNorthing); updateTransform(); } void ossimMapProjection::setUlGpt(const ossimGpt& ulGpt) { theUlGpt = ulGpt; // The ossimGpt data members need to use the same datum as this projection: if (*theDatum != *(ulGpt.datum())) theUlGpt.changeDatum(theDatum); // Adjust the stored easting / northing. theUlEastingNorthing = forward(theUlGpt); updateTransform(); } bool ossimMapProjection::saveState(ossimKeywordlist& kwl, const char* prefix) const { ossimProjection::saveState(kwl, prefix); kwl.add(prefix, ossimKeywordNames::ORIGIN_LATITUDE_KW, theOrigin.latd(), true); kwl.add(prefix, ossimKeywordNames::CENTRAL_MERIDIAN_KW, theOrigin.lond(), true); theEllipsoid.saveState(kwl, prefix); if(theDatum) { kwl.add(prefix, ossimKeywordNames::DATUM_KW, theDatum->code(), true); } // Calling access method to give it an opportunity to update the code in case of param change: ossim_uint32 code = getPcsCode(); if (code) { ossimString epsg_spec = ossimString("EPSG:") + ossimString::toString(code); kwl.add(prefix, ossimKeywordNames::SRS_NAME_KW, epsg_spec, true); } if(isGeographic()) { kwl.add(prefix, ossimKeywordNames::TIE_POINT_XY_KW, ossimDpt(theUlGpt).toString().c_str(), true); kwl.add(prefix, ossimKeywordNames::TIE_POINT_UNITS_KW, ossimUnitTypeLut::instance()->getEntryString(OSSIM_DEGREES), true); kwl.add(prefix, ossimKeywordNames::PIXEL_SCALE_XY_KW, theDegreesPerPixel.toString().c_str(), true); kwl.add(prefix, ossimKeywordNames::PIXEL_SCALE_UNITS_KW, ossimUnitTypeLut::instance()->getEntryString(OSSIM_DEGREES), true); } else { kwl.add(prefix, ossimKeywordNames::TIE_POINT_XY_KW, theUlEastingNorthing.toString().c_str(), true); kwl.add(prefix, ossimKeywordNames::TIE_POINT_UNITS_KW, ossimUnitTypeLut::instance()->getEntryString(OSSIM_METERS), true); kwl.add(prefix, ossimKeywordNames::PIXEL_SCALE_XY_KW, theMetersPerPixel.toString().c_str(), true); kwl.add(prefix, ossimKeywordNames::PIXEL_SCALE_UNITS_KW, ossimUnitTypeLut::instance()->getEntryString(OSSIM_METERS), true); } kwl.add(prefix, ossimKeywordNames::PCS_CODE_KW, code, true); kwl.add(prefix, ossimKeywordNames::FALSE_EASTING_NORTHING_KW, theFalseEastingNorthing.toString().c_str(), true); kwl.add(prefix, ossimKeywordNames::FALSE_EASTING_NORTHING_UNITS_KW, ossimUnitTypeLut::instance()->getEntryString(OSSIM_METERS), true); kwl.add(prefix, ossimKeywordNames::ELEVATION_LOOKUP_FLAG_KW, ossimString::toString(theElevationLookupFlag), true); kwl.add(prefix, ossimKeywordNames::ORIGINAL_MAP_UNITS_KW, ossimUnitTypeLut::instance()->getEntryString(theProjectionUnits), true); kwl.add(prefix, ossimKeywordNames::IMAGE_MODEL_ROTATION_KW, theImageToModelAzimuth, true); if (theImageToModelAzimuth != 0.0) { ostringstream xformstr; xformstr << theModelTransform << ends; kwl.add(prefix, ossimKeywordNames::IMAGE_MODEL_TRANSFORM_MATRIX_KW, xformstr.str().c_str(), true); kwl.add(prefix, ossimKeywordNames::IMAGE_MODEL_TRANSFORM_UNIT_KW, ossimUnitTypeLut::instance()->getEntryString(OSSIM_METERS), true); } return true; } bool ossimMapProjection::loadState(const ossimKeywordlist& kwl, const char* prefix) { ossimProjection::loadState(kwl, prefix); // Initialize the image-to-map transform to identity (no scale, rotation, or offset): theModelTransform.setIdentity(); theInverseModelTransform.setIdentity(); const char* elevLookupFlag = kwl.find(prefix, ossimKeywordNames::ELEVATION_LOOKUP_FLAG_KW); if(elevLookupFlag) { theElevationLookupFlag = ossimString(elevLookupFlag).toBool(); } // Get the ellipsoid. theEllipsoid.loadState(kwl, prefix); const char *lookup = nullptr; // Get the Projection Coordinate System (assumed from EPSG database). // NOTE: the code is read here for saving in this object only. // The code is not verified until a call to getPcs() is called. If ONLY this code // had been provided, then the EPSG projection factory would populate a new instance of the // corresponding map projection and have it saveState for constructing again later in the // conventional fashion here thePcsCode = 0; lookup = kwl.find(prefix, ossimKeywordNames::PCS_CODE_KW); if(lookup) thePcsCode = ossimString(lookup).toUInt32(); // EPSG PROJECTION CODE // The datum can be specified in 2 ways: either via OSSIM/geotrans alpha-codes or EPSG code. // Last resort use WGS 84 (consider throwing an exception to catch any bad datums): theDatum = ossimDatumFactoryRegistry::instance()->create(kwl, prefix); if (theDatum == NULL) { theDatum = ossimDatumFactory::instance()->wgs84(); } // Set all ossimGpt-type members to use this datum: theOrigin.datum(theDatum); theUlGpt.datum(theDatum); // Fetch the ellipsoid from the datum: const ossimEllipsoid* ellipse = theDatum->ellipsoid(); if(ellipse) theEllipsoid = *ellipse; // Get the latitude of the origin. lookup = kwl.find(prefix, ossimKeywordNames::ORIGIN_LATITUDE_KW); if (lookup) { theOrigin.latd(ossimString(lookup).toFloat64()); } // else ??? // Get the central meridian. lookup = kwl.find(prefix, ossimKeywordNames::CENTRAL_MERIDIAN_KW); if (lookup) { theOrigin.lond(ossimString(lookup).toFloat64()); } // else ??? // Get the pixel scale. theMetersPerPixel.makeNan(); theDegreesPerPixel.makeNan(); lookup = kwl.find(prefix, ossimKeywordNames::PIXEL_SCALE_UNITS_KW); if (lookup) { ossimUnitType units = static_cast<ossimUnitType>(ossimUnitTypeLut::instance()-> getEntryNumber(lookup)); lookup = kwl.find(prefix, ossimKeywordNames::PIXEL_SCALE_XY_KW); if (lookup) { ossimDpt scale; scale.toPoint(std::string(lookup)); switch (units) { case OSSIM_METERS: { theMetersPerPixel = scale; break; } case OSSIM_DEGREES: { theDegreesPerPixel.x = scale.x; theDegreesPerPixel.y = scale.y; break; } case OSSIM_FEET: case OSSIM_US_SURVEY_FEET: { ossimUnitConversionTool ut; ut.setValue(scale.x, units); theMetersPerPixel.x = ut.getValue(OSSIM_METERS); ut.setValue(scale.y, units); theMetersPerPixel.y = ut.getValue(OSSIM_METERS); break; } default: { if(traceDebug()) { // Unhandled unit type! ossimNotify(ossimNotifyLevel_WARN) << "ossimMapProjection::loadState WARNING!" << "Unhandled unit type for " << ossimKeywordNames::PIXEL_SCALE_UNITS_KW << ": " << ( ossimUnitTypeLut::instance()-> getEntryString(units).c_str() ) << endl; } break; } } // End of switch (units) } // End of if (PIXEL_SCALE_XY) } // End of if (PIXEL_SCALE_UNITS) else { // BACKWARDS COMPATIBILITY LOOKUPS... lookup = kwl.find(prefix, ossimKeywordNames::METERS_PER_PIXEL_X_KW); if(lookup) { theMetersPerPixel.x = fabs(ossimString(lookup).toFloat64()); } lookup = kwl.find(prefix, ossimKeywordNames::METERS_PER_PIXEL_Y_KW); if(lookup) { theMetersPerPixel.y = fabs(ossimString(lookup).toFloat64()); } lookup = kwl.find(prefix, ossimKeywordNames::DECIMAL_DEGREES_PER_PIXEL_LAT); if(lookup) { theDegreesPerPixel.y = fabs(ossimString(lookup).toFloat64()); } lookup = kwl.find(prefix, ossimKeywordNames::DECIMAL_DEGREES_PER_PIXEL_LON); if(lookup) { theDegreesPerPixel.x = fabs(ossimString(lookup).toFloat64()); } } // Get the tie point. theUlGpt.makeNan(); // Since this won't be picked up from keywords set to 0 to keep nan out. theUlGpt.hgt = 0.0; theUlEastingNorthing.makeNan(); lookup = kwl.find(prefix, ossimKeywordNames::TIE_POINT_UNITS_KW); if (lookup) { ossimUnitType units = static_cast<ossimUnitType>(ossimUnitTypeLut::instance()-> getEntryNumber(lookup)); lookup = kwl.find(prefix, ossimKeywordNames::TIE_POINT_XY_KW); if (lookup) { ossimDpt tie; tie.toPoint(std::string(lookup)); switch (units) { case OSSIM_METERS: { theUlEastingNorthing = tie; break; } case OSSIM_DEGREES: { theUlGpt.lond(tie.x); theUlGpt.latd(tie.y); break; } case OSSIM_FEET: case OSSIM_US_SURVEY_FEET: { ossimUnitConversionTool ut; ut.setValue(tie.x, units); theUlEastingNorthing.x = ut.getValue(OSSIM_METERS); ut.setValue(tie.y, units); theUlEastingNorthing.y = ut.getValue(OSSIM_METERS); break; } default: { if(traceDebug()) { // Unhandled unit type! ossimNotify(ossimNotifyLevel_WARN) << "ossimMapProjection::loadState WARNING!" << "Unhandled unit type for " << ossimKeywordNames::TIE_POINT_UNITS_KW << ": " << ( ossimUnitTypeLut::instance()-> getEntryString(units).c_str() ) << endl; } break; } } // End of switch (units) } // End of if (TIE_POINT_XY) } // End of if (TIE_POINT_UNITS) else { // BACKWARDS COMPATIBILITY LOOKUPS... lookup = kwl.find(prefix, ossimKeywordNames::TIE_POINT_EASTING_KW); if(lookup) { theUlEastingNorthing.x = (ossimString(lookup).toFloat64()); } lookup = kwl.find(prefix, ossimKeywordNames::TIE_POINT_NORTHING_KW); if(lookup) { theUlEastingNorthing.y = (ossimString(lookup).toFloat64()); } lookup = kwl.find(prefix, ossimKeywordNames::TIE_POINT_LAT_KW); if (lookup) { theUlGpt.latd(ossimString(lookup).toFloat64()); } lookup = kwl.find(prefix, ossimKeywordNames::TIE_POINT_LON_KW); if (lookup) { theUlGpt.lond(ossimString(lookup).toFloat64()); } } // Get the false easting northing. theFalseEastingNorthing.x = 0.0; theFalseEastingNorthing.y = 0.0; ossimUnitType en_units = OSSIM_METERS; lookup = kwl.find(prefix, ossimKeywordNames::FALSE_EASTING_NORTHING_UNITS_KW); if (lookup) { en_units = static_cast<ossimUnitType>(ossimUnitTypeLut::instance()->getEntryNumber(lookup)); } lookup = kwl.find(prefix, ossimKeywordNames::FALSE_EASTING_NORTHING_KW); if (lookup) { ossimDpt eastingNorthing; eastingNorthing.toPoint(std::string(lookup)); switch (en_units) { case OSSIM_METERS: { theFalseEastingNorthing = eastingNorthing; break; } case OSSIM_FEET: case OSSIM_US_SURVEY_FEET: { ossimUnitConversionTool ut; ut.setValue(eastingNorthing.x, en_units); theFalseEastingNorthing.x = ut.getValue(OSSIM_METERS); ut.setValue(eastingNorthing.y, en_units); theFalseEastingNorthing.y = ut.getValue(OSSIM_METERS); break; } default: { if(traceDebug()) { // Unhandled unit type! ossimNotify(ossimNotifyLevel_WARN) << "ossimMapProjection::loadState WARNING! Unhandled unit type for " << ossimKeywordNames::FALSE_EASTING_NORTHING_UNITS_KW << ": " << (ossimUnitTypeLut::instance()->getEntryString(en_units).c_str()) << endl; } break; } } // End of switch (units) } // End of if (FALSE_EASTING_NORTHING_KW) else { // BACKWARDS COMPATIBILITY LOOKUPS... lookup = kwl.find(prefix, ossimKeywordNames::FALSE_EASTING_KW); if(lookup) { theFalseEastingNorthing.x = (ossimString(lookup).toFloat64()); } lookup = kwl.find(prefix, ossimKeywordNames::FALSE_NORTHING_KW); if(lookup) { theFalseEastingNorthing.y = (ossimString(lookup).toFloat64()); } } // if((theDegreesPerPixel.x!=OSSIM_DBL_NAN)&& // (theDegreesPerPixel.y!=OSSIM_DBL_NAN)&& // theMetersPerPixel.hasNans()) // { // theMetersPerPixel = theOrigin.metersPerDegree(); // theMetersPerPixel.x *= theDegreesPerPixel.x; // theMetersPerPixel.y *= theDegreesPerPixel.y; // } lookup = kwl.find(prefix, ossimKeywordNames::PIXEL_TYPE_KW); if (lookup) { ossimString pixelType = lookup; pixelType=pixelType.trim(); if(pixelType!="") { pixelType.downcase(); if(pixelType.contains("area")) { if( theMetersPerPixel.hasNans() == false) { if(!theUlEastingNorthing.hasNans()) { theUlEastingNorthing.x += (theMetersPerPixel.x*0.5); theUlEastingNorthing.y -= (theMetersPerPixel.y*0.5); } } if(theDegreesPerPixel.hasNans() == false) { theUlGpt.latd( theUlGpt.latd() - (theDegreesPerPixel.y*0.5) ); theUlGpt.lond( theUlGpt.lond() + (theDegreesPerPixel.x*0.5) ); } } } } // We preserve the units of the originally created projection (typically from EPSG proj factory) // in case user needs map coordinates in those units (versus default meters) lookup = kwl.find(prefix, ossimKeywordNames::ORIGINAL_MAP_UNITS_KW); if (lookup) { theProjectionUnits = static_cast<ossimUnitType>(ossimUnitTypeLut::instance()->getEntryNumber(lookup)); } // Possible map-to-image rotation handled by theModelTransform: lookup = kwl.find(prefix, ossimKeywordNames::IMAGE_MODEL_ROTATION_KW); if (lookup) { theImageToModelAzimuth = ossimString(lookup).toFloat64(); } #if 0 theModelUnitType = OSSIM_UNIT_UNKNOWN; const char* mapUnit = kwl.find(prefix, ossimKeywordNames::IMAGE_MODEL_TRANSFORM_UNIT_KW); theModelUnitType = static_cast<ossimUnitType>(ossimUnitTypeLut::instance()->getEntryNumber(mapUnit)); #endif //--- // Set the datum of the origin and tie point. // Use method that does NOT perform a shift. //--- if (theDatum) { theOrigin.datum(theDatum); theUlGpt.datum(theDatum); } if (theMetersPerPixel.hasNans() && theDegreesPerPixel.hasNans()) { ossimDpt mpd = ossimGpt().metersPerDegree(); if (isGeographic()) { theDegreesPerPixel.lat = 1.0/mpd.y; theDegreesPerPixel.lon = 1.0/mpd.y; } else { theMetersPerPixel.x = 1.0; theMetersPerPixel.y = 1.0; } } ossimString transformElems = kwl.find(prefix, ossimKeywordNames::IMAGE_MODEL_TRANSFORM_MATRIX_KW); if (!transformElems.empty()) { // The model transform trumps (I hate that word) settings for scale, rotation, and map offset: vector<ossimString> elements = transformElems.split(" "); NEWMAT::Matrix& m = theModelTransform.getData(); // At this scope for IDE debugging if (elements.size() != 16) { ossimNotify(ossimNotifyLevel_WARN) << __FILE__ << ": " << __LINE__<< "\nossimMapProjection::loadState ERROR: Model " "Transform matrix must have 16 elements!"<< std::endl; } else { int i = 0; for (ossimString &e : elements) { m[i / 4][i % 4] = e.toDouble(); ++i; } } // If the transform is given in degrees, need to convert it to meters to work with geotrans: ossimString unitstr = kwl.find(prefix, ossimKeywordNames::IMAGE_MODEL_TRANSFORM_UNIT_KW); ossim_uint32 unitsId = ossimUnitTypeLut::instance()->getEntryNumber(unitstr.c_str()); if (unitsId == OSSIM_DEGREES) convertImageModelTransformToMeters(); // This pulls the UL tiepoint from the offset terms if needed theInverseModelTransform = theModelTransform; theInverseModelTransform.i(); updateFromTransform(); // This calls the concrete projection to perform inverse proj, but it may not be initialize! (OLK 01/20) } else { // No model transform matrix was provided, so calculate it given scale rotation and offset: update(); } return true; } std::ostream& ossimMapProjection::print(std::ostream& out) const { const char MODULE[] = "ossimMapProjection::print"; out << setiosflags(ios::fixed) << setprecision(15) << "\n// " << MODULE << "\n" << ossimKeywordNames::TYPE_KW << ": " << getClassName() << "\n" << ossimKeywordNames::MAJOR_AXIS_KW << ": " << theEllipsoid.getA() << "\n" << ossimKeywordNames::MINOR_AXIS_KW << ": " << theEllipsoid.getB() << "\n" << ossimKeywordNames::ORIGIN_LATITUDE_KW << ": " << theOrigin.latd() << "\n" << ossimKeywordNames::CENTRAL_MERIDIAN_KW << ": " << theOrigin.lond() << "\norigin: " << theOrigin << "\n" << ossimKeywordNames::DATUM_KW << ": " << (theDatum?theDatum->code().c_str():"unknown") << "\n" << ossimKeywordNames::METERS_PER_PIXEL_X_KW << ": " << ((ossim::isnan(theMetersPerPixel.x))?ossimString("nan"):ossimString::toString(theMetersPerPixel.x, 15)) << "\n" << ossimKeywordNames::METERS_PER_PIXEL_Y_KW << ": " << ((ossim::isnan(theMetersPerPixel.y))?ossimString("nan"):ossimString::toString(theMetersPerPixel.y, 15)) << "\n" << ossimKeywordNames::FALSE_EASTING_NORTHING_KW << ": " << theFalseEastingNorthing.toString().c_str() << "\n" << ossimKeywordNames::FALSE_EASTING_NORTHING_UNITS_KW << ": " << ossimUnitTypeLut::instance()->getEntryString(OSSIM_METERS) << "\n" << ossimKeywordNames::PCS_CODE_KW << ": " << thePcsCode << "\n" << ossimKeywordNames::IMAGE_MODEL_ROTATION_KW << ": " << theImageToModelAzimuth; const NEWMAT::Matrix& m = theModelTransform.getData(); out << "\nImageModelTransform [2x3]: "<<m[0][0]<<" "<<m[0][1]<<" "<<m[0][3] << "\n "<<m[1][0]<<" "<<m[1][1]<<" "<<m[1][3]; if(isGeographic()) { out << "\n" << ossimKeywordNames::TIE_POINT_XY_KW << ": " << ossimDpt(theUlGpt).toString().c_str() << "\n" << ossimKeywordNames::TIE_POINT_UNITS_KW << ": " << ossimUnitTypeLut::instance()->getEntryString(OSSIM_DEGREES) << "\n" << ossimKeywordNames::PIXEL_SCALE_XY_KW << ": " << theDegreesPerPixel.toString().c_str() << "\n" << ossimKeywordNames::PIXEL_SCALE_UNITS_KW << ": " << ossimUnitTypeLut::instance()->getEntryString(OSSIM_DEGREES) << std::endl; } else { out << "\n" << ossimKeywordNames::TIE_POINT_XY_KW << ": " << theUlEastingNorthing.toString().c_str() << "\n" << ossimKeywordNames::TIE_POINT_UNITS_KW << ": " << ossimUnitTypeLut::instance()->getEntryString(OSSIM_METERS) << "\n" << ossimKeywordNames::PIXEL_SCALE_XY_KW << ": " << theMetersPerPixel.toString().c_str() << "\n" << ossimKeywordNames::PIXEL_SCALE_UNITS_KW << ": " << ossimUnitTypeLut::instance()->getEntryString(OSSIM_METERS) << std::endl; } return ossimProjection::print(out); } void ossimMapProjection::computeDegreesPerPixel() { ossimDpt eastNorthGround = forward(theOrigin); ossimDpt rightEastNorth = eastNorthGround; ossimDpt downEastNorth = eastNorthGround; rightEastNorth.x += theMetersPerPixel.x; downEastNorth.y -= theMetersPerPixel.y; ossimGpt rightGpt = inverse(rightEastNorth); ossimGpt downGpt = inverse(downEastNorth); // use euclidean distance to get length along the horizontal (lon) // and vertical (lat) directions // double tempDeltaLat = rightGpt.latd() - theOrigin.latd(); double tempDeltaLon = rightGpt.lond() - theOrigin.lond(); theDegreesPerPixel.lon = sqrt(tempDeltaLat*tempDeltaLat + tempDeltaLon*tempDeltaLon); tempDeltaLat = downGpt.latd() - theOrigin.latd(); tempDeltaLon = downGpt.lond() - theOrigin.lond(); theDegreesPerPixel.lat = sqrt(tempDeltaLat*tempDeltaLat + tempDeltaLon*tempDeltaLon); } void ossimMapProjection::computeMetersPerPixel() { //#define USE_OSSIMGPT_METERS_PER_DEGREE #ifdef USE_OSSIMGPT_METERS_PER_DEGREE ossimDpt metersPerDegree (theOrigin.metersPerDegree()); theMetersPerPixel.x = metersPerDegree.x * theDegreesPerPixel.lon; theMetersPerPixel.y = metersPerDegree.y * theDegreesPerPixel.lat; #elif USE_MODEL_TRANSFORM_XXX // Not working so hide // Transform according to 4x4 transform embedded in the projection: const NEWMAT::Matrix& m = theModelTransform.getData(); theMetersPerPixel.x = sqrt(m[0][0]*m[0][0] + m[1][0]*m[1][0]); theMetersPerPixel.y = sqrt(m[0][1]*m[0][1] + m[1][1]*m[1][1]); #else ossimGpt right=theOrigin; ossimGpt down=theOrigin; down.latd(theOrigin.latd() + theDegreesPerPixel.lat); right.lond(theOrigin.lond() + theDegreesPerPixel.lon); ossimDpt centerMeters = forward(theOrigin); ossimDpt rightMeters = forward(right); ossimDpt downMeters = forward(down); theMetersPerPixel.x = (rightMeters - centerMeters).length(); theMetersPerPixel.y = (downMeters - centerMeters).length(); #endif } //************************************************************************************************** // METHOD: ossimMapProjection::operator== //! Compares this to arg projection and returns TRUE if the same. //! NOTE: As currently implemented in OSSIM, map projections also contain image geometry //! information like tiepoint and scale. This operator is only concerned with the map //! specification and ignores image geometry differences. //************************************************************************************************** bool ossimMapProjection::operator==(const ossimProjection& projection) const { // Verify that derived types match: if (getClassName() != projection.getClassName()) return false; // If both PCS codes are non-zero, that's all we need to check: // unless there are model transforms // const ossimMapProjection* mapProj = dynamic_cast<const ossimMapProjection*>(&projection); if(!mapProj) return false; if (thePcsCode && mapProj->thePcsCode && (thePcsCode != 32767) && (thePcsCode == mapProj->thePcsCode) ) { return true; } if ( *theDatum != *(mapProj->theDatum) ) return false; if (theOrigin != mapProj->theOrigin) return false; if (theFalseEastingNorthing != mapProj->theFalseEastingNorthing) return false; #if 0 THIS SECTION IGNORED SINCE IT DEALS WITH IMAGE GEOMETRY, NOT MAP PROJECTION if((theModelTransform.getData() != mapProj->theModelTransform.getData())) return false; #endif return true; } bool ossimMapProjection::isEqualTo(const ossimObject& obj, ossimCompareType compareType)const { const ossimMapProjection* mapProj = dynamic_cast<const ossimMapProjection*>(&obj); bool result = mapProj&&ossimProjection::isEqualTo(obj, compareType); if(result) { result = (theEllipsoid.isEqualTo(mapProj->theEllipsoid, compareType)&& theOrigin.isEqualTo(mapProj->theOrigin, compareType)&& theMetersPerPixel.isEqualTo(mapProj->theMetersPerPixel, compareType)&& theDegreesPerPixel.isEqualTo(mapProj->theDegreesPerPixel, compareType)&& theUlGpt.isEqualTo(mapProj->theUlGpt, compareType)&& theUlEastingNorthing.isEqualTo(mapProj->theUlEastingNorthing, compareType)&& theFalseEastingNorthing.isEqualTo(mapProj->theFalseEastingNorthing, compareType)&& (thePcsCode == mapProj->thePcsCode)&& (theElevationLookupFlag == mapProj->theElevationLookupFlag)&& (theModelTransform.isEqualTo(mapProj->theModelTransform))); if(result) { if(compareType == OSSIM_COMPARE_FULL) { if(theDatum&&mapProj->theDatum) { result = theDatum->isEqualTo(*mapProj->theDatum, compareType); } } else { result = (theDatum==mapProj->theDatum); } } } return result; } double ossimMapProjection::getFalseEasting() const { return theFalseEastingNorthing.x; } double ossimMapProjection::getFalseNorthing() const { return theFalseEastingNorthing.y; } double ossimMapProjection::getStandardParallel1() const { return 0.0; } double ossimMapProjection::getStandardParallel2() const { return 0.0; } void ossimMapProjection::snapTiePointTo(ossim_float64 multiple, ossimUnitType unitType) { ossim_float64 convertedMultiple = multiple; if (isGeographic() && (unitType != OSSIM_DEGREES) ) { // Convert to degrees. ossimUnitConversionTool convertor; convertor.setOrigin(theOrigin); convertor.setValue(multiple, unitType); convertedMultiple = convertor.getDegrees(); } else if ( !isGeographic() && (unitType != OSSIM_METERS) ) { // Convert to meters. ossimUnitConversionTool convertor; convertor.setOrigin(theOrigin); convertor.setValue(multiple, unitType); convertedMultiple = convertor.getMeters(); } // Convert the tie point. if (isGeographic()) { // Snap the latitude. ossim_float64 d = theUlGpt.latd(); d = ossim::round<int>(d / convertedMultiple) * convertedMultiple; theUlGpt.latd(d); // Snap the longitude. d = theUlGpt.lond(); d = ossim::round<int>(d / convertedMultiple) * convertedMultiple; theUlGpt.lond(d); // Adjust the stored easting / northing. theUlEastingNorthing = forward(theUlGpt); } else { // Snap the easting. ossim_float64 d = theUlEastingNorthing.x - getFalseEasting(); d = ossim::round<int>(d / convertedMultiple) * convertedMultiple; theUlEastingNorthing.x = d + getFalseEasting(); // Snap the northing. d = theUlEastingNorthing.y - getFalseNorthing(); d = ossim::round<int>(d / convertedMultiple) * convertedMultiple; theUlEastingNorthing.y = d + getFalseNorthing(); // Adjust the stored upper left ground point. theUlGpt = inverse(theUlEastingNorthing); } updateTransform(); } void ossimMapProjection::snapTiePointToOrigin() { // Convert the tie point. if (isGeographic()) { // Note the origin may not be 0.0, 0.0: // Snap the latitude. ossim_float64 d = theUlGpt.latd() - origin().latd(); d = ossim::round<int>(d / theDegreesPerPixel.y) * theDegreesPerPixel.y; theUlGpt.latd(d + origin().latd()); // Snap the longitude. d = theUlGpt.lond() - origin().lond(); d = ossim::round<int>(d / theDegreesPerPixel.x) * theDegreesPerPixel.x; theUlGpt.lond(d + origin().lond()); // Adjust the stored easting / northing. theUlEastingNorthing = forward(theUlGpt); } else { // Snap the easting. ossim_float64 d = theUlEastingNorthing.x - getFalseEasting(); d = ossim::round<int>(d / theMetersPerPixel.x) * theMetersPerPixel.x; theUlEastingNorthing.x = d + getFalseEasting(); // Snap the northing. d = theUlEastingNorthing.y - getFalseNorthing(); d = ossim::round<int>(d / theMetersPerPixel.y) * theMetersPerPixel.y; theUlEastingNorthing.y = d + getFalseNorthing(); // Adjust the stored upper left ground point. theUlGpt = inverse(theUlEastingNorthing); } updateTransform(); } void ossimMapProjection::setElevationLookupFlag(bool flag) { theElevationLookupFlag = flag; } bool ossimMapProjection::getElevationLookupFlag()const { return theElevationLookupFlag; } void ossimMapProjection::convertImageModelTransformToMeters() { ossimEllipsoid ellipsoid; double f = ellipsoid.flattening(); double es2 = 2 * f - f * f; double es4 = es2 * es2; double es6 = es4 * es2; double Ra = ellipsoid.a() * (1.0 - es2 / 6.0 - 17.0 * es4 / 360.0 - 67.0 * es6 /3024.0); NEWMAT::Matrix& m = theModelTransform.getData(); // A bit of a hack here, This may be the only place to recover the decimal degrees origin pt: if (theUlGpt.hasNans()) { theUlGpt.lat = m[1][3]; theUlGpt.lon = m[0][3]; } double refLat = m[1][3] * RAD_PER_DEG; double dn_dp = Ra * RAD_PER_DEG; double de_dl = dn_dp * cos(refLat); m[0][0] *= de_dl; m[0][1] *= de_dl; m[0][3] *= de_dl; m[1][0] *= dn_dp; m[1][1] *= dn_dp; m[1][3] *= dn_dp; }
32.823529
134
0.643496
eleaver
6191e0391e29c5328daecd47f087f142d541cf26
2,725
cpp
C++
src/ngraph/runtime/plaidml/plaidml_pass_concat_split.cpp
magrawal128/ngraph
ca911487d1eadfe6ec66dbe3da6f05cee3645b24
[ "Apache-2.0" ]
1
2019-12-27T05:47:23.000Z
2019-12-27T05:47:23.000Z
src/ngraph/runtime/plaidml/plaidml_pass_concat_split.cpp
biswajitcsecu/ngraph
d6bff37d7968922ef81f3bed63379e849fcf3b45
[ "Apache-2.0" ]
null
null
null
src/ngraph/runtime/plaidml/plaidml_pass_concat_split.cpp
biswajitcsecu/ngraph
d6bff37d7968922ef81f3bed63379e849fcf3b45
[ "Apache-2.0" ]
null
null
null
//***************************************************************************** // Copyright 2017-2019 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //***************************************************************************** #include "ngraph/runtime/plaidml/plaidml_pass_concat_split.hpp" #include "ngraph/graph_util.hpp" #include "ngraph/op/concat.hpp" #include "ngraph/pattern/matcher.hpp" #include "ngraph/pattern/op/label.hpp" static std::size_t kMaxConcatInputs = 8; ngraph::runtime::plaidml::pass::ConcatSplit::ConcatSplit() { auto concat_op = std::make_shared<pattern::op::Label>(element::i8, Shape{}, [](std::shared_ptr<Node> node) { auto op = dynamic_cast<ngraph::op::Concat*>(node.get()); return op != nullptr && kMaxConcatInputs < op->get_input_size(); }); auto callback = [](pattern::Matcher& m) { auto concat = std::static_pointer_cast<ngraph::op::Concat>(m.get_match_root()); auto args = concat->get_arguments(); while (1 < args.size()) { NodeVector new_args; auto b = args.begin(); auto e = args.end(); while (b != e) { NodeVector::iterator p; if (e < b + kMaxConcatInputs) { p = e; } else { p = b + kMaxConcatInputs; } if (p - b == 1) { new_args.emplace_back(*b); } else { NodeVector sub_args; for (auto n = b; n != p; ++n) { sub_args.push_back(*n); } new_args.emplace_back(std::make_shared<ngraph::op::Concat>( std::move(sub_args), concat->get_concatenation_axis())); } b = p; } args = std::move(new_args); } replace_node(std::move(concat), args[0]); return true; }; add_matcher(std::make_shared<pattern::Matcher>(concat_op), callback); }
34.935897
99
0.507523
magrawal128
6192705d3a896a7240b7921148ce1a46d505c305
36,460
cpp
C++
game/state/shared/agent.cpp
Skin36/OpenApoc
ab333c6fe8d0dcfc96f044482a38ef81c10442a5
[ "MIT" ]
null
null
null
game/state/shared/agent.cpp
Skin36/OpenApoc
ab333c6fe8d0dcfc96f044482a38ef81c10442a5
[ "MIT" ]
null
null
null
game/state/shared/agent.cpp
Skin36/OpenApoc
ab333c6fe8d0dcfc96f044482a38ef81c10442a5
[ "MIT" ]
null
null
null
#include "game/state/shared/agent.h" #include "framework/framework.h" #include "game/state/battle/ai/aitype.h" #include "game/state/battle/battleunit.h" #include "game/state/city/agentmission.h" #include "game/state/city/base.h" #include "game/state/city/building.h" #include "game/state/city/city.h" #include "game/state/city/facility.h" #include "game/state/city/scenery.h" #include "game/state/city/vehicle.h" #include "game/state/gameevent.h" #include "game/state/gamestate.h" #include "game/state/rules/aequipmenttype.h" #include "game/state/rules/city/scenerytiletype.h" #include "game/state/shared/aequipment.h" #include "game/state/shared/organisation.h" #include "game/state/tilemap/tileobject_scenery.h" #include "library/strings_format.h" #include <glm/glm.hpp> namespace OpenApoc { static const unsigned TICKS_PER_PHYSICAL_TRAINING = 4 * TICKS_PER_HOUR; static const unsigned TICKS_PER_PSI_TRAINING = 4 * TICKS_PER_HOUR; sp<Agent> Agent::get(const GameState &state, const UString &id) { auto it = state.agents.find(id); if (it == state.agents.end()) { LogError("No agent matching ID \"%s\"", id); return nullptr; } return it->second; } const UString &Agent::getPrefix() { static UString prefix = "AGENT_"; return prefix; } const UString &Agent::getTypeName() { static UString name = "Agent"; return name; } const UString &Agent::getId(const GameState &state, const sp<Agent> ptr) { static const UString emptyString = ""; for (auto &a : state.agents) { if (a.second == ptr) return a.first; } LogError("No agent matching pointer %p", ptr.get()); return emptyString; } StateRef<Agent> AgentGenerator::createAgent(GameState &state, StateRef<Organisation> org, AgentType::Role role) const { std::list<sp<AgentType>> types; for (auto &t : state.agent_types) if (t.second->role == role && t.second->playable) types.insert(types.begin(), t.second); auto type = listRandomiser(state.rng, types); return createAgent(state, org, {&state, AgentType::getId(state, type)}); } StateRef<Agent> AgentGenerator::createAgent(GameState &state, StateRef<Organisation> org, StateRef<AgentType> type) const { UString ID = Agent::generateObjectID(state); auto agent = mksp<Agent>(); agent->owner = org; agent->type = type; agent->gender = probabilityMapRandomizer(state.rng, type->gender_chance); if (type->playable) { auto firstNameList = this->first_names.find(agent->gender); if (firstNameList == this->first_names.end()) { LogError("No first name list for gender"); return nullptr; } auto firstName = listRandomiser(state.rng, firstNameList->second); auto secondName = listRandomiser(state.rng, this->second_names); agent->name = format("%s %s", tr(firstName), tr(secondName)); } else { agent->name = type->name; } // FIXME: When rng is fixed we can remove this unnesecary kludge // RNG is bad at generating small numbers, so we generate more and divide agent->appearance = randBoundsExclusive(state.rng, 0, type->appearance_count * 10) / 10; agent->portrait = randBoundsInclusive(state.rng, 0, (int)type->portraits[agent->gender].size() - 1); AgentStats s; s.health = randBoundsInclusive(state.rng, type->min_stats.health, type->max_stats.health); s.accuracy = randBoundsInclusive(state.rng, type->min_stats.accuracy, type->max_stats.accuracy); s.reactions = randBoundsInclusive(state.rng, type->min_stats.reactions, type->max_stats.reactions); s.setSpeed(randBoundsInclusive(state.rng, type->min_stats.speed, type->max_stats.speed)); s.stamina = randBoundsInclusive(state.rng, type->min_stats.stamina, type->max_stats.stamina) * 10; s.bravery = randBoundsInclusive(state.rng, type->min_stats.bravery / 10, type->max_stats.bravery / 10) * 10; s.strength = randBoundsInclusive(state.rng, type->min_stats.strength, type->max_stats.strength); s.morale = 100; s.psi_energy = randBoundsInclusive(state.rng, type->min_stats.psi_energy, type->max_stats.psi_energy); s.psi_attack = randBoundsInclusive(state.rng, type->min_stats.psi_attack, type->max_stats.psi_attack); s.psi_defence = randBoundsInclusive(state.rng, type->min_stats.psi_defence, type->max_stats.psi_defence); s.physics_skill = randBoundsInclusive(state.rng, type->min_stats.physics_skill, type->max_stats.physics_skill); s.biochem_skill = randBoundsInclusive(state.rng, type->min_stats.biochem_skill, type->max_stats.biochem_skill); s.engineering_skill = randBoundsInclusive(state.rng, type->min_stats.engineering_skill, type->max_stats.engineering_skill); agent->initial_stats = s; agent->current_stats = s; agent->modified_stats = s; // Everything worked, add agent to state (before we add his equipment) state.agents[ID] = agent; // Fill initial equipment list std::list<sp<AEquipmentType>> initialEquipment; if (type->inventory) { // Player gets no default equipment if (org == state.getPlayer()) { } // Aliens get equipment based on player score else if (org == state.getAliens()) { initialEquipment = EquipmentSet::getByScore(state, state.totalScore.tacticalMissions) ->generateEquipmentList(state); } // Every human org but civilians and player gets equipment based on tech level else if (org != state.getCivilian()) { initialEquipment = EquipmentSet::getByLevel(state, org->tech_level)->generateEquipmentList(state); } } else { initialEquipment.push_back(type->built_in_weapon_right); initialEquipment.push_back(type->built_in_weapon_left); } // Add initial equipment for (auto &t : initialEquipment) { if (!t) continue; agent->addEquipmentByType(state, {&state, t->id}, type->inventory); } agent->updateSpeed(); agent->modified_stats.restoreTU(); return {&state, ID}; } bool Agent::isBodyStateAllowed(BodyState bodyState) const { static const std::list<EquipmentSlotType> armorslots = { EquipmentSlotType::ArmorBody, EquipmentSlotType::ArmorHelmet, EquipmentSlotType::ArmorLeftHand, EquipmentSlotType::ArmorLegs, EquipmentSlotType::ArmorRightHand}; if (type->bodyType->allowed_body_states.find(bodyState) != type->bodyType->allowed_body_states.end()) { return true; } if (bodyState == BodyState::Flying) { for (auto &t : armorslots) { auto e = getFirstItemInSlot(t); if (e && e->type->provides_flight) { return true; } } } return false; } bool Agent::isMovementStateAllowed(MovementState movementState) const { return type->bodyType->allowed_movement_states.find(movementState) != type->bodyType->allowed_movement_states.end(); } bool Agent::isFireDuringMovementStateAllowed(MovementState movementState) const { return type->bodyType->allowed_fire_movement_states.find(movementState) != type->bodyType->allowed_fire_movement_states.end(); } bool Agent::isFacingAllowed(Vec2<int> facing) const { return type->bodyType->allowed_facing.empty() || type->bodyType->allowed_facing[appearance].find(facing) != type->bodyType->allowed_facing[appearance].end(); } const std::set<Vec2<int>> *Agent::getAllowedFacings() const { static const std::set<Vec2<int>> allFacings = {{0, -1}, {1, -1}, {1, 0}, {1, 1}, {0, 1}, {-1, 1}, {-1, 0}, {-1, -1}}; if (type->bodyType->allowed_facing.empty()) { return &allFacings; } else { return &type->bodyType->allowed_facing[appearance]; } } int Agent::getReactionValue() const { return modified_stats.reactions * modified_stats.time_units / current_stats.time_units; } int Agent::getTULimit(int reactionValue) const { if (reactionValue == 0) { return 0; } else if (reactionValue >= getReactionValue()) { return modified_stats.time_units; } else { return current_stats.time_units * reactionValue / modified_stats.reactions; } } UString Agent::getRankName() const { switch (rank) { case Rank::Rookie: return tr("Rookie"); case Rank::Squaddie: return tr("Squaddie"); case Rank::SquadLeader: return tr("Squad leader"); case Rank::Sergeant: return tr("Sergeant"); case Rank::Captain: return tr("Captain"); case Rank::Colonel: return tr("Colonel"); case Rank::Commander: return tr("Commander"); } LogError("Unknown rank %d", (int)rank); return ""; } /** * Get relevant skill. */ int Agent::getSkill() const { int skill = 0; switch (type->role) { case AgentType::Role::Physicist: skill = current_stats.physics_skill; break; case AgentType::Role::BioChemist: skill = current_stats.biochem_skill; break; case AgentType::Role::Engineer: skill = current_stats.engineering_skill; break; } return skill; } void Agent::leaveBuilding(GameState &state, Vec3<float> initialPosition) { if (currentBuilding) { currentBuilding->currentAgents.erase({&state, shared_from_this()}); currentBuilding = nullptr; } if (currentVehicle) { currentVehicle->currentAgents.erase({&state, shared_from_this()}); currentVehicle = nullptr; } position = initialPosition; goalPosition = initialPosition; } void Agent::enterBuilding(GameState &state, StateRef<Building> b) { if (currentVehicle) { currentVehicle->currentAgents.erase({&state, shared_from_this()}); currentVehicle = nullptr; } currentBuilding = b; currentBuilding->currentAgents.insert({&state, shared_from_this()}); position = (Vec3<float>)b->crewQuarters + Vec3<float>{0.5f, 0.5f, 0.5f}; goalPosition = position; } void Agent::enterVehicle(GameState &state, StateRef<Vehicle> v) { if (v->getPassengers() >= v->getMaxPassengers()) { return; } if (currentBuilding) { currentBuilding->currentAgents.erase({&state, shared_from_this()}); currentBuilding = nullptr; } if (currentVehicle) { currentVehicle->currentAgents.erase({&state, shared_from_this()}); currentVehicle = nullptr; } currentVehicle = v; currentVehicle->currentAgents.insert({&state, shared_from_this()}); } bool Agent::canTeleport() const { return teleportTicksAccumulated >= TELEPORT_TICKS_REQUIRED_AGENT; } bool Agent::hasTeleporter() const { for (auto &e : this->equipment) { if (e->type->type != AEquipmentType::Type::Teleporter) continue; return true; } return false; } void Agent::assignTraining(TrainingAssignment assignment) { if (type->role == AgentType::Role::Soldier && type->canTrain) { trainingAssignment = assignment; } } void Agent::hire(GameState &state, StateRef<Building> newHome) { owner = newHome->owner; homeBuilding = newHome; recentlyHired = true; setMission(state, AgentMission::gotoBuilding(state, *this, newHome, false, true)); } void Agent::transfer(GameState &state, StateRef<Building> newHome) { homeBuilding = newHome; recentlyHired = false; recentryTransferred = true; setMission(state, AgentMission::gotoBuilding(state, *this, newHome, false, true)); } sp<AEquipment> Agent::getArmor(BodyPart bodyPart) const { auto a = getFirstItemInSlot(AgentType::getArmorSlotType(bodyPart)); if (a) { return a; } return nullptr; } bool Agent::canAddEquipment(Vec2<int> pos, StateRef<AEquipmentType> equipmentType) const { EquipmentSlotType slotType = EquipmentSlotType::General; return canAddEquipment(pos, equipmentType, slotType); } bool Agent::canAddEquipment(Vec2<int> pos, StateRef<AEquipmentType> equipmentType, EquipmentSlotType &slotType) const { Vec2<int> slotOrigin; bool slotFound = false; bool slotIsArmor = false; // Check the slot this occupies hasn't already got something there for (auto &slot : type->equipment_layout->slots) { if (slot.bounds.within(pos)) { // If we are equipping into an armor slot, ensure the item being equipped is correct // armor if (isArmorEquipmentSlot(slot.type)) { if (equipmentType->type != AEquipmentType::Type::Armor) { break; } if (AgentType::getArmorSlotType(equipmentType->body_part) != slot.type) { break; } slotIsArmor = true; } slotOrigin = slot.bounds.p0; slotType = slot.type; slotFound = true; break; } } // If this was not within a slot fail if (!slotFound) { return false; } // Check that the equipment doesn't overlap with any other and doesn't // go outside a slot of the correct type // For agents, armor on the agent body does indeed overlap with each other, // So there is no point checking if there's an overlap (there will be) if (slotIsArmor) { // We still have to check that slot itself isn't full for (auto &otherEquipment : this->equipment) { // Something is already in that slot, fail if (otherEquipment->equippedPosition == slotOrigin) { return false; } } // This could would check that every slot is of appropriate type, // But for units armor this is unnecesary /* for (int y = 0; y < type->equipscreen_size.y; y++) { for (int x = 0; x < type->equipscreen_size.x; x++) { Vec2<int> slotPos = { x, y }; slotPos += pos; bool validSlot = false; for (auto &slot : type->equipment_layout->slots) { if (slot.bounds.within(slotPos) && (isArmorEquipmentSlot(slot.type))) { validSlot = true; break; } } if (!validSlot) { LogInfo("Equipping \"%s\" on \"%s\" at {%d,%d} failed: Armor intersecting both armor and non-armor slot", type->name, this->name, pos.x, pos.y); return false; } } } */ } else { pos = slotOrigin; // Check that the equipment doesn't overlap with any other Rect<int> bounds{pos, pos + equipmentType->equipscreen_size}; for (auto &otherEquipment : this->equipment) { // Something is already in that slot, fail if (otherEquipment->equippedPosition == slotOrigin) { return false; } Rect<int> otherBounds{otherEquipment->equippedPosition, otherEquipment->equippedPosition + otherEquipment->type->equipscreen_size}; if (otherBounds.intersects(bounds)) { return false; } } // Check that this doesn't go outside a slot of the correct type for (int y = 0; y < equipmentType->equipscreen_size.y; y++) { for (int x = 0; x < equipmentType->equipscreen_size.x; x++) { Vec2<int> slotPos = {x, y}; slotPos += pos; bool validSlot = false; for (auto &slot : type->equipment_layout->slots) { if (slot.bounds.within(slotPos) && slot.type == slotType) { validSlot = true; break; } } if (!validSlot) { return false; } } } } return true; } // If type is null we look for any slot, if type is not null we look for slot that can fit the type Vec2<int> Agent::findFirstSlotByType(EquipmentSlotType slotType, StateRef<AEquipmentType> equipmentType) { Vec2<int> pos = {-1, 0}; for (auto &slot : type->equipment_layout->slots) { if (slot.type == slotType && (!equipmentType || canAddEquipment(slot.bounds.p0, equipmentType))) { pos = slot.bounds.p0; break; } } return pos; } Vec2<int> Agent::findFirstSlot(StateRef<AEquipmentType> equipmentType) { Vec2<int> pos = {-1, 0}; for (auto &slot : type->equipment_layout->slots) { if (canAddEquipment(slot.bounds.p0, equipmentType)) { pos = slot.bounds.p0; break; } } return pos; } sp<AEquipment> Agent::addEquipmentByType(GameState &state, StateRef<AEquipmentType> equipmentType, bool allowFailure) { Vec2<int> pos; bool slotFound = false; EquipmentSlotType prefSlotType = EquipmentSlotType::General; bool prefSlot = false; if (equipmentType->type == AEquipmentType::Type::Ammo) { auto wpn = addEquipmentAsAmmoByType(equipmentType); if (wpn) { return wpn; } prefSlotType = EquipmentSlotType::General; prefSlot = true; } else if (equipmentType->type == AEquipmentType::Type::Armor) { switch (equipmentType->body_part) { case BodyPart::Body: prefSlotType = EquipmentSlotType::ArmorBody; break; case BodyPart::Legs: prefSlotType = EquipmentSlotType::ArmorLegs; break; case BodyPart::Helmet: prefSlotType = EquipmentSlotType::ArmorHelmet; break; case BodyPart::LeftArm: prefSlotType = EquipmentSlotType::ArmorLeftHand; break; case BodyPart::RightArm: prefSlotType = EquipmentSlotType::ArmorRightHand; break; } prefSlot = true; } if (prefSlot) { for (auto &slot : type->equipment_layout->slots) { if (slot.type != prefSlotType) { continue; } if (canAddEquipment(slot.bounds.p0, equipmentType)) { pos = slot.bounds.p0; slotFound = true; break; } } } if (!slotFound) { for (auto &slot : type->equipment_layout->slots) { if (canAddEquipment(slot.bounds.p0, equipmentType)) { pos = slot.bounds.p0; slotFound = true; break; } } } if (!slotFound) { if (!allowFailure) { LogError("Trying to add \"%s\" on agent \"%s\" failed: no valid slot found", equipmentType.id, this->name); } return nullptr; } return addEquipmentByType(state, pos, equipmentType); } sp<AEquipment> Agent::addEquipmentByType(GameState &state, StateRef<AEquipmentType> equipmentType, EquipmentSlotType slotType, bool allowFailure) { if (equipmentType->type == AEquipmentType::Type::Ammo) { auto wpn = addEquipmentAsAmmoByType(equipmentType); if (wpn) { return wpn; } } Vec2<int> pos = findFirstSlotByType(slotType, equipmentType); if (pos.x == -1) { if (!allowFailure) { LogError("Trying to add \"%s\" on agent \"%s\" failed: no valid slot found", equipmentType.id, this->name); } return nullptr; } return addEquipmentByType(state, pos, equipmentType); } sp<AEquipment> Agent::addEquipmentByType(GameState &state, Vec2<int> pos, StateRef<AEquipmentType> equipmentType) { auto equipment = mksp<AEquipment>(); equipment->type = equipmentType; equipment->armor = equipmentType->armor; if (equipmentType->ammo_types.size() == 0) { equipment->ammo = equipmentType->max_ammo; } this->addEquipment(state, pos, equipment); if (equipmentType->ammo_types.size() > 0) { equipment->loadAmmo(state); } return equipment; } sp<AEquipment> Agent::addEquipmentAsAmmoByType(StateRef<AEquipmentType> equipmentType) { for (auto &e : equipment) { if (e->type->type == AEquipmentType::Type::Weapon && e->ammo == 0 && std::find(e->type->ammo_types.begin(), e->type->ammo_types.end(), equipmentType) != e->type->ammo_types.end()) { e->payloadType = equipmentType; e->ammo = equipmentType->max_ammo; return e; } } return nullptr; } void Agent::addEquipment(GameState &state, sp<AEquipment> object, EquipmentSlotType slotType) { Vec2<int> pos = findFirstSlotByType(slotType, object->type); if (pos.x == -1) { LogError("Trying to add \"%s\" on agent \"%s\" failed: no valid slot found", type.id, this->name); return; } this->addEquipment(state, pos, object); } void Agent::addEquipment(GameState &state, Vec2<int> pos, sp<AEquipment> object) { EquipmentSlotType slotType; if (!canAddEquipment(pos, object->type, slotType)) { LogError("Trying to add \"%s\" at %s on agent \"%s\" failed", object->type.id, pos, this->name); } LogInfo("Equipped \"%s\" with equipment \"%s\"", this->name, object->type->name); // Proper position for (auto &slot : type->equipment_layout->slots) { if (slot.bounds.within(pos)) { pos = slot.bounds.p0; break; } } object->equippedPosition = pos; object->ownerAgent = StateRef<Agent>(&state, shared_from_this()); object->ownerUnit.clear(); object->equippedSlotType = slotType; if (slotType == EquipmentSlotType::RightHand) { rightHandItem = object; } if (slotType == EquipmentSlotType::LeftHand) { leftHandItem = object; } this->equipment.emplace_back(object); updateSpeed(); updateIsBrainsucker(); if (unit) { unit->updateDisplayedItem(state); } } void Agent::removeEquipment(GameState &state, sp<AEquipment> object) { this->equipment.remove(object); if (object->equippedSlotType == EquipmentSlotType::RightHand) { rightHandItem = nullptr; } if (object->equippedSlotType == EquipmentSlotType::LeftHand) { leftHandItem = nullptr; } if (unit) { // Stop flying if jetpack lost if (object->type->provides_flight && unit->target_body_state == BodyState::Flying && !isBodyStateAllowed(BodyState::Flying)) { unit->setBodyState(state, BodyState::Standing); } unit->updateDisplayedItem(state); } object->ownerAgent.clear(); updateSpeed(); updateIsBrainsucker(); } void Agent::updateSpeed() { int encumbrance = 0; for (auto &item : equipment) { encumbrance += item->getWeight(); } overEncumbred = current_stats.strength * 4 < encumbrance; encumbrance *= encumbrance; // Expecting str to never be 0 int strength = current_stats.strength; strength *= strength * 16; // Ensure actual speed is at least "1" modified_stats.speed = std::max(8, ((strength + encumbrance) / 2 + current_stats.speed * (strength - encumbrance)) / (strength + encumbrance)); } void Agent::updateModifiedStats() { int health = modified_stats.health; modified_stats = current_stats; modified_stats.health = health; updateSpeed(); } void Agent::updateIsBrainsucker() { isBrainsucker = false; for (auto &e : equipment) { if (e->type->type == AEquipmentType::Type::Brainsucker) { isBrainsucker = true; return; } } } bool Agent::addMission(GameState &state, AgentMission *mission, bool toBack) { if (missions.empty() || !toBack) { missions.emplace_front(mission); missions.front()->start(state, *this); } else { missions.emplace_back(mission); } return true; } bool Agent::setMission(GameState &state, AgentMission *mission) { missions.clear(); missions.emplace_front(mission); missions.front()->start(state, *this); return true; } bool Agent::popFinishedMissions(GameState &state) { bool popped = false; while (missions.size() > 0 && missions.front()->isFinished(state, *this)) { LogWarning("Agent %s mission \"%s\" finished", name, missions.front()->getName()); missions.pop_front(); popped = true; if (!missions.empty()) { LogWarning("Agent %s mission \"%s\" starting", name, missions.front()->getName()); missions.front()->start(state, *this); continue; } else { LogWarning("No next agent mission, going idle"); break; } } return popped; } bool Agent::getNewGoal(GameState &state) { bool popped = false; bool acquired = false; Vec3<float> nextGoal; // Pop finished missions if present popped = popFinishedMissions(state); do { // Try to get new destination if (!missions.empty()) { acquired = missions.front()->getNextDestination(state, *this, goalPosition); } // Pop finished missions if present popped = popFinishedMissions(state); } while (popped && !acquired); return acquired; } void Agent::die(GameState &state, bool silent) { auto thisRef = StateRef<Agent>{&state, shared_from_this()}; // Actually die modified_stats.health = 0; // Remove from lab if (assigned_to_lab) { for (auto &fac : homeBuilding->base->facilities) { if (!fac->lab) { continue; } auto it = std::find(fac->lab->assigned_agents.begin(), fac->lab->assigned_agents.end(), thisRef); if (it != fac->lab->assigned_agents.end()) { fac->lab->assigned_agents.erase(it); assigned_to_lab = false; break; } } } // Remove from building if (currentBuilding) { currentBuilding->currentAgents.erase(thisRef); } // Remove from vehicle if (currentVehicle) { currentVehicle->currentAgents.erase(thisRef); } // In city we remove agent if (!state.current_battle) { // In city (if not died in a vehicle) we make an event if (!silent && owner == state.getPlayer()) { fw().pushEvent( new GameSomethingDiedEvent(GameEventType::AgentDiedCity, name, "", position)); } state.agents.erase(getId(state, shared_from_this())); } } bool Agent::isDead() const { return getHealth() <= 0; } void Agent::update(GameState &state, unsigned ticks) { if (isDead() || !city) { return; } if (teleportTicksAccumulated < TELEPORT_TICKS_REQUIRED_VEHICLE) { teleportTicksAccumulated += ticks; } if (!hasTeleporter()) { teleportTicksAccumulated = 0; } // Agents in vehicles don't update missions and dont' move if (!currentVehicle) { if (!this->missions.empty()) { this->missions.front()->update(state, *this, ticks); } popFinishedMissions(state); updateMovement(state, ticks); } } void Agent::updateEachSecond(GameState &state) { if (type->role != AgentType::Role::Soldier && currentBuilding != homeBuilding && missions.empty()) { setMission(state, AgentMission::gotoBuilding(state, *this)); } } void Agent::updateDaily(GameState &state) { recentlyFought = false; } void Agent::updateHourly(GameState &state) { StateRef<Base> base; if (currentBuilding == homeBuilding) { // agent is in home building base = currentBuilding->base; } else if (currentVehicle && currentVehicle->currentBuilding == homeBuilding) { // agent is in a vehicle stationed in home building base = currentVehicle->currentBuilding->base; } else { // not in a base return; } // Heal if (modified_stats.health < current_stats.health && !recentlyFought) { int usage = base->getUsage(state, FacilityType::Capacity::Medical); if (usage < 999) { usage = std::max(100, usage); // As per Roger Wong's guide, healing is 0.8 points an hour healingProgress += 80.0f / (float)usage; if (healingProgress > 1.0f) { healingProgress -= 1.0f; modified_stats.health++; } } } // Train if (trainingAssignment != TrainingAssignment::None) { int usage = base->getUsage(state, trainingAssignment == TrainingAssignment::Physical ? FacilityType::Capacity::Training : FacilityType::Capacity::Psi); if (usage < 999) { usage = std::max(100, usage); // As per Roger Wong's guide if (trainingAssignment == TrainingAssignment::Physical) { trainPhysical(state, TICKS_PER_HOUR * 100 / usage); } else { trainPsi(state, TICKS_PER_HOUR * 100 / usage); } } } } void Agent::updateMovement(GameState &state, unsigned ticks) { auto ticksToMove = ticks; unsigned lastTicksToMove = 0; // See that we're not in the air if (!city->map->getTile(position)->presentScenery) { die(state); return; } // Move until we become idle or run out of ticks while (ticksToMove != lastTicksToMove) { lastTicksToMove = ticksToMove; // Advance agent position to goal if (ticksToMove > 0 && position != goalPosition) { Vec3<float> vectorToGoal = goalPosition - position; int distanceToGoal = (unsigned)ceilf(glm::length( vectorToGoal * VELOCITY_SCALE_CITY * (float)TICKS_PER_UNIT_TRAVELLED_AGENT)); // Cannot reach in one go if (distanceToGoal > ticksToMove) { auto dir = glm::normalize(vectorToGoal); Vec3<float> newPosition = (float)(ticksToMove)*dir; newPosition /= VELOCITY_SCALE_BATTLE; newPosition /= (float)TICKS_PER_UNIT_TRAVELLED_AGENT; newPosition += position; position = newPosition; ticksToMove = 0; } // Can reach in one go else { ticksToMove -= distanceToGoal; position = goalPosition; } } // Request new goal if (position == goalPosition) { if (!getNewGoal(state)) { break; } } } } void Agent::trainPhysical(GameState &state, unsigned ticks) { trainingPhysicalTicksAccumulated += ticks; while (trainingPhysicalTicksAccumulated >= TICKS_PER_PHYSICAL_TRAINING) { trainingPhysicalTicksAccumulated -= TICKS_PER_PHYSICAL_TRAINING; if (randBoundsExclusive(state.rng, 0, 100) >= current_stats.health) { current_stats.health++; modified_stats.health++; } if (randBoundsExclusive(state.rng, 0, 100) >= current_stats.accuracy) { current_stats.accuracy++; } if (randBoundsExclusive(state.rng, 0, 100) >= current_stats.reactions) { current_stats.reactions++; } if (randBoundsExclusive(state.rng, 0, 100) >= current_stats.speed) { current_stats.speed++; current_stats.restoreTU(); } if (randBoundsExclusive(state.rng, 0, 2000) >= current_stats.stamina) { current_stats.stamina += 20; } if (randBoundsExclusive(state.rng, 0, 100) >= current_stats.strength) { current_stats.strength++; } updateModifiedStats(); } } void Agent::trainPsi(GameState &state, unsigned ticks) { trainingPsiTicksAccumulated += ticks; while (trainingPsiTicksAccumulated >= TICKS_PER_PSI_TRAINING) { trainingPsiTicksAccumulated -= TICKS_PER_PSI_TRAINING; // FIXME: Ensure correct // Roger Wong gives this info: // - Improve up to 3x base value // - Chance is 100 - (3 x current - initial) // - Hybrids have much higher chance to improve and humans hardly ever improve // This seems very wong (lol)! // For example, if initial is 50, no improvement ever possible because 100 - (150-50) = 0 // already) // Or, for initial 10, even at 30 the formula would be 100 - (90-10) = 20% improve chance // In this formula the bigger is the initial stat, the harder it is to improve // Therefore, we'll use a formula that makes senes and follows what he said. // Properties of our formula: // - properly gives 0 chance when current = 3x initial // - gives higher chance with higher initial values if (randBoundsExclusive(state.rng, 0, 100) < 3 * initial_stats.psi_attack - current_stats.psi_attack) { current_stats.psi_attack += current_stats.psi_energy / 20; } if (randBoundsExclusive(state.rng, 0, 100) < 3 * initial_stats.psi_defence - current_stats.psi_defence) { current_stats.psi_defence += current_stats.psi_energy / 20; } if (randBoundsExclusive(state.rng, 0, 100) < 3 * initial_stats.psi_energy - current_stats.psi_energy) { current_stats.psi_energy++; } updateModifiedStats(); } } StateRef<BattleUnitAnimationPack> Agent::getAnimationPack() const { return type->animation_packs[appearance]; } StateRef<AEquipmentType> Agent::getDominantItemInHands(GameState &state, StateRef<AEquipmentType> itemLastFired) const { sp<AEquipment> e1 = getFirstItemInSlot(EquipmentSlotType::RightHand); sp<AEquipment> e2 = getFirstItemInSlot(EquipmentSlotType::LeftHand); // If there is only one item - return it, if none - return nothing if (!e1 && !e2) return nullptr; else if (e1 && !e2) return e1->type; else if (e2 && !e1) return e2->type; // If item was last fired and still in hands - return it if (itemLastFired) { if (e1 && e1->type == itemLastFired) return e1->type; if (e2 && e2->type == itemLastFired) return e2->type; } // Calculate item priorities: // - Firing (whichever fires sooner) // - CanFire >> Two-Handed >> Weapon >> Usable Item >> Others int e1Priority = e1->isFiring() ? 1440 - e1->weapon_fire_ticks_remaining : (e1->canFire(state) ? 4 : (e1->type->two_handed ? 3 : (e1->type->type == AEquipmentType::Type::Weapon ? 2 : (e1->type->type != AEquipmentType::Type::Ammo && e1->type->type != AEquipmentType::Type::Armor && e1->type->type != AEquipmentType::Type::Loot) ? 1 : 0))); int e2Priority = e2->isFiring() ? 1440 - e2->weapon_fire_ticks_remaining : (e2->canFire(state) ? 4 : (e2->type->two_handed ? 3 : (e2->type->type == AEquipmentType::Type::Weapon ? 2 : (e2->type->type != AEquipmentType::Type::Ammo && e2->type->type != AEquipmentType::Type::Armor && e2->type->type != AEquipmentType::Type::Loot) ? 1 : 0))); // Right hand has priority in case of a tie if (e1Priority >= e2Priority) return e1->type; return e2->type; } sp<AEquipment> Agent::getFirstItemInSlot(EquipmentSlotType equipmentSlotType, bool lazy) const { if (lazy) { if (equipmentSlotType == EquipmentSlotType::RightHand) return rightHandItem; if (equipmentSlotType == EquipmentSlotType::LeftHand) return leftHandItem; } for (auto &e : equipment) { for (auto &s : type->equipment_layout->slots) { if (s.bounds.p0 == e->equippedPosition && s.type == equipmentSlotType) { return e; } } } return nullptr; } sp<AEquipment> Agent::getFirstItemByType(StateRef<AEquipmentType> equipmentType) const { for (auto &e : equipment) { if (e->type == equipmentType) { return e; } } return nullptr; } sp<AEquipment> Agent::getFirstItemByType(AEquipmentType::Type itemType) const { for (auto &e : equipment) { if (e->type->type == itemType) { return e; } } return nullptr; } sp<AEquipment> Agent::getFirstShield(GameState &state) const { for (auto &e : equipment) { if (e->type->type == AEquipmentType::Type::DisruptorShield && e->canBeUsed(state)) { return e; } } return nullptr; } StateRef<BattleUnitImagePack> Agent::getImagePack(BodyPart bodyPart) const { EquipmentSlotType slotType = AgentType::getArmorSlotType(bodyPart); auto e = getFirstItemInSlot(slotType); if (e) return e->type->body_image_pack; auto it = type->image_packs[appearance].find(bodyPart); if (it != type->image_packs[appearance].end()) return it->second; return nullptr; } sp<Equipment> Agent::getEquipmentAt(const Vec2<int> &position) const { Vec2<int> slotPosition = {0, 0}; for (auto &slot : type->equipment_layout->slots) { if (slot.bounds.within(position)) { slotPosition = slot.bounds.p0; } } // Find whatever equipped in the slot itself for (auto &eq : this->equipment) { if (eq->equippedPosition == slotPosition) { return eq; } } // Find whatever occupies this space for (auto &eq : this->equipment) { Rect<int> eqBounds{eq->equippedPosition, eq->equippedPosition + eq->type->equipscreen_size}; if (eqBounds.within(slotPosition)) { return eq; } } return nullptr; } const std::list<EquipmentLayoutSlot> &Agent::getSlots() const { return type->equipment_layout->slots; } std::list<std::pair<Vec2<int>, sp<Equipment>>> Agent::getEquipment() const { std::list<std::pair<Vec2<int>, sp<Equipment>>> equipmentList; for (auto &equipmentObject : this->equipment) { equipmentList.emplace_back( std::make_pair(equipmentObject->equippedPosition, equipmentObject)); } return equipmentList; } int Agent::getMaxHealth() const { return current_stats.health; } int Agent::getHealth() const { return modified_stats.health; } int Agent::getMaxShield(GameState &state) const { int maxShield = 0; for (auto &e : equipment) { if (e->type->type != AEquipmentType::Type::DisruptorShield || !e->canBeUsed(state)) continue; maxShield += e->type->max_ammo; } return maxShield; } int Agent::getShield(GameState &state) const { int curShield = 0; for (auto &e : equipment) { if (e->type->type != AEquipmentType::Type::DisruptorShield || !e->canBeUsed(state)) continue; curShield += e->ammo; } return curShield; } void Agent::destroy() { leftHandItem = nullptr; rightHandItem = nullptr; while (!equipment.empty()) { GameState state; this->removeEquipment(state, equipment.front()); } } } // namespace OpenApoc
25.98717
100
0.661574
Skin36
61937fefa9ed7636fa0c3e9635aea96e1226dbc4
3,805
cpp
C++
ref_app/src/mcal/stm32f446/mcal_gpt.cpp
dustex/real-time-cpp
dedab60eefc6c5db94d53f1e1a890cfba8ae3f76
[ "BSL-1.0" ]
1
2020-03-19T08:10:23.000Z
2020-03-19T08:10:23.000Z
ref_app/src/mcal/stm32f446/mcal_gpt.cpp
dustex/real-time-cpp
dedab60eefc6c5db94d53f1e1a890cfba8ae3f76
[ "BSL-1.0" ]
null
null
null
ref_app/src/mcal/stm32f446/mcal_gpt.cpp
dustex/real-time-cpp
dedab60eefc6c5db94d53f1e1a890cfba8ae3f76
[ "BSL-1.0" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// // Copyright Christopher Kormanyos 2007 - 2015. // Distributed under the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt // or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <array> #include <cstddef> #include <cstdint> #include <mcal_cpu.h> #include <mcal_gpt.h> #include <mcal_reg.h> namespace { // The one (and only one) system tick. volatile std::uint64_t system_tick; bool& gpt_is_initialized() __attribute__((used, noinline)); bool& gpt_is_initialized() { static bool is_init = false; return is_init; } } extern "C" void __sys_tick_handler(void) __attribute__((used, noinline)); extern "C" void __sys_tick_handler(void) { // Increment the 64-bit system tick with 0x01000000, representing (2^24) [microseconds/32]. system_tick = system_tick + UINT32_C(0x01000000); } void mcal::gpt::init(const config_type*) { if(gpt_is_initialized() == false) { // Set up an interrupt on ARM(R) sys tick. mcal::reg::reg_access_static<std::uint32_t, std::uint32_t, mcal::reg::sys_tick_ctrl, UINT32_C(0)>::reg_set(); // Set sys tick reload register. mcal::reg::reg_access_static<std::uint32_t, std::uint32_t, mcal::reg::sys_tick_load, UINT32_C(0x00FFFFFF)>::reg_set(); // Initialize sys tick counter value. mcal::reg::reg_access_static<std::uint32_t, std::uint32_t, mcal::reg::sys_tick_val, UINT32_C(0)>::reg_set(); // Set sys tick clock source to ahb. mcal::reg::reg_access_static<std::uint32_t, std::uint32_t, mcal::reg::sys_tick_ctrl, UINT32_C(4)>::reg_or(); // Enable sys tick interrupt. mcal::reg::reg_access_static<std::uint32_t, std::uint32_t, mcal::reg::sys_tick_ctrl, UINT32_C(2)>::reg_or(); // Enable sys tick timer. mcal::reg::reg_access_static<std::uint32_t, std::uint32_t, mcal::reg::sys_tick_ctrl, UINT32_C(1)>::reg_or(); gpt_is_initialized() = true; } } mcal::gpt::value_type mcal::gpt::secure::get_time_elapsed() { if(gpt_is_initialized()) { // Return the system tick using a multiple read to ensure data consistency. typedef std::uint32_t timer_address_type; typedef std::uint32_t timer_register_type; // Do the first read of the sys tick counter and the system tick. // Handle reverse counting for sys tick counting down. const timer_register_type sys_tick_val_1 = timer_register_type( UINT32_C(0x00FFFFFF) - mcal::reg::reg_access_static<timer_address_type, timer_register_type, mcal::reg::sys_tick_val>::reg_get()); const std::uint64_t system_tick_gpt = system_tick; // Do the second read of the sys tick counter. // Handle reverse counting for sys tick counting down. const timer_register_type sys_tick_val_2 = timer_register_type( UINT32_C(0x00FFFFFF) - mcal::reg::reg_access_static<timer_address_type, timer_register_type, mcal::reg::sys_tick_val>::reg_get()); // Perform the consistency check. const std::uint64_t consistent_tick = ((sys_tick_val_2 >= sys_tick_val_1) ? std::uint64_t(system_tick_gpt | sys_tick_val_1) : std::uint64_t(system_tick | sys_tick_val_2)); // Perform scaling and include a rounding correction. const mcal::gpt::value_type consistent_microsecond_tick = mcal::gpt::value_type(std::uint64_t(consistent_tick + 84U) / 168U); return consistent_microsecond_tick; } else { return mcal::gpt::value_type(0U); } }
34.590909
122
0.639947
dustex
61946fd077293e6fe88434b89593f36220e38b21
6,632
cc
C++
src/09_bundle_adjustment/bundle_adjustment.cc
niebayes/uzh_robot_perception_codes
6ec429537b45a6389c4f364d19661c8757087035
[ "MIT" ]
1
2020-09-11T05:22:19.000Z
2020-09-11T05:22:19.000Z
src/09_bundle_adjustment/bundle_adjustment.cc
niebayes/uzh_robot_perception_codes
6ec429537b45a6389c4f364d19661c8757087035
[ "MIT" ]
null
null
null
src/09_bundle_adjustment/bundle_adjustment.cc
niebayes/uzh_robot_perception_codes
6ec429537b45a6389c4f364d19661c8757087035
[ "MIT" ]
null
null
null
#include <string> #include <tuple> #include "armadillo" #include "ba.h" #include "ceres/ceres.h" #include "google_suite.h" #include "io.h" #include "matlab_port.h" #include "opencv2/opencv.hpp" #include "pcl/visualization/pcl_plotter.h" #include "transform.h" int main(int /*argc*/, char** argv) { google::InitGoogleLogging(argv[0]); google::LogToStderr(); const std::string file_path{"data/09_bundle_adjustment/"}; // Load data. // Loaded hidden state and observations are obtained from a visual odometry // system, while loaded poses are the ground truth. const arma::vec hidden_state_all = uzh::LoadArma<double>(file_path + "hidden_state.txt"); const arma::vec observations_all = uzh::LoadArma<double>(file_path + "observations.txt"); // FIXME What is the data format of the poses.txt? const arma::mat poses = uzh::LoadArma<double>(file_path + "poses.txt"); const arma::mat K = uzh::LoadArma<double>(file_path + "K.txt"); // Get the ground truth trajectory. // The first p states that the poses (the second p) are the ground truth. The // poses in consider contain only translation part. G is the world frame of // the ground truth trajectory and C is the camera frame. const arma::mat pp_G_C_all = poses.cols(arma::uvec{3, 7, 11}).t(); // Prepare data. // Take the first 150 frames as the whole problem. const int kNumFrames = 150; arma::vec hidden_state, observations; arma::mat pp_G_C; std::tie(hidden_state, observations, pp_G_C) = uzh::CropProblem( hidden_state_all, observations_all, pp_G_C_all, kNumFrames); // Take the frist 4 frames as the cropped problem. const int kNumFramesForSmallBA = 4; arma::vec cropped_hidden_state, cropped_observations; std::tie(cropped_hidden_state, cropped_observations, std::ignore) = uzh::CropProblem(hidden_state_all, observations_all, pp_G_C_all, kNumFramesForSmallBA); // Part I: trajectory alignment. // Compare estimates from VO to ground truth. // V stands for VO. const arma::mat twists_V_C = arma::reshape(hidden_state.head(6 * kNumFrames), 6, kNumFrames); arma::mat p_V_C(3, kNumFrames, arma::fill::zeros); for (int i = 0; i < kNumFrames; ++i) { p_V_C.col(i) = uzh::twist_to_SE3<double>(twists_V_C.col(i))(0, 3, arma::size(3, 1)); } // Plot the VO trajectory and ground truth trajectory. pcl::visualization::PCLPlotter* plotter( new pcl::visualization::PCLPlotter); plotter->setTitle("VO trajectory and ground truth trajectory"); plotter->setShowLegend(true); plotter->setXRange(-5, 95); plotter->setYRange(-30, 10); //! The figure axes are not the same with the camera axes. //! For camera, positive x axis points to right of the camere, positive y //! axis points to the down of the camera and positive z axis points to the //! front of the camera. //! Therefore, x and z are the two axes needed for plotting in 2D figure, and //! x needs to be negated to be consistent with the x axis of the figure. plotter->addPlotData(arma::conv_to<std::vector<double>>::from(pp_G_C.row(2)), arma::conv_to<std::vector<double>>::from(-pp_G_C.row(0)), "Ground truth", vtkChart::LINE); plotter->addPlotData(arma::conv_to<std::vector<double>>::from(p_V_C.row(2)), arma::conv_to<std::vector<double>>::from(-p_V_C.row(0)), "Original estimate", vtkChart::LINE); plotter->plot(); // Apply non-linear least square (NLLS) method to align VO estimate to the // ground truth. const arma::mat p_G_C = uzh::AlignVOToGroundTruth(p_V_C, pp_G_C); // Show the optimized trajectory. plotter->addPlotData( arma::conv_to<std::vector<double>>::from(p_G_C.row(2)), arma::conv_to<std::vector<double>>::from(-p_G_C.row(0)), "Aligned estimate", vtkChart::LINE); plotter->plot(); // Part II: small bundle adjustment. // Part III: determine jacob pattern. // FIXME Seems no need to perform this using ceres? // Plot map before BA. plotter->clearPlots(); plotter->setTitle("Cropped problem before bundle adjustment"); uzh::PlotMap(plotter, cropped_hidden_state, cropped_observations, {0, 20, -5, 5}); plotter->plot(); // Run BA and plot. const arma::vec optimized_cropped_hidden_state = uzh::RunBA(cropped_hidden_state, cropped_observations, K); plotter->clearPlots(); plotter->setTitle("Cropped problem after bundle adjustment"); uzh::PlotMap(plotter, optimized_cropped_hidden_state, cropped_observations, {0, 20, -5, 5}); plotter->plot(); // Part IV: larger bundle adjustment and evaluation. // Plot full map before BA. plotter->clearPlots(); plotter->setTitle("Full problem before bundle adjustment"); uzh::PlotMap(plotter, hidden_state, observations, {0, 40, -10, 10}); plotter->plot(); // Run BA and plot. const arma::vec optimized_full_hidden_state = uzh::RunBA(hidden_state, observations, K); plotter->clearPlots(); plotter->setTitle("Full problem after bundle adjustment"); uzh::PlotMap(plotter, optimized_full_hidden_state, observations, {0, 40, -10, 10}); plotter->plot(); // Evaluate the BA performance by plotting. const arma::mat optimized_twists_V_C = arma::reshape( optimized_full_hidden_state.head(6 * kNumFrames), 6, kNumFrames); arma::mat optimized_p_V_C(3, kNumFrames, arma::fill::zeros); for (int i = 0; i < kNumFrames; ++i) { optimized_p_V_C.col(i) = uzh::twist_to_SE3<double>( optimized_twists_V_C.col(i))(0, 3, arma::size(3, 1)); } const arma::mat optimized_p_G_C = uzh::AlignVOToGroundTruth(optimized_p_V_C, pp_G_C); // Plot for comparision. plotter->clearPlots(); plotter->setTitle("Optimized VO trajectory and ground truth trajectory"); plotter->setShowLegend(true); plotter->setXRange(-5, 95); plotter->setYRange(-30, 10); plotter->addPlotData(arma::conv_to<std::vector<double>>::from(pp_G_C.row(2)), arma::conv_to<std::vector<double>>::from(-pp_G_C.row(0)), "Ground truth", vtkChart::LINE); plotter->addPlotData(arma::conv_to<std::vector<double>>::from(p_G_C.row(2)), arma::conv_to<std::vector<double>>::from(-p_G_C.row(0)), "Aligned original estimate", vtkChart::LINE); plotter->addPlotData( arma::conv_to<std::vector<double>>::from(optimized_p_G_C.row(2)), arma::conv_to<std::vector<double>>::from(-optimized_p_G_C.row(0)), "Aligned optimized estimate", vtkChart::LINE); plotter->plot(); return EXIT_SUCCESS; }
42.787097
80
0.680036
niebayes
61978f211a481bb80b61877035dfd6543fce522f
833
cpp
C++
main.cpp
dridk/abif
e64b4733e24fcd725b0a71741e98dfb2e00fc1a5
[ "MIT" ]
6
2018-06-14T08:57:35.000Z
2021-05-29T08:14:22.000Z
main.cpp
dridk/abif
e64b4733e24fcd725b0a71741e98dfb2e00fc1a5
[ "MIT" ]
1
2020-07-08T10:23:36.000Z
2020-07-14T15:40:49.000Z
main.cpp
dridk/abif
e64b4733e24fcd725b0a71741e98dfb2e00fc1a5
[ "MIT" ]
2
2021-04-19T02:17:52.000Z
2021-09-17T08:40:53.000Z
#include <iostream> #include <fstream> #include <byteswap.h> #include <tclap/CmdLine.h> #include "abif.h" using namespace std; int main(int argc, char** argv) { TCLAP::CmdLine cmd("ABIF reader", ' ', "0.1"); TCLAP::SwitchArg listArg("l","list","list all keys"); TCLAP::ValueArg<std::string> keyArg("k","key","get value from key",false,"","string"); TCLAP::UnlabeledValueArg<std::string> fileArg( "filename", "abi file", true, "", "filename"); cmd.xorAdd( keyArg, listArg ); cmd.add( fileArg ); cmd.parse( argc, argv ); std::string key = keyArg.getValue(); std::string filename = fileArg.getValue(); bool isList = listArg.getValue(); Abif file = Abif(filename); if (isList) file.showList(); else cout<<file.value(key).c_str()<<endl; return 0; }
20.317073
97
0.615846
dridk
619a86c1a826c23163839263effed7e5d1e60f40
3,693
cpp
C++
my_plugins/youcompleteme/third_party/ycmd/cpp/ycm/tests/TestUtils.cpp
VirtualLG/vimrc
33f961b0e465b852753479bc4aa0a32a6ff017cf
[ "MIT" ]
null
null
null
my_plugins/youcompleteme/third_party/ycmd/cpp/ycm/tests/TestUtils.cpp
VirtualLG/vimrc
33f961b0e465b852753479bc4aa0a32a6ff017cf
[ "MIT" ]
null
null
null
my_plugins/youcompleteme/third_party/ycmd/cpp/ycm/tests/TestUtils.cpp
VirtualLG/vimrc
33f961b0e465b852753479bc4aa0a32a6ff017cf
[ "MIT" ]
null
null
null
// Copyright (C) 2011-2018 ycmd contributors // // This file is part of ycmd. // // ycmd is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // ycmd 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 ycmd. If not, see <http://www.gnu.org/licenses/>. #include "TestUtils.h" #include <whereami.c> namespace std { namespace filesystem { void PrintTo( const fs::path &path, std::ostream *os ) { *os << path; } } // namespace filesystem } // namespace std namespace YouCompleteMe { std::ostream& operator<<( std::ostream& os, const CodePointTuple &code_point ) { os << "{ " << PrintToString( code_point.normal_ ) << ", " << PrintToString( code_point.folded_case_ ) << ", " << PrintToString( code_point.swapped_case_ ) << ", " << PrintToString( code_point.is_letter_ ) << ", " << PrintToString( code_point.is_punctuation_ ) << ", " << PrintToString( code_point.is_uppercase_ ) << ", " << PrintToString( code_point.break_property_ ) << " }"; return os; } std::ostream& operator<<( std::ostream& os, const CodePoint &code_point ) { os << CodePointTuple( code_point ); return os; } std::ostream& operator<<( std::ostream& os, const CodePoint *code_point ) { os << "*" << *code_point; return os; } std::ostream& operator<<( std::ostream& os, const CharacterTuple &character ) { os << "{ " << PrintToString( character.normal_ ) << ", " << PrintToString( character.base_ ) << ", " << PrintToString( character.folded_case_ ) << ", " << PrintToString( character.swapped_case_ ) << ", " << PrintToString( character.is_base_ ) << ", " << PrintToString( character.is_letter_ ) << ", " << PrintToString( character.is_punctuation_ ) << ", " << PrintToString( character.is_uppercase_ ) << " }"; return os; } std::ostream& operator<<( std::ostream& os, const Character &character ) { os << PrintToString( CharacterTuple( character ) ); return os; } std::ostream& operator<<( std::ostream& os, const Character *character ) { os << "*" << *character; return os; } std::ostream& operator<<( std::ostream& os, const WordTuple &word ) { os << "{ " << PrintToString( word.text_ ) << ", { "; const std::vector< const char* > &characters( word.characters_ ); auto character_pos = characters.begin(); if ( character_pos != characters.end() ) { os << PrintToString( *character_pos ); ++character_pos; for ( ; character_pos != characters.end() ; ++character_pos ) { os << ", " << PrintToString( *character_pos ); } os << " }"; } return os; } std::ostream& operator<<( std::ostream& os, const fs::path *path ) { os << *path; return os; } fs::path PathToTestFile( std::string_view filepath ) { int dirname_length; int exec_length = wai_getExecutablePath( NULL, 0, NULL ); std::unique_ptr< char[] > executable( new char [ exec_length ] ); wai_getExecutablePath( executable.get(), exec_length, &dirname_length ); executable[ dirname_length ] = '\0'; fs::path path_to_testdata = fs::path( executable.get() ) / "testdata"; return path_to_testdata / fs::path( filepath ); } } // namespace YouCompleteMe
31.564103
80
0.637422
VirtualLG
619aa313631f19a0064a2374ce4265254c46d50a
35,016
cpp
C++
aws-cpp-sdk-lookoutequipment/source/LookoutEquipmentClient.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-lookoutequipment/source/LookoutEquipmentClient.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-lookoutequipment/source/LookoutEquipmentClient.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2022-02-28T21:36:42.000Z
2022-02-28T21:36:42.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/core/utils/Outcome.h> #include <aws/core/auth/AWSAuthSigner.h> #include <aws/core/client/CoreErrors.h> #include <aws/core/client/RetryStrategy.h> #include <aws/core/http/HttpClient.h> #include <aws/core/http/HttpResponse.h> #include <aws/core/http/HttpClientFactory.h> #include <aws/core/auth/AWSCredentialsProviderChain.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <aws/core/utils/threading/Executor.h> #include <aws/core/utils/DNS.h> #include <aws/core/utils/logging/LogMacros.h> #include <aws/lookoutequipment/LookoutEquipmentClient.h> #include <aws/lookoutequipment/LookoutEquipmentEndpoint.h> #include <aws/lookoutequipment/LookoutEquipmentErrorMarshaller.h> #include <aws/lookoutequipment/model/CreateDatasetRequest.h> #include <aws/lookoutequipment/model/CreateInferenceSchedulerRequest.h> #include <aws/lookoutequipment/model/CreateModelRequest.h> #include <aws/lookoutequipment/model/DeleteDatasetRequest.h> #include <aws/lookoutequipment/model/DeleteInferenceSchedulerRequest.h> #include <aws/lookoutequipment/model/DeleteModelRequest.h> #include <aws/lookoutequipment/model/DescribeDataIngestionJobRequest.h> #include <aws/lookoutequipment/model/DescribeDatasetRequest.h> #include <aws/lookoutequipment/model/DescribeInferenceSchedulerRequest.h> #include <aws/lookoutequipment/model/DescribeModelRequest.h> #include <aws/lookoutequipment/model/ListDataIngestionJobsRequest.h> #include <aws/lookoutequipment/model/ListDatasetsRequest.h> #include <aws/lookoutequipment/model/ListInferenceExecutionsRequest.h> #include <aws/lookoutequipment/model/ListInferenceSchedulersRequest.h> #include <aws/lookoutequipment/model/ListModelsRequest.h> #include <aws/lookoutequipment/model/ListTagsForResourceRequest.h> #include <aws/lookoutequipment/model/StartDataIngestionJobRequest.h> #include <aws/lookoutequipment/model/StartInferenceSchedulerRequest.h> #include <aws/lookoutequipment/model/StopInferenceSchedulerRequest.h> #include <aws/lookoutequipment/model/TagResourceRequest.h> #include <aws/lookoutequipment/model/UntagResourceRequest.h> #include <aws/lookoutequipment/model/UpdateInferenceSchedulerRequest.h> using namespace Aws; using namespace Aws::Auth; using namespace Aws::Client; using namespace Aws::LookoutEquipment; using namespace Aws::LookoutEquipment::Model; using namespace Aws::Http; using namespace Aws::Utils::Json; static const char* SERVICE_NAME = "lookoutequipment"; static const char* ALLOCATION_TAG = "LookoutEquipmentClient"; LookoutEquipmentClient::LookoutEquipmentClient(const Client::ClientConfiguration& clientConfiguration) : BASECLASS(clientConfiguration, Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG, Aws::MakeShared<DefaultAWSCredentialsProviderChain>(ALLOCATION_TAG), SERVICE_NAME, Aws::Region::ComputeSignerRegion(clientConfiguration.region)), Aws::MakeShared<LookoutEquipmentErrorMarshaller>(ALLOCATION_TAG)), m_executor(clientConfiguration.executor) { init(clientConfiguration); } LookoutEquipmentClient::LookoutEquipmentClient(const AWSCredentials& credentials, const Client::ClientConfiguration& clientConfiguration) : BASECLASS(clientConfiguration, Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG, Aws::MakeShared<SimpleAWSCredentialsProvider>(ALLOCATION_TAG, credentials), SERVICE_NAME, Aws::Region::ComputeSignerRegion(clientConfiguration.region)), Aws::MakeShared<LookoutEquipmentErrorMarshaller>(ALLOCATION_TAG)), m_executor(clientConfiguration.executor) { init(clientConfiguration); } LookoutEquipmentClient::LookoutEquipmentClient(const std::shared_ptr<AWSCredentialsProvider>& credentialsProvider, const Client::ClientConfiguration& clientConfiguration) : BASECLASS(clientConfiguration, Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG, credentialsProvider, SERVICE_NAME, Aws::Region::ComputeSignerRegion(clientConfiguration.region)), Aws::MakeShared<LookoutEquipmentErrorMarshaller>(ALLOCATION_TAG)), m_executor(clientConfiguration.executor) { init(clientConfiguration); } LookoutEquipmentClient::~LookoutEquipmentClient() { } void LookoutEquipmentClient::init(const Client::ClientConfiguration& config) { SetServiceClientName("LookoutEquipment"); m_configScheme = SchemeMapper::ToString(config.scheme); if (config.endpointOverride.empty()) { m_uri = m_configScheme + "://" + LookoutEquipmentEndpoint::ForRegion(config.region, config.useDualStack); } else { OverrideEndpoint(config.endpointOverride); } } void LookoutEquipmentClient::OverrideEndpoint(const Aws::String& endpoint) { if (endpoint.compare(0, 7, "http://") == 0 || endpoint.compare(0, 8, "https://") == 0) { m_uri = endpoint; } else { m_uri = m_configScheme + "://" + endpoint; } } CreateDatasetOutcome LookoutEquipmentClient::CreateDataset(const CreateDatasetRequest& request) const { Aws::Http::URI uri = m_uri; return CreateDatasetOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER)); } CreateDatasetOutcomeCallable LookoutEquipmentClient::CreateDatasetCallable(const CreateDatasetRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< CreateDatasetOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->CreateDataset(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void LookoutEquipmentClient::CreateDatasetAsync(const CreateDatasetRequest& request, const CreateDatasetResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->CreateDatasetAsyncHelper( request, handler, context ); } ); } void LookoutEquipmentClient::CreateDatasetAsyncHelper(const CreateDatasetRequest& request, const CreateDatasetResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, CreateDataset(request), context); } CreateInferenceSchedulerOutcome LookoutEquipmentClient::CreateInferenceScheduler(const CreateInferenceSchedulerRequest& request) const { Aws::Http::URI uri = m_uri; return CreateInferenceSchedulerOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER)); } CreateInferenceSchedulerOutcomeCallable LookoutEquipmentClient::CreateInferenceSchedulerCallable(const CreateInferenceSchedulerRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< CreateInferenceSchedulerOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->CreateInferenceScheduler(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void LookoutEquipmentClient::CreateInferenceSchedulerAsync(const CreateInferenceSchedulerRequest& request, const CreateInferenceSchedulerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->CreateInferenceSchedulerAsyncHelper( request, handler, context ); } ); } void LookoutEquipmentClient::CreateInferenceSchedulerAsyncHelper(const CreateInferenceSchedulerRequest& request, const CreateInferenceSchedulerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, CreateInferenceScheduler(request), context); } CreateModelOutcome LookoutEquipmentClient::CreateModel(const CreateModelRequest& request) const { Aws::Http::URI uri = m_uri; return CreateModelOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER)); } CreateModelOutcomeCallable LookoutEquipmentClient::CreateModelCallable(const CreateModelRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< CreateModelOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->CreateModel(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void LookoutEquipmentClient::CreateModelAsync(const CreateModelRequest& request, const CreateModelResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->CreateModelAsyncHelper( request, handler, context ); } ); } void LookoutEquipmentClient::CreateModelAsyncHelper(const CreateModelRequest& request, const CreateModelResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, CreateModel(request), context); } DeleteDatasetOutcome LookoutEquipmentClient::DeleteDataset(const DeleteDatasetRequest& request) const { Aws::Http::URI uri = m_uri; return DeleteDatasetOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER)); } DeleteDatasetOutcomeCallable LookoutEquipmentClient::DeleteDatasetCallable(const DeleteDatasetRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DeleteDatasetOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DeleteDataset(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void LookoutEquipmentClient::DeleteDatasetAsync(const DeleteDatasetRequest& request, const DeleteDatasetResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DeleteDatasetAsyncHelper( request, handler, context ); } ); } void LookoutEquipmentClient::DeleteDatasetAsyncHelper(const DeleteDatasetRequest& request, const DeleteDatasetResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DeleteDataset(request), context); } DeleteInferenceSchedulerOutcome LookoutEquipmentClient::DeleteInferenceScheduler(const DeleteInferenceSchedulerRequest& request) const { Aws::Http::URI uri = m_uri; return DeleteInferenceSchedulerOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER)); } DeleteInferenceSchedulerOutcomeCallable LookoutEquipmentClient::DeleteInferenceSchedulerCallable(const DeleteInferenceSchedulerRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DeleteInferenceSchedulerOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DeleteInferenceScheduler(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void LookoutEquipmentClient::DeleteInferenceSchedulerAsync(const DeleteInferenceSchedulerRequest& request, const DeleteInferenceSchedulerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DeleteInferenceSchedulerAsyncHelper( request, handler, context ); } ); } void LookoutEquipmentClient::DeleteInferenceSchedulerAsyncHelper(const DeleteInferenceSchedulerRequest& request, const DeleteInferenceSchedulerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DeleteInferenceScheduler(request), context); } DeleteModelOutcome LookoutEquipmentClient::DeleteModel(const DeleteModelRequest& request) const { Aws::Http::URI uri = m_uri; return DeleteModelOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER)); } DeleteModelOutcomeCallable LookoutEquipmentClient::DeleteModelCallable(const DeleteModelRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DeleteModelOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DeleteModel(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void LookoutEquipmentClient::DeleteModelAsync(const DeleteModelRequest& request, const DeleteModelResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DeleteModelAsyncHelper( request, handler, context ); } ); } void LookoutEquipmentClient::DeleteModelAsyncHelper(const DeleteModelRequest& request, const DeleteModelResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DeleteModel(request), context); } DescribeDataIngestionJobOutcome LookoutEquipmentClient::DescribeDataIngestionJob(const DescribeDataIngestionJobRequest& request) const { Aws::Http::URI uri = m_uri; return DescribeDataIngestionJobOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER)); } DescribeDataIngestionJobOutcomeCallable LookoutEquipmentClient::DescribeDataIngestionJobCallable(const DescribeDataIngestionJobRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DescribeDataIngestionJobOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DescribeDataIngestionJob(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void LookoutEquipmentClient::DescribeDataIngestionJobAsync(const DescribeDataIngestionJobRequest& request, const DescribeDataIngestionJobResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DescribeDataIngestionJobAsyncHelper( request, handler, context ); } ); } void LookoutEquipmentClient::DescribeDataIngestionJobAsyncHelper(const DescribeDataIngestionJobRequest& request, const DescribeDataIngestionJobResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DescribeDataIngestionJob(request), context); } DescribeDatasetOutcome LookoutEquipmentClient::DescribeDataset(const DescribeDatasetRequest& request) const { Aws::Http::URI uri = m_uri; return DescribeDatasetOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER)); } DescribeDatasetOutcomeCallable LookoutEquipmentClient::DescribeDatasetCallable(const DescribeDatasetRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DescribeDatasetOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DescribeDataset(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void LookoutEquipmentClient::DescribeDatasetAsync(const DescribeDatasetRequest& request, const DescribeDatasetResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DescribeDatasetAsyncHelper( request, handler, context ); } ); } void LookoutEquipmentClient::DescribeDatasetAsyncHelper(const DescribeDatasetRequest& request, const DescribeDatasetResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DescribeDataset(request), context); } DescribeInferenceSchedulerOutcome LookoutEquipmentClient::DescribeInferenceScheduler(const DescribeInferenceSchedulerRequest& request) const { Aws::Http::URI uri = m_uri; return DescribeInferenceSchedulerOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER)); } DescribeInferenceSchedulerOutcomeCallable LookoutEquipmentClient::DescribeInferenceSchedulerCallable(const DescribeInferenceSchedulerRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DescribeInferenceSchedulerOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DescribeInferenceScheduler(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void LookoutEquipmentClient::DescribeInferenceSchedulerAsync(const DescribeInferenceSchedulerRequest& request, const DescribeInferenceSchedulerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DescribeInferenceSchedulerAsyncHelper( request, handler, context ); } ); } void LookoutEquipmentClient::DescribeInferenceSchedulerAsyncHelper(const DescribeInferenceSchedulerRequest& request, const DescribeInferenceSchedulerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DescribeInferenceScheduler(request), context); } DescribeModelOutcome LookoutEquipmentClient::DescribeModel(const DescribeModelRequest& request) const { Aws::Http::URI uri = m_uri; return DescribeModelOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER)); } DescribeModelOutcomeCallable LookoutEquipmentClient::DescribeModelCallable(const DescribeModelRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DescribeModelOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DescribeModel(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void LookoutEquipmentClient::DescribeModelAsync(const DescribeModelRequest& request, const DescribeModelResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DescribeModelAsyncHelper( request, handler, context ); } ); } void LookoutEquipmentClient::DescribeModelAsyncHelper(const DescribeModelRequest& request, const DescribeModelResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DescribeModel(request), context); } ListDataIngestionJobsOutcome LookoutEquipmentClient::ListDataIngestionJobs(const ListDataIngestionJobsRequest& request) const { Aws::Http::URI uri = m_uri; return ListDataIngestionJobsOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER)); } ListDataIngestionJobsOutcomeCallable LookoutEquipmentClient::ListDataIngestionJobsCallable(const ListDataIngestionJobsRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ListDataIngestionJobsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListDataIngestionJobs(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void LookoutEquipmentClient::ListDataIngestionJobsAsync(const ListDataIngestionJobsRequest& request, const ListDataIngestionJobsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ListDataIngestionJobsAsyncHelper( request, handler, context ); } ); } void LookoutEquipmentClient::ListDataIngestionJobsAsyncHelper(const ListDataIngestionJobsRequest& request, const ListDataIngestionJobsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ListDataIngestionJobs(request), context); } ListDatasetsOutcome LookoutEquipmentClient::ListDatasets(const ListDatasetsRequest& request) const { Aws::Http::URI uri = m_uri; return ListDatasetsOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER)); } ListDatasetsOutcomeCallable LookoutEquipmentClient::ListDatasetsCallable(const ListDatasetsRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ListDatasetsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListDatasets(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void LookoutEquipmentClient::ListDatasetsAsync(const ListDatasetsRequest& request, const ListDatasetsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ListDatasetsAsyncHelper( request, handler, context ); } ); } void LookoutEquipmentClient::ListDatasetsAsyncHelper(const ListDatasetsRequest& request, const ListDatasetsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ListDatasets(request), context); } ListInferenceExecutionsOutcome LookoutEquipmentClient::ListInferenceExecutions(const ListInferenceExecutionsRequest& request) const { Aws::Http::URI uri = m_uri; return ListInferenceExecutionsOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER)); } ListInferenceExecutionsOutcomeCallable LookoutEquipmentClient::ListInferenceExecutionsCallable(const ListInferenceExecutionsRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ListInferenceExecutionsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListInferenceExecutions(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void LookoutEquipmentClient::ListInferenceExecutionsAsync(const ListInferenceExecutionsRequest& request, const ListInferenceExecutionsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ListInferenceExecutionsAsyncHelper( request, handler, context ); } ); } void LookoutEquipmentClient::ListInferenceExecutionsAsyncHelper(const ListInferenceExecutionsRequest& request, const ListInferenceExecutionsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ListInferenceExecutions(request), context); } ListInferenceSchedulersOutcome LookoutEquipmentClient::ListInferenceSchedulers(const ListInferenceSchedulersRequest& request) const { Aws::Http::URI uri = m_uri; return ListInferenceSchedulersOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER)); } ListInferenceSchedulersOutcomeCallable LookoutEquipmentClient::ListInferenceSchedulersCallable(const ListInferenceSchedulersRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ListInferenceSchedulersOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListInferenceSchedulers(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void LookoutEquipmentClient::ListInferenceSchedulersAsync(const ListInferenceSchedulersRequest& request, const ListInferenceSchedulersResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ListInferenceSchedulersAsyncHelper( request, handler, context ); } ); } void LookoutEquipmentClient::ListInferenceSchedulersAsyncHelper(const ListInferenceSchedulersRequest& request, const ListInferenceSchedulersResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ListInferenceSchedulers(request), context); } ListModelsOutcome LookoutEquipmentClient::ListModels(const ListModelsRequest& request) const { Aws::Http::URI uri = m_uri; return ListModelsOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER)); } ListModelsOutcomeCallable LookoutEquipmentClient::ListModelsCallable(const ListModelsRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ListModelsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListModels(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void LookoutEquipmentClient::ListModelsAsync(const ListModelsRequest& request, const ListModelsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ListModelsAsyncHelper( request, handler, context ); } ); } void LookoutEquipmentClient::ListModelsAsyncHelper(const ListModelsRequest& request, const ListModelsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ListModels(request), context); } ListTagsForResourceOutcome LookoutEquipmentClient::ListTagsForResource(const ListTagsForResourceRequest& request) const { Aws::Http::URI uri = m_uri; return ListTagsForResourceOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER)); } ListTagsForResourceOutcomeCallable LookoutEquipmentClient::ListTagsForResourceCallable(const ListTagsForResourceRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ListTagsForResourceOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListTagsForResource(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void LookoutEquipmentClient::ListTagsForResourceAsync(const ListTagsForResourceRequest& request, const ListTagsForResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ListTagsForResourceAsyncHelper( request, handler, context ); } ); } void LookoutEquipmentClient::ListTagsForResourceAsyncHelper(const ListTagsForResourceRequest& request, const ListTagsForResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ListTagsForResource(request), context); } StartDataIngestionJobOutcome LookoutEquipmentClient::StartDataIngestionJob(const StartDataIngestionJobRequest& request) const { Aws::Http::URI uri = m_uri; return StartDataIngestionJobOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER)); } StartDataIngestionJobOutcomeCallable LookoutEquipmentClient::StartDataIngestionJobCallable(const StartDataIngestionJobRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< StartDataIngestionJobOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->StartDataIngestionJob(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void LookoutEquipmentClient::StartDataIngestionJobAsync(const StartDataIngestionJobRequest& request, const StartDataIngestionJobResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->StartDataIngestionJobAsyncHelper( request, handler, context ); } ); } void LookoutEquipmentClient::StartDataIngestionJobAsyncHelper(const StartDataIngestionJobRequest& request, const StartDataIngestionJobResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, StartDataIngestionJob(request), context); } StartInferenceSchedulerOutcome LookoutEquipmentClient::StartInferenceScheduler(const StartInferenceSchedulerRequest& request) const { Aws::Http::URI uri = m_uri; return StartInferenceSchedulerOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER)); } StartInferenceSchedulerOutcomeCallable LookoutEquipmentClient::StartInferenceSchedulerCallable(const StartInferenceSchedulerRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< StartInferenceSchedulerOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->StartInferenceScheduler(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void LookoutEquipmentClient::StartInferenceSchedulerAsync(const StartInferenceSchedulerRequest& request, const StartInferenceSchedulerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->StartInferenceSchedulerAsyncHelper( request, handler, context ); } ); } void LookoutEquipmentClient::StartInferenceSchedulerAsyncHelper(const StartInferenceSchedulerRequest& request, const StartInferenceSchedulerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, StartInferenceScheduler(request), context); } StopInferenceSchedulerOutcome LookoutEquipmentClient::StopInferenceScheduler(const StopInferenceSchedulerRequest& request) const { Aws::Http::URI uri = m_uri; return StopInferenceSchedulerOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER)); } StopInferenceSchedulerOutcomeCallable LookoutEquipmentClient::StopInferenceSchedulerCallable(const StopInferenceSchedulerRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< StopInferenceSchedulerOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->StopInferenceScheduler(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void LookoutEquipmentClient::StopInferenceSchedulerAsync(const StopInferenceSchedulerRequest& request, const StopInferenceSchedulerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->StopInferenceSchedulerAsyncHelper( request, handler, context ); } ); } void LookoutEquipmentClient::StopInferenceSchedulerAsyncHelper(const StopInferenceSchedulerRequest& request, const StopInferenceSchedulerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, StopInferenceScheduler(request), context); } TagResourceOutcome LookoutEquipmentClient::TagResource(const TagResourceRequest& request) const { Aws::Http::URI uri = m_uri; return TagResourceOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER)); } TagResourceOutcomeCallable LookoutEquipmentClient::TagResourceCallable(const TagResourceRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< TagResourceOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->TagResource(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void LookoutEquipmentClient::TagResourceAsync(const TagResourceRequest& request, const TagResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->TagResourceAsyncHelper( request, handler, context ); } ); } void LookoutEquipmentClient::TagResourceAsyncHelper(const TagResourceRequest& request, const TagResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, TagResource(request), context); } UntagResourceOutcome LookoutEquipmentClient::UntagResource(const UntagResourceRequest& request) const { Aws::Http::URI uri = m_uri; return UntagResourceOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER)); } UntagResourceOutcomeCallable LookoutEquipmentClient::UntagResourceCallable(const UntagResourceRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< UntagResourceOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->UntagResource(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void LookoutEquipmentClient::UntagResourceAsync(const UntagResourceRequest& request, const UntagResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->UntagResourceAsyncHelper( request, handler, context ); } ); } void LookoutEquipmentClient::UntagResourceAsyncHelper(const UntagResourceRequest& request, const UntagResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, UntagResource(request), context); } UpdateInferenceSchedulerOutcome LookoutEquipmentClient::UpdateInferenceScheduler(const UpdateInferenceSchedulerRequest& request) const { Aws::Http::URI uri = m_uri; return UpdateInferenceSchedulerOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER)); } UpdateInferenceSchedulerOutcomeCallable LookoutEquipmentClient::UpdateInferenceSchedulerCallable(const UpdateInferenceSchedulerRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< UpdateInferenceSchedulerOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->UpdateInferenceScheduler(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void LookoutEquipmentClient::UpdateInferenceSchedulerAsync(const UpdateInferenceSchedulerRequest& request, const UpdateInferenceSchedulerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->UpdateInferenceSchedulerAsyncHelper( request, handler, context ); } ); } void LookoutEquipmentClient::UpdateInferenceSchedulerAsyncHelper(const UpdateInferenceSchedulerRequest& request, const UpdateInferenceSchedulerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, UpdateInferenceScheduler(request), context); }
54.120556
259
0.804889
perfectrecall
619cc1d171ec873a1308e42f2a1ae93a8d8c82ad
10,763
cpp
C++
intern/cycles/device/device_denoising.cpp
1-MillionParanoidTterabytes/Blender-2.79b-blackened
e8d767324e69015aa66850d13bee7db1dc7d084b
[ "Unlicense" ]
2
2018-06-18T01:50:25.000Z
2018-06-18T01:50:32.000Z
intern/cycles/device/device_denoising.cpp
1-MillionParanoidTterabytes/Blender-2.79b-blackened
e8d767324e69015aa66850d13bee7db1dc7d084b
[ "Unlicense" ]
null
null
null
intern/cycles/device/device_denoising.cpp
1-MillionParanoidTterabytes/Blender-2.79b-blackened
e8d767324e69015aa66850d13bee7db1dc7d084b
[ "Unlicense" ]
null
null
null
/* * Copyright 2011-2017 Blender Foundation * * 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 "device/device_denoising.h" #include "kernel/filter/filter_defines.h" CCL_NAMESPACE_BEGIN void DenoisingTask::init_from_devicetask(const DeviceTask &task) { radius = task.denoising_radius; nlm_k_2 = powf(2.0f, lerp(-5.0f, 3.0f, task.denoising_strength)); if(task.denoising_relative_pca) { pca_threshold = -powf(10.0f, lerp(-8.0f, 0.0f, task.denoising_feature_strength)); } else { pca_threshold = powf(10.0f, lerp(-5.0f, 3.0f, task.denoising_feature_strength)); } render_buffer.pass_stride = task.pass_stride; render_buffer.denoising_data_offset = task.pass_denoising_data; render_buffer.denoising_clean_offset = task.pass_denoising_clean; /* Expand filter_area by radius pixels and clamp the result to the extent of the neighboring tiles */ rect = make_int4(max(tiles->x[0], filter_area.x - radius), max(tiles->y[0], filter_area.y - radius), min(tiles->x[3], filter_area.x + filter_area.z + radius), min(tiles->y[3], filter_area.y + filter_area.w + radius)); } void DenoisingTask::tiles_from_rendertiles(RenderTile *rtiles) { tiles = (TilesInfo*) tiles_mem.resize(sizeof(TilesInfo)/sizeof(int)); device_ptr buffers[9]; for(int i = 0; i < 9; i++) { buffers[i] = rtiles[i].buffer; tiles->offsets[i] = rtiles[i].offset; tiles->strides[i] = rtiles[i].stride; } tiles->x[0] = rtiles[3].x; tiles->x[1] = rtiles[4].x; tiles->x[2] = rtiles[5].x; tiles->x[3] = rtiles[5].x + rtiles[5].w; tiles->y[0] = rtiles[1].y; tiles->y[1] = rtiles[4].y; tiles->y[2] = rtiles[7].y; tiles->y[3] = rtiles[7].y + rtiles[7].h; render_buffer.offset = rtiles[4].offset; render_buffer.stride = rtiles[4].stride; render_buffer.ptr = rtiles[4].buffer; functions.set_tiles(buffers); } bool DenoisingTask::run_denoising() { /* Allocate denoising buffer. */ buffer.passes = 14; buffer.w = align_up(rect.z - rect.x, 4); buffer.h = rect.w - rect.y; buffer.pass_stride = align_up(buffer.w * buffer.h, divide_up(device->mem_address_alignment(), sizeof(float))); buffer.mem.resize(buffer.pass_stride * buffer.passes); device->mem_alloc("Denoising Pixel Buffer", buffer.mem, MEM_READ_WRITE); device_ptr null_ptr = (device_ptr) 0; /* Prefilter shadow feature. */ { device_sub_ptr unfiltered_a (device, buffer.mem, 0, buffer.pass_stride, MEM_READ_WRITE); device_sub_ptr unfiltered_b (device, buffer.mem, 1*buffer.pass_stride, buffer.pass_stride, MEM_READ_WRITE); device_sub_ptr sample_var (device, buffer.mem, 2*buffer.pass_stride, buffer.pass_stride, MEM_READ_WRITE); device_sub_ptr sample_var_var (device, buffer.mem, 3*buffer.pass_stride, buffer.pass_stride, MEM_READ_WRITE); device_sub_ptr buffer_var (device, buffer.mem, 5*buffer.pass_stride, buffer.pass_stride, MEM_READ_WRITE); device_sub_ptr filtered_var (device, buffer.mem, 6*buffer.pass_stride, buffer.pass_stride, MEM_READ_WRITE); device_sub_ptr nlm_temporary_1(device, buffer.mem, 7*buffer.pass_stride, buffer.pass_stride, MEM_READ_WRITE); device_sub_ptr nlm_temporary_2(device, buffer.mem, 8*buffer.pass_stride, buffer.pass_stride, MEM_READ_WRITE); device_sub_ptr nlm_temporary_3(device, buffer.mem, 9*buffer.pass_stride, buffer.pass_stride, MEM_READ_WRITE); nlm_state.temporary_1_ptr = *nlm_temporary_1; nlm_state.temporary_2_ptr = *nlm_temporary_2; nlm_state.temporary_3_ptr = *nlm_temporary_3; /* Get the A/B unfiltered passes, the combined sample variance, the estimated variance of the sample variance and the buffer variance. */ functions.divide_shadow(*unfiltered_a, *unfiltered_b, *sample_var, *sample_var_var, *buffer_var); /* Smooth the (generally pretty noisy) buffer variance using the spatial information from the sample variance. */ nlm_state.set_parameters(6, 3, 4.0f, 1.0f); functions.non_local_means(*buffer_var, *sample_var, *sample_var_var, *filtered_var); /* Reuse memory, the previous data isn't needed anymore. */ device_ptr filtered_a = *buffer_var, filtered_b = *sample_var; /* Use the smoothed variance to filter the two shadow half images using each other for weight calculation. */ nlm_state.set_parameters(5, 3, 1.0f, 0.25f); functions.non_local_means(*unfiltered_a, *unfiltered_b, *filtered_var, filtered_a); functions.non_local_means(*unfiltered_b, *unfiltered_a, *filtered_var, filtered_b); device_ptr residual_var = *sample_var_var; /* Estimate the residual variance between the two filtered halves. */ functions.combine_halves(filtered_a, filtered_b, null_ptr, residual_var, 2, rect); device_ptr final_a = *unfiltered_a, final_b = *unfiltered_b; /* Use the residual variance for a second filter pass. */ nlm_state.set_parameters(4, 2, 1.0f, 0.5f); functions.non_local_means(filtered_a, filtered_b, residual_var, final_a); functions.non_local_means(filtered_b, filtered_a, residual_var, final_b); /* Combine the two double-filtered halves to a final shadow feature. */ device_sub_ptr shadow_pass(device, buffer.mem, 4*buffer.pass_stride, buffer.pass_stride, MEM_READ_WRITE); functions.combine_halves(final_a, final_b, *shadow_pass, null_ptr, 0, rect); } /* Prefilter general features. */ { device_sub_ptr unfiltered (device, buffer.mem, 8*buffer.pass_stride, buffer.pass_stride, MEM_READ_WRITE); device_sub_ptr variance (device, buffer.mem, 9*buffer.pass_stride, buffer.pass_stride, MEM_READ_WRITE); device_sub_ptr nlm_temporary_1(device, buffer.mem, 10*buffer.pass_stride, buffer.pass_stride, MEM_READ_WRITE); device_sub_ptr nlm_temporary_2(device, buffer.mem, 11*buffer.pass_stride, buffer.pass_stride, MEM_READ_WRITE); device_sub_ptr nlm_temporary_3(device, buffer.mem, 12*buffer.pass_stride, buffer.pass_stride, MEM_READ_WRITE); nlm_state.temporary_1_ptr = *nlm_temporary_1; nlm_state.temporary_2_ptr = *nlm_temporary_2; nlm_state.temporary_3_ptr = *nlm_temporary_3; int mean_from[] = { 0, 1, 2, 12, 6, 7, 8 }; int variance_from[] = { 3, 4, 5, 13, 9, 10, 11}; int pass_to[] = { 1, 2, 3, 0, 5, 6, 7}; for(int pass = 0; pass < 7; pass++) { device_sub_ptr feature_pass(device, buffer.mem, pass_to[pass]*buffer.pass_stride, buffer.pass_stride, MEM_READ_WRITE); /* Get the unfiltered pass and its variance from the RenderBuffers. */ functions.get_feature(mean_from[pass], variance_from[pass], *unfiltered, *variance); /* Smooth the pass and store the result in the denoising buffers. */ nlm_state.set_parameters(2, 2, 1.0f, 0.25f); functions.non_local_means(*unfiltered, *unfiltered, *variance, *feature_pass); } } /* Copy color passes. */ { int mean_from[] = {20, 21, 22}; int variance_from[] = {23, 24, 25}; int mean_to[] = { 8, 9, 10}; int variance_to[] = {11, 12, 13}; int num_color_passes = 3; device_only_memory<float> temp_color; temp_color.resize(3*buffer.pass_stride); device->mem_alloc("Denoising temporary color", temp_color, MEM_READ_WRITE); for(int pass = 0; pass < num_color_passes; pass++) { device_sub_ptr color_pass(device, temp_color, pass*buffer.pass_stride, buffer.pass_stride, MEM_READ_WRITE); device_sub_ptr color_var_pass(device, buffer.mem, variance_to[pass]*buffer.pass_stride, buffer.pass_stride, MEM_READ_WRITE); functions.get_feature(mean_from[pass], variance_from[pass], *color_pass, *color_var_pass); } { device_sub_ptr depth_pass (device, buffer.mem, 0, buffer.pass_stride, MEM_READ_WRITE); device_sub_ptr color_var_pass(device, buffer.mem, variance_to[0]*buffer.pass_stride, 3*buffer.pass_stride, MEM_READ_WRITE); device_sub_ptr output_pass (device, buffer.mem, mean_to[0]*buffer.pass_stride, 3*buffer.pass_stride, MEM_READ_WRITE); functions.detect_outliers(temp_color.device_pointer, *color_var_pass, *depth_pass, *output_pass); } device->mem_free(temp_color); } storage.w = filter_area.z; storage.h = filter_area.w; storage.transform.resize(storage.w*storage.h*TRANSFORM_SIZE); storage.rank.resize(storage.w*storage.h); device->mem_alloc("Denoising Transform", storage.transform, MEM_READ_WRITE); device->mem_alloc("Denoising Rank", storage.rank, MEM_READ_WRITE); functions.construct_transform(); device_only_memory<float> temporary_1; device_only_memory<float> temporary_2; temporary_1.resize(buffer.w*buffer.h); temporary_2.resize(buffer.w*buffer.h); device->mem_alloc("Denoising NLM temporary 1", temporary_1, MEM_READ_WRITE); device->mem_alloc("Denoising NLM temporary 2", temporary_2, MEM_READ_WRITE); reconstruction_state.temporary_1_ptr = temporary_1.device_pointer; reconstruction_state.temporary_2_ptr = temporary_2.device_pointer; storage.XtWX.resize(storage.w*storage.h*XTWX_SIZE); storage.XtWY.resize(storage.w*storage.h*XTWY_SIZE); device->mem_alloc("Denoising XtWX", storage.XtWX, MEM_READ_WRITE); device->mem_alloc("Denoising XtWY", storage.XtWY, MEM_READ_WRITE); reconstruction_state.filter_rect = make_int4(filter_area.x-rect.x, filter_area.y-rect.y, storage.w, storage.h); int tile_coordinate_offset = filter_area.y*render_buffer.stride + filter_area.x; reconstruction_state.buffer_params = make_int4(render_buffer.offset + tile_coordinate_offset, render_buffer.stride, render_buffer.pass_stride, render_buffer.denoising_clean_offset); reconstruction_state.source_w = rect.z-rect.x; reconstruction_state.source_h = rect.w-rect.y; { device_sub_ptr color_ptr (device, buffer.mem, 8*buffer.pass_stride, 3*buffer.pass_stride, MEM_READ_WRITE); device_sub_ptr color_var_ptr(device, buffer.mem, 11*buffer.pass_stride, 3*buffer.pass_stride, MEM_READ_WRITE); functions.reconstruct(*color_ptr, *color_var_ptr, render_buffer.ptr); } device->mem_free(storage.XtWX); device->mem_free(storage.XtWY); device->mem_free(storage.transform); device->mem_free(storage.rank); device->mem_free(temporary_1); device->mem_free(temporary_2); device->mem_free(buffer.mem); device->mem_free(tiles_mem); return true; } CCL_NAMESPACE_END
46.193133
139
0.737341
1-MillionParanoidTterabytes
619d8b0c7ba4d8ea9778dc49055f6d2775c0da67
358
cpp
C++
clang/test/CodeGenCXX/block.cpp
clairechingching/ScaffCC
737ae90f85d9fe79819d66219747d27efa4fa5b9
[ "BSD-2-Clause" ]
36
2015-01-13T19:34:04.000Z
2022-03-07T22:22:15.000Z
clang/test/CodeGenCXX/block.cpp
clairechingching/ScaffCC
737ae90f85d9fe79819d66219747d27efa4fa5b9
[ "BSD-2-Clause" ]
7
2015-10-20T19:05:01.000Z
2021-11-13T14:55:47.000Z
clang/test/CodeGenCXX/block.cpp
clairechingching/ScaffCC
737ae90f85d9fe79819d66219747d27efa4fa5b9
[ "BSD-2-Clause" ]
18
2015-04-23T20:59:52.000Z
2021-11-18T20:06:39.000Z
// RUN: %clang_cc1 %s -emit-llvm -o - -fblocks // Just test that this doesn't crash the compiler... void func(void*); struct Test { virtual void use() { func((void*)this); } Test(Test&c) { func((void*)this); } Test() { func((void*)this); } }; void useBlock(void (^)(void)); int main (void) { __block Test t; useBlock(^(void) { t.use(); }); }
17.9
52
0.589385
clairechingching
619dc2d7a465539280ce70ca19acfb2c51194ad7
624
cpp
C++
Greedy/Maximum Number of Non-Overlapping Subarrays With Sum Equals Target/main.cpp
pratikj697/hacktoberfest-competitiveprogramming
3b392edf61d2bd284bd5714af72abd76ff049340
[ "MIT" ]
22
2021-10-02T13:18:58.000Z
2021-10-13T18:27:06.000Z
Greedy/Maximum Number of Non-Overlapping Subarrays With Sum Equals Target/main.cpp
pratikj697/hacktoberfest-competitiveprogramming
3b392edf61d2bd284bd5714af72abd76ff049340
[ "MIT" ]
96
2021-10-02T14:14:43.000Z
2021-10-09T06:17:33.000Z
Greedy/Maximum Number of Non-Overlapping Subarrays With Sum Equals Target/main.cpp
pratikj697/hacktoberfest-competitiveprogramming
3b392edf61d2bd284bd5714af72abd76ff049340
[ "MIT" ]
112
2021-10-02T14:57:15.000Z
2021-10-15T05:45:30.000Z
#include <iostream> #include <bits/stdc++.h> using namespace std; class Solution { public: int maxNonOverlapping(vector<int>& nums, int target) { int ans = 0, psum = 0; unordered_set<int> s; s.emplace(0); for (int i = 0; i < nums.size(); i++) { psum += nums[i]; if (s.count(psum - target)) { ans++; s.clear(); } s.emplace(psum); } return ans; } }; int main() { Solution s; vector<int> nums{1, 2, 1, 2, 4, 2, 1}; cout << s.maxNonOverlapping(nums, 3) << endl; return 0; }
21.517241
58
0.474359
pratikj697
619e7ff1a82ee7d4aea38fd616220d1998ff658f
6,001
cpp
C++
src/mlapack/Rlanv2.cpp
JaegerP/gmpack
1396fda32177b1517cb6c176543025c3336c8c21
[ "BSD-2-Clause" ]
null
null
null
src/mlapack/Rlanv2.cpp
JaegerP/gmpack
1396fda32177b1517cb6c176543025c3336c8c21
[ "BSD-2-Clause" ]
null
null
null
src/mlapack/Rlanv2.cpp
JaegerP/gmpack
1396fda32177b1517cb6c176543025c3336c8c21
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (c) 2008-2010 * Nakata, Maho * All rights reserved. * * $Id: Rlanv2.cpp,v 1.5 2010/08/07 04:48:32 nakatamaho Exp $ * * 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 AUTHOR 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 AUTHOR 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. * */ /* Copyright (c) 1992-2007 The University of Tennessee. All rights reserved. $COPYRIGHT$ Additional copyrights may follow $HEADER$ 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 listed in this license in the documentation and/or other materials provided with the distribution. - Neither the name of the copyright holders 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 <mblas.h> #include <mlapack.h> void Rlanv2(REAL * a, REAL * b, REAL * c, REAL * d, REAL * rt1r, REAL * rt1i, REAL * rt2r, REAL * rt2i, REAL * cs, REAL * sn) { REAL p, z, aa, bb, cc, dd, cs1, sn1, sab, sac, eps, tau, temp, scale, bcmax, bcmis, sigma; REAL One = 1.0, Half = 0.5, Zero = 0.0, Four = 4.0; REAL mtemp1, mtemp2; //Parameters of the rotation matrix. eps = Rlamch("P"); if (*c == Zero) { *cs = One; *sn = Zero; goto L10; } else if (*b == Zero) { //Swap rows and columns *cs = Zero; *sn = One; temp = *d; *d = *a; *a = temp; *b = -(*c); *c = Zero; goto L10; } else if (*a - *d == Zero && sign(One, *b) != sign(One, *c)) { *cs = One; *sn = Zero; goto L10; } else { temp = *a - *d; p = temp * Half; bcmax = max(*b, *c); bcmis = min(*b, *c) * sign(One, *b) * sign(One, *c); mtemp1 = abs(p); mtemp2 = bcmax; scale = max(mtemp1, mtemp2); z = p / scale * p + bcmax / scale * bcmis; //If Z is of the order of the machine accuracy, postpone the //decision on the nature of eigenvalues if (z >= eps * Four) { //Real eigenvalues. Compute A and D. mtemp1 = sqrt(scale) * sqrt(z); z = p + sign(mtemp1, p); *a = *d + z; *d -= bcmax / z * bcmis; //Compute B and the rotation matrix tau = Rlapy2(*c, z); *cs = z / tau; *sn = *c / tau; *b -= *c; *c = Zero; } else { //Complex eigenvalues, or real (almost) equal eigenvalues. //Make diagonal elements equal. sigma = *b + *c; tau = Rlapy2(sigma, temp); *cs = sqrt((abs(sigma) / tau + One) * Half); *sn = -(p / (tau * *cs)) * sign(One, sigma); //Compute [ AA BB ] = [ A B ] [ CS -SN ] // [ CC DD ] [ C D ] [ SN CS ] aa = *a * *cs + *b * *sn; bb = -(*a) * *sn + *b * *cs; cc = *c * *cs + *d * *sn; dd = -(*c) * *sn + *d * *cs; //Compute [ A B ] = [ CS SN ] [ AA BB ] // [ C D ] [-SN CS ] [ CC DD ] *a = aa * *cs + cc * *sn; *b = bb * *cs + dd * *sn; *c = -aa * *sn + cc * *cs; *d = -bb * *sn + dd * *cs; temp = (*a + *d) * Half; *a = temp; *d = temp; if (*c != Zero) { if (*b != Zero) { if (sign(One, *b) == sign(One, *c)) { //Real eigenvalues: reduce to upper triangular form sab = sqrt((abs(*b))); sac = sqrt((abs(*c))); mtemp1 = sab * sac; p = sign(mtemp1, *c); tau = One / sqrt(abs(*b + *c)); *a = temp + p; *d = temp - p; *b -= *c; *c = Zero; cs1 = sab * tau; sn1 = sac * tau; temp = *cs * cs1 - *sn * sn1; *sn = *cs * sn1 + *sn * cs1; *cs = temp; } } else { *b = -(*c); *c = Zero; temp = *cs; *cs = -(*sn); *sn = temp; } } } } L10: //Store eigenvalues in (RT1R,RT1I) and (RT2R,RT2I). *rt1r = *a; *rt2r = *d; if (*c == Zero) { *rt1i = Zero; *rt2i = Zero; } else { *rt1i = sqrt((abs(*b))) * sqrt((abs(*c))); *rt2i = -(*rt1i); } return; }
30.005
125
0.61873
JaegerP
619eb40613bab64dde4318ed75324f67467526a6
4,207
hpp
C++
Systems/Engine/Area.hpp
jodavis42/ZeroPhysicsTestbed
e84a3f6faf16b7a4242dc049121b5338e80039f8
[ "MIT" ]
1
2022-03-26T21:08:19.000Z
2022-03-26T21:08:19.000Z
Systems/Engine/Area.hpp
jodavis42/ZeroPhysicsTestbed
e84a3f6faf16b7a4242dc049121b5338e80039f8
[ "MIT" ]
null
null
null
Systems/Engine/Area.hpp
jodavis42/ZeroPhysicsTestbed
e84a3f6faf16b7a4242dc049121b5338e80039f8
[ "MIT" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// /// /// \file Area.hpp /// /// /// Authors: Chris Peters, Ryan Edgemon /// Copyright 2010-2012, DigiPen Institute of Technology /// /////////////////////////////////////////////////////////////////////////////// #pragma once namespace Zero { class Area; namespace Events { DeclareEvent(AreaChanged); } /// Sent when an area component's size or origin changes. class AreaEvent : public Event { public: ZilchDeclareType(AreaEvent, TypeCopyMode::ReferenceType); /// The area component that triggered this event. Area* mArea; }; class Area : public Component { public: ZilchDeclareType(Area, TypeCopyMode::ReferenceType); //Component Interface void Serialize(Serializer& stream) override; void Initialize(CogInitializer& initializer) override; void SetDefaults() override; void DebugDraw() override; /// Location of the Origin of the Area Location::Enum GetOrigin(); void SetOrigin(Location::Enum type); /// Size of the Area Vec2 GetSize(); void SetSize(Vec2 newSize); /// Local space Aabb for the area Aabb GetLocalAabb(); /// World space Aabb for the area Aabb GetAabb(); /// Offset of the given location in local space Vec2 LocalOffsetOf(Location::Enum location); Vec2 OffsetOfOffset(Location::Enum location); // Interanls Vec2 GetLocalTranslation( ); void SetLocalTranslation(Vec2Param translation); Vec2 GetWorldTranslation( ); void SetWorldTranslation(Vec2Param worldTranslation); /// Rectangle representing the area relative to parent. Rectangle GetLocalRectangle( ); void SetLocalRectangle(RectangleParam rectangle); /// Rectangle representing the area in world space. Rectangle GetWorldRectangle( ); void SetWorldRectangle(RectangleParam rectangle); Vec2 GetLocalLocation(Location::Enum location); void SetLocalLocation(Location::Enum location, Vec2Param localTranslation); Vec2 GetWorldLocation(Location::Enum location); void SetWorldLocation(Location::Enum location, Vec2Param worldTranslation); #define OffsetOfGetter(location) Vec2 Get##location() { return LocalOffsetOf(Location::location); } OffsetOfGetter(TopLeft) OffsetOfGetter(TopCenter) OffsetOfGetter(TopRight) OffsetOfGetter(CenterLeft) OffsetOfGetter(Center) OffsetOfGetter(CenterRight) OffsetOfGetter(BottomLeft) OffsetOfGetter(BottomCenter) OffsetOfGetter(BottomRight) #undef OffsetOfGetter #define LocationGetterSetter(location) \ Vec2 GetLocal##location() { return GetLocalLocation(Location::location); } \ void SetLocal##location(Vec2Param localTranslation) { SetLocalLocation(Location::location, localTranslation); } \ Vec2 GetWorld##location() { return GetWorldLocation(Location::location); } \ void SetWorld##location(Vec2Param worldTranslation) { SetWorldLocation(Location::location, worldTranslation); } LocationGetterSetter(TopLeft) LocationGetterSetter(TopCenter) LocationGetterSetter(TopRight) LocationGetterSetter(CenterLeft) LocationGetterSetter(Center) LocationGetterSetter(CenterRight) LocationGetterSetter(BottomLeft) LocationGetterSetter(BottomCenter) LocationGetterSetter(BottomRight) #undef LocationGetterSetter float GetLocalTop( ); void SetLocalTop(float localTop); float GetWorldTop( ); void SetWorldTop(float worldTop); float GetLocalRight( ); void SetLocalRight(float localRight); float GetWorldRight( ); void SetWorldRight(float worldRight); float GetLocalBottom( ); void SetLocalBottom(float localBottom); float GetWorldBottom( ); void SetWorldBottom(float worldBottom); float GetLocalLeft( ); void SetLocalLeft(float localLeft); float GetWorldLeft( ); void SetWorldLeft(float worldLeft); //Internals void DoAreaChanged(); Vec2 mSize; Location::Enum mOrigin; Transform* mTransform; }; }
31.631579
117
0.672688
jodavis42
61a272f8294c476bc42e37598479bc98d345dbbc
83,468
cpp
C++
B2G/gecko/gfx/angle/src/libGLESv2/ProgramBinary.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-08-31T15:24:31.000Z
2020-04-24T20:31:29.000Z
B2G/gecko/gfx/angle/src/libGLESv2/ProgramBinary.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
null
null
null
B2G/gecko/gfx/angle/src/libGLESv2/ProgramBinary.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-07-29T07:17:15.000Z
2020-11-04T06:55:37.000Z
// // Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // Program.cpp: Implements the gl::Program class. Implements GL program objects // and related functionality. [OpenGL ES 2.0.24] section 2.10.3 page 28. #include "libGLESv2/BinaryStream.h" #include "libGLESv2/Program.h" #include "libGLESv2/ProgramBinary.h" #include "common/debug.h" #include "common/version.h" #include "libGLESv2/main.h" #include "libGLESv2/Shader.h" #include "libGLESv2/utilities.h" #include <string> #if !defined(ANGLE_COMPILE_OPTIMIZATION_LEVEL) #define ANGLE_COMPILE_OPTIMIZATION_LEVEL D3DCOMPILE_OPTIMIZATION_LEVEL3 #endif namespace gl { std::string str(int i) { char buffer[20]; snprintf(buffer, sizeof(buffer), "%d", i); return buffer; } Uniform::Uniform(GLenum type, const std::string &_name, unsigned int arraySize) : type(type), _name(_name), name(ProgramBinary::undecorateUniform(_name)), arraySize(arraySize) { int bytes = UniformInternalSize(type) * arraySize; data = new unsigned char[bytes]; memset(data, 0, bytes); dirty = true; } Uniform::~Uniform() { delete[] data; } bool Uniform::isArray() { return _name.compare(0, 3, "ar_") == 0; } UniformLocation::UniformLocation(const std::string &_name, unsigned int element, unsigned int index) : name(ProgramBinary::undecorateUniform(_name)), element(element), index(index) { } unsigned int ProgramBinary::mCurrentSerial = 1; ProgramBinary::ProgramBinary() : RefCountObject(0), mSerial(issueSerial()) { mDevice = getDevice(); mPixelExecutable = NULL; mVertexExecutable = NULL; mConstantTablePS = NULL; mConstantTableVS = NULL; mValidated = false; for (int index = 0; index < MAX_VERTEX_ATTRIBS; index++) { mSemanticIndex[index] = -1; } for (int index = 0; index < MAX_TEXTURE_IMAGE_UNITS; index++) { mSamplersPS[index].active = false; } for (int index = 0; index < MAX_VERTEX_TEXTURE_IMAGE_UNITS_VTF; index++) { mSamplersVS[index].active = false; } mUsedVertexSamplerRange = 0; mUsedPixelSamplerRange = 0; mDxDepthRangeLocation = -1; mDxDepthLocation = -1; mDxCoordLocation = -1; mDxHalfPixelSizeLocation = -1; mDxFrontCCWLocation = -1; mDxPointsOrLinesLocation = -1; } ProgramBinary::~ProgramBinary() { if (mPixelExecutable) { mPixelExecutable->Release(); } if (mVertexExecutable) { mVertexExecutable->Release(); } if (mConstantTablePS) { mConstantTablePS->Release(); } if (mConstantTableVS) { mConstantTableVS->Release(); } while (!mUniforms.empty()) { delete mUniforms.back(); mUniforms.pop_back(); } } unsigned int ProgramBinary::getSerial() const { return mSerial; } unsigned int ProgramBinary::issueSerial() { return mCurrentSerial++; } IDirect3DPixelShader9 *ProgramBinary::getPixelShader() { return mPixelExecutable; } IDirect3DVertexShader9 *ProgramBinary::getVertexShader() { return mVertexExecutable; } GLuint ProgramBinary::getAttributeLocation(const char *name) { if (name) { for (int index = 0; index < MAX_VERTEX_ATTRIBS; index++) { if (mLinkedAttribute[index].name == std::string(name)) { return index; } } } return -1; } int ProgramBinary::getSemanticIndex(int attributeIndex) { ASSERT(attributeIndex >= 0 && attributeIndex < MAX_VERTEX_ATTRIBS); return mSemanticIndex[attributeIndex]; } // Returns one more than the highest sampler index used. GLint ProgramBinary::getUsedSamplerRange(SamplerType type) { switch (type) { case SAMPLER_PIXEL: return mUsedPixelSamplerRange; case SAMPLER_VERTEX: return mUsedVertexSamplerRange; default: UNREACHABLE(); return 0; } } // Returns the index of the texture image unit (0-19) corresponding to a Direct3D 9 sampler // index (0-15 for the pixel shader and 0-3 for the vertex shader). GLint ProgramBinary::getSamplerMapping(SamplerType type, unsigned int samplerIndex) { GLint logicalTextureUnit = -1; switch (type) { case SAMPLER_PIXEL: ASSERT(samplerIndex < sizeof(mSamplersPS)/sizeof(mSamplersPS[0])); if (mSamplersPS[samplerIndex].active) { logicalTextureUnit = mSamplersPS[samplerIndex].logicalTextureUnit; } break; case SAMPLER_VERTEX: ASSERT(samplerIndex < sizeof(mSamplersVS)/sizeof(mSamplersVS[0])); if (mSamplersVS[samplerIndex].active) { logicalTextureUnit = mSamplersVS[samplerIndex].logicalTextureUnit; } break; default: UNREACHABLE(); } if (logicalTextureUnit >= 0 && logicalTextureUnit < (GLint)getContext()->getMaximumCombinedTextureImageUnits()) { return logicalTextureUnit; } return -1; } // Returns the texture type for a given Direct3D 9 sampler type and // index (0-15 for the pixel shader and 0-3 for the vertex shader). TextureType ProgramBinary::getSamplerTextureType(SamplerType type, unsigned int samplerIndex) { switch (type) { case SAMPLER_PIXEL: ASSERT(samplerIndex < sizeof(mSamplersPS)/sizeof(mSamplersPS[0])); ASSERT(mSamplersPS[samplerIndex].active); return mSamplersPS[samplerIndex].textureType; case SAMPLER_VERTEX: ASSERT(samplerIndex < sizeof(mSamplersVS)/sizeof(mSamplersVS[0])); ASSERT(mSamplersVS[samplerIndex].active); return mSamplersVS[samplerIndex].textureType; default: UNREACHABLE(); } return TEXTURE_2D; } GLint ProgramBinary::getUniformLocation(std::string name) { unsigned int subscript = 0; // Strip any trailing array operator and retrieve the subscript size_t open = name.find_last_of('['); size_t close = name.find_last_of(']'); if (open != std::string::npos && close == name.length() - 1) { subscript = atoi(name.substr(open + 1).c_str()); name.erase(open); } unsigned int numUniforms = mUniformIndex.size(); for (unsigned int location = 0; location < numUniforms; location++) { if (mUniformIndex[location].name == name && mUniformIndex[location].element == subscript) { return location; } } return -1; } bool ProgramBinary::setUniform1fv(GLint location, GLsizei count, const GLfloat* v) { if (location < 0 || location >= (int)mUniformIndex.size()) { return false; } Uniform *targetUniform = mUniforms[mUniformIndex[location].index]; targetUniform->dirty = true; if (targetUniform->type == GL_FLOAT) { int arraySize = targetUniform->arraySize; if (arraySize == 1 && count > 1) return false; // attempting to write an array to a non-array uniform is an INVALID_OPERATION count = std::min(arraySize - (int)mUniformIndex[location].element, count); GLfloat *target = (GLfloat*)targetUniform->data + mUniformIndex[location].element * 4; for (int i = 0; i < count; i++) { target[0] = v[0]; target[1] = 0; target[2] = 0; target[3] = 0; target += 4; v += 1; } } else if (targetUniform->type == GL_BOOL) { int arraySize = targetUniform->arraySize; if (arraySize == 1 && count > 1) return false; // attempting to write an array to a non-array uniform is an INVALID_OPERATION count = std::min(arraySize - (int)mUniformIndex[location].element, count); GLboolean *boolParams = (GLboolean*)targetUniform->data + mUniformIndex[location].element; for (int i = 0; i < count; ++i) { if (v[i] == 0.0f) { boolParams[i] = GL_FALSE; } else { boolParams[i] = GL_TRUE; } } } else { return false; } return true; } bool ProgramBinary::setUniform2fv(GLint location, GLsizei count, const GLfloat *v) { if (location < 0 || location >= (int)mUniformIndex.size()) { return false; } Uniform *targetUniform = mUniforms[mUniformIndex[location].index]; targetUniform->dirty = true; if (targetUniform->type == GL_FLOAT_VEC2) { int arraySize = targetUniform->arraySize; if (arraySize == 1 && count > 1) return false; // attempting to write an array to a non-array uniform is an INVALID_OPERATION count = std::min(arraySize - (int)mUniformIndex[location].element, count); GLfloat *target = (GLfloat*)targetUniform->data + mUniformIndex[location].element * 4; for (int i = 0; i < count; i++) { target[0] = v[0]; target[1] = v[1]; target[2] = 0; target[3] = 0; target += 4; v += 2; } } else if (targetUniform->type == GL_BOOL_VEC2) { int arraySize = targetUniform->arraySize; if (arraySize == 1 && count > 1) return false; // attempting to write an array to a non-array uniform is an INVALID_OPERATION count = std::min(arraySize - (int)mUniformIndex[location].element, count); GLboolean *boolParams = (GLboolean*)targetUniform->data + mUniformIndex[location].element * 2; for (int i = 0; i < count * 2; ++i) { if (v[i] == 0.0f) { boolParams[i] = GL_FALSE; } else { boolParams[i] = GL_TRUE; } } } else { return false; } return true; } bool ProgramBinary::setUniform3fv(GLint location, GLsizei count, const GLfloat *v) { if (location < 0 || location >= (int)mUniformIndex.size()) { return false; } Uniform *targetUniform = mUniforms[mUniformIndex[location].index]; targetUniform->dirty = true; if (targetUniform->type == GL_FLOAT_VEC3) { int arraySize = targetUniform->arraySize; if (arraySize == 1 && count > 1) return false; // attempting to write an array to a non-array uniform is an INVALID_OPERATION count = std::min(arraySize - (int)mUniformIndex[location].element, count); GLfloat *target = (GLfloat*)targetUniform->data + mUniformIndex[location].element * 4; for (int i = 0; i < count; i++) { target[0] = v[0]; target[1] = v[1]; target[2] = v[2]; target[3] = 0; target += 4; v += 3; } } else if (targetUniform->type == GL_BOOL_VEC3) { int arraySize = targetUniform->arraySize; if (arraySize == 1 && count > 1) return false; // attempting to write an array to a non-array uniform is an INVALID_OPERATION count = std::min(arraySize - (int)mUniformIndex[location].element, count); GLboolean *boolParams = (GLboolean*)targetUniform->data + mUniformIndex[location].element * 3; for (int i = 0; i < count * 3; ++i) { if (v[i] == 0.0f) { boolParams[i] = GL_FALSE; } else { boolParams[i] = GL_TRUE; } } } else { return false; } return true; } bool ProgramBinary::setUniform4fv(GLint location, GLsizei count, const GLfloat *v) { if (location < 0 || location >= (int)mUniformIndex.size()) { return false; } Uniform *targetUniform = mUniforms[mUniformIndex[location].index]; targetUniform->dirty = true; if (targetUniform->type == GL_FLOAT_VEC4) { int arraySize = targetUniform->arraySize; if (arraySize == 1 && count > 1) return false; // attempting to write an array to a non-array uniform is an INVALID_OPERATION count = std::min(arraySize - (int)mUniformIndex[location].element, count); memcpy(targetUniform->data + mUniformIndex[location].element * sizeof(GLfloat) * 4, v, 4 * sizeof(GLfloat) * count); } else if (targetUniform->type == GL_BOOL_VEC4) { int arraySize = targetUniform->arraySize; if (arraySize == 1 && count > 1) return false; // attempting to write an array to a non-array uniform is an INVALID_OPERATION count = std::min(arraySize - (int)mUniformIndex[location].element, count); GLboolean *boolParams = (GLboolean*)targetUniform->data + mUniformIndex[location].element * 4; for (int i = 0; i < count * 4; ++i) { if (v[i] == 0.0f) { boolParams[i] = GL_FALSE; } else { boolParams[i] = GL_TRUE; } } } else { return false; } return true; } template<typename T, int targetWidth, int targetHeight, int srcWidth, int srcHeight> void transposeMatrix(T *target, const GLfloat *value) { int copyWidth = std::min(targetWidth, srcWidth); int copyHeight = std::min(targetHeight, srcHeight); for (int x = 0; x < copyWidth; x++) { for (int y = 0; y < copyHeight; y++) { target[x * targetWidth + y] = (T)value[y * srcWidth + x]; } } // clear unfilled right side for (int y = 0; y < copyHeight; y++) { for (int x = srcWidth; x < targetWidth; x++) { target[y * targetWidth + x] = (T)0; } } // clear unfilled bottom. for (int y = srcHeight; y < targetHeight; y++) { for (int x = 0; x < targetWidth; x++) { target[y * targetWidth + x] = (T)0; } } } bool ProgramBinary::setUniformMatrix2fv(GLint location, GLsizei count, const GLfloat *value) { if (location < 0 || location >= (int)mUniformIndex.size()) { return false; } Uniform *targetUniform = mUniforms[mUniformIndex[location].index]; targetUniform->dirty = true; if (targetUniform->type != GL_FLOAT_MAT2) { return false; } int arraySize = targetUniform->arraySize; if (arraySize == 1 && count > 1) return false; // attempting to write an array to a non-array uniform is an INVALID_OPERATION count = std::min(arraySize - (int)mUniformIndex[location].element, count); GLfloat *target = (GLfloat*)targetUniform->data + mUniformIndex[location].element * 8; for (int i = 0; i < count; i++) { transposeMatrix<GLfloat,4,2,2,2>(target, value); target += 8; value += 4; } return true; } bool ProgramBinary::setUniformMatrix3fv(GLint location, GLsizei count, const GLfloat *value) { if (location < 0 || location >= (int)mUniformIndex.size()) { return false; } Uniform *targetUniform = mUniforms[mUniformIndex[location].index]; targetUniform->dirty = true; if (targetUniform->type != GL_FLOAT_MAT3) { return false; } int arraySize = targetUniform->arraySize; if (arraySize == 1 && count > 1) return false; // attempting to write an array to a non-array uniform is an INVALID_OPERATION count = std::min(arraySize - (int)mUniformIndex[location].element, count); GLfloat *target = (GLfloat*)targetUniform->data + mUniformIndex[location].element * 12; for (int i = 0; i < count; i++) { transposeMatrix<GLfloat,4,3,3,3>(target, value); target += 12; value += 9; } return true; } bool ProgramBinary::setUniformMatrix4fv(GLint location, GLsizei count, const GLfloat *value) { if (location < 0 || location >= (int)mUniformIndex.size()) { return false; } Uniform *targetUniform = mUniforms[mUniformIndex[location].index]; targetUniform->dirty = true; if (targetUniform->type != GL_FLOAT_MAT4) { return false; } int arraySize = targetUniform->arraySize; if (arraySize == 1 && count > 1) return false; // attempting to write an array to a non-array uniform is an INVALID_OPERATION count = std::min(arraySize - (int)mUniformIndex[location].element, count); GLfloat *target = (GLfloat*)(targetUniform->data + mUniformIndex[location].element * sizeof(GLfloat) * 16); for (int i = 0; i < count; i++) { transposeMatrix<GLfloat,4,4,4,4>(target, value); target += 16; value += 16; } return true; } bool ProgramBinary::setUniform1iv(GLint location, GLsizei count, const GLint *v) { if (location < 0 || location >= (int)mUniformIndex.size()) { return false; } Uniform *targetUniform = mUniforms[mUniformIndex[location].index]; targetUniform->dirty = true; if (targetUniform->type == GL_INT || targetUniform->type == GL_SAMPLER_2D || targetUniform->type == GL_SAMPLER_CUBE) { int arraySize = targetUniform->arraySize; if (arraySize == 1 && count > 1) return false; // attempting to write an array to a non-array uniform is an INVALID_OPERATION count = std::min(arraySize - (int)mUniformIndex[location].element, count); memcpy(targetUniform->data + mUniformIndex[location].element * sizeof(GLint), v, sizeof(GLint) * count); } else if (targetUniform->type == GL_BOOL) { int arraySize = targetUniform->arraySize; if (arraySize == 1 && count > 1) return false; // attempting to write an array to a non-array uniform is an INVALID_OPERATION count = std::min(arraySize - (int)mUniformIndex[location].element, count); GLboolean *boolParams = (GLboolean*)targetUniform->data + mUniformIndex[location].element; for (int i = 0; i < count; ++i) { if (v[i] == 0) { boolParams[i] = GL_FALSE; } else { boolParams[i] = GL_TRUE; } } } else { return false; } return true; } bool ProgramBinary::setUniform2iv(GLint location, GLsizei count, const GLint *v) { if (location < 0 || location >= (int)mUniformIndex.size()) { return false; } Uniform *targetUniform = mUniforms[mUniformIndex[location].index]; targetUniform->dirty = true; if (targetUniform->type == GL_INT_VEC2) { int arraySize = targetUniform->arraySize; if (arraySize == 1 && count > 1) return false; // attempting to write an array to a non-array uniform is an INVALID_OPERATION count = std::min(arraySize - (int)mUniformIndex[location].element, count); memcpy(targetUniform->data + mUniformIndex[location].element * sizeof(GLint) * 2, v, 2 * sizeof(GLint) * count); } else if (targetUniform->type == GL_BOOL_VEC2) { int arraySize = targetUniform->arraySize; if (arraySize == 1 && count > 1) return false; // attempting to write an array to a non-array uniform is an INVALID_OPERATION count = std::min(arraySize - (int)mUniformIndex[location].element, count); GLboolean *boolParams = (GLboolean*)targetUniform->data + mUniformIndex[location].element * 2; for (int i = 0; i < count * 2; ++i) { if (v[i] == 0) { boolParams[i] = GL_FALSE; } else { boolParams[i] = GL_TRUE; } } } else { return false; } return true; } bool ProgramBinary::setUniform3iv(GLint location, GLsizei count, const GLint *v) { if (location < 0 || location >= (int)mUniformIndex.size()) { return false; } Uniform *targetUniform = mUniforms[mUniformIndex[location].index]; targetUniform->dirty = true; if (targetUniform->type == GL_INT_VEC3) { int arraySize = targetUniform->arraySize; if (arraySize == 1 && count > 1) return false; // attempting to write an array to a non-array uniform is an INVALID_OPERATION count = std::min(arraySize - (int)mUniformIndex[location].element, count); memcpy(targetUniform->data + mUniformIndex[location].element * sizeof(GLint) * 3, v, 3 * sizeof(GLint) * count); } else if (targetUniform->type == GL_BOOL_VEC3) { int arraySize = targetUniform->arraySize; if (arraySize == 1 && count > 1) return false; // attempting to write an array to a non-array uniform is an INVALID_OPERATION count = std::min(arraySize - (int)mUniformIndex[location].element, count); GLboolean *boolParams = (GLboolean*)targetUniform->data + mUniformIndex[location].element * 3; for (int i = 0; i < count * 3; ++i) { if (v[i] == 0) { boolParams[i] = GL_FALSE; } else { boolParams[i] = GL_TRUE; } } } else { return false; } return true; } bool ProgramBinary::setUniform4iv(GLint location, GLsizei count, const GLint *v) { if (location < 0 || location >= (int)mUniformIndex.size()) { return false; } Uniform *targetUniform = mUniforms[mUniformIndex[location].index]; targetUniform->dirty = true; if (targetUniform->type == GL_INT_VEC4) { int arraySize = targetUniform->arraySize; if (arraySize == 1 && count > 1) return false; // attempting to write an array to a non-array uniform is an INVALID_OPERATION count = std::min(arraySize - (int)mUniformIndex[location].element, count); memcpy(targetUniform->data + mUniformIndex[location].element * sizeof(GLint) * 4, v, 4 * sizeof(GLint) * count); } else if (targetUniform->type == GL_BOOL_VEC4) { int arraySize = targetUniform->arraySize; if (arraySize == 1 && count > 1) return false; // attempting to write an array to a non-array uniform is an INVALID_OPERATION count = std::min(arraySize - (int)mUniformIndex[location].element, count); GLboolean *boolParams = (GLboolean*)targetUniform->data + mUniformIndex[location].element * 4; for (int i = 0; i < count * 4; ++i) { if (v[i] == 0) { boolParams[i] = GL_FALSE; } else { boolParams[i] = GL_TRUE; } } } else { return false; } return true; } bool ProgramBinary::getUniformfv(GLint location, GLsizei *bufSize, GLfloat *params) { if (location < 0 || location >= (int)mUniformIndex.size()) { return false; } Uniform *targetUniform = mUniforms[mUniformIndex[location].index]; // sized queries -- ensure the provided buffer is large enough if (bufSize) { int requiredBytes = UniformExternalSize(targetUniform->type); if (*bufSize < requiredBytes) { return false; } } switch (targetUniform->type) { case GL_FLOAT_MAT2: transposeMatrix<GLfloat,2,2,4,2>(params, (GLfloat*)targetUniform->data + mUniformIndex[location].element * 8); break; case GL_FLOAT_MAT3: transposeMatrix<GLfloat,3,3,4,3>(params, (GLfloat*)targetUniform->data + mUniformIndex[location].element * 12); break; case GL_FLOAT_MAT4: transposeMatrix<GLfloat,4,4,4,4>(params, (GLfloat*)targetUniform->data + mUniformIndex[location].element * 16); break; default: { unsigned int count = UniformExternalComponentCount(targetUniform->type); unsigned int internalCount = UniformInternalComponentCount(targetUniform->type); switch (UniformComponentType(targetUniform->type)) { case GL_BOOL: { GLboolean *boolParams = (GLboolean*)targetUniform->data + mUniformIndex[location].element * internalCount; for (unsigned int i = 0; i < count; ++i) { params[i] = (boolParams[i] == GL_FALSE) ? 0.0f : 1.0f; } } break; case GL_FLOAT: memcpy(params, targetUniform->data + mUniformIndex[location].element * internalCount * sizeof(GLfloat), count * sizeof(GLfloat)); break; case GL_INT: { GLint *intParams = (GLint*)targetUniform->data + mUniformIndex[location].element * internalCount; for (unsigned int i = 0; i < count; ++i) { params[i] = (float)intParams[i]; } } break; default: UNREACHABLE(); } } } return true; } bool ProgramBinary::getUniformiv(GLint location, GLsizei *bufSize, GLint *params) { if (location < 0 || location >= (int)mUniformIndex.size()) { return false; } Uniform *targetUniform = mUniforms[mUniformIndex[location].index]; // sized queries -- ensure the provided buffer is large enough if (bufSize) { int requiredBytes = UniformExternalSize(targetUniform->type); if (*bufSize < requiredBytes) { return false; } } switch (targetUniform->type) { case GL_FLOAT_MAT2: { transposeMatrix<GLint,2,2,4,2>(params, (GLfloat*)targetUniform->data + mUniformIndex[location].element * 8); } break; case GL_FLOAT_MAT3: { transposeMatrix<GLint,3,3,4,3>(params, (GLfloat*)targetUniform->data + mUniformIndex[location].element * 12); } break; case GL_FLOAT_MAT4: { transposeMatrix<GLint,4,4,4,4>(params, (GLfloat*)targetUniform->data + mUniformIndex[location].element * 16); } break; default: { unsigned int count = UniformExternalComponentCount(targetUniform->type); unsigned int internalCount = UniformInternalComponentCount(targetUniform->type); switch (UniformComponentType(targetUniform->type)) { case GL_BOOL: { GLboolean *boolParams = targetUniform->data + mUniformIndex[location].element * internalCount; for (unsigned int i = 0; i < count; ++i) { params[i] = (GLint)boolParams[i]; } } break; case GL_FLOAT: { GLfloat *floatParams = (GLfloat*)targetUniform->data + mUniformIndex[location].element * internalCount; for (unsigned int i = 0; i < count; ++i) { params[i] = (GLint)floatParams[i]; } } break; case GL_INT: memcpy(params, targetUniform->data + mUniformIndex[location].element * internalCount * sizeof(GLint), count * sizeof(GLint)); break; default: UNREACHABLE(); } } } return true; } void ProgramBinary::dirtyAllUniforms() { unsigned int numUniforms = mUniforms.size(); for (unsigned int index = 0; index < numUniforms; index++) { mUniforms[index]->dirty = true; } } // Applies all the uniforms set for this program object to the Direct3D 9 device void ProgramBinary::applyUniforms() { for (std::vector<Uniform*>::iterator ub = mUniforms.begin(), ue = mUniforms.end(); ub != ue; ++ub) { Uniform *targetUniform = *ub; if (targetUniform->dirty) { int arraySize = targetUniform->arraySize; GLfloat *f = (GLfloat*)targetUniform->data; GLint *i = (GLint*)targetUniform->data; GLboolean *b = (GLboolean*)targetUniform->data; switch (targetUniform->type) { case GL_BOOL: applyUniformnbv(targetUniform, arraySize, 1, b); break; case GL_BOOL_VEC2: applyUniformnbv(targetUniform, arraySize, 2, b); break; case GL_BOOL_VEC3: applyUniformnbv(targetUniform, arraySize, 3, b); break; case GL_BOOL_VEC4: applyUniformnbv(targetUniform, arraySize, 4, b); break; case GL_FLOAT: case GL_FLOAT_VEC2: case GL_FLOAT_VEC3: case GL_FLOAT_VEC4: case GL_FLOAT_MAT2: case GL_FLOAT_MAT3: case GL_FLOAT_MAT4: applyUniformnfv(targetUniform, f); break; case GL_SAMPLER_2D: case GL_SAMPLER_CUBE: case GL_INT: applyUniform1iv(targetUniform, arraySize, i); break; case GL_INT_VEC2: applyUniform2iv(targetUniform, arraySize, i); break; case GL_INT_VEC3: applyUniform3iv(targetUniform, arraySize, i); break; case GL_INT_VEC4: applyUniform4iv(targetUniform, arraySize, i); break; default: UNREACHABLE(); } targetUniform->dirty = false; } } } // Compiles the HLSL code of the attached shaders into executable binaries ID3D10Blob *ProgramBinary::compileToBinary(InfoLog &infoLog, const char *hlsl, const char *profile, ID3DXConstantTable **constantTable) { if (!hlsl) { return NULL; } DWORD result; UINT flags = 0; std::string sourceText; if (perfActive()) { flags |= D3DCOMPILE_DEBUG; #ifdef NDEBUG flags |= ANGLE_COMPILE_OPTIMIZATION_LEVEL; #else flags |= D3DCOMPILE_SKIP_OPTIMIZATION; #endif std::string sourcePath = getTempPath(); sourceText = std::string("#line 2 \"") + sourcePath + std::string("\"\n\n") + std::string(hlsl); writeFile(sourcePath.c_str(), sourceText.c_str(), sourceText.size()); } else { flags |= ANGLE_COMPILE_OPTIMIZATION_LEVEL; sourceText = hlsl; } ID3D10Blob *binary = NULL; ID3D10Blob *errorMessage = NULL; result = D3DCompile(hlsl, strlen(hlsl), g_fakepath, NULL, NULL, "main", profile, flags, 0, &binary, &errorMessage); if (errorMessage) { const char *message = (const char*)errorMessage->GetBufferPointer(); infoLog.appendSanitized(message); TRACE("\n%s", hlsl); TRACE("\n%s", message); errorMessage->Release(); errorMessage = NULL; } if (FAILED(result)) { if (result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY) { error(GL_OUT_OF_MEMORY); } return NULL; } result = D3DXGetShaderConstantTable(static_cast<const DWORD*>(binary->GetBufferPointer()), constantTable); if (FAILED(result)) { if (result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY) { error(GL_OUT_OF_MEMORY); } binary->Release(); return NULL; } return binary; } // Packs varyings into generic varying registers, using the algorithm from [OpenGL ES Shading Language 1.00 rev. 17] appendix A section 7 page 111 // Returns the number of used varying registers, or -1 if unsuccesful int ProgramBinary::packVaryings(InfoLog &infoLog, const Varying *packing[][4], FragmentShader *fragmentShader) { Context *context = getContext(); const int maxVaryingVectors = context->getMaximumVaryingVectors(); for (VaryingList::iterator varying = fragmentShader->mVaryings.begin(); varying != fragmentShader->mVaryings.end(); varying++) { int n = VariableRowCount(varying->type) * varying->size; int m = VariableColumnCount(varying->type); bool success = false; if (m == 2 || m == 3 || m == 4) { for (int r = 0; r <= maxVaryingVectors - n && !success; r++) { bool available = true; for (int y = 0; y < n && available; y++) { for (int x = 0; x < m && available; x++) { if (packing[r + y][x]) { available = false; } } } if (available) { varying->reg = r; varying->col = 0; for (int y = 0; y < n; y++) { for (int x = 0; x < m; x++) { packing[r + y][x] = &*varying; } } success = true; } } if (!success && m == 2) { for (int r = maxVaryingVectors - n; r >= 0 && !success; r--) { bool available = true; for (int y = 0; y < n && available; y++) { for (int x = 2; x < 4 && available; x++) { if (packing[r + y][x]) { available = false; } } } if (available) { varying->reg = r; varying->col = 2; for (int y = 0; y < n; y++) { for (int x = 2; x < 4; x++) { packing[r + y][x] = &*varying; } } success = true; } } } } else if (m == 1) { int space[4] = {0}; for (int y = 0; y < maxVaryingVectors; y++) { for (int x = 0; x < 4; x++) { space[x] += packing[y][x] ? 0 : 1; } } int column = 0; for (int x = 0; x < 4; x++) { if (space[x] >= n && space[x] < space[column]) { column = x; } } if (space[column] >= n) { for (int r = 0; r < maxVaryingVectors; r++) { if (!packing[r][column]) { varying->reg = r; for (int y = r; y < r + n; y++) { packing[y][column] = &*varying; } break; } } varying->col = column; success = true; } } else UNREACHABLE(); if (!success) { infoLog.append("Could not pack varying %s", varying->name.c_str()); return -1; } } // Return the number of used registers int registers = 0; for (int r = 0; r < maxVaryingVectors; r++) { if (packing[r][0] || packing[r][1] || packing[r][2] || packing[r][3]) { registers++; } } return registers; } bool ProgramBinary::linkVaryings(InfoLog &infoLog, std::string& pixelHLSL, std::string& vertexHLSL, FragmentShader *fragmentShader, VertexShader *vertexShader) { if (pixelHLSL.empty() || vertexHLSL.empty()) { return false; } // Reset the varying register assignments for (VaryingList::iterator fragVar = fragmentShader->mVaryings.begin(); fragVar != fragmentShader->mVaryings.end(); fragVar++) { fragVar->reg = -1; fragVar->col = -1; } for (VaryingList::iterator vtxVar = vertexShader->mVaryings.begin(); vtxVar != vertexShader->mVaryings.end(); vtxVar++) { vtxVar->reg = -1; vtxVar->col = -1; } // Map the varyings to the register file const Varying *packing[MAX_VARYING_VECTORS_SM3][4] = {NULL}; int registers = packVaryings(infoLog, packing, fragmentShader); if (registers < 0) { return false; } // Write the HLSL input/output declarations Context *context = getContext(); const bool sm3 = context->supportsShaderModel3(); const int maxVaryingVectors = context->getMaximumVaryingVectors(); if (registers == maxVaryingVectors && fragmentShader->mUsesFragCoord) { infoLog.append("No varying registers left to support gl_FragCoord"); return false; } for (VaryingList::iterator input = fragmentShader->mVaryings.begin(); input != fragmentShader->mVaryings.end(); input++) { bool matched = false; for (VaryingList::iterator output = vertexShader->mVaryings.begin(); output != vertexShader->mVaryings.end(); output++) { if (output->name == input->name) { if (output->type != input->type || output->size != input->size) { infoLog.append("Type of vertex varying %s does not match that of the fragment varying", output->name.c_str()); return false; } output->reg = input->reg; output->col = input->col; matched = true; break; } } if (!matched) { infoLog.append("Fragment varying %s does not match any vertex varying", input->name.c_str()); return false; } } std::string varyingSemantic = (vertexShader->mUsesPointSize && sm3 ? "COLOR" : "TEXCOORD"); vertexHLSL += "struct VS_INPUT\n" "{\n"; int semanticIndex = 0; for (AttributeArray::iterator attribute = vertexShader->mAttributes.begin(); attribute != vertexShader->mAttributes.end(); attribute++) { switch (attribute->type) { case GL_FLOAT: vertexHLSL += " float "; break; case GL_FLOAT_VEC2: vertexHLSL += " float2 "; break; case GL_FLOAT_VEC3: vertexHLSL += " float3 "; break; case GL_FLOAT_VEC4: vertexHLSL += " float4 "; break; case GL_FLOAT_MAT2: vertexHLSL += " float2x2 "; break; case GL_FLOAT_MAT3: vertexHLSL += " float3x3 "; break; case GL_FLOAT_MAT4: vertexHLSL += " float4x4 "; break; default: UNREACHABLE(); } vertexHLSL += decorateAttribute(attribute->name) + " : TEXCOORD" + str(semanticIndex) + ";\n"; semanticIndex += VariableRowCount(attribute->type); } vertexHLSL += "};\n" "\n" "struct VS_OUTPUT\n" "{\n" " float4 gl_Position : POSITION;\n"; for (int r = 0; r < registers; r++) { int registerSize = packing[r][3] ? 4 : (packing[r][2] ? 3 : (packing[r][1] ? 2 : 1)); vertexHLSL += " float" + str(registerSize) + " v" + str(r) + " : " + varyingSemantic + str(r) + ";\n"; } if (fragmentShader->mUsesFragCoord) { vertexHLSL += " float4 gl_FragCoord : " + varyingSemantic + str(registers) + ";\n"; } if (vertexShader->mUsesPointSize && sm3) { vertexHLSL += " float gl_PointSize : PSIZE;\n"; } vertexHLSL += "};\n" "\n" "VS_OUTPUT main(VS_INPUT input)\n" "{\n"; for (AttributeArray::iterator attribute = vertexShader->mAttributes.begin(); attribute != vertexShader->mAttributes.end(); attribute++) { vertexHLSL += " " + decorateAttribute(attribute->name) + " = "; if (VariableRowCount(attribute->type) > 1) // Matrix { vertexHLSL += "transpose"; } vertexHLSL += "(input." + decorateAttribute(attribute->name) + ");\n"; } vertexHLSL += "\n" " gl_main();\n" "\n" " VS_OUTPUT output;\n" " output.gl_Position.x = gl_Position.x - dx_HalfPixelSize.x * gl_Position.w;\n" " output.gl_Position.y = -(gl_Position.y + dx_HalfPixelSize.y * gl_Position.w);\n" " output.gl_Position.z = (gl_Position.z + gl_Position.w) * 0.5;\n" " output.gl_Position.w = gl_Position.w;\n"; if (vertexShader->mUsesPointSize && sm3) { vertexHLSL += " output.gl_PointSize = gl_PointSize;\n"; } if (fragmentShader->mUsesFragCoord) { vertexHLSL += " output.gl_FragCoord = gl_Position;\n"; } for (VaryingList::iterator varying = vertexShader->mVaryings.begin(); varying != vertexShader->mVaryings.end(); varying++) { if (varying->reg >= 0) { for (int i = 0; i < varying->size; i++) { int rows = VariableRowCount(varying->type); for (int j = 0; j < rows; j++) { int r = varying->reg + i * rows + j; vertexHLSL += " output.v" + str(r); bool sharedRegister = false; // Register used by multiple varyings for (int x = 0; x < 4; x++) { if (packing[r][x] && packing[r][x] != packing[r][0]) { sharedRegister = true; break; } } if(sharedRegister) { vertexHLSL += "."; for (int x = 0; x < 4; x++) { if (packing[r][x] == &*varying) { switch(x) { case 0: vertexHLSL += "x"; break; case 1: vertexHLSL += "y"; break; case 2: vertexHLSL += "z"; break; case 3: vertexHLSL += "w"; break; } } } } vertexHLSL += " = " + varying->name; if (varying->array) { vertexHLSL += "[" + str(i) + "]"; } if (rows > 1) { vertexHLSL += "[" + str(j) + "]"; } vertexHLSL += ";\n"; } } } } vertexHLSL += "\n" " return output;\n" "}\n"; pixelHLSL += "struct PS_INPUT\n" "{\n"; for (VaryingList::iterator varying = fragmentShader->mVaryings.begin(); varying != fragmentShader->mVaryings.end(); varying++) { if (varying->reg >= 0) { for (int i = 0; i < varying->size; i++) { int rows = VariableRowCount(varying->type); for (int j = 0; j < rows; j++) { std::string n = str(varying->reg + i * rows + j); pixelHLSL += " float4 v" + n + " : " + varyingSemantic + n + ";\n"; } } } else UNREACHABLE(); } if (fragmentShader->mUsesFragCoord) { pixelHLSL += " float4 gl_FragCoord : " + varyingSemantic + str(registers) + ";\n"; if (sm3) { pixelHLSL += " float2 dx_VPos : VPOS;\n"; } } if (fragmentShader->mUsesPointCoord && sm3) { pixelHLSL += " float2 gl_PointCoord : TEXCOORD0;\n"; } if (fragmentShader->mUsesFrontFacing) { pixelHLSL += " float vFace : VFACE;\n"; } pixelHLSL += "};\n" "\n" "struct PS_OUTPUT\n" "{\n" " float4 gl_Color[1] : COLOR;\n" "};\n" "\n" "PS_OUTPUT main(PS_INPUT input)\n" "{\n"; if (fragmentShader->mUsesFragCoord) { pixelHLSL += " float rhw = 1.0 / input.gl_FragCoord.w;\n"; if (sm3) { pixelHLSL += " gl_FragCoord.x = input.dx_VPos.x + 0.5;\n" " gl_FragCoord.y = input.dx_VPos.y + 0.5;\n"; } else { // dx_Coord contains the viewport width/2, height/2, center.x and center.y. See Context::applyRenderTarget() pixelHLSL += " gl_FragCoord.x = (input.gl_FragCoord.x * rhw) * dx_Coord.x + dx_Coord.z;\n" " gl_FragCoord.y = (input.gl_FragCoord.y * rhw) * dx_Coord.y + dx_Coord.w;\n"; } pixelHLSL += " gl_FragCoord.z = (input.gl_FragCoord.z * rhw) * dx_Depth.x + dx_Depth.y;\n" " gl_FragCoord.w = rhw;\n"; } if (fragmentShader->mUsesPointCoord && sm3) { pixelHLSL += " gl_PointCoord.x = input.gl_PointCoord.x;\n"; pixelHLSL += " gl_PointCoord.y = 1.0 - input.gl_PointCoord.y;\n"; } if (fragmentShader->mUsesFrontFacing) { pixelHLSL += " gl_FrontFacing = dx_PointsOrLines || (dx_FrontCCW ? (input.vFace >= 0.0) : (input.vFace <= 0.0));\n"; } for (VaryingList::iterator varying = fragmentShader->mVaryings.begin(); varying != fragmentShader->mVaryings.end(); varying++) { if (varying->reg >= 0) { for (int i = 0; i < varying->size; i++) { int rows = VariableRowCount(varying->type); for (int j = 0; j < rows; j++) { std::string n = str(varying->reg + i * rows + j); pixelHLSL += " " + varying->name; if (varying->array) { pixelHLSL += "[" + str(i) + "]"; } if (rows > 1) { pixelHLSL += "[" + str(j) + "]"; } pixelHLSL += " = input.v" + n + ";\n"; } } } else UNREACHABLE(); } pixelHLSL += "\n" " gl_main();\n" "\n" " PS_OUTPUT output;\n" " output.gl_Color[0] = gl_Color[0];\n" "\n" " return output;\n" "}\n"; return true; } bool ProgramBinary::load(InfoLog &infoLog, const void *binary, GLsizei length) { BinaryInputStream stream(binary, length); int format = 0; stream.read(&format); if (format != GL_PROGRAM_BINARY_ANGLE) { infoLog.append("Invalid program binary format."); return false; } int version = 0; stream.read(&version); if (version != BUILD_REVISION) { infoLog.append("Invalid program binary version."); return false; } for (int i = 0; i < MAX_VERTEX_ATTRIBS; ++i) { stream.read(&mLinkedAttribute[i].type); std::string name; stream.read(&name); mLinkedAttribute[i].name = name; stream.read(&mSemanticIndex[i]); } for (unsigned int i = 0; i < MAX_TEXTURE_IMAGE_UNITS; ++i) { stream.read(&mSamplersPS[i].active); stream.read(&mSamplersPS[i].logicalTextureUnit); int textureType; stream.read(&textureType); mSamplersPS[i].textureType = (TextureType) textureType; } for (unsigned int i = 0; i < MAX_VERTEX_TEXTURE_IMAGE_UNITS_VTF; ++i) { stream.read(&mSamplersVS[i].active); stream.read(&mSamplersVS[i].logicalTextureUnit); int textureType; stream.read(&textureType); mSamplersVS[i].textureType = (TextureType) textureType; } stream.read(&mUsedVertexSamplerRange); stream.read(&mUsedPixelSamplerRange); unsigned int size; stream.read(&size); if (stream.error()) { infoLog.append("Invalid program binary."); return false; } mUniforms.resize(size); for (unsigned int i = 0; i < size; ++i) { GLenum type; std::string _name; unsigned int arraySize; stream.read(&type); stream.read(&_name); stream.read(&arraySize); mUniforms[i] = new Uniform(type, _name, arraySize); stream.read(&mUniforms[i]->ps.float4Index); stream.read(&mUniforms[i]->ps.samplerIndex); stream.read(&mUniforms[i]->ps.boolIndex); stream.read(&mUniforms[i]->ps.registerCount); stream.read(&mUniforms[i]->vs.float4Index); stream.read(&mUniforms[i]->vs.samplerIndex); stream.read(&mUniforms[i]->vs.boolIndex); stream.read(&mUniforms[i]->vs.registerCount); } stream.read(&size); if (stream.error()) { infoLog.append("Invalid program binary."); return false; } mUniformIndex.resize(size); for (unsigned int i = 0; i < size; ++i) { stream.read(&mUniformIndex[i].name); stream.read(&mUniformIndex[i].element); stream.read(&mUniformIndex[i].index); } stream.read(&mDxDepthRangeLocation); stream.read(&mDxDepthLocation); stream.read(&mDxCoordLocation); stream.read(&mDxHalfPixelSizeLocation); stream.read(&mDxFrontCCWLocation); stream.read(&mDxPointsOrLinesLocation); unsigned int pixelShaderSize; stream.read(&pixelShaderSize); unsigned int vertexShaderSize; stream.read(&vertexShaderSize); const char *ptr = (const char*) binary + stream.offset(); const D3DCAPS9 *binaryIdentifier = (const D3DCAPS9*) ptr; ptr += sizeof(GUID); D3DADAPTER_IDENTIFIER9 *currentIdentifier = getDisplay()->getAdapterIdentifier(); if (memcmp(&currentIdentifier->DeviceIdentifier, binaryIdentifier, sizeof(GUID)) != 0) { infoLog.append("Invalid program binary."); return false; } const char *pixelShaderFunction = ptr; ptr += pixelShaderSize; const char *vertexShaderFunction = ptr; ptr += vertexShaderSize; mPixelExecutable = getDisplay()->createPixelShader(reinterpret_cast<const DWORD*>(pixelShaderFunction), pixelShaderSize); if (!mPixelExecutable) { infoLog.append("Could not create pixel shader."); return false; } mVertexExecutable = getDisplay()->createVertexShader(reinterpret_cast<const DWORD*>(vertexShaderFunction), vertexShaderSize); if (!mVertexExecutable) { infoLog.append("Could not create vertex shader."); mPixelExecutable->Release(); mPixelExecutable = NULL; return false; } return true; } bool ProgramBinary::save(void* binary, GLsizei bufSize, GLsizei *length) { BinaryOutputStream stream; stream.write(GL_PROGRAM_BINARY_ANGLE); stream.write(BUILD_REVISION); for (unsigned int i = 0; i < MAX_VERTEX_ATTRIBS; ++i) { stream.write(mLinkedAttribute[i].type); stream.write(mLinkedAttribute[i].name); stream.write(mSemanticIndex[i]); } for (unsigned int i = 0; i < MAX_TEXTURE_IMAGE_UNITS; ++i) { stream.write(mSamplersPS[i].active); stream.write(mSamplersPS[i].logicalTextureUnit); stream.write((int) mSamplersPS[i].textureType); } for (unsigned int i = 0; i < MAX_VERTEX_TEXTURE_IMAGE_UNITS_VTF; ++i) { stream.write(mSamplersVS[i].active); stream.write(mSamplersVS[i].logicalTextureUnit); stream.write((int) mSamplersVS[i].textureType); } stream.write(mUsedVertexSamplerRange); stream.write(mUsedPixelSamplerRange); stream.write(mUniforms.size()); for (unsigned int i = 0; i < mUniforms.size(); ++i) { stream.write(mUniforms[i]->type); stream.write(mUniforms[i]->_name); stream.write(mUniforms[i]->arraySize); stream.write(mUniforms[i]->ps.float4Index); stream.write(mUniforms[i]->ps.samplerIndex); stream.write(mUniforms[i]->ps.boolIndex); stream.write(mUniforms[i]->ps.registerCount); stream.write(mUniforms[i]->vs.float4Index); stream.write(mUniforms[i]->vs.samplerIndex); stream.write(mUniforms[i]->vs.boolIndex); stream.write(mUniforms[i]->vs.registerCount); } stream.write(mUniformIndex.size()); for (unsigned int i = 0; i < mUniformIndex.size(); ++i) { stream.write(mUniformIndex[i].name); stream.write(mUniformIndex[i].element); stream.write(mUniformIndex[i].index); } stream.write(mDxDepthRangeLocation); stream.write(mDxDepthLocation); stream.write(mDxCoordLocation); stream.write(mDxHalfPixelSizeLocation); stream.write(mDxFrontCCWLocation); stream.write(mDxPointsOrLinesLocation); UINT pixelShaderSize; HRESULT result = mPixelExecutable->GetFunction(NULL, &pixelShaderSize); ASSERT(SUCCEEDED(result)); stream.write(pixelShaderSize); UINT vertexShaderSize; result = mVertexExecutable->GetFunction(NULL, &vertexShaderSize); ASSERT(SUCCEEDED(result)); stream.write(vertexShaderSize); D3DADAPTER_IDENTIFIER9 *identifier = getDisplay()->getAdapterIdentifier(); GLsizei streamLength = stream.length(); const void *streamData = stream.data(); GLsizei totalLength = streamLength + sizeof(GUID) + pixelShaderSize + vertexShaderSize; if (totalLength > bufSize) { if (length) { *length = 0; } return false; } if (binary) { char *ptr = (char*) binary; memcpy(ptr, streamData, streamLength); ptr += streamLength; memcpy(ptr, &identifier->DeviceIdentifier, sizeof(GUID)); ptr += sizeof(GUID); result = mPixelExecutable->GetFunction(ptr, &pixelShaderSize); ASSERT(SUCCEEDED(result)); ptr += pixelShaderSize; result = mVertexExecutable->GetFunction(ptr, &vertexShaderSize); ASSERT(SUCCEEDED(result)); ptr += vertexShaderSize; ASSERT(ptr - totalLength == binary); } if (length) { *length = totalLength; } return true; } GLint ProgramBinary::getLength() { GLint length; if (save(NULL, INT_MAX, &length)) { return length; } else { return 0; } } bool ProgramBinary::link(InfoLog &infoLog, const AttributeBindings &attributeBindings, FragmentShader *fragmentShader, VertexShader *vertexShader) { if (!fragmentShader || !fragmentShader->isCompiled()) { return false; } if (!vertexShader || !vertexShader->isCompiled()) { return false; } std::string pixelHLSL = fragmentShader->getHLSL(); std::string vertexHLSL = vertexShader->getHLSL(); if (!linkVaryings(infoLog, pixelHLSL, vertexHLSL, fragmentShader, vertexShader)) { return false; } Context *context = getContext(); const char *vertexProfile = context->supportsShaderModel3() ? "vs_3_0" : "vs_2_0"; const char *pixelProfile = context->supportsShaderModel3() ? "ps_3_0" : "ps_2_0"; ID3D10Blob *vertexBinary = compileToBinary(infoLog, vertexHLSL.c_str(), vertexProfile, &mConstantTableVS); ID3D10Blob *pixelBinary = compileToBinary(infoLog, pixelHLSL.c_str(), pixelProfile, &mConstantTablePS); if (vertexBinary && pixelBinary) { mVertexExecutable = getDisplay()->createVertexShader((DWORD*)vertexBinary->GetBufferPointer(), vertexBinary->GetBufferSize()); if (!mVertexExecutable) { return error(GL_OUT_OF_MEMORY, false); } mPixelExecutable = getDisplay()->createPixelShader((DWORD*)pixelBinary->GetBufferPointer(), pixelBinary->GetBufferSize()); if (!mPixelExecutable) { mVertexExecutable->Release(); mVertexExecutable = NULL; return error(GL_OUT_OF_MEMORY, false); } vertexBinary->Release(); pixelBinary->Release(); vertexBinary = NULL; pixelBinary = NULL; if (!linkAttributes(infoLog, attributeBindings, fragmentShader, vertexShader)) { return false; } if (!linkUniforms(infoLog, GL_FRAGMENT_SHADER, mConstantTablePS)) { return false; } if (!linkUniforms(infoLog, GL_VERTEX_SHADER, mConstantTableVS)) { return false; } // these uniforms are searched as already-decorated because gl_ and dx_ // are reserved prefixes, and do not receive additional decoration mDxDepthRangeLocation = getUniformLocation("dx_DepthRange"); mDxDepthLocation = getUniformLocation("dx_Depth"); mDxCoordLocation = getUniformLocation("dx_Coord"); mDxHalfPixelSizeLocation = getUniformLocation("dx_HalfPixelSize"); mDxFrontCCWLocation = getUniformLocation("dx_FrontCCW"); mDxPointsOrLinesLocation = getUniformLocation("dx_PointsOrLines"); context->markDxUniformsDirty(); return true; } return false; } // Determines the mapping between GL attributes and Direct3D 9 vertex stream usage indices bool ProgramBinary::linkAttributes(InfoLog &infoLog, const AttributeBindings &attributeBindings, FragmentShader *fragmentShader, VertexShader *vertexShader) { unsigned int usedLocations = 0; // Link attributes that have a binding location for (AttributeArray::iterator attribute = vertexShader->mAttributes.begin(); attribute != vertexShader->mAttributes.end(); attribute++) { int location = attributeBindings.getAttributeBinding(attribute->name); if (location != -1) // Set by glBindAttribLocation { if (!mLinkedAttribute[location].name.empty()) { // Multiple active attributes bound to the same location; not an error } mLinkedAttribute[location] = *attribute; int rows = VariableRowCount(attribute->type); if (rows + location > MAX_VERTEX_ATTRIBS) { infoLog.append("Active attribute (%s) at location %d is too big to fit", attribute->name.c_str(), location); return false; } for (int i = 0; i < rows; i++) { usedLocations |= 1 << (location + i); } } } // Link attributes that don't have a binding location for (AttributeArray::iterator attribute = vertexShader->mAttributes.begin(); attribute != vertexShader->mAttributes.end(); attribute++) { int location = attributeBindings.getAttributeBinding(attribute->name); if (location == -1) // Not set by glBindAttribLocation { int rows = VariableRowCount(attribute->type); int availableIndex = AllocateFirstFreeBits(&usedLocations, rows, MAX_VERTEX_ATTRIBS); if (availableIndex == -1 || availableIndex + rows > MAX_VERTEX_ATTRIBS) { infoLog.append("Too many active attributes (%s)", attribute->name.c_str()); return false; // Fail to link } mLinkedAttribute[availableIndex] = *attribute; } } for (int attributeIndex = 0; attributeIndex < MAX_VERTEX_ATTRIBS; ) { int index = vertexShader->getSemanticIndex(mLinkedAttribute[attributeIndex].name); int rows = std::max(VariableRowCount(mLinkedAttribute[attributeIndex].type), 1); for (int r = 0; r < rows; r++) { mSemanticIndex[attributeIndex++] = index++; } } return true; } bool ProgramBinary::linkUniforms(InfoLog &infoLog, GLenum shader, ID3DXConstantTable *constantTable) { D3DXCONSTANTTABLE_DESC constantTableDescription; constantTable->GetDesc(&constantTableDescription); for (unsigned int constantIndex = 0; constantIndex < constantTableDescription.Constants; constantIndex++) { D3DXHANDLE constantHandle = constantTable->GetConstant(0, constantIndex); D3DXCONSTANT_DESC constantDescription; UINT descriptionCount = 1; HRESULT result = constantTable->GetConstantDesc(constantHandle, &constantDescription, &descriptionCount); ASSERT(SUCCEEDED(result)); if (!defineUniform(infoLog, shader, constantHandle, constantDescription)) { return false; } } return true; } // Adds the description of a constant found in the binary shader to the list of uniforms // Returns true if succesful (uniform not already defined) bool ProgramBinary::defineUniform(InfoLog &infoLog, GLenum shader, const D3DXHANDLE &constantHandle, const D3DXCONSTANT_DESC &constantDescription, std::string name) { if (constantDescription.RegisterSet == D3DXRS_SAMPLER) { for (unsigned int i = 0; i < constantDescription.RegisterCount; i++) { D3DXHANDLE psConstant = mConstantTablePS->GetConstantByName(NULL, constantDescription.Name); D3DXHANDLE vsConstant = mConstantTableVS->GetConstantByName(NULL, constantDescription.Name); if (psConstant) { unsigned int samplerIndex = mConstantTablePS->GetSamplerIndex(psConstant) + i; if (samplerIndex < MAX_TEXTURE_IMAGE_UNITS) { mSamplersPS[samplerIndex].active = true; mSamplersPS[samplerIndex].textureType = (constantDescription.Type == D3DXPT_SAMPLERCUBE) ? TEXTURE_CUBE : TEXTURE_2D; mSamplersPS[samplerIndex].logicalTextureUnit = 0; mUsedPixelSamplerRange = std::max(samplerIndex + 1, mUsedPixelSamplerRange); } else { infoLog.append("Pixel shader sampler count exceeds MAX_TEXTURE_IMAGE_UNITS (%d).", MAX_TEXTURE_IMAGE_UNITS); return false; } } if (vsConstant) { unsigned int samplerIndex = mConstantTableVS->GetSamplerIndex(vsConstant) + i; if (samplerIndex < getContext()->getMaximumVertexTextureImageUnits()) { mSamplersVS[samplerIndex].active = true; mSamplersVS[samplerIndex].textureType = (constantDescription.Type == D3DXPT_SAMPLERCUBE) ? TEXTURE_CUBE : TEXTURE_2D; mSamplersVS[samplerIndex].logicalTextureUnit = 0; mUsedVertexSamplerRange = std::max(samplerIndex + 1, mUsedVertexSamplerRange); } else { infoLog.append("Vertex shader sampler count exceeds MAX_VERTEX_TEXTURE_IMAGE_UNITS (%d).", getContext()->getMaximumVertexTextureImageUnits()); return false; } } } } switch(constantDescription.Class) { case D3DXPC_STRUCT: { for (unsigned int arrayIndex = 0; arrayIndex < constantDescription.Elements; arrayIndex++) { D3DXHANDLE elementHandle = mConstantTablePS->GetConstantElement(constantHandle, arrayIndex); for (unsigned int field = 0; field < constantDescription.StructMembers; field++) { D3DXHANDLE fieldHandle = mConstantTablePS->GetConstant(elementHandle, field); D3DXCONSTANT_DESC fieldDescription; UINT descriptionCount = 1; HRESULT result = mConstantTablePS->GetConstantDesc(fieldHandle, &fieldDescription, &descriptionCount); ASSERT(SUCCEEDED(result)); std::string structIndex = (constantDescription.Elements > 1) ? ("[" + str(arrayIndex) + "]") : ""; if (!defineUniform(infoLog, shader, fieldHandle, fieldDescription, name + constantDescription.Name + structIndex + ".")) { return false; } } } return true; } case D3DXPC_SCALAR: case D3DXPC_VECTOR: case D3DXPC_MATRIX_COLUMNS: case D3DXPC_OBJECT: return defineUniform(shader, constantDescription, name + constantDescription.Name); default: UNREACHABLE(); return false; } } bool ProgramBinary::defineUniform(GLenum shader, const D3DXCONSTANT_DESC &constantDescription, const std::string &_name) { Uniform *uniform = createUniform(constantDescription, _name); if(!uniform) { return false; } // Check if already defined GLint location = getUniformLocation(uniform->name); GLenum type = uniform->type; if (location >= 0) { delete uniform; uniform = mUniforms[mUniformIndex[location].index]; } if (shader == GL_FRAGMENT_SHADER) uniform->ps.set(constantDescription); if (shader == GL_VERTEX_SHADER) uniform->vs.set(constantDescription); if (location >= 0) { return uniform->type == type; } mUniforms.push_back(uniform); unsigned int uniformIndex = mUniforms.size() - 1; for (unsigned int i = 0; i < uniform->arraySize; ++i) { mUniformIndex.push_back(UniformLocation(_name, i, uniformIndex)); } return true; } Uniform *ProgramBinary::createUniform(const D3DXCONSTANT_DESC &constantDescription, const std::string &_name) { if (constantDescription.Rows == 1) // Vectors and scalars { switch (constantDescription.Type) { case D3DXPT_SAMPLER2D: switch (constantDescription.Columns) { case 1: return new Uniform(GL_SAMPLER_2D, _name, constantDescription.Elements); default: UNREACHABLE(); } break; case D3DXPT_SAMPLERCUBE: switch (constantDescription.Columns) { case 1: return new Uniform(GL_SAMPLER_CUBE, _name, constantDescription.Elements); default: UNREACHABLE(); } break; case D3DXPT_BOOL: switch (constantDescription.Columns) { case 1: return new Uniform(GL_BOOL, _name, constantDescription.Elements); case 2: return new Uniform(GL_BOOL_VEC2, _name, constantDescription.Elements); case 3: return new Uniform(GL_BOOL_VEC3, _name, constantDescription.Elements); case 4: return new Uniform(GL_BOOL_VEC4, _name, constantDescription.Elements); default: UNREACHABLE(); } break; case D3DXPT_INT: switch (constantDescription.Columns) { case 1: return new Uniform(GL_INT, _name, constantDescription.Elements); case 2: return new Uniform(GL_INT_VEC2, _name, constantDescription.Elements); case 3: return new Uniform(GL_INT_VEC3, _name, constantDescription.Elements); case 4: return new Uniform(GL_INT_VEC4, _name, constantDescription.Elements); default: UNREACHABLE(); } break; case D3DXPT_FLOAT: switch (constantDescription.Columns) { case 1: return new Uniform(GL_FLOAT, _name, constantDescription.Elements); case 2: return new Uniform(GL_FLOAT_VEC2, _name, constantDescription.Elements); case 3: return new Uniform(GL_FLOAT_VEC3, _name, constantDescription.Elements); case 4: return new Uniform(GL_FLOAT_VEC4, _name, constantDescription.Elements); default: UNREACHABLE(); } break; default: UNREACHABLE(); } } else if (constantDescription.Rows == constantDescription.Columns) // Square matrices { switch (constantDescription.Type) { case D3DXPT_FLOAT: switch (constantDescription.Rows) { case 2: return new Uniform(GL_FLOAT_MAT2, _name, constantDescription.Elements); case 3: return new Uniform(GL_FLOAT_MAT3, _name, constantDescription.Elements); case 4: return new Uniform(GL_FLOAT_MAT4, _name, constantDescription.Elements); default: UNREACHABLE(); } break; default: UNREACHABLE(); } } else UNREACHABLE(); return 0; } // This method needs to match OutputHLSL::decorate std::string ProgramBinary::decorateAttribute(const std::string &name) { if (name.compare(0, 3, "gl_") != 0 && name.compare(0, 3, "dx_") != 0) { return "_" + name; } return name; } std::string ProgramBinary::undecorateUniform(const std::string &_name) { std::string name = _name; // Remove any structure field decoration size_t pos = 0; while ((pos = name.find("._", pos)) != std::string::npos) { name.replace(pos, 2, "."); } // Remove the leading decoration if (name[0] == '_') { return name.substr(1); } else if (name.compare(0, 3, "ar_") == 0) { return name.substr(3); } return name; } void ProgramBinary::applyUniformnbv(Uniform *targetUniform, GLsizei count, int width, const GLboolean *v) { float vector[D3D9_MAX_FLOAT_CONSTANTS * 4]; BOOL boolVector[D3D9_MAX_BOOL_CONSTANTS]; if (targetUniform->ps.float4Index >= 0 || targetUniform->vs.float4Index >= 0) { ASSERT(count <= D3D9_MAX_FLOAT_CONSTANTS); for (int i = 0; i < count; i++) { for (int j = 0; j < 4; j++) { if (j < width) { vector[i * 4 + j] = (v[i * width + j] == GL_FALSE) ? 0.0f : 1.0f; } else { vector[i * 4 + j] = 0.0f; } } } } if (targetUniform->ps.boolIndex >= 0 || targetUniform->vs.boolIndex >= 0) { int psCount = targetUniform->ps.boolIndex >= 0 ? targetUniform->ps.registerCount : 0; int vsCount = targetUniform->vs.boolIndex >= 0 ? targetUniform->vs.registerCount : 0; int copyCount = std::min(count * width, std::max(psCount, vsCount)); ASSERT(copyCount <= D3D9_MAX_BOOL_CONSTANTS); for (int i = 0; i < copyCount; i++) { boolVector[i] = v[i] != GL_FALSE; } } if (targetUniform->ps.float4Index >= 0) { mDevice->SetPixelShaderConstantF(targetUniform->ps.float4Index, vector, targetUniform->ps.registerCount); } if (targetUniform->ps.boolIndex >= 0) { mDevice->SetPixelShaderConstantB(targetUniform->ps.boolIndex, boolVector, targetUniform->ps.registerCount); } if (targetUniform->vs.float4Index >= 0) { mDevice->SetVertexShaderConstantF(targetUniform->vs.float4Index, vector, targetUniform->vs.registerCount); } if (targetUniform->vs.boolIndex >= 0) { mDevice->SetVertexShaderConstantB(targetUniform->vs.boolIndex, boolVector, targetUniform->vs.registerCount); } } bool ProgramBinary::applyUniformnfv(Uniform *targetUniform, const GLfloat *v) { if (targetUniform->ps.registerCount) { mDevice->SetPixelShaderConstantF(targetUniform->ps.float4Index, v, targetUniform->ps.registerCount); } if (targetUniform->vs.registerCount) { mDevice->SetVertexShaderConstantF(targetUniform->vs.float4Index, v, targetUniform->vs.registerCount); } return true; } bool ProgramBinary::applyUniform1iv(Uniform *targetUniform, GLsizei count, const GLint *v) { ASSERT(count <= D3D9_MAX_FLOAT_CONSTANTS); D3DXVECTOR4 vector[D3D9_MAX_FLOAT_CONSTANTS]; for (int i = 0; i < count; i++) { vector[i] = D3DXVECTOR4((float)v[i], 0, 0, 0); } if (targetUniform->ps.registerCount) { if (targetUniform->ps.samplerIndex >= 0) { unsigned int firstIndex = targetUniform->ps.samplerIndex; for (int i = 0; i < count; i++) { unsigned int samplerIndex = firstIndex + i; if (samplerIndex < MAX_TEXTURE_IMAGE_UNITS) { ASSERT(mSamplersPS[samplerIndex].active); mSamplersPS[samplerIndex].logicalTextureUnit = v[i]; } } } else { ASSERT(targetUniform->ps.float4Index >= 0); mDevice->SetPixelShaderConstantF(targetUniform->ps.float4Index, (const float*)vector, targetUniform->ps.registerCount); } } if (targetUniform->vs.registerCount) { if (targetUniform->vs.samplerIndex >= 0) { unsigned int firstIndex = targetUniform->vs.samplerIndex; for (int i = 0; i < count; i++) { unsigned int samplerIndex = firstIndex + i; if (samplerIndex < MAX_VERTEX_TEXTURE_IMAGE_UNITS_VTF) { ASSERT(mSamplersVS[samplerIndex].active); mSamplersVS[samplerIndex].logicalTextureUnit = v[i]; } } } else { ASSERT(targetUniform->vs.float4Index >= 0); mDevice->SetVertexShaderConstantF(targetUniform->vs.float4Index, (const float *)vector, targetUniform->vs.registerCount); } } return true; } bool ProgramBinary::applyUniform2iv(Uniform *targetUniform, GLsizei count, const GLint *v) { ASSERT(count <= D3D9_MAX_FLOAT_CONSTANTS); D3DXVECTOR4 vector[D3D9_MAX_FLOAT_CONSTANTS]; for (int i = 0; i < count; i++) { vector[i] = D3DXVECTOR4((float)v[0], (float)v[1], 0, 0); v += 2; } applyUniformniv(targetUniform, count, vector); return true; } bool ProgramBinary::applyUniform3iv(Uniform *targetUniform, GLsizei count, const GLint *v) { ASSERT(count <= D3D9_MAX_FLOAT_CONSTANTS); D3DXVECTOR4 vector[D3D9_MAX_FLOAT_CONSTANTS]; for (int i = 0; i < count; i++) { vector[i] = D3DXVECTOR4((float)v[0], (float)v[1], (float)v[2], 0); v += 3; } applyUniformniv(targetUniform, count, vector); return true; } bool ProgramBinary::applyUniform4iv(Uniform *targetUniform, GLsizei count, const GLint *v) { ASSERT(count <= D3D9_MAX_FLOAT_CONSTANTS); D3DXVECTOR4 vector[D3D9_MAX_FLOAT_CONSTANTS]; for (int i = 0; i < count; i++) { vector[i] = D3DXVECTOR4((float)v[0], (float)v[1], (float)v[2], (float)v[3]); v += 4; } applyUniformniv(targetUniform, count, vector); return true; } void ProgramBinary::applyUniformniv(Uniform *targetUniform, GLsizei count, const D3DXVECTOR4 *vector) { if (targetUniform->ps.registerCount) { ASSERT(targetUniform->ps.float4Index >= 0); mDevice->SetPixelShaderConstantF(targetUniform->ps.float4Index, (const float *)vector, targetUniform->ps.registerCount); } if (targetUniform->vs.registerCount) { ASSERT(targetUniform->vs.float4Index >= 0); mDevice->SetVertexShaderConstantF(targetUniform->vs.float4Index, (const float *)vector, targetUniform->vs.registerCount); } } bool ProgramBinary::isValidated() const { return mValidated; } void ProgramBinary::getActiveAttribute(GLuint index, GLsizei bufsize, GLsizei *length, GLint *size, GLenum *type, GLchar *name) { // Skip over inactive attributes unsigned int activeAttribute = 0; unsigned int attribute; for (attribute = 0; attribute < MAX_VERTEX_ATTRIBS; attribute++) { if (mLinkedAttribute[attribute].name.empty()) { continue; } if (activeAttribute == index) { break; } activeAttribute++; } if (bufsize > 0) { const char *string = mLinkedAttribute[attribute].name.c_str(); strncpy(name, string, bufsize); name[bufsize - 1] = '\0'; if (length) { *length = strlen(name); } } *size = 1; // Always a single 'type' instance *type = mLinkedAttribute[attribute].type; } GLint ProgramBinary::getActiveAttributeCount() { int count = 0; for (int attributeIndex = 0; attributeIndex < MAX_VERTEX_ATTRIBS; attributeIndex++) { if (!mLinkedAttribute[attributeIndex].name.empty()) { count++; } } return count; } GLint ProgramBinary::getActiveAttributeMaxLength() { int maxLength = 0; for (int attributeIndex = 0; attributeIndex < MAX_VERTEX_ATTRIBS; attributeIndex++) { if (!mLinkedAttribute[attributeIndex].name.empty()) { maxLength = std::max((int)(mLinkedAttribute[attributeIndex].name.length() + 1), maxLength); } } return maxLength; } void ProgramBinary::getActiveUniform(GLuint index, GLsizei bufsize, GLsizei *length, GLint *size, GLenum *type, GLchar *name) { // Skip over internal uniforms unsigned int activeUniform = 0; unsigned int uniform; for (uniform = 0; uniform < mUniforms.size(); uniform++) { if (mUniforms[uniform]->name.compare(0, 3, "dx_") == 0) { continue; } if (activeUniform == index) { break; } activeUniform++; } ASSERT(uniform < mUniforms.size()); // index must be smaller than getActiveUniformCount() if (bufsize > 0) { std::string string = mUniforms[uniform]->name; if (mUniforms[uniform]->isArray()) { string += "[0]"; } strncpy(name, string.c_str(), bufsize); name[bufsize - 1] = '\0'; if (length) { *length = strlen(name); } } *size = mUniforms[uniform]->arraySize; *type = mUniforms[uniform]->type; } GLint ProgramBinary::getActiveUniformCount() { int count = 0; unsigned int numUniforms = mUniforms.size(); for (unsigned int uniformIndex = 0; uniformIndex < numUniforms; uniformIndex++) { if (mUniforms[uniformIndex]->name.compare(0, 3, "dx_") != 0) { count++; } } return count; } GLint ProgramBinary::getActiveUniformMaxLength() { int maxLength = 0; unsigned int numUniforms = mUniforms.size(); for (unsigned int uniformIndex = 0; uniformIndex < numUniforms; uniformIndex++) { if (!mUniforms[uniformIndex]->name.empty() && mUniforms[uniformIndex]->name.compare(0, 3, "dx_") != 0) { int length = (int)(mUniforms[uniformIndex]->name.length() + 1); if (mUniforms[uniformIndex]->isArray()) { length += 3; // Counting in "[0]". } maxLength = std::max(length, maxLength); } } return maxLength; } void ProgramBinary::validate(InfoLog &infoLog) { applyUniforms(); if (!validateSamplers(&infoLog)) { mValidated = false; } else { mValidated = true; } } bool ProgramBinary::validateSamplers(InfoLog *infoLog) { // if any two active samplers in a program are of different types, but refer to the same // texture image unit, and this is the current program, then ValidateProgram will fail, and // DrawArrays and DrawElements will issue the INVALID_OPERATION error. const unsigned int maxCombinedTextureImageUnits = getContext()->getMaximumCombinedTextureImageUnits(); TextureType textureUnitType[MAX_COMBINED_TEXTURE_IMAGE_UNITS_VTF]; for (unsigned int i = 0; i < MAX_COMBINED_TEXTURE_IMAGE_UNITS_VTF; ++i) { textureUnitType[i] = TEXTURE_UNKNOWN; } for (unsigned int i = 0; i < mUsedPixelSamplerRange; ++i) { if (mSamplersPS[i].active) { unsigned int unit = mSamplersPS[i].logicalTextureUnit; if (unit >= maxCombinedTextureImageUnits) { if (infoLog) { infoLog->append("Sampler uniform (%d) exceeds MAX_COMBINED_TEXTURE_IMAGE_UNITS (%d)", unit, maxCombinedTextureImageUnits); } return false; } if (textureUnitType[unit] != TEXTURE_UNKNOWN) { if (mSamplersPS[i].textureType != textureUnitType[unit]) { if (infoLog) { infoLog->append("Samplers of conflicting types refer to the same texture image unit (%d).", unit); } return false; } } else { textureUnitType[unit] = mSamplersPS[i].textureType; } } } for (unsigned int i = 0; i < mUsedVertexSamplerRange; ++i) { if (mSamplersVS[i].active) { unsigned int unit = mSamplersVS[i].logicalTextureUnit; if (unit >= maxCombinedTextureImageUnits) { if (infoLog) { infoLog->append("Sampler uniform (%d) exceeds MAX_COMBINED_TEXTURE_IMAGE_UNITS (%d)", unit, maxCombinedTextureImageUnits); } return false; } if (textureUnitType[unit] != TEXTURE_UNKNOWN) { if (mSamplersVS[i].textureType != textureUnitType[unit]) { if (infoLog) { infoLog->append("Samplers of conflicting types refer to the same texture image unit (%d).", unit); } return false; } } else { textureUnitType[unit] = mSamplersVS[i].textureType; } } } return true; } GLint ProgramBinary::getDxDepthRangeLocation() const { return mDxDepthRangeLocation; } GLint ProgramBinary::getDxDepthLocation() const { return mDxDepthLocation; } GLint ProgramBinary::getDxCoordLocation() const { return mDxCoordLocation; } GLint ProgramBinary::getDxHalfPixelSizeLocation() const { return mDxHalfPixelSizeLocation; } GLint ProgramBinary::getDxFrontCCWLocation() const { return mDxFrontCCWLocation; } GLint ProgramBinary::getDxPointsOrLinesLocation() const { return mDxPointsOrLinesLocation; } ProgramBinary::Sampler::Sampler() : active(false), logicalTextureUnit(0), textureType(TEXTURE_2D) { } }
29.992095
164
0.563785
wilebeast
61a31dbf3413f91075e1ed69c843ac798dc4a05b
7,743
cpp
C++
dp/third-party/hyperscan/src/nfagraph/ng_literal_decorated.cpp
jtravee/neuvector
a88b9363108fc5c412be3007c3d4fb700d18decc
[ "Apache-2.0" ]
2,868
2017-10-26T02:25:23.000Z
2022-03-31T23:24:16.000Z
src/nfagraph/ng_literal_decorated.cpp
kuangxiaohong/phytium-hyperscan
ae1932734859906278dba623b77f99bba1010d5c
[ "BSD-2-Clause", "BSD-3-Clause" ]
270
2017-10-30T19:53:54.000Z
2022-03-30T22:03:17.000Z
src/nfagraph/ng_literal_decorated.cpp
kuangxiaohong/phytium-hyperscan
ae1932734859906278dba623b77f99bba1010d5c
[ "BSD-2-Clause", "BSD-3-Clause" ]
403
2017-11-02T01:18:22.000Z
2022-03-14T08:46:20.000Z
/* * Copyright (c) 2015-2017, Intel Corporation * * 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 Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE 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. */ /** \file * \brief Analysis for literals decorated by leading/trailing assertions or * character classes. */ #include "ng_literal_decorated.h" #include "nfagraph/ng_holder.h" #include "nfagraph/ng_util.h" #include "rose/rose_build.h" #include "rose/rose_in_graph.h" #include "rose/rose_in_util.h" #include "util/compile_context.h" #include "util/dump_charclass.h" #include "util/make_unique.h" #include <algorithm> #include <memory> #include <sstream> using namespace std; namespace ue2 { namespace { /** \brief Max fixed-width paths to generate from a graph. */ static constexpr size_t MAX_PATHS = 10; /** \brief Max degree for any non-special vertex in the graph. */ static constexpr size_t MAX_VERTEX_DEGREE = 6; using Path = vector<NFAVertex>; } // namespace static bool findPaths(const NGHolder &g, vector<Path> &paths) { vector<NFAVertex> order = getTopoOrdering(g); vector<size_t> read_count(num_vertices(g)); vector<vector<Path>> built(num_vertices(g)); for (auto it = order.rbegin(); it != order.rend(); ++it) { NFAVertex v = *it; auto &out = built[g[v].index]; assert(out.empty()); read_count[g[v].index] = out_degree(v, g); DEBUG_PRINTF("setting read_count to %zu for %zu\n", read_count[g[v].index], g[v].index); if (v == g.start || v == g.startDs) { out.push_back({v}); continue; } // The paths to v are the paths to v's predecessors, with v added to // the end of each. for (auto u : inv_adjacent_vertices_range(v, g)) { // We have a stylized connection from start -> startDs, but we // don't need anchored and unanchored versions of the same path. if (u == g.start && edge(g.startDs, v, g).second) { continue; } // Similarly, avoid the accept->acceptEod edge. if (u == g.accept) { assert(v == g.acceptEod); continue; } assert(!built[g[u].index].empty()); assert(read_count[g[u].index]); for (const auto &p : built[g[u].index]) { out.push_back(p); out.back().push_back(v); if (out.size() > MAX_PATHS) { // All these paths should eventually end up at a sink, so // we've blown past our limit. DEBUG_PRINTF("path limit exceeded\n"); return false; } } read_count[g[u].index]--; if (!read_count[g[u].index]) { DEBUG_PRINTF("clearing %zu as finished reading\n", g[u].index); built[g[u].index].clear(); built[g[u].index].shrink_to_fit(); } } } insert(&paths, paths.end(), built[NODE_ACCEPT]); insert(&paths, paths.end(), built[NODE_ACCEPT_EOD]); DEBUG_PRINTF("%zu paths generated\n", paths.size()); return paths.size() <= MAX_PATHS; } static bool hasLargeDegreeVertex(const NGHolder &g) { for (const auto &v : vertices_range(g)) { if (is_special(v, g)) { // specials can have large degree continue; } if (degree(v, g) > MAX_VERTEX_DEGREE) { DEBUG_PRINTF("vertex %zu has degree %zu\n", g[v].index, degree(v, g)); return true; } } return false; } #if defined(DEBUG) || defined(DUMP_SUPPORT) static UNUSED string dumpPath(const NGHolder &g, const Path &path) { ostringstream oss; for (const auto &v : path) { switch (g[v].index) { case NODE_START: oss << "<start>"; break; case NODE_START_DOTSTAR: oss << "<startDs>"; break; case NODE_ACCEPT: oss << "<accept>"; break; case NODE_ACCEPT_EOD: oss << "<acceptEod>"; break; default: oss << describeClass(g[v].char_reach); break; } } return oss.str(); } #endif struct PathMask { PathMask(const NGHolder &g, const Path &path) : is_anchored(path.front() == g.start), is_eod(path.back() == g.acceptEod) { assert(path.size() >= 2); mask.reserve(path.size() - 2); for (const auto &v : path) { if (is_special(v, g)) { continue; } mask.push_back(g[v].char_reach); } // Reports are attached to the second-to-last vertex. NFAVertex u = *std::next(path.rbegin()); reports = g[u].reports; assert(!reports.empty()); } vector<CharReach> mask; flat_set<ReportID> reports; bool is_anchored; bool is_eod; }; bool handleDecoratedLiterals(RoseBuild &rose, const NGHolder &g, const CompileContext &cc) { if (!cc.grey.allowDecoratedLiteral) { return false; } if (!isAcyclic(g)) { DEBUG_PRINTF("not acyclic\n"); return false; } if (!hasNarrowReachVertex(g)) { DEBUG_PRINTF("no narrow reach vertices\n"); return false; } if (hasLargeDegreeVertex(g)) { DEBUG_PRINTF("large degree\n"); return false; } vector<Path> paths; if (!findPaths(g, paths)) { DEBUG_PRINTF("couldn't split into a small number of paths\n"); return false; } assert(!paths.empty()); assert(paths.size() <= MAX_PATHS); vector<PathMask> masks; masks.reserve(paths.size()); for (const auto &path : paths) { DEBUG_PRINTF("path: %s\n", dumpPath(g, path).c_str()); PathMask pm(g, path); if (!rose.validateMask(pm.mask, pm.reports, pm.is_anchored, pm.is_eod)) { DEBUG_PRINTF("failed validation\n"); return false; } masks.push_back(move(pm)); } for (const auto &pm : masks) { rose.addMask(pm.mask, pm.reports, pm.is_anchored, pm.is_eod); } DEBUG_PRINTF("all ok, %zu masks added\n", masks.size()); return true; } } // namespace ue2
30.604743
79
0.593827
jtravee
61a3581908dc7c3e62da0690805946d31bbf60f5
8,530
cpp
C++
librtt/Rtt_LuaAssert.cpp
pouwelsjochem/corona
86ffe9002e42721b4bb2c386024111d995e7b27c
[ "MIT" ]
null
null
null
librtt/Rtt_LuaAssert.cpp
pouwelsjochem/corona
86ffe9002e42721b4bb2c386024111d995e7b27c
[ "MIT" ]
null
null
null
librtt/Rtt_LuaAssert.cpp
pouwelsjochem/corona
86ffe9002e42721b4bb2c386024111d995e7b27c
[ "MIT" ]
null
null
null
////////////////////////////////////////////////////////////////////////////// // // This file is part of the Corona game engine. // For overview and more information on licensing please refer to README.md // Home page: https://github.com/coronalabs/corona // Contact: support@coronalabs.com // ////////////////////////////////////////////////////////////////////////////// #include "Core/Rtt_Build.h" #include "Rtt_LuaAssert.h" // We limit this code to the Mac simulator because it depends // on libunwind which isn't available for __arm__ on iOS. #if defined( __APPLE__ ) && defined( __x86_64__ ) # # include <assert.h> # include <stdio.h> # include <string.h> # # include <dlfcn.h> // dlsym(). # include <libunwind.h> // unw_step(). # include <mach-o/dyld.h> // _NSGetExecutablePath(). # # ifdef __cplusplus extern "C" { # endif # # define lua_c # # include "lua.h" # include "lauxlib.h" # include "lualib.h" # # ifdef __cplusplus } # endif # # include "Core/Rtt_Build.h" # include "Rtt_LuaContext.h" # include "Rtt_Runtime.h" # define ENABLE_MY_PRINTF ( 0 ) # # if ENABLE_MY_PRINTF # # define MY_PRINTF( ... ) printf( __VA_ARGS__ ) # # else // NOT ENABLE_MY_PRINTF # # define MY_PRINTF( ... ) # # endif // ENABLE_MY_PRINTF namespace // anonymous namespace. { bool is_a_lua_C_function( unw_cursor_t &cursor ) { // 128 : We only need the first 5 characters, but we'll grab the // entire name for debugging purpose. This is the length of the // string necessary to find the prefix ("lua?_"). // "+ 1" : The trailing null character. // // We don't need the entire function name because we only need to // verify its prefix. // // For function names starting with "_Z", we can demangle the // name and verify that the first parameter, following the first // "(", is of type "lua_State *". See GCC's abi::__cxa_demangle() // in cxxabi.h. // // We can avoid demangling the function name by parsing it ourselves. // We can look for "P9lua_State" immediately after the function name. // // Then we can get the "lua_State *" by skipping over the implicit // "this" parameter. char name[ 128 + 1 ]; unw_word_t unused_ip_offset; if( unw_get_proc_name( &cursor, name, sizeof( name ), &unused_ip_offset ) ) { // Can't get the name. MY_PRINTF( "%s : Error: unw_get_proc_name() failed.\n", __FUNCTION__ ); return false; } // We want any functions that start with either "lua_", or "lua?_", // where "?" is any character. It's simpler to explicitly look at // each character than using regular expressions. if( ( name[ 0 ] == '_' ) && ( name[ 1 ] == 'Z' ) ) { // This is a mangled C++ function name. // Ignore these for now. MY_PRINTF( "%s : Skip over C++ functions: %s\n", __FUNCTION__, name ); return false; } if( ( name[ 0 ] == 'l' ) && ( name[ 1 ] == 'u' ) && ( name[ 2 ] == 'a' ) && ( name[ 3 ] == '_' ) ) { // We found a C function name prefixed with "lua_". MY_PRINTF( "%s : Found: %s\n", __FUNCTION__, name ); return true; } if( ( name[ 0 ] == 'l' ) && ( name[ 1 ] == 'u' ) && ( name[ 2 ] == 'a' ) && ( name[ 4 ] == '_' ) ) { // We found a C function name prefixed with "lua?_". MY_PRINTF( "%s : Found: %s\n", __FUNCTION__, name ); return true; } // Not a function we're interested in. MY_PRINTF( "%s : Skip over: %s\n", __FUNCTION__, name ); return false; } bool get_lua_State_from_the_first_C_function_parameter( unw_cursor_t &cursor, lua_State *&state ) { // RBP is a 64 bit register that points to the next stack frame. // ie: The function that called the current function. // ie: The parent caller of the current function. // // The values preceding the address in RBP are the current // function's parameters. // ie: To get the first pointer parameter to a function, take // the RBP address and subtract the size of one pointer. // // The values preceding the function's parameters, are the // function's local variables. These are the closest to the // value of the SP pointer. // // The function's parameters, in the stack frame, are presented in // reverse order of declaration. // ie: The first parameter has the largest address. // The last parameter has the smallest address. // // Some of this is discussed here: // http://llvm.org/docs/CodeGenerator.html#frame-layout unw_word_t rbp; if( unw_get_reg( &cursor, UNW_X86_64_RBP, &rbp ) ) { MY_PRINTF( "%s : Error: unw_get_reg() failed.\n", __FUNCTION__ ); state = NULL; return false; } // "sizeof( ptrdiff_t )" : The size of the first parameter of the // function, which should be a "lua_State *". // // If this was a C++ function, we would need to skip over the first // implicit "this" parameter. # ifdef Rtt_DEBUG # # define FIRST_ARGUMENT_OFFSET ( 1 ) # # else // NOT Rtt_DEBUG. # # // In non-debug builds (release builds), "compact unwind # // encoding" (introduced in OSX 10.6) causes the start # // of the local function arguments to be offset by 2 # // extra pointers. # define FIRST_ARGUMENT_OFFSET ( 3 ) # # endif // Rtt_DEBUG state = *(lua_State **)( rbp - ( FIRST_ARGUMENT_OFFSET * sizeof( ptrdiff_t ) ) ); MY_PRINTF( "%s : rbp: 0x%llx, L derived from rbp location: %p\n", __FUNCTION__, rbp, state ); if( (ptrdiff_t)state < (ptrdiff_t)0x10000 ) { // This is a sanity-check for bad pointers. // This should NEVER happen. MY_PRINTF( "%s : Error, L is bad: %p\n", __FUNCTION__, state ); state = NULL; return false; } return true; } lua_State *get_lua_State_from_current_callstack() { unw_context_t context; if( unw_getcontext( &context ) ) { MY_PRINTF( "%s : Error: unw_getcontext() failed.\n", __FUNCTION__ ); return NULL; } unw_cursor_t cursor; // "cursor" is now pointing to the current function. // We're NOT interested in the current function, so // we'll unw_step() to the next (parent) function // before we start to inspect the stack frames. if( unw_init_local( &cursor, &context ) ) { MY_PRINTF( "%s : Error: unw_init_local() failed.\n", __FUNCTION__ ); return NULL; } while( unw_step( &cursor ) > 0 ) { // Most Lua functions follow the same pattern: // // (1) They're C-based (NOT C++, so there's no "this" // pointer passed as the first argument). // // (2) Their name is prefixed with "lua_" or "lua?_". // // (3) Their first parameter is a "lua_State *". if( ! is_a_lua_C_function( cursor ) ) { // Not what we're looking for. continue; } lua_State *state; if( get_lua_State_from_the_first_C_function_parameter( cursor, state ) ) { // We found the what we want. return state; } // We DIDN'T find what we're looking for. } return NULL; } } // anonymous namespace. void Rtt_NotifyLuaInCallstack( const char *condition_string_prefix, const char *condition_string ) { lua_State *L = get_lua_State_from_current_callstack(); if( ! L ) { // Nothing to do. return; } // This typedef MUST stay in sync with any changes made to luaL_error(). typedef int (*luaL_error_t) (lua_State *L, const char *fmt, ...); // RTLD_MAIN_ONLY isn't POSIX. It's specific to __APPLE__. // It avoids having to dlopen() / dlclose() the current executable. luaL_error_t luaL_error_ptr = (luaL_error_t)dlsym( RTLD_MAIN_ONLY, "luaL_error" ); if( ! luaL_error_ptr ) { fprintf( stderr, "%s\n", dlerror() ); // Nothing to do. return; } // Report the error to Lua. { // Concatenate the condition string with its prefix. char *complete_condition_string = (char *)malloc( strlen( condition_string_prefix ) + strlen( condition_string ) + 1 ); // Trailing NULL character. strcpy( complete_condition_string, condition_string_prefix ); strcat( complete_condition_string, condition_string ); // Call luaL_error(). (*luaL_error_ptr)( L, complete_condition_string ); free( complete_condition_string ); } } #endif // defined( __APPLE__ ) && defined( __x86_64__ ).
26.823899
88
0.607503
pouwelsjochem
61a5ef5b7dd9f29cf78974ecd0eb92159a3ebf48
10,054
cpp
C++
android/android_9/frameworks/native/cmds/dumpstate/tests/dumpstate_smoke_test.cpp
yakuizhao/intel-vaapi-driver
b2bb0383352694941826543a171b557efac2219b
[ "MIT" ]
null
null
null
android/android_9/frameworks/native/cmds/dumpstate/tests/dumpstate_smoke_test.cpp
yakuizhao/intel-vaapi-driver
b2bb0383352694941826543a171b557efac2219b
[ "MIT" ]
null
null
null
android/android_9/frameworks/native/cmds/dumpstate/tests/dumpstate_smoke_test.cpp
yakuizhao/intel-vaapi-driver
b2bb0383352694941826543a171b557efac2219b
[ "MIT" ]
null
null
null
/* * Copyright (C) 2018 The Android Open Source Project * * 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 <gmock/gmock.h> #include <gtest/gtest.h> #include <fcntl.h> #include <libgen.h> #include <android-base/file.h> #include <cutils/properties.h> #include <ziparchive/zip_archive.h> #include "dumpstate.h" #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) namespace android { namespace os { namespace dumpstate { using ::testing::Test; using ::std::literals::chrono_literals::operator""s; struct SectionInfo { std::string name; status_t status; int32_t size_bytes; int32_t duration_ms; }; /** * Listens to bugreport progress and updates the user by writing the progress to STDOUT. All the * section details generated by dumpstate are added to a vector to be used by Tests later. */ class DumpstateListener : public IDumpstateListener { public: int outFd_, max_progress_; std::shared_ptr<std::vector<SectionInfo>> sections_; DumpstateListener(int fd, std::shared_ptr<std::vector<SectionInfo>> sections) : outFd_(fd), max_progress_(5000), sections_(sections) { } binder::Status onProgressUpdated(int32_t progress) override { dprintf(outFd_, "\rIn progress %d/%d", progress, max_progress_); return binder::Status::ok(); } binder::Status onMaxProgressUpdated(int32_t max_progress) override { max_progress_ = max_progress; return binder::Status::ok(); } binder::Status onSectionComplete(const ::std::string& name, int32_t status, int32_t size_bytes, int32_t duration_ms) override { sections_->push_back({name, status, size_bytes, duration_ms}); return binder::Status::ok(); } IBinder* onAsBinder() override { return nullptr; } }; /** * Generates bug report and provide access to the bug report file and other info for other tests. * Since bug report generation is slow, the bugreport is only generated once. */ class ZippedBugreportGenerationTest : public Test { public: static std::shared_ptr<std::vector<SectionInfo>> sections; static Dumpstate& ds; static std::chrono::milliseconds duration; static void SetUpTestCase() { property_set("dumpstate.options", "bugreportplus"); // clang-format off char* argv[] = { (char*)"dumpstate", (char*)"-d", (char*)"-z", (char*)"-B", (char*)"-o", (char*)dirname(android::base::GetExecutablePath().c_str()) }; // clang-format on sp<DumpstateListener> listener(new DumpstateListener(dup(fileno(stdout)), sections)); ds.listener_ = listener; ds.listener_name_ = "Smokey"; ds.report_section_ = true; auto start = std::chrono::steady_clock::now(); run_main(ARRAY_SIZE(argv), argv); auto end = std::chrono::steady_clock::now(); duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start); } static const char* getZipFilePath() { return ds.GetPath(".zip").c_str(); } }; std::shared_ptr<std::vector<SectionInfo>> ZippedBugreportGenerationTest::sections = std::make_shared<std::vector<SectionInfo>>(); Dumpstate& ZippedBugreportGenerationTest::ds = Dumpstate::GetInstance(); std::chrono::milliseconds ZippedBugreportGenerationTest::duration = 0s; TEST_F(ZippedBugreportGenerationTest, IsGeneratedWithoutErrors) { EXPECT_EQ(access(getZipFilePath(), F_OK), 0); } TEST_F(ZippedBugreportGenerationTest, Is3MBto30MBinSize) { struct stat st; EXPECT_EQ(stat(getZipFilePath(), &st), 0); EXPECT_GE(st.st_size, 3000000 /* 3MB */); EXPECT_LE(st.st_size, 30000000 /* 30MB */); } TEST_F(ZippedBugreportGenerationTest, TakesBetween30And150Seconds) { EXPECT_GE(duration, 30s) << "Expected completion in more than 30s. Actual time " << duration.count() << " s."; EXPECT_LE(duration, 150s) << "Expected completion in less than 150s. Actual time " << duration.count() << " s."; } /** * Run tests on contents of zipped bug report. */ class ZippedBugReportContentsTest : public Test { public: ZipArchiveHandle handle; void SetUp() { ASSERT_EQ(OpenArchive(ZippedBugreportGenerationTest::getZipFilePath(), &handle), 0); } void TearDown() { CloseArchive(handle); } void FileExists(const char* filename, uint32_t minsize, uint32_t maxsize) { ZipEntry entry; EXPECT_EQ(FindEntry(handle, ZipString(filename), &entry), 0); EXPECT_GT(entry.uncompressed_length, minsize); EXPECT_LT(entry.uncompressed_length, maxsize); } }; TEST_F(ZippedBugReportContentsTest, ContainsMainEntry) { ZipEntry mainEntryLoc; // contains main entry name file EXPECT_EQ(FindEntry(handle, ZipString("main_entry.txt"), &mainEntryLoc), 0); char* buf = new char[mainEntryLoc.uncompressed_length]; ExtractToMemory(handle, &mainEntryLoc, (uint8_t*)buf, mainEntryLoc.uncompressed_length); delete[] buf; // contains main entry file FileExists(buf, 1000000U, 50000000U); } TEST_F(ZippedBugReportContentsTest, ContainsVersion) { ZipEntry entry; // contains main entry name file EXPECT_EQ(FindEntry(handle, ZipString("version.txt"), &entry), 0); char* buf = new char[entry.uncompressed_length + 1]; ExtractToMemory(handle, &entry, (uint8_t*)buf, entry.uncompressed_length); buf[entry.uncompressed_length] = 0; EXPECT_STREQ(buf, ZippedBugreportGenerationTest::ds.version_.c_str()); delete[] buf; } TEST_F(ZippedBugReportContentsTest, ContainsBoardSpecificFiles) { FileExists("dumpstate_board.bin", 1000000U, 80000000U); FileExists("dumpstate_board.txt", 100000U, 1000000U); } // Spot check on some files pulled from the file system TEST_F(ZippedBugReportContentsTest, ContainsSomeFileSystemFiles) { // FS/proc/*/mountinfo size > 0 FileExists("FS/proc/1/mountinfo", 0U, 100000U); // FS/data/misc/profiles/cur/0/*/primary.prof size > 0 FileExists("FS/data/misc/profiles/cur/0/com.android.phone/primary.prof", 0U, 100000U); } /** * Runs tests on section data generated by dumpstate and captured by DumpstateListener. */ class BugreportSectionTest : public Test { public: int numMatches(const std::string& substring) { int matches = 0; for (auto const& section : *ZippedBugreportGenerationTest::sections) { if (section.name.find(substring) != std::string::npos) { matches++; } } return matches; } void SectionExists(const std::string& sectionName, int minsize) { for (auto const& section : *ZippedBugreportGenerationTest::sections) { if (sectionName == section.name) { EXPECT_GE(section.size_bytes, minsize); return; } } FAIL() << sectionName << " not found."; } }; // Test all sections are generated without timeouts or errors TEST_F(BugreportSectionTest, GeneratedWithoutErrors) { for (auto const& section : *ZippedBugreportGenerationTest::sections) { EXPECT_EQ(section.status, 0) << section.name << " failed with status " << section.status; } } TEST_F(BugreportSectionTest, Atleast3CriticalDumpsysSectionsGenerated) { int numSections = numMatches("DUMPSYS CRITICAL"); EXPECT_GE(numSections, 3); } TEST_F(BugreportSectionTest, Atleast2HighDumpsysSectionsGenerated) { int numSections = numMatches("DUMPSYS HIGH"); EXPECT_GE(numSections, 2); } TEST_F(BugreportSectionTest, Atleast50NormalDumpsysSectionsGenerated) { int allSections = numMatches("DUMPSYS"); int criticalSections = numMatches("DUMPSYS CRITICAL"); int highSections = numMatches("DUMPSYS HIGH"); int normalSections = allSections - criticalSections - highSections; EXPECT_GE(normalSections, 50) << "Total sections less than 50 (Critical:" << criticalSections << "High:" << highSections << "Normal:" << normalSections << ")"; } TEST_F(BugreportSectionTest, Atleast1ProtoDumpsysSectionGenerated) { int numSections = numMatches("proto/"); EXPECT_GE(numSections, 1); } // Test if some critical sections are being generated. TEST_F(BugreportSectionTest, CriticalSurfaceFlingerSectionGenerated) { SectionExists("DUMPSYS CRITICAL - SurfaceFlinger", /* bytes= */ 10000); } TEST_F(BugreportSectionTest, ActivitySectionsGenerated) { SectionExists("DUMPSYS CRITICAL - activity", /* bytes= */ 5000); SectionExists("DUMPSYS - activity", /* bytes= */ 10000); } TEST_F(BugreportSectionTest, CpuinfoSectionGenerated) { SectionExists("DUMPSYS CRITICAL - cpuinfo", /* bytes= */ 1000); } TEST_F(BugreportSectionTest, WindowSectionGenerated) { SectionExists("DUMPSYS CRITICAL - window", /* bytes= */ 20000); } TEST_F(BugreportSectionTest, ConnectivitySectionsGenerated) { SectionExists("DUMPSYS HIGH - connectivity", /* bytes= */ 5000); SectionExists("DUMPSYS - connectivity", /* bytes= */ 5000); } TEST_F(BugreportSectionTest, MeminfoSectionGenerated) { SectionExists("DUMPSYS HIGH - meminfo", /* bytes= */ 100000); } TEST_F(BugreportSectionTest, BatteryStatsSectionGenerated) { SectionExists("DUMPSYS - batterystats", /* bytes= */ 1000); } TEST_F(BugreportSectionTest, WifiSectionGenerated) { SectionExists("DUMPSYS - wifi", /* bytes= */ 100000); } } // namespace dumpstate } // namespace os } // namespace android
35.031359
99
0.68699
yakuizhao
61a655cfac46edd7e842df0c88a2425c73b40fa9
5,753
hxx
C++
main/toolkit/inc/toolkit/controls/formattedcontrol.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/toolkit/inc/toolkit/controls/formattedcontrol.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/toolkit/inc/toolkit/controls/formattedcontrol.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #ifndef TOOLKIT_FORMATTED_CONTROL_HXX #define TOOLKIT_FORMATTED_CONTROL_HXX #include <toolkit/controls/unocontrols.hxx> #include <toolkit/controls/unocontrolmodel.hxx> #include <toolkit/helper/servicenames.hxx> #include <com/sun/star/util/XNumberFormatter.hpp> //........................................................................ namespace toolkit { //........................................................................ // =================================================================== // = UnoControlFormattedFieldModel // =================================================================== class UnoControlFormattedFieldModel : public UnoControlModel { protected: ::com::sun::star::uno::Any ImplGetDefaultValue( sal_uInt16 nPropId ) const; ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper(); ::com::sun::star::uno::Any m_aCachedFormat; bool m_bRevokedAsClient; bool m_bSettingValueAndText; ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter > m_xCachedFormatter; protected: sal_Bool SAL_CALL convertFastPropertyValue( ::com::sun::star::uno::Any& rConvertedValue, ::com::sun::star::uno::Any& rOldValue, sal_Int32 nPropId, const ::com::sun::star::uno::Any& rValue ) throw (::com::sun::star::lang::IllegalArgumentException); void SAL_CALL setFastPropertyValue_NoBroadcast( sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue ) throw (::com::sun::star::uno::Exception); public: UnoControlFormattedFieldModel( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& i_factory ); UnoControlFormattedFieldModel( const UnoControlFormattedFieldModel& rModel ) :UnoControlModel( rModel ) { } UnoControlModel* Clone() const { return new UnoControlFormattedFieldModel( *this ); } // ::com::sun::star::io::XPersistObject ::rtl::OUString SAL_CALL getServiceName() throw(::com::sun::star::uno::RuntimeException); // ::com::sun::star::beans::XMultiPropertySet ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) throw(::com::sun::star::uno::RuntimeException); // ::com::sun::star::lang::XServiceInfo DECLIMPL_SERVICEINFO_DERIVED( UnoControlFormattedFieldModel, UnoControlModel, szServiceName2_UnoControlFormattedFieldModel ) protected: ~UnoControlFormattedFieldModel(); // XComponent void SAL_CALL dispose( ) throw(::com::sun::star::uno::RuntimeException); // XPropertySet void SAL_CALL setPropertyValues( const ::com::sun::star::uno::Sequence< ::rtl::OUString >& PropertyNames, const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& Values ) throw(::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); // UnoControlModel virtual void ImplNormalizePropertySequence( const sal_Int32 _nCount, /// the number of entries in the arrays sal_Int32* _pHandles, /// the handles of the properties to set ::com::sun::star::uno::Any* _pValues, /// the values of the properties to set sal_Int32* _pValidHandles /// pointer to the valid handles, allowed to be adjusted ) const SAL_THROW(()); private: void impl_updateTextFromValue_nothrow(); void impl_updateCachedFormatter_nothrow(); void impl_updateCachedFormatKey_nothrow(); }; // =================================================================== // = UnoFormattedFieldControl // =================================================================== class UnoFormattedFieldControl : public UnoSpinFieldControl { public: UnoFormattedFieldControl( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& i_factory ); ::rtl::OUString GetComponentServiceName(); // ::com::sun::star::awt::XTextListener void SAL_CALL textChanged( const ::com::sun::star::awt::TextEvent& rEvent ) throw(::com::sun::star::uno::RuntimeException); // ::com::sun::star::lang::XServiceInfo DECLIMPL_SERVICEINFO_DERIVED( UnoFormattedFieldControl, UnoEditControl, szServiceName2_UnoControlFormattedField ) }; //........................................................................ } // namespace toolkit //........................................................................ #endif // TOOLKIT_FORMATTED_CONTROL_HXX
45.299213
385
0.596732
Grosskopf
61a75c9675296f52a1a202903f455be932af1de4
573
cpp
C++
LeetCode/Weekly/5234. Find Resultant Array After Removing Anagrams.cpp
Sowmik23/All-Codes
212ef0d940fa84624bb2972a257768a830a709a3
[ "MIT" ]
1
2019-11-12T13:40:44.000Z
2019-11-12T13:40:44.000Z
LeetCode/Weekly/5234. Find Resultant Array After Removing Anagrams.cpp
Sowmik23/All-Codes
212ef0d940fa84624bb2972a257768a830a709a3
[ "MIT" ]
null
null
null
LeetCode/Weekly/5234. Find Resultant Array After Removing Anagrams.cpp
Sowmik23/All-Codes
212ef0d940fa84624bb2972a257768a830a709a3
[ "MIT" ]
null
null
null
class Solution { public: vector<string> removeAnagrams(vector<string>& words) { // for(int i=0;i<words.size();i++){ // sort(words[i].begin(), words[i].end()); // } int i = 1; while(i<words.size()){ string x = words[i]; sort(x.begin(), x.end()); string y = words[i-1]; sort(y.begin(), y.end()); if(x==y){ words.erase(words.begin()+i); } else i++; } return words; } };
22.92
58
0.385689
Sowmik23
61a8621d438416d59972d85f3ea28a4aa49a1256
2,282
cpp
C++
Silence.Core/Text2D.cpp
wt-student-projects/games-technology-project
70790e26f087fd401b0211a59b7c2beaef9546c9
[ "Apache-2.0" ]
null
null
null
Silence.Core/Text2D.cpp
wt-student-projects/games-technology-project
70790e26f087fd401b0211a59b7c2beaef9546c9
[ "Apache-2.0" ]
4
2016-07-15T21:23:08.000Z
2016-08-28T21:40:16.000Z
Silence.Core/Text2D.cpp
wt-student-projects/games-technology-project
70790e26f087fd401b0211a59b7c2beaef9546c9
[ "Apache-2.0" ]
null
null
null
#include "Text2D.h" Text2D::Text2D() : transfer(nullptr), texture(nullptr), height(0), width(0) { } Text2D::~Text2D() { SAFE_RELEASE(transfer); SAFE_RELEASE(texture); } void Text2D::setFont(FontAsset * asset, const char * text) { if (asset != nullptr) { asset->setText(text); const auto surface = asset->generateTexture(); texture = texture ? texture : new GPU_Sampler(SINGLE_SAMPLER); texture->setBitmapData(surface->pixels, surface->w, surface->h, surface->format->BytesPerPixel, surface->format->Rmask ); texture->send(); height = surface->h; width = surface->w; SDL_FreeSurface(surface); data = std::string(text); } } std::string Text2D::getText() { return data; } void Text2D::setArea(glm::vec2 size, Alignment align) { switch (align) { case Alignment::Center: { glm::vec2 newSize(size); newSize[0] -= width / 2; newSize[1] -= height / 2; setArea(newSize); break; } case Alignment::Left: { glm::vec2 newSize(size); newSize[0] -= width; newSize[1] -= height / 2; setArea(newSize); break; } case Alignment::Right: { setArea(size); break; } } } void Text2D::setArea(glm::vec2 size) { Vertices vert = { Vertex(size[0], size[1] + height, 0.1), Vertex(size[0] + width, size[1] + height, 0.1), Vertex(size[0] + width, size[1], 0.1), Vertex(size[0], size[1] + height, 0.1), Vertex(size[0], size[1], 0.1), Vertex(size[0] + width, size[1], 0.1), }; Vertices uvs = { Vertex(0.0, 0.0, 0.0), Vertex(1.0, 0.0, 0.0), Vertex(1.0, 1.0, 0.0), Vertex(0.0, 0.0, 0.0), Vertex(0.0, 1.0, 0.0), Vertex(1.0, 1.0, 0.0), }; transfer = transfer ? transfer : new GPU_Transfer(); transfer->setTextureCords(uvs); transfer->setVertices(vert); transfer->send(); } GpuID Text2D::getTextureID() { return texture->getID(); } GpuID Text2D::getDataID() { return transfer->getID(); }
21.327103
76
0.516214
wt-student-projects
61ab36d37158b290bbea78c514850c770d63357b
21,452
cc
C++
chrome/browser/notifications/platform_notification_service_impl.cc
Wzzzx/chromium-crosswalk
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2019-01-28T08:09:58.000Z
2021-11-15T15:32:10.000Z
chrome/browser/notifications/platform_notification_service_impl.cc
Wzzzx/chromium-crosswalk
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/notifications/platform_notification_service_impl.cc
Wzzzx/chromium-crosswalk
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
6
2020-09-23T08:56:12.000Z
2021-11-18T03:40:49.000Z
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/notifications/platform_notification_service_impl.h" #include <utility> #include <vector> #include "base/command_line.h" #include "base/metrics/histogram_macros.h" #include "base/metrics/user_metrics_action.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/browser/notifications/notification_display_service_factory.h" #include "chrome/browser/notifications/notification_object_proxy.h" #include "chrome/browser/notifications/notification_ui_manager.h" #include "chrome/browser/notifications/persistent_notification_delegate.h" #include "chrome/browser/permissions/permission_manager.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_attributes_storage.h" #include "chrome/browser/profiles/profile_io_data.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" #include "chrome/grit/generated_resources.h" #include "components/content_settings/core/browser/host_content_settings_map.h" #include "components/content_settings/core/common/content_settings.h" #include "components/content_settings/core/common/content_settings_types.h" #include "components/prefs/pref_service.h" #include "components/url_formatter/url_formatter.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_notification_delegate.h" #include "content/public/browser/notification_event_dispatcher.h" #include "content/public/browser/permission_type.h" #include "content/public/browser/platform_notification_context.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/user_metrics.h" #include "content/public/common/notification_resources.h" #include "content/public/common/platform_notification_data.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" #include "ui/message_center/notification_types.h" #include "ui/message_center/notifier_settings.h" #include "ui/resources/grit/ui_resources.h" #include "url/url_constants.h" #if defined(ENABLE_EXTENSIONS) #include "chrome/browser/notifications/notifier_state_tracker.h" #include "chrome/browser/notifications/notifier_state_tracker_factory.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/info_map.h" #include "extensions/common/constants.h" #include "extensions/common/permissions/api_permission.h" #include "extensions/common/permissions/permissions_data.h" #endif #if BUILDFLAG(ENABLE_BACKGROUND) #include "chrome/browser/lifetime/keep_alive_types.h" #include "chrome/browser/lifetime/scoped_keep_alive.h" #endif using content::BrowserContext; using content::BrowserThread; using content::PlatformNotificationContext; using message_center::NotifierId; class ProfileAttributesEntry; namespace { // Invalid id for a renderer process. Used in cases where we need to check for // permission without having an associated renderer process yet. const int kInvalidRenderProcessId = -1; void OnCloseNonPersistentNotificationProfileLoaded( const std::string& notification_id, Profile* profile) { NotificationDisplayServiceFactory::GetForProfile(profile)->Close( notification_id); } // Callback to run once the profile has been loaded in order to perform a // given |operation| in a notification. void ProfileLoadedCallback(NotificationCommon::Operation operation, const GURL& origin, int64_t persistent_notification_id, int action_index, Profile* profile) { if (!profile) { // TODO(miguelg): Add UMA for this condition. // Perhaps propagate this through PersistentNotificationStatus. LOG(WARNING) << "Profile not loaded correctly"; return; } switch (operation) { case NotificationCommon::CLICK: PlatformNotificationServiceImpl::GetInstance() ->OnPersistentNotificationClick(profile, persistent_notification_id, origin, action_index); break; case NotificationCommon::CLOSE: PlatformNotificationServiceImpl::GetInstance() ->OnPersistentNotificationClose(profile, persistent_notification_id, origin, true); break; case NotificationCommon::SETTINGS: NotificationCommon::OpenNotificationSettings(profile); break; } } // Callback used to close an non-persistent notification from blink. void CancelNotification(const std::string& notification_id, std::string profile_id, bool incognito) { ProfileManager* profile_manager = g_browser_process->profile_manager(); DCHECK(profile_manager); profile_manager->LoadProfile( profile_id, incognito, base::Bind(&OnCloseNonPersistentNotificationProfileLoaded, notification_id)); } } // namespace // static PlatformNotificationServiceImpl* PlatformNotificationServiceImpl::GetInstance() { return base::Singleton<PlatformNotificationServiceImpl>::get(); } PlatformNotificationServiceImpl::PlatformNotificationServiceImpl() : test_display_service_(nullptr) { #if BUILDFLAG(ENABLE_BACKGROUND) pending_click_dispatch_events_ = 0; #endif } PlatformNotificationServiceImpl::~PlatformNotificationServiceImpl() {} void PlatformNotificationServiceImpl::ProcessPersistentNotificationOperation( NotificationCommon::Operation operation, const std::string& profile_id, bool incognito, const GURL& origin, int64_t persistent_notification_id, int action_index) { ProfileManager* profile_manager = g_browser_process->profile_manager(); DCHECK(profile_manager); profile_manager->LoadProfile( profile_id, incognito, base::Bind(&ProfileLoadedCallback, operation, origin, persistent_notification_id, action_index)); } void PlatformNotificationServiceImpl::OnPersistentNotificationClick( BrowserContext* browser_context, int64_t persistent_notification_id, const GURL& origin, int action_index) { DCHECK_CURRENTLY_ON(BrowserThread::UI); blink::mojom::PermissionStatus permission_status = CheckPermissionOnUIThread(browser_context, origin, kInvalidRenderProcessId); // TODO(peter): Change this to a CHECK() when Issue 555572 is resolved. // Also change this method to be const again. if (permission_status != blink::mojom::PermissionStatus::GRANTED) { content::RecordAction(base::UserMetricsAction( "Notifications.Persistent.ClickedWithoutPermission")); return; } if (action_index == -1) { content::RecordAction(base::UserMetricsAction( "Notifications.Persistent.Clicked")); } else { content::RecordAction(base::UserMetricsAction( "Notifications.Persistent.ClickedActionButton")); } #if BUILDFLAG(ENABLE_BACKGROUND) // Ensure the browser stays alive while the event is processed. if (pending_click_dispatch_events_++ == 0) { click_dispatch_keep_alive_.reset( new ScopedKeepAlive(KeepAliveOrigin::PENDING_NOTIFICATION_CLICK_EVENT, KeepAliveRestartOption::DISABLED)); } #endif content::NotificationEventDispatcher::GetInstance() ->DispatchNotificationClickEvent( browser_context, persistent_notification_id, origin, action_index, base::Bind( &PlatformNotificationServiceImpl::OnClickEventDispatchComplete, base::Unretained(this))); } void PlatformNotificationServiceImpl::OnPersistentNotificationClose( BrowserContext* browser_context, int64_t persistent_notification_id, const GURL& origin, bool by_user) { DCHECK_CURRENTLY_ON(BrowserThread::UI); // If we programatically closed this notification, don't dispatch any event. if (closed_notifications_.erase(persistent_notification_id) != 0) return; if (by_user) { content::RecordAction(base::UserMetricsAction( "Notifications.Persistent.ClosedByUser")); } else { content::RecordAction(base::UserMetricsAction( "Notifications.Persistent.ClosedProgrammatically")); } content::NotificationEventDispatcher::GetInstance() ->DispatchNotificationCloseEvent( browser_context, persistent_notification_id, origin, by_user, base::Bind( &PlatformNotificationServiceImpl::OnCloseEventDispatchComplete, base::Unretained(this))); } blink::mojom::PermissionStatus PlatformNotificationServiceImpl::CheckPermissionOnUIThread( BrowserContext* browser_context, const GURL& origin, int render_process_id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); Profile* profile = Profile::FromBrowserContext(browser_context); DCHECK(profile); #if defined(ENABLE_EXTENSIONS) // Extensions support an API permission named "notification". This will grant // not only grant permission for using the Chrome App extension API, but also // for the Web Notification API. if (origin.SchemeIs(extensions::kExtensionScheme)) { extensions::ExtensionRegistry* registry = extensions::ExtensionRegistry::Get(browser_context); extensions::ProcessMap* process_map = extensions::ProcessMap::Get(browser_context); const extensions::Extension* extension = registry->GetExtensionById(origin.host(), extensions::ExtensionRegistry::ENABLED); if (extension && extension->permissions_data()->HasAPIPermission( extensions::APIPermission::kNotifications) && process_map->Contains(extension->id(), render_process_id)) { NotifierStateTracker* notifier_state_tracker = NotifierStateTrackerFactory::GetForProfile(profile); DCHECK(notifier_state_tracker); NotifierId notifier_id(NotifierId::APPLICATION, extension->id()); if (notifier_state_tracker->IsNotifierEnabled(notifier_id)) return blink::mojom::PermissionStatus::GRANTED; } } #endif return PermissionManager::Get(profile)->GetPermissionStatus( content::PermissionType::NOTIFICATIONS, origin, origin); } blink::mojom::PermissionStatus PlatformNotificationServiceImpl::CheckPermissionOnIOThread( content::ResourceContext* resource_context, const GURL& origin, int render_process_id) { DCHECK_CURRENTLY_ON(BrowserThread::IO); ProfileIOData* io_data = ProfileIOData::FromResourceContext(resource_context); #if defined(ENABLE_EXTENSIONS) // Extensions support an API permission named "notification". This will grant // not only grant permission for using the Chrome App extension API, but also // for the Web Notification API. if (origin.SchemeIs(extensions::kExtensionScheme)) { extensions::InfoMap* extension_info_map = io_data->GetExtensionInfoMap(); const extensions::ProcessMap& process_map = extension_info_map->process_map(); const extensions::Extension* extension = extension_info_map->extensions().GetByID(origin.host()); if (extension && extension->permissions_data()->HasAPIPermission( extensions::APIPermission::kNotifications) && process_map.Contains(extension->id(), render_process_id)) { if (!extension_info_map->AreNotificationsDisabled(extension->id())) return blink::mojom::PermissionStatus::GRANTED; } } #endif // No enabled extensions exist, so check the normal host content settings. HostContentSettingsMap* host_content_settings_map = io_data->GetHostContentSettingsMap(); ContentSetting setting = host_content_settings_map->GetContentSetting( origin, origin, CONTENT_SETTINGS_TYPE_NOTIFICATIONS, content_settings::ResourceIdentifier()); if (setting == CONTENT_SETTING_ALLOW) return blink::mojom::PermissionStatus::GRANTED; if (setting == CONTENT_SETTING_BLOCK) return blink::mojom::PermissionStatus::DENIED; return blink::mojom::PermissionStatus::ASK; } void PlatformNotificationServiceImpl::DisplayNotification( BrowserContext* browser_context, const GURL& origin, const content::PlatformNotificationData& notification_data, const content::NotificationResources& notification_resources, std::unique_ptr<content::DesktopNotificationDelegate> delegate, base::Closure* cancel_callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); Profile* profile = Profile::FromBrowserContext(browser_context); DCHECK(profile); DCHECK_EQ(0u, notification_data.actions.size()); DCHECK_EQ(0u, notification_resources.action_icons.size()); NotificationObjectProxy* proxy = new NotificationObjectProxy(browser_context, std::move(delegate)); Notification notification = CreateNotificationFromData( profile, origin, notification_data, notification_resources, proxy); GetNotificationDisplayService(profile)->Display(notification.delegate_id(), notification); if (cancel_callback) { #if defined(OS_WIN) std::string profile_id = base::WideToUTF8(profile->GetPath().BaseName().value()); #elif defined(OS_POSIX) std::string profile_id = profile->GetPath().BaseName().value(); #endif *cancel_callback = base::Bind(&CancelNotification, notification.delegate_id(), profile_id, profile->IsOffTheRecord()); } HostContentSettingsMapFactory::GetForProfile(profile)->UpdateLastUsage( origin, origin, CONTENT_SETTINGS_TYPE_NOTIFICATIONS); } void PlatformNotificationServiceImpl::DisplayPersistentNotification( BrowserContext* browser_context, int64_t persistent_notification_id, const GURL& origin, const content::PlatformNotificationData& notification_data, const content::NotificationResources& notification_resources) { DCHECK_CURRENTLY_ON(BrowserThread::UI); Profile* profile = Profile::FromBrowserContext(browser_context); DCHECK(profile); // The notification settings button will be appended after the developer- // supplied buttons, available in |notification_data.actions|. int settings_button_index = notification_data.actions.size(); PersistentNotificationDelegate* delegate = new PersistentNotificationDelegate( browser_context, persistent_notification_id, origin, settings_button_index); Notification notification = CreateNotificationFromData( profile, origin, notification_data, notification_resources, delegate); // TODO(peter): Remove this mapping when we have reliable id generation for // the message_center::Notification objects. persistent_notifications_[persistent_notification_id] = notification.id(); GetNotificationDisplayService(profile)->Display( base::Int64ToString(delegate->persistent_notification_id()), notification); content::RecordAction( base::UserMetricsAction("Notifications.Persistent.Shown")); HostContentSettingsMapFactory::GetForProfile(profile)->UpdateLastUsage( origin, origin, CONTENT_SETTINGS_TYPE_NOTIFICATIONS); } void PlatformNotificationServiceImpl::ClosePersistentNotification( BrowserContext* browser_context, int64_t persistent_notification_id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); Profile* profile = Profile::FromBrowserContext(browser_context); DCHECK(profile); closed_notifications_.insert(persistent_notification_id); #if defined(OS_ANDROID) bool cancel_by_persistent_id = true; #else bool cancel_by_persistent_id = GetNotificationDisplayService(profile)->SupportsNotificationCenter(); #endif if (cancel_by_persistent_id) { // TODO(peter): Remove this conversion when the notification ids are being // generated by the caller of this method. GetNotificationDisplayService(profile)->Close( base::Int64ToString(persistent_notification_id)); } else { auto iter = persistent_notifications_.find(persistent_notification_id); if (iter == persistent_notifications_.end()) return; GetNotificationDisplayService(profile)->Close(iter->second); } persistent_notifications_.erase(persistent_notification_id); } bool PlatformNotificationServiceImpl::GetDisplayedPersistentNotifications( BrowserContext* browser_context, std::set<std::string>* displayed_notifications) { DCHECK(displayed_notifications); Profile* profile = Profile::FromBrowserContext(browser_context); if (!profile || profile->AsTestingProfile()) return false; // Tests will not have a message center. // TODO(peter): Filter for persistent notifications only. return GetNotificationDisplayService(profile)->GetDisplayed( displayed_notifications); } void PlatformNotificationServiceImpl::OnClickEventDispatchComplete( content::PersistentNotificationStatus status) { UMA_HISTOGRAM_ENUMERATION( "Notifications.PersistentWebNotificationClickResult", status, content::PersistentNotificationStatus:: PERSISTENT_NOTIFICATION_STATUS_MAX); #if BUILDFLAG(ENABLE_BACKGROUND) DCHECK_GT(pending_click_dispatch_events_, 0); if (--pending_click_dispatch_events_ == 0) { click_dispatch_keep_alive_.reset(); } #endif } void PlatformNotificationServiceImpl::OnCloseEventDispatchComplete( content::PersistentNotificationStatus status) { UMA_HISTOGRAM_ENUMERATION( "Notifications.PersistentWebNotificationCloseResult", status, content::PersistentNotificationStatus:: PERSISTENT_NOTIFICATION_STATUS_MAX); } Notification PlatformNotificationServiceImpl::CreateNotificationFromData( Profile* profile, const GURL& origin, const content::PlatformNotificationData& notification_data, const content::NotificationResources& notification_resources, NotificationDelegate* delegate) const { DCHECK_EQ(notification_data.actions.size(), notification_resources.action_icons.size()); // TODO(peter): Handle different screen densities instead of always using the // 1x bitmap - crbug.com/585815. Notification notification( message_center::NOTIFICATION_TYPE_SIMPLE, notification_data.title, notification_data.body, gfx::Image::CreateFrom1xBitmap(notification_resources.notification_icon), message_center::NotifierId(origin), base::UTF8ToUTF16(origin.host()), origin, notification_data.tag, message_center::RichNotificationData(), delegate); notification.set_context_message( DisplayNameForContextMessage(profile, origin)); notification.set_vibration_pattern(notification_data.vibration_pattern); notification.set_timestamp(notification_data.timestamp); notification.set_renotify(notification_data.renotify); notification.set_silent(notification_data.silent); // Badges are only supported on Android, primarily because it's the only // platform that makes good use of them in the status bar. // TODO(mvanouwerkerk): ensure no badge is loaded when it will not be used. #if defined(OS_ANDROID) // TODO(peter): Handle different screen densities instead of always using the // 1x bitmap - crbug.com/585815. notification.set_small_image( gfx::Image::CreateFrom1xBitmap(notification_resources.badge)); #endif // defined(OS_ANDROID) // Developer supplied action buttons. std::vector<message_center::ButtonInfo> buttons; for (size_t i = 0; i < notification_data.actions.size(); i++) { message_center::ButtonInfo button(notification_data.actions[i].title); // TODO(peter): Handle different screen densities instead of always using // the 1x bitmap - crbug.com/585815. button.icon = gfx::Image::CreateFrom1xBitmap(notification_resources.action_icons[i]); buttons.push_back(button); } notification.set_buttons(buttons); // On desktop, notifications with require_interaction==true stay on-screen // rather than minimizing to the notification center after a timeout. // On mobile, this is ignored (notifications are minimized at all times). if (notification_data.require_interaction) notification.set_never_timeout(true); return notification; } NotificationDisplayService* PlatformNotificationServiceImpl::GetNotificationDisplayService( Profile* profile) { if (test_display_service_ != nullptr) return test_display_service_; return NotificationDisplayServiceFactory::GetForProfile(profile); } base::string16 PlatformNotificationServiceImpl::DisplayNameForContextMessage( Profile* profile, const GURL& origin) const { #if defined(ENABLE_EXTENSIONS) // If the source is an extension, lookup the display name. if (origin.SchemeIs(extensions::kExtensionScheme)) { const extensions::Extension* extension = extensions::ExtensionRegistry::Get(profile)->GetExtensionById( origin.host(), extensions::ExtensionRegistry::EVERYTHING); DCHECK(extension); return base::UTF8ToUTF16(extension->name()); } #endif return base::string16(); } void PlatformNotificationServiceImpl::SetNotificationDisplayServiceForTesting( NotificationDisplayService* display_service) { test_display_service_ = display_service; }
39.145985
80
0.760255
Wzzzx
61aba2584adebad82c3c521bb1a922940e583a23
9,585
cpp
C++
source/compilation/builtins/MathFuncs.cpp
masc-ucsc/slang
344f4b415d03ef4dc5b9cfcd3a9fcffdf44d5e8a
[ "MIT" ]
240
2017-02-03T22:29:12.000Z
2022-03-31T08:22:04.000Z
source/compilation/builtins/MathFuncs.cpp
masc-ucsc/slang
344f4b415d03ef4dc5b9cfcd3a9fcffdf44d5e8a
[ "MIT" ]
412
2017-02-04T04:57:18.000Z
2022-03-29T23:30:30.000Z
source/compilation/builtins/MathFuncs.cpp
masc-ucsc/slang
344f4b415d03ef4dc5b9cfcd3a9fcffdf44d5e8a
[ "MIT" ]
51
2017-02-19T23:57:30.000Z
2022-03-02T13:55:00.000Z
//------------------------------------------------------------------------------ // MathFuncs.cpp // Built-in math system functions // // File is under the MIT license; see LICENSE for details //------------------------------------------------------------------------------ #include "slang/binding/SystemSubroutine.h" #include "slang/compilation/Compilation.h" #include "slang/diagnostics/SysFuncsDiags.h" namespace slang::Builtins { class Clog2Function : public SystemSubroutine { public: Clog2Function() : SystemSubroutine("$clog2", SubroutineKind::Function) {} const Type& checkArguments(const BindContext& context, const Args& args, SourceRange range, const Expression*) const final { auto& comp = context.getCompilation(); if (!checkArgCount(context, false, args, range, 1, 1)) return comp.getErrorType(); if (!args[0]->type->isIntegral()) return badArg(context, *args[0]); return comp.getIntegerType(); } bool verifyConstant(EvalContext&, const Args&, SourceRange) const final { return true; } ConstantValue eval(EvalContext& context, const Args& args, const CallExpression::SystemCallInfo&) const final { ConstantValue v = args[0]->eval(context); if (!v) return nullptr; auto ci = v.integer(); ci.flattenUnknowns(); return SVInt(32, clog2(ci), true); } }; class CountBitsFunction : public SystemSubroutine { public: CountBitsFunction() : SystemSubroutine("$countbits", SubroutineKind::Function) {} const Type& checkArguments(const BindContext& context, const Args& args, SourceRange range, const Expression*) const final { auto& comp = context.getCompilation(); if (!checkArgCount(context, false, args, range, 2, INT32_MAX)) return comp.getErrorType(); if (!args[0]->type->isBitstreamType()) return badArg(context, *args[0]); for (auto arg : args.subspan(1)) { if (!arg->type->isIntegral()) return badArg(context, *arg); } return comp.getIntType(); } bool verifyConstant(EvalContext&, const Args&, SourceRange) const final { return true; } ConstantValue eval(EvalContext& context, const Args& args, const CallExpression::SystemCallInfo&) const final { ConstantValue value = args[0]->eval(context); if (!value) return nullptr; // TODO: should support any bitstream type... const SVInt& iv = value.integer(); // Figure out which bit values we're checking -- the caller can // pass any number of arguments; we always take the LSB and compare // that against all bits, counting each one that matches. // // This array tracks which bit values we've already counted: 0, 1, X, or Z bool seen[4]{}; uint64_t count = 0; for (auto arg : args.subspan(1)) { ConstantValue v = arg->eval(context); if (!v) return nullptr; logic_t bit = v.integer()[0]; if (bit.value == 0) { if (!seen[0]) { count += iv.countZeros(); seen[0] = true; } } else if (bit.value == 1) { if (!seen[1]) { count += iv.countOnes(); seen[1] = true; } } else if (bit.value == logic_t::X_VALUE) { if (!seen[2]) { count += iv.countXs(); seen[2] = true; } } else if (bit.value == logic_t::Z_VALUE) { if (!seen[3]) { count += iv.countZs(); seen[3] = true; } } } return SVInt(32, count, true); } }; class CountOnesFunction : public SystemSubroutine { public: CountOnesFunction() : SystemSubroutine("$countones", SubroutineKind::Function) {} const Type& checkArguments(const BindContext& context, const Args& args, SourceRange range, const Expression*) const final { auto& comp = context.getCompilation(); if (!checkArgCount(context, false, args, range, 1, 1)) return comp.getErrorType(); if (!args[0]->type->isBitstreamType()) return badArg(context, *args[0]); return comp.getIntType(); } bool verifyConstant(EvalContext&, const Args&, SourceRange) const final { return true; } ConstantValue eval(EvalContext& context, const Args& args, const CallExpression::SystemCallInfo&) const final { ConstantValue value = args[0]->eval(context); if (!value) return nullptr; // TODO: should support any bitstream type... const SVInt& iv = value.integer(); uint64_t count = iv.countOnes(); return SVInt(32, count, true); } }; class BooleanBitVectorFunction : public SystemSubroutine { public: enum BVFKind { OneHot, OneHot0, IsUnknown }; BooleanBitVectorFunction(const std::string& name, BVFKind kind) : SystemSubroutine(name, SubroutineKind::Function), kind(kind) {} const Type& checkArguments(const BindContext& context, const Args& args, SourceRange range, const Expression*) const final { auto& comp = context.getCompilation(); if (!checkArgCount(context, false, args, range, 1, 1)) return comp.getErrorType(); if (!args[0]->type->isBitstreamType()) return badArg(context, *args[0]); return comp.getBitType(); } bool verifyConstant(EvalContext&, const Args&, SourceRange) const final { return true; } ConstantValue eval(EvalContext& context, const Args& args, const CallExpression::SystemCallInfo&) const final { ConstantValue value = args[0]->eval(context); if (!value) return nullptr; // TODO: should support any bitstream type... const SVInt& iv = value.integer(); switch (kind) { case OneHot: return SVInt(1, uint64_t(iv.countOnes() == 1), false); case OneHot0: return SVInt(1, uint64_t(iv.countOnes() <= 1), false); case IsUnknown: return SVInt(1, uint64_t(iv.hasUnknown()), false); default: THROW_UNREACHABLE; } } private: BVFKind kind; }; template<double Func(double)> class RealMath1Function : public SimpleSystemSubroutine { public: RealMath1Function(Compilation& comp, const std::string& name) : SimpleSystemSubroutine(name, SubroutineKind::Function, 1, { &comp.getRealType() }, comp.getRealType(), false) {} ConstantValue eval(EvalContext& context, const Args& args, const CallExpression::SystemCallInfo&) const final { ConstantValue v = args[0]->eval(context); if (!v) return nullptr; double result = Func(v.real()); return real_t(result); } }; template<double Func(double, double)> class RealMath2Function : public SimpleSystemSubroutine { public: RealMath2Function(Compilation& comp, const std::string& name) : SimpleSystemSubroutine(name, SubroutineKind::Function, 2, { &comp.getRealType(), &comp.getRealType() }, comp.getRealType(), false) {} ConstantValue eval(EvalContext& context, const Args& args, const CallExpression::SystemCallInfo&) const final { ConstantValue a = args[0]->eval(context); ConstantValue b = args[1]->eval(context); if (!a || !b) return nullptr; double result = Func(a.real(), b.real()); return real_t(result); } }; void registerMathFuncs(Compilation& c) { c.addSystemSubroutine(std::make_unique<Clog2Function>()); c.addSystemSubroutine(std::make_unique<CountBitsFunction>()); c.addSystemSubroutine(std::make_unique<CountOnesFunction>()); #define REGISTER(name, kind) \ c.addSystemSubroutine( \ std::make_unique<BooleanBitVectorFunction>(name, BooleanBitVectorFunction::kind)) REGISTER("$onehot", OneHot); REGISTER("$onehot0", OneHot0); REGISTER("$isunknown", IsUnknown); #undef REGISTER #define REGISTER(name, func) \ c.addSystemSubroutine(std::make_unique<RealMath1Function<(func)>>(c, name)) REGISTER("$ln", std::log); REGISTER("$log10", std::log10); REGISTER("$exp", std::exp); REGISTER("$sqrt", std::sqrt); REGISTER("$floor", std::floor); REGISTER("$ceil", std::ceil); REGISTER("$sin", std::sin); REGISTER("$cos", std::cos); REGISTER("$tan", std::tan); REGISTER("$asin", std::asin); REGISTER("$acos", std::acos); REGISTER("$atan", std::atan); REGISTER("$sinh", std::sinh); REGISTER("$cosh", std::cosh); REGISTER("$tanh", std::tanh); REGISTER("$asinh", std::asinh); REGISTER("$acosh", std::acosh); REGISTER("$atanh", std::atanh); #undef REGISTER #define REGISTER(name, func) \ c.addSystemSubroutine(std::make_unique<RealMath2Function<(func)>>(c, name)) REGISTER("$pow", std::pow); REGISTER("$atan2", std::atan2); REGISTER("$hypot", std::hypot); #undef REGISTER } } // namespace slang::Builtins
33.869258
96
0.575378
masc-ucsc
61ae4327ae34850ccf63df9488da790eab8bcf46
5,263
cpp
C++
src/ramp.cpp
mloy/cppstream
74c96aeb464703fed765739b27dcfabed696dae5
[ "MIT" ]
4
2017-08-25T19:34:11.000Z
2022-02-16T14:35:43.000Z
src/ramp.cpp
mloy/cppstream
74c96aeb464703fed765739b27dcfabed696dae5
[ "MIT" ]
2
2016-07-25T17:32:23.000Z
2021-05-25T14:05:13.000Z
src/ramp.cpp
mloy/cppstream
74c96aeb464703fed765739b27dcfabed696dae5
[ "MIT" ]
6
2015-05-18T18:55:05.000Z
2021-11-18T19:29:08.000Z
// Copyright 2014 Hottinger Baldwin Messtechnik // Distributed under MIT license // See file LICENSE provided #include <iostream> #include <string> #include <signal.h> #include <unordered_map> #include <cmath> #include <json/writer.h> #include <json/value.h> #include "streamclient/streamclient.h" #include "streamclient/signalcontainer.h" #include "streamclient/types.h" struct lastRampValues { uint64_t timeStamp; double amplitude; }; typedef std::unordered_map < unsigned int, lastRampValues > lastRampValues_t; /// receives data from DAQ Stream Server. Subscribes/Unsubscribes signals static hbm::streaming::StreamClient streamClient; /// handles signal related meta information and measured data. static hbm::streaming::SignalContainer signalContainer; static double rampValueDiff = 0.1; static const double epsilon = 0.0000000001; static lastRampValues_t m_lastRampValues; static void sigHandler(int) { streamClient.stop(); } static void streamMetaInformationCb(hbm::streaming::StreamClient& stream, const std::string& method, const Json::Value& params) { if (method == hbm::streaming::META_METHOD_AVAILABLE) { // simply subscibe all signals that become available. hbm::streaming::signalReferences_t signalReferences; for (Json::ValueConstIterator iter = params.begin(); iter!= params.end(); ++iter) { const Json::Value& element = *iter; signalReferences.push_back(element.asString()); } try { stream.subscribe(signalReferences); std::cout << __FUNCTION__ << "the following " << signalReferences.size() << " signal(s) were subscribed: "; } catch(const std::runtime_error& e) { std::cerr << __FUNCTION__ << "error '" << e.what() << "' subscribing the following signal(s): "; } for(hbm::streaming::signalReferences_t::const_iterator iter=signalReferences.begin(); iter!=signalReferences.end(); ++iter) { std::cout << "'" << *iter << "' "; } std::cout << std::endl; } else if(method==hbm::streaming::META_METHOD_UNAVAILABLE) { std::cout << __FUNCTION__ << "the following signal(s) are not available anyore: "; for (Json::ValueConstIterator iter = params.begin(); iter!= params.end(); ++iter) { const Json::Value& element = *iter; std::cout << element.asString() << ", "; } std::cout << std::endl; } else if(method==hbm::streaming::META_METHOD_ALIVE) { // We do ignore this. We are using TCP keep alive in order to detect communication problems. } else if(method==hbm::streaming::META_METHOD_FILL) { if(params.empty()==false) { unsigned int fill = params[0u].asUInt(); if(fill>25) { std::cout << stream.address() << ": ring buffer fill level is " << params[0u].asUInt() << "%" << std::endl; } } } else { std::cout << __FUNCTION__ << " " << method << " " << Json::FastWriter().write(params) << std::endl; } } static void signalMetaInformationCb(hbm::streaming::SubscribedSignal& subscribedSignal, const std::string& method, const Json::Value& ) { std::cout << subscribedSignal.signalReference() << ": " << method << std::endl; } static void dataCb(hbm::streaming::SubscribedSignal& subscribedSignal, uint64_t timeStamp, const double* pValues, size_t count) { unsigned int signalNumber = subscribedSignal.signalNumber(); lastRampValues_t::iterator iter = m_lastRampValues.find(signalNumber); if(iter==m_lastRampValues.end()) { lastRampValues lastValues; lastValues.timeStamp = timeStamp; lastValues.amplitude = pValues[count-1]; m_lastRampValues.insert(std::make_pair(signalNumber, lastValues)); } else { double valueDiff = pValues[0] - iter->second.amplitude; if(fabs(valueDiff - rampValueDiff) > epsilon) { throw std::runtime_error (subscribedSignal.signalReference() + ": unexpected value in ramp!"); } else if (iter->second.timeStamp>=timeStamp){ throw std::runtime_error (subscribedSignal.signalReference() + ": unexpected time stamp in ramp!"); } else { iter->second.amplitude = pValues[count-1]; } } } int main(int argc, char* argv[]) { // Some signals should lead to a normal shutdown of the daq stream client. Afterwards the program exists. signal( SIGTERM, &sigHandler); signal( SIGINT, &sigHandler); if ((argc<2) || (std::string(argv[1])=="-h") ) { std::cout << "Subscribes all signals that become available." << std::endl; std::cout << "Each signal is expected to deliver a ramp with a defined slope." << std::endl; std::cout << std::endl; std::cout << "syntax: " << argv[0] << " <stream server address> <slope (default is " << rampValueDiff << ")>" << std::endl; return EXIT_SUCCESS; } if (argc==3) { char* pEnd; const char* pStart = argv[2]; rampValueDiff = strtod(pStart, &pEnd); if (pEnd ==pStart) { std::cerr << "invalid slope value. Must be a number" << std::endl; return EXIT_FAILURE; } } signalContainer.setDataAsDoubleCb(dataCb); signalContainer.setSignalMetaCb(signalMetaInformationCb); streamClient.setStreamMetaCb(streamMetaInformationCb); streamClient.setSignalContainer(&signalContainer); // connect to the daq stream service and give control to the receiving function. // returns on signal (terminate, interrupt) buffer overrun on the server side or loss of connection. streamClient.start(argv[1], hbm::streaming::DAQSTREAM_PORT); return EXIT_SUCCESS; }
35.322148
135
0.711001
mloy
61aed068b89fa7d92561892522e8eca9f87c90db
2,804
cpp
C++
components/libm8r/Mallocator.cpp
cmarrin/libm8r
2261a52d74a814541ca1a00c23f68a5695f06f99
[ "MIT" ]
null
null
null
components/libm8r/Mallocator.cpp
cmarrin/libm8r
2261a52d74a814541ca1a00c23f68a5695f06f99
[ "MIT" ]
null
null
null
components/libm8r/Mallocator.cpp
cmarrin/libm8r
2261a52d74a814541ca1a00c23f68a5695f06f99
[ "MIT" ]
null
null
null
/*------------------------------------------------------------------------- This source file is a part of m8rscript For the latest info, see http:www.marrin.org/ Copyright (c) 2018-2019, Chris Marrin All rights reserved. Use of this source code is governed by the MIT license that can be found in the LICENSE file. -------------------------------------------------------------------------*/ #include "Mallocator.h" #include "SystemInterface.h" #include <cstdio> using namespace m8r; Mallocator Mallocator::_mallocator; RawMad Mallocator::alloc(uint32_t size, MemoryType type) { assert(type != MemoryType::Unknown); RawMad allocatedBlock = reinterpret_cast<RawMad>(::malloc(size)); assert(_memoryInfo.numAllocations < std::numeric_limits<uint16_t>::max()); ++_memoryInfo.numAllocations; _memoryInfo.totalAllocatedBytes += size; if (allocatedBlock == NoRawMad) { return NoRawMad; } uint32_t index = static_cast<uint32_t>(type); _memoryInfo.allocationsByType[index].count++; _memoryInfo.allocationsByType[index].size += size; return allocatedBlock; } void Mallocator::free(RawMad ptr, MemoryType type) { // FIXME: How do we get the size? Pass it in? uint32_t size = 0; assert(type != MemoryType::Unknown); ::free(reinterpret_cast<void*>(ptr)); assert(_memoryInfo.numAllocations > 0); --_memoryInfo.numAllocations; _memoryInfo.totalAllocatedBytes -= size; uint32_t index = static_cast<uint32_t>(type); assert(_memoryInfo.allocationsByType[index].count > 0); _memoryInfo.allocationsByType[index].count--; assert(_memoryInfo.allocationsByType[index].size >= size); _memoryInfo.allocationsByType[index].size -= size; } uint32_t Mallocator::freeSize() const { int32_t size = SystemInterface::heapFreeSize(); if (size >= 0) { return size; } // This is the Mac, make an estimate return (_memoryInfo.totalAllocatedBytes > 80000) ? 0 : 80000 - _memoryInfo.totalAllocatedBytes; } const char* Mallocator::stringFromMemoryType(MemoryType type) { switch(type) { case MemoryType::String: return "String"; case MemoryType::Character: return "Char"; case MemoryType::Object: return "Object"; case MemoryType::ExecutionUnit: return "ExecutionUnit"; case MemoryType::Native: return "Native"; case MemoryType::Vector: return "Vector"; case MemoryType::UpValue: return "UpValue"; case MemoryType::Network: return "Network"; case MemoryType::Fixed: return "Fixed"; case MemoryType::NumTypes: case MemoryType::Unknown: default: return "Unknown"; } }
31.155556
99
0.628388
cmarrin
61af7799977d5ffdbd5bdd255d06b757173746a5
13,057
hpp
C++
source/code/utilities/types/vectors/transformers/lib.hpp
luxe/CodeLang-compiler
78837d90bdd09c4b5aabbf0586a5d8f8f0c1e76a
[ "MIT" ]
1
2019-01-06T08:45:46.000Z
2019-01-06T08:45:46.000Z
source/code/utilities/types/vectors/transformers/lib.hpp
luxe/CodeLang-compiler
78837d90bdd09c4b5aabbf0586a5d8f8f0c1e76a
[ "MIT" ]
264
2015-11-30T08:34:00.000Z
2018-06-26T02:28:41.000Z
source/code/utilities/types/vectors/transformers/lib.hpp
UniLang/compiler
c338ee92994600af801033a37dfb2f1a0c9ca897
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include <string> #include <algorithm> #include <iostream> #include <random> #include <set> #include "code/utilities/types/strings/transformers/casing/lib.hpp" #include "code/utilities/data_structures/index_mode.hpp" #include "code/utilities/data_structures/index/moded_index.hpp" #include "code/utilities/types/map/lib.hpp" #include "code/utilities/language_basic/std_hackery/std_aliases.hpp" #include "code/utilities/types/strings/observers/converting/lib.hpp" //whoops.. pre-pre-jstd is really needed template <typename T> void Add_To_Set(std::set<T> & s, T const& item_to_add); template <typename T> bool Exists_In_Set(std::set<T> const& s, T const& item); template <typename T> bool In_Vector(std::vector<T> const& vec, T const& item); //rotating void rotateLeft(std::vector<int> & vec); std::vector<int> rotateLeft(std::vector<int> vec, int numberOfTimes); std::vector<int> rotateLeftModVersion(std::vector<int> vec, int numberOfTimes); template <class T> void erase_selected(std::vector<T>& v, const std::vector<int>& selection) { v.resize(std::distance( v.begin(), std::stable_partition(v.begin(), v.end(), [&selection, &v](const T& item) { return !std::binary_search( selection.begin(), selection.end(), static_cast<int>(static_cast<const T*>(&item) - &v[0])); }))); } template <typename T> void Move_Indexed_Item_To_Back(std::vector<T>& v, size_t itemIndex) { auto it = v.begin() + itemIndex; std::rotate(it, it + 1, v.end()); } template <typename T> void Ensure_Not_Empty(std::vector<T>& v) { if (v.empty()){ T t; v.emplace_back(t); } } template <typename T> void Transfer_An_Element(std::vector<T>& from, std::vector<T>& to){ if (!from.empty()){ auto take = from[0]; Remove_First_Element(from); to.emplace_back(take); } } //math (string is treated as integer) void Add_Each_Line_By(std::vector<std::string> & v, int num); void Subtract_Each_Line_By(std::vector<std::string> & v, int num); void Multiply_Each_Line_By(std::vector<std::string> & v, int num); void Divide_Each_Line_By(std::vector<std::string> & v, int num); int Accumulate(std::vector<int> const& v); int Accumulate(std::vector<std::string> const& v); int Multiply(std::vector<int> const& v); template <typename T, typename Fun> int Accumulate(std::vector<T> const& v, Fun f){ int total = 0; for (auto const& it: v){ total += f(it); } return total; } template <typename T> std::vector<T> AccumulateLeftToRightDigonal(std::vector<std::vector<T>> arr){ std::vector<T> result; for (size_t i = 0; i < arr.size(); ++i){ result.emplace_back(arr[i][i]); } return result; } template <typename T> std::vector<T> AccumulateRightToLeftDigonal(std::vector<std::vector<T>> arr){ std::vector<T> result; for (size_t i = 0; i < arr.size(); ++i){ result.emplace_back(arr[arr.size()-(i+1)][i]); } return result; } template <typename T> int computeDiagonalDifference(std::vector<std::vector<T>> arr) { auto left = AccumulateLeftToRightDigonal(arr); auto right = AccumulateRightToLeftDigonal(arr); auto answer = Accumulate(right) - Accumulate(left); return abs(answer); } //insert an element between all the elements template <typename T> std::vector<T>& intersperse(std::vector<T> & vec, T const& item){ std::vector<T> new_vec; for (size_t i = 0; i < vec.size(); ++i){ new_vec.emplace_back(vec[i]); //if its not the last element if (i != vec.size()-1){ new_vec.emplace_back(item); } } } template <typename T> void Add_To_Back(std::vector<T> & vec, T const& item){ vec.push_back(item); } template <typename T> void Add_To_Front(std::vector<T> & vec, T const& item){ vec.insert(vec.begin(), item); } template <typename T> void Add(std::vector<T> & vec, T const& item){ vec.emplace_back(item); } template <typename T> void Add(std::vector<T> & vec){ T item; vec.emplace_back(item); } template <typename T> void Add_N(std::vector<T> & vec, T const& item, int num){ for (int i = 0; i < num; ++i){ vec.emplace_back(item); } } void Add(std::vector<std::string> & vec, std::string const& item); template <typename T> void Add_To_Vector_If_Not_Already_There(std::vector<T> & vec, T const& item){ if (!In_Vector(vec,item)){ vec.push_back(item); } } template <typename T> void Expand_Vector_For_Index(std::vector<T> & vec, size_t at_index){ for (size_t i = vec.size(); i < at_index+1; ++i){ T t; vec.emplace_back(t); } } template <typename T> void Safely_Add_To_Vector_At_Index(std::vector<T> & vec, size_t at_index, T const& item){ //buffer with the item as needed for (int i = vec.size(); i < at_index+1; ++i){ vec.emplace_back(item); } //add at index vec[at_index] = item; } template <typename T> std::vector<T>& Remove_Element(std::vector<T>& vec, T const& value){ vec.erase(std::remove(vec.begin(), vec.end(), value), vec.end()); return vec; } template <typename T> std::vector<T>& Remove_Element_First_Found_Only(std::vector<T>& vec, T const& value){ for (size_t i = 0; i < vec.size(); ++i){ if (vec[i] == value){ vec.erase(vec.begin() + i); return vec; } } return vec; } template <typename T> std::vector<T> RemoveMaxElement(std::vector<T> vec){ auto element = MaxElement(vec); return Remove_Element_First_Found_Only(vec,element); } template <typename T> std::vector<T> RemoveMinElement(std::vector<T> vec){ auto element = MinElement(vec); return Remove_Element_First_Found_Only(vec,element); } template <typename T> std::vector<T> RemoveMaxElements(std::vector<T> vec){ auto element = MaxElement(vec); return Remove_Element_First_Found_Only(vec,element); } template <typename T> std::vector<T> RemoveMinElements(std::vector<T> vec){ auto element = MinElement(vec); return Remove_Element_First_Found_Only(vec,element); } template <typename T> std::vector<T>& Sort_And_Remove_Duplicates(std::vector<T>& vec){ std::sort(vec.begin(), vec.end()); vec.erase(std::unique(vec.begin(), vec.end()), vec.end()); return vec; } template <typename T> std::vector<T>& Sort(std::vector<T>& vec){ std::sort(vec.begin(), vec.end()); return vec; } template <typename T> std::vector<T> & Sort_For_Colums(std::vector<T>& vec, size_t cols){ std::vector<T> new_vec; for (size_t skip_amount = 0; skip_amount < cols+1; ++skip_amount){ for (size_t i = skip_amount; i < vec.size(); i += cols+1){ new_vec.emplace_back(vec[i]); } } vec = new_vec; return vec; } template <typename T> std::vector<T>& Remove_Duplicates(std::vector<T>& vec){ std::vector<T> solution; std::set<T> found; for (auto it: vec){ if (!Exists_In_Set(found,it)){ solution.push_back(it); Add_To_Set(found,it); } } vec = solution; return vec; } template <typename T> std::vector<T>& Non_Case_Sensitive_Sort_And_Remove_Duplicates(std::vector<T>& vec){ std::vector<T> solution; std::set<T> found; for (auto it: vec){ if (!Exists_In_Set(found,As_Lowercase(it))){ solution.push_back(it); Add_To_Set(found,As_Lowercase(it)); } } vec = solution; std::sort(vec.begin(), vec.end()); return vec; } template <typename T> std::vector<T>& Reverse_Each_String(std::vector<T>& vec){ for (auto & it: vec){ Reverse(it); } return vec; } template <typename T> void Remove_First_Element(std::vector<T>& vec){ vec.erase(vec.begin()); return; } template <typename T> void Remove_First_N_Elements(std::vector<T>& vec, size_t const& n){ vec.erase(vec.begin(), vec.begin() + n); return; } template <typename T> void Remove_Last_Element(std::vector<T>& vec){ vec.pop_back(); return; } template <typename T> void Safe_Pop_Back(std::vector<T>& vec){ if (!vec.empty()){ vec.pop_back(); } return; } template <typename T> void Remove_Last_N_Elements(std::vector<T>& vec, size_t const& n){ for (size_t i = 0; i < n; ++i) vec.pop_back(); return; } template <typename T> void Remove_Nth_Element(std::vector<T>& vec, size_t const& n){ vec.erase(vec.begin() + n); return; } template <typename T> void Remove_Element_Range(std::vector<T>& vec, size_t const& start, size_t const& end){ vec.erase(vec.begin() + start, vec.begin() + end + 1); return; } template <typename T> void Remove_Elements_Of_Vector_One_Found_In_Vector_Two(std::vector<T> & one, std::vector<T> const& two){ for (auto const& it: two){ auto found = std::find(one.begin(), one.end(), it); if (found != one.end()){ one.erase(found); } } } template <typename T> void Remove_Elements_Of_Vector_Two_Found_In_Vector_One(std::vector<T> const& one, std::vector<T> & two){ for (auto const& it: one){ auto found = std::find(two.begin(), two.end(), it); if (found != two.end()){ two.erase(found); } } } // template <typename T> // std::vector<T> RemoveMaxElement(std::vector<T> vec){ // auto element = MaxElement(vec); // return Remove_Element(vec,element); // } // template <typename T> // std::vector<T> RemoveMinElement(std::vector<T> vec){ // auto element = MinElement(vec); // return Remove_Element(vec,element); // } template <typename T> std::vector<T>& Lowercase(std::vector<T>& vec){ std::for_each(vec.begin(),vec.end(),[](T & t){ Lowercase(t); return;}); return vec; } template <typename T> std::vector<T>& Uppercase(std::vector<T>& vec){ std::for_each(vec.begin(),vec.end(),[](T & t){ Uppercase(t); return;}); return vec; } template <typename T> std::vector<T>& Turn_Whitespace_Lines_Into_Empty_Lines(std::vector<T>& vec){ for (auto & line: vec){ if (Contains_Only_Whitespace_Characters(line)){ line.clear(); } } return vec; } std::vector<std::string>& Remove_Whitespace_Lines(std::vector<std::string>& v); std::vector<std::string>& Trim_Lines(std::vector<std::string>& v); std::vector<std::string>& Remove_First_Elements_That_Are_Whitespace_Elements(std::vector<std::string>& vec); std::vector<std::string>& Remove_Last_Elements_That_Are_Whitespace_Elements(std::vector<std::string>& vec); std::vector<std::string>& Remove_Last_Whitespace_Elements_And_Ensure_Only_One_Last_Empty_Element(std::vector<std::string>& vec); std::vector<std::string>& Remove_Elements_That_Match_String(std::vector<std::string>& vec, std::string const& match); std::vector<std::string>& Remove_All_Empty_String_Elements(std::vector<std::string>& vec); std::vector<std::string>& Move_First_Word_Of_String_To_The_End_For_Each_Element(std::vector<std::string>& vec); std::vector<std::string>& Squeeze_Away_Spaces_For_Each_Element(std::vector<std::string>& vec); std::vector<std::string>& Squeeze_Whitespace_Elements(std::vector<std::string>& vec); template <typename T, typename Function> std::vector<T>& Remove_Elements_Where_Function_Is_True( std::vector<T> & v, Function const& f){ v.erase( std::remove_if(std::begin(v), std::end(v), f), std::end(v) ); return v; } template <typename T, typename Function> std::vector<T>& Remove_Elements_Where_Function_Is_False( std::vector<T> & v, Function const& f){ v.erase( std::remove_if(std::begin(v), std::end(v), !f), std::end(v) ); return v; } template <typename T, typename Function> std::vector<T>& Remove_If( std::vector<T> & v, Function const& f){ v.erase( std::remove_if(std::begin(v), std::end(v), f), std::end(v) ); return v; } //void Remove_Empty_Strings(std::vector<std::string> & vec); //void Remove_Any_Strings_That_Are_Whitespace(std::vector<std::string> & vec); //this is a joke sort template <typename value_t> void BogoSort( std::vector< value_t > & data ){ while( !std::is_sorted(data.cbegin(), data.cend()) ) {std::shuffle(data.begin(), data.end());} } template <typename T> void Shuffle(std::vector<T> vec){ std::random_device rd; std::mt19937 g(rd()); std::shuffle(vec.begin(),vec.end(),g); } void Alphabetize_And_Print(std::vector<std::string> results); template <typename T> std::vector<std::vector<T>> transpose(const std::vector<std::vector<T>> matrix) { // this assumes that all inner vectors have the same size and // allocates space for the complete result in advance std::vector<std::vector<T>> result(matrix[0].size(),std::vector<T>(matrix.size())); for (typename std::vector<T>::size_type i = 0; i < matrix[0].size(); ++i){ for (typename std::vector<T>::size_type j = 0; j < matrix.size(); j++){ result[i][j] = matrix[j][i]; } } return result; }
28.446623
128
0.647852
luxe
61afee0168a286e2fabed63102035aea17224745
2,472
cpp
C++
wkkit/wkkit/src/XBuzzer.cpp
7thTool/XMixly
61f0c62fc8798fd2eb98ecb412500b55501c0ce9
[ "Apache-2.0" ]
null
null
null
wkkit/wkkit/src/XBuzzer.cpp
7thTool/XMixly
61f0c62fc8798fd2eb98ecb412500b55501c0ce9
[ "Apache-2.0" ]
null
null
null
wkkit/wkkit/src/XBuzzer.cpp
7thTool/XMixly
61f0c62fc8798fd2eb98ecb412500b55501c0ce9
[ "Apache-2.0" ]
null
null
null
/* XBuzzer.cpp * * Copyright (C) 2017-2022 Shanghai Mylecon Electronic Technology Co., Ltd. * * 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; * * Description: * This file is a driver for Buzzer module. * * Version: 1.0.0 */ #include <Arduino.h> #include <avr/wdt.h> #include <xport.h> #include <XBuzzer.h> #define XBUZZER_3C_NAME "BUZ" #if 0 #include <XDebug.h> #define LOG(x) XDebug.print(x) #define LOGN(x) XDebug.println(x) #else #define LOG(x) #define LOGN(x) #endif XBuzzer::~XBuzzer() { LOGN("XBuzzer::~XBuzzer()"); reset(); if (_portId >= 0) { PortRelease(_portId); } } int XBuzzer::setup(const char *model, const char *port) { PortMap pmap; LOG("XBuzzer::setup(");LOG(model);LOG(",");LOG(port);LOGN(")"); (void)model; _portId = PortSetup(port, XPORT_FUNC_D1, &pmap); if (_portId >= 0) { _pin = pmap.plat.io.D1.pin; pinMode(_pin, OUTPUT); } else{ LOGN("PortSetup() failed!"); return -1; } reset(); return 0; } int XBuzzer::setup(const char *label) { PortMap pmap; char model[8]; LOG("XBuzzer::setup(");LOG(label);LOGN(")"); if(PortOnBoardSetup(label, model, &pmap)) { _pin = pmap.plat.io.D1.pin; _portId = -1; pinMode(_pin, OUTPUT); } else { LOGN("PortOnBoardSetup failed!"); return -1; } reset(); return 0; } void XBuzzer::reset() { if (_pin != 0xFF) { digitalWrite(_pin, LOW); } } void XBuzzer::playTone(uint16_t frequency, uint32_t duration) { int period = 1000000L / frequency; int pulse = period / 2; LOGN("XBuzzer::playTone():"); LOG("frequency = ");LOGN(frequency); LOG("duration = ");LOGN(duration); LOG("period = ");LOGN(period); if (_pin == 0xFF) { LOGN("XBuzzer not setup"); return; } for (unsigned long i = 0; i < duration * 1000ul; i += period) { digitalWrite(_pin, HIGH); delayMicroseconds(pulse); digitalWrite(_pin, LOW); delayMicroseconds(pulse); wdt_reset(); /*!< CAUTION: */ } }
19.3125
75
0.663835
7thTool
61b04792f624f429602c4b87bd6d58e0a9af13ca
2,977
hpp
C++
include/traversecpp/composite.hpp
de-passage/opengl-stuffs
54b785ad7818118342b203ae8f5d2e55373a1813
[ "MIT" ]
null
null
null
include/traversecpp/composite.hpp
de-passage/opengl-stuffs
54b785ad7818118342b203ae8f5d2e55373a1813
[ "MIT" ]
null
null
null
include/traversecpp/composite.hpp
de-passage/opengl-stuffs
54b785ad7818118342b203ae8f5d2e55373a1813
[ "MIT" ]
null
null
null
#ifndef GUARD_DPSG_COMPOSITE_HPP #define GUARD_DPSG_COMPOSITE_HPP #include <type_traits> #include "./fold.hpp" #include "./traverse.hpp" namespace dpsg { template <class... Args> struct composite { constexpr composite() noexcept {} template < class... Args2, std::enable_if_t< std::conjunction_v<std::is_convertible<std::decay_t<Args2>, Args>...>, int> = 0> constexpr explicit composite(Args2&&... args) noexcept : components{std::forward<Args2>(args)...} {} std::tuple<Args...> components; template <class C, class F, class... Args2, std::enable_if_t<std::is_base_of_v<composite, C>, int> = 0> constexpr friend void dpsg_traverse(const C& c, F&& f, Args2&&... args) { f(c, next(c, f, dpsg::feed_t<composite, std::index_sequence_for>{}), std::forward<Args2>(args)...); } template <class C, class F, class A, class... Args2, std::enable_if_t<std::is_base_of_v<composite, C>, int> = 0> constexpr friend auto dpsg_fold(const C& c, A&& a, F&& f, Args2&... args) noexcept { return f(std::forward<A>(a), c, next_fold<0, feed_t<composite, detail::parameter_count>>(c, f), args...); } private: template <std::size_t N, class Count, class C, class F, std::size_t... Is> constexpr static auto next_fold(C&& c, F&& f) noexcept { return [&c, &f](auto&& acc, [[maybe_unused]] auto&&... user_input) { if constexpr (N >= Count::value) { (void)(c); (void)(f); return acc; } else { return dpsg::fold(std::get<N>(c.components), next_fold<N + 1, Count>(c, f)( std::forward<decltype(acc)>(acc), user_input...), f, user_input...); } }; } template <class C, class F, std::size_t... Is, std::enable_if_t<std::is_base_of_v<composite, C>, int> = 0> constexpr static auto next( [[maybe_unused]] const C& c1, [[maybe_unused]] F&& f, [[maybe_unused]] std::index_sequence<Is...> seq) noexcept { return [&c1, &f](auto&&... user_input) { if constexpr (sizeof...(Is) == 0) { // suppresses warnings in the case of a composite with no elements // there doesn't seem to be a way to apply [[maybe_unused]] to a // lambda capture list (void)(c1); (void)(f); } else { (dpsg::traverse(std::get<Is>(c1.components), f, std::forward<decltype(user_input)>(user_input)...), ...); } }; } }; template <class... Args> composite(Args&&...) -> composite<std::decay_t<Args>...>; } // namespace dpsg #endif // GUARD_DPSG_COMPOSITE_HPP
29.77
80
0.520994
de-passage
61b0a0445bab372d7975f16a01c275c463def660
13,204
cpp
C++
Vulkan/src/Vulkan/tests/TestGraphicsPipeline.cpp
ilkeraktug/Vulkan
b736ba2e01dc8fdfd1aaf3dec334882f7467263f
[ "MIT" ]
null
null
null
Vulkan/src/Vulkan/tests/TestGraphicsPipeline.cpp
ilkeraktug/Vulkan
b736ba2e01dc8fdfd1aaf3dec334882f7467263f
[ "MIT" ]
null
null
null
Vulkan/src/Vulkan/tests/TestGraphicsPipeline.cpp
ilkeraktug/Vulkan
b736ba2e01dc8fdfd1aaf3dec334882f7467263f
[ "MIT" ]
null
null
null
#include "pch.h" #include "TestGraphicsPipeline.h" namespace test { TestGraphicsPipeline::TestGraphicsPipeline(VulkanCore* core) { Test::Init(core); glfwSetWindowTitle(static_cast<GLFWwindow*>(Window::GetWindow()), "TestGraphicsPipeline"); float right = m_Core->swapchain.extent.width / 200.0f; float top = m_Core->swapchain.extent.height / 200.0f; m_Camera = new OrthographicCamera(-right, right, -top, top, core); float vertices[] = { // Vertex Positions, Colors, Tex Coords -0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.5f, -0.5f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.5f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, -0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f }; VertexBufferLayout layout = { {"a_Position", ShaderFormat::Float3}, {"a_Color", ShaderFormat::Float3}, {"a_TexCoords", ShaderFormat::Float2} }; m_VertexBuffer.reset(new VulkanVertexBuffer(vertices, sizeof(vertices), m_Core)); m_VertexBuffer->SetLayout(layout); uint16_t indices[] = { 0, 1, 2, 2, 3, 0 }; m_IndexBuffer.reset(new VulkanIndexBuffer(indices, 6, m_Core)); for (int i = 0; i < objs.size(); i++) { objs[i] = new QuadObj(m_Core); } objs[0]->SetScale(5.0f, 5.0f, 0.0f); objs[0]->SetRotation(0.0f, 0.0f, 45.0f); m_Texture.reset(new VulkanTexture2D("assets/textures/face.jpg", m_Core)); prepareDescriptorPool(); preparePipeline(); setCmdBuffers(); } TestGraphicsPipeline::~TestGraphicsPipeline() { vkDestroyDescriptorSetLayout(m_Core->GetDevice(), m_DescriptorSetLayout, nullptr); vkDestroyDescriptorPool(m_Core->GetDevice(), m_DescriptorPool, nullptr); vkDestroyPipeline(m_Core->GetDevice(), m_GraphicsPipeline, nullptr); vkDestroyPipelineLayout(m_Core->GetDevice(), m_PipelineLayout, nullptr); for (int i = 0; i < objs.size(); i++) { delete objs[i]; } delete m_Camera; } void TestGraphicsPipeline::OnUpdate(float deltaTime) { if (glfwGetKey(static_cast<GLFWwindow*>(Window::GetWindow()), GLFW_KEY_A) == GLFW_PRESS) { m_CameraPosition.x -= m_CameraMoveSpeed * deltaTime; } else if(glfwGetKey(static_cast<GLFWwindow*>(Window::GetWindow()), GLFW_KEY_D) == GLFW_PRESS) { m_CameraPosition.x += m_CameraMoveSpeed * deltaTime; } if (glfwGetKey(static_cast<GLFWwindow*>(Window::GetWindow()), GLFW_KEY_W) == GLFW_PRESS) { m_CameraPosition.y += m_CameraMoveSpeed * deltaTime; } else if (glfwGetKey(static_cast<GLFWwindow*>(Window::GetWindow()), GLFW_KEY_S) == GLFW_PRESS) { m_CameraPosition.y -= m_CameraMoveSpeed * deltaTime; } m_Camera->SetPosition(m_CameraPosition); objs[0]->Rotate(90.0f * deltaTime, { 0.0f, 0.0f, 1.0f }, Space::Local); updateUniformBuffers(); } void TestGraphicsPipeline::OnRender() { m_Core->BeginScene(); m_Core->resources.submitInfo.commandBufferCount = 1; m_Core->resources.submitInfo.pCommandBuffers = &m_Core->resources.drawCmdBuffers[m_Core->resources.imageIndex]; VK_CHECK(vkQueueSubmit(m_Core->queue.GraphicsQueue, 1, &m_Core->resources.submitInfo, VK_NULL_HANDLE)); VkResult err = m_Core->Submit(); if (err == VK_ERROR_OUT_OF_DATE_KHR || err == VK_SUBOPTIMAL_KHR) windowResized(); else VK_CHECK(err); //TODO : Fences and Semaphores ! vkDeviceWaitIdle(m_Core->GetDevice()); } void TestGraphicsPipeline::OnImGuiRender() { } void TestGraphicsPipeline::prepareDescriptorPool() { std::vector<VkDescriptorSetLayoutBinding> layoutBindings = { init::descriptorSetLayoutBinding( VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT, 0), init::descriptorSetLayoutBinding( VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT, 1), init::descriptorSetLayoutBinding( VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 2), }; VkDescriptorSetLayoutCreateInfo descriptorSetLayoutCI = init::descriptorSetLayoutCreateInfo(); descriptorSetLayoutCI.bindingCount = layoutBindings.size(); descriptorSetLayoutCI.pBindings = layoutBindings.data(); VK_CHECK(vkCreateDescriptorSetLayout(m_Core->GetDevice(), &descriptorSetLayoutCI, nullptr, &m_DescriptorSetLayout)); std::vector<VkDescriptorPoolSize> poolSizes = { init::descriptorPoolSize(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 100), init::descriptorPoolSize(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 100) }; VkDescriptorPoolCreateInfo descriptorPoolCI = init::descriptorPoolCreateInfo(); descriptorPoolCI.poolSizeCount = poolSizes.size(); descriptorPoolCI.pPoolSizes = poolSizes.data(); descriptorPoolCI.maxSets = 100; VK_CHECK(vkCreateDescriptorPool(m_Core->GetDevice(), &descriptorPoolCI, nullptr, &m_DescriptorPool)); for (int i = 0; i < objs.size(); i++) { VkDescriptorSetAllocateInfo descriptorSetAI = init::descriptorSetAllocateInfo(); descriptorSetAI.descriptorPool = m_DescriptorPool; descriptorSetAI.descriptorSetCount = 1; descriptorSetAI.pSetLayouts = &m_DescriptorSetLayout; VK_CHECK(vkAllocateDescriptorSets(m_Core->GetDevice(), &descriptorSetAI, &objs[i]->DescriptorSet)); std::array<VkWriteDescriptorSet, 3> writeDescriptors{}; writeDescriptors[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; writeDescriptors[0].dstSet = objs[i]->DescriptorSet; writeDescriptors[0].dstBinding = 0; writeDescriptors[0].descriptorCount = 1; writeDescriptors[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; writeDescriptors[0].pBufferInfo = &objs[i]->ModelBuffer->GetBufferInfo(); writeDescriptors[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; writeDescriptors[1].dstSet = objs[i]->DescriptorSet; writeDescriptors[1].dstBinding = 1; writeDescriptors[1].descriptorCount = 1; writeDescriptors[1].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; writeDescriptors[1].pBufferInfo = &m_Camera->MatricesBuffer->GetBufferInfo(); writeDescriptors[2].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; writeDescriptors[2].dstSet = objs[i]->DescriptorSet; writeDescriptors[2].dstBinding = 2; writeDescriptors[2].descriptorCount = 1; writeDescriptors[2].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; writeDescriptors[2].pImageInfo = &m_Texture->descriptor; vkUpdateDescriptorSets(m_Core->GetDevice(), writeDescriptors.size(), writeDescriptors.data(), 0, nullptr); } } void TestGraphicsPipeline::preparePipeline() { VkPipelineLayoutCreateInfo pipelineLayoutCreateInfo = init::pipelineLayout(); pipelineLayoutCreateInfo.pushConstantRangeCount = 0; pipelineLayoutCreateInfo.setLayoutCount = 1; pipelineLayoutCreateInfo.pSetLayouts = &m_DescriptorSetLayout; VK_CHECK(vkCreatePipelineLayout(m_Core->GetDevice(), &pipelineLayoutCreateInfo, nullptr, &m_PipelineLayout)); VkPipelineVertexInputStateCreateInfo vertexInputState = init::pipelineVertexInputState(); vertexInputState.vertexBindingDescriptionCount = 1; vertexInputState.pVertexBindingDescriptions = &m_VertexBuffer->GetVertexInput(); vertexInputState.vertexAttributeDescriptionCount = m_VertexBuffer->GetVertexAttributes().size(); vertexInputState.pVertexAttributeDescriptions = m_VertexBuffer->GetVertexAttributes().data(); VkPipelineShaderStageCreateInfo shaderStages[2]; shaderStages[0] = VulkanShader::GetShaderModule(m_Core->GetDevice(), "assets/shaders/graphicsPipeline/vert.spv", VK_SHADER_STAGE_VERTEX_BIT); shaderStages[1] = VulkanShader::GetShaderModule(m_Core->GetDevice(), "assets/shaders/graphicsPipeline/frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); VkPipelineInputAssemblyStateCreateInfo inputAssemblyState = init::pipelineInputAssemblyState(); inputAssemblyState.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; inputAssemblyState.primitiveRestartEnable = VK_FALSE; VkPipelineRasterizationStateCreateInfo rasterizationStateInfo = init::pipelineRasterizationState(); rasterizationStateInfo.depthClampEnable = VK_FALSE; rasterizationStateInfo.rasterizerDiscardEnable = VK_FALSE; rasterizationStateInfo.polygonMode = VK_POLYGON_MODE_FILL; rasterizationStateInfo.cullMode = 0; rasterizationStateInfo.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; rasterizationStateInfo.depthBiasEnable = VK_FALSE; rasterizationStateInfo.lineWidth = 1.0f; VkPipelineColorBlendAttachmentState blendAttachment{}; blendAttachment.blendEnable = VK_TRUE; blendAttachment.srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA; blendAttachment.dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; blendAttachment.colorBlendOp = VK_BLEND_OP_ADD; blendAttachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA; blendAttachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; blendAttachment.alphaBlendOp = VK_BLEND_OP_ADD; blendAttachment.colorWriteMask = 0xF; //VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; VkPipelineColorBlendStateCreateInfo blendState = init::pipelineColorBlendState(); blendState.logicOpEnable = VK_FALSE; blendState.attachmentCount = 1; blendState.pAttachments = &blendAttachment; VkPipelineDepthStencilStateCreateInfo depthStencilState = init::pipelineDepthStencilState(); depthStencilState.depthBoundsTestEnable = VK_FALSE; depthStencilState.depthWriteEnable = VK_TRUE; depthStencilState.depthCompareOp = VK_COMPARE_OP_LESS; depthStencilState.stencilTestEnable = VK_FALSE; VkViewport viewPort{0, 0, m_Core->swapchain.extent.width, m_Core->swapchain.extent.height, 0.0f, 1.0f}; VkRect2D scissor; scissor.offset = { 0, 0 }; scissor.extent = m_Core->swapchain.extent; VkPipelineViewportStateCreateInfo viewportState = init::pipelineViewportState(); viewportState.scissorCount = 1; viewportState.pScissors = &scissor; viewportState.viewportCount = 1; viewportState.pViewports = &viewPort; VkPipelineMultisampleStateCreateInfo multiSampleState = init::multiSampleState(); multiSampleState.sampleShadingEnable = VK_FALSE; multiSampleState.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; VkPipelineDynamicStateCreateInfo dynamicState = init::dynamicState(); dynamicState.dynamicStateCount = 0; VkGraphicsPipelineCreateInfo pipelineCreateInfo = init::pipelineCreateInfo(); pipelineCreateInfo.stageCount = 2; pipelineCreateInfo.pStages = shaderStages; pipelineCreateInfo.pVertexInputState = &vertexInputState; pipelineCreateInfo.pInputAssemblyState = &inputAssemblyState; pipelineCreateInfo.pRasterizationState = &rasterizationStateInfo; pipelineCreateInfo.pViewportState = &viewportState; pipelineCreateInfo.pMultisampleState = &multiSampleState; pipelineCreateInfo.pDepthStencilState = &depthStencilState; pipelineCreateInfo.pColorBlendState = &blendState; pipelineCreateInfo.pDynamicState = &dynamicState; pipelineCreateInfo.layout = m_PipelineLayout; pipelineCreateInfo.renderPass = m_Core->resources.renderPass; pipelineCreateInfo.subpass = 0; VK_CHECK(vkCreateGraphicsPipelines(m_Core->GetDevice(), VK_NULL_HANDLE, 1, &pipelineCreateInfo, nullptr, &m_GraphicsPipeline)); vkDestroyShaderModule(m_Core->GetDevice(), shaderStages[0].module, nullptr); vkDestroyShaderModule(m_Core->GetDevice(), shaderStages[1].module, nullptr); } void TestGraphicsPipeline::setCmdBuffers() { VkCommandBufferBeginInfo cmdBufferBI = init::cmdBufferBeginInfo(); VkClearValue clearValues[2]; clearValues[0].color = { 0.3f, 0.5f, 0.8f, 1.0f }; clearValues[1].depthStencil = { 1.0f, 0 }; VkRenderPassBeginInfo renderPassBI = init::renderPassBeginInfo(); renderPassBI.clearValueCount = 2; renderPassBI.pClearValues = clearValues; renderPassBI.renderArea.extent = m_Core->swapchain.extent; renderPassBI.renderArea.offset = { 0, 0 }; renderPassBI.renderPass = m_Core->resources.renderPass; for (uint32_t i = 0; i < m_Core->resources.drawCmdBuffers.size(); i++) { VK_CHECK(vkBeginCommandBuffer(m_Core->resources.drawCmdBuffers[i], &cmdBufferBI)); renderPassBI.framebuffer = m_Core->resources.frameBuffers[i]; vkCmdBeginRenderPass(m_Core->resources.drawCmdBuffers[i], &renderPassBI, VK_SUBPASS_CONTENTS_INLINE); vkCmdBindPipeline(m_Core->resources.drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, m_GraphicsPipeline); /*for(int k = 0; k < objs.size(); k++) objs[k]->draw(m_Core->resources.drawCmdBuffers[i], m_PipelineLayout);*/ vkCmdBindDescriptorSets(m_Core->resources.drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, m_PipelineLayout, 0, 1, &objs[0]->DescriptorSet, 0, nullptr); objs[0]->draw(m_Core->resources.drawCmdBuffers[i], m_PipelineLayout); vkCmdEndRenderPass(m_Core->resources.drawCmdBuffers[i]); VK_CHECK(vkEndCommandBuffer(m_Core->resources.drawCmdBuffers[i])); } } void TestGraphicsPipeline::updateUniformBuffers() { } void TestGraphicsPipeline::windowResized() { m_Core->windowResized(); vkDestroyPipeline(m_Core->GetDevice(), m_GraphicsPipeline, nullptr); vkDestroyPipelineLayout(m_Core->GetDevice(), m_PipelineLayout, nullptr); float right = m_Core->swapchain.extent.width / 200.0f; float top = m_Core->swapchain.extent.height / 200.0f; dynamic_cast<OrthographicCamera*>(m_Camera)->SetOrthograhic(-right, right, -top, top); preparePipeline(); setCmdBuffers(); } }
38.721408
158
0.77628
ilkeraktug
61b0b4e771760acb182c38aa4c3e1487b9dc399c
12,768
cpp
C++
recording/src/usb_cam/nodes/usb_cam_node.cpp
sbrodeur/CREATE-dataset
473e0555e81516139b6e70362ca0025af100158b
[ "BSD-3-Clause" ]
4
2016-09-22T18:28:21.000Z
2019-05-21T11:07:06.000Z
recording/src/usb_cam/nodes/usb_cam_node.cpp
sbrodeur/CREATE-dataset
473e0555e81516139b6e70362ca0025af100158b
[ "BSD-3-Clause" ]
40
2016-09-08T20:08:19.000Z
2016-12-22T17:38:55.000Z
recording/src/usb_cam/nodes/usb_cam_node.cpp
sbrodeur/CREATE-dataset
473e0555e81516139b6e70362ca0025af100158b
[ "BSD-3-Clause" ]
2
2016-12-28T08:22:00.000Z
2021-03-04T17:06:45.000Z
/********************************************************************* * * Software License Agreement (BSD License) * * Copyright (c) 2014, Robert Bosch LLC. * 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 Robert Bosch 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 <unistd.h> #include <ros/ros.h> #include <usb_cam/usb_cam.h> #include <image_transport/image_transport.h> #include <camera_info_manager/camera_info_manager.h> #include <sstream> #include <std_srvs/Empty.h> namespace usb_cam { static uint8_t huffman_table[] = {0xFF,0xC4,0x01,0xA2,0x00,0x00,0x01,0x05,0x01,0x01,0x01,0x01,0x01,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x01,0x00,0x03,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x10,0x00,0x02,0x01,0x03,0x03,0x02,0x04,0x03,0x05,0x05,0x04,0x04,0x00,0x00,0x01,0x7D,0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12,0x21,0x31,0x41,0x06,0x13,0x51,0x61,0x07,0x22,0x71,0x14,0x32,0x81,0x91,0xA1,0x08,0x23,0x42,0xB1,0xC1,0x15,0x52,0xD1,0xF0,0x24,0x33,0x62,0x72,0x82,0x09,0x0A,0x16,0x17,0x18,0x19,0x1A,0x25,0x26,0x27,0x28,0x29,0x2A,0x34,0x35,0x36,0x37,0x38,0x39,0x3A,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4A,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5A,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6A,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7A,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0x11,0x00,0x02,0x01,0x02,0x04,0x04,0x03,0x04,0x07,0x05,0x04,0x04,0x00,0x01,0x02,0x77,0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21,0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71,0x13,0x22,0x32,0x81,0x08,0x14,0x42,0x91,0xA1,0xB1,0xC1,0x09,0x23,0x33,0x52,0xF0,0x15,0x62,0x72,0xD1,0x0A,0x16,0x24,0x34,0xE1,0x25,0xF1,0x17,0x18,0x19,0x1A,0x26,0x27,0x28,0x29,0x2A,0x35,0x36,0x37,0x38,0x39,0x3A,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4A,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5A,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6A,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7A,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA}; class UsbCamNode { public: // private ROS node handle ros::NodeHandle node_; // shared image message sensor_msgs::Image img_; sensor_msgs::CompressedImage img_compressed_; image_transport::CameraPublisher image_pub_; ros::Publisher image_compressed_pub_; ros::Publisher cam_info_pub_; // parameters std::string video_device_name_, io_method_name_, pixel_format_name_, camera_name_, camera_info_url_; //std::string start_service_name_, start_service_name_; bool streaming_status_; bool passthrough_; int image_width_, image_height_, framerate_, exposure_, brightness_, contrast_, saturation_, sharpness_, focus_, white_balance_, gain_; bool autofocus_, autoexposure_, auto_white_balance_; boost::shared_ptr<camera_info_manager::CameraInfoManager> cinfo_; UsbCam cam_; ros::ServiceServer service_start_, service_stop_; bool service_start_cap(std_srvs::Empty::Request &req, std_srvs::Empty::Response &res ) { cam_.start_capturing(); return true; } bool service_stop_cap( std_srvs::Empty::Request &req, std_srvs::Empty::Response &res ) { cam_.stop_capturing(); return true; } UsbCamNode() : node_("~") { // grab the parameters node_.param("video_device", video_device_name_, std::string("/dev/video0")); node_.param("brightness", brightness_, -1); //0-255, -1 "leave alone" node_.param("contrast", contrast_, -1); //0-255, -1 "leave alone" node_.param("saturation", saturation_, -1); //0-255, -1 "leave alone" node_.param("sharpness", sharpness_, -1); //0-255, -1 "leave alone" // possible values: mmap, read, userptr node_.param("io_method", io_method_name_, std::string("mmap")); node_.param("image_width", image_width_, 640); node_.param("image_height", image_height_, 480); node_.param("framerate", framerate_, 30); // possible values: yuyv, uyvy, mjpeg, yuvmono10, rgb24 node_.param("pixel_format", pixel_format_name_, std::string("mjpeg")); node_.param("passthrough", passthrough_, false); // enable/disable autofocus node_.param("autofocus", autofocus_, false); node_.param("focus", focus_, -1); //0-255, -1 "leave alone" // enable/disable autoexposure node_.param("autoexposure", autoexposure_, true); node_.param("exposure", exposure_, 100); node_.param("gain", gain_, -1); //0-100?, -1 "leave alone" // enable/disable auto white balance temperature node_.param("auto_white_balance", auto_white_balance_, true); node_.param("white_balance", white_balance_, 4000); // load the camera info node_.param("camera_frame_id", img_.header.frame_id, std::string("head_camera")); node_.param("camera_name", camera_name_, std::string("head_camera")); node_.param("camera_info_url", camera_info_url_, std::string("")); cinfo_.reset(new camera_info_manager::CameraInfoManager(node_, camera_name_, camera_info_url_)); // create Publishers if (passthrough_){ image_compressed_pub_ = node_.advertise<sensor_msgs::CompressedImage>("/video/" + camera_name_ + "/compressed", 1); cam_info_pub_ = node_.advertise<sensor_msgs::CameraInfo>("/video/" + camera_name_ + "/camera_info",1); }else{ // advertise the main image topic image_transport::ImageTransport it(node_); image_pub_ = it.advertiseCamera("/video/" + camera_name_, 1); } // create Services service_start_ = node_.advertiseService("/video/" + camera_name_ + "start_capture", &UsbCamNode::service_start_cap, this); service_stop_ = node_.advertiseService("/video/" + camera_name_ + "stop_capture", &UsbCamNode::service_stop_cap, this); // check for default camera info if (!cinfo_->isCalibrated()) { cinfo_->setCameraName(video_device_name_); sensor_msgs::CameraInfo camera_info; camera_info.header.frame_id = img_.header.frame_id; camera_info.width = image_width_; camera_info.height = image_height_; cinfo_->setCameraInfo(camera_info); } ROS_INFO("Starting '%s' (%s) at %dx%d via %s (%s) at %i FPS", camera_name_.c_str(), video_device_name_.c_str(), image_width_, image_height_, io_method_name_.c_str(), pixel_format_name_.c_str(), framerate_); // set the IO method UsbCam::io_method io_method = UsbCam::io_method_from_string(io_method_name_); if(io_method == UsbCam::IO_METHOD_UNKNOWN) { ROS_FATAL("Unknown IO method '%s'", io_method_name_.c_str()); node_.shutdown(); return; } // set the pixel format UsbCam::pixel_format pixel_format = UsbCam::pixel_format_from_string(pixel_format_name_); if (pixel_format == UsbCam::PIXEL_FORMAT_UNKNOWN) { ROS_FATAL("Unknown pixel format '%s'", pixel_format_name_.c_str()); node_.shutdown(); return; } // start the camera cam_.start(video_device_name_.c_str(), io_method, pixel_format, image_width_, image_height_, framerate_); usleep(500000); // set camera parameters if (brightness_ >= 0) { cam_.set_v4l_parameter("brightness", brightness_); } if (contrast_ >= 0) { cam_.set_v4l_parameter("contrast", contrast_); } if (saturation_ >= 0) { cam_.set_v4l_parameter("saturation", saturation_); } if (sharpness_ >= 0) { cam_.set_v4l_parameter("sharpness", sharpness_); } usleep(500000); // check auto white balance if (auto_white_balance_) { cam_.set_v4l_parameter("white_balance_temperature_auto", 1); } else { cam_.set_v4l_parameter("white_balance_temperature_auto", 0); cam_.set_v4l_parameter("white_balance_temperature", white_balance_); } usleep(500000); // check auto exposure if (!autoexposure_) { // turn down exposure control (from max of 3) cam_.set_v4l_parameter("exposure_auto", 1); // change the exposure level cam_.set_v4l_parameter("exposure_absolute", exposure_); } if (gain_ >= 0) { cam_.set_v4l_parameter("gain", gain_); } // check auto focus if (autofocus_) { cam_.set_auto_focus(1); cam_.set_v4l_parameter("focus_auto", 1); } else { cam_.set_v4l_parameter("focus_auto", 0); if (focus_ >= 0) { cam_.set_v4l_parameter("focus", focus_); } } } virtual ~UsbCamNode() { cam_.shutdown(); } void mjpeg2jpeg(sensor_msgs::CompressedImage* msg){ if (msg->format != "mjpeg"){ ROS_FATAL("CompressedImage message format must be 'mjpeg', not '%s'", msg->format.c_str()); node_.shutdown(); return; } std::vector < uint8_t> frame = msg->data; uint8_t wHdr[2]; wHdr[0] = frame[0]; wHdr[1] = frame[1]; frame.erase(frame.begin(), frame.begin()+2); std::vector<uint8_t> new_frame(huffman_table, huffman_table+sizeof(huffman_table)/sizeof(uint8_t)); if(wHdr[0] == 0xFF && wHdr[1] == 0xD8){ //Header at start new_frame.insert(new_frame.begin(), wHdr, wHdr+2); //Original after Huffman table new_frame.insert(new_frame.end(), frame.begin(), frame.end()); } else{ ROS_FATAL("Incorrect header for mjpeg data"); node_.shutdown(); return; } msg->format = "jpeg"; msg->data.resize(new_frame.size()); memcpy(&(msg->data[0]), &(new_frame[0]), new_frame.size()); } bool take_and_send_image() { if (passthrough_){ // grab the image cam_.grab_image(&img_compressed_); if (pixel_format_name_ == "mjpeg"){ // convert to jpeg mjpeg2jpeg(&img_compressed_); } // grab the camera info sensor_msgs::CameraInfoPtr ci(new sensor_msgs::CameraInfo(cinfo_->getCameraInfo())); ci->header.frame_id = img_compressed_.header.frame_id; ci->header.stamp = img_compressed_.header.stamp; // publish the image image_compressed_pub_.publish(img_compressed_); cam_info_pub_.publish(*ci); }else{ // grab the image cam_.grab_image(&img_); // grab the camera info sensor_msgs::CameraInfoPtr ci(new sensor_msgs::CameraInfo(cinfo_->getCameraInfo())); ci->header.frame_id = img_.header.frame_id; ci->header.stamp = img_.header.stamp; // publish the image image_pub_.publish(img_, *ci); } return true; } bool spin() { ros::Rate loop_rate(this->framerate_); while (node_.ok()) { if (cam_.is_capturing()) { if (!take_and_send_image()) ROS_WARN("USB camera did not respond in time."); } ros::spinOnce(); loop_rate.sleep(); } return true; } }; } int main(int argc, char **argv) { ros::init(argc, argv, "usb_cam"); usb_cam::UsbCamNode a; a.spin(); return EXIT_SUCCESS; }
36.795389
2,135
0.700266
sbrodeur
61b0e9d3dd5b072e9decfba1143c5d4b9c9b8f33
3,056
cpp
C++
blades/xbmc/xbmc/utils/XSLTUtils.cpp
krattai/AEBL
a7b12c97479e1236d5370166b15ca9f29d7d4265
[ "BSD-2-Clause" ]
4
2016-04-26T03:43:54.000Z
2016-11-17T08:09:04.000Z
blades/xbmc/xbmc/utils/XSLTUtils.cpp
krattai/AEBL
a7b12c97479e1236d5370166b15ca9f29d7d4265
[ "BSD-2-Clause" ]
17
2015-01-05T21:06:22.000Z
2015-12-07T20:45:44.000Z
blades/xbmc/xbmc/utils/XSLTUtils.cpp
krattai/AEBL
a7b12c97479e1236d5370166b15ca9f29d7d4265
[ "BSD-2-Clause" ]
3
2016-04-26T03:43:55.000Z
2020-11-06T11:02:08.000Z
/* * Copyright (C) 2005-2013 Team XBMC * http://www.xbmc.org * * 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, 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 XBMC; see the file COPYING. If not, see * <http://www.gnu.org/licenses/>. * */ #include "XSLTUtils.h" #include "log.h" #include <libxslt/xslt.h> #include <libxslt/transform.h> #ifdef TARGET_WINDOWS #pragma comment(lib, "libxslt.lib") #pragma comment(lib, "libxml2.lib") #else #include <iostream> #endif #define TMP_BUF_SIZE 512 void err(void *ctx, const char *msg, ...) { char string[TMP_BUF_SIZE]; va_list arg_ptr; va_start(arg_ptr, msg); vsnprintf(string, TMP_BUF_SIZE, msg, arg_ptr); va_end(arg_ptr); CLog::Log(LOGDEBUG, "XSLT: %s", string); return; } XSLTUtils::XSLTUtils() : m_xmlInput(NULL), m_xmlStylesheet(NULL), m_xsltStylesheet(NULL) { // initialize libxslt xmlSubstituteEntitiesDefault(1); xmlLoadExtDtdDefaultValue = 0; xsltSetGenericErrorFunc(NULL, err); } XSLTUtils::~XSLTUtils() { if (m_xmlInput) xmlFreeDoc(m_xmlInput); if (m_xmlOutput) xmlFreeDoc(m_xmlOutput); if (m_xsltStylesheet) xsltFreeStylesheet(m_xsltStylesheet); } bool XSLTUtils::XSLTTransform(std::string& output) { const char *params[16+1]; params[0] = NULL; m_xmlOutput = xsltApplyStylesheet(m_xsltStylesheet, m_xmlInput, params); if (!m_xmlOutput) { CLog::Log(LOGDEBUG, "XSLT: xslt transformation failed"); return false; } xmlChar *xmlResultBuffer = NULL; int xmlResultLength = 0; int res = xsltSaveResultToString(&xmlResultBuffer, &xmlResultLength, m_xmlOutput, m_xsltStylesheet); if (res == -1) { xmlFree(xmlResultBuffer); return false; } output.append((const char *)xmlResultBuffer, xmlResultLength); xmlFree(xmlResultBuffer); return true; } bool XSLTUtils::SetInput(const std::string& input) { m_xmlInput = xmlParseMemory(input.c_str(), input.size()); if (!m_xmlInput) return false; return true; } bool XSLTUtils::SetStylesheet(const std::string& stylesheet) { if (m_xsltStylesheet) { xsltFreeStylesheet(m_xsltStylesheet); m_xsltStylesheet = NULL; } m_xmlStylesheet = xmlParseMemory(stylesheet.c_str(), stylesheet.size()); if (!m_xmlStylesheet) { CLog::Log(LOGDEBUG, "could not xmlParseMemory stylesheetdoc"); return false; } m_xsltStylesheet = xsltParseStylesheetDoc(m_xmlStylesheet); if (!m_xsltStylesheet) { CLog::Log(LOGDEBUG, "could not parse stylesheetdoc"); xmlFree(m_xmlStylesheet); m_xmlStylesheet = NULL; return false; } return true; }
25.256198
102
0.713678
krattai
61b0f2e43b3aab1d2cf090fb932a1b473a64de14
4,348
cc
C++
third_party/blink/renderer/platform/heap/gc_info.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/blink/renderer/platform/heap/gc_info.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/blink/renderer/platform/heap/gc_info.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2021-01-05T23:43:46.000Z
2021-01-07T23:36:34.000Z
// 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 "third_party/blink/renderer/platform/heap/gc_info.h" #include "base/allocator/partition_allocator/page_allocator.h" #include "base/bits.h" #include "third_party/blink/renderer/platform/heap/heap.h" #include "third_party/blink/renderer/platform/wtf/std_lib_extras.h" namespace blink { namespace { constexpr size_t kEntrySize = sizeof(GCInfo*); // Allocation and resizing are built around the following invariants. static_assert(base::bits::IsPowerOfTwo(kEntrySize), "GCInfoTable entries size must be power of " "two"); static_assert( 0 == base::kPageAllocationGranularity % base::kSystemPageSize, "System page size must be a multiple of page page allocation granularity"); constexpr size_t ComputeInitialTableLimit() { // (Light) experimentation suggests that Blink doesn't need more than this // while handling content on popular web properties. constexpr size_t kInitialWantedLimit = 512; // Different OSes have different page sizes, so we have to choose the minimum // of memory wanted and OS page size. constexpr size_t memory_wanted = kInitialWantedLimit * kEntrySize; return base::RoundUpToPageAllocationGranularity(memory_wanted) / kEntrySize; } constexpr size_t MaxTableSize() { constexpr size_t kMaxTableSize = base::RoundUpToPageAllocationGranularity( GCInfoTable::kMaxIndex * kEntrySize); return kMaxTableSize; } } // namespace GCInfoTable* GCInfoTable::global_table_ = nullptr; constexpr GCInfoIndex GCInfoTable::kMaxIndex; constexpr GCInfoIndex GCInfoTable::kMinIndex; void GCInfoTable::CreateGlobalTable() { DEFINE_STATIC_LOCAL(GCInfoTable, table, ()); global_table_ = &table; } GCInfoIndex GCInfoTable::EnsureGCInfoIndex( const GCInfo* gc_info, std::atomic<GCInfoIndex>* gc_info_index_slot) { DCHECK(gc_info); DCHECK(gc_info_index_slot); // Ensuring a new index involves current index adjustment as well as // potentially resizing the table. For simplicity we use a lock. MutexLocker locker(table_mutex_); // If more than one thread ends up allocating a slot for the same GCInfo, have // later threads reuse the slot allocated by the first. GCInfoIndex gc_info_index = gc_info_index_slot->load(std::memory_order_relaxed); if (gc_info_index) return gc_info_index; if (current_index_ == limit_) Resize(); gc_info_index = current_index_++; CHECK_LT(gc_info_index, GCInfoTable::kMaxIndex); table_[gc_info_index] = gc_info; gc_info_index_slot->store(gc_info_index, std::memory_order_release); return gc_info_index; } void GCInfoTable::Resize() { const GCInfoIndex new_limit = (limit_) ? 2 * limit_ : ComputeInitialTableLimit(); CHECK_GT(new_limit, limit_); const size_t old_committed_size = limit_ * kEntrySize; const size_t new_committed_size = new_limit * kEntrySize; CHECK(table_); CHECK_EQ(0u, new_committed_size % base::kPageAllocationGranularity); CHECK_GE(MaxTableSize(), limit_ * kEntrySize); // Recommitting and zapping assumes byte-addressable storage. uint8_t* const current_table_end = reinterpret_cast<uint8_t*>(table_) + old_committed_size; const size_t table_size_delta = new_committed_size - old_committed_size; // Commit the new size and allow read/write. // TODO(ajwong): SetSystemPagesAccess should be part of RecommitSystemPages to // avoid having two calls here. base::SetSystemPagesAccess(current_table_end, table_size_delta, base::PageReadWrite); bool ok = base::RecommitSystemPages(current_table_end, table_size_delta, base::PageReadWrite); CHECK(ok); #if DCHECK_IS_ON() // Check that newly-committed memory is zero-initialized. for (size_t i = 0; i < (table_size_delta / sizeof(uintptr_t)); ++i) { DCHECK(!reinterpret_cast<uintptr_t*>(current_table_end)[i]); } #endif // DCHECK_IS_ON() limit_ = new_limit; } GCInfoTable::GCInfoTable() { table_ = reinterpret_cast<GCInfo const**>(base::AllocPages( nullptr, MaxTableSize(), base::kPageAllocationGranularity, base::PageInaccessible, base::PageTag::kBlinkGC)); CHECK(table_); Resize(); } } // namespace blink
34.784
80
0.74494
sarang-apps
ba07e237bdc1645b33b7729ac0032c2c33ec3b2b
3,593
cpp
C++
projects/elevator/elevator.cpp
ab1aw/stm32f4-bare-metal
8ba0c6f5d51834c35b1262a2e0a5e5a4858d4391
[ "MIT" ]
null
null
null
projects/elevator/elevator.cpp
ab1aw/stm32f4-bare-metal
8ba0c6f5d51834c35b1262a2e0a5e5a4858d4391
[ "MIT" ]
null
null
null
projects/elevator/elevator.cpp
ab1aw/stm32f4-bare-metal
8ba0c6f5d51834c35b1262a2e0a5e5a4858d4391
[ "MIT" ]
1
2020-12-13T14:58:44.000Z
2020-12-13T14:58:44.000Z
#include <tinyfsm.hpp> #include "elevator.hpp" #include "fsmlist.hpp" #include "uart.h" class Idle; // forward declaration // ---------------------------------------------------------------------------- // Transition functions // static void CallMaintenance() { brand.data = (uint8_t *)"*** calling maintenance ***\n\r"; brand.data_len = sizeof("*** calling maintenance ***\n\r"); tx_complete = 0; bufpos = 0; // enable usart2 tx interrupt USART2->CR1 |= (1 << 7); while(tx_complete == 0) { flash(LEDDELAY1); } } static void CallFirefighters() { brand.data = (uint8_t *)"*** calling firefighters ***\n\r"; brand.data_len = sizeof("*** calling firefighters ***\n\r"); tx_complete = 0; bufpos = 0; // enable usart2 tx interrupt USART2->CR1 |= (1 << 7); while(tx_complete == 0) { flash(LEDDELAY1); } } // ---------------------------------------------------------------------------- // State: Panic // class Panic : public Elevator { void entry() override { send_event(MotorStop()); } }; // ---------------------------------------------------------------------------- // State: Moving // class Moving : public Elevator { void react(FloorSensor const & e) override { int floor_expected = current_floor + Motor::getDirection(); if(floor_expected != e.floor) { brand.data = (uint8_t *)"Floor sensor defect\n\r"; brand.data_len = sizeof("Floor sensor defect\n\r"); tx_complete = 0; bufpos = 0; // enable usart2 tx interrupt USART2->CR1 |= (1 << 7); while(tx_complete == 0) { flash(LEDDELAY1); } transit<Panic>(CallMaintenance); } else { brand.data = (uint8_t *)"Reached floor\n\r"; brand.data_len = sizeof("Reached floor\n\r"); tx_complete = 0; bufpos = 0; // enable usart2 tx interrupt USART2->CR1 |= (1 << 7); while(tx_complete == 0) { flash(LEDDELAY1); } current_floor = e.floor; if(e.floor == dest_floor) transit<Idle>(); } }; }; // ---------------------------------------------------------------------------- // State: Idle // class Idle : public Elevator { void entry() override { send_event(MotorStop()); } void react(Call const & e) override { dest_floor = e.floor; if(dest_floor == current_floor) return; /* lambda function used for transition action */ auto action = [] { if(dest_floor > current_floor) send_event(MotorUp()); else if(dest_floor < current_floor) send_event(MotorDown()); }; transit<Moving>(action); }; }; // ---------------------------------------------------------------------------- // Base state: default implementations // void Elevator::react(Call const &) { brand.data = (uint8_t *)"Call event ignored\n\r"; brand.data_len = sizeof("Call event ignored\n\r"); tx_complete = 0; bufpos = 0; // enable usart2 tx interrupt USART2->CR1 |= (1 << 7); while(tx_complete == 0) { flash(LEDDELAY1); } } void Elevator::react(FloorSensor const &) { brand.data = (uint8_t *)"FloorSensor event ignored\n\r"; brand.data_len = sizeof("FloorSensor event ignored\n\r"); tx_complete = 0; bufpos = 0; // enable usart2 tx interrupt USART2->CR1 |= (1 << 7); while(tx_complete == 0) { flash(LEDDELAY1); } } void Elevator::react(Alarm const &) { transit<Panic>(CallFirefighters); } int Elevator::current_floor = Elevator::initial_floor; int Elevator::dest_floor = Elevator::initial_floor; // ---------------------------------------------------------------------------- // Initial state definition // FSM_INITIAL_STATE(Elevator, Idle)
20.531429
79
0.550515
ab1aw
ba09123bc1b306dc12617c6c4571342407d97fb0
10,248
cc
C++
bench/qu8-vaddc.cc
mcx/XNNPACK
4aa243068e71f1064e8db37f6240e4c85f1f5314
[ "BSD-3-Clause" ]
null
null
null
bench/qu8-vaddc.cc
mcx/XNNPACK
4aa243068e71f1064e8db37f6240e4c85f1f5314
[ "BSD-3-Clause" ]
null
null
null
bench/qu8-vaddc.cc
mcx/XNNPACK
4aa243068e71f1064e8db37f6240e4c85f1f5314
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2021 Google LLC // // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. #include <algorithm> #include <cmath> #include <functional> #include <random> #include <vector> #include <benchmark/benchmark.h> #include "bench/utils.h" #include <xnnpack/aligned-allocator.h> #include <xnnpack/common.h> #include <xnnpack/params.h> #include <xnnpack/params-init.h> #include <xnnpack/vaddsub.h> static void qu8_vaddc( benchmark::State& state, xnn_qu8_vaddsub_minmax_ukernel_function vaddc, xnn_init_qu8_addsub_minmax_params_fn init_params, benchmark::utils::IsaCheckFunction isa_check = nullptr) { if (isa_check && !isa_check(state)) { return; } const size_t num_elements = state.range(0); std::random_device random_device; auto rng = std::mt19937(random_device()); auto u8rng = std::bind( std::uniform_int_distribution<uint32_t>(std::numeric_limits<uint8_t>::min(), std::numeric_limits<uint8_t>::max()), std::ref(rng)); std::vector<uint8_t, AlignedAllocator<uint8_t, 64>> a(num_elements); std::vector<uint8_t, AlignedAllocator<uint8_t, 64>> sum(num_elements); std::generate(a.begin(), a.end(), std::ref(u8rng)); const uint8_t b = u8rng(); union xnn_qu8_addsub_minmax_params params; init_params(&params, 127 /* a zero point */, 127 /* b zero point */, 127 /* output zero point */, 0.5f /* a-output scale */, 0.75f /* b-output scale */, std::numeric_limits<uint8_t>::min() + 1, std::numeric_limits<uint8_t>::max() - 1); for (auto _ : state) { vaddc(num_elements * sizeof(uint8_t), a.data(), &b, sum.data(), &params); } const uint64_t cpu_frequency = benchmark::utils::GetCurrentCpuFrequency(); if (cpu_frequency != 0) { state.counters["cpufreq"] = cpu_frequency; } const size_t num_elements_per_iteration = num_elements; state.counters["num_elements"] = benchmark::Counter(uint64_t(state.iterations()) * num_elements_per_iteration, benchmark::Counter::kIsRate); const size_t bytes_per_iteration = 2 * num_elements * sizeof(int8_t); state.counters["bytes"] = benchmark::Counter(uint64_t(state.iterations()) * bytes_per_iteration, benchmark::Counter::kIsRate); } #if XNN_ARCH_ARM || XNN_ARCH_ARM64 BENCHMARK_CAPTURE(qu8_vaddc, neon_ld64_x8, xnn_qu8_vaddc_minmax_ukernel__neon_ld64_x8, xnn_init_qu8_add_minmax_neon_params, benchmark::utils::CheckNEON) ->Apply(benchmark::utils::UnaryElementwiseParameters<uint8_t, uint8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qu8_vaddc, neon_ld64_x16, xnn_qu8_vaddc_minmax_ukernel__neon_ld64_x16, xnn_init_qu8_add_minmax_neon_params, benchmark::utils::CheckNEON) ->Apply(benchmark::utils::UnaryElementwiseParameters<uint8_t, uint8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qu8_vaddc, neon_ld64_x32, xnn_qu8_vaddc_minmax_ukernel__neon_ld64_x32, xnn_init_qu8_add_minmax_neon_params, benchmark::utils::CheckNEON) ->Apply(benchmark::utils::UnaryElementwiseParameters<uint8_t, uint8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qu8_vaddc, neon_ld128_x16, xnn_qu8_vaddc_minmax_ukernel__neon_ld128_x16, xnn_init_qu8_add_minmax_neon_params, benchmark::utils::CheckNEON) ->Apply(benchmark::utils::UnaryElementwiseParameters<uint8_t, uint8_t>) ->UseRealTime(); #endif // XNN_ARCH_ARM || XNN_ARCH_ARM64 #if XNN_ARCH_X86 || XNN_ARCH_X86_64 BENCHMARK_CAPTURE(qu8_vaddc, avx512skx_mul32_ld128_x16, xnn_qu8_vaddc_minmax_ukernel__avx512skx_mul32_ld128_x16, xnn_init_qu8_add_minmax_avx512_params, benchmark::utils::CheckAVX512SKX) ->Apply(benchmark::utils::UnaryElementwiseParameters<uint8_t, uint8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qu8_vaddc, avx512skx_mul32_ld128_x32, xnn_qu8_vaddc_minmax_ukernel__avx512skx_mul32_ld128_x32, xnn_init_qu8_add_minmax_avx512_params, benchmark::utils::CheckAVX512SKX) ->Apply(benchmark::utils::UnaryElementwiseParameters<uint8_t, uint8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qu8_vaddc, avx2_mul32_ld64_x8, xnn_qu8_vaddc_minmax_ukernel__avx2_mul32_ld64_x8, xnn_init_qu8_add_minmax_avx2_params, benchmark::utils::CheckAVX2) ->Apply(benchmark::utils::UnaryElementwiseParameters<uint8_t, uint8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qu8_vaddc, avx2_mul32_ld64_x16, xnn_qu8_vaddc_minmax_ukernel__avx2_mul32_ld64_x16, xnn_init_qu8_add_minmax_avx2_params, benchmark::utils::CheckAVX2) ->Apply(benchmark::utils::UnaryElementwiseParameters<uint8_t, uint8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qu8_vaddc, xop_mul32_ld32_x8, xnn_qu8_vaddc_minmax_ukernel__xop_mul32_ld32_x8, xnn_init_qu8_add_minmax_sse4_params, benchmark::utils::CheckXOP) ->Apply(benchmark::utils::UnaryElementwiseParameters<uint8_t, uint8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qu8_vaddc, xop_mul32_ld32_x16, xnn_qu8_vaddc_minmax_ukernel__xop_mul32_ld32_x16, xnn_init_qu8_add_minmax_sse4_params, benchmark::utils::CheckXOP) ->Apply(benchmark::utils::UnaryElementwiseParameters<uint8_t, uint8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qu8_vaddc, avx_mul16_ld64_x8, xnn_qu8_vaddc_minmax_ukernel__avx_mul16_ld64_x8, xnn_init_qu8_add_minmax_sse2_params, benchmark::utils::CheckAVX) ->Apply(benchmark::utils::UnaryElementwiseParameters<uint8_t, uint8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qu8_vaddc, avx_mul16_ld64_x16, xnn_qu8_vaddc_minmax_ukernel__avx_mul16_ld64_x16, xnn_init_qu8_add_minmax_sse2_params, benchmark::utils::CheckAVX) ->Apply(benchmark::utils::UnaryElementwiseParameters<uint8_t, uint8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qu8_vaddc, avx_mul32_ld32_x8, xnn_qu8_vaddc_minmax_ukernel__avx_mul32_ld32_x8, xnn_init_qu8_add_minmax_sse4_params, benchmark::utils::CheckAVX) ->Apply(benchmark::utils::UnaryElementwiseParameters<uint8_t, uint8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qu8_vaddc, avx_mul32_ld32_x16, xnn_qu8_vaddc_minmax_ukernel__avx_mul32_ld32_x16, xnn_init_qu8_add_minmax_sse4_params, benchmark::utils::CheckAVX) ->Apply(benchmark::utils::UnaryElementwiseParameters<uint8_t, uint8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qu8_vaddc, sse41_mul16_ld64_x8, xnn_qu8_vaddc_minmax_ukernel__sse41_mul16_ld64_x8, xnn_init_qu8_add_minmax_sse2_params, benchmark::utils::CheckSSE41) ->Apply(benchmark::utils::UnaryElementwiseParameters<uint8_t, uint8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qu8_vaddc, sse41_mul16_ld64_x16, xnn_qu8_vaddc_minmax_ukernel__sse41_mul16_ld64_x16, xnn_init_qu8_add_minmax_sse2_params, benchmark::utils::CheckSSE41) ->Apply(benchmark::utils::UnaryElementwiseParameters<uint8_t, uint8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qu8_vaddc, sse41_mul32_ld32_x8, xnn_qu8_vaddc_minmax_ukernel__sse41_mul32_ld32_x8, xnn_init_qu8_add_minmax_sse4_params, benchmark::utils::CheckSSE41) ->Apply(benchmark::utils::UnaryElementwiseParameters<uint8_t, uint8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qu8_vaddc, sse41_mul32_ld32_x16, xnn_qu8_vaddc_minmax_ukernel__sse41_mul32_ld32_x16, xnn_init_qu8_add_minmax_sse4_params, benchmark::utils::CheckSSE41) ->Apply(benchmark::utils::UnaryElementwiseParameters<uint8_t, uint8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qu8_vaddc, sse2_mul16_ld64_x8, xnn_qu8_vaddc_minmax_ukernel__sse2_mul16_ld64_x8, xnn_init_qu8_add_minmax_sse2_params) ->Apply(benchmark::utils::UnaryElementwiseParameters<uint8_t, uint8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qu8_vaddc, sse2_mul16_ld64_x16, xnn_qu8_vaddc_minmax_ukernel__sse2_mul16_ld64_x16, xnn_init_qu8_add_minmax_sse2_params) ->Apply(benchmark::utils::UnaryElementwiseParameters<uint8_t, uint8_t>) ->UseRealTime(); #endif // XNN_ARCH_X86 || XNN_ARCH_X86_64 #if XNN_ARCH_WASMSIMD || XNN_ARCH_WASMRELAXEDSIMD BENCHMARK_CAPTURE(qu8_vaddc, wasmsimd_x8, xnn_qu8_vaddc_minmax_ukernel__wasmsimd_x8, xnn_init_qu8_add_minmax_wasmsimd_params) ->Apply(benchmark::utils::UnaryElementwiseParameters<uint8_t, uint8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qu8_vaddc, wasmsimd_x16, xnn_qu8_vaddc_minmax_ukernel__wasmsimd_x16, xnn_init_qu8_add_minmax_wasmsimd_params) ->Apply(benchmark::utils::UnaryElementwiseParameters<uint8_t, uint8_t>) ->UseRealTime(); #endif // XNN_ARCH_WASMSIMD || XNN_ARCH_WASMRELAXEDSIMD BENCHMARK_CAPTURE(qu8_vaddc, scalar_x1, xnn_qu8_vaddc_minmax_ukernel__scalar_x1, xnn_init_qu8_add_minmax_scalar_params) ->Apply(benchmark::utils::UnaryElementwiseParameters<uint8_t, uint8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qu8_vaddc, scalar_x2, xnn_qu8_vaddc_minmax_ukernel__scalar_x2, xnn_init_qu8_add_minmax_scalar_params) ->Apply(benchmark::utils::UnaryElementwiseParameters<uint8_t, uint8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qu8_vaddc, scalar_x4, xnn_qu8_vaddc_minmax_ukernel__scalar_x4, xnn_init_qu8_add_minmax_scalar_params) ->Apply(benchmark::utils::UnaryElementwiseParameters<uint8_t, uint8_t>) ->UseRealTime(); #ifndef XNNPACK_BENCHMARK_NO_MAIN BENCHMARK_MAIN(); #endif
44.172414
118
0.697697
mcx
ba093a884d374251fff14944aaa3654721f98eac
55,512
cpp
C++
microCluster/adc.cpp
zakimjz/TriCluster
8c30203e1491bb6b0b3d28889e172575aacb9993
[ "Apache-2.0" ]
null
null
null
microCluster/adc.cpp
zakimjz/TriCluster
8c30203e1491bb6b0b3d28889e172575aacb9993
[ "Apache-2.0" ]
null
null
null
microCluster/adc.cpp
zakimjz/TriCluster
8c30203e1491bb6b0b3d28889e172575aacb9993
[ "Apache-2.0" ]
null
null
null
#include <math.h> #include <cstdlib> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <algorithm> #include <set> #include <vector> #include <map> #include "timeutil.h" using namespace std; char rowName[100000][30]; char colName[100000][30]; bool showColName=false; bool showRowName=false; template <class T> inline void Copy(T& s1, T& s2){ s2.clear(); copy( s1.begin(), s1.end(), insert_iterator<T>(s2, s2.begin())); } template <class T> inline void Intersect(T& s1, T &s2, T& r){ T tmp; set_intersection( s1.begin(), s1.end(), s2.begin(), s2.end(), insert_iterator<T> (tmp, tmp.begin())); Copy( tmp, r ); tmp.clear(); } template <class T> inline void Union(T& s1, T &s2, T& r){ T tmp; set_union( s1.begin(), s1.end(), s2.begin(), s2.end(), insert_iterator<T> (tmp, tmp.begin())); Copy( tmp, r ); tmp.clear(); } template <class T> void rd(int fd, T* x, int num) { int bytes; bytes = read(fd, x, num*sizeof(T)); if( bytes != num*sizeof(T) ) { cout << "error file format" << endl; exit(1); } } class Array2D { int width, height; float* data; public: void init(int w, int h) { width = w; height = h; data = new float[width * height]; if( data == NULL ) { cout << "Too large data volume to be load in to the memory" << endl; exit(1); } } float& operator()(int x, int y) { return data[y*width + x]; } float* operator()(int line) { return( data + line*width ); } void clear() { delete( data ); } }; struct Edge; typedef set<int, less<int> > Transet; typedef Transet::iterator TransetIt; typedef vector<Edge> Edges; typedef Edges::iterator EdgesIt; #define Attrset Transet #define AttrsetIt TransetIt #define EDGE(i, j) edgesMatrix[i*width+j] typedef vector<float> Ivn; // InvalidValue typedef vector<float>::iterator IvnIt; vector<Transet> *edgesMatrix; class Cluster{ public: Transet T; Attrset A; bool deleted; Cluster(){ deleted = false; } bool ColEqual( float delta, Array2D& array ) { float ave = 0.0; float sum = 0.0; TransetIt tit; AttrsetIt ait; if( delta < 0 ) return true; for( ait=A.begin(); ait!=A.end(); ait++ ){ ave = 0.0; for(tit=T.begin(); tit!=T.end(); tit++) ave += array(*ait, *tit); ave /= T.size(); ///////////////////////////////// sum = 0.0; for(tit=T.begin(); tit!=T.end(); tit++) sum += fabs( array(*ait, *tit) - ave ); sum /= T.size(); if( sum > delta ) return false; } return true; } bool RowEqual( float delta, Array2D& array ) { float ave = 0.0; float sum = 0.0; TransetIt tit; AttrsetIt ait; if( delta < 0 ) return true; for( tit=T.begin(); tit!=T.end(); tit++ ){ ave = 0.0; for(ait=A.begin(); ait!=A.end(); ait++) ave += array(*ait, *tit); ave /= A.size(); ///////////////////////////////// sum = 0.0; for(ait=A.begin(); ait!=A.end(); ait++) sum += fabs( array(*ait, *tit) - ave ); sum /= A.size(); if( sum > delta ) return false; } return true; } bool contain( Cluster c ){ Transet U; int x; if( T.size() < c.T.size() || A.size() < c.A.size() ) return false; Union( T, c.T, U ); if( U.size() > T.size() ) return false; Union( A, c.A, U ); if( U.size() > A.size() ) return false; return true; } bool ContainPoint( int t, int a ) { if( t != *find(T.begin(), T.end(), t) ) return false; if( a != *find(A.begin(), A.end(), a) ) return false; return true; } int elementNum(void) { return T.size() * A.size(); } void show(Array2D &data){ TransetIt it, it1; int k; cout << "width x height: " << A.size() << " x " << T.size() << endl; for(it=A.begin(), k=0; it!=A.end(); it++){ if( k++%20 == 0 ){ cout << endl << " "; if(showColName) cout << endl << " "; } if(showColName){ printf( "%8s", colName[*it] ); } else printf( "%4d ", *it ); } cout << endl; for(it=T.begin(), k=0; it!=T.end(); it++){ if(showRowName) printf( "%30s\t", rowName[*it] ); else printf( "%4d ", *it ); for(it1=A.begin(), k=0; it1!=A.end(); it1++){ if( k++%20 == 0 && k != 1 ) cout << endl << " "; printf( "%6.2f ", data(*it1, *it)); } cout << endl; } } }; inline void TranSub(Transet s1, Transet &s2){ TransetIt it; for(it=s2.begin(); it!=s2.end(); it++) s1.erase( find(s1.begin(), s1.end(), *it) ); } class Clusters { int width; public: vector<Cluster> CVec; bool contain( Cluster &c ){ vector<Cluster>::iterator it; for(it=CVec.begin(); it!=CVec.end(); it++) if(it->contain(c)) return true; return false; } void del_becontained( Cluster &c ){ vector<Cluster>::iterator it; it = CVec.begin(); while( it != CVec.end() ){ if( c.contain(*it) ){ it->A.clear(); it->T.clear(); it = CVec.erase(it); //it=CVec.begin(); } else it++; } } void show(Array2D &data){ vector<Cluster>::iterator it; int i=1; cout << endl <<"=========================== Clusters =========================" << endl; for(it=CVec.begin(); it!=CVec.end(); it++) if( !it->deleted ){ cout << endl << "Cluster " << i++ <<": "; it->show(data); } } int validNum(){ int num=0; vector<Cluster>::iterator it; for(it=CVec.begin(); it!=CVec.end(); it++) if( !it->deleted ) num++; return num; } void showQuality(Array2D& array){ vector<Cluster>::iterator it; TransetIt tit; AttrsetIt ait; int eSum, cNum, eCover; double Fluctuation, clusFluc, rowFluc, rowAve; map<int, int> Cover; cout << endl << "==================== Quality ====================" << endl; cNum = 0; eSum = 0; Fluctuation = 0.0; for(it=CVec.begin(); it!=CVec.end(); it++) if( !it->deleted ){ cNum++; eSum += it->elementNum(); for(ait=it->A.begin(); ait!=it->A.end(); ait++) for(tit=it->T.begin(); tit!=it->T.end(); tit++) Cover[(*tit) * width + (*ait)] = 1; //Cover[(*tit)*array.width + (*ait)] = 1; clusFluc = 0.0; for(tit=it->T.begin(); tit!=it->T.end(); tit++){ ///////////////////////////////// rowAve = 0.0; for(ait=it->A.begin(); ait!=it->A.end(); ait++) rowAve += array(*ait, *tit); rowAve /= it->A.size(); ///////////////////////////////// rowFluc = 0.0; for(ait=it->A.begin(); ait!=it->A.end(); ait++) rowFluc += fabs( array(*ait, *tit) - rowAve ); rowFluc /= it->A.size(); if( rowAve > 0.0000000001 ) rowFluc /= rowAve; // percentage ///////////////////////////////// clusFluc += rowFluc; } clusFluc /= it->T.size(); Fluctuation += clusFluc * it->elementNum(); } Fluctuation /= eSum; eCover = Cover.size(); Cover.clear(); cout << "Clusters#:\t" << cNum << endl << endl; if(cNum !=0 ){ cout << "Elements#:\t" << eSum << endl; cout << "Ave Elements#:\t" << eSum / cNum << endl << endl; cout << "Cover: \t" << eCover << endl; cout << "Ave Cover:\t" << eCover / cNum << endl << endl; printf( "Overlap%%:\t%2.2f%\n\n", double(eSum-eCover) / eCover * 100.0 ); printf( "Fluctuation:\t%2.2f%\n\n", Fluctuation*100.0 ); } } void EXPAND( Cluster C, Attrset P, int minW, int minH, float deltaR, float deltaC, Array2D& array); void getClusters( int minW, int minH, int w, float deltaR, float deltaC, Array2D& array); void delet( float overlaped ); void merge( float overlaped ); }; void Clusters::EXPAND( Cluster C, Attrset P, int minW, int minH, float deltaR, float deltaC, Array2D& array) { int x, y; Cluster C1; vector<Transet>::iterator it; AttrsetIt it1; vector<Cluster>::iterator cit; bool new_clus; if( C.A.size() >= minW && C.T.size() >= minH ){ /* cout << "A set: "; cout << C.A << endl; cout << "T set: "; cout << C.T << endl; */ if( C.RowEqual(deltaR, array) && C.ColEqual(deltaC, array) ){ if( !contain(C)){ del_becontained( C ); CVec.push_back(C); } } } while( !P.empty() ){ x = *(P.begin()); C1 = C; C1.A.insert(x); P.erase(x); ////////////////////////////////////////////// if( C.A.empty() ){ cout << "Processing Attribute: " << x << endl; EXPAND( C1, P, minW, minH, deltaR, deltaC, array ); // first time } else{ //y = *(C.A.begin()); it1 = C.A.end(); it1--; y = *it1; for(it=EDGE(y,x).begin(); it!=EDGE(y,x).end(); it++){ // continue to extend if( C.A.size() == 1 ) // at the beginning Copy( *it, C1.T ); else Intersect( C.T, *it, C1.T ); if( C1.T.size() >= minH ) EXPAND( C1, P, minW, minH, deltaR, deltaC, array ); } } ////////////////////////////////////////////// } } void Clusters::getClusters( int minW, int minH, int w, float deltaR, float deltaC, Array2D& array ) { Cluster C; Attrset P; int Edges=0; width = w; for(int i=0; i<width; i++) for(int j=0; j<width; j++) Edges += EDGE(i,j).size(); cout << "Got " << Edges << " edges, Average edges: " << Edges/(width*width) << endl; for( int i=0; i<width; i++ ) P.insert(i); EXPAND( C, P, minW, minH, deltaR, deltaC, array); } void Clusters::delet( float overlaped ) { vector<Cluster>::iterator it1, it2, it3; TransetIt tit; AttrsetIt ait; int in, total; for( it1=CVec.begin(); it1!=CVec.end(); it1++ ){ in = 0; total= 0; for( tit=it1->T.begin(); tit!=it1->T.end(); tit++) for( ait=it1->A.begin(); ait!=it1->A.end(); ait++){ // loop every point for( it2=CVec.begin(); it2!=CVec.end(); it2++) if( it1 != it2 && ! it2->deleted ){ if( it2->ContainPoint(*tit, *ait)){ in++; break; } } total++; } //cout << "in: " << in << ", total: " << total << endl; if( (double)in / total >= overlaped ){ it1->deleted = true; } } } void Clusters::merge( float overlaped ) // column share will be achieved by shrinking columns/ increasing rows. { vector<Cluster>::iterator it1, it2, it3; Transet TU; Attrset AU; TransetIt tit; AttrsetIt ait; Cluster mycluster; bool noMerge; int in, total; start: noMerge = true; it3 = CVec.end(); for( it1=CVec.begin(); it1!=it3; it1++) for( it2=it1, ++it2; it2!=it3; it2++) if( !it1->deleted && !it2->deleted ){ in = 0; total = 0; Intersect( it1->A, it2->A, AU ); //cout << AU.size() << " " << it1->A.size() << " " << it2->A.size() << endl; if( AU.size() < (it1->A.size() + it2->A.size()) / 3 ) continue; Intersect( it1->T, it2->T, TU ); if( TU.size() == 0 ) continue; Union( it1->T, it2->T, TU ); Union( it1->A, it2->A, AU ); for( tit=TU.begin(); tit!=TU.end(); tit++) for( ait=AU.begin(); ait!=AU.end(); ait++){ // loop every point if( it2->ContainPoint(*tit, *ait) || it1->ContainPoint(*tit, *ait) ) in++; total++; } //cout << "in: " << in << ", total: " << total << endl; if( (double)in / total >= overlaped ){ Copy( TU, mycluster.T ); Copy( AU, mycluster.A ); it1->deleted = true; it2->deleted = true; CVec.push_back( mycluster ); noMerge = false; } } if( !noMerge ){ //cout << "go start" << endl; goto start; } } class Ranges { string file; float max_value; vector<Transet> *pM; public: Array2D array; int width, height; Ranges(char* name) { file = name; } void GetStr2Tab( int &pos, int len, char *str, char*sub ){ int p=0; while( str[pos]!= '\t' && pos < len ){ if( str[pos] != 0 ){ sub[p] = str[pos]; p++; } pos++; } sub[p] = '\0'; while( str[pos] == '\t' ) pos++; assert( p < 1000 ); assert( len < 100000 ); } void GetTabFileSize( bool show ){ char buf[100000], sub[1000]; float cell; int w, h, len, k, w1; ifstream in; in.open(file.c_str()); w = h = 0; in.getline(buf, 100000, '\n'); len = strlen(buf); k = 0; while( k < len ){ GetStr2Tab( k, len, buf, sub ); if(show) cout << sub << '\t'; w++; } if(show) cout << endl; w -= 2; // if(show) cout << "width: " << w << endl; in.getline(buf, 100000, '\n'); do{ int tmp=0; for(int i=0; i<strlen(buf); i++){ if( buf[i] == '\t' ) tmp++; } //cout << endl << "tab number: " << tmp << endl; len = strlen(buf); k = 0; GetStr2Tab( k, len, buf, sub ); if(show) cout << sub; // ID GetStr2Tab( k, len, buf, sub ); if(show) cout << '\t' << sub; // NAME if( strlen(sub) == 0 ) break; h++; w1 = 0; while( k < len ){ GetStr2Tab( k, len, buf, sub ); if(show) cout << '\t' << sub; w1++; if( sub[0] == ' ' ){ for(int i=1; i<strlen(sub); i++) if( sub[i] != ' ' ){ cout << endl << "error input file, row: " << h << " not a blank" << endl; exit(0); } } else if( isdigit( sub[0]) || sub[0] == '-' ){ for(int i=1; i<strlen(sub); i++) if( !isdigit(sub[i]) && sub[i]!='.' ){ cout << endl << "error input file, row: " << h << " not a number" << endl; exit(0); } } else{ cout << endl << "error input file, row: " << h << " first character: " << sub[0]; printf( ", i.e. 0x%x\n", sub[0] ); exit(0); } if(show) cout << "\t" << sub; } if(show) cout << endl; if( w1 < w ){ cout << endl << "error input file, row: " << h << " col: " << w1 << " missing data" << endl; exit(0); } if( w1 > w ){ cout << endl << "error input file, row: " << h << " col: " << w1 << " extra data" << endl; exit(0); } in.getline(buf, 100000, '\n'); }while( !in.eof() ); width = w; height = h; in.close(); cout << endl << "width: " << w << endl; cout << "height: " << h << endl; } ///////////////////////////////////////// void ReadTabFile(){ char buf[100000], sub[1000]; int len, k; ifstream in; array.init( width, height ); in.open(file.c_str()); in.getline(buf, 100000, '\n'); len = strlen(buf); k=0; GetStr2Tab( k, len, buf, sub ); // ID GetStr2Tab( k, len, buf, sub ); // NAME for(int i=0; i<width; i++){ GetStr2Tab( k, len, buf, sub ); assert( strlen(sub) <=30 ); strcpy( colName[i], sub ); } for(int j=0; j<height; j++){ in.getline(buf, 100000, '\n'); len = strlen(buf); k=0; GetStr2Tab( k, len, buf, sub ); // ID GetStr2Tab( k, len, buf, sub ); // NAME assert( strlen(sub) <=30 ); strcpy( rowName[j], sub ); for(int i=0; i<width; i++){ GetStr2Tab( k, len, buf, sub ); if( sub[0] == ' ' ) array(i,j) = -1.0; // no value there else array(i,j) = atof( sub ); if( array(i,j) > max_value ) max_value = array(i,j); } } in.close(); edgesMatrix = new vector<Transet> [width*width]; } void Readfile(){ int fd, value; fd = open( file.c_str(), O_RDONLY ); rd( fd, (int *)&height, 1 ); rd( fd, (int *)&width, 1 ); array.init( width, height ); rd( fd, array(0), width ); // skip the scope of each attribute max_value = array(0, 0); for(int i=0; i< height; i++) { rd(fd, (int *)&value, 1); rd(fd, array(i), width); rd(fd, (int *)&value, 1); } close(fd); edgesMatrix = new vector<Transet> [width*width]; } void clear(){ array.clear(); for(int i=0; i<width*width; i++) edgesMatrix[i].clear(); delete[] edgesMatrix; } void showData(){ cout << "width: " << width << ", height: " << height << endl; cout << " "; for(int i=0; i<width; i++) printf( "%6d ", i ); cout << endl; for(int j=0; j<height; j++) { printf( "%6d ", j ); for(int i=0; i<width; i++) printf( "%6.2f ", array(i,j) ); cout << endl; } } void getRanges( float winsz, int minH, bool extend, Ivn &ivn, bool onlyRatioOne ); void showRanges(); }; struct attVecCell{ float val; int trans; }; struct attVec_less{ bool operator()(attVecCell c1, attVecCell c2) const { return(c1.val < c2.val); } }; void Ranges::getRanges( float winsz, int minH, bool extend, Ivn &ivn, bool onlyRatioOne ) { attVecCell cell; IvnIt iit; vector<attVecCell> attVec; vector<attVecCell>::iterator it, it1, it2, it3, it4, start_it, end_it; int support, sup, max_sup; float win_size, val1, val2; Transet transet; win_size = 1.0 + winsz; support = minH; for(int i=0; i<width-1; i++) // proof: 10 * 1.2 --> 12 <==> 1/12 * 1.2 --> 1/10 for(int j=i+1; j<width; j++){ // loop every pair of attributes //cout << "H21" << endl; attVec.clear(); //cout << i << " " << j << endl; for(int k=0; k<height; k++){ if( fabs(array(i,k)) < 0.0000001 || fabs(array(j,k)) < 0.0000001 ){ // avoid divided by zero and chain broken by zero if( fabs(array(i,k)) < 0.0000001 && fabs(array(j,k)) < 0.0000001 ){ // both are zero for(iit=ivn.begin(); iit!=ivn.end(); iit++) if( fabs(*iit) < 0.0000001 ) // zero is undesired values goto SKIP; cell.val = 1.0; cell.trans = k; attVec.push_back( cell ); } goto SKIP; } //cout << "H22" << endl; for(iit=ivn.begin(); iit!=ivn.end(); iit++){ if( fabs(*iit - array(i,k)) < 0.00001 || fabs(*iit - array(j,k)) < 0.00001 ) // undesired values goto SKIP; } cell.val = array(j,k) / array(i,k); cell.trans = k; if( onlyRatioOne ){ if( 1.0/win_size < cell.val && cell.val < win_size ) attVec.push_back( cell ); } else attVec.push_back( cell ); SKIP:; } sort(attVec.begin(), attVec.end(), attVec_less()); //////////////////////////////////////////////////////// to keep positive float vv = attVec.begin()->val; if( vv < 0 ) for( it1=attVec.begin(); it1!=attVec.end(); it1++ ) it1->val -= vv; //////////////////////////////////////////////////////////////////////// do{ it1 = it2 = attVec.begin(); max_sup = 0; sup = 0; while( it2 != attVec.end() ){ if( it1->trans == -1 ){ while( it1 != attVec.end() && it1->trans == -1 ) it1++; it2 = it1; } while( it2 != attVec.end() && it2->trans != -1 && it2->val <= it1->val * win_size ){ // positive values are required it2++; sup++; } if(sup > max_sup){ start_it = it1; end_it = it2; max_sup = sup; } if( it2->trans == -1 ){ //if( it2->trans == -1 || it2 != attVec.end() ){ it1 = it2; sup = 0; } else{ it1++; sup--; } } if(max_sup >= support){ if( extend ){ // EXTEND to both directions ///////////////////////////////////////////////////////////////////// it1 = it3 = start_it; it2 = it4 = end_it; /////////////////////////// sup = max_sup; while( sup > support ){ it1++; sup--; } while( it2->trans != -1 && it2 != attVec.end() && it2->val <= it1->val * win_size ){ // t2->val - it1->val <= win_size ){ it1++; it2++; } /////////////////////////// sup = max_sup; while( sup > support ){ it4--; sup--; } if( it3 != attVec.begin() ){ it4--; // changed it3--; while( it3->trans != -1 && it3 != attVec.begin() && it4->val <= it3->val * win_size ){// t4->val - it3->val <= win_size ){ it3--; it4--; } if( it3->trans == -1 || it4->val > it3->val * win_size ) //it4->val - it3->val > win_size ) it3++; } start_it = it3; end_it = it2; } //////////////////////////////////////////////////////////////////// for(it=start_it; it!=end_it; it++){ transet.insert( it->trans ); it->trans = -1; } if( transet.size() >= support ) EDGE(i,j).push_back( transet ); transet.clear(); } }while( max_sup >= support ); attVec.clear(); /////////////////////////////////////////// } // array.clear(); } ostream& operator<<(ostream& out, Transet &t){ char buf[200]; TransetIt it; for(it=t.begin(); it!=t.end(); it++){ sprintf(buf, "%3d ", *it ); out << buf; } out << endl; } void Ranges::showRanges() { vector<Transet>::iterator it; for(int i=0; i<width-1; i++) for(int j=i+1; j<width; j++){ // loop every pair of attributes if( !EDGE(i,j).empty() ){ cout << "========================= (" << i << ", " << j << ") ==========================" << endl; for(it=EDGE(i,j).begin(); it!=EDGE(i,j).end(); it++) cout << *it; } } } /*for shifting patterns, this program is sensitive to small values, so add a constant first*/ int main(int argc, char *argv[]) { Clusters clusters; /////////// default values ///////// char filename[100]; // -fdatafile.txt int row_sup; // -r10 int col_sup; // -c5 float win_size = 0.01; // -w0.01 float del_overlap = 1.00; // -d0.97 float mer_overlap = 1.00; // -m0.95 Ivn InvalidNum; bool showClusters1 = false; bool showClusters2 = false; bool showClusters3 = false; bool showQuality1 = false; bool showQuality2 = false; bool showQuality3 = false; bool onlyRatioOne = false; float deltaR = -1.0; float deltaC = -1.0; //////////////////////////////////// if(argc < 4) { cout << endl << "Usage: " << argv[0] << " -fFile -rRow -cColumn [other options]" << endl << endl; cout << "==================== OPTIONS =====================" << endl << endl; cout << "File Name: -fString" << endl; cout << "Minimum Rows: -rInteger" << endl; cout << "Minimum Columns: -cInteger" << endl; cout << "Range Window Size: -wFloat /*0.01 by default*/" << endl; cout << "Deletion Threshold: -dFloat /*1.00 by default*/" << endl; cout << "Merging Threshold: -mFloat /*1.00 by default*/" << endl; cout << "Unrelated Numbers: -uFloat /*mciroCluster will not consider the values refered by this option*/" << endl; cout << "Only Ratio 1.0: -e /*when trying to get the rows with close values only*/" << endl; cout << "delta-Row: -erFloat /*when trying to let the row values be around equal*/" << endl; cout << "delta-Column: -ecFloat /*when trying to let the column values be around equal*/" << endl; cout << "Show Qualities: -q123 /*1:Original qualities, 2:Qualities after deletion, 3:Qualities after merging*/" << endl; cout << "Output Clusters: -o123 /*1:Original clusters, 2:Clusters after deletion, 3:Clusters after merging*/" << endl; cout << "Output Names: -nrc /*r: row names c: column names*/" << endl << endl; exit(1); } for(int i=1; i<argc; i++){ if( argv[i][0] == '-' ){ switch( argv[i][1] ){ case 'f': strcpy( filename, argv[i]+2 ); break; case 'r': row_sup = atoi( argv[i]+2 ); break; case 'c': col_sup = atoi( argv[i]+2 ); break; case 'w': win_size = atof( argv[i]+2 ); break; case 'd': del_overlap = atof( argv[i]+2 ); break; case 'm': mer_overlap = atof( argv[i]+2 ); break; case 'u': InvalidNum.push_back( atof(argv[i]+2) ); break; case 'e': if( strlen(argv[i]) == 2 ) onlyRatioOne = true; else{ switch( argv[i][2] ){ case 'r': deltaR = atof( argv[i]+3 ); break; case 'c': deltaC = atof( argv[i]+3 ); break; default: cout << "Error Input Options: " << argv[i] << endl; exit(0); break; } } break; case 'q': for(int k=2; k<strlen(argv[i]); k++) switch( argv[i][k] ){ case '1': showQuality1 = true; break; case '2': showQuality2 = true; break; case '3': showQuality3 = true; break; default: cout << "Error Input Options: " << argv[i] << endl; exit(0); break; } break; case 'o': for(int k=2; k<strlen(argv[i]); k++) switch( argv[i][k] ){ case '1': showClusters1 = true; break; case '2': showClusters2 = true; break; case '3': showClusters3 = true; break; default: cout << "Error Input Options: " << argv[i] << endl; exit(0); break; } break; case 'n': for(int k=2; k<strlen(argv[i]); k++) switch( argv[i][k] ){ case 'c': showRowName = true; break; case 'r': showColName = true; break; default: cout << "Error Input Options: " << argv[i] << endl; exit(0); break; } break; default: cout << "Error Input Options: " << argv[i] << endl; exit(0); break; } } else{ cout << "Error Input Options: " << argv[i] << endl; exit(0); } } cout << endl; for(int i=0; i<argc; i++) cout << argv[i] << " "; cout << endl << endl; cout << "File:\t" << filename << endl; cout << "MinRow:\t" << row_sup << endl; cout << "MinCol:\t" << col_sup << endl; cout << "Win Size:" << win_size << endl; cout << "Deletion Threshold: " << del_overlap << endl; cout << "Merging Threshold: " << mer_overlap << endl; if(deltaR>0) cout << "delta-Row: " << deltaR << endl; if(deltaC>0) cout << "delta-Column:: " << deltaC << endl; Timer T("Time "); T.Start(); /////////////////////////////////////////////////////////////////// Ranges ranges( filename ); ranges.GetTabFileSize(false); // show data or not ranges.ReadTabFile(); //ranges.showData(); ranges.getRanges( win_size, row_sup, true, InvalidNum, onlyRatioOne ); // extend = true //ranges.showRanges(); clusters.getClusters( col_sup, row_sup, ranges.width, deltaR, deltaC, ranges.array); /////////////////////////////////////////////////////////////////// cout << endl << "Original clusters: " << clusters.validNum(); if( showClusters1 ) clusters.show(ranges.array); if(showQuality1) clusters.showQuality(ranges.array); /////////////////////////////////////////////////////////////////// if( fabs(del_overlap - 1.0) > 0.00001 ){ clusters.delet( del_overlap ); cout << endl << "Clusters after deletion: " << clusters.validNum(); if( showClusters2 ) clusters.show(ranges.array); } if(showQuality2) clusters.showQuality(ranges.array); /////////////////////////////////////////////////////////////////// if( fabs(mer_overlap - 1.0) > 0.00001 ){ clusters.merge( mer_overlap ); cout << endl << "Clusters after merging: " << clusters.validNum(); if( showClusters3 ) clusters.show(ranges.array); } if(showQuality3) clusters.showQuality(ranges.array); /////////////////////////////////////////////////////////////////// T.Stop(); cout << endl << T << endl; ranges.clear(); InvalidNum.clear(); return 0; }
49.431879
197
0.242848
zakimjz
ba0978372cfea3054b3b80fefb47b6c1ee423e96
4,292
cpp
C++
samples/SynchroTests/RecursiveMutexTester.cpp
biojppm/turf
9ae0d4b984fa95ed5f823274b39c87ee742f6650
[ "BSD-2-Clause" ]
565
2016-02-01T14:05:20.000Z
2022-03-30T22:52:15.000Z
samples/SynchroTests/RecursiveMutexTester.cpp
biojppm/turf
9ae0d4b984fa95ed5f823274b39c87ee742f6650
[ "BSD-2-Clause" ]
10
2016-02-01T22:28:05.000Z
2020-11-26T15:42:01.000Z
samples/SynchroTests/RecursiveMutexTester.cpp
biojppm/turf
9ae0d4b984fa95ed5f823274b39c87ee742f6650
[ "BSD-2-Clause" ]
90
2016-02-01T19:45:36.000Z
2022-03-17T02:41:38.000Z
/*------------------------------------------------------------------------ Turf: Configurable C++ platform adapter Copyright (c) 2016 Jeff Preshing Distributed under the Simplified BSD License. Original location: https://github.com/preshing/turf This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the LICENSE file for more information. ------------------------------------------------------------------------*/ #include <vector> #include <turf/Mutex.h> #include <string> #include <random> #include <thread> #include <turf/Assert.h> using namespace turf::intTypes; //--------------------------------------------------------- // RecursiveMutexTester //--------------------------------------------------------- class RecursiveMutexTester { private: struct ThreadStats { ureg iterations; ureg workUnitsComplete; ureg amountIncremented; ThreadStats() { iterations = 0; workUnitsComplete = 0; amountIncremented = 0; } ThreadStats& operator+=(const ThreadStats& other) { iterations += other.iterations; workUnitsComplete += other.workUnitsComplete; amountIncremented += other.amountIncremented; return *this; } }; ureg m_iterationCount; turf::Mutex m_mutex; ureg m_value; std::vector<ThreadStats> m_threadStats; public: RecursiveMutexTester() : m_iterationCount(0), m_value(0) { } void threadFunc(ureg threadNum) { std::random_device rd; std::mt19937 randomEngine(rd()); ThreadStats localStats; ureg lockCount = 0; ureg lastValue = 0; for (ureg i = 0; i < m_iterationCount; i++) { localStats.iterations++; // Do a random amount of work. ureg workUnits = std::uniform_int_distribution<>(0, 3)(randomEngine); for (ureg j = 1; j < workUnits; j++) randomEngine(); // Do one work unit localStats.workUnitsComplete += workUnits; // Consistency check. if (lockCount > 0) { TURF_ASSERT(m_value == lastValue); } // Decide what the new lock count should be in the range [0, 4), biased towards low numbers. float f = std::uniform_real_distribution<float>(0.f, 1.f)(randomEngine); ureg desiredLockCount = (ureg)(f * f * 4); // Perform unlocks, if any. while (lockCount > desiredLockCount) { m_mutex.unlock(); lockCount--; } // Perform locks, if any. bool useTryLock = (std::uniform_int_distribution<>(0, 1)(randomEngine) == 0); while (lockCount < desiredLockCount) { if (useTryLock) { if (!m_mutex.tryLock()) break; } else { m_mutex.lock(); } lockCount++; } // If locked, increment counter. if (lockCount > 0) { TURF_ASSERT((m_value - lastValue) >= 0); m_value += threadNum + 1; lastValue = m_value; localStats.amountIncremented += threadNum + 1; } } // Release Lock if still holding it. while (lockCount > 0) { m_mutex.unlock(); lockCount--; } // Copy statistics. m_threadStats[threadNum] = localStats; } bool test(ureg threadCount, ureg iterationCount) { m_iterationCount = iterationCount; m_value = 0; m_threadStats.resize(threadCount); std::vector<std::thread> threads; for (ureg i = 0; i < threadCount; i++) threads.emplace_back(&RecursiveMutexTester::threadFunc, this, i); for (std::thread& t : threads) t.join(); ThreadStats totalStats; for (const ThreadStats& s : m_threadStats) totalStats += s; return (m_value == totalStats.amountIncremented); } }; bool testRecursiveMutex() { RecursiveMutexTester tester; return tester.test(4, 100000); }
31.101449
104
0.532386
biojppm
ba0e8299aabb21f8e67fdccc15e8dac41d3fe644
9,661
cc
C++
src/Hmm/GrammarGenerator.cc
alexanderrichard/squirrel
12614a9eb429500c8f341654043f33a1b6bd1d31
[ "AFL-3.0" ]
63
2016-07-08T13:35:27.000Z
2021-01-13T18:37:13.000Z
src/Hmm/GrammarGenerator.cc
alexanderrichard/squirrel
12614a9eb429500c8f341654043f33a1b6bd1d31
[ "AFL-3.0" ]
4
2017-08-04T09:25:10.000Z
2022-02-24T15:38:52.000Z
src/Hmm/GrammarGenerator.cc
alexanderrichard/squirrel
12614a9eb429500c8f341654043f33a1b6bd1d31
[ "AFL-3.0" ]
30
2016-05-11T02:24:46.000Z
2021-11-12T14:06:20.000Z
/* * Copyright 2016 Alexander Richard * * This file is part of Squirrel. * * Licensed under the Academic Free License 3.0 (the "License"). * You may not use this file except in compliance with the License. * You should have received a copy of the License along with Squirrel. * If not, see <https://opensource.org/licenses/AFL-3.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. */ /* * GrammarGenerator.cc * * Created on: May 31, 2017 * Author: richard */ #include "GrammarGenerator.hh" using namespace Hmm; /* * GrammarGenerator */ const Core::ParameterEnum GrammarGenerator::paramGrammarType_("type", "finite, n-gram", "finite", "grammar"); const Core::ParameterString GrammarGenerator::paramGrammarFile_("file", "", "grammar"); GrammarGenerator::GrammarGenerator() : grammarFile_(Core::Configuration::config(paramGrammarFile_)) {} void GrammarGenerator::write() { /* write result to file */ if (grammarFile_.empty()) Core::Error::msg("GrammarGenerator::generate(): grammar.file not specified.") << Core::Error::abort; if (!Core::Utils::isGz(grammarFile_)) grammarFile_.append(".gz"); Core::CompressedStream f(grammarFile_, std::ios::out); // write nonterminal symbols std::vector<std::string> tmp; for (std::set<std::string>::iterator it = nonterminals_.begin(); it != nonterminals_.end(); it++) tmp.push_back(*it); for (u32 i = 0; i < tmp.size() - 1; i++) f << tmp.at(i) << ", "; f << tmp.back() << Core::IOStream::endl; // write terminal symbols for (u32 i = 0; i < labelReader_.featureDimension()-1; i++) f << i << ", "; f << labelReader_.featureDimension()-1 << Core::IOStream::endl; // write rules for (u32 i = 0; i < rules_.size(); i++) f << rules_.at(i) << Core::IOStream::endl; f.close(); } GrammarGenerator* GrammarGenerator::create() { switch ((GrammarType) Core::Configuration::config(paramGrammarType_)) { case finite: Core::Log::os("Create finite grammar generator."); return new FiniteGrammarGenerator(); break; case ngram: Core::Log::os("Create n-gram grammar generator."); return new NGramGenerator(); break; default: return 0; // this can not happen } } /* * FiniteGrammarGenerator */ void FiniteGrammarGenerator::depthFirstSearch(const Core::Tree<u32, Float>::Node& node, const std::string& prefix) { // store nonterminal and terminal symbol and generate rule std::stringstream n; n << prefix << "_" << node.key(); std::stringstream t; t << node.key(); nonterminals_.insert(n.str()); std::stringstream rule; rule << prefix << " -> " << t.str() << " " << n.str() << " " << node.value(); rules_.push_back(rule.str()); // if this is a leaf, add rule for sequence end symbol if (node.nChildren() == 0) { std::stringstream endrule; endrule << n.str() << " -> . . 1"; rules_.push_back(endrule.str()); } // else proceed with the children else { for (u32 i = 0; i < node.nChildren(); i++) { depthFirstSearch(node.child(i), n.str()); } } } void FiniteGrammarGenerator::generate() { /* create prefix tree with all label sequences */ Core::Tree<u32, Float> tree(0, 1.0); labelReader_.initialize(); while (labelReader_.hasSequences()) { std::vector<u32> path(labelReader_.nextLabelSequence()); path.insert(path.begin(), 0); tree.addPath(path, 1.0); } /* traverse tree in depth-first order and create rules of the grammar */ nonterminals_.insert("S"); for (u32 i = 0; i < tree.root().nChildren(); i++) depthFirstSearch(tree.root().child(i), "S"); write(); } /* * NGramGenerator */ const Core::ParameterInt NGramGenerator::paramNGramOrder_("n-gram-order", 0, "grammar"); const Core::ParameterBool NGramGenerator::paramBackingOff_("backing-off", true, "grammar"); const NGramGenerator::Word NGramGenerator::root = -1; const NGramGenerator::Word NGramGenerator::senStart = -2; /*** LmTree ***/ NGramGenerator::LmTree::LmTree(const Key& rootKey, const Value& rootValue) : Precursor(rootKey, rootValue) {} void NGramGenerator::LmTree::unseenWords(const Context& history, u32 lexiconSize, std::vector<Word>& unseen) const { unseen.clear(); // if history does not exist, N(h,w) = 0 for all w if (!pathExists(history)) { for (u32 w = 0; w < lexiconSize; w++) unseen.push_back((Word)w); } else { std::vector<bool> tmp(lexiconSize, false); const Node n = node(history); for (u32 i = 0; i < n.nChildren(); i++) { tmp.at(n.child(i).key()) = true; } for (u32 i = 0; i < lexiconSize; i++) { if (!tmp.at(i)) unseen.push_back((Word)i); } } } NGramGenerator::Count NGramGenerator::LmTree::countSingletons(const Node& node, u32 level) const { if (level == 0) { if (node.value() == 1) return 1; else return 0; } else { Count sum = 0; for (u32 i = 0; i < node.nChildren(); i++) { sum += countSingletons(node.child(i), level-1); } return sum; } } NGramGenerator::Count NGramGenerator::LmTree::countSingletons(u32 level) const { return countSingletons(root_, level); } /*** End LmTree ***/ NGramGenerator::NGramGenerator() : nGramOrder_(Core::Configuration::config(paramNGramOrder_)), backingOff_(Core::Configuration::config(paramBackingOff_)), nWords_(0), lexiconSize_(0), lmTree_(root, 0), lambda_(nGramOrder_, 0.0) {} void NGramGenerator::accumulate(const std::vector<u32>& sequence) { for (u32 i = 0; i < sequence.size(); i++) { Context path(1, root); // each context/path starts with the root node for (s32 k = nGramOrder_; k >= 0; k--) { if ((s32)i < k) path.push_back(senStart); else path.push_back(sequence.at(i - k)); } if (!lmTree_.pathExists(path)) lmTree_.addPath(path, 0); lmTree_.value(path)++; while (path.size() > 1) { path.pop_back(); lmTree_.value(path)++; } } nWords_ += sequence.size(); } void NGramGenerator::estimateDiscountingParameter() { for (u32 historyLength = 0; historyLength < nGramOrder_; historyLength++) { lambda_.at(historyLength) = (Float)lmTree_.countSingletons(historyLength + 1) / (Float)nWords_; } Core::Log::openTag("linear-discounting"); for (u32 historyLength = 0; historyLength < nGramOrder_; historyLength++) { Core::Log::os() << historyLength << "-gram discount: " << lambda_.at(historyLength); } Core::Log::closeTag(); } Float NGramGenerator::probability(const Context& c) { require_gt(c.size(), 1); Context context = c; u32 historyLength = context.size() - 2; std::vector<Word> unseen; /* standard n-gram */ if (lmTree_.pathExists(context)) { Float p = lmTree_.value(context); context.pop_back(); p /= lmTree_.value(context); lmTree_.unseenWords(context, lexiconSize_, unseen); if (backingOff_ && (unseen.size() > 0)) // multiplication with backing-off parameter only if unseen events with the same history actually exist return (1 - lambda_.at(historyLength)) * p; else return p; } /* unseen event with backing-off */ else if (backingOff_) { Word w = context.back(); context.pop_back(); std::vector<Word> unseen; lmTree_.unseenWords(context, lexiconSize_, unseen); context.push_back(w); context.erase(context.begin() + 1); // remove oldest history element // compute backing-off score p(w|h') Context tmpContext(context); Float p = probability(tmpContext); // compute renormalization for backing-off Float norm = 0; for (u32 i = 0; i < unseen.size(); i++) { context.back() = unseen.at(i); Context tmpContext(context); norm += probability(tmpContext); } // return renormalized probability, include backing-off parameter only if there are acutally seen events with the same history return (unseen.size() < lexiconSize_ ? lambda_.at(historyLength) : 1.0) * p / norm; } /* unseen event without backing-off */ else { return 0.0; } } void NGramGenerator::extendContext(Context& c, std::vector<Context>& contexts) { if (c.size() < nGramOrder_ + 2) { // + 2 due to root and actual word // extend context by all words for (Word w = 0; w < (s32)lexiconSize_; w++) { c.push_back(w); extendContext(c, contexts); c.pop_back(); } // also include senStart in the context history if ((c.size() < nGramOrder_ + 1) && (c.back() < 0)) { // c.back() < 0 is true for senStart and root c.push_back(senStart); extendContext(c, contexts); c.pop_back(); } } else { contexts.push_back(c); } } void NGramGenerator::addRule(const Context& c) { std::stringstream s; s << "S"; if (c.at(c.size() - 2) != senStart) { for (u32 i = 1; i < c.size()-1; i++) s << "_" << (c.at(i) < 0 ? lexiconSize_ : c.at(i)); } nonterminals_.insert(s.str()); s << " -> " << c.back() << " S"; for (u32 i = 2; i < c.size(); i++) s << "_" << (c.at(i) < 0 ? lexiconSize_ : c.at(i)); Float p = probability(c); s << " " << p; if (p > 0) rules_.push_back(s.str()); } void NGramGenerator::generate() { labelReader_.initialize(); lexiconSize_ = labelReader_.featureDimension(); while (labelReader_.hasSequences()) { accumulate(labelReader_.nextLabelSequence()); } if (backingOff_) estimateDiscountingParameter(); // generate all possible contexts (w, h) and add the corresponding rule std::vector<Context> contexts; Context c(1, root); extendContext(c, contexts); for (u32 i = 0; i < contexts.size(); i++) addRule(contexts.at(i)); // add end rules for (std::set<std::string>::iterator it = nonterminals_.begin(); it != nonterminals_.end(); ++it) { if (it->compare("S") != 0) { std::stringstream s; s << (*it) << " -> . . 1"; rules_.push_back(s.str()); } } write(); }
29.364742
145
0.661629
alexanderrichard
ba12898f31ff9cb6c18998655bd92ea83de02974
3,901
cc
C++
base/threading/thread_local_unittest.cc
SlimKatLegacy/android_external_chromium
bc611cda58cc18d0dbaa8a7aee05eb3c0742e573
[ "BSD-3-Clause" ]
2
2017-02-20T14:25:04.000Z
2019-12-13T13:58:28.000Z
base/threading/thread_local_unittest.cc
SlimKatLegacy/android_external_chromium
bc611cda58cc18d0dbaa8a7aee05eb3c0742e573
[ "BSD-3-Clause" ]
2
2017-07-25T09:37:22.000Z
2017-08-04T07:18:56.000Z
base/threading/thread_local_unittest.cc
SlimKatLegacy/android_external_chromium
bc611cda58cc18d0dbaa8a7aee05eb3c0742e573
[ "BSD-3-Clause" ]
2
2020-01-12T00:55:53.000Z
2020-11-04T06:36:41.000Z
// Copyright (c) 2010 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 "base/logging.h" #include "base/threading/simple_thread.h" #include "base/threading/thread_local.h" #include "base/synchronization/waitable_event.h" #include "testing/gtest/include/gtest/gtest.h" namespace base { namespace { class ThreadLocalTesterBase : public base::DelegateSimpleThreadPool::Delegate { public: typedef base::ThreadLocalPointer<ThreadLocalTesterBase> TLPType; ThreadLocalTesterBase(TLPType* tlp, base::WaitableEvent* done) : tlp_(tlp), done_(done) { } ~ThreadLocalTesterBase() { } protected: TLPType* tlp_; base::WaitableEvent* done_; }; class SetThreadLocal : public ThreadLocalTesterBase { public: SetThreadLocal(TLPType* tlp, base::WaitableEvent* done) : ThreadLocalTesterBase(tlp, done), val_(NULL) { } ~SetThreadLocal() { } void set_value(ThreadLocalTesterBase* val) { val_ = val; } virtual void Run() { DCHECK(!done_->IsSignaled()); tlp_->Set(val_); done_->Signal(); } private: ThreadLocalTesterBase* val_; }; class GetThreadLocal : public ThreadLocalTesterBase { public: GetThreadLocal(TLPType* tlp, base::WaitableEvent* done) : ThreadLocalTesterBase(tlp, done), ptr_(NULL) { } ~GetThreadLocal() { } void set_ptr(ThreadLocalTesterBase** ptr) { ptr_ = ptr; } virtual void Run() { DCHECK(!done_->IsSignaled()); *ptr_ = tlp_->Get(); done_->Signal(); } private: ThreadLocalTesterBase** ptr_; }; } // namespace // In this test, we start 2 threads which will access a ThreadLocalPointer. We // make sure the default is NULL, and the pointers are unique to the threads. TEST(ThreadLocalTest, Pointer) { base::DelegateSimpleThreadPool tp1("ThreadLocalTest tp1", 1); base::DelegateSimpleThreadPool tp2("ThreadLocalTest tp1", 1); tp1.Start(); tp2.Start(); base::ThreadLocalPointer<ThreadLocalTesterBase> tlp; static ThreadLocalTesterBase* const kBogusPointer = reinterpret_cast<ThreadLocalTesterBase*>(0x1234); ThreadLocalTesterBase* tls_val; base::WaitableEvent done(true, false); GetThreadLocal getter(&tlp, &done); getter.set_ptr(&tls_val); // Check that both threads defaulted to NULL. tls_val = kBogusPointer; done.Reset(); tp1.AddWork(&getter); done.Wait(); EXPECT_EQ(static_cast<ThreadLocalTesterBase*>(NULL), tls_val); tls_val = kBogusPointer; done.Reset(); tp2.AddWork(&getter); done.Wait(); EXPECT_EQ(static_cast<ThreadLocalTesterBase*>(NULL), tls_val); SetThreadLocal setter(&tlp, &done); setter.set_value(kBogusPointer); // Have thread 1 set their pointer value to kBogusPointer. done.Reset(); tp1.AddWork(&setter); done.Wait(); tls_val = NULL; done.Reset(); tp1.AddWork(&getter); done.Wait(); EXPECT_EQ(kBogusPointer, tls_val); // Make sure thread 2 is still NULL tls_val = kBogusPointer; done.Reset(); tp2.AddWork(&getter); done.Wait(); EXPECT_EQ(static_cast<ThreadLocalTesterBase*>(NULL), tls_val); // Set thread 2 to kBogusPointer + 1. setter.set_value(kBogusPointer + 1); done.Reset(); tp2.AddWork(&setter); done.Wait(); tls_val = NULL; done.Reset(); tp2.AddWork(&getter); done.Wait(); EXPECT_EQ(kBogusPointer + 1, tls_val); // Make sure thread 1 is still kBogusPointer. tls_val = NULL; done.Reset(); tp1.AddWork(&getter); done.Wait(); EXPECT_EQ(kBogusPointer, tls_val); tp1.JoinAll(); tp2.JoinAll(); } TEST(ThreadLocalTest, Boolean) { { base::ThreadLocalBoolean tlb; EXPECT_FALSE(tlb.Get()); tlb.Set(false); EXPECT_FALSE(tlb.Get()); tlb.Set(true); EXPECT_TRUE(tlb.Get()); } // Our slot should have been freed, we're all reset. { base::ThreadLocalBoolean tlb; EXPECT_FALSE(tlb.Get()); } } } // namespace base
23.786585
79
0.700846
SlimKatLegacy
ba182fb1825e331b9add4e29799607bddeea8f54
355
cpp
C++
tests/reverse_test.cpp
mtao/core
91f9bc6e852417989ed62675e2bb372e6afc7325
[ "MIT" ]
null
null
null
tests/reverse_test.cpp
mtao/core
91f9bc6e852417989ed62675e2bb372e6afc7325
[ "MIT" ]
4
2020-04-18T16:16:05.000Z
2020-04-18T16:17:36.000Z
tests/reverse_test.cpp
mtao/core
91f9bc6e852417989ed62675e2bb372e6afc7325
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <algorithm> #include <iterator> #include <numeric> #include <set> #include <mtao/iterator/reverse.hpp> using namespace mtao::iterator; int main() { std::vector<int> a(30); std::iota(a.begin(),a.end(),0); for(auto&& v: reverse(a)) { std::cout << v << std::endl; } return 0; }
16.136364
36
0.608451
mtao
ba1915ccd2696aec16c83a1a659486da1ce63384
22,322
cpp
C++
earth_enterprise/src/fusion/gst/gstGeoIndex.cpp
tornado12345/earthenterprise
0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9
[ "Apache-2.0" ]
2,661
2017-03-20T22:12:50.000Z
2022-03-30T09:43:19.000Z
earth_enterprise/src/fusion/gst/gstGeoIndex.cpp
tornado12345/earthenterprise
0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9
[ "Apache-2.0" ]
1,531
2017-03-24T17:20:32.000Z
2022-03-16T18:11:14.000Z
earth_enterprise/src/fusion/gst/gstGeoIndex.cpp
tornado12345/earthenterprise
0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9
[ "Apache-2.0" ]
990
2017-03-24T11:54:28.000Z
2022-03-22T11:51:47.000Z
// Copyright 2017 Google Inc. // Copyright 2020 The Open GEE Contributors // // 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 "fusion/gst/gstGeoIndex.h" #include <GL/gl.h> #include <algorithm> #include "fusion/gst/gstConstants.h" #include "fusion/gst/gstMisc.h" #include "fusion/gst/gstGeode.h" #include "fusion/gst/gstSourceManager.h" #include "common/khInsetCoverage.h" #include "common/khFileUtils.h" #include "common/khException.h" gstGeoIndexHandle gstGeoIndexImpl::Load(const std::string &select_file, const gstSharedSource &source, const khTilespace &tilespace, const double oversize_factor, const unsigned int target_level) { return khRefGuardFromNew(new gstGeoIndexImpl(select_file, source, tilespace, oversize_factor, target_level)); } gstGeoIndexImpl::gstGeoIndexImpl() : tilespace_(ClientVectorTilespace), oversize_factor_(0.0), grid_(), box_list_(), box_index_list_(), bounding_box_(), coverage_(), presence_mask_(), coverage_mask_(), target_level_(0) { Init(); } gstGeoIndexImpl::gstGeoIndexImpl(const khLevelCoverage &cov, const khTilespace &tilespace, double oversize_factor) : tilespace_(tilespace), oversize_factor_(oversize_factor), grid_(), box_list_(), box_index_list_(), bounding_box_(), coverage_(cov), presence_mask_(), coverage_mask_(), target_level_(0) { Init(); } gstGeoIndexImpl::gstGeoIndexImpl(const std::string &select_file, const gstSharedSource &source, const khTilespace &tilespace, const double oversize_factor, const unsigned int target_level) : tilespace_(tilespace), oversize_factor_(oversize_factor), grid_(), box_list_(), box_index_list_(), bounding_box_(), coverage_(), presence_mask_(), coverage_mask_(), target_level_(target_level) { Init(); ThrowingReadFile(select_file, source->Id()); } void gstGeoIndexImpl::Init() { box_list_ = FeatureList::Create(); } // Prepare index for a new insert cycle. void gstGeoIndexImpl::Reset() { bounding_box_.Invalidate(); for (FeatureGridIterator it = grid_.begin(); it != grid_.end(); ++it) { it->clear(); } box_list_ = FeatureList::Create(); box_index_list_.clear(); coverage_ = khLevelCoverage(); presence_mask_.clear(); // Delete old presence mask. coverage_mask_.clear(); // Delete old coverage mask. } // Each insert adds a single feature id and it's corresponding bounding box. void gstGeoIndexImpl::Insert(int feature_id, const gstBBox& bounding_box) { assert(box_list_); box_list_->push_back(FeatureHandle(feature_id, bounding_box)); box_index_list_.push_back(box_list_->size() - 1); assert(box_list_->size() == box_index_list_.size()); bounding_box_.Grow(bounding_box); } // Each insert adds a single feature index and it's corresponding bounding box. void gstGeoIndexImpl::InsertIndex(unsigned int idx) { assert(box_list_); box_index_list_.push_back(idx); bounding_box_.Grow((*box_list_)[idx].bounding_box); } // Once all features are inserted, compute the dimensions of our grid index // and insert the features into each cell that their bounding box intersects. void gstGeoIndexImpl::Finalize(void) { if (!bounding_box_.Valid()) return; if (coverage_.empty()) { // pick a new size for the grid based on how many objects // figure that the shapes are perfectly distributed geographically // then we would put 100 features in each bucket std::uint32_t size = static_cast<std::uint32_t>(sqrt(box_index_list_.size()) * 0.1); std::uint64_t targetTotal = size * size; std::uint64_t minTotal = 100; std::uint64_t maxTotal = 1000000; // now find the largest level that has fewer tiles than our max khExtents<double> normExtents(NSEWOrder, bounding_box_.n, bounding_box_.s, bounding_box_.e, bounding_box_.w); notify(NFY_DEBUG, "----------"); // Our (super)tile size is 2048 pxl (FusionMapTilespace.tileSizeLog2) and we // need oversize of one map tile 256 pxl // (FusionMapTilespace.pixelsAtLevel0Log2) in all directions. Oversize of // factor .25 effectively adds 1 more tile in each direction. We need that // to be 256 pxl at target_level_. So we go deep to 3 (11-8) more levels (or // less) here. Going to MaxClientLevel, rather was causing the extra tile // not add any extra tile at target_level_. Also we don't have a reason // to go to such finer grid as MaxClientLevel (24) when the target_level_ // is lower. const unsigned int level_where_oversize_is_a_tile = target_level_ + tilespace_.tileSizeLog2 - tilespace_.pixelsAtLevel0Log2; for (int level = std::min(MaxClientLevel, level_where_oversize_is_a_tile); level >= 0; --level) { khLevelCoverage tmpCov = khLevelCoverage::FromNormExtentsWithCrop(tilespace_, normExtents, level, level); if (tmpCov.NumTiles() > maxTotal) { continue; } else if (tmpCov.NumTiles() < minTotal) { if (coverage_.extents.empty()) { coverage_ = tmpCov; notify(NFY_DEBUG, "Chose level %u: %Zu (only one) (target %Zu)", coverage_.level, coverage_.NumTiles(), targetTotal); } else { notify(NFY_DEBUG, "Chose level %u: %Zu over %Zu (too small) (target %Zu)", coverage_.level, coverage_.NumTiles(), tmpCov.NumTiles(), targetTotal); } break; } else if (tmpCov.NumTiles() > targetTotal) { notify(NFY_DEBUG, "saving level %u", tmpCov.level); coverage_ = tmpCov; } else { std::uint64_t myDiff = targetTotal - tmpCov.NumTiles(); std::uint64_t prevDiff = coverage_.NumTiles() - targetTotal; if (myDiff < prevDiff) { notify(NFY_DEBUG, "Chose level %u: %Zu over %Zu (target %Zu)", tmpCov.level, tmpCov.NumTiles(), coverage_.NumTiles(), targetTotal); coverage_ = tmpCov; } else { notify(NFY_DEBUG, "Chose level %u: %Zu over %Zu (target %Zu)", coverage_.level, coverage_.NumTiles(), tmpCov.NumTiles(), targetTotal); } break; } } // Create presence mask for original build set for levels from // coverage_.level to kMaxLevelForBuildPresenceMask. It is created once - // only for original build sets when Finalize() is called from ReadFile(). // Presence mask of original build set is updated in QuadExporter and in // gstLayer::ExportQuad() and used for optimization quadtree partitioning // to skip empty quads at early stage. // TODO: based on coverage of source data set we // can calculate MaxLevelForBuildPresenceMask. Need to verify will it be // useful. It should be more effective for city, buidings data set (but // actually they have simple polygons). // +1 - one beyond the valid level. khInsetCoverage covt(tilespace_, coverage_, coverage_.level, (coverage_.level < kMaxLevelForBuildPresenceMask) ? (kMaxLevelForBuildPresenceMask + 1) : (coverage_.level + 1)); presence_mask_ = TransferOwnership( new khPresenceMask(covt, true)); // true - fill all with present. // Set to "not present" all elements of beginLevel. The PresenceMask of // beginLevel will be initialized below during grid filling. presence_mask_->SetPresence(covt.beginLevel(), false); // Create coverage mask for original build set for levels from // coverage_.level to kMaxLevelForBuildPresenceMask. It is created once - // only for original build sets when Finalize() is called from ReadFile(). coverage_mask_ = TransferOwnership( new khCoverageMask(covt, false)); // false - fill all with not covered. } else { // Create presence mask. It is used when we call Finalize() from // SplitCell(). presence_mask_ = TransferOwnership( new khPresenceMask(khInsetCoverage(coverage_))); } // resize our grid to have the right number of buckets grid_.resize(coverage_.NumTiles()); // iterate through the bbox index list, inserting every feature into the // cells that they intersect with for (BoxIndexList::const_iterator it = box_index_list_.begin(); it != box_index_list_.end(); ++it) { const FeatureHandle& feature_handle = (*box_list_)[*it]; // Note: we can check the bounding boxes of parts for // multi-polygon features instead of bounding box of feature. But in this // case we need to read feature from kvp-file. We check bounding boxes of // parts in clipper and it is effective. // get the coverage of this feature at this level const gstBBox& box = feature_handle.bounding_box; khExtents<double> normExtents(NSEWOrder, box.n, box.s, box.e, box.w); khLevelCoverage thisCov = khLevelCoverage::FromNormExtentsWithOversizeFactor (tilespace_, normExtents, coverage_.level, coverage_.level, oversize_factor_); // intersect this features coverage with the total coverage for the index khExtents<std::uint32_t> tiles = khExtents<std::uint32_t>::Intersection(coverage_.extents, thisCov.extents); // put this id into every grid cell that it touches { std::uint32_t row = tiles.beginRow(); std::uint32_t gridRow = row - coverage_.extents.beginRow(); for (; row < tiles.endRow(); ++row, ++gridRow) { std::uint32_t col = tiles.beginCol(); std::uint32_t gridCol = col - coverage_.extents.beginCol(); for (; col < tiles.endCol(); ++col, ++gridCol) { unsigned int pos = (gridRow * coverage_.extents.numCols()) + gridCol; // add it to the appropriate bucket grid_[pos].push_back(*it); // update the presence mask (cascading up) presence_mask_->SetPresenceCascade( khTileAddr(coverage_.level, row, col)); } } } } } void gstGeoIndexImpl::Intersect(const gstBBox& bbox, std::vector<int>* match_list, std::vector<gstBBox>* index_boxes) { if (!bounding_box_.Valid()) return; // this is our real cull box gstBBox ubox = gstBBox::Intersection(bbox, bounding_box_); if (!ubox.Valid()) return; // convert to tile coverage at this level khExtents<double> normExtents(NSEWOrder, ubox.n, ubox.s, ubox.e, ubox.w); khLevelCoverage thisCov = khLevelCoverage::FromNormExtentsWithOversizeFactor( tilespace_, normExtents, coverage_.level, coverage_.level, oversize_factor_); // intersect this coverage with the total coverage for the index // since we intersected the geo extents this intersection is probably // redundant. But we'd hate to have float rouding cause us to // index off the end of an array somewhere. :-) khExtents<std::uint32_t> tiles = khExtents<std::uint32_t>::Intersection(coverage_.extents, thisCov.extents); // covert level-wide extents to be index wide extents tiles.makeRelativeTo(coverage_.extents.origin()); // put all feature ids in a set so we don't get duplicates std::set<int> set; for (unsigned int row = tiles.beginRow(); row < tiles.endRow(); ++row) { for (unsigned int col = tiles.beginCol(); col < tiles.endCol(); ++col) { unsigned int pos = (row * coverage_.extents.numCols()) + col; for (FeatureBucketIterator it = grid_[pos].begin(); it != grid_[pos].end(); ++it) { const FeatureHandle& feature_handle = (*box_list_)[*it]; if (ubox.Intersect(feature_handle.bounding_box)) set.insert(feature_handle.feature_id); } // caller wants the index grid boxes for debug display purposes if (index_boxes != NULL) { khExtents<double> norm_extents = khTileAddr(coverage_.level, row + coverage_.extents.beginRow(), col + coverage_.extents.beginCol()) .normExtents(tilespace_); index_boxes->push_back(gstBBox(norm_extents.west(), norm_extents.east(), norm_extents.south(), norm_extents.north())); } } } // copy cell contents to supplied list std::copy(set.begin(), set.end(), std::back_inserter(*match_list)); } void gstGeoIndexImpl::SelectAll(std::vector<int>* list) { list->reserve(list->size() + box_index_list_.size()); const FeatureList& fh_list = *box_list_; for (BoxIndexList::const_iterator it = box_index_list_.begin(); it != box_index_list_.end(); ++it) { list->push_back(fh_list[*it].feature_id); } } namespace { // Assumption: tilespace is in pixel coordinate where as box is in normalized // coordinate. void ExpandBbox(gstBBox* box_in_norm, const double oversize_factor, const unsigned int level, const khTilespace& tilespace) { // Stretch in width, delta_width = width * oversizeFactor // Stretch in width in each dir = delta_width / 2.0 const double expand_pixel = tilespace.tileSize * (oversize_factor / 2.0); const double num_pixel_world = static_cast<double>(tilespace.pixelsAtLevel0 << level); const double expand_norm = expand_pixel / num_pixel_world; box_in_norm->ExpandBy(expand_norm); } } // end namespace bool gstGeoIndexImpl::ReadFile(const std::string& path, int source_id) { try { ThrowingReadFile(path, source_id); return true; } catch(const std::exception &e) { notify(NFY_WARN, "%s", e.what()); } catch(...) { notify(NFY_WARN, "Unknown error reading %s", path.c_str()); } return false; } void gstGeoIndexImpl::ThrowingReadFile(const std::string& path, int source_id) { assert(box_list_); FILE* select_fp = ::fopen(path.c_str(), "r"); if (select_fp == NULL) { throw khErrnoException(kh::tr("Unable to open query results file %1") .arg(path.c_str())); } khFILECloser closer(select_fp); // read old style file and upgrade it if necessary double xmin, xmax, ymin, ymax; if (fscanf(select_fp, "EXTENTS: %lf, %lf, %lf, %lf\n", &xmin, &xmax, &ymin, &ymax) == 4) { bounding_box_.init(xmin, xmax, ymin, ymax); } // The bounding box of a set of features, is used to decide whether there is // any feature on a tile. Since a feature may not be on a tile, but its // plotting (like label, icon etc.) may be on a tile, we expand each dimension // of bounding box by oversize_factor_ to get a bigger bounding box to decide // whether a set of feature has any intersection with a tile. ExpandBbox(&bounding_box_, oversize_factor_, target_level_, tilespace_); // TODO: use counter for number of features in box_list_. int val; while (!feof(select_fp)) { fscanf(select_fp, "%d\n", &val); gstBBox box = theSourceManager->GetFeatureBoxOrThrow( UniqueFeatureId(source_id, 0, val)); if (!box.Valid()) { throw khException( kh::tr("Invalid bounding box for selected feature %1") .arg(val)); } box_list_->push_back(FeatureHandle(val, box)); box_index_list_.push_back(box_list_->size() - 1); assert(box_list_->size() == box_index_list_.size()); } Finalize(); } bool gstGeoIndexImpl::WriteFile(const std::string& path) { // silently remove file if it already exists if (khExists(path)) { if (unlink(path.c_str()) == -1) { notify(NFY_WARN, "Unable to remove select results file %s", path.c_str()); return false; } } FILE* selectfp = fopen(path.c_str(), "w"); if (selectfp == NULL) { notify(NFY_WARN, "Unable to create select results file %s", path.c_str()); return false; } // this is a simple text file with every feature id on it's own line fprintf(selectfp, "EXTENTS: %.20lf, %.20lf, %.20lf, %.20lf\n", bounding_box_.w, bounding_box_.e, bounding_box_.s, bounding_box_.n); for (BoxIndexList::const_iterator it = box_index_list_.begin(); it != box_index_list_.end(); ++it) { fprintf(selectfp, "%d\n", (*box_list_)[*it].feature_id); } fclose(selectfp); return true; } namespace { const unsigned int SplitStepSize = 3; } gstGeoIndexHandle gstGeoIndexImpl::SplitCell(std::uint32_t row, std::uint32_t col, const khLevelCoverage &targetCov) { assert(coverage_.level < targetCov.level); assert(coverage_.extents.ContainsRowCol(row, col)); // choose level to split to. Try to go SplitStepSize levels. But stop // earlier if we hit the target level unsigned int splitLevel = 0; unsigned int levelDiff = targetCov.level - coverage_.level; if (levelDiff <= SplitStepSize) { // We're close to the target level. Split on the target level splitLevel = targetCov.level; } else { splitLevel = coverage_.level + SplitStepSize; } // figure out this tiles coverage at the split level khLevelCoverage mySplitCov = khTileAddr(coverage_.level, row, col).MagnifiedToLevel(splitLevel); // figure out the target coverage at the split level khLevelCoverage targetSplitCov = targetCov.MinifiedToLevel(splitLevel); // intersect the two khExtents<std::uint32_t> splitExtents = khExtents<std::uint32_t>::Intersection(mySplitCov.extents, targetSplitCov.extents); // make a new index supplying the coverage we want gstGeoIndexHandle newIndex = khRefGuardFromNew(new gstGeoIndexImpl(khLevelCoverage(splitLevel, splitExtents), tilespace_, oversize_factor_)); // initialize box list handle. newIndex->box_list_ = box_list_; // walk my grid cell and add all the FeatureHandles into the new index std::uint32_t gridRow = row - coverage_.extents.beginRow(); std::uint32_t gridCol = col - coverage_.extents.beginCol(); unsigned int pos = (gridRow * coverage_.extents.numCols()) + gridCol; for (FeatureBucketIterator it = grid_[pos].begin(); it != grid_[pos].end(); ++it) { newIndex->InsertIndex(*it); } // finalize the new index (assigns features into new grid & populates // presence_mask_) newIndex->Finalize(); return newIndex; } const gstGeoIndexImpl::FeatureBucket* gstGeoIndexImpl::GetBucket(std::uint32_t row, std::uint32_t col) const { std::uint32_t gridRow = row - coverage_.extents.beginRow(); std::uint32_t gridCol = col - coverage_.extents.beginCol(); unsigned int pos = (gridRow * coverage_.extents.numCols()) + gridCol; return &grid_[pos]; } void gstGeoIndexImpl::PopulateBucket(const khExtents<std::uint32_t> &extents, FeatureBucket *bucket) const { std::set<int> set; std::uint32_t row = extents.beginRow(); std::uint32_t gridRow = row - coverage_.extents.beginRow(); for (; row < extents.endRow(); ++row, ++gridRow) { std::uint32_t col = extents.beginCol(); std::uint32_t gridCol = col - coverage_.extents.beginCol(); for (; col < extents.endCol(); ++col, ++gridCol) { unsigned int pos = (gridRow * coverage_.extents.numCols()) + gridCol; for (FeatureBucketConstIterator it = grid_[pos].begin(); it != grid_[pos].end(); ++it) { set.insert(*it); } } } std::copy(set.begin(), set.end(), back_inserter(*bucket)); } void gstGeoIndexImpl::GetFeatureIdsFromBucket(std::uint32_t row, std::uint32_t col, std::vector<int> &ids) const { // find the desired bucket std::uint32_t gridRow = row - coverage_.extents.beginRow(); std::uint32_t gridCol = col - coverage_.extents.beginCol(); unsigned int pos = (gridRow * coverage_.extents.numCols()) + gridCol; const gstGeoIndexImpl::FeatureBucket &bucket = grid_[pos]; // copy the ids out of the bucket and into the vector ids.reserve(bucket.size()); for (FeatureBucketConstIterator it = bucket.begin(); it != bucket.end(); ++it) { ids.push_back((*box_list_)[*it].feature_id); } } void gstGeoIndexImpl::GetFeatureIdsFromBuckets(const khExtents<std::uint32_t> &extents, std::vector<int> &ids) const { std::set<int> set; std::uint32_t row = extents.beginRow(); std::uint32_t gridRow = row - coverage_.extents.beginRow(); std::uint32_t count = 0; for (; row < extents.endRow(); ++row, ++gridRow) { std::uint32_t col = extents.beginCol(); std::uint32_t gridCol = col - coverage_.extents.beginCol(); for (; col < extents.endCol(); ++col, ++gridCol) { unsigned int pos = (gridRow * coverage_.extents.numCols()) + gridCol; count += grid_[pos].size(); for (FeatureBucketConstIterator it = grid_[pos].begin(); it != grid_[pos].end(); ++it) { set.insert((*box_list_)[*it].feature_id); } } } ids.reserve(count); std::copy(set.begin(), set.end(), back_inserter(ids)); }
37.898132
88
0.641609
tornado12345
ba19174c9228d52be80e77f5d951e96f92245e0f
3,129
cpp
C++
cpp_models/libsrc/RLLib/util/TreeFitted/rtLeaf.cpp
akangasr/sdirl
b8b2bf34fea1b1f0c2f9961a9ad9c1ad34396f5b
[ "MIT" ]
null
null
null
cpp_models/libsrc/RLLib/util/TreeFitted/rtLeaf.cpp
akangasr/sdirl
b8b2bf34fea1b1f0c2f9961a9ad9c1ad34396f5b
[ "MIT" ]
null
null
null
cpp_models/libsrc/RLLib/util/TreeFitted/rtLeaf.cpp
akangasr/sdirl
b8b2bf34fea1b1f0c2f9961a9ad9c1ad34396f5b
[ "MIT" ]
null
null
null
/************************************************************************** * File: rtnode.h * * Description: Basic classes for Tree based algorithms * * Copyright (C) 2007 by Walter Corno & Daniele Dell'Aglio * *************************************************************************** * * * 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 "rtLeaf.h" //<< Sam using namespace PoliFitted; rtLeaf::rtLeaf() { mValue = 0.0; mVariance = 0.0; } /** * Basic constructor * @param val the value to store in the node */ rtLeaf::rtLeaf(Dataset* data) { Fit(data); } rtLeaf::~rtLeaf() { } float rtLeaf::Fit(Dataset* data) { mValue = data->Mean(); #ifdef LEAF_VARIANCE mVariance = data->Variance(); #endif #ifdef SPLIT_ANALYSIS for (unsigned int i = 0; i < data->GetInputSize(); i++) { float min, max, tmp; //initialize min and max with the attribute value of the first observation min = max = data->at(0)->GetInput(i); for (unsigned int c = 1; c < data->size(); c++) { tmp = data->at(c)->GetInput(i); if (tmp < min) min = tmp; else if (tmp > max) max = tmp; } char cmdf[100]; sprintf(cmdf,"+ (x>=%f && x<=%f ? %f : 0)",min,max,(max-min)); mPlotCutsF[i].insert(10,cmdf); char cmdg[100]; sprintf(cmdg,"+ (x>=%f && x<=%f ? %f : 0)",min,max,1.0); mPlotCutsG[i].insert(10,cmdg); char cmds[100]; sprintf(cmds,"+ (x>=%f && x<=%f ? %d : 0)",min,max,data->size()); mPlotCutsS[i].insert(10,cmds); } #endif return 0.0; //data->Variance(); } float rtLeaf::getValue(Tuple* input) { return mValue; } void rtLeaf::WriteOnStream(ofstream& out) { out << "L" << endl; out << mValue << endl; #ifdef LEAF_VARIANCE out << mVariance << endl; #endif } void rtLeaf::ReadFromStream(ifstream& in) { in >> mValue; #ifdef LEAF_VARIANCE in >> mVariance; #endif }
31.29
78
0.489613
akangasr
ba1d8272d8d1e412c8adf2f05a108676b0d219ab
1,913
cpp
C++
src/map/ai/states/trigger_state.cpp
PaulAnthonyReitz/topaz
ffa3a785f86ffdb2f6a5baf9895b649e3e3de006
[ "FTL" ]
6
2021-06-01T04:17:10.000Z
2021-06-01T04:32:21.000Z
src/map/ai/states/trigger_state.cpp
PaulAnthonyReitz/topaz
ffa3a785f86ffdb2f6a5baf9895b649e3e3de006
[ "FTL" ]
4
2020-04-24T18:01:31.000Z
2020-04-27T21:20:03.000Z
src/map/ai/states/trigger_state.cpp
PaulAnthonyReitz/topaz
ffa3a785f86ffdb2f6a5baf9895b649e3e3de006
[ "FTL" ]
1
2020-05-28T21:35:05.000Z
2020-05-28T21:35:05.000Z
/* =========================================================================== Copyright (c) 2010-2015 Darkstar Dev Teams This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ =========================================================================== */ #include "trigger_state.h" #include "../ai_container.h" #include "../../lua/luautils.h" #include "../../entities/charentity.h" #include "../../entities/npcentity.h" CTriggerState::CTriggerState(CBaseEntity* PEntity, uint16 targid) : CState(PEntity, targid) { } bool CTriggerState::Update(time_point tick) { if (!IsCompleted()) { auto PChar = static_cast<CCharEntity*>(GetTarget()); if (PChar && luautils::OnTrigger(PChar, m_PEntity) == -1 && m_PEntity->animation == ANIMATION_CLOSE_DOOR) { close = true; m_PEntity->animation = ANIMATION_OPEN_DOOR; m_PEntity->updatemask |= UPDATE_HP; } Complete(); } else if (close) { if (tick > GetEntryTime() + 7s) { m_PEntity->animation = ANIMATION_CLOSE_DOOR; m_PEntity->updatemask |= UPDATE_HP; return true; } } else { return true; } return false; } bool CTriggerState::CanChangeState() { return false; } bool CTriggerState::CanFollowPath() { return false; }
26.569444
113
0.611605
PaulAnthonyReitz
ba1da601349c51a281e4c132ee1f93cd47ce1b78
9,150
cpp
C++
extensions/ParticleUniverse/CCPUDynamicAttributeTranslator.cpp
lij0511/pandora
5988618f29d2f1ba418ef54a02e227903c1e7108
[ "Apache-2.0" ]
null
null
null
extensions/ParticleUniverse/CCPUDynamicAttributeTranslator.cpp
lij0511/pandora
5988618f29d2f1ba418ef54a02e227903c1e7108
[ "Apache-2.0" ]
null
null
null
extensions/ParticleUniverse/CCPUDynamicAttributeTranslator.cpp
lij0511/pandora
5988618f29d2f1ba418ef54a02e227903c1e7108
[ "Apache-2.0" ]
null
null
null
/**************************************************************************** Copyright (C) 2013 Henry van Merode. All rights reserved. Copyright (c) 2015 Chukong Technologies Inc. http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "CCPUDynamicAttributeTranslator.h" #include "CCPUParticleSystem3D.h" namespace pola { namespace graphic { PUDynamicAttributeTranslator::PUDynamicAttributeTranslator() { } PUDynamicAttributeTranslator::~PUDynamicAttributeTranslator() { } void PUDynamicAttributeTranslator::translate(PUScriptCompiler* compiler, PUAbstractNode *node) { PUObjectAbstractNode* obj = reinterpret_cast<PUObjectAbstractNode*>(node); // The first value is the type std::string type = obj->name; if (type == token[TOKEN_DYN_RANDOM]) { _dynamicAttribute = new (std::nothrow) PUDynamicAttributeRandom(); } else if (type == token[TOKEN_DYN_CURVED_LINEAR]) { _dynamicAttribute = new (std::nothrow) PUDynamicAttributeCurved(); } else if (type == token[TOKEN_DYN_CURVED_SPLINE]) { _dynamicAttribute = new (std::nothrow) PUDynamicAttributeCurved(); } else if (type == token[TOKEN_DYN_OSCILLATE]) { _dynamicAttribute = new (std::nothrow) PUDynamicAttributeOscillate(); } else { // Create a fixed one. _dynamicAttribute = new (std::nothrow) PUDynamicAttributeFixed(); } // Run through properties for(PUAbstractNodeList::iterator i = obj->children.begin(); i != obj->children.end(); ++i) { if((*i)->type == ANT_PROPERTY) { PUPropertyAbstractNode* prop = reinterpret_cast<PUPropertyAbstractNode*>((*i)); if (prop->name == token[TOKEN_DYN_MIN]) { // Property: min if (_dynamicAttribute->getType() == PUDynamicAttribute::DAT_RANDOM) { if (passValidateProperty(compiler, prop, token[TOKEN_DYN_MIN], VAL_REAL)) { float val = 0.0f; if(getFloat(*prop->values.front(), &val)) { (static_cast<PUDynamicAttributeRandom*>(_dynamicAttribute))->setMin(val); } } } } else if (prop->name == token[TOKEN_DYN_MAX]) { // Property: max if (_dynamicAttribute->getType() == PUDynamicAttribute::DAT_RANDOM) { if (passValidateProperty(compiler, prop, token[TOKEN_DYN_MAX], VAL_REAL)) { float val = 0.0f; if(getFloat(*prop->values.front(), &val)) { (static_cast<PUDynamicAttributeRandom*>(_dynamicAttribute))->setMax(val); } } } } else if (prop->name == token[TOKEN_DYN_CONTROL_POINT]) { // Property: control_point if (_dynamicAttribute->getType() == PUDynamicAttribute::DAT_CURVED) { if (passValidateProperty(compiler, prop, token[TOKEN_DYN_CONTROL_POINT], VAL_VECTOR2)) { vec2 val; if(getVector2(prop->values.begin(), prop->values.end(), &val)) { (static_cast<PUDynamicAttributeCurved*>(_dynamicAttribute))->addControlPoint(val.x, val.y); } } } } else if (prop->name == token[TOKEN_DYN_OSCILLATE_FREQUENCY]) { // Property: oscillate_frequency if (_dynamicAttribute->getType() == PUDynamicAttribute::DAT_OSCILLATE) { if (passValidateProperty(compiler, prop, token[TOKEN_DYN_OSCILLATE_FREQUENCY], VAL_REAL)) { float val = 0.0f; if(getFloat(*prop->values.front(), &val)) { (static_cast<PUDynamicAttributeOscillate*>(_dynamicAttribute))->setFrequency(val); } } } } else if (prop->name == token[TOKEN_DYN_OSCILLATE_PHASE]) { // Property: oscillate_phase if (_dynamicAttribute->getType() == PUDynamicAttribute::DAT_OSCILLATE) { if (passValidateProperty(compiler, prop, token[TOKEN_DYN_OSCILLATE_PHASE], VAL_REAL)) { float val = 0.0f; if(getFloat(*prop->values.front(), &val)) { (static_cast<PUDynamicAttributeOscillate*>(_dynamicAttribute))->setPhase(val); } } } } else if (prop->name == token[TOKEN_DYN_OSCILLATE_BASE]) { // Property: oscillate_base if (_dynamicAttribute->getType() == PUDynamicAttribute::DAT_OSCILLATE) { if (passValidateProperty(compiler, prop, token[TOKEN_DYN_OSCILLATE_BASE], VAL_REAL)) { float val = 0.0f; if(getFloat(*prop->values.front(), &val)) { (static_cast<PUDynamicAttributeOscillate*>(_dynamicAttribute))->setBase(val); } } } } else if (prop->name == token[TOKEN_DYN_OSCILLATE_AMPLITUDE]) { // Property: oscillate_amplitude if (_dynamicAttribute->getType() == PUDynamicAttribute::DAT_OSCILLATE) { if (passValidateProperty(compiler, prop, token[TOKEN_DYN_OSCILLATE_AMPLITUDE], VAL_REAL)) { float val = 0.0f; if(getFloat(*prop->values.front(), &val)) { (static_cast<PUDynamicAttributeOscillate*>(_dynamicAttribute))->setAmplitude(val); } } } } else if (prop->name == token[TOKEN_DYN_OSCILLATE_TYPE]) { // Property: oscillate_type if (_dynamicAttribute->getType() == PUDynamicAttribute::DAT_OSCILLATE) { if (passValidateProperty(compiler, prop, token[TOKEN_DYN_OSCILLATE_TYPE], VAL_STRING)) { std::string val; if(getString(*prop->values.front(), &val)) { if (val == token[TOKEN_DYN_SINE]) { (static_cast<PUDynamicAttributeOscillate*>(_dynamicAttribute))->setOscillationType( PUDynamicAttributeOscillate::OSCT_SINE); } else if (val == token[TOKEN_DYN_SQUARE]) { (static_cast<PUDynamicAttributeOscillate*>(_dynamicAttribute))->setOscillationType( PUDynamicAttributeOscillate::OSCT_SQUARE); } } } } } else { errorUnexpectedProperty(compiler, prop); } } else if((*i)->type == ANT_OBJECT) { processNode(compiler, *i); } else { errorUnexpectedToken(compiler, *i); } } // Set it in the context obj->context = _dynamicAttribute; } } /* namespace graphic */ } /* namespace pola */
39.956332
119
0.510055
lij0511
ba1df1adafc5de0b43c0c9a28dd85d9ee750e267
894
cpp
C++
Source/OpenTournament/Slate/UR_ColorSpectrum.cpp
HAARP-art/OpenTournament
1bb188983ba4d013a8ce00bbe1a333f2952814e8
[ "OML" ]
97
2020-05-24T23:09:26.000Z
2022-01-22T13:35:58.000Z
Source/OpenTournament/Slate/UR_ColorSpectrum.cpp
HAARP-art/OpenTournament
1bb188983ba4d013a8ce00bbe1a333f2952814e8
[ "OML" ]
165
2020-05-26T02:42:54.000Z
2022-03-29T11:01:11.000Z
Source/OpenTournament/Slate/UR_ColorSpectrum.cpp
HAARP-art/OpenTournament
1bb188983ba4d013a8ce00bbe1a333f2952814e8
[ "OML" ]
78
2020-05-24T23:10:29.000Z
2022-03-14T13:54:09.000Z
// Copyright (c) 2019-2020 Open Tournament Project, All Rights Reserved. ///////////////////////////////////////////////////////////////////////////////////////////////// #include "UR_ColorSpectrum.h" #include "Widgets/DeclarativeSyntaxSupport.h" #include "Widgets/Colors/SColorSpectrum.h" ///////////////////////////////////////////////////////////////////////////////////////////////// TSharedRef<SWidget> UUR_ColorSpectrum::RebuildWidget() { MyColorSpectrum = SNew(SColorSpectrum) .SelectedColor_UObject(this, &UUR_ColorSpectrum::GetColorHSV) .OnValueChanged(BIND_UOBJECT_DELEGATE(FOnLinearColorValueChanged, HandleColorSpectrumValueChanged)) .OnMouseCaptureBegin(BIND_UOBJECT_DELEGATE(FSimpleDelegate, HandleOnMouseCaptureBegin)) .OnMouseCaptureEnd(BIND_UOBJECT_DELEGATE(FSimpleDelegate, HandleOnMouseCaptureEnd)); return MyColorSpectrum.ToSharedRef(); }
42.571429
102
0.634228
HAARP-art
ba1e5eeee7f9103966150d05258b6d23b6aa8206
8,553
cpp
C++
source/Intro.cpp
TheCyberMonk/scionsofchanneling
7a4695d9c82faa41564e3bfbde87f7f0845f0f3b
[ "MIT" ]
null
null
null
source/Intro.cpp
TheCyberMonk/scionsofchanneling
7a4695d9c82faa41564e3bfbde87f7f0845f0f3b
[ "MIT" ]
null
null
null
source/Intro.cpp
TheCyberMonk/scionsofchanneling
7a4695d9c82faa41564e3bfbde87f7f0845f0f3b
[ "MIT" ]
null
null
null
#include "../include/Being.h" void Intro() { Weapon StarterWeapon; Being Hadgar("Hadgar", "Commander", "NPC", 10, 80, 15, 25, 8, 15, 100, 500); Player hero("Farmer John", "Peasant", 15, 0, 0, 0, 0, 5); Clear(&hero); Paragraph(&hero, "You have been trekking through an arid desert for days, searching for the rumored city of Tyria. It is said to be the last stronghold for the civilization of Ayataria, and probably the last " "hope for mankind. If there exists a safe haven yet in this world, that would be it. The only place where one could hope to make a difference. A darkness has swept over this land for centuries. " "A corruption that turns beasts, men and all life into a wicked and tormented form of existence. The elders say it was all started by very powerful Channelers called The Dark Liches. If that " "is the case though it is already far out of their control. No one really knows however, it could simply be that the gods have grown tired of this mortal plane...\n\nPondering this question your " "feet starts to drag, you're closing your limit. But just as thoughts of giving up start entering your mind, you can make out tall stone walls in the distance. As you move closer the guards " "on top of the wall notices you. They all aim different ranged weaponry at you, all the way from bows to powerful ancient boomsticks. They watch intently as you approach. Eventually, they " " stand down. Most likely assessing that you have no mutations. After a while the gate opens and a tall muscular man with a long ornate cloak approach and address you.", false, false, false, 39); Paragraph(&hero, "\n\"Greetings, it is rare to see anyone wandering alone these days.\"\n\"What is your name?\"", false, false, false, 39); hero.nameSet(GetStringInput(&hero, "", false)); Clear(&hero); Hadgar.Talk(&hero, "\"Welcome " + hero.nameGet() + " to Tyria! A bastion of humanity and a shining beacon of hope! I am Hadgar and I'm the military commander here. " "I'm glad you made the journey, not many do these days.\"\n", false, false, false, 39); Hadgar.Talk(&hero, "\"How did you make it if I may ask? What is your style of combat?\"", false, false, false, 39); int input = 0; hero.yResetSet(hero.yPosGet()); while (input != '1' && input != '2' && input != '3' && input != '4') { hero.yPosReset(); Paragraph(&hero, "1: Berserker\n2: Channeler\n3: Nightblade\n4: Monk\n>", false, false, false, 0); input = getch(); if (input == '1') { Paragraph(&hero, "Berserkers use brute strength to smash their enemies to pieces!\n-Strength focus\n-+2 base attack\n-Can use all armor\n-Keybindings: \'q\'-Whirlwind, \'w\'-Charge, \'e\'-Execute, \'r\'-Rage\n", false, false, false, 0); if (Question(&hero, "Are you sure that you want to be a Berserker?")) { hero.classSet("Berserker"); hero.strMod(3); hero.agiMod(2); hero.intMod(1); StarterWeapon.idTransform(1); hero.equipWeapon(&StarterWeapon); hero.learnSpell(11); hero.learnSpell(12); hero.learnSpell(13); hero.learnSpell(22); hero.Binding[113-97].setBinding(113, "Spell", 11); hero.Binding[119-97].setBinding(119, "Spell", 12); hero.Binding[101-97].setBinding(101, "Spell", 13); hero.Binding[114-97].setBinding(114, "Spell", 22); hero.yPosAdd(2); Hadgar.Talk(&hero, "The need for brutality has never been stronger, you'll fit right in.", false, false, true, 39); } else input = 0; } if (input == '2') { Paragraph(&hero, "Channelers call upon a strength from deep within to manipulate the chaotic energies of this world to their will.\n-Intelligence focus\n-Spell Casting!\n-Can only wear Cloth\n-Keybindings: \'q\'-Sparks, \'w\'-Heal, \'e\'-Mana Barrier, \'r\'-Drain Life\n", false, false, false, 0); if (Question(&hero, "Are you sure that you want to be a Channeler?")) { hero.classSet("Channeler"); hero.intMod(3); hero.agiMod(2); hero.strMod(1); hero.learnSpell(1); hero.learnSpell(3); hero.learnSpell(14); hero.learnSpell(7); hero.Binding[113-97].setBinding(113, "Spell", 1); hero.Binding[119-97].setBinding(119, "Spell", 3); hero.Binding[101-97].setBinding(101, "Spell", 14); hero.Binding[114-97].setBinding(114, "Spell", 7); StarterWeapon.idTransform(2); hero.equipWeapon(&StarterWeapon); Hadgar.Talk(&hero, "You have mastered the channeling of essence? We have few Channelers among us, but they have proven themselves invaluable to the city. Be wary though, some are suspicious and not as appreciative of your arts. ", false, false, true, 39); } else input = 0; } if (input == '3') { Paragraph(&hero, "Nightblades prefer the shadows, often using channeling to enhance their attacks and enchant their blades.\n-No stat focus\n-Bonus to initiative\n-Can wear cloth and leather\n-Keybindings: \'q\'-Ambush, \'w\'-Poison Strike, \'e\'-Enchant Weapon, \'r\'-Devastating Strike\n", false, false, false, 0); if (Question(&hero, "Are you sure that you want to be a Nightblade?")) { hero.classSet("Nightblade"); hero.strMod(2); hero.agiMod(2); hero.intMod(2); hero.learnSpell(15); hero.learnSpell(16); hero.learnSpell(17); hero.learnSpell(18); hero.Binding[113-97].setBinding(113, "Spell", 15); hero.Binding[119-97].setBinding(119, "Spell", 16); hero.Binding[101-97].setBinding(101, "Spell", 17); hero.Binding[114-97].setBinding(114, "Spell", 18); StarterWeapon.idTransform(36); hero.equipWeapon(&StarterWeapon); Hadgar.Talk(&hero, "So you prefer the shadows? The nights have grown long and full of terrors. I'm sure you will feel right at home. *He gives a short chuckle*", false, false, true, 39); } else input = 0; } if (input == '4') { Paragraph(&hero, "Monks study ancient martial techniques to master close quarter combat. \n-Agility focus\n-Quick actions\n-Ki(Mana regens between each fight)\n-Can wear cloth and leather\n-Keybindings: \'q\'-Quick Attack, \'w\'-Dodge, \'e\'-Stunning Strike\n", false, false, false, 0); if (Question(&hero, "Are you sure that you want to be a Monk?")) { hero.classSet("Monk"); hero.agiMod(2); hero.strMod(2); hero.intMod(2); hero.learnSpell(19); hero.learnSpell(20); hero.learnSpell(21); hero.Binding[113-97].setBinding(113, "Spell", 19); hero.Binding[119-97].setBinding(119, "Spell", 20); hero.Binding[101-97].setBinding(101, "Spell", 21); StarterWeapon.idTransform(36); hero.equipWeapon(&StarterWeapon); Hadgar.Talk(&hero, "\nYou walk the nameless path? We are honored to welcome you within our walls.", false, false, true, 39); } else input = 0; } } Clear(&hero); Hadgar.Talk(&hero, "I wanted to welcome you personally, but I am currently re-organizing the city's defences so you will have to excuse me. Please explore the city freely, and then come speak to me if you want to " "contribute to our continued survival. In any case you are free to stay here as long as the city does, the barracks are open to you if you need lodgings. They lay just east of the castle, you can't miss it. \n\n" "Hadgar gives you a smile and a nod, and then returns through the gate. You are left to your own devices. \n\nLarge stone walls encompass the entire city, as well as another smaller set of walls around the castle in the center. Almost everything towers in blinding white and the size of it all leaves you breathless. " "You've never seen anything like it before. It's not surprising that the city still stands.", false, false, false, 39); Paragraph(&hero, "\nThe amount of people is staggering, being a wanderer your whole life you have never seen more than a dozen people gathered, but here in the middle of the city there " "are hundreds of people going about their day. Thousands must live within these walls. After taking a moment, you gather yourself and decide to " "head out and see what other experiences this city has in store. \n\nWhat immediately grabs your attention is the fighting pits. It stands right in the middle of the town square. It's full of people fighting both mutants and each other. There even " "seems to be a system of retractable bar walls to section off the fighting pits so that multiple fights can happen at the same time. And they are currently making good " "use of it. It seems to be the perfect place to hone your skills.", false, false, true, 39); hero.healthMod(hero.maxHealthGet()); hero.manaMod(hero.maxManaGet()); Tyria(&hero); }
57.402685
320
0.698468
TheCyberMonk
ba20f17736135288bf25aaaf0000efd316f08b25
2,286
cpp
C++
src/tools/SceneLoader/SampleComponents/Rotator.cpp
elix22/urho3d-blender-runtime
9c495cb9f1c64e2d904085212bcf59b25e557d76
[ "MIT" ]
2
2020-12-08T06:06:14.000Z
2021-02-14T07:07:14.000Z
src/tools/SceneLoader/SampleComponents/Rotator.cpp
elix22/urho3d-blender-runtime
9c495cb9f1c64e2d904085212bcf59b25e557d76
[ "MIT" ]
1
2019-06-20T18:20:44.000Z
2019-06-20T18:20:44.000Z
src/tools/SceneLoader/SampleComponents/Rotator.cpp
elix22/urho3d-blender-runtime
9c495cb9f1c64e2d904085212bcf59b25e557d76
[ "MIT" ]
3
2019-06-30T16:15:37.000Z
2019-07-12T20:55:41.000Z
// // Copyright (c) 2008-2019 the Urho3D project. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #include "Rotator.h" #include <Urho3D/Urho3DAll.h> Rotator::Rotator(Context* context) : LogicComponent(context), speed_(DEFAULT_ROTATOR_SPEED) { // Only the physics update event is needed: unsubscribe from the rest for optimization SetUpdateEventMask(USE_UPDATE); } void Rotator::RegisterObject(Context* context) { context->RegisterFactory<Rotator>("Sample Component"); // These macros register the class attributes to the Context for automatic load / save handling. // We specify the Default attribute mode which means it will be used both for saving into file, and network replication URHO3D_ATTRIBUTE("Axis", Vector3, axis_ , Vector3::ZERO, AM_FILE); URHO3D_ATTRIBUTE("Speed", float, speed_, DEFAULT_ROTATOR_SPEED, AM_FILE); } void Rotator::DelayedStart() { // init whatever you want. at this point all nodes are already handled URHO3D_LOGINFO("STARTED"); int a=0; } void Rotator::Update(float timeStep) { node_->Rotate(Quaternion(axis_.x_*speed_*timeStep,axis_.y_*speed_*timeStep,axis_.z_*speed_*timeStep)); // do the logic here }
38.745763
124
0.730534
elix22
ba21becb6ad3a280b98362166f360fc852755dd3
4,590
cpp
C++
Tools/RemoteProtocolBridge/Source/ProtocolProcessor/ProtocolProcessor_Abstract.cpp
dbaudio-soundscape/Support-Generic-OSC-DiGiCo
54943f3d797844665644215da70bf7ee3a5bee64
[ "Xnet", "RSA-MD", "X11" ]
null
null
null
Tools/RemoteProtocolBridge/Source/ProtocolProcessor/ProtocolProcessor_Abstract.cpp
dbaudio-soundscape/Support-Generic-OSC-DiGiCo
54943f3d797844665644215da70bf7ee3a5bee64
[ "Xnet", "RSA-MD", "X11" ]
null
null
null
Tools/RemoteProtocolBridge/Source/ProtocolProcessor/ProtocolProcessor_Abstract.cpp
dbaudio-soundscape/Support-Generic-OSC-DiGiCo
54943f3d797844665644215da70bf7ee3a5bee64
[ "Xnet", "RSA-MD", "X11" ]
null
null
null
/* =============================================================================== Copyright (C) 2019 d&b audiotechnik GmbH & Co. KG. All Rights Reserved. This file is part of RemoteProtocolBridge. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY d&b audiotechnik GmbH & Co. KG "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. =============================================================================== */ #include "ProtocolProcessor_Abstract.h" #include "../ProcessingEngineNode.h" // ************************************************************************************** // class ProtocolProcessor_Abstract // ************************************************************************************** /** * @fn bool ProtocolProcessor_Abstract::Start() * Pure virtual function to start the derived processor object */ /** * @fn bool ProtocolProcessor_Abstract::Stop() * Pure virtual function to stop the derived processor object */ /** * @fn void ProtocolProcessor_Abstract::SetRemoteObjectsActive(const Array<RemoteObject>& Objs) * @param Objs The objects to set for active handling * Pure virtual function to set a set of remote object to be activly handled by derived processor object */ /** * @fn bool ProtocolProcessor_Abstract::SendMessage(RemoteObjectIdentifier Id, RemoteObjectMessageData& msgData) * @param Id The object id to send a message for * @param msgData The actual message value/content data * Pure virtual function to trigger sending a message by derived processor object */ /** * Constructor of abstract class ProtocolProcessor_Abstract. */ ProtocolProcessor_Abstract::ProtocolProcessor_Abstract() { m_type = ProtocolType::PT_Invalid; m_IsRunning = false; m_messageListener = nullptr; } /** * Destructor */ ProtocolProcessor_Abstract::~ProtocolProcessor_Abstract() { } /** * Sets the message listener object to be used for callback on message received. * * @param messageListener The listener object */ void ProtocolProcessor_Abstract::AddListener(Listener *messageListener) { m_messageListener = messageListener; } /** * Sets the configuration data for the protocol processor object. * * @param protocolData The configuration data struct with config data * @param activeObjs The objects to use as 'active' for this protocol * @param NId The node id of the parent node this protocol processing object is child of (needed to access data from config) * @param PId The protocol id of this protocol processing object (needed to access data from config) */ void ProtocolProcessor_Abstract::SetProtocolConfigurationData(const ProcessingEngineConfig::ProtocolData& protocolData, const Array<RemoteObject>& activeObjs, NodeId NId, ProtocolId PId) { m_parentNodeId = NId; m_protocolProcessorId = PId; m_ipAddress = protocolData.IpAddress; m_clientPort = protocolData.ClientPort; m_hostPort = protocolData.HostPort; if (protocolData.UsesActiveRemoteObjects) SetRemoteObjectsActive(activeObjs); } /** * Getter for the type of this protocol processing object * * @return The type of this protocol processing object */ ProtocolType ProtocolProcessor_Abstract::GetType() { return m_type; } /** * Getter for the id of this protocol processing object * * @return The id of this protocol processing object */ ProtocolId ProtocolProcessor_Abstract::GetId() { return m_protocolProcessorId; }
34.772727
186
0.726797
dbaudio-soundscape
ba22b6778ec9e6f7b5c30820a081e0696c16a7c2
1,907
cc
C++
lib/src/facts/posix/identity_resolver.cc
hkenney/facter
7856a75a6d5e637f90018ff91111d6e75df608dc
[ "Apache-2.0" ]
null
null
null
lib/src/facts/posix/identity_resolver.cc
hkenney/facter
7856a75a6d5e637f90018ff91111d6e75df608dc
[ "Apache-2.0" ]
null
null
null
lib/src/facts/posix/identity_resolver.cc
hkenney/facter
7856a75a6d5e637f90018ff91111d6e75df608dc
[ "Apache-2.0" ]
null
null
null
#include <internal/facts/posix/identity_resolver.hpp> #include <leatherman/logging/logging.hpp> #include <sys/types.h> #include <unistd.h> #include <pwd.h> #include <grp.h> using namespace std; namespace facter { namespace facts { namespace posix { identity_resolver::data identity_resolver::collect_data(collection& facts) { data result; vector<char> buffer; long buffer_size = sysconf(_SC_GETPW_R_SIZE_MAX); if (buffer_size == -1) { buffer.resize(1024); } else { buffer.resize(buffer_size); } uid_t uid = geteuid(); struct passwd pwd; struct passwd *pwd_ptr; int err = getpwuid_r(uid, &pwd, buffer.data(), buffer.size(), &pwd_ptr); if (err != 0) { LOG_WARNING("getpwuid_r failed: %1% (%2%)", strerror(err), err); } else if (pwd_ptr == NULL) { LOG_WARNING("effective uid %1% does not have a passwd entry.", uid); } else { result.user_id = static_cast<int64_t>(uid); result.user_name = pwd.pw_name; result.privileged = (uid == 0); } buffer_size = sysconf(_SC_GETGR_R_SIZE_MAX); if (buffer_size == -1) { buffer.resize(1024); } else { buffer.resize(buffer_size); } gid_t gid = getegid(); struct group grp; struct group *grp_ptr; err = getgrgid_r(gid, &grp, buffer.data(), buffer.size(), &grp_ptr); if (err != 0) { LOG_WARNING("getgrgid_r failed: %1% (%2%)", strerror(err), err); } else if (grp_ptr == NULL) { LOG_WARNING("effective gid %1% does not have a group entry.", gid); } else { result.group_id = static_cast<int64_t>(gid); result.group_name = grp.gr_name; } return result; } }}} // facter::facts::posix
28.893939
80
0.563188
hkenney
ba23ab00ac0f89bcc80affc5dc61265de02c73ac
602
cpp
C++
Solutions/Count Primes/main.cpp
Crayzero/LeetCodeProgramming
b10ebe22c0de1501722f0f5c934c0c1902a26789
[ "MIT" ]
1
2015-04-13T10:58:30.000Z
2015-04-13T10:58:30.000Z
Solutions/Count Primes/main.cpp
Crayzero/LeetCodeProgramming
b10ebe22c0de1501722f0f5c934c0c1902a26789
[ "MIT" ]
null
null
null
Solutions/Count Primes/main.cpp
Crayzero/LeetCodeProgramming
b10ebe22c0de1501722f0f5c934c0c1902a26789
[ "MIT" ]
null
null
null
#include <iostream> #include <unordered_map> using namespace std; class Solution { public: int countPrimes(int n) { int *m = new int[n]; for(int i = 0; i < n; i++) m[i] = 0; int res = 0; int i = 2; while(1) { for(; m[i] == 1 && i < n; i++); cout<<i<<endl; if (i >= n) break; res += 1; for(int k = 1; i * k < n; k++) { m[i * k] = 1; } } delete [] m; return res; } }; int main() { Solution s; cout<<s.countPrimes(4); return 0; }
18.242424
44
0.390365
Crayzero
ba269c4b8589c258115b5b470f432c614a11e178
2,749
cpp
C++
WeatherData.cpp
eb3nezer/WeatherOrNot
a2653676f59429c6204ea13023d4e9fa6681b1dc
[ "MIT", "Unlicense" ]
null
null
null
WeatherData.cpp
eb3nezer/WeatherOrNot
a2653676f59429c6204ea13023d4e9fa6681b1dc
[ "MIT", "Unlicense" ]
null
null
null
WeatherData.cpp
eb3nezer/WeatherOrNot
a2653676f59429c6204ea13023d4e9fa6681b1dc
[ "MIT", "Unlicense" ]
null
null
null
// Copyright (c) 2014 Ben Kelley. // // MIT License http://opensource.org/licenses/MIT #include "WeatherData.h" WeatherData::WeatherData() { int loop; for(loop = 0; loop < MAX_DATA_FIELDS; loop++) { key[loop] = -1; value[loop] = 0; dataIsSet[loop] = false; multiplier[loop] = 1; } } void WeatherData::setDataField(int field, int valueIn) { // Find where this is already set, or an empty slot bool found = false; int loop; for (loop = 0; loop < MAX_DATA_FIELDS && !found; loop++) { if (key[loop] == field || key[loop] == -1) { found = true; value[loop] = valueIn; dataIsSet[loop] = true; multiplier[loop] = 1; key[loop] = field; } } } void WeatherData::setDataField(int field, float valueIn, int multiplierIn) { // Find where this is already set, or an empty slot bool found = false; int loop; for (loop = 0; loop < MAX_DATA_FIELDS && !found; loop++) { if (key[loop] == field || key[loop] == -1) { found = true; value[loop] = valueIn * (float) multiplierIn; dataIsSet[loop] = true; multiplier[loop] = multiplierIn; key[loop] = field; } } } void WeatherData::clearDataFields() { bool found = false; for (int loop = MAX_DATA_FIELDS; loop >= 0; loop--) { key[loop] = -1; dataIsSet[loop] = false; } } int WeatherData::getDataAsInt(int fieldIn) { int result = 0; bool found = false; for (int loop = 0; loop < MAX_DATA_FIELDS && !found; loop++) { if (key[loop] == fieldIn) { found = true; if (dataIsSet[loop]) { result = value[loop]; } } } return result; } float WeatherData::getDataAsFloat(int fieldIn) { float result = 0.0; bool found = false; for (int loop = 0; loop < MAX_DATA_FIELDS && !found; loop++) { if (key[loop] == fieldIn) { found = true; if (dataIsSet[loop]) { result = (float) value[loop] / (float) multiplier[loop]; } } } return result; } bool WeatherData::isSet(int fieldIn) { bool result = false; bool found = false; for (int loop = 0; loop < MAX_DATA_FIELDS && !found; loop++) { if (key[loop] == fieldIn || key[loop] == -1) { found = true; if (key[loop] == fieldIn) { result = dataIsSet[loop]; } } } return result; } //void WeatherData::setSensorName(char *name) { // strcpy(sensorName, name); //} //char * WeatherData::getSensorName() { // return sensorName; //}
24.544643
76
0.524918
eb3nezer
ba27650ab2356c5a89808861b1650ac09c61f3a1
1,450
cpp
C++
Source/modules/credentialmanager/Credential.cpp
prepare/Blink_only_permissive_lic_files
8b3acc51c7ae8b074d2e2b610d0d9295d9a1ecb4
[ "BSD-3-Clause" ]
null
null
null
Source/modules/credentialmanager/Credential.cpp
prepare/Blink_only_permissive_lic_files
8b3acc51c7ae8b074d2e2b610d0d9295d9a1ecb4
[ "BSD-3-Clause" ]
null
null
null
Source/modules/credentialmanager/Credential.cpp
prepare/Blink_only_permissive_lic_files
8b3acc51c7ae8b074d2e2b610d0d9295d9a1ecb4
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "config.h" #include "modules/credentialmanager/Credential.h" #include "bindings/core/v8/ExceptionState.h" #include "core/dom/ExceptionCode.h" namespace blink { Credential* Credential::create(const String& id, const String& name, const KURL& avatar) { return new Credential(id, name, avatar); } Credential* Credential::create(const String& id, const String& name, const String& avatar, ExceptionState& exceptionState) { KURL avatarURL = parseStringAsURL(avatar, exceptionState); if (exceptionState.hadException()) return nullptr; return new Credential(id, name, avatarURL); } Credential::Credential(PlatformCredential* credential) : m_platformCredential(credential) { } Credential::Credential(const String& id, const String& name, const KURL& avatar) : m_platformCredential(PlatformCredential::create(id, name, avatar)) { } KURL Credential::parseStringAsURL(const String& url, ExceptionState& exceptionState) { if (url.isEmpty()) return KURL(); KURL parsedURL = KURL(KURL(), url); if (!parsedURL.isValid()) exceptionState.throwDOMException(SyntaxError, "'" + url + "' is not a valid URL."); return parsedURL; } DEFINE_TRACE(Credential) { visitor->trace(m_platformCredential); } } // namespace blink
27.884615
122
0.728966
prepare
ba2b36aba42288ce43537cffa23f8a5ee7e3a024
435
cpp
C++
cpp_lib/src/cpp_lib.cpp
hoelzl/cpp_binding_example
a00b9aee81998095f4d944dae58260e0062a7a9e
[ "MIT" ]
null
null
null
cpp_lib/src/cpp_lib.cpp
hoelzl/cpp_binding_example
a00b9aee81998095f4d944dae58260e0062a7a9e
[ "MIT" ]
null
null
null
cpp_lib/src/cpp_lib.cpp
hoelzl/cpp_binding_example
a00b9aee81998095f4d944dae58260e0062a7a9e
[ "MIT" ]
null
null
null
#include "cpp_lib.hpp" #include <iostream> int add1_with_c_interface(int arg) { return arg + 1; } namespace bex { void print_cpp_binding_example_info() { std::cout << "Project Info\n\n"; std::cout << " name: cpp_binding_example\n"; std::cout << " namespace: bex\n"; } std::string MyClass::get_name() { return name; } void MyClass::set_name(std::string name) { this->name = std::move(name); } } // namespace bex
22.894737
74
0.657471
hoelzl
ba2b522c7c7cb88fb266449d00674235d8241e3e
1,833
cpp
C++
aml.cpp
RusJJ/AndroidModLoader
981978237f020d571dac752e44ab9d70358f8156
[ "MIT" ]
10
2021-08-16T04:22:53.000Z
2022-02-14T01:22:23.000Z
aml.cpp
RusJJ/AndroidModLoader
981978237f020d571dac752e44ab9d70358f8156
[ "MIT" ]
null
null
null
aml.cpp
RusJJ/AndroidModLoader
981978237f020d571dac752e44ab9d70358f8156
[ "MIT" ]
4
2021-08-20T00:03:16.000Z
2022-02-04T10:29:53.000Z
#include <include/aml.h> #include <ARMPatch.h> #include <include/modslist.h> extern char g_szAppName[0xFF]; extern char g_szCfgPath[0xFF]; extern char g_szAndroidDataDir[0xFF]; extern const char* g_szDataDir; const char* AML::GetCurrentGame() { return g_szAppName; } const char* AML::GetConfigPath() { return g_szCfgPath; } const char* AML::GetDataPath() { return g_szDataDir; } const char* AML::GetAndroidDataPath() { return g_szAndroidDataDir; } bool AML::HasMod(const char* szGUID) { return modlist->HasMod(szGUID); } bool AML::HasModOfVersion(const char* szGUID, const char* szVersion) { return modlist->HasModOfVersion(szGUID, szVersion); } uintptr_t AML::GetLib(const char* szLib) { return ARMPatch::getLib(szLib); } uintptr_t AML::GetSym(void* handle, const char* sym) { return ARMPatch::getSym(handle, sym); } uintptr_t AML::GetSym(uintptr_t libAddr, const char* sym) { return ARMPatch::getSym(libAddr, sym); } bool AML::Hook(void* handle, void* fnAddress, void** orgFnAddress) { return ARMPatch::hookInternal(handle, fnAddress, orgFnAddress); } void AML::HookPLT(void* handle, void* fnAddress, void** orgFnAddress) { ARMPatch::hookPLTInternal(handle, fnAddress, orgFnAddress); } int AML::Unprot(uintptr_t handle, size_t len) { return ARMPatch::unprotect(handle, len); } void AML::Write(uintptr_t dest, uintptr_t src, size_t size) { ARMPatch::write(dest, src, size); } void AML::Read(uintptr_t src, uintptr_t dest, size_t size) { ARMPatch::read(src, dest, size); } void AML::PlaceNOP(uintptr_t addr, size_t count) { ARMPatch::NOP(addr, count); } void AML::PlaceJMP(uintptr_t addr, uintptr_t dest) { ARMPatch::JMP(addr, dest); } void AML::PlaceRET(uintptr_t addr) { ARMPatch::RET(addr); } static AML amlLocal; IAML* aml = (IAML*)&amlLocal;
19.09375
69
0.71413
RusJJ
ba2c5d62cce6403a906aa3785e4a28cc546fb9d4
11,175
cpp
C++
src/Hooks/QuickplayHooks.cpp
okibcn/MultiQuestensions
7c78cad89f88639c8a0ad9a1e124e9beedbe3e9a
[ "MIT" ]
null
null
null
src/Hooks/QuickplayHooks.cpp
okibcn/MultiQuestensions
7c78cad89f88639c8a0ad9a1e124e9beedbe3e9a
[ "MIT" ]
null
null
null
src/Hooks/QuickplayHooks.cpp
okibcn/MultiQuestensions
7c78cad89f88639c8a0ad9a1e124e9beedbe3e9a
[ "MIT" ]
1
2022-01-25T12:54:01.000Z
2022-01-25T12:54:01.000Z
#include "main.hpp" #include "Hooks/Hooks.hpp" #include "GlobalFields.hpp" #include "GlobalNamespace/MasterServerQuickPlaySetupData_QuickPlaySongPacksOverride_PredefinedPack.hpp" #include "GlobalNamespace/MasterServerQuickPlaySetupData_QuickPlaySongPacksOverride_LocalizedCustomPack.hpp" #include "GlobalNamespace/MasterServerQuickPlaySetupData_QuickPlaySongPacksOverride_LocalizedCustomPackName.hpp" #include "GlobalNamespace/MasterServerQuickPlaySetupData_QuickPlaySongPacksOverride.hpp" #include "GlobalNamespace/MasterServerQuickPlaySetupData.hpp" #include "GlobalNamespace/SongPackMaskModelSO.hpp" #include "GlobalNamespace/MultiplayerModeSelectionFlowCoordinator.hpp" #include "GlobalNamespace/JoinQuickplayViewController.hpp" #include "GlobalNamespace/SimpleDialogPromptViewController.hpp" #include "GlobalNamespace/MultiplayerModeSettings.hpp" #include "HMUI/ViewController_AnimationDirection.hpp" #include "HMUI/ViewController_AnimationType.hpp" #include "Polyglot/Localization.hpp" #include "Polyglot/LanguageExtensions.hpp" #include "GlobalNamespace/QuickPlaySongPacksDropdown.hpp" using namespace GlobalNamespace; using MSQSD_QPSPO_PredefinedPack = MasterServerQuickPlaySetupData::QuickPlaySongPacksOverride::PredefinedPack; using MSQSD_QPSPO_LocalizedCustomPack = MasterServerQuickPlaySetupData::QuickPlaySongPacksOverride::LocalizedCustomPack; using MSQD_QPSPO_LocalizedCustomPackName = MasterServerQuickPlaySetupData::QuickPlaySongPacksOverride::LocalizedCustomPackName; namespace MultiQuestensions { // Add our custom Packs MAKE_HOOK_MATCH(QuickPlaySongPacksDropdown_LazyInit, &QuickPlaySongPacksDropdown::LazyInit, void, QuickPlaySongPacksDropdown* self) { if (!self->dyn__initialized()) { if (self->dyn__quickPlaySongPacksOverride() == nullptr) self->dyn__quickPlaySongPacksOverride() = GlobalNamespace::MasterServerQuickPlaySetupData::QuickPlaySongPacksOverride::New_ctor(); self->dyn__quickPlaySongPacksOverride()->dyn_localizedCustomPacks() = System::Collections::Generic::List_1<GlobalNamespace::MasterServerQuickPlaySetupData::QuickPlaySongPacksOverride::LocalizedCustomPack*>::New_ctor(); if (self->dyn__quickPlaySongPacksOverride()->dyn_predefinedPackIds() == nullptr) self->dyn__quickPlaySongPacksOverride()->dyn_predefinedPackIds() = System::Collections::Generic::List_1<GlobalNamespace::MasterServerQuickPlaySetupData::QuickPlaySongPacksOverride::PredefinedPack*>::New_ctor(); //BUILT_IN_LEVEL_PACKS MSQSD_QPSPO_PredefinedPack* builtin = MSQSD_QPSPO_PredefinedPack::New_ctor(); builtin->dyn_order() = 1; builtin->dyn_packId() = il2cpp_utils::newcsstr("BUILT_IN_LEVEL_PACKS"); //ALL_LEVEL_PACKS MSQSD_QPSPO_PredefinedPack* all = MSQSD_QPSPO_PredefinedPack::New_ctor(); all->dyn_order() = 3; all->dyn_packId() = il2cpp_utils::newcsstr("ALL_LEVEL_PACKS"); self->dyn__quickPlaySongPacksOverride()->dyn_predefinedPackIds()->Add(builtin); self->dyn__quickPlaySongPacksOverride()->dyn_predefinedPackIds()->Add(all); MSQSD_QPSPO_LocalizedCustomPack* custom = MSQSD_QPSPO_LocalizedCustomPack::New_ctor(); custom->dyn_order() = 2; //newPack->dyn_order() = self->dyn__quickPlaySongPacksOverride()->dyn_localizedCustomPacks()->get_Count() + 1; custom->dyn_serializedName() = il2cpp_utils::newcsstr("custom_levelpack_CustomLevels"); MSQD_QPSPO_LocalizedCustomPackName* custom_packName_Default; custom_packName_Default = MSQD_QPSPO_LocalizedCustomPackName::New_ctor(); custom_packName_Default->dyn_packName() = il2cpp_utils::newcsstr("All + Custom Levels"); Polyglot::Language currentLang = Polyglot::Localization::get_Instance()->get_SelectedLanguage(); custom_packName_Default->dyn_language() = Polyglot::LanguageExtensions::ToSerializedName(currentLang); custom->dyn_localizedNames() = Array<GlobalNamespace::MasterServerQuickPlaySetupData::QuickPlaySongPacksOverride::LocalizedCustomPackName*>::New( { custom_packName_Default } ); custom->dyn_packIds()->Add(il2cpp_utils::newcsstr("custom_levelpack_CustomLevels")); //custom->dyn_packIds()->Add(self->dyn__songPackMaskModel()->ToSerializedName(SongPackMask::get_all())); //getLogger().debug("SongPackMask All serializedName: %s", to_utf8(csstrtostr(self->dyn__songPackMaskModel()->ToSerializedName(SongPackMask::get_all()))).c_str()); self->dyn__quickPlaySongPacksOverride()->dyn_localizedCustomPacks()->Add(custom); //MSQSD_QPSPO_LocalizedCustomPack* test = MSQSD_QPSPO_LocalizedCustomPack::New_ctor(); //test->dyn_order() = 4; ////newPack->dyn_order() = self->dyn__quickPlaySongPacksOverride()->dyn_localizedCustomPacks()->get_Count() + 1; //test->dyn_serializedName() = il2cpp_utils::newcsstr("test"); //MSQD_QPSPO_LocalizedCustomPackName* test_packName_En = MSQD_QPSPO_LocalizedCustomPackName::New_ctor(); //test_packName_En->dyn_language() = il2cpp_utils::newcsstr("en"); //test_packName_En->dyn_packName() = il2cpp_utils::newcsstr("Test"); //MSQD_QPSPO_LocalizedCustomPackName* test_packName_De = MSQD_QPSPO_LocalizedCustomPackName::New_ctor(); //test_packName_De->dyn_language() = il2cpp_utils::newcsstr("de"); //test_packName_De->dyn_packName() = il2cpp_utils::newcsstr("Test"); //test->dyn_localizedNames() = Array<GlobalNamespace::MasterServerQuickPlaySetupData::QuickPlaySongPacksOverride::LocalizedCustomPackName*>::New( // { test_packName_En, test_packName_De } //); //test->dyn_packIds()->Add(il2cpp_utils::newcsstr("OstVol1")); //test->dyn_packIds()->Add(il2cpp_utils::newcsstr("OstVol4")); //test->dyn_packIds()->Add(il2cpp_utils::newcsstr("PanicAtTheDisco")); //::Array<GlobalNamespace::IBeatmapLevelPack*>* ostAndExtraCollection = self->dyn__songPackMaskModel()->dyn__ostAndExtrasCollection()->get_beatmapLevelPacks(); //for (int i = 0; i < ostAndExtraCollection->Length(); i++) { // getLogger().debug("ostAndExtra Pack: '%s'", to_utf8(csstrtostr(ostAndExtraCollection->get(i)->get_packID())).c_str()); //} //::Array<GlobalNamespace::IBeatmapLevelPack*>* dlcCollection = self->dyn__songPackMaskModel()->dyn__dlcCollection()->get_beatmapLevelPacks(); //for (int i = 0; i < dlcCollection->Length(); i++) { // getLogger().debug("dlc Pack: '%s'", to_utf8(csstrtostr(dlcCollection->get(i)->get_packID())).c_str()); //} //self->dyn__quickPlaySongPacksOverride()->dyn_localizedCustomPacks()->Add(test); } //for (int i = 0; i < self->dyn__songPackMaskModel()->dyn__defaultSongPackMaskItems()->get_Count(); i++) { // ::Il2CppString* pack = self->dyn__songPackMaskModel()->dyn__defaultSongPackMaskItems()->get_Item(i); // getLogger().debug("defaultSongPackMaskItems name: %s", to_utf8(csstrtostr(pack)).c_str()/*, pack->dyn_order()*/); // //for (int j = 0; j < pack->dyn_packIds()->get_Count(); j++) { // // getLogger().debug("packId: %s", to_utf8(csstrtostr(pack->dyn_packIds()->get_Item(j))).c_str()); // //} //} //for (int i = 0; i < self->dyn__songPackMaskModel()->dyn__defaultSongPackMaskItems()->get_Count(); i++) { // ::Il2CppString* pack = self->dyn__songPackMaskModel()->dyn__defaultSongPackMaskItems()->get_Item(i); // getLogger().debug("defaultSongPackMaskItems serializedName: %s", to_utf8(csstrtostr(pack)).c_str()/*, pack->dyn_order()*/); // //for (int j = 0; j < pack->dyn_packIds()->get_Count(); j++) { // // getLogger().debug("packId: %s", to_utf8(csstrtostr(pack->dyn_packIds()->get_Item(j))).c_str()); // //} //} QuickPlaySongPacksDropdown_LazyInit(self); //for (int i = 0; i < self->dyn__quickPlaySongPacksOverride()->dyn_localizedCustomPacks()->get_Count(); i++) { // MSQSD_QPSPO_LocalizedCustomPack* pack = self->dyn__quickPlaySongPacksOverride()->dyn_localizedCustomPacks()->get_Item(i); // getLogger().debug("LocalizedPack serializedName: %s, order: %d", to_utf8(csstrtostr(pack->dyn_serializedName())).c_str(), pack->dyn_order()); // for (int j = 0; j < pack->dyn_packIds()->get_Count(); j++) { // getLogger().debug("packId: %s", to_utf8(csstrtostr(pack->dyn_packIds()->get_Item(j))).c_str()); // } //} } MAKE_HOOK_MATCH(MultiplayerModeSelectionFlowCoordinator_HandleJoinQuickPlayViewControllerDidFinish, &MultiplayerModeSelectionFlowCoordinator::HandleJoinQuickPlayViewControllerDidFinish, void, MultiplayerModeSelectionFlowCoordinator* self, bool success) { if (success && to_utf8(csstrtostr(self->dyn__joinQuickPlayViewController()->dyn__multiplayerModeSettings()->dyn_quickPlaySongPackMaskSerializedName())) == "custom_levelpack_CustomLevels") { self->dyn__simpleDialogPromptViewController()->Init( il2cpp_utils::newcsstr("Custom Song Quickplay"), il2cpp_utils::newcsstr("<color=#ff0000>This category includes songs of varying difficulty.\nIt may be more enjoyable to play in a private lobby with friends."), il2cpp_utils::newcsstr("Continue"), il2cpp_utils::newcsstr("Cancel"), il2cpp_utils::MakeDelegate<System::Action_1<int>*>(classof(System::Action_1<int>*), (std::function<void(int)>)[self, success](int btnId) { switch (btnId) { default: case 0: // Continue MultiplayerModeSelectionFlowCoordinator_HandleJoinQuickPlayViewControllerDidFinish(self, success); return; case 1: // Cancel //self->DismissViewController(self->dyn__simpleDialogPromptViewController(), HMUI::ViewController::AnimationDirection::Vertical, nullptr, false); self->ReplaceTopViewController(self->dyn__joinQuickPlayViewController(), nullptr, HMUI::ViewController::AnimationType::In, HMUI::ViewController::AnimationDirection::Vertical); return; } } ) ); self->ReplaceTopViewController(self->dyn__simpleDialogPromptViewController(), nullptr, HMUI::ViewController::AnimationType::In, HMUI::ViewController::AnimationDirection::Vertical); } else MultiplayerModeSelectionFlowCoordinator_HandleJoinQuickPlayViewControllerDidFinish(self, success); } void Hooks::QuickplayHooks() { INSTALL_HOOK(getLogger(), QuickPlaySongPacksDropdown_LazyInit); INSTALL_HOOK(getLogger(), MultiplayerModeSelectionFlowCoordinator_HandleJoinQuickPlayViewControllerDidFinish); } }
63.494318
258
0.697539
okibcn
ba2d367602f25e8aad14e7bb6dee1e23e4b864ae
1,111
hpp
C++
include/nudb/file.hpp
movitto/NuDB
79c1dcaec8aa54d93979fb56c66ab4d925eda29c
[ "BSL-1.0" ]
279
2016-08-24T18:50:33.000Z
2022-01-17T22:28:17.000Z
include/nudb/file.hpp
movitto/NuDB
79c1dcaec8aa54d93979fb56c66ab4d925eda29c
[ "BSL-1.0" ]
61
2016-08-23T23:26:00.000Z
2019-04-04T22:26:26.000Z
include/nudb/file.hpp
movitto/NuDB
79c1dcaec8aa54d93979fb56c66ab4d925eda29c
[ "BSL-1.0" ]
44
2016-08-25T19:17:03.000Z
2021-09-10T08:14:00.000Z
// // Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef NUDB_FILE_HPP #define NUDB_FILE_HPP #include <boost/core/ignore_unused.hpp> #include <cstddef> #include <string> namespace nudb { /// The type used to hold paths to files using path_type = std::string; /** Returns the best guess at the volume's block size. @param path A path to a file on the device. The file does not need to exist. */ inline std::size_t block_size(path_type const& path) { boost::ignore_unused(path); // A reasonable default for many SSD devices return 4096; } /** File create and open modes. These are used by @ref native_file. */ enum class file_mode { /// Open the file for sequential reads scan, /// Open the file for random reads read, /// Open the file for random reads and appending writes append, /// Open the file for random reads and writes write }; } // nudb #endif
19.839286
79
0.693069
movitto
ba2ebc46b22d1c7714d09740a4a250f1fb2284a8
3,114
cpp
C++
source/engine/physics_joint_component.cpp
Lauvak/ray
906d3991ddd232a7f78f0e51f29aeead008a139a
[ "BSD-3-Clause" ]
113
2015-06-25T06:24:59.000Z
2021-09-26T02:46:02.000Z
source/engine/physics_joint_component.cpp
Lauvak/ray
906d3991ddd232a7f78f0e51f29aeead008a139a
[ "BSD-3-Clause" ]
2
2015-05-03T07:22:49.000Z
2017-12-11T09:17:20.000Z
source/engine/physics_joint_component.cpp
Lauvak/ray
906d3991ddd232a7f78f0e51f29aeead008a139a
[ "BSD-3-Clause" ]
17
2015-11-10T15:07:15.000Z
2021-01-19T15:28:16.000Z
// +---------------------------------------------------------------------- // | Project : ray. // | All rights reserved. // +---------------------------------------------------------------------- // | Copyright (c) 2013-2017. // +---------------------------------------------------------------------- // | * Redistribution and use of this software 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 ray team, nor the names of its // | contributors may be used to endorse or promote products // | derived from this software without specific prior // | written permission of the ray team. // | // | 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 <ray/physics_joint_component.h> #include <ray/physics_body_component.h> _NAME_BEGIN __ImplementSubInterface(PhysicsJointComponent, GameComponent, "PhysicsJoint") PhysicsJointComponent::PhysicsJointComponent() noexcept { } PhysicsJointComponent::~PhysicsJointComponent() noexcept { } void PhysicsJointComponent::setConnectRigidbody(PhysicsBodyComponentPtr body) noexcept { if (_body != body) { _body = body; if (this->getGameObject()) this->onBodyChange(); } } PhysicsBodyComponentPtr PhysicsJointComponent::getConnectRigidbody() const noexcept { return _body; } void PhysicsJointComponent::load(iarchive& reader) noexcept { } void PhysicsJointComponent::save(archivebuf& write) noexcept { } PhysicsBody* PhysicsJointComponent::getRawRigidbody() const noexcept { auto body = this->getComponent<PhysicsBodyComponent>(); if (body) return body->getPhysicsBody(); return nullptr; } PhysicsBody* PhysicsJointComponent::getRawConnectRigidbody() const noexcept { if (_body) return _body->getPhysicsBody(); return nullptr; } void PhysicsJointComponent::onBodyChange() noexcept { } _NAME_END
30.529412
81
0.678548
Lauvak
ba2ecb2eabc008d4751f6e023b7e991c1818bd1d
32,233
hpp
C++
include/geometricks/data_structure/kd_tree.hpp
mitthy/TCC
4c48eb11cafd50334c5faef93edc5f03bc7fc171
[ "MIT" ]
null
null
null
include/geometricks/data_structure/kd_tree.hpp
mitthy/TCC
4c48eb11cafd50334c5faef93edc5f03bc7fc171
[ "MIT" ]
null
null
null
include/geometricks/data_structure/kd_tree.hpp
mitthy/TCC
4c48eb11cafd50334c5faef93edc5f03bc7fc171
[ "MIT" ]
null
null
null
#ifndef GEOMETRICKS_DATA_STRUCTURE_KD_TREE_HPP #define GEOMETRICKS_DATA_STRUCTURE_KD_TREE_HPP //C++ stdlib includes #include <functional> #include <type_traits> #include <algorithm> #include <queue> #include <vector> //Project includes #include "dimensional_traits.hpp" #include "geometricks/meta/utils.hpp" #include "geometricks/memory/allocator.hpp" #include "internal/small_vector.hpp" /** * @file Implements a cache friendly kd tree stored as an array. */ namespace geometricks { /** * @brief Cache friendly kd tree data structure * @tparam T The stored data type. * @tparam Compare Function that compares all the different data types stored in each dimension of the data so we can build the tree. * If the stored data type T is a std::tuple<int, std::string, float>, the function should be able to compare ( int, int ), ( std::string, std::string ), * ( float, float ) so we can work on all different dimensions. * @details This kd tree is stored as an array in memory. This gives better cache locality than node based kd trees. The elements are stored in the nodes. * Since it is extremely hard to balance a kd tree and it hurts performance to build a new one in each element insertion, insertion opperations are not allowed. * @see geometricks::dimension::dimensional_traits and @ref geometricks::dimension::get_t "geometricks::dimension::get" for a guide on how to use this struct with user defined types. * @see https://en.wikipedia.org/wiki/K-d_tree for a quick reference on kd tree. * @todo Static assert on compare so we know it can sort in all dimensions. * @todo noexcept and constexpr anotations. * @todo Add threshold neighbors to find all elements below threshold distance to efficiently implement collision detection algorithms. Maybe? */ template< typename T, typename Compare = std::less<> > struct kd_tree : private Compare { private: struct __heap_compare__ { template< typename DistanceType > constexpr bool operator()( const std::pair<T*, DistanceType>& lhs, const std::pair<T*, DistanceType>& rhs ) const noexcept { return lhs.second < rhs.second; } }; public: //Constructor /** * @brief Constructs a kd tree with a range of elements * @param begin Iterator to first element of the input range. * @param end Iterator to the last element of the input range or sentinel value. * @param comp Compare function to use for the kd tree. Should be able to sort objects in different dimensions. If not supplied, default constructs it. * @param alloc Memory allocator to use. Defaults to the default allocator. See also geometricks::allocator. * @pre If Sentinel is an iterator, first < last. Else, eventually first != last compares false. * @details Constructs a kd tree with the data supplied by the range [ begin, end ). * * @note Complexity: @b O(n log n) * @see https://en.wikipedia.org/wiki/K-d_tree#Complexity * @todo Supply paper on kd tree construction. */ template< typename InputIterator, typename Sentinel > kd_tree( InputIterator begin, Sentinel end, Compare comp = Compare{}, geometricks::allocator alloc = geometricks::allocator{} ): Compare( comp ), m_allocator( alloc ), m_size( std::distance( begin, end ) ), m_data_array( ( T* ) m_allocator.allocate( sizeof( T ) * m_size ) ) { __construct_kd_tree__<0>( begin, end, 0, m_size ); } /** * @brief Constructs a kd tree with a range of elements * @param begin Iterator to first element of the input range. * @param end Iterator to the last element of the input range or sentinel value. * @param comp Placeholder used to call the default constructor for the Compare template parameter. See also geometricks::default_compare_t. * @param alloc Memory allocator to use. Defaults to the default allocator. See also geometricks::allocator. * @pre If Sentinel is an iterator, first < last. Else, eventually first != last compares false. * @details Constructs a kd tree with the data supplied by the range [ begin, end ). * * @note Complexity: @b O(n log n) * @see https://en.wikipedia.org/wiki/K-d_tree#Complexity * @todo Supply paper on kd tree construction. */ template< typename InputIterator, typename Sentinel > kd_tree( InputIterator begin, Sentinel end, geometricks::default_compare_t comp, geometricks::allocator alloc = geometricks::allocator{} ): m_allocator( alloc ), m_size( std::distance( begin, end ) ), m_data_array( ( T* ) m_allocator.allocate( sizeof( T ) * m_size ) ) { ( void ) comp; //Silence warnings and errors. __construct_kd_tree__<0>( begin, end, 0, m_size ); } //Copy constructor /** * @brief Copy constructs a kd tree. * @param rhs Right hand side of the copy operation. * @param alloc Memory allocator to use. Defaults to the default allocator. See also geometricks::allocator * @details Performs a deep copy of the right hand side parameter. * @note Complexity: @b O(n) */ kd_tree( const kd_tree& rhs, geometricks::allocator alloc = geometricks::allocator{} ): Compare( rhs ), m_allocator( alloc ), m_size( rhs.m_size ), m_data_array( ( T* ) m_allocator.allocate( sizeof( T ) * m_size ) ) { std::copy( rhs.m_data_array, rhs.m_data_array + m_size, m_data_array ); } //Move constructor /** * @brief Move constructs a kd tree. * @param rhs Right hand side of the move operation. * @post Invalidates rhs. Any use of rhs after move is an error. * @details Moves the data from rhs into this. * @note Complexity: @b O(1) */ kd_tree( kd_tree&& rhs ): Compare( std::move( rhs ) ), m_allocator( rhs.m_allocator ), m_size( rhs.m_size ), m_data_array( rhs.m_data_array ) { rhs.m_data_array = nullptr; } //Copy assignment /** * @brief Copy assigns a kd tree. * @param rhs Right hand side of the copy operation. * @details Performs a deep copy of the right hand side parameter. Destroys the previous kd tree and allocates memory to construct rhs into this. * @note Complexity: @b O(n) * @todo Change this method so we only allocate if the buffer isn't large enough. * @todo Maybe we can get the strong exception guarantee here... */ kd_tree& operator=( const kd_tree& rhs ) { if( &rhs != this ) { //TODO: optimize to only allocate new buffer in case old capacity wasn't enough. //TODO: exception guarantee. Compare::operator=( rhs ); T* new_buff = ( T* ) m_allocator.allocate( sizeof( T ) * rhs.m_size ); std::copy( rhs.m_data_array, rhs.m_data_array + rhs.m_size, new_buff ); __destroy__(); m_data_array = new_buff; m_size = rhs.m_size; } return *this; } //Move assignment /** * @brief Move assigns a kd tree. * @param rhs Right hand side of the move operation. * @post Invalidates rhs. Any use of rhs after move is an error. * @details Moves the data from rhs into this. * @note Complexity: @b O(1) */ kd_tree& operator=( kd_tree&& rhs ) { if( &rhs != this ) { Compare::operator=( std::move( rhs ) ); __destroy__(); m_data_array = rhs.m_data_array; m_size = rhs.m_size; m_allocator = rhs.m_allocator; rhs.m_data_array = nullptr; } return *this; } ~kd_tree() { __destroy__(); } /** * @brief Finds the nearest neighbor of an input point. * @param point The input point to query. * @param f Point distance function object. Should be able to compare 2 points and return a size type as well as * compare 2 points in a specific dimension and return a size type with the following signature: operator()( const T& left, T& right, dimension::dimension_t<Index> ) const noexcept. * Also, distance( point1, point2 ) should be equal to distance( point2, point1 ). * @details Computes the nearest neighbor of a given input point given the distance function. The default distance is the euclidean distance of the points without computing * the square root to save on efficiency, since if sqrt( euclid_distance_no_sqrt_root(a, b) < euclid_distance_no_sqrt_root(a, c) ), euclid_distance_no_sqrt_root(a, b) < euclid_distance_no_sqrt_root(a, c). * * Example: * @code{.cpp} * std::vector<std::tuple<int, int, int>> input_vector; ... geometricks::kd_tree<std::tuple<int, int, int>> tree{ input_vector.begin(), input_vector.end() }; struct manhattan_distance_t { template< typename T, int N > size_t operator()( const T& lhs, const T& rhs, dimension::dimension_t<N> ) { return geometricks::algorithm::absolute_difference( geometricks::dimension::get( lhs, dimension::dimension_v<N> ), geometricks::dimension::get( rhs, dimension::dimension_v<N> ) ); } template< typename T > size_t operator()( const T& lhs, const T& rhs ) { return distance_impl( lhs, rhs, std::make_index_sequence<dimension::dimensional_traits<T>::dimensions>() ); } template< typename T, int... I > size_t distance_impl( const T& lhs, const T& rhs, std::index_sequence<I...> ) { return ( this->operator()( lhs, rhs, dimension_v<I> ) + ... ); } }; auto [nearest, distance] = tree.nearest_neighbor( std::make_tuple( 10, 10, 10 ), manhattan_distance_t{} ); * @endcode * @todo Add references. * @todo Add complexity. * @todo Allow searching for threshold on nearest neighbor. Could be useful for code like collision detection. */ template< typename DistanceFunction = dimension::euclidean_distance > auto nearest_neighbor( const T& point, DistanceFunction f = DistanceFunction{} ) const noexcept { using distance_t = std::decay_t<decltype(f( std::declval<T>(), std::declval<T>() ))>; distance_t best = meta::numeric_limits<distance_t>::max(); T* closest = nullptr; __nearest_neighbor_impl__<0>( point, __root__(), &closest, best, f ); return std::pair<const T&, distance_t>( *closest, best ); } /** * @brief Finds the k nearest neighbors of an input point and returns a vector containing them and their distances. * @param point The input point to query. * @param K the number of desired output points. * @param f Point distance function object. Should be able to compare 2 points and return a size type as well as * compare 2 points in a specific dimension and return a size type with the following signature: operator()( const T& left, T& right, dimension::dimension_t<Index> ) const noexcept. * Also, distance( point1, point2 ) should be equal to distance( point2, point1 ). * @return A vector containing the output points as well as the distance calculated from the input point. * @details Computes the k nearest neighbor of a given input point given the distance function. The default distance is the euclidean distance of the points without computing * the square root to save on efficiency, since if sqrt( euclid_distance_no_sqrt_root(a, b) < euclid_distance_no_sqrt_root(a, c) ), euclid_distance_no_sqrt_root(a, b) < euclid_distance_no_sqrt_root(a, c). * The points are returned in ascending order. * Example: * @code{.cpp} * std::vector<std::tuple<int, int, int>> input_vector; ... geometricks::kd_tree<std::tuple<int, int, int>> tree{ input_vector.begin(), input_vector.end() }; struct manhattan_distance_t { template< typename T, int N > size_t operator()( const T& lhs, const T& rhs, dimension::dimension_t<N> ) { return geometricks::algorithm::absolute_difference( geometricks::dimension::get( lhs, dimension::dimension_v<N> ), geometricks::dimension::get( rhs, dimension::dimension_v<N> ) ); } template< typename T > size_t operator()( const T& lhs, const T& rhs ) { return distance_impl( lhs, rhs, std::make_index_sequence<dimension::dimensional_traits<T>::dimensions>() ); } template< typename T, int... I > size_t distance_impl( const T& lhs, const T& rhs, std::index_sequence<I...> ) { return ( this->operator()( lhs, rhs, dimension_v<I> ) + ... ); } }; auto output_vector = tree.k_nearest_neighbor( std::make_tuple( 10, 10, 10 ), 4, manhattan_distance_t{} ); //output_vector now contains the 4 nearest neighbors of [10, 10, 10]. * @endcode * @todo Add references. * @todo Add complexity. * @todo Allow searching for threshold on nearest neighbor. Could be useful for code like collision detection. * @todo Improve performance by using a stack allocated vector as the max heeap, only fallbacking to the heap in case of a big K. * @todo Allow alternative version of this function to receive the number of neighbors as a template parameter. Could be useful with a stack allocated vector. * @todo Make a new version of this function that doesn't require an output_col as a parameter but simply returns a vector. */ template< typename DistanceFunction = dimension::euclidean_distance > auto k_nearest_neighbor( const T& point, uint32_t K, DistanceFunction f = DistanceFunction{} ) -> std::vector<std::pair<T, std::decay_t<decltype(f( std::declval<T>(), std::declval<T>() ))>>> { using distance_t = std::decay_t<decltype(f( std::declval<T>(), std::declval<T>() ))>; std::vector<std::pair<T, distance_t>> output_col; output_col.reserve( K ); std::priority_queue<std::pair<T*, distance_t>, small_vector<std::pair<T*, distance_t>, 11>, __heap_compare__> max_heap; __k_nearest_neighbor_impl__<0, DistanceFunction, distance_t>( point, __root__(), K, max_heap, f ); while( !max_heap.empty() ) { auto& element = max_heap.top(); meta::add_element( std::make_pair( *element.first, element.second ), output_col ); max_heap.pop(); } std::reverse( output_col.begin(), output_col.end() ); return output_col; } /** * @brief Performs a range query on the collection. * @param min_point Data containing the minimum values of the query. * @param max_point Data containing the maximum values of the query. * @return Vector containing all points in range. * @details Computes and gathers all given points that lie within the region min_point and max_point and outputs them in a vector. * Since the majority of the time is spent searching the tree for the output points, the algorithm first preprocess the input data so that there is no need for a precondition * that the minimum point contains all the minimum values. Instead, the algorithm sorts both points before processing. * Example: * @code{.cpp} std::vector<std::tuple<int, int, int>> input_vector; ... geometricks::kd_tree<std::tuple<int, int, int>> tree( input_vector.begin(), input_vector.end() ); auto output_vector = tree.range_search( std::make_tuple( 0, 50, 300 ), std::make_tuple( 57, 51, 500 ) ); //output_vector now contains all points between [0-57, 50-51, 300-500] from tree. @endcode * @todo Allow the user to input don't care values into the minimum and maximum point. Would need a new data structure for that. */ std::vector<T> range_search( T min_point, T max_point ) { std::vector<T> output_col; __organize_data__( min_point, max_point, std::make_index_sequence<DATA_DIMENSIONS>() ); __range_search_impl__<0>( min_point, max_point, __root__(), output_col ); return output_col; } private: geometricks::allocator m_allocator; int32_t m_size; T* m_data_array; static constexpr int DATA_DIMENSIONS = dimension::dimensional_traits<T>::dimensions; struct node_t { int32_t m_index; int32_t m_block_size; operator bool() const { return m_block_size; } }; void __destroy__() { if( m_data_array != nullptr ) { for( int32_t i = 0; i < m_size; ++i ) { m_data_array[ i ].~T(); } m_allocator.deallocate( m_data_array ); } } template< int Dimension, typename DistanceFunction, typename DistanceType > void __nearest_neighbor_impl__( const T& point, const node_t& cur_node, T** closest, DistanceType& best_distance, DistanceFunction f ) const { constexpr size_t NextDimension = ( Dimension + 1 ) % DATA_DIMENSIONS; auto compare_function = [this]( const T& left, const T& right ) { return Compare::operator()( dimension::get( left, dimension::dimension_v<Dimension> ), dimension::get( right, dimension::dimension_v<Dimension> ) ); }; auto distance_function = [ &f ]( auto&& lhs, auto&& rhs ) { constexpr int I = Dimension; if constexpr( __detail__::has_dimension_compare<DistanceFunction, T, T, I> ) { return f( std::forward<decltype( lhs )>( lhs ), std::forward<decltype( rhs )>( rhs ), dimension::dimension_v<I> ); } else if constexpr( __detail__::has_dimension_compare<DistanceFunction, T, dimension::type_at<T, I>, I> ) { return f( std::forward<decltype( lhs )>( lhs ), dimension::get( std::forward<decltype( rhs )>( rhs ), dimension::dimension_v<I> ), dimension::dimension_v<I> ); } else if constexpr( __detail__::has_dimension_compare<DistanceFunction, dimension::type_at<T, I>, T, I> ) { return f( dimension::get( std::forward<decltype( lhs )>( lhs ), dimension::dimension_v<I> ), std::forward<decltype( rhs )>( rhs ), dimension::dimension_v<I> ); } else if constexpr( __detail__::has_dimension_compare<DistanceFunction, dimension::type_at<T, I>, dimension::type_at<T, I>, I> ) { return f( dimension::get( std::forward<decltype( lhs )>( lhs ), dimension::dimension_v<I> ), dimension::get( std::forward<decltype( rhs )>( rhs ), dimension::dimension_v<I> ), dimension::dimension_v<I> ); } else { static_assert( __detail__::has_value_compare<DistanceFunction, dimension::type_at<T, I>, dimension::type_at<T, I>>, "Please supply a dimension compare, a value, value, dimension compare or a value compare." ); return f( dimension::get( std::forward<decltype( lhs )>( lhs ), dimension::dimension_v<I> ), dimension::get( std::forward<decltype( rhs )>( rhs ), dimension::dimension_v<I> ) ); } }; if( compare_function( point, m_data_array[ cur_node.m_index ] ) ) { //The point is to the left of the current axis. //Recurse left... auto left_child = __left_child__( cur_node ); if( left_child ) { __nearest_neighbor_impl__<NextDimension>( point, left_child, closest, best_distance, f ); } //Now we get the distance from the point to the current node. auto distance = f( point, m_data_array[ cur_node.m_index ] ); //If the distance is better than our current best distance, update it. if( distance < best_distance ) { best_distance = distance; *closest = &m_data_array[ cur_node.m_index ]; } //If we have another branch to search... auto right_child = __right_child__( cur_node ); if( right_child ) { //Finally, check the distance to the hyperplane. auto distance_to_hyperplane = distance_function( point, m_data_array[ cur_node.m_index ] ); if( distance_to_hyperplane < best_distance ) { __nearest_neighbor_impl__<NextDimension>( point, right_child, closest, best_distance, f ); } } } else { //The point is to the right of the current axis. //Recurse right.. auto right_child = __right_child__( cur_node ); if( right_child ) { __nearest_neighbor_impl__<NextDimension>( point, right_child, closest, best_distance, f ); } //Now we get the distance from the point to the current node. auto distance = f( point, m_data_array[ cur_node.m_index ] ); //If the distance is better than our current best distance, update it. if( distance < best_distance ) { best_distance = distance; *closest = &m_data_array[ cur_node.m_index ]; } //If we have another branch to search... auto left_child = __left_child__( cur_node ); if( left_child ) { //Finally, check the distance to the hyperplane. auto distance_to_hyperplane = distance_function( point, m_data_array[ cur_node.m_index ] ); if( distance_to_hyperplane < best_distance ) { __nearest_neighbor_impl__<NextDimension>( point, left_child, closest, best_distance, f ); } } } } template< int Dimension, typename DistanceFunction, typename DistanceType > void __k_nearest_neighbor_impl__( const T& point, const node_t& node, uint32_t K, std::priority_queue<std::pair<T*, DistanceType>, small_vector<std::pair<T*, DistanceType>, 11>, __heap_compare__>& max_heap, DistanceFunction f ) { constexpr size_t NextDimension = ( Dimension + 1 ) % DATA_DIMENSIONS; auto compare_function = [this]( const T& left, const T& right ) { return Compare::operator()( dimension::get( left, dimension::dimension_v<Dimension> ), dimension::get( right, dimension::dimension_v<Dimension> ) ); }; auto distance_function = [ &f ]( auto&& lhs, auto&& rhs ) { constexpr int I = Dimension; if constexpr( __detail__::has_dimension_compare<DistanceFunction, T, T, I> ) { return f( std::forward<decltype( lhs )>( lhs ), std::forward<decltype( rhs )>( rhs ), dimension::dimension_v<I> ); } else if constexpr( __detail__::has_dimension_compare<DistanceFunction, T, dimension::type_at<T, I>, I> ) { return f( std::forward<decltype( lhs )>( lhs ), dimension::get( std::forward<decltype( rhs )>( rhs ), dimension::dimension_v<I> ), dimension::dimension_v<I> ); } else if constexpr( __detail__::has_dimension_compare<DistanceFunction, dimension::type_at<T, I>, T, I> ) { return f( dimension::get( std::forward<decltype( lhs )>( lhs ), dimension::dimension_v<I> ), std::forward<decltype( rhs )>( rhs ), dimension::dimension_v<I> ); } else if constexpr( __detail__::has_dimension_compare<DistanceFunction, dimension::type_at<T, I>, dimension::type_at<T, I>, I> ) { return f( dimension::get( std::forward<decltype( lhs )>( lhs ), dimension::dimension_v<I> ), dimension::get( std::forward<decltype( rhs )>( rhs ), dimension::dimension_v<I> ), dimension::dimension_v<I> ); } else { static_assert( __detail__::has_value_compare<DistanceFunction, dimension::type_at<T, I>, dimension::type_at<T, I>>, "Please supply a dimension compare, a value, value, dimension compare or a value compare." ); return f( dimension::get( std::forward<decltype( lhs )>( lhs ), dimension::dimension_v<I> ), dimension::get( std::forward<decltype( rhs )>( rhs ), dimension::dimension_v<I> ) ); } }; if( compare_function( point, m_data_array[ node.m_index ] ) ) { auto left_child = __left_child__( node ); if( left_child ) { __k_nearest_neighbor_impl__<NextDimension, DistanceFunction, DistanceType>( point, left_child, K, max_heap, f ); } auto distance = f( point, m_data_array[ node.m_index ] ); auto heap_element = std::make_pair( &m_data_array[ node.m_index ], distance ); max_heap.push( heap_element ); if( ( uint32_t )max_heap.size() > K ) { max_heap.pop(); } auto right_child = __right_child__( node ); if( right_child ) { auto distance_to_hyperplane = distance_function( point, m_data_array[ node.m_index ] ); if( ( uint32_t )max_heap.size() < K || distance_to_hyperplane < max_heap.top().second ) { __k_nearest_neighbor_impl__<NextDimension, DistanceFunction, DistanceType>( point, right_child, K, max_heap, f ); } } } else { auto right_child = __right_child__( node ); if( right_child ) { __k_nearest_neighbor_impl__<NextDimension, DistanceFunction, DistanceType>( point, right_child, K, max_heap, f ); } auto distance = f( point, m_data_array[ node.m_index ] ); auto heap_element = std::make_pair( &m_data_array[ node.m_index ], distance ); max_heap.push( heap_element ); if( ( uint32_t )max_heap.size() > K ) { max_heap.pop(); } auto left_child = __left_child__( node ); if( left_child ) { auto distance_to_hyperplane = distance_function( point, m_data_array[ node.m_index ] ); if( ( uint32_t )max_heap.size() < K || distance_to_hyperplane < max_heap.top().second ) { __k_nearest_neighbor_impl__<NextDimension, DistanceFunction, DistanceType>( point, left_child, K, max_heap, f ); } } } } template< int Dimension, typename InputIterator, typename Sentinel > void __construct_kd_tree__( InputIterator begin, Sentinel end, int32_t startind_index, int32_t blocksize ) { if( begin != end ) { constexpr size_t NextDimension = ( Dimension + 1 ) % DATA_DIMENSIONS; auto middle = begin; int step = blocksize >> 1; int32_t insert_index = startind_index + step; std::advance( middle, step ); auto less_function = [this]( const T& left, const T& right ) { return Compare::operator()( dimension::get( left, dimension::dimension_v<Dimension> ), dimension::get( right, dimension::dimension_v<Dimension> ) ); }; std::nth_element( begin, middle ,end, less_function ); new ( &m_data_array[ insert_index ] ) T{ *middle }; __construct_kd_tree__<NextDimension>( begin, middle, startind_index, step ); std::advance( middle, 1 ); __construct_kd_tree__<NextDimension>( middle, end, insert_index + 1, blocksize - step - 1 ); } } template< typename _T > constexpr bool __compare__( const _T& first, const _T& second ) const { return Compare::operator()( first, second ); } node_t __root__() const { return { m_size >> 1, m_size }; } static node_t __left_child__( node_t node ) { int32_t count_left = node.m_block_size >> 1; int32_t index_left = ( node.m_index - ( count_left >> 1 ) - ( count_left & 1 ) ); return { index_left, count_left }; } static node_t __right_child__( node_t node ) { int32_t count_right = ( node.m_block_size >> 1 ) - !( node.m_block_size & 1 ); int32_t index_right = ( node.m_index + ( count_right >> 1 ) + 1 ); return { index_right, count_right }; } T& __get__( node_t node ) { return m_data_array[ node.m_index ]; } const T& __get__( node_t node ) const { return m_data_array[ node.m_index ]; } template< size_t... Is > void __organize_data__( T& first, T& second, std::index_sequence<Is...> ) { ( __swap_if_greater__( dimension::get( first, dimension::dimension_v<Is> ), dimension::get( second, dimension::dimension_v<Is> ) ), ... ); } template< typename DataType > void __swap_if_greater__( DataType& first, DataType& second ) { if( !Compare::operator()( first, second ) ) { using std::swap; swap( first, second ); } } template< int CurrentDimension, typename Collection > void __range_search_impl__( const T& min_point, const T& max_point, node_t current_node, Collection& output_collection ) { T& current_point = m_data_array[ current_node.m_index ]; constexpr int NextDimension = ( CurrentDimension + 1 ) % DATA_DIMENSIONS; if( Compare::operator()( dimension::get( current_point, dimension::dimension_v<CurrentDimension> ), dimension::get( min_point, dimension::dimension_v<CurrentDimension> ) ) ) { //If we're to the "left" side of the minimum value, we can discard the left children of this node since all of them would be on the left as well. node_t next_node = __right_child__( current_node ); if( next_node ) { __range_search_impl__<NextDimension>( min_point, max_point, next_node, output_collection ); } } else if( Compare::operator()( dimension::get( max_point, dimension::dimension_v<CurrentDimension> ), dimension::get( current_point, dimension::dimension_v<CurrentDimension> ) ) ) { //If we're to the "right" side of the maximum value, we can discard the right children of this node since all of them would be on the right as well. node_t next_node = __left_child__( current_node ); if( next_node ) { __range_search_impl__<NextDimension>( min_point, max_point, next_node, output_collection ); } } else { //If we're within the actual range, we have to check both children. //Also, note that we only have to check other dimensions in the actual data if we're actually inside the range. If we're not in the range, it is not needed. if( __is_inside_bounding_box__<CurrentDimension>( current_point, min_point, max_point) ) { meta::add_element( m_data_array[ current_node.m_index ], output_collection ); } node_t left_child = __left_child__( current_node ); if( left_child ) { __range_search_impl__<NextDimension>( min_point, max_point, left_child, output_collection ); } node_t right_child = __right_child__( current_node ); if( right_child ) { __range_search_impl__<NextDimension>( min_point, max_point, right_child, output_collection ); } } } template< int CurrentDimension > constexpr bool __is_inside_bounding_box__( const T& point, const T& min_point, const T& max_point ) { return __is_inside_bounding_box_helper__<CurrentDimension>( point, min_point, max_point, std::make_index_sequence<DATA_DIMENSIONS>{} ); } template< int CurrentDimension, size_t... Is > constexpr bool __is_inside_bounding_box_helper__( const T& point, const T& min_point, const T& max_point, std::index_sequence<Is...> ) { return ( __is_inside_interval__<CurrentDimension, Is>( dimension::get( point, dimension::dimension_v<Is> ), dimension::get( min_point, dimension::dimension_v<Is> ), dimension::get( max_point, dimension::dimension_v<Is> ) ) && ... ); } template< int CurrentDimension, int Index, typename DataType > constexpr bool __is_inside_interval__( const DataType& point, const DataType& min, const DataType& max ) { if constexpr( CurrentDimension == Index ) { return true; } else { return point >= min && point <= max; } } }; } #endif //GEOMETRICKS_DATA_STRUCTURE_MULTIDIMENSIONAL_kd_tree_HPP
52.156958
238
0.64012
mitthy
ba2f84ded1865910eb68a65561049c52615cddf2
19,601
cpp
C++
src/fios.cpp
trademarks/OpenTTD
fd7fca73cf61a2960e8df8fa221b179d23ae3ef0
[ "Unlicense" ]
8
2016-10-21T09:01:43.000Z
2021-05-31T06:32:14.000Z
src/fios.cpp
blackberry/OpenTTD
fd7fca73cf61a2960e8df8fa221b179d23ae3ef0
[ "Unlicense" ]
null
null
null
src/fios.cpp
blackberry/OpenTTD
fd7fca73cf61a2960e8df8fa221b179d23ae3ef0
[ "Unlicense" ]
4
2017-05-16T00:15:58.000Z
2020-08-06T01:46:31.000Z
/* $Id$ */ /* * This file is part of OpenTTD. * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2. * OpenTTD 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 OpenTTD. If not, see <http://www.gnu.org/licenses/>. */ /** * @file fios.cpp * This file contains functions for building file lists for the save/load dialogs. */ #include "stdafx.h" #include "fios.h" #include "fileio_func.h" #include "tar_type.h" #include "screenshot.h" #include "string_func.h" #include <sys/stat.h> #ifndef WIN32 # include <unistd.h> #endif /* WIN32 */ #include "table/strings.h" /* Variables to display file lists */ SmallVector<FiosItem, 32> _fios_items; static char *_fios_path; SmallFiosItem _file_to_saveload; SortingBits _savegame_sort_order = SORT_BY_DATE | SORT_DESCENDING; /* OS-specific functions are taken from their respective files (win32/unix/os2 .c) */ extern bool FiosIsRoot(const char *path); extern bool FiosIsValidFile(const char *path, const struct dirent *ent, struct stat *sb); extern bool FiosIsHiddenFile(const struct dirent *ent); extern void FiosGetDrives(); extern bool FiosGetDiskFreeSpace(const char *path, uint64 *tot); /* get the name of an oldstyle savegame */ extern void GetOldSaveGameName(const char *file, char *title, const char *last); /** * Compare two FiosItem's. Used with sort when sorting the file list. * @param da A pointer to the first FiosItem to compare. * @param db A pointer to the second FiosItem to compare. * @return -1, 0 or 1, depending on how the two items should be sorted. */ int CDECL CompareFiosItems(const FiosItem *da, const FiosItem *db) { int r = 0; if ((_savegame_sort_order & SORT_BY_NAME) == 0 && da->mtime != db->mtime) { r = da->mtime < db->mtime ? -1 : 1; } else { r = strcasecmp(da->title, db->title); } if (_savegame_sort_order & SORT_DESCENDING) r = -r; return r; } /** Free the list of savegames. */ void FiosFreeSavegameList() { _fios_items.Clear(); _fios_items.Compact(); } /** * Get descriptive texts. Returns the path and free space * left on the device * @param path string describing the path * @param total_free total free space in megabytes, optional (can be NULL) * @return StringID describing the path (free space or failure) */ StringID FiosGetDescText(const char **path, uint64 *total_free) { *path = _fios_path; return FiosGetDiskFreeSpace(*path, total_free) ? STR_SAVELOAD_BYTES_FREE : STR_ERROR_UNABLE_TO_READ_DRIVE; } /** * Browse to a new path based on the passed \a item, starting at #_fios_path. * @param *item Item telling us what to do. * @return A filename w/path if we reached a file, otherwise \c NULL. */ const char *FiosBrowseTo(const FiosItem *item) { char *path = _fios_path; switch (item->type) { case FIOS_TYPE_DRIVE: #if defined(WINCE) snprintf(path, MAX_PATH, PATHSEP ""); #elif defined(WIN32) || defined(__OS2__) snprintf(path, MAX_PATH, "%c:" PATHSEP, item->title[0]); #endif /* FALL THROUGH */ case FIOS_TYPE_INVALID: break; case FIOS_TYPE_PARENT: { /* Check for possible NULL ptr (not required for UNIXes, but AmigaOS-alikes) */ char *s = strrchr(path, PATHSEPCHAR); if (s != NULL && s != path) { s[0] = '\0'; // Remove last path separator character, so we can go up one level. } s = strrchr(path, PATHSEPCHAR); if (s != NULL) { s[1] = '\0'; // go up a directory #if defined(__MORPHOS__) || defined(__AMIGAOS__) /* On MorphOS or AmigaOS paths look like: "Volume:directory/subdirectory" */ } else if ((s = strrchr(path, ':')) != NULL) { s[1] = '\0'; #endif } break; } case FIOS_TYPE_DIR: strcat(path, item->name); strcat(path, PATHSEP); break; case FIOS_TYPE_DIRECT: snprintf(path, MAX_PATH, "%s", item->name); break; case FIOS_TYPE_FILE: case FIOS_TYPE_OLDFILE: case FIOS_TYPE_SCENARIO: case FIOS_TYPE_OLD_SCENARIO: case FIOS_TYPE_PNG: case FIOS_TYPE_BMP: return item->name; } return NULL; } /** * Construct a filename from its components in destination buffer \a buf. * @param buf Destination buffer. * @param path Directory path, may be \c NULL. * @param name Filename. * @param ext Filename extension (use \c "" for no extension). * @param size Size of \a buf. */ static void FiosMakeFilename(char *buf, const char *path, const char *name, const char *ext, size_t size) { const char *period; /* Don't append the extension if it is already there */ period = strrchr(name, '.'); if (period != NULL && strcasecmp(period, ext) == 0) ext = ""; #if defined(__MORPHOS__) || defined(__AMIGAOS__) if (path != NULL) { unsigned char sepchar = path[(strlen(path) - 1)]; if (sepchar != ':' && sepchar != '/') { snprintf(buf, size, "%s" PATHSEP "%s%s", path, name, ext); } else { snprintf(buf, size, "%s%s%s", path, name, ext); } } else { snprintf(buf, size, "%s%s", name, ext); } #else snprintf(buf, size, "%s" PATHSEP "%s%s", path, name, ext); #endif } /** * Make a save game or scenario filename from a name. * @param buf Destination buffer for saving the filename. * @param name Name of the file. * @param size Length of buffer \a buf. */ void FiosMakeSavegameName(char *buf, const char *name, size_t size) { const char *extension = (_game_mode == GM_EDITOR) ? ".scn" : ".sav"; FiosMakeFilename(buf, _fios_path, name, extension, size); } /** * Construct a filename for a height map. * @param buf Destination buffer. * @param name Filename. * @param size Size of \a buf. */ void FiosMakeHeightmapName(char *buf, const char *name, size_t size) { char ext[5]; ext[0] = '.'; strecpy(ext + 1, GetCurrentScreenshotExtension(), lastof(ext)); FiosMakeFilename(buf, _fios_path, name, ext, size); } /** * Delete a file. * @param name Filename to delete. */ bool FiosDelete(const char *name) { char filename[512]; FiosMakeSavegameName(filename, name, lengthof(filename)); return unlink(filename) == 0; } typedef FiosType fios_getlist_callback_proc(SaveLoadDialogMode mode, const char *filename, const char *ext, char *title, const char *last); /** * Scanner to scan for a particular type of FIOS file. */ class FiosFileScanner : public FileScanner { SaveLoadDialogMode mode; ///< The mode we want to search for fios_getlist_callback_proc *callback_proc; ///< Callback to check whether the file may be added public: /** * Create the scanner * @param mode The mode we are in. Some modes don't allow 'parent'. * @param callback_proc The function that is called where you need to do the filtering. */ FiosFileScanner(SaveLoadDialogMode mode, fios_getlist_callback_proc *callback_proc) : mode(mode), callback_proc(callback_proc) {} /* virtual */ bool AddFile(const char *filename, size_t basepath_length); }; /** * Try to add a fios item set with the given filename. * @param filename the full path to the file to read * @param basepath_length amount of characters to chop of before to get a relative filename * @return true if the file is added. */ bool FiosFileScanner::AddFile(const char *filename, size_t basepath_length) { const char *ext = strrchr(filename, '.'); if (ext == NULL) return false; char fios_title[64]; fios_title[0] = '\0'; // reset the title; FiosType type = this->callback_proc(this->mode, filename, ext, fios_title, lastof(fios_title)); if (type == FIOS_TYPE_INVALID) return false; for (const FiosItem *fios = _fios_items.Begin(); fios != _fios_items.End(); fios++) { if (strcmp(fios->name, filename) == 0) return false; } FiosItem *fios = _fios_items.Append(); #ifdef WIN32 struct _stat sb; if (_tstat(OTTD2FS(filename), &sb) == 0) { #else struct stat sb; if (stat(filename, &sb) == 0) { #endif fios->mtime = sb.st_mtime; } else { fios->mtime = 0; } fios->type = type; strecpy(fios->name, filename, lastof(fios->name)); /* If the file doesn't have a title, use its filename */ const char *t = fios_title; if (StrEmpty(fios_title)) { t = strrchr(filename, PATHSEPCHAR); t = (t == NULL) ? filename : (t + 1); } strecpy(fios->title, t, lastof(fios->title)); str_validate(fios->title, lastof(fios->title)); return true; } /** * Fill the list of the files in a directory, according to some arbitrary rule. * @param mode The mode we are in. Some modes don't allow 'parent'. * @param callback_proc The function that is called where you need to do the filtering. * @param subdir The directory from where to start (global) searching. */ static void FiosGetFileList(SaveLoadDialogMode mode, fios_getlist_callback_proc *callback_proc, Subdirectory subdir) { struct stat sb; struct dirent *dirent; DIR *dir; FiosItem *fios; int sort_start; char d_name[sizeof(fios->name)]; _fios_items.Clear(); /* A parent directory link exists if we are not in the root directory */ if (!FiosIsRoot(_fios_path)) { fios = _fios_items.Append(); fios->type = FIOS_TYPE_PARENT; fios->mtime = 0; strecpy(fios->name, "..", lastof(fios->name)); strecpy(fios->title, ".. (Parent directory)", lastof(fios->title)); } /* Show subdirectories */ if ((dir = ttd_opendir(_fios_path)) != NULL) { while ((dirent = readdir(dir)) != NULL) { strecpy(d_name, FS2OTTD(dirent->d_name), lastof(d_name)); /* found file must be directory, but not '.' or '..' */ if (FiosIsValidFile(_fios_path, dirent, &sb) && S_ISDIR(sb.st_mode) && (!FiosIsHiddenFile(dirent) || strncasecmp(d_name, PERSONAL_DIR, strlen(d_name)) == 0) && strcmp(d_name, ".") != 0 && strcmp(d_name, "..") != 0) { fios = _fios_items.Append(); fios->type = FIOS_TYPE_DIR; fios->mtime = 0; strecpy(fios->name, d_name, lastof(fios->name)); snprintf(fios->title, lengthof(fios->title), "%s" PATHSEP " (Directory)", d_name); str_validate(fios->title, lastof(fios->title)); } } closedir(dir); } /* Sort the subdirs always by name, ascending, remember user-sorting order */ { SortingBits order = _savegame_sort_order; _savegame_sort_order = SORT_BY_NAME | SORT_ASCENDING; QSortT(_fios_items.Begin(), _fios_items.Length(), CompareFiosItems); _savegame_sort_order = order; } /* This is where to start sorting for the filenames */ sort_start = _fios_items.Length(); /* Show files */ FiosFileScanner scanner(mode, callback_proc); if (subdir == NO_DIRECTORY) { scanner.Scan(NULL, _fios_path, false); } else { scanner.Scan(NULL, subdir, true, true); } QSortT(_fios_items.Get(sort_start), _fios_items.Length() - sort_start, CompareFiosItems); /* Show drives */ FiosGetDrives(); _fios_items.Compact(); } /** * Get the title of a file, which (if exists) is stored in a file named * the same as the data file but with '.title' added to it. * @param file filename to get the title for * @param title the title buffer to fill * @param last the last element in the title buffer */ static void GetFileTitle(const char *file, char *title, const char *last) { char buf[MAX_PATH]; strecpy(buf, file, lastof(buf)); strecat(buf, ".title", lastof(buf)); FILE *f = FioFOpenFile(buf, "r"); if (f == NULL) return; size_t read = fread(title, 1, last - title, f); assert(title + read <= last); title[read] = '\0'; str_validate(title, last); FioFCloseFile(f); } /** * Callback for FiosGetFileList. It tells if a file is a savegame or not. * @param mode Save/load mode. * @param file Name of the file to check. * @param ext A pointer to the extension identifier inside file * @param title Buffer if a callback wants to lookup the title of the file; NULL to skip the lookup * @param last Last available byte in buffer (to prevent buffer overflows); not used when title == NULL * @return a FIOS_TYPE_* type of the found file, FIOS_TYPE_INVALID if not a savegame * @see FiosGetFileList * @see FiosGetSavegameList */ FiosType FiosGetSavegameListCallback(SaveLoadDialogMode mode, const char *file, const char *ext, char *title, const char *last) { /* Show savegame files * .SAV OpenTTD saved game * .SS1 Transport Tycoon Deluxe preset game * .SV1 Transport Tycoon Deluxe (Patch) saved game * .SV2 Transport Tycoon Deluxe (Patch) saved 2-player game */ if (strcasecmp(ext, ".sav") == 0) { GetFileTitle(file, title, last); return FIOS_TYPE_FILE; } if (mode == SLD_LOAD_GAME || mode == SLD_LOAD_SCENARIO) { if (strcasecmp(ext, ".ss1") == 0 || strcasecmp(ext, ".sv1") == 0 || strcasecmp(ext, ".sv2") == 0) { if (title != NULL) GetOldSaveGameName(file, title, last); return FIOS_TYPE_OLDFILE; } } return FIOS_TYPE_INVALID; } /** * Get a list of savegames. * @param mode Save/load mode. * @see FiosGetFileList */ void FiosGetSavegameList(SaveLoadDialogMode mode) { static char *fios_save_path = NULL; if (fios_save_path == NULL) { fios_save_path = MallocT<char>(MAX_PATH); FioGetDirectory(fios_save_path, MAX_PATH, SAVE_DIR); } _fios_path = fios_save_path; FiosGetFileList(mode, &FiosGetSavegameListCallback, NO_DIRECTORY); } /** * Callback for FiosGetFileList. It tells if a file is a scenario or not. * @param mode Save/load mode. * @param file Name of the file to check. * @param ext A pointer to the extension identifier inside file * @param title Buffer if a callback wants to lookup the title of the file * @param last Last available byte in buffer (to prevent buffer overflows) * @return a FIOS_TYPE_* type of the found file, FIOS_TYPE_INVALID if not a scenario * @see FiosGetFileList * @see FiosGetScenarioList */ static FiosType FiosGetScenarioListCallback(SaveLoadDialogMode mode, const char *file, const char *ext, char *title, const char *last) { /* Show scenario files * .SCN OpenTTD style scenario file * .SV0 Transport Tycoon Deluxe (Patch) scenario * .SS0 Transport Tycoon Deluxe preset scenario */ if (strcasecmp(ext, ".scn") == 0) { GetFileTitle(file, title, last); return FIOS_TYPE_SCENARIO; } if (mode == SLD_LOAD_GAME || mode == SLD_LOAD_SCENARIO) { if (strcasecmp(ext, ".sv0") == 0 || strcasecmp(ext, ".ss0") == 0 ) { GetOldSaveGameName(file, title, last); return FIOS_TYPE_OLD_SCENARIO; } } return FIOS_TYPE_INVALID; } /** * Get a list of scenarios. * @param mode Save/load mode. * @see FiosGetFileList */ void FiosGetScenarioList(SaveLoadDialogMode mode) { static char *fios_scn_path = NULL; /* Copy the default path on first run or on 'New Game' */ if (fios_scn_path == NULL) { fios_scn_path = MallocT<char>(MAX_PATH); FioGetDirectory(fios_scn_path, MAX_PATH, SCENARIO_DIR); } _fios_path = fios_scn_path; char base_path[MAX_PATH]; FioGetDirectory(base_path, sizeof(base_path), SCENARIO_DIR); FiosGetFileList(mode, &FiosGetScenarioListCallback, (mode == SLD_LOAD_SCENARIO && strcmp(base_path, _fios_path) == 0) ? SCENARIO_DIR : NO_DIRECTORY); } static FiosType FiosGetHeightmapListCallback(SaveLoadDialogMode mode, const char *file, const char *ext, char *title, const char *last) { /* Show heightmap files * .PNG PNG Based heightmap files * .BMP BMP Based heightmap files */ FiosType type = FIOS_TYPE_INVALID; #ifdef WITH_PNG if (strcasecmp(ext, ".png") == 0) type = FIOS_TYPE_PNG; #endif /* WITH_PNG */ if (strcasecmp(ext, ".bmp") == 0) type = FIOS_TYPE_BMP; if (type == FIOS_TYPE_INVALID) return FIOS_TYPE_INVALID; TarFileList::iterator it = _tar_filelist.find(file); if (it != _tar_filelist.end()) { /* If the file is in a tar and that tar is not in a heightmap * directory we are for sure not supposed to see it. * Examples of this are pngs part of documentation within * collections of NewGRFs or 32 bpp graphics replacement PNGs. */ bool match = false; Searchpath sp; FOR_ALL_SEARCHPATHS(sp) { char buf[MAX_PATH]; FioAppendDirectory(buf, sizeof(buf), sp, HEIGHTMAP_DIR); if (strncmp(buf, it->second.tar_filename, strlen(buf)) == 0) { match = true; break; } } if (!match) return FIOS_TYPE_INVALID; } GetFileTitle(file, title, last); return type; } /** * Get a list of heightmaps. * @param mode Save/load mode. */ void FiosGetHeightmapList(SaveLoadDialogMode mode) { static char *fios_hmap_path = NULL; if (fios_hmap_path == NULL) { fios_hmap_path = MallocT<char>(MAX_PATH); FioGetDirectory(fios_hmap_path, MAX_PATH, HEIGHTMAP_DIR); } _fios_path = fios_hmap_path; char base_path[MAX_PATH]; FioGetDirectory(base_path, sizeof(base_path), HEIGHTMAP_DIR); FiosGetFileList(mode, &FiosGetHeightmapListCallback, strcmp(base_path, _fios_path) == 0 ? HEIGHTMAP_DIR : NO_DIRECTORY); } #if defined(ENABLE_NETWORK) #include "network/network_content.h" #include "3rdparty/md5/md5.h" /** Basic data to distinguish a scenario. Used in the server list window */ struct ScenarioIdentifier { uint32 scenid; ///< ID for the scenario (generated by content) uint8 md5sum[16]; ///< MD5 checksum of file bool operator == (const ScenarioIdentifier &other) const { return this->scenid == other.scenid && memcmp(this->md5sum, other.md5sum, sizeof(this->md5sum)) == 0; } bool operator != (const ScenarioIdentifier &other) const { return !(*this == other); } }; /** * Scanner to find the unique IDs of scenarios */ class ScenarioScanner : protected FileScanner, public SmallVector<ScenarioIdentifier, 8> { bool scanned; ///< Whether we've already scanned public: /** Initialise */ ScenarioScanner() : scanned(false) {} /** * Scan, but only if it's needed. * @param rescan whether to force scanning even when it's not necessary */ void Scan(bool rescan) { if (this->scanned && !rescan) return; this->FileScanner::Scan(".id", SCENARIO_DIR, true, true); this->scanned = true; } /* virtual */ bool AddFile(const char *filename, size_t basepath_length) { FILE *f = FioFOpenFile(filename, "r"); if (f == NULL) return false; ScenarioIdentifier id; int fret = fscanf(f, "%i", &id.scenid); FioFCloseFile(f); if (fret != 1) return false; Md5 checksum; uint8 buffer[1024]; char basename[MAX_PATH]; ///< \a filename without the extension. size_t len, size; /* open the scenario file, but first get the name. * This is safe as we check on extension which * must always exist. */ strecpy(basename, filename, lastof(basename)); *strrchr(basename, '.') = '\0'; f = FioFOpenFile(basename, "rb", SCENARIO_DIR, &size); if (f == NULL) return false; /* calculate md5sum */ while ((len = fread(buffer, 1, (size > sizeof(buffer)) ? sizeof(buffer) : size, f)) != 0 && size != 0) { size -= len; checksum.Append(buffer, len); } checksum.Finish(id.md5sum); FioFCloseFile(f); this->Include(id); return true; } }; /** Scanner for scenarios */ static ScenarioScanner _scanner; /** * Check whether we've got a given scenario based on its unique ID. * @param ci the content info to compare it to * @param md5sum whether to look at the md5sum or the id * @return true if we've got the scenario */ bool HasScenario(const ContentInfo *ci, bool md5sum) { _scanner.Scan(false); for (ScenarioIdentifier *id = _scanner.Begin(); id != _scanner.End(); id++) { if (md5sum ? (memcmp(id->md5sum, ci->md5sum, sizeof(id->md5sum)) == 0) : (id->scenid == ci->unique_id)) { return true; } } return false; } /** * Force a (re)scan of the scenarios. */ void ScanScenarios() { _scanner.Scan(true); } #endif /* ENABLE_NETWORK */
29.298954
185
0.69624
trademarks
ba2f9f2ba22a0ceff98639813067803c12bb4f6c
2,142
cpp
C++
src/GraphicsPipeline.cpp
skaarj1989/FrameGraph-Example
7867df8e3146acfffaf41173d5776b6ac265fd50
[ "MIT" ]
5
2022-03-17T06:02:13.000Z
2022-03-25T06:06:48.000Z
src/GraphicsPipeline.cpp
skaarj1989/FrameGraph-Example
7867df8e3146acfffaf41173d5776b6ac265fd50
[ "MIT" ]
null
null
null
src/GraphicsPipeline.cpp
skaarj1989/FrameGraph-Example
7867df8e3146acfffaf41173d5776b6ac265fd50
[ "MIT" ]
2
2022-03-17T06:53:48.000Z
2022-03-25T05:06:54.000Z
#include "GraphicsPipeline.hpp" #include "spdlog/spdlog.h" // // GraphicsPipeline class: // GraphicsPipeline::GraphicsPipeline(GraphicsPipeline &&other) noexcept : m_program{other.m_program}, m_vertexArray{other.m_vertexArray}, m_depthStencilState{std::move(other.m_depthStencilState)}, m_rasterizerState{std::move(other.m_rasterizerState)}, m_blendStates{std::move(other.m_blendStates)} { memset(&other, 0, sizeof(GraphicsPipeline)); } GraphicsPipeline::~GraphicsPipeline() { if (m_program != GL_NONE) SPDLOG_WARN("ShaderProgram leak: {}", m_program); } GraphicsPipeline &GraphicsPipeline::operator=(GraphicsPipeline &&rhs) noexcept { if (this != &rhs) { m_vertexArray = rhs.m_vertexArray; m_program = rhs.m_program; m_depthStencilState = std::move(rhs.m_depthStencilState); m_rasterizerState = std::move(rhs.m_rasterizerState); m_blendStates = std::move(rhs.m_blendStates); memset(&rhs, 0, sizeof(GraphicsPipeline)); } return *this; } // // Builder: // using Builder = GraphicsPipeline::Builder; Builder &GraphicsPipeline::Builder::setShaderProgram(GLuint program) { m_program = program; return *this; } Builder &GraphicsPipeline::Builder::setVertexArray(GLuint vao) { m_vertexArray = vao; return *this; } Builder & GraphicsPipeline::Builder::setDepthStencil(const DepthStencilState &state) { m_depthStencilState = state; return *this; } Builder & GraphicsPipeline::Builder::setRasterizerState(const RasterizerState &state) { m_rasterizerState = state; return *this; } Builder &GraphicsPipeline::Builder::setBlendState(uint32_t attachment, const BlendState &state) { assert(attachment < kMaxNumBlendStates); m_blendStates[attachment] = state; return *this; } GraphicsPipeline GraphicsPipeline::Builder::build() { assert(m_program != GL_NONE); GraphicsPipeline gp; gp.m_program = m_program; gp.m_vertexArray = m_vertexArray; gp.m_depthStencilState = m_depthStencilState; gp.m_rasterizerState = m_rasterizerState; gp.m_blendStates = m_blendStates; m_program = GL_NONE; return gp; }
27.818182
80
0.729692
skaarj1989
ba306e63838b3f5e22f98d026a03757494e21d1a
4,857
cpp
C++
src/Evolution/DgSubcell/Reconstruction.cpp
nilsvu/spectre
1455b9a8d7e92db8ad600c66f54795c29c3052ee
[ "MIT" ]
1
2022-01-11T00:17:33.000Z
2022-01-11T00:17:33.000Z
src/Evolution/DgSubcell/Reconstruction.cpp
nilsvu/spectre
1455b9a8d7e92db8ad600c66f54795c29c3052ee
[ "MIT" ]
null
null
null
src/Evolution/DgSubcell/Reconstruction.cpp
nilsvu/spectre
1455b9a8d7e92db8ad600c66f54795c29c3052ee
[ "MIT" ]
null
null
null
// Distributed under the MIT License. // See LICENSE.txt for details. #include "Evolution/DgSubcell/Reconstruction.hpp" #include <array> #include <cstddef> #include <functional> #include "DataStructures/ApplyMatrices.hpp" #include "DataStructures/DataVector.hpp" #include "DataStructures/Matrix.hpp" #include "Evolution/DgSubcell/Matrices.hpp" #include "NumericalAlgorithms/Spectral/Mesh.hpp" #include "Utilities/Blas.hpp" #include "Utilities/ContainerHelpers.hpp" #include "Utilities/ErrorHandling/Assert.hpp" #include "Utilities/GenerateInstantiations.hpp" #include "Utilities/Gsl.hpp" #include "Utilities/MakeArray.hpp" namespace evolution::dg::subcell::fd { namespace detail { template <size_t Dim> void reconstruct_impl( gsl::span<double> dg_u, const gsl::span<const double> subcell_u_times_projected_det_jac, const Mesh<Dim>& dg_mesh, const Index<Dim>& subcell_extents, const ReconstructionMethod reconstruction_method) { const size_t number_of_components = dg_u.size() / dg_mesh.number_of_grid_points(); if (reconstruction_method == ReconstructionMethod::AllDimsAtOnce) { const Matrix& recons_matrix = reconstruction_matrix(dg_mesh, subcell_extents); dgemm_<true>('N', 'N', recons_matrix.rows(), number_of_components, recons_matrix.columns(), 1.0, recons_matrix.data(), recons_matrix.rows(), subcell_u_times_projected_det_jac.data(), recons_matrix.columns(), 0.0, dg_u.data(), recons_matrix.rows()); } else { ASSERT(reconstruction_method == ReconstructionMethod::DimByDim, "reconstruction_method must be either DimByDim or AllDimsAtOnce"); // We multiply the last dim first because projection is done with the last // dim last. We do this because it ensures the R(P)==I up to machine // precision. const Matrix empty{}; auto recons_matrices = make_array<Dim>(std::cref(empty)); for (size_t d = 0; d < Dim; d++) { gsl::at(recons_matrices, d) = std::cref(reconstruction_matrix( dg_mesh.slice_through(d), Index<1>{subcell_extents[d]})); } DataVector result{dg_u.data(), dg_u.size()}; const DataVector u{ // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) const_cast<double*>(subcell_u_times_projected_det_jac.data()), subcell_u_times_projected_det_jac.size()}; apply_matrices(make_not_null(&result), recons_matrices, u, subcell_extents); } } } // namespace detail template <size_t Dim> void reconstruct(const gsl::not_null<DataVector*> dg_u, const DataVector& subcell_u_times_projected_det_jac, const Mesh<Dim>& dg_mesh, const Index<Dim>& subcell_extents, const ReconstructionMethod reconstruction_method) { ASSERT(subcell_u_times_projected_det_jac.size() == subcell_extents.product(), "Incorrect subcell size of u: " << subcell_u_times_projected_det_jac.size() << " but should be " << subcell_extents.product()); dg_u->destructive_resize(dg_mesh.number_of_grid_points()); detail::reconstruct_impl( gsl::span<double>{dg_u->data(), dg_u->size()}, gsl::span<const double>{subcell_u_times_projected_det_jac.data(), subcell_u_times_projected_det_jac.size()}, dg_mesh, subcell_extents, reconstruction_method); } template <size_t Dim> DataVector reconstruct(const DataVector& subcell_u_times_projected_det_jac, const Mesh<Dim>& dg_mesh, const Index<Dim>& subcell_extents, const ReconstructionMethod reconstruction_method) { DataVector dg_u{dg_mesh.number_of_grid_points()}; reconstruct(&dg_u, subcell_u_times_projected_det_jac, dg_mesh, subcell_extents, reconstruction_method); return dg_u; } #define DIM(data) BOOST_PP_TUPLE_ELEM(0, data) #define INSTANTIATION(r, data) \ template DataVector reconstruct(const DataVector&, const Mesh<DIM(data)>&, \ const Index<DIM(data)>&, \ ReconstructionMethod); \ template void reconstruct(gsl::not_null<DataVector*>, const DataVector&, \ const Mesh<DIM(data)>&, const Index<DIM(data)>&, \ ReconstructionMethod); \ template void detail::reconstruct_impl( \ gsl::span<double> dg_u, const gsl::span<const double>, \ const Mesh<DIM(data)>& dg_mesh, const Index<DIM(data)>& subcell_extents, \ ReconstructionMethod); GENERATE_INSTANTIATIONS(INSTANTIATION, (1, 2, 3)) #undef INSTANTIATION #undef DIM } // namespace evolution::dg::subcell::fd
44.559633
80
0.663578
nilsvu
ba3295fbb35e7a8dba5e617e1c1baf9ab4bf8387
419
cpp
C++
Engine/Math/Rotation/AxisAngle/AxisAngle.cpp
gregory-vovchok/YEngine
e28552e52588bd90db01dd53e5fc817d0a26d146
[ "BSD-2-Clause" ]
null
null
null
Engine/Math/Rotation/AxisAngle/AxisAngle.cpp
gregory-vovchok/YEngine
e28552e52588bd90db01dd53e5fc817d0a26d146
[ "BSD-2-Clause" ]
null
null
null
Engine/Math/Rotation/AxisAngle/AxisAngle.cpp
gregory-vovchok/YEngine
e28552e52588bd90db01dd53e5fc817d0a26d146
[ "BSD-2-Clause" ]
1
2020-12-04T08:57:03.000Z
2020-12-04T08:57:03.000Z
#include "AxisAngle.h" AxisAngle::AxisAngle(void): angle(0.0f) {} AxisAngle::AxisAngle(Vector3 _axis, float _angle): axis(_axis), angle(_angle) {} bool AxisAngle::operator == (const AxisAngle& _axisAngle)const { if(axis == _axisAngle.axis && angle == _axisAngle.angle) { return true; } return false; } bool AxisAngle::operator != (const AxisAngle& _axisAngle)const { return !(*this == _axisAngle); }
14.448276
77
0.689737
gregory-vovchok
ba32c8ad6b4cedc024a45d3d47a255226a6fc459
3,930
cc
C++
v8_4_8/src/crankshaft/hydrogen-store-elimination.cc
wenfeifei/miniblink49
2ed562ff70130485148d94b0e5f4c343da0c2ba4
[ "Apache-2.0" ]
5,964
2016-09-27T03:46:29.000Z
2022-03-31T16:25:27.000Z
v8_4_8/src/crankshaft/hydrogen-store-elimination.cc
w4454962/miniblink49
b294b6eacb3333659bf7b94d670d96edeeba14c0
[ "Apache-2.0" ]
459
2016-09-29T00:51:38.000Z
2022-03-07T14:37:46.000Z
v8_4_8/src/crankshaft/hydrogen-store-elimination.cc
w4454962/miniblink49
b294b6eacb3333659bf7b94d670d96edeeba14c0
[ "Apache-2.0" ]
1,006
2016-09-27T05:17:27.000Z
2022-03-30T02:46:51.000Z
// Copyright 2013 the V8 project 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 "src/crankshaft/hydrogen-store-elimination.h" #include "src/crankshaft/hydrogen-instructions.h" namespace v8 { namespace internal { #define TRACE(x) if (FLAG_trace_store_elimination) PrintF x // Performs a block-by-block local analysis for removable stores. void HStoreEliminationPhase::Run() { GVNFlagSet flags; // Use GVN flags as an approximation for some instructions. flags.RemoveAll(); flags.Add(kArrayElements); flags.Add(kArrayLengths); flags.Add(kStringLengths); flags.Add(kBackingStoreFields); flags.Add(kDoubleArrayElements); flags.Add(kDoubleFields); flags.Add(kElementsPointer); flags.Add(kInobjectFields); flags.Add(kExternalMemory); flags.Add(kStringChars); flags.Add(kTypedArrayElements); for (int i = 0; i < graph()->blocks()->length(); i++) { unobserved_.Rewind(0); HBasicBlock* block = graph()->blocks()->at(i); if (!block->IsReachable()) continue; for (HInstructionIterator it(block); !it.Done(); it.Advance()) { HInstruction* instr = it.Current(); if (instr->CheckFlag(HValue::kIsDead)) continue; // TODO(titzer): eliminate unobserved HStoreKeyed instructions too. switch (instr->opcode()) { case HValue::kStoreNamedField: // Remove any unobserved stores overwritten by this store. ProcessStore(HStoreNamedField::cast(instr)); break; case HValue::kLoadNamedField: // Observe any unobserved stores on this object + field. ProcessLoad(HLoadNamedField::cast(instr)); break; default: ProcessInstr(instr, flags); break; } } } } void HStoreEliminationPhase::ProcessStore(HStoreNamedField* store) { HValue* object = store->object()->ActualValue(); int i = 0; while (i < unobserved_.length()) { HStoreNamedField* prev = unobserved_.at(i); if (aliasing_->MustAlias(object, prev->object()->ActualValue()) && prev->CanBeReplacedWith(store)) { // This store is guaranteed to overwrite the previous store. prev->DeleteAndReplaceWith(NULL); TRACE(("++ Unobserved store S%d overwritten by S%d\n", prev->id(), store->id())); unobserved_.Remove(i); } else { // TODO(titzer): remove map word clearing from folded allocations. i++; } } // Only non-transitioning stores are removable. if (!store->has_transition()) { TRACE(("-- Might remove store S%d\n", store->id())); unobserved_.Add(store, zone()); } } void HStoreEliminationPhase::ProcessLoad(HLoadNamedField* load) { HValue* object = load->object()->ActualValue(); int i = 0; while (i < unobserved_.length()) { HStoreNamedField* prev = unobserved_.at(i); if (aliasing_->MayAlias(object, prev->object()->ActualValue()) && load->access().Equals(prev->access())) { TRACE(("-- Observed store S%d by load L%d\n", prev->id(), load->id())); unobserved_.Remove(i); } else { i++; } } } void HStoreEliminationPhase::ProcessInstr(HInstruction* instr, GVNFlagSet flags) { if (unobserved_.length() == 0) return; // Nothing to do. if (instr->CanDeoptimize()) { TRACE(("-- Observed stores at I%d (%s might deoptimize)\n", instr->id(), instr->Mnemonic())); unobserved_.Rewind(0); return; } if (instr->CheckChangesFlag(kNewSpacePromotion)) { TRACE(("-- Observed stores at I%d (%s might GC)\n", instr->id(), instr->Mnemonic())); unobserved_.Rewind(0); return; } if (instr->DependsOnFlags().ContainsAnyOf(flags)) { TRACE(("-- Observed stores at I%d (GVN flags of %s)\n", instr->id(), instr->Mnemonic())); unobserved_.Rewind(0); return; } } } // namespace internal } // namespace v8
31.693548
80
0.647837
wenfeifei
ba3365cd7882759f3e91fcb1a6387fc7a2500054
6,614
cc
C++
src/core/ext/filters/client_channel/backup_poller.cc
lishengze/grpc
70fa55155beade94670661f033e91b55f43c9dee
[ "Apache-2.0" ]
1
2021-12-01T03:10:14.000Z
2021-12-01T03:10:14.000Z
src/core/ext/filters/client_channel/backup_poller.cc
lishengze/grpc
70fa55155beade94670661f033e91b55f43c9dee
[ "Apache-2.0" ]
null
null
null
src/core/ext/filters/client_channel/backup_poller.cc
lishengze/grpc
70fa55155beade94670661f033e91b55f43c9dee
[ "Apache-2.0" ]
null
null
null
/* * * Copyright 2017 gRPC 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 <grpc/support/port_platform.h> #include "src/core/ext/filters/client_channel/backup_poller.h" #include <grpc/grpc.h> #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include <grpc/support/sync.h> #include "src/core/ext/filters/client_channel/client_channel.h" #include "src/core/lib/gpr/string.h" #include "src/core/lib/gprpp/global_config.h" #include "src/core/lib/gprpp/memory.h" #include "src/core/lib/gprpp/time.h" #include "src/core/lib/iomgr/error.h" #include "src/core/lib/iomgr/iomgr.h" #include "src/core/lib/iomgr/pollset.h" #include "src/core/lib/iomgr/timer.h" #include "src/core/lib/surface/channel.h" #include "src/core/lib/surface/completion_queue.h" #define DEFAULT_POLL_INTERVAL_MS 5000 namespace { struct backup_poller { grpc_timer polling_timer; grpc_closure run_poller_closure; grpc_closure shutdown_closure; gpr_mu* pollset_mu; grpc_pollset* pollset; // guarded by pollset_mu bool shutting_down; // guarded by pollset_mu gpr_refcount refs; gpr_refcount shutdown_refs; }; } // namespace static gpr_once g_once = GPR_ONCE_INIT; static gpr_mu g_poller_mu; static backup_poller* g_poller = nullptr; // guarded by g_poller_mu // g_poll_interval_ms is set only once at the first time // grpc_client_channel_start_backup_polling() is called, after that it is // treated as const. static grpc_core::Duration g_poll_interval = grpc_core::Duration::Milliseconds(DEFAULT_POLL_INTERVAL_MS); GPR_GLOBAL_CONFIG_DEFINE_INT32( grpc_client_channel_backup_poll_interval_ms, DEFAULT_POLL_INTERVAL_MS, "Declares the interval in ms between two backup polls on client channels. " "These polls are run in the timer thread so that gRPC can process " "connection failures while there is no active polling thread. " "They help reconnect disconnected client channels (mostly due to " "idleness), so that the next RPC on this channel won't fail. Set to 0 to " "turn off the backup polls."); void grpc_client_channel_global_init_backup_polling() { gpr_once_init(&g_once, [] { gpr_mu_init(&g_poller_mu); }); int32_t poll_interval_ms = GPR_GLOBAL_CONFIG_GET(grpc_client_channel_backup_poll_interval_ms); if (poll_interval_ms < 0) { gpr_log(GPR_ERROR, "Invalid GRPC_CLIENT_CHANNEL_BACKUP_POLL_INTERVAL_MS: %d, " "default value %" PRId64 " will be used.", poll_interval_ms, g_poll_interval.millis()); } else { g_poll_interval = grpc_core::Duration::Milliseconds(poll_interval_ms); } } static void backup_poller_shutdown_unref(backup_poller* p) { if (gpr_unref(&p->shutdown_refs)) { grpc_pollset_destroy(p->pollset); gpr_free(p->pollset); gpr_free(p); } } static void done_poller(void* arg, grpc_error_handle /*error*/) { backup_poller_shutdown_unref(static_cast<backup_poller*>(arg)); } static void g_poller_unref() { gpr_mu_lock(&g_poller_mu); if (gpr_unref(&g_poller->refs)) { backup_poller* p = g_poller; g_poller = nullptr; gpr_mu_unlock(&g_poller_mu); gpr_mu_lock(p->pollset_mu); p->shutting_down = true; grpc_pollset_shutdown( p->pollset, GRPC_CLOSURE_INIT(&p->shutdown_closure, done_poller, p, grpc_schedule_on_exec_ctx)); gpr_mu_unlock(p->pollset_mu); grpc_timer_cancel(&p->polling_timer); backup_poller_shutdown_unref(p); } else { gpr_mu_unlock(&g_poller_mu); } } static void run_poller(void* arg, grpc_error_handle error) { backup_poller* p = static_cast<backup_poller*>(arg); if (error != GRPC_ERROR_NONE) { if (error != GRPC_ERROR_CANCELLED) { GRPC_LOG_IF_ERROR("run_poller", GRPC_ERROR_REF(error)); } backup_poller_shutdown_unref(p); return; } gpr_mu_lock(p->pollset_mu); if (p->shutting_down) { gpr_mu_unlock(p->pollset_mu); backup_poller_shutdown_unref(p); return; } grpc_error_handle err = grpc_pollset_work(p->pollset, nullptr, grpc_core::ExecCtx::Get()->Now()); gpr_mu_unlock(p->pollset_mu); GRPC_LOG_IF_ERROR("Run client channel backup poller", err); grpc_timer_init(&p->polling_timer, grpc_core::ExecCtx::Get()->Now() + g_poll_interval, &p->run_poller_closure); } static void g_poller_init_locked() { if (g_poller == nullptr) { g_poller = grpc_core::Zalloc<backup_poller>(); g_poller->pollset = static_cast<grpc_pollset*>(gpr_zalloc(grpc_pollset_size())); g_poller->shutting_down = false; grpc_pollset_init(g_poller->pollset, &g_poller->pollset_mu); gpr_ref_init(&g_poller->refs, 0); // one for timer cancellation, one for pollset shutdown, one for g_poller gpr_ref_init(&g_poller->shutdown_refs, 3); GRPC_CLOSURE_INIT(&g_poller->run_poller_closure, run_poller, g_poller, grpc_schedule_on_exec_ctx); grpc_timer_init(&g_poller->polling_timer, grpc_core::ExecCtx::Get()->Now() + g_poll_interval, &g_poller->run_poller_closure); } } void grpc_client_channel_start_backup_polling( grpc_pollset_set* interested_parties) { if (g_poll_interval == grpc_core::Duration::Zero() || grpc_iomgr_run_in_background()) { return; } gpr_mu_lock(&g_poller_mu); g_poller_init_locked(); gpr_ref(&g_poller->refs); /* Get a reference to g_poller->pollset before releasing g_poller_mu to make * TSAN happy. Otherwise, reading from g_poller (i.e g_poller->pollset) after * releasing the lock and setting g_poller to NULL in g_poller_unref() is * being flagged as a data-race by TSAN */ grpc_pollset* pollset = g_poller->pollset; gpr_mu_unlock(&g_poller_mu); grpc_pollset_set_add_pollset(interested_parties, pollset); } void grpc_client_channel_stop_backup_polling( grpc_pollset_set* interested_parties) { if (g_poll_interval == grpc_core::Duration::Zero() || grpc_iomgr_run_in_background()) { return; } grpc_pollset_set_del_pollset(interested_parties, g_poller->pollset); g_poller_unref(); }
35.180851
79
0.725431
lishengze
ba33ba298ce65b6a4f3825f4cb0f7c2339bd317b
1,456
cpp
C++
Hooker/Driver/src/SSDT.cpp
SoftSec-KAIST/NTFuzz
f9e2beea5bfc0b562c7839cc821007bc237d6c5f
[ "MIT" ]
25
2021-09-30T05:56:59.000Z
2022-03-27T15:31:46.000Z
Hooker/Driver/src/SSDT.cpp
SoftSec-KAIST/NTFuzz
f9e2beea5bfc0b562c7839cc821007bc237d6c5f
[ "MIT" ]
2
2022-01-07T02:48:29.000Z
2022-01-24T03:20:57.000Z
Hooker/Driver/src/SSDT.cpp
SoftSec-KAIST/NTFuzz
f9e2beea5bfc0b562c7839cc821007bc237d6c5f
[ "MIT" ]
10
2021-09-30T04:57:03.000Z
2022-03-11T08:07:15.000Z
#include <ntddk.h> #include "..\inc\SSDT.h" #define SYSCALL_TABLE_MAXLEN 4096 PSERVICE_DESCRIPTOR pNtServiceDescriptor = NULL; PSERVICE_DESCRIPTOR pW32ServiceDescriptor = NULL; ULONG_PTR origNtSyscalls[SYSCALL_TABLE_MAXLEN] = { NULL, }; ULONG_PTR origW32Syscalls[SYSCALL_TABLE_MAXLEN] = { NULL, }; bool CheckTablePointer(void) { if (pNtServiceDescriptor && pW32ServiceDescriptor) { return true; } else { return false; } } bool InitTablePointer(void) { PSERVICE_DESCRIPTOR_TABLE shadowTable; if (!ntBase) { DbgPrint("Image base of 'nt' module not initialized yet.\n\n"); return false; } shadowTable = (PSERVICE_DESCRIPTOR_TABLE)(ntBase + SHADOW_TABLE_OFFSET); pNtServiceDescriptor = &(shadowTable->NtosTable); pW32ServiceDescriptor = &(shadowTable->Win32kTable); return true; } void RegisterNtHook(ULONG sysNum, ULONG_PTR newFunc) { ULONG idx = sysNum & 0xfff; PULONG origPtr = &(pNtServiceDescriptor->ServiceTableBase[idx]); origNtSyscalls[idx] = *origPtr; DbgPrint("Backup NtSyscall # 0x%x @ 0x%x\n", sysNum, origNtSyscalls[idx]); InterlockedExchange((PLONG)origPtr, newFunc); } void RegisterW32Hook(ULONG sysNum, ULONG_PTR newFunc) { ULONG idx = sysNum & 0xfff; PULONG origPtr = &(pW32ServiceDescriptor->ServiceTableBase[idx]); origW32Syscalls[idx] = *origPtr; DbgPrint("Backup W32Syscall # 0x%x @ 0x%x\n", sysNum, origW32Syscalls[idx]); InterlockedExchange((PLONG)origPtr, newFunc); }
28
78
0.741071
SoftSec-KAIST
ba37c13b3ec63bc1c4bd80a740619d8a1850f794
29,454
cpp
C++
src/umpire/ResourceManager.cpp
degrbg/Umpire
15f1d3e2f94b97746d63fc3a6a816a197fb9274a
[ "MIT-0", "MIT" ]
null
null
null
src/umpire/ResourceManager.cpp
degrbg/Umpire
15f1d3e2f94b97746d63fc3a6a816a197fb9274a
[ "MIT-0", "MIT" ]
null
null
null
src/umpire/ResourceManager.cpp
degrbg/Umpire
15f1d3e2f94b97746d63fc3a6a816a197fb9274a
[ "MIT-0", "MIT" ]
null
null
null
////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2016-22, Lawrence Livermore National Security, LLC and Umpire // project contributors. See the COPYRIGHT file for details. // // SPDX-License-Identifier: (MIT) ////////////////////////////////////////////////////////////////////////////// #include "umpire/ResourceManager.hpp" #include <iterator> #include <memory> #include <sstream> #include "umpire/Umpire.hpp" #include "umpire/config.hpp" #include "umpire/op/MemoryOperation.hpp" #include "umpire/op/MemoryOperationRegistry.hpp" #include "umpire/resource/MemoryResourceRegistry.hpp" #include "umpire/strategy/FixedPool.hpp" #if defined(UMPIRE_ENABLE_NUMA) #include "umpire/strategy/NumaPolicy.hpp" #endif #include "umpire/util/MPI.hpp" #include "umpire/util/Macros.hpp" #include "umpire/util/io.hpp" #include "umpire/util/make_unique.hpp" #include "umpire/util/wrap_allocator.hpp" #if defined(UMPIRE_ENABLE_CUDA) #include <cuda_runtime_api.h> #if defined(UMPIRE_ENABLE_DEVICE_ALLOCATOR) #include "umpire/device_allocator_helper.hpp" #endif #endif #if defined(UMPIRE_ENABLE_HIP) #include <hip/hip_runtime.h> #endif #if defined(UMPIRE_ENABLE_SYCL) #include <CL/sycl.hpp> #endif static const char* s_null_resource_name{"__umpire_internal_null"}; static const char* s_zero_byte_pool_name{"__umpire_internal_0_byte_pool"}; namespace umpire { ResourceManager& ResourceManager::getInstance() { static ResourceManager resource_manager; UMPIRE_LOG(Debug, "() returning " << &resource_manager); return resource_manager; } ResourceManager::ResourceManager() : m_allocations(), m_allocators(), m_allocators_by_id(), m_allocators_by_name(), m_memory_resources(), m_id(0), m_mutex() { UMPIRE_LOG(Debug, "() entering"); const char* env_enable_replay{getenv("UMPIRE_REPLAY")}; const bool enable_replay{env_enable_replay != nullptr}; const char* env_enable_log{getenv("UMPIRE_LOG_LEVEL")}; const bool enable_log{env_enable_log != nullptr}; util::initialize_io(enable_log, enable_replay); initialize(); UMPIRE_LOG(Debug, "() leaving"); } ResourceManager::~ResourceManager() { #if defined(UMPIRE_ENABLE_CUDA) && defined(UMPIRE_ENABLE_DEVICE_ALLOCATOR) // Tear down and deallocate memory. if (umpire::UMPIRE_DEV_ALLOCS_h != nullptr) { umpire::destroy_device_allocator(); } #endif for (auto&& allocator : m_allocators) { if (allocator->getCurrentSize() != 0) { std::stringstream ss; umpire::print_allocator_records(Allocator{allocator.get()}, ss); UMPIRE_LOG(Error, allocator->getName() << " Allocator still has " << allocator->getCurrentSize() << " bytes allocated" << std::endl << ss.str() << std::endl); } allocator.reset(); } } void ResourceManager::initialize() { UMPIRE_LOG(Debug, "() entering"); UMPIRE_LOG(Debug, "Umpire v" << UMPIRE_VERSION_MAJOR << "." << UMPIRE_VERSION_MINOR << "." << UMPIRE_VERSION_PATCH << "." << UMPIRE_VERSION_RC); UMPIRE_REPLAY(R"( "event": "version", "payload": { "major": )" << UMPIRE_VERSION_MAJOR << R"(, "minor": )" << UMPIRE_VERSION_MINOR << R"(, "patch": )" << UMPIRE_VERSION_PATCH << R"(, "rc": ")" << UMPIRE_VERSION_RC << R"(" })"); resource::MemoryResourceRegistry& registry{resource::MemoryResourceRegistry::getInstance()}; { std::unique_ptr<strategy::AllocationStrategy> allocator{ // util::wrap_allocator<strategy::AllocationTracker>( registry.makeMemoryResource(s_null_resource_name, getNextId())}; m_null_allocator = allocator.get(); m_allocators.emplace_front(std::move(allocator)); } { std::unique_ptr<strategy::AllocationStrategy> allocator{ new strategy::FixedPool{s_zero_byte_pool_name, getNextId(), Allocator{m_null_allocator}, 1}}; m_zero_byte_pool = allocator.get(); m_allocators.emplace_front(std::move(allocator)); } UMPIRE_LOG(Debug, "() leaving"); } Allocator ResourceManager::makeResource(const std::string& name) { resource::MemoryResourceRegistry& registry{resource::MemoryResourceRegistry::getInstance()}; return makeResource(name, registry.getDefaultTraitsForResource(name)); } Allocator ResourceManager::makeResource(const std::string& name, MemoryResourceTraits traits) { if (m_allocators_by_name.find(name) != m_allocators_by_name.end()) { UMPIRE_ERROR(runtime_error, umpire::fmt::format("Allocator \"{}\" already exists, and cannot be re-created.", name)); } resource::MemoryResourceRegistry& registry{resource::MemoryResourceRegistry::getInstance()}; if (name.find("DEVICE") != std::string::npos) { traits.id = resource::resource_to_device_id(name); } std::unique_ptr<strategy::AllocationStrategy> allocator{registry.makeMemoryResource(name, getNextId(), traits)}; allocator->setTracking(traits.tracking); UMPIRE_REPLAY(R"( "event": "makeMemoryResource", "payload": { "name": ")" << name << R"(" })" << R"(, "result": ")" << allocator.get() << R"(")"); int id{allocator->getId()}; m_allocators_by_name[name] = allocator.get(); if (name == "DEVICE") { m_allocators_by_name["DEVICE::0"] = allocator.get(); } if (name.find("::0") != std::string::npos) { std::string base_name{name.substr(0, name.find("::") - 1)}; m_allocators_by_name[base_name] = allocator.get(); } if (name.find("::") == std::string::npos) { m_memory_resources[resource::string_to_resource(name)] = allocator.get(); } m_allocators_by_id[id] = allocator.get(); m_allocators.emplace_front(std::move(allocator)); return Allocator{m_allocators_by_name[name]}; } strategy::AllocationStrategy* ResourceManager::getAllocationStrategy(const std::string& name) { resource::MemoryResourceRegistry& registry{resource::MemoryResourceRegistry::getInstance()}; auto resource_names = registry.getResourceNames(); UMPIRE_LOG(Debug, "(\"" << name << "\")"); auto allocator = m_allocators_by_name.find(name); if (allocator == m_allocators_by_name.end()) { auto resource_name = std::find(resource_names.begin(), resource_names.end(), name); if (resource_name != std::end(resource_names)) { makeResource(name); } else { UMPIRE_ERROR(runtime_error, umpire::fmt::format("Allocator \"{}\" not found. Available allocators: {}", name, getAllocatorInformation())); } } return m_allocators_by_name[name]; } Allocator ResourceManager::getAllocator(const std::string& name) { UMPIRE_LOG(Debug, "(\"" << name << "\")"); return Allocator(getAllocationStrategy(name)); } Allocator ResourceManager::getAllocator(const char* name) { return getAllocator(std::string{name}); } Allocator ResourceManager::getAllocator(resource::MemoryResourceType resource_type) { UMPIRE_LOG(Debug, "(\"" << static_cast<std::size_t>(resource_type) << "\")"); auto allocator = m_memory_resources.find(resource_type); if (allocator == m_memory_resources.end()) { return getAllocator(resource::resource_to_string(resource_type)); } else { return Allocator(m_memory_resources[resource_type]); } } Allocator ResourceManager::getAllocator(int id) { UMPIRE_LOG(Debug, "(\"" << id << "\")"); if (id < 0) { UMPIRE_ERROR(runtime_error, umpire::fmt::format("Passed an invalid id: {}. Is this a DeviceAllocator instead?", id)); } if (id == umpire::invalid_allocator_id) { UMPIRE_ERROR(runtime_error, "Passed umpire::invalid_allocator_id"); } auto allocator = m_allocators_by_id.find(id); if (allocator == m_allocators_by_id.end()) { UMPIRE_ERROR(runtime_error, umpire::fmt::format("Allocator {} not found. Available allocators: {}", id, getAllocatorInformation())); } return Allocator(m_allocators_by_id[id]); } Allocator ResourceManager::getDefaultAllocator() { UMPIRE_LOG(Debug, ""); if (!m_default_allocator) { UMPIRE_LOG(Debug, "Initializing m_default_allocator as HOST"); m_default_allocator = getAllocator("HOST").getAllocationStrategy(); } return Allocator(m_default_allocator); } std::vector<std::string> ResourceManager::getResourceNames() { resource::MemoryResourceRegistry& registry{resource::MemoryResourceRegistry::getInstance()}; return registry.getResourceNames(); } void ResourceManager::setDefaultAllocator(Allocator allocator) noexcept { UMPIRE_LOG(Debug, "(\"" << allocator.getName() << "\")"); UMPIRE_REPLAY(R"( "event": "setDefaultAllocator", "payload": { "allocator_ref": ")" << allocator.getAllocationStrategy() << R"(" })"); m_default_allocator = allocator.getAllocationStrategy(); } void ResourceManager::addAlias(const std::string& name, Allocator allocator) { if (isAllocator(name)) { auto ra = getAllocator(name); UMPIRE_ERROR(runtime_error, umpire::fmt::format("Allocator \"{}\" is already an alias for \"{}\"", name, ra.getName())); } m_allocators_by_name[name] = allocator.getAllocationStrategy(); } void ResourceManager::removeAlias(const std::string& name, Allocator allocator) { if (!isAllocator(name)) { UMPIRE_ERROR(runtime_error, umpire::fmt::format("Allocator \"{}\" is not registered", name)); } auto a = m_allocators_by_name.find(name); if (a->second->getName().compare(name) == 0) { UMPIRE_ERROR(runtime_error, umpire::fmt::format("\"{}\" is not an alias, so cannot be removed", name)); } if (a->second->getId() != allocator.getId()) { UMPIRE_ERROR(runtime_error, umpire::fmt::format("\"{}\" is not is not registered as an alias of {}", name, allocator.getName())); } m_allocators_by_name.erase(a); } Allocator ResourceManager::getAllocator(void* ptr) { UMPIRE_LOG(Debug, "(ptr=" << ptr << ")"); return Allocator(findAllocatorForPointer(ptr)); } bool ResourceManager::isAllocator(const std::string& name) noexcept { resource::MemoryResourceRegistry& registry{resource::MemoryResourceRegistry::getInstance()}; auto resource_names = registry.getResourceNames(); return (m_allocators_by_name.find(name) != m_allocators_by_name.end() || std::find(resource_names.begin(), resource_names.end(), name) != std::end(resource_names)); } bool ResourceManager::isAllocator(int id) noexcept { return (m_allocators_by_id.find(id) != m_allocators_by_id.end()); } bool ResourceManager::hasAllocator(void* ptr) { UMPIRE_LOG(Debug, "(ptr=" << ptr << ")"); return m_allocations.contains(ptr); } void ResourceManager::registerAllocation(void* ptr, util::AllocationRecord record) { if (!ptr) { UMPIRE_ERROR(runtime_error, "Cannot register nullptr!"); } UMPIRE_LOG(Debug, "(ptr=" << ptr << ", size=" << record.size << ", strategy=" << record.strategy << ") with " << this); UMPIRE_RECORD_BACKTRACE(record); m_allocations.insert(ptr, record); } util::AllocationRecord ResourceManager::deregisterAllocation(void* ptr) { UMPIRE_LOG(Debug, "(ptr=" << ptr << ")"); return m_allocations.remove(ptr); } const util::AllocationRecord* ResourceManager::findAllocationRecord(void* ptr) const { auto alloc_record = m_allocations.find(ptr); if (!alloc_record->strategy) { UMPIRE_ERROR(runtime_error, umpire::fmt::format("Cannot find allocator for {}", ptr)); } UMPIRE_LOG(Debug, "(Returning allocation record for ptr = " << ptr << ")"); return alloc_record; } void ResourceManager::copy(void* dst_ptr, void* src_ptr, std::size_t size) { UMPIRE_LOG(Debug, "(src_ptr=" << src_ptr << ", dst_ptr=" << dst_ptr << ", size=" << size << ")"); auto& op_registry = op::MemoryOperationRegistry::getInstance(); auto src_alloc_record = m_allocations.find(src_ptr); std::ptrdiff_t src_offset = static_cast<char*>(src_ptr) - static_cast<char*>(src_alloc_record->ptr); std::size_t src_size = src_alloc_record->size - src_offset; auto dst_alloc_record = m_allocations.find(dst_ptr); std::ptrdiff_t dst_offset = static_cast<char*>(dst_ptr) - static_cast<char*>(dst_alloc_record->ptr); std::size_t dst_size = dst_alloc_record->size - dst_offset; if (size == 0) { size = src_size; } UMPIRE_REPLAY(R"( "event": "copy", "payload": {)" << R"( "src": ")" << src_ptr << R"(")" << R"(, "src_offset": )" << src_offset << R"(, "dest": ")" << dst_ptr << R"(")" << R"(, "dst_offset": )" << dst_offset << R"(, "size": )" << size << R"(, "src_allocator_ref": ")" << src_alloc_record->strategy << R"(")" << R"(, "dst_allocator_ref": ")" << dst_alloc_record->strategy << R"(")" << R"( } )"); if (size > dst_size) { UMPIRE_ERROR(runtime_error, umpire::fmt::format("Not enough space in destination to copy {} bytes into {} bytes", size, dst_size)); } auto op = op_registry.find("COPY", src_alloc_record->strategy, dst_alloc_record->strategy); op->transform(src_ptr, &dst_ptr, src_alloc_record, dst_alloc_record, size); } camp::resources::EventProxy<camp::resources::Resource> ResourceManager::copy(void* dst_ptr, void* src_ptr, camp::resources::Resource& ctx, std::size_t size) { UMPIRE_LOG(Debug, "(src_ptr=" << src_ptr << ", dst_ptr=" << dst_ptr << ", size=" << size << ")"); auto& op_registry = op::MemoryOperationRegistry::getInstance(); auto src_alloc_record = m_allocations.find(src_ptr); std::ptrdiff_t src_offset = static_cast<char*>(src_ptr) - static_cast<char*>(src_alloc_record->ptr); std::size_t src_size = src_alloc_record->size - src_offset; auto dst_alloc_record = m_allocations.find(dst_ptr); std::ptrdiff_t dst_offset = static_cast<char*>(dst_ptr) - static_cast<char*>(dst_alloc_record->ptr); std::size_t dst_size = dst_alloc_record->size - dst_offset; if (size == 0) { size = src_size; } if (size > dst_size) { UMPIRE_ERROR(runtime_error, umpire::fmt::format("Not enough resource in destination for copy: {} -> {}", size, dst_size)); } auto op = op_registry.find("COPY", src_alloc_record->strategy, dst_alloc_record->strategy); return op->transform_async(src_ptr, &dst_ptr, src_alloc_record, dst_alloc_record, size, ctx); } void ResourceManager::memset(void* ptr, int value, std::size_t length) { UMPIRE_LOG(Debug, "(ptr=" << ptr << ", value=" << value << ", length=" << length << ")"); auto& op_registry = op::MemoryOperationRegistry::getInstance(); auto alloc_record = m_allocations.find(ptr); std::ptrdiff_t offset = static_cast<char*>(ptr) - static_cast<char*>(alloc_record->ptr); std::size_t size = alloc_record->size - offset; if (length == 0) { length = size; } UMPIRE_REPLAY(R"( "event": "memset", "payload": { )" << R"( "ptr": ")" << ptr << R"(")" << R"(, "value": )" << value << R"(, "size": )" << size << R"(, "allocator_ref": ")" << alloc_record->strategy << R"(")" << R"( })"); if (length > size) { UMPIRE_ERROR(runtime_error, umpire::fmt::format("Cannot memset over the end of allocation: {} -> {}", length, size)); } auto op = op_registry.find("MEMSET", alloc_record->strategy, alloc_record->strategy); op->apply(ptr, alloc_record, value, length); } camp::resources::EventProxy<camp::resources::Resource> ResourceManager::memset(void* ptr, int value, camp::resources::Resource& ctx, std::size_t length) { UMPIRE_LOG(Debug, "(ptr=" << ptr << ", value=" << value << ", length=" << length << ")"); auto& op_registry = op::MemoryOperationRegistry::getInstance(); auto alloc_record = m_allocations.find(ptr); std::ptrdiff_t offset = static_cast<char*>(ptr) - static_cast<char*>(alloc_record->ptr); std::size_t size = alloc_record->size - offset; if (length == 0) { length = size; } if (length > size) { UMPIRE_ERROR(runtime_error, umpire::fmt::format("Cannot memset over the end of allocation: {} -> {}", length, size)); } auto op = op_registry.find("MEMSET", alloc_record->strategy, alloc_record->strategy); return op->apply_async(ptr, alloc_record, value, length, ctx); } void* ResourceManager::reallocate(void* current_ptr, std::size_t new_size) { strategy::AllocationStrategy* strategy; if (current_ptr != nullptr) { auto alloc_record = m_allocations.find(current_ptr); strategy = alloc_record->strategy; } else { strategy = getDefaultAllocator().getAllocationStrategy(); } UMPIRE_REPLAY(R"( "event": "reallocate", "payload": {)" << R"( "ptr": ")" << current_ptr << R"(")" << R"(, "size": )" << new_size << R"(, "allocator_ref": ")" << strategy << R"(" } )"); void* new_ptr{reallocate_impl(current_ptr, new_size, Allocator(strategy))}; UMPIRE_REPLAY(R"( "event": "reallocate", "payload": {)" << R"( "ptr": ")" << current_ptr << R"(")" << R"(, "size": )" << new_size << R"(, "allocator_ref": ")" << strategy << R"(" } )" << R"(, "result": { "memory_ptr": ")" << new_ptr << R"(" } )"); return new_ptr; } void* ResourceManager::reallocate(void* current_ptr, std::size_t new_size, camp::resources::Resource& ctx) { strategy::AllocationStrategy* strategy; if (current_ptr != nullptr) { auto alloc_record = m_allocations.find(current_ptr); strategy = alloc_record->strategy; } else { strategy = getDefaultAllocator().getAllocationStrategy(); } void* new_ptr{reallocate_impl(current_ptr, new_size, Allocator(strategy), ctx)}; return new_ptr; } void* ResourceManager::reallocate(void* current_ptr, std::size_t new_size, Allocator alloc) { UMPIRE_REPLAY(R"( "event": "reallocate_ex", "payload": {)" << R"( "ptr": ")" << current_ptr << R"(")" << R"(, "size": )" << new_size << R"(, "allocator_ref": ")" << alloc.getAllocationStrategy() << R"(" } )"); void* new_ptr{reallocate_impl(current_ptr, new_size, alloc)}; UMPIRE_REPLAY(R"( "event": "reallocate_ex", "payload": {)" << R"( "ptr": ")" << current_ptr << R"(")" << R"(, "size": )" << new_size << R"(, "allocator_ref": ")" << alloc.getAllocationStrategy() << R"(" } )" << R"(, "result": { "memory_ptr": ")" << new_ptr << R"(" } )"); return new_ptr; } void* ResourceManager::reallocate(void* current_ptr, std::size_t new_size, Allocator alloc, camp::resources::Resource& ctx) { void* new_ptr{reallocate_impl(current_ptr, new_size, alloc, ctx)}; return new_ptr; } void* ResourceManager::reallocate_impl(void* current_ptr, std::size_t new_size, Allocator allocator) { UMPIRE_LOG(Debug, "(current_ptr=" << current_ptr << ", new_size=" << new_size << ", with Allocator " << allocator.getName() << ")"); void* new_ptr; // // If this is a brand new allocation, no reallocation necessary, just allocate // if (current_ptr == nullptr) { new_ptr = allocator.allocate(new_size); } else { auto alloc_record = m_allocations.find(current_ptr); auto alloc = Allocator(alloc_record->strategy); if (alloc_record->strategy != allocator.getAllocationStrategy()) { UMPIRE_ERROR(runtime_error, umpire::fmt::format("Cannot reallocate {} from allocator \"{}\" with allocator \"{}\"", current_ptr, alloc.getName(), allocator.getName())); } // // Special case 0-byte size here // if (new_size == 0) { alloc.deallocate(current_ptr); new_ptr = alloc.allocate(new_size); } else { auto& op_registry = op::MemoryOperationRegistry::getInstance(); if (current_ptr != alloc_record->ptr) { UMPIRE_ERROR(runtime_error, umpire::fmt::format("Cannot reallocate an offset ptr (ptr={}, base={})", current_ptr, alloc_record->ptr)); } std::shared_ptr<umpire::op::MemoryOperation> op; if (alloc_record->strategy->getPlatform() == Platform::host && getAllocator("HOST").getId() != alloc_record->strategy->getId()) { op = op_registry.find("REALLOCATE", std::make_pair(Platform::undefined, Platform::undefined)); } else { op = op_registry.find("REALLOCATE", alloc_record->strategy, alloc_record->strategy); } op->transform(current_ptr, &new_ptr, alloc_record, alloc_record, new_size); } } return new_ptr; } void* ResourceManager::reallocate_impl(void* current_ptr, std::size_t new_size, Allocator allocator, camp::resources::Resource& ctx) { UMPIRE_LOG(Debug, "(current_ptr=" << current_ptr << ", new_size=" << new_size << ", with Allocator " << allocator.getName() << ")"); void* new_ptr; // // If this is a brand new allocation, no reallocation necessary, just allocate // if (current_ptr == nullptr) { new_ptr = allocator.allocate(new_size); } else { auto alloc_record = m_allocations.find(current_ptr); auto alloc = Allocator(alloc_record->strategy); if (alloc_record->strategy != allocator.getAllocationStrategy()) { UMPIRE_ERROR(runtime_error, umpire::fmt::format("Cannot reallocate {} from allocator \"{}\" with allocator \"{}\"", current_ptr, alloc.getName(), allocator.getName())); } // // Special case 0-byte size here // if (new_size == 0) { alloc.deallocate(current_ptr); new_ptr = alloc.allocate(new_size); } else { auto& op_registry = op::MemoryOperationRegistry::getInstance(); if (current_ptr != alloc_record->ptr) { UMPIRE_ERROR(runtime_error, umpire::fmt::format("Cannot reallocate an offset ptr (ptr={}, base={})", current_ptr, alloc_record->ptr)); } std::shared_ptr<umpire::op::MemoryOperation> op; if (alloc_record->strategy->getPlatform() == Platform::host && getAllocator("HOST").getId() != alloc_record->strategy->getId()) { op = op_registry.find("REALLOCATE", std::make_pair(Platform::undefined, Platform::undefined)); op->transform(current_ptr, &new_ptr, alloc_record, alloc_record, new_size); } else { op = op_registry.find("REALLOCATE", alloc_record->strategy, alloc_record->strategy); op->transform_async(current_ptr, &new_ptr, alloc_record, alloc_record, new_size, ctx); } } } return new_ptr; } void* ResourceManager::move(void* ptr, Allocator allocator) { UMPIRE_LOG(Debug, "(src_ptr=" << ptr << ", allocator=" << allocator.getName() << ")"); UMPIRE_REPLAY(R"( "event": "move", "payload": {")" << R"( "ptr": ")" << ptr << R"(")" << R"(, "allocator_ref": ")" << allocator.getAllocationStrategy() << R"(" })"); auto alloc_record = m_allocations.find(ptr); // short-circuit if ptr was allocated by 'allocator' if (alloc_record->strategy == allocator.getAllocationStrategy()) { return ptr; } #if defined(UMPIRE_ENABLE_NUMA) { auto base_strategy = util::unwrap_allocator<strategy::AllocationStrategy>(allocator); // If found, use op::NumaMoveOperation to move in-place (same address // returned) if (dynamic_cast<strategy::NumaPolicy*>(base_strategy)) { auto& op_registry = op::MemoryOperationRegistry::getInstance(); auto src_alloc_record = m_allocations.find(ptr); const std::size_t size{src_alloc_record->size}; util::AllocationRecord dst_alloc_record{nullptr, size, allocator.getAllocationStrategy()}; if (size > 0) { auto op = op_registry.find("MOVE", src_alloc_record->strategy, dst_alloc_record.strategy); void* ret{nullptr}; op->transform(ptr, &ret, src_alloc_record, &dst_alloc_record, size); UMPIRE_ASSERT(ret == ptr); } UMPIRE_REPLAY(R"( "event": "move", "payload": {)" << R"( "ptr": ")" << ptr << R"(")" << R"(, "allocator": ")" << allocator.getAllocationStrategy() << R"(" })" << R"(, "result": { "ptr": ")" << ptr << R"(" })"); return ptr; } } #endif if (ptr != alloc_record->ptr) { UMPIRE_ERROR(runtime_error, umpire::fmt::format("Cannot move an offset ptr (ptr={}, base={})", ptr, alloc_record->ptr)); } void* dst_ptr{allocator.allocate(alloc_record->size)}; copy(dst_ptr, ptr); UMPIRE_REPLAY(R"( "event": "move", "payload": {)" << R"( "ptr": ")" << ptr << R"(")" << R"(, "allocator": ")" << allocator.getAllocationStrategy() << R"(" })" << R"(, "result": { "ptr": ")" << dst_ptr << R"(" })"); deallocate(ptr); return dst_ptr; } camp::resources::EventProxy<camp::resources::Resource> ResourceManager::prefetch(void* ptr, int device, camp::resources::Resource& ctx) { UMPIRE_LOG(Debug, "(ptr=" << ptr << ", device=" << device << ")"); auto& op_registry = op::MemoryOperationRegistry::getInstance(); auto alloc_record = m_allocations.find(ptr); if (alloc_record->strategy->getTraits().resource != umpire::MemoryResourceTraits::resource_type::um) { UMPIRE_ERROR(runtime_error, "ResourceManager::prefetch only works on allocations from a UM resource."); } std::ptrdiff_t offset = static_cast<char*>(ptr) - static_cast<char*>(alloc_record->ptr); std::size_t size = alloc_record->size - offset; auto op = op_registry.find("PREFETCH", alloc_record->strategy, alloc_record->strategy); return op->apply_async(ptr, alloc_record, device, size, ctx); } void ResourceManager::deallocate(void* ptr) { UMPIRE_LOG(Debug, "(ptr=" << ptr << ")"); Allocator allocator{findAllocatorForPointer(ptr)}; allocator.deallocate(ptr); } std::size_t ResourceManager::getSize(void* ptr) const { auto record = m_allocations.find(ptr); UMPIRE_LOG(Debug, "(ptr=" << ptr << ") returning " << record->size); return record->size; } strategy::AllocationStrategy* ResourceManager::findAllocatorForId(int id) { auto allocator_i = m_allocators_by_id.find(id); if (allocator_i == m_allocators_by_id.end()) { UMPIRE_ERROR(runtime_error, umpire::fmt::format("Cannot find allocator with id: {}", id)); } UMPIRE_LOG(Debug, "(id=" << id << ") returning " << allocator_i->second); return allocator_i->second; } strategy::AllocationStrategy* ResourceManager::findAllocatorForPointer(void* ptr) { auto allocation_record = m_allocations.find(ptr); if (!allocation_record->strategy) { UMPIRE_ERROR(runtime_error, umpire::fmt::format("Cannot find allocator for pointer: {}", ptr)); } UMPIRE_LOG(Debug, "(ptr=" << ptr << ") returning " << allocation_record->strategy); return allocation_record->strategy; } std::vector<std::string> ResourceManager::getAllocatorNames() const noexcept { std::vector<std::string> names; for (auto it = m_allocators_by_name.begin(); it != m_allocators_by_name.end(); ++it) { names.push_back(it->first); } UMPIRE_LOG(Debug, "() returning " << names.size() << " allocators"); return names; } std::vector<int> ResourceManager::getAllocatorIds() const noexcept { std::vector<int> ids; for (auto& it : m_allocators_by_id) { ids.push_back(it.first); } return ids; } int ResourceManager::getNextId() noexcept { return m_id++; } std::string ResourceManager::getAllocatorInformation() const noexcept { std::ostringstream info; for (auto& it : m_allocators_by_name) { info << *it.second << " "; } return info.str(); } strategy::AllocationStrategy* ResourceManager::getZeroByteAllocator() { return m_zero_byte_pool; } std::shared_ptr<op::MemoryOperation> ResourceManager::getOperation(const std::string& operation_name, Allocator src_allocator, Allocator dst_allocator) { auto& op_registry = op::MemoryOperationRegistry::getInstance(); return op_registry.find(operation_name, src_allocator.getAllocationStrategy(), dst_allocator.getAllocationStrategy()); } int ResourceManager::getNumDevices() const { int device_count{0}; #if defined(UMPIRE_ENABLE_CUDA) ::cudaGetDeviceCount(&device_count); #elif defined(UMPIRE_ENABLE_HIP) hipGetDeviceCount(&device_count); #elif defined(UMPIRE_ENABLE_SYCL) sycl::platform platform(sycl::gpu_selector{}); auto devices = platform.get_devices(); for (auto& device : devices) { if (device.is_gpu()) { if (device.get_info<sycl::info::device::partition_max_sub_devices>() > 0) { device_count += device.get_info<sycl::info::device::partition_max_sub_devices>(); } else { device_count++; } } } #endif return device_count; } } // end of namespace umpire
34.529894
120
0.637197
degrbg
ba39fbb769c22c3154fd5c898e3ce060291ae26e
1,378
cpp
C++
tests/llvmir2hll/optimizer/optimizers/deref_address_optimizer_tests.cpp
mehrdad-shokri/retdec
a82f16e97b163afe789876e0a819489c5b9b358e
[ "MIT", "Zlib", "BSD-3-Clause" ]
4,816
2017-12-12T18:07:09.000Z
2019-04-17T02:01:04.000Z
tests/llvmir2hll/optimizer/optimizers/deref_address_optimizer_tests.cpp
mehrdad-shokri/retdec
a82f16e97b163afe789876e0a819489c5b9b358e
[ "MIT", "Zlib", "BSD-3-Clause" ]
514
2017-12-12T18:22:52.000Z
2019-04-16T16:07:11.000Z
tests/llvmir2hll/optimizer/optimizers/deref_address_optimizer_tests.cpp
mehrdad-shokri/retdec
a82f16e97b163afe789876e0a819489c5b9b358e
[ "MIT", "Zlib", "BSD-3-Clause" ]
579
2017-12-12T18:38:02.000Z
2019-04-11T13:32:53.000Z
/** * @file tests/llvmir2hll/optimizer/optimizers/deref_address_optimizer_tests.cpp * @brief Tests for the @c deref_address_optimizer module. * @copyright (c) 2017 Avast Software, licensed under the MIT license */ #include <gtest/gtest.h> #include "retdec/llvmir2hll/ir/empty_stmt.h" #include "llvmir2hll/ir/tests_with_module.h" #include "retdec/llvmir2hll/optimizer/optimizers/deref_address_optimizer.h" using namespace ::testing; namespace retdec { namespace llvmir2hll { namespace tests { /** * @brief Tests for the @c deref_address_optimizer module. */ class DerefAddressOptimizerTests: public TestsWithModule {}; TEST_F(DerefAddressOptimizerTests, OptimizerHasNonEmptyID) { ShPtr<DerefAddressOptimizer> optimizer( new DerefAddressOptimizer(module)); EXPECT_TRUE(!optimizer->getId().empty()) << "the optimizer should have a non-empty ID"; } TEST_F(DerefAddressOptimizerTests, InEmptyBodyThereIsNothingToOptimize) { // Optimize the module. Optimizer::optimize<DerefAddressOptimizer>(module); // Check that the output is correct. ASSERT_TRUE(isa<EmptyStmt>(testFunc->getBody())) << "expected EmptyStmt, got " << testFunc->getBody(); EXPECT_TRUE(!testFunc->getBody()->hasSuccessor()) << "expected no successors of the statement, but got " << testFunc->getBody()->getSuccessor(); } } // namespace tests } // namespace llvmir2hll } // namespace retdec
28.122449
79
0.766328
mehrdad-shokri
ba3ae8078796072527773316a06b51bcb4a4a4eb
4,029
cpp
C++
source/tests/metacall_load_memory_test/source/metacall_load_memory_test.cpp
0xAnarz/core
0c9310d9c9c2074782b3641a639b1e1a931f1afe
[ "Apache-2.0" ]
928
2018-12-26T22:40:59.000Z
2022-03-31T12:17:43.000Z
source/tests/metacall_load_memory_test/source/metacall_load_memory_test.cpp
akshgpt7/core
29dda647a2c421ad941ad12bee7111d4fa0940de
[ "Apache-2.0" ]
132
2019-03-01T21:01:17.000Z
2022-03-17T09:00:42.000Z
source/tests/metacall_load_memory_test/source/metacall_load_memory_test.cpp
akshgpt7/core
29dda647a2c421ad941ad12bee7111d4fa0940de
[ "Apache-2.0" ]
112
2019-01-15T09:36:11.000Z
2022-03-12T06:39:01.000Z
/* * MetaCall Library by Parra Studios * A library for providing a foreign function interface calls. * * Copyright (C) 2016 - 2021 Vicente Eduardo Ferrer Garcia <vic798@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <gtest/gtest.h> #include <metacall/metacall.h> #include <metacall/metacall_loaders.h> class metacall_load_memory_test : public testing::Test { public: }; TEST_F(metacall_load_memory_test, DefaultConstructor) { metacall_print_info(); metacall_log_stdio_type log_stdio = { stdout }; ASSERT_EQ((int)0, (int)metacall_log(METACALL_LOG_STDIO, (void *)&log_stdio)); /* Python */ #if defined(OPTION_BUILD_LOADERS_PY) { static const char buffer[] = "#!/usr/bin/env python3\n" "def multmem(left: int, right: int) -> int:\n" "\tresult = left * right;\n" "\tprint(left, ' * ', right, ' = ', result);\n" "\treturn result;"; static const char tag[] = "py"; const long seven_multiples_limit = 10; long iterator; ASSERT_EQ((int)0, (int)metacall_load_from_memory(tag, buffer, sizeof(buffer), NULL)); void *ret = NULL; ret = metacall("multmem", 5, 15); EXPECT_NE((void *)NULL, (void *)ret); EXPECT_EQ((long)metacall_value_to_long(ret), (long)75); metacall_value_destroy(ret); for (iterator = 0; iterator <= seven_multiples_limit; ++iterator) { ret = metacall("multmem", 5, iterator); EXPECT_NE((void *)NULL, (void *)ret); EXPECT_EQ((long)metacall_value_to_long(ret), (long)(5 * iterator)); metacall_value_destroy(ret); } } #endif /* OPTION_BUILD_LOADERS_PY */ /* Ruby */ #if defined(OPTION_BUILD_LOADERS_RB) { static const char buffer[] = "#!/usr/bin/ruby\n" "#def comment_line(a: Fixnum)\n" "# puts('This never will be shown', a, '!')\n" "# return a\n" "#end\n" "=begin\n" "def comment_multi_line(a: Fixnum)\n" " puts('This =begin =end block never will be shown', a, '!')\n" " return a\n" "end\n" "=end\n" "def mem_multiply(left: Fixnum, right: Fixnum)\n" " result = left * right\n" " puts('Multiply', result, '!')\n" " return result\n" "end"; static const char extension[] = "rb"; ASSERT_EQ((int)0, (int)metacall_load_from_memory(extension, buffer, sizeof(buffer), NULL)); void *ret = NULL; ret = metacall("mem_multiply", 5, 5); EXPECT_NE((void *)NULL, (void *)ret); EXPECT_EQ((int)metacall_value_to_int(ret), (int)25); metacall_value_destroy(ret); ret = metacall("comment_line", 15); EXPECT_EQ((void *)NULL, (void *)ret); ret = metacall("comment_multi_line", 25); EXPECT_EQ((void *)NULL, (void *)ret); } #endif /* OPTION_BUILD_LOADERS_RB */ /* JavaScript V8 */ #if defined(OPTION_BUILD_LOADERS_JS) { static const char buffer[] = "#!/usr/bin/env sh\n" /*"':' //; exec \"$(command -v nodejs || command -v node)\" \"$0\" \"$@\"\n"*/ "/* function mem_comment(a :: Number) {\n" " return 15;\n" "} */\n" "function mem_divide(a :: Number, b :: Number) :: Number {\n" " return (a / b);\n" "}\n"; static const char extension[] = "js"; ASSERT_EQ((int)0, (int)metacall_load_from_memory(extension, buffer, sizeof(buffer), NULL)); void *ret = NULL; ret = metacall("mem_divide", 10.0, 5.0); EXPECT_NE((void *)NULL, (void *)ret); EXPECT_EQ((double)metacall_value_to_double(ret), (double)2.0); metacall_value_destroy(ret); ret = metacall("mem_comment", 10.0); EXPECT_EQ((void *)NULL, (void *)ret); } #endif /* OPTION_BUILD_LOADERS_JS */ EXPECT_EQ((int)0, (int)metacall_destroy()); }
25.18125
93
0.66071
0xAnarz
ba3c203c872ed128aef1c0071b53448e40c8700a
3,308
hxx
C++
Modules/Search/max_m_elements.hxx
michael-jeulinl/Hurna-Lib
624f60454fdab4dadcd33a3910c369f46ad5b4b0
[ "MIT" ]
17
2018-06-02T13:08:15.000Z
2022-01-05T15:01:28.000Z
Modules/Search/max_m_elements.hxx
michael-jeulinl/Hurna-Lib
624f60454fdab4dadcd33a3910c369f46ad5b4b0
[ "MIT" ]
2
2019-03-29T11:01:47.000Z
2021-11-21T13:45:52.000Z
Modules/Search/max_m_elements.hxx
michael-jeulinl/Hurna-Lib
624f60454fdab4dadcd33a3910c369f46ad5b4b0
[ "MIT" ]
9
2020-04-27T23:31:33.000Z
2022-01-03T09:02:25.000Z
/*=========================================================================================================== * * HUC - Hurna Core * * Copyright (c) Michael Jeulin-Lagarrigue * * Licensed under the MIT License, you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://github.com/Hurna/Hurna-Core/blob/master/LICENSE * * 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. * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * *=========================================================================================================*/ #ifndef MODULE_SEARCH_MAX_M_ELEMENTS_HXX #define MODULE_SEARCH_MAX_M_ELEMENTS_HXX // STD includes #include <functional> #include <limits> namespace huc { namespace search { /// Max M Elements /// Identify the m maximal/minimal values sorted in decreasing/increasing order. /// /// @details using this algorithm with the size of the vector as the number /// of elements to be found will give you a bubble sort algorithm. /// /// @tparam Container type used to return the elements. /// @tparam IT type using to go through the collection. /// @tparam Compare functor type. /// /// @param begin,end iterators to the initial and final positions of /// the sequence to be sorted. The range used is [first,last), which contains all the elements between /// first and last, including the element pointed by first but not the element pointed by last. /// @param m the numbers of max elements value to be found. /// /// @return a vector of sorted in decreasing/increasing order of the m maximum/minimum /// elements, an empty array in case of failure. template <typename Container, typename IT, typename Compare = std::greater_equal<typename std::iterator_traits<IT>::value_type>> Container MaxMElements(const IT& begin, const IT& end, const int m) { if (m < 1 || m > std::distance(begin, end)) return Container(); // Initiale values depends on the comparator functor const auto limitValue = Compare()(0, std::numeric_limits<typename std::iterator_traits<IT>::value_type>::lowest()) ? std::numeric_limits<typename std::iterator_traits<IT>::value_type>::lowest() : std::numeric_limits<typename std::iterator_traits<IT>::value_type>::max(); // Allocate the container final size Container maxMElements; maxMElements.resize(m, limitValue); for (auto it = begin; it != end; ++it) { // Insert the value at the right place and bubble down replacement value int index = 0; auto tmpVal = *it; for (auto subIt = maxMElements.begin(); index < m; ++subIt, ++index) if (Compare()(tmpVal, *subIt)) std::swap(*subIt, tmpVal); } return maxMElements; } } } #endif // MODULE_COLLECTIONS_SEARCH_HXX
40.839506
109
0.635732
michael-jeulinl
ba4197f1be408b08539d541a39e6833018fdd6f1
546
cpp
C++
Assets/oculusintegration/Samples/VoipNetChat/VoIPLoopback.cpp
vrshiftr/CovidVR
24f17bf567e58af6646688e32c26c8345d70b2bb
[ "MIT" ]
null
null
null
Assets/oculusintegration/Samples/VoipNetChat/VoIPLoopback.cpp
vrshiftr/CovidVR
24f17bf567e58af6646688e32c26c8345d70b2bb
[ "MIT" ]
null
null
null
Assets/oculusintegration/Samples/VoipNetChat/VoIPLoopback.cpp
vrshiftr/CovidVR
24f17bf567e58af6646688e32c26c8345d70b2bb
[ "MIT" ]
null
null
null
// OpenAL header files #include <al.h> #include <alc.h> #include <list> #include <conio.h> #include "OVR_Platform.h" #include "State.h" #include "Audio.h" Audio oAudio; int main(int argc, char** argv) { if (argc < 2) { fprintf(stderr, "usage: VoIPLoopback.exe <appID>"); exit(1); } Audio oAudio; // Init with false to use OpenAL Microphone instead of OVR if (oAudio.initialize(argv[1], true) != 0) { fprintf(stderr, "Could not initialize the Oculus Platform\n"); return 1; } oAudio.mainLoop(); return 0; }
17.0625
66
0.64652
vrshiftr
ba41d20d8af43a9e17255b43a4fa456ea5b3ad7d
28,011
cpp
C++
dev/Code/Framework/AzToolsFramework/AzToolsFramework/PropertyTreeEditor/PropertyTreeEditor.cpp
BadDevCode/lumberyard
3d688932f919dbf5821f0cb8a210ce24abe39e9e
[ "AML" ]
2
2020-06-27T12:13:44.000Z
2020-06-27T12:13:46.000Z
dev/Code/Framework/AzToolsFramework/AzToolsFramework/PropertyTreeEditor/PropertyTreeEditor.cpp
olivier-be/lumberyard
3d688932f919dbf5821f0cb8a210ce24abe39e9e
[ "AML" ]
null
null
null
dev/Code/Framework/AzToolsFramework/AzToolsFramework/PropertyTreeEditor/PropertyTreeEditor.cpp
olivier-be/lumberyard
3d688932f919dbf5821f0cb8a210ce24abe39e9e
[ "AML" ]
null
null
null
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #include <AzToolsFramework/PropertyTreeEditor/PropertyTreeEditor.h> #include <AzToolsFramework/UI/UICore/WidgetHelpers.h> #include <AzFramework/StringFunc/StringFunc.h> #include <AzCore/Component/ComponentApplicationBus.h> #include <AzCore/Asset/AssetManager.h> #include <AzFramework/Asset/SimpleAsset.h> #include <AzCore/Asset/AssetManagerBus.h> namespace AzToolsFramework { PropertyTreeEditor::PropertyTreeEditorNode::PropertyTreeEditorNode(const AZ::TypeId& typeId, AzToolsFramework::InstanceDataNode* nodePtr, AZStd::optional<AZStd::string> newName) : m_typeId(typeId) , m_nodePtr(nodePtr) , m_newName(newName) { } PropertyTreeEditor::PropertyTreeEditorNode::PropertyTreeEditorNode(AzToolsFramework::InstanceDataNode* nodePtr, AZStd::optional<AZStd::string> newName) : m_nodePtr(nodePtr) , m_newName(newName) { } PropertyTreeEditor::PropertyTreeEditorNode::PropertyTreeEditorNode(AzToolsFramework::InstanceDataNode* nodePtr, AZStd::optional<AZStd::string> newName, const AZStd::string& parentPath, const AZStd::vector<ChangeNotification>& notifiers) : m_nodePtr(nodePtr) , m_newName(newName) , m_parentPath(parentPath) , m_notifiers(notifiers) { } PropertyTreeEditor::PropertyTreeEditor(void* pointer, AZ::TypeId typeId) { AZ::ComponentApplicationBus::BroadcastResult(m_serializeContext, &AZ::ComponentApplicationRequests::GetSerializeContext); AZ_Error("Editor", m_serializeContext, "Serialize context not available"); if (!m_serializeContext) { return; } m_instanceDataHierarchy = AZStd::shared_ptr<InstanceDataHierarchy>(aznew InstanceDataHierarchy()); m_instanceDataHierarchy->AddRootInstance(pointer, typeId); m_instanceDataHierarchy->Build(m_serializeContext, AZ::SerializeContext::ENUM_ACCESS_FOR_READ); PopulateNodeMap(m_instanceDataHierarchy->GetChildren()); } const AZStd::vector<AZStd::string> PropertyTreeEditor::BuildPathsList() { AZStd::vector<AZStd::string> pathsList; for (auto node : m_nodeMap) { pathsList.push_back(node.first + " (" + node.second.m_nodePtr->GetClassMetadata()->m_name + ")"); } return pathsList; } AZStd::string PropertyTreeEditor::GetPropertyType(const AZStd::string_view propertyPath) { if (m_nodeMap.find(propertyPath) == m_nodeMap.end()) { AZ_Warning("PropertyTreeEditor", false, "GetProperty - path provided was not found in tree."); return AZStd::string(""); } const PropertyTreeEditorNode& pteNode = m_nodeMap[propertyPath]; // Notify the user that they should not use the deprecated name any more, and what it has been replaced with. AZ_Warning("PropertyTreeEditor", !pteNode.m_newName, "GetProperty - This path is deprecated; property name has been changed to %s.", pteNode.m_newName.value().c_str()); return AZStd::string(pteNode.m_nodePtr->GetClassMetadata()->m_name); } PropertyTreeEditor::PropertyAccessOutcome PropertyTreeEditor::GetProperty(const AZStd::string_view propertyPath) { if (m_nodeMap.find(propertyPath) == m_nodeMap.end()) { AZ_Warning("PropertyTreeEditor", false, "GetProperty - path provided [ %.*s ] was not found in tree.", static_cast<int>(propertyPath.size()), propertyPath.data()); return {PropertyAccessOutcome::ErrorType("GetProperty - path provided was not found in tree.")}; } PropertyTreeEditorNode pteNode = m_nodeMap[propertyPath]; // Notify the user that they should not use the deprecated name any more, and what it has been replaced with. AZ_Warning("PropertyTreeEditor", !pteNode.m_newName, "GetProperty - This path [ %.*s ] is deprecated; property name has been changed to %s.", static_cast<int>(propertyPath.size()), propertyPath.data(), pteNode.m_newName.value().c_str()); void* nodeData = nullptr; AZ::TypeId type = pteNode.m_nodePtr->GetClassMetadata()->m_typeId; if (!pteNode.m_nodePtr->ReadRaw(nodeData, type)) { AZ_Warning("PropertyTreeEditor", false, "GetProperty - path provided [ %.*s ] was found, but read operation failed.", static_cast<int>(propertyPath.size()), propertyPath.data()); return {PropertyAccessOutcome::ErrorType("GetProperty - path provided was found, but read operation failed.")}; } if (pteNode.m_nodePtr->GetClassMetadata()->m_azRtti && pteNode.m_nodePtr->GetClassMetadata()->m_azRtti->IsTypeOf(azrtti_typeid<AzFramework::SimpleAssetReferenceBase>())) { // Handle SimpleAssetReference (it should return an AssetId) AzFramework::SimpleAssetReferenceBase* instancePtr = reinterpret_cast<AzFramework::SimpleAssetReferenceBase*>(nodeData); AZ::Data::AssetId result = AZ::Data::AssetId(); AZStd::string assetPath = instancePtr->GetAssetPath(); if (!assetPath.empty()) { AZ::Data::AssetCatalogRequestBus::BroadcastResult(result, &AZ::Data::AssetCatalogRequests::GetAssetIdByPath, assetPath.c_str(), AZ::Uuid(), false); } return {PropertyAccessOutcome::ValueType(result)}; } else if (pteNode.m_nodePtr->GetClassMetadata()->m_azRtti && pteNode.m_nodePtr->GetClassMetadata()->m_azRtti->GetGenericTypeId() == azrtti_typeid<AZ::Data::Asset>()) { // Handle Asset<> (it should return an AssetId) AZ::Data::Asset<AZ::Data::AssetData>* instancePtr = reinterpret_cast<AZ::Data::Asset<AZ::Data::AssetData>*>(nodeData); return {PropertyAccessOutcome::ValueType(instancePtr->GetId())}; } else { // Default case - just return the value wrapped into an any AZStd::any typeInfoHelper = m_serializeContext->CreateAny(type); return {PropertyAccessOutcome::ValueType(nodeData, typeInfoHelper.get_type_info())}; } } PropertyTreeEditor::PropertyAccessOutcome PropertyTreeEditor::SetProperty(const AZStd::string_view propertyPath, const AZStd::any& value) { if (m_nodeMap.find(propertyPath) == m_nodeMap.end()) { AZ_Warning("PropertyTreeEditor", false, "SetProperty - path provided [ %.*s ] was not found in tree.", static_cast<int>(propertyPath.size()), propertyPath.data()); return {PropertyAccessOutcome::ErrorType("SetProperty - path provided was not found in tree.")}; } PropertyTreeEditorNode pteNode = m_nodeMap[propertyPath]; // Notify the user that they should not use the deprecated name any more, and what it has been replaced with. AZ_Warning("PropertyTreeEditor", !pteNode.m_newName, "SetProperty - This path [ %.*s ] is deprecated; property name has been changed to %s.", static_cast<int>(propertyPath.size()), propertyPath.data(), pteNode.m_newName.value().c_str()); // Handle Asset cases differently if (value.type() == azrtti_typeid<AZ::Data::AssetId>() && pteNode.m_nodePtr->GetClassMetadata()->m_azRtti && pteNode.m_nodePtr->GetClassMetadata()->m_azRtti->IsTypeOf(azrtti_typeid<AzFramework::SimpleAssetReferenceBase>())) { // Handle SimpleAssetReference size_t numInstances = pteNode.m_nodePtr->GetNumInstances(); // Get Asset Id from any AZ::Data::AssetId assetId = AZStd::any_cast<AZ::Data::AssetId>(value); for (size_t idx = 0; idx < numInstances; ++idx) { AzFramework::SimpleAssetReferenceBase* instancePtr = reinterpret_cast<AzFramework::SimpleAssetReferenceBase*>(pteNode.m_nodePtr->GetInstance(idx)); // Check if valid assetId was provided if (assetId.IsValid()) { // Get Asset Path from Asset Id AZStd::string assetPath; AZ::Data::AssetCatalogRequestBus::BroadcastResult(assetPath, &AZ::Data::AssetCatalogRequests::GetAssetPathById, assetId); // Set Asset Path in Asset Reference instancePtr->SetAssetPath(assetPath.c_str()); } else { // Clear Asset Path in Asset Reference instancePtr->SetAssetPath(""); } } PropertyNotify(&pteNode); return {PropertyAccessOutcome::ValueType(value)}; } else if (value.type() == azrtti_typeid<AZ::Data::AssetId>() && pteNode.m_nodePtr->GetClassMetadata()->m_azRtti && pteNode.m_nodePtr->GetClassMetadata()->m_azRtti->GetGenericTypeId() == azrtti_typeid<AZ::Data::Asset>()) { // Handle Asset<> size_t numInstances = pteNode.m_nodePtr->GetNumInstances(); // Get Asset Id from any AZ::Data::AssetId assetId = AZStd::any_cast<AZ::Data::AssetId>(value); for (size_t idx = 0; idx < numInstances; ++idx) { AZ::Data::Asset<AZ::Data::AssetData>* instancePtr = reinterpret_cast<AZ::Data::Asset<AZ::Data::AssetData>*>(pteNode.m_nodePtr->GetInstance(idx)); if (assetId.IsValid()) { *instancePtr = AZ::Data::AssetManager::Instance().GetAsset(assetId, instancePtr->GetType()); } else { *instancePtr = AZ::Data::Asset<AZ::Data::AssetData>(AZ::Data::AssetId(), instancePtr->GetType()); } } PropertyNotify(&pteNode); return {PropertyAccessOutcome::ValueType(value)}; } // Default handler //A temporary conversion buffer in case the src and dst data types are different. AZStd::any convertedValue; // Check if types match, or convert the value if its type supports it. const void* valuePtr = HandleTypeConversion(value.type(), pteNode.m_nodePtr->GetClassMetadata()->m_typeId, AZStd::any_cast<void>(&value), convertedValue); if (!valuePtr) { // If types are different and cannot be converted, bail AZ_Warning("PropertyTreeEditor", false, "SetProperty - value type cannot be converted to the property's type."); return {PropertyAccessOutcome::ErrorType("SetProperty - value type cannot be converted to the property's type.")}; } pteNode.m_nodePtr->WriteRaw(valuePtr, pteNode.m_nodePtr->GetClassMetadata()->m_typeId); PropertyNotify(&pteNode); return {PropertyAccessOutcome::ValueType(value)}; } bool PropertyTreeEditor::CompareProperty(const AZStd::string_view propertyPath, const AZStd::any& value) { if (m_nodeMap.find(propertyPath) == m_nodeMap.end()) { AZ_Error("PropertyTreeEditor", false, "CompareProperty - path provided [ %.*s ] was not found in tree.", static_cast<int>(propertyPath.size()), propertyPath.data()); return false; } PropertyTreeEditorNode pteNode = m_nodeMap[propertyPath]; // Notify the user that they should not use the deprecated name any more, and what it has been replaced with. AZ_Warning("PropertyTreeEditor", !pteNode.m_newName, "CompareProperty - This path [ %.*s ] is deprecated; property name has been changed to %s.", static_cast<int>(propertyPath.size()), propertyPath.data(), pteNode.m_newName.value().c_str()); void* nodeData = nullptr; AZ::TypeId type = pteNode.m_nodePtr->GetClassMetadata()->m_typeId; if (!pteNode.m_nodePtr->ReadRaw(nodeData, type)) { AZ_Warning("PropertyTreeEditor", false, "CompareProperty - path provided [ %.*s ] was found, but read operation failed.", static_cast<int>(propertyPath.size()), propertyPath.data()); return false; } if (pteNode.m_nodePtr->GetClassMetadata()->m_azRtti && pteNode.m_nodePtr->GetClassMetadata()->m_azRtti->IsTypeOf(azrtti_typeid<AzFramework::SimpleAssetReferenceBase>())) { // Handle SimpleAssetReference (it should return an AssetId) AzFramework::SimpleAssetReferenceBase* instancePtr = reinterpret_cast<AzFramework::SimpleAssetReferenceBase*>(nodeData); AZ::Data::AssetId result = AZ::Data::AssetId(); AZStd::string assetPath = instancePtr->GetAssetPath(); if (!assetPath.empty()) { AZ::Data::AssetCatalogRequestBus::BroadcastResult(result, &AZ::Data::AssetCatalogRequests::GetAssetIdByPath, assetPath.c_str(), AZ::Uuid(), false); } return result == AZStd::any_cast<AZ::Data::AssetId>(value); } else if (pteNode.m_nodePtr->GetClassMetadata()->m_azRtti && pteNode.m_nodePtr->GetClassMetadata()->m_azRtti->GetGenericTypeId() == azrtti_typeid<AZ::Data::Asset>()) { // Handle Asset<> (it should return an AssetId) AZ::Data::Asset<AZ::Data::AssetData>* instancePtr = reinterpret_cast<AZ::Data::Asset<AZ::Data::AssetData>*>(nodeData); return instancePtr->GetId() == AZStd::any_cast<AZ::Data::AssetId>(value); } else { //A temporary conversion buffer in case the src and dst data types are different. AZStd::any convertedValue; // Check if types match, or convert the value if its type supports it. const void* valuePtr = HandleTypeConversion(value.type(), pteNode.m_nodePtr->GetClassMetadata()->m_typeId, AZStd::any_cast<void>(&value), convertedValue); if (!valuePtr) { // If types are different and cannot be converted, bail AZ_Warning("PropertyTreeEditor", false, "CompareProperty - value type cannot be converted to the property's type."); return false; } auto& serializerPtr = pteNode.m_nodePtr->GetClassMetadata()->m_serializer; return serializerPtr && serializerPtr->CompareValueData(nodeData, valuePtr); } } const void* PropertyTreeEditor::HandleTypeConversion(AZ::TypeId fromType, AZ::TypeId toType, const void* sourceValuePtr, AZStd::any& convertedValue) { // If types match we don't need to convert. if (fromType == toType) { return sourceValuePtr; } AZ_Assert(sourceValuePtr, "Invalid pointer to the source value"); if (fromType == AZ::AzTypeInfo<double>::Uuid()) { double value = *static_cast<const double*>(sourceValuePtr); return HandleTypeConversion(value, toType, convertedValue); } if (fromType == AZ::AzTypeInfo<AZ::s64>::Uuid()) { AZ::s64 value = *static_cast<const AZ::s64*>(sourceValuePtr); return HandleTypeConversion(value, toType, convertedValue); } return nullptr; } template <typename V> const void* PropertyTreeEditor::HandleTypeConversion(V fromValue, AZ::TypeId toType, AZStd::any& convertedValue) { if (toType == AZ::AzTypeInfo<float>::Uuid()) { convertedValue = aznumeric_cast<float>(fromValue); return &convertedValue; } if (toType == AZ::AzTypeInfo<AZ::u32>::Uuid()) { convertedValue = aznumeric_cast<AZ::u32>(fromValue); return &convertedValue; } if (toType == AZ::AzTypeInfo<AZ::s32>::Uuid()) { convertedValue = aznumeric_cast<AZ::s32>(fromValue); return &convertedValue; } if (toType == AZ::AzTypeInfo<AZ::u16>::Uuid()) { convertedValue = aznumeric_cast<AZ::u16>(fromValue); return &convertedValue; } if (toType == AZ::AzTypeInfo<AZ::s16>::Uuid()) { convertedValue = aznumeric_cast<AZ::s16>(fromValue); return &convertedValue; } if (toType == AZ::AzTypeInfo<AZ::u8>::Uuid()) { convertedValue = aznumeric_cast<AZ::u8>(fromValue); return &convertedValue; } if (toType == AZ::AzTypeInfo<AZ::s8>::Uuid()) { convertedValue = aznumeric_cast<AZ::s8>(fromValue); return &convertedValue; } return nullptr; } void PropertyTreeEditor::HandleChangeNotifyAttribute(PropertyAttributeReader& reader, InstanceDataNode* node, AZStd::vector<ChangeNotification>& notifiers) { AZ::Edit::AttributeFunction<void()>* funcVoid = azdynamic_cast<AZ::Edit::AttributeFunction<void()>*>(reader.GetAttribute()); AZ::Edit::AttributeFunction<AZ::u32()>* funcU32 = azdynamic_cast<AZ::Edit::AttributeFunction<AZ::u32()>*>(reader.GetAttribute()); AZ::Edit::AttributeFunction<AZ::Crc32()>* funcCrc32 = azdynamic_cast<AZ::Edit::AttributeFunction<AZ::Crc32()>*>(reader.GetAttribute()); const AZ::Uuid handlerTypeId = funcVoid ? funcVoid->GetInstanceType() : (funcU32 ? funcU32->GetInstanceType() : (funcCrc32 ? funcCrc32->GetInstanceType() : AZ::Uuid::CreateNull())); InstanceDataNode* targetNode = node; if (!handlerTypeId.IsNull()) { // Walk up the chain looking for the first correct class type to handle the callback while (targetNode) { if (targetNode->GetClassMetadata()) { if (targetNode->GetClassMetadata()->m_azRtti) { if (targetNode->GetClassMetadata()->m_azRtti->IsTypeOf(handlerTypeId)) { // Instance has RTTI, and derives from type expected by the handler. break; } } else { if (handlerTypeId == targetNode->GetClassMetadata()->m_typeId) { // Instance does not have RTTI, and is the type expected by the handler. break; } } } targetNode = targetNode->GetParent(); } } if (targetNode) { notifiers.push_back(ChangeNotification(targetNode, reader.GetAttribute())); } } //! Recursive function - explores the whole hierarchy in search of all class properties //! and saves them in m_nodeMap along with their pipe-separated path for easier access. //! nodeList A list of InstanceDataNodes to add to the map. //! The function will call itself recursively on all node's children //! previousPath The property path to the current nodeList. void PropertyTreeEditor::PopulateNodeMap(AZStd::list<InstanceDataNode>& nodeList, const AZStd::string_view& previousPath) { for (InstanceDataNode& node : nodeList) { AZStd::string path = previousPath; AZStd::vector<ChangeNotification> changeNotifiers; auto editMetaData = node.GetElementEditMetadata(); if (editMetaData) { if (!path.empty()) { path += '|'; } // If this element is nested under a group, we need to include the group name (which is stored in the description) // in the path as well in order for the path to be unique auto groupMetaData = node.GetGroupElementMetadata(); if (groupMetaData && groupMetaData->m_description) { path += groupMetaData->m_description; path += '|'; } path += editMetaData->m_name; if (auto notifyAttribute = editMetaData->FindAttribute(AZ::Edit::Attributes::ChangeNotify)) { PropertyAttributeReader reader(node.FirstInstance(), notifyAttribute); HandleChangeNotifyAttribute(reader, &node, changeNotifiers); } auto classMetaData = node.GetClassMetadata(); if (classMetaData) { m_nodeMap.emplace(path, PropertyTreeEditorNode(&node, {}, previousPath, changeNotifiers)); // Add support for deprecated names. // Note that the property paths are unique, but deprecated paths can introduce collisions. // In those cases, the non-deprecated paths have precedence and hide the deprecated ones. // Also, in the case of multiple properties with the same deprecated paths, one will hide the other. if (editMetaData->m_deprecatedName && AzFramework::StringFunc::StringLength(editMetaData->m_deprecatedName) > 0) { AZStd::string deprecatedPath = previousPath; if (!deprecatedPath.empty()) { deprecatedPath += '|'; } deprecatedPath += editMetaData->m_deprecatedName; // Only add the name to the map if it's not already there. if (m_nodeMap.find(deprecatedPath) == m_nodeMap.end()) { m_nodeMap.emplace(deprecatedPath, PropertyTreeEditorNode(&node, editMetaData->m_name, previousPath, changeNotifiers)); } } } } PopulateNodeMap(node.GetChildren(), path); } } PropertyModificationRefreshLevel PropertyTreeEditor::PropertyNotify(const PropertyTreeEditorNode* node, size_t optionalIndex) { // Notify from this node all the way up through parents recursively. // Maintain the highest level of requested refresh along the way. PropertyModificationRefreshLevel level = Refresh_None; if (node->m_nodePtr) { for (const ChangeNotification notifier : node->m_notifiers) { // execute the function or read the value. InstanceDataNode* nodeToNotify = notifier.m_node; if (nodeToNotify && nodeToNotify->GetClassMetadata()->m_container) { nodeToNotify = nodeToNotify->GetParent(); } if (nodeToNotify) { for (size_t idx = 0; idx < nodeToNotify->GetNumInstances(); ++idx) { PropertyAttributeReader reader(nodeToNotify->GetInstance(idx), notifier.m_attribute); AZ::u32 refreshLevelCRC = 0; if (!reader.Read<AZ::u32>(refreshLevelCRC)) { AZ::Crc32 refreshLevelCrc32; if (reader.Read<AZ::Crc32>(refreshLevelCrc32)) { refreshLevelCRC = refreshLevelCrc32; } } if (refreshLevelCRC != 0) { if (refreshLevelCRC == AZ::Edit::PropertyRefreshLevels::None) { level = AZStd::GetMax(Refresh_None, level); } else if (refreshLevelCRC == AZ::Edit::PropertyRefreshLevels::ValuesOnly) { level = AZStd::GetMax(Refresh_Values, level); } else if (refreshLevelCRC == AZ::Edit::PropertyRefreshLevels::AttributesAndValues) { level = AZStd::GetMax(Refresh_AttributesAndValues, level); } else if (refreshLevelCRC == AZ::Edit::PropertyRefreshLevels::EntireTree) { level = AZStd::GetMax(Refresh_EntireTree, level); } else { AZ_WarningOnce("Property Editor", false, "Invalid value returned from change notification handler for %s. " "A CRC of one of the following refresh levels should be returned: " "RefreshNone, RefreshValues, RefreshAttributesAndValues, RefreshEntireTree.", nodeToNotify->GetElementEditMetadata() ? nodeToNotify->GetElementEditMetadata()->m_name : nodeToNotify->GetClassMetadata()->m_name); } } else { // Support invoking a void handler (either taking no parameters or an index) // (doesn't return a refresh level) AZ::Edit::AttributeFunction<void()>* func = azdynamic_cast<AZ::Edit::AttributeFunction<void()>*>(reader.GetAttribute()); AZ::Edit::AttributeFunction<void(size_t)>* funcWithIndex = azdynamic_cast<AZ::Edit::AttributeFunction<void(size_t)>*>(reader.GetAttribute()); if (func) { func->Invoke(nodeToNotify->GetInstance(idx)); } else if (funcWithIndex) { // if a function has been provided that takes an index, use this version // passing through the index of the element being modified funcWithIndex->Invoke(nodeToNotify->GetInstance(idx), optionalIndex); } else { AZ_WarningOnce("Property Editor", false, "Unable to invoke change notification handler for %s. " "Handler must return void, or the CRC of one of the following refresh levels: " "RefreshNone, RefreshValues, RefreshAttributesAndValues, RefreshEntireTree.", nodeToNotify->GetElementEditMetadata() ? nodeToNotify->GetElementEditMetadata()->m_name : nodeToNotify->GetClassMetadata()->m_name); } } } } } } if (!node->m_parentPath.empty() && m_nodeMap.find(node->m_parentPath) != m_nodeMap.end()) { return static_cast<PropertyModificationRefreshLevel>( AZStd::GetMax( aznumeric_cast<int>(PropertyNotify(&m_nodeMap[node->m_parentPath], optionalIndex)), aznumeric_cast<int>(level) ) ); } return level; } }
46.841137
249
0.584128
BadDevCode
ba4794632b65b2e7df579f667303447f8871f85b
3,298
cpp
C++
modules/imgcodecs/test/test_png.cpp
zhongshenxuexi/opencv
10ae0c4364ecf1bebf3a80f7a6570142e4da7632
[ "BSD-3-Clause" ]
17
2016-03-16T08:48:30.000Z
2022-02-21T12:09:28.000Z
modules/imgcodecs/test/test_png.cpp
nurisis/opencv
4378b4d03d8415a132b6675883957243f95d75ee
[ "BSD-3-Clause" ]
5
2017-10-15T15:44:47.000Z
2022-02-17T11:31:32.000Z
modules/imgcodecs/test/test_png.cpp
nurisis/opencv
4378b4d03d8415a132b6675883957243f95d75ee
[ "BSD-3-Clause" ]
25
2018-09-26T08:51:13.000Z
2022-02-24T13:43:58.000Z
// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html #include "test_precomp.hpp" namespace opencv_test { namespace { #ifdef HAVE_PNG TEST(Imgcodecs_Png, write_big) { const string root = cvtest::TS::ptr()->get_data_path(); const string filename = root + "readwrite/read.png"; const string dst_file = cv::tempfile(".png"); Mat img; ASSERT_NO_THROW(img = imread(filename)); ASSERT_FALSE(img.empty()); EXPECT_EQ(13043, img.cols); EXPECT_EQ(13917, img.rows); ASSERT_NO_THROW(imwrite(dst_file, img)); EXPECT_EQ(0, remove(dst_file.c_str())); } TEST(Imgcodecs_Png, encode) { vector<uchar> buff; Mat img_gt = Mat::zeros(1000, 1000, CV_8U); vector<int> param; param.push_back(IMWRITE_PNG_COMPRESSION); param.push_back(3); //default(3) 0-9. EXPECT_NO_THROW(imencode(".png", img_gt, buff, param)); Mat img; EXPECT_NO_THROW(img = imdecode(buff, IMREAD_ANYDEPTH)); // hang EXPECT_FALSE(img.empty()); EXPECT_PRED_FORMAT2(cvtest::MatComparator(0, 0), img, img_gt); } TEST(Imgcodecs_Png, regression_ImreadVSCvtColor) { const string root = cvtest::TS::ptr()->get_data_path(); const string imgName = root + "../cv/shared/lena.png"; Mat original_image = imread(imgName); Mat gray_by_codec = imread(imgName, IMREAD_GRAYSCALE); Mat gray_by_cvt; cvtColor(original_image, gray_by_cvt, CV_BGR2GRAY); Mat diff; absdiff(gray_by_codec, gray_by_cvt, diff); EXPECT_LT(cvtest::mean(diff)[0], 1.); EXPECT_PRED_FORMAT2(cvtest::MatComparator(10, 0), gray_by_codec, gray_by_cvt); } // Test OpenCV issue 3075 is solved TEST(Imgcodecs_Png, read_color_palette_with_alpha) { const string root = cvtest::TS::ptr()->get_data_path(); Mat img; // First Test : Read PNG with alpha, imread flag -1 img = imread(root + "readwrite/color_palette_alpha.png", IMREAD_UNCHANGED); ASSERT_FALSE(img.empty()); ASSERT_TRUE(img.channels() == 4); // pixel is red in BGRA EXPECT_EQ(img.at<Vec4b>(0, 0), Vec4b(0, 0, 255, 255)); EXPECT_EQ(img.at<Vec4b>(0, 1), Vec4b(0, 0, 255, 255)); // Second Test : Read PNG without alpha, imread flag -1 img = imread(root + "readwrite/color_palette_no_alpha.png", IMREAD_UNCHANGED); ASSERT_FALSE(img.empty()); ASSERT_TRUE(img.channels() == 3); // pixel is red in BGR EXPECT_EQ(img.at<Vec3b>(0, 0), Vec3b(0, 0, 255)); EXPECT_EQ(img.at<Vec3b>(0, 1), Vec3b(0, 0, 255)); // Third Test : Read PNG with alpha, imread flag 1 img = imread(root + "readwrite/color_palette_alpha.png", IMREAD_COLOR); ASSERT_FALSE(img.empty()); ASSERT_TRUE(img.channels() == 3); // pixel is red in BGR EXPECT_EQ(img.at<Vec3b>(0, 0), Vec3b(0, 0, 255)); EXPECT_EQ(img.at<Vec3b>(0, 1), Vec3b(0, 0, 255)); // Fourth Test : Read PNG without alpha, imread flag 1 img = imread(root + "readwrite/color_palette_no_alpha.png", IMREAD_COLOR); ASSERT_FALSE(img.empty()); ASSERT_TRUE(img.channels() == 3); // pixel is red in BGR EXPECT_EQ(img.at<Vec3b>(0, 0), Vec3b(0, 0, 255)); EXPECT_EQ(img.at<Vec3b>(0, 1), Vec3b(0, 0, 255)); } #endif // HAVE_PNG }} // namespace
33.313131
90
0.673135
zhongshenxuexi
ba482f1d4483d0606ac1e935759d77f2f5361e6b
735
cpp
C++
lovely/controller/src/controller/executor/executor.tests.cpp
tirpidz/lovely
772a248137be1ce6b2af1147a590554f160af5be
[ "Apache-2.0" ]
1
2021-01-15T16:55:03.000Z
2021-01-15T16:55:03.000Z
lovely/controller/src/controller/executor/executor.tests.cpp
tirpidz/lovely
772a248137be1ce6b2af1147a590554f160af5be
[ "Apache-2.0" ]
24
2021-01-11T01:06:10.000Z
2021-01-18T16:28:59.000Z
lovely/controller/src/controller/executor/executor.tests.cpp
tirpidz/lovely
772a248137be1ce6b2af1147a590554f160af5be
[ "Apache-2.0" ]
null
null
null
#include <lovely/controller/executor/executor.h> #include <lovely/controller/updater/updater.h> #include <lovely/model/model.h> #include <lovely/model/tests/model/custom_model.h> #include <catch2/catch.hpp> using namespace lovely; TEST_CASE("executor initialize", "[controller]") { const int int_ref = 42; custom_model model; model.initialize(); executor<custom_model> exectuor(model); } TEST_CASE("executor throw when model not initialized", "[controller]") { custom_model model_not_initialized; bool has_been_thrown = false; try { executor<custom_model> executor(model_not_initialized); } catch (...) { has_been_thrown = true; } REQUIRE(has_been_thrown == true); }
21.617647
70
0.703401
tirpidz
ba4989f48b7b47321e178f7c4a271928ee9b8d22
18,641
cpp
C++
USAP_H37Rv/Tools/bedtools2-2.25/src/utils/BamTools/src/api/internal/bam/BamWriter_p.cpp
SANBI-SA-archive/s_bvc_pipeline
43948b4ea5db6333633361dd91f7e7b320392fb2
[ "Apache-2.0" ]
29
2016-09-27T15:33:27.000Z
2021-07-14T03:26:53.000Z
USAP_H37Rv/Tools/bedtools2-2.25/src/utils/BamTools/src/api/internal/bam/BamWriter_p.cpp
SANBI-SA-archive/s_bvc_pipeline
43948b4ea5db6333633361dd91f7e7b320392fb2
[ "Apache-2.0" ]
15
2015-11-22T13:12:03.000Z
2022-01-19T02:18:25.000Z
USAP_H37Rv/Tools/bedtools2-2.25/src/utils/BamTools/src/api/internal/bam/BamWriter_p.cpp
SANBI-SA-archive/s_bvc_pipeline
43948b4ea5db6333633361dd91f7e7b320392fb2
[ "Apache-2.0" ]
9
2015-03-30T14:37:26.000Z
2019-06-20T19:06:07.000Z
// *************************************************************************** // BamWriter_p.cpp (c) 2010 Derek Barnett // Marth Lab, Department of Biology, Boston College // --------------------------------------------------------------------------- // Last modified: 25 October 2011 (DB) // --------------------------------------------------------------------------- // Provides the basic functionality for producing BAM files // *************************************************************************** #include "api/BamAlignment.h" #include "api/BamConstants.h" #include "api/IBamIODevice.h" #include "api/internal/bam/BamWriter_p.h" #include "api/internal/utils/BamException_p.h" using namespace BamTools; using namespace BamTools::Internal; #include <cstdlib> #include <cstring> using namespace std; // ctor BamWriterPrivate::BamWriterPrivate(void) : m_isBigEndian( BamTools::SystemIsBigEndian() ) { } // dtor BamWriterPrivate::~BamWriterPrivate(void) { Close(); } // calculates minimum bin for a BAM alignment interval [begin, end) uint32_t BamWriterPrivate::CalculateMinimumBin(const int begin, int end) const { --end; if ( (begin >> 14) == (end >> 14) ) return 4681 + (begin >> 14); if ( (begin >> 17) == (end >> 17) ) return 585 + (begin >> 17); if ( (begin >> 20) == (end >> 20) ) return 73 + (begin >> 20); if ( (begin >> 23) == (end >> 23) ) return 9 + (begin >> 23); if ( (begin >> 26) == (end >> 26) ) return 1 + (begin >> 26); return 0; } // closes the alignment archive void BamWriterPrivate::Close(void) { // skip if file not open if ( !IsOpen() ) return; // close output stream try { m_stream.Close(); } catch ( BamException& e ) { m_errorString = e.what(); } } // creates a cigar string from the supplied alignment void BamWriterPrivate::CreatePackedCigar(const vector<CigarOp>& cigarOperations, string& packedCigar) { // initialize const size_t numCigarOperations = cigarOperations.size(); packedCigar.resize(numCigarOperations * Constants::BAM_SIZEOF_INT); // pack the cigar data into the string unsigned int* pPackedCigar = (unsigned int*)packedCigar.data(); // iterate over cigar operations vector<CigarOp>::const_iterator coIter = cigarOperations.begin(); vector<CigarOp>::const_iterator coEnd = cigarOperations.end(); for ( ; coIter != coEnd; ++coIter ) { // store op in packedCigar uint8_t cigarOp; switch ( coIter->Type ) { case (Constants::BAM_CIGAR_MATCH_CHAR) : cigarOp = Constants::BAM_CIGAR_MATCH; break; case (Constants::BAM_CIGAR_INS_CHAR) : cigarOp = Constants::BAM_CIGAR_INS; break; case (Constants::BAM_CIGAR_DEL_CHAR) : cigarOp = Constants::BAM_CIGAR_DEL; break; case (Constants::BAM_CIGAR_REFSKIP_CHAR) : cigarOp = Constants::BAM_CIGAR_REFSKIP; break; case (Constants::BAM_CIGAR_SOFTCLIP_CHAR) : cigarOp = Constants::BAM_CIGAR_SOFTCLIP; break; case (Constants::BAM_CIGAR_HARDCLIP_CHAR) : cigarOp = Constants::BAM_CIGAR_HARDCLIP; break; case (Constants::BAM_CIGAR_PAD_CHAR) : cigarOp = Constants::BAM_CIGAR_PAD; break; case (Constants::BAM_CIGAR_SEQMATCH_CHAR) : cigarOp = Constants::BAM_CIGAR_SEQMATCH; break; case (Constants::BAM_CIGAR_MISMATCH_CHAR) : cigarOp = Constants::BAM_CIGAR_MISMATCH; break; default: const string message = string("invalid CIGAR operation type") + coIter->Type; throw BamException("BamWriter::CreatePackedCigar", message); } *pPackedCigar = coIter->Length << Constants::BAM_CIGAR_SHIFT | cigarOp; pPackedCigar++; } } // encodes the supplied query sequence into 4-bit notation void BamWriterPrivate::EncodeQuerySequence(const string& query, string& encodedQuery) { // prepare the encoded query string const size_t queryLength = query.size(); const size_t encodedQueryLength = static_cast<size_t>((queryLength+1)/2); encodedQuery.resize(encodedQueryLength); char* pEncodedQuery = (char*)encodedQuery.data(); const char* pQuery = (const char*)query.data(); // walk through original query sequence, encoding its bases unsigned char nucleotideCode; bool useHighWord = true; while ( *pQuery ) { switch ( *pQuery ) { case (Constants::BAM_DNA_EQUAL) : nucleotideCode = Constants::BAM_BASECODE_EQUAL; break; case (Constants::BAM_DNA_A) : nucleotideCode = Constants::BAM_BASECODE_A; break; case (Constants::BAM_DNA_C) : nucleotideCode = Constants::BAM_BASECODE_C; break; case (Constants::BAM_DNA_M) : nucleotideCode = Constants::BAM_BASECODE_M; break; case (Constants::BAM_DNA_G) : nucleotideCode = Constants::BAM_BASECODE_G; break; case (Constants::BAM_DNA_R) : nucleotideCode = Constants::BAM_BASECODE_R; break; case (Constants::BAM_DNA_S) : nucleotideCode = Constants::BAM_BASECODE_S; break; case (Constants::BAM_DNA_V) : nucleotideCode = Constants::BAM_BASECODE_V; break; case (Constants::BAM_DNA_T) : nucleotideCode = Constants::BAM_BASECODE_T; break; case (Constants::BAM_DNA_W) : nucleotideCode = Constants::BAM_BASECODE_W; break; case (Constants::BAM_DNA_Y) : nucleotideCode = Constants::BAM_BASECODE_Y; break; case (Constants::BAM_DNA_H) : nucleotideCode = Constants::BAM_BASECODE_H; break; case (Constants::BAM_DNA_K) : nucleotideCode = Constants::BAM_BASECODE_K; break; case (Constants::BAM_DNA_D) : nucleotideCode = Constants::BAM_BASECODE_D; break; case (Constants::BAM_DNA_B) : nucleotideCode = Constants::BAM_BASECODE_B; break; case (Constants::BAM_DNA_N) : nucleotideCode = Constants::BAM_BASECODE_N; break; default: const string message = string("invalid base: ") + *pQuery; throw BamException("BamWriter::EncodeQuerySequence", message); } // pack the nucleotide code if ( useHighWord ) { *pEncodedQuery = nucleotideCode << 4; useHighWord = false; } else { *pEncodedQuery |= nucleotideCode; ++pEncodedQuery; useHighWord = true; } // increment the query position ++pQuery; } } // returns a description of the last error that occurred std::string BamWriterPrivate::GetErrorString(void) const { return m_errorString; } // returns whether BAM file is open for writing or not bool BamWriterPrivate::IsOpen(void) const { return m_stream.IsOpen(); } // opens the alignment archive bool BamWriterPrivate::Open(const string& filename, const string& samHeaderText, const RefVector& referenceSequences) { try { // open the BGZF file for writing m_stream.Open(filename, IBamIODevice::WriteOnly); // write BAM file 'metadata' components WriteMagicNumber(); WriteSamHeaderText(samHeaderText); WriteReferences(referenceSequences); // return success return true; } catch ( BamException& e ) { m_errorString = e.what(); return false; } } // saves the alignment to the alignment archive bool BamWriterPrivate::SaveAlignment(const BamAlignment& al) { try { // if BamAlignment contains only the core data and a raw char data buffer // (as a result of BamReader::GetNextAlignmentCore()) if ( al.SupportData.HasCoreOnly ) WriteCoreAlignment(al); // otherwise, BamAlignment should contain character in the standard fields: Name, QueryBases, etc // (resulting from BamReader::GetNextAlignment() *OR* being generated directly by client code) else WriteAlignment(al); // if we get here, everything OK return true; } catch ( BamException& e ) { m_errorString = e.what(); return false; } } void BamWriterPrivate::SetWriteCompressed(bool ok) { // modifying compression is not allowed if BAM file is open if ( !IsOpen() ) m_stream.SetWriteCompressed(ok); } void BamWriterPrivate::WriteAlignment(const BamAlignment& al) { // calculate char lengths const unsigned int nameLength = al.Name.size() + 1; const unsigned int numCigarOperations = al.CigarData.size(); const unsigned int queryLength = al.QueryBases.size(); const unsigned int tagDataLength = al.TagData.size(); // no way to tell if alignment's bin is already defined (there is no default, invalid value) // so we'll go ahead calculate its bin ID before storing const uint32_t alignmentBin = CalculateMinimumBin(al.Position, al.GetEndPosition()); // create our packed cigar string string packedCigar; CreatePackedCigar(al.CigarData, packedCigar); const unsigned int packedCigarLength = packedCigar.size(); // encode the query string encodedQuery; EncodeQuerySequence(al.QueryBases, encodedQuery); const unsigned int encodedQueryLength = encodedQuery.size(); // write the block size const unsigned int dataBlockSize = nameLength + packedCigarLength + encodedQueryLength + queryLength + tagDataLength; unsigned int blockSize = Constants::BAM_CORE_SIZE + dataBlockSize; if ( m_isBigEndian ) BamTools::SwapEndian_32(blockSize); m_stream.Write((char*)&blockSize, Constants::BAM_SIZEOF_INT); // assign the BAM core data uint32_t buffer[Constants::BAM_CORE_BUFFER_SIZE]; buffer[0] = al.RefID; buffer[1] = al.Position; buffer[2] = (alignmentBin << 16) | (al.MapQuality << 8) | nameLength; buffer[3] = (al.AlignmentFlag << 16) | numCigarOperations; buffer[4] = queryLength; buffer[5] = al.MateRefID; buffer[6] = al.MatePosition; buffer[7] = al.InsertSize; // swap BAM core endian-ness, if necessary if ( m_isBigEndian ) { for ( int i = 0; i < 8; ++i ) BamTools::SwapEndian_32(buffer[i]); } // write the BAM core m_stream.Write((char*)&buffer, Constants::BAM_CORE_SIZE); // write the query name m_stream.Write(al.Name.c_str(), nameLength); // write the packed cigar if ( m_isBigEndian ) { char* cigarData = new char[packedCigarLength](); memcpy(cigarData, packedCigar.data(), packedCigarLength); if ( m_isBigEndian ) { for ( size_t i = 0; i < packedCigarLength; ++i ) BamTools::SwapEndian_32p(&cigarData[i]); } m_stream.Write(cigarData, packedCigarLength); delete[] cigarData; // TODO: cleanup on Write exception thrown? } else m_stream.Write(packedCigar.data(), packedCigarLength); // write the encoded query sequence m_stream.Write(encodedQuery.data(), encodedQueryLength); // write the base qualities char* pBaseQualities = (char*)al.Qualities.data(); for ( size_t i = 0; i < queryLength; ++i ) pBaseQualities[i] -= 33; // FASTQ conversion m_stream.Write(pBaseQualities, queryLength); // write the read group tag if ( m_isBigEndian ) { char* tagData = new char[tagDataLength](); memcpy(tagData, al.TagData.data(), tagDataLength); size_t i = 0; while ( i < tagDataLength ) { i += Constants::BAM_TAG_TAGSIZE; // skip tag chars (e.g. "RG", "NM", etc.) const char type = tagData[i]; // get tag type at position i ++i; switch ( type ) { case(Constants::BAM_TAG_TYPE_ASCII) : case(Constants::BAM_TAG_TYPE_INT8) : case(Constants::BAM_TAG_TYPE_UINT8) : ++i; break; case(Constants::BAM_TAG_TYPE_INT16) : case(Constants::BAM_TAG_TYPE_UINT16) : BamTools::SwapEndian_16p(&tagData[i]); i += sizeof(uint16_t); break; case(Constants::BAM_TAG_TYPE_FLOAT) : case(Constants::BAM_TAG_TYPE_INT32) : case(Constants::BAM_TAG_TYPE_UINT32) : BamTools::SwapEndian_32p(&tagData[i]); i += sizeof(uint32_t); break; case(Constants::BAM_TAG_TYPE_HEX) : case(Constants::BAM_TAG_TYPE_STRING) : // no endian swapping necessary for hex-string/string data while ( tagData[i] ) ++i; // increment one more for null terminator ++i; break; case(Constants::BAM_TAG_TYPE_ARRAY) : { // read array type const char arrayType = tagData[i]; ++i; // swap endian-ness of number of elements in place, then retrieve for loop BamTools::SwapEndian_32p(&tagData[i]); int32_t numElements; memcpy(&numElements, &tagData[i], sizeof(uint32_t)); i += sizeof(uint32_t); // swap endian-ness of array elements for ( int j = 0; j < numElements; ++j ) { switch (arrayType) { case (Constants::BAM_TAG_TYPE_INT8) : case (Constants::BAM_TAG_TYPE_UINT8) : // no endian-swapping necessary ++i; break; case (Constants::BAM_TAG_TYPE_INT16) : case (Constants::BAM_TAG_TYPE_UINT16) : BamTools::SwapEndian_16p(&tagData[i]); i += sizeof(uint16_t); break; case (Constants::BAM_TAG_TYPE_FLOAT) : case (Constants::BAM_TAG_TYPE_INT32) : case (Constants::BAM_TAG_TYPE_UINT32) : BamTools::SwapEndian_32p(&tagData[i]); i += sizeof(uint32_t); break; default: delete[] tagData; const string message = string("invalid binary array type: ") + arrayType; throw BamException("BamWriter::SaveAlignment", message); } } break; } default : delete[] tagData; const string message = string("invalid tag type: ") + type; throw BamException("BamWriter::SaveAlignment", message); } } m_stream.Write(tagData, tagDataLength); delete[] tagData; // TODO: cleanup on Write exception thrown? } else m_stream.Write(al.TagData.data(), tagDataLength); } void BamWriterPrivate::WriteCoreAlignment(const BamAlignment& al) { // write the block size unsigned int blockSize = al.SupportData.BlockLength; if ( m_isBigEndian ) BamTools::SwapEndian_32(blockSize); m_stream.Write((char*)&blockSize, Constants::BAM_SIZEOF_INT); // re-calculate bin (in case BamAlignment's position has been previously modified) const uint32_t alignmentBin = CalculateMinimumBin(al.Position, al.GetEndPosition()); // assign the BAM core data uint32_t buffer[Constants::BAM_CORE_BUFFER_SIZE]; buffer[0] = al.RefID; buffer[1] = al.Position; buffer[2] = (alignmentBin << 16) | (al.MapQuality << 8) | al.SupportData.QueryNameLength; buffer[3] = (al.AlignmentFlag << 16) | al.SupportData.NumCigarOperations; buffer[4] = al.SupportData.QuerySequenceLength; buffer[5] = al.MateRefID; buffer[6] = al.MatePosition; buffer[7] = al.InsertSize; // swap BAM core endian-ness, if necessary if ( m_isBigEndian ) { for ( int i = 0; i < 8; ++i ) BamTools::SwapEndian_32(buffer[i]); } // write the BAM core m_stream.Write((char*)&buffer, Constants::BAM_CORE_SIZE); // write the raw char data m_stream.Write((char*)al.SupportData.AllCharData.data(), al.SupportData.BlockLength-Constants::BAM_CORE_SIZE); } void BamWriterPrivate::WriteMagicNumber(void) { // write BAM file 'magic number' m_stream.Write(Constants::BAM_HEADER_MAGIC, Constants::BAM_HEADER_MAGIC_LENGTH); } void BamWriterPrivate::WriteReferences(const BamTools::RefVector& referenceSequences) { // write the number of reference sequences uint32_t numReferenceSequences = referenceSequences.size(); if ( m_isBigEndian ) BamTools::SwapEndian_32(numReferenceSequences); m_stream.Write((char*)&numReferenceSequences, Constants::BAM_SIZEOF_INT); // foreach reference sequence RefVector::const_iterator rsIter = referenceSequences.begin(); RefVector::const_iterator rsEnd = referenceSequences.end(); for ( ; rsIter != rsEnd; ++rsIter ) { // write the reference sequence name length uint32_t referenceSequenceNameLen = rsIter->RefName.size() + 1; if ( m_isBigEndian ) BamTools::SwapEndian_32(referenceSequenceNameLen); m_stream.Write((char*)&referenceSequenceNameLen, Constants::BAM_SIZEOF_INT); // write the reference sequence name m_stream.Write(rsIter->RefName.c_str(), referenceSequenceNameLen); // write the reference sequence length int32_t referenceLength = rsIter->RefLength; if ( m_isBigEndian ) BamTools::SwapEndian_32(referenceLength); m_stream.Write((char*)&referenceLength, Constants::BAM_SIZEOF_INT); } } void BamWriterPrivate::WriteSamHeaderText(const std::string& samHeaderText) { // write the SAM header text length uint32_t samHeaderLen = samHeaderText.size(); if ( m_isBigEndian ) BamTools::SwapEndian_32(samHeaderLen); m_stream.Write((char*)&samHeaderLen, Constants::BAM_SIZEOF_INT); // write the SAM header text if ( samHeaderLen > 0 ) m_stream.Write(samHeaderText.data(), samHeaderLen); }
40.261339
105
0.599968
SANBI-SA-archive
ba4adf2027797bf0e4d61f2fd2718a7bf1ebe4ed
2,131
hpp
C++
include/pstore/broker/quit.hpp
paulhuggett/pstore2
a0c663d10a2e2713fdf39ecdae1f9c1e96041f5c
[ "Apache-2.0" ]
11
2018-02-02T21:24:49.000Z
2020-12-11T04:06:03.000Z
include/pstore/broker/quit.hpp
SNSystems/pstore
74e9dd960245d6bfc125af03ed964d8ad660a62d
[ "Apache-2.0" ]
63
2018-02-05T17:24:59.000Z
2022-03-22T17:26:28.000Z
include/pstore/broker/quit.hpp
paulhuggett/pstore
067be94d87c87fce524c8d76c6f47c347d8f1853
[ "Apache-2.0" ]
5
2020-01-13T22:47:11.000Z
2021-05-14T09:31:15.000Z
//===- include/pstore/broker/quit.hpp ---------------------*- mode: C++ -*-===// //* _ _ * //* __ _ _ _(_) |_ * //* / _` | | | | | __| * //* | (_| | |_| | | |_ * //* \__, |\__,_|_|\__| * //* |_| * //===----------------------------------------------------------------------===// // // Part of the pstore project, under the Apache License v2.0 with LLVM Exceptions. // See https://github.com/SNSystems/pstore/blob/master/LICENSE.txt for license // information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// /// \file broker/quit.hpp /// \brief The broker's shutdown thread. #ifndef PSTORE_BROKER_QUIT_HPP #define PSTORE_BROKER_QUIT_HPP #include <atomic> #include <cstdlib> #include <memory> #include <thread> #include "pstore/support/gsl.hpp" #include "pstore/support/maybe.hpp" namespace pstore { namespace http { class server_status; } // end namespace http namespace broker { class command_processor; class scavenger; /// The pretend signal number that's raised when a remote shutdown request is received. constexpr int sig_self_quit = -1; void shutdown (command_processor * const cp, scavenger * const scav, int const signum, unsigned const num_read_threads, gsl::not_null<maybe<http::server_status> *> const http_status, gsl::not_null<std::atomic<bool> *> const uptime_done); /// Wakes up the quit thread to start the process of shutting down the server. void notify_quit_thread (); std::thread create_quit_thread (std::weak_ptr<command_processor> cp, std::weak_ptr<scavenger> scav, unsigned num_read_threads, gsl::not_null<maybe<http::server_status> *> http_status, gsl::not_null<std::atomic<bool> *> uptime_done); } // end namespace broker } // end namespace pstore #endif // PSTORE_BROKER_QUIT_HPP
34.934426
97
0.549038
paulhuggett
ba4afbc9efadf6ecb9f5157515176601d8020ee4
617
cpp
C++
Sequence.cpp
izziiyt/ChIPLabel
0df60d65e868cdc90d7febda235424fe654335fd
[ "MIT" ]
null
null
null
Sequence.cpp
izziiyt/ChIPLabel
0df60d65e868cdc90d7febda235424fe654335fd
[ "MIT" ]
null
null
null
Sequence.cpp
izziiyt/ChIPLabel
0df60d65e868cdc90d7febda235424fe654335fd
[ "MIT" ]
null
null
null
#ifndef SEQUENCE_CPP #define SEQUENCE_CPP #include "Sequence.h" namespace hhmm{ // Sequence::Sequence(vector<uint32_t> const& _V,vector<uint32_t> _stateNum,uint32_t _dim) // :len(_V.size()), // testV(_V), // param(_depth,_stateNum,_V.size(),_dim) // {} Sequence::Sequence(vector<VectorXld> const& _V,vector<uint32_t> const& _stateNum,uint32_t _dim) :len(_V.size()), V(_V), param(_stateNum,_V.size(),_dim) {} void Sequence::print(string const& filename) const { ofstream of(filename); for(auto& s:state){ of << s << endl; } } } #endif
15.425
97
0.617504
izziiyt
ba4bde7a3155d819bd8f67e1a44c96e3764a34a8
15,932
cpp
C++
qtdeclarative/src/qml/compiler/qv4compiler.cpp
wgnet/wds_qt
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
[ "Apache-2.0" ]
1
2020-04-30T15:47:35.000Z
2020-04-30T15:47:35.000Z
qtdeclarative/src/qml/compiler/qv4compiler.cpp
wgnet/wds_qt
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
[ "Apache-2.0" ]
null
null
null
qtdeclarative/src/qml/compiler/qv4compiler.cpp
wgnet/wds_qt
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
[ "Apache-2.0" ]
null
null
null
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the QtQml module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <qv4compiler_p.h> #include <qv4compileddata_p.h> #include <qv4isel_p.h> #include <private/qv4string_p.h> #include <private/qv4value_p.h> QV4::Compiler::StringTableGenerator::StringTableGenerator() { clear(); } int QV4::Compiler::StringTableGenerator::registerString(const QString &str) { QHash<QString, int>::ConstIterator it = stringToId.constFind(str); if (it != stringToId.cend()) return *it; stringToId.insert(str, strings.size()); strings.append(str); stringDataSize += QV4::CompiledData::String::calculateSize(str); return strings.size() - 1; } int QV4::Compiler::StringTableGenerator::getStringId(const QString &string) const { Q_ASSERT(stringToId.contains(string)); return stringToId.value(string); } void QV4::Compiler::StringTableGenerator::clear() { strings.clear(); stringToId.clear(); stringDataSize = 0; } void QV4::Compiler::StringTableGenerator::serialize(CompiledData::Unit *unit) { char *dataStart = reinterpret_cast<char *>(unit); uint *stringTable = reinterpret_cast<uint *>(dataStart + unit->offsetToStringTable); char *stringData = dataStart + unit->offsetToStringTable + unit->stringTableSize * sizeof(uint); for (int i = 0; i < strings.size(); ++i) { stringTable[i] = stringData - dataStart; const QString &qstr = strings.at(i); QV4::CompiledData::String *s = (QV4::CompiledData::String*)(stringData); s->flags = 0; // ### s->size = qstr.length(); memcpy(s + 1, qstr.constData(), qstr.length()*sizeof(ushort)); stringData += QV4::CompiledData::String::calculateSize(qstr); } } QV4::Compiler::JSUnitGenerator::JSUnitGenerator(QV4::IR::Module *module) : irModule(module) , jsClassDataSize(0) { // Make sure the empty string always gets index 0 registerString(QString()); } uint QV4::Compiler::JSUnitGenerator::registerIndexedGetterLookup() { CompiledData::Lookup l; l.type_and_flags = CompiledData::Lookup::Type_IndexedGetter; l.nameIndex = 0; lookups << l; return lookups.size() - 1; } uint QV4::Compiler::JSUnitGenerator::registerIndexedSetterLookup() { CompiledData::Lookup l; l.type_and_flags = CompiledData::Lookup::Type_IndexedSetter; l.nameIndex = 0; lookups << l; return lookups.size() - 1; } uint QV4::Compiler::JSUnitGenerator::registerGetterLookup(const QString &name) { CompiledData::Lookup l; l.type_and_flags = CompiledData::Lookup::Type_Getter; l.nameIndex = registerString(name); lookups << l; return lookups.size() - 1; } uint QV4::Compiler::JSUnitGenerator::registerSetterLookup(const QString &name) { CompiledData::Lookup l; l.type_and_flags = CompiledData::Lookup::Type_Setter; l.nameIndex = registerString(name); lookups << l; return lookups.size() - 1; } uint QV4::Compiler::JSUnitGenerator::registerGlobalGetterLookup(const QString &name) { CompiledData::Lookup l; l.type_and_flags = CompiledData::Lookup::Type_GlobalGetter; l.nameIndex = registerString(name); lookups << l; return lookups.size() - 1; } int QV4::Compiler::JSUnitGenerator::registerRegExp(QV4::IR::RegExp *regexp) { CompiledData::RegExp re; re.stringIndex = registerString(*regexp->value); re.flags = 0; if (regexp->flags & QV4::IR::RegExp::RegExp_Global) re.flags |= CompiledData::RegExp::RegExp_Global; if (regexp->flags & QV4::IR::RegExp::RegExp_IgnoreCase) re.flags |= CompiledData::RegExp::RegExp_IgnoreCase; if (regexp->flags & QV4::IR::RegExp::RegExp_Multiline) re.flags |= CompiledData::RegExp::RegExp_Multiline; regexps.append(re); return regexps.size() - 1; } int QV4::Compiler::JSUnitGenerator::registerConstant(QV4::ReturnedValue v) { int idx = constants.indexOf(v); if (idx >= 0) return idx; constants.append(v); return constants.size() - 1; } int QV4::Compiler::JSUnitGenerator::registerJSClass(int count, IR::ExprList *args) { // ### re-use existing class definitions. QList<CompiledData::JSClassMember> members; members.reserve(count); IR::ExprList *it = args; for (int i = 0; i < count; ++i, it = it->next) { CompiledData::JSClassMember member; QV4::IR::Name *name = it->expr->asName(); it = it->next; const bool isData = it->expr->asConst()->value; it = it->next; member.nameOffset = registerString(*name->id); member.isAccessor = !isData; members << member; if (!isData) it = it->next; } jsClasses << members; jsClassDataSize += CompiledData::JSClass::calculateSize(members.count()); return jsClasses.size() - 1; } QV4::CompiledData::Unit *QV4::Compiler::JSUnitGenerator::generateUnit(GeneratorOption option) { registerString(irModule->fileName); foreach (QV4::IR::Function *f, irModule->functions) { registerString(*f->name); for (int i = 0; i < f->formals.size(); ++i) registerString(*f->formals.at(i)); for (int i = 0; i < f->locals.size(); ++i) registerString(*f->locals.at(i)); } int unitSize = QV4::CompiledData::Unit::calculateSize(irModule->functions.size(), regexps.size(), constants.size(), lookups.size(), jsClasses.count()); uint functionDataSize = 0; for (int i = 0; i < irModule->functions.size(); ++i) { QV4::IR::Function *f = irModule->functions.at(i); functionOffsets.insert(f, functionDataSize + unitSize); const int qmlIdDepsCount = f->idObjectDependencies.count(); const int qmlPropertyDepsCount = f->scopeObjectPropertyDependencies.count() + f->contextObjectPropertyDependencies.count(); functionDataSize += QV4::CompiledData::Function::calculateSize(f->formals.size(), f->locals.size(), f->nestedFunctions.size(), qmlIdDepsCount, qmlPropertyDepsCount); } const int totalSize = unitSize + functionDataSize + jsClassDataSize + (option == GenerateWithStringTable ? stringTable.sizeOfTableAndData() : 0); char *data = (char *)malloc(totalSize); memset(data, 0, totalSize); QV4::CompiledData::Unit *unit = (QV4::CompiledData::Unit*)data; memcpy(unit->magic, QV4::CompiledData::magic_str, sizeof(unit->magic)); unit->architecture = 0; // ### unit->flags = QV4::CompiledData::Unit::IsJavascript; unit->version = 1; unit->unitSize = totalSize; unit->functionTableSize = irModule->functions.size(); unit->offsetToFunctionTable = sizeof(*unit); unit->lookupTableSize = lookups.count(); unit->offsetToLookupTable = unit->offsetToFunctionTable + unit->functionTableSize * sizeof(uint); unit->regexpTableSize = regexps.size(); unit->offsetToRegexpTable = unit->offsetToLookupTable + unit->lookupTableSize * CompiledData::Lookup::calculateSize(); unit->constantTableSize = constants.size(); unit->offsetToConstantTable = unit->offsetToRegexpTable + unit->regexpTableSize * CompiledData::RegExp::calculateSize(); unit->jsClassTableSize = jsClasses.count(); unit->offsetToJSClassTable = unit->offsetToConstantTable + unit->constantTableSize * sizeof(ReturnedValue); if (option == GenerateWithStringTable) { unit->stringTableSize = stringTable.stringCount(); unit->offsetToStringTable = unitSize + functionDataSize + jsClassDataSize; } else { unit->stringTableSize = 0; unit->offsetToStringTable = 0; } unit->indexOfRootFunction = -1; unit->sourceFileIndex = getStringId(irModule->fileName); unit->nImports = 0; unit->offsetToImports = 0; unit->nObjects = 0; unit->offsetToObjects = 0; unit->indexOfRootObject = 0; uint *functionTable = (uint *)(data + unit->offsetToFunctionTable); for (int i = 0; i < irModule->functions.size(); ++i) functionTable[i] = functionOffsets.value(irModule->functions.at(i)); char *f = data + unitSize; for (int i = 0; i < irModule->functions.size(); ++i) { QV4::IR::Function *function = irModule->functions.at(i); if (function == irModule->rootFunction) unit->indexOfRootFunction = i; const int bytes = writeFunction(f, i, function); f += bytes; } CompiledData::Lookup *lookupsToWrite = (CompiledData::Lookup*)(data + unit->offsetToLookupTable); foreach (const CompiledData::Lookup &l, lookups) *lookupsToWrite++ = l; CompiledData::RegExp *regexpTable = (CompiledData::RegExp *)(data + unit->offsetToRegexpTable); memcpy(regexpTable, regexps.constData(), regexps.size() * sizeof(*regexpTable)); ReturnedValue *constantTable = (ReturnedValue *)(data + unit->offsetToConstantTable); memcpy(constantTable, constants.constData(), constants.size() * sizeof(ReturnedValue)); // write js classes and js class lookup table uint *jsClassTable = (uint*)(data + unit->offsetToJSClassTable); char *jsClass = data + unitSize + functionDataSize; for (int i = 0; i < jsClasses.count(); ++i) { jsClassTable[i] = jsClass - data; const QList<CompiledData::JSClassMember> members = jsClasses.at(i); CompiledData::JSClass *c = reinterpret_cast<CompiledData::JSClass*>(jsClass); c->nMembers = members.count(); CompiledData::JSClassMember *memberToWrite = reinterpret_cast<CompiledData::JSClassMember*>(jsClass + sizeof(CompiledData::JSClass)); foreach (const CompiledData::JSClassMember &member, members) *memberToWrite++ = member; jsClass += CompiledData::JSClass::calculateSize(members.count()); } // write strings and string table if (option == GenerateWithStringTable) stringTable.serialize(unit); return unit; } int QV4::Compiler::JSUnitGenerator::writeFunction(char *f, int index, QV4::IR::Function *irFunction) { QV4::CompiledData::Function *function = (QV4::CompiledData::Function *)f; quint32 currentOffset = sizeof(QV4::CompiledData::Function); function->index = index; function->nameIndex = getStringId(*irFunction->name); function->flags = 0; if (irFunction->hasDirectEval) function->flags |= CompiledData::Function::HasDirectEval; if (irFunction->usesArgumentsObject) function->flags |= CompiledData::Function::UsesArgumentsObject; if (irFunction->isStrict) function->flags |= CompiledData::Function::IsStrict; if (irFunction->isNamedExpression) function->flags |= CompiledData::Function::IsNamedExpression; if (irFunction->hasTry || irFunction->hasWith) function->flags |= CompiledData::Function::HasCatchOrWith; function->nFormals = irFunction->formals.size(); function->formalsOffset = currentOffset; currentOffset += function->nFormals * sizeof(quint32); function->nLocals = irFunction->locals.size(); function->localsOffset = currentOffset; currentOffset += function->nLocals * sizeof(quint32); function->nInnerFunctions = irFunction->nestedFunctions.size(); function->innerFunctionsOffset = currentOffset; currentOffset += function->nInnerFunctions * sizeof(quint32); function->nDependingIdObjects = 0; function->nDependingContextProperties = 0; function->nDependingScopeProperties = 0; if (!irFunction->idObjectDependencies.isEmpty()) { function->nDependingIdObjects = irFunction->idObjectDependencies.count(); function->dependingIdObjectsOffset = currentOffset; currentOffset += function->nDependingIdObjects * sizeof(quint32); } if (!irFunction->contextObjectPropertyDependencies.isEmpty()) { function->nDependingContextProperties = irFunction->contextObjectPropertyDependencies.count(); function->dependingContextPropertiesOffset = currentOffset; currentOffset += function->nDependingContextProperties * sizeof(quint32) * 2; } if (!irFunction->scopeObjectPropertyDependencies.isEmpty()) { function->nDependingScopeProperties = irFunction->scopeObjectPropertyDependencies.count(); function->dependingScopePropertiesOffset = currentOffset; currentOffset += function->nDependingScopeProperties * sizeof(quint32) * 2; } function->location.line = irFunction->line; function->location.column = irFunction->column; // write formals quint32 *formals = (quint32 *)(f + function->formalsOffset); for (int i = 0; i < irFunction->formals.size(); ++i) formals[i] = getStringId(*irFunction->formals.at(i)); // write locals quint32 *locals = (quint32 *)(f + function->localsOffset); for (int i = 0; i < irFunction->locals.size(); ++i) locals[i] = getStringId(*irFunction->locals.at(i)); // write inner functions quint32 *innerFunctions = (quint32 *)(f + function->innerFunctionsOffset); for (int i = 0; i < irFunction->nestedFunctions.size(); ++i) innerFunctions[i] = functionOffsets.value(irFunction->nestedFunctions.at(i)); // write QML dependencies quint32 *writtenDeps = (quint32 *)(f + function->dependingIdObjectsOffset); foreach (int id, irFunction->idObjectDependencies) *writtenDeps++ = id; writtenDeps = (quint32 *)(f + function->dependingContextPropertiesOffset); for (QV4::IR::PropertyDependencyMap::ConstIterator property = irFunction->contextObjectPropertyDependencies.constBegin(), end = irFunction->contextObjectPropertyDependencies.constEnd(); property != end; ++property) { *writtenDeps++ = property.key(); // property index *writtenDeps++ = property.value(); // notify index } writtenDeps = (quint32 *)(f + function->dependingScopePropertiesOffset); for (QV4::IR::PropertyDependencyMap::ConstIterator property = irFunction->scopeObjectPropertyDependencies.constBegin(), end = irFunction->scopeObjectPropertyDependencies.constEnd(); property != end; ++property) { *writtenDeps++ = property.key(); // property index *writtenDeps++ = property.value(); // notify index } return CompiledData::Function::calculateSize(function->nFormals, function->nLocals, function->nInnerFunctions, function->nDependingIdObjects, function->nDependingContextProperties + function->nDependingScopeProperties); }
40.030151
189
0.680831
wgnet
ba4c71174f9b01c43456008e2038bbd017030b20
821
cpp
C++
ECS/Project/Project/ECS/Component/Component.cpp
AshwinKumarVijay/ECS-Development
c70bd6a9f681b828ded8e89bc7f4f14649edfb84
[ "MIT" ]
2
2017-01-30T23:37:42.000Z
2017-09-08T09:32:37.000Z
ECS/Project/Project/ECS/Component/Component.cpp
AshwinKumarVijay/SceneECS
2acc115d5e7738ef9bf087c025e5e5a10cac3443
[ "MIT" ]
null
null
null
ECS/Project/Project/ECS/Component/Component.cpp
AshwinKumarVijay/SceneECS
2acc115d5e7738ef9bf087c025e5e5a10cac3443
[ "MIT" ]
null
null
null
#include "Component.h" // Default Component Constructor Component::Component(const ComponentType & newComponentTypeSignature, const ComponentTypeRequirement & newComponentTypeRequirementsSignature) { componentTypeSignature = newComponentTypeSignature; componentTypeRequirementsSignature = newComponentTypeRequirementsSignature; } // Default Component Destructor Component::~Component() { } // Return a Component Type Signature - the type signature of this component. ComponentType Component::getComponentTypeSignature() const { return componentTypeSignature; } // Return a Component Type Requirements Signature - the list of types required to attach a component of current type. ComponentTypeRequirement Component::getComponentTypeRequirementsSignature() const { return componentTypeRequirementsSignature; }
28.310345
141
0.830694
AshwinKumarVijay
ba4d500bef3d7e02b7c80d4f29b78409d5971b39
2,990
cc
C++
openGLContext.cc
dfyzy/simpleGL
55790726559b46be596d16c294940ba629bd838c
[ "MIT" ]
1
2016-10-16T21:19:21.000Z
2016-10-16T21:19:21.000Z
openGLContext.cc
dfyzy/simpleGL
55790726559b46be596d16c294940ba629bd838c
[ "MIT" ]
null
null
null
openGLContext.cc
dfyzy/simpleGL
55790726559b46be596d16c294940ba629bd838c
[ "MIT" ]
null
null
null
#include <windows.h> #include "openGLContext.h" #include "log.h" namespace simpleGL { OpenGLContext::OpenGLContext() { println("GLEW:load"); // Set this to true so GLEW knows to use a modern approach to retrieving function pointers and extensions glewExperimental = GL_TRUE; // Initialize GLEW to setup the OpenGL Function pointers if (glewInit() != GLEW_OK) { println("error:GLEW:failed to init"); return; } #ifdef _WIN32 // Turn on vertical screen sync if on Windows. typedef BOOL (WINAPI *PFNWGLSWAPINTERVALEXTPROC)(int interval); PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = NULL; wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC)wglGetProcAddress("wglSwapIntervalEXT"); if(wglSwapIntervalEXT) wglSwapIntervalEXT(1); #else glfwSwapInterval(1); #endif glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_STENCIL_TEST); glGenVertexArrays(1, &vao); glBindVertexArray(vao); println("Data buffers:load"); glGenBuffers((int)EBufferDataType::Count, vbos); for (int i = 0; i < (int)EBufferDataType::Count; i++) { glBindBuffer(GL_ARRAY_BUFFER, vbos[i]); //alocating data for quadCapacity number of quads. glBufferData(GL_ARRAY_BUFFER, quadCapacity * bufferDataSize[i]*QUAD_VERTS*sizeof(float), nullptr, GL_DYNAMIC_DRAW); //binding buffers to layout locations in vertex shader. glVertexAttribPointer(i, bufferDataSize[i], GL_FLOAT, GL_FALSE, 0, nullptr); glEnableVertexAttribArray(i); } } OpenGLContext::~OpenGLContext() { println("OpenGL:unload"); glDeleteBuffers((int)EBufferDataType::Count, vbos); glDeleteVertexArrays(1, &vao); } GLint OpenGLContext::loadQID() { GLint qid; if (!deletedQIDs.empty()) { qid = deletedQIDs.front(); deletedQIDs.pop(); } else { qid = quadCount++; if (quadCapacity < quadCount) { println(std::string("Data buffers:resize:") + std::to_string(quadCapacity*RESIZE_FACTOR)); for (int i = 0; i < (int)EBufferDataType::Count; i++) { GLuint tempVbo; glGenBuffers(1, &tempVbo); int oldSize = quadCapacity * bufferDataSize[i]*QUAD_VERTS*sizeof(float); glBindBuffer(GL_COPY_WRITE_BUFFER, tempVbo); glBufferData(GL_COPY_WRITE_BUFFER, oldSize, nullptr, GL_DYNAMIC_DRAW); //loading current data into temp buffer, resizing this buffer and loading data back from temp buffer. glBindBuffer(GL_COPY_READ_BUFFER, vbos[i]); glCopyBufferSubData(GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, 0, 0, oldSize); glBufferData(GL_COPY_READ_BUFFER, RESIZE_FACTOR * oldSize, nullptr, GL_DYNAMIC_DRAW); glCopyBufferSubData(GL_COPY_WRITE_BUFFER, GL_COPY_READ_BUFFER, 0, 0, oldSize); glDeleteBuffers(1, &tempVbo); } //TOTRY: check if one copy/attribpointer is faster than copy/copy //GLuint t = vbos; //vbos = tempVbo; //tempVbo = t; quadCapacity *= RESIZE_FACTOR; } } return qid; } void OpenGLContext::unloadQID(GLint qid) { if (qid < quadCount - 1) deletedQIDs.push(qid); else quadCount--; } }
26.460177
117
0.73311
dfyzy
ba512dacf2ac24d4c5be3e048e6269f07459fef8
402
cpp
C++
Source/GUI/Submenus/Online.cpp
HatchesPls/GrandTheftAutoV-Cheat
f06011362a0a8297439b260a670f5091118ef5de
[ "curl", "MIT" ]
31
2021-07-13T21:24:58.000Z
2022-03-31T13:04:38.000Z
Source/GUI/Submenus/Online.cpp
HatchesPls/GrandTheftAutoV-Cheat
f06011362a0a8297439b260a670f5091118ef5de
[ "curl", "MIT" ]
12
2021-07-28T16:53:58.000Z
2022-03-31T22:51:03.000Z
Source/GUI/Submenus/Online.cpp
HowYouDoinMate/GrandTheftAutoV-Cheat
1a345749fc676b7bf2c5cd4df63ed6c9b80ff377
[ "curl", "MIT" ]
12
2020-08-16T15:57:52.000Z
2021-06-23T13:08:53.000Z
#include "../Header/Cheat Functions/FiberMain.h" using namespace Cheat; void GUI::Submenus::Online() { GUI::Title("Online"); GUI::MenuOption("Players", Submenus::PlayerList); GUI::MenuOption("All Players", Submenus::AllPlayers); GUI::MenuOption("Protections", Submenus::Protections); GUI::MenuOption("Recovery", Submenus::RecoverySubmenuWarning); GUI::MenuOption("Session", Submenus::Session); }
33.5
63
0.743781
HatchesPls
ba54939c6302318c34c410d020d4736bb31f63b7
10,392
hpp
C++
test/rocprim/test_block_reduce.kernels.hpp
pavahora/rocPRIM
180bf4ea64dc2262d4053c306e8e478a35c3c6e1
[ "MIT" ]
83
2018-04-17T22:14:24.000Z
2022-02-25T14:05:18.000Z
test/rocprim/test_block_reduce.kernels.hpp
pavahora/rocPRIM
180bf4ea64dc2262d4053c306e8e478a35c3c6e1
[ "MIT" ]
122
2018-05-08T05:34:40.000Z
2022-03-09T22:35:05.000Z
test/rocprim/test_block_reduce.kernels.hpp
pavahora/rocPRIM
180bf4ea64dc2262d4053c306e8e478a35c3c6e1
[ "MIT" ]
41
2018-05-24T19:12:50.000Z
2021-11-04T16:25:48.000Z
// MIT License // // Copyright (c) 2017-2020 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 TEST_BLOCK_REDUCE_KERNELS_HPP_ #define TEST_BLOCK_REDUCE_KERNELS_HPP_ template< unsigned int BlockSize, rocprim::block_reduce_algorithm Algorithm, class T, class BinaryOp > __global__ __launch_bounds__(BlockSize) void reduce_kernel(T* device_output, T* device_output_reductions) { const unsigned int index = (blockIdx.x * BlockSize) + threadIdx.x; T value = device_output[index]; rocprim::block_reduce<T, BlockSize, Algorithm> breduce; breduce.reduce(value, value, BinaryOp()); if(threadIdx.x == 0) { device_output_reductions[blockIdx.x] = value; } } template < class T, unsigned int BlockSize, rocprim::block_reduce_algorithm Algorithm, class BinaryOp > struct static_run_algo { static void run(std::vector<T>& output, std::vector<T>& output_reductions, std::vector<T>& expected_reductions, T* device_output, T* device_output_reductions, size_t grid_size, bool check_equal) { HIP_CHECK( hipMemcpy( device_output, output.data(), output.size() * sizeof(T), hipMemcpyHostToDevice ) ); // Running kernel hipLaunchKernelGGL( HIP_KERNEL_NAME(reduce_kernel<BlockSize, Algorithm, T, BinaryOp>), dim3(grid_size), dim3(BlockSize), 0, 0, device_output, device_output_reductions ); // Reading results back HIP_CHECK( hipMemcpy( output_reductions.data(), device_output_reductions, output_reductions.size() * sizeof(T), hipMemcpyDeviceToHost ) ); // Verifying results if(check_equal) { test_utils::assert_eq(output_reductions, expected_reductions); } else { float threshold_multiplier = std::is_same<T, ::rocprim::bfloat16>::value ? 10.0f : 5.0f; test_utils::assert_near(output_reductions, expected_reductions, threshold_multiplier * test_utils::precision_threshold<T>::percentage); } } }; template< unsigned int BlockSize, rocprim::block_reduce_algorithm Algorithm, class T, class BinaryOp > __global__ __launch_bounds__(BlockSize) void reduce_valid_kernel(T* device_output, T* device_output_reductions, const unsigned int valid_items) { const unsigned int index = (blockIdx.x * BlockSize) + threadIdx.x; T value = device_output[index]; rocprim::block_reduce<T, BlockSize, Algorithm> breduce; breduce.reduce(value, value, valid_items, BinaryOp()); if(threadIdx.x == 0) { device_output_reductions[blockIdx.x] = value; } } template < class T, unsigned int BlockSize, rocprim::block_reduce_algorithm Algorithm, class BinaryOp > struct static_run_valid { static void run(std::vector<T>& output, std::vector<T>& output_reductions, std::vector<T>& expected_reductions, T* device_output, T* device_output_reductions, const unsigned int valid_items, size_t grid_size) { HIP_CHECK( hipMemcpy( device_output, output.data(), output.size() * sizeof(T), hipMemcpyHostToDevice ) ); // Running kernel hipLaunchKernelGGL( HIP_KERNEL_NAME(reduce_valid_kernel<BlockSize, Algorithm, T, BinaryOp>), dim3(grid_size), dim3(BlockSize), 0, 0, device_output, device_output_reductions, valid_items ); // Reading results back HIP_CHECK( hipMemcpy( output_reductions.data(), device_output_reductions, output_reductions.size() * sizeof(T), hipMemcpyDeviceToHost ) ); // Verifying results float threshold_multiplier = std::is_same<T, ::rocprim::bfloat16>::value ? 10.0f : 5.0f; test_utils::assert_near(output_reductions, expected_reductions, threshold_multiplier * test_utils::precision_threshold<T>::percentage); } }; template< unsigned int BlockSize, unsigned int ItemsPerThread, rocprim::block_reduce_algorithm Algorithm, class T, class BinaryOp > __global__ __launch_bounds__(BlockSize) void reduce_array_kernel(T* device_output, T* device_output_reductions) { const unsigned int index = ((blockIdx.x * BlockSize) + threadIdx.x) * ItemsPerThread; // load T in_out[ItemsPerThread]; for(unsigned int j = 0; j < ItemsPerThread; j++) { in_out[j] = device_output[index + j]; } rocprim::block_reduce<T, BlockSize, Algorithm> breduce; T reduction; breduce.reduce(in_out, reduction, BinaryOp()); if(threadIdx.x == 0) { device_output_reductions[blockIdx.x] = reduction; } } // Test for reduce template< class T, unsigned int BlockSize = 256U, unsigned int ItemsPerThread = 1U, rocprim::block_reduce_algorithm Algorithm = rocprim::block_reduce_algorithm::using_warp_reduce > void test_block_reduce_input_arrays() { using binary_op_type = typename test_utils::select_maximum_operator<T>::type;; static constexpr auto algorithm = Algorithm; static constexpr size_t block_size = BlockSize; static constexpr size_t items_per_thread = ItemsPerThread; // Given block size not supported if(block_size > test_utils::get_max_block_size()) { return; } const size_t items_per_block = block_size * items_per_thread; const size_t size = items_per_block * 19; const size_t grid_size = size / items_per_block; for (size_t seed_index = 0; seed_index < random_seeds_count + seed_size; seed_index++) { unsigned int seed_value = seed_index < random_seeds_count ? rand() : seeds[seed_index - random_seeds_count]; SCOPED_TRACE(testing::Message() << "with seed= " << seed_value); // Generate data std::vector<T> output = test_utils::get_random_data<T>(size, 0, 100, seed_value); // Output reduce results std::vector<T> output_reductions(size / block_size, (T)0); // Calculate expected results on host std::vector<T> expected_reductions(output_reductions.size(), (T)0); binary_op_type binary_op; for(size_t i = 0; i < output.size() / items_per_block; i++) { T value = (T)0; for(size_t j = 0; j < items_per_block; j++) { auto idx = i * items_per_block + j; value = apply(binary_op, value, output[idx]); } expected_reductions[i] = value; } // Preparing device T* device_output; HIP_CHECK(test_common_utils::hipMallocHelper(&device_output, output.size() * sizeof(T))); T* device_output_reductions; HIP_CHECK(test_common_utils::hipMallocHelper(&device_output_reductions, output_reductions.size() * sizeof(T))); HIP_CHECK( hipMemcpy( device_output, output.data(), output.size() * sizeof(T), hipMemcpyHostToDevice ) ); HIP_CHECK( hipMemcpy( device_output_reductions, output_reductions.data(), output_reductions.size() * sizeof(T), hipMemcpyHostToDevice ) ); // Running kernel hipLaunchKernelGGL( HIP_KERNEL_NAME(reduce_array_kernel<block_size, items_per_thread, algorithm, T, binary_op_type>), dim3(grid_size), dim3(block_size), 0, 0, device_output, device_output_reductions ); // Reading results back HIP_CHECK( hipMemcpy( output_reductions.data(), device_output_reductions, output_reductions.size() * sizeof(T), hipMemcpyDeviceToHost ) ); // Verifying results float threshold_multiplier = std::is_same<T, ::rocprim::bfloat16>::value ? 10.0f : 5.0f; test_utils::assert_near(output_reductions, expected_reductions, threshold_multiplier * test_utils::precision_threshold<T>::percentage); HIP_CHECK(hipFree(device_output)); HIP_CHECK(hipFree(device_output_reductions)); } } // Static for-loop template < unsigned int First, unsigned int Last, class T, unsigned int BlockSize = 256U, rocprim::block_reduce_algorithm Algorithm = rocprim::block_reduce_algorithm::using_warp_reduce > struct static_for_input_array { static void run() { test_block_reduce_input_arrays<T, BlockSize, items[First], Algorithm>(); static_for_input_array<First + 1, Last, T, BlockSize, Algorithm>::run(); } }; template < unsigned int N, class T, unsigned int BlockSize, rocprim::block_reduce_algorithm Algorithm > struct static_for_input_array<N, N, T, BlockSize, Algorithm> { static void run() { } }; #endif // TEST_BLOCK_REDUCE_KERNELS_HPP_
32.273292
147
0.640878
pavahora
ba55c719bf78a2d034bd927bfcfc478b60c2e157
53
cpp
C++
libs/ph/libs/math/src/math.cpp
phiwen96/MyLibs
33b8b4db196040e91eb1c3596634ba73c72a494b
[ "MIT" ]
null
null
null
libs/ph/libs/math/src/math.cpp
phiwen96/MyLibs
33b8b4db196040e91eb1c3596634ba73c72a494b
[ "MIT" ]
null
null
null
libs/ph/libs/math/src/math.cpp
phiwen96/MyLibs
33b8b4db196040e91eb1c3596634ba73c72a494b
[ "MIT" ]
null
null
null
#include <ph/math/math.hpp> namespace ph::math { }
7.571429
27
0.660377
phiwen96
ba563514cc86229b57c639bfb47af7838cf91135
13,603
cc
C++
third_party/tests/Ibex/vendor/lowrisc_ip/dv_verilator/cpp/verilator_memutil.cc
parzival3/Surelog
cf126533ebfb2af7df321057af9e3535feb30487
[ "Apache-2.0" ]
156
2019-11-16T17:29:55.000Z
2022-01-21T05:41:13.000Z
third_party/tests/Ibex/vendor/lowrisc_ip/dv_verilator/cpp/verilator_memutil.cc
parzival3/Surelog
cf126533ebfb2af7df321057af9e3535feb30487
[ "Apache-2.0" ]
414
2021-06-11T07:22:01.000Z
2022-03-31T22:06:14.000Z
third_party/tests/Ibex/vendor/lowrisc_ip/dv_verilator/cpp/verilator_memutil.cc
parzival3/Surelog
cf126533ebfb2af7df321057af9e3535feb30487
[ "Apache-2.0" ]
30
2019-11-18T16:31:40.000Z
2021-12-26T01:22:51.000Z
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 #include "verilator_memutil.h" #include <fcntl.h> #include <gelf.h> #include <getopt.h> #include <libelf.h> #include <sys/stat.h> #include <unistd.h> #include <cassert> #include <cstring> #include <iostream> #include <list> // DPI Exports extern "C" { /** * Write |file| to a memory * * @param file path to a SystemVerilog $readmemh()-compatible file (VMEM file) */ extern void simutil_verilator_memload(const char *file); /** * Write a 32 bit word |val| to memory at index |index| * * @return 1 if successful, 0 otherwise */ extern int simutil_verilator_set_mem(int index, const svBitVecVal *val); } bool VerilatorMemUtil::RegisterMemoryArea(const std::string name, const std::string location) { // Default to 32bit width return RegisterMemoryArea(name, location, 32); } bool VerilatorMemUtil::RegisterMemoryArea(const std::string name, const std::string location, size_t width_bit) { MemArea mem = {.name = name, .location = location, .width_bit = width_bit}; assert((width_bit <= 256) && "TODO: Memory loading only supported up to 256 bits."); auto ret = mem_register_.emplace(name, mem); if (ret.second == false) { std::cerr << "ERROR: Can not register \"" << name << "\" at: \"" << location << "\" (Previously defined at: \"" << ret.first->second.location << "\")" << std::endl; return false; } return true; } bool VerilatorMemUtil::ParseCLIArguments(int argc, char **argv, bool &exit_app) { const struct option long_options[] = { {"rominit", required_argument, nullptr, 'r'}, {"raminit", required_argument, nullptr, 'm'}, {"flashinit", required_argument, nullptr, 'f'}, {"meminit", required_argument, nullptr, 'l'}, {"help", no_argument, nullptr, 'h'}, {nullptr, no_argument, nullptr, 0}}; // Reset the command parsing index in-case other utils have already parsed // some arguments optind = 1; while (1) { int c = getopt_long(argc, argv, ":r:m:f:l:h", long_options, nullptr); if (c == -1) { break; } // Disable error reporting by getopt opterr = 0; switch (c) { case 0: break; case 'r': if (!MemWrite("rom", optarg)) { std::cerr << "ERROR: Unable to initialize memory." << std::endl; return false; } break; case 'm': if (!MemWrite("ram", optarg)) { std::cerr << "ERROR: Unable to initialize memory." << std::endl; return false; } break; case 'f': if (!MemWrite("flash", optarg)) { std::cerr << "ERROR: Unable to initialize memory." << std::endl; return false; } break; case 'l': { if (strcasecmp(optarg, "list") == 0) { PrintMemRegions(); exit_app = true; return true; } std::string name; std::string filepath; MemImageType type; if (!ParseMemArg(optarg, name, filepath, type)) { std::cerr << "ERROR: Unable to parse meminit arguments." << std::endl; return false; } if (!MemWrite(name, filepath, type)) { std::cerr << "ERROR: Unable to initialize memory." << std::endl; return false; } } break; case 'h': PrintHelp(); return true; case ':': // missing argument std::cerr << "ERROR: Missing argument." << std::endl << std::endl; return false; case '?': default:; // Ignore unrecognized options since they might be consumed by // other utils } } return true; } void VerilatorMemUtil::PrintMemRegions() const { std::cout << "Registered memory regions:" << std::endl; for (const auto &m : mem_register_) { std::cout << "\t'" << m.second.name << "' (" << m.second.width_bit << "bits) at location: '" << m.second.location << "'" << std::endl; } } void VerilatorMemUtil::PrintHelp() const { std::cout << "Simulation memory utilities:\n\n" "-r|--rominit=FILE\n" " Initialize the ROM with FILE (elf/vmem)\n\n" "-m|--raminit=FILE\n" " Initialize the RAM with FILE (elf/vmem)\n\n" "-f|--flashinit=FILE\n" " Initialize the FLASH with FILE (elf/vmem)\n\n" "-l|--meminit=NAME,FILE[,TYPE]\n" " Initialize memory region NAME with FILE [of TYPE]\n" " TYPE is either 'elf' or 'vmem'\n\n" "-l list|--meminit=list\n" " Print registered memory regions\n\n" "-h|--help\n" " Show help\n\n"; } bool VerilatorMemUtil::ParseMemArg(std::string mem_argument, std::string &name, std::string &filepath, MemImageType &type) { std::array<std::string, 3> args; size_t pos = 0; size_t end_pos = 0; size_t i; for (i = 0; i < 3; ++i) { end_pos = mem_argument.find(",", pos); // Check for possible exit conditions if (pos == end_pos) { std::cerr << "ERROR: empty field in: " << mem_argument << std::endl; return false; } if (end_pos == std::string::npos) { args[i] = mem_argument.substr(pos); break; } args[i] = mem_argument.substr(pos, end_pos - pos); pos = end_pos + 1; } // mem_argument is not empty as getopt requires an argument, // but not a valid argument for memory initialization if (i == 0) { std::cerr << "ERROR: meminit must be in \"name,file[,type]\"" << " got: " << mem_argument << std::endl; return false; } name = args[0]; filepath = args[1]; if (i == 1) { // Type not set explicitly type = DetectMemImageType(filepath); } else { type = GetMemImageTypeByName(args[2]); } return true; } MemImageType VerilatorMemUtil::DetectMemImageType(const std::string filepath) { size_t ext_pos = filepath.find_last_of("."); std::string ext = filepath.substr(ext_pos + 1); if (ext_pos == std::string::npos) { // Assume ELF files if no file extension is given. // TODO: Make this more robust by actually checking the file contents. return kMemImageElf; } return GetMemImageTypeByName(ext); } MemImageType VerilatorMemUtil::GetMemImageTypeByName(const std::string name) { if (name.compare("elf") == 0) { return kMemImageElf; } if (name.compare("vmem") == 0) { return kMemImageVmem; } return kMemImageUnknown; } bool VerilatorMemUtil::IsFileReadable(std::string filepath) const { struct stat statbuf; return stat(filepath.data(), &statbuf) == 0; } bool VerilatorMemUtil::ElfFileToBinary(const std::string &filepath, uint8_t **data, size_t &len_bytes) const { uint8_t *buf; bool retval, any = false; GElf_Phdr phdr; GElf_Addr high = 0; GElf_Addr low = (GElf_Addr)-1; Elf_Data *elf_data; size_t i; (void)elf_errno(); len_bytes = 0; if (elf_version(EV_CURRENT) == EV_NONE) { std::cerr << elf_errmsg(-1) << std::endl; return false; } int fd = open(filepath.c_str(), O_RDONLY, 0); if (fd < 0) { std::cerr << "Could not open file: " << filepath << std::endl; return false; } Elf *elf_desc; elf_desc = elf_begin(fd, ELF_C_READ, NULL); if (elf_desc == NULL) { std::cerr << elf_errmsg(-1) << " in: " << filepath << std::endl; retval = false; goto return_fd_end; } if (elf_kind(elf_desc) != ELF_K_ELF) { std::cerr << "Not a ELF file: " << filepath << std::endl; retval = false; goto return_elf_end; } // TODO: add support for ELFCLASS64 if (gelf_getclass(elf_desc) != ELFCLASS32) { std::cerr << "Not a 32-bit ELF file: " << filepath << std::endl; retval = false; goto return_elf_end; } size_t phnum; if (elf_getphdrnum(elf_desc, &phnum) != 0) { std::cerr << elf_errmsg(-1) << " in: " << filepath << std::endl; retval = false; goto return_elf_end; } // // To mimic what objcopy does (that is, the binary target of BFD), we need to // iterate over all loadable program headers, find the lowest address, and // then copy in our loadable sections based on their offset with respect to // the found base address. // for (i = 0; i < phnum; i++) { if (gelf_getphdr(elf_desc, i, &phdr) == NULL) { std::cerr << elf_errmsg(-1) << " segment number: " << i << " in: " << filepath << std::endl; retval = false; goto return_elf_end; } if (phdr.p_type != PT_LOAD) { std::cout << "Program header number " << i << " is not of type PT_LOAD; " << "ignoring." << std::endl; continue; } if (phdr.p_filesz == 0) { continue; } if (!any || phdr.p_paddr < low) { low = phdr.p_paddr; } if (!any || phdr.p_paddr + phdr.p_filesz > high) { high = phdr.p_paddr + phdr.p_filesz; } any = true; } len_bytes = high - low; buf = (uint8_t *)malloc(len_bytes); assert(buf != NULL); for (i = 0; i < phnum; i++) { (void)gelf_getphdr(elf_desc, i, &phdr); if (phdr.p_type != PT_LOAD || phdr.p_filesz == 0) { continue; } elf_data = elf_getdata_rawchunk(elf_desc, phdr.p_offset, phdr.p_filesz, ELF_T_BYTE); if (elf_data == NULL) { retval = false; free(buf); goto return_elf_end; } memcpy(&buf[phdr.p_paddr - low], (uint8_t *)elf_data->d_buf, elf_data->d_size); } *data = buf; retval = true; return_elf_end: elf_end(elf_desc); return_fd_end: close(fd); return retval; } bool VerilatorMemUtil::MemWrite(const std::string &name, const std::string &filepath) { MemImageType type = DetectMemImageType(filepath); if (type == kMemImageUnknown) { std::cerr << "ERROR: Unable to detect file type for: " << filepath << std::endl; // Continuing for more error messages } return MemWrite(name, filepath, type); } bool VerilatorMemUtil::MemWrite(const std::string &name, const std::string &filepath, MemImageType type) { // Search for corresponding registered memory based on the name auto it = mem_register_.find(name); if (it == mem_register_.end()) { std::cerr << "ERROR: Memory location not set for: '" << name << "'" << std::endl; PrintMemRegions(); return false; } if (!MemWrite(it->second, filepath, type)) { std::cerr << "ERROR: Setting memory '" << name << "' failed." << std::endl; return false; } return true; } bool VerilatorMemUtil::MemWrite(const MemArea &m, const std::string &filepath, MemImageType type) { if (!IsFileReadable(filepath)) { std::cerr << "ERROR: Memory initialization file " << "'" << filepath << "'" << " is not readable." << std::endl; return false; } svScope scope = svGetScopeFromName(m.location.data()); if (!scope) { std::cerr << "ERROR: No memory found at " << m.location << std::endl; return false; } if ((m.width_bit % 8) != 0) { std::cerr << "ERROR: width for: " << m.name << "must be a multiple of 8 (was : " << m.width_bit << ")" << std::endl; return false; } size_t size_byte = m.width_bit / 8; switch (type) { case kMemImageElf: if (!WriteElfToMem(scope, filepath, size_byte)) { std::cerr << "ERROR: Writing ELF file to memory \"" << m.name << "\" (" << m.location << ") failed." << std::endl; return false; } break; case kMemImageVmem: if (!WriteVmemToMem(scope, filepath)) { std::cerr << "ERROR: Writing VMEM file to memory \"" << m.name << "\" (" << m.location << ") failed." << std::endl; return false; } break; case kMemImageUnknown: default: std::cerr << "ERROR: Unknown file type for " << m.name << std::endl; return false; } return true; } bool VerilatorMemUtil::WriteElfToMem(const svScope &scope, const std::string &filepath, size_t size_byte) { bool retcode; svScope prev_scope = svSetScope(scope); uint8_t *buf = nullptr; size_t len_bytes; if (!ElfFileToBinary(filepath, &buf, len_bytes)) { std::cerr << "ERROR: Could not load: " << filepath << std::endl; retcode = false; goto ret; } for (int i = 0; i < (len_bytes + size_byte - 1) / size_byte; ++i) { if (!simutil_verilator_set_mem(i, (svBitVecVal *)&buf[size_byte * i])) { std::cerr << "ERROR: Could not set memory byte: " << i * size_byte << "/" << len_bytes << "" << std::endl; retcode = false; goto ret; } } retcode = true; ret: svSetScope(prev_scope); free(buf); return retcode; } bool VerilatorMemUtil::WriteVmemToMem(const svScope &scope, const std::string &filepath) { svScope prev_scope = svSetScope(scope); // TODO: Add error handling. simutil_verilator_memload(filepath.data()); svSetScope(prev_scope); return true; }
28.758985
80
0.567669
parzival3
ba579f5af56716698204d215aae4274d6d359109
12,970
cpp
C++
algorithms/kernel/optimization_solver/sgd/sgd_types.cpp
h2oai/daal
d49815df3040f3872a1fdb9dc99ee86148e4494e
[ "Apache-2.0" ]
2
2020-05-16T00:57:44.000Z
2020-05-17T15:56:38.000Z
algorithms/kernel/optimization_solver/sgd/sgd_types.cpp
afcarl/daal
d49815df3040f3872a1fdb9dc99ee86148e4494e
[ "Apache-2.0" ]
null
null
null
algorithms/kernel/optimization_solver/sgd/sgd_types.cpp
afcarl/daal
d49815df3040f3872a1fdb9dc99ee86148e4494e
[ "Apache-2.0" ]
3
2017-09-29T19:51:42.000Z
2020-12-03T09:09:48.000Z
/* file: sgd_types.cpp */ /******************************************************************************* * Copyright 2014-2017 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ /* //++ // Implementation of sgd solver classes. //-- */ #include "algorithms/optimization_solver/iterative_solver/iterative_solver_types.h" #include "algorithms/optimization_solver/sgd/sgd_types.h" #include "data_management/data/memory_block.h" #include "numeric_table.h" #include "serialization_utils.h" #include "daal_strings.h" using namespace daal::data_management; using namespace daal::services; namespace daal { namespace algorithms { namespace optimization_solver { namespace sgd { namespace interface1 { __DAAL_REGISTER_SERIALIZATION_CLASS(Result, SERIALIZATION_SGD_RESULT_ID); /** * Constructs the parameter base class of the Stochastic gradient descent algorithm * \param[in] function Objective function represented as sum of functions * \param[in] nIterations Maximal number of iterations of the algorithm * \param[in] accuracyThreshold Accuracy of the algorithm. The algorithm terminates when this accuracy is achieved * \param[in] batchIndices Numeric table that represents 32 bit integer indices of terms in the objective function. * If no indices are provided, the implementation will generate random indices. * \param[in] learningRateSequence Numeric table that contains values of the learning rate sequence * \param[in] seed Seed for random generation of 32 bit integer indices of terms in the objective function. */ BaseParameter::BaseParameter( const sum_of_functions::BatchPtr &function, size_t nIterations, double accuracyThreshold, NumericTablePtr batchIndices, NumericTablePtr learningRateSequence, size_t batchSize, size_t seed) : optimization_solver::iterative_solver::Parameter(function, nIterations, accuracyThreshold, false, batchSize), batchIndices(batchIndices), learningRateSequence(learningRateSequence), seed(seed) {} /** * Checks the correctness of the parameter */ services::Status BaseParameter::check() const { services::Status s = iterative_solver::Parameter::check(); if(!s) return s; if(learningRateSequence.get() != NULL) { DAAL_CHECK_EX(learningRateSequence->getNumberOfRows() > 0, \ ErrorIncorrectNumberOfObservations, ArgumentName, "learningRateSequence"); DAAL_CHECK_EX(learningRateSequence->getNumberOfColumns() == 1, ErrorIncorrectNumberOfFeatures, ArgumentName, "learningRateSequence"); } return s; } /** * \param[in] function Objective function represented as sum of functions * \param[in] nIterations Maximal number of iterations of the algorithm * \param[in] accuracyThreshold Accuracy of the algorithm. The algorithm terminates when this accuracy is achieved * \param[in] batchIndices Numeric table that represents 32 bit integer indices of terms in the objective function. If no indices are provided, the implementation will generate random indices. * \param[in] learningRateSequence Numeric table that contains values of the learning rate sequence * \param[in] seed Seed for random generation of 32 bit integer indices of terms in the objective function. */ Parameter<defaultDense>::Parameter( const sum_of_functions::BatchPtr &function, size_t nIterations, double accuracyThreshold, NumericTablePtr batchIndices, NumericTablePtr learningRateSequence, size_t seed) : BaseParameter( function, nIterations, accuracyThreshold, batchIndices, learningRateSequence, 1, // batchSize seed ) {} /** * Checks the correctness of the parameter */ services::Status Parameter<defaultDense>::check() const { services::Status s = BaseParameter::check(); if(!s) return s; if(batchIndices.get() != NULL) { return checkNumericTable(batchIndices.get(), batchIndicesStr(), 0, 0, 1, nIterations); } return s; } /** * Constructs the parameter class of the Stochastic gradient descent algorithm * \param[in] function Objective function represented as sum of functions * \param[in] nIterations Maximal number of iterations of the algorithm * \param[in] accuracyThreshold Accuracy of the algorithm. The algorithm terminates when this accuracy is achieved * \param[in] batchIndices Numeric table that represents 32 bit integer indices of terms in the objective function. If no indices are provided, the implementation will generate random indices. * \param[in] batchSize Number of batch indices to compute the stochastic gradient. If batchSize is equal to the number of terms in objective function then no random sampling is performed, and all terms are used to calculate the gradient. This parameter is ignored if batchIndices is provided. * \param[in] conservativeSequence Numeric table of values of the conservative coefficient sequence * \param[in] innerNIterations Number of inner iterations * \param[in] learningRateSequence Numeric table that contains values of the learning rate sequence * \param[in] seed Seed for random generation of 32 bit integer indices of terms in the objective function. */ Parameter<miniBatch>::Parameter( const sum_of_functions::BatchPtr &function, size_t nIterations, double accuracyThreshold, NumericTablePtr batchIndices, size_t batchSize, NumericTablePtr conservativeSequence, size_t innerNIterations, NumericTablePtr learningRateSequence, size_t seed) : BaseParameter( function, nIterations, accuracyThreshold, batchIndices, learningRateSequence, batchSize, seed ), conservativeSequence(conservativeSequence), innerNIterations(innerNIterations) {} /** * Checks the correctness of the parameter */ services::Status Parameter<miniBatch>::check() const { services::Status s = BaseParameter::check(); if(!s) return s; if(batchIndices.get() != NULL) { s |= checkNumericTable(batchIndices.get(), batchIndicesStr(), 0, 0, batchSize, nIterations); if(!s) return s; } if(conservativeSequence.get() != NULL) { DAAL_CHECK_EX(conservativeSequence->getNumberOfRows() == nIterations || conservativeSequence->getNumberOfRows() == 1, \ ErrorIncorrectNumberOfObservations, ArgumentName, conservativeSequenceStr()); s |= checkNumericTable(conservativeSequence.get(), conservativeSequenceStr(), 0, 0, 1); if(!s) return s; } DAAL_CHECK_EX(batchSize <= function->sumOfFunctionsParameter->numberOfTerms && batchSize > 0, ErrorIncorrectParameter, \ ArgumentName, "batchSize"); return s; } Parameter<momentum>::Parameter( const sum_of_functions::BatchPtr &function, double momentum_, size_t nIterations, double accuracyThreshold, NumericTablePtr batchIndices, size_t batchSize, NumericTablePtr learningRateSequence, size_t seed) : BaseParameter(function, nIterations, accuracyThreshold, batchIndices, learningRateSequence, batchSize, seed), momentum(momentum_) {} /** * Checks the correctness of the parameter */ services::Status Parameter<momentum>::check() const { services::Status s = BaseParameter::check(); if(!s) return s; if(batchIndices.get() != NULL) { s |= checkNumericTable(batchIndices.get(), batchIndicesStr(), 0, 0, batchSize, nIterations); if(!s) return s; } DAAL_CHECK_EX(batchSize <= function->sumOfFunctionsParameter->numberOfTerms && batchSize > 0, ErrorIncorrectParameter, \ ArgumentName, "batchSize"); return s; } static services::Status checkRngState(const daal::algorithms::Input *input, const daal::algorithms::Parameter *par, const SerializationIface *pItem, bool bInput) { const sgd::BaseParameter *algParam = static_cast<const sgd::BaseParameter *>(par); //if random numbers generator in the algorithm is not required if(algParam->batchIndices.get()) { return services::Status(); // rgnState doesn't matter } //but if it is present then the SerializationIface should be an instance of expected type if(pItem) { if(!dynamic_cast<const MemoryBlock *>(pItem)) { const ErrorDetailID det = bInput ? OptionalInput : OptionalResult; return services::Status(Error::create(bInput ? ErrorIncorrectOptionalInput : ErrorIncorrectOptionalResult, det, rngStateStr())); } } else if(!bInput) { return services::Status(Error::create(ErrorNullOptionalResult, OptionalResult, rngStateStr())); } return services::Status(); } Input::Input() {} Input::Input(const Input& other) {} services::Status Input::check(const daal::algorithms::Parameter *par, int method) const { services::Status s = super::check(par, method); if(!s) return s; algorithms::OptionalArgumentPtr pOpt = get(iterative_solver::optionalArgument); if(!pOpt.get()) { return services::Status(); //ok } if(pOpt->size() != optionalDataSize) { return services::Status(ErrorIncorrectOptionalInput); } s |= checkRngState(this, par, pOpt->get(rngState).get(), true); if(!s) return s; size_t argumentSize = get(iterative_solver::inputArgument)->getNumberOfRows(); if(method == (int)momentum) { return checkNumericTable(get(pastUpdateVector).get(), pastUpdateVectorStr(), 0, 0, 1, argumentSize); } return s; } NumericTablePtr Input::get(OptionalDataId id) const { algorithms::OptionalArgumentPtr pOpt = get(iterative_solver::optionalArgument); if(pOpt.get()) { return NumericTable::cast(pOpt->get(id)); } return NumericTablePtr(); } void Input::set(OptionalDataId id, const NumericTablePtr &ptr) { algorithms::OptionalArgumentPtr pOpt = get(iterative_solver::optionalArgument); if(!pOpt.get()) { pOpt = algorithms::OptionalArgumentPtr(new algorithms::OptionalArgument(optionalDataSize)); set(iterative_solver::optionalArgument, pOpt); } pOpt->set(id, ptr); } services::Status Result::check(const daal::algorithms::Input *input, const daal::algorithms::Parameter *par, int method) const { services::Status s = super::check(input, par, method); if(!s || !static_cast<const BaseParameter *>(par)->optionalResultRequired) { return s; } algorithms::OptionalArgumentPtr pOpt = get(iterative_solver::optionalResult); if(!pOpt.get()) { return services::Status(ErrorNullOptionalResult); } if(pOpt->size() != optionalDataSize) { return services::Status(ErrorIncorrectOptionalResult); } DAAL_CHECK_STATUS(s, checkRngState(input, par, pOpt->get(rngState).get(), false)); const Input *algInput = static_cast<const Input *>(input); size_t argumentSize = algInput->get(iterative_solver::inputArgument)->getNumberOfRows(); if(method == (int)momentum) { DAAL_CHECK_STATUS(s, checkNumericTable(get(pastUpdateVector).get(), pastUpdateVectorStr(), 0, 0, 1, argumentSize)); } return s; } NumericTablePtr Result::get(OptionalDataId id) const { algorithms::OptionalArgumentPtr pOpt = get(iterative_solver::optionalResult); if(pOpt.get()) { return NumericTable::cast(pOpt->get(id)); } return NumericTablePtr(); } void Result::set(OptionalDataId id, const NumericTablePtr &ptr) { algorithms::OptionalArgumentPtr pOpt = get(iterative_solver::optionalResult); if(!pOpt.get()) { pOpt = algorithms::OptionalArgumentPtr(new algorithms::OptionalArgument(optionalDataSize)); set(iterative_solver::optionalResult, pOpt); } pOpt->set(id, ptr); } } // namespace interface1 } // namespace sgd } // namespace optimization_solver } // namespace algorithm } // namespace daal
36.432584
144
0.682729
h2oai