hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
2c444b193a34ac9953b2feaeb6e275413fdf9439
1,249
cpp
C++
engine/RenderQueue.cpp
shanysheng/orange3d
9ee081a98e14fdeb3aaafd6bbb49fe027d4cd3c0
[ "BSD-2-Clause" ]
11
2017-06-06T17:22:30.000Z
2022-03-23T11:56:49.000Z
engine/RenderQueue.cpp
shanysheng/orange3d
9ee081a98e14fdeb3aaafd6bbb49fe027d4cd3c0
[ "BSD-2-Clause" ]
null
null
null
engine/RenderQueue.cpp
shanysheng/orange3d
9ee081a98e14fdeb3aaafd6bbb49fe027d4cd3c0
[ "BSD-2-Clause" ]
5
2018-02-07T02:48:59.000Z
2021-08-23T05:16:59.000Z
#include "RenderQueue.h" namespace pipeline{ CRenderQueue::CRenderQueue() { m_Tag = 0; //m_bMatrixAggregated = false; m_pExtension = NULL; } CRenderQueue::~CRenderQueue() { Clear(); } int CRenderQueue::GetRenderQueueTag() { return m_Tag; } IRenderQueueExtension* CRenderQueue::GetRenderQueueExtension() { return m_pExtension; } void CRenderQueue::SetRenderQueueTag(int tag) { m_Tag = tag; } void CRenderQueue::SetRenderQueeuExtension(IRenderQueueExtension* pExtension) { m_pExtension = pExtension; } void CRenderQueue::PushBack(SGNode* pEntity) { m_Queue.push_back(pEntity); } void CRenderQueue::PushFront( SGNode* pEntity) { m_Queue.push_front(pEntity); } SGNode* CRenderQueue::operator [](int index) { return m_Queue[index]; } const SGNode* CRenderQueue::operator [](int index) const { return m_Queue[index]; } int CRenderQueue::Size() const { return (int)m_Queue.size(); } void CRenderQueue::Clear() { m_Queue.clear(); } }
18.367647
81
0.563651
shanysheng
2c4871ffe36ad93380fd405539af2813e0bd701a
2,510
cpp
C++
tests/crypto.cpp
MonokelPinguin/mtxclient
765bf87636c66db2da8ce583a782bf64f813f3c4
[ "MIT" ]
2
2021-03-23T11:57:49.000Z
2021-05-18T18:52:27.000Z
tests/crypto.cpp
MonokelPinguin/mtxclient
765bf87636c66db2da8ce583a782bf64f813f3c4
[ "MIT" ]
null
null
null
tests/crypto.cpp
MonokelPinguin/mtxclient
765bf87636c66db2da8ce583a782bf64f813f3c4
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include <nlohmann/json.hpp> #include <mtx/common.hpp> using json = nlohmann::json; using namespace mtx::crypto; TEST(Crypto, DeviceKeys) { DeviceKeys device1; device1.user_id = "@alice:example.com"; device1.device_id = "JLAFKJWSCS"; device1.keys = {{"curve25519:JLAFKJWSCS", "3C5BFWi2Y8MaVvjM8M22DBmh24PmgR0nPvJOIArzgyI"}, {"ed25519:JLAFKJWSCS", "lEuiRJBit0IG6nUf5pUzWTUEsRVVe/HJkoKuEww9ULI"}}; device1.signatures = { {"@alice:example.com", {{"ed25519:JLAFKJWSCS", "dSO80A01XiigH3uBiDVx/EjzaoycHcjq9lfQX0uWsqxl2giMIiSPR8a4d291W1ihKJL/" "a+myXS367WT6NAIcBA"}}}}; json j = device1; ASSERT_EQ(j.dump(), "{\"algorithms\":[\"m.olm.v1.curve25519-aes-sha2\",\"m.megolm.v1.aes-sha2\"]," "\"device_id\":\"JLAFKJWSCS\",\"keys\":{\"curve25519:JLAFKJWSCS\":" "\"3C5BFWi2Y8MaVvjM8M22DBmh24PmgR0nPvJOIArzgyI\",\"ed25519:JLAFKJWSCS\":" "\"lEuiRJBit0IG6nUf5pUzWTUEsRVVe/" "HJkoKuEww9ULI\"},\"signatures\":{\"@alice:example.com\":{\"ed25519:JLAFKJWSCS\":" "\"dSO80A01XiigH3uBiDVx/EjzaoycHcjq9lfQX0uWsqxl2giMIiSPR8a4d291W1ihKJL/" "a+myXS367WT6NAIcBA\"}},\"user_id\":\"@alice:example.com\"}"); json data = R"({ "user_id": "@alice:example.com", "device_id": "JLAFKJWSCS", "algorithms": [ "m.olm.v1.curve25519-aes-sha2", "m.megolm.v1.aes-sha2" ], "keys": { "curve25519:JLAFKJWSCS": "3C5BFWi2Y8MaVvjM8M22DBmh24PmgR0nPvJOIArzgyI", "ed25519:JLAFKJWSCS": "lEuiRJBit0IG6nUf5pUzWTUEsRVVe/HJkoKuEww9ULI" }, "signatures": { "@alice:example.com": { "ed25519:JLAFKJWSCS": "dSO80A01XiigH3uBiDVx/EjzaoycHcjq9lfQX0uWsqxl2giMIiSPR8a4d291W1ihKJL/a+myXS367WT6NAIcBA" } }, "unsigned": { "device_display_name": "Alice's mobile phone" } })"_json; DeviceKeys device2 = data; EXPECT_EQ(device2.user_id, device1.user_id); EXPECT_EQ(device2.device_id, device1.device_id); EXPECT_EQ(device2.keys, device1.keys); EXPECT_EQ(device2.algorithms, device1.algorithms); EXPECT_EQ(device2.signatures, device1.signatures); EXPECT_EQ(device2.unsigned_info.device_display_name, "Alice's mobile phone"); }
38.615385
124
0.600398
MonokelPinguin
2c494ef6071e79eb886ceb19dc8ab22b35fa1847
11,178
tpp
C++
include/signal/systemmodels/systemmodels.tpp
Bormachine-Learning/embedded
165daf847fe9c2a7bcc17c7aee4c5e28b3cf4055
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
include/signal/systemmodels/systemmodels.tpp
Bormachine-Learning/embedded
165daf847fe9c2a7bcc17c7aee4c5e28b3cf4055
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
include/signal/systemmodels/systemmodels.tpp
Bormachine-Learning/embedded
165daf847fe9c2a7bcc17c7aee4c5e28b3cf4055
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/** Copyright 2019 Bosch Engineering Center Cluj and BFMC organizers 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. ****************************************************************************** * @file systemmodels/systemmodels.tpp * @author RBRO/PJ-IU * @version V1.0.0 * @date day-month-2017 * @brief This file contains the class declarations for system model. ****************************************************************************** */ #ifndef SYSTEM_MODELS_TPP #define SYSTEM_MODELS_TPP #ifndef SYSTEM_MODELS_HPP #error __FILE__ should only be included from systemmodels.hpp. #endif // SYSTEM_MODELS_HPP /******************************************************************************/ /** * @brief Construct a new CDiscreteTransferFunction object without input, it initializes the coefficients with zero, only the first coefficient with 1 value. * * @tparam T Type of the variables * @tparam NNum Order of the nominator polynomial * @tparam NDen Order of the denominator polynomial */ template <class T,uint32_t NNum,uint32_t NDen> signal::systemmodels::lti::siso::CDiscreteTransferFunction<T,NNum,NDen>::CDiscreteTransferFunction() :m_num(CNumType::zeros()) ,m_den(CDenModType::zeros()) ,m_denCoef(1) ,m_memInput() ,m_memOutput() { } /** * @brief Construct a new CDiscreteTransferFunction object with input polynomials * * @tparam T Type of the variables * @tparam NNum Order of the nominator polynomial * @tparam NDen Order of the denominator polynomial * @param f_num Nominator polynomial coefficients * @param f_den Denominator polynomial coefficients */ template <class T,uint32_t NNum,uint32_t NDen> signal::systemmodels::lti::siso::CDiscreteTransferFunction<T,NNum,NDen>::CDiscreteTransferFunction(const CNumType& f_num,const CDenType& f_den) :m_num(CNumType::zeros()) ,m_den(CDenModType::zeros()) ,m_denCoef(1) ,m_memInput() ,m_memOutput() { this->setNum(f_num); this->setDen(f_den); } /** \brief Clear memory * * Set all memories to zero. * */ template <class T,uint32_t NNum,uint32_t NDen> void signal::systemmodels::lti::siso::CDiscreteTransferFunction<T,NNum,NDen>::clearMemmory() { m_memInput=CInputMem::zeros(); m_memOutput=COutputMem::zeros(); } /** \brief Applying the transfer function on the input signal value * * @param f_input next input signal value * @return the calculated next output value. */ template <class T,uint32_t NNum,uint32_t NDen> T signal::systemmodels::lti::siso::CDiscreteTransferFunction<T,NNum,NDen>::operator()(const T& f_input) { shiftMemory<NNum>(m_memInput); m_memInput[0][0]=f_input; T l_output=((m_memInput*m_num-m_memOutput*m_den)[0][0])/m_denCoef; shiftMemory<NDen-1>(m_memOutput); m_memOutput[0][0]=l_output; return l_output; } /** \brief Setting nominator coefficients * * @param f_num nominator coefficients * */ template <class T,uint32_t NNum,uint32_t NDen> void signal::systemmodels::lti::siso::CDiscreteTransferFunction<T,NNum,NDen>::setNum(const CNumType& f_num) { for(uint32_t i=0;i<NNum;++i) { m_num[i][0]=f_num[i][0]; } } /** \brief Setting denominator coefficients * * @param f_den denominator coefficients * */ template <class T,uint32_t NNum,uint32_t NDen> void signal::systemmodels::lti::siso::CDiscreteTransferFunction<T,NNum,NDen>::setDen(const CDenType& f_den) { for(uint32_t i=1;i<NDen;++i) { m_den[i-1][0]=f_den[i][0]; } m_denCoef = f_den[0][0]; } /** \brief Getting the last calculated output * * * @return last output value */ template <class T,uint32_t NNum,uint32_t NDen> T signal::systemmodels::lti::siso::CDiscreteTransferFunction<T,NNum,NDen>::getOutput() { return m_memOutput[0][0]; } /** \brief Shift the memorized values. After the shifting the first element in the memory can be placed with a new one. * * @param f_mem memory matrix. * @return none */ template <class T,uint32_t NNum,uint32_t NDen> template<uint32_t N> void signal::systemmodels::lti::siso::CDiscreteTransferFunction<T,NNum,NDen>::shiftMemory(utils::linalg::CMatrix<T,1,N>& f_mem) { for(uint32_t i=N-1;i>0;--i) { f_mem[0][i]=f_mem[0][i-1]; } } /** \brief Getter nominator * * @return the coefficients of the nominator */ template <class T,uint32_t NNum,uint32_t NDen> const typename signal::systemmodels::lti::siso::CDiscreteTransferFunction<T,NNum,NDen>::CNumType& signal::systemmodels::lti::siso::CDiscreteTransferFunction<T,NNum,NDen>::getNum(){ return m_num; } /** \brief Getter denominator * Return the denominator without the first coefficient. * * @return the coefficients of denominator */ template <class T,uint32_t NNum,uint32_t NDen> const typename signal::systemmodels::lti::siso::CDiscreteTransferFunction<T,NNum,NDen>::CDenModType& signal::systemmodels::lti::siso::CDiscreteTransferFunction<T,NNum,NDen>::getDen(){ return m_den; } /** \brief Getter denomitor first coefficeint * * @return value of the denomitor first coefficeint */ template <class T,uint32_t NNum,uint32_t NDen> float signal::systemmodels::lti::siso::CDiscreteTransferFunction<T,NNum,NDen>::getDenCurrent(){ return m_denCoef; } /******************************************************************************/ /** @brief CSSModel Class constructor * * Initialize the model matrixes of the state space model based the given input parameters. * The initial state is zero and the control-observation model is a zero matrix. * * @param f_stateTransitionMatrix state-state transition model * @param f_inputMatrix control-state transition model * @param f_measurementMatrix state-observation transition model */ template <class T, uint32_t NA, uint32_t NB, uint32_t NC> signal::systemmodels::lti::mimo::CSSModel<T,NA,NB,NC>::CSSModel( const CStateTransitionType& f_stateTransitionMatrix, const CInputMatrixType& f_inputMatrix, const CMeasurementMatrixType& f_measurementMatrix) : m_stateVector() , m_stateTransitionMatrix(f_stateTransitionMatrix) , m_inputMatrix(f_inputMatrix) , m_measurementMatrix(f_measurementMatrix) , m_directTransferMatrix() { } /** @brief CSSModel Class constructor * * Initialize the model matrixes of the state space model based the given input parameters. * The initial state is zero. * * @param f_stateTransitionMatrix state-state transition model * @param f_inputMatrix control-state transition model * @param f_measurementMatrix state-observation transition model * @param f_directTransferMatrix control-observation transition model */ template <class T, uint32_t NA, uint32_t NB, uint32_t NC> signal::systemmodels::lti::mimo::CSSModel<T,NA,NB,NC>::CSSModel( const CStateTransitionType& f_stateTransitionMatrix, const CInputMatrixType& f_inputMatrix, const CMeasurementMatrixType& f_measurementMatrix, const CDirectTransferMatrixType& f_directTransferMatrix) : m_stateVector() , m_stateTransitionMatrix(f_stateTransitionMatrix) , m_inputMatrix(f_inputMatrix) , m_measurementMatrix(f_measurementMatrix) , m_directTransferMatrix(f_directTransferMatrix) { } /** @brief CSSModel Class constructor * * Initialize the model matrixes of the state space model based the given input parameters. * * @param f_stateTransitionMatrix state-state transition model * @param f_inputMatrix control-state transition model * @param f_measurementMatrix state-observation transition model * @param f_directTransferMatrix control-observation transition model * @param f_state initial state of the system model */ template <class T, uint32_t NA, uint32_t NB, uint32_t NC> signal::systemmodels::lti::mimo::CSSModel<T,NA,NB,NC>::CSSModel( const CStateTransitionType& f_stateTransitionMatrix, const CInputMatrixType& f_inputMatrix, const CMeasurementMatrixType& f_measurementMatrix, const CDirectTransferMatrixType& f_directTransferMatrix, const CStateType& f_state) : m_stateVector(f_state) , m_stateTransitionMatrix(f_stateTransitionMatrix) , m_inputMatrix(f_inputMatrix) , m_measurementMatrix(f_measurementMatrix) , m_directTransferMatrix(f_directTransferMatrix) { } /** @brief Apply the model with the input control parameter and returning the observation. * * @param f_inputVector control values * @return observation values */ template <class T, uint32_t NA, uint32_t NB, uint32_t NC> utils::linalg::CColVector<T,NC> signal::systemmodels::lti::mimo::CSSModel<T,NA,NB,NC>::operator()(const CControlType& f_inputVector) { updateState(f_inputVector); return getOutput(f_inputVector); } /** @brief Update state of the model based the input control parameter. * * @param f_inputVector control values */ template <class T, uint32_t NA, uint32_t NB, uint32_t NC> void signal::systemmodels::lti::mimo::CSSModel<T,NA,NB,NC>::updateState(const CControlType& f_inputVector) { m_stateVector = m_stateTransitionMatrix * m_stateVector + m_inputMatrix * f_inputVector; } /** @brief Calculate and return the observation values based on the control value and the state of the system. * * @param f_inputVector control values * @return observation values */ template <class T, uint32_t NA, uint32_t NB, uint32_t NC> utils::linalg::CColVector<T,NC> signal::systemmodels::lti::mimo::CSSModel<T,NA,NB,NC>::getOutput(const CControlType& f_inputVector) { return m_measurementMatrix * m_stateVector + m_directTransferMatrix * f_inputVector; } /******************************************************************************/ /** \brief CDiscreteTimeSystemModel class constructor for non-linear systems * * @param f_dt Sampling time */ template <class T,uint32_t NA, uint32_t NB,uint32_t NC> signal::systemmodels::nlti::mimo::CDiscreteTimeSystemModel<T,NA,NB,NC>::CDiscreteTimeSystemModel(const double f_dt) : m_states() , m_dt(f_dt) { } /** \brief CDiscreteTimeSystemModel class constructor for non-linear systems * * @param f_states Initial states of the system * @param f_dt Sampling time */ template <class T,uint32_t NA, uint32_t NB,uint32_t NC> signal::systemmodels::nlti::mimo::CDiscreteTimeSystemModel<T,NA,NB,NC>::CDiscreteTimeSystemModel( const CStatesType& f_states ,const double f_dt) : m_states(f_states) , m_dt(f_dt) { } #endif // SYSTEM_MODELS_TPP
34.393846
183
0.699946
Bormachine-Learning
2c5075cf041e6e688b79119e94be7e73acc9fdc8
7,571
cpp
C++
Source/Vanity.cpp
ArchRobison/Voromoeba
608aeebd03f955a2180d05f310de6097c3df0c69
[ "Apache-2.0" ]
null
null
null
Source/Vanity.cpp
ArchRobison/Voromoeba
608aeebd03f955a2180d05f310de6097c3df0c69
[ "Apache-2.0" ]
1
2021-06-28T16:24:46.000Z
2021-06-29T13:40:23.000Z
Source/Vanity.cpp
ArchRobison/Voromoeba
608aeebd03f955a2180d05f310de6097c3df0c69
[ "Apache-2.0" ]
null
null
null
/* Copyright 2011-2021 Arch D. Robison 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. */ #define _CRT_SECURE_NO_WARNINGS #include "AssertLib.h" #include "Host.h" #include "Vanity.h" #include "NimbleDraw.h" #include "VoronoiText.h" #include "Region.h" #include <cctype> #include <cstdio> #include <cstring> #include <cstdlib> #include <sstream> /** Version field was added in version 1.2. Field was record count in version 1.1. 0x102 = version 1.2 */ static unsigned short CurrentVersion = 0x102; void VanityBoardData::VanityCheckSum::generateFrom(const VanityBoardData& data) { Assert((char*)&data.checkSum>(char*)&data); Assert(((char*)&data.checkSum-(char*)&data)%2 == 0); memset(digit, 0, sizeof(digit)); for (unsigned short* p=(unsigned short*)&data; p<(unsigned short*)&data.checkSum; ++p) { unsigned int carry = *p; for (int k=0; k<4; ++k) { carry += 41719*digit[k]; digit[k] = carry; carry >>= 16; } digit[0] ^= carry; } } std::string VanityBoardData::getVanityBoardPath() { return HostApplicationDataDir() + "/vanity.dat"; } void VanityBoardData::warn(const char* message) const { std::ostringstream tmp; tmp << message << ": " << getVanityBoardPath() << "\n"; HostWarning(tmp.str().c_str()); } void VanityBoardData::readFromFile() { bool okay = false; const auto path = getVanityBoardPath(); if (FILE* f = fopen(path.c_str(), "rb")) { const size_t n = fread(this, sizeof(VanityBoardData), 1, f); if (n==1) { if (version<=10) warn("Score file from incompatible Voromoeba 1.1"); else if (size<=maxSize) { if (version==CurrentVersion) { VanityCheckSum expected; expected.generateFrom(*this); okay = std::memcmp(&expected, &checkSum, sizeof(VanityCheckSum))==0; } else if (version<CurrentVersion) { warn("Score file from older version of Voromoeba"); } else { warn("Score file from newer version of Voromoeba"); } } } fclose(f); if (!okay) warn("Score file corrupted"); } else { warn("Cannot open score file for reading"); } if (!okay) { // Board has been corrupted. Clear it. std::memset(this, 0, sizeof(*this)); // Use to create initial file to be distributed in package. writeToFile(); } } void VanityBoardData::writeToFile() { const auto path = getVanityBoardPath(); if (FILE* f = fopen(path.c_str(), "wb")) { version = CurrentVersion; salt = RandomUInt(std::numeric_limits<uint32_t>::max()); checkSum.generateFrom(*this); // Write the signed copy const size_t n = fwrite(this, sizeof(VanityBoard), 1, f); if (n!=1) { warn("Cannot write to opened score file"); } fclose(f); } else { warn("Cannot open score file for writing"); } } size_t VanityBoardData::insert(short score) { // Set i to where score should be inserted size_t i; for (i=0; i<size; ++i) if (score > record[i].score) break; if (i<maxSize) { if (size<maxSize) ++size; // insert new score memmove(&record[i+1], &record[i], sizeof(record[0])*(maxSize-1-i)); memset(record[i].name, 0, VAIN_NAME_MAX); record[i].score = score; } return i; } VanityBoard TheVanityBoard; static VoronoiText TheVanityText; #if WIZARD_ALLOWED static void CopyTestCharsToVanityText() { int k = 0; for (int i=0; i<TheVanityText.textHeight(); ++i) for (size_t j=0; j<TheVanityText.textWidth(); ++j) { char c; if (i<8 && j<16) c = i*16+j; else { do { if (++k>=128) k=0; } while (TheVoronoiFont[k].size()==0); c = k; } TheVanityText.setChar(i, j, c); } } #endif bool VanityBoard::isCursorBlinkedOn() { const double blinkPeriod = 1; return std::fmod(HostClockTime(), blinkPeriod) < blinkPeriod*0.5; } void VanityBoard::draw(NimblePixMap& window) { #if WIZARD_ALLOWED if (myShowTestImage) { CopyTestCharsToVanityText(); TheVanityText.drawOn(window, (window.width()-TheVanityText.width())/2, (window.height()-TheVanityText.height())/2, true); return; } #endif TheVanityText.setLine(0, "Top Voromoebas"); TheVanityText.setLine(1, ""); TheVanityText.setLine(2, "Score Player"); for (size_t i=0; i<TheVanityBoard.maxSize; ++i) { const int scoreWidth=5; char buffer[scoreWidth+1+VAIN_NAME_MAX+1]; if (i<size) { sprintf(buffer, "%5d ", record[i].score); strncpy(buffer+scoreWidth+1, record[i].name, VAIN_NAME_MAX); if (i==currentRow && isCursorBlinkedOn()) { Assert(0<=currentCol && currentCol<VAIN_NAME_MAX); Assert(buffer[scoreWidth+1+currentCol]=='\0'); buffer[scoreWidth+1+currentCol] = 0x7F; } buffer[scoreWidth+1+VAIN_NAME_MAX] = 0; } else { buffer[0] = '\0'; } TheVanityText.setLine(3+i, buffer); } float scale = Min(0.9f*window.width()/TheVanityText.width(), 0.9f*window.height()/TheVanityText.height()); // Draw the text centered on the screen TheVanityText.drawOn(window, (window.width()-TheVanityText.width()*scale)/2, (window.height()-TheVanityText.height()*scale)/2, scale, true); } void VanityBoard::newScore(int score) { int i = insert(score); if (i<maxSize) { currentRow = i; currentCol = 0; } } bool VanityBoard::enterNextCharacterOfName(int key) { Assert(size_t(currentRow)<maxSize); // Only allow letters, spaces, and periods in a name. if (isalpha(key) || strchr(". ", key)!=NULL) { currentChar() = key; if (currentCol+1<VAIN_NAME_MAX) ++currentCol; } else { switch (key) { case HOST_KEY_RETURN: currentRow = -1; currentCol = -1; writeToFile(); return true; case HOST_KEY_DELETE: case HOST_KEY_BACKSPACE: if (currentCol>0) --currentCol; currentChar() = 0; break; default: break; } } return false; } #if WIZARD_ALLOWED void VanityBoard::showTestImage(bool flag) { myShowTestImage = flag; } #endif void InitializeVanity() { TheVanityBoard.readFromFile(); TheVanityText.initialize(13, 5+1+VAIN_NAME_MAX); }
32.633621
145
0.564523
ArchRobison
2c55283513cc0c90028dce3732e8eef7361087bd
2,872
cpp
C++
src/Compass.cpp
00steve/Lapster
42c11d7bf96694c36f75d938563031cb08951ff1
[ "Apache-2.0" ]
null
null
null
src/Compass.cpp
00steve/Lapster
42c11d7bf96694c36f75d938563031cb08951ff1
[ "Apache-2.0" ]
null
null
null
src/Compass.cpp
00steve/Lapster
42c11d7bf96694c36f75d938563031cb08951ff1
[ "Apache-2.0" ]
null
null
null
#include "Compass.h" /*define static variables which will pretty much be anything that reads from the compass. There is only one, so it only makes sense to read to the same variables that can be accessed from anywhere.*/ bool Compass::initialized = false; Adafruit_HMC5883_Unified Compass::mag = Adafruit_HMC5883_Unified(12345); sensors_event_t Compass::event; float Compass::heading; float Compass::declinationAngle = 0.157; //waukesha has 3deg. 32' declination float Compass::headingDegrees; Double3 Compass::directionVector = Double3(0,0,1); void Compass::Setup(){ if(initialized) return; if(!mag.begin()) { /* There was a problem detecting the HMC5883 ... check your connections */ Serial.println("Ooops, no HMC5883 detected ... Check your wiring!"); return; } Serial.println("[initialize] compass"); initialized = true; sensor_t sensor; mag.setMagGain(HMC5883_MAGGAIN_5_6); Serial.println("------------------------------------"); Serial.print ("Sensor: "); Serial.println(sensor.name); Serial.print ("Driver Ver: "); Serial.println(sensor.version); Serial.print ("Unique ID: "); Serial.println(sensor.sensor_id); Serial.print ("Max Value: "); Serial.print(sensor.max_value); Serial.println(" uT"); Serial.print ("Min Value: "); Serial.print(sensor.min_value); Serial.println(" uT"); Serial.print ("Resolution: "); Serial.print(sensor.resolution); Serial.println(" uT"); Serial.println("------------------------------------"); record = true; } void Compass::Update(){ mag.getEvent(&Compass::event); Compass::heading = atan2(Compass::event.magnetic.y, Compass::event.magnetic.x); Compass::heading += Compass::declinationAngle; // Correct for when signs are reversed. if(Compass::heading < 0) Compass::heading += 2*PI; // Check for wrap due to addition of declination. if(Compass::heading > 2*PI) Compass::heading -= 2*PI; Compass::headingDegrees = Compass::heading * 180/M_PI; directionVector.X = Compass::event.magnetic.x; directionVector.Y = Compass::event.magnetic.y; directionVector.Z = Compass::event.magnetic.z; directionVector.Normalize(); /* Serial.print(directionVector.X); Serial.print("\t"); Serial.print(directionVector.Y); Serial.print("\t"); Serial.println(directionVector.Z); */ newData = true; } String Compass::Label(){ return "Compass"; } void Compass::SetTilt(Double3 tilt){ } Double3 Compass::Raw(){ return Double3(event.magnetic.x,event.magnetic.y,event.magnetic.z); } String Compass::StatusString(){ return "X: \t"+ String(event.magnetic.x) + "," + String(event.magnetic.y) + "\n"; } Double3 Compass::DirectionVector(){ return directionVector; } Double3* Compass::MagneticNorthRef(){ return &directionVector; }
30.231579
93
0.66539
00steve
2c55bfb456b057200f2a5e2f6cfe043857080fb3
1,528
cpp
C++
libstarlight/source/starlight/ui/DrawLayerProxy.cpp
mothie/libstarlight
91bd6892ccc95ccf255cad73ef659b6cf37ab4a9
[ "MIT" ]
36
2017-01-17T22:58:08.000Z
2021-12-28T00:04:52.000Z
libstarlight/source/starlight/ui/DrawLayerProxy.cpp
mothie/libstarlight
91bd6892ccc95ccf255cad73ef659b6cf37ab4a9
[ "MIT" ]
3
2017-03-26T20:47:25.000Z
2019-12-12T01:50:02.000Z
libstarlight/source/starlight/ui/DrawLayerProxy.cpp
mothie/libstarlight
91bd6892ccc95ccf255cad73ef659b6cf37ab4a9
[ "MIT" ]
9
2017-04-17T19:01:24.000Z
2021-12-01T18:26:01.000Z
#include "DrawLayerProxy.h" #include "starlight/GFXManager.h" #include "starlight/InputManager.h" using starlight::GFXManager; using starlight::gfx::DrawContextCanvas; using starlight::InputManager; using starlight::ui::DrawLayerProxy; void DrawLayerProxy::Refresh() { canvas.reset(); MarkForRedraw(); } void DrawLayerProxy::PreDraw() { if (useCanvas) { if (!canvas) { canvas = std::make_unique<DrawContextCanvas>(rect.size); canvas->Clear(); GFXManager::PushContext(canvas.get()); if (eDraw) eDraw(*this); GFXManager::PopContext(); } } else canvas.reset(); } void DrawLayerProxy::Draw() { if (canvas) { auto rect = (this->rect + GFXManager::GetOffset()).IntSnap(); canvas->Draw(VRect(rect.pos, canvas->rect.size)); } else { if (eDraw) eDraw(*this); } } void DrawLayerProxy::OnTouchOn() { if (!eOnTap) return; if (InputManager::Pressed(Keys::Touch)) { InputManager::GetDragHandle().Grab(this); MarkForRedraw(); } } void DrawLayerProxy::OnTouchOff() { auto& drag = InputManager::GetDragHandle(); if (drag == this) drag.Release(); } void DrawLayerProxy::OnDragHold() { if (InputManager::TouchDragDist().Length() > InputManager::dragThreshold) { InputManager::GetDragHandle().PassUp(); } } void DrawLayerProxy::OnDragRelease() { if (InputManager::Released(Keys::Touch)) { if (eOnTap) eOnTap(*this); } MarkForRedraw(); }
23.875
79
0.627618
mothie
2c5e986cfccbcfbcfc55365638fce5a6aabafa9d
1,596
hpp
C++
src/ChunkManager.hpp
Zenpock/OpenFusion
2af33da4e8174158ac7016b7f381eab6475d39d9
[ "MIT" ]
null
null
null
src/ChunkManager.hpp
Zenpock/OpenFusion
2af33da4e8174158ac7016b7f381eab6475d39d9
[ "MIT" ]
null
null
null
src/ChunkManager.hpp
Zenpock/OpenFusion
2af33da4e8174158ac7016b7f381eab6475d39d9
[ "MIT" ]
null
null
null
#pragma once #include "CNProtocol.hpp" #include <utility> #include <vector> #include <set> #include <map> #include <tuple> class Chunk { public: std::set<CNSocket*> players; std::set<int32_t> NPCs; }; enum { INSTANCE_OVERWORLD, // default instance every player starts in INSTANCE_IZ, // these aren't actually used INSTANCE_UNIQUE // these aren't actually used }; namespace ChunkManager { void init(); void cleanup(); extern std::map<std::tuple<int, int, uint64_t>, Chunk*> chunks; void newChunk(std::tuple<int, int, uint64_t> pos); void populateNewChunk(Chunk* chunk, std::tuple<int, int, uint64_t> pos); void addNPC(int posX, int posY, uint64_t instanceID, int32_t id); void addPlayer(int posX, int posY, uint64_t instanceID, CNSocket* sock); bool removePlayer(std::tuple<int, int, uint64_t> chunkPos, CNSocket* sock); bool removeNPC(std::tuple<int, int, uint64_t> chunkPos, int32_t id); bool checkChunk(std::tuple<int, int, uint64_t> chunk); void destroyChunk(std::tuple<int, int, uint64_t> chunkPos); std::tuple<int, int, uint64_t> grabChunk(int posX, int posY, uint64_t instanceID); std::vector<Chunk*> grabChunks(std::tuple<int, int, uint64_t> chunkPos); std::vector<Chunk*> getDeltaChunks(std::vector<Chunk*> from, std::vector<Chunk*> to); std::vector<std::tuple<int, int, uint64_t>> getChunksInMap(uint64_t mapNum); bool inPopulatedChunks(int posX, int posY, uint64_t instanceID); void createInstance(uint64_t); void destroyInstance(uint64_t); void destroyInstanceIfEmpty(uint64_t); }
33.957447
89
0.707393
Zenpock
2c61f0b434ad1e27e13977a9e71c16d853ed41cf
461
cpp
C++
Interpreter_Fase-3/src/Interpreter/Core/Logger.cpp
favo52/Interpreter
229f0658dd91fde050919bc40179af2b857816f5
[ "Apache-2.0" ]
null
null
null
Interpreter_Fase-3/src/Interpreter/Core/Logger.cpp
favo52/Interpreter
229f0658dd91fde050919bc40179af2b857816f5
[ "Apache-2.0" ]
null
null
null
Interpreter_Fase-3/src/Interpreter/Core/Logger.cpp
favo52/Interpreter
229f0658dd91fde050919bc40179af2b857816f5
[ "Apache-2.0" ]
null
null
null
#include "pch.h" #include "Logger.h" #include <spdlog/sinks/stdout_color_sinks.h> namespace Interpreter { std::shared_ptr<spdlog::logger> Logger::s_Logger; void Logger::Init() { try { spdlog::set_pattern("%^%n: %v%$"); s_Logger = spdlog::stdout_color_mt("Interpreter"); s_Logger->set_level(spdlog::level::trace); } catch (const spdlog::spdlog_ex& ex) { std::cerr << "Log initialization failed: " << ex.what() << std::endl; } } }
18.44
72
0.650759
favo52
2c65af3f3d46b9fe6d111782c2dba8eba61aa677
997
cpp
C++
test_lib.cpp
alexb5/homework04
f352483d5466ec56d96a9c6092aff46ac85d25b0
[ "MIT" ]
null
null
null
test_lib.cpp
alexb5/homework04
f352483d5466ec56d96a9c6092aff46ac85d25b0
[ "MIT" ]
null
null
null
test_lib.cpp
alexb5/homework04
f352483d5466ec56d96a9c6092aff46ac85d25b0
[ "MIT" ]
null
null
null
#include "lib.h" #include <gtest/gtest.h> #include <list> #include <sstream> #include <vector> TEST(version_test_case, version_test) { EXPECT_GT(lib::version_patch(), 0); EXPECT_GT(lib::version_major(), 0); EXPECT_GT(lib::version_minor(), 0); } TEST(print_ip, test_print_integral_types) { std::stringstream s; lib::print_ip(uint8_t{}, s); lib::print_ip(char{-1}, s); lib::print_ip(uint8_t{1}, s); lib::print_ip(uint16_t{0xFEFF}, s); lib::print_ip(uint32_t{0xFCFDFEFF}, s); EXPECT_EQ(s.str(), std::string{"0\n255\n1\n254.255\n252.253.254.255\n"}); } TEST(print_ip, test_print_container_types) { std::stringstream s; lib::print_ip(std::vector<int>{1,2,3,4}, s); lib::print_ip(std::list{4,3,2,1}, s); EXPECT_EQ(s.str(), std::string{"1.2.3.4\n4.3.2.1\n"}); } TEST(print_ip, test_print_tuple) { std::stringstream s; lib::print_ip(std::make_tuple(1, 2, 3, 4), s); EXPECT_EQ(s.str(), std::string{"1.2.3.4\n"}); }
21.673913
77
0.631896
alexb5
ef19d102a83257c4e33c02a46bc4b1434cb12dc9
1,071
cpp
C++
程序设计与方法实践/压位.cpp
xiabee/BIT-CS
5d8d8331e6b9588773991a872c259e430ef1eae1
[ "Apache-2.0" ]
63
2021-01-10T02:32:17.000Z
2022-03-30T04:08:38.000Z
程序设计与方法实践/压位.cpp
xiabee/BIT-CS
5d8d8331e6b9588773991a872c259e430ef1eae1
[ "Apache-2.0" ]
2
2021-06-09T05:38:58.000Z
2021-12-14T13:53:54.000Z
程序设计与方法实践/压位.cpp
xiabee/BIT-CS
5d8d8331e6b9588773991a872c259e430ef1eae1
[ "Apache-2.0" ]
20
2021-01-12T11:49:36.000Z
2022-03-26T11:04:58.000Z
#include<bits/stdc++.h> using namespace std; #define w 9 const long long jw = 1e9; const int MAXN = 800005; char s1[MAXN],s2[MAXN]; long long a[MAXN],b[MAXN],ans[MAXN]; int change(char s[],long long n[]) { char temp[MAXN]; int len = strlen(s + 1),now = 0; while(len/w) { strncpy(temp,s+len-w + 1,w); n[++now] = atoi(temp); len -= w; } if(len) { memset(temp,0,sizeof temp); strncpy(temp,s + 1,len); n[++now] = atoi(temp); } return now; } void calc(long long a[],long long b[],long long c[],int l1,int l2) { for(int i = 1;i <= l1;i++) { for(int j = 1;j <= l2;j++) { c[i + j - 1] += a[i] * b[j]; c[i + j] += c[i + j - 1] / jw; c[i + j - 1] = c[i + j - 1] % jw; } } return; } void print(long long a[]) { for(int i = 200000;i > 0;i--) { if(a[i] != 0) { printf("%d",a[i]); for(int j = i - 1;j >= 1;j--) { printf("%0*d",w,a[j]); } printf("\n"); break; } } } int main() { scanf("%s %s",s1 + 1,s2 + 1); int la = change(s1 ,a), lb = change(s2 ,b); calc(a,b,ans,la,lb); print(ans); return 0; }
15.75
66
0.499533
xiabee
ef202d006ad04429dac71803fa747358dbc4d501
2,963
cpp
C++
project/source/engine/gui/Slider.cpp
ntnt/carpg
f26c43c76d39f2ec2c51bd929f1b85f3c5197337
[ "MIT" ]
1
2016-04-30T15:34:11.000Z
2016-04-30T15:34:11.000Z
project/source/engine/gui/Slider.cpp
ntnt/carpg
f26c43c76d39f2ec2c51bd929f1b85f3c5197337
[ "MIT" ]
null
null
null
project/source/engine/gui/Slider.cpp
ntnt/carpg
f26c43c76d39f2ec2c51bd929f1b85f3c5197337
[ "MIT" ]
1
2018-11-30T23:32:58.000Z
2018-11-30T23:32:58.000Z
#include "Pch.h" #include "EngineCore.h" #include "Slider.h" //================================================================================================= Slider::Slider() : hold(false), minstep(false) { bt[0].text = '<'; bt[0].id = GuiEvent_Custom; bt[0].parent = this; bt[0].size = Int2(32, 32); bt[1].text = '>'; bt[1].id = GuiEvent_Custom + 1; bt[1].parent = this; bt[1].size = Int2(32, 32); } //================================================================================================= void Slider::Draw(ControlDrawData*) { const int D = 150; bt[0].global_pos = bt[0].pos = global_pos; bt[1].global_pos = bt[1].pos = bt[0].pos + Int2(D, 0); for(int i = 0; i < 2; ++i) bt[i].Draw(); Rect r0 = { global_pos.x + 32, global_pos.y - 16, global_pos.x + D, global_pos.y + 48 }; GUI.DrawText(GUI.default_font, text, DTF_CENTER | DTF_VCENTER, Color::Black, r0); } //================================================================================================= void Slider::Update(float dt) { for(int i = 0; i < 2; ++i) { bt[i].mouse_focus = mouse_focus; bt[i].Update(dt); } if(hold) { if(hold_state == -1) { if(bt[0].state == Button::NONE) hold_state = 0; else { if(hold_tmp > 0.f) hold_tmp = 0.f; hold_tmp -= hold_val*dt; int count = (int)ceil(hold_tmp); if(count) { val += count; if(val < minv) val = minv; hold_tmp -= count; parent->Event((GuiEvent)id); minstep = true; } } } else if(hold_state == +1) { if(bt[1].state == Button::NONE) hold_state = 0; else { if(hold_tmp < 0.f) hold_tmp = 0.f; hold_tmp += hold_val*dt; int count = (int)floor(hold_tmp); if(count) { val += count; if(val > maxv) val = maxv; hold_tmp -= count; parent->Event((GuiEvent)id); minstep = true; } } } } } //================================================================================================= void Slider::Event(GuiEvent e) { if(e == GuiEvent_Custom) { if(val != minv) { if(hold) { if(bt[0].state == Button::DOWN) hold_state = -1; else { hold_state = 0; if(!minstep) { --val; parent->Event((GuiEvent)id); } minstep = false; } } else { --val; parent->Event((GuiEvent)id); } } } else if(e == GuiEvent_Custom + 1) { if(val != maxv) { if(hold) { if(bt[1].state == Button::DOWN) hold_state = +1; else { hold_state = 0; if(!minstep) { ++val; parent->Event((GuiEvent)id); } minstep = false; } } else { ++val; parent->Event((GuiEvent)id); } } } } //================================================================================================= void Slider::SetHold(bool _hold) { hold = _hold; for(int i = 0; i < 2; ++i) bt[i].hold = hold; hold_tmp = 0.f; hold_state = 0; }
18.99359
99
0.436045
ntnt
ef20e13a6e1f8e39fe6ea6fd28b1f72634ec2a40
452
cxx
C++
Algorithms/Sorting/big-sorting.cxx
will-crawford/HackerRank
74965480ee6a51603eb320e5982b0943fdaf1302
[ "MIT" ]
null
null
null
Algorithms/Sorting/big-sorting.cxx
will-crawford/HackerRank
74965480ee6a51603eb320e5982b0943fdaf1302
[ "MIT" ]
null
null
null
Algorithms/Sorting/big-sorting.cxx
will-crawford/HackerRank
74965480ee6a51603eb320e5982b0943fdaf1302
[ "MIT" ]
null
null
null
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { int n; cin >> n >> ws; vector<string> vs (n); while ( n > 0 ) cin >> vs[--n]; sort ( begin(vs), end(vs), [] ( const string &l, const string &r ) { size_t ll = l.length(), rl = r.length(); return ll < rl || ll == rl && l < r; } ); for ( auto &s : vs ) cout << s << endl; return 0; }
25.111111
89
0.524336
will-crawford
ef21fa806bb3d23f14b48118b063b66e24628942
599
cpp
C++
baekjoon/4276/count_zero.cpp
ucyang/AlgoEx
465c88f04b9449c06ee5c9a684ded5aba8ccf399
[ "MIT" ]
null
null
null
baekjoon/4276/count_zero.cpp
ucyang/AlgoEx
465c88f04b9449c06ee5c9a684ded5aba8ccf399
[ "MIT" ]
null
null
null
baekjoon/4276/count_zero.cpp
ucyang/AlgoEx
465c88f04b9449c06ee5c9a684ded5aba8ccf399
[ "MIT" ]
null
null
null
// Problem: https://www.acmicpc.net/problem/4276 #include <iostream> using namespace std; unsigned long long CountZeros(long long n) { unsigned long long count = 1; unsigned long long i = 1; unsigned long long a, b, c; if (n < 0) return 0; while (true) { a = n / i / 10; b = n / i % 10; c = n % i; if (!a) break; if (!b) count += (a - 1) * i + c + 1; else count += a * i; i *= 10; } return count; } int main() { long long n, m; while (true) { cin >> n >> m; if (n < 0) break; cout << CountZeros(m) - CountZeros(n - 1) << endl; } return 0; }
12.22449
52
0.532554
ucyang
ef2306095b2a2c04de2a0b0e51fcfc42c7803340
3,198
cpp
C++
SDKs/CryCode/3.8.1/CryEngine/CryAction/Network/GenericPlaybackListener.cpp
amrhead/FireNET
34d439aa0157b0c895b20b2b664fddf4f9b84af1
[ "BSD-2-Clause" ]
4
2017-12-18T20:10:16.000Z
2021-02-07T21:21:24.000Z
SDKs/CryCode/3.8.1/CryEngine/CryAction/Network/GenericPlaybackListener.cpp
amrhead/FireNET
34d439aa0157b0c895b20b2b664fddf4f9b84af1
[ "BSD-2-Clause" ]
null
null
null
SDKs/CryCode/3.8.1/CryEngine/CryAction/Network/GenericPlaybackListener.cpp
amrhead/FireNET
34d439aa0157b0c895b20b2b664fddf4f9b84af1
[ "BSD-2-Clause" ]
3
2019-03-11T21:36:15.000Z
2021-02-07T21:21:26.000Z
/************************************************************************* Crytek Source File. Copyright (C), Crytek Studios, 2007. ------------------------------------------------------------------------- $Id$ $DateTime$ Description: network breakability: playback of generic breaking events ------------------------------------------------------------------------- History: - 22/01/2007 10:34 : Created by Craig Tiller *************************************************************************/ #include "StdAfx.h" #include "IBreakableManager.h" #if !NET_USE_SIMPLE_BREAKAGE #include "GenericPlaybackListener.h" CGenericPlaybackListener::CGenericPlaybackListener() : m_spawnIdx(0), m_pBreakage(0) { } void CGenericPlaybackListener::Perform( const SSimulateRemoveEntityParts& param, INetBreakagePlaybackPtr pBreakage ) { CRY_ASSERT(!m_pBreakage); m_pBreakage = pBreakage; CRY_ASSERT(m_spawnIdx == 0); EventPhysRemoveEntityParts event; event.pEntity = param.ent.Find(); if (!event.pEntity) return; event.iForeignData = event.pEntity->GetiForeignData(); event.pForeignData = event.pEntity->GetForeignData(event.iForeignData); gEnv->pEntitySystem->GetBreakableManager()->FakePhysicsEvent(&event); } bool CGenericPlaybackListener::AcceptUpdateMesh( const EventPhysUpdateMesh * pEvent ) { return false; } bool CGenericPlaybackListener::AcceptCreateEntityPart( const EventPhysCreateEntityPart * pEvent ) { return false; } bool CGenericPlaybackListener::AcceptRemoveEntityParts( const EventPhysRemoveEntityParts * pEvent ) { return false; } bool CGenericPlaybackListener::AcceptJointBroken( const EventPhysJointBroken * pEvent ) { return false; } void CGenericPlaybackListener::OnSpawn( IEntity * pEntity, SEntitySpawnParams& params ) { CRY_ASSERT(m_pBreakage!=NULL); m_pBreakage->SpawnedEntity(m_spawnIdx++, pEntity->GetId()); } void CGenericPlaybackListener::OnRemove( IEntity * pEntity ) { } void CGenericPlaybackListener::EndEvent(INetContext * pCtx) { CRY_ASSERT(m_pBreakage!=NULL); m_pBreakage = 0; m_spawnIdx = 0; } void CGenericPlaybackListener::OnStartFrame() { } bool CGenericPlaybackListener::OnEndFrame() { CRY_ASSERT(false); return false; } void CGenericPlaybackListener::OnTimeout() { } /* void CGenericPlaybackListener::Perform( const SSimulateCreateEntityPart& param, INetBreakagePlayback * pBreakage ) { CRY_ASSERT(!m_pBreakage); m_pBreakage = pBreakage; CRY_ASSERT(m_spawnIdx == 0); EventPhysCreateEntityPart event; event.bInvalid = param.bInvalid; event.breakAngImpulse = param.breakAngImpulse; event.breakImpulse = param.breakImpulse; for (int i=0; i<2; i++) { event.cutDirLoc[i] = param.cutDirLoc[i]; event.cutPtLoc[i] = param.cutPtLoc[i]; } event.cutRadius = param.cutRadius; event.pEntNew = param.entNew.Find(); event.pEntity = param.entSrc.Find(); if (!event.pEntity) return; event.iForeignData = event.pEntity->GetiForeignData(); event.pForeignData = event.pEntity->GetForeignData(); event.nTotParts = param.nTotParts; event.partidNew = param.partidNew; event.partidSrc = param.partidSrc; gEnv->pEntitySystem->GetBreakableManager()->FakePhysicsEvent(&event); } */ #endif // !NET_USE_SIMPLE_BREAKAGE
26.213115
116
0.700438
amrhead
ef23398e57ee29ae97ba2b8561bdcfb8590b4df6
6,918
cpp
C++
tst/prob/uCdfInverse.cpp
transpixel/TPQZcam
b44a97d44b49e9aa76c36efb6e4102091ff36c67
[ "MIT" ]
1
2017-06-01T00:21:16.000Z
2017-06-01T00:21:16.000Z
tst/prob/uCdfInverse.cpp
transpixel/TPQZcam
b44a97d44b49e9aa76c36efb6e4102091ff36c67
[ "MIT" ]
3
2017-06-01T00:26:16.000Z
2020-05-09T21:06:27.000Z
testprob/uCdfInverse.cpp
transpixel/tpqz
2d8400b1be03292d0c5ab74710b87e798ae6c52c
[ "MIT" ]
null
null
null
// // // MIT License // // Copyright (c) 2017 Stellacore Corporation. // // 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. // // /*! \file \brief This file contains unit test for prob::CdfInverse */ #include "libprob/CdfInverse.h" #include "libdat/info.h" #include "libio/stream.h" #include "libio/sprintf.h" #include <array> #include <fstream> #include <iostream> #include <sstream> #include <string> #include <set> namespace { //! Check for common functions std::string prob_CdfInverse_test0 () { std::ostringstream oss; prob::CdfInverse const aNull; if (aNull.isValid()) { oss << "Failure of null value test" << std::endl; oss << "infoString: " << aNull.infoString("aNull") << std::endl; } return oss.str(); } bool isInteresting ( std::string const & str , std::set<std::string> const & keys ) { bool okay(false); for (std::string const & key : keys) { size_t const pos(str.find(key)); okay = (std::string::npos != pos); if (okay) { break; } } return okay; } std::string memoryInfoString ( std::string const & title = std::string() , std::set<std::string> const & keys = { "VmData" } , std::string const & sep = std::string(" ") ) { std::ostringstream oss; oss << title << sep; std::ifstream ifs("/proc/self/status"); std::string line; while (ifs && (! ifs.eof())) { line.clear(); std::getline(ifs, line); if (isInteresting(line, keys)) { if (! oss.str().empty()) { oss << sep; } oss << line; } } return oss.str(); } //! Check basic operations std::string prob_CdfInverse_test1 () { std::ostringstream oss; // determines resolution of test // large size for test accuracy - but also to make timing more significant // size_t const tabSize(16u*1024u*1024u + 2u); size_t const tabSize( 256u*1024u + 2u); // required cdf data end conditions double const cdf0( .000); double const cdf1(1.000); std::ostringstream omem; omem << " " << memoryInfoString("before data"); // create a simple CDF // [ 0 1 2 3) std::array<double, 4u> const probs{ cdf0, .125, .500, cdf1 }; // std::array<double, 4u> const probs{ cdf0, 1./3., 2./3., cdf1 }; // std::array<double, 4u> const probs{ cdf0, .001, .010, cdf1 }; // same number of data values std::vector<double> const expDatas{ 100., 200., 300., 400. }; dat::Range<double> const dataRange(expDatas.front(), expDatas.back()); omem << " " << memoryInfoString("before ctor"); // instantiate inverse prob::CdfInverse const invcdf (probs.begin(), probs.end(), dataRange, tabSize); if (! invcdf.isValid()) { oss << "Failure of invcdf ctor test" << std::endl; } omem << " " << memoryInfoString("after ctor"); // double const expKB(double(tabSize - 2u) * 8. / 1024.); // io::out() // << dat::infoString(expKB) << " kB" // << " " << omem.str() // << std::endl; /* io::out() << invcdf.infoString("invcdf") << std::endl; (void)invcdf.writeProbIndices(io::out(), "probs,data", 1./10.); (void)invcdf.writeProbIndices(io::out(), "probs,data", 1./(double)tabSize); */ // std::ofstream ofs("invcdf.dat"); // (void)invcdf.writeProbIndices(ofs, "probs,data", 1./1024.); // check extreme cases double const eps(dat::smallValue<double>()); // Prob(0) -> min data double const gotData0(invcdf(0.000)); double const expData0(dataRange.min()); if (! dat::nearlyEquals(gotData0, expData0)) { oss << "Failure of end point prob=0 test\n"; } // Prob(~=1) -> max data double const dataMag(dataRange.max()); double const tol0(dataMag * dat::smallValue<double>()); double const gotDataNear1(invcdf(1.000 - eps)); double const expDataNear1(dataRange.max() * (1. - eps)); if (! dat::nearlyEquals(gotDataNear1, expDataNear1, tol0)) { double const difDataNear1(gotDataNear1 - expDataNear1); oss << "Failure of end point prob NEAR 1 test\n"; oss << dat::infoString(expDataNear1, "expDataNear1") << std::endl; oss << dat::infoString(gotDataNear1, "gotDataNear1") << std::endl; oss << " tol: " << io::sprintf("%12.5e", tol0) << std::endl; oss << "difDataNear1: " << io::sprintf("%12.5e", difDataNear1) << std::endl; } // Prob(==1) -> is valid double const gotDataAt1(invcdf(1.000)); double const expDataAt1(dataRange.max()); if (! dat::nearlyEquals(gotDataAt1, expDataAt1)) { oss << "Failure of end point prob=1 test\n"; } // check general results double const maxFrac(probs.back() * (1. - eps)); std::vector<double> const gotDatas { invcdf(probs[0]) , invcdf(probs[1]) , invcdf(probs[2]) , invcdf(maxFrac) }; // check general results at data values // be a bit more lenient to handle "corners" in data double const tolN(1.e-6 * dataMag); bool const okay ( dat::nearlyEquals<double> ( gotDatas.begin(), gotDatas.end() , expDatas.begin(), expDatas.end() , tolN ) ); if (! okay) { std::vector<double> difDatas(gotDatas.size()); std::transform ( gotDatas.begin(), gotDatas.end() , expDatas.begin() , difDatas.begin() , std::minus<double>() ); double const rmse (math::rms<double>(difDatas.begin(), difDatas.end(), 0u)); oss << "Failure of invcdf op() test" << std::endl; oss << dat::infoString(expDatas.begin(), expDatas.end(), "expDatas") << std::endl; oss << dat::infoString(gotDatas.begin(), gotDatas.end(), "gotDatas") << std::endl; oss << "tolN: " << io::sprintf("%12.5e", tolN) << std::endl; oss << "rmse: " << io::sprintf("%12.5e", rmse) << std::endl; } return oss.str(); } } //! Unit test for prob::CdfInverse int main ( int const /*argc*/ , char const * const * const /*argv*/ ) { std::ostringstream oss; // run tests oss << prob_CdfInverse_test0(); oss << prob_CdfInverse_test1(); // check/report results std::string const errMessages(oss.str()); if (! errMessages.empty()) { io::err() << errMessages << std::endl; return 1; } return 0; }
25.340659
76
0.648453
transpixel
ef290e9d7cbdfafa7c0ce0694bdf2e69b3e6b740
215
cpp
C++
AED/2/2q10.cpp
Iigorsf/AED
2151ef562be8088cd76efe7afb9e73b165027fa1
[ "MIT" ]
null
null
null
AED/2/2q10.cpp
Iigorsf/AED
2151ef562be8088cd76efe7afb9e73b165027fa1
[ "MIT" ]
null
null
null
AED/2/2q10.cpp
Iigorsf/AED
2151ef562be8088cd76efe7afb9e73b165027fa1
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main(int argc, char **argv) { int v[8]; imp[7]; par[7]; for( int i=0; i<8; i++){ cin>>v[i]<<endl; } for( int i=0; i<8; i++){ if(i%2==0) } return 0; }
11.944444
31
0.511628
Iigorsf
ef323b34185fd570c0f055a3dcf7294ad3724910
4,734
cpp
C++
DeepLearningToolKit/Toolkit/Device/cSanTerminalLogAgent.cpp
zxyinz/DeepLearningForBlueShark
025206aa7450b7ec86ebab9ca2bbcabe4421af91
[ "MIT" ]
null
null
null
DeepLearningToolKit/Toolkit/Device/cSanTerminalLogAgent.cpp
zxyinz/DeepLearningForBlueShark
025206aa7450b7ec86ebab9ca2bbcabe4421af91
[ "MIT" ]
null
null
null
DeepLearningToolKit/Toolkit/Device/cSanTerminalLogAgent.cpp
zxyinz/DeepLearningForBlueShark
025206aa7450b7ec86ebab9ca2bbcabe4421af91
[ "MIT" ]
null
null
null
#include"cSanTerminalLogAgent.h" using namespace std; using namespace San; using namespace San::Device; cSanTerminalLogAgent::cSanTerminalLogAgent(cSanTerminalDevice* pTerminal, const SString &strLogFormat, const SString &strTimeFormat, const SString &strClockFormat) :cSanLogAgent(strLogFormat, strTimeFormat, strClockFormat), m_pTerminal(pTerminal) { this->iResetTagColor(); this->iResetItemColor(); } cSanTerminalLogAgent::cSanTerminalLogAgent(cSanTerminalDevice* pTerminal, const vector<FILITER> &FiliterArray, const SString &strLogFormat, const SString &strTimeFormat, const SString &strClockFormat) :cSanLogAgent(FiliterArray, strLogFormat, strTimeFormat, strClockFormat), m_pTerminal(pTerminal) { this->iResetTagColor(); this->iResetItemColor(); } cSanTerminalLogAgent::~cSanTerminalLogAgent() { } bool cSanTerminalLogAgent::iCreateAgent() { return true; } void cSanTerminalLogAgent::iReleaseAgent() { this->m_pTerminal = nullptr; } bool cSanTerminalLogAgent::_PushLog(const SANLOG &Log) { if (this->m_pTerminal == nullptr) { return false; } auto PairSet = this->iGenerateLogStringPairSet(Log); COLOR_PAIR Color; vector<TERMINALOUTPUTOBJ> ObjList; ObjList.reserve(PairSet.size() + 1); for (auto &Pair : PairSet) { Color = Pair.Type == IT_TAG ? this->iGetTagColor(Log.Type) : this->iGetItemColor(Pair.Type); ObjList.push_back(TERMINALOUTPUTOBJ(Pair.strVal, Color)); } ObjList.push_back(TERMINALOUTPUTOBJ(_SSTR("\r\n"))); (*this->m_pTerminal) << ObjList; return true; } void cSanTerminalLogAgent::iSetTagColor(const eSANLOGTYPE Type, const eSANTERMINALCOLOR FontColor, const eSANTERMINALCOLOR BackgroundColor) { auto It = this->m_TagColorSet.find(Type); if (It == this->m_TagColorSet.end()) { return; } It->second = COLOR_PAIR(FontColor, BackgroundColor); } void cSanTerminalLogAgent::iSetItemColor(const cSanTerminalLogAgent::eITEMTYPE Type, const eSANTERMINALCOLOR FontColor, const eSANTERMINALCOLOR BackgroundColor) { auto It = this->m_ItemColorSet.find(Type); if (It == this->m_ItemColorSet.end()) { return; } It->second = COLOR_PAIR(FontColor, BackgroundColor); } void cSanTerminalLogAgent::iResetTagColor() { this->m_TagColorSet.clear(); this->iResetTagColor(SLT_LOG); this->iResetTagColor(SLT_MSG); this->iResetTagColor(SLT_WARN); this->iResetTagColor(SLT_ERR); this->iResetTagColor(SLT_DBG); this->iResetTagColor(SLT_SYS); } void cSanTerminalLogAgent::iResetTagColor(const eSANLOGTYPE Type) { switch (Type) { case SLT_LOG: this->m_TagColorSet[SLT_LOG] = COLOR_PAIR(STC_DEFAULT, STC_DEFAULT); break; case SLT_MSG: this->m_TagColorSet[SLT_MSG] = COLOR_PAIR(STC_CYAN_HL, STC_DEFAULT); break; case SLT_WARN: this->m_TagColorSet[SLT_WARN] = COLOR_PAIR(STC_YELLOW_HL, STC_DEFAULT); break; case SLT_ERR: this->m_TagColorSet[SLT_ERR] = COLOR_PAIR(STC_RED_HL, STC_DEFAULT); break; case SLT_DBG: this->m_TagColorSet[SLT_DBG] = COLOR_PAIR(STC_GREY, STC_DEFAULT); break; case SLT_SYS: this->m_TagColorSet[SLT_SYS] = COLOR_PAIR(STC_MAGENTA_HL, STC_DEFAULT); break; default: break; } } void cSanTerminalLogAgent::iResetItemColor() { this->m_ItemColorSet.clear(); this->iResetItemColor(IT_TIME); this->iResetItemColor(IT_CLOCK); this->iResetItemColor(IT_TAG); this->iResetItemColor(IT_LEVEL); this->iResetItemColor(IT_CODE); this->iResetItemColor(IT_MSG); this->iResetItemColor(IT_DEBUG); this->iResetItemColor(IT_DEFAULT); } void cSanTerminalLogAgent::iResetItemColor(const eITEMTYPE Type) { switch (Type) { case IT_TIME: this->m_ItemColorSet[IT_TIME] = COLOR_PAIR(STC_DEFAULT, STC_DEFAULT); break; case IT_CLOCK: this->m_ItemColorSet[IT_CLOCK] = COLOR_PAIR(STC_DEFAULT, STC_DEFAULT); break; case IT_TAG: this->m_ItemColorSet[IT_TAG] = COLOR_PAIR(STC_DEFAULT, STC_DEFAULT); break; case IT_LEVEL: this->m_ItemColorSet[IT_LEVEL] = COLOR_PAIR(STC_DEFAULT, STC_DEFAULT); break; case IT_CODE: this->m_ItemColorSet[IT_CODE] = COLOR_PAIR(STC_DEFAULT, STC_DEFAULT); break; case IT_MSG: this->m_ItemColorSet[IT_MSG] = COLOR_PAIR(STC_DEFAULT, STC_DEFAULT); break; case IT_DEBUG: this->m_ItemColorSet[IT_DEBUG] = COLOR_PAIR(STC_GREY, STC_DEFAULT); break; case IT_DEFAULT: this->m_ItemColorSet[IT_DEFAULT] = COLOR_PAIR(STC_DEFAULT, STC_DEFAULT); break; default: break; } } COLOR_PAIR cSanTerminalLogAgent::iGetTagColor(const eSANLOGTYPE Type) const { const auto It = this->m_TagColorSet.find(Type); if (It == this->m_TagColorSet.end()) { return COLOR_PAIR(STC_DEFAULT, STC_DEFAULT); } return It->second; } COLOR_PAIR cSanTerminalLogAgent::iGetItemColor(const cSanTerminalLogAgent::eITEMTYPE Type) const { const auto It = this->m_ItemColorSet.find(Type); if (It == this->m_ItemColorSet.end()) { return COLOR_PAIR(STC_DEFAULT, STC_DEFAULT); } return It->second; }
36.415385
200
0.780313
zxyinz
ef35b0f856a99cf84d3194942ef1bc7d6a7f1a32
1,124
cpp
C++
examples/xtd.forms.examples/others/auto_scroll/src/auto_scroll.cpp
BaderEddineOuaich/xtd
6f28634c7949a541d183879d2de18d824ec3c8b1
[ "MIT" ]
1
2022-02-25T16:53:06.000Z
2022-02-25T16:53:06.000Z
examples/xtd.forms.examples/others/auto_scroll/src/auto_scroll.cpp
leanid/xtd
2e1ea6537218788ca08901faf8915d4100990b53
[ "MIT" ]
null
null
null
examples/xtd.forms.examples/others/auto_scroll/src/auto_scroll.cpp
leanid/xtd
2e1ea6537218788ca08901faf8915d4100990b53
[ "MIT" ]
null
null
null
#include <xtd/xtd> using namespace xtd; using namespace xtd::drawing; using namespace xtd::forms; int main() { form form_main; form_main.text("Auto scroll example"); form_main.size({400, 250}); form_main.auto_scroll(true); panel panel1; panel1.parent(form_main); panel1.back_color(color::light_salmon); panel1.border_style(border_style::fixed_single); panel1.dock(dock_style::top); panel panel2; panel2.parent(form_main); panel2.back_color(color::light_yellow); panel2.border_style(border_style::fixed_single); panel2.dock(dock_style::top); panel panel3; panel3.parent(form_main); panel3.back_color(color::light_blue); panel3.border_style(border_style::fixed_single); panel3.dock(dock_style::top); panel panel4; panel4.parent(form_main); panel4.back_color(color::light_pink); panel4.border_style(border_style::fixed_single); panel4.dock(dock_style::top); panel panel5; panel5.parent(form_main); panel5.back_color(color::light_green); panel5.border_style(border_style::fixed_single); panel5.dock(dock_style::top); application::run(form_main); }
24.977778
50
0.744662
BaderEddineOuaich
ef375ecf7949d6bb30307a017cdb39c1f9ee191a
20,198
cpp
C++
app/src/main/cpp/operators/sprk_exchange_common_measurement_op.cpp
techsoft3d/android_training
16663e03dbc0770d71efc26611d040f04f0e1a31
[ "MIT" ]
null
null
null
app/src/main/cpp/operators/sprk_exchange_common_measurement_op.cpp
techsoft3d/android_training
16663e03dbc0770d71efc26611d040f04f0e1a31
[ "MIT" ]
null
null
null
app/src/main/cpp/operators/sprk_exchange_common_measurement_op.cpp
techsoft3d/android_training
16663e03dbc0770d71efc26611d040f04f0e1a31
[ "MIT" ]
null
null
null
// Copyright (c) Tech Soft 3D, Inc. // // The information contained herein is confidential and proprietary to Tech Soft 3D, Inc., // and considered a trade secret as defined under civil and criminal statutes. // Tech Soft 3D, Inc. shall pursue its civil and criminal remedies in the event of // unauthorized use or misappropriation of its trade secrets. Use of this information // by anyone other than authorized employees of Tech Soft 3D, Inc. is granted only under // a written non-disclosure agreement, expressly prescribing the scope and manner of such use. #include "sprk_exchange.h" #if (defined(_MSC_VER) && _MSC_VER >= 1900) # pragma warning( push ) # pragma warning( disable: 4459 ) // declaration of <name> hides global declaration #endif #include "A3DSDKIncludes.h" #if (defined(_MSC_VER) && _MSC_VER >= 1900) # pragma warning ( pop ) #endif #include <sstream> using namespace HPS; size_t Exchange::CommonMeasurementOperator::length_measurement_index = 1; size_t Exchange::CommonMeasurementOperator::radius_measurement_index = 1; size_t Exchange::CommonMeasurementOperator::distance_measurement_index = 1; size_t Exchange::CommonMeasurementOperator::angle_measurement_index = 1; Exchange::CommonMeasurementOperator::CommonMeasurementOperator() : Operator() , measurement_precision(2) , manipulate_measurement(false) { } Exchange::CommonMeasurementOperator::CommonMeasurementOperator(Exchange::CADModel const & in_cad_model, MouseButtons in_mouse_trigger, ModifierKeys in_modifier_trigger) : Operator(in_mouse_trigger, in_modifier_trigger) , cad_model(in_cad_model) , measurement_precision(2) , manipulate_measurement(false) { selection_options.SetAlgorithm(Selection::Algorithm::Analytic).SetLevel(Selection::Level::Entity).SetProximity(0.01).SetSorting(Selection::Sorting::Default); text_attributes = TextAttributeKit::GetDefault(); text_attributes.SetSize(0.015, Text::SizeUnits::WindowRelative); materials = MaterialMappingKit::GetDefault(); materials.SetTextColor(RGBColor(1, 0, 0)).SetLineColor(RGBColor(1, 0, 0)).SetMarkerColor(RGBColor(1, 0, 0)).SetFaceColor(RGBColor(1, 0, 0)); GetUnits(); } Exchange::CommonMeasurementOperator::MeasurementInsertedEvent::~MeasurementInsertedEvent() { } Exchange::CommonMeasurementOperator::MeasurementDeletedEvent::~MeasurementDeletedEvent() { } void Exchange::CommonMeasurementOperator::OnViewAttached(HPS::View const & in_attached_view) { SetupConstructionSegment(); View view = in_attached_view; portfolio = view.GetPortfolioKey(); left_arrow = portfolio.DefineGlyph("left_arrow", HPS::GlyphKit::GetDefault(Glyph::Default::SolidTriangleLeft)); right_arrow = portfolio.DefineGlyph("right_arrow", HPS::GlyphKit::GetDefault(Glyph::Default::SolidTriangleRight)); SetGlyphColor(); GlyphLinePatternElement start_cap_glyph; start_cap_glyph.SetSource("left_arrow"); GlyphLinePatternElement end_cap_glyph; end_cap_glyph.SetSource("right_arrow"); LinePatternParallelKit line_parallel; line_parallel.SetStartCap(start_cap_glyph).SetEndCap(end_cap_glyph); LinePatternKit line_pattern; line_pattern.SetParallels(LinePatternParallelKitArray(1, line_parallel)); portfolio.DefineLinePattern("HPS_measurement_pointing_out", line_pattern); line_parallel.SetStartCap(end_cap_glyph).SetEndCap(start_cap_glyph); line_pattern.UnsetEverything(); line_pattern.SetParallels(LinePatternParallelKitArray(1, line_parallel)); portfolio.DefineLinePattern("HPS_measurement_pointing_in", line_pattern); style_segment = Database::CreateRootSegment(); style_segment.SetMaterialMapping(materials); portfolio.DefineNamedStyle("measurement_highlight", style_segment); highlight_options.SetStyleName("measurement_highlight").SetOverlay(Drawing::Overlay::InPlace); } void Exchange::CommonMeasurementOperator::SetupConstructionSegment() { SegmentKey model_segment = cad_model.GetModel().GetSegmentKey(); measurement_segment = model_segment.Subsegment("construction segments").Subsegment("measurement"); measurement_segment.GetDrawingAttributeControl().SetOverlay(Drawing::Overlay::Default); measurement_segment.GetVisibilityControl().SetText(true).SetLines(true).SetEdges(true).SetMarkers(true); measurement_segment.GetPerformanceControl().SetStaticModel(Performance::StaticModel::None); measurement_segment.GetTextAttributeControl().SetPreference(Text::Preference::Vector); measurement_segment.SetTextAttribute(text_attributes); SetMaterialsOnMeasurementSegment(measurement_segment, materials); measurement_segment.GetAttributeLockControl().SetLock(AttributeLock::Type::Material); } void Exchange::CommonMeasurementOperator::OnViewDetached(HPS::View const &) { style_segment.Delete(); portfolio.UndefineNamedStyle("measurement_highlight"); } Exchange::CADModel Exchange::CommonMeasurementOperator::GetCADModel() const { return cad_model; } void Exchange::CommonMeasurementOperator::SetCADModel(Exchange::CADModel const & in_cad_model) { cad_model = in_cad_model; GetUnits(); } size_t Exchange::CommonMeasurementOperator::GetPrecision() const { return measurement_precision; } void Exchange::CommonMeasurementOperator::SetPrecision(size_t in_precision) { measurement_precision = in_precision; } void Exchange::CommonMeasurementOperator::GetUnits() { StringMetadata string_metadata = cad_model.GetMetadata("Units"); UTF8 string_metadata_value = string_metadata.GetValue(); if (string_metadata_value != "Unknown") { if (string_metadata_value == "Millimeter") units = HPS::UTF8("mm", "utf8"); else if (string_metadata_value == "Centimeter") units = HPS::UTF8("cm", "utf8"); else if (string_metadata_value == "Meter") units = HPS::UTF8("m", "utf8"); else if (string_metadata_value == "Kilometer") units = HPS::UTF8("Km", "utf8"); else if (string_metadata_value == "Point") units = HPS::UTF8("pts", "utf8"); else if (string_metadata_value == "Pica") units = HPS::UTF8("pc", "utf8"); else if (string_metadata_value == "Inch") units = HPS::UTF8("in", "utf8"); else if (string_metadata_value == "Foot") units = HPS::UTF8("ft", "utf8"); else if (string_metadata_value == "Yard") units = HPS::UTF8("yd", "utf8"); else if (string_metadata_value == "Mile") units = HPS::UTF8("mi", "utf8"); } } MaterialMappingKit Exchange::CommonMeasurementOperator::GetMaterial() const { return materials; } void Exchange::CommonMeasurementOperator::SetMaterialsOnMeasurementSegment(HPS::SegmentKey const & set_materials_here, HPS::MaterialMappingKit const & materials_to_apply) { HPS::Material::Type material_type; HPS::RGBAColor rgba_color; float value; HPS::MaterialMappingControl material_mapping_control = set_materials_here.GetMaterialMappingControl(); if (materials_to_apply.ShowLineColor(material_type, rgba_color, value)) { if (material_type == Material::Type::MaterialIndex) material_mapping_control.SetLineMaterialByIndex(value); else material_mapping_control.SetLineColor(rgba_color); } if (materials_to_apply.ShowTextColor(material_type, rgba_color, value)) { if (material_type == Material::Type::MaterialIndex) material_mapping_control.SetTextMaterialByIndex(value); else material_mapping_control.SetTextColor(rgba_color); } if (materials_to_apply.ShowMarkerColor(material_type, rgba_color, value)) { if (material_type == Material::Type::MaterialIndex) material_mapping_control.SetMarkerMaterialByIndex(value); else material_mapping_control.SetMarkerColor(rgba_color); } } void Exchange::CommonMeasurementOperator::SetMaterial(MaterialMappingKit const & in_material_mapping) { materials = in_material_mapping; if (!measurement_segment.Empty()) { SetMaterialsOnMeasurementSegment(measurement_segment, materials); SetGlyphColor(); style_segment.SetMaterialMapping(materials); } } TextAttributeKit Exchange::CommonMeasurementOperator::GetTextAttributes() const { return text_attributes; } void Exchange::CommonMeasurementOperator::SetTextAttribute(TextAttributeKit const & in_text_attributes) { text_attributes = in_text_attributes; if (!measurement_segment.Empty()) measurement_segment.SetTextAttribute(text_attributes); } void Exchange::CommonMeasurementOperator::SetGlyphColor() { if (!left_arrow.Empty() && !right_arrow.Empty()) { RGBAColor glyph_color; Material::Type material_type; float index; materials.ShowMarkerColor(material_type, glyph_color, index); GlyphKit glyph; auto set_glyph_color = [&] () { GlyphElementArray elements; glyph.ShowElements(elements); for (auto & element : elements) { if (material_type == Material::Type::MaterialIndex) element.SetIndexedColor((byte)index); else element.SetExplicitColor(glyph_color); } glyph.SetElements(elements); }; left_arrow.Show(glyph); set_glyph_color(); left_arrow.Set(glyph); right_arrow.Show(glyph); set_glyph_color(); right_arrow.Set(glyph); } } void Exchange::CommonMeasurementOperator::GetCameraDirection() { CameraKit camera; GetAttachedView().GetSegmentKey().ShowCamera(camera); Point position, target; camera.ShowPosition(position); camera.ShowTarget(target); camera_direction = Vector(target - position); camera_direction = camera_direction.Normalize(); } void Exchange::CommonMeasurementOperator::PositionLinearMeasurementGeometry( WindowPoint const & window_cursor_location, // mouse cursor location in window coordinates KeyPath const & event_path, // event path LineKey & leader_line_one, // line extending from one end of the original measured geometry to the measurement_line LineKey & leader_line_two, // line extending from the other end of the original measured geometry to the measurement_line LineKey & measurement_line, // line between leader lines LineKey & line_to_cursor, // line extending to the cursor Point & original_point_one, // one point at one end of the geometry being measured Point & original_point_two, // one point at the other end of the geometry being measured TextKey & text, // the measurement label UTF8 const & text_string, // what the label says Point & distance_point_one, // intersection of leader_line_one and measurement_line Point & distance_point_two, // intersection of leader_line_two and measurement_line SegmentKey & current_measurement_segment, Plane const & measurement_plane, Vector const & explicit_direction) { Vector measurement_direction(original_point_two - original_point_one); float measure_distance = 0; Vector direction; HPS::Point world_point; event_path.ConvertCoordinate(HPS::Coordinate::Space::Window, window_cursor_location, HPS::Coordinate::Space::World, world_point); auto get_plane_intersection = [](KeyPath const & in_key_path, WindowPoint const & in_window_location, Plane const & in_measurement_plane) { Point window_cursor2 = in_window_location; window_cursor2.z += 100; Point world_cursor; Point world_cursor2; in_key_path.ConvertCoordinate(Coordinate::Space::Window, in_window_location, Coordinate::Space::World, world_cursor); in_key_path.ConvertCoordinate(Coordinate::Space::Window, window_cursor2, Coordinate::Space::World, world_cursor2); return in_measurement_plane.IntersectLineSegment2(world_cursor, world_cursor2); }; if (explicit_direction == Vector::Zero()) { Plane plane(camera_direction, original_point_one); Point intersection = get_plane_intersection(event_path, window_cursor_location, plane); Vector anchor_to_cursor(intersection - original_point_one); float anchor_to_cursor_distance = (float)anchor_to_cursor.Length(); anchor_to_cursor = anchor_to_cursor.Normalize(); direction = camera_direction.Cross(measurement_direction); direction = direction.Normalize(); float angle = HPS::ACos(anchor_to_cursor.Dot(direction)); measure_distance = anchor_to_cursor_distance * HPS::Cos(angle); } else { direction = explicit_direction; measurement_direction = measurement_direction.Normalize(); Plane explicit_measurement_plane(original_point_one, direction.Cross(measurement_direction)); Point intersection = get_plane_intersection(event_path, window_cursor_location, explicit_measurement_plane); Vector anchor_to_cursor(intersection - original_point_one); float anchor_to_cursor_distance = (float)anchor_to_cursor.Length(); anchor_to_cursor = anchor_to_cursor.Normalize(); direction = explicit_direction; float angle = HPS::ACos(anchor_to_cursor.Dot(direction)); measure_distance = anchor_to_cursor_distance * HPS::Cos(angle); } Point measure_point_one = original_point_one + direction * measure_distance; Point measure_point_two = original_point_two + direction * measure_distance; float const epsilon = 0.00001; if (fabs(measure_point_one.x - measure_point_two.x) <= epsilon && fabs(measure_point_one.y - measure_point_two.y) <= epsilon && fabs(measure_point_one.z - measure_point_two.z) <= epsilon) { //measurement of size 0 Point window_cursor2 = window_cursor_location; window_cursor2.z += 100; Point world_cursor; Point world_cursor2; event_path.ConvertCoordinate(Coordinate::Space::Window, window_cursor_location, Coordinate::Space::World, world_cursor); event_path.ConvertCoordinate(Coordinate::Space::Window, window_cursor2, Coordinate::Space::World, world_cursor2); world_point = measurement_plane.IntersectLineSegment2(world_cursor, world_cursor2); Point line_to_cursor_points [] = {world_point, world_point}; line_to_cursor.EditPointsByReplacement(0, 2, line_to_cursor_points); Point connector_one_points [] = {original_point_one, world_point}; leader_line_one.EditPointsByReplacement(0, 2, connector_one_points); Point connector_two_points [] = {original_point_two, world_point}; leader_line_two.EditPointsByReplacement(0, 2, connector_two_points); distance_point_one = world_point; distance_point_two = world_point; } else { Point measurement_line_points [] = {measure_point_one, measure_point_two}; measurement_line.EditPointsByReplacement(0, 2, measurement_line_points); //in order to track the cursor correctly, operate in camera space and restrain the line to the vector defined by the measurement points Point measure_point_one_camera; Point measure_point_two_camera; Point cursor_camera; event_path.ConvertCoordinate(Coordinate::Space::Window, window_cursor_location, Coordinate::Space::Camera, cursor_camera); event_path.ConvertCoordinate(Coordinate::Space::World, measure_point_one, Coordinate::Space::Camera, measure_point_one_camera); event_path.ConvertCoordinate(Coordinate::Space::World, measure_point_two, Coordinate::Space::Camera, measure_point_two_camera); float t = 0; if (Float::Equals(measure_point_two_camera.x - measure_point_one_camera.x, 0)) t = (cursor_camera.y - measure_point_one_camera.y) / (measure_point_two_camera.y - measure_point_one_camera.y); else t = (cursor_camera.x - measure_point_one_camera.x) / (measure_point_two_camera.x - measure_point_one_camera.x); Point cursor_camera_point = measure_point_one_camera + t * (measure_point_two_camera - measure_point_one_camera); event_path.ConvertCoordinate(HPS::Coordinate::Space::Camera, cursor_camera_point, HPS::Coordinate::Space::World, world_point); Point line_to_cursor_points [] = {measure_point_one, world_point}; line_to_cursor.EditPointsByReplacement(0, 2, line_to_cursor_points); //change the line pattern used if needed: //have the arrows point out if the cursor is within the measurement //have the arrows point in otherwise Vector line_to_cursor_vector(world_point - measure_point_one); Vector distance_vector(measure_point_two - measure_point_one); double distance_vector_length = distance_vector.Length(); double line_to_cursor_vector_length = line_to_cursor_vector.Length(); float dot_p = distance_vector.Dot(line_to_cursor_vector); SegmentKey patterned_line_segment = current_measurement_segment.Subsegment("patterned_line"); if (dot_p < 0 || (dot_p > 0 && line_to_cursor_vector_length > distance_vector_length)) patterned_line_segment.GetLineAttributeControl().SetPattern("HPS_measurement_pointing_in"); else patterned_line_segment.GetLineAttributeControl().SetPattern("HPS_measurement_pointing_out"); Point connector_one_points [] = {original_point_one, measure_point_one}; leader_line_one.EditPointsByReplacement(0, 2, connector_one_points); Point connector_two_points [] = {original_point_two, measure_point_two}; leader_line_two.EditPointsByReplacement(0, 2, connector_two_points); distance_point_one = measure_point_one; distance_point_two = measure_point_two; } text.Delete(); text = current_measurement_segment.InsertText(world_point, text_string); } void Exchange::CommonMeasurementOperator::Tag(HPS::Key & tag, const char * message, Tags tag_index) { auto to_bytes = [](const char * message) { HPS::ByteArray data; size_t len = strlen(message); for (size_t i = 0; i < len; ++i) data.push_back(message[i]); data.push_back('\0'); return data; }; size_t index = static_cast<size_t>(tag_index); HPS::Type tag_type = tag.Type(); switch (tag_type) { case HPS::Type::SegmentKey: { SegmentKey tag_me(tag); HPS::ByteArray data = to_bytes(message); tag_me.SetUserData(index, data); } break; case HPS::Type::LineKey: { LineKey tag_me(tag); HPS::ByteArray data = to_bytes(message); tag_me.SetUserData(index, data); } break; case HPS::Type::MarkerKey: { MarkerKey tag_me(tag); HPS::ByteArray data = to_bytes(message); tag_me.SetUserData(index, data); } break; case HPS::Type::TextKey: { TextKey tag_me(tag); HPS::ByteArray data = to_bytes(message); tag_me.SetUserData(index, data); } break; case HPS::Type::CircularArcKey: { CircularArcKey tag_me(tag); HPS::ByteArray data = to_bytes(message); tag_me.SetUserData(index, data); } break; default: break; } } float Exchange::CommonMeasurementOperator::GetModelScale(Exchange::Component const & component) { //get the scale from the model double scale = 1; HPS::Exchange::Component body; auto component_type = component.GetComponentType(); if (component_type == Component::ComponentType::ExchangeTopoEdge) { HPS::ComponentArray co_edges = component.GetOwners(); HPS::ComponentArray loops = co_edges[0].GetOwners(); HPS::ComponentArray faces = loops[0].GetOwners(); HPS::ComponentArray shells = faces[0].GetOwners(); HPS::ComponentArray connexes = shells[0].GetOwners(); HPS::ComponentArray bodies = connexes[0].GetOwners(); body = bodies[0]; } else if (component_type == Component::ComponentType::ExchangeTopoFace) { HPS::ComponentArray shells = component.GetOwners(); HPS::ComponentArray connexes = shells[0].GetOwners(); HPS::ComponentArray bodies = connexes[0].GetOwners(); body = bodies[0]; } else return 0; A3DTopoBodyData topo_body_data; A3D_INITIALIZE_DATA(A3DTopoBodyData, topo_body_data); if (A3DTopoBodyGet(body.GetExchangeEntity(), &topo_body_data) == A3D_SUCCESS) { A3DTopoContextData context_data; A3D_INITIALIZE_DATA(A3DTopoContextData, context_data); if (A3DTopoContextGet(topo_body_data.m_pContext, &context_data) == A3D_SUCCESS && context_data.m_bHaveScale) scale = context_data.m_dScale; A3DTopoContextGet(nullptr, &context_data); } A3DTopoBodyGet(nullptr, &topo_body_data); return (float)scale; } void Exchange::CommonMeasurementOperator::DeleteMeasurements() { measurement_segment.Delete(); SetupConstructionSegment(); } SegmentKey Exchange::CommonMeasurementOperator::GetMeasurementSegment() const { return measurement_segment; } UTF8 Exchange::CommonMeasurementOperator::GetNewMeasurementSegmentName(HPS::UTF8 const & in_prefix) { std::stringstream segment_name; if (in_prefix == HPS::UTF8("Angle")) segment_name << in_prefix << "." << angle_measurement_index++; else if (in_prefix == HPS::UTF8("Distance")) segment_name << in_prefix << "." << distance_measurement_index++; else if (in_prefix == HPS::UTF8("Radius")) segment_name << in_prefix << "." << radius_measurement_index++; else if (in_prefix == HPS::UTF8("Length")) segment_name << in_prefix << "." << length_measurement_index++; return HPS::UTF8(segment_name.str().data()); }
37.682836
170
0.779978
techsoft3d
ef3b99341f83607024989d3fdc204a24de7781ce
1,316
hpp
C++
include/nana/audio/detail/audio_device.hpp
bacusters/nana
1ed7702790e54388f8299b34a8279690ab733b97
[ "BSL-1.0" ]
92
2016-09-18T14:37:22.000Z
2022-01-27T19:55:00.000Z
include/nana/audio/detail/audio_device.hpp
bacusters/nana
1ed7702790e54388f8299b34a8279690ab733b97
[ "BSL-1.0" ]
2
2017-04-16T17:05:20.000Z
2017-04-17T21:18:06.000Z
include/nana/audio/detail/audio_device.hpp
bacusters/nana
1ed7702790e54388f8299b34a8279690ab733b97
[ "BSL-1.0" ]
10
2016-09-23T02:32:01.000Z
2021-12-20T11:43:48.000Z
#ifndef NANA_AUDIO_DETAIL_AUDIO_DEVICE_HPP #define NANA_AUDIO_DETAIL_AUDIO_DEVICE_HPP #include <nana/deploy.hpp> #ifdef NANA_ENABLE_AUDIO #include <nana/audio/detail/buffer_preparation.hpp> #include <vector> #if defined(NANA_WINDOWS) #include <windows.h> #elif defined(NANA_LINUX) #include <alsa/asoundlib.h> #endif namespace nana{ namespace audio { namespace detail { class audio_device { public: audio_device(); ~audio_device(); bool empty() const; bool open(std::size_t channels, std::size_t rate, std::size_t bits_per_sample); void close(); void prepare(buffer_preparation & buf_prep); void write(buffer_preparation::meta * m); void wait_for_drain() const; private: #if defined(NANA_WINDOWS) static void __stdcall _m_dev_callback(HWAVEOUT handle, UINT msg, audio_device * self, DWORD_PTR, DWORD_PTR); #endif #if defined(NANA_WINDOWS) HWAVEOUT handle_; std::recursive_mutex queue_lock_; std::vector<buffer_preparation::meta*> done_queue_; #elif defined(NANA_LINUX) snd_pcm_t * handle_; std::size_t rate_; std::size_t channels_; std::size_t bytes_per_sample_; std::size_t bytes_per_frame_; #endif buffer_preparation * buf_prep_; }; }//end namespace detail }//end namespace audio }//end namespace nana #endif //NANA_ENABLE_AUDIO #endif
23.087719
111
0.74924
bacusters
ef3d1d96e177faf6e9f88c1caa261f53d8445765
433
hpp
C++
visual_studio/visual_studio/oxi/scene/object/gate_factory.hpp
collus-corn/oxi
93e00c51c00f78cb3d09aa9c890e98c1a572af3a
[ "MIT" ]
null
null
null
visual_studio/visual_studio/oxi/scene/object/gate_factory.hpp
collus-corn/oxi
93e00c51c00f78cb3d09aa9c890e98c1a572af3a
[ "MIT" ]
null
null
null
visual_studio/visual_studio/oxi/scene/object/gate_factory.hpp
collus-corn/oxi
93e00c51c00f78cb3d09aa9c890e98c1a572af3a
[ "MIT" ]
null
null
null
#pragma once #include "../i_gate_factory.hpp" namespace oxi { class IController; namespace scene { namespace object { class GateFactory :public IGateFactory { private: std::shared_ptr<IController> controller_; public: explicit GateFactory(std::shared_ptr<IController> controller) :controller_(controller) {} std::vector<std::shared_ptr<IGate>> create(std::string scene_name) override; }; } } }
18.826087
93
0.709007
collus-corn
ef3f708f23f6259f3b3fc8473a82c1443bfc43df
7,675
cpp
C++
FilterImage.cpp
DanielMoya123/DFT
52769c7488c79743872ec2136a54e286580830c2
[ "MIT" ]
null
null
null
FilterImage.cpp
DanielMoya123/DFT
52769c7488c79743872ec2136a54e286580830c2
[ "MIT" ]
null
null
null
FilterImage.cpp
DanielMoya123/DFT
52769c7488c79743872ec2136a54e286580830c2
[ "MIT" ]
null
null
null
#include "FilterImage.h" /***************************** * * NameSpaces * * ****************************/ using namespace std; /****************************************************** * * Constructor of the class * * **********************************************/ FilterImage::FilterImage(void) {} /****************************************************** * * Function to generate the Square Odd Gaussian Filter * * ********************************************** * * Inputs: * int kSize: the size of the filter * int variance: the variance of the gaussian function * bool otoginal: if the filter is octogonal * * Outputs: * lti::kernel2D<float> filter: the filter that response to the inputs * * Restrinctions: * ksize > 0 * variance > 0 *****/ lti::kernel2D<float> FilterImage::GenerateSquareOddGaussianFilter(int kSize, int variance, bool octagonal){ // We create the kernel to response lti::kernel2D<float> kern; // We ask if the filter is octogonal or not if (octagonal){ lti::octagonalKernel<float> gauss(kSize,variance); kern.castFrom(gauss); }else{ lti::gaussKernel2D<float> gauss(kSize,variance); kern.castFrom(gauss); } //Normalize kernel kern.divide(kSize*kSize); return kern; } /****************************************************** * * Function to generate a convolution square filter * * ********************************************** * * Inputs: * lti::kernel2D<float> kernel: The kernel * lti::matrix<float> imgToFilter: The image to filter * * Outputs: * ------------------ * * Restrinctions: * ----------------- * *****/ lti::matrix<float> FilterImage::ConvolutionSquareFilter(lti::kernel2D<float> kernel,lti::matrix<float> imgToFilter){ // Create the convolution object lti::convolution convolutionO (kernel); //lti::convolution::parameters param; // Set the kernel to convolute //param.setKernel(kernel); // We do the convolution //convolutionO.setParameters(param); convolutionO.apply(imgToFilter); return imgToFilter; } /****************************************************** * * The square filter in frequency * * ********************************************** * * Inputs: * lti::kernel2D<float> kernel: The kernel * lti::matrix<float> imgToFilter: The image to filter * int oRow: The original size of the rows * * Outputs: * ------------------ * * Restrinctions: * ------------------ * *****/ lti::matrix<float> FilterImage::FreqSquareFilter(lti::kernel2D<float> kernel,lti::matrix<float> imgToFilter,int oRow,int oCol){ // The size of the image int row = imgToFilter.rows(); int col = imgToFilter.columns(); // shift the spectrum (in the space domain) for (int y=0;y<row;y++) { float s=lti::even(y) ? 1.f : -1.f; for (int x=0;x<col;x++) { imgToFilter.at(y,x)*=s; s*=-1.f; } } // end of the shift (in the space domain) // Transform to frequency spectrum static const lti::eCoordinateSystem cordSys = lti::Polar; lti::fft fft2d; // for 2-dimensional FFT lti::ifft ifft2d; // for 2-dimensional inverse FFT // The real and imaginary parts of the image and filter lti::channel re,im; lti::channel reF,imF; // Apply the cordSys to an image and filter fft2d.apply(imgToFilter,cordSys,re,im); fft2d.apply(kernel,cordSys,reF,imF); // The result of the multiply lti::channel rRe, rRe2, rIm(col,row,0.0f), rIm1(col,row,0.0f), rIm2(col,row,0.0f); // Multiply the real parts rRe.emultiply(re,reF); rRe2.emultiply(im,imF); rRe-= rRe2; //Multiply the imaginary parts rIm1.emultiply(re,imF); rIm2.emultiply(im,reF); rIm = rIm1 + rIm2; // As the gaussian function is an even function, don't has // imaginary part or is zero and we ommitted. //rIm.copy(im); lti::matrix<float> imgResult; ifft2d.apply(rRe,rIm,cordSys,imgResult); // shift back the result (in the space domain) for (int y=0;y<row;++y) { float s=lti::even(y) ? 1.f : -1.f; for (int x=0;x<col;++x) { imgResult.at(y,x)*=s; s*=-1.f; } } imgResult = CloneMatrix(imgResult, oRow, oCol,1,1); return imgResult; } /****************************************************** * * Function to set the padding in a image * * ********************************************** * * Inputs: * lti::matrix<float> imgToFilter: The image to filter * int kSize: The size of the kernel * * Outputs: * ------------------ * * Restrinctions: * ------------------ * *****/ void FilterImage::SetPadding(lti::matrix<float> *imgToFilter, int kSize){ // Set the padding const int n = lti::iround(lti::pow(2.0f,ceil(lti::log(lti::max(imgToFilter->rows(), imgToFilter->columns())+kSize-1)/lti::log(2.0f)))); // The type of padding is zero lti::eBoundaryType padding=lti::Zero; lti::boundaryExpansion::parameters bepar; bepar.boundaryType = padding; // We set where the image is with respect the padding bepar.topBorder = 0; bepar.leftBorder = 0; bepar.bottomBorder = n-imgToFilter->rows(); bepar.rightBorder = n-imgToFilter->columns(); // Apply the boundary expansion lti::boundaryExpansion be(bepar); be.apply(*imgToFilter); } /****************************************************** * * Function to set the padding in a image * * ********************************************** * * Inputs: * lti::matrix<float> imgToFilter: The image to filter * int kpSize: The size of the kernel + the padding * * Outputs: * ------------------ * * Restrinctions: * ------------------ * *****/ void FilterImage::SetPaddingKernel(lti::kernel2D<float> *kernelToFilter, int kpSize){ // Set the padding lti::eBoundaryType padding=lti::Zero; lti::boundaryExpansion::parameters bepar; bepar.boundaryType = padding; int rows = kernelToFilter->rows(); // We set where the filter is with respect the padding bepar.topBorder = (kpSize - rows)/2 + 1; bepar.leftBorder = (kpSize - rows)/2 + 1; bepar.bottomBorder = (kpSize - rows)/2; bepar.rightBorder = (kpSize - rows)/2; lti::boundaryExpansion be(bepar); be.apply(*kernelToFilter); } /****************************************************** * * Function to clone the matrix * * ********************************************** * * Inputs: * lti::matrix<float> img: The image to clone * int nSize: The columns amount of the image * int mSize: The rows amount of the image * * Outputs: * ------------------ * * Restrinctions: * ------------------ * *****/ lti::matrix<float> FilterImage::CloneMatrix(lti::matrix<float> img, int nSize, int mSize, int beginN, int beginM){ // We create a matrix with this lti::matrix<float> imgD(nSize,mSize); // We copy all the values for (int i = beginM; i < mSize; i++) { for (int j = beginN; j < nSize; j++) { imgD.at(j,i) = img.at(j,i); } } return imgD; } /****************************************************** * Get the error of the difference * **********************************************/ double FilterImage::GetSquareError(lti::matrix<float> imgSpace, lti::matrix<float> imgFreq){ double count = 0,diff = 0; // The size of the image int row = imgSpace.rows(); int col = imgSpace.columns(); for (int i = 1; i < row; i++) { for (int j = 1; j < col; j++) { diff = imgSpace.at(j,i) - imgFreq.at(j,i); //cout << imgSpace.at(j,i) << " " << imgFreq.at(j,i) << " " << diff << endl; count+=lti::sqr(diff); } } count = count/(row*col); return count; }
24.442675
128
0.546971
DanielMoya123
ef4294816014a417d42069f0b78948700a94b39b
13,512
cpp
C++
test/test_swarm_master.cpp
Rishabh96M/Swarm-Automation-for-Warehouses
904b8edba394cde65a68059648c1727cc2c70190
[ "MIT" ]
null
null
null
test/test_swarm_master.cpp
Rishabh96M/Swarm-Automation-for-Warehouses
904b8edba394cde65a68059648c1727cc2c70190
[ "MIT" ]
null
null
null
test/test_swarm_master.cpp
Rishabh96M/Swarm-Automation-for-Warehouses
904b8edba394cde65a68059648c1727cc2c70190
[ "MIT" ]
2
2021-12-03T19:55:22.000Z
2021-12-11T15:20:22.000Z
/** * @file test_swarm_master.cpp * @author Dani Lerner (dalerner@umd.edu) * @brief Tests for the swarm master * @version 0.1 * @date 2021-12-05 * * @copyright Copyright (c) 2021 TBD * */ #include <iostream> #include <array> #include <gtest/gtest.h> #include "../include/structs/task.hpp" #include "../include/swarm_master/swarm_master.hpp" #include "../include/swarm_master/assignment_designator.hpp" bool operator==(const Task& t1, const Task& t2); template<class Element> bool found_element_in_vec(std::vector<Element>& pos_along_crate, Element pos); std::vector<int> add_buncha_robots(SwarmMaster* master); TEST(SwarmMasterTests, InitializeSwarmMaster) { SimpleClosestDesignator designator; EXPECT_NO_THROW(SwarmMaster master(&designator)); EXPECT_NO_THROW(SwarmMaster master(&designator, 0.1)); EXPECT_ANY_THROW(SwarmMaster master(&designator, 0.0)); } TEST(SwarmMasterTests, TestAddRobotToSwarm) { SimpleClosestDesignator designator; SwarmMaster master(&designator); std::vector<int> robs_ids{}; std::array<double, 2> initial_pos{2, 3}; robs_ids.push_back(master.add_robot_to_swarm(initial_pos)); robs_ids.push_back(master.add_robot_to_swarm({1,4})); const auto& avail_robots = master.get_avail_robots(); for (const auto& id_robot : robs_ids) EXPECT_EQ(id_robot, avail_robots.at(id_robot).id); EXPECT_EQ(avail_robots.at(robs_ids[0]).pos[0], 2); EXPECT_EQ(avail_robots.at(robs_ids[0]).pos[1], 3); EXPECT_EQ(avail_robots.at(robs_ids[1]).pos[0], 1); EXPECT_EQ(avail_robots.at(robs_ids[1]).pos[1], 4); } TEST(SwarmMasterTests, TestAssignCrates) { SimpleClosestDesignator designator; SwarmMaster master(&designator); std::vector<int> site_ids{}; Crate c1({1,2,3}, {4,5,6}, {3,4}, 6.2); site_ids.push_back(master.add_crate_to_system(c1)); site_ids.push_back(master.add_crate_to_system({{3,2,1}, {6,5,4}, {4,6}, 1})); site_ids.push_back(master.add_crate_to_system({{3,2,1}, {6,5,4}, {4,6}, 5})); site_ids.push_back(master.add_crate_to_system({{3,2,1}, {6,5,4}, {4,6}, 7.2})); const auto& sites = master.get_sites(); for (const auto& id_site : site_ids) EXPECT_EQ(id_site, sites.at(id_site).site_id); EXPECT_EQ(sites.at(site_ids[0]).crate.goal_pos, c1.goal_pos); EXPECT_EQ(sites.at(site_ids[1]).site_id, 1); EXPECT_TRUE(sites.at(site_ids[2]).assigned_ids.empty()); EXPECT_EQ(sites.at(site_ids[0]).robots_required, 4); EXPECT_EQ(sites.at(site_ids[1]).robots_required, 2); EXPECT_EQ(sites.at(site_ids[2]).robots_required, 3); EXPECT_EQ(sites.at(site_ids[3]).robots_required, 4); EXPECT_ANY_THROW(master.add_crate_to_system({{3,2,1}, {6,5,4}, {4,6}, 8.1})); } TEST(SwarmMasterTests, TestResetSwarm) { SimpleClosestDesignator designator; SwarmMaster master(&designator); master.add_robot_to_swarm({1,4}); master.add_crate_to_system({{3,2,1}, {6,5,4}, {4,6}, 1}); EXPECT_NE(master.get_avail_robots().size(), 0); EXPECT_NE(master.get_sites().size(), 0); master.reset_swarm(); EXPECT_EQ(master.get_avail_robots().size(), 0); EXPECT_EQ(master.get_sites().size(), 0); } TEST(SwarmMasterTests, TestNotEnoughRobots) { SimpleClosestDesignator designator; SwarmMaster master(&designator); master.add_crate_to_system({{1,2,3}, {4,5,6}, {3,4}, 5.8}); master.add_robot_to_swarm({1,4}); EXPECT_FALSE(master.enough_robots_for_assignments()); EXPECT_EQ(master.assign_robots_to_crates()->size(), 0); } TEST(SwarmMasterTests, TestSwarmOccupied) { SimpleClosestDesignator designator; SwarmMaster master(&designator); master.add_crate_to_system({{1,2,3}, {4,5,6}, {3,4}, 1}); master.add_robot_to_swarm({1,4}); master.add_robot_to_swarm({2,5}); EXPECT_TRUE(master.enough_robots_for_assignments()); EXPECT_NE(master.assign_robots_to_crates()->size(), 0); EXPECT_TRUE(master.enough_robots_for_assignments()); EXPECT_EQ(master.assign_robots_to_crates()->size(), 0); master.clear_tasks(); master.add_crate_to_system({{1,2,3}, {4,5,6}, {3,4}, 1}); EXPECT_TRUE(master.enough_robots_for_assignments()); EXPECT_NE(master.assign_robots_to_crates()->size(), 0); } TEST(SwarmMasterTests, TestAssignUniqueRobotsToMultipleCrates) { SimpleClosestDesignator designator; SwarmMaster master(&designator); std::vector<int> site_ids{}; std::vector<int> robot_ids = add_buncha_robots(&master); site_ids.push_back(master.add_crate_to_system({{1,2,3}, {4,5,6}, {3,4}, 5.8})); site_ids.push_back(master.add_crate_to_system({{3,2,1}, {6,5,4}, {6,4}, 1})); site_ids.push_back(master.add_crate_to_system({{11,12,11}, {16,15,14}, {5,5}, 7.2})); const auto& sites = master.get_sites(); auto assignments = master.assign_robots_to_crates(); int s1 = 0, s2 = 0, s3 = 0; std::vector<int> all_robot_ids{}; std::vector<std::array<double, 3> > pos_along_crate_s1{}; std::vector<std::array<double, 3> > pos_along_crate_s2{}; std::vector<std::array<double, 3> > pos_along_crate_s3{}; for (const auto& assignment : *assignments) { if (assignment.site_id == site_ids[0]) { s1++; pos_along_crate_s1.push_back(assignment.pos_crate_frame); } else if (assignment.site_id == site_ids[1]) { s2++; pos_along_crate_s2.push_back(assignment.pos_crate_frame); } else if (assignment.site_id == site_ids[2]) { s3++; pos_along_crate_s3.push_back(assignment.pos_crate_frame); } all_robot_ids.push_back(assignment.robot_id); } EXPECT_EQ(s1, sites.at(site_ids[0]).robots_required); EXPECT_EQ(s2, sites.at(site_ids[1]).robots_required); EXPECT_EQ(s3, sites.at(site_ids[2]).robots_required); std::vector<int>::iterator it; const int size_all_robot_ids = all_robot_ids.size(); it = std::unique(all_robot_ids.begin(), all_robot_ids.end()); all_robot_ids.resize(std::distance(all_robot_ids.begin(), it)); EXPECT_EQ(all_robot_ids.size(), size_all_robot_ids); } TEST(SwarmMasterTests, TestAssignmentsForTwoRobotReq) { SimpleClosestDesignator designator; SwarmMaster master(&designator); std::vector<int> site_ids{}; std::vector<int> robot_ids = add_buncha_robots(&master); site_ids.push_back(master.add_crate_to_system({{3,2,1}, {6,5,4}, {6,4}, 1})); site_ids.push_back(master.add_crate_to_system({{3,2,1}, {6,5,4}, {2,8}, 1})); const auto& sites = master.get_sites(); auto assignments = master.assign_robots_to_crates(); EXPECT_EQ(assignments->size(), 4); std::vector<std::array<double, 3> > pos_along_crate{}; for (const auto& assignment : *assignments) pos_along_crate.push_back(assignment.pos_crate_frame); EXPECT_TRUE(found_element_in_vec(pos_along_crate, {-3, 0, 0})); EXPECT_TRUE(found_element_in_vec(pos_along_crate, {3, 0, 180})); EXPECT_TRUE(found_element_in_vec(pos_along_crate, {0, -4, 90})); EXPECT_TRUE(found_element_in_vec(pos_along_crate, {0, 4, 270})); } TEST(SwarmMasterTests, TestAssignmentsForThreeRobotReq) { SimpleClosestDesignator designator; SwarmMaster master(&designator); std::vector<int> site_ids{}; std::vector<int> robot_ids = add_buncha_robots(&master); site_ids.push_back(master.add_crate_to_system({{3,2,1}, {6,5,4}, {6,4}, 5})); site_ids.push_back(master.add_crate_to_system({{3,2,1}, {6,5,4}, {2,8}, 5})); const auto& sites = master.get_sites(); auto assignments = master.assign_robots_to_crates(); EXPECT_EQ(assignments->size(), 6); std::vector<std::array<double, 3> > pos_along_crate{}; for (const auto& assignment : *assignments) pos_along_crate.push_back(assignment.pos_crate_frame); EXPECT_TRUE(found_element_in_vec(pos_along_crate, {-3, 0, 0})); EXPECT_TRUE(found_element_in_vec(pos_along_crate, {2.8, 2, 270})); EXPECT_TRUE(found_element_in_vec(pos_along_crate, {2.8, -2, 90})); EXPECT_TRUE(found_element_in_vec(pos_along_crate, {0, -4, 90})); EXPECT_TRUE(found_element_in_vec(pos_along_crate, {1, 3.8, 180})); EXPECT_TRUE(found_element_in_vec(pos_along_crate, {-1, 3.8, 0})); } TEST(SwarmMasterTests, TestAssignmentsForFourRobotReq) { SimpleClosestDesignator designator; SwarmMaster master(&designator); std::vector<int> site_ids{}; std::vector<int> robot_ids = add_buncha_robots(&master); site_ids.push_back(master.add_crate_to_system({{3,2,1}, {6,5,4}, {6,4}, 7})); site_ids.push_back(master.add_crate_to_system({{3,2,1}, {6,5,4}, {2,8}, 7})); const auto& sites = master.get_sites(); auto assignments = master.assign_robots_to_crates(); EXPECT_EQ(assignments->size(), 8); std::vector<std::array<double, 3> > pos_along_crate{}; for (const auto& assignment : *assignments) pos_along_crate.push_back(assignment.pos_crate_frame); EXPECT_TRUE(found_element_in_vec(pos_along_crate, {-2.8, 2, 270})); EXPECT_TRUE(found_element_in_vec(pos_along_crate, {-2.8, -2, 90})); EXPECT_TRUE(found_element_in_vec(pos_along_crate, {2.8, 2, 270})); EXPECT_TRUE(found_element_in_vec(pos_along_crate, {2.8, -2, 90})); EXPECT_TRUE(found_element_in_vec(pos_along_crate, {1, 3.8, 180})); EXPECT_TRUE(found_element_in_vec(pos_along_crate, {-1, 3.8, 0})); EXPECT_TRUE(found_element_in_vec(pos_along_crate, {1, -3.8, 180})); EXPECT_TRUE(found_element_in_vec(pos_along_crate, {-1, -3.8, 0})); } TEST(SwarmMasterTests, TestBreakDownAssignment) { SimpleClosestDesignator designator; SwarmMaster master(&designator); std::vector<int> robot_ids = add_buncha_robots(&master); int site_id = master.add_crate_to_system({{3,2,1}, {6,5,4}, {6,4}, 5}); std::vector<Task> true_tasks; typedef std::unordered_map<std::string, double> commandDict; true_tasks.push_back({Task::MvPlatform, commandDict{{"PlatformHeight", 0.95}}}); true_tasks.push_back({Task::Drive, commandDict{{"ToX", 0}, {"ToY", 2}, {"ToTheta", 0}}}); true_tasks.push_back({Task::Drive, commandDict{{"ToX", 5.8}, {"ToY", 4}, {"ToTheta", 270}}}); true_tasks.push_back({Task::Drive, commandDict{{"ToX", 5.8}, {"ToY", 0}, {"ToTheta", 90}}}); true_tasks.push_back({Task::MvPlatform, commandDict{{"PlatformHeight", 4}}}); true_tasks.push_back({Task::Wait, commandDict{{"AssignmentID", site_id}}}); true_tasks.push_back({Task::Drive, commandDict{{"ToX", 3}, {"ToY", 5}, {"ToTheta", 0}}}); true_tasks.push_back({Task::Drive, commandDict{{"ToX", 8.8}, {"ToY", 7}, {"ToTheta", 270}}}); true_tasks.push_back({Task::Drive, commandDict{{"ToX", 8.8}, {"ToY", 3}, {"ToTheta", 90}}}); true_tasks.push_back({Task::Wait, commandDict{{"AssignmentID", site_id}}}); true_tasks.push_back({Task::MvPlatform, commandDict{{"PlatformHeight", 3.95}}}); EXPECT_FALSE(found_element_in_vec(true_tasks, Task(Task::Wait, commandDict{}))); const auto& assignments = master.assign_robots_to_crates(); EXPECT_EQ(assignments->size(), 3); for (const auto& assignment : *assignments) { const auto& tasks = master.break_down_assignment(assignment); EXPECT_EQ(tasks->size(), 7); for (const auto& task : *tasks) { EXPECT_TRUE(found_element_in_vec(true_tasks, task)); } } } TEST(SwarmMasterTests, TestAllRobotsAtSiteWaiting) { SimpleClosestDesignator designator; SwarmMaster master(&designator); std::vector<int> site_ids{}; std::vector<int> robot_ids = add_buncha_robots(&master); site_ids.push_back(master.add_crate_to_system({{3,2,1}, {6,5,4}, {6,4}, 1})); site_ids.push_back(master.add_crate_to_system({{3,2,1}, {6,5,4}, {2,8}, 5})); auto assignments = master.assign_robots_to_crates(); std::vector<int> site1_robot_ids{}; std::vector<int> site2_robot_ids{}; for (const auto& assignment : *assignments) { if (assignment.site_id == site_ids[0]) site1_robot_ids.push_back(assignment.robot_id); else if (assignment.site_id == site_ids[1]) site2_robot_ids.push_back(assignment.robot_id); else EXPECT_TRUE(false); } EXPECT_FALSE(master.all_robots_at_site_waiting(site1_robot_ids[0]).first); EXPECT_FALSE(master.all_robots_at_site_waiting(site2_robot_ids[0]).first); EXPECT_TRUE(master.all_robots_at_site_waiting(site1_robot_ids[1]).first); EXPECT_FALSE(master.all_robots_at_site_waiting(site2_robot_ids[1]).first); EXPECT_TRUE(master.all_robots_at_site_waiting(site2_robot_ids[2]).first); } std::vector<int> add_buncha_robots(SwarmMaster* master) { std::vector<int> ret{}; ret.push_back(master->add_robot_to_swarm({1,4})); ret.push_back(master->add_robot_to_swarm({3,2})); ret.push_back(master->add_robot_to_swarm({2,3})); ret.push_back(master->add_robot_to_swarm({5,5})); ret.push_back(master->add_robot_to_swarm({10,10})); ret.push_back(master->add_robot_to_swarm({11,11})); ret.push_back(master->add_robot_to_swarm({12,12})); ret.push_back(master->add_robot_to_swarm({13,14})); ret.push_back(master->add_robot_to_swarm({10,14})); return ret; } template<class Element> bool found_element_in_vec(std::vector<Element>& pos_along_crate, Element pos) { return (std::find(pos_along_crate.begin(), pos_along_crate.end(), pos) != pos_along_crate.end()); } bool operator==(const Task& t1, const Task& t2) { bool ret = true; ret = ret && (t1.task == t2.task); ret = ret && (t1.num_param_dict == t2.num_param_dict); return ret; }
43.728155
101
0.695752
Rishabh96M
ef446128ea4cfa7c68888c8fe5ae20616dce99a9
15,534
cc
C++
src/lnav_config.cc
emilianobonassi/lnav
37f46af7a691192fba4a889e4e4da6cbfcaac8e4
[ "BSD-2-Clause" ]
null
null
null
src/lnav_config.cc
emilianobonassi/lnav
37f46af7a691192fba4a889e4e4da6cbfcaac8e4
[ "BSD-2-Clause" ]
null
null
null
src/lnav_config.cc
emilianobonassi/lnav
37f46af7a691192fba4a889e4e4da6cbfcaac8e4
[ "BSD-2-Clause" ]
null
null
null
/** * Copyright (c) 2013, Timothy Stack * * 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 Timothy Stack 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 REGENTS 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 REGENTS 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 lnav_config.cc */ #include "config.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <glob.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include "pcrecpp.h" #include "auto_fd.hh" #include "lnav_log.hh" #include "auto_mem.hh" #include "auto_pid.hh" #include "lnav_config.hh" #include "yajlpp.hh" using namespace std; static const int MAX_CRASH_LOG_COUNT = 16; extern "C" { extern const char default_config_json[]; extern const char keymap_default_json[]; } struct _lnav_config lnav_config; static struct _lnav_config lnav_default_config; lnav_config_listener *lnav_config_listener::LISTENER_LIST; string dotlnav_path(const char *sub) { string retval; char * home; home = getenv("HOME"); if (home && access(home, W_OK|X_OK) == 0) { char hpath[2048]; snprintf(hpath, sizeof(hpath), "%s/.lnav/%s", home, sub); retval = hpath; } else { retval = sub; } return retval; } bool check_experimental(const char *feature_name) { const char *env_value = getenv("LNAV_EXP"); require(feature_name != NULL); if (env_value && strcasestr(env_value, feature_name)) { return true; } return false; } void ensure_dotlnav(void) { string path = dotlnav_path(""); if (!path.empty()) { log_perror(mkdir(path.c_str(), 0755)); } path = dotlnav_path("formats"); if (!path.empty()) { log_perror(mkdir(path.c_str(), 0755)); } path = dotlnav_path("formats/installed"); if (!path.empty()) { log_perror(mkdir(path.c_str(), 0755)); } path = dotlnav_path("crash"); if (!path.empty()) { log_perror(mkdir(path.c_str(), 0755)); } lnav_log_crash_dir = strdup(path.c_str()); { static_root_mem<glob_t, globfree> gl; path += "/*"; if (glob(path.c_str(), GLOB_NOCHECK, NULL, gl.inout()) == 0) { for (int lpc = 0; lpc < ((int)gl->gl_pathc - MAX_CRASH_LOG_COUNT); lpc++) { log_perror(remove(gl->gl_pathv[lpc])); } } } path = dotlnav_path("formats/default"); if (!path.empty()) { log_perror(mkdir(path.c_str(), 0755)); } } void install_git_format(const char *repo) { static pcrecpp::RE repo_name_converter("[^\\w]"); auto_pid git_cmd(fork()); if (git_cmd.in_child()) { string formats_path = dotlnav_path("formats/"); string local_name = repo; string local_path; repo_name_converter.GlobalReplace("_", &local_name); local_path = formats_path + local_name; if (access(local_path.c_str(), R_OK) == 0) { printf("Updating format repo: %s\n", repo); log_perror(chdir(local_path.c_str())); execlp("git", "git", "pull", NULL); } else { execlp("git", "git", "clone", repo, local_path.c_str(), NULL); } _exit(1); } git_cmd.wait_for_child(); } static int read_repo_path(yajlpp_parse_context *ypc, const unsigned char *str, size_t len) { string path = string((const char *)str, len); install_git_format(path.c_str()); return 1; } static struct json_path_handler format_handlers[] = { json_path_handler("/format-repos#", read_repo_path), json_path_handler() }; void install_extra_formats() { string config_root = dotlnav_path("remote-config"); auto_fd fd; if (access(config_root.c_str(), R_OK) == 0) { char pull_cmd[1024]; printf("Updating lnav remote config repo...\n"); snprintf(pull_cmd, sizeof(pull_cmd), "cd '%s' && git pull", config_root.c_str()); log_perror(system(pull_cmd)); } else { char clone_cmd[1024]; printf("Cloning lnav remote config repo...\n"); snprintf(clone_cmd, sizeof(clone_cmd), "git clone https://github.com/tstack/lnav-config.git %s", config_root.c_str()); log_perror(system(clone_cmd)); } string config_json = config_root + "/remote-config.json"; if ((fd = open(config_json.c_str(), O_RDONLY)) == -1) { perror("Unable to open remote-config.json"); } else { yajlpp_parse_context ypc_config(config_root, format_handlers); auto_mem<yajl_handle_t> jhandle(yajl_free); unsigned char buffer[4096]; ssize_t rc; jhandle = yajl_alloc(&ypc_config.ypc_callbacks, NULL, &ypc_config); yajl_config(jhandle, yajl_allow_comments, 1); while ((rc = read(fd, buffer, sizeof(buffer))) > 0) { if (yajl_parse(jhandle, buffer, rc) != yajl_status_ok) { fprintf(stderr, "Unable to parse remote-config.json -- %s", yajl_get_error(jhandle, 1, buffer, rc)); return; } } if (yajl_complete_parse(jhandle) != yajl_status_ok) { fprintf(stderr, "Unable to parse remote-config.json -- %s", yajl_get_error(jhandle, 1, buffer, rc)); } } } struct userdata { userdata(vector<string> &errors) : ud_errors(errors) {}; vector<string> &ud_errors; }; static struct json_path_handler keymap_def_handlers[] = { json_path_handler("(?<key_seq>(x[0-9a-f]{2})+)#") .with_synopsis("<command>") .with_description("The command to execute for the given key sequence") .with_pattern("[:|;].*") .with_path_provider<key_map>([](key_map *km, vector<string> &paths_out) { for (const auto &iter : km->km_seq_to_cmd) { paths_out.push_back(iter.first); } }) .for_field(&nullobj<key_map>()->km_seq_to_cmd), json_path_handler() }; static struct json_path_handler keymap_defs_handlers[] = { json_path_handler("(?<key_map_name>[^/]+)/") .with_synopsis("<name>") .with_description("The command to execute for the given key sequence") .with_obj_provider<key_map, _lnav_config>([](const yajlpp_provider_context &ypc, _lnav_config *root) { key_map &retval = root->lc_ui_keymaps[ypc.ypc_extractor.get_substr("key_map_name")]; return &retval; }) .with_path_provider<_lnav_config>([](struct _lnav_config *cfg, vector<string> &paths_out) { for (const auto &iter : cfg->lc_ui_keymaps) { paths_out.push_back(iter.first); } }) .with_children(keymap_def_handlers), json_path_handler() }; static struct json_path_handler global_var_handlers[] = { json_path_handler("(?<var_name>\\w+)") .with_synopsis("<name>") .with_description("A global variable definition") .with_path_provider<_lnav_config>([](struct _lnav_config *cfg, vector<string> &paths_out) { for (const auto &iter : cfg->lc_global_vars) { paths_out.push_back(iter.first); } }) .for_field(&nullobj<_lnav_config>()->lc_global_vars), json_path_handler() }; static struct json_path_handler root_config_handlers[] = { json_path_handler("/keymap_def/") .with_children(keymap_defs_handlers), json_path_handler("/global/") .with_children(global_var_handlers), json_path_handler() }; static struct json_path_handler ui_handlers[] = { json_path_handler("clock-format") .with_synopsis("<format>") .with_description( "The format for the clock displayed in " "the top-left corner using strftime(3) conversions") .for_field(&nullobj<_lnav_config>()->lc_ui_clock_format), json_path_handler("dim-text") .with_synopsis("<bool>") .with_description("Reduce the brightness of text (useful for xterms)") .for_field(&nullobj<_lnav_config>()->lc_ui_dim_text), json_path_handler("default-colors") .with_synopsis("<bool>") .with_description("Use default terminal fg/bg colors") .for_field(&nullobj<_lnav_config>()->lc_ui_default_colors), json_path_handler("keymap") .with_synopsis("<name>") .with_description("The name of the keymap to use") .for_field(&nullobj<_lnav_config>()->lc_ui_keymap), json_path_handler() }; struct json_path_handler lnav_config_handlers[] = { json_path_handler("/ui/") .with_children(ui_handlers), json_path_handler() }; static void load_config_from(const string &path, vector<string> &errors) { yajlpp_parse_context ypc(path, lnav_config_handlers); struct userdata ud(errors); auto_fd fd; ypc.with_obj(lnav_config); ypc.ypc_userdata = &ud; if ((fd = open(path.c_str(), O_RDONLY)) == -1) { if (errno != ENOENT) { char errmsg[1024]; snprintf(errmsg, sizeof(errmsg), "error: unable to open format file -- %s", path.c_str()); errors.push_back(errmsg); } } else { auto_mem<yajl_handle_t> handle(yajl_free); char buffer[2048]; off_t offset = 0; ssize_t rc = -1; handle = yajl_alloc(&ypc.ypc_callbacks, NULL, &ypc); yajl_config(handle, yajl_allow_comments, 1); while (true) { rc = read(fd, buffer, sizeof(buffer)); if (rc == 0) { break; } else if (rc == -1) { errors.push_back(path + ":unable to read file -- " + string(strerror(errno))); break; } if (yajl_parse(handle, (const unsigned char *)buffer, rc) != yajl_status_ok) { errors.push_back(path + ": invalid json -- " + string((char *)yajl_get_error(handle, 1, (unsigned char *)buffer, rc))); break; } offset += rc; } if (rc == 0) { if (yajl_complete_parse(handle) != yajl_status_ok) { errors.push_back(path + ": invalid json -- " + string((char *)yajl_get_error(handle, 0, NULL, 0))); } } } } static void load_default_config(yajlpp_parse_context &ypc_builtin, struct _lnav_config &config_obj, const char *config_json, vector<string> &errors) { auto_mem<yajl_handle_t> handle(yajl_free); struct userdata ud(errors); handle = yajl_alloc(&ypc_builtin.ypc_callbacks, NULL, &ypc_builtin); ypc_builtin.with_obj(config_obj); ypc_builtin.ypc_userdata = &ud; yajl_config(handle, yajl_allow_comments, 1); if (yajl_parse(handle, (const unsigned char *) config_json, strlen(config_json)) != yajl_status_ok) { errors.push_back("builtin: invalid json -- " + string((char *)yajl_get_error(handle, 1, (unsigned char *) config_json, strlen(config_json)))); } yajl_complete_parse(handle); } void load_config(const vector<string> &extra_paths, vector<string> &errors) { string user_config = dotlnav_path("config.json"); { yajlpp_parse_context ypc_builtin("keymap", root_config_handlers); load_default_config(ypc_builtin, lnav_config, keymap_default_json, errors); } { yajlpp_parse_context ypc_builtin("builtin", lnav_config_handlers); ypc_builtin.reset(lnav_config_handlers); load_default_config(ypc_builtin, lnav_default_config, default_config_json, errors); ypc_builtin.reset(lnav_config_handlers); load_default_config(ypc_builtin, lnav_config, default_config_json, errors); load_config_from(user_config, errors); } reload_config(); } void reset_config(const std::string &path) { yajlpp_parse_context ypc_builtin("builtin", lnav_config_handlers); vector<string> errors; if (path != "*") { ypc_builtin.ypc_ignore_unused = true; ypc_builtin.ypc_active_paths.insert(path); } load_default_config(ypc_builtin, lnav_config, default_config_json, errors); } string save_config() { auto_mem<yajl_gen_t> handle(yajl_gen_free); if ((handle = yajl_gen_alloc(NULL)) == NULL) { return "error: Unable to create yajl_gen_object"; } else { char filename[128]; snprintf(filename, sizeof(filename), "config.json.%d.tmp", getpid()); string user_config_tmp = dotlnav_path(filename); string user_config = dotlnav_path("config.json"); yajl_gen_config(handle, yajl_gen_beautify, true); yajlpp_gen_context ygc(handle, lnav_config_handlers); vector<string> errors; ygc.with_default_obj(lnav_default_config) .with_obj(lnav_config); ygc.gen(); const unsigned char *buffer; size_t len; yajl_gen_get_buf(handle, &buffer, &len); { auto_fd fd; if ((fd = open(user_config_tmp.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0600)) == -1) { return "error: unable to save configuration -- " + string(strerror(errno)); } else { log_perror(write(fd, buffer, len)); } } rename(user_config_tmp.c_str(), user_config.c_str()); } return "info: configuration saved"; } void reload_config() { lnav_config_listener *curr = lnav_config_listener::LISTENER_LIST; while (curr != NULL) { curr->reload_config(); curr = curr->lcl_next; } }
31.318548
120
0.604094
emilianobonassi
ef5239b8da270f13ec2e6cbbe3fe961b3a642826
1,782
hh
C++
sdf/include/ignition/physics/sdf/ConstructModel.hh
diegoferigo/ign-physics
8f0d8ce3229f53fbf4e05cb0273530169e6d9fef
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
sdf/include/ignition/physics/sdf/ConstructModel.hh
diegoferigo/ign-physics
8f0d8ce3229f53fbf4e05cb0273530169e6d9fef
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
sdf/include/ignition/physics/sdf/ConstructModel.hh
diegoferigo/ign-physics
8f0d8ce3229f53fbf4e05cb0273530169e6d9fef
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2018 Open Source Robotics 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. * */ #ifndef IGNITION_PHYSICS_SDF_CONSTRUCTMODEL_HH_ #define IGNITION_PHYSICS_SDF_CONSTRUCTMODEL_HH_ #include <sdf/Model.hh> #include <ignition/physics/FeatureList.hh> namespace ignition { namespace physics { namespace sdf { class ConstructSdfModel : public virtual Feature { public: template <typename PolicyT, typename FeaturesT> class World : public virtual Feature::World<PolicyT, FeaturesT> { public: using ModelPtrType = ModelPtr<PolicyT, FeaturesT>; public: ModelPtrType ConstructModel(const ::sdf::Model &_model); }; public: template <typename PolicyT> class Implementation : public virtual Feature::Implementation<PolicyT> { public: virtual Identity ConstructSdfModel( const Identity &_world, const ::sdf::Model &_model) = 0; }; }; ///////////////////////////////////////////////// template <typename PolicyT, typename FeaturesT> auto ConstructSdfModel::World<PolicyT, FeaturesT>::ConstructModel( const ::sdf::Model &_model) -> ModelPtrType { return ModelPtrType(this->pimpl, this->template Interface<ConstructSdfModel>() ->ConstructSdfModel(this->identity, _model)); } } } } #endif
28.741935
75
0.718294
diegoferigo
ef5590bd8a78f98a555517dd3bb0d7fc0fa5ffdd
9,397
hpp
C++
minimal_sdk/public/istudiorender.hpp
vocweb/cso2-launcher
abc144acaa3dfb5b0c9acd61cd75970cac012617
[ "MIT" ]
55
2018-09-01T17:52:17.000Z
2019-09-23T10:30:49.000Z
minimal_sdk/public/istudiorender.hpp
RedheatWei/cso2-launcher
4cebbb98d51d33bd24c9a86a1d3fc311686d5011
[ "MIT" ]
70
2018-08-22T05:53:34.000Z
2019-09-23T15:11:39.000Z
minimal_sdk/public/istudiorender.hpp
RedheatWei/cso2-launcher
4cebbb98d51d33bd24c9a86a1d3fc311686d5011
[ "MIT" ]
39
2018-09-01T21:42:50.000Z
2019-09-23T18:38:07.000Z
#pragma once #include "appframework/iappsystem.hpp" #include "datacache/imdlcache.hpp" class CUtlBuffer; class IMaterial; class IMaterialSystem; class ITexture; class Vector; class Vector4D; class VMatrix; struct FlashlightState_t; struct LightDesc_t; struct Ray_t; struct studiohdr_t; struct studiohwdata_t; struct matrix3x4_t; struct vertexFileHeader_t; struct DrawModelResults_t; struct DrawModelInfo_t; struct GetTriangles_Output_t; struct model_array_instance_t; struct StudioRenderConfig_t; typedef struct { int unused; } * StudioDecalHandle_t; #define STUDIORENDER_DECAL_INVALID ( (StudioDecalHandle_t)0 ) enum { ADDDECAL_TO_ALL_LODS = -1 }; enum { STUDIORENDER_DRAW_ENTIRE_MODEL = 0, STUDIORENDER_DRAW_OPAQUE_ONLY = 0x01, STUDIORENDER_DRAW_TRANSLUCENT_ONLY = 0x02, STUDIORENDER_DRAW_GROUP_MASK = 0x03, STUDIORENDER_DRAW_NO_FLEXES = 0x04, STUDIORENDER_DRAW_STATIC_LIGHTING = 0x08, STUDIORENDER_DRAW_ACCURATETIME = 0x10, // Use accurate timing when drawing the model. STUDIORENDER_DRAW_NO_SHADOWS = 0x20, STUDIORENDER_DRAW_GET_PERF_STATS = 0x40, STUDIORENDER_DRAW_WIREFRAME = 0x80, STUDIORENDER_DRAW_ITEM_BLINK = 0x100, STUDIORENDER_SHADOWDEPTHTEXTURE = 0x200, STUDIORENDER_SSAODEPTHTEXTURE = 0x1000, STUDIORENDER_GENERATE_STATS = 0x8000, }; enum OverrideType_t { OVERRIDE_NORMAL = 0, OVERRIDE_BUILD_SHADOWS, OVERRIDE_DEPTH_WRITE, OVERRIDE_SSAO_DEPTH_WRITE, }; constexpr const char* STUDIO_DATA_CACHE_INTERFACE_VERSION = "VStudioDataCache005"; class IStudioDataCache : public IAppSystem { public: virtual bool VerifyHeaders( studiohdr_t* pStudioHdr ) = 0; virtual vertexFileHeader_t* CacheVertexData( studiohdr_t* pStudioHdr ) = 0; }; constexpr const char* STUDIO_RENDER_INTERFACE_VERSION = "VStudioRender025"; class IStudioRender : public IAppSystem { public: virtual void BeginFrame() = 0; virtual void EndFrame() = 0; // Used for the mat_stub console command. virtual void Mat_Stub( IMaterialSystem* pMatSys ) = 0; // Updates the rendering configuration virtual void UpdateConfig( const StudioRenderConfig_t& config ) = 0; virtual void GetCurrentConfig( StudioRenderConfig_t& config ) = 0; // Load, unload model data virtual bool LoadModel( studiohdr_t* pStudioHdr, void* pVtxData, studiohwdata_t* pHardwareData ) = 0; virtual void UnloadModel( studiohwdata_t* pHardwareData ) = 0; // Refresh the studiohdr since it was lost... virtual void RefreshStudioHdr( studiohdr_t* pStudioHdr, studiohwdata_t* pHardwareData ) = 0; // This is needed to do eyeglint and calculate the correct texcoords for the // eyes. virtual void SetEyeViewTarget( const studiohdr_t* pStudioHdr, int nBodyIndex, const Vector& worldPosition ) = 0; // Methods related to lighting state // NOTE: SetAmbientLightColors assumes that the arraysize is the same as // returned from GetNumAmbientLightSamples virtual int GetNumAmbientLightSamples() = 0; virtual const Vector* GetAmbientLightDirections() = 0; virtual void SetAmbientLightColors( const Vector4D* pAmbientOnlyColors ) = 0; virtual void SetAmbientLightColors( const Vector* pAmbientOnlyColors ) = 0; virtual void SetLocalLights( int numLights, const LightDesc_t* pLights ) = 0; // Sets information about the camera location + orientation virtual void SetViewState( const Vector& viewOrigin, const Vector& viewRight, const Vector& viewUp, const Vector& viewPlaneNormal ) = 0; // Allocates flex weights for use in rendering // NOTE: Pass in a non-null second parameter to lock delayed flex weights virtual void LockFlexWeights( int nWeightCount, float** ppFlexWeights, float** ppFlexDelayedWeights = nullptr ) = 0; virtual void UnlockFlexWeights() = 0; // Used to allocate bone matrices to be used to pass into DrawModel virtual matrix3x4_t* LockBoneMatrices( int nBoneCount ) = 0; virtual void UnlockBoneMatrices() = 0; // LOD stuff virtual int GetNumLODs( const studiohwdata_t& hardwareData ) const = 0; virtual float GetLODSwitchValue( const studiohwdata_t& hardwareData, int lod ) const = 0; virtual void SetLODSwitchValue( studiohwdata_t& hardwareData, int lod, float switchValue ) = 0; // Sets the color/alpha modulation virtual void SetColorModulation( float const* pColor ) = 0; virtual void SetAlphaModulation( float flAlpha ) = 0; // Draws the model virtual void DrawModel( DrawModelResults_t* pResults, const DrawModelInfo_t& info, matrix3x4_t* pBoneToWorld, float* pFlexWeights, float* pFlexDelayedWeights, const Vector& modelOrigin, int flags = STUDIORENDER_DRAW_ENTIRE_MODEL ) = 0; // Methods related to static prop rendering virtual void DrawModelStaticProp( const DrawModelInfo_t& drawInfo, const matrix3x4_t& modelToWorld, int flags = STUDIORENDER_DRAW_ENTIRE_MODEL ) = 0; virtual void DrawStaticPropDecals( const DrawModelInfo_t& drawInfo, const matrix3x4_t& modelToWorld ) = 0; virtual void DrawStaticPropShadows( const DrawModelInfo_t& drawInfo, const matrix3x4_t& modelToWorld, int flags ) = 0; // Causes a material to be used instead of the materials the model was // compiled with virtual void ForcedMaterialOverride( IMaterial* newMaterial, OverrideType_t nOverrideType = OVERRIDE_NORMAL ) = 0; // Create, destroy list of decals for a particular model virtual StudioDecalHandle_t CreateDecalList( studiohwdata_t* pHardwareData ) = 0; virtual void DestroyDecalList( StudioDecalHandle_t handle ) = 0; // Add decals to a decal list by doing a planar projection along the ray // The BoneToWorld matrices must be set before this is called virtual void AddDecal( StudioDecalHandle_t handle, studiohdr_t* pStudioHdr, matrix3x4_t* pBoneToWorld, const Ray_t& ray, const Vector& decalUp, IMaterial* pDecalMaterial, float radius, int body, bool noPokethru = false, int maxLODToDecal = ADDDECAL_TO_ALL_LODS ) = 0; // Compute the lighting at a point and normal virtual void ComputeLighting( const Vector* pAmbient, int lightCount, LightDesc_t* pLights, const Vector& pt, const Vector& normal, Vector& lighting ) = 0; // Compute the lighting at a point, constant directional component is passed // as flDirectionalAmount virtual void ComputeLightingConstDirectional( const Vector* pAmbient, int lightCount, LightDesc_t* pLights, const Vector& pt, const Vector& normal, Vector& lighting, float flDirectionalAmount ) = 0; // Shadow state (affects the models as they are rendered) virtual void AddShadow( IMaterial* pMaterial, void* pProxyData, FlashlightState_t* m_pFlashlightState = nullptr, VMatrix* pWorldToTexture = nullptr, ITexture* pFlashlightDepthTexture = nullptr ) = 0; virtual void ClearAllShadows() = 0; // Gets the model LOD; pass in the screen size in pixels of a sphere // of radius 1 that has the same origin as the model to get the LOD out... virtual int ComputeModelLod( studiohwdata_t* pHardwareData, float unitSphereSize, float* pMetric = nullptr ) = 0; // Return a number that is usable for budgets, etc. // Things that we care about: // 1) effective triangle count (factors in batch sizes, state changes, etc) // 2) texture memory usage // Get Triangles returns the LOD used virtual void GetPerfStats( DrawModelResults_t* pResults, const DrawModelInfo_t& info, CUtlBuffer* pSpewBuf = nullptr ) const = 0; virtual void GetTriangles( const DrawModelInfo_t& info, matrix3x4_t* pBoneToWorld, GetTriangles_Output_t& out ) = 0; // Returns materials used by a particular model virtual int GetMaterialList( studiohdr_t* pStudioHdr, int count, IMaterial** ppMaterials ) = 0; virtual int GetMaterialListFromBodyAndSkin( MDLHandle_t studio, int nSkin, int nBody, int nCountOutputMaterials, IMaterial** ppOutputMaterials ) = 0; // draw an array of models with the same state virtual void DrawModelArray( const DrawModelInfo_t& drawInfo, int arrayCount, model_array_instance_t* pInstanceData, int instanceStride, int flags = STUDIORENDER_DRAW_ENTIRE_MODEL ) = 0; }; extern IStudioRender* g_pStudioRender;
39.317992
80
0.663403
vocweb
ef5c883a19f150c37e50bc0362fdaa740982e9a2
3,805
cpp
C++
src/examples/exampleVectorProcessor.cpp
elinjammal/opensmile
0ae2da44e61744ff1aaa9bae2b95d747febb08de
[ "W3C" ]
245
2020-10-24T16:27:13.000Z
2022-03-31T03:01:11.000Z
src/examples/exampleVectorProcessor.cpp
elinjammal/opensmile
0ae2da44e61744ff1aaa9bae2b95d747febb08de
[ "W3C" ]
41
2021-01-13T11:30:42.000Z
2022-01-14T14:36:11.000Z
src/examples/exampleVectorProcessor.cpp
elinjammal/opensmile
0ae2da44e61744ff1aaa9bae2b95d747febb08de
[ "W3C" ]
43
2020-12-11T15:28:19.000Z
2022-03-20T11:55:58.000Z
/*F*************************************************************************** * This file is part of openSMILE. * * Copyright (c) audEERING GmbH. All rights reserved. * See the file COPYING for details on license terms. ***************************************************************************E*/ /* openSMILE component: example of a vector processor */ #include <examples/exampleVectorProcessor.hpp> #define MODULE "cExampleVectorProcessor" SMILECOMPONENT_STATICS(cExampleVectorProcessor) SMILECOMPONENT_REGCOMP(cExampleVectorProcessor) { SMILECOMPONENT_REGCOMP_INIT scname = COMPONENT_NAME_CEXAMPLEVECTORPROCESSOR; sdescription = COMPONENT_DESCRIPTION_CEXAMPLEVECTORPROCESSOR; // we inherit cVectorProcessor configType and extend it: SMILECOMPONENT_INHERIT_CONFIGTYPE("cVectorProcessor") // if the inherited config type was found, we register our configuration variables SMILECOMPONENT_IFNOTREGAGAIN( {} // <- this is only to avoid compiler warnings... // name append has a special role: it is defined in cDataProcessor, and can be overwritten here: // if you set description to NULL, the existing description will be used, thus the following call can // be used to update the default value: //ct->setField("nameAppend",NULL,"processed"); // this is an example for adding an integer option: //ct->setField("inverse","1 = perform inverse FFT",0); ) // The configType gets automatically registered with the config manger by the SMILECOMPONENT_IFNOTREGAGAIN macro // we now create out sComponentInfo, including name, description, success status, etc. and return that SMILECOMPONENT_MAKEINFO(cExampleVectorProcessor); } SMILECOMPONENT_CREATE(cExampleVectorProcessor) //----- cExampleVectorProcessor::cExampleVectorProcessor(const char *_name) : cVectorProcessor(_name) { } void cExampleVectorProcessor::myFetchConfig() { cVectorProcessor::myFetchConfig(); /* inverse = getInt("inverse"); if (inverse) { SMILE_IDBG(2,"transformFFT set for inverse FFT",inverse); inverse = 1; // sign of exponent } else { inverse = -1; // sign of exponent } */ } /* int cExampleVectorProcessor::myConfigureInstance() { int ret=1; ret *= cVectorProcessor::myConfigureInstance(); if (ret == 0) return 0; //... return ret; } */ /* int cExampleVectorProcessor::configureWriter(const sDmLevelConfig *c) { // you must return 1, in order to indicate configure success (0 indicated failure) return 1; } */ // optional /* int cExampleVectorProcessor::setupNamesForField(int i, const char*name, long nEl) { return cVectorProcessor::setupNamesForField(i,name,nEl); } */ // use this to allocate data like filter coefficient arrays, etc... void cExampleVectorProcessor::configureField(int idxi, long __N, long nOut) { // const sDmLevelConfig *c = reader->getLevelConfig(); // idxc = getFconf(idxi); } /* int cExampleVectorProcessor::myFinaliseInstance() { int ret=1; ret *= cVectorProcessor::myFinaliseInstance(); //..... return ret; } */ // a derived class should override this method, in order to implement the actual processing int cExampleVectorProcessor::processVectorInt(const INT_DMEM *src, INT_DMEM *dst, long Nsrc, long Ndst, int idxi) // idxi=input field index { // do domething to data in *src, save result to *dst // NOTE: *src and *dst may be the same... return 1; } // a derived class should override this method, in order to implement the actual processing int cExampleVectorProcessor::processVectorFloat(const FLOAT_DMEM *src, FLOAT_DMEM *dst, long Nsrc, long Ndst, int idxi) // idxi=input field index { // do domething to data in *src, save result to *dst // NOTE: *src and *dst may be the same... return 1; } cExampleVectorProcessor::~cExampleVectorProcessor() { }
25.709459
145
0.708279
elinjammal
ef5dc8eff51fa298192f4e9d541f7214aa0063dc
11,929
cpp
C++
lib/TextInput.cpp
idigdoug/TextTools
3cc9b5867b938eebf78bd85f794d3ce8feaae4f3
[ "MIT" ]
null
null
null
lib/TextInput.cpp
idigdoug/TextTools
3cc9b5867b938eebf78bd85f794d3ce8feaae4f3
[ "MIT" ]
null
null
null
lib/TextInput.cpp
idigdoug/TextTools
3cc9b5867b938eebf78bd85f794d3ce8feaae4f3
[ "MIT" ]
null
null
null
// Copyright (c) Doug Cook. // Licensed under the MIT License. #include "pch.h" #include <TextInput.h> #include <CodePageInfo.h> #include "ByteOrderMark.h" #include "Utility.h" #include <stdexcept> #include <assert.h> #include <stdio.h> using namespace TextToolsImpl; static constexpr unsigned ReadMax = 0x1fffffff; // Max value to be used in ReadFile or ReadConsole. static constexpr unsigned FileBufferSize = 4096; static constexpr unsigned ConsoleBufferSize = 2048; constexpr bool TextInput::IsFlagSet(TextInputFlags flag) const noexcept { return (m_flags & flag) != TextInputFlags::None; } void TextInput::SetCodeConvert(unsigned codePage) { CodeConvert codeConvert(codePage); codeConvert.ThrowIfNotSupported(); m_codeConvert = codeConvert; } void TextInput::FoldCRLF() noexcept { assert(m_charsPos <= m_chars.size()); if (!IsFlagSet(TextInputFlags::FoldCRLF) || m_charsPos == 0) { return; } bool const skipNextCharIfNewline = m_skipNextCharIfNewline; m_skipNextCharIfNewline = false; auto const pChars = m_chars.data(); size_t iInput, iOutput; if (skipNextCharIfNewline && pChars[0] == L'\n') { // Last chunk ended on "\r", which we converted to "\n". // This chunk starts with "\n", so it was a "\r\n" sequence. // We already wrote the corresponding "\n" so skip it. iInput = 1; iOutput = 0; } else { auto const pFirstCR = (char16_t*)wmemchr((WCHAR*)pChars, L'\r', m_charsPos); if (!pFirstCR) { // If there is nothing to skip or convert, we're done. return; } iInput = pFirstCR - pChars; iOutput = iInput; } for (; iInput != m_charsPos; iInput += 1) { auto const ch = pChars[iInput]; if (ch != L'\r') { pChars[iOutput++] = ch; } else if (iInput + 1 == m_charsPos) { // "\r" at end of chunk. Assume lone "\r" and convert it to "\n". // If next chunk starts with "\n" we will need to skip it. m_skipNextCharIfNewline = true; pChars[iOutput++] = L'\n'; break; } else if (pChars[iInput + 1] != L'\n') { // Lone "\r", convert to "\n". pChars[iOutput++] = L'\n'; } else { // "\r\n" sequence, ignore the "\r". } } m_charsPos = iOutput; } void TextInput::ConsumeBytes(size_t consumedBytes) noexcept { if (consumedBytes >= m_bytesPos) { assert(consumedBytes == m_bytesPos); m_bytesPos = 0; } else if (consumedBytes != 0) { m_bytesPos -= consumedBytes; memmove(m_bytes.data(), m_bytes.data() + consumedBytes, m_bytesPos); } } void TextInput::Convert() { assert(m_mode == TextInputMode::Bytes || m_mode == TextInputMode::File); assert(m_bytesPos <= m_bytes.size()); m_charsPos = 0; size_t consumedBytes = 0; LSTATUS status = m_codeConvert.EncodedToUtf16( std::string_view(m_bytes.data(), m_bytesPos), consumedBytes, m_chars, m_charsPos, IsFlagSet(TextInputFlags::InvalidMbcsError) ? MB_ERR_INVALID_CHARS : 0); ConsumeBytes(consumedBytes); FoldCRLF(); if (status != ERROR_SUCCESS) { if (status == ERROR_NO_UNICODE_TRANSLATION) { throw std::range_error("Input is not valid for encoding " + std::to_string(m_codeConvert.CodePage()) + "."); } else { throw std::runtime_error("MBCS-to-UTF16 conversion error " + std::to_string(status) + "."); } } } void TextInput::ReadBytesFromFile() { auto const cbRemainingBuffer = m_bytes.size() - m_bytesPos; ReadBytesFromFile(cbRemainingBuffer < ReadMax ? (DWORD)cbRemainingBuffer : ReadMax); } void TextInput::ReadBytesFromFile(DWORD cbMaxToRead) { assert(m_inputHandle); assert(m_bytes.size() > m_bytesPos); assert(m_bytes.size() - m_bytesPos >= cbMaxToRead); DWORD cbRead = 0; if (!ReadFile(m_inputHandle, m_bytes.data() + m_bytesPos, cbMaxToRead, &cbRead, nullptr)) { auto lastError = GetLastError(); if (lastError != ERROR_BROKEN_PIPE) { throw std::runtime_error("ReadFile error " + std::to_string(lastError)); } } m_bytesPos += cbRead; if (cbRead == 0) { m_inputOwner.reset(); m_inputHandle = nullptr; } } void TextInput::ReadCharsFromConsole() { assert(m_inputHandle); assert(ConsoleBufferSize <= m_chars.size()); assert(m_charsPos == 0); CONSOLE_READCONSOLE_CONTROL control = {}; control.nLength = sizeof(control); control.dwCtrlWakeupMask = IsFlagSet(TextInputFlags::ConsoleCtrlZ) ? 1u << 26 : 0u; DWORD const cchMaxToRead = m_chars.size() < ReadMax ? (DWORD)m_chars.size() : ReadMax; DWORD cchRead = 0; if (!ReadConsoleW(m_inputHandle, m_chars.data(), cchMaxToRead, &cchRead, &control)) { auto lastError = GetLastError(); throw std::runtime_error("ReadConsoleW error " + std::to_string(lastError)); } m_charsPos = cchRead; if (cchRead == 0) { m_inputOwner.reset(); m_inputHandle = nullptr; } } void TextInput::OpenHandle( TextToolsUniqueHandle inputOwner, _In_ HANDLE inputHandle, unsigned codePage, TextInputFlags flags) { auto const fileType = GetFileType(inputHandle); if (fileType == FILE_TYPE_UNKNOWN) { auto lastError = GetLastError(); if (lastError != ERROR_SUCCESS) { throw std::runtime_error("GetFileType error " + std::to_string(lastError)); } } Close(); // Note: Even if the text ends up having a BOM or Console, we want to validate the codePage parameter. SetCodeConvert(codePage); m_mode = TextInputMode::File; m_flags = flags; m_inputOwner = std::move(inputOwner); m_inputHandle = inputHandle; if (IsFlagSet(TextInputFlags::CheckConsole) && fileType == FILE_TYPE_CHAR) { DWORD consoleMode; if (GetConsoleMode(m_inputHandle, &consoleMode)) { EnsureSize(m_chars, ConsoleBufferSize); m_codeConvert = CodeConvert(CodePageUtf16LE); m_mode = TextInputMode::Console; goto Done; // Note: Don't consume BOM from console. } } EnsureSize(m_bytes, FileBufferSize); if (IsFlagSet(TextInputFlags::ConsumeBom)) { ReadBytesFromFile(4); for (auto& bomInfo : ByteOrderMark::Standard) { for (;;) { auto match = bomInfo.Match({ m_bytes.data(), m_bytesPos }); if (match == ByteOrderMatch::Yes) { ConsumeBytes(bomInfo.Size); m_codeConvert = CodeConvert(bomInfo.CodePage); goto Done; } else if (match == ByteOrderMatch::No) { break; } else if (!m_inputHandle) { // NeedMoreData but EOF. Don't goto Done. Consider a 2-byte file with // UTF16 BOM. UTF32 will want more data but we want UTF16 to match. break; } else { assert(bomInfo.Size > m_bytesPos); ReadBytesFromFile(bomInfo.Size - (DWORD)m_bytesPos); } } } } Done: ReadNextChars(); return; } TextInput::TextInput() noexcept : m_bytes() , m_chars() , m_inputOwner() , m_inputHandle() , m_codeConvert() , m_mode() , m_flags() , m_skipNextCharIfNewline() , m_bytesPos() , m_charsPos() { return; } void TextInput::Close() noexcept { m_inputOwner.reset(); m_inputHandle = {}; m_codeConvert = {}; m_mode = {}; m_flags = {}; m_skipNextCharIfNewline = {}; m_bytesPos = {}; m_charsPos = {}; } TextInputMode TextInput::Mode() const noexcept { return m_mode; } void TextInput::OpenChars( std::u16string_view inputChars, TextInputFlags flags) { Close(); m_codeConvert = CodeConvert(CodePageUtf16LE); m_mode = TextInputMode::Chars; m_flags = flags; if (IsFlagSet(TextInputFlags::ConsumeBom) && inputChars.starts_with(u'\xFEFF')) { inputChars.remove_prefix(1); } EnsureSize(m_chars, inputChars.size()); memcpy(m_chars.data(), inputChars.data(), inputChars.size() * sizeof(char16_t)); m_charsPos = inputChars.size(); FoldCRLF(); } void TextInput::OpenBytes( std::string_view inputBytes, unsigned codePage, TextInputFlags flags) { Close(); // Note: Even if the text ends up having a BOM or Console, we want to validate the codePage parameter. SetCodeConvert(codePage); m_mode = TextInputMode::Bytes; m_flags = flags; size_t consumedBytes = 0; if (IsFlagSet(TextInputFlags::ConsumeBom)) { for (auto& bomInfo : ByteOrderMark::Standard) { if (bomInfo.Match(inputBytes) == ByteOrderMatch::Yes) { m_codeConvert = CodeConvert(bomInfo.CodePage); consumedBytes = bomInfo.Size; break; } } } LSTATUS status = m_codeConvert.EncodedToUtf16( inputBytes, consumedBytes, m_chars, m_charsPos, IsFlagSet(TextInputFlags::InvalidMbcsError) ? MB_ERR_INVALID_CHARS : 0); FoldCRLF(); // Copy any bytes that we couldn't convert. EnsureSize(m_bytes, inputBytes.size() - consumedBytes); memcpy(m_bytes.data(), inputBytes.data() + consumedBytes, inputBytes.size() - consumedBytes); m_bytesPos = inputBytes.size() - consumedBytes; if (status != ERROR_SUCCESS) { throw std::range_error("Conversion error " + std::to_string(status)); } } void TextInput::OpenBorrowedHandle( _In_ HANDLE inputHandle, unsigned codePage, TextInputFlags flags) { OpenHandle({}, inputHandle, codePage, flags); } LSTATUS TextInput::OpenFile( _In_ PCWSTR inputFile, unsigned codePage, TextInputFlags flags) { LSTATUS status; HANDLE const inputHandle = CreateFileW( inputFile, FILE_READ_DATA, FILE_SHARE_READ | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, nullptr); if (inputHandle == INVALID_HANDLE_VALUE) { status = GetLastError(); } else { OpenHandle(TextToolsUniqueHandle(inputHandle), inputHandle, codePage, flags); status = ERROR_SUCCESS; } return status; } std::u16string_view TextInput::Chars() const noexcept { return { m_chars.data(), m_charsPos }; } bool TextInput::ReadNextChars() { assert(m_mode != TextInputMode::None); m_charsPos = 0; if (m_mode == TextInputMode::Console) { while (m_inputHandle && m_charsPos == 0) { ReadCharsFromConsole(); FoldCRLF(); } } else { while (m_inputHandle && m_charsPos == 0) { ReadBytesFromFile(); Convert(); } } return m_charsPos != 0; }
25.598712
107
0.568614
idigdoug
ef61c26742b4568325930bfe82517150ccbc08e4
5,265
hh
C++
src/game/resources.hh
nilium/snow
296466e49fd5ebd8d4d40dbf96b14903daa705a8
[ "Zlib", "BSD-2-Clause" ]
4
2015-10-01T20:10:20.000Z
2021-08-28T23:43:33.000Z
src/game/resources.hh
nilium/snow
296466e49fd5ebd8d4d40dbf96b14903daa705a8
[ "Zlib", "BSD-2-Clause" ]
null
null
null
src/game/resources.hh
nilium/snow
296466e49fd5ebd8d4d40dbf96b14903daa705a8
[ "Zlib", "BSD-2-Clause" ]
null
null
null
/* resources.hh -- Copyright (c) 2013 Noel Cower. All rights reserved. See COPYING under the project root for the source code license. If this file is not present, refer to <https://raw.github.com/nilium/snow/master/COPYING>. */ #ifndef __SNOW__RESOURCES_HH__ #define __SNOW__RESOURCES_HH__ #include "../config.hh" #include "../ext/lexer.hh" #include "../ext/memory_pool.hh" #include "../renderer/constants.hh" #include <snow/memory/ref_counter.hh> #include <mutex> #include <set> #include <unordered_map> namespace snow { #define NULL_MATERIAL_NAME ("notex") struct rfont_t; struct rtexture_t; struct rmaterial_t; struct rprogram_t; struct rshader_t; struct resources_t { using nameset_t = std::set<string>; resources_t(); ~resources_t(); void prepare_resources(); rfont_t *load_font(const string &name); rtexture_t *load_texture(const string &path, bool mipmaps = true); rmaterial_t *load_material(const string &name); rprogram_t *load_program(const string &name); const nameset_t &definition_names() const; const nameset_t &definition_locations() const; bool name_is_material(const string &name) const; bool name_is_program(const string &name) const; void release_font(rfont_t *); void release_texture(rtexture_t *); void release_material(rmaterial_t *); void release_program(rprogram_t *); void release_all(); static resources_t &default_resources(); private: friend struct resdef_parser_t; static const uint32_t font_seed; static const uint32_t material_seed; static const uint32_t texture_seed; static const uint32_t program_seed; static const uint32_t vert_shader_seed; static const uint32_t frag_shader_seed; enum res_kind_t : unsigned { KIND_FONT, KIND_TEXTURE, KIND_MATERIAL, KIND_PROGRAM, KIND_SHADER, }; struct res_t { res_kind_t kind; union { rfont_t *font; rtexture_t *tex; rmaterial_t *mat; rprogram_t *prog; rshader_t *shader; }; }; struct resloc_t { size_t offset; size_t length; unsigned kind; // resdef_kind_t nameset_t::const_iterator resname; nameset_t::const_iterator matfile; }; using resmap_t = std::unordered_map<uint64_t, res_t>; template <typename T> using res_store_t = typename std::aligned_storage<sizeof(uint64_t) + sizeof(T)>::type; using fontmap_t = std::unordered_map<uint64_t, nameset_t::const_iterator>; using locmap_t = std::unordered_map<uint64_t, resloc_t>; using str_inserter_t = std::back_insert_iterator<std::list<nameset_t::const_iterator>>; template <typename T, typename... ARGS> T *allocate_resource(uint64_t hash, ARGS&& ...args); template <typename T> void destroy_resource(T *res); rshader_t *load_shader(const string &path, unsigned kind); void release_shader(rshader_t *shader); void prepare_fonts(); void prepare_definitions(); // Recursively searches for resource files under defs/ void find_definition_files(const char *dir, str_inserter_t &inserter); // Finds definitions within a given file void find_definitions(const nameset_t::const_iterator &path); // Finds definitions given a list of tokens void find_definitions_within(tokenlist_t::const_iterator iter, const tokenlist_t::const_iterator &end, const string::const_iterator &source_begin, const nameset_t::const_iterator &filepath); bool load_program_def(rprogram_t *prog, const locmap_t::const_iterator &from); bool read_program(rprogram_t *prog, tokenlist_t::const_iterator &iter, const tokenlist_t::const_iterator &end); bool read_program_shader(rprogram_t *prog, tokenlist_t::const_iterator &iter, const tokenlist_t::const_iterator &end); bool read_program_uniform(rprogram_t *prog, tokenlist_t::const_iterator &iter, const tokenlist_t::const_iterator &end); bool read_program_attrib(rprogram_t *prog, tokenlist_t::const_iterator &iter, const tokenlist_t::const_iterator &end); bool read_program_frag_out(rprogram_t *prog, tokenlist_t::const_iterator &iter, const tokenlist_t::const_iterator &end); // Parses the material given the location and lexer for use bool load_material_from(rmaterial_t *mat, const locmap_t::const_iterator &from); mempool_t pool_; nameset_t filepaths_; nameset_t def_names_; ref_counter_t refs_; resmap_t resources_; fontmap_t font_dbs_; locmap_t res_files_; mutable std::recursive_mutex lock_; }; template <typename T, typename... ARGS> T *resources_t::allocate_resource(uint64_t hash, ARGS&& ...args) { using res_type_t = res_store_t<T>; // res_type_t *store = new res_type_t; res_type_t *store = (res_type_t *)pool_malloc(&pool_, sizeof(*store), 1); if (!store) { s_log_error("Unable to allocate memory for resource"); return nullptr; } uint64_t * hash_ptr = (uint64_t *)store; hash_ptr[0] = hash; T *obj = (T *)&hash_ptr[1]; new(obj) T(std::forward<ARGS>(args)...); return obj; } template <typename T> void resources_t::destroy_resource(T *res) { using res_type_t = res_store_t<T>; uint64_t *hash_ptr = ((uint64_t *)res) - 1; resources_.erase(hash_ptr[0]); res->~T(); pool_free((res_type_t *)hash_ptr); // delete (res_type_t *)hash_ptr; } } // namespace snow #endif /* end __SNOW__RESOURCES_HH__ include guard */
28.928571
192
0.7415
nilium
ef639f485d0d520752c3987ea610f6d946308660
153
cpp
C++
level-editor/Config.cpp
lukas-vaiciunas/haterminator
7f42e5a4ed4c5dee21368859989b74ba6c80898b
[ "MIT" ]
null
null
null
level-editor/Config.cpp
lukas-vaiciunas/haterminator
7f42e5a4ed4c5dee21368859989b74ba6c80898b
[ "MIT" ]
null
null
null
level-editor/Config.cpp
lukas-vaiciunas/haterminator
7f42e5a4ed4c5dee21368859989b74ba6c80898b
[ "MIT" ]
null
null
null
#include "Config.h" namespace Config { const unsigned int displayWidth = 1600; const unsigned int displayHeight = 900; const unsigned int fps = 60; }
19.125
40
0.745098
lukas-vaiciunas
ef69d5b09b740143ea36afd4a84bd5dd06162b43
771
hh
C++
pegtl/analysis/grammar_info.hh
InspectorWidget/PEGTL
1f2c5bb8d43a9412fa7eeeb76a945fc5229500bc
[ "MIT" ]
9
2017-05-09T14:22:57.000Z
2018-04-25T11:48:54.000Z
ChatAssistant_iOS/Carthage/Checkouts/realm-cocoa/Realm/ObjectStore/external/pegtl/pegtl/analysis/grammar_info.hh
RickeyBoy/HACKxSJTU_ChatAssistant
12768c8b6710adb582aec6c3b40613eedc3dfeb2
[ "Apache-2.0" ]
null
null
null
ChatAssistant_iOS/Carthage/Checkouts/realm-cocoa/Realm/ObjectStore/external/pegtl/pegtl/analysis/grammar_info.hh
RickeyBoy/HACKxSJTU_ChatAssistant
12768c8b6710adb582aec6c3b40613eedc3dfeb2
[ "Apache-2.0" ]
1
2019-02-11T20:59:42.000Z
2019-02-11T20:59:42.000Z
// Copyright (c) 2014-2015 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/ColinH/PEGTL/ #ifndef PEGTL_ANALYSIS_GRAMMAR_INFO_HH #define PEGTL_ANALYSIS_GRAMMAR_INFO_HH #include <map> #include <string> #include <utility> #include "../internal/demangle.hh" #include "rule_info.hh" namespace pegtl { namespace analysis { struct grammar_info { using map_t = std::map< std::string, rule_info >; map_t map; template< typename Name > std::pair< map_t::iterator, bool > insert( const rule_type type ) { return map.insert( map_t::value_type( internal::demangle< Name >(), rule_info( type ) ) ); } }; } // analysis } // pegtl #endif
21.416667
102
0.640726
InspectorWidget
ef72a0d4da9b7cf331cbc7b131ca387edeaf25a8
33,713
cpp
C++
src/validate/chain_cache.cpp
eveybcd/BitcoinDiamond
ad08a18a13fb29cbf6d7b5a17c1632c5528a5f58
[ "MIT" ]
126
2017-12-21T07:17:47.000Z
2021-06-05T03:46:52.000Z
src/validate/chain_cache.cpp
Matthelonianxl/BitcoinDiamond
ad08a18a13fb29cbf6d7b5a17c1632c5528a5f58
[ "MIT" ]
63
2017-12-21T14:43:04.000Z
2021-11-18T03:43:35.000Z
src/validate/chain_cache.cpp
Matthelonianxl/BitcoinDiamond
ad08a18a13fb29cbf6d7b5a17c1632c5528a5f58
[ "MIT" ]
87
2017-12-21T07:17:50.000Z
2021-06-18T23:39:16.000Z
// Copyright (c) 2019 The BCD Core developers #include <validate/chain_cache.h> #include <validate/cchain_state.h> bool fRequireStandard = true; CFeeRate minRelayTxFee = CFeeRate(DEFAULT_MIN_RELAY_TX_FEE); // Used to avoid mempool polluting consensus critical paths if CCoinsViewMempool // were somehow broken and returning the wrong scriptPubKeys bool CheckInputsFromMempoolAndCache(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& view, const CTxMemPool& pool, unsigned int flags, bool cacheSigStore, PrecomputedTransactionData& txdata) { AssertLockHeld(cs_main); // pool.cs should be locked already, but go ahead and re-take the lock here // to enforce that mempool doesn't change between when we check the view // and when we actually call through to CheckInputs LOCK(pool.cs); assert(!tx.IsCoinBase()); for (const CTxIn& txin : tx.vin) { const Coin& coin = view.AccessCoin(txin.prevout); // At this point we haven't actually checked if the coins are all // available (or shouldn't assume we have, since CheckInputs does). // So we just return failure if the inputs are not available here, // and then only have to check equivalence for available inputs. if (coin.IsSpent()) return false; const CTransactionRef& txFrom = pool.get(txin.prevout.hash); if (txFrom) { assert(txFrom->GetHash() == txin.prevout.hash); assert(txFrom->vout.size() > txin.prevout.n); assert(txFrom->vout[txin.prevout.n] == coin.out); } else { const Coin& coinFromDisk = pcoinsTip->AccessCoin(txin.prevout); assert(!coinFromDisk.IsSpent()); assert(coinFromDisk.out == coin.out); } } return CheckInputs(tx, state, view, true, flags, cacheSigStore, true, txdata); } bool IsCurrentForFeeEstimation() { AssertLockHeld(cs_main); if (IsInitialBlockDownload()) return false; if (chainActive.Tip()->GetBlockTime() < (GetTime() - MAX_FEE_ESTIMATION_TIP_AGE)) return false; if (chainActive.Height() < pindexBestHeader->nHeight - 1) return false; return true; } bool AcceptToMemoryPoolWorker(const CChainParams& chainparams, CTxMemPool& pool, CValidationState& state, const CTransactionRef& ptx, bool* pfMissingInputs, int64_t nAcceptTime, std::list<CTransactionRef>* plTxnReplaced, bool bypass_limits, const CAmount& nAbsurdFee, std::vector<COutPoint>& coins_to_uncache, bool test_accept) { const CTransaction& tx = *ptx; const uint256 hash = tx.GetHash(); AssertLockHeld(cs_main); LOCK(pool.cs); // mempool "read lock" (held through GetMainSignals().TransactionAddedToMempool()) if (pfMissingInputs) { *pfMissingInputs = false; } if (!CheckTransaction(tx, state, true)) return false; // state filled in by CheckTransaction // Coinbase is only valid in a block, not as a loose transaction if (tx.IsCoinBase()) return state.DoS(100, false, REJECT_INVALID, "coinbase"); // Rather not work on nonstandard transactions (unless -testnet/-regtest) std::string reason; if (fRequireStandard && !IsStandardTx(tx, reason)) return state.DoS(0, false, REJECT_NONSTANDARD, reason); // Do not work on transactions that are too small. // A transaction with 1 segwit input and 1 P2WPHK output has non-witness size of 82 bytes. // Transactions smaller than this are not relayed to reduce unnecessary malloc overhead. if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS) < MIN_STANDARD_TX_NONWITNESS_SIZE) return state.DoS(0, false, REJECT_NONSTANDARD, "tx-size-small"); // Only accept nLockTime-using transactions that can be mined in the next // block; we don't want our mempool filled up with transactions that can't // be mined yet. if (!CheckFinalTx(tx, STANDARD_LOCKTIME_VERIFY_FLAGS)) return state.DoS(0, false, REJECT_NONSTANDARD, "non-final"); // is it already in the memory pool? if (pool.exists(hash)) { return state.Invalid(false, REJECT_DUPLICATE, "txn-already-in-mempool"); } // Check for conflicts with in-memory transactions std::set<uint256> setConflicts; for (const CTxIn &txin : tx.vin) { auto itConflicting = pool.mapNextTx.find(txin.prevout); if (itConflicting != pool.mapNextTx.end()) { const CTransaction *ptxConflicting = itConflicting->second; if (!setConflicts.count(ptxConflicting->GetHash())) { // Allow opt-out of transaction replacement by setting // nSequence > MAX_BIP125_RBF_SEQUENCE (SEQUENCE_FINAL-2) on all inputs. // // SEQUENCE_FINAL-1 is picked to still allow use of nLockTime by // non-replaceable transactions. All inputs rather than just one // is for the sake of multi-party protocols, where we don't // want a single party to be able to disable replacement. // // The opt-out ignores descendants as anyone relying on // first-seen mempool behavior should be checking all // unconfirmed ancestors anyway; doing otherwise is hopelessly // insecure. bool fReplacementOptOut = true; if (fEnableReplacement) { for (const CTxIn &_txin : ptxConflicting->vin) { if (_txin.nSequence <= MAX_BIP125_RBF_SEQUENCE) { fReplacementOptOut = false; break; } } } if (fReplacementOptOut) { return state.Invalid(false, REJECT_DUPLICATE, "txn-mempool-conflict"); } setConflicts.insert(ptxConflicting->GetHash()); } } } { CCoinsView dummy; CCoinsViewCache view(&dummy); LockPoints lp; CCoinsViewMemPool viewMemPool(pcoinsTip.get(), pool); view.SetBackend(viewMemPool); // do all inputs exist? for (const CTxIn& txin : tx.vin) { if (!pcoinsTip->HaveCoinInCache(txin.prevout)) { coins_to_uncache.push_back(txin.prevout); } if (!view.HaveCoin(txin.prevout)) { // Are inputs missing because we already have the tx? for (size_t out = 0; out < tx.vout.size(); out++) { // Optimistically just do efficient check of cache for outputs if (pcoinsTip->HaveCoinInCache(COutPoint(hash, out))) { return state.Invalid(false, REJECT_DUPLICATE, "txn-already-known"); } } // Otherwise assume this might be an orphan tx for which we just haven't seen parents yet if (pfMissingInputs) { *pfMissingInputs = true; } return false; // fMissingInputs and !state.IsInvalid() is used to detect this condition, don't set state.Invalid() } } // Bring the best block into scope view.GetBestBlock(); // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool view.SetBackend(dummy); // Only accept BIP68 sequence locked transactions that can be mined in the next // block; we don't want our mempool filled up with transactions that can't // be mined yet. // Must keep pool.cs for this unless we change CheckSequenceLocks to take a // CoinsViewCache instead of create its own if (!CheckSequenceLocks(tx, STANDARD_LOCKTIME_VERIFY_FLAGS, &lp)) return state.DoS(0, false, REJECT_NONSTANDARD, "non-BIP68-final"); CAmount nFees = 0; if (!Consensus::CheckTxInputs(tx, state, view, GetSpendHeight(view), nFees)) { return error("%s: Consensus::CheckTxInputs: %s, %s", __func__, tx.GetHash().ToString(), FormatStateMessage(state)); } // Check for non-standard pay-to-script-hash in inputs if (fRequireStandard && !AreInputsStandard(tx, view)) return state.Invalid(false, REJECT_NONSTANDARD, "bad-txns-nonstandard-inputs"); // Check for non-standard witness in P2WSH if (tx.HasWitness() && fRequireStandard && !IsWitnessStandard(tx, view)) return state.DoS(0, false, REJECT_NONSTANDARD, "bad-witness-nonstandard", true); int64_t nSigOpsCost = GetTransactionSigOpCost(tx, view, STANDARD_SCRIPT_VERIFY_FLAGS); // nModifiedFees includes any fee deltas from PrioritiseTransaction CAmount nModifiedFees = nFees; pool.ApplyDelta(hash, nModifiedFees); // Keep track of transactions that spend a coinbase, which we re-scan // during reorgs to ensure COINBASE_MATURITY is still met. bool fSpendsCoinbase = false; for (const CTxIn &txin : tx.vin) { const Coin &coin = view.AccessCoin(txin.prevout); if (coin.IsCoinBase()) { fSpendsCoinbase = true; break; } } CTxMemPoolEntry entry(ptx, nFees, nAcceptTime, chainActive.Height(), fSpendsCoinbase, nSigOpsCost, lp); unsigned int nSize = entry.GetTxSize(); // Check that the transaction doesn't have an excessive number of // sigops, making it impossible to mine. Since the coinbase transaction // itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than // merely non-standard transaction. if (nSigOpsCost > MAX_STANDARD_TX_SIGOPS_COST) return state.DoS(0, false, REJECT_NONSTANDARD, "bad-txns-too-many-sigops", false, strprintf("%d", nSigOpsCost)); CAmount mempoolRejectFee = pool.GetMinFee(gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFee(nSize); if (!bypass_limits && mempoolRejectFee > 0 && nModifiedFees < mempoolRejectFee) { return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool min fee not met", false, strprintf("%d < %d", nModifiedFees, mempoolRejectFee)); } // No transactions are allowed below minRelayTxFee except from disconnected blocks if (!bypass_limits && nModifiedFees < ::minRelayTxFee.GetFee(nSize)) { return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "min relay fee not met", false, strprintf("%d < %d", nModifiedFees, ::minRelayTxFee.GetFee(nSize))); } if (nAbsurdFee && nFees > nAbsurdFee) return state.Invalid(false, REJECT_HIGHFEE, "absurdly-high-fee", strprintf("%d > %d", nFees, nAbsurdFee)); // Calculate in-mempool ancestors, up to a limit. CTxMemPool::setEntries setAncestors; size_t nLimitAncestors = gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT); size_t nLimitAncestorSize = gArgs.GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000; size_t nLimitDescendants = gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT); size_t nLimitDescendantSize = gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000; std::string errString; if (!pool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) { return state.DoS(0, false, REJECT_NONSTANDARD, "too-long-mempool-chain", false, errString); } // A transaction that spends outputs that would be replaced by it is invalid. Now // that we have the set of all ancestors we can detect this // pathological case by making sure setConflicts and setAncestors don't // intersect. for (CTxMemPool::txiter ancestorIt : setAncestors) { const uint256 &hashAncestor = ancestorIt->GetTx().GetHash(); if (setConflicts.count(hashAncestor)) { return state.DoS(10, false, REJECT_INVALID, "bad-txns-spends-conflicting-tx", false, strprintf("%s spends conflicting transaction %s", hash.ToString(), hashAncestor.ToString())); } } // Check if it's economically rational to mine this transaction rather // than the ones it replaces. CAmount nConflictingFees = 0; size_t nConflictingSize = 0; uint64_t nConflictingCount = 0; CTxMemPool::setEntries allConflicting; // If we don't hold the lock allConflicting might be incomplete; the // subsequent RemoveStaged() and addUnchecked() calls don't guarantee // mempool consistency for us. const bool fReplacementTransaction = setConflicts.size(); if (fReplacementTransaction) { CFeeRate newFeeRate(nModifiedFees, nSize); std::set<uint256> setConflictsParents; const int maxDescendantsToVisit = 100; CTxMemPool::setEntries setIterConflicting; for (const uint256 &hashConflicting : setConflicts) { CTxMemPool::txiter mi = pool.mapTx.find(hashConflicting); if (mi == pool.mapTx.end()) continue; // Save these to avoid repeated lookups setIterConflicting.insert(mi); // Don't allow the replacement to reduce the feerate of the // mempool. // // We usually don't want to accept replacements with lower // feerates than what they replaced as that would lower the // feerate of the next block. Requiring that the feerate always // be increased is also an easy-to-reason about way to prevent // DoS attacks via replacements. // // We only consider the feerates of transactions being directly // replaced, not their indirect descendants. While that does // mean high feerate children are ignored when deciding whether // or not to replace, we do require the replacement to pay more // overall fees too, mitigating most cases. CFeeRate oldFeeRate(mi->GetModifiedFee(), mi->GetTxSize()); if (newFeeRate <= oldFeeRate) { return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "insufficient fee", false, strprintf("rejecting replacement %s; new feerate %s <= old feerate %s", hash.ToString(), newFeeRate.ToString(), oldFeeRate.ToString())); } for (const CTxIn &txin : mi->GetTx().vin) { setConflictsParents.insert(txin.prevout.hash); } nConflictingCount += mi->GetCountWithDescendants(); } // This potentially overestimates the number of actual descendants // but we just want to be conservative to avoid doing too much // work. if (nConflictingCount <= maxDescendantsToVisit) { // If not too many to replace, then calculate the set of // transactions that would have to be evicted for (CTxMemPool::txiter it : setIterConflicting) { pool.CalculateDescendants(it, allConflicting); } for (CTxMemPool::txiter it : allConflicting) { nConflictingFees += it->GetModifiedFee(); nConflictingSize += it->GetTxSize(); } } else { return state.DoS(0, false, REJECT_NONSTANDARD, "too many potential replacements", false, strprintf("rejecting replacement %s; too many potential replacements (%d > %d)\n", hash.ToString(), nConflictingCount, maxDescendantsToVisit)); } for (unsigned int j = 0; j < tx.vin.size(); j++) { // We don't want to accept replacements that require low // feerate junk to be mined first. Ideally we'd keep track of // the ancestor feerates and make the decision based on that, // but for now requiring all new inputs to be confirmed works. if (!setConflictsParents.count(tx.vin[j].prevout.hash)) { // Rather than check the UTXO set - potentially expensive - // it's cheaper to just check if the new input refers to a // tx that's in the mempool. if (pool.mapTx.find(tx.vin[j].prevout.hash) != pool.mapTx.end()) return state.DoS(0, false, REJECT_NONSTANDARD, "replacement-adds-unconfirmed", false, strprintf("replacement %s adds unconfirmed input, idx %d", hash.ToString(), j)); } } // The replacement must pay greater fees than the transactions it // replaces - if we did the bandwidth used by those conflicting // transactions would not be paid for. if (nModifiedFees < nConflictingFees) { return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "insufficient fee", false, strprintf("rejecting replacement %s, less fees than conflicting txs; %s < %s", hash.ToString(), FormatMoney(nModifiedFees), FormatMoney(nConflictingFees))); } // Finally in addition to paying more fees than the conflicts the // new transaction must pay for its own bandwidth. CAmount nDeltaFees = nModifiedFees - nConflictingFees; if (nDeltaFees < ::incrementalRelayFee.GetFee(nSize)) { return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "insufficient fee", false, strprintf("rejecting replacement %s, not enough additional fees to relay; %s < %s", hash.ToString(), FormatMoney(nDeltaFees), FormatMoney(::incrementalRelayFee.GetFee(nSize)))); } } constexpr unsigned int scriptVerifyFlags = STANDARD_SCRIPT_VERIFY_FLAGS; // Check against previous transactions // This is done last to help prevent CPU exhaustion denial-of-service attacks. PrecomputedTransactionData txdata(tx); if (!CheckInputs(tx, state, view, true, scriptVerifyFlags, true, false, txdata)) { // SCRIPT_VERIFY_CLEANSTACK requires SCRIPT_VERIFY_WITNESS, so we // need to turn both off, and compare against just turning off CLEANSTACK // to see if the failure is specifically due to witness validate. CValidationState stateDummy; // Want reported failures to be from first CheckInputs if (!tx.HasWitness() && CheckInputs(tx, stateDummy, view, true, scriptVerifyFlags & ~(SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_CLEANSTACK), true, false, txdata) && !CheckInputs(tx, stateDummy, view, true, scriptVerifyFlags & ~SCRIPT_VERIFY_CLEANSTACK, true, false, txdata)) { // Only the witness is missing, so the transaction itself may be fine. state.SetCorruptionPossible(); } return false; // state filled in by CheckInputs } // Check again against the current block tip's script verification // flags to cache our script execution flags. This is, of course, // useless if the next block has different script flags from the // previous one, but because the cache tracks script flags for us it // will auto-invalidate and we'll just have a few blocks of extra // misses on soft-fork activation. // // This is also useful in case of bugs in the standard flags that cause // transactions to pass as valid when they're actually invalid. For // instance the STRICTENC flag was incorrectly allowing certain // CHECKSIG NOT scripts to pass, even though they were invalid. // // There is a similar check in CreateNewBlock() to prevent creating // invalid blocks (using TestBlockValidity), however allowing such // transactions into the mempool can be exploited as a DoS attack. unsigned int currentBlockScriptVerifyFlags = gBlockStorage.GetBlockScriptFlags(chainActive.Tip(), Params().GetConsensus()); if (!CheckInputsFromMempoolAndCache(tx, state, view, pool, currentBlockScriptVerifyFlags, true, txdata)) { return error("%s: BUG! PLEASE REPORT THIS! CheckInputs failed against latest-block but not STANDARD flags %s, %s", __func__, hash.ToString(), FormatStateMessage(state)); } if (test_accept) { // Tx was accepted, but not added return true; } // Remove conflicting transactions from the mempool for (CTxMemPool::txiter it : allConflicting) { LogPrint(BCLog::MEMPOOL, "replacing tx %s with %s for %s BCD additional fees, %d delta bytes\n", it->GetTx().GetHash().ToString(), hash.ToString(), FormatMoney(nModifiedFees - nConflictingFees), (int)nSize - (int)nConflictingSize); if (plTxnReplaced) plTxnReplaced->push_back(it->GetSharedTx()); } pool.RemoveStaged(allConflicting, false, MemPoolRemovalReason::REPLACED); // This transaction should only count for fee estimation if: // - it isn't a BIP 125 replacement transaction (may not be widely supported) // - it's not being re-added during a reorg which bypasses typical mempool fee limits // - the node is not behind // - the transaction is not dependent on any other transactions in the mempool bool validForFeeEstimation = !fReplacementTransaction && !bypass_limits && IsCurrentForFeeEstimation() && pool.HasNoInputsOf(tx); // Store transaction in memory pool.addUnchecked(hash, entry, setAncestors, validForFeeEstimation); // trim mempool and check if tx was trimmed if (!bypass_limits) { LimitMempoolSize(pool, gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60); if (!pool.exists(hash)) return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool full"); } } GetMainSignals().TransactionAddedToMempool(ptx); return true; } bool CheckFinalTx(const CTransaction &tx, int flags) { AssertLockHeld(cs_main); // By convention a negative value for flags indicates that the // current network-enforced consensus rules should be used. In // a future soft-fork scenario that would mean checking which // rules would be enforced for the next block and setting the // appropriate flags. At the present time no soft-forks are // scheduled, so no flags are set. flags = std::max(flags, 0); // CheckFinalTx() uses chainActive.Height()+1 to evaluate // nLockTime because when IsFinalTx() is called within // CBlock::AcceptBlock(), the height of the block *being* // evaluated is what is used. Thus if we want to know if a // transaction can be part of the *next* block, we need to call // IsFinalTx() with one more than chainActive.Height(). const int nBlockHeight = chainActive.Height() + 1; // BIP113 requires that time-locked transactions have nLockTime set to // less than the median time of the previous block they're contained in. // When the next block is created its previous block will be the current // chain tip, so we use that to calculate the median time passed to // IsFinalTx() if LOCKTIME_MEDIAN_TIME_PAST is set. const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST) ? chainActive.Tip()->GetMedianTimePast() : GetAdjustedTime(); return IsFinalTx(tx, nBlockHeight, nBlockTime); } int GetSpendHeight(const CCoinsViewCache& inputs) { LOCK(cs_main); CBlockIndex* pindexPrev = gBlockStorage.LookupBlockIndex(inputs.GetBestBlock()); return pindexPrev->nHeight + 1; } bool CheckSequenceLocks(const CTransaction &tx, int flags, LockPoints* lp, bool useExistingLockPoints) { AssertLockHeld(cs_main); AssertLockHeld(mempool.cs); CBlockIndex* tip = chainActive.Tip(); assert(tip != nullptr); CBlockIndex index; index.pprev = tip; // CheckSequenceLocks() uses chainActive.Height()+1 to evaluate // height based locks because when SequenceLocks() is called within // ConnectBlock(), the height of the block *being* // evaluated is what is used. // Thus if we want to know if a transaction can be part of the // *next* block, we need to use one more than chainActive.Height() index.nHeight = tip->nHeight + 1; std::pair<int, int64_t> lockPair; if (useExistingLockPoints) { assert(lp); lockPair.first = lp->height; lockPair.second = lp->time; } else { // pcoinsTip contains the UTXO set for chainActive.Tip() CCoinsViewMemPool viewMemPool(pcoinsTip.get(), mempool); std::vector<int> prevheights; prevheights.resize(tx.vin.size()); for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) { const CTxIn& txin = tx.vin[txinIndex]; Coin coin; if (!viewMemPool.GetCoin(txin.prevout, coin)) { return error("%s: Missing input", __func__); } if (coin.nHeight == MEMPOOL_HEIGHT) { // Assume all mempool transaction confirm in the next block prevheights[txinIndex] = tip->nHeight + 1; } else { prevheights[txinIndex] = coin.nHeight; } } lockPair = CalculateSequenceLocks(tx, flags, &prevheights, index); if (lp) { lp->height = lockPair.first; lp->time = lockPair.second; // Also store the hash of the block with the highest height of // all the blocks which have sequence locked prevouts. // This hash needs to still be on the chain // for these LockPoint calculations to be valid // Note: It is impossible to correctly calculate a maxInputBlock // if any of the sequence locked inputs depend on unconfirmed txs, // except in the special case where the relative lock time/height // is 0, which is equivalent to no sequence lock. Since we assume // input height of tip+1 for mempool txs and test the resulting // lockPair from CalculateSequenceLocks against tip+1. We know // EvaluateSequenceLocks will fail if there was a non-zero sequence // lock on a mempool input, so we can use the return value of // CheckSequenceLocks to indicate the LockPoints validity int maxInputHeight = 0; for (int height : prevheights) { // Can ignore mempool inputs since we'll fail if they had non-zero locks if (height != tip->nHeight+1) { maxInputHeight = std::max(maxInputHeight, height); } } lp->maxInputBlock = tip->GetAncestor(maxInputHeight); } } return EvaluateSequenceLocks(index, lockPair); } /** (try to) add transaction to memory pool with a specified acceptance time **/ bool AcceptToMemoryPoolWithTime(const CChainParams& chainparams, CTxMemPool& pool, CValidationState &state, const CTransactionRef &tx, bool* pfMissingInputs, int64_t nAcceptTime, std::list<CTransactionRef>* plTxnReplaced, bool bypass_limits, const CAmount nAbsurdFee, bool test_accept) { std::vector<COutPoint> coins_to_uncache; bool res = AcceptToMemoryPoolWorker(chainparams, pool, state, tx, pfMissingInputs, nAcceptTime, plTxnReplaced, bypass_limits, nAbsurdFee, coins_to_uncache, test_accept); if (!res) { for (const COutPoint& hashTx : coins_to_uncache) pcoinsTip->Uncache(hashTx); } // After we've (potentially) uncached entries, ensure our coins cache is still within its size limits CValidationState stateDummy; gBlockStorage.FlushStateToDisk(chainparams, stateDummy, FlushStateMode::PERIODIC); return res; } bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransactionRef &tx, bool* pfMissingInputs, std::list<CTransactionRef>* plTxnReplaced, bool bypass_limits, const CAmount nAbsurdFee, bool test_accept) { const CChainParams& chainparams = Params(); return AcceptToMemoryPoolWithTime(chainparams, pool, state, tx, pfMissingInputs, GetTime(), plTxnReplaced, bypass_limits, nAbsurdFee, test_accept); } void LimitMempoolSize(CTxMemPool& pool, size_t limit, unsigned long age) { int expired = pool.Expire(GetTime() - age); if (expired != 0) { LogPrint(BCLog::MEMPOOL, "Expired %i transactions from the memory pool\n", expired); } std::vector<COutPoint> vNoSpendsRemaining; pool.TrimToSize(limit, &vNoSpendsRemaining); for (const COutPoint& removed : vNoSpendsRemaining) pcoinsTip->Uncache(removed); } /* Make mempool consistent after a reorg, by re-adding or recursively erasing * disconnected block transactions from the mempool, and also removing any * other transactions from the mempool that are no longer valid given the new * tip/height. * * Note: we assume that disconnectpool only contains transactions that are NOT * confirmed in the current chain nor already in the mempool (otherwise, * in-mempool descendants of such transactions would be removed). * * Passing fAddToMempool=false will skip trying to add the transactions back, * and instead just erase from the mempool as needed. */ void UpdateMempoolForReorg(DisconnectedBlockTransactions &disconnectpool, bool fAddToMempool) { AssertLockHeld(cs_main); std::vector<uint256> vHashUpdate; // disconnectpool's insertion_order index sorts the entries from // oldest to newest, but the oldest entry will be the last tx from the // latest mined block that was disconnected. // Iterate disconnectpool in reverse, so that we add transactions // back to the mempool starting with the earliest transaction that had // been previously seen in a block. auto it = disconnectpool.queuedTx.get<insertion_order>().rbegin(); while (it != disconnectpool.queuedTx.get<insertion_order>().rend()) { // ignore validate errors in resurrected transactions CValidationState stateDummy; if (!fAddToMempool || (*it)->IsCoinBase() || !AcceptToMemoryPool(mempool, stateDummy, *it, nullptr /* pfMissingInputs */, nullptr /* plTxnReplaced */, true /* bypass_limits */, 0 /* nAbsurdFee */)) { // If the transaction doesn't make it in to the mempool, remove any // transactions that depend on it (which would now be orphans). mempool.removeRecursive(**it, MemPoolRemovalReason::REORG); } else if (mempool.exists((*it)->GetHash())) { vHashUpdate.push_back((*it)->GetHash()); } ++it; } disconnectpool.queuedTx.clear(); // AcceptToMemoryPool/addUnchecked all assume that new mempool entries have // no in-mempool children, which is generally not true when adding // previously-confirmed transactions back to the mempool. // UpdateTransactionsFromBlock finds descendants of any transactions in // the disconnectpool that were added back and cleans up the mempool state. mempool.UpdateTransactionsFromBlock(vHashUpdate); // We also need to remove any now-immature transactions mempool.removeForReorg(pcoinsTip.get(), chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS); // Re-limit mempool size, in case we added any transactions LimitMempoolSize(mempool, gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60); }
49.432551
173
0.620473
eveybcd
ef73c47429c754ba759c2c5df0e3ff807e0c50b2
391
hpp
C++
src/textureholder.hpp
alexandre-janniaux/ludumdare_radonnykoteam
3f79bf4fab46eb5d380640714cfd341bbd37bc9b
[ "MIT" ]
null
null
null
src/textureholder.hpp
alexandre-janniaux/ludumdare_radonnykoteam
3f79bf4fab46eb5d380640714cfd341bbd37bc9b
[ "MIT" ]
null
null
null
src/textureholder.hpp
alexandre-janniaux/ludumdare_radonnykoteam
3f79bf4fab46eb5d380640714cfd341bbd37bc9b
[ "MIT" ]
null
null
null
#pragma once #include "ressourceholder.hpp" #include <SFML/Graphics.hpp> namespace Texture { enum ID { Branch , OffensiveLadybug , DefensiveLadybug , NormalLadybug , Aphid , Background , RegularFlower , AphidFlower , LadybugFlower , NodeFlower , None }; } class TextureHolder: public ResourceHolder<sf::Texture, Texture::ID> { public: TextureHolder() {}; };
14.481481
68
0.693095
alexandre-janniaux
ef7b6c12f9ad25567d48e150becab924d3b11f8a
3,187
cpp
C++
source/EterLib/GrpVertexBuffer.cpp
beetle2k/Metin2Client
114f492b71fcc90e8f5010c5b35b9fddb51639ca
[ "MIT" ]
13
2018-08-27T19:06:54.000Z
2021-11-12T05:44:04.000Z
source/EterLib/GrpVertexBuffer.cpp
stempomzeskas/Metin2Client
114f492b71fcc90e8f5010c5b35b9fddb51639ca
[ "MIT" ]
null
null
null
source/EterLib/GrpVertexBuffer.cpp
stempomzeskas/Metin2Client
114f492b71fcc90e8f5010c5b35b9fddb51639ca
[ "MIT" ]
15
2018-10-25T14:28:10.000Z
2022-03-25T14:05:09.000Z
#include "StdAfx.h" #include "../eterBase/Stl.h" #include "GrpVertexBuffer.h" #include "StateManager.h" int CGraphicVertexBuffer::GetVertexStride() const { int retSize = D3DXGetFVFVertexSize(m_dwFVF); return retSize; } DWORD CGraphicVertexBuffer::GetFlexibleVertexFormat() const { return m_dwFVF; } int CGraphicVertexBuffer::GetVertexCount() const { return m_vtxCount; } void CGraphicVertexBuffer::SetStream(int stride, int layer) const { assert(ms_lpd3dDevice != NULL); STATEMANAGER.SetStreamSource(layer, m_lpd3dVB, stride); } bool CGraphicVertexBuffer::LockRange(unsigned count, void** pretVertices) const { if (!m_lpd3dVB) return false; DWORD dwLockSize=GetVertexStride() * count; if (FAILED(m_lpd3dVB->Lock(0, dwLockSize, (BYTE **) pretVertices, m_dwLockFlag))) return false; return true; } bool CGraphicVertexBuffer::Lock(void ** pretVertices) const { if (!m_lpd3dVB) return false; DWORD dwLockSize=GetVertexStride()*GetVertexCount(); if (FAILED(m_lpd3dVB->Lock(0, dwLockSize, (BYTE **) pretVertices, m_dwLockFlag))) return false; return true; } bool CGraphicVertexBuffer::Unlock() const { if (!m_lpd3dVB) return false; if ( FAILED(m_lpd3dVB->Unlock()) ) return false; return true; } bool CGraphicVertexBuffer::IsEmpty() const { if (m_lpd3dVB) return true; else return false; } bool CGraphicVertexBuffer::LockDynamic(void** pretVertices) { if (!m_lpd3dVB) return false; if (FAILED(m_lpd3dVB->Lock(0, 0, (BYTE**)pretVertices, 0))) return false; return true; } bool CGraphicVertexBuffer::Lock(void ** pretVertices) { if (!m_lpd3dVB) return false; if (FAILED(m_lpd3dVB->Lock(0, 0, (BYTE**)pretVertices, m_dwLockFlag))) return false; return true; } bool CGraphicVertexBuffer::Unlock() { if (!m_lpd3dVB) return false; if ( FAILED(m_lpd3dVB->Unlock()) ) return false; return true; } bool CGraphicVertexBuffer::Copy(int bufSize, const void* srcVertices) { void * dstVertices; if (!Lock(&dstVertices)) return false; memcpy(dstVertices, srcVertices, bufSize); Unlock(); return true; } bool CGraphicVertexBuffer::CreateDeviceObjects() { assert(ms_lpd3dDevice != NULL); assert(m_lpd3dVB == NULL); if (FAILED( ms_lpd3dDevice->CreateVertexBuffer( m_dwBufferSize, m_dwUsage, m_dwFVF, m_d3dPool, &m_lpd3dVB) )) return false; return true; } void CGraphicVertexBuffer::DestroyDeviceObjects() { safe_release(m_lpd3dVB); } bool CGraphicVertexBuffer::Create(int vtxCount, DWORD fvf, DWORD usage, D3DPOOL d3dPool) { assert(ms_lpd3dDevice != NULL); assert(vtxCount > 0); Destroy(); m_vtxCount = vtxCount; m_dwBufferSize = D3DXGetFVFVertexSize(fvf) * m_vtxCount; m_d3dPool = d3dPool; m_dwUsage = usage; m_dwFVF = fvf; if (usage == D3DUSAGE_WRITEONLY || usage == D3DUSAGE_DYNAMIC) m_dwLockFlag = 0; else m_dwLockFlag = D3DLOCK_READONLY; return CreateDeviceObjects(); } void CGraphicVertexBuffer::Destroy() { DestroyDeviceObjects(); } void CGraphicVertexBuffer::Initialize() { m_lpd3dVB = NULL; m_vtxCount = 0; m_dwBufferSize = 0; } CGraphicVertexBuffer::CGraphicVertexBuffer() { Initialize(); } CGraphicVertexBuffer::~CGraphicVertexBuffer() { Destroy(); }
17.705556
88
0.73235
beetle2k
ef7dcd436bf751f598b613884290cc141a6cda56
1,054
cpp
C++
Shoot/src/OpenGL/OpenGLExtensionHandler.cpp
franticsoftware/starports
d723404b20383949874868c251c60cfa06120fde
[ "MIT" ]
5
2016-11-13T08:13:57.000Z
2019-03-31T10:22:38.000Z
Shoot/src/OpenGL/OpenGLExtensionHandler.cpp
franticsoftware/starports
d723404b20383949874868c251c60cfa06120fde
[ "MIT" ]
null
null
null
Shoot/src/OpenGL/OpenGLExtensionHandler.cpp
franticsoftware/starports
d723404b20383949874868c251c60cfa06120fde
[ "MIT" ]
1
2016-12-23T11:25:35.000Z
2016-12-23T11:25:35.000Z
/* Amine Rehioui Created: August 15th 2010 Uses code from the Irrlicht engine extension handler */ #include "Shoot.h" #include "OpenGLExtensionHandler.h" namespace shoot { //! Constructor OpenGLExtensionHandler::OpenGLExtensionHandler(const char* const strExtensionStrings[E_Count]) { const char* strExtensions = reinterpret_cast<const char*>(glGetString(GL_EXTENSIONS)); if (!strExtensions) { Log.Print("glGetString failed\n"); return; } auto length = strlen(strExtensions); std::string extension; for(size_t i=0; i<length; ++i) { if(strExtensions[i] == ' ') { Log << "GL EXTENSION: " << extension.c_str() << "\n"; for(int j=0; j<E_Count; ++j) { if(extension == strExtensionStrings[j]) { m_bHasExtension[j] = true; break; } } extension = ""; } else { extension = extension + strExtensions[i]; } } for(int i=0; i<E_Count; ++i) { if(std::string(strExtensionStrings[i]) == "Native") { m_bHasExtension[i] = true; } } } }
17
96
0.617647
franticsoftware
ef7fff08c24ba7f32e0206dd6c1ac9873f9b4f7c
1,577
cpp
C++
src/mpieventdistributor.cpp
j0r1/EATk
4ce34a030e21925532d2725cbb9460b19442424c
[ "MIT" ]
null
null
null
src/mpieventdistributor.cpp
j0r1/EATk
4ce34a030e21925532d2725cbb9460b19442424c
[ "MIT" ]
null
null
null
src/mpieventdistributor.cpp
j0r1/EATk
4ce34a030e21925532d2725cbb9460b19442424c
[ "MIT" ]
null
null
null
#include "mpieventdistributor.h" #ifdef EATKCONFIG_MPISUPPORT #include <string> using namespace errut; using namespace std; namespace eatk { MPIEventDistributor::MPIEventDistributor(int root, MPI_Comm communicator) : m_comm(communicator), m_root(root) { m_handlers.resize(MPIEventHandler::MaxEvent); } MPIEventDistributor::~MPIEventDistributor() { } errut::bool_t MPIEventDistributor::setHandler(MPIEventHandler::EventType evtType, const std::weak_ptr<MPIEventHandler> &calc) { int evt = (int)evtType; if (evt < 0 || evt >= (int)m_handlers.size()) return "Invalid event type " + to_string(evt); m_handlers[evt] = calc; return true; } bool_t MPIEventDistributor::signal(MPIEventHandler::EventType evtType) { int evt = (int)evtType; MPI_Bcast(&evt, 1, MPI_INT, m_root, m_comm); return true; } bool_t MPIEventDistributor::eventLoop() { while (true) { int evt = -1; // Set this to something invalid, in case we're misidentifying ourselves as root MPI_Bcast(&evt, 1, MPI_INT, m_root, m_comm); if ((MPIEventHandler::EventType)evt == MPIEventHandler::Done) break; if (evt < 0 || evt >= (int)m_handlers.size()) return "Received invalid event type " + to_string(evt); if (auto handler = m_handlers[evt].lock()) { bool_t r = handler->handleEvent((MPIEventHandler::EventType)evt); if (!r) return "Error handling event " + to_string(evt) + ": " + r.getErrorString(); } else return "No handler set for event type " + to_string(evt) + "(or handler expired)"; } return true; } } #endif // EATKCONFIG_MPISUPPORT
23.191176
96
0.707039
j0r1
ef84cf069f894f9989aa63193e4df94b42644b57
2,532
cpp
C++
Engine/src/Engine/Core/IMGUI/IMGUI.cpp
rogerbusquets97/OpenGL_RayMarcher
d1b37ebed66baa56a50441f0e41299064ac16249
[ "Apache-2.0" ]
null
null
null
Engine/src/Engine/Core/IMGUI/IMGUI.cpp
rogerbusquets97/OpenGL_RayMarcher
d1b37ebed66baa56a50441f0e41299064ac16249
[ "Apache-2.0" ]
4
2020-06-09T14:16:43.000Z
2020-06-09T14:18:07.000Z
Engine/src/Engine/Core/IMGUI/IMGUI.cpp
rogerbusquets97/RubEngine
d1b37ebed66baa56a50441f0e41299064ac16249
[ "Apache-2.0" ]
null
null
null
#include "IMGUI.h" #include <Renderer/RenderAPI.h> #include <Window/ModuleWindow.h> namespace rubEngine { std::shared_ptr<ImGuiPlatformHandler> IMGUI::mHandler = nullptr; int IMGUI::mWindowFlags = 0; bool IMGUI::mFrameClosed = true; void rubEngine::IMGUI::Init() { mHandler = ImGuiPlatformHandler::Create(); mHandler->Init(); mWindowFlags = ImGuiWindowFlags_MenuBar | ImGuiWindowFlags_NoDocking; mWindowFlags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove; mWindowFlags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus; mWindowFlags ^= ImGuiDockNodeFlags_PassthruCentralNode; mWindowFlags |= ImGuiWindowFlags_NoBackground; } void rubEngine::IMGUI::CleanUp() { if (!mFrameClosed) { EndFrame(); } mHandler->CleanUp(); } void rubEngine::IMGUI::BeginFrame() { if (mFrameClosed) { mHandler->BeginFrame(); mFrameClosed = false; } } void rubEngine::IMGUI::EndFrame() { mHandler->EndFrame(); mFrameClosed = true; } bool IMGUI::BeginWindow(const char* aName, bool* aOpen, int aFlags) { return ImGui::Begin(aName, aOpen, aFlags); } void IMGUI::EndWindow() { return ImGui::End(); } bool IMGUI::BeginMainMenuBar() { return ImGui::BeginMainMenuBar(); } void IMGUI::EndMainMenuBar() { ImGui::EndMainMenuBar(); } bool IMGUI::BeginMenuBar() { return ImGui::BeginMenuBar(); } void IMGUI::BeginDockSpace() { static ImGuiDockNodeFlags dockspace_flags = ImGuiDockNodeFlags_None; ImGuiIO& io = ImGui::GetIO(); if (io.ConfigFlags & ImGuiConfigFlags_DockingEnable) { ImGuiID dockspace_id = ImGui::GetID("MainDockSpace"); ImGui::DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags); } } bool IMGUI::BeginMenu(const char* aLabel, bool aEnabled) { return ImGui::BeginMenu(aLabel, aEnabled); } void IMGUI::EndMenu() { ImGui::EndMenu(); } void IMGUI::SetNextWindowSize(unsigned int aWidth, unsigned int aHeight) { ImGui::SetNextWindowSize(ImVec2(aWidth, aHeight)); } void IMGUI::EndMenuBar() { return ImGui::EndMenuBar(); } bool IMGUI::AddMenuItem(const char* aLabel, const char* aShortcut, bool aSelected, bool aEnabled) { return ImGui::MenuItem(aLabel, aShortcut, aSelected, aEnabled); } bool IMGUI::AddMenuItem(const char* aLabel, const char* aShortcut, bool* apSelected, bool aEnabled) { return ImGui::MenuItem(aLabel, aShortcut, apSelected, aEnabled); } int IMGUI::GetMainWindowFlags() { return mWindowFlags; } }
23.663551
130
0.727093
rogerbusquets97
ef888e845da652b0207a751f7a86762c67c50348
2,097
cpp
C++
src/Pass/Passes/LocateASTNodes.cpp
schwarzschild-radius/spmdfy
9b5543e3446347277f15b9fe2aee3c7f8311bc78
[ "MIT" ]
6
2019-07-26T12:37:32.000Z
2021-03-13T06:18:07.000Z
src/Pass/Passes/LocateASTNodes.cpp
schwarzschild-radius/spmdfy
9b5543e3446347277f15b9fe2aee3c7f8311bc78
[ "MIT" ]
6
2019-06-19T06:04:01.000Z
2019-08-23T11:12:31.000Z
src/Pass/Passes/LocateASTNodes.cpp
schwarzschild-radius/spmdfy
9b5543e3446347277f15b9fe2aee3c7f8311bc78
[ "MIT" ]
1
2020-05-28T06:43:12.000Z
2020-05-28T06:43:12.000Z
#include <spmdfy/Pass/Passes/LocateASTNodes.hpp> namespace spmdfy { namespace pass { #define CFGNODE_DEF_VISITOR(NODE, NAME) \ auto LocateASTNodes::Visit##NODE##Node(cfg::NODE##Node *NAME)->bool #define CASTAS(TYPE, NODE) dynamic_cast<TYPE>(NODE) bool locateASTNodes(SpmdTUTy &spmd_tu, clang::ASTContext &ast_context, Workspace &workspace) { LocateASTNodes finder(spmd_tu, ast_context, workspace); finder.HandleSpmdTU(spmd_tu); SPMDFY_INFO("Number of Synthread Nodes Detected: {}", workspace.syncthreads_queue.size()); SPMDFY_INFO("Number of Shmem Nodes Detected: {}", workspace.shmem_queue.size()); return false; } static std::string getKernelNodeName(cfg::CFGNode *node) { auto curr_node = node; while (curr_node->getNodeType() != cfg::CFGNode::KernelFunc) { curr_node = curr_node->getPrevious(); } return curr_node->getName(); } CFGNODE_DEF_VISITOR(Internal, internal) { const std::string &node_name = internal->getInternalNodeName(); const std::string &kernel_name = getKernelNodeName(internal); SPMDFY_INFO("Visiting InternalNode {} of type {}", internal->getName(), node_name); if (node_name == "CallExpr") { auto call_expr = internal->getInternalNodeAs<const clang::CallExpr>(); if (call_expr->getDirectCallee()->getNameAsString() == "__syncthreads") { SPMDFY_INFO("Detected synthreads after {}", internal->getPrevious()->getName()); m_workspace.syncthreads_queue[kernel_name].push(internal); } } if (node_name == "Var") { auto var_decl = internal->getInternalNodeAs<const clang::VarDecl>(); if (var_decl->hasAttr<clang::CUDASharedAttr>()) { SPMDFY_INFO("Detected SharedMemory Nodes {}", internal->getPrevious()->getName()); m_workspace.shmem_queue[kernel_name].push(internal); } } return true; } } // namespace pass } // namespace spmdfy
36.155172
80
0.632809
schwarzschild-radius
ef89a0bc9b7a02957c4fc4ce270166259f2b0899
9,309
cpp
C++
examples/boxbash/BoxCommands.cpp
slashdotted/dropboxQt
63d43fa882cec8fb980a2aab2464a2d7260b8089
[ "MIT" ]
17
2016-12-03T09:12:29.000Z
2020-06-20T22:08:44.000Z
examples/boxbash/BoxCommands.cpp
slashdotted/dropboxQt
63d43fa882cec8fb980a2aab2464a2d7260b8089
[ "MIT" ]
8
2017-01-05T17:50:16.000Z
2021-08-06T18:56:29.000Z
examples/boxbash/BoxCommands.cpp
slashdotted/dropboxQt
63d43fa882cec8fb980a2aab2464a2d7260b8089
[ "MIT" ]
8
2017-09-13T17:28:40.000Z
2020-07-27T00:41:44.000Z
#include <iostream> #include <functional> #include <QBuffer> #include <QFile> #include <QFileInfo> #include "BoxCommands.h" #include "dropbox/DropboxClient.h" #include "dropbox/files/FilesRoutes.h" #include "dropbox/users/UsersRoutes.h" using namespace dropboxQt; BoxCommands::BoxCommands(DropboxClient& c):m_c(c) { m_curr_dir = "/"; }; void BoxCommands::printLastApiCall() { //uncomment to see HTTP request /* std::cout << "-----------------------------------------" << std::endl; std::cout << "API call" << std::endl; std::cout << m_c.lastApiCall().toStdString() << std::endl; */ }; void BoxCommands::account(QString) { try { std::unique_ptr<users::FullAccount> accountInfo = m_c.getUsers()->getCurrentAccount(); std::cout << accountInfo->toString().toStdString() << std::endl; printLastApiCall(); } catch(DropboxException& e) { std::cout << "Exception: " << e.what() << std::endl; } }; void BoxCommands::printFileInfo(files::Metadata* md) { files::FileMetadata* asFile = dynamic_cast<files::FileMetadata*>(md); if(asFile != NULL){ std::cout << "FILE id=" << asFile->id().toStdString() << " size=" << asFile->size() << std::endl; } else{ files::FolderMetadata* asFolder = dynamic_cast<files::FolderMetadata*>(md); if(asFolder != NULL){ std::cout << "FOLDER id=" << asFolder->id().toStdString() << std::endl; } } std::cout << md->toString().toStdString() << std::endl; }; void BoxCommands::info(QString fileName) { try { std::unique_ptr<files::Metadata> md = m_c.getFiles()->getMetadata(m_curr_dir + fileName); printFileInfo(md.get()); printLastApiCall(); } catch(DropboxException& e) { std::cout << "Exception: " << e.what() << std::endl; } }; void BoxCommands::info_async(QString fileName) { DropboxTask<files::Metadata>* t = m_c.getFiles()->getMetadata_Async(m_curr_dir + fileName); try { std::unique_ptr<files::Metadata> md = t->waitForResultAndRelease(); std::cout << "async-result" << std::endl; printFileInfo(md.get()); printLastApiCall(); } catch(DropboxException& e) { std::cout << "Exception: " << e.what() << std::endl; } }; void BoxCommands::pwd(QString) { std::cout << m_curr_dir.toStdString() << std::endl; }; void BoxCommands::ls(QString) { try { QString path = m_curr_dir; if(path.compare("/") == 0) { path = ""; } files::ListFolderArg arg(path); std::unique_ptr<files::ListFolderResult> r = m_c.getFiles()->listFolder(arg); std::function<void(const std::unique_ptr<files::ListFolderResult>& r)> print_folder_entries = [&](const std::unique_ptr<files::ListFolderResult>& r) { const std::list<std::unique_ptr<files::Metadata>>& entries = r->entries(); for(std::list<std::unique_ptr<files::Metadata>>::const_iterator i = entries.cbegin(); i != entries.cend(); i++) { const std::unique_ptr<files::Metadata>& m = *i; std::cout << m->name().toStdString() << std::endl; // std::cout << m->toString().toStdString() << std::endl; } }; print_folder_entries(r); while(r->hasMore()) { files::ListFolderContinueArg continue_arg(r->cursor()); r = m_c.getFiles()->listFolderContinue(continue_arg); print_folder_entries(r); } printLastApiCall(); } catch(DropboxException& e) { std::cout << "Exception: " << e.what() << std::endl; } }; void BoxCommands::mkdir(QString path) { if(path.isEmpty()){ std::cout << "ERROR argument reguired" << std::endl; return; } try { files::CreateFolderArg arg(m_curr_dir + path); std::unique_ptr<files::FolderMetadata> res = m_c.getFiles()->createFolder(arg); std::cout << "created: " << path.toStdString() << " id=" << res->id().toStdString() << std::endl; printLastApiCall(); } catch(DropboxException& e) { std::cout << "Exception: " << e.what() << std::endl; } }; void BoxCommands::cat(QString fileName) { if(fileName.isEmpty()){ std::cout << "ERROR argument reguired" << std::endl; return; } QByteArray byteArray; QBuffer buffer(&byteArray); buffer.open(QIODevice::WriteOnly); try { files::DownloadArg d(m_curr_dir + fileName); std::unique_ptr<files::FileMetadata> md = m_c.getFiles()->download(d, &buffer); std::cout << byteArray.constData(); printLastApiCall(); } catch(DropboxException& e) { std::cout << "Exception: " << e.what() << std::endl; } buffer.close(); }; void BoxCommands::cd(QString dirName) { if(dirName.isEmpty()){ std::cout << "ERROR argument reguired" << std::endl; return; } try { QString newPath = m_curr_dir + dirName; if(dirName[0] == '/') { //absolute path newPath = dirName; } else { if(dirName == "..") { if(m_curr_dir != "/") { int idx = newPath.lastIndexOf("/", -4); if(idx != -1) { newPath.remove(idx, newPath.size()); } } else { std::cout << "root folder" << std::endl; return; } } } m_curr_dir = newPath; if(m_curr_dir.length() == 0 || m_curr_dir[m_curr_dir.length() - 1] != '/') m_curr_dir += "/"; printLastApiCall(); ls(""); } catch(DropboxException& e) { std::cout << "Exception: " << e.what() << std::endl; } }; void BoxCommands::put(QString fileName) { if(fileName.isEmpty()){ std::cout << "ERROR argument reguired" << std::endl; return; } QFile file_in(fileName); if(!file_in.open(QFile::ReadOnly)){ std::cout << "Error opening file: " << fileName.toStdString() << std::endl; return; } QFileInfo fi(fileName); QString doxFileName = fi.fileName(); try { files::CommitInfo arg(m_curr_dir + doxFileName); std::unique_ptr<files::Metadata> res = m_c.getFiles()->upload(arg, &file_in); std::cout << "file uploaded" << std::endl; std::cout << res->toString().toStdString() << std::endl; printLastApiCall(); } catch(DropboxException& e) { std::cout << "Exception: " << e.what() << std::endl; } file_in.close(); }; void BoxCommands::get(QString fileName) { if (fileName.isEmpty()){ std::cout << "ERROR argument reguired" << std::endl; return; } QFile out(fileName); if (!out.open(QFile::WriteOnly | QIODevice::Truncate)){ std::cout << "Error opening file: " << fileName.toStdString() << std::endl; return; } try { files::DownloadArg arg(m_curr_dir + fileName); std::unique_ptr<files::Metadata> res = m_c.getFiles()->download(arg, &out); std::cout << "file downloaded" << std::endl; std::cout << res->toString().toStdString() << std::endl; printLastApiCall(); } catch (DropboxException& e) { std::cout << "Exception: " << e.what() << std::endl; } out.close(); }; void BoxCommands::rm(QString fileName) { if(fileName.isEmpty()){ std::cout << "ERROR argument reguired" << std::endl; return; } std::string confirm_str; std::cout << "Please type 'yes' to confirm deleting " << fileName.toStdString() << " >"; std::cin >> confirm_str; if(confirm_str != "yes") return; try { files::DeleteArg d(m_curr_dir + fileName); std::unique_ptr<files::Metadata> md = m_c.getFiles()->deleteOperation(d); std::cout << "deleted"; std::cout << md->toString().toStdString(); printLastApiCall(); } catch(DropboxException& e) { std::cout << "Exception: " << e.what() << std::endl; } };
29.741214
160
0.486948
slashdotted
ef8ae52f7f3e079105846a97a40d5663f0fd20e8
1,957
cpp
C++
ScheduleOptimisation/LayoutPlanning/LayoutPlanningCP/LayoutPlanningCP/Rectangle.cpp
encosoftware/ifps
f246abb8c4c9e0aa700c2dfb657f639410b5e861
[ "MIT" ]
null
null
null
ScheduleOptimisation/LayoutPlanning/LayoutPlanningCP/LayoutPlanningCP/Rectangle.cpp
encosoftware/ifps
f246abb8c4c9e0aa700c2dfb657f639410b5e861
[ "MIT" ]
null
null
null
ScheduleOptimisation/LayoutPlanning/LayoutPlanningCP/LayoutPlanningCP/Rectangle.cpp
encosoftware/ifps
f246abb8c4c9e0aa700c2dfb657f639410b5e861
[ "MIT" ]
null
null
null
#include "Rectangle.hpp" namespace operations_research { bool Rectangle::DescArea(const Rectangle &a, const Rectangle &b) { return a.Area > b.Area; } bool Rectangle::AscOrder(const Rectangle &a, const Rectangle &b) { // TODO - by deadline! return a.OrderGuid < b.OrderGuid; } void Rectangle::Print(std::ofstream& ofile, sat::CpSolverResponse result, int type, int comp_n, std::string order_guid) { int left = sat::SolutionIntegerValue(result, X.StartVar()); int width = sat::SolutionIntegerValue(result, X.SizeVar()); int top = sat::SolutionIntegerValue(result, Y.StartVar()); int height = sat::SolutionIntegerValue(result, Y.SizeVar()); std::string area_type = ""; if (type == 1) { area_type = "component"; } else if (type == 2) { area_type = "border"; } else if (type == 3) { area_type = "leftover"; } else { LOG(ERROR) << "Unknown type!" << std::endl; } ofile << "<div class='" + area_type + "' style='left:" + std::to_string(left) + "px; width:" + std::to_string(width) + "px; top:" + std::to_string(top) + "px; height:" + std::to_string(height) + "px;'>" + Name + "&nbsp;&nbsp;&nbsp;</br><b>Num:" + std::to_string(comp_n) + ".</b></br>ORDER: " + order_guid + "</div>"; } int Rectangle::CalculateBoardNum(sat::CpSolverResponse result, int w_board) { int x_end = sat::SolutionIntegerValue(result, X.EndVar()); int bn = std::floor(x_end / (w_board + 1)); return bn; } json Rectangle::ToJson(sat::CpSolverResponse result, int bn, int w_board) { int tlx = sat::SolutionIntegerValue(result, X.StartVar()) - bn * w_board - bn; int tly = sat::SolutionIntegerValue(result, Y.StartVar()); int w = sat::SolutionIntegerValue(result, X.SizeVar()); int l = sat::SolutionIntegerValue(result, Y.SizeVar()); json cutting = { { "topLeftX", tlx }, { "topLeftY", tly }, { "width", w }, { "length", l}, { "componentId", ComponentId } }; return cutting; } }
29.208955
151
0.638222
encosoftware
ef90a0129a6ee2140f0d1e45375aa5bc0a6f51fc
4,188
cc
C++
src/xzero/JsonWriter.cc
pjsaksa/x0
96b69e5a54b006e3d929b9934c2708f7967371bb
[ "MIT" ]
24
2016-07-10T08:05:11.000Z
2021-11-16T10:53:48.000Z
src/xzero/JsonWriter.cc
pjsaksa/x0
96b69e5a54b006e3d929b9934c2708f7967371bb
[ "MIT" ]
14
2015-04-12T10:45:26.000Z
2016-06-28T22:27:50.000Z
src/xzero/JsonWriter.cc
pjsaksa/x0
96b69e5a54b006e3d929b9934c2708f7967371bb
[ "MIT" ]
4
2016-10-05T17:51:38.000Z
2020-04-20T07:45:23.000Z
// This file is part of the "x0" project, http://github.com/christianparpart/x0> // (c) 2009-2018 Christian Parpart <christian@parpart.family> // // Licensed under the MIT License (the "License"); you may not use this // file except in compliance with the License. You may obtain a copy of // the License at: http://opensource.org/licenses/MIT #include <xzero/JsonWriter.h> #include <xzero/Buffer.h> #include <atomic> namespace xzero { JsonWriter::JsonWriter(Buffer* output) : output_(*output), stack_() { } void JsonWriter::indent() { for (size_t i = 0, e = stack_.size(); i != e; ++i) { output_.push_back(" "); } } void JsonWriter::begin(Type t) { if (!stack_.empty()) { if (fieldCount() > 0) { output_ << ",\n"; } else if (isArray() && fieldCount() == 0) { output_ << "\n"; } indent(); incrementFieldCount(); } push(t); } void JsonWriter::preValue() { if (isComplex()) { if (fieldCount() > 0) { // i.e. Array output_ << ",\n"; } else { output_ << "\n"; } indent(); } incrementFieldCount(); } void JsonWriter::postValue() { if (isValue()) { pop(); } } JsonWriter& JsonWriter::name(const std::string& name) // "$NAME": { begin(Type::Value); output_ << "\"" << name << "\": "; return *this; } JsonWriter& JsonWriter::beginObject(const std::string& name) // { ... } { if (!name.empty()) { begin(Type::Object); output_ << "\"" << name << "\": {\n"; } else { if (isValue()) { stack_.back().type = Type::Object; } else { begin(Type::Object); } output_ << "{\n"; } return *this; } JsonWriter& JsonWriter::endObject() { output_ << "\n"; pop(); indent(); output_ << "}"; return *this; } JsonWriter& JsonWriter::beginArray(const std::string& name) // [ ... ] { begin(Type::Array); if (!name.empty()) output_ << "\"" << name << "\": ["; else output_ << "["; return *this; } JsonWriter& JsonWriter::endArray() { output_ << "\n"; pop(); indent(); output_ << "]"; return *this; } template<> JsonWriter& JsonWriter::value(const bool& value) { preValue(); buffer() << (value ? "true" : "false"); postValue(); return *this; } template<> JsonWriter& JsonWriter::value(const char& value) { preValue(); buffer() << '"' << value << '"'; postValue(); return *this; } template<> JsonWriter& JsonWriter::value(const int& value) { preValue(); buffer() << value; postValue(); return *this; } template<> JsonWriter& JsonWriter::value(const long& value) { preValue(); buffer() << value; postValue(); return *this; } template<> JsonWriter& JsonWriter::value(const long long& value) { preValue(); buffer() << value; postValue(); return *this; } template<> JsonWriter& JsonWriter::value(const unsigned int& value) { preValue(); buffer() << value; postValue(); return *this; } template<> JsonWriter& JsonWriter::value(const unsigned long& value) { preValue(); buffer() << value; postValue(); return *this; } template<> JsonWriter& JsonWriter::value(const unsigned long long& value) { preValue(); buffer() << value; postValue(); return *this; } template<> JsonWriter& JsonWriter::value(const float& value) { preValue(); char buf[128]; ssize_t n = snprintf(buf, sizeof(buf), "%f", value); buffer().push_back(buf, n); postValue(); return *this; } template<> JsonWriter& JsonWriter::value(const std::string& value) { preValue(); buffer() << '"' << value << '"'; postValue(); return *this; } template<> JsonWriter& JsonWriter::value(const Buffer& value) { preValue(); buffer() << '"' << value << '"'; postValue(); return *this; } template<> JsonWriter& JsonWriter::value(const BufferRef& value) { preValue(); buffer() << '"' << value << '"'; postValue(); return *this; } template<> JsonWriter& JsonWriter::value(const char* const& value) { buffer() << '"' << value << '"'; postValue(); return *this; } template<> JsonWriter& JsonWriter::value(const std::atomic<unsigned long long>& value) { preValue(); buffer() << value.load(); postValue(); return *this; } } // namespace xzero
18.208696
80
0.594317
pjsaksa
ef91ec9db472e83f4768cc030a08a16dac4cab4d
289
cpp
C++
ListV2/List.cpp
Tientuine/mccs-cpp-lists
580d965c7a95b7c30c570a2133ba8d07b98b356d
[ "MIT" ]
null
null
null
ListV2/List.cpp
Tientuine/mccs-cpp-lists
580d965c7a95b7c30c570a2133ba8d07b98b356d
[ "MIT" ]
null
null
null
ListV2/List.cpp
Tientuine/mccs-cpp-lists
580d965c7a95b7c30c570a2133ba8d07b98b356d
[ "MIT" ]
null
null
null
#ifndef HPP_PRELUDE_LIST #define HPP_PRELUDE_LIST #include <tuple> #include <memory> /** * Implementation of Haskell-like, functional programming idioms, particularly recursive Lists. */ namespace prelude { template <typename T> using List = std::pair<T,std::shared_ptr<List<T>>; }
17
95
0.750865
Tientuine
ef92cb44e5e6bfdf027572e46c182958765f0894
873
cpp
C++
61-70/61. Rotate List.cpp
zzuliLL/Leetcode-
a14fe1188da008a39d7aaf4e142ee582493b7c60
[ "MIT" ]
null
null
null
61-70/61. Rotate List.cpp
zzuliLL/Leetcode-
a14fe1188da008a39d7aaf4e142ee582493b7c60
[ "MIT" ]
null
null
null
61-70/61. Rotate List.cpp
zzuliLL/Leetcode-
a14fe1188da008a39d7aaf4e142ee582493b7c60
[ "MIT" ]
null
null
null
//如果k大于链表长度时,应该旋转 k%len //一个快指针,一个慢指针,快的指针比慢的先走k个,这样当快的指针走到NULL时,慢的刚好是倒数第k个 /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* rotateRight(ListNode* head, int k) { if(!head || !head->next) return head; ListNode *p, *q; p = q = head; int len = 0; while(p) { p = p->next; len++; } k %= len; if(k == 0) return head; p = head; while(p && k--) { p = p->next; } if(!p) return head; while(p->next) { p = p->next; q = q->next; } ListNode *cur = q->next; q->next = NULL; p->next = head; return cur; } };
21.292683
51
0.43299
zzuliLL
ef92cc7777eb61a431d69abde8fbd4c3f6d262fb
2,009
hpp
C++
include/srutil/event/event.hpp
Offirmo/impossibly-fast-delegates
ca81204601ef7aef030bd6b8d52bb9fe06676575
[ "MIT" ]
9
2015-08-31T02:28:27.000Z
2021-06-22T16:13:32.000Z
include/srutil/event/event.hpp
Offirmo/impossibly-fast-delegates
ca81204601ef7aef030bd6b8d52bb9fe06676575
[ "MIT" ]
7
2015-11-27T16:34:42.000Z
2016-05-07T18:29:24.000Z
include/srutil/event/event.hpp
Offirmo/impossibly-fast-delegates
ca81204601ef7aef030bd6b8d52bb9fe06676575
[ "MIT" ]
1
2016-12-31T03:59:46.000Z
2016-12-31T03:59:46.000Z
/* (c) Sergey Ryazanov (http://home.onego.ru/~ryazanov) Fast delegate compatible with C++ Standard. */ #ifndef SRUTIL_EVENT_INCLUDED #define SRUTIL_EVENT_INCLUDED namespace srutil { template <typename TSink> class event_source; template <typename TSink> class event_binder; template <typename TSink> class event_binder { public: typedef TSink sink_type; typedef event_source<sink_type> event_source_type; event_binder() : sink(sink_type()) {next = prev = this;} ~event_binder() {unbind();} void bind(const event_source<sink_type>& source, sink_type sink); void unbind() { prev->next = next; next->prev = prev; next = prev = this; } private: event_binder* prev; event_binder* next; sink_type sink; friend class event_source<sink_type>; void attach_after(event_binder* that) { next = that->next; next->prev = this; that->next = this; prev = that; } event_binder(event_binder const&); event_binder const& operator=(event_binder const&); }; template <typename TSink> class event_source { public: typedef TSink sink_type; typedef event_binder<sink_type> binder_type; void bind(binder_type& bndr, sink_type sink) { bndr.attach_after(&list_head); bndr.sink = sink; } template <class TInvoker> void emit(TInvoker const& invoker) { binder_type* current = list_head.next; while (current != &list_head) { if (current->sink) { event_binder<sink_type> bookmark; bookmark.attach_after(current); invoker(current->sink); // *current may be excluded from list, but mookmark will always keep valid current = bookmark.next; } else current = current->next; } } private: mutable binder_type list_head; friend class event_binder<sink_type>; }; template <typename TSink> void event_binder<TSink>::bind(const event_source<sink_type>& source, sink_type sink) { unbind(); attach_after(&source.list_head); this->sink = sink; } } #endif// SRUTIL_EVENT_INCLUDED
21.37234
103
0.699353
Offirmo
ef978feccc4c5c1a0d45253580712810a59e3e6f
64
cpp
C++
kernel/cpuid.cpp
leakingmemory/jeokernel
7c2413921cc2d30eef2b340de4efed66d41afeb1
[ "MIT" ]
null
null
null
kernel/cpuid.cpp
leakingmemory/jeokernel
7c2413921cc2d30eef2b340de4efed66d41afeb1
[ "MIT" ]
null
null
null
kernel/cpuid.cpp
leakingmemory/jeokernel
7c2413921cc2d30eef2b340de4efed66d41afeb1
[ "MIT" ]
null
null
null
// // Created by sigsegv on 26.04.2021. // #include <cpuid.h>
9.142857
36
0.609375
leakingmemory
aab74e9706bc8e4278c879ea789dd97b0c413a4c
1,132
cpp
C++
D01/ex05/Human.cpp
amoinier/piscine-cpp
43d4806d993eb712f49a32e54646d8c058a569ea
[ "MIT" ]
null
null
null
D01/ex05/Human.cpp
amoinier/piscine-cpp
43d4806d993eb712f49a32e54646d8c058a569ea
[ "MIT" ]
null
null
null
D01/ex05/Human.cpp
amoinier/piscine-cpp
43d4806d993eb712f49a32e54646d8c058a569ea
[ "MIT" ]
null
null
null
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Human.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: amoinier <amoinier@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/10/03 12:40:26 by amoinier #+# #+# */ /* Updated: 2017/10/03 13:48:35 by amoinier ### ########.fr */ /* */ /* ************************************************************************** */ #include "Human.hpp" Human::Human() : brain(Brain()) { return ; } Human::~Human() { return ; } Brain const & Human::getBrain() const { return this->brain; } std::string Human::identify(void) const { return this->brain.identify(); }
33.294118
80
0.225265
amoinier
aabf91638663ae968b12400a15a1232138299afc
9,824
cpp
C++
PyMieSim/includes/LMT/Cylinder.cpp
MartinPdS/PyMieSim
2560c7f4009df5d05bcb0ce8e929aa7baa7be8de
[ "MIT" ]
6
2021-02-11T17:53:40.000Z
2021-12-11T20:20:01.000Z
PyMieSim/includes/LMT/Cylinder.cpp
MartinPdS/PyMieSim
2560c7f4009df5d05bcb0ce8e929aa7baa7be8de
[ "MIT" ]
6
2021-05-12T04:33:26.000Z
2021-11-14T05:25:19.000Z
PyMieSim/includes/LMT/Cylinder.cpp
MartinPdS/PyMieSim
2560c7f4009df5d05bcb0ce8e929aa7baa7be8de
[ "MIT" ]
3
2021-05-10T19:46:42.000Z
2021-06-01T19:52:14.000Z
#ifndef CYLINDER_H #define CYLINDER_H #include "includes/SpecialFunc.h" #include "includes/utils.h" #include "includes/BaseScatterer.hpp" #include "includes/States.hpp" namespace CYLINDER { struct State : public BaseState { State(){}; State(const double &Wavelength, const double &Amplitude, const double &Diameter, const complex128 &Index, const double &nMedium, const CVector &Jones ) : BaseState(Wavelength, Amplitude, nMedium, Jones ), Diameter(Diameter), Index(Index) { this->k = 2 * PI / Wavelength; this->SizeParameter = PI * Diameter / Wavelength; this->MaxOrder = (size_t) (2 + SizeParameter + 4 * pow(SizeParameter,1./3.)) + 16; }; double Diameter; complex128 Index; }; struct VState { std::vector<State> Buffer; std::vector<size_t> Shape; size_t Size; State& operator[](size_t index){ return Buffer[index]; } void push_back(const State &state) { Buffer.push_back(state);} }; class Scatterer: public BaseScatterer{ private: void AnBn(); void CnDn(){}; public: CVector an1, an2, bn1, bn2; State state; void ComputeQsca() override; void ComputeQext() override; void ComputeG(); static VState MakeIterator(PyState &Pystate), MakeIteratorNotBound(PyState &Pystate), MakeIteratorBound(PyState &Pystate); std::tuple<CVector, CVector> S1S2(const DVector &Phi); Scatterer(const double &Wavelength, const double &Amplitude, const double &Diameter, const complex128 &Index, const double &nMedium, const CVector &Jones ) : Scatterer(State( Wavelength, Amplitude, Diameter, Index, nMedium, Jones)) {} Scatterer(const State &state) : state(state), BaseScatterer(state){CrossSection = state.Diameter;} void Print(){std::cout<<"\tWavelength: " <<state.Wavelength << "\n" <<"\tDiameter: " <<state.Diameter << "\n" <<"\tIndex: " <<state.Index << "\n" << "\tnMedium: " <<state.nMedium << "\n" << "\tAmplitude: " <<state.Amplitude << "\n" << "\tMaxOrder: " <<state.MaxOrder << "\n" << "\tSizeParameter: " <<state.SizeParameter << "\n";} }; void Scatterer::ComputeG() { ComputeGWithFields(1000, 1.0); } void Scatterer::ComputeQsca() { ComputeAnBn(); complex128 Qsca1=0, Qsca2=0; for(size_t it = 1; it < state.MaxOrder; it++) { Qsca1 += pow( std::abs(an1[it]), 2) + pow( std::abs(bn1[it]), 2) ; Qsca2 += pow( std::abs(an2[it]), 2) + pow( std::abs(bn2[it]), 2) ; } Qsca1 = 2. / state.SizeParameter * ( 2.0 * Qsca1 + pow( abs(bn1[0]), 2 ) ); Qsca2 = 2. / state.SizeParameter * ( 2.0 * Qsca2 + pow( abs(an2[0]), 2 ) ); Qsca = abs( Qsca2 ) * pow(abs(state.Jones[1]), 2) + abs( Qsca1 ) * pow(abs(state.Jones[1]), 2); } void Scatterer::ComputeQext() { ComputeAnBn(); complex128 Qext1=0, Qext2=0; for(size_t it = 1; it < state.MaxOrder; ++it) { Qext1 += bn1[it]; Qext2 += an2[it]; } Qext1 = 2. / state.SizeParameter * std::real( bn1[0] + 2.0 * Qext1 ); Qext2 = 2. / state.SizeParameter * std::real( an1[0] + 2.0 * Qext2 ); if (state.Polarization == 4242.) Qext = 0.5 * ( abs( Qext2 ) + abs( Qext1 ) ); else Qext = abs( Qext2 ) * pow(abs(state.Jones[1]), 2) + abs( Qext1 ) * pow(abs(state.Jones[1]), 2); } void Scatterer::AnBn() { an1.reserve(state.MaxOrder); an2.reserve(state.MaxOrder); bn1.reserve(state.MaxOrder); bn2.reserve(state.MaxOrder); double x = state.SizeParameter; complex128 m = state.Index / state.nMedium; complex128 z = m*x; complex128 numerator, denominator; CVector JVectorZ(state.MaxOrder+1), JVectorZp(state.MaxOrder+1), JVectorX(state.MaxOrder+1), JVectorXp(state.MaxOrder+1), HVectorX(state.MaxOrder+1), HVectorXp(state.MaxOrder+1); for (size_t n = 0; n < state.MaxOrder+1; ++n) { double nd = (double) n ; JVectorZ[n] = F90Jn(nd, z); JVectorZp[n] = F90Jn_p(nd, z); JVectorX[n] = F90Jn(nd, x); JVectorXp[n] = F90Jn_p(nd, x); HVectorX[n] = F90H1(nd, x); HVectorXp[n] = F90H1_p(nd, x); } for (size_t n = 0; n < (size_t) state.MaxOrder; n++) { numerator = m * JVectorZ[n] * JVectorXp[n] - JVectorZp[n] * JVectorX[n]; denominator = m * JVectorZ[n] * HVectorXp[n] - JVectorZp[n] * HVectorX[n]; an1.push_back( 0.0 ); an2.push_back( numerator/denominator ); numerator = JVectorZ[n] * JVectorXp[n] - m * JVectorZp[n] * JVectorX[n]; denominator = JVectorZ[n] * HVectorXp[n] - m * JVectorZp[n] * HVectorX[n]; bn1.push_back( numerator/denominator ); bn2.push_back( 0.0 ); } } std::tuple<CVector, CVector> Scatterer::S1S2(const DVector &Phi) { CVector T1(Phi.size()), T2(Phi.size()); ComputeAnBn(); for (uint i = 0; i < Phi.size(); i++){ T1[i] = bn1[0]; T2[i] = an2[0]; for (size_t order = 1; order < state.MaxOrder ; order++){ T1[i] += 2.0*bn1[order] * cos(order * (PI - (Phi[i]+PI/2.0) ) ); T2[i] += 2.0*an2[order] * cos(order * (PI - (Phi[i]+PI/2.0) ) ); } } return std::make_tuple( T1, T2 ) ; } VState Scatterer::MakeIterator(PyState &Pystate) { if (Pystate.Material) return MakeIteratorBound(Pystate); else return MakeIteratorNotBound(Pystate); } VState Scatterer::MakeIteratorNotBound(PyState &Pystate) { VState state; state.Shape = {Pystate.Wavelength.size(), Pystate.Jones.size()/2, Pystate.Amplitude.size(), Pystate.Diameter.size(), Pystate.Index.size(), Pystate.nMedium.size()}; state.Size = 1; for (auto v : state.Shape) state.Size *= v; state.Buffer.reserve(state.Size); for (auto w : Pystate.Wavelength) for (size_t j=0; j<Pystate.Jones.size(); j+=2) for (auto e : Pystate.Amplitude) for (auto d : Pystate.Diameter) for (auto i : Pystate.Index) for (auto n : Pystate.nMedium) { CVector jones = {Pystate.Jones[j], Pystate.Jones[j+1]}; state.push_back( State(w, e, d, i, n, jones) ) ; } return state; } VState Scatterer::MakeIteratorBound(PyState &Pystate) { VState state; size_t MaterialSize = Pystate.Index.size()/Pystate.Wavelength.size(); state.Shape = {Pystate.Wavelength.size(), Pystate.Jones.size()/2, Pystate.Amplitude.size(), Pystate.Diameter.size(), MaterialSize, Pystate.nMedium.size()}; state.Size = 1; for (auto v : state.Shape) state.Size *= v; state.Buffer.reserve(state.Size); for (size_t w=0; w<Pystate.Wavelength.size(); w++) for (size_t j=0; j<Pystate.Jones.size(); j+=2) for (auto e : Pystate.Amplitude) for (auto d : Pystate.Diameter) for (size_t i=0; i<MaterialSize; i++) for (auto n : Pystate.nMedium) { double wavelength = Pystate.Wavelength[w]; complex128 index = Pystate.Index[w + Pystate.Wavelength.size()*i]; CVector jones = {Pystate.Jones[j], Pystate.Jones[j+1]}; state.push_back( State( wavelength, e, d, index, n, jones) ) ; } return state; } } #endif // void // Scatterer::AnBn() // { // an2.reserve(state.MaxOrder); // bn1.reserve(state.MaxOrder); // // an1.reserve(state.MaxOrder); // bn2.reserve(state.MaxOrder); // // double x = state.SizeParameter; // complex128 m = state.Index / state.nMedium; // complex128 z = m*x; // // size_t nmx = std::max( state.MaxOrder, (size_t) std::abs(z) ) + 15; // // CVector Dn = VSH::CYLINDRICAL::ComputeDn(nmx, z); // // CVector JVector(state.MaxOrder+1), HVector(state.MaxOrder+1); // // for (size_t n = 0; n < state.MaxOrder+1; ++n) // { // double nd = (double) n ; // JVector[n] = F90Jn(nd, x); // HVector[n] = F90H1(nd, x); // } // // complex128 numerator, denominator; // // numerator = m * F90Jn(0, z) * F90Jn_p(0, x) - F90Jn_p(0, z) * F90Jn(0, x); // denominator = m * F90Jn(0, z) * F90H1_p(0, x) - F90Jn_p(0, z) * F90H1(0, x); // // an1.push_back(0.0); // an2.push_back( numerator/denominator ); // // numerator = F90Jn(0, z) * F90Jn_p(0, x) - m * F90Jn_p(0, z) * F90Jn(0, x); // denominator = F90Jn(0, z) * F90H1_p(0, x) - m * F90Jn_p(0, z) * F90H1(0, x); // // bn1.push_back( numerator/denominator ); // bn2.push_back(0.0); // // // for (size_t n = 1; n < state.MaxOrder; ++n) // { // double nd = (double) n ; // // complex128 term1 = ( Dn[n-1]/m + nd/x ); // complex128 term0 = ( Dn[n-1]*m + nd/x ); // an1.push_back(0.0); // an2.push_back( ( term0 * JVector[n] - JVector[n-1] ) \ // / ( term0 * HVector[n] - HVector[n-1] ) ); // // bn1.push_back( ( term1 * JVector[n] - JVector[n-1] ) \ // / ( term1 * HVector[n] - HVector[n-1] ) ); // // bn2.push_back(0.0); // } // // }
26.408602
102
0.531963
MartinPdS
aabfc00c49b8c600b1620723baa6f732709f2338
11,463
cpp
C++
exodus/libexodus/exodus/naturalorder.cpp
rdmenezes/exodusdb
f732e366b74ff4697890ec0682bc3697b8cb0bfb
[ "MIT" ]
null
null
null
exodus/libexodus/exodus/naturalorder.cpp
rdmenezes/exodusdb
f732e366b74ff4697890ec0682bc3697b8cb0bfb
[ "MIT" ]
null
null
null
exodus/libexodus/exodus/naturalorder.cpp
rdmenezes/exodusdb
f732e366b74ff4697890ec0682bc3697b8cb0bfb
[ "MIT" ]
null
null
null
//copied in pgexodus and exodus - please keep in sync 1 #include <cstring> #include <sstream> #include <cassert> namespace exodus { //select exodus_extract_text(data,1,0,0), exodus_extract_sort(data,1,0,0) //from test_alphanum order by exodus_extract_sort(data,1,0,0) /* lexicographical sorting of numbers We wish to be able to sort a report on an alphanumeric column and for the numbers to be sorted numerically and the non-numerics to be sorted alphabetically eg 2,10,A,B. We expect the classic pick behaviour and not be forced into alphabetic sorting of numbers eg 10,2. If possible we also wish mixed alphanumerics to be sorted reasonably eg A2,A10 (ie not A10,A2). NB the following is based on 32 bit ints and floats but the same techniques can be applied to 64 bit doubles, mapping them to some 64-bit ints like long long int. long int http://en.wikipedia.org/wiki/Long_integer long long int is from C99 and is required to be at least 64 bits http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm The IEEE float and double formats were designed so that the numbers are lexicographically ordered, which in the words of IEEE architect William Kahan means if two floating-point numbers in the same format are ordered (say x < y ), then they are ordered the same way when their bits are reinterpreted as Sign-Magnitude integers. This means that if we take two floats in memory, interpret their bit pattern as integers, and compare them, we can tell which is larger, without doing a floating point comparison. In the C/C++ language this comparison looks like this: if (*(int*)&f1 < *(int*)&f2) This charming syntax means take the address of f1, treat it as an integer pointer, and dereference it. All those pointer operations look expensive, but they basically all cancel out and just mean treat f1 as an integer. Since we apply the same syntax to f2 the whole line means compare f1 and f2, using their in-memory representations interpreted as integers instead of floats. Kahan says that we can compare them if we interpret them as sign-magnitude integers. Thats unfortunate because most processors these days use twos-complement integers. Effectively this means that the comparison only works if one or more of the floats is positive. If both floats are negative then the sense of the comparison is reversed the result will be the opposite of the equivalent float comparison. Later we will see that there is a handy technique for dealing with this inconvenience. int aInt = *(int*)&A; // Make aInt lexicographically ordered as a twos-complement int (or 0x8000000000000000 for double) if (aInt < 0) //nb 0x800000000000000000LL on 64bit aInt = 0x80000000 - aInt; Compiler issues In our last version of AlmostEqualUlps we use pointers and casting to tell the compiler to treat the in-memory representation of a float as an int. There are a couple of things that can go wrong with this. One risk is that int and float might not be the same size. A float should be 32 bits, but an int can be almost any size. This is certainly something to be aware of, but every modern compiler that I am aware of has 32-bit ints. If your compiler has ints of a different size, find a 32-bit integral type and use it instead. Another complication comes from aliasing optimizations. Strictly speaking the C/C++ standard says that the compiler can assume that different types do not overlap in memory (with a few exceptions such as char pointers). For instance, it is allowed to assume that a pointer to an int and a pointer to a float do not point to overlapping memory. This opens up lots of worthwhile optimizations, but for code that violates this rulewhich is quite commonit leads to undefined results. In particular, some versions of g++ default to very strict aliasing rules, and dont like the techniques used in AlmostEqualUlps. Luckily g++ knows that there will be a problem, and it gives this warning: warning: dereferencing type-punned pointer will break strict-aliasing rules There are two possible solutions if you encounter this problem. Turn off the strict aliasing option using the -fno-strict-aliasing switch, or use a union between a float and an int to implement the reinterpretation of a float as an int. The documentation for -fstrict-aliasing gives more information. Examples: hex int representation of some doubles - after inverting negatives so that "large" negatives sort before small negatives - and inverting the high bit so all negatives sort before all positives. // -5.0 3fec000000000000 // -4.0 3ff0000000000000 // -3.0 3ff8000000000000 // -2.0 4000000000000000 // -1.0 4010000000000000 // 0.0 8000000000000000 // 1.0 bff0000000000000 // 2.0 c000000000000000 // 3.0 c008000000000000 // 4.0 c010000000000000 // 5.0 c014000000000000 */ /* strategy The problem isnt just about sorting 10A and 2B correctly, it is about correctly sorting simple cases like 10, 2, A, and B as 2, 10, A, B ie mixed data but not mixed within any one field. All picks can do that because they have a type-less comparison operator > that works "correctly" on text and textual numbers. To avoid requiring the implementation of a proper pick comparison operator in every sql database that exodus uses in future, a function is provided that preprocesses a bit of text into a text that, when compared as ascii/unicode, produces the right result. Essentially this involves replacing all the numbers found in a string with a 16 hex digit representation of the number. This function must be called around all sorting and indexing fields and also on all filtering values passed like 'ABC' in "with xyz > 'ABC'". Since exodus build up the sql queries before each selection then the function can be built into the sql command. Note that selection on indexes built with natural order function in them must have the function matching in field and data when using the index. Note that in the conversion to 16 hex digits that all surplus zeroes are lost losing informaition. A proper comparison operator would be able to sort 001 before 1 but the current strategy cannot allow for this. NB all pick databases do text to floating point conversions on the fly since they store numbers as strings. This conversion-to-natural-order routine does a floating point conversion (but maybe for performance it should use the cpu's fp unit to do the job) The comparison then doesnt require an additional conversion to fp so the performance is perhaps ok for sorting pure numbers. Trailing E for exponent not supported at the moment. 2 < 10 .10 < .2 -20 < -1 2.0 = 2 02 = 2 ABC < BC Flat 2B < Flat 10A A-2 < A-10 dots and dashes within text dont imply negative/decimal points A -10 < A -2 unless prefixed by space A.2 < A.10 A .10 < A .2 A1.10 = A1.1 excess zeros are ignored in sorting A010 = A10 A1.0 = A1 A1-2 < A01-10 multi-level number sort */ void appenddouble2sortstring(const double& double1, std::ostringstream& stringstream1) { assert(sizeof(double) == sizeof(long long int)); //view the double as an 64 bit integer long long int integer1=*(long long int*) & double1; if (integer1<0) //invert the negative numbers and clear the high bit so that //lexicographically they sort in the right order and before the positive numbers integer1=0x8000000000000000LL-integer1+0x8000000000000000LL; else //set the high bit so that positive numbers appear lexicographically after the negative numbers integer1-=0x8000000000000000LL; //make leftmost digit a decimal so it sorts as a number instead of any chance hex a-f //put a 9 which sorts the same as 0 and removes the need for fill/width formatting below integer1=integer1>>4; integer1&=0x9fffffffffffffffLL; //hex output stringstream1.flags(std::ios::right|std::ios::hex); //needed if leftmost digit is zero //stringstream1.fill('0'); //stringstream1.width(16); stringstream1<<integer1; } std::string naturalorder(const std::string& string1) { //using goto here to break out of multiple embedded loops //since c/c++ break/continue is unable to do this std::ostringstream ostringstream1; std::string::const_iterator iter=string1.begin(); std::string::const_iterator iterend=string1.end(); double val; double power; naturalorderbegin: //must have one digit to pass as number //ie - + . -. +. are all not numbers bool hasdigit=false; //record the current position. in case the following characters dont constitute a proper number //then they will all be copied to the output as plain text std::string::const_iterator iterbegin=iter; //skip white space for (;;) { if (iter==iterend) goto naturalorderexit; if (!isspace(*iter)) break; ++iter; } //determine positive or negative and skip one leading + or - int sign; if (*iter == '-') { sign=-1; ++iter; } else if (*iter == '+') { sign=1; ++iter; } else sign=1; //get integer part val = 0.0; power = 1.0; //here in case there is no fractional part for (;;) { if (iter==iterend) goto naturalorderexit; if (!isdigit(*iter)) break; hasdigit=true; val = 10.0 * val + (*iter - '0'); ++iter; } //skip one decimal point if present after integer part if (*iter == '.') ++iter; //continue appending digits to the integer but recording progressive division by 10 for each one for (;;) { if (iter==iterend) goto naturalorderexit; if (!isdigit(*iter)) break; hasdigit=true; val = 10.0 * val + (*iter - '0'); power *= 10; ++iter; } naturalorderexit: if (hasdigit) { //leading zero to ensure that numbers sort in the usual sequence //(since the 16 character representation is hex with letters) //do this in the 16 digit //ostringstream1<<"0"; //append the 16 hex digit lexical sortable representation of the number appenddouble2sortstring(sign * val / power,ostringstream1); } else { //copy any characters that looked like they might be a number but in the end were not while (iterbegin!=iter) ostringstream1<<*iterbegin++; } //append any trailing non-numerical data while (iter!=iterend) { //go back and possibly output another number //NB - and . are NOT candidates to go back. this prevent strange effect like A-10 < A-2 //22.22.22 appearing like 22.22 and .22 //22-22-22 appearing like 22 -22 -22 //check low digits first since they are much commoner in practice as the starting digit of numbers const char* ptr=(strchr("1234567890 \"'+",*iter)); if (ptr!=0) { //also allow . - (or digits) after single or double quote to be considered as a number. if (*ptr=='"' || *ptr=='\'') { ostringstream1<<*iter++; if (iter==iterend) break; if (strchr("1234567890 .-+\"'",*iter)!=0) goto naturalorderbegin; } else goto naturalorderbegin; } ostringstream1<<*iter++; } // std::cout<<string1<<" --- "<<ostringstream1.str()<<std::endl; return ostringstream1.str(); } } //namespace exodus
38.083056
268
0.71299
rdmenezes
aac43fc55e1c4910fbb5cd63f4bcf17af02c5156
1,085
hpp
C++
hiro/core/widget/table-view-item.hpp
13824125580/higan
fbdd3f980b65412c362096579869ae76730e4118
[ "Intel", "ISC" ]
10
2019-12-19T01:19:41.000Z
2021-02-18T16:30:29.000Z
hiro/core/widget/table-view-item.hpp
13824125580/higan
fbdd3f980b65412c362096579869ae76730e4118
[ "Intel", "ISC" ]
null
null
null
hiro/core/widget/table-view-item.hpp
13824125580/higan
fbdd3f980b65412c362096579869ae76730e4118
[ "Intel", "ISC" ]
1
2021-03-22T16:15:30.000Z
2021-03-22T16:15:30.000Z
#if defined(Hiro_TableView) struct mTableViewItem : mObject { Declare(TableViewItem) auto alignment() const -> Alignment; auto append(sTableViewCell cell) -> type&; auto backgroundColor() const -> Color; auto cell(uint position) const -> TableViewCell; auto cellCount() const -> uint; auto cells() const -> vector<TableViewCell>; auto foregroundColor() const -> Color; auto remove() -> type& override; auto remove(sTableViewCell cell) -> type&; auto reset() -> type&; auto selected() const -> bool; auto setAlignment(Alignment alignment = {}) -> type&; auto setBackgroundColor(Color color = {}) -> type&; auto setFocused() -> type& override; auto setForegroundColor(Color color = {}) -> type&; auto setParent(mObject* parent = nullptr, int offset = -1) -> type& override; auto setSelected(bool selected = true) -> type&; //private: struct State { Alignment alignment; Color backgroundColor; vector<sTableViewCell> cells; Color foregroundColor; bool selected = false; } state; auto destruct() -> void override; }; #endif
31
79
0.687558
13824125580
aacc5c6302bffe27680b2bcb522a23b5a0ea2fae
933
cpp
C++
PAT_B/PAT_B1077.cpp
EnhydraGod/PATCode
ff38ea33ba319af78b3aeba8aa6c385cc5e8329f
[ "BSD-2-Clause" ]
3
2019-07-08T05:20:28.000Z
2021-09-22T10:53:26.000Z
PAT_B/PAT_B1077.cpp
EnhydraGod/PATCode
ff38ea33ba319af78b3aeba8aa6c385cc5e8329f
[ "BSD-2-Clause" ]
null
null
null
PAT_B/PAT_B1077.cpp
EnhydraGod/PATCode
ff38ea33ba319af78b3aeba8aa6c385cc5e8329f
[ "BSD-2-Clause" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int n, m, teaScore, tempScore, minScore, maxScore, tempCount; double totalScore, tempTotScore; int main() { scanf("%d%d", &n, &m); for (int i = 0; i < n; i++) { totalScore = tempTotScore = 0; minScore = m + 1; maxScore = -1; tempCount = 0; scanf("%d", &teaScore); for(int i = 1; i < n; i++) { scanf("%d", &tempScore); if(tempScore < 0 || tempScore > m) continue; tempTotScore += tempScore; tempCount++; if(tempScore < minScore) minScore = tempScore; if(tempScore > maxScore) maxScore = tempScore; } tempTotScore = 1.0 * (tempTotScore - minScore - maxScore) / (tempCount-2); totalScore = (tempTotScore + teaScore) / 2.0; //round(0, totalScore); printf("%d\n", (int)(totalScore + 0.5)); } return 0; }
30.096774
82
0.524116
EnhydraGod
aacd921b6225bd8a4b1afd90df409a741d71d261
473
cpp
C++
worker/src/Master/Loop.cpp
idarkblue/mediasoup
f77bbd3680c122a2a4f15836b746e53e4b8571d0
[ "0BSD" ]
null
null
null
worker/src/Master/Loop.cpp
idarkblue/mediasoup
f77bbd3680c122a2a4f15836b746e53e4b8571d0
[ "0BSD" ]
null
null
null
worker/src/Master/Loop.cpp
idarkblue/mediasoup
f77bbd3680c122a2a4f15836b746e53e4b8571d0
[ "0BSD" ]
null
null
null
#include "Master/Log.hpp" #include "Master/Loop.hpp" #define PMS_CLASS "pingos::Loop" namespace pingos { uv_loop_t *Loop::loop = nullptr; void Loop::ClassInit() { DepLibUV::ClassInit(); } uv_loop_t* Loop::FetchLoop() { loop = DepLibUV::GetLoop(); if (loop == nullptr || uWS::Loop::get(loop) == nullptr) { PMS_ERROR("Creating uWS loop failed."); return nullptr; } return loop; } void Loop::Run() { uWS::Loop::get()->run(); } }
15.258065
61
0.610994
idarkblue
aad1c3e786cbc4bdbf9bf9f53c65661c73f0520d
6,401
cpp
C++
lib/libcpp/Alat/vectoronevariable.cpp
beckerrh/simfemsrc
d857eb6f6f8627412d4f9d89a871834c756537db
[ "MIT" ]
null
null
null
lib/libcpp/Alat/vectoronevariable.cpp
beckerrh/simfemsrc
d857eb6f6f8627412d4f9d89a871834c756537db
[ "MIT" ]
1
2019-01-31T10:59:11.000Z
2019-01-31T10:59:11.000Z
lib/libcpp/Alat/vectoronevariable.cpp
beckerrh/simfemsrc
d857eb6f6f8627412d4f9d89a871834c756537db
[ "MIT" ]
null
null
null
#include "Alat/stringvector.hpp" #include "Alat/vectoronevariable.hpp" #include <cassert> #include <cmath> #include <iomanip> #include <iostream> #include <limits> #include <sstream> using namespace alat; /*----------------------------------------------------------*/ VectorOneVariable::~VectorOneVariable() {} VectorOneVariable::VectorOneVariable() : alat::armavec(), alat::VectorOneVariableInterface(), _ncomp(1), _n(-1){} VectorOneVariable::VectorOneVariable(int ncomp) : alat::armavec(), alat::VectorOneVariableInterface(), _ncomp(ncomp), _n(-1){} VectorOneVariable::VectorOneVariable(const VectorOneVariable& v) : alat::armavec(v), alat::VectorOneVariableInterface(v), _ncomp(v._ncomp), _n(v._n){} VectorOneVariable& VectorOneVariable::operator=(const VectorOneVariable& v) { assert(0); return *this; } std::unique_ptr<VectorOneVariableInterface> VectorOneVariable::clone() const { return std::unique_ptr<VectorOneVariableInterface>(new VectorOneVariable(*this)); } std::string VectorOneVariable::getClassName() const { return "VectorOneVariable"; } /*----------------------------------------------------------*/ std::ostream& alat::operator<<(std::ostream& os, const VectorOneVariable& g) { const alat::armavec& tarma =static_cast<const alat::armavec&>(g); os << tarma.t(); return os; } /*----------------------------------------------------------*/ void VectorOneVariable::copyFrom(const VectorOneVariable& u) { assert(_ncomp!=-1); for(int icomp=0;icomp<_ncomp;icomp++) { VectorOneVariable::const_iterator q = u.begin(icomp); for(iterator p=begin(icomp);p!=end(icomp);p++) { *p= *q++; } } } /*----------------------------------------------------------*/ void VectorOneVariable::scaleIntVector(const alat::armaivec& count) { assert(_ncomp!=-1); for(int icomp=0;icomp<_ncomp;icomp++) { alat::armaivec::const_iterator q = count.begin(); for(iterator p=begin(icomp);p!=end(icomp);p++) { *p /= (double)*q++; } } } /*----------------------------------------------------------*/ void VectorOneVariable::loadhdf5(const arma::hdf5_name& spec) { alat::armavec& tarma =static_cast<alat::armavec&>(*this); tarma.load(spec); } void VectorOneVariable::savehdf5(const arma::hdf5_name& spec) const { const alat::armavec& tarma =static_cast<const alat::armavec&>(*this); tarma.save(spec); } /*----------------------------------------------------------*/ void VectorOneVariable::save(std::ostream& os, arma::file_type datatype) const { const alat::armavec& tarma =static_cast<const alat::armavec&>(*this); tarma.save(os, datatype); } /*----------------------------------------------------------*/ int VectorOneVariable::size() const {return alat::armavec::size();} int VectorOneVariable::ncomp() const {return _ncomp;} void VectorOneVariable::setNcompAndN(int ncomp, int n) {_ncomp=ncomp; _n=n;} void VectorOneVariable::set_size(int n) { _n = n; alat::armavec::set_size( n ); } /*----------------------------------------------------------*/ VectorOneVariable::const_iterator VectorOneVariable::begin(int icomp) const{return alat::armavec::begin() + icomp* _n;} VectorOneVariable::iterator VectorOneVariable::begin(int icomp){return alat::armavec::begin() + icomp* _n;} VectorOneVariable::iterator VectorOneVariable::end(int icomp){return alat::armavec::begin() + ( icomp+1 )* _n;} VectorOneVariable::const_iterator VectorOneVariable::end(int icomp) const{return alat::armavec::begin() + ( icomp+1 )* _n;} int VectorOneVariable::n() const{return _n;} /*----------------------------------------------------------*/ void VectorOneVariable::assemble(const alat::armaimat& indices, const arma::mat& local, double d) { for(int ii = 0; ii < indices.n_rows; ii++) { for(int jj = 0; jj < indices.n_cols; jj++) { int i = indices(ii,jj); ( *this )[i] += d*local(ii,jj); } } } void VectorOneVariable::extract(const alat::armaimat& indices, arma::mat& local) const { local.set_size(indices.n_rows, indices.n_cols); for(int ii = 0; ii < indices.n_rows; ii++) { for(int jj = 0; jj < indices.n_cols; jj++) { int i = indices(ii,jj); local(ii,jj) = ( *this )[i]; } } } /*----------------------------------------------------------*/ void VectorOneVariable::scale(double s) { alat::armavec::operator*=(s); } /*----------------------------------------------------------*/ void VectorOneVariable::fillzeros() { alat::armavec::fill(arma::fill::zeros); } /*----------------------------------------------------------*/ double VectorOneVariable::norm() const { const alat::armavec& tarma =static_cast<const alat::armavec&>(*this); return arma::norm(tarma); } /*----------------------------------------------------------*/ double VectorOneVariable::dot(const alat::VectorOneVariableInterface* v) const { const alat::armavec& tarma =static_cast<const alat::armavec&>(*this); const alat::armavec& varma =dynamic_cast<const alat::armavec&>(*v); return arma::dot( tarma, varma ); } /*----------------------------------------------------------*/ void VectorOneVariable::equal(double d) { // assert(0); alat::armavec& tarma =static_cast<alat::armavec&>(*this); tarma.fill(d); } void VectorOneVariable::equal(const alat::VectorOneVariableInterface* v) { alat::armavec& tarma =static_cast<alat::armavec&>(*this); const alat::armavec& varma =dynamic_cast<const alat::armavec&>(*v); tarma = varma; } /*----------------------------------------------------------*/ void VectorOneVariable::add(const double& d, const alat::VectorOneVariableInterface* v) { alat::armavec& tarma =static_cast<alat::armavec&>(*this); const alat::armavec& varma =dynamic_cast<const alat::armavec&>(*v); tarma += d*varma; } /*----------------------------------------------------------*/ void VectorOneVariable::setVectorFromDirectSolver(int offset, const alat::armavec& u) { alat::armavec& tarma =static_cast<alat::armavec&>(*this); tarma = u.subvec(offset, offset+tarma.size()-1); } void VectorOneVariable::addVectorRhsForDirectSolver(int offset, alat::armavec& f) const { const alat::armavec& tarma =static_cast<const alat::armavec&>(*this); // std::cerr << "tarma " << tarma.t(); // std::cerr << "offset " << offset << "\n"; // std::cerr << "offset+tarma.size()-1 " << offset+tarma.size()-1 << "\n"; f.subvec(offset, offset+tarma.size()-1) += tarma; }
34.229947
150
0.58897
beckerrh
aad2068f75904af86573124bf2f2383785a43872
4,508
cpp
C++
src/airmap/rest/authenticator.cpp
thopiekar/airmap-platform-sdk
254aef58adc63fdda080222ba2f42e26c9a6ed03
[ "Apache-2.0" ]
13
2018-09-05T14:35:01.000Z
2021-03-04T07:17:40.000Z
src/airmap/rest/authenticator.cpp
thopiekar/airmap-platform-sdk
254aef58adc63fdda080222ba2f42e26c9a6ed03
[ "Apache-2.0" ]
31
2018-09-06T13:04:03.000Z
2021-11-15T22:46:50.000Z
src/airmap/rest/authenticator.cpp
thopiekar/airmap-platform-sdk
254aef58adc63fdda080222ba2f42e26c9a6ed03
[ "Apache-2.0" ]
12
2018-11-09T10:09:21.000Z
2021-10-08T05:28:12.000Z
// AirMap Platform SDK // Copyright © 2018 AirMap, 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. #include <airmap/rest/authenticator.h> #include <airmap/codec.h> #include <airmap/jsend.h> #include <airmap/net/http/middleware.h> #include <airmap/util/fmt.h> #include <nlohmann/json.hpp> namespace fmt = airmap::util::fmt; using json = nlohmann::json; std::string airmap::rest::Authenticator::default_route_for_version(Client::Version version) { static constexpr const char* pattern{"/auth/%s"}; switch (version) { case airmap::Client::Version::production: return fmt::sprintf(pattern, "v1"); case airmap::Client::Version::staging: return fmt::sprintf(pattern, "stage"); } throw std::logic_error{"should not reach here"}; } airmap::rest::Authenticator::Authenticator(const std::shared_ptr<net::http::Requester>& airmap_requester, const std::shared_ptr<net::http::Requester>& sso_requester) : airmap_requester_{airmap_requester}, sso_requester_{sso_requester} { } void airmap::rest::Authenticator::authenticate_with_password(const AuthenticateWithPassword::Params& params, const AuthenticateWithPassword::Callback& cb) { std::unordered_map<std::string, std::string> headers; json j; j = params; sso_requester_->post("/oauth/ro", std::move(headers), j.dump(), [cb, this](const auto& result) { if (result) { const auto& response = result.value(); switch (response.classify()) { case net::http::Response::Classification::informational: case net::http::Response::Classification::redirection: break; case net::http::Response::Classification::success: case net::http::Response::Classification::server_error: { auto outcome = jsend::parse_to_outcome<Token::OAuth>(result.value().body); auto token_string = outcome.value().id; this->notify_auth_token_updated(token_string); cb(outcome); break; } case net::http::Response::Classification::client_error: try { auto j = nlohmann::json::parse(result.value().body); if (j.count("error_description") > 0) { cb(Outcome<Token::OAuth, Error>{Error{j["error_description"].template get<std::string>()}}); } else { cb(Outcome<Token::OAuth, Error>{Error{"generic client error"}}); } } catch (...) { cb(Outcome<Token::OAuth, Error>{Error{"generic client error"}}); } break; default: cb(Outcome<Token::OAuth, Error>{ Error{"networking error"} .value(Error::Value{std::string{"status-code"}}, Error::Value{static_cast<std::int64_t>(result.value().status)}) .value(Error::Value{std::string{"body"}}, Error::Value{result.value().body})}); break; } } else { cb(Outcome<Token::OAuth, Error>{result.error()}); } }); } void airmap::rest::Authenticator::authenticate_anonymously(const AuthenticateAnonymously::Params& params, const AuthenticateAnonymously::Callback& cb) { std::unordered_map<std::string, std::string> headers; json j; j = params; airmap_requester_->post("/anonymous/token", std::move(headers), j.dump(), net::http::jsend_parsing_request_callback<Token::Anonymous>(cb)); } void airmap::rest::Authenticator::renew_authentication(const RenewAuthentication::Params& params, const RenewAuthentication::Callback& cb) { std::unordered_map<std::string, std::string> headers; json j; j = params; sso_requester_->post("/delegation", std::move(headers), j.dump(), net::http::jsend_parsing_request_callback<Token::Refreshed>(cb)); }
39.54386
108
0.629769
thopiekar
aad4530bbc8626962c48e14e6ba01ced49373a0d
2,299
cpp
C++
src/plugins/azoth/plugins/xoox/mediacall.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
120
2015-01-22T14:10:39.000Z
2021-11-25T12:57:16.000Z
src/plugins/azoth/plugins/xoox/mediacall.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
8
2015-02-07T19:38:19.000Z
2017-11-30T20:18:28.000Z
src/plugins/azoth/plugins/xoox/mediacall.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
33
2015-02-07T16:59:55.000Z
2021-10-12T00:36:40.000Z
/********************************************************************** * LeechCraft - modular cross-platform feature rich internet client. * Copyright (C) 2006-2014 Georg Rudoy * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt) **********************************************************************/ #include "mediacall.h" #include <QAudioFormat> #include <QtDebug> #include <QXmppCallManager.h> #include "clientconnection.h" #include "glooxaccount.h" namespace LC { namespace Azoth { namespace Xoox { MediaCall::MediaCall (GlooxAccount *acc, QXmppCall *call) : QObject (call) , Call_ (call) , Account_ (acc) { connect (Call_, &QXmppCall::stateChanged, this, [this] (QXmppCall::State state) { emit stateChanged (static_cast<State> (state); ) }); } IMediaCall::Direction MediaCall::GetDirection () const { switch (Call_->direction ()) { case QXmppCall::IncomingDirection: return DIn; case QXmppCall::OutgoingDirection: return DOut; default: qWarning () << Q_FUNC_INFO << "unknown direction" << Call_->direction (); return DIn; } } QString MediaCall::GetSourceID () const { return Account_->GetAccountID () + '_' + ClientConnection::Split (Call_->jid ()).Bare_; } void MediaCall::Accept () { Call_->accept (); } void MediaCall::Hangup () { Call_->hangup (); } QIODevice* MediaCall::GetAudioDevice () { const auto& payload = Call_->audioChannel ()->payloadType (); qDebug () << "INFO" << payload.name () << payload.parameters (); qDebug () << payload.channels () << payload.clockrate (); return Call_->audioChannel (); } QAudioFormat MediaCall::GetAudioReadFormat () const { const auto& payload = Call_->audioChannel ()->payloadType (); QAudioFormat result; result.setSampleRate (payload.clockrate ()); result.setChannelCount (payload.channels ()); result.setSampleSize (16); result.setCodec ("audio/pcm"); result.setByteOrder (QAudioFormat::LittleEndian); result.setSampleType (QAudioFormat::SignedInt); return result; } QAudioFormat MediaCall::GetAudioWriteFormat () const { return GetAudioReadFormat (); } QIODevice* MediaCall::GetVideoDevice () { return nullptr; } } } }
23.701031
90
0.647673
Maledictus
aae054fa11632b5b3b076aee56d282bee92dfdb7
531
cpp
C++
1300/50/1354a.cpp
actium/cf
d7be128c3a9adb014a231a399f1c5f19e1ab2a38
[ "Unlicense" ]
1
2020-07-03T15:55:52.000Z
2020-07-03T15:55:52.000Z
1300/50/1354a.cpp
actium/cf
d7be128c3a9adb014a231a399f1c5f19e1ab2a38
[ "Unlicense" ]
null
null
null
1300/50/1354a.cpp
actium/cf
d7be128c3a9adb014a231a399f1c5f19e1ab2a38
[ "Unlicense" ]
3
2020-10-01T14:55:28.000Z
2021-07-11T11:33:58.000Z
#include <iostream> void answer(long long v) { std::cout << v << '\n'; } void solve(size_t a, size_t b, size_t c, size_t d) { if (a <= b) return answer(b); if (c <= d) return answer(-1); const long long r = c - d; const long long k = (a - b + r - 1) / r; answer(b + k * c); } void test_case() { size_t a, b, c, d; std::cin >> a >> b >> c >> d; solve(a, b, c, d); } int main() { size_t t; std::cin >> t; while (t-- > 0) test_case(); return 0; }
12.95122
50
0.45951
actium
aae0acafa99293414b423b4697996875b280a897
783
cpp
C++
src/plugins/playback/nsf/xgm/devices/Memory/ram64k.cpp
emoon/HippoPlayer
a3145f9797a5ef7dd1b79ee8ccd3476c8c5310a6
[ "Apache-2.0", "MIT" ]
67
2018-01-17T17:18:37.000Z
2020-08-24T23:45:56.000Z
src/plugins/playback/nsf/xgm/devices/Memory/ram64k.cpp
emoon/HippoPlayer
a3145f9797a5ef7dd1b79ee8ccd3476c8c5310a6
[ "Apache-2.0", "MIT" ]
132
2018-01-17T17:43:25.000Z
2020-09-01T07:41:17.000Z
src/plugins/playback/nsf/xgm/devices/Memory/ram64k.cpp
HippoPlayer/HippoPlayer
a3145f9797a5ef7dd1b79ee8ccd3476c8c5310a6
[ "Apache-2.0", "MIT" ]
5
2021-02-12T15:23:31.000Z
2022-01-09T15:16:21.000Z
#include <assert.h> #include <cstring> #include "ram64k.h" namespace xgm { ///////////////////////////////////////////////////////////////////////////// RAM64K::RAM64K() { } RAM64K::~RAM64K() { } void RAM64K::Reset () { memset (image, 0, 0x10000); } bool RAM64K::SetImage (UINT8 * data, UINT32 offset, UINT32 size) { if( offset + size < 0x10000 ) memcpy (image + offset, data, size ); else memcpy (image + offset, data, 0x10000 - offset); return true; } bool RAM64K::Write (UINT32 adr, UINT32 val, UINT32 id) { image[adr & 0xFFFF] = val&0xFF; return true; } bool RAM64K::Read (UINT32 adr, UINT32 & val, UINT32 id) { val = image[adr & 0xFFFF]; return true; } ///////////////////////////////////////////////////////////////////////////// }// namespace
15.979592
77
0.512133
emoon
aae50735cdd514c849864e616abd2f229d99eee8
11,341
cpp
C++
sources/ui/components/SpectrumView.cpp
jpcima/spectacle
540d98ac381400bbf58084e3434cb4f300ad7232
[ "0BSD" ]
44
2020-04-16T19:20:00.000Z
2022-02-27T00:10:13.000Z
sources/ui/components/SpectrumView.cpp
jpcima/spectacle
540d98ac381400bbf58084e3434cb4f300ad7232
[ "0BSD" ]
18
2020-04-16T03:28:55.000Z
2021-11-15T19:49:12.000Z
sources/ui/components/SpectrumView.cpp
jpcima/spectral
540d98ac381400bbf58084e3434cb4f300ad7232
[ "0BSD" ]
3
2020-04-16T01:22:48.000Z
2021-08-10T20:34:30.000Z
#include "SpectrumView.h" #include "ui/FontEngine.h" #include "plugin/ColorPalette.h" #include "Color.hpp" #include "Window.hpp" #include <algorithm> #include <cassert> #if defined(_WIN32) #undef near #endif /// static double mtof(double m) { return 440.0 * std::exp2((m - 69.0) * (1.0 / 12.0)); } static double ftom(double f) { return 69.0 + 12.0 * std::log2(f * (1.0 / 440.0)); } /// SpectrumView::SpectrumView(Widget *parent, const ColorPalette &palette) : NanoWidget(parent), fColorPalette(palette) { } void SpectrumView::setData(const float *frequencies, const float *magnitudes, uint32_t size, uint32_t numChannels) { Memory &mem = fActiveMemory; mem.frequencies.assign(frequencies, frequencies + size * numChannels); mem.magnitudes.assign(magnitudes, magnitudes + size * numChannels); mem.size = size; mem.numChannels = numChannels; mem.dirty = true; repaint(); } void SpectrumView::toggleFreeze() { fFreezeMemory = fActiveMemory; fFreeze = !fFreeze; } double SpectrumView::evalMagnitudeOnDisplay(uint32_t channel, double frequency) const { const Memory &mem = getDisplayMemory(); DISTRHO_SAFE_ASSERT_RETURN(channel < mem.numChannels, 0.0); const Spline &spline = mem.getSpline(channel); return spline.interpolate(frequency); } SpectrumView::Peak SpectrumView::findNearbyPeakOnDisplay(uint32_t channel, double frequency) { SpectrumView::Peak pk = {}; const Memory &mem = getDisplayMemory(); DISTRHO_SAFE_ASSERT_RETURN(channel < mem.numChannels, pk); const uint32_t size = mem.size; DISTRHO_SAFE_ASSERT_RETURN(size > 0, pk); const Spline &spline = mem.getSpline(channel); // fprintf(stderr, "----- New search (C=%u) -----\n", channel); // fprintf(stderr, "Size: %u %d\n", size, spline.countElements()); // fprintf(stderr, "Real Middle: F=%f M=%f\n", frequency, spline.interpolate(frequency)); int32_t mid = spline.findElement(frequency); // fprintf(stderr, "Near Middle: I=%d F=%f M=%f\n", mid, spline.getX(mid), spline.getY(mid)); int32_t direction = 0; if (mid - 1 < 0) direction = +1; else if ((uint32_t)(mid + 1) >= size) direction = -1; else direction = (spline.interpolate(frequency) < spline.getY(mid + 1)) ? +1 : -1; // fprintf(stderr, "Peak direction: %d\n", direction); auto indexValid = [size](int32_t i) { return i >= 0 && (uint32_t)i < size; }; int32_t near = mid; while (indexValid(near + direction) && spline.getY(near + direction) >= spline.getY(near)) { near += direction; // fprintf(stderr, "Peak advance to: %d F=%f M=%f\n", near, spline.getX(near), spline.getY(near)); } if (0) { pk.frequency = spline.getX(near); pk.magnitude = spline.getY(near); } else { // narrow peak down by repeated spline evaluations constexpr uint32_t numEvaluations = 8; const int32_t left = std::max(0, near - 1); const int32_t right = std::min((int32_t)size - 1, near + 1); double f1 = 0.5 * (spline.getX(near) + spline.getX(left)); double f2 = 0.5 * (spline.getX(near) + spline.getX(right)); double f = 0.5 * (f1 + f2); double m = spline.interpolate(f); for (uint32_t i = 0; i < numEvaluations; ++i) { double fc1 = 0.5 * (f + f1); double mc1 = spline.interpolate(fc1); if (mc1 > m) { m = mc1; f2 = f; } else { double fc2 = 0.5 * (f + f2); double mc2 = spline.interpolate(fc2); m = mc2; f1 = f; } f = 0.5 * (f1 + f2); } pk.frequency = f; pk.magnitude = m; } // fprintf(stderr, "----- End search -----\n"); return pk; } void SpectrumView::setKeyScale(float keyMin, float keyMax) { if (keyMin == fKeyMin || keyMax == fKeyMax) return; fKeyMin = keyMin; fKeyMax = keyMax; repaint(); } void SpectrumView::setDbScale(float dbMin, float dbMax) { if (dbMin == fdBmin || dbMax == fdBmax) return; fdBmin = dbMin; fdBmax = dbMax; repaint(); } void SpectrumView::setDefaultScales() { setKeyScale(kKeyMinDefault, kKeyMaxDefault); setDbScale(kdBminDefault, kdBmaxDefault); } void SpectrumView::clearReferenceLine() { if (!fHaveReferenceLine) return; fHaveReferenceLine = false; repaint(); } void SpectrumView::setReferenceLine(float key, float db) { if (fHaveReferenceLine && fKeyRef == key && fdBref == db) return; fHaveReferenceLine = true; fKeyRef = key; fdBref = db; repaint(); } void SpectrumView::onNanoDisplay() { save(); /// const uint32_t width = getWidth(); const uint32_t height = getHeight(); /// displayBack(); /// const Memory &mem = getDisplayMemory(); const uint32_t size = mem.size; const uint32_t numChannels = mem.numChannels; if (size < 4) // need more elements for interpolation return; /// std::vector<PointF> points; points.reserve(width); /// const ColorPalette &cp = fColorPalette; /// for (uint32_t channel = 0; channel < numChannels; ++channel) { const Spline &spline = mem.getSpline(channel); const ColorRGBA8 linecolor = cp[Colors::spectrum_line_channel1 + channel]; const ColorRGBA8 fillcolor = cp[Colors::spectrum_fill_channel1 + channel]; /// points.clear(); for (uint32_t x = 0, step = 1; x <= width; x += step) { const float f = frequencyOfX(x); const float y = yOfDbMag(spline.interpolate(f)); points.emplace_back(x, y); } // plot line if (linecolor.a > 0) { beginPath(); moveTo(points[0].x, points[0].y); for (uint32_t i = 1, n = points.size(); i < n; ++i) lineTo(points[i].x, points[i].y); strokeWidth(1.0); strokeColor(Colors::fromRGBA8(linecolor)); stroke(); } // plot fill if (fillcolor.a > 0) { beginPath(); moveTo(points[0].x, points[0].y); for (uint32_t i = 1, n = points.size(); i < n; ++i) lineTo(points[i].x, points[i].y); lineTo(points.back().x, height); lineTo(points.front().x, height); fillColor(Colors::fromRGBA8(fillcolor)); fill(); } } /// if (fHaveReferenceLine) { const double x = xOfKey(fKeyRef); const double y = yOfDbMag(fdBref); strokeWidth(1.0); strokeColor(Colors::fromRGBA8(cp[Colors::spectrum_select_line])); beginPath(); moveTo(0.0, (int)y + 0.5); lineTo(width, (int)y + 0.5); stroke(); beginPath(); moveTo((int)x + 0.5, 0); lineTo((int)x + 0.5, height); stroke(); } /// restore(); } void SpectrumView::displayBack() { const ColorPalette &cp = fColorPalette; FontEngine fe(*this, cp); /// const uint32_t width = getWidth(); const uint32_t height = getHeight(); /// beginPath(); rect(0.0, 0.0, width, height); fillColor(Colors::fromRGBA8(cp[Colors::spectrum_background])); fill(); /// Font font; font.name = "regular"; font.color = cp[Colors::spectrum_grid_text]; font.size = 14; /// ColorRGBA8 gridLineColor = cp[Colors::spectrum_grid_lines]; ColorRGBA8 minorGridLineColor = cp[Colors::spectrum_minor_grid_lines]; strokeWidth(1.0); int32_t midiKey = (int32_t)std::ceil(fKeyMin); while ((midiKey + 3) % 12 != 0) ++midiKey; midiKey -= 11; for (const double keyMax = fKeyMax; midiKey <= keyMax; midiKey += 1) { bool isLaKey = midiKey % 12 == 9; double frequency = 440.0 * std::exp2((midiKey - 69) * (1.0 / 12.0)); double x = xOfFrequency(frequency); if (isLaKey) strokeColor(Colors::fromRGBA8(gridLineColor)); else strokeColor(Colors::fromRGBA8(minorGridLineColor)); beginPath(); moveTo((int)x + 0.5, 0.0); lineTo((int)x + 0.5, height); stroke(); if (isLaKey) { translate(x - 4, height - 4); rotate(-0.5 * M_PI); fe.draw(std::to_string(std::lrint(frequency)).c_str(), font, 0, 0); resetTransform(); } } /// const double dBmin = fdBmin; const double dBmax = fdBmax; constexpr double dBinterval = 12.0; constexpr uint32_t dBsubdivs = 4; const double dBminAligned = std::round(dBmin / dBinterval) * dBinterval; bool dBgridEnd = false; for (unsigned i = 0; !dBgridEnd; ++i) { for (uint32_t j = 0; j < dBsubdivs; ++j) { // draw preceding subdivs-1 minor lines, and then major line double g = dBminAligned + dBinterval * (i - 1.0 + (j + 1.0) / dBsubdivs); if (g > dBmax) { dBgridEnd = true; break; } if (j == dBsubdivs - 1) strokeColor(Colors::fromRGBA8(gridLineColor)); else strokeColor(Colors::fromRGBA8(minorGridLineColor)); double y = yOfDbMag(g); beginPath(); moveTo(0, (int)y + 0.5); lineTo(width, (int)y + 0.5); stroke(); if (j == dBsubdivs - 1) fe.drawInBox(std::to_string(std::lrint(g)).c_str(), font, RectF(0, y + 4, width - 4, 0), kAlignTopRight|kAlignInside); } } } double SpectrumView::keyOfX(double x) const { return keyOfR(x / getWidth()); } double SpectrumView::keyOfR(double r) const { return r * (fKeyMax - fKeyMin) + fKeyMin; } double SpectrumView::xOfKey(double k) const { return rOfKey(k) * getWidth(); } double SpectrumView::rOfKey(double k) const { return (k - fKeyMin) / (fKeyMax - fKeyMin); } double SpectrumView::frequencyOfX(double x) const { return frequencyOfR(x / getWidth()); } double SpectrumView::frequencyOfR(double r) const { return mtof(keyOfR(r)); } double SpectrumView::rOfFrequency(double f) const { return (ftom(f) - fKeyMin) / (fKeyMax - fKeyMin); } double SpectrumView::xOfFrequency(double f) const { return rOfFrequency(f) * getWidth(); } double SpectrumView::dbMagOfY(double y) const { return dbMagOfR(1 - y / getHeight()); } double SpectrumView::dbMagOfR(double r) const { return fdBmin + r * (fdBmax - fdBmin); } double SpectrumView::rOfDbMag(double m) const { return (m - fdBmin) / (fdBmax - fdBmin); } double SpectrumView::yOfDbMag(double m) const { return (1 - rOfDbMag(m)) * getHeight(); } Spline &SpectrumView::Memory::getSpline(uint32_t channel) const { assert(channel < numChannels); if (dirty) { lazySpline.resize(numChannels); for (uint32_t c = 0; c < numChannels; ++c) lazySpline[c].setup(&frequencies[c * size], &magnitudes[c * size], size); dirty = false; } return lazySpline[channel]; } constexpr float SpectrumView::kdBminDefault; constexpr float SpectrumView::kdBmaxDefault; constexpr float SpectrumView::kKeyMinDefault; constexpr float SpectrumView::kKeyMaxDefault;
25.951945
134
0.586633
jpcima
aae8d354801e511865422b188140376f4c90575e
249
cpp
C++
Source/Portals/Portals.cpp
FreetimeStudio/PortalPlugin
5eac85839f9411cb6a0a04ec2f1686d30eda893e
[ "MIT" ]
73
2017-05-29T17:13:30.000Z
2021-09-06T08:24:41.000Z
Source/Portals/Portals.cpp
getnamo/PortalPlugin
8296ccc167f0a864ac6b42e91244f533599beab3
[ "MIT" ]
12
2017-05-29T11:11:55.000Z
2021-02-11T22:14:27.000Z
Source/Portals/Portals.cpp
getnamo/PortalPlugin
8296ccc167f0a864ac6b42e91244f533599beab3
[ "MIT" ]
19
2017-07-16T17:13:03.000Z
2021-04-10T15:24:48.000Z
// Released under MIT License // Copyright (c) Pascal Krabbe 2017 #include "Portals.h" #include "Modules/ModuleManager.h" IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, Portals, "Portals" ); //Dummy file for host project to compile plugin
27.666667
76
0.783133
FreetimeStudio
aaec661a85fd6e8809dd875e739f3c85a1d2a871
56
cpp
C++
SIF_CONSOLE/Model/DAOCliente.cpp
VitorDiToro/EC206-EngenhariaDeSoftware2
bbe9b1d8fe9fcaa9f8eb4cd7b588a2df4665612c
[ "MIT" ]
null
null
null
SIF_CONSOLE/Model/DAOCliente.cpp
VitorDiToro/EC206-EngenhariaDeSoftware2
bbe9b1d8fe9fcaa9f8eb4cd7b588a2df4665612c
[ "MIT" ]
null
null
null
SIF_CONSOLE/Model/DAOCliente.cpp
VitorDiToro/EC206-EngenhariaDeSoftware2
bbe9b1d8fe9fcaa9f8eb4cd7b588a2df4665612c
[ "MIT" ]
1
2019-11-12T12:47:13.000Z
2019-11-12T12:47:13.000Z
#include "DAOCliente.h" DAOCliente::DAOCliente() { }
7
24
0.678571
VitorDiToro
aaed7e582c2760fdda986bb171bd7551cba883a7
4,439
cpp
C++
sem_2/course_dedinskiy/hashtable/src/un_opt/hashtable.cpp
KingCakeTheFruity/mipt
e32cfe5e53236cdd2933d8b666ca995508300f0f
[ "MIT" ]
null
null
null
sem_2/course_dedinskiy/hashtable/src/un_opt/hashtable.cpp
KingCakeTheFruity/mipt
e32cfe5e53236cdd2933d8b666ca995508300f0f
[ "MIT" ]
null
null
null
sem_2/course_dedinskiy/hashtable/src/un_opt/hashtable.cpp
KingCakeTheFruity/mipt
e32cfe5e53236cdd2933d8b666ca995508300f0f
[ "MIT" ]
null
null
null
#include "hashtable.h" Hashtable::Hashtable() {} Hashtable::~Hashtable() {} RETURN_CODE Hashtable::ctor(const size_t capacity_, const size_t bucket_size_, const float max_loadrate_) { size = 0; capacity = capacity_; bucket_size = bucket_size_; loadrate = 0; max_loadrate = max_loadrate_; overall_data_size = capacity * bucket_size; data = (HT_Node*) calloc(overall_data_size, sizeof(HT_Node)); if (!data) { return ERROR_MALLOC_FAIL; } for (size_t i = 0; i < overall_data_size; ++i) { data[i].ctor(); } check_loadrate(); return OK; } RETURN_CODE Hashtable::dtor() { if (data) { free(data); } data = nullptr; capacity = 0; bucket_size = 0; overall_data_size = 0; max_loadrate = 0; loadrate = 0; return OK; } bool Hashtable::is_valid() const { return !((capacity * bucket_size == overall_data_size) && (!overall_data_size || data)); } RETURN_CODE Hashtable::rehash() { VERIFY_OK(is_valid()); HT_Node *new_data = (HT_Node*) calloc((bucket_size + REHASH_BUCKET_INCREASE_CNT) * (capacity * REHASH_CAPACITY_INCREASE_RATE), sizeof(HT_Node)); if (!new_data) { return ERROR_REALLOC_FAIL; } HT_Node *old_data = data; size_t old_ov_size = overall_data_size; data = new_data; bucket_size += REHASH_BUCKET_INCREASE_CNT; capacity *= REHASH_CAPACITY_INCREASE_RATE; overall_data_size = capacity * bucket_size; size = 0; for (size_t i = 0; i < old_ov_size; ++i) { const HT_Node &n = old_data[i]; if (n.is() == IS_ALIVE) { insert(n, false); } } free(old_data); return OK; } RETURN_CODE Hashtable::check_loadrate() { loadrate = ((float) size) / overall_data_size; // printf("loadrate: %g\n", loadrate); if (loadrate > max_loadrate || overall_data_size - size < MIN_ADDITIONAL_CAPACITY) { return rehash(); } return OK; } RETURN_CODE Hashtable::insert(const HT_Node &node, bool to_check_loadrate) { VERIFY_OK(is_valid()); size_t hash = node.hashed % capacity; size_t coord = hash * bucket_size; // printf("hash_pos(%lu) for %s is %lu\n", node.hashed, node.key, hash); size_t max_i = bucket_size; size_t first_free_index = (size_t) -1; for (size_t i = 0; i < max_i; ++i, ++coord) { HT_Node &n = data[coord]; if (n.is() < IS_ALIVE && (first_free_index == (size_t) -1)) { first_free_index = coord; } if (n.is() == IS_DEAD) { break; } if (n == node) { n.count_copy(node); return OK; } } if (first_free_index != (size_t) -1) { data[first_free_index].copy_from(node); ++size; if (to_check_loadrate) VERIFY_OK(check_loadrate()); } else { VERIFY_OK(rehash()); VERIFY_OK(insert(node, true)); } return OK; } RETURN_CODE Hashtable::erase(const HT_Node &node) { VERIFY_OK(is_valid()); size_t hash = node.hashed % capacity; size_t coord = hash * bucket_size; size_t max_i = bucket_size; for (size_t i = 0; i < max_i; ++i, ++coord) { HT_Node &n = data[coord]; if (n.is() == IS_DEAD) { return OK; } if (n == node) { n.set_is(IS_DELETED); return OK; } } return OK; } HT_RET_TYPE Hashtable::find(const HT_Node &node) const { VERIFY_T(is_valid() == OK, HT_RET_TYPE); size_t hash = node.hashed % capacity; size_t coord = hash * bucket_size; size_t max_i = bucket_size; for (size_t i = 0; i < max_i; ++i, ++coord) { HT_Node &n = data[coord]; if (n.is() == IS_DEAD) { return (HT_RET_TYPE) 0; } if (n.is() == IS_ALIVE && n == node) { return n.val; } } return (HT_RET_TYPE) 0; } RETURN_CODE Hashtable::execute_queue(HT_Node *nodes, char *operations, size_t queue_size, HT_RET_TYPE *result) { assert(nodes); assert(operations); assert(result); for (size_t i = 0; i < queue_size; ++i) { nodes[i].hash(); } if ((long int) operations == HT_Q_INSERT) { for (size_t i = 0; i < queue_size; ++i, ++nodes) { VERIFY_OK(insert(*nodes)); } return OK; } else if ((long int) operations == HT_Q_ERASE) { for (size_t i = 0; i < queue_size; ++i, ++nodes) { VERIFY_OK(erase(*nodes)); } return OK; } else if ((long int) operations == HT_Q_FIND) { for (size_t i = 0; i < queue_size; ++i, ++nodes) { result[i] = find(*nodes); } return OK; } for (size_t i = 0; i < queue_size; ++i, ++nodes) { switch ((long int) operations[i]) { case HT_Q_INSERT : { VERIFY_OK(insert(*nodes)); break; } case HT_Q_ERASE : { VERIFY_OK(erase(*nodes)); break; } case HT_Q_FIND : { result[i] = find(*nodes); break; } } } return OK; }
20.456221
145
0.645641
KingCakeTheFruity
aaef5317b08aa2cde82397230d26d329a75bcff1
6,171
cpp
C++
src/cbag/layout/via_info.cpp
ayan-biswas/cbag
0d08394cf39e90bc3acb4a94fd7b5a6560cf103c
[ "BSD-3-Clause" ]
1
2020-01-07T04:44:17.000Z
2020-01-07T04:44:17.000Z
src/cbag/layout/via_info.cpp
skyworksinc/cbag
0d08394cf39e90bc3acb4a94fd7b5a6560cf103c
[ "BSD-3-Clause" ]
null
null
null
src/cbag/layout/via_info.cpp
skyworksinc/cbag
0d08394cf39e90bc3acb4a94fd7b5a6560cf103c
[ "BSD-3-Clause" ]
1
2020-01-07T04:45:13.000Z
2020-01-07T04:45:13.000Z
#include <algorithm> #include <boost/container_hash/hash.hpp> #include <cbag/layout/via_info.h> #include <cbag/layout/via_param.h> #include <cbag/util/unique_heap.h> namespace cbag { namespace layout { constexpr offset_t MAX_INT = std::numeric_limits<offset_t>::max(); venc_data::venc_data() = default; via_info::via_info() = default; via_info::via_info(vector &&cdim, vector &&s, std::vector<vector> &&s2_list, std::vector<vector> &&s3_list, std::array<venc_info, 2> &&e_list) : cut_dim(std::move(cdim)), sp(std::move(s)), sp2_list(std::move(s2_list)), sp3_list(std::move(s3_list)), enc_list(std::move(e_list)) { if (sp2_list.empty()) { sp2_list.emplace_back(sp); } if (sp3_list.empty()) { sp3_list.insert(sp3_list.end(), sp2_list.begin(), sp2_list.end()); } } cnt_t get_n_max(offset_t dim, offset_t w, offset_t sp) { if (sp == MAX_INT) { return (dim > w) ? 1 : 0; } return (dim + sp) / (w + sp); } const std::vector<vector> &get_enc_list(const venc_info &enc_info, offset_t width) { for (const auto &data : enc_info) { if (width <= data.width) return data.enc_list; } return enc_info.back().enc_list; } vector get_metal_dim(vector box_dim, vector arr_dim, const venc_info &enc_info, orient_2d_t dir_idx, bool extend) { auto pdir_idx = 1 - dir_idx; auto wire_w = box_dim[pdir_idx]; vector ans; ans[dir_idx] = MAX_INT; ans[pdir_idx] = wire_w; for (const auto &enc_vec : get_enc_list(enc_info, wire_w)) { vector enc_dim = {2 * enc_vec[0] + arr_dim[0], 2 * enc_vec[1] + arr_dim[1]}; if (enc_dim[pdir_idx] <= box_dim[pdir_idx]) { if (extend || enc_dim[dir_idx] <= box_dim[dir_idx]) { // enclosure rule passed, get optimal metal dimension ans[dir_idx] = std::min(ans[dir_idx], enc_dim[dir_idx]); } } } if (ans[dir_idx] == MAX_INT) { // no solution ans[0] = 0; ans[1] = 0; } else { ans[dir_idx] = std::max(ans[dir_idx], box_dim[dir_idx]); } return ans; } offset_t get_arr_dim(cnt_t n, offset_t w, offset_t sp) { if (sp == MAX_INT) if (n != 1) return 0; else return w; else return n * (w + sp) - sp; } via_param via_info::get_via_param(vector box_dim, direction vdir, orient_2d ex_dir, orient_2d ex_adj_dir, bool extend) const { via_param ans; auto vidx = to_int(vdir); auto dir_idx = to_int(ex_dir); auto adj_dir_idx = to_int(ex_adj_dir); // get maximum possible number of vias vector min_sp = sp; for (const auto &arr : sp2_list) { min_sp[0] = std::min(min_sp[0], arr[0]); min_sp[1] = std::min(min_sp[1], arr[1]); } for (const auto &arr : sp3_list) { min_sp[0] = std::min(min_sp[0], arr[0]); min_sp[1] = std::min(min_sp[1], arr[1]); } auto nx_max = get_n_max(box_dim[0], cut_dim[0], min_sp[0]); auto ny_max = get_n_max(box_dim[1], cut_dim[1], min_sp[1]); // check if it's possible to palce a via if (nx_max == 0 || ny_max == 0) return ans; // use priority queue to find maximum number of vias util::unique_heap<via_cnt_t, boost::hash<via_cnt_t>> heap; heap.emplace(nx_max * ny_max, std::array<cnt_t, 2>{nx_max, ny_max}); std::vector<vector> sp1_list({sp}); while (!heap.empty()) { auto &[via_cnt, num_via] = heap.top(); // get list of valid via spacing const std::vector<vector> *sp_vec_ptr; if (num_via[0] == 2 && num_via[1] == 2) { sp_vec_ptr = &sp2_list; } else if (num_via[0] > 1 && num_via[1] > 1) { sp_vec_ptr = &sp3_list; } else { sp_vec_ptr = &sp1_list; } // find optimal legal enclosure via vector opt_arr_dim; std::array<vector, 2> opt_mdim = {vector{MAX_INT, MAX_INT}, vector{MAX_INT, MAX_INT}}; vector opt_sp = {-1, -1}; for (const auto &sp_via : *sp_vec_ptr) { vector arr_dim = {get_arr_dim(num_via[0], cut_dim[0], sp_via[0]), get_arr_dim(num_via[1], cut_dim[1], sp_via[1])}; if (arr_dim[0] == 0 || arr_dim[1] == 0) continue; auto m_dim = get_metal_dim(box_dim, arr_dim, enc_list[0], dir_idx, extend); if (m_dim[0] == 0) continue; auto adj_m_dim = get_metal_dim(box_dim, arr_dim, enc_list[1], adj_dir_idx, extend); if (adj_m_dim[0] == 0) continue; if (m_dim[dir_idx] <= opt_mdim[vidx][dir_idx] && adj_m_dim[adj_dir_idx] <= opt_mdim[1 - vidx][adj_dir_idx]) { opt_arr_dim = arr_dim; opt_mdim[vidx] = m_dim; opt_mdim[1 - vidx] = adj_m_dim; opt_sp = sp_via; } } if (opt_sp[0] < 0) { // fail to find legal via enclosure // continue searching if (nx_max > 1) heap.emplace((nx_max - 1) * ny_max, std::array<cnt_t, 2>{nx_max - 1, ny_max}); if (ny_max > 1) heap.emplace(nx_max * (ny_max - 1), std::array<cnt_t, 2>{nx_max, ny_max - 1}); } else { // solution found // set space to 0 if ony 1 via, this prevents space with MAX_INT values. if (num_via[0] == 1) opt_sp[0] = 0; if (num_via[1] == 1) opt_sp[1] = 0; auto enc1x = (opt_mdim[0][0] - opt_arr_dim[0]) / 2; auto enc1y = (opt_mdim[0][1] - opt_arr_dim[1]) / 2; auto enc2x = (opt_mdim[1][0] - opt_arr_dim[0]) / 2; auto enc2y = (opt_mdim[1][1] - opt_arr_dim[1]) / 2; ans = {num_via[0], num_via[1], cut_dim[0], cut_dim[1], opt_sp[0], opt_sp[1], enc1x, enc1x, enc1y, enc1y, enc2x, enc2x, enc2y, enc2y}; return ans; } heap.pop(); } return ans; } } // namespace layout } // namespace cbag
33.538043
100
0.548371
ayan-biswas
aaf016f32ce3906c2fa2fce3b6566591d934c872
634
cpp
C++
libtes3/RecordTypes/STAT.cpp
btdavis/libtes3
d10e4adabaf53e3cbd48e8228aa9986fd12480b2
[ "MIT" ]
null
null
null
libtes3/RecordTypes/STAT.cpp
btdavis/libtes3
d10e4adabaf53e3cbd48e8228aa9986fd12480b2
[ "MIT" ]
null
null
null
libtes3/RecordTypes/STAT.cpp
btdavis/libtes3
d10e4adabaf53e3cbd48e8228aa9986fd12480b2
[ "MIT" ]
null
null
null
#include "STAT.h" namespace libtes3 { STAT::STAT(const TES3Record& from) : TES3Record(from) { for (const auto& subrecord : from) { auto reader = subrecord.subrecordData(); if (subrecord.subrecordType() == MakeRecordType('NAME')) { reader.readString(m_name); } else if (subrecord.subrecordType() == MakeRecordType('MODL')) { reader.readString(m_model); } } } std::string STAT::id() const { return std::string(name()); } std::string_view STAT::name() const { return m_name; } std::string_view STAT::model() const { return m_model; } }
15.85
65
0.596215
btdavis
aaf819927a553c204e0ad1807bbfe5dbb9672f02
61
cpp
C++
Engine/Source/Render/Image/Image.cpp
TzuChieh/XenoGameEngine
69d7524ee05491c8e6f8c45fdb6a12bfcecb4731
[ "MIT" ]
4
2016-09-04T12:58:44.000Z
2020-11-11T15:48:41.000Z
Engine/Source/Render/Image/Image.cpp
TzuChieh/VirtualGameEngine
69d7524ee05491c8e6f8c45fdb6a12bfcecb4731
[ "MIT" ]
1
2016-07-16T15:46:32.000Z
2016-08-05T11:01:16.000Z
Engine/Source/Render/Image/Image.cpp
TzuChieh/VirtualGameEngine
69d7524ee05491c8e6f8c45fdb6a12bfcecb4731
[ "MIT" ]
null
null
null
#include "Image.h" using namespace ve; Image::~Image() { }
7.625
19
0.639344
TzuChieh
aafc1a15e06b2f74f0902b9baf76e3c6fa96f6f4
144
hpp
C++
include/interfaces/ComponentInterface.hpp
Reesy/sdl-tridents-of-ardeus
4e806d6ae64177949b24c5f31ecdffee9588c1d0
[ "MIT" ]
null
null
null
include/interfaces/ComponentInterface.hpp
Reesy/sdl-tridents-of-ardeus
4e806d6ae64177949b24c5f31ecdffee9588c1d0
[ "MIT" ]
null
null
null
include/interfaces/ComponentInterface.hpp
Reesy/sdl-tridents-of-ardeus
4e806d6ae64177949b24c5f31ecdffee9588c1d0
[ "MIT" ]
null
null
null
#pragma once class ComponentInterface { public: virtual ~ComponentInterface() {}; virtual void receive(int message) = 0; };
18
46
0.645833
Reesy
aafdeb64033d6a39c91ea7267f139767ff41a460
468
cpp
C++
pg_answer/c3643232f6924f86abbb2b8d2ce44455.cpp
Guyutongxue/Introduction_to_Computation
062f688fe3ffb8e29cfaf139223e4994edbf64d6
[ "WTFPL" ]
8
2019-10-09T14:33:42.000Z
2020-12-03T00:49:29.000Z
pg_answer/c3643232f6924f86abbb2b8d2ce44455.cpp
Guyutongxue/Introduction_to_Computation
062f688fe3ffb8e29cfaf139223e4994edbf64d6
[ "WTFPL" ]
null
null
null
pg_answer/c3643232f6924f86abbb2b8d2ce44455.cpp
Guyutongxue/Introduction_to_Computation
062f688fe3ffb8e29cfaf139223e4994edbf64d6
[ "WTFPL" ]
null
null
null
#include <iostream> #include <queue> int main() { std::priority_queue<int, std::vector<int>, std::greater<int>> pq; int n; std::cin >> n; for (int i{0}; i < n; i++) { int x; std::cin >> x; pq.push(x); } int total{0}; while (pq.size() > 1) { int a, b; a = pq.top(), pq.pop(); b = pq.top(), pq.pop(); pq.push(a + b); total += a + b; } std::cout << total << std::endl; }
21.272727
69
0.433761
Guyutongxue
c903683a11550250c1beb1a5f92dbded7b7b5d94
6,464
cpp
C++
src/forms/credits/credits.cpp
pooki3bear/ashirt
2ef41fe7b3e6c418d8a83c894d5bc7b23b000811
[ "MIT" ]
32
2020-05-21T16:21:04.000Z
2022-03-17T18:29:41.000Z
src/forms/credits/credits.cpp
pooki3bear/ashirt
2ef41fe7b3e6c418d8a83c894d5bc7b23b000811
[ "MIT" ]
60
2020-06-08T22:02:11.000Z
2022-03-30T12:04:01.000Z
src/forms/credits/credits.cpp
pooki3bear/ashirt
2ef41fe7b3e6c418d8a83c894d5bc7b23b000811
[ "MIT" ]
6
2020-07-07T11:18:52.000Z
2021-10-09T23:39:22.000Z
// Copyright 2020, Verizon Media // Licensed under the terms of MIT. See LICENSE file in project root for terms. #include "credits.h" #include <QDateTime> #include <QKeySequence> #include "helpers/netman.h" #include "helpers/constants.h" struct Attribution { std::string library; std::string libraryUrl; std::string authors; std::string license; std::string licenseUrl; Attribution() = default; Attribution(std::string library, std::string libraryUrl, std::string authors, std::string license, std::string licenseUrl) { this->library = library; this->libraryUrl = libraryUrl; this->authors = authors; this->license = license; this->licenseUrl = licenseUrl; } }; static std::string hyperlinkMd(std::string label, std::string url) { return "[" + label + "](" + url + ")"; } static std::string attributionMarkdown() { std::vector<Attribution> attribs = { Attribution("Qt", "http://qt.io", "The Qt Company", "LGPLv3", "https://www.gnu.org/licenses/lgpl-3.0.html"), Attribution("QProgressIndicator", "https://github.com/mojocorp/QProgressIndicator", "Mojocorp, et al", "MIT License", "https://github.com/mojocorp/QProgressIndicator/blob/master/LICENSE"), Attribution("MultipartEncoder", "https://github.com/AndsonYe/MultipartEncoder", "Ye Yangang", "MIT License", "https://github.com/AndsonYe/MultipartEncoder/blob/master/LICENSE"), Attribution("UGlobalHotkey", "https://github.com/joelatdeluxe/UGlobalHotkey", "Anton Konstantinov, et al", "Public Domain", ""), Attribution("AspectRatioPixmapLabel", "https://stackoverflow.com/a/22618496/4262552", "phyatt, et al", "CC BY-SA 3.0", "https://creativecommons.org/licenses/by-sa/3.0/"), }; std::string msg = "This application uses the following open source software:\n\n" "| Project/Library | Authors | License |\n" "| --------------- | ------- | ------- |\n"; for (const auto& attrib : attribs) { std::string license; std::string suffix; if (!attrib.licenseUrl.empty()) { license += "["; suffix = "](" + attrib.licenseUrl + ")"; } license += attrib.license + suffix; // clang-format off msg += "| " + hyperlinkMd(attrib.library, attrib.libraryUrl) + " | " + attrib.authors + " | " + license + " |\n"; // clang-format on } return msg; } static std::string copyrightDate() { int initialYear = 2020; int currentYear = QDateTime::currentDateTime().date().year(); auto rtn = std::to_string(initialYear); if (currentYear != initialYear) { rtn += "-" + std::to_string(currentYear); } return rtn; } static std::string preambleMarkdown() { const std::string lf = "\n\n"; // double linefeed to add in linebreaks in markdown // clang-format off return "Version: " + Constants::releaseTag().toStdString() + lf + "Commit Hash: " + Constants::commitHash().toStdString() + lf + "Copyright " + copyrightDate() + ", Verizon Media" + lf + "Licensed under the terms of [MIT](https://github.com/theparanoids/ashirt/blob/master/LICENSE)" + lf + "A short user guide can be found " + hyperlinkMd("here", Constants::userGuideUrl().toStdString()) + lf + "Report issues " + hyperlinkMd("here", Constants::reportAnIssueUrl().toStdString()) + lf; // clang-format on } static std::string normalBodyMarkdown() { // clang-format off return "# ASHIRT\n\n" + preambleMarkdown() + "## Credits\n" + attributionMarkdown(); // clang-format on } Credits::Credits(QWidget* parent) : QDialog(parent) { buildUi(); wireUi(); } void Credits::updateRelease() { static QString baseUpdateText = "A new update is available! Click <a href=\"%1\">here</a> for more details."; if (updateDigest.hasUpgrade()) { updateLabel->setText(baseUpdateText.arg(Constants::releasePageUrl())); } else { updateLabel->setText(""); } } void Credits::buildUi() { gridLayout = new QGridLayout(this); updateLabel = new QLabel(""); updateLabel->setOpenExternalLinks(true); updateLabel->setTextFormat(Qt::RichText); updateLabel->setTextInteractionFlags(Qt::TextBrowserInteraction); creditsArea = new QTextBrowser(this); creditsArea->setOpenExternalLinks(true); creditsArea->setReadOnly(true); creditsArea->setMarkdown(normalBodyMarkdown().c_str()); buttonBox = new QDialogButtonBox(this); buttonBox->addButton(QDialogButtonBox::Close); // Layout /* 0 +------------------------------------+ 0 | update label | +------------------------------------+ | | 1 | Credits Area | | | +------------------------------------+ 2 | Dialog button Box{close} | +------------------------------------+ */ // row 0 gridLayout->addWidget(updateLabel, 0, 0); // row 1 gridLayout->addWidget(creditsArea, 1, 0); // row 2 gridLayout->addWidget(buttonBox, 2, 0); closeWindowAction = new QAction(this); closeWindowAction->setShortcut(QKeySequence::Close); this->addAction(closeWindowAction); this->setLayout(gridLayout); this->resize(640, 500); this->setWindowTitle("About"); // Make the dialog pop up above any other windows but retain title bar and buttons Qt::WindowFlags flags = this->windowFlags(); flags |= Qt::CustomizeWindowHint | Qt::WindowStaysOnTopHint | Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint; this->setWindowFlags(flags); } void Credits::wireUi() { connect(closeWindowAction, &QAction::triggered, this, &QDialog::close); connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::close); connect(&NetMan::getInstance(), &NetMan::releasesChecked, this, &Credits::onReleasesUpdate); } Credits::~Credits() { delete closeWindowAction; delete updateLabel; delete creditsArea; delete buttonBox; delete gridLayout; } void Credits::onReleasesUpdate(bool success, std::vector<dto::GithubRelease> releases) { if (!success) { return; //doesn't matter if this fails } auto digest = dto::ReleaseDigest::fromReleases(Constants::releaseTag(), releases); updateDigest = digest; updateRelease(); }
32.32
113
0.618502
pooki3bear
c907a7d8abb0aa419f55a16dd67acf2c7bb2f2ef
2,776
hpp
C++
plugin/jsbindings/auto/jsb_pluginx_umeng_auto.hpp
CocosRobot/cocos2d-x
1a527ea331363cfe108b5e2f0ac04a61f8883527
[ "Zlib", "libtiff", "BSD-2-Clause", "Apache-2.0", "MIT", "Libpng", "curl", "BSD-3-Clause" ]
1
2017-09-20T12:16:06.000Z
2017-09-20T12:16:06.000Z
plugin/jsbindings/auto/jsb_pluginx_umeng_auto.hpp
umeng/cocos2d-x
fa85e33b657e5234c1e27beb4acc5f8394b903be
[ "Zlib", "libtiff", "BSD-2-Clause", "Apache-2.0", "MIT", "Libpng", "curl", "BSD-3-Clause" ]
null
null
null
plugin/jsbindings/auto/jsb_pluginx_umeng_auto.hpp
umeng/cocos2d-x
fa85e33b657e5234c1e27beb4acc5f8394b903be
[ "Zlib", "libtiff", "BSD-2-Clause", "Apache-2.0", "MIT", "Libpng", "curl", "BSD-3-Clause" ]
null
null
null
#ifndef __pluginx_umeng_h__ #define __pluginx_umeng_h__ #include "jsapi.h" #include "jsfriendapi.h" extern JSClass *jsb_AnalyticsUmeng_class; extern JSObject *jsb_AnalyticsUmeng_prototype; JSBool js_pluginx_umeng_AnalyticsUmeng_constructor(JSContext *cx, uint32_t argc, jsval *vp); void js_pluginx_umeng_AnalyticsUmeng_finalize(JSContext *cx, JSObject *obj); void js_register_pluginx_umeng_AnalyticsUmeng(JSContext *cx, JSObject *global); void register_all_pluginx_umeng(JSContext* cx, JSObject* obj); JSBool js_pluginx_umeng_AnalyticsUmeng_setSessionContinueMillis(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_pluginx_umeng_AnalyticsUmeng_startSession(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_pluginx_umeng_AnalyticsUmeng_stopSession(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_pluginx_umeng_AnalyticsUmeng_getSDKVersion(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_pluginx_umeng_AnalyticsUmeng_updateOnlineConfig(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_pluginx_umeng_AnalyticsUmeng_logTimedEventBegin(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_pluginx_umeng_AnalyticsUmeng_logError(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_pluginx_umeng_AnalyticsUmeng_logEventWithDuration(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_pluginx_umeng_AnalyticsUmeng_checkUpdate(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_pluginx_umeng_AnalyticsUmeng_getPluginVersion(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_pluginx_umeng_AnalyticsUmeng_setDefaultReportPolicy(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_pluginx_umeng_AnalyticsUmeng_init(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_pluginx_umeng_AnalyticsUmeng_logTimedKVEventEnd(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_pluginx_umeng_AnalyticsUmeng_logTimedKVEventBegin(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_pluginx_umeng_AnalyticsUmeng_setCaptureUncaughtException(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_pluginx_umeng_AnalyticsUmeng_getConfigParams(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_pluginx_umeng_AnalyticsUmeng_getPluginName(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_pluginx_umeng_AnalyticsUmeng_logTimedEventWithLabelBegin(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_pluginx_umeng_AnalyticsUmeng_logTimedEventWithLabelEnd(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_pluginx_umeng_AnalyticsUmeng_logEvent(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_pluginx_umeng_AnalyticsUmeng_logTimedEventEnd(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_pluginx_umeng_AnalyticsUmeng_logEventWithLabel(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_pluginx_umeng_AnalyticsUmeng_setDebugMode(JSContext *cx, uint32_t argc, jsval *vp); #endif
69.4
108
0.854107
CocosRobot
c90a5ffd07483f58d5fa725b2b391e7f7836ed31
1,716
cpp
C++
src/Screen.cpp
jhonrocha/gradius
985870642c5a9cdafe0664be6ebd1e7265124126
[ "MIT" ]
null
null
null
src/Screen.cpp
jhonrocha/gradius
985870642c5a9cdafe0664be6ebd1e7265124126
[ "MIT" ]
null
null
null
src/Screen.cpp
jhonrocha/gradius
985870642c5a9cdafe0664be6ebd1e7265124126
[ "MIT" ]
null
null
null
/* * Screen.cpp * * Created on: 27/05/2013 * Author: jhonantans */ #include "Screen.h" Screen::Screen(string path, string title):background(path,3),text(title){ cout << "Screen!" << endl; screen = NULL; screen_width = background.getwidth(); screen_height = background.getheight(); screen = SDL_SetVideoMode( screen_width, screen_height, 32, SDL_SWSURFACE | SDL_RESIZABLE ); windowed = true; } Screen::~Screen() { // TODO Auto-generated destructor stub } void Screen::setScreenWidth(int screen_width){ this->screen_width = screen_width; screen = SDL_SetVideoMode( screen_width, screen_height, 32, SDL_SWSURFACE | SDL_RESIZABLE ); } void Screen::setScreenHeight(int screen_height){ this->screen_height = screen_height; screen = SDL_SetVideoMode( screen_width, screen_height, 32, SDL_SWSURFACE | SDL_RESIZABLE ); } int Screen::getScreenWidth(){ return screen_width; } int Screen::getScreenHeight(){ return screen_height; } void Screen::show_screen(){ SDL_Flip(screen); } void Screen::handle_events(SDL_Event event){ if( event.type == SDL_VIDEORESIZE ){ screen = SDL_SetVideoMode( event.resize.w, event.resize.h, 32, SDL_SWSURFACE | SDL_RESIZABLE ); } else if( ( event.type == SDL_KEYDOWN ) && ( event.key.keysym.sym == SDLK_RETURN ) ){ fullscreen(); } } void Screen::fullscreen(){ if( windowed == true ){ screen = SDL_SetVideoMode( screen_width, screen_height, 32, SDL_SWSURFACE | SDL_RESIZABLE | SDL_FULLSCREEN ); windowed = false; } //If the screen is fullscreen else if( windowed == false ){ screen = SDL_SetVideoMode( screen_width, screen_height, 32, SDL_SWSURFACE | SDL_RESIZABLE ); windowed = true; } }
25.235294
114
0.700466
jhonrocha
c90ecc854d83290814e4caec5372f49b44d8eb8a
1,511
hpp
C++
Tests/Performance/Logger.hpp
ulisesten/xalanc
a722de08e61ce66965c4a828242f7d1250950621
[ "Apache-2.0" ]
24
2015-07-29T22:49:17.000Z
2022-03-25T10:14:17.000Z
Tests/Performance/Logger.hpp
ulisesten/xalanc
a722de08e61ce66965c4a828242f7d1250950621
[ "Apache-2.0" ]
14
2019-05-10T16:25:50.000Z
2021-11-24T18:04:47.000Z
Tests/Performance/Logger.hpp
ulisesten/xalanc
a722de08e61ce66965c4a828242f7d1250950621
[ "Apache-2.0" ]
28
2015-04-20T15:50:51.000Z
2022-01-26T14:56:55.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. */ #if !defined(LOGGER_HEADER_GUARD_1357924680) #define LOGGER_HEADER_GUARD_1357924680 // Base header file. Must be first. #include <xalanc/Include/PlatformDefinitions.hpp> #include <iosfwd> #include <xalanc/XalanDOM/XalanDOMString.hpp> class Logger { public: typedef std::ostream StreamType; Logger(StreamType& stream); enum eLogType { eMessage = 0, eWarning = 1, eError = 2 }; StreamType& message(); StreamType& warning(); StreamType& error(); StreamType& log(eLogType logType); protected: const char* logText[3]; StreamType& m_stream; }; #endif //LOGGER_HEADER_GUARD_1357924680
20.418919
75
0.70086
ulisesten
c91187fb0741abb8e7b069a4b17f476b64ee2d4a
52
cpp
C++
source/segment/extrusion_move.cpp
ameisen/gcgg
6ee9a841ddd88182c235a688e6b7d8894f7af1fe
[ "Apache-2.0" ]
null
null
null
source/segment/extrusion_move.cpp
ameisen/gcgg
6ee9a841ddd88182c235a688e6b7d8894f7af1fe
[ "Apache-2.0" ]
null
null
null
source/segment/extrusion_move.cpp
ameisen/gcgg
6ee9a841ddd88182c235a688e6b7d8894f7af1fe
[ "Apache-2.0" ]
null
null
null
#include "gcgg.hpp" #include "extrusion_move.hpp"
17.333333
30
0.730769
ameisen
c911911f658ff36a426a010d4c7b03b72bc5c297
727
cc
C++
Dates/src/dates.cc
ULL-ESIT-IB-2020-2021/ib-practica11-oop-cmake-SergioPerera
58b6d9fac4667fead018dc94ccbfbefa1c59a8c2
[ "MIT" ]
null
null
null
Dates/src/dates.cc
ULL-ESIT-IB-2020-2021/ib-practica11-oop-cmake-SergioPerera
58b6d9fac4667fead018dc94ccbfbefa1c59a8c2
[ "MIT" ]
null
null
null
Dates/src/dates.cc
ULL-ESIT-IB-2020-2021/ib-practica11-oop-cmake-SergioPerera
58b6d9fac4667fead018dc94ccbfbefa1c59a8c2
[ "MIT" ]
null
null
null
#pragma once #include <iostream> #include <dates.h> #include <tools.h> #include <string> #include <fstream> #include <cstdlib> int main (int argc,char *argv[]){ Usage (argc, argv); int day_ {std::stoi(argv[1])}; int month_ {std::stoi(argv[2])}; int year_ {std::stoi(argv[3])}; int later_dates_number_ {std::stoi(argv[4])}; std::string archive_name {argv[5]}; DateClass in_date(day_, month_, year_, later_dates_number_); std::ofstream archive; archive.open(archive_name,std::ios::out); if(archive.fail()){ std::cout << "Error al crear el archivo" << std::endl; exit(EXIT_SUCCESS); } in_date.Print(archive); in_date.NextDates(archive); in_date.LeapYear(archive); archive.close(); }
21.382353
62
0.669876
ULL-ESIT-IB-2020-2021
c914a0a9d9869b59dba292c162610b6119e83235
1,724
cpp
C++
implementation/cpl_guiapplication/cpl_guiengine/cpl_wxguiobjects/cpl_wxmaintoolbar.cpp
cayprogram/cpl_main
9cc8f4c8cf33465506bdb18ddc84340992b16494
[ "MIT" ]
null
null
null
implementation/cpl_guiapplication/cpl_guiengine/cpl_wxguiobjects/cpl_wxmaintoolbar.cpp
cayprogram/cpl_main
9cc8f4c8cf33465506bdb18ddc84340992b16494
[ "MIT" ]
null
null
null
implementation/cpl_guiapplication/cpl_guiengine/cpl_wxguiobjects/cpl_wxmaintoolbar.cpp
cayprogram/cpl_main
9cc8f4c8cf33465506bdb18ddc84340992b16494
[ "MIT" ]
null
null
null
#include "cpl_wxguiobjectincludes.h" //local includes. #include "cpl_wxmaintoolbar.h" #include "cpl_wxmaintoolbarnormal.h" //----------------------------------------------------------------------------- // class cpl_wxMainToolbar //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- #if 0 wxPanel* cpl_wxMainToolbar::Create(int w, int h) { //@@preconditions assert(this->Owner != NULL); assert(w > 0); assert(h > 0); //@@end preconditions this->PPanel = new wxPanel(this->Owner, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxNO_BORDER); this->PPanel->SetSize(w, h); this->PPanel->SetMinSize(wxSize(-1, h)); this->PPanel->SetBackgroundColour(wxColour(223, 226, 229)); //this->PPanel->SetBackgroundColour(wxColour(204, 209, 212)); //this->PPanel->SetBackgroundColour(wxColour(128, 125, 120)); //this->PPanel->SetBackgroundColour(wxColour(173, 179, 183)); //this->PPanel->SetBackgroundColour(wxColour(6, 132, 200)); //this->PPanel->SetBackgroundColour(wxColour(4, 122, 172)); //this->PPanel->SetBackgroundColour(wxColour(153, 169, 188)); //create sub controls. //this->CreateSubControls(bw, bh); //this->BindControls(); this->boxw = w; this->boxh = h; return this->PPanel; } #endif //----------------------------------------------------------------------------- cpl_wxMainToolbar::cpl_wxMainToolbar(cpl_wxMainFrame* pOwner) : Owner(pOwner), PPanel(0) { this->tbBOXw = 0; this->tbBOXh = 0; } //----------------------------------------------------------------------------- cpl_wxMainToolbar::~cpl_wxMainToolbar() { }
32.528302
101
0.519722
cayprogram
c918a9b74eb7f53ed9d5b4d0d1adcc5515bb8282
4,852
cpp
C++
src/SimpleEngine/Resource/ResourceManager.cpp
SlavaGrasiuk/SiberianLynx
2047802c5b7b79ecddbb45dc193f553e7da522f5
[ "MIT" ]
null
null
null
src/SimpleEngine/Resource/ResourceManager.cpp
SlavaGrasiuk/SiberianLynx
2047802c5b7b79ecddbb45dc193f553e7da522f5
[ "MIT" ]
null
null
null
src/SimpleEngine/Resource/ResourceManager.cpp
SlavaGrasiuk/SiberianLynx
2047802c5b7b79ecddbb45dc193f553e7da522f5
[ "MIT" ]
null
null
null
#include "../include/Resource/ResourceManager.hpp" #include "ZipFile.hpp" #include "../Utilities/String.hpp" #include <cstring> /* ================== ResourceZipFile::~ResourceZipFile ================== */ ResourceZipFile::~ResourceZipFile() { if (m_zipFile) { delete m_zipFile; } } /* ================== ResourceZipFile::Open ================== */ bool ResourceZipFile::Open() { m_zipFile = new(std::nothrow) ZipFile; if (m_zipFile) { return m_zipFile->Init(m_resFileName); } return false; } /* ================== ResourceZipFile::GetRawResourceSize ================== */ int ResourceZipFile::GetRawResourceSize(const std::string & r) { const int resNum = m_zipFile->Find(r); if (resNum == -1) { return -1; } return m_zipFile->GetFileLen(resNum); } /* ================== ResourceZipFile::GetRawResource ================== */ size_t ResourceZipFile::GetRawResource(const std::string &r, uint8_t *buffer) { const int resNum = m_zipFile->Find(r); if (resNum == -1) { return 0; } const int resSize = m_zipFile->GetFileLen(resNum); return m_zipFile->ReadFile(resNum, buffer) ? resSize : 0; } /* ================== ResourceZipFile::GetNumResources ================== */ int ResourceZipFile::GetNumResources() const { return (m_zipFile == nullptr) ? 0 : m_zipFile->GetNumFiles(); } /* ================== ResourceZipFile::GetResourceName ================== */ std::string ResourceZipFile::GetResourceName(int num) const { if (m_zipFile == nullptr) { return ""; } return m_zipFile->GetFilename(num); } /* ================== ResHandle::~ResHandle ================== */ ResHandle::~ResHandle() { if (m_buffer) { delete[] m_buffer; } } /* ================== ResourceManager::~ResourceManager ================== */ ResourceManager::~ResourceManager() { if (m_resFile) { delete m_resFile; } } /* ================== ResourceManager::Init ================== */ bool ResourceManager::Init() { bool result = false; if (m_resFile->Open()) { RegisterLoader(make_shared<DefaultResourceLoader>()); result = true; } return result; } /* ================== ResourceManager::GetHandle ================== */ ResHandlePtr ResourceManager::GetHandle(const std::string & r) { auto weakHandle = Find(r); if (!weakHandle.expired()) { // resource already loaded return weakHandle.lock(); } auto handle = Load(r); if (handle) { // if resource found, store weak_ptr to loaded resources map m_loadedResources[r] = handle; } return handle; } /* ================== ResourceManager::Find ================== */ std::weak_ptr<ResHandle> ResourceManager::Find(const std::string & r) { auto it = m_loadedResources.find(r); if (it == m_loadedResources.end()) { // resource not found in map return std::weak_ptr<ResHandle>(); } if (it->second.expired()) { // resource record found, but resource was deleted m_loadedResources.erase(r); return std::weak_ptr<ResHandle>(); } return it->second; // valid resource found } /* ================== ResourceManager::Load Read resource from resource archive and unpack it. ================== */ ResHandlePtr ResourceManager::Load(const std::string & r) { std::shared_ptr<ResHandle> handle; auto loader = FindLoader(r); if (!loader) { return handle; //default loader not found } const int rawSize = m_resFile->GetRawResourceSize(r); if (rawSize < 0) { return handle; //resource not found in archive } const size_t allocSize = rawSize + ((loader->AddNullZero()) ? 1 : 0); uint8_t *rawBuffer = loader->UseRawFile() ? /*Allocate(allocSize)*/ new(std::nothrow) uint8_t[allocSize] : new(std::nothrow) uint8_t[allocSize]; if (!rawBuffer) { return handle; //out of memory } memset(rawBuffer, 0, allocSize); if (!m_resFile->GetRawResource(r, rawBuffer)) { return handle; //error reading raw resource } uint8_t *buffer = nullptr; size_t size; if (loader->UseRawFile()) { buffer = rawBuffer; handle = make_shared<ResHandle>(r, buffer, size); } else { size = loader->GetLoadedResourceSize(rawBuffer, rawSize); if (size) { buffer = /*Allocate(size)*/ new(std::nothrow) uint8_t[size]; if (!buffer) { return handle; //out of memory } } handle = make_shared<ResHandle>(r, buffer, size); const bool success = loader->LoadResource(rawBuffer, rawSize, handle); if (loader->DiscardRawBufferAfterLoad() && rawBuffer) { delete[] rawBuffer; } if (!success) { return std::shared_ptr<ResHandle>(); //out of memory } } return handle; } /* ================== ResourceManager::FindLoader ================== */ std::shared_ptr<IResourceLoader> ResourceManager::FindLoader(const std::string & r) { std::shared_ptr<IResourceLoader> loader; for (auto testLoader : m_loaders) { if (WildcardMatch(testLoader->GetPattern(), r.c_str())) { loader = testLoader; break; } } return loader; }
20.646809
145
0.622836
SlavaGrasiuk
c91a6b78c055a07b257c33294d2a9da329f318ee
16,184
cpp
C++
src/core/game.cpp
andrerogers/Enjin
ba9fd8be66b5dcac312d6887edb1ba12d3d3e48c
[ "MIT" ]
null
null
null
src/core/game.cpp
andrerogers/Enjin
ba9fd8be66b5dcac312d6887edb1ba12d3d3e48c
[ "MIT" ]
null
null
null
src/core/game.cpp
andrerogers/Enjin
ba9fd8be66b5dcac312d6887edb1ba12d3d3e48c
[ "MIT" ]
null
null
null
#include "game.h" // Default Constructor Game::Game() { } // Parameter Constructor Game::Game(const GLfloat& width, const GLfloat& height) : m_width(width), m_height(height) { m_mainCamera = Camera(m_width, m_height); m_lastXPos = 400.0f; m_lastYPos = 300.0f; m_firstMouse = true; Initialize(); } // Destructor Game::~Game() { } // Intialize the game void Game::Initialize() { m_texBox = Texture2D("assets/textures/container.jpg"); m_teapot = Model("assets/models/teapot.obj"); m_terrain = Model("assets/models/terrain/terrain.obj"); m_boxObj = CreateBoxMesh(2.0f); m_lampObj = CreateBoxMesh(0.05f); m_lampShader = Shader("assets/shaders/lamp.vs", "assets/shaders/lamp.fs"); m_rigidBoxShader = Shader("assets/shaders/rigidBox.vs", "assets/shaders/rigidBox.fs"); m_terrainShader = Shader("assets/shaders/terrain.vs", "assets/shaders/terrain.fs"); m_explodeShader = Shader("assets/shaders/explode.vs", "assets/shaders/explode.fs", "assets/shaders/explode.gs"); m_projection = m_mainCamera.GetProjectionMatrix(); m_lightDirectional = DirectionalLight(vec3(-0.2f, -1.0f, -0.3f), vec3(0.05f), vec3(0.05f), vec3(1.0f)); m_lightPoints.reserve(k_N_POINT_LIGHTS * sizeof(PointLight)); vec3 pointLightPositions[k_N_POINT_LIGHTS] = { vec3(0.0f, 0.0f, 0.0f), vec3(20.3f, 1.6f, 20.0f), vec3(-40.3f, 2.0f, -10.0f), vec3(0.3f, -1.6f, -20.0f), vec3(15.3f, 0.0f, 30.0f) }; for (unsigned int i = 0; i < k_N_POINT_LIGHTS; ++i) m_lightPoints.push_back(PointLight(pointLightPositions[i], 1.0f, 0.009f, 0.0032f, vec3(0.2f), vec3(0.5f), vec3(1.0f))); m_lightSpot = SpotLight(vec3(-20.3f, 0.0f, -50.0f), vec3(0.0f, -1.0f, 0.0f), 1.0f, 0.009f, 0.0032f, vec3(1.0f), vec3(0.8f), vec3(1.0f), glm::cos(glm::radians(12.5f)), glm::cos(glm::radians(17.5f))); m_explodeDelta = 0.0f; m_angle = 0.0f; // Set Terrain Shader Uniforms m_terrainShader.Use(); glUniform3f(glGetUniformLocation(m_terrainShader.GetProgram(), "_eyePos"), m_mainCamera.GetPosition().x, m_mainCamera.GetPosition().y, m_mainCamera.GetPosition().z); SetLightUniforms(m_terrainShader); glUniform3f(glGetUniformLocation(m_terrainShader.GetProgram(), "_material.ambient"), 0.05f, 0.05f, 0.05f); glUniform3f(glGetUniformLocation(m_terrainShader.GetProgram(), "_material.diffuse"), 0.151f, 0.151f, 0.151f); glUniform3f(glGetUniformLocation(m_terrainShader.GetProgram(), "_material.specular"), 0.297254f, 0.30829f, 0.306678f); glUniform1f(glGetUniformLocation(m_terrainShader.GetProgram(), "_material.shininess"), 0.1f * 128.0f); glUseProgram(0); // Set Explode Shader Uniforms m_explodeShader.Use(); glUniform3f(glGetUniformLocation(m_explodeShader.GetProgram(), "_eyePos"), m_mainCamera.GetPosition().x, m_mainCamera.GetPosition().y, m_mainCamera.GetPosition().z); glUniform1f(glGetUniformLocation(m_explodeShader.GetProgram(), "_time"), float(glfwGetTime())); glUniform3f(glGetUniformLocation(m_explodeShader.GetProgram(), "_material.ambient"), 1.0f, 0.5f, 0.3f); glUniform3f(glGetUniformLocation(m_explodeShader.GetProgram(), "_material.diffuse"), 1.0f, 0.5f, 0.3f); glUniform3f(glGetUniformLocation(m_explodeShader.GetProgram(), "_material.specular"), 0.5f, 0.5f, 0.5f); glUniform1f(glGetUniformLocation(m_explodeShader.GetProgram(), "_material.shininess"), 32.0f); SetLightUniforms(m_explodeShader); glUseProgram(0); } // Update the game void Game::Update() { m_mainCamera.Update(); m_angle += 0.5f * 0.01f; if (m_angle > 360.0f) m_angle = 0.0f; } // Render the game void Game::Render() { m_view = m_mainCamera.GetViewMatrix(); // Clear the colorbuffer glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); RenderLamps(); RenderRigidBoxes(); RenderTerrain(); RenderExplodingTeapot(); } RenderObject Game::CreateBoxMesh(float size) { // Set up vertex data (and buffer(s)) and attribute pointers GLfloat vertices[] = { // Positions // Normals // Texture Coords -size, -size, -size, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, size, -size, -size, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, size, size, -size, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, size, size, -size, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, -size, size, -size, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, -size, -size, -size, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -size, -size, size, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, size, -size, size, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, size, size, size, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, size, size, size, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, -size, size, size, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, -size, -size, size, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, -size, size, size, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, -size, size, -size, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f, -size, -size, -size, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, -size, -size, -size, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, -size, -size, size, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -size, size, size, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, size, size, size, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, size, size, -size, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, size, -size, -size, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, size, -size, -size, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, size, -size, size, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, size, size, size, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, -size, -size, -size, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, size, -size, -size, 0.0f, -1.0f, 0.0f, 1.0f, 1.0f, size, -size, size, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, size, -size, size, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, -size, -size, size, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, -size, -size, -size, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, -size, size, -size, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, size, size, -size, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, size, size, size, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, size, size, size, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, -size, size, size, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, -size, size, -size, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f }; return RenderObject(vertices, (8 * 6) * 6, 36); } void Game::RenderRigidBoxes() { m_rigidBoxShader.Use(); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, m_texBox.GetTextureUnit()); glUniform1i(glGetUniformLocation(m_lampShader.GetProgram(), "_texture"), 0); // Load Identity Matrix m_model = mat4(); // Translate to origin m_model = glm::translate(m_model, vec3(10.0f, 1.0f, 10.0f)); m_model = glm::rotate(m_model, m_angle, vec3(1.0f, 0.0f, 1.0f)); // Calculate Model View Projection Matrix mvp => projetction * view * model m_mvp = m_projection * m_view * m_model; glUniformMatrix4fv(glGetUniformLocation(m_lampShader.GetProgram(), "_mvpMat"), 1, GL_FALSE, glm::value_ptr(m_mvp)); // Render Box //glBindVertexArray(m_boxVAO); //glDrawArrays(GL_TRIANGLES, 0, 36); //glBindVertexArray(0); m_boxObj.DrawObject(); glBindTexture(GL_TEXTURE_2D, 0); glUseProgram(0); } void Game::RenderLamps() { m_lampShader.Use(); for (unsigned int i = 0; i < k_N_POINT_LIGHTS; ++i) { // Load Identity Matrix m_model = mat4(); // Translate to origin m_model = glm::translate(m_model, m_lightPoints[i].GetPosition()); // Calculate Model View Projection Matrix mvp => projetction * view * model m_mvp = m_projection * m_view * m_model; glUniformMatrix4fv(glGetUniformLocation(m_lampShader.GetProgram(), "_mvpMat"), 1, GL_FALSE, glm::value_ptr(m_mvp)); // Render Lamp m_lampObj.DrawObject(); } glUseProgram(0); } void Game::RenderTerrain() { // Terrain m_terrainShader.Use(); vec3 lightColor; lightColor.x = sin(float(glfwGetTime()) * 3.0f); lightColor.y = sin(float(glfwGetTime()) * 1.7f); lightColor.z = sin(float(glfwGetTime()) * 2.3f); vec3 diffuseColor = lightColor * glm::vec3(0.75f); // Decrease the influence vec3 ambientColor = diffuseColor * glm::vec3(0.25f); // Low influence m_lightSpot.SetAmbient(ambientColor); m_lightSpot.SetDiffuse(diffuseColor); glUniform3f(glGetUniformLocation(m_terrainShader.GetProgram(), "_spotLight.ambeint"), m_lightSpot.GetAmbient().x, m_lightSpot.GetAmbient().y, m_lightSpot.GetAmbient().z); glUniform3f(glGetUniformLocation(m_terrainShader.GetProgram(), "_spotLight.diffuse"), m_lightSpot.GetDiffuse().x, m_lightSpot.GetDiffuse().y, m_lightSpot.GetDiffuse().z); // Load Identity Matrix m_model = mat4(); // Translate to origin m_model = glm::translate(m_model, vec3(0.0f, -10.0f, 0.0f)); glUniformMatrix4fv(glGetUniformLocation(m_terrainShader.GetProgram(), "_modelMat"), 1, GL_FALSE, glm::value_ptr(m_model)); // Calculate Model View Projection Matrix mvp => projetction * view * model m_mvp = m_projection * m_view * m_model; glUniformMatrix4fv(glGetUniformLocation(m_terrainShader.GetProgram(), "_mvpMat"), 1, GL_FALSE, glm::value_ptr(m_mvp)); // Calculate Normal Matrix for models Normal => mat3(transpose(inverse(model))) m_normal = glm::inverse(m_model); m_normal = glm::transpose(m_normal); glUniformMatrix4fv(glGetUniformLocation(m_terrainShader.GetProgram(), "_normalMat"), 1, GL_FALSE, glm::value_ptr(m_normal)); m_terrain.Render(m_terrainShader); glUseProgram(0); } void Game::RenderExplodingTeapot() { m_explodeShader.Use(); glUniform1f(glGetUniformLocation(m_explodeShader.GetProgram(), "_explodeBias"), m_explodeDelta); vec3 lightColor; lightColor.x = sin(float(glfwGetTime()) * 2.0f); lightColor.y = sin(float(glfwGetTime()) * 0.7f); lightColor.z = sin(float(glfwGetTime()) * 1.3f); vec3 diffuseColor = lightColor * glm::vec3(0.5f); // Decrease the influence vec3 ambientColor = diffuseColor * glm::vec3(0.2f); // Low influence m_lightPoints[0].SetAmbient(ambientColor); m_lightPoints[0].SetDiffuse(diffuseColor); glUniform3f(glGetUniformLocation(m_explodeShader.GetProgram(), "_pointLights[0].ambient"), m_lightPoints[0].GetAmbient().x, m_lightPoints[0].GetAmbient().y, m_lightPoints[0].GetAmbient().z); glUniform3f(glGetUniformLocation(m_explodeShader.GetProgram(), "_pointLights[0].diffuse"), m_lightPoints[0].GetDiffuse().x, m_lightPoints[0].GetDiffuse().y, m_lightPoints[0].GetDiffuse().z); // Load Identity Matrix m_model = mat4(); // Translate to origin m_model = glm::translate(m_model, vec3(0.0f, 0.5f, 0.0f)); m_model = glm::scale(m_model, vec3(2.0f, 2.0f, 2.0f)); m_model = glm::rotate(m_model, m_angle, vec3(0.0f, 1.0f, 0.0f)); glUniformMatrix4fv(glGetUniformLocation(m_explodeShader.GetProgram(), "_modelMat"), 1, GL_FALSE, glm::value_ptr(m_model)); // Calculate Model View Projection Matrix mvp => projetction * view * model m_mvp = m_projection * m_view * m_model; glUniformMatrix4fv(glGetUniformLocation(m_explodeShader.GetProgram(), "_mvpMat"), 1, GL_FALSE, glm::value_ptr(m_mvp)); // Calculate Normal Matrix for models Normal => mat3(transpose(inverse(model))) m_normal = glm::inverse(m_model); m_normal = glm::transpose(m_normal); glUniformMatrix4fv(glGetUniformLocation(m_explodeShader.GetProgram(), "_normalMat"), 1, GL_FALSE, glm::value_ptr(m_normal)); m_teapot.Render(m_explodeShader); glUseProgram(0); } void Game::SetLightUniforms(Shader shader) { string pointLightUniformName = ""; glUniform3f(glGetUniformLocation(shader.GetProgram(), "_directionalLight.direction"), m_lightDirectional.GetDirection().x, m_lightDirectional.GetDirection().y, m_lightDirectional.GetDirection().z); glUniform3f(glGetUniformLocation(shader.GetProgram(), "_directionalLight.ambient"), m_lightDirectional.GetAmbient().x, m_lightDirectional.GetAmbient().y, m_lightDirectional.GetAmbient().z); glUniform3f(glGetUniformLocation(shader.GetProgram(), "_directionalLight.diffuse"), m_lightDirectional.GetDiffuse().x, m_lightDirectional.GetDiffuse().y, m_lightDirectional.GetDiffuse().z); glUniform3f(glGetUniformLocation(shader.GetProgram(), "_directionalLight.specular"), m_lightDirectional.GetSpecular().x, m_lightDirectional.GetSpecular().y, m_lightDirectional.GetSpecular().z); for (unsigned int i = 0; i < k_N_POINT_LIGHTS; ++i) { pointLightUniformName = "_pointLights[" + std::to_string(i) + "]"; glUniform3f(glGetUniformLocation(shader.GetProgram(), (pointLightUniformName + ".position").c_str()), m_lightPoints[i].GetPosition().x, m_lightPoints[i].GetPosition().y, m_lightPoints[i].GetPosition().z); glUniform3f(glGetUniformLocation(shader.GetProgram(), (pointLightUniformName + ".ambient").c_str()), m_lightPoints[i].GetAmbient().x, m_lightPoints[i].GetAmbient().y, m_lightPoints[i].GetAmbient().z); glUniform3f(glGetUniformLocation(shader.GetProgram(), (pointLightUniformName + ".diffuse").c_str()), m_lightPoints[i].GetDiffuse().x, m_lightPoints[i].GetDiffuse().y, m_lightPoints[i].GetDiffuse().z); glUniform3f(glGetUniformLocation(shader.GetProgram(), (pointLightUniformName + ".specular").c_str()), m_lightPoints[i].GetSpecular().x, m_lightPoints[i].GetSpecular().y, m_lightPoints[i].GetSpecular().z); glUniform1f(glGetUniformLocation(shader.GetProgram(), (pointLightUniformName + ".constant").c_str()), m_lightPoints[i].GetConstant()); glUniform1f(glGetUniformLocation(shader.GetProgram(), (pointLightUniformName + ".linear").c_str()), m_lightPoints[i].GetLinear()); glUniform1f(glGetUniformLocation(shader.GetProgram(), (pointLightUniformName + ".quadratic").c_str()), m_lightPoints[i].GetQuadratic()); } glUniform3f(glGetUniformLocation(shader.GetProgram(), "_spotLight.position"), m_lightSpot.GetPosition().x, m_lightSpot.GetPosition().y, m_lightSpot.GetPosition().z); glUniform3f(glGetUniformLocation(shader.GetProgram(), "_spotLight.direction"), m_lightSpot.GetDirection().x, m_lightSpot.GetDirection().y, m_lightSpot.GetDirection().z); glUniform3f(glGetUniformLocation(shader.GetProgram(), "_spotLight.ambeint"), m_lightSpot.GetAmbient().x, m_lightSpot.GetAmbient().y, m_lightSpot.GetAmbient().z); glUniform3f(glGetUniformLocation(shader.GetProgram(), "_spotLight.diffuse"), m_lightSpot.GetDiffuse().x, m_lightSpot.GetDiffuse().y, m_lightSpot.GetDiffuse().z); glUniform3f(glGetUniformLocation(shader.GetProgram(), "_spotLight.specular"), m_lightSpot.GetSpecular().x, m_lightSpot.GetSpecular().y, m_lightSpot.GetSpecular().z); glUniform1f(glGetUniformLocation(shader.GetProgram(), "_spotLight.constant"), m_lightSpot.GetConstant()); glUniform1f(glGetUniformLocation(shader.GetProgram(), "_spotLight.linear"), m_lightSpot.GetLinear()); glUniform1f(glGetUniformLocation(shader.GetProgram(), "_spotLight.quadratic"), m_lightSpot.GetQuadratic()); glUniform1f(glGetUniformLocation(shader.GetProgram(), "_spotLight.cutOff"), m_lightSpot.GetCutoff()); glUniform1f(glGetUniformLocation(shader.GetProgram(), "_spotLight.outerCutOff"), m_lightSpot.GetOuterCutoff()); } // Handle keyboard callbacks void Game::HandleKeyboardCallblack(GLFWwindow * window, int key, int scancode, int action, int mode) { if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) glfwSetWindowShouldClose(window, GL_TRUE); if (key == GLFW_KEY_W || key == GLFW_KEY_UP) m_mainCamera.m_position += 0.25f * m_mainCamera.m_fowardDirection; if (key == GLFW_KEY_S || key == GLFW_KEY_DOWN) m_mainCamera.m_position -= 0.25f * m_mainCamera.m_fowardDirection; if (key == GLFW_KEY_A || key == GLFW_KEY_LEFT) m_mainCamera.m_position -= 0.25f * m_mainCamera.GetRight(); if (key == GLFW_KEY_D || key == GLFW_KEY_RIGHT) m_mainCamera.m_position += 0.25f * m_mainCamera.GetRight(); if (key == GLFW_KEY_Z) { if (m_explodeDelta < 3.5f) m_explodeDelta += 0.01f; } if (key == GLFW_KEY_X) { if(m_explodeDelta > 0.0f) m_explodeDelta -= 0.01f; } if (key >= 0 && key < 1024) { if (action == GLFW_PRESS) m_keys[key] = true; else if (action == GLFW_RELEASE) m_keys[key] = false; } } void Game::HandleMouseCallback(GLFWwindow* window, double xpos, double ypos) { if (m_firstMouse) { m_lastXPos = float(xpos); m_lastYPos = float(ypos); m_firstMouse = false; } GLfloat xoffset = float(xpos) - m_lastXPos; GLfloat yoffset = m_lastYPos - float(ypos); // Reversed since y-coordinates go from bottom to left m_lastXPos = float(xpos); m_lastYPos = float(ypos); m_mainCamera.ProcessMouseMovement(xoffset, yoffset); }
35.569231
199
0.703967
andrerogers
c91c97e4d17744ac9f703cc3d5bb8993b3d3a40a
1,560
hh
C++
app/src/main/include/JobDrawLine.hh
tanxiang/stbox
1ade839dc2630c94075067ce8948d04a239988be
[ "Apache-2.0" ]
null
null
null
app/src/main/include/JobDrawLine.hh
tanxiang/stbox
1ade839dc2630c94075067ce8948d04a239988be
[ "Apache-2.0" ]
null
null
null
app/src/main/include/JobDrawLine.hh
tanxiang/stbox
1ade839dc2630c94075067ce8948d04a239988be
[ "Apache-2.0" ]
null
null
null
// // Created by ttand on 19-11-11. // #pragma once #include "util.hh" //#include "Device.hh" #include "PipelineResource.hh" #include "thread.hh" #include "JobBase.hh" #include "Window.hh" namespace tt { struct JobDrawLine : public JobBase{ vk::UniqueRenderPass renderPass; //vk::UniqueRenderPass createRenderpass(tt::Device &); gpuProgram<> compPipeline; gpuProgram<> graphPipeline; BufferMemoryWithParts<4> bufferMemoryPart; BufferMemory outputMemory; vk::UniqueCommandBuffer cCommandBuffer; Thread worker; std::vector<vk::UniqueCommandBuffer> gcmdBuffers; auto getGraphisCmdBuffer(uint32_t index){ return gcmdBuffers[index].get(); } vk::UniquePipeline createGraphsPipeline(tt::Device &, android_app *app,vk::PipelineLayout pipelineLayout); vk::UniquePipeline createComputePipeline(tt::Device &, android_app *app,vk::PipelineLayout pipelineLayout); //static JobDrawLine create(android_app *app, tt::Device &device); //static JobBase createBase(tt::Device &device); JobDrawLine(android_app *app,tt::Device &device); template <typename tupleType> JobDrawLine(tupleType args):JobDrawLine(std::get<android_app*>(args),*std::get<tt::Device*>(args)){} void buildCmdBuffer(tt::Window &swapchain, vk::RenderPass renderPass); void setMVP(tt::Device &device,vk::Buffer buffer); void CmdBufferRenderPassContinueBegin(CommandBufferBeginHandle &cmdHandleBegin, vk::Extent2D win,uint32_t frameIndex); //JobDrawLine(JobDrawLine&& j) = default; BufferMemory BAM; }; }
28.888889
109
0.734615
tanxiang
c91e8246ed57f4fae75c9db9aebe169f099d6e58
636
cpp
C++
abcdef.cpp
pv2k/my_spoj
c763b1797dd5c7c78fd2255b3ba1e20e67e27c52
[ "MIT" ]
null
null
null
abcdef.cpp
pv2k/my_spoj
c763b1797dd5c7c78fd2255b3ba1e20e67e27c52
[ "MIT" ]
null
null
null
abcdef.cpp
pv2k/my_spoj
c763b1797dd5c7c78fd2255b3ba1e20e67e27c52
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define ll long long int int main() { ios::sync_with_stdio(false); unordered_map<ll,int>mp; int n,i,j,k,res=0,tmp1,tmp2,tmp3; ll var; scanf("%d",&n); int a[n]; for(i=0;i<n;i++) scanf("%d",&a[i]); for(i=0;i<n;i++) { for(j=0;j<n;j++) { for(k=0;k<n;k++) { if(a[k]==0) continue; tmp1=a[i];tmp2=a[j];tmp3=a[k]; var=(tmp1+tmp2)*tmp3; mp[var]+=1; } } } for(i=0;i<n;i++) { for(j=0;j<n;j++) { for(k=0;k<n;k++) { tmp1=a[i];tmp2=a[j];tmp3=a[k]; var=((tmp1*tmp3)+tmp2); res+=mp[var]; } } } printf("%d\n",res); return 0; }
15.142857
34
0.498428
pv2k
c92b9da382f6f945082f32e3a99d6e06338b77b7
455
cpp
C++
Bridge/Cpp/curse_spell.cpp
john29917958/Design-Patterns
86b0139d67769552a9b97d1d436b9915a513871c
[ "MIT" ]
null
null
null
Bridge/Cpp/curse_spell.cpp
john29917958/Design-Patterns
86b0139d67769552a9b97d1d436b9915a513871c
[ "MIT" ]
null
null
null
Bridge/Cpp/curse_spell.cpp
john29917958/Design-Patterns
86b0139d67769552a9b97d1d436b9915a513871c
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include "spell.h" curse_spell::curse_spell(int power, int speed, int cost) : spell(power, speed, cost) { } void curse_spell::cast() { std::cout << "Casts a curse spell with power " + std::to_string(power) + " and speed " + std::to_string(speed) + ". Shows dark flame effect and keeps damage health of enemy for 10 seconds. Applies curse effect to every enemies who collide with the target enemy." << std::endl; }
35
277
0.712088
john29917958
c92ca85c115814d18b07b0f2c305766cdebacab8
32,494
cpp
C++
sunvox_engine/psynth/psynths_spectravoice.cpp
Sound-Linux-More/sunvox
7376fbe9f9bca92be1e17aefaac2e68b558d8357
[ "BSD-3-Clause" ]
100
2016-01-15T02:43:07.000Z
2022-03-16T14:02:38.000Z
sunvox_engine/psynth/psynths_spectravoice.cpp
Sound-Linux-More/sunvox
7376fbe9f9bca92be1e17aefaac2e68b558d8357
[ "BSD-3-Clause" ]
2
2018-01-10T18:21:37.000Z
2021-12-05T01:48:08.000Z
sunvox_engine/psynth/psynths_spectravoice.cpp
Sound-Linux-More/sunvox
7376fbe9f9bca92be1e17aefaac2e68b558d8357
[ "BSD-3-Clause" ]
17
2016-05-16T19:48:19.000Z
2022-03-23T10:59:42.000Z
/* psynths_spectravoice.cpp. This file is part of the SunVox engine. Copyright (C) 2002 - 2008 Alex Zolotov <nightradio@gmail.com> */ #include "psynth.h" #include "utils/utils.h" #include "core/debug.h" #include "sound/sound.h" #ifdef SUNVOX_GUI #include "window_manager/wmanager.h" #endif //Unique names for objects in your synth: #define SYNTH_DATA psynth_spectravoice_data #define SYNTH_HANDLER psynth_spectravoice //And unique parameters: #define SYNTH_INPUTS 0 #define SYNTH_OUTPUTS 2 #define MAX_CHANNELS 16 #define MAX_HARMONICS 16 #define MAX_SAMPLES 1 #define GET_FREQ(res,per) \ { \ if( per >= 0 ) \ res = ( data->linear_tab[ per % 768 ] >> ( per / 768 ) ); \ else \ res = ( data->linear_tab[ (7680*4+per) % 768 ] << -( ( (7680*4+per) / 768 ) - (7680*4)/768 ) ); /*if period is negative value*/ \ } #define GET_DELTA(f,resh,resl) \ { \ resh = f / pnet->sampling_freq; \ resl = ( ( ( f % pnet->sampling_freq ) << 14 ) / pnet->sampling_freq ) << 2; /*Max sampling freq = 256 kHz*/ \ } struct gen_channel { int playing; ulong id; int vel; int ptr_h; int ptr_l; ulong delta_h; ulong delta_l; ulong env_vol; int sustain; //Local controllers: CTYPE local_pan; }; enum { MODE_HQ = 0, MODE_HQ_MONO, MODE_LQ, MODE_LQ_MONO, MODE_CUBIC, MODES }; struct SYNTH_DATA { //Controls: ############################################################ CTYPE ctl_volume; CTYPE ctl_pan; CTYPE ctl_attack; CTYPE ctl_release; CTYPE ctl_channels; CTYPE ctl_mode; CTYPE ctl_sustain; CTYPE ctl_sample_size; CTYPE ctl_harm; CTYPE ctl_freq; CTYPE ctl_freq_vol; CTYPE ctl_freq_band; CTYPE ctl_freq_type; CTYPE ctl_samples; //Synth data: ########################################################## gen_channel channels[ MAX_CHANNELS ]; int search_ptr; ulong *linear_tab; uint16 *freq; uchar *freq_vol; uchar *freq_band; uchar *freq_type; int16 *samples[ MAX_SAMPLES ]; int sample_size; int note_offset; }; #define SVOX_PREC (long)16 //sample pointer (fixed point) precision #define SIGNED_SUB64( v1, v1_p, v2, v2_p ) \ { v1 -= v2; v1_p -= v2_p; \ if( v1_p < 0 ) { v1--; v1_p += ( (long)1 << SVOX_PREC ); } } #define SIGNED_ADD64( v1, v1_p, v2, v2_p ) \ { v1 += v2; v1_p += v2_p; \ if( v1_p > ( (long)1 << SVOX_PREC ) - 1 ) { v1++; v1_p -= ( (long)1 << SVOX_PREC ); } } #define APPLY_VOLUME \ s *= vol; \ s /= 256; #define APPLY_ENV_VOLUME \ s *= ( env_vol >> 20 ); \ s /= 1024; #define ENV_CONTROL_REPLACE \ if( sustain ) \ { \ env_vol += attack_delta; \ if( env_vol >= ( 1 << 30 ) ) { env_vol = ( 1 << 30 ); if( sustain_enabled == 0 ) sustain = 0; } \ } \ else \ { \ env_vol -= release_delta; \ if( env_vol > ( 1 << 30 ) ) { env_vol = 0; playing = 0; while( i < sample_frames ) { out[ i ] = 0; i++; } break; } \ } #define ENV_CONTROL \ if( sustain ) \ { \ env_vol += attack_delta; \ if( env_vol >= ( 1 << 30 ) ) { env_vol = ( 1 << 30 ); if( sustain_enabled == 0 ) sustain = 0; } \ } \ else \ { \ env_vol -= release_delta; \ if( env_vol > ( 1 << 30 ) ) { env_vol = 0; playing = 0; break; } \ } float g_fft_sin[ 22 ] = { (float)-5.89793E-10, (float)-1, (float)-0.707106781, (float)-0.382683432, (float)-0.195090322, (float)-0.09801714, (float)-0.049067674, (float)-0.024541229, (float)-0.012271538, (float)-0.006135885, (float)-0.003067957, (float)-0.00153398, (float)-0.00076699, (float)-0.000383495, (float)-0.000191748, (float)-9.58738E-05, (float)-4.79369E-05, (float)-2.39684E-05, (float)-1.19842E-05, (float)-5.99211E-06, (float)-2.99606E-06, (float)-1.49803E-06 }; float g_fft_sin2[ 22 ] = { (float)-1, (float)-0.707106781, (float)-0.382683432, (float)-0.195090322, (float)-0.09801714, (float)-0.049067674, (float)-0.024541229, (float)-0.012271538, (float)-0.006135885, (float)-0.003067957, (float)-0.00153398, (float)-0.00076699, (float)-0.000383495, (float)-0.000191748, (float)-9.58738E-05, (float)-4.79369E-05, (float)-2.39684E-05, (float)-1.19842E-05, (float)-5.99211E-06, (float)-2.99606E-06, (float)-1.49803E-06, (float)-7.49014E-07 }; int16 g_fft_rsin[ 128 ] = { 0, 27572, 29794, 4624, -24798, -31421, -9155, 21527, 32418, 13503, -17825, -32766, -17581, 13767, 32459, 21307, -9433, -31502, -24607, 4911, 29914, 27414, -290, -27728, -29673, -4336, 24986, 31337, 8876, -21745, -32374, -13239, 18068, 32764, 17336, -14030, -32497, -21086, 9711, 31580, 24415, -5197, -30031, -27254, 580, 27881, 29548, 4049, -25173, -31251, -8597, 21961, 32328, 12973, -18309, -32758, -17089, 14291, 32533, 20863, -9987, -31656, -24220, 5483, 30146, 27092, -870, -28032, -29422, -3761, 25358, 31163, 8317, -22175, -32280, -12706, 18549, 32751, 16841, -14552, -32566, -20639, 10263, 31730, 24024, -5769, -30258, -26928, 1159, 28181, 29293, 3472, -25540, -31072, -8036, 22388, 32229, 12438, -18788, -32741, -16592, 14811, 32597, 20413, -10538, -31801, -23826, 6054, 30369, 26762, -1449, -28328, -29162, -3184, 25721, 30979, 7754, -22599, -32175, -12169, 19024, 32728, 16341, -15069, -32625, -20185, 10812, 31870 }; int16 g_fft_rcos[ 128 ] = { 32767, 17704, -13635, -32439, -21417, 9294, 31461, 24703, -4767, -29855, -27493, 145, 27650, 29734, 4480, -24892, -31379, -9016, 21636, 32396, 13371, -17947, -32765, -17459, 13899, 32478, 21197, -9572, -31541, -24511, 5054, 29973, 27334, -435, -27805, -29611, -4192, 25080, 31294, 8737, -21853, -32352, -13106, 18189, 32761, 17213, -14161, -32515, -20975, 9849, 31619, 24318, -5340, -30089, -27173, 725, 27957, 29485, 3905, -25265, -31207, -8457, 22068, 32304, 12839, -18429, -32755, -16965, 14422, 32550, 20751, -10125, -31693, -24122, 5626, 30203, 27010, -1014, -28107, -29358, -3617, 25449, 31118, 8176, -22282, -32255, -12572, 18669, 32746, 16716, -14682, -32582, -20526, 10401, 31766, 23925, -5912, -30314, -26845, 1304, 28255, 29228, 3328, -25631, -31026, -7895, 22494, 32202, 12304, -18906, -32734, -16466, 14940, 32611, 20299, -10675, -31836, -23726, 6197, 30423, 26678, -1594, -28401, -29096, -3039, 25811, 30931, 7613 }; void fft( int16 *result, float *fi, float *fr, int fft_size ); void recalc_samples( SYNTH_DATA *data, int synth_id, psynth_net *pnet ); #ifdef SUNVOX_GUI struct spectravoice_visual_data { SYNTH_DATA *synth_data; int synth_id; psynth_net *pnet; WINDOWPTR render_button; }; int spectravoice_render_handler( void *user_data, WINDOWPTR win, window_manager *wm ) { spectravoice_visual_data *data = (spectravoice_visual_data*)user_data; //Render samples: recalc_samples( data->synth_data, data->synth_id, data->pnet ); return 0; } int spectravoice_visual_handler( sundog_event *evt, window_manager *wm ) { int retval = 0; WINDOWPTR win = evt->win; spectravoice_visual_data *data = (spectravoice_visual_data*)win->data; int but_ysize = BUTTON_YSIZE( win, wm ); switch( evt->type ) { case EVT_GETDATASIZE: return sizeof( spectravoice_visual_data ); break; case EVT_AFTERCREATE: data->render_button = new_window( "Render", 0, 0, 1, 1, wm->colors[ 11 ], win, button_handler, wm ); set_handler( data->render_button, spectravoice_render_handler, data, wm ); set_window_controller( data->render_button, 0, wm, 0, CEND ); set_window_controller( data->render_button, 1, wm, 0, CEND ); set_window_controller( data->render_button, 2, wm, BUTTON_XSIZE( win, wm ), CEND ); set_window_controller( data->render_button, 3, wm, but_ysize, CEND ); retval = 1; break; case EVT_MOUSEBUTTONDOWN: case EVT_MOUSEDOUBLECLICK: case EVT_MOUSEMOVE: case EVT_MOUSEBUTTONUP: retval = 1; break; case EVT_DRAW: break; } return retval; } #endif void fft( int16 *result, float *fi, float *fr, int fft_size ) { int i; int nn = fft_size; int nm1 = nn - 1; int nd2 = nn / 2; int m = 0; while( 1 ) { if( 1 << m == fft_size ) break; m++; } int j = nd2; int k; for( i = 1; i <= nn - 2; i++ ) { if( i < j ) { float tr = fr[ j ]; float ti = fi[ j ]; fr[ j ] = fr[ i ]; fi[ j ] = fi[ i ]; fr[ i ] = tr; fi[ i ] = ti; } k = nd2; nit: if( k <= j ) { j = j - k; k = k / 2; goto nit; } j = j + k; } int mmax = 1; int n = fft_size; int istep; int cnt = 0; while( n > mmax ) { istep = mmax << 1; //istep = 2; mmax = 1; ... istep = fft_size; mmax = fft_size >> 1; float wtemp = g_fft_sin2[ cnt ]; float wpr = -2.0F * wtemp * wtemp; float wpi = g_fft_sin[ cnt ]; float wr = 1.0; float wi = 0.0; for( m = 0; m < mmax; m ++ ) //m = 0..1; 0..2; ... 0..fft_size >> 1; { for( i = m; i < n; i += istep ) { j = i + mmax; float tempr = wr * fr[ j ] - wi * fi[ j ]; float tempi = wr * fi[ j ] + wi * fr[ j ]; fr[ j ] = fr[ i ] - tempr; fi[ j ] = fi[ i ] - tempi; fr[ i ] += tempr; fi[ i ] += tempi; } wr = ( wtemp = wr ) * wpr - wi * wpi + wr; wi = wi * wpr + wtemp * wpi + wi; } mmax = istep; cnt++; } //Normalize: float max = 0; for( i = 0; i < fft_size; i++ ) { float v = fr[ i ]; if( v < 0 ) v = -v; if( v > max ) max = v; } float coef = 1.0F / max; for( i = 0; i < fft_size; i++ ) { fr[ i ] = fr[ i ] * coef; } //Save result: for( i = 0; i < fft_size; i++ ) { int ires = (int)( fr[ i ] * 32768 ); if( ires > 32767 ) ires = 32767; if( ires < -32767 ) ires = -32767; result[ i ] = (int16)ires; } } void recalc_samples( SYNTH_DATA *data, int synth_id, psynth_net *pnet ) { data->freq = (uint16*)psynth_get_chunk( synth_id, 0, pnet ); data->freq_vol = (uchar*)psynth_get_chunk( synth_id, 1, pnet ); data->freq_band = (uchar*)psynth_get_chunk( synth_id, 2, pnet ); data->freq_type = (uchar*)psynth_get_chunk( synth_id, 3, pnet ); sound_stream_stop(); mem_off(); int prev_ss = data->sample_size; data->sample_size = 4096 << data->ctl_sample_size; if( data->sample_size != prev_ss ) { if( data->samples[ 0 ] ) mem_free( data->samples[ 0 ] ); data->samples[ 0 ] = (int16*)MEM_NEW( HEAP_STORAGE, data->sample_size * sizeof( int16 ) ); } mem_on(); sound_stream_play(); int16 *smp = data->samples[ 0 ]; mem_off(); float *hr = (float*)MEM_NEW( HEAP_STORAGE, data->sample_size * sizeof( float ) ); float *hi = (float*)MEM_NEW( HEAP_STORAGE, data->sample_size * sizeof( float ) ); uchar *distribution = (uchar*)MEM_NEW( HEAP_DYNAMIC, 256 ); mem_set( hr, data->sample_size * sizeof( float ), 0 ); mem_set( hi, data->sample_size * sizeof( float ), 0 ); set_seed( 0 ); int a; for( int n = 0; n < MAX_HARMONICS; n++ ) { switch( data->freq_type[ n ] ) { case 0: case 2: case 3: case 4: case 5: //Half sin: for( a = 0; a < 256; a++ ) distribution[ a ] = g_vibrato_tab[ a ]; break; case 6: //Gaussian: for( a = 0; a < 128; a++ ) { distribution[ ( a + 64 ) & 255 ] = g_vibrato_tab[ a * 2 ] / 2 + 127; distribution[ ( ( a + 128 ) + 64 ) & 255 ] = -( g_vibrato_tab[ a * 2 ] / 2 ) + 127; } break; case 1: //Square: for( a = 0; a < 256; a++ ) distribution[ a ] = 255; break; } int clones = 1; int harmonic_vol = data->freq_vol[ n ]; int bandwidth = data->freq_band[ n ]; if( data->freq_type[ n ] >= 2 && data->freq_type[ n ] < 6 ) clones = 8; for( int cc = 0; cc < clones; cc++ ) { int ptr = ( data->freq[ n ] * data->sample_size ) / 22050; if( ptr >= data->sample_size ) ptr = data->sample_size - 1; if( cc > 0 ) { ptr += ptr * cc; if( data->freq_type[ n ] == 3 ) bandwidth += 2; if( data->freq_type[ n ] == 4 ) bandwidth += 4; if( data->freq_type[ n ] == 5 ) bandwidth += 8; } ptr /= 2; int bw = ( ( bandwidth + 1 ) * ( data->sample_size / 16 ) ) / 256; bw /= 2; if( bw <= 0 ) bw = 1; int p1 = ptr - bw; int p2 = ptr + bw; if( p1 < 0 ) p1 = 0; if( p2 >= data->sample_size / 2 ) p2 = data->sample_size / 2 - 1; for( int i = p1; i <= p2; i++ ) { int d = i - ptr; d *= ( (128<<14) / bw ); d >>= 14; if( d < 128 && d >= -128 ) { int vol = distribution[ 128 + d ]; int amp = ( harmonic_vol * vol ) / 256; int phase = pseudo_random(); hi[ i ] += (float)( ( g_fft_rsin[ phase&127 ] * amp ) / 256 ) / 32767; hr[ i ] += (float)( ( g_fft_rcos[ phase&127 ] * amp ) / 256 ) / 32767; } } } } //Make mirror part of FFT: for( int i = 0; i < data->sample_size / 2; i++ ) { hr[ data->sample_size - 1 - i ] = -hr[ i ]; hi[ data->sample_size - 1 - i ] = -hi[ i ]; } fft( smp, hi, hr, data->sample_size ); mem_free( hr ); mem_free( hi ); mem_free( distribution ); mem_on(); } int SYNTH_HANDLER( PSYTEXX_SYNTH_PARAMETERS ) { psynth_net *pnet = (psynth_net*)net; SYNTH_DATA *data = (SYNTH_DATA*)data_ptr; int retval = 0; int i; int ch; switch( command ) { case COMMAND_GET_DATA_SIZE: retval = sizeof( SYNTH_DATA ); break; case COMMAND_GET_SYNTH_NAME: retval = (int)"SpectraVoice"; break; case COMMAND_GET_SYNTH_INFO: retval = (int)"FFT Based Synth\nMin. sample size: 4096 words\nMax. sample size: 65536 words\n\nAvailable local controllers:\n * Pan"; break; case COMMAND_GET_INPUTS_NUM: retval = SYNTH_INPUTS; break; case COMMAND_GET_OUTPUTS_NUM: retval = SYNTH_OUTPUTS; break; case COMMAND_GET_FLAGS: retval = PSYNTH_FLAG_GENERATOR; break; case COMMAND_INIT: psynth_register_ctl( synth_id, "Volume", "", 0, 256, 128, 0, &data->ctl_volume, net ); psynth_register_ctl( synth_id, "Panning", "", 0, 256, 128, 0, &data->ctl_pan, net ); psynth_register_ctl( synth_id, "Attack", "", 0, 512, 10, 0, &data->ctl_attack, net ); psynth_register_ctl( synth_id, "Release", "", 0, 512, 512, 0, &data->ctl_release, net ); psynth_register_ctl( synth_id, "Polyphony", "ch.", 1, MAX_CHANNELS, 8, 1, &data->ctl_channels, net ); psynth_register_ctl( synth_id, "Mode", "HQ/HQmono/LQ/LQmono/Cubic", 0, MODES - 1, MODE_CUBIC, 1, &data->ctl_mode, net ); psynth_register_ctl( synth_id, "Sustain", "off/on", 0, 1, 1, 1, &data->ctl_sustain, net ); psynth_register_ctl( synth_id, "Sample size", "", 0, 4, 1, 1, &data->ctl_sample_size, net ); psynth_register_ctl( synth_id, "Harmonic", "", 0, MAX_HARMONICS-1, 0, 1, &data->ctl_harm, net ); psynth_register_ctl( synth_id, "h.freq", "Hz", 0, 22050, 1098, 1, &data->ctl_freq, net ); psynth_register_ctl( synth_id, "h.volume", "", 0, 255, 255, 1, &data->ctl_freq_vol, net ); psynth_register_ctl( synth_id, "h.bandwidth", "", 0, 255, 3, 1, &data->ctl_freq_band, net ); psynth_register_ctl( synth_id, "h.bandtype", "hsin/square/org1/2/3/4/sin", 0, 6, 0, 1, &data->ctl_freq_type, net ); for( int c = 0; c < MAX_CHANNELS; c++ ) { data->channels[ c ].playing = 0; data->channels[ c ].ptr_l = 0; data->channels[ c ].ptr_h = 0; data->channels[ c ].env_vol = 0; data->channels[ c ].sustain = 0; } for( int s = 0; s < MAX_SAMPLES; s++ ) { data->samples[ s ] = 0; } data->sample_size = 0; psynth_new_chunk( synth_id, 0, MAX_HARMONICS * sizeof( uint16 ), 0, pnet ); psynth_new_chunk( synth_id, 1, MAX_HARMONICS, 0, pnet ); psynth_new_chunk( synth_id, 2, MAX_HARMONICS, 0, pnet ); psynth_new_chunk( synth_id, 3, MAX_HARMONICS, 0, pnet ); data->freq = (uint16*)psynth_get_chunk( synth_id, 0, pnet ); data->freq_vol = (uchar*)psynth_get_chunk( synth_id, 1, pnet ); data->freq_band = (uchar*)psynth_get_chunk( synth_id, 2, pnet ); data->freq_type = (uchar*)psynth_get_chunk( synth_id, 3, pnet ); for( int h = 0; h < MAX_HARMONICS; h++ ) { data->freq[ h ] = 0; data->freq_vol[ h ] = 0; data->freq_band[ h ] = 0; data->freq_type[ h ] = 0; } data->freq[ 0 ] = data->ctl_freq; data->freq_vol[ 0 ] = data->ctl_freq_vol; data->freq_band[ 0 ] = data->ctl_freq_band; data->freq_type[ 0 ] = data->ctl_freq_type; data->note_offset = 0; data->search_ptr = 0; data->linear_tab = g_linear_tab; #ifdef SUNVOX_GUI { pnet->items[ synth_id ].visual = new_window( "Spectravoice GUI", 0, 0, 10, 10, g_wm->colors[ 5 ], 0, spectravoice_visual_handler, g_wm ); spectravoice_visual_data *sv_data = (spectravoice_visual_data*)pnet->items[ synth_id ].visual->data; sv_data->synth_data = data; sv_data->synth_id = synth_id; sv_data->pnet = pnet; } #endif retval = 1; break; case COMMAND_SETUP_FINISHED: //Render samples: recalc_samples( data, synth_id, pnet ); retval = 1; break; case COMMAND_RENDER_REPLACE: if( !outputs[ 0 ] ) break; if( data->ctl_mode == MODE_HQ_MONO || data->ctl_mode == MODE_LQ_MONO ) psynth_set_number_of_outputs( 1, synth_id, pnet ); else psynth_set_number_of_outputs( SYNTH_OUTPUTS, synth_id, pnet ); for( int c = 0; c < data->ctl_channels; c++ ) { if( data->channels[ c ].playing ) { int attack_len = ( pnet->sampling_freq * data->ctl_attack ) / 256; int release_len = ( pnet->sampling_freq * data->ctl_release ) / 256; attack_len /= 1024; int attack_delta = 1 << 30; if( attack_len != 0 ) attack_delta = ( 1 << 20 ) / attack_len; release_len /= 1024; int release_delta = 1 << 30; if( release_len != 0 ) release_delta = ( 1 << 20 ) / release_len; gen_channel *chan = &data->channels[ c ]; ulong delta_h = chan->delta_h; ulong delta_l = chan->delta_l; int sustain = chan->sustain; int ptr_h = 0; int ptr_l = 0; int playing = 0; int sustain_enabled = data->ctl_sustain; ulong env_vol = 0; int outputs_num = psynth_get_number_of_outputs( synth_id, pnet ); for( ch = 0; ch < outputs_num; ch++ ) { STYPE *in = inputs[ ch ]; STYPE *out = outputs[ ch ]; sustain = chan->sustain; ptr_h = chan->ptr_h; ptr_l = chan->ptr_l; env_vol = chan->env_vol; playing = chan->playing; int vol = ( data->ctl_volume * chan->vel ) >> 8; int ctl_pan = data->ctl_pan + ( chan->local_pan - 128 ); if( ctl_pan < 0 ) ctl_pan = 0; if( ctl_pan > 256 ) ctl_pan = 256; if( ctl_pan < 128 ) { if( ch == 1 ) { vol *= ctl_pan; vol >>= 7; } } else { if( ch == 0 ) { vol *= 128 - ( ctl_pan - 128 ); vol >>= 7; } } int add = ch * 32768 / 2; int16 *smp = 0; smp = data->samples[ 0 ]; if( smp == 0 ) break; int sample_size = data->sample_size; int sample_size_mask = data->sample_size - 1; STYPE_CALC res; int poff = 0; if( ch == 1 ) poff = data->sample_size / 2; int s; if( retval == 0 ) { if( data->ctl_attack == 0 && data->ctl_release == 0 ) { //No attack. No release. if( sustain_enabled == 0 ) sustain = 0; if( sustain == 0 ) { for( i = 0; i < sample_frames; i++ ) out[ i ] = 0; playing = 0; } else { if( data->ctl_mode == MODE_LQ_MONO || data->ctl_mode == MODE_LQ ) { //Low Quality (No interpolation): for( i = 0; i < sample_frames; i++ ) { s = smp[ (ptr_h+poff) & sample_size_mask ]; APPLY_VOLUME; INT16_TO_STYPE( res, s ); out[ i ] = (STYPE)res; SIGNED_ADD64( ptr_h, ptr_l, delta_h, delta_l ); } } #ifdef STYPE_FLOATINGPOINT if( data->ctl_mode == MODE_HQ_MONO || data->ctl_mode == MODE_HQ ) #else else #endif { //High Quality (Linear interpolation): for( i = 0; i < sample_frames; i++ ) { s = smp[ (ptr_h+poff) & sample_size_mask ] * (32767-(ptr_l>>1)); s += smp[ (ptr_h+poff+1) & sample_size_mask ] * (ptr_l>>1); s >>= 15; APPLY_VOLUME; INT16_TO_STYPE( res, s ); out[ i ] = (STYPE)res; SIGNED_ADD64( ptr_h, ptr_l, delta_h, delta_l ); } } #ifdef STYPE_FLOATINGPOINT if( data->ctl_mode == MODE_CUBIC ) { //High Quality (Cubic interpolation): for( i = 0; i < sample_frames; i++ ) { STYPE_CALC y0 = smp[ (ptr_h+poff-1) & sample_size_mask ]; STYPE_CALC y1 = smp[ (ptr_h+poff) & sample_size_mask ]; STYPE_CALC y2 = smp[ (ptr_h+poff+1) & sample_size_mask ]; STYPE_CALC y3 = smp[ (ptr_h+poff+2) & sample_size_mask ]; STYPE_CALC mu = (STYPE_CALC)ptr_l / (STYPE_CALC)0x10000; STYPE_CALC a = (3 * (y1-y2) - y0 + y3) / 2; STYPE_CALC b = 2 * y2 + y0 - (5*y1 + y3) / 2; STYPE_CALC c = ( y2 - y0 ) / 2; s = (int)( (((a * mu) + b) * mu + c) * mu + y1 ); APPLY_VOLUME; INT16_TO_STYPE( res, s ); out[ i ] = (STYPE)res; SIGNED_ADD64( ptr_h, ptr_l, delta_h, delta_l ); } } #endif } } else { //Attack and release enabled: if( data->ctl_mode == MODE_LQ_MONO || data->ctl_mode == MODE_LQ ) { //Low Quality (No interpolation): for( i = 0; i < sample_frames; i++ ) { s = smp[ (ptr_h+poff) & sample_size_mask ]; APPLY_VOLUME; APPLY_ENV_VOLUME; INT16_TO_STYPE( res, s ); out[ i ] = (STYPE)res; SIGNED_ADD64( ptr_h, ptr_l, delta_h, delta_l ); ENV_CONTROL_REPLACE; } } #ifdef STYPE_FLOATINGPOINT if( data->ctl_mode == MODE_HQ_MONO || data->ctl_mode == MODE_HQ ) #else else #endif { //High Quality (Linear interpolation): for( i = 0; i < sample_frames; i++ ) { s = smp[ (ptr_h+poff) & sample_size_mask ] * (32767-(ptr_l>>1)); s += smp[ (ptr_h+poff+1) & sample_size_mask ] * (ptr_l>>1); s >>= 15; APPLY_VOLUME; APPLY_ENV_VOLUME; INT16_TO_STYPE( res, s ); out[ i ] = (STYPE)res; SIGNED_ADD64( ptr_h, ptr_l, delta_h, delta_l ); ENV_CONTROL_REPLACE; } } #ifdef STYPE_FLOATINGPOINT if( data->ctl_mode == MODE_CUBIC ) { //High Quality (Cubic interpolation): for( i = 0; i < sample_frames; i++ ) { STYPE_CALC y0 = smp[ (ptr_h+poff-1) & sample_size_mask ]; STYPE_CALC y1 = smp[ (ptr_h+poff) & sample_size_mask ]; STYPE_CALC y2 = smp[ (ptr_h+poff+1) & sample_size_mask ]; STYPE_CALC y3 = smp[ (ptr_h+poff+2) & sample_size_mask ]; STYPE_CALC mu = (STYPE_CALC)ptr_l / (STYPE_CALC)0x10000; STYPE_CALC a = (3 * (y1-y2) - y0 + y3) / 2; STYPE_CALC b = 2 * y2 + y0 - (5*y1 + y3) / 2; STYPE_CALC c = ( y2 - y0 ) / 2; s = (int)( (((a * mu) + b) * mu + c) * mu + y1 ); APPLY_VOLUME; APPLY_ENV_VOLUME; INT16_TO_STYPE( res, s ); out[ i ] = (STYPE)res; SIGNED_ADD64( ptr_h, ptr_l, delta_h, delta_l ); ENV_CONTROL_REPLACE; } } #endif } } else { if( data->ctl_attack == 0 && data->ctl_release == 0 ) { //No attack. No release. if( sustain == 0 ) { playing = 0; } else { if( data->ctl_mode == MODE_LQ_MONO || data->ctl_mode == MODE_LQ ) { //Low Quality (No interpolation): for( i = 0; i < sample_frames; i++ ) { s = smp[ (ptr_h+poff) & sample_size_mask ]; APPLY_VOLUME; INT16_TO_STYPE( res, s ); out[ i ] += (STYPE)res; SIGNED_ADD64( ptr_h, ptr_l, delta_h, delta_l ); } } #ifdef STYPE_FLOATINGPOINT if( data->ctl_mode == MODE_HQ_MONO || data->ctl_mode == MODE_HQ ) #else else #endif { //High Quality (Linear Interpolation): for( i = 0; i < sample_frames; i++ ) { s = smp[ (ptr_h+poff) & sample_size_mask ] * (32767-(ptr_l>>1)); s += smp[ (ptr_h+poff+1) & sample_size_mask ] * (ptr_l>>1); s >>= 15; APPLY_VOLUME; INT16_TO_STYPE( res, s ); out[ i ] += (STYPE)res; SIGNED_ADD64( ptr_h, ptr_l, delta_h, delta_l ); } } #ifdef STYPE_FLOATINGPOINT if( data->ctl_mode == MODE_CUBIC ) { //High Quality (Cubic interpolation): for( i = 0; i < sample_frames; i++ ) { STYPE_CALC y0 = smp[ (ptr_h+poff-1) & sample_size_mask ]; STYPE_CALC y1 = smp[ (ptr_h+poff) & sample_size_mask ]; STYPE_CALC y2 = smp[ (ptr_h+poff+1) & sample_size_mask ]; STYPE_CALC y3 = smp[ (ptr_h+poff+2) & sample_size_mask ]; STYPE_CALC mu = (STYPE_CALC)ptr_l / (STYPE_CALC)0x10000; STYPE_CALC a = (3 * (y1-y2) - y0 + y3) / 2; STYPE_CALC b = 2 * y2 + y0 - (5*y1 + y3) / 2; STYPE_CALC c = ( y2 - y0 ) / 2; s = (int)( (((a * mu) + b) * mu + c) * mu + y1 ); APPLY_VOLUME; INT16_TO_STYPE( res, s ); out[ i ] += (STYPE)res; SIGNED_ADD64( ptr_h, ptr_l, delta_h, delta_l ); } } #endif } } else { //Attack and release enabled: if( data->ctl_mode == MODE_LQ_MONO || data->ctl_mode == MODE_LQ ) { //Low Quality (No interpolation): for( i = 0; i < sample_frames; i++ ) { s = smp[ (ptr_h+poff) & sample_size_mask ]; APPLY_VOLUME; APPLY_ENV_VOLUME; INT16_TO_STYPE( res, s ); out[ i ] += (STYPE)res; SIGNED_ADD64( ptr_h, ptr_l, delta_h, delta_l ); ENV_CONTROL; } } #ifdef STYPE_FLOATINGPOINT if( data->ctl_mode == MODE_HQ_MONO || data->ctl_mode == MODE_HQ ) #else else #endif { //High Quality (Linear interpolation): for( i = 0; i < sample_frames; i++ ) { s = smp[ (ptr_h+poff) & sample_size_mask ] * (32767-(ptr_l>>1)); s += smp[ (ptr_h+poff+1) & sample_size_mask ] * (ptr_l>>1); s >>= 15; APPLY_VOLUME; APPLY_ENV_VOLUME; INT16_TO_STYPE( res, s ); out[ i ] += (STYPE)res; SIGNED_ADD64( ptr_h, ptr_l, delta_h, delta_l ); ENV_CONTROL; } } #ifdef STYPE_FLOATINGPOINT if( data->ctl_mode == MODE_CUBIC ) { //High Quality (Cubic interpolation): for( i = 0; i < sample_frames; i++ ) { STYPE_CALC y0 = smp[ (ptr_h+poff-1) & sample_size_mask ]; STYPE_CALC y1 = smp[ (ptr_h+poff) & sample_size_mask ]; STYPE_CALC y2 = smp[ (ptr_h+poff+1) & sample_size_mask ]; STYPE_CALC y3 = smp[ (ptr_h+poff+2) & sample_size_mask ]; STYPE_CALC mu = (STYPE_CALC)ptr_l / (STYPE_CALC)0x10000; STYPE_CALC a = (3 * (y1-y2) - y0 + y3) / 2; STYPE_CALC b = 2 * y2 + y0 - (5*y1 + y3) / 2; STYPE_CALC c = ( y2 - y0 ) / 2; s = (int)( (((a * mu) + b) * mu + c) * mu + y1 ); APPLY_VOLUME; APPLY_ENV_VOLUME; INT16_TO_STYPE( res, s ); out[ i ] += (STYPE)res; SIGNED_ADD64( ptr_h, ptr_l, delta_h, delta_l ); ENV_CONTROL; } } #endif } } } chan->ptr_h = ptr_h; chan->ptr_l = ptr_l; chan->delta_h = delta_h; chan->delta_l = delta_l; chan->env_vol = env_vol; chan->sustain = sustain; chan->playing = playing; retval = 1; } } break; case COMMAND_NOTE_ON: { int c; for( c = 0; c < data->ctl_channels; c++ ) { if( data->channels[ data->search_ptr ].playing == 0 ) break; data->search_ptr++; if( data->search_ptr >= data->ctl_channels ) data->search_ptr = 0; } if( c == data->ctl_channels ) { //Channel not found: data->search_ptr++; if( data->search_ptr >= data->ctl_channels ) data->search_ptr = 0; } ulong delta_h, delta_l; int freq; GET_FREQ( freq, pnet->period_ptr / 4 ); GET_DELTA( freq, delta_h, delta_l ); c = data->search_ptr; data->channels[ c ].playing = 1; data->channels[ c ].vel = pnet->velocity; data->channels[ c ].delta_h = delta_h; data->channels[ c ].delta_l = delta_l; data->channels[ c ].ptr_h = ( data->note_offset & (data->sample_size-1) ); data->note_offset += 333; data->channels[ c ].ptr_l = 0; data->channels[ c ].id = pnet->channel_id; data->channels[ c ].env_vol = 0; data->channels[ c ].sustain = 1; data->channels[ c ].local_pan = 128; retval = c; } break; case COMMAND_SET_FREQ: if( pnet->synth_channel >= 0 && pnet->synth_channel < MAX_CHANNELS ) { int c = pnet->synth_channel; if( data->channels[ c ].id == pnet->channel_id ) { ulong delta_h, delta_l; int freq; GET_FREQ( freq, pnet->period_ptr / 4 ); GET_DELTA( freq, delta_h, delta_l ); data->channels[ c ].delta_h = delta_h; data->channels[ c ].delta_l = delta_l; } } retval = 1; break; case COMMAND_SET_VELOCITY: if( pnet->synth_channel >= 0 && pnet->synth_channel < MAX_CHANNELS ) { int c = pnet->synth_channel; if( data->channels[ c ].id == pnet->channel_id ) { data->channels[ c ].vel = pnet->velocity; } } retval = 1; break; case COMMAND_NOTE_OFF: if( pnet->synth_channel >= 0 && pnet->synth_channel < MAX_CHANNELS ) { int c = pnet->synth_channel; if( data->channels[ c ].id == pnet->channel_id ) { data->channels[ c ].sustain = 0; } } retval = 1; break; case COMMAND_ALL_NOTES_OFF: for( int c = 0; c < MAX_CHANNELS; c++ ) { data->channels[ c ].sustain = 0; } retval = 1; break; case COMMAND_CLEAN: for( int c = 0; c < MAX_CHANNELS; c++ ) { data->channels[ c ].playing = 0; } retval = 1; break; case COMMAND_SET_GLOBAL_CONTROLLER: if( pnet->ctl_num == 8 ) { //Harmonic number: data->freq = (uint16*)psynth_get_chunk( synth_id, 0, pnet ); data->freq_vol = (uchar*)psynth_get_chunk( synth_id, 1, pnet ); data->freq_band = (uchar*)psynth_get_chunk( synth_id, 2, pnet ); data->freq_type = (uchar*)psynth_get_chunk( synth_id, 3, pnet ); data->ctl_harm = pnet->ctl_val; data->ctl_freq = data->freq[ data->ctl_harm ]; data->ctl_freq_vol = data->freq_vol[ data->ctl_harm ]; data->ctl_freq_band = data->freq_band[ data->ctl_harm ]; data->ctl_freq_type = data->freq_type[ data->ctl_harm ]; pnet->draw_request = 1; retval = 1; } if( pnet->ctl_num == 9 ) { //Harmonic frequency: data->freq = (uint16*)psynth_get_chunk( synth_id, 0, pnet ); data->freq[ data->ctl_harm ] = pnet->ctl_val; } if( pnet->ctl_num == 10 ) { //Harmonic volume: data->freq_vol = (uchar*)psynth_get_chunk( synth_id, 1, pnet ); data->freq_vol[ data->ctl_harm ] = pnet->ctl_val; } if( pnet->ctl_num == 11 ) { //Harmonic bandwidth: data->freq_band = (uchar*)psynth_get_chunk( synth_id, 2, pnet ); data->freq_band[ data->ctl_harm ] = pnet->ctl_val; } if( pnet->ctl_num == 12 ) { //Harmonic bandwidth type: data->freq_type = (uchar*)psynth_get_chunk( synth_id, 3, pnet ); data->freq_type[ data->ctl_harm ] = pnet->ctl_val; } break; case COMMAND_SET_LOCAL_CONTROLLER: if( pnet->ctl_num == 1 ) { if( pnet->synth_channel >= 0 && pnet->synth_channel < MAX_CHANNELS ) { int c = pnet->synth_channel; if( data->channels[ c ].id == pnet->channel_id ) { //Set "PAN" local controller of this channel: data->channels[ c ].local_pan = pnet->ctl_val >> 7; } } retval = 1; } break; case COMMAND_CLOSE: mem_off(); for( int s = 0; s < MAX_SAMPLES; s++ ) { if( data->samples[ s ] ) mem_free( data->samples[ s ] ); data->samples[ s ] = 0; } mem_on(); #ifdef SUNVOX_GUI remove_window( pnet->items[ synth_id ].visual, g_wm ); #endif retval = 1; break; } return retval; }
30.741722
140
0.559457
Sound-Linux-More
c938512f8112dbdf24166605b8e3ea9feca2a137
1,014
cpp
C++
tools/loader/syslinux/systhread.cpp
ikysil/ikforth
165e049fc007003cd05f59332dc856d553d8aac8
[ "Unlicense" ]
8
2017-08-03T08:49:06.000Z
2021-12-17T12:02:19.000Z
tools/loader/syslinux/systhread.cpp
clstrfsck/ikforth
165e049fc007003cd05f59332dc856d553d8aac8
[ "Unlicense" ]
58
2016-04-21T20:03:54.000Z
2022-01-16T00:40:50.000Z
tools/loader/syslinux/systhread.cpp
clstrfsck/ikforth
165e049fc007003cd05f59332dc856d553d8aac8
[ "Unlicense" ]
1
2018-07-25T21:07:00.000Z
2018-07-25T21:07:00.000Z
#include <stdlib.h> #include <stdio.h> #include <pthread.h> #include <string.h> #include "../IKFCommon.hpp" #include "../IKFunc.hpp" void * fThreadFunc(void * lpParameter) { ForthThreadParams * ftp = (ForthThreadParams *) lpParameter; IHeader.LinuxThreadProcAddr(ftp->UserDataAreaAddr, ftp->ExecutionToken); fFree(ftp->UserDataAreaAddr); fFree(ftp); return 0; } DWORD __stdcall fStartThread(void * ParentUserDataAreaAddr, DWORD CreateSuspended, DWORD XT) { //~ DWORD flags = 0; //~ if (CreateSuspended == fTRUE) { //~ flags |= CREATE_SUSPENDED; //~ } ForthThreadParams * ftp = (ForthThreadParams *) fAlloc(sizeof(ForthThreadParams)); ftp->ExecutionToken = XT; ftp->UserDataAreaAddr = fAlloc(IHeader.UserDataAreaSize); if (ParentUserDataAreaAddr != NULL) { memmove(ftp->UserDataAreaAddr, ParentUserDataAreaAddr, IHeader.UserDataAreaSize); } pthread_t threadId; pthread_create(&threadId, NULL, &fThreadFunc, ftp); return threadId; }
32.709677
95
0.696252
ikysil
c9394b7a7b93959e7d485c5a3b780841039f54e6
2,571
cpp
C++
Punto3/caos.cpp
santiagohenao/SantiagoHenao_Taller5
cdabc8d764b2890a54cdb45199b990c33a3a603f
[ "MIT" ]
null
null
null
Punto3/caos.cpp
santiagohenao/SantiagoHenao_Taller5
cdabc8d764b2890a54cdb45199b990c33a3a603f
[ "MIT" ]
null
null
null
Punto3/caos.cpp
santiagohenao/SantiagoHenao_Taller5
cdabc8d764b2890a54cdb45199b990c33a3a603f
[ "MIT" ]
null
null
null
#include <SFML/Graphics.hpp> #include <SFML/Keyboard.hpp> #include <iostream> #include <vector> #include <cmath> #include <fstream> #include <math.h> using namespace std; //constante de resolución temporal double step=6*10e-4; // constante de las ecuaciones, tiempo máximo #define epsilon 0.8 #define t_max 3000 // condiciones iniciales double q1=sqrt(2.)/4.; double q2=-sqrt(2.)/4.; double p1=0.; double p2=0.; double q1f; double q2f; double p1f; double p2f; // Método de Runge-Kutta de cuarto orden para una función general f double k1(double (*f)(double,double,double), double h, double tn, double y1, double y2) { return h*f(tn,y1,y2); } double k2(double (*f)(double,double,double), double h, double tn, double y1, double y2) { return h*f(tn+h/2, y1+k1(f,h,tn,y1,y2)/2 , y2+k1(f,h,tn,y1,y2)/2); } double k3(double (*f)(double,double,double), double h, double tn, double y1, double y2) { return h*f(tn+h/2, y1+k2(f,h,tn,y1,y2)/2 , y2+k2(f,h,tn,y1,y2)/2); } double k4(double (*f)(double,double,double), double h, double tn, double y1, double y2) { return h*f(tn+h, y1+k3(f,h,tn,y1,y2) , y2+k3(f,h,tn,y1,y2) ); } // Definición de las ecuaciones físicas del sistema double p1_dot(double tn, double y1, double y2) { return (-2*y1)/pow(pow(epsilon,2) + 4*pow(y1,2),1.5); } double p2_dot(double tn, double y1, double y2) { return (y1 - y2)/pow(pow(epsilon,2)/4. + pow(y1 - y2,2),1.5) - (y1 + y2)/pow(pow(epsilon,2)/4. + pow(y1 + y2,2),1.5); } double q1_dot(double tn, double y1, double y2) { return y1; } double q2_dot(double tn, double y1, double y2) { return y2; } int main() { // Runge-Kutta ofstream result("result.dat"); int mu=0; for(double t=0.;t<t_max;t+=step) { //cout << t << "\t" << p1 << endl; q1f=q1+(k1(q1_dot,step,t,p1,p2)+2*k2(q1_dot,step,t,p1,p2)+2*k3(q1_dot,step,t,p1,p2)+k4(q1_dot,step,t,p1,p2))/6.; q2f=q2+(k1(q2_dot,step,t,p1,p2)+2*k2(q2_dot,step,t,p1,p2)+2*k3(q2_dot,step,t,p1,p2)+k4(q2_dot,step,t,p1,p2))/6.; p1f=p1+(k1(p1_dot,step,t,q1,q2)+2*k2(p1_dot,step,t,q1,q2)+2*k3(p1_dot,step,t,q1,q2)+k4(p1_dot,step,t,q1,q2))/6.; p2f=p2+(k1(p2_dot,step,t,q1,q2)+2*k2(p2_dot,step,t,q1,q2)+2*k3(p2_dot,step,t,q1,q2)+k4(p2_dot,step,t,q1,q2))/6.; // actualizar valores q1=q1f;q2=q2f;p1=p1f;p2=p2f; if(mu==10) // Exportar uno de cada diez datos. { result << t << "\t" << q1 << "\t" << q2 << "\t" << p1 << "\t" << p2 << endl; mu=0; } mu++; } return 0; }
23.372727
122
0.606379
santiagohenao
c9396cd159b09ff1cf5c6ba2bdd7d340394606c0
2,520
cpp
C++
src/ui/login/LoginPanel.cpp
igorglotov/tizen-vk-client
de213ede7185818285f78abad36592bc864f76cc
[ "Unlicense" ]
null
null
null
src/ui/login/LoginPanel.cpp
igorglotov/tizen-vk-client
de213ede7185818285f78abad36592bc864f76cc
[ "Unlicense" ]
null
null
null
src/ui/login/LoginPanel.cpp
igorglotov/tizen-vk-client
de213ede7185818285f78abad36592bc864f76cc
[ "Unlicense" ]
null
null
null
/* * LoginPanel.cpp * * Created on: Nov 14, 2013 * Author: igorglotov */ #include "LoginPanel.h" #include "AppResourceId.h" #include "VKUAuthConfig.h" #include "SceneRegister.h" #include "ObjectCounter.h" static const int ACTION_LOGIN = 101; static const int ACTION_SIGNUP = 102; using namespace Tizen::Ui; using namespace Tizen::Base; using namespace Tizen::App; using namespace Tizen::Ui::Controls; using namespace Tizen::Ui::Scenes; LoginPanel::LoginPanel() { CONSTRUCT(L"LoginPanel"); } LoginPanel::~LoginPanel() { DESTRUCT(L"LoginPanel"); delete pPopup; } bool LoginPanel::Initialize() { result r = Panel::Construct(IDC_PANEL_LOGIN); return r == E_SUCCESS ? true : false; } result LoginPanel::OnInitializing(void) { result r = E_SUCCESS; pPopup = new (std::nothrow) VKULoginPopup(); pPopup->Construct(); pPopup->SetShowState(false); Button* pLoginBtn = static_cast<Button*>(GetControl(IDC_BUTTON_LOGIN)); if (pLoginBtn) { pLoginBtn->SetActionId(ACTION_LOGIN); pLoginBtn->AddActionEventListener(*this); } // IDC_BUTTON_REGISTER Button* pSignupBtn = static_cast<Button*>(GetControl(IDC_BUTTON_REGISTER)); if (pSignupBtn) { pSignupBtn->SetActionId(ACTION_SIGNUP); pSignupBtn->AddActionEventListener(*this); } return r; } void LoginPanel::OnActionPerformed(const Control& source, int actionId) { switch(actionId) { case ACTION_LOGIN: AppLog("Logging in in"); pPopup->StartLogin(this); // FIXME: free memory break; case ACTION_SIGNUP: pPopup->StartSignup(this); break; } } result LoginPanel::OnTerminating(void) { result r = E_SUCCESS; return r; } void LoginPanel::OnLoginSuccess(const String &accessToken, const String &expiresIn, const String &userId) { AppLog("login success: authToken %ls, expiresIn %ls, userId %ls", accessToken.GetPointer(), expiresIn.GetPointer(), userId.GetPointer()); VKUAuthConfig::Replace(accessToken, expiresIn, userId); SceneManager* pSceneManager = SceneManager::GetInstance(); pSceneManager->GoForward(ForwardSceneTransition(SCENE_MAIN_DIALOGS)); } void LoginPanel::OnLoginError(const String &error, const String &description) { AppLog("login error: %ls:%ls", error.GetPointer(), description.GetPointer()); } void LoginPanel::OnSignupSuccess(const String &accessToken, const String &expiresIn, const String &userId) { pPopup->SetShowState(false); } void LoginPanel::OnSignupError(const String &error, const String &description) { AppLog("signup error: %ls:%ls", error.GetPointer(), description.GetPointer()); }
25.714286
138
0.745238
igorglotov
c93ba268b597112217aa21d95fcea26edd159e54
1,820
cpp
C++
gko-tracker-src/minihttpd/src/monitor_helper.cpp
JohnnyFang0515/gingko
33f289b36d6d8176fa7be67275dda93d40efbfd7
[ "BSD-2-Clause" ]
11
2018-01-31T12:31:56.000Z
2022-01-06T04:45:03.000Z
gko-tracker-src/minihttpd/src/monitor_helper.cpp
jaewon713/gingko
33f289b36d6d8176fa7be67275dda93d40efbfd7
[ "BSD-2-Clause" ]
null
null
null
gko-tracker-src/minihttpd/src/monitor_helper.cpp
jaewon713/gingko
33f289b36d6d8176fa7be67275dda93d40efbfd7
[ "BSD-2-Clause" ]
9
2017-10-31T06:51:24.000Z
2020-02-10T09:21:00.000Z
#include <stdio.h> #include "minihttpd/monitor_helper.h" namespace argus { namespace common { void DataContainer::setKeyVal(string key, string val) { SpinLockGuard lock(lock_); strMap_[key] = val; } void DataContainer::setKeyVal(string key, int64_t val) { SpinLockGuard lock(lock_); intMap_[key] = val; } void DataContainer::increment(string key, int64_t val) { std::map<string, int64_t>::iterator it; SpinLockGuard lock(lock_); it = intMap_.find(key); if (it == intMap_.end()) { intMap_[key] = val; } else { intMap_[key] += val; } } void DataContainer::setKeyVal(string key, double val) { SpinLockGuard lock(lock_); floatMap_[key] = val; } void DataContainer::formatToString(string *output) { std::map<string, string> strMap; std::map<string, int64_t> intMap; std::map<string, double> floatMap; { SpinLockGuard lock(lock_); strMap = strMap_; intMap = intMap_; floatMap = floatMap_; } output->clear(); std::map<string, string>::iterator strIt; for (strIt = strMap.begin(); strIt != strMap.end(); ++strIt) { output->append(strIt->first); output->append(":"); output->append(strIt->second); output->append("\n"); } std::map<string, int64_t>::iterator intIt; for (intIt = intMap.begin(); intIt != intMap.end(); ++intIt) { char buf[64]; snprintf(buf, sizeof buf, "%ld\n", intIt->second); output->append(intIt->first); output->append(":"); output->append(buf); } std::map<string, double>::iterator floatIt; for (floatIt = floatMap.begin(); floatIt != floatMap.end(); ++floatIt) { char buf[64]; snprintf(buf, sizeof buf, "%f\n", floatIt->second); output->append(floatIt->first); output->append(":"); output->append(buf); } } } // namespace common } // namespace argus
21.411765
74
0.642308
JohnnyFang0515
c93bff340887d5b33200e55eb13b348b08c32033
17,252
cpp
C++
Engine/Source/GraphicsEngine/src/BaseControl.cpp
AnkurSheel/RoutePlanner
a50b6ccb735db42ff4e5b2f4c87e710819c4564b
[ "CC-BY-4.0" ]
null
null
null
Engine/Source/GraphicsEngine/src/BaseControl.cpp
AnkurSheel/RoutePlanner
a50b6ccb735db42ff4e5b2f4c87e710819c4564b
[ "CC-BY-4.0" ]
null
null
null
Engine/Source/GraphicsEngine/src/BaseControl.cpp
AnkurSheel/RoutePlanner
a50b6ccb735db42ff4e5b2f4c87e710819c4564b
[ "CC-BY-4.0" ]
null
null
null
// ******************************************************************************************************************* // BaseControl version: 1.0 Ankur Sheel date: 2011/07/21 // ******************************************************************************************************************* // purpose: // ******************************************************************************************************************* #include "stdafx.h" #include "BaseControl.h" #include "Sprite.hxx" #include "Structures.h" #include "GraphicUtils.h" #include "XMLNode.hxx" #include "Vector2.h" using namespace Graphics; using namespace Utilities; using namespace Base; using namespace std; // ******************************************************************************************************************* cBaseControl::cBaseControl() : m_bVisible(true) , m_pBGSprite(NULL) , m_pParentControl(NULL) , m_vPosition(cVector2(-1.0f, -1.0f)) , m_bFocus(false) , m_pFocusControl(NULL) , m_bIsLeftMouseDown(false) , m_bAllowMovingControls(false) , m_ConstrainInParent(true) { } // ******************************************************************************************************************* cBaseControl::cBaseControl(const cBaseControl & other) : m_bVisible(other.m_bVisible) , m_bFocus(false) , m_bAllowMovingControls(other.m_bAllowMovingControls) , m_bIsLeftMouseDown(false) , m_pFocusControl(other.m_pFocusControl) , m_pParentControl(other.m_pParentControl) , m_iMouseDownXPos(other.m_iMouseDownXPos) , m_iMouseDownYPos(other.m_iMouseDownYPos) , m_strControlName(other.m_strControlName) , m_ConstrainInParent(other.m_ConstrainInParent) , m_pBGSprite(NULL) { if(other.m_pBGSprite != NULL) { m_pBGSprite = ISprite::CreateSprite(); m_pBGSprite->VInitialize(other.m_pBGSprite->VGetTexture()); } VSetPosition(other.m_vPosition); VSetSize(other.m_vSize); for(auto iter = other.m_pChildControl.begin(); iter != other.m_pChildControl.end(); iter++) { shared_ptr<IBaseControl> pTest = (*iter); shared_ptr<IBaseControl> pControl = pTest->VDuplicate(); VAddChildControl(pControl); } } // ******************************************************************************************************************* cBaseControl::~cBaseControl() { VCleanup(); } // ******************************************************************************************************************* void cBaseControl::VInitialize(const shared_ptr<IXMLNode const> pXMLNode) { if(pXMLNode == NULL) { return; } VSetControlName(pXMLNode->VGetChildValue("Name")); cString bgImageFileName = pXMLNode->VGetChildValue("BackGroundImage"); if(!bgImageFileName.IsEmpty()) { m_pBGSprite = ISprite::CreateSprite(); m_pBGSprite->VInitialize(bgImageFileName); } m_ConstrainInParent = pXMLNode->VGetChildValueAsBool("ConstrainInParent", true); cVector2 size = pXMLNode->VGetChildValueAsVector2("ScaleInPixels", cVector2(8.0f, 8.0f)); VSetSize(size); cVector2 position = pXMLNode->VGetChildValueAsVector2("Position", cVector2::Zero); VSetPosition(position); bool visible = pXMLNode->VGetChildValueAsBool("Visible", true); VSetVisible(visible); } // ******************************************************************************************************************* void cBaseControl::Initialize(const cBaseControlDef & def) { VSetControlName(def.strControlName); VSetPosition(def.vPosition); VSetSize(def.vSize); } // ******************************************************************************************************************* bool cBaseControl::VPostMsg( const AppMsg & msg ) { if(!m_bVisible) { return false; } switch(msg.m_uMsg) { case WM_LBUTTONDOWN: if(IsCursorIntersect(LOWORD(msg.m_lParam), HIWORD(msg.m_lParam))) { if(!PostToAll(msg)) { VOnLeftMouseButtonDown(LOWORD(msg.m_lParam), HIWORD(msg.m_lParam)); if (AllowMovingControl() && m_pParentControl) { m_pParentControl->VMoveToFront(this); } SetFocusControl(this); } return true; } break; case WM_LBUTTONUP: if(!PostToAll(msg)) { if (m_pFocusControl) { return m_pFocusControl->VOnLeftMouseButtonUp(LOWORD(msg.m_lParam), HIWORD(msg.m_lParam)); } } break; case WM_MOUSEMOVE: if(!PostToAll(msg)) { if (m_pFocusControl) { return m_pFocusControl->VOnMouseMove(LOWORD(msg.m_lParam), HIWORD(msg.m_lParam)); } } break; case WM_KEYUP: if(!PostToAll(msg)) { if(m_pFocusControl) { return m_pFocusControl->VOnKeyUp(msg.m_wParam); } } break; case WM_KEYDOWN: if(!PostToAll(msg)) { if(m_pFocusControl) { return m_pFocusControl->VOnKeyDown(msg.m_wParam); } } break; case WM_CHAR: if(!PostToAll(msg)) { if(m_pFocusControl) { return m_pFocusControl->VOnCharPress(msg.m_wParam); } } break; } return false; } // ******************************************************************************************************************* void cBaseControl::VAddChildControl(shared_ptr<IBaseControl> pChildControl) { shared_ptr<cBaseControl> pControl = static_pointer_cast<cBaseControl>(pChildControl); if (pControl) { pControl->SetParentControl(this); pControl->VSetAbsolutePosition(); m_pChildControl.push_back(pControl); } } // ******************************************************************************************************************* void cBaseControl::VRemoveAllChildren() { if (m_bFocus) { m_pFocusControl = this; } for(auto iter = m_pChildControl.begin(); iter != m_pChildControl.end(); ++iter) { (*iter)->VUnRegisterAllCallBacks(); } m_pChildControl.clear(); } // ******************************************************************************************************************* void cBaseControl::VRemoveChildControl(const cString & strControlName) { ControlList::iterator iter; unsigned long checksum = cHashedString::CalculateChecksum(cStringUtilities::GetInLowerCase(strControlName)); for(iter = m_pChildControl.begin(); iter != m_pChildControl.end(); ++iter) { if((*iter).get()->m_strControlName.GetHash() == checksum) { break; } } SP_ASSERT(iter != m_pChildControl.end())(strControlName).SetCustomMessage("Could not find Child control in Base Control"); if(iter != m_pChildControl.end()) { if ((*iter).get()->m_bFocus) { m_pFocusControl = this; } m_pChildControl.erase(iter); } } // ******************************************************************************************************************* const shared_ptr<Graphics::IBaseControl> cBaseControl::VFindChildControl(const cString & strControlName) { ControlList::const_iterator iter; unsigned long checksum = cHashedString::CalculateChecksum(cStringUtilities::GetInLowerCase(strControlName)); for(iter = m_pChildControl.begin(); iter != m_pChildControl.end(); ++iter) { if((*iter).get()->m_strControlName.GetHash() == checksum) { break; } } SP_ASSERT(iter != m_pChildControl.end())(strControlName).SetCustomMessage("Could not find Child control in Base Control"); if(iter == m_pChildControl.end()) { return NULL; } else { return (*iter); } } // ******************************************************************************************************************* void cBaseControl::VSetPosition( const cVector2 & vPosition ) { if(m_vPosition != vPosition) { m_vPosition = vPosition; VSetAbsolutePosition(); } } // ******************************************************************************************************************* const cVector2 cBaseControl::VGetSize() const { return m_vSize; } // ******************************************************************************************************************* void cBaseControl::VSetSize( const cVector2 & vSize) { if (m_vSize != vSize) { m_vSize = vSize; if(m_pBGSprite) { m_pBGSprite->VSetSize(m_vSize); } } } // ******************************************************************************************************************* void cBaseControl::VRegisterCallBack(const UIEVENTTYPE::ENUM eventType, UIEventCallBackFn fnCallback) { m_CallbackMap.insert(std::make_pair(eventType, fnCallback)); } // ******************************************************************************************************************* void cBaseControl::VUnregisterCallBack(const UIEVENTTYPE::ENUM eventType) { m_CallbackMap.erase(eventType); } // ******************************************************************************************************************* void cBaseControl::VUnRegisterAllCallBacks() { m_CallbackMap.clear(); } // ******************************************************************************************************************* void cBaseControl::VMoveToFront(const IBaseControl * const pControl ) { auto iter = GetChildControlIterator(pControl); if(iter != m_pChildControl.end() && iter != m_pChildControl.begin()) { m_pChildControl.splice(m_pChildControl.begin(), m_pChildControl, iter); } } // ******************************************************************************************************************* void cBaseControl::VSetText(const Base::cString & strText) { SP_ASSERT(false).SetCustomMessage("This function should be implemented in a child class."); } // ******************************************************************************************************************* bool cBaseControl::VOnLeftMouseButtonUp( const int X, const int Y ) { if(AllowMovingControl() && m_bIsLeftMouseDown) { SP_LOG(2, cStringUtilities::MakeFormatted("New Position - X : %f , Y : %f", m_vPosition.x, m_vPosition.y )); } m_bIsLeftMouseDown = false; return true; } // ******************************************************************************************************************* bool cBaseControl::VOnLeftMouseButtonDown( const int X, const int Y ) { m_iMouseDownXPos = X - static_cast<int>(m_vControlAbsolutePosition.x); m_iMouseDownYPos = Y - static_cast<int>(m_vControlAbsolutePosition.y); m_bIsLeftMouseDown = true; return true; } // ******************************************************************************************************************* void cBaseControl::VRender(const ICamera * const pCamera) { if (!m_bVisible) { return; } if(m_pBGSprite) { m_pBGSprite->VRender(pCamera); } for(auto iter = m_pChildControl.rbegin(); iter != m_pChildControl.rend(); iter++) { (*iter)->VRender(pCamera); } } // ******************************************************************************************************************* bool cBaseControl::VOnKeyDown(const unsigned int iCharID) { if (UIEventCallBackFn * pFn = GetCallbackFromMap(UIEVENTTYPE::KEYDOWN)) { stUIEventCallbackParam param; param.uiCharId = iCharID; (*pFn)(param); } return false; } // ******************************************************************************************************************* bool cBaseControl::VOnKeyUp(const unsigned int iCharID) { return false; } // ******************************************************************************************************************* bool cBaseControl::VOnCharPress(const unsigned int iCharID) { return false; } // ******************************************************************************************************************* bool cBaseControl::VOnMouseMove( const int X, const int Y ) { if (AllowMovingControl() && m_bIsLeftMouseDown) { float x = m_vPosition.x + (X - (int)m_vControlAbsolutePosition.x) - m_iMouseDownXPos; float y = m_vPosition.y + (Y - (int)m_vControlAbsolutePosition.y) - m_iMouseDownYPos; if(m_ConstrainInParent) { ConstrainChildControl(x, y); } VSetPosition(cVector2(x, y)); return true; } return false; } // ******************************************************************************************************************* void cBaseControl::VSetAbsolutePosition() { if(m_ConstrainInParent) { ConstrainChildControl(m_vPosition.x, m_vPosition.y); } m_vControlAbsolutePosition = m_vPosition; if (m_pParentControl) { m_vControlAbsolutePosition += m_pParentControl->m_vControlAbsolutePosition; } if (m_pBGSprite) { m_pBGSprite->VSetPosition(m_vControlAbsolutePosition); } for(auto iter = m_pChildControl.begin(); iter != m_pChildControl.end(); iter++) { (*iter)->VSetAbsolutePosition(); } } // ******************************************************************************************************************* void cBaseControl::VOnFocusChanged() { } // ******************************************************************************************************************* void cBaseControl::VSetVisible( bool bIsVisible ) { m_bVisible = bIsVisible; } // ******************************************************************************************************************* void cBaseControl::VCleanup() { m_CallbackMap.clear(); VRemoveAllChildren(); SafeDelete(&m_pBGSprite); } // ******************************************************************************************************************* float cBaseControl::VGetHeight() const { return m_vSize.y; } // ******************************************************************************************************************* float cBaseControl::VGetWidth() const { return m_vSize.x; } // ******************************************************************************************************************* cString cBaseControl::VGetControlName() const { return m_strControlName.GetString(); } // ******************************************************************************************************************* void cBaseControl::VSetControlName(const cString & inControlName) { m_strControlName = cHashedString(cStringUtilities::GetInLowerCase(inControlName)); } // ******************************************************************************************************************* bool cBaseControl::IsCursorIntersect( const float fX, const float fY ) { if((fX >= m_vControlAbsolutePosition.x) && (fX <= m_vControlAbsolutePosition.x + VGetWidth()) && (fY >= m_vControlAbsolutePosition.y) && (fY <= m_vControlAbsolutePosition.y + VGetHeight())) { return true; } return false; } // ******************************************************************************************************************* bool cBaseControl::PostToAll( const AppMsg & msg ) { for(auto iter = m_pChildControl.begin(); iter != m_pChildControl.end(); iter++) { if((*iter)->VPostMsg(msg)) { return true; } } return false; } // ******************************************************************************************************************* void cBaseControl::SetFocusControl( const cBaseControl * const pControl ) { if (!m_bFocus || m_pFocusControl != pControl) { if (m_pParentControl) { m_pParentControl->SetFocusControl(pControl); } else { if(m_pFocusControl) { m_pFocusControl->SetFocus(false); } m_pFocusControl = const_cast<cBaseControl *>(pControl); } SetFocus(true); } } // ******************************************************************************************************************* void cBaseControl::SetFocus(const bool bFocus) { m_bFocus = bFocus; VOnFocusChanged(); } // ******************************************************************************************************************* void cBaseControl::ConstrainChildControl(float & fX, float & fY) { // constrain child control in parent control if (m_pParentControl) { if (fX < 0) { fX = 0; } if ((fX + m_vSize.x) > m_pParentControl->VGetWidth()) { fX = m_pParentControl->VGetWidth() - m_vSize.x; } if (fY < 0) { fY = 0; } if ((fY + m_vSize.y) > m_pParentControl->VGetHeight()) { fY = m_pParentControl->VGetHeight() - m_vSize.y; } } } // ******************************************************************************************************************* void cBaseControl::SetParentControl( cBaseControl * pParentControl ) { m_pParentControl = pParentControl; } // ******************************************************************************************************************* bool cBaseControl::AllowMovingControl() { if (m_pParentControl) { return m_pParentControl->AllowMovingControl(); } return m_bAllowMovingControls; } // ******************************************************************************************************************* cBaseControl::ControlList::const_iterator cBaseControl::GetChildControlIterator(const IBaseControl * const pChildControl) { ControlList::const_iterator iter; for(iter = m_pChildControl.begin(); iter != m_pChildControl.end(); ++iter) { if((*iter).get() == pChildControl) { break; } } if(iter == m_pChildControl.end()) { SP_LOG_CUSTOM(AssertLevels::LEVEL_ERROR, 2, "Could not find Child control in Base Control"); } return iter; } // ******************************************************************************************************************* UIEventCallBackFn * cBaseControl::GetCallbackFromMap(const UIEVENTTYPE::ENUM eventType) { auto iter = m_CallbackMap.find(eventType); if(iter != m_CallbackMap.end()) { return &(iter->second); } return NULL; }
29.092749
123
0.497681
AnkurSheel
c93c3106b0bc662877789a2b3973f11cf1d15861
2,671
cc
C++
source/detector/KBTpc.cc
KUNPL/KEBII
7feba36bb2ac2812c0dec21f5e3f3a0dcc1c8e39
[ "MIT" ]
null
null
null
source/detector/KBTpc.cc
KUNPL/KEBII
7feba36bb2ac2812c0dec21f5e3f3a0dcc1c8e39
[ "MIT" ]
null
null
null
source/detector/KBTpc.cc
KUNPL/KEBII
7feba36bb2ac2812c0dec21f5e3f3a0dcc1c8e39
[ "MIT" ]
null
null
null
#include "KBTpc.hh" #include <iostream> using namespace std; ClassImp(KBTpc) KBTpc::KBTpc(const char *name, const char *title) :KBDetector(name, title) { } bool KBTpc::Init() { TString axis = fPar -> GetParString("tpcEFieldAxis"); axis.ToLower(); if (axis == "x") fEFieldAxis = 0; if (axis == "y") fEFieldAxis = 1; if (axis == "z") fEFieldAxis = 2; fNPlanes = fPar -> GetParInt("tpcNPadPlanes"); fCathodeK = fPar -> GetParDouble("tpcCathodePlaneK"); for (Int_t iPlane = 0; iPlane < fNPlanes; iPlane++) fPlaneK[iPlane] = fPar -> GetParDouble(Form("tpcPadPlaneK%d",iPlane)); if (BuildGeometry() == false) return false; if (BuildDetectorPlane() == false) return false; return true; } KBPadPlane *KBTpc::GetPadPlane(Int_t idx) { return (KBPadPlane *) GetDetectorPlane(idx); } Int_t KBTpc::GetEFieldAxis() { return fEFieldAxis; } void KBTpc::GetDriftPlane(Double_t k, Int_t &planeID, Double_t &kPlane) { if (fNPlanes == 1) { planeID = 0; kPlane = fPlaneK[0]; } else if (fNPlanes == 2) { if (fPlaneK[0] > fPlaneK[1]) { if (k > fCathodeK && k < fPlaneK[0]) { planeID = 0; kPlane = fPlaneK[0]; } else if (k < fCathodeK && k > fPlaneK[1]) { planeID = 1; kPlane = fPlaneK[1]; } else { planeID = -1; } } else { if (k > fCathodeK && k < fPlaneK[1]) { planeID = 1; kPlane = fPlaneK[1]; } else if (k < fCathodeK && k > fPlaneK[0]) { planeID = 0; kPlane = fPlaneK[0]; } else { planeID = -1; } } } } TVector3 KBTpc::XYZToIJK(TVector3 xyz) { TVector3 ijk; if (fEFieldAxis == 0) ijk.SetXYZ(xyz.Y(), xyz.Z(), xyz.X()); else if (fEFieldAxis == 1) ijk.SetXYZ(xyz.Z(), xyz.X(), xyz.Y()); else if (fEFieldAxis == 2) ijk.SetXYZ(xyz.X(), xyz.Y(), xyz.Z()); return ijk; } TVector3 KBTpc::IJKToXYZ(TVector3 ijk) { TVector3 xyz; if (fEFieldAxis == 0) xyz.SetXYZ(ijk.Z(), ijk.X(), ijk.Y()); else if (fEFieldAxis == 1) xyz.SetXYZ(ijk.Y(), ijk.Z(), ijk.X()); else if (fEFieldAxis == 2) xyz.SetXYZ(ijk.X(), ijk.Y(), ijk.Z()); return xyz; } void KBTpc::XYZToIJK(Double_t x, Double_t y, Double_t z, Double_t &i, Double_t &j, Double_t &k) { if (fEFieldAxis == 0) { i = y; j = z; k = x; } else if (fEFieldAxis == 1) { i = z; j = x; k = y; } else if (fEFieldAxis == 2) { i = x; j = y; k = z; } } void KBTpc::IJKToXYZ(Double_t i, Double_t j, Double_t k, Double_t &x, Double_t &y, Double_t &z) { if (fEFieldAxis == 0) { x = k; y = i; z = j; } else if (fEFieldAxis == 1) { x = j; y = k; z = i; } else if (fEFieldAxis == 2) { x = i; y = j; z = k; } }
25.438095
95
0.570198
KUNPL
c946d97bb2dd61bf3db869dfcd93492eed1d9923
1,696
cpp
C++
TiroCertoServidor/ClientSockTest.cpp
enzoam/game-lab-c-multiplayer-TiroCerto
5ea9d1b0a2264077a43887af7a0f38a99310e40f
[ "MIT" ]
1
2021-05-15T06:53:50.000Z
2021-05-15T06:53:50.000Z
TiroCertoServidor/ClientSockTest.cpp
enzoam/game-lab-c-multiplayer-TiroCerto
5ea9d1b0a2264077a43887af7a0f38a99310e40f
[ "MIT" ]
null
null
null
TiroCertoServidor/ClientSockTest.cpp
enzoam/game-lab-c-multiplayer-TiroCerto
5ea9d1b0a2264077a43887af7a0f38a99310e40f
[ "MIT" ]
null
null
null
// ClientSockTest.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <stdio.h> #include <WinSock2.h> #include "protocolo\ProtocoloPartida.h" int _tmain(int argc, _TCHAR* argv[]) { //ConnServidor AutenticacaoHeader autenticacaoHeader; AutenticacaoRequest autenticacaoRequest; autenticacaoHeader.status = AUTH_STATUS_CONNECT; autenticacaoRequest.cabecalho = autenticacaoHeader; autenticacaoRequest.login = "MyLogin"; autenticacaoRequest.senha = "MySenha"; //TODO depois de recebido o IP e PORTA do server WSADATA wsaData; WSAStartup(MAKEWORD(2,2), &wsaData); SOCKET principalSocket; principalSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (principalSocket == INVALID_SOCKET) { closesocket(principalSocket); } sockaddr_in enderecoServidor; enderecoServidor.sin_family = AF_INET; enderecoServidor.sin_addr.s_addr = inet_addr("127.0.0.1"); //inet_addr(INADDR_ANY);//0.0.0.0 enderecoServidor.sin_port = htons(12345); //bind(principalSocket, (SOCKADDR*)&enderecoServidor, sizeof(enderecoServidor)); connect( principalSocket, (SOCKADDR*) &enderecoServidor, sizeof(enderecoServidor) ); sockaddr_in remetente; int rementeSize = sizeof(remetente); //sendto(principalSocket, ((char *)&autenticacaoRequest), sizeof(autenticacaoRequest), NULL,(SOCKADDR*)&enderecoServidor, sizeof(enderecoServidor)); int b = send(principalSocket, ((char *)&autenticacaoRequest), sizeof(autenticacaoRequest), 0); printf("Bytes sent %d", b); closesocket(principalSocket); WSACleanup(); //getchar(); return 0; }
37.688889
154
0.712264
enzoam
c94821f57008f131f50248355c78a915cd1aca08
3,869
cpp
C++
src/openms/source/FORMAT/IndexedMzMLFileLoader.cpp
vmusch/OpenMS
3c4a078ad4687677393c138d4acb91bb444a7c7b
[ "BSL-1.0", "Zlib", "Apache-2.0" ]
2
2017-06-27T04:21:37.000Z
2022-03-23T11:20:11.000Z
src/openms/source/FORMAT/IndexedMzMLFileLoader.cpp
vmusch/OpenMS
3c4a078ad4687677393c138d4acb91bb444a7c7b
[ "BSL-1.0", "Zlib", "Apache-2.0" ]
36
2018-03-23T15:00:23.000Z
2022-02-18T16:04:58.000Z
src/openms/source/FORMAT/IndexedMzMLFileLoader.cpp
vmusch/OpenMS
3c4a078ad4687677393c138d4acb91bb444a7c7b
[ "BSL-1.0", "Zlib", "Apache-2.0" ]
4
2018-03-22T09:53:58.000Z
2018-09-11T09:07:21.000Z
// -------------------------------------------------------------------------- // OpenMS -- Open-Source Mass Spectrometry // -------------------------------------------------------------------------- // Copyright The OpenMS Team -- Eberhard Karls University Tuebingen, // ETH Zurich, and Freie Universitaet Berlin 2002-2021. // // This software is released under a three-clause BSD license: // * 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 any author or any participating institution // may be used to endorse or promote products derived from this software // without specific prior written permission. // For a full list of authors, refer to the file AUTHORS. // -------------------------------------------------------------------------- // 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 ANY OF THE AUTHORS OR THE CONTRIBUTING // INSTITUTIONS 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. // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Hannes Roest $ // -------------------------------------------------------------------------- #include <OpenMS/FORMAT/IndexedMzMLFileLoader.h> #include <OpenMS/FORMAT/MzMLFile.h> #include <OpenMS/KERNEL/OnDiscMSExperiment.h> #include <OpenMS/FORMAT/DATAACCESS/MSDataWritingConsumer.h> namespace OpenMS { IndexedMzMLFileLoader::IndexedMzMLFileLoader() { } IndexedMzMLFileLoader::~IndexedMzMLFileLoader() { } PeakFileOptions & IndexedMzMLFileLoader::getOptions() { return options_; } const PeakFileOptions & IndexedMzMLFileLoader::getOptions() const { return options_; } void IndexedMzMLFileLoader::setOptions(const PeakFileOptions & options) { options_ = options; } bool IndexedMzMLFileLoader::load(const String& filename, OnDiscPeakMap& exp) { return exp.openFile(filename); } void IndexedMzMLFileLoader::store(const String& filename, OnDiscPeakMap& exp) { // Create a writing data consumer which consumes the experiment (writes it to disk) PlainMSDataWritingConsumer consumer(filename); consumer.setExpectedSize(exp.getNrSpectra(), exp.getNrChromatograms()); consumer.setExperimentalSettings(*exp.getExperimentalSettings().get()); options_.setWriteIndex(true); // ensure that we write the index consumer.setOptions(options_); for (Size i = 0; i < exp.getNrSpectra(); i++) { MSSpectrum s = exp.getSpectrum(i); consumer.consumeSpectrum(s); } for (Size i = 0; i < exp.getNrChromatograms(); i++) { MSChromatogram c = exp.getChromatogram(i); consumer.consumeChromatogram(c); } } void IndexedMzMLFileLoader::store(const String& filename, PeakMap& exp) { MzMLFile f; options_.setWriteIndex(true); // ensure that we write the index f.setOptions(options_); f.store(filename, exp); } }
38.69
87
0.660636
vmusch
c9487f57f9e19b1438ed8c1bf7a7a6db497ef6bf
210
hpp
C++
old/Net.Http.Server/inc/net/CRequest.hpp
raduionita/project-hermes
7935a1486d7b0f3c05208d2c7a2e36552581a23b
[ "MIT" ]
null
null
null
old/Net.Http.Server/inc/net/CRequest.hpp
raduionita/project-hermes
7935a1486d7b0f3c05208d2c7a2e36552581a23b
[ "MIT" ]
null
null
null
old/Net.Http.Server/inc/net/CRequest.hpp
raduionita/project-hermes
7935a1486d7b0f3c05208d2c7a2e36552581a23b
[ "MIT" ]
null
null
null
#ifndef __net_CREQUEST_HPP__ #define __net_CREQUEST_HPP__ #include <net\CMessage.hpp> namespace net { class CRequest : public CMessage { public: CRequest(); }; } #endif // __net_CREQUEST_HPP__
13.125
34
0.719048
raduionita
c9497d6156376874d098a91e1feed621577d870f
8,336
cpp
C++
casablanca/Release/src/pplx/windows/pplxwin.cpp
fpelliccioni/Tao
d23655bdf1ff521dc0c7e3fb2f101d1156fea4d9
[ "BSL-1.0" ]
1
2015-12-30T16:02:12.000Z
2015-12-30T16:02:12.000Z
casablanca/Release/src/pplx/windows/pplxwin.cpp
fpelliccioni/Tao
d23655bdf1ff521dc0c7e3fb2f101d1156fea4d9
[ "BSL-1.0" ]
null
null
null
casablanca/Release/src/pplx/windows/pplxwin.cpp
fpelliccioni/Tao
d23655bdf1ff521dc0c7e3fb2f101d1156fea4d9
[ "BSL-1.0" ]
null
null
null
/*** * ==++== * * Copyright (c) Microsoft Corporation. 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. * * ==--== * =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ * * pplxwin.cpp * * Windows specific implementation of PPL constructs * * =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- ****/ #include "stdafx.h" #include "pplxwin.h" #ifndef _MS_WINDOWS #error "ERROR: This file should only be included in Windows Build" #endif // Disable false alarm code analyze warning #pragma warning (disable : 26165 26110) namespace pplx { namespace platform { long GetCurrentThreadId() { return (long)(::GetCurrentThreadId()); } void YieldExecution() { YieldProcessor(); } } namespace details { // // Event implementation // event_impl::event_impl() { static_assert(sizeof(HANDLE) <= sizeof(_M_impl), "HANDLE version mismatch"); _M_impl = CreateEventEx(NULL, NULL, CREATE_EVENT_MANUAL_RESET, EVENT_ALL_ACCESS); if( _M_impl != NULL ) { ResetEvent(static_cast<HANDLE>(_M_impl)); } } event_impl::~event_impl() { CloseHandle(static_cast<HANDLE>(_M_impl)); } void event_impl::set() { SetEvent(static_cast<HANDLE>(_M_impl)); } void event_impl::reset() { ResetEvent(static_cast<HANDLE>(_M_impl)); } unsigned int event_impl::wait(unsigned int timeout) { DWORD waitTime = (timeout == event_impl::timeout_infinite) ? INFINITE : (DWORD)timeout; DWORD status = WaitForSingleObjectEx(static_cast<HANDLE>(_M_impl), waitTime, 0); _PPLX_ASSERT((status == WAIT_OBJECT_0) || (waitTime != INFINITE)); return (status == WAIT_OBJECT_0) ? 0 : event_impl::timeout_infinite; } // // critical_section implementation // // TFS# 612702 -- this implementation is unnecessariliy recursive. See bug for details. critical_section_impl::critical_section_impl() { static_assert(sizeof(CRITICAL_SECTION) <= sizeof(_M_impl), "CRITICAL_SECTION version mismatch"); InitializeCriticalSectionEx(reinterpret_cast<LPCRITICAL_SECTION>(&_M_impl), 0, 0); } critical_section_impl::~critical_section_impl() { DeleteCriticalSection(reinterpret_cast<LPCRITICAL_SECTION>(&_M_impl)); } void critical_section_impl::lock() { EnterCriticalSection(reinterpret_cast<LPCRITICAL_SECTION>(&_M_impl)); } void critical_section_impl::unlock() { LeaveCriticalSection(reinterpret_cast<LPCRITICAL_SECTION>(&_M_impl)); } // // reader_writer_lock implementation // reader_writer_lock_impl::reader_writer_lock_impl() : m_locked_exclusive(false) { static_assert(sizeof(SRWLOCK) <= sizeof(_M_impl), "SRWLOCK version mismatch"); InitializeSRWLock(reinterpret_cast<PSRWLOCK>(&_M_impl)); } void reader_writer_lock_impl::lock() { AcquireSRWLockExclusive(reinterpret_cast<PSRWLOCK>(&_M_impl)); m_locked_exclusive = true; } void reader_writer_lock_impl::lock_read() { AcquireSRWLockShared(reinterpret_cast<PSRWLOCK>(&_M_impl)); } void reader_writer_lock_impl::unlock() { if(m_locked_exclusive) { m_locked_exclusive = false; ReleaseSRWLockExclusive(reinterpret_cast<PSRWLOCK>(&_M_impl)); } else { ReleaseSRWLockShared(reinterpret_cast<PSRWLOCK>(&_M_impl)); } } // // Timer implementation // class windows_timer : public timer_impl::_Timer_interface { public: windows_timer(TaskProc userFunc, _In_ void * context) : m_userFunc(userFunc), m_userContext(context) { } virtual ~windows_timer() { } virtual void start(unsigned int ms, bool repeat) { #if defined(__cplusplus_winrt) auto timerHandler = ref new Windows::System::Threading::TimerElapsedHandler([this](Windows::System::Threading::ThreadPoolTimer ^) { this->m_userFunc(this->m_userContext); }); Windows::Foundation::TimeSpan span; span.Duration = ms * 10000; if (repeat) { m_hTimer = Windows::System::Threading::ThreadPoolTimer::CreatePeriodicTimer(timerHandler, span); } else { m_hTimer = Windows::System::Threading::ThreadPoolTimer::CreateTimer(timerHandler, span); } #else if (!CreateTimerQueueTimer(&m_hTimer, NULL, _TimerCallback, this, ms, repeat ? ms : 0, WT_EXECUTEDEFAULT)) { throw std::bad_alloc(); } #endif } virtual void stop(bool waitForCallbacks) { #if defined(__cplusplus_winrt) UNREFERENCED_PARAMETER(waitForCallbacks); if (m_hTimer != nullptr) { m_hTimer->Cancel(); m_hTimer = nullptr; } #else while (!DeleteTimerQueueTimer(NULL, m_hTimer, waitForCallbacks ? INVALID_HANDLE_VALUE : NULL)) { if (GetLastError() == ERROR_IO_PENDING) break; } #endif delete this; } private: static void CALLBACK _TimerCallback(PVOID context, BOOLEAN) { auto timer = static_cast<windows_timer *>(context); timer->m_userFunc(timer->m_userContext); } #if defined(__cplusplus_winrt) Windows::System::Threading::ThreadPoolTimer ^ m_hTimer; #else HANDLE m_hTimer; #endif TaskProc m_userFunc; void * m_userContext; }; void timer_impl::start(unsigned int ms, bool repeat, TaskProc userFunc, _In_ void * context) { _PPLX_ASSERT(m_timerImpl == nullptr); m_timerImpl = new windows_timer(userFunc, context); m_timerImpl->start(ms, repeat); } void timer_impl::stop(bool waitForCallbacks) { if (m_timerImpl != nullptr) { m_timerImpl->stop(waitForCallbacks); m_timerImpl = nullptr; } } // // scheduler implementation // #if defined(__cplusplus_winrt) void windows_scheduler::schedule( TaskProc proc, _In_ void* param) { auto workItemHandler = ref new Windows::System::Threading::WorkItemHandler([proc, param](Windows::Foundation::IAsyncAction ^ ) { proc(param); }); Windows::System::Threading::ThreadPool::RunAsync(workItemHandler); } #else struct _Scheduler_Param { TaskProc m_proc; void * m_param; _Scheduler_Param(TaskProc proc, _In_ void * param) : m_proc(proc), m_param(param) { } static void CALLBACK DefaultWorkCallback(PTP_CALLBACK_INSTANCE, PVOID pContext, PTP_WORK) { auto schedulerParam = (_Scheduler_Param *)(pContext); schedulerParam->m_proc(schedulerParam->m_param); delete schedulerParam; } }; void windows_scheduler::schedule( TaskProc proc, _In_ void* param) { auto schedulerParam = new _Scheduler_Param(proc, param); auto work = CreateThreadpoolWork(_Scheduler_Param::DefaultWorkCallback, schedulerParam, NULL); if (work == nullptr) { delete schedulerParam; throw utility::details::create_system_error(GetLastError()); } SubmitThreadpoolWork(work); CloseThreadpoolWork(work); } #endif } // namespace details } // namespace pplx
27.694352
141
0.604367
fpelliccioni
c94a45efcb827e009bf3a483ab85223fe81ecb9f
499
cpp
C++
Sorting/Bubble Sort.cpp
kavya98527/Data-Structures
e654bc3d8304b04bc2dc933d025fdddaa95be8d1
[ "Unlicense" ]
null
null
null
Sorting/Bubble Sort.cpp
kavya98527/Data-Structures
e654bc3d8304b04bc2dc933d025fdddaa95be8d1
[ "Unlicense" ]
null
null
null
Sorting/Bubble Sort.cpp
kavya98527/Data-Structures
e654bc3d8304b04bc2dc933d025fdddaa95be8d1
[ "Unlicense" ]
null
null
null
//Bubble Sort #include<iostream> using namespace std; int main() { int n; cin >> n; int Array[n]; cout<<"\nEnter any 6 Numbers for Unsorted Array : "; //Input for(int i=0; i<n; i++) { cin>>Array[i]; } //Bubble Sorting for(int i=0; i<n; i++) { for(int j=0; j<n-1; j++) { if(Array[j]>Array[j+1]) { int temp=Array[j]; Array[j]=Array[j+1]; Array[j+1]=temp; } } } //Output cout<<"\nSorted Array : "; for(int i=0; i<n; i++) { cout<<Array[i]<<"\t"; } }
12.475
53
0.521042
kavya98527
c94a5ae80dad357fd8a79c545c52888f575dac73
407
cpp
C++
C++/Algorithms/DynamicPrograming/Stairs problem.cpp
m-payal/AlgorithmsAndDataStructure
db53da00cefa3b681b4fcebfc0d22ee91cd489f9
[ "MIT" ]
195
2020-05-09T02:26:13.000Z
2022-03-30T06:12:07.000Z
C++/Algorithms/DynamicPrograming/Stairs problem.cpp
m-payal/AlgorithmsAndDataStructure
db53da00cefa3b681b4fcebfc0d22ee91cd489f9
[ "MIT" ]
31
2021-06-15T19:00:57.000Z
2022-02-02T15:51:25.000Z
C++/Algorithms/DynamicPrograming/Stairs problem.cpp
m-payal/AlgorithmsAndDataStructure
db53da00cefa3b681b4fcebfc0d22ee91cd489f9
[ "MIT" ]
64
2020-05-09T02:26:15.000Z
2022-02-23T16:02:01.000Z
#include <bits/stdc++.h> using namespace std; int main() { int n; //n represents the nth stair where a person wants to go cin>>n; int i; vector<int>A(n+1,0); A[0]=1; for(i=1;i<=n;i++) { A[i]+=A[i-1]; //number of ways from the previous step if(i>1) A[i]+=A[i-2]; // number of ways from the (current step-2)th step } cout<<A[n]<<endl; return 0; }
21.421053
74
0.535627
m-payal
c94ac6fabc48970ca0b67cd449a6340f3ab32cbc
1,571
cpp
C++
codeforces/A - Shifts/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
codeforces/A - Shifts/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
codeforces/A - Shifts/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: kzvd4729 created: Nov/24/2020 14:05 * solution_verdict: Accepted language: GNU C++14 * run_time: 154 ms memory_used: 4200 KB * problem: https://codeforces.com/contest/229/problem/A ****************************************************************************************/ #include<iostream> #include<vector> #include<cstring> #include<map> #include<bitset> #include<assert.h> #include<algorithm> #include<iomanip> #include<cmath> #include<set> #include<queue> #include<sstream> #include<unordered_map> #include<unordered_set> #include<chrono> #include<stack> #include<deque> #include<random> #define long long long using namespace std; const int N=1e6; string s;int cnt[N+2]; void cal() { int m=s.size(); vector<int>v;for(int i=0;i<m;i++)if(s[i]=='1')v.push_back(i); if((int)v.size()==0)cout<<-1<<endl,exit(0); for(int i=0;i<m;i++) { int id=lower_bound(v.begin(),v.end(),i)-v.begin(); int mn=N; if(id<(int)v.size())mn=min(mn,v[id]-i); else mn=min(mn,m+v[0]-i); id--; if(id>=0)mn=min(mn,i-v[id]); else mn=min(mn,m+i-v.back()); cnt[i]+=mn; } } int main() { ios_base::sync_with_stdio(0);cin.tie(0); int n,m;cin>>n>>m; for(int i=1;i<=n;i++) { cin>>s;cal(); } cout<<*min_element(cnt,cnt+m)<<endl; return 0; }
28.053571
111
0.484405
kzvd4729
c94c7c17c9e198b42b11834322606f625e91202f
1,238
cpp
C++
server/World/Packets/GWTeamLeaveHandler.cpp
viticm/web-pap
7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca
[ "BSD-3-Clause" ]
3
2018-06-19T21:37:38.000Z
2021-07-31T21:51:40.000Z
server/World/Packets/GWTeamLeaveHandler.cpp
viticm/web-pap
7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca
[ "BSD-3-Clause" ]
null
null
null
server/World/Packets/GWTeamLeaveHandler.cpp
viticm/web-pap
7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca
[ "BSD-3-Clause" ]
13
2015-01-30T17:45:06.000Z
2022-01-06T02:29:34.000Z
#include "stdafx.h" #include "GWTeamLeave.h" #include "Log.h" #include "OnlineUser.h" #include "ServerPlayer.h" #include "WGTeamError.h" #include "Team.h" #include "WGTeamResult.h" #include "ServerManager.h" UINT GWTeamLeaveHandler::Execute( GWTeamLeave* pPacket, Player* pPlayer ) { __ENTER_FUNCTION ServerPlayer* pServerPlayer = (ServerPlayer*)pPlayer; GUID_t guid = pPacket->GetGUID(); USER* pUser = g_pOnlineUser->FindUser( guid ); if( pUser==NULL ) { Log::SaveLog( WORLD_LOGFILE, "GWTeamLeaveHandler...User GUID=%X not find!", guid ); return PACKET_EXE_CONTINUE; } TeamID_t tid = pUser->GetTeamID(); if (tid == INVALID_ID) { Log::SaveLog( WORLD_LOGFILE, "GWTeamLeaveHandler...User GUID=%X TeamID is ERROR Success!", guid, tid ); } if( g_pOnlineUser->UserLeaveTeam( pUser ) ) { Log::SaveLog( WORLD_LOGFILE, "GWTeamLeaveHandler...User GUID=%X TeamID=%d Success!", guid, tid ); } else { Log::SaveLog( WORLD_LOGFILE, "GWTeamLeaveHandler...User GUID=%X TeamID=%d failed!", guid, tid ); } return PACKET_EXE_CONTINUE; __LEAVE_FUNCTION return PACKET_EXE_ERROR; }
22.107143
99
0.635703
viticm
c94fed8ffe323e48cde4cb84d40af16faf39e764
1,400
cpp
C++
2019/0609_ABC129/past/E.cpp
kazunetakahashi/atcoder
16ce65829ccc180260b19316e276c2fcf6606c53
[ "MIT" ]
7
2019-03-24T14:06:29.000Z
2020-09-17T21:16:36.000Z
2019/0609_ABC129/past/E.cpp
kazunetakahashi/atcoder
16ce65829ccc180260b19316e276c2fcf6606c53
[ "MIT" ]
null
null
null
2019/0609_ABC129/past/E.cpp
kazunetakahashi/atcoder
16ce65829ccc180260b19316e276c2fcf6606c53
[ "MIT" ]
1
2020-07-22T17:27:09.000Z
2020-07-22T17:27:09.000Z
#define DEBUG 1 /** * File : E.cpp * Author : Kazune Takahashi * Created : 6/9/2019, 9:16:59 PM * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> #include <algorithm> #include <vector> #include <string> #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> #include <set> #include <functional> #include <random> #include <chrono> #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; typedef long long ll; /* void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } */ /* const int dx[4] = {1, 0, -1, 0}; const int dy[4] = {0, 1, 0, -1}; */ const ll MOD = 1000000007; string L; ll dp[100010][2]; int main() { cin >> L; int N = L.size(); dp[0][0] = 1; for (auto i = 0; i < N; i++) { dp[i + 1][1] += (3 * dp[i][1]) % MOD; dp[i + 1][1] %= MOD; if (L[i] == '0') { dp[i + 1][0] += dp[i][0]; dp[i + 1][0] %= MOD; } else { dp[i + 1][1] += dp[i][0]; dp[i + 1][1] %= MOD; dp[i + 1][0] += (2 * dp[i][0]) % MOD; dp[i + 1][0] %= MOD; } #if DEBUG == 1 cerr << "dp[" << i + 1 << "][" << 0 << "] = " << dp[i + 1][0] << endl; cerr << "dp[" << i + 1 << "][" << 1 << "] = " << dp[i + 1][1] << endl; #endif } cout << (dp[N][0] + dp[N][1]) % MOD << endl; }
16.666667
74
0.48
kazunetakahashi
c9509f47f77b0612d3e71f3e5042c9ffd9a350ca
22,085
cpp
C++
wpd/WpdServiceSampleDriver/WpdObjectProperties.cpp
ixjf/Windows-driver-samples
38985ba91feb685095754775e101389ad90c2aa6
[ "MS-PL" ]
3,084
2015-03-18T04:40:32.000Z
2019-05-06T17:14:33.000Z
wpd/WpdServiceSampleDriver/WpdObjectProperties.cpp
ixjf/Windows-driver-samples
38985ba91feb685095754775e101389ad90c2aa6
[ "MS-PL" ]
275
2015-03-19T18:44:41.000Z
2019-05-06T14:13:26.000Z
wpd/WpdServiceSampleDriver/WpdObjectProperties.cpp
ixjf/Windows-driver-samples
38985ba91feb685095754775e101389ad90c2aa6
[ "MS-PL" ]
3,091
2015-03-19T00:08:54.000Z
2019-05-06T16:42:01.000Z
#include "stdafx.h" #include "WpdObjectProperties.tmh" WpdObjectProperties::WpdObjectProperties() : m_pDevice(NULL) { } WpdObjectProperties::~WpdObjectProperties() { } HRESULT WpdObjectProperties::Initialize(_In_ FakeDevice* pDevice) { if (pDevice == NULL) { return E_POINTER; } m_pDevice = pDevice; return S_OK; } HRESULT WpdObjectProperties::DispatchWpdMessage( _In_ REFPROPERTYKEY Command, _In_ IPortableDeviceValues* pParams, _In_ IPortableDeviceValues* pResults) { HRESULT hr = S_OK; if (hr == S_OK) { if (Command.fmtid != WPD_CATEGORY_OBJECT_PROPERTIES) { hr = E_INVALIDARG; CHECK_HR(hr, "This object does not support this command category %ws",CComBSTR(Command.fmtid)); } } if (hr == S_OK) { if (IsEqualPropertyKey(Command, WPD_COMMAND_OBJECT_PROPERTIES_GET_SUPPORTED)) { hr = OnGetSupportedProperties(pParams, pResults); CHECK_HR(hr, "Failed to get supported properties"); } else if(IsEqualPropertyKey(Command, WPD_COMMAND_OBJECT_PROPERTIES_GET)) { hr = OnGetPropertyValues(pParams, pResults); if(FAILED(hr)) { CHECK_HR(hr, "Failed to get properties"); } } else if(IsEqualPropertyKey(Command, WPD_COMMAND_OBJECT_PROPERTIES_GET_ALL)) { hr = OnGetAllPropertyValues(pParams, pResults); if(FAILED(hr)) { CHECK_HR(hr, "Failed to get all properties"); } } else if(IsEqualPropertyKey(Command, WPD_COMMAND_OBJECT_PROPERTIES_SET)) { hr = OnSetPropertyValues(pParams, pResults); if(FAILED(hr)) { CHECK_HR(hr, "Failed to set properties"); } } else if(IsEqualPropertyKey(Command, WPD_COMMAND_OBJECT_PROPERTIES_GET_ATTRIBUTES)) { hr = OnGetPropertyAttributes(pParams, pResults); if(FAILED(hr)) { CHECK_HR(hr, "Failed to get property attributes"); } } else if(IsEqualPropertyKey(Command, WPD_COMMAND_OBJECT_PROPERTIES_DELETE)) { hr = OnDeleteProperties(pParams, pResults); if(FAILED(hr)) { CHECK_HR(hr, "Failed to delete properties"); } } else { hr = E_NOTIMPL; CHECK_HR(hr, "This object does not support this command id %d", Command.pid); } } return hr; } /** * This method is called when we receive a WPD_COMMAND_OBJECT_PROPERTIES_GET_SUPPORTED * command. * * The parameters sent to us are: * - WPD_PROPERTY_OBJECT_PROPERTIES_OBJECT_ID: identifies the object whose supported properties have * been requested. * * - WPD_PROPERTY_OBJECT_PROPERTIES_FILTER: the filter to use when returning supported properties. * Since this parameter is optional, it may not exist. * ! This driver currently ignores the filter parameter. ! * * The driver should: * - Return supported property keys for the specified object in WPD_PROPERTY_OBJECT_PROPERTIES_PROPERTY_KEYS */ HRESULT WpdObjectProperties::OnGetSupportedProperties( _In_ IPortableDeviceValues* pParams, _In_ IPortableDeviceValues* pResults) { HRESULT hr = S_OK; LPWSTR wszObjectID = NULL; CComPtr<IPortableDeviceKeyCollection> pKeys; // First get ALL parameters for this command. If we cannot get ALL parameters // then E_INVALIDARG should be returned and no further processing should occur. // Get the object identifier whose supported properties have been requested hr = pParams->GetStringValue(WPD_PROPERTY_OBJECT_PROPERTIES_OBJECT_ID, &wszObjectID); if (hr != S_OK) { hr = E_INVALIDARG; CHECK_HR(hr, "Missing string value for WPD_PROPERTY_OBJECT_PROPERTIES_OBJECT_ID"); } // CoCreate a collection to store the supported property keys. if (hr == S_OK) { hr = CoCreateInstance(CLSID_PortableDeviceKeyCollection, NULL, CLSCTX_INPROC_SERVER, IID_IPortableDeviceKeyCollection, (VOID**) &pKeys); CHECK_HR(hr, "Failed to CoCreate CLSID_PortableDeviceKeyCollection"); } // Add supported property keys for the specified object to the collection if (hr == S_OK) { ACCESS_SCOPE Scope = m_pDevice->GetAccessScope(pParams); hr = m_pDevice->GetSupportedProperties(Scope, wszObjectID, pKeys); CHECK_HR(hr, "Failed to add supported property keys for object '%ws'", wszObjectID); } // Set the WPD_PROPERTY_OBJECT_PROPERTIES_PROPERTY_KEYS value in the results. if (hr == S_OK) { hr = pResults->SetIPortableDeviceKeyCollectionValue(WPD_PROPERTY_OBJECT_PROPERTIES_PROPERTY_KEYS, pKeys); CHECK_HR(hr, "Failed to set WPD_PROPERTY_OBJECT_PROPERTIES_PROPERTY_KEYS"); } // Free the memory. CoTaskMemFree ignores NULLs so no need to check. CoTaskMemFree(wszObjectID); return hr; } /** * This method is called when we receive a WPD_COMMAND_OBJECT_PROPERTIES_GET * command. * * The parameters sent to us are: * - WPD_PROPERTY_OBJECT_PROPERTIES_OBJECT_ID: identifies the object whose property values have been requested. * - WPD_PROPERTY_OBJECT_PROPERTIES_PROPERTY_KEYS: a collection of property keys, identifying which * specific property values we are requested to return. * * The driver should: * - Return all requested property values in WPD_PROPERTY_OBJECT_PROPERTIES_PROPERTY_VALUES. If any property read failed, the corresponding value should be * set to type VT_ERROR with the 'scode' member holding the HRESULT reason for the failure. * - S_OK should be returned if all properties were read successfully. * - S_FALSE should be returned if any property read failed. * - Any error return indicates that the driver did not fill in any results, and the caller will * not attempt to unpack any property values. */ HRESULT WpdObjectProperties::OnGetPropertyValues( _In_ IPortableDeviceValues* pParams, _In_ IPortableDeviceValues* pResults) { HRESULT hr = S_OK; LPWSTR wszObjectID = NULL; CComPtr<IPortableDeviceValues> pValues; CComPtr<IPortableDeviceKeyCollection> pKeys; // First get ALL parameters for this command. If we cannot get ALL parameters // then E_INVALIDARG should be returned and no further processing should occur. // Get the object identifier whose property values have been requested if (hr == S_OK) { hr = pParams->GetStringValue(WPD_PROPERTY_OBJECT_PROPERTIES_OBJECT_ID, &wszObjectID); CHECK_HR(hr, "Missing value for WPD_PROPERTY_OBJECT_PROPERTIES_OBJECT_ID"); } // Get the list of property keys for the property values the caller wants to retrieve from the specified object if (hr == S_OK) { hr = pParams->GetIPortableDeviceKeyCollectionValue(WPD_PROPERTY_OBJECT_PROPERTIES_PROPERTY_KEYS, &pKeys); CHECK_HR(hr, "Missing value for WPD_PROPERTY_OBJECT_PROPERTIES_PROPERTY_KEYS"); } // CoCreate a collection to store the property values. if (hr == S_OK) { hr = CoCreateInstance(CLSID_PortableDeviceValues, NULL, CLSCTX_INPROC_SERVER, IID_IPortableDeviceValues, (VOID**) &pValues); CHECK_HR(hr, "Failed to CoCreate CLSID_PortableDeviceValues"); } // Read the specified properties on the specified object and add the property values to the collection. if (hr == S_OK) { ACCESS_SCOPE Scope = m_pDevice->GetAccessScope(pParams); hr = m_pDevice->GetPropertyValues(Scope, wszObjectID, pKeys, pValues); CHECK_HR(hr, "Failed to get property values for object '%ws'", wszObjectID); } // S_OK or S_FALSE can be returned from GetPropertyValues( ). // S_FALSE means that 1 or more property values could not be retrieved successfully. // The value for the specified property should be set to an error HRESULT of // the reason why the property could not be read. // (e.g. If the property being requested is not supported on the object then an error of // HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED) should be set as the value. if (SUCCEEDED(hr)) { // Set the WPD_PROPERTY_OBJECT_PROPERTIES_PROPERTY_VALUES value in the results. HRESULT hrTemp = S_OK; hrTemp = pResults->SetIPortableDeviceValuesValue(WPD_PROPERTY_OBJECT_PROPERTIES_PROPERTY_VALUES, pValues); CHECK_HR(hrTemp, ("Failed to set WPD_PROPERTY_OBJECT_PROPERTIES_PROPERTY_VALUES")); if(FAILED(hrTemp)) { hr = hrTemp; } } // Free the memory. CoTaskMemFree ignores NULLs so no need to check. CoTaskMemFree(wszObjectID); return hr; } /** * This method is called when we receive a WPD_COMMAND_OBJECT_PROPERTIES_GET_ALL * command. * * The parameters sent to us are: * - WPD_PROPERTY_OBJECT_PROPERTIES_OBJECT_ID: identifies the object whose property values have been requested. * * The driver should: * - Return all property values in WPD_PROPERTY_OBJECT_PROPERTIES_PROPERTY_VALUES. If any property read failed, the corresponding value should be * set to type VT_ERROR with the 'scode' member holding the HRESULT reason for the failure. * - S_OK should be returned if all properties were read successfully. * - S_FALSE should be returned if any property read failed. * - Any error return indicates that the driver did not fill in any results, and the caller will * not attempt to unpack any property values. */ HRESULT WpdObjectProperties::OnGetAllPropertyValues( _In_ IPortableDeviceValues* pParams, _In_ IPortableDeviceValues* pResults) { HRESULT hr = S_OK; LPWSTR wszObjectID = NULL; CComPtr<IPortableDeviceValues> pValues; CComPtr<IPortableDeviceKeyCollection> pKeys; // First get ALL parameters for this command. If we cannot get ALL parameters // then E_INVALIDARG should be returned and no further processing should occur. // Get the object identifier whose property values have been requested if (hr == S_OK) { hr = pParams->GetStringValue(WPD_PROPERTY_OBJECT_PROPERTIES_OBJECT_ID, &wszObjectID); CHECK_HR(hr, "Missing value for WPD_PROPERTY_OBJECT_PROPERTIES_OBJECT_ID"); } // CoCreate a collection to store the property values. if (hr == S_OK) { hr = CoCreateInstance(CLSID_PortableDeviceValues, NULL, CLSCTX_INPROC_SERVER, IID_IPortableDeviceValues, (VOID**) &pValues); CHECK_HR(hr, "Failed to CoCreate CLSID_PortableDeviceValues"); } // First we make a request for ALL supported property keys for the specified object. // Next, we delegate to our helper function GetPropertyValuesForObject( ) passing // the entire property key collection. This will reuse existing implementation // in our driver to perform the GetAllPropertyValues operation. if (hr == S_OK) { ACCESS_SCOPE Scope = m_pDevice->GetAccessScope(pParams); hr = m_pDevice->GetAllPropertyValues(Scope, wszObjectID, pValues); CHECK_HR(hr, "Failed to get all property values for object '%ws'", wszObjectID); } // S_OK or S_FALSE can be returned from GetAllPropertyValues( ). // S_FALSE means that 1 or more property values could not be retrieved successfully. // The value for the specified property key should be set to the error HRESULT of // the reason why the property could not be read. // (i.e. an error of HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED) if a property value was // requested and is not supported by the specified object.) if (SUCCEEDED(hr)) { // Set the WPD_PROPERTY_OBJECT_PROPERTIES_PROPERTY_VALUES value in the results HRESULT hrTemp = S_OK; hrTemp = pResults->SetIPortableDeviceValuesValue(WPD_PROPERTY_OBJECT_PROPERTIES_PROPERTY_VALUES, pValues); CHECK_HR(hrTemp, "Failed to set WPD_PROPERTY_OBJECT_PROPERTIES_PROPERTY_VALUES"); if(FAILED(hrTemp)) { hr = hrTemp; } } // Free the memory. CoTaskMemFree ignores NULLs so no need to check. CoTaskMemFree(wszObjectID); return hr; } /** * This method is called when we receive a WPD_COMMAND_OBJECT_PROPERTIES_SET * command. * * The parameters sent to us are: * - WPD_PROPERTY_OBJECT_PROPERTIES_OBJECT_ID: identifies the object whose property values we want to return. * - WPD_PROPERTY_OBJECT_PROPERTIES_PROPERTY_VALUES: an IPortableDeviceValues of values, identifying which * specific property values we are requested to write. * * The driver should: * - Write all requested property values. For each property, a write result should be returned in the * write result property store. * - If any property write failed, the corresponding write result value should be * set to type VT_ERROR with the 'scode' member holding the HRESULT reason for the failure. * - S_OK should be returned if all properties were written successfully. * - S_FALSE should be returned if any property write failed. * - Any error return indicates that the driver did not write any results, and the caller will * not attempt to unpack any property write results. */ HRESULT WpdObjectProperties::OnSetPropertyValues( _In_ IPortableDeviceValues* pParams, _In_ IPortableDeviceValues* pResults) { HRESULT hr = S_OK; LPWSTR wszObjectID = NULL; bool bObjectChanged = false; CComPtr<IPortableDeviceValues> pValues; CComPtr<IPortableDeviceValues> pWriteResults; CComPtr<IPortableDeviceValues> pEventParams; // First get ALL parameters for this command. If we cannot get ALL parameters // then E_INVALIDARG should be returned and no further processing should occur. // Get the object identifier whose property values are being set if (hr == S_OK) { hr = pParams->GetStringValue(WPD_PROPERTY_OBJECT_PROPERTIES_OBJECT_ID, &wszObjectID); CHECK_HR(hr, "Missing value for WPD_PROPERTY_OBJECT_PROPERTIES_OBJECT_ID"); } // Get the caller-supplied property values requested to be set on the object if (hr == S_OK) { hr = pParams->GetIPortableDeviceValuesValue(WPD_PROPERTY_OBJECT_PROPERTIES_PROPERTY_VALUES, &pValues); CHECK_HR(hr, "Missing value for WPD_PROPERTY_OBJECT_PROPERTIES_PROPERTY_VALUES"); } // CoCreate a collection to store the property set operation results. if (hr == S_OK) { hr = CoCreateInstance(CLSID_PortableDeviceValues, NULL, CLSCTX_INPROC_SERVER, IID_IPortableDeviceValues, (VOID**) &pWriteResults); CHECK_HR(hr, "Failed to CoCreate CLSID_PortableDeviceValues"); } // CoCreate a collection to store the property set event parameters. if (hr == S_OK) { hr = CoCreateInstance(CLSID_PortableDeviceValues, NULL, CLSCTX_INPROC_SERVER, IID_IPortableDeviceValues, (VOID**) &pEventParams); CHECK_HR(hr, "Failed to CoCreateInstance CLSID_PortableDeviceValues"); } // Set the property values on the specified object if (hr == S_OK) { ACCESS_SCOPE Scope = m_pDevice->GetAccessScope(pParams); hr = m_pDevice->SetPropertyValues(Scope, wszObjectID, pValues, pWriteResults, pEventParams, &bObjectChanged); CHECK_HR(hr, "Failed to set property values on object '%ws'", wszObjectID); } if (SUCCEEDED(hr)) { // Set the WPD_PROPERTY_OBJECT_PROPERTIES_PROPERTY_WRITE_RESULTS value in the results HRESULT hrTemp = pResults->SetIPortableDeviceValuesValue(WPD_PROPERTY_OBJECT_PROPERTIES_PROPERTY_WRITE_RESULTS, pWriteResults); CHECK_HR(hrTemp, "Failed to set WPD_PROPERTY_OBJECT_PROPERTIES_PROPERTY_WRITE_RESULTS"); if (FAILED(hrTemp)) { hr = hrTemp; } if (SUCCEEDED(hr) && bObjectChanged) { // Post the event indicating the object has changed hrTemp = PostWpdEvent(pParams, pEventParams); CHECK_HR(hrTemp, "Failed post event for updated object [%ws] (errors ignored)", wszObjectID); } } // Free the memory. CoTaskMemFree ignores NULLs so no need to check. CoTaskMemFree(wszObjectID); return hr; } /** * This method is called when we receive a WPD_COMMAND_OBJECT_PROPERTIES_GET_ATTRIBUTES * command. * * The parameters sent to us are: * - WPD_PROPERTY_OBJECT_PROPERTIES_OBJECT_ID: identifies the object whose property attributes we want to return. * - WPD_PROPERTY_OBJECT_PROPERTIES_PROPERTY_KEYS: a collection of property keys containing a single value, * which is the key identifying the specific property attributes we are requested to return. * * The driver should: * - Return the requested property attributes. If any property attributes failed to be retrieved, * the corresponding value should be set to type VT_ERROR with the 'scode' member holding the * HRESULT reason for the failure. * - S_OK should be returned if all property attributes were read successfully. * - S_FALSE should be returned if any property attribute failed. * - Any error return indicates that the driver did not fill in any results, and the caller will * not attempt to unpack any property values. */ HRESULT WpdObjectProperties::OnGetPropertyAttributes( _In_ IPortableDeviceValues* pParams, _In_ IPortableDeviceValues* pResults) { HRESULT hr = S_OK; LPWSTR wszObjectID = NULL; PROPERTYKEY Key = WPD_PROPERTY_NULL; CComPtr<IPortableDeviceValues> pAttributes; // First get ALL parameters for this command. If we cannot get ALL parameters // then E_INVALIDARG should be returned and no further processing should occur. // Get the object identifier whose property attributes have been requested if (hr == S_OK) { hr = pParams->GetStringValue(WPD_PROPERTY_OBJECT_PROPERTIES_OBJECT_ID, &wszObjectID); CHECK_HR(hr, "Missing value for WPD_PROPERTY_OBJECT_PROPERTIES_OBJECT_ID"); } // Get the list of property keys whose attributes are being requested if (hr == S_OK) { hr = pParams->GetKeyValue(WPD_PROPERTY_OBJECT_PROPERTIES_PROPERTY_KEYS, &Key); CHECK_HR(hr, "Missing value for WPD_PROPERTY_OBJECT_PROPERTIES_PROPERTY_KEYS"); } // CoCreate a collection to store the property attributes. if (hr == S_OK) { hr = CoCreateInstance(CLSID_PortableDeviceValues, NULL, CLSCTX_INPROC_SERVER, IID_IPortableDeviceValues, (VOID**) &pAttributes); CHECK_HR(hr, "Failed to CoCreate CLSID_PortableDeviceValues"); } // Get the attributes for the specified properties on the specified object and add them // to the collection. if (hr == S_OK) { ACCESS_SCOPE Scope = m_pDevice->GetAccessScope(pParams); hr = m_pDevice->GetPropertyAtributes(Scope, wszObjectID, Key, pAttributes); CHECK_HR(hr, "Failed to get property attributes"); } if (SUCCEEDED(hr)) { // Set the WPD_PROPERTY_OBJECT_PROPERTIES_PROPERTY_ATTRIBUTES value in the results HRESULT hrTemp = S_OK; hrTemp = pResults->SetIPortableDeviceValuesValue(WPD_PROPERTY_OBJECT_PROPERTIES_PROPERTY_ATTRIBUTES, pAttributes); CHECK_HR(hrTemp, ("Failed to set WPD_PROPERTY_OBJECT_PROPERTIES_PROPERTY_ATTRIBUTES")); if(FAILED(hrTemp)) { hr = hrTemp; } } // Free the memory. CoTaskMemFree ignores NULLs so no need to check. CoTaskMemFree(wszObjectID); return hr; } /** * This method is called when we receive a WPD_COMMAND_OBJECT_PROPERTIES_DELETE * command. * * The parameters sent to us are: * - WPD_PROPERTY_OBJECT_PROPERTIES_OBJECT_ID: identifies the object whose properties should be deleted. * - WPD_PROPERTY_OBJECT_PROPERTIES_PROPERTY_KEYS: a collection of property keys indicating which * properties to delete. * * The driver should: * - Delete the specified properties from the object. * - S_OK should be returned if all specified properties were successfully deleted. * - E_ACCESSDENIED should be returned if the client attempts to delete a property which is not deletable (i.e. * WPD_PROPERTY_ATTRIBUTE_CAN_DELETE is FALSE for that property.) */ HRESULT WpdObjectProperties::OnDeleteProperties( _In_ IPortableDeviceValues* pParams, _In_ IPortableDeviceValues* pResults) { HRESULT hr = E_ACCESSDENIED; UNREFERENCED_PARAMETER(pParams); UNREFERENCED_PARAMETER(pResults); // This driver has no properties which can be deleted. return hr; }
40.597426
158
0.662576
ixjf
c95697ff3619b484d0173158a9e7645bb0049706
217
cpp
C++
RPG/GameTexture.cpp
JulesG10/Cube-RPG
183f9ed9ac2eb66de5b8c4192b2934a2314d1702
[ "MIT" ]
1
2021-05-15T13:43:43.000Z
2021-05-15T13:43:43.000Z
RPG/GameTexture.cpp
JulesG10/Cube
183f9ed9ac2eb66de5b8c4192b2934a2314d1702
[ "MIT" ]
null
null
null
RPG/GameTexture.cpp
JulesG10/Cube
183f9ed9ac2eb66de5b8c4192b2934a2314d1702
[ "MIT" ]
null
null
null
#include "GameTexture.h" GameTexture::GameTexture() { } GameTexture::~GameTexture() { this->block_textures.clear(); this->enemies_textures.clear(); this->items_textures.clear(); this->players_textures.clear(); }
16.692308
32
0.732719
JulesG10
c958cc49f87aeb1feb06aa37e28e27d3464c7fdb
115,838
cxx
C++
osprey/be/com/dep_graph.cxx
sharugupta/OpenUH
daddd76858a53035f5d713f648d13373c22506e8
[ "BSD-2-Clause" ]
null
null
null
osprey/be/com/dep_graph.cxx
sharugupta/OpenUH
daddd76858a53035f5d713f648d13373c22506e8
[ "BSD-2-Clause" ]
null
null
null
osprey/be/com/dep_graph.cxx
sharugupta/OpenUH
daddd76858a53035f5d713f648d13373c22506e8
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (C) 2008-2011 Advanced Micro Devices, Inc. All Rights Reserved. */ /* * Copyright 2004, 2005, 2006 PathScale, Inc. All Rights Reserved. */ /* Copyright (C) 2000, 2001 Silicon Graphics, Inc. All Rights Reserved. This program is free software; you can redistribute it and/or modify it under the terms of version 2 of the GNU General Public License as published by the Free Software Foundation. This program is distributed in the hope that it would be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Further, this software is distributed without any warranty that it is free of the rightful claim of any third person regarding infringement or the like. Any license provided herein, whether implied or otherwise, applies only to this software file. Patent licenses, if any, provided herein do not apply to combinations of this program with other software, or any other product whatsoever. You should have received a copy of the GNU General Public License along with this program; if not, write the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston MA 02111-1307, USA. Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pky, Mountain View, CA 94043, or: http://www.sgi.com For further information regarding this notice, see: http://oss.sgi.com/projects/GenInfo/NoticeExplan */ //-*-c++-*- // Array Dependence Graph // ----------------------- // // // /* ==================================================================== * ==================================================================== * * Module: dep_graph.cxx * $Revision: 1.1.1.1 $ * $Date: 2005/10/21 19:00:00 $ * $Author: marcel $ * $Source: /proj/osprey/CVS/open64/osprey1.0/be/com/dep_graph.cxx,v $ * * Revision history: * dd-mmm-94 - Original Version * * Description: Build array dependence graph * * ==================================================================== * ==================================================================== */ #include <stdint.h> #ifdef USE_PCH #include "be_com_pch.h" #endif /* USE_PCH */ #pragma hdrstop #ifdef _KEEP_RCS_ID static char *rcs_id = "$Source: be/com/SCCS/s.dep_graph.cxx $ $Revision: 1.7 $"; #endif /* _KEEP_RCS_ID */ #include <sys/types.h> #if defined(BUILD_OS_DARWIN) #include <darwin_elf.h> #else /* defined(BUILD_OS_DARWIN) */ #include <elf.h> #endif /* defined(BUILD_OS_DARWIN) */ #define USE_STANDARD_TYPES /* override unwanted defines in "defs.h" */ #include <bstring.h> #include "wn.h" #include "erglob.h" #include "errors.h" #include "strtab.h" /* for strtab */ #include "stab.h" /* for symtab */ #include "irbdata.h" /* for inito */ #include "dwarf_DST_mem.h" /* for DST */ #include "pu_info.h" #ifdef __MINGW32__ #include <WINDOWS.h> #endif /* __MINGW32__ */ #include "ir_bwrite.h" #include "ir_bcom.h" #include "dep_graph.h" #include "stab.h" #ifdef LNO #include "call_info.h" #include "config.h" #include "config_cache.h" #include "errors.h" #include "erbe.h" #include "lnopt_main.h" #include "soe.h" #include "lwn_util.h" #include "opt_alias_interface.h" #include "lego_util.h" #include "opt_du.h" #ifdef DRAGON #include <fstream> #include <iostream> #include <string> using namespace std; #endif // return TRUE if any erased vertices. static BOOL LNO_Erase_Dg_From_Here_In_X(WN* wn, ARRAY_DIRECTED_GRAPH16* dg) { BOOL erased_vertices = FALSE; if (WN_opcode(wn) == OPC_BLOCK) { for (WN* w = WN_first(wn); w; w = WN_next(w)) if (LNO_Erase_Dg_From_Here_In_X(w, dg)) erased_vertices = TRUE; } else { for (INT k = 0; k < WN_kid_count(wn); k++) if (LNO_Erase_Dg_From_Here_In_X(WN_kid(wn,k), dg)) erased_vertices = TRUE; } OPCODE op = WN_opcode(wn); OPERATOR opr = OPCODE_operator(op); VINDEX16 v = dg->Get_Vertex(wn); if (OPCODE_is_load(op) || OPCODE_is_store(op) || OPCODE_is_call(op) || (OPCODE_operator(op) == OPR_INTRINSIC_OP) #ifdef KEY || (OPCODE_operator(op) == OPR_PURE_CALL_OP) #endif ) { if (v) { EINDEX16 enext = 0; EINDEX16 e; for (e = dg->Get_In_Edge(v); e; e = enext) { enext = dg->Get_Next_In_Edge(e); dg->Delete_Array_Edge(e); } for (e = dg->Get_Out_Edge(v); e; e = enext) { enext = dg->Get_Next_Out_Edge(e); dg->Delete_Array_Edge(e); } dg->Delete_Vertex(v); erased_vertices = TRUE; } } if (opr == OPR_DO_LOOP) { DO_LOOP_INFO* dli = Get_Do_Loop_Info(wn); if (dli->Has_Bad_Mem == TRUE) erased_vertices = TRUE; dli->Has_Bad_Mem = erased_vertices; } return erased_vertices; } void Unmapped_Vertices_Here_Out(WN* wn) { for ( ; wn; wn = LWN_Get_Parent(wn)) { if (WN_opcode(wn) == OPC_DO_LOOP) { DO_LOOP_INFO* dli = Get_Do_Loop_Info(wn); dli->Has_Bad_Mem = 1; } } } void LNO_Erase_Dg_From_Here_In(WN* wn, ARRAY_DIRECTED_GRAPH16* dg) { WN *outer_do = wn; WN *tmp = wn; while (tmp) { if (WN_opcode(tmp) == OPC_DO_LOOP) { outer_do = tmp; } tmp = LWN_Get_Parent(tmp); } if (LNO_Erase_Dg_From_Here_In_X(outer_do, dg)) Unmapped_Vertices_Here_Out(outer_do); } extern WN* Get_Only_Loop_Inside(const WN* wn, BOOL regions_ok); #endif ARRAY_DIRECTED_GRAPH16 *Current_Dep_Graph = NULL; void *C_Dep_Graph(void) { return Current_Dep_Graph; } void Init_Dep_Graph(void *g) { if (Current_Dep_Graph != NULL) Dealloc_Dep_Graph (); Current_Dep_Graph = (ARRAY_DIRECTED_GRAPH16 *)g; } void Dealloc_Dep_Graph(void) { /* deallocate the old dependence graph */ if (Current_Dep_Graph) { CXX_DELETE(Current_Dep_Graph, Malloc_Mem_Pool); Current_Dep_Graph = NULL; } } void LNOPruneMapsUsingParity(void) { if (Current_Dep_Graph) Current_Dep_Graph->PruneMapsUsingParity(); } void LNOPreserveMapPair(WN *orig, WN *wn1, WN *wn2) { if (Current_Dep_Graph) Current_Dep_Graph->PreserveMapPair(orig, wn1, wn2); } void LNOPrintDepGraph(FILE *fp) { if (Current_Dep_Graph) Current_Dep_Graph->Print(fp); } BOOL LnoDependenceEdge(WN *wn1, WN *wn2, EINDEX16 *distance, DIRECTION *direction, BOOL *is_must, BOOL *status) { VINDEX16 v1, v2; EINDEX16 edge; *status= FALSE; if (Current_Dep_Graph == NULL) return FALSE; v1 = Current_Dep_Graph->Get_Vertex(wn1); v2 = Current_Dep_Graph->Get_Vertex(wn2); if (v1 == 0 || v2 == 0) return FALSE; *status = TRUE; edge = Current_Dep_Graph->Get_Edge(v1, v2); if (edge) { DEP dep = Current_Dep_Graph->Dep(edge); *direction = DEP_Direction(dep); *is_must = Current_Dep_Graph->Is_Must(edge); *distance = DEP_IsDistance(dep) ? DEP_Distance(dep) : DEP_DistanceBound(dep); return TRUE; } return FALSE; } VINDEX16 LNOGetVertex(WN *wn) { if (Current_Dep_Graph) return Current_Dep_Graph->Get_Vertex(wn); return 0; } // remove all the edges and vertices from the graph void ARRAY_DIRECTED_GRAPH16::Erase_Graph() { for(VINDEX16 v= Get_Vertex(); v; v= Get_Next_Vertex(v)) { WN *wn = Get_Wn(v); if (wn != NULL) WN_MAP_Set(_map,wn,0); } #ifdef LNO if (_type==DEPV_ARRAY_ARRAY_GRAPH) { for(EINDEX16 e= Get_Edge(); e; e= Get_Next_Edge(e)) { Delete_DEPV_ARRAY(_e[e].Depv_Array,_pool); } } #endif } void ARRAY_DIRECTED_GRAPH16::PruneMapsUsingParity(void) { /* * iterate over all vertices and remove nodes that are * proven independent by means of parity */ for(VINDEX16 v= Get_Vertex(); v; v= Get_Next_Vertex(v)) { EINDEX16 e= Get_Out_Edge(v); WN *tree= Get_Wn(v); while(e) { EINDEX16 e1= Get_Next_Out_Edge(e); if (WN_parity_independent(tree, Get_Wn(Get_Sink(e)))) { Remove_Edge(e); } e = e1; } e = Get_In_Edge(v); while(e) { EINDEX16 e1= Get_Next_In_Edge(e); if (WN_parity_independent(tree, Get_Wn(Get_Sink(e)))) { Remove_Edge(e); } e = e1; } } } #ifdef LNO #ifdef DRAGON void ARRAY_DIRECTED_GRAPH16::Dragon_Print(char dumpfilename[], WN *func) { bool debug =false; VINDEX16 i; EINDEX16 e; EINDEX16 e_temp; const char *filename; const char *dirname; char *symbol_name; int count = 0; int line; // add here filename of graph. ifstream check(dumpfilename, ios::in); ofstream outfile; if (!check) { outfile.open(dumpfilename,ios::out |ios::binary); } else { outfile.open(dumpfilename,ios::out |ios::binary |ios::app); } check.close(); char *func_name=NULL; func_name = ST_name(WN_st(func)); int name_len_temp = strlen(func_name)+1; outfile.write((char *) &name_len_temp, sizeof(int)); outfile.write((char *) func_name, name_len_temp); if (debug) cout << "\nFunction name="<<func_name<<endl; for (i=1; i<_v.Lastidx()+1; i++) if (!_v[i].Is_Free()) count ++; if (debug) cout <<"total nodes="<<count<<endl; outfile.write((char *) &count, sizeof(int)); for (i=1; i<_v.Lastidx()+1; i++) { if (!_v[i].Is_Free()) { BOOL is_load = FALSE; BOOL is_call = FALSE; WN *wn = _v[i].Wn; WN* temp = LWN_Get_Expression(_v[i].Wn); line =0; SRCPOS srcpos = WN_Get_Linenum(temp); USRCPOS linepos; USRCPOS_srcpos(linepos) = srcpos; line = USRCPOS_linenum(linepos); //IR_Srcpos_Filename(srcpos,&filename,&dirname); if (OPCODE_is_load(WN_opcode(wn))) { is_load = TRUE; if (WN_kid_count(wn) >= 1) { wn = WN_kid0(wn); // not an ldid } } else if (OPCODE_is_store(WN_opcode(wn))) { if (WN_kid_count(wn) >= 2) { wn = WN_kid1(wn); // not an stid } } else { is_call = TRUE; } //end of else int array = 0; int name_len=0; int tempi= (int) i; outfile.write((char *) &tempi, sizeof(int)); outfile.write((char *) &line, sizeof(int)); if(debug) cout << "Node ID="<<i<<" line="<<line; if (WN_operator(wn) == OPR_ARRAY) { array =1; outfile.write((char *) &array, sizeof(int)); WN *base = WN_array_base(wn); if (OPCODE_has_sym(WN_opcode(base)) && WN_st(base)) { if (is_load) { int load =0; if (debug) cout << " is load"; outfile.write((char *) &load, sizeof(int)); } else { int load =1; outfile.write((char *) &load, sizeof(int)); if (debug) cout << " is store"; } symbol_name = ST_name(WN_st(WN_array_base(wn))); name_len = strlen(symbol_name)+1; outfile.write((char *) &name_len, sizeof(int)); outfile.write((char *) symbol_name, name_len); if (debug) cout << " name="<<symbol_name; } else { if (is_load) { int load =0; if (debug) cout << " is load"; outfile.write((char *) &load, sizeof(int)); } else { int load =1; outfile.write((char *) &load, sizeof(int)); if (debug) cout << " is store"; } char nosymbol[]="NO SYMBOL"; name_len = strlen(nosymbol)+1; outfile.write((char *) &name_len, sizeof(int)); outfile.write((char *) nosymbol, name_len); if (debug) cout << " name="<<nosymbol; } ACCESS_ARRAY *array = (ACCESS_ARRAY *) WN_MAP_Get(LNO_Info_Map,wn); array->Dragon_Print(outfile); }else { array =0; outfile.write((char *) &array, sizeof(int)); if (is_load) { int load =0; if (debug) cout << " is load"; outfile.write((char *) &load, sizeof(int)); //fprintf(fp,"Vertex %d for load from Wn = ",i); } else if (is_call) { int load =2; outfile.write((char *) &load, sizeof(int)); if (debug) cout << " is call"; //fprintf(fp,"Vertex %d for call into Wn = ",i); } else { int load =1; outfile.write((char *) &load, sizeof(int)); if (debug) cout << " is store"; //fprintf(fp,"Vertex %d for store into Wn = ",i); } char *temp=NULL; temp = ST_name(WN_st(wn)); if(temp==NULL) { char nosymbol[]="NO SYMBOL"; name_len = strlen(nosymbol)+1; outfile.write((char *) &name_len, sizeof(int)); outfile.write((char *) nosymbol, name_len); if (debug) cout << " name="<<nosymbol; } else { name_len = strlen(temp)+1; outfile.write((char *) &name_len, sizeof(int)); outfile.write((char *) temp, name_len); if (debug) cout << " name="<<temp; } // Dump_WN(wn,fp,TRUE,0,0); } if (debug) cout <<endl; e = _v[i].Get_Out_Edge(); e_temp = _v[i].Get_Out_Edge(); int e_count = 0; while (e_temp) { e_temp = _e[e_temp].Get_Next_Out_Edge(); e_count++; } outfile.write((char *) &e_count, sizeof(int)); if (debug) cout << "# of edges" << e_count<<" edges="; while (e) { if (debug) { // fprintf(stdout,"Edge %d to vertex %d ",e,_e[e].Get_Sink()); //fprintf(stdout," has DEPV_ARRAY = "); // _e[e].Depv_Array->Print(stdout); } int edgenum = _e[e].Get_Sink(); outfile.write((char *) &edgenum, sizeof(int)); e = _e[e].Get_Next_Out_Edge(); if (debug) cout <<edgenum<<","; } if (debug) cout << endl; } // end of v if its free. }//end of vertex traversal outfile.close(); cout <<"."; } #endif #endif #if defined(SHARED_BUILD) && !defined(LNO) void ARRAY_DIRECTED_GRAPH16::Print(FILE *fp) #else void ARRAY_DIRECTED_GRAPH16::Print(FILE *fp, INT) #endif { VINDEX16 i; EINDEX16 e; if (_type==DEPV_ARRAY_ARRAY_GRAPH) { fprintf(fp,"Printing an ARRAY_DIRECTED_GRAPH16 of type DEPV_ARRAY \n"); } else if (_type == LEVEL_ARRAY_GRAPH) { fprintf(fp,"Printing an ARRAY_DIRECTED_GRAPH16 of type level \n"); } else { fprintf(fp,"Printing an ARRAY_DIRECTED_GRAPH16 of type DEP \n"); } for (i=1; i<_v.Lastidx()+1; i++) { if (!_v[i].Is_Free()) { if (_type==DEPV_ARRAY_ARRAY_GRAPH) { #ifdef LNO BOOL is_load = FALSE; BOOL is_call = FALSE; WN *wn = _v[i].Wn; if (OPCODE_is_load(WN_opcode(wn))) { is_load = TRUE; if (WN_kid_count(wn) >= 1) { wn = WN_kid0(wn); // not an ldid } } else if (OPCODE_is_store(WN_opcode(wn))) { if (WN_kid_count(wn) >= 2) { wn = WN_kid1(wn); // not an stid } } else { is_call = TRUE; } if (WN_operator(wn) == OPR_ARRAY) { WN *base = WN_array_base(wn); if (OPCODE_has_sym(WN_opcode(base)) && WN_st(base)) { if (is_load) { fprintf(fp,"Vertex %d for load from Wn = %s",i, ST_name(WN_st(WN_array_base(wn)))); } else { fprintf(fp,"Vertex %d for store into Wn = %s",i, ST_name(WN_st(WN_array_base(wn)))); } } else { if (is_load) { fprintf(fp,"Vertex %d for load from Wn = ??? ",i); } else { fprintf(fp,"Vertex %d for store into Wn = ??? ",i); } } ACCESS_ARRAY *array = (ACCESS_ARRAY *) WN_MAP_Get(LNO_Info_Map,wn); array->Print(fp); } else { if (is_load) { fprintf(fp,"Vertex %d for load from Wn = ",i); } else if (is_call) { fprintf(fp,"Vertex %d for call into Wn = ",i); } else { fprintf(fp,"Vertex %d for store into Wn = ",i); } Dump_WN(wn,fp,TRUE,0,0); } #endif } else { fprintf(fp,"Vertex %d for Wn = 0x%p",i,_v[i].Wn); #ifdef LNO // this is LNO specific but other groups might want something similar Dump_WN(_v[i].Wn,fp,TRUE,0,0); #endif fprintf(fp,"\n"); } e = _v[i].Get_Out_Edge(); while (e) { fprintf(fp,"Edge %d to vertex %d ",e,_e[e].Get_Sink()); if (_type==DEPV_ARRAY_ARRAY_GRAPH) { #ifdef LNO fprintf(fp," has DEPV_ARRAY = "); _e[e].Depv_Array->Print(fp); #endif } else if (_type == LEVEL_ARRAY_GRAPH) { #ifdef LNO fprintf(fp," has level %d \n",_e[e].Level_Info.Level); #endif } else { fprintf(fp," has dep "); DEP_Print(_e[e].DEP_Struct.Dep,fp); fprintf(fp," and Is_Must is %d\n",_e[e].DEP_Struct.Is_Must); } e = _e[e].Get_Next_Out_Edge(); } } } } extern "C" void Depgraph_Write (void *depgraph, Output_File *fl, WN_MAP off_map) { ARRAY_DIRECTED_GRAPH16 *g = (ARRAY_DIRECTED_GRAPH16 *)depgraph; VINDEX16 vmax, new_vmax, v, ve, x; EINDEX16 emax, e; Elf64_Word wn_off; DEP_STRUCT dep; VINDEX16 *vertex_map; /* write out the numbers of vertices and edges */ vmax = g->_v.Lastidx(); emax = g->_e.Lastidx(); /* remap the vertex indices to get rid of freed vertices */ vertex_map = CXX_NEW_ARRAY(VINDEX16, vmax + 1, Malloc_Mem_Pool); x = 1; for (v = 1; v <= vmax; v++) { // vertex is still in graph and there is some wn associated with this vertex if (g->Vertex_Is_In_Graph(v) && g->Get_Wn(v) != NULL) { vertex_map[v] = x; x += 1; } else { vertex_map[v] = 0; } } new_vmax = x - 1; ir_b_save_buf((void *)&new_vmax, sizeof(VINDEX16), sizeof(VINDEX16), 0, fl); ir_b_save_buf((void *)&emax, sizeof(EINDEX16), sizeof(EINDEX16), 0, fl); /* first write out all the vertices */ for (v = 1; v <= vmax; v++) { /* skip over freed vertices */ if (vertex_map[v] == 0) continue; /* write the offset of the WN */ wn_off = (Elf64_Word)WN_MAP32_Get(off_map, g->Get_Wn(v)); ir_b_save_buf((void *)&wn_off, sizeof(Elf64_Word), sizeof(Elf64_Word), 0, fl); } /* then write out the edges for each vertex */ for (v = 1; v <= vmax; v++) { /* skip over freed vertices */ if (vertex_map[v] == 0) continue; /* iterate through the "out" edges */ e = g->Get_Out_Edge(v); while (e) { /* write the sink of the edge */ ve = vertex_map[g->Get_Sink(e)]; if (ve) { // the sink exists ir_b_save_buf((void *)&ve, sizeof(VINDEX16), sizeof(VINDEX16),0,fl); /* write the dependence information */ dep = g->_e[e].DEP_Struct; ir_b_save_buf((void *)&dep, sizeof(DEP_STRUCT), MAX(4,sizeof(DEP_STRUCT)), 0, fl); } else { DevWarn("Missing sink \n"); } e = g->Get_Next_Out_Edge(e); } /* write a sink of zero to mark the last edge */ ve = 0; ir_b_save_buf((void *)&ve, sizeof(VINDEX16), sizeof(VINDEX16), 0, fl); } CXX_DELETE_ARRAY(vertex_map, Malloc_Mem_Pool); } #define WORD_ALIGNED(sz) (((sz) % 4) == 0 ? (sz) : (sz)+(4-((sz)%4))) extern "C" void * Depgraph_Read (char *cur_addr, char *end_addr, char *wn_base) { ARRAY_DIRECTED_GRAPH16 *g; VINDEX16 vmax, v, ve; EINDEX16 emax; Elf64_Word node_offset; DEP_STRUCT dep; WN *node; /* get the numbers of vertices and edges */ vmax = *(VINDEX16 *)cur_addr; cur_addr += (sizeof(VINDEX16)); emax = *(EINDEX16 *)cur_addr; cur_addr += (sizeof(EINDEX16)); g = CXX_NEW(ARRAY_DIRECTED_GRAPH16(vmax+1, emax+1, WN_MAP_DEPGRAPH, DEP_ARRAY_GRAPH), Malloc_Mem_Pool); /* create the vertices */ cur_addr = (char*) WORD_ALIGNED((INTPTR)cur_addr); for (v = 1; v <= vmax; v++) { node_offset = *(Elf64_Word *)cur_addr; cur_addr += (sizeof(Elf64_Word)); node = (WN *)(wn_base + node_offset); BOOL result = g->Add_Vertex(node); Is_True((result == v), ("New vertex not in order\n")); } /* read the edges */ for (v = 1; v <= vmax; v++) { while (1) { ve = *(VINDEX16 *)cur_addr; cur_addr += (sizeof(VINDEX16)); if (ve == 0) break; cur_addr = (char *)WORD_ALIGNED((INTPTR)cur_addr); dep = *(DEP_STRUCT *)cur_addr; cur_addr += (sizeof(DEP_STRUCT)); /* check for errors */ if ((ve > vmax) || (cur_addr > end_addr)) { CXX_DELETE(g, Malloc_Mem_Pool); return 0; } g->Add_Edge(v, ve, dep.Dep,dep.Is_Must); } } return (void *)g; } // All the remaining code is LNO specific and will not be linked in // by other phases #ifdef LNO extern MEM_POOL LNO_local_pool; // the local pool extern MEM_POOL LNO_default_pool; // the local pool static MEM_POOL DEP_local_pool; // a local pool for this file static BOOL dep_mempool_initialized = FALSE; static INT Common_Nest(const DOLOOP_STACK *s1, const DOLOOP_STACK *s2); static INT Num_Bad(const DOLOOP_STACK *s1); static DOLOOP_STACK *Copy_Doloop_Stack(DOLOOP_STACK *orig,MEM_POOL *pool); // mark all the DO loops surrounding wn as having bad memory references static void Set_Bad_Mem(WN *wn) { while (wn) { if (WN_opcode(wn) == OPC_DO_LOOP) { DO_LOOP_INFO *dli = (DO_LOOP_INFO *) WN_MAP_Get(LNO_Info_Map,wn); if (dli->Has_Bad_Mem) { return; } dli->Has_Bad_Mem = TRUE; } wn = LWN_Get_Parent(wn); } } // Build the DEPV_ARRAY or DEP graph, return 0 on error INT ARRAY_DIRECTED_GRAPH16::Build(WN *func_nd, MEM_POOL *pool) { Is_True(_type!=LEVEL_ARRAY_GRAPH, ("Build called on a LEVEL_ARRAY_GRAPH")); _pool = pool; if (!dep_mempool_initialized) { MEM_POOL_Initialize(&DEP_local_pool,"DEP_local_pool",FALSE); dep_mempool_initialized = TRUE; } MEM_POOL_Push(&LNO_local_pool); DOLOOP_STACK *stack=CXX_NEW(DOLOOP_STACK(&LNO_local_pool),&LNO_local_pool); INT res=Find_Region(func_nd,stack); MEM_POOL_Pop(&LNO_local_pool); if (res && _type == DEP_ARRAY_GRAPH) Add_Must(); return(res); } // find and then process an outer region // For DEPV_ARRAY graphs, an outer region is an outer "good" DO loop // For DEP graphs, we build graphs on inner loops, so an outer region // is an inner "good" do loop // Return 0 on error INT ARRAY_DIRECTED_GRAPH16::Find_Region(WN *wn, DOLOOP_STACK *stack) { WN *kid; if (OPCODE_is_leaf(WN_opcode(wn))) return(1); if (WN_opcode(wn) == OPC_BLOCK) { kid = WN_first (wn); while (kid) { if (!Find_Region(kid,stack)) return(0); kid = WN_next(kid); } } else if (WN_opcode(wn) == OPC_DO_LOOP) { DO_LOOP_INFO *dli = (DO_LOOP_INFO *) WN_MAP_Get(LNO_Info_Map,wn); dli->Has_Bad_Mem = FALSE; stack->Push(wn); if (Do_Loop_Is_Good(wn) && (!dli->Has_Unsummarized_Calls || dli->Is_Concurrent_Call) && !dli->Has_Exits && !dli->Has_Barriers && ((_type == DEPV_ARRAY_ARRAY_GRAPH) || (Do_Loop_Is_Inner(wn) && !dli->Has_Gotos && !dli->Has_Barriers))) { if (!Build_Region(WN_do_body(wn),WN_do_body(wn),stack)) { #ifdef KEY if (_type == DEPV_ARRAY_ARRAY_GRAPH) #endif LNO_Erase_Dg_From_Here_In(wn, this); return(0); } if (dli->Has_Bad_Mem) LNO_Erase_Vertices_In_Loop(wn,this); } else { Set_Bad_Mem(wn); for (INT kidno=0; kidno<WN_kid_count(wn); kidno++) { kid = WN_kid(wn,kidno); if (!Find_Region(kid,stack)) return(0); } } stack->Pop(); } else { for (INT kidno=0; kidno<WN_kid_count(wn); kidno++) { kid = WN_kid(wn,kidno); if (!Find_Region(kid,stack)) return(0); } } return(1); } // Is wn a loop variable in a common nesting of stack1 and stack2 static BOOL Loop_Var(WN *wn, DOLOOP_STACK *stack1, DOLOOP_STACK *stack2) { SYMBOL sym(wn); INT common_nest = Common_Nest(stack1,stack2); for (INT i=0; i<common_nest; i++) { if (sym == SYMBOL(WN_index(stack1->Top_nth(i)))) { return TRUE; } } return FALSE; } static UINT statement_number; // Process an outer region (an outer do loop if this is a DEPV_ARRAY graph, // an inner do loop if this is a DEP graph) // First make a list of all the reads and writes references // (this saves walking the code n^2 times) // While making the list, create a vertex for every reference // Then actually build the dependences // Return 0 on error INT ARRAY_DIRECTED_GRAPH16::Build_Region(WN *start, WN* end, DOLOOP_STACK *stack, BOOL rebuild, BOOL skip_bad) { REF_LIST_STACK *writes = CXX_NEW(REF_LIST_STACK(&LNO_local_pool), &LNO_local_pool); REF_LIST_STACK *reads = CXX_NEW(REF_LIST_STACK(&LNO_local_pool), &LNO_local_pool); CALL_STACK *calls = CXX_NEW(CALL_STACK(&LNO_local_pool), &LNO_local_pool); SCALAR_STACK *scalar_writes = CXX_NEW(SCALAR_STACK(&LNO_local_pool), &LNO_local_pool); SCALAR_STACK *scalar_reads = CXX_NEW(SCALAR_STACK(&LNO_local_pool), &LNO_local_pool); statement_number = 0; for (WN* wn=start; wn!=WN_next(end); wn=WN_next(wn)) { if (!Gather_References(wn,writes,reads,stack,scalar_writes,scalar_reads, calls,skip_bad)) return(0); } Is_True(!calls->Elements() || Has_Call_Info(calls->Bottom_nth(0)->_call) || WN_operator(calls->Bottom_nth(0)->_call) == OPR_INTRINSIC_CALL || Do_Loop_Is_Concurrent_Call(Enclosing_Do_Loop(start)), ("Unexpected call in Build_Region")); // If there are any permuation arrays, check if they're well behaved // (i.e. not written in the region of interest) if (Permutation_Arrays->Elements()) { INT i; for (i=0; i<Permutation_Arrays->Elements(); i++) { Permutation_Arrays->Bottom_nth(i)._is_good = TRUE; } for (i=0; i<reads->Elements(); i++) { REFERENCE_ITER iter1(reads->Bottom_nth(i)); for (REFERENCE_NODE *n1=iter1.First(); !iter1.Is_Empty(); n1=iter1.Next()) { WN *read = n1->Wn; WN *array = WN_kid0(read); if (WN_operator(array) == OPR_ADD) { WN *kid0 = WN_kid0(array); WN *kid1 = WN_kid1(array); if (WN_operator(kid0) == OPR_ARRAY) { array = kid0; } else { Is_True(WN_operator(kid1) == OPR_ARRAY, ("Bad ref in Build_Region")); array = kid1; } } Is_True(WN_operator(array) == OPR_ARRAY, ("Bad ref in Build_Region")); WN *base = WN_array_base(array); ST *read_st = WN_st(base); for (INT j=0; j<Permutation_Arrays->Elements(); j++) { if (read_st == Permutation_Arrays->Bottom_nth(j)._st) { // found a permutation, make sure it's not written BOOL is_bad = FALSE; for (INT k=0; k<writes->Elements() &&!is_bad; k++) { REFERENCE_ITER iter2(writes->Bottom_nth(k)); for (REFERENCE_NODE *n2=iter2.First(); !iter2.Is_Empty() && !is_bad; n2=iter2.Next()) { WN *write = n2->Wn; if (Overlapped_base(Alias_Mgr,write,read)!=NOT_ALIASED){ is_bad = TRUE; } } } for (INT si=0; si<scalar_writes->Elements(); si++) { SCALAR_NODE *snode = scalar_writes->Bottom_nth(si); WN *scalar_write = snode->Bottom_nth(0)->Wn; if (Overlapped_base(Alias_Mgr,scalar_write,read)!=NOT_ALIASED){ is_bad = TRUE; } } if (is_bad) Permutation_Arrays->Bottom_nth(j)._is_good = FALSE; } } } } } // Now visit the list, building the graph // First every write vrs every >= write INT i; for (i=0; i<writes->Elements(); i++) { for (INT j=i; j<writes->Elements(); j++) { // each element on the writes stack is a different base array // unless one of the base st pointers is zero if (i==j || !writes->Bottom_nth(i)->ST_Base || !writes->Bottom_nth(j)->ST_Base) { REFERENCE_ITER iter1(writes->Bottom_nth(i)); for (REFERENCE_NODE *n1=iter1.First(); !iter1.Is_Empty(); n1=iter1.Next()) { VINDEX16 v1=Get_Vertex(n1->Wn); if (v1) { // might not exist if a bad memory caused us to give up on loop REFERENCE_ITER iter2; if (i == j) iter2.Init(n1); else iter2.Init(writes->Bottom_nth(j)); for (REFERENCE_NODE *n2=iter2.First(); !iter2.Is_Empty(); n2=iter2.Next()) { VINDEX16 v2=Get_Vertex(n2->Wn); if (v2) { if (rebuild) { EINDEX16 e=Get_Edge(v1,v2); if (e) Delete_Edge(e); e=Get_Edge(v2,v1); if (e) Delete_Edge(e); } if (!Add_Edge(n1->Wn,n1->Stack,n2->Wn,n2->Stack, n1->Statement_Number < n2->Statement_Number)) { return(0); } } } } } } } } // Now every write vrs every read for (i=0; i<writes->Elements(); i++) { for (INT j=0; j<reads->Elements(); j++) { ST *base1 = writes->Bottom_nth(i)->ST_Base; ST *base2 = reads->Bottom_nth(j)->ST_Base; if (!base1 || !base2 || (base1 == base2)) { REFERENCE_ITER iter1(writes->Bottom_nth(i)); for (REFERENCE_NODE *n1=iter1.First(); !iter1.Is_Empty(); n1=iter1.Next()) { VINDEX16 v1=Get_Vertex(n1->Wn); if (v1) { REFERENCE_ITER iter2(reads->Bottom_nth(j)); for (REFERENCE_NODE *n2=iter2.First();!iter2.Is_Empty(); n2=iter2.Next()) { VINDEX16 v2=Get_Vertex(n2->Wn); if (v2) { if (rebuild) { EINDEX16 e=Get_Edge(v1,v2); if (e) Delete_Edge(e); e=Get_Edge(v2,v1); if (e) Delete_Edge(e); } if (!Add_Edge(n1->Wn,n1->Stack,n2->Wn,n2->Stack, n1->Statement_Number < n2->Statement_Number)) { return(0); } } } } } } } } // reset permutations for (i=0; i<Permutation_Arrays->Elements(); i++) { Permutation_Arrays->Bottom_nth(i)._is_good = FALSE; } // Deal with the concurrent calls // the only dependece with a concurrent call // is an all equals dependence for (i=0; i<calls->Elements(); i++) { if (calls->Bottom_nth(i)->_is_concurrent_call) { WN *call = calls->Bottom_nth(i)->_call; DOLOOP_STACK *call_stack = calls->Bottom_nth(i)->_stack; UINT call_statement_number = calls->Bottom_nth(i)->_statement_number; VINDEX16 vcall = Get_Vertex(call); INT j; for (j=i; j<calls->Elements(); j++) { if (calls->Bottom_nth(j)->_is_concurrent_call) { WN *call2 = calls->Bottom_nth(j)->_call; DOLOOP_STACK *call_stack2 = calls->Bottom_nth(j)->_stack; UINT call_statement_number2 = calls->Bottom_nth(j)->_statement_number; VINDEX16 vcall2 = Get_Vertex(call2); if (call_statement_number < call_statement_number2) { if (rebuild) { EINDEX16 e=Get_Edge(vcall,vcall2); if (e) Delete_Edge(e); } if (!Add_Edge_Equals(call,call_stack,call2,call_stack2)) { return 0; } } else { if (rebuild) { EINDEX16 e=Get_Edge(vcall2,vcall); if (e) Delete_Edge(e); } if (!Add_Edge_Equals(call2,call_stack2,call,call_stack)) { return 0; } } } } for (j=0; j<writes->Elements(); j++) { REFERENCE_ITER iter1(writes->Bottom_nth(j)); for (REFERENCE_NODE *n1=iter1.First(); !iter1.Is_Empty(); n1=iter1.Next()) { VINDEX16 v1=Get_Vertex(n1->Wn); if (call_statement_number < n1->Statement_Number) { if (rebuild) { EINDEX16 e=Get_Edge(vcall,v1); if (e) Delete_Edge(e); } if (!Add_Edge_Equals(call,call_stack,n1->Wn,n1->Stack)) { return 0; } } else { if (rebuild) { EINDEX16 e=Get_Edge(v1,vcall); if (e) Delete_Edge(e); } if (!Add_Edge_Equals(n1->Wn,n1->Stack,call,call_stack)) { return 0; } } } } for (j=0; j<reads->Elements(); j++) { REFERENCE_ITER iter1(reads->Bottom_nth(j)); for (REFERENCE_NODE *n1=iter1.First(); !iter1.Is_Empty(); n1=iter1.Next()) { VINDEX16 v1=Get_Vertex(n1->Wn); if (call_statement_number < n1->Statement_Number) { if (rebuild) { EINDEX16 e=Get_Edge(vcall,v1); if (e) Delete_Edge(e); } if (!Add_Edge_Equals(call,call_stack,n1->Wn,n1->Stack)) { return 0; } } else { if (rebuild) { EINDEX16 e=Get_Edge(v1,vcall); if (e) Delete_Edge(e); } if (!Add_Edge_Equals(n1->Wn,n1->Stack,call,call_stack)) { return 0; } } } } } } // Now deal with non-cunccurrent calls for (i=0; i<calls->Elements(); i++) { WN *call = calls->Bottom_nth(i)->_call; DOLOOP_STACK *call_stack = calls->Bottom_nth(i)->_stack; UINT call_statement_number = calls->Bottom_nth(i)->_statement_number; VINDEX16 vcall = Get_Vertex(call); for (INT j=i; j<calls->Elements(); j++) { WN *call2 = calls->Bottom_nth(j)->_call; if (!calls->Bottom_nth(i)->_is_concurrent_call || !calls->Bottom_nth(j)->_is_concurrent_call) { DOLOOP_STACK *call_stack2 = calls->Bottom_nth(j)->_stack; UINT call_statement_number2 = calls->Bottom_nth(j)->_statement_number; VINDEX16 vcall2 = Get_Vertex(call2); if (rebuild) { EINDEX16 e=Get_Edge(vcall,vcall2); if (e) Delete_Edge(e); e=Get_Edge(vcall2,vcall); if (e) Delete_Edge(e); } if (!Add_Edge(call,call_stack,call2,call_stack2, call_statement_number < call_statement_number2)) { return(0); } } } if (!calls->Bottom_nth(i)->_is_concurrent_call) { INT j; for (j=0; j<writes->Elements(); j++) { REFERENCE_ITER iter1(writes->Bottom_nth(j)); for (REFERENCE_NODE *n1=iter1.First(); !iter1.Is_Empty(); n1=iter1.Next()) { VINDEX16 v1=Get_Vertex(n1->Wn); if (rebuild) { EINDEX16 e=Get_Edge(vcall,v1); if (e) Delete_Edge(e); } if (!Add_Edge(call,call_stack,n1->Wn,n1->Stack, call_statement_number < n1->Statement_Number)) { return 0; } } } for (j=0; j<reads->Elements(); j++) { REFERENCE_ITER iter1(reads->Bottom_nth(j)); for (REFERENCE_NODE *n1=iter1.First(); !iter1.Is_Empty(); n1=iter1.Next()) { VINDEX16 v1=Get_Vertex(n1->Wn); if (rebuild) { EINDEX16 e=Get_Edge(vcall,v1); if (e) Delete_Edge(e); } if (!Add_Edge(call,call_stack,n1->Wn,n1->Stack, call_statement_number < n1->Statement_Number)) { return 0; } } } } } if (_type == DEPV_ARRAY_ARRAY_GRAPH) { // search for strange cross dependences between arrays and scalars // first the array writes vrs all the scalar references for (i=0; i<writes->Elements(); i++) { INT si; for (si=0; si<scalar_writes->Elements(); si++) { SCALAR_NODE *snode = scalar_writes->Bottom_nth(si); WN *scalar_write = snode->Bottom_nth(0)->Wn; ST *base = writes->Bottom_nth(i)->ST_Base; WN *array_write = writes->Bottom_nth(i)->Head()->Wn; if (!base || Overlapped_base(Alias_Mgr,scalar_write,array_write) != NOT_ALIASED) { REFERENCE_ITER iter1(writes->Bottom_nth(i)); for (REFERENCE_NODE *n1=iter1.First(); !iter1.Is_Empty(); n1=iter1.Next()) { array_write = n1->Wn; VINDEX16 awv = Get_Vertex(array_write); if (awv) { if (base || Overlapped_base(Alias_Mgr,scalar_write,array_write)!=NOT_ALIASED){ for (INT sj=0; sj<snode->Elements(); sj++) { scalar_write = snode->Bottom_nth(sj)->Wn; DOLOOP_STACK *scalar_stack=CXX_NEW(DOLOOP_STACK(&LNO_local_pool), &LNO_local_pool); Build_Doloop_Stack(scalar_write, scalar_stack); if (!Loop_Var(scalar_write,scalar_stack,n1->Stack)) { VINDEX16 swv = Get_Vertex(scalar_write); if (!swv) { if (!Add_Vertex(scalar_write)) { return 0; } swv = Get_Vertex(scalar_write); } if (rebuild) { EINDEX16 e=Get_Edge(awv,swv); if (e) Delete_Edge(e); e=Get_Edge(swv,awv); if (e) Delete_Edge(e); } if (!Add_Edge_Stars(array_write,n1->Stack, scalar_write,scalar_stack, n1->Statement_Number < snode->Bottom_nth(sj)->Statement_Number, FALSE)) { return 0; } } } } } } } } for (si=0; si<scalar_reads->Elements(); si++) { SCALAR_NODE *snode = scalar_reads->Bottom_nth(si); WN *scalar_read = snode->Bottom_nth(0)->Wn; ST *base = writes->Bottom_nth(i)->ST_Base; WN *array_write = writes->Bottom_nth(i)->Head()->Wn; if (!base || Overlapped_base(Alias_Mgr,scalar_read,array_write) != NOT_ALIASED) { REFERENCE_ITER iter1(writes->Bottom_nth(i)); // put in n^2 edges for (REFERENCE_NODE *n1=iter1.First(); !iter1.Is_Empty(); n1=iter1.Next()) { array_write = n1->Wn; VINDEX16 awv = Get_Vertex(array_write); if (awv) { if (base || Overlapped_base(Alias_Mgr,scalar_read,array_write)!=NOT_ALIASED) { for (INT sj=0; sj<snode->Elements(); sj++) { scalar_read = snode->Bottom_nth(sj)->Wn; DOLOOP_STACK *scalar_stack=CXX_NEW(DOLOOP_STACK(&LNO_local_pool), &LNO_local_pool); Build_Doloop_Stack(scalar_read, scalar_stack); VINDEX16 srv = Get_Vertex(scalar_read); if (!srv) { if (!Add_Vertex(scalar_read)) { return 0; } srv = Get_Vertex(scalar_read); } if (rebuild) { EINDEX16 e=Get_Edge(awv,srv); if (e) Delete_Edge(e); e=Get_Edge(srv,awv); if (e) Delete_Edge(e); } if (!Add_Edge_Stars(array_write,n1->Stack,scalar_read, scalar_stack, n1->Statement_Number < snode->Bottom_nth(sj)->Statement_Number, FALSE)) { return 0; } } } } } } } } // now the array reads vrs all the scalar writes for (i=0; i<reads->Elements(); i++) { for (INT si=0; si<scalar_writes->Elements(); si++) { SCALAR_NODE *snode = scalar_writes->Bottom_nth(si); WN *scalar_write = snode->Bottom_nth(0)->Wn; ST *base = reads->Bottom_nth(i)->ST_Base; WN *array_read = reads->Bottom_nth(i)->Head()->Wn; if (!base || Overlapped_base(Alias_Mgr,scalar_write,array_read) != NOT_ALIASED) { REFERENCE_ITER iter1(reads->Bottom_nth(i)); for (REFERENCE_NODE *n1=iter1.First(); !iter1.Is_Empty(); n1=iter1.Next()) { array_read = n1->Wn; VINDEX16 arv = Get_Vertex(array_read); if (arv) { if (base || Overlapped_base(Alias_Mgr,scalar_write,array_read)!=NOT_ALIASED) { for (INT sj=0; sj<snode->Elements(); sj++) { scalar_write = snode->Bottom_nth(sj)->Wn; DOLOOP_STACK *scalar_stack=CXX_NEW(DOLOOP_STACK(&LNO_local_pool), &LNO_local_pool); Build_Doloop_Stack(scalar_write, scalar_stack); VINDEX16 swv = Get_Vertex(scalar_write); if (!swv) { if (!Add_Vertex(scalar_write)) { return 0; } swv = Get_Vertex(scalar_write); } if (rebuild) { EINDEX16 e=Get_Edge(arv,swv); if (e) Delete_Edge(e); e=Get_Edge(swv,arv); if (e) Delete_Edge(e); } if (!Add_Edge_Stars(array_read,n1->Stack,scalar_write, scalar_stack, n1->Statement_Number < snode->Bottom_nth(sj)->Statement_Number, FALSE)) { return 0; } } } } } } } } } return(1); } // are the two memory array references "equivalent" // used as a guide for ivdep, if they are equivalent, we put in all equals // dependences regardless of ivdep static BOOL Equiv_Memory(WN *wn1, WN *wn2) { if (!wn1 || !wn2) return FALSE; if (!WN_Equiv(wn1,wn2)) { return FALSE; } for (INT i=0; i<WN_kid_count(wn1); i++) { if (!Equiv_Memory(WN_kid(wn1,i),WN_kid(wn2,i))) { return FALSE; } } return TRUE; } // is any part of the address a compiler_generated array // wn must be an expression static BOOL Compiler_Generated(WN *wn) { Is_True(OPCODE_is_expression(WN_opcode(wn)), ("Bad wn for Compiler_Generated")); OPCODE opc = WN_opcode(wn); if (OPCODE_has_sym(opc) && ST_pt_to_compiler_generated_mem(WN_st(wn))) { return TRUE; } else { for (INT kidno=0; kidno<WN_kid_count(wn); kidno++) { if (Compiler_Generated(WN_kid(wn,kidno))) { return TRUE; } } } return FALSE; } // Is this address invariant in its inner loop // if not sure, return FALSE static BOOL Ref_Inner_Invar(WN *addr, WN *loop) { OPCODE opcode = WN_opcode(addr); OPERATOR oper = OPCODE_operator(opcode); if ((oper == OPR_LDID) || (oper == OPR_PARM)) { DEF_LIST *defs = Du_Mgr->Ud_Get_Def(addr); if (defs) { DEF_LIST_ITER iter(defs); for(DU_NODE *node=iter.First(); !iter.Is_Empty(); node=iter.Next()) { WN *def = node->Wn(); WN *parent = def; while (parent && WN_opcode(parent) != OPC_DO_LOOP) { parent = LWN_Get_Parent(parent); } if (parent == loop) return FALSE; } } } else if (OPCODE_is_load(opcode)) { return FALSE; } for (INT kidno=0; kidno<WN_kid_count(addr); kidno++) { if (!Ref_Inner_Invar(WN_kid(addr,kidno),loop)) { return FALSE; } } return TRUE; } // Find the line number associated with this references static SRCPOS Find_Line(WN *wn) { WN *tmp_wn = wn; while (OPCODE_is_expression(WN_opcode(tmp_wn))) { tmp_wn = LWN_Get_Parent(tmp_wn); } return WN_Get_Linenum(tmp_wn); } // Compute the dependences and add two edges to the graph BOOL ARRAY_DIRECTED_GRAPH16::Add_Edge(WN *ref1, const DOLOOP_STACK *s1, WN *ref2, const DOLOOP_STACK *s2, BOOL s1_lex_before_s2, BOOL use_bounds) { OPCODE op1 = WN_opcode(ref1); OPCODE op2 = WN_opcode(ref2); OPERATOR oper1 = OPCODE_operator(op1); OPERATOR oper2 = OPCODE_operator(op2); Is_True(oper1 != OPR_ARRAY, ("ref 1 is an array in Add_Edge\n")); Is_True(oper2 != OPR_ARRAY, ("ref 2 is an array in Add_Edge\n")); if (!OPCODE_is_load(op1) && !OPCODE_is_store(op1) && !OPCODE_is_call(op1)) { return Add_Edge_Stars(ref1,s1,ref2,s2,s1_lex_before_s2); } if (!OPCODE_is_load(op2) && !OPCODE_is_store(op2) && !OPCODE_is_call(op2)) { return Add_Edge_Stars(ref1,s1,ref2,s2,s1_lex_before_s2); } if ((oper1 == OPR_LDID) || (oper1 == OPR_STID) || (oper2 == OPR_LDID) || (oper2 == OPR_STID)) { return Add_Edge_Stars(ref1,s1,ref2,s2,s1_lex_before_s2); } if (OPCODE_is_call(op1)) { if (Do_Loop_Is_Concurrent_Call(Enclosing_Do_Loop(ref1))) { if (s1_lex_before_s2) { return Add_Edge_Equals(ref1,s1,ref2,s2); } else { return Add_Edge_Equals(ref2,s2,ref1,s1); } } else if (!Has_Call_Info(ref1)) { return Add_Edge_Stars(ref1,s1,ref2,s2,s1_lex_before_s2); } } else if (OPCODE_is_call(op2)) { if (Do_Loop_Is_Concurrent_Call(Enclosing_Do_Loop(ref2))) { if (s1_lex_before_s2) { return Add_Edge_Equals(ref1,s1,ref2,s2); } else { return Add_Edge_Equals(ref2,s2,ref1,s1); } } else if (!Has_Call_Info(ref2)) { return Add_Edge_Stars(ref1,s1,ref2,s2,s1_lex_before_s2); } } WN *addr1=NULL,*addr2=NULL; if (!OPCODE_is_call(op1) ) { addr1 = (OPCODE_is_store(op1) ? (WN_kid1(ref1)) : (WN_kid0(ref1))) ; } if (!OPCODE_is_call(op2)) { addr2 = (OPCODE_is_store(op2) ? (WN_kid1(ref2)) : (WN_kid0(ref2))) ; } BOOL is_ivdep = FALSE; BOOL concurrent_directive = FALSE; BOOL s2_lex_before_s1 = ((!s1_lex_before_s2) && !(ref1 == ref2)); Is_True(_type!=LEVEL_ARRAY_GRAPH, ("Add_Edge called on a graph of type level")); UINT8 common_nest; if (_type == DEPV_ARRAY_ARRAY_GRAPH) { common_nest = Common_Nest(s1,s2); if ((common_nest == s1->Elements()) && Do_Loop_Is_Ivdep(s1->Top_nth(0))) { is_ivdep = TRUE; } for (INT i=0; i<common_nest; i++) { if (Do_Loop_Concurrent_Directive(s1->Bottom_nth(i))) { concurrent_directive = TRUE; } } } else { Is_True(s1->Elements() == s2->Elements(), ("Add_Edge called on a DEP graph with refs not in the same inner loop")); common_nest = s1->Elements(); if (Do_Loop_Concurrent_Directive(s1->Top_nth(0))) { concurrent_directive = TRUE; } if (Do_Loop_Is_Ivdep(s1->Top_nth(0))) { is_ivdep = TRUE; } } if (is_ivdep) { // ivdep should not apply to compiler generated arrays if (Compiler_Generated(addr1) || Compiler_Generated(addr2)) { is_ivdep = FALSE; } } if (is_ivdep && !Cray_Ivdep && !Liberal_Ivdep && !OPCODE_is_call(op1) && !OPCODE_is_call(op2) && Ref_Inner_Invar(addr1,s1->Top_nth(0)) && Ref_Inner_Invar(addr2,s1->Top_nth(0))) { is_ivdep = FALSE; // ivdep doesn't apply to "scalars" } UINT8 num_bad = Num_Bad(s1); if ((num_bad < common_nest) || (_type == DEP_ARRAY_GRAPH)) { MEM_POOL_Push(&DEP_local_pool); INT dv_dim; // how many dimensions of dvector to compute if (_type == DEPV_ARRAY_ARRAY_GRAPH) { dv_dim = common_nest-num_bad; // as many as possible } else { dv_dim = 1; // 1 } DEPV_LIST *tmp = CXX_NEW(DEPV_LIST(ref1,ref2,common_nest, dv_dim,use_bounds,&DEP_local_pool,s1,s2),&DEP_local_pool); if (!tmp->Is_Empty()) { VINDEX16 v1 = Get_Vertex(ref1); VINDEX16 v2 = Get_Vertex(ref2); if (v1 == 0 || v2 == 0) return FALSE; if (_type == DEPV_ARRAY_ARRAY_GRAPH) { DEPV_LIST *pos = CXX_NEW(DEPV_LIST(tmp->Num_Dim(),tmp->Num_Unused_Dim(), &DEP_local_pool), &DEP_local_pool); DEPV_LIST *neg = CXX_NEW(DEPV_LIST(tmp->Num_Dim(),tmp->Num_Unused_Dim(), &DEP_local_pool),&DEP_local_pool); if (ref1 == ref2) { tmp->Lex_Pos_Decompose(&DEP_local_pool,pos,neg,FALSE,FALSE); } else if (s1_lex_before_s2) { tmp->Lex_Pos_Decompose(&DEP_local_pool,pos,neg,TRUE,FALSE); } else { tmp->Lex_Pos_Decompose(&DEP_local_pool,pos,neg,FALSE,TRUE); } // Get rid of non-obvious dependences that inhibit parallelism if (concurrent_directive) { if (!OPCODE_is_call(op1) && !OPCODE_is_call(op2)) { if (!Ref_Inner_Invar(addr1,s1->Top_nth(0)) && !Ref_Inner_Invar(addr2,s2->Top_nth(0))) { for (INT i=0; i<dv_dim; i++) { if (Do_Loop_Concurrent_Directive(s1->Bottom_nth(i))) { pos->Eliminate_Non_Distance_Carried_By(i); neg->Eliminate_Non_Distance_Carried_By(i); } } } } } BOOL bad_ivdep = FALSE; if (is_ivdep) { if (Cray_Ivdep) { if (s1_lex_before_s2) { if (neg->Is_Inner_Non_Zero_Single_Distance()) bad_ivdep = TRUE; neg->Eliminate_Inner_Carried(); } else if (s2_lex_before_s1) { if (pos->Is_Inner_Non_Zero_Single_Distance()) bad_ivdep = TRUE; pos->Eliminate_Inner_Carried(); } else { if (neg->Is_Inner_Non_Zero_Single_Distance()) bad_ivdep = TRUE; if (pos->Is_Inner_Non_Zero_Single_Distance()) bad_ivdep = TRUE; pos->Eliminate_Inner_Carried(); neg->Eliminate_Inner_Carried(); } } else if (Liberal_Ivdep) { if ((ref1 != ref2) && Equiv_Memory(addr1,addr2)) bad_ivdep = TRUE; if (neg->Is_Inner_Non_Zero_Single_Distance()) bad_ivdep = TRUE; if (pos->Is_Inner_Non_Zero_Single_Distance()) bad_ivdep = TRUE; pos->Eliminate_Inner_Carried_Or_All_Equals(); neg->Eliminate_Inner_Carried_Or_All_Equals(); } else { if (neg->Is_Inner_Non_Zero_Single_Distance()) { bad_ivdep = TRUE; } if (pos->Is_Inner_Non_Zero_Single_Distance()) { bad_ivdep = TRUE; } pos->Eliminate_Inner_Carried(); neg->Eliminate_Inner_Carried(); } } if (bad_ivdep) { char error[120]; sprintf(error, "IVDEP where there is an obvious dependence to ref on line %d. Dependence ignored.", Srcpos_To_Line(Find_Line(ref2))); ErrMsgSrcpos(EC_LNO_Generic,Find_Line(ref1),error); } if (!pos->Is_Empty()) { DEPV_ARRAY *array = Create_DEPV_ARRAY(pos,_pool); if (!Add_Edge(v1, v2,array)) { MEM_POOL_Pop(&DEP_local_pool); return(FALSE); } } if (!neg->Is_Empty() && (ref2 != ref1)) { DEPV_ARRAY *array = Create_DEPV_ARRAY(neg,_pool); if (!Add_Edge(v2, v1,array)) { MEM_POOL_Pop(&DEP_local_pool); return(FALSE); } } } else { // a DEP_ARRAY_GRAPH DEP tmp_dep = tmp->Convert_To_Dep(); DEP *pos,*neg; if (ref1 == ref2) { DEP_Lex_Pos_Decompose(tmp_dep,&DEP_local_pool,&pos,&neg,0,0); } else if (s1_lex_before_s2) { DEP_Lex_Pos_Decompose(tmp_dep,&DEP_local_pool,&pos,&neg,TRUE,FALSE); } else { DEP_Lex_Pos_Decompose(tmp_dep,&DEP_local_pool,&pos,&neg,FALSE,TRUE); } BOOL bad_ivdep = FALSE; if (is_ivdep) { if (Cray_Ivdep) { if (DEP_IsDistance(tmp_dep)&&DEP_Distance(tmp_dep)) bad_ivdep=TRUE; if (s1_lex_before_s2) { neg = NULL; } else if (s2_lex_before_s1) { pos = NULL; } else { neg = pos = NULL; } } else if (Liberal_Ivdep) { if ((ref1 != ref2) && Equiv_Memory(addr1,addr2)) bad_ivdep = TRUE; if (DEP_IsDistance(tmp_dep)&&DEP_Distance(tmp_dep)) bad_ivdep=TRUE; neg = pos = NULL; } else { if (DEP_IsDistance(tmp_dep)&&DEP_Distance(tmp_dep)) bad_ivdep=TRUE; if (!neg || (DEP_Direction(*neg) == DIR_POS)) { neg = NULL; } else { *neg = DEP_SetDistance(0); } if (!pos || (DEP_Direction(*pos) == DIR_POS)) { pos = NULL; } else { *pos = DEP_SetDistance(0); } } } if (bad_ivdep) { char error[120]; sprintf(error, "IVDEP where there is an obvious dependence to ref on line %d. Dependence ignored.", Srcpos_To_Line(Find_Line(ref2))); ErrMsgSrcpos(EC_LNO_Generic,Find_Line(ref1),error); } if (pos) { if (!Add_Edge(v1, v2,*pos)) { MEM_POOL_Pop(&DEP_local_pool); return(FALSE); } } if (neg && (ref2 != ref1)) { if (!Add_Edge(v2, v1,*neg)) { MEM_POOL_Pop(&DEP_local_pool); return(FALSE); } } } } MEM_POOL_Pop(&DEP_local_pool); } return(TRUE); } // Compute the dependences and add two edges to the graph BOOL ARRAY_DIRECTED_GRAPH16::Add_Edge_Stars(WN *ls1, const DOLOOP_STACK *s1, WN *ls2, const DOLOOP_STACK *s2, BOOL s1_lex_before_s2, BOOL pos_only) { Is_True(OPCODE_is_load(WN_opcode(ls1)) || OPCODE_is_store(WN_opcode(ls1)) || OPCODE_is_call(WN_opcode(ls1)), ("bad ls1 in Add_Edge_Stars\n")); Is_True(OPCODE_is_load(WN_opcode(ls2)) || OPCODE_is_store(WN_opcode(ls2)) || OPCODE_is_call(WN_opcode(ls2)), ("bad ls2 in Add_Edge_Stars\n")); UINT8 common_nest; if (_type == DEPV_ARRAY_ARRAY_GRAPH) { common_nest = Common_Nest(s1,s2); } else { Is_True(s1->Elements() == s2->Elements(), ("Add_Edge called on a DEP graph with refs not in the same inner loop")); common_nest = s1->Elements(); } UINT8 num_bad = Num_Bad(s1); if (num_bad < common_nest) { MEM_POOL_Push(&DEP_local_pool); INT dv_dim; // how many dimensions of dvector to compute if (_type == DEPV_ARRAY_ARRAY_GRAPH) { dv_dim = common_nest-num_bad; // as many as possible } else { dv_dim = 1; // 1 } DEPV_ARRAY *dv_array = Create_DEPV_ARRAY(1, dv_dim, common_nest-dv_dim, &DEP_local_pool); for (INT ii = 0; ii < dv_dim; ii++) DEPV_Dep(dv_array->Depv(0), ii) = DEP_SetDirection(DIR_STAR); DEPV_LIST *tmp = CXX_NEW(DEPV_LIST(dv_array, &DEP_local_pool), &DEP_local_pool); VINDEX16 v1 = Get_Vertex(ls1); VINDEX16 v2 = Get_Vertex(ls2); if (v1 == 0 || v2 == 0) return FALSE; if (_type == DEPV_ARRAY_ARRAY_GRAPH) { DEPV_LIST *pos = CXX_NEW(DEPV_LIST(tmp->Num_Dim(),tmp->Num_Unused_Dim(), &DEP_local_pool), &DEP_local_pool); DEPV_LIST *neg = CXX_NEW(DEPV_LIST(tmp->Num_Dim(),tmp->Num_Unused_Dim(), &DEP_local_pool),&DEP_local_pool); if (ls1 == ls2) { tmp->Lex_Pos_Decompose(&DEP_local_pool,pos,neg,FALSE,FALSE); } else if (s1_lex_before_s2) { tmp->Lex_Pos_Decompose(&DEP_local_pool,pos,neg,TRUE,FALSE); } else { tmp->Lex_Pos_Decompose(&DEP_local_pool,pos,neg,FALSE,TRUE); } if (!pos->Is_Empty()) { DEPV_ARRAY *array = Create_DEPV_ARRAY(pos,_pool); if (!Add_Edge(v1, v2,array)) { MEM_POOL_Pop(&DEP_local_pool); return(FALSE); } } if (!pos_only && !neg->Is_Empty() && (ls2 != ls1)) { DEPV_ARRAY *array = Create_DEPV_ARRAY(neg,_pool); if (!Add_Edge(v2, v1,array)) { MEM_POOL_Pop(&DEP_local_pool); return(FALSE); } } } else { // a DEP_ARRAY_GRAPH DEP tmp_dep = tmp->Convert_To_Dep(); DEP *pos,*neg; if (ls1 == ls2) { DEP_Lex_Pos_Decompose(tmp_dep,&DEP_local_pool,&pos,&neg,0,0); } else if (s1_lex_before_s2) { DEP_Lex_Pos_Decompose(tmp_dep,&DEP_local_pool,&pos,&neg,TRUE,FALSE); } else { DEP_Lex_Pos_Decompose(tmp_dep,&DEP_local_pool,&pos,&neg,FALSE,TRUE); } if (pos) { if (!Add_Edge(v1, v2,*pos)) { MEM_POOL_Pop(&DEP_local_pool); return(FALSE); } } if (!pos_only && neg && (ls2 != ls1)) { if (!Add_Edge(v2, v1,*neg)) { MEM_POOL_Pop(&DEP_local_pool); return(FALSE); } } } MEM_POOL_Pop(&DEP_local_pool); } return(TRUE); } // Add an all equals dependence from ls1 to ls2 BOOL ARRAY_DIRECTED_GRAPH16::Add_Edge_Equals(WN *ls1, const DOLOOP_STACK *s1, WN *ls2, const DOLOOP_STACK *s2) { Is_True(OPCODE_is_load(WN_opcode(ls1)) || OPCODE_is_store(WN_opcode(ls1)) || OPCODE_is_call(WN_opcode(ls1)), ("bad ls1 in Add_Edge_Equals\n")); Is_True(OPCODE_is_load(WN_opcode(ls2)) || OPCODE_is_store(WN_opcode(ls2)) || OPCODE_is_call(WN_opcode(ls2)), ("bad ls2 in Add_Edge_Equals\n")); UINT8 common_nest; if (_type == DEPV_ARRAY_ARRAY_GRAPH) { common_nest = Common_Nest(s1,s2); } else { Is_True(s1->Elements() == s2->Elements(), ("Add_Edge called on a DEP graph with refs not in the same inner loop")); common_nest = s1->Elements(); } UINT8 num_bad = Num_Bad(s1); if (num_bad < common_nest) { MEM_POOL_Push(&DEP_local_pool); INT dv_dim; // how many dimensions of dvector to compute if (_type == DEPV_ARRAY_ARRAY_GRAPH) { dv_dim = common_nest-num_bad; // as many as possible } else { dv_dim = 1; // 1 } VINDEX16 v1 = Get_Vertex(ls1); VINDEX16 v2 = Get_Vertex(ls2); if (v1 == 0 || v2 == 0) return FALSE; if (_type == DEPV_ARRAY_ARRAY_GRAPH) { DEPV_ARRAY *dv_array = Create_DEPV_ARRAY(1, dv_dim, common_nest-dv_dim, _pool); for (INT ii = 0; ii < dv_dim; ii++) { DEPV_Dep(dv_array->Depv(0), ii) = DEP_SetDirection(DIR_EQ); } if (!Add_Edge(v1, v2,dv_array)) { MEM_POOL_Pop(&DEP_local_pool); return(FALSE); } } else { // a DEP_ARRAY_GRAPH DEP dep = DEP_SetDistance(0); if (!Add_Edge(v1, v2,dep)) { MEM_POOL_Pop(&DEP_local_pool); return(FALSE); } } } return(TRUE); } // Add all array reads and writes onto the appropriate list // We have one list for each base array (based on an arrays ST_Base pointer). // For efficiency reasons, we don't call dependence analysis on arrays with // different base pointers. They can never be aliased. If we can't figure // out the base pointer, we set it to zero. We call the dependence routines // on every zero-based array vrs every other array. // // Each reference is also annotated with the number of its statement // Statements are numbered so that if a comes lexically before b, // its statement number is less than b's (note that the converse // is not true due to IF nodes (i.e. we say all the statements in the // then clause come before all the statements in the else)) // Return 0 on error overflow // // Add all non-preg no loop_variable scalar writes/reads to the appropriate // SCALAR_STACK we use these to check for weird cross dependences // (scalar-array) INT ARRAY_DIRECTED_GRAPH16::Gather_References(WN *wn, REF_LIST_STACK *writes, REF_LIST_STACK *reads, DOLOOP_STACK *stack, SCALAR_STACK *scalar_writes, SCALAR_STACK *scalar_reads, CALL_STACK *calls, BOOL skip_bad) { WN *kid; if (OPCODE_is_stmt(WN_opcode(wn)) || OPCODE_is_scf(WN_opcode(wn))) { statement_number++; } if (WN_opcode(wn) == OPC_BLOCK) { kid = WN_first (wn); while (kid) { if (!Gather_References(kid,writes,reads,stack,scalar_writes, scalar_reads,calls,skip_bad)) return(0); kid = WN_next(kid); } return (1); } if (WN_opcode(wn) == OPC_DO_LOOP) { if (!skip_bad || Do_Loop_Is_Good(wn)) { DO_LOOP_INFO *dli = (DO_LOOP_INFO *) WN_MAP_Get(LNO_Info_Map,wn); dli->Has_Bad_Mem = FALSE; WN *body = WN_do_body(wn); for (INT kidno=0; kidno<WN_kid_count(wn); kidno++) { kid = WN_kid(wn,kidno); if (kid != body) { if (!Gather_References(kid,writes,reads,stack, scalar_writes,scalar_reads,calls,skip_bad)) { return(0); } } } stack->Push(wn); if (!Gather_References(body,writes,reads,stack,scalar_writes, scalar_reads,calls,skip_bad)) { return(0); } stack->Pop(); dli = (DO_LOOP_INFO *) WN_MAP_Get(LNO_Info_Map,wn); if (dli->Has_Bad_Mem && _type==DEPV_ARRAY_ARRAY_GRAPH) { LNO_Erase_Vertices_In_Loop (wn,this); } } } else if (OPCODE_is_call(WN_opcode(wn))) { VINDEX16 vindex = Get_Vertex(wn); if (!vindex) { vindex = Add_Vertex(wn); } if (!vindex) { DevWarn("Out of space for vertex?"); Set_Bad_Mem(wn); return 0; } DOLOOP_STACK *s = Copy_Doloop_Stack(stack,&LNO_local_pool); calls->Push(wn,statement_number,s, Do_Loop_Is_Concurrent_Call(s->Top_nth(0))); } else if (WN_opcode(wn) == OPC_IO) { Set_Bad_Mem(wn); return 1; } else if (OPCODE_is_load(WN_opcode(wn))) { OPCODE opcode = WN_opcode(wn); if (OPCODE_has_1ty(opcode) && TY_is_volatile(WN_ty(wn))) { Set_Bad_Mem(wn); return 1; } else if (OPCODE_has_2ty(opcode)&&(TY_is_volatile(WN_ty(wn)) || TY_is_volatile(WN_load_addr_ty(wn)))) { Set_Bad_Mem(wn); return 1; } if ((WN_kid_count(wn) == 1)) { if (stack->Elements()>0) { WN *array = WN_kid0(wn); if (WN_operator(array) == OPR_ADD) { // arrays of structures OPERATOR kid0 = WN_operator(WN_kid0(array)); OPERATOR kid1 = WN_operator(WN_kid1(array)); if ((kid0 == OPR_ARRAY) && (kid1 == OPR_INTCONST)) { array = WN_kid0(array); } else if ((kid1 == OPR_ARRAY) && (kid0 == OPR_INTCONST)) { array = WN_kid1(array); } else { Set_Bad_Mem(wn); return 1; } } else if (WN_operator(array) != OPR_ARRAY) { Set_Bad_Mem(wn); return 1; } DOLOOP_STACK *s = Copy_Doloop_Stack(stack,&LNO_local_pool); VINDEX16 vindex = Get_Vertex(wn); if (!vindex) { vindex = Add_Vertex(wn); } if (!vindex) { DevWarn("Out of space for vertex?"); if (WN_operator(wn) != OPR_LDID) Set_Bad_Mem(wn); return 0; } WN *base = WN_array_base(array); ST *st_base=Get_ST_Base(base); INT i; for (i=0;i<reads->Elements()&& !(reads->Bottom_nth(i)->ST_Base==st_base); i++); if (i==reads->Elements()) { REFERENCE_LIST *rl = CXX_NEW(REFERENCE_LIST(st_base, wn),&LNO_local_pool); reads->Push(rl); } reads->Bottom_nth(i)->Append(CXX_NEW(REFERENCE_NODE(wn,s, statement_number), &LNO_local_pool)); } else { if ((WN_operator(wn) != OPR_LDID) && !Is_Loop_Invariant_Indir(wn)) Set_Bad_Mem(wn); VINDEX16 vindex = Get_Vertex(wn); if (vindex) Delete_Vertex(vindex); } } else if (WN_operator(wn) == OPR_LDID) { if (ST_class(WN_st(wn)) != CLASS_PREG && stack->Elements()>0) { scalar_reads->Add_Scalar(wn,statement_number); } } else { Set_Bad_Mem(wn); } } else if (OPCODE_is_store(WN_opcode(wn))) { TY_IDX ty = WN_ty(wn); if (TY_is_volatile(ty)) { Set_Bad_Mem(wn); return 1; } else if ((WN_operator(wn) != OPR_STID) && TY_is_volatile(TY_pointed(WN_ty(wn)))) { Set_Bad_Mem(wn); return 1; } if (WN_kid_count(wn) == 2) { DOLOOP_STACK *s = Copy_Doloop_Stack(stack,&LNO_local_pool); VINDEX16 vindex = Get_Vertex(wn); if (stack->Elements() > 0) { WN *array = WN_kid1(wn); if (WN_operator(array) == OPR_ADD) { // arrays of structures OPERATOR kid0 = WN_operator(WN_kid0(array)); OPERATOR kid1 = WN_operator(WN_kid1(array)); if ((kid0 == OPR_ARRAY) && (kid1 == OPR_INTCONST)) { array = WN_kid0(array); } else if ((kid1 == OPR_ARRAY) && (kid0 == OPR_INTCONST)) { array = WN_kid1(array); } else { Set_Bad_Mem(wn); return 1; } } else if (WN_operator(array) != OPR_ARRAY) { Set_Bad_Mem(wn); return 1; } if (!vindex) { vindex = Add_Vertex(wn); } if (!vindex) { DevWarn("Out of space for vertex?"); if (WN_operator(wn) != OPR_STID) Set_Bad_Mem(wn); return 0; } WN *base = WN_array_base(array); ST *st_base=Get_ST_Base(base); INT i; for (i=0;i<writes->Elements() && !(writes->Bottom_nth(i)->ST_Base==st_base); i++); if (i==writes->Elements()) { REFERENCE_LIST *rl = CXX_NEW(REFERENCE_LIST(st_base,wn),&LNO_local_pool); writes->Push(rl); } writes->Bottom_nth(i)->Append(CXX_NEW(REFERENCE_NODE(wn,s, statement_number), &LNO_local_pool)); } else { if (WN_operator(wn) != OPR_STID) Set_Bad_Mem(wn); VINDEX16 vindex = Get_Vertex(wn); if (vindex) Delete_Vertex(vindex); } } else if (WN_operator(wn) == OPR_STID) { if (ST_class(WN_st(wn)) != CLASS_PREG && stack->Elements()>0) { scalar_writes->Add_Scalar(wn,statement_number); } } else { Set_Bad_Mem(wn); } } else if (WN_operator(wn) == OPR_ARRAY) { WN *ancestor = LWN_Get_Parent(wn); while (ancestor && !OPCODE_is_store(WN_opcode(ancestor)) && !OPCODE_is_load(WN_opcode(ancestor))) { if (WN_operator(ancestor) == OPR_PARM) { if (stack->Elements() > 0 && !Do_Loop_Is_Concurrent_Call(stack->Top_nth(0)) && !Has_Call_Info(LWN_Get_Parent(ancestor))) { Set_Bad_Mem(wn); } } ancestor = LWN_Get_Parent(ancestor); } } if (WN_opcode(wn) != OPC_DO_LOOP) { for (INT kidno=0; kidno<WN_kid_count(wn); kidno++) { kid = WN_kid(wn,kidno); if (!Gather_References(kid,writes,reads,stack, scalar_writes,scalar_reads,calls,skip_bad)) { return(0); } } } return(1); } // what is the Do loop enclosing this node // This assumes that wn is enclosed in a DO loop static WN *Get_Do(WN *wn) { while (wn && WN_opcode(wn) != OPC_DO_LOOP) { wn = LWN_Get_Parent(wn); } FmtAssert(wn, ("Missing enclosing do loop")); return (wn); } // Convert the DEPV_ARRAY into a DEP graph // Return 0 on error INT ARRAY_DIRECTED_GRAPH16::Build(ARRAY_DIRECTED_GRAPH16 *da_graph) { MEM_POOL_Push(&LNO_local_pool); Is_True((_type==DEP_ARRAY_GRAPH) && (da_graph->_type==DEPV_ARRAY_ARRAY_GRAPH), ("Build called on wrong types of graph")); // First copy the inner loop vertices // Don't copy ldids/stids, they appear in the DEPV_ARRAY graph but // not in the DEP graph // Since we're not copying them, we're setting Bad_Mem on loops that // have them for (VINDEX16 v=da_graph->Get_Vertex(); v; v=da_graph->Get_Next_Vertex(v)) { WN *wn = da_graph->Get_Wn(v); WN *do_wn = Get_Do(wn); if (Do_Loop_Is_Inner(do_wn) && !Do_Loop_Has_Gotos(do_wn)) { OPERATOR oper = WN_operator(wn); if ((oper != OPR_LDID) && (oper != OPR_STID) && (oper != OPR_CALL)) { if (!Add_Vertex(da_graph->Get_Wn(v))) { return(0); } } else { Set_Bad_Mem(wn); } } } // now the edges for (VINDEX16 source_v=da_graph->Get_Vertex(); source_v; source_v=da_graph->Get_Next_Vertex(source_v)) { EINDEX16 e = da_graph->_v[source_v].Get_Out_Edge(); WN *source_wn = da_graph->Get_Wn(source_v); WN *inner_do = Get_Do(source_wn); if (Do_Loop_Is_Inner(inner_do) && !Do_Loop_Has_Gotos(inner_do)) { OPERATOR source_oper = WN_operator(source_wn); if ((source_oper != OPR_LDID)&&(source_oper != OPR_STID) && (source_oper != OPR_CALL)) { while (e) { DEPV_ARRAY *da = da_graph->_e[e].Depv_Array; // Is this an edge to a vertex in the same inner loop VINDEX16 sink_v = da_graph->_e[e].Get_Sink(); WN *sink_wn = da_graph->Get_Wn(sink_v); WN *inner_do2 = Get_Do(sink_wn); if (inner_do == inner_do2) { OPERATOR sink_oper = WN_operator(sink_wn); if ((sink_oper != OPR_LDID) && (sink_oper != OPR_STID) && (sink_oper != OPR_CALL)) { // find the reverse edge, we do two edges at a time // because dividing by step might cause us switch edges DEPV_ARRAY *da2=NULL; DEP *dep=NULL; DEP *dep2 = NULL; EINDEX16 e2 = da_graph->Get_Edge(sink_v,source_v); if (e2 && (e < e2)) { // make sure we only get each edge once dep = da->Shorten_To_Dep(&LNO_local_pool); da2 = da_graph->_e[e2].Depv_Array; dep2 = da2->Shorten_To_Dep(&LNO_local_pool); } else if (e == e2) { dep = da->Shorten_To_Dep(&LNO_local_pool); } else if (!e2) { dep = da->Shorten_To_Dep(&LNO_local_pool); } VINDEX16 source_v2 = Get_Vertex(source_wn); // the corresponding // vertex in this graph WN *sink_wn = da_graph->Get_Wn(sink_v); VINDEX16 sink_v2 = Get_Vertex(sink_wn); if (dep && !Add_Edge(source_v2,sink_v2,*dep)) { MEM_POOL_Pop(&LNO_local_pool); return(0); } if (dep2 && !Add_Edge(sink_v2,source_v2,*dep2)) { MEM_POOL_Pop(&LNO_local_pool); return(0); } } } e = da_graph->_e[e].Get_Next_Out_Edge(); } } } } MEM_POOL_Pop(&LNO_local_pool); Add_Must(); return(1); } INT ARRAY_DIRECTED_GRAPH16::Add_Deps_To_Copy_Block(WN *orig, WN *copy, BOOL keep_internal_edge) { Is_True(_type==DEPV_ARRAY_ARRAY_GRAPH, ("Add_Deps_To_Copy_Block called on a non-DEPV_ARRAY graph")); INT result; MEM_POOL_Push(&LNO_local_pool); { // a hash table to map old vertices to the corresponding new ones // we could use the mapping mechanism, but it's a waste since this // is purely local info HASH_TABLE<VINDEX16,VINDEX16> hash_table(MIN(Get_Vertex_Count(),512), &LNO_local_pool); result = Add_Deps_To_Copy_Block_V(orig, copy,&hash_table); if (result) result=Add_Deps_To_Copy_Block_E(orig,copy,&hash_table,keep_internal_edge); } MEM_POOL_Pop(&LNO_local_pool); return result; } // Add the new vertices to the graph // Attacth the new vertices to the wn using _map // Enter the mapping from old vertices to new into the hash table // Return 0 on error INT ARRAY_DIRECTED_GRAPH16::Add_Deps_To_Copy_Block_V(WN *orig, WN *copy, HASH_TABLE<VINDEX16,VINDEX16> *hash_table) { if (orig) { if (OPCODE_is_load(WN_opcode(orig)) || OPCODE_is_store(WN_opcode(orig)) || OPCODE_is_call(WN_opcode(orig))) { VINDEX16 origv = Get_Vertex(orig); if (origv) { VINDEX16 newv = Add_Vertex(copy); if (!newv) return(0); hash_table->Enter(origv, newv); } } if (WN_opcode(orig) == OPC_BLOCK) { WN *orig_kid = WN_first (orig); WN *copy_kid = WN_first (copy); while (orig_kid) { if (!Add_Deps_To_Copy_Block_V(orig_kid, copy_kid,hash_table)) { return 0; } orig_kid = WN_next(orig_kid); copy_kid = WN_next(copy_kid); } } else { for (INT kidno=0; kidno<WN_kid_count(orig); kidno++) { if (!Add_Deps_To_Copy_Block_V(WN_kid(orig,kidno), WN_kid(copy,kidno), hash_table)) { return 0; } } } } return 1; } // Add the edges to the graph // For each vertex V in the region // Check all its out edges // If an out edge is to a vertex in the region, add an edge to the copy // If an out edge is to a vertex outside of the region, add edge from // copy of source to orig sink // Check all its in edges // If an in edge is to a vertex in the region, do nothing (caught above) // If an in edge is to a vertex outside the region, add an edge from orig // return 0 on error INT ARRAY_DIRECTED_GRAPH16::Add_Deps_To_Copy_Block_E(WN *orig, WN *copy, HASH_TABLE<VINDEX16,VINDEX16> *hash_table, BOOL keep_internal_edge) { VINDEX16 newv, new_sinkv; if (orig) { if (OPCODE_is_load(WN_opcode(orig)) || OPCODE_is_store(WN_opcode(orig)) || OPCODE_is_call(WN_opcode(orig))) { VINDEX16 origv = Get_Vertex(orig); // get all the edges from this vertex if (origv) { newv = hash_table->Find(origv); // newv is the corresponding vertex, now find all the edges EINDEX16 edge = Get_Out_Edge(origv); while (edge) { VINDEX16 orig_sinkv = Get_Sink(edge); VINDEX16 hash_element = hash_table->Find( orig_sinkv); if (hash_element) { // the sink is in the copy region if (keep_internal_edge) { new_sinkv = (VINDEX16) (UINT) hash_element; if (!Add_Edge(newv,new_sinkv, Create_DEPV_ARRAY(Depv_Array(edge),_pool))) { return 0; } } } else { new_sinkv = orig_sinkv; if (!Add_Edge(newv,new_sinkv, Create_DEPV_ARRAY(Depv_Array(edge),_pool))) { return 0; } } edge = Get_Next_Out_Edge(edge); } edge = Get_In_Edge(origv); while (edge) { VINDEX16 orig_sourcev = Get_Source(edge); VINDEX16 hash_element = hash_table->Find(orig_sourcev); if (!hash_element) { // the sink is not in the copy region if (!Add_Edge(orig_sourcev,newv, Create_DEPV_ARRAY(Depv_Array(edge),_pool))) { return 0; } } edge = Get_Next_In_Edge(edge); } } } if (WN_opcode(orig) == OPC_BLOCK) { WN *orig_kid = WN_first (orig); WN *copy_kid = WN_first (copy); while (orig_kid) { if (!Add_Deps_To_Copy_Block_E(orig_kid,copy_kid, hash_table, keep_internal_edge)) { return 0; } orig_kid = WN_next(orig_kid); copy_kid = WN_next(copy_kid); } } else { for (INT kidno=0; kidno<WN_kid_count(orig); kidno++) { if (!Add_Deps_To_Copy_Block_E(WN_kid(orig,kidno), WN_kid(copy,kidno), hash_table, keep_internal_edge)) { return 0; } } } } return 1; } // Copy a DOLOOP_STACK static DOLOOP_STACK *Copy_Doloop_Stack(DOLOOP_STACK *orig,MEM_POOL *pool) { DOLOOP_STACK *copy = CXX_NEW(DOLOOP_STACK(pool),pool); INT elements = orig->Elements(); for (INT i=0; i<elements; i++) { copy->Push(orig->Bottom_nth(i)); } return(copy); } static INT Common_Nest(const DOLOOP_STACK *s1, const DOLOOP_STACK *s2) { INT i; for (i=0; i<MIN(s1->Elements(),s2->Elements()); i++) { if (s1->Bottom_nth(i) != s2->Bottom_nth(i)) return(i); } return(i); } // how many of the outer loops are bad static INT Num_Bad(const DOLOOP_STACK *s1) { INT i; for (i=0; i<s1->Elements() && !Do_Loop_Is_Good(s1->Bottom_nth(i)); i++); return(i); } static INT lex_count; // Fix up the dependence graph after loop unrolling. // First, // Add the new vertices to the graph // Attach the new vertices to the wn using _map // Enter the mapping from old vertices to new into the hash table // Then get the edges right // Each edge in to or out of the region gets copied // For each edge within region // if (d+n) % u == 0 repace distance component d = (d+n)/u // otherwise get rid of the edge // where n is the "copy number" // Return 0 on error INT ARRAY_DIRECTED_GRAPH16::Unrolled_Dependences_Update( WN** bodies, UINT u, UINT loopno) { Is_True(_type==DEPV_ARRAY_ARRAY_GRAPH, ("Unrolled_Dependences_Update called on a non-DEPV_ARRAY graph")); INT result; MEM_POOL_Push(&LNO_local_pool); // a hash table to map old vertices to arrays of the corresponding new ones // and a count giving the lexical position of the original vertex // // we could use the mapping mechanism, but it's a waste since this // is purely local info typedef HASH_TABLE<VINDEX16,VINDEX16P_LEX_COUNT *> HTABLE_TYPE; HTABLE_TYPE *hash_table = CXX_NEW(HTABLE_TYPE(MIN(Get_Vertex_Count(),512),&LNO_local_pool), &LNO_local_pool); // a list of all the original vertices in bodies[0] VINDEX16_STACK *orig_vertices = CXX_NEW(VINDEX16_STACK(&LNO_local_pool),&LNO_local_pool); lex_count=0; result = Unrolled_Dependences_Update_V(bodies,u,hash_table,orig_vertices); if (!result) { CXX_DELETE(hash_table, &LNO_local_pool); MEM_POOL_Pop(&LNO_local_pool); return(0); } result = Unrolled_Dependences_Update_E(u,loopno,hash_table,orig_vertices); CXX_DELETE(hash_table, &LNO_local_pool); CXX_DELETE(orig_vertices, &LNO_local_pool); MEM_POOL_Pop(&LNO_local_pool); return(result); } // Add the new vertices to the graph // Attacth the new vertices to the wn using _map // Enter the mapping from old vertices to new into the hash table // Return 0 on error INT ARRAY_DIRECTED_GRAPH16::Unrolled_Dependences_Update_V(WN **bodies, UINT u, HASH_TABLE<VINDEX16,VINDEX16P_LEX_COUNT *> *hash_table, VINDEX16_STACK *orig_vertices) { if (bodies[0]) { if (WN_opcode(bodies[0]) == OPC_BLOCK) { WN **new_bodies = CXX_NEW_ARRAY(WN *,u,&LNO_local_pool); for (INT i=0; i<u; i++) { new_bodies[i] = WN_first(bodies[i]); } while (new_bodies[0]) { if (!Unrolled_Dependences_Update_V(new_bodies, u,hash_table, orig_vertices)) { return 0; } for (INT i=0; i<u; i++) { new_bodies[i] = WN_next(new_bodies[i]); } } } else if (WN_kid_count(bodies[0])) { WN **new_bodies = CXX_NEW_ARRAY(WN *,u,&LNO_local_pool); for (INT kidno=0; kidno<WN_kid_count(bodies[0]); kidno++) { for (INT i=0; i<u; i++) { new_bodies[i] = WN_kid(bodies[i],kidno); } if (!Unrolled_Dependences_Update_V(new_bodies, u,hash_table, orig_vertices)) { return 0; } } } if (OPCODE_is_load(WN_opcode(bodies[0])) || OPCODE_is_store(WN_opcode(bodies[0])) || OPCODE_is_call(WN_opcode(bodies[0]))) { VINDEX16 origv = Get_Vertex(bodies[0]); if (origv) { orig_vertices->Push(origv); VINDEX16 *newv = CXX_NEW_ARRAY(VINDEX16,u,&LNO_local_pool); newv[0] = origv; for (INT i=1; i<u; i++) { newv[i] = Add_Vertex(bodies[i]); if (!newv[i]) return(0); } VINDEX16P_LEX_COUNT *vlp = CXX_NEW(VINDEX16P_LEX_COUNT(newv,lex_count), &LNO_local_pool); hash_table->Enter(origv,vlp); } lex_count++; } } return 1; } // a hash table of pairs of vertices class VERTEX_PAIR { public: VINDEX16 _v1; VINDEX16 _v2; VERTEX_PAIR(VINDEX16 v1, VINDEX16 v2) { _v1=v1; _v2=v2; }; }; struct VERTEX_PAIR_HASH { INT operator() ( VERTEX_PAIR vp) const { return vp._v1 + 64*1024*vp._v2; } }; struct VERTEX_PAIR_EQ { BOOL operator() ( VERTEX_PAIR vp1, VERTEX_PAIR vp2) const { return vp1._v1 == vp2._v1 && vp1._v2 == vp2._v2; } }; typedef USER_HASH_TABLE<VERTEX_PAIR,BOOL,VERTEX_PAIR_HASH,VERTEX_PAIR_EQ> PAIR_TABLE; // get the edges right for updating after unrolling // Each edge in to or out of the region gets copied // For each edge within region repace distance component d = (d+n)/u // where n is the "copy number" // Return 0 on error INT ARRAY_DIRECTED_GRAPH16::Unrolled_Dependences_Update_E(UINT u, UINT loopno, HASH_TABLE<VINDEX16,VINDEX16P_LEX_COUNT *> *hash_table, VINDEX16_STACK *orig_vertices) { // first do all the external edges INT v; for (v=0; v<orig_vertices->Elements(); v++) { VINDEX16 origv = orig_vertices->Bottom_nth(v); // get all the edges from this vertex VINDEX16 *newv = hash_table->Find(origv)->_vp; // newv are the corresponding vertices, now find all the edges EINDEX16 edge = Get_Out_Edge(origv); while (edge) { VINDEX16 orig_sinkv = Get_Sink(edge); VINDEX16P_LEX_COUNT *hash_element = hash_table->Find(orig_sinkv); if (!hash_element) { // the sink goes out of the region for (INT i=1; i<u; i++) { if (!Add_Edge(newv[i],orig_sinkv, Create_DEPV_ARRAY(Depv_Array(edge),_pool))) { return 0; } } } edge = Get_Next_Out_Edge(edge); } edge = Get_In_Edge(origv); while (edge) { VINDEX16 orig_sourcev = Get_Source(edge); VINDEX16P_LEX_COUNT *hash_element = hash_table->Find(orig_sourcev); if (!hash_element) { // the source comes from out of the region for (INT i=1; i<u; i++) { if (!Add_Edge(orig_sourcev,newv[i], Create_DEPV_ARRAY(Depv_Array(edge),_pool))) { return 0; } } } edge = Get_Next_In_Edge(edge); } } // now the internal edges // pair_table is the set of pairs that we've processeed PAIR_TABLE *pair_table = CXX_NEW(PAIR_TABLE(200,&LNO_local_pool), &LNO_local_pool); for (v=0; v<orig_vertices->Elements(); v++) { VINDEX16 origv = orig_vertices->Bottom_nth(v); VINDEX16P_LEX_COUNT *vlc = hash_table->Find(origv); VINDEX16 *newv = vlc->_vp; INT lex_count = vlc->_lex_count; EINDEX16 edge = Get_Out_Edge(origv); while (edge) { EINDEX16 next_out = Get_Next_Out_Edge(edge); VINDEX16 orig_sinkv = Get_Sink(edge); VINDEX16P_LEX_COUNT *vlc_sink = hash_table->Find(orig_sinkv); if (vlc_sink) { // the sink is in region VINDEX16 *new_sinkv = vlc_sink->_vp; INT sink_lex_count = vlc_sink->_lex_count; // we do both edges ((origv,orig_sinkv) and (orig_sinkv,origv)) // at a time so want to make sure we only do them once if ((origv <= orig_sinkv) || (!Get_Edge(orig_sinkv,origv) && !pair_table->Find(VERTEX_PAIR(origv,orig_sinkv)))) { if (origv < orig_sinkv) { pair_table->Enter(VERTEX_PAIR(orig_sinkv,origv),1); } if (!Unrolled_Dependences_Update_E( newv,new_sinkv,edge,Get_Edge(orig_sinkv,origv),u,loopno, lex_count,sink_lex_count)) { return 0; } } } edge = next_out; } } return(1); } // Fix one internal edge // sources is the array of new source vertices (element 0 is the orig) // sinks is the array of new sink vertices (element 0 is the orig) // fedge is the edge from sources[0] to sinks[0] // bedge is the edge from sinks[0] to sources[0] // u is the unrolling factor // loop number is the number of the loop being unrolled INT ARRAY_DIRECTED_GRAPH16::Unrolled_Dependences_Update_E(VINDEX16 *sources, VINDEX16 *sinks, EINDEX16 fedge, EINDEX16 bedge, UINT u, UINT loopno, INT lex_count, INT sink_lex_count) { DEPV_ARRAY *farray = Depv_Array(fedge); DEPV_ARRAY *barray = 0; if (bedge) barray=Depv_Array(bedge); DEPV_LIST *fl = CXX_NEW(DEPV_LIST(farray,&LNO_local_pool),&LNO_local_pool); DEPV_LIST *bl; if (bedge) { bl=CXX_NEW(DEPV_LIST(barray,&LNO_local_pool),&LNO_local_pool); } else { bl=CXX_NEW(DEPV_LIST(fl->Num_Dim(),fl->Num_Unused_Dim(),&LNO_local_pool), &LNO_local_pool); } DEPV_LIST *dl = Lex_Pos_Compose(&LNO_local_pool,fl,bl); if (farray == barray) { Is_True(fedge==bedge, ("same array different edge in Unrolled_Dependences_Update_E")); Delete_DEPV_ARRAY(farray,_pool); Remove_Edge(fedge); } else { Delete_DEPV_ARRAY(farray,_pool); Delete_DEPV_ARRAY(barray,_pool); Remove_Edge(fedge); if (bedge) Remove_Edge(bedge); } // compare source of every copy vrs sink of every copy // unless source and sink are the same reference in which case // only compare half (reverse edges will get the other half) for (INT c1=0; c1<u; c1++) { for (INT c2=0; c2<(sources[0]==sinks[0] ? (c1+1) : u); c2++) { // create the edge btwn copies c1 and c2 INT diff = c1-c2; DEPV_LIST *result = CXX_NEW(DEPV_LIST(dl->Num_Dim(),dl->Num_Unused_Dim(), &LNO_local_pool), &LNO_local_pool); UINT ln_pos = loopno-dl->Num_Unused_Dim(); DEPV_ITER iter(dl); for (DEPV_NODE *node=iter.First(); !iter.Is_Empty();node=iter.Next()) { DEPV *Depv = node->Depv; DEP dep = DEPV_Dep(Depv,ln_pos); if (DEP_IsDistance(dep)) { INT dist = DEP_Distance(dep); if ((abs(dist+diff) % u) == 0) { DEPV *r = DEPV_Copy(&LNO_local_pool,Depv,dl->Num_Dim()); DEPV_Dep(r,ln_pos) = DEP_SetDistance((dist+diff)/u); result->Append(CXX_NEW(DEPV_NODE(r), &LNO_local_pool)); } } else { DEPV *r = DEPV_Copy(&LNO_local_pool,Depv,dl->Num_Dim()); if ((diff != 0) && DEP_Direction(dep) != DIR_STAR) { if (DEP_Direction(dep) == DIR_POSNEG) { DEPV_Dep(r,ln_pos) = DEP_SetDirection(DIR_STAR); } else if (DEP_Direction(dep) == DIR_POS) { if (diff < 0) DEPV_Dep(r,ln_pos) = DEP_SetDirection(DIR_POSEQ); } else if (DEP_Direction(dep) == DIR_NEG) { if (diff > 0) DEPV_Dep(r,ln_pos) = DEP_SetDirection(DIR_NEGEQ); } else if (DEP_Direction(dep) == DIR_NEGEQ) { if (diff > 0) DEPV_Dep(r,ln_pos) = DEP_SetDirection(DIR_STAR); if (diff < 0) DEPV_Dep(r,ln_pos) = DEP_SetDirection(DIR_NEG); } else if (DEP_Direction(dep) == DIR_POSEQ) { if (diff < 0) DEPV_Dep(r,ln_pos) = DEP_SetDirection(DIR_STAR); if (diff > 0) DEPV_Dep(r,ln_pos) = DEP_SetDirection(DIR_POS); } } result->Append(CXX_NEW(DEPV_NODE(r), &LNO_local_pool)); } } DEPV_LIST *pos = CXX_NEW(DEPV_LIST(result->Num_Dim(), result->Num_Unused_Dim(),&LNO_local_pool), &LNO_local_pool); DEPV_LIST *neg = CXX_NEW(DEPV_LIST(result->Num_Dim(), result->Num_Unused_Dim(),&LNO_local_pool),&LNO_local_pool); if (c1 < c2) { result->Lex_Pos_Decompose(&LNO_local_pool,pos,neg,TRUE,FALSE); } else if (c2 < c1) { result->Lex_Pos_Decompose(&LNO_local_pool,pos,neg,FALSE,TRUE); } else { result->Lex_Pos_Decompose(&LNO_local_pool,pos,neg, lex_count < sink_lex_count,sink_lex_count < lex_count); } if (!pos->Is_Empty()) { DEPV_ARRAY *array = Create_DEPV_ARRAY(pos,_pool); if (!Add_Edge(sources[c1],sinks[c2],array)) { return(0); } } if ((sources[c1] != sinks[c2]) && !neg->Is_Empty()) { DEPV_ARRAY *array = Create_DEPV_ARRAY(neg,_pool); if (!Add_Edge(sinks[c2],sources[c1],array)) { return(0); } } } } return 1; } void REFERENCE_LIST::Print(FILE *fp) { REFERENCE_ITER iter(this); REFERENCE_NODE *first = iter.First(); for (REFERENCE_NODE *node=first; !iter.Is_Empty(); node = iter.Next()) { node->Print(fp); } fprintf(fp,"\n"); } // Fix dependences in array graph after loop fission // // Given a reference inside a fissioned loop // All its dependences to references outside the region of fission don't change // All its dependences to references inside the same post-fission loop // don't change // All its dependences to references inside a different post-fission loop // get choped so that the number of dimensions equal the new common_nesting // (some edges might get erased if there are no longer any common good loops) // void ARRAY_DIRECTED_GRAPH16::Fission_Dep_Update(WN* in_loop, UINT32 total_loops) { Is_True(_type==DEPV_ARRAY_ARRAY_GRAPH, ("Fission_Dep_Update called on a non-DEPV_ARRAY graph")); UINT depth = Do_Loop_Depth(in_loop); for (INT i=0; i<total_loops; i++) { Is_True(WN_opcode(in_loop) == OPC_DO_LOOP, ("Non do loop in Fission_Dep_Update")); Fission_Dep_Update_R(WN_do_body(in_loop),in_loop,depth); in_loop = WN_next(in_loop); } } // Update one loop void ARRAY_DIRECTED_GRAPH16::Fission_Dep_Update_R(WN *wn, WN *in_loop, UINT depth) { OPCODE opcode = WN_opcode(wn); VINDEX16 v; if (opcode == OPC_BLOCK) { WN *kid = WN_first (wn); while (kid) { Fission_Dep_Update_R(kid,in_loop,depth); kid = WN_next(kid); } return; } if ((v=Get_Vertex(wn)) != 0) { Fission_Dep_Update_V(v,in_loop,depth); } for (INT kidno=0; kidno<WN_kid_count(wn); kidno++) { WN *kid = WN_kid(wn,kidno); Fission_Dep_Update_R(kid,in_loop,depth); } } // Find the ancestor of wn1 that is a child of wn2, return NULL if none // return wn1 if wn1 is a child of wn2 static WN *Find_Ancestor_WN1_Child_WN2(WN *wn1, WN *wn2) { while (wn1) { WN *parent = LWN_Get_Parent(wn1); if (parent == wn2) return(wn1); wn1 = parent; } return NULL; } // Update one reference in the loop void ARRAY_DIRECTED_GRAPH16::Fission_Dep_Update_V(VINDEX16 v,WN *in_loop, UINT depth) { //WN *Find_Ancestor_WN1_Child_WN2(WN *wn1, WN *wn2); EINDEX16 e = _v[v].Get_Out_Edge(); while (e) { EINDEX16 next_e = _e[e].Get_Next_Out_Edge(); WN *sink = _v[_e[e].Get_Sink()].Wn; WN *sink_loop = Find_Ancestor_WN1_Child_WN2(sink,LWN_Get_Parent(in_loop)); if (sink_loop && (sink_loop != in_loop)) { // the sink is in a diff copy INT unused = _e[e].Depv_Array->Num_Unused_Dim(); if (unused >= depth) { Delete_Array_Edge(e); } else { if (_e[e].Depv_Array->Num_Dim() > depth-unused) { // its too big DEPV_ARRAY *da = _e[e].Depv_Array->Shorten(depth-unused,_pool); Delete_DEPV_ARRAY(_e[e].Depv_Array,_pool); _e[e].Depv_Array = da; } } } e = next_e; } } // // Fix dependences in statement dependence graph after loop fission // // 1. Copy all the dependences from "do loop1" to the other copies // ie given // s0: // do i1 // do i2 // copy all the dependences (s0 <-> do i1) to (s0 <->do i2) // This is a conservative approximation. It is possible that s0 is only // dependent on the references in one of the do loops. Nonetheless, it // is impossible for us to know this since the statement dependence graph // doesn't have the dependences between s0 and the things inside a do // loop (it only has dependences to things in the same level). This // conservatism will never make a difference given our uses of fission, // but it might if we change our algorithm at some point. // 2. Given a reference inside a fissioned loop // All its dependeces to references inside the same post-fission loop remain // All its dependences to references inside a different post-fission loop // get moved to the dependence between the corresponding do loops // the level is chopped to the minimum(old_level, depth in_loop) // unless the corresponding do loops are the outer good do loops, // in which case we just get rid of the edge // Return 0 on overflow // fission_depth is the number of perfectly nested loops fissioned together INT ARRAY_DIRECTED_GRAPH16::Fission_Dep_Update(WN* in_loop, UINT32 total_loops, UINT fission_depth) { Is_True(_type==LEVEL_ARRAY_GRAPH, ("Fission_Dep_Update called on a non-level graph")); MEM_POOL_Push(&LNO_local_pool); BOOL outer_good_do = TRUE; WN *tmp = LWN_Get_Parent(in_loop); while (tmp && (WN_opcode(tmp) != OPC_DO_LOOP)) tmp = LWN_Get_Parent(tmp); if (tmp && Do_Loop_Is_Good(tmp)) outer_good_do = FALSE; VINDEX16 *do_loop_vertices = CXX_NEW_ARRAY(VINDEX16,total_loops,&LNO_local_pool); tmp = in_loop; INT i; for (i=0; i<total_loops; i++) { do_loop_vertices[i] = Get_Vertex(tmp); tmp = WN_next(tmp); } for (INT j=0; j<fission_depth; j++) { if (!Copy_Do_Loop_Deps(do_loop_vertices,total_loops)) { MEM_POOL_Pop(&LNO_local_pool); return 0; } if (j<fission_depth-1) for (INT i=0; i<total_loops; i++) { WN* wn=Get_Only_Loop_Inside(Get_Wn(do_loop_vertices[i]),FALSE); do_loop_vertices[i] = Get_Vertex(wn); } } UINT depth = Do_Loop_Depth(in_loop); for (i=0; i<total_loops; i++) { Is_True(WN_opcode(in_loop) == OPC_DO_LOOP, ("Non do loop in Fission_Dep_Update")); if (!Fission_Dep_Update_R(in_loop,fission_depth,depth,outer_good_do)) { return(0); } in_loop = WN_next(in_loop); } MEM_POOL_Pop(&LNO_local_pool); return(1); } // Copy all the dependences to/from the first loop to the other loops INT ARRAY_DIRECTED_GRAPH16::Copy_Do_Loop_Deps(VINDEX16 *do_loop_vertices, INT num_loops) { EINDEX16 e = _v[do_loop_vertices[0]].Get_Out_Edge(); while (e) { for (INT i=1; i<num_loops; i++) { Add_Edge(do_loop_vertices[i],_e[e].Get_Sink(),Level(e)); } e = _e[e].Get_Next_Out_Edge(); } e = _v[do_loop_vertices[0]].Get_In_Edge(); while (e) { for (INT i=1; i<num_loops; i++) { if (!Add_Edge(_e[e].Get_Source(),do_loop_vertices[i],Level(e))) { return(0); } } e = _e[e].Get_Next_In_Edge(); } return(1); } // Fix all the dependences in the copy rooted at in_loop // All intra copy dependences remain // All inter copy get moved to the level of the do loop and get chopped // Fission_depth is the number of perfectly nested loops fissioned together // Depth is the depth of each outer do loop // Outer good_do is TRUE if in_loop is the outermost good do loop INT ARRAY_DIRECTED_GRAPH16::Fission_Dep_Update_R(WN *in_loop, UINT fission_depth, UINT depth, BOOL outer_good_do) { VINDEX16 in_loop_v = Get_Vertex(in_loop); Is_True(in_loop_v,("No vertex for one of the fission copies")); // find the first statement in this copy WN *statement, *parent; WN* loop = in_loop; for (INT i=0; i<fission_depth; i++) { parent = WN_do_body(loop); statement = WN_first(parent); EINDEX16 e=0; while (statement) { if (WN_opcode(statement) == OPC_DO_LOOP) loop=statement; VINDEX16 v = Get_Vertex(statement); Is_True(v,("No vertex for one of the fission copies")); if (v) { e = _v[v].Get_Out_Edge(); } else while (e) { EINDEX16 next_e = _e[e].Get_Next_Out_Edge(); UINT level = MIN(Level(e),depth); VINDEX16 v2 = _e[e].Get_Sink(); WN *wn2 = Get_Wn(v2); if (LWN_Get_Parent(wn2) != parent) { // not the same copy if (!outer_good_do) { // find the outer do loop corresponding to the sink WN *parent2 = wn2; for (INT j=0; j<=i; j++) { parent2 = LWN_Get_Parent(LWN_Get_Parent(parent2)); } VINDEX16 sinkv = Get_Vertex(parent2); Is_True(sinkv,("No vertex for one of the fission copies")); EINDEX16 new_e = Get_Edge(in_loop_v,sinkv); if (new_e) { // an edge already exists, update level if need be _e[new_e].Level_Info.Level = MAX(Level(new_e),level); } else { if (!Add_Edge(in_loop_v,sinkv,level)) { return 0; } } } Remove_Edge(e); } e = next_e; } statement = WN_next(statement); } } return 1; } // Find the inner loop surrounding this wn // Assumes there is one static WN *Find_Inner(WN *wn) { if (WN_opcode(wn) == OPC_DO_LOOP) { return(wn); } else { return(Find_Inner(LWN_Get_Parent(wn))); } } // is this array invariant in the inner loop static BOOL Inner_Loop_Invariant(ACCESS_ARRAY *a) { if (a->Too_Messy) return FALSE; for (INT i=0; i<a->Num_Vec(); i++) { ACCESS_VECTOR *av = a->Dim(i); if (av->Too_Messy) { return FALSE; } if (av->Non_Const_Loops() >= av->Nest_Depth()) { return FALSE; } if (av->Loop_Coeff(av->Nest_Depth()-1)) { return FALSE; } } return TRUE; } // Given CG's dependence graph, add in the "must" edges // This is a two part algorithm. First, we go through all edges // in the graph. If their distance is constant // we set the must bit. If the references are invariant and identical, // we also set the must bit. Otherwise if the base array is the same, // we check for must dependences. // // Then we check every read in the graph vrs every read to the same // base array in the same inner loop. We add edges for all the must // dependences void ARRAY_DIRECTED_GRAPH16::Add_Must() { MEM_POOL_Push(&LNO_local_pool); Is_True(_type==DEP_ARRAY_GRAPH, ("Add_Must called on non-CG dependence graph")); // first the non ld-ld VINDEX16 v; for (v = Get_Vertex(); v; v = Get_Next_Vertex(v)) { WN *source = _v[v].Wn; WN *array1=0,*array2=0; ACCESS_ARRAY *a1=0,*a2=0; if (OPCODE_is_load(WN_opcode(source)) || OPCODE_is_store(WN_opcode(source))) { if (OPCODE_is_load(WN_opcode(source))) { if (WN_kid_count(source) >= 1) { array1 = WN_kid0(source); } } else { if (WN_kid_count(source) >= 2) { array1 = WN_kid1(source); } } if (WN_operator(array1) == OPR_ADD) { if (WN_operator(WN_kid0(array1)) == OPR_ARRAY) { array1 = WN_kid0(array1); } else { array1 = WN_kid1(array1); } } if (array1) a1=(ACCESS_ARRAY *) WN_MAP_Get(LNO_Info_Map,array1); if (a1) { BOOL a1_invar = Inner_Loop_Invariant(a1); EINDEX16 e = Get_Out_Edge(v); while (e) { EINDEX16 new_e = Get_Next_Out_Edge(e); VINDEX16 v2 = Get_Sink(e); WN *sink = _v[v2].Wn; if (OPCODE_is_load(WN_opcode(sink)) || OPCODE_is_store(WN_opcode(sink))) { if (DEPV_COMPUTE::Base_Test(source,NULL,sink,NULL)==DEP_CONTINUE) { if (OPCODE_is_load(WN_opcode(sink))) { if (WN_kid_count(sink) >= 1) { array2 = WN_kid0(sink); } } else { if (WN_kid_count(sink) >= 2) { array2 = WN_kid1(sink); } } if (WN_operator(array2) == OPR_ADD) { if (WN_operator(WN_kid0(array2)) == OPR_ARRAY) { array2 = WN_kid0(array2); } else { array2 = WN_kid1(array2); } } if (array2) a2=(ACCESS_ARRAY *) WN_MAP_Get(LNO_Info_Map,array2); if (a2) { DEP dep = Dep(e); if (DEP_IsDistance(dep)) { DEP dep2; if (Is_Must(a1,a2,Find_Inner(source),&dep2)) { if (DEP_IsDistance(dep2)) { if (DEP_Distance(dep) == DEP_Distance(dep2)) { Set_Must(e); } else { Delete_Edge(e); // incompatible so must be spurious } } } } else if (DEPV_COMPUTE::Base_Test(source,NULL,sink,NULL) == DEP_CONTINUE) { DEP dep2; if (a1_invar && (*a1 == *a2)) { Set_Must(e); } else if (!a1_invar && Is_Must(a1,a2,Find_Inner(source),&dep2)) { if (DEP_Distance(dep2) > 0) { if ((DEP_Direction(dep) == DIR_POS) || (DEP_Direction(dep) == DIR_POSEQ) || (DEP_Direction(dep) == DIR_STAR) || (DEP_Direction(dep) == DIR_POSNEG)) { Set_Dep(e,dep2,TRUE); } else { Delete_Edge(e); // incompatible so must be spurious } } else if (DEP_Distance(dep2) == 0) { if ((DEP_Direction(dep) == DIR_EQ) || (DEP_Direction(dep) == DIR_POSEQ) || (DEP_Direction(dep) == DIR_STAR) || (DEP_Direction(dep) == DIR_NEGEQ)) { Set_Dep(e,dep2,TRUE); } else { Delete_Edge(e); } } } } } } } e = new_e; } } } } // now the ld-ld // first gather from the graph all the reads // we partitition the loads from the graph by base array and inner loop // to avoid doing n^2 checks // we don't put on our list things with strange base arrays, we can // never get must dependences from these REF_LIST_STACK *reads = CXX_NEW(REF_LIST_STACK(&LNO_local_pool), &LNO_local_pool); for (v = Get_Vertex(); v; v = Get_Next_Vertex(v)) { WN *source = _v[v].Wn; OPCODE opcode = WN_opcode(source); if (OPCODE_is_load(opcode)) { if (WN_kid_count(source) == 1) { WN *inner_loop = Find_Inner(source); WN *array = WN_kid0(source); if (WN_operator(array) == OPR_ADD) { if (WN_operator(WN_kid0(array)) == OPR_ARRAY) { array = WN_kid0(array); } else { array = WN_kid1(array); } } if (WN_operator(array) == OPR_ARRAY) { WN *base = WN_array_base(array); ST *st_base = Get_ST_Base(base); INT i; for (i=0;i<reads->Elements() && !((reads->Bottom_nth(i)->ST_Base==st_base) && (reads->Bottom_nth(i)->Inner_Loop==inner_loop)); i++); if (i==reads->Elements()) { // a new partition REFERENCE_LIST *rl = CXX_NEW(REFERENCE_LIST(st_base,source,inner_loop),&LNO_local_pool); reads->Push(rl); } reads->Bottom_nth(i)->Append(CXX_NEW(REFERENCE_NODE(source,0, 0), &LNO_local_pool)); } } } } // now do an n^2 comparison on each partition. Note that we assume that // for two pairs to have a must dependence, they must be in the same // partition. It's always conservative to not set a must dependence. for (INT i=0; i<reads->Elements(); i++) { INT num_iterations = 0; WN *trip_count = WN_LOOP_TripCount(reads->Bottom_nth(i)->Inner_Loop); if (trip_count) { LWN_Parentize(trip_count); LWN_Set_Parent(trip_count, NULL); } BOOL const_trip = (trip_count) && (WN_operator(trip_count) == OPR_INTCONST); if (const_trip) num_iterations = WN_const_val(trip_count); LWN_Delete_Tree(trip_count); REFERENCE_ITER iter1(reads->Bottom_nth(i)); for (REFERENCE_NODE *n1=iter1.First(); !iter1.Is_Empty(); n1=iter1.Next()) { WN *wn1 = n1->Wn; WN *array1 = WN_kid0(wn1); if (WN_operator(array1) == OPR_ADD) { if (WN_operator(WN_kid0(array1)) == OPR_ARRAY) { array1 = WN_kid0(array1); } else { array1 = WN_kid1(array1); } } ACCESS_ARRAY *a1=(ACCESS_ARRAY *) WN_MAP_Get(LNO_Info_Map,array1); BOOL a1_invar = Inner_Loop_Invariant(a1); REFERENCE_ITER iter2(n1); REFERENCE_NODE *n2 = iter2.First(); for (n2=iter2.Next(); !iter2.Is_Empty(); n2=iter2.Next()) { WN *wn2 = n2->Wn; WN *array2 = WN_kid0(wn2); if (WN_operator(array2) == OPR_ADD) { if (WN_operator(WN_kid0(array2)) == OPR_ARRAY) { array2 = WN_kid0(array2); } else { array2 = WN_kid1(array2); } } // are they the same base if (DEPV_COMPUTE::Base_Test(wn1,NULL,wn2,NULL) == DEP_CONTINUE) { ACCESS_ARRAY *a2=(ACCESS_ARRAY *) WN_MAP_Get(LNO_Info_Map,array2); DEP dep; if (a1_invar && (*a1 == *a2)) { VINDEX16 v1 = Get_Vertex(wn1); VINDEX16 v2 = Get_Vertex(wn2); if (!Add_Edge(v1,v2,DEP_SetDirection(DIR_POSEQ),TRUE)) { MEM_POOL_Pop(&LNO_local_pool); return; } if (!Add_Edge(v2,v1,DEP_SetDirection(DIR_POS),TRUE)) { MEM_POOL_Pop(&LNO_local_pool); return; } } else if (Is_Must(a1,a2,reads->Bottom_nth(i)->Inner_Loop,&dep)) { VINDEX16 v1 = Get_Vertex(wn1); VINDEX16 v2 = Get_Vertex(wn2); if (!num_iterations || (abs(DEP_Distance(dep)) < num_iterations)) { if (DEP_Distance(dep) >= 0) { if (!Add_Edge(v1,v2,dep,TRUE)) { MEM_POOL_Pop(&LNO_local_pool); return; } } else { if (!Add_Edge(v2,v1,DEP_SetDistance(-DEP_Distance(dep)),TRUE)) { MEM_POOL_Pop(&LNO_local_pool); return; } } } } } } } } MEM_POOL_Pop(&LNO_local_pool); } // Is there a must dependence from a1 to a2 // This routine assume that either a1 or a2 is variant in the inner loop // This routine assumes a1 and a2 are in the same inner loop // For there to be a must dependence, the two references must vary only // in the constant term // If there is a must dependence and dep != NULL, set dep to its value BOOL ARRAY_DIRECTED_GRAPH16::Is_Must(ACCESS_ARRAY *a1, ACCESS_ARRAY *a2, WN *inner_loop,DEP *dep) { if (a1->Too_Messy || a2->Too_Messy) return(FALSE); if (a1->Num_Vec() != a2->Num_Vec()) return(FALSE); DO_LOOP_INFO *dli = (DO_LOOP_INFO *) WN_MAP_Get(LNO_Info_Map,inner_loop); INT depth = dli->Depth; ACCESS_VECTOR *ac_step = dli->Step; if (!ac_step->Is_Const()) { return(FALSE); } INT64 step = ac_step->Const_Offset; BOOL seen_mult = FALSE; INT diff=0; // for each dimension for (INT i=0; i<a1->Num_Vec(); i++) { ACCESS_VECTOR *av1 = a1->Dim(i); ACCESS_VECTOR *av2 = a2->Dim(i); if (av1->Too_Messy || av2->Too_Messy) return(FALSE); // does either have a constant term that varies in the inner loop if (av1->Non_Const_Loops() == (depth + 1)) return(FALSE); if (av2->Non_Const_Loops() == (depth + 1)) return(FALSE); INT dist = av1->Const_Offset - av2->Const_Offset; // short circuit to get const reference case quickly, ie a[0] vrs a[1] if (!av1->Has_Loop_Coeff() || !av2->Has_Loop_Coeff()) { if (dist) return(FALSE); } // the symbols must be equal if (av1->Lin_Symb!=NULL && !av1->Lin_Symb->Is_Empty()) { // av1 has a symb if (av2->Lin_Symb == NULL || av2->Lin_Symb->Is_Empty() || !(*av1->Lin_Symb == *av2->Lin_Symb)) { return(FALSE); } } else if (av2->Lin_Symb != NULL && !av2->Lin_Symb->Is_Empty()) { return(FALSE); } if (av1->Non_Lin_Symb != NULL && !av1->Non_Lin_Symb->Is_Empty()) { if (av2->Non_Lin_Symb == NULL || av2->Non_Lin_Symb->Is_Empty() || !(*av1->Non_Lin_Symb == *av2->Non_Lin_Symb)) { return(FALSE); } } else if (av2->Non_Lin_Symb != NULL && !av2->Non_Lin_Symb->Is_Empty()) { return(FALSE); } // Now check the induction variables for (INT ii=0; ii<av1->Nest_Depth(); ii++) { if (av1->Loop_Coeff(ii) != av2->Loop_Coeff(ii)) { return(FALSE); } } INT mult = av1->Loop_Coeff(depth); if (mult) { if ((dist % (step*mult)) != 0) { return(FALSE); // independent } INT this_diff = (dist / (step*mult)); if (seen_mult && (this_diff != diff)) { // contradictory coupling return(FALSE); } seen_mult = TRUE; diff = this_diff; } else { if (dist != 0) { return(FALSE); // independent } } } if (dep) { *dep = DEP_SetDistance(diff); if (!DEP_IsDistance(*dep)) return FALSE; // overflow } return(TRUE); } /*********************************************************************** * * Return true if wn is contained within the tree rooted at root, * false otherwise. * ***********************************************************************/ static BOOL Node_In_Tree (WN* wn, WN* root) { while (1) { if (wn == root) return TRUE; if (wn == NULL) return FALSE; wn = LWN_Get_Parent (wn); } } /*********************************************************************** * * Called to update the dependence graph when a loop is versioned * for prefetching. * - body_orig == pointer to loop-body of the original loop (then part) * - body_new == pointer to loop-body of the new version of loop (else part) * - loopno == depth of the loop * ***********************************************************************/ BOOL ARRAY_DIRECTED_GRAPH16::Versioned_Dependences_Update(WN* body_orig, WN* body_new, UINT loopno, WN_MAP version_map) { Is_True(_type==DEPV_ARRAY_ARRAY_GRAPH, ("Unrolled_Dependences_Update called on a non-DEPV_ARRAY graph")); MEM_POOL_Push(&LNO_local_pool); // First create the vertices for the new version of the loop body. Versioned_Create_Vertices (body_orig, body_new); BOOL ok = Versioned_Dependences_Update_E (body_orig, body_new, body_orig, body_new, loopno, version_map); MEM_POOL_Pop(&LNO_local_pool); return ok; } /*********************************************************************** * * Given a loop body, create vertices in the dependence graph for those * loads/stores in the new loop body for which the corresponding load/store * in the orig loop body had a vertex. * ***********************************************************************/ void ARRAY_DIRECTED_GRAPH16::Versioned_Create_Vertices (WN* body_orig, WN* body_new) { if (body_orig == NULL) { Is_True (body_new == NULL, ("mismatch in body_orig and body_new\n")); return; } if (Get_Vertex (body_orig)) Add_Vertex (body_new); if (WN_opcode(body_new) == OPC_BLOCK) { WN* kid_new = WN_first(body_new); WN* kid_orig = WN_first(body_orig); while (kid_new) { Versioned_Create_Vertices (kid_orig, kid_new); kid_orig = WN_next (kid_orig); kid_new = WN_next (kid_new); } } else if (WN_kid_count(body_new)) { for (INT kidno=0; kidno<WN_kid_count(body_new); kidno++) { Versioned_Create_Vertices (WN_kid(body_orig, kidno), WN_kid(body_new, kidno)); } } } /*********************************************************************** * * Update the edges after versioning (or rohit-splitting) * Each edge in to or out of the region gets copied. * For each edge within the region, * - copy it in the new body * - if any of the dependences from outermost loop to this loop are not EQ, * then add cross edges between the two versions of the code. */ BOOL ARRAY_DIRECTED_GRAPH16::Versioned_Dependences_Update_E(WN* body_orig, WN* body_new, WN* root_orig, WN* root_new, UINT loopno, WN_MAP version_map) { if (body_orig == NULL) { Is_True (body_new == NULL, ("mismatch in body_orig and body_new\n")); return TRUE; } if (OPCODE_is_load(WN_opcode(body_orig)) || OPCODE_is_store(WN_opcode(body_orig)) || OPCODE_is_call(WN_opcode(body_orig))) { VINDEX16 origv = Get_Vertex(body_orig); if (origv) { VINDEX16 newv = Get_Vertex (body_new); // since processing the internal edges may add external edges // from body_orig to body_new, process the external edges first. // First the outedges EINDEX16 edge = Get_Out_Edge(origv); while (edge) { VINDEX16 orig_sinkv = Get_Sink(edge); WN* orig_sinkwn = Get_Wn(orig_sinkv); if (!Node_In_Tree (orig_sinkwn, root_orig) && !Node_In_Tree (orig_sinkwn, root_new)) { // not in root_orig, hence an outside edge. // The test for sink in root_new is added since this could be // a cross-edge that had been added while traversing an earlier // node. // so add it to the body_new if (Add_Edge(newv,orig_sinkv, Create_DEPV_ARRAY(Depv_Array(edge),_pool)) == 0) { LNO_Erase_Dg_From_Here_In(LWN_Get_Parent(root_orig), this); LNO_Erase_Dg_From_Here_In(LWN_Get_Parent(body_orig), this); return FALSE; } } edge = Get_Next_Out_Edge(edge); } // now the in-edges to this vertex edge = Get_In_Edge (origv); while (edge) { VINDEX16 orig_sourcev = Get_Source(edge); WN* orig_sourcewn = Get_Wn(orig_sourcev); VINDEX16 new_sourcev; if (!Node_In_Tree (orig_sourcewn, root_orig) && !Node_In_Tree (orig_sourcewn, root_new)) { new_sourcev = orig_sourcev; if (Add_Edge(new_sourcev,newv, Create_DEPV_ARRAY(Depv_Array(edge),_pool)) == 0) { LNO_Erase_Dg_From_Here_In(LWN_Get_Parent(root_orig), this); LNO_Erase_Dg_From_Here_In(LWN_Get_Parent(body_orig), this); return FALSE; } } edge = Get_Next_In_Edge(edge); } // now all external edges have been processed. // so now do internal edges. // get all the edges from this vertex // process internal edges only as outedges, // to avoid processing them twice edge = Get_Out_Edge(origv); while (edge) { VINDEX16 orig_sinkv = Get_Sink(edge); WN* orig_sinkwn = Get_Wn(orig_sinkv); VINDEX16 new_sinkv; if (Node_In_Tree (orig_sinkwn, root_orig)) { // sink is within the replicated body, so internal edge. // add the internal edge to body_new new_sinkv = Get_Vertex((WN*) WN_MAP_Get (version_map, orig_sinkwn)); if (Add_Edge(newv,new_sinkv, Create_DEPV_ARRAY(Depv_Array(edge),_pool)) == 0) { LNO_Erase_Dg_From_Here_In(LWN_Get_Parent(root_orig), this); LNO_Erase_Dg_From_Here_In(LWN_Get_Parent(body_orig), this); return FALSE; } // see if we should add cross-edges if (Depv_Array(edge)->Equal_Through_Depth (loopno) == FALSE) { // maybe add cross edges INT unused = _e[edge].Depv_Array->Num_Unused_Dim(); if (loopno > unused) { // add cross edges only if there really is a dependence // Shorten returns a new copy of depv_array // loopno - unused is the number of loops with dependences. DEPV_ARRAY* tmp = Depv_Array (edge)->Shorten (loopno-unused, _pool); if (Add_Edge (origv, new_sinkv, tmp) == 0) { LNO_Erase_Dg_From_Here_In(LWN_Get_Parent(root_orig), this); LNO_Erase_Dg_From_Here_In(LWN_Get_Parent(body_orig), this); return FALSE; } tmp = Depv_Array (edge)->Shorten (loopno-unused, _pool); if (Add_Edge (newv, orig_sinkv, tmp) == 0) { LNO_Erase_Dg_From_Here_In(LWN_Get_Parent(root_orig), this); LNO_Erase_Dg_From_Here_In(LWN_Get_Parent(body_orig), this); return FALSE; } } } } edge = Get_Next_Out_Edge(edge); } } } if (WN_opcode(body_new) == OPC_BLOCK) { WN* kid_new = WN_first(body_new); WN* kid_orig = WN_first(body_orig); while (kid_new) { if (!Versioned_Dependences_Update_E (kid_orig, kid_new, root_orig, root_new, loopno, version_map)) return FALSE; kid_orig = WN_next (kid_orig); kid_new = WN_next (kid_new); } } else if (WN_kid_count(body_new)) { for (INT kidno=0; kidno<WN_kid_count(body_new); kidno++) { if (!Versioned_Dependences_Update_E (WN_kid(body_orig, kidno), WN_kid(body_new, kidno), root_orig, root_new, loopno, version_map)) return FALSE; } } return TRUE; } #ifdef Is_True_On void ARRAY_DIRECTED_GRAPH16::Check_Graph() { MEM_POOL_Push(&LNO_local_pool); { HASH_TABLE<VINDEX16,INT> vertices(200, &LNO_local_pool); for (VINDEX16 v = Get_Vertex(); v; v = Get_Next_Vertex(v)) { WN *wn = Get_Wn(v); FmtAssert(wn, ("Missing wn for vertex %d", v)); FmtAssert(Get_Do(wn), ("Missing enclosing loop for vertex %d", v)); vertices.Enter(v, 1); } for (EINDEX16 e = Get_Edge(); e; e = Get_Next_Edge(e)) { FmtAssert(_e[e].Depv_Array,("Null Array for edge %d \n",e)); VINDEX16 v1 = Get_Source(e); FmtAssert(vertices.Find(v1), ("Edge %d has source vertex %d not in graph", e, v1)); VINDEX16 v2 = Get_Sink(e); FmtAssert(vertices.Find(v2), ("Edge %d has sink vertex %d not in graph", e, v2)); } } MEM_POOL_Pop(&LNO_local_pool); } #endif /* Is_True_On */ // add a reference to the scalar stack void SCALAR_STACK::Add_Scalar(WN *wn, UINT snumber) { Is_True((WN_operator(wn) == OPR_LDID) || (WN_operator(wn) == OPR_STID), ("Non scalar passed to SCALAR_STACK::Add_Scalar")); SYMBOL symbol(wn); SCALAR_REF sref(wn,snumber); for (INT i=0; i<_stack->Elements(); i++) { if (symbol == _stack->Top_nth(i)._scalar) { _stack->Top_nth(i)._scalar_ref_stack->Push(sref); return; } } _stack->Push(SCALAR_NODE(_pool,symbol)); _stack->Top_nth(0)._scalar_ref_stack->Push(sref); } // add a reference to the scalar stack void SCALAR_STACK::Add_Scalar(WN *wn_call, SYMBOL* symbol, UINT snumber) { Is_True(WN_operator(wn_call) == OPR_CALL || WN_operator(wn_call) == OPR_LDID || WN_operator(wn_call) == OPR_LDA, ("Non scalar passed to SCALAR_STACK::Add_Scalar")); SCALAR_REF sref(wn_call, snumber); for (INT i=0; i<_stack->Elements(); i++) { if (*symbol == _stack->Top_nth(i)._scalar) { _stack->Top_nth(i)._scalar_ref_stack->Push(sref); return; } } _stack->Push(SCALAR_NODE(_pool,*symbol)); _stack->Top_nth(0)._scalar_ref_stack->Push(sref); } void SCALAR_STACK::Remove_Scalar(WN *wn) { Is_True((WN_operator(wn) == OPR_LDID) || (WN_operator(wn) == OPR_STID), ("Non scalar passed to SCALAR_STACK::Remove_Scalar")); SYMBOL symbol(wn); for (INT i=0; i<_stack->Elements(); i++) { if (symbol == _stack->Top_nth(i)._scalar) { //remove all scalar_references to this symbol for (INT j = 0; j < _stack->Top_nth(i)._scalar_ref_stack->Elements(); j++) _stack->Top_nth(i)._scalar_ref_stack->DeleteTop(j); //remove the SCALAR_NODE since its _scalar_ref_stack is now empty. if (_stack->Top_nth(i)._scalar_ref_stack->Elements() == 0) _stack->DeleteTop(i); return; } } } void SCALAR_STACK::Print(FILE *fp) { for (INT i=0; i<_stack->Elements(); i++) { SCALAR_NODE *node = &_stack->Bottom_nth(i); fprintf(fp,"The symbol is "); node->_scalar.Print(fp); fprintf(fp,"\n"); for (INT j=0; j<node->Elements(); j++) { fprintf(fp,"One with statement number %d \n", node->Bottom_nth(j)->Statement_Number); } } } void SCALAR_STACK::Clear_Formal(INT i) { STACK<SCALAR_NODE> temp_stack(_pool); INT j; for (j = 0; j < _stack->Elements(); j++) { SCALAR_NODE* sn = &_stack->Bottom_nth(j); if (!(sn->_scalar.Is_Formal() && sn->_scalar.Formal_Number() == i)) temp_stack.Push(*sn); } _stack->Clear(); for (j = 0; j < temp_stack.Elements(); j++) _stack->Push(temp_stack.Bottom_nth(j)); } #endif /* ifdef LNO */
31.290654
111
0.605829
sharugupta
c95bf755b9e1954aa7076a214c45120bf5d71875
621
cpp
C++
src/geometry/mesh/implementation/component/CupCfdAoSMeshVertex.cpp
thorbenlouw/CUP-CFD
d06f7673a1ed12bef24de4f1b828ef864fa45958
[ "MIT" ]
3
2021-06-24T10:20:12.000Z
2021-07-18T14:43:19.000Z
src/geometry/mesh/implementation/component/CupCfdAoSMeshVertex.cpp
thorbenlouw/CUP-CFD
d06f7673a1ed12bef24de4f1b828ef864fa45958
[ "MIT" ]
2
2021-07-22T15:31:03.000Z
2021-07-28T14:27:28.000Z
src/geometry/mesh/implementation/component/CupCfdAoSMeshVertex.cpp
thorbenlouw/CUP-CFD
d06f7673a1ed12bef24de4f1b828ef864fa45958
[ "MIT" ]
1
2021-07-22T15:24:24.000Z
2021-07-22T15:24:24.000Z
/* * @file * @author University of Warwick * @version 1.0 * * @section LICENSE * * @section DESCRIPTION * */ #include "CupCfdAoSMeshVertex.h" namespace cupcfd { namespace geometry { namespace mesh { template <class T> CupCfdAoSMeshVertex<T>::CupCfdAoSMeshVertex() { // === Default values setup === // Set vertex position to (0.0, 0.0, 0.0) this->pos = (T) 0.0; } template <class T> CupCfdAoSMeshVertex<T>::~CupCfdAoSMeshVertex() { } // Explicit instantiation template class CupCfdAoSMeshVertex<float>; template class CupCfdAoSMeshVertex<double>; } } }
15.146341
49
0.639291
thorbenlouw
c95fc57fa3de1dca43d51700a7f6c7bacc6bdcaa
1,264
hpp
C++
RX24T/rx24t_LOGGER/setup.hpp
hirakuni45/RX
3fb91bfc8d5282cde7aa00b8bd37f4aad32582d0
[ "BSD-3-Clause" ]
56
2015-06-04T14:15:38.000Z
2022-03-01T22:58:49.000Z
rx24t_LOGGER/setup.hpp
duybang140494/RX
7fed06a9d8295f4504e8a08fa589d4a52792095f
[ "BSD-3-Clause" ]
30
2019-07-27T11:03:14.000Z
2021-12-14T09:59:57.000Z
rx24t_LOGGER/setup.hpp
duybang140494/RX
7fed06a9d8295f4504e8a08fa589d4a52792095f
[ "BSD-3-Clause" ]
15
2017-06-24T11:33:39.000Z
2021-12-07T07:26:58.000Z
#pragma once //=====================================================================// /*! @file @brief セットアップ・クラス Copyright 2017 Kunihito Hiramatsu @author 平松邦仁 (hira@rvf-rc45.net) */ //=====================================================================// #include "main.hpp" namespace app { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief セットアップ・クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// class setup { public: //-------------------------------------------------------------// /*! @brief コンストラクター */ //-------------------------------------------------------------// setup() { } //-------------------------------------------------------------// /*! @brief 初期化 */ //-------------------------------------------------------------// void init() { auto& core = at_core(); core.menu_.set_space(4); } //-------------------------------------------------------------// /*! @brief サービス */ //-------------------------------------------------------------// void service() { auto& core = at_core(); core.bitmap_.frame(0, 0, 128, 64, 1); core.menu_.render(); } }; }
22.175439
74
0.221519
hirakuni45
e92aca0c24c190987fc86e3ac07c15d8dc636bb6
718
cpp
C++
BST/searchInBST.cpp
PranavDherange/Data_Structures
9962b5145f6b42d9317e2c328c2b3124f028ca70
[ "MIT" ]
2
2021-02-25T11:54:50.000Z
2021-02-25T11:54:54.000Z
BST/searchInBST.cpp
PranavDherange/Data_Structures
9962b5145f6b42d9317e2c328c2b3124f028ca70
[ "MIT" ]
null
null
null
BST/searchInBST.cpp
PranavDherange/Data_Structures
9962b5145f6b42d9317e2c328c2b3124f028ca70
[ "MIT" ]
1
2021-10-03T17:39:10.000Z
2021-10-03T17:39:10.000Z
/*Code: Search in BST Given a BST and an integer k. Find if the integer k is present in given BST or not. Return the node with data k if it is present, return null otherwise. Assume that BST contains all unique elements. Sample Input : 8 5 10 2 6 -1 -1 -1 -1 -1 7 -1 -1 6 10 Sample Output : 6 7 8 10 */ #include <bits/stdc++.h> using namespace std; #include "binaryTree.h" BinaryTreeNode<int> *findNode(BinaryTreeNode<int> *root, int k) { if (root == NULL) { return NULL; } if (root->data == k) { return root; } else if (root->data > k) { return findNode(root->left, k); } else if (root->data < k) { return findNode(root->right, k); } }
21.757576
152
0.604457
PranavDherange
e92b389be4d84499dc33a9f4757881f9d364f393
4,009
hpp
C++
dart/utils/amc/Skeleton.hpp
jyf588/nimblephysics
6c09228f0abcf7aa3526a8dd65cd2541aff32c4a
[ "BSD-2-Clause" ]
2
2021-09-30T06:23:29.000Z
2022-03-09T09:59:09.000Z
dart/utils/amc/Skeleton.hpp
jyf588/nimblephysics
6c09228f0abcf7aa3526a8dd65cd2541aff32c4a
[ "BSD-2-Clause" ]
null
null
null
dart/utils/amc/Skeleton.hpp
jyf588/nimblephysics
6c09228f0abcf7aa3526a8dd65cd2541aff32c4a
[ "BSD-2-Clause" ]
1
2021-08-20T13:56:14.000Z
2021-08-20T13:56:14.000Z
#ifndef AMC_SKELETON_HPP #define AMC_SKELETON_HPP #include <iostream> #include <string> #include <vector> #include "dart/utils/amc/Quat.hpp" #include "dart/utils/amc/Vector.hpp" namespace Library { using std::cerr; using std::endl; using std::string; using std::vector; // collection of joint angles, offset matrices, and so on. class Bone { public: string name; int parent; Vector3s direction; Vector3s axis_offset; // in degrees string offset_order; Quatd global_to_local; double radius; double density; double length; vector<Vector2s> torque_limits; string dof; // list of degrees of freedom -> 'xyz' -> rotation around 'x' 'y' // 'z'. 'a' -> angle-axis rotation [3 values] Vector3s color; int frame_offset; // where in lists of per-frame data this fellow's data // rests. // filled, but not yet taken advantage of vector<Vector3s> euler_axes; // for v-file. Actual axes of joint rotation //------------------------- // These are set every frame to reflect the bone's state. // Vector3s current_base_position; // Vector3s current_end_position; // Quatd current_rotation; //------------------------- inline void pre_parse() { name = ""; parent = 0; direction.x = direction.y = direction.z = 0; axis_offset.x = axis_offset.y = axis_offset.z = 0; offset_order = "xyz"; radius = density = length = -1; dof = ""; torque_limits.clear(); color.r = rand() / double(RAND_MAX); color.g = rand() / double(RAND_MAX); color.b = rand() / double(RAND_MAX); } inline bool post_parse() { if (name == "") { cerr << "Bone lacks name." << endl; return false; } if (length < 0) { cerr << "Bone lacks length. Picking 1." << endl; length = 1; } if (radius < 0) { // cerr << "Bone lacks radius. Picking length / 10." << endl; radius = length / 10.0; } if (density < 0) { // cerr << "Bone lacks density. Picking 1000." << endl; density = 1000; } if (torque_limits.size() > dof.size()) { cerr << "There are extra torque limits on " << name << " that will be ignored." << endl; } if (torque_limits.size() < dof.size()) { // cerr << "Not all dof of " << name << " have limits. Padding with 100s." // << endl; while (torque_limits.size() < dof.size()) { torque_limits.push_back(make_vector(-100.0, 100.0)); } } return true; } }; ostream& operator<<(std::ostream& os, const Bone& b); class Skeleton { public: vector<Bone> bones; // little letters are rotations, big letters are translations. // (think 'xXyzYZ' -- rotate x, trans x, rot y, rot z, trans Y, trans Z) string order; // order of transformation for root bone Vector3s position; // position for root bone string offset_order; // order for axis offset rotation values Vector3s axis_offset; // rotation for root bone (degrees) // These track the present position/rotation info. // Vector3s current_position; // Quatd current_rotation; // parser info: inline void init_parse() { in_bone = false; bones.clear(); mass = 1.0; length = 1.0; ang_is_deg = true; offset_order = "xyz"; order = "XYZxyz"; timestep = 1.0 / 120.0; rot_is_glob = false; z_is_up = false; } // large, has setup for bones. Stuff like that. bool check_parse(); int get_bone_by_name(string name) const; // returns a succinct string describing a dof string get_dof_description(unsigned int dof) const; bool in_bone; double mass, length, timestep; bool ang_is_deg; // true -> degrees, false -> radians bool rot_is_glob; // true -> global rotations (v-file), false -> local (amc) bool z_is_up; // If set, will rotate z-up to y-up. int frame_size; // how may dof per frame. string filename; // what file this was loaded from. }; } // namespace Library #endif // SKELETON_HPP
24.150602
80
0.616114
jyf588