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
ddf105cc18fd91e2f863fa2ef170e07d6225c060
931
hpp
C++
franken/main/Context.hpp
yatsuha4/franken
ae3aafe8da0c5663504e2e5c064dc98095ee37c8
[ "MIT" ]
null
null
null
franken/main/Context.hpp
yatsuha4/franken
ae3aafe8da0c5663504e2e5c064dc98095ee37c8
[ "MIT" ]
null
null
null
franken/main/Context.hpp
yatsuha4/franken
ae3aafe8da0c5663504e2e5c064dc98095ee37c8
[ "MIT" ]
null
null
null
/***********************************************************************//** @file ***************************************************************************/ #pragma once namespace franken { namespace main { /***********************************************************************//** @brief コンテキスト ***************************************************************************/ class Context : public fk::Context { using super = fk::Context; private: Application* application_; ConfigPtr config_; public: Context(Application* application); ~Context() override; FK_GETTER(Application, application_); FK_ACCESSOR(Config, config_); protected: void onRender(fk::Renderer& renderer, const fk::RenderParam& param) override; }; /***********************************************************************//** $Id$ ***************************************************************************/ } }
25.861111
77
0.348013
yatsuha4
ddf63a4ff2d03a9f08a40dfdf5d04a051e8cdb8e
6,919
cpp
C++
source/src/dxtmex_mexerror.cpp
gharveymn/dds-matlab
268546bb63d12e0a28fb476434f2e6940b3c68ab
[ "MIT" ]
null
null
null
source/src/dxtmex_mexerror.cpp
gharveymn/dds-matlab
268546bb63d12e0a28fb476434f2e6940b3c68ab
[ "MIT" ]
null
null
null
source/src/dxtmex_mexerror.cpp
gharveymn/dds-matlab
268546bb63d12e0a28fb476434f2e6940b3c68ab
[ "MIT" ]
null
null
null
/** mlerrorutils.c * Defines error and warning utility functions for easier * output of error information. * * Copyright © 2018 Gene Harvey * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #include "mex.h" #include "dxtmex_mexerror.hpp" #include <stdio.h> #include <stdarg.h> #include <errno.h> #ifndef _WIN32 # include <string.h> #else HRESULT hres = 0; #endif #define VALUE_AS_STRING(value) #value #define EXPAND_AS_STRING(num) VALUE_AS_STRING(num) #define MEU_SEVERITY_USER_STRING "[USER]" #define MEU_SEVERITY_INTERNAL_STRING "[INTERNAL]" #define MEU_SEVERITY_SYSTEM_STRING "[SYSTEM]" #define MEU_SEVERITY_CORRUPTION_STRING "[CORRUPTION]" #define MEU_SEVERITY_FATAL_STRING "[FATAL]" #define MEU_SEVERITY_HRESULT_STRING "[HRESULT]" #define MEU_LIBRARY_NAME_SIZE 31 #define MEU_ID_SIZE 95 #define MEU_ID_BUFFER_SIZE 128 #define MEU_ERROR_SEVERITY_SIZE 64 #define MEU_FILE_NAME_SIZE 260 #define MEU_ERROR_STRING_SIZE 2048 #define MEU_SYSTEM_ERROR_BUFFER_SIZE 1100 #define MEU_SYSTEM_ERROR_STRING_SIZE 1024 /* size of POSIX error buffer size */ #define MEU_MATLAB_HELP_MESSAGE_SIZE 512 #define MEU_FULL_MESSAGE_SIZE 4096 /* four times the size of max POSIX error buffer size */ #define MEU_ID_FORMAT "%." EXPAND_AS_STRING(MEU_LIBRARY_NAME_SIZE)"s:%." EXPAND_AS_STRING(MEU_ID_SIZE)"s" #define MEU_ERROR_MESSAGE_FORMAT "<strong>%." EXPAND_AS_STRING(MEU_ID_BUFFER_SIZE)"s</strong> in %." EXPAND_AS_STRING(MEU_FILE_NAME_SIZE)"s, at line %d.\n%." EXPAND_AS_STRING(MEU_ERROR_SEVERITY_SIZE)"s\n\n%." EXPAND_AS_STRING(MEU_ERROR_STRING_SIZE)"s\n%." EXPAND_AS_STRING(MEU_SYSTEM_ERROR_BUFFER_SIZE)"s%." EXPAND_AS_STRING(MEU_MATLAB_HELP_MESSAGE_SIZE)"s" #define MEU_WARN_MESSAGE_FORMAT "%." EXPAND_AS_STRING(MEU_ERROR_STRING_SIZE)"s%." EXPAND_AS_STRING(MEU_MATLAB_HELP_MESSAGE_SIZE)"s" void (*MEXError::error_callback)(unsigned int) = nullptr; void (*MEXError::warning_callback)() = nullptr; const char* MEXError::error_help_message = ""; const char* MEXError::warning_help_message = ""; namespace { /** * Writes out the severity string. * * @param buffer A preallocated buffer. Should be size MEU_ERROR_SEVERITY_SIZE. * @param error_severity The error severity bitmask. */ void WriteSeverityString(char* buffer, unsigned int error_severity) { char* buffer_iter = buffer; strcpy(buffer_iter, "Severity level: "); buffer_iter += strlen(buffer_iter); if(error_severity & MEU_SEVERITY_USER) { strcpy(buffer_iter, MEU_SEVERITY_USER_STRING); buffer_iter += strlen(MEU_SEVERITY_USER_STRING); } if(error_severity & MEU_SEVERITY_INTERNAL) { strcpy(buffer_iter, MEU_SEVERITY_INTERNAL_STRING); buffer_iter += strlen(MEU_SEVERITY_INTERNAL_STRING); } if(error_severity & MEU_SEVERITY_SYSTEM) { strcpy(buffer_iter, MEU_SEVERITY_SYSTEM_STRING); buffer_iter += strlen(MEU_SEVERITY_SYSTEM_STRING); } if(error_severity & MEU_SEVERITY_HRESULT) { strcpy(buffer_iter, MEU_SEVERITY_HRESULT_STRING); buffer_iter += strlen(MEU_SEVERITY_HRESULT_STRING); } if(error_severity & MEU_SEVERITY_CORRUPTION) { strcpy(buffer_iter, MEU_SEVERITY_CORRUPTION_STRING); buffer_iter += strlen(MEU_SEVERITY_CORRUPTION_STRING); } if(error_severity & MEU_SEVERITY_FATAL) { strcpy(buffer_iter, MEU_SEVERITY_FATAL_STRING); } } /** * Writes out the system error string. * * @param buffer A preallocated buffer. Should be size MEU_SYSTEM_ERROR_STRING_SIZE. * @param error_severity The system error code returned from GetLastError() or errno. */ void WriteSystemErrorString(char* buffer, unsigned int error_severity) { char* inner_buffer = buffer; #ifdef _WIN32 if(error_severity & MEU_ERRNO) { sprintf(buffer, "System error code 0x%d: ", errno); inner_buffer += strlen(buffer); strerror_s(inner_buffer, MEU_SYSTEM_ERROR_STRING_SIZE, errno); } else if(error_severity & MEU_SEVERITY_HRESULT) { sprintf(buffer, "System error code 0x%lX: ", hres); inner_buffer += strlen(buffer); FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, (DWORD)hres, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), inner_buffer, MEU_SYSTEM_ERROR_STRING_SIZE, nullptr); } else { sprintf(buffer, "System error code 0x%lX: ", GetLastError()); inner_buffer += strlen(buffer); FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), inner_buffer, MEU_SYSTEM_ERROR_STRING_SIZE, nullptr); } #else /* we use errno in any case */ sprintf(buffer, "System error code 0x%d: ", errno); inner_buffer += strlen(buffer); # if(((_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && !_GNU_SOURCE) || defined(__APPLE__)) /* XSI-compliant version */ strerror_r(errno, inner_buffer, MEU_SYSTEM_ERROR_STRING_SIZE); # else /* GNU-specific */ strcpy(inner_buffer, strerror_r(errno, inner_buffer, MEU_SYSTEM_ERROR_STRING_SIZE)); # endif #endif *(buffer + strlen(buffer)) = '\n'; } } void MEXError::PrintMexError(const char* file_name, int line, unsigned int error_severity, const char* error_id, const char* error_message, ...) { va_list va; char full_message[MEU_FULL_MESSAGE_SIZE] = {0}; char error_message_buffer[MEU_ERROR_STRING_SIZE] = {0}; char error_severity_buffer[MEU_ERROR_SEVERITY_SIZE] = {0}; char id_buffer[MEU_ID_BUFFER_SIZE] = {0}; char system_error_string_buffer[MEU_SYSTEM_ERROR_STRING_SIZE] = {0}; if(error_severity & (MEU_SEVERITY_SYSTEM|MEU_SEVERITY_HRESULT)) { WriteSystemErrorString(system_error_string_buffer, error_severity); } va_start(va, error_message); vsprintf(error_message_buffer, error_message, va); va_end(va); WriteSeverityString(error_severity_buffer, error_severity); sprintf(id_buffer, MEU_ID_FORMAT, MEXError::g_library_name, error_id); sprintf(full_message, MEU_ERROR_MESSAGE_FORMAT, error_id, file_name, line, error_severity_buffer, error_message_buffer, system_error_string_buffer, MEXError::error_help_message); if(MEXError::error_callback != nullptr) { MEXError::error_callback(error_severity); } mexErrMsgIdAndTxt(id_buffer, full_message); } void MEXError::PrintMexWarning(const char* warn_id, const char* warn_message, ...) { va_list va; char full_message[MEU_FULL_MESSAGE_SIZE] = {0}; char message_prebuffer[MEU_ERROR_STRING_SIZE] = {0}; char id_buffer[MEU_ID_BUFFER_SIZE] = {0}; va_start(va, warn_message); vsprintf(message_prebuffer, warn_message, va); va_end(va); sprintf(id_buffer, MEU_ID_FORMAT, MEXError::g_library_name, warn_id); sprintf(full_message, MEU_WARN_MESSAGE_FORMAT, message_prebuffer, MEXError::warning_help_message); if(MEXError::warning_callback != nullptr) { MEXError::warning_callback(); } mexWarnMsgIdAndTxt(id_buffer, full_message); }
31.884793
357
0.764128
gharveymn
ddf80d09da379150fb094c4b61a674972ee1bbb1
2,235
cpp
C++
addcitydialog.cpp
mholyoak/SampleWeatherReport
0947f865efeff93fcee8abc88d307809a3ab5055
[ "MIT" ]
null
null
null
addcitydialog.cpp
mholyoak/SampleWeatherReport
0947f865efeff93fcee8abc88d307809a3ab5055
[ "MIT" ]
null
null
null
addcitydialog.cpp
mholyoak/SampleWeatherReport
0947f865efeff93fcee8abc88d307809a3ab5055
[ "MIT" ]
null
null
null
#include "addcitydialog.h" #include "ui_addcitydialog.h" #include "openweathermapreporter.h" #include "curlrestrequester.h" CAddCityDialog::CAddCityDialog(QWidget *parent) : QDialog(parent), ui(new Ui::CAddCityDialog) { ui->setupUi(this); auto connected = QObject::connect(ui->_buttonBox, SIGNAL(accepted()), this, SLOT(onSaveButtonClicked())); assert(connected); connected = QObject::connect(ui->_findButton, SIGNAL(clicked()), this, SLOT(onFindButtonClicked())); assert(connected); connected = QObject::connect(ui->_cityList, SIGNAL(itemSelectionChanged()), this, SLOT(onListSelectionChanged())); assert(connected); onListSelectionChanged(); } CAddCityDialog::~CAddCityDialog() { delete ui; } void CAddCityDialog::ShowDialog() { exec(); } std::string CAddCityDialog::GetCityName() const { return _cityName; } std::string CAddCityDialog::GetCountryName() const { return _countryName; } void CAddCityDialog::onSaveButtonClicked() { _cityName = ui->_findCityEdit->text().toUtf8().constData(); auto currentItem = ui->_cityList->currentItem(); if (currentItem) { std::string cityCountry = currentItem->text().toUtf8().constData(); // Parse city and country std::string delimiter(", "); auto delimitePos = cityCountry.find(delimiter); if (delimitePos != std::string::npos) { _cityName = cityCountry.substr(0, delimitePos); _countryName = cityCountry.substr(delimitePos + delimiter.size()); } } } void CAddCityDialog::onFindButtonClicked() { std::string findCity = ui->_findCityEdit->text().toUtf8().constData(); if (!findCity.empty()) { std::shared_ptr<IRestRequester> restRequester = std::make_shared<CCurlRestRequester>(); COpenWeatherMapReporter weatherReporter(restRequester); auto cityList = weatherReporter.FindCity(findCity); for (auto city : cityList) { ui->_cityList->addItem(city.c_str()); } } } void CAddCityDialog::onListSelectionChanged() { auto selectedRow = ui->_cityList->currentRow(); ui->_buttonBox->button( QDialogButtonBox::Save )->setEnabled(selectedRow >= 0); }
26.294118
118
0.674273
mholyoak
fb0539534a06c01742b23cfa49b5a5631bfb7c79
789
cpp
C++
cpp/comm/serialRadio.cpp
MinesJA/meshNetwork
5ffada57c13049cb00c2996fe239cdff6edf6f17
[ "NASA-1.3" ]
133
2017-06-24T02:44:28.000Z
2022-03-25T05:17:00.000Z
cpp/comm/serialRadio.cpp
MinesJA/meshNetwork
5ffada57c13049cb00c2996fe239cdff6edf6f17
[ "NASA-1.3" ]
null
null
null
cpp/comm/serialRadio.cpp
MinesJA/meshNetwork
5ffada57c13049cb00c2996fe239cdff6edf6f17
[ "NASA-1.3" ]
33
2017-06-19T03:24:40.000Z
2022-02-03T20:13:12.000Z
#include "comm/serialRadio.hpp" using std::vector; namespace comm { SerialRadio::SerialRadio(serial::Serial * serialIn, RadioConfig & configIn) : Radio(configIn), serial(serialIn) { }; int SerialRadio::readBytes(bool bufferFlag, int bytesToRead) { // Attempt to read serial bytes vector<uint8_t> newBytes; serial->read(newBytes, bytesToRead); // Process received bytes if (newBytes.size() > 0) { return processRxBytes(newBytes, bufferFlag); } return 0; } unsigned int SerialRadio::sendMsg(vector<uint8_t> & msgBytes) { if (msgBytes.size() > 0) { serial->write(createMsg(msgBytes)); } return 1; // number of messages sent } }
23.205882
81
0.589354
MinesJA
fb0d55b77218e4583a2cee22317f9373758b7477
1,181
hpp
C++
integration/include/integration/Integrator.hpp
gavinband/bingwa
d52e166b3bb6bc32cd32ba63bf8a4a147275eca1
[ "BSL-1.0" ]
3
2021-04-21T05:42:24.000Z
2022-01-26T14:59:43.000Z
integration/include/integration/Integrator.hpp
gavinband/bingwa
d52e166b3bb6bc32cd32ba63bf8a4a147275eca1
[ "BSL-1.0" ]
2
2020-04-09T16:11:04.000Z
2020-11-10T11:18:56.000Z
integration/include/integration/Integrator.hpp
gavinband/qctool
8d8adb45151c91f953fe4a9af00498073b1132ba
[ "BSL-1.0" ]
null
null
null
// Copyright Gavin Band 2008 - 2012. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef INTEGRATION_INTEGRATOR_HPP #define INTEGRATION_INTEGRATOR_HPP #include <exception> namespace integration { class Integrator { protected: Integrator( double desired_error ) ; double desired_error() const { return m_desired_error ; } private: double m_desired_error ; } ; struct IntegrationError: public std::exception { char const* what() const throw() { return "IntegrationError" ; } } ; struct IntervalTooSmallToSubdivideError: public IntegrationError { IntervalTooSmallToSubdivideError( double xmin, double xmax ): m_xmin( xmin ), m_xmax( xmax ) {} char const* what() const throw() { return "IntervalTooSmallToSubdivideError" ; } double xmin() const { return m_xmin ; } double xmax() const { return m_xmax ; } private: double const m_xmin, m_xmax ; } ; struct IntegralIsNaNError: public IntegrationError { IntegralIsNaNError() {} char const* what() const throw() { return "IntegralIsNaNError" ; } } ; } #endif
26.244444
97
0.718036
gavinband
fb17e4223ea432f2a0617b21753de6cd92ab7f36
363
cpp
C++
input/copied_pointer.cpp
xdevkartik/cpp_basics
a6d5a6aca5cdd5b9634c300cfaf2e2914a57aa55
[ "MIT" ]
null
null
null
input/copied_pointer.cpp
xdevkartik/cpp_basics
a6d5a6aca5cdd5b9634c300cfaf2e2914a57aa55
[ "MIT" ]
null
null
null
input/copied_pointer.cpp
xdevkartik/cpp_basics
a6d5a6aca5cdd5b9634c300cfaf2e2914a57aa55
[ "MIT" ]
null
null
null
// Code copied from https://www.w3schools.com/cpp/trycpp.asp?filename=demo_array_change #include <iostream> #include <string> using namespace std; int main() { string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"}; cars[0] = "Opel"; cout << cars[0]; cout << cars[1]; cout << cars[2]; cout << cars[3]<<"\n"; cout << cars; return 0; }
21.352941
87
0.584022
xdevkartik
fb1af50bf4033d4acf39f15458666aa025ad92c4
4,035
cpp
C++
src/stream/preprocess/RtIntensityNorm.cpp
cdla/murfi2
45dba5eb90e7f573f01706a50e584265f0f8ffa7
[ "Apache-2.0" ]
7
2015-02-10T17:00:49.000Z
2021-07-27T22:09:43.000Z
src/stream/preprocess/RtIntensityNorm.cpp
cdla/murfi2
45dba5eb90e7f573f01706a50e584265f0f8ffa7
[ "Apache-2.0" ]
11
2015-02-22T19:15:53.000Z
2021-08-04T17:26:18.000Z
src/stream/preprocess/RtIntensityNorm.cpp
cdla/murfi2
45dba5eb90e7f573f01706a50e584265f0f8ffa7
[ "Apache-2.0" ]
8
2015-07-06T22:31:51.000Z
2019-04-22T21:22:07.000Z
/*========================================================================= * RtIntensityNorm.cpp is the implementation of a class that normalizes the * intensity of subsequent images in a timeseries to match the global signal * of the first. * * Copyright 2007-2013, the MURFI dev team. * * 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.txt * * 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"RtIntensityNorm.h" #include"RtExperiment.h" #include"RtConfigFmriExperiment.h" #include"ace/Mutex.h" #include"RtDataIDs.h" string RtIntensityNorm::moduleString(ID_SPATIALINTENSITYNORM); // default constructor RtIntensityNorm::RtIntensityNorm() : RtStreamComponent() { componentID = moduleString; } // destructor RtIntensityNorm::~RtIntensityNorm() { } // process a configuration option // in // name of the option to process // val text of the option node bool RtIntensityNorm::processOption(const string &name, const string &text, const map<string,string> &attrMap) { // look for known options if(name == "maskRoiID") { maskRoiID = text; return true; } return RtStreamComponent::processOption(name, text, attrMap); } // validate the configuration bool RtIntensityNorm::validateComponentConfig() { bool result = true; if(maskRoiID == "") { cerr << "ERROR: maskRoiID must be set to do intensity normalization" << endl; result = false; } return result; } // process a single acquisition int RtIntensityNorm::process(ACE_Message_Block *mb) { double sum = 0; ACE_TRACE(("RtIntensityNorm::process")); RtStreamMessage *msg = (RtStreamMessage*) mb->rd_ptr(); // get the current image and mask to operate on RtMRIImage *img = (RtMRIImage*) msg->getCurrentData(); RtMaskImage *mask = getMaskFromMessage(*msg); if(img == NULL) { cout << "RtIntensityNorm::process: image passed is NULL" << endl; ACE_DEBUG((LM_INFO, "RtIntensityNorm::process: image passed is NULL\n")); return 0; } if(mask == NULL) { cout << "RtIntensityNorm::process: mask is NULL" << endl; return 0; } // look for first image, compute mean intensity to norm further images by if(needsInit) { ACE_DEBUG((LM_DEBUG, "intensity normalization found first image\n")); // iterate over pixels accumulating intensity double sum = 0; for(unsigned int i = 0; i < img->getNumPix(); i++) { if(mask->getPixel(i)) { sum += img->getPixel(i); } } // store the average intensity in mask meanIntensity = sum/mask->getNumberOfOnVoxels(); needsInit = false; } // compute the mean intensity in the mask for this image // iterate over pixels accumulating intensity sum = 0; for(unsigned int i = 0; i < img->getNumPix(); i++) { if(mask->getPixel(i)) { sum += img->getPixel(i); } } // norm factor short intensityDiff = (short) rint(sum/mask->getNumberOfOnVoxels() - meanIntensity); // allocate a new data image for normalized image RtMRIImage *inorm = new RtMRIImage(*img); inorm->getDataID().setFromInputData(*img,*this); inorm->getDataID().setDataName(NAME_SPATIALINTENSITYNORM_IMG); // subtract the difference for each voxel for(unsigned int i = 0; i < img->getNumPix(); i++) { inorm->setPixel(i, (img->getPixel(i) - intensityDiff > 0) ? (img->getPixel(i) - intensityDiff) : 0); } // set the image id for handling setResult(msg,inorm); return 0; }
28.617021
77
0.652292
cdla
fb1b7e72a44e8c9557c923aaf9404f5c41e26796
2,209
cpp
C++
ME2D/GameController.cpp
kkmzero/microplane-engine
5ee9301b959807e8edefc8ef2ff10551b3b8836f
[ "Zlib" ]
null
null
null
ME2D/GameController.cpp
kkmzero/microplane-engine
5ee9301b959807e8edefc8ef2ff10551b3b8836f
[ "Zlib" ]
null
null
null
ME2D/GameController.cpp
kkmzero/microplane-engine
5ee9301b959807e8edefc8ef2ff10551b3b8836f
[ "Zlib" ]
1
2020-11-09T12:52:18.000Z
2020-11-09T12:52:18.000Z
//============================================================================ // Microplane Engine - ME2D // // Game Controller //---------------------------------------------------------------------------- // Copyright (c) 2018, 2020 Ivan Kmeťo // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // //============================================================================ #include "stdafx.hpp" #include "GameController.hpp" GameLevel* GameController::currentLevel; bool GameController::Loading; HPTimer* GameController::hpTimer; void GameController::Init() { Loading = true; currentLevel = 0; hpTimer = new HPTimer(); } void GameController::LoadInitialLevel(GameLevel* lev) { Loading = true; currentLevel = lev; currentLevel->Load(); Loading = false; } void GameController::SwitchLevel(GameLevel* lev) { Loading = true; currentLevel->UnLoad(); lev->Load(); delete currentLevel; currentLevel = lev; Loading = false; } void GameController::Render() { if (Loading) return; currentLevel->Render(); } void GameController::Update() { if (Loading) return; hpTimer->Update(); currentLevel->Update(hpTimer->GetTimeTotal(), hpTimer->GetTimeDelta()); } void GameController::UnLoad() { Loading = true; currentLevel->UnLoad(); delete currentLevel; delete hpTimer; Loading = false; }
25.988235
79
0.627886
kkmzero
fb254ca5fc4c9e1dd79349668d8a8628bda3dcf0
1,384
hpp
C++
iRODS/lib/api/include/getMiscSvrInfo.hpp
nesi/irods
49eeaf76305fc483f21b1bbfbdd77d540b59cfd2
[ "BSD-3-Clause" ]
null
null
null
iRODS/lib/api/include/getMiscSvrInfo.hpp
nesi/irods
49eeaf76305fc483f21b1bbfbdd77d540b59cfd2
[ "BSD-3-Clause" ]
null
null
null
iRODS/lib/api/include/getMiscSvrInfo.hpp
nesi/irods
49eeaf76305fc483f21b1bbfbdd77d540b59cfd2
[ "BSD-3-Clause" ]
null
null
null
/*** Copyright (c), The Regents of the University of California *** *** For more information please refer to files in the COPYRIGHT directory ***/ #ifndef GET_MISC_SVR_INFO_HPP #define GET_MISC_SVR_INFO_HPP #include "rods.hpp" #include "rcMisc.hpp" #include "procApiRequest.hpp" #include "apiNumber.hpp" /* there is no input struct. Therefore, the inPackInstruct is NULL */ /* definition for server type */ #define RCAT_NOT_ENABLED 0 #define RCAT_ENABLED 1 /* miscSvrInfo_t is the output struct */ typedef struct MiscSvrInfo { int serverType; /* RCAT_ENABLED or RCAT_NOT_ENABLED */ uint serverBootTime; char relVersion[NAME_LEN]; /* the release version number */ char apiVersion[NAME_LEN]; /* the API version number */ char rodsZone[NAME_LEN]; /* the zone of this server */ } miscSvrInfo_t; #define MiscSvrInfo_PI "int serverType; int serverBootTime; str relVersion[NAME_LEN]; str apiVersion[NAME_LEN]; str rodsZone[NAME_LEN];" #if defined(RODS_SERVER) #define RS_GET_MISC_SVR_INFO rsGetMiscSvrInfo /* prototype for the server handler */ int rsGetMiscSvrInfo( rsComm_t *rsComm, miscSvrInfo_t **outSvrInfo ); #else #define RS_GET_MISC_SVR_INFO NULL #endif #ifdef __cplusplus extern "C" { #endif int rcGetMiscSvrInfo( rcComm_t *conn, miscSvrInfo_t **outSvrInfo ); #ifdef __cplusplus } #endif #endif /* GET_MISC_SVR_INFO_H */
26.615385
136
0.741329
nesi
fb2c976b3edd5874de4f278f2008ca6c36f69ea5
2,143
cpp
C++
Source/PluginAiState_Misc1/CAiState_Defend.cpp
shanefarris/CoreGameEngine
5bef275d1cd4e84aa059f2f4f9e97bfa2414d000
[ "MIT" ]
3
2019-04-12T15:22:53.000Z
2022-01-05T02:59:56.000Z
Source/PluginAiState_Misc1/CAiState_Defend.cpp
shanefarris/CoreGameEngine
5bef275d1cd4e84aa059f2f4f9e97bfa2414d000
[ "MIT" ]
null
null
null
Source/PluginAiState_Misc1/CAiState_Defend.cpp
shanefarris/CoreGameEngine
5bef275d1cd4e84aa059f2f4f9e97bfa2414d000
[ "MIT" ]
2
2019-04-10T22:46:21.000Z
2020-05-27T16:21:37.000Z
#include "CAiState_Defend.h" #include "CPlayer.h" #include "CGameObjectManager.h" #include "Ai/CFpsVehicle.h" #include "CInventoryItem.h" #include "CWeapon.h" #include "CTextOutput.h" #include "IO/CoreLogging.h" using namespace Core; using namespace Core::Plugin; CAiState_Defend::CAiState_Defend(CPlayer* Player) : CCharacterState(Player) { m_State = WORKING; m_StateType = EPS_DEFEND; m_StateLabel = "Defend"; m_Level = 1; m_CheckCount = 0; m_GameObjectManager = CGameObjectManager::Instance(); } Core::AI::E_CHARACTER_STATE_OUTCOME CAiState_Defend::Update(f32 elapsedTime) { if(!m_Player->GetAiTarget()) { LookForTargets(); return WORKING; } else if(m_Player->GetAiTarget()->GetPlayer()->GetHealth() <= 0) { // Remove our target, it's dead m_Player->SetAiTarget(nullptr); LookForTargets(); return WORKING; } else { // Check inventory auto item = m_Player->GetCurrentInventoryItem(); if(item) { // Are we in range? CWeapon* weapon = static_cast<CWeapon*>(item); if(weapon) { const f32 d = Vec3Utilities::distance(m_Player->GetPosition(), m_Player->GetAiTarget()->Position()); if(weapon->GetRange() >= d) { auto dir = m_Player->GetAiTarget()->Position() - m_Player->GetPosition(); dir.y = 0.0f; m_Player->SetDirection(dir); m_Player->UseItem(m_Player->GetAiTarget()->GetPlayer()); } } else { // No weapon, can't defend, this should also count against leadership. return FailState(); } } } return WORKING; } Core::AI::E_CHARACTER_STATE_OUTCOME CAiState_Defend::FailState() { m_Player->SetAiTarget(nullptr); m_State = FAILED; return m_State; } void CAiState_Defend::LookForTargets() { auto target = CGameObjectManager::Instance()->GetClosestVisibleEnemy(m_Player); if(target) { m_Player->SetAiTarget(target->GetAiVehicle()); } } CAiState_DefendFactory::CAiState_DefendFactory() { LabelName = "Defend"; Type = EPS_DEFEND; Level = 0; } CAiState_DefendFactory::~CAiState_DefendFactory() { } Core::AI::CCharacterState* CAiState_DefendFactory::GetCharacterState(CPlayer* Player) { return new CAiState_Defend(Player); }
21.867347
104
0.709286
shanefarris
fb2cedc5a8839ba0b02f2f5f708007353c9e81eb
1,699
hpp
C++
src/en/EventSubscriber.hpp
kochol/ari2
ca185191531acc1954cd4acfec2137e32fdb5c2d
[ "MIT" ]
81
2018-12-11T20:48:41.000Z
2022-03-18T22:24:11.000Z
src/en/EventSubscriber.hpp
kochol/ari2
ca185191531acc1954cd4acfec2137e32fdb5c2d
[ "MIT" ]
7
2020-04-19T11:50:39.000Z
2021-11-12T16:08:53.000Z
src/en/EventSubscriber.hpp
kochol/ari2
ca185191531acc1954cd4acfec2137e32fdb5c2d
[ "MIT" ]
4
2019-04-24T11:51:29.000Z
2021-03-10T05:26:33.000Z
#pragma once #include "Entity.hpp" #include "io/IOEvents.hpp" #include "io/Window.hpp" namespace ari::en { struct World; struct FrameData; struct FrameData2D; namespace Internal { class BaseEventSubscriber { public: virtual ~BaseEventSubscriber() = default; }; } // Internal /** * Subclass this as EventSubscriber<EventType> and then call World::Subscribe() in order to Subscribe to events. Make sure * to call World::unsubscribe() or World::unsubscribeAll() when your subscriber is deleted! */ template<typename T> class EventSubscriber: public Internal::BaseEventSubscriber { public: virtual ~EventSubscriber() = default; /** * Called when an event is emitted by the world. */ virtual void Receive(World* world, const T& event) = 0; }; // EventSubscriber namespace events { // Called when a new entity is created. struct OnEntityCreated { EntityHandle entity; }; // Called when an entity is about to be destroyed. struct OnEntityDestroyed { EntityHandle entity; }; // Called when a component is assigned (not necessarily created). template <class T> struct OnComponentAssigned { EntityHandle entity; T* component; }; // Called when a component is removed template <class T> struct OnComponentRemoved { EntityHandle entity; T* component; }; struct OnFrameData { FrameData* frame_data; }; struct OnFrameData2D { FrameData2D* frame_data_2d; }; struct OnInputEvent { ari_event* event; io::WindowHandle window; }; struct OnClientConnected { int client_index; }; struct OnClientDisconnected { int client_index; }; } // events } // ari::en
16.656863
122
0.687463
kochol
fb45288ae611be3f69948bdaced6726194e5ab86
2,409
cpp
C++
Engine/Core/Source/Molten/Renderer/Vulkan/Utility/VulkanMemoryBlock.cpp
jimmiebergmann/CurseEngine
74a0502e36327f893c8e4f3e7cbe5b9d38fbe194
[ "MIT" ]
2
2019-11-11T21:17:14.000Z
2019-11-11T22:07:26.000Z
Engine/Core/Source/Molten/Renderer/Vulkan/Utility/VulkanMemoryBlock.cpp
jimmiebergmann/CurseEngine
74a0502e36327f893c8e4f3e7cbe5b9d38fbe194
[ "MIT" ]
null
null
null
Engine/Core/Source/Molten/Renderer/Vulkan/Utility/VulkanMemoryBlock.cpp
jimmiebergmann/CurseEngine
74a0502e36327f893c8e4f3e7cbe5b9d38fbe194
[ "MIT" ]
1
2020-04-05T03:50:57.000Z
2020-04-05T03:50:57.000Z
/* * MIT License * * Copyright (c) 2021 Jimmie Bergmann * * 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. * */ #if defined(MOLTEN_ENABLE_VULKAN) #include "Molten/Renderer/Vulkan/Utility/VulkanMemoryBlock.hpp" #include "Molten/Renderer/Vulkan/Utility/VulkanMemoryImpl.hpp" MOLTEN_UNSCOPED_ENUM_BEGIN namespace Molten::Vulkan { MemoryBlock::MemoryBlock(const VkDeviceSize size) : deviceMemory(VK_NULL_HANDLE), size(size), firstMemory{}, freeMemories{} {} MemoryBlock::~MemoryBlock() { for (auto memory = std::move(firstMemory); memory;) { memory = std::move(memory->nextMemory); } } MemoryBlock::MemoryBlock(MemoryBlock&& memoryBlock) noexcept : deviceMemory(memoryBlock.deviceMemory), size(memoryBlock.size), firstMemory(std::move(memoryBlock.firstMemory)), freeMemories(std::move(memoryBlock.freeMemories)) { memoryBlock.deviceMemory = VK_NULL_HANDLE; memoryBlock.size = 0; } MemoryBlock& MemoryBlock::operator = (MemoryBlock&& memoryBlock) noexcept { deviceMemory = memoryBlock.deviceMemory; size = memoryBlock.size; firstMemory = std::move(memoryBlock.firstMemory); memoryBlock.deviceMemory = VK_NULL_HANDLE; memoryBlock.size = 0; return *this; } } MOLTEN_UNSCOPED_ENUM_END #endif
31.285714
80
0.714819
jimmiebergmann
fb54b5aeba63882a7589314e638f04b71971ebf7
565
cpp
C++
peg_visitor/peg_visitor.cpp
blackgeorge-boom/parallel_packrat
545ea11688e6102693f4b196be5b34431e1ce3f0
[ "MIT" ]
null
null
null
peg_visitor/peg_visitor.cpp
blackgeorge-boom/parallel_packrat
545ea11688e6102693f4b196be5b34431e1ce3f0
[ "MIT" ]
null
null
null
peg_visitor/peg_visitor.cpp
blackgeorge-boom/parallel_packrat
545ea11688e6102693f4b196be5b34431e1ce3f0
[ "MIT" ]
1
2020-10-06T13:36:06.000Z
2020-10-06T13:36:06.000Z
// // Created by blackgeorge on 4/12/19. // #include "peg_visitor.h" #include "../peg/peg_elements.h" bool NonTerminal::accept(PegVisitor& pegv) { return pegv.visit(*this); } bool Terminal::accept(PegVisitor& pegv) { return pegv.visit(*this); } bool CompositeExpression::accept(PegVisitor& pegv) { return pegv.visit(*this); } bool Empty::accept(PegVisitor& pegv) { return pegv.visit(*this); } bool AnyChar::accept(PegVisitor& pegv) { return pegv.visit(*this); } bool PEG::accept(class PegVisitor& pegv) { return pegv.visit(*this); }
14.868421
50
0.681416
blackgeorge-boom
fb559826b3eb1003f6baed7c0f11e399ea23066a
2,900
cpp
C++
independent_cng/src/filter_ar.cpp
zhang-ray/audio-processing-module
3e779965e1316dbc07c1bd5c547646de8c4350bb
[ "BSD-3-Clause" ]
25
2018-10-11T10:43:52.000Z
2021-11-28T12:43:40.000Z
independent_cng/src/filter_ar.cpp
zhang-ray/audio-processing-module
3e779965e1316dbc07c1bd5c547646de8c4350bb
[ "BSD-3-Clause" ]
1
2018-08-25T14:55:07.000Z
2018-08-25T14:55:07.000Z
independent_cng/src/filter_ar.cpp
zhang-ray/audio-processing-module
3e779965e1316dbc07c1bd5c547646de8c4350bb
[ "BSD-3-Clause" ]
7
2018-08-20T11:32:14.000Z
2021-11-10T07:07:42.000Z
/* * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ /* * This file contains the function WebRtcSpl_FilterAR(). * The description header can be found in signal_processing_library.h * */ #include "signal_processing_library.hpp" size_t WebRtcSpl_FilterAR(const int16_t* a, size_t a_length, const int16_t* x, size_t x_length, int16_t* state, size_t state_length, int16_t* state_low, size_t state_low_length, int16_t* filtered, int16_t* filtered_low, size_t filtered_low_length) { int32_t o; int32_t oLOW; size_t i, j, stop; const int16_t* x_ptr = &x[0]; int16_t* filteredFINAL_ptr = filtered; int16_t* filteredFINAL_LOW_ptr = filtered_low; for (i = 0; i < x_length; i++) { // Calculate filtered[i] and filtered_low[i] const int16_t* a_ptr = &a[1]; int16_t* filtered_ptr = &filtered[i - 1]; int16_t* filtered_low_ptr = &filtered_low[i - 1]; int16_t* state_ptr = &state[state_length - 1]; int16_t* state_low_ptr = &state_low[state_length - 1]; o = (int32_t)(*x_ptr++) << 12; oLOW = (int32_t)0; stop = (i < a_length) ? i + 1 : a_length; for (j = 1; j < stop; j++) { o -= *a_ptr * *filtered_ptr--; oLOW -= *a_ptr++ * *filtered_low_ptr--; } for (j = i + 1; j < a_length; j++) { o -= *a_ptr * *state_ptr--; oLOW -= *a_ptr++ * *state_low_ptr--; } o += (oLOW >> 12); *filteredFINAL_ptr = (int16_t)((o + (int32_t)2048) >> 12); *filteredFINAL_LOW_ptr++ = (int16_t)(o - ((int32_t)(*filteredFINAL_ptr++) << 12)); } // Save the filter state if (x_length >= state_length) { WebRtcSpl_CopyFromEndW16(filtered, x_length, a_length - 1, state); WebRtcSpl_CopyFromEndW16(filtered_low, x_length, a_length - 1, state_low); } else { for (i = 0; i < state_length - x_length; i++) { state[i] = state[i + x_length]; state_low[i] = state_low[i + x_length]; } for (i = 0; i < x_length; i++) { state[state_length - x_length + i] = filtered[i]; state[state_length - x_length + i] = filtered_low[i]; } } return x_length; }
32.222222
82
0.542414
zhang-ray
fb68011b91a9280d7ac08edb96bf32760a521edf
3,728
cpp
C++
tests/src/tests/ut07_ipParser.cpp
microHAL/component-cli
179808696c6e0be65c9006b326c9454118f5c91a
[ "BSD-3-Clause" ]
null
null
null
tests/src/tests/ut07_ipParser.cpp
microHAL/component-cli
179808696c6e0be65c9006b326c9454118f5c91a
[ "BSD-3-Clause" ]
null
null
null
tests/src/tests/ut07_ipParser.cpp
microHAL/component-cli
179808696c6e0be65c9006b326c9454118f5c91a
[ "BSD-3-Clause" ]
null
null
null
/** * @license BSD 3-Clause * @copyright Pawel Okas * @version $Id$ * @brief * * @authors Pawel Okas * * @copyright Copyright (c) 2021, Pawel Okas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <doctest/doctest.h> #include "parsers/ipMaskParser.h" #include "parsers/ipParser.h" using namespace microhal; using namespace cli; using namespace std::literals; TEST_CASE("Test IP Parser") { IPParser ipParser("ip", "ip", "Static network addres."); char buffer[30]; CHECK(ipParser.formatArgument(buffer) == "[--ip ip]"sv); CHECK(ipParser.formatHelpEntry(buffer) == " --ip ip"sv); CHECK(ipParser.parse("0.0.0.0") == Status::Success); CHECK(ipParser.ip() == IP{0, 0, 0, 0}); CHECK(ipParser.parse("255.255.255.255") == Status::Success); CHECK(ipParser.ip() == IP{255, 255, 255, 255}); CHECK(ipParser.parse("1.1.1.1") == Status::Success); CHECK(ipParser.ip() == IP{1, 1, 1, 1}); CHECK(ipParser.parse("10.10.10.10") == Status::Success); CHECK(ipParser.ip() == IP{10, 10, 10, 10}); CHECK(ipParser.parse("100.100.100.100") == Status::Success); CHECK(ipParser.ip() == IP{100, 100, 100, 100}); CHECK(ipParser.parse("192.168.1.1") == Status::Success); CHECK(ipParser.ip() == IP{192, 168, 1, 1}); CHECK(ipParser.parse(" 192.168.1.1 ") == Status::Success); CHECK(ipParser.ip() == IP{192, 168, 1, 1}); CHECK(ipParser.parse("1.1.1. 1") == Status::IncorectArgument); CHECK(ipParser.parse("1.1.1 .1") == Status::IncorectArgument); CHECK(ipParser.parse("1.1 . 1.1") == Status::IncorectArgument); CHECK(ipParser.parse("1.256.1.1") == Status::IncorectArgument); } TEST_CASE("Test IP Mask Parser") { IPMaskParser mask("mask", "mask", "Network mask"); CHECK(mask.parse("255.255.255.0") == Status::Success); CHECK(mask.mask() == IP{255, 255, 255, 0}); CHECK(mask.parse("255.255.255.255") == Status::Success); CHECK(mask.mask() == IP{255, 255, 255, 255}); CHECK(mask.parse("0.0.0.0") == Status::Success); CHECK(mask.mask() == IP{0, 0, 0, 0}); CHECK(mask.parse("255.255.0.255") == Status::Error); CHECK(mask.parse("0.255.255.255") == Status::Error); CHECK(mask.parse("255.255.255.253") == Status::Error); }
41.88764
148
0.681867
microHAL
fb7221eb7159e3f435d3e888c992724739348165
315
hpp
C++
util/Stream.hpp
Xecutor/glider
811bfa91a76cb5dbc918a219681ad2e97cb553fa
[ "MIT" ]
null
null
null
util/Stream.hpp
Xecutor/glider
811bfa91a76cb5dbc918a219681ad2e97cb553fa
[ "MIT" ]
null
null
null
util/Stream.hpp
Xecutor/glider
811bfa91a76cb5dbc918a219681ad2e97cb553fa
[ "MIT" ]
null
null
null
#pragma once #include <sys/types.h> namespace glider::util { class Stream { public: virtual ~Stream() { } virtual size_t Read(void* buf, size_t sz) = 0; virtual size_t Write(const void* buf, size_t sz) = 0; virtual void Skip(size_t sz) = 0; virtual bool isEof() = 0; }; } // namespace glider::util
17.5
55
0.657143
Xecutor
fb74a5a941659ff01c33f3c3335d9eb6910ae8ed
728
cpp
C++
src/QtManagers/Text/nTextReplacement.cpp
Vladimir-Lin/QtManagers
2f906b165f773bff054a8349c577b7d07c2345d9
[ "MIT" ]
null
null
null
src/QtManagers/Text/nTextReplacement.cpp
Vladimir-Lin/QtManagers
2f906b165f773bff054a8349c577b7d07c2345d9
[ "MIT" ]
null
null
null
src/QtManagers/Text/nTextReplacement.cpp
Vladimir-Lin/QtManagers
2f906b165f773bff054a8349c577b7d07c2345d9
[ "MIT" ]
null
null
null
#include <qtmanagers.h> #include "ui_nTextReplacement.h" N::TextReplacement:: TextReplacement ( QWidget * widget , Plan * p ) : Dialog ( widget , p ) , ui ( new Ui::nTextReplacement ) { ui -> setupUi ( this ) ; if (NotNull(plan)) { plan -> setFont ( this ) ; } ; } N::TextReplacement::~TextReplacement (void) { delete ui; } void N::TextReplacement::setSource(QString source) { ui->Source->setPlainText(source) ; } QString N::TextReplacement::sourceString(void) { return ui->Source->toPlainText() ; } QString N::TextReplacement::replaceString(void) { return ui->Replace->toPlainText() ; }
22.060606
68
0.565934
Vladimir-Lin
fb77f825a4ca6091818170c8e0561a3e44e022d0
7,743
cpp
C++
src/structure/implementation/component/CupCfd.cpp
thorbenlouw/CUP-CFD
d06f7673a1ed12bef24de4f1b828ef864fa45958
[ "MIT" ]
3
2021-06-24T10:20:12.000Z
2021-07-18T14:43:19.000Z
src/structure/implementation/component/CupCfd.cpp
thorbenlouw/CUP-CFD
d06f7673a1ed12bef24de4f1b828ef864fa45958
[ "MIT" ]
2
2021-07-22T15:31:03.000Z
2021-07-28T14:27:28.000Z
src/structure/implementation/component/CupCfd.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 * * This file contains the definitions for the CupCfd class */ #include "CupCfd.h" #include "CupCfdAoSMesh.h" #include "CupCfdSoAMesh.h" // JsonCPP - Supplied as standalone in include/io/jsoncpp #include "json.h" #include "json-forwards.h" #include <fstream> #include "BenchmarkKernels.h" #include "BenchmarkConfigKernels.h" #include "BenchmarkConfigKernelsJSON.h" #include "BenchmarkExchange.h" #include "BenchmarkConfigExchange.h" #include "BenchmarkConfigExchangeJSON.h" #include "BenchmarkLinearSolver.h" #include "BenchmarkConfigLinearSolver.h" #include "BenchmarkConfigLinearSolverJSON.h" #include "BenchmarkParticleSystemSimple.h" #include "BenchmarkConfigParticleSystemSimple.h" #include "BenchmarkConfigParticleSystemSimpleJSON.h" #include <iostream> #include "Communicator.h" #include "SparseMatrixCSR.h" namespace cupcfd { template <class M, class I, class T, class L> CupCfd<M,I,T,L>::CupCfd(std::string jsonFilePath, std::shared_ptr<M> meshPtr) : meshPtr(meshPtr) { cupcfd::error::eCodes status; // ToDo: The JSON processing should be moved to a 'source' class. // This will suffice for now however. // Setup an initial system state (e.g. data arrays etc). // For now, will use random values. cupcfd::comm::Communicator comm(MPI_COMM_WORLD); // === Search for benchmark configurations === Json::Value configData; std::ifstream source(jsonFilePath, std::ifstream::binary); source >> configData; // Store all benchmarks under "Benchmarks" field name if(configData.isMember("Benchmarks")) { I size; size = cupcfd::utility::drivers::safeConvertSizeT<I>(configData["Benchmarks"].size()); for(I i = 0; i < size; i++) { Json::Value benchmarkConfigData = configData["Benchmarks"][i]; // === Finite Volume Kernel Benchmarks === if(benchmarkConfigData.isMember("BenchmarkKernels")) { cupcfd::benchmark::BenchmarkConfigKernelsJSON<I,T> fvmBenchJSON(benchmarkConfigData["BenchmarkKernels"]); // Build Finite Volume Kernel Benchmark Config cupcfd::benchmark::BenchmarkConfigKernels<I, T> * fvmBenchConfig; status = fvmBenchJSON.buildBenchmarkConfig(&fvmBenchConfig); if(status != cupcfd::error::E_SUCCESS) { std::cout << "Cannot Parse a Kernel Benchmark Config at " << jsonFilePath << ". Skipping.\n"; } else { // Build Finite Volume Kernel Benchmark if(comm.rank == 0) { std::cout << "Building Kernel Benchmark\n"; } cupcfd::benchmark::BenchmarkKernels<M,I,T,L> * fvmBench; status = fvmBenchConfig->buildBenchmark(&fvmBench, meshPtr); if(status != cupcfd::error::E_SUCCESS) { std::cout << "Error Encountered: Failed to build Kernel Benchmark with current configuration. Please check the provided configuration is correct.\n"; } else { // Run Benchmark status = fvmBench->runBenchmark(); HARD_CHECK_ECODE(status); delete(fvmBench); } delete(fvmBenchConfig); } } // === Exchange Benchmarks === if(benchmarkConfigData.isMember("BenchmarkExchange")) { cupcfd::benchmark::BenchmarkConfigExchangeJSON<I,T> exchangeBenchJSON(benchmarkConfigData["BenchmarkExchange"]); cupcfd::benchmark::BenchmarkConfigExchange<I,T> * exchangeBenchConfig; status = exchangeBenchJSON.buildBenchmarkConfig(&exchangeBenchConfig); if(status != cupcfd::error::E_SUCCESS) { std::cout << "Cannot Parse a Exchange Benchmark Config at " << jsonFilePath << ". Skipping.\n"; } else { // Build Exchange Benchmark Based on Mesh Connectivity Graph if(comm.rank == 0) { std::cout << "Building Exchange Benchmark\n"; } cupcfd::benchmark::BenchmarkExchange<I, T> * exchangeBench; status = exchangeBenchConfig->buildBenchmark(&exchangeBench, *(meshPtr->cellConnGraph)); if(status != cupcfd::error::E_SUCCESS) { std::cout << "Error Encountered: Failed to build Exchange Benchmark with current configuration. Please check the provided configuration is correct.\n"; } else { status = exchangeBench->runBenchmark(); HARD_CHECK_ECODE(status) delete(exchangeBench); } delete(exchangeBenchConfig); } } // === Linear Solver Benchmarks === // Hard-coded to Matrix CSR for now.... // Could make it an option in a config? (Would need to know it before building the object however) if(benchmarkConfigData.isMember("BenchmarkLinearSolver")) { if(comm.rank == 0) { std::cout << "Building Linear Solver Benchmark\n"; } cupcfd::benchmark::BenchmarkConfigLinearSolverJSON<cupcfd::data_structures::SparseMatrixCSR<I,T>,I,T> linearSolverBenchJSON(benchmarkConfigData["BenchmarkLinearSolver"]); cupcfd::benchmark::BenchmarkConfigLinearSolver<cupcfd::data_structures::SparseMatrixCSR<I,T>,I,T> * linearSolverBenchConfig; status = linearSolverBenchJSON.buildBenchmarkConfig(&linearSolverBenchConfig); if(status != cupcfd::error::E_SUCCESS) { std::cout << "Cannot Parse a Linear Solver Benchmark Config at " << jsonFilePath << ". Skipping.\n"; } else { cupcfd::benchmark::BenchmarkLinearSolver<cupcfd::data_structures::SparseMatrixCSR<I,T>,I,T> * linearSolverBench; status = linearSolverBenchConfig->buildBenchmark(&linearSolverBench); if(status != cupcfd::error::E_SUCCESS) { std::cout << "Error Encountered: Failed to build Linear Solver Benchmark with current configuration. Please check the provided configuration is correct.\n"; } else { status = linearSolverBench->runBenchmark(); HARD_CHECK_ECODE(status) delete(linearSolverBench); } delete(linearSolverBenchConfig); } } // === Particle Benchmarks === if(benchmarkConfigData.isMember("BenchmarkParticleSystem")) { if(comm.rank == 0) { std::cout << "Building Simple Particle Benchmark\n"; } // Test for a Particle Simple System Benchmark cupcfd::benchmark::BenchmarkConfigParticleSystemSimpleJSON<M,I,T,L> particleSystemJSON(benchmarkConfigData["BenchmarkParticleSystem"]); // Build Config cupcfd::benchmark::BenchmarkConfigParticleSystemSimple<M,I,T,L> * particleSystemConfig; status = particleSystemJSON.buildBenchmarkConfig(&particleSystemConfig); if(status != cupcfd::error::E_SUCCESS) { std::cout << "Cannot Parse a Particle Benchmark Config at " << jsonFilePath << ". Skipping.\n"; } else { cupcfd::benchmark::BenchmarkParticleSystemSimple<M,I,T,L> * benchmarkParticleSystem; status = particleSystemConfig->buildBenchmark(&benchmarkParticleSystem, meshPtr); if(status != cupcfd::error::E_SUCCESS) { std::cout << "Error Encountered: Failed to build Simple Particle Benchmark with current configuration. Please check the provided configuration is correct.\n"; } else { status = benchmarkParticleSystem->runBenchmark(); HARD_CHECK_ECODE(status) delete(benchmarkParticleSystem); } delete(particleSystemConfig); } } } } } template <class M, class I, class T, class L> CupCfd<M,I,T,L>::~CupCfd() { } } // Explicit Instantiation template class cupcfd::CupCfd<cupcfd::geometry::mesh::CupCfdAoSMesh<int,float,int>, int, float, int>; template class cupcfd::CupCfd<cupcfd::geometry::mesh::CupCfdAoSMesh<int,double,int>, int, double, int>; template class cupcfd::CupCfd<cupcfd::geometry::mesh::CupCfdSoAMesh<int,float,int>, int, float, int>; template class cupcfd::CupCfd<cupcfd::geometry::mesh::CupCfdSoAMesh<int,double,int>, int, double, int>;
35.518349
175
0.699341
thorbenlouw
fb799a61292609499dc6008a072990a68e51751e
538
cpp
C++
luogu/p5878.cpp
freedomDR/coding
310a68077de93ef445ccd2929e90ba9c22a9b8eb
[ "MIT" ]
null
null
null
luogu/p5878.cpp
freedomDR/coding
310a68077de93ef445ccd2929e90ba9c22a9b8eb
[ "MIT" ]
null
null
null
luogu/p5878.cpp
freedomDR/coding
310a68077de93ef445ccd2929e90ba9c22a9b8eb
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); int n; cin >> n; vector<int> arr(n), ans(n); for(auto &v:arr) cin >> v; stack<int> s; arr.push_back(-0x7FFFFFFF); for(int i = 0; i < arr.size(); i++) { while(!s.empty() && arr[s.top()] < arr[i]) { ans[s.top()] = i+1==n+1?0:i+1; s.pop(); } s.push(i); } for(auto v:ans) cout << v << " "; cout << endl; return 0; }
18.551724
50
0.436803
freedomDR
fb847365cf31c2123d85d3994f81859a5dc3ad7c
34
hpp
C++
src/boost_hana_reverse.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_hana_reverse.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_hana_reverse.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/hana/reverse.hpp>
17
33
0.764706
miathedev
fb875d0663df0842904ce2ae81d77705f08f3188
1,721
cpp
C++
cppLearningExercises/Chapter1Helper.cpp
QueeniePun/cppLearningExercises
4c4181573d1b7de9f67acdea1b0fd6d2245b8806
[ "MIT" ]
null
null
null
cppLearningExercises/Chapter1Helper.cpp
QueeniePun/cppLearningExercises
4c4181573d1b7de9f67acdea1b0fd6d2245b8806
[ "MIT" ]
null
null
null
cppLearningExercises/Chapter1Helper.cpp
QueeniePun/cppLearningExercises
4c4181573d1b7de9f67acdea1b0fd6d2245b8806
[ "MIT" ]
null
null
null
#include "Chapter1Helper.h" #include <iostream> using namespace std; void Chapter1Helper::RunExercise1() { // 1.1 Display Welcome to C++, Welcome to CS, and Programming is Fun cout << "Welcome to C++!" << endl; cout << "Welcome to Computer Science!" << endl; cout << "Programming is fun" << endl; } void Chapter1Helper::RunExercise2() { // 1.2 Display Welcome to C++ 5 times PrintMessage(5); } void Chapter1Helper::RunExercise3() { // 1.3 Program to Display pattern cout << " CCCC + +" << endl; cout << " C + +" << endl; cout << "C +++++++ +++++++" << endl; cout << " C + +" << endl; cout << " CCCC + +" << endl; } void Chapter1Helper::RunExercise4() { // 1.4 Print a table cout << "a a^2 a^3" << endl; cout << "1 1 1" << endl; cout << "2 4 8" << endl; cout << "3 9 27" << endl; cout << "4 16 64" << endl; } void Chapter1Helper::RunExercise5() { // 1.5 Write a program that displays math result cout << (9.5 * 4.5 - 2.5 * 3) / (45.5 - 3.5) << endl; } void Chapter1Helper::RunExercise6() { // 1.6 summation of 1+2+3+4+5+6+7+8+9 PrintSummation(9); } void Chapter1Helper::RunExercise7() { // 1.7 Approximating pi cout << 4 * (1.0 - 1.0 / 3.0 + 1.0 / 5 - 1.0 / 7 + 1.0 / 9 - 1.0 / 11 + 1.0 / 13) << endl; } void Chapter1Helper::PrintMessage(int num) { for (int i = 0; i < num; i++) { cout << "Welcome to C++!" << endl; } } void Chapter1Helper::PrintSummation(int num) { int sum = 0; for (int i = 1; i < num + 1; i++) { sum = sum + i; } cout << sum << endl; }
22.644737
94
0.500291
QueeniePun
fb8b5601dda47f1ccd53702d374b735f8b135e09
4,812
cpp
C++
tests/cpp/entity_metadata_validate.cpp
ZondaX/ledger-oasis
08abbff2e2ffc38fbf75ffc772b4a60194d6bc20
[ "Apache-2.0" ]
2
2021-01-10T20:47:11.000Z
2021-03-18T15:24:36.000Z
tests/cpp/entity_metadata_validate.cpp
Zondax/ledger-oasis
47621828556361ae872fefce9d83a0acac7295d5
[ "Apache-2.0" ]
44
2020-01-16T18:09:14.000Z
2022-02-03T21:49:03.000Z
tests/cpp/entity_metadata_validate.cpp
isabella232/app-oasis
570c550a844f6b68f0f76009891b7bbc0b20905b
[ "Apache-2.0" ]
5
2020-04-23T10:59:57.000Z
2022-03-01T11:38:45.000Z
/******************************************************************************* * (c) 2021 ZondaX GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ********************************************************************************/ #include <gmock/gmock.h> #include <fmt/core.h> #include <zxmacros.h> #include "common/parser.h" #include "consumer/parser_impl_con.h" #include "base64.h" #include "common.h" #include "testcases.h" #include "hexutils.h" TEST(EntityMetadataUrl, EntityMetadataUrlsNotStartingWithHTTPS) { url_t url; char buffer[] = "OK"; MEMZERO(&url, sizeof(url_t)); MEMCPY(&url, buffer, strlen(buffer)); url.len = strlen(buffer); auto err = _isValidUrl(&url); ASSERT_EQ(err, parser_invalid_url_format) << parser_getErrorDescription(err); } TEST(EntityMetadataUrl, EntityMetadataUrlsContainsQuery) { url_t url; char buffer[] = "https://example.com?name=lola"; MEMZERO(&url, sizeof(url_t)); MEMCPY(&url, buffer, strlen(buffer)); url.len = strlen(buffer); auto err = _isValidUrl(&url); ASSERT_EQ(err, parser_invalid_url_format) << parser_getErrorDescription(err); } TEST(EntityMetadataUrl, EntityMetadataUrlsContainsFragment) { url_t url; char buffer[] = "https://example.com#lola"; MEMZERO(&url, sizeof(url_t)); MEMCPY(&url, buffer, strlen(buffer)); url.len = strlen(buffer); auto err = _isValidUrl(&url); ASSERT_EQ(err, parser_invalid_url_format) << parser_getErrorDescription(err); } TEST(EntityMetadataUrl, EntityMetadataUrlsContainsSpace) { url_t url; char buffer[] = "https://example.com lola"; MEMZERO(&url, sizeof(url_t)); MEMCPY(&url, buffer, strlen(buffer)); url.len = strlen(buffer); auto err = _isValidUrl(&url); ASSERT_EQ(err, parser_invalid_url_format) << parser_getErrorDescription(err); } TEST(EntityMetadataEmail, EntityMetadataEmailValid) { email_t email; char buffer[] = "me@example.com"; MEMZERO(&email, sizeof(email_t)); MEMCPY(&email, buffer, strlen(buffer)); email.len = strlen(buffer); auto err = _isValidEmail(&email); ASSERT_EQ(err, parser_ok) << parser_getErrorDescription(err); } TEST(EntityMetadataEmail, EntityMetadataEmail2Arobases) { email_t email; char buffer[] = "me@bug@example.com"; MEMZERO(&email, sizeof(email_t)); MEMCPY(&email, buffer, strlen(buffer)); email.len = strlen(buffer); auto err = _isValidEmail(&email); ASSERT_EQ(err, parser_invalid_email_format) << parser_getErrorDescription(err); } TEST(EntityMetadataEmail, EntityMetadataEmailNotValidDomainName) { email_t email; char buffer[] = "me@example"; MEMZERO(&email, sizeof(email_t)); MEMCPY(&email, buffer, strlen(buffer)); email.len = strlen(buffer); auto err = _isValidEmail(&email); ASSERT_EQ(err, parser_invalid_email_format) << parser_getErrorDescription(err); } TEST(EntityMetadataEmail, EntityMetadataEmailNoArobase) { email_t email; char buffer[] = "me.example.com"; MEMZERO(&email, sizeof(email_t)); MEMCPY(&email, buffer, strlen(buffer)); email.len = strlen(buffer); auto err = _isValidEmail(&email); ASSERT_EQ(err, parser_invalid_email_format) << parser_getErrorDescription(err); } TEST(EntityMetadataHandle, EntityMetadataHandle) { handle_t handle; char buffer[] = "example_com"; MEMZERO(&handle, sizeof(handle_t)); MEMCPY(&handle, buffer, strlen(buffer)); handle.len = strlen(buffer); auto err = _isValidHandle(&handle); ASSERT_EQ(err, parser_ok) << parser_getErrorDescription(err); } TEST(EntityMetadataHandle, EntityMetadataHandleNotAllowChar) { handle_t handle; char buffer[] = "example*com"; MEMZERO(&handle, sizeof(handle_t)); MEMCPY(&handle, buffer, strlen(buffer)); handle.len = strlen(buffer); auto err = _isValidHandle(&handle); ASSERT_EQ(err, parser_invalid_handle_format) << parser_getErrorDescription(err); } TEST(EntityMetadataHandle, EntityMetadataHandleNotAllowChar2) { handle_t handle; char buffer[] = "@examplecom"; MEMZERO(&handle, sizeof(handle_t)); MEMCPY(&handle, buffer, strlen(buffer)); handle.len = strlen(buffer); auto err = _isValidHandle(&handle); ASSERT_EQ(err, parser_invalid_handle_format) << parser_getErrorDescription(err); }
35.382353
84
0.688903
ZondaX
fb8d5c3e5361fe501eb66cd222d4b5164233312d
508
cpp
C++
codes/leetcode/BinarySearch.cpp
smmehrab/problem-solving
4aeab1673f18d3270ee5fc9b64ed6805eacf4af5
[ "MIT" ]
null
null
null
codes/leetcode/BinarySearch.cpp
smmehrab/problem-solving
4aeab1673f18d3270ee5fc9b64ed6805eacf4af5
[ "MIT" ]
null
null
null
codes/leetcode/BinarySearch.cpp
smmehrab/problem-solving
4aeab1673f18d3270ee5fc9b64ed6805eacf4af5
[ "MIT" ]
null
null
null
/* ************************************************ username : smmehrab fullname : s.m.mehrabul islam email : mehrab.24csedu.001@gmail.com institute : university of dhaka, bangladesh session : 2017-2018 ************************************************ */ class Solution { public: int search(vector<int>& sorted, int target) { return binary_search(sorted.begin(), sorted.end(), target) ? lower_bound(sorted.begin(), sorted.end(), target) - sorted.begin() : -1; } };
33.866667
141
0.521654
smmehrab
fb8ef345b953529106082728a7199a50df4f1a9b
16,834
cpp
C++
test/glue/atlas/test_atlas_integration.cpp
GridTools/GHEX
1adce924c02cf0553d2ceed69f7dc37e39c7013d
[ "BSD-3-Clause" ]
9
2020-01-30T08:12:40.000Z
2022-01-17T11:18:07.000Z
test/glue/atlas/test_atlas_integration.cpp
ghex-org/GHEX
6eb91410d5c01d36a70f0eb106c1f065df3cee9f
[ "BSD-3-Clause" ]
50
2019-12-19T13:25:56.000Z
2021-09-16T13:57:36.000Z
test/glue/atlas/test_atlas_integration.cpp
ghex-org/GHEX
6eb91410d5c01d36a70f0eb106c1f065df3cee9f
[ "BSD-3-Clause" ]
10
2019-12-10T15:31:36.000Z
2021-07-04T19:31:28.000Z
/* * GridTools * * Copyright (c) 2014-2021, ETH Zurich * All rights reserved. * * Please, refer to the LICENSE file in the root directory. * SPDX-License-Identifier: BSD-3-Clause * */ #include <gtest/gtest.h> #include "../../mpi_runner/mpi_test_fixture.hpp" #include <ghex/config.hpp> #if defined(GHEX_ATLAS_GT_STORAGE_CPU_BACKEND_KFIRST) #include <gridtools/storage/cpu_kfirst.hpp> #elif defined(GHEX_ATLAS_GT_STORAGE_CPU_BACKEND_IFIRST) #include <gridtools/storage/cpu_ifirst.hpp> #endif #ifdef GHEX_CUDACC #include <gridtools/storage/gpu.hpp> #include <gridtools/common/cuda_util.hpp> #include <ghex/device/cuda/runtime.hpp> #endif #include <atlas/grid.h> #include <atlas/mesh.h> #include <atlas/meshgenerator.h> #include <atlas/functionspace.h> #include <atlas/field.h> #include <atlas/array.h> #include <ghex/unstructured/grid.hpp> #include <ghex/unstructured/pattern.hpp> #include <ghex/glue/atlas/field.hpp> #include <ghex/glue/atlas/atlas_user_concepts.hpp> #include <ghex/communication_object.hpp> #include <vector> TEST_F(mpi_test_fixture, atlas_halo_exchange) { using domain_id_t = int; using domain_descriptor_t = ghex::atlas_domain_descriptor<domain_id_t>; using grid_type = ghex::unstructured::grid; #if defined(GHEX_ATLAS_GT_STORAGE_CPU_BACKEND_KFIRST) using storage_traits_cpu = gridtools::storage::cpu_kfirst; #elif defined(GHEX_ATLAS_GT_STORAGE_CPU_BACKEND_IFIRST) using storage_traits_cpu = gridtools::storage::cpu_ifirst; #endif using function_space_t = atlas::functionspace::NodeColumns; using cpu_data_descriptor_t = ghex::atlas_data_descriptor<ghex::cpu, domain_id_t, int, storage_traits_cpu, function_space_t>; ghex::context ctxt{MPI_COMM_WORLD, thread_safe}; int rank = ctxt.rank(); // Global octahedral Gaussian grid atlas::StructuredGrid grid("O256"); // Generate mesh atlas::StructuredMeshGenerator meshgenerator; atlas::Mesh mesh = meshgenerator.generate(grid); // Number of vertical levels std::size_t nb_levels = 10; // Generate functionspace associated to the mesh atlas::functionspace::NodeColumns fs_nodes(mesh, atlas::option::levels(nb_levels) | atlas::option::halo(1)); // Instantiate domain descriptor std::vector<domain_descriptor_t> local_domains{}; domain_descriptor_t d{rank, mesh.nodes().partition(), mesh.nodes().remote_index(), nb_levels}; local_domains.push_back(d); // Instantiate halo generator ghex::atlas_halo_generator<int> hg{}; // Instantiate recv domain ids generator ghex::atlas_recv_domain_ids_gen<int> rdig{}; // Make patterns auto patterns = ghex::make_pattern<grid_type>(ctxt, hg, rdig, local_domains); // Make communication object auto co = ghex::make_communication_object<decltype(patterns)>(ctxt); // Fields creation and initialization auto atlas_field_1 = fs_nodes.createField<int>(atlas::option::name("atlas_field_1")); auto GHEX_field_1 = ghex::atlas::make_field<int, storage_traits_cpu>(fs_nodes, 1); // 1 component / scalar field { auto atlas_field_1_data = atlas::array::make_view<int, 2>(atlas_field_1); auto GHEX_field_1_data = GHEX_field_1.host_view(); for (auto node = 0; node < fs_nodes.nb_nodes(); ++node) { for (auto level = 0; level < fs_nodes.levels(); ++level) { auto value = (rank << 15) + (node << 7) + level; atlas_field_1_data(node, level) = value; GHEX_field_1_data(node, level, 0) = value; // TO DO: hard-coded 3d view. Should be more flexible } } } // GHEX target view auto GHEX_field_1_target_data = GHEX_field_1.target_view(); // Instantiate data descriptor cpu_data_descriptor_t data_1{local_domains.front(), GHEX_field_1_target_data, GHEX_field_1.components()}; // Atlas halo exchange (reference values) fs_nodes.haloExchange(atlas_field_1); // GHEX halo exchange auto h = co.exchange(patterns(data_1)); h.wait(); // test for correctness { auto atlas_field_1_data = atlas::array::make_view<const int, 2>(atlas_field_1); auto GHEX_field_1_data = GHEX_field_1.const_host_view(); for (auto node = 0; node < fs_nodes.nb_nodes(); ++node) { for (auto level = 0; level < fs_nodes.levels(); ++level) { EXPECT_TRUE(GHEX_field_1_data(node, level, 0) == atlas_field_1_data(node, level)); // TO DO: hard-coded 3d view. Should be more flexible } } } #ifdef GHEX_CUDACC using storage_traits_gpu = gridtools::storage::gpu; // Additional data descriptor type for GPU using gpu_data_descriptor_t = ghex::atlas_data_descriptor<ghex::gpu, domain_id_t, int, storage_traits_gpu, function_space_t>; // Additional field for GPU halo exchange auto GHEX_field_1_gpu = ghex::atlas::make_field<int, storage_traits_gpu>(fs_nodes, 1); // 1 component / scalar field { auto GHEX_field_1_gpu_data = GHEX_field_1_gpu.host_view(); for (auto node = 0; node < fs_nodes.nb_nodes(); ++node) { for (auto level = 0; level < fs_nodes.levels(); ++level) { auto value = (rank << 15) + (node << 7) + level; GHEX_field_1_gpu_data(node, level, 0) = value; // TO DO: hard-coded 3d view. Should be more flexible } } } // GHEX target view auto GHEX_field_1_gpu_target_data = GHEX_field_1_gpu.target_view(); // Additional data descriptor for GPU halo exchange gpu_data_descriptor_t data_1_gpu{local_domains.front(), 0, GHEX_field_1_gpu_target_data, GHEX_field_1_gpu.components()}; // GHEX halo exchange on GPU auto h_gpu = co.exchange(patterns(data_1_gpu)); h_gpu.wait(); // Test for correctness { auto atlas_field_1_data = atlas::array::make_view<const int, 2>(atlas_field_1); auto GHEX_field_1_gpu_data = GHEX_field_1_gpu.const_host_view(); for (auto node = 0; node < fs_nodes.nb_nodes(); ++node) { for (auto level = 0; level < fs_nodes.levels(); ++level) { EXPECT_TRUE(GHEX_field_1_gpu_data(node, level, 0) == atlas_field_1_data(node, level)); // TO DO: hard-coded 3d view. Should be more flexible } } } #endif } TEST_F(mpi_test_fixture, atlas_halo_exchange_multiple_patterns) { using domain_id_t = int; using domain_descriptor_t = ghex::atlas_domain_descriptor<domain_id_t>; using grid_type = ghex::unstructured::grid; #if defined(GHEX_ATLAS_GT_STORAGE_CPU_BACKEND_KFIRST) using storage_traits_cpu = gridtools::storage::cpu_kfirst; #elif defined(GHEX_ATLAS_GT_STORAGE_CPU_BACKEND_IFIRST) using storage_traits_cpu = gridtools::storage::cpu_ifirst; #endif using function_space_t = atlas::functionspace::NodeColumns; using cpu_int_data_descriptor_t = ghex::atlas_data_descriptor<ghex::cpu, domain_id_t, int, storage_traits_cpu, function_space_t>; using cpu_double_data_descriptor_t = ghex::atlas_data_descriptor<ghex::cpu, domain_id_t, double, storage_traits_cpu, function_space_t>; ghex::context ctxt{MPI_COMM_WORLD, thread_safe}; int rank = ctxt.rank(); // Global octahedral Gaussian grid atlas::StructuredGrid grid("O256"); // Generate mesh atlas::StructuredMeshGenerator meshgenerator; atlas::Mesh mesh = meshgenerator.generate(grid); // Number of vertical levels std::size_t nb_levels = 10; // Generate functionspace associated to the mesh with halo size = 1 atlas::functionspace::NodeColumns fs_nodes_1(mesh, atlas::option::levels(nb_levels) | atlas::option::halo(1)); // Instantiate domain descriptor (halo size = 1) std::vector<domain_descriptor_t> local_domains_1{}; domain_descriptor_t d_1{rank, mesh.nodes().partition(), mesh.nodes().remote_index(), nb_levels}; local_domains_1.push_back(d_1); // Generate functionspace associated to the mesh with halo size = 2 atlas::functionspace::NodeColumns fs_nodes_2(mesh, atlas::option::levels(nb_levels) | atlas::option::halo(2)); // Instantiate domain descriptor (halo size = 2) std::vector<domain_descriptor_t> local_domains_2{}; domain_descriptor_t d_2{rank, mesh.nodes().partition(), mesh.nodes().remote_index(), nb_levels}; local_domains_2.push_back(d_2); // Instantate halo generator ghex::atlas_halo_generator<int> hg{}; // Instantiate recv domain ids generator ghex::atlas_recv_domain_ids_gen<int> rdig{}; // Make patterns auto patterns_1 = ghex::make_pattern<grid_type>(ctxt, hg, rdig, local_domains_1); auto patterns_2 = ghex::make_pattern<grid_type>(ctxt, hg, rdig, local_domains_2); // Make communication object auto co = ghex::make_communication_object<decltype(patterns_1)>(ctxt); // Fields creation and initialization auto serial_field_1 = ghex::atlas::make_field<int, storage_traits_cpu>(fs_nodes_1, 1); // 1 component / scalar field auto multi_field_1 = ghex::atlas::make_field<int, storage_traits_cpu>(fs_nodes_1, 1); // 1 component / scalar field auto serial_field_2 = ghex::atlas::make_field<double, storage_traits_cpu>(fs_nodes_2, 1); // 1 component / scalar field auto multi_field_2 = ghex::atlas::make_field<double, storage_traits_cpu>(fs_nodes_2, 1); // 1 component / scalar field { auto serial_field_1_data = serial_field_1.host_view(); auto multi_field_1_data = multi_field_1.host_view(); auto serial_field_2_data = serial_field_2.host_view(); auto multi_field_2_data = multi_field_2.host_view(); for (auto node = 0; node < fs_nodes_1.nb_nodes(); ++node) { for (auto level = 0; level < fs_nodes_1.levels(); ++level) { auto value = (rank << 15) + (node << 7) + level; serial_field_1_data(node, level, 0) = value; // TO DO: hard-coded 3d view. Should be more flexible multi_field_1_data(node, level, 0) = value; // TO DO: hard-coded 3d view. Should be more flexible } } for (auto node = 0; node < fs_nodes_2.nb_nodes(); ++node) { for (auto level = 0; level < fs_nodes_2.levels(); ++level) { auto value = ((rank << 15) + (node << 7) + level) * 0.5; serial_field_2_data(node, level, 0) = value; // TO DO: hard-coded 3d view. Should be more flexible multi_field_2_data(node, level, 0) = value; // TO DO: hard-coded 3d view. Should be more flexible } } } // GHEX target views auto serial_field_1_target_data = serial_field_1.target_view(); auto multi_field_1_target_data = multi_field_1.target_view(); auto serial_field_2_target_data = serial_field_2.target_view(); auto multi_field_2_target_data = multi_field_2.target_view(); // Instantiate data descriptors cpu_int_data_descriptor_t serial_data_1{local_domains_1.front(), serial_field_1_target_data, serial_field_1.components()}; cpu_int_data_descriptor_t multi_data_1{local_domains_1.front(), multi_field_1_target_data, multi_field_1.components()}; cpu_double_data_descriptor_t serial_data_2{local_domains_2.front(), serial_field_2_target_data, serial_field_2.components()}; cpu_double_data_descriptor_t multi_data_2{local_domains_2.front(), multi_field_2_target_data, multi_field_2.components()}; // Serial halo exchange auto h_s1 = co.exchange(patterns_1(serial_data_1)); h_s1.wait(); auto h_s2 = co.exchange(patterns_2(serial_data_2)); h_s2.wait(); // Multiple halo exchange auto h_m = co.exchange(patterns_1(multi_data_1), patterns_2(multi_data_2)); h_m.wait(); // Test for correctness { auto serial_field_1_data = serial_field_1.const_host_view(); auto multi_field_1_data = multi_field_1.const_host_view(); auto serial_field_2_data = serial_field_2.const_host_view(); auto multi_field_2_data = multi_field_2.const_host_view(); for (auto node = 0; node < fs_nodes_1.nb_nodes(); ++node) { for (auto level = 0; level < fs_nodes_1.levels(); ++level) { EXPECT_TRUE(serial_field_1_data(node, level, 0) == multi_field_1_data(node, level, 0)); // TO DO: hard-coded 3d view. Should be more flexible } } for (auto node = 0; node < fs_nodes_2.nb_nodes(); ++node) { for (auto level = 0; level < fs_nodes_2.levels(); ++level) { EXPECT_TRUE(serial_field_2_data(node, level, 0) == multi_field_2_data(node, level, 0)); // TO DO: hard-coded 3d view. Should be more flexible } } } #ifdef GHEX_CUDACC using storage_traits_gpu = gridtools::storage::gpu; // Additional data descriptor types for GPU using gpu_int_data_descriptor_t = ghex::atlas_data_descriptor<ghex::gpu, domain_id_t, int, storage_traits_gpu, function_space_t>; using gpu_double_data_descriptor_t = ghex::atlas_data_descriptor<ghex::gpu, domain_id_t, double, storage_traits_gpu, function_space_t>; // Additional fields for GPU halo exchange auto gpu_multi_field_1 = ghex::atlas::make_field<int, storage_traits_gpu>(fs_nodes_1, 1); // 1 component / scalar field auto gpu_multi_field_2 = ghex::atlas::make_field<double, storage_traits_gpu>(fs_nodes_2, 1); // 1 component / scalar field { auto gpu_multi_field_1_data = gpu_multi_field_1.host_view(); auto gpu_multi_field_2_data = gpu_multi_field_2.host_view(); for (auto node = 0; node < fs_nodes_1.nb_nodes(); ++node) { for (auto level = 0; level < fs_nodes_1.levels(); ++level) { auto value = (rank << 15) + (node << 7) + level; gpu_multi_field_1_data(node, level, 0) = value; // TO DO: hard-coded 3d view. Should be more flexible } } for (auto node = 0; node < fs_nodes_2.nb_nodes(); ++node) { for (auto level = 0; level < fs_nodes_2.levels(); ++level) { auto value = ((rank << 15) + (node << 7) + level) * 0.5; gpu_multi_field_2_data(node, level, 0) = value; // TO DO: hard-coded 3d view. Should be more flexible } } } // GHEX target views auto gpu_multi_field_1_target_data = gpu_multi_field_1.target_view(); auto gpu_multi_field_2_target_data = gpu_multi_field_2.target_view(); // Additional data descriptors for GPU halo exchange gpu_int_data_descriptor_t gpu_multi_data_1{local_domains_1.front(), 0, gpu_multi_field_1_target_data, gpu_multi_field_1.components()}; gpu_double_data_descriptor_t gpu_multi_data_2{local_domains_2.front(), 0, gpu_multi_field_2_target_data, gpu_multi_field_2.components()}; // Multiple halo exchange on the GPU auto h_m_gpu = co.exchange(patterns_1(gpu_multi_data_1), patterns_2(gpu_multi_data_2)); h_m_gpu.wait(); // Test for correctness { auto serial_field_1_data = serial_field_1.const_host_view(); auto gpu_multi_field_1_data = gpu_multi_field_1.const_host_view(); auto serial_field_2_data = serial_field_2.const_host_view(); auto gpu_multi_field_2_data = gpu_multi_field_2.const_host_view(); for (auto node = 0; node < fs_nodes_1.nb_nodes(); ++node) { for (auto level = 0; level < fs_nodes_1.levels(); ++level) { EXPECT_TRUE(serial_field_1_data(node, level, 0) == gpu_multi_field_1_data(node, level, 0)); // TO DO: hard-coded 3d view. Should be more flexible } } for (auto node = 0; node < fs_nodes_2.nb_nodes(); ++node) { for (auto level = 0; level < fs_nodes_2.levels(); ++level) { EXPECT_TRUE(serial_field_2_data(node, level, 0) == gpu_multi_field_2_data(node, level, 0)); // TO DO: hard-coded 3d view. Should be more flexible } } } #endif }
39.985748
100
0.649519
GridTools
65267e5da7c542b968e6ebdf45fbecdda3536e00
2,748
cc
C++
test/aws_test.cc
Mnkras/atlas-system-agent
ee1e18002d5938bf83a01dd09125ffa6715a3c87
[ "Apache-2.0" ]
null
null
null
test/aws_test.cc
Mnkras/atlas-system-agent
ee1e18002d5938bf83a01dd09125ffa6715a3c87
[ "Apache-2.0" ]
null
null
null
test/aws_test.cc
Mnkras/atlas-system-agent
ee1e18002d5938bf83a01dd09125ffa6715a3c87
[ "Apache-2.0" ]
null
null
null
#include "../lib/aws.h" #include "../lib/logger.h" #include "measurement_utils.h" #include <fmt/ostream.h> #include <gtest/gtest.h> using namespace atlasagent; using spectator::GetConfiguration; using spectator::Registry; using std::chrono::seconds; using std::chrono::system_clock; static std::string to_str(system_clock::time_point t) { auto tt = system_clock::to_time_t(t); auto ptm = gmtime(&tt); // "2019-09-10T22:22:58Z" return fmt::format("{}-{:02}-{:02}T{:02}:{:02}:{:02}Z", ptm->tm_year + 1900, ptm->tm_mon + 1, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec); } class AwsTest : public Aws { public: explicit AwsTest(Registry* registry) : Aws{registry} {} void update_stats(system_clock::time_point now, system_clock::time_point lastUpdated, system_clock::time_point expires) { auto lastUpdatedStr = to_str(lastUpdated); auto expiresStr = to_str(expires); auto json = fmt::format(R"json( {{ "Code" : "Success", "LastUpdated" : "{}", "Type" : "AWS-HMAC", "AccessKeyId" : "KeyId", "SecretAccessKey" : "SomeSecret", "Token" : "SomeToken", "Expiration" : "{}" }} )json", lastUpdatedStr, expiresStr); Aws::update_stats_from(now, json); } }; // now() truncated to seconds static system_clock::time_point currentTime() { auto seconds_since_epoch = std::chrono::duration_cast<seconds>(system_clock::now().time_since_epoch()).count(); return std::chrono::system_clock::from_time_t(seconds_since_epoch); } TEST(Aws, UpdateStats) { Registry registry(GetConfiguration(), Logger()); auto now = currentTime(); auto lastUpdated = now - seconds{600}; auto expires = now + seconds{900}; AwsTest aws{&registry}; aws.update_stats(now, lastUpdated, expires); auto res = measurements_to_map(registry.Measurements(), "bucket"); EXPECT_DOUBLE_EQ(res["aws.credentialsAge|gauge"], 600.0); EXPECT_DOUBLE_EQ(res["aws.credentialsTtl|gauge"], 900.0); EXPECT_DOUBLE_EQ(res["aws.credentialsTtlBucket|count|30min"], 1.0); expires = now - seconds{1}; aws.update_stats(now, lastUpdated, expires); res = measurements_to_map(registry.Measurements(), "bucket"); EXPECT_DOUBLE_EQ(res["aws.credentialsAge|gauge"], 600.0); EXPECT_DOUBLE_EQ(res["aws.credentialsTtl|gauge"], -1.0); EXPECT_DOUBLE_EQ(res["aws.credentialsTtlBucket|count|expired"], 1.0); expires = now + std::chrono::hours{12}; aws.update_stats(now, lastUpdated, expires); res = measurements_to_map(registry.Measurements(), "bucket"); EXPECT_DOUBLE_EQ(res["aws.credentialsAge|gauge"], 600.0); EXPECT_DOUBLE_EQ(res["aws.credentialsTtl|gauge"], 12 * 3600.0); EXPECT_DOUBLE_EQ(res["aws.credentialsTtlBucket|count|hours"], 1.0); }
32.714286
95
0.691412
Mnkras
652ca62e7d6b86f38916a45036bbfce6ba09e990
27,349
cpp
C++
Game_exe/release_mode/windows/obj/src/Paths.cpp
hisatsuga/Salty-Psyche-Engine-Port-Main
0c6afc6ef57f6f6a8b83ff23bb6a26bb05117ab7
[ "Apache-2.0" ]
null
null
null
Game_exe/release_mode/windows/obj/src/Paths.cpp
hisatsuga/Salty-Psyche-Engine-Port-Main
0c6afc6ef57f6f6a8b83ff23bb6a26bb05117ab7
[ "Apache-2.0" ]
null
null
null
Game_exe/release_mode/windows/obj/src/Paths.cpp
hisatsuga/Salty-Psyche-Engine-Port-Main
0c6afc6ef57f6f6a8b83ff23bb6a26bb05117ab7
[ "Apache-2.0" ]
null
null
null
#include <hxcpp.h> #ifndef INCLUDED_Paths #include <Paths.h> #endif #ifndef INCLUDED_flixel_FlxG #include <flixel/FlxG.h> #endif #ifndef INCLUDED_flixel_graphics_FlxGraphic #include <flixel/graphics/FlxGraphic.h> #endif #ifndef INCLUDED_flixel_graphics_frames_FlxAtlasFrames #include <flixel/graphics/frames/FlxAtlasFrames.h> #endif #ifndef INCLUDED_flixel_graphics_frames_FlxFramesCollection #include <flixel/graphics/frames/FlxFramesCollection.h> #endif #ifndef INCLUDED_flixel_math_FlxRandom #include <flixel/math/FlxRandom.h> #endif #ifndef INCLUDED_flixel_util_IFlxDestroyable #include <flixel/util/IFlxDestroyable.h> #endif #ifndef INCLUDED_haxe_IMap #include <haxe/IMap.h> #endif #ifndef INCLUDED_haxe_ds_StringMap #include <haxe/ds/StringMap.h> #endif #ifndef INCLUDED_lime_utils_Assets #include <lime/utils/Assets.h> #endif #ifndef INCLUDED_openfl_display_BitmapData #include <openfl/display/BitmapData.h> #endif #ifndef INCLUDED_openfl_display_IBitmapDrawable #include <openfl/display/IBitmapDrawable.h> #endif #ifndef INCLUDED_openfl_utils_Assets #include <openfl/utils/Assets.h> #endif #ifndef INCLUDED_sys_FileSystem #include <sys/FileSystem.h> #endif #ifndef INCLUDED_sys_io_File #include <sys/io/File.h> #endif HX_LOCAL_STACK_FRAME(_hx_pos_d75e02b628d1544a_33_setCurrentLevel,"Paths","setCurrentLevel",0x8a8c27ed,"Paths.setCurrentLevel","Paths.hx",33,0x309ea470) HX_LOCAL_STACK_FRAME(_hx_pos_d75e02b628d1544a_37_getPath,"Paths","getPath",0x5f104ffb,"Paths.getPath","Paths.hx",37,0x309ea470) HX_LOCAL_STACK_FRAME(_hx_pos_d75e02b628d1544a_60_getLibraryPath,"Paths","getLibraryPath",0xe56efeaa,"Paths.getLibraryPath","Paths.hx",60,0x309ea470) HX_LOCAL_STACK_FRAME(_hx_pos_d75e02b628d1544a_65_getLibraryPathForce,"Paths","getLibraryPathForce",0xe1e5bae1,"Paths.getLibraryPathForce","Paths.hx",65,0x309ea470) HX_LOCAL_STACK_FRAME(_hx_pos_d75e02b628d1544a_70_getPreloadPath,"Paths","getPreloadPath",0x2fdd9e78,"Paths.getPreloadPath","Paths.hx",70,0x309ea470) HX_LOCAL_STACK_FRAME(_hx_pos_d75e02b628d1544a_75_file,"Paths","file",0x8f872fdc,"Paths.file","Paths.hx",75,0x309ea470) HX_LOCAL_STACK_FRAME(_hx_pos_d75e02b628d1544a_80_txt,"Paths","txt",0x5a3a5910,"Paths.txt","Paths.hx",80,0x309ea470) HX_LOCAL_STACK_FRAME(_hx_pos_d75e02b628d1544a_85_xml,"Paths","xml",0x5a3d5877,"Paths.xml","Paths.hx",85,0x309ea470) HX_LOCAL_STACK_FRAME(_hx_pos_d75e02b628d1544a_90_json,"Paths","json",0x9233a388,"Paths.json","Paths.hx",90,0x309ea470) HX_LOCAL_STACK_FRAME(_hx_pos_d75e02b628d1544a_95_lua,"Paths","lua",0x5a344458,"Paths.lua","Paths.hx",95,0x309ea470) HX_LOCAL_STACK_FRAME(_hx_pos_d75e02b628d1544a_100_sound,"Paths","sound",0x86f65f6f,"Paths.sound","Paths.hx",100,0x309ea470) HX_LOCAL_STACK_FRAME(_hx_pos_d75e02b628d1544a_105_soundRandom,"Paths","soundRandom",0x8e79b2d2,"Paths.soundRandom","Paths.hx",105,0x309ea470) HX_LOCAL_STACK_FRAME(_hx_pos_d75e02b628d1544a_110_music,"Paths","music",0x1684a345,"Paths.music","Paths.hx",110,0x309ea470) HX_LOCAL_STACK_FRAME(_hx_pos_d75e02b628d1544a_115_voices,"Paths","voices",0xbbb84fe1,"Paths.voices","Paths.hx",115,0x309ea470) HX_LOCAL_STACK_FRAME(_hx_pos_d75e02b628d1544a_120_inst,"Paths","inst",0x9186a526,"Paths.inst","Paths.hx",120,0x309ea470) HX_LOCAL_STACK_FRAME(_hx_pos_d75e02b628d1544a_124_image,"Paths","image",0xc392f1fb,"Paths.image","Paths.hx",124,0x309ea470) HX_LOCAL_STACK_FRAME(_hx_pos_d75e02b628d1544a_133_getTextFromFile,"Paths","getTextFromFile",0xab54cb29,"Paths.getTextFromFile","Paths.hx",133,0x309ea470) HX_LOCAL_STACK_FRAME(_hx_pos_d75e02b628d1544a_160_font,"Paths","font",0x8f8bbf2f,"Paths.font","Paths.hx",160,0x309ea470) HX_LOCAL_STACK_FRAME(_hx_pos_d75e02b628d1544a_164_fileExists,"Paths","fileExists",0x907b0ed8,"Paths.fileExists","Paths.hx",164,0x309ea470) HX_LOCAL_STACK_FRAME(_hx_pos_d75e02b628d1544a_178_getSparrowAtlas,"Paths","getSparrowAtlas",0x5a1f05f5,"Paths.getSparrowAtlas","Paths.hx",178,0x309ea470) HX_LOCAL_STACK_FRAME(_hx_pos_d75e02b628d1544a_193_getPackerAtlas,"Paths","getPackerAtlas",0xa8de8c4f,"Paths.getPackerAtlas","Paths.hx",193,0x309ea470) HX_LOCAL_STACK_FRAME(_hx_pos_d75e02b628d1544a_208_addCustomGraphic,"Paths","addCustomGraphic",0x854c9176,"Paths.addCustomGraphic","Paths.hx",208,0x309ea470) HX_LOCAL_STACK_FRAME(_hx_pos_d75e02b628d1544a_221_mods,"Paths","mods",0x942c34d1,"Paths.mods","Paths.hx",221,0x309ea470) HX_LOCAL_STACK_FRAME(_hx_pos_d75e02b628d1544a_224_modsImages,"Paths","modsImages",0x7f77ec69,"Paths.modsImages","Paths.hx",224,0x309ea470) HX_LOCAL_STACK_FRAME(_hx_pos_d75e02b628d1544a_228_modsXml,"Paths","modsXml",0x38d50986,"Paths.modsXml","Paths.hx",228,0x309ea470) HX_LOCAL_STACK_FRAME(_hx_pos_d75e02b628d1544a_231_modsTxt,"Paths","modsTxt",0x38d20a1f,"Paths.modsTxt","Paths.hx",231,0x309ea470) HX_LOCAL_STACK_FRAME(_hx_pos_d75e02b628d1544a_20_boot,"Paths","boot",0x8ce6e592,"Paths.boot","Paths.hx",20,0x309ea470) HX_LOCAL_STACK_FRAME(_hx_pos_d75e02b628d1544a_24_boot,"Paths","boot",0x8ce6e592,"Paths.boot","Paths.hx",24,0x309ea470) void Paths_obj::__construct() { } Dynamic Paths_obj::__CreateEmpty() { return new Paths_obj; } void *Paths_obj::_hx_vtable = 0; Dynamic Paths_obj::__Create(::hx::DynamicArray inArgs) { ::hx::ObjectPtr< Paths_obj > _hx_result = new Paths_obj(); _hx_result->__construct(); return _hx_result; } bool Paths_obj::_hx_isInstanceOf(int inClassId) { return inClassId==(int)0x00000001 || inClassId==(int)0x44c8e46a; } ::String Paths_obj::SOUND_EXT; ::haxe::ds::StringMap Paths_obj::customImagesLoaded; ::String Paths_obj::currentLevel; void Paths_obj::setCurrentLevel(::String name){ HX_STACKFRAME(&_hx_pos_d75e02b628d1544a_33_setCurrentLevel) HXDLIN( 33) ::Paths_obj::currentLevel = name.toLowerCase(); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Paths_obj,setCurrentLevel,(void)) ::String Paths_obj::getPath(::String file,::String type,::String library){ HX_STACKFRAME(&_hx_pos_d75e02b628d1544a_37_getPath) HXLINE( 38) if (::hx::IsNotNull( library )) { HXLINE( 39) return ::Paths_obj::getLibraryPath(file,library); } HXLINE( 41) if (::hx::IsNotNull( ::Paths_obj::currentLevel )) { HXLINE( 43) ::String levelPath = HX_("",00,00,00,00); HXLINE( 44) if ((::Paths_obj::currentLevel != HX_("shared",a5,5e,2b,1d))) { HXLINE( 45) ::String library = ::Paths_obj::currentLevel; HXDLIN( 45) levelPath = (((((HX_("",00,00,00,00) + library) + HX_(":assets/",52,05,4a,2c)) + library) + HX_("/",2f,00,00,00)) + file); HXLINE( 46) if (::openfl::utils::Assets_obj::exists(levelPath,type)) { HXLINE( 47) return levelPath; } } HXLINE( 50) levelPath = ((((HX_("shared",a5,5e,2b,1d) + HX_(":assets/",52,05,4a,2c)) + HX_("shared",a5,5e,2b,1d)) + HX_("/",2f,00,00,00)) + file); HXLINE( 51) if (::openfl::utils::Assets_obj::exists(levelPath,type)) { HXLINE( 52) return levelPath; } } HXLINE( 55) return (HX_("assets/",4c,2a,dc,36) + file); } STATIC_HX_DEFINE_DYNAMIC_FUNC3(Paths_obj,getPath,return ) ::String Paths_obj::getLibraryPath(::String file,::String __o_library){ ::String library = __o_library; if (::hx::IsNull(__o_library)) library = HX_("preload",c9,47,43,35); HX_STACKFRAME(&_hx_pos_d75e02b628d1544a_60_getLibraryPath) HXDLIN( 60) bool _hx_tmp; HXDLIN( 60) if ((library != HX_("preload",c9,47,43,35))) { HXDLIN( 60) _hx_tmp = (library == HX_("default",c1,d8,c3,9b)); } else { HXDLIN( 60) _hx_tmp = true; } HXDLIN( 60) if (_hx_tmp) { HXDLIN( 60) return (HX_("assets/",4c,2a,dc,36) + file); } else { HXDLIN( 60) return (((((HX_("",00,00,00,00) + library) + HX_(":assets/",52,05,4a,2c)) + library) + HX_("/",2f,00,00,00)) + file); } HXDLIN( 60) return null(); } STATIC_HX_DEFINE_DYNAMIC_FUNC2(Paths_obj,getLibraryPath,return ) ::String Paths_obj::getLibraryPathForce(::String file,::String library){ HX_STACKFRAME(&_hx_pos_d75e02b628d1544a_65_getLibraryPathForce) HXDLIN( 65) return (((((HX_("",00,00,00,00) + library) + HX_(":assets/",52,05,4a,2c)) + library) + HX_("/",2f,00,00,00)) + file); } STATIC_HX_DEFINE_DYNAMIC_FUNC2(Paths_obj,getLibraryPathForce,return ) ::String Paths_obj::getPreloadPath(::String file){ HX_STACKFRAME(&_hx_pos_d75e02b628d1544a_70_getPreloadPath) HXDLIN( 70) return (HX_("assets/",4c,2a,dc,36) + file); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Paths_obj,getPreloadPath,return ) ::String Paths_obj::file(::String file,::String __o_type,::String library){ ::String type = __o_type; if (::hx::IsNull(__o_type)) type = HX_("TEXT",ad,94,ba,37); HX_STACKFRAME(&_hx_pos_d75e02b628d1544a_75_file) HXDLIN( 75) return ::Paths_obj::getPath(file,type,library); } STATIC_HX_DEFINE_DYNAMIC_FUNC3(Paths_obj,file,return ) ::String Paths_obj::txt(::String key,::String library){ HX_STACKFRAME(&_hx_pos_d75e02b628d1544a_80_txt) HXDLIN( 80) return ::Paths_obj::getPath(((HX_("data/",c5,0e,88,d4) + key) + HX_(".txt",02,3f,c0,1e)),HX_("TEXT",ad,94,ba,37),library); } STATIC_HX_DEFINE_DYNAMIC_FUNC2(Paths_obj,txt,return ) ::String Paths_obj::xml(::String key,::String library){ HX_STACKFRAME(&_hx_pos_d75e02b628d1544a_85_xml) HXDLIN( 85) return ::Paths_obj::getPath(((HX_("data/",c5,0e,88,d4) + key) + HX_(".xml",69,3e,c3,1e)),HX_("TEXT",ad,94,ba,37),library); } STATIC_HX_DEFINE_DYNAMIC_FUNC2(Paths_obj,xml,return ) ::String Paths_obj::json(::String key,::String library){ HX_STACKFRAME(&_hx_pos_d75e02b628d1544a_90_json) HXDLIN( 90) return ::Paths_obj::getPath(((HX_("data/",c5,0e,88,d4) + key) + HX_(".json",56,f1,d6,c2)),HX_("TEXT",ad,94,ba,37),library); } STATIC_HX_DEFINE_DYNAMIC_FUNC2(Paths_obj,json,return ) ::String Paths_obj::lua(::String key,::String library){ HX_STACKFRAME(&_hx_pos_d75e02b628d1544a_95_lua) HXDLIN( 95) return ::Paths_obj::getPath(((HX_("",00,00,00,00) + key) + HX_(".lua",4a,2a,ba,1e)),HX_("TEXT",ad,94,ba,37),library); } STATIC_HX_DEFINE_DYNAMIC_FUNC2(Paths_obj,lua,return ) ::String Paths_obj::sound(::String key,::String library){ HX_STACKFRAME(&_hx_pos_d75e02b628d1544a_100_sound) HXDLIN( 100) return ::Paths_obj::getPath((((HX_("sounds/",eb,02,a5,b6) + key) + HX_(".",2e,00,00,00)) + HX_("ogg",4f,94,54,00)),HX_("SOUND",af,c4,ba,fe),library); } STATIC_HX_DEFINE_DYNAMIC_FUNC2(Paths_obj,sound,return ) ::String Paths_obj::soundRandom(::String key,int min,int max,::String library){ HX_STACKFRAME(&_hx_pos_d75e02b628d1544a_105_soundRandom) HXDLIN( 105) return ::Paths_obj::sound((key + ::flixel::FlxG_obj::random->_hx_int(min,max,null())),library); } STATIC_HX_DEFINE_DYNAMIC_FUNC4(Paths_obj,soundRandom,return ) ::String Paths_obj::music(::String key,::String library){ HX_STACKFRAME(&_hx_pos_d75e02b628d1544a_110_music) HXDLIN( 110) return ::Paths_obj::getPath((((HX_("music/",ea,bf,1b,3f) + key) + HX_(".",2e,00,00,00)) + HX_("ogg",4f,94,54,00)),HX_("MUSIC",85,08,49,8e),library); } STATIC_HX_DEFINE_DYNAMIC_FUNC2(Paths_obj,music,return ) ::String Paths_obj::voices(::String song){ HX_STACKFRAME(&_hx_pos_d75e02b628d1544a_115_voices) HXDLIN( 115) return (((HX_("songs:assets/songs/",c1,ed,e6,7e) + song.toLowerCase()) + HX_("/Voices.",1e,f6,e5,90)) + HX_("ogg",4f,94,54,00)); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Paths_obj,voices,return ) ::String Paths_obj::inst(::String song){ HX_STACKFRAME(&_hx_pos_d75e02b628d1544a_120_inst) HXDLIN( 120) return (((HX_("songs:assets/songs/",c1,ed,e6,7e) + song.toLowerCase()) + HX_("/Inst.",f9,6e,13,1c)) + HX_("ogg",4f,94,54,00)); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Paths_obj,inst,return ) ::Dynamic Paths_obj::image(::String key,::String library){ HX_STACKFRAME(&_hx_pos_d75e02b628d1544a_124_image) HXLINE( 126) ::flixel::graphics::FlxGraphic imageToReturn = ::Paths_obj::addCustomGraphic(key); HXLINE( 127) if (::hx::IsNotNull( imageToReturn )) { HXLINE( 127) return imageToReturn; } HXLINE( 129) return ::Paths_obj::getPath(((HX_("images/",77,50,74,c1) + key) + HX_(".png",3b,2d,bd,1e)),HX_("IMAGE",3b,57,57,3b),library); } STATIC_HX_DEFINE_DYNAMIC_FUNC2(Paths_obj,image,return ) ::String Paths_obj::getTextFromFile(::String key, ::Dynamic __o_ignoreMods){ ::Dynamic ignoreMods = __o_ignoreMods; if (::hx::IsNull(__o_ignoreMods)) ignoreMods = false; HX_STACKFRAME(&_hx_pos_d75e02b628d1544a_133_getTextFromFile) HXLINE( 135) bool _hx_tmp; HXDLIN( 135) if (!(( (bool)(ignoreMods) ))) { HXLINE( 135) _hx_tmp = ::sys::FileSystem_obj::exists((HX_("mods/",9e,2f,58,0c) + key)); } else { HXLINE( 135) _hx_tmp = false; } HXDLIN( 135) if (_hx_tmp) { HXLINE( 136) return ::sys::io::File_obj::getContent((HX_("mods/",9e,2f,58,0c) + key)); } HXLINE( 138) if (::sys::FileSystem_obj::exists((HX_("assets/",4c,2a,dc,36) + key))) { HXLINE( 139) return ::sys::io::File_obj::getContent((HX_("assets/",4c,2a,dc,36) + key)); } HXLINE( 141) if (::hx::IsNotNull( ::Paths_obj::currentLevel )) { HXLINE( 143) ::String levelPath = HX_("",00,00,00,00); HXLINE( 144) if ((::Paths_obj::currentLevel != HX_("shared",a5,5e,2b,1d))) { HXLINE( 145) ::String library = ::Paths_obj::currentLevel; HXDLIN( 145) levelPath = (((((HX_("",00,00,00,00) + library) + HX_(":assets/",52,05,4a,2c)) + library) + HX_("/",2f,00,00,00)) + key); HXLINE( 146) if (::sys::FileSystem_obj::exists(levelPath)) { HXLINE( 147) return ::sys::io::File_obj::getContent(levelPath); } } HXLINE( 150) levelPath = ((((HX_("shared",a5,5e,2b,1d) + HX_(":assets/",52,05,4a,2c)) + HX_("shared",a5,5e,2b,1d)) + HX_("/",2f,00,00,00)) + key); HXLINE( 151) if (::sys::FileSystem_obj::exists(levelPath)) { HXLINE( 152) return ::sys::io::File_obj::getContent(levelPath); } } HXLINE( 155) return ::lime::utils::Assets_obj::getText(::Paths_obj::getPath(key,HX_("TEXT",ad,94,ba,37),null())); } STATIC_HX_DEFINE_DYNAMIC_FUNC2(Paths_obj,getTextFromFile,return ) ::String Paths_obj::font(::String key){ HX_STACKFRAME(&_hx_pos_d75e02b628d1544a_160_font) HXDLIN( 160) return (HX_("assets/fonts/",37,ff,a5,9c) + key); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Paths_obj,font,return ) bool Paths_obj::fileExists(::String key,::String type, ::Dynamic __o_ignoreMods,::String library){ ::Dynamic ignoreMods = __o_ignoreMods; if (::hx::IsNull(__o_ignoreMods)) ignoreMods = false; HX_STACKFRAME(&_hx_pos_d75e02b628d1544a_164_fileExists) HXLINE( 165) if (::openfl::utils::Assets_obj::exists(::Paths_obj::getPath(key,type,null()),null())) { HXLINE( 166) return true; } HXLINE( 170) if (::sys::FileSystem_obj::exists((HX_("mods/",9e,2f,58,0c) + key))) { HXLINE( 171) return true; } HXLINE( 174) return false; } STATIC_HX_DEFINE_DYNAMIC_FUNC4(Paths_obj,fileExists,return ) ::flixel::graphics::frames::FlxAtlasFrames Paths_obj::getSparrowAtlas(::String key,::String library){ HX_STACKFRAME(&_hx_pos_d75e02b628d1544a_178_getSparrowAtlas) HXLINE( 180) ::flixel::graphics::FlxGraphic imageLoaded = ::Paths_obj::addCustomGraphic(key); HXLINE( 181) bool xmlExists = false; HXLINE( 182) if (::sys::FileSystem_obj::exists((HX_("mods/",9e,2f,58,0c) + ((HX_("images/",77,50,74,c1) + key) + HX_(".xml",69,3e,c3,1e))))) { HXLINE( 183) xmlExists = true; } HXLINE( 186) ::Dynamic _hx_tmp; HXDLIN( 186) if (::hx::IsNotNull( imageLoaded )) { HXLINE( 186) _hx_tmp = imageLoaded; } else { HXLINE( 186) ::flixel::graphics::FlxGraphic imageToReturn = ::Paths_obj::addCustomGraphic(key); HXDLIN( 186) if (::hx::IsNotNull( imageToReturn )) { HXLINE( 186) _hx_tmp = imageToReturn; } else { HXLINE( 186) _hx_tmp = ::Paths_obj::getPath(((HX_("images/",77,50,74,c1) + key) + HX_(".png",3b,2d,bd,1e)),HX_("IMAGE",3b,57,57,3b),library); } } HXDLIN( 186) ::String _hx_tmp1; HXDLIN( 186) if (xmlExists) { HXLINE( 186) _hx_tmp1 = ::sys::io::File_obj::getContent((HX_("mods/",9e,2f,58,0c) + ((HX_("images/",77,50,74,c1) + key) + HX_(".xml",69,3e,c3,1e)))); } else { HXLINE( 186) _hx_tmp1 = ::Paths_obj::getPath(((HX_("images/",77,50,74,c1) + key) + HX_(".xml",69,3e,c3,1e)),HX_("TEXT",ad,94,ba,37),library); } HXDLIN( 186) return ::flixel::graphics::frames::FlxAtlasFrames_obj::fromSparrow(_hx_tmp,_hx_tmp1); } STATIC_HX_DEFINE_DYNAMIC_FUNC2(Paths_obj,getSparrowAtlas,return ) ::flixel::graphics::frames::FlxAtlasFrames Paths_obj::getPackerAtlas(::String key,::String library){ HX_STACKFRAME(&_hx_pos_d75e02b628d1544a_193_getPackerAtlas) HXLINE( 195) ::flixel::graphics::FlxGraphic imageLoaded = ::Paths_obj::addCustomGraphic(key); HXLINE( 196) bool txtExists = false; HXLINE( 197) if (::sys::FileSystem_obj::exists((HX_("mods/",9e,2f,58,0c) + ((HX_("images/",77,50,74,c1) + key) + HX_(".xml",69,3e,c3,1e))))) { HXLINE( 198) txtExists = true; } HXLINE( 201) ::Dynamic _hx_tmp; HXDLIN( 201) if (::hx::IsNotNull( imageLoaded )) { HXLINE( 201) _hx_tmp = imageLoaded; } else { HXLINE( 201) ::flixel::graphics::FlxGraphic imageToReturn = ::Paths_obj::addCustomGraphic(key); HXDLIN( 201) if (::hx::IsNotNull( imageToReturn )) { HXLINE( 201) _hx_tmp = imageToReturn; } else { HXLINE( 201) _hx_tmp = ::Paths_obj::getPath(((HX_("images/",77,50,74,c1) + key) + HX_(".png",3b,2d,bd,1e)),HX_("IMAGE",3b,57,57,3b),library); } } HXDLIN( 201) ::String _hx_tmp1; HXDLIN( 201) if (txtExists) { HXLINE( 201) _hx_tmp1 = ::sys::io::File_obj::getContent((HX_("mods/",9e,2f,58,0c) + ((HX_("images/",77,50,74,c1) + key) + HX_(".xml",69,3e,c3,1e)))); } else { HXLINE( 201) _hx_tmp1 = ::Paths_obj::getPath(((HX_("images/",77,50,74,c1) + key) + HX_(".txt",02,3f,c0,1e)),HX_("TEXT",ad,94,ba,37),library); } HXDLIN( 201) return ::flixel::graphics::frames::FlxAtlasFrames_obj::fromSpriteSheetPacker(_hx_tmp,_hx_tmp1); } STATIC_HX_DEFINE_DYNAMIC_FUNC2(Paths_obj,getPackerAtlas,return ) ::flixel::graphics::FlxGraphic Paths_obj::addCustomGraphic(::String key){ HX_STACKFRAME(&_hx_pos_d75e02b628d1544a_208_addCustomGraphic) HXLINE( 209) if (::sys::FileSystem_obj::exists((HX_("mods/",9e,2f,58,0c) + ((HX_("images/",77,50,74,c1) + key) + HX_(".png",3b,2d,bd,1e))))) { HXLINE( 210) if (!(::Paths_obj::customImagesLoaded->exists(key))) { HXLINE( 211) ::flixel::graphics::FlxGraphic newGraphic = ::flixel::graphics::FlxGraphic_obj::fromBitmapData(::openfl::display::BitmapData_obj::fromFile((HX_("mods/",9e,2f,58,0c) + ((HX_("images/",77,50,74,c1) + key) + HX_(".png",3b,2d,bd,1e)))),null(),null(),null()); HXLINE( 212) newGraphic->persist = true; HXLINE( 213) ::Paths_obj::customImagesLoaded->set(key,newGraphic); } HXLINE( 215) return ( ( ::flixel::graphics::FlxGraphic)(::Paths_obj::customImagesLoaded->get(key)) ); } HXLINE( 217) return null(); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Paths_obj,addCustomGraphic,return ) ::String Paths_obj::mods(::String key){ HX_STACKFRAME(&_hx_pos_d75e02b628d1544a_221_mods) HXDLIN( 221) return (HX_("mods/",9e,2f,58,0c) + key); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Paths_obj,mods,return ) ::String Paths_obj::modsImages(::String key){ HX_STACKFRAME(&_hx_pos_d75e02b628d1544a_224_modsImages) HXDLIN( 224) return (HX_("mods/",9e,2f,58,0c) + ((HX_("images/",77,50,74,c1) + key) + HX_(".png",3b,2d,bd,1e))); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Paths_obj,modsImages,return ) ::String Paths_obj::modsXml(::String key){ HX_STACKFRAME(&_hx_pos_d75e02b628d1544a_228_modsXml) HXDLIN( 228) return (HX_("mods/",9e,2f,58,0c) + ((HX_("images/",77,50,74,c1) + key) + HX_(".xml",69,3e,c3,1e))); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Paths_obj,modsXml,return ) ::String Paths_obj::modsTxt(::String key){ HX_STACKFRAME(&_hx_pos_d75e02b628d1544a_231_modsTxt) HXDLIN( 231) return (HX_("mods/",9e,2f,58,0c) + ((HX_("images/",77,50,74,c1) + key) + HX_(".xml",69,3e,c3,1e))); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Paths_obj,modsTxt,return ) Paths_obj::Paths_obj() { } bool Paths_obj::__GetStatic(const ::String &inName, Dynamic &outValue, ::hx::PropertyAccess inCallProp) { switch(inName.length) { case 3: if (HX_FIELD_EQ(inName,"txt") ) { outValue = txt_dyn(); return true; } if (HX_FIELD_EQ(inName,"xml") ) { outValue = xml_dyn(); return true; } if (HX_FIELD_EQ(inName,"lua") ) { outValue = lua_dyn(); return true; } break; case 4: if (HX_FIELD_EQ(inName,"file") ) { outValue = file_dyn(); return true; } if (HX_FIELD_EQ(inName,"json") ) { outValue = json_dyn(); return true; } if (HX_FIELD_EQ(inName,"inst") ) { outValue = inst_dyn(); return true; } if (HX_FIELD_EQ(inName,"font") ) { outValue = font_dyn(); return true; } if (HX_FIELD_EQ(inName,"mods") ) { outValue = mods_dyn(); return true; } break; case 5: if (HX_FIELD_EQ(inName,"sound") ) { outValue = sound_dyn(); return true; } if (HX_FIELD_EQ(inName,"music") ) { outValue = music_dyn(); return true; } if (HX_FIELD_EQ(inName,"image") ) { outValue = image_dyn(); return true; } break; case 6: if (HX_FIELD_EQ(inName,"voices") ) { outValue = voices_dyn(); return true; } break; case 7: if (HX_FIELD_EQ(inName,"getPath") ) { outValue = getPath_dyn(); return true; } if (HX_FIELD_EQ(inName,"modsXml") ) { outValue = modsXml_dyn(); return true; } if (HX_FIELD_EQ(inName,"modsTxt") ) { outValue = modsTxt_dyn(); return true; } break; case 10: if (HX_FIELD_EQ(inName,"fileExists") ) { outValue = fileExists_dyn(); return true; } if (HX_FIELD_EQ(inName,"modsImages") ) { outValue = modsImages_dyn(); return true; } break; case 11: if (HX_FIELD_EQ(inName,"soundRandom") ) { outValue = soundRandom_dyn(); return true; } break; case 12: if (HX_FIELD_EQ(inName,"currentLevel") ) { outValue = ( currentLevel ); return true; } break; case 14: if (HX_FIELD_EQ(inName,"getLibraryPath") ) { outValue = getLibraryPath_dyn(); return true; } if (HX_FIELD_EQ(inName,"getPreloadPath") ) { outValue = getPreloadPath_dyn(); return true; } if (HX_FIELD_EQ(inName,"getPackerAtlas") ) { outValue = getPackerAtlas_dyn(); return true; } break; case 15: if (HX_FIELD_EQ(inName,"setCurrentLevel") ) { outValue = setCurrentLevel_dyn(); return true; } if (HX_FIELD_EQ(inName,"getTextFromFile") ) { outValue = getTextFromFile_dyn(); return true; } if (HX_FIELD_EQ(inName,"getSparrowAtlas") ) { outValue = getSparrowAtlas_dyn(); return true; } break; case 16: if (HX_FIELD_EQ(inName,"addCustomGraphic") ) { outValue = addCustomGraphic_dyn(); return true; } break; case 18: if (HX_FIELD_EQ(inName,"customImagesLoaded") ) { outValue = ( customImagesLoaded ); return true; } break; case 19: if (HX_FIELD_EQ(inName,"getLibraryPathForce") ) { outValue = getLibraryPathForce_dyn(); return true; } } return false; } bool Paths_obj::__SetStatic(const ::String &inName,Dynamic &ioValue,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 12: if (HX_FIELD_EQ(inName,"currentLevel") ) { currentLevel=ioValue.Cast< ::String >(); return true; } break; case 18: if (HX_FIELD_EQ(inName,"customImagesLoaded") ) { customImagesLoaded=ioValue.Cast< ::haxe::ds::StringMap >(); return true; } } return false; } #ifdef HXCPP_SCRIPTABLE static ::hx::StorageInfo *Paths_obj_sMemberStorageInfo = 0; static ::hx::StaticInfo Paths_obj_sStaticStorageInfo[] = { {::hx::fsString,(void *) &Paths_obj::SOUND_EXT,HX_("SOUND_EXT",b1,35,8c,6f)}, {::hx::fsObject /* ::haxe::ds::StringMap */ ,(void *) &Paths_obj::customImagesLoaded,HX_("customImagesLoaded",2e,80,89,34)}, {::hx::fsString,(void *) &Paths_obj::currentLevel,HX_("currentLevel",8b,fa,6e,b9)}, { ::hx::fsUnknown, 0, null()} }; #endif static void Paths_obj_sMarkStatics(HX_MARK_PARAMS) { HX_MARK_MEMBER_NAME(Paths_obj::SOUND_EXT,"SOUND_EXT"); HX_MARK_MEMBER_NAME(Paths_obj::customImagesLoaded,"customImagesLoaded"); HX_MARK_MEMBER_NAME(Paths_obj::currentLevel,"currentLevel"); }; #ifdef HXCPP_VISIT_ALLOCS static void Paths_obj_sVisitStatics(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(Paths_obj::SOUND_EXT,"SOUND_EXT"); HX_VISIT_MEMBER_NAME(Paths_obj::customImagesLoaded,"customImagesLoaded"); HX_VISIT_MEMBER_NAME(Paths_obj::currentLevel,"currentLevel"); }; #endif ::hx::Class Paths_obj::__mClass; static ::String Paths_obj_sStaticFields[] = { HX_("SOUND_EXT",b1,35,8c,6f), HX_("customImagesLoaded",2e,80,89,34), HX_("currentLevel",8b,fa,6e,b9), HX_("setCurrentLevel",4d,cd,24,d8), HX_("getPath",5b,95,d4,1c), HX_("getLibraryPath",4a,25,d8,33), HX_("getLibraryPathForce",41,90,ac,3f), HX_("getPreloadPath",18,c5,46,7e), HX_("file",7c,ce,bb,43), HX_("txt",70,6e,58,00), HX_("xml",d7,6d,5b,00), HX_("json",28,42,68,46), HX_("lua",b8,59,52,00), HX_("sound",cf,8c,cc,80), HX_("soundRandom",32,28,bc,6a), HX_("music",a5,d0,5a,10), HX_("voices",81,d6,49,5d), HX_("inst",c6,43,bb,45), HX_("image",5b,1f,69,bd), HX_("getTextFromFile",89,70,ed,f8), HX_("font",cf,5d,c0,43), HX_("fileExists",78,65,64,a0), HX_("getSparrowAtlas",55,ab,b7,a7), HX_("getPackerAtlas",ef,b2,47,f7), HX_("addCustomGraphic",16,a0,44,1d), HX_("mods",71,d3,60,48), HX_("modsImages",09,43,61,8f), HX_("modsXml",e6,4e,99,f6), HX_("modsTxt",7f,4f,96,f6), ::String(null()) }; void Paths_obj::__register() { Paths_obj _hx_dummy; Paths_obj::_hx_vtable = *(void **)&_hx_dummy; ::hx::Static(__mClass) = new ::hx::Class_obj(); __mClass->mName = HX_("Paths",0e,7b,84,50); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &Paths_obj::__GetStatic; __mClass->mSetStaticField = &Paths_obj::__SetStatic; __mClass->mMarkFunc = Paths_obj_sMarkStatics; __mClass->mStatics = ::hx::Class_obj::dupFunctions(Paths_obj_sStaticFields); __mClass->mMembers = ::hx::Class_obj::dupFunctions(0 /* sMemberFields */); __mClass->mCanCast = ::hx::TCanCast< Paths_obj >; #ifdef HXCPP_VISIT_ALLOCS __mClass->mVisitFunc = Paths_obj_sVisitStatics; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = Paths_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = Paths_obj_sStaticStorageInfo; #endif ::hx::_hx_RegisterClass(__mClass->mName, __mClass); } void Paths_obj::__boot() { { HX_STACKFRAME(&_hx_pos_d75e02b628d1544a_20_boot) HXDLIN( 20) SOUND_EXT = HX_("ogg",4f,94,54,00); } { HX_GC_STACKFRAME(&_hx_pos_d75e02b628d1544a_24_boot) HXDLIN( 24) customImagesLoaded = ::haxe::ds::StringMap_obj::__alloc( HX_CTX ); } }
44.254045
271
0.691214
hisatsuga
6531679fe42e8c88e8ac466450617d898fed738a
15,993
cc
C++
xmysqlnd/xmysqlnd_table.cc
kirmorozov/pecl-database-mysql_xdevapi
214e0b13dcea17dfa86000092860e3fb35f02257
[ "PHP-3.01" ]
14
2017-11-16T03:13:31.000Z
2022-03-10T14:59:53.000Z
xmysqlnd/xmysqlnd_table.cc
kirmorozov/pecl-database-mysql_xdevapi
214e0b13dcea17dfa86000092860e3fb35f02257
[ "PHP-3.01" ]
8
2018-03-02T06:08:27.000Z
2022-01-18T10:34:43.000Z
xmysqlnd/xmysqlnd_table.cc
kirmorozov/pecl-database-mysql_xdevapi
214e0b13dcea17dfa86000092860e3fb35f02257
[ "PHP-3.01" ]
18
2018-03-01T13:45:16.000Z
2022-03-10T06:30:02.000Z
/* +----------------------------------------------------------------------+ | PHP Version 7 | +----------------------------------------------------------------------+ | Copyright (c) The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andrey Hristov <andrey@php.net> | +----------------------------------------------------------------------+ */ #include "php_api.h" #include "mysqlnd_api.h" extern "C" { #include <ext/json/php_json_parser.h> } #include "xmysqlnd.h" #include "xmysqlnd_driver.h" #include "xmysqlnd_session.h" #include "xmysqlnd_schema.h" #include "xmysqlnd_stmt.h" #include "xmysqlnd_stmt_result_meta.h" #include "xmysqlnd_table.h" #include "xmysqlnd_utils.h" #include <vector> #include "util/exceptions.h" #include "util/pb_utils.h" namespace mysqlx { namespace drv { xmysqlnd_table::xmysqlnd_table(const MYSQLND_CLASS_METHODS_TYPE(xmysqlnd_object_factory) * const cur_obj_factory, xmysqlnd_schema * const cur_schema, const util::string_view& cur_table_name, zend_bool is_persistent) { DBG_ENTER("xmysqlnd_table::st_xmysqlnd_table_data"); if (!(schema = cur_schema->get_reference())) { throw util::xdevapi_exception(util::xdevapi_exception::Code::table_creation_failed); } persistent = is_persistent; table_name = cur_table_name; DBG_INF_FMT("name=[%d]%*s", table_name.length(), table_name.length(), table_name.c_str()); object_factory = cur_obj_factory; } //------------------------------------------------------------------------------ struct table_or_view_var_binder_ctx { util::string_view schema_name; util::string_view table_name; unsigned int counter; }; static const enum_hnd_func_status table_op_var_binder( void* context, XMYSQLND_SESSION session, XMYSQLND_STMT_OP__EXECUTE* const stmt_execute) { DBG_ENTER("table_op_var_binder"); table_or_view_var_binder_ctx* ctx = static_cast<table_or_view_var_binder_ctx*>(context); Mysqlx::Sql::StmtExecute& stmt_message = xmysqlnd_stmt_execute__get_pb_msg(stmt_execute); util::pb::Object* stmt_obj{util::pb::add_object_arg(stmt_message)}; util::pb::add_field_to_object("schema", ctx->schema_name, stmt_obj); util::pb::add_field_to_object("pattern", ctx->table_name, stmt_obj); DBG_RETURN(HND_PASS); } struct table_or_view_op_ctx { util::string_view expected_name; zval* exists; }; const enum_hnd_func_status table_or_view_exists_in_database_op( void * context, XMYSQLND_SESSION session, xmysqlnd_stmt * const /*stmt*/, const XMYSQLND_STMT_RESULT_META * const /*meta*/, const zval * const row, MYSQLND_STATS * const /*stats*/, MYSQLND_ERROR_INFO * const /*error_info*/) { table_or_view_op_ctx* ctx = static_cast<table_or_view_op_ctx*>(context); DBG_ENTER("table_or_view_exists_in_database_op"); if (ctx && row) { const util::string_view object_name{ Z_STRVAL(row[0]), Z_STRLEN(row[0]) }; const util::string_view object_type{ Z_STRVAL(row[1]), Z_STRLEN(row[1]) }; if ((object_name == ctx->expected_name) && (is_table_object_type(object_type) || is_view_object_type(object_type))) { ZVAL_TRUE(ctx->exists); DBG_RETURN(HND_PASS); } } DBG_RETURN(HND_AGAIN); } enum_func_status xmysqlnd_table::exists_in_database( st_xmysqlnd_session_on_error_bind on_error, zval* exists) { DBG_ENTER("xmysqlnd_table::exists_in_database"); ZVAL_FALSE(exists); enum_func_status ret; constexpr util::string_view query = "list_objects"; xmysqlnd_schema * schema = get_schema(); auto session = schema->get_session(); table_or_view_var_binder_ctx var_binder_ctx = { schema->get_name(), get_name(), 0 }; const st_xmysqlnd_session_query_bind_variable_bind var_binder = { table_op_var_binder, &var_binder_ctx }; table_or_view_op_ctx on_row_ctx = { get_name(), exists }; const st_xmysqlnd_session_on_row_bind on_row = { table_or_view_exists_in_database_op, &on_row_ctx }; ret = session->query_cb( namespace_mysqlx, query, var_binder, noop__on_result_start, on_row, noop__on_warning, on_error, noop__on_result_end, noop__on_statement_ok); DBG_RETURN(ret); } //------------------------------------------------------------------------------ const enum_hnd_func_status check_is_view_op( void * context, XMYSQLND_SESSION session, xmysqlnd_stmt * const /*stmt*/, const XMYSQLND_STMT_RESULT_META * const /*meta*/, const zval * const row, MYSQLND_STATS * const /*stats*/, MYSQLND_ERROR_INFO * const /*error_info*/) { table_or_view_op_ctx* ctx = static_cast<table_or_view_op_ctx*>(context); DBG_ENTER("check_is_view_op"); if (ctx && row) { const util::string_view object_name{ Z_STRVAL(row[0]), Z_STRLEN(row[0]) }; const util::string_view object_type{ Z_STRVAL(row[1]), Z_STRLEN(row[1]) }; if ((object_name == ctx->expected_name) && is_view_object_type(object_type)) { ZVAL_TRUE(ctx->exists); DBG_RETURN(HND_PASS); } } DBG_RETURN(HND_AGAIN); } enum_func_status xmysqlnd_table::is_view( st_xmysqlnd_session_on_error_bind on_error, zval* exists) { DBG_ENTER("xmysqlnd_table::is_view"); ZVAL_FALSE(exists); enum_func_status ret; constexpr util::string_view query = "list_objects"; xmysqlnd_schema * schema = get_schema(); auto session = schema->get_session(); table_or_view_var_binder_ctx var_binder_ctx = { schema->get_name(), get_name(), 0 }; const st_xmysqlnd_session_query_bind_variable_bind var_binder = { table_op_var_binder, &var_binder_ctx }; table_or_view_op_ctx on_row_ctx = { get_name(), exists }; const st_xmysqlnd_session_on_row_bind on_row = { check_is_view_op, &on_row_ctx }; ret = session->query_cb( namespace_mysqlx, query, var_binder, noop__on_result_start, on_row, noop__on_warning, on_error, noop__on_result_end, noop__on_statement_ok); DBG_RETURN(ret); } //------------------------------------------------------------------------------ struct st_table_sql_single_result_ctx { zval* result; }; const enum_hnd_func_status table_sql_single_result_op_on_row( void * context, XMYSQLND_SESSION session, xmysqlnd_stmt * const /*stmt*/, const XMYSQLND_STMT_RESULT_META * const /*meta*/, const zval * const row, MYSQLND_STATS * const /*stats*/, MYSQLND_ERROR_INFO * const /*error_info*/) { st_table_sql_single_result_ctx* ctx = (st_table_sql_single_result_ctx*) context; DBG_ENTER("table_sql_single_result_op_on_row"); if (ctx && row) { ZVAL_COPY_VALUE(ctx->result, &row[0]); DBG_RETURN(HND_PASS); } else { DBG_RETURN(HND_AGAIN); } } enum_func_status xmysqlnd_table::count( st_xmysqlnd_session_on_error_bind on_error, zval* counter) { DBG_ENTER("xmysqlnd_table::count"); ZVAL_LONG(counter, 0); enum_func_status ret; xmysqlnd_schema * schema = get_schema(); auto session = schema->get_session(); char* query_str; mnd_sprintf(&query_str, 0, "SELECT COUNT(*) FROM %s.%s", schema->get_name().data(), get_name().data()); if (!query_str) { DBG_RETURN(FAIL); } const util::string_view query{query_str, strlen(query_str)}; st_table_sql_single_result_ctx on_row_ctx = { counter }; const st_xmysqlnd_session_on_row_bind on_row = { table_sql_single_result_op_on_row, &on_row_ctx }; ret = session->query_cb(namespace_sql, query, noop__var_binder, noop__on_result_start, on_row, noop__on_warning, on_error, noop__on_result_end, noop__on_statement_ok); mnd_sprintf_free(query_str); DBG_RETURN(ret); } xmysqlnd_stmt * xmysqlnd_table::insert(XMYSQLND_CRUD_TABLE_OP__INSERT * op) { DBG_ENTER("xmysqlnd_table::opinsert"); xmysqlnd_stmt * stmt{nullptr}; auto session = get_schema()->get_session(); if (!op) { DBG_RETURN(stmt); } if ( FAIL == xmysqlnd_crud_table_insert__finalize_bind(op)) { DBG_RETURN(stmt); } if (xmysqlnd_crud_table_insert__is_initialized(op)) { st_xmysqlnd_message_factory msg_factory{ session->data->create_message_factory() }; st_xmysqlnd_msg__table_insert table_insert = msg_factory.get__table_insert(&msg_factory); if (PASS == table_insert.send_insert_request(&table_insert, xmysqlnd_crud_table_insert__get_protobuf_message(op))) { stmt = session->create_statement_object(session); stmt->get_msg_stmt_exec() = msg_factory.get__sql_stmt_execute(&msg_factory); } DBG_INF(stmt != nullptr ? "PASS" : "FAIL"); } DBG_RETURN(stmt); } xmysqlnd_stmt * xmysqlnd_table::opdelete(XMYSQLND_CRUD_TABLE_OP__DELETE * op) { DBG_ENTER("xmysqlnd_table::opdelete"); xmysqlnd_stmt * stmt{nullptr}; auto session = get_schema()->get_session(); drv::Prepare_stmt_data* ps_data = &session->get_data()->ps_data; if (!op) { DBG_RETURN(stmt); } if( false == ps_data->is_ps_supported() ) { if ( !ps_data->is_bind_finalized( op->ps_message_id ) && FAIL == xmysqlnd_crud_table_delete__finalize_bind(op)) { DBG_RETURN(stmt); } if (xmysqlnd_crud_table_delete__is_initialized(op)) { st_xmysqlnd_message_factory msg_factory{ session->data->create_message_factory() }; st_xmysqlnd_msg__collection_ud table_ud = msg_factory.get__collection_ud(&msg_factory); if (PASS == table_ud.send_delete_request(&table_ud, xmysqlnd_crud_table_delete__get_protobuf_message(op))) { stmt = session->create_statement_object(session); stmt->get_msg_stmt_exec() = msg_factory.get__sql_stmt_execute(&msg_factory); } DBG_INF(stmt != nullptr ? "PASS" : "FAIL"); } } else { auto res = ps_data->add_message( op->message, static_cast<uint32_t>(op->bound_values.size()) ); if (FAIL == xmysqlnd_crud_table_delete__finalize_bind(op)){ DBG_RETURN(stmt); } op->ps_message_id = res.second; ps_data->set_finalized_bind( res.second, true ); if( res.first ) { if( !ps_data->send_prepare_msg( res.second ) ) { if( ps_data->is_ps_supported() == false ) { return opdelete(op); } DBG_RETURN(stmt); } } if (!xmysqlnd_crud_table_delete__is_initialized(op)) { DBG_RETURN(stmt); } if( ps_data->prepare_msg_delivered( res.second ) && ps_data->bind_values( res.second, op->bound_values ) ) { stmt = ps_data->send_execute_msg( res.second ); } } DBG_RETURN(stmt); } xmysqlnd_stmt * xmysqlnd_table::update(XMYSQLND_CRUD_TABLE_OP__UPDATE * op) { DBG_ENTER("xmysqlnd_table::update"); xmysqlnd_stmt * stmt{nullptr}; auto session = get_schema()->get_session(); drv::Prepare_stmt_data* ps_data = &session->get_data()->ps_data; if (!op) { DBG_RETURN(stmt); } if( false == ps_data->is_ps_supported() ) { if ( !ps_data->is_bind_finalized( op->ps_message_id ) && FAIL == xmysqlnd_crud_table_update__finalize_bind(op)) { DBG_RETURN(stmt); } if (xmysqlnd_crud_table_update__is_initialized(op)) { st_xmysqlnd_message_factory msg_factory{ session->data->create_message_factory() }; st_xmysqlnd_msg__collection_ud table_ud = msg_factory.get__collection_ud(&msg_factory); if (PASS == table_ud.send_update_request(&table_ud, xmysqlnd_crud_table_update__get_protobuf_message(op))) { stmt = session->create_statement_object(session); stmt->get_msg_stmt_exec() = msg_factory.get__sql_stmt_execute(&msg_factory); } DBG_INF(stmt != nullptr ? "PASS" : "FAIL"); } } else { auto res = ps_data->add_message( op->message, static_cast<uint32_t>(op->bound_values.size())); if (FAIL == xmysqlnd_crud_table_update__finalize_bind(op)){ DBG_RETURN(stmt); } op->ps_message_id = res.second; ps_data->set_finalized_bind( res.second, true ); if( res.first ) { if( !ps_data->send_prepare_msg( res.second ) ) { if( ps_data->is_ps_supported() == false ) { return update(op); } DBG_RETURN(stmt); } } if (!xmysqlnd_crud_table_update__is_initialized(op)) { DBG_RETURN(stmt); } if( ps_data->prepare_msg_delivered( res.second ) && ps_data->bind_values( res.second, op->bound_values ) ) { stmt = ps_data->send_execute_msg( res.second ); } } DBG_RETURN(stmt); } xmysqlnd_stmt * xmysqlnd_table::select(XMYSQLND_CRUD_TABLE_OP__SELECT * op) { DBG_ENTER("xmysqlnd_table::select"); xmysqlnd_stmt * stmt{nullptr}; auto session = get_schema()->get_session(); drv::Prepare_stmt_data* ps_data = &session->get_data()->ps_data; if (!op) { DBG_RETURN(stmt); } if( false == ps_data->is_ps_supported() ) { if ( !ps_data->is_bind_finalized( op->ps_message_id ) && FAIL == xmysqlnd_crud_table_select__finalize_bind(op)) { DBG_RETURN(stmt); } if (xmysqlnd_crud_table_select__is_initialized(op)) { stmt = session->create_statement_object(session); if (FAIL == stmt->send_raw_message(stmt, xmysqlnd_crud_table_select__get_protobuf_message(op), session->get_data()->stats, session->get_data()->error_info)) { xmysqlnd_stmt_free(stmt, session->get_data()->stats, session->get_data()->error_info); stmt = nullptr; } } } else { auto res = ps_data->add_message( op->message, static_cast<uint32_t>(op->bound_values.size()) ); if (FAIL == xmysqlnd_crud_table_select__finalize_bind(op)) { DBG_RETURN(stmt); } if( res.first ) { if( !ps_data->send_prepare_msg( res.second ) ) { if( ps_data->is_ps_supported() == false ) { return select(op); } DBG_RETURN(stmt); } } if (!xmysqlnd_crud_table_select__is_initialized(op)) { DBG_RETURN(stmt); } if( ps_data->prepare_msg_delivered( res.second ) && ps_data->bind_values( res.second, op->bound_values ) ) { stmt = ps_data->send_execute_msg( res.second ); } } DBG_RETURN(stmt); } xmysqlnd_table * xmysqlnd_table::get_reference() { DBG_ENTER("xmysqlnd_table::get_reference"); ++refcount; DBG_INF_FMT("new_refcount=%u", refcount); DBG_RETURN(this); } enum_func_status xmysqlnd_table::free_reference(MYSQLND_STATS * stats, MYSQLND_ERROR_INFO * error_info) { enum_func_status ret{PASS}; DBG_ENTER("xmysqlnd_table::free_reference"); DBG_INF_FMT("old_refcount=%u", refcount); if (!(--refcount)) { cleanup(stats, error_info); } DBG_RETURN(ret); } void xmysqlnd_table::free_contents() { DBG_ENTER("xmysqlnd_table::free_contents"); table_name.clear(); DBG_VOID_RETURN; } void xmysqlnd_table::cleanup(MYSQLND_STATS * stats, MYSQLND_ERROR_INFO * error_info) { DBG_ENTER("xmysqlnd_table::dtor"); free_contents(); xmysqlnd_schema_free(schema, stats, error_info); DBG_VOID_RETURN; } PHP_MYSQL_XDEVAPI_API xmysqlnd_table * xmysqlnd_table_create(xmysqlnd_schema * schema, const util::string_view& table_name, const zend_bool persistent, const MYSQLND_CLASS_METHODS_TYPE(xmysqlnd_object_factory) * const object_factory, MYSQLND_STATS * const stats, MYSQLND_ERROR_INFO * const error_info) { xmysqlnd_table* ret{nullptr}; DBG_ENTER("xmysqlnd_table_create"); if (!table_name.empty()) { ret = object_factory->get_table(object_factory, schema, table_name, persistent, stats, error_info); if (ret) { ret = ret->get_reference(); } } DBG_RETURN(ret); } PHP_MYSQL_XDEVAPI_API void xmysqlnd_table_free(xmysqlnd_table * const table, MYSQLND_STATS * stats, MYSQLND_ERROR_INFO * error_info) { DBG_ENTER("xmysqlnd_table_free"); if (table) { table->free_reference(stats, error_info); } DBG_VOID_RETURN; } } // namespace drv } // namespace mysqlx
28.356383
116
0.691052
kirmorozov
65322af968f6f86c5a2dcc166214d2194ccca598
506
cpp
C++
Laborator 06/Tema/Dacia.cpp
Vladimir-Anfimov/oop-2022
8c4fc62960dcc3d06935a9b662b5b72bba275b6c
[ "MIT" ]
null
null
null
Laborator 06/Tema/Dacia.cpp
Vladimir-Anfimov/oop-2022
8c4fc62960dcc3d06935a9b662b5b72bba275b6c
[ "MIT" ]
null
null
null
Laborator 06/Tema/Dacia.cpp
Vladimir-Anfimov/oop-2022
8c4fc62960dcc3d06935a9b662b5b72bba275b6c
[ "MIT" ]
null
null
null
#include "Dacia.h" Dacia::Dacia() : Car(56.3, 8.3) { this->average_speed[(int)Weather::Rain] = 78; this->average_speed[(int) Weather::Snow] = 45; this->average_speed[(int) Weather::Sunny] = 103; } const char* Dacia::getName() { return "Dacia"; } double Dacia::getFuelCapacity() { return this->fuel_capacity; } double Dacia::getFuelConsumption() { return this->fuel_consumption; } double Dacia::getAverageSpeed(Weather weather) { return this->average_speed[(int)weather]; }
21.083333
52
0.673913
Vladimir-Anfimov
6532b4a4f46219b8bc564ca8e035fe912c257fba
425
cpp
C++
201712/20171201/main.cpp
Heliovic/My-CCF_CSP-Answer
089ce2601bee3d3d5dc463486dd4192f087aa7f0
[ "MIT" ]
4
2019-03-16T14:42:08.000Z
2019-07-18T13:57:29.000Z
201712/20171201/main.cpp
Heliovic/My_CCF-CSP_Answer
089ce2601bee3d3d5dc463486dd4192f087aa7f0
[ "MIT" ]
null
null
null
201712/20171201/main.cpp
Heliovic/My_CCF-CSP_Answer
089ce2601bee3d3d5dc463486dd4192f087aa7f0
[ "MIT" ]
null
null
null
#include <cstdio> #include <climits> #include <algorithm> #define MAX_N 1024 using namespace std; int N; int nums[MAX_N]; int main() { scanf("%d", &N); for (int i = 1; i <= N; i++) scanf("%d", &nums[i]); int min_d = INT_MAX; for (int i = 1; i <= N; i++) for (int j = i + 1; j <= N; j++) min_d = min(min_d, abs(nums[i] - nums[j])); printf("%d", min_d); return 0; }
14.655172
55
0.494118
Heliovic
653ff4b066ba68b60c544c619b2cad39333576bc
6,254
cpp
C++
beelzebub/arc/x86/src/tests/lock_elision.cpp
vercas/Beelzebub
9d0e4790060b313c6681ca7e478d08d3910332b0
[ "NCSA" ]
32
2015-09-02T22:56:22.000Z
2021-02-24T17:15:50.000Z
beelzebub/arc/x86/src/tests/lock_elision.cpp
vercas/Beelzebub
9d0e4790060b313c6681ca7e478d08d3910332b0
[ "NCSA" ]
30
2015-04-26T18:35:07.000Z
2021-06-06T09:57:02.000Z
beelzebub/arc/x86/src/tests/lock_elision.cpp
vercas/Beelzebub
9d0e4790060b313c6681ca7e478d08d3910332b0
[ "NCSA" ]
11
2015-09-03T20:47:41.000Z
2021-06-25T17:00:01.000Z
/* Copyright (c) 2016 Alexandru-Mihai Maftei. All rights reserved. Developed by: Alexandru-Mihai Maftei aka Vercas http://vercas.com | https://github.com/vercas/Beelzebub Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal with 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: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimers. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimers in the documentation and/or other materials provided with the distribution. * Neither the names of Alexandru-Mihai Maftei, Vercas, nor the names of its contributors may be used to endorse or promote products derived from this Software without specific prior written permission. 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 CONTRIBUTORS 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 WITH THE SOFTWARE. --- You may also find the text of this license in "LICENSE.md", along with a more thorough explanation regarding other files. */ #ifdef __BEELZEBUB__TEST_LOCK_ELISION #include <tests/lock_elision.hpp> #include <system/code_patch.hpp> #include <memory/vmm.hpp> #include <system/cpu_instructions.hpp> #include <kernel.hpp> #include <math.h> #include <debug.hpp> using namespace Beelzebub; using namespace Beelzebub::Memory; using namespace Beelzebub::System; __extern __section(data) uintptr_t testStart1; __extern __section(data) uintptr_t testEnd1; __startup void TestFunction1() { uint8_t volatile tVar = 0; msg("pre "); op_start: msg("mid "); op_end: msg("post %u1%n", tVar); asm volatile goto ( ".pushsection .data \n\t" ".global testStart1 \n\t" "testStart1: " _GAS_DATA_POINTER " %l0 \n\t" ".global testEnd1 \n\t" "testEnd1: " _GAS_DATA_POINTER " %l1 \n\t" ".popsection \n\t" : : : : op_start, op_end ); } __extern __section(data) uintptr_t testStart2; __extern __section(data) uintptr_t testEnd2; __startup void TestFunction2() { uint8_t volatile tVar = 0; msg("PRE %u1 ", tVar); op_start: tVar = 1; op_end: msg("POST %u1%n", tVar); asm volatile goto ( ".pushsection .data \n\t" ".global testStart2 \n\t" "testStart2: " _GAS_DATA_POINTER " %l0 \n\t" ".global testEnd2 \n\t" "testEnd2: " _GAS_DATA_POINTER " %l1 \n\t" ".popsection \n\t" : : : : op_start, op_end ); } __startup void PatchRange(uintptr_t tStart, uintptr_t tEnd) { // Debug::DebugTerminal->WriteHexDump(tStart, tEnd - tStart, 16); // msg("Lock: %Xp -> %Xp ", tStart, tEnd); vaddr_t const vaddr1 = RoundDown(tStart, PageSize); vaddr_t const vaddr2 = RoundDown(tEnd , PageSize); // First, get the page flags. MemoryFlags mf1 = MemoryFlags::None, mf2 = MemoryFlags::None; Handle res = Vmm::GetPageFlags(nullptr, vaddr1, mf1); ASSERT(res.IsOkayResult() , "Failed to retrieve flags of page %Xp for lock elision: %H" , vaddr1, res); if (vaddr2 != vaddr1) { res = Vmm::GetPageFlags(nullptr, vaddr2, mf2); ASSERT(res.IsOkayResult() , "Failed to retrieve flags of page %Xp for lock elision: %H" , vaddr2, res); } // msg("A "); // Then make the pages writable and executable (because they may overlap // with this code and all the functions used by it). res = Vmm::SetPageFlags(nullptr, vaddr1, MemoryFlags::Writable | MemoryFlags::Executable | MemoryFlags::Global); ASSERT(res.IsOkayResult() , "Failed to apply flags to page %Xp for lock elision: %H" , vaddr1, res); if (vaddr2 != vaddr1) { res = Vmm::SetPageFlags(nullptr, vaddr2, MemoryFlags::Writable | MemoryFlags::Executable | MemoryFlags::Global); ASSERT(res.IsOkayResult() , "Failed to apply flags to page %Xp for lock elision: %H" , vaddr2, res); } // msg("B%n"); // Finally, no-op the code. bool okay = TurnIntoNoOp(reinterpret_cast<void *>(tStart) , reinterpret_cast<void *>(tEnd), true); ASSERT(okay, "Failed to turn region %Xp-%Xp into a no-op." , tStart, tEnd); // Debug::DebugTerminal->WriteLine(); // Debug::DebugTerminal->WriteHexDump(tStart, tEnd - tStart, 16); // And close by restoring the page flags. for (uintptr_t i = tStart; i < tEnd; i += 32) CpuInstructions::FlushCache((void *)i); // msg("D "); res = Vmm::SetPageFlags(nullptr, vaddr1, mf1); ASSERT(res.IsOkayResult() , "Failed to apply flags to page %Xp for lock elision: %H" , vaddr1, res); if (vaddr2 != vaddr1) { res = Vmm::SetPageFlags(nullptr, vaddr2, mf2); ASSERT(res.IsOkayResult() , "Failed to apply flags to page %Xp for lock elision: %H" , vaddr2, res); } // msg("E%n"); } void TestLockElision() { // msg("Test range 1: %Xp-%Xp%n", testStart1, testEnd1); TestFunction1(); PatchRange(testStart1, testEnd1); TestFunction1(); // msg("Test range 2: %Xp-%Xp%n", testStart2, testEnd2); TestFunction2(); PatchRange(testStart2, testEnd2); TestFunction2(); } #endif
30.359223
120
0.637512
vercas
65410988ed1dfc3127d500b2ea3eea65ccf4779f
546
cpp
C++
6-array/6-8-2DArray.cpp
tanle8/cdope
2218cb2ece25b2d7bd47c3f06384302c300957f3
[ "MIT" ]
1
2018-04-04T13:43:28.000Z
2018-04-04T13:43:28.000Z
6-array/6-8-2DArray.cpp
tanle8/cdope
2218cb2ece25b2d7bd47c3f06384302c300957f3
[ "MIT" ]
null
null
null
6-array/6-8-2DArray.cpp
tanle8/cdope
2218cb2ece25b2d7bd47c3f06384302c300957f3
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main () { float marks[3][2]; int i, j; for ( i = 0; i < 3; i++ ) { // Input of marks from the user cout << "Enter marks of student " << (i + 1) << endl; for ( j = 0; j < 2; j++ ) { cout << "Subject " << (j + 1) << endl; cin >> marks[i][j]; } } // Printing the marks of students for ( i = 0; i < 3; i++ ) { cout << "Marks of student " << (i + 1) << endl; for ( j = 0; j < 2; j ++) { cout << "Subject " << (j + 1) << " : " << marks[i][j] << endl; } } return 0; }
18.2
64
0.454212
tanle8
6545849954c1069120a0c24f652667659549460d
2,012
hpp
C++
Source/Renderer.hpp
jazzfool/vuk-pbr
7accc89a0d516ffa7d75ca637b1c1c0d4a177238
[ "MIT" ]
4
2020-12-16T14:46:35.000Z
2021-07-05T20:48:27.000Z
Source/Renderer.hpp
jazzfool/vuk-pbr
7accc89a0d516ffa7d75ca637b1c1c0d4a177238
[ "MIT" ]
null
null
null
Source/Renderer.hpp
jazzfool/vuk-pbr
7accc89a0d516ffa7d75ca637b1c1c0d4a177238
[ "MIT" ]
1
2020-12-13T16:44:34.000Z
2020-12-13T16:44:34.000Z
#pragma once #include "Types.hpp" #include "Mesh.hpp" #include "Scene.hpp" #include "Material.hpp" #include "Uniforms.hpp" #include "PipelineStore.hpp" #include "GfxParts/CascadedShadows.hpp" #include "GfxParts/SSAO.hpp" #include "GfxParts/GBuffer.hpp" #include "GfxParts/VolumetricLights.hpp" #include "GfxParts/Atmosphere.hpp" #include <glm/vec3.hpp> #include <vuk/Image.hpp> #include <vuk/RenderGraph.hpp> #include <optional> class Renderer { public: Renderer(); void init(struct Context& ctxt); void update(); void render(); void mouse_event(f64 x_pos, f64 y_pos); private: vuk::RenderGraph render_graph(vuk::PerThreadContext& ptc); struct Context* m_ctxt; PipelineStore m_pipe_store; UniformStore m_uniforms; Scene m_scene; SceneRenderer m_scene_renderer; CascadedShadowRenderPass m_cascaded_shadows; SSAOPass m_ssao; GBufferPass m_gbuffer; VolumetricLightPass m_volumetric_light; AtmosphericSkyCubemap m_atmosphere; f64 m_last_x; f64 m_last_y; f32 m_pitch; f32 m_yaw; glm::vec3 m_cam_pos; glm::vec3 m_cam_front; glm::vec3 m_cam_up; vuk::Buffer m_transform_buffer; u32 m_transform_buffer_alignment; Mesh m_sphere; Mesh m_cube; Mesh m_quad; vuk::Texture m_hdr_texture; std::pair<vuk::Texture, vuk::SamplerCreateInfo> m_env_cubemap; std::pair<vuk::Texture, vuk::SamplerCreateInfo> m_irradiance_cubemap; std::pair<vuk::Texture, vuk::SamplerCreateInfo> m_prefilter_cubemap; std::pair<vuk::Texture, vuk::SamplerCreateInfo> m_brdf_lut; vuk::Unique<vuk::ImageView> m_env_cubemap_iv; vuk::Unique<vuk::ImageView> m_irradiance_cubemap_iv; vuk::Unique<vuk::ImageView> m_prefilter_cubemap_iv; }; struct RenderInfo { UniformStore* uniforms; Perspective cam_proj; glm::mat4 cam_view; glm::vec3 cam_pos; glm::vec3 cam_forward; glm::vec3 cam_up; u32 window_width; u32 window_height; glm::vec3 light_direction; vuk::ImageView shadow_map; std::array<CascadedShadowRenderPass::CascadeInfo, CascadedShadowRenderPass::SHADOW_MAP_CASCADE_COUNT> cascades; };
22.355556
112
0.777833
jazzfool
654f35bd815bd3c2f078ce51572c7c2270ed98a3
1,840
hpp
C++
Box2D/Common/Mat33.hpp
louis-langholtz/Box2D
7c74792bf177cf36640d735de2bba0225bf7f852
[ "Zlib" ]
32
2016-10-20T05:55:04.000Z
2021-11-25T16:34:41.000Z
Box2D/Common/Mat33.hpp
louis-langholtz/Box2D
7c74792bf177cf36640d735de2bba0225bf7f852
[ "Zlib" ]
50
2017-01-07T21:40:16.000Z
2018-01-31T10:04:05.000Z
Box2D/Common/Mat33.hpp
louis-langholtz/Box2D
7c74792bf177cf36640d735de2bba0225bf7f852
[ "Zlib" ]
7
2017-02-09T10:02:02.000Z
2020-07-23T22:49:04.000Z
/* * Original work Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * Modified work Copyright (c) 2017 Louis Langholtz https://github.com/louis-langholtz/Box2D * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #ifndef Mat33_hpp #define Mat33_hpp #include <Box2D/Common/Settings.hpp> #include <Box2D/Common/Vector3D.hpp> namespace box2d { /// @brief A 3-by-3 matrix. Stored in column-major order. /// @note This data structure is 36-bytes large (on at least one 64-bit platform with 4-byte Real). struct Mat33 { /// The default constructor does nothing (for performance). Mat33() noexcept = default; /// Construct this matrix using columns. constexpr Mat33(const Vec3 c1, const Vec3 c2, const Vec3 c3) noexcept: ex{c1}, ey{c2}, ez{c3} { // Intentionally empty. } Vec3 ex, ey, ez; }; constexpr auto Mat33_zero = Mat33(Vec3_zero, Vec3_zero, Vec3_zero); } #endif /* Mat33_hpp */
34.716981
103
0.688043
louis-langholtz
65507e931f257acffd9d3539abfd7cc91f2f6dd7
1,801
cpp
C++
Engine/src/PointLight.cpp
wqxhouse/CalVRPhysics
ebcb7c34a374ad46d25170d533ba7b23e7943312
[ "MIT" ]
null
null
null
Engine/src/PointLight.cpp
wqxhouse/CalVRPhysics
ebcb7c34a374ad46d25170d533ba7b23e7943312
[ "MIT" ]
null
null
null
Engine/src/PointLight.cpp
wqxhouse/CalVRPhysics
ebcb7c34a374ad46d25170d533ba7b23e7943312
[ "MIT" ]
null
null
null
// // PointLight.cpp // vrphysics // // Created by Robin Wu on 11/11/14. // Copyright (c) 2014 WSH. All rights reserved. // #include "PointLight.h" #include <osgDB/ReadFile> #include <cvrConfig/ConfigManager.h> PointLight::PointLight() : intensity(1.0f), _animated(false) { // init path for calvr if(_s_lightSphere == NULL) { _s_lightSphere = osgDB::readNodeFile("lightSphere.obj")->asGroup()->getChild(0)->asGeode(); } genGeometry(); memset(ambient, 0, sizeof(ambient)); memset(diffuse, 0, sizeof(diffuse)); memset(specular, 0, sizeof(specular)); // _light_effective_radius = intensity * _light_max_effective_radius; _animated = false; setAttenuation(1, 0, 0.6); _id = _highest_id++; } osg::ref_ptr<osg::MatrixTransform> PointLight::getGeomTransformNode() { return _lightGeomTransform; } osg::ref_ptr<osg::MatrixTransform> PointLight::getLightSphereTransformNode() { return _lightSphereTransform; } float PointLight::calcRadiusByAttenuation() { float MaxChannel = fmax(fmax(diffuse[0], diffuse[1]), diffuse[2]); if(MaxChannel == 0.0f) { return 0.0f; } float &c = attenuation[0]; float &l = attenuation[1]; float &e = attenuation[2]; float dist = 0.0f; if(e == 0.0f) { dist = (256 * MaxChannel * intensity - c) / l; } else { float sqrtInner = l*l - 4 * e * (c - 256 * MaxChannel * intensity); float sqrt = sqrtf(sqrtInner); dist = (-l + sqrt) / (2 * e); } return dist; } int PointLight::_highest_id; //osg::ref_ptr<osg::Geode> PointLight::_s_lightSphere = osgDB::readNodeFile("lightSphere.obj")->asGroup()->getChild(0)->asGeode(); osg::ref_ptr<osg::Geode> PointLight::_s_lightSphere = NULL;
23.38961
130
0.630761
wqxhouse
65550d52a48df9626e4c7c9b62397ff5e5369cf8
935
inl
C++
include/lug/Graphics/Render/View.inl
Lugdunum3D/Lugdunum3D
b6d6907d034fdba1ffc278b96598eba1d860f0d4
[ "MIT" ]
275
2016-10-08T15:33:17.000Z
2022-03-30T06:11:56.000Z
include/lug/Graphics/Render/View.inl
Lugdunum3D/Lugdunum3D
b6d6907d034fdba1ffc278b96598eba1d860f0d4
[ "MIT" ]
24
2016-09-29T20:51:20.000Z
2018-05-09T21:41:36.000Z
include/lug/Graphics/Render/View.inl
Lugdunum3D/Lugdunum3D
b6d6907d034fdba1ffc278b96598eba1d860f0d4
[ "MIT" ]
37
2017-02-25T05:03:48.000Z
2021-05-10T19:06:29.000Z
inline View::InitInfo& View::getInfo() { return _info; } inline const View::InitInfo& View::getInfo() const { return _info; } inline const View::Viewport& View::getViewport() const { return _viewport; } inline const View::Scissor& View::getScissor() const { return _scissor; } inline const Math::Vec3f& View::getClearColor() const { return _clearColor; } inline void View::setClearColor(const Math::Vec3f& color) { _clearColor = color; } inline void View::attachCamera(Resource::SharedPtr<Camera::Camera> camera) { if (!camera) { _camera = nullptr; return; } if (_camera) { _camera->setRenderView(nullptr); } _camera = std::move(camera); _camera->setRenderView(this); } inline Resource::SharedPtr<Camera::Camera> View::getCamera() const { return _camera; } inline float View::Viewport::getRatio() const { return extent.width / extent.height; }
19.893617
76
0.66738
Lugdunum3D
6555716d805655b63cb4b14de723a5fcc581c3be
1,201
cpp
C++
dbms/src/Storages/tests/system_numbers.cpp
rudneff/ClickHouse
3cb59b92bccbeb888d136f7c6e14b622382c0434
[ "Apache-2.0" ]
3
2016-12-30T14:19:47.000Z
2021-11-13T06:58:32.000Z
dbms/src/Storages/tests/system_numbers.cpp
rudneff/ClickHouse
3cb59b92bccbeb888d136f7c6e14b622382c0434
[ "Apache-2.0" ]
1
2017-01-13T21:29:36.000Z
2017-01-16T18:29:08.000Z
dbms/src/Storages/tests/system_numbers.cpp
jbfavre/clickhouse-debian
3806e3370decb40066f15627a3bca4063b992bfb
[ "Apache-2.0" ]
1
2021-02-07T16:00:54.000Z
2021-02-07T16:00:54.000Z
#include <iostream> #include <DB/IO/WriteBufferFromOStream.h> #include <DB/Storages/System/StorageSystemNumbers.h> #include <DB/DataStreams/LimitBlockInputStream.h> #include <DB/DataStreams/TabSeparatedRowOutputStream.h> #include <DB/DataStreams/BlockOutputStreamFromRowOutputStream.h> #include <DB/DataStreams/copyData.h> #include <DB/DataTypes/DataTypesNumberFixed.h> #include <DB/Interpreters/Context.h> int main(int argc, char ** argv) try { using namespace DB; StoragePtr table = StorageSystemNumbers::create("Numbers"); Names column_names; column_names.push_back("number"); Block sample; ColumnWithTypeAndName col; col.type = std::make_shared<DataTypeUInt64>(); sample.insert(std::move(col)); WriteBufferFromOStream out_buf(std::cout); QueryProcessingStage::Enum stage; LimitBlockInputStream input(table->read(column_names, 0, Context{}, Settings(), stage, 10)[0], 10, 96); RowOutputStreamPtr output_ = std::make_shared<TabSeparatedRowOutputStream>(out_buf, sample); BlockOutputStreamFromRowOutputStream output(output_); copyData(input, output); return 0; } catch (const DB::Exception & e) { std::cerr << e.what() << ", " << e.displayText() << std::endl; return 1; }
26.688889
104
0.762698
rudneff
6557ba1cf0b408b0570148dcadf56a27d8f6bed3
7,034
cc
C++
src/xenia/patcher/patcher.cc
Permdog99/xenia-canary
c99adff598480c4bf49100b90223e14bffbd802a
[ "BSD-3-Clause" ]
262
2019-08-17T08:27:30.000Z
2022-03-29T02:36:04.000Z
src/xenia/patcher/patcher.cc
Permdog99/xenia-canary
c99adff598480c4bf49100b90223e14bffbd802a
[ "BSD-3-Clause" ]
33
2019-08-18T09:39:40.000Z
2022-03-31T20:47:39.000Z
src/xenia/patcher/patcher.cc
Permdog99/xenia-canary
c99adff598480c4bf49100b90223e14bffbd802a
[ "BSD-3-Clause" ]
141
2019-09-06T01:37:01.000Z
2022-03-23T23:39:05.000Z
/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2021 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #include "xenia/patcher/patcher.h" #include "xenia/base/cvar.h" #include "xenia/base/filesystem.h" #include "xenia/base/logging.h" DEFINE_bool(apply_patches, true, "Enables patching functionality", "General"); namespace xe { namespace patcher { PatchingSystem::PatchingSystem() { is_any_patch_applied_ = false; LoadPatches(); } PatchingSystem::~PatchingSystem() {} void PatchingSystem::LoadPatches() { if (!cvars::apply_patches) { return; } const std::filesystem::path patches_directory = filesystem::GetExecutableFolder() / "patches"; const std::vector<xe::filesystem::FileInfo>& patch_files = filesystem::ListFiles(patches_directory); std::regex file_name_regex_match = std::regex("^[A-Fa-f0-9]{8}.*\\.patch$"); for (const xe::filesystem::FileInfo& patch_file : patch_files) { // Skip files that doesn't have only title_id as name and .patch as // extension if (!std::regex_match(patch_file.name.u8string(), file_name_regex_match)) { XELOGE( "PatchingSystem: Skipped loading file {} due to incorrect filename", patch_file.name.u8string()); continue; } const PatchFileEntry loaded_title_patches = ReadPatchFile(patch_file.path / patch_file.name); if (loaded_title_patches.title_id != -1) { loaded_patch_files.push_back(loaded_title_patches); } } XELOGI("Patching System: Loaded patches for {} titles", loaded_patch_files.size()); } void PatchingSystem::ApplyPatchesForTitle(Memory* memory, const uint32_t title_id, const uint64_t hash) { for (const PatchFileEntry& patchFile : loaded_patch_files) { if (patchFile.title_id != title_id) { continue; } if (patchFile.hash != 0 && patchFile.hash != hash) { continue; } for (const PatchInfoEntry& patchEntry : patchFile.patch_info) { if (!patchEntry.is_enabled) { continue; } XELOGE("Applying patch for: {}({:08X}) - {}", patchFile.title_name, patchFile.title_id, patchEntry.patch_name); ApplyPatch(memory, &patchEntry); } } } void PatchingSystem::ApplyPatch(Memory* memory, const PatchInfoEntry* patch) { for (const PatchDataEntry& patch_data_entry : patch->patch_data) { uint32_t old_address_protect = 0; auto address = memory->TranslateVirtual(patch_data_entry.memory_address_); auto heap = memory->LookupHeap(patch_data_entry.memory_address_); if (!heap) { continue; } heap->QueryProtect(patch_data_entry.memory_address_, &old_address_protect); heap->Protect(patch_data_entry.memory_address_, patch_data_entry.alloc_size_, kMemoryProtectRead | kMemoryProtectWrite); switch (patch_data_entry.alloc_size_) { case 1: xe::store_and_swap(address, uint8_t(patch_data_entry.new_value_)); break; case 2: xe::store_and_swap(address, uint16_t(patch_data_entry.new_value_)); break; case 4: xe::store_and_swap(address, uint32_t(patch_data_entry.new_value_)); break; case 8: xe::store_and_swap(address, uint64_t(patch_data_entry.new_value_)); break; default: XELOGE("Unsupported patch allocation size"); break; } // Restore previous protection heap->Protect(patch_data_entry.memory_address_, patch_data_entry.alloc_size_, old_address_protect); if (!is_any_patch_applied_) { is_any_patch_applied_ = true; } } } PatchFileEntry PatchingSystem::ReadPatchFile( const std::filesystem::path& file_path) { PatchFileEntry patchFile; std::shared_ptr<cpptoml::table> patch_toml_fields; try { patch_toml_fields = cpptoml::parse_file(file_path.u8string()); } catch (...) { XELOGE("Cannot load patch file: {}", file_path.u8string()); patchFile.title_id = -1; return patchFile; }; auto title_name = patch_toml_fields->get_as<std::string>("title_name"); auto title_id = patch_toml_fields->get_as<std::string>("title_id"); auto title_hash = patch_toml_fields->get_as<std::string>("hash"); patchFile.title_id = strtoul((*title_id).c_str(), NULL, 16); patchFile.hash = strtoull((*title_hash).c_str(), NULL, 16); patchFile.title_name = *title_name; auto tarr = patch_toml_fields->get_table_array("patch"); for (auto table : *tarr) { PatchInfoEntry patch = PatchInfoEntry(); auto patch_name = *table->get_as<std::string>("name"); auto patch_desc = *table->get_as<std::string>("desc"); auto patch_author = *table->get_as<std::string>("author"); auto is_enabled = *table->get_as<bool>("is_enabled"); patch.id = 0; // ToDo: Implement id for future GUI stuff patch.patch_name = patch_name; patch.patch_desc = patch_desc; patch.patch_author = patch_author; patch.is_enabled = is_enabled; const std::string data_types[] = {"be64", "be32", "be16", "be8"}; // Iterate through all available data sizes for (const std::string& type : data_types) { auto entries = ReadPatchData(type, table); for (const PatchDataEntry& entry : *entries) { patch.patch_data.push_back(entry); } } patchFile.patch_info.push_back(patch); } return patchFile; } std::vector<PatchDataEntry>* PatchingSystem::ReadPatchData( const std::string size_type, const std::shared_ptr<cpptoml::table>& patch_table) { std::vector<PatchDataEntry>* patch_data = new std::vector<PatchDataEntry>(); auto patch_data_tarr = patch_table->get_table_array(size_type); if (!patch_data_tarr) { return patch_data; } for (const auto& patch_data_table : *patch_data_tarr) { auto address = patch_data_table->get_as<std::uint32_t>("address"); // Todo: How to handle different sizes auto value = patch_data_table->get_as<std::uint64_t>("value"); PatchDataEntry patchData = {GetAllocSize(size_type), *address, *value}; patch_data->push_back(patchData); } return patch_data; } uint8_t PatchingSystem::GetAllocSize(const std::string provided_size) { uint8_t alloc_size = sizeof(uint32_t); if (provided_size == "be64") { alloc_size = sizeof(uint64_t); } else if (provided_size == "be32") { alloc_size = sizeof(uint32_t); } else if (provided_size == "be16") { alloc_size = sizeof(uint16_t); } else if (provided_size == "be8") { alloc_size = sizeof(uint8_t); } return alloc_size; } } // namespace patcher } // namespace xe
32.266055
79
0.646432
Permdog99
655e06f0fdc1bed2867c64ba655d5fa4f17ab2b6
2,619
cpp
C++
cga/secure/utility.cpp
cgacurrency/cga-node
ad21cd224bed5de4bd0cec8c2aa42d35aea842a5
[ "BSD-2-Clause" ]
null
null
null
cga/secure/utility.cpp
cgacurrency/cga-node
ad21cd224bed5de4bd0cec8c2aa42d35aea842a5
[ "BSD-2-Clause" ]
null
null
null
cga/secure/utility.cpp
cgacurrency/cga-node
ad21cd224bed5de4bd0cec8c2aa42d35aea842a5
[ "BSD-2-Clause" ]
null
null
null
#include <cga/secure/utility.hpp> #include <cga/lib/interface.h> #include <cga/node/working.hpp> static std::vector<boost::filesystem::path> all_unique_paths; boost::filesystem::path cga::working_path (bool legacy) { auto result (cga::app_path ()); switch (cga::cga_network) { case cga::cga_networks::cga_test_network: // if (!legacy) // { result /= "CGATest"; // } // else // { // result /= "RaiBlocksTest"; // } break; case cga::cga_networks::cga_beta_network: // if (!legacy) // { result /= "CGABeta"; // } // else // { // result /= "RaiBlocksBeta"; // } break; case cga::cga_networks::cga_live_network: // if (!legacy) // { result /= "CGA"; // } // else // { // result /= "RaiBlocks"; // } break; } return result; } bool cga::migrate_working_path (std::string & error_string) { bool result (true); auto old_path (cga::working_path (true)); auto new_path (cga::working_path ()); if (old_path != new_path) { boost::system::error_code status_error; auto old_path_status (boost::filesystem::status (old_path, status_error)); if (status_error == boost::system::errc::success && boost::filesystem::exists (old_path_status) && boost::filesystem::is_directory (old_path_status)) { auto new_path_status (boost::filesystem::status (new_path, status_error)); if (!boost::filesystem::exists (new_path_status)) { boost::system::error_code rename_error; boost::filesystem::rename (old_path, new_path, rename_error); if (rename_error != boost::system::errc::success) { std::stringstream error_string_stream; error_string_stream << "Unable to migrate data from " << old_path << " to " << new_path; error_string = error_string_stream.str (); result = false; } } } } return result; } boost::filesystem::path cga::unique_path () { auto result (working_path () / boost::filesystem::unique_path ()); all_unique_paths.push_back (result); return result; } std::vector<boost::filesystem::path> cga::remove_temporary_directories () { for (auto & path : all_unique_paths) { boost::system::error_code ec; boost::filesystem::remove_all (path, ec); if (ec) { std::cerr << "Could not remove temporary directory: " << ec.message () << std::endl; } // lmdb creates a -lock suffixed file for its MDB_NOSUBDIR databases auto lockfile = path; lockfile += "-lock"; boost::filesystem::remove (lockfile, ec); if (ec) { std::cerr << "Could not remove temporary lock file: " << ec.message () << std::endl; } } return all_unique_paths; }
23.383929
151
0.64643
cgacurrency
655e53e94c75ab1a92456d0353b3535136858035
564
cpp
C++
sem1/hw4/hw4.3/hw4.3/hw4.3/main.cpp
Daria-Donina/Homework
8853fb65c7a0ad62556a49d12908098af9caf7ed
[ "Apache-2.0" ]
1
2018-11-29T11:12:51.000Z
2018-11-29T11:12:51.000Z
sem1/hw4/hw4.3/hw4.3/hw4.3/main.cpp
Daria-Donina/Homework
8853fb65c7a0ad62556a49d12908098af9caf7ed
[ "Apache-2.0" ]
null
null
null
sem1/hw4/hw4.3/hw4.3/hw4.3/main.cpp
Daria-Donina/Homework
8853fb65c7a0ad62556a49d12908098af9caf7ed
[ "Apache-2.0" ]
null
null
null
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string.h> #include "auxiliary.h" #include "test.h" #include "interface.h" int main() { if (test()) { printf("Tests passed\n\n"); } else { printf("Tests failed\n\n"); } const int size = 100; FILE * phonebookFile = fopen("phonebook.txt", "r"); if (!phonebookFile) { phonebookFile = fopen("phonebook.txt", "w+"); } Record phonebook[101]; copyDataToStruct(phonebookFile, phonebook, size); fclose(phonebookFile); int number = -1; userInterface(number, phonebook); return 0; }
14.461538
52
0.66844
Daria-Donina
65606aa5ebf00de7c13b0c9abcba3145472d2958
916
hpp
C++
libs/core/include/fcppt/algorithm/equal.hpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
libs/core/include/fcppt/algorithm/equal.hpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
libs/core/include/fcppt/algorithm/equal.hpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
// Copyright Carl Philipp Reh 2009 - 2018. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef FCPPT_ALGORITHM_EQUAL_HPP_INCLUDED #define FCPPT_ALGORITHM_EQUAL_HPP_INCLUDED #include <fcppt/range/begin.hpp> #include <fcppt/range/end.hpp> #include <fcppt/config/external_begin.hpp> #include <algorithm> #include <fcppt/config/external_end.hpp> namespace fcppt { namespace algorithm { /** \brief Compares two ranges for equality. \ingroup fcpptalgorithm */ template< typename Range1, typename Range2 > inline bool equal( Range1 const &_range1, Range2 const &_range2 ) { return std::equal( fcppt::range::begin( _range1 ), fcppt::range::end( _range1 ), fcppt::range::begin( _range2 ), fcppt::range::end( _range2 ) ); } } } #endif
15.525424
61
0.695415
pmiddend
656c17691c55dbcb02e6663d3deead90925f1cce
650
cpp
C++
UVa/UVA1339.cpp
Insouciant21/solution
8f241ec2076c9c29c0d39c2c285ee12eac1dee9e
[ "Apache-2.0" ]
1
2020-09-11T13:17:28.000Z
2020-09-11T13:17:28.000Z
UVa/UVA1339.cpp
Insouciant21/solution
8f241ec2076c9c29c0d39c2c285ee12eac1dee9e
[ "Apache-2.0" ]
1
2020-10-22T13:36:23.000Z
2020-10-22T13:36:23.000Z
UVa/UVA1339.cpp
Insouciant21/solution
8f241ec2076c9c29c0d39c2c285ee12eac1dee9e
[ "Apache-2.0" ]
1
2020-10-22T13:33:11.000Z
2020-10-22T13:33:11.000Z
#include <bits/stdc++.h> using namespace std; int main() { string s, t; ios::sync_with_stdio(false); while (cin >> s >> t) { int p1[26], p2[26]; memset(p1, 0, sizeof(p1)); memset(p2, 0, sizeof(p2)); for (char &i : s) p1[i - 'A']++; for (char &i : t) p2[i - 'A']++; sort(p1, p1 + 26); sort(p2, p2 + 26); bool find = true; for (int i = 0; i < 26; i++) { if (p1[i] != p2[i]) { cout << "NO" << endl; find = false; break; } } if (find) cout << "YES" << endl; } return 0; }
23.214286
40
0.387692
Insouciant21
6570252780ca3970272dfdb1045f9576ee5f076a
3,075
hpp
C++
src/settings.hpp
tigrazone/fluctus
7f5721d725f2787e5fb705107c83611200fc5ebb
[ "MIT" ]
null
null
null
src/settings.hpp
tigrazone/fluctus
7f5721d725f2787e5fb705107c83611200fc5ebb
[ "MIT" ]
null
null
null
src/settings.hpp
tigrazone/fluctus
7f5721d725f2787e5fb705107c83611200fc5ebb
[ "MIT" ]
3
2021-05-06T12:43:07.000Z
2021-05-27T15:32:18.000Z
#pragma once #include <string> #include <map> #include "json.hpp" #include "clcontext.hpp" typedef struct { vfloat3 pos; vfloat3 right; vfloat3 up; vfloat3 dir; cl_float fov; cl_float apertureSize; cl_float focalDist; vfloat2 cameraRotation; float cameraSpeed; } CameraSettings; typedef struct { vfloat3 right; vfloat3 up; vfloat3 N; vfloat3 pos; vfloat3 E; vfloat2 size; } AreaLightSettings; class Settings { public: // Singleton pattern static Settings &getInstance() { static Settings instance; return instance; } Settings(Settings const&) = delete; void operator=(Settings const&) = delete; // allow import from custom json void import(nlohmann::json j); // Getters std::string getPlatformName() { return platformName; } std::string getDeviceName() { return deviceName; } std::string getEnvMapName() { return envMapName; } void setEnvMapName(const std::string name) { envMapName = name; } std::map<unsigned int, std::string> getShortcuts() { return shortcuts; } unsigned int getDefaultScene() { return defaultScene; } int getWindowWidth() { return windowWidth; } int getWindowHeight() { return windowHeight; } float getRenderScale() { return renderScale; } void setRenderScale(float s) { renderScale = s; } bool getUseBitstack() { return clUseBitstack; } bool getUseSoA() { return clUseSoA; } unsigned int getWfBufferSize() { return wfBufferSize; } bool getUseWavefront() { return useWavefront; } bool getUseRussianRoulette() { return useRussianRoulette; } bool getUseSeparateQueues() { return useSeparateQueues; } int getMaxPathDepth() { return maxPathDepth; } unsigned int getMaxSpp() { return maxSpp; } unsigned int getMaxRenderTime() { return maxRenderTime; } bool getSampleImplicit() { return sampleImplicit; } bool getSampleExplicit() { return sampleExplicit; } bool getUseEnvMap() { return useEnvMap; } bool getUseAreaLight() { return useAreaLight; } int getTonemap() { return tonemap; } CameraSettings getCameraSettings() { return cameraSettings; } AreaLightSettings getAreaLightSettings() { return areaLightSettings; } private: Settings(); void init(); void load(); void calculateCameraRotation(); void calculateCameraMatrix(); // Contents of settings singleton std::string platformName; std::string deviceName; std::string envMapName; std::map<unsigned int, std::string> shortcuts; unsigned int defaultScene; unsigned int wfBufferSize; bool clUseBitstack; bool clUseSoA; int windowWidth; int windowHeight; float renderScale; bool useWavefront; bool useRussianRoulette; bool useSeparateQueues; int maxPathDepth; unsigned int maxSpp; unsigned int maxRenderTime; bool sampleImplicit; bool sampleExplicit; bool useEnvMap; bool useAreaLight; int tonemap; CameraSettings cameraSettings; AreaLightSettings areaLightSettings; };
29.567308
76
0.695935
tigrazone
65717f4ca8c0cb4486be95dbc9a9c8dad2160289
88,262
cpp
C++
src/TressetteClient/cGameMainGfx.cpp
aaaasmile/tressettecpp
0f06a3d5eee6b5aa7e9a099652da548213d07f21
[ "MIT" ]
null
null
null
src/TressetteClient/cGameMainGfx.cpp
aaaasmile/tressettecpp
0f06a3d5eee6b5aa7e9a099652da548213d07f21
[ "MIT" ]
null
null
null
src/TressetteClient/cGameMainGfx.cpp
aaaasmile/tressettecpp
0f06a3d5eee6b5aa7e9a099652da548213d07f21
[ "MIT" ]
null
null
null
// cGameMainGfx.cpp #include "StdAfx.h" #pragma warning(disable:4786) #include "win_type_global.h" #include <stdio.h> #include <SDL_image.h> #include <SDL_endian.h> #include "cDelayNextAction.h" #include "cGameMainGfx.h" #include "gfx_util.h" #include "EngineApp.h" #include "cSettings.h" #include "cButtonGfx.h" #include <time.h> #include "lang_gen.h" #include "cBalloonGfx.h" #include "cMesgBoxGfx.h" #include "cMusicManager.h" #include "ErrorMsg.h" #include "cPopUpMenuGfx.h" #include "AlgSupport.h" #define FPS (1000 / 30) static const char* lpszImageDir = "data/images/"; static const char* lpszImageBack = "im000740.jpg"; static const char* lpszMazziDir = "data/mazzi/"; static const char* lpszFontConsoleImg = "data/images/ConsoleFont.png"; static const char* lpszaImage_filenames[cGameMainGfx::NUM_ANIMAGES] = { "data/images/tocca.png", "data/images/LedOff.bmp", "data/images/LedOn.bmp", "data/images/vertical.png", "data/images/horizontal.png", "data/images/LedOnBlue.bmp", "data/images/LedOnRed.bmp", "data/images/balloon_body.pcx", "data/images/balloon_down_left.pcx", "data/images/balloon_down_right.pcx", "data/images/balloon_up.pcx", "data/images/home_1.png", "data/images/home_2.png", "data/images/home_3.png", "data/images/puntodom_1.png", "data/images/puntodom_2.png", "data/images/puntodom_3.png" }; static const char* lpszCST_INFO = "[INFO]"; static const char* lpszCST_SCORE = "[SCORE]"; static const char* lpszCST_SU = "[SU]"; cCore* g_pCore; extern cEngineApp* g_MainApp; ////////////////////// cGameMainGfx cGameMainGfx* g_stacGameMainGfx = 0; //////////////////////////////////////// // fnEffectTer /*! Effect terminated notification of music manager // \param int iCh : */ void fnEffectTer(int iCh) { // do something ASSERT(g_stacGameMainGfx); g_stacGameMainGfx->NtfyTermEff(iCh); } //////////////////////////////////////// // cGameMainGfx /*! constructor */ cGameMainGfx::cGameMainGfx(cEngineApp* pApp) { m_pScene_background = 0; m_pFontText = 0; m_pSurf_Bar = 0; m_pApp = pApp; m_bStartdrag = false; m_iSymbolWidth = 84; m_iSymbolHeigth = 144; m_pDeck = 0; m_pSymbols = 0; m_pSmallSymbols = 0; m_pFontStatus = 0; m_pDeckType = 0; for (int i = 0; i < NUM_ANIMAGES; i++) { m_pAnImages[i] = 0; } m_pMatchPoints = 0; m_pCoreEngine = 0; m_bPlayerCanPlay = FALSE; m_iPlayerThatHaveMarkup = 0; for (int j = 0; j < NUMOFBUTTON; j++) { m_pbtArrayCmd[0] = 0; } m_pLangMgr = 0; m_pMusicMgr = 0; g_stacGameMainGfx = this; m_bMatchTerminated = FALSE; m_bDisplayConsole = FALSE; m_pAlphaDisplay = 0; m_eCurrentDeckType = cTipoDiMazzo::PIACENTINA; m_bInitPython = FALSE; m_iPlAlreadyPlayed = 0; } //////////////////////////////////////// // ~cGameMainGfx /*! Destructor */ cGameMainGfx::~cGameMainGfx() { cleanup(); } //////////////////////////////////////// // Initialize /*! Initialize the game gfx with the background // \param SDL_Surface *s : screen surface */ void cGameMainGfx::Initialize(SDL_Surface *pScreen, SDL_Renderer* pRender, SDL_Texture* pScreenTexture) { m_psdlRenderer = pRender; m_pScreen = pScreen; m_pScreenTexture = pScreenTexture; cleanup(); CHAR ErrBuff[512]; cLanguages* pLangMgr = m_pApp->GetLanguageMan(); m_pLangMgr = pLangMgr; m_pDeckType = new cTipoDiMazzo; m_pDeckType->SetType((cTipoDiMazzo::eTypeMazzo)g_Options.All.iTipoMazzo); initDeck(); std::string strFileName; // load background if (g_Options.All.bFotoBack) { strFileName = lpszImageDir; strFileName += lpszImageBack; SDL_RWops *srcBack = SDL_RWFromFile(strFileName.c_str(), "rb"); if (srcBack == 0) { sprintf(ErrBuff, "Unable to load %s background image", strFileName.c_str()); throw Error::Init(ErrBuff); } m_pScene_background = IMG_LoadJPG_RW(srcBack); } else { // use a default green surface m_pScene_background = SDL_CreateRGBSurface(SDL_SWSURFACE, m_pScreen->w, m_pScreen->h, 32, 0, 0, 0, 0); SDL_FillRect(m_pScene_background, NULL, SDL_MapRGBA(m_pScreen->format, 0, 80, 0, 0)); } // create stack regions createRegionsInit(); m_pFontStatus = m_pApp->GetFontAriblk(); m_pFontText = m_pApp->GetFontVera(); // load images for animation stuff int rr = 0; int gg = 0; int bb = 0; int i; for (i = 0; i < NUM_ANIMAGES; i++) { m_pAnImages[i] = IMG_Load(lpszaImage_filenames[i]); if (i == IMG_TOCCA_PLAYER || i == IMG_BT_RF1 || i == IMG_BT_RF2 || i == IMG_BT_RF3 || i == IMG_BT_INFO1 || i == IMG_BT_INFO2 || i == IMG_BT_INFO3) { gg = 0; rr = 0xff; bb = 0xff; } else { rr = 0; gg = 0; bb = 0; } if (m_pAnImages[i] == 0) { // image not found sprintf(ErrBuff, "Image not found %s", lpszaImage_filenames[i]); throw Error::Init(ErrBuff); } //SDL_SetColorKey(m_pAnImages[i], SDL_SRCCOLORKEY | SDL_RLEACCEL, SDL_MapRGB(m_pAnImages[i]->format, rr, gg, bb)); SDL_SetColorKey(m_pAnImages[i], TRUE, SDL_MapRGB(m_pAnImages[i]->format, rr, gg, bb)); // SDL 2.0 } //SDL_EnableKeyRepeat(250, 30); // command buttons if (m_pbtArrayCmd[0] == 0) { // we use command buttons for toolbar SDL_Rect rctBt; rctBt.w = m_pAnImages[IMG_BT_RF1]->w; rctBt.h = m_pAnImages[IMG_BT_RF1]->h; rctBt.y = 20; int iXButInit = 20; for (i = 0; i < NUMOFBUTTON; i++) { rctBt.x = iXButInit + i * (rctBt.w + 4); m_pbtArrayCmd[i] = new cButtonGfx; m_pbtArrayCmd[i]->Init(&rctBt, m_pScreen, /*m_pFontText*/m_pFontStatus, i, m_psdlRenderer); // delegate m_pbtArrayCmd[i]->m_fncbClickEvent = MakeDelegate(this, &cGameMainGfx::ButCmdClicked); // set type bitmap m_pbtArrayCmd[i]->SetButtonType(cButtonGfx::BITMAP_BUTTON); if (i == BUTID_EXIT) { // set bitmap for exit button m_pbtArrayCmd[i]->SetButBitmapSurfaces(m_pAnImages[IMG_BT_RF1], m_pAnImages[IMG_BT_RF2], m_pAnImages[IMG_BT_RF3]); } else if (i == BUTID_INFO) { // set bitmap for exit button m_pbtArrayCmd[i]->SetButBitmapSurfaces(m_pAnImages[IMG_BT_INFO1], m_pAnImages[IMG_BT_INFO2], m_pAnImages[IMG_BT_INFO3]); } } //enable all buttons enableNumButtonsCmd(NUMOFBUTTON); } // ballon for (i = 0; i < MAX_NUM_PLAYERS; i++) { SDL_Rect destWIN; m_pbalGfx[i] = new cBalloonGfx; destWIN.w = m_pAnImages[IMG_BALLOON]->w; destWIN.h = m_pAnImages[IMG_BALLOON]->h; if (i == PLAYER1) // player gui { destWIN.x = (m_pScreen->w - m_pAnImages[IMG_BALLOON]->w) / 2 - 10; //destWIN.y = 450; destWIN.y = m_pScreen->h - m_pAnImages[IMG_BALLOON]->h - 40; // first make init m_pbalGfx[i]->Init(destWIN, m_pAnImages[IMG_BALLOON], m_pFontStatus, 200); // setstyle comes after init m_pbalGfx[i]->SetStyle(cBalloonGfx::ARROW_DWN_RIGHT, m_pAnImages[IMG_BALL_ARROW_DWRIGHT]); } else if (i == PLAYER2) // opponente alla destra { destWIN.x = m_pScreen->w - m_pAnImages[IMG_BALLOON]->w - 10; //destWIN.y = 250; destWIN.y = (m_pScreen->h - m_pAnImages[IMG_BALLOON]->h) / 2 - 20; // first make init m_pbalGfx[i]->Init(destWIN, m_pAnImages[IMG_BALLOON], m_pFontStatus, 200); // setstyle comes after init m_pbalGfx[i]->SetStyle(cBalloonGfx::ARROW_DWN_RIGHT, m_pAnImages[IMG_BALL_ARROW_DWRIGHT]); } else if (i == PLAYER3) // socio { //destWIN.x = 320; destWIN.x = (m_pScreen->w - m_pAnImages[IMG_BALLOON]->w) / 2 - 20; //destWIN.y = 100; destWIN.y = m_pAnImages[IMG_BALLOON]->h + 5; // first make init m_pbalGfx[i]->Init(destWIN, m_pAnImages[IMG_BALLOON], m_pFontStatus, 200); // setstyle comes after init m_pbalGfx[i]->SetStyle(cBalloonGfx::ARROW_UP, m_pAnImages[IMG_BALL_ARROW_UP]); } else if (i == PLAYER4) //opponente alla sinistra { destWIN.x = 20; //destWIN.y = 250; destWIN.y = (m_pScreen->h - m_pAnImages[IMG_BALLOON]->h) / 2 - 20; // first make init m_pbalGfx[i]->Init(destWIN, m_pAnImages[IMG_BALLOON], m_pFontStatus, 200); // setstyle comes after init m_pbalGfx[i]->SetStyle(cBalloonGfx::ARROW_DWN_RIGHT, m_pAnImages[IMG_BALL_ARROW_DWLEFT]); } } // music manager m_pMusicMgr = m_pApp->GetMusicManager(); // messagebox background surface m_pAlphaDisplay = SDL_CreateRGBSurface(SDL_SWSURFACE, m_pScreen->w, m_pScreen->h, 32, 0, 0, 0, 0); } //////////////////////////////////////// // loadCardPac /*! Carica il mazzo delle carte dal file in formato pac */ int cGameMainGfx::loadCardPac() { Uint32 timetag; char describtion[100]; Uint8 num_anims; Uint16 w, h; Uint16 frames; int FRAMETICKS = (1000 / FPS); int THINKINGS_PER_TICK = 1; std::string strFileName = lpszMazziDir; strFileName += m_pDeckType->GetResFileName(); SDL_RWops *src = SDL_RWFromFile(strFileName.c_str(), "rb"); if (src == 0) { CHAR ErrBuff[512]; sprintf(ErrBuff, "Error on load deck file %s", strFileName.c_str()); throw Error::Init(ErrBuff); } SDL_RWread(src, describtion, 100, 1); timetag = SDL_ReadLE32(src); SDL_RWread(src, &num_anims, 1, 1); // witdh of the picture (pac of 4 cards) w = SDL_ReadLE16(src); // height of the picture (pac of 10 rows of cards) h = SDL_ReadLE16(src); frames = SDL_ReadLE16(src); for (int i = 0; i < frames; i++) { SDL_ReadLE16(src); } m_pDeck = IMG_LoadPNG_RW(src); if (!m_pDeck) { fprintf(stderr, "Cannot create deck: %s\n", SDL_GetError()); exit(1); } SDL_SetColorKey(m_pDeck, TRUE, SDL_MapRGB(m_pDeck->format, 0, 128, 0)); // SDL 2.0 m_iCardWidth = w / 4; m_iCardHeight = h / 10; return 0; } void cGameMainGfx::cleanup() { delete m_pCoreEngine; m_pCoreEngine = 0; delete m_pDeckType; m_pDeckType = 0; int i; for (i = 0; i < NUMOFBUTTON; i++) { delete m_pbtArrayCmd[i]; m_pbtArrayCmd[i] = 0; } for (i = 0; i < MAX_NUM_PLAYERS; i++) { delete m_pbalGfx[i]; m_pbalGfx[i] = 0; } if (m_pScene_background) { SDL_FreeSurface(m_pScene_background); m_pScene_background = NULL; } if (m_pSurf_Bar) { SDL_FreeSurface(m_pSurf_Bar); m_pSurf_Bar = NULL; } if (m_pAlphaDisplay) { SDL_FreeSurface(m_pAlphaDisplay); m_pAlphaDisplay = NULL; } } //////////////////////////////////////// // Init4PlayerGameVsCPU /*! Init the 4 players game: player against CPU */ void cGameMainGfx::Init4PlayerGameVsCPU() { m_pCoreEngine = new cCore(); m_pCoreEngine->Create(4); g_pCore = m_pCoreEngine; m_pMatchPoints = m_pCoreEngine->GetMatchPointsObj(); // random seed m_pCoreEngine->SetRandomSeed((unsigned)time(NULL)); // local type m_pCoreEngine->SetLocalType((eTypeLocal)g_Options.Match.iLocalGameType); // good game calls m_pCoreEngine->SetGoodGameCallEnabled(g_Options.Match.bUseGoodGameDecla); // match goal m_pMatchPoints->SetScoreGoal(g_Options.Match.iScoreGoal); cPlayer* pPlayer1 = m_pCoreEngine->GetPlayer(PLAYER1); cPlayer* pPlayer2 = m_pCoreEngine->GetPlayer(PLAYER2); cPlayer* pPlayer3 = m_pCoreEngine->GetPlayer(PLAYER3); cPlayer* pPlayer4 = m_pCoreEngine->GetPlayer(PLAYER4); // set level and iformations of all players // first pair pPlayer1->SetType(PT_LOCAL); pPlayer1->SetName(g_Options.All.strPlayerName.c_str()); if (g_Options.Match.iLevel_Pl_1 == HMI) { pPlayer1->SetLevel(HMI, this); } else { pPlayer1->SetLevel((eGameLevel)g_Options.Match.iLevel_Pl_1, NULL); } pPlayer1->InitPlugin(g_Options.Match.strPluginDll_Pl_1.c_str()); pPlayer3->SetType(PT_MACHINE); pPlayer3->SetName(g_Options.Match.strPlayerName_3.c_str()); pPlayer3->SetLevel((eGameLevel)g_Options.Match.iLevel_Pl_3, NULL); pPlayer3->InitPlugin(g_Options.Match.strPluginDll_Pl_3.c_str()); // opponent pair pPlayer2->SetType(PT_MACHINE); pPlayer2->SetName(g_Options.Match.strPlayerName_2.c_str()); pPlayer2->SetLevel((eGameLevel)g_Options.Match.iLevel_Pl_2, NULL); pPlayer2->InitPlugin(g_Options.Match.strPluginDll_Pl_2.c_str()); pPlayer4->SetType(PT_MACHINE); pPlayer4->SetName(g_Options.Match.strPlayerName_4.c_str()); pPlayer4->SetLevel((eGameLevel)g_Options.Match.iLevel_Pl_4, NULL); pPlayer4->InitPlugin(g_Options.Match.strPluginDll_Pl_4.c_str()); m_bMatchTerminated = FALSE; m_pCoreEngine->NoInitScript(); } //////////////////////////////////////// // initDeck /*! Inizializza il mazzo */ int cGameMainGfx::initDeck() { // load deck from pac file if (m_pDeck == NULL) { loadCardPac(); m_eCurrentDeckType = m_pDeckType->GetType(); } else if (m_eCurrentDeckType != m_pDeckType->GetType()) { // deck is changed SDL_FreeSurface(m_pDeck); loadCardPac(); } // use assert because if loadCardPac failed an exception is thrown ASSERT(m_pDeck); m_SrcBack.x = 0; m_SrcBack.y = 0; m_SrcCard.y = 0; m_SrcCard.w = m_iCardWidth; m_SrcCard.h = m_iCardHeight; // symbols std::string strFileSymbName = lpszMazziDir; strFileSymbName += m_pDeckType->GetSymbolFileName(); std::string strFileSymbSmallName = lpszMazziDir; strFileSymbSmallName += "symb_336_small.bmp"; if (m_pSymbols) { SDL_FreeSurface(m_pSymbols); } if (m_pSmallSymbols) { SDL_FreeSurface(m_pSmallSymbols); } m_pSmallSymbols = SDL_LoadBMP(strFileSymbSmallName.c_str()); if (m_pSmallSymbols == 0) { CHAR ErrBuff[512]; sprintf(ErrBuff, "Error on load small symbols %s", strFileSymbSmallName.c_str()); throw Error::Init(ErrBuff); } //SDL_SetColorKey(m_pSmallSymbols, SDL_SRCCOLORKEY, SDL_MapRGB(m_pSmallSymbols->format, 242, 30, 206)); SDL_SetColorKey(m_pSmallSymbols, TRUE, SDL_MapRGB(m_pSmallSymbols->format, 242, 30, 206)); // SDL 2.0 m_pSymbols = SDL_LoadBMP(strFileSymbName.c_str()); if (m_pSymbols == 0) { CHAR ErrBuff[512]; sprintf(ErrBuff, "Error on load deck file (symbols) %s", strFileSymbName.c_str()); throw Error::Init(ErrBuff); } if (m_pDeckType->GetSymbolFileName() == "symb_336.bmp") { //SDL_SetColorKey(m_pSymbols, SDL_SRCCOLORKEY, SDL_MapRGB(m_pSymbols->format, 242, 30, 206)); SDL_SetColorKey(m_pSymbols, TRUE, SDL_MapRGB(m_pSymbols->format, 242, 30, 206)); // SDL 2.0 } else { //SDL_SetColorKey(m_pSymbols, SDL_SRCCOLORKEY | SDL_RLEACCEL, SDL_MapRGB(m_pSymbols->format, 0, 128, 0)); SDL_SetColorKey(m_pSymbols, TRUE, SDL_MapRGB(m_pSymbols->format, 0, 128, 0)); // SDL 2.0 } m_iSymbolSmallWidth = m_pSmallSymbols->w / 4; m_iSymbolSmallHeigth = m_pSmallSymbols->h; m_iSymbolWidth = m_pSymbols->w / 4; m_iSymbolHeigth = m_pSymbols->h; m_SrcBack.w = m_iSymbolWidth; m_SrcBack.h = m_iSymbolHeigth; SDL_SetSurfaceBlendMode(m_pSymbols, SDL_BLENDMODE_BLEND); // black bar surface m_pSurf_Bar = SDL_CreateRGBSurface(SDL_SWSURFACE, m_pScreen->w, m_pScreen->h, 32, 0, 0, 0, 0); SDL_FillRect(m_pSurf_Bar, NULL, SDL_MapRGBA(m_pScreen->format, 0, 0, 0, 0)); SDL_SetSurfaceBlendMode(m_pSurf_Bar, SDL_BLENDMODE_BLEND); SDL_SetSurfaceAlphaMod(m_pSurf_Bar, 127); //SDL 2.0 return 0; } //////////////////////////////////////// // createRegionsInit /*! Create region for the table */ void cGameMainGfx::createRegionsInit() { // opponent cards on right site int i; for (i = 0; i < NUM_CARDS_HAND; i++) { m_aOpponentCards[0][i].m_iX = m_pScreen->w - m_iCardWidth - 10; m_aOpponentCards[0][i].m_iY = 70 + i * 15; m_aOpponentCards[0][i].SetDeckSurface(m_pDeck, m_iCardWidth, m_iCardHeight); m_aOpponentCards[0][i].SetSymbSurf(m_pSmallSymbols, m_iSymbolSmallWidth, m_iSymbolSmallHeigth); m_aOpponentCards[0][i].State = cCardGfx::CSW_ST_BACK; } // partner int iInitialX = (m_pScreen->w - (15 * NUM_CARDS_HAND + m_iCardWidth)) / 2; for (i = 0; i < NUM_CARDS_HAND; i++) { m_aOpponentCards[1][i].m_iX = 15 * i + iInitialX; m_aOpponentCards[1][i].m_iY = 10; m_aOpponentCards[1][i].SetDeckSurface(m_pDeck, m_iCardWidth, m_iCardHeight); m_aOpponentCards[1][i].SetSymbSurf(m_pSmallSymbols, m_iSymbolSmallWidth, m_iSymbolSmallHeigth); m_aOpponentCards[1][i].State = cCardGfx::CSW_ST_BACK; } // opponent on the left site for (i = 0; i < NUM_CARDS_HAND; i++) { m_aOpponentCards[2][i].m_iX = 10; m_aOpponentCards[2][i].m_iY = 70 + i * 15; m_aOpponentCards[2][i].SetDeckSurface(m_pDeck, m_iCardWidth, m_iCardHeight); m_aOpponentCards[2][i].SetSymbSurf(m_pSmallSymbols, m_iSymbolSmallWidth, m_iSymbolSmallHeigth); m_aOpponentCards[2][i].State = cCardGfx::CSW_ST_BACK; } // cards on player int stepX = (m_iCardWidth * 75) / 100; if (m_pScreen->w - (NUM_CARDS_HAND * stepX + m_iCardWidth) < 0) { stepX = (m_pScreen->w - m_iCardWidth) / NUM_CARDS_HAND; } int widthAllCardsPlayer = NUM_CARDS_HAND * stepX + m_iCardWidth; int initialCardX = (m_pScreen->w - widthAllCardsPlayer) / 2; for (int k = 0; k < NUM_CARDS_HAND; k++) { m_aPlayerCards[k].m_iX = initialCardX + k * stepX; m_aPlayerCards[k].m_iY = m_pScreen->h - m_iCardHeight - 4; m_aPlayerCards[k].SetCardInfo(k, m_iCardWidth, m_iCardHeight); m_aPlayerCards[k].SetDeckSurface(m_pDeck, m_iCardWidth, m_iCardHeight); m_aPlayerCards[k].SetSymbSurf(m_pSymbols, m_iSymbolWidth, m_iSymbolHeigth); m_aPlayerCards[k].m_iZOrder = k; m_aPlayerCards[k].State = cCardGfx::CSW_ST_BACK; } // cards on table played int iRefTableX = (m_pScreen->w - 2 * m_iCardWidth) / 2 - 30; int iRefTableY = (m_pScreen->h - 2 * m_iCardHeight) / 2; for (int g = 0; g < NUM_CARDS_PLAYED; g++) { // use the player position neighboor if (g == 0) { // near to player me m_CardsTable[g].m_iX = iRefTableX + m_iCardWidth; m_CardsTable[g].m_iY = iRefTableY + 80; } else if (g == 1) { // near to opponent on right site m_CardsTable[g].m_iX = iRefTableX + m_iCardWidth + 50; m_CardsTable[g].m_iY = iRefTableY + 50; } else if (g == 2) { // near to the partner m_CardsTable[g].m_iX = iRefTableX + m_iCardWidth; m_CardsTable[g].m_iY = iRefTableY + 30; } else if (g == 3) { // near to opponent on left site m_CardsTable[g].m_iX = iRefTableX + m_iCardWidth - 50; m_CardsTable[g].m_iY = iRefTableY + 50; } m_CardsTable[g].State = cCardGfx::CSW_ST_INVISIBLE; m_CardsTable[g].SetDeckSurface(m_pDeck, m_iCardWidth, m_iCardHeight); m_CardsTable[g].SetSymbSurf(m_pSymbols, m_iSymbolWidth, m_iSymbolHeigth); } } //////////////////////////////////////// // drawStaticScene /*! Draw the table, included all cards, status, chat */ void cGameMainGfx::drawStaticScene() { //renderChatPlayers(); if (m_pScene_background) { SDL_BlitSurface(m_pScene_background, NULL, m_pScreen, NULL); } // render cards in hand for (int g = 0; g < NUM_OTHER; g++) { for (int i = 0; i < NUM_CARDS_HAND; i++) { renderCard(&m_aOpponentCards[g][i]); if (g == 0) { // UI player if (m_aPlayerCards[i].State == cCardGfx::CSW_ST_SYMBOL) { // symbol card i drawn first renderCard(&m_aPlayerCards[i]); if (i > 0) { if (m_aPlayerCards[i - 1].State != cCardGfx::CSW_ST_SYMBOL) { // redraw the previous card to make it in background renderCard(&m_aPlayerCards[i - 1]); } } } else { renderCard(&m_aPlayerCards[i]); } } } } // cards played on the table size_t iNumCardPlayed = m_vctPlayedCardsGfx.size(); for (int k = 0; k < iNumCardPlayed; k++) { cCardGfx* pCardGfx = m_vctPlayedCardsGfx[k]; renderCard(pCardGfx); } showPlayerMarkup(m_iPlayerThatHaveMarkup); // shows names int i; int iNumPlayers = m_pCoreEngine->GetNumOfPlayers(); for (i = 0; i < iNumPlayers; i++) { renderPlayerName(i); } // show score (leds and points) showCurrentScore(); // draw command buttons for (int j = 0; j < NUMOFBUTTON; j++) { m_pbtArrayCmd[j]->DrawButton(m_pScreen); } // ballon for (i = 0; i < MAX_NUM_PLAYERS; i++) { m_pbalGfx[i]->Draw(m_pScreen); } SDL_RenderClear(m_psdlRenderer); SDL_UpdateTexture(m_pScreenTexture, NULL, m_pScreen->pixels, m_pScreen->pitch); // sdl 2.0 SDL_RenderCopy(m_psdlRenderer, m_pScreenTexture, NULL, NULL); SDL_RenderPresent(m_psdlRenderer); } //////////////////////////////////////// // renderCard /*! Render a card gfx // \param cCardGfx* pCard : pointer to the card */ void cGameMainGfx::renderCard(cCardGfx* pCard) { if (pCard->State == cCardGfx::CSW_ST_INVISIBLE) { return; } else if (pCard->State == cCardGfx::CSW_ST_SYMBOL) { pCard->DrawSymbol(m_pScreen); } else if (pCard->State == cCardGfx::CSW_ST_VISIBLE) { pCard->DrawCard(m_pScreen); } else if (pCard->State == cCardGfx::CSW_ST_BACK) { pCard->DrawCardBack(m_pScreen); } else { ASSERT(0); } } //////////////////////////////////////// // renderPlayerName /*! Display the name of the player // \param int iPlayerIx : */ void cGameMainGfx::renderPlayerName(int iPlayerIx) { cPlayer* pPlayer = m_pCoreEngine->GetPlayer(iPlayerIx); char txt_to_render[256]; static char un_char = ' '; int iLenBar = 100; int iX3 = 165; int iY3 = 25; int iX1 = m_pScreen->w - 100;//690; int iY1 = m_pScreen->h - 40; //560; int iX2 = iX1; int iY2 = 30; int iX4 = 16; int iY4 = m_pScreen->h - 200; //360; if (iPlayerIx == PLAYER2) { // first opponent sprintf(txt_to_render, "%s", pPlayer->GetName()); GFX_UTIL::DrawStaticSpriteEx(m_pScreen, 0, 0, iLenBar, 25, iX2, iY2, m_pSurf_Bar); GFX_UTIL::DrawString(m_pScreen, txt_to_render, iX2 + 5, iY2 + 4, GFX_UTIL_COLOR::White, m_pFontText, true); } else if (iPlayerIx == PLAYER1) { // user sprintf(txt_to_render, "%s", pPlayer->GetName()); GFX_UTIL::DrawStaticSpriteEx(m_pScreen, 0, 0, iLenBar, 25, iX1, iY1, m_pSurf_Bar); GFX_UTIL::DrawString(m_pScreen, txt_to_render, iX1 + 5, iY1 + 4, GFX_UTIL_COLOR::Orange, m_pFontText, true); } else if (iPlayerIx == PLAYER3) { // socio sprintf(txt_to_render, "%s", pPlayer->GetName()); GFX_UTIL::DrawStaticSpriteEx(m_pScreen, 0, 0, iLenBar, 25, iX3, iY3, m_pSurf_Bar); GFX_UTIL::DrawString(m_pScreen, txt_to_render, iX3 + 5, iY3 + 4, GFX_UTIL_COLOR::White, m_pFontText, true); } else if (iPlayerIx == PLAYER4) { // second opponent sprintf(txt_to_render, "%s", pPlayer->GetName()); GFX_UTIL::DrawStaticSpriteEx(m_pScreen, 0, 0, iLenBar, 25, iX4, iY4, m_pSurf_Bar); GFX_UTIL::DrawString(m_pScreen, txt_to_render, iX4 + 5, iY4 + 4, GFX_UTIL_COLOR::White, m_pFontText, true); } else { ASSERT(0); } } //////////////////////////////////////// // waitOnEvent /*! Block the main loop until the user press a key or a mouse */ void cGameMainGfx::waitOnEvent() { SDL_Event event; BOOL bEnd = FALSE; while (!bEnd) { while (SDL_PollEvent(&event)) { if (event.type == SDL_MOUSEBUTTONDOWN || event.type == SDL_KEYDOWN) { // event is raised bEnd = TRUE; } } } } //////////////////////////////////////// // animateBeginGiocata /*! Animation new giocata (card distribution) */ void cGameMainGfx::animateBeginGiocata() { SDL_Event event; while (SDL_PollEvent(&event)) { } Uint32 uiTickTot = 0; Uint32 uiInitialTick = SDL_GetTicks(); Uint32 uiLast_time = uiInitialTick; Uint32 uiFrameRate = 3; int iInitialSpeed; switch (g_Options.All.iAniSpeedLevel) { case 0: iInitialSpeed = 0; break; case 1: iInitialSpeed = 20; break; case 2: iInitialSpeed = 40; break; case 3: iInitialSpeed = 60; break; case 4: iInitialSpeed = 80; break; case 5: iInitialSpeed = 100; break; default: iInitialSpeed = 20; break; } cCardGfx cardTmp[NUM_CARDS_HAND]; for (int i = 0; i < NUM_CARDS_HAND; i++) { cardTmp[i].Copy(&m_aPlayerCards[i]); cardTmp[i].m_iY = 40 + i; cardTmp[i].m_iX = 10 + i; cardTmp[i].SetDeckSurface(m_pDeck, m_iCardWidth, m_iCardHeight); cardTmp[i].SetSymbSurf(m_pSymbols, m_iSymbolWidth, m_iSymbolHeigth); cardTmp[i].State = cCardGfx::CSW_ST_BACK; cardTmp[i].m_iVx = iInitialSpeed; cardTmp[i].m_iVy = iInitialSpeed; } BOOL bEnd = FALSE; int iCardMovingIx = 0; do { if (!bEnd) { // clear screen SDL_BlitSurface(m_pScene_background, NULL, m_pScreen, NULL); // update speed if (cardTmp[iCardMovingIx].m_iVx <= 9) { cardTmp[iCardMovingIx].m_iVx += 1; cardTmp[iCardMovingIx].m_iVy += 1; } if (cardTmp[iCardMovingIx].m_iX > m_aPlayerCards[iCardMovingIx].m_iX + m_aPlayerCards[iCardMovingIx].m_iWidth) { // go back on x cardTmp[iCardMovingIx].m_iVx -= 4; } if (cardTmp[iCardMovingIx].m_iX <= 0) { cardTmp[iCardMovingIx].m_iVx = 6; } // new position cardTmp[iCardMovingIx].m_iX += cardTmp[iCardMovingIx].m_iVx; cardTmp[iCardMovingIx].m_iY += cardTmp[iCardMovingIx].m_iVy; } // move the cards in the hand while (SDL_PollEvent(&event)) { if (event.type == SDL_MOUSEBUTTONDOWN || event.type == SDL_KEYDOWN) { // stop the animation drawStaticScene(); m_DelayAction.CheckPoint(500, cDelayNextAction::CHANGE_AVAIL); return; } } if (!bEnd) { // render all cards if (cardTmp[iCardMovingIx].m_iY >= m_aPlayerCards[iCardMovingIx].m_iY) { // ok the card reach the position, move the next one cardTmp[iCardMovingIx].Copy(&m_aPlayerCards[iCardMovingIx]); iCardMovingIx++; if (iCardMovingIx >= NUM_CARDS_HAND) { bEnd = TRUE; } } for (int i = 0; i < NUM_CARDS_HAND; i++) { cardTmp[i].DrawGeneric(m_pScreen); } SDL_UpdateTexture(m_pScreenTexture, NULL, m_pScreen->pixels, m_pScreen->pitch); // sdl 2.0 SDL_RenderClear(m_psdlRenderer); SDL_RenderCopy(m_psdlRenderer, m_pScreenTexture, NULL, NULL); SDL_RenderPresent(m_psdlRenderer); } // synch to frame rate Uint32 uiNowTime = SDL_GetTicks(); if (uiNowTime < (uiLast_time + uiFrameRate)) { int iDelayTime = uiFrameRate - (uiNowTime - uiLast_time); SDL_Delay(iDelayTime); TRACE("Delay time %d\n", iDelayTime); uiLast_time = uiNowTime; } uiTickTot = uiNowTime - uiInitialTick; } while (uiTickTot < 3000 && !bEnd); // restore begin scene m_DelayAction.CheckPoint(500, cDelayNextAction::CHANGE_AVAIL); drawStaticScene(); } //////////////////////////////////////// // animateManoEnd /*! Animate mano end. Move played cards together and than move it to the trick winner. // \param int iPlayerIx : player that win the trick */ void cGameMainGfx::animateManoEnd(int iPlayerIx) { Uint32 uiTickTot = 0; Uint32 uiInitialTick = SDL_GetTicks(); Uint32 uiLast_time = uiInitialTick; Uint32 uiFrameRate = 3; cCardGfx cardTmp[NUM_CARDS_PLAYED]; for (int i = 0; i < NUM_CARDS_PLAYED; i++) { cardTmp[i].Copy(&m_CardsTable[i]); cardTmp[i].SetDeckSurface(m_pDeck, m_iCardWidth, m_iCardHeight); } int iPhase1Speed = 2; int iPhase2Speed = 1; switch (g_Options.All.iAniSpeedLevel) { case 0: iPhase1Speed = 1; iPhase2Speed = 1; break; case 1: iPhase1Speed = 2; iPhase2Speed = 2; break; case 2: iPhase1Speed = 3; iPhase2Speed = 3; break; case 3: iPhase1Speed = 5; iPhase2Speed = 5; break; case 4: iPhase1Speed = 7; iPhase2Speed = 7; break; case 5: iPhase1Speed = 10; iPhase2Speed = 10; break; default: iPhase1Speed = 2; iPhase2Speed = 1; break; } // move on y cardTmp[0].m_iVy = -iPhase1Speed; cardTmp[0].m_iVx = 0; cardTmp[2].m_iVy = 2; cardTmp[2].m_iVx = 0; // move on x cardTmp[1].m_iVy = 0; cardTmp[1].m_iVx = -iPhase1Speed; cardTmp[3].m_iVy = 0; cardTmp[3].m_iVx = iPhase1Speed; // freeze the current display used as background SDL_Surface* pCurrentDisplay = SDL_CreateRGBSurface(SDL_SWSURFACE, m_pScreen->w, m_pScreen->h, 32, 0, 0, 0, 0); SDL_BlitSurface(m_pScreen, NULL, pCurrentDisplay, NULL); BOOL bEnd = FALSE; BOOL bPhase1_Y = FALSE; BOOL bPhase1_X = FALSE; do { // clear screen SDL_BlitSurface(pCurrentDisplay, NULL, m_pAlphaDisplay, NULL); for (int iCardPlayedIndex = 0; iCardPlayedIndex < NUM_CARDS_PLAYED; iCardPlayedIndex++) { cardTmp[iCardPlayedIndex].m_iX += cardTmp[iCardPlayedIndex].m_iVx; cardTmp[iCardPlayedIndex].m_iY += cardTmp[iCardPlayedIndex].m_iVy; // update card position cardTmp[iCardPlayedIndex].DrawCard(m_pAlphaDisplay); } if (!bPhase1_Y && cardTmp[0].m_iY <= cardTmp[2].m_iY) { cardTmp[0].m_iVy = 0; cardTmp[2].m_iVy = 0; bPhase1_Y = TRUE; } if (!bPhase1_X && cardTmp[1].m_iX <= cardTmp[3].m_iX) { // ok the card reach the central position cardTmp[1].m_iVx = 0; cardTmp[3].m_iVx = 0; bPhase1_X = TRUE; } SDL_BlitSurface(m_pAlphaDisplay, NULL, m_pScreen, NULL); //SDL_Flip(m_pScreen); // sdl 1.2 SDL_UpdateTexture(m_pScreenTexture, NULL, m_pScreen->pixels, m_pScreen->pitch); // sdl 2.0 SDL_RenderCopy(m_psdlRenderer, m_pScreenTexture, NULL, NULL); SDL_RenderPresent(m_psdlRenderer); int iIncVel = iPhase2Speed; if (bPhase1_X && bPhase1_Y) { // second step, move cards to the trick winner if (iPlayerIx == 0) { cardTmp[0].m_iVy += iIncVel; cardTmp[1].m_iVy += iIncVel; cardTmp[2].m_iVy += iIncVel; cardTmp[3].m_iVy += iIncVel; if (cardTmp[2].m_iY >= m_pScreen->h) { // cards outside of the screen bEnd = TRUE; } } else if (iPlayerIx == 1) { cardTmp[0].m_iVx += iIncVel; cardTmp[1].m_iVx += iIncVel; cardTmp[2].m_iVx += iIncVel; cardTmp[3].m_iVx += iIncVel; if (cardTmp[3].m_iX >= m_pScreen->w) { // cards outside of the screen bEnd = TRUE; } } else if (iPlayerIx == 2) { cardTmp[0].m_iVy -= iIncVel; cardTmp[1].m_iVy -= iIncVel; cardTmp[2].m_iVy -= iIncVel; cardTmp[3].m_iVy -= iIncVel; if (cardTmp[0].m_iY <= 0) { // cards outside of the screen bEnd = TRUE; } } else if (iPlayerIx == 3) { cardTmp[0].m_iVx -= iIncVel; cardTmp[1].m_iVx -= iIncVel; cardTmp[2].m_iVx -= iIncVel; cardTmp[3].m_iVx -= iIncVel; if (cardTmp[1].m_iX <= 0) { // cards outside of the screen bEnd = TRUE; } } } // synch to frame rate Uint32 uiNowTime = SDL_GetTicks(); uiTickTot = uiNowTime - uiInitialTick; if (uiNowTime < uiLast_time + uiFrameRate) { SDL_Delay(uiLast_time + uiFrameRate - uiNowTime); uiLast_time = uiNowTime; } } while (uiTickTot < 2000 && !bEnd); SDL_FreeSurface(pCurrentDisplay); } //////////////////////////////////////// // animGiocataEnd /*! Shows a little animation because giocata is terminated. // \param int iPlayerIx : Player that wons the giocata */ void cGameMainGfx::animGiocataEnd(int iPlayerIx) { } //////////////////////////////////////// // animateCards /*! Shows a little animation. */ int cGameMainGfx::animateCards() { //srand((unsigned)time(NULL)); int rot; int xspeed; int yspeed; int GRAVITY = 1; int MAXY = m_pScreen->h; float BOUNCE = 0.8f; cCardGfx cardGfx; do { rot = rand() % 2; cardGfx.cardSpec.SetCardIndex(rand() % 40); cardGfx.m_iX = rand() % m_pScreen->w; cardGfx.m_iY = rand() % m_pScreen->h / 2; if (rot) { xspeed = -4; } else { xspeed = 4; } yspeed = 0; do //while card is within the m_pScreen { SDL_PumpEvents(); if (SDL_GetMouseState(NULL, NULL)) return -1; // stop the animation yspeed = yspeed + GRAVITY; cardGfx.m_iX += xspeed; cardGfx.m_iY += yspeed; if (cardGfx.m_iY + m_iCardHeight > MAXY) { cardGfx.m_iY = MAXY - m_iCardHeight; yspeed = int(-yspeed * BOUNCE); } cardGfx.DrawCard(m_pScreen); //SDL_Flip(m_pScreen); SDL_UpdateTexture(m_pScreenTexture, NULL, m_pScreen->pixels, m_pScreen->pitch); // sdl 2.0 SDL_RenderCopy(m_psdlRenderer, m_pScreenTexture, NULL, NULL); SDL_RenderPresent(m_psdlRenderer); } while ((cardGfx.m_iX + 73 > 0) && (cardGfx.m_iX < m_pScreen->w)); } while (1); return 0; } //////////////////////////////////////// // showOkMsgBox /*! Show an ok messge box */ void cGameMainGfx::showOkMsgBox(LPCSTR strText) { ASSERT(m_pAlphaDisplay); // prepare the size of the box cMesgBoxGfx MsgBox; SDL_Rect rctBox; rctBox.w = m_pScreen->w - 100; rctBox.h = 130; rctBox.y = (m_pScreen->h - rctBox.h) / 2; rctBox.x = (m_pScreen->w - rctBox.w) / 2; // show a mesage box MsgBox.Init(&rctBox, m_pScreen, m_pFontStatus, cMesgBoxGfx::MBOK, m_psdlRenderer); SDL_BlitSurface(m_pScreen, NULL, m_pAlphaDisplay, NULL); STRING strTextBt = m_pLangMgr->GetStringId(cLanguages::ID_OK); MsgBox.Show(m_pAlphaDisplay, strTextBt.c_str(), "", strText); } //////////////////////////////////////// // showResultMsgBox /*! Show a window with match points // \param VCT_STRING& vct_strText : text to render */ void cGameMainGfx::showResultMsgBox(VCT_STRING& vct_strText) { ASSERT(m_pAlphaDisplay); // prepare the size of the box cMesgBoxGfx MsgBox; SDL_Rect rctBox; rctBox.w = m_pScreen->w - 100; rctBox.h = m_pScreen->h - 180; rctBox.y = 80; rctBox.x = (m_pScreen->w - rctBox.w) / 2; // show a mesage box MsgBox.Init(&rctBox, m_pScreen, m_pFontStatus, cMesgBoxGfx::MBOK, m_psdlRenderer); SDL_BlitSurface(m_pScreen, NULL, m_pAlphaDisplay, NULL); for (UINT i = 0; i < vct_strText.size(); i++) { MsgBox.AddLineText(vct_strText[i].c_str()); } STRING strTextBt = m_pLangMgr->GetStringId(cLanguages::ID_OK); MsgBox.Show(m_pAlphaDisplay, strTextBt.c_str(), "", ""); } //////////////////////////////////////// // showDeclarMsgBox /*! Show a good game declaration box // \param int iPlayerIx : // \param LPCSTR strText : */ void cGameMainGfx::showDeclarMsgBox(int iPlayerIx, LPCSTR strText) { ASSERT(m_pAlphaDisplay); // prepare the size of the box cMesgBoxGfx MsgBox; SDL_Rect rctBox; rctBox.w = 350; rctBox.h = 170; if (iPlayerIx == 0) { rctBox.y = (m_pScreen->h - rctBox.h) - 100; rctBox.x = (m_pScreen->w - rctBox.w) / 2; } else if (iPlayerIx == 1) { rctBox.y = (m_pScreen->h - rctBox.h) / 2; rctBox.x = (m_pScreen->w - rctBox.w) - 10; } else if (iPlayerIx == 2) { rctBox.y = 50; rctBox.x = (m_pScreen->w - rctBox.w) / 2; } else if (iPlayerIx == 3) { rctBox.y = (m_pScreen->h - rctBox.h) / 2; rctBox.x = 50; } // show a mesage box MsgBox.Init(&rctBox, m_pScreen, /*m_pFontText*/ m_pFontStatus, cMesgBoxGfx::MBOK, m_psdlRenderer); SDL_BlitSurface(m_pScreen, NULL, m_pAlphaDisplay, NULL); STRING strTextBt = m_pLangMgr->GetStringId(cLanguages::ID_OK); cPlayer* pPlayer = m_pCoreEngine->GetPlayer(iPlayerIx); STRING strTmp2 = pPlayer->GetName(); STRING strTmp = m_pLangMgr->GetStringId(cLanguages::ID_A_ACCUSA); STRING strLine = strTmp2 + " " + strTmp + ":"; MsgBox.AddLineText(strLine.c_str()); MsgBox.AddLineText(strText); MsgBox.Show(m_pAlphaDisplay, strTextBt.c_str(), "", ""); // default display drawStaticScene(); } //////////////////////////////////////// // showYesNoMsgBox /*! Show yes/no message box // \param LPCSTR strText : Content of the messagebox \return :1 for yes \return :0 for no */ int cGameMainGfx::showYesNoMsgBox(LPCSTR strText) { ASSERT(m_pAlphaDisplay); // prepare the size of the box cMesgBoxGfx MsgBox; SDL_Rect rctBox; rctBox.w = m_pScreen->w - 100; rctBox.h = 130; rctBox.y = (m_pScreen->h - rctBox.h) / 2; rctBox.x = (m_pScreen->w - rctBox.w) / 2; // show a mesage box MsgBox.Init(&rctBox, m_pScreen, m_pFontStatus, cMesgBoxGfx::MB_YES_NO, m_psdlRenderer); SDL_BlitSurface(m_pScreen, NULL, m_pAlphaDisplay, NULL); STRING strTextYes = m_pLangMgr->GetStringId(cLanguages::ID_YES); STRING strTextNo = m_pLangMgr->GetStringId(cLanguages::ID_NO); int iRes = MsgBox.Show(m_pAlphaDisplay, strTextYes.c_str(), strTextNo.c_str(), strText); return iRes; } //////////////////////////////////////// // showPopUpCallMenu /*! Show a popup menu to select what the user say // \param int iX : mouse x position // \param int iY : mouse y position // \param eSayPlayer eSay : say result */ void cGameMainGfx::showPopUpCallMenu(CardSpec& cardClicked, int iX, int iY, eSayPlayer* peSay) { if (m_iTrickRound >= NUM_CARDS_HAND) { // last trick, don't need to show call menu return; } if ((m_iPlAlreadyPlayed > 0) && (m_pCoreEngine->GetLocalType() == LT_CHITARELLA || m_pCoreEngine->GetLocalType() == LT_ROMANA)) { // don't show declaration pop-up in this local return; } TRACE("show popup menu\n"); ASSERT(peSay); ASSERT(m_pAlphaDisplay); *peSay = NOTHING; VCT_SIGNALS vctAvail; m_pCoreEngine->GetAdmittedSignals(cardClicked, vctAvail, m_iPlayer1Index); size_t iNumCmdsAval = vctAvail.size(); if (iNumCmdsAval == 0) { // no commands available return; } // prepare the size of the box cPopUpMenuGfx Menu; SDL_Rect rctBox; rctBox.w = m_pScreen->w; // max value, width is autocalculated rctBox.h = m_pScreen->h; // max value hight is autocalculated rctBox.y = iY; rctBox.x = iX; // show a mesage box Menu.Init(&rctBox, m_pScreen, m_pFontText, m_psdlRenderer); SDL_BlitSurface(m_pScreen, NULL, m_pAlphaDisplay, NULL); for (int i = 0; i < iNumCmdsAval; i++) { Menu.AddLineText(vctAvail[i].lpcText); } Menu.Show(m_pAlphaDisplay); // menu is terminated if (Menu.MenuIsSelected()) { // the user choice a menu int iIndexSel = Menu.GetSlectedIndex(); *peSay = vctAvail[iIndexSel].eSay; } else { *peSay = NOTHING; } TRACE("END popup menu\n"); drawStaticScene(); } //////////////////////////////////////// // NewMatch /*! */ void cGameMainGfx::NewMatch() { Mix_ChannelFinished(fnEffectTer); // a new match is being started m_pCoreEngine->NewMatch(); // draw the static scene drawStaticScene(); } //////////////////////////////////////// // MatchLoop /*! Match loop */ void cGameMainGfx::MatchLoop() { SDL_Event event; int done = 0; Uint32 uiLast_time; Uint32 uiFrame = 0; Uint32 uiNowTime = 0; m_DelayAction.Reset(); STRING strTextTmp; uiLast_time = SDL_GetTicks(); while (done == 0 && m_bMatchTerminated == FALSE) { uiFrame++; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: // user want to exit the match // show a messagebox for confirm strTextTmp = m_pLangMgr->GetStringId(cLanguages::ID_MATCHENDQUESTION); if (showYesNoMsgBox(strTextTmp.c_str()) == cMesgBoxGfx::MB_RES_YES) { return; } break; case SDL_KEYDOWN: if (event.key.keysym.sym == SDLK_ESCAPE) { strTextTmp = m_pLangMgr->GetStringId(cLanguages::ID_MATCHENDQUESTION); if (showYesNoMsgBox(strTextTmp.c_str()) == cMesgBoxGfx::MB_RES_YES) { done = 1; } } handleKeyDownEvent(event); break; case SDL_MOUSEBUTTONDOWN: handleMouseDownEvent(event); break; case SDL_MOUSEMOTION: handleMouseMoveEvent(event); break; case SDL_MOUSEBUTTONUP: handleMouseUpEvent(event); break; } } uiNowTime = SDL_GetTicks(); if (uiNowTime > uiLast_time + FPS) { drawStaticScene(); uiLast_time = uiNowTime; } if (m_DelayAction.CanStart()) { m_pCoreEngine->NextAction(); } // SDL 2.0 SDL_UpdateTexture(m_pScreenTexture, NULL, m_pScreen->pixels, m_pScreen->pitch); SDL_RenderClear(m_psdlRenderer); SDL_RenderCopy(m_psdlRenderer, m_pScreenTexture, NULL, NULL); SDL_RenderPresent(m_psdlRenderer); } } //////////////////////////////////////// // handleMouseDownEvent /*! Mouse down event happens // \param SDL_Event &event : */ void cGameMainGfx::handleMouseDownEvent(SDL_Event &event) { if (event.button.button == SDL_BUTTON_LEFT) { // check if the player have to play a card for (int i = 0; i < NUM_CARDS_HAND; i++) { // check if a card was clicked if (m_aPlayerCards[i].MouseInCard(event.button.x, event.button.y)) { int iIndex_1 = i; int iIndex_2 = i + 1; int iZor_1 = m_aPlayerCards[iIndex_1].m_iZOrder; // check if another card was clicked // could be only the next eSayPlayer eSay = NOTHING; if (iIndex_2 < NUM_CARDS_HAND) { if (m_aPlayerCards[iIndex_2].MouseInCard(event.button.x, event.button.y)) { int iZor_2 = m_aPlayerCards[iIndex_2].m_iZOrder; // other card have a click // check the z order if (iZor_1 > iZor_2) { // card is played correctly if (!g_Options.All.bSignalWithRMouse) { // ask about user signal // shows declaration pop-up showPopUpCallMenu(m_aPlayerCards[iIndex_1].cardSpec, event.button.x, event.button.y, &eSay); } if (clickOnPlayerCard(iIndex_1)) { if (eSay != NOTHING) { // trigger signal m_pCoreEngine->Player_saySomething(m_iPlayer1Index, eSay); } break; } } else { if (!g_Options.All.bSignalWithRMouse) { // ask about user signal // shows declaration pop-up showPopUpCallMenu(m_aPlayerCards[iIndex_2].cardSpec, event.button.x, event.button.y, &eSay); } if (clickOnPlayerCard(iIndex_2)) { if (eSay != NOTHING) { // trigger signal m_pCoreEngine->Player_saySomething(m_iPlayer1Index, eSay); } break; } } } else { if (!g_Options.All.bSignalWithRMouse) { // ask about user signal // shows declaration pop-up showPopUpCallMenu(m_aPlayerCards[i].cardSpec, event.button.x, event.button.y, &eSay); } // only one card has a click if (clickOnPlayerCard(i)) { if (eSay != NOTHING) { // trigger signal m_pCoreEngine->Player_saySomething(m_iPlayer1Index, eSay); } break; } } } else { if (!g_Options.All.bSignalWithRMouse) { // ask about user signal // shows declaration pop-up showPopUpCallMenu(m_aPlayerCards[i].cardSpec, event.button.x, event.button.y, &eSay); } // no other cards if (clickOnPlayerCard(i)) { if (eSay != NOTHING) { // trigger signal m_pCoreEngine->Player_saySomething(m_iPlayer1Index, eSay); } break; } } } } } else if (event.button.button == SDL_BUTTON_RIGHT) { // mouse right // use the right button to show a popup menu to select a signal and play a card // check if the player is on turn and if was clicked on a card if (m_bPlayerCanPlay && g_Options.All.bSignalWithRMouse) { for (int i = 0; i < NUM_CARDS_HAND; i++) { if (m_aPlayerCards[i].State == cCardGfx::CSW_ST_VISIBLE && m_aPlayerCards[i].MouseInCard(event.button.x, event.button.y)) { // take care of Zorder int iIndex_1 = i; int iIndex_2 = i + 1; int iZor_1 = m_aPlayerCards[iIndex_1].m_iZOrder; int iZor_2 = -1; if (iIndex_2 < NUM_CARDS_HAND) { if (m_aPlayerCards[iIndex_2].MouseInCard(event.button.x, event.button.y)) { // overlap the second card iZor_2 = m_aPlayerCards[iIndex_2].m_iZOrder; } } int iIndexCardSelected = iIndex_1; if (iZor_2 > iZor_1) { iIndexCardSelected = iIndex_2; } eSayPlayer eSay = NOTHING; showPopUpCallMenu(m_aPlayerCards[iIndexCardSelected].cardSpec, event.button.x, event.button.y, &eSay); if (eSay != NOTHING) { BOOL bCardPlayed = clickOnPlayerCard(iIndexCardSelected); if (bCardPlayed) { // card palyed // set also call m_pCoreEngine->Player_saySomething(m_iPlayer1Index, eSay); } } // stop search other cards break; } } } } for (int i = 0; i < NUMOFBUTTON; i++) { m_pbtArrayCmd[i]->MouseDown(event, m_pScreen, m_pScene_background, m_pScreenTexture); } } //////////////////////////////////////// // clickOnPlayerCard /*! A player card was clicked // \param int iIndex : index of the card clicked */ BOOL cGameMainGfx::clickOnPlayerCard(int iIndex) { BOOL bRet = FALSE; TRACE("card clicked %d\n", iIndex); if (m_bPlayerCanPlay && (m_aPlayerCards[iIndex].State == cCardGfx::CSW_ST_VISIBLE)) { BOOL bGiocAdmit = m_pCoreEngine->Player_playCard(m_iPlayer1Index, m_aPlayerCards[iIndex].cardSpec.GetCardInfo()); if (bGiocAdmit) { // card admitted m_bPlayerCanPlay = FALSE; TRACE("Player is blocked\n"); bRet = TRUE; } else { // card is not admitted // force to draw the card for a little with color reversed m_aPlayerCards[iIndex].StartShowReversed(); if (g_Options.All.bSoundEffect) { // play sound effect on error card clicked m_pMusicMgr->PlayEffect(cMusicManager::SND_EFC_CARDFALSE); m_DelayAction.CheckPoint(60, cDelayNextAction::CHANGE_AVAIL); } } } return bRet; } //////////////////////////////////////// // drawPlayedCard /*! Draw a card that was played // \param cCardGfx* pCard : card played // \param int iPlayerIx: player index that played */ void cGameMainGfx::drawPlayedCard(cCardGfx* pCard, int iPlayerIx) { ASSERT(iPlayerIx >= 0 && iPlayerIx < NUM_CARDS_PLAYED); if (g_Options.All.bAnimatePlayCard) { animatePlayCard(pCard, iPlayerIx); } else { drawStaticScene(); m_CardsTable[iPlayerIx].CopyButNoPosition(pCard); renderCard(&m_CardsTable[iPlayerIx]); pCard->SetSymbolTocard(cCardGfx::SYMBOL_BRISCNET, m_iCardWidth, m_iCardHeight, m_pScreen); renderCard(pCard); m_vctPlayedCardsGfx.push_back(&m_CardsTable[iPlayerIx]); //SDL_Flip(m_pScreen); renderScreen(); } } void cGameMainGfx::renderScreen() { SDL_UpdateTexture(m_pScreenTexture, NULL, m_pScreen->pixels, m_pScreen->pitch); // sdl 2.0 SDL_RenderCopy(m_psdlRenderer, m_pScreenTexture, NULL, NULL); SDL_RenderPresent(m_psdlRenderer); } //////////////////////////////////////// // animatePlayCard /*! // \param cCardGfx* pCard : // \param int iPlayerIx : */ void cGameMainGfx::animatePlayCard(cCardGfx* pCard, int iPlayerIx) { Uint32 uiTickTot = 0; Uint32 uiInitialTick = SDL_GetTicks(); Uint32 uiLast_time = uiInitialTick; Uint32 uiFrameRate = 3; cCardGfx cardTmp; cardTmp.Copy(pCard); cardTmp.SetDeckSurface(m_pDeck, m_iCardWidth, m_iCardHeight); int iTimeSlow = 30; switch (g_Options.All.iAniSpeedLevel) { case 0: iTimeSlow = 100; break; case 1: iTimeSlow = 60; break; case 2: iTimeSlow = 20; break; case 3: iTimeSlow = 6; break; case 4: iTimeSlow = 3; break; case 5: iTimeSlow = 1; break; default: iTimeSlow = 30; break; } cardTmp.m_iVx = (m_CardsTable[iPlayerIx].m_iX - cardTmp.m_iX) / iTimeSlow; cardTmp.m_iVy = (m_CardsTable[iPlayerIx].m_iY - cardTmp.m_iY) / iTimeSlow; // make card to play invisible and draw a background pCard->State = cCardGfx::CSW_ST_INVISIBLE; drawStaticScene(); // freeze the current display used as background SDL_Surface* pCurrentDisplay = SDL_CreateRGBSurface(SDL_SWSURFACE, m_pScreen->w, m_pScreen->h, 32, 0, 0, 0, 0); SDL_BlitSurface(m_pScreen, NULL, pCurrentDisplay, NULL); int iX0 = cardTmp.m_iX; int iY0 = cardTmp.m_iY; int iXF = m_CardsTable[iPlayerIx].m_iX; int iYF = m_CardsTable[iPlayerIx].m_iY; // use + 1 to avoid division by 0 int iM = 1; if (iXF - iX0 != 0) { iM = (iYF - iY0) * 1000 / (iXF - iX0); } int iQ = iY0 - iM * iX0 / 1000; BOOL bEnd = FALSE; BOOL bXEnd = FALSE; do { // clear screen SDL_BlitSurface(pCurrentDisplay, NULL, m_pAlphaDisplay, NULL); if (((iXF > iX0) && (iXF - iX0 < 2)) || ((iX0 >= iXF) && (iX0 - iXF < 2))) { // we need to move only on Y and not on X cardTmp.m_iY += cardTmp.m_iVy; } else { cardTmp.m_iX += cardTmp.m_iVx; if (cardTmp.m_iVx > 0) { if (cardTmp.m_iX > iXF + 4) { if (bXEnd) { // second time that X limit is reached bEnd = TRUE; } cardTmp.m_iX = iXF; bXEnd = TRUE; } } else { if (cardTmp.m_iX < iXF - 4) { if (bXEnd) { // second time that X limit is reached bEnd = TRUE; } cardTmp.m_iX = iXF; bXEnd = TRUE; } } cardTmp.m_iY = iM * cardTmp.m_iX / 1000 + iQ; } // update card position cardTmp.DrawCard(m_pAlphaDisplay); if (iPlayerIx == 0) { if (cardTmp.m_iX <= m_CardsTable[iPlayerIx].m_iX) { if (cardTmp.m_iVx < 0) { //if (cardTmp.m_iVx > -6) cardTmp.m_iVx -= 2; } else { //if (cardTmp.m_iVx < 6) cardTmp.m_iVx++; } } else { if (cardTmp.m_iVx > 0) { cardTmp.m_iVx -= 2; } else { cardTmp.m_iVx--; } } if (cardTmp.m_iY <= (m_CardsTable[iPlayerIx].m_iY)) { // cards on target bEnd = TRUE; } else { cardTmp.m_iVy -= 1; } } else if (iPlayerIx == 2) { if (cardTmp.m_iX <= m_CardsTable[iPlayerIx].m_iX) { if (cardTmp.m_iVx < 0) cardTmp.m_iVx += 2; else cardTmp.m_iVx++; } else { if (cardTmp.m_iVx > 0) cardTmp.m_iVx -= 2; else cardTmp.m_iVx--; } if (cardTmp.m_iY >= (m_CardsTable[iPlayerIx].m_iY)) { // cards outside of the screen bEnd = TRUE; } else { cardTmp.m_iVy += 1; } } else if (iPlayerIx == 1) { if (cardTmp.m_iY < m_CardsTable[iPlayerIx].m_iY) { if (cardTmp.m_iVy < 0) cardTmp.m_iVy += 2; else if (cardTmp.m_iVy < 6) cardTmp.m_iVy++; } else { if (cardTmp.m_iVy > 0) cardTmp.m_iVy -= 2; else if (cardTmp.m_iVy > -6) cardTmp.m_iVy--; } if (cardTmp.m_iX <= (m_CardsTable[iPlayerIx].m_iX)) { // cards outside of the screen bEnd = TRUE; } else { cardTmp.m_iVx -= 1; } } else if (iPlayerIx == 3) { if (cardTmp.m_iY < m_CardsTable[iPlayerIx].m_iY) { if (cardTmp.m_iVy < 0) cardTmp.m_iVy += 2; else if (cardTmp.m_iVy < 6) cardTmp.m_iVy++; } else { if (cardTmp.m_iVy > 0) cardTmp.m_iVy -= 2; else if (cardTmp.m_iVy > -6) cardTmp.m_iVy--; } if (cardTmp.m_iX >= (m_CardsTable[iPlayerIx].m_iX)) { // cards outside of the screen bEnd = TRUE; } else { cardTmp.m_iVx += 1; } } if (bEnd) { m_CardsTable[iPlayerIx].CopyButNoPosition(pCard); m_CardsTable[iPlayerIx].State = cCardGfx::CSW_ST_VISIBLE; renderCard(&m_CardsTable[iPlayerIx]); pCard->SetSymbolTocard(cCardGfx::SYMBOL_BRISCNET, m_iCardWidth, m_iCardHeight, m_pScreen); renderCard(pCard); m_vctPlayedCardsGfx.push_back(&m_CardsTable[iPlayerIx]); } SDL_BlitSurface(m_pAlphaDisplay, NULL, m_pScreen, NULL); //SDL_Flip(m_pScreen); SDL_UpdateTexture(m_pScreenTexture, NULL, m_pScreen->pixels, m_pScreen->pitch); // sdl 2.0 SDL_RenderCopy(m_psdlRenderer, m_pScreenTexture, NULL, NULL); SDL_RenderPresent(m_psdlRenderer); // synch to frame rate Uint32 uiNowTime = SDL_GetTicks(); uiTickTot = uiNowTime - uiInitialTick; if (uiNowTime < uiLast_time + uiFrameRate) { SDL_Delay(uiLast_time + uiFrameRate - uiNowTime); uiLast_time = uiNowTime; } } while (uiTickTot < 2000 && !bEnd); ASSERT(bEnd); if (!bEnd) { m_CardsTable[iPlayerIx].CopyButNoPosition(pCard); m_CardsTable[iPlayerIx].State = cCardGfx::CSW_ST_VISIBLE; renderCard(&m_CardsTable[iPlayerIx]); pCard->SetSymbolTocard(cCardGfx::SYMBOL_BRISCNET, m_iCardWidth, m_iCardHeight, m_pScreen); renderCard(pCard); m_vctPlayedCardsGfx.push_back(&m_CardsTable[iPlayerIx]); } SDL_FreeSurface(pCurrentDisplay); } //////////////////////////////////////// // HandleMouseMoveEvent /*! // \param SDL_Event &event : */ void cGameMainGfx::handleMouseMoveEvent(SDL_Event &event) { for (int i = 0; i < NUMOFBUTTON; i++) { m_pbtArrayCmd[i]->MouseMove(event, m_pScreen, m_pScene_background, m_pScreenTexture); } } //////////////////////////////////////// // HandleMouseUpEvent /*! Mouse up event // \param SDL_Event &event : */ void cGameMainGfx::handleMouseUpEvent(SDL_Event &event) { for (int i = 0; i < NUMOFBUTTON; i++) { m_pbtArrayCmd[i]->MouseUp(event); } } //////////////////////////////////////// // handleKeyDownEvent /*! User press a key on keyboard // \param SDL_Event &event : */ void cGameMainGfx::handleKeyDownEvent(SDL_Event &event) { if (event.key.keysym.sym == SDLK_n) { //startNewMatch(); drawStaticScene(); } if (event.key.keysym.sym == SDLK_a) { animateCards(); }; // Test animation if (event.key.keysym.sym == SDLK_r) { // refresh drawStaticScene(); }; // Refresh } //////////////////////////////////////// // showPlayerMarkup /*! Show a little bitmap near to the player that have to play // \param int iPlayerIx : */ void cGameMainGfx::showPlayerMarkup(int iPlayerIx) { SDL_Rect dest; if (iPlayerIx == PLAYER1) { dest.x = m_pScreen->w - m_pAnImages[IMG_TOCCA_PLAYER]->w - 20; dest.y = m_pScreen->h - m_iCardHeight / 2; } else if (iPlayerIx == PLAYER2) { dest.x = m_pScreen->w - m_pAnImages[IMG_TOCCA_PLAYER]->w - 10; dest.y = m_pScreen->h / 2; } else if (iPlayerIx == PLAYER3) { dest.x = m_pScreen->w / 2 + 10; dest.y = m_iCardHeight / 2; } else if (iPlayerIx == PLAYER4) { dest.x = 10; dest.y = m_pScreen->h / 2; } else { ASSERT(0); } dest.w = m_pAnImages[IMG_TOCCA_PLAYER]->w; dest.h = m_pAnImages[IMG_TOCCA_PLAYER]->h; SDL_BlitSurface(m_pAnImages[IMG_TOCCA_PLAYER], NULL, m_pScreen, &dest); } //////////////////////////////////////// // showPointsPlayer /*! Shows the score of the players. Caneli are drawn max 3 one the same line, egg max 2. No caneli and eggs on // the same line are possible. // \param int iPlayerIx : player index // \param VCT_INT& vct_Points : vector of points scored (sequence of 3 and 1) */ void cGameMainGfx::showPointsPlayer(int iPlayerIx, VCT_INT& vct_Points) { } //////////////////////////////////////// // showManoScore /*! Show the score of the mano using leds. */ void cGameMainGfx::showManoScore(BOOL bIsPlayed, int iPlayerIx, BOOL bIsPata, int iManoNum) { SDL_Rect dest; SDL_Rect destOff; dest.x = 400 + 16 * iManoNum; destOff.x = dest.x; int iCooYA = m_pScreen->h - 30; int iCooYB = 20; if (iPlayerIx == PLAYER1 || !bIsPlayed || bIsPata) { dest.y = iCooYA; destOff.y = iCooYB; } else if (iPlayerIx == PLAYER2) { dest.y = iCooYB; destOff.y = iCooYA; } else { ASSERT(0); } if (bIsPlayed) { // winner is ON dest.w = m_pAnImages[IMG_LEDGREEN_ON]->w; dest.h = m_pAnImages[IMG_LEDGREEN_ON]->h; SDL_BlitSurface(m_pAnImages[IMG_LEDGREEN_ON], NULL, m_pScreen, &dest); if (bIsPata) { // pata, both blue destOff.w = m_pAnImages[IMG_LED_BLUEON]->w; destOff.h = m_pAnImages[IMG_LED_BLUEON]->h; SDL_BlitSurface(m_pAnImages[IMG_LED_BLUEON], NULL, m_pScreen, &destOff); dest.w = m_pAnImages[IMG_LED_BLUEON]->w; dest.h = m_pAnImages[IMG_LED_BLUEON]->h; SDL_BlitSurface(m_pAnImages[IMG_LED_BLUEON], NULL, m_pScreen, &dest); } else { // loser is red destOff.w = m_pAnImages[IMG_LED_REDON]->w; destOff.h = m_pAnImages[IMG_LED_REDON]->h; SDL_BlitSurface(m_pAnImages[IMG_LED_REDON], NULL, m_pScreen, &destOff); } } else { // mano was not played (both off) dest.w = m_pAnImages[IMG_LEDGREEN_OFF]->w; dest.h = m_pAnImages[IMG_LEDGREEN_OFF]->h; SDL_BlitSurface(m_pAnImages[IMG_LEDGREEN_OFF], NULL, m_pScreen, &dest); destOff.w = m_pAnImages[IMG_LEDGREEN_OFF]->w; destOff.h = m_pAnImages[IMG_LEDGREEN_OFF]->h; SDL_BlitSurface(m_pAnImages[IMG_LEDGREEN_OFF], NULL, m_pScreen, &destOff); } } //////////////////////////////////////// // disableBallons /*! Disable all ballons */ void cGameMainGfx::disableBallons() { for (int i = 0; i < MAX_NUM_PLAYERS; i++) { m_pbalGfx[i]->Disable(); } } //////////////////////////////////////// // allBallonAreDisabled /*! Check if all ballon are disabled */ BOOL cGameMainGfx::allBallonAreDisabled() { BOOL bRet = TRUE; for (int i = 0; i < MAX_NUM_PLAYERS; i++) { BOOL bTemp = m_pbalGfx[i]->GetEnableState(); if (bTemp) { // one ballon is enabled bRet = FALSE; break; } } return bRet; } //////////////////////////////////////// // guiPlayerTurn /*! Inform that the player have to play using the GUI // \param int iPlayer : */ void cGameMainGfx::guiPlayerTurn(int iPlayer) { ASSERT(m_pMatchPoints); m_bPlayerCanPlay = TRUE; TRACE("Player can play\n"); m_iPlayerThatHaveMarkup = iPlayer; // update the screen drawStaticScene(); } //////////////////////////////////////// // showCurrentScore /*! Show the current match score */ void cGameMainGfx::showCurrentScore() { /* // mano score for (int iManoNum = 0; iManoNum < NUM_CARDS_HAND; iManoNum++) { BOOL bIsPata; BOOL bIsPlayed; int iPlayerIx; m_pMatchPoints->GetManoInfo(iManoNum, &iPlayerIx, &bIsPlayed, &bIsPata); showManoScore(bIsPlayed, iPlayerIx, bIsPata, iManoNum); } // grid int iX1 = 540; int iY_oriz = 45; int iX_end = iX1 + 240; int iX_vertical = iX1 + (iX_end - iX1) / 2; int iY1 = iY_oriz - 30; int iY_end = iY1 + 300; SDL_Rect dest; // vertical line int i; for ( i = iY1; i < iY_end; i += m_pAnImages[IMG_VERTICAL]->h) { dest.x = iX_vertical - 2; dest.y = i; dest.w = m_pAnImages[IMG_VERTICAL]->w; dest.h = m_pAnImages[IMG_VERTICAL]->h; SDL_BlitSurface(m_pAnImages[IMG_VERTICAL], NULL, m_pScreen, &dest); } // horizontal dest.w = m_pAnImages[IMG_HORIZONTAL]->w; dest.h = m_pAnImages[IMG_HORIZONTAL]->h; for (i = iX1; i < iX_end; i += m_pAnImages[IMG_HORIZONTAL]->w) { dest.x = i; dest.y = iY_oriz; SDL_BlitSurface(m_pAnImages[IMG_HORIZONTAL], NULL, m_pScreen, &dest); } // name on grid cPlayer* pPlayer = m_pCoreEngine->GetPlayer(PLAYER1) ; STRING strTmp = pPlayer->GetName(); int iLenName = strTmp.length(); GFX_UTIL::DrawString(m_pScreen, pPlayer->GetName(), iX_vertical -(9 * iLenName), iY1, GFX_UTIL_COLOR::White, m_pFontText); pPlayer = m_pCoreEngine->GetPlayer(PLAYER2) ; GFX_UTIL::DrawString(m_pScreen, pPlayer->GetName(), iX_vertical + 10, iY1, GFX_UTIL_COLOR::White, m_pFontText); // current giocata score eGiocataScoreState eCurrScore = m_pMatchPoints->GetCurrScore(); STRING lpsNamePoints = m_MapPunti[eCurrScore]; if (m_pMatchPoints->IsGiocataMonte()) { lpsNamePoints = m_pLangMgr->GetStringId(cLanguages::ID_S_AMONTE).c_str(); } CHAR buffTmp[256]; sprintf(buffTmp, "%s: %s", m_pLangMgr->GetStringId(cLanguages::ID_STA_PTCURRENT).c_str(), lpsNamePoints.c_str()); int tx, ty; TTF_SizeText(m_pFontText, buffTmp, &tx, &ty); int iX_posCurrScore = iX_vertical - tx/2; int iY_posCurrScore = iY_end + 10; GFX_UTIL::DrawString(m_pScreen, buffTmp, iX_posCurrScore, iY_posCurrScore, GFX_UTIL_COLOR::White, m_pFontText); //player score int iNumGiocate = m_pMatchPoints->GetNumGiocateInCurrMatch(); VCT_INT vct_Point_pl1; for (int j = 0; j < NUM_PLAY_INVIDO_2; j++) { vct_Point_pl1.clear(); for (int iNumGio = 0; iNumGio < iNumGiocate; iNumGio++ ) { cGiocataInfo GioInfo; m_pMatchPoints->GetGiocataInfo(iNumGio, &GioInfo); if (GioInfo.eScore > 0) { if (GioInfo.iPlayerIndex == j) { if (GioInfo.eScore == SC_TRASMAS) { vct_Point_pl1.push_back(3); vct_Point_pl1.push_back(3); } else if (GioInfo.eScore == SC_TRASMASNOEF) { vct_Point_pl1.push_back(3); vct_Point_pl1.push_back(3); vct_Point_pl1.push_back(3); } else if (GioInfo.eScore == SC_FUERAJEUQ) { vct_Point_pl1.push_back(3); vct_Point_pl1.push_back(3); vct_Point_pl1.push_back(3); vct_Point_pl1.push_back(3); } else if (GioInfo.eScore == SC_PARTIDA) { vct_Point_pl1.push_back(3); vct_Point_pl1.push_back(3); vct_Point_pl1.push_back(3); vct_Point_pl1.push_back(3); vct_Point_pl1.push_back(3); vct_Point_pl1.push_back(3); vct_Point_pl1.push_back(3); vct_Point_pl1.push_back(3); } else { vct_Point_pl1.push_back(GioInfo.eScore); } } } } showPointsPlayer(j, vct_Point_pl1); } */ } //////////////////////////////////////// // enableCmds /*! Enable available commands */ void cGameMainGfx::enableCmds() { } //////////////////////////////////////// // enableNumButtonsCmd /*! Enables the buttons for receiving inputs. If the parameter is 0, all buttons are disabled // \param int iNumButt : number of buttons to be enabled */ void cGameMainGfx::enableNumButtonsCmd(int iNumButt) { int i, j; for (i = 0; i < iNumButt; i++) { // enable buttons with commands m_pbtArrayCmd[i]->EnableWindow(TRUE); m_pbtArrayCmd[i]->SetState(cButtonGfx::VISIBLE); } for (j = i; j < NUMOFBUTTON; j++) { // the rest of buttons are disabled m_pbtArrayCmd[j]->EnableWindow(FALSE); m_pbtArrayCmd[j]->SetState(cButtonGfx::INVISIBLE); m_pbtArrayCmd[j]->SetWindowText("-"); m_pbtArrayCmd[j]->RedrawButton(m_pScreen, m_pScene_background, m_pScreenTexture); } } //////////////////////////////////////// // setCmdButton /*! Set the command on the button // \param int iButtonIndex : // \param eSayPlayer eSay : // \param LPCSTR strCaption : */ void cGameMainGfx::setCmdButton(int iButtonIndex, eSayPlayer eSay, LPCSTR strCaption) { if (iButtonIndex >= 0 && iButtonIndex < NUMOFBUTTON) { m_pbtArrayCmd[iButtonIndex]->SetWindowText(strCaption); m_pbtArrayCmd[iButtonIndex]->RedrawButton(m_pScreen, m_pScene_background, m_pScreenTexture); } else { ASSERT(0); } } //////////////////////////////////////// // ButCmdClicked /*! Button clicked callback // \param int iButID : button id */ void cGameMainGfx::ButCmdClicked(int iButID) { if (iButID >= 0 && iButID < NUMOFBUTTON) { //ASSERT(0); if (BUTID_EXIT == iButID) { SDL_Event event; event.type = SDL_QUIT; SDL_PushEvent(&event); } else if (BUTID_INFO == iButID) { g_MainApp->ShowHelp(); } } } //////////////////////////////////////// // NtfyTermEff /*! Effect playing is terminated // \param int iCh : */ void cGameMainGfx::NtfyTermEff(int iCh) { m_DelayAction.ChangeCurrDelay(50); } //////////////////////////////////////// // lookforDeclGoodGames /*! */ void cGameMainGfx::lookforDeclGoodGames() { VCT_GOODGAMEDETAIL vct_GGRec; VCT_CARDINFO vctMyCards; for (int j = 0; j < NUM_CARDS_HAND; j++) { vctMyCards.push_back((*m_aPlayerCards[j].cardSpec.GetCardInfo())); } // retrives all available good games AlgSupport::GetAvailbDeclGoodGames(vctMyCards, vct_GGRec); for (UINT i = 0; i < vct_GGRec.size(); i++) { m_pCoreEngine->DeclareGoodGame(m_iPlayer1Index, vct_GGRec[i].eGGval, vct_GGRec[i].eSManca); } } // *************************************************** //******** interface core callback ********** // *************************************************** //////////////////////////////////////// // ALG_Play /*! player have to play notification */ void cGameMainGfx::ALG_Play() { guiPlayerTurn(m_iPlayer1Index); if (m_iTrickRound == 0) { lookforDeclGoodGames(); } m_iTrickRound++; } //////////////////////////////////////// // ALG_Say /*! player have to responce notification */ void cGameMainGfx::ALG_Say() { } //////////////////////////////////////// // ALG_PlayerHasSaid /*! player say something // \param int iPlayerIx : // \param eSayPlayer SaySomeThing : */ void cGameMainGfx::ALG_PlayerHasSaid(int iPlayerIx, eSayPlayer SaySomeThing) { STRING lpsNameSay = m_pCoreEngine->GetComandString(SaySomeThing); if (lpsNameSay.length() == 0) return; disableBallons(); Uint32 m_uiShowTick; switch (m_iPlAlreadyPlayed) { case 0: m_uiShowTick = 4000; break; case 1: m_uiShowTick = 3500; break; case 2: m_uiShowTick = 3000; break; case 3: m_uiShowTick = 2600; break; default: m_uiShowTick = 2500; break; } m_pbalGfx[iPlayerIx]->StartShow(lpsNameSay.c_str(), m_uiShowTick); /* if (g_Options.All.bSoundEffect ) { // say also with music int iMusId = m_Map_idSynth_Say[SaySomeThing]; m_pMusicMgr->PlayEffect(iMusId); m_DelayAction.CheckPoint(60, cDelayNextAction::CHANGE_AVAIL); } */ } //////////////////////////////////////// // ALG_PlayerHasPlayed /*! player play a card // \param int iPlayerIx : // \param CardSpec Card : */ void cGameMainGfx::ALG_PlayerHasPlayed(int iPlayerIx, CARDINFO* pCard) { // disable ballon disableBallons(); CardSpec Card; Card.SetCardInfo(*pCard); // markup player that have to play cPlayer* pPlayer = 0; m_pCoreEngine->GetPlayerInPlaying(&pPlayer); ASSERT(pPlayer); if (pPlayer) { m_iPlayerThatHaveMarkup = pPlayer->GetIndex(); } bool bFound = false; if (iPlayerIx != m_iPlayer1Index) { int iOppIx = iPlayerIx - 1; // opponent play a card for (int iIndex = 0; !bFound && iIndex < NUM_CARDS_HAND; iIndex++) { if (m_aOpponentCards[iOppIx][iIndex].State == cCardGfx::CSW_ST_BACK) { m_aOpponentCards[iOppIx][iIndex].State = cCardGfx::CSW_ST_VISIBLE; m_aOpponentCards[iOppIx][iIndex].cardSpec = Card; TRACE("card played %s\n", Card.GetName()); drawPlayedCard(&m_aOpponentCards[iOppIx][iIndex], iPlayerIx); bFound = true; } } ASSERT(bFound); cPlayer* pPlayer = m_pCoreEngine->GetPlayer(iPlayerIx); } else { // user player // card was played correctly for (int iIndex = 0; !bFound && iIndex < NUM_CARDS_HAND; iIndex++) { if (m_aPlayerCards[iIndex].cardSpec == Card) { TRACE("card played %s\n", Card.GetName()); drawPlayedCard(&m_aPlayerCards[iIndex], iPlayerIx); bFound = true; } } ASSERT(bFound); } if (bFound) { // card was played correctly // make a feedback m_pMusicMgr->PlayEffect(cMusicManager::SND_EFC_CLICK); int iNumCardPlayed = m_pMatchPoints->GetCurrNumCardPlayed(); if (iNumCardPlayed == NUM_CARDS_PLAYED) { // first card played from opponent m_DelayAction.CheckPoint(1250, cDelayNextAction::NOCHANGE); } else { // opponent was not the first, delay action to show a little the current table m_DelayAction.CheckPoint(500, cDelayNextAction::NOCHANGE); } } // increment the number of players that have played m_iPlAlreadyPlayed++; } //////////////////////////////////////// // ALG_NewGiocata /*! Cards are distruited. Draw it. */ void cGameMainGfx::ALG_NewGiocata(CARDINFO* pCardArray, int iNumOfCards, int iPlayerIx) { m_bPlayerCanPlay = FALSE; TRACE("Player is blocked\n"); m_iTrickRound = 0; ASSERT(iNumOfCards == NUM_CARDS_HAND); // NOTE: to set the cards is better to use pCardArray and not using the core class. // Cards of the opponent are not yet set, so we can't display it. // This is correct because the Gfx engine operate like a player and not have to // know the opponent cards // player // store cards in vector for sorting VCT_PCARDINFO vctRecCards; for (int h = 0; h < iNumOfCards; h++) { vctRecCards.push_back(&pCardArray[h]); } // sort the recived card on suit std::sort(vctRecCards.begin(), vctRecCards.end(), cmpCardInfoSuit()); CardSpec Card; for (int i = 0; i < NUM_CARDS_HAND; i++) { Card.SetCardInfo(*vctRecCards[i]); m_aPlayerCards[i].cardSpec = Card; m_aPlayerCards[i].State = cCardGfx::CSW_ST_VISIBLE; } // opponents for (int g = 0; g < NUM_OTHER; g++) { for (int j = 0; j < NUM_CARDS_HAND; j++) { m_aOpponentCards[g][j].State = cCardGfx::CSW_ST_BACK; } } // cards played for (int k = 0; k < NUM_CARDS_PLAYED; k++) { m_CardsTable[k].State = cCardGfx::CSW_ST_INVISIBLE; } m_vctPlayedCardsGfx.clear(); if (g_Options.All.bAnimatePlayCard) { animateBeginGiocata(); } else { // restore begin scene m_DelayAction.CheckPoint(500, cDelayNextAction::CHANGE_AVAIL); drawStaticScene(); } // reset counter m_iPlAlreadyPlayed = 0; // markup to the first player cPlayer* pPlayer = 0; m_pCoreEngine->GetPlayerInPlaying(&pPlayer); ASSERT(pPlayer); if (pPlayer) { m_iPlayerThatHaveMarkup = pPlayer->GetIndex(); } } //////////////////////////////////////// // ALG_ManoEnd /*! Mano is terminated */ void cGameMainGfx::ALG_ManoEnd(I_MatchScore* pScore) { // wait a little beacuse a ballon could be shown // don't use SDL_Delay() because ballons are disabled in drawStaticScene Uint32 uiStartTime = SDL_GetTicks(); Uint32 uiNowTime = uiStartTime; Uint32 uiLast_time = uiStartTime; while (uiNowTime < uiStartTime + 2000) { uiNowTime = SDL_GetTicks(); if (uiNowTime > uiLast_time + 30) { drawStaticScene(); uiLast_time = uiNowTime; } if (allBallonAreDisabled()) { break; } } if (g_Options.All.bBlockOnManoEnd) { // wait until the user click on mouse or keyboard waitOnEvent(); } ASSERT(pScore); m_bPlayerCanPlay = FALSE; TRACE("Player is blocked\n"); int iPlayerIx = pScore->GetManoWinner(); // cards played for (int k = 0; k < NUM_CARDS_PLAYED; k++) { m_CardsTable[k].State = cCardGfx::CSW_ST_INVISIBLE; } // update the screen m_iPlayerThatHaveMarkup = iPlayerIx; drawStaticScene(); if (g_Options.All.bAnimatePlayCard) { // animate mano end animateManoEnd(iPlayerIx); } m_iPlAlreadyPlayed = 0; } //////////////////////////////////////// // ALG_GiocataEnd /*! Giocata is terminated */ void cGameMainGfx::ALG_GiocataEnd(I_MatchScore* pScore) { int iPlayerIx = pScore->GetGiocataWinner(); STRING strPuntiTot; // giocata with a winner CHAR buffText[512]; int iIndex1 = TEAM_1; int iIndex2 = TEAM_2; int iNumPl = m_pCoreEngine->GetNumOfPlayers(); if (iNumPl == 2) { iIndex2 = PLAYER2; } cPlayer* pPlayer_Team1 = m_pCoreEngine->GetPlayer(iIndex1); cPlayer* pPlayer_Team2 = m_pCoreEngine->GetPlayer(iIndex2); sprintf(buffText, "%s %s %d, %s %s %d", pPlayer_Team1->GetName(), m_pLangMgr->GetStringId(cLanguages::ID_CP_PUNTI).c_str(), pScore->GetPointsPlayer(iIndex1), pPlayer_Team2->GetName(), m_pLangMgr->GetStringId(cLanguages::ID_CP_PUNTI).c_str(), pScore->GetPointsPlayer(iIndex2)); VCT_STRING vct_Text; strPuntiTot = buffText; STRING strPuntiGio; STRING strPuntiAccuse; // retrives points of the current giocata cGiocataInfo NowInfoGio; m_pMatchPoints->GetCurrGiocataInfo(&NowInfoGio); // build the message sprintf(buffText, "%s %s %d, %s %s %d", pPlayer_Team1->GetName(), m_pLangMgr->GetStringId(cLanguages::ID_CP_PUNTI).c_str(), NowInfoGio.iPointsTeam_1, pPlayer_Team2->GetName(), m_pLangMgr->GetStringId(cLanguages::ID_CP_PUNTI).c_str(), NowInfoGio.iPointsTeam_2); strPuntiGio = buffText; // points of current giocata vct_Text.push_back(m_pLangMgr->GetStringId(cLanguages::ID_CP_PUNTIGIOCATA)); vct_Text.push_back(strPuntiGio); vct_Text.push_back(""); // points of good game declarations if (g_Options.Match.bUseGoodGameDecla) { // build the message sprintf(buffText, "%s %s %d, %s %s %d", pPlayer_Team1->GetName(), m_pLangMgr->GetStringId(cLanguages::ID_CP_PUNTI).c_str(), NowInfoGio.iAccusePointTeam_1, pPlayer_Team2->GetName(), m_pLangMgr->GetStringId(cLanguages::ID_CP_PUNTI).c_str(), NowInfoGio.iAccusePointTeam_2); strPuntiAccuse = buffText; vct_Text.push_back(m_pLangMgr->GetStringId(cLanguages::ID_CP_PUNTIACCUSE)); vct_Text.push_back(strPuntiAccuse); vct_Text.push_back(""); } // total points vct_Text.push_back(m_pLangMgr->GetStringId(cLanguages::ID_CP_PUNTITOT)); vct_Text.push_back(strPuntiTot); STRING strPartitaEndOn; sprintf(buffText, "%s %d", m_pLangMgr->GetStringId(cLanguages::ID_PUNTIMATCH_GOAL).c_str(), g_Options.Match.iScoreGoal); strPartitaEndOn = buffText; vct_Text.push_back(""); vct_Text.push_back(""); vct_Text.push_back(strPartitaEndOn); m_bPlayerCanPlay = FALSE; TRACE("Player is blocked\n"); // draw a background and scene drawStaticScene(); // little animation animGiocataEnd(iPlayerIx); // show results in a multiline messagebox showResultMsgBox(vct_Text); } //////////////////////////////////////// // ALG_MatchEnd /*! Match is end */ void cGameMainGfx::ALG_MatchEnd(I_MatchScore* pScore) { int iPlayerIx = pScore->GetMatchWinner(); int iPlayLoser; if (iPlayerIx == m_iPlayer1Index) { iPlayLoser = m_iOpponentIndex; } else { iPlayLoser = m_iPlayer1Index; } cPlayer* pPlayer = m_pCoreEngine->GetPlayer(iPlayerIx); cPlayer* pPlLoser = m_pCoreEngine->GetPlayer(iPlayLoser); m_bPlayerCanPlay = FALSE; TRACE("Player is blocked\n"); // partita finita. player vince x:x CHAR buff[256]; sprintf(buff, "%s. %s %s %d : %d.", m_pLangMgr->GetStringId(cLanguages::ID_CP_PARTITAFIN).c_str(), pPlayer->GetName(), m_pLangMgr->GetStringId(cLanguages::ID_CP_VINCE).c_str(), pScore->GetPointsPlayer(iPlayerIx), pScore->GetPointsPlayer(iPlayLoser)); drawStaticScene(); showOkMsgBox(buff); m_bMatchTerminated = TRUE; } //////////////////////////////////////// // ALG_GicataScoreChange /*! giocata score changed // \param eGiocataScoreState eNewScore : */ void cGameMainGfx::ALG_GicataScoreChange(eGiocataScoreState eNewScore) { } //////////////////////////////////////// // ALG_PLayerSaidFalse /*! // \param int iPlayerIx : */ void cGameMainGfx::ALG_PLayerSaidFalse(int iPlayerIx) { } //////////////////////////////////////// // ALG_PLayerDeclareGoodGame /*! Display a call of a good game // \param int iPlayerIx : player that make the good game // \param eDeclGoodGame eValgg : good game value // \param eSUIT eValsuit : suit to complete the declaration */ void cGameMainGfx::ALG_PLayerDeclareGoodGame(int iPlayerIx, eDeclGoodGame eValgg, eSEED eValsuit) { STRING strTmp; STRING strTmp1; // we need a word sbaglia or senza STRING strSenza; if (m_pCoreEngine->GetLocalType() == LT_BREDA) { strSenza = m_pLangMgr->GetStringId(cLanguages::ID_A_SBAGLIA); } else { strSenza = m_pLangMgr->GetStringId(cLanguages::ID_A_SENZA); } switch (eValgg) { case TRE_TRE: strTmp = m_pLangMgr->GetStringId(cLanguages::ID_A_TRETRE); break; case TRE_DUE: strTmp = m_pLangMgr->GetStringId(cLanguages::ID_A_TREDUE); break; case TRE_ASSI: strTmp = m_pLangMgr->GetStringId(cLanguages::ID_A_TREASSI); break; case QUATTRO_TRE: strTmp = m_pLangMgr->GetStringId(cLanguages::ID_A_4TRE); strSenza = ""; break; case QUATTRO_DUE: strTmp = m_pLangMgr->GetStringId(cLanguages::ID_A_4DUE); strSenza = ""; break; case QUATTRO_ASSI: strTmp = m_pLangMgr->GetStringId(cLanguages::ID_A_4ASSI); strSenza = ""; break; case NAPOLETANA: strTmp = m_pLangMgr->GetStringId(cLanguages::ID_A_NAPOLA); strSenza = ""; break; default: ASSERT(0); break; } switch (eValsuit) { case BASTONI: strTmp1 = m_pLangMgr->GetStringId(cLanguages::ID_A_BASTONI); break; case COPPE: strTmp1 = m_pLangMgr->GetStringId(cLanguages::ID_A_COPPE); break; case DENARI: strTmp1 = m_pLangMgr->GetStringId(cLanguages::ID_A_DENARI); break; case SPADE: strTmp1 = m_pLangMgr->GetStringId(cLanguages::ID_A_SPADE); break; default: strTmp1 = ""; break; } STRING strLine; if (strSenza.length() > 0) { strLine = strTmp + " " + strSenza + " " + strTmp1; } else { strLine = strTmp + " " + strTmp1; } showDeclarMsgBox(iPlayerIx, strLine.c_str()); } //////////////////////////////////////// // INP_PlayerSay /*! // \param eSayPlayer eSay : */ void cGameMainGfx::INP_PlayerSay(eSayPlayer eSay) { m_pCoreEngine->Player_saySomething(m_iPlayer1Index, eSay); }
28.037484
129
0.555675
aaaasmile
6576e499016076640224d7fdb994a7bed306b7c9
13,304
cpp
C++
extern/libebml/src/src/EbmlCrc32.cpp
MinjingLin/Azure-Kinect-Sensor-SDK-bk
ff2b5b1ca7578355c40d1c5230b9d8b7511ebae5
[ "MIT" ]
46
2016-07-05T14:55:24.000Z
2021-12-24T05:10:00.000Z
extern/libebml/src/src/EbmlCrc32.cpp
MinjingLin/Azure-Kinect-Sensor-SDK-bk
ff2b5b1ca7578355c40d1c5230b9d8b7511ebae5
[ "MIT" ]
8
2018-05-25T07:36:41.000Z
2021-04-08T14:27:54.000Z
extern/libebml/src/src/EbmlCrc32.cpp
MinjingLin/Azure-Kinect-Sensor-SDK-bk
ff2b5b1ca7578355c40d1c5230b9d8b7511ebae5
[ "MIT" ]
16
2016-05-29T13:39:23.000Z
2022-02-22T13:53:05.000Z
/**************************************************************************** ** libebml : parse EBML files, see http://embl.sourceforge.net/ ** ** <file/class description> ** ** Copyright (C) 2002-2010 Steve Lhomme. All rights reserved. ** ** This file is part of libebml. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** You should have received a copy of the GNU Lesser General Public ** License along with this library; if not, write to the Free Software ** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ** ** See http://www.gnu.org/licenses/lgpl-2.1.html for LGPL licensing information. ** ** Contact license@matroska.org if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ /*! \file \version \$Id: EbmlCrc32.cpp 1155 2005-05-06 11:43:38Z robux4 $ \author Steve Lhomme <robux4 @ users.sf.net> \author Jory Stone <jcsston @ toughguy.net> */ #include "ebml/EbmlCrc32.h" #include "ebml/EbmlContexts.h" #include "ebml/MemIOCallback.h" #ifdef WORDS_BIGENDIAN # define CRC32_INDEX(c) (c >> 24) # define CRC32_SHIFTED(c) (c << 8) #else # define CRC32_INDEX(c) (c & 0xff) # define CRC32_SHIFTED(c) (c >> 8) #endif const uint32 CRC32_NEGL = 0xffffffffL; START_LIBEBML_NAMESPACE DEFINE_EBML_CLASS_GLOBAL(EbmlCrc32, 0xBF, 1, "EBMLCrc32\0ratamadabapa"); const uint32 EbmlCrc32::m_tab[] = { #ifdef WORDS_BIGENDIAN 0x00000000L, 0x96300777L, 0x2c610eeeL, 0xba510999L, 0x19c46d07L, 0x8ff46a70L, 0x35a563e9L, 0xa395649eL, 0x3288db0eL, 0xa4b8dc79L, 0x1ee9d5e0L, 0x88d9d297L, 0x2b4cb609L, 0xbd7cb17eL, 0x072db8e7L, 0x911dbf90L, 0x6410b71dL, 0xf220b06aL, 0x4871b9f3L, 0xde41be84L, 0x7dd4da1aL, 0xebe4dd6dL, 0x51b5d4f4L, 0xc785d383L, 0x56986c13L, 0xc0a86b64L, 0x7af962fdL, 0xecc9658aL, 0x4f5c0114L, 0xd96c0663L, 0x633d0ffaL, 0xf50d088dL, 0xc8206e3bL, 0x5e10694cL, 0xe44160d5L, 0x727167a2L, 0xd1e4033cL, 0x47d4044bL, 0xfd850dd2L, 0x6bb50aa5L, 0xfaa8b535L, 0x6c98b242L, 0xd6c9bbdbL, 0x40f9bcacL, 0xe36cd832L, 0x755cdf45L, 0xcf0dd6dcL, 0x593dd1abL, 0xac30d926L, 0x3a00de51L, 0x8051d7c8L, 0x1661d0bfL, 0xb5f4b421L, 0x23c4b356L, 0x9995bacfL, 0x0fa5bdb8L, 0x9eb80228L, 0x0888055fL, 0xb2d90cc6L, 0x24e90bb1L, 0x877c6f2fL, 0x114c6858L, 0xab1d61c1L, 0x3d2d66b6L, 0x9041dc76L, 0x0671db01L, 0xbc20d298L, 0x2a10d5efL, 0x8985b171L, 0x1fb5b606L, 0xa5e4bf9fL, 0x33d4b8e8L, 0xa2c90778L, 0x34f9000fL, 0x8ea80996L, 0x18980ee1L, 0xbb0d6a7fL, 0x2d3d6d08L, 0x976c6491L, 0x015c63e6L, 0xf4516b6bL, 0x62616c1cL, 0xd8306585L, 0x4e0062f2L, 0xed95066cL, 0x7ba5011bL, 0xc1f40882L, 0x57c40ff5L, 0xc6d9b065L, 0x50e9b712L, 0xeab8be8bL, 0x7c88b9fcL, 0xdf1ddd62L, 0x492dda15L, 0xf37cd38cL, 0x654cd4fbL, 0x5861b24dL, 0xce51b53aL, 0x7400bca3L, 0xe230bbd4L, 0x41a5df4aL, 0xd795d83dL, 0x6dc4d1a4L, 0xfbf4d6d3L, 0x6ae96943L, 0xfcd96e34L, 0x468867adL, 0xd0b860daL, 0x732d0444L, 0xe51d0333L, 0x5f4c0aaaL, 0xc97c0dddL, 0x3c710550L, 0xaa410227L, 0x10100bbeL, 0x86200cc9L, 0x25b56857L, 0xb3856f20L, 0x09d466b9L, 0x9fe461ceL, 0x0ef9de5eL, 0x98c9d929L, 0x2298d0b0L, 0xb4a8d7c7L, 0x173db359L, 0x810db42eL, 0x3b5cbdb7L, 0xad6cbac0L, 0x2083b8edL, 0xb6b3bf9aL, 0x0ce2b603L, 0x9ad2b174L, 0x3947d5eaL, 0xaf77d29dL, 0x1526db04L, 0x8316dc73L, 0x120b63e3L, 0x843b6494L, 0x3e6a6d0dL, 0xa85a6a7aL, 0x0bcf0ee4L, 0x9dff0993L, 0x27ae000aL, 0xb19e077dL, 0x44930ff0L, 0xd2a30887L, 0x68f2011eL, 0xfec20669L, 0x5d5762f7L, 0xcb676580L, 0x71366c19L, 0xe7066b6eL, 0x761bd4feL, 0xe02bd389L, 0x5a7ada10L, 0xcc4add67L, 0x6fdfb9f9L, 0xf9efbe8eL, 0x43beb717L, 0xd58eb060L, 0xe8a3d6d6L, 0x7e93d1a1L, 0xc4c2d838L, 0x52f2df4fL, 0xf167bbd1L, 0x6757bca6L, 0xdd06b53fL, 0x4b36b248L, 0xda2b0dd8L, 0x4c1b0aafL, 0xf64a0336L, 0x607a0441L, 0xc3ef60dfL, 0x55df67a8L, 0xef8e6e31L, 0x79be6946L, 0x8cb361cbL, 0x1a8366bcL, 0xa0d26f25L, 0x36e26852L, 0x95770cccL, 0x03470bbbL, 0xb9160222L, 0x2f260555L, 0xbe3bbac5L, 0x280bbdb2L, 0x925ab42bL, 0x046ab35cL, 0xa7ffd7c2L, 0x31cfd0b5L, 0x8b9ed92cL, 0x1daede5bL, 0xb0c2649bL, 0x26f263ecL, 0x9ca36a75L, 0x0a936d02L, 0xa906099cL, 0x3f360eebL, 0x85670772L, 0x13570005L, 0x824abf95L, 0x147ab8e2L, 0xae2bb17bL, 0x381bb60cL, 0x9b8ed292L, 0x0dbed5e5L, 0xb7efdc7cL, 0x21dfdb0bL, 0xd4d2d386L, 0x42e2d4f1L, 0xf8b3dd68L, 0x6e83da1fL, 0xcd16be81L, 0x5b26b9f6L, 0xe177b06fL, 0x7747b718L, 0xe65a0888L, 0x706a0fffL, 0xca3b0666L, 0x5c0b0111L, 0xff9e658fL, 0x69ae62f8L, 0xd3ff6b61L, 0x45cf6c16L, 0x78e20aa0L, 0xeed20dd7L, 0x5483044eL, 0xc2b30339L, 0x612667a7L, 0xf71660d0L, 0x4d476949L, 0xdb776e3eL, 0x4a6ad1aeL, 0xdc5ad6d9L, 0x660bdf40L, 0xf03bd837L, 0x53aebca9L, 0xc59ebbdeL, 0x7fcfb247L, 0xe9ffb530L, 0x1cf2bdbdL, 0x8ac2bacaL, 0x3093b353L, 0xa6a3b424L, 0x0536d0baL, 0x9306d7cdL, 0x2957de54L, 0xbf67d923L, 0x2e7a66b3L, 0xb84a61c4L, 0x021b685dL, 0x942b6f2aL, 0x37be0bb4L, 0xa18e0cc3L, 0x1bdf055aL, 0x8def022dL #else 0x00000000L, 0x77073096L, 0xee0e612cL, 0x990951baL, 0x076dc419L, 0x706af48fL, 0xe963a535L, 0x9e6495a3L, 0x0edb8832L, 0x79dcb8a4L, 0xe0d5e91eL, 0x97d2d988L, 0x09b64c2bL, 0x7eb17cbdL, 0xe7b82d07L, 0x90bf1d91L, 0x1db71064L, 0x6ab020f2L, 0xf3b97148L, 0x84be41deL, 0x1adad47dL, 0x6ddde4ebL, 0xf4d4b551L, 0x83d385c7L, 0x136c9856L, 0x646ba8c0L, 0xfd62f97aL, 0x8a65c9ecL, 0x14015c4fL, 0x63066cd9L, 0xfa0f3d63L, 0x8d080df5L, 0x3b6e20c8L, 0x4c69105eL, 0xd56041e4L, 0xa2677172L, 0x3c03e4d1L, 0x4b04d447L, 0xd20d85fdL, 0xa50ab56bL, 0x35b5a8faL, 0x42b2986cL, 0xdbbbc9d6L, 0xacbcf940L, 0x32d86ce3L, 0x45df5c75L, 0xdcd60dcfL, 0xabd13d59L, 0x26d930acL, 0x51de003aL, 0xc8d75180L, 0xbfd06116L, 0x21b4f4b5L, 0x56b3c423L, 0xcfba9599L, 0xb8bda50fL, 0x2802b89eL, 0x5f058808L, 0xc60cd9b2L, 0xb10be924L, 0x2f6f7c87L, 0x58684c11L, 0xc1611dabL, 0xb6662d3dL, 0x76dc4190L, 0x01db7106L, 0x98d220bcL, 0xefd5102aL, 0x71b18589L, 0x06b6b51fL, 0x9fbfe4a5L, 0xe8b8d433L, 0x7807c9a2L, 0x0f00f934L, 0x9609a88eL, 0xe10e9818L, 0x7f6a0dbbL, 0x086d3d2dL, 0x91646c97L, 0xe6635c01L, 0x6b6b51f4L, 0x1c6c6162L, 0x856530d8L, 0xf262004eL, 0x6c0695edL, 0x1b01a57bL, 0x8208f4c1L, 0xf50fc457L, 0x65b0d9c6L, 0x12b7e950L, 0x8bbeb8eaL, 0xfcb9887cL, 0x62dd1ddfL, 0x15da2d49L, 0x8cd37cf3L, 0xfbd44c65L, 0x4db26158L, 0x3ab551ceL, 0xa3bc0074L, 0xd4bb30e2L, 0x4adfa541L, 0x3dd895d7L, 0xa4d1c46dL, 0xd3d6f4fbL, 0x4369e96aL, 0x346ed9fcL, 0xad678846L, 0xda60b8d0L, 0x44042d73L, 0x33031de5L, 0xaa0a4c5fL, 0xdd0d7cc9L, 0x5005713cL, 0x270241aaL, 0xbe0b1010L, 0xc90c2086L, 0x5768b525L, 0x206f85b3L, 0xb966d409L, 0xce61e49fL, 0x5edef90eL, 0x29d9c998L, 0xb0d09822L, 0xc7d7a8b4L, 0x59b33d17L, 0x2eb40d81L, 0xb7bd5c3bL, 0xc0ba6cadL, 0xedb88320L, 0x9abfb3b6L, 0x03b6e20cL, 0x74b1d29aL, 0xead54739L, 0x9dd277afL, 0x04db2615L, 0x73dc1683L, 0xe3630b12L, 0x94643b84L, 0x0d6d6a3eL, 0x7a6a5aa8L, 0xe40ecf0bL, 0x9309ff9dL, 0x0a00ae27L, 0x7d079eb1L, 0xf00f9344L, 0x8708a3d2L, 0x1e01f268L, 0x6906c2feL, 0xf762575dL, 0x806567cbL, 0x196c3671L, 0x6e6b06e7L, 0xfed41b76L, 0x89d32be0L, 0x10da7a5aL, 0x67dd4accL, 0xf9b9df6fL, 0x8ebeeff9L, 0x17b7be43L, 0x60b08ed5L, 0xd6d6a3e8L, 0xa1d1937eL, 0x38d8c2c4L, 0x4fdff252L, 0xd1bb67f1L, 0xa6bc5767L, 0x3fb506ddL, 0x48b2364bL, 0xd80d2bdaL, 0xaf0a1b4cL, 0x36034af6L, 0x41047a60L, 0xdf60efc3L, 0xa867df55L, 0x316e8eefL, 0x4669be79L, 0xcb61b38cL, 0xbc66831aL, 0x256fd2a0L, 0x5268e236L, 0xcc0c7795L, 0xbb0b4703L, 0x220216b9L, 0x5505262fL, 0xc5ba3bbeL, 0xb2bd0b28L, 0x2bb45a92L, 0x5cb36a04L, 0xc2d7ffa7L, 0xb5d0cf31L, 0x2cd99e8bL, 0x5bdeae1dL, 0x9b64c2b0L, 0xec63f226L, 0x756aa39cL, 0x026d930aL, 0x9c0906a9L, 0xeb0e363fL, 0x72076785L, 0x05005713L, 0x95bf4a82L, 0xe2b87a14L, 0x7bb12baeL, 0x0cb61b38L, 0x92d28e9bL, 0xe5d5be0dL, 0x7cdcefb7L, 0x0bdbdf21L, 0x86d3d2d4L, 0xf1d4e242L, 0x68ddb3f8L, 0x1fda836eL, 0x81be16cdL, 0xf6b9265bL, 0x6fb077e1L, 0x18b74777L, 0x88085ae6L, 0xff0f6a70L, 0x66063bcaL, 0x11010b5cL, 0x8f659effL, 0xf862ae69L, 0x616bffd3L, 0x166ccf45L, 0xa00ae278L, 0xd70dd2eeL, 0x4e048354L, 0x3903b3c2L, 0xa7672661L, 0xd06016f7L, 0x4969474dL, 0x3e6e77dbL, 0xaed16a4aL, 0xd9d65adcL, 0x40df0b66L, 0x37d83bf0L, 0xa9bcae53L, 0xdebb9ec5L, 0x47b2cf7fL, 0x30b5ffe9L, 0xbdbdf21cL, 0xcabac28aL, 0x53b39330L, 0x24b4a3a6L, 0xbad03605L, 0xcdd70693L, 0x54de5729L, 0x23d967bfL, 0xb3667a2eL, 0xc4614ab8L, 0x5d681b02L, 0x2a6f2b94L, 0xb40bbe37L, 0xc30c8ea1L, 0x5a05df1bL, 0x2d02ef8dL #endif }; EbmlCrc32::EbmlCrc32() { ResetCRC(); SetDefaultSize(4); m_crc_final = 0; SetSize_(4); //This EbmlElement has been set // SetValueIsSet(); } EbmlCrc32::EbmlCrc32(const EbmlCrc32 & ElementToClone) :EbmlBinary(ElementToClone) { m_crc = ElementToClone.m_crc; m_crc_final = ElementToClone.m_crc_final; } void EbmlCrc32::ResetCRC() { m_crc = CRC32_NEGL; } void EbmlCrc32::UpdateByte(binary b) { m_crc = m_tab[CRC32_INDEX(m_crc) ^ b] ^ CRC32_SHIFTED(m_crc); } void EbmlCrc32::AddElementCRC32(EbmlElement &ElementToCRC) { // Use a special IOCallback class that Render's to memory instead of to disk MemIOCallback memoryBuffer; ElementToCRC.Render(memoryBuffer, true, true); Update(memoryBuffer.GetDataBuffer(), memoryBuffer.GetDataBufferSize()); // Finalize(); }; bool EbmlCrc32::CheckElementCRC32(EbmlElement &ElementToCRC) { MemIOCallback memoryBuffer; ElementToCRC.Render(memoryBuffer); return CheckCRC(m_crc_final, memoryBuffer.GetDataBuffer(), memoryBuffer.GetDataBufferSize()); }; filepos_t EbmlCrc32::RenderData(IOCallback & output, bool /* bForceRender */, bool /* bWithDefault */) { filepos_t Result = 4; if (Result != 0) { output.writeFully(&m_crc_final, Result); } if (Result < GetDefaultSize()) { // pad the rest with 0 binary *Pad = new (std::nothrow) binary[GetDefaultSize() - Result]; if (Pad != NULL) { memset(Pad, 0x00, GetDefaultSize() - Result); output.writeFully(Pad, GetDefaultSize() - Result); Result = GetDefaultSize(); delete [] Pad; } } return Result; } filepos_t EbmlCrc32::ReadData(IOCallback & input, ScopeMode ReadFully) { if (ReadFully != SCOPE_NO_DATA) { binary *Buffer = new (std::nothrow) binary[GetSize()]; if (Buffer == NULL) { // impossible to read, skip it input.setFilePointer(GetSize(), seek_current); } else { input.readFully(Buffer, GetSize()); memcpy((void *)&m_crc_final, Buffer, 4); delete [] Buffer; SetValueIsSet(); } } return GetSize(); } bool EbmlCrc32::CheckCRC(uint32 inputCRC, const binary *input, uint32 length) { uint32 crc = CRC32_NEGL; for(; !IsAligned<uint32>(input) && length > 0; length--) crc = m_tab[CRC32_INDEX(crc) ^ *input++] ^ CRC32_SHIFTED(crc); while (length >= 4) { crc ^= *(const uint32 *)input; crc = m_tab[CRC32_INDEX(crc)] ^ CRC32_SHIFTED(crc); crc = m_tab[CRC32_INDEX(crc)] ^ CRC32_SHIFTED(crc); crc = m_tab[CRC32_INDEX(crc)] ^ CRC32_SHIFTED(crc); crc = m_tab[CRC32_INDEX(crc)] ^ CRC32_SHIFTED(crc); length -= 4; input += 4; } while (length--) crc = m_tab[CRC32_INDEX(crc) ^ *input++] ^ CRC32_SHIFTED(crc); //Now we finalize the CRC32 crc ^= CRC32_NEGL; if (crc == inputCRC) return true; return false; }; void EbmlCrc32::FillCRC32(const binary *s, uint32 n) { ResetCRC(); Update(s, n); Finalize(); /*uint32 crc = CRC32_NEGL; for(; !IsAligned<uint32>(s) && n > 0; n--) crc = m_tab[CRC32_INDEX(crc) ^ *s++] ^ CRC32_SHIFTED(crc); while (n >= 4) { crc ^= *(const uint32 *)s; crc = m_tab[CRC32_INDEX(crc)] ^ CRC32_SHIFTED(crc); crc = m_tab[CRC32_INDEX(crc)] ^ CRC32_SHIFTED(crc); crc = m_tab[CRC32_INDEX(crc)] ^ CRC32_SHIFTED(crc); crc = m_tab[CRC32_INDEX(crc)] ^ CRC32_SHIFTED(crc); n -= 4; s += 4; } while (n--) crc = m_tab[CRC32_INDEX(crc) ^ *s++] ^ CRC32_SHIFTED(crc); m_crc = crc; //Now we finalize the CRC32 m_crc ^= CRC32_NEGL; //for (unsigned int i = 0; i < 4; i++) // (&last_crc32)[i] = GetCrcByte(i);*/ } void EbmlCrc32::Update(const binary *input, uint32 length) { uint32 crc = m_crc; for(; !IsAligned<uint32>(input) && length > 0; length--) crc = m_tab[CRC32_INDEX(crc) ^ *input++] ^ CRC32_SHIFTED(crc); while (length >= 4) { crc ^= *(const uint32 *)input; crc = m_tab[CRC32_INDEX(crc)] ^ CRC32_SHIFTED(crc); crc = m_tab[CRC32_INDEX(crc)] ^ CRC32_SHIFTED(crc); crc = m_tab[CRC32_INDEX(crc)] ^ CRC32_SHIFTED(crc); crc = m_tab[CRC32_INDEX(crc)] ^ CRC32_SHIFTED(crc); length -= 4; input += 4; } while (length--) crc = m_tab[CRC32_INDEX(crc) ^ *input++] ^ CRC32_SHIFTED(crc); m_crc = crc; } void EbmlCrc32::Finalize() { //Finalize the CRC32 m_crc ^= CRC32_NEGL; //Copy it over to completed CRC32 memeber m_crc_final = m_crc; //Reset the holding CRC member (m_crc) ResetCRC(); //This EbmlElement has been set SetValueIsSet(); } END_LIBEBML_NAMESPACE
37.903134
102
0.741206
MinjingLin
6583058fb30183899862e7a0f1c33f57e939399b
3,560
cpp
C++
interpretador.cpp
viniciusfer01/SculptorTheReturn
9c80c9fc4c8a74759d1663e9b57a4d9199e2b2e2
[ "MIT" ]
null
null
null
interpretador.cpp
viniciusfer01/SculptorTheReturn
9c80c9fc4c8a74759d1663e9b57a4d9199e2b2e2
[ "MIT" ]
null
null
null
interpretador.cpp
viniciusfer01/SculptorTheReturn
9c80c9fc4c8a74759d1663e9b57a4d9199e2b2e2
[ "MIT" ]
null
null
null
#include "interpretador.h" #include <fstream> #include <sstream> #include <string> #include <iostream> #include <string.h> #include <vector> #include "putbox.h" #include "putellipsoid.h" #include "putsphere.h" #include "putvoxel.h" #include "cutbox.h" #include "cutellipsoid.h" #include "cutsphere.h" #include "cutvoxel.h" using namespace std; Interpretador::Interpretador(){ } std::vector<FiguraGeometrica *> Interpretador::parse(std::string filename){ std::vector<FiguraGeometrica*> figs; std::ifstream fin; std::stringstream ss; std::string s, token; ofstream entrada; //entrada.open("ler.txt"); fin.open("ler.txt"); if(!fin.is_open()){ cout<<"Erro ao abrir o arquivo ou arquivo inexistente"<<endl; exit(0); } while(fin.good()){ getline(fin, s); if(fin.good()){ ss.clear(); ss.str(s); ss >> token; if(ss.good()){ if(token.compare("dim") == 0){ ss >> dimx >> dimy >> dimz; } else if(token.compare("putvoxel") == 0){ int x, y, z; ss >> x >> y >> z >> r >> g >> b >> a; figs.push_back(new putvoxel(x, y, z, r, g, b, a)); } else if(token.compare("cutvoxel") == 0){ int x, y, z; ss >> x >> y >> z; figs.push_back(new cutvoxel(x, y, z)); } else if(token.compare("putbox") == 0){ int x0, x1, y0, y1, z0, z1; ss >> x0 >> x1 >> y0 >> y1 >> z0 >> z1 >> r >> g >> b >> a; figs.push_back(new PutBox(x0, x1, y0, y1, z0, z1, r, g, b, a)); } else if(token.compare("cutbox") == 0){ int x0, x1, y0, y1, z0, z1; ss >> x0 >> x1 >> y0 >> y1 >> z0 >> z1; figs.push_back(new CutBox(x0, x1, y0, y1, z0, z1)); } else if(token.compare("putsphere") == 0){ int xcenter, ycenter, zcenter, radius; ss >> xcenter >> ycenter >> zcenter >> radius >> r >> g >> b >> a; figs.push_back(new putsphere(xcenter, ycenter, zcenter, radius, r, g, b, a)); } else if(token.compare("cutsphere") == 0){ int xcenter, ycenter, zcenter, radius; ss >> xcenter >> ycenter >> zcenter >> radius; figs.push_back(new cutsphere(xcenter, ycenter, zcenter, radius)); } else if(token.compare("putellipsoid") == 0){ int xcenter, ycenter, zcenter, rx, ry, rz; ss >> xcenter >> ycenter >> zcenter >> rx >> ry >> rz >> r >> g >> b >> a; figs.push_back(new putellipsoid(xcenter, ycenter, zcenter, rx, ry, rz, r, g, b, a)); } else if(token.compare("cutellipsoid") == 0){ int xcenter, ycenter, zcenter, rx, ry, rz; ss >> xcenter >> ycenter >> zcenter >> rx >> ry >> rz; figs.push_back(new cutellipsoid(xcenter, ycenter, zcenter, rx, ry, rz)); } } } } return(figs); } int Interpretador::getDimx(){ return dimx; } int Interpretador::getDimy(){ return dimy; } int Interpretador::getDimz(){ return dimz; }
32.072072
104
0.458427
viniciusfer01
658329ac20085ef0ced31e4bbfe4ead8ae468281
2,453
cpp
C++
modules/camera_calibration/event/src/EventFrame.cpp
MobilePerceptionLab/EventCameraCalibration
debd774ac989674b500caf27641b7ad4e94681e9
[ "Apache-2.0" ]
22
2021-08-06T03:21:03.000Z
2022-02-25T03:40:54.000Z
modules/camera_calibration/event/src/EventFrame.cpp
MobilePerceptionLab/EventCameraCalibration
debd774ac989674b500caf27641b7ad4e94681e9
[ "Apache-2.0" ]
1
2022-02-25T02:55:13.000Z
2022-02-25T15:18:45.000Z
modules/camera_calibration/event/src/EventFrame.cpp
MobilePerceptionLab/EventCameraCalibration
debd774ac989674b500caf27641b7ad4e94681e9
[ "Apache-2.0" ]
7
2021-08-11T12:29:35.000Z
2022-02-25T03:41:01.000Z
// // Created by huangkun on 2020/9/22. // #include <Eigen/Eigen> #include <opencv2/core/eigen.hpp> #include <opengv2/event/EventFrame.hpp> opengv2::EventFrame::EventFrame(opengv2::EventContainer::Ptr container, const std::pair<double, double> &duration) : CameraFrame(cv::Mat(), container->camera), container_(container), duration_(duration) { std::unordered_set<Eigen::Vector2d, EigenMatrixHash<Eigen::Vector2d>, std::equal_to<>, Eigen::aligned_allocator<Eigen::Vector2d>> positiveEvents, negativeEvents; for (auto itr = container_->container.lower_bound(duration_.first); itr != container_->container.upper_bound(duration_.second); itr++) { if (itr->second.polarity) { positiveEvents.insert(itr->second.location); } else { negativeEvents.insert(itr->second.location); } } // delete event, which have + and - event at the same pixel for (auto itr = positiveEvents.begin(); itr != positiveEvents.end();) { auto found = negativeEvents.find(*itr); if (found == negativeEvents.end()) { itr++; } else { negativeEvents.erase(found); itr = positiveEvents.erase(itr); } } std::move(positiveEvents.begin(), positiveEvents.end(), std::back_inserter(positiveEvents_)); std::move(negativeEvents.begin(), negativeEvents.end(), std::back_inserter(negativeEvents_)); } cv::Mat opengv2::EventFrame::undistortedImage(CameraBase::Ptr camera) const { cv::Mat image = cv::Mat(std::round(camera->size()[1] * 1.2), std::round(camera->size()[0] * 1.2), CV_8UC3, cv::Vec3b(0, 0, 0)); if (positiveEvents_.empty() || negativeEvents_.empty()) { throw std::logic_error("Events in Frame was cleared."); } for (const Eigen::Vector2d &p: positiveEvents_) { Eigen::Vector2d p_c = camera->undistortPoint(p); cv::Point loc(std::round(p_c[0] + camera->size()[0] * 0.1), std::round(p_c[1] + camera->size()[1] * 0.1)); image.at<cv::Vec3b>(loc) = cv::Vec3b(0, 0, 255); } for (const Eigen::Vector2d &p: negativeEvents_) { Eigen::Vector2d p_c = camera->undistortPoint(p); cv::Point loc(std::round(p_c[0] + camera->size()[0] * 0.1), std::round(p_c[1] + camera->size()[1] * 0.1)); image.at<cv::Vec3b>(loc) = cv::Vec3b(0, 255, 0); } return image; }
40.883333
114
0.611088
MobilePerceptionLab
658745b8c3dc60105bf8f831f56dea8706b674b8
2,371
hpp
C++
input/Key.hpp
quyse/inanity
a39225c5a41f879abe5aa492bb22b500dbe77433
[ "MIT" ]
26
2015-04-22T05:25:25.000Z
2020-11-15T11:07:56.000Z
input/Key.hpp
quyse/inanity
a39225c5a41f879abe5aa492bb22b500dbe77433
[ "MIT" ]
2
2015-01-05T10:41:27.000Z
2015-01-06T20:46:11.000Z
input/Key.hpp
quyse/inanity
a39225c5a41f879abe5aa492bb22b500dbe77433
[ "MIT" ]
5
2016-08-02T11:13:57.000Z
2018-10-26T11:19:27.000Z
#ifndef ___INANITY_INPUT_KEY_HPP___ #define ___INANITY_INPUT_KEY_HPP___ #include "input.hpp" BEGIN_INANITY_INPUT /// Key numbers. /** Cross-platform, but are got mostly from X11 key numbers. */ struct Keys { enum _ { _Unknown = 0, BackSpace = 0x08, Tab = 0x09, LineFeed = 0x0a, Clear = 0x0b, Return = 0x0d, Pause = 0x13, ScrollLock = 0x14, SysReq = 0x15, Escape = 0x1b, Insert = 0x1c, Delete = 0x1d, Space = ' ', // 0x20 Plus = '+', // 0x2b Comma = ',', // 0x2c Hyphen = '-', // 0x2d Period = '.', // 0x2e Slash = '/', // 0x2f _0 = '0', // 0x30 _1 = '1', _2 = '2', _3 = '3', _4 = '4', _5 = '5', _6 = '6', _7 = '7', _8 = '8', _9 = '9', // 0x39 A = 'A', // 0x41 B = 'B', C = 'C', D = 'D', E = 'E', F = 'F', G = 'G', H = 'H', I = 'I', J = 'J', K = 'K', L = 'L', M = 'M', N = 'N', O = 'O', P = 'P', Q = 'Q', R = 'R', S = 'S', T = 'T', U = 'U', V = 'V', W = 'W', X = 'X', Y = 'Y', Z = 'Z', // 0x5A Home = 0x60, Left = 0x61, Up = 0x62, Right = 0x63, Down = 0x64, PageUp = 0x65, PageDown = 0x66, End = 0x67, Begin = 0x68, Grave = 0x7e, // keypad NumLock = 0x7f, NumPadSpace = 0x80, NumPadTab = 0x89, NumPadEnter = 0x8d, NumPadF1 = 0x91, NumPadF2 = 0x92, NumPadF3 = 0x93, NumPadF4 = 0x94, NumPadHome = 0x95, NumPadLeft = 0x96, NumPadUp = 0x97, NumPadRight = 0x98, NumPadDown = 0x99, NumPadPageUp = 0x9a, NumPadPageDown = 0x9b, NumPadEnd = 0x9c, NumPadBegin = 0x9d, NumPadInsert = 0x9e, NumPadDelete = 0x9f, NumPadEqual = 0xbd, NumPadMultiply = 0xaa, NumPadAdd = 0xab, NumPadSeparator = 0xac, // comma NumPadSubtract = 0xad, NumPadDecimal = 0xae, NumPadDivide = 0xaf, NumPad0 = 0xb0, NumPad1 = 0xb1, NumPad2 = 0xb2, NumPad3 = 0xb3, NumPad4 = 0xb4, NumPad5 = 0xb5, NumPad6 = 0xb6, NumPad7 = 0xb7, NumPad8 = 0xb8, NumPad9 = 0xb9, F1 = 0xbe, F2 = 0xbf, F3 = 0xc0, F4 = 0xc1, F5 = 0xc2, F6 = 0xc3, F7 = 0xc4, F8 = 0xc5, F9 = 0xc6, F10 = 0xc7, F11 = 0xc8, F12 = 0xc9, ShiftL = 0xe1, ShiftR = 0xe2, ControlL = 0xe3, ControlR = 0xe4, CapsLock = 0xe5, AltL = 0xe9, AltR = 0xea, SuperL = 0xeb, SuperR = 0xec, // virtual keys Shift = 0xed, Control = 0xee, Alt = 0xef }; }; typedef Keys::_ Key; END_INANITY_INPUT #endif
15.006329
63
0.53817
quyse
658cde5dc6c6838030c7eb22831420311cec2135
1,189
cpp
C++
lib/guide/guideuihighlighter.cpp
frank-lesser/gambit
21601d3fd939405523d18e7a9f51eae9780de964
[ "Apache-2.0" ]
41
2015-12-19T12:03:08.000Z
2021-10-05T16:15:51.000Z
lib/guide/guideuihighlighter.cpp
frank-lesser/gambit
21601d3fd939405523d18e7a9f51eae9780de964
[ "Apache-2.0" ]
133
2015-12-21T08:28:00.000Z
2017-11-24T03:48:05.000Z
lib/guide/guideuihighlighter.cpp
udem-dlteam/gambit
776ccd958acc36b86397767c159c6ac526f14319
[ "Apache-2.0" ]
4
2017-10-07T01:22:11.000Z
2021-01-24T10:21:54.000Z
/* File: "guideuihighlighter.cpp", Time-stamp: <2005-04-12 14:25:52 feeley> */ /* Copyright (C) 1994-2005 by Marc Feeley, All Rights Reserved. */ /*---------------------------------------------------------------------------*/ #include "guideuihighlighter.h" #include <qtextedit.h> /*---------------------------------------------------------------------------*/ GuideUiHighlighter::GuideUiHighlighter (QTextEdit *textEdit) : QSyntaxHighlighter (textEdit) { consoleInfo = 0; } // Set format of current paragraph with the specified color void GuideUiHighlighter::setFormat (int start, int length, int colorNb) { GuideUiElementFormat *ef = codeFormat->getElement(colorNb); QSyntaxHighlighter::setFormat(start, length, ef->getFont(textEdit()->font()), ef->getColor()); } // Return the related code format GuideUiCodeFormat* GuideUiHighlighter::getCodeFormat () { return codeFormat; } // Links the console infos at this highlighter void GuideUiHighlighter::setConsoleInfo (GuideUiConsoleInfo *consoleInfo) { this->consoleInfo = consoleInfo; } /*---------------------------------------------------------------------------*/ /* Local Variables: */ /* mode: C++ */ /* End: */
28.309524
96
0.587889
frank-lesser
658fd31652866d6240c66c059ba8abd29b8cb38b
1,327
cpp
C++
source/min-lib/test/dcblocker/dcblocker_test.cpp
wwerk/wkw
a17bb2184a20a67d942b87d346f3200fc0c138af
[ "MIT" ]
2
2015-08-31T19:44:15.000Z
2018-01-30T04:05:33.000Z
source/min-lib/test/dcblocker/dcblocker_test.cpp
electrotap/Teabox
fc1b466ec9fe4eb343982df8e8de37c86675cbec
[ "MIT" ]
null
null
null
source/min-lib/test/dcblocker/dcblocker_test.cpp
electrotap/Teabox
fc1b466ec9fe4eb343982df8e8de37c86675cbec
[ "MIT" ]
null
null
null
/// @file /// @brief Unit test for the dcblocker class /// @ingroup minlib /// @copyright Copyright 2018 The Min-Lib Authors. All rights reserved. /// @license Use of this source code is governed by the MIT License found in the License.md file. #define CATCH_CONFIG_MAIN #include "c74_min_catch.h" SCENARIO ("produce the correct impulse response") { GIVEN ("An instance of the dcblocker class") { c74::min::lib::dcblocker f; WHEN ("processing a 64-sample impulse") { // create an impulse buffer to process const int buffersize = 64; c74::min::sample_vector impulse(buffersize); std::fill_n(impulse.begin(), buffersize, 0.0); impulse[0] = 1.0; // output from our object's processing c74::min::sample_vector output; // run the calculations for (auto x : impulse) { auto y = f(x); output.push_back(y); } // get a reference impulse response to compare against auto reference = c74::min::lib::filters::generate_impulse_response({1.0,-1.0}, {1.0,-0.9997}, buffersize); THEN("The result produced matches an externally produced reference impulse") REQUIRE( output == reference ); } } }
31.595238
118
0.596081
wwerk
65941343b6fee25d2e7ceaa636c4e3377a50795b
3,291
cpp
C++
common/hAStar.cpp
huangjund/path_planner
79892899ffa39a6368ae8b70ff4742b6d618ae14
[ "BSD-3-Clause" ]
null
null
null
common/hAStar.cpp
huangjund/path_planner
79892899ffa39a6368ae8b70ff4742b6d618ae14
[ "BSD-3-Clause" ]
null
null
null
common/hAStar.cpp
huangjund/path_planner
79892899ffa39a6368ae8b70ff4742b6d618ae14
[ "BSD-3-Clause" ]
null
null
null
#include "hAStar.h" namespace HybridAStar { namespace Common { struct CompareNodes { bool operator()(const std::shared_ptr<GridState> lhs, const std::shared_ptr<GridState> rhs) const { return lhs->getC() > rhs->getC(); } }; hAStar::hAStar(const std::shared_ptr<GridState>& start, const GridState& goal,std::shared_ptr<CollisionDetection>& config): start_(start), goal_(goal), config_(config), pMap_(std::unique_ptr<Map<GridState>>()){} void hAStar::setGoal(const GridState& goal){ goal_ = goal; } void hAStar::setStart(const std::shared_ptr<GridState>& start) { start_ = start; } void hAStar::setStartGoal(const std::shared_ptr<GridState>& start, const GridState& goal) { start_ = start; goal_ = goal; } double hAStar::getDistance() { int iPred, iSucc; float newG; const int pwidth = pMap_->info_.width*pMap_->info_.resolution/pMap_->info_.planResolution; const int pheight = pMap_->info_.height*pMap_->info_.resolution/pMap_->info_.planResolution; int dir = 8; std::vector<std::shared_ptr<GridState>> statespace(pwidth*pheight); using binomial_heap = boost::heap::binomial_heap<std::shared_ptr<GridState>, boost::heap::compare<CompareNodes>>; binomial_heap O; std::vector<binomial_heap::handle_type> handler(pwidth*pheight); start_->updateH(goal_); start_->open(); O.push(start_); iPred = start_->setIdx(pwidth); statespace[iPred] = start_; std::shared_ptr<GridState> nPred; std::shared_ptr<GridState> nSucc; while(!O.empty()) { nPred = O.top(); iPred = nPred->setIdx(pwidth); if(statespace[iPred]->isClosed()) { O.pop(); continue; } else if(statespace[iPred]->isOpen()) { statespace[iPred]->close(); O.pop(); if(*nPred == goal_) { return nPred->getG(); } else { for (int i = 0; i<dir; ++i) { nSucc.reset(nPred->createSuccessor(i,nPred)); iSucc = nSucc->setIdx(pwidth); if (nSucc->isOnGrid(pwidth,pheight) && config_->isTraversable(nSucc.get()) && (statespace[iSucc] == NULL || !statespace[iSucc]->isClosed())) { nSucc->updateG(); newG = nSucc->getG(); // if this point has not explored yet or g is greater if (statespace[iSucc] == NULL || !statespace[iSucc]->isOpen()) { nSucc->updateH(goal_); nSucc->open(); statespace[iSucc] = nSucc; handler[iSucc] = O.push(nSucc); } else if(newG < statespace[iSucc]->getG()) { statespace[iSucc]->setG(newG); statespace[iSucc]->setPred(nSucc->getPred()); O.update(handler[iSucc]); } } } } } } std::cerr << "ERROR: no A* path found" << std::endl; return std::numeric_limits<double>::min(); } void hAStar::setRawmap(const nav_msgs::OccupancyGrid::Ptr& map) { pMap_->setMap(map); } void hAStar::setSS() { pMap_->setSS(); } std::unique_ptr<Map<GridState>>& hAStar::returnMap() { return pMap_; } } // namespace Common } // namespace HybridAstar
28.37069
125
0.583409
huangjund
6595b9db5252ea435ae581b966550d0605b31f77
627
hpp
C++
src/Core/GameObjects/BattleFwd.hpp
heroesiiifan/FreeHeroes
d9b396b527918cdf863fd2310bcf261e213bf553
[ "MIT" ]
17
2020-08-13T03:23:27.000Z
2022-02-04T00:17:53.000Z
src/Core/GameObjects/BattleFwd.hpp
heroesiiifan/FreeHeroes
d9b396b527918cdf863fd2310bcf261e213bf553
[ "MIT" ]
2
2021-09-05T21:00:31.000Z
2021-09-12T07:46:53.000Z
src/Core/GameObjects/BattleFwd.hpp
heroesiiifan/FreeHeroes
d9b396b527918cdf863fd2310bcf261e213bf553
[ "MIT" ]
2
2021-09-08T10:37:34.000Z
2021-09-09T00:35:44.000Z
/* * Copyright (C) 2020 Smirnov Vladimir / mapron1@gmail.com * SPDX-License-Identifier: MIT * See LICENSE file for details. */ #pragma once namespace FreeHeroes::Core { struct BattleStack; using BattleStackConstPtr = const BattleStack*; using BattleStackMutablePtr = BattleStack*; struct BattleHero; using BattleHeroMutablePtr = BattleHero*; using BattleHeroConstPtr = const BattleHero*; struct BattleArmy; using BattleArmyConstPtr = const BattleArmy*; using BattleArmyMutablePtr = BattleArmy*; struct BattleSquad; using BattleSquadConstPtr = const BattleSquad*; using BattleSquadMutablePtr = BattleSquad*; }
23.222222
58
0.783094
heroesiiifan
659870e52c3593b88e8b2188fcf8c5c1e7753ecb
1,052
cpp
C++
codes/vj/F.cpp
hiperwe/Grade1
e987d37cbae73d8ad1cb60007fc1497b08c4fa01
[ "MIT" ]
1
2019-07-21T16:41:22.000Z
2019-07-21T16:41:22.000Z
codes/vj/F.cpp
hiperwe/Grade1
e987d37cbae73d8ad1cb60007fc1497b08c4fa01
[ "MIT" ]
null
null
null
codes/vj/F.cpp
hiperwe/Grade1
e987d37cbae73d8ad1cb60007fc1497b08c4fa01
[ "MIT" ]
null
null
null
#include <stdio.h> #include <string.h> int n,q,l,r; int a[5050],ans[5050][5050]; int max(int a,int b){ return a > b?a:b; } int main(){ int end, tmp; scanf("%d",&n); memset(ans,0,sizeof(ans)); for(int i = 1;i <= n;i++){ scanf("%d",&a[i]); ans[i][i] = a[i]; // printf("ans[%d][%d] = %d\n",i,i,ans[i][i]); } for(int i = 1;i < n;i++){ for(int di = 1;di + i <= n;di++){ ans[di][i + di] = ans[di + 1][di + i] ^ ans[di][di + i - 1]; } } // for(int i = 1;i <= n;i++){ // for(int j = 1;j <= n;j++){ // printf("ans[%d][%d] = %d\n",i,j,ans[i][j]); // } // } for(int i = 1;i <= n;i++){ for(int di = 1;di + i <= n;di++){ end = di + i; // printf("ans[%d][%d] = %d,ans[%d][%d] = %d,ans[%d][%d] = %d\n",i-1,end,ans[i-1][end],i,end,ans[i][end],i,end,ans[i][end+1]); tmp = max(ans[di][end-1],ans[di+1][end]); ans[di][end] = max(ans[di][end],tmp); // printf("ans[%d][%d] = %d\n",di,end,ans[di][end]); } } scanf("%d",&q); for(int i = 1;i <= q;i++){ scanf("%d %d",&l,&r); printf("%d\n",ans[l][r]); } return 0; }
21.469388
128
0.447719
hiperwe
659e7b4211d898c7f15bb97afe2d52e7e0291443
607
hpp
C++
include/member_thunk/error/win32_error.hpp
sylveon/member_thunk
1ac81a983e951678638be7785de2cce2d9f73151
[ "MIT" ]
9
2019-12-02T11:59:24.000Z
2022-02-28T06:34:59.000Z
include/member_thunk/error/win32_error.hpp
sylveon/member_thunk
1ac81a983e951678638be7785de2cce2d9f73151
[ "MIT" ]
29
2019-11-26T17:12:33.000Z
2020-10-06T04:58:53.000Z
include/member_thunk/error/win32_error.hpp
sylveon/member_thunk
1ac81a983e951678638be7785de2cce2d9f73151
[ "MIT" ]
null
null
null
#pragma once #include <errhandlingapi.h> #include <minwindef.h> #include <string_view> #include "./exception.hpp" namespace member_thunk { class win32_error final : public exception { std::string_view api; DWORD error; public: constexpr win32_error(std::string_view api, DWORD error) noexcept : exception("A Windows API call failed."), api(api), error(error) { } win32_error(std::string_view api) noexcept : win32_error(api, GetLastError()) { } constexpr std::string_view failing_api() const noexcept { return api; } constexpr DWORD error_code() const noexcept { return error; } }; }
24.28
133
0.729819
sylveon
4f1ebc9675ce2121777d0bfcb2f0862af2115297
18,743
cpp
C++
include/hlsdk-2.3-p4/singleplayer/dlls/leech.cpp
siger-yeung/demobot
01cf4a4c18fe507ac854e7205ef03dac84003eb3
[ "MIT" ]
null
null
null
include/hlsdk-2.3-p4/singleplayer/dlls/leech.cpp
siger-yeung/demobot
01cf4a4c18fe507ac854e7205ef03dac84003eb3
[ "MIT" ]
null
null
null
include/hlsdk-2.3-p4/singleplayer/dlls/leech.cpp
siger-yeung/demobot
01cf4a4c18fe507ac854e7205ef03dac84003eb3
[ "MIT" ]
null
null
null
/*** * * Copyright (c) 1996-2002, Valve LLC. All rights reserved. * * This product contains software technology licensed from Id * Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. * All Rights Reserved. * * This source code contains proprietary and confidential information of * Valve LLC and its suppliers. Access to this code is restricted to * persons who have executed a written SDK license with Valve. Any access, * use or distribution of this code by or to any unlicensed person is illegal. * ****/ //========================================================= // leech - basic little swimming monster //========================================================= // // UNDONE: // DONE:Steering force model for attack // DONE:Attack animation control / damage // DONE:Establish range of up/down motion and steer around vertical obstacles // DONE:Re-evaluate height periodically // DONE:Fall (MOVETYPE_TOSS) and play different anim if out of water // Test in complex room (c2a3?) // DONE:Sounds? - Kelly will fix // Blood cloud? Hurt effect? // Group behavior? // DONE:Save/restore // Flop animation - just bind to ACT_TWITCH // Fix fatal push into wall case // // Try this on a bird // Try this on a model with hulls/tracehull? // #include "float.h" #include "extdll.h" #include "util.h" #include "cbase.h" #include "monsters.h" // Animation events #define LEECH_AE_ATTACK 1 #define LEECH_AE_FLOP 2 // Movement constants #define LEECH_ACCELERATE 10 #define LEECH_CHECK_DIST 45 #define LEECH_SWIM_SPEED 50 #define LEECH_SWIM_ACCEL 80 #define LEECH_SWIM_DECEL 10 #define LEECH_TURN_RATE 90 #define LEECH_SIZEX 10 #define LEECH_FRAMETIME 0.1 #define DEBUG_BEAMS 0 #if DEBUG_BEAMS #include "effects.h" #endif class CLeech : public CBaseMonster { public: void Spawn( void ); void Precache( void ); void EXPORT SwimThink( void ); void EXPORT DeadThink( void ); void Touch( CBaseEntity *pOther ) { if ( pOther->IsPlayer() ) { // If the client is pushing me, give me some base velocity if ( gpGlobals->trace_ent && gpGlobals->trace_ent == edict() ) { pev->basevelocity = pOther->pev->velocity; pev->flags |= FL_BASEVELOCITY; } } } void SetObjectCollisionBox( void ) { pev->absmin = pev->origin + Vector(-8,-8,0); pev->absmax = pev->origin + Vector(8,8,2); } void AttackSound( void ); void AlertSound( void ); void UpdateMotion( void ); float ObstacleDistance( CBaseEntity *pTarget ); void MakeVectors( void ); void RecalculateWaterlevel( void ); void SwitchLeechState( void ); // Base entity functions void HandleAnimEvent( MonsterEvent_t *pEvent ); int BloodColor( void ) { return DONT_BLEED; } void Killed( entvars_t *pevAttacker, int iGib ); void Activate( void ); int TakeDamage( entvars_t *pevInflictor, entvars_t *pevAttacker, float flDamage, int bitsDamageType ); int Classify( void ) { return CLASS_INSECT; } int IRelationship( CBaseEntity *pTarget ); virtual int Save( CSave &save ); virtual int Restore( CRestore &restore ); static TYPEDESCRIPTION m_SaveData[]; static const char *pAttackSounds[]; static const char *pAlertSounds[]; private: // UNDONE: Remove unused boid vars, do group behavior float m_flTurning;// is this boid turning? BOOL m_fPathBlocked;// TRUE if there is an obstacle ahead float m_flAccelerate; float m_obstacle; float m_top; float m_bottom; float m_height; float m_waterTime; float m_sideTime; // Timer to randomly check clearance on sides float m_zTime; float m_stateTime; float m_attackSoundTime; #if DEBUG_BEAMS CBeam *m_pb; CBeam *m_pt; #endif }; LINK_ENTITY_TO_CLASS( monster_leech, CLeech ); TYPEDESCRIPTION CLeech::m_SaveData[] = { DEFINE_FIELD( CLeech, m_flTurning, FIELD_FLOAT ), DEFINE_FIELD( CLeech, m_fPathBlocked, FIELD_BOOLEAN ), DEFINE_FIELD( CLeech, m_flAccelerate, FIELD_FLOAT ), DEFINE_FIELD( CLeech, m_obstacle, FIELD_FLOAT ), DEFINE_FIELD( CLeech, m_top, FIELD_FLOAT ), DEFINE_FIELD( CLeech, m_bottom, FIELD_FLOAT ), DEFINE_FIELD( CLeech, m_height, FIELD_FLOAT ), DEFINE_FIELD( CLeech, m_waterTime, FIELD_TIME ), DEFINE_FIELD( CLeech, m_sideTime, FIELD_TIME ), DEFINE_FIELD( CLeech, m_zTime, FIELD_TIME ), DEFINE_FIELD( CLeech, m_stateTime, FIELD_TIME ), DEFINE_FIELD( CLeech, m_attackSoundTime, FIELD_TIME ), }; IMPLEMENT_SAVERESTORE( CLeech, CBaseMonster ); const char *CLeech::pAttackSounds[] = { "leech/leech_bite1.wav", "leech/leech_bite2.wav", "leech/leech_bite3.wav", }; const char *CLeech::pAlertSounds[] = { "leech/leech_alert1.wav", "leech/leech_alert2.wav", }; void CLeech::Spawn( void ) { Precache(); SET_MODEL(ENT(pev), "models/leech.mdl"); // Just for fun // SET_MODEL(ENT(pev), "models/icky.mdl"); // UTIL_SetSize( pev, g_vecZero, g_vecZero ); UTIL_SetSize( pev, Vector(-1,-1,0), Vector(1,1,2)); // Don't push the minz down too much or the water check will fail because this entity is really point-sized pev->solid = SOLID_SLIDEBOX; pev->movetype = MOVETYPE_FLY; SetBits(pev->flags, FL_SWIM); pev->health = gSkillData.leechHealth; m_flFieldOfView = -0.5; // 180 degree FOV m_flDistLook = 750; MonsterInit(); SetThink( SwimThink ); SetUse( NULL ); SetTouch( NULL ); pev->view_ofs = g_vecZero; m_flTurning = 0; m_fPathBlocked = FALSE; SetActivity( ACT_SWIM ); SetState( MONSTERSTATE_IDLE ); m_stateTime = gpGlobals->time + RANDOM_FLOAT( 1, 5 ); } void CLeech::Activate( void ) { RecalculateWaterlevel(); } void CLeech::RecalculateWaterlevel( void ) { // Calculate boundaries Vector vecTest = pev->origin - Vector(0,0,400); TraceResult tr; UTIL_TraceLine(pev->origin, vecTest, missile, edict(), &tr); if ( tr.flFraction != 1.0 ) m_bottom = tr.vecEndPos.z + 1; else m_bottom = vecTest.z; m_top = UTIL_WaterLevel( pev->origin, pev->origin.z, pev->origin.z + 400 ) - 1; // Chop off 20% of the outside range float newBottom = m_bottom * 0.8 + m_top * 0.2; m_top = m_bottom * 0.2 + m_top * 0.8; m_bottom = newBottom; m_height = RANDOM_FLOAT( m_bottom, m_top ); m_waterTime = gpGlobals->time + RANDOM_FLOAT( 5, 7 ); } void CLeech::SwitchLeechState( void ) { m_stateTime = gpGlobals->time + RANDOM_FLOAT( 3, 6 ); if ( m_MonsterState == MONSTERSTATE_COMBAT ) { m_hEnemy = NULL; SetState( MONSTERSTATE_IDLE ); // We may be up against the player, so redo the side checks m_sideTime = 0; } else { Look( m_flDistLook ); CBaseEntity *pEnemy = BestVisibleEnemy(); if ( pEnemy && pEnemy->pev->waterlevel != 0 ) { m_hEnemy = pEnemy; SetState( MONSTERSTATE_COMBAT ); m_stateTime = gpGlobals->time + RANDOM_FLOAT( 18, 25 ); AlertSound(); } } } int CLeech::IRelationship( CBaseEntity *pTarget ) { if ( pTarget->IsPlayer() ) return R_DL; return CBaseMonster::IRelationship( pTarget ); } void CLeech::AttackSound( void ) { if ( gpGlobals->time > m_attackSoundTime ) { EMIT_SOUND_DYN ( ENT(pev), CHAN_VOICE, pAttackSounds[ RANDOM_LONG(0,ARRAYSIZE(pAttackSounds)-1) ], 1.0, ATTN_NORM, 0, PITCH_NORM ); m_attackSoundTime = gpGlobals->time + 0.5; } } void CLeech::AlertSound( void ) { EMIT_SOUND_DYN ( ENT(pev), CHAN_VOICE, pAlertSounds[ RANDOM_LONG(0,ARRAYSIZE(pAlertSounds)-1) ], 1.0, ATTN_NORM * 0.5, 0, PITCH_NORM ); } void CLeech::Precache( void ) { int i; //PRECACHE_MODEL("models/icky.mdl"); PRECACHE_MODEL("models/leech.mdl"); for ( i = 0; i < ARRAYSIZE( pAttackSounds ); i++ ) PRECACHE_SOUND((char *)pAttackSounds[i]); for ( i = 0; i < ARRAYSIZE( pAlertSounds ); i++ ) PRECACHE_SOUND((char *)pAlertSounds[i]); } int CLeech::TakeDamage( entvars_t *pevInflictor, entvars_t *pevAttacker, float flDamage, int bitsDamageType ) { pev->velocity = g_vecZero; // Nudge the leech away from the damage if ( pevInflictor ) { pev->velocity = (pev->origin - pevInflictor->origin).Normalize() * 25; } return CBaseMonster::TakeDamage( pevInflictor, pevAttacker, flDamage, bitsDamageType ); } void CLeech::HandleAnimEvent( MonsterEvent_t *pEvent ) { switch( pEvent->event ) { case LEECH_AE_ATTACK: AttackSound(); CBaseEntity *pEnemy; pEnemy = m_hEnemy; if ( pEnemy != NULL ) { Vector dir, face; UTIL_MakeVectorsPrivate( pev->angles, face, NULL, NULL ); face.z = 0; dir = (pEnemy->pev->origin - pev->origin); dir.z = 0; dir = dir.Normalize(); face = face.Normalize(); if ( DotProduct(dir, face) > 0.9 ) // Only take damage if the leech is facing the prey pEnemy->TakeDamage( pev, pev, gSkillData.leechDmgBite, DMG_SLASH ); } m_stateTime -= 2; break; case LEECH_AE_FLOP: // Play flop sound break; default: CBaseMonster::HandleAnimEvent( pEvent ); break; } } void CLeech::MakeVectors( void ) { Vector tmp = pev->angles; tmp.x = -tmp.x; UTIL_MakeVectors ( tmp ); } // // ObstacleDistance - returns normalized distance to obstacle // float CLeech::ObstacleDistance( CBaseEntity *pTarget ) { TraceResult tr; Vector vecTest; // use VELOCITY, not angles, not all boids point the direction they are flying //Vector vecDir = UTIL_VecToAngles( pev->velocity ); MakeVectors(); // check for obstacle ahead vecTest = pev->origin + gpGlobals->v_forward * LEECH_CHECK_DIST; UTIL_TraceLine(pev->origin, vecTest, missile, edict(), &tr); if ( tr.fStartSolid ) { pev->speed = -LEECH_SWIM_SPEED * 0.5; // ALERT( at_console, "Stuck from (%f %f %f) to (%f %f %f)\n", pev->oldorigin.x, pev->oldorigin.y, pev->oldorigin.z, pev->origin.x, pev->origin.y, pev->origin.z ); // UTIL_SetOrigin( pev, pev->oldorigin ); } if ( tr.flFraction != 1.0 ) { if ( (pTarget == NULL || tr.pHit != pTarget->edict()) ) { return tr.flFraction; } else { if ( fabs(m_height - pev->origin.z) > 10 ) return tr.flFraction; } } if ( m_sideTime < gpGlobals->time ) { // extra wide checks vecTest = pev->origin + gpGlobals->v_right * LEECH_SIZEX * 2 + gpGlobals->v_forward * LEECH_CHECK_DIST; UTIL_TraceLine(pev->origin, vecTest, missile, edict(), &tr); if (tr.flFraction != 1.0) return tr.flFraction; vecTest = pev->origin - gpGlobals->v_right * LEECH_SIZEX * 2 + gpGlobals->v_forward * LEECH_CHECK_DIST; UTIL_TraceLine(pev->origin, vecTest, missile, edict(), &tr); if (tr.flFraction != 1.0) return tr.flFraction; // Didn't hit either side, so stop testing for another 0.5 - 1 seconds m_sideTime = gpGlobals->time + RANDOM_FLOAT(0.5,1); } return 1.0; } void CLeech::DeadThink( void ) { if ( m_fSequenceFinished ) { if ( m_Activity == ACT_DIEFORWARD ) { SetThink( NULL ); StopAnimation(); return; } else if ( pev->flags & FL_ONGROUND ) { pev->solid = SOLID_NOT; SetActivity(ACT_DIEFORWARD); } } StudioFrameAdvance(); pev->nextthink = gpGlobals->time + 0.1; // Apply damage velocity, but keep out of the walls if ( pev->velocity.x != 0 || pev->velocity.y != 0 ) { TraceResult tr; // Look 0.5 seconds ahead UTIL_TraceLine(pev->origin, pev->origin + pev->velocity * 0.5, missile, edict(), &tr); if (tr.flFraction != 1.0) { pev->velocity.x = 0; pev->velocity.y = 0; } } } void CLeech::UpdateMotion( void ) { float flapspeed = (pev->speed - m_flAccelerate) / LEECH_ACCELERATE; m_flAccelerate = m_flAccelerate * 0.8 + pev->speed * 0.2; if (flapspeed < 0) flapspeed = -flapspeed; flapspeed += 1.0; if (flapspeed < 0.5) flapspeed = 0.5; if (flapspeed > 1.9) flapspeed = 1.9; pev->framerate = flapspeed; if ( !m_fPathBlocked ) pev->avelocity.y = pev->ideal_yaw; else pev->avelocity.y = pev->ideal_yaw * m_obstacle; if ( pev->avelocity.y > 150 ) m_IdealActivity = ACT_TURN_LEFT; else if ( pev->avelocity.y < -150 ) m_IdealActivity = ACT_TURN_RIGHT; else m_IdealActivity = ACT_SWIM; // lean float targetPitch, delta; delta = m_height - pev->origin.z; if ( delta < -10 ) targetPitch = -30; else if ( delta > 10 ) targetPitch = 30; else targetPitch = 0; pev->angles.x = UTIL_Approach( targetPitch, pev->angles.x, 60 * LEECH_FRAMETIME ); // bank pev->avelocity.z = - (pev->angles.z + (pev->avelocity.y * 0.25)); if ( m_MonsterState == MONSTERSTATE_COMBAT && HasConditions( bits_COND_CAN_MELEE_ATTACK1 ) ) m_IdealActivity = ACT_MELEE_ATTACK1; // Out of water check if ( !pev->waterlevel ) { pev->movetype = MOVETYPE_TOSS; m_IdealActivity = ACT_TWITCH; pev->velocity = g_vecZero; // Animation will intersect the floor if either of these is non-zero pev->angles.z = 0; pev->angles.x = 0; if ( pev->framerate < 1.0 ) pev->framerate = 1.0; } else if ( pev->movetype == MOVETYPE_TOSS ) { pev->movetype = MOVETYPE_FLY; pev->flags &= ~FL_ONGROUND; RecalculateWaterlevel(); m_waterTime = gpGlobals->time + 2; // Recalc again soon, water may be rising } if ( m_Activity != m_IdealActivity ) { SetActivity ( m_IdealActivity ); } float flInterval = StudioFrameAdvance(); DispatchAnimEvents ( flInterval ); #if DEBUG_BEAMS if ( !m_pb ) m_pb = CBeam::BeamCreate( "sprites/laserbeam.spr", 5 ); if ( !m_pt ) m_pt = CBeam::BeamCreate( "sprites/laserbeam.spr", 5 ); m_pb->PointsInit( pev->origin, pev->origin + gpGlobals->v_forward * LEECH_CHECK_DIST ); m_pt->PointsInit( pev->origin, pev->origin - gpGlobals->v_right * (pev->avelocity.y*0.25) ); if ( m_fPathBlocked ) { float color = m_obstacle * 30; if ( m_obstacle == 1.0 ) color = 0; if ( color > 255 ) color = 255; m_pb->SetColor( 255, (int)color, (int)color ); } else m_pb->SetColor( 255, 255, 0 ); m_pt->SetColor( 0, 0, 255 ); #endif } void CLeech::SwimThink( void ) { TraceResult tr; float flLeftSide; float flRightSide; float targetSpeed; float targetYaw = 0; CBaseEntity *pTarget; if ( FNullEnt( FIND_CLIENT_IN_PVS( edict() ) ) ) { pev->nextthink = gpGlobals->time + RANDOM_FLOAT(1,1.5); pev->velocity = g_vecZero; return; } else pev->nextthink = gpGlobals->time + 0.1; targetSpeed = LEECH_SWIM_SPEED; if ( m_waterTime < gpGlobals->time ) RecalculateWaterlevel(); if ( m_stateTime < gpGlobals->time ) SwitchLeechState(); ClearConditions( bits_COND_CAN_MELEE_ATTACK1 ); switch( m_MonsterState ) { case MONSTERSTATE_COMBAT: pTarget = m_hEnemy; if ( !pTarget ) SwitchLeechState(); else { // Chase the enemy's eyes m_height = pTarget->pev->origin.z + pTarget->pev->view_ofs.z - 5; // Clip to viable water area if ( m_height < m_bottom ) m_height = m_bottom; else if ( m_height > m_top ) m_height = m_top; Vector location = pTarget->pev->origin - pev->origin; location.z += (pTarget->pev->view_ofs.z); if ( location.Length() < 40 ) SetConditions( bits_COND_CAN_MELEE_ATTACK1 ); // Turn towards target ent targetYaw = UTIL_VecToYaw( location ); targetYaw = UTIL_AngleDiff( targetYaw, UTIL_AngleMod( pev->angles.y ) ); if ( targetYaw < (-LEECH_TURN_RATE*0.75) ) targetYaw = (-LEECH_TURN_RATE*0.75); else if ( targetYaw > (LEECH_TURN_RATE*0.75) ) targetYaw = (LEECH_TURN_RATE*0.75); else targetSpeed *= 2; } break; default: if ( m_zTime < gpGlobals->time ) { float newHeight = RANDOM_FLOAT( m_bottom, m_top ); m_height = 0.5 * m_height + 0.5 * newHeight; m_zTime = gpGlobals->time + RANDOM_FLOAT( 1, 4 ); } if ( RANDOM_LONG( 0, 100 ) < 10 ) targetYaw = RANDOM_LONG( -30, 30 ); pTarget = NULL; // oldorigin test if ( (pev->origin - pev->oldorigin).Length() < 1 ) { // If leech didn't move, there must be something blocking it, so try to turn m_sideTime = 0; } break; } m_obstacle = ObstacleDistance( pTarget ); pev->oldorigin = pev->origin; if ( m_obstacle < 0.1 ) m_obstacle = 0.1; // is the way ahead clear? if ( m_obstacle == 1.0 ) { // if the leech is turning, stop the trend. if ( m_flTurning != 0 ) { m_flTurning = 0; } m_fPathBlocked = FALSE; pev->speed = UTIL_Approach( targetSpeed, pev->speed, LEECH_SWIM_ACCEL * LEECH_FRAMETIME ); pev->velocity = gpGlobals->v_forward * pev->speed; } else { m_obstacle = 1.0 / m_obstacle; // IF we get this far in the function, the leader's path is blocked! m_fPathBlocked = TRUE; if ( m_flTurning == 0 )// something in the way and leech is not already turning to avoid { Vector vecTest; // measure clearance on left and right to pick the best dir to turn vecTest = pev->origin + (gpGlobals->v_right * LEECH_SIZEX) + (gpGlobals->v_forward * LEECH_CHECK_DIST); UTIL_TraceLine(pev->origin, vecTest, missile, edict(), &tr); flRightSide = tr.flFraction; vecTest = pev->origin + (gpGlobals->v_right * -LEECH_SIZEX) + (gpGlobals->v_forward * LEECH_CHECK_DIST); UTIL_TraceLine(pev->origin, vecTest, missile, edict(), &tr); flLeftSide = tr.flFraction; // turn left, right or random depending on clearance ratio float delta = (flRightSide - flLeftSide); if ( delta > 0.1 || (delta > -0.1 && RANDOM_LONG(0,100)<50) ) m_flTurning = -LEECH_TURN_RATE; else m_flTurning = LEECH_TURN_RATE; } pev->speed = UTIL_Approach( -(LEECH_SWIM_SPEED*0.5), pev->speed, LEECH_SWIM_DECEL * LEECH_FRAMETIME * m_obstacle ); pev->velocity = gpGlobals->v_forward * pev->speed; } pev->ideal_yaw = m_flTurning + targetYaw; UpdateMotion(); } void CLeech::Killed(entvars_t *pevAttacker, int iGib) { Vector vecSplatDir; TraceResult tr; //ALERT(at_aiconsole, "Leech: killed\n"); // tell owner ( if any ) that we're dead.This is mostly for MonsterMaker functionality. CBaseEntity *pOwner = CBaseEntity::Instance(pev->owner); if (pOwner) pOwner->DeathNotice(pev); // When we hit the ground, play the "death_end" activity if ( pev->waterlevel ) { pev->angles.z = 0; pev->angles.x = 0; pev->origin.z += 1; pev->avelocity = g_vecZero; if ( RANDOM_LONG( 0, 99 ) < 70 ) pev->avelocity.y = RANDOM_LONG( -720, 720 ); pev->gravity = 0.02; ClearBits(pev->flags, FL_ONGROUND); SetActivity( ACT_DIESIMPLE ); } else SetActivity( ACT_DIEFORWARD ); pev->movetype = MOVETYPE_TOSS; pev->takedamage = DAMAGE_NO; SetThink( DeadThink ); }
25.888122
165
0.652297
siger-yeung
4f1f80963f4cc6473e9d8a1bdac991dc8d4a3dba
925
cpp
C++
codeforces/1619A.cpp
mhilmyh/algo-data-struct
6a9b1e5220e3c4e4a41200a09cb27f3f55560693
[ "MIT" ]
null
null
null
codeforces/1619A.cpp
mhilmyh/algo-data-struct
6a9b1e5220e3c4e4a41200a09cb27f3f55560693
[ "MIT" ]
null
null
null
codeforces/1619A.cpp
mhilmyh/algo-data-struct
6a9b1e5220e3c4e4a41200a09cb27f3f55560693
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; bool DebugMode = false; typedef unsigned long long int ulli; typedef long long int lli; typedef unsigned long int uli; typedef long int li; typedef unsigned short int usi; typedef short int si; void printYesOrNo(bool v) { if (v) printf("YES\n"); else printf("NO\n"); } void printDebug(const char* cs, int x) { if (DebugMode) printf("[%s]: %d\n", cs, x); } void initMain(int argc, char** argv) { if (argc > 1 && strcmp(argv[1], "debug") == 0) { DebugMode = true; } } void solve() { string s; cin >> s; if (s.length() % 2) { printYesOrNo(false); } else { bool valid = true; size_t n = s.length()/2; for (size_t i = 0; valid && i < n; i++) { valid = s[i] == s[i+n]; } printYesOrNo(valid); } } int main(int argc, char** argv) { initMain(argc, argv); int t; cin >> t; while(t--) { solve(); } return 0; }
17.12963
50
0.581622
mhilmyh
4f1fcf853e921ab29c189488ba51303b719dccc4
3,854
cpp
C++
SQLC/CircularQueue.cpp
Zafershah24/Data-Structures-and-Algorithms
9aad10d4f969e2c0cd74795f3ba373ccd6c81c50
[ "Apache-2.0" ]
null
null
null
SQLC/CircularQueue.cpp
Zafershah24/Data-Structures-and-Algorithms
9aad10d4f969e2c0cd74795f3ba373ccd6c81c50
[ "Apache-2.0" ]
null
null
null
SQLC/CircularQueue.cpp
Zafershah24/Data-Structures-and-Algorithms
9aad10d4f969e2c0cd74795f3ba373ccd6c81c50
[ "Apache-2.0" ]
null
null
null
#include<iostream> #include <cstdlib> // Change rear ++ to (rear=rear+1)%sizeofarray (in EnQueue Operation) // Change frnt ++ to (frnt=frntr+1)%sizeofarray (in DeQueue Operation) //And in IsFull Method (rear+1)%sizeofarray==frnt // Count Method changes a bit using namespace std; class CircularQueue { int a[4]; int frnt; int rear; int itemCnt; public: CircularQueue() { frnt=-1; rear=-1; itemCnt=0 for(int i=0;i<4;i++) { a[i]=0; } } bool IsEmp(){ if (frnt==-1&&rear==-1) return true; else return false; } bool IsFull(){ if ((rear+1)%4==frnt) return true; else return false; } void enqueue(int val){ if (IsFull()){ cout<<"queue is Full"<<endl; return; } else if (IsEmp()){ rear=frnt=0; a[rear]=val; itemCnt++; } else{ rear=(rear+1)%4; a[rear]=val; itemCnt++; } } int dequeue(){ int popV=0; if (IsEmp()){ cout<<"Queue is empty"<<endl; return 0; } else if (rear == frnt) { popV = a[frnt]; rear = -1; frnt = -1; itemCnt--; return popV; } else { popV=a[frnt]; a[frnt]=0; frnt=(frnt+1)%4; itemCnt--; // cout<<frnt<<endl; return popV; } } int count(){ return (itemCnt); } void display(){ for( int i=0;i<4;i++) cout<<a[i]<<endl; } int see(int pos) { if (IsEmp()) { cout << "Queue empty" << endl; return 0; } else { return a[pos]; } }; void change(int pos, int val) { a[pos] = val; cout << "value changed at location " << pos << endl; } }; int main() { CircularQueue s1; int option, postion, value; do { cout << "What operation do you want to perform? Select Option number. Enter 0 to exit." << endl; cout << "1. Enqueue()" << endl; cout << "2. Dequeue()" << endl; cout << "3. isEmpty()" << endl; cout << "4. isFull()" << endl; cout << "5. see()" << endl; cout << "6. count()" << endl; cout << "7. change()" << endl; cout << "8. display()" << endl; cout << "9. Clear Screen" << endl << endl; cin >> option; switch (option) { case 0: break; case 1: cout << "Enter an item to push in the queue" << endl; cin >> value; s1.enqueue(value); break; case 2: cout << "Dequeue Function Called - Popped Value: " << s1.dequeue() << endl; break; case 3: if (s1.IsEmp()) cout << "Queue is Empty" << endl; else cout << "Queue is not Empty" << endl; break; case 4: if (s1.IsFull()) cout << "Queue is Full" << endl; else cout << "Queue is not Full" << endl; break; case 5: cout << "Enter position of item you want to peek: " << endl; cin >> postion; cout << "See Function Called - Value at position " << postion << " is " << s1.see(postion) << endl; break; case 6: cout << "Count Function Called - Number of Items in the Queue are: " << s1.count() << endl; break; case 7: cout << "Change Function Called - " << endl; cout << "Enter position of item you want to change : "; cin >> postion; cout << endl; cout << "Enter value of item you want to change : "; cin >> value; s1.change(postion, value); break; case 8: cout << "Display Function Called - " << endl; s1.display(); break; case 9: system("cls"); break; default: cout << "Enter Proper Option number " << endl; } } while (option != 0); return 0; }
21.060109
105
0.483134
Zafershah24
4f224e32ceea45c401e363ed65f7d506a454a115
6,207
hpp
C++
mpfr/mpfr.hpp
hirakuni45/test
04254eab7d2398408aa0015194d4c21011f9bd7a
[ "BSD-3-Clause" ]
null
null
null
mpfr/mpfr.hpp
hirakuni45/test
04254eab7d2398408aa0015194d4c21011f9bd7a
[ "BSD-3-Clause" ]
null
null
null
mpfr/mpfr.hpp
hirakuni45/test
04254eab7d2398408aa0015194d4c21011f9bd7a
[ "BSD-3-Clause" ]
null
null
null
#pragma once //=============================================================================// /*! @file @brief mpfr クラス @n GNU gmp, mpfr の C++ ラッパー @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2020 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=============================================================================// #include <cmath> #include <mpfr.h> namespace mpfr { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief mpfr オブジェクト @param[in] num 有効桁数 */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <uint32_t num> class value { mpfr_t t_; mpfr_rnd_t rnd_; public: //-----------------------------------------------------------------// /*! @brief コンストラクター @param[in] rnd 丸めパラメータ */ //-----------------------------------------------------------------// value(mpfr_rnd_t rnd = MPFR_RNDN) noexcept : t_(), rnd_(rnd) { mpfr_init2(t_, num); } //-----------------------------------------------------------------// /*! @brief コンストラクター @param[in] rnd 丸めパラメータ */ //-----------------------------------------------------------------// value(const value& t, mpfr_rnd_t rnd = MPFR_RNDN) noexcept : rnd_(rnd) { mpfr_init2(t_, num); mpfr_set(t_, t.t_, rnd_); } //-----------------------------------------------------------------// /*! @brief コンストラクター(int) @param[in] iv 初期値 @param[in] rnd 丸めパラメータ */ //-----------------------------------------------------------------// explicit value(int iv, mpfr_rnd_t rnd = MPFR_RNDN) noexcept : rnd_(rnd) { mpfr_init2(t_, num); mpfr_set_si(t_, iv, rnd); } //-----------------------------------------------------------------// /*! @brief コンストラクター(float) @param[in] iv 初期値 @param[in] rnd 丸めパラメータ */ //-----------------------------------------------------------------// explicit value(float iv, mpfr_rnd_t rnd = MPFR_RNDN) noexcept : rnd_(rnd) { mpfr_init2(t_, num); mpfr_set_flt(t_, iv, rnd); } //-----------------------------------------------------------------// /*! @brief コンストラクター(double) @param[in] iv 初期値 @param[in] rnd 丸めパラメータ */ //-----------------------------------------------------------------// explicit value(double iv, mpfr_rnd_t rnd = MPFR_RNDN) noexcept : rnd_(rnd) { mpfr_init2(t_, num); mpfr_set_d(t_, iv, rnd); } //-----------------------------------------------------------------// /*! @brief コンストラクター(文字列) @param[in] iv 初期値 @param[in] rnd 丸めパラメータ */ //-----------------------------------------------------------------// explicit value(const char* iv, mpfr_rnd_t rnd = MPFR_RNDN) noexcept : rnd_(rnd) { mpfr_init2(t_, num); mpfr_set_str(t_, iv, 10, rnd); } //-----------------------------------------------------------------// /*! @brief デストラクター */ //-----------------------------------------------------------------// ~value() { mpfr_clear(t_); } //-----------------------------------------------------------------// /*! @brief mpfr_ptr を取得 @return mpfr_ptr */ //-----------------------------------------------------------------// mpfr_ptr get() noexcept { return t_; } //-----------------------------------------------------------------// /*! @brief mpfr_rnd_t を取得 @return mpfr_rnd_t */ //-----------------------------------------------------------------// auto get_rnd() const noexcept { return rnd_; } //-----------------------------------------------------------------// /*! @brief 円周率を取得 @return 円周率 */ //-----------------------------------------------------------------// static const auto get_pi() { value tmp; mpfr_const_pi(tmp.t_, tmp.get_rnd()); return tmp; } void assign(const char* str) noexcept { mpfr_set_str(t_, str, 10, rnd_); } bool operator == (int v) const noexcept { return mpfr_cmp_si(t_, v) == 0; } bool operator == (long v) const noexcept { return mpfr_cmp_si(t_, v) == 0; } bool operator == (double v) const noexcept { return mpfr_cmp_d(t_, v) == 0; } value& operator = (const value& th) noexcept { mpfr_set(t_, th.t_, rnd_); return *this; } value& operator = (long v) noexcept { mpfr_set_si(t_, v, rnd_); return *this; } value& operator = (double v) noexcept { mpfr_set_d(t_, v, rnd_); return *this; } const value operator - () noexcept { value tmp(*this); mpfr_neg(tmp.t_, tmp.t_, rnd_); return tmp; } value& operator += (const value& th) noexcept { mpfr_add(t_, t_, th.t_, rnd_); return *this; } value& operator -= (const value& th) noexcept { mpfr_sub(t_, t_, th.t_, rnd_); return *this; } value& operator *= (const value& th) noexcept { mpfr_mul(t_, t_, th.t_, rnd_); return *this; } value& operator /= (const value& th) noexcept { mpfr_div(t_, t_, th.t_, rnd_); return *this; } value operator + (const value& th) const noexcept { return value(*this) += th; } value operator - (const value& th) const noexcept { return value(*this) -= th; } value operator * (const value& th) const noexcept { return value(*this) *= th; } value operator / (const value& th) const noexcept { return value(*this) /= th; } void operator() (char* out, uint32_t len) noexcept { mpfr_snprintf(out, len, "%.50RNf", t_); } static value sin(const value& in) { value out; mpfr_sin(out.t_, in.t_, out.get_rnd()); return out; } static value cos(const value& in) { value out; mpfr_cos(out.t_, in.t_, out.get_rnd()); return out; } static value tan(const value& in) { value out; mpfr_tan(out.t_, in.t_, out.get_rnd()); return out; } static value log10(const value& in) { value out; mpfr_log10(out.t_, in.t_, out.get_rnd()); return out; } static value log(const value& in) { value out; mpfr_log(out.t_, in.t_, out.get_rnd()); return out; } static value sqrt(const value& in) { value out; mpfr_sqrt(out.t_, in.t_, out.get_rnd()); return out; } }; }
23.074349
83
0.435476
hirakuni45
4f2510044980ab172e68ba6d5af37704b284317a
5,156
hpp
C++
vendor/entt-3.2.0/src/entt/core/algorithm.hpp
MirrasHue/PopHead
f6bfe51059723bc6567a057028b7a83fabf7a015
[ "MIT" ]
117
2019-03-18T20:09:54.000Z
2022-03-27T22:40:52.000Z
vendor/entt-3.2.0/src/entt/core/algorithm.hpp
MirrasHue/PopHead
f6bfe51059723bc6567a057028b7a83fabf7a015
[ "MIT" ]
443
2019-04-07T19:59:56.000Z
2020-05-23T12:25:28.000Z
vendor/entt-3.2.0/src/entt/core/algorithm.hpp
MirrasHue/PopHead
f6bfe51059723bc6567a057028b7a83fabf7a015
[ "MIT" ]
19
2019-03-20T19:57:34.000Z
2020-11-21T15:35:02.000Z
#ifndef ENTT_CORE_ALGORITHM_HPP #define ENTT_CORE_ALGORITHM_HPP #include <utility> #include <iterator> #include <algorithm> #include <functional> #include "utility.hpp" namespace entt { /** * @brief Function object to wrap `std::sort` in a class type. * * Unfortunately, `std::sort` cannot be passed as template argument to a class * template or a function template.<br/> * This class fills the gap by wrapping some flavors of `std::sort` in a * function object. */ struct std_sort { /** * @brief Sorts the elements in a range. * * Sorts the elements in a range using the given binary comparison function. * * @tparam It Type of random access iterator. * @tparam Compare Type of comparison function object. * @tparam Args Types of arguments to forward to the sort function. * @param first An iterator to the first element of the range to sort. * @param last An iterator past the last element of the range to sort. * @param compare A valid comparison function object. * @param args Arguments to forward to the sort function, if any. */ template<typename It, typename Compare = std::less<>, typename... Args> void operator()(It first, It last, Compare compare = Compare{}, Args &&... args) const { std::sort(std::forward<Args>(args)..., std::move(first), std::move(last), std::move(compare)); } }; /*! @brief Function object for performing insertion sort. */ struct insertion_sort { /** * @brief Sorts the elements in a range. * * Sorts the elements in a range using the given binary comparison function. * * @tparam It Type of random access iterator. * @tparam Compare Type of comparison function object. * @param first An iterator to the first element of the range to sort. * @param last An iterator past the last element of the range to sort. * @param compare A valid comparison function object. */ template<typename It, typename Compare = std::less<>> void operator()(It first, It last, Compare compare = Compare{}) const { if(first < last) { for(auto it = first+1; it < last; ++it) { auto value = std::move(*it); auto pre = it; for(; pre > first && compare(value, *(pre-1)); --pre) { *pre = std::move(*(pre-1)); } *pre = std::move(value); } } } }; /** * @brief Function object for performing LSD radix sort. * @tparam Bit Number of bits processed per pass. * @tparam N Maximum number of bits to sort. */ template<std::size_t Bit, std::size_t N> struct radix_sort { static_assert((N % Bit) == 0); /** * @brief Sorts the elements in a range. * * Sorts the elements in a range using the given _getter_ to access the * actual data to be sorted. * * This implementation is inspired by the online book * [Physically Based Rendering](http://www.pbr-book.org/3ed-2018/Primitives_and_Intersection_Acceleration/Bounding_Volume_Hierarchies.html#RadixSort). * * @tparam It Type of random access iterator. * @tparam Getter Type of _getter_ function object. * @param first An iterator to the first element of the range to sort. * @param last An iterator past the last element of the range to sort. * @param getter A valid _getter_ function object. */ template<typename It, typename Getter = identity> void operator()(It first, It last, Getter getter = Getter{}) const { if(first < last) { static constexpr auto mask = (1 << Bit) - 1; static constexpr auto buckets = 1 << Bit; static constexpr auto passes = N / Bit; using value_type = typename std::iterator_traits<It>::value_type; std::vector<value_type> aux(std::distance(first, last)); auto part = [getter = std::move(getter)](auto from, auto to, auto out, auto start) { std::size_t index[buckets]{}; std::size_t count[buckets]{}; std::for_each(from, to, [&getter, &count, start](const value_type &item) { ++count[(getter(item) >> start) & mask]; }); std::for_each(std::next(std::begin(index)), std::end(index), [index = std::begin(index), count = std::begin(count)](auto &item) mutable { item = *(index++) + *(count++); }); std::for_each(from, to, [&getter, &out, &index, start](value_type &item) { out[index[(getter(item) >> start) & mask]++] = std::move(item); }); }; for(std::size_t pass = 0; pass < (passes & ~1); pass += 2) { part(first, last, aux.begin(), pass * Bit); part(aux.begin(), aux.end(), first, (pass + 1) * Bit); } if constexpr(passes & 1) { part(first, last, aux.begin(), (passes - 1) * Bit); std::move(aux.begin(), aux.end(), first); } } } }; } #endif // ENTT_CORE_ALGORITHM_HPP
35.805556
154
0.593871
MirrasHue
4f25db442b3062aaf7aadb41a2d61e14303097c3
1,477
cpp
C++
aws-cpp-sdk-serverlessrepo/source/model/PutApplicationPolicyRequest.cpp
woohoou/aws-sdk-cpp
a42835a8aad2eac1e334d899a3fbfedcaa341d51
[ "Apache-2.0" ]
1
2020-07-16T19:03:13.000Z
2020-07-16T19:03:13.000Z
aws-cpp-sdk-serverlessrepo/source/model/PutApplicationPolicyRequest.cpp
woohoou/aws-sdk-cpp
a42835a8aad2eac1e334d899a3fbfedcaa341d51
[ "Apache-2.0" ]
18
2018-05-15T16:41:07.000Z
2018-05-21T00:46:30.000Z
aws-cpp-sdk-serverlessrepo/source/model/PutApplicationPolicyRequest.cpp
woohoou/aws-sdk-cpp
a42835a8aad2eac1e334d899a3fbfedcaa341d51
[ "Apache-2.0" ]
1
2019-10-31T11:19:50.000Z
2019-10-31T11:19:50.000Z
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/serverlessrepo/model/PutApplicationPolicyRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::ServerlessApplicationRepository::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; PutApplicationPolicyRequest::PutApplicationPolicyRequest() : m_applicationIdHasBeenSet(false), m_statementsHasBeenSet(false) { } Aws::String PutApplicationPolicyRequest::SerializePayload() const { JsonValue payload; if(m_statementsHasBeenSet) { Array<JsonValue> statementsJsonList(m_statements.size()); for(unsigned statementsIndex = 0; statementsIndex < statementsJsonList.GetLength(); ++statementsIndex) { statementsJsonList[statementsIndex].AsObject(m_statements[statementsIndex].Jsonize()); } payload.WithArray("statements", std::move(statementsJsonList)); } return payload.WriteReadable(); }
28.403846
105
0.765741
woohoou
4f26272c351863625be15f91a7edc7fff8e67368
1,871
hpp
C++
src/scene.hpp
DavoSK/baliksena
c347055084b8e5ea9b0f970cbceb0769ab4504d3
[ "BSD-3-Clause" ]
5
2021-11-12T18:03:06.000Z
2021-12-19T14:22:05.000Z
src/scene.hpp
DavoSK/baliksena
c347055084b8e5ea9b0f970cbceb0769ab4504d3
[ "BSD-3-Clause" ]
null
null
null
src/scene.hpp
DavoSK/baliksena
c347055084b8e5ea9b0f970cbceb0769ab4504d3
[ "BSD-3-Clause" ]
1
2021-11-12T18:03:08.000Z
2021-11-12T18:03:08.000Z
#pragma once #include <memory> #include <string> #include <queue> #include "mafia/parser_cachebin.hpp" #include "mafia/parser_scene2bin.hpp" #include "model.hpp" #include "renderer.hpp" class Light; class Material; class Model; class Camera; class Sector; class Sound; class Mesh; class Scene : public Model { public: [[nodiscard]] Camera* getActiveCamera() { return mActiveCamera; } void setActiveCamera(Camera* cam) { mActiveCamera = cam; } [[nodiscard]] Camera* getDebugCamera() { return mDebugCamera; } [[nodiscard]] Sector* getCurrentSector() { return mCurrentSector; } void setCurrentSector(Sector* sector) { mCurrentSector = sector; } [[nodiscard]] Sector* getCameraSector(); void init(); void load(const std::string& mission); void clear(); void render(); void addToRenderList(Mesh* frameToPush) { mRenderList.push_back(frameToPush); } private: void createCameras(float fov, float near, float far); void updateActiveCamera(float deltaTime); void initVertexBuffers(); void getSectorOfPoint(const glm::vec3& pos, Frame* node, std::optional<Sector*>& foundSector); std::shared_ptr<Sound> loadSound(const MFFormat::DataFormatScene2BIN::Object& object); std::shared_ptr<Light> loadLight(const MFFormat::DataFormatScene2BIN::Object& object); std::shared_ptr<Sector> loadSector(const MFFormat::DataFormatScene2BIN::Object& object); std::shared_ptr<Model> loadModel(const MFFormat::DataFormatScene2BIN::Object& object); std::shared_ptr<Sector> mPrimarySector{ nullptr }; std::shared_ptr<Sector> mBackdropSector{ nullptr }; Camera* mActiveCamera{ nullptr }; Camera* mDebugCamera{ nullptr }; Sector* mCurrentSector{ nullptr }; Renderer::BufferHandle mVertexBuffer{ 0 }; Renderer::BufferHandle mIndexBuffer{ 0 }; std::vector<Mesh*> mRenderList; };
32.824561
98
0.722074
DavoSK
4f26cfbbe07d6c9554f96f091a10e3fe37f5f408
1,504
cpp
C++
examples/example4.cpp
hlitz/cache-table
2efb629236c5a72a3931ee3defdaa4cfcb11b7e7
[ "BSD-3-Clause" ]
null
null
null
examples/example4.cpp
hlitz/cache-table
2efb629236c5a72a3931ee3defdaa4cfcb11b7e7
[ "BSD-3-Clause" ]
null
null
null
examples/example4.cpp
hlitz/cache-table
2efb629236c5a72a3931ee3defdaa4cfcb11b7e7
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> #include <mm/cache_set.hpp> /** * This example shows how to use the discard function. * * The discard function is used when there is a key collision, in * this case the old element is removed and passed to the discard * function. * * The function can be used to verify discarded items, save them * into another level of cache (eg: on disk) or just ignore them. * */ struct DiscardLog { void operator() ( const std::string& old_value, const std::string& new_value ) { std::cout << "Replacing '" << old_value << "' ==> '" << new_value << "'" << std::endl; } }; typedef mm::cache_set< std::string, // Value mm::hash<std::string>, // HashFunction std::equal_to<std::string>, // KeyEqual DiscardLog // DiscardFunction > Set; int main() { Set set; set.resize( 10 ); set.insert( "kiwi" ); set.insert( "plum" ); set.insert( "apple" ); set.insert( "mango" ); set.insert( "apricot" ); set.insert( "banana" ); set.insert( "peer" ); set.insert( "melon" ); set.insert( "passion fruit" ); set.insert( "pineapple" ); std::cout << std::endl << " - All the elements - " << std::endl; Set::const_iterator it; for ( it = set.begin(); it != set.end(); ++it ) std::cout << *it << " "; std::cout << std::endl; }
25.931034
69
0.524601
hlitz
4f2b9ab667a70a0f1e8e88a7cf2c29821896ee90
6,411
cc
C++
squid/squid3-3.3.8.spaceify/src/DiskIO/AIO/AIODiskIOStrategy.cc
spaceify/spaceify
4296d6c93cad32bb735cefc9b8157570f18ffee4
[ "MIT" ]
4
2015-01-20T15:25:34.000Z
2017-12-20T06:47:42.000Z
squid/squid3-3.3.8.spaceify/src/DiskIO/AIO/AIODiskIOStrategy.cc
spaceify/spaceify
4296d6c93cad32bb735cefc9b8157570f18ffee4
[ "MIT" ]
4
2015-05-15T09:32:55.000Z
2016-02-18T13:43:31.000Z
squid/squid3-3.3.8.spaceify/src/DiskIO/AIO/AIODiskIOStrategy.cc
spaceify/spaceify
4296d6c93cad32bb735cefc9b8157570f18ffee4
[ "MIT" ]
null
null
null
/* * SQUID Web Proxy Cache http://www.squid-cache.org/ * ---------------------------------------------------------- * * Squid is the result of efforts by numerous individuals from * the Internet community; see the CONTRIBUTORS file for full * details. Many organizations have provided support for Squid's * development; see the SPONSORS file for full details. Squid is * Copyrighted (C) 2001 by the Regents of the University of * California; see the COPYRIGHT file for full details. Squid * incorporates software developed and/or copyrighted by other * sources; see the CREDITS file for full details. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. * * Copyright (c) 2003, Robert Collins <robertc@squid-cache.org> */ /* * Author: Adrian Chadd <adrian@squid-cache.org> * * These routines are simple plugin replacements for the file_* routines * in disk.c . They back-end into the POSIX AIO routines to provide * a nice and simple async IO framework for COSS. * * AIO is suitable for COSS - the only sync operations that the standard * supports are read/write, and since COSS works on a single file * per storedir it should work just fine. */ #include "squid.h" #include "AIODiskIOStrategy.h" #include "AIODiskFile.h" #include "DiskIO/IORequestor.h" #include "DiskIO/ReadRequest.h" #include "DiskIO/WriteRequest.h" AIODiskIOStrategy::AIODiskIOStrategy() : fd(-1) { aq.aq_state = AQ_STATE_NONE; aq.aq_numpending = 0; memset(&aq.aq_queue, 0, sizeof(aq.aq_queue)); } AIODiskIOStrategy::~AIODiskIOStrategy() { assert(aq.aq_state == AQ_STATE_SETUP || aq.aq_numpending == 0); sync(); aq.aq_state = AQ_STATE_NONE; } bool AIODiskIOStrategy::shedLoad() { return false; } int AIODiskIOStrategy::load() { return aq.aq_numpending * 1000 / MAX_ASYNCOP; } RefCount<DiskFile> AIODiskIOStrategy::newFile (char const *path) { if (shedLoad()) { return NULL; } return new AIODiskFile (path, this); } void AIODiskIOStrategy::sync() { assert(aq.aq_state == AQ_STATE_SETUP); /* * Keep calling callback to complete ops until the queue is empty * We can't quit when callback returns 0 - some calls may not * return any completed pending events, but they're still pending! */ while (aq.aq_numpending) callback(); } bool AIODiskIOStrategy::unlinkdUseful() const { return false; } void AIODiskIOStrategy::unlinkFile (char const *) {} /* * Note: we grab the state and free the state before calling the callback * because this allows us to cut down the amount of time it'll take * to find a free slot (since if we call the callback first, we're going * to probably be allocated the slot _after_ this one..) * * I'll make it much more optimal later. */ int AIODiskIOStrategy::callback() { return 0; int i; int completed = 0; int retval, reterr; FREE *freefunc; void *cbdata; int callback_valid; void *buf; async_queue_entry_t *aqe; async_queue_entry_type_t type; assert(aq.aq_state == AQ_STATE_SETUP); /* Loop through all slots */ for (i = 0; i < MAX_ASYNCOP; ++i) { if (aq.aq_queue[i].aq_e_state == AQ_ENTRY_USED) { aqe = &aq.aq_queue[i]; /* Active, get status */ reterr = aio_error(&aqe->aq_e_aiocb); if (reterr < 0) { fatal("aio_error returned an error!\n"); } if (reterr != EINPROGRESS) { /* Get the return code */ retval = aio_return(&aqe->aq_e_aiocb); /* Get the callback parameters */ freefunc = aqe->aq_e_free; buf = aqe->aq_e_buf; type = aqe->aq_e_type; callback_valid = cbdataReferenceValidDone(aqe->aq_e_callback_data, &cbdata); AIODiskFile * theFile = NULL; void *theFileVoid = NULL; void *theTmpFile = aqe->theFile; bool fileOk = cbdataReferenceValidDone(theTmpFile, &theFileVoid); if (fileOk) { theFile = static_cast<AIODiskFile *>(theFileVoid); } /* Free slot */ memset(aqe, 0, sizeof(async_queue_entry_t)); aqe->aq_e_state = AQ_ENTRY_FREE; --aq.aq_numpending; /* Callback */ if (callback_valid) { assert (fileOk); if (type == AQ_ENTRY_READ) theFile->ioRequestor->readCompleted((const char *)buf, retval, reterr, static_cast<ReadRequest *>(cbdata)); if (type == AQ_ENTRY_WRITE) theFile->ioRequestor->writeCompleted(reterr,retval, static_cast<WriteRequest *>(cbdata)); } if (type == AQ_ENTRY_WRITE && freefunc) freefunc(buf); } } } return completed; } void AIODiskIOStrategy::init() { /* Make sure the queue isn't setup */ assert(aq.aq_state == AQ_STATE_NONE); /* Loop through, blanking the queue entries */ /* Done */ aq.aq_state = AQ_STATE_SETUP; } void AIODiskIOStrategy::statfs(StoreEntry & sentry)const {} ConfigOption * AIODiskIOStrategy::getOptionTree() const { return NULL; } /* * find a free aio slot. * Return the index, or -1 if we can't find one. */ int AIODiskIOStrategy::findSlot() { /* Later we should use something a little more .. efficient :) */ for (int i = 0; i < MAX_ASYNCOP; ++i) { if (aq.aq_queue[i].aq_e_state == AQ_ENTRY_FREE) /* Found! */ return i; } /* found nothing */ return -1; }
27.165254
131
0.621276
spaceify
4f2c23bc97197017aae5579d50485ea92e3234a8
37,370
cpp
C++
src/tests/ngraph_helpers/ngraph_functions/src/utils/ngraph_helpers.cpp
ivkalgin/openvino
81685c8d212135dd9980da86a18db41fbf6d250a
[ "Apache-2.0" ]
null
null
null
src/tests/ngraph_helpers/ngraph_functions/src/utils/ngraph_helpers.cpp
ivkalgin/openvino
81685c8d212135dd9980da86a18db41fbf6d250a
[ "Apache-2.0" ]
18
2022-01-21T08:42:58.000Z
2022-03-28T13:21:31.000Z
src/tests/ngraph_helpers/ngraph_functions/src/utils/ngraph_helpers.cpp
ematroso/openvino
403339f8f470c90dee6f6d94ed58644b2787f66b
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <vector> #include <memory> #include <queue> #include <ngraph/op/util/op_types.hpp> #include <ngraph/opsets/opset1.hpp> #include <ngraph/opsets/opset3.hpp> #include <ngraph/opsets/opset5.hpp> #include <ngraph/pass/constant_folding.hpp> #include <ngraph/specialize_function.hpp> #include <ngraph_functions/utils/ngraph_helpers.hpp> #include <ngraph/opsets/opset.hpp> #include <backend.hpp> namespace ngraph { namespace helpers { std::ostream &operator<<(std::ostream &os, const ReductionType &m) { switch (m) { case Mean: os << "Mean"; break; case Max: os << "Max"; break; case Min: os << "Min"; break; case Prod: os << "Prod"; break; case Sum: os << "Sum"; break; case LogicalOr: os << "LogicalOr"; break; case LogicalAnd: os << "LogicalAnd"; break; case L1: os << "ReduceL1"; break; case L2: os << "ReduceL2"; break; } return os; } std::ostream &operator<<(std::ostream &os, const PadMode &m) { switch (m) { case PadMode::CONSTANT: os << "CONSTANT"; break; case PadMode::EDGE: os << "EDGE"; break; case PadMode::REFLECT: os << "REFLECT"; break; case PadMode::SYMMETRIC: os << "SYMMETRIC"; break; } return os; } OutputVector convert2OutputVector(const std::vector<std::shared_ptr<Node>> &nodes) { OutputVector outs; std::for_each(nodes.begin(), nodes.end(), [&outs](const std::shared_ptr<Node> &n) { for (const auto &out_p : n->outputs()) { outs.push_back(out_p); } }); return outs; } std::vector<std::pair<ngraph::element::Type, std::vector<std::uint8_t>>> interpreterFunction(const std::shared_ptr<Function> &function, const std::vector<std::vector<std::uint8_t>> &inputs, const std::vector<ngraph::element::Type> &inputTypes) { auto backend = runtime::Backend::create(); const auto &parameters = function->get_parameters(); const auto &parametersNumber = parameters.size(); const auto &inputsNumber = inputs.size(); NGRAPH_CHECK(parametersNumber == inputsNumber, "Got function (", function->get_friendly_name(), ") with ", parametersNumber, " parameters, but ", inputsNumber, " input blobs"); if (!inputTypes.empty()) { NGRAPH_CHECK(inputTypes.size() == inputsNumber, "Got function (", function->get_friendly_name(), ") with ", inputsNumber, " inputs, but ", inputTypes.size(), " types"); } auto inputTensors = std::vector<std::shared_ptr<runtime::Tensor>>{}; for (size_t i = 0; i < parametersNumber; ++i) { const auto &parameter = parameters[i]; const auto &parameterIndex = function->get_parameter_index(parameter); const auto &parameterShape = parameter->get_shape(); const auto &parameterType = parameter->get_element_type(); const auto &parameterSize = shape_size(parameterShape) * parameterType.size(); auto input = inputs[parameterIndex]; const auto inType = inputTypes.empty() ? element::undefined : inputTypes[i]; if (inType != element::undefined && inType != parameterType) { input = convertOutputPrecision(input, inType, parameterType, shape_size(parameterShape)); } const auto &inputSize = input.size(); NGRAPH_CHECK(parameterSize == inputSize, "Got parameter (", parameter->get_friendly_name(), ") of size ", parameterSize, " bytes, but corresponding input with index ", parameterIndex, " has ", inputSize, " bytes"); auto tensor = backend->create_tensor(parameterType, parameterShape); tensor->write(input.data(), parameterSize); inputTensors.push_back(tensor); } auto outputTensors = std::vector<std::shared_ptr<runtime::Tensor>>{}; const auto &results = function->get_results(); for (size_t i = 0; i < results.size(); ++i) { outputTensors.push_back(std::make_shared<HostTensor>()); } auto handle = backend->compile(function); handle->call_with_validate(outputTensors, inputTensors); std::vector<std::pair<ngraph::element::Type, std::vector<std::uint8_t>>> outputs(results.size()); for (size_t resultIndex = 0; resultIndex < results.size(); resultIndex++) { auto& output = outputs[resultIndex]; output.first = results[resultIndex]->get_element_type(); const auto& outputTensor = outputTensors[resultIndex]; output.second.resize(ceil(shape_size(outputTensor->get_shape()) * outputTensor->get_element_type().bitwidth() / 8.f)); outputTensors[resultIndex]->read(output.second.data(), output.second.size()); } return outputs; } std::vector<ov::runtime::Tensor> interpretFunction(const std::shared_ptr<Function> &function, const std::map<std::shared_ptr<ov::Node>, ov::runtime::Tensor>& inputs) { auto backend = runtime::Backend::create(); const auto &funcInputs = function->inputs(); const auto &funcInputsNumber = funcInputs.size(); const auto &inputsNumber = inputs.size(); NGRAPH_CHECK(funcInputsNumber == inputsNumber, "Got function (", function->get_friendly_name(), ") with ", funcInputsNumber, " parameters, but ", inputsNumber, " input blobs"); auto inputTensors = std::vector<std::shared_ptr<runtime::Tensor>>{}; for (size_t i = 0; i < funcInputsNumber; ++i) { const auto &input = funcInputs[i]; const auto &inputShape = input.get_shape(); const auto &inputType = input.get_element_type(); const auto &inputSize = shape_size(inputShape) * inputType.size(); auto inputIt = std::find_if(inputs.begin(), inputs.end(), [&input](std::pair<std::shared_ptr<ov::Node>, ov::runtime::Tensor> elem) { return elem.first->get_friendly_name() == input.get_node_shared_ptr()->get_friendly_name(); }); if (inputIt == inputs.end()) { throw std::runtime_error("Parameter: " + input.get_node_shared_ptr()->get_friendly_name() + " was not find in input parameters"); } auto inputTensor = inputIt->second; const auto &inputTensorSize = inputTensor.get_byte_size(); NGRAPH_CHECK(inputSize == inputTensorSize, "Got parameter (", input.get_node_shared_ptr()->get_friendly_name(), ") of size ", inputSize, " bytes, but corresponding input ", " has ", inputTensorSize, " bytes"); auto tensor = backend->create_tensor(inputType, inputShape); tensor->write(inputTensor.data(), inputSize); inputTensors.push_back(tensor); } std::vector<std::shared_ptr<runtime::Tensor>> outputTensors; const auto &results = function->get_results(); for (size_t i = 0; i < results.size(); ++i) { outputTensors.push_back(std::make_shared<HostTensor>()); } auto handle = backend->compile(function); handle->call_with_validate(outputTensors, inputTensors); std::vector<ov::runtime::Tensor> outputs; for (const auto& outTensor : outputTensors) { ov::runtime::Tensor tmpBuffer(outTensor->get_element_type(), outTensor->get_shape()); outTensor->read(tmpBuffer.data(), tmpBuffer.get_byte_size()); outputs.push_back(tmpBuffer); } return outputs; } std::shared_ptr<Function> foldFunction(const std::shared_ptr<Function> &function, const std::vector<std::vector<std::uint8_t>> &inputs, const std::vector<ngraph::element::Type> &inputTypes) { const auto &parameters = function->get_parameters(); const auto &parametersNumber = parameters.size(); const auto &inputsNumber = inputs.size(); NGRAPH_CHECK(parametersNumber == inputsNumber, "Got function (", function->get_friendly_name(), ") with ", parametersNumber, " parameters, but ", inputsNumber, " input blobs"); if (!inputTypes.empty()) { NGRAPH_CHECK(inputTypes.size() == inputsNumber, "Got function (", function->get_friendly_name(), ") with ", inputsNumber, " inputs, but ", inputTypes.size(), " types"); } std::vector<element::Type> paramElementTypes; std::vector<PartialShape> paramShapes; std::vector<std::vector<std::uint8_t>> vecTmpConvertedInputs; vecTmpConvertedInputs.reserve(inputs.size()); std::vector<void *> inBuffers; inBuffers.reserve(inputs.size()); for (size_t i = 0; i < parametersNumber; ++i) { const auto &param = parameters[i]; paramElementTypes.emplace_back(param->get_element_type()); paramShapes.emplace_back(param->get_shape()); auto parameterIndex = function->get_parameter_index(param); auto& input = inputs[parameterIndex]; const auto inpType = inputTypes.empty() ? element::undefined : inputTypes[i]; if (inpType != element::undefined && inpType != paramElementTypes.back()) { vecTmpConvertedInputs.emplace_back(convertOutputPrecision(input, inpType, param->get_element_type(), shape_size(param->get_shape()))); inBuffers.push_back(vecTmpConvertedInputs.back().data()); } else { // const_cast added to satisfy specialize_function interface // which requires inputs as std::vector<void *> inBuffers.push_back(const_cast<std::uint8_t *>(input.data())); } } NGRAPH_SUPPRESS_DEPRECATED_START; const auto &foldedFunc = specialize_function(function, paramElementTypes, paramShapes, inBuffers); NGRAPH_SUPPRESS_DEPRECATED_END; ngraph::pass::ConstantFolding().run_on_model(foldedFunc); for (const auto &op : foldedFunc->get_ops()) { NGRAPH_CHECK(op::is_constant(op) || op::is_output(op) || op::is_parameter(op), "Function was not fully folded to constant state!\n", "At least one non constant node with type ", op->get_type_name(), " present in function."); } return foldedFunc; } std::vector<std::pair<ngraph::element::Type, std::vector<std::uint8_t>>> getConstData(const std::shared_ptr<Function> &function) { size_t numOutputs = function->get_output_size(); std::vector<std::pair<ngraph::element::Type, std::vector<std::uint8_t>>> outputs(numOutputs); auto funcResults = function->get_results(); for (size_t i = 0; i < numOutputs; i++) { outputs[i].first = funcResults[i]->get_element_type(); const auto &output = function->output(i).get_node_shared_ptr(); NGRAPH_CHECK(output->inputs().size() == 1); auto parrentNode = output->input_value(0).get_node_shared_ptr(); NGRAPH_CHECK(op::is_constant(parrentNode), "Function was not fully folded to constant state!\n", "Parent node of one of results is not constant and has type ", parrentNode->get_type_name()); const auto data = std::dynamic_pointer_cast<opset1::Constant>(parrentNode)->get_data_ptr<std::uint8_t>(); const auto dataSize = shape_size(parrentNode->get_shape()) * parrentNode->get_element_type().size(); outputs[i].second.resize(dataSize); std::copy(data, data + dataSize, outputs[i].second.data()); } return outputs; } namespace { std::string toString(const NodeTypeInfo& typeInfo) { return std::string(typeInfo.name) + " ver. " + std::to_string(typeInfo.version); } void CompareShapes(const PartialShape& actual, const PartialShape& expected) { NGRAPH_CHECK(actual.relaxes(expected) && actual.refines(expected), "Functions compare: Different shape detected ", actual, " and ", expected); } void CompareNodes(const Node& actual, const Node& expected) { const auto& actualType = actual.get_type_info(); const auto& expectedType = expected.get_type_info(); NGRAPH_CHECK(actualType == expectedType, "Functions compare: data types must be equal ", toString(actualType), " != ", toString(expectedType)); const auto& numActualInputs = actual.inputs().size(); const auto& numExpectedInputs = expected.inputs().size(); NGRAPH_CHECK(numActualInputs == numExpectedInputs, "Functions compare: numbers of inputs are different: ", numActualInputs, " and ", numExpectedInputs); const auto& numActualOutputs = actual.outputs().size(); const auto& numExpectedOutputs = expected.outputs().size(); NGRAPH_CHECK(numActualOutputs == numExpectedOutputs, "Functions compare: numbers of outputs are different: ", numActualOutputs, " and ", numExpectedOutputs); } } // namespace void CompareFunctions(const Function& actual, const Function& expected) { const auto& actualOrderedOps = actual.get_ordered_ops(); const auto& expectedOrderedOps = expected.get_ordered_ops(); NGRAPH_CHECK(expectedOrderedOps.size() == actualOrderedOps.size(), "Functions compare: expected and actual ops number should be equal " "but got ", expectedOrderedOps.size(), " and ", actualOrderedOps.size(), " respectively"); for (std::size_t i = 0; i < expectedOrderedOps.size(); i++) { const auto& expectedOp = expectedOrderedOps[i]; const auto& actualOp = actualOrderedOps[i]; CompareNodes(*actualOp, *expectedOp); for (std::size_t i = 0; i < actualOp->inputs().size(); ++i) { const auto& actualShape = actualOp->input(i).get_partial_shape(); const auto& expectedShape = expectedOp->input(i).get_partial_shape(); CompareShapes(actualShape, expectedShape); } for (std::size_t i = 0; i < actualOp->outputs().size(); ++i) { const auto& actualShape = actualOp->output(i).get_partial_shape(); const auto& expectedShape = expectedOp->output(i).get_partial_shape(); CompareShapes(actualShape, expectedShape); } } } std::shared_ptr<ngraph::Node> getNodeSharedPtr(const ngraph::NodeTypeInfo &type_info, const ngraph::OutputVector &outputVector) { for (const auto& opset : {ngraph::get_opset5(), ngraph::get_opset4(), ngraph::get_opset3(), ngraph::get_opset2(), ngraph::get_opset1()}) if (opset.contains_type(type_info)) { const auto ngraphNode = std::shared_ptr<ngraph::Node>(opset.create(type_info.name)); ngraphNode->set_arguments(outputVector); ngraphNode->validate_and_infer_types(); return ngraphNode; } NGRAPH_UNREACHABLE("supported opsets does not contain op with name: ", type_info.name, " version: ", type_info.version); } bool is_tensor_iterator_exist(const std::shared_ptr<ngraph::Function> & func) { const auto& ops = func->get_ops(); for (const auto& node : ops) { const auto& ti = std::dynamic_pointer_cast<ngraph::opset5::TensorIterator>(node); if (ti) { return true; } } return false; } namespace { template <int Bitwidth, typename Value, typename In, typename std::enable_if<std::is_unsigned<Value>::value, bool>::type = true> Value fix_sign(In v) { return v; } template <int Bitwidth, typename Value, typename In, typename std::enable_if<std::is_signed<Value>::value, bool>::type = true> Value fix_sign(In v) { constexpr unsigned sign_bit = 1u << (Bitwidth -1); const bool is_negative_number = v & sign_bit; return is_negative_number ? v | 0xFFF0 : v; } template<int Bitwidth, typename Value> class LowPrecisionWrapper { public: static constexpr int bitwidth = Bitwidth; static constexpr uint8_t value_mask = (1u << bitwidth) - 1u; static constexpr int elements_in_byte = 8 / bitwidth; LowPrecisionWrapper(uint8_t* data, int position): data(data), position(position) {} operator Value() const { return fix_sign<Bitwidth, Value>(((*data) >> (position * bitwidth)) & value_mask); } LowPrecisionWrapper& operator=(Value v) { uint8_t masked_value = v & value_mask; *data &= ~(value_mask << (position * bitwidth)); *data |= masked_value << (position * bitwidth); return *this; } private: int position{elements_in_byte - 1}; uint8_t* data; }; template<int Bitwidth, typename Value> class LowPrecisionWrapperToConst { public: static constexpr int bitwidth = Bitwidth; static constexpr uint8_t value_mask = (1u << bitwidth) - 1u; static constexpr int elements_in_byte = 8 / bitwidth; LowPrecisionWrapperToConst(const uint8_t* data, int position): data(data), position(position) {} operator Value() const { return fix_sign<Bitwidth, Value>(((*data) >> (position * bitwidth)) & value_mask); } private: int position{elements_in_byte - 1}; const uint8_t* data; }; template<int Bitwidth, typename Value> class LowPrecistionRange { public: static constexpr int bitwidth = Bitwidth; static constexpr int elements_in_byte = 8 / bitwidth; LowPrecistionRange(uint8_t* data): data(data) {} LowPrecisionWrapper<Bitwidth, Value> operator[](size_t index) const { const ptrdiff_t byte_offset = index / elements_in_byte; const int bit_position = elements_in_byte - 1 - (index % elements_in_byte); return {data + byte_offset, bit_position}; } uint8_t* data; }; template<int Bitwidth, typename Value> class LowPrecistionConstRange { public: static constexpr int bitwidth = Bitwidth; static constexpr int elements_in_byte = 8 / bitwidth; LowPrecistionConstRange(const uint8_t* data) : data(data) {} LowPrecisionWrapperToConst<Bitwidth, Value> operator[](size_t index) const { const ptrdiff_t byte_offset = index / elements_in_byte; const int bit_position = elements_in_byte - 1 - (index % elements_in_byte); return {data + byte_offset, bit_position}; } const uint8_t* data; }; template <element::Type_t FromType, typename std::enable_if<FromType != element::Type_t::u1 && FromType != element::Type_t::u4 && FromType != element::Type_t::i4, bool>::type = true> const fundamental_type_for<FromType>* cast_to(const uint8_t* data) { return reinterpret_cast<const fundamental_type_for<FromType>*>(data); } template <element::Type_t FromType, typename std::enable_if<FromType != element::Type_t::u1 && FromType != element::Type_t::u4 && FromType != element::Type_t::i4, bool>::type = true> fundamental_type_for<FromType>* cast_to(uint8_t* data) { return reinterpret_cast<fundamental_type_for<FromType>*>(data); } template <element::Type_t FromType, typename std::enable_if<FromType == element::Type_t::u1, bool>::type = true> LowPrecistionConstRange<1, uint8_t> cast_to(const uint8_t* data) { return LowPrecistionConstRange<1, uint8_t>(data); } template <element::Type_t FromType, typename std::enable_if<FromType == element::Type_t::u1, bool>::type = true> LowPrecistionRange<1, uint8_t> cast_to(uint8_t* data) { return LowPrecistionRange<1, uint8_t>(data); } template <element::Type_t FromType, typename std::enable_if<FromType == element::Type_t::u4, bool>::type = true> LowPrecistionConstRange<4, uint8_t> cast_to(const uint8_t* data) { return LowPrecistionConstRange<4, uint8_t>(data); } template <element::Type_t FromType, typename std::enable_if<FromType == element::Type_t::u4, bool>::type = true> LowPrecistionRange<4, uint8_t> cast_to(uint8_t* data) { return LowPrecistionRange<4, uint8_t>(data); } template <element::Type_t FromType, typename std::enable_if<FromType == element::Type_t::i4, bool>::type = true> LowPrecistionConstRange<4, int8_t> cast_to(const uint8_t* data) { return LowPrecistionConstRange<4, int8_t>(data); } template <element::Type_t FromType, typename std::enable_if<FromType == element::Type_t::i4, bool>::type = true> LowPrecistionRange<4, int8_t> cast_to(uint8_t* data) { return LowPrecistionRange<4, int8_t>(data); } template <element::Type_t FromType, element::Type_t ToType> std::vector<std::uint8_t> convertPrecision(const std::vector<std::uint8_t> &buffer, const size_t elementsCount) { using fromPrec = fundamental_type_for<FromType>; using toPrec = fundamental_type_for<ToType>; const size_t min_buffer_size = [&] { element::Type from_type(FromType); if (from_type.bitwidth() >= 8) { return elementsCount * sizeof(fromPrec); } return from_type.bitwidth() * elementsCount / 8; }(); NGRAPH_CHECK(buffer.size() >= min_buffer_size, "avoid buffer overflow"); constexpr auto elementSize = sizeof(toPrec); std::vector<std::uint8_t> convertedData(elementsCount * elementSize); auto src = cast_to<FromType>(buffer.data()); auto dst = cast_to<ToType>(convertedData.data()); for (size_t i = 0; i < elementsCount; i++) { dst[i] = static_cast<toPrec>(src[i]); } return convertedData; } template <element::Type_t FromType> std::vector<std::uint8_t> convertPrecisionFrom(const std::vector<std::uint8_t> &output, const element::Type_t &toPrecision, const size_t elementsCount) { switch (toPrecision) { case element::Type_t::boolean: { return convertPrecision<FromType, element::Type_t::boolean>(output, elementsCount); } case element::Type_t::bf16: { return convertPrecision<FromType, element::Type_t::bf16>(output, elementsCount); } case element::Type_t::f16: { return convertPrecision<FromType, element::Type_t::f16>(output, elementsCount); } case element::Type_t::f32: { return convertPrecision<FromType, element::Type_t::f32>(output, elementsCount); } case element::Type_t::f64: { return convertPrecision<FromType, element::Type_t::f64>(output, elementsCount); } case element::Type_t::i4: { return convertPrecision<FromType, element::Type_t::i4>(output, elementsCount); } case element::Type_t::i8: { return convertPrecision<FromType, element::Type_t::i8>(output, elementsCount); } case element::Type_t::i16: { return convertPrecision<FromType, element::Type_t::i16>(output, elementsCount); } case element::Type_t::i32: { return convertPrecision<FromType, element::Type_t::i32>(output, elementsCount); } case element::Type_t::i64: { return convertPrecision<FromType, element::Type_t::i64>(output, elementsCount); } case element::Type_t::u1: { return convertPrecision<FromType, element::Type_t::u1>(output, elementsCount); } case element::Type_t::u4: { return convertPrecision<FromType, element::Type_t::u4>(output, elementsCount); } case element::Type_t::u8: { return convertPrecision<FromType, element::Type_t::u8>(output, elementsCount); } case element::Type_t::u16: { return convertPrecision<FromType, element::Type_t::u16>(output, elementsCount); } case element::Type_t::u32: { return convertPrecision<FromType, element::Type_t::u32>(output, elementsCount); } case element::Type_t::u64: { return convertPrecision<FromType, element::Type_t::u64>(output, elementsCount); } default: throw std::runtime_error( std::string("convertOutputPrecision can't convert from: ") + element::Type(FromType).get_type_name() + " to: " + element::Type(toPrecision).get_type_name()); } } } // namespace std::vector<std::uint8_t> convertOutputPrecision(const std::vector<std::uint8_t> &output, const element::Type_t &fromPrecision, const element::Type_t &toPrecision, const size_t elementsCount) { switch (fromPrecision) { case element::Type_t::boolean: { return convertPrecisionFrom<element::Type_t::boolean>(output, toPrecision, elementsCount); } case element::Type_t::bf16: { return convertPrecisionFrom<element::Type_t::bf16>(output, toPrecision, elementsCount); } case element::Type_t::f16: { return convertPrecisionFrom<element::Type_t::f16>(output, toPrecision, elementsCount); } case element::Type_t::f32: { return convertPrecisionFrom<element::Type_t::f32>(output, toPrecision, elementsCount); } case element::Type_t::f64: { return convertPrecisionFrom<element::Type_t::f64>(output, toPrecision, elementsCount); } case element::Type_t::i4: { return convertPrecisionFrom<element::Type_t::i4>(output, toPrecision, elementsCount); } case element::Type_t::i8: { return convertPrecisionFrom<element::Type_t::i8>(output, toPrecision, elementsCount); } case element::Type_t::i16: { return convertPrecisionFrom<element::Type_t::i16>(output, toPrecision, elementsCount); } case element::Type_t::i32: { return convertPrecisionFrom<element::Type_t::i32>(output, toPrecision, elementsCount); } case element::Type_t::i64: { return convertPrecisionFrom<element::Type_t::i64>(output, toPrecision, elementsCount); } case element::Type_t::u1: { return convertPrecisionFrom<element::Type_t::u1>(output, toPrecision, elementsCount); } case element::Type_t::u4: { return convertPrecisionFrom<element::Type_t::u4>(output, toPrecision, elementsCount); } case element::Type_t::u8: { return convertPrecisionFrom<element::Type_t::u8>(output, toPrecision, elementsCount); } case element::Type_t::u16: { return convertPrecisionFrom<element::Type_t::u16>(output, toPrecision, elementsCount); } case element::Type_t::u32: { return convertPrecisionFrom<element::Type_t::u32>(output, toPrecision, elementsCount); } case element::Type_t::u64: { return convertPrecisionFrom<element::Type_t::u64>(output, toPrecision, elementsCount); } default: throw std::runtime_error( std::string("convertOutputPrecision can't convert from: ") + element::Type(fromPrecision).get_type_name() + " precision"); } } std::ostream& operator<<(std::ostream & os, const ngraph::helpers::EltwiseTypes type) { switch (type) { case ngraph::helpers::EltwiseTypes::SUBTRACT: os << "Sub"; break; case ngraph::helpers::EltwiseTypes::MULTIPLY: os << "Prod"; break; case ngraph::helpers::EltwiseTypes::ADD: os << "Sum"; break; case ngraph::helpers::EltwiseTypes::DIVIDE: os << "Div"; break; case ngraph::helpers::EltwiseTypes::SQUARED_DIFF: os << "SqDiff"; break; case ngraph::helpers::EltwiseTypes::POWER: os << "Pow"; break; case ngraph::helpers::EltwiseTypes::FLOOR_MOD: os << "FloorMod"; break; case ngraph::helpers::EltwiseTypes::MOD: os << "Mod"; break; case ngraph::helpers::EltwiseTypes::ERF: os << "Erf"; break; default: throw std::runtime_error("NOT_SUPPORTED_OP_TYPE"); } return os; } std::ostream& operator<<(std::ostream & os, ngraph::helpers::SqueezeOpType type) { switch (type) { case ngraph::helpers::SqueezeOpType::SQUEEZE: os << "Squeeze"; break; case ngraph::helpers::SqueezeOpType::UNSQUEEZE: os << "Unsqueeze"; break; default: throw std::runtime_error("NOT_SUPPORTED_OP_TYPE"); } return os; } std::ostream& operator<<(std::ostream& os, ngraph::helpers::InputLayerType type) { switch (type) { case ngraph::helpers::InputLayerType::CONSTANT: os << "CONSTANT"; break; case ngraph::helpers::InputLayerType::PARAMETER: os << "PARAMETER"; break; default: throw std::runtime_error("NOT_SUPPORTED_INPUT_LAYER_TYPE"); } return os; } std::ostream& operator<<(std::ostream & os, ngraph::helpers::ComparisonTypes type) { switch (type) { case ngraph::helpers::ComparisonTypes::EQUAL: os << "Equal"; break; case ngraph::helpers::ComparisonTypes::NOT_EQUAL: os << "NotEqual"; break; case ngraph::helpers::ComparisonTypes::GREATER: os << "Greater"; break; case ngraph::helpers::ComparisonTypes::GREATER_EQUAL: os << "GreaterEqual"; break; case ngraph::helpers::ComparisonTypes::LESS: os << "Less"; break; case ngraph::helpers::ComparisonTypes::LESS_EQUAL: os << "LessEqual"; break; default: throw std::runtime_error("NOT_SUPPORTED_OP_TYPE"); } return os; } std::ostream& operator<<(std::ostream & os, ngraph::helpers::LogicalTypes type) { switch (type) { case ngraph::helpers::LogicalTypes::LOGICAL_AND: os << "LogicalAnd"; break; case ngraph::helpers::LogicalTypes::LOGICAL_OR: os << "LogicalOr"; break; case ngraph::helpers::LogicalTypes::LOGICAL_NOT: os << "LogicalNot"; break; case ngraph::helpers::LogicalTypes::LOGICAL_XOR: os << "LogicalXor"; break; default: throw std::runtime_error("NOT_SUPPORTED_OP_TYPE"); } return os; } std::ostream& operator<<(std::ostream & os, ngraph::op::v4::Interpolate::InterpolateMode type) { switch (type) { case ngraph::op::v4::Interpolate::InterpolateMode::CUBIC: os << "cubic"; break; case ngraph::op::v4::Interpolate::InterpolateMode::LINEAR: os << "linear"; break; case ngraph::op::v4::Interpolate::InterpolateMode::LINEAR_ONNX: os << "linear_onnx"; break; case ngraph::op::v4::Interpolate::InterpolateMode::NEAREST: os << "nearest"; break; default: throw std::runtime_error("NOT_SUPPORTED_OP_TYPE"); } return os; } std::ostream& operator<<(std::ostream & os, ngraph::op::v4::Interpolate::CoordinateTransformMode type) { switch (type) { case ngraph::op::v4::Interpolate::CoordinateTransformMode::ALIGN_CORNERS: os << "align_corners"; break; case ngraph::op::v4::Interpolate::CoordinateTransformMode::ASYMMETRIC: os << "asymmetric"; break; case ngraph::op::v4::Interpolate::CoordinateTransformMode::HALF_PIXEL: os << "half_pixel"; break; case ngraph::op::v4::Interpolate::CoordinateTransformMode::PYTORCH_HALF_PIXEL: os << "pytorch_half_pixel"; break; case ngraph::op::v4::Interpolate::CoordinateTransformMode::TF_HALF_PIXEL_FOR_NN: os << "tf_half_pixel_for_nn"; break; default: throw std::runtime_error("NOT_SUPPORTED_OP_TYPE"); } return os; } std::ostream& operator<<(std::ostream & os, ngraph::op::v4::Interpolate::NearestMode type) { switch (type) { case ngraph::op::v4::Interpolate::NearestMode::CEIL: os << "ceil"; break; case ngraph::op::v4::Interpolate::NearestMode::ROUND_PREFER_CEIL: os << "round_prefer_ceil"; break; case ngraph::op::v4::Interpolate::NearestMode::FLOOR: os << "floor"; break; case ngraph::op::v4::Interpolate::NearestMode::ROUND_PREFER_FLOOR: os << "round_prefer_floor"; break; case ngraph::op::v4::Interpolate::NearestMode::SIMPLE: os << "simple"; break; default: throw std::runtime_error("NOT_SUPPORTED_OP_TYPE"); } return os; } std::ostream& operator<<(std::ostream & os, ngraph::op::v4::Interpolate::ShapeCalcMode type) { switch (type) { case ngraph::op::v4::Interpolate::ShapeCalcMode::SCALES: os << "scales"; break; case ngraph::op::v4::Interpolate::ShapeCalcMode::SIZES: os << "sizes"; break; default: throw std::runtime_error("NOT_SUPPORTED_OP_TYPE"); } return os; } std::ostream& operator<<(std::ostream & os, TensorIteratorBody type) { switch (type) { case TensorIteratorBody::LSTM: os << "LSTM"; break; case TensorIteratorBody::RNN: os << "RNN"; break; case TensorIteratorBody::GRU: os << "GRU"; break; default: throw std::runtime_error("NOT_SUPPORTED_OP_TYPE"); } return os; } std::ostream& operator<<(std::ostream & os, SequenceTestsMode type) { switch (type) { case SequenceTestsMode::PURE_SEQ: os << "PURE_SEQ"; break; case SequenceTestsMode::PURE_SEQ_RAND_SEQ_LEN_CONST: os << "PURE_SEQ_RAND_SEQ_LEN_CONST"; break; case SequenceTestsMode::PURE_SEQ_RAND_SEQ_LEN_PARAM: os << "PURE_SEQ_RAND_SEQ_LEN_PARAM"; break; case SequenceTestsMode::CONVERT_TO_TI_RAND_SEQ_LEN_PARAM: os << "CONVERT_TO_TI_RAND_SEQ_LEN_PARAM"; break; case SequenceTestsMode::CONVERT_TO_TI_RAND_SEQ_LEN_CONST: os << "CONVERT_TO_TI_RAND_SEQ_LEN_CONST"; break; case SequenceTestsMode::CONVERT_TO_TI_MAX_SEQ_LEN_PARAM: os << "CONVERT_TO_TI_MAX_SEQ_LEN_PARAM"; break; case SequenceTestsMode::CONVERT_TO_TI_MAX_SEQ_LEN_CONST: os << "CONVERT_TO_TI_MAX_SEQ_LEN_CONST"; break; default: throw std::runtime_error("NOT_SUPPORTED_OP_TYPE"); } return os; } std::ostream& operator<<(std::ostream & os, MemoryTransformation type) { switch (type) { case MemoryTransformation::NONE: os << "NONE"; break; case MemoryTransformation::LOW_LATENCY_V2: os << "LOW_LATENCY_V2"; break; case MemoryTransformation::LOW_LATENCY: os << "LOW_LATENCY"; break; case MemoryTransformation::LOW_LATENCY_V2_REGULAR_API: os << "LOW_LATENCY_V2_REGULAR_API"; break; case MemoryTransformation::LOW_LATENCY_REGULAR_API: os << "LOW_LATENCY_REGULAR_API"; break; case MemoryTransformation::LOW_LATENCY_V2_ORIGINAL_INIT: os << "LOW_LATENCY_V2_ORIGINAL_INIT"; break; default: throw std::runtime_error("NOT_SUPPORTED_TYPE"); } return os; } std::ostream& operator<<(std::ostream & os, ngraph::op::util::NmsBase::SortResultType type) { switch (type) { case op::util::NmsBase::SortResultType::CLASSID: os << "CLASSID"; break; case op::util::NmsBase::SortResultType::SCORE: os << "SCORE"; break; case op::util::NmsBase::SortResultType::NONE: os << "NONE"; break; default: throw std::runtime_error("NOT_SUPPORTED_TYPE"); } return os; } std::ostream& operator<<(std::ostream & os, op::v8::MatrixNms::DecayFunction type) { switch (type) { case op::v8::MatrixNms::DecayFunction::GAUSSIAN: os << "GAUSSIAN"; break; case op::v8::MatrixNms::DecayFunction::LINEAR: os << "LINEAR"; break; default: throw std::runtime_error("NOT_SUPPORTED_TYPE"); } return os; } void resize_function(std::shared_ptr<ov::Model> function, const std::vector<ov::Shape>& targetInputStaticShapes) { auto inputs = function->inputs(); std::map<ov::Output<ov::Node>, ov::PartialShape> shapes; if (inputs.size() > targetInputStaticShapes.size()) { throw std::runtime_error("targetInputStaticShapes.size() = " + std::to_string(targetInputStaticShapes.size()) + " != inputs.size() = " + std::to_string(inputs.size())); } for (size_t i = 0; i < inputs.size(); i++) { shapes.insert({inputs[i], targetInputStaticShapes[i]}); } function->reshape(shapes); } } // namespace helpers } // namespace ngraph
39.254202
156
0.622933
ivkalgin
4f2d2db26cf1825ff0c6fca4c0f560f07df7f21c
25,970
cpp
C++
system/jlib/jmisc.cpp
oxhead/HPCC-Platform
62e092695542a9bbea1bb3672f0d1ff572666cfc
[ "Apache-2.0" ]
null
null
null
system/jlib/jmisc.cpp
oxhead/HPCC-Platform
62e092695542a9bbea1bb3672f0d1ff572666cfc
[ "Apache-2.0" ]
null
null
null
system/jlib/jmisc.cpp
oxhead/HPCC-Platform
62e092695542a9bbea1bb3672f0d1ff572666cfc
[ "Apache-2.0" ]
null
null
null
/*############################################################################## HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®. 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 MINIMALTRACE // a more readable version of the trace file (IMO) //#define LOGCLOCK #include "platform.h" #include "stdio.h" #include <time.h> #include "jmisc.hpp" #include "jmutex.hpp" #include "jexcept.hpp" #include "jstring.hpp" #include "jdebug.hpp" #ifndef _WIN32 #include <sys/wait.h> #include <pwd.h> #endif #ifdef LOGCLOCK #define MSGFIELD_PRINTLOG MSGFIELD_timeDate | MSGFIELD_msgID | MSGFIELD_process | MSGFIELD_thread | MSGFIELD_code | MSGFIELD_milliTime #else #define MSGFIELD_PRINTLOG MSGFIELD_timeDate | MSGFIELD_msgID | MSGFIELD_process | MSGFIELD_thread | MSGFIELD_code #endif #define FPRINTF(s) { fprintf(stdlog, "%s", s); \ if (logFile) fprintf(logFile, "%s", s); } void _rev(size32_t len, void * _ptr) { byte * ptr = (byte *)_ptr; while (len > 1) { byte t = *ptr; *ptr = ptr[--len]; ptr[len] = t; len--; ptr++; } } Mutex printMutex; FILE *logFile; FILE *stdlog = stderr; HiresTimer logTimer; class CStdLogIntercept: public ILogIntercept { bool nl; #ifdef MINIMALTRACE time_t lastt; unsigned lasttpid; #endif unsigned detail; public: CStdLogIntercept() { #ifdef MINIMALTRACE lasttpid = 0; lastt = 0; #endif nl = true; detail = _LOG_TIME | _LOG_PID | _LOG_TID; #ifdef LOGCLOCK detail |= _LOG_CLOCK; #endif queryStderrLogMsgHandler()->setMessageFields(detail); } unsigned setLogDetail(unsigned i) { unsigned ret = detail; detail = i; return ret; } void print(const char *str) { if (nl) { char timeStamp[32]; time_t tNow; time(&tNow); #ifdef _WIN32 struct tm ltNow = *localtime(&tNow); #else struct tm ltNow; localtime_r(&tNow, &ltNow); #endif #ifdef MINIMALTRACE unsigned tpid = GetCurrentThreadId(); if (((detail & _LOG_TID) && tpid!=lasttpid)||((detail & _LOG_TIME) && memcmp(&tNow,&lastt,sizeof(tNow))!=0)) { lasttpid = tpid; lastt = tNow; FPRINTF("["); if (detail & _LOG_TIME) { strftime(timeStamp, 32, "%H:%M:%S ", &ltNow); FPRINTF(timeStamp); } if (detail & _LOG_TID) { fprintf(stdlog, "TID=%d ", tpid); if (logFile) fprintf(logFile, "TID=%d ", tpid); } FPRINTF("]\n"); } #else if (detail & _LOG_TIME) { strftime(timeStamp, 32, "%m/%d/%y %H:%M:%S ", &ltNow); FPRINTF(timeStamp); } if (detail & _LOG_CLOCK) { unsigned t=msTick(); fprintf(stdlog, "%u ", t); if (logFile) fprintf(logFile, "%u ", t); } if (detail & _LOG_HIRESCLOCK) { unsigned clock = usTick(); fprintf(stdlog, " TICK=%u ", clock); if (logFile) fprintf(logFile, " TICK=%u ", clock); } #if defined(_WIN32) if (detail & _LOG_TID) { fprintf(stdlog, "TID=%d ", GetCurrentThreadId()); if (logFile) fprintf(logFile, "TID=%d ", GetCurrentThreadId()); } if (detail & _LOG_PID) { fprintf(stdlog, "PID=%d ", GetCurrentProcessId()); if (logFile) fprintf(logFile, "PID=%d ", GetCurrentProcessId()); } #else if (detail & _LOG_PID) { fprintf(stdlog, "PID=%d ", getpid()); if (logFile) fprintf(logFile, "PID=%d ", getpid()); } #endif if (detail & (_LOG_PID|_LOG_TID|_LOG_TIME)) { fprintf(stdlog, "- "); if (logFile) fprintf(logFile, "- "); } #endif } if (str && *str) { nl = str[strlen(str)-1]=='\n'; FPRINTF(str); } else nl = false; fflush(stdlog); if (logFile) { fflush(logFile); } } void close() { if (logFile) { fclose(logFile); logFile = 0; } } }; static ILogIntercept *logintercept = NULL; jlib_decl ILogIntercept* interceptLog(ILogIntercept *intercept) { ILogIntercept *old=logintercept; logintercept = intercept; return old; } jlib_decl void openLogFile(StringBuffer & resolvedFS, const char *filename, unsigned detail, bool enterQueueMode, bool append) { if(enterQueueMode) queryLogMsgManager()->enterQueueingMode(); Owned<IComponentLogFileCreator> lf = createComponentLogFileCreator(".", 0); lf->setCreateAliasFile(false); lf->setLocal(true); lf->setRolling(false); lf->setAppend(append); lf->setCompleteFilespec(filename);//user specified log filespec lf->setMaxDetail(detail ? detail : DefaultDetail); lf->setMsgFields(MSGFIELD_timeDate | MSGFIELD_msgID | MSGFIELD_process | MSGFIELD_thread | MSGFIELD_code); lf->beginLogging(); resolvedFS.set(lf->queryLogFileSpec()); } jlib_decl void PrintLogDirect(const char *msg) { LOG(MClegacy, unknownJob, "%s", msg); } jlib_decl int PrintLog(const char *fmt, ...) { va_list args; va_start(args, fmt); VALOG(MClegacy, unknownJob, fmt, args); va_end(args); return 0; } jlib_decl void SPrintLog(const char *fmt, ...) { va_list args; va_start(args, fmt); VALOG(MClegacy, unknownJob, fmt, args); va_end(args); } StringBuffer &addFileTimestamp(StringBuffer &fname, bool daily) { time_t tNow; time(&tNow); char timeStamp[32]; #ifdef _WIN32 struct tm *ltNow; ltNow = localtime(&tNow); strftime(timeStamp, 32, daily ? ".%Y_%m_%d" : ".%Y_%m_%d_%H_%M_%S", ltNow); #else struct tm ltNow; localtime_r(&tNow, &ltNow); strftime(timeStamp, 32, daily ? ".%Y_%m_%d" : ".%Y_%m_%d_%H_%M_%S", &ltNow); #endif return fname.append(timeStamp); } #define MAX_TRY_SIZE 0x8000000 // 256 MB jlib_decl void PrintMemoryStatusLog() { #ifdef _WIN32 MEMORYSTATUS mS; GlobalMemoryStatus(&mS); LOG(MCdebugInfo, unknownJob, "Available Physical Memory = %dK", (unsigned)(mS.dwAvailPhys/1024)); #ifdef FRAGMENTATION_CHECK // see if fragmented size32_t sz = MAX_TRY_SIZE; while (sz) { if (sz<mS.dwAvailPhys/4) { void *p=malloc(sz); if (p) { free(p); break; } } sz /= 2; } sz *= 2; if ((sz<MAX_TRY_SIZE)&&(sz<mS.dwAvailPhys/4)) { LOG(MCdebugInfo, unknownJob, "WARNING: Could not allocate block size %d", sz); _HEAPINFO hinfo; int heapstatus; hinfo._pentry = NULL; size32_t max=0; unsigned fragments=0; while( ( heapstatus = _heapwalk( &hinfo ) ) == _HEAPOK ) { if (hinfo._useflag != _USEDENTRY) { if (hinfo._size>max) max = hinfo._size; fragments++; } } LOG(MCdebugInfo, unknownJob, "Largest unused fragment = %d", max); LOG(MCdebugInfo, unknownJob, "Number of fragments = %d", fragments); } #endif #endif } static class _init_jmisc_class { public: ~_init_jmisc_class() { if (logFile) fclose(logFile); } } _init_jmisc; FILE *xfopen(const char *path, const char *mode) { char *s, *e, *p; p = s = strdup(path); e = s+strlen(path); bool alt=false; for (; p<e; p++) { #ifdef _WIN32 if (*p == '/') #else if (*p == '\\') #endif { alt = true; *p = PATHSEPCHAR; } } if (alt) printf("XFOPEN ALTERED FILENAME FROM:%s TO %s\n", path, s); FILE *file = ::fopen(s, mode); free(s); return file; } const char * queryCcLogName() { const char* logFileName = getenv("ECL_CCLOG"); if (!logFileName) { logFileName = "cclog.txt"; } return logFileName; //More does output get redirected here? } StringBuffer& queryCcLogName(const char* wuid, StringBuffer& logname) { if(!wuid || !*wuid) logname.append(queryCcLogName()); else { const char* presetName = getenv("ECL_CCLOG"); if (presetName && *presetName) logname.append(presetName); else logname.append(wuid).trim().append(".cclog.txt"); } return logname; } jlib_decl char* readarg(char*& curptr) { char *cur = curptr; if(cur == NULL || *cur == 0) return NULL; while(*cur == ' ' || *cur == '\t') { cur++; if (!*cur) { curptr = cur; return NULL; } } char quote = 0; if(*cur == '\'' || *cur == '"') { quote = *cur; cur++; } char *ret = cur; if (quote) { while (*cur && *cur!=quote) cur++; } else { do { cur++; } while(*cur && *cur != ' ' && *cur != '\t'); } if(*cur != 0) { *cur = 0; cur++; } curptr = cur; return ret; } #ifdef _WIN32 bool invoke_program(const char *command_line, DWORD &runcode, bool wait, const char *outfile, HANDLE *rethandle, bool throwException, bool newProcessGroup) { runcode = 0; if (rethandle) *rethandle = 0; if(!command_line || !*command_line) return false; STARTUPINFO StartupInfo; SECURITY_ATTRIBUTES security; _clear(security); security.nLength = sizeof(security); security.bInheritHandle = TRUE; _clear(StartupInfo); StartupInfo.cb = sizeof(StartupInfo); HANDLE outh = NULL; if (outfile&&*outfile) { outh = CreateFile(outfile,GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,&security,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL); if (outh == INVALID_HANDLE_VALUE) { ERRLOG("Cannot create file '%s' error code %d",outfile,(int)GetLastError()); return false; } } if (outh) { if (!DuplicateHandle(GetCurrentProcess(),outh,GetCurrentProcess(),&StartupInfo.hStdOutput, 0, TRUE, DUPLICATE_SAME_ACCESS) || !DuplicateHandle(GetCurrentProcess(),outh,GetCurrentProcess(),&StartupInfo.hStdError, 0, TRUE, DUPLICATE_SAME_ACCESS)) { ERRLOG("Execution of \"%s\" failed, DuplicateHandle error = %d",command_line, (int)GetLastError()); CloseHandle(outh); return false; } StartupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE); StartupInfo.dwFlags = STARTF_USESTDHANDLES; CloseHandle(outh); } PROCESS_INFORMATION ProcessInformation; bool ok = CreateProcess(NULL,(char *)command_line,NULL,NULL,TRUE,0,NULL,NULL,&StartupInfo,&ProcessInformation)!=0; if (ok) { if (wait) { WaitForSingleObject(ProcessInformation.hProcess,INFINITE); GetExitCodeProcess(ProcessInformation.hProcess, &runcode); } CloseHandle(ProcessInformation.hThread); if (rethandle) { *rethandle = (HANDLE)ProcessInformation.hProcess; if (wait) CloseHandle(ProcessInformation.hProcess); } else CloseHandle(ProcessInformation.hProcess); } else { int lastError = (int)GetLastError(); // for debugging //print out why create process failed ERRLOG("Execution of \"%s\" failed, error = %d",command_line,lastError); } if (outh) { CloseHandle(StartupInfo.hStdOutput); CloseHandle(StartupInfo.hStdError); } return ok; } bool wait_program(HANDLE handle,DWORD &runcode,bool block) { runcode = (DWORD)-1; if ((handle==NULL)||(handle==(HANDLE)-1)) return true; // actually it failed int ret = WaitForSingleObject(handle,block?INFINITE:0); int err = GetLastError(); if (ret==WAIT_OBJECT_0) { GetExitCodeProcess(handle, &runcode); CloseHandle(handle); return true; } return false; } jlib_decl bool interrupt_program(HANDLE handle, bool stopChildren, int signum) { if (signum==0) return TerminateProcess(handle,1)!=FALSE; ERRLOG("interrupt_program signal %d not supported in windows",signum); return false; } void close_program(HANDLE handle) { CloseHandle(handle); } #else bool invoke_program(const char *command_line, DWORD &runcode, bool wait, const char *outfile, HANDLE *rethandle, bool throwException, bool newProcessGroup) { runcode = 0; if (rethandle) *rethandle = 0; if(!command_line || !*command_line) return false; pid_t pid = fork(); if (pid == 0) { //Force the child process into its own process group, so we can terminate it and its children. if (newProcessGroup) setpgid(0,0); if (outfile&&*outfile) { int outh = open(outfile, O_CREAT|O_WRONLY|O_TRUNC, S_IRUSR|S_IWUSR); if(outh >= 0) { dup2(outh, STDOUT_FILENO); dup2(outh, STDERR_FILENO); close(outh); } else { ERRLOG("invoke_program: could not open %s",outfile); return false; } } int size = 10; char **args; char **argptr = args = (char **) malloc(sizeof(args) * size); char **over = argptr+size; char *cl = strdup(command_line); char *curptr = cl; *argptr = readarg(curptr); while (*argptr != NULL) { argptr++; if (argptr==over) { args = (char **) realloc(args, sizeof(args) * size * 2); argptr = args+size; size *= 2; over = args+size; } *argptr = readarg(curptr); } // JCSMORE - do I not need to free args, if successful exec? if (execvp(*args, args)) { //print out why create process failed int err = errno; ERRLOG("invoke_program(%s) failed with error(%d): %s",command_line,err,strerror(err)); } assertex(0); // don't expect to get here! _exit(0); } else if (pid < 0) { StringBuffer s("fork of \""); s.append(command_line).append("\" failed. fork() returned:"); if (errno == EAGAIN) s.append("EAGAIN"); else if (errno == ENOMEM) s.append("ENOMEM"); else s.append(errno); ERRLOG("%s",s.str()); if(throwException) throw MakeStringExceptionDirect(-1, s.str()); return false; } if (rethandle) *rethandle = (HANDLE)pid; if (wait) { int retv; if (waitpid(pid, &retv, 0) != pid) { ERRLOG("invoke_program(%s): wait failed (%d)",command_line,(int)pid); return false; } if (!WIFEXITED(retv)) //did not exit normally { int err = errno; ERRLOG("invoke_program(%s): failed.",command_line); ERRLOG("The process was killed by signal %d%s.",(int)WTERMSIG(retv),WCOREDUMP(retv)?" - core dumped":""); ERRLOG("Last system error is %s",strerror(err)); } runcode = WEXITSTATUS(retv); } return true; // it did run even if signalled } bool wait_program(HANDLE handle,DWORD &runcode,bool block) { pid_t pid = (pid_t)handle; runcode = (DWORD)-1; if ((int)pid<=0) return true; // actually it failed int retv; pid_t ret = waitpid(pid, &retv, block?0:WNOHANG); if (ret == (pid_t)-1) { ERRLOG("wait_program: wait failed (%d)",errno); return true; // actually it failed but assume finished } else if (ret==0) return false; runcode = WEXITSTATUS(retv); return true; } bool interrupt_program(HANDLE handle, bool stopChildren, int signum) { if (signum == 0) signum = SIGINT; pid_t pid = (pid_t)handle; if ((int)pid<=0) return false; //If we need to also stop child processes then kill the process group (same as the pid) //Note: This will not apply to grand-children started by the children by calling invoke_program() //since they will have a different process group if (stopChildren) pid = -pid; return (kill(pid, signum)==0); } void close_program(HANDLE handle) { // not needed in linux } #endif #ifndef _WIN32 bool CopyFile(const char *file, const char *newfile, bool fail) { struct stat s; if ((fail) && (0 == stat((char *)newfile, &s))) return false; FILE *in=fopen(file,"rb"), *out=fopen(newfile,"wb"); try { if (!in) throw MakeStringException(-1, "failed to open %s for copy",file); if (!out) throw MakeStringException(-1, "failed to create %s",newfile); char b[1024]; while (true) { int c=fread(b,1,sizeof(b),in); if (!c) break; if (!fwrite(b,c,1,out)) throw MakeStringException(-1, "failed to copy file %s to %s",file,newfile); } fclose(in); fclose(out); stat((char *)file, &s); chmod(newfile, s.st_mode); } catch (...) { if (in) fclose(in); if (out) fclose(out); return false; } return true; } #endif //======================================================================================================================== static bool hadAbortSignal = false; static bool handlerInstalled = false; CriticalSection abortCrit; class AbortHandlerInfo : public CInterface { public: ThreadId installer; AbortHandler handler; SimpleAbortHandler shandler; IAbortHandler *ihandler; AbortHandlerInfo(AbortHandler _handler) { handler = _handler; shandler = NULL; ihandler = NULL; installer = GetCurrentThreadId(); } AbortHandlerInfo(SimpleAbortHandler _handler) { handler = NULL; shandler = _handler; ihandler = NULL; installer = GetCurrentThreadId(); } AbortHandlerInfo(IAbortHandler *_ihandler) { handler = NULL; shandler = NULL; ihandler = _ihandler; installer = GetCurrentThreadId(); } bool handle(ahType type) { #ifndef _WIN32 if (installer == GetCurrentThreadId()) #endif { // DBGLOG("handle abort %x", GetCurrentThreadId()); if (handler) return handler(type); else if (shandler) return shandler(); else return ihandler->onAbort(); } #ifndef _WIN32 else return false; #endif } }; CIArrayOf<AbortHandlerInfo> handlers; bool notifyOnAbort(ahType type) { // DBGLOG("notifyOnAbort %x", GetCurrentThreadId()); // CriticalBlock c(abortCrit); You would think that this was needed, but it locks up. // If it needs to be threadsafe, have to clone the list or something bool doExit = false; ForEachItemInRev(idx, handlers) { if (handlers.item(idx).handle(type)) doExit = true; } // DBGLOG("notifyOnAbort returning %d", (int) doExit); return doExit; } #ifdef _WIN32 BOOL WINAPI WindowsAbortHandler ( DWORD dwCtrlType ) { switch( dwCtrlType ) { case CTRL_BREAK_EVENT: // use Ctrl+C or Ctrl+Break to simulate case CTRL_C_EVENT: // SERVICE_CONTROL_STOP in debug mode case CTRL_CLOSE_EVENT: { hadAbortSignal = true; bool doExit = notifyOnAbort(ahInterrupt); return !doExit; } case CTRL_LOGOFF_EVENT: case CTRL_SHUTDOWN_EVENT: hadAbortSignal = true; notifyOnAbort(ahTerminate); return FALSE; } return FALSE; } BOOL WINAPI ModuleExitHandler ( DWORD dwCtrlType ) { switch( dwCtrlType ) { case CTRL_BREAK_EVENT: // use Ctrl+C or Ctrl+Break to simulate case CTRL_C_EVENT: // SERVICE_CONTROL_STOP in debug mode case CTRL_CLOSE_EVENT: case CTRL_LOGOFF_EVENT: case CTRL_SHUTDOWN_EVENT: ExitModuleObjects(); } return FALSE; } #elif defined(__linux__) static void UnixAbortHandler(int signo) { ahType type = ahInterrupt; if (SIGTERM == signo) type = ahTerminate; hadAbortSignal = true; if (handlers.length()==0 || notifyOnAbort(type)) { _exit(0); } } #endif void queryInstallAbortHandler() { if (handlerInstalled) return; #if defined(_WIN32) SetConsoleCtrlHandler( WindowsAbortHandler, TRUE ); #elif defined(__linux__) struct sigaction action; sigemptyset(&action.sa_mask); action.sa_flags = SA_RESTART; action.sa_handler = (void(*)(int))UnixAbortHandler; if (sigaction(SIGINT, &action, NULL) == -1 || sigaction(SIGQUIT, &action, NULL) == -1 || sigaction(SIGTERM, &action, NULL) == -1) { perror("sigaction in queryInstallAbortHandler failed"); } #endif handlerInstalled = true; } void queryUninstallAbortHandler() { if (handlers.ordinality()) return; #if defined(_WIN32) if (handlerInstalled) { SetConsoleCtrlHandler( WindowsAbortHandler, FALSE); handlerInstalled = false; } #else // Don't uninstall - we always want one for the module exit support #endif } MODULE_INIT(INIT_PRIORITY_JMISC2) { #if defined(_WIN32) // NOTE: handlers are called in LIFO order and hence any handler that returns false // (e.g CTRL-C not wanting to abort)) will stop this handler being called also (correctly). SetConsoleCtrlHandler( ModuleExitHandler, TRUE); #elif defined(__linux__) queryInstallAbortHandler(); #endif return true; } void addAbortHandler(AbortHandler handler) { CriticalBlock c(abortCrit); queryInstallAbortHandler(); handlers.append(*new AbortHandlerInfo(handler)); } void addAbortHandler(SimpleAbortHandler handler) { CriticalBlock c(abortCrit); queryInstallAbortHandler(); handlers.append(*new AbortHandlerInfo(handler)); } void addAbortHandler(IAbortHandler & handler) { CriticalBlock c(abortCrit); queryInstallAbortHandler(); handlers.append(*new AbortHandlerInfo(&handler)); } void removeAbortHandler(AbortHandler handler) { CriticalBlock c(abortCrit); ForEachItemInRev(idx, handlers) { if (handlers.item(idx).handler == handler) { handlers.remove(idx); break; } } queryUninstallAbortHandler(); } void removeAbortHandler(SimpleAbortHandler handler) { CriticalBlock c(abortCrit); ForEachItemInRev(idx, handlers) { if (handlers.item(idx).shandler == handler) { handlers.remove(idx); break; } } queryUninstallAbortHandler(); } void removeAbortHandler(IAbortHandler & handler) { CriticalBlock c(abortCrit); ForEachItemInRev(idx, handlers) { if (handlers.item(idx).ihandler == &handler) { handlers.remove(idx); break; } } queryUninstallAbortHandler(); } bool isAborting() { return hadAbortSignal; } void throwAbortException() { throw MakeStringException(JLIBERR_UserAbort, "Operation aborted by user"); } void throwExceptionIfAborting() { if (isAborting()) throwAbortException(); } //======================================================================================================================== StringBuffer & hexdump2string(byte const * in, size32_t inSize, StringBuffer & out) { out.append("["); byte last = 0; unsigned seq = 1; for(unsigned i=0; i<inSize; ++i) { if((i>0) && (in[i]==last)) { ++seq; } else { if(seq>1) { if(seq==2) out.appendf(" %02X", last); else out.appendf("x%u", seq); seq = 1; } out.appendf(" %02X", in[i]); last = in[i]; } } if(seq>1) out.appendf("x%u", seq); out.append(" ]"); return out; } jlib_decl bool getHomeDir(StringBuffer & homepath) { #ifdef _WIN32 const char *home = getenv("APPDATA"); // Not the 'official' way - which changes with every windows version // but should work well enough for us (and avoids sorting out windows include mess) #else const char *home = getenv("HOME"); if (!home) { struct passwd *pw = getpwuid(getuid()); home = pw->pw_dir; } #endif if (!home) return false; homepath.append(home); return true; }
26.048144
155
0.561841
oxhead
4f2f203beeaf2ea35431f800e2d1063f1f769177
3,549
cpp
C++
tests/unit/parallel/segmented_algorithms/partitioned_vector_transform_reduce2.cpp
bremerm31/hpx
a9d22b8eb2e443d2e95991da9b1a621f94d4ebaa
[ "BSL-1.0" ]
1
2019-07-04T10:18:01.000Z
2019-07-04T10:18:01.000Z
tests/unit/parallel/segmented_algorithms/partitioned_vector_transform_reduce2.cpp
bremerm31/hpx
a9d22b8eb2e443d2e95991da9b1a621f94d4ebaa
[ "BSL-1.0" ]
1
2017-07-24T07:16:26.000Z
2017-07-24T08:03:33.000Z
tests/unit/parallel/segmented_algorithms/partitioned_vector_transform_reduce2.cpp
biddisco/hpx
2d244e1e27c6e014189a6cd59c474643b31fad4b
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2014-2017 Hartmut Kaiser // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <hpx/hpx_main.hpp> #include <hpx/include/parallel_for_each.hpp> #include <hpx/include/parallel_transform_reduce.hpp> #include <hpx/include/partitioned_vector_predef.hpp> #include <hpx/util/zip_iterator.hpp> #include <hpx/util/lightweight_test.hpp> #include <iterator> #include <cstddef> #include <vector> /////////////////////////////////////////////////////////////////////////////// struct multiply { template <typename T> typename hpx::util::decay<T>::type operator()( hpx::util::tuple<T, T> const& r) const { using hpx::util::get; return get<0>(r) * get<1>(r); } }; /////////////////////////////////////////////////////////////////////////////// template <typename ExPolicy, typename T> T test_transform_reduce(ExPolicy&& policy, hpx::partitioned_vector<T> const& xvalues, hpx::partitioned_vector<T> const& yvalues) { using hpx::util::make_zip_iterator; return hpx::parallel::transform_reduce(policy, make_zip_iterator(std::begin(xvalues), std::begin(yvalues)), make_zip_iterator(std::end(xvalues), std::end(yvalues)), T(1), std::plus<T>(), multiply()); } template <typename ExPolicy, typename T> hpx::future<T> test_transform_reduce_async(ExPolicy&& policy, hpx::partitioned_vector<T> const& xvalues, hpx::partitioned_vector<T> const& yvalues) { using hpx::util::make_zip_iterator; return hpx::parallel::transform_reduce(policy, make_zip_iterator(std::begin(xvalues), std::begin(yvalues)), make_zip_iterator(std::end(xvalues), std::end(yvalues)), T(1), std::plus<T>(), multiply()); } template <typename T> void transform_reduce_tests(std::size_t num, hpx::partitioned_vector<T> const& xvalues, hpx::partitioned_vector<T> const& yvalues) { HPX_TEST_EQ( test_transform_reduce(hpx::parallel::execution::seq, xvalues, yvalues), T(num + 1)); HPX_TEST_EQ( test_transform_reduce(hpx::parallel::execution::par, xvalues, yvalues), T(num + 1)); HPX_TEST_EQ(test_transform_reduce_async(hpx::parallel::execution::seq( hpx::parallel::execution::task), xvalues, yvalues) .get(), T(num + 1)); HPX_TEST_EQ(test_transform_reduce_async(hpx::parallel::execution::par( hpx::parallel::execution::task), xvalues, yvalues) .get(), T(num + 1)); } template <typename T> void transform_reduce_tests(std::vector<hpx::id_type>& localities) { std::size_t const num = 10007; { hpx::partitioned_vector<T> xvalues(num, T(1)); hpx::partitioned_vector<T> yvalues(num, T(1)); transform_reduce_tests(num, xvalues, yvalues); } { hpx::partitioned_vector<T> xvalues( num, T(1), hpx::container_layout(localities)); hpx::partitioned_vector<T> yvalues( num, T(1), hpx::container_layout(localities)); transform_reduce_tests(num, xvalues, yvalues); } } /////////////////////////////////////////////////////////////////////////////// int main() { std::vector<hpx::id_type> localities = hpx::find_all_localities(); transform_reduce_tests<double>(localities); return hpx::util::report_errors(); }
33.481132
80
0.601578
bremerm31
4f30a899e85dfb149885fb4e0a8f13b621b3a600
852
cpp
C++
src/vehicle.cpp
lucianefalcao/cvrp
a26dd2a33d90a1ecee879f2cb415151dca573778
[ "Apache-2.0" ]
null
null
null
src/vehicle.cpp
lucianefalcao/cvrp
a26dd2a33d90a1ecee879f2cb415151dca573778
[ "Apache-2.0" ]
null
null
null
src/vehicle.cpp
lucianefalcao/cvrp
a26dd2a33d90a1ecee879f2cb415151dca573778
[ "Apache-2.0" ]
null
null
null
#include "../includes/vehicle.h" Vehicle::Vehicle() { this->cost = 0; } void Vehicle::setCapacity(int capacity) { this->capacity = capacity; } int Vehicle::getCapacity() { return capacity; } void Vehicle::addClientToRoute(Client client) { this->route.push_back(client); } void Vehicle::setLoad(int capacity) { this->load = capacity; } int Vehicle::getLoad() { return load; } void Vehicle::calculateLoad(int load) { this->load -= load; } void Vehicle::setCost(int cost) { this->cost = cost; } void Vehicle::addCost(int cost) { this->cost += cost; } int Vehicle::getCost() { return cost; } void Vehicle::setRoute(std::vector<Client> r) { this->route = r; } std::vector<Client> Vehicle::getRoute() { return route; } bool Vehicle::CheckDelivery(int demand) { return (load-demand) >= 0; }
12.716418
45
0.644366
lucianefalcao
4f32c352808735c2bb3a0ad3daabf046333b7db3
4,928
cpp
C++
VC2012Samples/Windows 8 samples/C++/Windows 8 app samples/XAML animation library sample (Windows 8)/C++/Scenario3.xaml.cpp
alonmm/VCSamples
6aff0b4902f5027164d593540fcaa6601a0407c3
[ "MIT" ]
300
2019-05-09T05:32:33.000Z
2022-03-31T20:23:24.000Z
VC2012Samples/Windows 8 samples/C++/Windows 8 app samples/XAML animation library sample (Windows 8)/C++/Scenario3.xaml.cpp
JaydenChou/VCSamples
9e1d4475555b76a17a3568369867f1d7b6cc6126
[ "MIT" ]
9
2016-09-19T18:44:26.000Z
2018-10-26T10:20:05.000Z
VC2012Samples/Windows 8 samples/C++/Windows 8 app samples/XAML animation library sample (Windows 8)/C++/Scenario3.xaml.cpp
JaydenChou/VCSamples
9e1d4475555b76a17a3568369867f1d7b6cc6126
[ "MIT" ]
633
2019-05-08T07:34:12.000Z
2022-03-30T04:38:28.000Z
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* // // Scenario3.xaml.cpp // Implementation of the Scenario3 class // #include "pch.h" #include "Scenario3.xaml.h" using namespace SDKSample::Animation; using namespace Platform; using namespace Windows::Foundation; using namespace Windows::UI; using namespace Windows::UI::Xaml; using namespace Windows::UI::Xaml::Media; using namespace Windows::UI::Xaml::Media::Animation; using namespace Windows::UI::Xaml::Shapes; using namespace Windows::UI::Xaml::Controls; using namespace Windows::UI::Xaml::Navigation; using namespace Windows::UI::ViewManagement; Scenario3::Scenario3() { InitializeComponent(); } // Invoked when this page is about to be displayed in a Frame. void Scenario3::OnNavigatedTo(NavigationEventArgs^ e) { // A pointer back to the main page. This is needed if you want to call methods in MainPage such // as NotifyUser() rootPage = MainPage::Current; // Set the initaial combo box values Scenario3EasingModeSelector->SelectedIndex = 0; Scenario3FunctionSelector->SelectedIndex = 0; } void Scenario3::Scenario3EasingFunctionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e) { // Stop the storyboard Scenario3Storyboard->Stop(); EasingFunctionBase^ easingFunction = nullptr; // Select an easing function based on the user's selection auto selectedFunctionItem = (ComboBoxItem^) Scenario3FunctionSelector->SelectedItem; if (selectedFunctionItem != nullptr) { auto selectedFunction = selectedFunctionItem->Content->ToString(); if(selectedFunction == "BounceEase") { easingFunction = ref new BounceEase(); } else if(selectedFunction == "CircleEase") { easingFunction = ref new CircleEase(); } else if(selectedFunction == "ExponentialEase") { easingFunction = ref new ExponentialEase(); } else if(selectedFunction == "PowerEase") { easingFunction = ref new PowerEase(); } else {} } // If no valid easing function was specified, let the storyboard stay stopped and do not continue if (easingFunction == nullptr) return; auto selectedEasingModeItem = (ComboBoxItem^) Scenario3EasingModeSelector->SelectedItem; // Select an easing mode based on the user's selection, defaulting to EaseIn if no selection was given if (selectedEasingModeItem != nullptr) { auto easingMode = selectedEasingModeItem->Content->ToString(); if(easingMode == "EaseOut") { easingFunction->EasingMode = EasingMode::EaseOut; } if(easingMode == "EaseIn") { easingFunction->EasingMode = EasingMode::EaseIn; } if(easingMode == "EaseInOut") { easingFunction->EasingMode = EasingMode::EaseInOut; } } // Plot a graph of the easing function PlotEasingFunctionGraph(easingFunction, 0.005); // Set the easing functions RectanglePositionAnimation->EasingFunction = easingFunction; GraphPositionMarkerXAnimation->EasingFunction = easingFunction; GraphPositionMarkerYAnimation->EasingFunction = easingFunction; // Start the storyboard Scenario3Storyboard->Begin(); } // Plot an easing function graph void Scenario3::PlotEasingFunctionGraph(EasingFunctionBase^ easingFunction, double samplingInterval) { UISettings^ UserSettings = ref new UISettings(); // Clear the element Graph->Children->Clear(); // Initialize path auto path = ref new Path(); auto pathGeometry = ref new PathGeometry(); auto pathFigure = ref new PathFigure(); // Set starting point Point startPoint; startPoint.X = 0; startPoint.Y = 0; pathFigure->StartPoint = startPoint; auto pathSegmentCollection = ref new PathSegmentCollection(); // Note that an easing function is just like a regular function that operates on doubles. // Here we plot the range of the easing function's output on the y-axis of a graph. for (double i = 0; i < 1; i += samplingInterval) { auto x = i * GraphContainer->Width; auto y = easingFunction->Ease(i) * GraphContainer->Height; auto segment = ref new LineSegment(); Point p; p.X = (float)x; p.Y = (float)y; segment->Point = p; pathSegmentCollection->Append(segment); } // Define the path parameters pathFigure->Segments = pathSegmentCollection; pathGeometry->Figures->Append(pathFigure); path->Data = pathGeometry; path->Stroke = ref new SolidColorBrush(UserSettings->UIElementColor(UIElementType::ButtonText)); path->StrokeThickness = 1; // Append the path to the Canvas Graph->Children->Append(path); }
29.866667
131
0.702516
alonmm
4f34f3ac87b0f794c9af18b9dc1431fb030ec623
146,440
cpp
C++
openmp/runtime/src/kmp_csupport.cpp
kubamracek/llvm-project
f7ff1869cdd487d4baaf009380901e5469d8344d
[ "Apache-2.0" ]
null
null
null
openmp/runtime/src/kmp_csupport.cpp
kubamracek/llvm-project
f7ff1869cdd487d4baaf009380901e5469d8344d
[ "Apache-2.0" ]
null
null
null
openmp/runtime/src/kmp_csupport.cpp
kubamracek/llvm-project
f7ff1869cdd487d4baaf009380901e5469d8344d
[ "Apache-2.0" ]
null
null
null
/* * kmp_csupport.cpp -- kfront linkage support for OpenMP. */ //===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #define __KMP_IMP #include "omp.h" /* extern "C" declarations of user-visible routines */ #include "kmp.h" #include "kmp_error.h" #include "kmp_i18n.h" #include "kmp_itt.h" #include "kmp_lock.h" #include "kmp_stats.h" #include "ompt-specific.h" #define MAX_MESSAGE 512 // flags will be used in future, e.g. to implement openmp_strict library // restrictions /*! * @ingroup STARTUP_SHUTDOWN * @param loc in source location information * @param flags in for future use (currently ignored) * * Initialize the runtime library. This call is optional; if it is not made then * it will be implicitly called by attempts to use other library functions. */ void __kmpc_begin(ident_t *loc, kmp_int32 flags) { // By default __kmpc_begin() is no-op. char *env; if ((env = getenv("KMP_INITIAL_THREAD_BIND")) != NULL && __kmp_str_match_true(env)) { __kmp_middle_initialize(); KC_TRACE(10, ("__kmpc_begin: middle initialization called\n")); } else if (__kmp_ignore_mppbeg() == FALSE) { // By default __kmp_ignore_mppbeg() returns TRUE. __kmp_internal_begin(); KC_TRACE(10, ("__kmpc_begin: called\n")); } } /*! * @ingroup STARTUP_SHUTDOWN * @param loc source location information * * Shutdown the runtime library. This is also optional, and even if called will * not do anything unless the `KMP_IGNORE_MPPEND` environment variable is set to * zero. */ void __kmpc_end(ident_t *loc) { // By default, __kmp_ignore_mppend() returns TRUE which makes __kmpc_end() // call no-op. However, this can be overridden with KMP_IGNORE_MPPEND // environment variable. If KMP_IGNORE_MPPEND is 0, __kmp_ignore_mppend() // returns FALSE and __kmpc_end() will unregister this root (it can cause // library shut down). if (__kmp_ignore_mppend() == FALSE) { KC_TRACE(10, ("__kmpc_end: called\n")); KA_TRACE(30, ("__kmpc_end\n")); __kmp_internal_end_thread(-1); } #if KMP_OS_WINDOWS && OMPT_SUPPORT // Normal exit process on Windows does not allow worker threads of the final // parallel region to finish reporting their events, so shutting down the // library here fixes the issue at least for the cases where __kmpc_end() is // placed properly. if (ompt_enabled.enabled) __kmp_internal_end_library(__kmp_gtid_get_specific()); #endif } /*! @ingroup THREAD_STATES @param loc Source location information. @return The global thread index of the active thread. This function can be called in any context. If the runtime has ony been entered at the outermost level from a single (necessarily non-OpenMP<sup>*</sup>) thread, then the thread number is that which would be returned by omp_get_thread_num() in the outermost active parallel construct. (Or zero if there is no active parallel construct, since the primary thread is necessarily thread zero). If multiple non-OpenMP threads all enter an OpenMP construct then this will be a unique thread identifier among all the threads created by the OpenMP runtime (but the value cannot be defined in terms of OpenMP thread ids returned by omp_get_thread_num()). */ kmp_int32 __kmpc_global_thread_num(ident_t *loc) { kmp_int32 gtid = __kmp_entry_gtid(); KC_TRACE(10, ("__kmpc_global_thread_num: T#%d\n", gtid)); return gtid; } /*! @ingroup THREAD_STATES @param loc Source location information. @return The number of threads under control of the OpenMP<sup>*</sup> runtime This function can be called in any context. It returns the total number of threads under the control of the OpenMP runtime. That is not a number that can be determined by any OpenMP standard calls, since the library may be called from more than one non-OpenMP thread, and this reflects the total over all such calls. Similarly the runtime maintains underlying threads even when they are not active (since the cost of creating and destroying OS threads is high), this call counts all such threads even if they are not waiting for work. */ kmp_int32 __kmpc_global_num_threads(ident_t *loc) { KC_TRACE(10, ("__kmpc_global_num_threads: num_threads = %d\n", __kmp_all_nth)); return TCR_4(__kmp_all_nth); } /*! @ingroup THREAD_STATES @param loc Source location information. @return The thread number of the calling thread in the innermost active parallel construct. */ kmp_int32 __kmpc_bound_thread_num(ident_t *loc) { KC_TRACE(10, ("__kmpc_bound_thread_num: called\n")); return __kmp_tid_from_gtid(__kmp_entry_gtid()); } /*! @ingroup THREAD_STATES @param loc Source location information. @return The number of threads in the innermost active parallel construct. */ kmp_int32 __kmpc_bound_num_threads(ident_t *loc) { KC_TRACE(10, ("__kmpc_bound_num_threads: called\n")); return __kmp_entry_thread()->th.th_team->t.t_nproc; } /*! * @ingroup DEPRECATED * @param loc location description * * This function need not be called. It always returns TRUE. */ kmp_int32 __kmpc_ok_to_fork(ident_t *loc) { #ifndef KMP_DEBUG return TRUE; #else const char *semi2; const char *semi3; int line_no; if (__kmp_par_range == 0) { return TRUE; } semi2 = loc->psource; if (semi2 == NULL) { return TRUE; } semi2 = strchr(semi2, ';'); if (semi2 == NULL) { return TRUE; } semi2 = strchr(semi2 + 1, ';'); if (semi2 == NULL) { return TRUE; } if (__kmp_par_range_filename[0]) { const char *name = semi2 - 1; while ((name > loc->psource) && (*name != '/') && (*name != ';')) { name--; } if ((*name == '/') || (*name == ';')) { name++; } if (strncmp(__kmp_par_range_filename, name, semi2 - name)) { return __kmp_par_range < 0; } } semi3 = strchr(semi2 + 1, ';'); if (__kmp_par_range_routine[0]) { if ((semi3 != NULL) && (semi3 > semi2) && (strncmp(__kmp_par_range_routine, semi2 + 1, semi3 - semi2 - 1))) { return __kmp_par_range < 0; } } if (KMP_SSCANF(semi3 + 1, "%d", &line_no) == 1) { if ((line_no >= __kmp_par_range_lb) && (line_no <= __kmp_par_range_ub)) { return __kmp_par_range > 0; } return __kmp_par_range < 0; } return TRUE; #endif /* KMP_DEBUG */ } /*! @ingroup THREAD_STATES @param loc Source location information. @return 1 if this thread is executing inside an active parallel region, zero if not. */ kmp_int32 __kmpc_in_parallel(ident_t *loc) { return __kmp_entry_thread()->th.th_root->r.r_active; } /*! @ingroup PARALLEL @param loc source location information @param global_tid global thread number @param num_threads number of threads requested for this parallel construct Set the number of threads to be used by the next fork spawned by this thread. This call is only required if the parallel construct has a `num_threads` clause. */ void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid, kmp_int32 num_threads) { KA_TRACE(20, ("__kmpc_push_num_threads: enter T#%d num_threads=%d\n", global_tid, num_threads)); __kmp_assert_valid_gtid(global_tid); __kmp_push_num_threads(loc, global_tid, num_threads); } void __kmpc_pop_num_threads(ident_t *loc, kmp_int32 global_tid) { KA_TRACE(20, ("__kmpc_pop_num_threads: enter\n")); /* the num_threads are automatically popped */ } void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid, kmp_int32 proc_bind) { KA_TRACE(20, ("__kmpc_push_proc_bind: enter T#%d proc_bind=%d\n", global_tid, proc_bind)); __kmp_assert_valid_gtid(global_tid); __kmp_push_proc_bind(loc, global_tid, (kmp_proc_bind_t)proc_bind); } /*! @ingroup PARALLEL @param loc source location information @param argc total number of arguments in the ellipsis @param microtask pointer to callback routine consisting of outlined parallel construct @param ... pointers to shared variables that aren't global Do the actual fork and call the microtask in the relevant number of threads. */ void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro microtask, ...) { int gtid = __kmp_entry_gtid(); #if (KMP_STATS_ENABLED) // If we were in a serial region, then stop the serial timer, record // the event, and start parallel region timer stats_state_e previous_state = KMP_GET_THREAD_STATE(); if (previous_state == stats_state_e::SERIAL_REGION) { KMP_EXCHANGE_PARTITIONED_TIMER(OMP_parallel_overhead); } else { KMP_PUSH_PARTITIONED_TIMER(OMP_parallel_overhead); } int inParallel = __kmpc_in_parallel(loc); if (inParallel) { KMP_COUNT_BLOCK(OMP_NESTED_PARALLEL); } else { KMP_COUNT_BLOCK(OMP_PARALLEL); } #endif // maybe to save thr_state is enough here { va_list ap; va_start(ap, microtask); #if OMPT_SUPPORT ompt_frame_t *ompt_frame; if (ompt_enabled.enabled) { kmp_info_t *master_th = __kmp_threads[gtid]; kmp_team_t *parent_team = master_th->th.th_team; ompt_lw_taskteam_t *lwt = parent_team->t.ompt_serialized_team_info; if (lwt) ompt_frame = &(lwt->ompt_task_info.frame); else { int tid = __kmp_tid_from_gtid(gtid); ompt_frame = &( parent_team->t.t_implicit_task_taskdata[tid].ompt_task_info.frame); } ompt_frame->enter_frame.ptr = OMPT_GET_FRAME_ADDRESS(0); } OMPT_STORE_RETURN_ADDRESS(gtid); #endif #if INCLUDE_SSC_MARKS SSC_MARK_FORKING(); #endif __kmp_fork_call(loc, gtid, fork_context_intel, argc, VOLATILE_CAST(microtask_t) microtask, // "wrapped" task VOLATILE_CAST(launch_t) __kmp_invoke_task_func, kmp_va_addr_of(ap)); #if INCLUDE_SSC_MARKS SSC_MARK_JOINING(); #endif __kmp_join_call(loc, gtid #if OMPT_SUPPORT , fork_context_intel #endif ); va_end(ap); } #if KMP_STATS_ENABLED if (previous_state == stats_state_e::SERIAL_REGION) { KMP_EXCHANGE_PARTITIONED_TIMER(OMP_serial); KMP_SET_THREAD_STATE(previous_state); } else { KMP_POP_PARTITIONED_TIMER(); } #endif // KMP_STATS_ENABLED } /*! @ingroup PARALLEL @param loc source location information @param global_tid global thread number @param num_teams number of teams requested for the teams construct @param num_threads number of threads per team requested for the teams construct Set the number of teams to be used by the teams construct. This call is only required if the teams construct has a `num_teams` clause or a `thread_limit` clause (or both). */ void __kmpc_push_num_teams(ident_t *loc, kmp_int32 global_tid, kmp_int32 num_teams, kmp_int32 num_threads) { KA_TRACE(20, ("__kmpc_push_num_teams: enter T#%d num_teams=%d num_threads=%d\n", global_tid, num_teams, num_threads)); __kmp_assert_valid_gtid(global_tid); __kmp_push_num_teams(loc, global_tid, num_teams, num_threads); } /*! @ingroup PARALLEL @param loc source location information @param global_tid global thread number @param num_teams_lo lower bound on number of teams requested for the teams construct @param num_teams_up upper bound on number of teams requested for the teams construct @param num_threads number of threads per team requested for the teams construct Set the number of teams to be used by the teams construct. The number of initial teams cretaed will be greater than or equal to the lower bound and less than or equal to the upper bound. This call is only required if the teams construct has a `num_teams` clause or a `thread_limit` clause (or both). */ void __kmpc_push_num_teams_51(ident_t *loc, kmp_int32 global_tid, kmp_int32 num_teams_lb, kmp_int32 num_teams_ub, kmp_int32 num_threads) { KA_TRACE(20, ("__kmpc_push_num_teams_51: enter T#%d num_teams_lb=%d" " num_teams_ub=%d num_threads=%d\n", global_tid, num_teams_lb, num_teams_ub, num_threads)); __kmp_assert_valid_gtid(global_tid); __kmp_push_num_teams_51(loc, global_tid, num_teams_lb, num_teams_ub, num_threads); } /*! @ingroup PARALLEL @param loc source location information @param argc total number of arguments in the ellipsis @param microtask pointer to callback routine consisting of outlined teams construct @param ... pointers to shared variables that aren't global Do the actual fork and call the microtask in the relevant number of threads. */ void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro microtask, ...) { int gtid = __kmp_entry_gtid(); kmp_info_t *this_thr = __kmp_threads[gtid]; va_list ap; va_start(ap, microtask); #if KMP_STATS_ENABLED KMP_COUNT_BLOCK(OMP_TEAMS); stats_state_e previous_state = KMP_GET_THREAD_STATE(); if (previous_state == stats_state_e::SERIAL_REGION) { KMP_EXCHANGE_PARTITIONED_TIMER(OMP_teams_overhead); } else { KMP_PUSH_PARTITIONED_TIMER(OMP_teams_overhead); } #endif // remember teams entry point and nesting level this_thr->th.th_teams_microtask = microtask; this_thr->th.th_teams_level = this_thr->th.th_team->t.t_level; // AC: can be >0 on host #if OMPT_SUPPORT kmp_team_t *parent_team = this_thr->th.th_team; int tid = __kmp_tid_from_gtid(gtid); if (ompt_enabled.enabled) { parent_team->t.t_implicit_task_taskdata[tid] .ompt_task_info.frame.enter_frame.ptr = OMPT_GET_FRAME_ADDRESS(0); } OMPT_STORE_RETURN_ADDRESS(gtid); #endif // check if __kmpc_push_num_teams called, set default number of teams // otherwise if (this_thr->th.th_teams_size.nteams == 0) { __kmp_push_num_teams(loc, gtid, 0, 0); } KMP_DEBUG_ASSERT(this_thr->th.th_set_nproc >= 1); KMP_DEBUG_ASSERT(this_thr->th.th_teams_size.nteams >= 1); KMP_DEBUG_ASSERT(this_thr->th.th_teams_size.nth >= 1); __kmp_fork_call( loc, gtid, fork_context_intel, argc, VOLATILE_CAST(microtask_t) __kmp_teams_master, // "wrapped" task VOLATILE_CAST(launch_t) __kmp_invoke_teams_master, kmp_va_addr_of(ap)); __kmp_join_call(loc, gtid #if OMPT_SUPPORT , fork_context_intel #endif ); // Pop current CG root off list KMP_DEBUG_ASSERT(this_thr->th.th_cg_roots); kmp_cg_root_t *tmp = this_thr->th.th_cg_roots; this_thr->th.th_cg_roots = tmp->up; KA_TRACE(100, ("__kmpc_fork_teams: Thread %p popping node %p and moving up" " to node %p. cg_nthreads was %d\n", this_thr, tmp, this_thr->th.th_cg_roots, tmp->cg_nthreads)); KMP_DEBUG_ASSERT(tmp->cg_nthreads); int i = tmp->cg_nthreads--; if (i == 1) { // check is we are the last thread in CG (not always the case) __kmp_free(tmp); } // Restore current task's thread_limit from CG root KMP_DEBUG_ASSERT(this_thr->th.th_cg_roots); this_thr->th.th_current_task->td_icvs.thread_limit = this_thr->th.th_cg_roots->cg_thread_limit; this_thr->th.th_teams_microtask = NULL; this_thr->th.th_teams_level = 0; *(kmp_int64 *)(&this_thr->th.th_teams_size) = 0L; va_end(ap); #if KMP_STATS_ENABLED if (previous_state == stats_state_e::SERIAL_REGION) { KMP_EXCHANGE_PARTITIONED_TIMER(OMP_serial); KMP_SET_THREAD_STATE(previous_state); } else { KMP_POP_PARTITIONED_TIMER(); } #endif // KMP_STATS_ENABLED } // I don't think this function should ever have been exported. // The __kmpc_ prefix was misapplied. I'm fairly certain that no generated // openmp code ever called it, but it's been exported from the RTL for so // long that I'm afraid to remove the definition. int __kmpc_invoke_task_func(int gtid) { return __kmp_invoke_task_func(gtid); } /*! @ingroup PARALLEL @param loc source location information @param global_tid global thread number Enter a serialized parallel construct. This interface is used to handle a conditional parallel region, like this, @code #pragma omp parallel if (condition) @endcode when the condition is false. */ void __kmpc_serialized_parallel(ident_t *loc, kmp_int32 global_tid) { // The implementation is now in kmp_runtime.cpp so that it can share static // functions with kmp_fork_call since the tasks to be done are similar in // each case. __kmp_assert_valid_gtid(global_tid); #if OMPT_SUPPORT OMPT_STORE_RETURN_ADDRESS(global_tid); #endif __kmp_serialized_parallel(loc, global_tid); } /*! @ingroup PARALLEL @param loc source location information @param global_tid global thread number Leave a serialized parallel construct. */ void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32 global_tid) { kmp_internal_control_t *top; kmp_info_t *this_thr; kmp_team_t *serial_team; KC_TRACE(10, ("__kmpc_end_serialized_parallel: called by T#%d\n", global_tid)); /* skip all this code for autopar serialized loops since it results in unacceptable overhead */ if (loc != NULL && (loc->flags & KMP_IDENT_AUTOPAR)) return; // Not autopar code __kmp_assert_valid_gtid(global_tid); if (!TCR_4(__kmp_init_parallel)) __kmp_parallel_initialize(); __kmp_resume_if_soft_paused(); this_thr = __kmp_threads[global_tid]; serial_team = this_thr->th.th_serial_team; kmp_task_team_t *task_team = this_thr->th.th_task_team; // we need to wait for the proxy tasks before finishing the thread if (task_team != NULL && task_team->tt.tt_found_proxy_tasks) __kmp_task_team_wait(this_thr, serial_team USE_ITT_BUILD_ARG(NULL)); KMP_MB(); KMP_DEBUG_ASSERT(serial_team); KMP_ASSERT(serial_team->t.t_serialized); KMP_DEBUG_ASSERT(this_thr->th.th_team == serial_team); KMP_DEBUG_ASSERT(serial_team != this_thr->th.th_root->r.r_root_team); KMP_DEBUG_ASSERT(serial_team->t.t_threads); KMP_DEBUG_ASSERT(serial_team->t.t_threads[0] == this_thr); #if OMPT_SUPPORT if (ompt_enabled.enabled && this_thr->th.ompt_thread_info.state != ompt_state_overhead) { OMPT_CUR_TASK_INFO(this_thr)->frame.exit_frame = ompt_data_none; if (ompt_enabled.ompt_callback_implicit_task) { ompt_callbacks.ompt_callback(ompt_callback_implicit_task)( ompt_scope_end, NULL, OMPT_CUR_TASK_DATA(this_thr), 1, OMPT_CUR_TASK_INFO(this_thr)->thread_num, ompt_task_implicit); } // reset clear the task id only after unlinking the task ompt_data_t *parent_task_data; __ompt_get_task_info_internal(1, NULL, &parent_task_data, NULL, NULL, NULL); if (ompt_enabled.ompt_callback_parallel_end) { ompt_callbacks.ompt_callback(ompt_callback_parallel_end)( &(serial_team->t.ompt_team_info.parallel_data), parent_task_data, ompt_parallel_invoker_program | ompt_parallel_team, OMPT_LOAD_RETURN_ADDRESS(global_tid)); } __ompt_lw_taskteam_unlink(this_thr); this_thr->th.ompt_thread_info.state = ompt_state_overhead; } #endif /* If necessary, pop the internal control stack values and replace the team * values */ top = serial_team->t.t_control_stack_top; if (top && top->serial_nesting_level == serial_team->t.t_serialized) { copy_icvs(&serial_team->t.t_threads[0]->th.th_current_task->td_icvs, top); serial_team->t.t_control_stack_top = top->next; __kmp_free(top); } // if( serial_team -> t.t_serialized > 1 ) serial_team->t.t_level--; /* pop dispatch buffers stack */ KMP_DEBUG_ASSERT(serial_team->t.t_dispatch->th_disp_buffer); { dispatch_private_info_t *disp_buffer = serial_team->t.t_dispatch->th_disp_buffer; serial_team->t.t_dispatch->th_disp_buffer = serial_team->t.t_dispatch->th_disp_buffer->next; __kmp_free(disp_buffer); } this_thr->th.th_def_allocator = serial_team->t.t_def_allocator; // restore --serial_team->t.t_serialized; if (serial_team->t.t_serialized == 0) { /* return to the parallel section */ #if KMP_ARCH_X86 || KMP_ARCH_X86_64 if (__kmp_inherit_fp_control && serial_team->t.t_fp_control_saved) { __kmp_clear_x87_fpu_status_word(); __kmp_load_x87_fpu_control_word(&serial_team->t.t_x87_fpu_control_word); __kmp_load_mxcsr(&serial_team->t.t_mxcsr); } #endif /* KMP_ARCH_X86 || KMP_ARCH_X86_64 */ this_thr->th.th_team = serial_team->t.t_parent; this_thr->th.th_info.ds.ds_tid = serial_team->t.t_master_tid; /* restore values cached in the thread */ this_thr->th.th_team_nproc = serial_team->t.t_parent->t.t_nproc; /* JPH */ this_thr->th.th_team_master = serial_team->t.t_parent->t.t_threads[0]; /* JPH */ this_thr->th.th_team_serialized = this_thr->th.th_team->t.t_serialized; /* TODO the below shouldn't need to be adjusted for serialized teams */ this_thr->th.th_dispatch = &this_thr->th.th_team->t.t_dispatch[serial_team->t.t_master_tid]; __kmp_pop_current_task_from_thread(this_thr); KMP_ASSERT(this_thr->th.th_current_task->td_flags.executing == 0); this_thr->th.th_current_task->td_flags.executing = 1; if (__kmp_tasking_mode != tskm_immediate_exec) { // Copy the task team from the new child / old parent team to the thread. this_thr->th.th_task_team = this_thr->th.th_team->t.t_task_team[this_thr->th.th_task_state]; KA_TRACE(20, ("__kmpc_end_serialized_parallel: T#%d restoring task_team %p / " "team %p\n", global_tid, this_thr->th.th_task_team, this_thr->th.th_team)); } } else { if (__kmp_tasking_mode != tskm_immediate_exec) { KA_TRACE(20, ("__kmpc_end_serialized_parallel: T#%d decreasing nesting " "depth of serial team %p to %d\n", global_tid, serial_team, serial_team->t.t_serialized)); } } if (__kmp_env_consistency_check) __kmp_pop_parallel(global_tid, NULL); #if OMPT_SUPPORT if (ompt_enabled.enabled) this_thr->th.ompt_thread_info.state = ((this_thr->th.th_team_serialized) ? ompt_state_work_serial : ompt_state_work_parallel); #endif } /*! @ingroup SYNCHRONIZATION @param loc source location information. Execute <tt>flush</tt>. This is implemented as a full memory fence. (Though depending on the memory ordering convention obeyed by the compiler even that may not be necessary). */ void __kmpc_flush(ident_t *loc) { KC_TRACE(10, ("__kmpc_flush: called\n")); /* need explicit __mf() here since use volatile instead in library */ KMP_MB(); /* Flush all pending memory write invalidates. */ #if (KMP_ARCH_X86 || KMP_ARCH_X86_64) #if KMP_MIC // fence-style instructions do not exist, but lock; xaddl $0,(%rsp) can be used. // We shouldn't need it, though, since the ABI rules require that // * If the compiler generates NGO stores it also generates the fence // * If users hand-code NGO stores they should insert the fence // therefore no incomplete unordered stores should be visible. #else // C74404 // This is to address non-temporal store instructions (sfence needed). // The clflush instruction is addressed either (mfence needed). // Probably the non-temporal load monvtdqa instruction should also be // addressed. // mfence is a SSE2 instruction. Do not execute it if CPU is not SSE2. if (!__kmp_cpuinfo.initialized) { __kmp_query_cpuid(&__kmp_cpuinfo); } if (!__kmp_cpuinfo.sse2) { // CPU cannot execute SSE2 instructions. } else { #if KMP_COMPILER_ICC _mm_mfence(); #elif KMP_COMPILER_MSVC MemoryBarrier(); #else __sync_synchronize(); #endif // KMP_COMPILER_ICC } #endif // KMP_MIC #elif (KMP_ARCH_ARM || KMP_ARCH_AARCH64 || KMP_ARCH_MIPS || KMP_ARCH_MIPS64 || \ KMP_ARCH_RISCV64) // Nothing to see here move along #elif KMP_ARCH_PPC64 // Nothing needed here (we have a real MB above). #else #error Unknown or unsupported architecture #endif #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.ompt_callback_flush) { ompt_callbacks.ompt_callback(ompt_callback_flush)( __ompt_get_thread_data_internal(), OMPT_GET_RETURN_ADDRESS(0)); } #endif } /* -------------------------------------------------------------------------- */ /*! @ingroup SYNCHRONIZATION @param loc source location information @param global_tid thread id. Execute a barrier. */ void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid) { KMP_COUNT_BLOCK(OMP_BARRIER); KC_TRACE(10, ("__kmpc_barrier: called T#%d\n", global_tid)); __kmp_assert_valid_gtid(global_tid); if (!TCR_4(__kmp_init_parallel)) __kmp_parallel_initialize(); __kmp_resume_if_soft_paused(); if (__kmp_env_consistency_check) { if (loc == 0) { KMP_WARNING(ConstructIdentInvalid); // ??? What does it mean for the user? } __kmp_check_barrier(global_tid, ct_barrier, loc); } #if OMPT_SUPPORT ompt_frame_t *ompt_frame; if (ompt_enabled.enabled) { __ompt_get_task_info_internal(0, NULL, NULL, &ompt_frame, NULL, NULL); if (ompt_frame->enter_frame.ptr == NULL) ompt_frame->enter_frame.ptr = OMPT_GET_FRAME_ADDRESS(0); } OMPT_STORE_RETURN_ADDRESS(global_tid); #endif __kmp_threads[global_tid]->th.th_ident = loc; // TODO: explicit barrier_wait_id: // this function is called when 'barrier' directive is present or // implicit barrier at the end of a worksharing construct. // 1) better to add a per-thread barrier counter to a thread data structure // 2) set to 0 when a new team is created // 4) no sync is required __kmp_barrier(bs_plain_barrier, global_tid, FALSE, 0, NULL, NULL); #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.enabled) { ompt_frame->enter_frame = ompt_data_none; } #endif } /* The BARRIER for a MASTER section is always explicit */ /*! @ingroup WORK_SHARING @param loc source location information. @param global_tid global thread number . @return 1 if this thread should execute the <tt>master</tt> block, 0 otherwise. */ kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid) { int status = 0; KC_TRACE(10, ("__kmpc_master: called T#%d\n", global_tid)); __kmp_assert_valid_gtid(global_tid); if (!TCR_4(__kmp_init_parallel)) __kmp_parallel_initialize(); __kmp_resume_if_soft_paused(); if (KMP_MASTER_GTID(global_tid)) { KMP_COUNT_BLOCK(OMP_MASTER); KMP_PUSH_PARTITIONED_TIMER(OMP_master); status = 1; } #if OMPT_SUPPORT && OMPT_OPTIONAL if (status) { if (ompt_enabled.ompt_callback_masked) { kmp_info_t *this_thr = __kmp_threads[global_tid]; kmp_team_t *team = this_thr->th.th_team; int tid = __kmp_tid_from_gtid(global_tid); ompt_callbacks.ompt_callback(ompt_callback_masked)( ompt_scope_begin, &(team->t.ompt_team_info.parallel_data), &(team->t.t_implicit_task_taskdata[tid].ompt_task_info.task_data), OMPT_GET_RETURN_ADDRESS(0)); } } #endif if (__kmp_env_consistency_check) { #if KMP_USE_DYNAMIC_LOCK if (status) __kmp_push_sync(global_tid, ct_master, loc, NULL, 0); else __kmp_check_sync(global_tid, ct_master, loc, NULL, 0); #else if (status) __kmp_push_sync(global_tid, ct_master, loc, NULL); else __kmp_check_sync(global_tid, ct_master, loc, NULL); #endif } return status; } /*! @ingroup WORK_SHARING @param loc source location information. @param global_tid global thread number . Mark the end of a <tt>master</tt> region. This should only be called by the thread that executes the <tt>master</tt> region. */ void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid) { KC_TRACE(10, ("__kmpc_end_master: called T#%d\n", global_tid)); __kmp_assert_valid_gtid(global_tid); KMP_DEBUG_ASSERT(KMP_MASTER_GTID(global_tid)); KMP_POP_PARTITIONED_TIMER(); #if OMPT_SUPPORT && OMPT_OPTIONAL kmp_info_t *this_thr = __kmp_threads[global_tid]; kmp_team_t *team = this_thr->th.th_team; if (ompt_enabled.ompt_callback_masked) { int tid = __kmp_tid_from_gtid(global_tid); ompt_callbacks.ompt_callback(ompt_callback_masked)( ompt_scope_end, &(team->t.ompt_team_info.parallel_data), &(team->t.t_implicit_task_taskdata[tid].ompt_task_info.task_data), OMPT_GET_RETURN_ADDRESS(0)); } #endif if (__kmp_env_consistency_check) { if (KMP_MASTER_GTID(global_tid)) __kmp_pop_sync(global_tid, ct_master, loc); } } /*! @ingroup WORK_SHARING @param loc source location information. @param global_tid global thread number. @param filter result of evaluating filter clause on thread global_tid, or zero if no filter clause present @return 1 if this thread should execute the <tt>masked</tt> block, 0 otherwise. */ kmp_int32 __kmpc_masked(ident_t *loc, kmp_int32 global_tid, kmp_int32 filter) { int status = 0; int tid; KC_TRACE(10, ("__kmpc_masked: called T#%d\n", global_tid)); __kmp_assert_valid_gtid(global_tid); if (!TCR_4(__kmp_init_parallel)) __kmp_parallel_initialize(); __kmp_resume_if_soft_paused(); tid = __kmp_tid_from_gtid(global_tid); if (tid == filter) { KMP_COUNT_BLOCK(OMP_MASKED); KMP_PUSH_PARTITIONED_TIMER(OMP_masked); status = 1; } #if OMPT_SUPPORT && OMPT_OPTIONAL if (status) { if (ompt_enabled.ompt_callback_masked) { kmp_info_t *this_thr = __kmp_threads[global_tid]; kmp_team_t *team = this_thr->th.th_team; ompt_callbacks.ompt_callback(ompt_callback_masked)( ompt_scope_begin, &(team->t.ompt_team_info.parallel_data), &(team->t.t_implicit_task_taskdata[tid].ompt_task_info.task_data), OMPT_GET_RETURN_ADDRESS(0)); } } #endif if (__kmp_env_consistency_check) { #if KMP_USE_DYNAMIC_LOCK if (status) __kmp_push_sync(global_tid, ct_masked, loc, NULL, 0); else __kmp_check_sync(global_tid, ct_masked, loc, NULL, 0); #else if (status) __kmp_push_sync(global_tid, ct_masked, loc, NULL); else __kmp_check_sync(global_tid, ct_masked, loc, NULL); #endif } return status; } /*! @ingroup WORK_SHARING @param loc source location information. @param global_tid global thread number . Mark the end of a <tt>masked</tt> region. This should only be called by the thread that executes the <tt>masked</tt> region. */ void __kmpc_end_masked(ident_t *loc, kmp_int32 global_tid) { KC_TRACE(10, ("__kmpc_end_masked: called T#%d\n", global_tid)); __kmp_assert_valid_gtid(global_tid); KMP_POP_PARTITIONED_TIMER(); #if OMPT_SUPPORT && OMPT_OPTIONAL kmp_info_t *this_thr = __kmp_threads[global_tid]; kmp_team_t *team = this_thr->th.th_team; if (ompt_enabled.ompt_callback_masked) { int tid = __kmp_tid_from_gtid(global_tid); ompt_callbacks.ompt_callback(ompt_callback_masked)( ompt_scope_end, &(team->t.ompt_team_info.parallel_data), &(team->t.t_implicit_task_taskdata[tid].ompt_task_info.task_data), OMPT_GET_RETURN_ADDRESS(0)); } #endif if (__kmp_env_consistency_check) { __kmp_pop_sync(global_tid, ct_masked, loc); } } /*! @ingroup WORK_SHARING @param loc source location information. @param gtid global thread number. Start execution of an <tt>ordered</tt> construct. */ void __kmpc_ordered(ident_t *loc, kmp_int32 gtid) { int cid = 0; kmp_info_t *th; KMP_DEBUG_ASSERT(__kmp_init_serial); KC_TRACE(10, ("__kmpc_ordered: called T#%d\n", gtid)); __kmp_assert_valid_gtid(gtid); if (!TCR_4(__kmp_init_parallel)) __kmp_parallel_initialize(); __kmp_resume_if_soft_paused(); #if USE_ITT_BUILD __kmp_itt_ordered_prep(gtid); // TODO: ordered_wait_id #endif /* USE_ITT_BUILD */ th = __kmp_threads[gtid]; #if OMPT_SUPPORT && OMPT_OPTIONAL kmp_team_t *team; ompt_wait_id_t lck; void *codeptr_ra; OMPT_STORE_RETURN_ADDRESS(gtid); if (ompt_enabled.enabled) { team = __kmp_team_from_gtid(gtid); lck = (ompt_wait_id_t)(uintptr_t)&team->t.t_ordered.dt.t_value; /* OMPT state update */ th->th.ompt_thread_info.wait_id = lck; th->th.ompt_thread_info.state = ompt_state_wait_ordered; /* OMPT event callback */ codeptr_ra = OMPT_LOAD_RETURN_ADDRESS(gtid); if (ompt_enabled.ompt_callback_mutex_acquire) { ompt_callbacks.ompt_callback(ompt_callback_mutex_acquire)( ompt_mutex_ordered, omp_lock_hint_none, kmp_mutex_impl_spin, lck, codeptr_ra); } } #endif if (th->th.th_dispatch->th_deo_fcn != 0) (*th->th.th_dispatch->th_deo_fcn)(&gtid, &cid, loc); else __kmp_parallel_deo(&gtid, &cid, loc); #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.enabled) { /* OMPT state update */ th->th.ompt_thread_info.state = ompt_state_work_parallel; th->th.ompt_thread_info.wait_id = 0; /* OMPT event callback */ if (ompt_enabled.ompt_callback_mutex_acquired) { ompt_callbacks.ompt_callback(ompt_callback_mutex_acquired)( ompt_mutex_ordered, (ompt_wait_id_t)(uintptr_t)lck, codeptr_ra); } } #endif #if USE_ITT_BUILD __kmp_itt_ordered_start(gtid); #endif /* USE_ITT_BUILD */ } /*! @ingroup WORK_SHARING @param loc source location information. @param gtid global thread number. End execution of an <tt>ordered</tt> construct. */ void __kmpc_end_ordered(ident_t *loc, kmp_int32 gtid) { int cid = 0; kmp_info_t *th; KC_TRACE(10, ("__kmpc_end_ordered: called T#%d\n", gtid)); __kmp_assert_valid_gtid(gtid); #if USE_ITT_BUILD __kmp_itt_ordered_end(gtid); // TODO: ordered_wait_id #endif /* USE_ITT_BUILD */ th = __kmp_threads[gtid]; if (th->th.th_dispatch->th_dxo_fcn != 0) (*th->th.th_dispatch->th_dxo_fcn)(&gtid, &cid, loc); else __kmp_parallel_dxo(&gtid, &cid, loc); #if OMPT_SUPPORT && OMPT_OPTIONAL OMPT_STORE_RETURN_ADDRESS(gtid); if (ompt_enabled.ompt_callback_mutex_released) { ompt_callbacks.ompt_callback(ompt_callback_mutex_released)( ompt_mutex_ordered, (ompt_wait_id_t)(uintptr_t)&__kmp_team_from_gtid(gtid) ->t.t_ordered.dt.t_value, OMPT_LOAD_RETURN_ADDRESS(gtid)); } #endif } #if KMP_USE_DYNAMIC_LOCK static __forceinline void __kmp_init_indirect_csptr(kmp_critical_name *crit, ident_t const *loc, kmp_int32 gtid, kmp_indirect_locktag_t tag) { // Pointer to the allocated indirect lock is written to crit, while indexing // is ignored. void *idx; kmp_indirect_lock_t **lck; lck = (kmp_indirect_lock_t **)crit; kmp_indirect_lock_t *ilk = __kmp_allocate_indirect_lock(&idx, gtid, tag); KMP_I_LOCK_FUNC(ilk, init)(ilk->lock); KMP_SET_I_LOCK_LOCATION(ilk, loc); KMP_SET_I_LOCK_FLAGS(ilk, kmp_lf_critical_section); KA_TRACE(20, ("__kmp_init_indirect_csptr: initialized indirect lock #%d\n", tag)); #if USE_ITT_BUILD __kmp_itt_critical_creating(ilk->lock, loc); #endif int status = KMP_COMPARE_AND_STORE_PTR(lck, nullptr, ilk); if (status == 0) { #if USE_ITT_BUILD __kmp_itt_critical_destroyed(ilk->lock); #endif // We don't really need to destroy the unclaimed lock here since it will be // cleaned up at program exit. // KMP_D_LOCK_FUNC(&idx, destroy)((kmp_dyna_lock_t *)&idx); } KMP_DEBUG_ASSERT(*lck != NULL); } // Fast-path acquire tas lock #define KMP_ACQUIRE_TAS_LOCK(lock, gtid) \ { \ kmp_tas_lock_t *l = (kmp_tas_lock_t *)lock; \ kmp_int32 tas_free = KMP_LOCK_FREE(tas); \ kmp_int32 tas_busy = KMP_LOCK_BUSY(gtid + 1, tas); \ if (KMP_ATOMIC_LD_RLX(&l->lk.poll) != tas_free || \ !__kmp_atomic_compare_store_acq(&l->lk.poll, tas_free, tas_busy)) { \ kmp_uint32 spins; \ KMP_FSYNC_PREPARE(l); \ KMP_INIT_YIELD(spins); \ kmp_backoff_t backoff = __kmp_spin_backoff_params; \ do { \ if (TCR_4(__kmp_nth) > \ (__kmp_avail_proc ? __kmp_avail_proc : __kmp_xproc)) { \ KMP_YIELD(TRUE); \ } else { \ KMP_YIELD_SPIN(spins); \ } \ __kmp_spin_backoff(&backoff); \ } while ( \ KMP_ATOMIC_LD_RLX(&l->lk.poll) != tas_free || \ !__kmp_atomic_compare_store_acq(&l->lk.poll, tas_free, tas_busy)); \ } \ KMP_FSYNC_ACQUIRED(l); \ } // Fast-path test tas lock #define KMP_TEST_TAS_LOCK(lock, gtid, rc) \ { \ kmp_tas_lock_t *l = (kmp_tas_lock_t *)lock; \ kmp_int32 tas_free = KMP_LOCK_FREE(tas); \ kmp_int32 tas_busy = KMP_LOCK_BUSY(gtid + 1, tas); \ rc = KMP_ATOMIC_LD_RLX(&l->lk.poll) == tas_free && \ __kmp_atomic_compare_store_acq(&l->lk.poll, tas_free, tas_busy); \ } // Fast-path release tas lock #define KMP_RELEASE_TAS_LOCK(lock, gtid) \ { KMP_ATOMIC_ST_REL(&((kmp_tas_lock_t *)lock)->lk.poll, KMP_LOCK_FREE(tas)); } #if KMP_USE_FUTEX #include <sys/syscall.h> #include <unistd.h> #ifndef FUTEX_WAIT #define FUTEX_WAIT 0 #endif #ifndef FUTEX_WAKE #define FUTEX_WAKE 1 #endif // Fast-path acquire futex lock #define KMP_ACQUIRE_FUTEX_LOCK(lock, gtid) \ { \ kmp_futex_lock_t *ftx = (kmp_futex_lock_t *)lock; \ kmp_int32 gtid_code = (gtid + 1) << 1; \ KMP_MB(); \ KMP_FSYNC_PREPARE(ftx); \ kmp_int32 poll_val; \ while ((poll_val = KMP_COMPARE_AND_STORE_RET32( \ &(ftx->lk.poll), KMP_LOCK_FREE(futex), \ KMP_LOCK_BUSY(gtid_code, futex))) != KMP_LOCK_FREE(futex)) { \ kmp_int32 cond = KMP_LOCK_STRIP(poll_val) & 1; \ if (!cond) { \ if (!KMP_COMPARE_AND_STORE_RET32(&(ftx->lk.poll), poll_val, \ poll_val | \ KMP_LOCK_BUSY(1, futex))) { \ continue; \ } \ poll_val |= KMP_LOCK_BUSY(1, futex); \ } \ kmp_int32 rc; \ if ((rc = syscall(__NR_futex, &(ftx->lk.poll), FUTEX_WAIT, poll_val, \ NULL, NULL, 0)) != 0) { \ continue; \ } \ gtid_code |= 1; \ } \ KMP_FSYNC_ACQUIRED(ftx); \ } // Fast-path test futex lock #define KMP_TEST_FUTEX_LOCK(lock, gtid, rc) \ { \ kmp_futex_lock_t *ftx = (kmp_futex_lock_t *)lock; \ if (KMP_COMPARE_AND_STORE_ACQ32(&(ftx->lk.poll), KMP_LOCK_FREE(futex), \ KMP_LOCK_BUSY(gtid + 1 << 1, futex))) { \ KMP_FSYNC_ACQUIRED(ftx); \ rc = TRUE; \ } else { \ rc = FALSE; \ } \ } // Fast-path release futex lock #define KMP_RELEASE_FUTEX_LOCK(lock, gtid) \ { \ kmp_futex_lock_t *ftx = (kmp_futex_lock_t *)lock; \ KMP_MB(); \ KMP_FSYNC_RELEASING(ftx); \ kmp_int32 poll_val = \ KMP_XCHG_FIXED32(&(ftx->lk.poll), KMP_LOCK_FREE(futex)); \ if (KMP_LOCK_STRIP(poll_val) & 1) { \ syscall(__NR_futex, &(ftx->lk.poll), FUTEX_WAKE, \ KMP_LOCK_BUSY(1, futex), NULL, NULL, 0); \ } \ KMP_MB(); \ KMP_YIELD_OVERSUB(); \ } #endif // KMP_USE_FUTEX #else // KMP_USE_DYNAMIC_LOCK static kmp_user_lock_p __kmp_get_critical_section_ptr(kmp_critical_name *crit, ident_t const *loc, kmp_int32 gtid) { kmp_user_lock_p *lck_pp = (kmp_user_lock_p *)crit; // Because of the double-check, the following load doesn't need to be volatile kmp_user_lock_p lck = (kmp_user_lock_p)TCR_PTR(*lck_pp); if (lck == NULL) { void *idx; // Allocate & initialize the lock. // Remember alloc'ed locks in table in order to free them in __kmp_cleanup() lck = __kmp_user_lock_allocate(&idx, gtid, kmp_lf_critical_section); __kmp_init_user_lock_with_checks(lck); __kmp_set_user_lock_location(lck, loc); #if USE_ITT_BUILD __kmp_itt_critical_creating(lck); // __kmp_itt_critical_creating() should be called *before* the first usage // of underlying lock. It is the only place where we can guarantee it. There // are chances the lock will destroyed with no usage, but it is not a // problem, because this is not real event seen by user but rather setting // name for object (lock). See more details in kmp_itt.h. #endif /* USE_ITT_BUILD */ // Use a cmpxchg instruction to slam the start of the critical section with // the lock pointer. If another thread beat us to it, deallocate the lock, // and use the lock that the other thread allocated. int status = KMP_COMPARE_AND_STORE_PTR(lck_pp, 0, lck); if (status == 0) { // Deallocate the lock and reload the value. #if USE_ITT_BUILD __kmp_itt_critical_destroyed(lck); // Let ITT know the lock is destroyed and the same memory location may be reused // for another purpose. #endif /* USE_ITT_BUILD */ __kmp_destroy_user_lock_with_checks(lck); __kmp_user_lock_free(&idx, gtid, lck); lck = (kmp_user_lock_p)TCR_PTR(*lck_pp); KMP_DEBUG_ASSERT(lck != NULL); } } return lck; } #endif // KMP_USE_DYNAMIC_LOCK /*! @ingroup WORK_SHARING @param loc source location information. @param global_tid global thread number. @param crit identity of the critical section. This could be a pointer to a lock associated with the critical section, or some other suitably unique value. Enter code protected by a `critical` construct. This function blocks until the executing thread can enter the critical section. */ void __kmpc_critical(ident_t *loc, kmp_int32 global_tid, kmp_critical_name *crit) { #if KMP_USE_DYNAMIC_LOCK #if OMPT_SUPPORT && OMPT_OPTIONAL OMPT_STORE_RETURN_ADDRESS(global_tid); #endif // OMPT_SUPPORT __kmpc_critical_with_hint(loc, global_tid, crit, omp_lock_hint_none); #else KMP_COUNT_BLOCK(OMP_CRITICAL); #if OMPT_SUPPORT && OMPT_OPTIONAL ompt_state_t prev_state = ompt_state_undefined; ompt_thread_info_t ti; #endif kmp_user_lock_p lck; KC_TRACE(10, ("__kmpc_critical: called T#%d\n", global_tid)); __kmp_assert_valid_gtid(global_tid); // TODO: add THR_OVHD_STATE KMP_PUSH_PARTITIONED_TIMER(OMP_critical_wait); KMP_CHECK_USER_LOCK_INIT(); if ((__kmp_user_lock_kind == lk_tas) && (sizeof(lck->tas.lk.poll) <= OMP_CRITICAL_SIZE)) { lck = (kmp_user_lock_p)crit; } #if KMP_USE_FUTEX else if ((__kmp_user_lock_kind == lk_futex) && (sizeof(lck->futex.lk.poll) <= OMP_CRITICAL_SIZE)) { lck = (kmp_user_lock_p)crit; } #endif else { // ticket, queuing or drdpa lck = __kmp_get_critical_section_ptr(crit, loc, global_tid); } if (__kmp_env_consistency_check) __kmp_push_sync(global_tid, ct_critical, loc, lck); // since the critical directive binds to all threads, not just the current // team we have to check this even if we are in a serialized team. // also, even if we are the uber thread, we still have to conduct the lock, // as we have to contend with sibling threads. #if USE_ITT_BUILD __kmp_itt_critical_acquiring(lck); #endif /* USE_ITT_BUILD */ #if OMPT_SUPPORT && OMPT_OPTIONAL OMPT_STORE_RETURN_ADDRESS(gtid); void *codeptr_ra = NULL; if (ompt_enabled.enabled) { ti = __kmp_threads[global_tid]->th.ompt_thread_info; /* OMPT state update */ prev_state = ti.state; ti.wait_id = (ompt_wait_id_t)(uintptr_t)lck; ti.state = ompt_state_wait_critical; /* OMPT event callback */ codeptr_ra = OMPT_LOAD_RETURN_ADDRESS(gtid); if (ompt_enabled.ompt_callback_mutex_acquire) { ompt_callbacks.ompt_callback(ompt_callback_mutex_acquire)( ompt_mutex_critical, omp_lock_hint_none, __ompt_get_mutex_impl_type(), (ompt_wait_id_t)(uintptr_t)lck, codeptr_ra); } } #endif // Value of 'crit' should be good for using as a critical_id of the critical // section directive. __kmp_acquire_user_lock_with_checks(lck, global_tid); #if USE_ITT_BUILD __kmp_itt_critical_acquired(lck); #endif /* USE_ITT_BUILD */ #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.enabled) { /* OMPT state update */ ti.state = prev_state; ti.wait_id = 0; /* OMPT event callback */ if (ompt_enabled.ompt_callback_mutex_acquired) { ompt_callbacks.ompt_callback(ompt_callback_mutex_acquired)( ompt_mutex_critical, (ompt_wait_id_t)(uintptr_t)lck, codeptr_ra); } } #endif KMP_POP_PARTITIONED_TIMER(); KMP_PUSH_PARTITIONED_TIMER(OMP_critical); KA_TRACE(15, ("__kmpc_critical: done T#%d\n", global_tid)); #endif // KMP_USE_DYNAMIC_LOCK } #if KMP_USE_DYNAMIC_LOCK // Converts the given hint to an internal lock implementation static __forceinline kmp_dyna_lockseq_t __kmp_map_hint_to_lock(uintptr_t hint) { #if KMP_USE_TSX #define KMP_TSX_LOCK(seq) lockseq_##seq #else #define KMP_TSX_LOCK(seq) __kmp_user_lock_seq #endif #if KMP_ARCH_X86 || KMP_ARCH_X86_64 #define KMP_CPUINFO_RTM (__kmp_cpuinfo.rtm) #else #define KMP_CPUINFO_RTM 0 #endif // Hints that do not require further logic if (hint & kmp_lock_hint_hle) return KMP_TSX_LOCK(hle); if (hint & kmp_lock_hint_rtm) return KMP_CPUINFO_RTM ? KMP_TSX_LOCK(rtm_queuing) : __kmp_user_lock_seq; if (hint & kmp_lock_hint_adaptive) return KMP_CPUINFO_RTM ? KMP_TSX_LOCK(adaptive) : __kmp_user_lock_seq; // Rule out conflicting hints first by returning the default lock if ((hint & omp_lock_hint_contended) && (hint & omp_lock_hint_uncontended)) return __kmp_user_lock_seq; if ((hint & omp_lock_hint_speculative) && (hint & omp_lock_hint_nonspeculative)) return __kmp_user_lock_seq; // Do not even consider speculation when it appears to be contended if (hint & omp_lock_hint_contended) return lockseq_queuing; // Uncontended lock without speculation if ((hint & omp_lock_hint_uncontended) && !(hint & omp_lock_hint_speculative)) return lockseq_tas; // Use RTM lock for speculation if (hint & omp_lock_hint_speculative) return KMP_CPUINFO_RTM ? KMP_TSX_LOCK(rtm_spin) : __kmp_user_lock_seq; return __kmp_user_lock_seq; } #if OMPT_SUPPORT && OMPT_OPTIONAL #if KMP_USE_DYNAMIC_LOCK static kmp_mutex_impl_t __ompt_get_mutex_impl_type(void *user_lock, kmp_indirect_lock_t *ilock = 0) { if (user_lock) { switch (KMP_EXTRACT_D_TAG(user_lock)) { case 0: break; #if KMP_USE_FUTEX case locktag_futex: return kmp_mutex_impl_queuing; #endif case locktag_tas: return kmp_mutex_impl_spin; #if KMP_USE_TSX case locktag_hle: case locktag_rtm_spin: return kmp_mutex_impl_speculative; #endif default: return kmp_mutex_impl_none; } ilock = KMP_LOOKUP_I_LOCK(user_lock); } KMP_ASSERT(ilock); switch (ilock->type) { #if KMP_USE_TSX case locktag_adaptive: case locktag_rtm_queuing: return kmp_mutex_impl_speculative; #endif case locktag_nested_tas: return kmp_mutex_impl_spin; #if KMP_USE_FUTEX case locktag_nested_futex: #endif case locktag_ticket: case locktag_queuing: case locktag_drdpa: case locktag_nested_ticket: case locktag_nested_queuing: case locktag_nested_drdpa: return kmp_mutex_impl_queuing; default: return kmp_mutex_impl_none; } } #else // For locks without dynamic binding static kmp_mutex_impl_t __ompt_get_mutex_impl_type() { switch (__kmp_user_lock_kind) { case lk_tas: return kmp_mutex_impl_spin; #if KMP_USE_FUTEX case lk_futex: #endif case lk_ticket: case lk_queuing: case lk_drdpa: return kmp_mutex_impl_queuing; #if KMP_USE_TSX case lk_hle: case lk_rtm_queuing: case lk_rtm_spin: case lk_adaptive: return kmp_mutex_impl_speculative; #endif default: return kmp_mutex_impl_none; } } #endif // KMP_USE_DYNAMIC_LOCK #endif // OMPT_SUPPORT && OMPT_OPTIONAL /*! @ingroup WORK_SHARING @param loc source location information. @param global_tid global thread number. @param crit identity of the critical section. This could be a pointer to a lock associated with the critical section, or some other suitably unique value. @param hint the lock hint. Enter code protected by a `critical` construct with a hint. The hint value is used to suggest a lock implementation. This function blocks until the executing thread can enter the critical section unless the hint suggests use of speculative execution and the hardware supports it. */ void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid, kmp_critical_name *crit, uint32_t hint) { KMP_COUNT_BLOCK(OMP_CRITICAL); kmp_user_lock_p lck; #if OMPT_SUPPORT && OMPT_OPTIONAL ompt_state_t prev_state = ompt_state_undefined; ompt_thread_info_t ti; // This is the case, if called from __kmpc_critical: void *codeptr = OMPT_LOAD_RETURN_ADDRESS(global_tid); if (!codeptr) codeptr = OMPT_GET_RETURN_ADDRESS(0); #endif KC_TRACE(10, ("__kmpc_critical: called T#%d\n", global_tid)); __kmp_assert_valid_gtid(global_tid); kmp_dyna_lock_t *lk = (kmp_dyna_lock_t *)crit; // Check if it is initialized. KMP_PUSH_PARTITIONED_TIMER(OMP_critical_wait); if (*lk == 0) { kmp_dyna_lockseq_t lckseq = __kmp_map_hint_to_lock(hint); if (KMP_IS_D_LOCK(lckseq)) { KMP_COMPARE_AND_STORE_ACQ32((volatile kmp_int32 *)crit, 0, KMP_GET_D_TAG(lckseq)); } else { __kmp_init_indirect_csptr(crit, loc, global_tid, KMP_GET_I_TAG(lckseq)); } } // Branch for accessing the actual lock object and set operation. This // branching is inevitable since this lock initialization does not follow the // normal dispatch path (lock table is not used). if (KMP_EXTRACT_D_TAG(lk) != 0) { lck = (kmp_user_lock_p)lk; if (__kmp_env_consistency_check) { __kmp_push_sync(global_tid, ct_critical, loc, lck, __kmp_map_hint_to_lock(hint)); } #if USE_ITT_BUILD __kmp_itt_critical_acquiring(lck); #endif #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.enabled) { ti = __kmp_threads[global_tid]->th.ompt_thread_info; /* OMPT state update */ prev_state = ti.state; ti.wait_id = (ompt_wait_id_t)(uintptr_t)lck; ti.state = ompt_state_wait_critical; /* OMPT event callback */ if (ompt_enabled.ompt_callback_mutex_acquire) { ompt_callbacks.ompt_callback(ompt_callback_mutex_acquire)( ompt_mutex_critical, (unsigned int)hint, __ompt_get_mutex_impl_type(crit), (ompt_wait_id_t)(uintptr_t)lck, codeptr); } } #endif #if KMP_USE_INLINED_TAS if (__kmp_user_lock_seq == lockseq_tas && !__kmp_env_consistency_check) { KMP_ACQUIRE_TAS_LOCK(lck, global_tid); } else #elif KMP_USE_INLINED_FUTEX if (__kmp_user_lock_seq == lockseq_futex && !__kmp_env_consistency_check) { KMP_ACQUIRE_FUTEX_LOCK(lck, global_tid); } else #endif { KMP_D_LOCK_FUNC(lk, set)(lk, global_tid); } } else { kmp_indirect_lock_t *ilk = *((kmp_indirect_lock_t **)lk); lck = ilk->lock; if (__kmp_env_consistency_check) { __kmp_push_sync(global_tid, ct_critical, loc, lck, __kmp_map_hint_to_lock(hint)); } #if USE_ITT_BUILD __kmp_itt_critical_acquiring(lck); #endif #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.enabled) { ti = __kmp_threads[global_tid]->th.ompt_thread_info; /* OMPT state update */ prev_state = ti.state; ti.wait_id = (ompt_wait_id_t)(uintptr_t)lck; ti.state = ompt_state_wait_critical; /* OMPT event callback */ if (ompt_enabled.ompt_callback_mutex_acquire) { ompt_callbacks.ompt_callback(ompt_callback_mutex_acquire)( ompt_mutex_critical, (unsigned int)hint, __ompt_get_mutex_impl_type(0, ilk), (ompt_wait_id_t)(uintptr_t)lck, codeptr); } } #endif KMP_I_LOCK_FUNC(ilk, set)(lck, global_tid); } KMP_POP_PARTITIONED_TIMER(); #if USE_ITT_BUILD __kmp_itt_critical_acquired(lck); #endif /* USE_ITT_BUILD */ #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.enabled) { /* OMPT state update */ ti.state = prev_state; ti.wait_id = 0; /* OMPT event callback */ if (ompt_enabled.ompt_callback_mutex_acquired) { ompt_callbacks.ompt_callback(ompt_callback_mutex_acquired)( ompt_mutex_critical, (ompt_wait_id_t)(uintptr_t)lck, codeptr); } } #endif KMP_PUSH_PARTITIONED_TIMER(OMP_critical); KA_TRACE(15, ("__kmpc_critical: done T#%d\n", global_tid)); } // __kmpc_critical_with_hint #endif // KMP_USE_DYNAMIC_LOCK /*! @ingroup WORK_SHARING @param loc source location information. @param global_tid global thread number . @param crit identity of the critical section. This could be a pointer to a lock associated with the critical section, or some other suitably unique value. Leave a critical section, releasing any lock that was held during its execution. */ void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid, kmp_critical_name *crit) { kmp_user_lock_p lck; KC_TRACE(10, ("__kmpc_end_critical: called T#%d\n", global_tid)); #if KMP_USE_DYNAMIC_LOCK if (KMP_IS_D_LOCK(__kmp_user_lock_seq)) { lck = (kmp_user_lock_p)crit; KMP_ASSERT(lck != NULL); if (__kmp_env_consistency_check) { __kmp_pop_sync(global_tid, ct_critical, loc); } #if USE_ITT_BUILD __kmp_itt_critical_releasing(lck); #endif #if KMP_USE_INLINED_TAS if (__kmp_user_lock_seq == lockseq_tas && !__kmp_env_consistency_check) { KMP_RELEASE_TAS_LOCK(lck, global_tid); } else #elif KMP_USE_INLINED_FUTEX if (__kmp_user_lock_seq == lockseq_futex && !__kmp_env_consistency_check) { KMP_RELEASE_FUTEX_LOCK(lck, global_tid); } else #endif { KMP_D_LOCK_FUNC(lck, unset)((kmp_dyna_lock_t *)lck, global_tid); } } else { kmp_indirect_lock_t *ilk = (kmp_indirect_lock_t *)TCR_PTR(*((kmp_indirect_lock_t **)crit)); KMP_ASSERT(ilk != NULL); lck = ilk->lock; if (__kmp_env_consistency_check) { __kmp_pop_sync(global_tid, ct_critical, loc); } #if USE_ITT_BUILD __kmp_itt_critical_releasing(lck); #endif KMP_I_LOCK_FUNC(ilk, unset)(lck, global_tid); } #else // KMP_USE_DYNAMIC_LOCK if ((__kmp_user_lock_kind == lk_tas) && (sizeof(lck->tas.lk.poll) <= OMP_CRITICAL_SIZE)) { lck = (kmp_user_lock_p)crit; } #if KMP_USE_FUTEX else if ((__kmp_user_lock_kind == lk_futex) && (sizeof(lck->futex.lk.poll) <= OMP_CRITICAL_SIZE)) { lck = (kmp_user_lock_p)crit; } #endif else { // ticket, queuing or drdpa lck = (kmp_user_lock_p)TCR_PTR(*((kmp_user_lock_p *)crit)); } KMP_ASSERT(lck != NULL); if (__kmp_env_consistency_check) __kmp_pop_sync(global_tid, ct_critical, loc); #if USE_ITT_BUILD __kmp_itt_critical_releasing(lck); #endif /* USE_ITT_BUILD */ // Value of 'crit' should be good for using as a critical_id of the critical // section directive. __kmp_release_user_lock_with_checks(lck, global_tid); #endif // KMP_USE_DYNAMIC_LOCK #if OMPT_SUPPORT && OMPT_OPTIONAL /* OMPT release event triggers after lock is released; place here to trigger * for all #if branches */ OMPT_STORE_RETURN_ADDRESS(global_tid); if (ompt_enabled.ompt_callback_mutex_released) { ompt_callbacks.ompt_callback(ompt_callback_mutex_released)( ompt_mutex_critical, (ompt_wait_id_t)(uintptr_t)lck, OMPT_LOAD_RETURN_ADDRESS(0)); } #endif KMP_POP_PARTITIONED_TIMER(); KA_TRACE(15, ("__kmpc_end_critical: done T#%d\n", global_tid)); } /*! @ingroup SYNCHRONIZATION @param loc source location information @param global_tid thread id. @return one if the thread should execute the master block, zero otherwise Start execution of a combined barrier and master. The barrier is executed inside this function. */ kmp_int32 __kmpc_barrier_master(ident_t *loc, kmp_int32 global_tid) { int status; KC_TRACE(10, ("__kmpc_barrier_master: called T#%d\n", global_tid)); __kmp_assert_valid_gtid(global_tid); if (!TCR_4(__kmp_init_parallel)) __kmp_parallel_initialize(); __kmp_resume_if_soft_paused(); if (__kmp_env_consistency_check) __kmp_check_barrier(global_tid, ct_barrier, loc); #if OMPT_SUPPORT ompt_frame_t *ompt_frame; if (ompt_enabled.enabled) { __ompt_get_task_info_internal(0, NULL, NULL, &ompt_frame, NULL, NULL); if (ompt_frame->enter_frame.ptr == NULL) ompt_frame->enter_frame.ptr = OMPT_GET_FRAME_ADDRESS(0); } OMPT_STORE_RETURN_ADDRESS(global_tid); #endif #if USE_ITT_NOTIFY __kmp_threads[global_tid]->th.th_ident = loc; #endif status = __kmp_barrier(bs_plain_barrier, global_tid, TRUE, 0, NULL, NULL); #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.enabled) { ompt_frame->enter_frame = ompt_data_none; } #endif return (status != 0) ? 0 : 1; } /*! @ingroup SYNCHRONIZATION @param loc source location information @param global_tid thread id. Complete the execution of a combined barrier and master. This function should only be called at the completion of the <tt>master</tt> code. Other threads will still be waiting at the barrier and this call releases them. */ void __kmpc_end_barrier_master(ident_t *loc, kmp_int32 global_tid) { KC_TRACE(10, ("__kmpc_end_barrier_master: called T#%d\n", global_tid)); __kmp_assert_valid_gtid(global_tid); __kmp_end_split_barrier(bs_plain_barrier, global_tid); } /*! @ingroup SYNCHRONIZATION @param loc source location information @param global_tid thread id. @return one if the thread should execute the master block, zero otherwise Start execution of a combined barrier and master(nowait) construct. The barrier is executed inside this function. There is no equivalent "end" function, since the */ kmp_int32 __kmpc_barrier_master_nowait(ident_t *loc, kmp_int32 global_tid) { kmp_int32 ret; KC_TRACE(10, ("__kmpc_barrier_master_nowait: called T#%d\n", global_tid)); __kmp_assert_valid_gtid(global_tid); if (!TCR_4(__kmp_init_parallel)) __kmp_parallel_initialize(); __kmp_resume_if_soft_paused(); if (__kmp_env_consistency_check) { if (loc == 0) { KMP_WARNING(ConstructIdentInvalid); // ??? What does it mean for the user? } __kmp_check_barrier(global_tid, ct_barrier, loc); } #if OMPT_SUPPORT ompt_frame_t *ompt_frame; if (ompt_enabled.enabled) { __ompt_get_task_info_internal(0, NULL, NULL, &ompt_frame, NULL, NULL); if (ompt_frame->enter_frame.ptr == NULL) ompt_frame->enter_frame.ptr = OMPT_GET_FRAME_ADDRESS(0); } OMPT_STORE_RETURN_ADDRESS(global_tid); #endif #if USE_ITT_NOTIFY __kmp_threads[global_tid]->th.th_ident = loc; #endif __kmp_barrier(bs_plain_barrier, global_tid, FALSE, 0, NULL, NULL); #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.enabled) { ompt_frame->enter_frame = ompt_data_none; } #endif ret = __kmpc_master(loc, global_tid); if (__kmp_env_consistency_check) { /* there's no __kmpc_end_master called; so the (stats) */ /* actions of __kmpc_end_master are done here */ if (ret) { /* only one thread should do the pop since only */ /* one did the push (see __kmpc_master()) */ __kmp_pop_sync(global_tid, ct_master, loc); } } return (ret); } /* The BARRIER for a SINGLE process section is always explicit */ /*! @ingroup WORK_SHARING @param loc source location information @param global_tid global thread number @return One if this thread should execute the single construct, zero otherwise. Test whether to execute a <tt>single</tt> construct. There are no implicit barriers in the two "single" calls, rather the compiler should introduce an explicit barrier if it is required. */ kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid) { __kmp_assert_valid_gtid(global_tid); kmp_int32 rc = __kmp_enter_single(global_tid, loc, TRUE); if (rc) { // We are going to execute the single statement, so we should count it. KMP_COUNT_BLOCK(OMP_SINGLE); KMP_PUSH_PARTITIONED_TIMER(OMP_single); } #if OMPT_SUPPORT && OMPT_OPTIONAL kmp_info_t *this_thr = __kmp_threads[global_tid]; kmp_team_t *team = this_thr->th.th_team; int tid = __kmp_tid_from_gtid(global_tid); if (ompt_enabled.enabled) { if (rc) { if (ompt_enabled.ompt_callback_work) { ompt_callbacks.ompt_callback(ompt_callback_work)( ompt_work_single_executor, ompt_scope_begin, &(team->t.ompt_team_info.parallel_data), &(team->t.t_implicit_task_taskdata[tid].ompt_task_info.task_data), 1, OMPT_GET_RETURN_ADDRESS(0)); } } else { if (ompt_enabled.ompt_callback_work) { ompt_callbacks.ompt_callback(ompt_callback_work)( ompt_work_single_other, ompt_scope_begin, &(team->t.ompt_team_info.parallel_data), &(team->t.t_implicit_task_taskdata[tid].ompt_task_info.task_data), 1, OMPT_GET_RETURN_ADDRESS(0)); ompt_callbacks.ompt_callback(ompt_callback_work)( ompt_work_single_other, ompt_scope_end, &(team->t.ompt_team_info.parallel_data), &(team->t.t_implicit_task_taskdata[tid].ompt_task_info.task_data), 1, OMPT_GET_RETURN_ADDRESS(0)); } } } #endif return rc; } /*! @ingroup WORK_SHARING @param loc source location information @param global_tid global thread number Mark the end of a <tt>single</tt> construct. This function should only be called by the thread that executed the block of code protected by the `single` construct. */ void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid) { __kmp_assert_valid_gtid(global_tid); __kmp_exit_single(global_tid); KMP_POP_PARTITIONED_TIMER(); #if OMPT_SUPPORT && OMPT_OPTIONAL kmp_info_t *this_thr = __kmp_threads[global_tid]; kmp_team_t *team = this_thr->th.th_team; int tid = __kmp_tid_from_gtid(global_tid); if (ompt_enabled.ompt_callback_work) { ompt_callbacks.ompt_callback(ompt_callback_work)( ompt_work_single_executor, ompt_scope_end, &(team->t.ompt_team_info.parallel_data), &(team->t.t_implicit_task_taskdata[tid].ompt_task_info.task_data), 1, OMPT_GET_RETURN_ADDRESS(0)); } #endif } /*! @ingroup WORK_SHARING @param loc Source location @param global_tid Global thread id Mark the end of a statically scheduled loop. */ void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid) { KMP_POP_PARTITIONED_TIMER(); KE_TRACE(10, ("__kmpc_for_static_fini called T#%d\n", global_tid)); #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.ompt_callback_work) { ompt_work_t ompt_work_type = ompt_work_loop; ompt_team_info_t *team_info = __ompt_get_teaminfo(0, NULL); ompt_task_info_t *task_info = __ompt_get_task_info_object(0); // Determine workshare type if (loc != NULL) { if ((loc->flags & KMP_IDENT_WORK_LOOP) != 0) { ompt_work_type = ompt_work_loop; } else if ((loc->flags & KMP_IDENT_WORK_SECTIONS) != 0) { ompt_work_type = ompt_work_sections; } else if ((loc->flags & KMP_IDENT_WORK_DISTRIBUTE) != 0) { ompt_work_type = ompt_work_distribute; } else { // use default set above. // a warning about this case is provided in __kmpc_for_static_init } KMP_DEBUG_ASSERT(ompt_work_type); } ompt_callbacks.ompt_callback(ompt_callback_work)( ompt_work_type, ompt_scope_end, &(team_info->parallel_data), &(task_info->task_data), 0, OMPT_GET_RETURN_ADDRESS(0)); } #endif if (__kmp_env_consistency_check) __kmp_pop_workshare(global_tid, ct_pdo, loc); } // User routines which take C-style arguments (call by value) // different from the Fortran equivalent routines void ompc_set_num_threads(int arg) { // !!!!! TODO: check the per-task binding __kmp_set_num_threads(arg, __kmp_entry_gtid()); } void ompc_set_dynamic(int flag) { kmp_info_t *thread; /* For the thread-private implementation of the internal controls */ thread = __kmp_entry_thread(); __kmp_save_internal_controls(thread); set__dynamic(thread, flag ? true : false); } void ompc_set_nested(int flag) { kmp_info_t *thread; /* For the thread-private internal controls implementation */ thread = __kmp_entry_thread(); __kmp_save_internal_controls(thread); set__max_active_levels(thread, flag ? __kmp_dflt_max_active_levels : 1); } void ompc_set_max_active_levels(int max_active_levels) { /* TO DO */ /* we want per-task implementation of this internal control */ /* For the per-thread internal controls implementation */ __kmp_set_max_active_levels(__kmp_entry_gtid(), max_active_levels); } void ompc_set_schedule(omp_sched_t kind, int modifier) { // !!!!! TODO: check the per-task binding __kmp_set_schedule(__kmp_entry_gtid(), (kmp_sched_t)kind, modifier); } int ompc_get_ancestor_thread_num(int level) { return __kmp_get_ancestor_thread_num(__kmp_entry_gtid(), level); } int ompc_get_team_size(int level) { return __kmp_get_team_size(__kmp_entry_gtid(), level); } /* OpenMP 5.0 Affinity Format API */ void ompc_set_affinity_format(char const *format) { if (!__kmp_init_serial) { __kmp_serial_initialize(); } __kmp_strncpy_truncate(__kmp_affinity_format, KMP_AFFINITY_FORMAT_SIZE, format, KMP_STRLEN(format) + 1); } size_t ompc_get_affinity_format(char *buffer, size_t size) { size_t format_size; if (!__kmp_init_serial) { __kmp_serial_initialize(); } format_size = KMP_STRLEN(__kmp_affinity_format); if (buffer && size) { __kmp_strncpy_truncate(buffer, size, __kmp_affinity_format, format_size + 1); } return format_size; } void ompc_display_affinity(char const *format) { int gtid; if (!TCR_4(__kmp_init_middle)) { __kmp_middle_initialize(); } gtid = __kmp_get_gtid(); __kmp_aux_display_affinity(gtid, format); } size_t ompc_capture_affinity(char *buffer, size_t buf_size, char const *format) { int gtid; size_t num_required; kmp_str_buf_t capture_buf; if (!TCR_4(__kmp_init_middle)) { __kmp_middle_initialize(); } gtid = __kmp_get_gtid(); __kmp_str_buf_init(&capture_buf); num_required = __kmp_aux_capture_affinity(gtid, format, &capture_buf); if (buffer && buf_size) { __kmp_strncpy_truncate(buffer, buf_size, capture_buf.str, capture_buf.used + 1); } __kmp_str_buf_free(&capture_buf); return num_required; } void kmpc_set_stacksize(int arg) { // __kmp_aux_set_stacksize initializes the library if needed __kmp_aux_set_stacksize(arg); } void kmpc_set_stacksize_s(size_t arg) { // __kmp_aux_set_stacksize initializes the library if needed __kmp_aux_set_stacksize(arg); } void kmpc_set_blocktime(int arg) { int gtid, tid; kmp_info_t *thread; gtid = __kmp_entry_gtid(); tid = __kmp_tid_from_gtid(gtid); thread = __kmp_thread_from_gtid(gtid); __kmp_aux_set_blocktime(arg, thread, tid); } void kmpc_set_library(int arg) { // __kmp_user_set_library initializes the library if needed __kmp_user_set_library((enum library_type)arg); } void kmpc_set_defaults(char const *str) { // __kmp_aux_set_defaults initializes the library if needed __kmp_aux_set_defaults(str, KMP_STRLEN(str)); } void kmpc_set_disp_num_buffers(int arg) { // ignore after initialization because some teams have already // allocated dispatch buffers if (__kmp_init_serial == FALSE && arg >= KMP_MIN_DISP_NUM_BUFF && arg <= KMP_MAX_DISP_NUM_BUFF) { __kmp_dispatch_num_buffers = arg; } } int kmpc_set_affinity_mask_proc(int proc, void **mask) { #if defined(KMP_STUB) || !KMP_AFFINITY_SUPPORTED return -1; #else if (!TCR_4(__kmp_init_middle)) { __kmp_middle_initialize(); } return __kmp_aux_set_affinity_mask_proc(proc, mask); #endif } int kmpc_unset_affinity_mask_proc(int proc, void **mask) { #if defined(KMP_STUB) || !KMP_AFFINITY_SUPPORTED return -1; #else if (!TCR_4(__kmp_init_middle)) { __kmp_middle_initialize(); } return __kmp_aux_unset_affinity_mask_proc(proc, mask); #endif } int kmpc_get_affinity_mask_proc(int proc, void **mask) { #if defined(KMP_STUB) || !KMP_AFFINITY_SUPPORTED return -1; #else if (!TCR_4(__kmp_init_middle)) { __kmp_middle_initialize(); } return __kmp_aux_get_affinity_mask_proc(proc, mask); #endif } /* -------------------------------------------------------------------------- */ /*! @ingroup THREADPRIVATE @param loc source location information @param gtid global thread number @param cpy_size size of the cpy_data buffer @param cpy_data pointer to data to be copied @param cpy_func helper function to call for copying data @param didit flag variable: 1=single thread; 0=not single thread __kmpc_copyprivate implements the interface for the private data broadcast needed for the copyprivate clause associated with a single region in an OpenMP<sup>*</sup> program (both C and Fortran). All threads participating in the parallel region call this routine. One of the threads (called the single thread) should have the <tt>didit</tt> variable set to 1 and all other threads should have that variable set to 0. All threads pass a pointer to a data buffer (cpy_data) that they have built. The OpenMP specification forbids the use of nowait on the single region when a copyprivate clause is present. However, @ref __kmpc_copyprivate implements a barrier internally to avoid race conditions, so the code generation for the single region should avoid generating a barrier after the call to @ref __kmpc_copyprivate. The <tt>gtid</tt> parameter is the global thread id for the current thread. The <tt>loc</tt> parameter is a pointer to source location information. Internal implementation: The single thread will first copy its descriptor address (cpy_data) to a team-private location, then the other threads will each call the function pointed to by the parameter cpy_func, which carries out the copy by copying the data using the cpy_data buffer. The cpy_func routine used for the copy and the contents of the data area defined by cpy_data and cpy_size may be built in any fashion that will allow the copy to be done. For instance, the cpy_data buffer can hold the actual data to be copied or it may hold a list of pointers to the data. The cpy_func routine must interpret the cpy_data buffer appropriately. The interface to cpy_func is as follows: @code void cpy_func( void *destination, void *source ) @endcode where void *destination is the cpy_data pointer for the thread being copied to and void *source is the cpy_data pointer for the thread being copied from. */ void __kmpc_copyprivate(ident_t *loc, kmp_int32 gtid, size_t cpy_size, void *cpy_data, void (*cpy_func)(void *, void *), kmp_int32 didit) { void **data_ptr; KC_TRACE(10, ("__kmpc_copyprivate: called T#%d\n", gtid)); __kmp_assert_valid_gtid(gtid); KMP_MB(); data_ptr = &__kmp_team_from_gtid(gtid)->t.t_copypriv_data; if (__kmp_env_consistency_check) { if (loc == 0) { KMP_WARNING(ConstructIdentInvalid); } } // ToDo: Optimize the following two barriers into some kind of split barrier if (didit) *data_ptr = cpy_data; #if OMPT_SUPPORT ompt_frame_t *ompt_frame; if (ompt_enabled.enabled) { __ompt_get_task_info_internal(0, NULL, NULL, &ompt_frame, NULL, NULL); if (ompt_frame->enter_frame.ptr == NULL) ompt_frame->enter_frame.ptr = OMPT_GET_FRAME_ADDRESS(0); } OMPT_STORE_RETURN_ADDRESS(gtid); #endif /* This barrier is not a barrier region boundary */ #if USE_ITT_NOTIFY __kmp_threads[gtid]->th.th_ident = loc; #endif __kmp_barrier(bs_plain_barrier, gtid, FALSE, 0, NULL, NULL); if (!didit) (*cpy_func)(cpy_data, *data_ptr); // Consider next barrier a user-visible barrier for barrier region boundaries // Nesting checks are already handled by the single construct checks { #if OMPT_SUPPORT OMPT_STORE_RETURN_ADDRESS(gtid); #endif #if USE_ITT_NOTIFY __kmp_threads[gtid]->th.th_ident = loc; // TODO: check if it is needed (e.g. // tasks can overwrite the location) #endif __kmp_barrier(bs_plain_barrier, gtid, FALSE, 0, NULL, NULL); #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.enabled) { ompt_frame->enter_frame = ompt_data_none; } #endif } } /* -------------------------------------------------------------------------- */ #define INIT_LOCK __kmp_init_user_lock_with_checks #define INIT_NESTED_LOCK __kmp_init_nested_user_lock_with_checks #define ACQUIRE_LOCK __kmp_acquire_user_lock_with_checks #define ACQUIRE_LOCK_TIMED __kmp_acquire_user_lock_with_checks_timed #define ACQUIRE_NESTED_LOCK __kmp_acquire_nested_user_lock_with_checks #define ACQUIRE_NESTED_LOCK_TIMED \ __kmp_acquire_nested_user_lock_with_checks_timed #define RELEASE_LOCK __kmp_release_user_lock_with_checks #define RELEASE_NESTED_LOCK __kmp_release_nested_user_lock_with_checks #define TEST_LOCK __kmp_test_user_lock_with_checks #define TEST_NESTED_LOCK __kmp_test_nested_user_lock_with_checks #define DESTROY_LOCK __kmp_destroy_user_lock_with_checks #define DESTROY_NESTED_LOCK __kmp_destroy_nested_user_lock_with_checks // TODO: Make check abort messages use location info & pass it into // with_checks routines #if KMP_USE_DYNAMIC_LOCK // internal lock initializer static __forceinline void __kmp_init_lock_with_hint(ident_t *loc, void **lock, kmp_dyna_lockseq_t seq) { if (KMP_IS_D_LOCK(seq)) { KMP_INIT_D_LOCK(lock, seq); #if USE_ITT_BUILD __kmp_itt_lock_creating((kmp_user_lock_p)lock, NULL); #endif } else { KMP_INIT_I_LOCK(lock, seq); #if USE_ITT_BUILD kmp_indirect_lock_t *ilk = KMP_LOOKUP_I_LOCK(lock); __kmp_itt_lock_creating(ilk->lock, loc); #endif } } // internal nest lock initializer static __forceinline void __kmp_init_nest_lock_with_hint(ident_t *loc, void **lock, kmp_dyna_lockseq_t seq) { #if KMP_USE_TSX // Don't have nested lock implementation for speculative locks if (seq == lockseq_hle || seq == lockseq_rtm_queuing || seq == lockseq_rtm_spin || seq == lockseq_adaptive) seq = __kmp_user_lock_seq; #endif switch (seq) { case lockseq_tas: seq = lockseq_nested_tas; break; #if KMP_USE_FUTEX case lockseq_futex: seq = lockseq_nested_futex; break; #endif case lockseq_ticket: seq = lockseq_nested_ticket; break; case lockseq_queuing: seq = lockseq_nested_queuing; break; case lockseq_drdpa: seq = lockseq_nested_drdpa; break; default: seq = lockseq_nested_queuing; } KMP_INIT_I_LOCK(lock, seq); #if USE_ITT_BUILD kmp_indirect_lock_t *ilk = KMP_LOOKUP_I_LOCK(lock); __kmp_itt_lock_creating(ilk->lock, loc); #endif } /* initialize the lock with a hint */ void __kmpc_init_lock_with_hint(ident_t *loc, kmp_int32 gtid, void **user_lock, uintptr_t hint) { KMP_DEBUG_ASSERT(__kmp_init_serial); if (__kmp_env_consistency_check && user_lock == NULL) { KMP_FATAL(LockIsUninitialized, "omp_init_lock_with_hint"); } __kmp_init_lock_with_hint(loc, user_lock, __kmp_map_hint_to_lock(hint)); #if OMPT_SUPPORT && OMPT_OPTIONAL // This is the case, if called from omp_init_lock_with_hint: void *codeptr = OMPT_LOAD_RETURN_ADDRESS(gtid); if (!codeptr) codeptr = OMPT_GET_RETURN_ADDRESS(0); if (ompt_enabled.ompt_callback_lock_init) { ompt_callbacks.ompt_callback(ompt_callback_lock_init)( ompt_mutex_lock, (omp_lock_hint_t)hint, __ompt_get_mutex_impl_type(user_lock), (ompt_wait_id_t)(uintptr_t)user_lock, codeptr); } #endif } /* initialize the lock with a hint */ void __kmpc_init_nest_lock_with_hint(ident_t *loc, kmp_int32 gtid, void **user_lock, uintptr_t hint) { KMP_DEBUG_ASSERT(__kmp_init_serial); if (__kmp_env_consistency_check && user_lock == NULL) { KMP_FATAL(LockIsUninitialized, "omp_init_nest_lock_with_hint"); } __kmp_init_nest_lock_with_hint(loc, user_lock, __kmp_map_hint_to_lock(hint)); #if OMPT_SUPPORT && OMPT_OPTIONAL // This is the case, if called from omp_init_lock_with_hint: void *codeptr = OMPT_LOAD_RETURN_ADDRESS(gtid); if (!codeptr) codeptr = OMPT_GET_RETURN_ADDRESS(0); if (ompt_enabled.ompt_callback_lock_init) { ompt_callbacks.ompt_callback(ompt_callback_lock_init)( ompt_mutex_nest_lock, (omp_lock_hint_t)hint, __ompt_get_mutex_impl_type(user_lock), (ompt_wait_id_t)(uintptr_t)user_lock, codeptr); } #endif } #endif // KMP_USE_DYNAMIC_LOCK /* initialize the lock */ void __kmpc_init_lock(ident_t *loc, kmp_int32 gtid, void **user_lock) { #if KMP_USE_DYNAMIC_LOCK KMP_DEBUG_ASSERT(__kmp_init_serial); if (__kmp_env_consistency_check && user_lock == NULL) { KMP_FATAL(LockIsUninitialized, "omp_init_lock"); } __kmp_init_lock_with_hint(loc, user_lock, __kmp_user_lock_seq); #if OMPT_SUPPORT && OMPT_OPTIONAL // This is the case, if called from omp_init_lock_with_hint: void *codeptr = OMPT_LOAD_RETURN_ADDRESS(gtid); if (!codeptr) codeptr = OMPT_GET_RETURN_ADDRESS(0); if (ompt_enabled.ompt_callback_lock_init) { ompt_callbacks.ompt_callback(ompt_callback_lock_init)( ompt_mutex_lock, omp_lock_hint_none, __ompt_get_mutex_impl_type(user_lock), (ompt_wait_id_t)(uintptr_t)user_lock, codeptr); } #endif #else // KMP_USE_DYNAMIC_LOCK static char const *const func = "omp_init_lock"; kmp_user_lock_p lck; KMP_DEBUG_ASSERT(__kmp_init_serial); if (__kmp_env_consistency_check) { if (user_lock == NULL) { KMP_FATAL(LockIsUninitialized, func); } } KMP_CHECK_USER_LOCK_INIT(); if ((__kmp_user_lock_kind == lk_tas) && (sizeof(lck->tas.lk.poll) <= OMP_LOCK_T_SIZE)) { lck = (kmp_user_lock_p)user_lock; } #if KMP_USE_FUTEX else if ((__kmp_user_lock_kind == lk_futex) && (sizeof(lck->futex.lk.poll) <= OMP_LOCK_T_SIZE)) { lck = (kmp_user_lock_p)user_lock; } #endif else { lck = __kmp_user_lock_allocate(user_lock, gtid, 0); } INIT_LOCK(lck); __kmp_set_user_lock_location(lck, loc); #if OMPT_SUPPORT && OMPT_OPTIONAL // This is the case, if called from omp_init_lock_with_hint: void *codeptr = OMPT_LOAD_RETURN_ADDRESS(gtid); if (!codeptr) codeptr = OMPT_GET_RETURN_ADDRESS(0); if (ompt_enabled.ompt_callback_lock_init) { ompt_callbacks.ompt_callback(ompt_callback_lock_init)( ompt_mutex_lock, omp_lock_hint_none, __ompt_get_mutex_impl_type(), (ompt_wait_id_t)(uintptr_t)user_lock, codeptr); } #endif #if USE_ITT_BUILD __kmp_itt_lock_creating(lck); #endif /* USE_ITT_BUILD */ #endif // KMP_USE_DYNAMIC_LOCK } // __kmpc_init_lock /* initialize the lock */ void __kmpc_init_nest_lock(ident_t *loc, kmp_int32 gtid, void **user_lock) { #if KMP_USE_DYNAMIC_LOCK KMP_DEBUG_ASSERT(__kmp_init_serial); if (__kmp_env_consistency_check && user_lock == NULL) { KMP_FATAL(LockIsUninitialized, "omp_init_nest_lock"); } __kmp_init_nest_lock_with_hint(loc, user_lock, __kmp_user_lock_seq); #if OMPT_SUPPORT && OMPT_OPTIONAL // This is the case, if called from omp_init_lock_with_hint: void *codeptr = OMPT_LOAD_RETURN_ADDRESS(gtid); if (!codeptr) codeptr = OMPT_GET_RETURN_ADDRESS(0); if (ompt_enabled.ompt_callback_lock_init) { ompt_callbacks.ompt_callback(ompt_callback_lock_init)( ompt_mutex_nest_lock, omp_lock_hint_none, __ompt_get_mutex_impl_type(user_lock), (ompt_wait_id_t)(uintptr_t)user_lock, codeptr); } #endif #else // KMP_USE_DYNAMIC_LOCK static char const *const func = "omp_init_nest_lock"; kmp_user_lock_p lck; KMP_DEBUG_ASSERT(__kmp_init_serial); if (__kmp_env_consistency_check) { if (user_lock == NULL) { KMP_FATAL(LockIsUninitialized, func); } } KMP_CHECK_USER_LOCK_INIT(); if ((__kmp_user_lock_kind == lk_tas) && (sizeof(lck->tas.lk.poll) + sizeof(lck->tas.lk.depth_locked) <= OMP_NEST_LOCK_T_SIZE)) { lck = (kmp_user_lock_p)user_lock; } #if KMP_USE_FUTEX else if ((__kmp_user_lock_kind == lk_futex) && (sizeof(lck->futex.lk.poll) + sizeof(lck->futex.lk.depth_locked) <= OMP_NEST_LOCK_T_SIZE)) { lck = (kmp_user_lock_p)user_lock; } #endif else { lck = __kmp_user_lock_allocate(user_lock, gtid, 0); } INIT_NESTED_LOCK(lck); __kmp_set_user_lock_location(lck, loc); #if OMPT_SUPPORT && OMPT_OPTIONAL // This is the case, if called from omp_init_lock_with_hint: void *codeptr = OMPT_LOAD_RETURN_ADDRESS(gtid); if (!codeptr) codeptr = OMPT_GET_RETURN_ADDRESS(0); if (ompt_enabled.ompt_callback_lock_init) { ompt_callbacks.ompt_callback(ompt_callback_lock_init)( ompt_mutex_nest_lock, omp_lock_hint_none, __ompt_get_mutex_impl_type(), (ompt_wait_id_t)(uintptr_t)user_lock, codeptr); } #endif #if USE_ITT_BUILD __kmp_itt_lock_creating(lck); #endif /* USE_ITT_BUILD */ #endif // KMP_USE_DYNAMIC_LOCK } // __kmpc_init_nest_lock void __kmpc_destroy_lock(ident_t *loc, kmp_int32 gtid, void **user_lock) { #if KMP_USE_DYNAMIC_LOCK #if USE_ITT_BUILD kmp_user_lock_p lck; if (KMP_EXTRACT_D_TAG(user_lock) == 0) { lck = ((kmp_indirect_lock_t *)KMP_LOOKUP_I_LOCK(user_lock))->lock; } else { lck = (kmp_user_lock_p)user_lock; } __kmp_itt_lock_destroyed(lck); #endif #if OMPT_SUPPORT && OMPT_OPTIONAL // This is the case, if called from omp_init_lock_with_hint: void *codeptr = OMPT_LOAD_RETURN_ADDRESS(gtid); if (!codeptr) codeptr = OMPT_GET_RETURN_ADDRESS(0); if (ompt_enabled.ompt_callback_lock_destroy) { kmp_user_lock_p lck; if (KMP_EXTRACT_D_TAG(user_lock) == 0) { lck = ((kmp_indirect_lock_t *)KMP_LOOKUP_I_LOCK(user_lock))->lock; } else { lck = (kmp_user_lock_p)user_lock; } ompt_callbacks.ompt_callback(ompt_callback_lock_destroy)( ompt_mutex_lock, (ompt_wait_id_t)(uintptr_t)user_lock, codeptr); } #endif KMP_D_LOCK_FUNC(user_lock, destroy)((kmp_dyna_lock_t *)user_lock); #else kmp_user_lock_p lck; if ((__kmp_user_lock_kind == lk_tas) && (sizeof(lck->tas.lk.poll) <= OMP_LOCK_T_SIZE)) { lck = (kmp_user_lock_p)user_lock; } #if KMP_USE_FUTEX else if ((__kmp_user_lock_kind == lk_futex) && (sizeof(lck->futex.lk.poll) <= OMP_LOCK_T_SIZE)) { lck = (kmp_user_lock_p)user_lock; } #endif else { lck = __kmp_lookup_user_lock(user_lock, "omp_destroy_lock"); } #if OMPT_SUPPORT && OMPT_OPTIONAL // This is the case, if called from omp_init_lock_with_hint: void *codeptr = OMPT_LOAD_RETURN_ADDRESS(gtid); if (!codeptr) codeptr = OMPT_GET_RETURN_ADDRESS(0); if (ompt_enabled.ompt_callback_lock_destroy) { ompt_callbacks.ompt_callback(ompt_callback_lock_destroy)( ompt_mutex_lock, (ompt_wait_id_t)(uintptr_t)user_lock, codeptr); } #endif #if USE_ITT_BUILD __kmp_itt_lock_destroyed(lck); #endif /* USE_ITT_BUILD */ DESTROY_LOCK(lck); if ((__kmp_user_lock_kind == lk_tas) && (sizeof(lck->tas.lk.poll) <= OMP_LOCK_T_SIZE)) { ; } #if KMP_USE_FUTEX else if ((__kmp_user_lock_kind == lk_futex) && (sizeof(lck->futex.lk.poll) <= OMP_LOCK_T_SIZE)) { ; } #endif else { __kmp_user_lock_free(user_lock, gtid, lck); } #endif // KMP_USE_DYNAMIC_LOCK } // __kmpc_destroy_lock /* destroy the lock */ void __kmpc_destroy_nest_lock(ident_t *loc, kmp_int32 gtid, void **user_lock) { #if KMP_USE_DYNAMIC_LOCK #if USE_ITT_BUILD kmp_indirect_lock_t *ilk = KMP_LOOKUP_I_LOCK(user_lock); __kmp_itt_lock_destroyed(ilk->lock); #endif #if OMPT_SUPPORT && OMPT_OPTIONAL // This is the case, if called from omp_init_lock_with_hint: void *codeptr = OMPT_LOAD_RETURN_ADDRESS(gtid); if (!codeptr) codeptr = OMPT_GET_RETURN_ADDRESS(0); if (ompt_enabled.ompt_callback_lock_destroy) { ompt_callbacks.ompt_callback(ompt_callback_lock_destroy)( ompt_mutex_nest_lock, (ompt_wait_id_t)(uintptr_t)user_lock, codeptr); } #endif KMP_D_LOCK_FUNC(user_lock, destroy)((kmp_dyna_lock_t *)user_lock); #else // KMP_USE_DYNAMIC_LOCK kmp_user_lock_p lck; if ((__kmp_user_lock_kind == lk_tas) && (sizeof(lck->tas.lk.poll) + sizeof(lck->tas.lk.depth_locked) <= OMP_NEST_LOCK_T_SIZE)) { lck = (kmp_user_lock_p)user_lock; } #if KMP_USE_FUTEX else if ((__kmp_user_lock_kind == lk_futex) && (sizeof(lck->futex.lk.poll) + sizeof(lck->futex.lk.depth_locked) <= OMP_NEST_LOCK_T_SIZE)) { lck = (kmp_user_lock_p)user_lock; } #endif else { lck = __kmp_lookup_user_lock(user_lock, "omp_destroy_nest_lock"); } #if OMPT_SUPPORT && OMPT_OPTIONAL // This is the case, if called from omp_init_lock_with_hint: void *codeptr = OMPT_LOAD_RETURN_ADDRESS(gtid); if (!codeptr) codeptr = OMPT_GET_RETURN_ADDRESS(0); if (ompt_enabled.ompt_callback_lock_destroy) { ompt_callbacks.ompt_callback(ompt_callback_lock_destroy)( ompt_mutex_nest_lock, (ompt_wait_id_t)(uintptr_t)user_lock, codeptr); } #endif #if USE_ITT_BUILD __kmp_itt_lock_destroyed(lck); #endif /* USE_ITT_BUILD */ DESTROY_NESTED_LOCK(lck); if ((__kmp_user_lock_kind == lk_tas) && (sizeof(lck->tas.lk.poll) + sizeof(lck->tas.lk.depth_locked) <= OMP_NEST_LOCK_T_SIZE)) { ; } #if KMP_USE_FUTEX else if ((__kmp_user_lock_kind == lk_futex) && (sizeof(lck->futex.lk.poll) + sizeof(lck->futex.lk.depth_locked) <= OMP_NEST_LOCK_T_SIZE)) { ; } #endif else { __kmp_user_lock_free(user_lock, gtid, lck); } #endif // KMP_USE_DYNAMIC_LOCK } // __kmpc_destroy_nest_lock void __kmpc_set_lock(ident_t *loc, kmp_int32 gtid, void **user_lock) { KMP_COUNT_BLOCK(OMP_set_lock); #if KMP_USE_DYNAMIC_LOCK int tag = KMP_EXTRACT_D_TAG(user_lock); #if USE_ITT_BUILD __kmp_itt_lock_acquiring( (kmp_user_lock_p) user_lock); // itt function will get to the right lock object. #endif #if OMPT_SUPPORT && OMPT_OPTIONAL // This is the case, if called from omp_init_lock_with_hint: void *codeptr = OMPT_LOAD_RETURN_ADDRESS(gtid); if (!codeptr) codeptr = OMPT_GET_RETURN_ADDRESS(0); if (ompt_enabled.ompt_callback_mutex_acquire) { ompt_callbacks.ompt_callback(ompt_callback_mutex_acquire)( ompt_mutex_lock, omp_lock_hint_none, __ompt_get_mutex_impl_type(user_lock), (ompt_wait_id_t)(uintptr_t)user_lock, codeptr); } #endif #if KMP_USE_INLINED_TAS if (tag == locktag_tas && !__kmp_env_consistency_check) { KMP_ACQUIRE_TAS_LOCK(user_lock, gtid); } else #elif KMP_USE_INLINED_FUTEX if (tag == locktag_futex && !__kmp_env_consistency_check) { KMP_ACQUIRE_FUTEX_LOCK(user_lock, gtid); } else #endif { __kmp_direct_set[tag]((kmp_dyna_lock_t *)user_lock, gtid); } #if USE_ITT_BUILD __kmp_itt_lock_acquired((kmp_user_lock_p)user_lock); #endif #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.ompt_callback_mutex_acquired) { ompt_callbacks.ompt_callback(ompt_callback_mutex_acquired)( ompt_mutex_lock, (ompt_wait_id_t)(uintptr_t)user_lock, codeptr); } #endif #else // KMP_USE_DYNAMIC_LOCK kmp_user_lock_p lck; if ((__kmp_user_lock_kind == lk_tas) && (sizeof(lck->tas.lk.poll) <= OMP_LOCK_T_SIZE)) { lck = (kmp_user_lock_p)user_lock; } #if KMP_USE_FUTEX else if ((__kmp_user_lock_kind == lk_futex) && (sizeof(lck->futex.lk.poll) <= OMP_LOCK_T_SIZE)) { lck = (kmp_user_lock_p)user_lock; } #endif else { lck = __kmp_lookup_user_lock(user_lock, "omp_set_lock"); } #if USE_ITT_BUILD __kmp_itt_lock_acquiring(lck); #endif /* USE_ITT_BUILD */ #if OMPT_SUPPORT && OMPT_OPTIONAL // This is the case, if called from omp_init_lock_with_hint: void *codeptr = OMPT_LOAD_RETURN_ADDRESS(gtid); if (!codeptr) codeptr = OMPT_GET_RETURN_ADDRESS(0); if (ompt_enabled.ompt_callback_mutex_acquire) { ompt_callbacks.ompt_callback(ompt_callback_mutex_acquire)( ompt_mutex_lock, omp_lock_hint_none, __ompt_get_mutex_impl_type(), (ompt_wait_id_t)(uintptr_t)lck, codeptr); } #endif ACQUIRE_LOCK(lck, gtid); #if USE_ITT_BUILD __kmp_itt_lock_acquired(lck); #endif /* USE_ITT_BUILD */ #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.ompt_callback_mutex_acquired) { ompt_callbacks.ompt_callback(ompt_callback_mutex_acquired)( ompt_mutex_lock, (ompt_wait_id_t)(uintptr_t)lck, codeptr); } #endif #endif // KMP_USE_DYNAMIC_LOCK } void __kmpc_set_nest_lock(ident_t *loc, kmp_int32 gtid, void **user_lock) { #if KMP_USE_DYNAMIC_LOCK #if USE_ITT_BUILD __kmp_itt_lock_acquiring((kmp_user_lock_p)user_lock); #endif #if OMPT_SUPPORT && OMPT_OPTIONAL // This is the case, if called from omp_init_lock_with_hint: void *codeptr = OMPT_LOAD_RETURN_ADDRESS(gtid); if (!codeptr) codeptr = OMPT_GET_RETURN_ADDRESS(0); if (ompt_enabled.enabled) { if (ompt_enabled.ompt_callback_mutex_acquire) { ompt_callbacks.ompt_callback(ompt_callback_mutex_acquire)( ompt_mutex_nest_lock, omp_lock_hint_none, __ompt_get_mutex_impl_type(user_lock), (ompt_wait_id_t)(uintptr_t)user_lock, codeptr); } } #endif int acquire_status = KMP_D_LOCK_FUNC(user_lock, set)((kmp_dyna_lock_t *)user_lock, gtid); (void)acquire_status; #if USE_ITT_BUILD __kmp_itt_lock_acquired((kmp_user_lock_p)user_lock); #endif #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.enabled) { if (acquire_status == KMP_LOCK_ACQUIRED_FIRST) { if (ompt_enabled.ompt_callback_mutex_acquired) { // lock_first ompt_callbacks.ompt_callback(ompt_callback_mutex_acquired)( ompt_mutex_nest_lock, (ompt_wait_id_t)(uintptr_t)user_lock, codeptr); } } else { if (ompt_enabled.ompt_callback_nest_lock) { // lock_next ompt_callbacks.ompt_callback(ompt_callback_nest_lock)( ompt_scope_begin, (ompt_wait_id_t)(uintptr_t)user_lock, codeptr); } } } #endif #else // KMP_USE_DYNAMIC_LOCK int acquire_status; kmp_user_lock_p lck; if ((__kmp_user_lock_kind == lk_tas) && (sizeof(lck->tas.lk.poll) + sizeof(lck->tas.lk.depth_locked) <= OMP_NEST_LOCK_T_SIZE)) { lck = (kmp_user_lock_p)user_lock; } #if KMP_USE_FUTEX else if ((__kmp_user_lock_kind == lk_futex) && (sizeof(lck->futex.lk.poll) + sizeof(lck->futex.lk.depth_locked) <= OMP_NEST_LOCK_T_SIZE)) { lck = (kmp_user_lock_p)user_lock; } #endif else { lck = __kmp_lookup_user_lock(user_lock, "omp_set_nest_lock"); } #if USE_ITT_BUILD __kmp_itt_lock_acquiring(lck); #endif /* USE_ITT_BUILD */ #if OMPT_SUPPORT && OMPT_OPTIONAL // This is the case, if called from omp_init_lock_with_hint: void *codeptr = OMPT_LOAD_RETURN_ADDRESS(gtid); if (!codeptr) codeptr = OMPT_GET_RETURN_ADDRESS(0); if (ompt_enabled.enabled) { if (ompt_enabled.ompt_callback_mutex_acquire) { ompt_callbacks.ompt_callback(ompt_callback_mutex_acquire)( ompt_mutex_nest_lock, omp_lock_hint_none, __ompt_get_mutex_impl_type(), (ompt_wait_id_t)(uintptr_t)lck, codeptr); } } #endif ACQUIRE_NESTED_LOCK(lck, gtid, &acquire_status); #if USE_ITT_BUILD __kmp_itt_lock_acquired(lck); #endif /* USE_ITT_BUILD */ #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.enabled) { if (acquire_status == KMP_LOCK_ACQUIRED_FIRST) { if (ompt_enabled.ompt_callback_mutex_acquired) { // lock_first ompt_callbacks.ompt_callback(ompt_callback_mutex_acquired)( ompt_mutex_nest_lock, (ompt_wait_id_t)(uintptr_t)lck, codeptr); } } else { if (ompt_enabled.ompt_callback_nest_lock) { // lock_next ompt_callbacks.ompt_callback(ompt_callback_nest_lock)( ompt_scope_begin, (ompt_wait_id_t)(uintptr_t)lck, codeptr); } } } #endif #endif // KMP_USE_DYNAMIC_LOCK } void __kmpc_unset_lock(ident_t *loc, kmp_int32 gtid, void **user_lock) { #if KMP_USE_DYNAMIC_LOCK int tag = KMP_EXTRACT_D_TAG(user_lock); #if USE_ITT_BUILD __kmp_itt_lock_releasing((kmp_user_lock_p)user_lock); #endif #if KMP_USE_INLINED_TAS if (tag == locktag_tas && !__kmp_env_consistency_check) { KMP_RELEASE_TAS_LOCK(user_lock, gtid); } else #elif KMP_USE_INLINED_FUTEX if (tag == locktag_futex && !__kmp_env_consistency_check) { KMP_RELEASE_FUTEX_LOCK(user_lock, gtid); } else #endif { __kmp_direct_unset[tag]((kmp_dyna_lock_t *)user_lock, gtid); } #if OMPT_SUPPORT && OMPT_OPTIONAL // This is the case, if called from omp_init_lock_with_hint: void *codeptr = OMPT_LOAD_RETURN_ADDRESS(gtid); if (!codeptr) codeptr = OMPT_GET_RETURN_ADDRESS(0); if (ompt_enabled.ompt_callback_mutex_released) { ompt_callbacks.ompt_callback(ompt_callback_mutex_released)( ompt_mutex_lock, (ompt_wait_id_t)(uintptr_t)user_lock, codeptr); } #endif #else // KMP_USE_DYNAMIC_LOCK kmp_user_lock_p lck; /* Can't use serial interval since not block structured */ /* release the lock */ if ((__kmp_user_lock_kind == lk_tas) && (sizeof(lck->tas.lk.poll) <= OMP_LOCK_T_SIZE)) { #if KMP_OS_LINUX && \ (KMP_ARCH_X86 || KMP_ARCH_X86_64 || KMP_ARCH_ARM || KMP_ARCH_AARCH64) // "fast" path implemented to fix customer performance issue #if USE_ITT_BUILD __kmp_itt_lock_releasing((kmp_user_lock_p)user_lock); #endif /* USE_ITT_BUILD */ TCW_4(((kmp_user_lock_p)user_lock)->tas.lk.poll, 0); KMP_MB(); #if OMPT_SUPPORT && OMPT_OPTIONAL // This is the case, if called from omp_init_lock_with_hint: void *codeptr = OMPT_LOAD_RETURN_ADDRESS(gtid); if (!codeptr) codeptr = OMPT_GET_RETURN_ADDRESS(0); if (ompt_enabled.ompt_callback_mutex_released) { ompt_callbacks.ompt_callback(ompt_callback_mutex_released)( ompt_mutex_lock, (ompt_wait_id_t)(uintptr_t)lck, codeptr); } #endif return; #else lck = (kmp_user_lock_p)user_lock; #endif } #if KMP_USE_FUTEX else if ((__kmp_user_lock_kind == lk_futex) && (sizeof(lck->futex.lk.poll) <= OMP_LOCK_T_SIZE)) { lck = (kmp_user_lock_p)user_lock; } #endif else { lck = __kmp_lookup_user_lock(user_lock, "omp_unset_lock"); } #if USE_ITT_BUILD __kmp_itt_lock_releasing(lck); #endif /* USE_ITT_BUILD */ RELEASE_LOCK(lck, gtid); #if OMPT_SUPPORT && OMPT_OPTIONAL // This is the case, if called from omp_init_lock_with_hint: void *codeptr = OMPT_LOAD_RETURN_ADDRESS(gtid); if (!codeptr) codeptr = OMPT_GET_RETURN_ADDRESS(0); if (ompt_enabled.ompt_callback_mutex_released) { ompt_callbacks.ompt_callback(ompt_callback_mutex_released)( ompt_mutex_lock, (ompt_wait_id_t)(uintptr_t)lck, codeptr); } #endif #endif // KMP_USE_DYNAMIC_LOCK } /* release the lock */ void __kmpc_unset_nest_lock(ident_t *loc, kmp_int32 gtid, void **user_lock) { #if KMP_USE_DYNAMIC_LOCK #if USE_ITT_BUILD __kmp_itt_lock_releasing((kmp_user_lock_p)user_lock); #endif int release_status = KMP_D_LOCK_FUNC(user_lock, unset)((kmp_dyna_lock_t *)user_lock, gtid); (void)release_status; #if OMPT_SUPPORT && OMPT_OPTIONAL // This is the case, if called from omp_init_lock_with_hint: void *codeptr = OMPT_LOAD_RETURN_ADDRESS(gtid); if (!codeptr) codeptr = OMPT_GET_RETURN_ADDRESS(0); if (ompt_enabled.enabled) { if (release_status == KMP_LOCK_RELEASED) { if (ompt_enabled.ompt_callback_mutex_released) { // release_lock_last ompt_callbacks.ompt_callback(ompt_callback_mutex_released)( ompt_mutex_nest_lock, (ompt_wait_id_t)(uintptr_t)user_lock, codeptr); } } else if (ompt_enabled.ompt_callback_nest_lock) { // release_lock_prev ompt_callbacks.ompt_callback(ompt_callback_nest_lock)( ompt_scope_end, (ompt_wait_id_t)(uintptr_t)user_lock, codeptr); } } #endif #else // KMP_USE_DYNAMIC_LOCK kmp_user_lock_p lck; /* Can't use serial interval since not block structured */ if ((__kmp_user_lock_kind == lk_tas) && (sizeof(lck->tas.lk.poll) + sizeof(lck->tas.lk.depth_locked) <= OMP_NEST_LOCK_T_SIZE)) { #if KMP_OS_LINUX && \ (KMP_ARCH_X86 || KMP_ARCH_X86_64 || KMP_ARCH_ARM || KMP_ARCH_AARCH64) // "fast" path implemented to fix customer performance issue kmp_tas_lock_t *tl = (kmp_tas_lock_t *)user_lock; #if USE_ITT_BUILD __kmp_itt_lock_releasing((kmp_user_lock_p)user_lock); #endif /* USE_ITT_BUILD */ #if OMPT_SUPPORT && OMPT_OPTIONAL int release_status = KMP_LOCK_STILL_HELD; #endif if (--(tl->lk.depth_locked) == 0) { TCW_4(tl->lk.poll, 0); #if OMPT_SUPPORT && OMPT_OPTIONAL release_status = KMP_LOCK_RELEASED; #endif } KMP_MB(); #if OMPT_SUPPORT && OMPT_OPTIONAL // This is the case, if called from omp_init_lock_with_hint: void *codeptr = OMPT_LOAD_RETURN_ADDRESS(gtid); if (!codeptr) codeptr = OMPT_GET_RETURN_ADDRESS(0); if (ompt_enabled.enabled) { if (release_status == KMP_LOCK_RELEASED) { if (ompt_enabled.ompt_callback_mutex_released) { // release_lock_last ompt_callbacks.ompt_callback(ompt_callback_mutex_released)( ompt_mutex_nest_lock, (ompt_wait_id_t)(uintptr_t)lck, codeptr); } } else if (ompt_enabled.ompt_callback_nest_lock) { // release_lock_previous ompt_callbacks.ompt_callback(ompt_callback_nest_lock)( ompt_mutex_scope_end, (ompt_wait_id_t)(uintptr_t)lck, codeptr); } } #endif return; #else lck = (kmp_user_lock_p)user_lock; #endif } #if KMP_USE_FUTEX else if ((__kmp_user_lock_kind == lk_futex) && (sizeof(lck->futex.lk.poll) + sizeof(lck->futex.lk.depth_locked) <= OMP_NEST_LOCK_T_SIZE)) { lck = (kmp_user_lock_p)user_lock; } #endif else { lck = __kmp_lookup_user_lock(user_lock, "omp_unset_nest_lock"); } #if USE_ITT_BUILD __kmp_itt_lock_releasing(lck); #endif /* USE_ITT_BUILD */ int release_status; release_status = RELEASE_NESTED_LOCK(lck, gtid); #if OMPT_SUPPORT && OMPT_OPTIONAL // This is the case, if called from omp_init_lock_with_hint: void *codeptr = OMPT_LOAD_RETURN_ADDRESS(gtid); if (!codeptr) codeptr = OMPT_GET_RETURN_ADDRESS(0); if (ompt_enabled.enabled) { if (release_status == KMP_LOCK_RELEASED) { if (ompt_enabled.ompt_callback_mutex_released) { // release_lock_last ompt_callbacks.ompt_callback(ompt_callback_mutex_released)( ompt_mutex_nest_lock, (ompt_wait_id_t)(uintptr_t)lck, codeptr); } } else if (ompt_enabled.ompt_callback_nest_lock) { // release_lock_previous ompt_callbacks.ompt_callback(ompt_callback_nest_lock)( ompt_mutex_scope_end, (ompt_wait_id_t)(uintptr_t)lck, codeptr); } } #endif #endif // KMP_USE_DYNAMIC_LOCK } /* try to acquire the lock */ int __kmpc_test_lock(ident_t *loc, kmp_int32 gtid, void **user_lock) { KMP_COUNT_BLOCK(OMP_test_lock); #if KMP_USE_DYNAMIC_LOCK int rc; int tag = KMP_EXTRACT_D_TAG(user_lock); #if USE_ITT_BUILD __kmp_itt_lock_acquiring((kmp_user_lock_p)user_lock); #endif #if OMPT_SUPPORT && OMPT_OPTIONAL // This is the case, if called from omp_init_lock_with_hint: void *codeptr = OMPT_LOAD_RETURN_ADDRESS(gtid); if (!codeptr) codeptr = OMPT_GET_RETURN_ADDRESS(0); if (ompt_enabled.ompt_callback_mutex_acquire) { ompt_callbacks.ompt_callback(ompt_callback_mutex_acquire)( ompt_mutex_lock, omp_lock_hint_none, __ompt_get_mutex_impl_type(user_lock), (ompt_wait_id_t)(uintptr_t)user_lock, codeptr); } #endif #if KMP_USE_INLINED_TAS if (tag == locktag_tas && !__kmp_env_consistency_check) { KMP_TEST_TAS_LOCK(user_lock, gtid, rc); } else #elif KMP_USE_INLINED_FUTEX if (tag == locktag_futex && !__kmp_env_consistency_check) { KMP_TEST_FUTEX_LOCK(user_lock, gtid, rc); } else #endif { rc = __kmp_direct_test[tag]((kmp_dyna_lock_t *)user_lock, gtid); } if (rc) { #if USE_ITT_BUILD __kmp_itt_lock_acquired((kmp_user_lock_p)user_lock); #endif #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.ompt_callback_mutex_acquired) { ompt_callbacks.ompt_callback(ompt_callback_mutex_acquired)( ompt_mutex_lock, (ompt_wait_id_t)(uintptr_t)user_lock, codeptr); } #endif return FTN_TRUE; } else { #if USE_ITT_BUILD __kmp_itt_lock_cancelled((kmp_user_lock_p)user_lock); #endif return FTN_FALSE; } #else // KMP_USE_DYNAMIC_LOCK kmp_user_lock_p lck; int rc; if ((__kmp_user_lock_kind == lk_tas) && (sizeof(lck->tas.lk.poll) <= OMP_LOCK_T_SIZE)) { lck = (kmp_user_lock_p)user_lock; } #if KMP_USE_FUTEX else if ((__kmp_user_lock_kind == lk_futex) && (sizeof(lck->futex.lk.poll) <= OMP_LOCK_T_SIZE)) { lck = (kmp_user_lock_p)user_lock; } #endif else { lck = __kmp_lookup_user_lock(user_lock, "omp_test_lock"); } #if USE_ITT_BUILD __kmp_itt_lock_acquiring(lck); #endif /* USE_ITT_BUILD */ #if OMPT_SUPPORT && OMPT_OPTIONAL // This is the case, if called from omp_init_lock_with_hint: void *codeptr = OMPT_LOAD_RETURN_ADDRESS(gtid); if (!codeptr) codeptr = OMPT_GET_RETURN_ADDRESS(0); if (ompt_enabled.ompt_callback_mutex_acquire) { ompt_callbacks.ompt_callback(ompt_callback_mutex_acquire)( ompt_mutex_lock, omp_lock_hint_none, __ompt_get_mutex_impl_type(), (ompt_wait_id_t)(uintptr_t)lck, codeptr); } #endif rc = TEST_LOCK(lck, gtid); #if USE_ITT_BUILD if (rc) { __kmp_itt_lock_acquired(lck); } else { __kmp_itt_lock_cancelled(lck); } #endif /* USE_ITT_BUILD */ #if OMPT_SUPPORT && OMPT_OPTIONAL if (rc && ompt_enabled.ompt_callback_mutex_acquired) { ompt_callbacks.ompt_callback(ompt_callback_mutex_acquired)( ompt_mutex_lock, (ompt_wait_id_t)(uintptr_t)lck, codeptr); } #endif return (rc ? FTN_TRUE : FTN_FALSE); /* Can't use serial interval since not block structured */ #endif // KMP_USE_DYNAMIC_LOCK } /* try to acquire the lock */ int __kmpc_test_nest_lock(ident_t *loc, kmp_int32 gtid, void **user_lock) { #if KMP_USE_DYNAMIC_LOCK int rc; #if USE_ITT_BUILD __kmp_itt_lock_acquiring((kmp_user_lock_p)user_lock); #endif #if OMPT_SUPPORT && OMPT_OPTIONAL // This is the case, if called from omp_init_lock_with_hint: void *codeptr = OMPT_LOAD_RETURN_ADDRESS(gtid); if (!codeptr) codeptr = OMPT_GET_RETURN_ADDRESS(0); if (ompt_enabled.ompt_callback_mutex_acquire) { ompt_callbacks.ompt_callback(ompt_callback_mutex_acquire)( ompt_mutex_nest_lock, omp_lock_hint_none, __ompt_get_mutex_impl_type(user_lock), (ompt_wait_id_t)(uintptr_t)user_lock, codeptr); } #endif rc = KMP_D_LOCK_FUNC(user_lock, test)((kmp_dyna_lock_t *)user_lock, gtid); #if USE_ITT_BUILD if (rc) { __kmp_itt_lock_acquired((kmp_user_lock_p)user_lock); } else { __kmp_itt_lock_cancelled((kmp_user_lock_p)user_lock); } #endif #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.enabled && rc) { if (rc == 1) { if (ompt_enabled.ompt_callback_mutex_acquired) { // lock_first ompt_callbacks.ompt_callback(ompt_callback_mutex_acquired)( ompt_mutex_nest_lock, (ompt_wait_id_t)(uintptr_t)user_lock, codeptr); } } else { if (ompt_enabled.ompt_callback_nest_lock) { // lock_next ompt_callbacks.ompt_callback(ompt_callback_nest_lock)( ompt_scope_begin, (ompt_wait_id_t)(uintptr_t)user_lock, codeptr); } } } #endif return rc; #else // KMP_USE_DYNAMIC_LOCK kmp_user_lock_p lck; int rc; if ((__kmp_user_lock_kind == lk_tas) && (sizeof(lck->tas.lk.poll) + sizeof(lck->tas.lk.depth_locked) <= OMP_NEST_LOCK_T_SIZE)) { lck = (kmp_user_lock_p)user_lock; } #if KMP_USE_FUTEX else if ((__kmp_user_lock_kind == lk_futex) && (sizeof(lck->futex.lk.poll) + sizeof(lck->futex.lk.depth_locked) <= OMP_NEST_LOCK_T_SIZE)) { lck = (kmp_user_lock_p)user_lock; } #endif else { lck = __kmp_lookup_user_lock(user_lock, "omp_test_nest_lock"); } #if USE_ITT_BUILD __kmp_itt_lock_acquiring(lck); #endif /* USE_ITT_BUILD */ #if OMPT_SUPPORT && OMPT_OPTIONAL // This is the case, if called from omp_init_lock_with_hint: void *codeptr = OMPT_LOAD_RETURN_ADDRESS(gtid); if (!codeptr) codeptr = OMPT_GET_RETURN_ADDRESS(0); if (ompt_enabled.enabled) && ompt_enabled.ompt_callback_mutex_acquire) { ompt_callbacks.ompt_callback(ompt_callback_mutex_acquire)( ompt_mutex_nest_lock, omp_lock_hint_none, __ompt_get_mutex_impl_type(), (ompt_wait_id_t)(uintptr_t)lck, codeptr); } #endif rc = TEST_NESTED_LOCK(lck, gtid); #if USE_ITT_BUILD if (rc) { __kmp_itt_lock_acquired(lck); } else { __kmp_itt_lock_cancelled(lck); } #endif /* USE_ITT_BUILD */ #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.enabled && rc) { if (rc == 1) { if (ompt_enabled.ompt_callback_mutex_acquired) { // lock_first ompt_callbacks.ompt_callback(ompt_callback_mutex_acquired)( ompt_mutex_nest_lock, (ompt_wait_id_t)(uintptr_t)lck, codeptr); } } else { if (ompt_enabled.ompt_callback_nest_lock) { // lock_next ompt_callbacks.ompt_callback(ompt_callback_nest_lock)( ompt_mutex_scope_begin, (ompt_wait_id_t)(uintptr_t)lck, codeptr); } } } #endif return rc; /* Can't use serial interval since not block structured */ #endif // KMP_USE_DYNAMIC_LOCK } // Interface to fast scalable reduce methods routines // keep the selected method in a thread local structure for cross-function // usage: will be used in __kmpc_end_reduce* functions; // another solution: to re-determine the method one more time in // __kmpc_end_reduce* functions (new prototype required then) // AT: which solution is better? #define __KMP_SET_REDUCTION_METHOD(gtid, rmethod) \ ((__kmp_threads[(gtid)]->th.th_local.packed_reduction_method) = (rmethod)) #define __KMP_GET_REDUCTION_METHOD(gtid) \ (__kmp_threads[(gtid)]->th.th_local.packed_reduction_method) // description of the packed_reduction_method variable: look at the macros in // kmp.h // used in a critical section reduce block static __forceinline void __kmp_enter_critical_section_reduce_block(ident_t *loc, kmp_int32 global_tid, kmp_critical_name *crit) { // this lock was visible to a customer and to the threading profile tool as a // serial overhead span (although it's used for an internal purpose only) // why was it visible in previous implementation? // should we keep it visible in new reduce block? kmp_user_lock_p lck; #if KMP_USE_DYNAMIC_LOCK kmp_dyna_lock_t *lk = (kmp_dyna_lock_t *)crit; // Check if it is initialized. if (*lk == 0) { if (KMP_IS_D_LOCK(__kmp_user_lock_seq)) { KMP_COMPARE_AND_STORE_ACQ32((volatile kmp_int32 *)crit, 0, KMP_GET_D_TAG(__kmp_user_lock_seq)); } else { __kmp_init_indirect_csptr(crit, loc, global_tid, KMP_GET_I_TAG(__kmp_user_lock_seq)); } } // Branch for accessing the actual lock object and set operation. This // branching is inevitable since this lock initialization does not follow the // normal dispatch path (lock table is not used). if (KMP_EXTRACT_D_TAG(lk) != 0) { lck = (kmp_user_lock_p)lk; KMP_DEBUG_ASSERT(lck != NULL); if (__kmp_env_consistency_check) { __kmp_push_sync(global_tid, ct_critical, loc, lck, __kmp_user_lock_seq); } KMP_D_LOCK_FUNC(lk, set)(lk, global_tid); } else { kmp_indirect_lock_t *ilk = *((kmp_indirect_lock_t **)lk); lck = ilk->lock; KMP_DEBUG_ASSERT(lck != NULL); if (__kmp_env_consistency_check) { __kmp_push_sync(global_tid, ct_critical, loc, lck, __kmp_user_lock_seq); } KMP_I_LOCK_FUNC(ilk, set)(lck, global_tid); } #else // KMP_USE_DYNAMIC_LOCK // We know that the fast reduction code is only emitted by Intel compilers // with 32 byte critical sections. If there isn't enough space, then we // have to use a pointer. if (__kmp_base_user_lock_size <= INTEL_CRITICAL_SIZE) { lck = (kmp_user_lock_p)crit; } else { lck = __kmp_get_critical_section_ptr(crit, loc, global_tid); } KMP_DEBUG_ASSERT(lck != NULL); if (__kmp_env_consistency_check) __kmp_push_sync(global_tid, ct_critical, loc, lck); __kmp_acquire_user_lock_with_checks(lck, global_tid); #endif // KMP_USE_DYNAMIC_LOCK } // used in a critical section reduce block static __forceinline void __kmp_end_critical_section_reduce_block(ident_t *loc, kmp_int32 global_tid, kmp_critical_name *crit) { kmp_user_lock_p lck; #if KMP_USE_DYNAMIC_LOCK if (KMP_IS_D_LOCK(__kmp_user_lock_seq)) { lck = (kmp_user_lock_p)crit; if (__kmp_env_consistency_check) __kmp_pop_sync(global_tid, ct_critical, loc); KMP_D_LOCK_FUNC(lck, unset)((kmp_dyna_lock_t *)lck, global_tid); } else { kmp_indirect_lock_t *ilk = (kmp_indirect_lock_t *)TCR_PTR(*((kmp_indirect_lock_t **)crit)); if (__kmp_env_consistency_check) __kmp_pop_sync(global_tid, ct_critical, loc); KMP_I_LOCK_FUNC(ilk, unset)(ilk->lock, global_tid); } #else // KMP_USE_DYNAMIC_LOCK // We know that the fast reduction code is only emitted by Intel compilers // with 32 byte critical sections. If there isn't enough space, then we have // to use a pointer. if (__kmp_base_user_lock_size > 32) { lck = *((kmp_user_lock_p *)crit); KMP_ASSERT(lck != NULL); } else { lck = (kmp_user_lock_p)crit; } if (__kmp_env_consistency_check) __kmp_pop_sync(global_tid, ct_critical, loc); __kmp_release_user_lock_with_checks(lck, global_tid); #endif // KMP_USE_DYNAMIC_LOCK } // __kmp_end_critical_section_reduce_block static __forceinline int __kmp_swap_teams_for_teams_reduction(kmp_info_t *th, kmp_team_t **team_p, int *task_state) { kmp_team_t *team; // Check if we are inside the teams construct? if (th->th.th_teams_microtask) { *team_p = team = th->th.th_team; if (team->t.t_level == th->th.th_teams_level) { // This is reduction at teams construct. KMP_DEBUG_ASSERT(!th->th.th_info.ds.ds_tid); // AC: check that tid == 0 // Let's swap teams temporarily for the reduction. th->th.th_info.ds.ds_tid = team->t.t_master_tid; th->th.th_team = team->t.t_parent; th->th.th_team_nproc = th->th.th_team->t.t_nproc; th->th.th_task_team = th->th.th_team->t.t_task_team[0]; *task_state = th->th.th_task_state; th->th.th_task_state = 0; return 1; } } return 0; } static __forceinline void __kmp_restore_swapped_teams(kmp_info_t *th, kmp_team_t *team, int task_state) { // Restore thread structure swapped in __kmp_swap_teams_for_teams_reduction. th->th.th_info.ds.ds_tid = 0; th->th.th_team = team; th->th.th_team_nproc = team->t.t_nproc; th->th.th_task_team = team->t.t_task_team[task_state]; __kmp_type_convert(task_state, &(th->th.th_task_state)); } /* 2.a.i. Reduce Block without a terminating barrier */ /*! @ingroup SYNCHRONIZATION @param loc source location information @param global_tid global thread number @param num_vars number of items (variables) to be reduced @param reduce_size size of data in bytes to be reduced @param reduce_data pointer to data to be reduced @param reduce_func callback function providing reduction operation on two operands and returning result of reduction in lhs_data @param lck pointer to the unique lock data structure @result 1 for the primary thread, 0 for all other team threads, 2 for all team threads if atomic reduction needed The nowait version is used for a reduce clause with the nowait argument. */ kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32 global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck) { KMP_COUNT_BLOCK(REDUCE_nowait); int retval = 0; PACKED_REDUCTION_METHOD_T packed_reduction_method; kmp_info_t *th; kmp_team_t *team; int teams_swapped = 0, task_state; KA_TRACE(10, ("__kmpc_reduce_nowait() enter: called T#%d\n", global_tid)); __kmp_assert_valid_gtid(global_tid); // why do we need this initialization here at all? // Reduction clause can not be used as a stand-alone directive. // do not call __kmp_serial_initialize(), it will be called by // __kmp_parallel_initialize() if needed // possible detection of false-positive race by the threadchecker ??? if (!TCR_4(__kmp_init_parallel)) __kmp_parallel_initialize(); __kmp_resume_if_soft_paused(); // check correctness of reduce block nesting #if KMP_USE_DYNAMIC_LOCK if (__kmp_env_consistency_check) __kmp_push_sync(global_tid, ct_reduce, loc, NULL, 0); #else if (__kmp_env_consistency_check) __kmp_push_sync(global_tid, ct_reduce, loc, NULL); #endif th = __kmp_thread_from_gtid(global_tid); teams_swapped = __kmp_swap_teams_for_teams_reduction(th, &team, &task_state); // packed_reduction_method value will be reused by __kmp_end_reduce* function, // the value should be kept in a variable // the variable should be either a construct-specific or thread-specific // property, not a team specific property // (a thread can reach the next reduce block on the next construct, reduce // method may differ on the next construct) // an ident_t "loc" parameter could be used as a construct-specific property // (what if loc == 0?) // (if both construct-specific and team-specific variables were shared, // then unness extra syncs should be needed) // a thread-specific variable is better regarding two issues above (next // construct and extra syncs) // a thread-specific "th_local.reduction_method" variable is used currently // each thread executes 'determine' and 'set' lines (no need to execute by one // thread, to avoid unness extra syncs) packed_reduction_method = __kmp_determine_reduction_method( loc, global_tid, num_vars, reduce_size, reduce_data, reduce_func, lck); __KMP_SET_REDUCTION_METHOD(global_tid, packed_reduction_method); OMPT_REDUCTION_DECL(th, global_tid); if (packed_reduction_method == critical_reduce_block) { OMPT_REDUCTION_BEGIN; __kmp_enter_critical_section_reduce_block(loc, global_tid, lck); retval = 1; } else if (packed_reduction_method == empty_reduce_block) { OMPT_REDUCTION_BEGIN; // usage: if team size == 1, no synchronization is required ( Intel // platforms only ) retval = 1; } else if (packed_reduction_method == atomic_reduce_block) { retval = 2; // all threads should do this pop here (because __kmpc_end_reduce_nowait() // won't be called by the code gen) // (it's not quite good, because the checking block has been closed by // this 'pop', // but atomic operation has not been executed yet, will be executed // slightly later, literally on next instruction) if (__kmp_env_consistency_check) __kmp_pop_sync(global_tid, ct_reduce, loc); } else if (TEST_REDUCTION_METHOD(packed_reduction_method, tree_reduce_block)) { // AT: performance issue: a real barrier here // AT: (if primary thread is slow, other threads are blocked here waiting for // the primary thread to come and release them) // AT: (it's not what a customer might expect specifying NOWAIT clause) // AT: (specifying NOWAIT won't result in improvement of performance, it'll // be confusing to a customer) // AT: another implementation of *barrier_gather*nowait() (or some other design) // might go faster and be more in line with sense of NOWAIT // AT: TO DO: do epcc test and compare times // this barrier should be invisible to a customer and to the threading profile // tool (it's neither a terminating barrier nor customer's code, it's // used for an internal purpose) #if OMPT_SUPPORT // JP: can this barrier potentially leed to task scheduling? // JP: as long as there is a barrier in the implementation, OMPT should and // will provide the barrier events // so we set-up the necessary frame/return addresses. ompt_frame_t *ompt_frame; if (ompt_enabled.enabled) { __ompt_get_task_info_internal(0, NULL, NULL, &ompt_frame, NULL, NULL); if (ompt_frame->enter_frame.ptr == NULL) ompt_frame->enter_frame.ptr = OMPT_GET_FRAME_ADDRESS(0); } OMPT_STORE_RETURN_ADDRESS(global_tid); #endif #if USE_ITT_NOTIFY __kmp_threads[global_tid]->th.th_ident = loc; #endif retval = __kmp_barrier(UNPACK_REDUCTION_BARRIER(packed_reduction_method), global_tid, FALSE, reduce_size, reduce_data, reduce_func); retval = (retval != 0) ? (0) : (1); #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.enabled) { ompt_frame->enter_frame = ompt_data_none; } #endif // all other workers except primary thread should do this pop here // ( none of other workers will get to __kmpc_end_reduce_nowait() ) if (__kmp_env_consistency_check) { if (retval == 0) { __kmp_pop_sync(global_tid, ct_reduce, loc); } } } else { // should never reach this block KMP_ASSERT(0); // "unexpected method" } if (teams_swapped) { __kmp_restore_swapped_teams(th, team, task_state); } KA_TRACE( 10, ("__kmpc_reduce_nowait() exit: called T#%d: method %08x, returns %08x\n", global_tid, packed_reduction_method, retval)); return retval; } /*! @ingroup SYNCHRONIZATION @param loc source location information @param global_tid global thread id. @param lck pointer to the unique lock data structure Finish the execution of a reduce nowait. */ void __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid, kmp_critical_name *lck) { PACKED_REDUCTION_METHOD_T packed_reduction_method; KA_TRACE(10, ("__kmpc_end_reduce_nowait() enter: called T#%d\n", global_tid)); __kmp_assert_valid_gtid(global_tid); packed_reduction_method = __KMP_GET_REDUCTION_METHOD(global_tid); OMPT_REDUCTION_DECL(__kmp_thread_from_gtid(global_tid), global_tid); if (packed_reduction_method == critical_reduce_block) { __kmp_end_critical_section_reduce_block(loc, global_tid, lck); OMPT_REDUCTION_END; } else if (packed_reduction_method == empty_reduce_block) { // usage: if team size == 1, no synchronization is required ( on Intel // platforms only ) OMPT_REDUCTION_END; } else if (packed_reduction_method == atomic_reduce_block) { // neither primary thread nor other workers should get here // (code gen does not generate this call in case 2: atomic reduce block) // actually it's better to remove this elseif at all; // after removal this value will checked by the 'else' and will assert } else if (TEST_REDUCTION_METHOD(packed_reduction_method, tree_reduce_block)) { // only primary thread gets here // OMPT: tree reduction is annotated in the barrier code } else { // should never reach this block KMP_ASSERT(0); // "unexpected method" } if (__kmp_env_consistency_check) __kmp_pop_sync(global_tid, ct_reduce, loc); KA_TRACE(10, ("__kmpc_end_reduce_nowait() exit: called T#%d: method %08x\n", global_tid, packed_reduction_method)); return; } /* 2.a.ii. Reduce Block with a terminating barrier */ /*! @ingroup SYNCHRONIZATION @param loc source location information @param global_tid global thread number @param num_vars number of items (variables) to be reduced @param reduce_size size of data in bytes to be reduced @param reduce_data pointer to data to be reduced @param reduce_func callback function providing reduction operation on two operands and returning result of reduction in lhs_data @param lck pointer to the unique lock data structure @result 1 for the primary thread, 0 for all other team threads, 2 for all team threads if atomic reduction needed A blocking reduce that includes an implicit barrier. */ kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck) { KMP_COUNT_BLOCK(REDUCE_wait); int retval = 0; PACKED_REDUCTION_METHOD_T packed_reduction_method; kmp_info_t *th; kmp_team_t *team; int teams_swapped = 0, task_state; KA_TRACE(10, ("__kmpc_reduce() enter: called T#%d\n", global_tid)); __kmp_assert_valid_gtid(global_tid); // why do we need this initialization here at all? // Reduction clause can not be a stand-alone directive. // do not call __kmp_serial_initialize(), it will be called by // __kmp_parallel_initialize() if needed // possible detection of false-positive race by the threadchecker ??? if (!TCR_4(__kmp_init_parallel)) __kmp_parallel_initialize(); __kmp_resume_if_soft_paused(); // check correctness of reduce block nesting #if KMP_USE_DYNAMIC_LOCK if (__kmp_env_consistency_check) __kmp_push_sync(global_tid, ct_reduce, loc, NULL, 0); #else if (__kmp_env_consistency_check) __kmp_push_sync(global_tid, ct_reduce, loc, NULL); #endif th = __kmp_thread_from_gtid(global_tid); teams_swapped = __kmp_swap_teams_for_teams_reduction(th, &team, &task_state); packed_reduction_method = __kmp_determine_reduction_method( loc, global_tid, num_vars, reduce_size, reduce_data, reduce_func, lck); __KMP_SET_REDUCTION_METHOD(global_tid, packed_reduction_method); OMPT_REDUCTION_DECL(th, global_tid); if (packed_reduction_method == critical_reduce_block) { OMPT_REDUCTION_BEGIN; __kmp_enter_critical_section_reduce_block(loc, global_tid, lck); retval = 1; } else if (packed_reduction_method == empty_reduce_block) { OMPT_REDUCTION_BEGIN; // usage: if team size == 1, no synchronization is required ( Intel // platforms only ) retval = 1; } else if (packed_reduction_method == atomic_reduce_block) { retval = 2; } else if (TEST_REDUCTION_METHOD(packed_reduction_method, tree_reduce_block)) { // case tree_reduce_block: // this barrier should be visible to a customer and to the threading profile // tool (it's a terminating barrier on constructs if NOWAIT not specified) #if OMPT_SUPPORT ompt_frame_t *ompt_frame; if (ompt_enabled.enabled) { __ompt_get_task_info_internal(0, NULL, NULL, &ompt_frame, NULL, NULL); if (ompt_frame->enter_frame.ptr == NULL) ompt_frame->enter_frame.ptr = OMPT_GET_FRAME_ADDRESS(0); } OMPT_STORE_RETURN_ADDRESS(global_tid); #endif #if USE_ITT_NOTIFY __kmp_threads[global_tid]->th.th_ident = loc; // needed for correct notification of frames #endif retval = __kmp_barrier(UNPACK_REDUCTION_BARRIER(packed_reduction_method), global_tid, TRUE, reduce_size, reduce_data, reduce_func); retval = (retval != 0) ? (0) : (1); #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.enabled) { ompt_frame->enter_frame = ompt_data_none; } #endif // all other workers except primary thread should do this pop here // (none of other workers except primary will enter __kmpc_end_reduce()) if (__kmp_env_consistency_check) { if (retval == 0) { // 0: all other workers; 1: primary thread __kmp_pop_sync(global_tid, ct_reduce, loc); } } } else { // should never reach this block KMP_ASSERT(0); // "unexpected method" } if (teams_swapped) { __kmp_restore_swapped_teams(th, team, task_state); } KA_TRACE(10, ("__kmpc_reduce() exit: called T#%d: method %08x, returns %08x\n", global_tid, packed_reduction_method, retval)); return retval; } /*! @ingroup SYNCHRONIZATION @param loc source location information @param global_tid global thread id. @param lck pointer to the unique lock data structure Finish the execution of a blocking reduce. The <tt>lck</tt> pointer must be the same as that used in the corresponding start function. */ void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid, kmp_critical_name *lck) { PACKED_REDUCTION_METHOD_T packed_reduction_method; kmp_info_t *th; kmp_team_t *team; int teams_swapped = 0, task_state; KA_TRACE(10, ("__kmpc_end_reduce() enter: called T#%d\n", global_tid)); __kmp_assert_valid_gtid(global_tid); th = __kmp_thread_from_gtid(global_tid); teams_swapped = __kmp_swap_teams_for_teams_reduction(th, &team, &task_state); packed_reduction_method = __KMP_GET_REDUCTION_METHOD(global_tid); // this barrier should be visible to a customer and to the threading profile // tool (it's a terminating barrier on constructs if NOWAIT not specified) OMPT_REDUCTION_DECL(th, global_tid); if (packed_reduction_method == critical_reduce_block) { __kmp_end_critical_section_reduce_block(loc, global_tid, lck); OMPT_REDUCTION_END; // TODO: implicit barrier: should be exposed #if OMPT_SUPPORT ompt_frame_t *ompt_frame; if (ompt_enabled.enabled) { __ompt_get_task_info_internal(0, NULL, NULL, &ompt_frame, NULL, NULL); if (ompt_frame->enter_frame.ptr == NULL) ompt_frame->enter_frame.ptr = OMPT_GET_FRAME_ADDRESS(0); } OMPT_STORE_RETURN_ADDRESS(global_tid); #endif #if USE_ITT_NOTIFY __kmp_threads[global_tid]->th.th_ident = loc; #endif __kmp_barrier(bs_plain_barrier, global_tid, FALSE, 0, NULL, NULL); #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.enabled) { ompt_frame->enter_frame = ompt_data_none; } #endif } else if (packed_reduction_method == empty_reduce_block) { OMPT_REDUCTION_END; // usage: if team size==1, no synchronization is required (Intel platforms only) // TODO: implicit barrier: should be exposed #if OMPT_SUPPORT ompt_frame_t *ompt_frame; if (ompt_enabled.enabled) { __ompt_get_task_info_internal(0, NULL, NULL, &ompt_frame, NULL, NULL); if (ompt_frame->enter_frame.ptr == NULL) ompt_frame->enter_frame.ptr = OMPT_GET_FRAME_ADDRESS(0); } OMPT_STORE_RETURN_ADDRESS(global_tid); #endif #if USE_ITT_NOTIFY __kmp_threads[global_tid]->th.th_ident = loc; #endif __kmp_barrier(bs_plain_barrier, global_tid, FALSE, 0, NULL, NULL); #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.enabled) { ompt_frame->enter_frame = ompt_data_none; } #endif } else if (packed_reduction_method == atomic_reduce_block) { #if OMPT_SUPPORT ompt_frame_t *ompt_frame; if (ompt_enabled.enabled) { __ompt_get_task_info_internal(0, NULL, NULL, &ompt_frame, NULL, NULL); if (ompt_frame->enter_frame.ptr == NULL) ompt_frame->enter_frame.ptr = OMPT_GET_FRAME_ADDRESS(0); } OMPT_STORE_RETURN_ADDRESS(global_tid); #endif // TODO: implicit barrier: should be exposed #if USE_ITT_NOTIFY __kmp_threads[global_tid]->th.th_ident = loc; #endif __kmp_barrier(bs_plain_barrier, global_tid, FALSE, 0, NULL, NULL); #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.enabled) { ompt_frame->enter_frame = ompt_data_none; } #endif } else if (TEST_REDUCTION_METHOD(packed_reduction_method, tree_reduce_block)) { // only primary thread executes here (primary releases all other workers) __kmp_end_split_barrier(UNPACK_REDUCTION_BARRIER(packed_reduction_method), global_tid); } else { // should never reach this block KMP_ASSERT(0); // "unexpected method" } if (teams_swapped) { __kmp_restore_swapped_teams(th, team, task_state); } if (__kmp_env_consistency_check) __kmp_pop_sync(global_tid, ct_reduce, loc); KA_TRACE(10, ("__kmpc_end_reduce() exit: called T#%d: method %08x\n", global_tid, packed_reduction_method)); return; } #undef __KMP_GET_REDUCTION_METHOD #undef __KMP_SET_REDUCTION_METHOD /* end of interface to fast scalable reduce routines */ kmp_uint64 __kmpc_get_taskid() { kmp_int32 gtid; kmp_info_t *thread; gtid = __kmp_get_gtid(); if (gtid < 0) { return 0; } thread = __kmp_thread_from_gtid(gtid); return thread->th.th_current_task->td_task_id; } // __kmpc_get_taskid kmp_uint64 __kmpc_get_parent_taskid() { kmp_int32 gtid; kmp_info_t *thread; kmp_taskdata_t *parent_task; gtid = __kmp_get_gtid(); if (gtid < 0) { return 0; } thread = __kmp_thread_from_gtid(gtid); parent_task = thread->th.th_current_task->td_parent; return (parent_task == NULL ? 0 : parent_task->td_task_id); } // __kmpc_get_parent_taskid /*! @ingroup WORK_SHARING @param loc source location information. @param gtid global thread number. @param num_dims number of associated doacross loops. @param dims info on loops bounds. Initialize doacross loop information. Expect compiler send us inclusive bounds, e.g. for(i=2;i<9;i+=2) lo=2, up=8, st=2. */ void __kmpc_doacross_init(ident_t *loc, int gtid, int num_dims, const struct kmp_dim *dims) { __kmp_assert_valid_gtid(gtid); int j, idx; kmp_int64 last, trace_count; kmp_info_t *th = __kmp_threads[gtid]; kmp_team_t *team = th->th.th_team; kmp_uint32 *flags; kmp_disp_t *pr_buf = th->th.th_dispatch; dispatch_shared_info_t *sh_buf; KA_TRACE( 20, ("__kmpc_doacross_init() enter: called T#%d, num dims %d, active %d\n", gtid, num_dims, !team->t.t_serialized)); KMP_DEBUG_ASSERT(dims != NULL); KMP_DEBUG_ASSERT(num_dims > 0); if (team->t.t_serialized) { KA_TRACE(20, ("__kmpc_doacross_init() exit: serialized team\n")); return; // no dependencies if team is serialized } KMP_DEBUG_ASSERT(team->t.t_nproc > 1); idx = pr_buf->th_doacross_buf_idx++; // Increment index of shared buffer for // the next loop sh_buf = &team->t.t_disp_buffer[idx % __kmp_dispatch_num_buffers]; // Save bounds info into allocated private buffer KMP_DEBUG_ASSERT(pr_buf->th_doacross_info == NULL); pr_buf->th_doacross_info = (kmp_int64 *)__kmp_thread_malloc( th, sizeof(kmp_int64) * (4 * num_dims + 1)); KMP_DEBUG_ASSERT(pr_buf->th_doacross_info != NULL); pr_buf->th_doacross_info[0] = (kmp_int64)num_dims; // first element is number of dimensions // Save also address of num_done in order to access it later without knowing // the buffer index pr_buf->th_doacross_info[1] = (kmp_int64)&sh_buf->doacross_num_done; pr_buf->th_doacross_info[2] = dims[0].lo; pr_buf->th_doacross_info[3] = dims[0].up; pr_buf->th_doacross_info[4] = dims[0].st; last = 5; for (j = 1; j < num_dims; ++j) { kmp_int64 range_length; // To keep ranges of all dimensions but the first dims[0] if (dims[j].st == 1) { // most common case // AC: should we care of ranges bigger than LLONG_MAX? (not for now) range_length = dims[j].up - dims[j].lo + 1; } else { if (dims[j].st > 0) { KMP_DEBUG_ASSERT(dims[j].up > dims[j].lo); range_length = (kmp_uint64)(dims[j].up - dims[j].lo) / dims[j].st + 1; } else { // negative increment KMP_DEBUG_ASSERT(dims[j].lo > dims[j].up); range_length = (kmp_uint64)(dims[j].lo - dims[j].up) / (-dims[j].st) + 1; } } pr_buf->th_doacross_info[last++] = range_length; pr_buf->th_doacross_info[last++] = dims[j].lo; pr_buf->th_doacross_info[last++] = dims[j].up; pr_buf->th_doacross_info[last++] = dims[j].st; } // Compute total trip count. // Start with range of dims[0] which we don't need to keep in the buffer. if (dims[0].st == 1) { // most common case trace_count = dims[0].up - dims[0].lo + 1; } else if (dims[0].st > 0) { KMP_DEBUG_ASSERT(dims[0].up > dims[0].lo); trace_count = (kmp_uint64)(dims[0].up - dims[0].lo) / dims[0].st + 1; } else { // negative increment KMP_DEBUG_ASSERT(dims[0].lo > dims[0].up); trace_count = (kmp_uint64)(dims[0].lo - dims[0].up) / (-dims[0].st) + 1; } for (j = 1; j < num_dims; ++j) { trace_count *= pr_buf->th_doacross_info[4 * j + 1]; // use kept ranges } KMP_DEBUG_ASSERT(trace_count > 0); // Check if shared buffer is not occupied by other loop (idx - // __kmp_dispatch_num_buffers) if (idx != sh_buf->doacross_buf_idx) { // Shared buffer is occupied, wait for it to be free __kmp_wait_4((volatile kmp_uint32 *)&sh_buf->doacross_buf_idx, idx, __kmp_eq_4, NULL); } #if KMP_32_BIT_ARCH // Check if we are the first thread. After the CAS the first thread gets 0, // others get 1 if initialization is in progress, allocated pointer otherwise. // Treat pointer as volatile integer (value 0 or 1) until memory is allocated. flags = (kmp_uint32 *)KMP_COMPARE_AND_STORE_RET32( (volatile kmp_int32 *)&sh_buf->doacross_flags, NULL, 1); #else flags = (kmp_uint32 *)KMP_COMPARE_AND_STORE_RET64( (volatile kmp_int64 *)&sh_buf->doacross_flags, NULL, 1LL); #endif if (flags == NULL) { // we are the first thread, allocate the array of flags size_t size = (size_t)trace_count / 8 + 8; // in bytes, use single bit per iteration flags = (kmp_uint32 *)__kmp_thread_calloc(th, size, 1); KMP_MB(); sh_buf->doacross_flags = flags; } else if (flags == (kmp_uint32 *)1) { #if KMP_32_BIT_ARCH // initialization is still in progress, need to wait while (*(volatile kmp_int32 *)&sh_buf->doacross_flags == 1) #else while (*(volatile kmp_int64 *)&sh_buf->doacross_flags == 1LL) #endif KMP_YIELD(TRUE); KMP_MB(); } else { KMP_MB(); } KMP_DEBUG_ASSERT(sh_buf->doacross_flags > (kmp_uint32 *)1); // check ptr value pr_buf->th_doacross_flags = sh_buf->doacross_flags; // save private copy in order to not // touch shared buffer on each iteration KA_TRACE(20, ("__kmpc_doacross_init() exit: T#%d\n", gtid)); } void __kmpc_doacross_wait(ident_t *loc, int gtid, const kmp_int64 *vec) { __kmp_assert_valid_gtid(gtid); kmp_int64 shft; size_t num_dims, i; kmp_uint32 flag; kmp_int64 iter_number; // iteration number of "collapsed" loop nest kmp_info_t *th = __kmp_threads[gtid]; kmp_team_t *team = th->th.th_team; kmp_disp_t *pr_buf; kmp_int64 lo, up, st; KA_TRACE(20, ("__kmpc_doacross_wait() enter: called T#%d\n", gtid)); if (team->t.t_serialized) { KA_TRACE(20, ("__kmpc_doacross_wait() exit: serialized team\n")); return; // no dependencies if team is serialized } // calculate sequential iteration number and check out-of-bounds condition pr_buf = th->th.th_dispatch; KMP_DEBUG_ASSERT(pr_buf->th_doacross_info != NULL); num_dims = (size_t)pr_buf->th_doacross_info[0]; lo = pr_buf->th_doacross_info[2]; up = pr_buf->th_doacross_info[3]; st = pr_buf->th_doacross_info[4]; #if OMPT_SUPPORT && OMPT_OPTIONAL ompt_dependence_t deps[num_dims]; #endif if (st == 1) { // most common case if (vec[0] < lo || vec[0] > up) { KA_TRACE(20, ("__kmpc_doacross_wait() exit: T#%d iter %lld is out of " "bounds [%lld,%lld]\n", gtid, vec[0], lo, up)); return; } iter_number = vec[0] - lo; } else if (st > 0) { if (vec[0] < lo || vec[0] > up) { KA_TRACE(20, ("__kmpc_doacross_wait() exit: T#%d iter %lld is out of " "bounds [%lld,%lld]\n", gtid, vec[0], lo, up)); return; } iter_number = (kmp_uint64)(vec[0] - lo) / st; } else { // negative increment if (vec[0] > lo || vec[0] < up) { KA_TRACE(20, ("__kmpc_doacross_wait() exit: T#%d iter %lld is out of " "bounds [%lld,%lld]\n", gtid, vec[0], lo, up)); return; } iter_number = (kmp_uint64)(lo - vec[0]) / (-st); } #if OMPT_SUPPORT && OMPT_OPTIONAL deps[0].variable.value = iter_number; deps[0].dependence_type = ompt_dependence_type_sink; #endif for (i = 1; i < num_dims; ++i) { kmp_int64 iter, ln; size_t j = i * 4; ln = pr_buf->th_doacross_info[j + 1]; lo = pr_buf->th_doacross_info[j + 2]; up = pr_buf->th_doacross_info[j + 3]; st = pr_buf->th_doacross_info[j + 4]; if (st == 1) { if (vec[i] < lo || vec[i] > up) { KA_TRACE(20, ("__kmpc_doacross_wait() exit: T#%d iter %lld is out of " "bounds [%lld,%lld]\n", gtid, vec[i], lo, up)); return; } iter = vec[i] - lo; } else if (st > 0) { if (vec[i] < lo || vec[i] > up) { KA_TRACE(20, ("__kmpc_doacross_wait() exit: T#%d iter %lld is out of " "bounds [%lld,%lld]\n", gtid, vec[i], lo, up)); return; } iter = (kmp_uint64)(vec[i] - lo) / st; } else { // st < 0 if (vec[i] > lo || vec[i] < up) { KA_TRACE(20, ("__kmpc_doacross_wait() exit: T#%d iter %lld is out of " "bounds [%lld,%lld]\n", gtid, vec[i], lo, up)); return; } iter = (kmp_uint64)(lo - vec[i]) / (-st); } iter_number = iter + ln * iter_number; #if OMPT_SUPPORT && OMPT_OPTIONAL deps[i].variable.value = iter; deps[i].dependence_type = ompt_dependence_type_sink; #endif } shft = iter_number % 32; // use 32-bit granularity iter_number >>= 5; // divided by 32 flag = 1 << shft; while ((flag & pr_buf->th_doacross_flags[iter_number]) == 0) { KMP_YIELD(TRUE); } KMP_MB(); #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.ompt_callback_dependences) { ompt_callbacks.ompt_callback(ompt_callback_dependences)( &(OMPT_CUR_TASK_INFO(th)->task_data), deps, (kmp_uint32)num_dims); } #endif KA_TRACE(20, ("__kmpc_doacross_wait() exit: T#%d wait for iter %lld completed\n", gtid, (iter_number << 5) + shft)); } void __kmpc_doacross_post(ident_t *loc, int gtid, const kmp_int64 *vec) { __kmp_assert_valid_gtid(gtid); kmp_int64 shft; size_t num_dims, i; kmp_uint32 flag; kmp_int64 iter_number; // iteration number of "collapsed" loop nest kmp_info_t *th = __kmp_threads[gtid]; kmp_team_t *team = th->th.th_team; kmp_disp_t *pr_buf; kmp_int64 lo, st; KA_TRACE(20, ("__kmpc_doacross_post() enter: called T#%d\n", gtid)); if (team->t.t_serialized) { KA_TRACE(20, ("__kmpc_doacross_post() exit: serialized team\n")); return; // no dependencies if team is serialized } // calculate sequential iteration number (same as in "wait" but no // out-of-bounds checks) pr_buf = th->th.th_dispatch; KMP_DEBUG_ASSERT(pr_buf->th_doacross_info != NULL); num_dims = (size_t)pr_buf->th_doacross_info[0]; lo = pr_buf->th_doacross_info[2]; st = pr_buf->th_doacross_info[4]; #if OMPT_SUPPORT && OMPT_OPTIONAL ompt_dependence_t deps[num_dims]; #endif if (st == 1) { // most common case iter_number = vec[0] - lo; } else if (st > 0) { iter_number = (kmp_uint64)(vec[0] - lo) / st; } else { // negative increment iter_number = (kmp_uint64)(lo - vec[0]) / (-st); } #if OMPT_SUPPORT && OMPT_OPTIONAL deps[0].variable.value = iter_number; deps[0].dependence_type = ompt_dependence_type_source; #endif for (i = 1; i < num_dims; ++i) { kmp_int64 iter, ln; size_t j = i * 4; ln = pr_buf->th_doacross_info[j + 1]; lo = pr_buf->th_doacross_info[j + 2]; st = pr_buf->th_doacross_info[j + 4]; if (st == 1) { iter = vec[i] - lo; } else if (st > 0) { iter = (kmp_uint64)(vec[i] - lo) / st; } else { // st < 0 iter = (kmp_uint64)(lo - vec[i]) / (-st); } iter_number = iter + ln * iter_number; #if OMPT_SUPPORT && OMPT_OPTIONAL deps[i].variable.value = iter; deps[i].dependence_type = ompt_dependence_type_source; #endif } #if OMPT_SUPPORT && OMPT_OPTIONAL if (ompt_enabled.ompt_callback_dependences) { ompt_callbacks.ompt_callback(ompt_callback_dependences)( &(OMPT_CUR_TASK_INFO(th)->task_data), deps, (kmp_uint32)num_dims); } #endif shft = iter_number % 32; // use 32-bit granularity iter_number >>= 5; // divided by 32 flag = 1 << shft; KMP_MB(); if ((flag & pr_buf->th_doacross_flags[iter_number]) == 0) KMP_TEST_THEN_OR32(&pr_buf->th_doacross_flags[iter_number], flag); KA_TRACE(20, ("__kmpc_doacross_post() exit: T#%d iter %lld posted\n", gtid, (iter_number << 5) + shft)); } void __kmpc_doacross_fini(ident_t *loc, int gtid) { __kmp_assert_valid_gtid(gtid); kmp_int32 num_done; kmp_info_t *th = __kmp_threads[gtid]; kmp_team_t *team = th->th.th_team; kmp_disp_t *pr_buf = th->th.th_dispatch; KA_TRACE(20, ("__kmpc_doacross_fini() enter: called T#%d\n", gtid)); if (team->t.t_serialized) { KA_TRACE(20, ("__kmpc_doacross_fini() exit: serialized team %p\n", team)); return; // nothing to do } num_done = KMP_TEST_THEN_INC32((kmp_uintptr_t)(pr_buf->th_doacross_info[1])) + 1; if (num_done == th->th.th_team_nproc) { // we are the last thread, need to free shared resources int idx = pr_buf->th_doacross_buf_idx - 1; dispatch_shared_info_t *sh_buf = &team->t.t_disp_buffer[idx % __kmp_dispatch_num_buffers]; KMP_DEBUG_ASSERT(pr_buf->th_doacross_info[1] == (kmp_int64)&sh_buf->doacross_num_done); KMP_DEBUG_ASSERT(num_done == sh_buf->doacross_num_done); KMP_DEBUG_ASSERT(idx == sh_buf->doacross_buf_idx); __kmp_thread_free(th, CCAST(kmp_uint32 *, sh_buf->doacross_flags)); sh_buf->doacross_flags = NULL; sh_buf->doacross_num_done = 0; sh_buf->doacross_buf_idx += __kmp_dispatch_num_buffers; // free buffer for future re-use } // free private resources (need to keep buffer index forever) pr_buf->th_doacross_flags = NULL; __kmp_thread_free(th, (void *)pr_buf->th_doacross_info); pr_buf->th_doacross_info = NULL; KA_TRACE(20, ("__kmpc_doacross_fini() exit: T#%d\n", gtid)); } /* omp_alloc/omp_calloc/omp_free only defined for C/C++, not for Fortran */ void *omp_alloc(size_t size, omp_allocator_handle_t allocator) { return __kmpc_alloc(__kmp_entry_gtid(), size, allocator); } void *omp_calloc(size_t nmemb, size_t size, omp_allocator_handle_t allocator) { return __kmpc_calloc(__kmp_entry_gtid(), nmemb, size, allocator); } void *omp_realloc(void *ptr, size_t size, omp_allocator_handle_t allocator, omp_allocator_handle_t free_allocator) { return __kmpc_realloc(__kmp_entry_gtid(), ptr, size, allocator, free_allocator); } void omp_free(void *ptr, omp_allocator_handle_t allocator) { __kmpc_free(__kmp_entry_gtid(), ptr, allocator); } int __kmpc_get_target_offload(void) { if (!__kmp_init_serial) { __kmp_serial_initialize(); } return __kmp_target_offload; } int __kmpc_pause_resource(kmp_pause_status_t level) { if (!__kmp_init_serial) { return 1; // Can't pause if runtime is not initialized } return __kmp_pause_resource(level); }
33.587156
80
0.692762
kubamracek
4f38390b293611523388d4d5f5ae856f4a010f76
4,330
cpp
C++
examples/example-08d-write-hyperslab-using-dsetinfo.cpp
mpb27/h5pp
bd0c70d30329732285b2c06f9dc48795f7d18180
[ "MIT" ]
60
2019-03-11T09:02:49.000Z
2022-02-01T05:42:30.000Z
examples/example-08d-write-hyperslab-using-dsetinfo.cpp
mpb27/h5pp
bd0c70d30329732285b2c06f9dc48795f7d18180
[ "MIT" ]
10
2020-01-24T09:40:53.000Z
2022-03-30T10:56:12.000Z
examples/example-08d-write-hyperslab-using-dsetinfo.cpp
mpb27/h5pp
bd0c70d30329732285b2c06f9dc48795f7d18180
[ "MIT" ]
9
2020-01-24T10:23:43.000Z
2022-01-21T02:34:55.000Z
#include <h5pp/h5pp.h> #include <iostream> // This example shows how to write data into a portion of a dataset, a so-called "hyperslab". // This time we will use a metadata object of type "h5pp::DsetInfo" which is normally returned from .writeDataset(...). // The main motivation is that reusing the h5pp::DsetInfo object in repeated operations (e.g. for loops) avoids costly metadata analysis. /******************************************************************** Note that the HDF5 C-API uses row-major layout! *********************************************************************/ int main() { // Initialize a file h5pp::File file("exampledir/example-08d-write-hyperslab-using-dsetinfo.h5", h5pp::FilePermission::REPLACE); // Initialize a vector with size 25 filled with zeros std::vector<double> data5x5(25, 0); // Write the data to a dataset, but interpret it as a 5x5 matrix (read about reinterpreting dimensions in example 08a) // 0 0 0 0 0 // 0 0 0 0 0 // 0 0 0 0 0 // 0 0 0 0 0 // 0 0 0 0 0 h5pp::DsetInfo dsetInfo = file.writeDataset(data5x5, "data5x5", {5, 5}); // Store the generated metadata about data5x5 in dsetInfo // In this example we would like write a 2x2 matrix // // 1 2 // 3 4 // // into the larger 5x5 matrix, with the top left corner starting at position (1,2), so that we get: // // 0 0 0 0 0 // 0 0 1 2 0 // 0 0 3 4 0 // 0 0 0 0 0 // 0 0 0 0 0 // Initialize the small vector with size 4 filled with 1,2,3,4 which will become our 2x2 matrix std::vector<double> data2x2 = {1, 2, 3, 4}; // Now we need to select a 2x2 hyperslab in data5x5. There are three ways of doing this: // 1) Define a hyperslab and give it to .writeHyperslab(...). (simplest) // 2) Define a hyperslab in an instance of "h5pp::DsetInfo" corresponding to data5x5, and pass to .writeDataset(...) (see example 08e) // 3) Define a hyperslab in an instance of "h5pp::Options" and pass that to .writeDataset(...). (see example 08d) // Let's try 2) here: // NOTE: Internally h5pp populates instances of type h5pp::DsetInfo and h5pp::DataInfo with metadata about // the dataset on file and the given data buffer, respectively. When updating a dataset, it pays to reuse // these metadata objects to avoid repeated analysis of the dataset. // In the following, we make use of the h5pp::DsetInfo object that we just obtained, and make a hyperslab // selection on it before passing it to .writeDataset(...) again. // The following three lines below can be replaced by dsetInfo.dsetSlab = h5pp::Hyperslab({1,2},{2,2}) dsetInfo.dsetSlab = h5pp::Hyperslab(); dsetInfo.dsetSlab->offset = {1, 2}; // The starting point (top left corner of the slab) dsetInfo.dsetSlab->extent = {2, 2}; // The dimensions of data2x2 // The shape of data2x2 can be inferred from the shape of the hyperslab, or be specified in // an optional "h5pp::Options" (as in example 08b) given as the third argument to writeDataset below file.writeDataset(data2x2, dsetInfo); // Print the result auto read5x5 = file.readDataset<std::vector<double>>("data5x5"); h5pp::print("Read 5x5 matrix:\n"); for(size_t row = 0; row < 5ul; row++) { for(size_t col = 0; col < 5; col++) { size_t idx = row * 5 + col; h5pp::print("{} ", read5x5[idx]); } h5pp::print("\n"); } #ifdef H5PP_EIGEN3 // Eigen comes in handy when dealing with matrices // Note 1: h5pp resizes the Eigen container as indicated by the dataset dimensions // Note 2: The rank (number of dimensions) of the Eigen container must agree with the rank of the dataset // Note 3: Eigen uses column-major storage. Internally, h5pp needs to make a transposed copy to transform // the data from row-major to column-major. For very large datasets this operation can be expensive. // In that case consider using row-major Eigen containers, such as // Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic,Eigen::RowMajor> // std::cout << "Read 5x5 Eigen matrix: \n" << file.readDataset<Eigen::MatrixXd>("data5x5") << std::endl; #endif return 0; }
48.651685
138
0.633256
mpb27
4f39836eb4aa857ccb4f4f5990747cc810532923
7,570
cpp
C++
export/release/macos/obj/src/BackgroundGirls.cpp
EnvyBun/KB-FNF-MOD
f7541661229c587bf99f0508cc3eba7043f8c177
[ "Apache-2.0" ]
1
2021-07-19T05:10:43.000Z
2021-07-19T05:10:43.000Z
export/release/macos/obj/src/BackgroundGirls.cpp
EnvyBun/KB-FNF-MOD
f7541661229c587bf99f0508cc3eba7043f8c177
[ "Apache-2.0" ]
null
null
null
export/release/macos/obj/src/BackgroundGirls.cpp
EnvyBun/KB-FNF-MOD
f7541661229c587bf99f0508cc3eba7043f8c177
[ "Apache-2.0" ]
null
null
null
// Generated by Haxe 4.1.5 #include <hxcpp.h> #ifndef INCLUDED_BackgroundGirls #include <BackgroundGirls.h> #endif #ifndef INCLUDED_CoolUtil #include <CoolUtil.h> #endif #ifndef INCLUDED_Paths #include <Paths.h> #endif #ifndef INCLUDED_flixel_FlxBasic #include <flixel/FlxBasic.h> #endif #ifndef INCLUDED_flixel_FlxObject #include <flixel/FlxObject.h> #endif #ifndef INCLUDED_flixel_FlxSprite #include <flixel/FlxSprite.h> #endif #ifndef INCLUDED_flixel_animation_FlxAnimationController #include <flixel/animation/FlxAnimationController.h> #endif #ifndef INCLUDED_flixel_graphics_frames_FlxAtlasFrames #include <flixel/graphics/frames/FlxAtlasFrames.h> #endif #ifndef INCLUDED_flixel_graphics_frames_FlxFramesCollection #include <flixel/graphics/frames/FlxFramesCollection.h> #endif #ifndef INCLUDED_flixel_util_IFlxDestroyable #include <flixel/util/IFlxDestroyable.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_0cad68011be830e6_6_new,"BackgroundGirls","new",0x9440151b,"BackgroundGirls.new","BackgroundGirls.hx",6,0x75c246b5) HX_LOCAL_STACK_FRAME(_hx_pos_0cad68011be830e6_24_getScared,"BackgroundGirls","getScared",0x19260451,"BackgroundGirls.getScared","BackgroundGirls.hx",24,0x75c246b5) HX_LOCAL_STACK_FRAME(_hx_pos_0cad68011be830e6_31_dance,"BackgroundGirls","dance",0x6f96acae,"BackgroundGirls.dance","BackgroundGirls.hx",31,0x75c246b5) void BackgroundGirls_obj::__construct(Float x,Float y){ HX_STACKFRAME(&_hx_pos_0cad68011be830e6_6_new) HXLINE( 21) this->danceDir = false; HXLINE( 10) super::__construct(x,y,null()); HXLINE( 13) ::String library = null(); HXDLIN( 13) ::String _hx_tmp = ::Paths_obj::getPath(((HX_("images/",77,50,74,c1) + HX_("weeb/bgFreaks",d9,71,bd,0f)) + HX_(".png",3b,2d,bd,1e)),HX_("IMAGE",3b,57,57,3b),library); HXDLIN( 13) this->set_frames(::flixel::graphics::frames::FlxAtlasFrames_obj::fromSparrow(_hx_tmp,::Paths_obj::getPath(((HX_("images/",77,50,74,c1) + HX_("weeb/bgFreaks",d9,71,bd,0f)) + HX_(".xml",69,3e,c3,1e)),HX_("TEXT",ad,94,ba,37),library))); HXLINE( 15) ::flixel::animation::FlxAnimationController _hx_tmp1 = this->animation; HXDLIN( 15) _hx_tmp1->addByIndices(HX_("danceLeft",da,cc,f9,df),HX_("BG girls group",1b,d2,55,9d),::CoolUtil_obj::numberArray(14,null()),HX_("",00,00,00,00),24,false,null(),null()); HXLINE( 16) ::flixel::animation::FlxAnimationController _hx_tmp2 = this->animation; HXDLIN( 16) _hx_tmp2->addByIndices(HX_("danceRight",a9,7f,a6,91),HX_("BG girls group",1b,d2,55,9d),::CoolUtil_obj::numberArray(30,15),HX_("",00,00,00,00),24,false,null(),null()); HXLINE( 18) this->animation->play(HX_("danceLeft",da,cc,f9,df),null(),null(),null()); } Dynamic BackgroundGirls_obj::__CreateEmpty() { return new BackgroundGirls_obj; } void *BackgroundGirls_obj::_hx_vtable = 0; Dynamic BackgroundGirls_obj::__Create(::hx::DynamicArray inArgs) { ::hx::ObjectPtr< BackgroundGirls_obj > _hx_result = new BackgroundGirls_obj(); _hx_result->__construct(inArgs[0],inArgs[1]); return _hx_result; } bool BackgroundGirls_obj::_hx_isInstanceOf(int inClassId) { if (inClassId<=(int)0x2c01639b) { if (inClassId<=(int)0x10bdbe3d) { return inClassId==(int)0x00000001 || inClassId==(int)0x10bdbe3d; } else { return inClassId==(int)0x2c01639b; } } else { return inClassId==(int)0x7ccf8994 || inClassId==(int)0x7dab0655; } } void BackgroundGirls_obj::getScared(){ HX_STACKFRAME(&_hx_pos_0cad68011be830e6_24_getScared) HXLINE( 25) ::flixel::animation::FlxAnimationController _hx_tmp = this->animation; HXDLIN( 25) _hx_tmp->addByIndices(HX_("danceLeft",da,cc,f9,df),HX_("BG fangirls dissuaded",b1,42,22,06),::CoolUtil_obj::numberArray(14,null()),HX_("",00,00,00,00),24,false,null(),null()); HXLINE( 26) ::flixel::animation::FlxAnimationController _hx_tmp1 = this->animation; HXDLIN( 26) _hx_tmp1->addByIndices(HX_("danceRight",a9,7f,a6,91),HX_("BG fangirls dissuaded",b1,42,22,06),::CoolUtil_obj::numberArray(30,15),HX_("",00,00,00,00),24,false,null(),null()); HXLINE( 27) this->dance(); } HX_DEFINE_DYNAMIC_FUNC0(BackgroundGirls_obj,getScared,(void)) void BackgroundGirls_obj::dance(){ HX_STACKFRAME(&_hx_pos_0cad68011be830e6_31_dance) HXLINE( 32) this->danceDir = !(this->danceDir); HXLINE( 34) if (this->danceDir) { HXLINE( 35) this->animation->play(HX_("danceRight",a9,7f,a6,91),true,null(),null()); } else { HXLINE( 37) this->animation->play(HX_("danceLeft",da,cc,f9,df),true,null(),null()); } } HX_DEFINE_DYNAMIC_FUNC0(BackgroundGirls_obj,dance,(void)) ::hx::ObjectPtr< BackgroundGirls_obj > BackgroundGirls_obj::__new(Float x,Float y) { ::hx::ObjectPtr< BackgroundGirls_obj > __this = new BackgroundGirls_obj(); __this->__construct(x,y); return __this; } ::hx::ObjectPtr< BackgroundGirls_obj > BackgroundGirls_obj::__alloc(::hx::Ctx *_hx_ctx,Float x,Float y) { BackgroundGirls_obj *__this = (BackgroundGirls_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(BackgroundGirls_obj), true, "BackgroundGirls")); *(void **)__this = BackgroundGirls_obj::_hx_vtable; __this->__construct(x,y); return __this; } BackgroundGirls_obj::BackgroundGirls_obj() { } ::hx::Val BackgroundGirls_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 5: if (HX_FIELD_EQ(inName,"dance") ) { return ::hx::Val( dance_dyn() ); } break; case 8: if (HX_FIELD_EQ(inName,"danceDir") ) { return ::hx::Val( danceDir ); } break; case 9: if (HX_FIELD_EQ(inName,"getScared") ) { return ::hx::Val( getScared_dyn() ); } } return super::__Field(inName,inCallProp); } ::hx::Val BackgroundGirls_obj::__SetField(const ::String &inName,const ::hx::Val &inValue,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 8: if (HX_FIELD_EQ(inName,"danceDir") ) { danceDir=inValue.Cast< bool >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } void BackgroundGirls_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_("danceDir",da,33,3a,58)); super::__GetFields(outFields); }; #ifdef HXCPP_SCRIPTABLE static ::hx::StorageInfo BackgroundGirls_obj_sMemberStorageInfo[] = { {::hx::fsBool,(int)offsetof(BackgroundGirls_obj,danceDir),HX_("danceDir",da,33,3a,58)}, { ::hx::fsUnknown, 0, null()} }; static ::hx::StaticInfo *BackgroundGirls_obj_sStaticStorageInfo = 0; #endif static ::String BackgroundGirls_obj_sMemberFields[] = { HX_("danceDir",da,33,3a,58), HX_("getScared",56,01,81,b8), HX_("dance",33,83,83,d4), ::String(null()) }; ::hx::Class BackgroundGirls_obj::__mClass; void BackgroundGirls_obj::__register() { BackgroundGirls_obj _hx_dummy; BackgroundGirls_obj::_hx_vtable = *(void **)&_hx_dummy; ::hx::Static(__mClass) = new ::hx::Class_obj(); __mClass->mName = HX_("BackgroundGirls",a9,eb,7a,b7); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &::hx::Class_obj::GetNoStaticField; __mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField; __mClass->mStatics = ::hx::Class_obj::dupFunctions(0 /* sStaticFields */); __mClass->mMembers = ::hx::Class_obj::dupFunctions(BackgroundGirls_obj_sMemberFields); __mClass->mCanCast = ::hx::TCanCast< BackgroundGirls_obj >; #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = BackgroundGirls_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = BackgroundGirls_obj_sStaticStorageInfo; #endif ::hx::_hx_RegisterClass(__mClass->mName, __mClass); }
40.05291
247
0.737252
EnvyBun
4f3a0fd41e06c391ace19d0265339c768f1403b5
279
cpp
C++
pekingUniversity-cpp-tutorial/polymorphic_example.cpp
Ailikez/cpp_tech_notes
b24c3fbe3e0624c73166af3d1c831361f1708f82
[ "MIT" ]
null
null
null
pekingUniversity-cpp-tutorial/polymorphic_example.cpp
Ailikez/cpp_tech_notes
b24c3fbe3e0624c73166af3d1c831361f1708f82
[ "MIT" ]
null
null
null
pekingUniversity-cpp-tutorial/polymorphic_example.cpp
Ailikez/cpp_tech_notes
b24c3fbe3e0624c73166af3d1c831361f1708f82
[ "MIT" ]
null
null
null
/* * 多态原理 * 动态联编 * 虚函数表 * 1.每一个有虚函数的类都有一个虚函数表(编译器生成)与之对应 * 2.每一个有虚函数的类的对象的内存空间内都存着指向虚函数表的指针(这就是为什么会多4Bytes) * 3.虚函数表里面放的是对应类里面所有虚函数的地址 * 4.多态的函数调用语句被编译成一系列 根据基类指针所指向的 对象中 存放的虚函数表 * 的地址,在虚函数表中查询虚函数地址,并调用虚函数指令 * 多态的程序在时间和空间上都有额外开销 */
25.363636
56
0.666667
Ailikez
4f3a5bc69d33247b58d61cbd729f0be7824472a3
65
cpp
C++
Cli/CommandMap.cpp
dllexport/cxxredis
91bebcea1c873b868a538742b17f3cf02f077de1
[ "BSD-3-Clause" ]
null
null
null
Cli/CommandMap.cpp
dllexport/cxxredis
91bebcea1c873b868a538742b17f3cf02f077de1
[ "BSD-3-Clause" ]
null
null
null
Cli/CommandMap.cpp
dllexport/cxxredis
91bebcea1c873b868a538742b17f3cf02f077de1
[ "BSD-3-Clause" ]
null
null
null
// // Created by Mario on 2020/5/31. // #include "CommandMap.h"
10.833333
33
0.630769
dllexport
4f3ae8629a841beb11441690d7e1b80e8dc26aa5
3,216
hpp
C++
Workspace/src/Enemy.hpp
Llemmert/UntitledCatGame
4618cef62d329a90a7387a63cdf87b5b9762097b
[ "MIT" ]
null
null
null
Workspace/src/Enemy.hpp
Llemmert/UntitledCatGame
4618cef62d329a90a7387a63cdf87b5b9762097b
[ "MIT" ]
null
null
null
Workspace/src/Enemy.hpp
Llemmert/UntitledCatGame
4618cef62d329a90a7387a63cdf87b5b9762097b
[ "MIT" ]
null
null
null
#pragma once #include <SDL.h> #include <cmath> #include <iostream> using namespace std; class enemy { private: SDL_Renderer *ren; Animation *a; SDL_Rect *src; SDL_Rect dest; SDL_Rect StompBox; double x, y, vx, vy, w, h; SDL_Point center; SDL_RendererFlip FlipState = SDL_FLIP_NONE; public: enemy(SDL_Renderer *newRen, Animation *newA, SDL_Rect *newSrc, double newx = 0.0, double newy = 0.0, double newvx = 0.0, double newvy = 0.0 /*, double newW = 0, double newH = 0*/) { src = newSrc; ren = newRen; a = newA; dest.w = src->w / 6; // img width dest.h = src->h / 6; // img height dest.x = newx; // starting x pos dest.y = newy; // starting y pos center = {dest.w / 2, dest.h / 2}; if (dest.y + center.y < 243) { StompBox.x = dest.x; StompBox.y = dest.y; StompBox.w = dest.w; StompBox.h = 10; } else { StompBox.x = dest.x; StompBox.y = dest.y + dest.h - 10; StompBox.w = dest.w; StompBox.h = 10; } x = newx; y = newy; vx = newvx; vy = newvy; } void update(double dt) { x += vx * dt; y += vy * dt; dest.x = (int)x; dest.y = (int)y; StompBox.x = dest.x; StompBox.y = dest.y; a->update(dt); if (vx < 0) { if (dest.y + center.y > 243) FlipState = (SDL_RendererFlip)(SDL_FLIP_HORIZONTAL | SDL_FLIP_VERTICAL); else FlipState = SDL_FLIP_HORIZONTAL; } else if (dest.y + center.y > 243) FlipState = SDL_FLIP_VERTICAL; else FlipState = SDL_FLIP_NONE; SDL_RenderCopyEx(ren, a->getTexture(), src, &dest, 0, &center, FlipState); } double getVelocityX() { return vx; } double getVelocityY() { return vy; } double getx() { return x; } double gety() { return y; } bool inside(int x, int y) { return (dest.x <= x && x <= dest.x + dest.w && dest.y <= y && y <= dest.y + dest.h); } bool insideStompBox(int x, int y) { return (StompBox.x <= x && x <= StompBox.x + StompBox.w && StompBox.y <= y && y <= StompBox.y + StompBox.h); } bool detectCollision(wall *aWall) { double adx = abs((dest.x + (dest.w / 2)) - (aWall->getx() + aWall->centerx())); double ady = abs((dest.y + (dest.h / 2)) - (aWall->gety() + aWall->centery())); double shw = (dest.w / 2) + aWall->centerx(); double shh = (dest.h / 2) + aWall->centery(); if (adx <= shw && ady <= shh) return true; return false; } void handleCollision(vector<wall *> &walls) { for (auto aWall : walls) { if (detectCollision(aWall)) { if (vx < 0) dest.x += 3; else dest.x -= 3; vx = -vx; } } } };
24.549618
126
0.460199
Llemmert
4f3c847b51f41bc47f8b90cb2ae9dc98a12d2438
418
hpp
C++
gtkpp-StyleContext.hpp
btryba/gtkpp
9849557e96aa61e09a9df85e5d03453fe6863842
[ "BSD-3-Clause" ]
null
null
null
gtkpp-StyleContext.hpp
btryba/gtkpp
9849557e96aa61e09a9df85e5d03453fe6863842
[ "BSD-3-Clause" ]
null
null
null
gtkpp-StyleContext.hpp
btryba/gtkpp
9849557e96aa61e09a9df85e5d03453fe6863842
[ "BSD-3-Clause" ]
null
null
null
#ifndef __GTKPP_STYLECONTEXT_HPP__ #define __GTKPP_STYLECONTEXT_HPP__ extern "C" { #include <gtk/gtk.h> } namespace gtkpp { class StyleContext { GtkStyleContext* context; public: StyleContext(GtkStyleContext* context); virtual ~StyleContext(); void add_class(const char* className); void invalidate(); }; } #endif //__GTKPP_STYLECONTEXT_HPP__
18.173913
47
0.65311
btryba
4f3dad7e0e50fbcea84e35f0cf68b008e00b2946
20,576
cpp
C++
contracts/test_api_db/test_db.cpp
SheldonHH/snax_Ibc
2f244bcaf09f75cbbb987060f7e15ab514e6346b
[ "MIT" ]
21
2018-11-29T19:30:30.000Z
2021-11-07T08:29:32.000Z
contracts/test_api_db/test_db.cpp
SheldonHH/snax_Ibc
2f244bcaf09f75cbbb987060f7e15ab514e6346b
[ "MIT" ]
6
2019-03-11T16:25:16.000Z
2022-01-22T04:52:44.000Z
contracts/test_api_db/test_db.cpp
SheldonHH/snax_Ibc
2f244bcaf09f75cbbb987060f7e15ab514e6346b
[ "MIT" ]
10
2019-04-02T19:52:02.000Z
2021-03-04T20:24:29.000Z
#include <snaxlib/types.hpp> #include <snaxlib/action.hpp> #include <snaxlib/transaction.hpp> #include <snaxlib/datastream.hpp> #include <snaxlib/db.h> #include <snaxlib/memory.hpp> #include <snaxlib/fixed_key.hpp> #include "../test_api/test_api.hpp" int primary[11] = {0,1,2,3,4,5,6,7,8,9,10}; int secondary[11] = {7,0,1,3,6,9,10,2,4,5,8}; int tertiary[11] = {0,10,1,2,4,3,5,6,7,8,9}; int primary_lb[11] = {0,0,0,3,3,3,6,7,7,9,9}; int secondary_lb[11] = {0,0,10,0,10,10,0,7,8,0,10}; int tertiary_lb[11] = {0,1,2,3,2,5,6,7,8,9,0}; int primary_ub[11] = {3,3,3,6,6,6,7,9,9,-1,-1}; int secondary_ub[11] = {10,10,8,10,8,8,10,0,-1,10,8}; int tertiary_ub[11] = {1,2,3,5,3,6,7,8,9,-1,1}; #pragma pack(push, 1) struct test_model { account_name name; unsigned char age; uint64_t phone; }; struct test_model_v2 : test_model { test_model_v2() : new_field(0) {} uint64_t new_field; }; struct test_model_v3 : test_model_v2 { uint64_t another_field; }; struct TestModel128x2 { uint128_t number; uint128_t price; uint64_t extra; uint64_t table_name; }; struct TestModel128x2_V2 : TestModel128x2 { uint64_t new_field; }; struct TestModel3xi64 { uint64_t a; uint64_t b; uint64_t c; uint64_t table; }; struct TestModel3xi64_V2 : TestModel3xi64 { uint64_t new_field; }; #pragma pack(pop) #define STRLEN(s) my_strlen(s) extern "C" { void my_memset(void *vptr, unsigned char val, unsigned int size) { char *ptr = (char *)vptr; while(size--) { *(ptr++)=(char)val; } } uint32_t my_strlen(const char *str) { uint32_t len = 0; while(str[len]) ++len; return len; } bool my_memcmp(void *s1, void *s2, uint32_t n) { unsigned char *c1 = (unsigned char*)s1; unsigned char *c2 = (unsigned char*)s2; for (uint32_t i = 0; i < n; i++) { if (c1[i] != c2[i]) { return false; } } return true; } } void test_db::primary_i64_general(uint64_t receiver, uint64_t code, uint64_t action) { (void)code; (void)action; auto table1 = N(table1); int alice_itr = db_store_i64(receiver, table1, receiver, N(alice), "alice's info", strlen("alice's info")); db_store_i64(receiver, table1, receiver, N(bob), "bob's info", strlen("bob's info")); db_store_i64(receiver, table1, receiver, N(charlie), "charlie's info", strlen("charlies's info")); db_store_i64(receiver, table1, receiver, N(allyson), "allyson's info", strlen("allyson's info")); // find { uint64_t prim = 0; int itr_next = db_next_i64(alice_itr, &prim); int itr_next_expected = db_find_i64(receiver, receiver, table1, N(allyson)); snax_assert(itr_next == itr_next_expected && prim == N(allyson), "primary_i64_general - db_find_i64" ); itr_next = db_next_i64(itr_next, &prim); itr_next_expected = db_find_i64(receiver, receiver, table1, N(bob)); snax_assert(itr_next == itr_next_expected && prim == N(bob), "primary_i64_general - db_next_i64"); } // next { int charlie_itr = db_find_i64(receiver, receiver, table1, N(charlie)); // nothing after charlie uint64_t prim = 0; int end_itr = db_next_i64(charlie_itr, &prim); snax_assert(end_itr < 0, "primary_i64_general - db_next_i64"); // prim didn't change snax_assert(prim == 0, "primary_i64_general - db_next_i64"); } // previous { int charlie_itr = db_find_i64(receiver, receiver, table1, N(charlie)); uint64_t prim = 0; int itr_prev = db_previous_i64(charlie_itr, &prim); int itr_prev_expected = db_find_i64(receiver, receiver, table1, N(bob)); snax_assert(itr_prev == itr_prev_expected && prim == N(bob), "primary_i64_general - db_previous_i64"); itr_prev = db_previous_i64(itr_prev, &prim); itr_prev_expected = db_find_i64(receiver, receiver, table1, N(allyson)); snax_assert(itr_prev == itr_prev_expected && prim == N(allyson), "primary_i64_general - db_previous_i64"); itr_prev = db_previous_i64(itr_prev, &prim); itr_prev_expected = db_find_i64(receiver, receiver, table1, N(alice)); snax_assert(itr_prev == itr_prev_expected && prim == N(alice), "primary_i64_general - db_previous_i64"); itr_prev = db_previous_i64(itr_prev, &prim); snax_assert(itr_prev < 0 && prim == N(alice), "primary_i64_general - db_previous_i64"); } // remove { int itr = db_find_i64(receiver, receiver, table1, N(alice)); snax_assert(itr >= 0, "primary_i64_general - db_find_i64"); db_remove_i64(itr); itr = db_find_i64(receiver, receiver, table1, N(alice)); snax_assert(itr < 0, "primary_i64_general - db_find_i64"); } // get { int itr = db_find_i64(receiver, receiver, table1, N(bob)); snax_assert(itr >= 0, ""); uint32_t buffer_len = 5; char value[50]; auto len = db_get_i64(itr, value, buffer_len); value[buffer_len] = '\0'; std::string s(value); snax_assert(uint32_t(len) == buffer_len, "primary_i64_general - db_get_i64"); snax_assert(s == "bob's", "primary_i64_general - db_get_i64 - 5"); buffer_len = 20; len = db_get_i64(itr, value, 0); len = db_get_i64(itr, value, (uint32_t)len); value[len] = '\0'; std::string sfull(value); snax_assert(sfull == "bob's info", "primary_i64_general - db_get_i64 - full"); } // update { int itr = db_find_i64(receiver, receiver, table1, N(bob)); snax_assert(itr >= 0, ""); const char* new_value = "bob's new info"; uint32_t new_value_len = strlen(new_value); db_update_i64(itr, receiver, new_value, new_value_len); char ret_value[50]; db_get_i64(itr, ret_value, new_value_len); ret_value[new_value_len] = '\0'; std::string sret(ret_value); snax_assert(sret == "bob's new info", "primary_i64_general - db_update_i64"); } } void test_db::primary_i64_lowerbound(uint64_t receiver, uint64_t code, uint64_t action) { (void)code;(void)action; auto table = N(mytable); db_store_i64(receiver, table, receiver, N(alice), "alice's info", strlen("alice's info")); db_store_i64(receiver, table, receiver, N(bob), "bob's info", strlen("bob's info")); db_store_i64(receiver, table, receiver, N(charlie), "charlie's info", strlen("charlies's info")); db_store_i64(receiver, table, receiver, N(emily), "emily's info", strlen("emily's info")); db_store_i64(receiver, table, receiver, N(allyson), "allyson's info", strlen("allyson's info")); db_store_i64(receiver, table, receiver, N(joe), "nothing here", strlen("nothing here")); const std::string err = "primary_i64_lowerbound"; { int lb = db_lowerbound_i64(receiver, receiver, table, N(alice)); snax_assert(lb == db_find_i64(receiver, receiver, table, N(alice)), err.c_str()); } { int lb = db_lowerbound_i64(receiver, receiver, table, N(billy)); snax_assert(lb == db_find_i64(receiver, receiver, table, N(bob)), err.c_str()); } { int lb = db_lowerbound_i64(receiver, receiver, table, N(frank)); snax_assert(lb == db_find_i64(receiver, receiver, table, N(joe)), err.c_str()); } { int lb = db_lowerbound_i64(receiver, receiver, table, N(joe)); snax_assert(lb == db_find_i64(receiver, receiver, table, N(joe)), err.c_str()); } { int lb = db_lowerbound_i64(receiver, receiver, table, N(kevin)); snax_assert(lb < 0, err.c_str()); } } void test_db::primary_i64_upperbound(uint64_t receiver, uint64_t code, uint64_t action) { (void)code;(void)action; auto table = N(mytable); const std::string err = "primary_i64_upperbound"; { int ub = db_upperbound_i64(receiver, receiver, table, N(alice)); snax_assert(ub == db_find_i64(receiver, receiver, table, N(allyson)), err.c_str()); } { int ub = db_upperbound_i64(receiver, receiver, table, N(billy)); snax_assert(ub == db_find_i64(receiver, receiver, table, N(bob)), err.c_str()); } { int ub = db_upperbound_i64(receiver, receiver, table, N(frank)); snax_assert(ub == db_find_i64(receiver, receiver, table, N(joe)), err.c_str()); } { int ub = db_upperbound_i64(receiver, receiver, table, N(joe)); snax_assert(ub < 0, err.c_str()); } { int ub = db_upperbound_i64(receiver, receiver, table, N(kevin)); snax_assert(ub < 0, err.c_str()); } } void test_db::idx64_general(uint64_t receiver, uint64_t code, uint64_t action) { (void)code;(void)action; const auto table = N(myindextable); typedef uint64_t secondary_type; struct record { uint64_t ssn; secondary_type name; }; record records[] = {{265, N(alice)}, {781, N(bob)}, {234, N(charlie)}, {650, N(allyson)}, {540, N(bob)}, {976, N(emily)}, {110, N(joe)} }; for (uint32_t i = 0; i < sizeof(records)/sizeof(records[0]); ++i) { db_idx64_store(receiver, table, receiver, records[i].ssn, &records[i].name); } // find_primary { secondary_type sec = 0; int itr = db_idx64_find_primary(receiver, receiver, table, &sec, 999); snax_assert(itr < 0 && sec == 0, "idx64_general - db_idx64_find_primary"); itr = db_idx64_find_primary(receiver, receiver, table, &sec, 110); snax_assert(itr >= 0 && sec == N(joe), "idx64_general - db_idx64_find_primary"); uint64_t prim_next = 0; int itr_next = db_idx64_next(itr, &prim_next); snax_assert(itr_next < 0 && prim_next == 0, "idx64_general - db_idx64_find_primary"); } // iterate forward starting with charlie { secondary_type sec = 0; int itr = db_idx64_find_primary(receiver, receiver, table, &sec, 234); snax_assert(itr >= 0 && sec == N(charlie), "idx64_general - db_idx64_find_primary"); uint64_t prim_next = 0; int itr_next = db_idx64_next(itr, &prim_next); snax_assert(itr_next >= 0 && prim_next == 976, "idx64_general - db_idx64_next"); secondary_type sec_next = 0; int itr_next_expected = db_idx64_find_primary(receiver, receiver, table, &sec_next, prim_next); snax_assert(itr_next == itr_next_expected && sec_next == N(emily), "idx64_general - db_idx64_next"); itr_next = db_idx64_next(itr_next, &prim_next); snax_assert(itr_next >= 0 && prim_next == 110, "idx64_general - db_idx64_next"); itr_next_expected = db_idx64_find_primary(receiver, receiver, table, &sec_next, prim_next); snax_assert(itr_next == itr_next_expected && sec_next == N(joe), "idx64_general - db_idx64_next"); itr_next = db_idx64_next(itr_next, &prim_next); snax_assert(itr_next < 0 && prim_next == 110, "idx64_general - db_idx64_next"); } // iterate backward staring with second bob { secondary_type sec = 0; int itr = db_idx64_find_primary(receiver, receiver, table, &sec, 781); snax_assert(itr >= 0 && sec == N(bob), "idx64_general - db_idx64_find_primary"); uint64_t prim_prev = 0; int itr_prev = db_idx64_previous(itr, &prim_prev); snax_assert(itr_prev >= 0 && prim_prev == 540, "idx64_general - db_idx64_previous"); secondary_type sec_prev = 0; int itr_prev_expected = db_idx64_find_primary(receiver, receiver, table, &sec_prev, prim_prev); snax_assert(itr_prev == itr_prev_expected && sec_prev == N(bob), "idx64_general - db_idx64_previous"); itr_prev = db_idx64_previous(itr_prev, &prim_prev); snax_assert(itr_prev >= 0 && prim_prev == 650, "idx64_general - db_idx64_previous"); itr_prev_expected = db_idx64_find_primary(receiver, receiver, table, &sec_prev, prim_prev); snax_assert(itr_prev == itr_prev_expected && sec_prev == N(allyson), "idx64_general - db_idx64_previous"); itr_prev = db_idx64_previous(itr_prev, &prim_prev); snax_assert(itr_prev >= 0 && prim_prev == 265, "idx64_general - db_idx64_previous"); itr_prev_expected = db_idx64_find_primary(receiver, receiver, table, &sec_prev, prim_prev); snax_assert(itr_prev == itr_prev_expected && sec_prev == N(alice), "idx64_general - db_idx64_previous"); itr_prev = db_idx64_previous(itr_prev, &prim_prev); snax_assert(itr_prev < 0 && prim_prev == 265, "idx64_general - db_idx64_previous"); } // find_secondary { uint64_t prim = 0; auto sec = N(bob); int itr = db_idx64_find_secondary(receiver, receiver, table, &sec, &prim); snax_assert(itr >= 0 && prim == 540, "idx64_general - db_idx64_find_secondary"); sec = N(emily); itr = db_idx64_find_secondary(receiver, receiver, table, &sec, &prim); snax_assert(itr >= 0 && prim == 976, "idx64_general - db_idx64_find_secondary"); sec = N(frank); itr = db_idx64_find_secondary(receiver, receiver, table, &sec, &prim); snax_assert(itr < 0 && prim == 976, "idx64_general - db_idx64_find_secondary"); } // update and remove { auto one_more_bob = N(bob); const uint64_t ssn = 421; int itr = db_idx64_store(receiver, table, receiver, ssn, &one_more_bob); auto new_name = N(billy); db_idx64_update(itr, receiver, &new_name); secondary_type sec = 0; int sec_itr = db_idx64_find_primary(receiver, receiver, table, &sec, ssn); snax_assert(sec_itr == itr && sec == new_name, "idx64_general - db_idx64_update"); db_idx64_remove(itr); int itrf = db_idx64_find_primary(receiver, receiver, table, &sec, ssn); snax_assert(itrf < 0, "idx64_general - db_idx64_remove"); } } void test_db::idx64_lowerbound(uint64_t receiver, uint64_t code, uint64_t action) { (void)code;(void)action; const auto table = N(myindextable); typedef uint64_t secondary_type; const std::string err = "idx64_lowerbound"; { secondary_type lb_sec = N(alice); uint64_t lb_prim = 0; const uint64_t ssn = 265; int lb = db_idx64_lowerbound(receiver, receiver, table, &lb_sec, &lb_prim); snax_assert(lb_prim == ssn && lb_sec == N(alice), err.c_str()); snax_assert(lb == db_idx64_find_primary(receiver, receiver, table, &lb_sec, ssn), err.c_str()); } { secondary_type lb_sec = N(billy); uint64_t lb_prim = 0; const uint64_t ssn = 540; int lb = db_idx64_lowerbound(receiver, receiver, table, &lb_sec, &lb_prim); snax_assert(lb_prim == ssn && lb_sec == N(bob), err.c_str()); snax_assert(lb == db_idx64_find_primary(receiver, receiver, table, &lb_sec, ssn), err.c_str()); } { secondary_type lb_sec = N(joe); uint64_t lb_prim = 0; const uint64_t ssn = 110; int lb = db_idx64_lowerbound(receiver, receiver, table, &lb_sec, &lb_prim); snax_assert(lb_prim == ssn && lb_sec == N(joe), err.c_str()); snax_assert(lb == db_idx64_find_primary(receiver, receiver, table, &lb_sec, ssn), err.c_str()); } { secondary_type lb_sec = N(kevin); uint64_t lb_prim = 0; int lb = db_idx64_lowerbound(receiver, receiver, table, &lb_sec, &lb_prim); snax_assert(lb_prim == 0 && lb_sec == N(kevin), err.c_str()); snax_assert(lb < 0, ""); } } void test_db::idx64_upperbound(uint64_t receiver, uint64_t code, uint64_t action) { (void)code;(void)action; const auto table = N(myindextable); typedef uint64_t secondary_type; const std::string err = "idx64_upperbound"; { secondary_type ub_sec = N(alice); uint64_t ub_prim = 0; const uint64_t allyson_ssn = 650; int ub = db_idx64_upperbound(receiver, receiver, table, &ub_sec, &ub_prim); snax_assert(ub_prim == allyson_ssn && ub_sec == N(allyson), ""); snax_assert(ub == db_idx64_find_primary(receiver, receiver, table, &ub_sec, allyson_ssn), err.c_str()); } { secondary_type ub_sec = N(billy); uint64_t ub_prim = 0; const uint64_t bob_ssn = 540; int ub = db_idx64_upperbound(receiver, receiver, table, &ub_sec, &ub_prim); snax_assert(ub_prim == bob_ssn && ub_sec == N(bob), ""); snax_assert(ub == db_idx64_find_primary(receiver, receiver, table, &ub_sec, bob_ssn), err.c_str()); } { secondary_type ub_sec = N(joe); uint64_t ub_prim = 0; int ub = db_idx64_upperbound(receiver, receiver, table, &ub_sec, &ub_prim); snax_assert(ub_prim == 0 && ub_sec == N(joe), err.c_str()); snax_assert(ub < 0, err.c_str()); } { secondary_type ub_sec = N(kevin); uint64_t ub_prim = 0; int ub = db_idx64_upperbound(receiver, receiver, table, &ub_sec, &ub_prim); snax_assert(ub_prim == 0 && ub_sec == N(kevin), err.c_str()); snax_assert(ub < 0, err.c_str()); } } void test_db::test_invalid_access(uint64_t receiver, uint64_t code, uint64_t action) { (void)code;(void)action; auto act = snax::get_action(1, 0); auto ia = snax::unpack<invalid_access_action>(act.data); uint64_t scope = N(access); uint64_t table = scope; uint64_t pk = scope; int32_t itr = -1; uint64_t value = 0; switch( ia.index ) { case 1: itr = db_idx64_find_primary(ia.code, scope, table, &value, pk); break; case 0: default: itr = db_find_i64(ia.code, scope, table, pk); break; } if( ia.store ) { uint64_t value_to_store = ia.val; if( itr < 0 ) { switch( ia.index ) { case 1: db_idx64_store( scope, table, receiver, pk, &value_to_store ); break; case 0: default: db_store_i64( scope, table, receiver, pk, &value_to_store, sizeof(value_to_store) ); break; } } else { switch( ia.index ) { case 1: db_idx64_update( itr, receiver, &value_to_store); break; case 0: default: db_update_i64( itr, receiver, &value_to_store, sizeof(value_to_store) ); break; } } //snax::print("test_invalid_access: stored ", value_to_store, "\n"); } else { snax_assert( itr >= 0, "test_invalid_access: could not find row" ); switch( ia.index ) { case 1: break; case 0: default: snax_assert( db_get_i64( itr, &value, sizeof(value) ) == sizeof(value), "test_invalid_access: value in primary table was incorrect size" ); break; } //snax::print("test_invalid_access: expected ", ia.val, " and retrieved ", value, "\n"); snax_assert( value == ia.val, "test_invalid_access: value did not match" ); } } void test_db::idx_double_nan_create_fail(uint64_t receiver, uint64_t, uint64_t) { double x = 0.0; x = x / x; // create a NaN db_idx_double_store( N(nan), N(nan), receiver, 0, &x); // should fail } void test_db::idx_double_nan_modify_fail(uint64_t receiver, uint64_t, uint64_t) { double x = 0.0; db_idx_double_store( N(nan), N(nan), receiver, 0, &x); auto itr = db_idx_double_find_primary(receiver, N(nan), N(nan), &x, 0); x = 0.0; x = x / x; // create a NaN db_idx_double_update(itr, 0, &x); // should fail } void test_db::idx_double_nan_lookup_fail(uint64_t receiver, uint64_t, uint64_t) { auto act = snax::get_action(1, 0); auto lookup_type = snax::unpack<uint32_t>(act.data); uint64_t pk; double x = 0.0; db_idx_double_store( N(nan), N(nan), receiver, 0, &x); x = x / x; // create a NaN switch( lookup_type ) { case 0: // find db_idx_double_find_secondary(receiver, N(nan), N(nan), &x, &pk); break; case 1: // lower bound db_idx_double_lowerbound(receiver, N(nan), N(nan), &x, &pk); break; case 2: // upper bound db_idx_double_upperbound(receiver, N(nan), N(nan), &x, &pk); break; default: snax_assert( false, "idx_double_nan_lookup_fail: unexpected lookup_type" ); } } #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wcast-align" void test_db::misaligned_secondary_key256_tests(uint64_t /* receiver */, uint64_t, uint64_t) { auto key = snax::key256::make_from_word_sequence<uint64_t>(0ULL, 0ULL, 0ULL, 42ULL); char* ptr = (char*)(&key); ptr += 1; // test that store doesn't crash on unaligned data db_idx256_store( N(testapi), N(testtable), N(testapi), 1, (uint128_t*)(ptr), 2 ); // test that find_primary doesn't crash on unaligned data db_idx256_find_primary( N(testapi), N(testtable), N(testapi), (uint128_t*)(ptr), 2, 0); } #pragma clang diagnostic pop
37.207957
112
0.642496
SheldonHH
4f3fd89a5e456156658b6a332360b6c7e0e0ec1b
12,704
cpp
C++
hphp/compiler/option.cpp
sgolemon/hhvm
240f1370de88926a6c0760cc089b93b84bb0f88d
[ "PHP-3.01", "Zend-2.0" ]
2
2016-12-06T07:37:31.000Z
2017-05-19T17:08:48.000Z
hphp/compiler/option.cpp
sgolemon/hhvm
240f1370de88926a6c0760cc089b93b84bb0f88d
[ "PHP-3.01", "Zend-2.0" ]
1
2020-01-19T19:06:32.000Z
2020-01-19T19:06:32.000Z
hphp/compiler/option.cpp
profclems/hhvm
240f1370de88926a6c0760cc089b93b84bb0f88d
[ "PHP-3.01", "Zend-2.0" ]
2
2017-02-19T16:11:15.000Z
2019-07-18T20:16:53.000Z
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/compiler/option.h" #include <map> #include <set> #include <string> #include <vector> #include "hphp/compiler/analysis/analysis_result.h" #include "hphp/compiler/analysis/class_scope.h" #include "hphp/compiler/analysis/file_scope.h" #include "hphp/compiler/analysis/variable_table.h" #include "hphp/parser/scanner.h" #include "hphp/runtime/base/config.h" #include "hphp/runtime/base/ini-setting.h" #include "hphp/runtime/base/preg.h" #include "hphp/util/hdf.h" #include "hphp/util/logger.h" #include "hphp/util/process.h" #include "hphp/util/text-util.h" #include "hphp/hhbbc/hhbbc.h" namespace HPHP { /////////////////////////////////////////////////////////////////////////////// std::string Option::RootDirectory; std::set<std::string> Option::PackageDirectories; std::set<std::string> Option::PackageFiles; std::set<std::string> Option::PackageExcludeDirs; std::set<std::string> Option::PackageExcludeFiles; std::set<std::string> Option::PackageExcludePatterns; std::set<std::string> Option::PackageExcludeStaticDirs; std::set<std::string> Option::PackageExcludeStaticFiles; std::set<std::string> Option::PackageExcludeStaticPatterns; bool Option::CachePHPFile = false; std::vector<std::string> Option::ParseOnDemandDirs; std::map<std::string, std::string> Option::IncludeRoots; std::map<std::string, std::string> Option::AutoloadRoots; std::vector<std::string> Option::IncludeSearchPaths; std::string Option::DefaultIncludeRoot; hphp_string_imap<std::string> Option::ConstantFunctions; bool Option::GeneratePickledPHP = false; bool Option::GenerateInlinedPHP = false; bool Option::GenerateTrimmedPHP = false; bool Option::ConvertSuperGlobals = false; std::string Option::ProgramPrologue; std::string Option::TrimmedPrologue; std::set<std::string> Option::VolatileClasses; std::map<std::string,std::string,stdltistr> Option::AutoloadClassMap; std::map<std::string,std::string,stdltistr> Option::AutoloadFuncMap; std::map<std::string,std::string> Option::AutoloadConstMap; std::string Option::AutoloadRoot; std::vector<std::string> Option::APCProfile; std::map<std::string, std::string> Option::FunctionSections; bool Option::GenerateTextHHBC = false; bool Option::GenerateBinaryHHBC = false; std::string Option::RepoCentralPath; bool Option::RepoDebugInfo = false; std::string Option::IdPrefix = "$$"; std::string Option::LambdaPrefix = "df_"; std::string Option::Tab = " "; const char *Option::UserFilePrefix = "php/"; bool Option::PreOptimization = false; bool Option::KeepStatementsWithNoEffect = false; std::string Option::ProgramName; bool Option::ParseTimeOpts = true; bool Option::EnableHipHopExperimentalSyntax = false; bool Option::EnableShortTags = true; bool Option::EnableAspTags = false; int Option::ParserThreadCount = 0; int Option::GetScannerType() { int type = 0; if (EnableShortTags) type |= Scanner::AllowShortTags; if (EnableAspTags) type |= Scanner::AllowAspTags; if (RuntimeOption::EnableXHP) type |= Scanner::AllowXHPSyntax; if (RuntimeOption::EnableHipHopSyntax) type |= Scanner::AllowHipHopSyntax; return type; } bool Option::DumpAst = false; bool Option::WholeProgram = true; bool Option::UseHHBBC = !getenv("HHVM_DISABLE_HHBBC"); bool Option::RecordErrors = true; bool Option::AllVolatile = false; StringBag Option::OptionStrings; bool Option::GenerateDocComments = true; /////////////////////////////////////////////////////////////////////////////// // load from HDF file void Option::LoadRootHdf(const IniSetting::Map& ini, const Hdf &roots, const std::string& name, std::map<std::string, std::string> &map) { auto root_map_callback = [&] (const IniSetting::Map &ini_rm, const Hdf &hdf_rm, const std::string &ini_rm_key) { map[Config::GetString(ini_rm, hdf_rm, "root", "", false)] = Config::GetString(ini_rm, hdf_rm, "path", "", false); }; Config::Iterate(root_map_callback, ini, roots, name); } void Option::Load(const IniSetting::Map& ini, Hdf &config) { LoadRootHdf(ini, config, "IncludeRoots", IncludeRoots); LoadRootHdf(ini, config, "AutoloadRoots", AutoloadRoots); Config::Bind(PackageFiles, ini, config, "PackageFiles", PackageFiles); Config::Bind(IncludeSearchPaths, ini, config, "IncludeSearchPaths"); Config::Bind(PackageDirectories, ini, config, "PackageDirectories"); Config::Bind(PackageExcludeDirs, ini, config, "PackageExcludeDirs"); Config::Bind(PackageExcludeFiles, ini, config, "PackageExcludeFiles"); Config::Bind(PackageExcludePatterns, ini, config, "PackageExcludePatterns"); Config::Bind(PackageExcludeStaticDirs, ini, config, "PackageExcludeStaticDirs"); Config::Bind(PackageExcludeStaticFiles, ini, config, "PackageExcludeStaticFiles"); Config::Bind(PackageExcludeStaticFiles, ini, config, "PackageExcludeStaticPatterns"); Config::Bind(CachePHPFile, ini, config, "CachePHPFile"); Config::Bind(ParseOnDemandDirs, ini, config, "ParseOnDemandDirs"); { std::string tmp; #define READ_CG_OPTION(name) \ tmp = Config::GetString(ini, config, "CodeGeneration."#name); \ if (!tmp.empty()) { \ name = OptionStrings.add(tmp.c_str()); \ } READ_CG_OPTION(IdPrefix); READ_CG_OPTION(LambdaPrefix); } Config::Bind(RuntimeOption::DynamicInvokeFunctions, ini, config, "DynamicInvokeFunctions", RuntimeOption::DynamicInvokeFunctions); Config::Bind(VolatileClasses, ini, config, "VolatileClasses"); for (auto& str : Config::GetVector(ini, config, "ConstantFunctions")) { std::string func; std::string value; if (folly::split('|', str, func, value)) { ConstantFunctions[func] = value; } else { std::cerr << folly::format("Invalid ConstantFunction: '{}'\n", str); } } // build map from function names to sections auto function_sections_callback = [&] (const IniSetting::Map &ini_fs, const Hdf &hdf_fs, const std::string &ini_fs_key) { auto function_callback = [&] (const IniSetting::Map &ini_f, const Hdf &hdf_f, const std::string &ini_f_key) { FunctionSections[Config::GetString(ini_f, hdf_f, "", "", false)] = hdf_fs.exists() && !hdf_fs.isEmpty() ? hdf_fs.getName() : ini_fs_key; }; Config::Iterate(function_callback, ini_fs, hdf_fs, "", false); }; Config::Iterate(function_sections_callback, ini, config, "FunctionSections"); { // Repo { // Repo Central Config::Bind(RepoCentralPath, ini, config, "Repo.Central.Path"); } Config::Bind(RepoDebugInfo, ini, config, "Repo.DebugInfo", false); } { // AutoloadMap Config::Bind(AutoloadClassMap, ini, config, "AutoloadMap.class"); Config::Bind(AutoloadFuncMap, ini, config, "AutoloadMap.function"); Config::Bind(AutoloadConstMap, ini, config, "AutoloadMap.constant"); Config::Bind(AutoloadRoot, ini, config, "AutoloadMap.root"); } Config::Bind(HHBBC::options.HardTypeHints, ini, config, "HardTypeHints", true); Config::Bind(HHBBC::options.HardReturnTypeHints, ini, config, "HardReturnTypeHints", false); Config::Bind(HHBBC::options.HardConstProp, ini, config, "HardConstProp", true); Config::Bind(HHBBC::options.ElideAutoloadInvokes, ini, config, "ElideAutoloadInvokes", true); Config::Bind(APCProfile, ini, config, "APCProfile"); Config::Bind(RuntimeOption::EnableHipHopSyntax, ini, config, "EnableHipHopSyntax", RuntimeOption::EnableHipHopSyntax); Config::Bind(RuntimeOption::EvalPromoteEmptyObject, ini, config, "PromoteEmptyObject", RuntimeOption::EvalPromoteEmptyObject); Config::Bind(RuntimeOption::EnableZendCompat, ini, config, "EnableZendCompat", RuntimeOption::EnableZendCompat); Config::Bind(RuntimeOption::EvalJitEnableRenameFunction, ini, config, "JitEnableRenameFunction", RuntimeOption::EvalJitEnableRenameFunction); Config::Bind(EnableHipHopExperimentalSyntax, ini, config, "EnableHipHopExperimentalSyntax"); Config::Bind(EnableShortTags, ini, config, "EnableShortTags", true); Config::Bind(RuntimeOption::EvalHackArrCompatNotices, ini, config, "HackArrCompatNotices", RuntimeOption::EvalHackArrCompatNotices); { // Hack Config::Bind(RuntimeOption::IntsOverflowToInts, ini, config, "Hack.Lang.IntsOverflowToInts", RuntimeOption::IntsOverflowToInts); Config::Bind(RuntimeOption::StrictArrayFillKeys, ini, config, "Hack.Lang.StrictArrayFillKeys", RuntimeOption::StrictArrayFillKeys); Config::Bind(RuntimeOption::DisallowDynamicVarEnvFuncs, ini, config, "Hack.Lang.DisallowDynamicVarEnvFuncs", RuntimeOption::DisallowDynamicVarEnvFuncs); } Config::Bind(EnableAspTags, ini, config, "EnableAspTags"); Config::Bind(RuntimeOption::EnableXHP, ini, config, "EnableXHP", RuntimeOption::EnableXHP); if (RuntimeOption::EnableHipHopSyntax) { // If EnableHipHopSyntax is true, it forces EnableXHP to true // regardless of how it was set in the config RuntimeOption::EnableXHP = true; } Config::Bind(ParserThreadCount, ini, config, "ParserThreadCount", 0); if (ParserThreadCount <= 0) { ParserThreadCount = Process::GetCPUCount(); } // Just to silence warnings until we remove them from various config files (void)Config::GetByte(ini, config, "EnableEval", 0); (void)Config::GetBool(ini, config, "AllDynamic", true); Config::Bind(AllVolatile, ini, config, "AllVolatile"); Config::Bind(GenerateDocComments, ini, config, "GenerateDocComments", true); Config::Bind(DumpAst, ini, config, "DumpAst", false); Config::Bind(WholeProgram, ini, config, "WholeProgram", true); Config::Bind(UseHHBBC, ini, config, "UseHHBBC", UseHHBBC); // Temporary, during file-cache migration. Config::Bind(FileCache::UseNewCache, ini, config, "UseNewCache", false); } void Option::Load() { } /////////////////////////////////////////////////////////////////////////////// std::string Option::GetAutoloadRoot(const std::string &name) { for (auto const& pair : AutoloadRoots) { if (name.substr(0, pair.first.length()) == pair.first) { return pair.second; } } return ""; } std::string Option::MangleFilename(const std::string &name, bool id) { std::string ret = UserFilePrefix; ret += name; if (id) { replaceAll(ret, "/", "$"); replaceAll(ret, "-", "_"); replaceAll(ret, ".", "_"); } return ret; } bool Option::IsFileExcluded(const std::string &file, const std::set<std::string> &patterns) { String sfile(file.c_str(), file.size(), CopyString); for (auto const& pattern : patterns) { Variant matches; Variant ret = preg_match(String(pattern.c_str(), pattern.size(), CopyString), sfile, &matches); if (ret.toInt64() > 0) { return true; } } return false; } void Option::FilterFiles(std::vector<std::string> &files, const std::set<std::string> &patterns) { for (int i = files.size() - 1; i >= 0; i--) { if (IsFileExcluded(files[i], patterns)) { files.erase(files.begin() + i); } } } ////////////////////////////////////////////////////////////////////// }
36.930233
80
0.634918
sgolemon
4f41aa1acf73ae0e4c07d37428c77e987b4fc71f
2,667
cpp
C++
node/functionaltests/tools/coins_checker.cpp
hadescoincom/hds-core
383a38da9a5e40de66ba2277b54fea41b7c32537
[ "Apache-2.0" ]
null
null
null
node/functionaltests/tools/coins_checker.cpp
hadescoincom/hds-core
383a38da9a5e40de66ba2277b54fea41b7c32537
[ "Apache-2.0" ]
null
null
null
node/functionaltests/tools/coins_checker.cpp
hadescoincom/hds-core
383a38da9a5e40de66ba2277b54fea41b7c32537
[ "Apache-2.0" ]
null
null
null
// Copyright 2020 The Hds Team // // 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 "coins_checker.h" #include "utility/logger.h" using namespace hds; using namespace ECC; CoinsChecker::CoinsChecker(int argc, char* argv[]) : BaseNodeConnection(argc, argv) , m_IsInitChecker(false) { Rules::get().FakePoW = true; Rules::get().UpdateChecksum(); } void CoinsChecker::Check(const Inputs& inputs, Callback callback) { m_Queue.push_back(std::make_pair(inputs, callback)); if (m_IsInitChecker && m_Queue.size() == 1) { StartChecking(); } } void CoinsChecker::StartChecking() { m_Current = m_Queue.front().first.begin(); m_IsOk = true; m_Maturity = 0; Send(proto::GetProofUtxo{ *m_Current, 0 }); } void CoinsChecker::InitChecker() { ConnectToNode(); } void CoinsChecker::OnConnectedSecure() { SendLogin(); } void CoinsChecker::OnMsg(proto::Authentication&& msg) { proto::NodeConnection::OnMsg(std::move(msg)); if (proto::IDType::Node == msg.m_IDType) ProveKdfObscured(*m_pKdf, proto::IDType::Owner); } void CoinsChecker::OnDisconnect(const DisconnectReason& reason) { LOG_ERROR() << "problem with connecting to node: code = " << reason; for (const auto& tmp : m_Queue) { tmp.second(false, m_Maturity); } m_Queue.clear(); } void CoinsChecker::OnMsg(proto::NewTip&& msg) { m_Hdr = msg.m_Description; if (!m_IsInitChecker) { m_IsInitChecker = true; if (!m_Queue.empty()) StartChecking(); } } void CoinsChecker::OnMsg(proto::ProofUtxo&& msg) { if (m_Current == m_Queue.front().first.end()) { LOG_INFO() << "reaceived ProofUtxo twice"; } if (msg.m_Proofs.empty()) { m_IsOk = false; } else { bool isValid = false; for (const auto& proof : msg.m_Proofs) { if (m_Hdr.IsValidProofUtxo(*m_Current, proof)) { std::setmax(m_Maturity, proof.m_State.m_Maturity); isValid = true; break; } } if (!isValid) { m_IsOk = false; } } if (m_IsOk && ++m_Current != m_Queue.front().first.end()) { Send(proto::GetProofUtxo{ *m_Current, 0 }); } else { m_Queue.front().second(m_IsOk, m_Maturity); m_Queue.pop_front(); if (!m_Queue.empty()) StartChecking(); } }
21
75
0.687664
hadescoincom
4f420c45d7bd90025fc2fae01b8d3b3ea2393936
2,864
cpp
C++
src/info.cpp
RybaPila-IT/Multiprocess-Snake-Game
7719a2d0ffa45691eb8f1665a75e73aac09b8a2d
[ "MIT" ]
null
null
null
src/info.cpp
RybaPila-IT/Multiprocess-Snake-Game
7719a2d0ffa45691eb8f1665a75e73aac09b8a2d
[ "MIT" ]
null
null
null
src/info.cpp
RybaPila-IT/Multiprocess-Snake-Game
7719a2d0ffa45691eb8f1665a75e73aac09b8a2d
[ "MIT" ]
1
2021-05-20T07:59:16.000Z
2021-05-20T07:59:16.000Z
// // Created by radoslaw on 07.05.2021. // #include <iostream> #include "synchronizer.hpp" #include "constants.hpp" #include "Log.hpp" namespace { [[noreturn]] void synchronize(Synchronizer& synchronizer_capture, Synchronizer& synchronizer_process, Synchronizer& synchronizer_game) { //gameOff - przechowuje wartość wstawianą do logów czasu procesu gry gdy ten nie jest aktywny const std::string gameOff = "0,0"; Log log; log.open_file(); while (true) { char captureBuffer[INFO_MESS_SIZE]; char processBuffer[INFO_MESS_SIZE]; char gameBuffer[INFO_MESS_SIZE]; synchronizer_capture.receive_data(captureBuffer, INFO_MESS_SIZE); synchronizer_process.receive_data(processBuffer, INFO_MESS_SIZE); if(processBuffer[0] != 'P'){ synchronizer_game.receive_data(gameBuffer, INFO_MESS_SIZE); log.convert_and_write(captureBuffer, processBuffer, gameBuffer); } else { processBuffer[0] = ' '; log.convert_and_write(captureBuffer, processBuffer, gameOff.c_str()); } } } void sync_with_semaphores(const char* argv[]) { try { SharedMemorySemaphoresSynchronizer synchronizer_capture(argv[2], argv[3], argv[4]); SharedMemorySemaphoresSynchronizer synchronizer_process(argv[5], argv[6], argv[7]); SharedMemorySemaphoresSynchronizer synchronizer_game(argv[8], argv[9], argv[10]); synchronize(synchronizer_capture, synchronizer_process, synchronizer_game); } catch (std::runtime_error& e) { std::cerr << "Info process: " << e.what() << std::endl; exit(-1); } } void sync_with_queues_and_mem(const char* argv[]) { try { QueueSharedMemorySynchronizer synchronizer_capture(argv[2], argv[3], argv[4]); QueueSharedMemorySynchronizer synchronizer_process(argv[5], argv[6], argv[7]); QueueSharedMemorySynchronizer synchronizer_game(argv[8], argv[9], argv[10]); synchronize(synchronizer_capture, synchronizer_process, synchronizer_game); } catch (std::runtime_error& e) { std::cerr << "Info process: " << e.what() << std::endl; exit(-1); } } } int main(int argc, const char* argv[]) { if (argc != 11) { std::cerr << "CRITICAL ERROR: Not enough parameters for semaphores info process synchronization." << std::endl; exit(-1); } unsigned int sync_mode = std::atoi(argv[1]); if (sync_mode == SEMAPHORES_SYNC) sync_with_semaphores(argv); else if (sync_mode == QUEUES_MEM_SYNC) sync_with_queues_and_mem(argv); else std::cerr << "WRONG SYNC METHOD" << std::endl; return 0; }
32.545455
140
0.625349
RybaPila-IT
4f46401698d2d37d9c0f0ff0f8f4cb6bf56f9694
568
cpp
C++
ch12/list_12.12/main.cpp
shoeisha-books/dokushu-cpp
8a1e7833fe080ed0f3059428c3a76d297a43a5dd
[ "MIT" ]
17
2020-01-01T16:44:05.000Z
2022-03-31T07:20:13.000Z
ch12/list_12.12/main.cpp
shoeisha-books/dokushu-cpp
8a1e7833fe080ed0f3059428c3a76d297a43a5dd
[ "MIT" ]
1
2021-07-04T01:41:53.000Z
2021-07-14T19:17:01.000Z
ch12/list_12.12/main.cpp
shoeisha-books/dokushu-cpp
8a1e7833fe080ed0f3059428c3a76d297a43a5dd
[ "MIT" ]
3
2019-11-28T14:37:09.000Z
2021-05-22T02:55:15.000Z
#include <iostream> #include <vector> void print_vector(const std::vector<int>& v) { for (int i : v) { std::cout << i << " "; } std::cout << std::endl; } int main() { std::vector v = { 1, 5, 9 }; v.insert(v.begin(), 0); // 先頭に0を挿入 print_vector(v); v.insert(v.end(), 10); // 末尾に10を挿入 print_vector(v); v.insert(v.begin() + 2, 2, 3); // 先頭から2番目(5)の手前に2個の3を挿入 print_vector(v); int ia[] = { 6, 7, 8 }; v.insert(v.end() - 2, ia, ia + 3); // イテレーターが指す範囲を挿入 print_vector(v); }
18.933333
60
0.492958
shoeisha-books
4f473eb9f5b497ef6133285bed2a115aedf82a72
38,005
cc
C++
FELICITY/Demo/Laplace_Beltrami_Open_Surface/Assembly_Code_AutoGen/Basis_Functions/Data_Type_G_h_phi_restricted_to_dGamma.cc
brianchowlab/BcLOV4-FEM
f54bd8efa0e0f2c7ca2de4a6688ef1a403376285
[ "MIT" ]
null
null
null
FELICITY/Demo/Laplace_Beltrami_Open_Surface/Assembly_Code_AutoGen/Basis_Functions/Data_Type_G_h_phi_restricted_to_dGamma.cc
brianchowlab/BcLOV4-FEM
f54bd8efa0e0f2c7ca2de4a6688ef1a403376285
[ "MIT" ]
null
null
null
FELICITY/Demo/Laplace_Beltrami_Open_Surface/Assembly_Code_AutoGen/Basis_Functions/Data_Type_G_h_phi_restricted_to_dGamma.cc
brianchowlab/BcLOV4-FEM
f54bd8efa0e0f2c7ca2de4a6688ef1a403376285
[ "MIT" ]
null
null
null
/* ============================================================================================ This class contains data about a given FE function space, and methods for computing transformations of the local basis functions. This code references the header files: matrix_vector_defn.h matrix_vector_ops.h geometric_computations.h basis_function_computations.h NOTE: portions of this code are automatically generated! Copyright (c) 01-15-2018, Shawn W. Walker ============================================================================================ */ /*------------ BEGIN: Auto Generate ------------*/ // define the name of the FE basis function (should be the same as the filename of this file) #define SpecificFUNC Data_Type_G_h_phi_restricted_to_dGamma #define SpecificFUNC_str "Data_Type_G_h_phi_restricted_to_dGamma" // set the type of function space #define SPACE_type "CG - lagrange_deg2_dim2" // set the name of function space #define SPACE_name "G_h" // set the Subdomain topological dimension #define SUB_TD 2 // set the Domain of Integration (DoI) topological dimension #define DOI_TD 1 // set the geometric dimension #define GD 3 // set the number of cartesian tuple components (m*n) = 3 * 1 #define NC 3 // NOTE: the (i,j) tuple component is accessed by the linear index k = i + (j-1)*m // set the number of quad points #define NQ 5 // set the number of basis functions #define NB 6 /*------------ END: Auto Generate ------------*/ /* C++ (Specific) FE Function class definition */ class SpecificFUNC: public ABSTRACT_FEM_Function_Class // derive from base class { public: int* Elem_DoF[NB]; // element DoF list // data structure containing information on the function evaluations. // Note: this data is evaluated at several quadrature points! // local function evaluated at a quadrature point in reference element // (this is a pointer because it will change depending on the local mesh entity) SCALAR (*Func_f_Value)[NB][NQ]; // constructor SpecificFUNC (); ~SpecificFUNC (); // destructor void Setup_Function_Space(const mxArray*); void Get_Local_to_Global_DoFmap(const int&, int*) const; // need the "const" to ENSURE that nothing in this object will change! void Transform_Basis_Functions(); const CLASS_geom_Gamma_embedded_in_Gamma_restricted_to_dGamma* Mesh; private: void Map_Basis_p1(); void Map_Basis_n1(); void Map_Basis_p2(); void Map_Basis_n2(); void Map_Basis_p3(); void Map_Basis_n3(); SCALAR Value_p1[NB][NQ]; SCALAR Value_n1[NB][NQ]; SCALAR Value_p2[NB][NQ]; SCALAR Value_n2[NB][NQ]; SCALAR Value_p3[NB][NQ]; SCALAR Value_n3[NB][NQ]; void Basis_Value_p1(SCALAR V[NB][NQ]); void Basis_Value_n1(SCALAR V[NB][NQ]); void Basis_Value_p2(SCALAR V[NB][NQ]); void Basis_Value_n2(SCALAR V[NB][NQ]); void Basis_Value_p3(SCALAR V[NB][NQ]); void Basis_Value_n3(SCALAR V[NB][NQ]); }; /*------------ BEGIN: Auto Generate ------------*/ /***************************************************************************************/ /* constructor */ SpecificFUNC::SpecificFUNC () : ABSTRACT_FEM_Function_Class () // call the base class constructor { Name = (char*) SpecificFUNC_str; Type = (char*) SPACE_type; Space_Name = (char*) SPACE_name; Sub_TopDim = SUB_TD; DoI_TopDim = DOI_TD; GeoDim = GD; Num_Basis = NB; Num_Comp = NC; Num_QP = NQ; Mesh = NULL; // init DoF information to NULL for (int basis_i = 0; (basis_i < Num_Basis); basis_i++) Elem_DoF[basis_i] = NULL; // init everything to zero // init basis function values on local mesh entities Basis_Value_p1(Value_p1); Basis_Value_n1(Value_n1); Basis_Value_p2(Value_p2); Basis_Value_n2(Value_n2); Basis_Value_p3(Value_p3); Basis_Value_n3(Value_n3); } /***************************************************************************************/ /*------------ END: Auto Generate ------------*/ /***************************************************************************************/ /* DE-structor */ SpecificFUNC::~SpecificFUNC () { } /***************************************************************************************/ /***************************************************************************************/ /* put incoming function data from MATLAB into a nice struct */ void SpecificFUNC::Setup_Function_Space(const mxArray* Elem) // inputs { Init_Function_Space(Elem); // split up the columns of the element data Elem_DoF[0] = (int *) mxGetPr(Elem); for (int basis_i = 1; (basis_i < Num_Basis); basis_i++) Elem_DoF[basis_i] = Elem_DoF[basis_i-1] + Num_Elem; } /***************************************************************************************/ /***************************************************************************************/ /* get the local DoFs on the given element. Note: elem_index is in the C-style (i.e. 0 <= elem_index <= Num_Elem - 1), Indices is in the MATLAB-style (i.e. 1 <= Indices[:] <= max(Elem_DoF)). */ void SpecificFUNC::Get_Local_to_Global_DoFmap(const int& elem_index, int* Indices) const // inputs { /* error check: */ if (elem_index < 0) { mexPrintf("ERROR: Given element index #%d is not positive. It must be > 0!\n",elem_index+1); mexPrintf("ERROR: There is an issue with the Finite Element Space = %s!\n",Space_Name); mexErrMsgTxt("ERROR: Make sure your inputs are valid!"); } else if (elem_index >= Num_Elem) { mexPrintf("ERROR: Given element index #%d exceeds the number of elements in the finite element (FE) space.\n",elem_index+1); mexPrintf("It must be <= %d! OR Your FE space DoFmap is not defined correctly!\n",Num_Elem); mexPrintf(" For example, the number of rows in DoFmap should *equal*\n"); mexPrintf(" the number of mesh elements in the (sub)-domain.\n"); mexPrintf("ERROR: There is an issue with the Finite Element Space = %s!\n",Space_Name); mexErrMsgTxt("ERROR: Make sure your inputs are valid!"); } // get local to global index map for the current element for (int basis_i = 0; (basis_i < Num_Basis); basis_i++) { int DoF_index = Elem_DoF[basis_i][elem_index] - 1; // shifted for C - style indexing Indices[basis_i] = DoF_index; } } /***************************************************************************************/ /*------------ BEGIN: Auto Generate ------------*/ /***************************************************************************************/ /* compute the correct local transformation */ void SpecificFUNC::Transform_Basis_Functions() { // read in the embedding info const int Entity_Index = Mesh->Domain->DoI_Entity_Index; // if orientation is positive if (Entity_Index > 0) { // pick the correct one if (Entity_Index==1) Map_Basis_p1(); else if (Entity_Index==2) Map_Basis_p2(); else if (Entity_Index==3) Map_Basis_p3(); else mexErrMsgTxt("ERROR: Entity_Index outside valid range or is zero!"); } else // else it is negative { // pick the correct one if (Entity_Index==-1) Map_Basis_n1(); else if (Entity_Index==-2) Map_Basis_n2(); else if (Entity_Index==-3) Map_Basis_n3(); else mexErrMsgTxt("ERROR: Entity_Index outside valid range or is zero!"); } } /***************************************************************************************/ /*------------ END: Auto Generate ------------*/ /*------------ BEGIN: Auto Generate ------------*/ /***************************************************************************************/ /* map basis functions from the standard reference element to an actual element in the Domain. */ void SpecificFUNC::Map_Basis_p1() { /*------------ BEGIN: Auto Generate ------------*/ // Local Element defined on Subdomain: CG, lagrange_deg2_dim2 // the Subdomain has topological dimension = 2 // the Domain of Integration has topological dimension = 1 // geometric dimension = 3 // Number of Quadrature Points = 5 // // set of quadrature points // static const double Quad_Points[NQ][SUB_TD] = { \ // 4.69100770306680737E-02, \ // 2.30765344947158446E-01, \ // 5.00000000000000000E-01, \ // 7.69234655052841498E-01, \ // 9.53089922969331926E-01 \ // }; // // set of quadrature weights // static const double Quad_Weights[NQ] = { \ // 1.18463442528094529E-01, \ // 2.39314335249683374E-01, \ // 2.84444444444444333E-01, \ // 2.39314335249683430E-01, \ // 1.18463442528094445E-01 \ // }; /*------------ END: Auto Generate ------------*/ // set basis function values to the correct mesh entity Func_f_Value = &Value_p1; // point to the correct mesh entity /*------------ BEGIN: Auto Generate ------------*/ /*** compute basis function quantities ***/ /*------------ END: Auto Generate ------------*/ } /***************************************************************************************/ /*------------ END: Auto Generate ------------*/ /*------------ BEGIN: Auto Generate ------------*/ /***************************************************************************************/ /* map basis functions from the standard reference element to an actual element in the Domain. */ void SpecificFUNC::Map_Basis_n1() { /*------------ BEGIN: Auto Generate ------------*/ // Local Element defined on Subdomain: CG, lagrange_deg2_dim2 // the Subdomain has topological dimension = 2 // the Domain of Integration has topological dimension = 1 // geometric dimension = 3 // Number of Quadrature Points = 5 // // set of quadrature points // static const double Quad_Points[NQ][SUB_TD] = { \ // 4.69100770306680737E-02, \ // 2.30765344947158446E-01, \ // 5.00000000000000000E-01, \ // 7.69234655052841498E-01, \ // 9.53089922969331926E-01 \ // }; // // set of quadrature weights // static const double Quad_Weights[NQ] = { \ // 1.18463442528094529E-01, \ // 2.39314335249683374E-01, \ // 2.84444444444444333E-01, \ // 2.39314335249683430E-01, \ // 1.18463442528094445E-01 \ // }; /*------------ END: Auto Generate ------------*/ // set basis function values to the correct mesh entity Func_f_Value = &Value_n1; // point to the correct mesh entity /*------------ BEGIN: Auto Generate ------------*/ /*** compute basis function quantities ***/ /*------------ END: Auto Generate ------------*/ } /***************************************************************************************/ /*------------ END: Auto Generate ------------*/ /*------------ BEGIN: Auto Generate ------------*/ /***************************************************************************************/ /* map basis functions from the standard reference element to an actual element in the Domain. */ void SpecificFUNC::Map_Basis_p2() { /*------------ BEGIN: Auto Generate ------------*/ // Local Element defined on Subdomain: CG, lagrange_deg2_dim2 // the Subdomain has topological dimension = 2 // the Domain of Integration has topological dimension = 1 // geometric dimension = 3 // Number of Quadrature Points = 5 // // set of quadrature points // static const double Quad_Points[NQ][SUB_TD] = { \ // 4.69100770306680737E-02, \ // 2.30765344947158446E-01, \ // 5.00000000000000000E-01, \ // 7.69234655052841498E-01, \ // 9.53089922969331926E-01 \ // }; // // set of quadrature weights // static const double Quad_Weights[NQ] = { \ // 1.18463442528094529E-01, \ // 2.39314335249683374E-01, \ // 2.84444444444444333E-01, \ // 2.39314335249683430E-01, \ // 1.18463442528094445E-01 \ // }; /*------------ END: Auto Generate ------------*/ // set basis function values to the correct mesh entity Func_f_Value = &Value_p2; // point to the correct mesh entity /*------------ BEGIN: Auto Generate ------------*/ /*** compute basis function quantities ***/ /*------------ END: Auto Generate ------------*/ } /***************************************************************************************/ /*------------ END: Auto Generate ------------*/ /*------------ BEGIN: Auto Generate ------------*/ /***************************************************************************************/ /* map basis functions from the standard reference element to an actual element in the Domain. */ void SpecificFUNC::Map_Basis_n2() { /*------------ BEGIN: Auto Generate ------------*/ // Local Element defined on Subdomain: CG, lagrange_deg2_dim2 // the Subdomain has topological dimension = 2 // the Domain of Integration has topological dimension = 1 // geometric dimension = 3 // Number of Quadrature Points = 5 // // set of quadrature points // static const double Quad_Points[NQ][SUB_TD] = { \ // 4.69100770306680737E-02, \ // 2.30765344947158446E-01, \ // 5.00000000000000000E-01, \ // 7.69234655052841498E-01, \ // 9.53089922969331926E-01 \ // }; // // set of quadrature weights // static const double Quad_Weights[NQ] = { \ // 1.18463442528094529E-01, \ // 2.39314335249683374E-01, \ // 2.84444444444444333E-01, \ // 2.39314335249683430E-01, \ // 1.18463442528094445E-01 \ // }; /*------------ END: Auto Generate ------------*/ // set basis function values to the correct mesh entity Func_f_Value = &Value_n2; // point to the correct mesh entity /*------------ BEGIN: Auto Generate ------------*/ /*** compute basis function quantities ***/ /*------------ END: Auto Generate ------------*/ } /***************************************************************************************/ /*------------ END: Auto Generate ------------*/ /*------------ BEGIN: Auto Generate ------------*/ /***************************************************************************************/ /* map basis functions from the standard reference element to an actual element in the Domain. */ void SpecificFUNC::Map_Basis_p3() { /*------------ BEGIN: Auto Generate ------------*/ // Local Element defined on Subdomain: CG, lagrange_deg2_dim2 // the Subdomain has topological dimension = 2 // the Domain of Integration has topological dimension = 1 // geometric dimension = 3 // Number of Quadrature Points = 5 // // set of quadrature points // static const double Quad_Points[NQ][SUB_TD] = { \ // 4.69100770306680737E-02, \ // 2.30765344947158446E-01, \ // 5.00000000000000000E-01, \ // 7.69234655052841498E-01, \ // 9.53089922969331926E-01 \ // }; // // set of quadrature weights // static const double Quad_Weights[NQ] = { \ // 1.18463442528094529E-01, \ // 2.39314335249683374E-01, \ // 2.84444444444444333E-01, \ // 2.39314335249683430E-01, \ // 1.18463442528094445E-01 \ // }; /*------------ END: Auto Generate ------------*/ // set basis function values to the correct mesh entity Func_f_Value = &Value_p3; // point to the correct mesh entity /*------------ BEGIN: Auto Generate ------------*/ /*** compute basis function quantities ***/ /*------------ END: Auto Generate ------------*/ } /***************************************************************************************/ /*------------ END: Auto Generate ------------*/ /*------------ BEGIN: Auto Generate ------------*/ /***************************************************************************************/ /* map basis functions from the standard reference element to an actual element in the Domain. */ void SpecificFUNC::Map_Basis_n3() { /*------------ BEGIN: Auto Generate ------------*/ // Local Element defined on Subdomain: CG, lagrange_deg2_dim2 // the Subdomain has topological dimension = 2 // the Domain of Integration has topological dimension = 1 // geometric dimension = 3 // Number of Quadrature Points = 5 // // set of quadrature points // static const double Quad_Points[NQ][SUB_TD] = { \ // 4.69100770306680737E-02, \ // 2.30765344947158446E-01, \ // 5.00000000000000000E-01, \ // 7.69234655052841498E-01, \ // 9.53089922969331926E-01 \ // }; // // set of quadrature weights // static const double Quad_Weights[NQ] = { \ // 1.18463442528094529E-01, \ // 2.39314335249683374E-01, \ // 2.84444444444444333E-01, \ // 2.39314335249683430E-01, \ // 1.18463442528094445E-01 \ // }; /*------------ END: Auto Generate ------------*/ // set basis function values to the correct mesh entity Func_f_Value = &Value_n3; // point to the correct mesh entity /*------------ BEGIN: Auto Generate ------------*/ /*** compute basis function quantities ***/ /*------------ END: Auto Generate ------------*/ } /***************************************************************************************/ /*------------ END: Auto Generate ------------*/ /*------------ BEGIN: Auto Generate ------------*/ /***************************************************************************************/ /* evaluate basis functions (no derivatives!) on the local reference element. */ void SpecificFUNC::Basis_Value_p1(SCALAR BF_V[NB][NQ]) { /*------------ BEGIN: Auto Generate ------------*/ // Local Element defined on Subdomain: CG, lagrange_deg2_dim2 // the Subdomain has topological dimension = 2 // the Domain of Integration has topological dimension = 1 // geometric dimension = 3 // Number of Quadrature Points = 5 // get "Val" of basis functions SCALAR phi_Val[NQ][NB]; phi_Val[0][0].Set_Equal_To(0.00000000000000000E+00); phi_Val[0][1].Set_Equal_To(8.63670879562042249E-01); phi_Val[0][2].Set_Equal_To(-4.25089663766216458E-02); phi_Val[0][3].Set_Equal_To(1.78838086814579439E-01); phi_Val[0][4].Set_Equal_To(0.00000000000000000E+00); phi_Val[0][5].Set_Equal_To(0.00000000000000000E+00); phi_Val[1][0].Set_Equal_To(0.00000000000000000E+00); phi_Val[1][1].Set_Equal_To(4.14209254015686701E-01); phi_Val[1][2].Set_Equal_To(-1.24260056089996393E-01); phi_Val[1][3].Set_Equal_To(7.10050802074309706E-01); phi_Val[1][4].Set_Equal_To(0.00000000000000000E+00); phi_Val[1][5].Set_Equal_To(0.00000000000000000E+00); phi_Val[2][0].Set_Equal_To(0.00000000000000000E+00); phi_Val[2][1].Set_Equal_To(0.00000000000000000E+00); phi_Val[2][2].Set_Equal_To(0.00000000000000000E+00); phi_Val[2][3].Set_Equal_To(1.00000000000000000E+00); phi_Val[2][4].Set_Equal_To(0.00000000000000000E+00); phi_Val[2][5].Set_Equal_To(0.00000000000000000E+00); phi_Val[3][0].Set_Equal_To(0.00000000000000000E+00); phi_Val[3][1].Set_Equal_To(-1.24260056089996393E-01); phi_Val[3][2].Set_Equal_To(4.14209254015686590E-01); phi_Val[3][3].Set_Equal_To(7.10050802074309817E-01); phi_Val[3][4].Set_Equal_To(0.00000000000000000E+00); phi_Val[3][5].Set_Equal_To(0.00000000000000000E+00); phi_Val[4][0].Set_Equal_To(0.00000000000000000E+00); phi_Val[4][1].Set_Equal_To(-4.25089663766216458E-02); phi_Val[4][2].Set_Equal_To(8.63670879562042249E-01); phi_Val[4][3].Set_Equal_To(1.78838086814579439E-01); phi_Val[4][4].Set_Equal_To(0.00000000000000000E+00); phi_Val[4][5].Set_Equal_To(0.00000000000000000E+00); // // set of quadrature points // static const double Quad_Points[NQ][SUB_TD] = { \ // 4.69100770306680737E-02, \ // 2.30765344947158446E-01, \ // 5.00000000000000000E-01, \ // 7.69234655052841498E-01, \ // 9.53089922969331926E-01 \ // }; // // set of quadrature weights // static const double Quad_Weights[NQ] = { \ // 1.18463442528094529E-01, \ // 2.39314335249683374E-01, \ // 2.84444444444444333E-01, \ // 2.39314335249683430E-01, \ // 1.18463442528094445E-01 \ // }; /*------------ END: Auto Generate ------------*/ // copy function evaluations over (indexing is in the C style) // loop through quad points for (int qp_i = 0; (qp_i < Num_QP); qp_i++) { // evaluate for each basis function for (int basis_i = 0; (basis_i < Num_Basis); basis_i++) { BF_V[basis_i][qp_i].a = phi_Val[qp_i][basis_i].a; } } } /***************************************************************************************/ /*------------ END: Auto Generate ------------*/ /*------------ BEGIN: Auto Generate ------------*/ /***************************************************************************************/ /* evaluate basis functions (no derivatives!) on the local reference element. */ void SpecificFUNC::Basis_Value_n1(SCALAR BF_V[NB][NQ]) { /*------------ BEGIN: Auto Generate ------------*/ // Local Element defined on Subdomain: CG, lagrange_deg2_dim2 // the Subdomain has topological dimension = 2 // the Domain of Integration has topological dimension = 1 // geometric dimension = 3 // Number of Quadrature Points = 5 // get "Val" of basis functions SCALAR phi_Val[NQ][NB]; phi_Val[0][0].Set_Equal_To(0.00000000000000000E+00); phi_Val[0][1].Set_Equal_To(-4.25089663766216458E-02); phi_Val[0][2].Set_Equal_To(8.63670879562042249E-01); phi_Val[0][3].Set_Equal_To(1.78838086814579439E-01); phi_Val[0][4].Set_Equal_To(0.00000000000000000E+00); phi_Val[0][5].Set_Equal_To(0.00000000000000000E+00); phi_Val[1][0].Set_Equal_To(0.00000000000000000E+00); phi_Val[1][1].Set_Equal_To(-1.24260056089996393E-01); phi_Val[1][2].Set_Equal_To(4.14209254015686701E-01); phi_Val[1][3].Set_Equal_To(7.10050802074309706E-01); phi_Val[1][4].Set_Equal_To(0.00000000000000000E+00); phi_Val[1][5].Set_Equal_To(0.00000000000000000E+00); phi_Val[2][0].Set_Equal_To(0.00000000000000000E+00); phi_Val[2][1].Set_Equal_To(0.00000000000000000E+00); phi_Val[2][2].Set_Equal_To(0.00000000000000000E+00); phi_Val[2][3].Set_Equal_To(1.00000000000000000E+00); phi_Val[2][4].Set_Equal_To(0.00000000000000000E+00); phi_Val[2][5].Set_Equal_To(0.00000000000000000E+00); phi_Val[3][0].Set_Equal_To(0.00000000000000000E+00); phi_Val[3][1].Set_Equal_To(4.14209254015686590E-01); phi_Val[3][2].Set_Equal_To(-1.24260056089996393E-01); phi_Val[3][3].Set_Equal_To(7.10050802074309817E-01); phi_Val[3][4].Set_Equal_To(0.00000000000000000E+00); phi_Val[3][5].Set_Equal_To(0.00000000000000000E+00); phi_Val[4][0].Set_Equal_To(0.00000000000000000E+00); phi_Val[4][1].Set_Equal_To(8.63670879562042249E-01); phi_Val[4][2].Set_Equal_To(-4.25089663766216458E-02); phi_Val[4][3].Set_Equal_To(1.78838086814579439E-01); phi_Val[4][4].Set_Equal_To(0.00000000000000000E+00); phi_Val[4][5].Set_Equal_To(0.00000000000000000E+00); // // set of quadrature points // static const double Quad_Points[NQ][SUB_TD] = { \ // 4.69100770306680737E-02, \ // 2.30765344947158446E-01, \ // 5.00000000000000000E-01, \ // 7.69234655052841498E-01, \ // 9.53089922969331926E-01 \ // }; // // set of quadrature weights // static const double Quad_Weights[NQ] = { \ // 1.18463442528094529E-01, \ // 2.39314335249683374E-01, \ // 2.84444444444444333E-01, \ // 2.39314335249683430E-01, \ // 1.18463442528094445E-01 \ // }; /*------------ END: Auto Generate ------------*/ // copy function evaluations over (indexing is in the C style) // loop through quad points for (int qp_i = 0; (qp_i < Num_QP); qp_i++) { // evaluate for each basis function for (int basis_i = 0; (basis_i < Num_Basis); basis_i++) { BF_V[basis_i][qp_i].a = phi_Val[qp_i][basis_i].a; } } } /***************************************************************************************/ /*------------ END: Auto Generate ------------*/ /*------------ BEGIN: Auto Generate ------------*/ /***************************************************************************************/ /* evaluate basis functions (no derivatives!) on the local reference element. */ void SpecificFUNC::Basis_Value_p2(SCALAR BF_V[NB][NQ]) { /*------------ BEGIN: Auto Generate ------------*/ // Local Element defined on Subdomain: CG, lagrange_deg2_dim2 // the Subdomain has topological dimension = 2 // the Domain of Integration has topological dimension = 1 // geometric dimension = 3 // Number of Quadrature Points = 5 // get "Val" of basis functions SCALAR phi_Val[NQ][NB]; phi_Val[0][0].Set_Equal_To(-4.25089663766216458E-02); phi_Val[0][1].Set_Equal_To(0.00000000000000000E+00); phi_Val[0][2].Set_Equal_To(8.63670879562042249E-01); phi_Val[0][3].Set_Equal_To(0.00000000000000000E+00); phi_Val[0][4].Set_Equal_To(1.78838086814579439E-01); phi_Val[0][5].Set_Equal_To(0.00000000000000000E+00); phi_Val[1][0].Set_Equal_To(-1.24260056089996393E-01); phi_Val[1][1].Set_Equal_To(0.00000000000000000E+00); phi_Val[1][2].Set_Equal_To(4.14209254015686701E-01); phi_Val[1][3].Set_Equal_To(0.00000000000000000E+00); phi_Val[1][4].Set_Equal_To(7.10050802074309706E-01); phi_Val[1][5].Set_Equal_To(0.00000000000000000E+00); phi_Val[2][0].Set_Equal_To(0.00000000000000000E+00); phi_Val[2][1].Set_Equal_To(0.00000000000000000E+00); phi_Val[2][2].Set_Equal_To(0.00000000000000000E+00); phi_Val[2][3].Set_Equal_To(0.00000000000000000E+00); phi_Val[2][4].Set_Equal_To(1.00000000000000000E+00); phi_Val[2][5].Set_Equal_To(0.00000000000000000E+00); phi_Val[3][0].Set_Equal_To(4.14209254015686590E-01); phi_Val[3][1].Set_Equal_To(0.00000000000000000E+00); phi_Val[3][2].Set_Equal_To(-1.24260056089996393E-01); phi_Val[3][3].Set_Equal_To(0.00000000000000000E+00); phi_Val[3][4].Set_Equal_To(7.10050802074309817E-01); phi_Val[3][5].Set_Equal_To(0.00000000000000000E+00); phi_Val[4][0].Set_Equal_To(8.63670879562042249E-01); phi_Val[4][1].Set_Equal_To(0.00000000000000000E+00); phi_Val[4][2].Set_Equal_To(-4.25089663766216458E-02); phi_Val[4][3].Set_Equal_To(0.00000000000000000E+00); phi_Val[4][4].Set_Equal_To(1.78838086814579439E-01); phi_Val[4][5].Set_Equal_To(0.00000000000000000E+00); // // set of quadrature points // static const double Quad_Points[NQ][SUB_TD] = { \ // 4.69100770306680737E-02, \ // 2.30765344947158446E-01, \ // 5.00000000000000000E-01, \ // 7.69234655052841498E-01, \ // 9.53089922969331926E-01 \ // }; // // set of quadrature weights // static const double Quad_Weights[NQ] = { \ // 1.18463442528094529E-01, \ // 2.39314335249683374E-01, \ // 2.84444444444444333E-01, \ // 2.39314335249683430E-01, \ // 1.18463442528094445E-01 \ // }; /*------------ END: Auto Generate ------------*/ // copy function evaluations over (indexing is in the C style) // loop through quad points for (int qp_i = 0; (qp_i < Num_QP); qp_i++) { // evaluate for each basis function for (int basis_i = 0; (basis_i < Num_Basis); basis_i++) { BF_V[basis_i][qp_i].a = phi_Val[qp_i][basis_i].a; } } } /***************************************************************************************/ /*------------ END: Auto Generate ------------*/ /*------------ BEGIN: Auto Generate ------------*/ /***************************************************************************************/ /* evaluate basis functions (no derivatives!) on the local reference element. */ void SpecificFUNC::Basis_Value_n2(SCALAR BF_V[NB][NQ]) { /*------------ BEGIN: Auto Generate ------------*/ // Local Element defined on Subdomain: CG, lagrange_deg2_dim2 // the Subdomain has topological dimension = 2 // the Domain of Integration has topological dimension = 1 // geometric dimension = 3 // Number of Quadrature Points = 5 // get "Val" of basis functions SCALAR phi_Val[NQ][NB]; phi_Val[0][0].Set_Equal_To(8.63670879562042249E-01); phi_Val[0][1].Set_Equal_To(0.00000000000000000E+00); phi_Val[0][2].Set_Equal_To(-4.25089663766216458E-02); phi_Val[0][3].Set_Equal_To(0.00000000000000000E+00); phi_Val[0][4].Set_Equal_To(1.78838086814579439E-01); phi_Val[0][5].Set_Equal_To(0.00000000000000000E+00); phi_Val[1][0].Set_Equal_To(4.14209254015686701E-01); phi_Val[1][1].Set_Equal_To(0.00000000000000000E+00); phi_Val[1][2].Set_Equal_To(-1.24260056089996393E-01); phi_Val[1][3].Set_Equal_To(0.00000000000000000E+00); phi_Val[1][4].Set_Equal_To(7.10050802074309706E-01); phi_Val[1][5].Set_Equal_To(0.00000000000000000E+00); phi_Val[2][0].Set_Equal_To(0.00000000000000000E+00); phi_Val[2][1].Set_Equal_To(0.00000000000000000E+00); phi_Val[2][2].Set_Equal_To(0.00000000000000000E+00); phi_Val[2][3].Set_Equal_To(0.00000000000000000E+00); phi_Val[2][4].Set_Equal_To(1.00000000000000000E+00); phi_Val[2][5].Set_Equal_To(0.00000000000000000E+00); phi_Val[3][0].Set_Equal_To(-1.24260056089996393E-01); phi_Val[3][1].Set_Equal_To(0.00000000000000000E+00); phi_Val[3][2].Set_Equal_To(4.14209254015686590E-01); phi_Val[3][3].Set_Equal_To(0.00000000000000000E+00); phi_Val[3][4].Set_Equal_To(7.10050802074309817E-01); phi_Val[3][5].Set_Equal_To(0.00000000000000000E+00); phi_Val[4][0].Set_Equal_To(-4.25089663766216458E-02); phi_Val[4][1].Set_Equal_To(0.00000000000000000E+00); phi_Val[4][2].Set_Equal_To(8.63670879562042249E-01); phi_Val[4][3].Set_Equal_To(0.00000000000000000E+00); phi_Val[4][4].Set_Equal_To(1.78838086814579439E-01); phi_Val[4][5].Set_Equal_To(0.00000000000000000E+00); // // set of quadrature points // static const double Quad_Points[NQ][SUB_TD] = { \ // 4.69100770306680737E-02, \ // 2.30765344947158446E-01, \ // 5.00000000000000000E-01, \ // 7.69234655052841498E-01, \ // 9.53089922969331926E-01 \ // }; // // set of quadrature weights // static const double Quad_Weights[NQ] = { \ // 1.18463442528094529E-01, \ // 2.39314335249683374E-01, \ // 2.84444444444444333E-01, \ // 2.39314335249683430E-01, \ // 1.18463442528094445E-01 \ // }; /*------------ END: Auto Generate ------------*/ // copy function evaluations over (indexing is in the C style) // loop through quad points for (int qp_i = 0; (qp_i < Num_QP); qp_i++) { // evaluate for each basis function for (int basis_i = 0; (basis_i < Num_Basis); basis_i++) { BF_V[basis_i][qp_i].a = phi_Val[qp_i][basis_i].a; } } } /***************************************************************************************/ /*------------ END: Auto Generate ------------*/ /*------------ BEGIN: Auto Generate ------------*/ /***************************************************************************************/ /* evaluate basis functions (no derivatives!) on the local reference element. */ void SpecificFUNC::Basis_Value_p3(SCALAR BF_V[NB][NQ]) { /*------------ BEGIN: Auto Generate ------------*/ // Local Element defined on Subdomain: CG, lagrange_deg2_dim2 // the Subdomain has topological dimension = 2 // the Domain of Integration has topological dimension = 1 // geometric dimension = 3 // Number of Quadrature Points = 5 // get "Val" of basis functions SCALAR phi_Val[NQ][NB]; phi_Val[0][0].Set_Equal_To(8.63670879562042249E-01); phi_Val[0][1].Set_Equal_To(-4.25089663766216458E-02); phi_Val[0][2].Set_Equal_To(0.00000000000000000E+00); phi_Val[0][3].Set_Equal_To(0.00000000000000000E+00); phi_Val[0][4].Set_Equal_To(0.00000000000000000E+00); phi_Val[0][5].Set_Equal_To(1.78838086814579439E-01); phi_Val[1][0].Set_Equal_To(4.14209254015686701E-01); phi_Val[1][1].Set_Equal_To(-1.24260056089996393E-01); phi_Val[1][2].Set_Equal_To(0.00000000000000000E+00); phi_Val[1][3].Set_Equal_To(0.00000000000000000E+00); phi_Val[1][4].Set_Equal_To(0.00000000000000000E+00); phi_Val[1][5].Set_Equal_To(7.10050802074309706E-01); phi_Val[2][0].Set_Equal_To(0.00000000000000000E+00); phi_Val[2][1].Set_Equal_To(0.00000000000000000E+00); phi_Val[2][2].Set_Equal_To(0.00000000000000000E+00); phi_Val[2][3].Set_Equal_To(0.00000000000000000E+00); phi_Val[2][4].Set_Equal_To(0.00000000000000000E+00); phi_Val[2][5].Set_Equal_To(1.00000000000000000E+00); phi_Val[3][0].Set_Equal_To(-1.24260056089996393E-01); phi_Val[3][1].Set_Equal_To(4.14209254015686590E-01); phi_Val[3][2].Set_Equal_To(0.00000000000000000E+00); phi_Val[3][3].Set_Equal_To(0.00000000000000000E+00); phi_Val[3][4].Set_Equal_To(0.00000000000000000E+00); phi_Val[3][5].Set_Equal_To(7.10050802074309817E-01); phi_Val[4][0].Set_Equal_To(-4.25089663766216458E-02); phi_Val[4][1].Set_Equal_To(8.63670879562042249E-01); phi_Val[4][2].Set_Equal_To(0.00000000000000000E+00); phi_Val[4][3].Set_Equal_To(0.00000000000000000E+00); phi_Val[4][4].Set_Equal_To(0.00000000000000000E+00); phi_Val[4][5].Set_Equal_To(1.78838086814579439E-01); // // set of quadrature points // static const double Quad_Points[NQ][SUB_TD] = { \ // 4.69100770306680737E-02, \ // 2.30765344947158446E-01, \ // 5.00000000000000000E-01, \ // 7.69234655052841498E-01, \ // 9.53089922969331926E-01 \ // }; // // set of quadrature weights // static const double Quad_Weights[NQ] = { \ // 1.18463442528094529E-01, \ // 2.39314335249683374E-01, \ // 2.84444444444444333E-01, \ // 2.39314335249683430E-01, \ // 1.18463442528094445E-01 \ // }; /*------------ END: Auto Generate ------------*/ // copy function evaluations over (indexing is in the C style) // loop through quad points for (int qp_i = 0; (qp_i < Num_QP); qp_i++) { // evaluate for each basis function for (int basis_i = 0; (basis_i < Num_Basis); basis_i++) { BF_V[basis_i][qp_i].a = phi_Val[qp_i][basis_i].a; } } } /***************************************************************************************/ /*------------ END: Auto Generate ------------*/ /*------------ BEGIN: Auto Generate ------------*/ /***************************************************************************************/ /* evaluate basis functions (no derivatives!) on the local reference element. */ void SpecificFUNC::Basis_Value_n3(SCALAR BF_V[NB][NQ]) { /*------------ BEGIN: Auto Generate ------------*/ // Local Element defined on Subdomain: CG, lagrange_deg2_dim2 // the Subdomain has topological dimension = 2 // the Domain of Integration has topological dimension = 1 // geometric dimension = 3 // Number of Quadrature Points = 5 // get "Val" of basis functions SCALAR phi_Val[NQ][NB]; phi_Val[0][0].Set_Equal_To(-4.25089663766216458E-02); phi_Val[0][1].Set_Equal_To(8.63670879562042249E-01); phi_Val[0][2].Set_Equal_To(0.00000000000000000E+00); phi_Val[0][3].Set_Equal_To(0.00000000000000000E+00); phi_Val[0][4].Set_Equal_To(0.00000000000000000E+00); phi_Val[0][5].Set_Equal_To(1.78838086814579439E-01); phi_Val[1][0].Set_Equal_To(-1.24260056089996393E-01); phi_Val[1][1].Set_Equal_To(4.14209254015686701E-01); phi_Val[1][2].Set_Equal_To(0.00000000000000000E+00); phi_Val[1][3].Set_Equal_To(0.00000000000000000E+00); phi_Val[1][4].Set_Equal_To(0.00000000000000000E+00); phi_Val[1][5].Set_Equal_To(7.10050802074309706E-01); phi_Val[2][0].Set_Equal_To(0.00000000000000000E+00); phi_Val[2][1].Set_Equal_To(0.00000000000000000E+00); phi_Val[2][2].Set_Equal_To(0.00000000000000000E+00); phi_Val[2][3].Set_Equal_To(0.00000000000000000E+00); phi_Val[2][4].Set_Equal_To(0.00000000000000000E+00); phi_Val[2][5].Set_Equal_To(1.00000000000000000E+00); phi_Val[3][0].Set_Equal_To(4.14209254015686590E-01); phi_Val[3][1].Set_Equal_To(-1.24260056089996393E-01); phi_Val[3][2].Set_Equal_To(0.00000000000000000E+00); phi_Val[3][3].Set_Equal_To(0.00000000000000000E+00); phi_Val[3][4].Set_Equal_To(0.00000000000000000E+00); phi_Val[3][5].Set_Equal_To(7.10050802074309817E-01); phi_Val[4][0].Set_Equal_To(8.63670879562042249E-01); phi_Val[4][1].Set_Equal_To(-4.25089663766216458E-02); phi_Val[4][2].Set_Equal_To(0.00000000000000000E+00); phi_Val[4][3].Set_Equal_To(0.00000000000000000E+00); phi_Val[4][4].Set_Equal_To(0.00000000000000000E+00); phi_Val[4][5].Set_Equal_To(1.78838086814579439E-01); // // set of quadrature points // static const double Quad_Points[NQ][SUB_TD] = { \ // 4.69100770306680737E-02, \ // 2.30765344947158446E-01, \ // 5.00000000000000000E-01, \ // 7.69234655052841498E-01, \ // 9.53089922969331926E-01 \ // }; // // set of quadrature weights // static const double Quad_Weights[NQ] = { \ // 1.18463442528094529E-01, \ // 2.39314335249683374E-01, \ // 2.84444444444444333E-01, \ // 2.39314335249683430E-01, \ // 1.18463442528094445E-01 \ // }; /*------------ END: Auto Generate ------------*/ // copy function evaluations over (indexing is in the C style) // loop through quad points for (int qp_i = 0; (qp_i < Num_QP); qp_i++) { // evaluate for each basis function for (int basis_i = 0; (basis_i < Num_Basis); basis_i++) { BF_V[basis_i][qp_i].a = phi_Val[qp_i][basis_i].a; } } } /***************************************************************************************/ /*------------ END: Auto Generate ------------*/ // remove those macros! #undef SpecificFUNC #undef SpecificFUNC_str #undef SPACE_type #undef SPACE_name #undef SUB_TD #undef DOI_TD #undef GD #undef NC #undef NB #undef NQ /***/
39.465213
132
0.587686
brianchowlab
4f482c11c7912c8b7e7ecb1ddaa736d64031bde7
1,541
cpp
C++
modules/core/base/cover/operator/simd/divides.cpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
34
2017-05-19T18:10:17.000Z
2022-01-04T02:18:13.000Z
modules/core/base/cover/operator/simd/divides.cpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
null
null
null
modules/core/base/cover/operator/simd/divides.cpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
7
2017-12-02T12:59:17.000Z
2021-07-31T12:46:14.000Z
//============================================================================== // Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2012 LRI UMR 8623 CNRS/Univ Paris Sud XI // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #include <nt2/operator/include/functions/divides.hpp> #include <boost/simd/sdk/simd/native.hpp> #include <boost/simd/sdk/simd/io.hpp> #include <nt2/include/constants/one.hpp> #include <nt2/include/constants/valmin.hpp> #include <nt2/include/constants/valmax.hpp> #include <vector> #include <nt2/sdk/unit/module.hpp> #include <nt2/sdk/unit/tests/cover.hpp> NT2_TEST_CASE_TPL ( divides_all_types, NT2_SIMD_TYPES) { using nt2::divides; using nt2::tag::divides_; using boost::simd::native; typedef NT2_SIMD_DEFAULT_EXTENSION ext_t; typedef native<T,ext_t> nT; typedef typename nt2::meta::call<divides_(T, T)>::type r_t; // random verifications nt2::uint32_t NR = NT2_NB_RANDOM_TEST; std::vector<T> in1(NR), in2(NR); nt2::roll(in1, nt2::Valmin<T>()/2, nt2::Valmax<T>()/2); nt2::roll(in2, nt2::One<T>(), nt2::Valmax<T>()/2); std::vector<r_t> ref(NR); for(nt2::uint32_t i=0; i < NR ; ++i) ref[i] = divides(in1[i], in2[i]); NT2_COVER_ULP_EQUAL(divides_, ((nT, in1))((nT, in2)), ref, 0); }
37.585366
80
0.592472
psiha
4f48cf2b42c42b2175503c589fc5a3d27737b8af
2,683
cpp
C++
src/profiler/util/util.cpp
ABaboshin/DotNetCoreProfiler
1421bb265317e23c447d5087e4739a9ae9fdc9ba
[ "MIT" ]
9
2020-05-28T14:29:15.000Z
2021-06-24T01:57:29.000Z
src/profiler/util/util.cpp
ABaboshin/DotNetCoreProfiler
1421bb265317e23c447d5087e4739a9ae9fdc9ba
[ "MIT" ]
null
null
null
src/profiler/util/util.cpp
ABaboshin/DotNetCoreProfiler
1421bb265317e23c447d5087e4739a9ae9fdc9ba
[ "MIT" ]
2
2020-12-21T14:57:29.000Z
2021-06-23T06:59:54.000Z
#include <cstdlib> #include <iostream> #include "miniutf/miniutf.hpp" #include "util.h" namespace util { std::string GetEnvironmentValue(const std::string& name) { auto cstr = std::getenv(name.c_str()); if (cstr == nullptr) { return ""; } return std::string(cstr); } wstring ToString(const std::vector<WCHAR>& data, size_t length) { if (data.empty() || length == 0) { return wstring(); } auto result = wstring(data.begin(), data.begin() + length); while (result[result.length() - 1] == 0) { result.resize(result.length() - 1); } return result; } std::vector<WCHAR> ToRaw(const wstring& str) { return std::vector<WCHAR>(str.begin(), str.end()); } std::vector<BYTE> ToRaw(PCCOR_SIGNATURE signature, ULONG length) { return std::vector<BYTE>(&signature[0], &signature[length]); } wstring ToWSTRING(const std::string& str) { auto ustr = miniutf::to_utf16(str); return wstring(reinterpret_cast<const WCHAR*>(ustr.c_str())); } std::string ToString(const wstring& wstr) { std::u16string ustr(reinterpret_cast<const char16_t*>(wstr.c_str())); return miniutf::to_utf8(ustr); } WCHAR operator"" _W(const char c) { return WCHAR(c); } wstring operator"" _W(const char* arr, size_t size) { std::string str(arr, size); return ToWSTRING(str); } wstring ToWSTRING(const char* str) { return ToWSTRING(std::string(str)); } wstring Trim(const wstring& str) { if (str.length() == 0) { return ""_W; } wstring trimmed = str; auto trimSymbols = " \t\r\n\0"_W; auto lpos = trimmed.find_first_not_of(trimSymbols); if (lpos != std::string::npos && lpos > 0) { trimmed = trimmed.substr(lpos); } auto rpos = trimmed.find_last_not_of(trimSymbols); if (rpos != std::string::npos) { trimmed = trimmed.substr(0, rpos + 1); } return trimmed; } std::string Trim(const std::string& str) { if (str.length() == 0) { return ""; } std::string trimmed = str; auto trimSymbols = " \t\r\n\0"; auto lpos = trimmed.find_first_not_of(trimSymbols); if (lpos != std::string::npos && lpos > 0) { trimmed = trimmed.substr(lpos); } auto rpos = trimmed.find_last_not_of(trimSymbols); if (rpos != std::string::npos) { trimmed = trimmed.substr(0, rpos + 1); } return trimmed; } }
24.842593
77
0.549758
ABaboshin
4f49184aabdd041b5a6a5c0a40bff72e3182b7c5
3,548
hpp
C++
third_party/protozero/test/include/scalar_access.hpp
asaveljevs/osrm-backend
15f0ca8ddaa35c5b4d93c25afa72e81e1fb40c3e
[ "BSD-2-Clause" ]
13
2019-02-21T02:02:41.000Z
2021-09-09T13:49:31.000Z
third_party/protozero/test/include/scalar_access.hpp
serarca/osrm-backend
3b4e2e83ef85983df1381dbeacd0ea5d4b9bbbcb
[ "BSD-2-Clause" ]
288
2019-02-21T01:34:04.000Z
2021-03-27T12:19:10.000Z
third_party/protozero/test/include/scalar_access.hpp
serarca/osrm-backend
3b4e2e83ef85983df1381dbeacd0ea5d4b9bbbcb
[ "BSD-2-Clause" ]
4
2019-06-21T20:51:59.000Z
2021-01-13T09:22:24.000Z
// NOLINT(llvm-header-guard) #define PBF_TYPE_NAME PROTOZERO_TEST_STRING(PBF_TYPE) #define GET_TYPE PROTOZERO_TEST_CONCAT(get_, PBF_TYPE) #define ADD_TYPE PROTOZERO_TEST_CONCAT(add_, PBF_TYPE) TEST_CASE("read field: " PBF_TYPE_NAME) { SECTION("zero") { const std::string buffer = load_data(PBF_TYPE_NAME "/data-zero"); protozero::pbf_reader item{buffer}; REQUIRE(item.next()); REQUIRE(item.GET_TYPE() == 0); REQUIRE_FALSE(item.next()); } SECTION("positive") { const std::string buffer = load_data(PBF_TYPE_NAME "/data-pos"); protozero::pbf_reader item{buffer}; REQUIRE(item.next()); REQUIRE(item.GET_TYPE() == 1); REQUIRE_FALSE(item.next()); } SECTION("pos200") { const std::string buffer = load_data(PBF_TYPE_NAME "/data-pos200"); protozero::pbf_reader item{buffer}; REQUIRE(item.next()); REQUIRE(item.GET_TYPE() == 200); REQUIRE_FALSE(item.next()); } SECTION("max") { const std::string buffer = load_data(PBF_TYPE_NAME "/data-max"); protozero::pbf_reader item{buffer}; REQUIRE(item.next()); REQUIRE(item.GET_TYPE() == std::numeric_limits<cpp_type>::max()); REQUIRE_FALSE(item.next()); } #if PBF_TYPE_IS_SIGNED SECTION("negative") { if (std::is_signed<cpp_type>::value) { const std::string buffer = load_data(PBF_TYPE_NAME "/data-neg"); protozero::pbf_reader item{buffer}; REQUIRE(item.next()); REQUIRE(item.GET_TYPE() == -1); REQUIRE_FALSE(item.next()); } } SECTION("neg200") { const std::string buffer = load_data(PBF_TYPE_NAME "/data-neg200"); protozero::pbf_reader item{buffer}; REQUIRE(item.next()); REQUIRE(item.GET_TYPE() == -200); REQUIRE_FALSE(item.next()); } SECTION("min") { if (std::is_signed<cpp_type>::value) { const std::string buffer = load_data(PBF_TYPE_NAME "/data-min"); protozero::pbf_reader item{buffer}; REQUIRE(item.next()); REQUIRE(item.GET_TYPE() == std::numeric_limits<cpp_type>::min()); REQUIRE_FALSE(item.next()); } } #endif SECTION("end_of_buffer") { const std::string buffer = load_data(PBF_TYPE_NAME "/data-max"); for (std::string::size_type i = 1; i < buffer.size(); ++i) { protozero::pbf_reader item{buffer.data(), i}; REQUIRE(item.next()); REQUIRE_THROWS_AS(item.GET_TYPE(), const protozero::end_of_buffer_exception&); } } } TEST_CASE("write field: " PBF_TYPE_NAME) { std::string buffer; protozero::pbf_writer pw(buffer); SECTION("zero") { pw.ADD_TYPE(1, 0); REQUIRE(buffer == load_data(PBF_TYPE_NAME "/data-zero")); } SECTION("positive") { pw.ADD_TYPE(1, 1); REQUIRE(buffer == load_data(PBF_TYPE_NAME "/data-pos")); } SECTION("max") { pw.ADD_TYPE(1, std::numeric_limits<cpp_type>::max()); REQUIRE(buffer == load_data(PBF_TYPE_NAME "/data-max")); } #if PBF_TYPE_IS_SIGNED SECTION("negative") { pw.ADD_TYPE(1, -1); REQUIRE(buffer == load_data(PBF_TYPE_NAME "/data-neg")); } SECTION("min") { if (std::is_signed<cpp_type>::value) { pw.ADD_TYPE(1, std::numeric_limits<cpp_type>::min()); REQUIRE(buffer == load_data(PBF_TYPE_NAME "/data-min")); } } #endif }
27.292308
90
0.590192
asaveljevs
4f4b473a0972f734c233f9d12c6b1c3556a9600d
2,793
cpp
C++
migration.cpp
pkrdac/pkrcustodian
61deaace35e931d8a461b74087307fd1bca6770a
[ "MIT" ]
null
null
null
migration.cpp
pkrdac/pkrcustodian
61deaace35e931d8a461b74087307fd1bca6770a
[ "MIT" ]
null
null
null
migration.cpp
pkrdac/pkrcustodian
61deaace35e931d8a461b74087307fd1bca6770a
[ "MIT" ]
null
null
null
template <typename T> void cleanTable(uint64_t code, uint64_t account){ T db(code, account); while(db.begin() != db.end()){ auto itr = --db.end(); db.erase(itr); } } void daccustodian::migrate() { // contr_config2 oldconf = configs(); // contr_config newconfig{ // oldconf.lockupasset, // oldconf.maxvotes, // oldconf.numelected, // oldconf.periodlength, // oldconf.authaccount, // oldconf.tokenholder, // oldconf.tokenholder, // true, // oldconf.initial_vote_quorum_percent, // oldconf.vote_quorum_percent, // oldconf.auth_threshold_high, // oldconf.auth_threshold_mid, // oldconf.auth_threshold_low, // oldconf.lockup_release_time_delay, // oldconf.requested_pay_max}; // // config_singleton.set(newconfig, _self); // Remove the old configs so the schema can be changed. // configscontainer2 configs(_self, _self); // configs.remove(); // contract_state.remove(); // _currentState = contr_state{}; // cleanTable<candidates_table>(_self, _self.value); // cleanTable<custodians_table>(_self, _self.value); // cleanTable<votes_table>(_self, _self.value); // cleanTable<pending_pay_table>(_self, _self.value); /* //Copy to a holding table - Enable this for the first step candidates_table oldcands(_self, _self.value); candidates_table2 holding_table(_self, _self.value); auto it = oldcands.begin(); while (it != oldcands.end()) { holding_table.emplace(_self, [&](candidate2 &c) { c.candidate_name = it->candidate_name; c.bio = it->bio; c.requestedpay = it->requestedpay; c.pendreqpay = it->pendreqpay; c.locked_tokens = it->locked_tokens; c.total_votes = it->total_votes; }); it = oldcands.erase(it); } // Copy back to the original table with the new schema - Enable this for the second step *after* modifying the original object's schema before copying back to the original table location. candidates_table2 holding_table(_self, _self.value); candidates_table oldcands(_self, _self.value); auto it = holding_table.begin(); while (it != holding_table.end()) { oldcands.emplace(_self, [&](candidate &c) { c.candidate_name = it->candidate_name; c.bio = it->bio; c.requestedpay = it->requestedpay; c.locked_tokens = it->locked_tokens; c.total_votes = it->total_votes; }); it = holding_table.erase(it); } */ }
33.25
191
0.587898
pkrdac
4f4fc080380713620b65905d79eaa28da6af743b
157,085
cc
C++
src/bin/dhcp4/tests/dhcp4_srv_unittest.cc
piskyscan/kea
72c0a679a1101aada8d22c98abf7bde615fa7a11
[ "Apache-2.0" ]
null
null
null
src/bin/dhcp4/tests/dhcp4_srv_unittest.cc
piskyscan/kea
72c0a679a1101aada8d22c98abf7bde615fa7a11
[ "Apache-2.0" ]
null
null
null
src/bin/dhcp4/tests/dhcp4_srv_unittest.cc
piskyscan/kea
72c0a679a1101aada8d22c98abf7bde615fa7a11
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2011-2020 Internet Systems Consortium, Inc. ("ISC") // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include <config.h> #include <sstream> #include <asiolink/io_address.h> #include <cc/command_interpreter.h> #include <config/command_mgr.h> #include <dhcp4/tests/dhcp4_test_utils.h> #include <dhcp4/tests/dhcp4_client.h> #include <dhcp/tests/pkt_captures.h> #include <dhcp/dhcp4.h> #include <dhcp/iface_mgr.h> #include <dhcp/libdhcp++.h> #include <dhcp/option.h> #include <dhcp/option_int.h> #include <dhcp/option4_addrlst.h> #include <dhcp/option_custom.h> #include <dhcp/option_int_array.h> #include <dhcp/pkt_filter.h> #include <dhcp/pkt_filter_inet.h> #include <dhcp/tests/iface_mgr_test_config.h> #include <dhcp4/dhcp4_srv.h> #include <dhcp4/dhcp4_log.h> #include <dhcp4/json_config_parser.h> #include <dhcpsrv/cfgmgr.h> #include <dhcpsrv/lease_mgr.h> #include <dhcpsrv/lease_mgr_factory.h> #include <dhcpsrv/utils.h> #include <dhcpsrv/host_mgr.h> #include <stats/stats_mgr.h> #include <testutils/gtest_utils.h> #include <util/encode/hex.h> #include <boost/scoped_ptr.hpp> #include <iostream> #include <cstdlib> #include <arpa/inet.h> using namespace std; using namespace isc; using namespace isc::dhcp; using namespace isc::data; using namespace isc::asiolink; using namespace isc::config; using namespace isc::dhcp::test; namespace { const char* CONFIGS[] = { // Configuration 0: // - 1 subnet: 10.254.226.0/25 // - used for recorded traffic (see PktCaptures::captureRelayedDiscover) "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ]" "}," "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"subnet4\": [ { " " \"pools\": [ { \"pool\": \"10.254.226.0/25\" } ]," " \"subnet\": \"10.254.226.0/24\", " " \"rebind-timer\": 2000, " " \"renew-timer\": 1000, " " \"valid-lifetime\": 4000," " \"interface\": \"eth0\" " " } ]," "\"valid-lifetime\": 4000 }", // Configuration 1: // - 1 subnet: 192.0.2.0/24 // - MySQL Host Data Source configured "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ]" "}," "\"hosts-database\": {" " \"type\": \"mysql\"," " \"name\": \"keatest\"," " \"user\": \"keatest\"," " \"password\": \"keatest\"" "}," "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"subnet4\": [ { " " \"pools\": [ { \"pool\": \"192.0.2.1 - 192.0.2.100\" } ]," " \"subnet\": \"192.0.2.0/24\", " " \"rebind-timer\": 2000, " " \"renew-timer\": 1000, " " \"valid-lifetime\": 4000," " \"interface\": \"eth0\" " " } ]," "\"valid-lifetime\": 4000 }", // Configuration 2: // - 1 subnet, 2 global options (one forced with always-send) "{" " \"interfaces-config\": {" " \"interfaces\": [ \"*\" ] }, " " \"rebind-timer\": 2000, " " \"renew-timer\": 1000, " " \"valid-lifetime\": 4000, " " \"subnet4\": [ {" " \"pools\": [ { \"pool\": \"192.0.2.1 - 192.0.2.100\" } ], " " \"subnet\": \"192.0.2.0/24\"" " } ], " " \"option-data\": [" " {" " \"name\": \"default-ip-ttl\", " " \"data\": \"FF\", " " \"csv-format\": false" " }, " " {" " \"name\": \"ip-forwarding\", " " \"data\": \"false\", " " \"always-send\": true" " }" " ]" "}", // Configuration 3: // - one subnet, with one pool // - user-contexts defined in both subnet and pool "{" " \"subnet4\": [ { " " \"pools\": [ { \"pool\": \"10.254.226.0/25\"," " \"user-context\": { \"value\": 42 } } ]," " \"subnet\": \"10.254.226.0/24\", " " \"user-context\": {" " \"secure\": false" " }" " } ]," "\"valid-lifetime\": 4000 }", }; // This test verifies that the destination address of the response // message is set to giaddr, when giaddr is set to non-zero address // in the received message. TEST_F(Dhcpv4SrvTest, adjustIfaceDataRelay) { IfaceMgrTestConfig test_config(true); IfaceMgr::instance().openSockets4(); // Create the instance of the incoming packet. boost::shared_ptr<Pkt4> req(new Pkt4(DHCPDISCOVER, 1234)); // Set the giaddr to non-zero address and hops to non-zero value // as if it was relayed. req->setGiaddr(IOAddress("192.0.1.1")); req->setHops(2); // Set ciaddr to zero. This simulates the client which applies // for the new lease. req->setCiaddr(IOAddress("0.0.0.0")); // Clear broadcast flag. req->setFlags(0x0000); // Set local address, port and interface. req->setLocalAddr(IOAddress("192.0.2.5")); req->setLocalPort(1001); req->setIface("eth1"); req->setIndex(ETH1_INDEX); // Set remote port (it will be used in the next test). req->setRemotePort(1234); // Create the exchange using the req. Dhcpv4Exchange ex = createExchange(req); Pkt4Ptr resp = ex.getResponse(); resp->setYiaddr(IOAddress("192.0.1.100")); // Clear the remote address. resp->setRemoteAddr(IOAddress("0.0.0.0")); // Set hops value for the response. resp->setHops(req->getHops()); // This function never throws. ASSERT_NO_THROW(srv_.adjustIfaceData(ex)); // Now the destination address should be relay's address. EXPECT_EQ("192.0.1.1", resp->getRemoteAddr().toText()); // The query has been relayed, so the response must be sent to the port 67. EXPECT_EQ(DHCP4_SERVER_PORT, resp->getRemotePort()); // Local address should be the address assigned to interface eth1. EXPECT_EQ("192.0.2.5", resp->getLocalAddr().toText()); // The local port is always DHCPv4 server port 67. EXPECT_EQ(DHCP4_SERVER_PORT, resp->getLocalPort()); // We will send response over the same interface which was used to receive // query. EXPECT_EQ("eth1", resp->getIface()); EXPECT_EQ(ETH1_INDEX, resp->getIndex()); // Let's do another test and set other fields: ciaddr and // flags. By doing it, we want to make sure that the relay // address will take precedence. req->setGiaddr(IOAddress("192.0.1.50")); req->setCiaddr(IOAddress("192.0.1.11")); req->setFlags(Pkt4::FLAG_BROADCAST_MASK); resp->setYiaddr(IOAddress("192.0.1.100")); // Clear remote address. resp->setRemoteAddr(IOAddress("0.0.0.0")); // Set the client and server ports. srv_.client_port_ = 1234; srv_.server_port_ = 2345; ASSERT_NO_THROW(srv_.adjustIfaceData(ex)); // Response should be sent back to the relay address. EXPECT_EQ("192.0.1.50", resp->getRemoteAddr().toText()); // Remote port was enforced to the client port. EXPECT_EQ(srv_.client_port_, resp->getRemotePort()); // Local port was enforced to the server port. EXPECT_EQ(srv_.server_port_, resp->getLocalPort()); } // This test verifies that the remote port is adjusted when // the query carries a relay port RAI sub-option. TEST_F(Dhcpv4SrvTest, adjustIfaceDataRelayPort) { IfaceMgrTestConfig test_config(true); IfaceMgr::instance().openSockets4(); // Create the instance of the incoming packet. boost::shared_ptr<Pkt4> req(new Pkt4(DHCPDISCOVER, 1234)); // Set the giaddr to non-zero address and hops to non-zero value // as if it was relayed. req->setGiaddr(IOAddress("192.0.1.1")); req->setHops(2); // Set ciaddr to zero. This simulates the client which applies // for the new lease. req->setCiaddr(IOAddress("0.0.0.0")); // Clear broadcast flag. req->setFlags(0x0000); // Set local address, port and interface. req->setLocalAddr(IOAddress("192.0.2.5")); req->setLocalPort(1001); req->setIface("eth1"); req->setIndex(ETH1_INDEX); // Set remote port. req->setRemotePort(1234); // Add a RAI relay-port sub-option (the only difference with the previous test). OptionDefinitionPtr rai_def = LibDHCP::getOptionDef(DHCP4_OPTION_SPACE, DHO_DHCP_AGENT_OPTIONS); ASSERT_TRUE(rai_def); OptionCustomPtr rai(new OptionCustom(*rai_def, Option::V4)); ASSERT_TRUE(rai); req->addOption(rai); OptionPtr relay_port(new Option(Option::V4, RAI_OPTION_RELAY_PORT)); ASSERT_TRUE(relay_port); rai->addOption(relay_port); // Create the exchange using the req. Dhcpv4Exchange ex = createExchange(req); Pkt4Ptr resp = ex.getResponse(); resp->setYiaddr(IOAddress("192.0.1.100")); // Clear the remote address. resp->setRemoteAddr(IOAddress("0.0.0.0")); // Set hops value for the response. resp->setHops(req->getHops()); // Set the remote port to 67 as we know it will be updated. resp->setRemotePort(67); // This function never throws. ASSERT_NO_THROW(srv_.adjustIfaceData(ex)); // Now the destination address should be relay's address. EXPECT_EQ("192.0.1.1", resp->getRemoteAddr().toText()); // The query has been relayed, so the response should be sent to the // port 67, but here there is a relay port RAI so another value is used. EXPECT_EQ(1234, resp->getRemotePort()); // Local address should be the address assigned to interface eth1. EXPECT_EQ("192.0.2.5", resp->getLocalAddr().toText()); // The local port is always DHCPv4 server port 67. EXPECT_EQ(DHCP4_SERVER_PORT, resp->getLocalPort()); // We will send response over the same interface which was used to receive // query. EXPECT_EQ("eth1", resp->getIface()); EXPECT_EQ(ETH1_INDEX, resp->getIndex()); } // This test verifies that it is possible to configure the server to use // routing information to determine the right outbound interface to sent // responses to a relayed client. TEST_F(Dhcpv4SrvTest, adjustIfaceDataUseRouting) { IfaceMgrTestConfig test_config(true); IfaceMgr::instance().openSockets4(); // Create configuration for interfaces. It includes the outbound-interface // setting which indicates that the responses aren't neccessarily sent // over the same interface via which a request has been received, but routing // information is used to determine this interface. CfgMgr::instance().clear(); CfgIfacePtr cfg_iface = CfgMgr::instance().getStagingCfg()->getCfgIface(); cfg_iface->useSocketType(AF_INET, CfgIface::SOCKET_UDP); cfg_iface->use(AF_INET, "eth0"); cfg_iface->use(AF_INET, "eth1"); cfg_iface->setOutboundIface(CfgIface::USE_ROUTING); CfgMgr::instance().commit();; // Create the instance of the incoming packet. boost::shared_ptr<Pkt4> req(new Pkt4(DHCPDISCOVER, 1234)); // Set the giaddr to non-zero address and hops to non-zero value // as if it was relayed. req->setGiaddr(IOAddress("192.0.1.1")); req->setHops(2); // Set ciaddr to zero. This simulates the client which applies // for the new lease. req->setCiaddr(IOAddress("0.0.0.0")); // Clear broadcast flag. req->setFlags(0x0000); // Set local address, port and interface. req->setLocalAddr(IOAddress("192.0.2.5")); req->setLocalPort(1001); req->setIface("eth1"); req->setIndex(ETH1_INDEX); // Create the exchange using the req. Dhcpv4Exchange ex = createExchange(req); Pkt4Ptr resp = ex.getResponse(); resp->setYiaddr(IOAddress("192.0.1.100")); // Clear the remote address. resp->setRemoteAddr(IOAddress("0.0.0.0")); // Set hops value for the response. resp->setHops(req->getHops()); // This function never throws. ASSERT_NO_THROW(srv_.adjustIfaceData(ex)); // Now the destination address should be relay's address. EXPECT_EQ("192.0.1.1", resp->getRemoteAddr().toText()); // The query has been relayed, so the response must be sent to the port 67. EXPECT_EQ(DHCP4_SERVER_PORT, resp->getRemotePort()); // The local port is always DHCPv4 server port 67. EXPECT_EQ(DHCP4_SERVER_PORT, resp->getLocalPort()); // No specific interface is selected as outbound interface and no specific // local address is provided. The IfaceMgr will figure out which interface to use. EXPECT_TRUE(resp->getLocalAddr().isV4Zero()); EXPECT_FALSE(resp->indexSet()); // Fixed in #5515 so now the interface name is never empty. EXPECT_FALSE(resp->getIface().empty()); // Another test verifies that setting outbound interface to same as inbound will // cause the server to set interface and local address as expected. cfg_iface = CfgMgr::instance().getStagingCfg()->getCfgIface(); cfg_iface->useSocketType(AF_INET, CfgIface::SOCKET_UDP); cfg_iface->use(AF_INET, "eth0"); cfg_iface->use(AF_INET, "eth1"); cfg_iface->setOutboundIface(CfgIface::SAME_AS_INBOUND); CfgMgr::instance().commit(); ASSERT_NO_THROW(srv_.adjustIfaceData(ex)); EXPECT_EQ("192.0.2.5", resp->getLocalAddr().toText()); EXPECT_EQ("eth1", resp->getIface()); EXPECT_EQ(ETH1_INDEX, resp->getIndex()); } // This test verifies that the destination address of the response // message is set to source address when the testing mode is enabled. // Relayed message: not testing mode was tested in adjustIfaceDataRelay. TEST_F(Dhcpv4SrvTest, adjustRemoteAddressRelaySendToSourceTestingModeEnabled) { IfaceMgrTestConfig test_config(true); IfaceMgr::instance().openSockets4(); // Create the instance of the incoming packet. boost::shared_ptr<Pkt4> req(new Pkt4(DHCPDISCOVER, 1234)); // Set the giaddr to non-zero address and hops to non-zero value // as if it was relayed. req->setGiaddr(IOAddress("192.0.1.1")); req->setHops(2); // Set ciaddr to zero. This simulates the client which applies // for the new lease. req->setCiaddr(IOAddress("0.0.0.0")); // Clear broadcast flag. req->setFlags(0x0000); // Set local address, port and interface. req->setLocalAddr(IOAddress("192.0.2.5")); req->setLocalPort(1001); req->setIface("eth1"); req->setIndex(ETH1_INDEX); // Set remote address and port. req->setRemoteAddr(IOAddress("192.0.2.1")); req->setRemotePort(1234); // Create the exchange using the req. Dhcpv4Exchange ex = createExchange(req); Pkt4Ptr resp = ex.getResponse(); resp->setYiaddr(IOAddress("192.0.1.100")); // Clear the remote address. resp->setRemoteAddr(IOAddress("0.0.0.0")); // Set hops value for the response. resp->setHops(req->getHops()); // Set the testing mode. srv_.setSendResponsesToSource(true); // This function never throws. ASSERT_NO_THROW(srv_.adjustIfaceData(ex)); // Now the destination address should be source address. EXPECT_EQ("192.0.2.1", resp->getRemoteAddr().toText()); } // This test verifies that the destination address of the response message // is set to ciaddr when giaddr is set to zero and the ciaddr is set to // non-zero address in the received message. This is the case when the // client is in Renew or Rebind state. TEST_F(Dhcpv4SrvTest, adjustIfaceDataRenew) { IfaceMgrTestConfig test_config(true); IfaceMgr::instance().openSockets4(); // Create instance of the incoming packet. boost::shared_ptr<Pkt4> req(new Pkt4(DHCPDISCOVER, 1234)); // Clear giaddr to simulate direct packet. req->setGiaddr(IOAddress("0.0.0.0")); // Set ciaddr to non-zero address. The response should be sent to this // address as the client is in renewing or rebinding state (it is fully // configured). req->setCiaddr(IOAddress("192.0.1.15")); // Let's configure broadcast flag. It should be ignored because // we are responding directly to the client having an address // and trying to extend his lease. Broadcast flag is only used // when new lease is acquired and server must make a decision // whether to unicast the response to the acquired address or // broadcast it. req->setFlags(Pkt4::FLAG_BROADCAST_MASK); // This is a direct message, so the hops should be cleared. req->setHops(0); // Set local unicast address as if we are renewing a lease. req->setLocalAddr(IOAddress("192.0.2.1")); // Request is received on the DHCPv4 server port. req->setLocalPort(DHCP4_SERVER_PORT); // Set the interface. The response should be sent over the same interface. req->setIface("eth1"); req->setIndex(ETH1_INDEX); // Create the exchange using the req. Dhcpv4Exchange ex = createExchange(req); Pkt4Ptr resp = ex.getResponse(); // Let's extend the lease for the client in such a way that // it will actually get different address. The response // should not be sent to this address but rather to ciaddr // as client still have ciaddr configured. resp->setYiaddr(IOAddress("192.0.1.13")); // Clear the remote address. resp->setRemoteAddr(IOAddress("0.0.0.0")); // Copy hops value from the query. resp->setHops(req->getHops()); ASSERT_NO_THROW(srv_.adjustIfaceData(ex)); // Check that server responds to ciaddr EXPECT_EQ("192.0.1.15", resp->getRemoteAddr().toText()); // The query was non-relayed, so the response should be sent to a DHCPv4 // client port 68. EXPECT_EQ(DHCP4_CLIENT_PORT, resp->getRemotePort()); // The response should be sent from the unicast address on which the // query has been received. EXPECT_EQ("192.0.2.1", resp->getLocalAddr().toText()); // The response should be sent from the DHCPv4 server port. EXPECT_EQ(DHCP4_SERVER_PORT, resp->getLocalPort()); // The interface data should match the data in the query. EXPECT_EQ("eth1", resp->getIface()); EXPECT_EQ(ETH1_INDEX, resp->getIndex()); } // This test verifies that the destination address of the response message // is set to source address when the testing mode is enabled. // Renew: not testing mode was tested in adjustIfaceDataRenew. TEST_F(Dhcpv4SrvTest, adjustRemoteAddressRenewSendToSourceTestingModeEnabled) { IfaceMgrTestConfig test_config(true); IfaceMgr::instance().openSockets4(); // Create instance of the incoming packet. boost::shared_ptr<Pkt4> req(new Pkt4(DHCPDISCOVER, 1234)); // Clear giaddr to simulate direct packet. req->setGiaddr(IOAddress("0.0.0.0")); // Set ciaddr to non-zero address. The response should be sent to this // address as the client is in renewing or rebinding state (it is fully // configured). req->setCiaddr(IOAddress("192.0.1.15")); // Let's configure broadcast flag. It should be ignored because // we are responding directly to the client having an address // and trying to extend his lease. Broadcast flag is only used // when new lease is acquired and server must make a decision // whether to unicast the response to the acquired address or // broadcast it. req->setFlags(Pkt4::FLAG_BROADCAST_MASK); // This is a direct message, so the hops should be cleared. req->setHops(0); // Set local unicast address as if we are renewing a lease. req->setLocalAddr(IOAddress("192.0.2.1")); // Request is received on the DHCPv4 server port. req->setLocalPort(DHCP4_SERVER_PORT); // Set the interface. The response should be sent over the same interface. req->setIface("eth1"); req->setIndex(ETH1_INDEX); // Set remote address. req->setRemoteAddr(IOAddress("192.0.2.1")); // Create the exchange using the req. Dhcpv4Exchange ex = createExchange(req); Pkt4Ptr resp = ex.getResponse(); // Let's extend the lease for the client in such a way that // it will actually get different address. The response // should not be sent to this address but rather to ciaddr // as client still have ciaddr configured. resp->setYiaddr(IOAddress("192.0.1.13")); // Clear the remote address. resp->setRemoteAddr(IOAddress("0.0.0.0")); // Copy hops value from the query. resp->setHops(req->getHops()); // Set the testing mode. srv_.setSendResponsesToSource(true); ASSERT_NO_THROW(srv_.adjustIfaceData(ex)); // Check that server responds to source address. EXPECT_EQ("192.0.2.1", resp->getRemoteAddr().toText()); } // This test verifies that the destination address of the response message // is set correctly when giaddr and ciaddr is zeroed in the received message // and the new lease is acquired. The lease address is carried in the // response message in the yiaddr field. In this case destination address // of the response should be set to yiaddr if server supports direct responses // to the client which doesn't have an address yet or broadcast if the server // doesn't support direct responses. TEST_F(Dhcpv4SrvTest, adjustIfaceDataSelect) { IfaceMgrTestConfig test_config(true); IfaceMgr::instance().openSockets4(); // Create instance of the incoming packet. boost::shared_ptr<Pkt4> req(new Pkt4(DHCPDISCOVER, 1234)); // Clear giaddr to simulate direct packet. req->setGiaddr(IOAddress("0.0.0.0")); // Clear client address as it hasn't got any address configured yet. req->setCiaddr(IOAddress("0.0.0.0")); // Let's clear the broadcast flag. req->setFlags(0); // This is a non-relayed message, so let's clear hops count. req->setHops(0); // The query is sent to the broadcast address in the Select state. req->setLocalAddr(IOAddress("255.255.255.255")); // The query has been received on the DHCPv4 server port 67. req->setLocalPort(DHCP4_SERVER_PORT); // Set the interface. The response should be sent via the same interface. req->setIface("eth1"); req->setIndex(ETH1_INDEX); // Create the exchange using the req. Dhcpv4Exchange ex = createExchange(req); Pkt4Ptr resp = ex.getResponse(); // Assign some new address for this client. resp->setYiaddr(IOAddress("192.0.1.13")); // Clear the remote address. resp->setRemoteAddr(IOAddress("0.0.0.0")); // Copy hops count. resp->setHops(req->getHops()); // We want to test the case, when the server (packet filter) doesn't support // direct responses to the client which doesn't have an address yet. In // case, the server should send its response to the broadcast address. // We can control whether the current packet filter returns that its support // direct responses or not. test_config.setDirectResponse(false); // When running unit tests, the IfaceMgr is using the default Packet // Filtering class, PktFilterInet. This class does not support direct // responses to clients without address assigned. When giaddr and ciaddr // are zero and client has just got new lease, the assigned address is // carried in yiaddr. In order to send this address to the client, // server must broadcast its response. ASSERT_NO_THROW(srv_.adjustIfaceData(ex)); // Check that the response is sent to broadcast address as the // server doesn't have capability to respond directly. EXPECT_EQ("255.255.255.255", resp->getRemoteAddr().toText()); // Although the query has been sent to the broadcast address, the // server should select a unicast address on the particular interface // as a source address for the response. EXPECT_EQ("192.0.2.3", resp->getLocalAddr().toText()); // The response should be sent from the DHCPv4 server port. EXPECT_EQ(DHCP4_SERVER_PORT, resp->getLocalPort()); // The response should be sent via the same interface through which // query has been received. EXPECT_EQ("eth1", resp->getIface()); EXPECT_EQ(ETH1_INDEX, resp->getIndex()); // We also want to test the case when the server has capability to // respond directly to the client which is not configured. Server // makes decision whether it responds directly or broadcast its // response based on the capability reported by IfaceMgr. We can // control whether the current packet filter returns that it supports // direct responses or not. test_config.setDirectResponse(true); // Now we expect that the server will send its response to the // address assigned for the client. ASSERT_NO_THROW(srv_.adjustIfaceData(ex)); EXPECT_EQ("192.0.1.13", resp->getRemoteAddr().toText()); } // This test verifies that the destination address of the response message // is set to source address when the testing mode is enabled. // Select cases: not testing mode were tested in adjustIfaceDataSelect. TEST_F(Dhcpv4SrvTest, adjustRemoteAddressSelectSendToSourceTestingModeEnabled) { IfaceMgrTestConfig test_config(true); IfaceMgr::instance().openSockets4(); // Create instance of the incoming packet. boost::shared_ptr<Pkt4> req(new Pkt4(DHCPDISCOVER, 1234)); // Clear giaddr to simulate direct packet. req->setGiaddr(IOAddress("0.0.0.0")); // Clear client address as it hasn't got any address configured yet. req->setCiaddr(IOAddress("0.0.0.0")); // Let's clear the broadcast flag. req->setFlags(0); // This is a non-relayed message, so let's clear hops count. req->setHops(0); // The query is sent to the broadcast address in the Select state. req->setLocalAddr(IOAddress("255.255.255.255")); // The query has been received on the DHCPv4 server port 67. req->setLocalPort(DHCP4_SERVER_PORT); // Set the interface. The response should be sent via the same interface. req->setIface("eth1"); req->setIndex(ETH1_INDEX); // Set remote address. req->setRemoteAddr(IOAddress("192.0.2.1")); // Create the exchange using the req. Dhcpv4Exchange ex = createExchange(req); Pkt4Ptr resp = ex.getResponse(); // Assign some new address for this client. resp->setYiaddr(IOAddress("192.0.1.13")); // Clear the remote address. resp->setRemoteAddr(IOAddress("0.0.0.0")); // Copy hops count. resp->setHops(req->getHops()); // Disable direct responses. test_config.setDirectResponse(false); // Set the testing mode. srv_.setSendResponsesToSource(true); ASSERT_NO_THROW(srv_.adjustIfaceData(ex)); // Check that server responds to source address. EXPECT_EQ("192.0.2.1", resp->getRemoteAddr().toText()); // Enable direct responses. test_config.setDirectResponse(true); // Clear the remote address. resp->setRemoteAddr(IOAddress("0.0.0.0")); ASSERT_NO_THROW(srv_.adjustIfaceData(ex)); // Check that server still responds to source address. EXPECT_EQ("192.0.2.1", resp->getRemoteAddr().toText()); } // This test verifies that the destination address of the response message // is set to broadcast address when client set broadcast flag in its // query. Client sets this flag to indicate that it can't receive direct // responses from the server when it doesn't have its interface configured. // Server must respect broadcast flag. TEST_F(Dhcpv4SrvTest, adjustIfaceDataBroadcast) { IfaceMgrTestConfig test_config(true); IfaceMgr::instance().openSockets4(); // Create instance of the incoming packet. boost::shared_ptr<Pkt4> req(new Pkt4(DHCPDISCOVER, 1234)); // Clear giaddr to simulate direct packet. req->setGiaddr(IOAddress("0.0.0.0")); // Clear client address as it hasn't got any address configured yet. req->setCiaddr(IOAddress("0.0.0.0")); // The query is sent to the broadcast address in the Select state. req->setLocalAddr(IOAddress("255.255.255.255")); // The query has been received on the DHCPv4 server port 67. req->setLocalPort(DHCP4_SERVER_PORT); // Set the interface. The response should be sent via the same interface. req->setIface("eth1"); req->setIndex(ETH1_INDEX); // Let's set the broadcast flag. req->setFlags(Pkt4::FLAG_BROADCAST_MASK); // Create the exchange using the req. Dhcpv4Exchange ex = createExchange(req); Pkt4Ptr resp = ex.getResponse(); // Assign some new address for this client. resp->setYiaddr(IOAddress("192.0.1.13")); // Clear the remote address. resp->setRemoteAddr(IOAddress("0.0.0.0")); ASSERT_NO_THROW(srv_.adjustIfaceData(ex)); // Server must respond to broadcast address when client desired that // by setting the broadcast flag in its request. EXPECT_EQ("255.255.255.255", resp->getRemoteAddr().toText()); // Although the query has been sent to the broadcast address, the // server should select a unicast address on the particular interface // as a source address for the response. EXPECT_EQ("192.0.2.3", resp->getLocalAddr().toText()); // The response should be sent from the DHCPv4 server port. EXPECT_EQ(DHCP4_SERVER_PORT, resp->getLocalPort()); // The response should be sent via the same interface through which // query has been received. EXPECT_EQ("eth1", resp->getIface()); EXPECT_EQ(ETH1_INDEX, resp->getIndex()); } // This test verifies that the destination address of the response message // is set to source address when the testing mode is enabled. // Broadcast case: not testing mode was tested in adjustIfaceDataBroadcast. TEST_F(Dhcpv4SrvTest, adjustRemoteAddressBroadcastSendToSourceTestingModeEnabled) { IfaceMgrTestConfig test_config(true); IfaceMgr::instance().openSockets4(); // Create instance of the incoming packet. boost::shared_ptr<Pkt4> req(new Pkt4(DHCPDISCOVER, 1234)); // Clear giaddr to simulate direct packet. req->setGiaddr(IOAddress("0.0.0.0")); // Clear client address as it hasn't got any address configured yet. req->setCiaddr(IOAddress("0.0.0.0")); // The query is sent to the broadcast address in the Select state. req->setLocalAddr(IOAddress("255.255.255.255")); // The query has been received on the DHCPv4 server port 67. req->setLocalPort(DHCP4_SERVER_PORT); // Set the interface. The response should be sent via the same interface. req->setIface("eth1"); req->setIndex(ETH1_INDEX); // Set remote address. req->setRemoteAddr(IOAddress("192.0.2.1")); // Let's set the broadcast flag. req->setFlags(Pkt4::FLAG_BROADCAST_MASK); // Create the exchange using the req. Dhcpv4Exchange ex = createExchange(req); Pkt4Ptr resp = ex.getResponse(); // Assign some new address for this client. resp->setYiaddr(IOAddress("192.0.1.13")); // Clear the remote address. resp->setRemoteAddr(IOAddress("0.0.0.0")); // Set the testing mode. srv_.setSendResponsesToSource(true); ASSERT_NO_THROW(srv_.adjustIfaceData(ex)); // Check that server responds to source address. EXPECT_EQ("192.0.2.1", resp->getRemoteAddr().toText()); } // This test verifies that the mandatory to copy fields and options // are really copied into the response. TEST_F(Dhcpv4SrvTest, initResponse) { Pkt4Ptr query(new Pkt4(DHCPDISCOVER, 1234)); // Set fields which must be copied query->setIface("foo"); query->setIndex(111); query->setHops(5); const HWAddr& hw = HWAddr::fromText("11:22:33:44:55:66:77:88", 10); HWAddrPtr hw_addr(new HWAddr(hw)); query->setHWAddr(hw_addr); query->setGiaddr(IOAddress("10.10.10.10")); const HWAddr& src_hw = HWAddr::fromText("e4:ce:8f:12:34:56"); HWAddrPtr src_hw_addr(new HWAddr(src_hw)); query->setLocalHWAddr(src_hw_addr); const HWAddr& dst_hw = HWAddr::fromText("e8:ab:cd:78:9a:bc"); HWAddrPtr dst_hw_addr(new HWAddr(dst_hw)); query->setRemoteHWAddr(dst_hw_addr); query->setFlags(BOOTP_BROADCAST); // Add options which must be copied // client-id echo is optional // rai echo is done in relayAgentInfoEcho // Do subnet selection option OptionDefinitionPtr sbnsel_def = LibDHCP::getOptionDef(DHCP4_OPTION_SPACE, DHO_SUBNET_SELECTION); ASSERT_TRUE(sbnsel_def); OptionCustomPtr sbnsel(new OptionCustom(*sbnsel_def, Option::V4)); ASSERT_TRUE(sbnsel); sbnsel->writeAddress(IOAddress("192.0.2.3")); query->addOption(sbnsel); // Create exchange and get Response Dhcpv4Exchange ex = createExchange(query); Pkt4Ptr response = ex.getResponse(); ASSERT_TRUE(response); // Check fields EXPECT_EQ("foo", response->getIface()); EXPECT_EQ(111, response->getIndex()); EXPECT_TRUE(response->getSiaddr().isV4Zero()); EXPECT_TRUE(response->getCiaddr().isV4Zero()); EXPECT_EQ(5, response->getHops()); EXPECT_TRUE(hw == *response->getHWAddr()); EXPECT_EQ(IOAddress("10.10.10.10"), response->getGiaddr()); EXPECT_TRUE(src_hw == *response->getLocalHWAddr()); EXPECT_TRUE(dst_hw == *response->getRemoteHWAddr()); EXPECT_TRUE(BOOTP_BROADCAST == response->getFlags()); // Check options (i.e., subnet selection option) OptionPtr resp_sbnsel = response->getOption(DHO_SUBNET_SELECTION); ASSERT_TRUE(resp_sbnsel); OptionCustomPtr resp_custom = boost::dynamic_pointer_cast<OptionCustom>(resp_sbnsel); ASSERT_TRUE(resp_custom); IOAddress subnet_addr("0.0.0.0"); ASSERT_NO_THROW(subnet_addr = resp_custom->readAddress()); EXPECT_EQ(IOAddress("192.0.2.3"), subnet_addr); } // This test verifies that the server identifier option is appended to // a specified DHCPv4 message and the server identifier is correct. TEST_F(Dhcpv4SrvTest, appendServerID) { Pkt4Ptr query(new Pkt4(DHCPDISCOVER, 1234)); Dhcpv4Exchange ex = createExchange(query); Pkt4Ptr response = ex.getResponse(); // Set a local address. It is required by the function under test // to create the Server Identifier option. query->setLocalAddr(IOAddress("192.0.3.1")); // Append the Server Identifier. ASSERT_NO_THROW(NakedDhcpv4Srv::appendServerID(ex)); // Make sure that the option has been added. OptionPtr opt = response->getOption(DHO_DHCP_SERVER_IDENTIFIER); ASSERT_TRUE(opt); Option4AddrLstPtr opt_server_id = boost::dynamic_pointer_cast<Option4AddrLst>(opt); ASSERT_TRUE(opt_server_id); // The option is represented as a list of IPv4 addresses but with // only one address added. Option4AddrLst::AddressContainer addrs = opt_server_id->getAddresses(); ASSERT_EQ(1, addrs.size()); // This address should match the local address of the packet. EXPECT_EQ("192.0.3.1", addrs[0].toText()); } // Sanity check. Verifies that both Dhcpv4Srv and its derived // class NakedDhcpv4Srv can be instantiated and destroyed. TEST_F(Dhcpv4SrvTest, basic) { // Check that the base class can be instantiated boost::scoped_ptr<Dhcpv4Srv> srv; ASSERT_NO_THROW(srv.reset(new Dhcpv4Srv(DHCP4_SERVER_PORT + 10000, false, false))); srv.reset(); // We have to close open sockets because further in this test we will // call the Dhcpv4Srv constructor again. This constructor will try to // set the appropriate packet filter class for IfaceMgr. This requires // that all sockets are closed. IfaceMgr::instance().closeSockets(); // Check that the derived class can be instantiated boost::scoped_ptr<NakedDhcpv4Srv> naked_srv; ASSERT_NO_THROW( naked_srv.reset(new NakedDhcpv4Srv(DHCP4_SERVER_PORT + 10000))); // Close sockets again for the next test. IfaceMgr::instance().closeSockets(); ASSERT_NO_THROW(naked_srv.reset(new NakedDhcpv4Srv(0))); } // This test verifies the test_send_responses_to_source_ is false by default // and sets by the KEA_TEST_SEND_RESPONSES_TO_SOURCE environment variable. TEST_F(Dhcpv4SrvTest, testSendResponsesToSource) { ASSERT_FALSE(std::getenv("KEA_TEST_SEND_RESPONSES_TO_SOURCE")); boost::scoped_ptr<NakedDhcpv4Srv> naked_srv; ASSERT_NO_THROW( naked_srv.reset(new NakedDhcpv4Srv(DHCP4_SERVER_PORT + 10000))); EXPECT_FALSE(naked_srv->getSendResponsesToSource()); ::setenv("KEA_TEST_SEND_RESPONSES_TO_SOURCE", "ENABLED", 1); // Do not use ASSERT as we want unsetenv to be always called. EXPECT_NO_THROW( naked_srv.reset(new NakedDhcpv4Srv(DHCP4_SERVER_PORT + 10000))); EXPECT_TRUE(naked_srv->getSendResponsesToSource()); ::unsetenv("KEA_TEST_SEND_RESPONSES_TO_SOURCE"); } // Verifies that DISCOVER message can be processed correctly, // that the OFFER message generated in response is valid and // contains necessary options. // // Note: this test focuses on the packet correctness. There // are other tests that verify correctness of the allocation // engine. See DiscoverBasic, DiscoverHint, DiscoverNoClientId // and DiscoverInvalidHint. TEST_F(Dhcpv4SrvTest, processDiscover) { testDiscoverRequest(DHCPDISCOVER); } // Verifies that REQUEST message can be processed correctly, // that the OFFER message generated in response is valid and // contains necessary options. // // Note: this test focuses on the packet correctness. There // are other tests that verify correctness of the allocation // engine. See DiscoverBasic, DiscoverHint, DiscoverNoClientId // and DiscoverInvalidHint. TEST_F(Dhcpv4SrvTest, processRequest) { testDiscoverRequest(DHCPREQUEST); } // Verifies that DHCPDISCOVERs are sanity checked correctly. // 1. They must have either hardware address or client id // 2. They must not have server id TEST_F(Dhcpv4SrvTest, sanityCheckDiscover) { NakedDhcpv4Srv srv; Pkt4Ptr pkt(new Pkt4(DHCPDISCOVER, 1234)); // Should throw, no hardware address or client id ASSERT_THROW_MSG(srv.processDiscover(pkt), RFCViolation, "Missing or useless client-id and no HW address" " provided in message DHCPDISCOVER"); // Add a hardware address. This should not throw. std::vector<uint8_t> data = { 0, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe}; HWAddrPtr hwaddr(new HWAddr(data, HTYPE_ETHER)); pkt->setHWAddr(hwaddr); ASSERT_NO_THROW(srv.processDiscover(pkt)); // Now let's make a new pkt with client-id only, it should not throw. pkt.reset(new Pkt4(DHCPDISCOVER, 1234)); pkt->addOption(generateClientId()); ASSERT_NO_THROW(srv.processDiscover(pkt)); // Now let's add a server-id. This should throw. OptionDefinitionPtr server_id_def = LibDHCP::getOptionDef(DHCP4_OPTION_SPACE, DHO_DHCP_SERVER_IDENTIFIER); ASSERT_TRUE(server_id_def); OptionCustomPtr server_id(new OptionCustom(*server_id_def, Option::V4)); server_id->writeAddress(IOAddress("192.0.2.3")); pkt->addOption(server_id); EXPECT_THROW_MSG(srv.processDiscover(pkt), RFCViolation, "Server-id option was not expected," " but received in message DHCPDISCOVER"); } // Verifies that DHCPREQEUSTs are sanity checked correctly. // 1. They must have either hardware address or client id // 2. They must have a requested address // 3. They may or may not have a server id TEST_F(Dhcpv4SrvTest, sanityCheckRequest) { NakedDhcpv4Srv srv; Pkt4Ptr pkt(new Pkt4(DHCPREQUEST, 1234)); // Should throw, no hardware address or client id ASSERT_THROW_MSG(srv.processRequest(pkt), RFCViolation, "Missing or useless client-id and no HW address" " provided in message DHCPREQUEST"); // Add a hardware address. Should not throw. std::vector<uint8_t> data = { 0, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe}; HWAddrPtr hwaddr(new HWAddr(data, HTYPE_ETHER)); pkt->setHWAddr(hwaddr); EXPECT_NO_THROW(srv.processRequest(pkt)); // Now let's add a requested address. This should not throw. OptionDefinitionPtr req_addr_def = LibDHCP::getOptionDef(DHCP4_OPTION_SPACE, DHO_DHCP_REQUESTED_ADDRESS); ASSERT_TRUE(req_addr_def); OptionCustomPtr req_addr(new OptionCustom(*req_addr_def, Option::V4)); req_addr->writeAddress(IOAddress("192.0.2.3")); pkt->addOption(req_addr); ASSERT_NO_THROW(srv.processRequest(pkt)); // Now let's make a new pkt with client-id only and an address, it should not throw. pkt.reset(new Pkt4(DHCPREQUEST, 1234)); pkt->addOption(generateClientId()); pkt->addOption(req_addr); ASSERT_NO_THROW(srv.processRequest(pkt)); // Now let's add a server-id. This should not throw. OptionDefinitionPtr server_id_def = LibDHCP::getOptionDef(DHCP4_OPTION_SPACE, DHO_DHCP_SERVER_IDENTIFIER); ASSERT_TRUE(server_id_def); OptionCustomPtr server_id(new OptionCustom(*server_id_def, Option::V4)); server_id->writeAddress(IOAddress("192.0.2.3")); pkt->addOption(server_id); EXPECT_NO_THROW(srv.processRequest(pkt)); } // Verifies that DHCPDECLINEs are sanity checked correctly. // 1. They must have either hardware address or client id // 2. They must have a requested address // 3. They may or may not have a server id TEST_F(Dhcpv4SrvTest, sanityCheckDecline) { NakedDhcpv4Srv srv; Pkt4Ptr pkt(new Pkt4(DHCPDECLINE, 1234)); // Should throw, no hardware address or client id ASSERT_THROW_MSG(srv.processDecline(pkt), RFCViolation, "Missing or useless client-id and no HW address" " provided in message DHCPDECLINE"); // Add a hardware address. Should throw because of missing address. std::vector<uint8_t> data = { 0, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe}; HWAddrPtr hwaddr(new HWAddr(data, HTYPE_ETHER)); pkt->setHWAddr(hwaddr); ASSERT_THROW_MSG(srv.processDecline(pkt), RFCViolation, "Mandatory 'Requested IP address' option missing in DHCPDECLINE" " sent from [hwtype=1 00:fe:fe:fe:fe:fe], cid=[no info], tid=0x4d2"); // Now let's add a requested address. This should not throw. OptionDefinitionPtr req_addr_def = LibDHCP::getOptionDef(DHCP4_OPTION_SPACE, DHO_DHCP_REQUESTED_ADDRESS); ASSERT_TRUE(req_addr_def); OptionCustomPtr req_addr(new OptionCustom(*req_addr_def, Option::V4)); req_addr->writeAddress(IOAddress("192.0.2.3")); pkt->addOption(req_addr); ASSERT_NO_THROW(srv.processDecline(pkt)); // Now let's make a new pkt with client-id only and an address, it should not throw. pkt.reset(new Pkt4(DHCPDECLINE, 1234)); pkt->addOption(generateClientId()); pkt->addOption(req_addr); ASSERT_NO_THROW(srv.processDecline(pkt)); // Now let's add a server-id. This should not throw. OptionDefinitionPtr server_id_def = LibDHCP::getOptionDef(DHCP4_OPTION_SPACE, DHO_DHCP_SERVER_IDENTIFIER); ASSERT_TRUE(server_id_def); OptionCustomPtr server_id(new OptionCustom(*server_id_def, Option::V4)); server_id->writeAddress(IOAddress("192.0.2.3")); pkt->addOption(server_id); EXPECT_NO_THROW(srv.processDecline(pkt)); } // Verifies that DHCPRELEASEs are sanity checked correctly. // 1. They must have either hardware address or client id // 2. They may or may not have a server id TEST_F(Dhcpv4SrvTest, sanityCheckRelease) { NakedDhcpv4Srv srv; Pkt4Ptr pkt(new Pkt4(DHCPRELEASE, 1234)); // Should throw, no hardware address or client id ASSERT_THROW_MSG(srv.processRelease(pkt), RFCViolation, "Missing or useless client-id and no HW address" " provided in message DHCPRELEASE"); // Add a hardware address. Should not throw. std::vector<uint8_t> data = { 0, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe}; HWAddrPtr hwaddr(new HWAddr(data, HTYPE_ETHER)); pkt->setHWAddr(hwaddr); EXPECT_NO_THROW(srv.processRelease(pkt)); // Make a new pkt with client-id only. Should not throw. pkt.reset(new Pkt4(DHCPRELEASE, 1234)); pkt->addOption(generateClientId()); ASSERT_NO_THROW(srv.processRelease(pkt)); // Now let's add a server-id. This should not throw. OptionDefinitionPtr server_id_def = LibDHCP::getOptionDef(DHCP4_OPTION_SPACE, DHO_DHCP_SERVER_IDENTIFIER); ASSERT_TRUE(server_id_def); OptionCustomPtr server_id(new OptionCustom(*server_id_def, Option::V4)); server_id->writeAddress(IOAddress("192.0.2.3")); pkt->addOption(server_id); EXPECT_NO_THROW(srv.processRelease(pkt)); } // Verifies that DHCPINFORMs are sanity checked correctly. // 1. They must have either hardware address or client id // 2. They may or may not have requested address // 3. They may or may not have a server id TEST_F(Dhcpv4SrvTest, sanityCheckInform) { NakedDhcpv4Srv srv; Pkt4Ptr pkt(new Pkt4(DHCPINFORM, 1234)); // Should throw, no hardware address or client id ASSERT_THROW_MSG(srv.processInform(pkt), RFCViolation, "Missing or useless client-id and no HW address" " provided in message DHCPINFORM"); // Add a hardware address. Should not throw. std::vector<uint8_t> data = { 0, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe}; HWAddrPtr hwaddr(new HWAddr(data, HTYPE_ETHER)); pkt->setHWAddr(hwaddr); ASSERT_NO_THROW(srv.processInform(pkt)); // Now let's add a requested address. This should not throw. OptionDefinitionPtr req_addr_def = LibDHCP::getOptionDef(DHCP4_OPTION_SPACE, DHO_DHCP_REQUESTED_ADDRESS); ASSERT_TRUE(req_addr_def); OptionCustomPtr req_addr(new OptionCustom(*req_addr_def, Option::V4)); req_addr->writeAddress(IOAddress("192.0.2.3")); pkt->addOption(req_addr); ASSERT_NO_THROW(srv.processInform(pkt)); // Now let's make a new pkt with client-id only and an address, it should not throw. pkt.reset(new Pkt4(DHCPINFORM, 1234)); pkt->addOption(generateClientId()); pkt->addOption(req_addr); ASSERT_NO_THROW(srv.processInform(pkt)); // Now let's add a server-id. This should not throw. OptionDefinitionPtr server_id_def = LibDHCP::getOptionDef(DHCP4_OPTION_SPACE, DHO_DHCP_SERVER_IDENTIFIER); ASSERT_TRUE(server_id_def); OptionCustomPtr server_id(new OptionCustom(*server_id_def, Option::V4)); server_id->writeAddress(IOAddress("192.0.2.3")); pkt->addOption(server_id); EXPECT_NO_THROW(srv.processInform(pkt)); } // This test verifies that incoming DISCOVER can be handled properly, that an // OFFER is generated, that the response has an address and that address // really belongs to the configured pool. // // constructed very simple DISCOVER message with: // - client-id option // // expected returned OFFER message: // - copy of client-id // - server-id // - offered address TEST_F(Dhcpv4SrvTest, DiscoverBasic) { IfaceMgrTestConfig test_config(true); IfaceMgr::instance().openSockets4(); boost::scoped_ptr<NakedDhcpv4Srv> srv; ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0))); Pkt4Ptr dis = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 1234)); dis->setRemoteAddr(IOAddress("192.0.2.1")); OptionPtr clientid = generateClientId(); dis->addOption(clientid); dis->setIface("eth1"); dis->setIndex(ETH1_INDEX); // Pass it to the server and get an offer Pkt4Ptr offer = srv->processDiscover(dis); // Check if we get response at all checkResponse(offer, DHCPOFFER, 1234); // Check that address was returned from proper range, that its lease // lifetime is correct, that T1 and T2 are returned properly checkAddressParams(offer, subnet_, true, true); // Check identifiers checkServerId(offer, srv->getServerID()); checkClientId(offer, clientid); } // This test verifies that OFFERs return expected valid lifetimes. TEST_F(Dhcpv4SrvTest, DiscoverValidLifetime) { IfaceMgrTestConfig test_config(true); IfaceMgr::instance().openSockets4(); boost::scoped_ptr<NakedDhcpv4Srv> srv; ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0))); // Recreate subnet Triplet<uint32_t> unspecified; Triplet<uint32_t> valid_lft(500, 1000, 1500); subnet_.reset(new Subnet4(IOAddress("192.0.2.0"), 24, unspecified, unspecified, valid_lft)); pool_ = Pool4Ptr(new Pool4(IOAddress("192.0.2.100"), IOAddress("192.0.2.110"))); subnet_->addPool(pool_); CfgMgr::instance().clear(); CfgMgr::instance().getStagingCfg()->getCfgSubnets4()->add(subnet_); CfgMgr::instance().commit(); // Struct for describing an individual lifetime test scenario struct LifetimeTest { // logged test description std::string description_; // lifetime hint (0 means not send dhcp-lease-time option) uint32_t hint; // expected returned value uint32_t expected; }; // Test scenarios std::vector<LifetimeTest> tests = { { "default valid lifetime", 0, 1000 }, { "specified valid lifetime", 1001, 1001 }, { "too small valid lifetime", 100, 500 }, { "too large valid lifetime", 2000, 1500 } }; // Iterate over the test scenarios. for (auto test : tests) { SCOPED_TRACE(test.description_); // Create a discover packet to use Pkt4Ptr dis = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 1234)); dis->setRemoteAddr(IOAddress("192.0.2.1")); OptionPtr clientid = generateClientId(); dis->addOption(clientid); dis->setIface("eth1"); dis->setIndex(ETH1_INDEX); // Add dhcp-lease-time option. if (test.hint) { OptionUint32Ptr opt(new OptionUint32(Option::V4, DHO_DHCP_LEASE_TIME, test.hint)); dis->addOption(opt); } // Pass it to the server and get an offer Pkt4Ptr offer = srv->processDiscover(dis); // Check if we get response at all checkResponse(offer, DHCPOFFER, 1234); // Check that address was returned from proper range, that its lease // lifetime is correct and has the expected value. checkAddressParams(offer, subnet_, false, false, test.expected); // Check identifiers checkServerId(offer, srv->getServerID()); checkClientId(offer, clientid); } } // Check that option 58 and 59 are only included if they were specified // (and calculate-tee-times = false) and the values are sane: // T2 is less than valid lft; T1 is less than T2 (if given) or valid // lft if T2 is not given. TEST_F(Dhcpv4SrvTest, DiscoverTimers) { IfaceMgrTestConfig test_config(true); IfaceMgr::instance().openSockets4(); boost::scoped_ptr<NakedDhcpv4Srv> srv; ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0))); // Recreate subnet Triplet<uint32_t> unspecified; Triplet<uint32_t> valid_lft(1000); subnet_.reset(new Subnet4(IOAddress("192.0.2.0"), 24, unspecified, unspecified, valid_lft)); pool_ = Pool4Ptr(new Pool4(IOAddress("192.0.2.100"), IOAddress("192.0.2.110"))); subnet_->addPool(pool_); CfgMgr::instance().clear(); CfgMgr::instance().getStagingCfg()->getCfgSubnets4()->add(subnet_); CfgMgr::instance().commit(); // Struct for describing an individual timer test scenario struct TimerTest { // logged test description std::string description_; // configured value for subnet's T1 Triplet<uint32_t> cfg_t1_; // configured value for subnet's T1 Triplet<uint32_t> cfg_t2_; // True if Offer should contain Subnet's T1 value bool exp_t1_; // True if Offer should contain Subnet's T2 value bool exp_t2_; }; // Convenience constants bool T1 = true; bool T2 = true; // Test scenarios std::vector<TimerTest> tests = { { "T1:unspecified, T2:unspecified", unspecified, unspecified, // Client should neither. !T1, !T2 }, { "T1 unspecified, T2 < VALID", unspecified, valid_lft - 1, // Client should only get T2. !T1, T2 }, { "T1:unspecified, T2 = VALID", unspecified, valid_lft, // Client should get neither. !T1, !T2 }, { "T1:unspecified, T2 > VALID", unspecified, valid_lft + 1, // Client should get neither. !T1, !T2 }, { "T1 < VALID, T2:unspecified", valid_lft - 1, unspecified, // Client should only get T1. T1, !T2 }, { "T1 = VALID, T2:unspecified", valid_lft, unspecified, // Client should get neither. !T1, !T2 }, { "T1 > VALID, T2:unspecified", valid_lft + 1, unspecified, // Client should get neither. !T1, !T2 }, { "T1 < T2 < VALID", valid_lft - 2, valid_lft - 1, // Client should get both. T1, T2 }, { "T1 = T2 < VALID", valid_lft - 1, valid_lft - 1, // Client should only get T2. !T1, T2 }, { "T1 > T2 < VALID", valid_lft - 1, valid_lft - 2, // Client should only get T2. !T1, T2 }, { "T1 = T2 = VALID", valid_lft, valid_lft, // Client should get neither. !T1, !T2 }, { "T1 > VALID < T2, T2 > VALID", valid_lft + 1, valid_lft + 2, // Client should get neither. !T1, !T2 } }; // Create a discover packet to use Pkt4Ptr dis = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 1234)); dis->setRemoteAddr(IOAddress("192.0.2.1")); OptionPtr clientid = generateClientId(); dis->addOption(clientid); dis->setIface("eth1"); dis->setIndex(ETH1_INDEX); // Iterate over the test scenarios. for (auto test = tests.begin(); test != tests.end(); ++test) { { SCOPED_TRACE((*test).description_); // Configure sunbet's timer values subnet_->setT1((*test).cfg_t1_); subnet_->setT2((*test).cfg_t2_); // Discover/Offer exchange with the server Pkt4Ptr offer = srv->processDiscover(dis); // Verify we have an offer checkResponse(offer, DHCPOFFER, 1234); // Verify the timers are as expected. checkAddressParams(offer, subnet_, (*test).exp_t1_, (*test).exp_t2_); } } } // Check that option 58 and 59 are included when calculate-tee-times // is enabled, but only when they are not explicitly specified via // renew-timer and rebinding-timer. This test does not check whether // the subnet's for t1-percent and t2-percent are valid, as this is // enforced by parsing and tested elsewhere. TEST_F(Dhcpv4SrvTest, calculateTeeTimers) { IfaceMgrTestConfig test_config(true); IfaceMgr::instance().openSockets4(); boost::scoped_ptr<NakedDhcpv4Srv> srv; ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0))); // Recreate subnet Triplet<uint32_t> unspecified; Triplet<uint32_t> valid_lft(1000); subnet_.reset(new Subnet4(IOAddress("192.0.2.0"), 24, unspecified, unspecified, valid_lft)); pool_ = Pool4Ptr(new Pool4(IOAddress("192.0.2.100"), IOAddress("192.0.2.110"))); subnet_->addPool(pool_); CfgMgr::instance().clear(); CfgMgr::instance().getStagingCfg()->getCfgSubnets4()->add(subnet_); CfgMgr::instance().commit(); // Struct for describing an individual timer test scenario struct TimerTest { // logged test description std::string description_; // configured value for subnet's T1 Triplet<uint32_t> cfg_t1_; // configured value for subnet's T1 Triplet<uint32_t> cfg_t2_; // configured value for sunbet's t1_percent. double t1_percent_; // configured value for sunbet's t2_percent. double t2_percent_; // expected value for T1 in server response. // A value of 0 means server should not have sent T1. uint32_t t1_exp_value_; // expected value for T2 in server response. // A value of 0 means server should not have sent T2. uint32_t t2_exp_value_; }; // Convenience constant uint32_t not_expected = 0; // Test scenarios std::vector<TimerTest> tests = { { "T1 and T2 calculated", unspecified, unspecified, 0.4, 0.8, 400, 800 }, { "T1 and T2 specified insane", valid_lft + 1, valid_lft + 2, 0.4, 0.8, not_expected, not_expected }, { "T1 should be calculated, T2 specified", unspecified, valid_lft - 1, 0.4, 0.8, 400, valid_lft - 1 }, { "T1 specified, T2 should be calculated", 299, unspecified, 0.4, 0.8, 299, 800 }, { "T1 specified > T2, T2 should be calculated", valid_lft - 1, unspecified, 0.4, 0.8, not_expected, 800 } }; // Calculation is enabled for all the scenarios. subnet_->setCalculateTeeTimes(true); // Create a discover packet to use Pkt4Ptr dis = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 1234)); dis->setRemoteAddr(IOAddress("192.0.2.1")); OptionPtr clientid = generateClientId(); dis->addOption(clientid); dis->setIface("eth1"); dis->setIndex(ETH1_INDEX); // Iterate over the test scenarios. for (auto test = tests.begin(); test != tests.end(); ++test) { { SCOPED_TRACE((*test).description_); // Configure sunbet's timer values subnet_->setT1((*test).cfg_t1_); subnet_->setT2((*test).cfg_t2_); subnet_->setT1Percent((*test).t1_percent_); subnet_->setT2Percent((*test).t2_percent_); // Discover/Offer exchange with the server Pkt4Ptr offer = srv->processDiscover(dis); // Verify we have an offer checkResponse(offer, DHCPOFFER, 1234); // Check T1 timer OptionUint32Ptr opt = boost::dynamic_pointer_cast <OptionUint32> (offer->getOption(DHO_DHCP_RENEWAL_TIME)); if ((*test).t1_exp_value_ == not_expected) { EXPECT_FALSE(opt) << "T1 present and shouldn't be"; } else { ASSERT_TRUE(opt) << "Required T1 option missing or it has" " an unexpected type"; EXPECT_EQ(opt->getValue(), (*test).t1_exp_value_); } // Check T2 timer opt = boost::dynamic_pointer_cast <OptionUint32>(offer->getOption(DHO_DHCP_REBINDING_TIME)); if ((*test).t2_exp_value_ == not_expected) { EXPECT_FALSE(opt) << "T2 present and shouldn't be"; } else { ASSERT_TRUE(opt) << "Required T2 option missing or it has" " an unexpected type"; EXPECT_EQ(opt->getValue(), (*test).t2_exp_value_); } } } } // This test verifies that incoming DISCOVER can be handled properly, that an // OFFER is generated, that the response has an address and that address // really belongs to the configured pool. // // constructed very simple DISCOVER message with: // - client-id option // - address set to specific value as hint, but that hint is invalid // // expected returned OFFER message: // - copy of client-id // - server-id // - offered address (!= hint) TEST_F(Dhcpv4SrvTest, DiscoverInvalidHint) { IfaceMgrTestConfig test_config(true); IfaceMgr::instance().openSockets4(); boost::scoped_ptr<NakedDhcpv4Srv> srv; ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0))); IOAddress hint("10.1.2.3"); Pkt4Ptr dis = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 1234)); dis->setRemoteAddr(IOAddress("192.0.2.107")); OptionPtr clientid = generateClientId(); dis->addOption(clientid); dis->setYiaddr(hint); dis->setIface("eth1"); dis->setIndex(ETH1_INDEX); // Pass it to the server and get an offer Pkt4Ptr offer = srv->processDiscover(dis); // Check if we get response at all checkResponse(offer, DHCPOFFER, 1234); // Check that address was returned from proper range, that its lease // lifetime is correct, that T1 and T2 are returned properly checkAddressParams(offer, subnet_, true, true); EXPECT_NE(offer->getYiaddr(), hint); // Check identifiers checkServerId(offer, srv->getServerID()); checkClientId(offer, clientid); } /// @todo: Add a test that client sends hint that is in pool, but currently /// being used by a different client. // This test checks that the server is offering different addresses to different // clients in OFFERs. Please note that OFFER is not a guarantee that such // an address will be assigned. Had the pool was very small and contained only // 2 addresses, the third client would get the same offer as the first one // and this is a correct behavior. It is REQUEST that will fail for the third // client. OFFER is basically saying "if you send me a request, you will // probably get an address like this" (there are no guarantees). TEST_F(Dhcpv4SrvTest, ManyDiscovers) { IfaceMgrTestConfig test_config(true); IfaceMgr::instance().openSockets4(); boost::scoped_ptr<NakedDhcpv4Srv> srv; ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0))); Pkt4Ptr dis1 = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 1234)); Pkt4Ptr dis2 = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 2345)); Pkt4Ptr dis3 = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 3456)); dis1->setRemoteAddr(IOAddress("192.0.2.1")); dis2->setRemoteAddr(IOAddress("192.0.2.2")); dis3->setRemoteAddr(IOAddress("192.0.2.3")); // Assign interfaces dis1->setIface("eth1"); dis1->setIndex(ETH1_INDEX); dis2->setIface("eth1"); dis2->setIndex(ETH1_INDEX); dis3->setIface("eth1"); dis3->setIndex(ETH1_INDEX); // Different client-id sizes OptionPtr clientid1 = generateClientId(4); // length 4 OptionPtr clientid2 = generateClientId(5); // length 5 OptionPtr clientid3 = generateClientId(6); // length 6 dis1->addOption(clientid1); dis2->addOption(clientid2); dis3->addOption(clientid3); // Pass it to the server and get an offer Pkt4Ptr offer1 = srv->processDiscover(dis1); Pkt4Ptr offer2 = srv->processDiscover(dis2); Pkt4Ptr offer3 = srv->processDiscover(dis3); // Check if we get response at all checkResponse(offer1, DHCPOFFER, 1234); checkResponse(offer2, DHCPOFFER, 2345); checkResponse(offer3, DHCPOFFER, 3456); IOAddress addr1 = offer1->getYiaddr(); IOAddress addr2 = offer2->getYiaddr(); IOAddress addr3 = offer3->getYiaddr(); // Check that the assigned address is indeed from the configured pool checkAddressParams(offer1, subnet_, true, true); checkAddressParams(offer2, subnet_, true, true); checkAddressParams(offer3, subnet_, true, true); // Check server-ids checkServerId(offer1, srv->getServerID()); checkServerId(offer2, srv->getServerID()); checkServerId(offer3, srv->getServerID()); checkClientId(offer1, clientid1); checkClientId(offer2, clientid2); checkClientId(offer3, clientid3); // Finally check that the addresses offered are different EXPECT_NE(addr1, addr2); EXPECT_NE(addr2, addr3); EXPECT_NE(addr3, addr1); cout << "Offered address to client1=" << addr1 << endl; cout << "Offered address to client2=" << addr2 << endl; cout << "Offered address to client3=" << addr3 << endl; } // Checks whether echoing back client-id is controllable, i.e. // whether the server obeys echo-client-id and sends (or not) // client-id TEST_F(Dhcpv4SrvTest, discoverEchoClientId) { IfaceMgrTestConfig test_config(true); IfaceMgr::instance().openSockets4(); NakedDhcpv4Srv srv(0); Pkt4Ptr dis = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 1234)); dis->setRemoteAddr(IOAddress("192.0.2.1")); OptionPtr clientid = generateClientId(); dis->addOption(clientid); dis->setIface("eth1"); dis->setIndex(ETH1_INDEX); // Pass it to the server and get an offer Pkt4Ptr offer = srv.processDiscover(dis); // Check if we get response at all checkResponse(offer, DHCPOFFER, 1234); checkClientId(offer, clientid); ConstSrvConfigPtr cfg = CfgMgr::instance().getCurrentCfg(); const Subnet4Collection* subnets = cfg->getCfgSubnets4()->getAll(); ASSERT_EQ(1, subnets->size()); CfgMgr::instance().clear(); CfgMgr::instance().getStagingCfg()->getCfgSubnets4()->add(*subnets->begin()); CfgMgr::instance().getStagingCfg()->setEchoClientId(false); CfgMgr::instance().commit(); offer = srv.processDiscover(dis); // Check if we get response at all checkResponse(offer, DHCPOFFER, 1234); checkClientId(offer, clientid); } // Check that option 58 and 59 are not included if they are not specified. TEST_F(Dhcpv4SrvTest, RequestNoTimers) { IfaceMgrTestConfig test_config(true); IfaceMgr::instance().openSockets4(); boost::scoped_ptr<NakedDhcpv4Srv> srv; ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0))); Pkt4Ptr req = Pkt4Ptr(new Pkt4(DHCPREQUEST, 1234)); req->setRemoteAddr(IOAddress("192.0.2.1")); OptionPtr clientid = generateClientId(); req->addOption(clientid); req->setIface("eth1"); req->setIndex(ETH1_INDEX); // Recreate a subnet but set T1 and T2 to "unspecified". subnet_.reset(new Subnet4(IOAddress("192.0.2.0"), 24, Triplet<uint32_t>(), Triplet<uint32_t>(), 3000)); pool_ = Pool4Ptr(new Pool4(IOAddress("192.0.2.100"), IOAddress("192.0.2.110"))); subnet_->addPool(pool_); CfgMgr::instance().clear(); CfgMgr::instance().getStagingCfg()->getCfgSubnets4()->add(subnet_); CfgMgr::instance().commit(); // Pass it to the server and get an ACK. Pkt4Ptr ack = srv->processRequest(req); // Check if we get response at all checkResponse(ack, DHCPACK, 1234); // T1 and T2 timers must not be present. checkAddressParams(ack, subnet_, false, false); // Check identifiers checkServerId(ack, srv->getServerID()); checkClientId(ack, clientid); } // Checks whether echoing back client-id is controllable TEST_F(Dhcpv4SrvTest, requestEchoClientId) { IfaceMgrTestConfig test_config(true); IfaceMgr::instance().openSockets4(); NakedDhcpv4Srv srv(0); Pkt4Ptr dis = Pkt4Ptr(new Pkt4(DHCPREQUEST, 1234)); dis->setRemoteAddr(IOAddress("192.0.2.1")); OptionPtr clientid = generateClientId(); dis->addOption(clientid); dis->setIface("eth1"); dis->setIndex(ETH1_INDEX); // Pass it to the server and get ACK Pkt4Ptr ack = srv.processRequest(dis); // Check if we get response at all checkResponse(ack, DHCPACK, 1234); checkClientId(ack, clientid); ConstSrvConfigPtr cfg = CfgMgr::instance().getCurrentCfg(); const Subnet4Collection* subnets = cfg->getCfgSubnets4()->getAll(); ASSERT_EQ(1, subnets->size()); CfgMgr::instance().clear(); CfgMgr::instance().getStagingCfg()->getCfgSubnets4()->add(*subnets->begin()); CfgMgr::instance().getStagingCfg()->setEchoClientId(false); CfgMgr::instance().commit(); ack = srv.processRequest(dis); // Check if we get response at all checkResponse(ack, DHCPACK, 1234); checkClientId(ack, clientid); } // This test verifies that incoming (positive) REQUEST/Renewing can be handled properly, that a // REPLY is generated, that the response has an address and that address // really belongs to the configured pool and that lease is actually renewed. // // expected: // - returned REPLY message has copy of client-id // - returned REPLY message has server-id // - returned REPLY message has IA that includes IAADDR // - lease is actually renewed in LeaseMgr TEST_F(Dhcpv4SrvTest, RenewBasic) { IfaceMgrTestConfig test_config(true); IfaceMgr::instance().openSockets4(); boost::scoped_ptr<NakedDhcpv4Srv> srv; ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0))); const IOAddress addr("192.0.2.106"); const uint32_t temp_valid = 100; const time_t temp_timestamp = time(NULL) - 10; // Generate client-id also sets client_id_ member OptionPtr clientid = generateClientId(); // Check that the address we are about to use is indeed in pool ASSERT_TRUE(subnet_->inPool(Lease::TYPE_V4, addr)); // let's create a lease and put it in the LeaseMgr uint8_t hwaddr2_data[] = { 0, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe}; HWAddrPtr hwaddr2(new HWAddr(hwaddr2_data, sizeof(hwaddr2_data), HTYPE_ETHER)); Lease4Ptr used(new Lease4(IOAddress("192.0.2.106"), hwaddr2, &client_id_->getDuid()[0], client_id_->getDuid().size(), temp_valid, temp_timestamp, subnet_->getID())); ASSERT_TRUE(LeaseMgrFactory::instance().addLease(used)); // Check that the lease is really in the database Lease4Ptr l = LeaseMgrFactory::instance().getLease4(addr); ASSERT_TRUE(l); // Check that preferred, valid and cltt really set. // Constructed lease looks as if it was assigned 10 seconds ago EXPECT_EQ(l->valid_lft_, temp_valid); EXPECT_EQ(l->cltt_, temp_timestamp); // Let's create a RENEW Pkt4Ptr req = Pkt4Ptr(new Pkt4(DHCPREQUEST, 1234)); req->setRemoteAddr(IOAddress(addr)); req->setYiaddr(addr); req->setCiaddr(addr); // client's address req->setIface("eth0"); req->setIndex(ETH0_INDEX); req->setHWAddr(hwaddr2); req->addOption(clientid); req->addOption(srv->getServerID()); // Pass it to the server and hope for a REPLY Pkt4Ptr ack = srv->processRequest(req); // Check if we get response at all checkResponse(ack, DHCPACK, 1234); EXPECT_EQ(addr, ack->getYiaddr()); // Check that address was returned from proper range, that its lease // lifetime is correct, that T1 and T2 are returned properly checkAddressParams(ack, subnet_, true, true); // Check identifiers checkServerId(ack, srv->getServerID()); checkClientId(ack, clientid); // Check that the lease is really in the database l = checkLease(ack, clientid, req->getHWAddr(), addr); ASSERT_TRUE(l); // Check that preferred, valid and cltt were really updated EXPECT_EQ(l->valid_lft_, subnet_->getValid()); // Checking for CLTT is a bit tricky if we want to avoid off by 1 errors int32_t cltt = static_cast<int32_t>(l->cltt_); int32_t expected = static_cast<int32_t>(time(NULL)); // Equality or difference by 1 between cltt and expected is ok. EXPECT_GE(1, abs(cltt - expected)); Lease4Ptr lease = LeaseMgrFactory::instance().getLease4(addr); EXPECT_TRUE(LeaseMgrFactory::instance().deleteLease(lease)); } // Renew*Lifetime common code. namespace { struct ctx { Dhcpv4SrvTest* test; NakedDhcpv4Srv* srv; const IOAddress& addr; const uint32_t temp_valid; const time_t temp_timestamp; OptionPtr clientid; HWAddrPtr hwaddr; Lease4Ptr used; Lease4Ptr l; OptionPtr opt; Pkt4Ptr req; Pkt4Ptr ack; }; void prepare(struct ctx& c) { IfaceMgrTestConfig test_config(true); IfaceMgr::instance().openSockets4(); // Check that the address we are about to use is indeed in pool ASSERT_TRUE(c.test->subnet_->inPool(Lease::TYPE_V4, c.addr)); // let's create a lease and put it in the LeaseMgr uint8_t hwaddr_data[] = { 0, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe}; c.hwaddr.reset(new HWAddr(hwaddr_data, sizeof(hwaddr_data), HTYPE_ETHER)); c.used.reset(new Lease4(c.addr, c.hwaddr, &c.test->client_id_->getDuid()[0], c.test->client_id_->getDuid().size(), c.temp_valid, c.temp_timestamp, c.test->subnet_->getID())); ASSERT_TRUE(LeaseMgrFactory::instance().addLease(c.used)); // Check that the lease is really in the database c.l = LeaseMgrFactory::instance().getLease4(c.addr); ASSERT_TRUE(c.l); // Check that valid and cltt really set. // Constructed lease looks as if it was assigned 10 seconds ago EXPECT_EQ(c.l->valid_lft_, c.temp_valid); EXPECT_EQ(c.l->cltt_, c.temp_timestamp); // Set the valid lifetime interval. c.test->subnet_->setValid(Triplet<uint32_t>(2000, 3000, 4000)); // Let's create a RENEW c.req.reset(new Pkt4(DHCPREQUEST, 1234)); c.req->setRemoteAddr(IOAddress(c.addr)); c.req->setYiaddr(c.addr); c.req->setCiaddr(c.addr); // client's address c.req->setIface("eth0"); c.req->setIndex(ETH0_INDEX); c.req->setHWAddr(c.hwaddr); c.req->addOption(c.clientid); c.req->addOption(c.srv->getServerID()); if (c.opt) { c.req->addOption(c.opt); } // Pass it to the server and hope for a REPLY c.ack = c.srv->processRequest(c.req); // Check if we get response at all c.test->checkResponse(c.ack, DHCPACK, 1234); EXPECT_EQ(c.addr, c.ack->getYiaddr()); // Check identifiers c.test->checkServerId(c.ack, c.srv->getServerID()); c.test->checkClientId(c.ack, c.clientid); // Check that the lease is really in the database c.l = c.test->checkLease(c.ack, c.clientid, c.req->getHWAddr(), c.addr); ASSERT_TRUE(c.l); } // This test verifies that renewal returns the default valid lifetime // when the client does not specify a value. TEST_F(Dhcpv4SrvTest, RenewDefaultLifetime) { boost::scoped_ptr<NakedDhcpv4Srv> srv; ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0))); struct ctx c = { this, // test srv.get(), // srv IOAddress("192.0.2.106"), // addr 100, // temp_valid time(NULL) - 10, // temp_timestamp // Generate client-id also sets client_id_ member generateClientId(), // clientid HWAddrPtr(), // hwaddr Lease4Ptr(), // used Lease4Ptr(), // l OptionPtr(), // opt Pkt4Ptr(), // req Pkt4Ptr() // acka }; prepare(c); // There is no valid lifetime hint so the default will be returned. // Check that address was returned from proper range, that its lease // lifetime is correct, that T1 and T2 are returned properly checkAddressParams(c.ack, subnet_, true, true, subnet_->getValid()); // Check that valid and cltt were really updated EXPECT_EQ(c.l->valid_lft_, subnet_->getValid()); // Checking for CLTT is a bit tricky if we want to avoid off by 1 errors int32_t cltt = static_cast<int32_t>(c.l->cltt_); int32_t expected = static_cast<int32_t>(time(NULL)); // Equality or difference by 1 between cltt and expected is ok. EXPECT_GE(1, abs(cltt - expected)); Lease4Ptr lease = LeaseMgrFactory::instance().getLease4(c.addr); EXPECT_TRUE(LeaseMgrFactory::instance().deleteLease(lease)); } // This test verifies that renewal returns the specified valid lifetime // when the client adds an in-bound hint in the DISCOVER. TEST_F(Dhcpv4SrvTest, RenewHintLifetime) { boost::scoped_ptr<NakedDhcpv4Srv> srv; ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0))); struct ctx c = { this, // test srv.get(), // srv IOAddress("192.0.2.106"), // addr 100, // temp_valid time(NULL) - 10, // temp_timestamp // Generate client-id also sets client_id_ member generateClientId(), // clientid HWAddrPtr(), // hwaddr Lease4Ptr(), // used Lease4Ptr(), // l OptionPtr(), // opt Pkt4Ptr(), // req Pkt4Ptr() // acka }; // Add a dhcp-lease-time with an in-bound valid lifetime hint // which will be returned in the OFFER. uint32_t hint = 3001; c.opt.reset(new OptionUint32(Option::V4, DHO_DHCP_LEASE_TIME, hint)); prepare(c); // Check that address was returned from proper range, that its lease // lifetime is correct, that T1 and T2 are returned properly checkAddressParams(c.ack, subnet_, true, true, hint); // Check that valid and cltt were really updated EXPECT_EQ(c.l->valid_lft_, hint); // Checking for CLTT is a bit tricky if we want to avoid off by 1 errors int32_t cltt = static_cast<int32_t>(c.l->cltt_); int32_t expected = static_cast<int32_t>(time(NULL)); // Equality or difference by 1 between cltt and expected is ok. EXPECT_GE(1, abs(cltt - expected)); Lease4Ptr lease = LeaseMgrFactory::instance().getLease4(c.addr); EXPECT_TRUE(LeaseMgrFactory::instance().deleteLease(lease)); } // This test verifies that renewal returns the min valid lifetime // when the client adds a too small hint in the DISCOVER. TEST_F(Dhcpv4SrvTest, RenewMinLifetime) { boost::scoped_ptr<NakedDhcpv4Srv> srv; ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0))); struct ctx c = { this, // test srv.get(), // srv IOAddress("192.0.2.106"), // addr 100, // temp_valid time(NULL) - 10, // temp_timestamp // Generate client-id also sets client_id_ member generateClientId(), // clientid HWAddrPtr(), // hwaddr Lease4Ptr(), // used Lease4Ptr(), // l OptionPtr(), // opt Pkt4Ptr(), // req Pkt4Ptr() // acka }; // Add a dhcp-lease-time with too small valid lifetime hint. // The min valid lifetime will be returned in the OFFER. c.opt.reset(new OptionUint32(Option::V4, DHO_DHCP_LEASE_TIME, 1000)); prepare(c); // Check that address was returned from proper range, that its lease // lifetime is correct, that T1 and T2 are returned properly // Note that T2 should be false for a reason which does not matter... checkAddressParams(c.ack, subnet_, true, false, subnet_->getValid().getMin()); // Check that valid and cltt were really updated EXPECT_EQ(c.l->valid_lft_, subnet_->getValid().getMin()); // Checking for CLTT is a bit tricky if we want to avoid off by 1 errors int32_t cltt = static_cast<int32_t>(c.l->cltt_); int32_t expected = static_cast<int32_t>(time(NULL)); // Equality or difference by 1 between cltt and expected is ok. EXPECT_GE(1, abs(cltt - expected)); Lease4Ptr lease = LeaseMgrFactory::instance().getLease4(c.addr); EXPECT_TRUE(LeaseMgrFactory::instance().deleteLease(lease)); } // This test verifies that renewal returns the max valid lifetime // when the client adds a too large hint in the DISCOVER. TEST_F(Dhcpv4SrvTest, RenewMaxLifetime) { boost::scoped_ptr<NakedDhcpv4Srv> srv; ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0))); struct ctx c = { this, // test srv.get(), // srv IOAddress("192.0.2.106"), // addr 100, // temp_valid time(NULL) - 10, // temp_timestamp // Generate client-id also sets client_id_ member generateClientId(), // clientid HWAddrPtr(), // hwaddr Lease4Ptr(), // used Lease4Ptr(), // l OptionPtr(), // opt Pkt4Ptr(), // req Pkt4Ptr() // acka }; // Add a dhcp-lease-time with too large valid lifetime hint. // The max valid lifetime will be returned in the OFFER. c.opt.reset(new OptionUint32(Option::V4, DHO_DHCP_LEASE_TIME, 5000)); prepare(c); // Check that address was returned from proper range, that its lease // lifetime is correct, that T1 and T2 are returned properly checkAddressParams(c.ack, subnet_, true, true, subnet_->getValid().getMax()); // Check that valid and cltt were really updated EXPECT_EQ(c.l->valid_lft_, subnet_->getValid().getMax()); // Checking for CLTT is a bit tricky if we want to avoid off by 1 errors int32_t cltt = static_cast<int32_t>(c.l->cltt_); int32_t expected = static_cast<int32_t>(time(NULL)); // Equality or difference by 1 between cltt and expected is ok. EXPECT_GE(1, abs(cltt - expected)); Lease4Ptr lease = LeaseMgrFactory::instance().getLease4(c.addr); EXPECT_TRUE(LeaseMgrFactory::instance().deleteLease(lease)); } } // end of Renew*Lifetime // This test verifies that the logic which matches server identifier in the // received message with server identifiers used by a server works correctly: // - a message with no server identifier is accepted, // - a message with a server identifier which matches one of the server // identifiers used by a server is accepted, // - a message with a server identifier which doesn't match any server // identifier used by a server, is not accepted. TEST_F(Dhcpv4SrvTest, acceptServerId) { IfaceMgrTestConfig test_config(true); IfaceMgr::instance().openSockets4(); NakedDhcpv4Srv srv(0); Pkt4Ptr pkt(new Pkt4(DHCPREQUEST, 1234)); // If no server identifier option is present, the message is always // accepted. EXPECT_TRUE(srv.acceptServerId(pkt)); // Create definition of the server identifier option. OptionDefinition def("server-identifier", DHO_DHCP_SERVER_IDENTIFIER, "ipv4-address", false); // Add a server identifier option which doesn't match server ids being // used by the server. The accepted server ids are the IPv4 addresses // configured on the interfaces. The 10.1.2.3 is not configured on // any interfaces. OptionCustomPtr other_serverid(new OptionCustom(def, Option::V6)); other_serverid->writeAddress(IOAddress("10.1.2.3")); pkt->addOption(other_serverid); EXPECT_FALSE(srv.acceptServerId(pkt)); // Remove the server identifier. ASSERT_NO_THROW(pkt->delOption(DHO_DHCP_SERVER_IDENTIFIER)); // Add a server id being an IPv4 address configured on eth0 interface. // A DHCPv4 message holding this server identifier should be accepted. OptionCustomPtr eth0_serverid(new OptionCustom(def, Option::V6)); eth0_serverid->writeAddress(IOAddress("192.0.2.3")); ASSERT_NO_THROW(pkt->addOption(eth0_serverid)); EXPECT_TRUE(srv.acceptServerId(pkt)); // Remove the server identifier. ASSERT_NO_THROW(pkt->delOption(DHO_DHCP_SERVER_IDENTIFIER)); // Add a server id being an IPv4 address configured on eth1 interface. // A DHCPv4 message holding this server identifier should be accepted. OptionCustomPtr eth1_serverid(new OptionCustom(def, Option::V6)); eth1_serverid->writeAddress(IOAddress("10.0.0.1")); ASSERT_NO_THROW(pkt->addOption(eth1_serverid)); EXPECT_TRUE(srv.acceptServerId(pkt)); } // @todo: Implement tests for rejecting renewals // This test verifies if the sanityCheck() really checks options presence. TEST_F(Dhcpv4SrvTest, sanityCheck) { boost::scoped_ptr<NakedDhcpv4Srv> srv; ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0))); Pkt4Ptr pkt = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 1234)); pkt->setHWAddr(generateHWAddr(6)); // Server-id is optional for information-request, so EXPECT_NO_THROW(NakedDhcpv4Srv::sanityCheck(pkt, Dhcpv4Srv::OPTIONAL)); // Empty packet, no server-id EXPECT_THROW(NakedDhcpv4Srv::sanityCheck(pkt, Dhcpv4Srv::MANDATORY), RFCViolation); pkt->addOption(srv->getServerID()); // Server-id is mandatory and present = no exception EXPECT_NO_THROW(NakedDhcpv4Srv::sanityCheck(pkt, Dhcpv4Srv::MANDATORY)); // Server-id is forbidden, but present => exception EXPECT_THROW(NakedDhcpv4Srv::sanityCheck(pkt, Dhcpv4Srv::FORBIDDEN), RFCViolation); // There's no client-id and no HWADDR. Server needs something to // identify the client pkt->setHWAddr(generateHWAddr(0)); EXPECT_THROW(NakedDhcpv4Srv::sanityCheck(pkt, Dhcpv4Srv::MANDATORY), RFCViolation); } } // end of anonymous namespace namespace isc { namespace dhcp { namespace test { void Dhcpv4SrvTest::relayAgentInfoEcho() { IfaceMgrTestConfig test_config(true); NakedDhcpv4Srv srv(0); // Use of the captured DHCPDISCOVER packet requires that // subnet 10.254.226.0/24 is in use, because this packet // contains the giaddr which belongs to this subnet and // this giaddr is used to select the subnet configure(CONFIGS[0]); // Let's create a relayed DISCOVER. This particular relayed DISCOVER has // added option 82 (relay agent info) with 3 suboptions. The server // is supposed to echo it back in its response. Pkt4Ptr dis; ASSERT_NO_THROW(dis = PktCaptures::captureRelayedDiscover()); // Simulate that we have received that traffic srv.fakeReceive(dis); // Server will now process to run its normal loop, but instead of calling // IfaceMgr::receive4(), it will read all packets from the list set by // fakeReceive() // In particular, it should call registered buffer4_receive callback. srv.run(); // Check that the server did send a response ASSERT_EQ(1, srv.fake_sent_.size()); // Make sure that we received a response Pkt4Ptr offer = srv.fake_sent_.front(); ASSERT_TRUE(offer); // Get Relay Agent Info from query... OptionPtr rai_query = dis->getOption(DHO_DHCP_AGENT_OPTIONS); ASSERT_TRUE(rai_query); // Get Relay Agent Info from response... OptionPtr rai_response = offer->getOption(DHO_DHCP_AGENT_OPTIONS); ASSERT_TRUE(rai_response); EXPECT_TRUE(rai_response->equals(rai_query)); } void Dhcpv4SrvTest::badRelayAgentInfoEcho() { IfaceMgrTestConfig test_config(true); NakedDhcpv4Srv srv(0); // Use of the captured DHCPDISCOVER packet requires that // subnet 10.254.226.0/24 is in use, because this packet // contains the giaddr which belongs to this subnet and // this giaddr is used to select the subnet configure(CONFIGS[0]); // Let's create a relayed DISCOVER. This particular relayed DISCOVER has // added option 82 (relay agent info) with a sub-option which does not // fit in the option. Unpacking it gave an empty option which is // supposed to not be echoed back in its response. Pkt4Ptr dis; ASSERT_NO_THROW(dis = PktCaptures::captureBadRelayedDiscover()); // Simulate that we have received that traffic srv.fakeReceive(dis); // Server will now process to run its normal loop, but instead of calling // IfaceMgr::receive4(), it will read all packets from the list set by // fakeReceive() // In particular, it should call registered buffer4_receive callback. srv.run(); // Check that the server did send a response ASSERT_EQ(1, srv.fake_sent_.size()); // Make sure that we received a response Pkt4Ptr offer = srv.fake_sent_.front(); ASSERT_TRUE(offer); // Get Relay Agent Info from query... OptionPtr rai_query = dis->getOption(DHO_DHCP_AGENT_OPTIONS); ASSERT_TRUE(rai_query); ASSERT_EQ(2, rai_query->len()); // Get Relay Agent Info from response... OptionPtr rai_response = offer->getOption(DHO_DHCP_AGENT_OPTIONS); ASSERT_FALSE(rai_response); } void Dhcpv4SrvTest::portsClientPort() { IfaceMgrTestConfig test_config(true); NakedDhcpv4Srv srv(0); // By default te client port is supposed to be zero. EXPECT_EQ(0, srv.client_port_); // Use of the captured DHCPDISCOVER packet requires that // subnet 10.254.226.0/24 is in use, because this packet // contains the giaddr which belongs to this subnet and // this giaddr is used to select the subnet configure(CONFIGS[0]); srv.client_port_ = 1234; // Let's create a relayed DISCOVER. This particular relayed DISCOVER has // added option 82 (relay agent info) with 3 suboptions. The server // is supposed to echo it back in its response. Pkt4Ptr dis; ASSERT_NO_THROW(dis = PktCaptures::captureRelayedDiscover()); // Simulate that we have received that traffic srv.fakeReceive(dis); // Server will now process to run its normal loop, but instead of calling // IfaceMgr::receive4(), it will read all packets from the list set by // fakeReceive() // In particular, it should call registered buffer4_receive callback. srv.run(); // Check that the server did send a response ASSERT_EQ(1, srv.fake_sent_.size()); // Make sure that we received a response Pkt4Ptr offer = srv.fake_sent_.front(); ASSERT_TRUE(offer); // Get Relay Agent Info from query... EXPECT_EQ(srv.client_port_, offer->getRemotePort()); } void Dhcpv4SrvTest::portsServerPort() { IfaceMgrTestConfig test_config(true); // Do not use DHCP4_SERVER_PORT here as 0 means don't open sockets. NakedDhcpv4Srv srv(0); EXPECT_EQ(0, srv.server_port_); // Use of the captured DHCPDISCOVER packet requires that // subnet 10.254.226.0/24 is in use, because this packet // contains the giaddr which belongs to this subnet and // this giaddr is used to select the subnet configure(CONFIGS[0]); srv.server_port_ = 1234; // Let's create a relayed DISCOVER. This particular relayed DISCOVER has // added option 82 (relay agent info) with 3 suboptions. The server // is supposed to echo it back in its response. Pkt4Ptr dis; ASSERT_NO_THROW(dis = PktCaptures::captureRelayedDiscover()); // Simulate that we have received that traffic srv.fakeReceive(dis); // Server will now process to run its normal loop, but instead of calling // IfaceMgr::receive4(), it will read all packets from the list set by // fakeReceive() // In particular, it should call registered buffer4_receive callback. srv.run(); // Check that the server did send a response ASSERT_EQ(1, srv.fake_sent_.size()); // Make sure that we received a response Pkt4Ptr offer = srv.fake_sent_.front(); ASSERT_TRUE(offer); // Get Relay Agent Info from query... EXPECT_EQ(srv.server_port_, offer->getLocalPort()); } } // end of isc::dhcp::test namespace } // end of isc::dhcp namespace } // end of isc namespace namespace { TEST_F(Dhcpv4SrvTest, relayAgentInfoEcho) { Dhcpv4SrvMTTestGuard guard(*this, false); relayAgentInfoEcho(); } TEST_F(Dhcpv4SrvTest, relayAgentInfoEchoMultiThreading) { Dhcpv4SrvMTTestGuard guard(*this, true); relayAgentInfoEcho(); } TEST_F(Dhcpv4SrvTest, badRelayAgentInfoEcho) { Dhcpv4SrvMTTestGuard guard(*this, false); badRelayAgentInfoEcho(); } TEST_F(Dhcpv4SrvTest, badRelayAgentInfoEchoMultiThreading) { Dhcpv4SrvMTTestGuard guard(*this, true); badRelayAgentInfoEcho(); } TEST_F(Dhcpv4SrvTest, portsClientPort) { Dhcpv4SrvMTTestGuard guard(*this, false); portsClientPort(); } TEST_F(Dhcpv4SrvTest, portsClientPortMultiThreading) { Dhcpv4SrvMTTestGuard guard(*this, true); portsClientPort(); } TEST_F(Dhcpv4SrvTest, portsServerPort) { Dhcpv4SrvMTTestGuard guard(*this, false); portsServerPort(); } TEST_F(Dhcpv4SrvTest, portsServerPortMultiTHreading) { Dhcpv4SrvMTTestGuard guard(*this, true); portsServerPort(); } /// @todo Implement tests for subnetSelect See tests in dhcp6_srv_unittest.cc: /// selectSubnetAddr, selectSubnetIface, selectSubnetRelayLinkaddr, /// selectSubnetRelayInterfaceId. Note that the concept of interface-id is not /// present in the DHCPv4, so not everything is applicable directly. /// See ticket #3057 // Checks whether the server uses default (0.0.0.0) siaddr value, unless // explicitly specified TEST_F(Dhcpv4SrvTest, siaddrDefault) { IfaceMgrTestConfig test_config(true); IfaceMgr::instance().openSockets4(); boost::scoped_ptr<NakedDhcpv4Srv> srv; ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0))); IOAddress hint("192.0.2.107"); Pkt4Ptr dis = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 1234)); dis->setRemoteAddr(IOAddress("192.0.2.1")); OptionPtr clientid = generateClientId(); dis->addOption(clientid); dis->setYiaddr(hint); dis->setIface("eth1"); dis->setIndex(ETH1_INDEX); // Pass it to the server and get an offer Pkt4Ptr offer = srv->processDiscover(dis); ASSERT_TRUE(offer); // Check if we get response at all checkResponse(offer, DHCPOFFER, 1234); // Verify that it is 0.0.0.0 EXPECT_EQ("0.0.0.0", offer->getSiaddr().toText()); } // Checks whether the server uses specified siaddr value TEST_F(Dhcpv4SrvTest, siaddr) { IfaceMgrTestConfig test_config(true); IfaceMgr::instance().openSockets4(); boost::scoped_ptr<NakedDhcpv4Srv> srv; ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0))); subnet_->setSiaddr(IOAddress("192.0.2.123")); Pkt4Ptr dis = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 1234)); dis->setRemoteAddr(IOAddress("192.0.2.1")); dis->setIface("eth1"); dis->setIndex(ETH1_INDEX); OptionPtr clientid = generateClientId(); dis->addOption(clientid); // Pass it to the server and get an offer Pkt4Ptr offer = srv->processDiscover(dis); ASSERT_TRUE(offer); // Check if we get response at all checkResponse(offer, DHCPOFFER, 1234); // Verify that its value is proper EXPECT_EQ("192.0.2.123", offer->getSiaddr().toText()); } // Checks if the next-server defined as global value is overridden by subnet // specific value and returned in server messages. There's also similar test for // checking parser only configuration, see Dhcp4ParserTest.nextServerOverride in // config_parser_unittest.cc. This test was extended to other BOOTP fixed fields. TEST_F(Dhcpv4SrvTest, nextServerOverride) { IfaceMgrTestConfig test_config(true); IfaceMgr::instance().openSockets4(); NakedDhcpv4Srv srv(0); ConstElementPtr status; string config = "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ]" "}," "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"next-server\": \"192.0.0.1\", " "\"server-hostname\": \"nohost\", " "\"boot-file-name\": \"nofile\", " "\"subnet4\": [ { " " \"pools\": [ { \"pool\": \"192.0.2.1 - 192.0.2.100\" } ]," " \"next-server\": \"1.2.3.4\", " " \"server-hostname\": \"some-name.example.org\", " " \"boot-file-name\": \"bootfile.efi\", " " \"subnet\": \"192.0.2.0/24\" } ]," "\"valid-lifetime\": 4000 }"; ConstElementPtr json; ASSERT_NO_THROW(json = parseDHCP4(config, true)); EXPECT_NO_THROW(status = configureDhcp4Server(srv, json)); CfgMgr::instance().commit(); // check if returned status is OK ASSERT_TRUE(status); comment_ = config::parseAnswer(rcode_, status); ASSERT_EQ(0, rcode_); Pkt4Ptr dis = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 1234)); dis->setRemoteAddr(IOAddress("192.0.2.1")); dis->setIface("eth1"); dis->setIndex(ETH1_INDEX); OptionPtr clientid = generateClientId(); dis->addOption(clientid); // Pass it to the server and get an offer Pkt4Ptr offer = srv.processDiscover(dis); ASSERT_TRUE(offer); EXPECT_EQ(DHCPOFFER, offer->getType()); EXPECT_EQ("1.2.3.4", offer->getSiaddr().toText()); std::string sname("some-name.example.org"); uint8_t sname_buf[Pkt4::MAX_SNAME_LEN]; std::memset(sname_buf, 0, Pkt4::MAX_SNAME_LEN); std::memcpy(sname_buf, sname.c_str(), sname.size()); EXPECT_EQ(0, std::memcmp(sname_buf, &offer->getSname()[0], Pkt4::MAX_SNAME_LEN)); std::string filename("bootfile.efi"); uint8_t filename_buf[Pkt4::MAX_FILE_LEN]; std::memset(filename_buf, 0, Pkt4::MAX_FILE_LEN); std::memcpy(filename_buf, filename.c_str(), filename.size()); EXPECT_EQ(0, std::memcmp(filename_buf, &offer->getFile()[0], Pkt4::MAX_FILE_LEN)); } // Checks if the next-server defined as global value is used in responses // when there is no specific value defined in subnet and returned to the client // properly. There's also similar test for checking parser only configuration, // see Dhcp4ParserTest.nextServerGlobal in config_parser_unittest.cc. TEST_F(Dhcpv4SrvTest, nextServerGlobal) { IfaceMgrTestConfig test_config(true); IfaceMgr::instance().openSockets4(); NakedDhcpv4Srv srv(0); ConstElementPtr status; string config = "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ]" "}," "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"next-server\": \"192.0.0.1\", " "\"server-hostname\": \"some-name.example.org\", " "\"boot-file-name\": \"bootfile.efi\", " "\"subnet4\": [ { " " \"pools\": [ { \"pool\": \"192.0.2.1 - 192.0.2.100\" } ]," " \"subnet\": \"192.0.2.0/24\" } ]," "\"valid-lifetime\": 4000 }"; ConstElementPtr json; ASSERT_NO_THROW(json = parseDHCP4(config, true)); EXPECT_NO_THROW(status = configureDhcp4Server(srv, json)); CfgMgr::instance().commit(); // check if returned status is OK ASSERT_TRUE(status); comment_ = config::parseAnswer(rcode_, status); ASSERT_EQ(0, rcode_); Pkt4Ptr dis = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 1234)); dis->setRemoteAddr(IOAddress("192.0.2.1")); dis->setIface("eth1"); dis->setIndex(ETH1_INDEX); OptionPtr clientid = generateClientId(); dis->addOption(clientid); // Pass it to the server and get an offer Pkt4Ptr offer = srv.processDiscover(dis); ASSERT_TRUE(offer); EXPECT_EQ(DHCPOFFER, offer->getType()); EXPECT_EQ("192.0.0.1", offer->getSiaddr().toText()); std::string sname("some-name.example.org"); uint8_t sname_buf[Pkt4::MAX_SNAME_LEN]; std::memset(sname_buf, 0, Pkt4::MAX_SNAME_LEN); std::memcpy(sname_buf, sname.c_str(), sname.size()); EXPECT_EQ(0, std::memcmp(sname_buf, &offer->getSname()[0], Pkt4::MAX_SNAME_LEN)); std::string filename("bootfile.efi"); uint8_t filename_buf[Pkt4::MAX_FILE_LEN]; std::memset(filename_buf, 0, Pkt4::MAX_FILE_LEN); std::memcpy(filename_buf, filename.c_str(), filename.size()); EXPECT_EQ(0, std::memcmp(filename_buf, &offer->getFile()[0], Pkt4::MAX_FILE_LEN)); } // Checks if client packets are classified properly using match expressions. TEST_F(Dhcpv4SrvTest, matchClassification) { IfaceMgrTestConfig test_config(true); IfaceMgr::instance().openSockets4(); NakedDhcpv4Srv srv(0); // The router class matches incoming packets with foo in a host-name // option (code 12) and sets an ip-forwarding option in the response. string config = "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ] }, " "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"valid-lifetime\": 4000, " "\"subnet4\": [ " "{ \"pools\": [ { \"pool\": \"192.0.2.1 - 192.0.2.100\" } ], " " \"subnet\": \"192.0.2.0/24\" } ], " "\"client-classes\": [ " "{ \"name\": \"router\", " " \"option-data\": [" " { \"name\": \"ip-forwarding\", " " \"data\": \"true\" } ], " " \"test\": \"option[12].text == 'foo'\" } ] }"; ConstElementPtr json; ASSERT_NO_THROW(json = parseDHCP4(config)); ConstElementPtr status; // Configure the server and make sure the config is accepted EXPECT_NO_THROW(status = configureDhcp4Server(srv, json)); ASSERT_TRUE(status); comment_ = config::parseAnswer(rcode_, status); ASSERT_EQ(0, rcode_); CfgMgr::instance().commit(); // Create packets with enough to select the subnet OptionPtr clientid = generateClientId(); Pkt4Ptr query1(new Pkt4(DHCPDISCOVER, 1234)); query1->setRemoteAddr(IOAddress("192.0.2.1")); query1->addOption(clientid); query1->setIface("eth1"); query1->setIndex(ETH1_INDEX); Pkt4Ptr query2(new Pkt4(DHCPDISCOVER, 1234)); query2->setRemoteAddr(IOAddress("192.0.2.1")); query2->addOption(clientid); query2->setIface("eth1"); query2->setIndex(ETH1_INDEX); Pkt4Ptr query3(new Pkt4(DHCPDISCOVER, 1234)); query3->setRemoteAddr(IOAddress("192.0.2.1")); query3->addOption(clientid); query3->setIface("eth1"); query3->setIndex(ETH1_INDEX); // Create and add a PRL option to the first 2 queries OptionUint8ArrayPtr prl(new OptionUint8Array(Option::V4, DHO_DHCP_PARAMETER_REQUEST_LIST)); ASSERT_TRUE(prl); prl->addValue(DHO_IP_FORWARDING); query1->addOption(prl); query2->addOption(prl); // Create and add a host-name option to the first and last queries OptionStringPtr hostname(new OptionString(Option::V4, 12, "foo")); ASSERT_TRUE(hostname); query1->addOption(hostname); query3->addOption(hostname); // Classify packets srv.classifyPacket(query1); srv.classifyPacket(query2); srv.classifyPacket(query3); // Packets with the exception of the second should be in the router class EXPECT_TRUE(query1->inClass("router")); EXPECT_FALSE(query2->inClass("router")); EXPECT_TRUE(query3->inClass("router")); // Process queries Pkt4Ptr response1 = srv.processDiscover(query1); Pkt4Ptr response2 = srv.processDiscover(query2); Pkt4Ptr response3 = srv.processDiscover(query3); // Classification processing should add an ip-forwarding option OptionPtr opt1 = response1->getOption(DHO_IP_FORWARDING); EXPECT_TRUE(opt1); // But only for the first query: second was not classified OptionPtr opt2 = response2->getOption(DHO_IP_FORWARDING); EXPECT_FALSE(opt2); // But only for the first query: third has no PRL OptionPtr opt3 = response3->getOption(DHO_IP_FORWARDING); EXPECT_FALSE(opt3); } // Checks if client packets are classified properly using match expressions // using option names TEST_F(Dhcpv4SrvTest, matchClassificationOptionName) { NakedDhcpv4Srv srv(0); // The router class matches incoming packets with foo in a host-name string config = "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ] }, " "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"valid-lifetime\": 4000, " "\"subnet4\": [ " "{ \"pools\": [ { \"pool\": \"192.0.2.1 - 192.0.2.100\" } ], " " \"subnet\": \"192.0.2.0/24\" } ], " "\"client-classes\": [ " "{ \"name\": \"router\", " " \"test\": \"option[host-name].text == 'foo'\" } ] }"; ConstElementPtr json; ASSERT_NO_THROW(json = parseDHCP4(config)); ConstElementPtr status; // Configure the server and make sure the config is accepted EXPECT_NO_THROW(status = configureDhcp4Server(srv, json)); ASSERT_TRUE(status); comment_ = config::parseAnswer(rcode_, status); ASSERT_EQ(0, rcode_); CfgMgr::instance().commit(); // Create a packet with enough to select the subnet Pkt4Ptr query(new Pkt4(DHCPDISCOVER, 1234)); query->setRemoteAddr(IOAddress("192.0.2.1")); // Create and add a host-name option to the query OptionStringPtr hostname(new OptionString(Option::V4, 12, "foo")); ASSERT_TRUE(hostname); query->addOption(hostname); // Classify packets srv.classifyPacket(query); // The query should be in the router class EXPECT_TRUE(query->inClass("router")); } // Checks if client packets are classified properly using match expressions // using option names and definitions TEST_F(Dhcpv4SrvTest, matchClassificationOptionDef) { NakedDhcpv4Srv srv(0); // The router class matches incoming packets with foo in a defined // option string config = "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ] }, " "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"valid-lifetime\": 4000, " "\"subnet4\": [ " "{ \"pools\": [ { \"pool\": \"192.0.2.1 - 192.0.2.100\" } ], " " \"subnet\": \"192.0.2.0/24\" } ], " "\"client-classes\": [ " "{ \"name\": \"router\", " " \"test\": \"option[my-host-name].text == 'foo'\" } ], " "\"option-def\": [ {" " \"name\": \"my-host-name\", " " \"code\": 250, " " \"type\": \"string\" } ] }"; ConstElementPtr json; ASSERT_NO_THROW(json = parseDHCP4(config)); ConstElementPtr status; // Configure the server and make sure the config is accepted EXPECT_NO_THROW(status = configureDhcp4Server(srv, json)); ASSERT_TRUE(status); comment_ = config::parseAnswer(rcode_, status); ASSERT_EQ(0, rcode_); CfgMgr::instance().commit(); // Create a packet with enough to select the subnet Pkt4Ptr query(new Pkt4(DHCPDISCOVER, 1234)); query->setRemoteAddr(IOAddress("192.0.2.1")); // Create and add a my-host-name option to the query OptionStringPtr hostname(new OptionString(Option::V4, 250, "foo")); ASSERT_TRUE(hostname); query->addOption(hostname); // Classify packets srv.classifyPacket(query); // The query should be in the router class EXPECT_TRUE(query->inClass("router")); } // Checks subnet options have the priority over class options TEST_F(Dhcpv4SrvTest, subnetClassPriority) { IfaceMgrTestConfig test_config(true); IfaceMgr::instance().openSockets4(); NakedDhcpv4Srv srv(0); // Subnet sets an ip-forwarding option in the response. // The router class matches incoming packets with foo in a host-name // option (code 12) and sets an ip-forwarding option in the response. string config = "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ] }, " "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"valid-lifetime\": 4000, " "\"subnet4\": [ " "{ \"pools\": [ { \"pool\": \"192.0.2.1 - 192.0.2.100\" } ], " " \"subnet\": \"192.0.2.0/24\", " " \"option-data\": [" " { \"name\": \"ip-forwarding\", " " \"data\": \"false\" } ] } ], " "\"client-classes\": [ " "{ \"name\": \"router\"," " \"option-data\": [" " { \"name\": \"ip-forwarding\", " " \"data\": \"true\" } ], " " \"test\": \"option[12].text == 'foo'\" } ] }"; ConstElementPtr json; ASSERT_NO_THROW(json = parseDHCP4(config)); ConstElementPtr status; // Configure the server and make sure the config is accepted EXPECT_NO_THROW(status = configureDhcp4Server(srv, json)); ASSERT_TRUE(status); comment_ = config::parseAnswer(rcode_, status); ASSERT_EQ(0, rcode_); CfgMgr::instance().commit(); // Create a packet with enough to select the subnet and go through // the DISCOVER processing Pkt4Ptr query(new Pkt4(DHCPDISCOVER, 1234)); query->setRemoteAddr(IOAddress("192.0.2.1")); OptionPtr clientid = generateClientId(); query->addOption(clientid); query->setIface("eth1"); query->setIndex(ETH1_INDEX); // Create and add a PRL option to the query OptionUint8ArrayPtr prl(new OptionUint8Array(Option::V4, DHO_DHCP_PARAMETER_REQUEST_LIST)); ASSERT_TRUE(prl); prl->addValue(DHO_IP_FORWARDING); query->addOption(prl); // Create and add a host-name option to the query OptionStringPtr hostname(new OptionString(Option::V4, 12, "foo")); ASSERT_TRUE(hostname); query->addOption(hostname); // Classify the packet srv.classifyPacket(query); // The packet should be in the router class EXPECT_TRUE(query->inClass("router")); // Process the query Pkt4Ptr response = srv.processDiscover(query); // Processing should add an ip-forwarding option OptionPtr opt = response->getOption(DHO_IP_FORWARDING); ASSERT_TRUE(opt); ASSERT_GT(opt->len(), opt->getHeaderLen()); // Classification sets the value to true/1, subnet to false/0 // Here subnet has the priority EXPECT_EQ(0, opt->getUint8()); } // Checks subnet options have the priority over global options TEST_F(Dhcpv4SrvTest, subnetGlobalPriority) { IfaceMgrTestConfig test_config(true); IfaceMgr::instance().openSockets4(); NakedDhcpv4Srv srv(0); // Subnet and global set an ip-forwarding option in the response. string config = "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ] }, " "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"valid-lifetime\": 4000, " "\"subnet4\": [ " "{ \"pools\": [ { \"pool\": \"192.0.2.1 - 192.0.2.100\" } ], " " \"subnet\": \"192.0.2.0/24\", " " \"option-data\": [" " { \"name\": \"ip-forwarding\", " " \"data\": \"false\" } ] } ], " "\"option-data\": [" " { \"name\": \"ip-forwarding\", " " \"data\": \"true\" } ] }"; ConstElementPtr json; ASSERT_NO_THROW(json = parseDHCP4(config)); ConstElementPtr status; // Configure the server and make sure the config is accepted EXPECT_NO_THROW(status = configureDhcp4Server(srv, json)); ASSERT_TRUE(status); comment_ = config::parseAnswer(rcode_, status); ASSERT_EQ(0, rcode_); CfgMgr::instance().commit(); // Create a packet with enough to select the subnet and go through // the DISCOVER processing Pkt4Ptr query(new Pkt4(DHCPDISCOVER, 1234)); query->setRemoteAddr(IOAddress("192.0.2.1")); OptionPtr clientid = generateClientId(); query->addOption(clientid); query->setIface("eth1"); query->setIndex(ETH1_INDEX); // Create and add a PRL option to the query OptionUint8ArrayPtr prl(new OptionUint8Array(Option::V4, DHO_DHCP_PARAMETER_REQUEST_LIST)); ASSERT_TRUE(prl); prl->addValue(DHO_IP_FORWARDING); query->addOption(prl); // Create and add a host-name option to the query OptionStringPtr hostname(new OptionString(Option::V4, 12, "foo")); ASSERT_TRUE(hostname); query->addOption(hostname); // Process the query Pkt4Ptr response = srv.processDiscover(query); // Processing should add an ip-forwarding option OptionPtr opt = response->getOption(DHO_IP_FORWARDING); ASSERT_TRUE(opt); ASSERT_GT(opt->len(), opt->getHeaderLen()); // Global sets the value to true/1, subnet to false/0 // Here subnet has the priority EXPECT_EQ(0, opt->getUint8()); } // Checks class options have the priority over global options TEST_F(Dhcpv4SrvTest, classGlobalPriority) { IfaceMgrTestConfig test_config(true); IfaceMgr::instance().openSockets4(); NakedDhcpv4Srv srv(0); // A global ip-forwarding option is set in the response. // The router class matches incoming packets with foo in a host-name // option (code 12) and sets an ip-forwarding option in the response. string config = "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ] }, " "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"valid-lifetime\": 4000, " "\"subnet4\": [ " "{ \"pools\": [ { \"pool\": \"192.0.2.1 - 192.0.2.100\" } ], " " \"subnet\": \"192.0.2.0/24\" } ], " "\"option-data\": [" " { \"name\": \"ip-forwarding\", " " \"data\": \"false\" } ], " "\"client-classes\": [ " "{ \"name\": \"router\"," " \"option-data\": [" " { \"name\": \"ip-forwarding\", " " \"data\": \"true\" } ], " " \"test\": \"option[12].text == 'foo'\" } ] }"; ConstElementPtr json; ASSERT_NO_THROW(json = parseDHCP4(config)); ConstElementPtr status; // Configure the server and make sure the config is accepted EXPECT_NO_THROW(status = configureDhcp4Server(srv, json)); ASSERT_TRUE(status); comment_ = config::parseAnswer(rcode_, status); ASSERT_EQ(0, rcode_); CfgMgr::instance().commit(); // Create a packet with enough to select the subnet and go through // the DISCOVER processing Pkt4Ptr query(new Pkt4(DHCPDISCOVER, 1234)); query->setRemoteAddr(IOAddress("192.0.2.1")); OptionPtr clientid = generateClientId(); query->addOption(clientid); query->setIface("eth1"); query->setIndex(ETH1_INDEX); // Create and add a PRL option to the query OptionUint8ArrayPtr prl(new OptionUint8Array(Option::V4, DHO_DHCP_PARAMETER_REQUEST_LIST)); ASSERT_TRUE(prl); prl->addValue(DHO_IP_FORWARDING); query->addOption(prl); // Create and add a host-name option to the query OptionStringPtr hostname(new OptionString(Option::V4, 12, "foo")); ASSERT_TRUE(hostname); query->addOption(hostname); // Classify the packet srv.classifyPacket(query); // The packet should be in the router class EXPECT_TRUE(query->inClass("router")); // Process the query Pkt4Ptr response = srv.processDiscover(query); // Processing should add an ip-forwarding option OptionPtr opt = response->getOption(DHO_IP_FORWARDING); ASSERT_TRUE(opt); ASSERT_GT(opt->len(), opt->getHeaderLen()); // Classification sets the value to true/1, global to false/0 // Here class has the priority EXPECT_NE(0, opt->getUint8()); } // Checks class options have the priority over global persistent options TEST_F(Dhcpv4SrvTest, classGlobalPersistency) { IfaceMgrTestConfig test_config(true); IfaceMgr::instance().openSockets4(); NakedDhcpv4Srv srv(0); // A global ip-forwarding option is set in the response. // The router class matches incoming packets with foo in a host-name // option (code 12) and sets an ip-forwarding option in the response. // Note the persistency flag follows a "OR" semantic so to set // it to false (or to leave the default) has no effect. string config = "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ] }, " "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"valid-lifetime\": 4000, " "\"subnet4\": [ " "{ \"pools\": [ { \"pool\": \"192.0.2.1 - 192.0.2.100\" } ], " " \"subnet\": \"192.0.2.0/24\" } ], " "\"option-data\": [" " { \"name\": \"ip-forwarding\", " " \"data\": \"false\", " " \"always-send\": true } ], " "\"client-classes\": [ " "{ \"name\": \"router\"," " \"option-data\": [" " { \"name\": \"ip-forwarding\", " " \"data\": \"true\", " " \"always-send\": false } ], " " \"test\": \"option[12].text == 'foo'\" } ] }"; ConstElementPtr json; ASSERT_NO_THROW(json = parseDHCP4(config)); ConstElementPtr status; // Configure the server and make sure the config is accepted EXPECT_NO_THROW(status = configureDhcp4Server(srv, json)); ASSERT_TRUE(status); comment_ = config::parseAnswer(rcode_, status); ASSERT_EQ(0, rcode_); CfgMgr::instance().commit(); // Create a packet with enough to select the subnet and go through // the DISCOVER processing Pkt4Ptr query(new Pkt4(DHCPDISCOVER, 1234)); query->setRemoteAddr(IOAddress("192.0.2.1")); OptionPtr clientid = generateClientId(); query->addOption(clientid); query->setIface("eth1"); query->setIndex(ETH1_INDEX); // Do not add a PRL OptionPtr prl = query->getOption(DHO_DHCP_PARAMETER_REQUEST_LIST); EXPECT_FALSE(prl); // Create and add a host-name option to the query OptionStringPtr hostname(new OptionString(Option::V4, 12, "foo")); ASSERT_TRUE(hostname); query->addOption(hostname); // Classify the packet srv.classifyPacket(query); // The packet should be in the router class EXPECT_TRUE(query->inClass("router")); // Process the query Pkt4Ptr response = srv.processDiscover(query); // Processing should add an ip-forwarding option OptionPtr opt = response->getOption(DHO_IP_FORWARDING); ASSERT_TRUE(opt); ASSERT_GT(opt->len(), opt->getHeaderLen()); // Classification sets the value to true/1, global to false/0 // Here class has the priority EXPECT_NE(0, opt->getUint8()); } // Checks if the client-class field is indeed used for subnet selection. // Note that packet classification is already checked in Dhcpv4SrvTest // .*Classification above. TEST_F(Dhcpv4SrvTest, clientClassify) { // This test configures 2 subnets. We actually only need the // first one, but since there's still this ugly hack that picks // the pool if there is only one, we must use more than one // subnet. That ugly hack will be removed in #3242, currently // under review. // The second subnet does not play any role here. The client's // IP address belongs to the first subnet, so only that first // subnet is being tested. string config = "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ]" "}," "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"subnet4\": [ " "{ \"pools\": [ { \"pool\": \"192.0.2.1 - 192.0.2.100\" } ]," " \"client-class\": \"foo\", " " \"subnet\": \"192.0.2.0/24\" }, " "{ \"pools\": [ { \"pool\": \"192.0.3.1 - 192.0.3.100\" } ]," " \"client-class\": \"xyzzy\", " " \"subnet\": \"192.0.3.0/24\" } " "]," "\"valid-lifetime\": 4000 }"; ASSERT_NO_THROW(configure(config, true, false)); // Create a simple packet that we'll use for classification Pkt4Ptr dis = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 1234)); dis->setRemoteAddr(IOAddress("192.0.2.1")); dis->setCiaddr(IOAddress("192.0.2.1")); dis->setIface("eth0"); dis->setIndex(ETH0_INDEX); OptionPtr clientid = generateClientId(); dis->addOption(clientid); // This discover does not belong to foo class, so it will not // be serviced bool drop = false; EXPECT_FALSE(srv_.selectSubnet(dis, drop)); EXPECT_FALSE(drop); // Let's add the packet to bar class and try again. dis->addClass("bar"); // Still not supported, because it belongs to wrong class. EXPECT_FALSE(srv_.selectSubnet(dis, drop)); EXPECT_FALSE(drop); // Let's add it to matching class. dis->addClass("foo"); // This time it should work EXPECT_TRUE(srv_.selectSubnet(dis, drop)); EXPECT_FALSE(drop); } // Checks if the client-class field is indeed used for pool selection. TEST_F(Dhcpv4SrvTest, clientPoolClassify) { IfaceMgrTestConfig test_config(true); IfaceMgr::instance().openSockets4(); NakedDhcpv4Srv srv(0); // This test configures 2 pools. // The second pool does not play any role here. The client's // IP address belongs to the first pool, so only that first // pool is being tested. string config = "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ]" "}," "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"subnet4\": [ " "{ \"pools\": [ { " " \"pool\": \"192.0.2.1 - 192.0.2.100\", " " \"client-class\": \"foo\" }, " " { \"pool\": \"192.0.3.1 - 192.0.3.100\", " " \"client-class\": \"xyzzy\" } ], " " \"subnet\": \"192.0.0.0/16\" } " "]," "\"valid-lifetime\": 4000 }"; ConstElementPtr json; ASSERT_NO_THROW(json = parseDHCP4(config, true)); ConstElementPtr status; EXPECT_NO_THROW(status = configureDhcp4Server(srv, json)); CfgMgr::instance().commit(); // check if returned status is OK ASSERT_TRUE(status); comment_ = config::parseAnswer(rcode_, status); ASSERT_EQ(0, rcode_); // Create a simple packet that we'll use for classification Pkt4Ptr dis = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 1234)); dis->setRemoteAddr(IOAddress("192.0.2.1")); dis->setCiaddr(IOAddress("192.0.2.1")); dis->setIface("eth0"); dis->setIndex(ETH0_INDEX); OptionPtr clientid = generateClientId(); dis->addOption(clientid); // This discover does not belong to foo class, so it will not // be serviced Pkt4Ptr offer = srv.processDiscover(dis); EXPECT_FALSE(offer); // Let's add the packet to bar class and try again. dis->addClass("bar"); // Still not supported, because it belongs to wrong class. offer = srv.processDiscover(dis); EXPECT_FALSE(offer); // Let's add it to matching class. dis->addClass("foo"); // This time it should work offer = srv.processDiscover(dis); ASSERT_TRUE(offer); EXPECT_EQ(DHCPOFFER, offer->getType()); EXPECT_FALSE(offer->getYiaddr().isV4Zero()); } // Checks if the KNOWN built-in classes is indeed used for pool selection. TEST_F(Dhcpv4SrvTest, clientPoolClassifyKnown) { IfaceMgrTestConfig test_config(true); IfaceMgr::instance().openSockets4(); NakedDhcpv4Srv srv(0); // This test configures 2 pools. // The first one requires reservation, the second does the opposite. string config = "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ]" "}," "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"subnet4\": [ " "{ \"pools\": [ { " " \"pool\": \"192.0.2.1 - 192.0.2.100\", " " \"client-class\": \"KNOWN\" }, " " { \"pool\": \"192.0.3.1 - 192.0.3.100\", " " \"client-class\": \"UNKNOWN\" } ], " " \"subnet\": \"192.0.0.0/16\" } " "]," "\"valid-lifetime\": 4000 }"; ConstElementPtr json; ASSERT_NO_THROW(json = parseDHCP4(config, true)); ConstElementPtr status; EXPECT_NO_THROW(status = configureDhcp4Server(srv, json)); CfgMgr::instance().commit(); // check if returned status is OK ASSERT_TRUE(status); comment_ = config::parseAnswer(rcode_, status); ASSERT_EQ(0, rcode_); // Create a simple packet that we'll use for classification Pkt4Ptr dis = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 1234)); dis->setRemoteAddr(IOAddress("192.0.2.1")); dis->setCiaddr(IOAddress("192.0.2.1")); dis->setIface("eth0"); dis->setIndex(ETH0_INDEX); OptionPtr clientid = generateClientId(); dis->addOption(clientid); // First pool requires reservation so the second will be used Pkt4Ptr offer = srv.processDiscover(dis); ASSERT_TRUE(offer); EXPECT_EQ(DHCPOFFER, offer->getType()); EXPECT_EQ("192.0.3.1", offer->getYiaddr().toText()); } // Checks if the UNKNOWN built-in classes is indeed used for pool selection. TEST_F(Dhcpv4SrvTest, clientPoolClassifyUnknown) { IfaceMgrTestConfig test_config(true); IfaceMgr::instance().openSockets4(); NakedDhcpv4Srv srv(0); // This test configures 2 pools. // The first one requires no reservation, the second does the opposite. string config = "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ]" "}," "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"subnet4\": [ " "{ \"pools\": [ { " " \"pool\": \"192.0.2.1 - 192.0.2.100\", " " \"client-class\": \"UNKNOWN\" }, " " { \"pool\": \"192.0.3.1 - 192.0.3.100\", " " \"client-class\": \"KNOWN\" } ], " " \"subnet\": \"192.0.0.0/16\", " " \"reservations\": [ { " " \"hw-address\": \"00:00:00:11:22:33\", " " \"hostname\": \"foo.bar\" } ] } " "]," "\"valid-lifetime\": 4000 }"; ConstElementPtr json; ASSERT_NO_THROW(json = parseDHCP4(config, true)); ConstElementPtr status; EXPECT_NO_THROW(status = configureDhcp4Server(srv, json)); CfgMgr::instance().commit(); // check if returned status is OK ASSERT_TRUE(status); comment_ = config::parseAnswer(rcode_, status); ASSERT_EQ(0, rcode_); // Create a simple packet that we'll use for classification Pkt4Ptr dis = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 1234)); dis->setRemoteAddr(IOAddress("192.0.2.1")); dis->setCiaddr(IOAddress("192.0.2.1")); dis->setIface("eth0"); dis->setIndex(ETH0_INDEX); OptionPtr clientid = generateClientId(); dis->addOption(clientid); // Set harware address / identifier const HWAddr& hw = HWAddr::fromText("00:00:00:11:22:33"); HWAddrPtr hw_addr(new HWAddr(hw)); dis->setHWAddr(hw_addr); // First pool requires no reservation so the second will be used Pkt4Ptr offer = srv.processDiscover(dis); ASSERT_TRUE(offer); EXPECT_EQ(DHCPOFFER, offer->getType()); EXPECT_EQ("192.0.3.1", offer->getYiaddr().toText()); } // Verifies private option deferred processing TEST_F(Dhcpv4SrvTest, privateOption) { IfaceMgrTestConfig test_config(true); IfaceMgr::instance().openSockets4(); NakedDhcpv4Srv srv(0); // Same than option43Class but with private options string config = "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ] }, " "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"valid-lifetime\": 4000, " "\"subnet4\": [ " "{ \"pools\": [ { \"pool\": \"192.0.2.1 - 192.0.2.100\" } ], " " \"subnet\": \"192.0.2.0/24\" } ]," "\"client-classes\": [ " "{ \"name\": \"private\", " " \"test\": \"option[234].exists\", " " \"option-def\": [ " " { \"code\": 245, " " \"name\": \"privint\", " " \"type\": \"uint32\" } ]," " \"option-data\": [ " " { \"code\": 234, " " \"data\": \"01\" }, " " { \"name\": \"privint\", " " \"data\": \"12345678\" } ] } ] }"; ConstElementPtr json; ASSERT_NO_THROW(json = parseDHCP4(config)); ConstElementPtr status; // Configure the server and make sure the config is accepted EXPECT_NO_THROW(status = configureDhcp4Server(srv, json)); ASSERT_TRUE(status); comment_ = config::parseAnswer(rcode_, status); ASSERT_EQ(0, rcode_); CfgMgr::instance().commit(); // Create a packet with enough to select the subnet and go through // the DISCOVER processing Pkt4Ptr query(new Pkt4(DHCPDISCOVER, 1234)); query->setRemoteAddr(IOAddress("192.0.2.1")); OptionPtr clientid = generateClientId(); query->addOption(clientid); query->setIface("eth1"); query->setIndex(ETH1_INDEX); // Create and add a private option with code 234 OptionBuffer buf; buf.push_back(0x01); OptionPtr opt1(new Option(Option::V4, 234, buf)); query->addOption(opt1); query->getDeferredOptions().push_back(234); // Create and add a private option with code 245 buf.clear(); buf.push_back(0x87); buf.push_back(0x65); buf.push_back(0x43); buf.push_back(0x21); OptionPtr opt2(new Option(Option::V4, 245, buf)); query->addOption(opt2); query->getDeferredOptions().push_back(245); // Create and add a PRL option to the query OptionUint8ArrayPtr prl(new OptionUint8Array(Option::V4, DHO_DHCP_PARAMETER_REQUEST_LIST)); ASSERT_TRUE(prl); prl->addValue(234); prl->addValue(245); query->addOption(prl); srv.classifyPacket(query); ASSERT_NO_THROW(srv.deferredUnpack(query)); // Check if the option 245 was re-unpacked opt2 = query->getOption(245); OptionUint32Ptr opt32 = boost::dynamic_pointer_cast<OptionUint32>(opt2); EXPECT_TRUE(opt32); // Pass it to the server and get an offer Pkt4Ptr offer = srv.processDiscover(query); // Check if we get response at all checkResponse(offer, DHCPOFFER, 1234); // Processing should add an option with code 234 OptionPtr opt = offer->getOption(234); EXPECT_TRUE(opt); // And an option with code 245 opt = offer->getOption(245); ASSERT_TRUE(opt); // Verifies the content opt32 = boost::dynamic_pointer_cast<OptionUint32>(opt); ASSERT_TRUE(opt32); EXPECT_EQ(12345678, opt32->getValue()); } // Checks effect of persistency (aka always-true) flag on the PRL TEST_F(Dhcpv4SrvTest, prlPersistency) { IfaceMgrTestConfig test_config(true); ASSERT_NO_THROW(configure(CONFIGS[2])); // Create a packet with enough to select the subnet and go through // the DISCOVER processing Pkt4Ptr query(new Pkt4(DHCPDISCOVER, 1234)); query->setRemoteAddr(IOAddress("192.0.2.1")); OptionPtr clientid = generateClientId(); query->addOption(clientid); query->setIface("eth1"); query->setIndex(ETH1_INDEX); // Create and add a PRL option for another option OptionUint8ArrayPtr prl(new OptionUint8Array(Option::V4, DHO_DHCP_PARAMETER_REQUEST_LIST)); ASSERT_TRUE(prl); prl->addValue(DHO_ARP_CACHE_TIMEOUT); query->addOption(prl); // Create and add a host-name option to the query OptionStringPtr hostname(new OptionString(Option::V4, 12, "foo")); ASSERT_TRUE(hostname); query->addOption(hostname); // Let the server process it. Pkt4Ptr response = srv_.processDiscover(query); // Processing should add an ip-forwarding option ASSERT_TRUE(response->getOption(DHO_IP_FORWARDING)); // But no default-ip-ttl ASSERT_FALSE(response->getOption(DHO_DEFAULT_IP_TTL)); // Nor an arp-cache-timeout ASSERT_FALSE(response->getOption(DHO_ARP_CACHE_TIMEOUT)); // Reset PRL adding default-ip-ttl query->delOption(DHO_DHCP_PARAMETER_REQUEST_LIST); prl->addValue(DHO_DEFAULT_IP_TTL); query->addOption(prl); // Let the server process it again. response = srv_.processDiscover(query); // Processing should add an ip-forwarding option ASSERT_TRUE(response->getOption(DHO_IP_FORWARDING)); // and now a default-ip-ttl ASSERT_TRUE(response->getOption(DHO_DEFAULT_IP_TTL)); // and still no arp-cache-timeout ASSERT_FALSE(response->getOption(DHO_ARP_CACHE_TIMEOUT)); } // Checks if relay IP address specified in the relay-info structure in // subnet4 is being used properly. TEST_F(Dhcpv4SrvTest, relayOverride) { // We have 2 subnets defined. Note that both have a relay address // defined. Both are not belonging to the subnets. That is // important, because if the relay belongs to the subnet, there's // no need to specify relay override. string config = "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ]" "}," "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"subnet4\": [ " "{ \"pools\": [ { \"pool\": \"192.0.2.2 - 192.0.2.100\" } ]," " \"relay\": { " " \"ip-address\": \"192.0.5.1\"" " }," " \"subnet\": \"192.0.2.0/24\" }, " "{ \"pools\": [ { \"pool\": \"192.0.3.1 - 192.0.3.100\" } ]," " \"relay\": { " " \"ip-address\": \"192.0.5.2\"" " }," " \"subnet\": \"192.0.3.0/24\" } " "]," "\"valid-lifetime\": 4000 }"; // Use this config to set up the server ASSERT_NO_THROW(configure(config, true, false)); // Let's get the subnet configuration objects const Subnet4Collection* subnets = CfgMgr::instance().getCurrentCfg()->getCfgSubnets4()->getAll(); ASSERT_EQ(2, subnets->size()); // Let's get them for easy reference Subnet4Ptr subnet1 = *subnets->begin(); Subnet4Ptr subnet2 = *std::next(subnets->begin()); ASSERT_TRUE(subnet1); ASSERT_TRUE(subnet2); // Let's create a packet. Pkt4Ptr dis = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 1234)); dis->setRemoteAddr(IOAddress("192.0.2.1")); dis->setIface("eth0"); dis->setIndex(ETH0_INDEX); dis->setHops(1); OptionPtr clientid = generateClientId(); dis->addOption(clientid); // This is just a sanity check, we're using regular method: ciaddr 192.0.2.1 // belongs to the first subnet, so it is selected dis->setGiaddr(IOAddress("192.0.2.1")); bool drop = false; EXPECT_TRUE(subnet1 == srv_.selectSubnet(dis, drop)); EXPECT_FALSE(drop); // Relay belongs to the second subnet, so it should be selected. dis->setGiaddr(IOAddress("192.0.3.1")); EXPECT_TRUE(subnet2 == srv_.selectSubnet(dis, drop)); EXPECT_FALSE(drop); // Now let's check if the relay override for the first subnets works dis->setGiaddr(IOAddress("192.0.5.1")); EXPECT_TRUE(subnet1 == srv_.selectSubnet(dis, drop)); EXPECT_FALSE(drop); // The same check for the second subnet... dis->setGiaddr(IOAddress("192.0.5.2")); EXPECT_TRUE(subnet2 == srv_.selectSubnet(dis, drop)); EXPECT_FALSE(drop); // And finally, let's check if mis-matched relay address will end up // in not selecting a subnet at all dis->setGiaddr(IOAddress("192.0.5.3")); EXPECT_FALSE(srv_.selectSubnet(dis, drop)); EXPECT_FALSE(drop); // Finally, check that the relay override works only with relay address // (GIADDR) and does not affect client address (CIADDR) dis->setGiaddr(IOAddress("0.0.0.0")); dis->setHops(0); dis->setCiaddr(IOAddress("192.0.5.1")); EXPECT_FALSE(srv_.selectSubnet(dis, drop)); EXPECT_FALSE(drop); } // Checks if relay IP address specified in the relay-info structure can be // used together with client-classification. TEST_F(Dhcpv4SrvTest, relayOverrideAndClientClass) { // This test configures 2 subnets. They both are on the same link, so they // have the same relay-ip address. Furthermore, the first subnet is // reserved for clients that belong to class "foo". string config = "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ]" "}," "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"subnet4\": [ " "{ \"pools\": [ { \"pool\": \"192.0.2.2 - 192.0.2.100\" } ]," " \"client-class\": \"foo\", " " \"relay\": { " " \"ip-address\": \"192.0.5.1\"" " }," " \"subnet\": \"192.0.2.0/24\" }, " "{ \"pools\": [ { \"pool\": \"192.0.3.1 - 192.0.3.100\" } ]," " \"relay\": { " " \"ip-address\": \"192.0.5.1\"" " }," " \"subnet\": \"192.0.3.0/24\" } " "]," "\"valid-lifetime\": 4000 }"; // Use this config to set up the server ASSERT_NO_THROW(configure(config, true, false)); const Subnet4Collection* subnets = CfgMgr::instance().getCurrentCfg()->getCfgSubnets4()->getAll(); ASSERT_EQ(2, subnets->size()); // Let's get them for easy reference Subnet4Ptr subnet1 = *subnets->begin(); Subnet4Ptr subnet2 = *std::next(subnets->begin()); ASSERT_TRUE(subnet1); ASSERT_TRUE(subnet2); // Let's create a packet. Pkt4Ptr dis = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 1234)); dis->setRemoteAddr(IOAddress("192.0.2.1")); dis->setIface("eth0"); dis->setIndex(ETH0_INDEX); dis->setHops(1); dis->setGiaddr(IOAddress("192.0.5.1")); OptionPtr clientid = generateClientId(); dis->addOption(clientid); // This packet does not belong to class foo, so it should be rejected in // subnet[0], even though the relay-ip matches. It should be accepted in // subnet[1], because the subnet matches and there are no class // requirements. bool drop = false; EXPECT_TRUE(subnet2 == srv_.selectSubnet(dis, drop)); EXPECT_FALSE(drop); // Now let's add this packet to class foo and recheck. This time it should // be accepted in the first subnet, because both class and relay-ip match. dis->addClass("foo"); EXPECT_TRUE(subnet1 == srv_.selectSubnet(dis, drop)); EXPECT_FALSE(drop); } // Checks if a RAI link selection sub-option works as expected TEST_F(Dhcpv4SrvTest, relayLinkSelect) { // We have 3 subnets defined. string config = "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ]" "}," "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"subnet4\": [ " "{ \"pools\": [ { \"pool\": \"192.0.2.2 - 192.0.2.100\" } ]," " \"relay\": { " " \"ip-address\": \"192.0.5.1\"" " }," " \"subnet\": \"192.0.2.0/24\" }, " "{ \"pools\": [ { \"pool\": \"192.0.3.1 - 192.0.3.100\" } ]," " \"subnet\": \"192.0.3.0/24\" }, " "{ \"pools\": [ { \"pool\": \"192.0.4.1 - 192.0.4.100\" } ]," " \"client-class\": \"foo\", " " \"subnet\": \"192.0.4.0/24\" } " "]," "\"valid-lifetime\": 4000 }"; // Use this config to set up the server ASSERT_NO_THROW(configure(config, true, false)); // Let's get the subnet configuration objects const Subnet4Collection* subnets = CfgMgr::instance().getCurrentCfg()->getCfgSubnets4()->getAll(); ASSERT_EQ(3, subnets->size()); // Let's get them for easy reference auto subnet_it = subnets->begin(); Subnet4Ptr subnet1 = *subnet_it; ++subnet_it; Subnet4Ptr subnet2 = *subnet_it; ++subnet_it; Subnet4Ptr subnet3 = *subnet_it; ASSERT_TRUE(subnet1); ASSERT_TRUE(subnet2); ASSERT_TRUE(subnet3); // Let's create a packet. Pkt4Ptr dis = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 1234)); dis->setRemoteAddr(IOAddress("192.0.2.1")); dis->setIface("eth0"); dis->setIndex(ETH0_INDEX); dis->setHops(1); OptionPtr clientid = generateClientId(); dis->addOption(clientid); // Let's create a Relay Agent Information option OptionDefinitionPtr rai_def = LibDHCP::getOptionDef(DHCP4_OPTION_SPACE, DHO_DHCP_AGENT_OPTIONS); ASSERT_TRUE(rai_def); OptionCustomPtr rai(new OptionCustom(*rai_def, Option::V4)); ASSERT_TRUE(rai); IOAddress addr("192.0.3.2"); OptionPtr ols(new Option(Option::V4, RAI_OPTION_LINK_SELECTION, addr.toBytes())); ASSERT_TRUE(ols); rai->addOption(ols); // This is just a sanity check, we're using regular method: ciaddr 192.0.3.1 // belongs to the second subnet, so it is selected dis->setGiaddr(IOAddress("192.0.3.1")); bool drop = false; EXPECT_TRUE(subnet2 == srv_.selectSubnet(dis, drop)); EXPECT_FALSE(drop); // Setup a relay override for the first subnet as it has a high precedence dis->setGiaddr(IOAddress("192.0.5.1")); EXPECT_TRUE(subnet1 == srv_.selectSubnet(dis, drop)); EXPECT_FALSE(drop); // Put a RAI to select back the second subnet as it has // the highest precedence dis->addOption(rai); EXPECT_TRUE(subnet2 == srv_.selectSubnet(dis, drop)); EXPECT_FALSE(drop); // Subnet select option has a lower precedence OptionDefinitionPtr sbnsel_def = LibDHCP::getOptionDef(DHCP4_OPTION_SPACE, DHO_SUBNET_SELECTION); ASSERT_TRUE(sbnsel_def); OptionCustomPtr sbnsel(new OptionCustom(*sbnsel_def, Option::V4)); ASSERT_TRUE(sbnsel); sbnsel->writeAddress(IOAddress("192.0.2.3")); dis->addOption(sbnsel); EXPECT_TRUE(subnet2 == srv_.selectSubnet(dis, drop)); EXPECT_FALSE(drop); dis->delOption(DHO_SUBNET_SELECTION); // Check client-classification still applies IOAddress addr_foo("192.0.4.2"); ols.reset(new Option(Option::V4, RAI_OPTION_LINK_SELECTION, addr_foo.toBytes())); rai->delOption(RAI_OPTION_LINK_SELECTION); dis->delOption(DHO_DHCP_AGENT_OPTIONS); rai->addOption(ols); dis->addOption(rai); // Note it shall fail (vs. try the next criterion). EXPECT_FALSE(srv_.selectSubnet(dis, drop)); EXPECT_FALSE(drop); // Add the packet to the class and check again: now it shall succeed dis->addClass("foo"); EXPECT_TRUE(subnet3 == srv_.selectSubnet(dis, drop)); EXPECT_FALSE(drop); // Check it fails with a bad address in the sub-option IOAddress addr_bad("10.0.0.1"); ols.reset(new Option(Option::V4, RAI_OPTION_LINK_SELECTION, addr_bad.toBytes())); rai->delOption(RAI_OPTION_LINK_SELECTION); dis->delOption(DHO_DHCP_AGENT_OPTIONS); rai->addOption(ols); dis->addOption(rai); EXPECT_FALSE(srv_.selectSubnet(dis, drop)); EXPECT_FALSE(drop); } // Checks if a subnet selection option works as expected TEST_F(Dhcpv4SrvTest, subnetSelect) { // We have 3 subnets defined. string config = "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ]" "}," "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"subnet4\": [ " "{ \"pools\": [ { \"pool\": \"192.0.2.2 - 192.0.2.100\" } ]," " \"relay\": { " " \"ip-address\": \"192.0.5.1\"" " }," " \"subnet\": \"192.0.2.0/24\" }, " "{ \"pools\": [ { \"pool\": \"192.0.3.1 - 192.0.3.100\" } ]," " \"subnet\": \"192.0.3.0/24\" }, " "{ \"pools\": [ { \"pool\": \"192.0.4.1 - 192.0.4.100\" } ]," " \"client-class\": \"foo\", " " \"subnet\": \"192.0.4.0/24\" } " "]," "\"valid-lifetime\": 4000 }"; // Use this config to set up the server ASSERT_NO_THROW(configure(config, true, false)); // Let's get the subnet configuration objects const Subnet4Collection* subnets = CfgMgr::instance().getCurrentCfg()->getCfgSubnets4()->getAll(); ASSERT_EQ(3, subnets->size()); // Let's get them for easy reference auto subnet_it = subnets->begin(); Subnet4Ptr subnet1 = *subnet_it; ++subnet_it; Subnet4Ptr subnet2 = *subnet_it; ++subnet_it; Subnet4Ptr subnet3 = *subnet_it; ASSERT_TRUE(subnet1); ASSERT_TRUE(subnet2); ASSERT_TRUE(subnet3); // Let's create a packet. Pkt4Ptr dis = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 1234)); dis->setRemoteAddr(IOAddress("192.0.2.1")); dis->setIface("eth0"); dis->setIndex(ETH0_INDEX); dis->setHops(1); OptionPtr clientid = generateClientId(); dis->addOption(clientid); // Let's create a Subnet Selection option OptionDefinitionPtr sbnsel_def = LibDHCP::getOptionDef(DHCP4_OPTION_SPACE, DHO_SUBNET_SELECTION); ASSERT_TRUE(sbnsel_def); OptionCustomPtr sbnsel(new OptionCustom(*sbnsel_def, Option::V4)); ASSERT_TRUE(sbnsel); sbnsel->writeAddress(IOAddress("192.0.3.2")); // This is just a sanity check, we're using regular method: ciaddr 192.0.3.1 // belongs to the second subnet, so it is selected dis->setGiaddr(IOAddress("192.0.3.1")); bool drop = false; EXPECT_TRUE(subnet2 == srv_.selectSubnet(dis, drop)); EXPECT_FALSE(drop); // Setup a relay override for the first subnet as it has a high precedence dis->setGiaddr(IOAddress("192.0.5.1")); EXPECT_TRUE(subnet1 == srv_.selectSubnet(dis, drop)); EXPECT_FALSE(drop); // Put a subnet select option to select back the second subnet as // it has the second highest precedence dis->addOption(sbnsel); EXPECT_TRUE(subnet2 == srv_.selectSubnet(dis, drop)); EXPECT_FALSE(drop); // Check client-classification still applies sbnsel->writeAddress(IOAddress("192.0.4.2")); // Note it shall fail (vs. try the next criterion). EXPECT_FALSE(srv_.selectSubnet(dis, drop)); EXPECT_FALSE(drop); // Add the packet to the class and check again: now it shall succeed dis->addClass("foo"); EXPECT_TRUE(subnet3 == srv_.selectSubnet(dis, drop)); EXPECT_FALSE(drop); // Check it fails with a bad address in the sub-option sbnsel->writeAddress(IOAddress("10.0.0.1")); EXPECT_FALSE(srv_.selectSubnet(dis, drop)); EXPECT_FALSE(drop); } // This test verifies that the direct message is dropped when it has been // received by the server via an interface for which there is no subnet // configured. It also checks that the message is not dropped (is processed) // when it is relayed or unicast. TEST_F(Dhcpv4SrvTest, acceptDirectRequest) { IfaceMgrTestConfig test_config(true); IfaceMgr::instance().openSockets4(); NakedDhcpv4Srv srv(0); Pkt4Ptr pkt(new Pkt4(DHCPDISCOVER, 1234)); // Set Giaddr and local server's unicast address, but don't set hops. // Hops value should not matter. The server will treat the message // with the hops value of 0 and non-zero giaddr as relayed. pkt->setGiaddr(IOAddress("192.0.10.1")); pkt->setRemoteAddr(IOAddress("0.0.0.0")); pkt->setLocalAddr(IOAddress("192.0.2.3")); pkt->setIface("eth1"); pkt->setIndex(ETH1_INDEX); EXPECT_TRUE(srv.accept(pkt)); // Let's set hops and check that the message is still accepted as // a relayed message. pkt->setHops(1); EXPECT_TRUE(srv.accept(pkt)); // Make it a direct message but keep unicast server's address. The // messages sent to unicast address should be accepted as they are // most likely to renew existing leases. The server should respond // to renews so they have to be accepted and processed. pkt->setHops(0); pkt->setGiaddr(IOAddress("0.0.0.0")); EXPECT_TRUE(srv.accept(pkt)); // Direct message is now sent to a broadcast address. The server // should accept this message because it has been received via // eth1 for which there is a subnet configured (see test fixture // class constructor). pkt->setLocalAddr(IOAddress("255.255.255.255")); EXPECT_TRUE(srv.accept(pkt)); // For eth0, there is no subnet configured. Such message is expected // to be silently dropped. pkt->setIface("eth0"); pkt->setIndex(ETH0_INDEX); EXPECT_FALSE(srv.accept(pkt)); // But, if the message is unicast it should be accepted, even though // it has been received via eth0. pkt->setLocalAddr(IOAddress("10.0.0.1")); EXPECT_TRUE(srv.accept(pkt)); // For the DHCPINFORM the ciaddr should be set or at least the source // address. pkt->setType(DHCPINFORM); pkt->setRemoteAddr(IOAddress("10.0.0.101")); EXPECT_TRUE(srv.accept(pkt)); // When neither ciaddr nor source address is present, the packet should // be dropped. pkt->setRemoteAddr(IOAddress("0.0.0.0")); EXPECT_FALSE(srv.accept(pkt)); // When ciaddr is set, the packet should be accepted. pkt->setCiaddr(IOAddress("10.0.0.1")); EXPECT_TRUE(srv.accept(pkt)); } // This test checks that the server rejects a message with invalid type. TEST_F(Dhcpv4SrvTest, acceptMessageType) { IfaceMgrTestConfig test_config(true); IfaceMgr::instance().openSockets4(); NakedDhcpv4Srv srv(0); // Specify messages to be accepted by the server. int allowed[] = { DHCPDISCOVER, DHCPREQUEST, DHCPRELEASE, DHCPDECLINE, DHCPINFORM }; size_t allowed_size = sizeof(allowed) / sizeof(allowed[0]); // Check that the server actually accepts these message types. for (size_t i = 0; i < allowed_size; ++i) { EXPECT_TRUE(srv.acceptMessageType(Pkt4Ptr(new Pkt4(allowed[i], 1234)))) << "Test failed for message type " << i; } // Specify messages which server is supposed to drop. int not_allowed[] = { DHCPOFFER, DHCPACK, DHCPNAK, DHCPLEASEQUERY, DHCPLEASEUNASSIGNED, DHCPLEASEUNKNOWN, DHCPLEASEACTIVE, DHCPBULKLEASEQUERY, DHCPLEASEQUERYDONE, }; size_t not_allowed_size = sizeof(not_allowed) / sizeof(not_allowed[0]); // Actually check that the server will drop these messages. for (size_t i = 0; i < not_allowed_size; ++i) { EXPECT_FALSE(srv.acceptMessageType(Pkt4Ptr(new Pkt4(not_allowed[i], 1234)))) << "Test failed for message type " << i; } // Verify that we drop packets with no option 53 // Make a BOOTP packet (i.e. no option 53) std::vector<uint8_t> bin; const char* bootp_txt = "01010601002529b629b600000000000000000000000000000ace5001944452fe711700" "0000000000000000000000000000000000000000000000000000000000000000000000" "0000000000000000000000000000000000000000000000000000000000000000000000" "0000000000000000000000000000000000000000000000000000000000000000000000" "0000000000000000000000000000000000000000000000000000000000000000000000" "0000000000000000000000000000000000000000000000000000000000000000000000" "000000000000000000000000000000000000000000000000000063825363521b010400" "020418020600237453fc48090b0000118b06010401020300ff00000000000000000000" "0000000000000000000000000000000000000000"; isc::util::encode::decodeHex(bootp_txt, bin); Pkt4Ptr pkt(new Pkt4(&bin[0], bin.size())); pkt->unpack(); ASSERT_EQ(DHCP_NOTYPE, pkt->getType()); EXPECT_FALSE(srv.acceptMessageType(Pkt4Ptr(new Pkt4(&bin[0], bin.size())))); // Verify that we drop packets with types >= DHCP_TYPES_EOF // Make Discover with type changed to 0xff std::vector<uint8_t> bin2; const char* invalid_msg_type = "010106015d05478d000000000000000000000000000000000afee20120e52ab8151400" "0000000000000000000000000000000000000000000000000000000000000000000000" "0000000000000000000000000000000000000000000000000000000000000000000000" "0000000000000000000000000000000000000000000000000000000000000000000000" "0000000000000000000000000000000000000000000000000000000000000000000000" "0000000000000000000000000000000000000000000000000000000000000000000000" "0000000000000000000000000000000000000000000000000000638253633501ff3707" "0102030407067d3c0a646f63736973332e303a7d7f0000118b7a010102057501010102" "010303010104010105010106010107010f0801100901030a01010b01180c01010d0200" "400e0200100f010110040000000211010014010015013f160101170101180104190104" "1a01041b01201c01021d01081e01201f01102001102101022201012301002401002501" "01260200ff2701012b59020345434d030b45434d3a45524f55544552040d3242523232" "39553430303434430504312e3034060856312e33332e30330707322e332e3052320806" "30303039354209094347333030304443520a074e657467656172fe01083d0fff2ab815" "140003000120e52ab81514390205dc5219010420000002020620e52ab8151409090000" "118b0401020300ff"; bin.clear(); isc::util::encode::decodeHex(invalid_msg_type, bin); pkt.reset(new Pkt4(&bin[0], bin.size())); pkt->unpack(); ASSERT_EQ(0xff, pkt->getType()); EXPECT_FALSE(srv.acceptMessageType(pkt)); } // Test checks whether statistic is bumped up appropriately when Decline // message is received. TEST_F(Dhcpv4SrvTest, statisticsDecline) { NakedDhcpv4Srv srv(0); pretendReceivingPkt(srv, CONFIGS[0], DHCPDECLINE, "pkt4-decline-received"); } // Test checks whether statistic is bumped up appropriately when Offer // message is received (this should never happen in a sane network). TEST_F(Dhcpv4SrvTest, statisticsOfferRcvd) { NakedDhcpv4Srv srv(0); pretendReceivingPkt(srv, CONFIGS[0], DHCPOFFER, "pkt4-offer-received"); } // Test checks whether statistic is bumped up appropriately when Ack // message is received (this should never happen in a sane network). TEST_F(Dhcpv4SrvTest, statisticsAckRcvd) { NakedDhcpv4Srv srv(0); pretendReceivingPkt(srv, CONFIGS[0], DHCPACK, "pkt4-ack-received"); } // Test checks whether statistic is bumped up appropriately when Nak // message is received (this should never happen in a sane network). TEST_F(Dhcpv4SrvTest, statisticsNakRcvd) { NakedDhcpv4Srv srv(0); pretendReceivingPkt(srv, CONFIGS[0], DHCPNAK, "pkt4-nak-received"); } // Test checks whether statistic is bumped up appropriately when Release // message is received. TEST_F(Dhcpv4SrvTest, statisticsReleaseRcvd) { NakedDhcpv4Srv srv(0); pretendReceivingPkt(srv, CONFIGS[0], DHCPRELEASE, "pkt4-release-received"); } // Test checks whether statistic is bumped up appropriately when unknown // message is received. TEST_F(Dhcpv4SrvTest, statisticsUnknownRcvd) { NakedDhcpv4Srv srv(0); pretendReceivingPkt(srv, CONFIGS[0], 200, "pkt4-unknown-received"); // There should also be pkt4-receive-drop stat bumped up using namespace isc::stats; StatsMgr& mgr = StatsMgr::instance(); ObservationPtr drop_stat = mgr.getObservation("pkt4-receive-drop"); // This statistic must be present and must be set to 1. ASSERT_TRUE(drop_stat); EXPECT_EQ(1, drop_stat->getInteger().first); } // This test verifies that the server is able to handle an empty client-id // in incoming client message. TEST_F(Dhcpv4SrvTest, emptyClientId) { IfaceMgrTestConfig test_config(true); Dhcp4Client client; EXPECT_NO_THROW(configure(CONFIGS[0], *client.getServer())); // Tell the client to not send client-id on its own. client.includeClientId(""); // Instead, tell him to send this extra option, which happens to be // an empty client-id. OptionPtr empty_client_id(new Option(Option::V4, DHO_DHCP_CLIENT_IDENTIFIER)); client.addExtraOption(empty_client_id); // Let's check whether the server is able to process this packet without // throwing any exceptions. We don't care whether the server sent any // responses or not. The goal is to check that the server didn't throw // any exceptions. EXPECT_NO_THROW(client.doDORA()); } // This test verifies that the server is able to handle too long client-id // in incoming client message. TEST_F(Dhcpv4SrvTest, tooLongClientId) { IfaceMgrTestConfig test_config(true); Dhcp4Client client; EXPECT_NO_THROW(configure(CONFIGS[0], *client.getServer())); // Tell the client to not send client-id on its own. client.includeClientId(""); // Instead, tell him to send this extra option, which happens to be // an empty client-id. std::vector<uint8_t> data(250, 250); OptionPtr long_client_id(new Option(Option::V4, DHO_DHCP_CLIENT_IDENTIFIER, data)); client.addExtraOption(long_client_id); // Let's check whether the server is able to process this packet without // throwing any exceptions. We don't care whether the server sent any // responses or not. The goal is to check that the server didn't throw // any exceptions. EXPECT_NO_THROW(client.doDORA()); } // Checks if user-contexts are parsed properly. TEST_F(Dhcpv4SrvTest, userContext) { IfaceMgrTestConfig test_config(true); NakedDhcpv4Srv srv(0); // This config has one subnet with user-context with one // pool (also with context). Make sure the configuration could be accepted. cout << CONFIGS[3] << endl; EXPECT_NO_THROW(configure(CONFIGS[3])); // Now make sure the data was not lost. ConstSrvConfigPtr cfg = CfgMgr::instance().getCurrentCfg(); const Subnet4Collection* subnets = cfg->getCfgSubnets4()->getAll(); ASSERT_TRUE(subnets); ASSERT_EQ(1, subnets->size()); // Let's get the subnet and check its context. Subnet4Ptr subnet1 = *subnets->begin(); ASSERT_TRUE(subnet1); ASSERT_TRUE(subnet1->getContext()); EXPECT_EQ("{ \"secure\": false }", subnet1->getContext()->str()); // Ok, not get the sole pool in it and check its context, too. PoolCollection pools = subnet1->getPools(Lease::TYPE_V4); ASSERT_EQ(1, pools.size()); ASSERT_TRUE(pools[0]); ASSERT_TRUE(pools[0]->getContext()); EXPECT_EQ("{ \"value\": 42 }", pools[0]->getContext()->str()); } /// @todo: Implement proper tests for MySQL lease/host database, /// see ticket #4214. } // end of anonymous namespace
37.171084
95
0.648031
piskyscan
4f5167869a49afdb5b5f8137893247d673b5e466
3,173
cpp
C++
include/liveMedia/MPEG1or2DemuxedElementaryStream.cpp
RayanWang/DShowRtspVideo
cd8d641758dad71ef11b693e5716a05acfe86fca
[ "MIT" ]
5
2019-02-11T02:21:37.000Z
2022-03-26T16:17:32.000Z
include/liveMedia/MPEG1or2DemuxedElementaryStream.cpp
RayanWang/DShowRtspVideo
cd8d641758dad71ef11b693e5716a05acfe86fca
[ "MIT" ]
null
null
null
include/liveMedia/MPEG1or2DemuxedElementaryStream.cpp
RayanWang/DShowRtspVideo
cd8d641758dad71ef11b693e5716a05acfe86fca
[ "MIT" ]
6
2019-01-09T08:18:19.000Z
2021-01-08T18:21:27.000Z
/********** This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.) This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********/ // "liveMedia" // Copyright (c) 1996-2008 Live Networks, Inc. All rights reserved. // A MPEG 1 or 2 Elementary Stream, demultiplexed from a Program Stream // Implementation #include "MPEG1or2DemuxedElementaryStream.hh" ////////// MPEG1or2DemuxedElementaryStream ////////// MPEG1or2DemuxedElementaryStream:: MPEG1or2DemuxedElementaryStream(UsageEnvironment& env, u_int8_t streamIdTag, MPEG1or2Demux& sourceDemux) : FramedSource(env), fOurStreamIdTag(streamIdTag), fOurSourceDemux(sourceDemux), fMPEGversion(0) { // Set our MIME type string for known media types: if ((streamIdTag&0xE0) == 0xC0) { fMIMEtype = "audio/MPEG"; } else if ((streamIdTag&0xF0) == 0xE0) { fMIMEtype = "video/MPEG"; } else { fMIMEtype = MediaSource::MIMEtype(); } } MPEG1or2DemuxedElementaryStream::~MPEG1or2DemuxedElementaryStream() { fOurSourceDemux.noteElementaryStreamDeletion(this); } void MPEG1or2DemuxedElementaryStream::doGetNextFrame() { fOurSourceDemux.getNextFrame(fOurStreamIdTag, fTo, fMaxSize, afterGettingFrame, this, handleClosure, this); } void MPEG1or2DemuxedElementaryStream::doStopGettingFrames() { fOurSourceDemux.stopGettingFrames(fOurStreamIdTag); } char const* MPEG1or2DemuxedElementaryStream::MIMEtype() const { return fMIMEtype; } unsigned MPEG1or2DemuxedElementaryStream::maxFrameSize() const { return 6+65535; // because the MPEG spec allows for PES packets as large as // (6 + 65535) bytes (header + data) } void MPEG1or2DemuxedElementaryStream ::afterGettingFrame(void* clientData, unsigned frameSize, unsigned numTruncatedBytes, struct timeval presentationTime, unsigned durationInMicroseconds) { MPEG1or2DemuxedElementaryStream* stream = (MPEG1or2DemuxedElementaryStream*)clientData; stream->afterGettingFrame1(frameSize, numTruncatedBytes, presentationTime, durationInMicroseconds); } void MPEG1or2DemuxedElementaryStream ::afterGettingFrame1(unsigned frameSize, unsigned numTruncatedBytes, struct timeval presentationTime, unsigned durationInMicroseconds) { fFrameSize = frameSize; fNumTruncatedBytes = numTruncatedBytes; fPresentationTime = presentationTime; fDurationInMicroseconds = durationInMicroseconds; fLastSeenSCR = fOurSourceDemux.lastSeenSCR(); fMPEGversion = fOurSourceDemux.mpegVersion(); FramedSource::afterGetting(this); }
35.651685
81
0.765206
RayanWang
4f51f1fd6c1bc77cd55ee498df2e416278997d04
4,702
cpp
C++
src/formats/nsf_decoder.cpp
lexus2k/vgm_converter
b7a552a3a2f5287913b88f47209dc48bbcd0623f
[ "MIT" ]
2
2020-12-27T03:46:24.000Z
2021-10-09T15:02:21.000Z
src/formats/nsf_decoder.cpp
lexus2k/vgm_decoder
b7a552a3a2f5287913b88f47209dc48bbcd0623f
[ "MIT" ]
null
null
null
src/formats/nsf_decoder.cpp
lexus2k/vgm_decoder
b7a552a3a2f5287913b88f47209dc48bbcd0623f
[ "MIT" ]
null
null
null
/* MIT License Copyright (c) 2020 Aleksei Dynda Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "nsf_decoder.h" #include "formats/nsf_format.h" #include "chips/nsf_cartridge.h" #define NSF_DECODER_DEBUG 1 #if NSF_DECODER_DEBUG && !defined(VGM_DECODER_LOGGER) #define VGM_DECODER_LOGGER NSF_DECODER_DEBUG #endif #include "../vgm_logger.h" /** Vgm file are always based on 44.1kHz rate */ #define VGM_SAMPLE_RATE 44100 NsfMusicDecoder::NsfMusicDecoder(): BaseMusicDecoder() { } NsfMusicDecoder::~NsfMusicDecoder() { close(); } NsfMusicDecoder *NsfMusicDecoder::tryOpen(const uint8_t *data, int size) { NsfMusicDecoder *decoder = new NsfMusicDecoder(); if ( !decoder->open( data, size ) ) { delete decoder; decoder = nullptr; } return decoder; } bool NsfMusicDecoder::open(const uint8_t * data, int size) { close(); if ( size < sizeof(NsfHeader) ) { return false; } m_rawData = data; m_size = size; m_nsfHeader = reinterpret_cast<const NsfHeader *>(m_rawData); m_dataPtr = m_rawData; if ( m_nsfHeader->ident != 0x4D53454E ) { LOGE("%08X\n", m_nsfHeader->ident ); m_nsfHeader = nullptr; return false; } NsfCartridge *cartridge = new NsfCartridge(); cartridge->setDataBlock( m_nsfHeader->loadAddress, m_dataPtr + 0x80, m_size - 0x80 ); m_nesChip.insertCartridge( cartridge ); if ( !setTrack( 0 ) ) { return false; } LOG( "Init complete \n" ); LOG( "Nsf NTSC rate: %d us\n", m_nsfHeader->ntscPlaySpeed ); m_waitSamples = 0; return true; } void NsfMusicDecoder::close() { m_nesChip.insertCartridge( nullptr ); m_nsfHeader = nullptr; m_rawData = nullptr; } void NsfMusicDecoder::setVolume( uint16_t volume ) { m_nesChip.getApu()->setVolume( volume ); } int NsfMusicDecoder::getTrackCount() { // read nsf track count if ( m_nsfHeader ) return m_nsfHeader->songIndex; return 0; } bool NsfMusicDecoder::setTrack(int track) { // For vgm files this is not supported if ( !m_nsfHeader ) return false; m_nesChip.reset(); bool useBanks = false; for (int i=0; i<8; i++) if ( m_nsfHeader->bankSwitch[i] ) useBanks = true; if ( useBanks ) { for (int i=0; i<8; i++) m_nesChip.write( 0x5FF8 + i, m_nsfHeader->bankSwitch[i] ); } // Reset NES CPU memory and state NesCpuState &cpu = m_nesChip.cpuState(); for (uint16_t i = 0; i < 0x07FF; i++) m_nesChip.write(i, 0); for (uint16_t i = 0x4000; i < 0x4013; i++) m_nesChip.write(i, 0); m_nesChip.write(0x4015, 0x00); m_nesChip.write(0x4015, 0x0F); m_nesChip.write(0x4017, 0x40); // if the tune is bank switched, load the bank values from $070-$077 into $5FF8-$5FFF. cpu.x = 0; // ntsc cpu.a = track < m_nsfHeader->songIndex ? track: 0; cpu.sp = 0xEF; if ( m_nesChip.callSubroutine( m_nsfHeader->initAddress ) < 0 ) { LOGE( "Failed to call init subroutine for NSF file\n" ); return false; } // m_samplesPlayed = 0; return true; } uint32_t NsfMusicDecoder::getSample() { return m_nesChip.getApu()->getSample(); } int NsfMusicDecoder::decodeBlock() { int result = m_nesChip.callSubroutine( m_nsfHeader->playAddress, 20000 ); if ( result < 0 ) { LOGE( "Failed to call play subroutine due to CPU error, stopping\n" ); return -1; } if ( result == 0 ) { LOGE( "Failed to call play subroutine, it looks infinite loop, stopping\n" ); return 0; } m_waitSamples = (VGM_SAMPLE_RATE * static_cast<uint64_t>( m_nsfHeader->ntscPlaySpeed )) / 1000000; return m_waitSamples; }
28.670732
102
0.676521
lexus2k
4f524e6082dcc56f60148c59b1f970b3c0809c9e
685
cpp
C++
Foundation/src/RWLock_STD.cpp
astlin/poco
b878152e9034b89c923bc3c97e16ae1b92c09bf4
[ "BSL-1.0" ]
3
2015-06-08T15:09:28.000Z
2020-12-31T02:28:37.000Z
Foundation/src/RWLock_STD.cpp
astlin/poco
b878152e9034b89c923bc3c97e16ae1b92c09bf4
[ "BSL-1.0" ]
3
2021-06-02T02:59:06.000Z
2021-09-16T04:35:06.000Z
Foundation/src/RWLock_STD.cpp
astlin/poco
b878152e9034b89c923bc3c97e16ae1b92c09bf4
[ "BSL-1.0" ]
6
2021-06-02T02:39:34.000Z
2022-03-29T05:51:57.000Z
// // RWLock_WIN32.cpp // // Library: Foundation // Package: Threading // Module: RWLock // // Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // SPDX-License-Identifier: BSL-1.0 // #include "Poco/RWLock_STD.h" namespace Poco { RWLockImpl::RWLockImpl(): _mutex() { } void RWLockImpl::readLockImpl() { _mutex.lock_shared(); } bool RWLockImpl::tryReadLockImpl() { return _mutex.try_lock_shared(); } void RWLockImpl::writeLockImpl() { _mutex.lock(); } bool RWLockImpl::tryWriteLockImpl() { return _mutex.try_lock(); } void RWLockImpl::unlockImpl() { // TODO: unlock_shared()? _mutex.unlock(); } } // namespace Poco
11.810345
74
0.690511
astlin
4f55415d9dfe648373db56c769a566ffc8b52c9a
3,040
cpp
C++
gporca/libnaucrates/src/operators/CDXLScalarJoinFilter.cpp
Tanmoy248/gpdb
67fa1568b3ef2dc1c7757e3e94705de2f92e124b
[ "PostgreSQL", "Apache-2.0" ]
null
null
null
gporca/libnaucrates/src/operators/CDXLScalarJoinFilter.cpp
Tanmoy248/gpdb
67fa1568b3ef2dc1c7757e3e94705de2f92e124b
[ "PostgreSQL", "Apache-2.0" ]
null
null
null
gporca/libnaucrates/src/operators/CDXLScalarJoinFilter.cpp
Tanmoy248/gpdb
67fa1568b3ef2dc1c7757e3e94705de2f92e124b
[ "PostgreSQL", "Apache-2.0" ]
1
2022-03-22T18:45:41.000Z
2022-03-22T18:45:41.000Z
//--------------------------------------------------------------------------- // Greenplum Database // Copyright (C) 2010 Greenplum, Inc. // // @filename: // CDXLScalarJoinFilter.cpp // // @doc: // Implementation of DXL join filter operator //--------------------------------------------------------------------------- #include "naucrates/dxl/operators/CDXLScalarJoinFilter.h" #include "naucrates/dxl/operators/CDXLNode.h" #include "naucrates/dxl/xml/CXMLSerializer.h" using namespace gpos; using namespace gpdxl; //--------------------------------------------------------------------------- // @function: // CDXLScalarJoinFilter::CDXLScalarJoinFilter // // @doc: // Constructor // //--------------------------------------------------------------------------- CDXLScalarJoinFilter::CDXLScalarJoinFilter ( IMemoryPool *mp ) : CDXLScalarFilter(mp) { } //--------------------------------------------------------------------------- // @function: // CDXLScalarJoinFilter::GetDXLOperator // // @doc: // Operator type // //--------------------------------------------------------------------------- Edxlopid CDXLScalarJoinFilter::GetDXLOperator() const { return EdxlopScalarJoinFilter; } //--------------------------------------------------------------------------- // @function: // CDXLScalarJoinFilter::GetOpNameStr // // @doc: // Operator name // //--------------------------------------------------------------------------- const CWStringConst * CDXLScalarJoinFilter::GetOpNameStr() const { return CDXLTokens::GetDXLTokenStr(EdxltokenScalarJoinFilter); } //--------------------------------------------------------------------------- // @function: // CDXLScalarJoinFilter::SerializeToDXL // // @doc: // Serialize operator in DXL format // //--------------------------------------------------------------------------- void CDXLScalarJoinFilter::SerializeToDXL ( CXMLSerializer *xml_serializer, const CDXLNode *node ) const { const CWStringConst *element_name = GetOpNameStr(); xml_serializer->OpenElement(CDXLTokens::GetDXLTokenStr(EdxltokenNamespacePrefix), element_name); // serilize children node->SerializeChildrenToDXL(xml_serializer); xml_serializer->CloseElement(CDXLTokens::GetDXLTokenStr(EdxltokenNamespacePrefix), element_name); } #ifdef GPOS_DEBUG //--------------------------------------------------------------------------- // @function: // CDXLScalarJoinFilter::AssertValid // // @doc: // Checks whether operator node is well-structured // //--------------------------------------------------------------------------- void CDXLScalarJoinFilter::AssertValid ( const CDXLNode *node, BOOL validate_children ) const { GPOS_ASSERT(1 >= node->Arity()); if (1 == node->Arity()) { CDXLNode *dxlnode_condition = (*node)[0]; GPOS_ASSERT(EdxloptypeScalar == dxlnode_condition->GetOperator()->GetDXLOperatorType()); if (validate_children) { dxlnode_condition->GetOperator()->AssertValid(dxlnode_condition, validate_children); } } } #endif // GPOS_DEBUG // EOF
23.030303
99
0.511842
Tanmoy248
4f556eb0fdb3606f68d53dd17215a1559bdcac58
4,006
cpp
C++
tests/testGradientDescentOptimizer.cpp
sdmiller/gtsam_pcl
1e607bd75090d35e325a8fb37a6c5afe630f1207
[ "BSD-3-Clause" ]
11
2015-02-04T16:41:47.000Z
2021-12-10T07:02:44.000Z
tests/testGradientDescentOptimizer.cpp
malcolmreynolds/GTSAM
e911b4d39f8a8c8604663bd46f10e7f53c860ae8
[ "BSD-3-Clause" ]
null
null
null
tests/testGradientDescentOptimizer.cpp
malcolmreynolds/GTSAM
e911b4d39f8a8c8604663bd46f10e7f53c860ae8
[ "BSD-3-Clause" ]
6
2015-09-10T12:06:08.000Z
2021-12-10T07:02:48.000Z
/** * @file testGradientDescentOptimizer.cpp * @brief * @author ydjian * @date Jun 11, 2012 */ #include <gtsam/slam/PriorFactor.h> #include <gtsam/slam/BetweenFactor.h> #include <gtsam/nonlinear/NonlinearConjugateGradientOptimizer.h> #include <gtsam/nonlinear/NonlinearFactorGraph.h> #include <gtsam/nonlinear/Values.h> #include <gtsam/geometry/Pose2.h> #include <CppUnitLite/TestHarness.h> #include <boost/make_shared.hpp> #include <boost/shared_ptr.hpp> #include <boost/tuple/tuple.hpp> using namespace std; using namespace gtsam; boost::tuple<NonlinearFactorGraph, Values> generateProblem() { // 1. Create graph container and add factors to it NonlinearFactorGraph graph ; // 2a. Add Gaussian prior Pose2 priorMean(0.0, 0.0, 0.0); // prior at origin SharedDiagonal priorNoise = noiseModel::Diagonal::Sigmas(Vector_(3, 0.3, 0.3, 0.1)); graph.add(PriorFactor<Pose2>(1, priorMean, priorNoise)); // 2b. Add odometry factors SharedDiagonal odometryNoise = noiseModel::Diagonal::Sigmas(Vector_(3, 0.2, 0.2, 0.1)); graph.add(BetweenFactor<Pose2>(1, 2, Pose2(2.0, 0.0, 0.0 ), odometryNoise)); graph.add(BetweenFactor<Pose2>(2, 3, Pose2(2.0, 0.0, M_PI_2), odometryNoise)); graph.add(BetweenFactor<Pose2>(3, 4, Pose2(2.0, 0.0, M_PI_2), odometryNoise)); graph.add(BetweenFactor<Pose2>(4, 5, Pose2(2.0, 0.0, M_PI_2), odometryNoise)); // 2c. Add pose constraint SharedDiagonal constraintUncertainty = noiseModel::Diagonal::Sigmas(Vector_(3, 0.2, 0.2, 0.1)); graph.add(BetweenFactor<Pose2>(5, 2, Pose2(2.0, 0.0, M_PI_2), constraintUncertainty)); // 3. Create the data structure to hold the initialEstimate estinmate to the solution Values initialEstimate; Pose2 x1(0.5, 0.0, 0.2 ); initialEstimate.insert(1, x1); Pose2 x2(2.3, 0.1,-0.2 ); initialEstimate.insert(2, x2); Pose2 x3(4.1, 0.1, M_PI_2); initialEstimate.insert(3, x3); Pose2 x4(4.0, 2.0, M_PI ); initialEstimate.insert(4, x4); Pose2 x5(2.1, 2.1,-M_PI_2); initialEstimate.insert(5, x5); return boost::tie(graph, initialEstimate); } /* ************************************************************************* */ TEST(optimize, GradientDescentOptimizer) { NonlinearFactorGraph graph; Values initialEstimate; boost::tie(graph, initialEstimate) = generateProblem(); // cout << "initial error = " << graph.error(initialEstimate) << endl ; // Single Step Optimization using Levenberg-Marquardt NonlinearOptimizerParams param; param.maxIterations = 500; /* requires a larger number of iterations to converge */ param.verbosity = NonlinearOptimizerParams::SILENT; NonlinearConjugateGradientOptimizer optimizer(graph, initialEstimate, param); Values result = optimizer.optimize(); // cout << "gd1 solver final error = " << graph.error(result) << endl; /* the optimality of the solution is not comparable to the */ DOUBLES_EQUAL(0.0, graph.error(result), 1e-2); CHECK(1); } /* ************************************************************************* */ TEST(optimize, ConjugateGradientOptimizer) { NonlinearFactorGraph graph; Values initialEstimate; boost::tie(graph, initialEstimate) = generateProblem(); // cout << "initial error = " << graph.error(initialEstimate) << endl ; // Single Step Optimization using Levenberg-Marquardt NonlinearOptimizerParams param; param.maxIterations = 500; /* requires a larger number of iterations to converge */ param.verbosity = NonlinearOptimizerParams::SILENT; NonlinearConjugateGradientOptimizer optimizer(graph, initialEstimate, param); Values result = optimizer.optimize(); // cout << "cg final error = " << graph.error(result) << endl; /* the optimality of the solution is not comparable to the */ DOUBLES_EQUAL(0.0, graph.error(result), 1e-2); } /* ************************************************************************* */ int main() { TestResult tr; return TestRegistry::runAllTests(tr); } /* ************************************************************************* */
37.439252
97
0.665502
sdmiller
4f592b5fefaabab727c6e9ef71e75b562c3def73
7,515
cc
C++
Path.cc
lemrobotry/thesis
14ad489e8f04cb957707b89c454ee7d81ec672ad
[ "MIT" ]
null
null
null
Path.cc
lemrobotry/thesis
14ad489e8f04cb957707b89c454ee7d81ec672ad
[ "MIT" ]
null
null
null
Path.cc
lemrobotry/thesis
14ad489e8f04cb957707b89c454ee7d81ec672ad
[ "MIT" ]
null
null
null
#include "Path.hh" #include "PathVisitor.hh" #include <Core/Types.hh> #include <Fsa/Automaton.hh> namespace Permute { Arc::Arc (size_t index, Fsa::StateId source, Fsa::StateId target, double score) : PathImpl (score), original_index_ (index), source_ (source), target_ (target) {} size_t Arc::getIndex () const { return original_index_; } Fsa::StateId Arc::getStart () const { return source_; } Fsa::StateId Arc::getEnd () const { return target_; } void Arc::accept (PathVisitor * visitor) const { visitor -> visit (this); } /**********************************************************************/ PathComposite::PathComposite (const ConstPathRef & left, const ConstPathRef & right, double score) : PathImpl (left -> getScore () + right -> getScore () + score), left_ (left), right_ (right) {} ConstPathRef PathComposite::getLeft () const { return left_; } ConstPathRef PathComposite::getRight () const { return right_; } Fsa::StateId PathComposite::getStart () const { return left_ -> getStart (); } Fsa::StateId PathComposite::getEnd () const { return right_ -> getEnd (); } void PathComposite::accept (PathVisitor * visitor) const { visitor -> visit (this); } // A KeepNode is a composite path that preserves the order of its two // children. It is normal if its right child is not also a KeepNode. class KeepNode : public PathComposite { public: KeepNode (const ConstPathRef & left, const ConstPathRef & right, double score) : PathComposite (left, right, score) {} virtual Type type () const { return KEEP; } virtual bool normal () const { return right_ -> type () != KEEP; } }; // A SwapNode is a composite path that reverses the order of its two // children. It is normal if its right child in the resulting permutation // (which is its left child in the tree) is not also a SwapNode. class SwapNode : public PathComposite { public: SwapNode (const ConstPathRef & left, const ConstPathRef & right, double score) : PathComposite (left, right, score) {} virtual Type type () const { return SWAP; } virtual bool normal () const { return right_ -> type () != SWAP; } }; /**********************************************************************/ // A DummyPath is a path with no symbols used mostly for algorithmic and // testing purposes. class DummyPath : public Path { private: Fsa::StateId start_, end_; double weight_; public: DummyPath (Fsa::StateId start = Fsa::InvalidStateId, Fsa::StateId end = Fsa::InvalidStateId, double weight = Core::Type <double>::min) : Path (), start_ (start), end_ (end), weight_ (weight) {} Fsa::StateId getStart () const { return start_; } Fsa::StateId getEnd () const { return end_; } double getScore () const { return weight_; } void accept (PathVisitor * visitor) const {} }; /**********************************************************************/ // A FinalPath is a path of length zero that applies a state's final weight. // Its end state is Fsa::InvalidStateId, which stands in for a super-final // state. class FinalPath : public PathImpl { private: Fsa::StateId state_; public: FinalPath (Fsa::StateId state, double score) : PathImpl (score), state_ (state) {} Fsa::StateId getStart () const { return state_; } Fsa::StateId getEnd () const { return Fsa::InvalidStateId; } void accept (PathVisitor * visitor) const {} }; /**********************************************************************/ // An AddScorePath is a path with an additional score applied. It computes // it's wrapped path's score at construction time and returns the resulting // sum from getScore. class AddScorePath : public PathDecorator { private: double score_; public: AddScorePath (const ConstPathRef & path, double score) : PathDecorator (path), score_ (path -> getScore () + score) {} virtual double getScore () const { return score_; } }; /**********************************************************************/ ConstPathRef Path::nullPath () { static ConstPathRef nullPath_ (new DummyPath); return nullPath_; } ConstPathRef Path::lowerBound (Fsa::StateId start) { return ConstPathRef (new DummyPath (start, Core::Type <Fsa::StateId>::min)); } ConstPathRef Path::rLowerBound (Fsa::StateId end) { return ConstPathRef (new DummyPath (Core::Type <Fsa::StateId>::min, end)); } ConstPathRef Path::upperBound (Fsa::StateId start) { return ConstPathRef (new DummyPath (start, Core::Type <Fsa::StateId>::max)); } ConstPathRef Path::rUpperBound (Fsa::StateId end) { return ConstPathRef (new DummyPath (Core::Type <Fsa::StateId>::max, end)); } ConstPathRef Path::forSearch (Fsa::StateId start, Fsa::StateId end) { return ConstPathRef (new DummyPath (start, end)); } ConstPathRef Path::connect (const ConstPathRef & left, const ConstPathRef & right, double score, bool swap) { if (swap) { return ConstPathRef (new SwapNode (left, right, score)); } else { return ConstPathRef (new KeepNode (left, right, score)); } } ConstPathRef Path::arc (size_t index, Fsa::StateId start, Fsa::StateId end, double score) { return ConstPathRef (new Arc (index, start, end, score)); } ConstPathRef Path::epsilon (Fsa::StateId start, Fsa::StateId end, double score) { return ConstPathRef (new DummyPath (start, end, score)); } ConstPathRef Path::final (Fsa::StateId state, double score) { return ConstPathRef (new FinalPath (state, score)); } ConstPathRef Path::addScore (const ConstPathRef & path, double score) { return ConstPathRef (new AddScorePath (path, score)); } /**********************************************************************/ // One path is less than the other if it start state precedes the other's, or if // the start states are identical and its end state precedes the other's. bool Path::LessThan::operator () (const ConstPathRef & one, const ConstPathRef & two) const { if (one -> getStart () == two -> getStart ()) { return one -> getEnd () < two -> getEnd (); } else { return one -> getStart () < two -> getStart (); } } // From the reverse perspective, end states take precedence over start states. bool Path::rLessThan::operator () (const ConstPathRef & one, const ConstPathRef & two) const { if (one -> getEnd () == two -> getEnd ()) { return one -> getStart () < two -> getStart (); } else { return one -> getEnd () < two -> getEnd (); } } /**********************************************************************/ PathImpl::PathImpl (double score) : Path (), score_ (score) {} double PathImpl::getScore () const { return score_; } /**********************************************************************/ PathDecorator::PathDecorator (const ConstPathRef & decorated) : Path (), decorated_ (decorated) {} Fsa::StateId PathDecorator::getStart () const { return decorated_ -> getStart (); } Fsa::StateId PathDecorator::getEnd () const { return decorated_ -> getEnd (); } double PathDecorator::getScore () const { return decorated_ -> getScore (); } void PathDecorator::accept (PathVisitor * visitor) const { decorated_ -> accept (visitor); } }
31.443515
111
0.601597
lemrobotry
4f5a13ecc94699a96d2ea1b3b8a631cc44dec9e8
126,361
cpp
C++
VoIPController.cpp
openaphid/libtgvoip
b98a01ea44916444cb1b9192f80b46f974d296a6
[ "Unlicense" ]
null
null
null
VoIPController.cpp
openaphid/libtgvoip
b98a01ea44916444cb1b9192f80b46f974d296a6
[ "Unlicense" ]
null
null
null
VoIPController.cpp
openaphid/libtgvoip
b98a01ea44916444cb1b9192f80b46f974d296a6
[ "Unlicense" ]
null
null
null
// // libtgvoip is free and unencumbered public domain software. // For more information, see http://unlicense.org or the UNLICENSE file // you should have received with this source code distribution. // #ifndef _WIN32 #include <unistd.h> #include <sys/time.h> #endif #include <errno.h> #include <string.h> #include <wchar.h> #include "VoIPController.h" #include "logging.h" #include "threading.h" #include "Buffers.h" #include "OpusEncoder.h" #include "OpusDecoder.h" #include "VoIPServerConfig.h" #include "PrivateDefines.h" #include "json11.hpp" #include <assert.h> #include <time.h> #include <math.h> #include <exception> #include <stdexcept> #include <algorithm> #include <sstream> #include <inttypes.h> #include <float.h> #if TGVOIP_INCLUDE_OPUS_PACKAGE #include <opus/opus.h> #else #include <opus.h> #endif inline int pad4(int x){ int r=PAD4(x); if(r==4) return 0; return r; } using namespace tgvoip; // using namespace std; // Already used in BlockingQueue.h. #ifdef __APPLE__ #include "os/darwin/AudioUnitIO.h" #include <mach/mach_time.h> double VoIPController::machTimebase=0; uint64_t VoIPController::machTimestart=0; #endif #ifdef _WIN32 int64_t VoIPController::win32TimeScale = 0; bool VoIPController::didInitWin32TimeScale = false; #endif #ifdef __ANDROID__ #include "os/android/JNIUtilities.h" #include "os/android/AudioInputAndroid.h" extern jclass jniUtilitiesClass; #endif #if defined(TGVOIP_USE_CALLBACK_AUDIO_IO) #include "audio/AudioIOCallback.h" #endif extern FILE* tgvoipLogFile; #pragma mark - Public API VoIPController::VoIPController() : activeNetItfName(""), currentAudioInput("default"), currentAudioOutput("default"), proxyAddress(""), proxyUsername(""), proxyPassword(""){ seq=1; lastRemoteSeq=0; state=STATE_WAIT_INIT; audioInput=NULL; audioOutput=NULL; encoder=NULL; audioOutStarted=false; audioTimestampIn=0; audioTimestampOut=0; stopping=false; memset(recvPacketTimes, 0, sizeof(double)*32); memset(&stats, 0, sizeof(TrafficStats)); lastRemoteAckSeq=0; lastSentSeq=0; recvLossCount=0; packetsReceived=0; waitingForAcks=false; networkType=NET_TYPE_UNKNOWN; echoCanceller=NULL; dontSendPackets=0; micMuted=false; waitingForRelayPeerInfo=false; allowP2p=true; dataSavingMode=false; publicEndpointsReqTime=0; connectionInitTime=0; lastRecvPacketTime=0; dataSavingRequestedByPeer=false; peerVersion=0; conctl=new CongestionControl(); prevSendLossCount=0; receivedInit=false; receivedInitAck=false; statsDump=NULL; useTCP=false; useUDP=true; didAddTcpRelays=false; udpPingCount=0; lastUdpPingTime=0; proxyProtocol=PROXY_NONE; proxyPort=0; resolvedProxyAddress=NULL; selectCanceller=SocketSelectCanceller::Create(); udpSocket=NetworkSocket::Create(PROTO_UDP); realUdpSocket=udpSocket; udpConnectivityState=UDP_UNKNOWN; echoCancellationStrength=1; peerCapabilities=0; callbacks={0}; didReceiveGroupCallKey=false; didReceiveGroupCallKeyAck=false; didSendGroupCallKey=false; didSendUpgradeRequest=false; didInvokeUpgradeCallback=false; connectionMaxLayer=0; useMTProto2=false; setCurrentEndpointToTCP=false; useIPv6=false; peerIPv6Available=false; shittyInternetMode=false; didAddIPv6Relays=false; didSendIPv6Endpoint=false; unsentStreamPackets.store(0); sendThread=NULL; recvThread=NULL; maxAudioBitrate=(uint32_t) ServerConfig::GetSharedInstance()->GetInt("audio_max_bitrate", 20000); maxAudioBitrateGPRS=(uint32_t) ServerConfig::GetSharedInstance()->GetInt("audio_max_bitrate_gprs", 8000); maxAudioBitrateEDGE=(uint32_t) ServerConfig::GetSharedInstance()->GetInt("audio_max_bitrate_edge", 16000); maxAudioBitrateSaving=(uint32_t) ServerConfig::GetSharedInstance()->GetInt("audio_max_bitrate_saving", 8000); initAudioBitrate=(uint32_t) ServerConfig::GetSharedInstance()->GetInt("audio_init_bitrate", 16000); initAudioBitrateGPRS=(uint32_t) ServerConfig::GetSharedInstance()->GetInt("audio_init_bitrate_gprs", 8000); initAudioBitrateEDGE=(uint32_t) ServerConfig::GetSharedInstance()->GetInt("audio_init_bitrate_edge", 8000); initAudioBitrateSaving=(uint32_t) ServerConfig::GetSharedInstance()->GetInt("audio_init_bitrate_saving", 8000); audioBitrateStepIncr=(uint32_t) ServerConfig::GetSharedInstance()->GetInt("audio_bitrate_step_incr", 1000); audioBitrateStepDecr=(uint32_t) ServerConfig::GetSharedInstance()->GetInt("audio_bitrate_step_decr", 1000); minAudioBitrate=(uint32_t) ServerConfig::GetSharedInstance()->GetInt("audio_min_bitrate", 8000); relaySwitchThreshold=ServerConfig::GetSharedInstance()->GetDouble("relay_switch_threshold", 0.8); p2pToRelaySwitchThreshold=ServerConfig::GetSharedInstance()->GetDouble("p2p_to_relay_switch_threshold", 0.6); relayToP2pSwitchThreshold=ServerConfig::GetSharedInstance()->GetDouble("relay_to_p2p_switch_threshold", 0.8); reconnectingTimeout=ServerConfig::GetSharedInstance()->GetDouble("reconnecting_state_timeout", 2.0); needRateFlags=static_cast<uint32_t>(ServerConfig::GetSharedInstance()->GetInt("rate_flags", 0xFFFFFFFF)); rateMaxAcceptableRTT=ServerConfig::GetSharedInstance()->GetDouble("rate_min_rtt", 0.6); rateMaxAcceptableSendLoss=ServerConfig::GetSharedInstance()->GetDouble("rate_min_send_loss", 0.2); packetLossToEnableExtraEC=ServerConfig::GetSharedInstance()->GetDouble("packet_loss_for_extra_ec", 0.02); maxUnsentStreamPackets=static_cast<uint32_t>(ServerConfig::GetSharedInstance()->GetInt("max_unsent_stream_packets", 2)); #ifdef __APPLE__ machTimestart=0; #endif shared_ptr<Stream> stm=make_shared<Stream>(); stm->id=1; stm->type=STREAM_TYPE_AUDIO; stm->codec=CODEC_OPUS; stm->enabled=1; stm->frameDuration=60; outgoingStreams.push_back(stm); } VoIPController::~VoIPController(){ LOGD("Entered VoIPController::~VoIPController"); if(!stopping){ LOGE("!!!!!!!!!!!!!!!!!!!! CALL controller->Stop() BEFORE DELETING THE CONTROLLER OBJECT !!!!!!!!!!!!!!!!!!!!!!!1"); abort(); } LOGD("before close socket"); if(udpSocket) delete udpSocket; if(udpSocket!=realUdpSocket) delete realUdpSocket; LOGD("before delete audioIO"); if(audioIO){ delete audioIO; audioInput=NULL; audioOutput=NULL; } for(vector<shared_ptr<Stream>>::iterator _stm=incomingStreams.begin();_stm!=incomingStreams.end();++_stm){ shared_ptr<Stream> stm=*_stm; LOGD("before stop decoder"); if(stm->decoder){ stm->decoder->Stop(); } } LOGD("before delete encoder"); if(encoder){ encoder->Stop(); delete encoder; } LOGD("before delete echo canceller"); if(echoCanceller){ echoCanceller->Stop(); delete echoCanceller; } delete conctl; if(statsDump) fclose(statsDump); if(resolvedProxyAddress) delete resolvedProxyAddress; delete selectCanceller; LOGD("Left VoIPController::~VoIPController"); if(tgvoipLogFile){ FILE* log=tgvoipLogFile; tgvoipLogFile=NULL; fclose(log); } #if defined(TGVOIP_USE_CALLBACK_AUDIO_IO) if (preprocDecoder) { opus_decoder_destroy(preprocDecoder); preprocDecoder=nullptr; } #endif } void VoIPController::Stop(){ LOGD("Entered VoIPController::Stop"); stopping=true; runReceiver=false; LOGD("before shutdown socket"); if(udpSocket) udpSocket->Close(); if(realUdpSocket!=udpSocket) realUdpSocket->Close(); selectCanceller->CancelSelect(); Buffer emptyBuf(0); //PendingOutgoingPacket emptyPacket{0, 0, 0, move(emptyBuf), 0}; //sendQueue->Put(move(emptyPacket)); LOGD("before join sendThread"); if(sendThread){ sendThread->Join(); delete sendThread; } LOGD("before join recvThread"); if(recvThread){ recvThread->Join(); delete recvThread; } LOGD("before stop messageThread"); messageThread.Stop(); { LOGD("Before stop audio I/O"); MutexGuard m(audioIOMutex); if(audioInput){ audioInput->Stop(); audioInput->SetCallback(NULL, NULL); } if(audioOutput){ audioOutput->Stop(); audioOutput->SetCallback(NULL, NULL); } } LOGD("Left VoIPController::Stop [need rate = %d]", (int)needRate); } bool VoIPController::NeedRate(){ return needRate && ServerConfig::GetSharedInstance()->GetBoolean("bad_call_rating", false); } void VoIPController::SetRemoteEndpoints(vector<Endpoint> endpoints, bool allowP2p, int32_t connectionMaxLayer){ LOGW("Set remote endpoints, allowP2P=%d, connectionMaxLayer=%u", allowP2p ? 1 : 0, connectionMaxLayer); preferredRelay=0; { MutexGuard m(endpointsMutex); this->endpoints.clear(); didAddTcpRelays=false; useTCP=true; for(vector<Endpoint>::iterator itrtr=endpoints.begin();itrtr!=endpoints.end();++itrtr){ if(this->endpoints.find(itrtr->id)!=this->endpoints.end()) LOGE("Endpoint IDs are not unique!"); this->endpoints[itrtr->id]=*itrtr; if(currentEndpoint==0) currentEndpoint=itrtr->id; if(itrtr->type==Endpoint::Type::TCP_RELAY) didAddTcpRelays=true; if(itrtr->type==Endpoint::Type::UDP_RELAY) useTCP=false; LOGV("Adding endpoint: %s:%d, %s", itrtr->address.ToString().c_str(), itrtr->port, itrtr->type==Endpoint::Type::UDP_RELAY ? "UDP" : "TCP"); } } preferredRelay=currentEndpoint; this->allowP2p=allowP2p; this->connectionMaxLayer=connectionMaxLayer; if(connectionMaxLayer>=74){ useMTProto2=true; } AddIPv6Relays(); } void VoIPController::Start(){ LOGW("Starting voip controller"); udpSocket->Open(); if(udpSocket->IsFailed()){ SetState(STATE_FAILED); return; } //SendPacket(NULL, 0, currentEndpoint); runReceiver=true; recvThread=new Thread(bind(&VoIPController::RunRecvThread, this)); recvThread->SetName("VoipRecv"); recvThread->Start(); messageThread.Start(); } void VoIPController::Connect(){ assert(state!=STATE_WAIT_INIT_ACK); connectionInitTime=GetCurrentTime(); if(config.initTimeout==0.0){ LOGE("Init timeout is 0 -- did you forget to set config?"); config.initTimeout=30.0; } //InitializeTimers(); //SendInit(); sendThread=new Thread(bind(&VoIPController::RunSendThread, this)); sendThread->SetName("VoipSend"); sendThread->Start(); } void VoIPController::SetEncryptionKey(char *key, bool isOutgoing){ memcpy(encryptionKey, key, 256); uint8_t sha1[SHA1_LENGTH]; crypto.sha1((uint8_t*) encryptionKey, 256, sha1); memcpy(keyFingerprint, sha1+(SHA1_LENGTH-8), 8); uint8_t sha256[SHA256_LENGTH]; crypto.sha256((uint8_t*) encryptionKey, 256, sha256); memcpy(callID, sha256+(SHA256_LENGTH-16), 16); this->isOutgoing=isOutgoing; } void VoIPController::SetNetworkType(int type){ networkType=type; UpdateDataSavingState(); UpdateAudioBitrateLimit(); myIPv6=IPv6Address(); string itfName=udpSocket->GetLocalInterfaceInfo(NULL, &myIPv6); LOGI("set network type: %s, active interface %s", NetworkTypeToString(type).c_str(), itfName.c_str()); LOGI("Local IPv6 address: %s", myIPv6.ToString().c_str()); if(IS_MOBILE_NETWORK(networkType)){ CellularCarrierInfo carrier=GetCarrierInfo(); if(!carrier.name.empty()){ LOGI("Carrier: %s [%s; mcc=%s, mnc=%s]", carrier.name.c_str(), carrier.countryCode.c_str(), carrier.mcc.c_str(), carrier.mnc.c_str()); } } if(itfName!=activeNetItfName){ udpSocket->OnActiveInterfaceChanged(); LOGI("Active network interface changed: %s -> %s", activeNetItfName.c_str(), itfName.c_str()); bool isFirstChange=activeNetItfName.length()==0 && state!=STATE_ESTABLISHED && state!=STATE_RECONNECTING; activeNetItfName=itfName; if(isFirstChange) return; wasNetworkHandover=true; if(currentEndpoint){ const Endpoint& _currentEndpoint=endpoints.at(currentEndpoint); const Endpoint& _preferredRelay=endpoints.at(preferredRelay); if(_currentEndpoint.type!=Endpoint::Type::UDP_RELAY){ if(_preferredRelay.type==Endpoint::Type::UDP_RELAY) currentEndpoint=preferredRelay; MutexGuard m(endpointsMutex); constexpr int64_t lanID=(int64_t)(FOURCC('L','A','N','4')) << 32; endpoints.erase(lanID); for(pair<const int64_t, Endpoint>& e:endpoints){ Endpoint& endpoint=e.second; if(endpoint.type==Endpoint::Type::UDP_RELAY && useTCP){ useTCP=false; if(_preferredRelay.type==Endpoint::Type::TCP_RELAY){ preferredRelay=currentEndpoint=endpoint.id; } }else if(endpoint.type==Endpoint::Type::TCP_RELAY && endpoint.socket){ endpoint.socket->Close(); //delete endpoint.socket; //endpoint.socket=NULL; } //if(endpoint->type==Endpoint::Type::UDP_P2P_INET){ endpoint.averageRTT=0; endpoint.rtts.Reset(); //} } } } lastUdpPingTime=0; if(proxyProtocol==PROXY_SOCKS5) InitUDPProxy(); if(allowP2p && currentEndpoint){ SendPublicEndpointsRequest(); } BufferOutputStream s(4); s.WriteInt32(dataSavingMode ? INIT_FLAG_DATA_SAVING_ENABLED : 0); if(peerVersion<6){ SendPacketReliably(PKT_NETWORK_CHANGED, s.GetBuffer(), s.GetLength(), 1, 20); }else{ Buffer buf(move(s)); SendExtra(buf, EXTRA_TYPE_NETWORK_CHANGED); } needReInitUdpProxy=true; selectCanceller->CancelSelect(); didSendIPv6Endpoint=false; AddIPv6Relays(); ResetUdpAvailability(); ResetEndpointPingStats(); } } double VoIPController::GetAverageRTT(){ if(lastSentSeq>=lastRemoteAckSeq){ uint32_t diff=lastSentSeq-lastRemoteAckSeq; //LOGV("rtt diff=%u", diff); if(diff<32){ double res=0; int count=0; /*for(i=diff;i<32;i++){ if(remoteAcks[i-diff]>0){ res+=(remoteAcks[i-diff]-sentPacketTimes[i]); count++; } }*/ MutexGuard m(queuedPacketsMutex); for(std::vector<RecentOutgoingPacket>::iterator itr=recentOutgoingPackets.begin();itr!=recentOutgoingPackets.end();++itr){ if(itr->ackTime>0){ res+=(itr->ackTime-itr->sendTime); count++; } } if(count>0) res/=count; return res; } } return 999; } void VoIPController::SetMicMute(bool mute){ if(micMuted==mute) return; micMuted=mute; if(audioInput){ if(mute) audioInput->Stop(); else audioInput->Start(); if(!audioInput->IsInitialized()){ lastError=ERROR_AUDIO_IO; SetState(STATE_FAILED); return; } } if(echoCanceller) echoCanceller->Enable(!mute); if(state==STATE_ESTABLISHED){ for(shared_ptr<Stream>& s:outgoingStreams){ if(s->type==STREAM_TYPE_AUDIO){ s->enabled=!mute; if(peerVersion<6){ unsigned char buf[2]; buf[0]=s->id; buf[1]=(char) (mute ? 0 : 1); SendPacketReliably(PKT_STREAM_STATE, buf, 2, .5f, 20); }else{ SendStreamFlags(*s); } } } } if(mute){ if(noStreamsNopID==MessageThread::INVALID_ID) noStreamsNopID=messageThread.Post(std::bind(&VoIPController::SendNopPacket, this), 0.2, 0.2); }else{ if(noStreamsNopID!=MessageThread::INVALID_ID){ messageThread.Cancel(noStreamsNopID); noStreamsNopID=MessageThread::INVALID_ID; } } } string VoIPController::GetDebugString(){ string r="Remote endpoints: \n"; char buffer[2048]; MutexGuard m(endpointsMutex); for(pair<const int64_t, Endpoint>& _e:endpoints){ Endpoint& endpoint=_e.second; const char* type; switch(endpoint.type){ case Endpoint::Type::UDP_P2P_INET: type="UDP_P2P_INET"; break; case Endpoint::Type::UDP_P2P_LAN: type="UDP_P2P_LAN"; break; case Endpoint::Type::UDP_RELAY: type="UDP_RELAY"; break; case Endpoint::Type::TCP_RELAY: type="TCP_RELAY"; break; default: type="UNKNOWN"; break; } snprintf(buffer, sizeof(buffer), "%s:%u %dms %d 0x%" PRIx64 " [%s%s]\n", endpoint.address.IsEmpty() ? ("["+endpoint.v6address.ToString()+"]").c_str() : endpoint.address.ToString().c_str(), endpoint.port, (int)(endpoint.averageRTT*1000), endpoint.udpPongCount, (uint64_t)endpoint.id, type, currentEndpoint==endpoint.id ? ", IN_USE" : ""); r+=buffer; } if(shittyInternetMode){ snprintf(buffer, sizeof(buffer), "ShittyInternetMode: level %d\n", extraEcLevel); r+=buffer; } double avgLate[3]; shared_ptr<Stream> stm=GetStreamByType(STREAM_TYPE_AUDIO, false); shared_ptr<JitterBuffer> jitterBuffer; if(stm) jitterBuffer=stm->jitterBuffer; if(jitterBuffer) jitterBuffer->GetAverageLateCount(avgLate); else memset(avgLate, 0, 3*sizeof(double)); snprintf(buffer, sizeof(buffer), "Jitter buffer: %d/%.2f | %.1f, %.1f, %.1f\n" "RTT avg/min: %d/%d\n" "Congestion window: %d/%d bytes\n" "Key fingerprint: %02hhX%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX%s\n" "Last sent/ack'd seq: %u/%u\n" "Last recvd seq: %u\n" "Send/recv losses: %u/%u (%d%%)\n" "Audio bitrate: %d kbit\n" "Outgoing queue: %u\n" // "Packet grouping: %d\n" "Frame size out/in: %d/%d\n" "Bytes sent/recvd: %llu/%llu", jitterBuffer ? jitterBuffer->GetMinPacketCount() : 0, jitterBuffer ? jitterBuffer->GetAverageDelay() : 0, avgLate[0], avgLate[1], avgLate[2], // (int)(GetAverageRTT()*1000), 0, (int)(conctl->GetAverageRTT()*1000), (int)(conctl->GetMinimumRTT()*1000), int(conctl->GetInflightDataSize()), int(conctl->GetCongestionWindow()), keyFingerprint[0],keyFingerprint[1],keyFingerprint[2],keyFingerprint[3],keyFingerprint[4],keyFingerprint[5],keyFingerprint[6],keyFingerprint[7], useMTProto2 ? " (MTProto2.0)" : "", lastSentSeq, lastRemoteAckSeq, lastRemoteSeq, conctl->GetSendLossCount(), recvLossCount, encoder ? encoder->GetPacketLoss() : 0, encoder ? (encoder->GetBitrate()/1000) : 0, static_cast<unsigned int>(unsentStreamPackets), // audioPacketGrouping, outgoingStreams[0]->frameDuration, incomingStreams.size()>0 ? incomingStreams[0]->frameDuration : 0, (long long unsigned int)(stats.bytesSentMobile+stats.bytesSentWifi), (long long unsigned int)(stats.bytesRecvdMobile+stats.bytesRecvdWifi)); r+=buffer; return r; } const char* VoIPController::GetVersion(){ return LIBTGVOIP_VERSION; } int64_t VoIPController::GetPreferredRelayID(){ return preferredRelay; } int VoIPController::GetLastError(){ return lastError; } void VoIPController::GetStats(TrafficStats *stats){ memcpy(stats, &this->stats, sizeof(TrafficStats)); } string VoIPController::GetDebugLog(){ map<string, json11::Json> network{ {"type", NetworkTypeToString(networkType)} }; if(IS_MOBILE_NETWORK(networkType)){ CellularCarrierInfo carrier=GetCarrierInfo(); if(!carrier.name.empty()){ network["carrier"]=carrier.name; network["country"]=carrier.countryCode; network["mcc"]=carrier.mcc; network["mnc"]=carrier.mnc; } }else if(networkType==NET_TYPE_WIFI){ #ifdef __ANDROID__ jni::DoWithJNI([&](JNIEnv* env){ jmethodID getWifiInfoMethod=env->GetStaticMethodID(jniUtilitiesClass, "getWifiInfo", "()[I"); jintArray res=static_cast<jintArray>(env->CallStaticObjectMethod(jniUtilitiesClass, getWifiInfoMethod)); if(res){ jint* wifiInfo=env->GetIntArrayElements(res, NULL); network["rssi"]=wifiInfo[0]; network["link_speed"]=wifiInfo[1]; env->ReleaseIntArrayElements(res, wifiInfo, JNI_ABORT); } }); #endif } /*vector<json11::Json> lpkts; for(DebugLoggedPacket& lpkt:debugLoggedPackets){ lpkts.push_back(json11::Json::array{lpkt.timestamp, lpkt.seq, lpkt.length}); } return json11::Json(json11::Json::object{ {"log_type", "out_packet_stats"}, {"libtgvoip_version", LIBTGVOIP_VERSION}, {"network", network}, {"protocol_version", std::min(peerVersion, PROTOCOL_VERSION)}, {"total_losses", json11::Json::object{ {"s", (int32_t)conctl->GetSendLossCount()}, {"r", (int32_t)recvLossCount} }}, {"call_duration", GetCurrentTime()-connectionInitTime}, {"out_packet_stats", lpkts} }).dump();*/ string p2pType="none"; Endpoint& cur=endpoints[currentEndpoint]; if(cur.type==Endpoint::Type::UDP_P2P_INET) p2pType=cur.IsIPv6Only() ? "inet6" : "inet"; else if(cur.type==Endpoint::Type::UDP_P2P_LAN) p2pType="lan"; vector<string> problems; if(lastError==ERROR_TIMEOUT) problems.push_back("timeout"); if(wasReconnecting) problems.push_back("reconnecting"); if(wasExtraEC) problems.push_back("extra_ec"); if(wasEncoderLaggy) problems.push_back("encoder_lag"); if(!wasEstablished) problems.push_back("not_inited"); if(wasNetworkHandover) problems.push_back("network_handover"); ostringstream prefRelay; prefRelay << preferredRelay; return json11::Json(json11::Json::object{ {"log_type", "call_stats"}, {"libtgvoip_version", LIBTGVOIP_VERSION}, {"network", network}, {"protocol_version", std::min(peerVersion, PROTOCOL_VERSION)}, {"udp_avail", udpConnectivityState==UDP_AVAILABLE}, {"tcp_used", useTCP}, {"relay_rtt", (int)(endpoints[preferredRelay].averageRTT*1000.0)}, {"p2p_type", p2pType}, {"rtt", (int)(endpoints[currentEndpoint].averageRTT*1000.0)}, {"packet_stats", json11::Json::object{ {"out", (int)seq}, {"in", (int)packetsReceived}, {"lost_out", (int)conctl->GetSendLossCount()}, {"lost_in", (int)recvLossCount} }}, {"problems", problems}, {"pref_relay", prefRelay.str()} }).dump(); } vector<AudioInputDevice> VoIPController::EnumerateAudioInputs(){ vector<AudioInputDevice> devs; audio::AudioInput::EnumerateDevices(devs); return devs; } vector<AudioOutputDevice> VoIPController::EnumerateAudioOutputs(){ vector<AudioOutputDevice> devs; audio::AudioOutput::EnumerateDevices(devs); return devs; } void VoIPController::SetCurrentAudioInput(string id){ currentAudioInput=id; if(audioInput) audioInput->SetCurrentDevice(id); } void VoIPController::SetCurrentAudioOutput(string id){ currentAudioOutput=id; if(audioOutput) audioOutput->SetCurrentDevice(id); } string VoIPController::GetCurrentAudioInputID(){ return currentAudioInput; } string VoIPController::GetCurrentAudioOutputID(){ return currentAudioOutput; } void VoIPController::SetProxy(int protocol, string address, uint16_t port, string username, string password){ proxyProtocol=protocol; proxyAddress=std::move(address); proxyPort=port; proxyUsername=std::move(username); proxyPassword=std::move(password); } int VoIPController::GetSignalBarsCount(){ return signalBarsHistory.NonZeroAverage(); } void VoIPController::SetCallbacks(VoIPController::Callbacks callbacks){ this->callbacks=callbacks; if(callbacks.connectionStateChanged) callbacks.connectionStateChanged(this, state); } void VoIPController::SetAudioOutputGainControlEnabled(bool enabled){ LOGD("New output AGC state: %d", enabled); } uint32_t VoIPController::GetPeerCapabilities(){ return peerCapabilities; } void VoIPController::SendGroupCallKey(unsigned char *key){ if(!(peerCapabilities & TGVOIP_PEER_CAP_GROUP_CALLS)){ LOGE("Tried to send group call key but peer isn't capable of them"); return; } if(didSendGroupCallKey){ LOGE("Tried to send a group call key repeatedly"); return; } if(!isOutgoing){ LOGE("You aren't supposed to send group call key in an incoming call, use VoIPController::RequestCallUpgrade() instead"); return; } didSendGroupCallKey=true; Buffer buf(256); buf.CopyFrom(key, 0, 256); SendExtra(buf, EXTRA_TYPE_GROUP_CALL_KEY); } void VoIPController::RequestCallUpgrade(){ if(!(peerCapabilities & TGVOIP_PEER_CAP_GROUP_CALLS)){ LOGE("Tried to send group call key but peer isn't capable of them"); return; } if(didSendUpgradeRequest){ LOGE("Tried to send upgrade request repeatedly"); return; } if(isOutgoing){ LOGE("You aren't supposed to send an upgrade request in an outgoing call, generate an encryption key and use VoIPController::SendGroupCallKey instead"); return; } didSendUpgradeRequest=true; Buffer empty(0); SendExtra(empty, EXTRA_TYPE_REQUEST_GROUP); } void VoIPController::SetEchoCancellationStrength(int strength){ echoCancellationStrength=strength; if(echoCanceller) echoCanceller->SetAECStrength(strength); } #if defined(TGVOIP_USE_CALLBACK_AUDIO_IO) void VoIPController::SetAudioDataCallbacks(std::function<void(int16_t*, size_t)> input, std::function<void(int16_t*, size_t)> output, std::function<void(int16_t*, size_t)> preproc=nullptr){ audioInputDataCallback=input; audioOutputDataCallback=output; audioPreprocDataCallback=preproc; preprocDecoder=preprocDecoder ? preprocDecoder : opus_decoder_create(48000, 1, NULL); } #endif int VoIPController::GetConnectionState(){ return state; } void VoIPController::SetConfig(const Config& cfg){ config=cfg; if(tgvoipLogFile){ fclose(tgvoipLogFile); tgvoipLogFile=NULL; } if(!config.logFilePath.empty()){ #ifndef _WIN32 tgvoipLogFile=fopen(config.logFilePath.c_str(), "a"); #else if(_wfopen_s(&tgvoipLogFile, config.logFilePath.c_str(), L"a")!=0){ tgvoipLogFile=NULL; } #endif tgvoip_log_file_write_header(tgvoipLogFile); }else{ tgvoipLogFile=NULL; } if(statsDump){ fclose(statsDump); statsDump=NULL; } if(!config.statsDumpFilePath.empty()){ #ifndef _WIN32 statsDump=fopen(config.statsDumpFilePath.c_str(), "w"); #else if(_wfopen_s(&statsDump, config.statsDumpFilePath.c_str(), L"w")!=0){ statsDump=NULL; } #endif if(statsDump) fprintf(statsDump, "Time\tRTT\tLRSeq\tLSSeq\tLASeq\tLostR\tLostS\tCWnd\tBitrate\tLoss%%\tJitter\tJDelay\tAJDelay\n"); //else // LOGW("Failed to open stats dump file %s for writing", config.statsDumpFilePath.c_str()); }else{ statsDump=NULL; } UpdateDataSavingState(); UpdateAudioBitrateLimit(); } void VoIPController::SetPersistentState(vector<uint8_t> state){ using namespace json11; if(state.empty()) return; string jsonErr; string json=string(state.begin(), state.end()); Json _obj=Json::parse(json, jsonErr); if(!jsonErr.empty()){ LOGE("Error parsing persistable state: %s", jsonErr.c_str()); return; } Json::object obj=_obj.object_items(); if(obj.find("proxy")!=obj.end()){ Json::object proxy=obj["proxy"].object_items(); lastTestedProxyServer=proxy["server"].string_value(); proxySupportsUDP=proxy["udp"].bool_value(); proxySupportsTCP=proxy["tcp"].bool_value(); } } vector<uint8_t> VoIPController::GetPersistentState(){ using namespace json11; Json::object obj=Json::object{ {"ver", 1}, }; if(proxyProtocol==PROXY_SOCKS5){ char pbuf[128]; snprintf(pbuf, sizeof(pbuf), "%s:%u", proxyAddress.c_str(), proxyPort); obj.insert({"proxy", Json::object{ {"server", string(pbuf)}, {"udp", proxySupportsUDP}, {"tcp", proxySupportsTCP} }}); } string _jstr=Json(obj).dump(); const char* jstr=_jstr.c_str(); return vector<uint8_t>(jstr, jstr+strlen(jstr)); } void VoIPController::SetOutputVolume(float level){ outputVolume.SetLevel(level); } void VoIPController::SetInputVolume(float level){ inputVolume.SetLevel(level); } #if defined(__APPLE__) && TARGET_OS_OSX void VoIPController::SetAudioOutputDuckingEnabled(bool enabled){ macAudioDuckingEnabled=enabled; audio::AudioUnitIO* osxAudio=dynamic_cast<audio::AudioUnitIO*>(audioIO); if(osxAudio){ osxAudio->SetDuckingEnabled(enabled); } } #endif #pragma mark - Internal intialization void VoIPController::InitializeTimers(){ initTimeoutID=messageThread.Post([this]{ LOGW("Init timeout, disconnecting"); lastError=ERROR_TIMEOUT; SetState(STATE_FAILED); }, config.initTimeout); if(!config.statsDumpFilePath.empty()){ messageThread.Post([this]{ if(statsDump && incomingStreams.size()==1){ shared_ptr<JitterBuffer>& jitterBuffer=incomingStreams[0]->jitterBuffer; //fprintf(statsDump, "Time\tRTT\tLISeq\tLASeq\tCWnd\tBitrate\tJitter\tJDelay\tAJDelay\n"); fprintf(statsDump, "%.3f\t%.3f\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%.3f\t%.3f\t%.3f\n", GetCurrentTime()-connectionInitTime, endpoints.at(currentEndpoint).rtts[0], lastRemoteSeq, (uint32_t)seq, lastRemoteAckSeq, recvLossCount, conctl ? conctl->GetSendLossCount() : 0, conctl ? (int)conctl->GetInflightDataSize() : 0, encoder ? encoder->GetBitrate() : 0, encoder ? encoder->GetPacketLoss() : 0, jitterBuffer ? jitterBuffer->GetLastMeasuredJitter() : 0, jitterBuffer ? jitterBuffer->GetLastMeasuredDelay()*0.06 : 0, jitterBuffer ? jitterBuffer->GetAverageDelay()*0.06 : 0); } }, 0.1, 0.1); } messageThread.Post(std::bind(&VoIPController::SendRelayPings, this), 0.0, 2.0); } void VoIPController::RunSendThread(){ InitializeAudio(); InitializeTimers(); SendInit(); LOGI("=== send thread exiting ==="); } #pragma mark - Miscellaneous void VoIPController::SetState(int state){ this->state=state; LOGV("Call state changed to %d", state); stateChangeTime=GetCurrentTime(); messageThread.Post([this, state]{ if(callbacks.connectionStateChanged) callbacks.connectionStateChanged(this, state); }); if(state==STATE_ESTABLISHED){ SetMicMute(micMuted); if(!wasEstablished){ wasEstablished=true; messageThread.Post(std::bind(&VoIPController::UpdateRTT, this), 0.1, 0.5); messageThread.Post(std::bind(&VoIPController::UpdateAudioBitrate, this), 0.0, 0.3); messageThread.Post(std::bind(&VoIPController::UpdateCongestion, this), 0.0, 1.0); messageThread.Post(std::bind(&VoIPController::UpdateSignalBars, this), 1.0, 1.0); messageThread.Post(std::bind(&VoIPController::TickJitterBufferAngCongestionControl, this), 0.0, 0.1); } } } void VoIPController::SendStreamFlags(Stream& stream){ BufferOutputStream s(5); s.WriteByte(stream.id); uint32_t flags=0; if(stream.enabled) flags|=STREAM_FLAG_ENABLED; if(stream.extraECEnabled) flags|=STREAM_FLAG_EXTRA_EC; s.WriteInt32(flags); LOGV("My stream state: id %u flags %u", (unsigned int)stream.id, (unsigned int)flags); Buffer buf(move(s)); SendExtra(buf, EXTRA_TYPE_STREAM_FLAGS); } shared_ptr<VoIPController::Stream> VoIPController::GetStreamByType(int type, bool outgoing){ shared_ptr<Stream> s; for(shared_ptr<Stream>& ss:(outgoing ? outgoingStreams : incomingStreams)){ if(ss->type==type) return ss; } return s; } CellularCarrierInfo VoIPController::GetCarrierInfo(){ #if defined(__APPLE__) && TARGET_OS_IOS return DarwinSpecific::GetCarrierInfo(); #elif defined(__ANDROID__) CellularCarrierInfo carrier; jni::DoWithJNI([&carrier](JNIEnv* env){ jmethodID getCarrierInfoMethod=env->GetStaticMethodID(jniUtilitiesClass, "getCarrierInfo", "()[Ljava/lang/String;"); jobjectArray jinfo=(jobjectArray) env->CallStaticObjectMethod(jniUtilitiesClass, getCarrierInfoMethod); if(jinfo && env->GetArrayLength(jinfo)==4){ carrier.name=jni::JavaStringToStdString(env, (jstring)env->GetObjectArrayElement(jinfo, 0)); carrier.countryCode=jni::JavaStringToStdString(env, (jstring)env->GetObjectArrayElement(jinfo, 1)); carrier.mcc=jni::JavaStringToStdString(env, (jstring)env->GetObjectArrayElement(jinfo, 2)); carrier.mnc=jni::JavaStringToStdString(env, (jstring)env->GetObjectArrayElement(jinfo, 3)); }else{ LOGW("Failed to get carrier info"); } }); return carrier; #else return CellularCarrierInfo(); #endif } #pragma mark - Audio I/O void VoIPController::AudioInputCallback(unsigned char* data, size_t length, unsigned char* secondaryData, size_t secondaryLength, void* param){ ((VoIPController*)param)->HandleAudioInput(data, length, secondaryData, secondaryLength); } void VoIPController::HandleAudioInput(unsigned char *data, size_t len, unsigned char* secondaryData, size_t secondaryLen){ if(stopping) return; unsentStreamPacketsHistory.Add(static_cast<unsigned int>(unsentStreamPackets)); if(unsentStreamPacketsHistory.Average()>=maxUnsentStreamPackets && !videoSource){ LOGW("Resetting stalled send queue"); sendQueue.clear(); unsentStreamPacketsHistory.Reset(); unsentStreamPackets=0; } if(waitingForAcks || dontSendPackets>0 || ((unsigned int)unsentStreamPackets>=maxUnsentStreamPackets /*&& endpoints[currentEndpoint].type==Endpoint::Type::TCP_RELAY*/)){ LOGV("waiting for queue, dropping outgoing audio packet, %d %d %d [%d]", (unsigned int)unsentStreamPackets, waitingForAcks, dontSendPackets, maxUnsentStreamPackets); return; } //LOGV("Audio packet size %u", (unsigned int)len); if(!receivedInitAck) return; BufferOutputStream pkt(1500); bool hasExtraFEC=peerVersion>=7 && secondaryData && secondaryLen && shittyInternetMode; unsigned char flags=(unsigned char) (len>255 || hasExtraFEC ? STREAM_DATA_FLAG_LEN16 : 0); pkt.WriteByte((unsigned char) (1 | flags)); // streamID + flags if(len>255 || hasExtraFEC){ int16_t lenAndFlags=static_cast<int16_t>(len); if(hasExtraFEC) lenAndFlags|=STREAM_DATA_XFLAG_EXTRA_FEC; pkt.WriteInt16(lenAndFlags); }else{ pkt.WriteByte((unsigned char) len); } pkt.WriteInt32(audioTimestampOut); pkt.WriteBytes(data, len); if(hasExtraFEC){ Buffer ecBuf(secondaryLen); ecBuf.CopyFrom(secondaryData, 0, secondaryLen); ecAudioPackets.push_back(move(ecBuf)); while(ecAudioPackets.size()>4) ecAudioPackets.erase(ecAudioPackets.begin()); pkt.WriteByte((unsigned char)MIN(ecAudioPackets.size(), extraEcLevel)); for(vector<Buffer>::iterator ecData=ecAudioPackets.begin()+MAX(0, (int)ecAudioPackets.size()-extraEcLevel);ecData!=ecAudioPackets.end();++ecData){ pkt.WriteByte((unsigned char)ecData->Length()); pkt.WriteBytes(*ecData); } } unsentStreamPackets++; size_t pktLength = pkt.GetLength(); PendingOutgoingPacket p{ /*.seq=*/GenerateOutSeq(), /*.type=*/PKT_STREAM_DATA, /*.len=*/pktLength, /*.data=*/Buffer(move(pkt)), /*.endpoint=*/0, }; conctl->PacketSent(p.seq, p.len); SendOrEnqueuePacket(move(p)); if(peerVersion<7 && secondaryData && secondaryLen && shittyInternetMode){ Buffer ecBuf(secondaryLen); ecBuf.CopyFrom(secondaryData, 0, secondaryLen); ecAudioPackets.push_back(move(ecBuf)); while(ecAudioPackets.size()>4) ecAudioPackets.erase(ecAudioPackets.begin()); pkt=BufferOutputStream(1500); pkt.WriteByte(outgoingStreams[0]->id); pkt.WriteInt32(audioTimestampOut); pkt.WriteByte((unsigned char)MIN(ecAudioPackets.size(), extraEcLevel)); for(vector<Buffer>::iterator ecData=ecAudioPackets.begin()+MAX(0, (int)ecAudioPackets.size()-extraEcLevel);ecData!=ecAudioPackets.end();++ecData){ pkt.WriteByte((unsigned char)ecData->Length()); pkt.WriteBytes(*ecData); } pktLength = pkt.GetLength(); PendingOutgoingPacket p{ GenerateOutSeq(), PKT_STREAM_EC, pktLength, Buffer(move(pkt)), 0 }; SendOrEnqueuePacket(move(p)); } audioTimestampOut+=outgoingStreams[0]->frameDuration; #if defined(TGVOIP_USE_CALLBACK_AUDIO_IO) if (audioPreprocDataCallback && preprocDecoder) { int size=opus_decode(preprocDecoder, data, len, preprocBuffer, 4096, 0); audioPreprocDataCallback(preprocBuffer, size); } #endif } void VoIPController::InitializeAudio(){ double t=GetCurrentTime(); shared_ptr<Stream> outgoingAudioStream=GetStreamByType(STREAM_TYPE_AUDIO, true); LOGI("before create audio io"); audioIO=audio::AudioIO::Create(currentAudioInput, currentAudioOutput); audioInput=audioIO->GetInput(); audioOutput=audioIO->GetOutput(); #ifdef __ANDROID__ audio::AudioInputAndroid* androidInput=dynamic_cast<audio::AudioInputAndroid*>(audioInput); if(androidInput){ unsigned int effects=androidInput->GetEnabledEffects(); if(!(effects & audio::AudioInputAndroid::EFFECT_AEC)){ config.enableAEC=true; LOGI("Forcing software AEC because built-in is not good"); } if(!(effects & audio::AudioInputAndroid::EFFECT_NS)){ config.enableNS=true; LOGI("Forcing software NS because built-in is not good"); } } #elif defined(__APPLE__) && TARGET_OS_OSX SetAudioOutputDuckingEnabled(macAudioDuckingEnabled); #endif LOGI("AEC: %d NS: %d AGC: %d", config.enableAEC, config.enableNS, config.enableAGC); echoCanceller=new EchoCanceller(config.enableAEC, config.enableNS, config.enableAGC); encoder=new OpusEncoder(audioInput, true); encoder->SetCallback(AudioInputCallback, this); encoder->SetOutputFrameDuration(outgoingAudioStream->frameDuration); encoder->SetEchoCanceller(echoCanceller); encoder->SetSecondaryEncoderEnabled(false); if(config.enableVolumeControl){ encoder->AddAudioEffect(&inputVolume); } #if defined(TGVOIP_USE_CALLBACK_AUDIO_IO) dynamic_cast<audio::AudioInputCallback*>(audioInput)->SetDataCallback(audioInputDataCallback); dynamic_cast<audio::AudioOutputCallback*>(audioOutput)->SetDataCallback(audioOutputDataCallback); #endif if(!audioOutput->IsInitialized()){ LOGE("Error initializing audio playback"); lastError=ERROR_AUDIO_IO; SetState(STATE_FAILED); return; } UpdateAudioBitrateLimit(); LOGI("Audio initialization took %f seconds", GetCurrentTime()-t); } void VoIPController::StartAudio(){ OnAudioOutputReady(); encoder->Start(); if(!micMuted){ audioInput->Start(); if(!audioInput->IsInitialized()){ LOGE("Error initializing audio capture"); lastError=ERROR_AUDIO_IO; SetState(STATE_FAILED); return; } } } void VoIPController::OnAudioOutputReady(){ LOGI("Audio I/O ready"); shared_ptr<Stream>& stm=incomingStreams[0]; stm->decoder=make_shared<OpusDecoder>(audioOutput, true, peerVersion>=6); stm->decoder->SetEchoCanceller(echoCanceller); if(config.enableVolumeControl){ stm->decoder->AddAudioEffect(&outputVolume); } stm->decoder->SetJitterBuffer(stm->jitterBuffer); stm->decoder->SetFrameDuration(stm->frameDuration); stm->decoder->Start(); } void VoIPController::UpdateAudioOutputState(){ bool areAnyAudioStreamsEnabled=false; for(vector<shared_ptr<Stream>>::iterator s=incomingStreams.begin();s!=incomingStreams.end();++s){ if((*s)->type==STREAM_TYPE_AUDIO && (*s)->enabled) areAnyAudioStreamsEnabled=true; } if(audioOutput){ LOGV("New audio output state: %d", areAnyAudioStreamsEnabled); if(audioOutput->IsPlaying()!=areAnyAudioStreamsEnabled){ if(areAnyAudioStreamsEnabled) audioOutput->Start(); else audioOutput->Stop(); } } } #pragma mark - Bandwidth management void VoIPController::UpdateAudioBitrateLimit(){ if(encoder){ if(dataSavingMode || dataSavingRequestedByPeer){ maxBitrate=maxAudioBitrateSaving; encoder->SetBitrate(initAudioBitrateSaving); }else if(networkType==NET_TYPE_GPRS){ maxBitrate=maxAudioBitrateGPRS; encoder->SetBitrate(initAudioBitrateGPRS); }else if(networkType==NET_TYPE_EDGE){ maxBitrate=maxAudioBitrateEDGE; encoder->SetBitrate(initAudioBitrateEDGE); }else{ maxBitrate=maxAudioBitrate; encoder->SetBitrate(initAudioBitrate); } encoder->SetVadMode(dataSavingMode || dataSavingRequestedByPeer); if(echoCanceller) echoCanceller->SetVoiceDetectionEnabled(dataSavingMode || dataSavingRequestedByPeer); } } void VoIPController::UpdateDataSavingState(){ if(config.dataSaving==DATA_SAVING_ALWAYS){ dataSavingMode=true; }else if(config.dataSaving==DATA_SAVING_MOBILE){ dataSavingMode=networkType==NET_TYPE_GPRS || networkType==NET_TYPE_EDGE || networkType==NET_TYPE_3G || networkType==NET_TYPE_HSPA || networkType==NET_TYPE_LTE || networkType==NET_TYPE_OTHER_MOBILE; }else{ dataSavingMode=false; } LOGI("update data saving mode, config %d, enabled %d, reqd by peer %d", config.dataSaving, dataSavingMode, dataSavingRequestedByPeer); } #pragma mark - Networking & crypto uint32_t VoIPController::GenerateOutSeq(){ return seq++; } void VoIPController::WritePacketHeader(uint32_t pseq, BufferOutputStream *s, unsigned char type, uint32_t length){ uint32_t acks=0; int i; for(i=0;i<32;i++){ if(recvPacketTimes[i]>0) acks|=1; if(i<31) acks<<=1; } if(peerVersion>=8 || (!peerVersion && connectionMaxLayer>=92)){ s->WriteByte(type); s->WriteInt32(lastRemoteSeq); s->WriteInt32(pseq); s->WriteInt32(acks); MutexGuard m(queuedPacketsMutex); unsigned char flags; if(currentExtras.empty()){ flags=0; }else{ flags=XPFLAG_HAS_EXTRA; } shared_ptr<Stream> videoStream=GetStreamByType(STREAM_TYPE_VIDEO, false); if(peerVersion>=9 && videoStream && videoStream->enabled) flags |= XPFLAG_HAS_RECV_TS; s->WriteByte(flags); if(!currentExtras.empty()){ s->WriteByte(static_cast<unsigned char>(currentExtras.size())); for(vector<UnacknowledgedExtraData>::iterator x=currentExtras.begin(); x!=currentExtras.end(); ++x){ LOGV("Writing extra into header: type %u, length %d", x->type, int(x->data.Length())); assert(x->data.Length()<=254); s->WriteByte(static_cast<unsigned char>(x->data.Length()+1)); s->WriteByte(x->type); s->WriteBytes(*x->data, x->data.Length()); if(x->firstContainingSeq==0) x->firstContainingSeq=pseq; } } if(peerVersion>=9 && videoStream && videoStream->enabled){ s->WriteInt32((uint32_t)((lastRecvPacketTime-connectionInitTime)*1000.0)); } }else{ if(state==STATE_WAIT_INIT || state==STATE_WAIT_INIT_ACK){ s->WriteInt32(TLID_DECRYPTED_AUDIO_BLOCK); int64_t randomID; crypto.rand_bytes((uint8_t *) &randomID, 8); s->WriteInt64(randomID); unsigned char randBytes[7]; crypto.rand_bytes(randBytes, 7); s->WriteByte(7); s->WriteBytes(randBytes, 7); uint32_t pflags=PFLAG_HAS_RECENT_RECV | PFLAG_HAS_SEQ; if(length>0) pflags|=PFLAG_HAS_DATA; if(state==STATE_WAIT_INIT || state==STATE_WAIT_INIT_ACK){ pflags|=PFLAG_HAS_CALL_ID | PFLAG_HAS_PROTO; } pflags|=((uint32_t) type) << 24; s->WriteInt32(pflags); if(pflags & PFLAG_HAS_CALL_ID){ s->WriteBytes(callID, 16); } s->WriteInt32(lastRemoteSeq); s->WriteInt32(pseq); s->WriteInt32(acks); if(pflags & PFLAG_HAS_PROTO){ s->WriteInt32(PROTOCOL_NAME); } if(length>0){ if(length<=253){ s->WriteByte((unsigned char) length); }else{ s->WriteByte(254); s->WriteByte((unsigned char) (length & 0xFF)); s->WriteByte((unsigned char) ((length >> 8) & 0xFF)); s->WriteByte((unsigned char) ((length >> 16) & 0xFF)); } } }else{ s->WriteInt32(TLID_SIMPLE_AUDIO_BLOCK); int64_t randomID; crypto.rand_bytes((uint8_t *) &randomID, 8); s->WriteInt64(randomID); unsigned char randBytes[7]; crypto.rand_bytes(randBytes, 7); s->WriteByte(7); s->WriteBytes(randBytes, 7); uint32_t lenWithHeader=length+13; if(lenWithHeader>0){ if(lenWithHeader<=253){ s->WriteByte((unsigned char) lenWithHeader); }else{ s->WriteByte(254); s->WriteByte((unsigned char) (lenWithHeader & 0xFF)); s->WriteByte((unsigned char) ((lenWithHeader >> 8) & 0xFF)); s->WriteByte((unsigned char) ((lenWithHeader >> 16) & 0xFF)); } } s->WriteByte(type); s->WriteInt32(lastRemoteSeq); s->WriteInt32(pseq); s->WriteInt32(acks); if(peerVersion>=6){ MutexGuard m(queuedPacketsMutex); if(currentExtras.empty()){ s->WriteByte(0); }else{ s->WriteByte(XPFLAG_HAS_EXTRA); s->WriteByte(static_cast<unsigned char>(currentExtras.size())); for(vector<UnacknowledgedExtraData>::iterator x=currentExtras.begin(); x!=currentExtras.end(); ++x){ LOGV("Writing extra into header: type %u, length %d", x->type, int(x->data.Length())); assert(x->data.Length()<=254); s->WriteByte(static_cast<unsigned char>(x->data.Length()+1)); s->WriteByte(x->type); s->WriteBytes(*x->data, x->data.Length()); if(x->firstContainingSeq==0) x->firstContainingSeq=pseq; } } } } } MutexGuard m(queuedPacketsMutex); recentOutgoingPackets.push_back(RecentOutgoingPacket{ pseq, 0, GetCurrentTime(), 0, type, length }); while(recentOutgoingPackets.size()>MAX_RECENT_PACKETS){ recentOutgoingPackets.erase(recentOutgoingPackets.begin()); } lastSentSeq=pseq; //LOGI("packet header size %d", s->GetLength()); } void VoIPController::SendInit(){ { MutexGuard m(endpointsMutex); uint32_t initSeq=GenerateOutSeq(); for(pair<const int64_t, Endpoint>& _e:endpoints){ Endpoint& e=_e.second; if(e.type==Endpoint::Type::TCP_RELAY && !useTCP) continue; BufferOutputStream out(1024); out.WriteInt32(PROTOCOL_VERSION); out.WriteInt32(MIN_PROTOCOL_VERSION); uint32_t flags=0; if(config.enableCallUpgrade) flags|=INIT_FLAG_GROUP_CALLS_SUPPORTED; if(config.enableVideoReceive) flags|=INIT_FLAG_VIDEO_RECV_SUPPORTED; if(config.enableVideoSend) flags|=INIT_FLAG_VIDEO_SEND_SUPPORTED; if(dataSavingMode) flags|=INIT_FLAG_DATA_SAVING_ENABLED; out.WriteInt32(flags); if(connectionMaxLayer<74){ out.WriteByte(2); // audio codecs count out.WriteByte(CODEC_OPUS_OLD); out.WriteByte(0); out.WriteByte(0); out.WriteByte(0); out.WriteInt32(CODEC_OPUS); out.WriteByte(0); // video codecs count (decode) out.WriteByte(0); // video codecs count (encode) }else{ out.WriteByte(1); out.WriteInt32(CODEC_OPUS); vector<uint32_t> decoders=config.enableVideoReceive ? video::VideoRenderer::GetAvailableDecoders() : vector<uint32_t>(); vector<uint32_t> encoders=config.enableVideoSend ? video::VideoSource::GetAvailableEncoders() : vector<uint32_t>(); out.WriteByte((unsigned char)decoders.size()); for(uint32_t id:decoders){ out.WriteInt32(id); } if(connectionMaxLayer>=92) out.WriteByte((unsigned char)video::VideoRenderer::GetMaximumResolution()); else out.WriteByte(0); /*out.WriteByte((unsigned char)encoders.size()); for(uint32_t id:encoders){ out.WriteInt32(id); }*/ } size_t outLength = out.GetLength(); SendOrEnqueuePacket(PendingOutgoingPacket{ /*.seq=*/initSeq, /*.type=*/PKT_INIT, /*.len=*/outLength, /*.data=*/Buffer(move(out)), /*.endpoint=*/e.id }); } } if(state==STATE_WAIT_INIT) SetState(STATE_WAIT_INIT_ACK); messageThread.Post([this]{ if(state==STATE_WAIT_INIT_ACK){ SendInit(); } }, 0.5); } void VoIPController::InitUDPProxy(){ if(realUdpSocket!=udpSocket){ udpSocket->Close(); delete udpSocket; udpSocket=realUdpSocket; } char sbuf[128]; snprintf(sbuf, sizeof(sbuf), "%s:%u", proxyAddress.c_str(), proxyPort); string proxyHostPort(sbuf); if(proxyHostPort==lastTestedProxyServer && !proxySupportsUDP){ LOGI("Proxy does not support UDP - using UDP directly instead"); ResetUdpAvailability(); return; } NetworkSocket* tcp=NetworkSocket::Create(PROTO_TCP); tcp->Connect(resolvedProxyAddress, proxyPort); vector<NetworkSocket*> writeSockets; vector<NetworkSocket*> readSockets; vector<NetworkSocket*> errorSockets; while(!tcp->IsFailed() && !tcp->IsReadyToSend()){ writeSockets.push_back(tcp); if(!NetworkSocket::Select(readSockets, writeSockets, errorSockets, selectCanceller)){ LOGW("Select canceled while waiting for proxy control socket to connect"); delete tcp; return; } } LOGV("UDP proxy control socket ready to send"); NetworkSocketSOCKS5Proxy* udpProxy=new NetworkSocketSOCKS5Proxy(tcp, realUdpSocket, proxyUsername, proxyPassword); udpProxy->OnReadyToSend(); writeSockets.clear(); while(!udpProxy->IsFailed() && !tcp->IsFailed() && !udpProxy->IsReadyToSend()){ readSockets.clear(); errorSockets.clear(); readSockets.push_back(tcp); errorSockets.push_back(tcp); if(!NetworkSocket::Select(readSockets, writeSockets, errorSockets, selectCanceller)){ LOGW("Select canceled while waiting for UDP proxy to initialize"); delete udpProxy; return; } if(!readSockets.empty()) udpProxy->OnReadyToReceive(); } LOGV("UDP proxy initialized"); if(udpProxy->IsFailed()){ udpProxy->Close(); delete udpProxy; proxySupportsUDP=false; }else{ udpSocket=udpProxy; } ResetUdpAvailability(); } void VoIPController::RunRecvThread(){ LOGI("Receive thread starting"); Buffer buffer(1500); NetworkPacket packet={0}; if(proxyProtocol==PROXY_SOCKS5){ resolvedProxyAddress=NetworkSocket::ResolveDomainName(proxyAddress); if(!resolvedProxyAddress){ LOGW("Error resolving proxy address %s", proxyAddress.c_str()); SetState(STATE_FAILED); return; } }else{ udpConnectivityState=UDP_PING_PENDING; udpPingTimeoutID=messageThread.Post(std::bind(&VoIPController::SendUdpPings, this), 0.0, 0.5); } while(runReceiver){ if(proxyProtocol==PROXY_SOCKS5 && needReInitUdpProxy){ InitUDPProxy(); needReInitUdpProxy=false; } packet.data=*buffer; packet.length=buffer.Length(); vector<NetworkSocket*> readSockets; vector<NetworkSocket*> errorSockets; vector<NetworkSocket*> writeSockets; readSockets.push_back(udpSocket); errorSockets.push_back(realUdpSocket); if(!realUdpSocket->IsReadyToSend()) writeSockets.push_back(realUdpSocket); { MutexGuard m(endpointsMutex); for(pair<const int64_t, Endpoint>& _e:endpoints){ const Endpoint& e=_e.second; if(e.type==Endpoint::Type::TCP_RELAY){ if(e.socket){ readSockets.push_back(e.socket); errorSockets.push_back(e.socket); if(!e.socket->IsReadyToSend()){ NetworkSocketSOCKS5Proxy* proxy=dynamic_cast<NetworkSocketSOCKS5Proxy*>(e.socket); if(!proxy || proxy->NeedSelectForSending()) writeSockets.push_back(e.socket); } } } } } { MutexGuard m(socketSelectMutex); bool selRes=NetworkSocket::Select(readSockets, writeSockets, errorSockets, selectCanceller); if(!selRes){ LOGV("Select canceled"); continue; } } if(!runReceiver) return; if(!errorSockets.empty()){ if(find(errorSockets.begin(), errorSockets.end(), realUdpSocket)!=errorSockets.end()){ LOGW("UDP socket failed"); SetState(STATE_FAILED); return; } MutexGuard m(endpointsMutex); for(NetworkSocket*& socket:errorSockets){ for(pair<const int64_t, Endpoint>& _e:endpoints){ Endpoint& e=_e.second; if(e.socket && e.socket==socket){ e.socket->Close(); delete e.socket; e.socket=NULL; LOGI("Closing failed TCP socket for %s:%u", e.GetAddress().ToString().c_str(), e.port); } } } continue; } for(NetworkSocket*& socket:readSockets){ //while(packet.length){ packet.length=1500; socket->Receive(&packet); if(!packet.address){ LOGE("Packet has null address. This shouldn't happen."); continue; } size_t len=packet.length; if(!len){ LOGE("Packet has zero length."); continue; } //LOGV("Received %d bytes from %s:%d at %.5lf", len, packet.address->ToString().c_str(), packet.port, GetCurrentTime()); int64_t srcEndpointID=0; IPv4Address *src4=dynamic_cast<IPv4Address *>(packet.address); if(src4){ MutexGuard m(endpointsMutex); for(pair<const int64_t, Endpoint>& _e:endpoints){ const Endpoint& e=_e.second; if(e.address==*src4 && e.port==packet.port){ if((e.type!=Endpoint::Type::TCP_RELAY && packet.protocol==PROTO_UDP) || (e.type==Endpoint::Type::TCP_RELAY && packet.protocol==PROTO_TCP)){ srcEndpointID=e.id; break; } } } if(!srcEndpointID && packet.protocol==PROTO_UDP){ try{ Endpoint &p2p=GetEndpointByType(Endpoint::Type::UDP_P2P_INET); if(p2p.rtts[0]==0.0 && p2p.address.PrefixMatches(24, *packet.address)){ LOGD("Packet source matches p2p endpoint partially: %s:%u", packet.address->ToString().c_str(), packet.port); srcEndpointID=p2p.id; } }catch(out_of_range& ex){} } }else{ IPv6Address *src6=dynamic_cast<IPv6Address *>(packet.address); if(src6){ MutexGuard m(endpointsMutex); for(pair<const int64_t, Endpoint> &_e:endpoints){ const Endpoint& e=_e.second; if(e.v6address==*src6 && e.port==packet.port && e.IsIPv6Only()){ if((e.type!=Endpoint::Type::TCP_RELAY && packet.protocol==PROTO_UDP) || (e.type==Endpoint::Type::TCP_RELAY && packet.protocol==PROTO_TCP)){ srcEndpointID=e.id; break; } } } } } if(!srcEndpointID){ LOGW("Received a packet from unknown source %s:%u", packet.address->ToString().c_str(), packet.port); continue; } if(len<=0){ //LOGW("error receiving: %d / %s", errno, strerror(errno)); continue; } if(IS_MOBILE_NETWORK(networkType)) stats.bytesRecvdMobile+=(uint64_t) len; else stats.bytesRecvdWifi+=(uint64_t) len; try{ ProcessIncomingPacket(packet, endpoints.at(srcEndpointID)); }catch(out_of_range& x){ LOGW("Error parsing packet: %s", x.what()); } //} } for(vector<PendingOutgoingPacket>::iterator opkt=sendQueue.begin();opkt!=sendQueue.end();){ Endpoint* endpoint=GetEndpointForPacket(*opkt); if(!endpoint){ opkt=sendQueue.erase(opkt); LOGE("SendQueue contained packet for nonexistent endpoint"); continue; } bool canSend; if(endpoint->type!=Endpoint::Type::TCP_RELAY) canSend=realUdpSocket->IsReadyToSend(); else canSend=endpoint->socket && endpoint->socket->IsReadyToSend(); if(canSend){ LOGI("Sending queued packet"); SendOrEnqueuePacket(move(*opkt), false); opkt=sendQueue.erase(opkt); }else{ ++opkt; } } } LOGI("=== recv thread exiting ==="); } bool VoIPController::WasOutgoingPacketAcknowledged(uint32_t seq){ RecentOutgoingPacket* pkt=GetRecentOutgoingPacket(seq); if(!pkt) return false; return pkt->ackTime!=0.0; } VoIPController::RecentOutgoingPacket *VoIPController::GetRecentOutgoingPacket(uint32_t seq){ for(RecentOutgoingPacket& opkt:recentOutgoingPackets){ if(opkt.seq==seq){ return &opkt; } } return NULL; } void VoIPController::ProcessIncomingPacket(NetworkPacket &packet, Endpoint& srcEndpoint){ unsigned char *buffer=packet.data; size_t len=packet.length; BufferInputStream in(buffer, (size_t) len); bool hasPeerTag=false; if(peerVersion<9 || srcEndpoint.type==Endpoint::Type::UDP_RELAY || srcEndpoint.type==Endpoint::Type::TCP_RELAY){ if(memcmp(buffer, srcEndpoint.type==Endpoint::Type::UDP_RELAY || srcEndpoint.type==Endpoint::Type::TCP_RELAY ? (void *) srcEndpoint.peerTag : (void *) callID, 16)!=0){ LOGW("Received packet has wrong peerTag"); return; } in.Seek(16); hasPeerTag=true; } if(in.Remaining()>=16 && (srcEndpoint.type==Endpoint::Type::UDP_RELAY || srcEndpoint.type==Endpoint::Type::TCP_RELAY) && *reinterpret_cast<uint64_t *>(buffer+16)==0xFFFFFFFFFFFFFFFFLL && *reinterpret_cast<uint32_t *>(buffer+24)==0xFFFFFFFF){ // relay special request response in.Seek(16+12); uint32_t tlid=(uint32_t) in.ReadInt32(); if(tlid==TLID_UDP_REFLECTOR_SELF_INFO){ if(srcEndpoint.type==Endpoint::Type::UDP_RELAY /*&& udpConnectivityState==UDP_PING_SENT*/ && in.Remaining()>=32){ int32_t date=in.ReadInt32(); int64_t queryID=in.ReadInt64(); unsigned char myIP[16]; in.ReadBytes(myIP, 16); int32_t myPort=in.ReadInt32(); //udpConnectivityState=UDP_AVAILABLE; LOGV("Received UDP ping reply from %s:%d: date=%d, queryID=%ld, my IP=%s, my port=%d", srcEndpoint.address.ToString().c_str(), srcEndpoint.port, date, (long int) queryID, IPv4Address(*reinterpret_cast<uint32_t *>(myIP+12)).ToString().c_str(), myPort); srcEndpoint.udpPongCount++; if(srcEndpoint.IsIPv6Only() && !didSendIPv6Endpoint){ IPv6Address realAddr(myIP); if(realAddr==myIPv6){ LOGI("Public IPv6 matches local address"); useIPv6=true; if(allowP2p){ didSendIPv6Endpoint=true; BufferOutputStream o(18); o.WriteBytes(myIP, 16); o.WriteInt16(udpSocket->GetLocalPort()); Buffer b(move(o)); SendExtra(b, EXTRA_TYPE_IPV6_ENDPOINT); } } } } }else if(tlid==TLID_UDP_REFLECTOR_PEER_INFO){ if(in.Remaining()>=16){ MutexGuard _m(endpointsMutex); uint32_t myAddr=(uint32_t) in.ReadInt32(); uint32_t myPort=(uint32_t) in.ReadInt32(); uint32_t peerAddr=(uint32_t) in.ReadInt32(); uint32_t peerPort=(uint32_t) in.ReadInt32(); constexpr int64_t p2pID=(int64_t) (FOURCC('P', '2', 'P', '4')) << 32; constexpr int64_t lanID=(int64_t) (FOURCC('L', 'A', 'N', '4')) << 32; if(currentEndpoint==p2pID || currentEndpoint==lanID) currentEndpoint=preferredRelay; endpoints.erase(lanID); IPv4Address _peerAddr(peerAddr); IPv6Address emptyV6(string("::0")); unsigned char peerTag[16]; LOGW("Received reflector peer info, my=%s:%u, peer=%s:%u", IPv4Address(myAddr).ToString().c_str(), myPort, IPv4Address(peerAddr).ToString().c_str(), peerPort); if(waitingForRelayPeerInfo){ Endpoint p2p(p2pID, (uint16_t) peerPort, _peerAddr, emptyV6, Endpoint::Type::UDP_P2P_INET, peerTag); endpoints[p2pID]=p2p; if(myAddr==peerAddr){ LOGW("Detected LAN"); IPv4Address lanAddr(0); udpSocket->GetLocalInterfaceInfo(&lanAddr, NULL); BufferOutputStream pkt(8); pkt.WriteInt32(lanAddr.GetAddress()); pkt.WriteInt32(udpSocket->GetLocalPort()); if(peerVersion<6){ SendPacketReliably(PKT_LAN_ENDPOINT, pkt.GetBuffer(), pkt.GetLength(), 0.5, 10); }else{ Buffer buf(move(pkt)); SendExtra(buf, EXTRA_TYPE_LAN_ENDPOINT); } } waitingForRelayPeerInfo=false; } } }else{ LOGV("Received relay response with unknown tl id: 0x%08X", tlid); } return; } if(in.Remaining()<40){ LOGV("Received packet is too small"); return; } bool retryWith2=false; size_t innerLen=0; bool shortFormat=peerVersion>=8 || (!peerVersion && connectionMaxLayer>=92); if(!useMTProto2){ unsigned char fingerprint[8], msgHash[16]; in.ReadBytes(fingerprint, 8); in.ReadBytes(msgHash, 16); unsigned char key[32], iv[32]; KDF(msgHash, isOutgoing ? 8 : 0, key, iv); unsigned char aesOut[MSC_STACK_FALLBACK(in.Remaining(), 1500)]; if(in.Remaining()>sizeof(aesOut)) return; crypto.aes_ige_decrypt((unsigned char *) buffer+in.GetOffset(), aesOut, in.Remaining(), key, iv); BufferInputStream _in(aesOut, in.Remaining()); unsigned char sha[SHA1_LENGTH]; uint32_t _len=(uint32_t) _in.ReadInt32(); if(_len>_in.Remaining()) _len=(uint32_t) _in.Remaining(); crypto.sha1((uint8_t *) (aesOut), (size_t) (_len+4), sha); if(memcmp(msgHash, sha+(SHA1_LENGTH-16), 16)!=0){ LOGW("Received packet has wrong hash after decryption"); if(state==STATE_WAIT_INIT || state==STATE_WAIT_INIT_ACK) retryWith2=true; else return; }else{ memcpy(buffer+in.GetOffset(), aesOut, in.Remaining()); in.ReadInt32(); } } if(useMTProto2 || retryWith2){ if(hasPeerTag) in.Seek(16); // peer tag unsigned char fingerprint[8], msgKey[16]; if(!shortFormat){ in.ReadBytes(fingerprint, 8); if(memcmp(fingerprint, keyFingerprint, 8)!=0){ LOGW("Received packet has wrong key fingerprint"); return; } } in.ReadBytes(msgKey, 16); unsigned char decrypted[1500]; unsigned char aesKey[32], aesIv[32]; KDF2(msgKey, isOutgoing ? 8 : 0, aesKey, aesIv); size_t decryptedLen=in.Remaining(); if(decryptedLen>sizeof(decrypted)) return; if(decryptedLen%16!=0){ LOGW("wrong decrypted length"); return; } crypto.aes_ige_decrypt(packet.data+in.GetOffset(), decrypted, decryptedLen, aesKey, aesIv); in=BufferInputStream(decrypted, decryptedLen); //LOGD("received packet length: %d", in.ReadInt32()); size_t sizeSize=shortFormat ? 0 : 4; BufferOutputStream buf(decryptedLen+32); size_t x=isOutgoing ? 8 : 0; buf.WriteBytes(encryptionKey+88+x, 32); buf.WriteBytes(decrypted+sizeSize, decryptedLen-sizeSize); unsigned char msgKeyLarge[32]; crypto.sha256(buf.GetBuffer(), buf.GetLength(), msgKeyLarge); if(memcmp(msgKey, msgKeyLarge+8, 16)!=0){ LOGW("Received packet has wrong hash"); return; } innerLen=(uint32_t) (shortFormat ? in.ReadInt16() : in.ReadInt32()); if(innerLen>decryptedLen-sizeSize){ LOGW("Received packet has wrong inner length (%d with total of %u)", (int) innerLen, (unsigned int) decryptedLen); return; } if(decryptedLen-innerLen<(shortFormat ? 16 : 12)){ LOGW("Received packet has too little padding (%u)", (unsigned int) (decryptedLen-innerLen)); return; } memcpy(buffer, decrypted+(shortFormat ? 2 : 4), innerLen); in=BufferInputStream(buffer, (size_t) innerLen); if(retryWith2){ LOGD("Successfully decrypted packet in MTProto2.0 fallback, upgrading"); useMTProto2=true; } } lastRecvPacketTime=GetCurrentTime(); if(state==STATE_RECONNECTING){ LOGI("Received a valid packet while reconnecting - setting state to established"); SetState(STATE_ESTABLISHED); } if(srcEndpoint.type==Endpoint::Type::UDP_P2P_INET && !srcEndpoint.IsIPv6Only()){ if(srcEndpoint.port!=packet.port || srcEndpoint.address!=*packet.address){ IPv4Address *v4=dynamic_cast<IPv4Address *>(packet.address); if(v4){ LOGI("Incoming packet was decrypted successfully, changing P2P endpoint to %s:%u", packet.address->ToString().c_str(), packet.port); srcEndpoint.address=*v4; srcEndpoint.port=packet.port; } } } /*decryptedAudioBlock random_id:long random_bytes:string flags:# voice_call_id:flags.2?int128 in_seq_no:flags.4?int out_seq_no:flags.4?int * recent_received_mask:flags.5?int proto:flags.3?int extra:flags.1?string raw_data:flags.0?string = DecryptedAudioBlock simpleAudioBlock random_id:long random_bytes:string raw_data:string = DecryptedAudioBlock; */ uint32_t ackId, pseq, acks; unsigned char type, pflags; size_t packetInnerLen=0; if(shortFormat){ type=in.ReadByte(); ackId=(uint32_t) in.ReadInt32(); pseq=(uint32_t) in.ReadInt32(); acks=(uint32_t) in.ReadInt32(); pflags=in.ReadByte(); packetInnerLen=innerLen-14; }else{ uint32_t tlid=(uint32_t) in.ReadInt32(); if(tlid==TLID_DECRYPTED_AUDIO_BLOCK){ in.ReadInt64(); // random id uint32_t randLen=(uint32_t) in.ReadTlLength(); in.Seek(in.GetOffset()+randLen+pad4(randLen)); uint32_t flags=(uint32_t) in.ReadInt32(); type=(unsigned char) ((flags >> 24) & 0xFF); if(!(flags & PFLAG_HAS_SEQ && flags & PFLAG_HAS_RECENT_RECV)){ LOGW("Received packet doesn't have PFLAG_HAS_SEQ, PFLAG_HAS_RECENT_RECV, or both"); return; } if(flags & PFLAG_HAS_CALL_ID){ unsigned char pktCallID[16]; in.ReadBytes(pktCallID, 16); if(memcmp(pktCallID, callID, 16)!=0){ LOGW("Received packet has wrong call id"); lastError=ERROR_UNKNOWN; SetState(STATE_FAILED); return; } } ackId=(uint32_t) in.ReadInt32(); pseq=(uint32_t) in.ReadInt32(); acks=(uint32_t) in.ReadInt32(); if(flags & PFLAG_HAS_PROTO){ uint32_t proto=(uint32_t) in.ReadInt32(); if(proto!=PROTOCOL_NAME){ LOGW("Received packet uses wrong protocol"); lastError=ERROR_INCOMPATIBLE; SetState(STATE_FAILED); return; } } if(flags & PFLAG_HAS_EXTRA){ uint32_t extraLen=(uint32_t) in.ReadTlLength(); in.Seek(in.GetOffset()+extraLen+pad4(extraLen)); } if(flags & PFLAG_HAS_DATA){ packetInnerLen=in.ReadTlLength(); } pflags=0; }else if(tlid==TLID_SIMPLE_AUDIO_BLOCK){ in.ReadInt64(); // random id uint32_t randLen=(uint32_t) in.ReadTlLength(); in.Seek(in.GetOffset()+randLen+pad4(randLen)); packetInnerLen=in.ReadTlLength(); type=in.ReadByte(); ackId=(uint32_t) in.ReadInt32(); pseq=(uint32_t) in.ReadInt32(); acks=(uint32_t) in.ReadInt32(); if(peerVersion>=6) pflags=in.ReadByte(); else pflags=0; }else{ LOGW("Received a packet of unknown type %08X", tlid); return; } } packetsReceived++; if(seqgt(pseq, lastRemoteSeq)){ uint32_t diff=pseq-lastRemoteSeq; if(diff>31){ memset(recvPacketTimes, 0, 32*sizeof(double)); }else{ memmove(&recvPacketTimes[diff], recvPacketTimes, (32-diff)*sizeof(double)); if(diff>1){ memset(recvPacketTimes, 0, diff*sizeof(double)); } recvPacketTimes[0]=GetCurrentTime(); } lastRemoteSeq=pseq; }else if(!seqgt(pseq, lastRemoteSeq) && lastRemoteSeq-pseq<32){ if(recvPacketTimes[lastRemoteSeq-pseq]!=0){ LOGW("Received duplicated packet for seq %u", pseq); return; } recvPacketTimes[lastRemoteSeq-pseq]=GetCurrentTime(); }else if(lastRemoteSeq-pseq>=32){ LOGW("Packet %u is out of order and too late", pseq); return; } bool didAckNewPackets=false; unsigned int newlyAckedVideoBytes=0; if(seqgt(ackId, lastRemoteAckSeq)){ didAckNewPackets=true; MutexGuard _m(queuedPacketsMutex); if(waitingForAcks && lastRemoteAckSeq>=firstSentPing){ rttHistory.Reset(); waitingForAcks=false; dontSendPackets=10; messageThread.Post([this]{ dontSendPackets=0; }, 1.0); LOGI("resuming sending"); } lastRemoteAckSeq=ackId; conctl->PacketAcknowledged(ackId); unsigned int i; for(i=0;i<31;i++){ for(vector<RecentOutgoingPacket>::iterator itr=recentOutgoingPackets.begin();itr!=recentOutgoingPackets.end();++itr){ if(itr->ackTime!=0) continue; if(((acks >> (31-i)) & 1) && itr->seq==ackId-(i+1)){ itr->ackTime=GetCurrentTime(); conctl->PacketAcknowledged(itr->seq); } } /*if(remoteAcks[i+1]==0){ if((acks >> (31-i)) & 1){ remoteAcks[i+1]=GetCurrentTime(); conctl->PacketAcknowledged(ackId-(i+1)); } }*/ } for(i=0;i<queuedPackets.size();i++){ QueuedPacket& qp=queuedPackets[i]; int j; bool didAck=false; for(j=0;j<16;j++){ LOGD("queued packet %u, seq %u=%u", i, j, qp.seqs[j]); if(qp.seqs[j]==0) break; int remoteAcksIndex=lastRemoteAckSeq-qp.seqs[j]; //LOGV("remote acks index %u, value %f", remoteAcksIndex, remoteAcksIndex>=0 && remoteAcksIndex<32 ? remoteAcks[remoteAcksIndex] : -1); if(seqgt(lastRemoteAckSeq, qp.seqs[j]) && remoteAcksIndex>=0 && remoteAcksIndex<32){ for(RecentOutgoingPacket& opkt:recentOutgoingPackets){ if(opkt.seq==qp.seqs[j] && opkt.ackTime>0){ LOGD("did ack seq %u, removing", qp.seqs[j]); didAck=true; break; } } if(didAck) break; } } if(didAck){ queuedPackets.erase(queuedPackets.begin()+i); i--; continue; } } for(vector<UnacknowledgedExtraData>::iterator x=currentExtras.begin();x!=currentExtras.end();){ if(x->firstContainingSeq!=0 && (lastRemoteAckSeq==x->firstContainingSeq || seqgt(lastRemoteAckSeq, x->firstContainingSeq))){ LOGV("Peer acknowledged extra type %u length %d", x->type, int(x->data.Length())); ProcessAcknowledgedOutgoingExtra(*x); x=currentExtras.erase(x); continue; } ++x; } if(videoSource && !videoKeyframeRequested){ // video frames are stored in sentVideoFrames in order of increasing numbers // so if a frame (or part of it) is acknowledged but isn't sentVideoFrames[0], we know there was a packet loss MutexGuard m(sentVideoFramesMutex); for(SentVideoFrame& f:sentVideoFrames){ for(vector<uint32_t>::iterator s=f.unacknowledgedPackets.begin(); s!=f.unacknowledgedPackets.end();){ RecentOutgoingPacket* opkt=GetRecentOutgoingPacket(*s); if(opkt && opkt->ackTime!=0.0){ s=f.unacknowledgedPackets.erase(s); newlyAckedVideoBytes+=opkt->size; }else{ ++s; } } } bool first=true; for(vector<SentVideoFrame>::iterator f=sentVideoFrames.begin();f!=sentVideoFrames.end();){ if(f->unacknowledgedPackets.empty() && f->fragmentsInQueue==0){ //LOGV("Video frame %u was acknowledged", f->num); if(first){ f=sentVideoFrames.erase(f); continue; }else{ LOGE("!!!!!!!!!!!!!!11 VIDEO FRAME LOSS DETECTED [1] %d of %u fragments", int(sentVideoFrames[0].unacknowledgedPackets.size()), sentVideoFrames[0].fragmentCount); videoPacketLossCount++; videoKeyframeRequested=true; videoSource->RequestKeyFrame(); break; } }else if(first){ first=false; }else if(!first && f->unacknowledgedPackets.size()<f->fragmentCount){ LOGE("!!!!!!!!!!!!!!11 VIDEO FRAME LOSS DETECTED [2] %d of %u fragments", int(f->unacknowledgedPackets.size()), f->fragmentCount); videoPacketLossCount++; videoKeyframeRequested=true; videoSource->RequestKeyFrame(); break; } ++f; } } } Endpoint* _currentEndpoint=&endpoints.at(currentEndpoint); if(srcEndpoint.id!=currentEndpoint && (srcEndpoint.type==Endpoint::Type::UDP_RELAY || srcEndpoint.type==Endpoint::Type::TCP_RELAY) && ((_currentEndpoint->type!=Endpoint::Type::UDP_RELAY && _currentEndpoint->type!=Endpoint::Type::TCP_RELAY) || _currentEndpoint->averageRTT==0)){ if(seqgt(lastSentSeq-32, lastRemoteAckSeq)){ currentEndpoint=srcEndpoint.id; _currentEndpoint=&srcEndpoint; LOGI("Peer network address probably changed, switching to relay"); if(allowP2p) SendPublicEndpointsRequest(); } } if(pflags & XPFLAG_HAS_EXTRA){ unsigned char extraCount=in.ReadByte(); for(int i=0;i<extraCount;i++){ size_t extraLen=in.ReadByte(); Buffer xbuffer(extraLen); in.ReadBytes(*xbuffer, extraLen); ProcessExtraData(xbuffer); } } if(pflags & XPFLAG_HAS_RECV_TS){ uint32_t recvTS=static_cast<uint32_t>(in.ReadInt32()); if(didAckNewPackets){ //LOGV("recv ts %u", recvTS); for(RecentOutgoingPacket& opkt:recentOutgoingPackets){ if(opkt.seq==lastRemoteAckSeq){ float sendTime=(float)(opkt.sendTime-connectionInitTime); float recvTime=(float)recvTS/1000.0f; float oneWayDelay=recvTime-sendTime; //LOGV("one-way delay: %f", oneWayDelay); videoCongestionControl.ProcessAcks(oneWayDelay, newlyAckedVideoBytes, videoPacketLossCount, rttHistory.Average(5)); break; } } } } if(config.logPacketStats){ DebugLoggedPacket dpkt={ static_cast<int32_t>(pseq), GetCurrentTime()-connectionInitTime, static_cast<int32_t>(packet.length) }; debugLoggedPackets.push_back(dpkt); if(debugLoggedPackets.size()>=2500){ debugLoggedPackets.erase(debugLoggedPackets.begin(), debugLoggedPackets.begin()+500); } } #ifdef LOG_PACKETS LOGV("Received: from=%s:%u, seq=%u, length=%u, type=%s", srcEndpoint.GetAddress().ToString().c_str(), srcEndpoint.port, pseq, packet.length, GetPacketTypeString(type).c_str()); #endif //LOGV("acks: %u -> %.2lf, %.2lf, %.2lf, %.2lf, %.2lf, %.2lf, %.2lf, %.2lf", lastRemoteAckSeq, remoteAcks[0], remoteAcks[1], remoteAcks[2], remoteAcks[3], remoteAcks[4], remoteAcks[5], remoteAcks[6], remoteAcks[7]); //LOGD("recv: %u -> %.2lf, %.2lf, %.2lf, %.2lf, %.2lf, %.2lf, %.2lf, %.2lf", lastRemoteSeq, recvPacketTimes[0], recvPacketTimes[1], recvPacketTimes[2], recvPacketTimes[3], recvPacketTimes[4], recvPacketTimes[5], recvPacketTimes[6], recvPacketTimes[7]); //LOGI("RTT = %.3lf", GetAverageRTT()); //LOGV("Packet %u type is %d", pseq, type); if(type==PKT_INIT){ LOGD("Received init"); uint32_t ver=(uint32_t)in.ReadInt32(); if(!receivedInit) peerVersion=ver; LOGI("Peer version is %d", peerVersion); uint32_t minVer=(uint32_t) in.ReadInt32(); if(minVer>PROTOCOL_VERSION || peerVersion<MIN_PROTOCOL_VERSION){ lastError=ERROR_INCOMPATIBLE; SetState(STATE_FAILED); return; } uint32_t flags=(uint32_t) in.ReadInt32(); if(!receivedInit){ if(flags & INIT_FLAG_DATA_SAVING_ENABLED){ dataSavingRequestedByPeer=true; UpdateDataSavingState(); UpdateAudioBitrateLimit(); } if(flags & INIT_FLAG_GROUP_CALLS_SUPPORTED){ peerCapabilities|=TGVOIP_PEER_CAP_GROUP_CALLS; } if(flags & INIT_FLAG_VIDEO_RECV_SUPPORTED){ peerCapabilities|=TGVOIP_PEER_CAP_VIDEO_DISPLAY; } if(flags & INIT_FLAG_VIDEO_SEND_SUPPORTED){ peerCapabilities|=TGVOIP_PEER_CAP_VIDEO_CAPTURE; } } unsigned int i; unsigned int numSupportedAudioCodecs=in.ReadByte(); for(i=0; i<numSupportedAudioCodecs; i++){ if(peerVersion<5) in.ReadByte(); // ignore for now else in.ReadInt32(); } if(!receivedInit && ((flags & INIT_FLAG_VIDEO_SEND_SUPPORTED && config.enableVideoReceive) || (flags & INIT_FLAG_VIDEO_RECV_SUPPORTED && config.enableVideoSend))){ LOGD("Peer video decoders:"); unsigned int numSupportedVideoDecoders=in.ReadByte(); for(i=0; i<numSupportedVideoDecoders; i++){ uint32_t id=static_cast<uint32_t>(in.ReadInt32()); peerVideoDecoders.push_back(id); char* _id=reinterpret_cast<char*>(&id); LOGD("%c%c%c%c", _id[3], _id[2], _id[1], _id[0]); } peerMaxVideoResolution=in.ReadByte(); SetupOutgoingVideoStream(); } BufferOutputStream out(1024); out.WriteInt32(PROTOCOL_VERSION); out.WriteInt32(MIN_PROTOCOL_VERSION); out.WriteByte((unsigned char) outgoingStreams.size()); for(vector<shared_ptr<Stream>>::iterator s=outgoingStreams.begin(); s!=outgoingStreams.end(); ++s){ out.WriteByte((*s)->id); out.WriteByte((*s)->type); if(peerVersion<5) out.WriteByte((unsigned char) ((*s)->codec==CODEC_OPUS ? CODEC_OPUS_OLD : 0)); else out.WriteInt32((*s)->codec); out.WriteInt16((*s)->frameDuration); out.WriteByte((unsigned char) ((*s)->enabled ? 1 : 0)); } LOGI("Sending init ack"); size_t outLength = out.GetLength(); SendOrEnqueuePacket(PendingOutgoingPacket{ /*.seq=*/GenerateOutSeq(), /*.type=*/PKT_INIT_ACK, /*.len=*/outLength, /*.data=*/Buffer(move(out)), /*.endpoint=*/0 }); if(!receivedInit){ receivedInit=true; if((srcEndpoint.type==Endpoint::Type::UDP_RELAY && udpConnectivityState!=UDP_BAD && udpConnectivityState!=UDP_NOT_AVAILABLE) || srcEndpoint.type==Endpoint::Type::TCP_RELAY){ currentEndpoint=srcEndpoint.id; if(srcEndpoint.type==Endpoint::Type::UDP_RELAY || (useTCP && srcEndpoint.type==Endpoint::Type::TCP_RELAY)) preferredRelay=srcEndpoint.id; } } if(!audioStarted && receivedInitAck){ StartAudio(); audioStarted=true; } } if(type==PKT_INIT_ACK){ LOGD("Received init ack"); if(!receivedInitAck){ receivedInitAck=true; messageThread.Cancel(initTimeoutID); initTimeoutID=MessageThread::INVALID_ID; if(packetInnerLen>10){ peerVersion=in.ReadInt32(); uint32_t minVer=(uint32_t) in.ReadInt32(); if(minVer>PROTOCOL_VERSION || peerVersion<MIN_PROTOCOL_VERSION){ lastError=ERROR_INCOMPATIBLE; SetState(STATE_FAILED); return; } }else{ peerVersion=1; } LOGI("peer version from init ack %d", peerVersion); unsigned char streamCount=in.ReadByte(); if(streamCount==0) return; int i; shared_ptr<Stream> incomingAudioStream=NULL; for(i=0; i<streamCount; i++){ shared_ptr<Stream> stm=make_shared<Stream>(); stm->id=in.ReadByte(); stm->type=in.ReadByte(); if(peerVersion<5){ unsigned char codec=in.ReadByte(); if(codec==CODEC_OPUS_OLD) stm->codec=CODEC_OPUS; }else{ stm->codec=(uint32_t) in.ReadInt32(); } in.ReadInt16(); stm->frameDuration=60; stm->enabled=in.ReadByte()==1; if(stm->type==STREAM_TYPE_VIDEO && peerVersion<9){ LOGV("Skipping video stream for old protocol version"); continue; } if(stm->type==STREAM_TYPE_AUDIO){ stm->jitterBuffer=make_shared<JitterBuffer>(nullptr, stm->frameDuration); if(stm->frameDuration>50) stm->jitterBuffer->SetMinPacketCount((uint32_t) ServerConfig::GetSharedInstance()->GetInt("jitter_initial_delay_60", 2)); else if(stm->frameDuration>30) stm->jitterBuffer->SetMinPacketCount((uint32_t) ServerConfig::GetSharedInstance()->GetInt("jitter_initial_delay_40", 4)); else stm->jitterBuffer->SetMinPacketCount((uint32_t) ServerConfig::GetSharedInstance()->GetInt("jitter_initial_delay_20", 6)); stm->decoder=NULL; }else if(stm->type==STREAM_TYPE_VIDEO){ if(!stm->packetReassembler){ //stm->packetReassembler=make_shared<PacketReassembler>(); //stm->packetReassembler->SetCallback(bind(&VoIPController::ProcessIncomingVideoFrame, this, placeholders::_1, placeholders::_2, placeholders::_3)); } }else{ LOGW("Unknown incoming stream type: %d", stm->type); continue; } incomingStreams.push_back(stm); if(stm->type==STREAM_TYPE_AUDIO && !incomingAudioStream) incomingAudioStream=stm; } if(!incomingAudioStream) return; if(peerVersion>=5 && !useMTProto2){ useMTProto2=true; LOGD("MTProto2 wasn't initially enabled for whatever reason but peer supports it; upgrading"); } if(!audioStarted && receivedInit){ StartAudio(); audioStarted=true; } messageThread.Post([this]{ if(state==STATE_WAIT_INIT_ACK){ SetState(STATE_ESTABLISHED); } }, ServerConfig::GetSharedInstance()->GetDouble("established_delay_if_no_stream_data", 1.5)); if(allowP2p) SendPublicEndpointsRequest(); } } if(type==PKT_STREAM_DATA || type==PKT_STREAM_DATA_X2 || type==PKT_STREAM_DATA_X3){ if(!receivedFirstStreamPacket){ receivedFirstStreamPacket=true; if(state!=STATE_ESTABLISHED && receivedInitAck){ messageThread.Post([this](){ SetState(STATE_ESTABLISHED); }, .5); LOGW("First audio packet - setting state to ESTABLISHED"); } } int count; switch(type){ case PKT_STREAM_DATA_X2: count=2; break; case PKT_STREAM_DATA_X3: count=3; break; case PKT_STREAM_DATA: default: count=1; break; } int i; if(srcEndpoint.type==Endpoint::Type::UDP_RELAY && srcEndpoint.id!=peerPreferredRelay){ peerPreferredRelay=srcEndpoint.id; } for(i=0;i<count;i++){ unsigned char streamID=in.ReadByte(); unsigned char flags=(unsigned char) (streamID & 0xC0); streamID&=0x3F; uint16_t sdlen=(uint16_t) (flags & STREAM_DATA_FLAG_LEN16 ? in.ReadInt16() : in.ReadByte()); uint32_t pts=(uint32_t) in.ReadInt32(); unsigned char fragmentCount=1; unsigned char fragmentIndex=0; //LOGD("stream data, pts=%d, len=%d, rem=%d", pts, sdlen, in.Remaining()); audioTimestampIn=pts; if(!audioOutStarted && audioOutput){ MutexGuard m(audioIOMutex); audioOutput->Start(); audioOutStarted=true; } bool fragmented=static_cast<bool>(sdlen & STREAM_DATA_XFLAG_FRAGMENTED); bool extraFEC=static_cast<bool>(sdlen & STREAM_DATA_XFLAG_EXTRA_FEC); bool keyframe=static_cast<bool>(sdlen & STREAM_DATA_XFLAG_KEYFRAME); if(fragmented){ fragmentIndex=in.ReadByte(); fragmentCount=in.ReadByte(); } sdlen&=0x7FF; if(in.GetOffset()+sdlen>len){ return; } shared_ptr<Stream> stm; for(shared_ptr<Stream>& ss:incomingStreams){ if(ss->id==streamID){ stm=ss; break; } } if(stm && stm->type==STREAM_TYPE_AUDIO){ if(stm->jitterBuffer){ stm->jitterBuffer->HandleInput((unsigned char *) (buffer+in.GetOffset()), sdlen, pts, false); if(extraFEC){ in.Seek(in.GetOffset()+sdlen); unsigned int fecCount=in.ReadByte(); for(unsigned int j=0;j<fecCount;j++){ unsigned char dlen=in.ReadByte(); unsigned char data[256]; in.ReadBytes(data, dlen); stm->jitterBuffer->HandleInput(data, dlen, pts-(fecCount-j-1)*stm->frameDuration, true); } } } }else if(stm && stm->type==STREAM_TYPE_VIDEO){ if(stm->packetReassembler){ Buffer pdata(sdlen); pdata.CopyFrom(buffer+in.GetOffset(), 0, sdlen); stm->packetReassembler->AddFragment(std::move(pdata), fragmentIndex, fragmentCount, pts, keyframe); } //LOGV("Received video fragment %u of %u", fragmentIndex, fragmentCount); }else{ LOGW("received packet for unknown stream %u", (unsigned int)streamID); } if(i<count-1) in.Seek(in.GetOffset()+sdlen); } } if(type==PKT_PING){ //LOGD("Received ping from %s:%d", srcEndpoint.address.ToString().c_str(), srcEndpoint.port); if(srcEndpoint.type!=Endpoint::Type::UDP_RELAY && srcEndpoint.type!=Endpoint::Type::TCP_RELAY && !allowP2p){ LOGW("Received p2p ping but p2p is disabled by manual override"); return; } BufferOutputStream pkt(128); pkt.WriteInt32(pseq); size_t pktLength = pkt.GetLength(); SendOrEnqueuePacket(PendingOutgoingPacket{ /*.seq=*/GenerateOutSeq(), /*.type=*/PKT_PONG, /*.len=*/pktLength, /*.data=*/Buffer(move(pkt)), /*.endpoint=*/srcEndpoint.id, }); } if(type==PKT_PONG){ if(packetInnerLen>=4){ uint32_t pingSeq=(uint32_t) in.ReadInt32(); #ifdef LOG_PACKETS LOGD("Received pong for ping in seq %u", pingSeq); #endif if(pingSeq==srcEndpoint.lastPingSeq){ srcEndpoint.rtts.Add(GetCurrentTime()-srcEndpoint.lastPingTime); srcEndpoint.averageRTT=srcEndpoint.rtts.NonZeroAverage(); LOGD("Current RTT via %s: %.3f, average: %.3f", packet.address->ToString().c_str(), srcEndpoint.rtts[0], srcEndpoint.averageRTT); if(srcEndpoint.averageRTT>rateMaxAcceptableRTT) needRate=true; } } } if(type==PKT_STREAM_STATE){ unsigned char id=in.ReadByte(); unsigned char enabled=in.ReadByte(); LOGV("Peer stream state: id %u flags %u", (int)id, (int)enabled); for(vector<shared_ptr<Stream>>::iterator s=incomingStreams.begin();s!=incomingStreams.end();++s){ if((*s)->id==id){ (*s)->enabled=enabled==1; UpdateAudioOutputState(); break; } } } if(type==PKT_LAN_ENDPOINT){ LOGV("received lan endpoint"); uint32_t peerAddr=(uint32_t) in.ReadInt32(); uint16_t peerPort=(uint16_t) in.ReadInt32(); MutexGuard m(endpointsMutex); constexpr int64_t lanID=(int64_t)(FOURCC('L','A','N','4')) << 32; IPv4Address v4addr(peerAddr); IPv6Address v6addr(string("::0")); unsigned char peerTag[16]; Endpoint lan(lanID, peerPort, v4addr, v6addr, Endpoint::Type::UDP_P2P_LAN, peerTag); if(currentEndpoint==lanID) currentEndpoint=preferredRelay; endpoints[lanID]=lan; } if(type==PKT_NETWORK_CHANGED && _currentEndpoint->type!=Endpoint::Type::UDP_RELAY && _currentEndpoint->type!=Endpoint::Type::TCP_RELAY){ currentEndpoint=preferredRelay; if(allowP2p) SendPublicEndpointsRequest(); if(peerVersion>=2){ uint32_t flags=(uint32_t) in.ReadInt32(); dataSavingRequestedByPeer=(flags & INIT_FLAG_DATA_SAVING_ENABLED)==INIT_FLAG_DATA_SAVING_ENABLED; UpdateDataSavingState(); UpdateAudioBitrateLimit(); ResetEndpointPingStats(); } } if(type==PKT_STREAM_EC){ unsigned char streamID=in.ReadByte(); uint32_t lastTimestamp=(uint32_t)in.ReadInt32(); unsigned char count=in.ReadByte(); for(shared_ptr<Stream>& stm:incomingStreams){ if(stm->id==streamID){ for(unsigned int i=0;i<count;i++){ unsigned char dlen=in.ReadByte(); unsigned char data[256]; in.ReadBytes(data, dlen); if(stm->jitterBuffer){ stm->jitterBuffer->HandleInput(data, dlen, lastTimestamp-(count-i-1)*stm->frameDuration, true); } } break; } } } } void VoIPController::ProcessExtraData(Buffer &data){ BufferInputStream in(*data, data.Length()); unsigned char type=in.ReadByte(); unsigned char fullHash[SHA1_LENGTH]; crypto.sha1(*data, data.Length(), fullHash); uint64_t hash=*reinterpret_cast<uint64_t*>(fullHash); if(lastReceivedExtrasByType[type]==hash){ return; } LOGE("ProcessExtraData"); lastReceivedExtrasByType[type]=hash; if(type==EXTRA_TYPE_STREAM_FLAGS){ unsigned char id=in.ReadByte(); uint32_t flags=static_cast<uint32_t>(in.ReadInt32()); LOGV("Peer stream state: id %u flags %u", (unsigned int)id, (unsigned int)flags); for(shared_ptr<Stream>& s:incomingStreams){ if(s->id==id){ bool prevEnabled=s->enabled; s->enabled=(flags & STREAM_FLAG_ENABLED)==STREAM_FLAG_ENABLED; if(flags & STREAM_FLAG_EXTRA_EC){ if(!s->extraECEnabled){ s->extraECEnabled=true; if(s->jitterBuffer) s->jitterBuffer->SetMinPacketCount(4); } }else{ if(s->extraECEnabled){ s->extraECEnabled=false; if(s->jitterBuffer) s->jitterBuffer->SetMinPacketCount(2); } } if(prevEnabled!=s->enabled && s->type==STREAM_TYPE_VIDEO && videoRenderer) videoRenderer->SetStreamEnabled(s->enabled); UpdateAudioOutputState(); break; } } }else if(type==EXTRA_TYPE_STREAM_CSD){ LOGI("Received codec specific data"); /* os.WriteByte(stream.id); os.WriteByte(static_cast<unsigned char>(stream.codecSpecificData.size())); for(Buffer& b:stream.codecSpecificData){ assert(b.Length()<255); os.WriteByte(static_cast<unsigned char>(b.Length())); os.WriteBytes(b); } Buffer buf(move(os)); SendExtra(buf, EXTRA_TYPE_STREAM_CSD); */ unsigned char streamID=in.ReadByte(); for(shared_ptr<Stream>& stm:incomingStreams){ if(stm->id==streamID){ stm->codecSpecificData.clear(); stm->csdIsValid=false; stm->width=static_cast<unsigned int>(in.ReadInt16()); stm->height=static_cast<unsigned int>(in.ReadInt16()); size_t count=(size_t)in.ReadByte(); for(size_t i=0;i<count;i++){ size_t len=(size_t)in.ReadByte(); Buffer csd(len); in.ReadBytes(*csd, len); stm->codecSpecificData.push_back(move(csd)); } break; } } }else if(type==EXTRA_TYPE_LAN_ENDPOINT){ if(!allowP2p) return; LOGV("received lan endpoint (extra)"); uint32_t peerAddr=(uint32_t) in.ReadInt32(); uint16_t peerPort=(uint16_t) in.ReadInt32(); MutexGuard m(endpointsMutex); constexpr int64_t lanID=(int64_t)(FOURCC('L','A','N','4')) << 32; if(currentEndpoint==lanID) currentEndpoint=preferredRelay; IPv4Address v4addr(peerAddr); IPv6Address v6addr(string("::0")); unsigned char peerTag[16]; Endpoint lan(lanID, peerPort, v4addr, v6addr, Endpoint::Type::UDP_P2P_LAN, peerTag); endpoints[lanID]=lan; }else if(type==EXTRA_TYPE_NETWORK_CHANGED){ LOGI("Peer network changed"); wasNetworkHandover=true; const Endpoint& _currentEndpoint=endpoints.at(currentEndpoint); if(_currentEndpoint.type!=Endpoint::Type::UDP_RELAY && _currentEndpoint.type!=Endpoint::Type::TCP_RELAY) currentEndpoint=preferredRelay; if(allowP2p) SendPublicEndpointsRequest(); uint32_t flags=(uint32_t) in.ReadInt32(); dataSavingRequestedByPeer=(flags & INIT_FLAG_DATA_SAVING_ENABLED)==INIT_FLAG_DATA_SAVING_ENABLED; UpdateDataSavingState(); UpdateAudioBitrateLimit(); ResetEndpointPingStats(); }else if(type==EXTRA_TYPE_GROUP_CALL_KEY){ if(!didReceiveGroupCallKey && !didSendGroupCallKey){ unsigned char groupKey[256]; in.ReadBytes(groupKey, 256); messageThread.Post([this, &groupKey]{ if(callbacks.groupCallKeyReceived) callbacks.groupCallKeyReceived(this, groupKey); }); didReceiveGroupCallKey=true; } }else if(type==EXTRA_TYPE_REQUEST_GROUP){ if(!didInvokeUpgradeCallback){ messageThread.Post([this]{ if(callbacks.upgradeToGroupCallRequested) callbacks.upgradeToGroupCallRequested(this); }); didInvokeUpgradeCallback=true; } }else if(type==EXTRA_TYPE_IPV6_ENDPOINT){ if(!allowP2p) return; unsigned char _addr[16]; in.ReadBytes(_addr, 16); IPv6Address addr(_addr); uint16_t port=static_cast<uint16_t>(in.ReadInt16()); MutexGuard m(endpointsMutex); peerIPv6Available=true; LOGV("Received peer IPv6 endpoint [%s]:%u", addr.ToString().c_str(), port); constexpr int64_t p2pID=(int64_t)(FOURCC('P','2','P','6')) << 32; Endpoint ep; ep.type=Endpoint::Type::UDP_P2P_INET; ep.port=port; ep.v6address=addr; ep.id=p2pID; endpoints[p2pID]=ep; if(!myIPv6.IsEmpty()) currentEndpoint=p2pID; } } void VoIPController::ProcessAcknowledgedOutgoingExtra(UnacknowledgedExtraData &extra){ if(extra.type==EXTRA_TYPE_GROUP_CALL_KEY){ if(!didReceiveGroupCallKeyAck){ didReceiveGroupCallKeyAck=true; messageThread.Post([this]{ if(callbacks.groupCallKeySent) callbacks.groupCallKeySent(this); }); } } } Endpoint& VoIPController::GetRemoteEndpoint(){ return endpoints.at(currentEndpoint); } Endpoint* VoIPController::GetEndpointForPacket(const PendingOutgoingPacket& pkt){ Endpoint* endpoint=NULL; if(pkt.endpoint){ try{ endpoint=&endpoints.at(pkt.endpoint); }catch(out_of_range& x){ LOGW("Unable to send packet via nonexistent endpoint %" PRIu64, pkt.endpoint); return NULL; } } if(!endpoint) endpoint=&endpoints.at(currentEndpoint); return endpoint; } bool VoIPController::SendOrEnqueuePacket(PendingOutgoingPacket pkt, bool enqueue){ Endpoint* endpoint=GetEndpointForPacket(pkt); if(!endpoint){ abort(); return false; } bool canSend; if(endpoint->type!=Endpoint::Type::TCP_RELAY){ canSend=realUdpSocket->IsReadyToSend(); }else{ if(!endpoint->socket){ LOGV("Connecting to %s:%u", endpoint->GetAddress().ToString().c_str(), endpoint->port); if(proxyProtocol==PROXY_NONE){ endpoint->socket=new NetworkSocketTCPObfuscated(NetworkSocket::Create(NetworkProtocol::PROTO_TCP)); endpoint->socket->Connect(&endpoint->GetAddress(), endpoint->port); }else if(proxyProtocol==PROXY_SOCKS5){ NetworkSocket* tcp=NetworkSocket::Create(NetworkProtocol::PROTO_TCP); tcp->Connect(resolvedProxyAddress, proxyPort); NetworkSocketSOCKS5Proxy* proxy=new NetworkSocketSOCKS5Proxy(tcp, NULL, proxyUsername, proxyPassword); endpoint->socket=proxy; endpoint->socket->Connect(&endpoint->GetAddress(), endpoint->port); } selectCanceller->CancelSelect(); } canSend=endpoint->socket && endpoint->socket->IsReadyToSend(); } if(!canSend){ if(enqueue){ LOGW("Not ready to send - enqueueing"); sendQueue.push_back(move(pkt)); } return false; } if((endpoint->type==Endpoint::Type::TCP_RELAY && useTCP) || (endpoint->type!=Endpoint::Type::TCP_RELAY && useUDP)){ //BufferOutputStream p(buf, sizeof(buf)); BufferOutputStream p(1500); WritePacketHeader(pkt.seq, &p, pkt.type, (uint32_t)pkt.len); p.WriteBytes(pkt.data); SendPacket(p.GetBuffer(), p.GetLength(), *endpoint, pkt); if(pkt.type==PKT_STREAM_DATA){ unsentStreamPackets--; } } return true; } void VoIPController::SendPacket(unsigned char *data, size_t len, Endpoint& ep, PendingOutgoingPacket& srcPacket){ if(stopping) return; if(ep.type==Endpoint::Type::TCP_RELAY && !useTCP) return; BufferOutputStream out(len+128); if(ep.type==Endpoint::Type::UDP_RELAY || ep.type==Endpoint::Type::TCP_RELAY) out.WriteBytes((unsigned char*)ep.peerTag, 16); else if(peerVersion<9) out.WriteBytes(callID, 16); if(len>0){ if(useMTProto2){ BufferOutputStream inner(len+128); size_t sizeSize; if(peerVersion>=8 || (!peerVersion && connectionMaxLayer>=92)){ inner.WriteInt16((uint16_t) len); sizeSize=0; }else{ inner.WriteInt32((uint32_t) len); out.WriteBytes(keyFingerprint, 8); sizeSize=4; } inner.WriteBytes(data, len); size_t padLen=16-inner.GetLength()%16; if(padLen<16) padLen+=16; unsigned char padding[32]; crypto.rand_bytes((uint8_t *) padding, padLen); inner.WriteBytes(padding, padLen); assert(inner.GetLength()%16==0); unsigned char key[32], iv[32], msgKey[16]; BufferOutputStream buf(len+32); size_t x=isOutgoing ? 0 : 8; buf.WriteBytes(encryptionKey+88+x, 32); buf.WriteBytes(inner.GetBuffer()+sizeSize, inner.GetLength()-sizeSize); unsigned char msgKeyLarge[32]; crypto.sha256(buf.GetBuffer(), buf.GetLength(), msgKeyLarge); memcpy(msgKey, msgKeyLarge+8, 16); KDF2(msgKey, isOutgoing ? 0 : 8, key, iv); out.WriteBytes(msgKey, 16); //LOGV("<- MSG KEY: %08x %08x %08x %08x, hashed %u", *reinterpret_cast<int32_t*>(msgKey), *reinterpret_cast<int32_t*>(msgKey+4), *reinterpret_cast<int32_t*>(msgKey+8), *reinterpret_cast<int32_t*>(msgKey+12), inner.GetLength()-4); unsigned char aesOut[MSC_STACK_FALLBACK(inner.GetLength(), 1500)]; crypto.aes_ige_encrypt(inner.GetBuffer(), aesOut, inner.GetLength(), key, iv); out.WriteBytes(aesOut, inner.GetLength()); }else{ BufferOutputStream inner(len+128); inner.WriteInt32((int32_t)len); inner.WriteBytes(data, len); if(inner.GetLength()%16!=0){ size_t padLen=16-inner.GetLength()%16; unsigned char padding[16]; crypto.rand_bytes((uint8_t *) padding, padLen); inner.WriteBytes(padding, padLen); } assert(inner.GetLength()%16==0); unsigned char key[32], iv[32], msgHash[SHA1_LENGTH]; crypto.sha1((uint8_t *) inner.GetBuffer(), len+4, msgHash); out.WriteBytes(keyFingerprint, 8); out.WriteBytes((msgHash+(SHA1_LENGTH-16)), 16); KDF(msgHash+(SHA1_LENGTH-16), isOutgoing ? 0 : 8, key, iv); unsigned char aesOut[MSC_STACK_FALLBACK(inner.GetLength(), 1500)]; crypto.aes_ige_encrypt(inner.GetBuffer(), aesOut, inner.GetLength(), key, iv); out.WriteBytes(aesOut, inner.GetLength()); } } //LOGV("Sending %d bytes to %s:%d", out.GetLength(), ep.address.ToString().c_str(), ep.port); #ifdef LOG_PACKETS LOGV("Sending: to=%s:%u, seq=%u, length=%u, type=%s", ep.GetAddress().ToString().c_str(), ep.port, srcPacket.seq, out.GetLength(), GetPacketTypeString(srcPacket.type).c_str()); #endif NetworkPacket pkt={0}; pkt.address=&ep.GetAddress(); pkt.port=ep.port; pkt.length=out.GetLength(); pkt.data=out.GetBuffer(); pkt.protocol=ep.type==Endpoint::Type::TCP_RELAY ? PROTO_TCP : PROTO_UDP; ActuallySendPacket(pkt, ep); } void VoIPController::ActuallySendPacket(NetworkPacket &pkt, Endpoint& ep){ //LOGI("Sending packet of %d bytes", pkt.length); if(IS_MOBILE_NETWORK(networkType)) stats.bytesSentMobile+=(uint64_t)pkt.length; else stats.bytesSentWifi+=(uint64_t)pkt.length; if(ep.type==Endpoint::Type::TCP_RELAY){ if(ep.socket && !ep.socket->IsFailed()){ ep.socket->Send(&pkt); } }else{ udpSocket->Send(&pkt); } } std::string VoIPController::NetworkTypeToString(int type){ switch(type){ case NET_TYPE_WIFI: return "wifi"; case NET_TYPE_GPRS: return "gprs"; case NET_TYPE_EDGE: return "edge"; case NET_TYPE_3G: return "3g"; case NET_TYPE_HSPA: return "hspa"; case NET_TYPE_LTE: return "lte"; case NET_TYPE_ETHERNET: return "ethernet"; case NET_TYPE_OTHER_HIGH_SPEED: return "other_high_speed"; case NET_TYPE_OTHER_LOW_SPEED: return "other_low_speed"; case NET_TYPE_DIALUP: return "dialup"; case NET_TYPE_OTHER_MOBILE: return "other_mobile"; default: return "unknown"; } } std::string VoIPController::GetPacketTypeString(unsigned char type){ switch(type){ case PKT_INIT: return "init"; case PKT_INIT_ACK: return "init_ack"; case PKT_STREAM_STATE: return "stream_state"; case PKT_STREAM_DATA: return "stream_data"; case PKT_PING: return "ping"; case PKT_PONG: return "pong"; case PKT_LAN_ENDPOINT: return "lan_endpoint"; case PKT_NETWORK_CHANGED: return "network_changed"; case PKT_NOP: return "nop"; case PKT_STREAM_EC: return "stream_ec"; } char buf[255]; snprintf(buf, sizeof(buf), "unknown(%u)", type); return string(buf); } void VoIPController::AddIPv6Relays(){ if(!myIPv6.IsEmpty() && !didAddIPv6Relays){ unordered_map<string, vector<Endpoint>> endpointsByAddress; MutexGuard m(endpointsMutex); for(pair<const int64_t, Endpoint>& _e:endpoints){ Endpoint& e=_e.second; if((e.type==Endpoint::Type::UDP_RELAY || e.type==Endpoint::Type::TCP_RELAY) && !e.v6address.IsEmpty() && !e.address.IsEmpty()){ endpointsByAddress[e.v6address.ToString()].push_back(e); } } for(pair<const string, vector<Endpoint>>& addr:endpointsByAddress){ for(Endpoint& e:addr.second){ didAddIPv6Relays=true; e.address=IPv4Address(0); e.id=e.id ^ ((int64_t)(FOURCC('I','P','v','6')) << 32); e.averageRTT=0; e.lastPingSeq=0; e.lastPingTime=0; e.rtts.Reset(); e.udpPongCount=0; endpoints[e.id]=e; LOGD("Adding IPv6-only endpoint [%s]:%u", e.v6address.ToString().c_str(), e.port); } } } } void VoIPController::AddTCPRelays(){ if(!didAddTcpRelays){ bool wasSetCurrentToTCP=setCurrentEndpointToTCP; LOGV("Adding TCP relays"); MutexGuard m(endpointsMutex); vector<Endpoint> relays; for(pair<const int64_t, Endpoint> &_e:endpoints){ Endpoint& e=_e.second; if(e.type!=Endpoint::Type::UDP_RELAY) continue; if(wasSetCurrentToTCP && !useUDP){ e.rtts.Reset(); e.averageRTT=0; e.lastPingSeq=0; } Endpoint tcpRelay(e); tcpRelay.type=Endpoint::Type::TCP_RELAY; tcpRelay.averageRTT=0; tcpRelay.lastPingSeq=0; tcpRelay.lastPingTime=0; tcpRelay.rtts.Reset(); tcpRelay.udpPongCount=0; tcpRelay.id=tcpRelay.id ^ ((int64_t) (FOURCC('T', 'C', 'P', 0)) << 32); if(setCurrentEndpointToTCP && endpoints.at(currentEndpoint).type!=Endpoint::Type::TCP_RELAY){ LOGV("Setting current endpoint to TCP"); setCurrentEndpointToTCP=false; currentEndpoint=tcpRelay.id; preferredRelay=tcpRelay.id; } relays.push_back(tcpRelay); } for(Endpoint& e:relays){ endpoints[e.id]=e; } didAddTcpRelays=true; } } #if defined(__APPLE__) static void initMachTimestart() { mach_timebase_info_data_t tb = { 0, 0 }; mach_timebase_info(&tb); VoIPController::machTimebase = tb.numer; VoIPController::machTimebase /= tb.denom; VoIPController::machTimestart = mach_absolute_time(); } #endif double VoIPController::GetCurrentTime(){ #if defined(__linux__) struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return ts.tv_sec+(double)ts.tv_nsec/1000000000.0; #elif defined(__APPLE__) static pthread_once_t token = PTHREAD_ONCE_INIT; pthread_once(&token, &initMachTimestart); return (mach_absolute_time() - machTimestart) * machTimebase / 1000000000.0f; #elif defined(_WIN32) if(!didInitWin32TimeScale){ LARGE_INTEGER scale; QueryPerformanceFrequency(&scale); win32TimeScale=scale.QuadPart; didInitWin32TimeScale=true; } LARGE_INTEGER t; QueryPerformanceCounter(&t); return (double)t.QuadPart/(double)win32TimeScale; #endif } void VoIPController::KDF(unsigned char* msgKey, size_t x, unsigned char* aesKey, unsigned char* aesIv){ uint8_t sA[SHA1_LENGTH], sB[SHA1_LENGTH], sC[SHA1_LENGTH], sD[SHA1_LENGTH]; BufferOutputStream buf(128); buf.WriteBytes(msgKey, 16); buf.WriteBytes(encryptionKey+x, 32); crypto.sha1(buf.GetBuffer(), buf.GetLength(), sA); buf.Reset(); buf.WriteBytes(encryptionKey+32+x, 16); buf.WriteBytes(msgKey, 16); buf.WriteBytes(encryptionKey+48+x, 16); crypto.sha1(buf.GetBuffer(), buf.GetLength(), sB); buf.Reset(); buf.WriteBytes(encryptionKey+64+x, 32); buf.WriteBytes(msgKey, 16); crypto.sha1(buf.GetBuffer(), buf.GetLength(), sC); buf.Reset(); buf.WriteBytes(msgKey, 16); buf.WriteBytes(encryptionKey+96+x, 32); crypto.sha1(buf.GetBuffer(), buf.GetLength(), sD); buf.Reset(); buf.WriteBytes(sA, 8); buf.WriteBytes(sB+8, 12); buf.WriteBytes(sC+4, 12); assert(buf.GetLength()==32); memcpy(aesKey, buf.GetBuffer(), 32); buf.Reset(); buf.WriteBytes(sA+8, 12); buf.WriteBytes(sB, 8); buf.WriteBytes(sC+16, 4); buf.WriteBytes(sD, 8); assert(buf.GetLength()==32); memcpy(aesIv, buf.GetBuffer(), 32); } void VoIPController::KDF2(unsigned char* msgKey, size_t x, unsigned char *aesKey, unsigned char *aesIv){ uint8_t sA[32], sB[32]; BufferOutputStream buf(128); buf.WriteBytes(msgKey, 16); buf.WriteBytes(encryptionKey+x, 36); crypto.sha256(buf.GetBuffer(), buf.GetLength(), sA); buf.Reset(); buf.WriteBytes(encryptionKey+40+x, 36); buf.WriteBytes(msgKey, 16); crypto.sha256(buf.GetBuffer(), buf.GetLength(), sB); buf.Reset(); buf.WriteBytes(sA, 8); buf.WriteBytes(sB+8, 16); buf.WriteBytes(sA+24, 8); memcpy(aesKey, buf.GetBuffer(), 32); buf.Reset(); buf.WriteBytes(sB, 8); buf.WriteBytes(sA+8, 16); buf.WriteBytes(sB+24, 8); memcpy(aesIv, buf.GetBuffer(), 32); } void VoIPController::SendPublicEndpointsRequest(const Endpoint& relay){ if(!useUDP) return; LOGD("Sending public endpoints request to %s:%d", relay.address.ToString().c_str(), relay.port); publicEndpointsReqTime=GetCurrentTime(); waitingForRelayPeerInfo=true; unsigned char buf[32]; memcpy(buf, relay.peerTag, 16); memset(buf+16, 0xFF, 16); NetworkPacket pkt={0}; pkt.data=buf; pkt.length=32; pkt.address=(NetworkAddress*)&relay.address; pkt.port=relay.port; pkt.protocol=PROTO_UDP; udpSocket->Send(&pkt); } Endpoint& VoIPController::GetEndpointByType(int type){ if(type==Endpoint::Type::UDP_RELAY && preferredRelay) return endpoints.at(preferredRelay); for(pair<const int64_t, Endpoint>& e:endpoints){ if(e.second.type==type) return e.second; } throw out_of_range("no endpoint"); } void VoIPController::SendPacketReliably(unsigned char type, unsigned char *data, size_t len, double retryInterval, double timeout){ LOGD("Send reliably, type=%u, len=%u, retry=%.3f, timeout=%.3f", type, unsigned(len), retryInterval, timeout); QueuedPacket pkt; if(data){ Buffer b(len); b.CopyFrom(data, 0, len); pkt.data=move(b); } pkt.type=type; pkt.retryInterval=retryInterval; pkt.timeout=timeout; pkt.firstSentTime=0; pkt.lastSentTime=0; { MutexGuard m(queuedPacketsMutex); queuedPackets.push_back(move(pkt)); } messageThread.Post(std::bind(&VoIPController::UpdateQueuedPackets, this)); if(timeout>0.0){ messageThread.Post(std::bind(&VoIPController::UpdateQueuedPackets, this), timeout); } } void VoIPController::SendExtra(Buffer &data, unsigned char type){ MutexGuard m(queuedPacketsMutex); LOGV("Sending extra type %u length %d", type, int(data.Length())); for(vector<UnacknowledgedExtraData>::iterator x=currentExtras.begin();x!=currentExtras.end();++x){ if(x->type==type){ x->firstContainingSeq=0; x->data=move(data); return; } } UnacknowledgedExtraData xd={type, move(data), 0}; currentExtras.push_back(move(xd)); } void VoIPController::DebugCtl(int request, int param){ if(request==1){ // set bitrate maxBitrate=param; if(encoder){ encoder->SetBitrate(maxBitrate); } }else if(request==2){ // set packet loss if(encoder){ encoder->SetPacketLoss(param); } }else if(request==3){ // force enable/disable p2p allowP2p=param==1; /*if(!allowP2p && currentEndpoint && currentEndpoint->type!=Endpoint::Type::UDP_RELAY){ currentEndpoint=preferredRelay; }else if(allowP2p){ SendPublicEndpointsRequest(); }*/ BufferOutputStream s(4); s.WriteInt32(dataSavingMode ? INIT_FLAG_DATA_SAVING_ENABLED : 0); SendPacketReliably(PKT_NETWORK_CHANGED, s.GetBuffer(), s.GetLength(), 1, 20); }else if(request==4){ if(echoCanceller) echoCanceller->Enable(param==1); } } void VoIPController::SendUdpPing(Endpoint& endpoint){ if(endpoint.type!=Endpoint::Type::UDP_RELAY) return; BufferOutputStream p(1024); p.WriteBytes(endpoint.peerTag, 16); p.WriteInt32(-1); p.WriteInt32(-1); p.WriteInt32(-1); p.WriteInt32(-2); int64_t id; crypto.rand_bytes(reinterpret_cast<uint8_t*>(&id), 8); p.WriteInt64(id); NetworkPacket pkt={0}; pkt.address=&endpoint.GetAddress(); pkt.port=endpoint.port; pkt.protocol=PROTO_UDP; pkt.data=p.GetBuffer(); pkt.length=p.GetLength(); udpSocket->Send(&pkt); LOGV("Sending UDP ping to %s:%d, id %" PRId64, endpoint.GetAddress().ToString().c_str(), endpoint.port, id); } void VoIPController::ResetUdpAvailability(){ LOGI("Resetting UDP availability"); if(udpPingTimeoutID!=MessageThread::INVALID_ID){ messageThread.Cancel(udpPingTimeoutID); } { MutexGuard m(endpointsMutex); for(pair<const int64_t, Endpoint>& e:endpoints){ e.second.udpPongCount=0; } } udpPingCount=0; udpConnectivityState=UDP_PING_PENDING; udpPingTimeoutID=messageThread.Post(std::bind(&VoIPController::SendUdpPings, this), 0.0, 0.5); } void VoIPController::ResetEndpointPingStats(){ MutexGuard m(endpointsMutex); for(pair<const int64_t, Endpoint>& e:endpoints){ e.second.averageRTT=0.0; e.second.rtts.Reset(); } } #pragma mark - Video int VoIPController::GetVideoResolutionForCurrentBitrate(){ shared_ptr<Stream> stm=GetStreamByType(STREAM_TYPE_VIDEO, true); if(!stm) return INIT_VIDEO_RES_NONE; int resolutionFromBitrate=INIT_VIDEO_RES_1080; // TODO: probably move this to server config if(stm->codec==CODEC_AVC || stm->codec==CODEC_VP8){ if(currentVideoBitrate>400000){ resolutionFromBitrate=INIT_VIDEO_RES_720; }else if(currentVideoBitrate>250000){ resolutionFromBitrate=INIT_VIDEO_RES_480; }else{ resolutionFromBitrate=INIT_VIDEO_RES_360; } }else if(stm->codec==CODEC_HEVC || stm->codec==CODEC_VP9){ if(currentVideoBitrate>400000){ resolutionFromBitrate=INIT_VIDEO_RES_1080; }else if(currentVideoBitrate>250000){ resolutionFromBitrate=INIT_VIDEO_RES_720; }else if(currentVideoBitrate>100000){ resolutionFromBitrate=INIT_VIDEO_RES_480; }else{ resolutionFromBitrate=INIT_VIDEO_RES_360; } } return min(peerMaxVideoResolution, resolutionFromBitrate); } void VoIPController::SetVideoSource(video::VideoSource *source){ if(videoSource){ videoSource->Stop(); videoSource->SetCallback(nullptr); } videoSource=source; shared_ptr<Stream> stm=GetStreamByType(STREAM_TYPE_VIDEO, true); if(!stm){ LOGE("Can't set video source when there is no outgoing video stream"); return; } if(videoSource){ if(!stm->enabled){ stm->enabled=true; SendStreamFlags(*stm); } uint32_t bitrate=videoCongestionControl.GetBitrate(); currentVideoBitrate=bitrate; videoSource->SetBitrate(bitrate); videoSource->Reset(stm->codec, stm->resolution=GetVideoResolutionForCurrentBitrate()); videoSource->Start(); videoSource->SetCallback(bind(&VoIPController::SendVideoFrame, this, placeholders::_1, placeholders::_2)); lastVideoResolutionChangeTime=GetCurrentTime(); }else{ if(stm->enabled){ stm->enabled=false; SendStreamFlags(*stm); } } } void VoIPController::SetVideoRenderer(video::VideoRenderer *renderer){ videoRenderer=renderer; } void VoIPController::SetVideoCodecSpecificData(const std::vector<Buffer>& data){ outgoingStreams[1]->codecSpecificData.clear(); for(const Buffer& csd:data){ outgoingStreams[1]->codecSpecificData.push_back(Buffer::CopyOf(csd)); } LOGI("Set outgoing video stream CSD"); } void VoIPController::SendVideoFrame(const Buffer &frame, uint32_t flags){ //LOGI("Send video frame %u flags %u", (unsigned int)frame.Length(), flags); shared_ptr<Stream> stm=GetStreamByType(STREAM_TYPE_VIDEO, true); if(stm){ if(firstVideoFrameTime==0.0) firstVideoFrameTime=GetCurrentTime(); videoCongestionControl.UpdateMediaRate(static_cast<uint32_t>(frame.Length())); uint32_t bitrate=videoCongestionControl.GetBitrate(); if(bitrate!=currentVideoBitrate){ currentVideoBitrate=bitrate; LOGD("Setting video bitrate to %u", bitrate); videoSource->SetBitrate(bitrate); int resolutionFromBitrate=GetVideoResolutionForCurrentBitrate(); if(resolutionFromBitrate!=stm->resolution && GetCurrentTime()-lastVideoResolutionChangeTime>3.0){ LOGI("Changing video resolution: %d -> %d", stm->resolution, resolutionFromBitrate); stm->resolution=resolutionFromBitrate; messageThread.Post([this, stm, resolutionFromBitrate]{ videoSource->Reset(stm->codec, resolutionFromBitrate); stm->csdIsValid=false; }); lastVideoResolutionChangeTime=GetCurrentTime(); return; } } if(videoKeyframeRequested){ if(flags & VIDEO_FRAME_FLAG_KEYFRAME){ for(SentVideoFrame& f:sentVideoFrames){ if(!f.unacknowledgedPackets.empty()){ for(uint32_t& pseq:f.unacknowledgedPackets){ RecentOutgoingPacket* opkt=GetRecentOutgoingPacket(pseq); if(opkt){ videoCongestionControl.ProcessPacketLost(opkt->size); } } } } sentVideoFrames.clear(); videoKeyframeRequested=false; }else{ LOGV("Dropping input video frame waiting for key frame"); return; } } uint32_t pts=videoFrameCount++; if(!stm->csdIsValid){ vector<Buffer>& csd=videoSource->GetCodecSpecificData(); stm->codecSpecificData.clear(); for(Buffer& b:csd){ stm->codecSpecificData.push_back(Buffer::CopyOf(b)); } stm->csdIsValid=true; stm->width=videoSource->GetFrameWidth(); stm->height=videoSource->GetFrameHeight(); SendStreamCSD(*stm); } size_t segmentCount=frame.Length()/1024; if(frame.Length()%1024>0) segmentCount++; SentVideoFrame sentFrame; sentFrame.num=pts; sentFrame.fragmentCount=static_cast<uint32_t>(segmentCount); sentFrame.fragmentsInQueue=0;//static_cast<uint32_t>(segmentCount); for(size_t seg=0;seg<segmentCount;seg++){ BufferOutputStream pkt(1500); size_t offset=seg*1024; size_t len=MIN(1024, frame.Length()-offset); unsigned char pflags=STREAM_DATA_FLAG_LEN16; //pflags |= STREAM_DATA_FLAG_HAS_MORE_FLAGS; pkt.WriteByte((unsigned char) (stm->id | pflags)); // streamID + flags int16_t lengthAndFlags=static_cast<int16_t>(len & 0x7FF); if(segmentCount>1) lengthAndFlags |= STREAM_DATA_XFLAG_FRAGMENTED; if(flags & VIDEO_FRAME_FLAG_KEYFRAME) lengthAndFlags |= STREAM_DATA_XFLAG_KEYFRAME; pkt.WriteInt16(lengthAndFlags); //pkt.WriteInt32(audioTimestampOut); pkt.WriteInt32(pts); if(segmentCount>1){ pkt.WriteByte((unsigned char)seg); pkt.WriteByte((unsigned char)segmentCount); } //LOGV("Sending segment %u of %u", (unsigned int)seg, (unsigned int)segmentCount); pkt.WriteBytes(frame, offset, len); uint32_t seq=GenerateOutSeq(); size_t pktLength = pkt.GetLength(); PendingOutgoingPacket p{ /*.seq=*/seq, /*.type=*/PKT_STREAM_DATA, /*.len=*/pktLength, /*.data=*/Buffer(move(pkt)), /*.endpoint=*/0, }; unsentStreamPackets++; SendOrEnqueuePacket(move(p)); videoCongestionControl.ProcessPacketSent(static_cast<unsigned int>(pktLength)); sentFrame.unacknowledgedPackets.push_back(seq); } MutexGuard m(sentVideoFramesMutex); sentVideoFrames.push_back(sentFrame); } } void VoIPController::SendStreamCSD(VoIPController::Stream &stream){ assert(stream.csdIsValid); BufferOutputStream os(256); os.WriteByte(stream.id); os.WriteInt16((int16_t)stream.width); os.WriteInt16((int16_t)stream.height); os.WriteByte(static_cast<unsigned char>(stream.codecSpecificData.size())); for(Buffer& b:stream.codecSpecificData){ assert(b.Length()<255); os.WriteByte(static_cast<unsigned char>(b.Length())); os.WriteBytes(b); } Buffer buf(move(os)); SendExtra(buf, EXTRA_TYPE_STREAM_CSD); } void VoIPController::ProcessIncomingVideoFrame(Buffer frame, uint32_t pts, bool keyframe){ //LOGI("Incoming video frame size %u pts %u", (unsigned int)frame.Length(), pts); if(frame.Length()==0){ LOGE("EMPTY FRAME"); } if(videoRenderer){ shared_ptr<Stream> stm=GetStreamByType(STREAM_TYPE_VIDEO, false); if(!stm->csdIsValid){ videoRenderer->Reset(stm->codec, stm->width, stm->height, stm->codecSpecificData); stm->csdIsValid=true; } if(lastReceivedVideoFrameNumber==UINT32_MAX || lastReceivedVideoFrameNumber==pts-1 || keyframe){ lastReceivedVideoFrameNumber=pts; //LOGV("3 before decode %u", (unsigned int)frame.Length()); videoRenderer->DecodeAndDisplay(move(frame), pts); }else{ LOGW("Skipping non-keyframe after packet loss..."); } } } void VoIPController::SetupOutgoingVideoStream(){ vector<uint32_t> myEncoders=video::VideoSource::GetAvailableEncoders(); shared_ptr<Stream> vstm=make_shared<Stream>(); vstm->id=2; vstm->type=STREAM_TYPE_VIDEO; if(find(myEncoders.begin(), myEncoders.end(), CODEC_HEVC)!=myEncoders.end() && find(peerVideoDecoders.begin(), peerVideoDecoders.end(), CODEC_HEVC)!=peerVideoDecoders.end()){ vstm->codec=CODEC_HEVC; }else if(find(myEncoders.begin(), myEncoders.end(), CODEC_AVC)!=myEncoders.end() && find(peerVideoDecoders.begin(), peerVideoDecoders.end(), CODEC_AVC)!=peerVideoDecoders.end()){ vstm->codec=CODEC_AVC; }else if(find(myEncoders.begin(), myEncoders.end(), CODEC_VP8)!=myEncoders.end() && find(peerVideoDecoders.begin(), peerVideoDecoders.end(), CODEC_VP8)!=peerVideoDecoders.end()){ vstm->codec=CODEC_VP8; }else{ LOGW("Can't setup outgoing video stream: no codecs in common"); return; } vstm->enabled=false; outgoingStreams.push_back(vstm); } #pragma mark - Timer methods void VoIPController::SendUdpPings(){ LOGW("Send udp pings"); MutexGuard m(endpointsMutex); for(pair<const int64_t, Endpoint>& e:endpoints){ if(e.second.type==Endpoint::Type::UDP_RELAY){ SendUdpPing(e.second); } } if(udpConnectivityState==UDP_UNKNOWN || udpConnectivityState==UDP_PING_PENDING) udpConnectivityState=UDP_PING_SENT; udpPingCount++; if(udpPingCount==4 || udpPingCount==10){ messageThread.CancelSelf(); udpPingTimeoutID=messageThread.Post(std::bind(&VoIPController::EvaluateUdpPingResults, this), 1.0); } } void VoIPController::EvaluateUdpPingResults(){ double avgPongs=0; int count=0; for(pair<const int64_t, Endpoint>& _e:endpoints){ Endpoint& e=_e.second; if(e.type==Endpoint::Type::UDP_RELAY){ if(e.udpPongCount>0){ avgPongs+=(double) e.udpPongCount; count++; } } } if(count>0) avgPongs/=(double)count; else avgPongs=0.0; LOGI("UDP ping reply count: %.2f", avgPongs); if(avgPongs==0.0 && proxyProtocol==PROXY_SOCKS5 && udpSocket!=realUdpSocket){ LOGI("Proxy does not let UDP through, closing proxy connection and using UDP directly"); NetworkSocket* proxySocket=udpSocket; proxySocket->Close(); udpSocket=realUdpSocket; selectCanceller->CancelSelect(); delete proxySocket; proxySupportsUDP=false; ResetUdpAvailability(); return; } bool configUseTCP=ServerConfig::GetSharedInstance()->GetBoolean("use_tcp", true); if(configUseTCP){ if(avgPongs==0.0 || (udpConnectivityState==UDP_BAD && avgPongs<7.0)){ if(needRateFlags & NEED_RATE_FLAG_UDP_NA) needRate=true; udpConnectivityState=UDP_NOT_AVAILABLE; useTCP=true; useUDP=avgPongs>1.0; if(endpoints.at(currentEndpoint).type!=Endpoint::Type::TCP_RELAY) setCurrentEndpointToTCP=true; AddTCPRelays(); waitingForRelayPeerInfo=false; }else if(avgPongs<3.0){ if(needRateFlags & NEED_RATE_FLAG_UDP_BAD) needRate=true; udpConnectivityState=UDP_BAD; useTCP=true; setCurrentEndpointToTCP=true; AddTCPRelays(); udpPingTimeoutID=messageThread.Post(std::bind(&VoIPController::SendUdpPings, this), 0.5, 0.5); }else{ udpPingTimeoutID=MessageThread::INVALID_ID; udpConnectivityState=UDP_AVAILABLE; } }else{ udpPingTimeoutID=MessageThread::INVALID_ID; udpConnectivityState=UDP_NOT_AVAILABLE; } } void VoIPController::SendRelayPings(){ MutexGuard m(endpointsMutex); if((state==STATE_ESTABLISHED || state==STATE_RECONNECTING) && endpoints.size()>1){ Endpoint* _preferredRelay=&endpoints.at(preferredRelay); Endpoint* _currentEndpoint=&endpoints.at(currentEndpoint); Endpoint* minPingRelay=_preferredRelay; double minPing=_preferredRelay->averageRTT*(_preferredRelay->type==Endpoint::Type::TCP_RELAY ? 2 : 1); if(minPing==0.0) // force the switch to an available relay, if any minPing=DBL_MAX; for(pair<const int64_t, Endpoint>& _endpoint:endpoints){ Endpoint& endpoint=_endpoint.second; if(endpoint.type==Endpoint::Type::TCP_RELAY && !useTCP) continue; if(endpoint.type==Endpoint::Type::UDP_RELAY && !useUDP) continue; if(GetCurrentTime()-endpoint.lastPingTime>=10){ LOGV("Sending ping to %s", endpoint.GetAddress().ToString().c_str()); SendOrEnqueuePacket(PendingOutgoingPacket{ /*.seq=*/(endpoint.lastPingSeq=GenerateOutSeq()), /*.type=*/PKT_PING, /*.len=*/0, /*.data=*/Buffer(), /*.endpoint=*/endpoint.id }); endpoint.lastPingTime=GetCurrentTime(); } if((useUDP && endpoint.type==Endpoint::Type::UDP_RELAY) || (useTCP && endpoint.type==Endpoint::Type::TCP_RELAY)){ double k=endpoint.type==Endpoint::Type::UDP_RELAY ? 1 : 2; if(endpoint.averageRTT>0 && endpoint.averageRTT*k<minPing*relaySwitchThreshold){ minPing=endpoint.averageRTT*k; minPingRelay=&endpoint; } } } if(minPingRelay->id!=preferredRelay){ preferredRelay=minPingRelay->id; _preferredRelay=minPingRelay; LOGV("set preferred relay to %s", _preferredRelay->address.ToString().c_str()); if(_currentEndpoint->type==Endpoint::Type::UDP_RELAY || _currentEndpoint->type==Endpoint::Type::TCP_RELAY){ currentEndpoint=preferredRelay; _currentEndpoint=_preferredRelay; } } if(_currentEndpoint->type==Endpoint::Type::UDP_RELAY && useUDP){ constexpr int64_t p2pID=(int64_t)(FOURCC('P','2','P','4')) << 32; constexpr int64_t lanID=(int64_t)(FOURCC('L','A','N','4')) << 32; if(endpoints.find(p2pID)!=endpoints.end()){ Endpoint& p2p=endpoints[p2pID]; if(endpoints.find(lanID)!=endpoints.end() && endpoints[lanID].averageRTT>0 && endpoints[lanID].averageRTT<minPing*relayToP2pSwitchThreshold){ currentEndpoint=lanID; LOGI("Switching to p2p (LAN)"); }else{ if(p2p.averageRTT>0 && p2p.averageRTT<minPing*relayToP2pSwitchThreshold){ currentEndpoint=p2pID; LOGI("Switching to p2p (Inet)"); } } } }else{ if(minPing>0 && minPing<_currentEndpoint->averageRTT*p2pToRelaySwitchThreshold){ LOGI("Switching to relay"); currentEndpoint=preferredRelay; } } } } void VoIPController::UpdateRTT(){ rttHistory.Add(GetAverageRTT()); //double v=rttHistory.Average(); if(rttHistory[0]>10.0 && rttHistory[8]>10.0 && (networkType==NET_TYPE_EDGE || networkType==NET_TYPE_GPRS)){ waitingForAcks=true; }else{ waitingForAcks=false; } //LOGI("%.3lf/%.3lf, rtt diff %.3lf, waiting=%d, queue=%d", rttHistory[0], rttHistory[8], v, waitingForAcks, sendQueue->Size()); for(vector<shared_ptr<Stream>>::iterator stm=incomingStreams.begin();stm!=incomingStreams.end();++stm){ if((*stm)->jitterBuffer){ int lostCount=(*stm)->jitterBuffer->GetAndResetLostPacketCount(); if(lostCount>0 || (lostCount<0 && recvLossCount>((uint32_t) -lostCount))) recvLossCount+=lostCount; } } } void VoIPController::UpdateCongestion(){ if(conctl && encoder){ uint32_t sendLossCount=conctl->GetSendLossCount(); sendLossCountHistory.Add(sendLossCount-prevSendLossCount); prevSendLossCount=sendLossCount; double packetsPerSec=1000/(double) outgoingStreams[0]->frameDuration; double avgSendLossCount=sendLossCountHistory.Average()/packetsPerSec; //LOGV("avg send loss: %.3f%%", avgSendLossCount*100); if(avgSendLossCount>packetLossToEnableExtraEC && networkType!=NET_TYPE_GPRS && networkType!=NET_TYPE_EDGE){ if(!shittyInternetMode){ // Shitty Internet Mode™. Redundant redundancy you can trust. shittyInternetMode=true; for(shared_ptr<Stream> &s:outgoingStreams){ if(s->type==STREAM_TYPE_AUDIO){ s->extraECEnabled=true; SendStreamFlags(*s); break; } } if(encoder) encoder->SetSecondaryEncoderEnabled(true); LOGW("Enabling extra EC"); if(needRateFlags & NEED_RATE_FLAG_SHITTY_INTERNET_MODE) needRate=true; wasExtraEC=true; } } if(avgSendLossCount>0.08){ extraEcLevel=4; }else if(avgSendLossCount>0.05){ extraEcLevel=3; }else if(avgSendLossCount>0.02){ extraEcLevel=2; }else{ extraEcLevel=0; } encoder->SetPacketLoss((int)(avgSendLossCount*100.0)); if(avgSendLossCount>rateMaxAcceptableSendLoss) needRate=true; if((avgSendLossCount<packetLossToEnableExtraEC || networkType==NET_TYPE_EDGE || networkType==NET_TYPE_GPRS) && shittyInternetMode){ shittyInternetMode=false; for(shared_ptr<Stream> &s:outgoingStreams){ if(s->type==STREAM_TYPE_AUDIO){ s->extraECEnabled=false; SendStreamFlags(*s); break; } } if(encoder) encoder->SetSecondaryEncoderEnabled(false); LOGW("Disabling extra EC"); } if(!wasEncoderLaggy && encoder->GetComplexity()<10) wasEncoderLaggy=true; } } void VoIPController::UpdateAudioBitrate(){ if(encoder && conctl){ double time=GetCurrentTime(); if((audioInput && !audioInput->IsInitialized()) || (audioOutput && !audioOutput->IsInitialized())){ LOGE("Audio I/O failed"); lastError=ERROR_AUDIO_IO; SetState(STATE_FAILED); } int act=conctl->GetBandwidthControlAction(); if(shittyInternetMode){ encoder->SetBitrate(8000); }else if(act==TGVOIP_CONCTL_ACT_DECREASE){ uint32_t bitrate=encoder->GetBitrate(); if(bitrate>8000) encoder->SetBitrate(bitrate<(minAudioBitrate+audioBitrateStepDecr) ? minAudioBitrate : (bitrate-audioBitrateStepDecr)); }else if(act==TGVOIP_CONCTL_ACT_INCREASE){ uint32_t bitrate=encoder->GetBitrate(); if(bitrate<maxBitrate) encoder->SetBitrate(bitrate+audioBitrateStepIncr); } if(state==STATE_ESTABLISHED && time-lastRecvPacketTime>=reconnectingTimeout){ SetState(STATE_RECONNECTING); if(needRateFlags & NEED_RATE_FLAG_RECONNECTING) needRate=true; wasReconnecting=true; ResetUdpAvailability(); } if(state==STATE_ESTABLISHED || state==STATE_RECONNECTING){ if(time-lastRecvPacketTime>=config.recvTimeout){ const Endpoint& _currentEndpoint=endpoints.at(currentEndpoint); if(_currentEndpoint.type!=Endpoint::Type::UDP_RELAY && _currentEndpoint.type!=Endpoint::Type::TCP_RELAY){ LOGW("Packet receive timeout, switching to relay"); currentEndpoint=preferredRelay; for(pair<const int64_t, Endpoint>& _e:endpoints){ Endpoint& e=_e.second; if(e.type==Endpoint::Type::UDP_P2P_INET || e.type==Endpoint::Type::UDP_P2P_LAN){ e.averageRTT=0; e.rtts.Reset(); } } if(allowP2p){ SendPublicEndpointsRequest(); } UpdateDataSavingState(); UpdateAudioBitrateLimit(); BufferOutputStream s(4); s.WriteInt32(dataSavingMode ? INIT_FLAG_DATA_SAVING_ENABLED : 0); if(peerVersion<6){ SendPacketReliably(PKT_NETWORK_CHANGED, s.GetBuffer(), s.GetLength(), 1, 20); }else{ Buffer buf(move(s)); SendExtra(buf, EXTRA_TYPE_NETWORK_CHANGED); } lastRecvPacketTime=time; }else{ LOGW("Packet receive timeout, disconnecting"); lastError=ERROR_TIMEOUT; SetState(STATE_FAILED); } } } } } void VoIPController::UpdateSignalBars(){ int prevSignalBarCount=GetSignalBarsCount(); double packetsPerSec=1000/(double) outgoingStreams[0]->frameDuration; double avgSendLossCount=sendLossCountHistory.Average()/packetsPerSec; int signalBarCount=4; if(state==STATE_RECONNECTING || waitingForAcks) signalBarCount=1; if(endpoints.at(currentEndpoint).type==Endpoint::Type::TCP_RELAY){ signalBarCount=MIN(signalBarCount, 3); } if(avgSendLossCount>0.1){ signalBarCount=1; }else if(avgSendLossCount>0.0625){ signalBarCount=MIN(signalBarCount, 2); }else if(avgSendLossCount>0.025){ signalBarCount=MIN(signalBarCount, 3); } for(shared_ptr<Stream>& stm:incomingStreams){ if(stm->jitterBuffer){ double avgLateCount[3]; stm->jitterBuffer->GetAverageLateCount(avgLateCount); if(avgLateCount[2]>=0.2) signalBarCount=1; else if(avgLateCount[2]>=0.1) signalBarCount=MIN(signalBarCount, 2); } } signalBarsHistory.Add(static_cast<unsigned char>(signalBarCount)); //LOGV("Signal bar count history %08X", *reinterpret_cast<uint32_t *>(&signalBarsHistory)); int _signalBarCount=GetSignalBarsCount(); if(_signalBarCount!=prevSignalBarCount){ LOGD("SIGNAL BAR COUNT CHANGED: %d", _signalBarCount); if(callbacks.signalBarCountChanged) callbacks.signalBarCountChanged(this, _signalBarCount); } } void VoIPController::UpdateQueuedPackets(){ vector<PendingOutgoingPacket> packetsToSend; { MutexGuard m(queuedPacketsMutex); for(std::vector<QueuedPacket>::iterator qp=queuedPackets.begin(); qp!=queuedPackets.end();){ if(qp->timeout>0 && qp->firstSentTime>0 && GetCurrentTime()-qp->firstSentTime>=qp->timeout){ LOGD("Removing queued packet because of timeout"); qp=queuedPackets.erase(qp); continue; } if(GetCurrentTime()-qp->lastSentTime>=qp->retryInterval){ messageThread.Post(std::bind(&VoIPController::UpdateQueuedPackets, this), qp->retryInterval); uint32_t seq=GenerateOutSeq(); qp->seqs.Add(seq); qp->lastSentTime=GetCurrentTime(); //LOGD("Sending queued packet, seq=%u, type=%u, len=%u", seq, qp.type, qp.data.Length()); Buffer buf(qp->data.Length()); if(qp->firstSentTime==0) qp->firstSentTime=qp->lastSentTime; if(qp->data.Length()) buf.CopyFrom(qp->data, qp->data.Length()); packetsToSend.push_back(PendingOutgoingPacket{ /*.seq=*/seq, /*.type=*/qp->type, /*.len=*/qp->data.Length(), /*.data=*/move(buf), /*.endpoint=*/0 }); } ++qp; } } for(PendingOutgoingPacket& pkt:packetsToSend){ SendOrEnqueuePacket(move(pkt)); } } void VoIPController::SendNopPacket(){ if(state!=STATE_ESTABLISHED) return; SendOrEnqueuePacket(PendingOutgoingPacket{ /*.seq=*/(firstSentPing=GenerateOutSeq()), /*.type=*/PKT_NOP, /*.len=*/0, /*.data=*/Buffer(), /*.endpoint=*/0 }); } void VoIPController::SendPublicEndpointsRequest(){ if(!allowP2p) return; LOGI("Sending public endpoints request"); MutexGuard m(endpointsMutex); for(pair<const int64_t, Endpoint>& e:endpoints){ if(e.second.type==Endpoint::Type::UDP_RELAY && !e.second.IsIPv6Only()){ SendPublicEndpointsRequest(e.second); } } publicEndpointsReqCount++; if(publicEndpointsReqCount<10){ messageThread.Post([this]{ if(waitingForRelayPeerInfo){ LOGW("Resending peer relay info request"); SendPublicEndpointsRequest(); } }, 5.0); }else{ publicEndpointsReqCount=0; } } void VoIPController::TickJitterBufferAngCongestionControl(){ // TODO get rid of this and update states of these things internally and retroactively for(shared_ptr<Stream>& stm:incomingStreams){ if(stm->jitterBuffer){ stm->jitterBuffer->Tick(); } } if(conctl){ conctl->Tick(); } } #pragma mark - Endpoint Endpoint::Endpoint(int64_t id, uint16_t port, const IPv4Address& _address, const IPv6Address& _v6address, Type type, unsigned char peerTag[16]) : address(_address), v6address(_v6address){ this->id=id; this->port=port; this->type=type; memcpy(this->peerTag, peerTag, 16); if(type==Type::UDP_RELAY && ServerConfig::GetSharedInstance()->GetBoolean("force_tcp", false)) this->type=Type::TCP_RELAY; lastPingSeq=0; lastPingTime=0; averageRTT=0; socket=NULL; udpPongCount=0; } Endpoint::Endpoint() : address(0), v6address(string("::0")) { lastPingSeq=0; lastPingTime=0; averageRTT=0; socket=NULL; udpPongCount=0; } const NetworkAddress &Endpoint::GetAddress() const{ return IsIPv6Only() ? (NetworkAddress&)v6address : (NetworkAddress&)address; } NetworkAddress &Endpoint::GetAddress(){ return IsIPv6Only() ? (NetworkAddress&)v6address : (NetworkAddress&)address; } bool Endpoint::IsIPv6Only() const{ return address.IsEmpty() && !v6address.IsEmpty(); } Endpoint::~Endpoint(){ if(socket){ socket->Close(); delete socket; } } #pragma mark - AudioInputTester AudioInputTester::AudioInputTester(std::string deviceID) : deviceID(std::move(deviceID)){ io=audio::AudioIO::Create(deviceID, "default"); if(io->Failed()){ LOGE("Audio IO failed"); return; } input=io->GetInput(); input->SetCallback([](unsigned char* data, size_t size, void* ctx) -> size_t{ reinterpret_cast<AudioInputTester*>(ctx)->Update(reinterpret_cast<int16_t*>(data), size/2); return 0; }, this); input->Start(); /*thread=new MessageThread(); thread->Start(); thread->Post([this]{ this->callback(maxSample/(float)INT16_MAX); maxSample=0; }, updateInterval, updateInterval);*/ } AudioInputTester::~AudioInputTester(){ //thread->Stop(); //delete thread; input->Stop(); delete io; } void AudioInputTester::Update(int16_t *samples, size_t count){ for(size_t i=0;i<count;i++){ int16_t s=abs(samples[i]); if(s>maxSample) maxSample=s; } } float AudioInputTester::GetAndResetLevel(){ float s=maxSample; maxSample=0; return s/(float)INT16_MAX; }
31.79693
339
0.713124
openaphid
4f5bc2b9a4b8010053a9632b2ab17252645fba7f
128
cpp
C++
Tracking/Viterbi/Count.cpp
BrockFletcher/BaxterAlgorithms
aeecaa39a782878798036e6724ad5027b7062959
[ "MIT" ]
31
2019-02-22T00:43:47.000Z
2022-03-30T13:39:50.000Z
Tracking/Viterbi/Count.cpp
BrockFletcher/BaxterAlgorithms
aeecaa39a782878798036e6724ad5027b7062959
[ "MIT" ]
17
2019-01-26T19:51:49.000Z
2021-05-15T07:21:57.000Z
Tracking/Viterbi/Count.cpp
BrockFletcher/BaxterAlgorithms
aeecaa39a782878798036e6724ad5027b7062959
[ "MIT" ]
14
2019-10-18T23:08:49.000Z
2022-02-01T21:39:29.000Z
#include "Count.h" Count::Count(int aValue, int aNumScores, const double *aScores) : Variable(aValue, aNumScores, aScores) { }
25.6
63
0.734375
BrockFletcher
4f5be879dc43331155dfeaddfe9858377e21f6e2
4,483
inl
C++
depends/include/CUDA/thrust/detail/backend/cuda/set_difference.inl
mtheory101/hybrid-rendering-thesis
314a200726450e27982e1a95eec3702ad5c9d320
[ "MIT" ]
1
2019-06-14T20:22:21.000Z
2019-06-14T20:22:21.000Z
depends/include/CUDA/thrust/detail/backend/cuda/set_difference.inl
ptrefall/hybrid-rendering-thesis
72be3b3f6b457741737cd83cefb90f2bdbaa46dc
[ "MIT" ]
null
null
null
depends/include/CUDA/thrust/detail/backend/cuda/set_difference.inl
ptrefall/hybrid-rendering-thesis
72be3b3f6b457741737cd83cefb90f2bdbaa46dc
[ "MIT" ]
null
null
null
/* * Copyright 2008-2012 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <thrust/detail/config.h> #if THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC #include <thrust/pair.h> #include <thrust/iterator/iterator_traits.h> #include <thrust/detail/backend/copy.h> #include <thrust/detail/backend/cuda/block/set_difference.h> #include <thrust/detail/backend/cuda/detail/split_for_set_operation.h> #include <thrust/detail/backend/cuda/detail/set_operation.h> namespace thrust { namespace detail { namespace backend { namespace cuda { namespace set_difference_detail { struct block_convergent_set_difference_functor { __host__ __device__ __forceinline__ static size_t get_min_size_of_result_in_number_of_elements(size_t size_of_range1, size_t size_of_range2) { // set_difference could result in 0 output return 0u; } __host__ __device__ __forceinline__ static size_t get_max_size_of_result_in_number_of_elements(size_t size_of_range1, size_t size_of_range2) { // set_difference could output all of range1 return size_of_range1; } __host__ __device__ __forceinline__ static unsigned int get_temporary_array_size_in_number_of_bytes(unsigned int block_size) { return block_size * sizeof(int); } // operator() simply calls the block-wise function template<typename RandomAccessIterator1, typename RandomAccessIterator2, typename RandomAccessIterator3, typename StrictWeakOrdering> __device__ __forceinline__ RandomAccessIterator3 operator()(RandomAccessIterator1 first1, RandomAccessIterator1 last1, RandomAccessIterator2 first2, RandomAccessIterator2 last2, void *temporary, RandomAccessIterator3 result, StrictWeakOrdering comp) { return block::set_difference(first1,last1,first2,last2,reinterpret_cast<int*>(temporary),result,comp); } // end operator()() }; // end block_convergent_set_difference_functor } // end namespace set_difference_detail template<typename RandomAccessIterator1, typename RandomAccessIterator2, typename RandomAccessIterator3, typename Compare> RandomAccessIterator3 set_difference(RandomAccessIterator1 first1, RandomAccessIterator1 last1, RandomAccessIterator2 first2, RandomAccessIterator2 last2, RandomAccessIterator3 result, Compare comp) { typedef typename thrust::iterator_difference<RandomAccessIterator1>::type difference1; typedef typename thrust::iterator_difference<RandomAccessIterator2>::type difference2; const difference1 num_elements1 = last1 - first1; const difference1 num_elements2 = last2 - first2; // check for trivial problem if(num_elements1 == 0) return result; else if(num_elements2 == 0) return thrust::detail::backend::copy(first1, last1, result); return detail::set_operation(first1, last1, first2, last2, result, comp, detail::split_for_set_operation(), set_difference_detail::block_convergent_set_difference_functor()); } // end set_difference } // end namespace cuda } // end namespace backend } // end namespace detail } // end namespace thrust #endif // THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC
36.153226
107
0.642427
mtheory101
4f5c0054a89260c531cf53ac66e033bc22e4d4e2
4,752
cpp
C++
hphp/runtime/ext/vsdebug/stack_trace_command.cpp
ActindoForks/hhvm
670822e2b396f2d411f4e841b4ec9ae8627ba965
[ "PHP-3.01", "Zend-2.0" ]
null
null
null
hphp/runtime/ext/vsdebug/stack_trace_command.cpp
ActindoForks/hhvm
670822e2b396f2d411f4e841b4ec9ae8627ba965
[ "PHP-3.01", "Zend-2.0" ]
null
null
null
hphp/runtime/ext/vsdebug/stack_trace_command.cpp
ActindoForks/hhvm
670822e2b396f2d411f4e841b4ec9ae8627ba965
[ "PHP-3.01", "Zend-2.0" ]
null
null
null
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2017-present Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/ext/vsdebug/debugger.h" #include "hphp/runtime/ext/vsdebug/command.h" #include "hphp/runtime/base/backtrace.h" #include "hphp/runtime/base/tv-variant.h" namespace HPHP { namespace VSDEBUG { StackTraceCommand::StackTraceCommand( Debugger* debugger, folly::dynamic message ) : VSCommand(debugger, message) { } StackTraceCommand::~StackTraceCommand() { } const StaticString s_file("file"); const StaticString s_line("line"); const StaticString s_function("function"); bool StackTraceCommand::executeImpl( DebuggerSession* session, folly::dynamic* responseMsg ) { const int requestId = m_debugger->getCurrentThreadId(); const folly::dynamic& message = getMessage(); const folly::dynamic& args = tryGetObject(message, "arguments", s_emptyArgs); (*responseMsg)["body"] = folly::dynamic::object; folly::dynamic& stackTrace = (*responseMsg)["body"]; stackTrace["stackFrames"] = folly::dynamic::array(); folly::dynamic& frames = stackTrace["stackFrames"]; if (m_debugger->getRequestInfo()->m_pauseRecurseCount == 0) { stackTrace["stackFrames"] = frames; stackTrace["totalFrames"] = 0; (*responseMsg)["body"] = stackTrace; return false; } int startFrame = tryGetInt(args, "startFrame", 0); int levels = tryGetInt(args, "levels", INT_MAX); int levelsAdded = 0; // Respond with a stack trace! auto backtraceArgs = BacktraceArgs() .withSelf() .withPseudoMain() .setParserFrame(nullptr); const Array backtrace = createBacktrace(backtraceArgs); int backtraceSize = backtrace.size(); const ClientPreferences& prefs = m_debugger->getClientPreferences(); for (int depth = 0; depth < backtraceSize - 1; depth++) { if (depth < startFrame) { continue; } if (levelsAdded >= levels) { break; } auto const parentFrame = backtrace.rvalAt(depth + 1).unboxed(); auto const funcName = tvCastToString(parentFrame.val().parr->get(s_function).tv()).data(); auto const frame = backtrace.rvalAt(depth).unboxed(); const auto file = frame.val().parr->get(s_file); const auto line = frame.val().parr->get(s_line); frames.push_back(folly::dynamic::object); folly::dynamic& stackFrame = frames[frames.size() - 1]; stackFrame["id"] = session->generateFrameId(requestId, depth); stackFrame["name"] = funcName; int64_t lineNumber = tvCastToInt64(line.tv()); if (!prefs.linesStartAt1) { lineNumber--; } stackFrame["line"] = lineNumber; stackFrame["column"] = 0; stackFrame["source"] = folly::dynamic::object; folly::dynamic& source = stackFrame["source"]; std::string fileName = tvCastToString(file.tv()).toCppString(); if (fileName.empty()) { // Some routines like builtins and native extensions do not have // a PHP file path in their frame's file name field. fileName = std::string("<unknown>"); } source["name"] = fileName; source["path"] = fileName; levelsAdded++; } if (backtrace.size() == 0) { // The backtrace will be empty if the request is just starting up and hasn't // invoked anything yet. frames.push_back(folly::dynamic::object); folly::dynamic& stackFrame = frames[frames.size() - 1]; stackFrame["id"] = -1; stackFrame["name"] = "{request initializing}"; stackFrame["line"] = 0; stackFrame["column"] = 0; folly::dynamic source = folly::dynamic::object; source["name"] = "<unknown>"; source["path"] = "<unknown>"; stackFrame["source"] = source; } stackTrace["totalFrames"] = backtraceSize == 0 ? 0 : backtraceSize - 1; // Completion of this command does not resume the target. return false; } } }
33.464789
80
0.602062
ActindoForks
4f5e4e436dca0d62eaca086e67a39eb28d5c00b9
2,599
cpp
C++
ironbeepp/tests/test_module_bootstrap_b.cpp
b1v1r/ironbee
97b453afd9c3dc70342c6183a875bde22c9c4a76
[ "Apache-2.0" ]
148
2015-01-10T01:53:39.000Z
2022-03-20T20:48:12.000Z
ironbeepp/tests/test_module_bootstrap_b.cpp
ErikHendriks/ironbee
97b453afd9c3dc70342c6183a875bde22c9c4a76
[ "Apache-2.0" ]
8
2015-03-09T15:50:36.000Z
2020-10-10T19:23:06.000Z
ironbeepp/tests/test_module_bootstrap_b.cpp
ErikHendriks/ironbee
97b453afd9c3dc70342c6183a875bde22c9c4a76
[ "Apache-2.0" ]
46
2015-03-08T22:45:42.000Z
2022-01-15T13:47:59.000Z
/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS 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. ****************************************************************************/ /** * @file * @brief IronBee++ Internals --- Module Bootstrap Tests (B) * * @author Christopher Alfeld <calfeld@qualys.com> **/ #include <ironbeepp/module_bootstrap.hpp> #include "engine_private.h" #include <ironbeepp/test_fixture.hpp> #include "gtest/gtest.h" class TestModuleBootstrapB : public ::testing::Test, public IronBee::TestFixture { }; static bool s_delegate_destructed; static bool s_delegate_initialized; static const ib_module_t* s_ib_module; static ib_context_t* s_ib_context; struct Delegate { Delegate(IronBee::Module m) { s_delegate_initialized = true; s_ib_module = m.ib(); } ~Delegate() { s_delegate_destructed = true; } }; static const char* s_module_name = "test_module_bootstrap_b"; IBPP_BOOTSTRAP_MODULE_DELEGATE(s_module_name, Delegate); TEST_F(TestModuleBootstrapB, basic) { s_delegate_destructed = false; s_delegate_initialized = false; s_ib_module = NULL; s_ib_context = NULL; ib_module_t m = *IB_MODULE_SYM(m_engine.ib()); EXPECT_EQ(s_module_name, m.name); EXPECT_EQ(std::string(__FILE__), m.filename); EXPECT_EQ(m_engine.ib(), m.ib); ib_status_t rc; s_delegate_initialized = false; rc = m.fn_init( m_engine.ib(), &m, m.cbdata_init ); EXPECT_EQ(IB_OK, rc); EXPECT_TRUE(s_delegate_initialized); EXPECT_EQ(&m, s_ib_module); s_delegate_destructed = false; rc = m.fn_fini( m_engine.ib(), &m, m.cbdata_fini ); ASSERT_TRUE(s_delegate_destructed); }
27.357895
78
0.636399
b1v1r
4f5e9d8fb21dc216a02d695b7f045843202c128a
749
cpp
C++
test/test_alarm.cpp
fredrikdanielmoller/p-net
b927ea0440869e27b97865d6505a655132862b8f
[ "BSD-3-Clause" ]
null
null
null
test/test_alarm.cpp
fredrikdanielmoller/p-net
b927ea0440869e27b97865d6505a655132862b8f
[ "BSD-3-Clause" ]
null
null
null
test/test_alarm.cpp
fredrikdanielmoller/p-net
b927ea0440869e27b97865d6505a655132862b8f
[ "BSD-3-Clause" ]
null
null
null
/********************************************************************* * _ _ _ * _ __ | |_ _ | | __ _ | |__ ___ * | '__|| __|(_)| | / _` || '_ \ / __| * | | | |_ _ | || (_| || |_) |\__ \ * |_| \__|(_)|_| \__,_||_.__/ |___/ * * www.rt-labs.com * Copyright 2018 rt-labs AB, Sweden. * * This software is dual-licensed under GPLv3 and a commercial * license. See the file LICENSE.md distributed with this software for * full license information. ********************************************************************/ #include "utils_for_testing.h" #include "mocks.h" #include "pf_includes.h" #include <gtest/gtest.h> class AlarmTest : public PnetIntegrationTest { }; TEST_F (AlarmTest, AlarmRunTest) { }
24.966667
70
0.471295
fredrikdanielmoller
4f61ad84ba1e6fd4d3c573f203f05b76e16b9f11
1,790
hpp
C++
libs/boost_1_72_0/boost/spirit/home/x3/numeric/bool_policies.hpp
henrywarhurst/matrix
317a2a7c35c1c7e3730986668ad2270dc19809ef
[ "BSD-3-Clause" ]
null
null
null
libs/boost_1_72_0/boost/spirit/home/x3/numeric/bool_policies.hpp
henrywarhurst/matrix
317a2a7c35c1c7e3730986668ad2270dc19809ef
[ "BSD-3-Clause" ]
null
null
null
libs/boost_1_72_0/boost/spirit/home/x3/numeric/bool_policies.hpp
henrywarhurst/matrix
317a2a7c35c1c7e3730986668ad2270dc19809ef
[ "BSD-3-Clause" ]
null
null
null
/*============================================================================= Copyright (c) 2009 Hartmut Kaiser Copyright (c) 2014 Joel de Guzman Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ #if !defined(BOOST_SPIRIT_X3_BOOL_POLICIES_SEP_29_2009_0710AM) #define BOOST_SPIRIT_X3_BOOL_POLICIES_SEP_29_2009_0710AM #include <boost/spirit/home/x3/string/detail/string_parse.hpp> #include <boost/spirit/home/x3/support/traits/move_to.hpp> namespace boost { namespace spirit { namespace x3 { /////////////////////////////////////////////////////////////////////////// // Default boolean policies /////////////////////////////////////////////////////////////////////////// template <typename T = bool> struct bool_policies { template <typename Iterator, typename Attribute, typename CaseCompare> static bool parse_true(Iterator &first, Iterator const &last, Attribute &attr_, CaseCompare const &case_compare) { if (detail::string_parse("true", first, last, unused, case_compare)) { traits::move_to(T(true), attr_); // result is true return true; } return false; } template <typename Iterator, typename Attribute, typename CaseCompare> static bool parse_false(Iterator &first, Iterator const &last, Attribute &attr_, CaseCompare const &case_compare) { if (detail::string_parse("false", first, last, unused, case_compare)) { traits::move_to(T(false), attr_); // result is false return true; } return false; } }; } // namespace x3 } // namespace spirit } // namespace boost #endif
38.913043
80
0.586034
henrywarhurst
4f638d5239c108936b3126e87662f0a53c313351
2,618
hpp
C++
naos/tests/kernel/test.hpp
kadds/NaOS
ea5eeed6f777b8f62acf3400b185c94131b6e1f0
[ "BSD-3-Clause" ]
14
2020-02-12T11:07:58.000Z
2022-02-02T00:05:08.000Z
naos/tests/kernel/test.hpp
kadds/NaOS
ea5eeed6f777b8f62acf3400b185c94131b6e1f0
[ "BSD-3-Clause" ]
null
null
null
naos/tests/kernel/test.hpp
kadds/NaOS
ea5eeed6f777b8f62acf3400b185c94131b6e1f0
[ "BSD-3-Clause" ]
4
2020-02-27T09:53:53.000Z
2021-11-07T17:43:44.000Z
#pragma once #include "comm.hpp" #include <functional> #include <iostream> #include <string> #include <thread> int add_test(std::function<void()> f, std::string module, std::string name); #define test(module, name) int x##module##_##name = add_test(test_##module##_##name, #module, #name); #define assert(exp) \ do \ { \ if (!(exp)) \ { \ std::cerr << #exp << " failed at " << __FILE__ << ":" << __LINE__ << std::endl; \ exit(-1); \ } \ } while (0) struct Int { Int(int i, int s = 0) : inner(new int(i)) , v(i) , s(s) { } Int(const Int &rhs) : inner(new int(*rhs.inner)) , v(rhs.v) , s(rhs.s) { } Int(Int &&rhs) : inner(rhs.inner) , v(rhs.v) , s(rhs.s) { rhs.inner = nullptr; rhs.v = 0; rhs.s = 0; } Int &operator=(const Int &rhs) { if (this == &rhs) { return *this; } if (inner) { delete inner; } inner = new int(*rhs.inner); v = rhs.v; s = rhs.s; return *this; } Int &operator=(Int &&rhs) { if (this == &rhs) { return *this; } if (inner) { delete inner; } inner = rhs.inner; v = rhs.v; s = rhs.s; rhs.inner = nullptr; rhs.v = 0; rhs.s = 0; return *this; } bool operator==(const Int &rhs) const { return *inner == *rhs.inner && v == rhs.v && s == rhs.s; } bool operator!=(const Int &rhs) const { return !operator==(rhs); } ~Int() { if (inner) { assert(v == *inner); delete inner; } } int *inner; int v; int s; };
26.444444
120
0.297173
kadds
4f646880a7fb37dd5028b785f9af4096fd609eef
80,294
cpp
C++
src/libawkward/array/UnionArray.cpp
ioanaif/awkward-1.0
22501ba218646dc24dc515c4394eb22f126d340d
[ "BSD-3-Clause" ]
2
2021-06-26T11:31:32.000Z
2021-06-26T11:31:40.000Z
src/libawkward/array/UnionArray.cpp
henryiii/awkward-1.0
d9b8082314911041acc7b1c1b63313d66c2d3315
[ "BSD-3-Clause" ]
null
null
null
src/libawkward/array/UnionArray.cpp
henryiii/awkward-1.0
d9b8082314911041acc7b1c1b63313d66c2d3315
[ "BSD-3-Clause" ]
null
null
null
// BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE #define FILENAME(line) FILENAME_FOR_EXCEPTIONS("src/libawkward/array/UnionArray.cpp", line) #define FILENAME_C(line) FILENAME_FOR_EXCEPTIONS_C("src/libawkward/array/UnionArray.cpp", line) #include <sstream> #include <type_traits> #include "awkward/kernels.h" #include "awkward/kernel-utils.h" #include "awkward/type/UnionType.h" #include "awkward/Reducer.h" #include "awkward/Slice.h" #include "awkward/io/json.h" #include "awkward/array/EmptyArray.h" #include "awkward/array/NumpyArray.h" #include "awkward/array/VirtualArray.h" #define AWKWARD_UNIONARRAY_NO_EXTERN_TEMPLATE #include "awkward/array/UnionArray.h" namespace awkward { ////////// UnionForm UnionForm::UnionForm(bool has_identities, const util::Parameters& parameters, const FormKey& form_key, Index::Form tags, Index::Form index, const std::vector<FormPtr>& contents) : Form(has_identities, parameters, form_key) , tags_(tags) , index_(index) , contents_(contents) { } Index::Form UnionForm::tags() const { return tags_; } Index::Form UnionForm::index() const { return index_; } const std::vector<FormPtr> UnionForm::contents() const { return contents_; } int64_t UnionForm::numcontents() const { return (int64_t)contents_.size(); } const FormPtr UnionForm::content(int64_t index) const { return contents_[(size_t)index]; } const TypePtr UnionForm::type(const util::TypeStrs& typestrs) const { std::vector<TypePtr> types; for (auto item : contents_) { types.push_back(item.get()->type(typestrs)); } return std::make_shared<UnionType>( parameters_, util::gettypestr(parameters_, typestrs), types); } void UnionForm::tojson_part(ToJson& builder, bool verbose) const { builder.beginrecord(); builder.field("class"); if (index_ == Index::Form::i32) { builder.string("UnionArray8_32"); } else if (index_ == Index::Form::u32) { builder.string("UnionArray8_U32"); } else if (index_ == Index::Form::i64) { builder.string("UnionArray8_64"); } else { builder.string("UnrecognizedUnionArray"); } builder.field("tags"); builder.string(Index::form2str(tags_)); builder.field("index"); builder.string(Index::form2str(index_)); builder.field("contents"); builder.beginlist(); for (auto x : contents_) { x.get()->tojson_part(builder, verbose); } builder.endlist(); identities_tojson(builder, verbose); parameters_tojson(builder, verbose); form_key_tojson(builder, verbose); builder.endrecord(); } const FormPtr UnionForm::shallow_copy() const { return std::make_shared<UnionForm>(has_identities_, parameters_, form_key_, tags_, index_, contents_); } const FormPtr UnionForm::with_form_key(const FormKey& form_key) const { return std::make_shared<UnionForm>(has_identities_, parameters_, form_key, tags_, index_, contents_); } const std::string UnionForm::purelist_parameter(const std::string& key) const { std::string out = parameter(key); if (out == std::string("null")) { if (contents_.empty()) { return "null"; } out = contents_[0].get()->purelist_parameter(key); for (size_t i = 1; i < contents_.size(); i++) { if (!contents_[i].get()->parameter_equals(key, out)) { return "null"; } } return out; } else { return out; } } bool UnionForm::purelist_isregular() const { for (auto content : contents_) { if (!content.get()->purelist_isregular()) { return false; } } return true; } int64_t UnionForm::purelist_depth() const { bool first = true; int64_t out = -1; for (auto content : contents_) { if (first) { first = false; out = content.get()->purelist_depth(); } else if (out != content.get()->purelist_depth()) { return -1; } } return out; } bool UnionForm::dimension_optiontype() const { for (auto content : contents_) { if (content.get()->dimension_optiontype()) { return true; } } return false; } const std::pair<int64_t, int64_t> UnionForm::minmax_depth() const { if (contents_.empty()) { return std::pair<int64_t, int64_t>(0, 0); } int64_t min = kMaxInt64; int64_t max = 0; for (auto content : contents_) { std::pair<int64_t, int64_t> minmax = content.get()->minmax_depth(); if (minmax.first < min) { min = minmax.first; } if (minmax.second > max) { max = minmax.second; } } return std::pair<int64_t, int64_t>(min, max); } const std::pair<bool, int64_t> UnionForm::branch_depth() const { bool anybranch = false; int64_t mindepth = -1; for (auto content : contents_) { std::pair<bool, int64_t> content_depth = content.get()->branch_depth(); if (mindepth == -1) { mindepth = content_depth.second; } if (content_depth.first || mindepth != content_depth.second) { anybranch = true; } if (mindepth > content_depth.second) { mindepth = content_depth.second; } } return std::pair<bool, int64_t>(anybranch, mindepth); } int64_t UnionForm::numfields() const { return (int64_t)keys().size(); } int64_t UnionForm::fieldindex(const std::string& key) const { throw std::invalid_argument( std::string("UnionForm breaks the one-to-one relationship " "between fieldindexes and keys") + FILENAME(__LINE__)); } const std::string UnionForm::key(int64_t fieldindex) const { throw std::invalid_argument( std::string("UnionForm breaks the one-to-one relationship " "between fieldindexes and keys") + FILENAME(__LINE__)); } bool UnionForm::haskey(const std::string& key) const { for (auto x : keys()) { if (x == key) { return true; } } return false; } const std::vector<std::string> UnionForm::keys() const { std::vector<std::string> out; if (contents_.empty()) { return out; } out = contents_[0].get()->keys(); for (size_t i = 1; i < contents_.size(); i++) { std::vector<std::string> tmp = contents_[i].get()->keys(); for (int64_t j = (int64_t)out.size() - 1; j >= 0; j--) { bool found = false; for (size_t k = 0; k < tmp.size(); k++) { if (tmp[k] == out[(size_t)j]) { found = true; break; } } if (!found) { out.erase(std::next(out.begin(), j)); } } } return out; } bool UnionForm::equal(const FormPtr& other, bool check_identities, bool check_parameters, bool check_form_key, bool compatibility_check) const { if (compatibility_check) { if (VirtualForm* raw = dynamic_cast<VirtualForm*>(other.get())) { if (raw->form().get() != nullptr) { return equal(raw->form(), check_identities, check_parameters, check_form_key, compatibility_check); } } } if (check_identities && has_identities_ != other.get()->has_identities()) { return false; } if (check_parameters && !util::parameters_equal(parameters_, other.get()->parameters(), false)) { return false; } if (check_form_key && !form_key_equals(other.get()->form_key())) { return false; } if (UnionForm* t = dynamic_cast<UnionForm*>(other.get())) { if (tags_ != t->tags() || index_ != t->index()) { return false; } if (numcontents() != t->numcontents()) { return false; } for (int64_t i = 0; i < numcontents(); i++) { if (!content(i).get()->equal(t->content(i), check_identities, check_parameters, check_form_key, compatibility_check)) { return false; } } return true; } else { return false; } } const FormPtr UnionForm::getitem_field(const std::string& key) const { throw std::invalid_argument( std::string("UnionForm breaks the one-to-one relationship " "between fieldindexes and keys") + FILENAME(__LINE__)); } const FormPtr UnionForm::getitem_fields(const std::vector<std::string>& keys) const { throw std::invalid_argument( std::string("UnionForm breaks the one-to-one relationship " "between fieldindexes and keys") + FILENAME(__LINE__)); } ////////// UnionArray template <> const IndexOf<int32_t> UnionArrayOf<int8_t, int32_t>::sparse_index(int64_t len) { IndexOf<int32_t> outindex(len); struct Error err = kernel::carry_arange<int32_t>( kernel::lib::cpu, // DERIVE outindex.data(), len); util::handle_error(err, "UnionArray", nullptr); return outindex; } template <> const IndexOf<uint32_t> UnionArrayOf<int8_t, uint32_t>::sparse_index(int64_t len) { IndexOf<uint32_t> outindex(len); struct Error err = kernel::carry_arange<uint32_t>( kernel::lib::cpu, // DERIVE outindex.data(), len); util::handle_error(err, "UnionArray", nullptr); return outindex; } template <> const IndexOf<int64_t> UnionArrayOf<int8_t, int64_t>::sparse_index(int64_t len) { IndexOf<int64_t> outindex(len); struct Error err = kernel::carry_arange<int64_t>( kernel::lib::cpu, // DERIVE outindex.data(), len); util::handle_error(err, "UnionArray", nullptr); return outindex; } template <typename T, typename I> const IndexOf<I> UnionArrayOf<T, I>::regular_index(const IndexOf<T>& tags) { int64_t lentags = tags.length(); int64_t size; struct Error err1 = kernel::UnionArray_regular_index_getsize<T>( kernel::lib::cpu, // DERIVE &size, tags.data(), lentags); util::handle_error(err1, "UnionArray", nullptr); IndexOf<I> current(size); IndexOf<I> outindex(lentags); struct Error err2 = kernel::UnionArray_regular_index<T, I>( kernel::lib::cpu, // DERIVE outindex.data(), current.data(), size, tags.data(), lentags); util::handle_error(err2, "UnionArray", nullptr); return outindex; } template <typename T, typename I> const std::pair<IndexOf<T>, IndexOf<I>> UnionArrayOf<T, I>::nested_tags_index(const Index64& offsets, const std::vector<Index64>& counts) { int64_t contentlen = offsets.getitem_at_nowrap(offsets.length() - 1); Index64 tmpstarts = offsets.deep_copy(); IndexOf<T> tags(contentlen); IndexOf<I> index(contentlen); for (T tag = 0; tag < (T)counts.size(); tag++) { struct Error err = kernel::UnionArray_nestedfill_tags_index_64( kernel::lib::cpu, // DERIVE tags.data(), index.data(), tmpstarts.data(), tag, counts[(size_t)tag].data(), tmpstarts.length() - 1); util::handle_error(err, "UnionArray", nullptr); } return std::pair<IndexOf<T>, IndexOf<I>>(tags, index); } template <typename T, typename I> UnionArrayOf<T, I>::UnionArrayOf(const IdentitiesPtr& identities, const util::Parameters& parameters, const IndexOf<T> tags, const IndexOf<I>& index, const ContentPtrVec& contents) : Content(identities, parameters) , tags_(tags) , index_(index) , contents_(contents) { if (contents_.empty()) { throw std::invalid_argument("UnionArray must have at least one content"); } if (index.length() < tags.length()) { throw std::invalid_argument( std::string("UnionArray index must not be shorter than its tags") + FILENAME(__LINE__)); } } template <typename T, typename I> const IndexOf<T> UnionArrayOf<T, I>::tags() const { return tags_; } template <typename T, typename I> const IndexOf<I> UnionArrayOf<T, I>::index() const { return index_; } template <typename T, typename I> const ContentPtrVec UnionArrayOf<T, I>::contents() const { return contents_; } template <typename T, typename I> int64_t UnionArrayOf<T, I>::numcontents() const { return (int64_t)contents_.size(); } template <typename T, typename I> const ContentPtr UnionArrayOf<T, I>::content(int64_t index) const { if (!(0 <= index && index < numcontents())) { throw std::invalid_argument( std::string("index ") + std::to_string(index) + std::string(" out of range for ") + classname() + std::string(" with ") + std::to_string(numcontents()) + std::string(" contents") + FILENAME(__LINE__)); } return contents_[(size_t)index]; } template <typename T, typename I> const ContentPtr UnionArrayOf<T, I>::project(int64_t index) const { if (!(0 <= index && index < numcontents())) { throw std::invalid_argument( std::string("index ") + std::to_string(index) + std::string(" out of range for ") + classname() + std::string(" with ") + std::to_string(numcontents()) + std::string(" contents") + FILENAME(__LINE__)); } int64_t lentags = tags_.length(); if (index_.length() < lentags) { util::handle_error( failure("len(index) < len(tags)", kSliceNone, kSliceNone, FILENAME_C(__LINE__)), classname(), identities_.get()); } int64_t lenout; Index64 tmpcarry(lentags); struct Error err = kernel::UnionArray_project_64<T, I>( kernel::lib::cpu, // DERIVE &lenout, tmpcarry.data(), tags_.data(), index_.data(), lentags, index); util::handle_error(err, classname(), identities_.get()); Index64 nextcarry(tmpcarry.ptr(), 0, lenout, tmpcarry.ptr_lib()); return contents_[(size_t)index].get()->carry(nextcarry, false); } template <typename T, typename I> const ContentPtr UnionArrayOf<T, I>::simplify_uniontype(bool merge, bool mergebool) const { int64_t len = length(); if (index_.length() < len) { util::handle_error( failure("len(index) < len(tags)", kSliceNone, kSliceNone, FILENAME_C(__LINE__)), classname(), identities_.get()); } Index8 tags(len); Index64 index(len); ContentPtrVec contents; for (size_t i = 0; i < contents_.size(); i++) { if (UnionArray8_32* rawcontent = dynamic_cast<UnionArray8_32*>(contents_[i].get())) { Index8 innertags = rawcontent->tags(); Index32 innerindex = rawcontent->index(); ContentPtrVec innercontents = rawcontent->contents(); for (size_t j = 0; j < innercontents.size(); j++) { bool unmerged = true; for (size_t k = 0; k < contents.size(); k++) { if (merge && contents[k].get()->mergeable(innercontents[j], mergebool)) { struct Error err = kernel::UnionArray_simplify8_32_to8_64<T, I>( kernel::lib::cpu, // DERIVE tags.data(), index.data(), tags_.data(), index_.data(), innertags.data(), innerindex.data(), (int64_t)k, (int64_t)j, (int64_t)i, len, contents[k].get()->length()); util::handle_error(err, classname(), identities_.get()); contents[k] = contents[k].get()->merge(innercontents[j]); unmerged = false; break; } } if (unmerged) { struct Error err = kernel::UnionArray_simplify8_32_to8_64<T, I>( kernel::lib::cpu, // DERIVE tags.data(), index.data(), tags_.data(), index_.data(), innertags.data(), innerindex.data(), (int64_t)contents.size(), (int64_t)j, (int64_t)i, len, 0); util::handle_error(err, classname(), identities_.get()); contents.push_back(innercontents[j]); } } } else if (UnionArray8_U32* rawcontent = dynamic_cast<UnionArray8_U32*>(contents_[i].get())) { Index8 innertags = rawcontent->tags(); IndexU32 innerindex = rawcontent->index(); ContentPtrVec innercontents = rawcontent->contents(); for (size_t j = 0; j < innercontents.size(); j++) { bool unmerged = true; for (size_t k = 0; k < contents.size(); k++) { if (merge && contents[k].get()->mergeable(innercontents[j], mergebool)) { struct Error err = kernel::UnionArray_simplify8_U32_to8_64<T, I>( kernel::lib::cpu, // DERIVE tags.data(), index.data(), tags_.data(), index_.data(), innertags.data(), innerindex.data(), (int64_t)k, (int64_t)j, (int64_t)i, len, contents[k].get()->length()); util::handle_error(err, classname(), identities_.get()); contents[k] = contents[k].get()->merge(innercontents[j]); unmerged = false; break; } } if (unmerged) { struct Error err = kernel::UnionArray_simplify8_U32_to8_64<T, I>( kernel::lib::cpu, // DERIVE tags.data(), index.data(), tags_.data(), index_.data(), innertags.data(), innerindex.data(), (int64_t)contents.size(), (int64_t)j, (int64_t)i, len, 0); util::handle_error(err, classname(), identities_.get()); contents.push_back(innercontents[j]); } } } else if (UnionArray8_64* rawcontent = dynamic_cast<UnionArray8_64*>(contents_[i].get())) { Index8 innertags = rawcontent->tags(); Index64 innerindex = rawcontent->index(); ContentPtrVec innercontents = rawcontent->contents(); for (size_t j = 0; j < innercontents.size(); j++) { bool unmerged = true; for (size_t k = 0; k < contents.size(); k++) { if (merge && contents[k].get()->mergeable(innercontents[j], mergebool)) { struct Error err = kernel::UnionArray_simplify8_64_to8_64<T, I>( kernel::lib::cpu, // DERIVE tags.data(), index.data(), tags_.data(), index_.data(), innertags.data(), innerindex.data(), (int64_t)k, (int64_t)j, (int64_t)i, len, contents[k].get()->length()); util::handle_error(err, classname(), identities_.get()); contents[k] = contents[k].get()->merge(innercontents[j]); unmerged = false; break; } } if (unmerged) { struct Error err = kernel::UnionArray_simplify8_64_to8_64<T, I>( kernel::lib::cpu, // DERIVE tags.data(), index.data(), tags_.data(), index_.data(), innertags.data(), innerindex.data(), (int64_t)contents.size(), (int64_t)j, (int64_t)i, len, 0); util::handle_error(err, classname(), identities_.get()); contents.push_back(innercontents[j]); } } } else { bool unmerged = true; for (size_t k = 0; k < contents.size(); k++) { if (contents[k].get()->referentially_equal(contents_[i])) { struct Error err = kernel::UnionArray_simplify_one_to8_64<T, I>( kernel::lib::cpu, // DERIVE tags.data(), index.data(), tags_.data(), index_.data(), (int64_t)k, (int64_t)i, len, 0); util::handle_error(err, classname(), identities_.get()); unmerged = false; break; } else if (merge && contents[k].get()->mergeable(contents_[i], mergebool)) { struct Error err = kernel::UnionArray_simplify_one_to8_64<T, I>( kernel::lib::cpu, // DERIVE tags.data(), index.data(), tags_.data(), index_.data(), (int64_t)k, (int64_t)i, len, contents[k].get()->length()); util::handle_error(err, classname(), identities_.get()); contents[k] = contents[k].get()->merge(contents_[i]); unmerged = false; break; } } if (unmerged) { struct Error err = kernel::UnionArray_simplify_one_to8_64<T, I>( kernel::lib::cpu, // DERIVE tags.data(), index.data(), tags_.data(), index_.data(), (int64_t)contents.size(), (int64_t)i, len, 0); util::handle_error(err, classname(), identities_.get()); contents.push_back(contents_[i]); } } } if (contents.size() > kMaxInt8) { throw std::runtime_error( std::string("FIXME: handle UnionArray with more than 127 contents") + FILENAME(__LINE__)); } if (contents.size() == 1) { return contents[0].get()->carry(index, true); } else { return std::make_shared<UnionArray8_64>(identities_, parameters_, tags, index, contents); } } template <typename T, typename I> const std::string UnionArrayOf<T, I>::classname() const { if (std::is_same<T, int8_t>::value) { if (std::is_same<I, int32_t>::value) { return "UnionArray8_32"; } else if (std::is_same<I, uint32_t>::value) { return "UnionArray8_U32"; } else if (std::is_same<I, int64_t>::value) { return "UnionArray8_64"; } } return "UnrecognizedUnionArray"; } template <typename T, typename I> void UnionArrayOf<T, I>::setidentities() { if (length() <= kMaxInt32) { IdentitiesPtr newidentities = std::make_shared<Identities32>(Identities::newref(), Identities::FieldLoc(), 1, length()); Identities32* rawidentities = reinterpret_cast<Identities32*>(newidentities.get()); struct Error err = kernel::new_Identities<int32_t>( kernel::lib::cpu, // DERIVE rawidentities->data(), length()); util::handle_error(err, classname(), identities_.get()); setidentities(newidentities); } else { IdentitiesPtr newidentities = std::make_shared<Identities64>(Identities::newref(), Identities::FieldLoc(), 1, length()); Identities64* rawidentities = reinterpret_cast<Identities64*>(newidentities.get()); struct Error err = kernel::new_Identities<int64_t>( kernel::lib::cpu, // DERIVE rawidentities->data(), length()); util::handle_error(err, classname(), identities_.get()); setidentities(newidentities); } } template <typename T, typename I> void UnionArrayOf<T, I>::setidentities(const IdentitiesPtr& identities) { if (identities.get() == nullptr) { for (auto content : contents_) { content.get()->setidentities(identities); } } else { if (index_.length() < tags_.length()) { util::handle_error( failure("len(index) < len(tags)", kSliceNone, kSliceNone, FILENAME_C(__LINE__)), classname(), identities_.get()); } if (length() != identities.get()->length()) { util::handle_error( failure("content and its identities must have the same length", kSliceNone, kSliceNone, FILENAME_C(__LINE__)), classname(), identities_.get()); } for (size_t which = 0; which < contents_.size(); which++) { ContentPtr content = contents_[which]; IdentitiesPtr bigidentities = identities; if (content.get()->length() > kMaxInt32 || !std::is_same<I, int32_t>::value) { bigidentities = identities.get()->to64(); } if (Identities32* rawidentities = dynamic_cast<Identities32*>(bigidentities.get())) { bool uniquecontents; IdentitiesPtr subidentities = std::make_shared<Identities32>(Identities::newref(), rawidentities->fieldloc(), rawidentities->width(), content.get()->length()); Identities32* rawsubidentities = reinterpret_cast<Identities32*>(subidentities.get()); struct Error err = kernel::Identities_from_UnionArray<int32_t, T, I>( kernel::lib::cpu, // DERIVE &uniquecontents, rawsubidentities->data(), rawidentities->data(), tags_.data(), index_.data(), content.get()->length(), length(), rawidentities->width(), (int64_t)which); util::handle_error(err, classname(), identities_.get()); if (uniquecontents) { content.get()->setidentities(subidentities); } else { content.get()->setidentities(Identities::none()); } } else if (Identities64* rawidentities = dynamic_cast<Identities64*>(bigidentities.get())) { bool uniquecontents; IdentitiesPtr subidentities = std::make_shared<Identities64>(Identities::newref(), rawidentities->fieldloc(), rawidentities->width(), content.get()->length()); Identities64* rawsubidentities = reinterpret_cast<Identities64*>(subidentities.get()); struct Error err = kernel::Identities_from_UnionArray<int64_t, T, I>( kernel::lib::cpu, // DERIVE &uniquecontents, rawsubidentities->data(), rawidentities->data(), tags_.data(), index_.data(), content.get()->length(), length(), rawidentities->width(), (int64_t)which); util::handle_error(err, classname(), identities_.get()); if (uniquecontents) { content.get()->setidentities(subidentities); } else { content.get()->setidentities(Identities::none()); } } else { throw std::runtime_error( std::string("unrecognized Identities specialization") + FILENAME(__LINE__)); } } } identities_ = identities; } template <typename T, typename I> const TypePtr UnionArrayOf<T, I>::type(const util::TypeStrs& typestrs) const { return form(true).get()->type(typestrs); } template <typename T, typename I> const FormPtr UnionArrayOf<T, I>::form(bool materialize) const { std::vector<FormPtr> contents; for (auto x : contents_) { contents.push_back(x.get()->form(materialize)); } return std::make_shared<UnionForm>(identities_.get() != nullptr, parameters_, FormKey(nullptr), tags_.form(), index_.form(), contents); } template <typename T, typename I> kernel::lib UnionArrayOf<T, I>::kernels() const { kernel::lib last = kernel::lib::size; for (auto content : contents_) { if (last == kernel::lib::size) { last = content.get()->kernels(); } else if (last != content.get()->kernels()) { return kernel::lib::size; } } if (identities_.get() == nullptr) { if (last == kernel::lib::size) { return kernel::lib::cpu; } else { return last; } } else { if (last == kernel::lib::size) { return identities_.get()->ptr_lib(); } else if (last == identities_.get()->ptr_lib()) { return last; } else { return kernel::lib::size; } } } template <typename T, typename I> void UnionArrayOf<T, I>::caches(std::vector<ArrayCachePtr>& out) const { for (auto content : contents_) { content.get()->caches(out); } } template <typename T, typename I> const std::string UnionArrayOf<T, I>::tostring_part(const std::string& indent, const std::string& pre, const std::string& post) const { std::stringstream out; out << indent << pre << "<" << classname() << ">\n"; if (identities_.get() != nullptr) { out << identities_.get()->tostring_part( indent + std::string(" "), "", "\n"); } if (!parameters_.empty()) { out << parameters_tostring(indent + std::string(" "), "", "\n"); } out << tags_.tostring_part( indent + std::string(" "), "<tags>", "</tags>\n"); out << index_.tostring_part( indent + std::string(" "), "<index>", "</index>\n"); for (size_t i = 0; i < contents_.size(); i++) { out << indent << " <content tag=\"" << i << "\">\n"; out << contents_[i].get()->tostring_part( indent + std::string(" "), "", "\n"); out << indent << " </content>\n"; } out << indent << "</" << classname() << ">" << post; return out.str(); } template <typename T, typename I> void UnionArrayOf<T, I>::tojson_part(ToJson& builder, bool include_beginendlist) const { int64_t len = length(); check_for_iteration(); if (include_beginendlist) { builder.beginlist(); } for (int64_t i = 0; i < len; i++) { getitem_at_nowrap(i).get()->tojson_part(builder, true); } if (include_beginendlist) { builder.endlist(); } } template <typename T, typename I> void UnionArrayOf<T, I>::nbytes_part(std::map<size_t, int64_t>& largest) const { for (auto x : contents_) { x.get()->nbytes_part(largest); } if (identities_.get() != nullptr) { identities_.get()->nbytes_part(largest); } } template <typename T, typename I> int64_t UnionArrayOf<T, I>::length() const { return tags_.length(); } template <typename T, typename I> const ContentPtr UnionArrayOf<T, I>::shallow_copy() const { return std::make_shared<UnionArrayOf<T, I>>(identities_, parameters_, tags_, index_, contents_); } template <typename T, typename I> const ContentPtr UnionArrayOf<T, I>::deep_copy(bool copyarrays, bool copyindexes, bool copyidentities) const { IndexOf<T> tags = copyindexes ? tags_.deep_copy() : tags_; IndexOf<I> index = copyindexes ? index_.deep_copy() : index_; ContentPtrVec contents; for (auto x : contents_) { contents.push_back(x.get()->deep_copy(copyarrays, copyindexes, copyidentities)); } IdentitiesPtr identities = identities_; if (copyidentities && identities_.get() != nullptr) { identities = identities_.get()->deep_copy(); } return std::make_shared<UnionArrayOf<T, I>>(identities, parameters_, tags, index, contents); } template <typename T, typename I> void UnionArrayOf<T, I>::check_for_iteration() const { if (index_.length() < tags_.length()) { util::handle_error( failure("len(index) < len(tags)", kSliceNone, kSliceNone, FILENAME_C(__LINE__)), classname(), identities_.get()); } if (identities_.get() != nullptr && identities_.get()->length() < index_.length()) { util::handle_error( failure("len(identities) < len(array)", kSliceNone, kSliceNone, FILENAME_C(__LINE__)), identities_.get()->classname(), nullptr); } } template <typename T, typename I> const ContentPtr UnionArrayOf<T, I>::getitem_nothing() const { return getitem_range_nowrap(0, 0); } template <typename T, typename I> const ContentPtr UnionArrayOf<T, I>::getitem_at(int64_t at) const { int64_t regular_at = at; int64_t len = length(); if (regular_at < 0) { regular_at += len; } if (!(0 <= regular_at && regular_at < len)) { util::handle_error( failure("index out of range", kSliceNone, at, FILENAME_C(__LINE__)), classname(), identities_.get()); } return getitem_at_nowrap(regular_at); } template <typename T, typename I> const ContentPtr UnionArrayOf<T, I>::getitem_at_nowrap(int64_t at) const { size_t tag = (size_t)tags_.getitem_at_nowrap(at); int64_t index = (int64_t)index_.getitem_at_nowrap(at); if (!(0 <= tag && tag < contents_.size())) { util::handle_error( failure("not 0 <= tag[i] < numcontents", kSliceNone, at, FILENAME_C(__LINE__)), classname(), identities_.get()); } ContentPtr content = contents_[tag]; if (!(0 <= index && index < content.get()->length())) { util::handle_error( failure("index[i] > len(content(tag))", kSliceNone, at, FILENAME_C(__LINE__)), classname(), identities_.get()); } return content.get()->getitem_at_nowrap(index); } template <typename T, typename I> const ContentPtr UnionArrayOf<T, I>::getitem_range(int64_t start, int64_t stop) const { int64_t regular_start = start; int64_t regular_stop = stop; kernel::regularize_rangeslice(&regular_start, &regular_stop, true, start != Slice::none(), stop != Slice::none(), tags_.length()); if (identities_.get() != nullptr && regular_stop > identities_.get()->length()) { util::handle_error( failure("index out of range", kSliceNone, stop, FILENAME_C(__LINE__)), identities_.get()->classname(), nullptr); } return getitem_range_nowrap(regular_start, regular_stop); } template <typename T, typename I> const ContentPtr UnionArrayOf<T, I>::getitem_range_nowrap(int64_t start, int64_t stop) const { IdentitiesPtr identities(nullptr); if (identities_.get() != nullptr) { identities = identities_.get()->getitem_range_nowrap(start, stop); } return std::make_shared<UnionArrayOf<T, I>>( identities, parameters_, tags_.getitem_range_nowrap(start, stop), index_.getitem_range_nowrap(start, stop), contents_); } template <typename T, typename I> const ContentPtr UnionArrayOf<T, I>::getitem_field(const std::string& key) const { ContentPtrVec contents; for (auto content : contents_) { contents.push_back(content.get()->getitem_field(key)); } return UnionArrayOf<T, I>(identities_, util::Parameters(), tags_, index_, contents).simplify_uniontype(true, false); } template <typename T, typename I> const ContentPtr UnionArrayOf<T, I>::getitem_field(const std::string& key, const Slice& only_fields) const { ContentPtrVec contents; for (auto content : contents_) { contents.push_back(content.get()->getitem_field(key, only_fields)); } return UnionArrayOf<T, I>(identities_, util::Parameters(), tags_, index_, contents).simplify_uniontype(true, false); } template <typename T, typename I> const ContentPtr UnionArrayOf<T, I>::getitem_fields( const std::vector<std::string>& keys) const { ContentPtrVec contents; for (auto content : contents_) { contents.push_back(content.get()->getitem_fields(keys)); } return UnionArrayOf<T, I>(identities_, util::Parameters(), tags_, index_, contents).simplify_uniontype(true, false); } template <typename T, typename I> const ContentPtr UnionArrayOf<T, I>::getitem_fields( const std::vector<std::string>& keys, const Slice& only_fields) const { ContentPtrVec contents; for (auto content : contents_) { contents.push_back(content.get()->getitem_fields(keys, only_fields)); } return UnionArrayOf<T, I>(identities_, util::Parameters(), tags_, index_, contents).simplify_uniontype(true, false); } template <typename T, typename I> const ContentPtr UnionArrayOf<T, I>::getitem_next(const SliceItemPtr& head, const Slice& tail, const Index64& advanced) const { if (head.get() == nullptr) { return shallow_copy(); } else if (dynamic_cast<SliceAt*>(head.get()) || dynamic_cast<SliceRange*>(head.get()) || dynamic_cast<SliceArray64*>(head.get()) || dynamic_cast<SliceJagged64*>(head.get())) { ContentPtrVec outcontents; for (int64_t i = 0; i < numcontents(); i++) { ContentPtr projection = project(i); outcontents.push_back( projection.get()->getitem_next(head, tail, advanced)); } IndexOf<I> outindex = regular_index(tags_); UnionArrayOf<T, I> out(identities_, parameters_, tags_, outindex, outcontents); return out.simplify_uniontype(true, false); } else if (SliceEllipsis* ellipsis = dynamic_cast<SliceEllipsis*>(head.get())) { return Content::getitem_next(*ellipsis, tail, advanced); } else if (SliceNewAxis* newaxis = dynamic_cast<SliceNewAxis*>(head.get())) { return Content::getitem_next(*newaxis, tail, advanced); } else if (SliceField* field = dynamic_cast<SliceField*>(head.get())) { return Content::getitem_next(*field, tail, advanced); } else if (SliceFields* fields = dynamic_cast<SliceFields*>(head.get())) { return Content::getitem_next(*fields, tail, advanced); } else if (SliceMissing64* missing = dynamic_cast<SliceMissing64*>(head.get())) { return Content::getitem_next(*missing, tail, advanced); } else if (SliceVarNewAxis* varnewaxis = dynamic_cast<SliceVarNewAxis*>(head.get())) { return UnionArrayOf<T, I>::getitem_next(*varnewaxis, tail, advanced); } else { throw std::runtime_error( std::string("unrecognized slice type") + FILENAME(__LINE__)); } } template <typename T, typename I> const ContentPtr UnionArrayOf<T, I>::carry(const Index64& carry, bool allow_lazy) const { if (carry.iscontiguous()) { if (carry.length() == length()) { return shallow_copy(); } else { return getitem_range_nowrap(0, carry.length()); } } int64_t lentags = tags_.length(); if (index_.length() < lentags) { util::handle_error( failure("len(index) < len(tags)", kSliceNone, kSliceNone, FILENAME_C(__LINE__)), classname(), identities_.get()); } int64_t lencarry = carry.length(); IndexOf<T> nexttags(lencarry); struct Error err1 = kernel::Index_carry_64<T>( kernel::lib::cpu, // DERIVE nexttags.data(), tags_.data(), carry.data(), lentags, lencarry); util::handle_error(err1, classname(), identities_.get()); IndexOf<I> nextindex(lencarry); struct Error err2 = kernel::Index_carry_nocheck_64<I>( kernel::lib::cpu, // DERIVE nextindex.data(), index_.data(), carry.data(), lencarry); util::handle_error(err2, classname(), identities_.get()); IdentitiesPtr identities(nullptr); if (identities_.get() != nullptr) { identities = identities_.get()->getitem_carry_64(carry); } return std::make_shared<UnionArrayOf<T, I>>(identities, parameters_, nexttags, nextindex, contents_); } template <typename T, typename I> int64_t UnionArrayOf<T, I>::purelist_depth() const { bool first = true; int64_t out = -1; for (auto content : contents_) { if (first) { first = false; out = content.get()->purelist_depth(); } else if (out != content.get()->purelist_depth()) { return -1; } } return out; } template <typename T, typename I> const std::pair<int64_t, int64_t> UnionArrayOf<T, I>::minmax_depth() const { if (contents_.empty()) { return std::pair<int64_t, int64_t>(0, 0); } int64_t min = kMaxInt64; int64_t max = 0; for (auto content : contents_) { std::pair<int64_t, int64_t> minmax = content.get()->minmax_depth(); if (minmax.first < min) { min = minmax.first; } if (minmax.second > max) { max = minmax.second; } } return std::pair<int64_t, int64_t>(min, max); } template <typename T, typename I> const std::pair<bool, int64_t> UnionArrayOf<T, I>::branch_depth() const { bool anybranch = false; int64_t mindepth = -1; for (auto content : contents_) { std::pair<bool, int64_t> content_depth = content.get()->branch_depth(); if (mindepth == -1) { mindepth = content_depth.second; } if (content_depth.first || mindepth != content_depth.second) { anybranch = true; } if (mindepth > content_depth.second) { mindepth = content_depth.second; } } return std::pair<bool, int64_t>(anybranch, mindepth); } template <typename T, typename I> int64_t UnionArrayOf<T, I>::numfields() const { return (int64_t)keys().size(); } template <typename T, typename I> int64_t UnionArrayOf<T, I>::fieldindex(const std::string& key) const { throw std::invalid_argument( std::string("UnionForm breaks the one-to-one relationship " "between fieldindexes and keys") + FILENAME(__LINE__)); } template <typename T, typename I> const std::string UnionArrayOf<T, I>::key(int64_t fieldindex) const { throw std::invalid_argument( std::string("UnionForm breaks the one-to-one relationship " "between fieldindexes and keys") + FILENAME(__LINE__)); } template <typename T, typename I> bool UnionArrayOf<T, I>::haskey(const std::string& key) const { for (auto x : keys()) { if (x == key) { return true; } } return false; } template <typename T, typename I> const std::vector<std::string> UnionArrayOf<T, I>::keys() const { std::vector<std::string> out; if (contents_.empty()) { return out; } out = contents_[0].get()->keys(); for (size_t i = 1; i < contents_.size(); i++) { std::vector<std::string> tmp = contents_[i].get()->keys(); for (int64_t j = (int64_t)out.size() - 1; j >= 0; j--) { bool found = false; for (size_t k = 0; k < tmp.size(); k++) { if (tmp[k] == out[(size_t)j]) { found = true; break; } } if (!found) { out.erase(std::next(out.begin(), j)); } } } return out; } template <typename T, typename I> const std::string UnionArrayOf<T, I>::validityerror(const std::string& path) const { const std::string paramcheck = validityerror_parameters(path); if (paramcheck != std::string("")) { return paramcheck; } for (int64_t i = 0; i < numcontents(); i++) { if (dynamic_cast<UnionArray8_32*>(content(i).get()) || dynamic_cast<UnionArray8_U32*>(content(i).get()) || dynamic_cast<UnionArray8_64*>(content(i).get())) { return classname() + " contains " + content(i).get()->classname() + ", the operation that made it might have forgotten to call 'simplify_uniontype()'"; } } if (index_.length() < tags_.length()) { return (std::string("at ") + path + std::string(" (") + classname() + std::string("): ") + std::string("len(index) < len(tags)") + FILENAME(__LINE__)); } std::vector<int64_t> lencontents; for (int64_t i = 0; i < numcontents(); i++) { lencontents.push_back(content(i).get()->length()); } struct Error err = kernel::UnionArray_validity<T, I>( kernel::lib::cpu, // DERIVE tags_.data(), index_.data(), tags_.length(), numcontents(), lencontents.data()); if (err.str != nullptr) { return (std::string("at ") + path + std::string(" (") + classname() + std::string("): ") + std::string(err.str) + std::string(" at i=") + std::to_string(err.identity) + std::string(err.filename == nullptr ? "" : err.filename)); } for (int64_t i = 0; i < numcontents(); i++) { std::string sub = content(i).get()->validityerror( path + std::string(".content(") + std::to_string(i) + (")")); if (!sub.empty()) { return sub; } } return std::string(); } template <typename T, typename I> const ContentPtr UnionArrayOf<T, I>::shallow_simplify() const { return simplify_uniontype(true, false); } template <typename T, typename I> const ContentPtr UnionArrayOf<T, I>::num(int64_t axis, int64_t depth) const { int64_t posaxis = axis_wrap_if_negative(axis); if (posaxis == depth) { Index64 out(1); out.setitem_at_nowrap(0, length()); return NumpyArray(out).getitem_at_nowrap(0); } else { ContentPtrVec contents; for (auto content : contents_) { contents.push_back(content.get()->num(posaxis, depth)); } UnionArrayOf<T, I> out(Identities::none(), util::Parameters(), tags_, index_, contents); return out.simplify_uniontype(true, false); } } template <typename T, typename I> const std::pair<Index64, ContentPtr> UnionArrayOf<T, I>::offsets_and_flattened(int64_t axis, int64_t depth) const { int64_t posaxis = axis_wrap_if_negative(axis); if (posaxis == depth) { throw std::invalid_argument( std::string("axis=0 not allowed for flatten") + FILENAME(__LINE__)); } else { bool has_offsets = false; std::vector<std::shared_ptr<int64_t>> offsetsptrs; std::vector<int64_t*> offsetsraws; ContentPtrVec contents; for (auto content : contents_) { std::pair<Index64, ContentPtr> pair = content.get()->offsets_and_flattened(posaxis, depth); Index64 offsets = pair.first; offsetsptrs.push_back(offsets.ptr()); offsetsraws.push_back(offsets.data()); contents.push_back(pair.second); has_offsets = (offsets.length() != 0); } if (has_offsets) { int64_t total_length; struct Error err1 = kernel::UnionArray_flatten_length_64<T, I>( kernel::lib::cpu, // DERIVE &total_length, tags_.data(), index_.data(), tags_.length(), offsetsraws.data()); util::handle_error(err1, classname(), identities_.get()); Index8 totags(total_length); Index64 toindex(total_length); Index64 tooffsets(tags_.length() + 1); struct Error err2 = kernel::UnionArray_flatten_combine_64<T, I>( kernel::lib::cpu, // DERIVE totags.data(), toindex.data(), tooffsets.data(), tags_.data(), index_.data(), tags_.length(), offsetsraws.data()); util::handle_error(err2, classname(), identities_.get()); return std::pair<Index64, ContentPtr>( tooffsets, std::make_shared<UnionArray8_64>(Identities::none(), util::Parameters(), totags, toindex, contents)); } else { return std::pair<Index64, ContentPtr>( Index64(0), std::make_shared<UnionArrayOf<T, I>>(Identities::none(), util::Parameters(), tags_, index_, contents)); } } } template <typename T, typename I> bool UnionArrayOf<T, I>::mergeable(const ContentPtr& other, bool mergebool) const { if (VirtualArray* raw = dynamic_cast<VirtualArray*>(other.get())) { return mergeable(raw->array(), mergebool); } if (!parameters_equal(other.get()->parameters(), false)) { return false; } return true; } template <typename T, typename I> bool UnionArrayOf<T, I>::referentially_equal(const ContentPtr& other) const { if (identities_.get() == nullptr && other.get()->identities().get() != nullptr) { return false; } if (identities_.get() != nullptr && other.get()->identities().get() == nullptr) { return false; } if (identities_.get() != nullptr && other.get()->identities().get() != nullptr) { if (!identities_.get()->referentially_equal(other->identities())) { return false; } } if (UnionArrayOf<T, I>* raw = dynamic_cast<UnionArrayOf<T, I>*>(other.get())) { if (!tags_.referentially_equal(raw->tags()) || !index_.referentially_equal(raw->index())) { return false; } if (numcontents() != raw->numcontents()) { return false; } for (int64_t i = 0; i < numcontents(); i++) { if (!content(i).get()->referentially_equal(raw->content(i))) { return false; } } return true; } else { return false; } } template <typename T, typename I> const ContentPtr UnionArrayOf<T, I>::reverse_merge(const ContentPtr& other) const { if (VirtualArray* raw = dynamic_cast<VirtualArray*>(other.get())) { return reverse_merge(raw->array()); } int64_t theirlength = other.get()->length(); int64_t mylength = length(); Index8 tags(theirlength + mylength); Index64 index(theirlength + mylength); ContentPtrVec contents({ other }); contents.insert(contents.end(), contents_.begin(), contents_.end()); struct Error err1 = kernel::UnionArray_filltags_to8_const( kernel::lib::cpu, // DERIVE tags.data(), 0, theirlength, 0); util::handle_error(err1, classname(), identities_.get()); struct Error err2 = kernel::UnionArray_fillindex_count_64( kernel::lib::cpu, // DERIVE index.data(), 0, theirlength); util::handle_error(err2, classname(), identities_.get()); if (std::is_same<T, int8_t>::value) { struct Error err = kernel::UnionArray_filltags_to8_from8( kernel::lib::cpu, // DERIVE tags.data(), theirlength, reinterpret_cast<int8_t*>(tags_.data()), mylength, 1); util::handle_error(err, classname(), identities_.get()); } else { throw std::runtime_error( std::string("unrecognized UnionArray specialization") + FILENAME(__LINE__)); } if (std::is_same<I, int32_t>::value) { struct Error err = kernel::UnionArray_fillindex<int32_t, int64_t>( kernel::lib::cpu, // DERIVE index.data(), theirlength, reinterpret_cast<int32_t*>(index_.data()), mylength); util::handle_error(err, classname(), identities_.get()); } else if (std::is_same<I, uint32_t>::value) { struct Error err = kernel::UnionArray_fillindex<uint32_t, int64_t>( kernel::lib::cpu, // DERIVE index.data(), theirlength, reinterpret_cast<uint32_t*>(index_.data()), mylength); util::handle_error(err, classname(), identities_.get()); } else if (std::is_same<I, int64_t>::value) { struct Error err = kernel::UnionArray_fillindex<int64_t, int64_t>( kernel::lib::cpu, // DERIVE index.data(), theirlength, reinterpret_cast<int64_t*>(index_.data()), mylength); util::handle_error(err, classname(), identities_.get()); } else { throw std::runtime_error( std::string("unrecognized UnionArray specialization") + FILENAME(__LINE__)); } if (contents.size() > kMaxInt8) { throw std::runtime_error( std::string("FIXME: handle UnionArray with more than 127 contents") + FILENAME(__LINE__)); } util::Parameters parameters(parameters_); util::merge_parameters(parameters, other.get()->parameters()); return std::make_shared<UnionArray8_64>(Identities::none(), parameters, tags, index, contents); } template <typename T, typename I> const std::pair<ContentPtrVec, ContentPtrVec> UnionArrayOf<T, I>::merging_strategy(const ContentPtrVec& others) const { if (others.empty()) { throw std::invalid_argument( std::string("to merge this array with 'others', at least one other " "must be provided") + FILENAME(__LINE__)); } ContentPtrVec head; ContentPtrVec tail; head.push_back(shallow_copy()); for (size_t i = 0; i < others.size(); i++) { ContentPtr other = others[i]; if (VirtualArray* raw = dynamic_cast<VirtualArray*>(other.get())) { head.push_back(raw->array()); } else { head.push_back(other); } } return std::pair<ContentPtrVec, ContentPtrVec>(head, tail); } template <typename T, typename I> const ContentPtr UnionArrayOf<T, I>::mergemany(const ContentPtrVec& others) const { if (others.empty()) { return shallow_copy(); } std::pair<ContentPtrVec, ContentPtrVec> head_tail = merging_strategy(others); ContentPtrVec head = head_tail.first; ContentPtrVec tail = head_tail.second; int64_t total_length = 0; for (auto array : head) { total_length += array.get()->length(); } Index8 nexttags(total_length); Index64 nextindex(total_length); ContentPtrVec nextcontents; int64_t length_so_far = 0; kernel::lib ptr_lib = kernel::lib::cpu; // DERIVE util::Parameters parameters(parameters_); for (auto array : head) { util::merge_parameters(parameters, array.get()->parameters()); if (UnionArray8_32* raw = dynamic_cast<UnionArray8_32*>(array.get())) { Index8 union_tags = raw->tags(); Index32 union_index = raw->index(); ContentPtrVec union_contents = raw->contents(); struct Error err1 = kernel::UnionArray_filltags_to8_from8( ptr_lib, nexttags.data(), length_so_far, union_tags.data(), array.get()->length(), (int64_t)nextcontents.size()); util::handle_error(err1, array.get()->classname(), array.get()->identities().get()); struct Error err2 = kernel::UnionArray_fillindex<int32_t, int64_t>( ptr_lib, nextindex.data(), length_so_far, union_index.data(), array.get()->length()); util::handle_error(err2, array.get()->classname(), array.get()->identities().get()); length_so_far += array.get()->length(); nextcontents.insert(nextcontents.end(), union_contents.begin(), union_contents.end()); } else if (UnionArray8_U32* raw = dynamic_cast<UnionArray8_U32*>(array.get())) { Index8 union_tags = raw->tags(); IndexU32 union_index = raw->index(); ContentPtrVec union_contents = raw->contents(); struct Error err1 = kernel::UnionArray_filltags_to8_from8( ptr_lib, nexttags.data(), length_so_far, union_tags.data(), array.get()->length(), (int64_t)nextcontents.size()); util::handle_error(err1, array.get()->classname(), array.get()->identities().get()); struct Error err2 = kernel::UnionArray_fillindex<uint32_t, int64_t>( ptr_lib, nextindex.data(), length_so_far, union_index.data(), array.get()->length()); util::handle_error(err2, array.get()->classname(), array.get()->identities().get()); length_so_far += array.get()->length(); nextcontents.insert(nextcontents.end(), union_contents.begin(), union_contents.end()); } else if (UnionArray8_64* raw = dynamic_cast<UnionArray8_64*>(array.get())) { Index8 union_tags = raw->tags(); Index64 union_index = raw->index(); ContentPtrVec union_contents = raw->contents(); struct Error err1 = kernel::UnionArray_filltags_to8_from8( ptr_lib, nexttags.data(), length_so_far, union_tags.data(), array.get()->length(), (int64_t)nextcontents.size()); util::handle_error(err1, array.get()->classname(), array.get()->identities().get()); struct Error err2 = kernel::UnionArray_fillindex<int64_t, int64_t>( ptr_lib, nextindex.data(), length_so_far, union_index.data(), array.get()->length()); util::handle_error(err2, array.get()->classname(), array.get()->identities().get()); length_so_far += array.get()->length(); nextcontents.insert(nextcontents.end(), union_contents.begin(), union_contents.end()); } else if (EmptyArray* raw = dynamic_cast<EmptyArray*>(array.get())) { ; } else { struct Error err1 = kernel::UnionArray_filltags_to8_const( ptr_lib, nexttags.data(), length_so_far, array.get()->length(), (int64_t)nextcontents.size()); util::handle_error(err1, array.get()->classname(), array.get()->identities().get()); struct Error err2 = kernel::UnionArray_fillindex_count_64( ptr_lib, nextindex.data(), length_so_far, array.get()->length()); util::handle_error(err2, array.get()->classname(), array.get()->identities().get()); length_so_far += array.get()->length(); nextcontents.push_back(array); } } if (nextcontents.size() > kMaxInt8) { throw std::runtime_error( std::string("FIXME: handle UnionArray with more than 127 contents") + FILENAME(__LINE__)); } ContentPtr next = std::make_shared<UnionArray8_64>(Identities::none(), parameters, nexttags, nextindex, nextcontents); // Given UnionArray's merging_strategy, tail is always empty, but just to be formal... if (tail.empty()) { return next; } ContentPtr reversed = tail[0].get()->reverse_merge(next); if (tail.size() == 1) { return reversed; } else { return reversed.get()->mergemany(ContentPtrVec(tail.begin() + 1, tail.end())); } } template <typename T, typename I> const SliceItemPtr UnionArrayOf<T, I>::asslice() const { ContentPtr simplified = simplify_uniontype(true, false); if (UnionArray8_32* raw = dynamic_cast<UnionArray8_32*>(simplified.get())) { if (raw->numcontents() == 1) { return raw->content(0).get()->asslice(); } else { throw std::invalid_argument( std::string("cannot use a union of different types as a slice") + FILENAME(__LINE__)); } } else if (UnionArray8_U32* raw = dynamic_cast<UnionArray8_U32*>(simplified.get())) { if (raw->numcontents() == 1) { return raw->content(0).get()->asslice(); } else { throw std::invalid_argument( std::string("cannot use a union of different types as a slice") + FILENAME(__LINE__)); } } else if (UnionArray8_64* raw = dynamic_cast<UnionArray8_64*>(simplified.get())) { if (raw->numcontents() == 1) { return raw->content(0).get()->asslice(); } else { throw std::invalid_argument( std::string("cannot use a union of different types as a slice") + FILENAME(__LINE__)); } } else { return simplified.get()->asslice(); } } template <typename T, typename I> const ContentPtr UnionArrayOf<T, I>::fillna(const ContentPtr& value) const { ContentPtrVec contents; for (auto content : contents_) { contents.emplace_back(content.get()->fillna(value)); } UnionArrayOf<T, I> out(identities_, parameters_, tags_, index_, contents); return out.simplify_uniontype(true, false); } template <typename T, typename I> const ContentPtr UnionArrayOf<T, I>::rpad(int64_t target, int64_t axis, int64_t depth) const { int64_t posaxis = axis_wrap_if_negative(axis); if (posaxis == depth) { return rpad_axis0(target, false); } else { ContentPtrVec contents; for (auto content : contents_) { contents.emplace_back(content.get()->rpad(target, posaxis, depth)); } UnionArrayOf<T, I> out(identities_, parameters_, tags_, index_, contents); return out.simplify_uniontype(true, false); } } template <typename T, typename I> const ContentPtr UnionArrayOf<T, I>::rpad_and_clip(int64_t target, int64_t axis, int64_t depth) const { int64_t posaxis = axis_wrap_if_negative(axis); if (posaxis == depth) { return rpad_axis0(target, true); } else { ContentPtrVec contents; for (auto content : contents_) { contents.emplace_back( content.get()->rpad_and_clip(target, posaxis, depth)); } UnionArrayOf<T, I> out(identities_, parameters_, tags_, index_, contents); return out.simplify_uniontype(true, false); } } template <typename T, typename I> const ContentPtr UnionArrayOf<T, I>::reduce_next(const Reducer& reducer, int64_t negaxis, const Index64& starts, const Index64& shifts, const Index64& parents, int64_t outlength, bool mask, bool keepdims) const { ContentPtr simplified = simplify_uniontype(true, true); if (dynamic_cast<UnionArray8_32*>(simplified.get()) || dynamic_cast<UnionArray8_U32*>(simplified.get()) || dynamic_cast<UnionArray8_64*>(simplified.get())) { throw std::invalid_argument( std::string("cannot reduce (call '") + reducer.name() + std::string("' on) an irreducible ") + classname() + FILENAME(__LINE__)); } return simplified.get()->reduce_next(reducer, negaxis, starts, shifts, parents, outlength, mask, keepdims); } template <typename T, typename I> const ContentPtr UnionArrayOf<T, I>::localindex(int64_t axis, int64_t depth) const { int64_t posaxis = axis_wrap_if_negative(axis); if (posaxis == depth) { return localindex_axis0(); } else { ContentPtrVec contents; for (auto content : contents_) { contents.push_back(content.get()->localindex(posaxis, depth)); } return std::make_shared<UnionArrayOf<T, I>>(identities_, util::Parameters(), tags_, index_, contents); } } template <typename T, typename I> const ContentPtr UnionArrayOf<T, I>::combinations(int64_t n, bool replacement, const util::RecordLookupPtr& recordlookup, const util::Parameters& parameters, int64_t axis, int64_t depth) const { if (n < 1) { throw std::invalid_argument( std::string("in combinations, 'n' must be at least 1") + FILENAME(__LINE__)); } int64_t posaxis = axis_wrap_if_negative(axis); if (posaxis == depth) { return combinations_axis0(n, replacement, recordlookup, parameters); } else { ContentPtrVec contents; for (auto content : contents_) { contents.push_back(content.get()->combinations(n, replacement, recordlookup, parameters, posaxis, depth)); } return std::make_shared<UnionArrayOf<T, I>>(identities_, util::Parameters(), tags_, index_, contents); } } template <typename T, typename I> const ContentPtr UnionArrayOf<T, I>::sort_next(int64_t negaxis, const Index64& starts, const Index64& parents, int64_t outlength, bool ascending, bool stable, bool keepdims) const { if (length() == 0) { return shallow_copy(); } ContentPtr simplified = simplify_uniontype(true, true); if (dynamic_cast<UnionArray8_32*>(simplified.get()) || dynamic_cast<UnionArray8_U32*>(simplified.get()) || dynamic_cast<UnionArray8_64*>(simplified.get())) { throw std::invalid_argument( std::string("cannot sort ") + classname() + FILENAME(__LINE__)); } return simplified.get()->sort_next(negaxis, starts, parents, outlength, ascending, stable, keepdims); } template <typename T, typename I> const ContentPtr UnionArrayOf<T, I>::argsort_next(int64_t negaxis, const Index64& starts, const Index64& parents, int64_t outlength, bool ascending, bool stable, bool keepdims) const { if (length() == 0) { return std::make_shared<NumpyArray>(Index64(0)); } ContentPtr simplified = simplify_uniontype(true, true); if (dynamic_cast<UnionArray8_32*>(simplified.get()) || dynamic_cast<UnionArray8_U32*>(simplified.get()) || dynamic_cast<UnionArray8_64*>(simplified.get())) { throw std::invalid_argument( std::string("cannot sort ") + classname() + FILENAME(__LINE__)); } return simplified.get()->argsort_next(negaxis, starts, parents, outlength, ascending, stable, keepdims); } template <typename T, typename I> const ContentPtr UnionArrayOf<T, I>::getitem_next(const SliceAt& at, const Slice& tail, const Index64& advanced) const { throw std::runtime_error( std::string("undefined operation: UnionArray::getitem_next(at)") + FILENAME(__LINE__)); } template <typename T, typename I> const ContentPtr UnionArrayOf<T, I>::getitem_next(const SliceRange& range, const Slice& tail, const Index64& advanced) const { throw std::runtime_error( std::string("undefined operation: UnionArray::getitem_next(range)") + FILENAME(__LINE__)); } template <typename T, typename I> const ContentPtr UnionArrayOf<T, I>::getitem_next(const SliceArray64& array, const Slice& tail, const Index64& advanced) const { throw std::runtime_error( std::string("undefined operation: UnionArray::getitem_next(array)") + FILENAME(__LINE__)); } template <typename T, typename I> const ContentPtr UnionArrayOf<T, I>::getitem_next(const SliceJagged64& jagged, const Slice& tail, const Index64& advanced) const { throw std::runtime_error( std::string("undefined operation: UnionArray::getitem_next(jagged)") + FILENAME(__LINE__)); } template <typename T, typename I> const ContentPtr UnionArrayOf<T, I>::getitem_next_jagged(const Index64& slicestarts, const Index64& slicestops, const SliceArray64& slicecontent, const Slice& tail) const { return getitem_next_jagged_generic<SliceArray64>(slicestarts, slicestops, slicecontent, tail); } template <typename T, typename I> const ContentPtr UnionArrayOf<T, I>::getitem_next_jagged(const Index64& slicestarts, const Index64& slicestops, const SliceMissing64& slicecontent, const Slice& tail) const { return getitem_next_jagged_generic<SliceMissing64>(slicestarts, slicestops, slicecontent, tail); } template <typename T, typename I> const ContentPtr UnionArrayOf<T, I>::getitem_next_jagged(const Index64& slicestarts, const Index64& slicestops, const SliceJagged64& slicecontent, const Slice& tail) const { return getitem_next_jagged_generic<SliceJagged64>(slicestarts, slicestops, slicecontent, tail); } template <typename T, typename I> const ContentPtr UnionArrayOf<T, I>::getitem_next_jagged(const Index64& slicestarts, const Index64& slicestops, const SliceVarNewAxis& slicecontent, const Slice& tail) const { return getitem_next_jagged_generic<SliceVarNewAxis>(slicestarts, slicestops, slicecontent, tail); } template <typename T, typename I> const ContentPtr UnionArrayOf<T, I>::getitem_next(const SliceVarNewAxis& varnewaxis, const Slice& tail, const Index64& advanced) const { throw std::runtime_error( std::string("FIXME: operation not yet implemented: UnionArrayOf<T, I>::getitem_next") + FILENAME(__LINE__)); } template <typename T, typename I> const SliceJagged64 UnionArrayOf<T, I>::varaxis_to_jagged(const SliceVarNewAxis& varnewaxis) const { throw std::runtime_error( std::string("FIXME: operation not yet implemented: UnionArrayOf<T, I>::varaxis_to_jagged") + FILENAME(__LINE__)); } template <typename T, typename I> const ContentPtr UnionArrayOf<T, I>::copy_to(kernel::lib ptr_lib) const { IndexOf<T> tags = tags_.copy_to(ptr_lib); IndexOf<I> index = index_.copy_to(ptr_lib); ContentPtrVec contents; for (auto content : contents_) { contents.push_back(content.get()->copy_to(ptr_lib)); } IdentitiesPtr identities(nullptr); if (identities_.get() != nullptr) { identities = identities_.get()->copy_to(ptr_lib); } return std::make_shared<UnionArrayOf<T, I>>(identities, parameters_, tags, index, contents); } template <typename T, typename I> const ContentPtr UnionArrayOf<T, I>::numbers_to_type(const std::string& name) const { IndexOf<T> tags = tags_.deep_copy(); IndexOf<I> index = index_.deep_copy(); ContentPtrVec contents; for (auto x : contents_) { contents.push_back(x.get()->numbers_to_type(name)); } IdentitiesPtr identities = identities_; if (identities_.get() != nullptr) { identities = identities_.get()->deep_copy(); } return std::make_shared<UnionArrayOf<T, I>>(identities, parameters_, tags, index, contents); } template <typename T, typename I> template <typename S> const ContentPtr UnionArrayOf<T, I>::getitem_next_jagged_generic(const Index64& slicestarts, const Index64& slicestops, const S& slicecontent, const Slice& tail) const { ContentPtr simplified = simplify_uniontype(true, false); if (dynamic_cast<UnionArray8_32*>(simplified.get()) || dynamic_cast<UnionArray8_U32*>(simplified.get()) || dynamic_cast<UnionArray8_64*>(simplified.get())) { throw std::invalid_argument( std::string("cannot apply jagged slices to irreducible union arrays") + FILENAME(__LINE__)); } return simplified.get()->getitem_next_jagged(slicestarts, slicestops, slicecontent, tail); } template <typename T, typename I> bool UnionArrayOf<T, I>::is_unique() const { throw std::runtime_error( std::string("FIXME: operation not yet implemented: UnionArrayOf<T, I>::is_unique") + FILENAME(__LINE__)); } template <typename T, typename I> const ContentPtr UnionArrayOf<T, I>::unique() const { throw std::runtime_error( std::string("FIXME: operation not yet implemented: UnionArrayOf<T, I>::unique") + FILENAME(__LINE__)); } template <typename T, typename I> bool UnionArrayOf<T, I>::is_subrange_equal(const Index64& start, const Index64& stop) const { throw std::runtime_error( std::string("FIXME: operation not yet implemented: UnionArrayOf<T, I>::is_subrange_equal") + FILENAME(__LINE__)); } template class EXPORT_TEMPLATE_INST UnionArrayOf<int8_t, int32_t>; template class EXPORT_TEMPLATE_INST UnionArrayOf<int8_t, uint32_t>; template class EXPORT_TEMPLATE_INST UnionArrayOf<int8_t, int64_t>; }
34.255119
98
0.534598
ioanaif