hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
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
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
0572a28b13f72df24086478cb886eba345f98289
7,309
cpp
C++
Causality/CausalityApplication.cpp
ArcEarth/PPARM
8e22e3f20a90a22940218c243b7fe5e24e754e5b
[ "MIT" ]
3
2016-07-13T18:30:33.000Z
2020-03-31T22:20:34.000Z
Causality/CausalityApplication.cpp
ArcEarth/PPARM
8e22e3f20a90a22940218c243b7fe5e24e754e5b
[ "MIT" ]
null
null
null
Causality/CausalityApplication.cpp
ArcEarth/PPARM
8e22e3f20a90a22940218c243b7fe5e24e754e5b
[ "MIT" ]
5
2016-01-16T14:25:28.000Z
2017-06-12T16:15:18.000Z
#include "pch_bcl.h" #include "CausalityApplication.h" //#include "Content\CubeScene.h" //#include "Content\SampleFpsTextRenderer.h" #include <CommonStates.h> #include <PrimitiveVisualizer.h> #include <ppltasks.h> #include "KinectSensor.h" #include "OculusRift.h" #include "LeapMotion.h" #include "Vicon.h" #include <tinyxml2.h> #include "Tests.h" using namespace Causality; using namespace std; namespace sys = std::tr2::sys; using namespace DirectX; using namespace DirectX::Scene; string g_AppManifest = "App.xml"; //std::wstring sceneFile = L"SelectorScene.xml"; App::App() { } App::~App() { for (auto& pCom : Components) { UnregisterComponent(pCom.get()); } } bool App::OnStartup(const std::vector<std::string>& args) { using namespace tinyxml2; tinyxml2::XMLDocument appDoc(true, Whitespace::COLLAPSE_WHITESPACE); auto error = appDoc.LoadFile(g_AppManifest.c_str()); if (error != XML_SUCCESS) { string message = "Failed to load or parse file : " + g_AppManifest; MessageBoxA(NULL, message.c_str(), "Startup failed", MB_OK); return false; } auto appSettings = appDoc.FirstChildElement("application"); if (!appSettings) { MessageBoxA(NULL, "App.xml is not formated correct", "Startup failed", MB_OK); return false; } auto windowSettings = appSettings->FirstChildElement("window"); auto consoleSettings = appSettings->FirstChildElement("console"); string assetDir; GetParam(appSettings->FirstChildElement("assets"), "path", assetDir); string scenestr; GetParam(appSettings->FirstChildElement("scenes"), "path", scenestr); m_assetsDir = assetDir; path sceneFile = scenestr; if (m_assetsDir.empty()) m_assetsDir = sys::current_path(); else if (m_assetsDir.is_relative()) m_assetsDir = sys::current_path() / m_assetsDir; if (sceneFile.is_relative()) sceneFile = m_assetsDir / sceneFile; if (!sys::exists(sceneFile)) { string message = "Secen file doest exist : " + sceneFile.string(); MessageBoxA(NULL, message.c_str(), "Startup failed", MB_OK); return false; } string title = "No title"; GetParam(appSettings, "title", title); unsigned width = 1280, height = 720; int x, y; bool fullscreen = false; // Initialize Windows if (consoleSettings) { GetParam(consoleSettings, "width", width); GetParam(consoleSettings, "height", height); GetParam(consoleSettings, "fullscreen", fullscreen); GetParam(consoleSettings, "left", x); GetParam(consoleSettings, "top", y); pConsole = make_shared<DebugConsole>(); pConsole->Initialize(title, width, height, fullscreen); pConsole->Move(x, y); } bool runTest = false; GetParam(appSettings, "run_test", runTest); if (runTest && !TestManager::RunTest()) { std::cout << "[Error] Test Failed! Press any key to exit" << std::endl; return false; } if (windowSettings) { GetParam(windowSettings, "width", width); GetParam(windowSettings, "height", height); GetParam(windowSettings, "fullscreen", fullscreen); GetParam(windowSettings, "left", x); GetParam(windowSettings, "top", y); } pWindow = make_shared<NativeWindow>(); if (!pRift) { pWindow->Initialize(title, width, height, fullscreen); pWindow->Move(x, y); } else { //auto res = pRift->Resoulution(); Vector2 res = { 1920, 1080 }; pWindow->Initialize(std::string(title), (unsigned)res.x, (unsigned)res.y, false); } //bool useOvr = Devices::OculusRift::Initialize(); // Initialize DirectX pDeviceResources = make_shared<DirectX::DeviceResources>(); pDeviceResources->SetNativeWindow(pWindow->Handle()); // Register to be notified if the Device is lost or recreated pDeviceResources->RegisterDeviceNotify(this); pWindow->SizeChanged += MakeEventHandler(&App::OnResize, this); //return; pDeviceResources->GetD3DDevice()->AddRef(); pDeviceResources->GetD3DDeviceContext()->AddRef(); pDevice.Attach(pDeviceResources->GetD3DDevice()); pContext.Attach(pDeviceResources->GetD3DDeviceContext()); Visualizers::g_PrimitiveDrawer.Initialize(pContext.Get()); // Oculus Rift //if (pRift) //{ // if (!pRift->InitializeGraphics(pWindow->Handle(), pDeviceResources.get())) // pRift = nullptr; //} SetupDevices(appSettings); //auto loadingScene = new Scene; //Scenes.emplace_back(loadingScene); //loadingScene->SetRenderDeviceAndContext(pDevice, pContext); //loadingScene->SetCanvas(pDeviceResources->GetBackBufferRenderTarget()); Scenes.emplace_back(new Scene); auto& scene = Scenes.back(); scene->SetRenderDeviceAndContext(pDevice.Get(), pContext.Get()); scene->SetHudRenderDevice(pDeviceResources->GetD2DFactory(), pDeviceResources->GetD2DDeviceContext(), pDeviceResources->GetDWriteFactory()); scene->SetCanvas(pDeviceResources->GetBackBufferRenderTarget()); concurrency::task<void> loadScene([sceneFile,&scene]() { cout << "Current Directory :" << sys::current_path() << endl; cout << "Loading [Scene](" << sceneFile << ") ..." << endl; CoInitializeEx(NULL, COINIT::COINIT_APARTMENTTHREADED); scene->LoadFromFile(sceneFile.string()); CoUninitialize(); cout << "[Scene] Loading Finished!"; }); return true; } void App::SetupDevices(const ParamArchive* arch) { bool enable = false; auto setting = arch->FirstChildElement("vicon"); GetParam(setting, "enable", enable); if (setting && enable) { pVicon = Devices::IViconClient::Create(); if (pVicon) { pVicon->Initialize(setting); pVicon->Start(); } } #if defined(__HAS_LEAP__) setting = arch->FirstChildElement("leap"); GetParam(setting, "enable", enable); if (setting && enable) { pLeap = Devices::LeapSensor::GetForCurrentView(); pLeap->Initialize(setting); } #endif #if defined(__HAS_KINECT__) setting = arch->FirstChildElement("kinect"); GetParam(setting, "enable", enable); if (setting && enable) { pKinect = Devices::KinectSensor::GetForCurrentView(); if (pKinect) { XMMATRIX kinectCoord = XMMatrixRigidTransform( XMQuaternionRotationRollPitchYaw(-XM_PI / 12.0f, XM_PI, 0), // Orientation XMVectorSet(0, 0.0, 1.0f, 1.0f)); // Position pKinect->SetDeviceCoordinate(kinectCoord); //pKinect->Start(); } } #endif } void App::OnExit() { } bool App::OnIdle() { if (pLeap && !pLeap->IsAsychronize()) pLeap->Update(); if (pVicon && !pVicon->IsAsychronize()) pVicon->Update(); if (pKinect && !pKinect->IsAsychronize()) pKinect->Update(); for (auto& pScene : Scenes) { pScene->Update(); } pDeviceResources->GetBackBufferRenderTarget().Clear(pContext.Get()); for (auto& pScene : Scenes) { pScene->Render(pContext.Get()); } pDeviceResources->Present(); return true; } void App::OnDeviceLost() { } void App::OnDeviceRestored() { } void App::OnResize(Vector2 size) { //pDeviceResources->SetLogicalSize(DeviceResources::Size(size.x,size.y)); //auto& bb = pDeviceResources->GetBackBufferRenderTarget(); //for (auto& scene : Scenes) //{ // scene->SetCanvas(bb); //} } path App::GetResourcesDirectory() const { return m_assetsDir.wstring(); } void App::SetResourcesDirectory(const std::wstring & dir) { m_assetsDir = dir; }
25.735915
142
0.682857
[ "render", "vector" ]
0574d5dce2c9f90c3761973a30fdf404d925b134
2,645
cpp
C++
source/code/utilities/filesystem/files/moving/lib.cpp
luxe/CodeLang-compiler
78837d90bdd09c4b5aabbf0586a5d8f8f0c1e76a
[ "MIT" ]
33
2019-05-30T07:43:32.000Z
2021-12-30T13:12:32.000Z
source/code/utilities/filesystem/files/moving/lib.cpp
luxe/CodeLang-compiler
78837d90bdd09c4b5aabbf0586a5d8f8f0c1e76a
[ "MIT" ]
371
2019-05-16T15:23:50.000Z
2021-09-04T15:45:27.000Z
source/code/utilities/filesystem/files/moving/lib.cpp
UniLang/compiler
c338ee92994600af801033a37dfb2f1a0c9ca897
[ "MIT" ]
6
2019-08-22T17:37:36.000Z
2020-11-07T07:15:32.000Z
#include "code/utilities/filesystem/files/moving/lib.hpp" #include "code/utilities/program/call/lib.hpp" #include "code/utilities/filesystem/files/getting/lib.hpp" #include "code/utilities/types/vectors/transformers/lib.hpp" #include "code/utilities/filesystem/files/observers/lstat_wrap/lib.hpp" #include "code/utilities/filesystem/files/deleting/lib.hpp" #include "code/utilities/filesystem/files/observers/other/lib.hpp" #include "code/utilities/filesystem/files/creating/lib.hpp" #include "code/utilities/types/strings/transformers/removing/lib.hpp" #include <iostream> void Copy_File_And_Follow_Symlink(std::string file, std::string to){ execute("cp -rfHL " + file + " " + to); } void Copy_Folder_To_Path(std::string folder_name, std::string directory_to_copy_to){ execute("cp -rf " + folder_name + " " + directory_to_copy_to); } void Copy_File_To_Dir(std::string file, std::string dir){ execute("cp -rf " + file + " " + dir); } void Copy_Dereferenced_File_To_Dir(std::string file, std::string dir){ execute("cp -rfL " + file + " " + dir); } void Copy_Folder_Contents_To_Path(std::string folder_name, std::string directory_to_copy_to){ execute("cp -rf " + folder_name + "/* " + directory_to_copy_to); } void Copy_Files_To_Current_Directory(std::vector<std::string> const& files){ for (auto const& it: files){ execute("cp -f " + it + " ."); } } void Copy_Folder_Contents_To_Path_Only_If_Contents_Are_Different(std::string folder_name, std::string directory_to_copy_to){ //get all the files we might want to copy over auto from_files = Recursively_Get_All_Paths_To_Files_From_Path(folder_name); //first element is the name of the directories. don't want that Remove_First_Element(from_files); //remove directories std::vector<std::string> new_from_files; for (auto & it: from_files){ if (!Is_Directory(it)){ new_from_files.push_back(it); } } //trim off the base directory names for (auto & it: new_from_files){ Remove_First_N_Chars(it,folder_name.size()+1); } //copy over only the files that have different content //if the file doesn't exist where we are copying it to, it will not be the same and thus copied over for (auto & it: new_from_files){ auto from_file = folder_name + "/" + it; auto to_file = directory_to_copy_to + "/" + it; if (!Files_Are_The_Same(from_file,to_file)){ Create_File_Even_If_The_Path_Doesnt_Exist(to_file); std::string command = std::string("cp -f ") + from_file + " " + to_file; std::cout << command << std::endl; execute_quietly(command); } } }
37.253521
124
0.710775
[ "vector" ]
0574d8b0f874f64a28b8784d4b085a395f177195
1,697
hpp
C++
projects/robots/gctronic/e-puck/plugins/robot_windows/botstudio/core/AutomatonObjectRepresentation.hpp
awesome-archive/webots
8e74fb8393d1e3a6540749afc492635c43f1b30f
[ "Apache-2.0" ]
2
2019-07-12T13:47:44.000Z
2019-08-17T02:53:54.000Z
projects/robots/gctronic/e-puck/plugins/robot_windows/botstudio/core/AutomatonObjectRepresentation.hpp
golbh/webots
8e74fb8393d1e3a6540749afc492635c43f1b30f
[ "Apache-2.0" ]
null
null
null
projects/robots/gctronic/e-puck/plugins/robot_windows/botstudio/core/AutomatonObjectRepresentation.hpp
golbh/webots
8e74fb8393d1e3a6540749afc492635c43f1b30f
[ "Apache-2.0" ]
1
2019-07-13T17:58:04.000Z
2019-07-13T17:58:04.000Z
// Copyright 1996-2018 Cyberbotics Ltd. // // 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. /* * Description: Class redefining a QGraphicsTextItem */ #ifndef AUTOMATON_OBJECT_REPRESENTATION_HPP #define AUTOMATON_OBJECT_REPRESENTATION_HPP #include <QtWidgets/QGraphicsTextItem> class AutomatonObject; class AutomatonObjectRepresentation : public QGraphicsTextItem { Q_OBJECT public: explicit AutomatonObjectRepresentation(AutomatonObject *object); virtual ~AutomatonObjectRepresentation() {} virtual void initialize(); QPointF computeCenter() const; AutomatonObject *automatonObject() const { return mAutomatonObject; } virtual QVariant itemChange(GraphicsItemChange change, const QVariant &value); signals: void selectionChanged(bool newValue); void positionChanged(); public slots: void propagateSelection(bool newValue); void propagatePosition(); void propagateName(); void emitPositionChanged(); void updateSelection(); void updateName(); void updatePosition(); private: virtual void focusOutEvent(QFocusEvent *event); virtual void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event); AutomatonObject *mAutomatonObject; }; #endif
27.819672
80
0.777843
[ "object" ]
0579a0dcd91ec2e8fa9c2f4be3e5b9f228cddce4
6,574
cpp
C++
libraries/plugins/non_consensus/non_consensus_plugin.cpp
LianshuOne/yoyow-core
fba1274b79f85110febd66aab428473ad75148a7
[ "MIT" ]
1
2019-06-11T09:00:42.000Z
2019-06-11T09:00:42.000Z
libraries/plugins/non_consensus/non_consensus_plugin.cpp
LianshuOne/yoyow-core
fba1274b79f85110febd66aab428473ad75148a7
[ "MIT" ]
null
null
null
libraries/plugins/non_consensus/non_consensus_plugin.cpp
LianshuOne/yoyow-core
fba1274b79f85110febd66aab428473ad75148a7
[ "MIT" ]
null
null
null
/* * Copyright (c) YOYOW-team., and contributors. * * The MIT License * * 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 <graphene/non_consensus/non_consensus_plugin.hpp> #include <graphene/chain/impacted.hpp> #include <graphene/chain/account_evaluator.hpp> #include <graphene/chain/account_object.hpp> #include <graphene/chain/config.hpp> #include <graphene/chain/database.hpp> #include <graphene/chain/evaluator.hpp> #include <graphene/chain/operation_history_object.hpp> #include <graphene/chain/transaction_evaluation_state.hpp> #include <fc/smart_ref_impl.hpp> #include <fc/thread/thread.hpp> namespace graphene { namespace non_consensus { namespace detail { using namespace non_consensus; class non_consensus_plugin_impl { public: non_consensus_plugin_impl(non_consensus_plugin& _plugin) : _self( _plugin ) { } virtual ~non_consensus_plugin_impl(){}; non_consensus_plugin& _self; graphene::chain::database& database() { return _self.database(); } void update_custom_vote(const account_uid_type& account, asset delta); void create_custom_vote_index(const custom_vote_cast_operation & op); }; void non_consensus_plugin_impl::update_custom_vote(const account_uid_type& account,asset delta) { graphene::chain::database& db = database(); const auto& custom_vote_idx = db.get_index_type<custom_vote_index>().indices().get<by_creater>(); const auto& cast_vote_idx = db.get_index_type<cast_custom_vote_index>().indices().get<by_custom_vote_asset_id>(); auto cast_vote_itr = cast_vote_idx.lower_bound(std::make_tuple(account, delta.asset_id, db.head_block_time())); while (cast_vote_itr != cast_vote_idx.end() && cast_vote_itr->voter == account && cast_vote_itr->vote_asset_id == delta.asset_id) { auto custom_vote_itr = custom_vote_idx.find(std::make_tuple(cast_vote_itr->custom_vote_creater, cast_vote_itr->custom_vote_vid)); FC_ASSERT(custom_vote_itr != custom_vote_idx.end(), "custom vote ${id} not found.", ("id", cast_vote_itr->custom_vote_vid)); db.modify(*custom_vote_itr, [&](custom_vote_object& obj) { for (const auto& v : cast_vote_itr->vote_result) obj.vote_result.at(v) += delta.amount.value; }); ++cast_vote_itr; } } void non_consensus_plugin_impl::create_custom_vote_index(const custom_vote_cast_operation & op) { graphene::chain::database& db = database(); auto custom_vote_obj = db.find_custom_vote_by_vid(op.custom_vote_creater, op.custom_vote_vid); auto votes = db.get_balance(op.voter, custom_vote_obj->vote_asset_id).amount; const auto& cast_idx = db.get_index_type<cast_custom_vote_index>().indices().get<by_custom_voter>(); auto cast_itr = cast_idx.find(std::make_tuple(op.voter, op.custom_vote_creater, op.custom_vote_vid)); if (cast_itr == cast_idx.end()) { db.create<cast_custom_vote_object>([&](cast_custom_vote_object& obj) { obj.voter = op.voter; obj.custom_vote_creater = op.custom_vote_creater; obj.custom_vote_vid = op.custom_vote_vid; obj.vote_result = op.vote_result; obj.vote_asset_id = custom_vote_obj->vote_asset_id; obj.vote_expired_time = custom_vote_obj->vote_expired_time; }); db.modify(*custom_vote_obj, [&](custom_vote_object& obj) { for (const auto& v : op.vote_result) obj.vote_result.at(v) += votes.value; }); } else { db.modify(*custom_vote_obj, [&](custom_vote_object& obj) { for (const auto& v : cast_itr->vote_result) obj.vote_result.at(v) -= votes.value; for (const auto& v : op.vote_result) obj.vote_result.at(v) += votes.value; }); db.modify(*cast_itr, [&](cast_custom_vote_object& obj) { obj.vote_result = op.vote_result; }); } } } void non_consensus_plugin::plugin_initialize(const boost::program_options::variables_map& options) { const std::vector<std::string>& ops = options["non_consensus_indexs"].as<std::vector<std::string>>(); std::transform(ops.begin(), ops.end(), std::inserter(non_consensus_indexs, non_consensus_indexs.end()), [&](const std::string& s){return s;}); if(non_consensus_indexs.count("customer_vote")){ database().balance_adjusted.connect( [&]( const account_uid_type& account,const asset& delta){ my->update_custom_vote(account,delta); } ); database().update_non_consensus_index.connect( [&]( const operation& op) { if(op.which()==operation::tag<custom_vote_cast_operation>::value) my->create_custom_vote_index(op.get<custom_vote_cast_operation>()); }); } } void non_consensus_plugin::plugin_startup() { } non_consensus_plugin::non_consensus_plugin() : my( new detail::non_consensus_plugin_impl(*this) ) { } std::string non_consensus_plugin::plugin_name()const { return "non_consensus"; } non_consensus_plugin::~non_consensus_plugin() { } void non_consensus_plugin::plugin_set_program_options( boost::program_options::options_description& cli, boost::program_options::options_description& cfg ) { cli.add_options()("non_consensus_indexs", boost::program_options::value<std::vector<std::string>>()->composing()->multitoken(), "add non consensus index"); cfg.add(cli); } } }
39.365269
159
0.696988
[ "vector", "transform" ]
057cb6f7d261d89f177d2c314735464e239bb9a6
4,210
cpp
C++
controller/src/user_panel.cpp
danielmohansahu/cleanup-robot
a74b636855200bf2cbfbaebc69b35d588ccd3609
[ "MIT" ]
1
2020-12-01T00:52:37.000Z
2020-12-01T00:52:37.000Z
controller/src/user_panel.cpp
danielmohansahu/cleanup-robot
a74b636855200bf2cbfbaebc69b35d588ccd3609
[ "MIT" ]
1
2020-12-14T04:21:30.000Z
2020-12-14T04:21:30.000Z
controller/src/user_panel.cpp
danielmohansahu/cleanup-robot
a74b636855200bf2cbfbaebc69b35d588ccd3609
[ "MIT" ]
1
2021-03-10T00:08:47.000Z
2021-03-10T00:08:47.000Z
/** * @file user_panel.cpp * @brief Implementation of custom RVIZ user panel for control * * @copyright [2020] <Daniel Sahu, Spencer Elyard, Santosh Kesani> */ /* * Copyright (c) 2011, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "user_panel.h" #include <stdio.h> #include <geometry_msgs/Twist.h> // Tell pluginlib about this class. Every class which should be // loadable by pluginlib::ClassLoader must have these two lines // compiled in its .cpp file, outside of any namespace scope. #include <pluginlib/class_list_macros.h> #include <QPainter> #include <QLineEdit> #include <QVBoxLayout> #include <QHBoxLayout> #include <QLabel> #include <QTimer> #include <QPushButton> #include <string> namespace cleanup { // BEGIN_TUTORIAL // Here is the implementation of the TeleopPanel class. TeleopPanel // has these responsibilities: // // - Act as a container for GUI elements DriveWidget and QLineEdit. // - Publish command velocities 10 times per second (whether 0 or not). // - Saving and restoring internal state from a config file. // // We start with the constructor, doing the standard Qt thing of // passing the optional *parent* argument on to the superclass // constructor, and also zero-ing the velocities we will be // publishing. UserPanel::UserPanel(QWidget* parent) : rviz::Panel(parent), client_("controller/set_mode") { // add buttons to send specific goals QHBoxLayout* button_layout = new QHBoxLayout; button_layout->addWidget( new QLabel("Behaviors:")); // explore behavior explore_button_ = new QPushButton("Explore"); button_layout->addWidget(explore_button_); // clean behavior clean_button_ = new QPushButton("Clean"); button_layout->addWidget(clean_button_); // stop behavior stop_button_ = new QPushButton("Stop"); button_layout->addWidget(stop_button_); // Lay out the topic field above the control widget. QVBoxLayout* layout = new QVBoxLayout; layout->addLayout(button_layout); setLayout(layout); // Next we make signal/slot connections. connect(explore_button_, SIGNAL(clicked()), this, SLOT(explore())); connect(clean_button_, SIGNAL(clicked()), this, SLOT(clean())); connect(stop_button_, SIGNAL(clicked()), this, SLOT(stop())); } void UserPanel::explore() { sendGoal("explore"); } void UserPanel::clean() { sendGoal("clean"); } void UserPanel::stop() { client_.cancelAllGoals(); } // Send a navigation goal. void UserPanel::sendGoal(const std::string& mode) { // construct goal object controller::SetModeGoal goal; goal.mode = mode; client_.sendGoal(goal); } } // end namespace cleanup PLUGINLIB_EXPORT_CLASS(cleanup::UserPanel, rviz::Panel)
33.149606
78
0.739905
[ "object" ]
057fe98c296d336083c03323b0664b77968e8d2a
10,984
cpp
C++
components/render/opengl_driver/sources/platform/glx/glx_output.cpp
untgames/funner
c91614cda55fd00f5631d2bd11c4ab91f53573a3
[ "MIT" ]
7
2016-03-30T17:00:39.000Z
2017-03-27T16:04:04.000Z
components/render/opengl_driver/sources/platform/glx/glx_output.cpp
untgames/Funner
c91614cda55fd00f5631d2bd11c4ab91f53573a3
[ "MIT" ]
4
2017-11-21T11:25:49.000Z
2018-09-20T17:59:27.000Z
components/render/opengl_driver/sources/platform/glx/glx_output.cpp
untgames/Funner
c91614cda55fd00f5631d2bd11c4ab91f53573a3
[ "MIT" ]
4
2016-11-29T15:18:40.000Z
2017-03-27T16:04:08.000Z
#include "shared.h" using namespace render::low_level; using namespace render::low_level::opengl; using namespace render::low_level::opengl::glx; namespace { /* Константы */ const int GAMMA_RAMP_SIZE = 256; //базовый размер гаммы } /* Описание реализации устройства вывода */ typedef xtl::com_ptr<Adapter> AdapterPtr; typedef stl::vector<OutputModeDesc> OutputModeArray; struct Output::Impl { Log log; //протокол графического драйвера OutputModeArray modes; //режимы работы устройства Display* display; //соединение с дисплеем int screen_number; //номер экрана дисплея stl::string name; //имя OutputModeDesc default_mode_desc; ///Конструктор Impl (Display* in_display, int in_screen_number) : display (in_display) , screen_number (in_screen_number) , name(common::format ("screen%u", in_screen_number)) { #ifdef HAS_XRANDR DisplayLock lock (display); int event_base = 0, error_base = 0; /* if (!XRRQueryExtension (display, &event_base, &error_base)) throw xtl::format_operation_exception ("render::low_level::opengl::glx::Output::Impl::Impl", "RandR extension missing"); int sizes_count = 0, depths_count = 0; XRRScreenSize *sizes = XRRSizes (display, screen_number, &sizes_count); int *depths = XListDepths (display, screen_number, &depths_count); if (!depths_count) { static int default_depths = 0; depths = &default_depths; depths_count = 1; } for (int size_id=0; size_id<sizes_count; size_id++) { int rates_count = 0; short *rates = XRRRates (display, screen_number, size_id, &rates_count); if (!rates_count) { static short default_rate = 0; rates_count = 1; rates = &default_rate; } for (int rate_id=0; rate_id<rates_count; rate_id++) { for (int depth_id=0; depth_id<depths_count; depth_id++) { OutputModeDesc mode_desc; mode_desc.width = sizes [size_id].width; mode_desc.height = sizes [size_id].height; mode_desc.color_bits = depths [depth_id]; mode_desc.refresh_rate = rates [rate_id]; modes.push_back (mode_desc); } } } */ #endif } ///Деструктор ~Impl () { } }; /* Конструктор / деструктор */ Output::Output (Display* display, int screen_number) { try { if (!display) throw xtl::make_null_argument_exception ("", "display"); if (screen_number < 0) throw xtl::make_null_argument_exception ("", "screen_number"); impl = new Impl (display, screen_number); GetCurrentMode (impl->default_mode_desc); } catch (xtl::exception& exception) { exception.touch ("render::low_level::opengl::glx::Output::Output"); throw; } } Output::~Output () { try { SetCurrentMode (impl->default_mode_desc); } catch (...) { } } /* Получение имени */ const char* Output::GetName () { return impl->name.c_str (); } /* Получение номера экрана */ int Output::GetScreenNumber () { return impl->screen_number; } /* Получение списка видео-режимов */ size_t Output::GetModesCount () { return impl->modes.size (); } void Output::GetModeDesc (size_t mode_index, OutputModeDesc& mode_desc) { if (mode_index >= impl->modes.size ()) throw xtl::make_range_exception ("render::low_level::opengl::glx::Output::GetModeDesc", "mode_index", mode_index, impl->modes.size ()); mode_desc = impl->modes [mode_index]; } /* Установка текущего видео-режима */ namespace { #ifdef HAS_XRANDR void raise_format_not_supported_exception (const OutputModeDesc& mode_desc) { throw xtl::format_not_supported_exception ("render::low_level::opengl::glx::Output::SetModeDesc", "Screen mode '%dx%dx%d@%d' not supported", mode_desc.width, mode_desc.height, mode_desc.color_bits, mode_desc.refresh_rate); } #endif } void Output::SetCurrentMode (const OutputModeDesc& mode_desc) { #ifdef HAS_XRANDR // блокировка дисплея DisplayLock lock (impl->display); // получение корневого окна Window root = RootWindow (impl->display, impl->screen_number); // получение конфигурации экрана XRRScreenConfiguration *conf = XRRGetScreenInfo (impl->display, root); // получение текущего разрешения и ориентации экрана Rotation original_rotation = 0; SizeID original_size_id = XRRConfigCurrentConfiguration (conf, &original_rotation); short original_rate = XRRConfigCurrentRate (conf); // получение всех доступных расрешений int sizes_count = 0; SizeID size_id = 0; XRRScreenSize* sizes = XRRSizes (impl->display, impl->screen_number, &sizes_count); // поиск запрашиваемого разрешения в списке доступных for (size_id=0; size_id<sizes_count; size_id++) { if (sizes [size_id].width == (int)mode_desc.width && sizes [size_id].height == (int)mode_desc.height) break; } // если не нашли, то выбрасываем исключение if (size_id == sizes_count) raise_format_not_supported_exception (mode_desc); // получение всех доступных частот для запрашиваемого разрешения int rates_count = 0, rate_id = 0; short *rates = XRRRates (impl->display, impl->screen_number, size_id, &rates_count); // если доступных частот нет, то выбрасываем исключение if (!rates_count) raise_format_not_supported_exception (mode_desc); // поиск запрашиваемой частоты for (rate_id=0; rate_id<rates_count; rate_id++) { if (rates [rate_id] == (int)mode_desc.refresh_rate) break; } // если частота не найдена, то выбрасываем исключение if (rate_id == rates_count) raise_format_not_supported_exception (mode_desc); // глубина цвета окна указывается при его создании и не может быть изменена // возможный вариант установки глубины цвета - пересоздание корневого или клиентского окна // если текущие разрешение и частота совпадают с запрашиваемыми, то ничего не делаем if (original_size_id == size_id && original_rate == rates [rate_id]) return; // установка конфигурации экрана Status status = XRRSetScreenConfigAndRate (impl->display, conf, root, size_id, original_rotation, mode_desc.refresh_rate, CurrentTime); // если установка завершилась с ошибкой, то выбрасываем исключение if (status < Success) throw xtl::format_operation_exception ("render::low_level::opengl::glx::Output::SetModeDesc", "XRRSetScreenConfigAndRate failed"); */ #else throw xtl::format_operation_exception ("render::low_level::opengl::glx::Output::SetModeDesc", "Mode changes not supported (no Xrandr)"); #endif } void Output::RestoreDefaultMode () { try { SetCurrentMode (impl->default_mode_desc); } catch (xtl::exception& e) { e.touch ("render::low_level::opengl::glx::Output::RestoreDefaultMode"); throw; } } void Output::GetCurrentMode (OutputModeDesc& mode_desc) { // блокировка дисплея DisplayLock lock (impl->display); // получение конфигурации экрана mode_desc.width = DisplayWidth (impl->display, impl->screen_number); mode_desc.height = DisplayHeight (impl->display, impl->screen_number); mode_desc.color_bits = DefaultDepth (impl->display, impl->screen_number); #ifdef HAS_XRANDR Window root = RootWindow (impl->display, impl->screen_number); XRRScreenConfiguration* conf = XRRGetScreenInfo (impl->display, root); mode_desc.refresh_rate = XRRConfigCurrentRate (conf); #else mode_desc.refresh_rate = 0; #endif } /* Управление гамма-коррекцией */ void Output::SetGammaRamp (const Color3f table [GAMMA_RAMP_SIZE]) { #ifdef HAS_X86VMODE int error_base; // запрос расширения XF86VidMode if (XF86VidModeQueryExtension (impl->display, &event_base, &error_base) == 0) throw xtl::format_operation_exception ("render::low_level::opengl::glx::Output::GetGammaRamp", "XF86VidModeQueryExtension missing"); stl::vector<unsigned short> red (GAMMA_RAMP_SIZE); stl::vector<unsigned short> green (GAMMA_RAMP_SIZE); stl::vector<unsigned short> blue (GAMMA_RAMP_SIZE); // преобразование гаммы for (int i=0; i<GAMMA_RAMP_SIZE; i++) { red [i] = (unsigned short)(table [i].red * 65535.f); green [i] = (unsigned short)(table [i].green * 65535.f); blue [i] = (unsigned short)(table [i].blue * 65535.f); } // установка гаммы XF86VidModeSetGammaRamp (impl->display, impl->screen_number, GAMMA_RAMP_SIZE, &red[0], &green[0], &blue[0]); */ #else throw xtl::format_not_supported_exception ("render::low_level::opengl::glx::Output::SetGammaRamp", "Gamma ramp not supported (X86VMode not supported)"); #endif } void Output::GetGammaRamp (Color3f table [GAMMA_RAMP_SIZE]) { #ifdef HAS_X86VMODE // блокировка дисплея DisplayLock lock (impl->display); int size = 0; int event_base; int error_base; // запрос расширения XF86VidMode if (XF86VidModeQueryExtension (impl->display, &event_base, &error_base) == 0) throw xtl::format_operation_exception ("render::low_level::opengl::glx::Output::GetGammaRamp", "XF86VidModeQueryExtension missing"); // получение размера гаммы if (!XF86VidModeGetGammaRampSize(impl->display, impl->screen_number, &size)) throw xtl::format_operation_exception ("render::low_level::opengl::glx::Output::GetGammaRamp", "failed to get XF86VidModeGetGammaRampSize"); // проверка корректности размера гаммы if (size != GAMMA_RAMP_SIZE) throw xtl::format_operation_exception ("render::low_level::opengl::glx::Output::GetGammaRamp", "bad gamma ramp size: %d", size); // получение гаммы stl::vector<unsigned short> red (size); stl::vector<unsigned short> green (size); stl::vector<unsigned short> blue (size); XF86VidModeGetGammaRamp (impl->display, impl->screen_number, size, &red[0], &green[0], &blue[0]); // преобразование гаммы for (int i=0; i<size; i++) { table [i].red = red [i] / 65535.f; table [i].green = green [i] / 65535.f; table [i].blue = blue [i] / 65535.f; }*/ #else throw xtl::format_not_supported_exception ("render::low_level::opengl::glx::Output::GetGammaRamp", "Gamma ramp not supported (X86VMode not supported)"); #endif }
28.020408
155
0.644119
[ "render", "vector" ]
058687573bacc56b0bc8d0fdc1aad1edb4a321e9
14,653
cpp
C++
XML/testsuite/src/XMLStreamParserTest.cpp
e0861280/poco
961ca3e246f55646ab6e101e35e3ec0db359360f
[ "BSL-1.0" ]
null
null
null
XML/testsuite/src/XMLStreamParserTest.cpp
e0861280/poco
961ca3e246f55646ab6e101e35e3ec0db359360f
[ "BSL-1.0" ]
null
null
null
XML/testsuite/src/XMLStreamParserTest.cpp
e0861280/poco
961ca3e246f55646ab6e101e35e3ec0db359360f
[ "BSL-1.0" ]
1
2019-10-21T03:40:54.000Z
2019-10-21T03:40:54.000Z
// // XMLStreamParserTest.cpp // // $Id$ // // Copyright (c) 2015, Applied Informatics Software Engineering GmbH. // and Contributors. // // SPDX-License-Identifier: BSL-1.0 // #include "XMLStreamParserTest.h" #include "Poco/CppUnit/TestCaller.h" #include "Poco/CppUnit/TestSuite.h" #include "Poco/XML/XMLStreamParser.h" #include "Poco/Exception.h" #include <sstream> #include <string> #include <vector> #include <iostream> using namespace Poco::XML; XMLStreamParserTest::XMLStreamParserTest(const std::string& name): CppUnit::TestCase(name) { } XMLStreamParserTest::~XMLStreamParserTest() { } void XMLStreamParserTest::testParser() { // Test error handling. // try { std::istringstream is("<root><nested>X</nasted></root>"); XMLStreamParser p(is, "test"); assert(p.next() == XMLStreamParser::EV_START_ELEMENT); assert(p.next() == XMLStreamParser::EV_START_ELEMENT); assert(p.next() == XMLStreamParser::EV_CHARACTERS && p.value() == "X"); p.next(); assert(false); } catch (const Poco::Exception&) { // cerr << e.what () << endl; } try { std::istringstream is("<root/>"); is.exceptions(std::ios_base::badbit | std::ios_base::failbit); XMLStreamParser p(is, "test"); is.setstate(std::ios_base::badbit); p.next(); assert(false); } catch (const std::ios_base::failure&) { } // Test the nextExpect() functionality. // { std::istringstream is("<root/>"); XMLStreamParser p(is, "test"); p.nextExpect(XMLStreamParser::EV_START_ELEMENT, "root"); p.nextExpect(XMLStreamParser::EV_END_ELEMENT); } try { std::istringstream is("<root/>"); XMLStreamParser p(is, "test"); p.nextExpect(XMLStreamParser::EV_END_ELEMENT); assert(false); } catch (const Poco::Exception&) { // cerr << e.what () << endl; } try { std::istringstream is("<root/>"); XMLStreamParser p(is, "test"); p.nextExpect(XMLStreamParser::EV_START_ELEMENT, "root1"); assert(false); } catch (const Poco::Exception&) { // cerr << e.what () << endl; } // Test nextExpect() with content setting. // { std::istringstream is("<root> </root>"); XMLStreamParser p(is, "empty"); p.nextExpect(XMLStreamParser::EV_START_ELEMENT, "root", Content::Empty); p.nextExpect(XMLStreamParser::EV_END_ELEMENT); p.nextExpect(XMLStreamParser::EV_EOF); } // Test namespace declarations. // { // Followup end element event that should be precedeeded by end // namespace declaration. // std::istringstream is("<root xmlns:a='a'/>"); XMLStreamParser p(is, "test", XMLStreamParser::RECEIVE_DEFAULT | XMLStreamParser::RECEIVE_NAMESPACE_DECLS); p.nextExpect(XMLStreamParser::EV_START_ELEMENT, "root"); p.nextExpect(XMLStreamParser::EV_START_NAMESPACE_DECL); p.nextExpect(XMLStreamParser::EV_END_NAMESPACE_DECL); p.nextExpect(XMLStreamParser::EV_END_ELEMENT); } // Test value extraction. // { std::istringstream is("<root>123</root>"); XMLStreamParser p(is, "test"); p.nextExpect(XMLStreamParser::EV_START_ELEMENT, "root"); p.nextExpect(XMLStreamParser::EV_CHARACTERS); assert(p.value<int>() == 123); p.nextExpect(XMLStreamParser::EV_END_ELEMENT); } // Test attribute maps. // { std::istringstream is("<root a='a' b='b' d='123' t='true'/>"); XMLStreamParser p(is, "test"); p.nextExpect(XMLStreamParser::EV_START_ELEMENT, "root"); assert(p.attribute("a") == "a"); assert(p.attribute("b", "B") == "b"); assert(p.attribute("c", "C") == "C"); assert(p.attribute<int>("d") == 123); assert(p.attribute<bool>("t") == true); assert(p.attribute("f", false) == false); p.nextExpect(XMLStreamParser::EV_END_ELEMENT); } { std::istringstream is("<root a='a'><nested a='A'><inner/></nested></root>"); XMLStreamParser p(is, "test"); p.nextExpect(XMLStreamParser::EV_START_ELEMENT, "root"); assert(p.attribute("a") == "a"); assert(p.peek() == XMLStreamParser::EV_START_ELEMENT && p.localName() == "nested"); assert(p.attribute("a") == "a"); p.nextExpect(XMLStreamParser::EV_START_ELEMENT, "nested"); assert(p.attribute("a") == "A"); p.nextExpect(XMLStreamParser::EV_START_ELEMENT, "inner"); assert(p.attribute("a", "") == ""); p.nextExpect(XMLStreamParser::EV_END_ELEMENT); assert(p.attribute("a") == "A"); assert(p.peek() == XMLStreamParser::EV_END_ELEMENT); assert(p.attribute("a") == "A"); // Still valid. p.nextExpect(XMLStreamParser::EV_END_ELEMENT); assert(p.attribute("a") == "a"); p.nextExpect(XMLStreamParser::EV_END_ELEMENT); assert(p.attribute("a", "") == ""); } try { std::istringstream is("<root a='a' b='b'/>"); XMLStreamParser p(is, "test"); p.nextExpect(XMLStreamParser::EV_START_ELEMENT, "root"); assert(p.attribute("a") == "a"); p.nextExpect(XMLStreamParser::EV_END_ELEMENT); assert(false); } catch (const Poco::Exception&) { // cerr << e.what () << endl; } try { std::istringstream is("<root a='abc'/>"); XMLStreamParser p(is, "test"); p.nextExpect(XMLStreamParser::EV_START_ELEMENT, "root"); p.attribute<int>("a"); assert(false); } catch (const Poco::Exception&) { // cerr << e.what () << endl; } // Test peeking and getting the current event. // { std::istringstream is("<root x='x'>x<nested/></root>"); XMLStreamParser p(is, "peek", XMLStreamParser::RECEIVE_DEFAULT | XMLStreamParser::RECEIVE_ATTRIBUTES_EVENT); assert(p.event() == XMLStreamParser::EV_EOF); assert(p.peek() == XMLStreamParser::EV_START_ELEMENT); assert(p.next() == XMLStreamParser::EV_START_ELEMENT); assert(p.event() == XMLStreamParser::EV_START_ELEMENT); assert(p.peek() == XMLStreamParser::EV_START_ATTRIBUTE); assert(p.event() == XMLStreamParser::EV_START_ATTRIBUTE); assert(p.next() == XMLStreamParser::EV_START_ATTRIBUTE); assert(p.peek() == XMLStreamParser::EV_CHARACTERS && p.value() == "x"); assert(p.next() == XMLStreamParser::EV_CHARACTERS && p.value() == "x"); assert(p.event() == XMLStreamParser::EV_CHARACTERS && p.value() == "x"); assert(p.peek() == XMLStreamParser::EV_END_ATTRIBUTE); assert(p.event() == XMLStreamParser::EV_END_ATTRIBUTE); assert(p.next() == XMLStreamParser::EV_END_ATTRIBUTE); assert(p.peek() == XMLStreamParser::EV_CHARACTERS && p.value() == "x"); assert(p.next() == XMLStreamParser::EV_CHARACTERS && p.value() == "x"); assert(p.event() == XMLStreamParser::EV_CHARACTERS && p.value() == "x"); assert(p.peek() == XMLStreamParser::EV_START_ELEMENT); assert(p.next() == XMLStreamParser::EV_START_ELEMENT); assert(p.event() == XMLStreamParser::EV_START_ELEMENT); assert(p.peek() == XMLStreamParser::EV_END_ELEMENT); assert(p.next() == XMLStreamParser::EV_END_ELEMENT); assert(p.event() == XMLStreamParser::EV_END_ELEMENT); assert(p.peek() == XMLStreamParser::EV_END_ELEMENT); assert(p.next() == XMLStreamParser::EV_END_ELEMENT); assert(p.event() == XMLStreamParser::EV_END_ELEMENT); assert(p.peek() == XMLStreamParser::EV_EOF); assert(p.next() == XMLStreamParser::EV_EOF); assert(p.event() == XMLStreamParser::EV_EOF); } // Test content processing. // // empty // { std::istringstream is("<root x=' x '> \n\t </root>"); XMLStreamParser p(is, "empty", XMLStreamParser::RECEIVE_DEFAULT | XMLStreamParser::RECEIVE_ATTRIBUTES_EVENT); assert(p.next() == XMLStreamParser::EV_START_ELEMENT); p.content(Content::Empty); assert(p.next() == XMLStreamParser::EV_START_ATTRIBUTE); assert(p.next() == XMLStreamParser::EV_CHARACTERS && p.value() == " x "); assert(p.next() == XMLStreamParser::EV_END_ATTRIBUTE); assert(p.next() == XMLStreamParser::EV_END_ELEMENT); assert(p.next() == XMLStreamParser::EV_EOF); } try { std::istringstream is("<root> \n &amp; X \t </root>"); XMLStreamParser p(is, "empty"); assert(p.next() == XMLStreamParser::EV_START_ELEMENT); p.content(Content::Empty); p.next(); assert(false); } catch (const Poco::Exception&) { // cerr << e.what () << endl; } // simple // { std::istringstream is("<root> X </root>"); XMLStreamParser p(is, "simple"); assert(p.next() == XMLStreamParser::EV_START_ELEMENT); p.content(Content::Simple); assert(p.next() == XMLStreamParser::EV_CHARACTERS && p.value() == " X "); assert(p.next() == XMLStreamParser::EV_END_ELEMENT); assert(p.next() == XMLStreamParser::EV_EOF); } try { std::istringstream is("<root> ? <nested/></root>"); XMLStreamParser p(is, "simple"); assert(p.next() == XMLStreamParser::EV_START_ELEMENT); p.content(Content::Simple); assert(p.next() == XMLStreamParser::EV_CHARACTERS && p.value() == " ? "); p.next(); assert(false); } catch (const Poco::Exception&) { // cerr << e.what () << endl; } { // Test content accumulation in simple content. // std::istringstream is("<root xmlns:a='a'>1&#x32;3</root>"); XMLStreamParser p(is, "simple", XMLStreamParser::RECEIVE_DEFAULT | XMLStreamParser::RECEIVE_NAMESPACE_DECLS); assert(p.next() == XMLStreamParser::EV_START_ELEMENT); p.nextExpect(XMLStreamParser::EV_START_NAMESPACE_DECL); p.content(Content::Simple); assert(p.next() == XMLStreamParser::EV_CHARACTERS && p.value() == "123"); p.nextExpect(XMLStreamParser::EV_END_NAMESPACE_DECL); assert(p.next() == XMLStreamParser::EV_END_ELEMENT); assert(p.next() == XMLStreamParser::EV_EOF); } try { // Test error handling in accumulation in simple content. // std::istringstream is("<root xmlns:a='a'>1&#x32;<nested/>3</root>"); XMLStreamParser p(is, "simple", XMLStreamParser::RECEIVE_DEFAULT | XMLStreamParser::RECEIVE_NAMESPACE_DECLS); assert(p.next() == XMLStreamParser::EV_START_ELEMENT); p.nextExpect(XMLStreamParser::EV_START_NAMESPACE_DECL); p.content(Content::Simple); p.next(); assert(false); } catch (const Poco::Exception&) { // cerr << e.what () << endl; } // complex // { std::istringstream is("<root x=' x '>\n" " <nested>\n" " <inner/>\n" " <inner> X </inner>\n" " </nested>\n" "</root>\n"); XMLStreamParser p(is, "complex", XMLStreamParser::RECEIVE_DEFAULT | XMLStreamParser::RECEIVE_ATTRIBUTES_EVENT); assert(p.next() == XMLStreamParser::EV_START_ELEMENT); // root p.content(Content::Complex); assert(p.next() == XMLStreamParser::EV_START_ATTRIBUTE); assert(p.next() == XMLStreamParser::EV_CHARACTERS && p.value() == " x "); assert(p.next() == XMLStreamParser::EV_END_ATTRIBUTE); assert(p.next() == XMLStreamParser::EV_START_ELEMENT); // nested p.content(Content::Complex); assert(p.next() == XMLStreamParser::EV_START_ELEMENT); // inner p.content(Content::Empty); assert(p.next() == XMLStreamParser::EV_END_ELEMENT); // inner assert(p.next() == XMLStreamParser::EV_START_ELEMENT); // inner p.content(Content::Simple); assert(p.next() == XMLStreamParser::EV_CHARACTERS && p.value() == " X "); assert(p.next() == XMLStreamParser::EV_END_ELEMENT); // inner assert(p.next() == XMLStreamParser::EV_END_ELEMENT); // nested assert(p.next() == XMLStreamParser::EV_END_ELEMENT); // root assert(p.next() == XMLStreamParser::EV_EOF); } try { std::istringstream is("<root> \n<n/> X <n> X </n> </root>"); XMLStreamParser p(is, "complex"); assert(p.next() == XMLStreamParser::EV_START_ELEMENT); p.content(Content::Complex); assert(p.next() == XMLStreamParser::EV_START_ELEMENT); assert(p.next() == XMLStreamParser::EV_END_ELEMENT); p.next(); assert(false); } catch (const Poco::Exception&) { // cerr << e.what () << endl; } // Test element with simple content helpers. // { std::istringstream is("<root>" " <nested>X</nested>" " <nested/>" " <nested>123</nested>" " <nested>Y</nested>" " <t:nested xmlns:t='test'>Z</t:nested>" " <nested>234</nested>" " <t:nested xmlns:t='test'>345</t:nested>" " <nested>A</nested>" " <t:nested xmlns:t='test'>B</t:nested>" " <nested1>A</nested1>" " <t:nested1 xmlns:t='test'>B</t:nested1>" " <nested>1</nested>" " <t:nested xmlns:t='test'>2</t:nested>" " <nested1>1</nested1>" " <t:nested1 xmlns:t='test'>2</t:nested1>" "</root>"); XMLStreamParser p(is, "element"); p.nextExpect(XMLStreamParser::EV_START_ELEMENT, "root", Content::Complex); p.nextExpect(XMLStreamParser::EV_START_ELEMENT, "nested"); assert(p.element() == "X"); p.nextExpect(XMLStreamParser::EV_START_ELEMENT, "nested"); assert(p.element() == ""); p.nextExpect(XMLStreamParser::EV_START_ELEMENT, "nested"); assert(p.element<unsigned int>() == 123); assert(p.element("nested") == "Y"); assert(p.element(QName("test", "nested")) == "Z"); assert(p.element<unsigned int>("nested") == 234); assert(p.element<unsigned int>(QName("test", "nested")) == 345); assert(p.element("nested", "a") == "A"); assert(p.element(QName("test", "nested"), "b") == "B"); assert(p.element("nested", "a") == "a" && p.element("nested1") == "A"); assert(p.element(QName("test", "nested"), "b") == "b" && p.element(QName("test", "nested1")) == "B"); assert(p.element<unsigned int>("nested", 10) == 1); assert(p.element<unsigned int>(QName("test", "nested"), 20) == 2); assert(p.element<unsigned int>("nested", 10) == 10 && p.element<unsigned int>("nested1") == 1); assert(p.element<unsigned int>(QName("test", "nested"), 20) == 20 && p.element<unsigned int>(QName("test", "nested1")) == 2); p.nextExpect(XMLStreamParser::EV_END_ELEMENT); } // Test the iterator interface. // { std::istringstream is("<root><nested>X</nested></root>"); XMLStreamParser p(is, "iterator"); std::vector<XMLStreamParser::EventType> v; for (XMLStreamParser::Iterator i(p.begin()); i != p.end(); ++i) v.push_back(*i); //for (XMLStreamParser::EventType e: p) // v.push_back (e); assert(v.size() == 5); assert(v[0] == XMLStreamParser::EV_START_ELEMENT); assert(v[1] == XMLStreamParser::EV_START_ELEMENT); assert(v[2] == XMLStreamParser::EV_CHARACTERS); assert(v[3] == XMLStreamParser::EV_END_ELEMENT); assert(v[4] == XMLStreamParser::EV_END_ELEMENT); } // Test space extraction into the std::string value. // { std::istringstream is("<root a=' a '> b </root>"); XMLStreamParser p(is, "test"); p.nextExpect(XMLStreamParser::EV_START_ELEMENT, "root"); assert(p.attribute<std::string>("a") == " a "); p.nextExpect(XMLStreamParser::EV_CHARACTERS); assert(p.value<std::string>() == " b "); p.nextExpect(XMLStreamParser::EV_END_ELEMENT); } } void XMLStreamParserTest::setUp() { } void XMLStreamParserTest::tearDown() { } CppUnit::Test* XMLStreamParserTest::suite() { CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("XMLStreamParserTest"); CppUnit_addTest(pSuite, XMLStreamParserTest, testParser); return pSuite; }
28.958498
127
0.661298
[ "vector" ]
05899a1918605c7b18335f63ece8da64ec2826ce
1,912
cpp
C++
VSProject/LeetCodeSol/UnitTest/SingleNumberIIITestSuite.cpp
wangxiaotao1980/leetCodeCPP
1806c00cd89eacddbdd20a7c33875f54400a20a8
[ "MIT" ]
null
null
null
VSProject/LeetCodeSol/UnitTest/SingleNumberIIITestSuite.cpp
wangxiaotao1980/leetCodeCPP
1806c00cd89eacddbdd20a7c33875f54400a20a8
[ "MIT" ]
null
null
null
VSProject/LeetCodeSol/UnitTest/SingleNumberIIITestSuite.cpp
wangxiaotao1980/leetCodeCPP
1806c00cd89eacddbdd20a7c33875f54400a20a8
[ "MIT" ]
null
null
null
/******************************************************************************************* * @file SingleNumberIIITestSuite.cpp 2015\12\8 10:39:10 $ * @author Wang Xiaotao<wangxiaotao1980@gmail.com> (中文编码测试) * @note LeetCode No.260 Single Number III *******************************************************************************************/ #include "gtest/gtest.h" #include "../Src/SingleNumberIII.hpp" #include "disabled.hpp" // ------------------------------------------------------------------------------------------ // TEST(SingleNumberIIITestSuite, SingleNumberIIITestSuiteTestCase0) { SingleNumberIII sol; std::vector<int> data{ -1, 0 }; std::vector<int> result = sol.singleNumberIII(data); std::vector<int> result1{ -1, 0 }; std::vector<int> result2{ 0, -1 }; bool rs = ((result == result1) || (result == result2)); ASSERT_TRUE(rs); } // ------------------------------------------------------------------------------------------ // TEST(SingleNumberIIITestSuite, SingleNumberIIITestSuiteTestCase1) { std::vector<int> data{ 1, 2, 1, 3, 2, 5 }; SingleNumberIII sol; std::vector<int> result = sol.singleNumberIII(data); std::vector<int> result1{ 3, 5 }; std::vector<int> result2{ 5, 3 }; bool rs = ((result == result1) || (result == result2)); ASSERT_TRUE(rs); } // ------------------------------------------------------------------------------------------ // TEST(SingleNumberIIITestSuite, SingleNumberIIITestSuiteTestCase2) { std::vector<int> data{ 1, 2, 1, 1, 2, 2 }; SingleNumberIII sol; std::vector<int> result = sol.singleNumberIII(data); std::vector<int> result1{ 1, 2 }; std::vector<int> result2{ 2, 1 }; bool rs = ((result == result1) || (result == result2)); ASSERT_TRUE(rs); } // // -------------------------------------------------------------------------------------------
33.54386
94
0.452929
[ "vector" ]
058e07a1164af1bffc5e7d00dc4af82ae880959b
9,516
cc
C++
crypto/asn1/asn1_test.cc
azimot/boringssl
669ffe64a498a16ed8a339758c3abedcbb3d9522
[ "MIT" ]
null
null
null
crypto/asn1/asn1_test.cc
azimot/boringssl
669ffe64a498a16ed8a339758c3abedcbb3d9522
[ "MIT" ]
null
null
null
crypto/asn1/asn1_test.cc
azimot/boringssl
669ffe64a498a16ed8a339758c3abedcbb3d9522
[ "MIT" ]
null
null
null
/* Copyright (c) 2016, Google Inc. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <limits.h> #include <stdio.h> #include <vector> #include <gtest/gtest.h> #include <openssl/asn1.h> #include <openssl/asn1t.h> #include <openssl/bytestring.h> #include <openssl/err.h> #include <openssl/mem.h> #include <openssl/obj.h> #include <openssl/span.h> #include "../test/test_util.h" // kTag128 is an ASN.1 structure with a universal tag with number 128. static const uint8_t kTag128[] = { 0x1f, 0x81, 0x00, 0x01, 0x00, }; // kTag258 is an ASN.1 structure with a universal tag with number 258. static const uint8_t kTag258[] = { 0x1f, 0x82, 0x02, 0x01, 0x00, }; static_assert(V_ASN1_NEG_INTEGER == 258, "V_ASN1_NEG_INTEGER changed. Update kTag258 to collide with it."); // kTagOverflow is an ASN.1 structure with a universal tag with number 2^35-1, // which will not fit in an int. static const uint8_t kTagOverflow[] = { 0x1f, 0xff, 0xff, 0xff, 0xff, 0x7f, 0x01, 0x00, }; TEST(ASN1Test, LargeTags) { const uint8_t *p = kTag258; bssl::UniquePtr<ASN1_TYPE> obj(d2i_ASN1_TYPE(NULL, &p, sizeof(kTag258))); EXPECT_FALSE(obj) << "Parsed value with illegal tag" << obj->type; ERR_clear_error(); p = kTagOverflow; obj.reset(d2i_ASN1_TYPE(NULL, &p, sizeof(kTagOverflow))); EXPECT_FALSE(obj) << "Parsed value with tag overflow" << obj->type; ERR_clear_error(); p = kTag128; obj.reset(d2i_ASN1_TYPE(NULL, &p, sizeof(kTag128))); ASSERT_TRUE(obj); EXPECT_EQ(128, obj->type); const uint8_t kZero = 0; EXPECT_EQ(Bytes(&kZero, 1), Bytes(obj->value.asn1_string->data, obj->value.asn1_string->length)); } TEST(ASN1Test, IntegerSetting) { bssl::UniquePtr<ASN1_INTEGER> by_bn(ASN1_INTEGER_new()); bssl::UniquePtr<ASN1_INTEGER> by_long(ASN1_INTEGER_new()); bssl::UniquePtr<ASN1_INTEGER> by_uint64(ASN1_INTEGER_new()); bssl::UniquePtr<BIGNUM> bn(BN_new()); const std::vector<int64_t> kValues = { LONG_MIN, -2, -1, 0, 1, 2, 0xff, 0x100, 0xffff, 0x10000, LONG_MAX, }; for (const auto &i : kValues) { SCOPED_TRACE(i); ASSERT_EQ(1, ASN1_INTEGER_set(by_long.get(), i)); const uint64_t abs = i < 0 ? (0 - (uint64_t) i) : i; ASSERT_TRUE(BN_set_u64(bn.get(), abs)); BN_set_negative(bn.get(), i < 0); ASSERT_TRUE(BN_to_ASN1_INTEGER(bn.get(), by_bn.get())); EXPECT_EQ(0, ASN1_INTEGER_cmp(by_bn.get(), by_long.get())); if (i >= 0) { ASSERT_EQ(1, ASN1_INTEGER_set_uint64(by_uint64.get(), i)); EXPECT_EQ(0, ASN1_INTEGER_cmp(by_bn.get(), by_uint64.get())); } } } template <typename T> void TestSerialize(T obj, int (*i2d_func)(T a, uint8_t **pp), bssl::Span<const uint8_t> expected) { int len = static_cast<int>(expected.size()); ASSERT_EQ(i2d_func(obj, nullptr), len); std::vector<uint8_t> buf(expected.size()); uint8_t *ptr = buf.data(); ASSERT_EQ(i2d_func(obj, &ptr), len); EXPECT_EQ(ptr, buf.data() + buf.size()); EXPECT_EQ(Bytes(expected), Bytes(buf)); // Test the allocating version. ptr = nullptr; ASSERT_EQ(i2d_func(obj, &ptr), len); EXPECT_EQ(Bytes(expected), Bytes(ptr, expected.size())); OPENSSL_free(ptr); } TEST(ASN1Test, SerializeObject) { static const uint8_t kDER[] = {0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01}; const ASN1_OBJECT *obj = OBJ_nid2obj(NID_rsaEncryption); TestSerialize(obj, i2d_ASN1_OBJECT, kDER); } TEST(ASN1Test, SerializeBoolean) { static const uint8_t kTrue[] = {0x01, 0x01, 0xff}; TestSerialize(0xff, i2d_ASN1_BOOLEAN, kTrue); static const uint8_t kFalse[] = {0x01, 0x01, 0x00}; TestSerialize(0x00, i2d_ASN1_BOOLEAN, kFalse); } TEST(ASN1Test, ASN1Type) { const struct { int type; std::vector<uint8_t> der; } kTests[] = { // BOOLEAN { TRUE } {V_ASN1_BOOLEAN, {0x01, 0x01, 0xff}}, // BOOLEAN { FALSE } {V_ASN1_BOOLEAN, {0x01, 0x01, 0x00}}, // OCTET_STRING { "a" } {V_ASN1_OCTET_STRING, {0x04, 0x01, 0x61}}, // BIT_STRING { `01` `00` } {V_ASN1_BIT_STRING, {0x03, 0x02, 0x01, 0x00}}, // INTEGER { -1 } {V_ASN1_INTEGER, {0x02, 0x01, 0xff}}, // OBJECT_IDENTIFIER { 1.2.840.113554.4.1.72585.2 } {V_ASN1_OBJECT, {0x06, 0x0c, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x12, 0x04, 0x01, 0x84, 0xb7, 0x09, 0x02}}, // NULL {} {V_ASN1_NULL, {0x05, 0x00}}, // SEQUENCE {} {V_ASN1_SEQUENCE, {0x30, 0x00}}, // SET {} {V_ASN1_SET, {0x31, 0x00}}, // [0] { UTF8String { "a" } } {V_ASN1_OTHER, {0xa0, 0x03, 0x0c, 0x01, 0x61}}, }; for (const auto &t : kTests) { SCOPED_TRACE(Bytes(t.der)); // The input should successfully parse. const uint8_t *ptr = t.der.data(); bssl::UniquePtr<ASN1_TYPE> val(d2i_ASN1_TYPE(nullptr, &ptr, t.der.size())); ASSERT_TRUE(val); EXPECT_EQ(ASN1_TYPE_get(val.get()), t.type); EXPECT_EQ(val->type, t.type); TestSerialize(val.get(), i2d_ASN1_TYPE, t.der); } } // Test that reading |value.ptr| from a FALSE |ASN1_TYPE| behaves correctly. The // type historically supported this, so maintain the invariant in case external // code relies on it. TEST(ASN1Test, UnusedBooleanBits) { // OCTET_STRING { "a" } static const uint8_t kDER[] = {0x04, 0x01, 0x61}; const uint8_t *ptr = kDER; bssl::UniquePtr<ASN1_TYPE> val(d2i_ASN1_TYPE(nullptr, &ptr, sizeof(kDER))); ASSERT_TRUE(val); EXPECT_EQ(V_ASN1_OCTET_STRING, val->type); EXPECT_TRUE(val->value.ptr); // Set |val| to a BOOLEAN containing FALSE. ASN1_TYPE_set(val.get(), V_ASN1_BOOLEAN, NULL); EXPECT_EQ(V_ASN1_BOOLEAN, val->type); EXPECT_FALSE(val->value.ptr); } // The ASN.1 macros do not work on Windows shared library builds, where usage of // |OPENSSL_EXPORT| is a bit stricter. #if !defined(OPENSSL_WINDOWS) || !defined(BORINGSSL_SHARED_LIBRARY) typedef struct asn1_linked_list_st { struct asn1_linked_list_st *next; } ASN1_LINKED_LIST; DECLARE_ASN1_ITEM(ASN1_LINKED_LIST) DECLARE_ASN1_FUNCTIONS(ASN1_LINKED_LIST) ASN1_SEQUENCE(ASN1_LINKED_LIST) = { ASN1_OPT(ASN1_LINKED_LIST, next, ASN1_LINKED_LIST), } ASN1_SEQUENCE_END(ASN1_LINKED_LIST) IMPLEMENT_ASN1_FUNCTIONS(ASN1_LINKED_LIST) static bool MakeLinkedList(bssl::UniquePtr<uint8_t> *out, size_t *out_len, size_t count) { bssl::ScopedCBB cbb; std::vector<CBB> cbbs(count); if (!CBB_init(cbb.get(), 2 * count) || !CBB_add_asn1(cbb.get(), &cbbs[0], CBS_ASN1_SEQUENCE)) { return false; } for (size_t i = 1; i < count; i++) { if (!CBB_add_asn1(&cbbs[i - 1], &cbbs[i], CBS_ASN1_SEQUENCE)) { return false; } } uint8_t *ptr; if (!CBB_finish(cbb.get(), &ptr, out_len)) { return false; } out->reset(ptr); return true; } TEST(ASN1Test, Recursive) { bssl::UniquePtr<uint8_t> data; size_t len; // Sanity-check that MakeLinkedList can be parsed. ASSERT_TRUE(MakeLinkedList(&data, &len, 5)); const uint8_t *ptr = data.get(); ASN1_LINKED_LIST *list = d2i_ASN1_LINKED_LIST(nullptr, &ptr, len); EXPECT_TRUE(list); ASN1_LINKED_LIST_free(list); // Excessively deep structures are rejected. ASSERT_TRUE(MakeLinkedList(&data, &len, 100)); ptr = data.get(); list = d2i_ASN1_LINKED_LIST(nullptr, &ptr, len); EXPECT_FALSE(list); // Note checking the error queue here does not work. The error "stack trace" // is too deep, so the |ASN1_R_NESTED_TOO_DEEP| entry drops off the queue. ASN1_LINKED_LIST_free(list); } struct IMPLICIT_CHOICE { ASN1_STRING *string; }; // clang-format off DECLARE_ASN1_FUNCTIONS(IMPLICIT_CHOICE) ASN1_SEQUENCE(IMPLICIT_CHOICE) = { ASN1_IMP(IMPLICIT_CHOICE, string, DIRECTORYSTRING, 0) } ASN1_SEQUENCE_END(IMPLICIT_CHOICE) IMPLEMENT_ASN1_FUNCTIONS(IMPLICIT_CHOICE) // clang-format on // Test that the ASN.1 templates reject types with implicitly-tagged CHOICE // types. TEST(ASN1Test, ImplicitChoice) { // Serializing a type with an implicitly tagged CHOICE should fail. std::unique_ptr<IMPLICIT_CHOICE, decltype(&IMPLICIT_CHOICE_free)> obj( IMPLICIT_CHOICE_new(), IMPLICIT_CHOICE_free); EXPECT_EQ(-1, i2d_IMPLICIT_CHOICE(obj.get(), nullptr)); // An implicitly-tagged CHOICE is an error. Depending on the implementation, // it may be misinterpreted as without the tag, or as clobbering the CHOICE // tag. Test both inputs and ensure they fail. // SEQUENCE { UTF8String {} } static const uint8_t kInput1[] = {0x30, 0x02, 0x0c, 0x00}; const uint8_t *ptr = kInput1; EXPECT_EQ(nullptr, d2i_IMPLICIT_CHOICE(nullptr, &ptr, sizeof(kInput1))); // SEQUENCE { [0 PRIMITIVE] {} } static const uint8_t kInput2[] = {0x30, 0x02, 0x80, 0x00}; ptr = kInput2; EXPECT_EQ(nullptr, d2i_IMPLICIT_CHOICE(nullptr, &ptr, sizeof(kInput2))); } #endif // !WINDOWS || !SHARED_LIBRARY
32.813793
80
0.684636
[ "vector" ]
059af5c6bcc243d4fe788ad77ed12f0cfd4c2d75
41,586
cpp
C++
src/message_conversions.cpp
perchess/qml_ros_plugin
d0e3ef3567026e61122efd1bd1c77881a034fd73
[ "MIT" ]
15
2019-12-01T14:07:59.000Z
2021-12-28T09:45:48.000Z
src/message_conversions.cpp
perchess/qml_ros_plugin
d0e3ef3567026e61122efd1bd1c77881a034fd73
[ "MIT" ]
3
2022-02-16T16:10:12.000Z
2022-02-20T11:06:32.000Z
src/message_conversions.cpp
perchess/qml_ros_plugin
d0e3ef3567026e61122efd1bd1c77881a034fd73
[ "MIT" ]
2
2021-09-01T09:49:43.000Z
2021-11-19T09:29:25.000Z
// Copyright (c) 2019 Stefan Fabian. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include "qml_ros_plugin/message_conversions.h" #include "qml_ros_plugin/array.h" #include "qml_ros_plugin/babel_fish_dispenser.h" #include "qml_ros_plugin/qml_ros_conversion.h" #include "qml_ros_plugin/time.h" #include <QAbstractListModel> #include <QDateTime> #include <QMetaProperty> #include <QQuaternion> #include <QUrl> #include <QVector2D> #include <QVector3D> #include <QVector4D> #include <ros_babel_fish/message_types.h> #include <ros/ros.h> using namespace ros_babel_fish; namespace qml_ros_plugin { namespace conversion { QVariantMap msgToMap( const std_msgs::Header &msg ) { QVariantMap result; result.insert( "frame_id", QString::fromStdString( msg.frame_id )); result.insert( "stamp", QVariant::fromValue( Time( msg.stamp ))); result.insert( "seq", msg.seq ); return result; } QVariantMap msgToMap( const geometry_msgs::Transform &msg ) { QVariantMap result; result.insert( "translation", QVariant::fromValue( msgToMap( msg.translation ))); result.insert( "rotation", QVariant::fromValue( msgToMap( msg.rotation ))); return result; } QVariantMap msgToMap( const geometry_msgs::TransformStamped &msg ) { QVariantMap result; result.insert( "header", QVariant::fromValue( msgToMap( msg.header ))); result.insert( "child_frame_id", QString::fromStdString( msg.child_frame_id )); result.insert( "transform", QVariant::fromValue( msgToMap( msg.transform ))); return result; } QVariantMap msgToMap( const geometry_msgs::Vector3 &msg ) { QVariantMap result; result.insert( "x", msg.x ); result.insert( "y", msg.y ); result.insert( "z", msg.z ); return result; } QVariantMap msgToMap( const geometry_msgs::Quaternion &msg ) { QVariantMap result; result.insert( "w", msg.w ); result.insert( "x", msg.x ); result.insert( "y", msg.y ); result.insert( "z", msg.z ); return result; } QVariantMap msgToMap( const actionlib_msgs::GoalID &msg ) { QVariantMap result; result.insert( "id", QString::fromStdString( msg.id )); result.insert( "stamp", QVariant::fromValue( Time( msg.stamp ))); return result; } QVariantMap msgToMap( const actionlib_msgs::GoalStatus &msg ) { QVariantMap result; result.insert( "goal_id", QVariant::fromValue( msgToMap( msg.goal_id ))); result.insert( "status", msg.status ); result.insert( "text", QString::fromStdString( msg.text )); return result; } QVariant msgToMap( const TranslatedMessage::ConstPtr &msg ) { return msgToMap( msg, *msg->translated_message ); } QVariant msgToMap( const TranslatedMessage::ConstPtr &storage, const Message &msg ) { if ( msg.type() == MessageTypes::Compound ) { QVariantMap result; const auto &compound = msg.as<CompoundMessage>(); for ( size_t i = 0; i < compound.keys().size(); ++i ) { result.insert( QString::fromStdString( compound.keys()[i] ), msgToMap( storage, *compound.values()[i] )); } return result; } else if ( msg.type() == MessageTypes::Array ) { return QVariant::fromValue( Array( storage, &msg.as<ArrayMessageBase>())); } switch ( msg.type()) { case MessageTypes::Bool: return QVariant::fromValue( msg.as<ValueMessage<bool>>().getValue()); case MessageTypes::UInt8: return QVariant::fromValue<unsigned int>( msg.as<ValueMessage<uint8_t>>().getValue()); case MessageTypes::UInt16: return QVariant::fromValue<unsigned int>( msg.as<ValueMessage<uint16_t>>().getValue()); case MessageTypes::UInt32: return QVariant::fromValue( msg.as<ValueMessage<uint32_t>>().getValue()); case MessageTypes::UInt64: return QVariant::fromValue( msg.as<ValueMessage<uint64_t>>().getValue()); case MessageTypes::Int8: return QVariant::fromValue<int>( msg.as<ValueMessage<int8_t>>().getValue()); case MessageTypes::Int16: return QVariant::fromValue<int>( msg.as<ValueMessage<int16_t>>().getValue()); case MessageTypes::Int32: return QVariant::fromValue( msg.as<ValueMessage<int32_t>>().getValue()); case MessageTypes::Int64: return QVariant::fromValue( msg.as<ValueMessage<int64_t>>().getValue()); case MessageTypes::Float32: return QVariant::fromValue( msg.as<ValueMessage<float>>().getValue()); case MessageTypes::Float64: return QVariant::fromValue( msg.as<ValueMessage<double>>().getValue()); case MessageTypes::String: return QVariant::fromValue( QString::fromStdString( msg.as<ValueMessage<std::string>>().getValue())); case MessageTypes::Time: { return QVariant::fromValue( Time( msg.value<ros::Time>())); } case MessageTypes::Duration: return QVariant::fromValue( rosToQmlDuration( msg.as<ValueMessage<ros::Duration>>().getValue())); default: ROS_WARN( "Unknown type '%d' while processing message!", msg.type()); break; } return QVariant(); } namespace { template<typename T> QVariantList msgToList( const ArrayMessageBase &array ) { QVariantList result; result.reserve( array.length()); auto &typed_array = array.as<ArrayMessage<T>>(); for ( size_t i = 0; i < array.length(); ++i ) { result.append( QVariant::fromValue( typed_array[i] )); } return result; } template<> QVariantList msgToList<ros::Duration>( const ArrayMessageBase &array ) { QVariantList result; result.reserve( array.length()); auto &typed_array = array.as<ArrayMessage<ros::Duration>>(); for ( size_t i = 0; i < array.length(); ++i ) { result.append( QVariant::fromValue( rosToQmlDuration( typed_array[i] ))); } return result; } template<> QVariantList msgToList<ros::Time>( const ArrayMessageBase &array ) { QVariantList result; result.reserve( array.length()); auto &typed_array = array.as<ArrayMessage<ros::Time>>(); for ( size_t i = 0; i < array.length(); ++i ) { result.append( QVariant::fromValue( Time( typed_array[i] ))); } return result; } template<> QVariantList msgToList<std::string>( const ArrayMessageBase &array ) { QVariantList result; result.reserve( array.length()); auto &typed_array = array.as<ArrayMessage<std::string>>(); for ( size_t i = 0; i < array.length(); ++i ) { result.append( QVariant::fromValue( QString::fromStdString( typed_array[i] ))); } return result; } } QVariant msgToMap( const Message &msg ) { if ( msg.type() == MessageTypes::Compound ) { QVariantMap result; const auto &compound = msg.as<CompoundMessage>(); for ( size_t i = 0; i < compound.keys().size(); ++i ) { result.insert( QString::fromStdString( compound.keys()[i] ), msgToMap( *compound.values()[i] )); } return result; } else if ( msg.type() == MessageTypes::Array ) { auto &arr = msg.as<ArrayMessageBase>(); switch ( arr.elementType()) { case MessageTypes::Bool: return msgToList<bool>( arr ); case MessageTypes::UInt8: return msgToList<uint8_t>( arr ); case MessageTypes::UInt16: return msgToList<uint16_t>( arr ); case MessageTypes::UInt32: return msgToList<uint32_t>( arr ); case MessageTypes::UInt64: return msgToList<uint64_t>( arr ); case MessageTypes::Int8: return msgToList<int8_t>( arr ); case MessageTypes::Int16: return msgToList<int16_t>( arr ); case MessageTypes::Int32: return msgToList<int32_t>( arr ); case MessageTypes::Int64: return msgToList<int64_t>( arr ); case MessageTypes::Float32: return msgToList<float>( arr ); case MessageTypes::Float64: return msgToList<double>( arr ); case MessageTypes::Time: return msgToList<ros::Time>( arr ); case MessageTypes::Duration: return msgToList<ros::Duration>( arr ); case MessageTypes::String: return msgToList<std::string>( arr ); case MessageTypes::None: default: return QVariantList(); } } switch ( msg.type()) { case MessageTypes::Bool: return QVariant::fromValue( msg.as<ValueMessage<bool>>().getValue()); case MessageTypes::UInt8: return QVariant::fromValue<unsigned int>( msg.as<ValueMessage<uint8_t>>().getValue()); case MessageTypes::UInt16: return QVariant::fromValue<unsigned int>( msg.as<ValueMessage<uint16_t>>().getValue()); case MessageTypes::UInt32: return QVariant::fromValue( msg.as<ValueMessage<uint32_t>>().getValue()); case MessageTypes::UInt64: return QVariant::fromValue( msg.as<ValueMessage<uint64_t>>().getValue()); case MessageTypes::Int8: return QVariant::fromValue<int>( msg.as<ValueMessage<int8_t>>().getValue()); case MessageTypes::Int16: return QVariant::fromValue<int>( msg.as<ValueMessage<int16_t>>().getValue()); case MessageTypes::Int32: return QVariant::fromValue( msg.as<ValueMessage<int32_t>>().getValue()); case MessageTypes::Int64: return QVariant::fromValue( msg.as<ValueMessage<int64_t>>().getValue()); case MessageTypes::Float32: return QVariant::fromValue( msg.as<ValueMessage<float>>().getValue()); case MessageTypes::Float64: return QVariant::fromValue( msg.as<ValueMessage<double>>().getValue()); case MessageTypes::String: return QVariant::fromValue( QString::fromStdString( msg.as<ValueMessage<std::string>>().getValue())); case MessageTypes::Time: { return QVariant::fromValue( Time( msg.value<ros::Time>())); } case MessageTypes::Duration: return QVariant::fromValue( rosToQmlDuration( msg.as<ValueMessage<ros::Duration>>().getValue())); default: ROS_WARN( "Unknown type '%d' while processing message!", msg.type()); break; } return QVariant(); } namespace { template<typename T> bool fillValue( Message &msg, T value, uint32_t types ) { if ( !(msg.type() & types)) { ROS_WARN( "Tried to fill '%s' field with incompatible type!", typeid( T ).name()); return false; } switch ( msg.type()) { case MessageTypes::Bool: msg.as<ValueMessage<bool>>().setValue( static_cast<bool>(value)); break; case MessageTypes::UInt8: msg.as<ValueMessage<uint8_t>>().setValue( static_cast<uint8_t>(value)); break; case MessageTypes::UInt16: msg.as<ValueMessage<uint16_t>>().setValue( static_cast<uint16_t>(value)); break; case MessageTypes::UInt32: msg.as<ValueMessage<uint32_t>>().setValue( static_cast<uint32_t>(value)); break; case MessageTypes::UInt64: msg.as<ValueMessage<uint64_t>>().setValue( static_cast<uint64_t>(value)); break; case MessageTypes::Int8: msg.as<ValueMessage<int8_t>>().setValue( static_cast<int8_t>(value)); break; case MessageTypes::Int16: msg.as<ValueMessage<int16_t>>().setValue( static_cast<int16_t>(value)); break; case MessageTypes::Int32: msg.as<ValueMessage<int32_t>>().setValue( static_cast<int32_t>(value)); break; case MessageTypes::Int64: msg.as<ValueMessage<int64_t>>().setValue( static_cast<int64_t>(value)); break; case MessageTypes::Float32: msg.as<ValueMessage<float>>().setValue( static_cast<float>(value)); break; case MessageTypes::Float64: msg.as<ValueMessage<double>>().setValue( static_cast<double>(value)); break; // case MessageTypes::String: // msg.as<ValueMessage<std::string>>().setValue( std::to_string( value )); // break; // case MessageTypes::Time: // msg.as<ValueMessage<ros::Time>>().setValue( ros::Time( static_cast<double>(value))); // break; case MessageTypes::Duration: // Durations in qml are given in milliseconds msg.as<ValueMessage<ros::Duration>>().setValue( ros::Duration( value / 1000.0 )); break; default: ROS_WARN( "Unknown type while filling message!" ); return false; } return true; } template<> bool fillValue( Message &msg, ros::Time value, uint32_t ) { if ( msg.type() != MessageTypes::Time ) { ROS_WARN( "Tried to fill 'ros::Time' field with incompatible type!" ); return false; } msg.as<ValueMessage<ros::Time>>().setValue( value ); return true; } template<> bool fillValue( Message &msg, std::string value, uint32_t ) { if ( msg.type() != MessageTypes::String ) { ROS_WARN( "Tried to fill 'std::string' field with incompatible type!" ); return false; } auto &value_msg = msg.as<ValueMessage<std::string>>(); value_msg.setValue( std::move( value )); return true; } template<typename TBounds, typename TVal> typename std::enable_if<std::is_signed<TVal>::value, bool>::type inBounds( TVal val ) { typedef typename std::make_signed<TBounds>::type STBounds; typedef typename std::make_unsigned<TBounds>::type UTBounds; typedef typename std::make_unsigned<TVal>::type UTVal; // val is in bounds of a signed target type if it is greater than the min of the signed type and either smaller than // zero or smaller than its max. If val is greater or equal to zero, the val and max are casted to unsigned types to // prevent compiler warnings if the TVal and TBounds are not both signed or both unsigned. return static_cast<STBounds>(std::numeric_limits<TBounds>::min()) <= val && (val < 0 || static_cast<UTBounds>(val) <= static_cast<UTVal>(std::numeric_limits<TBounds>::max())); } template<typename TBounds, typename TVal> typename std::enable_if<std::is_unsigned<TVal>::value, bool>::type inBounds( TVal val ) { return val <= static_cast<typename std::make_unsigned<TBounds>::type>(std::numeric_limits<TBounds>::max()); } // Default implementation is for all integer types template<typename T> bool isCompatible( const QVariant &variant ) { switch ((int) variant.type()) { case QMetaType::UChar: { auto val = variant.value<uint8_t>(); return inBounds<T>( val ); } case QMetaType::UShort: { auto val = variant.value<uint16_t>(); return inBounds<T>( val ); } case QVariant::UInt: { uint val = variant.toUInt(); return inBounds<T>( val ); } case QMetaType::ULong: { auto val = variant.value<unsigned long>(); return inBounds<T>( val ); } case QVariant::ULongLong: { qulonglong val = variant.toULongLong(); return inBounds<T>( val ); } case QMetaType::SChar: case QMetaType::Char: { auto val = variant.value<int8_t>(); return inBounds<T>( val ); } case QMetaType::Short: { auto val = variant.value<int16_t>(); return inBounds<T>( val ); } case QVariant::Int: { int val = variant.toInt(); return inBounds<T>( val ); } case QMetaType::Long: { auto val = variant.value<long>(); return inBounds<T>( val ); } case QVariant::LongLong: { qlonglong val = variant.toLongLong(); return inBounds<T>( val ); } case QMetaType::Float: { auto val = variant.value<float>(); return val == std::round( val ) && std::numeric_limits<T>::min() <= val && val <= std::numeric_limits<T>::max(); } case QVariant::Double: { double val = variant.toDouble(); return val == std::round( val ) && std::numeric_limits<T>::min() <= val && val <= std::numeric_limits<T>::max(); } default: break; } return false; } template<> bool isCompatible<bool>( const QVariant &variant ) { return variant.type() == QVariant::Bool; } template<> bool isCompatible<float>( const QVariant &variant ) { return (int) variant.type() == QMetaType::Float || variant.type() == QVariant::Double || variant.type() == QVariant::UInt || variant.type() == QVariant::Int || variant.type() == QVariant::ULongLong || variant.type() == QVariant::LongLong; } template<> bool isCompatible<double>( const QVariant &variant ) { return (int) variant.type() == QMetaType::Float || variant.type() == QVariant::Double || variant.type() == QVariant::UInt || variant.type() == QVariant::Int || variant.type() == QVariant::ULongLong || variant.type() == QVariant::LongLong; } template<> bool isCompatible<ros::Time>( const QVariant &variant ) { return variant.type() == QVariant::Double || variant.type() == QVariant::UInt || variant.type() == QVariant::Int || variant.type() == QVariant::ULongLong || variant.type() == QVariant::LongLong || variant.type() == QVariant::DateTime || variant.typeName() == std::string( "qml_ros_plugin::Time" ) || variant.typeName() == std::string( "qml_ros_plugin::WallTime" ); } template<> bool isCompatible<ros::Duration>( const QVariant &variant ) { return variant.type() == QVariant::Double || variant.type() == QVariant::UInt || variant.type() == QVariant::Int || variant.type() == QVariant::ULongLong || variant.type() == QVariant::LongLong; } template<typename T> T getValue( const QVariant &variant ) { switch ((int) variant.type()) { case QVariant::Bool: return variant.toBool(); case QMetaType::SChar: return static_cast<T>(variant.value<int8_t>()); case QMetaType::UChar: return static_cast<T>(variant.value<uint8_t>()); case QMetaType::Short: return static_cast<T>(variant.value<int16_t>()); case QMetaType::UShort: return static_cast<T>(variant.value<uint16_t>()); case QVariant::Int: return static_cast<T>(variant.toInt()); case QVariant::UInt: return static_cast<T>(variant.toUInt()); case QMetaType::Long: return static_cast<T>(variant.value<long>()); case QMetaType::ULong: return static_cast<T>(variant.value<unsigned long>()); case QVariant::LongLong: return static_cast<T>(variant.toLongLong()); case QVariant::ULongLong: return static_cast<T>(variant.toULongLong()); case QMetaType::Float: return variant.value<float>(); case QVariant::Double: return static_cast<T>(variant.toDouble()); default: ROS_WARN_STREAM( "Tried to get " << typeid( T ).name() << " from incompatible type! Type: " << variant.typeName()); } return T(); } template<> ros::Time getValue<ros::Time>( const QVariant &variant ) { switch ( variant.type()) { case QVariant::Int: return qmlToRosTime( variant.toInt()); case QVariant::UInt: return qmlToRosTime( variant.toUInt()); case QVariant::LongLong: return qmlToRosTime( variant.toLongLong()); case QVariant::ULongLong: return qmlToRosTime( variant.toULongLong()); case QVariant::Double: return ros::Time( variant.toDouble() / 1000.0 ); case QVariant::DateTime: return qmlToRosTime( variant.toDateTime().toMSecsSinceEpoch()); case QVariant::Date: case QVariant::Time: default: if ( variant.canConvert<Time>()) return variant.value<Time>().getRosTime(); if ( variant.canConvert<WallTime>()) { ros::WallTime wall_time = variant.value<WallTime>().getRosTime(); return { wall_time.sec, wall_time.nsec }; } ROS_WARN_STREAM( "Tried to get ros::Time from incompatible type! Type: " << variant.typeName()); return {}; } } template<> ros::Duration getValue<ros::Duration>( const QVariant &variant ) { switch ( variant.type()) { case QVariant::Int: return qmlToRosDuration( variant.toInt()); case QVariant::UInt: return qmlToRosDuration( variant.toUInt()); case QVariant::LongLong: return qmlToRosDuration( variant.toLongLong()); case QVariant::ULongLong: return qmlToRosDuration( variant.toULongLong()); case QVariant::Double: return qmlToRosDuration( variant.toDouble()); case QVariant::Date: case QVariant::Time: case QVariant::DateTime: default: ROS_WARN_STREAM( "Tried to get ros::Duration from incompatible type! Type: " << variant.typeName()); return {}; } } template<typename T, typename ArrayType> typename std::enable_if<!std::is_same<ArrayType, QAbstractListModel>::value, bool>::type fillArray( Message &msg, const ArrayType &list ) { auto &array = msg.as<ArrayMessage<T>>(); size_t count = list.size(); bool no_error = true; if ( array.isFixedSize() && count > array.length()) { count = array.length(); no_error = false; } for ( size_t i = 0; i < count; ++i ) { const QVariant &variant = list.at( i ); if ( !isCompatible<T>( variant )) { ROS_WARN( "Tried to fill array of '%s' with incompatible value! Skipped. (Type: %s)", typeid( T ).name(), variant.typeName()); no_error = false; continue; } if ( array.isFixedSize()) array.assign( i, getValue<T>( variant )); else array.push_back( getValue<T>( variant )); } return no_error; } template<typename T, typename ArrayType> typename std::enable_if<std::is_same<ArrayType, QAbstractListModel>::value, bool>::type fillArray( Message &msg, const ArrayType &list ) { auto &array = msg.as<ArrayMessage<T>>(); size_t count = list.rowCount(); bool no_error = true; if ( array.isFixedSize() && count > array.length()) { count = array.length(); no_error = false; } for ( size_t i = 0; i < count; ++i ) { QModelIndex index = list.index( i, 0 ); const QVariant &variant = list.data( index ); if ( !isCompatible<T>( variant )) { ROS_WARN( "Tried to fill array of '%s' with incompatible value! Skipped. (Type: %s)", typeid( T ).name(), variant.typeName()); no_error = false; continue; } if ( array.isFixedSize()) array.assign( i, getValue<T>( variant )); else array.push_back( getValue<T>( variant )); } return no_error; } template<typename T> using limits = std::numeric_limits<T>; uint32_t getCompatibleTypes( int val ) { uint32_t compatible_types = MessageTypes::Int32 | MessageTypes::Int64 | MessageTypes::Float32 | MessageTypes::Float64 | MessageTypes::Duration; // If it fits, it sits if ( limits<int8_t>::min() <= val && val <= limits<int8_t>::max()) compatible_types |= MessageTypes::Int8; if ( limits<uint8_t>::min() <= val && val <= limits<uint8_t>::max()) compatible_types |= MessageTypes::UInt8; if ( limits<int16_t>::min() <= val && val <= limits<int16_t>::max()) compatible_types |= MessageTypes::Int16; if ( limits<uint16_t>::min() <= val && val <= limits<uint16_t>::max()) compatible_types |= MessageTypes::UInt16; if ( val >= 0 ) compatible_types |= MessageTypes::UInt32 | MessageTypes::UInt64; return compatible_types; } uint32_t getCompatibleTypes( uint val ) { uint32_t compatible_types = MessageTypes::UInt32 | MessageTypes::UInt64 | MessageTypes::Int64 | MessageTypes::Float32 | MessageTypes::Float64 | MessageTypes::Duration; if ( val <= static_cast<uint>(limits<int8_t>::max())) compatible_types |= MessageTypes::Int8; if ( val <= static_cast<uint>(limits<uint8_t>::max())) compatible_types |= MessageTypes::UInt8; if ( val <= static_cast<uint>(limits<int16_t>::max())) compatible_types |= MessageTypes::Int16; if ( val <= static_cast<uint>(limits<uint16_t>::max())) compatible_types |= MessageTypes::UInt16; if ( val <= static_cast<uint>(limits<int32_t>::max())) compatible_types |= MessageTypes::Int32; return compatible_types; } uint32_t getCompatibleTypes( qlonglong val ) { uint32_t compatible_types = MessageTypes::Int64 | MessageTypes::Float32 | MessageTypes::Float64 | MessageTypes::Duration; if ( limits<int8_t>::min() <= val && val <= limits<int8_t>::max()) compatible_types |= MessageTypes::Int8; if ( limits<uint8_t>::min() <= val && val <= limits<uint8_t>::max()) compatible_types |= MessageTypes::UInt8; if ( limits<int16_t>::min() <= val && val <= limits<int16_t>::max()) compatible_types |= MessageTypes::Int16; if ( limits<uint16_t>::min() <= val && val <= limits<uint16_t>::max()) compatible_types |= MessageTypes::UInt16; if ( limits<int32_t>::min() <= val && val <= limits<int32_t>::max()) compatible_types |= MessageTypes::Int32; if ( val >= 0 ) compatible_types |= MessageTypes::UInt32 | MessageTypes::UInt64; return compatible_types; } uint32_t getCompatibleTypes( qulonglong val ) { uint32_t compatible_types = MessageTypes::UInt64 | MessageTypes::Float32 | MessageTypes::Float64 | MessageTypes::Duration; if ( val <= static_cast<qulonglong>(limits<int8_t>::max())) compatible_types |= MessageTypes::Int8; if ( val <= static_cast<qulonglong>(limits<uint8_t>::max())) compatible_types |= MessageTypes::UInt8; if ( val <= static_cast<qulonglong>(limits<int16_t>::max())) compatible_types |= MessageTypes::Int16; if ( val <= static_cast<qulonglong>(limits<uint16_t>::max())) compatible_types |= MessageTypes::UInt16; if ( val <= static_cast<qulonglong>(limits<int32_t>::max())) compatible_types |= MessageTypes::Int32; if ( val <= static_cast<qulonglong>(limits<uint32_t>::max())) compatible_types |= MessageTypes::UInt32; if ( val <= static_cast<qulonglong>(limits<int64_t>::max())) compatible_types |= MessageTypes::Int64; return compatible_types; } uint32_t getCompatibleTypes( double val ) { uint32_t compatible_types = MessageTypes::Float32 | MessageTypes::Float64 | MessageTypes::Duration; if ( val == std::round( val )) { if ( limits<int8_t>::min() <= val && val <= limits<int8_t>::max()) compatible_types |= MessageTypes::Int8; if ( limits<uint8_t>::min() <= val && val <= limits<uint8_t>::max()) compatible_types |= MessageTypes::UInt8; if ( limits<int16_t>::min() <= val && val <= limits<int16_t>::max()) compatible_types |= MessageTypes::Int16; if ( limits<uint16_t>::min() <= val && val <= limits<uint16_t>::max()) compatible_types |= MessageTypes::UInt16; if ( limits<int32_t>::min() <= val && val <= limits<int32_t>::max()) compatible_types |= MessageTypes::Int32; if ( limits<uint32_t>::min() <= val && val <= limits<uint32_t>::max()) compatible_types |= MessageTypes::UInt32; if ( limits<int64_t>::min() <= val && val <= limits<int64_t>::max()) compatible_types |= MessageTypes::Int64; if ( limits<uint64_t>::min() <= val && val <= limits<uint64_t>::max()) compatible_types |= MessageTypes::UInt64; } return compatible_types; } } bool fillMessage( ros_babel_fish::Message &msg, const QVariant &value ) { BabelFish fish = BabelFishDispenser::getBabelFish(); return fillMessage( fish, msg, value ); } template<typename Array> bool fillArrayFromVariant( ros_babel_fish::Message &msg, const Array &list ) { if ( msg.type() != MessageTypes::Array ) { ROS_WARN( "Tried to fill array in non-array message field!" ); return false; } auto &array = msg.as<ArrayMessageBase>(); size_t count = list.size(); if ( array.isFixedSize() && count > array.length()) { ROS_WARN( "Too many values for fixed size array (%lu vs %lu)! Only using first %lu.", count, array.length(), array.length()); count = array.length(); } switch ( array.elementType()) { case MessageTypes::None: break; case MessageTypes::Bool: return fillArray<bool>( array, list ); case MessageTypes::UInt8: return fillArray<uint8_t>( array, list ); case MessageTypes::UInt16: return fillArray<uint16_t>( array, list ); case MessageTypes::UInt32: return fillArray<uint32_t>( array, list ); case MessageTypes::UInt64: return fillArray<uint64_t>( array, list ); case MessageTypes::Int8: return fillArray<int8_t>( array, list ); case MessageTypes::Int16: return fillArray<int16_t>( array, list ); case MessageTypes::Int32: return fillArray<int32_t>( array, list ); case MessageTypes::Int64: return fillArray<int64_t>( array, list ); case MessageTypes::Float32: return fillArray<float>( array, list ); case MessageTypes::Float64: return fillArray<double>( array, list ); case MessageTypes::Time: return fillArray<ros::Time>( array, list ); case MessageTypes::Duration: return fillArray<ros::Duration>( array, list ); case MessageTypes::String: { auto &array = msg.as<ArrayMessage<std::string>>(); bool no_error = true; for ( size_t i = 0; i < count; ++i ) { const QVariant &variant = list.at( i ); if ( !variant.canConvert<QString>()) { ROS_WARN( "Tried to fill string array with non-string value! Skipped." ); no_error = false; continue; } if ( array.isFixedSize()) array.assign( i, variant.toString().toStdString()); else array.push_back( variant.toString().toStdString()); } return no_error; } case MessageTypes::Compound: { auto &array = msg.as<CompoundArrayMessage>(); bool no_error = true; for ( size_t i = 0; i < count; ++i ) { const QVariant &variant = list.at( i ); if ( variant.type() != QVariant::Map ) { ROS_WARN( "Tried to fill compound array with non-map value! Skipped." ); no_error = false; continue; } auto &child = array.isFixedSize() ? array[i] : array.appendEmpty(); fillMessage( child, variant ); } return no_error; } case MessageTypes::Array: ROS_ERROR_ONCE( "Arrays of arrays are not supported!" ); break; } return false; } template<> bool fillArrayFromVariant( ros_babel_fish::Message &msg, const QAbstractListModel &list ) { if ( msg.type() != MessageTypes::Array ) { ROS_WARN( "Invalid value passed to fillMessage!" ); return false; } auto &array = msg.as<ArrayMessageBase>(); size_t count = list.rowCount(); if ( array.isFixedSize() && count > array.length()) { ROS_WARN( "Too many values for fixed size array (%lu vs %lu)! Only using first %lu.", count, array.length(), array.length()); count = array.length(); } switch ( array.elementType()) { case MessageTypes::None: break; case MessageTypes::Bool: return fillArray<bool>( array, list ); case MessageTypes::UInt8: return fillArray<uint8_t>( array, list ); case MessageTypes::UInt16: return fillArray<uint16_t>( array, list ); case MessageTypes::UInt32: return fillArray<uint32_t>( array, list ); case MessageTypes::UInt64: return fillArray<uint64_t>( array, list ); case MessageTypes::Int8: return fillArray<int8_t>( array, list ); case MessageTypes::Int16: return fillArray<int16_t>( array, list ); case MessageTypes::Int32: return fillArray<int32_t>( array, list ); case MessageTypes::Int64: return fillArray<int64_t>( array, list ); case MessageTypes::Float32: return fillArray<float>( array, list ); case MessageTypes::Float64: return fillArray<double>( array, list ); case MessageTypes::Time: return fillArray<ros::Time>( array, list ); case MessageTypes::Duration: return fillArray<ros::Duration>( array, list ); case MessageTypes::String: { auto &array = msg.as<ArrayMessage<std::string>>(); bool no_error = true; for ( size_t i = 0; i < count; ++i ) { QModelIndex index = list.index( i, 0 ); const QVariant &variant = list.data( index ); if ( variant.type() != QVariant::String ) { ROS_WARN( "Tried to fill string array with non-string value! Skipped." ); no_error = false; continue; } if ( array.isFixedSize()) array.assign( i, variant.toString().toStdString()); else array.push_back( variant.toString().toStdString()); } return no_error; } case MessageTypes::Compound: { auto &array = msg.as<CompoundArrayMessage>(); bool no_error = true; QHash<int, QByteArray> roleNames = list.roleNames(); if ( roleNames.empty()) return true; std::vector<std::string> names; { int max_key = 0; for ( auto key: roleNames.keys()) max_key = std::max( max_key, key ); names.resize( max_key + 1 ); } // Collect keys QHashIterator<int, QByteArray> it( roleNames ); while ( it.hasNext()) { it.next(); names[it.key()] = it.value().data(); } // Check that all keys are in message const std::vector<std::string> &compound_names = array.elementTemplate()->compound.names; for ( auto &name: names ) { const std::string &key = name; if ( key.empty()) continue; if ( std::find( compound_names.begin(), compound_names.end(), key ) == compound_names.end()) { ROS_WARN_STREAM( "Message doesn't have field '" << key << "'!" ); no_error = false; name = std::string(); } } for ( size_t i = 0; i < count; ++i ) { QModelIndex index = list.index( i ); auto &child = array.isFixedSize() ? array[i] : array.appendEmpty(); auto &compound = child.as<CompoundMessage>(); for ( size_t j = 0; j < names.size(); ++j ) { const std::string &key = names[j]; if ( key.empty()) continue; no_error &= fillMessage( compound[key], index.data( j )); } } return no_error; } case MessageTypes::Array: ROS_ERROR_ONCE( "Arrays of arrays are not supported!" ); break; } return false; } bool fillMessage( BabelFish &fish, ros_babel_fish::Message &msg, const QVariant &value ) { if ( value.canConvert<QVariantMap>() && msg.type() == MessageTypes::Compound ) { auto &compound = msg.as<CompoundMessage>(); const QVariantMap &map = value.value<QVariantMap>(); bool no_error = true; for ( auto &key: map.keys()) { std::string skey = key.toStdString(); if ( !compound.containsKey( skey )) { ROS_WARN_STREAM( "Message doesn't have field '" << skey << "'!" ); no_error = false; continue; } no_error &= fillMessage( fish, compound[skey], map[key] ); } return no_error; } else if ( value.canConvert<Array>() && msg.type() == MessageTypes::Array ) { return fillArrayFromVariant( msg, value.value<Array>()); } else if ( value.canConvert<QVariantList>() && msg.type() == MessageTypes::Array ) { const QVariantList &list = value.value<QVariantList>(); return fillArrayFromVariant( msg, list ); } else if ( value.canConvert<QObject *>()) { const auto *list_model = value.value<QAbstractListModel *>(); if ( list_model != nullptr ) { return fillArrayFromVariant( msg, *list_model ); } if ( msg.type() == MessageTypes::Compound ) { const auto *obj = value.value<QObject *>(); const QMetaObject *metaObj = obj->metaObject(); auto &compound = msg.as<CompoundMessage>(); bool no_error = true; for ( int i = metaObj->propertyOffset(); i < metaObj->propertyCount(); ++i ) { QMetaProperty prop = metaObj->property( i ); std::string skey = prop.name(); // Skip keys that don't exist, we don't warn here because there will very likely be properties that don't exist. if ( !compound.containsKey( skey )) continue; no_error &= fillMessage( fish, compound[skey], prop.read( obj )); } return no_error; } } else if ( value.type() == QVariant::Vector2D && msg.type() == MessageTypes::Compound ) { auto vector = value.value<QVector2D>(); auto &compound = msg.as<CompoundMessage>(); bool no_error = true; int i = 0; for ( const auto &key: { "x", "y" } ) { if ( !compound.containsKey( key )) { ROS_WARN_THROTTLE_NAMED( 1.0, "qml_ros_plugin", "Tried to set QVector2D to compound message that has no %s property", key ); no_error = false; continue; } no_error &= fillMessage( fish, compound[key], vector[i++] ); } return no_error; } else if ( value.type() == QVariant::Vector3D && msg.type() == MessageTypes::Compound ) { QVector3D vector = value.value<QVector3D>(); auto &compound = msg.as<CompoundMessage>(); bool no_error = true; int i = 0; for ( const auto &key: { "x", "y", "z" } ) { if ( !compound.containsKey( key )) { ROS_WARN_THROTTLE_NAMED( 1.0, "qml_ros_plugin", "Tried to set QVector3D to compound message that has no %s property", key ); no_error = false; continue; } no_error &= fillMessage( fish, compound[key], vector[i++] ); } return no_error; } else if ( value.type() == QVariant::Vector4D && msg.type() == MessageTypes::Compound ) { auto vector = value.value<QVector4D>(); auto &compound = msg.as<CompoundMessage>(); bool no_error = true; int i = 0; for ( const auto &key: { "x", "y", "z", "w" } ) { if ( !compound.containsKey( key )) { ROS_WARN_THROTTLE_NAMED( 1.0, "qml_ros_plugin", "Tried to set QVector4D to compound message that has no %s property", key ); no_error = false; continue; } no_error &= fillMessage( fish, compound[key], vector[i++] ); } return no_error; } else if ( value.type() == QVariant::Quaternion && msg.type() == MessageTypes::Compound ) { auto quaternion = value.value<QQuaternion>(); auto &compound = msg.as<CompoundMessage>(); bool no_error = true; for ( const std::string &key: { "w", "x", "y", "z" } ) { if ( !compound.containsKey( key )) { ROS_WARN_THROTTLE_NAMED( 1.0, "qml_ros_plugin", "Tried to set QQuaternion to compound message that has no %s property", key.c_str()); no_error = false; continue; } if ( key == "w" ) no_error &= fillMessage( fish, compound[key], quaternion.scalar()); else if ( key == "x" ) no_error &= fillMessage( fish, compound[key], quaternion.x()); else if ( key == "y" ) no_error &= fillMessage( fish, compound[key], quaternion.y()); else no_error &= fillMessage( fish, compound[key], quaternion.z()); } return no_error; } if ( msg.type() & (MessageTypes::Array | MessageTypes::Compound)) { ROS_WARN_STREAM( "Invalid type for array/compound message: " << value.typeName() << " (" << value.type() << ")" ); return false; } switch ((int) value.type()) { case QVariant::Invalid: break; case QVariant::Bool: return fillValue<bool>( msg, value.toBool(), MessageTypes::Bool ); // Since it is specifically a bool, we don't accept other types case QMetaType::Short: case QMetaType::SChar: case QVariant::Int: { int val = value.toInt(); return fillValue<int>( msg, val, getCompatibleTypes( val )); } case QMetaType::UShort: case QMetaType::UChar: case QVariant::UInt: { uint val = value.toUInt(); return fillValue<uint>( msg, val, getCompatibleTypes( val )); } case QMetaType::Long: case QVariant::LongLong: { qlonglong val = value.toLongLong(); return fillValue<qlonglong>( msg, val, getCompatibleTypes( val )); } case QMetaType::ULong: case QVariant::ULongLong: { qulonglong val = value.toULongLong(); return fillValue<qulonglong>( msg, val, getCompatibleTypes( val )); } case QMetaType::Float: case QVariant::Double: { double val = value.toDouble(); return fillValue<double>( msg, value.toDouble(), getCompatibleTypes( val )); } case QVariant::String: return fillValue<std::string>( msg, value.toString().toStdString(), 0 /* ignored for this special case anyway */); case QVariant::Url: return fillValue<std::string>( msg, value.toUrl().toString().toStdString(), 0 /* same */ ); case QVariant::DateTime: return fillValue<ros::Time>( msg, qmlToRosTime( value.toDateTime()), MessageTypes::Time ); case QVariant::Date: // Not sure if any of these types should be supported case QVariant::Time: case QVariant::Char: default: if ( value.canConvert<Time>()) { return fillValue<ros::Time>( msg, value.value<Time>().getRosTime(), MessageTypes::Time ); } if ( value.canConvert<WallTime>()) { ros::WallTime wall_time = value.value<WallTime>().getRosTime(); return fillValue<ros::Time>( msg, ros::Time( wall_time.sec, wall_time.nsec ), MessageTypes::Time ); } if ( value.canConvert<QVariantMap>()) { const QVariantMap &map = value.value<QVariantMap>(); if ( msg.type() == MessageTypes::Time ) { uint32_t sec = 0; if ( map.contains( "sec" )) sec = map["sec"].toUInt(); uint32_t nsec = 0; if ( map.contains( "nsec" )) nsec = map["nsec"].toUInt(); msg.as<ValueMessage<ros::Time>>().setValue( ros::Time( sec, nsec )); return true; } else if ( msg.type() == MessageTypes::Duration ) { int32_t sec = 0; if ( map.contains( "sec" )) sec = map["sec"].toInt(); int32_t nsec = 0; if ( map.contains( "nsec" )) nsec = map["nsec"].toInt(); msg.as<ValueMessage<ros::Duration>>().setValue( ros::Duration( sec, nsec )); return true; } } ROS_WARN( "Unsupported QVariant type '%s' encountered while filling message!", value.typeName()); break; } return false; } } }
35.452685
120
0.637498
[ "vector", "transform" ]
059d169e23eb1fc38f32913d2be1839a1501c956
4,143
cpp
C++
src/Library/PhotonMapping/GlobalSpectralPhotonTracer.cpp
aravindkrishnaswamy/rise
297d0339a7f7acd1418e322a30a21f44c7dbbb1d
[ "BSD-2-Clause" ]
1
2018-12-20T19:31:02.000Z
2018-12-20T19:31:02.000Z
src/Library/PhotonMapping/GlobalSpectralPhotonTracer.cpp
aravindkrishnaswamy/rise
297d0339a7f7acd1418e322a30a21f44c7dbbb1d
[ "BSD-2-Clause" ]
null
null
null
src/Library/PhotonMapping/GlobalSpectralPhotonTracer.cpp
aravindkrishnaswamy/rise
297d0339a7f7acd1418e322a30a21f44c7dbbb1d
[ "BSD-2-Clause" ]
null
null
null
////////////////////////////////////////////////////////////////////// // // GlobalSpectralPhotonTracer.cpp - Implementation of the GlobalSpectralPhotonTracer class // // Author: Aravind Krishnaswamy // Date of Birth: October 8, 2002 // Tabs: 4 // Comments: // // License Information: Please see the attached LICENSE.TXT file // ////////////////////////////////////////////////////////////////////// #include "pch.h" #include "GlobalSpectralPhotonTracer.h" #include "../Utilities/RandomNumbers.h" #include "../Interfaces/ILog.h" #include "../Intersection/RayIntersection.h" using namespace RISE; using namespace RISE::Implementation; #define ENABLE_MAX_RECURSION GlobalSpectralPhotonTracer::GlobalSpectralPhotonTracer( const unsigned int maxR, ///< [in] Maximum recursion depth const Scalar ext, ///< [in] Minimum importance for a photon before extinction const Scalar nm_begin_, ///< [in] Wavelength to start shooting photons at const Scalar nm_end_, ///< [in] Wavelength to end shooting photons at const unsigned int num_wavelengths_, ///< [in] Number of wavelengths to shoot photons at const bool useiorstack, ///< [in] Should we use an ior stack ? const bool branch, ///< [in] Should the tracer branch or only follow one path? const Scalar powerscale, const unsigned int temporal_samples, const bool regenerate ) : SpectralPhotonTracer<GlobalSpectralPhotonMap>( nm_begin_, nm_end_, num_wavelengths_, useiorstack, powerscale, temporal_samples, regenerate ), nMaxRecursions( maxR ), dExtinction( ext ), bBranch( branch ) { } GlobalSpectralPhotonTracer::~GlobalSpectralPhotonTracer( ) { } void GlobalSpectralPhotonTracer::TracePhoton( const Ray& ray, const Scalar power, const Scalar nm, bool bStorePhoton, GlobalSpectralPhotonMap& pPhotonMap, const IORStack* const ior_stack ///< [in/out] Index of refraction stack ) const { static unsigned int numRecursions = 0; #ifdef ENABLE_MAX_RECURSION if( numRecursions > nMaxRecursions ) { #ifdef ENABLE_TERMINATION_MESSAGES GlobalLog()->PrintEasyInfo( "FORCED RECURSION TERMINATION" ); #endif return; } #endif if( power < dExtinction ) { #ifdef ENABLE_TERMINATION_MESSAGES GlobalLog()->PrintEasyInfo( "PHOTON BECAME EXTINCT :(" ); #endif return; } numRecursions++; // Cast the ray into the scene RayIntersection ri( ray, nullRasterizerState ); Vector3Ops::NormalizeMag(ri.geometric.ray.dir); pScene->GetObjects()->IntersectRay( ri, true, true, false ); if( ri.geometric.bHit ) { // If there is an intersection modifier, then get it to modify // the intersection information if( ri.pModifier ) { ri.pModifier->Modify( ri.geometric ); } // Set the current object on the IOR stack if( ior_stack ) { ior_stack->SetCurrentObject( ri.pObject ); } ISPF* pSPF = ri.pMaterial->GetSPF(); if( pSPF ) { // Get information from the material as to what to do ScatteredRayContainer scattered; pSPF->ScatterNM( ri.geometric, random, nm, scattered, ior_stack ); bool bDiffuseComponentAvailable = false; for( unsigned int i=0; i<scattered.Count(); i++ ) { ScatteredRay& scat = scattered[i]; if( scat.type==ScatteredRay::eRayDiffuse ) { bDiffuseComponentAvailable = true; break; } } if( bDiffuseComponentAvailable && bStorePhoton ) { pPhotonMap.Store( power, nm, ri.geometric.ptIntersection, -ray.dir ); } if( bBranch ) { for( unsigned int i=0; i<scattered.Count(); i++ ) { ScatteredRay& scat = scattered[i]; scat.ray.Advance( 1e-8 ); TracePhoton( scat.ray, power*scat.krayNM, nm, scat.type==ScatteredRay::eRayDiffuse, pPhotonMap, scat.ior_stack?scat.ior_stack:ior_stack ); } } else { ScatteredRay* pScat = scattered.RandomlySelect( random.CanonicalRandom(), true ); if( pScat ) { pScat->ray.Advance( 1e-8 ); TracePhoton( pScat->ray, power*pScat->krayNM, nm, pScat->type==ScatteredRay::eRayDiffuse, pPhotonMap, pScat->ior_stack?pScat->ior_stack:ior_stack ); } } } } // If there was no hit then the photon just got ejected into space! numRecursions--; }
29.382979
153
0.684045
[ "object" ]
05a0c23fe7772fff188b08f9e1b4b8a8e4edf8a0
5,111
cc
C++
src/cpp/examples/two_models_two_tpus_threaded.cc
SanggunLee/edgetpu
d3cf166783265f475c1ddba5883e150ee84f7bfe
[ "Apache-2.0" ]
320
2019-09-19T07:10:48.000Z
2022-03-12T01:48:56.000Z
src/cpp/examples/two_models_two_tpus_threaded.cc
Machine-Learning-Practice/edgetpu
6d699665efdc5d84944b5233223c55fe5d3bd1a6
[ "Apache-2.0" ]
563
2019-09-27T06:40:40.000Z
2022-03-31T23:12:15.000Z
src/cpp/examples/two_models_two_tpus_threaded.cc
Machine-Learning-Practice/edgetpu
6d699665efdc5d84944b5233223c55fe5d3bd1a6
[ "Apache-2.0" ]
119
2019-09-25T02:51:10.000Z
2022-03-03T08:11:12.000Z
// Example to run two models with two Edge TPUs using two threads. // It depends only on tflite and edgetpu.h // // Example usage: // 1. Create directory /tmp/edgetpu_cpp_example // 2. wget -O /tmp/edgetpu_cpp_example/inat_bird_edgetpu.tflite \ // http://storage.googleapis.com/cloud-iot-edge-pretrained-models/canned_models/mobilenet_v2_1.0_224_inat_bird_quant_edgetpu.tflite // 3. wget -O /tmp/edgetpu_cpp_example/inat_plant_edgetpu.tflite \ // http://storage.googleapis.com/cloud-iot-edge-pretrained-models/canned_models/mobilenet_v2_1.0_224_inat_plant_quant_edgetpu.tflite // 4. wget -O /tmp/edgetpu_cpp_example/bird.jpg \ // https://farm3.staticflickr.com/8008/7523974676_40bbeef7e3_o.jpg // 5. wget -O /tmp/edgetpu_cpp_example/plant.jpg \ // https://c2.staticflickr.com/1/62/184682050_db90d84573_o.jpg // 6. cd /tmp/edgetpu_cpp_example && mogrify -format bmp *.jpg // 7. Build and run `two_models_two_tpus_threaded` // // To reduce variation between different runs, one can disable CPU scaling with // sudo cpupower frequency-set --governor performance #include <algorithm> #include <chrono> // NOLINT #include <iostream> #include <memory> #include <string> #include <thread> // NOLINT #include "edgetpu.h" #include "src/cpp/examples/model_utils.h" #include "src/cpp/test_utils.h" #include "tensorflow/lite/interpreter.h" #include "tensorflow/lite/model.h" int main(int argc, char* argv[]) { if (argc != 1 && argc != 5) { std::cout << argv[0] << " <bird_model> <plant_model> <bird_image> <plant_image>" << std::endl; return 1; } // Modify the following accordingly to try different models. const std::string bird_model_path = argc == 5 ? argv[1] : coral::GetTempPrefix() + "/edgetpu_cpp_example/inat_bird_edgetpu.tflite"; const std::string plant_model_path = argc == 5 ? argv[2] : coral::GetTempPrefix() + "/edgetpu_cpp_example/inat_plant_edgetpu.tflite"; const std::string bird_image_path = argc == 5 ? argv[3] : coral::GetTempPrefix() + "/edgetpu_cpp_example/bird.bmp"; const std::string plant_image_path = argc == 5 ? argv[4] : coral::GetTempPrefix() + "/edgetpu_cpp_example/plant.bmp"; const int num_inferences = 2000; const auto& available_tpus = edgetpu::EdgeTpuManager::GetSingleton()->EnumerateEdgeTpu(); if (available_tpus.size() < 2) { std::cerr << "This example requires two Edge TPUs to run." << std::endl; return 0; } auto thread_job = [num_inferences] // NOLINT(clang-diagnostic-unused-lambda-capture) (const edgetpu::EdgeTpuManager::DeviceEnumerationRecord& tpu, const std::string& model_path, const std::string& image_path) { const auto& tid = std::this_thread::get_id(); std::cout << "Thread: " << tid << " Using model: " << model_path << " Running " << num_inferences << " inferences." << std::endl; std::unordered_map<std::string, std::string> options = { {"Usb.MaxBulkInQueueLength", "8"}, }; auto tpu_context = edgetpu::EdgeTpuManager::GetSingleton()->OpenDevice( tpu.type, tpu.path, options); std::unique_ptr<tflite::FlatBufferModel> model = tflite::FlatBufferModel::BuildFromFile(model_path.c_str()); if (model == nullptr) { std::cerr << "Fail to build FlatBufferModel from file: " << model_path << std::endl; std::abort(); } std::unique_ptr<tflite::Interpreter> interpreter = coral::BuildEdgeTpuInterpreter(*model, tpu_context.get()); std::cout << "Thread: " << tid << " Interpreter was built." << std::endl; std::vector<uint8_t> input = coral::GetInputFromImage( image_path, coral::GetInputShape(*interpreter, 0)); for (int i = 0; i < num_inferences; ++i) { coral::RunInference(input, interpreter.get()); } // Print inference result. const auto& result = coral::RunInference(input, interpreter.get()); auto it_a = std::max_element(result.begin(), result.end()); std::cout << "Thread: " << tid << " printing analysis result. Max value index: " << std::distance(result.begin(), it_a) << " value: " << *it_a << std::endl; }; const auto& start_time = std::chrono::steady_clock::now(); std::thread bird_model_thread(thread_job, available_tpus[0], bird_model_path, bird_image_path); std::thread plant_model_thread(thread_job, available_tpus[1], plant_model_path, plant_image_path); bird_model_thread.join(); plant_model_thread.join(); std::chrono::duration<double> time_span = std::chrono::steady_clock::now() - start_time; std::cout << "Using two Edge TPUs, # inferences: " << num_inferences << " costs: " << time_span.count() << " seconds." << std::endl; return 0; }
43.683761
137
0.630405
[ "vector", "model" ]
05a85b1af619d0da57a060cb7c96e748efb401c3
5,210
hpp
C++
include/Modbus.hpp
StratifyLabs/ModbusRTU
706446abadd7a89cbe3fd7df64cff374da0a3a19
[ "Apache-2.0" ]
null
null
null
include/Modbus.hpp
StratifyLabs/ModbusRTU
706446abadd7a89cbe3fd7df64cff374da0a3a19
[ "Apache-2.0" ]
null
null
null
include/Modbus.hpp
StratifyLabs/ModbusRTU
706446abadd7a89cbe3fd7df64cff374da0a3a19
[ "Apache-2.0" ]
1
2021-03-02T01:35:56.000Z
2021-03-02T01:35:56.000Z
#ifndef MODBUS_MODBUS_HPP #define MODBUS_MODBUS_HPP #include <mcu/types.h> #include <sapi/sys/Thread.hpp> #include <sapi/var/Data.hpp> #include <sapi/chrono/MicroTime.hpp> #include <sapi/chrono/Timer.hpp> #include <sapi/var/String.hpp> namespace mbus { class ModbusObject { public: const var::String & error_message() const { return m_error_message; } protected: void set_error_message(const var::ConstString & value){ m_error_message = value; } private: var::String m_error_message; }; class ModbusPhy : public ModbusObject { public: virtual int initialize(){ return 0; } //success if not implemented virtual int finalize(){ return 0; } //success if not implemented virtual int send(const var::Data & data) = 0; virtual var::Data receive() = 0; void flush(){ buffer().free(); } u8 calculate_lrc(const var::Data & data); u16 calculate_crc(const var::Data & data); protected: var::Data & buffer(){ return m_buffer; } private: var::Data m_buffer; }; class Modbus : public ModbusObject { public: Modbus(ModbusPhy & phy); enum { NONE = 0, ILLEGAL_FUNCTION = 1, ILLEGAL_DATA_ADDRESS = 2, ILLEGAL_DATA_VALUE = 3, SLAVE_DEVICE_FAILURE = 4, ACKNOWLEDGE = 5, SLAVE_DEVICE_BUSY = 6, NEGATIVE_ACKNOWLEDGE = 7, MEMORY_PARITY_ERROR = 8 }; enum function_code { READ_COIL_STATUS = 0x01, READ_INPUT_STATUS = 0x02, READ_HOLDING_REGISTERS = 0x03, READ_INPUT_REGISTERS = 0x04, FORCE_SINGLE_COIL = 0x05, PRESET_SINGLE_REGISTER = 0x06, READ_EXCEPTION_STATUS = 0x07, DIAGNOSTICS = 0x08, PROGRAM_484 = 0x09, POLL_484 = 0x10, FETCH_COMMUNICATION_EVENT_CONTROLLER = 0x11, FETCH_COMMUNICATION_EVENT_LOG = 0x12, PROGRAM_CONTROLLER = 0x13, POLL_CONTROLLER = 0x14, FORCE_MULTIPLE_COILS = 0x15, PRESET_MULTIPLE_REGISTERS = 0x16, REPORT_SLAVE_ID = 0x17, PROGRAM_884_M84 = 0x18, RESET_COMMUNICATIONS_LINK = 0x19, READ_GENERAL_REFERENCE = 0x20, WRITE_GENERAL_REFERENCE = 0x21 }; void set_max_packet_size(u32 value){ m_max_packet_size = value; } u32 max_packet_size() const { return m_max_packet_size; } protected: int send_read_holding_registers_query(u8 slave_address, u16 register_address, u16 number_of_points); int send_read_holding_registers_response(u8 slave_address, const var::Data & data); int send_preset_single_register_query(u8 slave_address, u16 register_address, u16 value); int send_preset_single_register_response(u8 slave_address, u16 register_address, u16 value); int send_exception_response(u8 slave_address, u8 function_code); void set_exception_code(u16 exception_code){ m_exception_code = exception_code; } u8 exception_code() const { return m_exception_code; } ModbusPhy & phy(){ return m_phy; } private: int send_query(u8 slave_address, enum function_code function_code, const var::Data & data); int send_response(u8 slave_address, enum function_code function_code, const var::Data & data); ModbusPhy & m_phy; u16 m_exception_code; u32 m_max_packet_size; }; class ModbusMaster : public Modbus { public: ModbusMaster(ModbusPhy & phy) : Modbus(phy){ m_timeout = chrono::MicroTime::from_milliseconds(1000); } int initialize(){ int result = phy().initialize(); if( result < 0 ){ set_error_message(var::String().format("phy initialize; %s", phy().error_message().to_char())); } return result; } void finalize(){ phy().finalize(); } var::Data read_holding_registers(u8 slave_address, u16 register_address, u16 number_of_points); int preset_single_register(u8 slave_address, u16 register_address, u16 value); private: var::Data wait_for_response(); chrono::MicroTime m_timeout; }; class ModbusSlave : public Modbus { public: ModbusSlave(ModbusPhy & phy, int stack_size = 1024) : Modbus(phy), m_thread(stack_size){ set_polling_interval(chrono::MicroTime(10000)); } int initialize(); void finalize(){ m_is_running = false; m_thread.wait(); } void set_slave_address(u8 slave_address){ m_slave_address = slave_address; } virtual int preset_single_register(u16 register_address, u16 value){ set_exception_code(ILLEGAL_FUNCTION); return -1; } virtual var::Data read_holding_registers(u16 register_address, u16 size){ set_exception_code(ILLEGAL_FUNCTION); return -1; } void set_polling_interval(const chrono::MicroTime & interval){ m_interval = interval; } const chrono::MicroTime polling_interval() const { return m_interval; } private: u32 m_max_packet_size; volatile bool m_is_running; u8 m_slave_address; sys::Thread m_thread; static void * listen_worker(void * args){ ModbusSlave * object = (ModbusSlave*)args; return object->listen(); } void * listen(); chrono::MicroTime m_interval; }; } #endif // MODBUS_MODBUS_HPP
26.717949
107
0.677735
[ "object" ]
05ade6ad830a03c862d0899a4fcf0466a5db5e53
5,448
cpp
C++
src/cpp11.cpp
jianggx/learn_cpp
82e8d29c89d752660d7be34ceb29450f5eafaa22
[ "MIT" ]
1
2018-10-20T17:59:22.000Z
2018-10-20T17:59:22.000Z
src/cpp11.cpp
jianggx/learn_cpp
82e8d29c89d752660d7be34ceb29450f5eafaa22
[ "MIT" ]
null
null
null
src/cpp11.cpp
jianggx/learn_cpp
82e8d29c89d752660d7be34ceb29450f5eafaa22
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include "include/add.h" // 1, initialize list class MyVector{ std::vector<int> m_vec; public: MyVector(const std::initializer_list<int>& list){ // initialize list constructor for(auto x : list){ m_vec.push_back(x); } } }; void test_initializerList(){ int arr[3] = {1,2,3}; // c++ 03 std::vector<int> b = {1,2,3}; // initializer list MyVector myvec = {1,2,3}; // // initializer list } // 2, uniform initializer class AggregateIntializer{ public: int age; std::string name; }; class RegularConstructor{ public: RegularConstructor (int age, std::string name){ } }; void test_uniformInitializer(){ AggregateIntializer a = {1, "leo"}; // c++ 03, aggregate initalizer AggregateIntializer a2{1, "leo"}; // c++ 03, aggregate initalizer RegularConstructor b = {1, "leo"}; // regular constructor RegularConstructor b2 {1, "leo"}; // regular constructor MyVector myvec = {1,2,3}; // initializer list MyVector myvec2{1,2,3}; // initializer list // priority: initializer list > regular constructor > aggregate initalizer } // 3, auto type int test_auto(){ auto a = 3; // type inferece auto b = "abc"; auto c = 0.4; auto d = c; std::vector<int> v = {1,2,3}; // initializer list // c++ 03 for(std::vector<int>::iterator it = v.begin(); it !=v.end(); ++it){ std::cout << *it << std::endl; } // auto type for(auto it = v.begin(); it !=v.end(); ++it){ std::cout << *it << std::endl; } return 0; } // 4, foreach void test_foreach() { std::vector<int> v = {1,2,3}; // initializer list // foreach works on class that has begin() and end() for(auto i : v){ std::cout << i << std::endl; } for(auto &i : v){ ++i; // change value in v } } // 5, nullptr // NULL is just defined as 0, nullptr specify to pointer to avoid ambiguty void foo(int i) { std::cout << i << std::endl; } void foo(char* pc) { std::cout << R"(foo(char* pc) )" << std::endl; } void test_nullptr() { // foo(NULL); // not compile foo(nullptr); // call foo(char* pc) } // 6, enum class // c++ 03 enum Apple {green, red}; enum Orange {big, small}; enum class Apple_C {green, red}; enum class Orange_C {big, small}; void test_enumClass(){ Apple a = Apple::green; Orange b = Orange::big; // can compare! not make sense if(a == b){ std::cout << "can compare! not make sense" << std::endl; } Apple_C a2 = Apple_C::green; Orange_C b2 = Orange_C::big; // not compile, that make sense /* if(a2 == b2){ std::cout << "can compare! not make sense" << std::endl; } */ } // 7, static assert void test_staticAssert(){ // compile time assert, faster static_assert(sizeof(int)==4); } // 8, delegate constructor class DelegateConstructor{ public: DelegateConstructor(){ std::cout<< "some base construction" << std::endl; } // delegate constructor DelegateConstructor(int x): DelegateConstructor(){ std::cout<< "do some other things" << std::endl; } }; void test_delegateConstructor(){ DelegateConstructor d(2); } // 9, override class Dog{ public: virtual void foo(int x) const { std::cout<< "Dog foo" << std::endl; }; }; class YellowDog : public Dog{ public: void foo(int x) const override { std::cout<< "YellowDog foo" << std::endl; }; }; // 10, final // final class : no subclass // final virtual : no override in subclass class BlackDog final : public Dog { void foo(int x) const override final { std::cout<< "YellowDog foo" << std::endl; }; }; // 11, compile generate default constructor class DefConstructor{ public: DefConstructor(int x){ std::cout<< "no default constructor will be generated as already has this" << std::endl; } DefConstructor() = default; // force to generate a default constructor }; // 12, delete class Delete{ public: Delete(int x){}; Delete(double d) = delete; // delete this constructor explicitly Delete& operator=(const Delete& other) = delete; // delete the assign operator }; void test_delete() { Delete d(1); // works //Delete e(1.5); // not compile, as the Delete(double d) is deleted //d = e; // not compile, as the operator= function is deleted } // 13, constexpr constexpr int A(int x){return x*3;} void test_constexpr(){ int arr[A(1)+2]; // this works int y = A(2) + 3; // computer at comile time } // 14, new string literal void test_string_literals(){ // c++ 03 way const char* cpp03 = "abc"; // c++ 11 const char* a = u8"abc"; // utf8 string const char16_t* b = u"abc"; // utf16 string const char32_t* c = U"abc"; // utf32 string const char* d = R"(abc)"; // raw string, note that the () is the row string delimeter } // 15, lambda int test_lambda(int x){ int y =5; auto func = [](int x){return x - 5;}; auto func2 = [&](int x){return x - y;}; // & for variable capture return func(x)+func2(x); } int main() { test_initializerList(); test_uniformInitializer(); test_auto(); test_foreach(); test_nullptr(); test_enumClass(); test_staticAssert(); test_delegateConstructor(); test_delete(); test_constexpr(); test_string_literals(); test_lambda(3); return 0; }
23.790393
96
0.601138
[ "vector" ]
05b1e9bd02260129864396d9b0df21b4996c6abe
2,849
cpp
C++
Tree_Problems_Template.cpp
vicennial/Competitive-Coding-Library
48e338ca5f572d44d8f4224cdb373bb0cab5b856
[ "MIT" ]
1
2019-02-20T06:44:04.000Z
2019-02-20T06:44:04.000Z
Tree_Problems_Template.cpp
vicennial/Competitive-Coding-Library
48e338ca5f572d44d8f4224cdb373bb0cab5b856
[ "MIT" ]
null
null
null
Tree_Problems_Template.cpp
vicennial/Competitive-Coding-Library
48e338ca5f572d44d8f4224cdb373bb0cab5b856
[ "MIT" ]
null
null
null
//Gvs Akhil (Vicennial) #include<bits/stdc++.h> #define int long long #define pb push_back #define eb emplace_back #define mp make_pair #define mt make_tuple #define ld(a) while(a--) #define tci(v,i) for(auto i=v.begin();i!=v.end();i++) #define tcf(v,i) for(auto i : v) #define all(v) v.begin(),v.end() #define rep(i,start,lim) for(long long (i)=(start);i<(lim);i++) #define sync ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0) #define osit ostream_iterator #define INF 0x3f3f3f3f #define LLINF 1000111000111000111LL #define PI 3.14159265358979323 #define endl '\n' #define trace1(x) cerr<<#x<<": "<<x<<endl #define trace2(x, y) cerr<<#x<<": "<<x<<" | "<<#y<<": "<<y<<endl #define trace3(x, y, z) cerr<<#x<<":" <<x<<" | "<<#y<<": "<<y<<" | "<<#z<<": "<<z<<endl #define trace4(a, b, c, d) cerr<<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<endl #define trace5(a, b, c, d, e) cerr<<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<" | "<<#e<< ": "<<e<<endl #define trace6(a, b, c, d, e, f) cerr<<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<" | "<<#e<< ": "<<e<<" | "<<#f<<": "<<f<<endl const int N=1000006; using namespace std; typedef vector<int> vi; typedef vector<vi> vvi; typedef long long ll; typedef vector<long long> vll; typedef vector<vll> vvll; typedef long double ld; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<vii> vvii; typedef tuple<int,int,int> iii; typedef set<int> si; typedef complex<double> pnt; typedef vector<pnt> vpnt; typedef priority_queue<ii,vii,greater<ii> > spq; const ll MOD=1000000007LL; template<typename T> T gcd(T a,T b){if(a==0) return b; return gcd(b%a,a);} template<typename T> T power(T x,T y,ll m=MOD){T ans=1;while(y>0){if(y&1LL) ans=(ans*x)%m;y>>=1LL;x=(x*x)%m;}return ans%m;} vvi g; const int LF=20; int par[N],level[N],st[N][LF]; void dfs(int n,int p,int ct){ par[n]=p; level[n]=ct; st[n][0]=p; tcf(g[n],i){ if(i==p) continue; dfs(i,n,ct+1); } } void pre(int n){ for(int j=1;(1<<j)<=n;j++){ for(int i=0;i<n;i++){ if(st[i][j-1]!=-1){ st[i][j]=st[st[i][j-1]][j-1]; } } } } int lca(int u,int v){ if(level[u]<level[v]) swap(u,v); int dist=level[u]-level[v]; while(dist){ int k=log2(dist); dist-=(1<<k); u=st[u][k]; } if(u==v) return u; for(int i=LF-1;i>=0;i--){ if(st[u][i]!=-1 && st[u][i]!=st[v][i]){ u=st[u][i]; v=st[v][i]; } } return par[u]; } int32_t main(){ memset(st,-1,sizeof(st)); sync; int n; cin>>n; g.resize(n); rep(i,0,n-1){ int x,y; cin>>x>>y; --x; --y; g[x].eb(y); g[y].eb(x); } dfs(0,-1,0); pre(n); int q; cin>>q; ld(q){ int u,v; cin>>u>>v; cout<<lca(u,v)<<endl; } }
29.071429
158
0.521236
[ "vector" ]
05ba9449f7c227839ad03d6d24c071c33cdb2634
3,366
cpp
C++
asp_commons/src/ASPCommonsTerm.cpp
StephanOpfer/symrock
519f684374124707f684edceb9b53156fe3bafbc
[ "MIT" ]
1
2018-12-04T16:16:41.000Z
2018-12-04T16:16:41.000Z
asp_commons/src/ASPCommonsTerm.cpp
carpe-noctem-cassel/symrock
519f684374124707f684edceb9b53156fe3bafbc
[ "MIT" ]
2
2019-02-28T10:44:06.000Z
2019-03-28T12:31:01.000Z
asp_commons/src/ASPCommonsTerm.cpp
carpe-noctem-cassel/symrock
519f684374124707f684edceb9b53156fe3bafbc
[ "MIT" ]
null
null
null
/* * Term.cpp * * Created on: Jul 13, 2016 * Author: Stefan Jakob */ #include <ASPCommonsTerm.h> #include <SystemConfig.h> namespace reasoner { ASPCommonsTerm::ASPCommonsTerm(int lifeTime) { this->programSection = ""; this->id = -1; this->lifeTime = lifeTime; this->externals = nullptr; this->numberOfModels = ""; this->type = ASPQueryType::Undefined; this->queryId = -1; } ASPCommonsTerm::~ASPCommonsTerm() { } void ASPCommonsTerm::addRule(std::string rule) { this->rules.push_back(rule); } void ASPCommonsTerm::addFact(std::string fact) { if (fact.find(".") == std::string::npos) { this->facts.push_back(fact + "."); } else { this->facts.push_back(fact); } } std::vector<std::string> ASPCommonsTerm::getRuleHeads() { return this->heads; } std::vector<std::string> ASPCommonsTerm::getRuleBodies() { return this->bodies; } std::string ASPCommonsTerm::getProgramSection() { return this->programSection; } void ASPCommonsTerm::setProgramSection(std::string programSection) { this->programSection = programSection; } int ASPCommonsTerm::getLifeTime() { return this->lifeTime; } void ASPCommonsTerm::setLifeTime(int lifeTime) { this->lifeTime = lifeTime; } std::vector<std::string> ASPCommonsTerm::getRules() { return this->rules; } std::vector<std::string> ASPCommonsTerm::getFacts() { return this->facts; } void ASPCommonsTerm::setExternals(std::shared_ptr<std::map<std::string, bool>> externals) { this->externals = externals; } std::shared_ptr<std::map<std::string, bool> > ASPCommonsTerm::getExternals() { return this->externals; } std::string ASPCommonsTerm::getNumberOfModels() { return this->numberOfModels; } void ASPCommonsTerm::setNumberOfModels(std::string numberOfModels) { this->numberOfModels = numberOfModels; } ASPQueryType ASPCommonsTerm::getType() { return this->type; } void ASPCommonsTerm::setType(ASPQueryType type) { this->type = type; } long ASPCommonsTerm::getId() { return id; } void ASPCommonsTerm::setId(long id) { this->id = id; } /** * The query id has to be added to any predicate which is added to the program, naming rule * heads and facts! * An unique id is given by the ASPSolver! */ int ASPCommonsTerm::getQueryId() { return queryId; } /** * The query id has to be added to any predicate which is added to the program, naming rule * heads and facts! * An unique id is given by the ASPSolver! */ void ASPCommonsTerm::setQueryId(int queryId) { this->queryId = queryId; } std::string ASPCommonsTerm::getQueryRule() { return queryRule; } void ASPCommonsTerm::setQueryRule(std::string queryRule) { if (queryRule.empty()) { return; } queryRule = supplementary::Configuration::trim(queryRule); size_t endOfHead = queryRule.find(":-"); if (endOfHead != std::string::npos) { // for rules (including variables) size_t startOfBody = endOfHead + 2; this->heads.push_back(supplementary::Configuration::trim(queryRule.substr(0, endOfHead))); this->bodies.push_back( supplementary::Configuration::trim(queryRule.substr(startOfBody, queryRule.size() - startOfBody - 1))); } else { // for ground literals this->heads.push_back(queryRule); } this->queryRule = queryRule; } } /* namespace reasoner */
18.910112
108
0.683304
[ "vector" ]
05bc5b30986ce45b44adb23b002ebe1b5b89fd92
3,900
cpp
C++
radiosity/source/ortho_projector.cpp
armenalaray/GI_Solvers
82f12185ac4017ed45e25b3393a5b2140b7ccf0d
[ "MIT" ]
1
2021-04-05T21:22:20.000Z
2021-04-05T21:22:20.000Z
radiosity/source/ortho_projector.cpp
armenalaray/GI_Solvers
82f12185ac4017ed45e25b3393a5b2140b7ccf0d
[ "MIT" ]
null
null
null
radiosity/source/ortho_projector.cpp
armenalaray/GI_Solvers
82f12185ac4017ed45e25b3393a5b2140b7ccf0d
[ "MIT" ]
null
null
null
#include "ortho_projector.h" /* OrthoProjector::render Description: Renders 5 faces of Cornell Box. Parameters: float fw: Cornell Box's face width. float fh: Cornell Box's face height. int th: Image Height. int tw: Image Width. Output: - */ void OrthoProjector::render(float fw, float fh, int th, int tw) { float cg = 0.4f; // NOTE(Alex): XY (0,0) (5,5) Z = 0 { Vec3<float> O{0,0,0}; Vec3<float> X{1,0,0}; Vec3<float> Y{0,1,0}; Vec3<float> d{0,0,-1}; Canvas canvas(X, Y, O, fw, fh, th, tw, cg); if(canvas.open_ppm_file("XY_Z0.ppm")) { do { Vec3<float> p = canvas.get_p_sample(); Ray r{p-d,d}; Color<int> c = space.request_color(r, 0.001f, FLT_MAX); canvas.write_color(c); } while(canvas.not_finished_writing()); canvas.close_ppm_file(); } } { /* X has to be based from 0,0 Y as well Origin has to be the origin!!! */ // NOTE(Alex): YZ (0,0) (5,5) X = 0 Vec3<float> O{0,0,fw}; Vec3<float> X{0,0,-1}; Vec3<float> Y{0,1,0}; Vec3<float> d{-1,0,0}; Canvas canvas(X, Y, O, fw, fh, th, tw, cg); if(canvas.open_ppm_file("YZ_X0.ppm")) { do { Vec3<float> p = canvas.get_p_sample(); Ray r{p-d,d}; Color<int> c = space.request_color(r, 0.001f, FLT_MAX); canvas.write_color(c); } while(canvas.not_finished_writing()); canvas.close_ppm_file(); } } { /* X has to be based from 0,0 Y as well Origin has to be the origin!!! */ // NOTE(Alex): XZ (0,0) (5,5) Y = 0 Vec3<float> O{fw,0,fw}; Vec3<float> X{0,0,-1}; Vec3<float> Y{-1,0,0}; Vec3<float> d{0,-1,0}; Canvas canvas(X, Y, O, fw, fh, th, tw, cg); if(canvas.open_ppm_file("XZ_Y0.ppm")) { do { Vec3<float> p = canvas.get_p_sample(); Ray r{p-d,d}; Color<int> c = space.request_color(r, 0.001f, FLT_MAX); canvas.write_color(c); } while(canvas.not_finished_writing()); canvas.close_ppm_file(); } } { /* X has to be based from 0,0 Y as well Origin has to be the origin!!! */ // NOTE(Alex): YZ (0,0) (5,5) X = 5.0f Vec3<float> O{fw,0,0}; Vec3<float> X{0,0,1}; Vec3<float> Y{0,1,0}; Vec3<float> d{1,0,0}; Canvas canvas(X, Y, O, fw, fh, th, tw, cg); if(canvas.open_ppm_file("YZ_X5.ppm")) { do { Vec3<float> p = canvas.get_p_sample(); Ray r{p-d,d}; Color<int> c = space.request_color(r, 0.001f, FLT_MAX); canvas.write_color(c); } while(canvas.not_finished_writing()); canvas.close_ppm_file(); } } { /* X has to be based from 0,0 Y as well Origin has to be the origin!!! */ // NOTE(Alex): XZ (0,0) (5,5) Y = 5.0f Vec3<float> O{fw,fw,0}; Vec3<float> X{0,0,1}; Vec3<float> Y{-1,0,0}; Vec3<float> d{0,1,0}; Canvas canvas(X, Y, O, fw, fh, th, tw, cg); if(canvas.open_ppm_file("XZ_Y5.ppm")) { do { Vec3<float> p = canvas.get_p_sample(); Ray r{p-d,d}; Color<int> c = space.request_color(r, 0.001f, FLT_MAX); canvas.write_color(c); } while(canvas.not_finished_writing()); canvas.close_ppm_file(); } } }
26
71
0.456667
[ "render" ]
05be659606c0dc93abf21da600da2449966c42a9
18,124
cc
C++
test/cctest/wasm/test-gc.cc
jie-pan/v8
780a495c58a32ff17d4b4332a122aea1d2e0f0b1
[ "BSD-3-Clause" ]
1
2020-06-01T18:07:24.000Z
2020-06-01T18:07:24.000Z
test/cctest/wasm/test-gc.cc
jie-pan/v8
780a495c58a32ff17d4b4332a122aea1d2e0f0b1
[ "BSD-3-Clause" ]
null
null
null
test/cctest/wasm/test-gc.cc
jie-pan/v8
780a495c58a32ff17d4b4332a122aea1d2e0f0b1
[ "BSD-3-Clause" ]
1
2020-06-03T13:25:49.000Z
2020-06-03T13:25:49.000Z
// Copyright 2020 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <stdint.h> #include "src/utils/utils.h" #include "src/utils/vector.h" #include "src/wasm/module-decoder.h" #include "src/wasm/struct-types.h" #include "src/wasm/wasm-engine.h" #include "src/wasm/wasm-module-builder.h" #include "src/wasm/wasm-module.h" #include "src/wasm/wasm-objects-inl.h" #include "src/wasm/wasm-opcodes.h" #include "test/cctest/cctest.h" #include "test/cctest/compiler/value-helper.h" #include "test/cctest/wasm/wasm-run-utils.h" #include "test/common/wasm/test-signatures.h" #include "test/common/wasm/wasm-macro-gen.h" #include "test/common/wasm/wasm-module-runner.h" namespace v8 { namespace internal { namespace wasm { namespace test_gc { WASM_EXEC_TEST(BasicStruct) { // TODO(7748): Implement support in other tiers. if (execution_tier == ExecutionTier::kLiftoff) return; if (execution_tier == ExecutionTier::kInterpreter) return; TestSignatures sigs; EXPERIMENTAL_FLAG_SCOPE(gc); EXPERIMENTAL_FLAG_SCOPE(anyref); v8::internal::AccountingAllocator allocator; Zone zone(&allocator, ZONE_NAME); WasmModuleBuilder* builder = new (&zone) WasmModuleBuilder(&zone); StructType::Builder type_builder(&zone, 2); type_builder.AddField(kWasmI32, true); type_builder.AddField(kWasmI32, true); int32_t type_index = builder->AddStructType(type_builder.Build()); ValueType kRefTypes[] = {ValueType(ValueType::kRef, type_index)}; ValueType kOptRefType = ValueType(ValueType::kOptRef, type_index); FunctionSig sig_q_v(1, 0, kRefTypes); // Test struct.new and struct.get. WasmFunctionBuilder* f = builder->AddFunction(sigs.i_v()); f->builder()->AddExport(CStrVector("f"), f); byte f_code[] = {WASM_STRUCT_GET(type_index, 0, WASM_STRUCT_NEW(type_index, WASM_I32V(42), WASM_I32V(64))), kExprEnd}; f->EmitCode(f_code, sizeof(f_code)); // Test struct.new and struct.get. WasmFunctionBuilder* g = builder->AddFunction(sigs.i_v()); g->builder()->AddExport(CStrVector("g"), g); byte g_code[] = {WASM_STRUCT_GET(type_index, 1, WASM_STRUCT_NEW(type_index, WASM_I32V(42), WASM_I32V(64))), kExprEnd}; g->EmitCode(g_code, sizeof(g_code)); // Test struct.new, returning struct references to JS. WasmFunctionBuilder* h = builder->AddFunction(&sig_q_v); h->builder()->AddExport(CStrVector("h"), h); byte h_code[] = {WASM_STRUCT_NEW(type_index, WASM_I32V(42), WASM_I32V(64)), kExprEnd}; h->EmitCode(h_code, sizeof(h_code)); // Test struct.set, struct refs types in locals. WasmFunctionBuilder* j = builder->AddFunction(sigs.i_v()); uint32_t j_local_index = j->AddLocal(kOptRefType); uint32_t j_field_index = 0; j->builder()->AddExport(CStrVector("j"), j); byte j_code[] = { WASM_SET_LOCAL(j_local_index, WASM_STRUCT_NEW(type_index, WASM_I32V(42), WASM_I32V(64))), WASM_STRUCT_SET(type_index, j_field_index, WASM_GET_LOCAL(j_local_index), WASM_I32V(-99)), WASM_STRUCT_GET(type_index, j_field_index, WASM_GET_LOCAL(j_local_index)), kExprEnd}; j->EmitCode(j_code, sizeof(j_code)); // Test struct.set, ref.as_non_null, // struct refs types in globals and if-results. uint32_t k_global_index = builder->AddGlobal(kOptRefType, true); WasmFunctionBuilder* k = builder->AddFunction(sigs.i_v()); uint32_t k_field_index = 0; k->builder()->AddExport(CStrVector("k"), k); byte k_code[] = { WASM_SET_GLOBAL(k_global_index, WASM_STRUCT_NEW(type_index, WASM_I32V(55), WASM_I32V(66))), WASM_STRUCT_GET(type_index, k_field_index, WASM_REF_AS_NON_NULL(WASM_IF_ELSE_R( kOptRefType, WASM_I32V(1), WASM_GET_GLOBAL(k_global_index), WASM_REF_NULL))), kExprEnd}; k->EmitCode(k_code, sizeof(k_code)); // Test br_on_null 1. WasmFunctionBuilder* l = builder->AddFunction(sigs.i_v()); uint32_t l_local_index = l->AddLocal(kOptRefType); l->builder()->AddExport(CStrVector("l"), l); byte l_code[] = { WASM_BLOCK_I(WASM_I32V(42), // Branch will be taken. // 42 left on stack outside the block (not 52). WASM_BR_ON_NULL(0, WASM_GET_LOCAL(l_local_index)), WASM_I32V(52), WASM_BR(0)), kExprEnd}; l->EmitCode(l_code, sizeof(l_code)); // Test br_on_null 2. WasmFunctionBuilder* m = builder->AddFunction(sigs.i_v()); uint32_t m_field_index = 0; m->builder()->AddExport(CStrVector("m"), m); byte m_code[] = { WASM_BLOCK_I( WASM_I32V(42), WASM_STRUCT_GET( type_index, m_field_index, // Branch will not be taken. // 52 left on stack outside the block (not 42). WASM_BR_ON_NULL(0, WASM_STRUCT_NEW(type_index, WASM_I32V(52), WASM_I32V(62)))), WASM_BR(0)), kExprEnd}; m->EmitCode(m_code, sizeof(m_code)); // Test ref.eq WasmFunctionBuilder* n = builder->AddFunction(sigs.i_v()); uint32_t n_local_index = n->AddLocal(kOptRefType); n->builder()->AddExport(CStrVector("n"), n); byte n_code[] = { WASM_SET_LOCAL(n_local_index, WASM_STRUCT_NEW(type_index, WASM_I32V(55), WASM_I32V(66))), WASM_I32_ADD( WASM_I32_SHL( WASM_REF_EQ( // true WASM_GET_LOCAL(n_local_index), WASM_GET_LOCAL(n_local_index)), WASM_I32V(0)), WASM_I32_ADD( WASM_I32_SHL(WASM_REF_EQ( // false WASM_GET_LOCAL(n_local_index), WASM_STRUCT_NEW(type_index, WASM_I32V(55), WASM_I32V(66))), WASM_I32V(1)), WASM_I32_ADD( WASM_I32_SHL( // false WASM_REF_EQ(WASM_GET_LOCAL(n_local_index), WASM_REF_NULL), WASM_I32V(2)), WASM_I32_SHL(WASM_REF_EQ( // true WASM_REF_NULL, WASM_REF_NULL), WASM_I32V(3))))), kExprEnd}; n->EmitCode(n_code, sizeof(n_code)); // Result: 0b1001 /************************* End of test definitions *************************/ ZoneBuffer buffer(&zone); builder->WriteTo(&buffer); Isolate* isolate = CcTest::InitIsolateOnce(); HandleScope scope(isolate); testing::SetupIsolateForWasmModule(isolate); ErrorThrower thrower(isolate, "Test"); MaybeHandle<WasmInstanceObject> maybe_instance = testing::CompileAndInstantiateForTesting( isolate, &thrower, ModuleWireBytes(buffer.begin(), buffer.end())); if (thrower.error()) FATAL("%s", thrower.error_msg()); Handle<WasmInstanceObject> instance = maybe_instance.ToHandleChecked(); CHECK_EQ(42, testing::CallWasmFunctionForTesting(isolate, instance, &thrower, "f", 0, nullptr)); CHECK_EQ(64, testing::CallWasmFunctionForTesting(isolate, instance, &thrower, "g", 0, nullptr)); // TODO(7748): This uses the JavaScript interface to retrieve the plain // WasmStruct. Once the JS interaction story is settled, this may well // need to be changed. Handle<WasmExportedFunction> h_export = testing::GetExportedFunction(isolate, instance, "h").ToHandleChecked(); Handle<Object> undefined = isolate->factory()->undefined_value(); Handle<Object> ref_result = Execution::Call(isolate, h_export, undefined, 0, nullptr) .ToHandleChecked(); CHECK(ref_result->IsWasmStruct()); CHECK_EQ(-99, testing::CallWasmFunctionForTesting(isolate, instance, &thrower, "j", 0, nullptr)); CHECK_EQ(55, testing::CallWasmFunctionForTesting(isolate, instance, &thrower, "k", 0, nullptr)); CHECK_EQ(42, testing::CallWasmFunctionForTesting(isolate, instance, &thrower, "l", 0, nullptr)); CHECK_EQ(52, testing::CallWasmFunctionForTesting(isolate, instance, &thrower, "m", 0, nullptr)); CHECK_EQ(0b1001, testing::CallWasmFunctionForTesting( isolate, instance, &thrower, "n", 0, nullptr)); } WASM_EXEC_TEST(LetInstruction) { // TODO(7748): Implement support in other tiers. if (execution_tier == ExecutionTier::kLiftoff) return; if (execution_tier == ExecutionTier::kInterpreter) return; TestSignatures sigs; EXPERIMENTAL_FLAG_SCOPE(gc); EXPERIMENTAL_FLAG_SCOPE(typed_funcref); EXPERIMENTAL_FLAG_SCOPE(anyref); v8::internal::AccountingAllocator allocator; Zone zone(&allocator, ZONE_NAME); WasmModuleBuilder* builder = new (&zone) WasmModuleBuilder(&zone); StructType::Builder type_builder(&zone, 2); type_builder.AddField(kWasmI32, true); type_builder.AddField(kWasmI32, true); int32_t type_index = builder->AddStructType(type_builder.Build()); ValueType kRefTypes[] = {ValueType(ValueType::kRef, type_index)}; FunctionSig sig_q_v(1, 0, kRefTypes); WasmFunctionBuilder* let_test_1 = builder->AddFunction(sigs.i_v()); let_test_1->builder()->AddExport(CStrVector("let_test_1"), let_test_1); uint32_t let_local_index = 0; uint32_t let_field_index = 0; byte let_code[] = { WASM_LET_1_I(WASM_REF_TYPE(type_index), WASM_STRUCT_NEW(type_index, WASM_I32V(42), WASM_I32V(52)), WASM_STRUCT_GET(type_index, let_field_index, WASM_GET_LOCAL(let_local_index))), kExprEnd}; let_test_1->EmitCode(let_code, sizeof(let_code)); WasmFunctionBuilder* let_test_2 = builder->AddFunction(sigs.i_v()); let_test_2->builder()->AddExport(CStrVector("let_test_2"), let_test_2); uint32_t let_2_field_index = 0; byte let_code_2[] = { WASM_LET_2_I(kLocalI32, WASM_I32_ADD(WASM_I32V(42), WASM_I32V(-32)), WASM_REF_TYPE(type_index), WASM_STRUCT_NEW(type_index, WASM_I32V(42), WASM_I32V(52)), WASM_I32_MUL(WASM_STRUCT_GET(type_index, let_2_field_index, WASM_GET_LOCAL(1)), WASM_GET_LOCAL(0))), kExprEnd}; let_test_2->EmitCode(let_code_2, sizeof(let_code_2)); WasmFunctionBuilder* let_test_locals = builder->AddFunction(sigs.i_i()); let_test_locals->builder()->AddExport(CStrVector("let_test_locals"), let_test_locals); let_test_locals->AddLocal(kWasmI32); byte let_code_locals[] = { WASM_SET_LOCAL(1, WASM_I32V(100)), WASM_LET_2_I( kLocalI32, WASM_I32V(1), kLocalI32, WASM_I32V(10), WASM_I32_SUB(WASM_I32_ADD(WASM_GET_LOCAL(0), // 1st let-local WASM_GET_LOCAL(2)), // Parameter WASM_I32_ADD(WASM_GET_LOCAL(1), // 2nd let-local WASM_GET_LOCAL(3)))), // Function local kExprEnd}; // Result: (1 + 1000) - (10 + 100) = 891 let_test_locals->EmitCode(let_code_locals, sizeof(let_code_locals)); WasmFunctionBuilder* let_test_erase = builder->AddFunction(sigs.i_v()); let_test_erase->builder()->AddExport(CStrVector("let_test_erase"), let_test_erase); uint32_t let_erase_local_index = let_test_erase->AddLocal(kWasmI32); byte let_code_erase[] = {WASM_SET_LOCAL(let_erase_local_index, WASM_I32V(0)), WASM_LET_1_V(kLocalI32, WASM_I32V(1), WASM_NOP), WASM_GET_LOCAL(let_erase_local_index), kExprEnd}; // The result should be 0 and not 1, as local_get(0) refers to the original // local. let_test_erase->EmitCode(let_code_erase, sizeof(let_code_erase)); /************************* End of test definitions *************************/ ZoneBuffer buffer(&zone); builder->WriteTo(&buffer); Isolate* isolate = CcTest::InitIsolateOnce(); HandleScope scope(isolate); testing::SetupIsolateForWasmModule(isolate); ErrorThrower thrower(isolate, "Test"); MaybeHandle<WasmInstanceObject> maybe_instance = testing::CompileAndInstantiateForTesting( isolate, &thrower, ModuleWireBytes(buffer.begin(), buffer.end())); if (thrower.error()) FATAL("%s", thrower.error_msg()); Handle<WasmInstanceObject> instance = maybe_instance.ToHandleChecked(); CHECK_EQ(42, testing::CallWasmFunctionForTesting(isolate, instance, &thrower, "let_test_1", 0, nullptr)); CHECK_EQ(420, testing::CallWasmFunctionForTesting(isolate, instance, &thrower, "let_test_2", 0, nullptr)); Handle<Object> let_local_args[] = {handle(Smi::FromInt(1000), isolate)}; CHECK_EQ(891, testing::CallWasmFunctionForTesting(isolate, instance, &thrower, "let_test_locals", 1, let_local_args)); CHECK_EQ(0, testing::CallWasmFunctionForTesting( isolate, instance, &thrower, "let_test_erase", 0, nullptr)); } WASM_EXEC_TEST(BasicArray) { // TODO(7748): Implement support in other tiers. if (execution_tier == ExecutionTier::kLiftoff) return; if (execution_tier == ExecutionTier::kInterpreter) return; TestSignatures sigs; EXPERIMENTAL_FLAG_SCOPE(gc); EXPERIMENTAL_FLAG_SCOPE(anyref); v8::internal::AccountingAllocator allocator; Zone zone(&allocator, ZONE_NAME); WasmModuleBuilder* builder = new (&zone) WasmModuleBuilder(&zone); ArrayType type(wasm::kWasmI32, true); int32_t type_index = builder->AddArrayType(&type); ValueType kRefTypes[] = {ValueType(ValueType::kRef, type_index)}; FunctionSig sig_q_v(1, 0, kRefTypes); ValueType kOptRefType = ValueType(ValueType::kOptRef, type_index); WasmFunctionBuilder* f = builder->AddFunction(sigs.i_i()); uint32_t local_index = f->AddLocal(kOptRefType); f->builder()->AddExport(CStrVector("f"), f); // f: a = [12, 12, 12]; a[1] = 42; return a[arg0] byte f_code[] = { WASM_SET_LOCAL(local_index, WASM_ARRAY_NEW(type_index, WASM_I32V(12), WASM_I32V(3))), WASM_ARRAY_SET(type_index, WASM_GET_LOCAL(local_index), WASM_I32V(1), WASM_I32V(42)), WASM_ARRAY_GET(type_index, WASM_GET_LOCAL(local_index), WASM_GET_LOCAL(0)), kExprEnd}; f->EmitCode(f_code, sizeof(f_code)); // Reads and returns an array's length. WasmFunctionBuilder* g = builder->AddFunction(sigs.i_v()); f->builder()->AddExport(CStrVector("g"), g); byte g_code[] = { WASM_ARRAY_LEN(type_index, WASM_ARRAY_NEW(type_index, WASM_I32V(0), WASM_I32V(42))), kExprEnd}; g->EmitCode(g_code, sizeof(g_code)); WasmFunctionBuilder* h = builder->AddFunction(&sig_q_v); h->builder()->AddExport(CStrVector("h"), h); // Create an array of length 2, initialized to [42, 42]. byte h_code[] = {WASM_ARRAY_NEW(type_index, WASM_I32V(42), WASM_I32V(2)), kExprEnd}; h->EmitCode(h_code, sizeof(h_code)); ZoneBuffer buffer(&zone); builder->WriteTo(&buffer); Isolate* isolate = CcTest::InitIsolateOnce(); HandleScope scope(isolate); testing::SetupIsolateForWasmModule(isolate); ErrorThrower thrower(isolate, "Test"); Handle<WasmInstanceObject> instance = testing::CompileAndInstantiateForTesting( isolate, &thrower, ModuleWireBytes(buffer.begin(), buffer.end())) .ToHandleChecked(); Handle<Object> argv[] = {handle(Smi::FromInt(0), isolate)}; CHECK_EQ(12, testing::CallWasmFunctionForTesting(isolate, instance, &thrower, "f", 1, argv)); argv[0] = handle(Smi::FromInt(1), isolate); CHECK_EQ(42, testing::CallWasmFunctionForTesting(isolate, instance, &thrower, "f", 1, argv)); argv[0] = handle(Smi::FromInt(2), isolate); CHECK_EQ(12, testing::CallWasmFunctionForTesting(isolate, instance, &thrower, "f", 1, argv)); Handle<Object> undefined = isolate->factory()->undefined_value(); { Handle<WasmExportedFunction> f_export = testing::GetExportedFunction(isolate, instance, "f").ToHandleChecked(); TryCatch try_catch(reinterpret_cast<v8::Isolate*>(isolate)); argv[0] = handle(Smi::FromInt(3), isolate); MaybeHandle<Object> no_result = Execution::Call(isolate, f_export, undefined, 1, argv); CHECK(no_result.is_null()); CHECK(try_catch.HasCaught()); isolate->clear_pending_exception(); argv[0] = handle(Smi::FromInt(-1), isolate); no_result = Execution::Call(isolate, f_export, undefined, 1, argv); CHECK(no_result.is_null()); CHECK(try_catch.HasCaught()); isolate->clear_pending_exception(); } CHECK_EQ(42, testing::CallWasmFunctionForTesting(isolate, instance, &thrower, "g", 0, nullptr)); // TODO(7748): This uses the JavaScript interface to retrieve the plain // WasmArray. Once the JS interaction story is settled, this may well // need to be changed. Handle<WasmExportedFunction> h_export = testing::GetExportedFunction(isolate, instance, "h").ToHandleChecked(); Handle<Object> ref_result = Execution::Call(isolate, h_export, undefined, 0, nullptr) .ToHandleChecked(); CHECK(ref_result->IsWasmArray()); #if OBJECT_PRINT ref_result->Print(); #endif } } // namespace test_gc } // namespace wasm } // namespace internal } // namespace v8
43.672289
80
0.634407
[ "object", "vector" ]
05bf7efdc49ef73c425bc01bbceecce976308010
1,690
hpp
C++
boost/geometry/extensions/nsphere/index/detail/algorithms/comparable_distance_near.hpp
ballisticwhisper/boost
f72119ab640b564c4b983bd457457046b52af9ee
[ "BSL-1.0" ]
2
2015-01-02T14:24:56.000Z
2015-01-02T14:25:17.000Z
boost/geometry/extensions/nsphere/index/detail/algorithms/comparable_distance_near.hpp
ballisticwhisper/boost
f72119ab640b564c4b983bd457457046b52af9ee
[ "BSL-1.0" ]
2
2019-01-13T23:45:51.000Z
2019-02-03T08:13:26.000Z
boost/geometry/extensions/nsphere/index/detail/algorithms/comparable_distance_near.hpp
ballisticwhisper/boost
f72119ab640b564c4b983bd457457046b52af9ee
[ "BSL-1.0" ]
1
2016-05-29T13:41:15.000Z
2016-05-29T13:41:15.000Z
// Boost.Geometry Index // // squared distance between point and nearest point of the box or point // // Copyright (c) 2011-2013 Adam Wulkiewicz, Lodz, Poland. // // Use, modification and distribution is subject to 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 BOOST_GEOMETRY_EXTENSIONS_NSPHERE_INDEX_DETAIL_ALGORITHMS_COMPARABLE_DISTANCE_NEAR_HPP #define BOOST_GEOMETRY_EXTENSIONS_NSPHERE_INDEX_DETAIL_ALGORITHMS_COMPARABLE_DISTANCE_NEAR_HPP #include <boost/geometry/index/detail/algorithms/comparable_distance_near.hpp> #include <boost/geometry/extensions/nsphere/views/center_view.hpp> namespace boost { namespace geometry { namespace index { namespace detail { template < typename Point, typename Indexable, size_t N> struct sum_for_indexable<Point, Indexable, nsphere_tag, comparable_distance_near_tag, N> { typedef typename default_distance_result<Point, center_view<const Indexable> >::type result_type; inline static result_type apply(Point const& pt, Indexable const& i) { result_type center_dist = ::sqrt( comparable_distance(pt, center_view<const Indexable>(i)) ); result_type dist = get_radius<0>(i) < center_dist ? center_dist - get_radius<0>(i) : 0; return dist; // return dist * dist to be conformant with comparable_distance? // CONSIDER returning negative value related to the distance or normalized distance to the center if dist < radius } }; }}}} // namespace boost::geometry::index::detail #endif // BOOST_GEOMETRY_EXTENSIONS_NSPHERE_INDEX_DETAIL_ALGORITHMS_COMPARABLE_DISTANCE_NEAR_HPP
40.238095
122
0.769822
[ "geometry" ]
05c82102b27e6feccf92d619d202a06bce660b57
3,081
cpp
C++
OpenglSphere/src/Sphere.cpp
linux-admirer/OpenglSphere
ed6937ed3f72bfbf54227e0fa9f2abde3394e156
[ "MIT" ]
1
2019-08-08T16:58:46.000Z
2019-08-08T16:58:46.000Z
OpenglSphere/src/Sphere.cpp
linux-admirer/OpenglSphere
ed6937ed3f72bfbf54227e0fa9f2abde3394e156
[ "MIT" ]
null
null
null
OpenglSphere/src/Sphere.cpp
linux-admirer/OpenglSphere
ed6937ed3f72bfbf54227e0fa9f2abde3394e156
[ "MIT" ]
null
null
null
#include "Sphere.h" #include <algorithm> #define _USE_MATH_DEFINES #include <cmath> #include <math.h> static const double pi180 = M_PI / 180; double degreeToRadian(float degrees) { return (degrees * pi180); } void negateY(Triangle& triangle) { auto& vertices = triangle.vertices; vertices[0].y = -vertices[0].y; vertices[1].y = -vertices[1].y; vertices[2].y = -vertices[2].y; } void negateX(Triangle& triangle) { auto& vertices = triangle.vertices; vertices[0].x = -vertices[0].x; vertices[1].x = -vertices[1].x; vertices[2].x = -vertices[2].x; } void swapXY(Triangle& triangle) { auto& vertices = triangle.vertices; std::swap(vertices[0].x, vertices[0].y); std::swap(vertices[0].x, vertices[0].y); std::swap(vertices[0].x, vertices[0].y); } std::vector<Triangle> Sphere::getCoordinates(float radius, float delta_d) { std::vector<Triangle> triangles; triangles.reserve(static_cast<size_t>(180 * 360 * 2/ (delta_d * delta_d))); //x = r cos(azimuth_d) sin(polar_d) //y = r sin(azimuth_d) sin(polar_d) //z = r cos(polar_d) float polar_d = 0.; double polarCurRad = degreeToRadian(polar_d); float polarCur = radius * std::sin(polarCurRad); float zcoordCur = radius * std::cos(polarCurRad); for (; polar_d < 180; polar_d += delta_d) { double polarNextRad = degreeToRadian(polar_d + delta_d); float polarNext = radius * std::sin(polarNextRad); float zcoordNext = radius * std::cos(polarNextRad); float azimuth_d = 0.; double azimuthCurRad = degreeToRadian(azimuth_d); Point pointCur; pointCur.x = polarCur * std::cos(azimuthCurRad); pointCur.y = polarCur * std::sin(azimuthCurRad); pointCur.z = zcoordCur; Point pointTop; pointTop.x = polarNext * std::cos(azimuthCurRad); pointTop.y = polarNext * std::sin(azimuthCurRad); pointTop.z = zcoordNext; Triangle triangle; for (; azimuth_d < 90; azimuth_d += delta_d) { double azimuthNextRad = degreeToRadian(azimuth_d + delta_d); Point pointNext; pointNext.x = polarCur * std::cos(azimuthNextRad); pointNext.y = polarCur * std::sin(azimuthNextRad); pointNext.z = zcoordCur; triangle.vertices[0] = pointCur; triangle.vertices[1] = pointNext; triangle.vertices[1] = pointTop; triangles.push_back(triangle); Point pointTopNext; pointTopNext.x = polarNext * std::cos(azimuthNextRad); pointTopNext.y = polarNext * std::sin(azimuthNextRad); pointTopNext.z = zcoordNext; triangle.vertices[0] = pointTopNext; triangles.push_back(triangle); pointCur = pointNext; pointTop = pointTopNext; azimuthCurRad = azimuthNextRad; } polarCur = polarNext; zcoordCur = zcoordNext; } auto size = triangles.size(); Triangle triangle; for (size_t i = 0; i < size; ++i) { // 180 + theta triangle = triangles[i]; negateX(triangle); negateY(triangle); triangles.push_back(triangle); // 90 + theta triangle = triangles[i]; swapXY(triangle); negateY(triangle); triangles.push_back(triangle); // 270 + theta negateX(triangle); negateY(triangle); triangles.push_back(triangle); } return triangles; }
24.452381
76
0.695229
[ "vector" ]
05cbf887d59b208376db90dfc74507429c8005ec
6,987
cc
C++
src/main.cc
rlan/cpp_sandbox
5889513e2f5874a01fd610c259135d627847e8b9
[ "MIT" ]
null
null
null
src/main.cc
rlan/cpp_sandbox
5889513e2f5874a01fd610c259135d627847e8b9
[ "MIT" ]
null
null
null
src/main.cc
rlan/cpp_sandbox
5889513e2f5874a01fd610c259135d627847e8b9
[ "MIT" ]
null
null
null
// Options class // https://gist.github.com/ksimek/4a2814ba7d74f778bbee // boost::log // boost::log tutorial #include <boost/program_options.hpp> #include <boost/log/core.hpp> #include <boost/log/trivial.hpp> #include <boost/log/expressions.hpp> #include <iostream> #include <sstream> #include <fstream> #include <iterator> #include <algorithm> #include <string> #include <cstdint> namespace logging = boost::log; namespace po = boost::program_options; class Options { public: bool parse(int argc, char** argv) { std::vector<std::string> config_fnames; po::options_description desc("General Options"); desc.add_options() ("help", "Display help message") ("config", po::value(&config_fnames), "Config file where options may be specified (can be specified more than once)") ("threshold,t", po::value<double>(&threshold)->default_value(0.25), "Threshold value") ("optional,o", po::bool_switch(&optional_flag), "Optional flag") ("log-level,l", po::value(&log_level), "trace, debug, info, warning, error (default) or fatel") ; po::options_description hidden; hidden.add_options() ("fname", po::value<std::string>(&fname)->required(), "filename") ; po::options_description all_options; all_options.add(desc); all_options.add(hidden); po::positional_options_description p; p.add("fname", -1); po::variables_map vm; po::store(po::command_line_parser(argc, argv). options(all_options). positional(p). run(), vm); if(vm.count("help")) { std::cout << make_usage_string_(basename_(argv[0]), desc, p) << '\n'; return false; } if(vm.count("config") > 0) { config_fnames = vm["config"].as<std::vector<std::string> >(); for(size_t i = 0; i < config_fnames.size(); ++i) { std::ifstream ifs(config_fnames[i].c_str()); if(ifs.fail()) { std::cerr << "Error opening config file: " << config_fnames[i] << std::endl; return false; } po::store(po::parse_config_file(ifs, all_options), vm); } } if(vm.count("log-level")) set_log_level(vm["log-level"].as<std::string>()); else set_log_level("error"); po::notify(vm); return true; } private: // https://stackoverflow.com/a/19123540/1704566 static inline constexpr unsigned const_hash(char const *input, unsigned hash = 5381) { return *input ? const_hash(input + 1, hash * 33 + static_cast<unsigned>(*input)): hash; } void set_log_level(const std::string &level) { switch (const_hash(level.c_str())) { case const_hash("trace"): logging::core::get()->set_filter(logging::trivial::severity >= logging::trivial::trace); break; case const_hash("debug"): logging::core::get()->set_filter(logging::trivial::severity >= logging::trivial::debug); break; case const_hash("info"): logging::core::get()->set_filter(logging::trivial::severity >= logging::trivial::info); break; case const_hash("warning"): logging::core::get()->set_filter(logging::trivial::severity >= logging::trivial::warning); break; case const_hash("error"): logging::core::get()->set_filter(logging::trivial::severity >= logging::trivial::error); break; case const_hash("fatal"): logging::core::get()->set_filter(logging::trivial::severity >= logging::trivial::fatal); break; default: logging::core::get()->set_filter(logging::trivial::severity >= logging::trivial::error); break; } } std::string basename_(const std::string& p) { #ifdef HAVE_BOOST_FILESYSTEM return boost::filesystem::path(p).stem().string(); #else size_t start = p.find_last_of("/"); if(start == std::string::npos) start = 0; else ++start; return p.substr(start); #endif } // Boost doesn't offer any obvious way to construct a usage string // from an infinite list of positional parameters. This hack // should work in most reasonable cases. std::vector<std::string> get_unlimited_positional_args_(const po::positional_options_description& p) { assert(p.max_total_count() == std::numeric_limits<unsigned>::max()); std::vector<std::string> parts; // reasonable upper limit for number of positional options: const int MAX = 1000; std::string last = p.name_for_position(MAX); for(size_t i = 0; true; ++i) { std::string cur = p.name_for_position(i); if(cur == last) { parts.push_back(cur); parts.push_back('[' + cur + ']'); parts.push_back("..."); return parts; } parts.push_back(cur); } return parts; // never get here } std::string make_usage_string_(const std::string& program_name, const po::options_description& desc, po::positional_options_description& p) { std::vector<std::string> parts; parts.push_back("Usage: "); parts.push_back(program_name); size_t N = p.max_total_count(); if(N == std::numeric_limits<unsigned>::max()) { std::vector<std::string> args = get_unlimited_positional_args_(p); parts.insert(parts.end(), args.begin(), args.end()); } else { for(size_t i = 0; i < N; ++i) { parts.push_back(p.name_for_position(i)); } } if(desc.options().size() > 0) { parts.push_back("[options]"); } std::ostringstream oss; std::copy( parts.begin(), parts.end(), std::ostream_iterator<std::string>(oss, " ")); oss << '\n' << desc; return oss.str(); } public: std::string fname; double threshold; bool optional_flag; std::string log_level; }; Options options; int main(int argc, char** argv) { if(!options.parse(argc, argv)) return 1; std::cout << options.fname << std::endl; BOOST_LOG_TRIVIAL(trace) << "A trace severity message"; BOOST_LOG_TRIVIAL(debug) << "A debug severity message"; BOOST_LOG_TRIVIAL(info) << "An informational severity message"; BOOST_LOG_TRIVIAL(warning) << "A warning severity message"; BOOST_LOG_TRIVIAL(error) << "An error severity message"; BOOST_LOG_TRIVIAL(fatal) << "A fatal severity message"; return 0; }
32.649533
143
0.566051
[ "vector" ]
fe465786707123d3e74cf5431d3d156654f0cfb1
1,369
cc
C++
cv_utils/src/DisplayImages.cc
MRSD2018/reefbot-1
a595ca718d0cda277726894a3105815cef000475
[ "MIT" ]
null
null
null
cv_utils/src/DisplayImages.cc
MRSD2018/reefbot-1
a595ca718d0cda277726894a3105815cef000475
[ "MIT" ]
null
null
null
cv_utils/src/DisplayImages.cc
MRSD2018/reefbot-1
a595ca718d0cda277726894a3105815cef000475
[ "MIT" ]
null
null
null
#include "cv_utils/DisplayImages.h" #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> using namespace cv; namespace cv_utils { void DisplayNormalizedImage(const cv::Mat& image, const char* windowName) { Mat outImage = image; if (image.channels() == 1) { normalize(image, outImage, 0, 255, NORM_MINMAX, CV_MAKETYPE(CV_8U, image.channels())); } cvNamedWindow(windowName, CV_WINDOW_AUTOSIZE); cvShowImage(windowName, &IplImage(outImage)); } void DisplayLabImage(const cv::Mat& image, const char* windowName) { Mat outImage; Mat outImage32; image.convertTo(outImage32, CV_32FC3); cvtColor(outImage32, outImage, CV_Lab2BGR); cvNamedWindow(windowName, CV_WINDOW_AUTOSIZE); cvShowImage(windowName, &IplImage(outImage)); } void DisplayImageWithBoxes(const cv::Mat& image, const std::vector<cv::Rect>& boxes, const char* windowName) { Mat outImage = image.clone(); for (vector<Rect>::const_iterator i = boxes.begin(); i != boxes.end(); ++i) { rectangle(outImage, *i, Scalar(255, 0, 0)); } cvNamedWindow(windowName, CV_WINDOW_AUTOSIZE); cvShowImage(windowName, &IplImage(outImage)); } void ShowWindowsUntilKeyPress() { int key = -1; while (key < 0) { key = cvWaitKey(100); } } } // namespace
24.446429
75
0.665449
[ "vector" ]
fe4c333c832944501a2abfad0cfa9356b655acff
3,159
cpp
C++
Semester_2/Assignment11 Object-oriented design ATM/BankDatabase.cpp
ryankert01/Programming-1--1-hw7
c0b7fcf35000406d0bb3ae6cc862e71ea986d796
[ "Apache-2.0" ]
null
null
null
Semester_2/Assignment11 Object-oriented design ATM/BankDatabase.cpp
ryankert01/Programming-1--1-hw7
c0b7fcf35000406d0bb3ae6cc862e71ea986d796
[ "Apache-2.0" ]
null
null
null
Semester_2/Assignment11 Object-oriented design ATM/BankDatabase.cpp
ryankert01/Programming-1--1-hw7
c0b7fcf35000406d0bb3ae6cc862e71ea986d796
[ "Apache-2.0" ]
null
null
null
// BankDatabase.cpp // Member-function definitions for class BankDatabase. #include <iostream> #include "BankDatabase.h" // BankDatabase class definition // BankDatabase default constructor initializes accounts // read account informations for all accounts from the binary file "Accounts.dat" BankDatabase::BankDatabase() { ifstream inFile("Accounts.dat", ios::binary); if(!inFile) { cout << "File could not be opened" << endl; system("pause"); exit(1); } int a = 0, b = 0; double c = 0, d = 0 ; while (!inFile.eof()) { Account temp(a, b, c, d); inFile.read(reinterpret_cast<char*>(&temp), sizeof(temp)); accounts.push_back(temp); } accounts.pop_back(); cout << accounts.size(); inFile.close(); } // write account informations for all accounts to the binary file "Accounts.dat" BankDatabase::~BankDatabase() { ofstream outFile("Accounts.dat", ios::binary); if(!outFile) { cout << "File could not be opened" << endl; system("pause"); exit(1); } for(Account i : accounts) outFile.write(reinterpret_cast<const char*>(&i), sizeof(i)); outFile.close(); } // retrieve Account object containing specified account number Account* BankDatabase::getAccount( int accountNumber ) { for (Account& i : accounts) { if (accountNumber == i.getAccountNumber()) return &i; } return nullptr; // if no matching account was found, return nullptr } // determine whether user-specified account number and PIN match // those of an account in the database bool BankDatabase::authenticateUser( int userAccountNumber, int userPIN ) { // attempt to retrieve the account with the account number Account * const userAccountPtr = getAccount( userAccountNumber ); // if account exists, return result of Account function validatePIN if ( userAccountPtr != nullptr ) return userAccountPtr->validatePIN( userPIN ); else return false; // account number not found, so return false } // return available balance of Account with specified account number double BankDatabase::getAvailableBalance( int userAccountNumber ) { Account * const userAccountPtr = getAccount( userAccountNumber ); return userAccountPtr->getAvailableBalance(); } // return total balance of Account with specified account number double BankDatabase::getTotalBalance( int userAccountNumber ) { Account * const userAccountPtr = getAccount( userAccountNumber ); return userAccountPtr->getTotalBalance(); } // credit an amount to Account with specified account number void BankDatabase::credit( int userAccountNumber, double amount ) { Account * const userAccountPtr = getAccount( userAccountNumber ); userAccountPtr->credit( amount ); } // debit an amount from Account with specified account number void BankDatabase::debit( int userAccountNumber, double amount ) { Account * const userAccountPtr = getAccount( userAccountNumber ); userAccountPtr->debit( amount ); }
29.25
82
0.675214
[ "object" ]
fe5153f0679a8326fb73de010078df7e0c6497b8
1,557
cc
C++
libs/core/src/core/utf8.test.cc
madeso/euphoria
59b72d148a90ae7a19e197e91216d4d42f194fd5
[ "MIT" ]
24
2015-07-27T14:32:18.000Z
2021-11-15T12:11:31.000Z
libs/core/src/core/utf8.test.cc
madeso/euphoria
59b72d148a90ae7a19e197e91216d4d42f194fd5
[ "MIT" ]
27
2021-07-09T21:18:40.000Z
2021-07-14T13:39:56.000Z
libs/core/src/core/utf8.test.cc
madeso/euphoria
59b72d148a90ae7a19e197e91216d4d42f194fd5
[ "MIT" ]
null
null
null
#include "core/utf8.h" #include "tests/stringeq.h" #include "catch.hpp" #include <vector> #include <string> using namespace euphoria::core; namespace { using T = std::vector<unsigned int>; std::pair<bool, T> parse_to_codepoints(const std::string& str) { auto ret = T{}; const auto r = utf8_to_codepoints(str, [&](unsigned int cp) { ret.push_back(cp); }); return std::make_pair(r, ret); } } TEST_CASE("utf8_tests") { SECTION("empty") { const auto [ok, code_points] = parse_to_codepoints(u8""); CHECK(ok); CHECK_THAT(code_points, Catch::Equals(T{})); } SECTION("Dollar sign") { const auto [ok, code_points] = parse_to_codepoints(u8"$"); CHECK(ok); CHECK_THAT(code_points, Catch::Equals(T{044})); } SECTION("Cent sign") { const auto [ok, code_points] = parse_to_codepoints(u8"¢"); CHECK(ok); CHECK_THAT(code_points, Catch::Equals(T{0242})); } SECTION("Devanagari character") { const auto [ok, code_points] = parse_to_codepoints(u8"ह"); CHECK(ok); CHECK_THAT(code_points, Catch::Equals(T{004471})); } SECTION("Euro sign") { const auto [ok, code_points] = parse_to_codepoints(u8"€"); CHECK(ok); CHECK_THAT(code_points, Catch::Equals(T{020254})); } SECTION("Hwair") { const auto [ok, code_points] = parse_to_codepoints(u8"𐍈"); CHECK(ok); CHECK_THAT(code_points, Catch::Equals(T{0201510})); } }
23.590909
92
0.588953
[ "vector" ]
fe58d141314d9f0eb6e0db005681e29e480b4bf8
676
cpp
C++
Blocks/expanding_visual.cpp
dtulga/arcBlocks
db54cfc09e51a7330135fa139f7436e81fd9de9f
[ "MIT" ]
null
null
null
Blocks/expanding_visual.cpp
dtulga/arcBlocks
db54cfc09e51a7330135fa139f7436e81fd9de9f
[ "MIT" ]
null
null
null
Blocks/expanding_visual.cpp
dtulga/arcBlocks
db54cfc09e51a7330135fa139f7436e81fd9de9f
[ "MIT" ]
null
null
null
#include "expanding_visual.h" namespace Blocks { void ExpandingVisual::draw() { bool drawn = false; if (!props_.background_color.is_transparent()) { render.DrawRect(width_, height_, props_.background_color); drawn = true; } if (props_.sprite != nullptr) { if (props_.sprite_tile_mode) { render.DrawSpriteTiled(*(props_.sprite), width_, height_); } else { render.DrawSpriteStretch(*(props_.sprite), width_, height_); } } else if (props_.ondraw_func != nullptr) { props_.ondraw_func(width_, height_); } else if (!drawn) { log::Error("ExpandingVisual", "Attempted to draw a null expanding visual"); } } } // namespace Blocks
27.04
78
0.678994
[ "render" ]
fe5e3f7c2a7b61bbbe455b6de13f514e04bf778b
8,785
cpp
C++
macOSCoder/KnapSack.cpp
lawarner/macOSCoder
096c49e5b6bc0ea2ffd7f875fa3f390306133669
[ "Apache-2.0" ]
null
null
null
macOSCoder/KnapSack.cpp
lawarner/macOSCoder
096c49e5b6bc0ea2ffd7f875fa3f390306133669
[ "Apache-2.0" ]
null
null
null
macOSCoder/KnapSack.cpp
lawarner/macOSCoder
096c49e5b6bc0ea2ffd7f875fa3f390306133669
[ "Apache-2.0" ]
null
null
null
// // KnapSack.cpp // macOSCoder // // Copyright © 2016 Andy Warner. // #include "KnapSack.hpp" #include <iostream> using namespace std; enum AlgoType { AT_RECURSE, AT_PERMUTE_UNIQUE, AT_PERMUTE_DUPLICATE }; #if 0 //////////////////////////// QuickPerm non-recursive //////////////////////////// #define N 4 // number of elements to permute. N > 2 void display(unsigned int *a, unsigned int j, unsigned int i) { for(unsigned int x = 0; x < N; x++) { cout << a[x] << " "; } cout << " swapped(" << j << ", " << i << ")" << endl; } void QuickPerm(void) { unsigned int a[N], p[N+1]; unsigned int i, j, tmp; // Upper Index i; Lower Index j for (i = 0; i < N; i++) // initialize arrays { a[i] = i + 1; p[i] = i; } p[N] = N; // p[N] > 0 controls iteration and the index boundary for i display(a, 0, 0); // display initial array a[] i = 1; // setup first swap points to be 1 and 0 respectively (i & j) while (i < N) { p[i]--; // decrease index "weight" for i by one j = i % 2 * p[i]; // IF i is odd then j = p[i] otherwise j = 0 tmp = a[j]; // swap(a[j], a[i]) a[j] = a[i]; a[i] = tmp; display(a, j, i); // display target array a[] i = 1; // reset index i to 1 (assumed) while (!p[i]) { p[i] = i; // reset p[i] zero value i++; // set new index value for i (increase by one) } } } #endif /* * Knapsack problem: maximize the value of boxes in knacksack given a maximum weight constraint. * Determine solution when only 1 of each color box can be used. * Then determine solution when multiple of each color box can be used. const char* boxColors[] = { "orange", "grey", "blue", "yellow", "green" }; */ int netWorth(const vector<int>& knapSack, const vector<Box>& boxes) { int worth = 0; for (int idx = 0; idx < knapSack.size(); ++idx) { int xx = knapSack[idx]; worth += boxes[xx].value; } return worth; } int netWeight(const vector<int>& knapSack, const vector<Box>& boxes) { int weight = 0; for (int idx = 0; idx < knapSack.size(); ++idx) { int xx = knapSack[idx]; weight += boxes[xx].weight; } return weight; } void swapItems(int* i1, int* i2) { int tmp = *i1; *i1 = *i2; *i2 = tmp; } enum Method { METHOD_EXAMPLE, METHOD_RECURSIVE_FILL, METHOD_PERMUTE_ONE_EACH, METHOD_PERMUTE_DUPS }; static const char* methods[] = { "KnapSack-example.txt", "Use recursive fill", "Use permute, one each", "Use permute, duplicates allowed" }; KnapSack::KnapSack() : CodeJamPerformer("KnapSack") , algorithm_(0) { methods_.push_back(methods[METHOD_EXAMPLE]); methods_.push_back(methods[METHOD_RECURSIVE_FILL]); methods_.push_back(methods[METHOD_PERMUTE_ONE_EACH]); methods_.push_back(methods[METHOD_PERMUTE_DUPS]); } KnapSack::~KnapSack() { } void KnapSack::printKnapsack(bool withValues) { log_ << "Knapsack: "; if (contents_.empty()) { log_ << "(empty)"; } else { for (int idx = 0; idx < contents_.size(); ++idx) { int kx = contents_[idx]; Box& box = boxes_[kx]; log_ << " " << kx; if (withValues) { log_ << "(" << box.weight << "," << box.value << ")"; } } } log_ << endl; //log_ << "\nNet worth = " << netWorth(contents_, boxes_) << endl; } void KnapSack::printSolution(int solution, int dups) { log_ << "Knapsack with " << dups << " dups: "; for (int idx = 0; idx < dups * boxes_.size(); ++idx) { if (solution & (1 << idx)) { log_ << " " << idx / dups; } } log_ << endl; } bool KnapSack::fillKnapSack(int maxWeight) { bool retval = false; size_t savedSize = contents_.size(); for (int idx = 0; idx < boxes_.size(); ++idx) { int remainder = maxWeight - boxes_[idx].weight; if (remainder < 0) { retval = true; } else { contents_.push_back(idx); if (remainder > 0) retval = fillKnapSack(remainder); int worth = netWorth(contents_, boxes_); if (worth > maxValue_) { maxValue_ = worth; saveContents_ = contents_; } } contents_.resize(savedSize); } return retval; } void KnapSack::permuteOneEach(int dups) { int dupBoxesCount = dups * boxes_.size(); int solution = 0; int boxBitMax = 1 << dupBoxesCount; maxValue_ = 0; for (int permBits = 1; permBits < boxBitMax; ++permBits) { int currValue = 0; int currWeight = 0; for (int idx = 0; idx < dupBoxesCount; ++idx) { if (permBits & (1 << idx)) { currWeight += boxes_[idx / dups].weight; if (currWeight > maxWeight_) { break; // short cirtcuit if overweight } currValue += boxes_[idx / dups].value; } } if (currWeight <= maxWeight_ && currValue > maxValue_) { maxValue_ = currValue; solution = permBits; //cout << "New Maximum = " << dec << maxValue_ << ", bits 0x" << hex << permBits << endl; } } printSolution(solution, dups); log_ << "Net worth: " << maxValue_ << endl; } // Naive non-recursive permutation: // 1 item: 0, 1, 2, 3, 4 // 2 items: 00, 01, ..., 04, 11, ..., 14, ..., 44 // 3 items: 000, 001 // Solution (from 0): 3 X 1, 3 X 3 void KnapSack::permuteItems(int maxItems) { size_t maxIdx = boxes_.size() - 1; size_t currItem = 0; do { // printKnapsack(true); if (netWeight(contents_, boxes_) <= maxWeight_) { int worth = netWorth(contents_, boxes_); if (worth > maxValue_) { maxValue_ = worth; saveContents_ = contents_; log_ << "Net worth now: " << maxValue_ << endl; } } while (contents_[currItem] == maxIdx) { contents_[currItem++] = 0; } if (currItem == maxItems) break; ++contents_[currItem]; currItem = 0; } while (currItem < maxItems); } int KnapSack::perform(const std::string &method, const StringList &arguments) { if (method == methods[METHOD_RECURSIVE_FILL]) { algorithm_ = AT_RECURSE; } else if (method == methods[METHOD_PERMUTE_ONE_EACH]) { algorithm_ = AT_PERMUTE_UNIQUE; } else if (method == methods[METHOD_PERMUTE_DUPS]) { algorithm_ = AT_PERMUTE_DUPLICATE; } else { return CodeJamPerformer::perform(method, arguments); } log_.clear(); log_.str(""); log_ << "Algorithm set to: " << method << endl; return 0; } int KnapSack::cjPerform(const std::string &method, const std::vector<IntList> &lines) { switch (algorithm_) { case AT_RECURSE: fillKnapSack(maxWeight_); contents_ = saveContents_; printKnapsack(true); break; case AT_PERMUTE_UNIQUE: for (int idx = 1; idx < 6; ++idx) { log_ << "Permute allowing " << idx << " duplicates" << endl; permuteOneEach(idx); } break; case AT_PERMUTE_DUPLICATE: for (int idx = 1; idx < 8; ++idx) { log_ << "Permute and pick " << idx << " items" << endl; contents_.clear(); while (contents_.size() < idx) contents_.push_back(0); permuteItems(idx); } contents_ = saveContents_; printKnapsack(true); break; default: break; } log_ << "Boxes: "; for (int idx = 0; idx < boxes_.size(); ++idx) { log_ << " " << idx << "(" << boxes_[idx].weight << "," << boxes_[idx].value << ")"; } log_ << endl << "Max Weight: " << maxWeight_ << " Max Value: " << maxValue_ << endl; return 0; } void KnapSack::cjSetup(std::ifstream& ins, std::vector<IntList>& lines) { boxes_.clear(); contents_.clear(); maxValue_ = 0; // first line: num_boxes max_weight // second line: weight1 value1 ... int numBoxes; ins >> numBoxes; ins >> maxWeight_; for (int idx = 0; idx < numBoxes; ++idx) { int w, v; ins >> w >> v; boxes_.push_back(Box(w,v)); } }
25.463768
101
0.512578
[ "vector" ]
fe6afde790bdd3a52e7054e213d956e87f59b54c
3,012
cpp
C++
cpp/example_code/dynamodb/update_table.cpp
iconara/aws-doc-sdk-examples
52706b31b4fce8fb89468e56743edf5369e69628
[ "Apache-2.0" ]
1
2022-02-02T03:49:17.000Z
2022-02-02T03:49:17.000Z
cpp/example_code/dynamodb/update_table.cpp
iconara/aws-doc-sdk-examples
52706b31b4fce8fb89468e56743edf5369e69628
[ "Apache-2.0" ]
1
2021-04-09T21:17:09.000Z
2021-04-09T21:17:09.000Z
cpp/example_code/dynamodb/update_table.cpp
iconara/aws-doc-sdk-examples
52706b31b4fce8fb89468e56743edf5369e69628
[ "Apache-2.0" ]
27
2020-04-16T22:52:53.000Z
2021-09-30T22:55:58.000Z
//snippet-sourcedescription:[update_table.cpp demonstrates how to update information about an Amazon DynamoDB table.] //snippet-keyword:[AWS SDK for C++] //snippet-keyword:[Code Sample] //snippet-service:[Amazon DynamoDB] //snippet-sourcetype:[full-example] //snippet-sourcedate:[11/30/2021] //snippet-sourceauthor:[scmacdon - aws] /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ //snippet-start:[dynamodb.cpp.update_table.inc] #include <aws/core/Aws.h> #include <aws/core/utils/Outcome.h> #include <aws/dynamodb/DynamoDBClient.h> #include <aws/dynamodb/model/ProvisionedThroughput.h> #include <aws/dynamodb/model/UpdateTableRequest.h> #include <iostream> //snippet-end:[dynamodb.cpp.update_table.inc] /** Update a DynamoDB table. Takes the name of the table to update, the read capacity and the write capacity to use. To run this C++ code example, ensure that you have setup your development environment, including your credentials. For information, see this documentation topic: https://docs.aws.amazon.com/sdk-for-cpp/v1/developer-guide/getting-started.html */ int main(int argc, char** argv) { const std::string USAGE = \ "Usage:\n" " update_table <table> <read> <write>\n\n" "Where:\n" " table - the table to put the item in.\n" " read - the new read capacity of the table.\n" " write - the new write capacity of the table.\n\n" "Example:\n" " update_table HelloTable 16 10\n"; if (argc < 3) { std::cout << USAGE; return 1; } Aws::SDKOptions options; Aws::InitAPI(options); { const Aws::String table(argv[1]); const long long rc = Aws::Utils::StringUtils::ConvertToInt64(argv[2]); const long long wc = Aws::Utils::StringUtils::ConvertToInt64(argv[3]); // snippet-start:[dynamodb.cpp.update_table.code] Aws::Client::ClientConfiguration clientConfig; Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfig); std::cout << "Updating " << table << " with new provisioned throughput values" << std::endl; std::cout << "Read capacity : " << rc << std::endl; std::cout << "Write capacity: " << wc << std::endl; Aws::DynamoDB::Model::UpdateTableRequest utr; Aws::DynamoDB::Model::ProvisionedThroughput pt; pt.WithReadCapacityUnits(rc).WithWriteCapacityUnits(wc); utr.WithProvisionedThroughput(pt).WithTableName(table); const Aws::DynamoDB::Model::UpdateTableOutcome& result = dynamoClient.UpdateTable(utr); if (!result.IsSuccess()) { std::cout << result.GetError().GetMessage() << std::endl; return 1; } std::cout << "Done!" << std::endl; // snippet-end:[dynamodb.cpp.update_table.code] } Aws::ShutdownAPI(options); return 0; }
35.857143
118
0.63745
[ "model" ]
fe6cb6cb8b55dbc66a7dc2e838a7afe2a9766f3d
7,457
cpp
C++
lib/Basics/AttributeNameParser.cpp
rajeev02101987/arangodb
817e6c04cb82777d266f3b444494140676da98e2
[ "Apache-2.0" ]
1
2020-07-30T23:33:02.000Z
2020-07-30T23:33:02.000Z
lib/Basics/AttributeNameParser.cpp
rajeev02101987/arangodb
817e6c04cb82777d266f3b444494140676da98e2
[ "Apache-2.0" ]
109
2022-01-06T07:05:24.000Z
2022-03-21T01:39:35.000Z
lib/Basics/AttributeNameParser.cpp
rajeev02101987/arangodb
817e6c04cb82777d266f3b444494140676da98e2
[ "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Michael Hackstein //////////////////////////////////////////////////////////////////////////////// #include <stddef.h> #include <algorithm> #include <memory> #include <ostream> #include "AttributeNameParser.h" #include "Basics/Exceptions.h" #include "Basics/debugging.h" #include "Basics/fasthash.h" #include "Basics/voc-errors.h" #include <velocypack/StringRef.h> using AttributeName = arangodb::basics::AttributeName; arangodb::basics::AttributeName::AttributeName(arangodb::velocypack::StringRef const& name) : AttributeName(name, false) {} arangodb::basics::AttributeName::AttributeName(arangodb::velocypack::StringRef const& name, bool expand) : name(name.toString()), shouldExpand(expand) {} uint64_t arangodb::basics::AttributeName::hash(uint64_t seed) const { return fasthash64(name.data(), name.size(), seed) ^ (shouldExpand ? 0xec59a4d : 0x4040ec59a4d40); } //////////////////////////////////////////////////////////////////////////////// /// @brief compare two attribute name vectors //////////////////////////////////////////////////////////////////////////////// bool arangodb::basics::AttributeName::isIdentical(std::vector<AttributeName> const& lhs, std::vector<AttributeName> const& rhs, bool ignoreExpansionInLast) { if (lhs.size() != rhs.size()) { return false; } for (size_t i = 0; i < lhs.size(); ++i) { if (lhs[i].name != rhs[i].name) { return false; } if (lhs[i].shouldExpand != rhs[i].shouldExpand) { if (!ignoreExpansionInLast) { return false; } if (i != lhs.size() - 1) { return false; } } } return true; } //////////////////////////////////////////////////////////////////////////////// /// @brief compare two attribute name vectors and return true if their names /// matches //////////////////////////////////////////////////////////////////////////////// bool arangodb::basics::AttributeName::namesMatch(std::vector<AttributeName> const& lhs, std::vector<AttributeName> const& rhs) { if (lhs.size() != rhs.size()) { return false; } for (size_t i = 0; i < lhs.size(); ++i) { if (lhs[i].name != rhs[i].name) { return false; } } return true; } //////////////////////////////////////////////////////////////////////////////// /// @brief compare two attribute name vectors //////////////////////////////////////////////////////////////////////////////// bool arangodb::basics::AttributeName::isIdentical( std::vector<std::vector<AttributeName>> const& lhs, std::vector<std::vector<AttributeName>> const& rhs, bool ignoreExpansionInLast) { if (lhs.size() != rhs.size()) { return false; } for (size_t i = 0; i < lhs.size(); ++i) { if (!isIdentical(lhs[i], rhs[i], ignoreExpansionInLast && (i == lhs.size() - 1))) { return false; } } return true; } void arangodb::basics::TRI_ParseAttributeString(std::string const& input, std::vector<AttributeName>& result, bool allowExpansion) { TRI_ParseAttributeString(arangodb::velocypack::StringRef(input), result, allowExpansion); } void arangodb::basics::TRI_ParseAttributeString(arangodb::velocypack::StringRef const& input, std::vector<AttributeName>& result, bool allowExpansion) { bool foundExpansion = false; size_t parsedUntil = 0; size_t const length = input.length(); for (size_t pos = 0; pos < length; ++pos) { auto token = input[pos]; if (token == '[') { if (!allowExpansion) { THROW_ARANGO_EXCEPTION_MESSAGE( TRI_ERROR_BAD_PARAMETER, "cannot use [*] expansion for this type of index"); } // We only allow attr[*] and attr[*].attr2 as valid patterns if (length - pos < 3 || input[pos + 1] != '*' || input[pos + 2] != ']' || (length - pos > 3 && input[pos + 3] != '.')) { THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_ARANGO_ATTRIBUTE_PARSER_FAILED, "can only use [*] for indexes"); } if (foundExpansion) { THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_BAD_PARAMETER, "cannot use multiple [*] " "expansions for a single index " "field"); } result.emplace_back(input.substr(parsedUntil, pos - parsedUntil), true); foundExpansion = true; pos += 4; parsedUntil = pos; } else if (token == '.') { result.emplace_back(input.substr(parsedUntil, pos - parsedUntil), false); ++pos; parsedUntil = pos; } } if (parsedUntil < length) { result.emplace_back(input.substr(parsedUntil), false); } } void arangodb::basics::TRI_AttributeNamesToString(std::vector<AttributeName> const& input, std::string& result, bool excludeExpansion) { TRI_ASSERT(result.empty()); bool isFirst = true; for (auto const& it : input) { if (!isFirst) { result += "."; } isFirst = false; result += it.name; if (!excludeExpansion && it.shouldExpand) { result += "[*]"; } } } bool arangodb::basics::TRI_AttributeNamesHaveExpansion(std::vector<AttributeName> const& input) { return std::any_of(input.begin(), input.end(), [](AttributeName const& value) { return value.shouldExpand; }); } //////////////////////////////////////////////////////////////////////////////// /// @brief append the attribute name to an output stream //////////////////////////////////////////////////////////////////////////////// std::ostream& operator<<(std::ostream& stream, arangodb::basics::AttributeName const& name) { stream << name.name; if (name.shouldExpand) { stream << "[*]"; } return stream; } //////////////////////////////////////////////////////////////////////////////// /// @brief append the attribute names to an output stream //////////////////////////////////////////////////////////////////////////////// std::ostream& operator<<(std::ostream& stream, std::vector<arangodb::basics::AttributeName> const& attributes) { size_t const n = attributes.size(); for (size_t i = 0; i < n; ++i) { if (i > 0) { stream << "."; } stream << attributes[i]; } return stream; }
34.683721
104
0.524205
[ "vector" ]
fe6e56789b6ece96bb8f31bcae34e11549e7cc63
1,746
cpp
C++
341-flatten-nested-list-iterator/flatten-nested-list-iterator.cpp
amorphobia/Leetcode_solutions
f7b68a10bdad9aa42498ab36233b9b9c687dc860
[ "MIT" ]
null
null
null
341-flatten-nested-list-iterator/flatten-nested-list-iterator.cpp
amorphobia/Leetcode_solutions
f7b68a10bdad9aa42498ab36233b9b9c687dc860
[ "MIT" ]
null
null
null
341-flatten-nested-list-iterator/flatten-nested-list-iterator.cpp
amorphobia/Leetcode_solutions
f7b68a10bdad9aa42498ab36233b9b9c687dc860
[ "MIT" ]
null
null
null
/** * // This is the interface that allows for creating nested lists. * // You should not implement it, or speculate about its implementation * class NestedInteger { * public: * // Return true if this NestedInteger holds a single integer, rather than a nested list. * bool isInteger() const; * * // Return the single integer that this NestedInteger holds, if it holds a single integer * // The result is undefined if this NestedInteger holds a nested list * int getInteger() const; * * // Return the nested list that this NestedInteger holds, if it holds a nested list * // The result is undefined if this NestedInteger holds a single integer * const vector<NestedInteger> &getList() const; * }; */ class NestedIterator { public: NestedIterator(vector<NestedInteger> &nestedList) { for (auto rit = nestedList.rbegin(); rit != nestedList.rend(); ++rit) { list.push(*rit); } } int next() { int ret = list.top().getInteger(); list.pop(); return ret; } bool hasNext() { if (list.empty()) return false; // flatten the first element until it becomes an integer NestedInteger top_ele = list.top(); if (top_ele.isInteger()) return true; list.pop(); // pop it out if it is not an integer vector<NestedInteger> top_list = top_ele.getList(); for (auto rit = top_list.rbegin(); rit != top_list.rend(); ++rit) { list.push(*rit); } return hasNext(); } stack<NestedInteger> list; }; /** * Your NestedIterator object will be instantiated and called as such: * NestedIterator i(nestedList); * while (i.hasNext()) cout << i.next(); */
31.178571
95
0.624284
[ "object", "vector" ]
fe72e98b9bf5a41d004e3b4e7eb1116cb12d0601
3,805
cpp
C++
DesignPatterns/command/main.cpp
alexey-malov/modern-cpp-usage
e915578850c9cc7adbbccfe6eb1c63f69db4d7a6
[ "WTFPL" ]
1
2017-11-16T16:51:40.000Z
2017-11-16T16:51:40.000Z
DesignPatterns/command/main.cpp
alexey-malov/modern-cpp-usage
e915578850c9cc7adbbccfe6eb1c63f69db4d7a6
[ "WTFPL" ]
null
null
null
DesignPatterns/command/main.cpp
alexey-malov/modern-cpp-usage
e915578850c9cc7adbbccfe6eb1c63f69db4d7a6
[ "WTFPL" ]
null
null
null
#include "Commands.h" #include "Menu.h" #include "MenuFP.h" using namespace std; class MenuHelpCommand : public ICommand { public: MenuHelpCommand(const Menu& menu) : m_menu(menu) {} void Execute() override { m_menu.ShowInstructions(); } private: const Menu& m_menu; }; class ExitMenuCommand : public ICommand { public: ExitMenuCommand(Menu& menu) : m_menu(menu) {} void Execute() override { m_menu.Exit(); } private: Menu& m_menu; }; template <typename Commands> MenuFP::Command CreateMacroCommand(Commands&& commands) { return [=] { for (auto& command : commands) { command(); } }; } void TestMenuWithClassicCommandPattern() { Robot robot; Menu menu; menu.AddItem("on", "Turns the Robot on", make_unique<TurnOnCommand>(robot)); menu.AddItem("off", "Turns the Robot off", make_unique<TurnOffCommand>(robot)); menu.AddItem( "north", "Makes the Robot walk north", make_unique<WalkCommand>(robot, WalkDirection::North)); menu.AddItem( "south", "Makes the Robot walk south", make_unique<WalkCommand>(robot, WalkDirection::South)); menu.AddItem( "west", "Makes the Robot walk west", make_unique<WalkCommand>(robot, WalkDirection::West)); menu.AddItem( "east", "Makes the Robot walk east", make_unique<WalkCommand>(robot, WalkDirection::East)); auto cmd = make_unique<MacroCommand>(); cmd->AddCommand(make_unique<TurnOnCommand>(robot)); cmd->AddCommand(make_unique<WalkCommand>(robot, WalkDirection::North)); cmd->AddCommand(make_unique<WalkCommand>(robot, WalkDirection::East)); cmd->AddCommand(make_unique<WalkCommand>(robot, WalkDirection::South)); cmd->AddCommand(make_unique<WalkCommand>(robot, WalkDirection::West)); cmd->AddCommand(make_unique<TurnOffCommand>(robot)); menu.AddItem("patrol", "Patrol the territory", move(cmd)); menu.AddItem("stop", "Stops the Robot", make_unique<StopCommand>(robot)); menu.AddItem("help", "Show instructions", make_unique<MenuHelpCommand>(menu)); menu.AddItem("exit", "Exit from this menu", make_unique<ExitMenuCommand>(menu)); menu.Run(); } void TestMenuWithFunctionalCommandPattern() { Robot robot; MenuFP menu; menu.AddItem("on", "Turns the Robot on", [&] { robot.TurnOn(); }); menu.AddItem("off", "Turns the Robot off", bind(&Robot::TurnOff, &robot)); menu.AddItem( "north", "Makes the Robot walk north", bind(&Robot::Walk, &robot, WalkDirection::North)); menu.AddItem( "south", "Makes the Robot walk south", bind(&Robot::Walk, &robot, WalkDirection::South)); menu.AddItem( "west", "Makes the Robot walk west", bind(&Robot::Walk, &robot, WalkDirection::West)); menu.AddItem( "east", "Makes the Robot walk east", bind(&Robot::Walk, &robot, WalkDirection::East)); menu.AddItem("stop", "Stops the Robot", bind(&Robot::Stop, &robot)); menu.AddItem( "patrol", "Patrol the territory", CreateMacroCommand<vector<MenuFP::Command>>( {bind(&Robot::TurnOn, &robot), bind(&Robot::Walk, &robot, WalkDirection::North), bind(&Robot::Walk, &robot, WalkDirection::South), bind(&Robot::Walk, &robot, WalkDirection::West), bind(&Robot::Walk, &robot, WalkDirection::East), bind(&Robot::TurnOff, &robot)})); menu.AddItem("help", "Show instructions", bind(&MenuFP::ShowInstructions, &menu)); menu.AddItem("exit", "Exit from this menu", bind(&MenuFP::Exit, &menu)); menu.Run(); } int main() { MenuFP menu; menu.AddItem("c", "Classic command pattern implementation", [&] { TestMenuWithClassicCommandPattern(); menu.ShowInstructions(); }); menu.AddItem("f", "Functional command pattern implementation", [&] { TestMenuWithFunctionalCommandPattern(); menu.ShowInstructions(); }); menu.AddItem("q", "Exit Program", bind(&MenuFP::Exit, &menu)); menu.Run(); return 0; }
32.801724
98
0.691196
[ "vector" ]
fe7416a4ee595eb474db1d707b7e9d8dfe439b61
15,541
cpp
C++
plugins/multiarc/ArcMix.cpp
data-man/FarAS
8bd1725cdd2aaee90081ae35c492738e0be470a3
[ "BSD-3-Clause" ]
1
2020-12-05T17:33:05.000Z
2020-12-05T17:33:05.000Z
plugins/multiarc/ArcMix.cpp
data-man/FarAS
8bd1725cdd2aaee90081ae35c492738e0be470a3
[ "BSD-3-Clause" ]
1
2021-02-23T13:01:10.000Z
2021-02-23T13:01:10.000Z
plugins/multiarc/ArcMix.cpp
data-man/FarAS
8bd1725cdd2aaee90081ae35c492738e0be470a3
[ "BSD-3-Clause" ]
null
null
null
#include "MultiArc.hpp" #include "marclng.hpp" #include <dos.h> BOOL FileExists(const char* Name) { return GetFileAttributes(Name)!=0xFFFFFFFF; } BOOL GoToFile(const char *Target, BOOL AllowChangeDir) { if(!Target || !*Target) return FALSE; BOOL rc=FALSE, search=TRUE; PanelRedrawInfo PRI; PanelInfo PInfo; char Name[NM], Dir[NM*5]; int pathlen; lstrcpy(Name,FSF.PointToName(const_cast<char*>(Target))); pathlen=(int)(FSF.PointToName(const_cast<char*>(Target))-Target); if(pathlen) memcpy(Dir,Target,pathlen); Dir[pathlen]=0; FSF.Trim(Name); FSF.Trim(Dir); FSF.Unquote(Name); FSF.Unquote(Dir); Info.Control(INVALID_HANDLE_VALUE,FCTL_UPDATEPANEL,(void*)1); Info.Control(INVALID_HANDLE_VALUE,FCTL_GETPANELINFO,&PInfo); pathlen=lstrlen(Dir); if(pathlen) { if(*PInfo.CurDir && PInfo.CurDir[lstrlen(PInfo.CurDir)-1]!='\\' // old path != "*\" && Dir[pathlen-1]=='\\') Dir[pathlen-1]=0; if(0!=FSF.LStricmp(Dir,PInfo.CurDir)) { if(AllowChangeDir) { Info.Control(INVALID_HANDLE_VALUE,FCTL_SETPANELDIR,&Dir); Info.Control(INVALID_HANDLE_VALUE,FCTL_GETPANELINFO,&PInfo); } else search=FALSE; } } PRI.CurrentItem=PInfo.CurrentItem; PRI.TopPanelItem=PInfo.TopPanelItem; if(search) { for(int J=0; J < PInfo.ItemsNumber; J++) { if(!FSF.LStricmp(Name, FSF.PointToName(PInfo.PanelItems[J].FindData.cFileName))) { PRI.CurrentItem=J; PRI.TopPanelItem=J; rc=TRUE; break; } } } return rc?Info.Control(INVALID_HANDLE_VALUE,FCTL_REDRAWPANEL,&PRI):FALSE; } int __isspace(int Chr) { return Chr == 0x09 || Chr == 0x0A || Chr == 0x0B || Chr == 0x0C || Chr == 0x0D || Chr == 0x20; } const char *GetMsg(int MsgId) { return Info.GetMsg(Info.ModuleNumber,MsgId); } /* $ 13.09.2000 tran запуск треда для ожидания момента убийства лист файла */ void StartThreadForKillListFile(PROCESS_INFORMATION *pi,char *list) { if ( pi==0 || list==0 || *list==0) return; KillStruct *ks; DWORD dummy; ks=(KillStruct*)GlobalAlloc(GPTR,sizeof(KillStruct)); if ( ks==0 ) return ; ks->hThread=pi->hThread; ks->hProcess=pi->hProcess; lstrcpy(ks->ListFileName,list); CreateThread(NULL,0xf000,ThreadWhatWaitingForKillListFile,ks,0 /* no flags */,&dummy); } DWORD WINAPI ThreadWhatWaitingForKillListFile(LPVOID par) { KillStruct *ks=(KillStruct*)par; WaitForSingleObject(ks->hProcess,INFINITE); CloseHandle(ks->hThread); CloseHandle(ks->hProcess); DeleteFile(ks->ListFileName); GlobalFree((LPVOID)ks); return SUPER_PUPER_ZERO; } /* tran 13.09.2000 $ */ int Execute(HANDLE hPlugin,char *CmdStr,int HideOutput,int Silent,int ShowTitle,char *ListFileName) { STARTUPINFO si; PROCESS_INFORMATION pi; int ExitCode,ExitCode2,LastError; memset(&si,0,sizeof(si)); si.cb=sizeof(si); HANDLE hChildStdoutRd,hChildStdoutWr; HANDLE StdInput=GetStdHandle(STD_INPUT_HANDLE); HANDLE StdOutput=GetStdHandle(STD_OUTPUT_HANDLE); HANDLE StdError=GetStdHandle(STD_ERROR_HANDLE); HANDLE hScreen=NULL; CONSOLE_SCREEN_BUFFER_INFO csbi; if (HideOutput) { SECURITY_ATTRIBUTES saAttr; saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); saAttr.bInheritHandle = TRUE; saAttr.lpSecurityDescriptor = NULL; if (CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 32768)) { if (Silent) { /*hScreen=Info.SaveScreen(0,0,-1,0); Info.Text(2,0,LIGHTGRAY,GetMsg(MWaitForExternalProgram))*/; } else { hScreen=Info.SaveScreen(0,0,-1,-1); const char *MsgItems[]={"",GetMsg(MWaitForExternalProgram)}; Info.Message(Info.ModuleNumber,0,NULL,MsgItems, ARRAYSIZE(MsgItems),0); } SetStdHandle(STD_OUTPUT_HANDLE,hChildStdoutWr); SetStdHandle(STD_ERROR_HANDLE,hChildStdoutWr); } else HideOutput=FALSE; } else { Info.Control(hPlugin, FCTL_GETUSERSCREEN, NULL); GetConsoleScreenBufferInfo(StdOutput, &csbi); COORD C = { 0, csbi.dwCursorPosition.Y }; SetConsoleCursorPosition(StdOutput, C); } DWORD ConsoleMode; GetConsoleMode(StdInput,&ConsoleMode); SetConsoleMode(StdInput,ENABLE_PROCESSED_INPUT|ENABLE_LINE_INPUT| ENABLE_ECHO_INPUT|ENABLE_MOUSE_INPUT); char ExpandedCmd[MAX_COMMAND_LENGTH]; ExpandEnvironmentStrings(CmdStr,ExpandedCmd,sizeof(ExpandedCmd)); FSF.LTrim(ExpandedCmd); //$ AA 12.11.2001 char SaveTitle[512]; GetConsoleTitle(SaveTitle,sizeof(SaveTitle)); if (ShowTitle) SetConsoleTitle(ExpandedCmd); /* $ 14.02.2001 raVen делать окошку minimize, если в фоне */ if (Opt.Background) { si.dwFlags=si.dwFlags | STARTF_USESHOWWINDOW; si.wShowWindow=SW_MINIMIZE; } /* raVen $ */ ExitCode2=ExitCode=CreateProcess(NULL,ExpandedCmd,NULL,NULL,HideOutput, (Opt.Background?CREATE_NEW_CONSOLE:0)|PriorityProcessCode[Opt.PriorityClass], NULL,NULL,&si,&pi); LastError=!ExitCode?GetLastError():0; if (HideOutput) { SetStdHandle(STD_OUTPUT_HANDLE,StdOutput); SetStdHandle(STD_ERROR_HANDLE,StdError); CloseHandle(hChildStdoutWr); } SetLastError(LastError); if(!ExitCode2 /*|| !FindExecuteFile(ExecuteName,NULL,0)*/) //$ 06.03.2002 AA { char Msg[100]; char ExecuteName[NM]; lstrcpyn(ExecuteName,ExpandedCmd+(*ExpandedCmd=='"'), NM); char *Ptr; Ptr=strchr(ExecuteName,(*ExpandedCmd=='"')?'"':' '); if(Ptr) *Ptr=0; FindExecuteFile(ExecuteName,NULL,0); char NameMsg[NM]; FSF.TruncPathStr(lstrcpyn(NameMsg,ExecuteName,sizeof(NameMsg)),MAX_WIDTH_MESSAGE); FSF.sprintf(Msg,GetMsg(MCannotFindArchivator),NameMsg); const char *MsgItems[]={GetMsg(MError),Msg, GetMsg(MOk)}; Info.Message(Info.ModuleNumber,FMSG_WARNING|FMSG_ERRORTYPE, NULL,MsgItems,ARRAYSIZE(MsgItems),1); ExitCode=RETEXEC_ARCNOTFOUND; } if (ExitCode && ExitCode!=RETEXEC_ARCNOTFOUND) { if (HideOutput) { WaitForSingleObject(pi.hProcess,1000); char PipeBuf[32768]; DWORD Read; while (ReadFile(hChildStdoutRd,PipeBuf,sizeof(PipeBuf),&Read,NULL)) ; CloseHandle(hChildStdoutRd); } /* $ 13.09.2000 tran фоновой выполнение */ if ( !Opt.Background ) { WaitForSingleObject(pi.hProcess,INFINITE); GetExitCodeProcess(pi.hProcess,(LPDWORD)&ExitCode); CloseHandle(pi.hThread); CloseHandle(pi.hProcess); } else { StartThreadForKillListFile(&pi,ListFileName); // нехай за процессом тред следит, и файл бъет тапком ExitCode=0; } /* tran 13.09.2000 $ */ } SetConsoleTitle(SaveTitle); SetConsoleMode(StdInput,ConsoleMode); if (!HideOutput) { Info.Control(hPlugin,FCTL_SETUSERSCREEN,NULL); } if (hScreen) { Info.RestoreScreen(NULL); Info.RestoreScreen(hScreen); } return ExitCode; } char* QuoteText(char *Str) { int LastPos=lstrlen(Str); memmove(Str+1,Str,LastPos+1); Str[LastPos+1]=*Str='"'; Str[LastPos+2]=0; return Str; } void ConvertNameToShort(const char *Src,char *Dest) { char ShortName[NM],AnsiName[NM]; SetFileApisToANSI(); OemToChar(Src,AnsiName); if (GetShortPathName(AnsiName,ShortName,sizeof(ShortName))) CharToOem(ShortName,Dest); else lstrcpy(Dest,Src); SetFileApisToOEM(); } void InitDialogItems(const struct InitDialogItem *Init,struct FarDialogItem *Item, int ItemsNumber) { int I; struct FarDialogItem *PItem=Item; const struct InitDialogItem *PInit=Init; for (I=0;I<ItemsNumber;I++,PItem++,PInit++) { PItem->Type=PInit->Type; PItem->X1=PInit->X1; PItem->Y1=PInit->Y1; PItem->X2=PInit->X2; PItem->Y2=PInit->Y2; PItem->Focus=PInit->Focus; PItem->History=(const char *)PInit->Selected; PItem->Flags=PInit->Flags; PItem->DefaultButton=PInit->DefaultButton; lstrcpy(PItem->Data,((DWORD_PTR)PInit->Data<2000)?GetMsg((unsigned int)(DWORD_PTR)PInit->Data):PInit->Data); } } static void __InsertCommas(char *Dest) { int I; for (I=lstrlen(Dest)-4;I>=0;I-=3) if (Dest[I]) { memmove(Dest+I+2,Dest+I+1,lstrlen(Dest+I)); Dest[I+1]=','; } } void InsertCommas(unsigned long Number,char *Dest) { __InsertCommas(FSF.itoa(Number,Dest,10)); } void InsertCommas(__int64 Number,char *Dest) { __InsertCommas(FSF.itoa64(Number,Dest,10)); } int ToPercent(long N1,long N2) { if (N1 > 10000) { N1/=100; N2/=100; } if (N2==0) return 0; if (N2<N1) return 100; return (int)(N1*100/N2); } int ToPercent(__int64 N1,__int64 N2) { if (N1 > 10000) { N1/=100; N2/=100; } if (N2==0) return 0; if (N2<N1) return 100; return (int)(N1*100/N2); } int IsCaseMixed(const char *Str) { while (*Str && !IsCharAlpha(*Str)) Str++; int Case=IsCharLower(*Str); while (*(Str++)) if (IsCharAlpha(*Str) && IsCharLower(*Str)!=Case) return TRUE; return FALSE; } int CheckForEsc() { int ExitCode=FALSE; while (1) { INPUT_RECORD rec; /*static*/ HANDLE hConInp=GetStdHandle(STD_INPUT_HANDLE); DWORD ReadCount; PeekConsoleInput(hConInp,&rec,1,&ReadCount); if (ReadCount==0) break; ReadConsoleInput(hConInp,&rec,1,&ReadCount); if (rec.EventType==KEY_EVENT) if (rec.Event.KeyEvent.wVirtualKeyCode==VK_ESCAPE && rec.Event.KeyEvent.bKeyDown) ExitCode=TRUE; } return ExitCode; } int LocalStrnicmp(const char *Str1,const char *Str2,int Length) { char AnsiStr1[8192],AnsiStr2[8192]; OemToChar(Str1,AnsiStr1); OemToChar(Str2,AnsiStr2); AnsiStr1[Length]=AnsiStr2[Length]=0; CharLower(AnsiStr1); CharLower(AnsiStr2); return lstrcmp(AnsiStr1,AnsiStr2); } char *GetCommaWord(char *Src,char *Word,char Separator) { int WordPos,SkipBrackets; if (*Src==0) return NULL; SkipBrackets=FALSE; for (WordPos=0;*Src!=0;Src++,WordPos++) { if (*Src=='[' && strchr(Src+1,']')!=NULL) SkipBrackets=TRUE; if (*Src==']') SkipBrackets=FALSE; if (*Src==Separator && !SkipBrackets) { Word[WordPos]=0; Src++; while (__isspace(*Src)) Src++; return Src; } else Word[WordPos]=*Src; } Word[WordPos]=0; return Src; } int FindExecuteFile(char *OriginalName,char *DestName,int SizeDest) { char Env[512]; char TempDestName[1024],*FilePart; char Ext[64],*PtrExt; if((PtrExt=strrchr(OriginalName,'.')) == NULL) { if(!GetEnvironmentVariable("PATHEXT",Env,sizeof(Env))) lstrcpy(Env,".exe;.com;.bat;.cmd"); PtrExt=Env; while(1) { if((PtrExt=GetCommaWord(PtrExt,Ext,';')) == NULL) break; if(SearchPath(NULL,OriginalName,Ext, sizeof(TempDestName), // size, in characters, of buffer TempDestName, // address of buffer for found filename &FilePart)) // address of pointer to file component { if(DestName) lstrcpyn(DestName,TempDestName,SizeDest); return TRUE; } } } else if(SearchPath(NULL,OriginalName,PtrExt, sizeof(TempDestName), // size, in characters, of buffer TempDestName, // address of buffer for found filename &FilePart)) // address of pointer to file component { if(DestName) lstrcpyn(DestName,TempDestName,SizeDest); return TRUE; } return FALSE; } char *SeekDefExtPoint(char *Name, char *DefExt/*=NULL*/, char **Ext/*=NULL*/) { FSF.Unquote(Name); //$ AA 15.04.2003 для правильной обработки имен в кавычках Name=FSF.PointToName(Name); char *TempExt=strrchr(Name, '.'); if(!DefExt) return TempExt; if(Ext) *Ext=TempExt; return (TempExt!=NULL)?(FSF.LStricmp(TempExt+1, DefExt)?NULL:TempExt):NULL; } BOOL AddExt(char *Name, char *Ext) { char *ExtPnt; FSF.Unquote(Name); //$ AA 15.04.2003 для правильной обработки имен в кавычках if(Name && *Name && !SeekDefExtPoint(Name, Ext, &ExtPnt)) { // transform Ext char NewExt[NM], *Ptr; lstrcpyn(NewExt,Ext,sizeof(NewExt)); int Up=0, Lw=0; Ptr=FSF.PointToName(Name); // yjh 11.04.2020 while(*Ptr) { if(FSF.LIsAlpha(*Ptr)) { if(FSF.LIsLower(*Ptr)) Lw++; if(FSF.LIsUpper(*Ptr)) Up++; } ++Ptr; } if (Lw) FSF.LStrlwr (NewExt); else if (Up) FSF.LStrupr (NewExt); if(ExtPnt && !*(ExtPnt+1)) lstrcpy(ExtPnt+1, NewExt); else FSF.sprintf(Name+lstrlen(Name), ".%s", NewExt); return TRUE; } return FALSE; } #ifdef _NEW_ARC_SORT_ void WritePrivateProfileInt(char *Section, char *Key, int Value, char *Ini) { char Buf32[32]; wsprintf(Buf32, "%d", Value); WritePrivateProfileString(Section, Key, Buf32, Ini); } #endif int WINAPI GetPassword(char *Password,const char *FileName) { char Prompt[2*NM],InPass[512]; FSF.sprintf(Prompt,GetMsg(MGetPasswordForFile),FileName); if(Info.InputBox((const char*)GetMsg(MGetPasswordTitle), (const char*)Prompt,NULL,NULL, InPass,sizeof(InPass),NULL,FIB_PASSWORD|FIB_ENABLEEMPTY)) { lstrcpy(Password,InPass); return TRUE; } return FALSE; } // Number of 100 nanosecond units from 01.01.1601 to 01.01.1970 #define EPOCH_BIAS I64(116444736000000000) void WINAPI UnixTimeToFileTime( DWORD time, FILETIME * ft ) { *(__int64*)ft = EPOCH_BIAS + time * I64(10000000); } int GetScrX(void) { CONSOLE_SCREEN_BUFFER_INFO ConsoleScreenBufferInfo; if(GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE),&ConsoleScreenBufferInfo)) return ConsoleScreenBufferInfo.dwSize.X; return 0; } int PathMayBeAbsolute(const char *Path) { return (Path && ( (((*Path >= 'a' && *Path <= 'z') || (*Path >= 'A' && *Path <= 'Z')) && Path[1]==':') || (Path[0]=='\\' && Path[1]=='\\') || (Path[0]=='/' && Path[1]=='/') ) ); } /* преобразует строку "cdrecord-1.6.1/mkisofs-1.12b4/../cdrecord/cd_misc.c" в "cdrecord-1.6.1/cdrecord/cd_misc.c" */ void NormalizePath(const char *lpcSrcName,char *lpDestName) { char *DestName=lpDestName; char *Ptr; char *SrcName=strdup(lpcSrcName); char *oSrcName=SrcName; int dist; while(*SrcName) { Ptr=strchr(SrcName,'\\'); if(!Ptr) Ptr=strchr(SrcName,'/'); if(!Ptr) Ptr=SrcName+lstrlen(SrcName); dist=(int)(Ptr-SrcName)+1; if(dist == 1 && (*SrcName == '\\' || *SrcName == '/')) { *DestName=*SrcName; DestName++; SrcName++; } else if(dist == 2 && *SrcName == '.') { SrcName++; if(*SrcName == 0) DestName--; else SrcName++; } else if(dist == 3 && *SrcName == '.' && SrcName[1] == '.') { if(!PathMayBeAbsolute(lpDestName)) { char *ptrCurDestName=lpDestName, *Temp=NULL; for ( ; ptrCurDestName < DestName-1; ptrCurDestName++) { if (*ptrCurDestName == '\\' || *ptrCurDestName == '/') Temp = ptrCurDestName; } if(!Temp) Temp=lpDestName; DestName=Temp; } else { if(SrcName[2] == '\\' || SrcName[2] == '/') SrcName++; } SrcName+=2; } else { lstrcpyn(DestName, SrcName, dist); dist--; DestName += dist; SrcName += dist; } *DestName=0; } free(oSrcName); }
23.726718
112
0.632713
[ "transform" ]
fe770213104990accafcda27a5cc5d34e99691a7
3,641
cpp
C++
test/unit/module/math/sin.cpp
the-moisrex/eve
80b52663eefee11460abb0aedf4158a5067cf7dc
[ "MIT" ]
340
2020-09-16T21:12:48.000Z
2022-03-28T15:40:33.000Z
test/unit/module/math/sin.cpp
the-moisrex/eve
80b52663eefee11460abb0aedf4158a5067cf7dc
[ "MIT" ]
383
2020-09-17T06:56:35.000Z
2022-03-13T15:58:53.000Z
test/unit/module/math/sin.cpp
the-moisrex/eve
80b52663eefee11460abb0aedf4158a5067cf7dc
[ "MIT" ]
28
2021-02-27T23:11:23.000Z
2022-03-25T12:31:29.000Z
//================================================================================================== /** EVE - Expressive Vector Engine Copyright : EVE Contributors & Maintainers SPDX-License-Identifier: MIT **/ //================================================================================================== #include "test.hpp" #include <eve/concept/value.hpp> #include <eve/constant/valmin.hpp> #include <eve/constant/valmax.hpp> #include <eve/constant/pio_4.hpp> #include <eve/constant/pio_2.hpp> #include <eve/function/sin.hpp> #include <eve/function/diff/sin.hpp> #include <cmath> #include <eve/module/math/detail/constant/rempio2_limits.hpp> //================================================================================================== // Types tests //================================================================================================== EVE_TEST_TYPES( "Check return types of sin" , eve::test::simd::ieee_reals ) <typename T>(eve::as<T>) { using v_t = eve::element_type_t<T>; TTS_EXPR_IS( eve::sin(T()) , T); TTS_EXPR_IS( eve::sin(v_t()), v_t); }; //================================================================================================== // sin tests //================================================================================================== auto mquarter_c = []<typename T>(eve::as<T> const & tgt){ return -eve::pio_4(tgt); }; auto quarter_c = []<typename T>(eve::as<T> const & tgt){ return eve::pio_4(tgt); }; auto mhalf_c = []<typename T>(eve::as<T> const & tgt){ return -eve::pio_2(tgt); }; auto half_c = []<typename T>(eve::as<T> const & tgt){ return eve::pio_2(tgt); }; auto mfull_c =[]<typename T>(eve::as<T> const & tgt){ return -eve::pi(tgt); }; auto full_c =[]<typename T>(eve::as<T> const & tgt){ return eve::pi(tgt); }; auto mmed = []<typename T>(eve::as<T> const & tgt){ return -eve::detail::Rempio2_limit(eve::detail::medium_type(), tgt); }; auto med = []<typename T>(eve::as<T> const & tgt){ return eve::detail::Rempio2_limit(eve::detail::medium_type(), tgt); }; EVE_TEST( "Check behavior of sin on wide" , eve::test::simd::ieee_reals , eve::test::generate( eve::test::randoms(mquarter_c, quarter_c) , eve::test::randoms(mhalf_c, half_c) , eve::test::randoms(mfull_c ,full_c) , eve::test::randoms(mmed, med) , eve::test::randoms(eve::valmin, eve::valmax)) ) <typename T>(T const& a0, T const& a1, T const& a2, T const& a3, T const& a4) { using eve::detail::map; using eve::sin; using eve::diff; using v_t = eve::element_type_t<T>; auto ref = [](auto e) -> v_t { return std::sin(e); }; TTS_ULP_EQUAL(eve::quarter_circle(sin)(a0) , map(ref, a0), 2); TTS_ULP_EQUAL(eve::half_circle(sin)(a0) , map(ref, a0), 2); TTS_ULP_EQUAL(eve::half_circle(sin)(a1) , map(ref, a1), 2); TTS_ULP_EQUAL(eve::full_circle(sin)(a0) , map(ref, a0), 2); TTS_ULP_EQUAL(eve::full_circle(sin)(a1) , map(ref, a1), 2); TTS_ULP_EQUAL(eve::full_circle(sin)(a2) , map(ref, a2), 2); TTS_ULP_EQUAL(sin(a0) , map(ref, a0), 2); TTS_ULP_EQUAL(sin(a1) , map(ref, a1), 2); TTS_ULP_EQUAL(sin(a2) , map(ref, a2), 2); TTS_ULP_EQUAL(sin(a3) , map(ref, a3), 2); TTS_ULP_EQUAL(sin(a4) , map(ref, a4), 2); TTS_ULP_EQUAL(diff(sin)(a0), map([](auto e) -> v_t { return std::cos(e); }, a0), 2); };
49.876712
126
0.480912
[ "vector" ]
fe77b6171ca6ff287999f5245cd810d0db74ae20
1,546
hpp
C++
VVISF/include/VVISF_StringUtils.hpp
mrRay/VVISF-GL
96b00da11e4497da304041ea2a5ffc6e3a8c9454
[ "BSD-3-Clause" ]
24
2019-01-17T17:56:18.000Z
2022-02-27T19:57:13.000Z
VVISF/include/VVISF_StringUtils.hpp
mrRay/VVISF-GL
96b00da11e4497da304041ea2a5ffc6e3a8c9454
[ "BSD-3-Clause" ]
6
2019-01-17T17:17:12.000Z
2020-06-19T11:27:50.000Z
VVISF/include/VVISF_StringUtils.hpp
mrRay/VVISF-GL
96b00da11e4497da304041ea2a5ffc6e3a8c9454
[ "BSD-3-Clause" ]
2
2020-12-25T04:57:31.000Z
2021-03-02T22:05:31.000Z
#ifndef ISFStringUtils_hpp #define ISFStringUtils_hpp #include <string> #include <vector> #include <map> #include "VVISF_Base.hpp" namespace VVISF { struct ISFVal; //struct Range; // this function parses a std::string as a bool val, and returns either an ISFNullVal (if the std::string couldn't be decisively parsed) or an ISFBoolVal (if it could) VVISF_EXPORT ISFVal ParseStringAsBool(const std::string & n); // this function evaluates the passed std::string and returns a null ISFVal (if the std::string couldn't be evaluated) or a float ISFVal (if it could) VVISF_EXPORT ISFVal ISFValByEvaluatingString(const std::string & n, const std::map<std::string, double> & inSymbols=std::map<std::string,double>()); // this function parses a function call from a std::string, dumping the strings of the function arguments // to the provided array. returns the size of the function std::string (from first char of function call // to the closing parenthesis of the function call) VVISF_EXPORT VVGL::Range LexFunctionCall(const std::string & inBaseStr, const VVGL::Range & inFuncNameRange, std::vector<std::string> & outVarArray); VVISF_EXPORT std::string TrimWhitespace(const std::string & inBaseStr); VVISF_EXPORT void FindAndReplaceInPlace(std::string & inSearch, std::string & inReplace, std::string & inBase); VVISF_EXPORT void FindAndReplaceInPlace(const char * inSearch, const char * inReplace, std::string & inBase); VVISF_EXPORT std::string FullPath(const std::string & inRelativePath); } #endif /* ISFStringUtils_hpp */
33.608696
167
0.763907
[ "vector" ]
fe7907fc83c8018cf598f25f600e1bf7c4a5cdc7
4,279
cpp
C++
FTSE/AttributesTable.cpp
melindil/FTSE
c0b54194900ac45ce1ecc778d838a72d09278bab
[ "MIT" ]
3
2019-10-05T15:51:12.000Z
2021-01-08T21:58:48.000Z
FTSE/AttributesTable.cpp
melindil/FTSE
c0b54194900ac45ce1ecc778d838a72d09278bab
[ "MIT" ]
2
2021-06-04T13:42:16.000Z
2021-07-27T10:38:38.000Z
FTSE/AttributesTable.cpp
melindil/FTSE
c0b54194900ac45ce1ecc778d838a72d09278bab
[ "MIT" ]
2
2018-07-03T11:31:11.000Z
2021-06-16T21:05:38.000Z
/* MIT License Copyright (c) 2018 melindil 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 "AttributesTable.h" #include <sstream> std::map<uint32_t, AttributesTable::AttributeTableEntry> AttributesTable::namemap_; std::map<std::string, uint32_t> AttributesTable::reversemap_; std::vector<std::string> AttributesTable::groups_; void AttributesTable::Initialize(Logger* logger_) { groups_.clear(); namemap_.clear(); reversemap_.clear(); groups_.push_back("Error"); groups_.push_back("stats"); groups_.push_back("traits"); groups_.push_back("derived"); groups_.push_back("skills"); groups_.push_back("otraits"); groups_.push_back("perks"); groups_.push_back("chems"); // stats char** ptr = (char**)0x8a6b70; uint32_t offset = OFFSET_STATS; for (int i = 0; i < 7; i++) { AttributeTableEntry ate; ate.name = std::string(ptr[i]); ate.group = 1; namemap_[offset] = ate; reversemap_[ate.name] = offset; offset += 4; } // traits ptr = (char**)0x8a6b8c; offset = OFFSET_TRAITS; for (int i = 0; i < 11; i++) { AttributeTableEntry ate; ate.name = std::string(ptr[i]); ate.group = 2; namemap_[offset] = ate; reversemap_[ate.name] = offset; offset += 4; } // Derived ptr = (char**)0x8a41a0; offset = OFFSET_DERIVED; for (int i = 0; i < 26; i++) { AttributeTableEntry ate; ate.name = std::string(ptr[i]); ate.group = 3; namemap_[offset] = ate; reversemap_[ate.name] = offset; offset += 4; } // Skills ptr = (char**)0x8a6b18; offset = OFFSET_SKILLS; for (int i = 0; i < 18; i++) { AttributeTableEntry ate; ate.name = std::string(ptr[i]); ate.group = 4; namemap_[offset] = ate; reversemap_[ate.name] = offset; offset += 4; } for (int i = 0; i < 18; i++) { AttributeTableEntry ate; ate.name = std::string("tag_") + std::string(ptr[i]); ate.group = 4; namemap_[offset] = ate; reversemap_[ate.name] = offset; offset += 1; } // Optional Traits ptr = (char**)0x8a42d0; offset = OFFSET_OTRAITS; for (int i = 0; i < 38; i++) { AttributeTableEntry ate; ate.name = std::string(ptr[i]); ate.group = 5; namemap_[offset] = ate; reversemap_[ate.name] = offset; offset += 1; } // Perks ptr = (char**)0x8a4500; offset = OFFSET_PERKS; for (int i = 0; i < 111; i++) { AttributeTableEntry ate; ate.name = std::string(ptr[i * 19]); ate.group = 6; namemap_[offset] = ate; reversemap_[ate.name] = offset; offset += 4; } // Chems ptr = (char**)0x8a40cc; offset = OFFSET_CHEMS; for (int i = 0; i < 10; i++) { AttributeTableEntry ate; ate.name = std::string(ptr[i]); ate.group = 7; namemap_[offset] = ate; reversemap_[ate.name] = offset; offset += 4; } for (auto e : namemap_) { std::stringstream ss; ss << std::hex << e.first; //(*logger_) << "Attribute " << e.second.name << " at location 0x" << ss.str() << std::endl; } } std::string AttributesTable::GetNameByOffset(uint32_t offset) { return namemap_[offset].name; } std::string AttributesTable::GetGroupByOffset(uint32_t offset) { return groups_[namemap_[offset].group]; } uint32_t AttributesTable::GetOffsetByName(std::string const& name) { return reversemap_[name]; } std::string AttributesTable::GetGroupByName(std::string const& name) { return groups_[namemap_[reversemap_[name]].group]; }
24.877907
95
0.688712
[ "vector" ]
fe7e529f7deda7539a8728976b2970e9435a1b83
2,186
hpp
C++
include/Interop/ComCastor3D/Castor3D/ComGeometry.hpp
Mu-L/Castor3D
7b9c6e7be6f7373ad60c0811d136c0004e50e76b
[ "MIT" ]
245
2015-10-29T14:31:45.000Z
2022-03-31T13:04:45.000Z
include/Interop/ComCastor3D/Castor3D/ComGeometry.hpp
Mu-L/Castor3D
7b9c6e7be6f7373ad60c0811d136c0004e50e76b
[ "MIT" ]
64
2016-03-11T19:45:05.000Z
2022-03-31T23:58:33.000Z
include/Interop/ComCastor3D/Castor3D/ComGeometry.hpp
Mu-L/Castor3D
7b9c6e7be6f7373ad60c0811d136c0004e50e76b
[ "MIT" ]
11
2018-05-24T09:07:43.000Z
2022-03-21T21:05:20.000Z
/* See LICENSE file in root folder */ #ifndef __COMC3D_COM_GEOMETRY_H__ #define __COMC3D_COM_GEOMETRY_H__ #include "ComCastor3D/Castor3D/ComMesh.hpp" #include "ComCastor3D/Castor3D/ComSubmesh.hpp" #include <Castor3D/Scene/Geometry.hpp> namespace CastorCom { /*! \author Sylvain DOREMUS \version 0.7.0 \date 10/09/2014 \~english \brief This class defines a CGeometry object accessible from COM. \~french \brief Cette classe définit un CGeometry accessible depuis COM. */ class ATL_NO_VTABLE CGeometry : COM_ATL_OBJECT( Geometry ) { public: /** *\~english *\brief Default constructor. *\~french *\brief Constructeur par défaut. */ CGeometry(); /** *\~english *\brief Destructor. *\~french *\brief Destructeur. */ virtual ~CGeometry(); inline castor3d::GeometrySPtr getInternal()const { return m_internal; } inline void setInternal( castor3d::GeometrySPtr internal ) { m_internal = internal; } COM_PROPERTY( Mesh, IMesh *, makeGetter( m_internal.get(), &castor3d::Geometry::getMesh ), makePutter( m_internal.get(), &castor3d::Geometry::setMesh ) ); COM_PROPERTY_GET( Name, BSTR, makeGetter( m_internal.get(), &castor3d::MovableObject::getName ) ); COM_PROPERTY_GET( Type, eMOVABLE_TYPE, makeGetter( m_internal.get(), &castor3d::MovableObject::getType ) ); COM_PROPERTY_GET( Scene, IScene *, makeGetter( m_internal.get(), &castor3d::MovableObject::getScene ) ); STDMETHOD( GetMaterial )( /* [in] */ ISubmesh * submesh, /* [out, retval] */ IMaterial ** pVal ); STDMETHOD( SetMaterial )( /* [in] */ ISubmesh * submesh, /* [in] */ IMaterial * val ); STDMETHOD( AttachTo )( /* [in] */ ISceneNode * val ); STDMETHOD( Detach )(); private: castor3d::GeometrySPtr m_internal; }; //!\~english Enters the ATL object into the object map, updates the registry and creates an instance of the object \~french Ecrit l'objet ATL dans la table d'objets, met à jour le registre et crée une instance de l'objet OBJECT_ENTRY_AUTO( __uuidof( Geometry ), CGeometry ); DECLARE_VARIABLE_PTR_GETTER( Geometry, castor3d, Geometry ); DECLARE_VARIABLE_PTR_PUTTER( Geometry, castor3d, Geometry ); } #endif
30.361111
221
0.709058
[ "mesh", "geometry", "object" ]
fe811541d2658f816e87aeb698d2cfa64dcb15ab
2,078
cpp
C++
src/execs/update_exec.cpp
farleyknight/PotatoDB
cf8e39a76caf8a66a0182310509756737c624cfa
[ "MIT" ]
3
2021-06-24T01:05:42.000Z
2021-07-23T07:24:16.000Z
src/execs/update_exec.cpp
farleyknight/PotatoDB
cf8e39a76caf8a66a0182310509756737c624cfa
[ "MIT" ]
5
2021-06-25T00:13:51.000Z
2021-07-23T14:26:01.000Z
src/execs/update_exec.cpp
farleyknight/PotatoDB
cf8e39a76caf8a66a0182310509756737c624cfa
[ "MIT" ]
null
null
null
#include "execs/update_exec.hpp" UpdateExec::UpdateExec(ExecCtx& exec_ctx, ptr<UpdatePlan>&& plan, ptr<BaseExec>&& child) : BaseExec (exec_ctx), plan_ (move(plan)), child_ (move(child)) {} const QuerySchema& UpdateExec::schema() { return plan_->schema(); } void UpdateExec::init() { child_->init(); } bool UpdateExec::has_next() { return child_->has_next(); } ValueMap UpdateExec::next_value_map() { const auto &update_values = plan_->update_values(); auto value_map = child_->next_value_map(); const auto &query_schema = exec_ctx_.schema_mgr().query_schema_for(table_oid); for (const auto &[oid, eval_query] : plan_->update_values()) { value_map.emplace(oid, eval_query->eval(value_map, query_schema)); } } Tuple UpdateExec::next_tuple() { auto value_map = child_->next_value_map(); auto rid = value_map.rid(); auto new_tuple = layout.make(value_map, txn()); logger->debug("[UpdateExec] Our tuple has been updated to now be: " + layout.to_string(new_tuple)); table_heap().update_tuple(new_tuple, rid, exec_ctx_.txn()); return new_tuple; } TableHeap& UpdateExec::table_heap() { auto table_oid = plan_->table_oid(); return exec_ctx_.schema_mgr().table_heap_for(table_oid); } Tuple UpdateExec::updated_tuple(const Tuple& old_tuple) { const auto table_oid = plan_->table_oid(); const auto &update_values = plan_->update_values(); const auto &query_schema = exec_ctx_.schema_mgr().query_schema_for(table_oid); vector<Value> values; for (const auto oid : schema().column_oids()) { if (update_values.contains(oid)) { Value new_value = update_values.at(oid)->eval(old_tuple, query_schema); values.emplace_back(new_value); } else { Value new_value = old_tuple.value_by_oid(query_schema, oid); values.emplace_back(new_value); } } auto &layout = schema().layout(); return Tuple(values, layout, exec_ctx().txn()); }
24.447059
71
0.652069
[ "vector" ]
fe84283093c7bbb5e6d7690c165487bbcef18d38
668
cpp
C++
C++/1491.AverageSalaryExcludingTheMinimumAndMaximumSalary.cpp
SSKale1/LeetCode-Solutions
dd6ff16f6af1e96acd036b6e9c2a5cc11f0e330b
[ "MIT" ]
null
null
null
C++/1491.AverageSalaryExcludingTheMinimumAndMaximumSalary.cpp
SSKale1/LeetCode-Solutions
dd6ff16f6af1e96acd036b6e9c2a5cc11f0e330b
[ "MIT" ]
null
null
null
C++/1491.AverageSalaryExcludingTheMinimumAndMaximumSalary.cpp
SSKale1/LeetCode-Solutions
dd6ff16f6af1e96acd036b6e9c2a5cc11f0e330b
[ "MIT" ]
null
null
null
class Solution { public: double average(vector<int>& salary) { int n=salary.size(); //changed long double -> double! double sum=0.0; //sorting the salary array in increasing order sort(begin(salary), end(salary)); //iterating from 2nd element till 2nd last element to store their sum for(int i=1; i<=n-2; i++) { sum = sum + salary[i]; } //dividing the sum by (n-2) to find the average because we did not include the min(1st) and the //max(last) element in the salary array, so total employees = n-2 double avg = sum/(n-2); return avg; } };
26.72
103
0.568862
[ "vector" ]
fe88218b9b9d2f1587af47ba08d52c2d9d9416df
18,456
cpp
C++
src/getpy.cpp
ksob/getpy
8baa4e1062b94e5ea5a8f6fd07ff3fed98887550
[ "MIT" ]
1
2019-11-14T13:10:33.000Z
2019-11-14T13:10:33.000Z
src/getpy.cpp
ksob/getpy
8baa4e1062b94e5ea5a8f6fd07ff3fed98887550
[ "MIT" ]
null
null
null
src/getpy.cpp
ksob/getpy
8baa4e1062b94e5ea5a8f6fd07ff3fed98887550
[ "MIT" ]
2
2020-06-24T05:58:04.000Z
2020-08-03T21:22:53.000Z
#include <pybind11/pybind11.h> #include <pybind11/numpy.h> #include <pybind11/stl.h> namespace py = pybind11; #include <parallel_hashmap/phmap_utils.h> #include <parallel_hashmap/phmap.h> #include <cereal/archives/binary.hpp> #include <cereal/types/utility.hpp> #include <cereal/types/array.hpp> #include <cereal/types/string.hpp> #include <cereal/types/vector.hpp> #include <fstream> #include <iostream> template <typename Key, typename Value> struct Dict { Dict () {} Dict ( Value default_value ) : default_value ( default_value ) {} Dict ( py::array_t<Value> complex_default_value ) { py::buffer_info complex_default_value_buffer = complex_default_value.request(); if ( complex_default_value_buffer.ndim != 1 | complex_default_value_buffer.shape[0] != 1 ) throw std::runtime_error("The default value for complex dtypes must be set with one value."); auto * complex_default_value_ptr = (Value *) complex_default_value_buffer.ptr; default_value = complex_default_value_ptr[0]; } py::array_t<Value> __getitem__ ( py::array_t<Key> & key_array ) { py::buffer_info key_array_buffer = key_array.request(); auto * key_array_ptr = (Key *) key_array_buffer.ptr; auto result_array = py::array_t<Value> ( key_array_buffer.shape[0] ); py::buffer_info result_array_buffer = result_array.request(); auto * result_array_ptr = (Value *) result_array_buffer.ptr; for (size_t idx = 0; idx < key_array_buffer.shape[0]; idx++) { auto search = __dict.find( key_array_ptr[idx] ); if ( search != __dict.end() ) { result_array_ptr[idx] = search->second; } else if ( default_value ) { result_array_ptr[idx] = *default_value; } else { throw std::runtime_error("Key Error: Key not found and default value is not defined."); } } return result_array; } void __setitem__ ( py::array_t<Key> & key_array, py::array_t<Value> & value_array ) { py::buffer_info key_array_buffer = key_array.request(); auto * key_array_ptr = (Key *) key_array_buffer.ptr; py::buffer_info value_array_buffer = value_array.request(); auto * value_array_ptr = (Value *) value_array_buffer.ptr; if (key_array_buffer.shape[0] != value_array_buffer.shape[0]) throw std::runtime_error("The size of the first dimension for the key and value must match."); for (size_t idx = 0; idx < key_array_buffer.shape[0]; idx++) { __dict.insert_or_assign( key_array_ptr[idx], value_array_ptr[idx] ); } } void iadd ( py::array_t<Key> & key_array, py::array_t<Value> & value_array ) { py::buffer_info key_array_buffer = key_array.request(); auto * key_array_ptr = (Key *) key_array_buffer.ptr; py::buffer_info value_array_buffer = value_array.request(); auto * value_array_ptr = (Value *) value_array_buffer.ptr; if (key_array_buffer.shape[0] != value_array_buffer.shape[0]) throw std::runtime_error("The size of the first dimension for the key and value must match."); for (size_t idx = 0; idx < key_array_buffer.shape[0]; idx++) { auto search = __dict.find( key_array_ptr[idx] ); if ( search != __dict.end() ) { search->second += value_array_ptr[idx]; } else if ( default_value ) { Value value = *default_value; value += value_array_ptr[idx]; __dict.insert_or_assign( key_array_ptr[idx], value); } else { throw std::runtime_error("Key Error: Key not found and default value is not defined."); } } } void isub ( py::array_t<Key> & key_array, py::array_t<Value> & value_array ) { py::buffer_info key_array_buffer = key_array.request(); auto * key_array_ptr = (Key *) key_array_buffer.ptr; py::buffer_info value_array_buffer = value_array.request(); auto * value_array_ptr = (Value *) value_array_buffer.ptr; if (key_array_buffer.shape[0] != value_array_buffer.shape[0]) throw std::runtime_error("The size of the first dimension for the key and value must match."); for (size_t idx = 0; idx < key_array_buffer.shape[0]; idx++) { auto search = __dict.find( key_array_ptr[idx] ); if ( search != __dict.end() ) { search->second -= value_array_ptr[idx]; } else if ( default_value ) { Value value = *default_value; value -= value_array_ptr[idx]; __dict.insert_or_assign( key_array_ptr[idx], value); } else { throw std::runtime_error("Key Error: Key not found and default value is not defined."); } } } void ior ( py::array_t<Key> & key_array, py::array_t<Value> & value_array ) { py::buffer_info key_array_buffer = key_array.request(); auto * key_array_ptr = (Key *) key_array_buffer.ptr; py::buffer_info value_array_buffer = value_array.request(); auto * value_array_ptr = (Value *) value_array_buffer.ptr; if (key_array_buffer.shape[0] != value_array_buffer.shape[0]) throw std::runtime_error("The size of the first dimension for the key and value must match."); for (size_t idx = 0; idx < key_array_buffer.shape[0]; idx++) { auto search = __dict.find( key_array_ptr[idx] ); if ( search != __dict.end() ) { search->second |= value_array_ptr[idx]; } else if ( default_value ) { Value value = *default_value; value |= value_array_ptr[idx]; __dict.insert_or_assign( key_array_ptr[idx], value); } else { throw std::runtime_error("Key Error: Key not found and default value is not defined."); } } } void iand ( py::array_t<Key> & key_array, py::array_t<Value> & value_array ) { py::buffer_info key_array_buffer = key_array.request(); auto * key_array_ptr = (Key *) key_array_buffer.ptr; py::buffer_info value_array_buffer = value_array.request(); auto * value_array_ptr = (Value *) value_array_buffer.ptr; if (key_array_buffer.shape[0] != value_array_buffer.shape[0]) throw std::runtime_error("The size of the first dimension for the key and value must match."); for (size_t idx = 0; idx < key_array_buffer.shape[0]; idx++) { auto search = __dict.find( key_array_ptr[idx] ); if ( search != __dict.end() ) { search->second &= value_array_ptr[idx]; } else if ( default_value ) { Value value = *default_value; value &= value_array_ptr[idx]; __dict.insert_or_assign( key_array_ptr[idx], value); } else { throw std::runtime_error("Key Error: Key not found and default value is not defined."); } } } void __delitem__ ( py::array_t<Key> & key_array ) { py::buffer_info key_array_buffer = key_array.request(); auto * key_array_ptr = (Key *) key_array_buffer.ptr; for (size_t idx = 0; idx < key_array_buffer.shape[0]; idx++) __dict.erase( key_array_ptr[idx] ); } py::array_t<bool> contains ( py::array_t<Key> & key_array ) { py::buffer_info key_array_buffer = key_array.request(); auto * key_array_ptr = (Key *) key_array_buffer.ptr; auto result_array = py::array_t<bool>( key_array_buffer.shape[0] ); py::buffer_info result_array_buffer = result_array.request(); auto * result_array_ptr = (bool *) result_array_buffer.ptr; for (size_t idx = 0; idx < key_array_buffer.shape[0]; idx++) { auto search = __dict.find( key_array_ptr[idx] ); if ( search != __dict.end() ) { result_array_ptr[idx] = true; } else { result_array_ptr[idx] = false; } } return result_array; } long __len__ () { return __dict.size(); } py::array_t<Key> keys () { auto result_array = py::array_t<Key>( __dict.size() ); py::buffer_info result_array_buffer = result_array.request(); auto * result_array_ptr = (Key *) result_array_buffer.ptr; size_t idx = 0; for ( auto & key_value : __dict ) { result_array_ptr[idx] = key_value.first; idx++; } return result_array; } py::array_t<Value> values () { auto result_array = py::array_t<Value>( __dict.size() ); py::buffer_info result_array_buffer = result_array.request(); auto * result_array_ptr = (Value *) result_array_buffer.ptr; size_t idx = 0; for ( auto & key_value : __dict ) { result_array_ptr[idx] = key_value.second; idx++; } return result_array; } std::pair<py::array_t<Key>, py::array_t<Value>> items () { auto key_result_array = py::array_t<Key>( __dict.size() ); py::buffer_info key_result_array_buffer = key_result_array.request(); auto * key_result_array_ptr = (Key *) key_result_array_buffer.ptr; auto value_result_array = py::array_t<Value>( __dict.size() ); py::buffer_info value_result_array_buffer = value_result_array.request(); auto * value_result_array_ptr = (Value *) value_result_array_buffer.ptr; size_t idx = 0; for ( auto & key_value : __dict ) { key_result_array_ptr[idx] = key_value.first; value_result_array_ptr[idx] = key_value.second; idx++; } return std::make_pair(key_result_array, value_result_array); } void dump ( const std::string & filename ) { std::ofstream stream ( filename , std::ios::binary ); cereal::BinaryOutputArchive oarchive ( stream ); for ( auto & key_value : __dict ) { oarchive(key_value); } } void load ( const std::string & filename ) { std::ifstream stream ( filename , std::ios::binary); cereal::BinaryInputArchive iarchive ( stream ); std::pair<Key, Value> in_key_value; while ( stream.peek() != EOF ) { iarchive(in_key_value); __dict.emplace(in_key_value.first, in_key_value.second); } } std::optional<Value> default_value; phmap::parallel_flat_hash_map<Key, Value> __dict; }; template <typename Key, typename Value> struct Dict_Without_Bitwise_Operations : Dict<Key, Value> { void ior ( py::array_t<Key> & key_array, py::array_t<Value> & value_array ) { throw std::runtime_error("This dict does not support bitwise operations."); } void iand ( py::array_t<Key> & key_array, py::array_t<Value> & value_array ) { throw std::runtime_error("This dict does not support bitwise operations."); } }; template <typename Key> struct Set { Set () {} void add ( py::array_t<Key> & key_array ) { py::buffer_info key_array_buffer = key_array.request(); auto * key_array_ptr = (Key *) key_array_buffer.ptr; for (size_t idx = 0; idx < key_array_buffer.shape[0]; idx++) { __set.emplace( key_array_ptr[idx] ); } } void discard ( py::array_t<Key> & key_array ) { py::buffer_info key_array_buffer = key_array.request(); auto * key_array_ptr = (Key *) key_array_buffer.ptr; for (size_t idx = 0; idx < key_array_buffer.shape[0]; idx++) __set.erase( key_array_ptr[idx] ); } py::array_t<bool> contains ( py::array_t<Key> & key_array ) { py::buffer_info key_array_buffer = key_array.request(); auto * key_array_ptr = (Key *) key_array_buffer.ptr; auto result_array = py::array_t<bool>( key_array_buffer.shape[0] ); py::buffer_info result_array_buffer = result_array.request(); auto * result_array_ptr = (bool *) result_array_buffer.ptr; for (size_t idx = 0; idx < key_array_buffer.shape[0]; idx++) { auto search = __set.find( key_array_ptr[idx] ); if ( search != __set.end() ) { result_array_ptr[idx] = true; } else { result_array_ptr[idx] = false; } } return result_array; } long __len__ () { return __set.size(); } py::array_t<Key> items () { auto result_array = py::array_t<Key>( __set.size() ); py::buffer_info result_array_buffer = result_array.request(); auto * result_array_ptr = (Key *) result_array_buffer.ptr; size_t idx = 0; for ( auto & key : __set ) { result_array_ptr[idx] = key; idx++; } return result_array; } void dump ( const std::string & filename ) { std::ofstream stream ( filename , std::ios::binary ); cereal::BinaryOutputArchive oarchive ( stream ); for ( auto & key : __set ) { oarchive(key); } } void load ( const std::string & filename ) { std::ifstream stream ( filename , std::ios::binary); cereal::BinaryInputArchive iarchive ( stream ); Key in_key; while ( stream.peek() != EOF ) { iarchive(in_key); __set.emplace(in_key); } } phmap::flat_hash_set<Key> __set; }; template<typename Key, typename Value> void declare_dict(const py::module& m, const std::string& class_name) { using Class = Dict<Key, Value>; py::class_<Class>(m, class_name.c_str()) .def(py::init<>()) .def(py::init<Value &>()) .def(py::init<py::array_t<Value> &>()) .def("__getitem__", &Class::__getitem__) .def("__setitem__", &Class::__setitem__) .def("__delitem__", &Class::__delitem__) .def("contains", &Class::contains) .def("iadd", &Class::iadd) .def("isub", &Class::isub) .def("ior", &Class::ior) .def("iand", &Class::iand) .def("dump", &Class::dump) .def("load", &Class::load) .def("keys", &Class::keys) .def("values", &Class::values) .def("items", &Class::items) // .def("items", [](const Class &c) { return py::make_iterator(c.__dict.begin(), c.__dict.end()); }, py::keep_alive<0, 1>() ) .def("__len__", &Class::__len__); } template<typename Key, typename Value> void declare_dict_without_bitwise_operations(const py::module& m, const std::string& class_name) { using Class = Dict_Without_Bitwise_Operations<Key, Value>; py::class_<Class>(m, class_name.c_str()) .def(py::init<>()) .def(py::init<const Value &>()) .def("__getitem__", &Class::__getitem__) .def("__setitem__", &Class::__setitem__) .def("__delitem__", &Class::__delitem__) .def("contains", &Class::contains) .def("iadd", &Class::iadd) .def("isub", &Class::isub) .def("ior", &Class::ior) .def("iand", &Class::iand) .def("dump", &Class::dump) .def("load", &Class::load) .def("keys", &Class::keys) // .def("items", [](const Class &c) { return py::make_iterator(c.__dict.begin(), c.__dict.end()); }, py::keep_alive<0, 1>() ) .def("__len__", &Class::__len__); } template<typename Key> void declare_set(const py::module& m, const std::string& class_name) { using Class = Set<Key>; py::class_<Class>(m, class_name.c_str()) .def(py::init<>()) .def("add", &Class::add) .def("discard", &Class::discard) .def("contains", &Class::contains) .def("dump", &Class::dump) .def("load", &Class::load) .def("items", &Class::items) // .def("items", [](const Class &c) { return py::make_iterator(c.__set.begin(), c.__set.end()); }, py::keep_alive<0, 1>() ) .def("__len__", &Class::__len__); } template<typename T, size_t N> struct std::hash<std::array<T, N>> { size_t operator () ( const std::array<T, N> & array ) const { size_t seed = N; for(auto& value : array) { seed ^= value + 0x9e3779b9 + (seed << 6) + (seed >> 2); } // phmap::HashState().combine(seed, array); return seed; } }; template<typename T, size_t N> std::array<T, N> & operator += ( std::array<T, N> & a, std::array<T, N> b ) { for (int i = 0 ; i < N ; ++i) { a[i] = a[i] + b[i]; } } template<typename T, size_t N> std::array<T, N> & operator -= ( std::array<T, N> & a, std::array<T, N> b ) { for (int i = 0 ; i < N ; ++i) { a[i] = a[i] - b[i]; } } template<typename T, size_t N> std::array<T, N> & operator |= ( std::array<T, N> & a, std::array<T, N> b ) { for (int i = 0 ; i < N ; ++i) { a[i] = a[i] | b[i]; } } template<typename T, size_t N> std::array<T, N> & operator &= ( std::array<T, N> & a, std::array<T, N> b ) { for (int i = 0 ; i < N ; ++i) { a[i] = a[i] & b[i]; } } template<typename T, size_t N> struct bytearray { std::array<T, N> bytearray; template <class Archive> void serialize( Archive & archive ) { archive( bytearray ); } }; template<typename T, size_t N> struct std::hash<bytearray<T, N>> { size_t operator () ( const bytearray<T, N> & ba ) const { size_t seed = N; for(auto& value : ba.bytearray) { seed ^= value + 0x9e3779b9 + (seed << 6) + (seed >> 2); } // phmap::HashState().combine(seed, ba.bytearray); return seed; } }; template<typename T, size_t N> bool operator == ( const bytearray<T, N> & a, const bytearray<T, N> & b ) { return a.bytearray == b.bytearray; } template<typename T, size_t N> bytearray<T, N> & operator += ( bytearray<T, N> & a, bytearray<T, N> b ) { a.bytearray += b.bytearray; } template<typename T, size_t N> bytearray<T, N> & operator -= ( bytearray<T, N> & a, bytearray<T, N> b ) { a.bytearray -= b.bytearray; } template<typename T, size_t N> bytearray<T, N> & operator |= ( bytearray<T, N> & a, bytearray<T, N> b ) { a.bytearray |= b.bytearray; } template<typename T, size_t N> bytearray<T, N> & operator &= ( bytearray<T, N> & a, bytearray<T, N> b ) { a.bytearray &= b.bytearray; }
31.82069
133
0.588643
[ "shape", "vector" ]
fe885fc32bcfe24775a460c56bf3d288014510c7
1,228
cpp
C++
src/modules/block/models/generator_result.cpp
abelov-spirent/openperf
303b6b5534973ea145a8223a55ee7b65e7464e25
[ "Apache-2.0" ]
null
null
null
src/modules/block/models/generator_result.cpp
abelov-spirent/openperf
303b6b5534973ea145a8223a55ee7b65e7464e25
[ "Apache-2.0" ]
null
null
null
src/modules/block/models/generator_result.cpp
abelov-spirent/openperf
303b6b5534973ea145a8223a55ee7b65e7464e25
[ "Apache-2.0" ]
null
null
null
#include "generator_result.hpp" namespace openperf::block::model { std::string block_generator_result::get_id() const { return m_id; } void block_generator_result::set_id(std::string_view value) { m_id = value; } std::string block_generator_result::get_generator_id() const { return m_generator_id; } void block_generator_result::set_generator_id(std::string_view value) { m_generator_id = value; } bool block_generator_result::is_active() const { return m_active; } void block_generator_result::set_active(bool value) { m_active = value; } time_point block_generator_result::get_timestamp() const { return m_timestamp; } void block_generator_result::set_timestamp(const time_point& value) { m_timestamp = value; } block_generator_statistics block_generator_result::get_read_stats() const { return m_read_stats; } void block_generator_result::set_read_stats( const block_generator_statistics& value) { m_read_stats = value; } block_generator_statistics block_generator_result::get_write_stats() const { return m_write_stats; } void block_generator_result::set_write_stats( const block_generator_statistics& value) { m_write_stats = value; } } // namespace openperf::block::model
23.615385
80
0.78013
[ "model" ]
fe9309c68cf481d75133e6a0f469c9a6e4d9988e
2,333
cpp
C++
vc16/DeepLearning/Annealing.cpp
kiseonjeong/mll-v1.x
43c740c2d621e4b5d846f7ebf6ccd096b299147f
[ "MIT" ]
1
2020-07-05T16:46:19.000Z
2020-07-05T16:46:19.000Z
vc16/DeepLearning/Annealing.cpp
kiseonjeong/MachineLearning-v2.x
43c740c2d621e4b5d846f7ebf6ccd096b299147f
[ "MIT" ]
1
2020-09-28T16:01:35.000Z
2020-09-28T16:14:38.000Z
vc16/DeepLearning/Annealing.cpp
kiseonjeong/mll-v1.x
43c740c2d621e4b5d846f7ebf6ccd096b299147f
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "Annealing.h" namespace mll { annealing::annealing() { // Set an object setObject(); } annealing::annealing(const int cycle, const double k, const antype type) { // Set an object setObject(); // Set the parameters set(cycle, k, type); } annealing::annealing(const annealing& obj) { // Set an object setObject(); // Clone the object *this = obj; } annealing::~annealing() { // Clear the object clearObject(); } annealing& annealing::operator=(const annealing& obj) { // Clear the object clearObject(); // Set an object setObject(); // Copy the object copyObject(obj); return *this; } void annealing::setObject() { // Set the parameters setType(*this); type = ANNEALING_UNKNOWN; cycle = 100; k = 1.0; } void annealing::copyObject(const object& obj) { // Do down casting annealing* _obj = (annealing*)&obj; // Copy the parameters type = _obj->type; cycle = _obj->cycle; k = _obj->k; } void annealing::clearObject() { } void annealing::set(const int cycle, const double k, const antype type) { // Set the parameters this->cycle = cycle; this->k = k; this->type = type; } void annealing::update(const int epoch, optimizer* opt) const { // Check the annealer type if (this->type != ANNEALING_UNKNOWN) { // Check the epoch and the cycle if (epoch != 0 && epoch % cycle == 0) { // Check the optimizer type if (opt->type == OPTIMIZER_ADADELTA) { // Do down casting adadelta* _opt = (adadelta*)opt; // Calculate annealing numem<numat> epsilon = _opt->s; for (int i = 0; i < epsilon.length(); i++) { switch (type) { case ANNEALING_STEP: epsilon(i) = epsilon(i) * k; break; case ANNEALING_EXP: epsilon(i) = epsilon(i) * exp(-k * epoch); break; case ANNEALING_INV: epsilon(i) = epsilon(i) / (1.0 + k * epoch); break; } } // Save the learning rate _opt->s = epsilon; } else { // Calculate annealing switch (type) { case ANNEALING_STEP: opt->epsilon = opt->epsilon * k; break; case ANNEALING_EXP: opt->epsilon = opt->epsilon * exp(-k * epoch); break; case ANNEALING_INV: opt->epsilon = opt->epsilon / (1.0 + k * epoch); break; } } } } } }
18.664
80
0.600514
[ "object" ]
fe9470babbcc332519eaec16291a815f08e43059
2,708
cpp
C++
code/Specjalizacja kontenera/2011B-FileFolder.cpp
irmikrys/Cpp-Exam
35845c0d4e34192d98a6e4705ccef1b6fb3878c7
[ "MIT" ]
null
null
null
code/Specjalizacja kontenera/2011B-FileFolder.cpp
irmikrys/Cpp-Exam
35845c0d4e34192d98a6e4705ccef1b6fb3878c7
[ "MIT" ]
null
null
null
code/Specjalizacja kontenera/2011B-FileFolder.cpp
irmikrys/Cpp-Exam
35845c0d4e34192d98a6e4705ccef1b6fb3878c7
[ "MIT" ]
null
null
null
/*Klasa Folder zawiera dowolna sekwencje obiektow nalezacych do klas File lub Folder. Obiekty wystepuja w dowolnej * kolejnosci i sa roznych typow. Klasa Folder dziedziczy po File. Pliki i katalogi maja nazwe (tekst). Do przechowywa- * nia podobiektow w klasie Folder wykorzystaj wybrany kontener STL. * (a) zadeklaruj i zaimplementuj klasy File i Folder * Dla klasy Folder zaimplementuj * (b) konstruktor kopiujacy * (c) destruktor * (d) operator przypisania */ #include <iostream> #include <vector> using namespace std; class File { public: string name; virtual File* clone()const{ return new File(*this); } File(){} File(const char* n): name(n){} virtual ~File(){} }; class Folder: public File { public: vector<File*> kat; Folder(){} Folder(const char* _n): File(_n){} Folder(const Folder& other){copy(other);} ~Folder(){free();} Folder& operator=(const Folder& other){if(&other != this){free(); copy(other);} return *this;} File* clone()const{ return new Folder(*this); } void add(const File* f){ for(vector<File*>::const_iterator it = kat.begin(); it != kat.end(); it++){ if((*it)->name == f->name) return; } kat.push_back(f->clone()); } friend ostream& operator << (ostream& os, const Folder& f){ os << f.name << ": " << f.kat.size() << endl; for(vector<File*>::const_iterator it = f.kat.begin(); it != f.kat.end(); it++) os << typeid(*(*it)).name() << " " << (*it)->name << endl; os << endl; return os; } protected: void free(){ if(kat.size()){ for(vector<File*>::iterator it = kat.begin(); it != kat.end(); it++) delete *it; kat.erase(kat.begin(), kat.end()); kat.clear(); } } void copy(const Folder& other){ kat.reserve(other.kat.size()); for(vector<File*>::const_iterator it = other.kat.begin(); it != other.kat.end(); it++) add((*it)->clone()); } }; int main() { File f1("cpp"); File f2("jimp.doc"); File f3("doc.txt"); Folder kat1("Home"); Folder kat2("Documents"); Folder kat3("Downloads"); Folder kat4("Photos"); File* kk = kat1.clone(); cout << kk->name << endl << endl; Folder default1("Default1"); default1.add(f1.clone()); default1.add(kat1.clone()); default1.add(kat2.clone()); default1.add(f3.clone()); cout << default1; Folder default2("Default2"); default2.add(f3.clone()); default2.add(f2.clone()); cout << default2; default1 = default2; cout << default1; return 0; }
29.434783
120
0.567947
[ "vector" ]
fe968b4b113c7dbb6a96a00f7b87c5299430dc4b
1,164
cpp
C++
SPTracer/src/SPTracer/Material/Material.cpp
bogoms/sptracer
3593f01c9d5ba040ba87b692e01e4282197e8e66
[ "MIT" ]
2
2018-05-11T10:50:08.000Z
2021-12-13T12:58:03.000Z
SPTracer/src/SPTracer/Material/Material.cpp
sbogomolov/sptracer
3593f01c9d5ba040ba87b692e01e4282197e8e66
[ "MIT" ]
1
2015-05-19T10:57:29.000Z
2015-05-19T10:57:29.000Z
SPTracer/src/SPTracer/Material/Material.cpp
sbogomolov/sptracer
3593f01c9d5ba040ba87b692e01e4282197e8e66
[ "MIT" ]
1
2016-07-30T09:23:51.000Z
2016-07-30T09:23:51.000Z
#include "../stdafx.h" #include "../Tracer/Intersection.h" #include "../Tracer/Ray.h" #include "../Util.h" #include "../Vec3.h" #include "Material.h" namespace SPTracer { void Material::GetNewRayDiffuse(const Ray& ray, const Intersection& intersection, Ray& newRay, std::vector<float>& reflectance) const { // NOTE: Importance sampling. // BDRF is 1/pi * cos(theta), it will be used as PDF // to prefer bright directions. Because the bright // directions are preferred in the choice of samples, // we do not have to weight them again by applying // the BDRF as a scaling factor to reflectance. // Scaling factor in this case is: BDRF/PDF = 1 // z axis static const Vec3 zAxis(0.0f, 0.0f, 1.0f); // generate random ray direction using BDRF as PDF float phi = Util::RandFloat(0.0f, 2.0f * Util::Pi); float cosTheta = std::sqrt(Util::RandFloat(0.0f, 1.0f)); newRay.direction = Vec3::FromPhiTheta(phi, cosTheta).RotateFromTo(zAxis, intersection.normal); // new ray origin is intersection point newRay.origin = intersection.point; // get diffuse reflectance GetDiffuseReflectance(ray, intersection, newRay, reflectance); } }
31.459459
134
0.707045
[ "vector" ]
fe9830b8b50c3355f234adc5b9bb895ce6038ffb
5,486
hxx
C++
include/z5/factory.hxx
vharron/z5
ad0a925219f9adb8d58137951e364b866df2e1d7
[ "MIT" ]
null
null
null
include/z5/factory.hxx
vharron/z5
ad0a925219f9adb8d58137951e364b866df2e1d7
[ "MIT" ]
null
null
null
include/z5/factory.hxx
vharron/z5
ad0a925219f9adb8d58137951e364b866df2e1d7
[ "MIT" ]
null
null
null
#pragma once #include "z5/filesystem/factory.hxx" #ifdef WITH_S3 #include "z5/s3/factory.hxx" #endif #ifdef WITH_GCS #include "z5/gcs/factory.hxx" #endif namespace z5 { template<class GROUP> inline std::unique_ptr<Dataset> openDataset(const handle::Group<GROUP> & root, const std::string & key) { // check if this is a s3 group #ifdef WITH_S3 if(root.isS3()) { s3::handle::Dataset ds(root, key); return s3::openDataset(ds); } #endif #ifdef WITH_GCS if(root.isGcs()) { gcs::handle::Dataset ds(root, key); return gcs::openDataset(ds); } #endif filesystem::handle::Dataset ds(root, key); return filesystem::openDataset(ds); } template<class GROUP> inline std::unique_ptr<Dataset> createDataset( const handle::Group<GROUP> & root, const std::string & key, const DatasetMetadata & metadata ) { #ifdef WITH_S3 if(root.isS3()) { s3::handle::Dataset ds(root, key); return s3::createDataset(ds, metadata); } #endif #ifdef WITH_GCS if(root.isGcs()) { gcs::handle::Dataset ds(root, key); return gcs::createDataset(ds, metadata); } #endif filesystem::handle::Dataset ds(root, key); return filesystem::createDataset(ds, metadata); } template<class GROUP> inline std::unique_ptr<Dataset> createDataset( const handle::Group<GROUP> & root, const std::string & key, const std::string & dtype, const types::ShapeType & shape, const types::ShapeType & chunkShape, const std::string & compressor="raw", const types::CompressionOptions & compressionOptions=types::CompressionOptions(), const double fillValue=0 ) { DatasetMetadata metadata; createDatasetMetadata(dtype, shape, chunkShape, root.isZarr(), compressor, compressionOptions, fillValue, metadata); #ifdef WITH_S3 if(root.isS3()) { s3::handle::Dataset ds(root, key); return s3::createDataset(ds, metadata); } #endif #ifdef WITH_GCS if(root.isGcs()) { gcs::handle::Dataset ds(root, key); return gcs::createDataset(ds, metadata); } #endif filesystem::handle::Dataset ds(root, key); return filesystem::createDataset(ds, metadata); } // dataset creation from json, because wrapping the CompressionOptions type // to python is very brittle template<class GROUP> inline std::unique_ptr<Dataset> createDataset( const handle::Group<GROUP> & root, const std::string & key, const std::string & dtype, const types::ShapeType & shape, const types::ShapeType & chunkShape, const std::string & compressor, const nlohmann::json & compressionOptions, const double fillValue=0 ) { types::Compressor internalCompressor; try { internalCompressor = types::Compressors::stringToCompressor().at(compressor); } catch(const std::out_of_range & e) { throw std::runtime_error("z5::createDataset: Invalid compressor for dataset"); } types::CompressionOptions cOpts; types::jsonToCompressionType(compressionOptions, cOpts); return createDataset(root, key, dtype, shape, chunkShape, compressor, cOpts, fillValue); } template<class GROUP> inline void createFile(const handle::File<GROUP> & file, const bool isZarr) { #ifdef WITH_S3 if(file.isS3()) { s3::createFile(file, isZarr); return; } #endif #ifdef WITH_GCS if(file.isGcs()) { gcs::createFile(file, isZarr); return; } #endif filesystem::createFile(file, isZarr); } template<class GROUP> inline void createGroup(const handle::Group<GROUP> & root, const std::string & key) { #ifdef WITH_S3 if(root.isS3()) { s3::handle::Group newGroup(root, key); s3::createGroup(newGroup, root.isZarr()); return; } #endif #ifdef WITH_GCS if(root.isGcs()) { gcs::handle::Group newGroup(root, key); gcs::createGroup(newGroup, root.isZarr()); return; } #endif filesystem::handle::Group newGroup(root, key); filesystem::createGroup(newGroup, root.isZarr()); } template<class GROUP1, class GROUP2> inline std::string relativePath(const handle::Group<GROUP1> & g1, const GROUP2 & g2) { #ifdef WITH_S3 if(g1.isS3()) { if(!g2.isS3()) { throw std::runtime_error("Can't get relative path of different backends."); } return s3::relativePath(g1, g2); } #endif #ifdef WITH_GCS if(g1.isGcs()) { if(!g2.isGcs()) { throw std::runtime_error("Can't get relative path of different backends."); } throw new std::logic_error("Not implemented"); } #endif return filesystem::relativePath(g1, g2); } }
29.336898
96
0.560518
[ "shape" ]
fe9c8bf3d5047062067daf2562e353cdd9db474e
28,969
cc
C++
L1Trigger/L1TMuonBayes/src/Omtf/XMLConfigWriter.cc
thesps/cmssw
ad5315934948ce96699b29cc1d5b03a59f99634f
[ "Apache-2.0" ]
null
null
null
L1Trigger/L1TMuonBayes/src/Omtf/XMLConfigWriter.cc
thesps/cmssw
ad5315934948ce96699b29cc1d5b03a59f99634f
[ "Apache-2.0" ]
null
null
null
L1Trigger/L1TMuonBayes/src/Omtf/XMLConfigWriter.cc
thesps/cmssw
ad5315934948ce96699b29cc1d5b03a59f99634f
[ "Apache-2.0" ]
null
null
null
#include <L1Trigger/L1TMuonBayes/interface/Omtf/AlgoMuon.h> #include <L1Trigger/L1TMuonBayes/interface/Omtf/GoldenPattern.h> #include <L1Trigger/L1TMuonBayes/interface/Omtf/GoldenPatternResult.h> #include <L1Trigger/L1TMuonBayes/interface/Omtf/GoldenPatternWithStat.h> #include "FWCore/Framework/interface/Event.h" #include <L1Trigger/L1TMuonBayes/interface/Omtf/OMTFConfiguration.h> #include <L1Trigger/L1TMuonBayes/interface/Omtf/OMTFinput.h> #include <L1Trigger/L1TMuonBayes/interface/Omtf/XMLConfigWriter.h> #include "DataFormats/L1TMuon/interface/RegionalMuonCand.h" #include <iostream> #include <sstream> #include <cmath> #include <ctime> #include <iomanip> #include <bitset> #include "xercesc/framework/StdOutFormatTarget.hpp" #include "xercesc/framework/LocalFileFormatTarget.hpp" #include "xercesc/parsers/XercesDOMParser.hpp" #include "xercesc/dom/DOM.hpp" #include "xercesc/dom/DOMException.hpp" #include "xercesc/dom/DOMImplementation.hpp" #include "xercesc/sax/HandlerBase.hpp" #include "xercesc/util/XMLString.hpp" #include "xercesc/util/PlatformUtils.hpp" #include "xercesc/util/XercesDefs.hpp" #include "xercesc/util/XercesVersion.hpp" XERCES_CPP_NAMESPACE_USE #if _XERCES_VERSION <30100 #include "xercesc/dom/DOMWriter.hpp" #else #include "xercesc/dom/DOMLSSerializer.hpp" #include "xercesc/dom/DOMLSOutput.hpp" #endif // namespace { unsigned int eta2Bits(unsigned int eta) { if (eta== 73) return 0b100000000; else if (eta== 78) return 0b010000000; else if (eta== 85) return 0b001000000; else if (eta== 90) return 0b000100000; else if (eta== 94) return 0b000010000; else if (eta== 99) return 0b000001000; else if (eta==103) return 0b000000100; else if (eta==110) return 0b000000010; else if (eta== 75) return 0b110000000; else if (eta== 79) return 0b011000000; else if (eta== 92) return 0b000110000; else if (eta==115) return 0b000000001; else if (eta==121) return 0b000000000; else return 0b111111111; ; } } ////////////////////////////////// // XMLConfigWriter ////////////////////////////////// inline std::string _toString(XMLCh const* toTranscode) { std::string tmp(xercesc::XMLString::transcode(toTranscode)); return tmp; } inline XMLCh* _toDOMS(std::string temp) { XMLCh* buff = XMLString::transcode(temp.c_str()); return buff; } //////////////////////////////////// //////////////////////////////////// XMLConfigWriter::XMLConfigWriter(const OMTFConfiguration* aOMTFConfig, bool writePdfThresholds, bool writeMeanDistPhi1): writePdfThresholds(writePdfThresholds), writeMeanDistPhi1(writeMeanDistPhi1) { XMLPlatformUtils::Initialize(); ///Initialise XML document domImpl = DOMImplementationRegistry::getDOMImplementation(_toDOMS("Range")); myOMTFConfig = aOMTFConfig; } ////////////////////////////////////////////////// ////////////////////////////////////////////////// void XMLConfigWriter::initialiseXMLDocument(const std::string & docName){ theDoc = domImpl->createDocument(nullptr,_toDOMS(docName), nullptr); theTopElement = theDoc->getDocumentElement(); unsigned int version = myOMTFConfig->patternsVersion(); unsigned int mask16bits = 0xFFFF; version &=mask16bits; std::ostringstream stringStr; stringStr.str(""); stringStr<<"0x"<<std::hex<<std::setfill('0')<<std::setw(4)<<version; theTopElement->setAttribute(_toDOMS("version"), _toDOMS(stringStr.str())); } ////////////////////////////////////////////////// ////////////////////////////////////////////////// void XMLConfigWriter::finaliseXMLDocument(const std::string & fName){ XMLFormatTarget* formTarget = new LocalFileFormatTarget(fName.c_str()); #if _XERCES_VERSION <30100 xercesc::DOMWriter* domWriter = (dynamic_cast<DOMImplementation*>(domImpl))->createDOMWriter(); if(domWriter->canSetFeature(XMLUni::fgDOMWRTFormatPrettyPrint, true)){ domWriter->setFeature(XMLUni::fgDOMWRTFormatPrettyPrint, true); } domWriter->writeNode(formTarget,*theTopElement); #else xercesc::DOMLSSerializer* theSerializer = (dynamic_cast<DOMImplementation*>(domImpl))->createLSSerializer(); if (theSerializer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true)) theSerializer->getDomConfig()->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true); DOMLSOutput* theOutput = (dynamic_cast<DOMImplementation*>(domImpl))->createLSOutput(); theOutput->setByteStream(formTarget); theSerializer->write(theTopElement, theOutput); theOutput->release(); theSerializer->release(); #endif delete formTarget; } ////////////////////////////////////////////////// ////////////////////////////////////////////////// xercesc::DOMElement * XMLConfigWriter::writeEventHeader(unsigned int eventId, unsigned int mixedEventId){ unsigned int eventBx = eventId*2; xercesc::DOMElement *aEvent = nullptr; xercesc::DOMElement *aBx = nullptr; std::ostringstream stringStr; aEvent = theDoc->createElement(_toDOMS("Event")); stringStr.str(""); stringStr<<eventId; aEvent->setAttribute(_toDOMS("iEvent"), _toDOMS(stringStr.str())); stringStr.str(""); stringStr<<mixedEventId; aEvent->setAttribute(_toDOMS("iMixedEvent"), _toDOMS(stringStr.str())); aBx = theDoc->createElement(_toDOMS("bx")); stringStr.str(""); stringStr<<eventBx; aBx->setAttribute(_toDOMS("iBx"), _toDOMS(stringStr.str())); aEvent->appendChild(aBx); theTopElement->appendChild(aEvent); return aBx; } ////////////////////////////////////////////////// ////////////////////////////////////////////////// xercesc::DOMElement * XMLConfigWriter::writeEventData(xercesc::DOMElement *aTopElement, const OmtfName & board, const OMTFinput & aInput){ std::ostringstream stringStr; xercesc::DOMElement *aProcessor = theDoc->createElement(_toDOMS("Processor")); aProcessor->setAttribute(_toDOMS("board"), _toDOMS(board.name()) ); unsigned int iProcessor = board.processor(); stringStr.str(""); stringStr<<iProcessor; aProcessor->setAttribute(_toDOMS("iProcessor"), _toDOMS(stringStr.str())); stringStr.str(""); if (board.position()==1) stringStr<<"+"; stringStr<<board.position(); aProcessor->setAttribute(_toDOMS("position"), _toDOMS(stringStr.str())); xercesc::DOMElement *aLayer, *aHit; for(unsigned int iLayer=0;iLayer<myOMTFConfig->nLayers();++iLayer){ aLayer = theDoc->createElement(_toDOMS("Layer")); stringStr.str(""); stringStr<<iLayer; aLayer->setAttribute(_toDOMS("iLayer"), _toDOMS(stringStr.str())); for(unsigned int iHit=0; iHit < aInput.getMuonStubs()[iLayer].size(); ++iHit) { int hitPhi = aInput.getPhiHw(iLayer, iHit); if(hitPhi >= (int)myOMTFConfig->nPhiBins()) continue; aHit = theDoc->createElement(_toDOMS("Hit")); stringStr.str(""); stringStr<<iHit; aHit->setAttribute(_toDOMS("iInput"), _toDOMS(stringStr.str())); stringStr.str(""); stringStr<<hitPhi; aHit->setAttribute(_toDOMS("iPhi"), _toDOMS(stringStr.str())); stringStr.str(""); stringStr<<eta2Bits(abs(aInput.getHitEta(iLayer, iHit))); aHit->setAttribute(_toDOMS("iEta"), _toDOMS(stringStr.str())); aLayer->appendChild(aHit); } if(aLayer->getChildNodes()->getLength()) aProcessor->appendChild(aLayer); } aTopElement->appendChild(aProcessor); return aProcessor; } ////////////////////////////////////////////////// ////////////////////////////////////////////////// void XMLConfigWriter::writeAlgoMuon(xercesc::DOMElement *aTopElement, const AlgoMuon & aCand){ xercesc::DOMElement* aResult = theDoc->createElement(_toDOMS("AlgoMuon")); std::ostringstream stringStr; stringStr.str(""); stringStr<<aCand.getRefHitNumber(); aResult->setAttribute(_toDOMS("iRefHit"),_toDOMS(stringStr.str())); stringStr.str(""); stringStr<<aCand.getPt(); aResult->setAttribute(_toDOMS("ptCode"),_toDOMS(stringStr.str())); stringStr.str(""); stringStr<<aCand.getPhi(); aResult->setAttribute(_toDOMS("phiCode"),_toDOMS(stringStr.str())); stringStr.str(""); stringStr<<eta2Bits(abs(aCand.getEtaHw())); aResult->setAttribute(_toDOMS("etaCode"),_toDOMS(stringStr.str())); stringStr.str(""); stringStr<<aCand.getCharge(); aResult->setAttribute(_toDOMS("charge"),_toDOMS(stringStr.str())); stringStr.str(""); stringStr<<aCand.getQ(); aResult->setAttribute(_toDOMS("nHits"), _toDOMS(stringStr.str())); stringStr.str(""); stringStr<<aCand.getDisc(); aResult->setAttribute(_toDOMS("disc"), _toDOMS(stringStr.str())); stringStr.str(""); stringStr<<aCand.getRefLayer(); aResult->setAttribute(_toDOMS("iRefLayer"), _toDOMS(stringStr.str())); stringStr.str(""); stringStr<<std::bitset<18>(aCand.getFiredLayerBits()); aResult->setAttribute(_toDOMS("layers"),_toDOMS(stringStr.str())); stringStr.str(""); stringStr<<aCand.getPhiRHit(); aResult->setAttribute(_toDOMS("phiRHit"),_toDOMS(stringStr.str())); stringStr.str(""); stringStr<<aCand.getPatternNumber(); aResult->setAttribute(_toDOMS("patNum"),_toDOMS(stringStr.str())); aTopElement->appendChild(aResult); } ////////////////////////////////////////////////// ////////////////////////////////////////////////// void XMLConfigWriter::writeCandMuon(xercesc::DOMElement *aTopElement, const l1t::RegionalMuonCand& aCand){ xercesc::DOMElement* aResult = theDoc->createElement(_toDOMS("CandMuon")); std::ostringstream stringStr; stringStr.str(""); stringStr<<aCand.hwPt(); aResult->setAttribute(_toDOMS("hwPt"),_toDOMS(stringStr.str())); stringStr.str(""); stringStr<<aCand.hwPhi(); aResult->setAttribute(_toDOMS("hwPhi"),_toDOMS(stringStr.str())); stringStr.str(""); stringStr<<aCand.hwEta(); aResult->setAttribute(_toDOMS("hwEta"),_toDOMS(stringStr.str())); stringStr.str(""); stringStr<<aCand.hwSign(); aResult->setAttribute(_toDOMS("hwSign"),_toDOMS(stringStr.str())); stringStr.str(""); stringStr<<aCand.hwSignValid(); aResult->setAttribute(_toDOMS("hwSignValid"),_toDOMS(stringStr.str())); stringStr.str(""); stringStr<<aCand.hwQual(); aResult->setAttribute(_toDOMS("hwQual"), _toDOMS(stringStr.str())); stringStr.str(""); std::map<int, int> hwAddrMap = aCand.trackAddress(); stringStr<<std::bitset<29>(hwAddrMap[0]); aResult->setAttribute(_toDOMS("hwTrackAddress"), _toDOMS(stringStr.str())); stringStr.str(""); stringStr<<aCand.link(); aResult->setAttribute(_toDOMS("link"), _toDOMS(stringStr.str())); stringStr.str(""); stringStr<<aCand.processor(); aResult->setAttribute(_toDOMS("processor"), _toDOMS(stringStr.str())); stringStr.str(""); if (aCand.trackFinderType() == l1t::omtf_neg) stringStr<<"OMTF_NEG"; else if (aCand.trackFinderType() == l1t::omtf_pos) stringStr<<"OMTF_POS"; else stringStr<<aCand.trackFinderType(); aResult->setAttribute(_toDOMS("trackFinderType"), _toDOMS(stringStr.str())); aTopElement->appendChild(aResult); } ////////////////////////////////////////////////// ////////////////////////////////////////////////// ////////////////////////////////////////////////// ////////////////////////////////////////////////// void XMLConfigWriter::writeResultsData(xercesc::DOMElement *aTopElement, unsigned int iRegion, const Key & aKey, const GoldenPatternResult & aResult){ std::ostringstream stringStr; ///Write GP key parameters xercesc::DOMElement* aGP = theDoc->createElement(_toDOMS("GP")); stringStr.str(""); stringStr<<aKey.thePt; aGP->setAttribute(_toDOMS("iPt"), _toDOMS(stringStr.str())); stringStr.str(""); stringStr<<aKey.theEtaCode; aGP->setAttribute(_toDOMS("iEta"), _toDOMS(stringStr.str())); stringStr.str(""); stringStr<<"0"; aGP->setAttribute(_toDOMS("iPhi"), _toDOMS(stringStr.str())); stringStr.str(""); stringStr<<aKey.theCharge; aGP->setAttribute(_toDOMS("iCharge"), _toDOMS(stringStr.str())); ///////////////// ///Write results details for this GP { xercesc::DOMElement* aRefLayer = theDoc->createElement(_toDOMS("Result")); stringStr.str(""); stringStr<<aResult.getRefLayer(); aRefLayer->setAttribute(_toDOMS("iRefLayer"), _toDOMS(stringStr.str())); stringStr.str(""); stringStr<<iRegion; aRefLayer->setAttribute(_toDOMS("iRegion"), _toDOMS(stringStr.str())); stringStr.str(""); stringStr<<myOMTFConfig->getRefToLogicNumber()[aResult.getRefLayer()]; aRefLayer->setAttribute(_toDOMS("iLogicLayer"), _toDOMS(stringStr.str())); for(unsigned int iLogicLayer=0;iLogicLayer<myOMTFConfig->nLayers();++iLogicLayer){ xercesc::DOMElement* aLayer = theDoc->createElement(_toDOMS("Layer")); stringStr.str(""); stringStr<<iLogicLayer; aLayer->setAttribute(_toDOMS("iLayer"), _toDOMS(stringStr.str())); stringStr.str(""); stringStr<<aResult.getStubResults()[iLogicLayer].getPdfVal(); aLayer->setAttribute(_toDOMS("value"), _toDOMS(stringStr.str())); if(aResult.getStubResults()[iLogicLayer].getPdfVal()) aRefLayer->appendChild(aLayer); } if(aRefLayer->getChildNodes()->getLength()) aGP->appendChild(aRefLayer); } if(aGP->getChildNodes()->getLength()) aTopElement->appendChild(aGP); } ////////////////////////////////////////////////// ////////////////////////////////////////////////// void XMLConfigWriter::writeGPData(const GoldenPattern & aGP){ std::ostringstream stringStr; xercesc::DOMElement *aLayer=nullptr, *aRefLayer=nullptr, *aPdf=nullptr; xercesc::DOMElement* aGPElement = theDoc->createElement(_toDOMS("GP")); stringStr.str(""); stringStr<<aGP.key().thePt; aGPElement->setAttribute(_toDOMS("iPt"), _toDOMS(stringStr.str())); stringStr.str(""); //stringStr<<aGP.key().theEtaCode; stringStr<<"0";//No eta code at the moment aGPElement->setAttribute(_toDOMS("iEta"), _toDOMS(stringStr.str())); stringStr.str(""); stringStr<<0; //No phi code is assigned to GP for the moment. aGPElement->setAttribute(_toDOMS("iPhi"), _toDOMS(stringStr.str())); stringStr.str(""); stringStr<<aGP.key().theCharge; aGPElement->setAttribute(_toDOMS("iCharge"), _toDOMS(stringStr.str())); for(unsigned int iLayer = 0;iLayer<myOMTFConfig->nLayers();++iLayer){ int nOfPhis = 0; ///////////////////////////////////// aLayer = theDoc->createElement(_toDOMS("Layer")); stringStr.str(""); stringStr<<iLayer; ////////////////////////////////// aLayer->setAttribute(_toDOMS("iLayer"), _toDOMS(stringStr.str())); stringStr.str(""); stringStr<<nOfPhis; aLayer->setAttribute(_toDOMS("nOfPhis"), _toDOMS(stringStr.str())); for(unsigned int iRefLayer=0;iRefLayer<myOMTFConfig->nRefLayers();++iRefLayer){ aRefLayer = theDoc->createElement(_toDOMS("RefLayer")); int meanDistPhi0 = aGP.getMeanDistPhi()[iLayer][iRefLayer][0]; stringStr.str(""); stringStr<<meanDistPhi0; aRefLayer->setAttribute(_toDOMS("meanDistPhi0"), _toDOMS(stringStr.str())); int meanDistPhi1 = aGP.getMeanDistPhi()[iLayer][iRefLayer][1]; stringStr.str(""); stringStr<<meanDistPhi1; aRefLayer->setAttribute(_toDOMS("meanDistPhi1"), _toDOMS(stringStr.str())); int selDistPhi = 0; stringStr.str(""); stringStr<<selDistPhi; aRefLayer->setAttribute(_toDOMS("selDistPhi"), _toDOMS(stringStr.str())); int selDistPhiShift = aGP.getDistPhiBitShift(iLayer, iRefLayer); //TODO check if Wojtek expects it here or on the distMsbPhiShift stringStr.str(""); stringStr<<selDistPhiShift; aRefLayer->setAttribute(_toDOMS("selDistPhiShift"), _toDOMS(stringStr.str())); int distMsbPhiShift = 0; stringStr.str(""); stringStr<<distMsbPhiShift; aRefLayer->setAttribute(_toDOMS("distMsbPhiShift"), _toDOMS(stringStr.str())); aLayer->appendChild(aRefLayer); } for(unsigned int iRefLayer=0;iRefLayer<myOMTFConfig->nRefLayers();++iRefLayer){ for(unsigned int iPdf=0;iPdf<exp2(myOMTFConfig->nPdfAddrBits());++iPdf){ aPdf = theDoc->createElement(_toDOMS("PDF")); stringStr.str(""); stringStr<<aGP.pdfValue(iLayer,iRefLayer,iPdf); aPdf->setAttribute(_toDOMS("value"), _toDOMS(stringStr.str())); aLayer->appendChild(aPdf); } } aGPElement->appendChild(aLayer); } theTopElement->appendChild(aGPElement); } ////////////////////////////////////////////////// ////////////////////////////////////////////////// void XMLConfigWriter::writeGPData(const GoldenPattern* aGP1, const GoldenPattern* aGP2, const GoldenPattern* aGP3, const GoldenPattern* aGP4){ std::ostringstream stringStr; auto setAttributeInt = [&](xercesc::DOMElement* domElement, std::string name, int value)->void { stringStr<<value; domElement->setAttribute(_toDOMS(name), _toDOMS(stringStr.str())); stringStr.str(""); }; auto setAttributeFloat = [&](xercesc::DOMElement* domElement, std::string name, float value)->void { stringStr<<value; domElement->setAttribute(_toDOMS(name), _toDOMS(stringStr.str())); stringStr.str(""); }; //xercesc::DOMElement *aLayer=nullptr, *aRefLayer=nullptr, *aPdf=nullptr; xercesc::DOMElement* aGPElement = theDoc->createElement(_toDOMS("GP")); setAttributeInt(aGPElement, "iPt1", aGP1->key().thePt); setAttributeInt(aGPElement, "iPt2", aGP2->key().thePt); setAttributeInt(aGPElement, "iPt3", aGP3->key().thePt); setAttributeInt(aGPElement, "iPt4", aGP4->key().thePt); if(writePdfThresholds) { if(dynamic_cast<const GoldenPatternWithThresh*>(aGP1) != 0) { for(unsigned int iRefLayer=0;iRefLayer<myOMTFConfig->nRefLayers();++iRefLayer){ //cout<<__FUNCTION__<<":"<<__LINE__<<std::endl; xercesc::DOMElement* aRefLayerThresh = theDoc->createElement(_toDOMS("RefLayerThresh")); setAttributeFloat(aRefLayerThresh, "tresh1", dynamic_cast<const GoldenPatternWithThresh*>(aGP1)->getThreshold(iRefLayer)); setAttributeFloat(aRefLayerThresh, "tresh2", dynamic_cast<const GoldenPatternWithThresh*>(aGP2)->getThreshold(iRefLayer)); setAttributeFloat(aRefLayerThresh, "tresh3", dynamic_cast<const GoldenPatternWithThresh*>(aGP3)->getThreshold(iRefLayer)); setAttributeFloat(aRefLayerThresh, "tresh4", dynamic_cast<const GoldenPatternWithThresh*>(aGP4)->getThreshold(iRefLayer)); aGPElement->appendChild(aRefLayerThresh); } } } setAttributeInt(aGPElement, "iEta", 0); //aGP1.key().theEtaCode; //No eta code at the moment setAttributeInt(aGPElement, "iPhi", 0); //No phi code is assigned to GP for the moment. setAttributeInt(aGPElement, "iCharge", aGP1->key().theCharge); for(unsigned int iLayer = 0;iLayer<myOMTFConfig->nLayers();++iLayer){ int nOfPhis = 0; ///////////////////////////////////// xercesc::DOMElement* aLayer = theDoc->createElement(_toDOMS("Layer")); setAttributeInt(aLayer, "iLayer", iLayer); setAttributeInt(aLayer, "nOfPhis", nOfPhis); for(unsigned int iRefLayer=0;iRefLayer<myOMTFConfig->nRefLayers();++iRefLayer){ xercesc::DOMElement* aRefLayer = theDoc->createElement(_toDOMS("RefLayer")); if(writeMeanDistPhi1) { int meanDistPhi0 = aGP1->getMeanDistPhi()[iLayer][iRefLayer][0]; setAttributeInt(aRefLayer, "meanDistPhi0", meanDistPhi0); int meanDistPhi1 = aGP1->getMeanDistPhi()[iLayer][iRefLayer][1]; setAttributeInt(aRefLayer, "meanDistPhi1", meanDistPhi1); } else { int meanDistPhi = aGP1->getMeanDistPhi()[iLayer][iRefLayer][0]; setAttributeInt(aRefLayer, "meanDistPhi", meanDistPhi); } int selDistPhi = 0; setAttributeInt(aRefLayer, "selDistPhi", selDistPhi); int selDistPhiShift = aGP1->getDistPhiBitShift(iLayer, iRefLayer); //TODO check if Wojtek expects it here or on the distMsbPhiShift; setAttributeInt(aRefLayer, "selDistPhiShift", selDistPhiShift); int distMsbPhiShift = 0; setAttributeInt(aRefLayer, "distMsbPhiShift", distMsbPhiShift); aLayer->appendChild(aRefLayer); } for(unsigned int iRefLayer=0;iRefLayer<myOMTFConfig->nRefLayers();++iRefLayer){ for(unsigned int iPdf=0; iPdf < exp2(myOMTFConfig->nPdfAddrBits()); ++iPdf){ xercesc::DOMElement* aPdf = theDoc->createElement(_toDOMS("PDF")); setAttributeFloat(aPdf, "value1", aGP1->pdfValue(iLayer,iRefLayer,iPdf)); setAttributeFloat(aPdf, "value2", aGP2->pdfValue(iLayer,iRefLayer,iPdf)); setAttributeFloat(aPdf, "value3", aGP3->pdfValue(iLayer,iRefLayer,iPdf)); setAttributeFloat(aPdf, "value4", aGP4->pdfValue(iLayer,iRefLayer,iPdf)); aLayer->appendChild(aPdf); } } aGPElement->appendChild(aLayer); } theTopElement->appendChild(aGPElement); } ////////////////////////////////////////////////// ////////////////////////////////////////////////// template <class GoldenPatternType> void XMLConfigWriter::writeGPs(const std::vector<std::shared_ptr<GoldenPatternType> >& goldenPats, std::string fName ) { initialiseXMLDocument("OMTF"); GoldenPattern* dummy = new GoldenPatternWithThresh(Key(0,0,0), myOMTFConfig); OMTFConfiguration::vector2D mergedPartters = myOMTFConfig->getMergedPatterns(goldenPats); for(unsigned int iGroup = 0; iGroup < mergedPartters.size(); iGroup++) { std::vector<GoldenPattern*> gps(4, dummy); for(unsigned int i = 0; i < mergedPartters[iGroup].size(); i++) { GoldenPattern* gp = dynamic_cast<GoldenPattern*> (goldenPats.at(mergedPartters[iGroup][i]).get() ); if(!gp) { throw cms::Exception("OMTF::XMLConfigWriter::writeGPs: the gps are not GoldenPatterns "); } /*cout<<gp->key()<<endl;; for(unsigned int iLayer = 0; iLayer<myOMTFConfig->nLayers(); ++iLayer) { for(unsigned int iRefLayer=0; iRefLayer<myOMTFConfig->nRefLayers(); ++iRefLayer) { if(gp->getPdf()[iLayer][iRefLayer][0] != 0) { cout<<"iLayer "<<iLayer<<" iRefLayer "<<iRefLayer<<" pdf[0] "<<gp->getPdf()[iLayer][iRefLayer][0]<<"!!!!!!!!!!!!!!!!!!!!\n"; } } }*/ gps[i] = gp; } writeGPData(gps[0], gps[1], gps[2], gps[3]); } finaliseXMLDocument(fName); } ////////////////////////////////////////////////// ////////////////////////////////////////////////// void XMLConfigWriter::writeConnectionsData(const std::vector<std::vector <OMTFConfiguration::vector2D> > & measurements4D){ std::ostringstream stringStr; for(unsigned int iProcessor=0;iProcessor<6;++iProcessor){ xercesc::DOMElement* aProcessorElement = theDoc->createElement(_toDOMS("Processor")); stringStr.str(""); stringStr<<iProcessor; aProcessorElement->setAttribute(_toDOMS("iProcessor"), _toDOMS(stringStr.str())); for(unsigned int iRefLayer=0;iRefLayer<myOMTFConfig->nRefLayers();++iRefLayer){ xercesc::DOMElement* aRefLayerElement = theDoc->createElement(_toDOMS("RefLayer")); stringStr.str(""); stringStr<<iRefLayer; aRefLayerElement->setAttribute(_toDOMS("iRefLayer"), _toDOMS(stringStr.str())); stringStr.str(""); stringStr<<myOMTFConfig->getProcessorPhiVsRefLayer()[iProcessor][iRefLayer]; aRefLayerElement->setAttribute(_toDOMS("iGlobalPhiStart"), _toDOMS(stringStr.str())); aProcessorElement->appendChild(aRefLayerElement); } unsigned int iRefHit = 0; /////// for(unsigned int iRefLayer=0;iRefLayer<myOMTFConfig->nRefLayers();++iRefLayer){ for(unsigned int iRegion=0;iRegion<6;++iRegion){ unsigned int maxHitCount = 0; for(unsigned int iInput=0;iInput<14;++iInput) { if((int)maxHitCount<myOMTFConfig->getMeasurements4Dref()[iProcessor][iRegion][iRefLayer][iInput]) maxHitCount = myOMTFConfig->getMeasurements4Dref()[iProcessor][iRegion][iRefLayer][iInput]; } for(unsigned int iInput=0;iInput<14;++iInput){ unsigned int hitCount = myOMTFConfig->getMeasurements4Dref()[iProcessor][iRegion][iRefLayer][iInput]; if(hitCount<maxHitCount*0.1) continue; xercesc::DOMElement* aRefHitElement = theDoc->createElement(_toDOMS("RefHit")); stringStr.str(""); stringStr<<iRefHit; aRefHitElement->setAttribute(_toDOMS("iRefHit"), _toDOMS(stringStr.str())); stringStr.str(""); stringStr<<iRefLayer; aRefHitElement->setAttribute(_toDOMS("iRefLayer"), _toDOMS(stringStr.str())); stringStr.str(""); stringStr<<iRegion; aRefHitElement->setAttribute(_toDOMS("iRegion"), _toDOMS(stringStr.str())); stringStr.str(""); stringStr<<iInput; aRefHitElement->setAttribute(_toDOMS("iInput"), _toDOMS(stringStr.str())); unsigned int logicRegionSize = 10/360.0*myOMTFConfig->nPhiBins(); int lowScaleEnd = std::pow(2,myOMTFConfig->nPhiBits()-1); ///iPhiMin and iPhiMax are expressed in n bit scale -2**n, +2**2-1 used in each processor int iPhiMin = myOMTFConfig->getProcessorPhiVsRefLayer()[iProcessor][iRefLayer]-myOMTFConfig->globalPhiStart(iProcessor)-lowScaleEnd; int iPhiMax = iPhiMin+logicRegionSize-1; iPhiMin+=iRegion*logicRegionSize; iPhiMax+=iRegion*logicRegionSize; stringStr.str(""); stringStr<<iPhiMin; aRefHitElement->setAttribute(_toDOMS("iPhiMin"), _toDOMS(stringStr.str())); stringStr.str(""); stringStr<<iPhiMax; aRefHitElement->setAttribute(_toDOMS("iPhiMax"), _toDOMS(stringStr.str())); if(iRefHit<myOMTFConfig->nRefHits()) aProcessorElement->appendChild(aRefHitElement); ++iRefHit; } for(;iRegion==5 && iRefLayer==7 && iRefHit<myOMTFConfig->nRefHits();++iRefHit){ xercesc::DOMElement* aRefHitElement = theDoc->createElement(_toDOMS("RefHit")); stringStr.str(""); stringStr<<iRefHit; aRefHitElement->setAttribute(_toDOMS("iRefHit"), _toDOMS(stringStr.str())); stringStr.str(""); stringStr<<0; aRefHitElement->setAttribute(_toDOMS("iRefLayer"), _toDOMS(stringStr.str())); stringStr.str(""); stringStr<<0; aRefHitElement->setAttribute(_toDOMS("iRegion"), _toDOMS(stringStr.str())); stringStr.str(""); stringStr<<0; aRefHitElement->setAttribute(_toDOMS("iInput"), _toDOMS(stringStr.str())); int iPhiMin = 0; int iPhiMax = 1; stringStr.str(""); stringStr<<iPhiMin; aRefHitElement->setAttribute(_toDOMS("iPhiMin"), _toDOMS(stringStr.str())); stringStr.str(""); stringStr<<iPhiMax; aRefHitElement->setAttribute(_toDOMS("iPhiMax"), _toDOMS(stringStr.str())); aProcessorElement->appendChild(aRefHitElement); } } } //// for(unsigned int iRegion=0;iRegion<6;++iRegion){ xercesc::DOMElement* aRegionElement = theDoc->createElement(_toDOMS("LogicRegion")); stringStr.str(""); stringStr<<iRegion; aRegionElement->setAttribute(_toDOMS("iRegion"), _toDOMS(stringStr.str())); for(unsigned int iLogicLayer=0;iLogicLayer<myOMTFConfig->nLayers();++iLogicLayer){ xercesc::DOMElement* aLayerElement = theDoc->createElement(_toDOMS("Layer")); stringStr.str(""); stringStr<<iLogicLayer; //////////////////////////////////////////////// aLayerElement->setAttribute(_toDOMS("iLayer"), _toDOMS(stringStr.str())); const OMTFConfiguration::vector1D & myCounts = myOMTFConfig->getMeasurements4D()[iProcessor][iRegion][iLogicLayer]; unsigned int maxInput = findMaxInput(myCounts); unsigned int begin = 0, end = 0; if((int)maxInput-2>=0) begin = maxInput-2; else begin = maxInput; end = maxInput+3; stringStr.str(""); stringStr<<begin; aLayerElement->setAttribute(_toDOMS("iFirstInput"), _toDOMS(stringStr.str())); stringStr.str(""); stringStr<<end-begin+1; aLayerElement->setAttribute(_toDOMS("nInputs"), _toDOMS(stringStr.str())); aRegionElement->appendChild(aLayerElement); } aProcessorElement->appendChild(aRegionElement); } theTopElement->appendChild(aProcessorElement); } } ////////////////////////////////////////////////// ////////////////////////////////////////////////// unsigned int XMLConfigWriter::findMaxInput(const OMTFConfiguration::vector1D & myCounts){ unsigned int max = 0; unsigned int maxInput = 0; for(unsigned int iInput=0;iInput<14;++iInput){ if(myCounts[iInput]>(int)max){ max = myCounts[iInput]; maxInput = iInput; } } return maxInput; } ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// template void XMLConfigWriter::writeGPs(const std::vector<std::shared_ptr<GoldenPattern> >& goldenPats, std::string fName); template void XMLConfigWriter::writeGPs(const std::vector<std::shared_ptr<GoldenPatternWithStat> >& goldenPats, std::string fName);
41.207681
199
0.653354
[ "vector" ]
feb60621a2812c8f99cc43dcda07890a082cf665
2,616
cpp
C++
tf2_src/game/shared/tf2/weapon_combat_grenade_emp.cpp
d3fc0n6/TeamFortress2
1b81dded673d49adebf4d0958e52236ecc28a956
[ "MIT" ]
4
2021-10-03T05:16:55.000Z
2021-12-28T16:49:27.000Z
tf2_src/game/shared/tf2/weapon_combat_grenade_emp.cpp
Counter2828/TeamFortress2
1b81dded673d49adebf4d0958e52236ecc28a956
[ "MIT" ]
null
null
null
tf2_src/game/shared/tf2/weapon_combat_grenade_emp.cpp
Counter2828/TeamFortress2
1b81dded673d49adebf4d0958e52236ecc28a956
[ "MIT" ]
3
2022-02-02T18:09:58.000Z
2022-03-06T18:54:39.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: The Commando's anti-personnel grenades // // $NoKeywords: $ //=============================================================================// #include "cbase.h" #include "Sprite.h" #include "basetfplayer_shared.h" #include "weapon_combat_usedwithshieldbase.h" #include "weapon_combat_basegrenade.h" #include "weapon_combatshield.h" #include "in_buttons.h" #include "grenade_emp.h" #if defined( CLIENT_DLL ) #define CWeaponCombatGrenadeEMP C_WeaponCombatGrenadeEMP #endif // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" //----------------------------------------------------------------------------- // Purpose: Combo shield & grenade weapon //----------------------------------------------------------------------------- class CWeaponCombatGrenadeEMP : public CWeaponCombatBaseGrenade { DECLARE_CLASS( CWeaponCombatGrenadeEMP, CWeaponCombatBaseGrenade ); public: DECLARE_NETWORKCLASS(); DECLARE_PREDICTABLE(); CWeaponCombatGrenadeEMP(); virtual void Precache( void ); virtual CBaseGrenade *CreateGrenade( const Vector &vecOrigin, const Vector &vecAngles, CBasePlayer *pOwner ); // All predicted weapons need to implement and return true virtual bool IsPredicted( void ) const { return true; } #if defined( CLIENT_DLL ) virtual bool ShouldPredict( void ) { if ( GetOwner() == C_BasePlayer::GetLocalPlayer() ) return true; return BaseClass::ShouldPredict(); } #endif private: CWeaponCombatGrenadeEMP( const CWeaponCombatGrenadeEMP & ); }; LINK_ENTITY_TO_CLASS( weapon_combat_grenade_emp, CWeaponCombatGrenadeEMP ); IMPLEMENT_NETWORKCLASS_ALIASED( WeaponCombatGrenadeEMP, DT_WeaponCombatGrenadeEMP ) BEGIN_NETWORK_TABLE( CWeaponCombatGrenadeEMP, DT_WeaponCombatGrenadeEMP ) END_NETWORK_TABLE() BEGIN_PREDICTION_DATA( CWeaponCombatGrenadeEMP ) END_PREDICTION_DATA() PRECACHE_WEAPON_REGISTER(weapon_combat_grenade_emp); CWeaponCombatGrenadeEMP::CWeaponCombatGrenadeEMP( void ) { SetPredictionEligible( true ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWeaponCombatGrenadeEMP::Precache( void ) { BaseClass::Precache(); #if !defined( CLIENT_DLL ) UTIL_PrecacheOther( "grenade_emp" ); #endif } CBaseGrenade *CWeaponCombatGrenadeEMP::CreateGrenade( const Vector &vecOrigin, const Vector &vecAngles, CBasePlayer *pOwner ) { return CGrenadeEMP::Create(vecOrigin, vecAngles, pOwner ); }
28.129032
125
0.652905
[ "vector" ]
feb940e8d3325156e2dd3e100aa210f766a89a95
8,826
hpp
C++
examples/CBuilder/Compound/ProdStruct/ProdStructClasses.hpp
LenakeTech/BoldForDelphi
3ef25517d5c92ebccc097c6bc2f2af62fc506c71
[ "MIT" ]
121
2020-09-22T10:46:20.000Z
2021-11-17T12:33:35.000Z
examples/CBuilder/Compound/ProdStruct/ProdStructClasses.hpp
LenakeTech/BoldForDelphi
3ef25517d5c92ebccc097c6bc2f2af62fc506c71
[ "MIT" ]
8
2020-09-23T12:32:23.000Z
2021-07-28T07:01:26.000Z
examples/CBuilder/Compound/ProdStruct/ProdStructClasses.hpp
LenakeTech/BoldForDelphi
3ef25517d5c92ebccc097c6bc2f2af62fc506c71
[ "MIT" ]
42
2020-09-22T14:37:20.000Z
2021-10-04T10:24:12.000Z
/*****************************************/ /* This file is autogenerated */ /* Any manual changes will be LOST! */ /*****************************************/ /* Generated 2002-01-02 16:01:16 */ /*****************************************/ /* This file should be stored in the */ /* same directory as the form/datamodule */ /* with the corresponding model */ /*****************************************/ /* Copyright notice: */ /* */ /*****************************************/ #if !defined (ProdStructClasses_HPP) #define ProdStructClasses_HPP // interface uses // interface dependancies // attribute dependancies #include "BoldAttributes.hpp" #include <Classes.hpp> #include <Controls.hpp> #include <SysUtils.hpp> #include "BoldDefs.hpp" #include "BoldSubscription.hpp" #include "BoldDeriver.hpp" #include "BoldElements.hpp" #include "BoldDomainElement.hpp" #include "BoldSystemRT.hpp" #include "BoldSystem.hpp" void unregisterCode(); // forward declarations of all classes } class TProdStructClassesRoot; class TProdStructClassesRootList; class TPartOfParts; class TPartOfPartsList; class TProduct; class TProductList; class TAssembly; class TAssemblyList; class TSimple_Product; class TSimple_ProductList; class DELPHICLASS TProdStructClassesRoot; class TProdStructClassesRoot : public Boldsystem::TBoldObject { typedef Boldsystem::TBoldObject inherited; private: protected: public: #pragma option push -w-inl inline __fastcall TProdStructClassesRoot(Boldsystem::TBoldSystem* aBoldSystem) : Boldsystem::TBoldObject(aBoldSystem, true) { } #pragma option pop }; class DELPHICLASS TPartOfParts; class TPartOfParts : public TProdStructClassesRoot { typedef TProdStructClassesRoot inherited; private: TProduct* __fastcall _GetParts(); TBoldObjectReference* __fastcall _Get_M_Parts(); TAssembly* __fastcall _GetPartOf(); TBoldObjectReference* __fastcall _Get_M_PartOf(); __property TBoldObjectReference* M_PartOf = {read=_Get_M_PartOf}; __property TAssembly* PartOf = {read=_GetPartOf}; protected: public: #pragma option push -w-inl inline __fastcall TPartOfParts(Boldsystem::TBoldSystem* aBoldSystem) : TProdStructClassesRoot(aBoldSystem) { } #pragma option pop __property TBoldObjectReference* M_Parts = {read=_Get_M_Parts}; __property TProduct* Parts = {read=_GetParts}; }; class DELPHICLASS TProduct; class TProduct : public TProdStructClassesRoot { typedef TProdStructClassesRoot inherited; private: TBAString* __fastcall _Get_M_Name(); String __fastcall _GetName(); void __fastcall _SetName(String NewValue); TBACurrency* __fastcall _Get_M_Price(); Currency __fastcall _GetPrice(); void __fastcall _SetPrice(Currency NewValue); TBACurrency* __fastcall _Get_M_TotalCost(); Currency __fastcall _GetTotalCost(); TAssemblyList* __fastcall _GetPartOf(); TPartOfPartsList* __fastcall _GetPartOfPartOfParts(); __property TAssemblyList* M_PartOf = {read=_GetPartOf}; __property TPartOfPartsList* M_PartOfPartOfParts = {read=_GetPartOfPartOfParts}; __property TAssemblyList* PartOf = {read=_GetPartOf}; __property TPartOfPartsList* PartOfPartOfParts = {read=_GetPartOfPartOfParts}; protected: virtual void __fastcall _TotalCost_DeriveAndSubscribe(TObject *DerivedObject, TBoldSubscriber *Subscriber); virtual TBoldDeriveAndResubscribe __fastcall GetDeriveMethodForMember(TBoldMember *Member); virtual TBoldReverseDerive __fastcall GetReverseDeriveMethodForMember(TBoldMember *Member); public: #pragma option push -w-inl inline __fastcall TProduct(Boldsystem::TBoldSystem* aBoldSystem) : TProdStructClassesRoot(aBoldSystem) { } #pragma option pop __property TBAString* M_Name = {read=_Get_M_Name}; __property TBACurrency* M_Price = {read=_Get_M_Price}; __property TBACurrency* M_TotalCost = {read=_Get_M_TotalCost}; __property String Name = {read=_GetName, write=_SetName}; __property Currency Price = {read=_GetPrice, write=_SetPrice}; __property Currency TotalCost = {read=_GetTotalCost}; }; class DELPHICLASS TAssembly; class TAssembly : public TProduct { typedef TProduct inherited; private: TBACurrency* __fastcall _Get_M_AssemblyCost(); Currency __fastcall _GetAssemblyCost(); void __fastcall _SetAssemblyCost(Currency NewValue); TProductList* __fastcall _GetParts(); TPartOfPartsList* __fastcall _GetPartsPartOfParts(); protected: virtual void __fastcall _TotalCost_DeriveAndSubscribe(TObject *DerivedObject, TBoldSubscriber *Subscriber); public: #pragma option push -w-inl inline __fastcall TAssembly(Boldsystem::TBoldSystem* aBoldSystem) : TProduct(aBoldSystem) { } #pragma option pop __property TBACurrency* M_AssemblyCost = {read=_Get_M_AssemblyCost}; __property TProductList* M_Parts = {read=_GetParts}; __property TPartOfPartsList* M_PartsPartOfParts = {read=_GetPartsPartOfParts}; __property Currency AssemblyCost = {read=_GetAssemblyCost, write=_SetAssemblyCost}; __property TProductList* Parts = {read=_GetParts}; __property TPartOfPartsList* PartsPartOfParts = {read=_GetPartsPartOfParts}; }; class DELPHICLASS TSimple_Product; class TSimple_Product : public TProduct { typedef TProduct inherited; private: TBACurrency* __fastcall _Get_M_ProductionCost(); Currency __fastcall _GetProductionCost(); void __fastcall _SetProductionCost(Currency NewValue); protected: virtual void __fastcall _TotalCost_DeriveAndSubscribe(TObject *DerivedObject, TBoldSubscriber *Subscriber); public: #pragma option push -w-inl inline __fastcall TSimple_Product(Boldsystem::TBoldSystem* aBoldSystem) : TProduct(aBoldSystem) { } #pragma option pop __property TBACurrency* M_ProductionCost = {read=_Get_M_ProductionCost}; __property Currency ProductionCost = {read=_GetProductionCost, write=_SetProductionCost}; }; class DELPHICLASS TProdStructClassesRootList; class TProdStructClassesRootList : public TBoldObjectList { protected: TProdStructClassesRoot* __fastcall GetBoldObject(int index); void __fastcall SetBoldObject(int index, TProdStructClassesRoot *NewObject); public: int __fastcall Includes(TProdStructClassesRoot *anObject); int __fastcall IndexOf(TProdStructClassesRoot *anObject); void __fastcall Add(TProdStructClassesRoot *NewObject); TProdStructClassesRoot* __fastcall AddNew(); void __fastcall Insert(int index, TProdStructClassesRoot *NewObject); __property TProdStructClassesRoot* BoldObjects[int index] = {read=GetBoldObject, write=SetBoldObject}; }; class DELPHICLASS TPartOfPartsList; class TPartOfPartsList : public TProdStructClassesRootList { protected: TPartOfParts* __fastcall GetBoldObject(int index); void __fastcall SetBoldObject(int index, TPartOfParts *NewObject); public: int __fastcall Includes(TPartOfParts *anObject); int __fastcall IndexOf(TPartOfParts *anObject); void __fastcall Add(TPartOfParts *NewObject); TPartOfParts* __fastcall AddNew(); void __fastcall Insert(int index, TPartOfParts *NewObject); __property TPartOfParts* BoldObjects[int index] = {read=GetBoldObject, write=SetBoldObject}; }; class DELPHICLASS TProductList; class TProductList : public TProdStructClassesRootList { protected: TProduct* __fastcall GetBoldObject(int index); void __fastcall SetBoldObject(int index, TProduct *NewObject); public: int __fastcall Includes(TProduct *anObject); int __fastcall IndexOf(TProduct *anObject); void __fastcall Add(TProduct *NewObject); TProduct* __fastcall AddNew(); void __fastcall Insert(int index, TProduct *NewObject); __property TProduct* BoldObjects[int index] = {read=GetBoldObject, write=SetBoldObject}; }; class DELPHICLASS TAssemblyList; class TAssemblyList : public TProductList { protected: TAssembly* __fastcall GetBoldObject(int index); void __fastcall SetBoldObject(int index, TAssembly *NewObject); public: int __fastcall Includes(TAssembly *anObject); int __fastcall IndexOf(TAssembly *anObject); void __fastcall Add(TAssembly *NewObject); TAssembly* __fastcall AddNew(); void __fastcall Insert(int index, TAssembly *NewObject); __property TAssembly* BoldObjects[int index] = {read=GetBoldObject, write=SetBoldObject}; }; class DELPHICLASS TSimple_ProductList; class TSimple_ProductList : public TProductList { protected: TSimple_Product* __fastcall GetBoldObject(int index); void __fastcall SetBoldObject(int index, TSimple_Product *NewObject); public: int __fastcall Includes(TSimple_Product *anObject); int __fastcall IndexOf(TSimple_Product *anObject); void __fastcall Add(TSimple_Product *NewObject); TSimple_Product* __fastcall AddNew(); void __fastcall Insert(int index, TSimple_Product *NewObject); __property TSimple_Product* BoldObjects[int index] = {read=GetBoldObject, write=SetBoldObject}; }; char* GeneratedCodeCRC(); #endif
36.02449
129
0.773623
[ "model" ]
febb4c5a6a3fae242c67c8fdcd5250dd6c22849e
233,284
cc
C++
stack/btm/btm_sec.cc
digi-embedded/android_platform_system_bt
635ddc5671274697ecfc9d4d44881f23d73a4cd0
[ "Apache-2.0" ]
null
null
null
stack/btm/btm_sec.cc
digi-embedded/android_platform_system_bt
635ddc5671274697ecfc9d4d44881f23d73a4cd0
[ "Apache-2.0" ]
null
null
null
stack/btm/btm_sec.cc
digi-embedded/android_platform_system_bt
635ddc5671274697ecfc9d4d44881f23d73a4cd0
[ "Apache-2.0" ]
2
2019-05-30T08:37:28.000Z
2019-10-01T16:39:33.000Z
/****************************************************************************** * * Copyright (C) 1999-2012 Broadcom 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. * ******************************************************************************/ /****************************************************************************** * * This file contains functions for the Bluetooth Security Manager * ******************************************************************************/ #define LOG_TAG "bt_btm_sec" #include <stdarg.h> #include <stdio.h> #include <string.h> #include "device/include/controller.h" #include "osi/include/log.h" #include "osi/include/osi.h" #include "osi/include/time.h" #include "bt_types.h" #include "bt_utils.h" #include "btm_int.h" #include "btu.h" #include "hcimsgs.h" #include "l2c_int.h" #include "gatt_int.h" #define BTM_SEC_MAX_COLLISION_DELAY (5000) extern fixed_queue_t* btu_general_alarm_queue; #ifdef APPL_AUTH_WRITE_EXCEPTION bool(APPL_AUTH_WRITE_EXCEPTION)(BD_ADDR bd_addr); #endif /******************************************************************************* * L O C A L F U N C T I O N P R O T O T Y P E S * ******************************************************************************/ tBTM_SEC_SERV_REC* btm_sec_find_first_serv(bool is_originator, uint16_t psm); static tBTM_SEC_SERV_REC* btm_sec_find_next_serv(tBTM_SEC_SERV_REC* p_cur); static tBTM_SEC_SERV_REC* btm_sec_find_mx_serv(uint8_t is_originator, uint16_t psm, uint32_t mx_proto_id, uint32_t mx_chan_id); static tBTM_STATUS btm_sec_execute_procedure(tBTM_SEC_DEV_REC* p_dev_rec); static bool btm_sec_start_get_name(tBTM_SEC_DEV_REC* p_dev_rec); static void btm_sec_start_authentication(tBTM_SEC_DEV_REC* p_dev_rec); static void btm_sec_start_encryption(tBTM_SEC_DEV_REC* p_dev_rec); static void btm_sec_collision_timeout(void* data); static void btm_restore_mode(void); static void btm_sec_pairing_timeout(void* data); static tBTM_STATUS btm_sec_dd_create_conn(tBTM_SEC_DEV_REC* p_dev_rec); static void btm_sec_change_pairing_state(tBTM_PAIRING_STATE new_state); static const char* btm_pair_state_descr(tBTM_PAIRING_STATE state); static void btm_sec_check_pending_reqs(void); static bool btm_sec_queue_mx_request(BD_ADDR bd_addr, uint16_t psm, bool is_orig, uint32_t mx_proto_id, uint32_t mx_chan_id, tBTM_SEC_CALLBACK* p_callback, void* p_ref_data); static void btm_sec_bond_cancel_complete(void); static void btm_send_link_key_notif(tBTM_SEC_DEV_REC* p_dev_rec); static bool btm_sec_check_prefetch_pin(tBTM_SEC_DEV_REC* p_dev_rec); static uint8_t btm_sec_start_authorization(tBTM_SEC_DEV_REC* p_dev_rec); bool btm_sec_are_all_trusted(uint32_t p_mask[]); static tBTM_STATUS btm_sec_send_hci_disconnect(tBTM_SEC_DEV_REC* p_dev_rec, uint8_t reason, uint16_t conn_handle); uint8_t btm_sec_start_role_switch(tBTM_SEC_DEV_REC* p_dev_rec); tBTM_SEC_DEV_REC* btm_sec_find_dev_by_sec_state(uint8_t state); static bool btm_sec_set_security_level(CONNECTION_TYPE conn_type, const char* p_name, uint8_t service_id, uint16_t sec_level, uint16_t psm, uint32_t mx_proto_id, uint32_t mx_chan_id); static bool btm_dev_authenticated(tBTM_SEC_DEV_REC* p_dev_rec); static bool btm_dev_encrypted(tBTM_SEC_DEV_REC* p_dev_rec); static bool btm_dev_authorized(tBTM_SEC_DEV_REC* p_dev_rec); static bool btm_serv_trusted(tBTM_SEC_DEV_REC* p_dev_rec, tBTM_SEC_SERV_REC* p_serv_rec); static bool btm_sec_is_serv_level0(uint16_t psm); static uint16_t btm_sec_set_serv_level4_flags(uint16_t cur_security, bool is_originator); static bool btm_sec_queue_encrypt_request(BD_ADDR bd_addr, tBT_TRANSPORT transport, tBTM_SEC_CALLBACK* p_callback, void* p_ref_data, tBTM_BLE_SEC_ACT sec_act); static void btm_sec_check_pending_enc_req(tBTM_SEC_DEV_REC* p_dev_rec, tBT_TRANSPORT transport, uint8_t encr_enable); static bool btm_sec_use_smp_br_chnl(tBTM_SEC_DEV_REC* p_dev_rec); static bool btm_sec_is_master(tBTM_SEC_DEV_REC* p_dev_rec); /* true - authenticated link key is possible */ static const bool btm_sec_io_map[BTM_IO_CAP_MAX][BTM_IO_CAP_MAX] = { /* OUT, IO, IN, NONE */ /* OUT */ {false, false, true, false}, /* IO */ {false, true, true, false}, /* IN */ {true, true, true, false}, /* NONE */ {false, false, false, false}}; /* BTM_IO_CAP_OUT 0 DisplayOnly */ /* BTM_IO_CAP_IO 1 DisplayYesNo */ /* BTM_IO_CAP_IN 2 KeyboardOnly */ /* BTM_IO_CAP_NONE 3 NoInputNoOutput */ /******************************************************************************* * * Function btm_dev_authenticated * * Description check device is authenticated * * Returns bool true or false * ******************************************************************************/ static bool btm_dev_authenticated(tBTM_SEC_DEV_REC* p_dev_rec) { if (p_dev_rec->sec_flags & BTM_SEC_AUTHENTICATED) { return (true); } return (false); } /******************************************************************************* * * Function btm_dev_encrypted * * Description check device is encrypted * * Returns bool true or false * ******************************************************************************/ static bool btm_dev_encrypted(tBTM_SEC_DEV_REC* p_dev_rec) { if (p_dev_rec->sec_flags & BTM_SEC_ENCRYPTED) { return (true); } return (false); } /******************************************************************************* * * Function btm_dev_authorized * * Description check device is authorized * * Returns bool true or false * ******************************************************************************/ static bool btm_dev_authorized(tBTM_SEC_DEV_REC* p_dev_rec) { if (p_dev_rec->sec_flags & BTM_SEC_AUTHORIZED) { return (true); } return (false); } /******************************************************************************* * * Function btm_dev_16_digit_authenticated * * Description check device is authenticated by using 16 digit pin or MITM * * Returns bool true or false * ******************************************************************************/ static bool btm_dev_16_digit_authenticated(tBTM_SEC_DEV_REC* p_dev_rec) { // BTM_SEC_16_DIGIT_PIN_AUTHED is set if MITM or 16 digit pin is used if (p_dev_rec->sec_flags & BTM_SEC_16_DIGIT_PIN_AUTHED) { return (true); } return (false); } /******************************************************************************* * * Function btm_serv_trusted * * Description check service is trusted * * Returns bool true or false * ******************************************************************************/ static bool btm_serv_trusted(tBTM_SEC_DEV_REC* p_dev_rec, tBTM_SEC_SERV_REC* p_serv_rec) { if (BTM_SEC_IS_SERVICE_TRUSTED(p_dev_rec->trusted_mask, p_serv_rec->service_id)) { return (true); } return (false); } /******************************************************************************* * * Function BTM_SecRegister * * Description Application manager calls this function to register for * security services. There can be one and only one * application saving link keys. BTM allows only first * registration. * * Returns true if registered OK, else false * ******************************************************************************/ bool BTM_SecRegister(tBTM_APPL_INFO* p_cb_info) { BT_OCTET16 temp_value = {0}; BTM_TRACE_EVENT("%s application registered", __func__); LOG_INFO(LOG_TAG, "%s p_cb_info->p_le_callback == 0x%p", __func__, p_cb_info->p_le_callback); if (p_cb_info->p_le_callback) { BTM_TRACE_EVENT("%s SMP_Register( btm_proc_smp_cback )", __func__); SMP_Register(btm_proc_smp_cback); /* if no IR is loaded, need to regenerate all the keys */ if (memcmp(btm_cb.devcb.id_keys.ir, &temp_value, sizeof(BT_OCTET16)) == 0) { btm_ble_reset_id(); } } else { LOG_WARN(LOG_TAG, "%s p_cb_info->p_le_callback == NULL", __func__); } btm_cb.api = *p_cb_info; LOG_INFO(LOG_TAG, "%s btm_cb.api.p_le_callback = 0x%p ", __func__, btm_cb.api.p_le_callback); BTM_TRACE_EVENT("%s application registered", __func__); return (true); } /******************************************************************************* * * Function BTM_SecRegisterLinkKeyNotificationCallback * * Description Application manager calls this function to register for * link key notification. When there is nobody registered * we should avoid changing link key * * Returns true if registered OK, else false * ******************************************************************************/ bool BTM_SecRegisterLinkKeyNotificationCallback( tBTM_LINK_KEY_CALLBACK* p_callback) { btm_cb.api.p_link_key_callback = p_callback; return true; } /******************************************************************************* * * Function BTM_SecAddRmtNameNotifyCallback * * Description Any profile can register to be notified when name of the * remote device is resolved. * * Returns true if registered OK, else false * ******************************************************************************/ bool BTM_SecAddRmtNameNotifyCallback(tBTM_RMT_NAME_CALLBACK* p_callback) { int i; for (i = 0; i < BTM_SEC_MAX_RMT_NAME_CALLBACKS; i++) { if (btm_cb.p_rmt_name_callback[i] == NULL) { btm_cb.p_rmt_name_callback[i] = p_callback; return (true); } } return (false); } /******************************************************************************* * * Function BTM_SecDeleteRmtNameNotifyCallback * * Description Any profile can deregister notification when a new Link Key * is generated per connection. * * Returns true if OK, else false * ******************************************************************************/ bool BTM_SecDeleteRmtNameNotifyCallback(tBTM_RMT_NAME_CALLBACK* p_callback) { int i; for (i = 0; i < BTM_SEC_MAX_RMT_NAME_CALLBACKS; i++) { if (btm_cb.p_rmt_name_callback[i] == p_callback) { btm_cb.p_rmt_name_callback[i] = NULL; return (true); } } return (false); } /******************************************************************************* * * Function BTM_GetSecurityFlags * * Description Get security flags for the device * * Returns bool true or false is device found * ******************************************************************************/ bool BTM_GetSecurityFlags(BD_ADDR bd_addr, uint8_t* p_sec_flags) { tBTM_SEC_DEV_REC* p_dev_rec; p_dev_rec = btm_find_dev(bd_addr); if (p_dev_rec != NULL) { *p_sec_flags = (uint8_t)p_dev_rec->sec_flags; return (true); } BTM_TRACE_ERROR("BTM_GetSecurityFlags false"); return (false); } /******************************************************************************* * * Function BTM_GetSecurityFlagsByTransport * * Description Get security flags for the device on a particular transport * * Returns bool true or false is device found * ******************************************************************************/ bool BTM_GetSecurityFlagsByTransport(BD_ADDR bd_addr, uint8_t* p_sec_flags, tBT_TRANSPORT transport) { tBTM_SEC_DEV_REC* p_dev_rec; p_dev_rec = btm_find_dev(bd_addr); if (p_dev_rec != NULL) { if (transport == BT_TRANSPORT_BR_EDR) *p_sec_flags = (uint8_t)p_dev_rec->sec_flags; else *p_sec_flags = (uint8_t)(p_dev_rec->sec_flags >> 8); return (true); } BTM_TRACE_ERROR("BTM_GetSecurityFlags false"); return (false); } /******************************************************************************* * * Function BTM_SetPinType * * Description Set PIN type for the device. * * Returns void * ******************************************************************************/ void BTM_SetPinType(uint8_t pin_type, PIN_CODE pin_code, uint8_t pin_code_len) { BTM_TRACE_API( "BTM_SetPinType: pin type %d [variable-0, fixed-1], code %s, length %d", pin_type, (char*)pin_code, pin_code_len); /* If device is not up security mode will be set as a part of startup */ if ((btm_cb.cfg.pin_type != pin_type) && controller_get_interface()->get_is_ready()) { btsnd_hcic_write_pin_type(pin_type); } btm_cb.cfg.pin_type = pin_type; btm_cb.cfg.pin_code_len = pin_code_len; memcpy(btm_cb.cfg.pin_code, pin_code, pin_code_len); } /******************************************************************************* * * Function BTM_SetPairableMode * * Description Enable or disable pairing * * Parameters allow_pairing - (true or false) whether or not the device * allows pairing. * connect_only_paired - (true or false) whether or not to * only allow paired devices to connect. * * Returns void * ******************************************************************************/ void BTM_SetPairableMode(bool allow_pairing, bool connect_only_paired) { BTM_TRACE_API( "BTM_SetPairableMode() allow_pairing: %u connect_only_paired: %u", allow_pairing, connect_only_paired); btm_cb.pairing_disabled = !allow_pairing; btm_cb.connect_only_paired = connect_only_paired; } /******************************************************************************* * * Function BTM_SetSecureConnectionsOnly * * Description Enable or disable default treatment for Mode 4 Level 0 * services * * Parameter secure_connections_only_mode - * true means that the device should treat Mode 4 Level 0 * services as services of other levels. * false means that the device should provide default * treatment for Mode 4 Level 0 services. * * Returns void * ******************************************************************************/ void BTM_SetSecureConnectionsOnly(bool secure_connections_only_mode) { BTM_TRACE_API("%s: Mode : %u", __func__, secure_connections_only_mode); btm_cb.devcb.secure_connections_only = secure_connections_only_mode; btm_cb.security_mode = BTM_SEC_MODE_SC; } #define BTM_NO_AVAIL_SEC_SERVICES ((uint16_t)0xffff) /******************************************************************************* * * Function BTM_SetSecurityLevel * * Description Register service security level with Security Manager * * Parameters: is_originator - true if originating the connection * p_name - Name of the service relevant only if * authorization will show this name to user. * Ignored if BTM_SEC_SERVICE_NAME_LEN is 0. * service_id - service ID for the service passed to * authorization callback * sec_level - bit mask of the security features * psm - L2CAP PSM * mx_proto_id - protocol ID of multiplexing proto below * mx_chan_id - channel ID of multiplexing proto below * * Returns true if registered OK, else false * ******************************************************************************/ bool BTM_SetSecurityLevel(bool is_originator, const char* p_name, uint8_t service_id, uint16_t sec_level, uint16_t psm, uint32_t mx_proto_id, uint32_t mx_chan_id) { #if (L2CAP_UCD_INCLUDED == TRUE) CONNECTION_TYPE conn_type; if (is_originator) conn_type = CONN_ORIENT_ORIG; else conn_type = CONN_ORIENT_TERM; return (btm_sec_set_security_level(conn_type, p_name, service_id, sec_level, psm, mx_proto_id, mx_chan_id)); #else return (btm_sec_set_security_level(is_originator, p_name, service_id, sec_level, psm, mx_proto_id, mx_chan_id)); #endif } /******************************************************************************* * * Function btm_sec_set_security_level * * Description Register service security level with Security Manager * * Parameters: conn_type - true if originating the connection * p_name - Name of the service relevant only if * authorization will show this name to user. * Ignored if BTM_SEC_SERVICE_NAME_LEN is 0. * service_id - service ID for the service passed to * authorization callback * sec_level - bit mask of the security features * psm - L2CAP PSM * mx_proto_id - protocol ID of multiplexing proto below * mx_chan_id - channel ID of multiplexing proto below * * Returns true if registered OK, else false * ******************************************************************************/ static bool btm_sec_set_security_level(CONNECTION_TYPE conn_type, const char* p_name, uint8_t service_id, uint16_t sec_level, uint16_t psm, uint32_t mx_proto_id, uint32_t mx_chan_id) { tBTM_SEC_SERV_REC* p_srec; uint16_t index; uint16_t first_unused_record = BTM_NO_AVAIL_SEC_SERVICES; bool record_allocated = false; bool is_originator; #if (L2CAP_UCD_INCLUDED == TRUE) bool is_ucd; if (conn_type & CONNECTION_TYPE_ORIG_MASK) is_originator = true; else is_originator = false; if (conn_type & CONNECTION_TYPE_CONNLESS_MASK) { is_ucd = true; } else { is_ucd = false; } #else is_originator = conn_type; #endif BTM_TRACE_API("%s : sec: 0x%x", __func__, sec_level); /* See if the record can be reused (same service name, psm, mx_proto_id, service_id, and mx_chan_id), or obtain the next unused record */ p_srec = &btm_cb.sec_serv_rec[0]; for (index = 0; index < BTM_SEC_MAX_SERVICE_RECORDS; index++, p_srec++) { /* Check if there is already a record for this service */ if (p_srec->security_flags & BTM_SEC_IN_USE) { #if BTM_SEC_SERVICE_NAME_LEN > 0 if (p_srec->psm == psm && p_srec->mx_proto_id == mx_proto_id && service_id == p_srec->service_id && p_name && (!strncmp(p_name, (char*)p_srec->orig_service_name, /* strlcpy replaces end char with termination char*/ BTM_SEC_SERVICE_NAME_LEN - 1) || !strncmp(p_name, (char*)p_srec->term_service_name, /* strlcpy replaces end char with termination char*/ BTM_SEC_SERVICE_NAME_LEN - 1))) #else if (p_srec->psm == psm && p_srec->mx_proto_id == mx_proto_id && service_id == p_srec->service_id) #endif { record_allocated = true; break; } } /* Mark the first available service record */ else if (!record_allocated) { memset(p_srec, 0, sizeof(tBTM_SEC_SERV_REC)); record_allocated = true; first_unused_record = index; } } if (!record_allocated) { BTM_TRACE_WARNING("BTM_SEC_REG: Out of Service Records (%d)", BTM_SEC_MAX_SERVICE_RECORDS); return (record_allocated); } /* Process the request if service record is valid */ /* If a duplicate service wasn't found, use the first available */ if (index >= BTM_SEC_MAX_SERVICE_RECORDS) { index = first_unused_record; p_srec = &btm_cb.sec_serv_rec[index]; } p_srec->psm = psm; p_srec->service_id = service_id; p_srec->mx_proto_id = mx_proto_id; if (is_originator) { p_srec->orig_mx_chan_id = mx_chan_id; #if BTM_SEC_SERVICE_NAME_LEN > 0 strlcpy((char*)p_srec->orig_service_name, p_name, BTM_SEC_SERVICE_NAME_LEN + 1); #endif /* clear out the old setting, just in case it exists */ #if (L2CAP_UCD_INCLUDED == TRUE) if (is_ucd) { p_srec->ucd_security_flags &= ~( BTM_SEC_OUT_AUTHORIZE | BTM_SEC_OUT_ENCRYPT | BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_OUT_MITM | BTM_SEC_FORCE_MASTER | BTM_SEC_ATTEMPT_MASTER | BTM_SEC_FORCE_SLAVE | BTM_SEC_ATTEMPT_SLAVE); } else #endif { p_srec->security_flags &= ~( BTM_SEC_OUT_AUTHORIZE | BTM_SEC_OUT_ENCRYPT | BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_OUT_MITM | BTM_SEC_FORCE_MASTER | BTM_SEC_ATTEMPT_MASTER | BTM_SEC_FORCE_SLAVE | BTM_SEC_ATTEMPT_SLAVE); } /* Parameter validation. Originator should not set requirements for * incoming connections */ sec_level &= ~(BTM_SEC_IN_AUTHORIZE | BTM_SEC_IN_ENCRYPT | BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_MITM | BTM_SEC_IN_MIN_16_DIGIT_PIN); if (btm_cb.security_mode == BTM_SEC_MODE_SP || btm_cb.security_mode == BTM_SEC_MODE_SP_DEBUG || btm_cb.security_mode == BTM_SEC_MODE_SC) { if (sec_level & BTM_SEC_OUT_AUTHENTICATE) sec_level |= BTM_SEC_OUT_MITM; } /* Make sure the authenticate bit is set, when encrypt bit is set */ if (sec_level & BTM_SEC_OUT_ENCRYPT) sec_level |= BTM_SEC_OUT_AUTHENTICATE; /* outgoing connections usually set the security level right before * the connection is initiated. * set it to be the outgoing service */ #if (L2CAP_UCD_INCLUDED == TRUE) if (is_ucd == false) #endif { btm_cb.p_out_serv = p_srec; } } else { p_srec->term_mx_chan_id = mx_chan_id; #if BTM_SEC_SERVICE_NAME_LEN > 0 strlcpy((char*)p_srec->term_service_name, p_name, BTM_SEC_SERVICE_NAME_LEN + 1); #endif /* clear out the old setting, just in case it exists */ #if (L2CAP_UCD_INCLUDED == TRUE) if (is_ucd) { p_srec->ucd_security_flags &= ~(BTM_SEC_IN_AUTHORIZE | BTM_SEC_IN_ENCRYPT | BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_MITM | BTM_SEC_FORCE_MASTER | BTM_SEC_ATTEMPT_MASTER | BTM_SEC_FORCE_SLAVE | BTM_SEC_ATTEMPT_SLAVE | BTM_SEC_IN_MIN_16_DIGIT_PIN); } else #endif { p_srec->security_flags &= ~(BTM_SEC_IN_AUTHORIZE | BTM_SEC_IN_ENCRYPT | BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_MITM | BTM_SEC_FORCE_MASTER | BTM_SEC_ATTEMPT_MASTER | BTM_SEC_FORCE_SLAVE | BTM_SEC_ATTEMPT_SLAVE | BTM_SEC_IN_MIN_16_DIGIT_PIN); } /* Parameter validation. Acceptor should not set requirements for outgoing * connections */ sec_level &= ~(BTM_SEC_OUT_AUTHORIZE | BTM_SEC_OUT_ENCRYPT | BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_OUT_MITM); if (btm_cb.security_mode == BTM_SEC_MODE_SP || btm_cb.security_mode == BTM_SEC_MODE_SP_DEBUG || btm_cb.security_mode == BTM_SEC_MODE_SC) { if (sec_level & BTM_SEC_IN_AUTHENTICATE) sec_level |= BTM_SEC_IN_MITM; } /* Make sure the authenticate bit is set, when encrypt bit is set */ if (sec_level & BTM_SEC_IN_ENCRYPT) sec_level |= BTM_SEC_IN_AUTHENTICATE; } #if (L2CAP_UCD_INCLUDED == TRUE) if (is_ucd) { p_srec->security_flags |= (uint16_t)(BTM_SEC_IN_USE); p_srec->ucd_security_flags |= (uint16_t)(sec_level | BTM_SEC_IN_USE); } else { p_srec->security_flags |= (uint16_t)(sec_level | BTM_SEC_IN_USE); } BTM_TRACE_API( "BTM_SEC_REG[%d]: id %d, conn_type 0x%x, psm 0x%04x, proto_id %d, " "chan_id %d", index, service_id, conn_type, psm, mx_proto_id, mx_chan_id); BTM_TRACE_API( " : security_flags: 0x%04x, ucd_security_flags: 0x%04x", p_srec->security_flags, p_srec->ucd_security_flags); #if BTM_SEC_SERVICE_NAME_LEN > 0 BTM_TRACE_API(" : service name [%s] (up to %d chars saved)", p_name, BTM_SEC_SERVICE_NAME_LEN); #endif #else p_srec->security_flags |= (uint16_t)(sec_level | BTM_SEC_IN_USE); BTM_TRACE_API( "BTM_SEC_REG[%d]: id %d, is_orig %d, psm 0x%04x, proto_id %d, chan_id %d", index, service_id, is_originator, psm, mx_proto_id, mx_chan_id); #if BTM_SEC_SERVICE_NAME_LEN > 0 BTM_TRACE_API( " : sec: 0x%x, service name [%s] (up to %d chars saved)", p_srec->security_flags, p_name, BTM_SEC_SERVICE_NAME_LEN); #endif #endif return (record_allocated); } /******************************************************************************* * * Function BTM_SecClrService * * Description Removes specified service record(s) from the security * database. All service records with the specified name are * removed. Typically used only by devices with limited RAM so * that it can reuse an old security service record. * * Note: Unpredictable results may occur if a service is * cleared that is still in use by an application/profile. * * Parameters Service ID - Id of the service to remove. '0' removes all * service records (except SDP). * * Returns Number of records that were freed. * ******************************************************************************/ uint8_t BTM_SecClrService(uint8_t service_id) { tBTM_SEC_SERV_REC* p_srec = &btm_cb.sec_serv_rec[0]; uint8_t num_freed = 0; int i; for (i = 0; i < BTM_SEC_MAX_SERVICE_RECORDS; i++, p_srec++) { /* Delete services with specified name (if in use and not SDP) */ if ((p_srec->security_flags & BTM_SEC_IN_USE) && (p_srec->psm != BT_PSM_SDP) && (!service_id || (service_id == p_srec->service_id))) { BTM_TRACE_API("BTM_SEC_CLR[%d]: id %d", i, service_id); p_srec->security_flags = 0; #if (L2CAP_UCD_INCLUDED == TRUE) p_srec->ucd_security_flags = 0; #endif num_freed++; } } return (num_freed); } /******************************************************************************* * * Function btm_sec_clr_service_by_psm * * Description Removes specified service record from the security database. * All service records with the specified psm are removed. * Typically used by L2CAP to free up the service record used * by dynamic PSM clients when the channel is closed. * The given psm must be a virtual psm. * * Parameters Service ID - Id of the service to remove. '0' removes all * service records (except SDP). * * Returns Number of records that were freed. * ******************************************************************************/ uint8_t btm_sec_clr_service_by_psm(uint16_t psm) { tBTM_SEC_SERV_REC* p_srec = &btm_cb.sec_serv_rec[0]; uint8_t num_freed = 0; int i; for (i = 0; i < BTM_SEC_MAX_SERVICE_RECORDS; i++, p_srec++) { /* Delete services with specified name (if in use and not SDP) */ if ((p_srec->security_flags & BTM_SEC_IN_USE) && (p_srec->psm == psm)) { BTM_TRACE_API("BTM_SEC_CLR[%d]: id %d ", i, p_srec->service_id); p_srec->security_flags = 0; num_freed++; } } BTM_TRACE_API("btm_sec_clr_service_by_psm psm:0x%x num_freed:%d", psm, num_freed); return (num_freed); } /******************************************************************************* * * Function btm_sec_clr_temp_auth_service * * Description Removes specified device record's temporary authorization * flag from the security database. * * Parameters Device address to be cleared * * Returns void. * ******************************************************************************/ void btm_sec_clr_temp_auth_service(BD_ADDR bda) { tBTM_SEC_DEV_REC* p_dev_rec; p_dev_rec = btm_find_dev(bda); if (p_dev_rec == NULL) { BTM_TRACE_WARNING("btm_sec_clr_temp_auth_service() - no dev CB"); return; } /* Reset the temporary authorized flag so that next time (untrusted) service * is accessed autorization will take place */ if (p_dev_rec->last_author_service_id != BTM_SEC_NO_LAST_SERVICE_ID && p_dev_rec->p_cur_service) { BTM_TRACE_DEBUG( "btm_sec_clr_auth_service_by_psm [clearing device: " "%02x:%02x:%02x:%02x:%02x:%02x]", bda[0], bda[1], bda[2], bda[3], bda[4], bda[5]); p_dev_rec->last_author_service_id = BTM_SEC_NO_LAST_SERVICE_ID; } } /******************************************************************************* * * Function BTM_PINCodeReply * * Description This function is called after Security Manager submitted * PIN code request to the UI. * * Parameters: bd_addr - Address of the device for which PIN was * requested * res - result of the operation BTM_SUCCESS * if success * pin_len - length in bytes of the PIN Code * p_pin - pointer to array with the PIN Code * trusted_mask - bitwise OR of trusted services * (array of uint32_t) * ******************************************************************************/ void BTM_PINCodeReply(BD_ADDR bd_addr, uint8_t res, uint8_t pin_len, uint8_t* p_pin, uint32_t trusted_mask[]) { tBTM_SEC_DEV_REC* p_dev_rec; BTM_TRACE_API( "BTM_PINCodeReply(): PairState: %s PairFlags: 0x%02x PinLen:%d " "Result:%d", btm_pair_state_descr(btm_cb.pairing_state), btm_cb.pairing_flags, pin_len, res); /* If timeout already expired or has been canceled, ignore the reply */ if (btm_cb.pairing_state != BTM_PAIR_STATE_WAIT_LOCAL_PIN) { BTM_TRACE_WARNING("BTM_PINCodeReply() - Wrong State: %d", btm_cb.pairing_state); return; } if (memcmp(bd_addr, btm_cb.pairing_bda, BD_ADDR_LEN) != 0) { BTM_TRACE_ERROR("BTM_PINCodeReply() - Wrong BD Addr"); return; } p_dev_rec = btm_find_dev(bd_addr); if (p_dev_rec == NULL) { BTM_TRACE_ERROR("BTM_PINCodeReply() - no dev CB"); return; } if ((pin_len > PIN_CODE_LEN) || (pin_len == 0) || (p_pin == NULL)) res = BTM_ILLEGAL_VALUE; if (res != BTM_SUCCESS) { /* if peer started dd OR we started dd and pre-fetch pin was not used send * negative reply */ if ((btm_cb.pairing_flags & BTM_PAIR_FLAGS_PEER_STARTED_DD) || ((btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) && (btm_cb.pairing_flags & BTM_PAIR_FLAGS_DISC_WHEN_DONE))) { /* use BTM_PAIR_STATE_WAIT_AUTH_COMPLETE to report authentication failed * event */ btm_sec_change_pairing_state(BTM_PAIR_STATE_WAIT_AUTH_COMPLETE); btm_cb.acl_disc_reason = HCI_ERR_HOST_REJECT_SECURITY; btsnd_hcic_pin_code_neg_reply(bd_addr); } else { p_dev_rec->security_required = BTM_SEC_NONE; btm_sec_change_pairing_state(BTM_PAIR_STATE_IDLE); } return; } if (trusted_mask) BTM_SEC_COPY_TRUSTED_DEVICE(trusted_mask, p_dev_rec->trusted_mask); p_dev_rec->sec_flags |= BTM_SEC_LINK_KEY_AUTHED; p_dev_rec->pin_code_length = pin_len; if (pin_len >= 16) { p_dev_rec->sec_flags |= BTM_SEC_16_DIGIT_PIN_AUTHED; } if ((btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) && (p_dev_rec->hci_handle == BTM_SEC_INVALID_HANDLE) && (btm_cb.security_mode_changed == false)) { /* This is start of the dedicated bonding if local device is 2.0 */ btm_cb.pin_code_len = pin_len; memcpy(btm_cb.pin_code, p_pin, pin_len); btm_cb.security_mode_changed = true; #ifdef APPL_AUTH_WRITE_EXCEPTION if (!(APPL_AUTH_WRITE_EXCEPTION)(p_dev_rec->bd_addr)) #endif btsnd_hcic_write_auth_enable(true); btm_cb.acl_disc_reason = 0xff; /* if we rejected incoming connection request, we have to wait * HCI_Connection_Complete event */ /* before originating */ if (btm_cb.pairing_flags & BTM_PAIR_FLAGS_REJECTED_CONNECT) { BTM_TRACE_WARNING( "BTM_PINCodeReply(): waiting HCI_Connection_Complete after rejected " "incoming connection"); /* we change state little bit early so btm_sec_connected() will originate * connection */ /* when existing ACL link is down completely */ btm_sec_change_pairing_state(BTM_PAIR_STATE_WAIT_PIN_REQ); } /* if we already accepted incoming connection from pairing device */ else if (p_dev_rec->sm4 & BTM_SM4_CONN_PEND) { BTM_TRACE_WARNING( "BTM_PINCodeReply(): link is connecting so wait pin code request " "from peer"); btm_sec_change_pairing_state(BTM_PAIR_STATE_WAIT_PIN_REQ); } else if (btm_sec_dd_create_conn(p_dev_rec) != BTM_CMD_STARTED) { btm_sec_change_pairing_state(BTM_PAIR_STATE_IDLE); p_dev_rec->sec_flags &= ~BTM_SEC_LINK_KEY_AUTHED; if (btm_cb.api.p_auth_complete_callback) (*btm_cb.api.p_auth_complete_callback)( p_dev_rec->bd_addr, p_dev_rec->dev_class, p_dev_rec->sec_bd_name, HCI_ERR_AUTH_FAILURE); } return; } btm_sec_change_pairing_state(BTM_PAIR_STATE_WAIT_AUTH_COMPLETE); btm_cb.acl_disc_reason = HCI_SUCCESS; btsnd_hcic_pin_code_req_reply(bd_addr, pin_len, p_pin); } /******************************************************************************* * * Function btm_sec_bond_by_transport * * Description this is the bond function that will start either SSP or SMP. * * Parameters: bd_addr - Address of the device to bond * pin_len - length in bytes of the PIN Code * p_pin - pointer to array with the PIN Code * trusted_mask - bitwise OR of trusted services * (array of uint32_t) * * Note: After 2.1 parameters are not used and preserved here not to change API ******************************************************************************/ tBTM_STATUS btm_sec_bond_by_transport(BD_ADDR bd_addr, tBT_TRANSPORT transport, uint8_t pin_len, uint8_t* p_pin, uint32_t trusted_mask[]) { tBTM_SEC_DEV_REC* p_dev_rec; tBTM_STATUS status; uint8_t* p_features; uint8_t ii; tACL_CONN* p = btm_bda_to_acl(bd_addr, transport); BTM_TRACE_API("btm_sec_bond_by_transport BDA: %02x:%02x:%02x:%02x:%02x:%02x", bd_addr[0], bd_addr[1], bd_addr[2], bd_addr[3], bd_addr[4], bd_addr[5]); BTM_TRACE_DEBUG("btm_sec_bond_by_transport: Transport used %d", transport); /* Other security process is in progress */ if (btm_cb.pairing_state != BTM_PAIR_STATE_IDLE) { BTM_TRACE_ERROR("BTM_SecBond: already busy in state: %s", btm_pair_state_descr(btm_cb.pairing_state)); return (BTM_WRONG_MODE); } p_dev_rec = btm_find_or_alloc_dev(bd_addr); if (p_dev_rec == NULL) { return (BTM_NO_RESOURCES); } if (!controller_get_interface()->get_is_ready()) { BTM_TRACE_ERROR("%s controller module is not ready", __func__); return (BTM_NO_RESOURCES); } BTM_TRACE_DEBUG("before update sec_flags=0x%x", p_dev_rec->sec_flags); /* Finished if connection is active and already paired */ if (((p_dev_rec->hci_handle != BTM_SEC_INVALID_HANDLE) && transport == BT_TRANSPORT_BR_EDR && (p_dev_rec->sec_flags & BTM_SEC_AUTHENTICATED)) || ((p_dev_rec->ble_hci_handle != BTM_SEC_INVALID_HANDLE) && transport == BT_TRANSPORT_LE && (p_dev_rec->sec_flags & BTM_SEC_LE_AUTHENTICATED))) { BTM_TRACE_WARNING("BTM_SecBond -> Already Paired"); return (BTM_SUCCESS); } /* Tell controller to get rid of the link key if it has one stored */ if ((BTM_DeleteStoredLinkKey(bd_addr, NULL)) != BTM_SUCCESS) return (BTM_NO_RESOURCES); /* Save the PIN code if we got a valid one */ if (p_pin && (pin_len <= PIN_CODE_LEN) && (pin_len != 0)) { btm_cb.pin_code_len = pin_len; p_dev_rec->pin_code_length = pin_len; memcpy(btm_cb.pin_code, p_pin, PIN_CODE_LEN); } memcpy(btm_cb.pairing_bda, bd_addr, BD_ADDR_LEN); btm_cb.pairing_flags = BTM_PAIR_FLAGS_WE_STARTED_DD; p_dev_rec->security_required = BTM_SEC_OUT_AUTHENTICATE; p_dev_rec->is_originator = true; if (trusted_mask) BTM_SEC_COPY_TRUSTED_DEVICE(trusted_mask, p_dev_rec->trusted_mask); if (transport == BT_TRANSPORT_LE) { btm_ble_init_pseudo_addr(p_dev_rec, bd_addr); p_dev_rec->sec_flags &= ~BTM_SEC_LE_MASK; if (SMP_Pair(bd_addr) == SMP_STARTED) { btm_cb.pairing_flags |= BTM_PAIR_FLAGS_LE_ACTIVE; p_dev_rec->sec_state = BTM_SEC_STATE_AUTHENTICATING; btm_sec_change_pairing_state(BTM_PAIR_STATE_WAIT_AUTH_COMPLETE); return BTM_CMD_STARTED; } btm_cb.pairing_flags = 0; return (BTM_NO_RESOURCES); } p_dev_rec->sec_flags &= ~(BTM_SEC_LINK_KEY_KNOWN | BTM_SEC_AUTHENTICATED | BTM_SEC_ENCRYPTED | BTM_SEC_ROLE_SWITCHED | BTM_SEC_LINK_KEY_AUTHED); BTM_TRACE_DEBUG("after update sec_flags=0x%x", p_dev_rec->sec_flags); if (!controller_get_interface()->supports_simple_pairing()) { /* The special case when we authenticate keyboard. Set pin type to fixed */ /* It would be probably better to do it from the application, but it is */ /* complicated */ if (((p_dev_rec->dev_class[1] & BTM_COD_MAJOR_CLASS_MASK) == BTM_COD_MAJOR_PERIPHERAL) && (p_dev_rec->dev_class[2] & BTM_COD_MINOR_KEYBOARD) && (btm_cb.cfg.pin_type != HCI_PIN_TYPE_FIXED)) { btm_cb.pin_type_changed = true; btsnd_hcic_write_pin_type(HCI_PIN_TYPE_FIXED); } } for (ii = 0; ii <= HCI_EXT_FEATURES_PAGE_MAX; ii++) { p_features = p_dev_rec->feature_pages[ii]; BTM_TRACE_EVENT(" remote_features page[%1d] = %02x-%02x-%02x-%02x", ii, p_features[0], p_features[1], p_features[2], p_features[3]); BTM_TRACE_EVENT(" %02x-%02x-%02x-%02x", p_features[4], p_features[5], p_features[6], p_features[7]); } BTM_TRACE_EVENT("BTM_SecBond: Remote sm4: 0x%x HCI Handle: 0x%04x", p_dev_rec->sm4, p_dev_rec->hci_handle); #if (BTM_SEC_FORCE_RNR_FOR_DBOND == TRUE) p_dev_rec->sec_flags &= ~BTM_SEC_NAME_KNOWN; #endif /* If connection already exists... */ if (p && p->hci_handle != BTM_SEC_INVALID_HANDLE) { btm_sec_start_authentication(p_dev_rec); btm_sec_change_pairing_state(BTM_PAIR_STATE_WAIT_PIN_REQ); /* Mark lcb as bonding */ l2cu_update_lcb_4_bonding(bd_addr, true); return (BTM_CMD_STARTED); } BTM_TRACE_DEBUG("sec mode: %d sm4:x%x", btm_cb.security_mode, p_dev_rec->sm4); if (!controller_get_interface()->supports_simple_pairing() || (p_dev_rec->sm4 == BTM_SM4_KNOWN)) { if (btm_sec_check_prefetch_pin(p_dev_rec)) return (BTM_CMD_STARTED); } if ((btm_cb.security_mode == BTM_SEC_MODE_SP || btm_cb.security_mode == BTM_SEC_MODE_SP_DEBUG || btm_cb.security_mode == BTM_SEC_MODE_SC) && BTM_SEC_IS_SM4_UNKNOWN(p_dev_rec->sm4)) { /* local is 2.1 and peer is unknown */ if ((p_dev_rec->sm4 & BTM_SM4_CONN_PEND) == 0) { /* we are not accepting connection request from peer * -> RNR (to learn if peer is 2.1) * RNR when no ACL causes HCI_RMT_HOST_SUP_FEAT_NOTIFY_EVT */ btm_sec_change_pairing_state(BTM_PAIR_STATE_GET_REM_NAME); status = BTM_ReadRemoteDeviceName(bd_addr, NULL, BT_TRANSPORT_BR_EDR); } else { /* We are accepting connection request from peer */ btm_sec_change_pairing_state(BTM_PAIR_STATE_WAIT_PIN_REQ); status = BTM_CMD_STARTED; } BTM_TRACE_DEBUG("State:%s sm4: 0x%x sec_state:%d", btm_pair_state_descr(btm_cb.pairing_state), p_dev_rec->sm4, p_dev_rec->sec_state); } else { /* both local and peer are 2.1 */ status = btm_sec_dd_create_conn(p_dev_rec); } if (status != BTM_CMD_STARTED) { BTM_TRACE_ERROR( "%s BTM_ReadRemoteDeviceName or btm_sec_dd_create_conn error: 0x%x", __func__, (int)status); btm_sec_change_pairing_state(BTM_PAIR_STATE_IDLE); } return status; } /******************************************************************************* * * Function BTM_SecBondByTransport * * Description This function is called to perform bonding with peer device. * If the connection is already up, but not secure, pairing * is attempted. If already paired BTM_SUCCESS is returned. * * Parameters: bd_addr - Address of the device to bond * transport - doing SSP over BR/EDR or SMP over LE * pin_len - length in bytes of the PIN Code * p_pin - pointer to array with the PIN Code * trusted_mask - bitwise OR of trusted services * (array of uint32_t) * * Note: After 2.1 parameters are not used and preserved here not to change API ******************************************************************************/ tBTM_STATUS BTM_SecBondByTransport(BD_ADDR bd_addr, tBT_TRANSPORT transport, uint8_t pin_len, uint8_t* p_pin, uint32_t trusted_mask[]) { tBT_DEVICE_TYPE dev_type; tBLE_ADDR_TYPE addr_type; BTM_ReadDevInfo(bd_addr, &dev_type, &addr_type); /* LE device, do SMP pairing */ if ((transport == BT_TRANSPORT_LE && (dev_type & BT_DEVICE_TYPE_BLE) == 0) || (transport == BT_TRANSPORT_BR_EDR && (dev_type & BT_DEVICE_TYPE_BREDR) == 0)) { return BTM_ILLEGAL_ACTION; } return btm_sec_bond_by_transport(bd_addr, transport, pin_len, p_pin, trusted_mask); } /******************************************************************************* * * Function BTM_SecBond * * Description This function is called to perform bonding with peer device. * If the connection is already up, but not secure, pairing * is attempted. If already paired BTM_SUCCESS is returned. * * Parameters: bd_addr - Address of the device to bond * pin_len - length in bytes of the PIN Code * p_pin - pointer to array with the PIN Code * trusted_mask - bitwise OR of trusted services * (array of uint32_t) * * Note: After 2.1 parameters are not used and preserved here not to change API ******************************************************************************/ tBTM_STATUS BTM_SecBond(BD_ADDR bd_addr, uint8_t pin_len, uint8_t* p_pin, uint32_t trusted_mask[]) { tBT_TRANSPORT transport = BT_TRANSPORT_BR_EDR; if (BTM_UseLeLink(bd_addr)) transport = BT_TRANSPORT_LE; return btm_sec_bond_by_transport(bd_addr, transport, pin_len, p_pin, trusted_mask); } /******************************************************************************* * * Function BTM_SecBondCancel * * Description This function is called to cancel ongoing bonding process * with peer device. * * Parameters: bd_addr - Address of the peer device * transport - false for BR/EDR link; true for LE link * ******************************************************************************/ tBTM_STATUS BTM_SecBondCancel(BD_ADDR bd_addr) { tBTM_SEC_DEV_REC* p_dev_rec; BTM_TRACE_API("BTM_SecBondCancel() State: %s flags:0x%x", btm_pair_state_descr(btm_cb.pairing_state), btm_cb.pairing_flags); p_dev_rec = btm_find_dev(bd_addr); if ((p_dev_rec == NULL) || (memcmp(btm_cb.pairing_bda, bd_addr, BD_ADDR_LEN) != 0)) { return BTM_UNKNOWN_ADDR; } if (btm_cb.pairing_flags & BTM_PAIR_FLAGS_LE_ACTIVE) { if (p_dev_rec->sec_state == BTM_SEC_STATE_AUTHENTICATING) { BTM_TRACE_DEBUG("Cancel LE pairing"); if (SMP_PairCancel(bd_addr)) { return BTM_CMD_STARTED; } } return BTM_WRONG_MODE; } BTM_TRACE_DEBUG("hci_handle:0x%x sec_state:%d", p_dev_rec->hci_handle, p_dev_rec->sec_state); if (BTM_PAIR_STATE_WAIT_LOCAL_PIN == btm_cb.pairing_state && BTM_PAIR_FLAGS_WE_STARTED_DD & btm_cb.pairing_flags) { /* pre-fetching pin for dedicated bonding */ btm_sec_bond_cancel_complete(); return BTM_SUCCESS; } /* If this BDA is in a bonding procedure */ if ((btm_cb.pairing_state != BTM_PAIR_STATE_IDLE) && (btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD)) { /* If the HCI link is up */ if (p_dev_rec->hci_handle != BTM_SEC_INVALID_HANDLE) { /* If some other thread disconnecting, we do not send second command */ if ((p_dev_rec->sec_state == BTM_SEC_STATE_DISCONNECTING) || (p_dev_rec->sec_state == BTM_SEC_STATE_DISCONNECTING_BOTH)) return (BTM_CMD_STARTED); /* If the HCI link was set up by Bonding process */ if (btm_cb.pairing_flags & BTM_PAIR_FLAGS_DISC_WHEN_DONE) return btm_sec_send_hci_disconnect(p_dev_rec, HCI_ERR_PEER_USER, p_dev_rec->hci_handle); else l2cu_update_lcb_4_bonding(bd_addr, false); return BTM_NOT_AUTHORIZED; } else /*HCI link is not up */ { /* If the HCI link creation was started by Bonding process */ if (btm_cb.pairing_flags & BTM_PAIR_FLAGS_DISC_WHEN_DONE) { btsnd_hcic_create_conn_cancel(bd_addr); return BTM_CMD_STARTED; } if (btm_cb.pairing_state == BTM_PAIR_STATE_GET_REM_NAME) { BTM_CancelRemoteDeviceName(); btm_cb.pairing_flags |= BTM_PAIR_FLAGS_WE_CANCEL_DD; return BTM_CMD_STARTED; } return BTM_NOT_AUTHORIZED; } } return BTM_WRONG_MODE; } /******************************************************************************* * * Function BTM_SecGetDeviceLinkKey * * Description This function is called to obtain link key for the device * it returns BTM_SUCCESS if link key is available, or * BTM_UNKNOWN_ADDR if Security Manager does not know about * the device or device record does not contain link key info * * Parameters: bd_addr - Address of the device * link_key - Link Key is copied into this array * ******************************************************************************/ tBTM_STATUS BTM_SecGetDeviceLinkKey(BD_ADDR bd_addr, LINK_KEY link_key) { tBTM_SEC_DEV_REC* p_dev_rec; p_dev_rec = btm_find_dev(bd_addr); if ((p_dev_rec != NULL) && (p_dev_rec->sec_flags & BTM_SEC_LINK_KEY_KNOWN)) { memcpy(link_key, p_dev_rec->link_key, LINK_KEY_LEN); return (BTM_SUCCESS); } return (BTM_UNKNOWN_ADDR); } /******************************************************************************* * * Function BTM_SecGetDeviceLinkKeyType * * Description This function is called to obtain link key type for the * device. * it returns BTM_SUCCESS if link key is available, or * BTM_UNKNOWN_ADDR if Security Manager does not know about * the device or device record does not contain link key info * * Returns BTM_LKEY_TYPE_IGNORE if link key is unknown, link type * otherwise. * ******************************************************************************/ tBTM_LINK_KEY_TYPE BTM_SecGetDeviceLinkKeyType(BD_ADDR bd_addr) { tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr); if ((p_dev_rec != NULL) && (p_dev_rec->sec_flags & BTM_SEC_LINK_KEY_KNOWN)) { return p_dev_rec->link_key_type; } return BTM_LKEY_TYPE_IGNORE; } /******************************************************************************* * * Function BTM_SetEncryption * * Description This function is called to ensure that connection is * encrypted. Should be called only on an open connection. * Typically only needed for connections that first want to * bring up unencrypted links, then later encrypt them. * * Parameters: bd_addr - Address of the peer device * transport - Link transport * p_callback - Pointer to callback function called if * this function returns PENDING after required * procedures are completed. Can be set to * NULL if status is not desired. * p_ref_data - pointer to any data the caller wishes to * receive in the callback function upon * completion. can be set to NULL if not used. * sec_act - LE security action, unused for BR/EDR * * Returns BTM_SUCCESS - already encrypted * BTM_PENDING - command will be returned in the callback * BTM_WRONG_MODE- connection not up. * BTM_BUSY - security procedures are currently active * BTM_MODE_UNSUPPORTED - if security manager not linked in. * ******************************************************************************/ tBTM_STATUS BTM_SetEncryption(BD_ADDR bd_addr, tBT_TRANSPORT transport, tBTM_SEC_CBACK* p_callback, void* p_ref_data, tBTM_BLE_SEC_ACT sec_act) { tBTM_STATUS rc = 0; tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr); if (!p_dev_rec || (transport == BT_TRANSPORT_BR_EDR && p_dev_rec->hci_handle == BTM_SEC_INVALID_HANDLE) || (transport == BT_TRANSPORT_LE && p_dev_rec->ble_hci_handle == BTM_SEC_INVALID_HANDLE)) { /* Connection should be up and runnning */ BTM_TRACE_WARNING("Security Manager: BTM_SetEncryption not connected"); if (p_callback) (*p_callback)(bd_addr, transport, p_ref_data, BTM_WRONG_MODE); return (BTM_WRONG_MODE); } if (transport == BT_TRANSPORT_BR_EDR && (p_dev_rec->sec_flags & BTM_SEC_ENCRYPTED)) { BTM_TRACE_EVENT("Security Manager: BTM_SetEncryption already encrypted"); if (p_callback) (*p_callback)(bd_addr, transport, p_ref_data, BTM_SUCCESS); return (BTM_SUCCESS); } /* enqueue security request if security is active */ if (p_dev_rec->p_callback || (p_dev_rec->sec_state != BTM_SEC_STATE_IDLE)) { BTM_TRACE_WARNING( "Security Manager: BTM_SetEncryption busy, enqueue request"); if (btm_sec_queue_encrypt_request(bd_addr, transport, p_callback, p_ref_data, sec_act)) { return BTM_CMD_STARTED; } else { if (p_callback) (*p_callback)(bd_addr, transport, p_ref_data, BTM_NO_RESOURCES); return BTM_NO_RESOURCES; } } p_dev_rec->p_callback = p_callback; p_dev_rec->p_ref_data = p_ref_data; p_dev_rec->security_required |= (BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_ENCRYPT); p_dev_rec->is_originator = false; BTM_TRACE_API( "Security Manager: BTM_SetEncryption Handle:%d State:%d Flags:0x%x " "Required:0x%x", p_dev_rec->hci_handle, p_dev_rec->sec_state, p_dev_rec->sec_flags, p_dev_rec->security_required); if (transport == BT_TRANSPORT_LE) { tACL_CONN* p = btm_bda_to_acl(bd_addr, transport); if (p) { rc = btm_ble_set_encryption(bd_addr, sec_act, p->link_role); } else { rc = BTM_WRONG_MODE; BTM_TRACE_WARNING("%s: cannot call btm_ble_set_encryption, p is NULL", __func__); } } else { rc = btm_sec_execute_procedure(p_dev_rec); } if (rc != BTM_CMD_STARTED && rc != BTM_BUSY) { if (p_callback) { p_dev_rec->p_callback = NULL; (*p_callback)(bd_addr, transport, p_dev_rec->p_ref_data, rc); } } return (rc); } /******************************************************************************* * disconnect the ACL link, if it's not done yet. ******************************************************************************/ static tBTM_STATUS btm_sec_send_hci_disconnect(tBTM_SEC_DEV_REC* p_dev_rec, uint8_t reason, uint16_t conn_handle) { uint8_t old_state = p_dev_rec->sec_state; tBTM_STATUS status = BTM_CMD_STARTED; BTM_TRACE_EVENT("btm_sec_send_hci_disconnect: handle:0x%x, reason=0x%x", conn_handle, reason); /* send HCI_Disconnect on a transport only once */ switch (old_state) { case BTM_SEC_STATE_DISCONNECTING: if (conn_handle == p_dev_rec->hci_handle) return status; p_dev_rec->sec_state = BTM_SEC_STATE_DISCONNECTING_BOTH; break; case BTM_SEC_STATE_DISCONNECTING_BLE: if (conn_handle == p_dev_rec->ble_hci_handle) return status; p_dev_rec->sec_state = BTM_SEC_STATE_DISCONNECTING_BOTH; break; case BTM_SEC_STATE_DISCONNECTING_BOTH: return status; default: p_dev_rec->sec_state = (conn_handle == p_dev_rec->hci_handle) ? BTM_SEC_STATE_DISCONNECTING : BTM_SEC_STATE_DISCONNECTING_BLE; break; } /* If a role switch is in progress, delay the HCI Disconnect to avoid * controller problem */ if (p_dev_rec->rs_disc_pending == BTM_SEC_RS_PENDING && p_dev_rec->hci_handle == conn_handle) { BTM_TRACE_DEBUG( "RS in progress - Set DISC Pending flag in btm_sec_send_hci_disconnect " "to delay disconnect"); p_dev_rec->rs_disc_pending = BTM_SEC_DISC_PENDING; status = BTM_SUCCESS; } /* Tear down the HCI link */ else { btsnd_hcic_disconnect(conn_handle, reason); } return status; } /******************************************************************************* * * Function BTM_ConfirmReqReply * * Description This function is called to confirm the numeric value for * Simple Pairing in response to BTM_SP_CFM_REQ_EVT * * Parameters: res - result of the operation BTM_SUCCESS if * success * bd_addr - Address of the peer device * ******************************************************************************/ void BTM_ConfirmReqReply(tBTM_STATUS res, BD_ADDR bd_addr) { tBTM_SEC_DEV_REC* p_dev_rec; BTM_TRACE_EVENT("BTM_ConfirmReqReply() State: %s Res: %u", btm_pair_state_descr(btm_cb.pairing_state), res); /* If timeout already expired or has been canceled, ignore the reply */ if ((btm_cb.pairing_state != BTM_PAIR_STATE_WAIT_NUMERIC_CONFIRM) || (memcmp(btm_cb.pairing_bda, bd_addr, BD_ADDR_LEN) != 0)) return; btm_sec_change_pairing_state(BTM_PAIR_STATE_WAIT_AUTH_COMPLETE); if ((res == BTM_SUCCESS) || (res == BTM_SUCCESS_NO_SECURITY)) { btm_cb.acl_disc_reason = HCI_SUCCESS; if (res == BTM_SUCCESS) { p_dev_rec = btm_find_dev(bd_addr); if (p_dev_rec != NULL) { p_dev_rec->sec_flags |= BTM_SEC_LINK_KEY_AUTHED; p_dev_rec->sec_flags |= BTM_SEC_16_DIGIT_PIN_AUTHED; } } btsnd_hcic_user_conf_reply(bd_addr, true); } else { /* Report authentication failed event from state * BTM_PAIR_STATE_WAIT_AUTH_COMPLETE */ btm_cb.acl_disc_reason = HCI_ERR_HOST_REJECT_SECURITY; btsnd_hcic_user_conf_reply(bd_addr, false); } } /******************************************************************************* * * Function BTM_PasskeyReqReply * * Description This function is called to provide the passkey for * Simple Pairing in response to BTM_SP_KEY_REQ_EVT * * Parameters: res - result of the operation BTM_SUCCESS if success * bd_addr - Address of the peer device * passkey - numeric value in the range of * BTM_MIN_PASSKEY_VAL(0) - * BTM_MAX_PASSKEY_VAL(999999(0xF423F)). * ******************************************************************************/ #if (BTM_LOCAL_IO_CAPS != BTM_IO_CAP_NONE) void BTM_PasskeyReqReply(tBTM_STATUS res, BD_ADDR bd_addr, uint32_t passkey) { BTM_TRACE_API("BTM_PasskeyReqReply: State: %s res:%d", btm_pair_state_descr(btm_cb.pairing_state), res); if ((btm_cb.pairing_state == BTM_PAIR_STATE_IDLE) || (memcmp(btm_cb.pairing_bda, bd_addr, BD_ADDR_LEN) != 0)) { return; } /* If timeout already expired or has been canceled, ignore the reply */ if ((btm_cb.pairing_state == BTM_PAIR_STATE_WAIT_AUTH_COMPLETE) && (res != BTM_SUCCESS)) { tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr); if (p_dev_rec != NULL) { btm_cb.acl_disc_reason = HCI_ERR_HOST_REJECT_SECURITY; if (p_dev_rec->hci_handle != BTM_SEC_INVALID_HANDLE) btm_sec_send_hci_disconnect(p_dev_rec, HCI_ERR_AUTH_FAILURE, p_dev_rec->hci_handle); else BTM_SecBondCancel(bd_addr); p_dev_rec->sec_flags &= ~(BTM_SEC_LINK_KEY_AUTHED | BTM_SEC_LINK_KEY_KNOWN); btm_sec_change_pairing_state(BTM_PAIR_STATE_IDLE); return; } } else if (btm_cb.pairing_state != BTM_PAIR_STATE_KEY_ENTRY) return; if (passkey > BTM_MAX_PASSKEY_VAL) res = BTM_ILLEGAL_VALUE; btm_sec_change_pairing_state(BTM_PAIR_STATE_WAIT_AUTH_COMPLETE); if (res != BTM_SUCCESS) { /* use BTM_PAIR_STATE_WAIT_AUTH_COMPLETE to report authentication failed * event */ btm_cb.acl_disc_reason = HCI_ERR_HOST_REJECT_SECURITY; btsnd_hcic_user_passkey_neg_reply(bd_addr); } else { btm_cb.acl_disc_reason = HCI_SUCCESS; btsnd_hcic_user_passkey_reply(bd_addr, passkey); } } #endif /******************************************************************************* * * Function BTM_SendKeypressNotif * * Description This function is used during the passkey entry model * by a device with KeyboardOnly IO capabilities * (very likely to be a HID Device). * It is called by a HID Device to inform the remote device * when a key has been entered or erased. * * Parameters: bd_addr - Address of the peer device * type - notification type * ******************************************************************************/ #if (BTM_LOCAL_IO_CAPS != BTM_IO_CAP_NONE) void BTM_SendKeypressNotif(BD_ADDR bd_addr, tBTM_SP_KEY_TYPE type) { /* This API only make sense between PASSKEY_REQ and SP complete */ if (btm_cb.pairing_state == BTM_PAIR_STATE_KEY_ENTRY) btsnd_hcic_send_keypress_notif(bd_addr, type); } #endif /******************************************************************************* * * Function BTM_IoCapRsp * * Description This function is called in response to BTM_SP_IO_REQ_EVT * When the event data io_req.oob_data is set to * BTM_OOB_UNKNOWN by the tBTM_SP_CALLBACK implementation, * this function is called to provide the actual response * * Parameters: bd_addr - Address of the peer device * io_cap - The IO capability of local device. * oob - BTM_OOB_NONE or BTM_OOB_PRESENT. * auth_req- MITM protection required or not. * ******************************************************************************/ void BTM_IoCapRsp(BD_ADDR bd_addr, tBTM_IO_CAP io_cap, tBTM_OOB_DATA oob, tBTM_AUTH_REQ auth_req) { BTM_TRACE_EVENT("BTM_IoCapRsp: state: %s oob: %d io_cap: %d", btm_pair_state_descr(btm_cb.pairing_state), oob, io_cap); if ((btm_cb.pairing_state != BTM_PAIR_STATE_WAIT_LOCAL_IOCAPS) || (memcmp(btm_cb.pairing_bda, bd_addr, BD_ADDR_LEN) != 0)) return; if (oob < BTM_OOB_UNKNOWN && io_cap < BTM_IO_CAP_MAX) { btm_cb.devcb.loc_auth_req = auth_req; btm_cb.devcb.loc_io_caps = io_cap; if (btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) auth_req = (BTM_AUTH_DD_BOND | (auth_req & BTM_AUTH_YN_BIT)); btsnd_hcic_io_cap_req_reply(bd_addr, io_cap, oob, auth_req); } } /******************************************************************************* * * Function BTM_ReadLocalOobData * * Description This function is called to read the local OOB data from * LM * ******************************************************************************/ void BTM_ReadLocalOobData(void) { btsnd_hcic_read_local_oob_data(); } /******************************************************************************* * * Function BTM_RemoteOobDataReply * * Description This function is called to provide the remote OOB data for * Simple Pairing in response to BTM_SP_RMT_OOB_EVT * * Parameters: bd_addr - Address of the peer device * c - simple pairing Hash C. * r - simple pairing Randomizer C. * ******************************************************************************/ void BTM_RemoteOobDataReply(tBTM_STATUS res, BD_ADDR bd_addr, BT_OCTET16 c, BT_OCTET16 r) { BTM_TRACE_EVENT("%s() - State: %s res: %d", __func__, btm_pair_state_descr(btm_cb.pairing_state), res); /* If timeout already expired or has been canceled, ignore the reply */ if (btm_cb.pairing_state != BTM_PAIR_STATE_WAIT_LOCAL_OOB_RSP) return; btm_sec_change_pairing_state(BTM_PAIR_STATE_WAIT_AUTH_COMPLETE); if (res != BTM_SUCCESS) { /* use BTM_PAIR_STATE_WAIT_AUTH_COMPLETE to report authentication failed * event */ btm_cb.acl_disc_reason = HCI_ERR_HOST_REJECT_SECURITY; btsnd_hcic_rem_oob_neg_reply(bd_addr); } else { btm_cb.acl_disc_reason = HCI_SUCCESS; btsnd_hcic_rem_oob_reply(bd_addr, c, r); } } /******************************************************************************* * * Function BTM_BuildOobData * * Description This function is called to build the OOB data payload to * be sent over OOB (non-Bluetooth) link * * Parameters: p_data - the location for OOB data * max_len - p_data size. * c - simple pairing Hash C. * r - simple pairing Randomizer C. * name_len- 0, local device name would not be included. * otherwise, the local device name is included for * up to this specified length * * Returns Number of bytes in p_data. * ******************************************************************************/ uint16_t BTM_BuildOobData(uint8_t* p_data, uint16_t max_len, BT_OCTET16 c, BT_OCTET16 r, uint8_t name_len) { uint8_t* p = p_data; uint16_t len = 0; uint16_t name_size; uint8_t name_type = BTM_EIR_SHORTENED_LOCAL_NAME_TYPE; if (p_data && max_len >= BTM_OOB_MANDATORY_SIZE) { /* add mandatory part */ UINT16_TO_STREAM(p, len); BDADDR_TO_STREAM(p, controller_get_interface()->get_address()->address); len = BTM_OOB_MANDATORY_SIZE; max_len -= len; /* now optional part */ /* add Hash C */ uint16_t delta = BTM_OOB_HASH_C_SIZE + 2; if (max_len >= delta) { *p++ = BTM_OOB_HASH_C_SIZE + 1; *p++ = BTM_EIR_OOB_SSP_HASH_C_TYPE; ARRAY_TO_STREAM(p, c, BTM_OOB_HASH_C_SIZE); len += delta; max_len -= delta; } /* add Rand R */ delta = BTM_OOB_RAND_R_SIZE + 2; if (max_len >= delta) { *p++ = BTM_OOB_RAND_R_SIZE + 1; *p++ = BTM_EIR_OOB_SSP_RAND_R_TYPE; ARRAY_TO_STREAM(p, r, BTM_OOB_RAND_R_SIZE); len += delta; max_len -= delta; } /* add class of device */ delta = BTM_OOB_COD_SIZE + 2; if (max_len >= delta) { *p++ = BTM_OOB_COD_SIZE + 1; *p++ = BTM_EIR_OOB_COD_TYPE; DEVCLASS_TO_STREAM(p, btm_cb.devcb.dev_class); len += delta; max_len -= delta; } name_size = name_len; if (name_size > strlen(btm_cb.cfg.bd_name)) { name_type = BTM_EIR_COMPLETE_LOCAL_NAME_TYPE; name_size = (uint16_t)strlen(btm_cb.cfg.bd_name); } delta = name_size + 2; if (max_len >= delta) { *p++ = name_size + 1; *p++ = name_type; ARRAY_TO_STREAM(p, btm_cb.cfg.bd_name, name_size); len += delta; max_len -= delta; } /* update len */ p = p_data; UINT16_TO_STREAM(p, len); } return len; } /******************************************************************************* * * Function BTM_BothEndsSupportSecureConnections * * Description This function is called to check if both the local device * and the peer device specified by bd_addr support BR/EDR * Secure Connections. * * Parameters: bd_addr - address of the peer * * Returns true if BR/EDR Secure Connections are supported by both * local and the remote device, else false. * ******************************************************************************/ bool BTM_BothEndsSupportSecureConnections(BD_ADDR bd_addr) { return ((controller_get_interface()->supports_secure_connections()) && (BTM_PeerSupportsSecureConnections(bd_addr))); } /******************************************************************************* * * Function BTM_PeerSupportsSecureConnections * * Description This function is called to check if the peer supports * BR/EDR Secure Connections. * * Parameters: bd_addr - address of the peer * * Returns true if BR/EDR Secure Connections are supported by the peer, * else false. * ******************************************************************************/ bool BTM_PeerSupportsSecureConnections(BD_ADDR bd_addr) { tBTM_SEC_DEV_REC* p_dev_rec; p_dev_rec = btm_find_dev(bd_addr); if (p_dev_rec == NULL) { BTM_TRACE_WARNING("%s: unknown BDA: %08x%04x", __func__, (bd_addr[0] << 24) + (bd_addr[1] << 16) + (bd_addr[2] << 8) + bd_addr[3], (bd_addr[4] << 8) + bd_addr[5]); return false; } return (p_dev_rec->remote_supports_secure_connections); } /******************************************************************************* * * Function BTM_ReadOobData * * Description This function is called to parse the OOB data payload * received over OOB (non-Bluetooth) link * * Parameters: p_data - the location for OOB data * eir_tag - The associated EIR tag to read the data. * *p_len(output) - the length of the data with the given tag. * * Returns the beginning of the data with the given tag. * NULL, if the tag is not found. * ******************************************************************************/ uint8_t* BTM_ReadOobData(uint8_t* p_data, uint8_t eir_tag, uint8_t* p_len) { uint8_t* p = p_data; uint16_t max_len; uint8_t len, type; uint8_t* p_ret = NULL; uint8_t ret_len = 0; if (p_data) { STREAM_TO_UINT16(max_len, p); if (max_len >= BTM_OOB_MANDATORY_SIZE) { if (BTM_EIR_OOB_BD_ADDR_TYPE == eir_tag) { p_ret = p; /* the location for bd_addr */ ret_len = BTM_OOB_BD_ADDR_SIZE; } else { p += BD_ADDR_LEN; max_len -= BTM_OOB_MANDATORY_SIZE; /* now the optional data in EIR format */ while (max_len > 0) { len = *p++; /* tag data len + 1 */ type = *p++; if (eir_tag == type) { p_ret = p; ret_len = len - 1; break; } /* the data size of this tag is len + 1 (tag data len + 2) */ if (max_len > len) { max_len -= len; max_len--; len--; p += len; } else max_len = 0; } } } } if (p_len) *p_len = ret_len; return p_ret; } /******************************************************************************* * * Function BTM_SetOutService * * Description This function is called to set the service for * outgoing connections. * * If the profile/application calls BTM_SetSecurityLevel * before initiating a connection, this function does not * need to be called. * * Returns void * ******************************************************************************/ void BTM_SetOutService(BD_ADDR bd_addr, uint8_t service_id, uint32_t mx_chan_id) { tBTM_SEC_DEV_REC* p_dev_rec; tBTM_SEC_SERV_REC* p_serv_rec = &btm_cb.sec_serv_rec[0]; btm_cb.p_out_serv = p_serv_rec; p_dev_rec = btm_find_dev(bd_addr); for (int i = 0; i < BTM_SEC_MAX_SERVICE_RECORDS; i++, p_serv_rec++) { if ((p_serv_rec->security_flags & BTM_SEC_IN_USE) && (p_serv_rec->service_id == service_id) && (p_serv_rec->orig_mx_chan_id == mx_chan_id)) { BTM_TRACE_API( "BTM_SetOutService p_out_serv id %d, psm 0x%04x, proto_id %d, " "chan_id %d", p_serv_rec->service_id, p_serv_rec->psm, p_serv_rec->mx_proto_id, p_serv_rec->orig_mx_chan_id); btm_cb.p_out_serv = p_serv_rec; if (p_dev_rec) p_dev_rec->p_cur_service = p_serv_rec; break; } } } /************************************************************************ * I N T E R N A L F U N C T I O N S ************************************************************************/ /******************************************************************************* * * Function btm_sec_is_upgrade_possible * * Description This function returns true if the existing link key * can be upgraded or if the link key does not exist. * * Returns bool * ******************************************************************************/ static bool btm_sec_is_upgrade_possible(tBTM_SEC_DEV_REC* p_dev_rec, bool is_originator) { uint16_t mtm_check = is_originator ? BTM_SEC_OUT_MITM : BTM_SEC_IN_MITM; bool is_possible = true; if (p_dev_rec->sec_flags & BTM_SEC_LINK_KEY_KNOWN) { is_possible = false; if (p_dev_rec->p_cur_service) { BTM_TRACE_DEBUG( "%s() id: %d, link_key_typet: %d, rmt_io_caps: %d, chk flags: 0x%x, " "flags: 0x%x", __func__, p_dev_rec->p_cur_service->service_id, p_dev_rec->link_key_type, p_dev_rec->rmt_io_caps, mtm_check, p_dev_rec->p_cur_service->security_flags); } else { BTM_TRACE_DEBUG( "%s() link_key_typet: %d, rmt_io_caps: %d, chk flags: 0x%x", __func__, p_dev_rec->link_key_type, p_dev_rec->rmt_io_caps, mtm_check); } /* Already have a link key to the connected peer. Is the link key secure *enough? ** Is a link key upgrade even possible? */ if ((p_dev_rec->security_required & mtm_check) /* needs MITM */ && ((p_dev_rec->link_key_type == BTM_LKEY_TYPE_UNAUTH_COMB) || (p_dev_rec->link_key_type == BTM_LKEY_TYPE_UNAUTH_COMB_P_256)) /* has unauthenticated link key */ && (p_dev_rec->rmt_io_caps < BTM_IO_CAP_MAX) /* a valid peer IO cap */ && (btm_sec_io_map[p_dev_rec->rmt_io_caps][btm_cb.devcb.loc_io_caps])) /* authenticated link key is possible */ { /* upgrade is possible: check if the application wants the upgrade. * If the application is configured to use a global MITM flag, * it probably would not want to upgrade the link key based on the * security level database */ is_possible = true; } } BTM_TRACE_DEBUG("%s() is_possible: %d sec_flags: 0x%x", __func__, is_possible, p_dev_rec->sec_flags); return is_possible; } /******************************************************************************* * * Function btm_sec_check_upgrade * * Description This function is called to check if the existing link key * needs to be upgraded. * * Returns void * ******************************************************************************/ static void btm_sec_check_upgrade(tBTM_SEC_DEV_REC* p_dev_rec, bool is_originator) { BTM_TRACE_DEBUG("%s()", __func__); /* Only check if link key already exists */ if (!(p_dev_rec->sec_flags & BTM_SEC_LINK_KEY_KNOWN)) return; if (btm_sec_is_upgrade_possible(p_dev_rec, is_originator) == true) { BTM_TRACE_DEBUG("need upgrade!! sec_flags:0x%x", p_dev_rec->sec_flags); /* upgrade is possible: check if the application wants the upgrade. * If the application is configured to use a global MITM flag, * it probably would not want to upgrade the link key based on the security * level database */ tBTM_SP_UPGRADE evt_data; memcpy(evt_data.bd_addr, p_dev_rec->bd_addr, BD_ADDR_LEN); evt_data.upgrade = true; if (btm_cb.api.p_sp_callback) (*btm_cb.api.p_sp_callback)(BTM_SP_UPGRADE_EVT, (tBTM_SP_EVT_DATA*)&evt_data); BTM_TRACE_DEBUG("evt_data.upgrade:0x%x", evt_data.upgrade); if (evt_data.upgrade) { /* if the application confirms the upgrade, set the upgrade bit */ p_dev_rec->sm4 |= BTM_SM4_UPGRADE; /* Clear the link key known to go through authentication/pairing again */ p_dev_rec->sec_flags &= ~(BTM_SEC_LINK_KEY_KNOWN | BTM_SEC_LINK_KEY_AUTHED); p_dev_rec->sec_flags &= ~BTM_SEC_AUTHENTICATED; BTM_TRACE_DEBUG("sec_flags:0x%x", p_dev_rec->sec_flags); } } } /******************************************************************************* * * Function btm_sec_l2cap_access_req * * Description This function is called by the L2CAP to grant permission to * establish L2CAP connection to or from the peer device. * * Parameters: bd_addr - Address of the peer device * psm - L2CAP PSM * is_originator - true if protocol above L2CAP originates * connection * p_callback - Pointer to callback function called if * this function returns PENDING after required * procedures are complete. MUST NOT BE NULL. * * Returns tBTM_STATUS * ******************************************************************************/ tBTM_STATUS btm_sec_l2cap_access_req(BD_ADDR bd_addr, uint16_t psm, uint16_t handle, CONNECTION_TYPE conn_type, tBTM_SEC_CALLBACK* p_callback, void* p_ref_data) { tBTM_SEC_DEV_REC* p_dev_rec; tBTM_SEC_SERV_REC* p_serv_rec; uint16_t security_required; uint16_t old_security_required; bool old_is_originator; tBTM_STATUS rc = BTM_SUCCESS; bool chk_acp_auth_done = false; bool is_originator; tBT_TRANSPORT transport = BT_TRANSPORT_BR_EDR; /* should check PSM range in LE connection oriented L2CAP connection */ #if (L2CAP_UCD_INCLUDED == TRUE) if (conn_type & CONNECTION_TYPE_ORIG_MASK) is_originator = true; else is_originator = false; BTM_TRACE_DEBUG("%s() conn_type: 0x%x, 0x%x", __func__, conn_type, p_ref_data); #else is_originator = conn_type; BTM_TRACE_DEBUG("%s() is_originator:%d, 0x%x", __func__, is_originator, p_ref_data); #endif /* Find or get oldest record */ p_dev_rec = btm_find_or_alloc_dev(bd_addr); p_dev_rec->hci_handle = handle; /* Find the service record for the PSM */ p_serv_rec = btm_sec_find_first_serv(conn_type, psm); /* If there is no application registered with this PSM do not allow connection */ if (!p_serv_rec) { BTM_TRACE_WARNING("%s() PSM: %d no application registerd", __func__, psm); (*p_callback)(bd_addr, transport, p_ref_data, BTM_MODE_UNSUPPORTED); return (BTM_MODE_UNSUPPORTED); } /* Services level0 by default have no security */ if ((btm_sec_is_serv_level0(psm)) && (!btm_cb.devcb.secure_connections_only)) { (*p_callback)(bd_addr, transport, p_ref_data, BTM_SUCCESS_NO_SECURITY); return (BTM_SUCCESS); } #if (L2CAP_UCD_INCLUDED == TRUE) if (conn_type & CONNECTION_TYPE_CONNLESS_MASK) { if (btm_cb.security_mode == BTM_SEC_MODE_SC) { security_required = btm_sec_set_serv_level4_flags( p_serv_rec->ucd_security_flags, is_originator); } else { security_required = p_serv_rec->ucd_security_flags; } rc = BTM_CMD_STARTED; if (is_originator) { if (((security_required & BTM_SEC_OUT_FLAGS) == 0) || ((((security_required & BTM_SEC_OUT_FLAGS) == BTM_SEC_OUT_AUTHENTICATE) && (p_dev_rec->sec_flags & BTM_SEC_AUTHENTICATED))) || ((((security_required & BTM_SEC_OUT_FLAGS) == (BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_OUT_ENCRYPT)) && (p_dev_rec->sec_flags & BTM_SEC_ENCRYPTED))) || ((((security_required & BTM_SEC_OUT_FLAGS) == BTM_SEC_OUT_FLAGS) && (p_dev_rec->sec_flags & BTM_SEC_AUTHORIZED)))) { rc = BTM_SUCCESS; } } else { if (((security_required & BTM_SEC_IN_FLAGS) == 0) || ((((security_required & BTM_SEC_IN_FLAGS) == BTM_SEC_IN_AUTHENTICATE) && (p_dev_rec->sec_flags & BTM_SEC_AUTHENTICATED))) || ((((security_required & BTM_SEC_IN_FLAGS) == (BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_ENCRYPT)) && (p_dev_rec->sec_flags & BTM_SEC_ENCRYPTED))) || ((((security_required & BTM_SEC_IN_FLAGS) == BTM_SEC_IN_FLAGS) && (p_dev_rec->sec_flags & BTM_SEC_AUTHORIZED)))) { // Check for 16 digits (or MITM) if (((security_required & BTM_SEC_IN_MIN_16_DIGIT_PIN) == 0) || (((security_required & BTM_SEC_IN_MIN_16_DIGIT_PIN) == BTM_SEC_IN_MIN_16_DIGIT_PIN) && btm_dev_16_digit_authenticated(p_dev_rec))) { rc = BTM_SUCCESS; } } } if ((rc == BTM_SUCCESS) && (security_required & BTM_SEC_MODE4_LEVEL4) && (p_dev_rec->link_key_type != BTM_LKEY_TYPE_AUTH_COMB_P_256)) { rc = BTM_CMD_STARTED; } if (rc == BTM_SUCCESS) { if (p_callback) (*p_callback)(bd_addr, transport, (void*)p_ref_data, BTM_SUCCESS); return (BTM_SUCCESS); } } else #endif { if (btm_cb.security_mode == BTM_SEC_MODE_SC) { security_required = btm_sec_set_serv_level4_flags( p_serv_rec->security_flags, is_originator); } else { security_required = p_serv_rec->security_flags; } } BTM_TRACE_DEBUG( "%s: security_required 0x%04x, is_originator 0x%02x, psm 0x%04x", __func__, security_required, is_originator, psm); if ((!is_originator) && (security_required & BTM_SEC_MODE4_LEVEL4)) { bool local_supports_sc = controller_get_interface()->supports_secure_connections(); /* acceptor receives L2CAP Channel Connect Request for Secure Connections * Only service */ if (!(local_supports_sc) || !(p_dev_rec->remote_supports_secure_connections)) { BTM_TRACE_DEBUG("%s: SC only service, local_support_for_sc %d", "rmt_support_for_sc : %d -> fail pairing", __func__, local_supports_sc, p_dev_rec->remote_supports_secure_connections); if (p_callback) (*p_callback)(bd_addr, transport, (void*)p_ref_data, BTM_MODE4_LEVEL4_NOT_SUPPORTED); return (BTM_MODE4_LEVEL4_NOT_SUPPORTED); } } /* there are some devices (moto KRZR) which connects to several services at * the same time */ /* we will process one after another */ if ((p_dev_rec->p_callback) || (btm_cb.pairing_state != BTM_PAIR_STATE_IDLE)) { BTM_TRACE_EVENT("%s() - busy - PSM:%d delayed state: %s mode:%d, sm4:0x%x", __func__, psm, btm_pair_state_descr(btm_cb.pairing_state), btm_cb.security_mode, p_dev_rec->sm4); BTM_TRACE_EVENT("security_flags:x%x, sec_flags:x%x", security_required, p_dev_rec->sec_flags); rc = BTM_CMD_STARTED; if ((btm_cb.security_mode == BTM_SEC_MODE_UNDEFINED || btm_cb.security_mode == BTM_SEC_MODE_NONE || btm_cb.security_mode == BTM_SEC_MODE_SERVICE || btm_cb.security_mode == BTM_SEC_MODE_LINK) || (BTM_SM4_KNOWN == p_dev_rec->sm4) || (BTM_SEC_IS_SM4(p_dev_rec->sm4) && (btm_sec_is_upgrade_possible(p_dev_rec, is_originator) == false))) { /* legacy mode - local is legacy or local is lisbon/peer is legacy * or SM4 with no possibility of link key upgrade */ if (is_originator) { if (((security_required & BTM_SEC_OUT_FLAGS) == 0) || ((((security_required & BTM_SEC_OUT_FLAGS) == BTM_SEC_OUT_AUTHENTICATE) && btm_dev_authenticated(p_dev_rec))) || ((((security_required & BTM_SEC_OUT_FLAGS) == (BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_OUT_ENCRYPT)) && btm_dev_encrypted(p_dev_rec))) || ((((security_required & BTM_SEC_OUT_FLAGS) == BTM_SEC_OUT_FLAGS) && btm_dev_authorized(p_dev_rec) && btm_dev_encrypted(p_dev_rec)))) { rc = BTM_SUCCESS; } } else { if (((security_required & BTM_SEC_IN_FLAGS) == 0) || (((security_required & BTM_SEC_IN_FLAGS) == BTM_SEC_IN_AUTHENTICATE) && btm_dev_authenticated(p_dev_rec)) || (((security_required & BTM_SEC_IN_FLAGS) == (BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_ENCRYPT)) && btm_dev_encrypted(p_dev_rec)) || (((security_required & BTM_SEC_IN_FLAGS) == BTM_SEC_IN_AUTHORIZE) && (btm_dev_authorized(p_dev_rec) || btm_serv_trusted(p_dev_rec, p_serv_rec))) || (((security_required & BTM_SEC_IN_FLAGS) == (BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_AUTHORIZE)) && ((btm_dev_authorized(p_dev_rec) || btm_serv_trusted(p_dev_rec, p_serv_rec)) && btm_dev_authenticated(p_dev_rec))) || (((security_required & BTM_SEC_IN_FLAGS) == (BTM_SEC_IN_ENCRYPT | BTM_SEC_IN_AUTHORIZE)) && ((btm_dev_authorized(p_dev_rec) || btm_serv_trusted(p_dev_rec, p_serv_rec)) && btm_dev_encrypted(p_dev_rec))) || (((security_required & BTM_SEC_IN_FLAGS) == BTM_SEC_IN_FLAGS) && btm_dev_encrypted(p_dev_rec) && (btm_dev_authorized(p_dev_rec) || btm_serv_trusted(p_dev_rec, p_serv_rec)))) { // Check for 16 digits (or MITM) if (((security_required & BTM_SEC_IN_MIN_16_DIGIT_PIN) == 0) || (((security_required & BTM_SEC_IN_MIN_16_DIGIT_PIN) == BTM_SEC_IN_MIN_16_DIGIT_PIN) && btm_dev_16_digit_authenticated(p_dev_rec))) { rc = BTM_SUCCESS; } } } if ((rc == BTM_SUCCESS) && (security_required & BTM_SEC_MODE4_LEVEL4) && (p_dev_rec->link_key_type != BTM_LKEY_TYPE_AUTH_COMB_P_256)) { rc = BTM_CMD_STARTED; } if (rc == BTM_SUCCESS) { if (p_callback) (*p_callback)(bd_addr, transport, (void*)p_ref_data, BTM_SUCCESS); return (BTM_SUCCESS); } } btm_cb.sec_req_pending = true; return (BTM_CMD_STARTED); } /* Save pointer to service record */ p_dev_rec->p_cur_service = p_serv_rec; /* Modify security_required in btm_sec_l2cap_access_req for Lisbon */ if (btm_cb.security_mode == BTM_SEC_MODE_SP || btm_cb.security_mode == BTM_SEC_MODE_SP_DEBUG || btm_cb.security_mode == BTM_SEC_MODE_SC) { if (BTM_SEC_IS_SM4(p_dev_rec->sm4)) { if (is_originator) { /* SM4 to SM4 -> always authenticate & encrypt */ security_required |= (BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_OUT_ENCRYPT); } else /* acceptor */ { /* SM4 to SM4: the acceptor needs to make sure the authentication is * already done */ chk_acp_auth_done = true; /* SM4 to SM4 -> always authenticate & encrypt */ security_required |= (BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_ENCRYPT); } } else if (!(BTM_SM4_KNOWN & p_dev_rec->sm4)) { /* the remote features are not known yet */ BTM_TRACE_DEBUG("%s: (%s) remote features unknown!!sec_flags:0x%02x", __func__, (is_originator) ? "initiator" : "acceptor", p_dev_rec->sec_flags); p_dev_rec->sm4 |= BTM_SM4_REQ_PEND; return (BTM_CMD_STARTED); } } BTM_TRACE_DEBUG( "%s() sm4:0x%x, sec_flags:0x%x, security_required:0x%x chk:%d", __func__, p_dev_rec->sm4, p_dev_rec->sec_flags, security_required, chk_acp_auth_done); old_security_required = p_dev_rec->security_required; old_is_originator = p_dev_rec->is_originator; p_dev_rec->security_required = security_required; p_dev_rec->p_ref_data = p_ref_data; p_dev_rec->is_originator = is_originator; #if (L2CAP_UCD_INCLUDED == TRUE) if (conn_type & CONNECTION_TYPE_CONNLESS_MASK) p_dev_rec->is_ucd = true; else p_dev_rec->is_ucd = false; #endif /* If there are multiple service records used through the same PSM */ /* leave security decision for the multiplexor on the top */ #if (L2CAP_UCD_INCLUDED == TRUE) if (((btm_sec_find_next_serv(p_serv_rec)) != NULL) && (!(conn_type & CONNECTION_TYPE_CONNLESS_MASK))) /* if not UCD */ #else if ((btm_sec_find_next_serv(p_serv_rec)) != NULL) #endif { BTM_TRACE_DEBUG("no next_serv sm4:0x%x, chk:%d", p_dev_rec->sm4, chk_acp_auth_done); if (!BTM_SEC_IS_SM4(p_dev_rec->sm4)) { BTM_TRACE_EVENT( "Security Manager: l2cap_access_req PSM:%d postponed for multiplexer", psm); /* pre-Lisbon: restore the old settings */ p_dev_rec->security_required = old_security_required; p_dev_rec->is_originator = old_is_originator; (*p_callback)(bd_addr, transport, p_ref_data, BTM_SUCCESS); return (BTM_SUCCESS); } } /* if the originator is using dynamic PSM in legacy mode, do not start any * security process now * The layer above L2CAP needs to carry out the security requirement after * L2CAP connect * response is received */ if (is_originator && ((btm_cb.security_mode == BTM_SEC_MODE_UNDEFINED || btm_cb.security_mode == BTM_SEC_MODE_NONE || btm_cb.security_mode == BTM_SEC_MODE_SERVICE || btm_cb.security_mode == BTM_SEC_MODE_LINK) || !BTM_SEC_IS_SM4(p_dev_rec->sm4)) && (psm >= 0x1001)) { BTM_TRACE_EVENT( "dynamic PSM:0x%x in legacy mode - postponed for upper layer", psm); /* restore the old settings */ p_dev_rec->security_required = old_security_required; p_dev_rec->is_originator = old_is_originator; (*p_callback)(bd_addr, transport, p_ref_data, BTM_SUCCESS); return (BTM_SUCCESS); } if (chk_acp_auth_done) { BTM_TRACE_DEBUG( "(SM4 to SM4) btm_sec_l2cap_access_req rspd. authenticated: x%x, enc: " "x%x", (p_dev_rec->sec_flags & BTM_SEC_AUTHENTICATED), (p_dev_rec->sec_flags & BTM_SEC_ENCRYPTED)); /* SM4, but we do not know for sure which level of security we need. * as long as we have a link key, it's OK */ if ((0 == (p_dev_rec->sec_flags & BTM_SEC_AUTHENTICATED)) || (0 == (p_dev_rec->sec_flags & BTM_SEC_ENCRYPTED))) { rc = BTM_DELAY_CHECK; /* 2046 may report HCI_Encryption_Change and L2C Connection Request out of sequence because of data path issues. Delay this disconnect a little bit */ LOG_INFO( LOG_TAG, "%s peer should have initiated security process by now (SM4 to SM4)", __func__); p_dev_rec->p_callback = p_callback; p_dev_rec->sec_state = BTM_SEC_STATE_DELAY_FOR_ENC; (*p_callback)(bd_addr, transport, p_ref_data, rc); return BTM_SUCCESS; } } p_dev_rec->p_callback = p_callback; if (p_dev_rec->last_author_service_id == BTM_SEC_NO_LAST_SERVICE_ID || p_dev_rec->last_author_service_id != p_dev_rec->p_cur_service->service_id) { /* Although authentication and encryption are per connection ** authorization is per access request. For example when serial connection ** is up and authorized and client requests to read file (access to other ** scn), we need to request user's permission again. */ p_dev_rec->sec_flags &= ~BTM_SEC_AUTHORIZED; } if (BTM_SEC_IS_SM4(p_dev_rec->sm4)) { if ((p_dev_rec->security_required & BTM_SEC_MODE4_LEVEL4) && (p_dev_rec->link_key_type != BTM_LKEY_TYPE_AUTH_COMB_P_256)) { /* BTM_LKEY_TYPE_AUTH_COMB_P_256 is the only acceptable key in this case */ if ((p_dev_rec->sec_flags & BTM_SEC_LINK_KEY_KNOWN) != 0) { p_dev_rec->sm4 |= BTM_SM4_UPGRADE; } p_dev_rec->sec_flags &= ~(BTM_SEC_LINK_KEY_KNOWN | BTM_SEC_LINK_KEY_AUTHED | BTM_SEC_AUTHENTICATED); BTM_TRACE_DEBUG("%s: sec_flags:0x%x", __func__, p_dev_rec->sec_flags); } else { /* If we already have a link key to the connected peer, is it secure * enough? */ btm_sec_check_upgrade(p_dev_rec, is_originator); } } BTM_TRACE_EVENT( "%s() PSM:%d Handle:%d State:%d Flags: 0x%x Required: 0x%x Service ID:%d", __func__, psm, handle, p_dev_rec->sec_state, p_dev_rec->sec_flags, p_dev_rec->security_required, p_dev_rec->p_cur_service->service_id); rc = btm_sec_execute_procedure(p_dev_rec); if (rc != BTM_CMD_STARTED) { p_dev_rec->p_callback = NULL; (*p_callback)(bd_addr, transport, p_dev_rec->p_ref_data, (uint8_t)rc); } return (rc); } /******************************************************************************* * * Function btm_sec_mx_access_request * * Description This function is called by all Multiplexing Protocols during * establishing connection to or from peer device to grant * permission to establish application connection. * * Parameters: bd_addr - Address of the peer device * psm - L2CAP PSM * is_originator - true if protocol above L2CAP originates * connection * mx_proto_id - protocol ID of the multiplexer * mx_chan_id - multiplexer channel to reach application * p_callback - Pointer to callback function called if * this function returns PENDING after required * procedures are completed * p_ref_data - Pointer to any reference data needed by the * the callback function. * * Returns BTM_CMD_STARTED * ******************************************************************************/ tBTM_STATUS btm_sec_mx_access_request(BD_ADDR bd_addr, uint16_t psm, bool is_originator, uint32_t mx_proto_id, uint32_t mx_chan_id, tBTM_SEC_CALLBACK* p_callback, void* p_ref_data) { tBTM_SEC_DEV_REC* p_dev_rec; tBTM_SEC_SERV_REC* p_serv_rec; tBTM_STATUS rc; uint16_t security_required; bool transport = false; /* should check PSM range in LE connection oriented L2CAP connection */ BTM_TRACE_DEBUG("%s() is_originator: %d", __func__, is_originator); /* Find or get oldest record */ p_dev_rec = btm_find_or_alloc_dev(bd_addr); /* Find the service record for the PSM */ p_serv_rec = btm_sec_find_mx_serv(is_originator, psm, mx_proto_id, mx_chan_id); /* If there is no application registered with this PSM do not allow connection */ if (!p_serv_rec) { if (p_callback) (*p_callback)(bd_addr, transport, p_ref_data, BTM_MODE_UNSUPPORTED); BTM_TRACE_ERROR( "Security Manager: MX service not found PSM:%d Proto:%d SCN:%d", psm, mx_proto_id, mx_chan_id); return BTM_NO_RESOURCES; } if ((btm_cb.security_mode == BTM_SEC_MODE_SC) && (!btm_sec_is_serv_level0(psm))) { security_required = btm_sec_set_serv_level4_flags( p_serv_rec->security_flags, is_originator); } else { security_required = p_serv_rec->security_flags; } /* there are some devices (moto phone) which connects to several services at * the same time */ /* we will process one after another */ if ((p_dev_rec->p_callback) || (btm_cb.pairing_state != BTM_PAIR_STATE_IDLE)) { BTM_TRACE_EVENT("%s() service PSM:%d Proto:%d SCN:%d delayed state: %s", __func__, psm, mx_proto_id, mx_chan_id, btm_pair_state_descr(btm_cb.pairing_state)); rc = BTM_CMD_STARTED; if ((btm_cb.security_mode == BTM_SEC_MODE_UNDEFINED || btm_cb.security_mode == BTM_SEC_MODE_NONE || btm_cb.security_mode == BTM_SEC_MODE_SERVICE || btm_cb.security_mode == BTM_SEC_MODE_LINK) || (BTM_SM4_KNOWN == p_dev_rec->sm4) || (BTM_SEC_IS_SM4(p_dev_rec->sm4) && (btm_sec_is_upgrade_possible(p_dev_rec, is_originator) == false))) { /* legacy mode - local is legacy or local is lisbon/peer is legacy * or SM4 with no possibility of link key upgrade */ if (is_originator) { if (((security_required & BTM_SEC_OUT_FLAGS) == 0) || ((((security_required & BTM_SEC_OUT_FLAGS) == BTM_SEC_OUT_AUTHENTICATE) && btm_dev_authenticated(p_dev_rec))) || ((((security_required & BTM_SEC_OUT_FLAGS) == (BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_OUT_ENCRYPT)) && btm_dev_encrypted(p_dev_rec)))) { rc = BTM_SUCCESS; } } else { if (((security_required & BTM_SEC_IN_FLAGS) == 0) || ((((security_required & BTM_SEC_IN_FLAGS) == BTM_SEC_IN_AUTHENTICATE) && btm_dev_authenticated(p_dev_rec))) || (((security_required & BTM_SEC_IN_FLAGS) == BTM_SEC_IN_AUTHORIZE) && (btm_dev_authorized(p_dev_rec) || btm_serv_trusted(p_dev_rec, p_serv_rec))) || (((security_required & BTM_SEC_IN_FLAGS) == (BTM_SEC_IN_AUTHORIZE | BTM_SEC_IN_AUTHENTICATE)) && ((btm_dev_authorized(p_dev_rec) || btm_serv_trusted(p_dev_rec, p_serv_rec)) && btm_dev_authenticated(p_dev_rec))) || (((security_required & BTM_SEC_IN_FLAGS) == (BTM_SEC_IN_AUTHORIZE | BTM_SEC_IN_ENCRYPT)) && ((btm_dev_authorized(p_dev_rec) || btm_serv_trusted(p_dev_rec, p_serv_rec)) && btm_dev_encrypted(p_dev_rec))) || ((((security_required & BTM_SEC_IN_FLAGS) == (BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_ENCRYPT)) && btm_dev_encrypted(p_dev_rec)))) { // Check for 16 digits (or MITM) if (((security_required & BTM_SEC_IN_MIN_16_DIGIT_PIN) == 0) || (((security_required & BTM_SEC_IN_MIN_16_DIGIT_PIN) == BTM_SEC_IN_MIN_16_DIGIT_PIN) && btm_dev_16_digit_authenticated(p_dev_rec))) { rc = BTM_SUCCESS; } } } if ((rc == BTM_SUCCESS) && (security_required & BTM_SEC_MODE4_LEVEL4) && (p_dev_rec->link_key_type != BTM_LKEY_TYPE_AUTH_COMB_P_256)) { rc = BTM_CMD_STARTED; } } if (rc == BTM_SUCCESS) { BTM_TRACE_EVENT("%s: allow to bypass, checking authorization", __func__); /* the security in BTM_SEC_IN_FLAGS is fullfilled so far, check the * requirements in */ /* btm_sec_execute_procedure */ if ((is_originator && (p_serv_rec->security_flags & BTM_SEC_OUT_AUTHORIZE)) || (!is_originator && (p_serv_rec->security_flags & BTM_SEC_IN_AUTHORIZE))) { BTM_TRACE_EVENT("%s: still need authorization", __func__); rc = BTM_CMD_STARTED; } } /* Check whether there is a pending security procedure, if so we should * always queue */ /* the new security request */ if (p_dev_rec->sec_state != BTM_SEC_STATE_IDLE) { BTM_TRACE_EVENT("%s: There is a pending security procedure", __func__); rc = BTM_CMD_STARTED; } if (rc == BTM_CMD_STARTED) { BTM_TRACE_EVENT("%s: call btm_sec_queue_mx_request", __func__); btm_sec_queue_mx_request(bd_addr, psm, is_originator, mx_proto_id, mx_chan_id, p_callback, p_ref_data); } else /* rc == BTM_SUCCESS */ { /* access granted */ if (p_callback) { (*p_callback)(bd_addr, transport, p_ref_data, (uint8_t)rc); } } BTM_TRACE_EVENT("%s: return with rc = 0x%02x in delayed state %s", __func__, rc, btm_pair_state_descr(btm_cb.pairing_state)); return rc; } if ((!is_originator) && ((security_required & BTM_SEC_MODE4_LEVEL4) || (btm_cb.security_mode == BTM_SEC_MODE_SC))) { bool local_supports_sc = controller_get_interface()->supports_secure_connections(); /* acceptor receives service connection establishment Request for */ /* Secure Connections Only service */ if (!(local_supports_sc) || !(p_dev_rec->remote_supports_secure_connections)) { BTM_TRACE_DEBUG("%s: SC only service,local_support_for_sc %d,", "remote_support_for_sc %d: fail pairing", __func__, local_supports_sc, p_dev_rec->remote_supports_secure_connections); if (p_callback) (*p_callback)(bd_addr, transport, (void*)p_ref_data, BTM_MODE4_LEVEL4_NOT_SUPPORTED); return (BTM_MODE4_LEVEL4_NOT_SUPPORTED); } } p_dev_rec->p_cur_service = p_serv_rec; p_dev_rec->security_required = security_required; if (btm_cb.security_mode == BTM_SEC_MODE_SP || btm_cb.security_mode == BTM_SEC_MODE_SP_DEBUG || btm_cb.security_mode == BTM_SEC_MODE_SC) { if (BTM_SEC_IS_SM4(p_dev_rec->sm4)) { if ((p_dev_rec->security_required & BTM_SEC_MODE4_LEVEL4) && (p_dev_rec->link_key_type != BTM_LKEY_TYPE_AUTH_COMB_P_256)) { /* BTM_LKEY_TYPE_AUTH_COMB_P_256 is the only acceptable key in this case */ if ((p_dev_rec->sec_flags & BTM_SEC_LINK_KEY_KNOWN) != 0) { p_dev_rec->sm4 |= BTM_SM4_UPGRADE; } p_dev_rec->sec_flags &= ~(BTM_SEC_LINK_KEY_KNOWN | BTM_SEC_LINK_KEY_AUTHED | BTM_SEC_AUTHENTICATED); BTM_TRACE_DEBUG("%s: sec_flags:0x%x", __func__, p_dev_rec->sec_flags); } else { /* If we already have a link key, check if that link key is good enough */ btm_sec_check_upgrade(p_dev_rec, is_originator); } } } p_dev_rec->is_originator = is_originator; p_dev_rec->p_callback = p_callback; p_dev_rec->p_ref_data = p_ref_data; /* Although authentication and encryption are per connection */ /* authorization is per access request. For example when serial connection */ /* is up and authorized and client requests to read file (access to other */ /* scn, we need to request user's permission again. */ p_dev_rec->sec_flags &= ~(BTM_SEC_AUTHORIZED); BTM_TRACE_EVENT( "%s() proto_id:%d chan_id:%d State:%d Flags:0x%x Required:0x%x Service " "ID:%d", __func__, mx_proto_id, mx_chan_id, p_dev_rec->sec_state, p_dev_rec->sec_flags, p_dev_rec->security_required, p_dev_rec->p_cur_service->service_id); rc = btm_sec_execute_procedure(p_dev_rec); if (rc != BTM_CMD_STARTED) { if (p_callback) { p_dev_rec->p_callback = NULL; (*p_callback)(bd_addr, transport, p_ref_data, (uint8_t)rc); } } return rc; } /******************************************************************************* * * Function btm_sec_conn_req * * Description This function is when the peer device is requesting * connection * * Returns void * ******************************************************************************/ void btm_sec_conn_req(uint8_t* bda, uint8_t* dc) { tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bda); /* Some device may request a connection before we are done with the HCI_Reset * sequence */ if (!controller_get_interface()->get_is_ready()) { BTM_TRACE_EVENT("Security Manager: connect request when device not ready"); btsnd_hcic_reject_conn(bda, HCI_ERR_HOST_REJECT_DEVICE); return; } /* Security guys wants us not to allow connection from not paired devices */ /* Check if connection is allowed for only paired devices */ if (btm_cb.connect_only_paired) { if (!p_dev_rec || !(p_dev_rec->sec_flags & BTM_SEC_LINK_KEY_AUTHED)) { BTM_TRACE_EVENT( "Security Manager: connect request from non-paired device"); btsnd_hcic_reject_conn(bda, HCI_ERR_HOST_REJECT_DEVICE); return; } } #if (BTM_ALLOW_CONN_IF_NONDISCOVER == FALSE) /* If non-discoverable, only allow known devices to connect */ if (btm_cb.btm_inq_vars.discoverable_mode == BTM_NON_DISCOVERABLE) { if (!p_dev_rec) { BTM_TRACE_EVENT( "Security Manager: connect request from not paired device"); btsnd_hcic_reject_conn(bda, HCI_ERR_HOST_REJECT_DEVICE); return; } } #endif if ((btm_cb.pairing_state != BTM_PAIR_STATE_IDLE) && (btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) && (!memcmp(btm_cb.pairing_bda, bda, BD_ADDR_LEN))) { BTM_TRACE_EVENT( "Security Manager: reject connect request from bonding device"); /* incoming connection from bonding device is rejected */ btm_cb.pairing_flags |= BTM_PAIR_FLAGS_REJECTED_CONNECT; btsnd_hcic_reject_conn(bda, HCI_ERR_HOST_REJECT_DEVICE); return; } /* Host is not interested or approved connection. Save BDA and DC and */ /* pass request to L2CAP */ memcpy(btm_cb.connecting_bda, bda, BD_ADDR_LEN); memcpy(btm_cb.connecting_dc, dc, DEV_CLASS_LEN); if (l2c_link_hci_conn_req(bda)) { if (!p_dev_rec) { /* accept the connection -> allocate a device record */ p_dev_rec = btm_sec_alloc_dev(bda); } if (p_dev_rec) { p_dev_rec->sm4 |= BTM_SM4_CONN_PEND; } } } /******************************************************************************* * * Function btm_sec_bond_cancel_complete * * Description This function is called to report bond cancel complete * event. * * Returns void * ******************************************************************************/ static void btm_sec_bond_cancel_complete(void) { tBTM_SEC_DEV_REC* p_dev_rec; if ((btm_cb.pairing_flags & BTM_PAIR_FLAGS_DISC_WHEN_DONE) || (BTM_PAIR_STATE_WAIT_LOCAL_PIN == btm_cb.pairing_state && BTM_PAIR_FLAGS_WE_STARTED_DD & btm_cb.pairing_flags) || (btm_cb.pairing_state == BTM_PAIR_STATE_GET_REM_NAME && BTM_PAIR_FLAGS_WE_CANCEL_DD & btm_cb.pairing_flags)) { /* for dedicated bonding in legacy mode, authentication happens at "link * level" * btm_sec_connected is called with failed status. * In theory, the code that handles is_pairing_device/true should clean out * security related code. * However, this function may clean out the security related flags and * btm_sec_connected would not know * this function also needs to do proper clean up. */ p_dev_rec = btm_find_dev(btm_cb.pairing_bda); if (p_dev_rec != NULL) p_dev_rec->security_required = BTM_SEC_NONE; btm_sec_change_pairing_state(BTM_PAIR_STATE_IDLE); /* Notify application that the cancel succeeded */ if (btm_cb.api.p_bond_cancel_cmpl_callback) btm_cb.api.p_bond_cancel_cmpl_callback(BTM_SUCCESS); } } /******************************************************************************* * * Function btm_create_conn_cancel_complete * * Description This function is called when the command complete message * is received from the HCI for the create connection cancel * command. * * Returns void * ******************************************************************************/ void btm_create_conn_cancel_complete(uint8_t* p) { uint8_t status; STREAM_TO_UINT8(status, p); BTM_TRACE_EVENT("btm_create_conn_cancel_complete(): in State: %s status:%d", btm_pair_state_descr(btm_cb.pairing_state), status); /* if the create conn cancel cmd was issued by the bond cancel, ** the application needs to be notified that bond cancel succeeded */ switch (status) { case HCI_SUCCESS: btm_sec_bond_cancel_complete(); break; case HCI_ERR_CONNECTION_EXISTS: case HCI_ERR_NO_CONNECTION: default: /* Notify application of the error */ if (btm_cb.api.p_bond_cancel_cmpl_callback) btm_cb.api.p_bond_cancel_cmpl_callback(BTM_ERR_PROCESSING); break; } } /******************************************************************************* * * Function btm_sec_check_pending_reqs * * Description This function is called at the end of the security procedure * to let L2CAP and RFCOMM know to re-submit any pending * requests * * Returns void * ******************************************************************************/ void btm_sec_check_pending_reqs(void) { if (btm_cb.pairing_state == BTM_PAIR_STATE_IDLE) { /* First, resubmit L2CAP requests */ if (btm_cb.sec_req_pending) { btm_cb.sec_req_pending = false; l2cu_resubmit_pending_sec_req(NULL); } /* Now, re-submit anything in the mux queue */ fixed_queue_t* bq = btm_cb.sec_pending_q; btm_cb.sec_pending_q = fixed_queue_new(SIZE_MAX); tBTM_SEC_QUEUE_ENTRY* p_e; while ((p_e = (tBTM_SEC_QUEUE_ENTRY*)fixed_queue_try_dequeue(bq)) != NULL) { /* Check that the ACL is still up before starting security procedures */ if (btm_bda_to_acl(p_e->bd_addr, p_e->transport) != NULL) { if (p_e->psm != 0) { BTM_TRACE_EVENT( "%s PSM:0x%04x Is_Orig:%u mx_proto_id:%u mx_chan_id:%u", __func__, p_e->psm, p_e->is_orig, p_e->mx_proto_id, p_e->mx_chan_id); btm_sec_mx_access_request(p_e->bd_addr, p_e->psm, p_e->is_orig, p_e->mx_proto_id, p_e->mx_chan_id, p_e->p_callback, p_e->p_ref_data); } else { BTM_SetEncryption(p_e->bd_addr, p_e->transport, p_e->p_callback, p_e->p_ref_data, p_e->sec_act); } } osi_free(p_e); } fixed_queue_free(bq, NULL); } } /******************************************************************************* * * Function btm_sec_init * * Description This function is on the SEC startup * * Returns void * ******************************************************************************/ void btm_sec_init(uint8_t sec_mode) { btm_cb.security_mode = sec_mode; memset(btm_cb.pairing_bda, 0xff, BD_ADDR_LEN); btm_cb.max_collision_delay = BTM_SEC_MAX_COLLISION_DELAY; } /******************************************************************************* * * Function btm_sec_device_down * * Description This function should be called when device is disabled or * turned off * * Returns void * ******************************************************************************/ void btm_sec_device_down(void) { BTM_TRACE_EVENT("%s() State: %s", __func__, btm_pair_state_descr(btm_cb.pairing_state)); btm_sec_change_pairing_state(BTM_PAIR_STATE_IDLE); } /******************************************************************************* * * Function btm_sec_dev_reset * * Description This function should be called after device reset * * Returns void * ******************************************************************************/ void btm_sec_dev_reset(void) { if (controller_get_interface()->supports_simple_pairing()) { /* set the default IO capabilities */ btm_cb.devcb.loc_io_caps = BTM_LOCAL_IO_CAPS; /* add mx service to use no security */ BTM_SetSecurityLevel(false, "RFC_MUX", BTM_SEC_SERVICE_RFC_MUX, BTM_SEC_NONE, BT_PSM_RFCOMM, BTM_SEC_PROTO_RFCOMM, 0); } else { btm_cb.security_mode = BTM_SEC_MODE_SERVICE; } BTM_TRACE_DEBUG("btm_sec_dev_reset sec mode: %d", btm_cb.security_mode); } /******************************************************************************* * * Function btm_sec_abort_access_req * * Description This function is called by the L2CAP or RFCOMM to abort * the pending operation. * * Parameters: bd_addr - Address of the peer device * * Returns void * ******************************************************************************/ void btm_sec_abort_access_req(BD_ADDR bd_addr) { tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr); if (!p_dev_rec) return; if ((p_dev_rec->sec_state != BTM_SEC_STATE_AUTHORIZING) && (p_dev_rec->sec_state != BTM_SEC_STATE_AUTHENTICATING)) return; p_dev_rec->sec_state = BTM_SEC_STATE_IDLE; p_dev_rec->p_callback = NULL; } /******************************************************************************* * * Function btm_sec_dd_create_conn * * Description This function is called to create the ACL connection for * the dedicated boding process * * Returns void * ******************************************************************************/ static tBTM_STATUS btm_sec_dd_create_conn(tBTM_SEC_DEV_REC* p_dev_rec) { tL2C_LCB* p_lcb = l2cu_find_lcb_by_bd_addr(p_dev_rec->bd_addr, BT_TRANSPORT_BR_EDR); if (p_lcb && (p_lcb->link_state == LST_CONNECTED || p_lcb->link_state == LST_CONNECTING)) { BTM_TRACE_WARNING("%s Connection already exists", __func__); btm_sec_change_pairing_state(BTM_PAIR_STATE_WAIT_PIN_REQ); return BTM_CMD_STARTED; } /* Make sure an L2cap link control block is available */ if (!p_lcb && (p_lcb = l2cu_allocate_lcb(p_dev_rec->bd_addr, true, BT_TRANSPORT_BR_EDR)) == NULL) { BTM_TRACE_WARNING( "Security Manager: failed allocate LCB [%02x%02x%02x%02x%02x%02x]", p_dev_rec->bd_addr[0], p_dev_rec->bd_addr[1], p_dev_rec->bd_addr[2], p_dev_rec->bd_addr[3], p_dev_rec->bd_addr[4], p_dev_rec->bd_addr[5]); return (BTM_NO_RESOURCES); } /* set up the control block to indicated dedicated bonding */ btm_cb.pairing_flags |= BTM_PAIR_FLAGS_DISC_WHEN_DONE; if (l2cu_create_conn(p_lcb, BT_TRANSPORT_BR_EDR) == false) { BTM_TRACE_WARNING( "Security Manager: failed create [%02x%02x%02x%02x%02x%02x]", p_dev_rec->bd_addr[0], p_dev_rec->bd_addr[1], p_dev_rec->bd_addr[2], p_dev_rec->bd_addr[3], p_dev_rec->bd_addr[4], p_dev_rec->bd_addr[5]); l2cu_release_lcb(p_lcb); return (BTM_NO_RESOURCES); } btm_acl_update_busy_level(BTM_BLI_PAGE_EVT); BTM_TRACE_DEBUG( "Security Manager: btm_sec_dd_create_conn [%02x%02x%02x%02x%02x%02x]", p_dev_rec->bd_addr[0], p_dev_rec->bd_addr[1], p_dev_rec->bd_addr[2], p_dev_rec->bd_addr[3], p_dev_rec->bd_addr[4], p_dev_rec->bd_addr[5]); btm_sec_change_pairing_state(BTM_PAIR_STATE_WAIT_PIN_REQ); return (BTM_CMD_STARTED); } bool is_state_getting_name(void* data, void* context) { tBTM_SEC_DEV_REC* p_dev_rec = static_cast<tBTM_SEC_DEV_REC*>(data); if (p_dev_rec->sec_state == BTM_SEC_STATE_GETTING_NAME) { return false; } return true; } /******************************************************************************* * * Function btm_sec_rmt_name_request_complete * * Description This function is called when remote name was obtained from * the peer device * * Returns void * ******************************************************************************/ void btm_sec_rmt_name_request_complete(uint8_t* p_bd_addr, uint8_t* p_bd_name, uint8_t status) { tBTM_SEC_DEV_REC* p_dev_rec; int i; DEV_CLASS dev_class; uint8_t old_sec_state; BTM_TRACE_EVENT("btm_sec_rmt_name_request_complete"); if (((p_bd_addr == NULL) && !BTM_ACL_IS_CONNECTED(btm_cb.connecting_bda)) || ((p_bd_addr != NULL) && !BTM_ACL_IS_CONNECTED(p_bd_addr))) { btm_acl_resubmit_page(); } /* If remote name request failed, p_bd_addr is null and we need to search */ /* based on state assuming that we are doing 1 at a time */ if (p_bd_addr) p_dev_rec = btm_find_dev(p_bd_addr); else { list_node_t* node = list_foreach(btm_cb.sec_dev_rec, is_state_getting_name, NULL); if (node != NULL) { p_dev_rec = static_cast<tBTM_SEC_DEV_REC*>(list_node(node)); p_bd_addr = p_dev_rec->bd_addr; } else { p_dev_rec = NULL; } } /* Commenting out trace due to obf/compilation problems. */ if (!p_bd_name) p_bd_name = (uint8_t*)""; if (p_dev_rec) { BTM_TRACE_EVENT( "%s PairState: %s RemName: %s status: %d State:%d p_dev_rec: " "0x%08x ", __func__, btm_pair_state_descr(btm_cb.pairing_state), p_bd_name, status, p_dev_rec->sec_state, p_dev_rec); } else { BTM_TRACE_EVENT("%s PairState: %s RemName: %s status: %d", __func__, btm_pair_state_descr(btm_cb.pairing_state), p_bd_name, status); } if (p_dev_rec) { old_sec_state = p_dev_rec->sec_state; if (status == HCI_SUCCESS) { strlcpy((char*)p_dev_rec->sec_bd_name, (char*)p_bd_name, BTM_MAX_REM_BD_NAME_LEN); p_dev_rec->sec_flags |= BTM_SEC_NAME_KNOWN; BTM_TRACE_EVENT("setting BTM_SEC_NAME_KNOWN sec_flags:0x%x", p_dev_rec->sec_flags); } else { /* Notify all clients waiting for name to be resolved even if it failed so * clients can continue */ p_dev_rec->sec_bd_name[0] = 0; } if (p_dev_rec->sec_state == BTM_SEC_STATE_GETTING_NAME) p_dev_rec->sec_state = BTM_SEC_STATE_IDLE; /* Notify all clients waiting for name to be resolved */ for (i = 0; i < BTM_SEC_MAX_RMT_NAME_CALLBACKS; i++) { if (btm_cb.p_rmt_name_callback[i] && p_bd_addr) (*btm_cb.p_rmt_name_callback[i])(p_bd_addr, p_dev_rec->dev_class, p_dev_rec->sec_bd_name); } } else { dev_class[0] = 0; dev_class[1] = 0; dev_class[2] = 0; /* Notify all clients waiting for name to be resolved even if not found so * clients can continue */ for (i = 0; i < BTM_SEC_MAX_RMT_NAME_CALLBACKS; i++) { if (btm_cb.p_rmt_name_callback[i] && p_bd_addr) (*btm_cb.p_rmt_name_callback[i])(p_bd_addr, dev_class, (uint8_t*)""); } return; } /* If we were delaying asking UI for a PIN because name was not resolved, ask * now */ if ((btm_cb.pairing_state == BTM_PAIR_STATE_WAIT_LOCAL_PIN) && p_bd_addr && (memcmp(btm_cb.pairing_bda, p_bd_addr, BD_ADDR_LEN) == 0)) { BTM_TRACE_EVENT( "%s() delayed pin now being requested flags:0x%x, " "(p_pin_callback=0x%p)", __func__, btm_cb.pairing_flags, btm_cb.api.p_pin_callback); if ((btm_cb.pairing_flags & BTM_PAIR_FLAGS_PIN_REQD) == 0 && btm_cb.api.p_pin_callback) { BTM_TRACE_EVENT("%s() calling pin_callback", __func__); btm_cb.pairing_flags |= BTM_PAIR_FLAGS_PIN_REQD; (*btm_cb.api.p_pin_callback)( p_dev_rec->bd_addr, p_dev_rec->dev_class, p_bd_name, (p_dev_rec->p_cur_service == NULL) ? false : (p_dev_rec->p_cur_service->security_flags & BTM_SEC_IN_MIN_16_DIGIT_PIN)); } /* Set the same state again to force the timer to be restarted */ btm_sec_change_pairing_state(BTM_PAIR_STATE_WAIT_LOCAL_PIN); return; } /* Check if we were delaying bonding because name was not resolved */ if (btm_cb.pairing_state == BTM_PAIR_STATE_GET_REM_NAME) { if (p_bd_addr && memcmp(btm_cb.pairing_bda, p_bd_addr, BD_ADDR_LEN) == 0) { BTM_TRACE_EVENT("%s() continue bonding sm4: 0x%04x, status:0x%x", __func__, p_dev_rec->sm4, status); if (btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_CANCEL_DD) { btm_sec_bond_cancel_complete(); return; } if (status != HCI_SUCCESS) { btm_sec_change_pairing_state(BTM_PAIR_STATE_IDLE); if (btm_cb.api.p_auth_complete_callback) (*btm_cb.api.p_auth_complete_callback)( p_dev_rec->bd_addr, p_dev_rec->dev_class, p_dev_rec->sec_bd_name, status); return; } /* if peer is very old legacy devices, HCI_RMT_HOST_SUP_FEAT_NOTIFY_EVT is * not reported */ if (BTM_SEC_IS_SM4_UNKNOWN(p_dev_rec->sm4)) { /* set the KNOWN flag only if BTM_PAIR_FLAGS_REJECTED_CONNECT is not * set.*/ /* If it is set, there may be a race condition */ BTM_TRACE_DEBUG("%s IS_SM4_UNKNOWN Flags:0x%04x", __func__, btm_cb.pairing_flags); if ((btm_cb.pairing_flags & BTM_PAIR_FLAGS_REJECTED_CONNECT) == 0) p_dev_rec->sm4 |= BTM_SM4_KNOWN; } BTM_TRACE_DEBUG("%s, SM4 Value: %x, Legacy:%d,IS SM4:%d, Unknown:%d", __func__, p_dev_rec->sm4, BTM_SEC_IS_SM4_LEGACY(p_dev_rec->sm4), BTM_SEC_IS_SM4(p_dev_rec->sm4), BTM_SEC_IS_SM4_UNKNOWN(p_dev_rec->sm4)); /* BT 2.1 or carkit, bring up the connection to force the peer to request *PIN. ** Else prefetch (btm_sec_check_prefetch_pin will do the prefetching if *needed) */ if ((p_dev_rec->sm4 != BTM_SM4_KNOWN) || !btm_sec_check_prefetch_pin(p_dev_rec)) { /* if we rejected incoming connection request, we have to wait * HCI_Connection_Complete event */ /* before originating */ if (btm_cb.pairing_flags & BTM_PAIR_FLAGS_REJECTED_CONNECT) { BTM_TRACE_WARNING( "%s: waiting HCI_Connection_Complete after rejecting connection", __func__); } /* Both we and the peer are 2.1 - continue to create connection */ else if (btm_sec_dd_create_conn(p_dev_rec) != BTM_CMD_STARTED) { BTM_TRACE_WARNING("%s: failed to start connection", __func__); btm_sec_change_pairing_state(BTM_PAIR_STATE_IDLE); if (btm_cb.api.p_auth_complete_callback) { (*btm_cb.api.p_auth_complete_callback)( p_dev_rec->bd_addr, p_dev_rec->dev_class, p_dev_rec->sec_bd_name, HCI_ERR_MEMORY_FULL); } } } return; } else { BTM_TRACE_WARNING("%s: wrong BDA, retry with pairing BDA", __func__); if (BTM_ReadRemoteDeviceName(btm_cb.pairing_bda, NULL, BT_TRANSPORT_BR_EDR) != BTM_CMD_STARTED) { BTM_TRACE_ERROR("%s: failed to start remote name request", __func__); if (btm_cb.api.p_auth_complete_callback) { (*btm_cb.api.p_auth_complete_callback)( p_dev_rec->bd_addr, p_dev_rec->dev_class, p_dev_rec->sec_bd_name, HCI_ERR_MEMORY_FULL); } }; return; } } /* check if we were delaying link_key_callback because name was not resolved */ if (p_dev_rec->link_key_not_sent) { /* If HCI connection complete has not arrived, wait for it */ if (p_dev_rec->hci_handle == BTM_SEC_INVALID_HANDLE) return; p_dev_rec->link_key_not_sent = false; btm_send_link_key_notif(p_dev_rec); /* If its not us who perform authentication, we should tell stackserver */ /* that some authentication has been completed */ /* This is required when different entities receive link notification and * auth complete */ if (!(p_dev_rec->security_required & BTM_SEC_OUT_AUTHENTICATE)) { if (btm_cb.api.p_auth_complete_callback) (*btm_cb.api.p_auth_complete_callback)( p_dev_rec->bd_addr, p_dev_rec->dev_class, p_dev_rec->sec_bd_name, HCI_SUCCESS); } } /* If this is a bonding procedure can disconnect the link now */ if ((btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) && (p_dev_rec->sec_flags & BTM_SEC_AUTHENTICATED)) { BTM_TRACE_WARNING("btm_sec_rmt_name_request_complete (none/ce)"); p_dev_rec->security_required &= ~(BTM_SEC_OUT_AUTHENTICATE); l2cu_start_post_bond_timer(p_dev_rec->hci_handle); return; } if (old_sec_state != BTM_SEC_STATE_GETTING_NAME) return; /* If get name failed, notify the waiting layer */ if (status != HCI_SUCCESS) { btm_sec_dev_rec_cback_event(p_dev_rec, BTM_ERR_PROCESSING, false); return; } if (p_dev_rec->sm4 & BTM_SM4_REQ_PEND) { BTM_TRACE_EVENT("waiting for remote features!!"); return; } /* Remote Name succeeded, execute the next security procedure, if any */ status = (uint8_t)btm_sec_execute_procedure(p_dev_rec); /* If result is pending reply from the user or from the device is pending */ if (status == BTM_CMD_STARTED) return; /* There is no next procedure or start of procedure failed, notify the waiting * layer */ btm_sec_dev_rec_cback_event(p_dev_rec, status, false); } /******************************************************************************* * * Function btm_sec_rmt_host_support_feat_evt * * Description This function is called when the * HCI_RMT_HOST_SUP_FEAT_NOTIFY_EVT is received * * Returns void * ******************************************************************************/ void btm_sec_rmt_host_support_feat_evt(uint8_t* p) { tBTM_SEC_DEV_REC* p_dev_rec; BD_ADDR bd_addr; /* peer address */ BD_FEATURES features; STREAM_TO_BDADDR(bd_addr, p); p_dev_rec = btm_find_or_alloc_dev(bd_addr); BTM_TRACE_EVENT("btm_sec_rmt_host_support_feat_evt sm4: 0x%x p[0]: 0x%x", p_dev_rec->sm4, p[0]); if (BTM_SEC_IS_SM4_UNKNOWN(p_dev_rec->sm4)) { p_dev_rec->sm4 = BTM_SM4_KNOWN; STREAM_TO_ARRAY(features, p, HCI_FEATURE_BYTES_PER_PAGE); if (HCI_SSP_HOST_SUPPORTED(features)) { p_dev_rec->sm4 = BTM_SM4_TRUE; } BTM_TRACE_EVENT( "btm_sec_rmt_host_support_feat_evt sm4: 0x%x features[0]: 0x%x", p_dev_rec->sm4, features[0]); } } /******************************************************************************* * * Function btm_io_capabilities_req * * Description This function is called when LM request for the IO * capability of the local device and * if the OOB data is present for the device in the event * * Returns void * ******************************************************************************/ void btm_io_capabilities_req(uint8_t* p) { tBTM_SP_IO_REQ evt_data; uint8_t err_code = 0; tBTM_SEC_DEV_REC* p_dev_rec; bool is_orig = true; uint8_t callback_rc = BTM_SUCCESS; STREAM_TO_BDADDR(evt_data.bd_addr, p); /* setup the default response according to compile options */ /* assume that the local IO capability does not change * loc_io_caps is initialized with the default value */ evt_data.io_cap = btm_cb.devcb.loc_io_caps; evt_data.oob_data = BTM_OOB_NONE; evt_data.auth_req = BTM_DEFAULT_AUTH_REQ; BTM_TRACE_EVENT("%s: State: %s", __func__, btm_pair_state_descr(btm_cb.pairing_state)); p_dev_rec = btm_find_or_alloc_dev(evt_data.bd_addr); BTM_TRACE_DEBUG("%s:Security mode: %d, Num Read Remote Feat pages: %d", __func__, btm_cb.security_mode, p_dev_rec->num_read_pages); if ((btm_cb.security_mode == BTM_SEC_MODE_SC) && (p_dev_rec->num_read_pages == 0)) { BTM_TRACE_EVENT("%s: Device security mode is SC only.", "To continue need to know remote features.", __func__); p_dev_rec->remote_features_needed = true; return; } p_dev_rec->sm4 |= BTM_SM4_TRUE; BTM_TRACE_EVENT("%s: State: %s Flags: 0x%04x p_cur_service: 0x%08x", __func__, btm_pair_state_descr(btm_cb.pairing_state), btm_cb.pairing_flags, p_dev_rec->p_cur_service); if (p_dev_rec->p_cur_service) { BTM_TRACE_EVENT("%s: cur_service psm: 0x%04x, security_flags: 0x%04x", __func__, p_dev_rec->p_cur_service->psm, p_dev_rec->p_cur_service->security_flags); } switch (btm_cb.pairing_state) { /* initiator connecting */ case BTM_PAIR_STATE_IDLE: // TODO: Handle Idle pairing state // security_required = p_dev_rec->security_required; break; /* received IO capability response already->acceptor */ case BTM_PAIR_STATE_INCOMING_SSP: is_orig = false; if (btm_cb.pairing_flags & BTM_PAIR_FLAGS_PEER_STARTED_DD) { /* acceptor in dedicated bonding */ evt_data.auth_req = BTM_DEFAULT_DD_AUTH_REQ; } break; /* initiator, at this point it is expected to be dedicated bonding initiated by local device */ case BTM_PAIR_STATE_WAIT_PIN_REQ: if (!memcmp(evt_data.bd_addr, btm_cb.pairing_bda, BD_ADDR_LEN)) { evt_data.auth_req = BTM_DEFAULT_DD_AUTH_REQ; } else { err_code = HCI_ERR_HOST_BUSY_PAIRING; } break; /* any other state is unexpected */ default: err_code = HCI_ERR_HOST_BUSY_PAIRING; BTM_TRACE_ERROR("%s: Unexpected Pairing state received %d", __func__, btm_cb.pairing_state); break; } if (btm_cb.pairing_disabled) { /* pairing is not allowed */ BTM_TRACE_DEBUG("%s: Pairing is not allowed -> fail pairing.", __func__); err_code = HCI_ERR_PAIRING_NOT_ALLOWED; } else if (btm_cb.security_mode == BTM_SEC_MODE_SC) { bool local_supports_sc = controller_get_interface()->supports_secure_connections(); /* device in Secure Connections Only mode */ if (!(local_supports_sc) || !(p_dev_rec->remote_supports_secure_connections)) { BTM_TRACE_DEBUG("%s: SC only service, local_support_for_sc %d,", " remote_support_for_sc 0x%02x -> fail pairing", __func__, local_supports_sc, p_dev_rec->remote_supports_secure_connections); err_code = HCI_ERR_PAIRING_NOT_ALLOWED; } } if (err_code != 0) { btsnd_hcic_io_cap_req_neg_reply(evt_data.bd_addr, err_code); return; } evt_data.is_orig = is_orig; if (is_orig) { /* local device initiated the pairing non-bonding -> use p_cur_service */ if (!(btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) && p_dev_rec->p_cur_service && (p_dev_rec->p_cur_service->security_flags & BTM_SEC_OUT_AUTHENTICATE)) { if (btm_cb.security_mode == BTM_SEC_MODE_SC) { /* SC only mode device requires MITM protection */ evt_data.auth_req = BTM_AUTH_SP_YES; } else { evt_data.auth_req = (p_dev_rec->p_cur_service->security_flags & BTM_SEC_OUT_MITM) ? BTM_AUTH_SP_YES : BTM_AUTH_SP_NO; } } } /* Notify L2CAP to increase timeout */ l2c_pin_code_request(evt_data.bd_addr); memcpy(btm_cb.pairing_bda, evt_data.bd_addr, BD_ADDR_LEN); if (!memcmp(evt_data.bd_addr, btm_cb.connecting_bda, BD_ADDR_LEN)) memcpy(p_dev_rec->dev_class, btm_cb.connecting_dc, DEV_CLASS_LEN); btm_sec_change_pairing_state(BTM_PAIR_STATE_WAIT_LOCAL_IOCAPS); callback_rc = BTM_SUCCESS; if (p_dev_rec->sm4 & BTM_SM4_UPGRADE) { p_dev_rec->sm4 &= ~BTM_SM4_UPGRADE; /* link key upgrade: always use SPGB_YES - assuming we want to save the link * key */ evt_data.auth_req = BTM_AUTH_SPGB_YES; } else if (btm_cb.api.p_sp_callback) { /* the callback function implementation may change the IO capability... */ callback_rc = (*btm_cb.api.p_sp_callback)(BTM_SP_IO_REQ_EVT, (tBTM_SP_EVT_DATA*)&evt_data); } if ((callback_rc == BTM_SUCCESS) || (BTM_OOB_UNKNOWN != evt_data.oob_data)) { if ((btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD)) { evt_data.auth_req = (BTM_AUTH_DD_BOND | (evt_data.auth_req & BTM_AUTH_YN_BIT)); } if (btm_cb.security_mode == BTM_SEC_MODE_SC) { /* At this moment we know that both sides are SC capable, device in */ /* SC only mode requires MITM for any service so let's set MITM bit */ evt_data.auth_req |= BTM_AUTH_YN_BIT; BTM_TRACE_DEBUG( "%s: for device in \"SC only\" mode set auth_req to 0x%02x", __func__, evt_data.auth_req); } /* if the user does not indicate "reply later" by setting the oob_data to * unknown */ /* send the response right now. Save the current IO capability in the * control block */ btm_cb.devcb.loc_auth_req = evt_data.auth_req; btm_cb.devcb.loc_io_caps = evt_data.io_cap; BTM_TRACE_EVENT("%s: State: %s IO_CAP:%d oob_data:%d auth_req:%d", __func__, btm_pair_state_descr(btm_cb.pairing_state), evt_data.io_cap, evt_data.oob_data, evt_data.auth_req); btsnd_hcic_io_cap_req_reply(evt_data.bd_addr, evt_data.io_cap, evt_data.oob_data, evt_data.auth_req); } } /******************************************************************************* * * Function btm_io_capabilities_rsp * * Description This function is called when the IO capability of the * specified device is received * * Returns void * ******************************************************************************/ void btm_io_capabilities_rsp(uint8_t* p) { tBTM_SEC_DEV_REC* p_dev_rec; tBTM_SP_IO_RSP evt_data; STREAM_TO_BDADDR(evt_data.bd_addr, p); STREAM_TO_UINT8(evt_data.io_cap, p); STREAM_TO_UINT8(evt_data.oob_data, p); STREAM_TO_UINT8(evt_data.auth_req, p); /* Allocate a new device record or reuse the oldest one */ p_dev_rec = btm_find_or_alloc_dev(evt_data.bd_addr); /* If no security is in progress, this indicates incoming security */ if (btm_cb.pairing_state == BTM_PAIR_STATE_IDLE) { memcpy(btm_cb.pairing_bda, evt_data.bd_addr, BD_ADDR_LEN); btm_sec_change_pairing_state(BTM_PAIR_STATE_INCOMING_SSP); /* Make sure we reset the trusted mask to help against attacks */ BTM_SEC_CLR_TRUSTED_DEVICE(p_dev_rec->trusted_mask); /* work around for FW bug */ btm_inq_stop_on_ssp(); } /* Notify L2CAP to increase timeout */ l2c_pin_code_request(evt_data.bd_addr); /* We must have a device record here. * Use the connecting device's CoD for the connection */ if (!memcmp(evt_data.bd_addr, btm_cb.connecting_bda, BD_ADDR_LEN)) memcpy(p_dev_rec->dev_class, btm_cb.connecting_dc, DEV_CLASS_LEN); /* peer sets dedicated bonding bit and we did not initiate dedicated bonding */ if (btm_cb.pairing_state == BTM_PAIR_STATE_INCOMING_SSP /* peer initiated bonding */ && (evt_data.auth_req & BTM_AUTH_DD_BOND)) /* and dedicated bonding bit is set */ { btm_cb.pairing_flags |= BTM_PAIR_FLAGS_PEER_STARTED_DD; } /* save the IO capability in the device record */ p_dev_rec->rmt_io_caps = evt_data.io_cap; p_dev_rec->rmt_auth_req = evt_data.auth_req; if (btm_cb.api.p_sp_callback) (*btm_cb.api.p_sp_callback)(BTM_SP_IO_RSP_EVT, (tBTM_SP_EVT_DATA*)&evt_data); } /******************************************************************************* * * Function btm_proc_sp_req_evt * * Description This function is called to process/report * HCI_USER_CONFIRMATION_REQUEST_EVT * or HCI_USER_PASSKEY_REQUEST_EVT * or HCI_USER_PASSKEY_NOTIFY_EVT * * Returns void * ******************************************************************************/ void btm_proc_sp_req_evt(tBTM_SP_EVT event, uint8_t* p) { tBTM_STATUS status = BTM_ERR_PROCESSING; tBTM_SP_EVT_DATA evt_data; uint8_t* p_bda = evt_data.cfm_req.bd_addr; tBTM_SEC_DEV_REC* p_dev_rec; /* All events start with bd_addr */ STREAM_TO_BDADDR(p_bda, p); BTM_TRACE_EVENT( "btm_proc_sp_req_evt() BDA: %08x%04x event: 0x%x, State: %s", (p_bda[0] << 24) + (p_bda[1] << 16) + (p_bda[2] << 8) + p_bda[3], (p_bda[4] << 8) + p_bda[5], event, btm_pair_state_descr(btm_cb.pairing_state)); p_dev_rec = btm_find_dev(p_bda); if ((p_dev_rec != NULL) && (btm_cb.pairing_state != BTM_PAIR_STATE_IDLE) && (memcmp(btm_cb.pairing_bda, p_bda, BD_ADDR_LEN) == 0)) { memcpy(evt_data.cfm_req.bd_addr, p_dev_rec->bd_addr, BD_ADDR_LEN); memcpy(evt_data.cfm_req.dev_class, p_dev_rec->dev_class, DEV_CLASS_LEN); strlcpy((char*)evt_data.cfm_req.bd_name, (char*)p_dev_rec->sec_bd_name, BTM_MAX_REM_BD_NAME_LEN); switch (event) { case BTM_SP_CFM_REQ_EVT: /* Numeric confirmation. Need user to conf the passkey */ btm_sec_change_pairing_state(BTM_PAIR_STATE_WAIT_NUMERIC_CONFIRM); /* The device record must be allocated in the "IO cap exchange" step */ STREAM_TO_UINT32(evt_data.cfm_req.num_val, p); BTM_TRACE_DEBUG("BTM_SP_CFM_REQ_EVT: num_val: %u", evt_data.cfm_req.num_val); evt_data.cfm_req.just_works = true; /* process user confirm req in association with the auth_req param */ #if (BTM_LOCAL_IO_CAPS == BTM_IO_CAP_IO) if (p_dev_rec->rmt_io_caps == BTM_IO_CAP_UNKNOWN) { BTM_TRACE_ERROR( "%s did not receive IO cap response prior" " to BTM_SP_CFM_REQ_EVT, failing pairing request", __func__); status = BTM_WRONG_MODE; BTM_ConfirmReqReply(status, p_bda); return; } if ((p_dev_rec->rmt_io_caps == BTM_IO_CAP_IO) && (btm_cb.devcb.loc_io_caps == BTM_IO_CAP_IO) && ((p_dev_rec->rmt_auth_req & BTM_AUTH_SP_YES) || (btm_cb.devcb.loc_auth_req & BTM_AUTH_SP_YES))) { /* Both devices are DisplayYesNo and one or both devices want to authenticate -> use authenticated link key */ evt_data.cfm_req.just_works = false; } #endif BTM_TRACE_DEBUG( "btm_proc_sp_req_evt() just_works:%d, io loc:%d, rmt:%d, auth " "loc:%d, rmt:%d", evt_data.cfm_req.just_works, btm_cb.devcb.loc_io_caps, p_dev_rec->rmt_io_caps, btm_cb.devcb.loc_auth_req, p_dev_rec->rmt_auth_req); evt_data.cfm_req.loc_auth_req = btm_cb.devcb.loc_auth_req; evt_data.cfm_req.rmt_auth_req = p_dev_rec->rmt_auth_req; evt_data.cfm_req.loc_io_caps = btm_cb.devcb.loc_io_caps; evt_data.cfm_req.rmt_io_caps = p_dev_rec->rmt_io_caps; break; case BTM_SP_KEY_NOTIF_EVT: /* Passkey notification (other side is a keyboard) */ STREAM_TO_UINT32(evt_data.key_notif.passkey, p); BTM_TRACE_DEBUG("BTM_SP_KEY_NOTIF_EVT: passkey: %u", evt_data.key_notif.passkey); btm_sec_change_pairing_state(BTM_PAIR_STATE_WAIT_AUTH_COMPLETE); break; #if (BTM_LOCAL_IO_CAPS != BTM_IO_CAP_NONE) case BTM_SP_KEY_REQ_EVT: /* HCI_USER_PASSKEY_REQUEST_EVT */ btm_sec_change_pairing_state(BTM_PAIR_STATE_KEY_ENTRY); break; #endif } if (btm_cb.api.p_sp_callback) { status = (*btm_cb.api.p_sp_callback)(event, (tBTM_SP_EVT_DATA*)&evt_data); if (status != BTM_NOT_AUTHORIZED) { return; } /* else BTM_NOT_AUTHORIZED means when the app wants to reject the req * right now */ } else if ((event == BTM_SP_CFM_REQ_EVT) && (evt_data.cfm_req.just_works == true)) { /* automatically reply with just works if no sp_cback */ status = BTM_SUCCESS; } if (event == BTM_SP_CFM_REQ_EVT) { BTM_TRACE_DEBUG("calling BTM_ConfirmReqReply with status: %d", status); BTM_ConfirmReqReply(status, p_bda); } #if (BTM_LOCAL_IO_CAPS != BTM_IO_CAP_NONE) else if (event == BTM_SP_KEY_REQ_EVT) { BTM_PasskeyReqReply(status, p_bda, 0); } #endif return; } /* Something bad. we can only fail this connection */ btm_cb.acl_disc_reason = HCI_ERR_HOST_REJECT_SECURITY; if (BTM_SP_CFM_REQ_EVT == event) { btsnd_hcic_user_conf_reply(p_bda, false); } else if (BTM_SP_KEY_NOTIF_EVT == event) { /* do nothing -> it very unlikely to happen. This event is most likely to be received by a HID host when it first connects to a HID device. Usually the Host initiated the connection in this case. On Mobile platforms, if there's a security process happening, the host probably can not initiate another connection. BTW (PC) is another story. */ p_dev_rec = btm_find_dev(p_bda); if (p_dev_rec != NULL) { btm_sec_disconnect(p_dev_rec->hci_handle, HCI_ERR_AUTH_FAILURE); } } #if (BTM_LOCAL_IO_CAPS != BTM_IO_CAP_NONE) else { btsnd_hcic_user_passkey_neg_reply(p_bda); } #endif } /******************************************************************************* * * Function btm_keypress_notif_evt * * Description This function is called when a key press notification is * received * * Returns void * ******************************************************************************/ void btm_keypress_notif_evt(uint8_t* p) { tBTM_SP_KEYPRESS evt_data; uint8_t* p_bda; /* parse & report BTM_SP_KEYPRESS_EVT */ if (btm_cb.api.p_sp_callback) { p_bda = evt_data.bd_addr; STREAM_TO_BDADDR(p_bda, p); evt_data.notif_type = *p; (*btm_cb.api.p_sp_callback)(BTM_SP_KEYPRESS_EVT, (tBTM_SP_EVT_DATA*)&evt_data); } } /******************************************************************************* * * Function btm_simple_pair_complete * * Description This function is called when simple pairing process is * complete * * Returns void * ******************************************************************************/ void btm_simple_pair_complete(uint8_t* p) { tBTM_SP_COMPLT evt_data; tBTM_SEC_DEV_REC* p_dev_rec; uint8_t status; bool disc = false; status = *p++; STREAM_TO_BDADDR(evt_data.bd_addr, p); p_dev_rec = btm_find_dev(evt_data.bd_addr); if (p_dev_rec == NULL) { BTM_TRACE_ERROR("btm_simple_pair_complete() with unknown BDA: %08x%04x", (evt_data.bd_addr[0] << 24) + (evt_data.bd_addr[1] << 16) + (evt_data.bd_addr[2] << 8) + evt_data.bd_addr[3], (evt_data.bd_addr[4] << 8) + evt_data.bd_addr[5]); return; } BTM_TRACE_EVENT( "btm_simple_pair_complete() Pair State: %s Status:%d sec_state: %u", btm_pair_state_descr(btm_cb.pairing_state), status, p_dev_rec->sec_state); evt_data.status = BTM_ERR_PROCESSING; if (status == HCI_SUCCESS) { evt_data.status = BTM_SUCCESS; p_dev_rec->sec_flags |= BTM_SEC_AUTHENTICATED; } else { if (status == HCI_ERR_PAIRING_NOT_ALLOWED) { /* The test spec wants the peer device to get this failure code. */ btm_sec_change_pairing_state(BTM_PAIR_STATE_WAIT_DISCONNECT); /* Change the timer to 1 second */ alarm_set_on_queue(btm_cb.pairing_timer, BT_1SEC_TIMEOUT_MS, btm_sec_pairing_timeout, NULL, btu_general_alarm_queue); } else if (memcmp(btm_cb.pairing_bda, evt_data.bd_addr, BD_ADDR_LEN) == 0) { /* stop the timer */ alarm_cancel(btm_cb.pairing_timer); if (p_dev_rec->sec_state != BTM_SEC_STATE_AUTHENTICATING) { /* the initiating side: will receive auth complete event. disconnect ACL * at that time */ disc = true; } } else disc = true; } /* Let the pairing state stay active, p_auth_complete_callback will report the * failure */ memcpy(evt_data.bd_addr, p_dev_rec->bd_addr, BD_ADDR_LEN); memcpy(evt_data.dev_class, p_dev_rec->dev_class, DEV_CLASS_LEN); if (btm_cb.api.p_sp_callback) (*btm_cb.api.p_sp_callback)(BTM_SP_COMPLT_EVT, (tBTM_SP_EVT_DATA*)&evt_data); if (disc) { /* simple pairing failed */ /* Avoid sending disconnect on HCI_ERR_PEER_USER */ if ((status != HCI_ERR_PEER_USER) && (status != HCI_ERR_CONN_CAUSE_LOCAL_HOST)) { btm_sec_send_hci_disconnect(p_dev_rec, HCI_ERR_AUTH_FAILURE, p_dev_rec->hci_handle); } } } /******************************************************************************* * * Function btm_rem_oob_req * * Description This function is called to process/report * HCI_REMOTE_OOB_DATA_REQUEST_EVT * * Returns void * ******************************************************************************/ void btm_rem_oob_req(uint8_t* p) { uint8_t* p_bda; tBTM_SP_RMT_OOB evt_data; tBTM_SEC_DEV_REC* p_dev_rec; BT_OCTET16 c; BT_OCTET16 r; p_bda = evt_data.bd_addr; STREAM_TO_BDADDR(p_bda, p); BTM_TRACE_EVENT("btm_rem_oob_req() BDA: %02x:%02x:%02x:%02x:%02x:%02x", p_bda[0], p_bda[1], p_bda[2], p_bda[3], p_bda[4], p_bda[5]); p_dev_rec = btm_find_dev(p_bda); if ((p_dev_rec != NULL) && btm_cb.api.p_sp_callback) { memcpy(evt_data.bd_addr, p_dev_rec->bd_addr, BD_ADDR_LEN); memcpy(evt_data.dev_class, p_dev_rec->dev_class, DEV_CLASS_LEN); strlcpy((char*)evt_data.bd_name, (char*)p_dev_rec->sec_bd_name, BTM_MAX_REM_BD_NAME_LEN); btm_sec_change_pairing_state(BTM_PAIR_STATE_WAIT_LOCAL_OOB_RSP); if ((*btm_cb.api.p_sp_callback)(BTM_SP_RMT_OOB_EVT, (tBTM_SP_EVT_DATA*)&evt_data) == BTM_NOT_AUTHORIZED) { BTM_RemoteOobDataReply(true, p_bda, c, r); } return; } /* something bad. we can only fail this connection */ btm_cb.acl_disc_reason = HCI_ERR_HOST_REJECT_SECURITY; btsnd_hcic_rem_oob_neg_reply(p_bda); } /******************************************************************************* * * Function btm_read_local_oob_complete * * Description This function is called when read local oob data is * completed by the LM * * Returns void * ******************************************************************************/ void btm_read_local_oob_complete(uint8_t* p) { tBTM_SP_LOC_OOB evt_data; uint8_t status = *p++; BTM_TRACE_EVENT("btm_read_local_oob_complete:%d", status); if (status == HCI_SUCCESS) { evt_data.status = BTM_SUCCESS; STREAM_TO_ARRAY16(evt_data.c, p); STREAM_TO_ARRAY16(evt_data.r, p); } else evt_data.status = BTM_ERR_PROCESSING; if (btm_cb.api.p_sp_callback) (*btm_cb.api.p_sp_callback)(BTM_SP_LOC_OOB_EVT, (tBTM_SP_EVT_DATA*)&evt_data); } /******************************************************************************* * * Function btm_sec_auth_collision * * Description This function is called when authentication or encryption * needs to be retried at a later time. * * Returns void * ******************************************************************************/ static void btm_sec_auth_collision(uint16_t handle) { tBTM_SEC_DEV_REC* p_dev_rec; if (!btm_cb.collision_start_time) btm_cb.collision_start_time = time_get_os_boottime_ms(); if ((time_get_os_boottime_ms() - btm_cb.collision_start_time) < btm_cb.max_collision_delay) { if (handle == BTM_SEC_INVALID_HANDLE) { p_dev_rec = btm_sec_find_dev_by_sec_state(BTM_SEC_STATE_AUTHENTICATING); if (p_dev_rec == NULL) p_dev_rec = btm_sec_find_dev_by_sec_state(BTM_SEC_STATE_ENCRYPTING); } else p_dev_rec = btm_find_dev_by_handle(handle); if (p_dev_rec != NULL) { BTM_TRACE_DEBUG( "btm_sec_auth_collision: state %d (retrying in a moment...)", p_dev_rec->sec_state); /* We will restart authentication after timeout */ if (p_dev_rec->sec_state == BTM_SEC_STATE_AUTHENTICATING || p_dev_rec->sec_state == BTM_SEC_STATE_ENCRYPTING) p_dev_rec->sec_state = 0; btm_cb.p_collided_dev_rec = p_dev_rec; alarm_set_on_queue(btm_cb.sec_collision_timer, BT_1SEC_TIMEOUT_MS, btm_sec_collision_timeout, NULL, btu_general_alarm_queue); } } } /****************************************************************************** * * Function btm_sec_auth_retry * * Description This function is called when authentication or encryption * needs to be retried at a later time. * * Returns TRUE if a security retry required * *****************************************************************************/ static bool btm_sec_auth_retry(uint16_t handle, uint8_t status) { tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev_by_handle(handle); if (!p_dev_rec) return false; /* keep the old sm4 flag and clear the retry bit in control block */ uint8_t old_sm4 = p_dev_rec->sm4; p_dev_rec->sm4 &= ~BTM_SM4_RETRY; if ((btm_cb.pairing_state == BTM_PAIR_STATE_IDLE) && ((old_sm4 & BTM_SM4_RETRY) == 0) && (HCI_ERR_KEY_MISSING == status) && BTM_SEC_IS_SM4(p_dev_rec->sm4)) { /* This retry for missing key is for Lisbon or later only. Legacy device do not need this. the controller will drive the retry automatically set the retry bit */ btm_cb.collision_start_time = 0; btm_restore_mode(); p_dev_rec->sm4 |= BTM_SM4_RETRY; p_dev_rec->sec_flags &= ~BTM_SEC_LINK_KEY_KNOWN; BTM_TRACE_DEBUG("%s Retry for missing key sm4:x%x sec_flags:0x%x", __func__, p_dev_rec->sm4, p_dev_rec->sec_flags); /* With BRCM controller, we do not need to delete the stored link key in controller. If the stack may sit on top of other controller, we may need this BTM_DeleteStoredLinkKey (bd_addr, NULL); */ p_dev_rec->sec_state = BTM_SEC_STATE_IDLE; btm_sec_execute_procedure(p_dev_rec); return true; } return false; } /******************************************************************************* * * Function btm_sec_auth_complete * * Description This function is when authentication of the connection is * completed by the LM * * Returns void * ******************************************************************************/ void btm_sec_auth_complete(uint16_t handle, uint8_t status) { tBTM_PAIRING_STATE old_state = btm_cb.pairing_state; tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev_by_handle(handle); bool are_bonding = false; if (p_dev_rec) { BTM_TRACE_EVENT( "Security Manager: auth_complete PairState: %s handle:%u status:%d " "dev->sec_state: %u Bda:%08x, RName:%s", btm_pair_state_descr(btm_cb.pairing_state), handle, status, p_dev_rec->sec_state, (p_dev_rec->bd_addr[2] << 24) + (p_dev_rec->bd_addr[3] << 16) + (p_dev_rec->bd_addr[4] << 8) + p_dev_rec->bd_addr[5], p_dev_rec->sec_bd_name); } else { BTM_TRACE_EVENT( "Security Manager: auth_complete PairState: %s handle:%u status:%d", btm_pair_state_descr(btm_cb.pairing_state), handle, status); } /* For transaction collision we need to wait and repeat. There is no need */ /* for random timeout because only slave should receive the result */ if ((status == HCI_ERR_LMP_ERR_TRANS_COLLISION) || (status == HCI_ERR_DIFF_TRANSACTION_COLLISION)) { btm_sec_auth_collision(handle); return; } else if (btm_sec_auth_retry(handle, status)) { return; } btm_cb.collision_start_time = 0; btm_restore_mode(); /* Check if connection was made just to do bonding. If we authenticate the connection that is up, this is the last event received. */ if (p_dev_rec && (btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) && !(btm_cb.pairing_flags & BTM_PAIR_FLAGS_DISC_WHEN_DONE)) { p_dev_rec->security_required &= ~BTM_SEC_OUT_AUTHENTICATE; l2cu_start_post_bond_timer(p_dev_rec->hci_handle); } if (!p_dev_rec) return; if ((btm_cb.pairing_state != BTM_PAIR_STATE_IDLE) && (btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) && (memcmp(p_dev_rec->bd_addr, btm_cb.pairing_bda, BD_ADDR_LEN) == 0)) are_bonding = true; if ((btm_cb.pairing_state != BTM_PAIR_STATE_IDLE) && (memcmp(p_dev_rec->bd_addr, btm_cb.pairing_bda, BD_ADDR_LEN) == 0)) btm_sec_change_pairing_state(BTM_PAIR_STATE_IDLE); if (p_dev_rec->sec_state != BTM_SEC_STATE_AUTHENTICATING) { if ((btm_cb.api.p_auth_complete_callback && status != HCI_SUCCESS) && (old_state != BTM_PAIR_STATE_IDLE)) { (*btm_cb.api.p_auth_complete_callback)(p_dev_rec->bd_addr, p_dev_rec->dev_class, p_dev_rec->sec_bd_name, status); } return; } /* There can be a race condition, when we are starting authentication and ** the peer device is doing encryption. ** If first we receive encryption change up, then initiated authentication ** can not be performed. According to the spec we can not do authentication ** on the encrypted link, so device is correct. */ if ((status == HCI_ERR_COMMAND_DISALLOWED) && ((p_dev_rec->sec_flags & (BTM_SEC_AUTHENTICATED | BTM_SEC_ENCRYPTED)) == (BTM_SEC_AUTHENTICATED | BTM_SEC_ENCRYPTED))) { status = HCI_SUCCESS; } /* Currently we do not notify user if it is a keyboard which connects */ /* User probably Disabled the keyboard while it was asleap. Let her try */ if (btm_cb.api.p_auth_complete_callback) { /* report the suthentication status */ if ((old_state != BTM_PAIR_STATE_IDLE) || (status != HCI_SUCCESS)) (*btm_cb.api.p_auth_complete_callback)(p_dev_rec->bd_addr, p_dev_rec->dev_class, p_dev_rec->sec_bd_name, status); } p_dev_rec->sec_state = BTM_SEC_STATE_IDLE; /* If this is a bonding procedure can disconnect the link now */ if (are_bonding) { p_dev_rec->security_required &= ~BTM_SEC_OUT_AUTHENTICATE; if (status != HCI_SUCCESS) { if (((status != HCI_ERR_PEER_USER) && (status != HCI_ERR_CONN_CAUSE_LOCAL_HOST))) btm_sec_send_hci_disconnect(p_dev_rec, HCI_ERR_PEER_USER, p_dev_rec->hci_handle); } else { BTM_TRACE_DEBUG("TRYING TO DECIDE IF CAN USE SMP_BR_CHNL"); if (p_dev_rec->new_encryption_key_is_p256 && (btm_sec_use_smp_br_chnl(p_dev_rec)) /* no LE keys are available, do deriving */ && (!(p_dev_rec->sec_flags & BTM_SEC_LE_LINK_KEY_KNOWN) || /* or BR key is higher security than existing LE keys */ (!(p_dev_rec->sec_flags & BTM_SEC_LE_LINK_KEY_AUTHED) && (p_dev_rec->sec_flags & BTM_SEC_LINK_KEY_AUTHED)))) { BTM_TRACE_DEBUG( "link encrypted afer dedic bonding can use SMP_BR_CHNL"); if (btm_sec_is_master(p_dev_rec)) { // Encryption is required to start SM over BR/EDR // indicate that this is encryption after authentication BTM_SetEncryption(p_dev_rec->bd_addr, BT_TRANSPORT_BR_EDR, NULL, NULL, 0); } } l2cu_start_post_bond_timer(p_dev_rec->hci_handle); } return; } /* If authentication failed, notify the waiting layer */ if (status != HCI_SUCCESS) { btm_sec_dev_rec_cback_event(p_dev_rec, BTM_ERR_PROCESSING, false); if (btm_cb.pairing_flags & BTM_PAIR_FLAGS_DISC_WHEN_DONE) { btm_sec_send_hci_disconnect(p_dev_rec, HCI_ERR_AUTH_FAILURE, p_dev_rec->hci_handle); } return; } p_dev_rec->sec_flags |= BTM_SEC_AUTHENTICATED; if (p_dev_rec->pin_code_length >= 16 || p_dev_rec->link_key_type == BTM_LKEY_TYPE_AUTH_COMB || p_dev_rec->link_key_type == BTM_LKEY_TYPE_AUTH_COMB_P_256) { // If we have MITM protection we have a higher level of security than // provided by 16 digits PIN p_dev_rec->sec_flags |= BTM_SEC_16_DIGIT_PIN_AUTHED; } /* Authentication succeeded, execute the next security procedure, if any */ status = btm_sec_execute_procedure(p_dev_rec); /* If there is no next procedure, or procedure failed to start, notify the * caller */ if (status != BTM_CMD_STARTED) btm_sec_dev_rec_cback_event(p_dev_rec, status, false); } /******************************************************************************* * * Function btm_sec_encrypt_change * * Description This function is when encryption of the connection is * completed by the LM * * Returns void * ******************************************************************************/ void btm_sec_encrypt_change(uint16_t handle, uint8_t status, uint8_t encr_enable) { tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev_by_handle(handle); tACL_CONN* p_acl = NULL; uint8_t acl_idx = btm_handle_to_acl_index(handle); BTM_TRACE_EVENT( "Security Manager: encrypt_change status:%d State:%d, encr_enable = %d", status, (p_dev_rec) ? p_dev_rec->sec_state : 0, encr_enable); BTM_TRACE_DEBUG("before update p_dev_rec->sec_flags=0x%x", (p_dev_rec) ? p_dev_rec->sec_flags : 0); /* For transaction collision we need to wait and repeat. There is no need */ /* for random timeout because only slave should receive the result */ if ((status == HCI_ERR_LMP_ERR_TRANS_COLLISION) || (status == HCI_ERR_DIFF_TRANSACTION_COLLISION)) { btm_sec_auth_collision(handle); return; } btm_cb.collision_start_time = 0; if (!p_dev_rec) return; if ((status == HCI_SUCCESS) && encr_enable) { if (p_dev_rec->hci_handle == handle) { p_dev_rec->sec_flags |= (BTM_SEC_AUTHENTICATED | BTM_SEC_ENCRYPTED); if (p_dev_rec->pin_code_length >= 16 || p_dev_rec->link_key_type == BTM_LKEY_TYPE_AUTH_COMB || p_dev_rec->link_key_type == BTM_LKEY_TYPE_AUTH_COMB_P_256) { p_dev_rec->sec_flags |= BTM_SEC_16_DIGIT_PIN_AUTHED; } } else { p_dev_rec->sec_flags |= (BTM_SEC_LE_AUTHENTICATED | BTM_SEC_LE_ENCRYPTED); } } /* It is possible that we decrypted the link to perform role switch */ /* mark link not to be encrypted, so that when we execute security next time * it will kick in again */ if ((status == HCI_SUCCESS) && !encr_enable) { if (p_dev_rec->hci_handle == handle) p_dev_rec->sec_flags &= ~BTM_SEC_ENCRYPTED; else p_dev_rec->sec_flags &= ~BTM_SEC_LE_ENCRYPTED; } BTM_TRACE_DEBUG("after update p_dev_rec->sec_flags=0x%x", p_dev_rec->sec_flags); if (acl_idx != MAX_L2CAP_LINKS) p_acl = &btm_cb.acl_db[acl_idx]; if (p_acl != NULL) btm_sec_check_pending_enc_req(p_dev_rec, p_acl->transport, encr_enable); if (p_acl && p_acl->transport == BT_TRANSPORT_LE) { if (status == HCI_ERR_KEY_MISSING || status == HCI_ERR_AUTH_FAILURE || status == HCI_ERR_ENCRY_MODE_NOT_ACCEPTABLE) { p_dev_rec->sec_flags &= ~(BTM_SEC_LE_LINK_KEY_KNOWN); p_dev_rec->ble.key_type = BTM_LE_KEY_NONE; } btm_ble_link_encrypted(p_dev_rec->ble.pseudo_addr, encr_enable); return; } else { /* BR/EDR connection, update the encryption key size to be 16 as always */ p_dev_rec->enc_key_size = 16; } BTM_TRACE_DEBUG("in %s new_encr_key_256 is %d", __func__, p_dev_rec->new_encryption_key_is_p256); if ((status == HCI_SUCCESS) && encr_enable && (p_dev_rec->hci_handle == handle)) { /* if BR key is temporary no need for LE LTK derivation */ bool derive_ltk = true; if (p_dev_rec->rmt_auth_req == BTM_AUTH_SP_NO && btm_cb.devcb.loc_auth_req == BTM_AUTH_SP_NO) { derive_ltk = false; BTM_TRACE_DEBUG("%s: BR key is temporary, skip derivation of LE LTK", __func__); } if (p_dev_rec->new_encryption_key_is_p256) { if (btm_sec_use_smp_br_chnl(p_dev_rec) && btm_sec_is_master(p_dev_rec) && /* if LE key is not known, do deriving */ (!(p_dev_rec->sec_flags & BTM_SEC_LE_LINK_KEY_KNOWN) || /* or BR key is higher security than existing LE keys */ (!(p_dev_rec->sec_flags & BTM_SEC_LE_LINK_KEY_AUTHED) && (p_dev_rec->sec_flags & BTM_SEC_LINK_KEY_AUTHED))) && derive_ltk) { /* BR/EDR is encrypted with LK that can be used to derive LE LTK */ p_dev_rec->new_encryption_key_is_p256 = false; if (p_dev_rec->no_smp_on_br) { BTM_TRACE_DEBUG("%s NO SM over BR/EDR", __func__); } else { BTM_TRACE_DEBUG("%s start SM over BR/EDR", __func__); SMP_BR_PairWith(p_dev_rec->bd_addr); } } } else { // BR/EDR is successfully encrypted. Correct LK type if needed // (BR/EDR LK derived from LE LTK was used for encryption) if ((encr_enable == 1) && /* encryption is ON for SSP */ /* LK type is for BR/EDR SC */ (p_dev_rec->link_key_type == BTM_LKEY_TYPE_UNAUTH_COMB_P_256 || p_dev_rec->link_key_type == BTM_LKEY_TYPE_AUTH_COMB_P_256)) { if (p_dev_rec->link_key_type == BTM_LKEY_TYPE_UNAUTH_COMB_P_256) p_dev_rec->link_key_type = BTM_LKEY_TYPE_UNAUTH_COMB; else /* BTM_LKEY_TYPE_AUTH_COMB_P_256 */ p_dev_rec->link_key_type = BTM_LKEY_TYPE_AUTH_COMB; BTM_TRACE_DEBUG("updated link key type to %d", p_dev_rec->link_key_type); btm_send_link_key_notif(p_dev_rec); } } } /* If this encryption was started by peer do not need to do anything */ if (p_dev_rec->sec_state != BTM_SEC_STATE_ENCRYPTING) { if (BTM_SEC_STATE_DELAY_FOR_ENC == p_dev_rec->sec_state) { p_dev_rec->sec_state = BTM_SEC_STATE_IDLE; p_dev_rec->p_callback = NULL; l2cu_resubmit_pending_sec_req(p_dev_rec->bd_addr); } return; } p_dev_rec->sec_state = BTM_SEC_STATE_IDLE; /* If encryption setup failed, notify the waiting layer */ if (status != HCI_SUCCESS) { btm_sec_dev_rec_cback_event(p_dev_rec, BTM_ERR_PROCESSING, false); return; } /* Encryption setup succeeded, execute the next security procedure, if any */ status = (uint8_t)btm_sec_execute_procedure(p_dev_rec); /* If there is no next procedure, or procedure failed to start, notify the * caller */ if (status != BTM_CMD_STARTED) btm_sec_dev_rec_cback_event(p_dev_rec, status, false); } /******************************************************************************* * * Function btm_sec_connect_after_reject_timeout * * Description Connection for bonding could not start because of the * collision. Initiate outgoing connection * * Returns Pointer to the TLE struct * ******************************************************************************/ static void btm_sec_connect_after_reject_timeout(UNUSED_ATTR void* data) { tBTM_SEC_DEV_REC* p_dev_rec = btm_cb.p_collided_dev_rec; BTM_TRACE_EVENT("%s", __func__); btm_cb.p_collided_dev_rec = 0; if (btm_sec_dd_create_conn(p_dev_rec) != BTM_CMD_STARTED) { BTM_TRACE_WARNING("Security Manager: %s: failed to start connection", __func__); btm_sec_change_pairing_state(BTM_PAIR_STATE_IDLE); if (btm_cb.api.p_auth_complete_callback) (*btm_cb.api.p_auth_complete_callback)( p_dev_rec->bd_addr, p_dev_rec->dev_class, p_dev_rec->sec_bd_name, HCI_ERR_MEMORY_FULL); } } /******************************************************************************* * * Function btm_sec_connected * * Description This function is when a connection to the peer device is * establsihed * * Returns void * ******************************************************************************/ void btm_sec_connected(uint8_t* bda, uint16_t handle, uint8_t status, uint8_t enc_mode) { tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bda); uint8_t res; bool is_pairing_device = false; tACL_CONN* p_acl_cb; uint8_t bit_shift = 0; btm_acl_resubmit_page(); if (p_dev_rec) { BTM_TRACE_EVENT( "Security Manager: btm_sec_connected in state: %s handle:%d status:%d " "enc_mode:%d bda:%x RName:%s", btm_pair_state_descr(btm_cb.pairing_state), handle, status, enc_mode, (bda[2] << 24) + (bda[3] << 16) + (bda[4] << 8) + bda[5], p_dev_rec->sec_bd_name); } else { BTM_TRACE_EVENT( "Security Manager: btm_sec_connected in state: %s handle:%d status:%d " "enc_mode:%d bda:%x ", btm_pair_state_descr(btm_cb.pairing_state), handle, status, enc_mode, (bda[2] << 24) + (bda[3] << 16) + (bda[4] << 8) + bda[5]); } if (!p_dev_rec) { /* There is no device record for new connection. Allocate one */ if (status == HCI_SUCCESS) { p_dev_rec = btm_sec_alloc_dev(bda); } else { /* If the device matches with stored paring address * reset the paring state to idle */ if ((btm_cb.pairing_state != BTM_PAIR_STATE_IDLE) && (memcmp(btm_cb.pairing_bda, bda, BD_ADDR_LEN) == 0)) { btm_sec_change_pairing_state(BTM_PAIR_STATE_IDLE); } /* can not find the device record and the status is error, * just ignore it */ return; } } else /* Update the timestamp for this device */ { bit_shift = (handle == p_dev_rec->ble_hci_handle) ? 8 : 0; p_dev_rec->timestamp = btm_cb.dev_rec_count++; if (p_dev_rec->sm4 & BTM_SM4_CONN_PEND) { /* tell L2CAP it's a bonding connection. */ if ((btm_cb.pairing_state != BTM_PAIR_STATE_IDLE) && (memcmp(btm_cb.pairing_bda, p_dev_rec->bd_addr, BD_ADDR_LEN) == 0) && (btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD)) { /* if incoming connection failed while pairing, then try to connect and * continue */ /* Motorola S9 disconnects without asking pin code */ if ((status != HCI_SUCCESS) && (btm_cb.pairing_state == BTM_PAIR_STATE_WAIT_PIN_REQ)) { BTM_TRACE_WARNING( "Security Manager: btm_sec_connected: incoming connection failed " "without asking PIN"); p_dev_rec->sm4 &= ~BTM_SM4_CONN_PEND; if (p_dev_rec->sec_flags & BTM_SEC_NAME_KNOWN) { /* Start timer with 0 to initiate connection with new LCB */ /* because L2CAP will delete current LCB with this event */ btm_cb.p_collided_dev_rec = p_dev_rec; alarm_set_on_queue(btm_cb.sec_collision_timer, 0, btm_sec_connect_after_reject_timeout, NULL, btu_general_alarm_queue); } else { btm_sec_change_pairing_state(BTM_PAIR_STATE_GET_REM_NAME); if (BTM_ReadRemoteDeviceName(p_dev_rec->bd_addr, NULL, BT_TRANSPORT_BR_EDR) != BTM_CMD_STARTED) { BTM_TRACE_ERROR("%s cannot read remote name", __func__); btm_sec_change_pairing_state(BTM_PAIR_STATE_IDLE); } } #if (BTM_DISC_DURING_RS == TRUE) p_dev_rec->rs_disc_pending = BTM_SEC_RS_NOT_PENDING; /* reset flag */ #endif return; } else { l2cu_update_lcb_4_bonding(p_dev_rec->bd_addr, true); } } /* always clear the pending flag */ p_dev_rec->sm4 &= ~BTM_SM4_CONN_PEND; } } p_dev_rec->device_type |= BT_DEVICE_TYPE_BREDR; #if (BTM_DISC_DURING_RS == TRUE) p_dev_rec->rs_disc_pending = BTM_SEC_RS_NOT_PENDING; /* reset flag */ #endif p_dev_rec->rs_disc_pending = BTM_SEC_RS_NOT_PENDING; /* reset flag */ if ((btm_cb.pairing_state != BTM_PAIR_STATE_IDLE) && (memcmp(btm_cb.pairing_bda, bda, BD_ADDR_LEN) == 0)) { /* if we rejected incoming connection from bonding device */ if ((status == HCI_ERR_HOST_REJECT_DEVICE) && (btm_cb.pairing_flags & BTM_PAIR_FLAGS_REJECTED_CONNECT)) { BTM_TRACE_WARNING( "Security Manager: btm_sec_connected: HCI_Conn_Comp Flags:0x%04x, " "sm4: 0x%x", btm_cb.pairing_flags, p_dev_rec->sm4); btm_cb.pairing_flags &= ~BTM_PAIR_FLAGS_REJECTED_CONNECT; if (BTM_SEC_IS_SM4_UNKNOWN(p_dev_rec->sm4)) { /* Try again: RNR when no ACL causes HCI_RMT_HOST_SUP_FEAT_NOTIFY_EVT */ btm_sec_change_pairing_state(BTM_PAIR_STATE_GET_REM_NAME); if (BTM_ReadRemoteDeviceName(bda, NULL, BT_TRANSPORT_BR_EDR) != BTM_CMD_STARTED) { BTM_TRACE_ERROR("%s cannot read remote name", __func__); btm_sec_change_pairing_state(BTM_PAIR_STATE_IDLE); } return; } /* if we already have pin code */ if (btm_cb.pairing_state != BTM_PAIR_STATE_WAIT_LOCAL_PIN) { /* Start timer with 0 to initiate connection with new LCB */ /* because L2CAP will delete current LCB with this event */ btm_cb.p_collided_dev_rec = p_dev_rec; alarm_set_on_queue(btm_cb.sec_collision_timer, 0, btm_sec_connect_after_reject_timeout, NULL, btu_general_alarm_queue); } return; } /* wait for incoming connection without resetting pairing state */ else if (status == HCI_ERR_CONNECTION_EXISTS) { BTM_TRACE_WARNING( "Security Manager: btm_sec_connected: Wait for incoming connection"); return; } is_pairing_device = true; } /* If connection was made to do bonding restore link security if changed */ btm_restore_mode(); /* if connection fails during pin request, notify application */ if (status != HCI_SUCCESS) { /* If connection failed because of during pairing, need to tell user */ if (is_pairing_device) { p_dev_rec->security_required &= ~BTM_SEC_OUT_AUTHENTICATE; p_dev_rec->sec_flags &= ~((BTM_SEC_LINK_KEY_KNOWN | BTM_SEC_LINK_KEY_AUTHED) << bit_shift); BTM_TRACE_DEBUG("security_required:%x ", p_dev_rec->security_required); btm_sec_change_pairing_state(BTM_PAIR_STATE_IDLE); /* We need to notify host that the key is not known any more */ if (btm_cb.api.p_auth_complete_callback) { (*btm_cb.api.p_auth_complete_callback)(p_dev_rec->bd_addr, p_dev_rec->dev_class, p_dev_rec->sec_bd_name, status); } } /* Do not send authentication failure, if following conditions hold good 1. BTM Sec Pairing state is idle 2. Link key for the remote device is present. 3. Remote is SSP capable. */ else if ((p_dev_rec->link_key_type <= BTM_LKEY_TYPE_REMOTE_UNIT) && (((status == HCI_ERR_AUTH_FAILURE) || (status == HCI_ERR_KEY_MISSING) || (status == HCI_ERR_HOST_REJECT_SECURITY) || (status == HCI_ERR_PAIRING_NOT_ALLOWED) || (status == HCI_ERR_UNIT_KEY_USED) || (status == HCI_ERR_PAIRING_WITH_UNIT_KEY_NOT_SUPPORTED) || (status == HCI_ERR_ENCRY_MODE_NOT_ACCEPTABLE) || (status == HCI_ERR_REPEATED_ATTEMPTS)))) { p_dev_rec->security_required &= ~BTM_SEC_OUT_AUTHENTICATE; p_dev_rec->sec_flags &= ~(BTM_SEC_LE_LINK_KEY_KNOWN << bit_shift); #ifdef BRCM_NOT_4_BTE /* If we rejected pairing, pass this special result code */ if (btm_cb.acl_disc_reason == HCI_ERR_HOST_REJECT_SECURITY) { status = HCI_ERR_HOST_REJECT_SECURITY; } #endif /* We need to notify host that the key is not known any more */ if (btm_cb.api.p_auth_complete_callback) { (*btm_cb.api.p_auth_complete_callback)(p_dev_rec->bd_addr, p_dev_rec->dev_class, p_dev_rec->sec_bd_name, status); } } if (status == HCI_ERR_CONNECTION_TOUT || status == HCI_ERR_LMP_RESPONSE_TIMEOUT || status == HCI_ERR_UNSPECIFIED || status == HCI_ERR_PAGE_TIMEOUT) btm_sec_dev_rec_cback_event(p_dev_rec, BTM_DEVICE_TIMEOUT, false); else btm_sec_dev_rec_cback_event(p_dev_rec, BTM_ERR_PROCESSING, false); return; } /* If initiated dedicated bonding, return the link key now, and initiate * disconnect */ /* If dedicated bonding, and we now have a link key, we are all done */ if (is_pairing_device && (p_dev_rec->sec_flags & BTM_SEC_LINK_KEY_KNOWN)) { if (p_dev_rec->link_key_not_sent) { p_dev_rec->link_key_not_sent = false; btm_send_link_key_notif(p_dev_rec); } p_dev_rec->security_required &= ~BTM_SEC_OUT_AUTHENTICATE; /* remember flag before it is initialized */ if (btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) res = true; else res = false; if (btm_cb.api.p_auth_complete_callback) (*btm_cb.api.p_auth_complete_callback)( p_dev_rec->bd_addr, p_dev_rec->dev_class, p_dev_rec->sec_bd_name, HCI_SUCCESS); btm_sec_change_pairing_state(BTM_PAIR_STATE_IDLE); if (res) { /* Let l2cap start bond timer */ l2cu_update_lcb_4_bonding(p_dev_rec->bd_addr, true); } return; } p_dev_rec->hci_handle = handle; /* role may not be correct here, it will be updated by l2cap, but we need to */ /* notify btm_acl that link is up, so starting of rmt name request will not */ /* set paging flag up */ p_acl_cb = btm_bda_to_acl(bda, BT_TRANSPORT_BR_EDR); if (p_acl_cb) { /* whatever is in btm_establish_continue() without reporting the BTM_BL_CONN_EVT * event */ #if (BTM_BYPASS_EXTRA_ACL_SETUP == FALSE) /* For now there are a some devices that do not like sending */ /* commands events and data at the same time. */ /* Set the packet types to the default allowed by the device */ btm_set_packet_types(p_acl_cb, btm_cb.btm_acl_pkt_types_supported); if (btm_cb.btm_def_link_policy) BTM_SetLinkPolicy(p_acl_cb->remote_addr, &btm_cb.btm_def_link_policy); #endif } btm_acl_created(bda, p_dev_rec->dev_class, p_dev_rec->sec_bd_name, handle, HCI_ROLE_SLAVE, BT_TRANSPORT_BR_EDR); /* Initialize security flags. We need to do that because some */ /* authorization complete could have come after the connection is dropped */ /* and that would set wrong flag that link has been authorized already */ p_dev_rec->sec_flags &= ~((BTM_SEC_AUTHORIZED | BTM_SEC_AUTHENTICATED | BTM_SEC_ENCRYPTED | BTM_SEC_ROLE_SWITCHED) << bit_shift); if (enc_mode != HCI_ENCRYPT_MODE_DISABLED) p_dev_rec->sec_flags |= ((BTM_SEC_AUTHENTICATED | BTM_SEC_ENCRYPTED) << bit_shift); if (btm_cb.security_mode == BTM_SEC_MODE_LINK) p_dev_rec->sec_flags |= (BTM_SEC_AUTHENTICATED << bit_shift); if (p_dev_rec->pin_code_length >= 16 || p_dev_rec->link_key_type == BTM_LKEY_TYPE_AUTH_COMB || p_dev_rec->link_key_type == BTM_LKEY_TYPE_AUTH_COMB_P_256) { p_dev_rec->sec_flags |= (BTM_SEC_16_DIGIT_PIN_AUTHED << bit_shift); } p_dev_rec->link_key_changed = false; /* After connection is established we perform security if we do not know */ /* the name, or if we are originator because some procedure can have */ /* been scheduled while connection was down */ BTM_TRACE_DEBUG("is_originator:%d ", p_dev_rec->is_originator); if (!(p_dev_rec->sec_flags & BTM_SEC_NAME_KNOWN) || p_dev_rec->is_originator) { res = btm_sec_execute_procedure(p_dev_rec); if (res != BTM_CMD_STARTED) btm_sec_dev_rec_cback_event(p_dev_rec, res, false); } return; } /******************************************************************************* * * Function btm_sec_disconnect * * Description This function is called to disconnect HCI link * * Returns btm status * ******************************************************************************/ tBTM_STATUS btm_sec_disconnect(uint16_t handle, uint8_t reason) { tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev_by_handle(handle); /* In some weird race condition we may not have a record */ if (!p_dev_rec) { btsnd_hcic_disconnect(handle, reason); return (BTM_SUCCESS); } /* If we are in the process of bonding we need to tell client that auth failed */ if ((btm_cb.pairing_state != BTM_PAIR_STATE_IDLE) && (memcmp(btm_cb.pairing_bda, p_dev_rec->bd_addr, BD_ADDR_LEN) == 0) && (btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD)) { /* we are currently doing bonding. Link will be disconnected when done */ btm_cb.pairing_flags |= BTM_PAIR_FLAGS_DISC_WHEN_DONE; return (BTM_BUSY); } return (btm_sec_send_hci_disconnect(p_dev_rec, reason, handle)); } /******************************************************************************* * * Function btm_sec_disconnected * * Description This function is when a connection to the peer device is * dropped * * Returns void * ******************************************************************************/ void btm_sec_disconnected(uint16_t handle, uint8_t reason) { tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev_by_handle(handle); uint8_t old_pairing_flags = btm_cb.pairing_flags; int result = HCI_ERR_AUTH_FAILURE; tBTM_SEC_CALLBACK* p_callback = NULL; tBT_TRANSPORT transport = BT_TRANSPORT_BR_EDR; /* If page was delayed for disc complete, can do it now */ btm_cb.discing = false; btm_acl_resubmit_page(); if (!p_dev_rec) return; transport = (handle == p_dev_rec->hci_handle) ? BT_TRANSPORT_BR_EDR : BT_TRANSPORT_LE; p_dev_rec->rs_disc_pending = BTM_SEC_RS_NOT_PENDING; /* reset flag */ #if (BTM_DISC_DURING_RS == TRUE) LOG_INFO(LOG_TAG, "%s clearing pending flag handle:%d reason:%d", __func__, handle, reason); p_dev_rec->rs_disc_pending = BTM_SEC_RS_NOT_PENDING; /* reset flag */ #endif /* clear unused flags */ p_dev_rec->sm4 &= BTM_SM4_TRUE; uint8_t* bd_addr = (uint8_t*)p_dev_rec->bd_addr; BTM_TRACE_EVENT( "%s sec_req:x%x state:%s reason:%d bd_addr:%02x:%02x:%02x:%02x:%02x:%02x" " remote_name:%s", __func__, p_dev_rec->security_required, btm_pair_state_descr(btm_cb.pairing_state), reason, bd_addr[0], bd_addr[1], bd_addr[2], bd_addr[3], bd_addr[4], bd_addr[5], p_dev_rec->sec_bd_name); BTM_TRACE_EVENT("%s before update sec_flags=0x%x", __func__, p_dev_rec->sec_flags); /* If we are in the process of bonding we need to tell client that auth failed */ if ((btm_cb.pairing_state != BTM_PAIR_STATE_IDLE) && (memcmp(btm_cb.pairing_bda, p_dev_rec->bd_addr, BD_ADDR_LEN) == 0)) { btm_sec_change_pairing_state(BTM_PAIR_STATE_IDLE); p_dev_rec->sec_flags &= ~BTM_SEC_LINK_KEY_KNOWN; if (btm_cb.api.p_auth_complete_callback) { /* If the disconnection reason is REPEATED_ATTEMPTS, send this error message to complete callback function to display the error message of Repeated attempts. All others, send HCI_ERR_AUTH_FAILURE. */ if (reason == HCI_ERR_REPEATED_ATTEMPTS) { result = HCI_ERR_REPEATED_ATTEMPTS; } else if (old_pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) { result = HCI_ERR_HOST_REJECT_SECURITY; } (*btm_cb.api.p_auth_complete_callback)(p_dev_rec->bd_addr, p_dev_rec->dev_class, p_dev_rec->sec_bd_name, result); } } btm_ble_update_mode_operation(HCI_ROLE_UNKNOWN, p_dev_rec->bd_addr, HCI_SUCCESS); /* see sec_flags processing in btm_acl_removed */ if (transport == BT_TRANSPORT_LE) { p_dev_rec->ble_hci_handle = BTM_SEC_INVALID_HANDLE; p_dev_rec->sec_flags &= ~(BTM_SEC_LE_AUTHENTICATED | BTM_SEC_LE_ENCRYPTED); p_dev_rec->enc_key_size = 0; } else { p_dev_rec->hci_handle = BTM_SEC_INVALID_HANDLE; p_dev_rec->sec_flags &= ~(BTM_SEC_AUTHORIZED | BTM_SEC_AUTHENTICATED | BTM_SEC_ENCRYPTED | BTM_SEC_ROLE_SWITCHED | BTM_SEC_16_DIGIT_PIN_AUTHED); } if (p_dev_rec->sec_state == BTM_SEC_STATE_DISCONNECTING_BOTH) { p_dev_rec->sec_state = (transport == BT_TRANSPORT_LE) ? BTM_SEC_STATE_DISCONNECTING : BTM_SEC_STATE_DISCONNECTING_BLE; return; } p_dev_rec->sec_state = BTM_SEC_STATE_IDLE; p_dev_rec->security_required = BTM_SEC_NONE; p_callback = p_dev_rec->p_callback; /* if security is pending, send callback to clean up the security state */ if (p_callback) { p_dev_rec->p_callback = NULL; /* when the peer device time out the authentication before we do, this call back must be reset here */ (*p_callback)(p_dev_rec->bd_addr, transport, p_dev_rec->p_ref_data, BTM_ERR_PROCESSING); } BTM_TRACE_EVENT("%s after update sec_flags=0x%x", __func__, p_dev_rec->sec_flags); } /******************************************************************************* * * Function btm_sec_link_key_notification * * Description This function is called when a new connection link key is * generated * * Returns Pointer to the record or NULL * ******************************************************************************/ void btm_sec_link_key_notification(uint8_t* p_bda, uint8_t* p_link_key, uint8_t key_type) { tBTM_SEC_DEV_REC* p_dev_rec = btm_find_or_alloc_dev(p_bda); bool we_are_bonding = false; bool ltk_derived_lk = false; BTM_TRACE_EVENT( "btm_sec_link_key_notification() BDA:%04x%08x, TYPE: %d", (p_bda[0] << 8) + p_bda[1], (p_bda[2] << 24) + (p_bda[3] << 16) + (p_bda[4] << 8) + p_bda[5], key_type); if ((key_type >= BTM_LTK_DERIVED_LKEY_OFFSET + BTM_LKEY_TYPE_COMBINATION) && (key_type <= BTM_LTK_DERIVED_LKEY_OFFSET + BTM_LKEY_TYPE_AUTH_COMB_P_256)) { ltk_derived_lk = true; key_type -= BTM_LTK_DERIVED_LKEY_OFFSET; } /* If connection was made to do bonding restore link security if changed */ btm_restore_mode(); if (key_type != BTM_LKEY_TYPE_CHANGED_COMB) p_dev_rec->link_key_type = key_type; p_dev_rec->sec_flags |= BTM_SEC_LINK_KEY_KNOWN; /* * Until this point in time, we do not know if MITM was enabled, hence we * add the extended security flag here. */ if (p_dev_rec->pin_code_length >= 16 || p_dev_rec->link_key_type == BTM_LKEY_TYPE_AUTH_COMB || p_dev_rec->link_key_type == BTM_LKEY_TYPE_AUTH_COMB_P_256) { p_dev_rec->sec_flags |= BTM_SEC_16_DIGIT_PIN_AUTHED; } /* BR/EDR connection, update the encryption key size to be 16 as always */ p_dev_rec->enc_key_size = 16; memcpy(p_dev_rec->link_key, p_link_key, LINK_KEY_LEN); if ((btm_cb.pairing_state != BTM_PAIR_STATE_IDLE) && (memcmp(btm_cb.pairing_bda, p_bda, BD_ADDR_LEN) == 0)) { if (btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) we_are_bonding = true; else btm_sec_change_pairing_state(BTM_PAIR_STATE_IDLE); } /* save LTK derived LK no matter what */ if (ltk_derived_lk) { if (btm_cb.api.p_link_key_callback) { BTM_TRACE_DEBUG("%s() Save LTK derived LK (key_type = %d)", __func__, p_dev_rec->link_key_type); (*btm_cb.api.p_link_key_callback)(p_bda, p_dev_rec->dev_class, p_dev_rec->sec_bd_name, p_link_key, p_dev_rec->link_key_type); } } else { if ((p_dev_rec->link_key_type == BTM_LKEY_TYPE_UNAUTH_COMB_P_256) || (p_dev_rec->link_key_type == BTM_LKEY_TYPE_AUTH_COMB_P_256)) { p_dev_rec->new_encryption_key_is_p256 = true; BTM_TRACE_DEBUG("%s set new_encr_key_256 to %d", __func__, p_dev_rec->new_encryption_key_is_p256); } } /* If name is not known at this point delay calling callback until the name is */ /* resolved. Unless it is a HID Device and we really need to send all link * keys. */ if ((!(p_dev_rec->sec_flags & BTM_SEC_NAME_KNOWN) && ((p_dev_rec->dev_class[1] & BTM_COD_MAJOR_CLASS_MASK) != BTM_COD_MAJOR_PERIPHERAL)) && !ltk_derived_lk) { BTM_TRACE_EVENT( "btm_sec_link_key_notification() Delayed BDA: %08x%04x Type:%d", (p_bda[0] << 24) + (p_bda[1] << 16) + (p_bda[2] << 8) + p_bda[3], (p_bda[4] << 8) + p_bda[5], key_type); p_dev_rec->link_key_not_sent = true; /* If it is for bonding nothing else will follow, so we need to start name * resolution */ if (we_are_bonding) { btsnd_hcic_rmt_name_req(p_bda, HCI_PAGE_SCAN_REP_MODE_R1, HCI_MANDATARY_PAGE_SCAN_MODE, 0); } BTM_TRACE_EVENT("rmt_io_caps:%d, sec_flags:x%x, dev_class[1]:x%02x", p_dev_rec->rmt_io_caps, p_dev_rec->sec_flags, p_dev_rec->dev_class[1]) return; } /* If its not us who perform authentication, we should tell stackserver */ /* that some authentication has been completed */ /* This is required when different entities receive link notification and auth * complete */ if (!(p_dev_rec->security_required & BTM_SEC_OUT_AUTHENTICATE) /* for derived key, always send authentication callback for BR channel */ || ltk_derived_lk) { if (btm_cb.api.p_auth_complete_callback) (*btm_cb.api.p_auth_complete_callback)( p_dev_rec->bd_addr, p_dev_rec->dev_class, p_dev_rec->sec_bd_name, HCI_SUCCESS); } /* We will save link key only if the user authorized it - BTE report link key in * all cases */ #ifdef BRCM_NONE_BTE if (p_dev_rec->sec_flags & BTM_SEC_LINK_KEY_AUTHED) #endif { if (btm_cb.api.p_link_key_callback) { if (ltk_derived_lk) { BTM_TRACE_DEBUG( "btm_sec_link_key_notification() LTK derived LK is saved already" " (key_type = %d)", p_dev_rec->link_key_type); } else { (*btm_cb.api.p_link_key_callback)(p_bda, p_dev_rec->dev_class, p_dev_rec->sec_bd_name, p_link_key, p_dev_rec->link_key_type); } } } } /******************************************************************************* * * Function btm_sec_link_key_request * * Description This function is called when controller requests link key * * Returns Pointer to the record or NULL * ******************************************************************************/ void btm_sec_link_key_request(uint8_t* p_bda) { tBTM_SEC_DEV_REC* p_dev_rec = btm_find_or_alloc_dev(p_bda); BTM_TRACE_EVENT( "btm_sec_link_key_request() BDA: %02x:%02x:%02x:%02x:%02x:%02x", p_bda[0], p_bda[1], p_bda[2], p_bda[3], p_bda[4], p_bda[5]); if ((btm_cb.pairing_state == BTM_PAIR_STATE_WAIT_PIN_REQ) && (btm_cb.collision_start_time != 0) && (memcmp(btm_cb.p_collided_dev_rec->bd_addr, p_bda, BD_ADDR_LEN) == 0)) { BTM_TRACE_EVENT( "btm_sec_link_key_request() rejecting link key req " "State: %d START_TIMEOUT : %d", btm_cb.pairing_state, btm_cb.collision_start_time); btsnd_hcic_link_key_neg_reply(p_bda); return; } if (p_dev_rec->sec_flags & BTM_SEC_LINK_KEY_KNOWN) { btsnd_hcic_link_key_req_reply(p_bda, p_dev_rec->link_key); return; } /* Notify L2CAP to increase timeout */ l2c_pin_code_request(p_bda); /* The link key is not in the database and it is not known to the manager */ btsnd_hcic_link_key_neg_reply(p_bda); } /******************************************************************************* * * Function btm_sec_pairing_timeout * * Description This function is called when host does not provide PIN * within requested time * * Returns Pointer to the TLE struct * ******************************************************************************/ static void btm_sec_pairing_timeout(UNUSED_ATTR void* data) { tBTM_CB* p_cb = &btm_cb; tBTM_SEC_DEV_REC* p_dev_rec; #if (BTM_LOCAL_IO_CAPS == BTM_IO_CAP_NONE) tBTM_AUTH_REQ auth_req = BTM_AUTH_AP_NO; #else tBTM_AUTH_REQ auth_req = BTM_AUTH_AP_YES; #endif uint8_t name[2]; p_dev_rec = btm_find_dev(p_cb->pairing_bda); BTM_TRACE_EVENT("%s State: %s Flags: %u", __func__, btm_pair_state_descr(p_cb->pairing_state), p_cb->pairing_flags); switch (p_cb->pairing_state) { case BTM_PAIR_STATE_WAIT_PIN_REQ: btm_sec_bond_cancel_complete(); break; case BTM_PAIR_STATE_WAIT_LOCAL_PIN: if ((btm_cb.pairing_flags & BTM_PAIR_FLAGS_PRE_FETCH_PIN) == 0) btsnd_hcic_pin_code_neg_reply(p_cb->pairing_bda); btm_sec_change_pairing_state(BTM_PAIR_STATE_IDLE); /* We need to notify the UI that no longer need the PIN */ if (btm_cb.api.p_auth_complete_callback) { if (p_dev_rec == NULL) { name[0] = 0; (*btm_cb.api.p_auth_complete_callback)(p_cb->pairing_bda, NULL, name, HCI_ERR_CONNECTION_TOUT); } else (*btm_cb.api.p_auth_complete_callback)( p_dev_rec->bd_addr, p_dev_rec->dev_class, p_dev_rec->sec_bd_name, HCI_ERR_CONNECTION_TOUT); } break; case BTM_PAIR_STATE_WAIT_NUMERIC_CONFIRM: btsnd_hcic_user_conf_reply(p_cb->pairing_bda, false); /* btm_sec_change_pairing_state (BTM_PAIR_STATE_IDLE); */ break; #if (BTM_LOCAL_IO_CAPS != BTM_IO_CAP_NONE) case BTM_PAIR_STATE_KEY_ENTRY: btsnd_hcic_user_passkey_neg_reply(p_cb->pairing_bda); /* btm_sec_change_pairing_state (BTM_PAIR_STATE_IDLE); */ break; #endif /* !BTM_IO_CAP_NONE */ case BTM_PAIR_STATE_WAIT_LOCAL_IOCAPS: if (btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) auth_req |= BTM_AUTH_DD_BOND; btsnd_hcic_io_cap_req_reply(p_cb->pairing_bda, btm_cb.devcb.loc_io_caps, BTM_OOB_NONE, auth_req); btm_sec_change_pairing_state(BTM_PAIR_STATE_IDLE); break; case BTM_PAIR_STATE_WAIT_LOCAL_OOB_RSP: btsnd_hcic_rem_oob_neg_reply(p_cb->pairing_bda); btm_sec_change_pairing_state(BTM_PAIR_STATE_IDLE); break; case BTM_PAIR_STATE_WAIT_DISCONNECT: /* simple pairing failed. Started a 1-sec timer at simple pairing * complete. * now it's time to tear down the ACL link*/ if (p_dev_rec == NULL) { BTM_TRACE_ERROR( "%s BTM_PAIR_STATE_WAIT_DISCONNECT unknown BDA: %08x%04x", __func__, (p_cb->pairing_bda[0] << 24) + (p_cb->pairing_bda[1] << 16) + (p_cb->pairing_bda[2] << 8) + p_cb->pairing_bda[3], (p_cb->pairing_bda[4] << 8) + p_cb->pairing_bda[5]); break; } btm_sec_send_hci_disconnect(p_dev_rec, HCI_ERR_AUTH_FAILURE, p_dev_rec->hci_handle); btm_sec_change_pairing_state(BTM_PAIR_STATE_IDLE); break; case BTM_PAIR_STATE_WAIT_AUTH_COMPLETE: case BTM_PAIR_STATE_GET_REM_NAME: /* We need to notify the UI that timeout has happened while waiting for * authentication*/ btm_sec_change_pairing_state(BTM_PAIR_STATE_IDLE); if (btm_cb.api.p_auth_complete_callback) { if (p_dev_rec == NULL) { name[0] = 0; (*btm_cb.api.p_auth_complete_callback)(p_cb->pairing_bda, NULL, name, HCI_ERR_CONNECTION_TOUT); } else (*btm_cb.api.p_auth_complete_callback)( p_dev_rec->bd_addr, p_dev_rec->dev_class, p_dev_rec->sec_bd_name, HCI_ERR_CONNECTION_TOUT); } break; default: BTM_TRACE_WARNING("%s not processed state: %s", __func__, btm_pair_state_descr(btm_cb.pairing_state)); btm_sec_change_pairing_state(BTM_PAIR_STATE_IDLE); break; } } /******************************************************************************* * * Function btm_sec_pin_code_request * * Description This function is called when controller requests PIN code * * Returns Pointer to the record or NULL * ******************************************************************************/ void btm_sec_pin_code_request(uint8_t* p_bda) { tBTM_SEC_DEV_REC* p_dev_rec; tBTM_CB* p_cb = &btm_cb; BTM_TRACE_EVENT( "btm_sec_pin_code_request() State: %s, BDA:%04x%08x", btm_pair_state_descr(btm_cb.pairing_state), (p_bda[0] << 8) + p_bda[1], (p_bda[2] << 24) + (p_bda[3] << 16) + (p_bda[4] << 8) + p_bda[5]); if (btm_cb.pairing_state != BTM_PAIR_STATE_IDLE) { if ((memcmp(p_bda, btm_cb.pairing_bda, BD_ADDR_LEN) == 0) && (btm_cb.pairing_state == BTM_PAIR_STATE_WAIT_AUTH_COMPLETE)) { btsnd_hcic_pin_code_neg_reply(p_bda); return; } else if ((btm_cb.pairing_state != BTM_PAIR_STATE_WAIT_PIN_REQ) || memcmp(p_bda, btm_cb.pairing_bda, BD_ADDR_LEN) != 0) { BTM_TRACE_WARNING("btm_sec_pin_code_request() rejected - state: %s", btm_pair_state_descr(btm_cb.pairing_state)); btsnd_hcic_pin_code_neg_reply(p_bda); return; } } p_dev_rec = btm_find_or_alloc_dev(p_bda); /* received PIN code request. must be non-sm4 */ p_dev_rec->sm4 = BTM_SM4_KNOWN; if (btm_cb.pairing_state == BTM_PAIR_STATE_IDLE) { memcpy(btm_cb.pairing_bda, p_bda, BD_ADDR_LEN); btm_cb.pairing_flags = BTM_PAIR_FLAGS_PEER_STARTED_DD; /* Make sure we reset the trusted mask to help against attacks */ BTM_SEC_CLR_TRUSTED_DEVICE(p_dev_rec->trusted_mask); } if (!p_cb->pairing_disabled && (p_cb->cfg.pin_type == HCI_PIN_TYPE_FIXED)) { BTM_TRACE_EVENT("btm_sec_pin_code_request fixed pin replying"); btm_sec_change_pairing_state(BTM_PAIR_STATE_WAIT_AUTH_COMPLETE); btsnd_hcic_pin_code_req_reply(p_bda, p_cb->cfg.pin_code_len, p_cb->cfg.pin_code); return; } /* Use the connecting device's CoD for the connection */ if ((!memcmp(p_bda, p_cb->connecting_bda, BD_ADDR_LEN)) && (p_cb->connecting_dc[0] || p_cb->connecting_dc[1] || p_cb->connecting_dc[2])) memcpy(p_dev_rec->dev_class, p_cb->connecting_dc, DEV_CLASS_LEN); /* We could have started connection after asking user for the PIN code */ if (btm_cb.pin_code_len != 0) { BTM_TRACE_EVENT("btm_sec_pin_code_request bonding sending reply"); btsnd_hcic_pin_code_req_reply(p_bda, btm_cb.pin_code_len, p_cb->pin_code); /* Mark that we forwarded received from the user PIN code */ btm_cb.pin_code_len = 0; /* We can change mode back right away, that other connection being * established */ /* is not forced to be secure - found a FW issue, so we can not do this btm_restore_mode(); */ btm_sec_change_pairing_state(BTM_PAIR_STATE_WAIT_AUTH_COMPLETE); } /* If pairing disabled OR (no PIN callback and not bonding) */ /* OR we could not allocate entry in the database reject pairing request */ else if ( p_cb->pairing_disabled || (p_cb->api.p_pin_callback == NULL) /* OR Microsoft keyboard can for some reason try to establish connection */ /* the only thing we can do here is to shut it up. Normally we will be originator */ /* for keyboard bonding */ || (!p_dev_rec->is_originator && ((p_dev_rec->dev_class[1] & BTM_COD_MAJOR_CLASS_MASK) == BTM_COD_MAJOR_PERIPHERAL) && (p_dev_rec->dev_class[2] & BTM_COD_MINOR_KEYBOARD))) { BTM_TRACE_WARNING( "btm_sec_pin_code_request(): Pairing disabled:%d; PIN callback:%x, Dev " "Rec:%x!", p_cb->pairing_disabled, p_cb->api.p_pin_callback, p_dev_rec); btsnd_hcic_pin_code_neg_reply(p_bda); } /* Notify upper layer of PIN request and start expiration timer */ else { btm_sec_change_pairing_state(BTM_PAIR_STATE_WAIT_LOCAL_PIN); /* Pin code request can not come at the same time as connection request */ memcpy(p_cb->connecting_bda, p_bda, BD_ADDR_LEN); memcpy(p_cb->connecting_dc, p_dev_rec->dev_class, DEV_CLASS_LEN); /* Check if the name is known */ /* Even if name is not known we might not be able to get one */ /* this is the case when we are already getting something from the */ /* device, so HCI level is flow controlled */ /* Also cannot send remote name request while paging, i.e. connection is not * completed */ if (p_dev_rec->sec_flags & BTM_SEC_NAME_KNOWN) { BTM_TRACE_EVENT("btm_sec_pin_code_request going for callback"); btm_cb.pairing_flags |= BTM_PAIR_FLAGS_PIN_REQD; if (p_cb->api.p_pin_callback) { (*p_cb->api.p_pin_callback)( p_bda, p_dev_rec->dev_class, p_dev_rec->sec_bd_name, (p_dev_rec->p_cur_service == NULL) ? false : (p_dev_rec->p_cur_service->security_flags & BTM_SEC_IN_MIN_16_DIGIT_PIN)); } } else { BTM_TRACE_EVENT("btm_sec_pin_code_request going for remote name"); /* We received PIN code request for the device with unknown name */ /* it is not user friendly just to ask for the PIN without name */ /* try to get name at first */ btsnd_hcic_rmt_name_req(p_dev_rec->bd_addr, HCI_PAGE_SCAN_REP_MODE_R1, HCI_MANDATARY_PAGE_SCAN_MODE, 0); } } return; } /******************************************************************************* * * Function btm_sec_update_clock_offset * * Description This function is called to update clock offset * * Returns void * ******************************************************************************/ void btm_sec_update_clock_offset(uint16_t handle, uint16_t clock_offset) { tBTM_SEC_DEV_REC* p_dev_rec; tBTM_INQ_INFO* p_inq_info; p_dev_rec = btm_find_dev_by_handle(handle); if (p_dev_rec == NULL) return; p_dev_rec->clock_offset = clock_offset | BTM_CLOCK_OFFSET_VALID; p_inq_info = BTM_InqDbRead(p_dev_rec->bd_addr); if (p_inq_info == NULL) return; p_inq_info->results.clock_offset = clock_offset | BTM_CLOCK_OFFSET_VALID; } /****************************************************************** * S T A T I C F U N C T I O N S ******************************************************************/ /******************************************************************************* * * Function btm_sec_execute_procedure * * Description This function is called to start required security * procedure. There is a case when multiplexing protocol * calls this function on the originating side, connection to * the peer will not be established. This function in this * case performs only authorization. * * Returns BTM_SUCCESS - permission is granted * BTM_CMD_STARTED - in process * BTM_NO_RESOURCES - permission declined * ******************************************************************************/ static tBTM_STATUS btm_sec_execute_procedure(tBTM_SEC_DEV_REC* p_dev_rec) { BTM_TRACE_EVENT( "btm_sec_execute_procedure: Required:0x%x Flags:0x%x State:%d", p_dev_rec->security_required, p_dev_rec->sec_flags, p_dev_rec->sec_state); /* There is a chance that we are getting name. Wait until done. */ if (p_dev_rec->sec_state != 0) return (BTM_CMD_STARTED); /* If any security is required, get the name first */ if (!(p_dev_rec->sec_flags & BTM_SEC_NAME_KNOWN) && (p_dev_rec->hci_handle != BTM_SEC_INVALID_HANDLE)) { BTM_TRACE_EVENT("Security Manager: Start get name"); if (!btm_sec_start_get_name(p_dev_rec)) { return (BTM_NO_RESOURCES); } return (BTM_CMD_STARTED); } /* If connection is not authenticated and authentication is required */ /* start authentication and return PENDING to the caller */ if ((((!(p_dev_rec->sec_flags & BTM_SEC_AUTHENTICATED)) && ((p_dev_rec->is_originator && (p_dev_rec->security_required & BTM_SEC_OUT_AUTHENTICATE)) || (!p_dev_rec->is_originator && (p_dev_rec->security_required & BTM_SEC_IN_AUTHENTICATE)))) || (!(p_dev_rec->sec_flags & BTM_SEC_16_DIGIT_PIN_AUTHED) && (!p_dev_rec->is_originator && (p_dev_rec->security_required & BTM_SEC_IN_MIN_16_DIGIT_PIN)))) && (p_dev_rec->hci_handle != BTM_SEC_INVALID_HANDLE)) { /* * We rely on BTM_SEC_16_DIGIT_PIN_AUTHED being set if MITM is in use, * as 16 DIGIT is only needed if MITM is not used. Unfortunately, the * BTM_SEC_AUTHENTICATED is used for both MITM and non-MITM * authenticated connections, hence we cannot distinguish here. */ #if (L2CAP_UCD_INCLUDED == TRUE) /* if incoming UCD packet, discard it */ if (!p_dev_rec->is_originator && (p_dev_rec->is_ucd == true)) return (BTM_FAILED_ON_SECURITY); #endif BTM_TRACE_EVENT("Security Manager: Start authentication"); /* * If we do have a link-key, but we end up here because we need an * upgrade, then clear the link-key known and authenticated flag before * restarting authentication. * WARNING: If the controller has link-key, it is optional and * recommended for the controller to send a Link_Key_Request. * In case we need an upgrade, the only alternative would be to delete * the existing link-key. That could lead to very bad user experience * or even IOP issues, if a reconnect causes a new connection that * requires an upgrade. */ if ((p_dev_rec->sec_flags & BTM_SEC_LINK_KEY_KNOWN) && (!(p_dev_rec->sec_flags & BTM_SEC_16_DIGIT_PIN_AUTHED) && (!p_dev_rec->is_originator && (p_dev_rec->security_required & BTM_SEC_IN_MIN_16_DIGIT_PIN)))) { p_dev_rec->sec_flags &= ~(BTM_SEC_LINK_KEY_KNOWN | BTM_SEC_LINK_KEY_AUTHED | BTM_SEC_AUTHENTICATED); } btm_sec_start_authentication(p_dev_rec); return (BTM_CMD_STARTED); } /* If connection is not encrypted and encryption is required */ /* start encryption and return PENDING to the caller */ if (!(p_dev_rec->sec_flags & BTM_SEC_ENCRYPTED) && ((p_dev_rec->is_originator && (p_dev_rec->security_required & BTM_SEC_OUT_ENCRYPT)) || (!p_dev_rec->is_originator && (p_dev_rec->security_required & BTM_SEC_IN_ENCRYPT))) && (p_dev_rec->hci_handle != BTM_SEC_INVALID_HANDLE)) { #if (L2CAP_UCD_INCLUDED == TRUE) /* if incoming UCD packet, discard it */ if (!p_dev_rec->is_originator && (p_dev_rec->is_ucd == true)) return (BTM_FAILED_ON_SECURITY); #endif BTM_TRACE_EVENT("Security Manager: Start encryption"); btm_sec_start_encryption(p_dev_rec); return (BTM_CMD_STARTED); } if ((p_dev_rec->security_required & BTM_SEC_MODE4_LEVEL4) && (p_dev_rec->link_key_type != BTM_LKEY_TYPE_AUTH_COMB_P_256)) { BTM_TRACE_EVENT( "%s: Security Manager: SC only service, but link key type is 0x%02x -", "security failure", __func__, p_dev_rec->link_key_type); return (BTM_FAILED_ON_SECURITY); } /* If connection is not authorized and authorization is required */ /* start authorization and return PENDING to the caller */ if (!(p_dev_rec->sec_flags & BTM_SEC_AUTHORIZED) && ((p_dev_rec->is_originator && (p_dev_rec->security_required & BTM_SEC_OUT_AUTHORIZE)) || (!p_dev_rec->is_originator && (p_dev_rec->security_required & BTM_SEC_IN_AUTHORIZE)))) { BTM_TRACE_EVENT( "service id:%d, is trusted:%d", p_dev_rec->p_cur_service->service_id, (BTM_SEC_IS_SERVICE_TRUSTED(p_dev_rec->trusted_mask, p_dev_rec->p_cur_service->service_id))); if ((btm_sec_are_all_trusted(p_dev_rec->trusted_mask) == false) && (p_dev_rec->p_cur_service->service_id < BTM_SEC_MAX_SERVICES) && (BTM_SEC_IS_SERVICE_TRUSTED(p_dev_rec->trusted_mask, p_dev_rec->p_cur_service->service_id) == false)) { BTM_TRACE_EVENT("Security Manager: Start authorization"); return (btm_sec_start_authorization(p_dev_rec)); } } /* All required security procedures already established */ p_dev_rec->security_required &= ~(BTM_SEC_OUT_AUTHORIZE | BTM_SEC_IN_AUTHORIZE | BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_IN_AUTHENTICATE | BTM_SEC_OUT_ENCRYPT | BTM_SEC_IN_ENCRYPT | BTM_SEC_FORCE_MASTER | BTM_SEC_ATTEMPT_MASTER | BTM_SEC_FORCE_SLAVE | BTM_SEC_ATTEMPT_SLAVE); BTM_TRACE_EVENT("Security Manager: trusted:0x%04x%04x", p_dev_rec->trusted_mask[1], p_dev_rec->trusted_mask[0]); BTM_TRACE_EVENT("Security Manager: access granted"); return (BTM_SUCCESS); } /******************************************************************************* * * Function btm_sec_start_get_name * * Description This function is called to start get name procedure * * Returns true if started * ******************************************************************************/ static bool btm_sec_start_get_name(tBTM_SEC_DEV_REC* p_dev_rec) { uint8_t tempstate = p_dev_rec->sec_state; p_dev_rec->sec_state = BTM_SEC_STATE_GETTING_NAME; /* 0 and NULL are as timeout and callback params because they are not used in * security get name case */ if ((btm_initiate_rem_name(p_dev_rec->bd_addr, BTM_RMT_NAME_SEC, 0, NULL)) != BTM_CMD_STARTED) { p_dev_rec->sec_state = tempstate; return (false); } return (true); } /******************************************************************************* * * Function btm_sec_start_authentication * * Description This function is called to start authentication * ******************************************************************************/ static void btm_sec_start_authentication(tBTM_SEC_DEV_REC* p_dev_rec) { p_dev_rec->sec_state = BTM_SEC_STATE_AUTHENTICATING; btsnd_hcic_auth_request(p_dev_rec->hci_handle); } /******************************************************************************* * * Function btm_sec_start_encryption * * Description This function is called to start encryption * ******************************************************************************/ static void btm_sec_start_encryption(tBTM_SEC_DEV_REC* p_dev_rec) { btsnd_hcic_set_conn_encrypt(p_dev_rec->hci_handle, true); p_dev_rec->sec_state = BTM_SEC_STATE_ENCRYPTING; } /******************************************************************************* * * Function btm_sec_start_authorization * * Description This function is called to start authorization * * Returns true if started * ******************************************************************************/ static uint8_t btm_sec_start_authorization(tBTM_SEC_DEV_REC* p_dev_rec) { uint8_t result; uint8_t* p_service_name = NULL; uint8_t service_id; if ((p_dev_rec->sec_flags & BTM_SEC_NAME_KNOWN) || (p_dev_rec->hci_handle == BTM_SEC_INVALID_HANDLE)) { if (!btm_cb.api.p_authorize_callback) return (BTM_MODE_UNSUPPORTED); if (p_dev_rec->p_cur_service) { #if BTM_SEC_SERVICE_NAME_LEN > 0 if (p_dev_rec->is_originator) p_service_name = p_dev_rec->p_cur_service->orig_service_name; else p_service_name = p_dev_rec->p_cur_service->term_service_name; #endif service_id = p_dev_rec->p_cur_service->service_id; } else service_id = 0; /* Send authorization request if not already sent during this service * connection */ if (p_dev_rec->last_author_service_id == BTM_SEC_NO_LAST_SERVICE_ID || p_dev_rec->last_author_service_id != service_id) { p_dev_rec->sec_state = BTM_SEC_STATE_AUTHORIZING; result = (*btm_cb.api.p_authorize_callback)( p_dev_rec->bd_addr, p_dev_rec->dev_class, p_dev_rec->sec_bd_name, p_service_name, service_id, p_dev_rec->is_originator); } else /* Already authorized once for this L2CAP bringup */ { BTM_TRACE_DEBUG( "btm_sec_start_authorization: (Ignoring extra Authorization prompt " "for service %d)", service_id); return (BTM_SUCCESS); } if (result == BTM_SUCCESS) { p_dev_rec->sec_flags |= BTM_SEC_AUTHORIZED; /* Save the currently authorized service in case we are asked again by * another multiplexer layer */ if (!p_dev_rec->is_originator) p_dev_rec->last_author_service_id = service_id; p_dev_rec->sec_state = BTM_SEC_STATE_IDLE; } return (result); } btm_sec_start_get_name(p_dev_rec); return (BTM_CMD_STARTED); } /******************************************************************************* * * Function btm_sec_are_all_trusted * * Description This function is called check if all services are trusted * * Returns true if all are trusted, otherwise false * ******************************************************************************/ bool btm_sec_are_all_trusted(uint32_t p_mask[]) { uint32_t trusted_inx; for (trusted_inx = 0; trusted_inx < BTM_SEC_SERVICE_ARRAY_SIZE; trusted_inx++) { if (p_mask[trusted_inx] != BTM_SEC_TRUST_ALL) return (false); } return (true); } /******************************************************************************* * * Function btm_sec_find_first_serv * * Description Look for the first record in the service database * with specified PSM * * Returns Pointer to the record or NULL * ******************************************************************************/ tBTM_SEC_SERV_REC* btm_sec_find_first_serv(CONNECTION_TYPE conn_type, uint16_t psm) { tBTM_SEC_SERV_REC* p_serv_rec = &btm_cb.sec_serv_rec[0]; int i; bool is_originator; #if (L2CAP_UCD_INCLUDED == TRUE) if (conn_type & CONNECTION_TYPE_ORIG_MASK) is_originator = true; else is_originator = false; #else is_originator = conn_type; #endif if (is_originator && btm_cb.p_out_serv && btm_cb.p_out_serv->psm == psm) { /* If this is outgoing connection and the PSM matches p_out_serv, * use it as the current service */ return btm_cb.p_out_serv; } /* otherwise, just find the first record with the specified PSM */ for (i = 0; i < BTM_SEC_MAX_SERVICE_RECORDS; i++, p_serv_rec++) { if ((p_serv_rec->security_flags & BTM_SEC_IN_USE) && (p_serv_rec->psm == psm)) return (p_serv_rec); } return (NULL); } /******************************************************************************* * * Function btm_sec_find_next_serv * * Description Look for the next record in the service database * with specified PSM * * Returns Pointer to the record or NULL * ******************************************************************************/ static tBTM_SEC_SERV_REC* btm_sec_find_next_serv(tBTM_SEC_SERV_REC* p_cur) { tBTM_SEC_SERV_REC* p_serv_rec = &btm_cb.sec_serv_rec[0]; int i; for (i = 0; i < BTM_SEC_MAX_SERVICE_RECORDS; i++, p_serv_rec++) { if ((p_serv_rec->security_flags & BTM_SEC_IN_USE) && (p_serv_rec->psm == p_cur->psm)) { if (p_cur != p_serv_rec) { return (p_serv_rec); } } } return (NULL); } /******************************************************************************* * * Function btm_sec_find_mx_serv * * Description Look for the record in the service database with specified * PSM and multiplexor channel information * * Returns Pointer to the record or NULL * ******************************************************************************/ static tBTM_SEC_SERV_REC* btm_sec_find_mx_serv(uint8_t is_originator, uint16_t psm, uint32_t mx_proto_id, uint32_t mx_chan_id) { tBTM_SEC_SERV_REC* p_out_serv = btm_cb.p_out_serv; tBTM_SEC_SERV_REC* p_serv_rec = &btm_cb.sec_serv_rec[0]; int i; BTM_TRACE_DEBUG("%s()", __func__); if (is_originator && p_out_serv && p_out_serv->psm == psm && p_out_serv->mx_proto_id == mx_proto_id && p_out_serv->orig_mx_chan_id == mx_chan_id) { /* If this is outgoing connection and the parameters match p_out_serv, * use it as the current service */ return btm_cb.p_out_serv; } /* otherwise, the old way */ for (i = 0; i < BTM_SEC_MAX_SERVICE_RECORDS; i++, p_serv_rec++) { if ((p_serv_rec->security_flags & BTM_SEC_IN_USE) && (p_serv_rec->psm == psm) && (p_serv_rec->mx_proto_id == mx_proto_id) && ((is_originator && (p_serv_rec->orig_mx_chan_id == mx_chan_id)) || (!is_originator && (p_serv_rec->term_mx_chan_id == mx_chan_id)))) { return (p_serv_rec); } } return (NULL); } /******************************************************************************* * * Function btm_sec_collision_timeout * * Description Encryption could not start because of the collision * try to do it again * * Returns Pointer to the TLE struct * ******************************************************************************/ static void btm_sec_collision_timeout(UNUSED_ATTR void* data) { BTM_TRACE_EVENT("%s()", __func__); tBTM_STATUS status = btm_sec_execute_procedure(btm_cb.p_collided_dev_rec); /* If result is pending reply from the user or from the device is pending */ if (status != BTM_CMD_STARTED) { /* There is no next procedure or start of procedure failed, notify the * waiting layer */ btm_sec_dev_rec_cback_event(btm_cb.p_collided_dev_rec, status, false); } } /******************************************************************************* * * Function btm_sec_link_key_request * * Description This function is called when controller requests link key * * Returns Pointer to the record or NULL * ******************************************************************************/ static void btm_send_link_key_notif(tBTM_SEC_DEV_REC* p_dev_rec) { if (btm_cb.api.p_link_key_callback) (*btm_cb.api.p_link_key_callback)( p_dev_rec->bd_addr, p_dev_rec->dev_class, p_dev_rec->sec_bd_name, p_dev_rec->link_key, p_dev_rec->link_key_type); } /******************************************************************************* * * Function BTM_ReadTrustedMask * * Description Get trusted mask for the peer device * * Parameters: bd_addr - Address of the device * * Returns NULL, if the device record is not found. * otherwise, the trusted mask * ******************************************************************************/ uint32_t* BTM_ReadTrustedMask(BD_ADDR bd_addr) { tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr); if (p_dev_rec != NULL) return (p_dev_rec->trusted_mask); return NULL; } /******************************************************************************* * * Function btm_restore_mode * * Description This function returns the security mode to previous setting * if it was changed during bonding. * * * Parameters: void * ******************************************************************************/ static void btm_restore_mode(void) { if (btm_cb.security_mode_changed) { btm_cb.security_mode_changed = false; BTM_TRACE_DEBUG("%s() Auth enable -> %d", __func__, (btm_cb.security_mode == BTM_SEC_MODE_LINK)); btsnd_hcic_write_auth_enable( (uint8_t)(btm_cb.security_mode == BTM_SEC_MODE_LINK)); } if (btm_cb.pin_type_changed) { btm_cb.pin_type_changed = false; btsnd_hcic_write_pin_type(btm_cb.cfg.pin_type); } } bool is_sec_state_equal(void* data, void* context) { tBTM_SEC_DEV_REC* p_dev_rec = static_cast<tBTM_SEC_DEV_REC*>(data); uint8_t* state = static_cast<uint8_t*>(context); if (p_dev_rec->sec_state == *state) return false; return true; } /******************************************************************************* * * Function btm_sec_find_dev_by_sec_state * * Description Look for the record in the device database for the device * which is being authenticated or encrypted * * Returns Pointer to the record or NULL * ******************************************************************************/ tBTM_SEC_DEV_REC* btm_sec_find_dev_by_sec_state(uint8_t state) { list_node_t* n = list_foreach(btm_cb.sec_dev_rec, is_sec_state_equal, &state); if (n) return static_cast<tBTM_SEC_DEV_REC*>(list_node(n)); return NULL; } /******************************************************************************* * * Function btm_sec_change_pairing_state * * Description This function is called to change pairing state * ******************************************************************************/ static void btm_sec_change_pairing_state(tBTM_PAIRING_STATE new_state) { tBTM_PAIRING_STATE old_state = btm_cb.pairing_state; BTM_TRACE_EVENT("%s() Old: %s", __func__, btm_pair_state_descr(btm_cb.pairing_state)); BTM_TRACE_EVENT("%s() New: %s pairing_flags:0x%x", __func__, btm_pair_state_descr(new_state), btm_cb.pairing_flags); btm_cb.pairing_state = new_state; if (new_state == BTM_PAIR_STATE_IDLE) { alarm_cancel(btm_cb.pairing_timer); btm_cb.pairing_flags = 0; btm_cb.pin_code_len = 0; /* Make sure the the lcb shows we are not bonding */ l2cu_update_lcb_4_bonding(btm_cb.pairing_bda, false); btm_restore_mode(); btm_sec_check_pending_reqs(); btm_inq_clear_ssp(); memset(btm_cb.pairing_bda, 0xFF, BD_ADDR_LEN); } else { /* If transitioning out of idle, mark the lcb as bonding */ if (old_state == BTM_PAIR_STATE_IDLE) l2cu_update_lcb_4_bonding(btm_cb.pairing_bda, true); alarm_set_on_queue(btm_cb.pairing_timer, BTM_SEC_TIMEOUT_VALUE * 1000, btm_sec_pairing_timeout, NULL, btu_general_alarm_queue); } } /******************************************************************************* * * Function btm_pair_state_descr * * Description Return state description for tracing * ******************************************************************************/ static const char* btm_pair_state_descr(tBTM_PAIRING_STATE state) { switch (state) { case BTM_PAIR_STATE_IDLE: return ("IDLE"); case BTM_PAIR_STATE_GET_REM_NAME: return ("GET_REM_NAME"); case BTM_PAIR_STATE_WAIT_PIN_REQ: return ("WAIT_PIN_REQ"); case BTM_PAIR_STATE_WAIT_LOCAL_PIN: return ("WAIT_LOCAL_PIN"); case BTM_PAIR_STATE_WAIT_NUMERIC_CONFIRM: return ("WAIT_NUM_CONFIRM"); case BTM_PAIR_STATE_KEY_ENTRY: return ("KEY_ENTRY"); case BTM_PAIR_STATE_WAIT_LOCAL_OOB_RSP: return ("WAIT_LOCAL_OOB_RSP"); case BTM_PAIR_STATE_WAIT_LOCAL_IOCAPS: return ("WAIT_LOCAL_IOCAPS"); case BTM_PAIR_STATE_INCOMING_SSP: return ("INCOMING_SSP"); case BTM_PAIR_STATE_WAIT_AUTH_COMPLETE: return ("WAIT_AUTH_COMPLETE"); case BTM_PAIR_STATE_WAIT_DISCONNECT: return ("WAIT_DISCONNECT"); } return ("???"); } /******************************************************************************* * * Function btm_sec_dev_rec_cback_event * * Description This function calls the callback function with the given * result and clear the callback function. * * Parameters: void * ******************************************************************************/ void btm_sec_dev_rec_cback_event(tBTM_SEC_DEV_REC* p_dev_rec, uint8_t res, bool is_le_transport) { tBTM_SEC_CALLBACK* p_callback = p_dev_rec->p_callback; if (p_dev_rec->p_callback) { p_dev_rec->p_callback = NULL; if (is_le_transport) (*p_callback)(p_dev_rec->ble.pseudo_addr, BT_TRANSPORT_LE, p_dev_rec->p_ref_data, res); else (*p_callback)(p_dev_rec->bd_addr, BT_TRANSPORT_BR_EDR, p_dev_rec->p_ref_data, res); } btm_sec_check_pending_reqs(); } /******************************************************************************* * * Function btm_sec_queue_mx_request * * Description Return state description for tracing * ******************************************************************************/ static bool btm_sec_queue_mx_request(BD_ADDR bd_addr, uint16_t psm, bool is_orig, uint32_t mx_proto_id, uint32_t mx_chan_id, tBTM_SEC_CALLBACK* p_callback, void* p_ref_data) { tBTM_SEC_QUEUE_ENTRY* p_e = (tBTM_SEC_QUEUE_ENTRY*)osi_malloc(sizeof(tBTM_SEC_QUEUE_ENTRY)); p_e->psm = psm; p_e->is_orig = is_orig; p_e->p_callback = p_callback; p_e->p_ref_data = p_ref_data; p_e->mx_proto_id = mx_proto_id; p_e->mx_chan_id = mx_chan_id; p_e->transport = BT_TRANSPORT_BR_EDR; p_e->sec_act = 0; memcpy(p_e->bd_addr, bd_addr, BD_ADDR_LEN); BTM_TRACE_EVENT( "%s() PSM: 0x%04x Is_Orig: %u mx_proto_id: %u mx_chan_id: %u", __func__, psm, is_orig, mx_proto_id, mx_chan_id); fixed_queue_enqueue(btm_cb.sec_pending_q, p_e); return true; } static bool btm_sec_check_prefetch_pin(tBTM_SEC_DEV_REC* p_dev_rec) { uint8_t major = (uint8_t)(p_dev_rec->dev_class[1] & BTM_COD_MAJOR_CLASS_MASK); uint8_t minor = (uint8_t)(p_dev_rec->dev_class[2] & BTM_COD_MINOR_CLASS_MASK); bool rv = false; if ((major == BTM_COD_MAJOR_AUDIO) && ((minor == BTM_COD_MINOR_CONFM_HANDSFREE) || (minor == BTM_COD_MINOR_CAR_AUDIO))) { BTM_TRACE_EVENT( "%s() Skipping pre-fetch PIN for carkit COD Major: 0x%02x Minor: " "0x%02x", __func__, major, minor); if (btm_cb.security_mode_changed == false) { btm_cb.security_mode_changed = true; #ifdef APPL_AUTH_WRITE_EXCEPTION if (!(APPL_AUTH_WRITE_EXCEPTION)(p_dev_rec->bd_addr)) #endif btsnd_hcic_write_auth_enable(true); } } else { btm_sec_change_pairing_state(BTM_PAIR_STATE_WAIT_LOCAL_PIN); /* If we got a PIN, use that, else try to get one */ if (btm_cb.pin_code_len) { BTM_PINCodeReply(p_dev_rec->bd_addr, BTM_SUCCESS, btm_cb.pin_code_len, btm_cb.pin_code, p_dev_rec->trusted_mask); } else { /* pin was not supplied - pre-fetch pin code now */ if (btm_cb.api.p_pin_callback && ((btm_cb.pairing_flags & BTM_PAIR_FLAGS_PIN_REQD) == 0)) { BTM_TRACE_DEBUG("%s() PIN code callback called", __func__); if (btm_bda_to_acl(p_dev_rec->bd_addr, BT_TRANSPORT_BR_EDR) == NULL) btm_cb.pairing_flags |= BTM_PAIR_FLAGS_PIN_REQD; (btm_cb.api.p_pin_callback)( p_dev_rec->bd_addr, p_dev_rec->dev_class, p_dev_rec->sec_bd_name, (p_dev_rec->p_cur_service == NULL) ? false : (p_dev_rec->p_cur_service->security_flags & BTM_SEC_IN_MIN_16_DIGIT_PIN)); } } rv = true; } return rv; } /******************************************************************************* * * Function btm_sec_auth_payload_tout * * Description Processes the HCI Autheniticated Payload Timeout Event * indicating that a packet containing a valid MIC on the * connection handle was not received within the programmed * timeout value. (Spec Default is 30 secs, but can be * changed via the BTM_SecSetAuthPayloadTimeout() function. * ******************************************************************************/ void btm_sec_auth_payload_tout(uint8_t* p, uint16_t hci_evt_len) { uint16_t handle; STREAM_TO_UINT16(handle, p); handle = HCID_GET_HANDLE(handle); /* Will be exposed to upper layers in the future if/when determined necessary */ BTM_TRACE_ERROR("%s on handle 0x%02x", __func__, handle); } /******************************************************************************* * * Function btm_sec_queue_encrypt_request * * Description encqueue encryption request when device has active security * process pending. * ******************************************************************************/ static bool btm_sec_queue_encrypt_request(BD_ADDR bd_addr, tBT_TRANSPORT transport, tBTM_SEC_CALLBACK* p_callback, void* p_ref_data, tBTM_BLE_SEC_ACT sec_act) { tBTM_SEC_QUEUE_ENTRY* p_e = (tBTM_SEC_QUEUE_ENTRY*)osi_malloc(sizeof(tBTM_SEC_QUEUE_ENTRY) + 1); p_e->psm = 0; /* if PSM 0, encryption request */ p_e->p_callback = p_callback; p_e->p_ref_data = p_ref_data; p_e->transport = transport; p_e->sec_act = sec_act; memcpy(p_e->bd_addr, bd_addr, BD_ADDR_LEN); fixed_queue_enqueue(btm_cb.sec_pending_q, p_e); return true; } /******************************************************************************* * * Function btm_sec_set_peer_sec_caps * * Description This function is called to set sm4 and rmt_sec_caps fields * based on the available peer device features. * * Returns void * ******************************************************************************/ void btm_sec_set_peer_sec_caps(tACL_CONN* p_acl_cb, tBTM_SEC_DEV_REC* p_dev_rec) { BD_ADDR rem_bd_addr; uint8_t* p_rem_bd_addr; if ((btm_cb.security_mode == BTM_SEC_MODE_SP || btm_cb.security_mode == BTM_SEC_MODE_SP_DEBUG || btm_cb.security_mode == BTM_SEC_MODE_SC) && HCI_SSP_HOST_SUPPORTED(p_acl_cb->peer_lmp_feature_pages[1])) { p_dev_rec->sm4 = BTM_SM4_TRUE; p_dev_rec->remote_supports_secure_connections = (HCI_SC_HOST_SUPPORTED(p_acl_cb->peer_lmp_feature_pages[1])); } else { p_dev_rec->sm4 = BTM_SM4_KNOWN; p_dev_rec->remote_supports_secure_connections = false; } BTM_TRACE_API("%s: sm4: 0x%02x, rmt_support_for_secure_connections %d", __func__, p_dev_rec->sm4, p_dev_rec->remote_supports_secure_connections); if (p_dev_rec->remote_features_needed) { BTM_TRACE_EVENT( "%s: Now device in SC Only mode, waiting for peer remote features!", __func__); p_rem_bd_addr = (uint8_t*)rem_bd_addr; BDADDR_TO_STREAM(p_rem_bd_addr, p_dev_rec->bd_addr); p_rem_bd_addr = (uint8_t*)rem_bd_addr; btm_io_capabilities_req(p_rem_bd_addr); p_dev_rec->remote_features_needed = false; } } /******************************************************************************* * * Function btm_sec_is_serv_level0 * * Description This function is called to check if the service * corresponding to PSM is security mode 4 level 0 service. * * Returns true if the service is security mode 4 level 0 service * ******************************************************************************/ static bool btm_sec_is_serv_level0(uint16_t psm) { if (psm == BT_PSM_SDP) { BTM_TRACE_DEBUG("%s: PSM: 0x%04x -> mode 4 level 0 service", __func__, psm); return true; } return false; } /******************************************************************************* * * Function btm_sec_check_pending_enc_req * * Description This function is called to send pending encryption callback * if waiting * * Returns void * ******************************************************************************/ static void btm_sec_check_pending_enc_req(tBTM_SEC_DEV_REC* p_dev_rec, tBT_TRANSPORT transport, uint8_t encr_enable) { if (fixed_queue_is_empty(btm_cb.sec_pending_q)) return; uint8_t res = encr_enable ? BTM_SUCCESS : BTM_ERR_PROCESSING; list_t* list = fixed_queue_get_list(btm_cb.sec_pending_q); for (const list_node_t* node = list_begin(list); node != list_end(list);) { tBTM_SEC_QUEUE_ENTRY* p_e = (tBTM_SEC_QUEUE_ENTRY*)list_node(node); node = list_next(node); if (memcmp(p_e->bd_addr, p_dev_rec->bd_addr, BD_ADDR_LEN) == 0 && p_e->psm == 0 && p_e->transport == transport) { if (encr_enable == 0 || transport == BT_TRANSPORT_BR_EDR || p_e->sec_act == BTM_BLE_SEC_ENCRYPT || p_e->sec_act == BTM_BLE_SEC_ENCRYPT_NO_MITM || (p_e->sec_act == BTM_BLE_SEC_ENCRYPT_MITM && p_dev_rec->sec_flags & BTM_SEC_LE_AUTHENTICATED)) { if (p_e->p_callback) (*p_e->p_callback)(p_dev_rec->bd_addr, transport, p_e->p_ref_data, res); fixed_queue_try_remove_from_queue(btm_cb.sec_pending_q, (void*)p_e); } } } } /******************************************************************************* * * Function btm_sec_set_serv_level4_flags * * Description This function is called to set security mode 4 level 4 * flags. * * Returns service security requirements updated to include secure * connections only mode. * ******************************************************************************/ static uint16_t btm_sec_set_serv_level4_flags(uint16_t cur_security, bool is_originator) { uint16_t sec_level4_flags = is_originator ? BTM_SEC_OUT_LEVEL4_FLAGS : BTM_SEC_IN_LEVEL4_FLAGS; return cur_security | sec_level4_flags; } /******************************************************************************* * * Function btm_sec_clear_ble_keys * * Description This function is called to clear out the BLE keys. * Typically when devices are removed in BTM_SecDeleteDevice, * or when a new BT Link key is generated. * * Returns void * ******************************************************************************/ void btm_sec_clear_ble_keys(tBTM_SEC_DEV_REC* p_dev_rec) { BTM_TRACE_DEBUG("%s() Clearing BLE Keys", __func__); p_dev_rec->ble.key_type = BTM_LE_KEY_NONE; memset(&p_dev_rec->ble.keys, 0, sizeof(tBTM_SEC_BLE_KEYS)); #if (BLE_PRIVACY_SPT == TRUE) btm_ble_resolving_list_remove_dev(p_dev_rec); #endif } /******************************************************************************* * * Function btm_sec_is_a_bonded_dev * * Description Is the specified device is a bonded device * * Returns true - dev is bonded * ******************************************************************************/ bool btm_sec_is_a_bonded_dev(BD_ADDR bda) { tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bda); bool is_bonded = false; if (p_dev_rec && ((p_dev_rec->ble.key_type && (p_dev_rec->sec_flags & BTM_SEC_LE_LINK_KEY_KNOWN)) || (p_dev_rec->sec_flags & BTM_SEC_LINK_KEY_KNOWN))) { is_bonded = true; } BTM_TRACE_DEBUG("%s() is_bonded=%d", __func__, is_bonded); return (is_bonded); } /******************************************************************************* * * Function btm_sec_is_le_capable_dev * * Description Is the specified device is dual mode or LE only device * * Returns true - dev is a dual mode * ******************************************************************************/ bool btm_sec_is_le_capable_dev(BD_ADDR bda) { tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bda); bool le_capable = false; if (p_dev_rec && (p_dev_rec->device_type & BT_DEVICE_TYPE_BLE) == BT_DEVICE_TYPE_BLE) le_capable = true; return le_capable; } /******************************************************************************* * * Function btm_sec_use_smp_br_chnl * * Description The function checks if SMP BR connection can be used with * the peer. * Is called when authentication for dedicated bonding is * successfully completed. * * Returns true - if SMP BR connection can be used (the link key is * generated from P-256 and the peer supports Security * Manager over BR). * ******************************************************************************/ static bool btm_sec_use_smp_br_chnl(tBTM_SEC_DEV_REC* p_dev_rec) { uint32_t ext_feat; uint8_t chnl_mask[L2CAP_FIXED_CHNL_ARRAY_SIZE]; BTM_TRACE_DEBUG("%s() link_key_type = 0x%x", __func__, p_dev_rec->link_key_type); if ((p_dev_rec->link_key_type != BTM_LKEY_TYPE_UNAUTH_COMB_P_256) && (p_dev_rec->link_key_type != BTM_LKEY_TYPE_AUTH_COMB_P_256)) return false; if (!L2CA_GetPeerFeatures(p_dev_rec->bd_addr, &ext_feat, chnl_mask)) return false; if (!(chnl_mask[0] & L2CAP_FIXED_CHNL_SMP_BR_BIT)) return false; return true; } /******************************************************************************* * * Function btm_sec_is_master * * Description The function checks if the device is BR/EDR master after * pairing is completed. * * Returns true - if the device is master. * ******************************************************************************/ static bool btm_sec_is_master(tBTM_SEC_DEV_REC* p_dev_rec) { tACL_CONN* p = btm_bda_to_acl(p_dev_rec->bd_addr, BT_TRANSPORT_BR_EDR); return (p && (p->link_role == BTM_ROLE_MASTER)); }
38.112073
80
0.60669
[ "model" ]
febd3f4995f826313f65c00b36ae67cdf979814c
1,466
cpp
C++
227-Basic-Calculator-2/Basic-Calculator-2-2.cpp
xta0/LeetCode-Solutions
ab0de97b35fb54c24bcef0398a9d75bdac9ee8b2
[ "MIT" ]
4
2018-08-07T11:45:32.000Z
2019-05-19T08:52:19.000Z
227-Basic-Calculator-2/Basic-Calculator-2-2.cpp
xta0/LeetCode-Solutions
ab0de97b35fb54c24bcef0398a9d75bdac9ee8b2
[ "MIT" ]
null
null
null
227-Basic-Calculator-2/Basic-Calculator-2-2.cpp
xta0/LeetCode-Solutions
ab0de97b35fb54c24bcef0398a9d75bdac9ee8b2
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <string> #include <stack> #include <queue> #include <map> #include <set> #include <unordered_set> #include <unordered_map> using namespace std; /* keep tracking of last sign 1. if c is digit, update the num 2. if c is '+/-', push num to stack */ class Solution { void helper(stack<int>& stk, char sign, int num){ if(sign == ' ' || sign == '+'){ stk.push(num); }else if(sign == '-'){ stk.push(-num); }else if(sign == '*'){ int x = stk.top(); stk.pop(); stk.push(x*num); }else { int x = stk.top(); stk.pop(); stk.push(x/num); } } public: int calculate(string s) { char sign = ' '; int num = 0; stack<int> stk; for(int i=0;i<s.size();i++){ char c = s[i]; if( isspace(c) ){ continue; } if(isdigit(c)){ num = 10*num + c-'0'; }else{ helper(stk,sign,num); num = 0; sign = c; } } //handle the last number helper(stk,sign,num); int result = 0; while(!stk.empty()){ result += stk.top(); stk.pop(); } return result; } }; int main(){ Solution s; cout<<s.calculate("5*10-4/2/1+1")<<endl; return 0; }
21.558824
53
0.43588
[ "vector" ]
febfb99ba3111d41b9108442c803431d34657be6
9,118
hpp
C++
metaprogrammed_polymorphism/polymorphic.hpp
google/cpp-from-the-sky-down
10c8d16e877796f2906bedbd3a66fb6469b3a211
[ "Apache-2.0" ]
219
2018-08-15T22:01:07.000Z
2022-03-23T11:46:54.000Z
metaprogrammed_polymorphism/polymorphic.hpp
sthagen/cpp-from-the-sky-down
72114a17a659e5919b4cbe3363e35c04f833d9d9
[ "Apache-2.0" ]
5
2018-09-11T06:15:28.000Z
2022-01-05T15:27:31.000Z
metaprogrammed_polymorphism/polymorphic.hpp
sthagen/cpp-from-the-sky-down
72114a17a659e5919b4cbe3363e35c04f833d9d9
[ "Apache-2.0" ]
27
2018-09-11T06:14:40.000Z
2022-03-20T09:46:14.000Z
// Copyright 2018 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // limitations under the License. #pragma once #include <array> #include <cstdint> #include <limits> #include <memory> #include <utility> namespace polymorphic { namespace detail { // We have a lot of intermediate functions. We want to make sure that we forward // the parameters correctly. For non-reference parameters, we always move them. template <typename T> struct fwd_helper { using type = T&&; }; template <typename T> struct fwd_helper<T&> { using type = T&; }; template <typename T> struct fwd_helper<T&&> { using type = T&&; }; template <typename T, typename U> decltype(auto) fwd(U&& u) { return static_cast<typename fwd_helper<T>::type>(u); } template <typename T> using ptr = T*; template <typename T> struct type {}; template <typename... F> struct overload : F... { using F::operator()...; }; template <typename T, typename Signature> struct trampoline; template <typename T, typename Return, typename Method, typename... Parameters> struct trampoline<T, Return(Method, Parameters...)> { static auto jump(void* t, Parameters... parameters) -> Return { return poly_extend(Method{}, *static_cast<T*>(t), fwd<Parameters>(parameters)...); } }; template <typename T, typename Return, typename Method, typename... Parameters> struct trampoline<T, Return(Method, Parameters...) const> { static auto jump(const void* t, Parameters... parameters) -> Return { return poly_extend(Method{}, *static_cast<const T*>(t), fwd<Parameters>(parameters)...); } }; using vtable_fun = ptr<void()>; template <typename T, typename... Signatures> inline const vtable_fun vtable[] = { reinterpret_cast<vtable_fun>(trampoline<T, Signatures>::jump)... }; template <size_t I, typename Signature> struct vtable_caller; template <size_t I, typename Method, typename Return, typename... Parameters> struct vtable_caller<I, Return(Method, Parameters...)> { decltype(auto) operator()(const vtable_fun* vt, const std::uint8_t* permutation, Method, void* t, Parameters... parameters) const { return reinterpret_cast<ptr<Return(void*, Parameters...)>>(vt[permutation[I]])( t, fwd<Parameters>(parameters)...); } }; template <std::size_t I, typename Method, typename Return, typename... Parameters> struct vtable_caller<I, Return(Method, Parameters...) const> { decltype(auto) operator()(const vtable_fun* vt, const std::uint8_t* permutation, Method, const void* t, Parameters... parameters) const { return reinterpret_cast<ptr<Return(const void*, Parameters...)>>(vt[permutation[I]])(t, fwd<Parameters>(parameters)...); } }; template <typename Signature> struct is_const_signature : std::false_type {}; template <typename Method, typename Return, typename... Parameters> struct is_const_signature<Return(Method, Parameters...) const> : std::true_type {}; template <std::size_t I, typename Signature> struct index_getter { constexpr int operator()(type<Signature>) const { return I; } }; struct value_tag {}; template <typename Holder, typename Sequence, typename... Signatures> class ref_impl; template<typename T> struct is_ref_impl :std::false_type {}; template <typename Holder, typename Sequence, typename... Signatures> struct is_ref_impl<ref_impl<Holder, Sequence, Signatures...>> :std::true_type {}; template <typename Holder, size_t... I, typename... Signatures> class ref_impl<Holder, std::index_sequence<I...>, Signatures...> { template <typename OtherHolder, typename OtherSequence, typename... OtherSignatures> friend class ref_impl; const detail::vtable_fun* vptr_; std::array<std::uint8_t, sizeof...(Signatures)> permutation_; Holder t_; static constexpr overload<vtable_caller<I, Signatures>...> call_vtable{}; static constexpr overload<index_getter<I, Signatures>...> get_index{}; template <typename T> ref_impl(T&& t, std::false_type) : vptr_(&detail::vtable<std::decay_t<T>, Signatures...>[0]), permutation_{ I... }, t_(std::forward<T>(t), value_tag{}) {} template <typename OtherRef> ref_impl(OtherRef&& other, std::true_type) : vptr_(other.vptr_), permutation_{ other.permutation_[other.get_index(type<Signatures>{})]... }, t_(std::forward<OtherRef>(other).t_) { } public: template <typename T> ref_impl(T&& t) :ref_impl(std::forward<T>(t), is_ref_impl<std::decay_t<T>>{}) {} explicit operator bool() const { return t_ != nullptr; } auto get_ptr() const { return t_.get_ptr(); } auto get_ptr() { return t_.get_ptr(); } template <typename Method, typename... Parameters> decltype(auto) call(Parameters&&... parameters) const { return call_vtable(vptr_, permutation_.data(), Method{}, t_.get_ptr(), std::forward<Parameters>(parameters)...); } template <typename Method, typename... Parameters> decltype(auto) call(Parameters&&... parameters) { return call_vtable(vptr_, permutation_.data(), Method{}, t_.get_ptr(), std::forward<Parameters>(parameters)...); } }; struct holder_interface { virtual std::unique_ptr<holder_interface> clone()const = 0; virtual ~holder_interface() {} void* ptr_ = nullptr; }; template<typename T> struct holder_impl :holder_interface { holder_impl(T t) :t_(std::move(t)) { ptr_ = &t_; } std::unique_ptr<holder_interface> clone() const override { return std::make_unique<holder_impl<T>>(t_); } T t_; }; class value_holder { std::unique_ptr<holder_interface> impl_; void* ptr_ = nullptr; public: template<typename T> value_holder(T t, value_tag) :impl_(std::make_unique<holder_impl<T>>(std::move(t))), ptr_(get_ptr_impl()) {} value_holder(value_holder&& other)noexcept :impl_(std::move(other.impl_)), ptr_(other.ptr_) { other.ptr_ = nullptr; } value_holder& operator=(value_holder&& other)noexcept { impl_ = std::move(other.impl_); ptr_ = std::move(other.ptr_); other.ptr_ = nullptr; return *this; } value_holder(const value_holder& other) :impl_(other.impl_ ? other.impl_->clone() : nullptr), ptr_(get_ptr_impl()) {} value_holder& operator=(const value_holder& other) { return (*this) = value_holder(other); } void* get_ptr_impl() { return impl_ ? impl_->ptr_ : nullptr; } void* get_ptr() { return ptr_; } const void* get_ptr()const { return ptr_; } auto clone_ptr()const { return impl_ ? impl_->clone() : nullptr; } }; struct shared_ptr_holder { std::shared_ptr<const holder_interface> impl_; const void* ptr_ = nullptr; const void* get_ptr()const { return ptr_; } const void* get_ptr_impl()const { return impl_ ? impl_->ptr_ : nullptr; } shared_ptr_holder(const shared_ptr_holder&) = default; shared_ptr_holder& operator=(const shared_ptr_holder&) = default; shared_ptr_holder(shared_ptr_holder&& other)noexcept :impl_(std::move(other.impl_)), ptr_(other.ptr_) { other.ptr_ = nullptr; } shared_ptr_holder& operator=(shared_ptr_holder&& other)noexcept { impl_ = std::move(other.impl_); ptr_ = std::move(other.ptr_); other.ptr_ = nullptr; return *this; } template<typename T> shared_ptr_holder(T t, value_tag) :impl_(std::make_shared<const holder_impl<T>>(std::move(t))), ptr_(get_ptr_impl()) {} shared_ptr_holder(const value_holder& v) :impl_(v.clone_ptr()), ptr_(get_ptr_impl()) {} auto clone_ptr()const { return impl_ ? impl_->clone() : nullptr; } }; template<typename T> struct ptr_holder { T* ptr_; T* get_ptr()const { return ptr_; } template<typename V> ptr_holder(V& v, value_tag) :ptr_(&v) {} template<typename OtherT> ptr_holder(const ptr_holder<OtherT>& other) : ptr_(other.get_ptr()) {} template<typename OtherT> ptr_holder& operator=(const ptr_holder<OtherT>& other) { return (*this) = ptr_holder(other); } ptr_holder(value_holder& v) :ptr_(v.get_ptr()) {} ptr_holder(const value_holder& v) :ptr_(v.get_ptr()) {} ptr_holder(const shared_ptr_holder& v) :ptr_(v.get_ptr()) {} }; } // namespace detail template <typename... Signatures> using ref = detail::ref_impl< detail::ptr_holder<std::conditional_t< std::conjunction_v<detail::is_const_signature<Signatures>...>, const void, void>>, std::make_index_sequence<sizeof...(Signatures)>, Signatures...>; template <typename... Signatures> using object = detail::ref_impl< std::conditional_t< std::conjunction_v<detail::is_const_signature<Signatures>...>, detail::shared_ptr_holder, detail::value_holder >, std::make_index_sequence<sizeof...(Signatures)>, Signatures...>; } // namespace polymorphic
36.326693
124
0.692038
[ "object" ]
fec1b1d01f7f80986d2630fb130654a864fa4508
1,906
cpp
C++
src/vw_common/test/actions_test.cpp
TomFinley/FeatureBroker
481a8f9a1a2e0980eee14d84f712ec3abf40ef0e
[ "MIT" ]
10
2020-03-17T00:35:54.000Z
2021-08-22T12:31:27.000Z
src/vw_common/test/actions_test.cpp
TomFinley/FeatureBroker
481a8f9a1a2e0980eee14d84f712ec3abf40ef0e
[ "MIT" ]
3
2020-03-17T17:25:15.000Z
2020-03-17T21:10:41.000Z
src/vw_common/test/actions_test.cpp
TomFinley/FeatureBroker
481a8f9a1a2e0980eee14d84f712ec3abf40ef0e
[ "MIT" ]
6
2020-03-13T15:39:03.000Z
2021-11-10T08:19:06.000Z
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include <gtest/gtest.h> #include <vw_common/actions.hpp> #include <vw_common/error.hpp> using namespace resonance_vw; namespace resonance_vw_test { TEST(vw_common, Actions) { auto result = Actions::Create(std::vector<int>{1, 2, 3, 4}); EXPECT_TRUE(result.has_value()); EXPECT_EQ(result.value()->Type(), ActionType::Int); auto resultIntVec = result.value()->GetIntActions(); EXPECT_TRUE(resultIntVec.has_value()); EXPECT_EQ(resultIntVec.value().size(), 4); result = Actions::Create(std::vector<float>{1.1f, 2.3f, 4.5f}); EXPECT_TRUE(result.has_value()); EXPECT_EQ(result.value()->Type(), ActionType::Float); auto resultFloatVec = result.value()->GetFloatActions(); EXPECT_TRUE(resultFloatVec.has_value()); EXPECT_EQ(resultFloatVec.value().size(), 3); result = Actions::Create(std::vector<std::string>{"1", "2", "3", "4"}); EXPECT_TRUE(result.has_value()); EXPECT_EQ(result.value()->Type(), ActionType::String); auto resultStringVec = result.value()->GetStringActions(); EXPECT_TRUE(resultStringVec.has_value()); EXPECT_EQ(resultStringVec.value().size(), 4); } TEST(vw_common, ActionsBadCase) { auto result = Actions::Create(std::vector<int>{}); EXPECT_FALSE(result.has_value()); EXPECT_EQ(vw_errc::invalid_actions, result.error()); result = Actions::Create(std::vector<float>{}); EXPECT_FALSE(result.has_value()); EXPECT_EQ(vw_errc::invalid_actions, result.error()); result = Actions::Create(std::vector<std::string>{}); EXPECT_FALSE(result.has_value()); EXPECT_EQ(vw_errc::invalid_actions, result.error()); // Invalid type result = Actions::Create(std::vector<double>{}); EXPECT_FALSE(result.has_value()); EXPECT_EQ(vw_errc::invalid_actions, result.error()); } } // namespace resonance_vw_test
34.654545
75
0.69255
[ "vector" ]
fec1d5bca1dd00d72ce37d549693860d036bd73c
991
cpp
C++
BOJ/1787. 문자열의 주기 예측.cpp
Jeongseo21/Algorithm-1
1bce4f3d2328c3b3e24b9d7772fca43090a285e1
[ "MIT" ]
null
null
null
BOJ/1787. 문자열의 주기 예측.cpp
Jeongseo21/Algorithm-1
1bce4f3d2328c3b3e24b9d7772fca43090a285e1
[ "MIT" ]
null
null
null
BOJ/1787. 문자열의 주기 예측.cpp
Jeongseo21/Algorithm-1
1bce4f3d2328c3b3e24b9d7772fca43090a285e1
[ "MIT" ]
null
null
null
/** * problem : https://www.acmicpc.net/problem/1787 * algorithm : KMP + DP * time complexity : O(N) */ #include <string> #include <algorithm> #include <vector> #include <iostream> #include <stack> #include <string.h> #define MAX 1e9 using namespace std; vector<int> dp; vector<int> pi; vector<int> makePi(string s) { vector<int> pi(s.size(), 0); int ind = 0; for (int i = 1; i < s.size(); i++) { while (ind > 0 && s[ind] != s[i]) ind = pi[ind - 1]; if (s[ind] == s[i]) pi[i] = ++ind; } return pi; } int dfs(int ind) { if (ind < 0 || pi[ind] == 0) // not same return MAX; int& ret = dp[ind]; if (ret != -1) return ret; ret = min(pi[ind], dfs(pi[ind] - 1)); return ret; } long long int solve(int N, string s) { pi = makePi(s); dp = vector<int>(N, -1); long long int ans = 0; for (int i = 0; i < N; i++) { ans += max(0, i - dfs(i) + 1); } return ans; } int main() { int N; cin >> N; string s; cin >> s; cout << solve(N, s) << endl; return 0; }
16.516667
49
0.551968
[ "vector" ]
fec54dc1ad098f06a271843f77609a72772c2aef
18,495
cc
C++
RecoLocalCalo/EcalRecProducers/plugins/EcalRecHitProducer.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
1
2020-08-12T08:37:04.000Z
2020-08-12T08:37:04.000Z
RecoLocalCalo/EcalRecProducers/plugins/EcalRecHitProducer.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
null
null
null
RecoLocalCalo/EcalRecProducers/plugins/EcalRecHitProducer.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
null
null
null
/** \class EcalRecHitProducer * produce ECAL rechits from uncalibrated rechits * * \author Shahram Rahatlou, University of Rome & INFN, March 2006 * **/ #include "RecoLocalCalo/EcalRecProducers/plugins/EcalRecHitProducer.h" #include "RecoLocalCalo/EcalRecAlgos/interface/EcalCleaningAlgo.h" #include "DataFormats/Common/interface/Handle.h" #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "DataFormats/EcalRecHit/interface/EcalRecHitCollections.h" #include "DataFormats/EcalRecHit/interface/EcalRecHitCollections.h" #include "DataFormats/EcalDetId/interface/EBDetId.h" #include "DataFormats/EcalDetId/interface/EEDetId.h" #include "DataFormats/EcalDetId/interface/EcalElectronicsId.h" #include "DataFormats/EcalDetId/interface/EcalTrigTowerDetId.h" #include "DataFormats/EcalDetId/interface/EcalScDetId.h" #include "CondFormats/DataRecord/interface/EcalChannelStatusRcd.h" #include "CondFormats/EcalObjects/interface/EcalChannelStatus.h" #include "RecoLocalCalo/EcalRecProducers/interface/EcalRecHitWorkerFactory.h" #include "FWCore/ParameterSet/interface/ConfigurationDescriptions.h" #include "FWCore/ParameterSet/interface/ParameterSetDescription.h" EcalRecHitProducer::EcalRecHitProducer(const edm::ParameterSet& ps) { ebRechitCollection_ = ps.getParameter<std::string>("EBrechitCollection"); eeRechitCollection_ = ps.getParameter<std::string>("EErechitCollection"); recoverEBIsolatedChannels_ = ps.getParameter<bool>("recoverEBIsolatedChannels"); recoverEEIsolatedChannels_ = ps.getParameter<bool>("recoverEEIsolatedChannels"); recoverEBVFE_ = ps.getParameter<bool>("recoverEBVFE"); recoverEEVFE_ = ps.getParameter<bool>("recoverEEVFE"); recoverEBFE_ = ps.getParameter<bool>("recoverEBFE"); recoverEEFE_ = ps.getParameter<bool>("recoverEEFE"); killDeadChannels_ = ps.getParameter<bool>("killDeadChannels"); produces< EBRecHitCollection >(ebRechitCollection_); produces< EERecHitCollection >(eeRechitCollection_); ebUncalibRecHitToken_ = consumes<EBUncalibratedRecHitCollection>( ps.getParameter<edm::InputTag>("EBuncalibRecHitCollection")); eeUncalibRecHitToken_ = consumes<EEUncalibratedRecHitCollection>( ps.getParameter<edm::InputTag>("EEuncalibRecHitCollection")); ebDetIdToBeRecoveredToken_ = consumes<std::set<EBDetId>>(ps.getParameter<edm::InputTag>("ebDetIdToBeRecovered")); eeDetIdToBeRecoveredToken_= consumes<std::set<EEDetId>>(ps.getParameter<edm::InputTag>("eeDetIdToBeRecovered")); ebFEToBeRecoveredToken_ = consumes<std::set<EcalTrigTowerDetId>>(ps.getParameter<edm::InputTag>("ebFEToBeRecovered")); eeFEToBeRecoveredToken_= consumes<std::set<EcalScDetId>>( ps.getParameter<edm::InputTag>("eeFEToBeRecovered")) ; std::string componentType = ps.getParameter<std::string>("algo"); edm::ConsumesCollector c{consumesCollector()}; worker_ = EcalRecHitWorkerFactory::get()->create(componentType, ps, c); // to recover problematic channels componentType = ps.getParameter<std::string>("algoRecover"); workerRecover_ = EcalRecHitWorkerFactory::get()->create(componentType, ps, c); edm::ParameterSet cleaningPs = ps.getParameter<edm::ParameterSet>("cleaningConfig"); cleaningAlgo_ = new EcalCleaningAlgo(cleaningPs); } EcalRecHitProducer::~EcalRecHitProducer() { delete worker_; delete workerRecover_; delete cleaningAlgo_; } void EcalRecHitProducer::produce(edm::Event& evt, const edm::EventSetup& es) { using namespace edm; Handle< EBUncalibratedRecHitCollection > pEBUncalibRecHits; Handle< EEUncalibratedRecHitCollection > pEEUncalibRecHits; const EBUncalibratedRecHitCollection* ebUncalibRecHits = nullptr; const EEUncalibratedRecHitCollection* eeUncalibRecHits = nullptr; // get the barrel uncalib rechit collection evt.getByToken( ebUncalibRecHitToken_, pEBUncalibRecHits); ebUncalibRecHits = pEBUncalibRecHits.product(); LogDebug("EcalRecHitDebug") << "total # EB uncalibrated rechits: " << ebUncalibRecHits->size(); evt.getByToken( eeUncalibRecHitToken_, pEEUncalibRecHits); eeUncalibRecHits = pEEUncalibRecHits.product(); // get a ptr to the product LogDebug("EcalRecHitDebug") << "total # EE uncalibrated rechits: " << eeUncalibRecHits->size(); // collection of rechits to put in the event auto ebRecHits = std::make_unique<EBRecHitCollection>(); auto eeRecHits = std::make_unique<EERecHitCollection>(); worker_->set(es); if ( recoverEBIsolatedChannels_ || recoverEEIsolatedChannels_ || recoverEBFE_ || recoverEEFE_ || recoverEBVFE_ || recoverEEVFE_ || killDeadChannels_ ) { workerRecover_->set(es); } if (ebUncalibRecHits) { // loop over uncalibrated rechits to make calibrated ones for(EBUncalibratedRecHitCollection::const_iterator it = ebUncalibRecHits->begin(); it != ebUncalibRecHits->end(); ++it) { worker_->run(evt, *it, *ebRecHits); } } if (eeUncalibRecHits) { // loop over uncalibrated rechits to make calibrated ones for(EEUncalibratedRecHitCollection::const_iterator it = eeUncalibRecHits->begin(); it != eeUncalibRecHits->end(); ++it) { worker_->run(evt, *it, *eeRecHits); } } // sort collections before attempting recovery, to avoid insertion of double recHits ebRecHits->sort(); eeRecHits->sort(); if ( recoverEBIsolatedChannels_ || recoverEBFE_ || killDeadChannels_ ) { edm::Handle< std::set<EBDetId> > pEBDetId; const std::set<EBDetId> * detIds = nullptr; evt.getByToken( ebDetIdToBeRecoveredToken_, pEBDetId); detIds = pEBDetId.product(); if ( detIds ) { edm::ESHandle<EcalChannelStatus> chStatus; es.get<EcalChannelStatusRcd>().get(chStatus); for( std::set<EBDetId>::const_iterator it = detIds->begin(); it != detIds->end(); ++it ) { // get channel status map to treat dead VFE separately EcalChannelStatusMap::const_iterator chit = chStatus->find( *it ); EcalChannelStatusCode chStatusCode; if ( chit != chStatus->end() ) { chStatusCode = *chit; } else { edm::LogError("EcalRecHitProducerError") << "No channel status found for xtal " << (*it).rawId() << "! something wrong with EcalChannelStatus in your DB? "; } EcalUncalibratedRecHit urh; if ( chStatusCode.getStatusCode() == EcalChannelStatusCode::kDeadVFE ) { // dead VFE (from DB info) // uses the EcalUncalibratedRecHit to pass the DetId info urh = EcalUncalibratedRecHit( *it, 0, 0, 0, 0, EcalRecHitWorkerBaseClass::EB_VFE ); if ( recoverEBVFE_ || killDeadChannels_ ) workerRecover_->run( evt, urh, *ebRecHits ); } else { // uses the EcalUncalibratedRecHit to pass the DetId info urh = EcalUncalibratedRecHit( *it, 0, 0, 0, 0, EcalRecHitWorkerBaseClass::EB_single ); if ( recoverEBIsolatedChannels_ || killDeadChannels_ ) workerRecover_->run( evt, urh, *ebRecHits ); } } } } if ( recoverEEIsolatedChannels_ || recoverEEVFE_ || killDeadChannels_ ) { edm::Handle< std::set<EEDetId> > pEEDetId; const std::set<EEDetId> * detIds = nullptr; evt.getByToken( eeDetIdToBeRecoveredToken_, pEEDetId); detIds = pEEDetId.product(); if ( detIds ) { edm::ESHandle<EcalChannelStatus> chStatus; es.get<EcalChannelStatusRcd>().get(chStatus); for( std::set<EEDetId>::const_iterator it = detIds->begin(); it != detIds->end(); ++it ) { // get channel status map to treat dead VFE separately EcalChannelStatusMap::const_iterator chit = chStatus->find( *it ); EcalChannelStatusCode chStatusCode; if ( chit != chStatus->end() ) { chStatusCode = *chit; } else { edm::LogError("EcalRecHitProducerError") << "No channel status found for xtal " << (*it).rawId() << "! something wrong with EcalChannelStatus in your DB? "; } EcalUncalibratedRecHit urh; if ( chStatusCode.getStatusCode() == EcalChannelStatusCode::kDeadVFE) { // dead VFE (from DB info) // uses the EcalUncalibratedRecHit to pass the DetId info urh = EcalUncalibratedRecHit( *it, 0, 0, 0, 0, EcalRecHitWorkerBaseClass::EE_VFE ); if ( recoverEEVFE_ || killDeadChannels_ ) workerRecover_->run( evt, urh, *eeRecHits ); } else { // uses the EcalUncalibratedRecHit to pass the DetId info urh = EcalUncalibratedRecHit( *it, 0, 0, 0, 0, EcalRecHitWorkerBaseClass::EE_single ); if ( recoverEEIsolatedChannels_ || killDeadChannels_ ) workerRecover_->run( evt, urh, *eeRecHits ); } } } } if ( recoverEBFE_ || killDeadChannels_ ) { edm::Handle< std::set<EcalTrigTowerDetId> > pEBFEId; const std::set<EcalTrigTowerDetId> * ttIds = nullptr; evt.getByToken( ebFEToBeRecoveredToken_, pEBFEId); ttIds = pEBFEId.product(); if ( ttIds ) { for( std::set<EcalTrigTowerDetId>::const_iterator it = ttIds->begin(); it != ttIds->end(); ++it ) { // uses the EcalUncalibratedRecHit to pass the DetId info int ieta = (((*it).ietaAbs()-1)*5+1)*(*it).zside(); // from EcalTrigTowerConstituentsMap int iphi = (((*it).iphi()-1)*5+11)%360; // from EcalTrigTowerConstituentsMap if( iphi <= 0 ) iphi += 360; // from EcalTrigTowerConstituentsMap EcalUncalibratedRecHit urh( EBDetId(ieta, iphi, EBDetId::ETAPHIMODE), 0, 0, 0, 0, EcalRecHitWorkerBaseClass::EB_FE ); workerRecover_->run( evt, urh, *ebRecHits ); } } } if ( recoverEEFE_ || killDeadChannels_ ) { edm::Handle< std::set<EcalScDetId> > pEEFEId; const std::set<EcalScDetId> * scIds = nullptr; evt.getByToken( eeFEToBeRecoveredToken_, pEEFEId); scIds = pEEFEId.product(); if ( scIds ) { for( std::set<EcalScDetId>::const_iterator it = scIds->begin(); it != scIds->end(); ++it ) { // uses the EcalUncalibratedRecHit to pass the DetId info if (EEDetId::validDetId( ((*it).ix()-1)*5+1, ((*it).iy()-1)*5+1, (*it).zside() )) { EcalUncalibratedRecHit urh( EEDetId( ((*it).ix()-1)*5+1, ((*it).iy()-1)*5+1, (*it).zside() ), 0, 0, 0, 0, EcalRecHitWorkerBaseClass::EE_FE ); workerRecover_->run( evt, urh, *eeRecHits ); } } } } // without re-sorting, find (used below in cleaning) will lead // to undefined results ebRecHits->sort(); eeRecHits->sort(); // apply spike cleaning if (cleaningAlgo_){ cleaningAlgo_->setFlags(*ebRecHits); cleaningAlgo_->setFlags(*eeRecHits); } // put the collection of recunstructed hits in the event LogInfo("EcalRecHitInfo") << "total # EB calibrated rechits: " << ebRecHits->size(); LogInfo("EcalRecHitInfo") << "total # EE calibrated rechits: " << eeRecHits->size(); evt.put(std::move(ebRecHits), ebRechitCollection_); evt.put(std::move(eeRecHits), eeRechitCollection_); } void EcalRecHitProducer::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { edm::ParameterSetDescription desc; desc.add<bool>("recoverEEVFE",false); desc.add<std::string>("EErechitCollection","EcalRecHitsEE"); desc.add<bool>("recoverEBIsolatedChannels",false); desc.add<bool>("recoverEBVFE",false); desc.add<bool>("laserCorrection",true); desc.add<double>("EBLaserMIN",0.5); desc.add<bool>("killDeadChannels",true); { std::vector<int> temp1; temp1.reserve(3); temp1.push_back(14); temp1.push_back(78); temp1.push_back(142); desc.add<std::vector<int> >("dbStatusToBeExcludedEB",temp1); } desc.add<edm::InputTag>("EEuncalibRecHitCollection",edm::InputTag("ecalMultiFitUncalibRecHit","EcalUncalibRecHitsEE")); { std::vector<int> temp1; temp1.reserve(3); temp1.push_back(14); temp1.push_back(78); temp1.push_back(142); desc.add<std::vector<int> >("dbStatusToBeExcludedEE",temp1); } desc.add<double>("EELaserMIN",0.5); desc.add<edm::InputTag>("ebFEToBeRecovered",edm::InputTag("ecalDetIdToBeRecovered","ebFE")); { edm::ParameterSetDescription psd0; psd0.add<double>("e6e2thresh",0.04); psd0.add<double>("tightenCrack_e6e2_double",3); psd0.add<double>("e4e1Threshold_endcap",0.3); psd0.add<double>("tightenCrack_e4e1_single",3); psd0.add<double>("tightenCrack_e1_double",2); psd0.add<double>("cThreshold_barrel",4); psd0.add<double>("e4e1Threshold_barrel",0.08); psd0.add<double>("tightenCrack_e1_single",2); psd0.add<double>("e4e1_b_barrel",-0.024); psd0.add<double>("e4e1_a_barrel",0.04); psd0.add<double>("ignoreOutOfTimeThresh",1000000000.0); psd0.add<double>("cThreshold_endcap",15); psd0.add<double>("e4e1_b_endcap",-0.0125); psd0.add<double>("e4e1_a_endcap",0.02); psd0.add<double>("cThreshold_double",10); desc.add<edm::ParameterSetDescription>("cleaningConfig",psd0); } desc.add<double>("logWarningEtThreshold_EE_FE",50); desc.add<edm::InputTag>("eeDetIdToBeRecovered",edm::InputTag("ecalDetIdToBeRecovered","eeDetId")); desc.add<bool>("recoverEBFE",true); desc.add<edm::InputTag>("eeFEToBeRecovered",edm::InputTag("ecalDetIdToBeRecovered","eeFE")); desc.add<edm::InputTag>("ebDetIdToBeRecovered",edm::InputTag("ecalDetIdToBeRecovered","ebDetId")); desc.add<double>("singleChannelRecoveryThreshold",8); { std::vector<std::string> temp1; temp1.reserve(9); temp1.push_back("kNoisy"); temp1.push_back("kNNoisy"); temp1.push_back("kFixedG6"); temp1.push_back("kFixedG1"); temp1.push_back("kFixedG0"); temp1.push_back("kNonRespondingIsolated"); temp1.push_back("kDeadVFE"); temp1.push_back("kDeadFE"); temp1.push_back("kNoDataNoTP"); desc.add<std::vector<std::string> >("ChannelStatusToBeExcluded",temp1); } desc.add<std::string>("EBrechitCollection","EcalRecHitsEB"); desc.add<edm::InputTag>("triggerPrimitiveDigiCollection",edm::InputTag("ecalDigis","EcalTriggerPrimitives")); desc.add<bool>("recoverEEFE",true); desc.add<std::string>("singleChannelRecoveryMethod","NeuralNetworks"); desc.add<double>("EBLaserMAX",3.0); { edm::ParameterSetDescription psd0; { std::vector<std::string> temp2; temp2.reserve(4); temp2.push_back("kOk"); temp2.push_back("kDAC"); temp2.push_back("kNoLaser"); temp2.push_back("kNoisy"); psd0.add<std::vector<std::string> >("kGood",temp2); } { std::vector<std::string> temp2; temp2.reserve(3); temp2.push_back("kFixedG0"); temp2.push_back("kNonRespondingIsolated"); temp2.push_back("kDeadVFE"); psd0.add<std::vector<std::string> >("kNeighboursRecovered",temp2); } { std::vector<std::string> temp2; temp2.reserve(1); temp2.push_back("kNoDataNoTP"); psd0.add<std::vector<std::string> >("kDead",temp2); } { std::vector<std::string> temp2; temp2.reserve(3); temp2.push_back("kNNoisy"); temp2.push_back("kFixedG6"); temp2.push_back("kFixedG1"); psd0.add<std::vector<std::string> >("kNoisy",temp2); } { std::vector<std::string> temp2; temp2.reserve(1); temp2.push_back("kDeadFE"); psd0.add<std::vector<std::string> >("kTowerRecovered",temp2); } desc.add<edm::ParameterSetDescription>("flagsMapDBReco",psd0); } desc.add<edm::InputTag>("EBuncalibRecHitCollection",edm::InputTag("ecalMultiFitUncalibRecHit","EcalUncalibRecHitsEB")); desc.add<std::string>("algoRecover","EcalRecHitWorkerRecover"); desc.add<std::string>("algo","EcalRecHitWorkerSimple"); desc.add<double>("EELaserMAX",8.0); desc.add<double>("logWarningEtThreshold_EB_FE",50); desc.add<bool>("recoverEEIsolatedChannels",false); desc.add<bool>("skipTimeCalib",false); descriptions.add("ecalRecHit",desc); } #include "FWCore/Framework/interface/MakerMacros.h" DEFINE_FWK_MODULE( EcalRecHitProducer );
46.353383
181
0.60027
[ "vector" ]
fecc6039de8d0eb468fadc994df197fde7380f5d
1,034
cpp
C++
backup/2/codewars/c++/oring-arrays.cpp
yangyanzhan/code-camp
4272564e916fc230a4a488f92ae32c07d355dee0
[ "Apache-2.0" ]
21
2019-11-16T19:08:35.000Z
2021-11-12T12:26:01.000Z
backup/2/codewars/c++/oring-arrays.cpp
yangyanzhan/code-camp
4272564e916fc230a4a488f92ae32c07d355dee0
[ "Apache-2.0" ]
1
2022-02-04T16:02:53.000Z
2022-02-04T16:02:53.000Z
backup/2/codewars/c++/oring-arrays.cpp
yangyanzhan/code-camp
4272564e916fc230a4a488f92ae32c07d355dee0
[ "Apache-2.0" ]
4
2020-05-15T19:39:41.000Z
2021-10-30T06:40:31.000Z
// Hi, I'm Yanzhan. For more algothmic problems, visit my Youtube Channel (Yanzhan Yang's Youtube Channel) : https://www.youtube.com/channel/UCDkz-__gl3frqLexukpG0DA?view_as=subscriber or my Twitter Account (Yanzhan Yang's Twitter) : https://twitter.com/YangYanzhan or my GitHub HomePage (Yanzhan Yang's GitHub HomePage) : https://yanzhan.site . // For this specific algothmic problem, visit my Youtube Video : . // It's fascinating to solve algothmic problems, follow Yanzhan to learn more! // Blog URL for this problem: https://yanzhan.site/codewars/oring-arrays.html . #include <vector> using namespace std; std::vector<int> orArrays(const std::vector<int> &arr1, const std::vector<int> &arr2, int default_value = 0) { vector<int> res; int n = max(arr1.size(), arr2.size()); for (int i = 0; i < n; i++) { int num1 = i < arr1.size() ? arr1[i] : default_value; int num2 = i < arr2.size() ? arr2[i] : default_value; res.push_back(num1 | num2); } return res; }
49.238095
345
0.67118
[ "vector" ]
fed1a295ad79010708d58cb4ae4add2810addcc9
2,647
hpp
C++
IsometricEditor/Grid.hpp
NicksterSand/IsometricEditor
a422f103e5837631356f90c94eb39048824a32e5
[ "MIT" ]
null
null
null
IsometricEditor/Grid.hpp
NicksterSand/IsometricEditor
a422f103e5837631356f90c94eb39048824a32e5
[ "MIT" ]
null
null
null
IsometricEditor/Grid.hpp
NicksterSand/IsometricEditor
a422f103e5837631356f90c94eb39048824a32e5
[ "MIT" ]
null
null
null
#ifndef GRID_HPP #define GRID_HPP #include <vector> #include "Renderer.hpp" struct Pair { int x; int y; }; class Grid { public: Grid(int x, int y, int size, Color color, Renderer* render) { sizeX = x; sizeY = y; blockSize = size; gridColor = color; renderer = render; }; int sizeX; //Grid Pixel Size (Without scaling from window) int sizeY; int blockSize; void drawGrid() { for (int x = 0; x < sizeX; x += blockSize) { gridLines.push_back(renderer->drawLine(x, 0, x - (sizeY * 2 + 1), sizeY, gridColor)); gridLines.push_back(renderer->drawLine(x + 2, 0, x + (sizeY * 2 + 1), sizeY, gridColor)); } for (int y = (blockSize / 2) - 1; y < sizeY; y += (blockSize / 2)) { if (sizeX % 2 == 0) { gridLines.push_back(renderer->drawLine(0, y, sizeX + 1, y + (sizeX / 2 + 1), gridColor)); } else { gridLines.push_back(renderer->drawLine(0, y, sizeX, y + (sizeX / 2 + 1), gridColor)); } } for (int y = (blockSize / 2) - (((sizeX - 1) % 48) / 2 + 1); y < sizeY; y += (blockSize / 2)) { if (sizeX % 2 == 0) { gridLines.push_back(renderer->drawLine(sizeX, y, 0, y + (sizeX / 2), gridColor)); } else { gridLines.push_back(renderer->drawLine(sizeX + 1, y, 1, y + (sizeX / 2), gridColor)); } } } Pair getSquareFromGridPixel(int x, int y) { int modX = (x + 1) % blockSize; int modY = (y + 1) % (blockSize / 2); int xSection = (int)((x + 1) / blockSize); int ySection = (int)((y + 1) / (blockSize / 2)); int y1Top; if (modX < (blockSize / 2) + 2) { y1Top = (int)((modX * 0.5) - 1); } else { y1Top = (int)((modX * -0.5) + (blockSize / 2) + .5); } if (y1Top < 0) { y1Top = 0; } int y1Bottom = (-1 * y1Top) + 22; int gridY; if ((modY - 1) > y1Bottom) { gridY = 2 + (2 * ySection); } else if ((modY - 1) < y1Top) { gridY = 2 * ySection; } else { gridY = 1 + (2 * ySection); } int x1Left; if (modY <= (blockSize / 4)) { x1Left = (-2 * modY) + 49; } else { x1Left = (2 * modY) + 1; } int gridX; if (modX < x1Left) { gridX = xSection; } else { gridX = xSection + 1; } return { gridX, gridY }; } //Returns the top left corner of a square Pair getGridPixelFromSquare(int x, int y) { int pixelX, pixelY; if (y % 2 == 0) { pixelX = (x * blockSize) + 1; pixelY = ((y - 1) * (blockSize / 4)); } else { pixelX = (x * blockSize) - ((blockSize / 2) - 1); pixelY = ((y - 1) * (blockSize / 4)); } return { pixelX, pixelY }; } private: std::vector<Line*> gridLines; Renderer* renderer; Color gridColor; }; #endif
25.699029
98
0.539101
[ "render", "vector" ]
fed6e513b30842d7d2043ff8826663ff4e4c8bc3
1,389
cpp
C++
src/ast/operators/binaryOperators/binaryLogicalAnd.cpp
EthanSK/C-to-MIPS-Compiler
a736901053ec1a2ad009bf33f588b4ce5293317c
[ "MIT" ]
6
2019-05-21T09:42:10.000Z
2021-03-22T04:34:20.000Z
src/ast/operators/binaryOperators/binaryLogicalAnd.cpp
EthanSK/C-to-MIPS-Compiler
a736901053ec1a2ad009bf33f588b4ce5293317c
[ "MIT" ]
null
null
null
src/ast/operators/binaryOperators/binaryLogicalAnd.cpp
EthanSK/C-to-MIPS-Compiler
a736901053ec1a2ad009bf33f588b4ce5293317c
[ "MIT" ]
1
2019-06-25T22:35:24.000Z
2019-06-25T22:35:24.000Z
#include "binaryLogicalAnd.hpp" #include "lvalue.hpp" #include "utils.hpp" #include <sstream> void BinaryLogicalAnd::printC(std::ostream &os) const { os << "("; os << getLeft(); os << " && "; os << getRight(); os << ")"; } void BinaryLogicalAnd::generatePython(std::ostream &os, PythonContext &context, int scopeDepth) const { os << "("; getLeft()->generatePython(os, context, scopeDepth); os << " and "; getRight()->generatePython(os, context, scopeDepth); os << ")"; } void BinaryLogicalAnd::generateIL(std::vector<Instr> &instrs, ILContext &context, std::string destReg) const { std::string opcode = "andl"; std::string leftReg = context.makeName(opcode + "_l"); std::string rightReg = context.makeName(opcode + "_r"); std::string shortCircuit_lb = context.makeLabelName(opcode + "_sc"); std::string end_lb = context.makeLabelName(opcode + "_end"); context.compileInput(getLeft(), instrs, leftReg); instrs.push_back(Instr("bez", shortCircuit_lb, leftReg)); context.compileInput(getRight(), instrs, rightReg); instrs.push_back(Instr(opcode, destReg, leftReg, rightReg)); instrs.push_back(Instr("b", end_lb)); instrs.push_back(Instr::makeLabel(shortCircuit_lb)); instrs.push_back(Instr("li", destReg, "0")); instrs.push_back(Instr::makeLabel(end_lb)); } int BinaryLogicalAnd::evalConst() const { return getLeftR()->evalConst() && getRightR()->evalConst(); }
29.553191
108
0.704824
[ "vector" ]
fed7df0296d8dd0904e10b1cf0f49b58dfb144a0
1,632
cpp
C++
test/bitio/bitio.cpp
kounoike/cpp-mp4
65703c1402242afcc1e4d822d9828e79f3dcec01
[ "Apache-2.0" ]
23
2020-12-29T07:17:30.000Z
2022-03-25T09:18:37.000Z
test/bitio/bitio.cpp
kounoike/cpp-mp4
65703c1402242afcc1e4d822d9828e79f3dcec01
[ "Apache-2.0" ]
2
2021-01-12T06:02:42.000Z
2021-05-19T01:44:22.000Z
test/bitio/bitio.cpp
kounoike/cpp-mp4
65703c1402242afcc1e4d822d9828e79f3dcec01
[ "Apache-2.0" ]
2
2021-05-04T02:15:17.000Z
2022-02-19T14:45:00.000Z
#include <algorithm> #include <cstdint> #include <iterator> #include <ostream> #include <string> #include <vector> #include <boost/test/unit_test.hpp> #include "shiguredo/mp4/bitio/bitio.hpp" #include "shiguredo/mp4/bitio/reader.hpp" BOOST_AUTO_TEST_SUITE(marshal) struct UnmarshalPascalStringTestCase { const std::string name; const std::vector<std::uint8_t> bin; const std::string str; }; UnmarshalPascalStringTestCase unmarshal_pascal_string_test_cases[] = { { "NormalString", {'s', 'h', 'i', 'g', 'u', 'r', 'e', 'd', 'o', 0}, "shiguredo", }, { "EmptyString", {}, "", }, { "AppleQuickTimePascalStringWithEmpty", {0x00}, "", }, { "AppleQuickTimePascalString", {9, 's', 'h', 'i', 'g', 'u', 'r', 'e', 'd', 'o'}, "shiguredo", }, { "AppleQuickTimePascalStringLong", {' ', 'a', ' ', '1', 's', 't', ' ', 'b', 'y', 't', 'e', ' ', 'e', 'q', 'u', 'a', 'l', 's', ' ', 't', 'o', ' ', 't', 'h', 'i', 's', ' ', 'l', 'e', 'n', 'g', 't', 'h'}, "a 1st byte equals to this length", }, }; BOOST_AUTO_TEST_CASE(unmarshal_pascal_string) { for (const auto& tc : unmarshal_pascal_string_test_cases) { BOOST_TEST_MESSAGE(tc.name); std::stringstream ss; std::copy(std::begin(tc.bin), std::end(tc.bin), std::ostreambuf_iterator<char>(ss)); shiguredo::mp4::bitio::Reader reader(ss); std::string s; shiguredo::mp4::bitio::read_pascal_string(&reader, &s, std::size(tc.bin) * 8); BOOST_REQUIRE_EQUAL(tc.str, s); } } BOOST_AUTO_TEST_SUITE_END()
25.5
93
0.558211
[ "vector" ]
fed80885a4775e926db01e52b3363d55c4e20a55
8,412
cpp
C++
src/initialization.cpp
RugessNome/libscript
e27b1dfeb5cd9eb7e59a6d16e182758a56fc0e4f
[ "MIT" ]
3
2020-12-28T01:40:45.000Z
2021-05-18T01:47:07.000Z
src/initialization.cpp
strandfield/libscript
5d413762ad8ce88ff887642f6947032017dd284c
[ "MIT" ]
4
2019-06-29T12:23:11.000Z
2020-07-25T15:38:46.000Z
src/initialization.cpp
RugessNome/libscript
e27b1dfeb5cd9eb7e59a6d16e182758a56fc0e4f
[ "MIT" ]
1
2021-11-17T01:49:42.000Z
2021-11-17T01:49:42.000Z
// Copyright (C) 2018 Vincent Chambrin // This file is part of the libscript library // For conditions of distribution and use, see copyright notice in LICENSE #include "script/initialization.h" #include "script/class.h" #include "script/engine.h" #include "script/templateargument.h" #include "script/typesystem.h" #include "script/program/expression.h" #include <algorithm> #include <stdexcept> namespace script { struct InitializationData { InitializationData(Type t) : type(t) { } InitializationData(Function ctor) : constructor(ctor) { type = ctor.memberOf().id(); } Type type; Function constructor; std::vector<Initialization> initializations; }; Initialization::Initialization() : mCategory(DefaultInitialization) { } Initialization::Initialization(Category cat) : mCategory(cat) { } Initialization::Initialization(Category cat, Type t) : mCategory(cat) { mData = std::make_shared<InitializationData>(t); } Initialization::Initialization(Category cat, Function ctor) : mCategory(cat) { mData = std::make_shared<InitializationData>(ctor); } Initialization::Initialization(Category cat, const Conversion & conv) : mCategory(cat) , mConversion(conv) { if (conv.isInvalid()) mCategory = InvalidInitialization; } bool Initialization::isValid() const { return mData != nullptr || mConversion != Conversion::NotConvertible(); } bool Initialization::createsTemporary() const { if (!isReferenceInitialization()) return false; return !mConversion.firstStandardConversion().isReferenceConversion() || !mConversion.firstStandardConversion().isReferenceConversion(); } ConversionRank Initialization::rank() const { if (mData == nullptr) return mConversion.rank(); ConversionRank r = mData->initializations.front().rank(); for (size_t i(1); i < mData->initializations.size(); ++i) r = std::max(r, mData->initializations.at(i).rank()); return r; } bool Initialization::isNarrowing() const { if (mData == nullptr) return mConversion.isNarrowing(); for (const auto & init : mData->initializations) { if (init.isNarrowing()) return true; } return false; } bool Initialization::hasInitializations() const { return mData != nullptr; } std::vector<Initialization> & Initialization::initializations() { return mData->initializations; } const std::vector<Initialization> & Initialization::initializations() const { return mData->initializations; } Type Initialization::destType() const { switch (kind()) { case DirectInitialization: case ListInitialization: case AggregateInitialization: return mData->type; case DefaultInitialization: case ReferenceInitialization: case CopyInitialization: return Type::Auto; case InvalidInitialization: return Type::Null; } return Type::Null; } const Function & Initialization::constructor() const { return mData->constructor; } int Initialization::comp(const Initialization & a, const Initialization & b) { if ((a.mData == nullptr) != (b.mData == nullptr)) throw std::runtime_error{ "Initialization::comp() : the two sequences are not comparable" }; if(a.mData == nullptr) return Conversion::comp(a.conversion(), b.conversion()); if (a.kind() == ListInitialization && b.kind() != ListInitialization) return 1; else if (a.kind() != ListInitialization && b.kind() == ListInitialization) return -1; if (a.constructor().isNull() && !b.constructor().isNull()) { // a initializes an initializer_list return -1; } else if (!a.constructor().isNull() && b.constructor().isNull()) { return 1; } return 0; } static Initialization compute_initializer_list_conv(const Type & vartype, const std::shared_ptr<program::Expression> & expr, Engine *engine) { if (!expr->is<program::InitializerList>()) return Initialization::InvalidInitialization; const program::InitializerList & init_list = dynamic_cast<const program::InitializerList &>(*expr); Class initializer_list_type = engine->typeSystem()->getClass(vartype); Type T = initializer_list_type.arguments().front().type; std::vector<Initialization> inits; for (const auto & e : init_list.elements) { Initialization i = Initialization::compute(T, e, engine); if (!i.isValid()) return i; inits.push_back(i); } Initialization result{ Initialization::ListInitialization, initializer_list_type.id() }; result.initializations() = std::move(inits); return result; } static Initialization compute_initializer_list_conv(const std::shared_ptr<program::Expression> & expr, const Function & ctor, Engine *engine) { assert(expr->is<program::InitializerList>()); assert(engine->typeSystem()->isInitializerList(ctor.parameter(1))); const program::InitializerList & init_list = dynamic_cast<const program::InitializerList &>(*expr); Class initializer_list_type = engine->typeSystem()->getClass(ctor.parameter(1)); Type T = initializer_list_type.arguments().front().type; std::vector<Initialization> inits; for (const auto & e : init_list.elements) { Initialization i = Initialization::compute(T, e, engine); if (!i.isValid()) return i; inits.push_back(i); } Initialization result{ Initialization::ListInitialization, ctor }; result.initializations() = std::move(inits); return result; } Initialization Initialization::compute(const Type & vartype, Engine *engine) { if (vartype.isEnumType() || vartype.isClosureType() || vartype.isFunctionType()) return InvalidInitialization; else if (vartype.isFundamentalType()) return DefaultInitialization; assert(vartype.isObjectType()); Class cla = engine->typeSystem()->getClass(vartype); if (!cla.isDefaultConstructible()) return InvalidInitialization; return DefaultInitialization; } Initialization Initialization::compute(const Type & vartype, const Type & arg, Engine *engine, Initialization::Category cat) { if(cat != DirectInitialization && cat != CopyInitialization) throw std::runtime_error{ "Invalid Initialization::Category" }; auto opts = cat == DirectInitialization ? Conversion::AllowExplicitConversions : Conversion::NoExplicitConversions; Conversion conv = Conversion::compute(arg, vartype, engine, opts); if(!conv.isInvalid() || !vartype.isConstRef()) return Initialization{ cat, conv }; assert(vartype.isConstRef() && conv.isInvalid()); conv = Conversion::compute(arg, vartype.withoutRef(), engine, opts); return Initialization{ ReferenceInitialization, conv }; } Initialization Initialization::compute(const Type & vartype, const std::shared_ptr<program::Expression> & expr, Engine *engine) { if (expr->type() != Type::InitializerList) return compute(vartype, expr->type(), engine, CopyInitialization); if (engine->typeSystem()->isInitializerList(vartype)) return compute_initializer_list_conv(vartype, expr, engine); if (vartype.isReference() && !vartype.isConst()) return InvalidInitialization; const program::InitializerList & init_list = dynamic_cast<const program::InitializerList &>(*expr); if (init_list.elements.empty()) return Initialization::compute(vartype, engine); if (!vartype.isObjectType()) return InvalidInitialization; const Class dest_class = engine->typeSystem()->getClass(vartype); std::vector<Initialization> inits; inits.resize(init_list.elements.size()); /// TODO: check all initializer_list ctors first // then perform overload resolution on the other ctos if needed for (const auto & ctor : dest_class.constructors()) { if (ctor.prototype().count() == 2 && engine->typeSystem()->isInitializerList(ctor.parameter(1))) return compute_initializer_list_conv(expr, ctor, engine); if (ctor.prototype().count() != init_list.elements.size() + 1) continue; inits.clear(); for (size_t i(0); i < init_list.elements.size(); ++i) { Initialization init = Initialization::compute(ctor.prototype().at(i+1), init_list.elements.at(i), engine); inits.push_back(init); if (!init.isValid()) break; } if (inits.back().isValid()) { Initialization result{ ListInitialization, ctor }; result.initializations() = std::move(inits); return result; } } // TODO : implement aggregate and initializer_list initialization return InvalidInitialization; } } // namespace script
27.048232
141
0.71505
[ "vector" ]
fed8c287404a8304a9bef0c2ea62e270eeb059d7
29,745
cpp
C++
core/variant_parser.cpp
KwesiDavis/godot
2cc60386d83d06e3b2005f0d2e3094eebfb9e382
[ "CC-BY-3.0", "MIT" ]
1
2020-06-13T05:57:51.000Z
2020-06-13T05:57:51.000Z
core/variant_parser.cpp
vision-kwest/godot-mirror
2cc60386d83d06e3b2005f0d2e3094eebfb9e382
[ "CC-BY-3.0", "MIT" ]
null
null
null
core/variant_parser.cpp
vision-kwest/godot-mirror
2cc60386d83d06e3b2005f0d2e3094eebfb9e382
[ "CC-BY-3.0", "MIT" ]
null
null
null
#include "variant_parser.h" #include "io/resource_loader.h" #include "os/keyboard.h" CharType VariantParser::StreamFile::get_char() { return f->get_8(); } bool VariantParser::StreamFile::is_utf8() const { return true; } bool VariantParser::StreamFile::is_eof() const { return f->eof_reached(); } ///////////////////////////////////////////////////////////////////////////////////////////////// const char * VariantParser::tk_name[TK_MAX] = { "'{'", "'}'", "'['", "']'", "'('", "')'", "identifier", "string", "number", "':'", "','", "'='", "EOF", "ERROR" }; Error VariantParser::get_token(Stream *p_stream, Token& r_token, int &line, String &r_err_str) { while (true) { CharType cchar; if (p_stream->saved) { cchar=p_stream->saved; p_stream->saved=0; } else { cchar=p_stream->get_char(); if (p_stream->is_eof()) { r_token.type=TK_EOF; return OK; } } switch(cchar) { case '\n': { line++; break; }; case 0: { r_token.type=TK_EOF; return OK; } break; case '{': { r_token.type=TK_CURLY_BRACKET_OPEN; return OK; }; case '}': { r_token.type=TK_CURLY_BRACKET_CLOSE; return OK; }; case '[': { r_token.type=TK_BRACKET_OPEN; return OK; }; case ']': { r_token.type=TK_BRACKET_CLOSE; return OK; }; case '(': { r_token.type=TK_PARENTHESIS_OPEN; return OK; }; case ')': { r_token.type=TK_PARENTHESIS_CLOSE; return OK; }; case ':': { r_token.type=TK_COLON; return OK; }; case ',': { r_token.type=TK_COMMA; return OK; }; case '=': { r_token.type=TK_EQUAL; return OK; }; case '"': { String str; while(true) { CharType ch=p_stream->get_char(); if (ch==0) { r_err_str="Unterminated String"; r_token.type=TK_ERROR; return ERR_PARSE_ERROR; } else if (ch=='"') { break; } else if (ch=='\\') { //escaped characters... CharType next = p_stream->get_char(); if (next==0) { r_err_str="Unterminated String"; r_token.type=TK_ERROR; return ERR_PARSE_ERROR; } CharType res=0; switch(next) { case 'b': res=8; break; case 't': res=9; break; case 'n': res=10; break; case 'f': res=12; break; case 'r': res=13; break; case 'u': { //hexnumbarh - oct is deprecated for(int j=0;j<4;j++) { CharType c = p_stream->get_char(); if (c==0) { r_err_str="Unterminated String"; r_token.type=TK_ERROR; return ERR_PARSE_ERROR; } if (!((c>='0' && c<='9') || (c>='a' && c<='f') || (c>='A' && c<='F'))) { r_err_str="Malformed hex constant in string"; r_token.type=TK_ERROR; return ERR_PARSE_ERROR; } CharType v; if (c>='0' && c<='9') { v=c-'0'; } else if (c>='a' && c<='f') { v=c-'a'; v+=10; } else if (c>='A' && c<='F') { v=c-'A'; v+=10; } else { ERR_PRINT("BUG"); v=0; } res<<=4; res|=v; } } break; //case '\"': res='\"'; break; //case '\\': res='\\'; break; //case '/': res='/'; break; default: { res = next; //r_err_str="Invalid escape sequence"; //return ERR_PARSE_ERROR; } break; } str+=res; } else { if (ch=='\n') line++; str+=ch; } } if (p_stream->is_utf8()) { str.parse_utf8( str.ascii(true).get_data() ); } r_token.type=TK_STRING; r_token.value=str; return OK; } break; default: { if (cchar<=32) { break; } if (cchar=='-' || (cchar>='0' && cchar<='9')) { //a number String num; #define READING_SIGN 0 #define READING_INT 1 #define READING_DEC 2 #define READING_EXP 3 #define READING_DONE 4 int reading=READING_INT; if (cchar=='-') { num+='-'; cchar=p_stream->get_char(); } CharType c = cchar; bool exp_sign=false; bool exp_beg=false; bool is_float=false; while(true) { switch(reading) { case READING_INT: { if (c>='0' && c<='9') { //pass } else if (c=='.') { reading=READING_DEC; is_float=true; } else if (c=='e') { reading=READING_EXP; } else { reading=READING_DONE; } } break; case READING_DEC: { if (c>='0' && c<='9') { } else if (c=='e') { reading=READING_EXP; } else { reading=READING_DONE; } } break; case READING_EXP: { if (c>='0' && c<='9') { exp_beg=true; } else if ((c=='-' || c=='+') && !exp_sign && !exp_beg) { exp_sign=true; } else { reading=READING_DONE; } } break; } if (reading==READING_DONE) break; num+=String::chr(c); c = p_stream->get_char(); } p_stream->saved=c; r_token.type=TK_NUMBER; if (is_float) r_token.value=num.to_double(); else r_token.value=num.to_int(); return OK; } else if ((cchar>='A' && cchar<='Z') || (cchar>='a' && cchar<='z') || cchar=='_') { String id; bool first=true; while((cchar>='A' && cchar<='Z') || (cchar>='a' && cchar<='z') || cchar=='_' || (!first && cchar>='0' && cchar<='9')) { id+=String::chr(cchar); cchar=p_stream->get_char(); first=false; } p_stream->saved=cchar; r_token.type=TK_IDENTIFIER; r_token.value=id; return OK; } else { r_err_str="Unexpected character."; r_token.type=TK_ERROR; return ERR_PARSE_ERROR; } } } } r_token.type=TK_ERROR; return ERR_PARSE_ERROR; } template<class T> Error VariantParser::_parse_construct(Stream *p_stream,Vector<T>& r_construct,int &line,String &r_err_str) { Token token; get_token(p_stream,token,line,r_err_str); if (token.type!=TK_PARENTHESIS_OPEN) { r_err_str="Expected '(' in constructor"; return ERR_PARSE_ERROR; } bool first=true; while(true) { if (!first) { get_token(p_stream,token,line,r_err_str); if (token.type==TK_COMMA) { //do none } else if (token.type==TK_PARENTHESIS_CLOSE) { break; } else { r_err_str="Expected ',' or ')' in constructor"; return ERR_PARSE_ERROR; } } get_token(p_stream,token,line,r_err_str); if (token.type!=TK_NUMBER) { r_err_str="Expected float in constructor"; return ERR_PARSE_ERROR; } r_construct.push_back(token.value); first=false; } return OK; } Error VariantParser::parse_value(Token& token,Variant &value,Stream *p_stream,int &line,String &r_err_str,ResourceParser *p_res_parser) { /* { Error err = get_token(p_stream,token,line,r_err_str); if (err) return err; }*/ if (token.type==TK_CURLY_BRACKET_OPEN) { Dictionary d; Error err = _parse_dictionary(d,p_stream,line,r_err_str,p_res_parser); if (err) return err; value=d; return OK; } else if (token.type==TK_BRACKET_OPEN) { Array a; Error err = _parse_array(a,p_stream,line,r_err_str,p_res_parser); if (err) return err; value=a; return OK; } else if (token.type==TK_IDENTIFIER) { /* VECTOR2, // 5 RECT2, VECTOR3, MATRIX32, PLANE, QUAT, // 10 _AABB, //sorry naming convention fail :( not like it's used often MATRIX3, TRANSFORM, // misc types COLOR, IMAGE, // 15 NODE_PATH, _RID, OBJECT, INPUT_EVENT, DICTIONARY, // 20 ARRAY, // arrays RAW_ARRAY, INT_ARRAY, REAL_ARRAY, STRING_ARRAY, // 25 VECTOR2_ARRAY, VECTOR3_ARRAY, COLOR_ARRAY, VARIANT_MAX */ String id = token.value; if (id=="true") value=true; else if (id=="false") value=false; else if (id=="null") value=Variant(); else if (id=="Vector2"){ Vector<float> args; Error err = _parse_construct<float>(p_stream,args,line,r_err_str); if (err) return err; if (args.size()!=2) { r_err_str="Expected 2 arguments for constructor"; } value=Vector2(args[0],args[1]); return OK; } else if (id=="Vector3"){ Vector<float> args; Error err = _parse_construct<float>(p_stream,args,line,r_err_str); if (err) return err; if (args.size()!=3) { r_err_str="Expected 3 arguments for constructor"; } value=Vector3(args[0],args[1],args[2]); return OK; } else if (id=="Matrix32"){ Vector<float> args; Error err = _parse_construct<float>(p_stream,args,line,r_err_str); if (err) return err; if (args.size()!=6) { r_err_str="Expected 6 arguments for constructor"; } Matrix32 m; m[0]=Vector2(args[0],args[1]); m[1]=Vector2(args[2],args[3]); m[2]=Vector2(args[4],args[5]); value=m; return OK; } else if (id=="Plane") { Vector<float> args; Error err = _parse_construct<float>(p_stream,args,line,r_err_str); if (err) return err; if (args.size()!=4) { r_err_str="Expected 4 arguments for constructor"; } value=Plane(args[0],args[1],args[2],args[3]); return OK; } else if (id=="Quat") { Vector<float> args; Error err = _parse_construct<float>(p_stream,args,line,r_err_str); if (err) return err; if (args.size()!=4) { r_err_str="Expected 4 arguments for constructor"; } value=Quat(args[0],args[1],args[2],args[3]); return OK; } else if (id=="AABB"){ Vector<float> args; Error err = _parse_construct<float>(p_stream,args,line,r_err_str); if (err) return err; if (args.size()!=6) { r_err_str="Expected 6 arguments for constructor"; } value=AABB(Vector3(args[0],args[1],args[2]),Vector3(args[3],args[4],args[5])); return OK; } else if (id=="Matrix3"){ Vector<float> args; Error err = _parse_construct<float>(p_stream,args,line,r_err_str); if (err) return err; if (args.size()!=9) { r_err_str="Expected 9 arguments for constructor"; } value=Matrix3(args[0],args[1],args[2],args[3],args[4],args[5],args[6],args[7],args[8]); return OK; } else if (id=="Transform"){ Vector<float> args; Error err = _parse_construct<float>(p_stream,args,line,r_err_str); if (err) return err; if (args.size()!=12) { r_err_str="Expected 12 arguments for constructor"; } value=Transform(Matrix3(args[0],args[1],args[2],args[3],args[4],args[5],args[6],args[7],args[8]),Vector3(args[9],args[10],args[11])); return OK; } else if (id=="Color") { Vector<float> args; Error err = _parse_construct<float>(p_stream,args,line,r_err_str); if (err) return err; if (args.size()!=4) { r_err_str="Expected 4 arguments for constructor"; } value=Color(args[0],args[1],args[2],args[3]); return OK; } else if (id=="Image") { //:| get_token(p_stream,token,line,r_err_str); if (token.type!=TK_PARENTHESIS_OPEN) { r_err_str="Expected '('"; return ERR_PARSE_ERROR; } get_token(p_stream,token,line,r_err_str); if (token.type==TK_PARENTHESIS_CLOSE) { value=Image(); // just an Image() return OK; } else if (token.type!=TK_NUMBER) { r_err_str="Expected number (width)"; return ERR_PARSE_ERROR; } get_token(p_stream,token,line,r_err_str); int width=token.value; if (token.type!=TK_COMMA) { r_err_str="Expected ','"; return ERR_PARSE_ERROR; } get_token(p_stream,token,line,r_err_str); if (token.type!=TK_NUMBER) { r_err_str="Expected number (height)"; return ERR_PARSE_ERROR; } int height=token.value; get_token(p_stream,token,line,r_err_str); if (token.type!=TK_COMMA) { r_err_str="Expected ','"; return ERR_PARSE_ERROR; } get_token(p_stream,token,line,r_err_str); if (token.type!=TK_NUMBER) { r_err_str="Expected number (mipmaps)"; return ERR_PARSE_ERROR; } int mipmaps=token.value; get_token(p_stream,token,line,r_err_str); if (token.type!=TK_COMMA) { r_err_str="Expected ','"; return ERR_PARSE_ERROR; } get_token(p_stream,token,line,r_err_str); if (token.type!=TK_IDENTIFIER) { r_err_str="Expected identifier (format)"; return ERR_PARSE_ERROR; } String sformat=token.value; Image::Format format; if (sformat=="GRAYSCALE") format=Image::FORMAT_GRAYSCALE; else if (sformat=="INTENSITY") format=Image::FORMAT_INTENSITY; else if (sformat=="GRAYSCALE_ALPHA") format=Image::FORMAT_GRAYSCALE_ALPHA; else if (sformat=="RGB") format=Image::FORMAT_RGB; else if (sformat=="RGBA") format=Image::FORMAT_RGBA; else if (sformat=="INDEXED") format=Image::FORMAT_INDEXED; else if (sformat=="INDEXED_ALPHA") format=Image::FORMAT_INDEXED_ALPHA; else if (sformat=="BC1") format=Image::FORMAT_BC1; else if (sformat=="BC2") format=Image::FORMAT_BC2; else if (sformat=="BC3") format=Image::FORMAT_BC3; else if (sformat=="BC4") format=Image::FORMAT_BC4; else if (sformat=="BC5") format=Image::FORMAT_BC5; else if (sformat=="PVRTC2") format=Image::FORMAT_PVRTC2; else if (sformat=="PVRTC2_ALPHA") format=Image::FORMAT_PVRTC2_ALPHA; else if (sformat=="PVRTC4") format=Image::FORMAT_PVRTC4; else if (sformat=="PVRTC4_ALPHA") format=Image::FORMAT_PVRTC4_ALPHA; else if (sformat=="ATC") format=Image::FORMAT_ATC; else if (sformat=="ATC_ALPHA_EXPLICIT") format=Image::FORMAT_ATC_ALPHA_EXPLICIT; else if (sformat=="ATC_ALPHA_INTERPOLATED") format=Image::FORMAT_ATC_ALPHA_INTERPOLATED; else if (sformat=="CUSTOM") format=Image::FORMAT_CUSTOM; else { r_err_str="Invalid image format: '"+sformat+"'"; return ERR_PARSE_ERROR; }; int len = Image::get_image_data_size(width,height,format,mipmaps); DVector<uint8_t> buffer; buffer.resize(len); if (buffer.size()!=len) { r_err_str="Couldn't allocate image buffer of size: "+itos(len); } { DVector<uint8_t>::Write w=buffer.write(); for(int i=0;i<len;i++) { get_token(p_stream,token,line,r_err_str); if (token.type!=TK_COMMA) { r_err_str="Expected ','"; return ERR_PARSE_ERROR; } get_token(p_stream,token,line,r_err_str); if (token.type!=TK_NUMBER) { r_err_str="Expected number"; return ERR_PARSE_ERROR; } w[i]=int(token.value); } } Image img(width,height,mipmaps,format,buffer); value=img; return OK; } else if (id=="NodePath") { get_token(p_stream,token,line,r_err_str); if (token.type!=TK_PARENTHESIS_OPEN) { r_err_str="Expected '('"; return ERR_PARSE_ERROR; } get_token(p_stream,token,line,r_err_str); if (token.type!=TK_STRING) { r_err_str="Expected string as argument for NodePath()"; return ERR_PARSE_ERROR; } value=NodePath(String(token.value)); get_token(p_stream,token,line,r_err_str); if (token.type!=TK_PARENTHESIS_CLOSE) { r_err_str="Expected ')'"; return ERR_PARSE_ERROR; } } else if (id=="RID") { get_token(p_stream,token,line,r_err_str); if (token.type!=TK_PARENTHESIS_OPEN) { r_err_str="Expected '('"; return ERR_PARSE_ERROR; } get_token(p_stream,token,line,r_err_str); if (token.type!=TK_NUMBER) { r_err_str="Expected number as argument"; return ERR_PARSE_ERROR; } value=token.value; get_token(p_stream,token,line,r_err_str); if (token.type!=TK_PARENTHESIS_CLOSE) { r_err_str="Expected ')'"; return ERR_PARSE_ERROR; } return OK; } else if (id=="Resource" || id=="SubResource" || id=="ExtResource") { get_token(p_stream,token,line,r_err_str); if (token.type!=TK_PARENTHESIS_OPEN) { r_err_str="Expected '('"; return ERR_PARSE_ERROR; } if (p_res_parser && id=="Resource" && p_res_parser->func){ RES res; Error err = p_res_parser->func(p_res_parser->userdata,p_stream,res,line,r_err_str); if (err) return err; value=res; return OK; } else if (p_res_parser && id=="ExtResource" && p_res_parser->ext_func){ RES res; Error err = p_res_parser->ext_func(p_res_parser->userdata,p_stream,res,line,r_err_str); if (err) return err; value=res; return OK; } else if (p_res_parser && id=="SubResource" && p_res_parser->sub_func){ RES res; Error err = p_res_parser->sub_func(p_res_parser->userdata,p_stream,res,line,r_err_str); if (err) return err; value=res; return OK; } else { get_token(p_stream,token,line,r_err_str); if (token.type==TK_STRING) { String path=token.value; RES res = ResourceLoader::load(path); if (res.is_null()) { r_err_str="Can't load resource at path: '"+path+"'."; return ERR_PARSE_ERROR; } get_token(p_stream,token,line,r_err_str); if (token.type!=TK_PARENTHESIS_CLOSE) { r_err_str="Expected ')'"; return ERR_PARSE_ERROR; } value=res; return OK; } else { r_err_str="Expected string as argument for Resource()."; return ERR_PARSE_ERROR; } } return OK; } else if (id=="InputEvent") { get_token(p_stream,token,line,r_err_str); if (token.type!=TK_PARENTHESIS_OPEN) { r_err_str="Expected '('"; return ERR_PARSE_ERROR; } get_token(p_stream,token,line,r_err_str); if (token.type!=TK_IDENTIFIER) { r_err_str="Expected identifier"; return ERR_PARSE_ERROR; } String id = token.value; InputEvent ie; if (id=="KEY") { get_token(p_stream,token,line,r_err_str); if (token.type!=TK_COMMA) { r_err_str="Expected ','"; return ERR_PARSE_ERROR; } ie.type=InputEvent::KEY; get_token(p_stream,token,line,r_err_str); if (token.type==TK_IDENTIFIER) { String name=token.value; ie.key.scancode=find_keycode(name); } else if (token.type==TK_NUMBER) { ie.key.scancode=token.value; } else { r_err_str="Expected string or integer for keycode"; return ERR_PARSE_ERROR; } get_token(p_stream,token,line,r_err_str); if (token.type==TK_COMMA) { get_token(p_stream,token,line,r_err_str); if (token.type!=TK_IDENTIFIER) { r_err_str="Expected identifier with modifier flas"; return ERR_PARSE_ERROR; } String mods=token.value; if (mods.findn("C")!=-1) ie.key.mod.control=true; if (mods.findn("A")!=-1) ie.key.mod.alt=true; if (mods.findn("S")!=-1) ie.key.mod.shift=true; if (mods.findn("M")!=-1) ie.key.mod.meta=true; get_token(p_stream,token,line,r_err_str); if (token.type!=TK_PARENTHESIS_CLOSE) { r_err_str="Expected ')'"; return ERR_PARSE_ERROR; } } else if (token.type!=TK_PARENTHESIS_CLOSE) { r_err_str="Expected ')' or modifier flags."; return ERR_PARSE_ERROR; } } else if (id=="MBUTTON") { get_token(p_stream,token,line,r_err_str); if (token.type!=TK_COMMA) { r_err_str="Expected ','"; return ERR_PARSE_ERROR; } ie.type=InputEvent::MOUSE_BUTTON; get_token(p_stream,token,line,r_err_str); if (token.type!=TK_NUMBER) { r_err_str="Expected button index"; return ERR_PARSE_ERROR; } ie.mouse_button.button_index = token.value; get_token(p_stream,token,line,r_err_str); if (token.type!=TK_PARENTHESIS_CLOSE) { r_err_str="Expected ')'"; return ERR_PARSE_ERROR; } } else if (id=="JBUTTON") { get_token(p_stream,token,line,r_err_str); if (token.type!=TK_COMMA) { r_err_str="Expected ','"; return ERR_PARSE_ERROR; } ie.type=InputEvent::JOYSTICK_BUTTON; get_token(p_stream,token,line,r_err_str); if (token.type!=TK_NUMBER) { r_err_str="Expected button index"; return ERR_PARSE_ERROR; } ie.joy_button.button_index = token.value; get_token(p_stream,token,line,r_err_str); if (token.type!=TK_PARENTHESIS_CLOSE) { r_err_str="Expected ')'"; return ERR_PARSE_ERROR; } } else if (id=="JAXIS") { get_token(p_stream,token,line,r_err_str); if (token.type!=TK_COMMA) { r_err_str="Expected ','"; return ERR_PARSE_ERROR; } ie.type=InputEvent::JOYSTICK_MOTION; get_token(p_stream,token,line,r_err_str); if (token.type!=TK_NUMBER) { r_err_str="Expected axis index"; return ERR_PARSE_ERROR; } ie.joy_motion.axis = token.value; get_token(p_stream,token,line,r_err_str); if (token.type!=TK_PARENTHESIS_CLOSE) { r_err_str="Expected ')'"; return ERR_PARSE_ERROR; } } else { r_err_str="Invalid input event type."; return ERR_PARSE_ERROR; } value=ie; return OK; } else if (id=="ByteArray") { Vector<uint8_t> args; Error err = _parse_construct<uint8_t>(p_stream,args,line,r_err_str); if (err) return err; DVector<uint8_t> arr; { int len=args.size(); arr.resize(len); DVector<uint8_t>::Write w = arr.write(); for(int i=0;i<len;i++) { w[i]=args[i]; } } value=arr; return OK; } else if (id=="IntArray") { Vector<int32_t> args; Error err = _parse_construct<int32_t>(p_stream,args,line,r_err_str); if (err) return err; DVector<int32_t> arr; { int len=args.size(); arr.resize(len); DVector<int32_t>::Write w = arr.write(); for(int i=0;i<len;i++) { w[i]=int(args[i]); } } value=arr; return OK; } else if (id=="FloatArray") { Vector<float> args; Error err = _parse_construct<float>(p_stream,args,line,r_err_str); if (err) return err; DVector<float> arr; { int len=args.size(); arr.resize(len); DVector<float>::Write w = arr.write(); for(int i=0;i<len;i++) { w[i]=args[i]; } } value=arr; return OK; } else if (id=="StringArray") { get_token(p_stream,token,line,r_err_str); if (token.type!=TK_PARENTHESIS_OPEN) { r_err_str="Expected '('"; return ERR_PARSE_ERROR; } Vector<String> cs; bool first=true; while(true) { if (!first) { get_token(p_stream,token,line,r_err_str); if (token.type==TK_COMMA) { //do none } else if (token.type!=TK_PARENTHESIS_CLOSE) { break; } else { r_err_str="Expected ',' or ')'"; return ERR_PARSE_ERROR; } } get_token(p_stream,token,line,r_err_str); if (token.type!=TK_STRING) { r_err_str="Expected string"; return ERR_PARSE_ERROR; } cs.push_back(token.value); } DVector<String> arr; { int len=cs.size(); arr.resize(len); DVector<String>::Write w = arr.write(); for(int i=0;i<len;i++) { w[i]=cs[i]; } } value=arr; return OK; } else if (id=="Vector2Array") { Vector<float> args; Error err = _parse_construct<float>(p_stream,args,line,r_err_str); if (err) return err; DVector<Vector2> arr; { int len=args.size()/2; arr.resize(len); DVector<Vector2>::Write w = arr.write(); for(int i=0;i<len;i++) { w[i]=Vector2(args[i*2+0],args[i*2+1]); } } value=arr; return OK; } else if (id=="Vector3Array") { Vector<float> args; Error err = _parse_construct<float>(p_stream,args,line,r_err_str); if (err) return err; DVector<Vector3> arr; { int len=args.size()/3; arr.resize(len); DVector<Vector3>::Write w = arr.write(); for(int i=0;i<len;i++) { w[i]=Vector3(args[i*3+0],args[i*3+1],args[i*3+2]); } } value=arr; return OK; } else if (id=="ColorArray") { Vector<float> args; Error err = _parse_construct<float>(p_stream,args,line,r_err_str); if (err) return err; DVector<Color> arr; { int len=args.size()/4; arr.resize(len); DVector<Color>::Write w = arr.write(); for(int i=0;i<len;i++) { w[i]=Color(args[i*3+0],args[i*3+1],args[i*3+2],args[i*3+3]); } } value=arr; return OK; } else { r_err_str="Unexpected identifier: '"+id+"'."; return ERR_PARSE_ERROR; } /* VECTOR2, // 5 RECT2, VECTOR3, MATRIX32, PLANE, QUAT, // 10 _AABB, //sorry naming convention fail :( not like it's used often MATRIX3, TRANSFORM, // misc types COLOR, IMAGE, // 15 NODE_PATH, _RID, OBJECT, INPUT_EVENT, DICTIONARY, // 20 ARRAY, // arrays RAW_ARRAY, INT_ARRAY, REAL_ARRAY, STRING_ARRAY, // 25 VECTOR2_ARRAY, VECTOR3_ARRAY, COLOR_ARRAY, VARIANT_MAX */ return OK; } else if (token.type==TK_NUMBER) { value=token.value; return OK; } else if (token.type==TK_STRING) { value=token.value; return OK; } else { r_err_str="Expected value, got "+String(tk_name[token.type])+"."; return ERR_PARSE_ERROR; } return ERR_PARSE_ERROR; } Error VariantParser::_parse_array(Array &array, Stream *p_stream, int &line, String &r_err_str, ResourceParser *p_res_parser) { Token token; bool need_comma=false; while(true) { if (p_stream->is_eof()) { r_err_str="Unexpected End of File while parsing array"; return ERR_FILE_CORRUPT; } Error err = get_token(p_stream,token,line,r_err_str); if (err!=OK) return err; if (token.type==TK_BRACKET_CLOSE) { return OK; } if (need_comma) { if (token.type!=TK_COMMA) { r_err_str="Expected ','"; return ERR_PARSE_ERROR; } else { need_comma=false; continue; } } Variant v; err = parse_value(token,v,p_stream,line,r_err_str,p_res_parser); if (err) return err; array.push_back(v); need_comma=true; } return OK; } Error VariantParser::_parse_dictionary(Dictionary &object, Stream *p_stream, int &line, String &r_err_str, ResourceParser *p_res_parser) { bool at_key=true; Variant key; Token token; bool need_comma=false; while(true) { if (p_stream->is_eof()) { r_err_str="Unexpected End of File while parsing dictionary"; return ERR_FILE_CORRUPT; } if (at_key) { Error err = get_token(p_stream,token,line,r_err_str); if (err!=OK) return err; if (token.type==TK_CURLY_BRACKET_CLOSE) { return OK; } if (need_comma) { if (token.type!=TK_COMMA) { r_err_str="Expected '}' or ','"; return ERR_PARSE_ERROR; } else { need_comma=false; continue; } } err = parse_value(token,key,p_stream,line,r_err_str,p_res_parser); if (err) return err; err = get_token(p_stream,token,line,r_err_str); if (err!=OK) return err; if (token.type!=TK_COLON) { r_err_str="Expected ':'"; return ERR_PARSE_ERROR; } at_key=false; } else { Error err = get_token(p_stream,token,line,r_err_str); if (err!=OK) return err; Variant v; err = parse_value(token,v,p_stream,line,r_err_str,p_res_parser); if (err) return err; object[key]=v; need_comma=true; at_key=true; } } return OK; } Error VariantParser::_parse_tag(Token& token, Stream *p_stream, int &line, String &r_err_str, Tag& r_tag, ResourceParser *p_res_parser) { r_tag.fields.clear(); if (token.type!=TK_BRACKET_OPEN) { r_err_str="Expected '['"; return ERR_PARSE_ERROR; } get_token(p_stream,token,line,r_err_str); if (token.type!=TK_IDENTIFIER) { r_err_str="Expected identifier (tag name)"; return ERR_PARSE_ERROR; } r_tag.name=token.value; while(true) { if (p_stream->is_eof()) { r_err_str="Unexpected End of File while parsing tag: "+r_tag.name; return ERR_FILE_CORRUPT; } get_token(p_stream,token,line,r_err_str); if (token.type==TK_BRACKET_CLOSE) break; if (token.type!=TK_IDENTIFIER) { r_err_str="Expected Identifier"; return ERR_PARSE_ERROR; } String id=token.value; get_token(p_stream,token,line,r_err_str); if (token.type!=TK_EQUAL) { r_err_str="Expected '='"; return ERR_PARSE_ERROR; } get_token(p_stream,token,line,r_err_str); Variant value; Error err = parse_value(token,value,p_stream,line,r_err_str,p_res_parser); if (err) return err; r_tag.fields[id]=value; } return OK; } Error VariantParser::parse_tag(Stream *p_stream, int &line, String &r_err_str, Tag& r_tag, ResourceParser *p_res_parser) { Token token; get_token(p_stream,token,line,r_err_str); if (token.type==TK_EOF) { return ERR_FILE_EOF; } if (token.type!=TK_BRACKET_OPEN) { r_err_str="Expected '['"; return ERR_PARSE_ERROR; } return _parse_tag(token,p_stream,line,r_err_str,r_tag,p_res_parser); } Error VariantParser::parse_tag_assign_eof(Stream *p_stream, int &line, String &r_err_str, Tag& r_tag, String &r_assign, Variant &r_value, ResourceParser *p_res_parser) { //assign.. String what; while(true) { CharType c; if (p_stream->saved) { c=p_stream->saved; p_stream->saved=0; } else { c=p_stream->get_char(); } if (p_stream->is_eof()) return ERR_FILE_EOF; if (c=='[' && what.length()==0) { //it's a tag! p_stream->saved='['; //go back one Error err = parse_tag(p_stream,line,r_err_str,r_tag,p_res_parser); return err; } if (c>32) { if (c!='=') { what+=String::chr(c); } else { r_assign=what; Token token; get_token(p_stream,token,line,r_err_str); Error err = parse_value(token,r_value,p_stream,line,r_err_str,p_res_parser); if (err) { } return err; } } else if (c=='\n') { line++; } } return OK; } Error VariantParser::parse(Stream *p_stream, Variant& r_ret, String &r_err_str, int &r_err_line, ResourceParser *p_res_parser) { Token token; Error err = get_token(p_stream,token,r_err_line,r_err_str); if (err) return err; if (token.type==TK_EOF) { return ERR_FILE_EOF; } return parse_value(token,r_ret,p_stream,r_err_line,r_err_str,p_res_parser); }
19.883021
169
0.610926
[ "object", "vector", "transform" ]
fedc12105ec43c51504f45f02f545b2bd0687b01
2,094
cpp
C++
examples/nn/4_NLP/5_sentiment_rnn_all.cpp
ilveroluca/eddl
02e37c0dfb674468495f4d0ae3c159de3b2d3cc0
[ "MIT" ]
null
null
null
examples/nn/4_NLP/5_sentiment_rnn_all.cpp
ilveroluca/eddl
02e37c0dfb674468495f4d0ae3c159de3b2d3cc0
[ "MIT" ]
null
null
null
examples/nn/4_NLP/5_sentiment_rnn_all.cpp
ilveroluca/eddl
02e37c0dfb674468495f4d0ae3c159de3b2d3cc0
[ "MIT" ]
null
null
null
/* * EDDL Library - European Distributed Deep Learning Library. * Version: 0.6 * copyright (c) 2020, Universidad Politécnica de Valencia (UPV), PRHLT Research Centre * Date: April 2020 * Author: PRHLT Research Centre, UPV, (rparedes@prhlt.upv.es), (jon@prhlt.upv.es) * All rights reserved */ #include <cstdio> #include <cstdlib> #include <iostream> #include "eddl/apis/eddl.h" using namespace eddl; ////////////////////////////////// // Embeding+RNN for // aclImdb sentiment analysis // using all vocabulary ////////////////////////////////// int main(int argc, char **argv) { // Download aclImdb download_imdb(); // Settings int epochs = 1000; int batch_size = 100; int num_classes = 2; int length=100; int embdim=250; int vocsize=72682; // Define network layer in = Input({1}); //1 word layer l = in; layer lE = Embedding(l, vocsize, 1,embdim,true); //mask_zeros=true l = LSTM(lE,512); l = LeakyReLu(BatchNormalization(Dense(l,128)),false); layer out = Softmax(Dense(l, num_classes)); model net = Model({in}, {out}); // dot from graphviz should be installed: plot(net, "model.pdf"); optimizer opt=rmsprop(0.0001); //opt->set_clip_val(0.01); // Build model build(net, opt, // Optimizer {"soft_cross_entropy"}, // Losses {"categorical_accuracy"}, // Metrics CS_GPU({1}) // one GPU //CS_GPU({1,1},100) // two GPU with weight sync every 100 batches //CS_CPU() ); // View model summary(net); // Load dataset Tensor* x_train=Tensor::load("imdb_trX.bin"); Tensor* y_train=Tensor::load("imdb_trY.bin"); Tensor* x_test=Tensor::load("imdb_tsX.bin"); Tensor* y_test=Tensor::load("imdb_tsY.bin"); x_train->reshape_({x_train->shape[0],length,1}); //batch x timesteps x input_dim x_test->reshape_({x_test->shape[0],length,1}); //batch x timesteps x input_dim for(int i=0;i<epochs;i++) { fit(net, {x_train}, {y_train}, batch_size, 5); evaluate(net,{x_test},{y_test}); } }
24.068966
86
0.606017
[ "shape", "model" ]
fedc1aef2c0e2deffc9c4d820a98471eb6eb074a
715
cpp
C++
G/Maximum_Time/main.cpp
camelboat/LeetCode_Archive
c29d263e068752a9ad355925f326b56f672bb584
[ "MIT" ]
3
2019-09-21T16:25:44.000Z
2021-08-29T20:43:57.000Z
G/Maximum_Time/main.cpp
camelboat/LeetCode_Archive
c29d263e068752a9ad355925f326b56f672bb584
[ "MIT" ]
null
null
null
G/Maximum_Time/main.cpp
camelboat/LeetCode_Archive
c29d263e068752a9ad355925f326b56f672bb584
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; class Solution { public: string maximum_time(string s) { string answer; answer+= s[0]=='?' ? (s[1] > '3' && s[1] != '?' ? '1' : '2') : s[0]; answer+= s[1]=='?' ? (answer[0] == '2' ? '3' : '9') : s[1]; answer+=":"; answer+= s[3]=='?' ? '5' : s[3]; answer+= s[4]=='?' ? '9' : s[4]; return answer; } }; int main() { Solution test; cout << test.maximum_time("?4:59") << '\n'; cout << test.maximum_time("23:5?") << '\n'; cout << test.maximum_time("2?:22") << '\n'; cout << test.maximum_time("0?:??") << '\n'; cout << test.maximum_time("??:??") << '\n'; return 0; }
23.833333
76
0.446154
[ "vector" ]
fedf466bf79def67fe98c4823386ee2c834ea4ec
6,132
hxx
C++
examples/IFServer.hxx
kb1vc/SoDaRadio
0a41fa3d795b1c93795ad62ad17bf2de5f60a752
[ "BSD-2-Clause" ]
14
2017-10-27T16:01:05.000Z
2021-03-16T08:12:42.000Z
examples/IFServer.hxx
dd0vs/SoDaRadio
0a41fa3d795b1c93795ad62ad17bf2de5f60a752
[ "BSD-2-Clause" ]
11
2017-09-16T03:13:11.000Z
2020-12-11T09:11:35.000Z
examples/IFServer.hxx
dd0vs/SoDaRadio
0a41fa3d795b1c93795ad62ad17bf2de5f60a752
[ "BSD-2-Clause" ]
6
2017-09-13T12:47:43.000Z
2020-12-02T20:54:25.000Z
/* Copyright (c) 2020 Matthew H. Reilly (kb1vc) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef SODA_IF_SERVER_HDR #define SODA_IF_SERVER_HDR #include <SoDaRadio/SoDaBase.hxx> #include <SoDaRadio/SoDaThread.hxx> #include <SoDaRadio/UDSockets.hxx> /** * @file IFServer.hxx * * IFServer is an example of a simple "plugin" that may be * built as a shareable library and then loaded into SoDaRadio * via the loadable plugin interface. * * Plugins may be loaded by setting an environment variable * "SODA_LOAD_LIBS" or by providing the "--load" option to * the SoDaServer. * * For instance, once this plugin has been built, it will be loaded * by this command: * ~~~ $ SoDaRadio --serverargs "--load libIFServer.so" ~~~ * * or, using an environment variable instead: * ~~~ $ export SODA_LOAD_LIBS=libIFServer.so $ SoDaRadio ~~~ * * User developed plugins may find this a useful starting point. * * @author Matt Reilly (kb1vc) * */ /** * @class IFServer * * This is a thread that subscribes to the SoDaRadio command and * IF streams. It listens for new IF buffers from the RX thread, * and makes them available on a unix domain socket called "IFServer" * and located in the directory from which SoDaRadio was started. * * Each block is of the form: * * uint32 buffer_length (bytes) * double center * complex<float> [buffer_length] */ class IFServer : public SoDa::Thread { public: /** * @brief create the plugin thread instance. * * This will register the plugin with the thread registrar and make the * server process aware of the plugin's existence. * * @param name This is a convenience name used in error reports and * debugging aids. It need not be unique or even meaningful. */ IFServer(const std::string & name); /** * @brief connect to useful mailboxes. * * This is a virtual method that should be implemented by * any SoDa::Thread object, as it is the mechanism through * which a thread may subscribe or connect to the data and * command streams. * * The SoDaRadio server will offer each mailbox/stream to * every thread. A thread may subscribe to or ignore the stream. * * @param mbox_name which mailbox are we being offered? * @param mbox_p a pointer to the mailbox we are being offered. */ void subscribeToMailBox(const std::string & mbox_name, SoDa::BaseMBox * mbox_p); /** * @brief This is the method that does the actual work. It is * called by the server for each thread. The thread should not * return from this function until a STOP message arrives on the command * stream. */ void run(); /** * @brief Each thread must implement this method. It provides for * an orderly shutdown of all open connections, or other resources * and processes in a thread. It is *not* necessarily the destructor * for this thread. */ void shutDown(); /** * @brief A thread may implement any or all of the command * execution methods (execRepCommand, execSetCommand, execGetCommand). * * execRepCommand interprets an incoming SoDa::Command where the * SoDa::Command::CmdType is REP (report). Commands of this kind * carry information like "this is my status" or "the current * RX front end tuning frequency is X MHz." * * This plugin listens on the command channel for "STOP" messages * and "RX_FE_FREQ" messages. The former tells the plugin to exit * the run method. The latter tells the plugin that the IF center * frequency has changed to the new RX_FE_FREQ. * * @param cmd a command of type SoDa::Command that includes the * type of command (report, setter, getter), the parameter being * referenced (RX_FE_FREQ, STOP...) and an optional data value. */ void execRepCommand(SoDa::Command * cmd); protected: /** * @brief send a buffer of complex samples to clients connected * to the socket. The buffer is preceded by a buffer length (UI32) * and the current center frequency (double). The buffer itself * is a sequence of complex<float> values. * * @param rxbuf a complex<float> buffer wrapped in a SoDa::Buf object. * @return true if data was sent, false otherwise. */ bool sendBuffer(SoDa::Buf * rxbuf); unsigned int cmd_subs; ///< mailbox subscription ID for command stream SoDa::CmdMBox * cmd_stream; ///< mailbox producing command stream from user unsigned int rx_subs; ///< mailbox subscription ID for command stream SoDa::DatMBox * rx_stream; ///< mailbox producing command stream from user /** * @brief unix domain server socket object. SoDa::UD::ServerSocket * wraps the normal select/read/write/accept/connect interface in a * simple socket object. */ SoDa::UD::ServerSocket * server_socket; double current_rx_center_freq; }; #endif
35.04
82
0.717058
[ "object" ]
fee2f5a946245426e6caefced8e4b8bf5401c391
733
hpp
C++
Wisper/Plugins/CPP/Native/Native/Utilities/Utilities.hpp
yodiwo/plegma
a6fe7735783491fd45769c973d103aec036dde76
[ "Apache-2.0" ]
6
2016-04-25T17:02:31.000Z
2018-02-26T09:38:38.000Z
Wisper/Plugins/CPP/Native/Native/Utilities/Utilities.hpp
yodiwo/plegma
a6fe7735783491fd45769c973d103aec036dde76
[ "Apache-2.0" ]
null
null
null
Wisper/Plugins/CPP/Native/Native/Utilities/Utilities.hpp
yodiwo/plegma
a6fe7735783491fd45769c973d103aec036dde76
[ "Apache-2.0" ]
6
2016-04-25T17:02:36.000Z
2018-11-20T03:46:26.000Z
#pragma once #ifndef YODIWO_UTILITIES_HPP #define YODIWO_UTILITIES_HPP #include <set> #include <regex> #include <tuple> #include <regex> #include <cmath> #include <random> #include <vector> #include <cstdio> #include <thread> #include <fstream> #include <sstream> #include <iomanip> #include <cstring> #include <cstdarg> #include <iterator> #include <iostream> #include <exception> #include <stdexcept> #include <algorithm> #include <functional> #include <type_traits> #include "Macros.hpp" #include "Constants.hpp" #include "Time.hpp" #include "Vector.hpp" #include "String.hpp" #include "Filesystem.hpp" #include "Enumeration.hpp" #include "TraceSystem.hpp" #include "SettingsParser.hpp" #include "GenericException.hpp" #endif
18.325
31
0.754434
[ "vector" ]
fee3825565818cd193b473ca5ea5fc45957e619b
913
cpp
C++
src/code/Library/ScanlineSequencer.cpp
1iyiwei/texture
eaa78c00666060ca0a51c69920031b367c265e7d
[ "MIT" ]
33
2017-04-13T18:32:42.000Z
2021-12-21T07:53:59.000Z
src/code/Library/ScanlineSequencer.cpp
1iyiwei/texture
eaa78c00666060ca0a51c69920031b367c265e7d
[ "MIT" ]
1
2021-09-24T07:21:03.000Z
2021-09-29T23:39:41.000Z
src/code/Library/ScanlineSequencer.cpp
1iyiwei/texture
eaa78c00666060ca0a51c69920031b367c265e7d
[ "MIT" ]
5
2017-04-12T17:46:03.000Z
2021-03-31T00:50:12.000Z
/* ScanlineSequencer.cpp Li-Yi Wei August 17, 2014 */ #include <algorithm> using namespace std; #include "ScanlineSequencer.hpp" #include "Utility.hpp" ScanlineSequencer::ScanlineSequencer(void): _over(true) { // nothing else to do } bool ScanlineSequencer::Reset(const Texture & target) { const int dimension = target.Dimension(); vector<int> min_index = vector<int>(dimension, 0); vector<int> max_index = Utility::Minus1(target.Size()); Reverse(max_index); _over = false; return _counter.Reset(dimension, min_index, max_index); } bool ScanlineSequencer::Next(Position & answer) { if(_over) { return false; } else { _counter.Get(answer); Reverse(answer); _over = !_counter.Next(); return true; } } void ScanlineSequencer::Reverse(Position & position) { reverse(position.begin(), position.end()); }
17.226415
59
0.653888
[ "vector" ]
fee5cad035370b1efbc7fb5748884fbb982127c8
3,093
hpp
C++
Engine/Src/Runtime/RHI/Public/RHI/Pipeline/ShaderProgram.hpp
Septus10/Fade-Engine
285a2a1cf14a4e9c3eb8f6d30785d1239cef10b6
[ "MIT" ]
null
null
null
Engine/Src/Runtime/RHI/Public/RHI/Pipeline/ShaderProgram.hpp
Septus10/Fade-Engine
285a2a1cf14a4e9c3eb8f6d30785d1239cef10b6
[ "MIT" ]
null
null
null
Engine/Src/Runtime/RHI/Public/RHI/Pipeline/ShaderProgram.hpp
Septus10/Fade-Engine
285a2a1cf14a4e9c3eb8f6d30785d1239cef10b6
[ "MIT" ]
null
null
null
#pragma once #include <RHI/RHIApi.hpp> #include <string> #include <unordered_map> #include <Core/Containers/Array.hpp> #include <Core/definitions.hpp> #include <Core/FileWatcher/FileWatcher.h> #include <Core/Math/Math.hpp> namespace Fade { inline namespace RHI { inline namespace Pipeline { namespace Constants { #if (__cplusplus >= 201703L) // If we're C++17 or above inline #endif constexpr i32 gc_ShaderError = -1; }; enum class EShaderType : u8 { Vertex = 0, Fragment = 1, Geometry = 2, Unknown = 3, NUM_SHADERTYPES = 4 }; class FADE_RHI_API CShaderProgram : public FW::FileWatchListener { public: CShaderProgram(); CShaderProgram(std::string a_FolderPath); int LoadShaderProgram(std::string a_FolderPath); void Bind() const; void Unbind() const; i32 GetID() { return m_ProgramID; } //================================================== // Setting uniform values //================================================== // Scalars void SetBoolValue (std::string a_Name, bool a_Value); void SetIntValue (std::string a_Name, i32 a_Value); void SetUintValue (std::string a_Name, u32 a_Value); void SetFloatValue (std::string a_Name, float a_Value); void SetDoubleValue (std::string a_Name, double a_Value); // Vectors // Bool void SetVec(std::string a_Name, Fade::Math::Vec2 a_Vec); void SetVec(std::string a_Name, Fade::Math::Vec3 a_Vec); void SetVec(std::string a_Name, Fade::Math::Vec4 a_Vec); // Signed integer //void SetVec(std::string a_Name, Fade::Math::Vec2 a_Vec); //void SetVec(std::string a_Name, Fade::Math::Vec3 a_Vec); //void SetVec(std::string a_Name, Fade::Math::Vec4 a_Vec); // Unsigned integer //void SetVec(std::string a_Name, Fade::Math::Vec2 a_Vec); //void SetVec(std::string a_Name, Fade::Math::Vec3 a_Vec); //void SetVec(std::string a_Name, Fade::Math::Vec4 a_Vec); // Float //void SetVec(std::string a_Name, Fade::Math::Vec2 a_Vec); //void SetVec(std::string a_Name, Fade::Math::Vec3 a_Vec); //void SetVec(std::string a_Name, Fade::Math::Vec4 a_Vec); // Double //void SetVec(std::string a_Name, Fade::Math::Vec2 a_Vec); //void SetVec(std::string a_Name, Fade::Math::Vec3 a_Vec); //void SetVec(std::string a_Name, Fade::Math::Vec4 a_Vec); // Matrices // Same proportions void SetMat(std::string a_Name, Fade::Math::Mat2 a_Mat); void SetMat(std::string a_Name, Fade::Math::Mat3 a_Mat); void SetMat(std::string a_Name, Fade::Math::Mat4 a_Mat); // Textures //void SetTexture(std::string a_Name, Fade::u32 a_TextureID); i32 GetUniformLocation(std::string a_Name); protected: // FileWatchListener interface virtual void handleFileAction(FW::WatchID a_WatchID, const FW::String& a_Dir, const FW::String& a_Filename, FW::Action a_Action) override; bool GetUniformLocation(std::string a_Name, i32& oa_Location); EShaderType GetShaderType(std::string a_FilePath); i32 LoadShader(std::string a_FileContents, EShaderType a_ShaderType, i32 a_Shader); i32 LinkProgram(); private: TArray<i32> m_Shaders; std::unordered_map<std::string, i32> m_UniformLocations; i32 m_ProgramID; }; }}}
30.323529
139
0.698998
[ "geometry" ]
fee7370d507b92f1725f75ca118e1b5d8867f957
15,572
cpp
C++
src/caffe/layers/data_layer.cpp
NEWPLAN/nvcaffe-0.17.3
7b8e4fdef8216d8497f6d71df465e881e47e009b
[ "BSD-2-Clause" ]
null
null
null
src/caffe/layers/data_layer.cpp
NEWPLAN/nvcaffe-0.17.3
7b8e4fdef8216d8497f6d71df465e881e47e009b
[ "BSD-2-Clause" ]
null
null
null
src/caffe/layers/data_layer.cpp
NEWPLAN/nvcaffe-0.17.3
7b8e4fdef8216d8497f6d71df465e881e47e009b
[ "BSD-2-Clause" ]
null
null
null
#include "caffe/data_transformer.hpp" #include "caffe/layer.hpp" #include "caffe/layers/data_layer.hpp" #include "caffe/parallel.hpp" namespace caffe { template <typename Ftype, typename Btype> DataLayer<Ftype, Btype>::DataLayer(const LayerParameter &param, size_t solver_rank) : BasePrefetchingDataLayer<Ftype, Btype>(param, solver_rank), cache_(param.data_param().cache()), shuffle_(param.data_param().shuffle()) { sample_only_.store(this->auto_mode_); init_offsets(); datum_encoded_ = false; } template <typename Ftype, typename Btype> void DataLayer<Ftype, Btype>::init_offsets() { CHECK_EQ(this->transf_num_, this->threads_num()); CHECK_LE(parser_offsets_.size(), this->transf_num_); CHECK_LE(queue_ids_.size(), this->transf_num_); parser_offsets_.resize(this->transf_num_); random_vectors_.resize(this->transf_num_); queue_ids_.resize(this->transf_num_); for (size_t i = 0; i < this->transf_num_; ++i) { parser_offsets_[i] = 0; queue_ids_[i] = i * this->parsers_num_; if (!random_vectors_[i]) { random_vectors_[i] = make_shared<TBlob<unsigned int>>(); } } } template <typename Ftype, typename Btype> DataLayer<Ftype, Btype>::~DataLayer() { this->StopInternalThread(); } template <typename Ftype, typename Btype> void DataLayer<Ftype, Btype>::InitializePrefetch() { if (layer_inititialized_flag_.is_set()) { return; } const bool auto_mode = this->auto_mode_; if (auto_mode) { // Here we try to optimize memory split between prefetching and convolution. // All data and parameter blobs are allocated at this moment. // Now let's find out what's left... Net *pnet = this->parent_net(); const size_t batch_bytes = pnet->prefetch_bytes<Ftype, Btype>(); const size_t gpu_bytes = Caffe::min_avail_device_memory(); const size_t batches_fit = gpu_bytes / batch_bytes; size_t parsers_num = this->parsers_num_; size_t transf_num = this->threads_num(); if (this->is_gpu_transform()) { // in this mode memory demand is O(n) high size_t max_parsers_num = 2; const size_t max_transf_num = 4; float ratio = datum_encoded_ ? 3.F : 4.F; const float fit = std::min(float(max_parsers_num * max_transf_num), std::floor(batches_fit / ratio) - 1.F); parsers_num = std::min(max_parsers_num, std::max(1UL, static_cast<size_t>(std::sqrt(fit)))); if (cache_ && parsers_num > 1UL) { LOG(INFO) << this->print_current_device() << " Reduced parser threads count from " << parsers_num << " to 1 because cache is used"; parsers_num = 1UL; } transf_num = std::min(max_transf_num, std::max(transf_num, static_cast<size_t>(std::lround(fit / parsers_num)))); if (parsers_num > 1 && transf_num == max_transf_num - 1) { parsers_num = 1; transf_num = max_transf_num; } if (parsers_num == 2 && transf_num == 2) { parsers_num = 1; transf_num = max_transf_num; } } else { // in this mode memory demand is O(1) if (batches_fit > 0) { parsers_num = cache_ ? 1 : 3; transf_num = 4; } } this->RestartAllThreads(transf_num, true, false, Caffe::next_seed()); this->transf_num_ = this->threads_num(); this->parsers_num_ = parsers_num; this->queues_num_ = this->transf_num_ * this->parsers_num_; this->batch_transformer_->ResizeQueues(this->queues_num_); BasePrefetchingDataLayer<Ftype, Btype>::InitializePrefetch(); if (this->parsers_num_ > 1) { parser_offsets_[0]++; // 0th already processed } this->auto_mode_ = false; layer_inititialized_flag_.set(); this->go(); // kick off new threads if any } CHECK_EQ(this->threads_num(), this->transf_num_); LOG(INFO) << this->print_current_device() << " Parser threads: " << this->parsers_num_ << (auto_mode ? " (auto)" : ""); LOG(INFO) << this->print_current_device() << " Transformer threads: " << this->transf_num_ << (auto_mode ? " (auto)" : ""); layer_inititialized_flag_.set(); } template <typename Ftype, typename Btype> size_t DataLayer<Ftype, Btype>::queue_id(size_t thread_id) const { const size_t qid = queue_ids_[thread_id] + parser_offsets_[thread_id]; parser_offsets_[thread_id]++; if (parser_offsets_[thread_id] >= this->parsers_num_) { parser_offsets_[thread_id] = 0UL; queue_ids_[thread_id] += this->parsers_num_ * this->threads_num(); } return qid % this->queues_num_; }; template <typename Ftype, typename Btype> void DataLayer<Ftype, Btype>::DataLayerSetUp(const vector<Blob *> &bottom, const vector<Blob *> &top) { const LayerParameter &param = this->layer_param(); const int batch_size = param.data_param().batch_size(); const bool cache = cache_ && this->phase_ == TRAIN; const bool shuffle = cache && shuffle_ && this->phase_ == TRAIN; if (this->auto_mode_) { if (!sample_reader_) { sample_reader_ = std::make_shared<DataReader<Datum>>(param, Caffe::device_in_use_per_host_count(), this->rank_ % Caffe::device_in_use_per_host_count(), this->parsers_num_, this->threads_num(), batch_size, true, false, cache, shuffle, false); } else if (!reader_) { reader_ = std::make_shared<DataReader<Datum>>(param, Caffe::device_in_use_per_host_count(), this->rank_ % Caffe::device_in_use_per_host_count(), this->parsers_num_, this->threads_num(), batch_size, false, true, cache, shuffle, this->phase_ == TRAIN); } } else if (!reader_) { reader_ = std::make_shared<DataReader<Datum>>(param, Caffe::device_in_use_per_host_count(), this->rank_ % Caffe::device_in_use_per_host_count(), this->parsers_num_, this->threads_num(), batch_size, false, false, cache, shuffle, this->phase_ == TRAIN); } // Read a data point, and use it to initialize the top blob. shared_ptr<Datum> sample_datum = sample_only_ ? sample_reader_->sample() : reader_->sample(); datum_encoded_ = sample_datum->encoded(); this->ResizeQueues(); init_offsets(); // Reshape top[0] and prefetch_data according to the batch_size. // Note: all these reshapings here in load_batch are needed only in case of // different datum shapes coming from database. Packing packing = NHWC; // OpenCV vector<int> top_shape = this->bdt(0)->Transform(sample_datum.get(), nullptr, 0, packing); top_shape[0] = batch_size; top[0]->Reshape(top_shape); if (this->is_gpu_transform()) { CHECK(Caffe::mode() == Caffe::GPU); LOG(INFO) << this->print_current_device() << " Transform on GPU enabled"; tmp_gpu_buffer_.resize(this->threads_num()); for (int i = 0; i < this->tmp_gpu_buffer_.size(); ++i) { this->tmp_gpu_buffer_[i] = make_shared<GPUMemory::Workspace>(); } } // label vector<int> label_shape(1, batch_size); if (this->output_labels_) { vector<int> label_shape(1, batch_size); top[1]->Reshape(label_shape); } this->batch_transformer_->reshape(top_shape, label_shape, this->is_gpu_transform()); LOG(INFO) << this->print_current_device() << " Output data size: " << top[0]->num() << ", " << top[0]->channels() << ", " << top[0]->height() << ", " << top[0]->width(); } template <typename Ftype, typename Btype> bool DataLayer<Ftype, Btype>::load_batch(Batch *batch, int thread_id, size_t queue_id) { const bool sample_only = sample_only_.load(); // Reshape according to the first datum of each batch // on single input batches allows for inputs of varying dimension. const int batch_size = this->layer_param_.data_param().batch_size(); const size_t qid = sample_only ? 0UL : queue_id; DataReader<Datum> *reader = sample_only ? sample_reader_.get() : reader_.get(); shared_ptr<Datum> init_datum = reader->full_peek(qid); CHECK(init_datum); const bool use_gpu_transform = this->is_gpu_transform(); Packing packing = NHWC; // OpenCV // Use data_transformer to infer the expected blob shape from datum. vector<int> top_shape = this->bdt(thread_id)->Transform(init_datum.get(), nullptr, 0, packing); // Reshape batch according to the batch_size. top_shape[0] = batch_size; if (top_shape != batch->data_->shape()) { batch->data_->Reshape(top_shape); } int init_datum_height = init_datum->height(); int init_datum_width = init_datum->width(); const int color_mode = this->transform_param_.force_color() ? 1 : (this->transform_param_.force_gray() ? -1 : 0); size_t datum_sizeof_element = 0UL; int datum_len = top_shape[1] * top_shape[2] * top_shape[3]; size_t datum_size = 0UL; const char *src_ptr = nullptr; vector<char> src_buf; cv::Mat img; if (use_gpu_transform) { if (init_datum->encoded()) { DecodeDatumToCVMat(*init_datum, color_mode, img, false, false); datum_len = img.channels() * img.rows * img.cols; datum_sizeof_element = sizeof(char); init_datum_height = img.rows; init_datum_width = img.cols; } else { datum_len = init_datum->channels() * init_datum->height() * init_datum->width(); CHECK_GT(datum_len, 0); const string &datum_data = init_datum->data(); if (datum_data.empty()) { CHECK_LE(sizeof(float), sizeof(Ftype)); datum_sizeof_element = sizeof(float); } else { CHECK_LE(sizeof(uint8_t), sizeof(Ftype)); CHECK_EQ(datum_len, datum_data.size()); datum_sizeof_element = sizeof(uint8_t); } } vector<int> random_vec_shape(1, batch_size * 3); random_vectors_[thread_id]->Reshape(random_vec_shape); datum_size = datum_len * datum_sizeof_element; src_buf.resize(datum_size); } if (this->output_labels_) { batch->label_->Reshape(vector<int>(1, batch_size)); } Ftype *top_label = this->output_labels_ ? batch->label_->template mutable_cpu_data_c<Ftype>(false) : nullptr; void *dst_gptr = nullptr; Btype *dst_cptr = nullptr; if (use_gpu_transform) { size_t buffer_size = top_shape[0] * top_shape[1] * init_datum_height * init_datum_width; tmp_gpu_buffer_[thread_id]->safe_reserve(buffer_size, Caffe::device()); dst_gptr = tmp_gpu_buffer_[thread_id]->data(); } else { dst_cptr = batch->data_->template mutable_cpu_data_c<Btype>(false); } size_t current_batch_id = 0UL; const size_t buf_len = batch->data_->offset(1); for (size_t entry = 0; entry < batch_size; ++entry) { shared_ptr<Datum> datum = reader->full_pop(qid, "Waiting for datum"); size_t item_id = datum->record_id() % batch_size; if (item_id == 0UL) { current_batch_id = datum->record_id() / batch_size; } // Copy label. if (top_label != nullptr) { top_label[item_id] = datum->label(); } if (use_gpu_transform) { cudaStream_t stream = Caffe::thread_stream(Caffe::GPU_TRANSF_GROUP); if (datum->encoded()) { DecodeDatumToSignedBuf(*datum, color_mode, src_buf.data(), datum_size, false); } else { CHECK_EQ(datum_len, datum->channels() * datum->height() * datum->width()) << "Datum size can't vary in the same batch"; src_ptr = datum->data().size() > 0 ? &datum->data().front() : reinterpret_cast<const char *>(&datum->float_data().Get(0)); // NOLINT_NEXT_LINE(caffe/alt_fn) std::memcpy(src_buf.data(), src_ptr, datum_size); } CUDA_CHECK(cudaMemcpyAsync(static_cast<char *>(dst_gptr) + item_id * datum_size, src_buf.data(), datum_size, cudaMemcpyHostToDevice, stream)); CUDA_CHECK(cudaStreamSynchronize(stream)); this->bdt(thread_id)->Fill3Randoms(&random_vectors_[thread_id]->mutable_cpu_data()[item_id * 3]); } else { // Get data offset for this datum to hand off to transform thread const size_t offset = batch->data_->offset(item_id); CHECK_EQ(0, offset % buf_len); #if defined(USE_CUDNN) vector<int> shape = this->bdt(thread_id)->Transform(datum.get(), dst_cptr + offset, buf_len, packing, false); #else vector<Btype> tmp(top_shape[1] * top_shape[2] * top_shape[3]); CHECK_EQ(buf_len, tmp.size()); vector<int> shape = this->bdt(thread_id)->Transform(datum.get(), tmp.data(), buf_len, packing, false); if (packing == NHWC) { hwc2chw(top_shape[1], top_shape[3], top_shape[2], tmp.data(), dst_cptr + offset); packing = NCHW; } else { // NOLINT_NEXT_LINE(caffe/alt_fn) memcpy(dst_cptr + offset, tmp.data(), buf_len * sizeof(Btype)); } #endif CHECK_EQ(top_shape[1], shape[1]) << "Number of channels can't vary in the same batch"; CHECK_EQ(top_shape[2], shape[2]) << "Image height can't vary in the same batch"; CHECK_EQ(top_shape[3], shape[3]) << "Image width can't vary in the same batch"; } reader->free_push(qid, datum); } if (use_gpu_transform) { this->fdt(thread_id)->TransformGPU(top_shape[0], top_shape[1], init_datum_height, // non-crop init_datum_width, // non-crop datum_sizeof_element, dst_gptr, batch->data_->template mutable_gpu_data_c<Ftype>(false), random_vectors_[thread_id]->gpu_data(), true); packing = NCHW; } batch->set_data_packing(packing); batch->set_id(current_batch_id); sample_only_.store(false); return reader->cached_all(); } INSTANTIATE_CLASS_FB(DataLayer); REGISTER_LAYER_CLASS_R(Data); } // namespace caffe
38.449383
130
0.576548
[ "shape", "vector", "transform" ]
feecd9611ac9663fda0860df3c8b3d2618927170
2,558
cpp
C++
webkit/WebCore/html/CollectionCache.cpp
s1rcheese/nintendo-3ds-internetbrowser-sourcecode
3dd05f035e0a5fc9723300623e9b9b359be64e11
[ "Unlicense" ]
15
2016-01-05T12:43:41.000Z
2022-03-15T10:34:47.000Z
webkit/WebCore/html/CollectionCache.cpp
s1rcheese/nintendo-3ds-internetbrowser-sourcecode
3dd05f035e0a5fc9723300623e9b9b359be64e11
[ "Unlicense" ]
null
null
null
webkit/WebCore/html/CollectionCache.cpp
s1rcheese/nintendo-3ds-internetbrowser-sourcecode
3dd05f035e0a5fc9723300623e9b9b359be64e11
[ "Unlicense" ]
2
2020-11-30T18:36:01.000Z
2021-02-05T23:20:24.000Z
/* * Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * */ #include "config.h" #include "CollectionCache.h" namespace WebCore { CollectionCache::CollectionCache() : version(0) { reset(); } inline void CollectionCache::copyCacheMap(NodeCacheMap& dest, const NodeCacheMap& src) { ASSERT(dest.isEmpty()); NodeCacheMap::const_iterator end = src.end(); for (NodeCacheMap::const_iterator it = src.begin(); it != end; ++it) dest.add(it->first, new Vector<Element*>(*it->second)); } CollectionCache::CollectionCache(const CollectionCache& other) : version(other.version) , current(other.current) , position(other.position) , length(other.length) , elementsArrayPosition(other.elementsArrayPosition) , hasLength(other.hasLength) , hasNameCache(other.hasNameCache) { copyCacheMap(idCache, other.idCache); copyCacheMap(nameCache, other.nameCache); } void CollectionCache::swap(CollectionCache& other) { std::swap(version, other.version); std::swap(current, other.current); std::swap(position, other.position); std::swap(length, other.length); std::swap(elementsArrayPosition, other.elementsArrayPosition); idCache.swap(other.idCache); nameCache.swap(other.nameCache); std::swap(hasLength, other.hasLength); std::swap(hasNameCache, other.hasNameCache); } CollectionCache::~CollectionCache() { deleteAllValues(idCache); deleteAllValues(nameCache); } void CollectionCache::reset() { current = 0; position = 0; length = 0; hasLength = false; elementsArrayPosition = 0; deleteAllValues(idCache); idCache.clear(); deleteAllValues(nameCache); nameCache.clear(); hasNameCache = false; } } // namespace WebCore
28.741573
86
0.712275
[ "vector" ]
feedbb31efa0a88ff26b37713045736f1ea80fca
9,291
cpp
C++
src/xrCDB/xrCDB_box.cpp
clayne/xray-16
32ebf81a252c7179e2824b2874f911a91e822ad1
[ "OML", "Linux-OpenIB" ]
2
2015-02-23T10:43:02.000Z
2015-06-11T14:45:08.000Z
src/xrCDB/xrCDB_box.cpp
clayne/xray-16
32ebf81a252c7179e2824b2874f911a91e822ad1
[ "OML", "Linux-OpenIB" ]
17
2022-01-25T08:58:23.000Z
2022-03-28T17:18:28.000Z
src/xrCDB/xrCDB_box.cpp
clayne/xray-16
32ebf81a252c7179e2824b2874f911a91e822ad1
[ "OML", "Linux-OpenIB" ]
1
2015-06-05T20:04:00.000Z
2015-06-05T20:04:00.000Z
#include "stdafx.h" #pragma hdrstop #include "xrCDB.h" using namespace CDB; using namespace Opcode; //! This macro quickly finds the min & max values among 3 variables #define FINDMINMAX(x0, x1, x2, min, max)\ min = max = x0;\ if (x1 < min)\ min = x1;\ if (x1 > max)\ max = x1;\ if (x2 < min)\ min = x2;\ if (x2 > max)\ max = x2; //! TO BE DOCUMENTED ICF bool planeBoxOverlap(const Point& normal, const float d, const Point& maxbox) { Point vmin, vmax; for (udword q = 0; q <= 2; q++) { if (((const float*)normal)[q] > 0.0f) { ((float*)vmin)[q] = -((const float*)maxbox)[q]; ((float*)vmax)[q] = ((const float*)maxbox)[q]; } else { ((float*)vmin)[q] = ((const float*)maxbox)[q]; ((float*)vmax)[q] = -((const float*)maxbox)[q]; } } if ((normal | vmin) + d > 0.0f) return false; if ((normal | vmax) + d >= 0.0f) return true; return false; } //! TO BE DOCUMENTED #define AXISTEST_X01(a, b, fa, fb)\ min = a * v0.y - b * v0.z;\ max = a * v2.y - b * v2.z;\ if (min > max)\ {\ const float tmp = max;\ max = min;\ min = tmp;\ }\ rad = fa * extents.y + fb * extents.z;\ if (min > rad || max < -rad)\ return false; //! TO BE DOCUMENTED #define AXISTEST_X2(a, b, fa, fb)\ min = a * v0.y - b * v0.z;\ max = a * v1.y - b * v1.z;\ if (min > max)\ {\ const float tmp = max;\ max = min;\ min = tmp;\ }\ rad = fa * extents.y + fb * extents.z;\ if (min > rad || max < -rad)\ return false; //! TO BE DOCUMENTED #define AXISTEST_Y02(a, b, fa, fb)\ min = b * v0.z - a * v0.x;\ max = b * v2.z - a * v2.x;\ if (min > max)\ {\ const float tmp = max;\ max = min;\ min = tmp;\ }\ rad = fa * extents.x + fb * extents.z;\ if (min > rad || max < -rad)\ return false; //! TO BE DOCUMENTED #define AXISTEST_Y1(a, b, fa, fb)\ min = b * v0.z - a * v0.x;\ max = b * v1.z - a * v1.x;\ if (min > max)\ {\ const float tmp = max;\ max = min;\ min = tmp;\ }\ rad = fa * extents.x + fb * extents.z;\ if (min > rad || max < -rad)\ return false; //! TO BE DOCUMENTED #define AXISTEST_Z12(a, b, fa, fb)\ min = a * v1.x - b * v1.y;\ max = a * v2.x - b * v2.y;\ if (min > max)\ {\ const float tmp = max;\ max = min;\ min = tmp;\ }\ rad = fa * extents.x + fb * extents.y;\ if (min > rad || max < -rad)\ return false; //! TO BE DOCUMENTED #define AXISTEST_Z0(a, b, fa, fb)\ min = a * v0.x - b * v0.y;\ max = a * v1.x - b * v1.y;\ if (min > max)\ {\ const float tmp = max;\ max = min;\ min = tmp;\ }\ rad = fa * extents.x + fb * extents.y;\ if (min > rad || max < -rad)\ return false; template <bool bClass3, bool bFirst> class box_collider { public: COLLIDER* dest; TRI* tris; Fvector* verts; Fvector b_min, b_max; Point center, extents; Point mLeafVerts[3]; IC void _init(COLLIDER* CL, Fvector* V, TRI* T, const Fvector& C, const Fvector& E) { dest = CL; verts = V; tris = T; center = Point(C.x, C.y, C.z); extents = Point(E.x, E.y, E.z); b_min.sub(C, E); b_max.add(C, E); } ICF bool _box(const Fvector& C, const Fvector& E) { if (b_max.x < C.x - E.x) return false; if (b_max.y < C.y - E.y) return false; if (b_max.z < C.z - E.z) return false; if (b_min.x > C.x + E.x) return false; if (b_min.y > C.y + E.y) return false; if (b_min.z > C.z + E.z) return false; return true; }; ICF bool _tri() { // move everything so that the boxcenter is in (0,0,0) Point v0, v1, v2; v0.x = mLeafVerts[0].x - center.x; v1.x = mLeafVerts[1].x - center.x; v2.x = mLeafVerts[2].x - center.x; // First, test overlap in the {x,y,z}-directions { float min, max; // Find min, max of the triangle in x-direction, and test for overlap in X FINDMINMAX(v0.x, v1.x, v2.x, min, max); if (min > extents.x || max < -extents.x) return false; // Same for Y v0.y = mLeafVerts[0].y - center.y; v1.y = mLeafVerts[1].y - center.y; v2.y = mLeafVerts[2].y - center.y; FINDMINMAX(v0.y, v1.y, v2.y, min, max); if (min > extents.y || max < -extents.y) return false; // Same for Z v0.z = mLeafVerts[0].z - center.z; v1.z = mLeafVerts[1].z - center.z; v2.z = mLeafVerts[2].z - center.z; FINDMINMAX(v0.z, v1.z, v2.z, min, max); if (min > extents.z || max < -extents.z) return false; } // 2) Test if the box intersects the plane of the triangle // compute plane equation of triangle: normal*x+d=0 // ### could be precomputed since we use the same leaf triangle several times const Point e0 = v1 - v0; const Point e1 = v2 - v1; const Point normal = e0 ^ e1; const float d = -normal | v0; if (!planeBoxOverlap(normal, d, extents)) return false; // 3) "Class III" tests if (bClass3) { float rad; float min, max; // compute triangle edges // - edges lazy evaluated to take advantage of early exits // - fabs precomputed (half less work, possible since extents are always >0) // - customized macros to take advantage of the null component // - axis vector3 discarded, possibly saves useless movs const float fey0 = _abs(e0.y); const float fez0 = _abs(e0.z); AXISTEST_X01(e0.z, e0.y, fez0, fey0); const float fex0 = _abs(e0.x); AXISTEST_Y02(e0.z, e0.x, fez0, fex0); AXISTEST_Z12(e0.y, e0.x, fey0, fex0); const float fey1 = _abs(e1.y); const float fez1 = _abs(e1.z); AXISTEST_X01(e1.z, e1.y, fez1, fey1); const float fex1 = _abs(e1.x); AXISTEST_Y02(e1.z, e1.x, fez1, fex1); AXISTEST_Z0(e1.y, e1.x, fey1, fex1); const Point e2 = mLeafVerts[0] - mLeafVerts[2]; const float fey2 = _abs(e2.y); const float fez2 = _abs(e2.z); AXISTEST_X2(e2.z, e2.y, fez2, fey2); const float fex2 = _abs(e2.x); AXISTEST_Y1(e2.z, e2.x, fez2, fex2); AXISTEST_Z12(e2.y, e2.x, fey2, fex2); } return true; } void _prim(u32 prim) { TRI& T = tris[prim]; Fvector& v0 = verts[T.verts[0]]; mLeafVerts[0].x = v0.x; mLeafVerts[0].y = v0.y; mLeafVerts[0].z = v0.z; Fvector& v1 = verts[T.verts[1]]; mLeafVerts[1].x = v1.x; mLeafVerts[1].y = v1.y; mLeafVerts[1].z = v1.z; Fvector& v2 = verts[T.verts[2]]; mLeafVerts[2].x = v2.x; mLeafVerts[2].y = v2.y; mLeafVerts[2].z = v2.z; if (!_tri()) return; RESULT& R = dest->r_add(); R.id = prim; R.verts[0] = v0; R.verts[1] = v1; R.verts[2] = v2; R.dummy = T.dummy; } void _stab(const AABBNoLeafNode* node) { // Actual box-box test if (!_box((Fvector&)node->mAABB.mCenter, (Fvector&)node->mAABB.mExtents)) return; // 1st chield if (node->HasLeaf()) _prim(node->GetPrimitive()); else _stab(node->GetPos()); // Early exit for "only first" if (bFirst && dest->r_count()) return; // 2nd chield if (node->HasLeaf2()) _prim(node->GetPrimitive2()); else _stab(node->GetNeg()); } }; void COLLIDER::box_query(const MODEL* m_def, const Fvector& b_center, const Fvector& b_dim) { m_def->syncronize(); // Get nodes const AABBNoLeafTree* T = (const AABBNoLeafTree*)m_def->tree->GetTree(); const AABBNoLeafNode* N = T->GetNodes(); r_clear(); // Binary dispatcher if (box_mode & OPT_FULL_TEST) { if (box_mode & OPT_ONLYFIRST) { box_collider<true, true> BC; BC._init(this, m_def->verts, m_def->tris, b_center, b_dim); BC._stab(N); } else { box_collider<true, false> BC; BC._init(this, m_def->verts, m_def->tris, b_center, b_dim); BC._stab(N); } } else { if (box_mode & OPT_ONLYFIRST) { box_collider<false, true> BC; BC._init(this, m_def->verts, m_def->tris, b_center, b_dim); BC._stab(N); } else { box_collider<false, false> BC; BC._init(this, m_def->verts, m_def->tris, b_center, b_dim); BC._stab(N); } } }
27.651786
91
0.486169
[ "model" ]
feef4b791e85492f74c002a6b7c29339d355e629
11,151
cc
C++
src/cpsw_proto_mod_udp.cc
slaclab/cpsw
0b0410fb33af4904b51063b730d1743ec59fb73b
[ "BSD-3-Clause-LBNL" ]
1
2021-09-21T06:51:11.000Z
2021-09-21T06:51:11.000Z
src/cpsw_proto_mod_udp.cc
slaclab/cpsw
0b0410fb33af4904b51063b730d1743ec59fb73b
[ "BSD-3-Clause-LBNL" ]
1
2019-11-12T22:24:49.000Z
2019-11-12T22:24:49.000Z
src/cpsw_proto_mod_udp.cc
slaclab/cpsw
0b0410fb33af4904b51063b730d1743ec59fb73b
[ "BSD-3-Clause-LBNL" ]
3
2018-11-28T21:02:02.000Z
2020-12-13T00:09:34.000Z
//@C Copyright Notice //@C ================ //@C This file is part of CPSW. It is subject to the license terms in the LICENSE.txt //@C file found in the top-level directory of this distribution and at //@C https://confluence.slac.stanford.edu/display/ppareg/LICENSE.html. //@C //@C No part of CPSW, including this file, may be copied, modified, propagated, or //@C distributed except according to the terms contained in the LICENSE.txt file. #define __STDC_FORMAT_MACROS #include <inttypes.h> #include <cpsw_api_user.h> #include <cpsw_error.h> #include <cpsw_proto_mod_udp.h> #include <cpsw_stdio.h> #include <errno.h> #include <sys/select.h> #include <sys/uio.h> #include <stdio.h> #include <cpsw_yaml.h> //#define UDP_DEBUG //#define UDP_DEBUG_STRM CUdpHandlerThread::CUdpHandlerThread( const char *name, int threadPriority, struct sockaddr_in *dest, struct sockaddr_in *me_p ) : CRunnable(name, threadPriority) { sd_.init( dest, me_p, false ); } CUdpHandlerThread::CUdpHandlerThread(CUdpHandlerThread &orig, struct sockaddr_in *dest, struct sockaddr_in *me_p) : CRunnable(orig), sd_(orig.sd_) { sd_.init( dest, me_p, false ); } #define NBUFS_MAX 8 void * CProtoModUdp::CUdpRxHandlerThread::threadBody() { ssize_t got,siz,cap; std::vector<Buf> bufs; unsigned idx; struct iovec iov[NBUFS_MAX]; int niovs; for ( niovs = 0, cap = 0; niovs<NBUFS_MAX && cap < (ssize_t)IBuf::CAPA_ETH_JUM; niovs++ ) { bufs.push_back( IBuf::getBuf( IBuf::CAPA_ETH_BIG ) ); iov[niovs].iov_base = bufs[niovs]->getPayload(); cap += (iov[niovs].iov_len = bufs[niovs]->getAvail()); } while ( 1 ) { #ifdef UDP_DEBUG fprintf(CPSW::fDbg(), "UDP -- waiting for data\n"); #endif got = ::readv( sd_.getSd(), iov, niovs ); if ( got < 0 ) { perror("rx thread"); sleep(10); continue; } nDgrams_.fetch_add(1, cpsw::memory_order_relaxed); nOctets_.fetch_add(got, cpsw::memory_order_relaxed); if ( got > 0 ) { #ifdef UDP_DEBUG #ifdef UDP_DEBUG_STRM unsigned fram, frag; #endif #endif BufChain bufch = IBufChain::create(); siz = got; idx = 0; while ( siz > 0 ) { if ( siz < (cap = bufs[idx]->getAvail()) ) { cap = siz; } bufs[idx]->setSize( cap ); #ifdef UDP_DEBUG if ( idx == 0 ) { int i; uint8_t *p = bufs[idx]->getPayload(); #ifdef UDP_DEBUG_STRM fram = (p[1]<<4) | (p[0]>>4); frag = (p[4]<<16) | (p[3] << 8) | p[2]; #endif fprintf(CPSW::fDbg(), "UDP data: "); for ( i=0; i< (got < 4 ? got : 4); i++ ) fprintf(CPSW::fDbg(), "%02x ", p[i]); fprintf(CPSW::fDbg(), "\n"); } #endif bufch->addAtTail( bufs[idx] ); // get new buffers bufs[idx] = IBuf::getBuf( IBuf::CAPA_ETH_BIG ); iov[idx].iov_base = bufs[idx]->getPayload(); iov[idx].iov_len = bufs[idx]->getAvail(); idx++; siz -= cap; } bool st= // do NOT wait indefinitely // could be that the queue is full with // retry replies they will only discover // next time they care about reading from // this VC... owner_->pushDown( bufch, &TIMEOUT_NONE ); #ifdef UDP_DEBUG fprintf(CPSW::fDbg(), "UDP got %d", (int)got); #ifdef UDP_DEBUG_STRM fprintf(CPSW::fDbg(), " fram # %4d, frag # %4d", fram, frag); #endif if ( st ) fprintf(CPSW::fDbg(), " (pushdown SUCC)\n"); else fprintf(CPSW::fDbg(), " (pushdown DROP)\n"); #endif if ( st ) { nRxDrop_.fetch_add(1, cpsw::memory_order_relaxed); } } #ifdef UDP_DEBUG else { fprintf(CPSW::fDbg(), "UDP got ZERO\n"); } #endif } return NULL; } CProtoModUdp::CUdpRxHandlerThread::CUdpRxHandlerThread( const char *name, int threadPriority, struct sockaddr_in *dest, struct sockaddr_in *me, CProtoModUdp *owner ) : CUdpHandlerThread(name, threadPriority, dest, me), nOctets_(0), nDgrams_(0), nRxDrop_(0), owner_(owner) { } CProtoModUdp::CUdpRxHandlerThread::CUdpRxHandlerThread(CUdpRxHandlerThread &orig, struct sockaddr_in *dest, struct sockaddr_in *me, CProtoModUdp *owner) : CUdpHandlerThread( orig, dest, me ), nOctets_(0), nDgrams_(0), nRxDrop_(0), owner_(owner) { } void * CUdpPeerPollerThread::threadBody() { uint8_t buf[4]; memset( buf, 0, sizeof(buf) ); while ( 1 ) { if ( ::write( sd_.getSd(), buf, 0 ) < 0 ) { perror("poller thread (write)"); continue; } if ( sleep( pollSecs_ ) ) continue; // interrupted by signal } return NULL; } CUdpPeerPollerThread::CUdpPeerPollerThread(const char *name, struct sockaddr_in *dest, struct sockaddr_in *me, unsigned pollSecs) : CUdpHandlerThread(name, IProtoStackBuilder::NORT_THREAD_PRIORITY, dest, me), pollSecs_(pollSecs) { } CUdpPeerPollerThread::CUdpPeerPollerThread(CUdpPeerPollerThread &orig, struct sockaddr_in *dest, struct sockaddr_in *me) : CUdpHandlerThread(orig, dest, me), pollSecs_(orig.pollSecs_) { } void CProtoModUdp::createThreads(unsigned nRxThreads, int pollSeconds) { unsigned i; struct sockaddr_in me; tx_.getMyAddr( &me ); if ( poller_ ) { // called from copy constructor poller_ = new CUdpPeerPollerThread(*poller_, &dest_, &me); } else if ( pollSeconds > 0 ) { poller_ = new CUdpPeerPollerThread("UDP Poller (UDP protocol module)", &dest_, &me, pollSeconds ); } // might be called by the copy constructor rxHandlers_.clear(); for ( i=0; i<nRxThreads; i++ ) { rxHandlers_.push_back( new CUdpRxHandlerThread("UDP RX Handler (UDP protocol module)", threadPriority_, &dest_, &me, this ) ); } // maybe setting the threadPriority failed? if ( nRxThreads ) { threadPriority_ = rxHandlers_[0]->getPrio(); } } void CProtoModUdp::modStartup() { unsigned i; if ( poller_ ) poller_->threadStart(); for ( i=0; i<rxHandlers_.size(); i++ ) { rxHandlers_[i]->threadStart(); } } void CProtoModUdp::modShutdown() { unsigned i; if ( poller_ ) poller_->threadStop(); for ( i=0; i<rxHandlers_.size(); i++ ) { rxHandlers_[i]->threadStop(); } } CProtoModUdp::CProtoModUdp( Key &k, struct sockaddr_in *dest, unsigned depth, int threadPriority, unsigned nRxThreads, int pollSecs ) :CProtoMod(k, depth), dest_(*dest), nTxOctets_(0), nTxDgrams_(0), threadPriority_(threadPriority), poller_( NULL ) { tx_.init( dest, 0, true ); createThreads( nRxThreads, pollSecs ); } void CProtoModUdp::dumpYaml(YAML::Node &node) const { YAML::Node udpParms; writeNode(udpParms, YAML_KEY_port, getDestPort() ); writeNode(udpParms, YAML_KEY_outQueueDepth, getQueueDepth() ); writeNode(udpParms, YAML_KEY_numRxThreads, rxHandlers_.size()); writeNode(udpParms, YAML_KEY_pollSecs, poller_ ? poller_->getPollSecs() : 0); if ( threadPriority_ != IProtoStackBuilder::DFLT_THREAD_PRIORITY ) { writeNode(udpParms, YAML_KEY_threadPriority, threadPriority_); } writeNode(node, YAML_KEY_UDP, udpParms); } CProtoModUdp::CProtoModUdp(CProtoModUdp &orig, Key &k) :CProtoMod(orig, k), dest_(orig.dest_), tx_(orig.tx_), nTxOctets_(0), nTxDgrams_(0), threadPriority_(orig.threadPriority_), poller_(orig.poller_) { tx_.init( &dest_, 0, true ); createThreads( orig.rxHandlers_.size(), -1 ); } uint64_t CProtoModUdp::getNumRxOctets() { unsigned i; uint64_t rval = 0; for ( i=0; i<rxHandlers_.size(); i++ ) rval += rxHandlers_[i]->getNumOctets(); return rval; } uint64_t CProtoModUdp::getNumRxDgrams() { unsigned i; uint64_t rval = 0; for ( i=0; i<rxHandlers_.size(); i++ ) rval += rxHandlers_[i]->getNumDgrams(); return rval; } uint64_t CProtoModUdp::getNumRxDrops() { unsigned i; uint64_t rval = 0; for ( i=0; i<rxHandlers_.size(); i++ ) rval += rxHandlers_[i]->getNumRxDrop(); return rval; } CProtoModUdp::~CProtoModUdp() { unsigned i; for ( i=0; i<rxHandlers_.size(); i++ ) delete rxHandlers_[i]; if ( poller_ ) delete poller_; } void CProtoModUdp::dumpInfo(FILE *f) { if ( ! f ) throw InternalError("CProtoModUdp::dumpInfo now requires FILE argument"); fprintf(f,"CProtoModUdp:\n"); fprintf(f," Peer port : %15u\n", getDestPort()); fprintf(f," RX Threads: %15lu\n", (unsigned long)rxHandlers_.size()); fprintf(f," ThreadPrio: %15d\n", threadPriority_); fprintf(f," Has Poller: %c\n", poller_ ? 'Y' : 'N'); fprintf(f," #TX Octets: %15" PRIu64 "\n", getNumTxOctets()); fprintf(f," #TX DGRAMs: %15" PRIu64 "\n", getNumTxDgrams()); fprintf(f," #RX Octets: %15" PRIu64 "\n", getNumRxOctets()); fprintf(f," #RX DGRAMs: %15" PRIu64 "\n", getNumRxDgrams()); fprintf(f," #RX droppd: %15" PRIu64 "\n", getNumRxDrops() ); } bool CProtoModUdp::doPush(BufChain bc, bool wait, const CTimeout *timeout, bool abs_timeout) { fd_set fds; int selres, sndres; Buf b; struct iovec iov[bc->getLen()]; unsigned nios; // there could be two models for sending a chain of buffers: // a) the chain describes a gather list (one UDP message assembled from chain) // b) the chain describes a fragmented frame (multiple messages sent) // We follow a) here... // If they were to fragment a large frame they have to push each // fragment individually. nTxDgrams_.fetch_add( 1, cpsw::memory_order_relaxed ); nTxOctets_.fetch_add( bc->getSize(), cpsw::memory_order_relaxed ); for (nios=0, b=bc->getHead(); nios<bc->getLen(); nios++, b=b->getNext()) { iov[nios].iov_base = b->getPayload(); iov[nios].iov_len = b->getSize(); } if ( wait ) { FD_ZERO( &fds ); FD_SET( tx_.getSd(), &fds ); // use pselect: does't modify the timeout and it's a timespec selres = ::pselect( tx_.getSd() + 1, NULL, &fds, NULL, !timeout || timeout->isIndefinite() ? NULL : &timeout->tv_, NULL ); if ( selres < 0 ) { perror("::pselect() - dropping message due to error"); return false; } if ( selres == 0 ) { #ifdef UDP_DEBUG fprintf(CPSW::fDbg(), "UDP doPush -- pselect timeout\n"); #endif // TIMEOUT return false; } } sndres = writev( tx_.getSd(), iov, nios ); if ( sndres < 0 ) { perror("::writev() - dropping message due to error"); #ifdef UDP_DEBUG // this could help debugging the occasinal EPERM I get here... #warning FIXME abort(); #endif return false; } #ifdef UDP_DEBUG fprintf(CPSW::fDbg(), "UDP doPush -- wrote %d:", sndres); for ( unsigned i=0; i < (iov[0].iov_len < 4 ? iov[0].iov_len : 4); i++ ) fprintf(CPSW::fDbg(), " %02x", ((unsigned char*)iov[0].iov_base)[i]); fprintf(CPSW::fDbg(), "\n"); #endif return true; } int CProtoModUdp::iMatch(ProtoPortMatchParams *cmp) { cmp->udpDestPort_.handledBy_ = getProtoMod(); if ( cmp->udpDestPort_ == getDestPort() ) { cmp->udpDestPort_.matchedBy_ = getSelfAs<ProtoModUdp>(); return 1; } return 0; } unsigned CProtoModUdp::getMTU() { int rval = tx_.getMTU(); #ifdef UDP_DEBUG fprintf(CPSW::fDbg(), "UDP SOCKET MTU: %d\n", rval); #endif rval -= 60; /* max. IP header */ rval -= 8; /* UDP header */ if ( rval > 65536 ) { rval = 65536; } else if ( 0 >= rval ) { /* ??? unable to determine; use some default */ fprintf(CPSW::fErr(), "WARNING: cpsw_proto_mod_udp: unable to determine MTU\n"); rval = 1024; } return rval; }
25.114865
152
0.653215
[ "vector" ]
fef10b9a328524fbc8cdb8ec8fa6f1dc9bcaf0ee
18,753
cpp
C++
artifact/storm/src/test/storm/builder/DdPrismModelBuilderTest.cpp
glatteis/tacas21-artifact
30b4f522bd3bdb4bebccbfae93f19851084a3db5
[ "MIT" ]
null
null
null
artifact/storm/src/test/storm/builder/DdPrismModelBuilderTest.cpp
glatteis/tacas21-artifact
30b4f522bd3bdb4bebccbfae93f19851084a3db5
[ "MIT" ]
null
null
null
artifact/storm/src/test/storm/builder/DdPrismModelBuilderTest.cpp
glatteis/tacas21-artifact
30b4f522bd3bdb4bebccbfae93f19851084a3db5
[ "MIT" ]
1
2022-02-05T12:39:53.000Z
2022-02-05T12:39:53.000Z
#include "test/storm_gtest.h" #include "storm-config.h" #include "storm/settings/SettingMemento.h" #include "storm/settings/SettingsManager.h" #include "storm/settings/modules/BuildSettings.h" #include "storm/storage/SymbolicModelDescription.h" #include "storm/models/symbolic/Dtmc.h" #include "storm/models/symbolic/Ctmc.h" #include "storm/models/symbolic/Mdp.h" #include "storm/models/symbolic/StandardRewardModel.h" #include "storm-parsers/parser/PrismParser.h" #include "storm/builder/DdPrismModelBuilder.h" TEST(DdPrismModelBuilderTest_Sylvan, Dtmc) { storm::storage::SymbolicModelDescription modelDescription = storm::parser::PrismParser::parse(STORM_TEST_RESOURCES_DIR "/dtmc/die.pm"); storm::prism::Program program = modelDescription.preprocess().asPrismProgram(); std::shared_ptr<storm::models::symbolic::Model<storm::dd::DdType::Sylvan>> model = storm::builder::DdPrismModelBuilder<storm::dd::DdType::Sylvan>().build(program); EXPECT_EQ(13ul, model->getNumberOfStates()); EXPECT_EQ(20ul, model->getNumberOfTransitions()); modelDescription = storm::parser::PrismParser::parse(STORM_TEST_RESOURCES_DIR "/dtmc/brp-16-2.pm"); program = modelDescription.preprocess().asPrismProgram(); model = storm::builder::DdPrismModelBuilder<storm::dd::DdType::Sylvan>().build(program); EXPECT_EQ(677ul, model->getNumberOfStates()); EXPECT_EQ(867ul, model->getNumberOfTransitions()); modelDescription = storm::parser::PrismParser::parse(STORM_TEST_RESOURCES_DIR "/dtmc/crowds-5-5.pm"); program = modelDescription.preprocess().asPrismProgram(); model = storm::builder::DdPrismModelBuilder<storm::dd::DdType::Sylvan>().build(program); EXPECT_EQ(8607ul, model->getNumberOfStates()); EXPECT_EQ(15113ul, model->getNumberOfTransitions()); modelDescription = storm::parser::PrismParser::parse(STORM_TEST_RESOURCES_DIR "/dtmc/leader-3-5.pm"); program = modelDescription.preprocess().asPrismProgram(); model = storm::builder::DdPrismModelBuilder<storm::dd::DdType::Sylvan>().build(program); EXPECT_EQ(273ul, model->getNumberOfStates()); EXPECT_EQ(397ul, model->getNumberOfTransitions()); modelDescription = storm::parser::PrismParser::parse(STORM_TEST_RESOURCES_DIR "/dtmc/nand-5-2.pm"); program = modelDescription.preprocess().asPrismProgram(); model = storm::builder::DdPrismModelBuilder<storm::dd::DdType::Sylvan>().build(program); EXPECT_EQ(1728ul, model->getNumberOfStates()); EXPECT_EQ(2505ul, model->getNumberOfTransitions()); } TEST(DdPrismModelBuilderTest_Cudd, Dtmc) { storm::storage::SymbolicModelDescription modelDescription = storm::parser::PrismParser::parse(STORM_TEST_RESOURCES_DIR "/dtmc/die.pm"); storm::prism::Program program = modelDescription.preprocess().asPrismProgram(); std::shared_ptr<storm::models::symbolic::Model<storm::dd::DdType::CUDD>> model = storm::builder::DdPrismModelBuilder<storm::dd::DdType::CUDD>().build(program); EXPECT_EQ(13ul, model->getNumberOfStates()); EXPECT_EQ(20ul, model->getNumberOfTransitions()); modelDescription = storm::parser::PrismParser::parse(STORM_TEST_RESOURCES_DIR "/dtmc/brp-16-2.pm"); program = modelDescription.preprocess().asPrismProgram(); model = storm::builder::DdPrismModelBuilder<storm::dd::DdType::CUDD>().build(program); EXPECT_EQ(677ul, model->getNumberOfStates()); EXPECT_EQ(867ul, model->getNumberOfTransitions()); modelDescription = storm::parser::PrismParser::parse(STORM_TEST_RESOURCES_DIR "/dtmc/crowds-5-5.pm"); program = modelDescription.preprocess().asPrismProgram(); model = storm::builder::DdPrismModelBuilder<storm::dd::DdType::CUDD>().build(program); EXPECT_EQ(8607ul, model->getNumberOfStates()); EXPECT_EQ(15113ul, model->getNumberOfTransitions()); modelDescription = storm::parser::PrismParser::parse(STORM_TEST_RESOURCES_DIR "/dtmc/leader-3-5.pm"); program = modelDescription.preprocess().asPrismProgram(); model = storm::builder::DdPrismModelBuilder<storm::dd::DdType::CUDD>().build(program); EXPECT_EQ(273ul, model->getNumberOfStates()); EXPECT_EQ(397ul, model->getNumberOfTransitions()); modelDescription = storm::parser::PrismParser::parse(STORM_TEST_RESOURCES_DIR "/dtmc/nand-5-2.pm"); program = modelDescription.preprocess().asPrismProgram(); model = storm::builder::DdPrismModelBuilder<storm::dd::DdType::CUDD>().build(program); EXPECT_EQ(1728ul, model->getNumberOfStates()); EXPECT_EQ(2505ul, model->getNumberOfTransitions()); } TEST(DdPrismModelBuilderTest_Sylvan, Ctmc) { storm::storage::SymbolicModelDescription modelDescription = storm::parser::PrismParser::parse(STORM_TEST_RESOURCES_DIR "/ctmc/cluster2.sm", true); storm::prism::Program program = modelDescription.preprocess().asPrismProgram(); std::shared_ptr<storm::models::symbolic::Model<storm::dd::DdType::Sylvan>> model = storm::builder::DdPrismModelBuilder<storm::dd::DdType::Sylvan>().build(program); EXPECT_EQ(276ul, model->getNumberOfStates()); EXPECT_EQ(1120ul, model->getNumberOfTransitions()); modelDescription = storm::parser::PrismParser::parse(STORM_TEST_RESOURCES_DIR "/ctmc/embedded2.sm", true); program = modelDescription.preprocess().asPrismProgram(); model = storm::builder::DdPrismModelBuilder<storm::dd::DdType::Sylvan>().build(program); EXPECT_EQ(3478ul, model->getNumberOfStates()); EXPECT_EQ(14639ul, model->getNumberOfTransitions()); modelDescription = storm::parser::PrismParser::parse(STORM_TEST_RESOURCES_DIR "/ctmc/polling2.sm", true); program = modelDescription.preprocess().asPrismProgram(); model = storm::builder::DdPrismModelBuilder<storm::dd::DdType::Sylvan>().build(program); EXPECT_EQ(12ul, model->getNumberOfStates()); EXPECT_EQ(22ul, model->getNumberOfTransitions()); modelDescription = storm::parser::PrismParser::parse(STORM_TEST_RESOURCES_DIR "/ctmc/fms2.sm", true); program = modelDescription.preprocess().asPrismProgram(); model = storm::builder::DdPrismModelBuilder<storm::dd::DdType::Sylvan>().build(program); EXPECT_EQ(810ul, model->getNumberOfStates()); EXPECT_EQ(3699ul, model->getNumberOfTransitions()); modelDescription = storm::parser::PrismParser::parse(STORM_TEST_RESOURCES_DIR "/ctmc/tandem5.sm", true); program = modelDescription.preprocess().asPrismProgram(); model = storm::builder::DdPrismModelBuilder<storm::dd::DdType::Sylvan>().build(program); EXPECT_EQ(66ul, model->getNumberOfStates()); EXPECT_EQ(189ul, model->getNumberOfTransitions()); } TEST(DdPrismModelBuilderTest_Cudd, Ctmc) { storm::storage::SymbolicModelDescription modelDescription = storm::parser::PrismParser::parse(STORM_TEST_RESOURCES_DIR "/ctmc/cluster2.sm", true); storm::prism::Program program = modelDescription.preprocess().asPrismProgram(); std::shared_ptr<storm::models::symbolic::Model<storm::dd::DdType::CUDD>> model = storm::builder::DdPrismModelBuilder<storm::dd::DdType::CUDD>().build(program); EXPECT_EQ(276ul, model->getNumberOfStates()); EXPECT_EQ(1120ul, model->getNumberOfTransitions()); modelDescription = storm::parser::PrismParser::parse(STORM_TEST_RESOURCES_DIR "/ctmc/embedded2.sm", true); program = modelDescription.preprocess().asPrismProgram(); model = storm::builder::DdPrismModelBuilder<storm::dd::DdType::CUDD>().build(program); EXPECT_EQ(3478ul, model->getNumberOfStates()); EXPECT_EQ(14639ul, model->getNumberOfTransitions()); modelDescription = storm::parser::PrismParser::parse(STORM_TEST_RESOURCES_DIR "/ctmc/polling2.sm", true); program = modelDescription.preprocess().asPrismProgram(); model = storm::builder::DdPrismModelBuilder<storm::dd::DdType::CUDD>().build(program); EXPECT_EQ(12ul, model->getNumberOfStates()); EXPECT_EQ(22ul, model->getNumberOfTransitions()); modelDescription = storm::parser::PrismParser::parse(STORM_TEST_RESOURCES_DIR "/ctmc/fms2.sm", true); program = modelDescription.preprocess().asPrismProgram(); model = storm::builder::DdPrismModelBuilder<storm::dd::DdType::CUDD>().build(program); EXPECT_EQ(810ul, model->getNumberOfStates()); EXPECT_EQ(3699ul, model->getNumberOfTransitions()); modelDescription = storm::parser::PrismParser::parse(STORM_TEST_RESOURCES_DIR "/ctmc/tandem5.sm", true); program = modelDescription.preprocess().asPrismProgram(); model = storm::builder::DdPrismModelBuilder<storm::dd::DdType::CUDD>().build(program); EXPECT_EQ(66ul, model->getNumberOfStates()); EXPECT_EQ(189ul, model->getNumberOfTransitions()); } TEST(DdPrismModelBuilderTest_Sylvan, Mdp) { storm::storage::SymbolicModelDescription modelDescription = storm::parser::PrismParser::parse(STORM_TEST_RESOURCES_DIR "/mdp/two_dice.nm"); storm::prism::Program program = modelDescription.preprocess().asPrismProgram(); std::shared_ptr<storm::models::symbolic::Model<storm::dd::DdType::Sylvan>> model = storm::builder::DdPrismModelBuilder<storm::dd::DdType::Sylvan>().build(program); EXPECT_TRUE(model->getType() == storm::models::ModelType::Mdp); std::shared_ptr<storm::models::symbolic::Mdp<storm::dd::DdType::Sylvan>> mdp = model->as<storm::models::symbolic::Mdp<storm::dd::DdType::Sylvan>>(); EXPECT_EQ(169ul, mdp->getNumberOfStates()); EXPECT_EQ(436ul, mdp->getNumberOfTransitions()); EXPECT_EQ(254ul, mdp->getNumberOfChoices()); modelDescription = storm::parser::PrismParser::parse(STORM_TEST_RESOURCES_DIR "/mdp/leader3.nm"); program = modelDescription.preprocess().asPrismProgram(); model = storm::builder::DdPrismModelBuilder<storm::dd::DdType::Sylvan>().build(program); EXPECT_TRUE(model->getType() == storm::models::ModelType::Mdp); mdp = model->as<storm::models::symbolic::Mdp<storm::dd::DdType::Sylvan>>(); EXPECT_EQ(364ul, mdp->getNumberOfStates()); EXPECT_EQ(654ul, mdp->getNumberOfTransitions()); EXPECT_EQ(573ul, mdp->getNumberOfChoices()); modelDescription = storm::parser::PrismParser::parse(STORM_TEST_RESOURCES_DIR "/mdp/coin2-2.nm"); program = modelDescription.preprocess().asPrismProgram(); model = storm::builder::DdPrismModelBuilder<storm::dd::DdType::Sylvan>().build(program); EXPECT_TRUE(model->getType() == storm::models::ModelType::Mdp); mdp = model->as<storm::models::symbolic::Mdp<storm::dd::DdType::Sylvan>>(); EXPECT_EQ(272ul, mdp->getNumberOfStates()); EXPECT_EQ(492ul, mdp->getNumberOfTransitions()); EXPECT_EQ(400ul, mdp->getNumberOfChoices()); modelDescription = storm::parser::PrismParser::parse(STORM_TEST_RESOURCES_DIR "/mdp/csma2-2.nm"); program = modelDescription.preprocess().asPrismProgram(); model = storm::builder::DdPrismModelBuilder<storm::dd::DdType::Sylvan>().build(program); EXPECT_TRUE(model->getType() == storm::models::ModelType::Mdp); mdp = model->as<storm::models::symbolic::Mdp<storm::dd::DdType::Sylvan>>(); EXPECT_EQ(1038ul, mdp->getNumberOfStates()); EXPECT_EQ(1282ul, mdp->getNumberOfTransitions()); EXPECT_EQ(1054ul, mdp->getNumberOfChoices()); modelDescription = storm::parser::PrismParser::parse(STORM_TEST_RESOURCES_DIR "/mdp/firewire3-0.5.nm"); program = modelDescription.preprocess().asPrismProgram(); model = storm::builder::DdPrismModelBuilder<storm::dd::DdType::Sylvan>().build(program); EXPECT_TRUE(model->getType() == storm::models::ModelType::Mdp); mdp = model->as<storm::models::symbolic::Mdp<storm::dd::DdType::Sylvan>>(); EXPECT_EQ(4093ul, mdp->getNumberOfStates()); EXPECT_EQ(5585ul, mdp->getNumberOfTransitions()); EXPECT_EQ(5519ul, mdp->getNumberOfChoices()); modelDescription = storm::parser::PrismParser::parse(STORM_TEST_RESOURCES_DIR "/mdp/wlan0-2-2.nm"); program = modelDescription.preprocess().asPrismProgram(); model = storm::builder::DdPrismModelBuilder<storm::dd::DdType::Sylvan>().build(program); EXPECT_TRUE(model->getType() == storm::models::ModelType::Mdp); mdp = model->as<storm::models::symbolic::Mdp<storm::dd::DdType::Sylvan>>(); EXPECT_EQ(37ul, mdp->getNumberOfStates()); EXPECT_EQ(59ul, mdp->getNumberOfTransitions()); EXPECT_EQ(59ul, mdp->getNumberOfChoices()); } TEST(DdPrismModelBuilderTest_Cudd, Mdp) { storm::storage::SymbolicModelDescription modelDescription = storm::parser::PrismParser::parse(STORM_TEST_RESOURCES_DIR "/mdp/two_dice.nm"); storm::prism::Program program = modelDescription.preprocess().asPrismProgram(); std::shared_ptr<storm::models::symbolic::Model<storm::dd::DdType::CUDD>> model = storm::builder::DdPrismModelBuilder<storm::dd::DdType::CUDD>().build(program); EXPECT_TRUE(model->getType() == storm::models::ModelType::Mdp); std::shared_ptr<storm::models::symbolic::Mdp<storm::dd::DdType::CUDD>> mdp = model->as<storm::models::symbolic::Mdp<storm::dd::DdType::CUDD>>(); EXPECT_EQ(169ul, mdp->getNumberOfStates()); EXPECT_EQ(436ul, mdp->getNumberOfTransitions()); EXPECT_EQ(254ul, mdp->getNumberOfChoices()); modelDescription = storm::parser::PrismParser::parse(STORM_TEST_RESOURCES_DIR "/mdp/leader3.nm"); program = modelDescription.preprocess().asPrismProgram(); model = storm::builder::DdPrismModelBuilder<storm::dd::DdType::CUDD>().build(program); EXPECT_TRUE(model->getType() == storm::models::ModelType::Mdp); mdp = model->as<storm::models::symbolic::Mdp<storm::dd::DdType::CUDD>>(); EXPECT_EQ(364ul, mdp->getNumberOfStates()); EXPECT_EQ(654ul, mdp->getNumberOfTransitions()); EXPECT_EQ(573ul, mdp->getNumberOfChoices()); modelDescription = storm::parser::PrismParser::parse(STORM_TEST_RESOURCES_DIR "/mdp/coin2-2.nm"); program = modelDescription.preprocess().asPrismProgram(); model = storm::builder::DdPrismModelBuilder<storm::dd::DdType::CUDD>().build(program); EXPECT_TRUE(model->getType() == storm::models::ModelType::Mdp); mdp = model->as<storm::models::symbolic::Mdp<storm::dd::DdType::CUDD>>(); EXPECT_EQ(272ul, mdp->getNumberOfStates()); EXPECT_EQ(492ul, mdp->getNumberOfTransitions()); EXPECT_EQ(400ul, mdp->getNumberOfChoices()); modelDescription = storm::parser::PrismParser::parse(STORM_TEST_RESOURCES_DIR "/mdp/csma2-2.nm"); program = modelDescription.preprocess().asPrismProgram(); model = storm::builder::DdPrismModelBuilder<storm::dd::DdType::CUDD>().build(program); EXPECT_TRUE(model->getType() == storm::models::ModelType::Mdp); mdp = model->as<storm::models::symbolic::Mdp<storm::dd::DdType::CUDD>>(); EXPECT_EQ(1038ul, mdp->getNumberOfStates()); EXPECT_EQ(1282ul, mdp->getNumberOfTransitions()); EXPECT_EQ(1054ul, mdp->getNumberOfChoices()); modelDescription = storm::parser::PrismParser::parse(STORM_TEST_RESOURCES_DIR "/mdp/firewire3-0.5.nm"); program = modelDescription.preprocess().asPrismProgram(); model = storm::builder::DdPrismModelBuilder<storm::dd::DdType::CUDD>().build(program); EXPECT_TRUE(model->getType() == storm::models::ModelType::Mdp); mdp = model->as<storm::models::symbolic::Mdp<storm::dd::DdType::CUDD>>(); EXPECT_EQ(4093ul, mdp->getNumberOfStates()); EXPECT_EQ(5585ul, mdp->getNumberOfTransitions()); EXPECT_EQ(5519ul, mdp->getNumberOfChoices()); modelDescription = storm::parser::PrismParser::parse(STORM_TEST_RESOURCES_DIR "/mdp/wlan0-2-2.nm"); program = modelDescription.preprocess().asPrismProgram(); model = storm::builder::DdPrismModelBuilder<storm::dd::DdType::CUDD>().build(program); EXPECT_TRUE(model->getType() == storm::models::ModelType::Mdp); mdp = model->as<storm::models::symbolic::Mdp<storm::dd::DdType::CUDD>>(); EXPECT_EQ(37ul, mdp->getNumberOfStates()); EXPECT_EQ(59ul, mdp->getNumberOfTransitions()); EXPECT_EQ(59ul, mdp->getNumberOfChoices()); } TEST(DdPrismModelBuilderTest_Sylvan, Composition) { storm::storage::SymbolicModelDescription modelDescription = storm::parser::PrismParser::parse(STORM_TEST_RESOURCES_DIR "/mdp/system_composition.nm"); storm::prism::Program program = modelDescription.preprocess().asPrismProgram(); std::shared_ptr<storm::models::symbolic::Model<storm::dd::DdType::Sylvan>> model = storm::builder::DdPrismModelBuilder<storm::dd::DdType::Sylvan>().build(program); EXPECT_TRUE(model->getType() == storm::models::ModelType::Mdp); std::shared_ptr<storm::models::symbolic::Mdp<storm::dd::DdType::Sylvan>> mdp = model->as<storm::models::symbolic::Mdp<storm::dd::DdType::Sylvan>>(); EXPECT_EQ(21ul, mdp->getNumberOfStates()); EXPECT_EQ(61ul, mdp->getNumberOfTransitions()); EXPECT_EQ(61ul, mdp->getNumberOfChoices()); modelDescription = storm::parser::PrismParser::parse(STORM_TEST_RESOURCES_DIR "/mdp/system_composition2.nm"); program = modelDescription.preprocess().asPrismProgram(); model = storm::builder::DdPrismModelBuilder<storm::dd::DdType::Sylvan>().build(program); EXPECT_TRUE(model->getType() == storm::models::ModelType::Mdp); mdp = model->as<storm::models::symbolic::Mdp<storm::dd::DdType::Sylvan>>(); EXPECT_EQ(8ul, mdp->getNumberOfStates()); EXPECT_EQ(21ul, mdp->getNumberOfTransitions()); EXPECT_EQ(21ul, mdp->getNumberOfChoices()); } TEST(DdPrismModelBuilderTest_Cudd, Composition) { storm::storage::SymbolicModelDescription modelDescription = storm::parser::PrismParser::parse(STORM_TEST_RESOURCES_DIR "/mdp/system_composition.nm"); storm::prism::Program program = modelDescription.preprocess().asPrismProgram(); std::shared_ptr<storm::models::symbolic::Model<storm::dd::DdType::CUDD>> model = storm::builder::DdPrismModelBuilder<storm::dd::DdType::CUDD>().build(program); EXPECT_TRUE(model->getType() == storm::models::ModelType::Mdp); std::shared_ptr<storm::models::symbolic::Mdp<storm::dd::DdType::CUDD>> mdp = model->as<storm::models::symbolic::Mdp<storm::dd::DdType::CUDD>>(); EXPECT_EQ(21ul, mdp->getNumberOfStates()); EXPECT_EQ(61ul, mdp->getNumberOfTransitions()); EXPECT_EQ(61ul, mdp->getNumberOfChoices()); modelDescription = storm::parser::PrismParser::parse(STORM_TEST_RESOURCES_DIR "/mdp/system_composition2.nm"); program = modelDescription.preprocess().asPrismProgram(); model = storm::builder::DdPrismModelBuilder<storm::dd::DdType::CUDD>().build(program); EXPECT_TRUE(model->getType() == storm::models::ModelType::Mdp); mdp = model->as<storm::models::symbolic::Mdp<storm::dd::DdType::CUDD>>(); EXPECT_EQ(8ul, mdp->getNumberOfStates()); EXPECT_EQ(21ul, mdp->getNumberOfTransitions()); EXPECT_EQ(21ul, mdp->getNumberOfChoices()); }
58.23913
167
0.726284
[ "model" ]
fef487d9fff64e68f0aa668003e99d590bdaec7d
1,367
cpp
C++
130. Surrounded Regions.cpp
rajeev-ranjan-au6/Leetcode_Cpp
f64cd98ab96ec110f1c21393f418acf7d88473e8
[ "MIT" ]
3
2020-12-30T00:29:59.000Z
2021-01-24T22:43:04.000Z
130. Surrounded Regions.cpp
rajeevranjancom/Leetcode_Cpp
f64cd98ab96ec110f1c21393f418acf7d88473e8
[ "MIT" ]
null
null
null
130. Surrounded Regions.cpp
rajeevranjancom/Leetcode_Cpp
f64cd98ab96ec110f1c21393f418acf7d88473e8
[ "MIT" ]
null
null
null
class Solution { public: void solve(vector<vector<char>>& board) { if(board.empty()) return; int m = board.size(), n = board[0].size(); vector<vector<int>>visited(m, vector<int>(n, 0)); for(int i = 0; i < m; i++) for(int j = 0; j < n; j++){ if(visited[i][j] || board[i][j] == 'X') continue; bool surrounded = DFS(board, visited, i, j, m, n); if(surrounded) replace(board, i, j, m, n); } } bool DFS(vector<vector<char>>& board, vector<vector<int>>& visited, int r, int c, int m, int n){ if(r < 0 || r == m || c < 0 || c == n) return false; if(board[r][c] == 'X' || visited[r][c]) return true; visited[r][c] = 1; bool L = DFS(board, visited, r, c - 1, m, n); bool R = DFS(board, visited, r, c + 1, m, n); bool U = DFS(board, visited, r - 1, c, m, n); bool D = DFS(board, visited, r + 1, c, m, n); return L && R && U && D; } void replace(vector<vector<char>>& board, int r, int c, int m, int n){ if(r < 0 || r == m || c < 0 || c == n || board[r][c] == 'X') return; board[r][c] = 'X'; replace(board, r + 1, c, m, n); replace(board, r - 1, c, m, n); replace(board, r, c + 1, m, n); replace(board, r, c - 1, m, n); } };
39.057143
100
0.452816
[ "vector" ]
679684e261ac31ac5b9ecc8a2bdc2dee5c964bf3
10,149
cc
C++
chrome/browser/local_discovery/privetv3_session_unittest.cc
hefen1/chromium
52f0b6830e000ca7c5e9aa19488af85be792cc88
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/local_discovery/privetv3_session_unittest.cc
hefen1/chromium
52f0b6830e000ca7c5e9aa19488af85be792cc88
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/local_discovery/privetv3_session_unittest.cc
hefen1/chromium
52f0b6830e000ca7c5e9aa19488af85be792cc88
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2020-04-04T13:34:56.000Z
2020-11-04T07:17:52.000Z
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/local_discovery/privetv3_session.h" #include "base/base64.h" #include "base/strings/stringprintf.h" #include "chrome/browser/local_discovery/privet_http.h" #include "content/public/test/test_utils.h" #include "crypto/hmac.h" #include "crypto/p224_spake.h" #include "net/url_request/test_url_fetcher_factory.h" #include "net/url_request/url_request_test_util.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace local_discovery { namespace { using testing::InSequence; using testing::Invoke; using testing::SaveArg; using testing::StrictMock; using testing::_; using PairingType = PrivetV3Session::PairingType; using Result = PrivetV3Session::Result; const char kInfoResponse[] = "{\"version\":\"3.0\"," "\"endpoints\":{\"httpsPort\": 443}," "\"authentication\":{" " \"mode\":[\"anonymous\",\"pairing\",\"cloud\"]," " \"pairing\":[\"pinCode\",\"embeddedCode\"]," " \"crypto\":[\"p224_spake2\"]" "}}"; class MockPrivetHTTPClient : public PrivetHTTPClient { public: MockPrivetHTTPClient() { request_context_ = new net::TestURLRequestContextGetter(base::MessageLoopProxy::current()); } MOCK_METHOD0(GetName, const std::string&()); MOCK_METHOD1( CreateInfoOperationPtr, PrivetJSONOperation*(const PrivetJSONOperation::ResultCallback&)); virtual void RefreshPrivetToken( const PrivetURLFetcher::TokenCallback& callback) override { FAIL(); } virtual scoped_ptr<PrivetJSONOperation> CreateInfoOperation( const PrivetJSONOperation::ResultCallback& callback) override { return make_scoped_ptr(CreateInfoOperationPtr(callback)); } virtual scoped_ptr<PrivetURLFetcher> CreateURLFetcher( const GURL& url, net::URLFetcher::RequestType request_type, PrivetURLFetcher::Delegate* delegate) override { return make_scoped_ptr(new PrivetURLFetcher( url, request_type, request_context_.get(), delegate)); } scoped_refptr<net::TestURLRequestContextGetter> request_context_; }; } // namespace class PrivetV3SessionTest : public testing::Test { public: PrivetV3SessionTest() : fetcher_factory_(nullptr), session_(make_scoped_ptr(new MockPrivetHTTPClient())) {} virtual ~PrivetV3SessionTest() {} MOCK_METHOD2(OnInitialized, void(Result, const std::vector<PairingType>&)); MOCK_METHOD1(OnPairingStarted, void(Result)); MOCK_METHOD1(OnCodeConfirmed, void(Result)); MOCK_METHOD2(OnMessageSend, void(Result, const base::DictionaryValue& value)); MOCK_METHOD1(OnPostData, void(const base::DictionaryValue& data)); protected: virtual void SetUp() override { EXPECT_CALL(*this, OnInitialized(_, _)).Times(0); EXPECT_CALL(*this, OnPairingStarted(_)).Times(0); EXPECT_CALL(*this, OnCodeConfirmed(_)).Times(0); EXPECT_CALL(*this, OnMessageSend(_, _)).Times(0); EXPECT_CALL(*this, OnPostData(_)).Times(0); session_.on_post_data_ = base::Bind(&PrivetV3SessionTest::OnPostData, base::Unretained(this)); } base::MessageLoop loop_; base::Closure quit_closure_; net::FakeURLFetcherFactory fetcher_factory_; PrivetV3Session session_; }; TEST_F(PrivetV3SessionTest, InitError) { EXPECT_CALL(*this, OnInitialized(Result::STATUS_CONNECTIONERROR, _)).Times(1); fetcher_factory_.SetFakeResponse(GURL("http://host/privet/info"), "", net::HTTP_OK, net::URLRequestStatus::FAILED); session_.Init( base::Bind(&PrivetV3SessionTest::OnInitialized, base::Unretained(this))); base::RunLoop().RunUntilIdle(); } TEST_F(PrivetV3SessionTest, VersionError) { std::string response(kInfoResponse); ReplaceFirstSubstringAfterOffset(&response, 0, "3.0", "4.1"); EXPECT_CALL(*this, OnInitialized(Result::STATUS_SESSIONERROR, _)).Times(1); fetcher_factory_.SetFakeResponse(GURL("http://host/privet/info"), response, net::HTTP_OK, net::URLRequestStatus::SUCCESS); session_.Init( base::Bind(&PrivetV3SessionTest::OnInitialized, base::Unretained(this))); base::RunLoop().RunUntilIdle(); } TEST_F(PrivetV3SessionTest, ModeError) { std::string response(kInfoResponse); ReplaceFirstSubstringAfterOffset(&response, 0, "mode", "mode_"); EXPECT_CALL(*this, OnInitialized(Result::STATUS_SESSIONERROR, _)).Times(1); fetcher_factory_.SetFakeResponse(GURL("http://host/privet/info"), response, net::HTTP_OK, net::URLRequestStatus::SUCCESS); session_.Init( base::Bind(&PrivetV3SessionTest::OnInitialized, base::Unretained(this))); base::RunLoop().RunUntilIdle(); } TEST_F(PrivetV3SessionTest, Pairing) { std::vector<PairingType> pairings; EXPECT_CALL(*this, OnInitialized(Result::STATUS_SUCCESS, _)) .WillOnce(SaveArg<1>(&pairings)); fetcher_factory_.SetFakeResponse(GURL("http://host/privet/info"), kInfoResponse, net::HTTP_OK, net::URLRequestStatus::SUCCESS); session_.Init( base::Bind(&PrivetV3SessionTest::OnInitialized, base::Unretained(this))); base::RunLoop().RunUntilIdle(); EXPECT_EQ(2u, pairings.size()); EXPECT_EQ(PairingType::PAIRING_TYPE_PINCODE, pairings[0]); EXPECT_EQ(PairingType::PAIRING_TYPE_EMBEDDEDCODE, pairings[1]); crypto::P224EncryptedKeyExchange spake( crypto::P224EncryptedKeyExchange::kPeerTypeServer, "testPin"); EXPECT_CALL(*this, OnPairingStarted(Result::STATUS_SUCCESS)).Times(1); EXPECT_CALL(*this, OnPostData(_)) .WillOnce( testing::Invoke([this, &spake](const base::DictionaryValue& data) { std::string pairing_type; EXPECT_TRUE(data.GetString("pairing", &pairing_type)); EXPECT_EQ("embeddedCode", pairing_type); std::string crypto_type; EXPECT_TRUE(data.GetString("crypto", &crypto_type)); EXPECT_EQ("p224_spake2", crypto_type); std::string device_commitment; base::Base64Encode(spake.GetNextMessage(), &device_commitment); fetcher_factory_.SetFakeResponse( GURL("http://host/privet/v3/pairing/start"), base::StringPrintf( "{\"deviceCommitment\":\"%s\",\"sessionId\":\"testId\"}", device_commitment.c_str()), net::HTTP_OK, net::URLRequestStatus::SUCCESS); })); session_.StartPairing(PairingType::PAIRING_TYPE_EMBEDDEDCODE, base::Bind(&PrivetV3SessionTest::OnPairingStarted, base::Unretained(this))); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(session_.fingerprint_.empty()); EXPECT_EQ("Privet anonymous", session_.privet_auth_token_); EXPECT_CALL(*this, OnCodeConfirmed(Result::STATUS_SUCCESS)).Times(1); InSequence in_sequence; EXPECT_CALL(*this, OnPostData(_)) .WillOnce( testing::Invoke([this, &spake](const base::DictionaryValue& data) { std::string commitment_base64; EXPECT_TRUE(data.GetString("clientCommitment", &commitment_base64)); std::string commitment; EXPECT_TRUE(base::Base64Decode(commitment_base64, &commitment)); std::string session_id; EXPECT_TRUE(data.GetString("sessionId", &session_id)); EXPECT_EQ("testId", session_id); EXPECT_EQ(spake.ProcessMessage(commitment), crypto::P224EncryptedKeyExchange::kResultPending); std::string fingerprint("testFinterprint"); std::string fingerprint_base64; base::Base64Encode(fingerprint, &fingerprint_base64); crypto::HMAC hmac(crypto::HMAC::SHA256); const std::string& key = spake.GetUnverifiedKey(); EXPECT_TRUE(hmac.Init(key)); std::string signature(hmac.DigestLength(), ' '); EXPECT_TRUE(hmac.Sign(fingerprint, reinterpret_cast<unsigned char*>( string_as_array(&signature)), signature.size())); std::string signature_base64; base::Base64Encode(signature, &signature_base64); fetcher_factory_.SetFakeResponse( GURL("http://host/privet/v3/pairing/confirm"), base::StringPrintf( "{\"certFingerprint\":\"%s\",\"certSignature\":\"%s\"}", fingerprint_base64.c_str(), signature_base64.c_str()), net::HTTP_OK, net::URLRequestStatus::SUCCESS); })); EXPECT_CALL(*this, OnPostData(_)) .WillOnce( testing::Invoke([this, &spake](const base::DictionaryValue& data) { std::string access_token_base64; EXPECT_TRUE(data.GetString("authCode", &access_token_base64)); std::string access_token; EXPECT_TRUE(base::Base64Decode(access_token_base64, &access_token)); crypto::HMAC hmac(crypto::HMAC::SHA256); const std::string& key = spake.GetUnverifiedKey(); EXPECT_TRUE(hmac.Init(key)); EXPECT_TRUE(hmac.Verify("testId", access_token)); fetcher_factory_.SetFakeResponse( GURL("http://host/privet/v3/auth"), "{\"accessToken\":\"567\",\"tokenType\":\"testType\"," "\"scope\":\"owner\"}", net::HTTP_OK, net::URLRequestStatus::SUCCESS); })); session_.ConfirmCode("testPin", base::Bind(&PrivetV3SessionTest::OnCodeConfirmed, base::Unretained(this))); base::RunLoop().RunUntilIdle(); EXPECT_FALSE(session_.fingerprint_.empty()); EXPECT_EQ("testType 567", session_.privet_auth_token_); } // TODO(vitalybuka): replace PrivetHTTPClient with regular URL fetcher and // implement SendMessage test. } // namespace local_discovery
39.034615
80
0.658291
[ "vector" ]
679a8d0f61d6db94388e814d27f76dfc3cd29952
1,111
hpp
C++
inference-engine/src/low_precision_transformations/include/low_precision/reduce_base_transformation.hpp
NikDemoShow/openvino
31907e51e96f1603753dc69811bdf738374ca5e6
[ "Apache-2.0" ]
1
2022-02-10T08:05:09.000Z
2022-02-10T08:05:09.000Z
inference-engine/src/low_precision_transformations/include/low_precision/reduce_base_transformation.hpp
NikDemoShow/openvino
31907e51e96f1603753dc69811bdf738374ca5e6
[ "Apache-2.0" ]
40
2020-12-04T07:46:57.000Z
2022-02-21T13:04:40.000Z
inference-engine/src/low_precision_transformations/include/low_precision/reduce_base_transformation.hpp
NikDemoShow/openvino
31907e51e96f1603753dc69811bdf738374ca5e6
[ "Apache-2.0" ]
3
2021-04-25T06:52:41.000Z
2021-05-07T02:01:44.000Z
// Copyright (C) 2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #pragma once #include <memory> #include <ngraph/ngraph.hpp> #include "layer_transformation.hpp" namespace ngraph { namespace pass { namespace low_precision { /** * @brief ReduceBaseTransformation: base class for Reduce*Transformation * detects dequantization operations in front of the Reduce* layer and * propagates them through the Reduce* if possible * */ class TRANSFORMATIONS_API ReduceBaseTransformation : public LayerTransformation { public: ReduceBaseTransformation(const Params& params); bool transform(TransformationContext& context, ngraph::pattern::Matcher& m) const override; bool canBeTransformed(const TransformationContext& context, std::shared_ptr<Node> reduce) const override; protected: virtual void changeDequantizationValues( const std::shared_ptr<Node>& reduce, FakeQuantizeDequantization& dequantization) const; virtual bool getUpdatePrecision(const std::shared_ptr<Node>& reduce) const; }; } // namespace low_precision } // namespace pass } // namespace ngraph
29.236842
109
0.771377
[ "transform" ]
679f436e7de105f935e7c435e43bd5bd8a2cf3a5
8,931
cc
C++
src/system/van.cc
wakensky/parameter_server
12f9e086ca637366fdf3a5e5292ad8234e2b214e
[ "Apache-2.0" ]
null
null
null
src/system/van.cc
wakensky/parameter_server
12f9e086ca637366fdf3a5e5292ad8234e2b214e
[ "Apache-2.0" ]
null
null
null
src/system/van.cc
wakensky/parameter_server
12f9e086ca637366fdf3a5e5292ad8234e2b214e
[ "Apache-2.0" ]
null
null
null
#include "system/van.h" #include <string.h> #include <zmq.h> #include "base/shared_array_inl.h" #include "util/local_machine.h" namespace PS { DEFINE_string(my_node, "role:SCHEDULER,hostname:'127.0.0.1',port:8000,id:'H'", "my node"); DEFINE_string(scheduler, "role:SCHEDULER,hostname:'127.0.0.1',port:8000,id:'H'", "the scheduler node"); DEFINE_string(server_master, "", "the master of servers"); DEFINE_int32(num_retries, 3, "number of retries for zmq"); DEFINE_bool(compress_message, true, ""); DEFINE_bool(print_van, false, ""); DEFINE_int32(my_rank, -1, "my rank among MPI peers"); DEFINE_string(interface, "", "network interface"); DECLARE_int32(num_workers); DECLARE_int32(num_servers); void Van::init() { scheduler_ = parseNode(FLAGS_scheduler); num_retries_ = std::max(0, FLAGS_num_retries); // assemble my_node_ if (FLAGS_my_rank < 0) { LL << "You must pass me -my_rank with a valid value (GE 0)"; throw std::runtime_error("invalid my_rank"); } else if (0 == FLAGS_my_rank) { my_node_ = scheduler_; } else { my_node_ = assembleMyNode(); } LI << "I am [" << my_node_.ShortDebugString() << "]; pid:" << getpid(); context_ = zmq_ctx_new(); // TODO the following does not work... // zmq_ctx_set(context_, ZMQ_MAX_SOCKETS, 1000000); // zmq_ctx_set(context_, ZMQ_IO_THREADS, 4); // LL << "ZMQ_MAX_SOCKETS: " << zmq_ctx_get(context_, ZMQ_MAX_SOCKETS); CHECK(context_ != NULL) << "create 0mq context failed"; bind(); connect(my_node_); connect(scheduler_); if (FLAGS_print_van) { debug_out_.open("van_"+my_node_.id()); } } void Van::destroy() { for (auto& it : senders_) zmq_close (it.second); zmq_close (receiver_); zmq_ctx_destroy (context_); } void Van::bind() { receiver_ = zmq_socket(context_, ZMQ_ROUTER); CHECK(receiver_ != NULL) << "create receiver socket failed: " << zmq_strerror(errno); CHECK(my_node_.has_port()) << my_node_.ShortDebugString(); string addr = "tcp://*:" + std::to_string(my_node_.port()); // string addr = "tcp://" + address(my_node_); CHECK(zmq_bind(receiver_, addr.c_str()) == 0) << "bind to " << addr << " failed: " << zmq_strerror(errno); if (FLAGS_print_van) { debug_out_ << my_node_.id() << ": binds address " << addr << std::endl; } } Status Van::connect(Node const& node) { CHECK(node.has_id()) << node.ShortDebugString(); CHECK(node.has_port()) << node.ShortDebugString(); CHECK(node.has_hostname()) << node.ShortDebugString(); NodeID id = node.id(); // the socket already exists? probably we are re-connecting to this node if (senders_.find(id) != senders_.end()) { // zmq_close (senders_[id]); return Status::OK(); } void *sender = zmq_socket(context_, ZMQ_DEALER); CHECK(sender != NULL) << zmq_strerror(errno); string my_id = my_node_.id(); // address(my_node_); zmq_setsockopt (sender, ZMQ_IDENTITY, my_id.data(), my_id.size()); // TODO is it useful? // uint64_t hwm = 5000000; // zmq_setsockopt (sender, ZMQ_SNDHWM, &hwm, sizeof(hwm)); // connect string addr = "tcp://" + address(node); if (zmq_connect(sender, addr.c_str()) != 0) return Status:: NetError( "connect to " + addr + " failed: " + zmq_strerror(errno)); senders_[id] = sender; if (FLAGS_print_van) { debug_out_ << my_node_.id() << ": connect to " << addr << std::endl; } return Status::OK(); } // TODO use zmq_msg_t to allow zero_copy send // btw, it is not thread safe Status Van::send(const MessageCPtr& msg, size_t& send_bytes) { send_bytes = 0; // find the socket NodeID id = msg->recver; auto it = senders_.find(id); if (it == senders_.end()) return Status::NotFound("there is no socket to node " + (id)); void *socket = it->second; // fill data auto task = msg->task; task.clear_uncompressed_size(); bool has_key = !msg->key.empty(); std::vector<SArray<char> > data; if (FLAGS_compress_message) { if (has_key) { data.push_back(msg->key.compressTo()); task.add_uncompressed_size(msg->key.size()); } for (auto& m : msg->value) { if (m.empty()) continue; data.push_back(m.compressTo()); task.add_uncompressed_size(m.size()); } } else { if (has_key) data.push_back(msg->key); for (auto& m : msg->value) { if (m.empty()) continue; data.push_back(m); } } // send task string str; task.set_has_key(has_key); CHECK(task.SerializeToString(&str)) << "failed to serialize " << task.ShortDebugString(); int tag = ZMQ_SNDMORE; if (data.size() == 0) tag = 0; // ZMQ_DONTWAIT; while (true) { if (zmq_send(socket, str.c_str(), str.size(), tag) == str.size()) break; if (errno == EINTR) continue; // maybe interupted by google profiler return Status::NetError( "failed to send mailer to node " + (id) + zmq_strerror(errno)); } data_sent_ += str.size(); // send key and value for (int i = 0; i < data.size(); ++i) { const auto& raw = data[i]; if (i == data.size() - 1) tag = 0; // ZMQ_DONTWAIT; send_bytes += raw.size(); while (true) { if (zmq_send(socket, raw.data(), raw.size(), tag) == raw.size()) break; if (errno == EINTR) continue; // maybe interupted by google profiler return Status::NetError( "failed to send mailer to node " + (id) + zmq_strerror(errno)); } data_sent_ += raw.size(); } if (FLAGS_print_van) { debug_out_ << "\tSND " << msg->shortDebugString()<< std::endl; } return Status::OK(); } // TODO Zero copy Status Van::recv(const MessagePtr& msg, size_t& recv_bytes) { recv_bytes = 0; msg->key = SArray<char>(); msg->value.clear(); NodeID sender; for (int i = 0; ; ++i) { zmq_msg_t zmsg; CHECK(zmq_msg_init(&zmsg) == 0) << zmq_strerror(errno); while (true) { if (zmq_msg_recv(&zmsg, receiver_, 0) != -1) break; if (errno == EINTR) continue; // maybe interupted by google profiler return Status::NetError( "recv message failed: " + std::string(zmq_strerror(errno))); } char* buf = (char *)zmq_msg_data(&zmsg); CHECK(buf != NULL); size_t size = zmq_msg_size(&zmsg); data_received_ += size; recv_bytes += size; if (i == 0) { // identify sender = id(std::string(buf, size)); msg->sender = sender; msg->recver = my_node_.id(); } else if (i == 1) { // task CHECK(msg->task.ParseFromString(std::string(buf, size))) << "parse string failed"; } else { // key and value SArray<char> data; int n = msg->task.uncompressed_size_size(); if (n > 0) { // data are compressed CHECK_GT(n, i - 2); data.resize(msg->task.uncompressed_size(i-2)+16); data.uncompressFrom(buf, size); } else { // data are not compressed // data = SArray<char>(buf, buf+size); data.copyFrom(buf, size); } if (i == 2 && msg->task.has_key()) { msg->key = data; } else { msg->value.push_back(data); } } zmq_msg_close(&zmsg); if (!zmq_msg_more(&zmsg)) { CHECK_GT(i, 0); break; } } if (FLAGS_print_van) { debug_out_ << "\tRCV " << msg->shortDebugString() << std::endl; } return Status::OK();; } void Van::statistic() { if (my_node_.role() == Node::UNUSED || my_node_.role() == Node::SCHEDULER) return; auto gb = [](size_t x) { return x / 1e9; }; LI << my_node_.id() << " sent " << gb(data_sent_) << " Gbyte, received " << gb(data_received_) << " Gbyte"; } Node Van::assembleMyNode() { if (0 == FLAGS_my_rank) { return scheduler_; } Node ret_node; // role and id if (FLAGS_my_rank <= FLAGS_num_workers) { ret_node.set_role(Node::WORKER); ret_node.set_id("W" + std::to_string(FLAGS_my_rank - 1)); } else if (FLAGS_my_rank <= FLAGS_num_workers + FLAGS_num_servers) { ret_node.set_role(Node::SERVER); ret_node.set_id("S" + std::to_string(FLAGS_my_rank - FLAGS_num_workers - 1)); } else { ret_node.set_role(Node::UNUSED); ret_node.set_id("U" + std::to_string( FLAGS_my_rank - FLAGS_num_workers - FLAGS_num_servers - 1)); } // IP, port and interface string ip; unsigned short port; if (FLAGS_interface.empty()) { LocalMachine::pickupAvailableInterfaceAndIP(FLAGS_interface, ip); } else { LocalMachine::IP(FLAGS_interface); } if (ip.empty() || FLAGS_interface.empty()) { throw std::runtime_error("got interface/ip failed"); } port = LocalMachine::pickupAvailablePort(); if (0 == port) { throw std::runtime_error("got port failed"); } ret_node.set_hostname(ip); ret_node.set_port(static_cast<int32>(port)); return ret_node; } Status Van::connectivity(const string &node_id) { auto it = senders_.find(node_id); if (senders_.end() != it) { return Status::OK(); } else { return Status::NotFound("there is no socket to node " + node_id); } } } // namespace PS
30.377551
103
0.625574
[ "vector" ]
67a88e9842d955eff583162f96b5335b8045929e
13,625
cpp
C++
nucleus/applications/bookmark_tools/js_marks_maker.cpp
fredhamster/feisty_meow
66dc4221dc485a5cf9e28b724fe36268e8843043
[ "Apache-2.0" ]
2
2019-01-22T23:34:37.000Z
2021-10-31T15:44:15.000Z
nucleus/applications/bookmark_tools/js_marks_maker.cpp
fredhamster/feisty_meow
66dc4221dc485a5cf9e28b724fe36268e8843043
[ "Apache-2.0" ]
2
2020-06-01T16:35:46.000Z
2021-10-05T21:02:09.000Z
nucleus/applications/bookmark_tools/js_marks_maker.cpp
fredhamster/feisty_meow
66dc4221dc485a5cf9e28b724fe36268e8843043
[ "Apache-2.0" ]
null
null
null
/*****************************************************************************\ * * * Name : marks_maker_javascript * * Author : Chris Koeritz * * * * Purpose: * * * * Turns a link database in HOOPLE format into a web page, when given a * * suitable template file. The template file must have the phrase: * * $INSERT_LINKS_HERE * * at the point where the generated links are supposed to be stored. * * * ******************************************************************************* * Copyright (c) 2005-$now By Author. 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 is online at: * * http://www.fsf.org/copyleft/gpl.html * * Please send any updates to: fred@gruntose.com * \*****************************************************************************/ #include "bookmark_tree.h" #include <application/command_line.h> #include <application/hoople_main.h> #include <basis/astring.h> #include <basis/functions.h> #include <basis/guards.h> #include <filesystem/byte_filer.h> #include <filesystem/filename.h> #include <loggers/file_logger.h> #include <structures/stack.h> #include <structures/static_memory_gremlin.h> #include <textual/list_parsing.h> #include <timely/time_stamp.h> using namespace application; using namespace basis; using namespace filesystem; using namespace loggers; using namespace nodes; using namespace structures; using namespace textual; using namespace timely; //#define DEBUG_MARKS // uncomment to have more debugging noise. #undef BASE_LOG #define BASE_LOG(s) program_wide_logger::get().log(s, ALWAYS_PRINT) #undef LOG #define LOG(s) CLASS_EMERGENCY_LOG(program_wide_logger::get(), \ a_sprintf("line %d: ", _categories._line_number) + s, ALWAYS_PRINT) const int MAX_FILE_SIZE = 4 * MEGABYTE; // the largest file we'll read. //////////////////////////////////////////////////////////////////////////// class marks_maker_javascript : public application_shell { public: marks_maker_javascript() : application_shell(), _need_closure(false), _loader_count(0), _link_spool(0), _functions_pending(0) {} DEFINE_CLASS_NAME("marks_maker_javascript"); virtual int execute(); int print_instructions(const filename &program_name); int write_marks_page(const astring &output_filename, const astring &template_filename); // given a tree of links, this writes out a web page to "output_filename" // using a template file "template_filename". private: bookmark_tree _categories; // our tree of categories. bool _need_closure; // true if our <div> needs a closure. int _loader_count; // count of the loader functions. int _link_spool; // count of which link we're writing. stack<astring> _functions_pending; // used for javascript node functions. //this needs to gather any strings that would have gone into functions. //instead, they need to be written into the current node's string. //when a new function def would be seen, then we need to push a new node //for accumulating the text. // these handle outputting text for categories and links. void write_category(inner_mark_tree *node, astring &output); void write_link(inner_mark_tree *node, const link_record &linko, astring &output); }; //////////////////////////////////////////////////////////////////////////// int marks_maker_javascript::print_instructions(const filename &program_name) { a_sprintf to_show("%s:\n\ This program needs three filenames as command line parameters. The -i flag\n\ is used to specify the input filename, the -t flag specifies a template web\n\ page which is used as the wrapper around the links, and the -o flag specifies\n\ the web page to be created. The input file is expected to be in the HOOPLE\n\ link database format. The output file will be created from the template file\n\ by finding the phrase $INSERT_LINKS_HERE in it and replacing that with html\n\ formatted link and categories from the input file. Another tag of $TODAYS_DATE\n\ will be replaced with the date when the output file is regenerated.\n\ The HOOPLE link format is documented here:\n\ http://feistymeow.org/guides/link_database/format_manifesto.txt\n\ ", program_name.basename().raw().s(), program_name.basename().raw().s()); program_wide_logger::get().log(to_show, ALWAYS_PRINT); return 12; } void marks_maker_javascript::write_category(inner_mark_tree *node, astring &output) { FUNCDEF("write_category"); // output a javascript line for the category. int node_num = node->_uid; inner_mark_tree *parent = dynamic_cast<inner_mark_tree *>(node->parent()); int parent_node = parent? parent->_uid : -1; // the parent node for root is a negative one. astring chewed_name = node->name(); for (int i = chewed_name.end(); i >= 0; i--) { // escape any raw single quotes that we see. if (chewed_name[i] == '\'') { chewed_name.zap(i, i); chewed_name.insert(i, "\\'"); } } output += a_sprintf(" b.add(%d, %d, '%s');\n", node_num, parent_node, chewed_name.s()); } void marks_maker_javascript::write_link(inner_mark_tree *node, const link_record &linko, astring &output) { FUNCDEF("write_link"); // write a javascript link definition. int parent_node = node->_uid; astring chewed_name = linko._description; for (int i = chewed_name.end(); i >= 0; i--) { // escape any raw single quotes that we see. if (chewed_name[i] == '\'') { chewed_name.zap(i, i); chewed_name.insert(i, "\\'"); } } if (!linko._url) { // this just appears to be a comment line. if (!linko._description) return; // it's a nothing line. /* //hmmm: probably not what we want. //hmmm: why not, again? output += linko._description; output += "<br>"; output += parser_bits::platform_eol_to_chars(); */ return; } // generate a function header if the number of links is a multiple of 100. if (! (_link_spool % 100) ) { if (_link_spool) { // close out the previous function and set a timeout. output += " setTimeout('run_tree_loaders()', 0);\n"; output += "}\n"; } output += a_sprintf("function tree_loader_%d() {\n", _loader_count++); } _link_spool++; output += a_sprintf(" b.add(%d, %d, '%s', '%s');\n", linko._uid, parent_node, chewed_name.s(), linko._url.s()); } int marks_maker_javascript::execute() { FUNCDEF("execute"); SETUP_COMBO_LOGGER; command_line cmds(_global_argc, _global_argv); // process the command line parameters. astring input_filename; // we'll store our link database name here. astring output_filename; // where the web page we're creating goes. astring template_filename; // the wrapper html code that we'll stuff. if (!cmds.get_value('i', input_filename, false)) return print_instructions(cmds.program_name()); if (!cmds.get_value('o', output_filename, false)) return print_instructions(cmds.program_name()); if (!cmds.get_value('t', template_filename, false)) return print_instructions(cmds.program_name()); BASE_LOG(astring("input file: ") + input_filename); BASE_LOG(astring("output file: ") + output_filename); BASE_LOG(astring("template file: ") + template_filename); int ret = _categories.read_csv_file(input_filename); if (ret) return ret; ret = write_marks_page(output_filename, template_filename); if (ret) return ret; return 0; } int marks_maker_javascript::write_marks_page(const astring &output_filename, const astring &template_filename) { FUNCDEF("write_marks_page"); astring long_string; // this is our accumulator of links. it is the semi-final result that will // be injected into the template file. // add our target layer so that we can write to a useful place. long_string += "<div class=\"marks_target\" id=\"martarg\">Marks Target</div>\n"; // add the tree style and creation of the tree object into the text. long_string += "\n<div class=\"dtree\">\n"; long_string += "<script type=\"text/javascript\">\n"; long_string += "<!--\n"; long_string += "function open_mark(url) {\n"; long_string += " window.open(url, '', '');\n"; long_string += "}\n"; // the list of functions is used for calling into the tree loaders // without blocking. long_string += " b = new dTree('b');\n"; /// long_string += " b.config.inOrder = true;\n"; long_string += " b.config.useCookies = false;\n"; long_string += " b.config.folderLinks = false;\n"; // traverse the tree in prefix order. tree::iterator itty = _categories.access_root().start(tree::prefix); tree *curr = NULL_POINTER; while ( (curr = itty.next()) ) { inner_mark_tree *nod = (inner_mark_tree *)curr; // print out the category on this node. write_category(nod, long_string); // print the link for all of the ones stored at this node. for (int i = 0; i < nod->_links.elements(); i++) { link_record *lin = nod->_links.borrow(i); write_link(nod, *lin, long_string); } } // close the block of script in the output. long_string += " setTimeout('run_tree_loaders()', 0);\n"; long_string += "}\n\n"; long_string += a_sprintf("function tree_loader_%d()" "{ setTimeout('run_tree_loaders()', 0); }\n", _loader_count++); long_string += "\nconst max_funcs = 1000;\n"; long_string += "var loader_functions = new Array(max_funcs);\n"; long_string += "var curr_func = 0;\n"; long_string += "var done_rendering = false;\n\n"; long_string += a_sprintf("for (var i = 0; i < %d; i++) {\n", _loader_count); long_string += " loader_functions[curr_func++] " "= 'tree_loader_' + i + '()';\n"; long_string += "}\n"; long_string += "var run_index = 0;\n"; long_string += "function run_tree_loaders() {\n"; long_string += " if (done_rendering) return;\n"; long_string += " if (run_index >= curr_func) {\n"; long_string += " if (document.getElementById) {\n"; long_string += " x = document.getElementById('martarg');\n"; long_string += " x.innerHTML = '';\n"; long_string += " x.innerHTML = b;\n"; long_string += " } else { document.write(b); }\n"; //not a very graceful degradation. we should use the other options from: // http://www.quirksmode.org/js/layerwrite.html long_string += " done_rendering = true;\n"; long_string += " return;\n"; long_string += " }\n"; long_string += " var next_func = loader_functions[run_index++];\n"; long_string += " setTimeout(next_func, 0);\n"; long_string += "}\n"; long_string += a_sprintf(" run_tree_loaders();\n", _loader_count); long_string += "//-->\n"; long_string += "</script>\n"; long_string += "<p><a href=\"javascript: b.openAll();\">open all</a> | " "<a href=\"javascript: b.closeAll();\">close all</a></p>\n"; long_string += "</div>\n"; byte_filer template_file(template_filename, "r"); astring full_template; if (!template_file.good()) non_continuable_error(class_name(), func, "the template file could not be opened"); template_file.read(full_template, MAX_FILE_SIZE); template_file.close(); // javascript output needs some extra junk added to the header section. int indy = full_template.ifind("</title>"); if (negative(indy)) non_continuable_error(class_name(), func, "the template file is missing " "a <head> declaration"); //hmmm: the path here must be configurable! full_template.insert(indy + 8, "\n\n" "<link rel=\"StyleSheet\" href=\"/yeti/javascript/dtree/dtree.css\" " "type=\"text/css\" />\n" "<script type=\"text/javascript\" src=\"/yeti/javascript/" "dtree/dtree.js\"></script>\n"); // replace the tag with the long string we created. bool found_it = full_template.replace("$INSERT_LINKS_HERE", long_string); if (!found_it) non_continuable_error(class_name(), func, "the template file is missing " "the insertion point"); full_template.replace("$TODAYS_DATE", time_stamp::notarize(true)); filename outname(output_filename); if (outname.exists()) { non_continuable_error(class_name(), func, astring("the output file ") + output_filename + " already exists. It would be over-written if " "we continued."); } byte_filer output_file(output_filename, "w"); if (!output_file.good()) non_continuable_error(class_name(), func, "the output file could not be opened"); // write the newly generated web page out now. output_file.write(full_template); output_file.close(); // show the tree. // BASE_LOG(""); // BASE_LOG(_categories.access_root().text_form()); BASE_LOG(a_sprintf("wrote %d links in %d categories.", _categories.link_count(), _categories.category_count())); BASE_LOG(astring("")); return 0; } //////////////////////////////////////////////////////////////////////////// HOOPLE_MAIN(marks_maker_javascript, )
39.152299
89
0.633174
[ "object" ]
67ac0437cbaf03281605abef9845c1804d44bba6
874
cpp
C++
sources/cards/creatures/blues/Zappies.cpp
angeluriot/Magic_royal
a337ce4ad6c3215bbdec8c376d6e88fe97f48f94
[ "MIT" ]
1
2022-02-02T21:41:59.000Z
2022-02-02T21:41:59.000Z
sources/cards/creatures/blues/Zappies.cpp
angeluriot/Magic_royal
a337ce4ad6c3215bbdec8c376d6e88fe97f48f94
[ "MIT" ]
null
null
null
sources/cards/creatures/blues/Zappies.cpp
angeluriot/Magic_royal
a337ce4ad6c3215bbdec8c376d6e88fe97f48f94
[ "MIT" ]
2
2022-02-01T12:59:57.000Z
2022-03-05T12:50:27.000Z
#include "cards/creatures/blues/Zappies.hpp" Zappies::Zappies(): Creature(get_full_power(), get_full_toughness(), get_capacities()) {} Zappies::~Zappies() {} std::string Zappies::get_full_type() const { return Creature::get_full_type() + " - Machine"; } Card::Color Zappies::get_color() const { return Color::Blue; } std::string Zappies::get_name() const { return "Zappies"; } std::vector<Creature::Capacity> Zappies::get_capacities() const { return { Capacity::Reach, Capacity::Freeze }; } std::string Zappies::get_description() const { return Creature::get_description() + ""; } Card::Cost Zappies::get_cost() const { return { { Color::Colorless, 3 }, { Color::Blue, 1 } }; } int Zappies::get_full_power() const { return 3; } int Zappies::get_full_toughness() const { return 3; } Card* Zappies::clone() const { return new Zappies(*this); }
14.813559
89
0.684211
[ "vector" ]
67b13b4a8b1096f244cd2fcd332593b396f237c9
606
cc
C++
Codeforces/255 Division 2/Problem B/B.cc
VastoLorde95/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
170
2017-07-25T14:47:29.000Z
2022-01-26T19:16:31.000Z
Codeforces/255 Division 2/Problem B/B.cc
navodit15/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
null
null
null
Codeforces/255 Division 2/Problem B/B.cc
navodit15/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
55
2017-07-28T06:17:33.000Z
2021-10-31T03:06:22.000Z
#include<stdio.h> #include<iostream> #include<cmath> #include<algorithm> #include<cstring> #include<map> #include<set> #include<vector> #include<utility> #include<math.h> #define sd(x) scanf("%d",&x); #define sd2(x,y) scanf("%d%d",&x,&y); #define sd3(x,y,z) scanf("%d%d%d",&x,&y,&z); using namespace std; string s; int k, w[26], val, l, mx; int main(){ cin>>s>>k; l = s.length(); for(int i = 0; i < 26; i++){ cin>>w[i]; mx = max(mx, w[i]); } for(int i = 0; i < l; i++){ val += (i+1)*w[s[i]-'a']; } for(int i = 0; i < k; i++){ val += (l+i+1)*mx; } cout<< val <<endl; return 0; }
15.15
44
0.541254
[ "vector" ]
67bed3f3c1f1173a39846ef8a78556027954e493
16,773
cpp
C++
lightbar_manager/src/lightbar_manager/lightbar_manager_worker.cpp
adamlm/carma-platform
f6d46274cf6b6e14eddf8715b1a5204050d4c0e2
[ "Apache-2.0", "CC-BY-4.0", "MIT" ]
112
2020-04-27T17:06:46.000Z
2022-03-31T15:27:14.000Z
lightbar_manager/src/lightbar_manager/lightbar_manager_worker.cpp
adamlm/carma-platform
f6d46274cf6b6e14eddf8715b1a5204050d4c0e2
[ "Apache-2.0", "CC-BY-4.0", "MIT" ]
982
2020-04-17T11:28:04.000Z
2022-03-31T21:12:19.000Z
lightbar_manager/src/lightbar_manager/lightbar_manager_worker.cpp
adamlm/carma-platform
f6d46274cf6b6e14eddf8715b1a5204050d4c0e2
[ "Apache-2.0", "CC-BY-4.0", "MIT" ]
57
2020-05-07T15:48:11.000Z
2022-03-09T23:31:45.000Z
/* * Copyright (C) 2018-2021 LEIDOS. * * 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 "lightbar_manager/lightbar_manager_worker.hpp" #include <algorithm> #include <ros/console.h> namespace lightbar_manager { LightBarManagerWorker::LightBarManagerWorker(std::string node_name) : node_name_(node_name){}; void LightBarManagerWorker::next(const LightBarEvent& event) { lbsm_.next(event); } LightBarState LightBarManagerWorker::getCurrentState() { return lbsm_.getCurrentState(); } std::vector<cav_msgs::LightBarIndicator> LightBarManagerWorker::getMsg(std::vector<LightBarIndicator> indicators) { std::vector<cav_msgs::LightBarIndicator> return_msg; for (auto indicator : indicators) { cav_msgs::LightBarIndicator msg; msg.indicator = indicator; return_msg.push_back(msg); } return return_msg; } std::vector<cav_msgs::LightBarCDAType> LightBarManagerWorker::getMsg(std::vector<LightBarCDAType> cda_types) { std::vector<cav_msgs::LightBarCDAType> return_msg; for (auto cda_type : cda_types) { cav_msgs::LightBarCDAType msg; msg.type = cda_type; return_msg.push_back(msg); } return return_msg; } cav_msgs::LightBarIndicatorControllers LightBarManagerWorker::getMsg(std::map<LightBarIndicator, std::string> ind_ctrl_map) { cav_msgs::LightBarIndicatorControllers curr; curr.green_solid_owner = ind_ctrl_map[GREEN_SOLID]; curr.green_flash_owner = ind_ctrl_map[GREEN_FLASH]; curr.yellow_sides_owner= ind_ctrl_map[YELLOW_SIDES]; curr.yellow_dim_owner = ind_ctrl_map[YELLOW_DIM]; curr.yellow_flash_owner = ind_ctrl_map[YELLOW_FLASH]; curr.yellow_arrow_left_owner = ind_ctrl_map[YELLOW_ARROW_LEFT]; curr.yellow_arrow_right_owner = ind_ctrl_map[YELLOW_ARROW_RIGHT]; curr.yellow_arrow_out_owner = ind_ctrl_map[YELLOW_ARROW_OUT]; return curr; } void LightBarManagerWorker::handleStateChange(const cav_msgs::GuidanceStateConstPtr& msg_ptr) { lbsm_.handleStateChange(msg_ptr); return; } std::vector<lightbar_manager::LightBarIndicator> LightBarManagerWorker::handleTurnSignal(const automotive_platform_msgs::TurnSignalCommandPtr& msg_ptr) { std::vector<lightbar_manager::LightBarIndicator> turn_signal; if (msg_ptr->turn_signal == current_turn_signal_) { return {}; } if (msg_ptr->turn_signal == automotive_platform_msgs::TurnSignalCommand::LEFT) //NONE -> LEFT { turn_signal.push_back(lightbar_manager::LightBarIndicator::YELLOW_ARROW_LEFT); } else if (msg_ptr->turn_signal == automotive_platform_msgs::TurnSignalCommand::RIGHT) //NONE -> RIGHT { turn_signal.push_back(lightbar_manager::LightBarIndicator::YELLOW_ARROW_RIGHT); } else if (msg_ptr->turn_signal == automotive_platform_msgs::TurnSignalCommand::NONE) { // check previous signal if (current_turn_signal_ == automotive_platform_msgs::TurnSignalCommand::RIGHT) // RIGHT -> NONE turn_signal.push_back(lightbar_manager::LightBarIndicator::YELLOW_ARROW_RIGHT); else if (current_turn_signal_ == automotive_platform_msgs::TurnSignalCommand::LEFT) // LEFT -> NONE turn_signal.push_back(lightbar_manager::LightBarIndicator::YELLOW_ARROW_LEFT); } current_turn_signal_ = msg_ptr->turn_signal; return turn_signal; } std::map<LightBarIndicator, std::string> LightBarManagerWorker::getIndicatorControllers() { return ind_ctrl_map_; } std::map<LightBarCDAType, LightBarIndicator> LightBarManagerWorker::setIndicatorCDAMap(std::map<std::string, std::string> raw_map) { // In case if the parameter is not loaded corretly and there is an error, return this`1 std::map<LightBarCDAType, LightBarIndicator> default_map; default_map[TYPE_A] = YELLOW_DIM; default_map[TYPE_B] = YELLOW_DIM; default_map[TYPE_C] = YELLOW_FLASH; default_map[TYPE_D] = YELLOW_SIDES; if (raw_map.size() < 4) { ROS_WARN_STREAM("In function: " << __FUNCTION__ << ": LightBarManager's CDAType to Indicator table is not configured correctly. Using default mapping..."); cda_ind_map_ = default_map; return cda_ind_map_; } // Convert from string:string mapping to correct enums for (std::pair<std::string, std::string> element : raw_map) { LightBarCDAType cda_type; LightBarIndicator indicator; try { cda_type = cda_type_dict_.at(element.first); } catch(const std::exception& e) { ROS_WARN_STREAM ("In function: " << __FUNCTION__ << ": LightBarManager Received unknown CDA Msg Type. Using default mapping for cda-indicators..."); cda_ind_map_ = default_map; return cda_ind_map_; } try { indicator = ind_dict.at(element.second); } catch(const std::exception& e) { ROS_WARN_STREAM ("In function: " << __FUNCTION__ << ": LightBarManager Received unknown indicator type. Using default mapping for cda-indicators..."); cda_ind_map_ = default_map; return cda_ind_map_; } cda_ind_map_.emplace(cda_type, indicator); } return cda_ind_map_; } bool LightBarManagerWorker::hasHigherPriority (std::string requester, std::string controller) { auto start = control_priorities.begin(); auto end = control_priorities.end(); auto requesterPriority = std::find(start, end, requester); auto controllerPriority = std::find(start, end, controller); // Components not in the priority list are assumed to have the lowest priority if (requesterPriority == end) { ROS_WARN_STREAM(requester << " is referenced in lightbar_manager, but is not in the priority list"); return false; } else if (controllerPriority == end) { ROS_WARN_STREAM(controller << " is referenced in lightbar_manager and is controlling an indicator, but is not in the priority list"); return true; } return (requesterPriority - end) <= (controllerPriority - end); } std::vector<LightBarIndicator> LightBarManagerWorker::requestControl(std::vector<LightBarIndicator> ind_list, std::string requester_name) { std::vector<LightBarIndicator> denied_list; std::string indicator_owner; // Attempt to acquire control of every indicators for (LightBarIndicator indicator: ind_list) { // Attempt control try { indicator_owner = ind_ctrl_map_.at(indicator); } catch(const std::exception& e) { ROS_WARN_STREAM("In function: " << __FUNCTION__ << ", the component, " << requester_name << ", requested a control of invalid indicator. Skipping with WARNING:" << e.what() << "\n"); continue; } if (indicator_owner == "") { // Add new controller If no other component has claimed this indicator handleControlChange(indicator, requester_name, CONTROL_GAINED); } else if (indicator_owner != requester_name) { // If this indicator is already controlled // If the requesting component has higher priority it may take control of this indicator if (hasHigherPriority(requester_name, indicator_owner)) { // Handle previous controller handleControlChange(indicator, indicator_owner, CONTROL_LOST); // Add new controller handleControlChange(indicator, requester_name, CONTROL_GAINED); } else { denied_list.push_back(indicator); // Notify caller of failure to take control of component } } } return denied_list; } void LightBarManagerWorker::releaseControl(std::vector<LightBarIndicator> ind_list, std::string owner_name) { std::string current_owner; // Attempt to release control of all indicators for (LightBarIndicator indicator: ind_list) { // Attempt release control try { current_owner = ind_ctrl_map_.at(indicator); } catch(const std::exception& e) { ROS_WARN_STREAM("In function: " << __FUNCTION__ << ", the component, " << owner_name << ", requested a release of an invalid indicator. Skipping with WARNING:" << e.what() << "\n"); continue; } // Lose control only if the requester is currently controlling it if (current_owner == owner_name) { handleControlChange(indicator,owner_name, CONTROL_LOST); } } return; } void LightBarManagerWorker::handleControlChange(LightBarIndicator indicator, std::string controller, IndicatorControlEvent event) { // Pick new owner name depending on losing or gaining control std::string new_owner; if (event == CONTROL_GAINED) new_owner = controller; else new_owner = ""; // Handle mutually in-exclusive indicators // These are indicators that are controlled indirectly due to change in one indicator // Priority of every one of those indicators, must be compared to that of requester to change it. // e.g. if A>B and YELLOW_RIGHT= "" & YELLOW_LEFT = A (means YELLOW_FLASH = A & YELLOW_OUT = A) // Then if YELLOW_RIGHT = "" -> YELLOW_RIGHT = "B", B should not be able to control YELLOW_FLASH nor YELLOW_OUT switch (indicator) { case YELLOW_ARROW_LEFT: case YELLOW_ARROW_RIGHT: ind_ctrl_map_[YELLOW_ARROW_OUT] = hasHigherPriority(controller, ind_ctrl_map_[YELLOW_ARROW_OUT]) ? new_owner :ind_ctrl_map_[YELLOW_ARROW_OUT]; ind_ctrl_map_[YELLOW_FLASH] = ind_ctrl_map_[YELLOW_ARROW_OUT]; //they always have same owner ind_ctrl_map_[indicator] = new_owner; break; case YELLOW_ARROW_OUT: case YELLOW_FLASH: ind_ctrl_map_[YELLOW_ARROW_LEFT] = hasHigherPriority(controller, ind_ctrl_map_[YELLOW_ARROW_LEFT]) ? new_owner :ind_ctrl_map_[YELLOW_ARROW_LEFT]; ind_ctrl_map_[YELLOW_ARROW_RIGHT] = hasHigherPriority(controller, ind_ctrl_map_[YELLOW_ARROW_RIGHT]) ? new_owner :ind_ctrl_map_[YELLOW_ARROW_RIGHT]; ind_ctrl_map_[YELLOW_ARROW_OUT] = hasHigherPriority(controller, ind_ctrl_map_[YELLOW_ARROW_OUT]) ? new_owner :ind_ctrl_map_[YELLOW_ARROW_OUT]; ind_ctrl_map_[YELLOW_FLASH] = ind_ctrl_map_[YELLOW_ARROW_OUT]; //they always have same owner break; case GREEN_FLASH: case GREEN_SOLID: ind_ctrl_map_[GREEN_FLASH] = hasHigherPriority(controller, ind_ctrl_map_[GREEN_FLASH]) ? new_owner :ind_ctrl_map_[GREEN_FLASH]; ind_ctrl_map_[GREEN_SOLID] = ind_ctrl_map_[GREEN_FLASH]; //they always have same owner break; default: ind_ctrl_map_[indicator] = new_owner; break; } return; } std::vector<IndicatorStatus> LightBarManagerWorker::setIndicator(LightBarIndicator ind, IndicatorStatus ind_status, std::string requester_name) { std::string current_controller = ind_ctrl_map_[ind]; // Use a local copy in case manager fails to set the light std::vector<IndicatorStatus> light_status_copy = light_status; // Handle mutually non-exclusive cases // If desired indicator is already at the status do not change any indicators if (ind_status != light_status_copy[ind]) { switch(ind) { case YELLOW_ARROW_LEFT: case YELLOW_ARROW_RIGHT: light_status_copy[YELLOW_ARROW_OUT] = OFF; light_status_copy[YELLOW_FLASH] = OFF; break; case YELLOW_ARROW_OUT: case YELLOW_FLASH: light_status_copy[YELLOW_ARROW_OUT] = OFF; light_status_copy[YELLOW_FLASH] = OFF; light_status_copy[YELLOW_ARROW_LEFT] = OFF; light_status_copy[YELLOW_ARROW_RIGHT] = OFF; break; case GREEN_FLASH: case GREEN_SOLID: light_status_copy[GREEN_FLASH] = OFF; light_status_copy[GREEN_SOLID] = OFF; break; default: break; } } // Set the desired indicator now that there is no conflict. light_status_copy[ind] = ind_status; return light_status_copy; } cav_msgs::LightBarStatus LightBarManagerWorker::getLightBarStatusMsg(std::vector<IndicatorStatus> indicators) { // it is assumed that mutually exclusive cases are handled properly. cav_msgs::LightBarStatus msg; msg.green_solid = indicators[GREEN_SOLID] == ON ? cav_msgs::LightBarStatus::ON : cav_msgs::LightBarStatus::OFF; msg.green_flash = indicators[GREEN_FLASH]== ON ? cav_msgs::LightBarStatus::ON : cav_msgs::LightBarStatus::OFF; msg.sides_solid = indicators[YELLOW_SIDES]== ON ? cav_msgs::LightBarStatus::ON : cav_msgs::LightBarStatus::OFF; msg.yellow_solid = indicators[YELLOW_DIM]== ON ? cav_msgs::LightBarStatus::ON : cav_msgs::LightBarStatus::OFF; msg.flash = indicators[YELLOW_FLASH]== ON ? cav_msgs::LightBarStatus::ON : cav_msgs::LightBarStatus::OFF; msg.left_arrow = indicators[YELLOW_ARROW_LEFT]== ON ? cav_msgs::LightBarStatus::ON : cav_msgs::LightBarStatus::OFF; msg.right_arrow = indicators[YELLOW_ARROW_RIGHT]== ON ? cav_msgs::LightBarStatus::ON : cav_msgs::LightBarStatus::OFF; // for YELLOW_ARROW_OUT set left and right if (indicators[YELLOW_ARROW_OUT] == ON) { msg.left_arrow = cav_msgs::LightBarStatus::ON; msg.right_arrow = cav_msgs::LightBarStatus::ON; } return msg; } void LightBarManagerWorker::setIndicatorControllers() { for (int i = 0; i <= INDICATOR_COUNT; i++ ) { LightBarIndicator indicator = static_cast<LightBarIndicator>(i); // initialize the owner as empty string ind_ctrl_map_[indicator] = ""; } } void LightBarManagerWorker::setIndicatorControllers(std::map<LightBarIndicator, std::string> ind_ctrl_map) { ind_ctrl_map_ = ind_ctrl_map; } LightBarIndicator LightBarManagerWorker::getIndicatorFromCDAType(LightBarCDAType cda_type) { return cda_ind_map_[cda_type]; } LightBarCDAType LightBarManagerWorker::getCDATypeFromIndicator(LightBarIndicator indicator) { for (std::pair<LightBarCDAType,LightBarIndicator> element : cda_ind_map_) { if (element.second == indicator) return element.first; } // if the indicator does not have any mapped CDA Msg Type, throw and handle outside throw INDICATOR_NOT_MAPPED(std::string("Specified indicator does not have a mapped CDA Msg Type. Skipping...")); } }
42.356061
167
0.624873
[ "vector" ]
67c37fc405da104ea86312f13f04817c22a802e5
5,334
cpp
C++
src/InjectImageIntrinsics.cpp
trgardos/Halide
3d895bcf7c9b6632dda6445c218ed2361b698584
[ "MIT" ]
null
null
null
src/InjectImageIntrinsics.cpp
trgardos/Halide
3d895bcf7c9b6632dda6445c218ed2361b698584
[ "MIT" ]
null
null
null
src/InjectImageIntrinsics.cpp
trgardos/Halide
3d895bcf7c9b6632dda6445c218ed2361b698584
[ "MIT" ]
null
null
null
#include "InjectImageIntrinsics.h" #include "IRMutator.h" #include "IROperator.h" #include "CodeGen_GPU_Dev.h" #include "Substitute.h" #include "FuseGPUThreadLoops.h" namespace Halide { namespace Internal { using std::string; using std::vector; class InjectImageIntrinsics : public IRMutator { public: InjectImageIntrinsics() : inside_kernel_loop(false) {} Scope<int> scope; bool inside_kernel_loop; private: using IRMutator::visit; void visit(const Provide *provide) { if (!inside_kernel_loop) { IRMutator::visit(provide); return; } internal_assert(provide->values.size() == 1) << "Image currently only supports single-valued stores.\n"; user_assert(provide->args.size() == 3) << "Image stores require three coordinates.\n"; // Create image_store("name", name.buffer, x, y, c, value) // intrinsic. Expr value_arg = mutate(provide->values[0]); vector<Expr> args = { provide->name, Variable::make(type_of<struct buffer_t *>(), provide->name + ".buffer"), provide->args[0], provide->args[1], provide->args[2], value_arg}; stmt = Evaluate::make(Call::make(value_arg.type(), Call::image_store, args, Call::Intrinsic)); } void visit(const Call *call) { if (!inside_kernel_loop || (call->call_type != Call::Halide && call->call_type != Call::Image)) { IRMutator::visit(call); return; } string name = call->name; if (call->call_type == Call::Halide && call->func.outputs() > 1) { name = name + '.' + std::to_string(call->value_index); } vector<Expr> padded_call_args = call->args; // Check to see if we are reading from a one or two dimension function // and pad to three dimensions. while (padded_call_args.size() < 3) { padded_call_args.push_back(0); } // Create image_load("name", name.buffer, x, x_extent, y, y_extent, ...). // Extents can be used by successive passes. OpenGL, for example, uses them // for coordinates normalization. vector<Expr> args(2); args[0] = call->name; args[1] = Variable::make(type_of<struct buffer_t *>(), call->name + ".buffer"); for (size_t i = 0; i < padded_call_args.size(); i++) { // If this is an ordinary dimension, insert a variable that will be // subsequently defined by StorageFlattening to with the min and // extent. Otherwise, add a default value for the padded dimension. // If 'i' is greater or equal to the number of args in the original // node, it must be a padded dimension we added above. if (i < call->args.size()) { string d = std::to_string(i); string min_name = name + ".min." + d; string min_name_constrained = min_name + ".constrained"; if (scope.contains(min_name_constrained)) { min_name = min_name_constrained; } string extent_name = name + ".extent." + d; string extent_name_constrained = extent_name + ".constrained"; if (scope.contains(extent_name_constrained)) { extent_name = extent_name_constrained; } Expr min = Variable::make(Int(32), min_name); args.push_back(mutate(padded_call_args[i]) - min); args.push_back(Variable::make(Int(32), extent_name)); } else { args.push_back(0); args.push_back(1); } } Type load_type = call->type; // load_type = load_type.with_lanes(4); Expr load_call = Call::make(load_type, Call::image_load, args, Call::PureIntrinsic, Function(), 0, call->image, call->param); expr = load_call; } void visit(const LetStmt *let) { // Discover constrained versions of things. bool constrained_version_exists = ends_with(let->name, ".constrained"); if (constrained_version_exists) { scope.push(let->name, 0); } IRMutator::visit(let); if (constrained_version_exists) { scope.pop(let->name); } } void visit(const For *loop) { bool old_kernel_loop = inside_kernel_loop; if (loop->for_type == ForType::Parallel && (loop->device_api == DeviceAPI::GLSL || loop->device_api == DeviceAPI::Renderscript)) { inside_kernel_loop = true; } IRMutator::visit(loop); inside_kernel_loop = old_kernel_loop; } }; Stmt inject_image_intrinsics(Stmt s) { debug(4) << "InjectImageIntrinsics: inject_image_intrinsics stmt: " << s << "\n"; s = zero_gpu_loop_mins(s); InjectImageIntrinsics gl; return gl.mutate(s); } } }
33.759494
87
0.542182
[ "vector" ]
67c38445e518cc2f371b5a740e1d9ceafdae0aae
11,237
cpp
C++
quantitative_finance/L2/tests/CPICapFloorEngine/host/main.cpp
vmayoral/Vitis_Libraries
2323dc5036041e18242718287aee4ce66ba071ef
[ "Apache-2.0" ]
1
2021-09-11T01:05:01.000Z
2021-09-11T01:05:01.000Z
quantitative_finance/L2/tests/CPICapFloorEngine/host/main.cpp
vmayoral/Vitis_Libraries
2323dc5036041e18242718287aee4ce66ba071ef
[ "Apache-2.0" ]
null
null
null
quantitative_finance/L2/tests/CPICapFloorEngine/host/main.cpp
vmayoral/Vitis_Libraries
2323dc5036041e18242718287aee4ce66ba071ef
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2019 Xilinx, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef HLS_TEST #include "xcl2.hpp" #endif #include <cstring> #include <vector> #include <fstream> #include <iostream> #include <sys/time.h> #include "ap_int.h" #include "utils.hpp" #include "cpi_capfloor_engine_kernel.hpp" #include "xf_utils_sw/logger.hpp" class ArgParser { public: ArgParser(int& argc, const char** argv) { for (int i = 1; i < argc; ++i) mTokens.push_back(std::string(argv[i])); } bool getCmdOption(const std::string option, std::string& value) const { std::vector<std::string>::const_iterator itr; itr = std::find(this->mTokens.begin(), this->mTokens.end(), option); if (itr != this->mTokens.end() && ++itr != this->mTokens.end()) { value = *itr; return true; } return false; } private: std::vector<std::string> mTokens; }; int main(int argc, const char* argv[]) { std::cout << "\n----------------------CPI CapFloor Engine-----------------\n"; xf::common::utils_sw::Logger logger(std::cout, std::cerr); // cmd parser ArgParser parser(argc, argv); std::string xclbin_path; if (!parser.getCmdOption("-xclbin", xclbin_path)) { std::cout << "ERROR:xclbin path is not set!\n"; return 1; } // Allocate Memory in Host Memory double* times_alloc = aligned_alloc<double>(LEN); double* strikes_alloc = aligned_alloc<double>(LEN); double* prices_alloc = aligned_alloc<double>(LEN * LEN); DT* output = aligned_alloc<DT>(1); // -------------setup k0 params--------------- int err = 0; DT minErr = 10e-10; int xSize = 7; int ySize = 8; double golden = 0.022759999999999999; DT cfMaturityTimes[7] = {3.0054794520547947, 5, 7, 10.001601916311101, 15.002739726027396, 20.005479452054796, 30.001601916311103}; DT cfStrikes[8] = {-0.01, 0, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06}; DT cPriceB[56] = {0.1189026727532132, 0.19234884598336022, 0.25893190845247194, 0.34716101441352776, 0.45149515082144476, 0.54984156444044396, 0.68506774112094337, 0.092142126147838899, 0.15086931377480772, 0.20609223629086393, 0.28298752968117147, 0.37776538469755194, 0.47195914772445069, 0.60883382967607202, 0.066062203731440894, 0.10909964072251221, 0.15160923940178606, 0.21468337452033526, 0.29520946272431492, 0.37985640392630282, 0.50921195588585078, 0.041986241745908481, 0.068822646085233807, 0.097601702943668323, 0.14444396141115279, 0.20582824893879248, 0.27381429347506581, 0.38239007859277974, 0.022759999999999999, 0.034532, 0.047794999999999997, 0.075781000000000001, 0.11407300000000001, 0.15375999999999998, 0.221167, 0.010026999999999999, 0.012790000000000001, 0.017018999999999999, 0.030394999999999998, 0.048188999999999996, 0.060772, 0.083923999999999999, 0.0038799999999999998, 0.0040590000000000001, 0.0050619999999999997, 0.010762000000000001, 0.016840000000000001, 0.017227000000000003, 0.018474999999999998, 0.0014939999999999999, 0.0014109999999999999, 0.0016879999999999998, 0.0043610000000000003, 0.006365, 0.0054869999999999997, 0.0045030000000000001}; DT fPriceB_[56] = {0.001562, 0.0021449999999999998, 0.0024450000000000001, 0.0039249999999999997, 0.0036819999999999999, 0.0039700000000000004, 0.0041479999999999998, 0.0028379999999999998, 0.0036729999999999996, 0.0042079999999999999, 0.006352, 0.0063619999999999996, 0.0067469999999999995, 0.0073900000000000007, 0.0053610000000000003, 0.0066660000000000001, 0.0077040000000000008, 0.010920000000000001, 0.011696999999999999, 0.012179000000000001, 0.013975, 0.010459999999999999, 0.012959999999999999, 0.015224000000000001, 0.020344000000000001, 0.023272999999999999, 0.023855999999999999, 0.028674999999999999, 0.020986423566868195, 0.027102914440439996, 0.030672544709074989, 0.038692580066551074, 0.047326314871280251, 0.04562055531365905, 0.055501689276864274, 0.038589455964999964, 0.055712359250414734, 0.069065840642156262, 0.088262673232410438, 0.11411008563692915, 0.12317631764911008, 0.16744489410569519, 0.063367519206596779, 0.099307091363403766, 0.13038590020945451, 0.1721686783337858, 0.23454395102070713, 0.2843548261064861, 0.43130230651061563, 0.092501277049768627, 0.15101660895125213, 0.20459803401350229, 0.27857239514041832, 0.3974986330688387, 0.5179412029467938, 0.85136429970596605}; DT r = 0.03; DT t = 3.0054794520547947; for (int i = 0; i < xSize; i++) { times_alloc[i] = cfMaturityTimes[i]; } for (int i = 0; i < ySize; i++) { strikes_alloc[i] = cfStrikes[i]; } for (int i = 0; i < xSize * ySize; i++) { prices_alloc[i] = cPriceB[i]; } #ifndef HLS_TEST cl_int cl_err; // do pre-process on CPU struct timeval start_time, end_time, test_time; // platform related operations std::vector<cl::Device> devices = xcl::get_xil_devices(); cl::Device device = devices[0]; // Creating Context and Command Queue for selected Device cl::Context context(device, NULL, NULL, NULL, &cl_err); logger.logCreateContext(cl_err); cl::CommandQueue q(context, device, CL_QUEUE_PROFILING_ENABLE | CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE, &cl_err); logger.logCreateCommandQueue(cl_err); std::string devName = device.getInfo<CL_DEVICE_NAME>(); printf("Found Device=%s\n", devName.c_str()); // cl::Program::Binaries xclBins = xcl::import_binary_file("../xclbin/MCAE_u250_hw.xclbin"); cl::Program::Binaries xclBins = xcl::import_binary_file(xclbin_path); devices.resize(1); cl::Program program(context, devices, xclBins, NULL, &cl_err); logger.logCreateProgram(cl_err); cl::Kernel kernel_CPIEngine(program, "CPI_k0", &cl_err); logger.logCreateKernel(cl_err); std::cout << "kernel has been created" << std::endl; cl_mem_ext_ptr_t mext_o[4]; mext_o[0] = {7, output, kernel_CPIEngine()}; mext_o[1] = {2, times_alloc, kernel_CPIEngine()}; mext_o[2] = {3, strikes_alloc, kernel_CPIEngine()}; mext_o[3] = {4, prices_alloc, kernel_CPIEngine()}; // create device buffer and map dev buf to host buf cl::Buffer output_buf; cl::Buffer times_buf, strikes_buf, prices_buf; output_buf = cl::Buffer(context, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE, sizeof(DT) * N, &mext_o[0]); times_buf = cl::Buffer(context, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE, sizeof(DT) * LEN, &mext_o[1]); strikes_buf = cl::Buffer(context, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE, sizeof(DT) * LEN, &mext_o[2]); prices_buf = cl::Buffer(context, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE, sizeof(DT) * LEN * LEN, &mext_o[3]); std::vector<cl::Memory> ob_out; ob_out.push_back(output_buf); q.finish(); // launch kernel and calculate kernel execution time std::cout << "kernel start------" << std::endl; gettimeofday(&start_time, 0); for (int i = 0; i < 1; ++i) { kernel_CPIEngine.setArg(0, xSize); kernel_CPIEngine.setArg(1, ySize); kernel_CPIEngine.setArg(2, times_buf); kernel_CPIEngine.setArg(3, strikes_buf); kernel_CPIEngine.setArg(4, prices_buf); kernel_CPIEngine.setArg(5, t); kernel_CPIEngine.setArg(6, r); kernel_CPIEngine.setArg(7, output_buf); q.enqueueTask(kernel_CPIEngine, nullptr, nullptr); } q.finish(); gettimeofday(&end_time, 0); std::cout << "kernel end------" << std::endl; std::cout << "Execution time " << tvdiff(&start_time, &end_time) << "us" << std::endl; q.enqueueMigrateMemObjects(ob_out, 1, nullptr, nullptr); q.finish(); #else CPI_k0(xSize, ySize, cfMaturityTimes, cfStrikes, cPriceB, t, r, output); #endif DT out = output[0]; if (std::fabs(out - golden) > minErr) err++; std::cout << "NPV= " << out << " ,diff/NPV= " << (out - golden) / golden << std::endl; err ? logger.error(xf::common::utils_sw::Logger::Message::TEST_FAIL) : logger.info(xf::common::utils_sw::Logger::Message::TEST_PASS); return err; }
39.847518
120
0.541337
[ "vector" ]
67c925f15fa97d8fab6981e316b4de1614fc2ea4
2,423
cpp
C++
aws-cpp-sdk-mediaconnect/source/model/Maintenance.cpp
Nexuscompute/aws-sdk-cpp
e7ef485e46e6962c9e084b8c9b104c1bfcceaf26
[ "Apache-2.0" ]
1
2022-01-05T18:20:03.000Z
2022-01-05T18:20:03.000Z
aws-cpp-sdk-mediaconnect/source/model/Maintenance.cpp
Nexuscompute/aws-sdk-cpp
e7ef485e46e6962c9e084b8c9b104c1bfcceaf26
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-mediaconnect/source/model/Maintenance.cpp
Nexuscompute/aws-sdk-cpp
e7ef485e46e6962c9e084b8c9b104c1bfcceaf26
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/mediaconnect/model/Maintenance.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace MediaConnect { namespace Model { Maintenance::Maintenance() : m_maintenanceDay(MaintenanceDay::NOT_SET), m_maintenanceDayHasBeenSet(false), m_maintenanceDeadlineHasBeenSet(false), m_maintenanceScheduledDateHasBeenSet(false), m_maintenanceStartHourHasBeenSet(false) { } Maintenance::Maintenance(JsonView jsonValue) : m_maintenanceDay(MaintenanceDay::NOT_SET), m_maintenanceDayHasBeenSet(false), m_maintenanceDeadlineHasBeenSet(false), m_maintenanceScheduledDateHasBeenSet(false), m_maintenanceStartHourHasBeenSet(false) { *this = jsonValue; } Maintenance& Maintenance::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("maintenanceDay")) { m_maintenanceDay = MaintenanceDayMapper::GetMaintenanceDayForName(jsonValue.GetString("maintenanceDay")); m_maintenanceDayHasBeenSet = true; } if(jsonValue.ValueExists("maintenanceDeadline")) { m_maintenanceDeadline = jsonValue.GetString("maintenanceDeadline"); m_maintenanceDeadlineHasBeenSet = true; } if(jsonValue.ValueExists("maintenanceScheduledDate")) { m_maintenanceScheduledDate = jsonValue.GetString("maintenanceScheduledDate"); m_maintenanceScheduledDateHasBeenSet = true; } if(jsonValue.ValueExists("maintenanceStartHour")) { m_maintenanceStartHour = jsonValue.GetString("maintenanceStartHour"); m_maintenanceStartHourHasBeenSet = true; } return *this; } JsonValue Maintenance::Jsonize() const { JsonValue payload; if(m_maintenanceDayHasBeenSet) { payload.WithString("maintenanceDay", MaintenanceDayMapper::GetNameForMaintenanceDay(m_maintenanceDay)); } if(m_maintenanceDeadlineHasBeenSet) { payload.WithString("maintenanceDeadline", m_maintenanceDeadline); } if(m_maintenanceScheduledDateHasBeenSet) { payload.WithString("maintenanceScheduledDate", m_maintenanceScheduledDate); } if(m_maintenanceStartHourHasBeenSet) { payload.WithString("maintenanceStartHour", m_maintenanceStartHour); } return payload; } } // namespace Model } // namespace MediaConnect } // namespace Aws
22.858491
109
0.768469
[ "model" ]
67c9b25a2ce5057da1fd09f8f2f41c1dc73937c0
4,356
hpp
C++
include/System/Data/DataRowCollection_DataRowTree.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/System/Data/DataRowCollection_DataRowTree.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/System/Data/DataRowCollection_DataRowTree.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
1
2022-03-30T21:07:35.000Z
2022-03-30T21:07:35.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: System.Data.DataRowCollection #include "System/Data/DataRowCollection.hpp" // Including type: System.Data.RBTree`1 #include "System/Data/RBTree_1.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: System::Data namespace System::Data { // Forward declaring type: DataRow class DataRow; } // Completed forward declares #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::System::Data::DataRowCollection::DataRowTree); DEFINE_IL2CPP_ARG_TYPE(::System::Data::DataRowCollection::DataRowTree*, "System.Data", "DataRowCollection/DataRowTree"); // Type namespace: System.Data namespace System::Data { // WARNING Size may be invalid! // Autogenerated type: System.Data.DataRowCollection/System.Data.DataRowTree // [TokenAttribute] Offset: FFFFFFFF class DataRowCollection::DataRowTree : public ::System::Data::RBTree_1<::System::Data::DataRow*> { public: // System.Void .ctor() // Offset: 0x18CDFAC template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static DataRowCollection::DataRowTree* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataRowCollection::DataRowTree::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<DataRowCollection::DataRowTree*, creationType>())); } // protected System.Int32 CompareNode(System.Data.DataRow record1, System.Data.DataRow record2) // Offset: 0x18CDFFC int CompareNode(::System::Data::DataRow* record1, ::System::Data::DataRow* record2); // protected System.Int32 CompareSateliteTreeNode(System.Data.DataRow record1, System.Data.DataRow record2) // Offset: 0x18CE030 int CompareSateliteTreeNode(::System::Data::DataRow* record1, ::System::Data::DataRow* record2); }; // System.Data.DataRowCollection/System.Data.DataRowTree } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: System::Data::DataRowCollection::DataRowTree::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: System::Data::DataRowCollection::DataRowTree::CompareNode // Il2CppName: CompareNode template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::Data::DataRowCollection::DataRowTree::*)(::System::Data::DataRow*, ::System::Data::DataRow*)>(&System::Data::DataRowCollection::DataRowTree::CompareNode)> { static const MethodInfo* get() { static auto* record1 = &::il2cpp_utils::GetClassFromName("System.Data", "DataRow")->byval_arg; static auto* record2 = &::il2cpp_utils::GetClassFromName("System.Data", "DataRow")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Data::DataRowCollection::DataRowTree*), "CompareNode", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{record1, record2}); } }; // Writing MetadataGetter for method: System::Data::DataRowCollection::DataRowTree::CompareSateliteTreeNode // Il2CppName: CompareSateliteTreeNode template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::Data::DataRowCollection::DataRowTree::*)(::System::Data::DataRow*, ::System::Data::DataRow*)>(&System::Data::DataRowCollection::DataRowTree::CompareSateliteTreeNode)> { static const MethodInfo* get() { static auto* record1 = &::il2cpp_utils::GetClassFromName("System.Data", "DataRow")->byval_arg; static auto* record2 = &::il2cpp_utils::GetClassFromName("System.Data", "DataRow")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Data::DataRowCollection::DataRowTree*), "CompareSateliteTreeNode", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{record1, record2}); } };
58.864865
250
0.746556
[ "vector" ]
67ce00861c7d26d69dc003fde0d96cc331fd73b2
13,849
cpp
C++
dragoncello.cpp
sscerr/DRAGONCELLO
1dfa2a9bf4d6359d5a9257c10f9adf825edd4594
[ "MIT" ]
5
2020-11-25T22:05:46.000Z
2021-02-25T07:12:12.000Z
dragoncello.cpp
sscerr/DRAGONCELLO
1dfa2a9bf4d6359d5a9257c10f9adf825edd4594
[ "MIT" ]
null
null
null
dragoncello.cpp
sscerr/DRAGONCELLO
1dfa2a9bf4d6359d5a9257c10f9adf825edd4594
[ "MIT" ]
1
2020-11-26T02:21:41.000Z
2020-11-26T02:21:41.000Z
#include "dragoncello.h" #include <string> #include <cmath> using namespace std; using namespace DRAGON; DRAGONCELLO::DRAGONCELLO(int Z_, int A_) : Z(Z_), A(A_), species_id(1000 * Z + A) { cout << "I am the constructor " << endl; } void DRAGONCELLO::initGrids(void) { cout << "Creating grids..." << endl; buildXGrid(); buildYGrid(); //code is 3D-ready for next release (currently: ny = 1) buildZGrid(); buildPGrid(); initEmptyGrids(); } void DRAGONCELLO::initBfield(void) { cout << "Initializing ordered B field..." << endl; #ifdef USER_DEFINED_BFIELD // // The user can implement any desired B-field here (i.e., different from the one used in Cerri et al., JCAP 10:019 (2017) // // cout << " *** user-defined B-field ***" << endl; for (int ix = 0; ix < nx; ++ix) for (int iy = 0; iy < ny; ++iy) for (int iz = 0; iz < nz; ++iz) { long int ind_sp = indexSpatial(ix,iy,iz); // define B field (example) b_r[ind_sp] = B_0; b_phi[ind_sp] = 0.; b_z[ind_sp] = B_0; // compute local unit vector b = B/|B| double modB = sqrt( b_r[ind_sp]*b_r[ind_sp] + b_phi[ind_sp]*b_phi[ind_sp] + b_z[ind_sp]*b_z[ind_sp] ); b_r[ind_sp] /= modB; b_phi[ind_sp] /= modB; b_z[ind_sp] /= modB; } #endif #ifdef FARRAR_SIMPLE_2D // // X-shaped B-field model: Jansson & Farrar, ApJ 757:14 (2012) // B-field ring model: Pshirkov et al., ApJ 738:192 (2011) // cout << " *** Simplified Farrar-like B-field (axisymmetric: X-shaped halo + rings) ***" << endl; const double rcX = 4.8*kpc; const double rcD = 5.*kpc; const double rX = 3.*kpc; const double R0 = 10.*kpc; const double R0H = 8.*kpc; const double Z0 = 1.*kpc; const double Z0H = 1.3*kpc; const double ThetaX0 = 49.*M_PI/180.; const double BX0 = 4.6; const double BD0 = 4.; const double BH0 = 1.; double Bxx, Bdisk, Bhalo; double ThetaX, rp; for (int ix = 0; ix < nx; ++ix) for (int iy = 0; iy < ny; ++iy) for (int iz = 0; iz < nz; ++iz) { long int ind_sp = indexSpatial(ix,iy,iz); double r = x_vec[ix]; double z = z_vec[iz]; //Bxx if (r > rcX) { rp = r-fabs(z)/tan(ThetaX0); ThetaX = ThetaX0; Bxx = BX0*exp(-rp/rX)*(rp/max(aTinyNumber,r)); } else { rp = r*rcX/(rcX+fabs(z)/tan(ThetaX0)); ThetaX = atan( (fabs(z)/max(0.1*aTinyNumber,r)) + (rcX/max(0.1*aTinyNumber,r))*tan(ThetaX0) ); Bxx = BX0*exp(-rp/rX)*pow(rp/max(aTinyNumber,r),2); } //Bdisk Bdisk = BD0*exp(-fabs(z)/Z0); if (r > rcD) Bdisk *= exp(-(r-r_Sun)/R0); //Bhalo if (fabs(z) < Z0H) { double Z1H = 0.2*kpc; Bhalo = (BH0/(1.+pow((fabs(z)-Z0H)/Z1H,2)))*(r/R0H)*exp(1.-r/R0H); } else { double Z1H = 0.4*kpc; Bhalo = (BH0/(1.+pow((fabs(z)-Z0H)/Z1H,2)))*(r/R0H)*exp(1.-r/R0H); } // B_r should change sign at z < 0 in order to have "X shape" if (z<0) { b_r[ind_sp] = - Bxx*cos(ThetaX); } else { b_r[ind_sp] = Bxx*cos(ThetaX); } b_z[ind_sp] = Bxx*sin(ThetaX); b_phi[ind_sp] = Bhalo + Bdisk; b_r[ind_sp] *= microgauss; b_phi[ind_sp] *= microgauss; b_z[ind_sp] *= microgauss; // this ensure that |B| doesn't go to zero (setting lower limit to 0.01*B_inf ~ 0.001*nanogauss) double modB = sqrt( b_r[ind_sp]*b_r[ind_sp] + b_phi[ind_sp]*b_phi[ind_sp] + b_z[ind_sp]*b_z[ind_sp] ) + 0.01*B_inf; if (z_vec[iz] == 0) { cout << x_vec[ix]/kpc << "\t" << y_vec[iy]/kpc << "\t" << z_vec[iz]/kpc << "\t" << " br = " << b_r[ind_sp] << " bz = " << b_z[ind_sp] << endl; cout << rp << "\t" << ThetaX << "\t" << Bxx << endl; } if (modB == 0) cout << "WARNING" << endl; b_r[ind_sp] /= modB; b_phi[ind_sp] /= modB; b_z[ind_sp] /= modB; } #endif } void DRAGONCELLO::initSource(void) { cout << "Initializing source term..." << endl; double sourceProfile = 0.; double injSpectrum = 0.; for (int ix = 0; ix < nx; ++ix) for (int iy = 0; iy < ny; ++iy) for (int iz = 0; iz < nz; ++iz) { for (int ip = 0; ip < np; ++ip) { sourceProfile = 1.; double sigma = 0.3*kpc; #ifdef REALISTIC_SOURCE // // realistic source distribution: Lorimer et al., MNRAS 372:777 (2006) // sourceProfile = exp( -(z_vec[iz]*z_vec[iz]) / (sigma*sigma) ); sourceProfile *= pow( x_vec[ix]/r_Sun , 1.9 )*exp( -5.00*(x_vec[ix]-r_Sun)/r_Sun - fabs(z_vec[iz])/sigma ); #endif #ifdef GREEN_FUNCTION // // Green-funtion test: point-like source located at (R,z) = (X_0,Z_0) and width ~ SIGMA_0 // [ see Appendix B.1 in Cerri et al., JCAP 10:019 (2017) ] // double alpha0 = M_PI/4.; sourceProfile = ( 1./(SIGMA_0*SIGMA_0*2.* M_PI) ) * exp( -( pow( (x_vec[ix] - X_0), 2.) + pow( (z_vec[iz] - Z_0), 2.) ) / ( 2.*SIGMA_0*SIGMA_0 ) ); #endif #ifdef ANALYTIC_SOLUTION_TEST // // analytical-solution test described in Kissmann, APP 55:37 (2014) // [ see Appendix B.2 in Cerri et al., JCAP 10:019 (2017) ] // long int ind = index(ix,iy,iz,ip); double kR = 0.5*M_PI/(xmax-xmin); double kH = M_PI/(zmax-zmin); double psi = cos(kR*x_vec[ix])*cos(kH*z_vec[iz]); double dpsidr = - kR*sin(kR*x_vec[ix])*cos(kH*z_vec[iz]); double dpsidz = - kH*cos(kR*x_vec[ix])*sin(kH*z_vec[iz]); double d2psidrdz = kR*kH*sin(kR*x_vec[ix])*sin(kH*z_vec[iz]); sourceProfile = ( kR*kR*D_rr[ind] + kH*kH*D_zz[ind] )*psi - 2.*D_rz[ind]*d2psidrdz - u_r[ind]*dpsidr - u_z[ind]*dpsidz ; #endif injSpectrum = pow( p_vec[ip]/p_ref, injSlope); sourceTerm[index(ix,iy,iz,ip)] = injSpectrum * sourceProfile; } } } void DRAGONCELLO::initAnisoSpatialDiffusion(void) { cout << "Initializing *ANISOTROPIC* diffusion term..." << endl; double slope_para = 0; double slope_perp = 0; for (int ix = 0; ix < nx; ++ix) for (int iy = 0; iy < ny; ++iy) for (int iz = 0; iz < nz; ++iz) { long int ind_sp = indexSpatial(ix,iy,iz); for (int ip = 0; ip < np; ++ip) { long int ind_tot = index(ix,iy,iz,ip); slope_para = pow((p_vec[ip] / reference_rigidity), delta_para); slope_perp = pow((p_vec[ip] / reference_rigidity), delta_perp); Dpara[ind_tot] = D0para*slope_para; Dperp[ind_tot] = D0perp*slope_perp; D_rr[ind_tot] = Dperp[ind_tot] + (Dpara[ind_tot]-Dperp[ind_tot])*b_r[ind_sp]*b_r[ind_sp]; D_rz[ind_tot] = (Dpara[ind_tot]-Dperp[ind_tot])*b_r[ind_sp]*b_z[ind_sp]; D_zz[ind_tot] = Dperp[ind_tot] + (Dpara[ind_tot]-Dperp[ind_tot])*b_z[ind_sp]*b_z[ind_sp]; // check: diffusion timescales should be larger than time step! if (ix==nx/2 && iz==nz/2 && ip%1==0) { cout << "*PARALLEL* diffusion timescale at p = " << p_vec[ip]/GeV << ": " << zmax*zmax/Dpara[index(ix,iy,iz,ip)]/Myr << " Myr " << endl; cout << "*PERPENDICULAR* diffusion timescale at p = " << p_vec[ip]/GeV << ": " << xmax*xmax/Dperp[index(ix,iy,iz,ip)]/Myr << " Myr " << endl; cout << "*PARALLEL* diffusion timescale across a bin at p = " << p_vec[ip]/GeV << ": " << deltaz*deltaz/Dpara[index(ix,iy,iz,ip)]/Myr << " Myr " << endl; cout << "*PERPENDICULAR* diffusion timescale across a bin at p = " << p_vec[ip]/GeV << ": " << deltax*deltax/Dperp[index(ix,iy,iz,ip)]/Myr << " Myr " << endl; } } } } void DRAGONCELLO::initDriftLikeVelocities(void) { // // see Appendix A in Cerri et al., JCAP 10:019 (2017) // cout << "Initializing drift-like velocities..." << endl; for (int ix = 0; ix < nx; ++ix) for (int iy = 0; iy < ny; ++iy) for (int iz = 0; iz < nz; ++iz) for (int ip = 0; ip < np; ++ip) { long int ind = index(ix,iy,iz,ip); long int ind_rup, ind_rdown, ind_zup, ind_zdown; ind_rup = (ix < nx-1) ? index(ix+1,iy,iz,ip) : ind; ind_zup = (iz < nz-1) ? index(ix,iy,iz+1,ip) : ind; ind_rdown = (ix > 0) ? index(ix-1,iy,iz,ip) : ind; ind_zdown = (iz > 0) ? index(ix,iy,iz-1,ip) : ind; u_r[ind] = D_rr[ind]/max(aTinyNumber,x_vec[ix]) + (D_rr[ind_rup]-D_rr[ind_rdown])/(2.*deltaxCentral[ix]) + (D_rz[ind_zup]-D_rz[ind_zdown])/(2.*deltazCentral[iz]); u_z[ind] = D_rz[ind]/max(aTinyNumber,x_vec[ix]) + (D_rz[ind_rup]-D_rz[ind_rdown])/(2.*deltaxCentral[ix]) + (D_zz[ind_zup]-D_zz[ind_zdown])/(2.*deltazCentral[iz]); } } void DRAGONCELLO::initEloss(void) { if (A > 0) cout << "Calculating Hadronic energy losses..." << endl; else cout << "Calculating Leptonic energy losses..." << endl; double value = 0.; for (int ix = 0; ix < nx; ++ix) for (int iy = 0; iy < ny; ++iy) for (int iz = 0; iz < nz; ++iz) for (int ip = 0; ip < np; ++ip) { double profile = 1.; #ifdef TEST_REALISTIC profile = 1. * exp(-(z_vec[iz]*z_vec[iz]/(2.*z_losses*z_losses))); #endif if (A>0) { value = hadronicElossNorm * gasDensity; energyLossTerm[index(ix,iy,iz,ip)] = 0.; } else { value = leptonicElossConstant*profile + leptonicElossNorm * pow2(p_vec[ip]/GeV) * pow2(magneticField*profile/muG); //erg/s energyLossTerm[index(ix,iy,iz,ip)] = value; } if (ix==nx/2 && iz==nz/2 && ip%10==0) cout << "eloss timescale at p = " << p_vec[ip]/GeV << ": " << p_vec[ip]/energyLossTerm[index(ix,iy,iz,ip)]/Myr << " Myr " << endl; } } void DRAGONCELLO::dumpSpectra(void) { cout << "Dumping spectra ..." << endl; ofstream outfile; outfile.open("output/galaxy_spectra.txt"); outfile << "#p [GeV]" << " " << "N " << " " << "Source " << " " << "Dxx " << " " << "Dpp " << endl; outfile << scientific << setprecision(2); for (int ip = 0; ip < np; ++ip) { outfile << p_vec[ip] / GeV << " "; outfile << N[index(ixsun,0,izsun,ip)] << " "; outfile << sourceTerm[index(ixsun,0,izsun,ip)] << " "; outfile << diffusionCoefficient[index(ixsun,0,izsun,ip)] << " "; outfile << reaccelerationCoefficient[index(ixsun,0,izsun,ip)] << " "; outfile << energyLossTerm[index(ixsun,0,izsun,ip)] << endl; } outfile.close(); } void DRAGONCELLO::dumpProfiles(void) { cout << "Dumping profiles ..." << endl; ofstream outfile; outfile.open("output/galaxy_profiles.txt"); outfile << "#z [kpc] " << " " << "N " << " " << "Source " << " " << "Dxx " << " " << "Dpp " << endl; outfile << scientific << setprecision(2); for (int iz = 0; iz < nz; ++iz) { outfile << z_vec[iz] / kpc << " "; outfile << N[index(ixsun,0,iz,10)] << " "; outfile << sourceTerm[index(ixsun,0,iz,10)] << " "; outfile << diffusionCoefficient[index(ixsun,0,iz,10)] << " "; outfile << reaccelerationCoefficient[index(ixsun,0,iz,10)] << " "; outfile << energyLossTerm[index(ixsun,0,iz,10)] << endl; } outfile.close(); } void DRAGONCELLO::dumpProfiles2D(void) { cout << "Dumping r-z maps ..." << endl; ofstream outfile; outfile.open("output/2DAnisoMaps.txt"); outfile << "#r" << "\t" << "z" << "\t" << "N" << "\n"; // " " << "Source " << " " << "Dxx " << " " << "Dpp " << endl; outfile << scientific << setprecision(2); for (int ix = 0; ix < nx; ++ix) for (int iz = 0; iz < nz; ++iz) { outfile << x_vec[ix] / kpc << " "; outfile << z_vec[iz] / kpc << " "; outfile << N[index(ix,0,iz,0)] * cm3 * GeV << " "; outfile << sourceTerm[index(ix,0,iz,0)] << " "; outfile << diffusionCoefficient[index(ix,0,iz,0)] << " "; outfile << reaccelerationCoefficient[index(ix,0,iz,0)] << " "; outfile << energyLossTerm[index(ix,0,iz,0)] << endl; } outfile.close(); } void DRAGONCELLO::initCN2Daniso(void) { // // see Appendix A in Cerri et al., JCAP 10:019 (2017) // cout << "Calculating the CN coefficients for *ANISOTROPIC* case..." << endl; int iy = 0; for (int ix = 0; ix < nx; ++ix) for (int iz = 0; iz < nz; ++iz) for (int ip = 0; ip < np; ++ip) { long int ind = index(ix,iy,iz,ip); upperDiagonalR.push_back( D_rr[ind] / (deltaxUp[ix]*deltaxCentral[ix]) + u_r[ind]/(2.*deltaxCentral[ix]) ); centralDiagonalR.push_back( 2. * D_rr[ind] / (deltaxUp[ix]*deltaxDown[ix]) ); lowerDiagonalR.push_back( D_rr[ind] / (deltaxDown[ix]*deltaxCentral[ix]) - u_r[ind]/(2.*deltaxCentral[ix]) ); upperDiagonalZ.push_back( D_zz[ind] / (deltazUp[iz]*deltazCentral[iz]) + u_z[ind]/(2.*deltazCentral[iz]) ); centralDiagonalZ.push_back( 2. * D_zz[ind] / (deltazUp[iz]*deltazDown[iz]) ); lowerDiagonalZ.push_back( D_zz[ind] / (deltazDown[iz]*deltazCentral[iz]) - u_z[ind]/(2.*deltazCentral[iz]) ); } }
34.027027
170
0.518305
[ "shape", "vector", "model", "3d" ]
67cf06485419b5b3962a8a59799a5878d3da14c5
2,600
hpp
C++
mpc/kmpc_casadi/casadi_windows/include/casadi/core/external.hpp
se-hwan/MIT_Driverless
7674b29887ba518c134cfba805432f9c98f92270
[ "MIT" ]
29
2020-05-11T16:59:10.000Z
2022-02-24T11:30:16.000Z
mpc/kmpc_casadi/casadi_windows/include/casadi/core/external.hpp
se-hwan/MIT_Driverless
7674b29887ba518c134cfba805432f9c98f92270
[ "MIT" ]
1
2021-02-04T04:20:55.000Z
2021-02-28T20:47:02.000Z
mpc/kmpc_casadi/casadi_windows/include/casadi/core/external.hpp
se-hwan/MIT_Driverless
7674b29887ba518c134cfba805432f9c98f92270
[ "MIT" ]
10
2020-06-22T22:41:32.000Z
2021-12-15T12:26:13.000Z
/* * This file is part of CasADi. * * CasADi -- A symbolic framework for dynamic optimization. * Copyright (C) 2010-2014 Joel Andersson, Joris Gillis, Moritz Diehl, * K.U. Leuven. All rights reserved. * Copyright (C) 2011-2014 Greg Horn * * CasADi 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 3 of the License, or (at your option) any later version. * * CasADi 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 CasADi; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ #ifndef CASADI_EXTERNAL_HPP #define CASADI_EXTERNAL_HPP #include "function.hpp" #include "importer.hpp" namespace casadi { /** \brief Load an external function from a shared library * \param name Name as in the label assigned to a CasADi Function object: * Function(name,...,...) * Will be used to look up symbols/functions named eg. <name>_eval * Use `nm` (linux/osx) or `depends.exe` (win) to check which symbols are present * in your shared library * * File name is assumed to be ./<name>.so */ CASADI_EXPORT Function external(const std::string& name, const Dict& opts=Dict()); /** \brief Load an external function from a shared library * * \param name Name as in the label assigned to a CasADi Function object: * Function(name,...,...) * Will be used to look up symbols/functions named eg. <name>_eval * Use `nm` (linux/osx) or `depends.exe` (win) to check which symbols are present * in your shared library * \param bin_name File name of the shared library */ CASADI_EXPORT Function external(const std::string& name, const std::string& bin_name, const Dict& opts=Dict()); /** \brief Load a just-in-time compiled external function * File name given */ CASADI_EXPORT Function external(const std::string& name, const Importer& li, const Dict& opts=Dict()); } // namespace casadi #endif // CASADI_EXTERNAL_HPP
39.393939
95
0.649231
[ "object" ]
67d03df54f23f3c86ccbfc8b4bbd36b94ad617f8
36,676
cpp
C++
Tools/SceneCommon/SceneTools.cpp
niello/deusexmachina
2f698054fe82d8b40a0a0e58b86d64ffed0de06c
[ "MIT" ]
15
2019-05-07T11:26:13.000Z
2022-01-12T18:26:45.000Z
Tools/SceneCommon/SceneTools.cpp
niello/deusexmachina
2f698054fe82d8b40a0a0e58b86d64ffed0de06c
[ "MIT" ]
16
2021-10-04T17:15:31.000Z
2022-03-20T09:34:29.000Z
Tools/SceneCommon/SceneTools.cpp
niello/deusexmachina
2f698054fe82d8b40a0a0e58b86d64ffed0de06c
[ "MIT" ]
2
2019-04-28T23:27:48.000Z
2019-05-07T11:26:18.000Z
#include <SceneTools.h> #include <Logging.h> #include <Utils.h> #include <ParamsUtils.h> #include <meshoptimizer.h> #include <acl/core/ansi_allocator.h> #include <acl/core/unique_ptr.h> #include <acl/algorithm/uniformly_sampled/encoder.h> #include <IL/il.h> #include <LinearMath/btConvexHullComputer.h> #include <regex> namespace acl { typedef std::unique_ptr<AnimationClip, Deleter<AnimationClip>> AnimationClipPtr; typedef std::unique_ptr<RigidSkeleton, Deleter<RigidSkeleton>> RigidSkeletonPtr; } namespace fs = std::filesystem; std::string GetRelativeNodePath(std::vector<std::string>&& From, std::vector<std::string>&& To) { std::string RelPath; while (!From.empty() && !To.empty() && From.back() == To.back()) { From.pop_back(); To.pop_back(); } for (const auto& NodeID : From) { if (!RelPath.empty()) RelPath += '.'; RelPath += '^'; } if (!To.empty()) To.erase(To.begin()); for (auto It = To.crbegin(); It != To.crend(); ++It) { if (!RelPath.empty()) RelPath += '.'; RelPath += GetValidNodeName(*It); } return RelPath; } //--------------------------------------------------------------------- bool LoadSceneSettings(const std::filesystem::path& Path, CSceneSettings& Out) { //!!!FIXME: don't convert path to string! Use path in API! Data::CParams SceneSettings; if (!ParamsUtils::LoadParamsFromHRD(Path.generic_string().c_str(), SceneSettings)) { std::cout << "Couldn't load scene settings from " << Path; return false; } const Data::CParams* pMap; if (ParamsUtils::TryGetParam(pMap, SceneSettings, "Effects")) for (const auto& Pair : *pMap) Out.EffectsByType.emplace(Pair.first.ToString(), Pair.second.GetValue<std::string>()); if (ParamsUtils::TryGetParam(pMap, SceneSettings, "Params")) for (const auto& Pair : *pMap) Out.EffectParamAliases.emplace(Pair.first.ToString(), Pair.second.GetValue<std::string>()); return true; } //--------------------------------------------------------------------- void ProcessGeometry(const std::vector<CVertex>& RawVertices, const std::vector<unsigned int>& RawIndices, std::vector<CVertex>& Vertices, std::vector<unsigned int>& Indices) { if (RawIndices.empty()) { // Index not indexed mesh Indices.resize(RawVertices.size()); const auto VertexCount = meshopt_generateVertexRemap(Indices.data(), nullptr, RawVertices.size(), RawVertices.data(), RawVertices.size(), sizeof(CVertex)); Vertices.resize(VertexCount); meshopt_remapVertexBuffer(Vertices.data(), RawVertices.data(), RawVertices.size(), sizeof(CVertex), Indices.data()); } else { // Remap indexed mesh std::vector<unsigned int> Remap(RawVertices.size()); const auto VertexCount = meshopt_generateVertexRemap(Remap.data(), RawIndices.data(), RawIndices.size(), RawVertices.data(), RawVertices.size(), sizeof(CVertex)); Vertices.resize(VertexCount); meshopt_remapVertexBuffer(Vertices.data(), RawVertices.data(), RawVertices.size(), sizeof(CVertex), Remap.data()); Indices.resize(RawIndices.size()); meshopt_remapIndexBuffer(Indices.data(), RawIndices.data(), RawIndices.size(), Remap.data()); } meshopt_optimizeVertexCache(Indices.data(), Indices.data(), Indices.size(), Vertices.size()); meshopt_optimizeOverdraw(Indices.data(), Indices.data(), Indices.size(), &Vertices[0].Position.x, Vertices.size(), sizeof(CVertex), 1.05f); meshopt_optimizeVertexFetch(Vertices.data(), Indices.data(), Indices.size(), Vertices.data(), Vertices.size(), sizeof(CVertex)); // TODO: meshopt_generateShadowIndexBuffer for Z prepass and shadow rendering. // Also can separate positions from all other data into 2 vertex streams, and use only positions for shadows & Z prepass. } //--------------------------------------------------------------------- void WriteVertexComponent(std::ostream& Stream, EVertexComponentSemantic Semantic, EVertexComponentFormat Format, uint8_t Index, uint8_t StreamIndex) { WriteStream(Stream, static_cast<uint8_t>(Semantic)); WriteStream(Stream, static_cast<uint8_t>(Format)); WriteStream(Stream, Index); WriteStream(Stream, StreamIndex); } //--------------------------------------------------------------------- bool WriteDEMMesh(const fs::path& DestPath, const std::map<std::string, CMeshGroup>& SubMeshes, const CVertexFormat& VertexFormat, size_t BoneCount, CThreadSafeLog& Log) { fs::create_directories(DestPath.parent_path()); std::ofstream File(DestPath, std::ios_base::binary | std::ios_base::trunc); if (!File) { Log.LogError("Error opening an output file " + DestPath.string()); return false; } if (VertexFormat.BlendWeightSize != 8 && VertexFormat.BlendWeightSize != 16 && VertexFormat.BlendWeightSize != 32) Log.LogWarning("Unsupported blend weight size, defaulting to full-precision floats (32). Supported values are 8/16/32."); size_t TotalVertices = 0; size_t TotalIndices = 0; for (const auto& Pair : SubMeshes) { TotalVertices += Pair.second.Vertices.size(); TotalIndices += Pair.second.Indices.size(); } WriteStream<uint32_t>(File, 'MESH'); // Format magic value WriteStream<uint32_t>(File, 0x00010000); // Version 0.1.0.0 WriteStream(File, static_cast<uint32_t>(SubMeshes.size())); WriteStream(File, static_cast<uint32_t>(TotalVertices)); WriteStream(File, static_cast<uint32_t>(TotalIndices)); // One index size in bytes const bool Indices32 = (TotalVertices > std::numeric_limits<uint16_t>().max()); if (Indices32) { Log.LogWarning("Mesh " + DestPath.filename().string() + " has " + std::to_string(TotalVertices) + " vertices and will use 32-bit indices"); WriteStream<uint8_t>(File, 4); } else { WriteStream<uint8_t>(File, 2); } const uint32_t VertexComponentCount = 1 + // Position VertexFormat.NormalCount + VertexFormat.TangentCount + VertexFormat.BitangentCount + VertexFormat.UVCount + VertexFormat.ColorCount + (VertexFormat.BonesPerVertex ? 2 : 0); // Blend indices and weights WriteStream(File, VertexComponentCount); WriteVertexComponent(File, EVertexComponentSemantic::VCSem_Position, EVertexComponentFormat::VCFmt_Float32_3, 0, 0); for (uint8_t i = 0; i < VertexFormat.NormalCount; ++i) WriteVertexComponent(File, EVertexComponentSemantic::VCSem_Normal, EVertexComponentFormat::VCFmt_Float32_3, i, 0); for (uint8_t i = 0; i < VertexFormat.TangentCount; ++i) WriteVertexComponent(File, EVertexComponentSemantic::VCSem_Tangent, EVertexComponentFormat::VCFmt_Float32_3, i, 0); for (uint8_t i = 0; i < VertexFormat.BitangentCount; ++i) WriteVertexComponent(File, EVertexComponentSemantic::VCSem_Bitangent, EVertexComponentFormat::VCFmt_Float32_3, i, 0); for (uint8_t i = 0; i < VertexFormat.ColorCount; ++i) WriteVertexComponent(File, EVertexComponentSemantic::VCSem_Color, EVertexComponentFormat::VCFmt_UInt8_4_Norm, i, 0); for (uint8_t i = 0; i < VertexFormat.UVCount; ++i) WriteVertexComponent(File, EVertexComponentSemantic::VCSem_TexCoord, EVertexComponentFormat::VCFmt_Float32_2, i, 0); if (VertexFormat.BonesPerVertex) { if (BoneCount > 256) // Could use unsigned, but it is not supported in D3D9. > 32k bones is nonsense anyway. WriteVertexComponent(File, EVertexComponentSemantic::VCSem_BoneIndices, EVertexComponentFormat::VCFmt_SInt16_4, 0, 0); else WriteVertexComponent(File, EVertexComponentSemantic::VCSem_BoneIndices, EVertexComponentFormat::VCFmt_UInt8_4, 0, 0); // Max 4 bones per vertex are supported, at least for now assert(VertexFormat.BonesPerVertex < 5); if (VertexFormat.BlendWeightSize == 8) { WriteVertexComponent(File, EVertexComponentSemantic::VCSem_BoneWeights, EVertexComponentFormat::VCFmt_UInt8_4_Norm, 0, 0); } else if (VertexFormat.BlendWeightSize == 16) { // FIXME: shader defaults missing components to (0, 0, 0, 1), making the last weight incorrect //if (VertexFormat.BonesPerVertex <= 2) // WriteVertexComponent(File, EVertexComponentSemantic::VCSem_BoneWeights, EVertexComponentFormat::VCFmt_UInt16_2_Norm, 0, 0); //else WriteVertexComponent(File, EVertexComponentSemantic::VCSem_BoneWeights, EVertexComponentFormat::VCFmt_UInt16_4_Norm, 0, 0); } else { // FIXME: shader defaults missing components to (0, 0, 0, 1), making the last weight incorrect //if (VertexFormat.BonesPerVertex == 1) // WriteVertexComponent(File, EVertexComponentSemantic::VCSem_BoneWeights, EVertexComponentFormat::VCFmt_Float32_1, 0, 0); //else if (VertexFormat.BonesPerVertex == 2) // WriteVertexComponent(File, EVertexComponentSemantic::VCSem_BoneWeights, EVertexComponentFormat::VCFmt_Float32_2, 0, 0); //else if (VertexFormat.BonesPerVertex == 3) // WriteVertexComponent(File, EVertexComponentSemantic::VCSem_BoneWeights, EVertexComponentFormat::VCFmt_Float32_3, 0, 0); //else WriteVertexComponent(File, EVertexComponentSemantic::VCSem_BoneWeights, EVertexComponentFormat::VCFmt_Float32_4, 0, 0); } } // Save mesh groups (always 1 LOD now, may change later) // TODO: test if index offset is needed, each submesh starts from zero now for (const auto& [SubMeshID, SubMesh] : SubMeshes) { WriteStream<uint32_t>(File, 0); // First vertex WriteStream(File, static_cast<uint32_t>(SubMesh.Vertices.size())); // Vertex count WriteStream<uint32_t>(File, 0); // First index WriteStream(File, static_cast<uint32_t>(SubMesh.Indices.size())); // Index count WriteStream(File, static_cast<uint8_t>(EPrimitiveTopology::Prim_TriList)); WriteStream(File, SubMesh.AABB.Min); WriteStream(File, SubMesh.AABB.Max); } // Align vertex and index data offsets to 16 bytes. It should speed up loading from memory-mapped file. // TODO: test! // Delay writing vertex and index data offsets. const auto DataOffsetsPos = File.tellp(); WriteStream<uint32_t>(File, 0); WriteStream<uint32_t>(File, 0); uint32_t VertexStartPos = static_cast<uint32_t>(DataOffsetsPos) + 2 * sizeof(uint32_t); if (const auto VertexStartPadding = VertexStartPos % 16) { VertexStartPos += (16 - VertexStartPadding); for (auto i = VertexStartPadding; i < 16; ++i) WriteStream<uint8_t>(File, 0); } assert(!(static_cast<uint32_t>(File.tellp()) % 16)); for (const auto& Pair : SubMeshes) { const auto& Vertices = Pair.second.Vertices; for (const auto& Vertex : Vertices) { WriteStream(File, Vertex.Position); if (VertexFormat.NormalCount) WriteStream(File, Vertex.Normal); if (VertexFormat.TangentCount) WriteStream(File, Vertex.Tangent); if (VertexFormat.BitangentCount) WriteStream(File, Vertex.Bitangent); if (VertexFormat.ColorCount) WriteStream(File, Vertex.Color); for (size_t i = 0; i < VertexFormat.UVCount; ++i) WriteStream(File, Vertex.UV[i]); if (VertexFormat.BonesPerVertex) { // Blend indices are always 4-component for (int i = 0; i < 4; ++i) { const int BoneIndex = (i < MaxBonesPerVertex) ? Vertex.BlendIndices[i] : 0; if (BoneCount > 256) WriteStream(File, static_cast<int16_t>(BoneIndex)); else WriteStream(File, static_cast<uint8_t>(BoneIndex)); } if (VertexFormat.BlendWeightSize == 8) { WriteStream<uint32_t>(File, Vertex.BlendWeights8); } else if (VertexFormat.BlendWeightSize == 16) { // FIXME: shader defaults missing components to (0, 0, 0, 1), making the last weight incorrect //if (VertexFormat.BonesPerVertex <= 2) // File.write(reinterpret_cast<const char*>(Vertex.BlendWeights16), 2 * sizeof(uint16_t)); //else File.write(reinterpret_cast<const char*>(Vertex.BlendWeights16), 4 * sizeof(uint16_t)); } else { // FIXME: shader defaults missing components to (0, 0, 0, 1), making the last weight incorrect //File.write(reinterpret_cast<const char*>(Vertex.BlendWeights32), VertexFormat.BonesPerVertex * sizeof(float)); File.write(reinterpret_cast<const char*>(Vertex.BlendWeights32), 4 * sizeof(float)); } } } } uint32_t IndexStartPos = static_cast<uint32_t>(File.tellp()); if (const auto IndexStartPadding = IndexStartPos % 16) { IndexStartPos += (16 - IndexStartPadding); for (auto i = IndexStartPadding; i < 16; ++i) WriteStream<uint8_t>(File, 0); } assert(!(static_cast<uint32_t>(File.tellp()) % 16)); for (const auto& Pair : SubMeshes) { const auto& Indices = Pair.second.Indices; if (Indices32) { static_assert(sizeof(unsigned int) == 4); File.write(reinterpret_cast<const char*>(Indices.data()), Indices.size() * 4); } else { for (auto Index : Indices) WriteStream(File, static_cast<uint16_t>(Index)); } } Log.LogInfo(DestPath.filename().generic_string() + " " + std::to_string(File.tellp()) + " bytes saved"); // Write delayed values File.seekp(DataOffsetsPos); WriteStream<uint32_t>(File, VertexStartPos); WriteStream<uint32_t>(File, IndexStartPos); return true; } //--------------------------------------------------------------------- bool ReadDEMMeshVertexPositions(const std::filesystem::path& Path, std::vector<float3>& Out, CThreadSafeLog& Log) { std::ifstream File(Path, std::ios_base::binary); if (!File) { Log.LogError("Can't open mesh file " + Path.generic_string()); return false; } // Check format magic and version if (ReadStream<uint32_t>(File) != 'MESH') return false; if (ReadStream<uint32_t>(File) != 0x00010000) return false; const auto SubMeshCount = ReadStream<uint32_t>(File); const auto VertexCount = ReadStream<uint32_t>(File); Out.resize(VertexCount); if (!VertexCount) return true; const auto IndexCount = ReadStream<uint32_t>(File); ReadStream<uint8_t>(File); // Skip index size size_t PosOffset = 0; size_t VertexSize = 0; bool PosFound = false; const auto VertexComponentCount = ReadStream<uint32_t>(File); for (uint32_t i = 0; i < VertexComponentCount; ++i) { const auto Semantic = static_cast<EVertexComponentSemantic>(ReadStream<uint8_t>(File)); const auto Format = static_cast<EVertexComponentFormat>(ReadStream<uint8_t>(File)); const size_t ComponentSize = GetVertexComponentSize(Format); VertexSize += ComponentSize; if (Semantic == EVertexComponentSemantic::VCSem_Position) PosFound = true; else if (!PosFound) PosOffset += ComponentSize; // Skip Index and StreamIndex ReadStream<uint8_t>(File); ReadStream<uint8_t>(File); } // Skip mesh group definitions, 41 byte each File.seekg(SubMeshCount * 41, std::ios_base::_Seekcur); const auto VertexDataOffset = ReadStream<uint32_t>(File); const auto IndexDataOffset = ReadStream<uint32_t>(File); // Seek to the first vertex position File.seekg(VertexDataOffset + PosOffset, std::ios_base::_Seekbeg); const auto RemainingVertexSize = VertexSize - sizeof(float3); for (uint32_t i = 0; i < VertexCount; ++i) { ReadStream(File, Out[i]); if (i < VertexCount - 1 && RemainingVertexSize > 0) File.seekg(RemainingVertexSize, std::ios_base::_Seekcur); } return true; } //--------------------------------------------------------------------- bool WriteDEMSkin(const fs::path& DestPath, const std::vector<CBone>& Bones, CThreadSafeLog& Log) { fs::create_directories(DestPath.parent_path()); std::ofstream File(DestPath, std::ios_base::binary | std::ios_base::trunc); if (!File) { Log.LogError("Error opening an output file " + DestPath.string()); return false; } WriteStream<uint32_t>(File, 'SKIN'); // Format magic value WriteStream<uint32_t>(File, 0x00010000); // Version 0.1.0.0 WriteStream(File, static_cast<uint32_t>(Bones.size())); WriteStream<uint32_t>(File, 0); // Padding to align matrices offset to 16 bytes boundary assert(!(static_cast<uint32_t>(File.tellp()) % 16)); for (const auto& Bone : Bones) WriteStream(File, Bone.InvLocalBindPose); for (const auto& Bone : Bones) { WriteStream(File, Bone.ParentBoneIndex); WriteStream(File, Bone.ID); } Log.LogInfo(DestPath.filename().generic_string() + " " + std::to_string(File.tellp()) + " bytes saved"); return true; } //--------------------------------------------------------------------- bool WriteDEMAnimation(const std::filesystem::path& DestPath, acl::IAllocator& ACLAllocator, const acl::AnimationClip& Clip, const std::vector<std::string>& NodeNames, const CLocomotionInfo* pLocomotionInfo, CThreadSafeLog& Log) { const auto AnimName = DestPath.filename().string(); const auto& Skeleton = Clip.get_skeleton(); const auto NodeCount = Skeleton.get_num_bones(); if (!NodeCount) { Log.LogWarning(std::string("Skipped saving empty animation ") + AnimName); return true; } if (Skeleton.get_bone(0).parent_index != acl::k_invalid_bone_index) { Log.LogError("Animation " + AnimName + " doesn't start from the root node (may be broken)!"); return false; } acl::TransformErrorMetric ACLErrorMetric; acl::CompressionSettings ACLSettings = acl::get_default_compression_settings(); ACLSettings.error_metric = &ACLErrorMetric; acl::OutputStats Stats; acl::CompressedClip* CompressedClip = nullptr; acl::ErrorResult ErrorResult = acl::uniformly_sampled::compress_clip(ACLAllocator, Clip, ACLSettings, CompressedClip, Stats); if (!ErrorResult.empty()) { Log.LogWarning(std::string("ACL failed to compress animation ") + AnimName + " for one of skeletons"); return true; } Log.LogDebug(std::string("ACL compressed animation ") + AnimName + " to " + std::to_string(CompressedClip->get_size()) + " bytes"); fs::create_directories(DestPath.parent_path()); std::ofstream File(DestPath, std::ios_base::out | std::ios_base::binary | std::ios_base::trunc); if (!File) { Log.LogError("Error opening an output file " + DestPath.string()); return false; } WriteStream<uint32_t>(File, 'ANIM'); // Format magic value WriteStream<uint32_t>(File, 0x00010000); // Version 0.1.0.0 WriteStream<float>(File, Clip.get_duration()); WriteStream<uint32_t>(File, Clip.get_num_samples()); WriteStream<uint16_t>(File, NodeCount); // Write skeleton info to be able to bind animation to the node hierarchy in DEM // Note that DEM requires all nodes without a parent to have a full path relative // to the root in their IDs. So for the root itself ID must be empty. WriteStream<uint16_t>(File, Skeleton.get_bone(0).parent_index); WriteStream(File, std::string{}); for (uint16_t i = 1; i < NodeCount; ++i) { WriteStream<uint16_t>(File, Skeleton.get_bone(i).parent_index); WriteStream(File, NodeNames[i]); } // For locomotion clips save locomotion info WriteStream<uint8_t>(File, pLocomotionInfo != nullptr); if (pLocomotionInfo) { const float Speed = CompareFloat(pLocomotionInfo->SpeedFromFeet, 0.f) ? pLocomotionInfo->SpeedFromRoot : pLocomotionInfo->SpeedFromFeet; WriteStream<float>(File, Speed); WriteStream(File, pLocomotionInfo->CycleStartFrame); WriteStream(File, pLocomotionInfo->LeftFootOnGroundFrame); WriteStream(File, pLocomotionInfo->RightFootOnGroundFrame); WriteVectorToStream(File, pLocomotionInfo->Phases); WriteMapToStream(File, pLocomotionInfo->PhaseNormalizedTimes); } // Align compressed clip data in a file to 16 bytes (plan to use memory mapped files for faster loading) uint32_t CurrPos = static_cast<uint32_t>(File.tellp()) + sizeof(uint8_t); // Added padding size if (const auto PaddingStart = CurrPos % 16) { WriteStream<uint8_t>(File, 16 - PaddingStart); for (auto i = PaddingStart; i < 16; ++i) WriteStream<uint8_t>(File, 0); } else { WriteStream<uint8_t>(File, 0); } assert(!(static_cast<uint32_t>(File.tellp()) % 16)); File.write(reinterpret_cast<const char*>(CompressedClip), CompressedClip->get_size()); Log.LogInfo(DestPath.filename().generic_string() + " " + std::to_string(File.tellp()) + " bytes saved" + (pLocomotionInfo ? ", including locomotion info" : "")); return true; } //--------------------------------------------------------------------- // FIXME: to common ancestor of FBX & glTF tools, to have access to a CF tool class data // Name = Task.TaskID.ToString() // TaskParams = Task.Params // DestDir = GetPath(Task.Params, "Output"); bool WriteDEMScene(const std::filesystem::path& DestDir, const std::string& Name, Data::CParams&& Nodes, const Data::CSchemeSet& Schemes, const Data::CParams& TaskParams, bool HRD, bool Binary, CThreadSafeLog& Log) { const std::string TaskName = GetValidResourceName(Name); Data::CParams Result; const Data::CParams* pTfmParams; if (ParamsUtils::TryGetParam(pTfmParams, TaskParams, "Transform")) { float3 Vec3Value; float4 Vec4Value; if (ParamsUtils::TryGetParam(Vec3Value, *pTfmParams, "S")) Result.emplace_back(CStrID("Scale"), Vec3Value); if (ParamsUtils::TryGetParam(Vec4Value, *pTfmParams, "R")) Result.emplace_back(CStrID("Rotation"), Vec4Value); if (ParamsUtils::TryGetParam(Vec3Value, *pTfmParams, "T")) Result.emplace_back(CStrID("Translation"), Vec3Value); } //if (Nodes.size() == 1) //{ // // TODO: Is it a good idea to save its only child as a root instead? // Result = std::move(Nodes[0].second.GetValue<Data::CParams>()); //} //else if (!Nodes.empty()) { Result.emplace_back(CStrID("Children"), std::move(Nodes)); } if (HRD) { const auto DestPath = DestDir / (TaskName + ".hrd"); if (!ParamsUtils::SaveParamsToHRD(DestPath.string().c_str(), Result)) { Log.LogError("Error serializing " + TaskName + " to text"); return false; } } if (Binary) { const auto DestPath = DestDir / (TaskName + ".scn"); if (!ParamsUtils::SaveParamsByScheme(DestPath.string().c_str(), Result, CStrID("SceneNode"), Schemes)) { Log.LogError("Error serializing " + TaskName + " to binary"); return false; } } return true; } //--------------------------------------------------------------------- void InitImageProcessing() { ilInit(); } //--------------------------------------------------------------------- void TermImageProcessing() { ilShutDown(); } //--------------------------------------------------------------------- std::string WriteTexture(const std::filesystem::path& SrcPath, const std::filesystem::path& DestDir, const Data::CParams& TaskParams, CThreadSafeLog& Log) { const auto RsrcName = GetValidResourceName(SrcPath.stem().string()); const auto SrcExtension = SrcPath.extension().generic_string(); // Search in order for the first matching conversion rule // TODO: preload and store as structs? std::string DestFormat; const Data::CDataArray* pTextures = nullptr; if (ParamsUtils::TryGetParam(pTextures, TaskParams, "Textures")) { for (const auto& Data : *pTextures) { const std::regex Rule(ParamsUtils::GetParam(Data.GetValue<Data::CParams>(), "Name", std::string{})); if (std::regex_match(SrcPath.generic_string(), Rule)) { DestFormat = ParamsUtils::GetParam(Data.GetValue<Data::CParams>(), "DestFormat", std::string{}); break; } } } fs::path DestPath = DestDir; if (DestFormat.empty()) { // No conversion required, copy file as is DestPath /= (RsrcName + SrcExtension); try { fs::create_directories(DestDir); fs::copy_file(SrcPath, DestPath, fs::copy_options::overwrite_existing); } catch (fs::filesystem_error& e) { Log.LogError("Error copying " + SrcPath.generic_string() + " to " + DestPath.generic_string() + ":\n" + e.what()); return {}; } } else { ILuint ImgId; ilGenImages(1, &ImgId); ilBindImage(ImgId); if (!ilLoadImage(SrcPath.string().c_str())) { Log.LogError("Can't load " + SrcPath.generic_string() + " for export, error: " + std::to_string(ilGetError())); return {}; } ilEnable(IL_FILE_OVERWRITE); if (DestFormat == "DXT5") { DestPath /= (RsrcName + ".dds"); ilSetInteger(IL_DXTC_FORMAT, IL_DXT5); ilSave(IL_DDS, DestPath.string().c_str()); } else if (DestFormat == "DXT5nm") { // FIXME: no normal map compression for now. Use NV texture tools or the like? DestPath /= (RsrcName + ".dds"); ilSave(IL_DDS, DestPath.string().c_str()); } else if (DestFormat == "DDS") { DestPath /= (RsrcName + ".dds"); ilSave(IL_DDS, DestPath.string().c_str()); } else if (DestFormat == "TGA") { DestPath /= (RsrcName + ".tga"); ilSetInteger(IL_TGA_RLE, IL_TRUE); //???!!!per-texture (per-rule) setting? ilSave(IL_TGA, DestPath.string().c_str()); } else { Log.LogWarning("Format " + DestFormat + " unknown, used for " + SrcPath.generic_string() + ", will copy as is"); DestPath /= (RsrcName + SrcExtension); ilSaveImage(DestPath.string().c_str()); } ilDeleteImages(1, &ImgId); } return DestPath.generic_string(); } //--------------------------------------------------------------------- // TODO: check if already created on this launch, don't recreate std::optional<std::string> GenerateCollisionShape(std::string ShapeType, const std::filesystem::path& ShapeDir, const std::string& MeshRsrcName, const CMeshAttrInfo& MeshInfo, const acl::Transform_32& GlobalTfm, const std::map<std::string, std::filesystem::path>& PathAliases, CThreadSafeLog& Log) { trim(ShapeType, " \t\n\r"); ToLower(ShapeType); if (ShapeType.empty()) return std::string{}; Log.LogInfo(std::string("Mesh ") + MeshRsrcName + " has an autogenerated collision shape: " + ShapeType); const float3 Center( (MeshInfo.AABB.Max.x + MeshInfo.AABB.Min.x) * 0.5f, (MeshInfo.AABB.Max.y + MeshInfo.AABB.Min.y) * 0.5f, (MeshInfo.AABB.Max.z + MeshInfo.AABB.Min.z) * 0.5f); const float3 Size( MeshInfo.AABB.Max.x - MeshInfo.AABB.Min.x, MeshInfo.AABB.Max.y - MeshInfo.AABB.Min.y, MeshInfo.AABB.Max.z - MeshInfo.AABB.Min.z); const float3 Scaling( acl::vector_get_x(GlobalTfm.scale), acl::vector_get_y(GlobalTfm.scale), acl::vector_get_z(GlobalTfm.scale)); Data::CParams CollisionShape; if (ShapeType == "box") { //!!!NB: AABB only, to use OBB add collision mesh manually! CollisionShape.emplace_back(CStrID("Type"), CStrID("Box")); CollisionShape.emplace_back(CStrID("Size"), Size); } else if (ShapeType == "sphere") { // FIXME: now circumscribed around AABB, need parameter for user to choose? CollisionShape.emplace_back(CStrID("Type"), CStrID("Sphere")); CollisionShape.emplace_back(CStrID("Radius"), 0.707107f * std::max({ Size.x, Size.y, Size.z })); } else if (ShapeType == "capsule") { std::vector<float> Dims{ Size.x, Size.y, Size.z }; auto MaxIt = std::max_element(Dims.begin(), Dims.end()); const float MaxDim = *MaxIt; const auto Axis = std::distance(Dims.begin(), MaxIt); Dims.erase(MaxIt); const float Diameter = *std::max_element(Dims.begin(), Dims.end()); // FIXME: now inscribed into AABB, need parameter for user to choose? switch (Axis) { case 0: CollisionShape.emplace_back(CStrID("Type"), CStrID("CapsuleX")); break; case 1: CollisionShape.emplace_back(CStrID("Type"), CStrID("CapsuleY")); break; case 2: CollisionShape.emplace_back(CStrID("Type"), CStrID("CapsuleZ")); break; } CollisionShape.emplace_back(CStrID("Radius"), Diameter * 0.5f); CollisionShape.emplace_back(CStrID("Height"), MaxDim - Diameter); } else if (ShapeType == "convex") { std::vector<float3> Vertices; if (!ReadDEMMeshVertexPositions(ResolvePathAliases(MeshInfo.MeshID, PathAliases), Vertices, Log)) return std::nullopt; if (Vertices.empty()) return std::string{}; btConvexHullComputer Conv; Conv.compute(Vertices[0].v, sizeof(float3), Vertices.size(), 0.f, 0.f); const int HullVertexCount = Conv.vertices.size(); if (!HullVertexCount) return std::string{}; CollisionShape.emplace_back(CStrID("Type"), CStrID("ConvexHull")); Data::CDataArray HullVertices(HullVertexCount); for (int i = 0; i < HullVertexCount; ++i) { const auto& HullVertex = Conv.vertices[i]; HullVertices[i].SetValue(float3(HullVertex.getX(), HullVertex.getY(), HullVertex.getZ())); } CollisionShape.emplace_back(CStrID("Vertices"), std::move(HullVertices)); } else if (ShapeType == "mesh") { // BVH mesh? } else { //???warning? Log.LogError(std::string("Mesh ") + MeshRsrcName + ": can't generate collision shape"); return std::nullopt; } if (ShapeType != "convex" && ShapeType != "mesh") CollisionShape.emplace_back(CStrID("Offset"), Center); CollisionShape.emplace_back(CStrID("Scaling"), Scaling); const auto ShapePath = ShapeDir / (MeshRsrcName + ".hrd"); if (!ParamsUtils::SaveParamsToHRD(ShapePath.string().c_str(), CollisionShape)) { Log.LogError("Error saving colision shape to " + ShapePath.generic_string()); return std::nullopt; } return ShapePath.generic_string(); } //--------------------------------------------------------------------- void FillNodeTransform(const acl::Transform_32& Tfm, Data::CParams& NodeSection) { static const CStrID sidTranslation("Translation"); static const CStrID sidRotation("Rotation"); static const CStrID sidScale("Scale"); constexpr acl::Vector4_32 Unit3 = { 1.f, 1.f, 1.f, 0.f }; constexpr acl::Vector4_32 Zero3 = { 0.f, 0.f, 0.f, 0.f }; constexpr acl::Quat_32 IdentityQuat = { 0.f, 0.f, 0.f, 1.f }; if (!acl::vector_all_near_equal3(Tfm.scale, Unit3)) NodeSection.emplace_back(sidScale, float3({ acl::vector_get_x(Tfm.scale), acl::vector_get_y(Tfm.scale), acl::vector_get_z(Tfm.scale) })); if (!acl::quat_near_equal(Tfm.rotation, IdentityQuat)) NodeSection.emplace_back(sidRotation, float4({ acl::quat_get_x(Tfm.rotation), acl::quat_get_y(Tfm.rotation), acl::quat_get_z(Tfm.rotation), acl::quat_get_w(Tfm.rotation) })); if (!acl::vector_all_near_equal3(Tfm.translation, Zero3)) NodeSection.emplace_back(sidTranslation, float3({ acl::vector_get_x(Tfm.translation), acl::vector_get_y(Tfm.translation), acl::vector_get_z(Tfm.translation) })); } //--------------------------------------------------------------------- static std::pair<size_t, size_t> FindFootOnGroundFrames(acl::Vector4_32 UpDir, const std::vector<acl::Vector4_32>& FootPositions) { if (FootPositions.empty()) return { std::numeric_limits<size_t>().max(), std::numeric_limits<size_t>().max() }; std::vector<float> Heights(FootPositions.size()); for (size_t i = 0; i < FootPositions.size(); ++i) Heights[i] = acl::vector_dot3(FootPositions[i], UpDir); const auto MinMax = std::minmax_element(Heights.cbegin(), Heights.cend()); const float Min = *MinMax.first; const float Max = *MinMax.second; const float Tolerance = (Max - Min) * 0.001f; size_t Start = 0, End = 0; // TODO: handle multiple ranges! bool PrevFrameDown = false; bool CurrFrameDown = (Heights[0] - Min < Tolerance); for (size_t i = 1; i < Heights.size(); ++i) { PrevFrameDown = CurrFrameDown; CurrFrameDown = (Heights[i] - Min < Tolerance); if (PrevFrameDown == CurrFrameDown) continue; if (CurrFrameDown) Start = i; else End = (i > 0) ? (i - 1) : (Heights.size() - 1); } return { Start, End }; } //--------------------------------------------------------------------- bool ComputeLocomotion(CLocomotionInfo& Out, float FrameRate, acl::Vector4_32 ForwardDir, acl::Vector4_32 UpDir, acl::Vector4_32 SideDir, const std::vector<acl::Vector4_32>& RootPositions, const std::vector<acl::Vector4_32>& LeftFootPositions, const std::vector<acl::Vector4_32>& RightFootPositions) { if (LeftFootPositions.empty() || RightFootPositions.empty() || LeftFootPositions.size() != RightFootPositions.size()) return false; ForwardDir = acl::vector_normalize3(ForwardDir); UpDir = acl::vector_normalize3(UpDir); SideDir = acl::vector_normalize3(SideDir); const size_t FrameCount = LeftFootPositions.size(); // Foot phase matching inspired by the method described in: // https://cdn.gearsofwar.com/thecoalition/publications/SIGGRAPH%202017%20-%20High%20Performance%20Animation%20in%20Gears%20ofWar%204%20-%20Abstract.pdf Out.Phases.resize(FrameCount); size_t PhaseStart = 0; for (size_t i = 0; i < FrameCount; ++i) { // Project foot offset onto the locomotion plane (fwd, up) and normalize it to get phase direction const auto Offset = acl::vector_sub(LeftFootPositions[i], RightFootPositions[i]); const auto ProjectedOffset = acl::vector_sub(Offset, acl::vector_mul(SideDir, acl::vector_dot3(Offset, SideDir))); const auto PhaseDir = acl::vector_normalize3(ProjectedOffset); const float CosA = acl::vector_dot3(PhaseDir, ForwardDir); const float SinA = acl::vector_dot3(acl::vector_cross3(PhaseDir, ForwardDir), SideDir); const float Angle = std::copysignf(RadToDeg(std::acosf(CosA)), SinA); // Could also use Angle = RadToDeg(std::atan2f(SinA, CosA)); // Calculate phase in degrees, where: // 0 - left behind right // 90 - left above right // 180 - left in front of right // 270 - left below right Out.Phases[i] = 180.f - Angle; // map 180 -> -180 to 0 -> 360 // Find a loop start (a frame where 360 becomes 0) // FIXME: is the current heuristic robust enough? if (i > 0 && (Out.Phases[i - 1] - Out.Phases[i]) > 180.f) PhaseStart = i; } Out.CycleStartFrame = static_cast<uint32_t>(PhaseStart); // Fill phase to time mapping const float InvFrame = (FrameCount > 1) ? (1.f / static_cast<float>(FrameCount - 1)) : 0.f; const size_t PhaseEnd = (PhaseStart > 0) ? (PhaseStart - 1) : (FrameCount > 1) ? (FrameCount - 2) : 0; size_t FrameIdx = PhaseStart; float PrevValue = Out.Phases[FrameIdx]; Out.PhaseNormalizedTimes.emplace(PrevValue, FrameIdx * InvFrame); while (true) { ++FrameIdx; // Filter out the last frame due to looping (the last frame is the first frame) if (FrameIdx >= FrameCount - 1) FrameIdx = 0; if (FrameIdx == PhaseStart) break; // Filter out decreasing frames to keep it monotone if (Out.Phases[FrameIdx] >= PrevValue) { PrevValue = Out.Phases[FrameIdx]; Out.PhaseNormalizedTimes.emplace(PrevValue, FrameIdx * InvFrame); } }; // Add sentinel frames to PhaseTimes to simplify runtime search Out.PhaseNormalizedTimes.emplace(Out.Phases[PhaseStart] + 360.f, PhaseStart * InvFrame); Out.PhaseNormalizedTimes.emplace(Out.Phases[PhaseEnd] - 360.f, PhaseEnd * InvFrame); // Locomotion speed is a speed with which a root moves while a foot stands on the ground. // Here we detect frame ranges with either foot planted. It is also used for "foot down" events. acl::Vector4_32 RootDiff = { 0.f, 0.f, 0.f, 0.f }; size_t FramesOnGround = 0; // Accumulate motion during the left foot on the ground... const auto LeftFoGFrames = FindFootOnGroundFrames(UpDir, LeftFootPositions); if (LeftFoGFrames.first < FrameCount) { Out.LeftFootOnGroundFrame = static_cast<uint32_t>(LeftFoGFrames.first); const auto RelRootStart = acl::vector_sub(RootPositions[LeftFoGFrames.first], LeftFootPositions[LeftFoGFrames.first]); const auto RelRootEnd = acl::vector_sub(RootPositions[LeftFoGFrames.second], LeftFootPositions[LeftFoGFrames.second]); RootDiff = acl::vector_add(RootDiff, acl::vector_sub(RelRootEnd, RelRootStart)); FramesOnGround += (LeftFoGFrames.second >= LeftFoGFrames.first) ? (LeftFoGFrames.second - LeftFoGFrames.first) : (FrameCount - LeftFoGFrames.first + LeftFoGFrames.second + 1); } // ...and the same for the right foot const auto RightFoGFrames = FindFootOnGroundFrames(UpDir, RightFootPositions); if (RightFoGFrames.first < FrameCount) { Out.RightFootOnGroundFrame = static_cast<uint32_t>(RightFoGFrames.first); const auto RelRootStart = acl::vector_sub(RootPositions[RightFoGFrames.first], RightFootPositions[RightFoGFrames.first]); const auto RelRootEnd = acl::vector_sub(RootPositions[RightFoGFrames.second], RightFootPositions[RightFoGFrames.second]); RootDiff = acl::vector_add(RootDiff, acl::vector_sub(RelRootEnd, RelRootStart)); FramesOnGround += (RightFoGFrames.second >= RightFoGFrames.first) ? (RightFoGFrames.second - RightFoGFrames.first) : (FrameCount - RightFoGFrames.first + RightFoGFrames.second + 1); } if (FramesOnGround) { //???or project RootDiff onto XZ plane? or store RootDiff as velocity instead of speed? const auto ForwardMovement = acl::vector_mul(ForwardDir, acl::vector_dot3(RootDiff, ForwardDir)); Out.SpeedFromFeet = acl::vector_length3(ForwardMovement) * FrameRate / static_cast<float>(FramesOnGround); } else { Out.SpeedFromFeet = 0.f; } // Try to extract averaged locomotion speed from the root motion. // Note that it can be not equal to SpeedFromFeet and may be even non-constant during the clip. { //???or project FullRootDiff onto XZ plane? or store FullRootDiff as velocity instead of speed? const auto FullRootDiff = acl::vector_sub(RootPositions.back(), RootPositions.front()); const auto ForwardMovement = acl::vector_mul(ForwardDir, acl::vector_dot3(FullRootDiff, ForwardDir)); Out.SpeedFromRoot = acl::vector_length3(ForwardMovement) * FrameRate / static_cast<float>(FrameCount); } return true; } //---------------------------------------------------------------------
37.046465
186
0.695605
[ "mesh", "shape", "vector", "transform" ]
67d224c66710d32a4e5b8229f10fc9627490c8bb
24,614
cpp
C++
src/libs/vk_utils/vk_utils/context.cpp
VladislavKhudziakov/renderer
af7b204c084cfe72ebf329228c88e42d70cb7a1e
[ "MIT" ]
null
null
null
src/libs/vk_utils/vk_utils/context.cpp
VladislavKhudziakov/renderer
af7b204c084cfe72ebf329228c88e42d70cb7a1e
[ "MIT" ]
null
null
null
src/libs/vk_utils/vk_utils/context.cpp
VladislavKhudziakov/renderer
af7b204c084cfe72ebf329228c88e42d70cb7a1e
[ "MIT" ]
null
null
null
#include "context.hpp" #include <logger/log.hpp> #include <cstdio> #include <cstring> #include <algorithm> namespace { template<typename... LogArgs> void log(const char* fmt, LogArgs&&... args) { constexpr const char* ignore[]{ "vmaFlushAllocation"}; for (const auto* ignored : ignore) { if (strstr(fmt, ignored) != nullptr) { return; } } printf(fmt, std::forward<LogArgs>(args)...); } } // namespace #ifndef VMA_IMPLEMENTATION #define VMA_IMPLEMENTATION #ifndef NDEBUG // #define VMA_DEBUG_LOG(format, ...) log(LOGGER_COLOR_MODIFIER_FG_BLUE "[DEBUG] [VMA] " format LOGGER_COLOR_MODIFIER_FG_DEFAULT "\n" __VA_OPT__(, ) __VA_ARGS__); // printf(LOGGER_COLOR_MODIFIER_FG_BLUE "[DEBUG] [VMA] " format LOGGER_COLOR_MODIFIER_FG_DEFAULT "\n" __VA_OPT__(, ) __VA_ARGS__); #endif #include <VulkanMemoryAllocator/src/vk_mem_alloc.h> #endif #include <vector> #include <cstring> #include <optional> namespace { std::optional<vk_utils::context> ctx; void merge_extensions_list(const std::vector<VkExtensionProperties>& props, const char** ext_list, uint32_t ext_count, std::vector<const char*>& out_extensions) { for (uint32_t i = 0; i < ext_count; ++i) { const auto required_ext_found = std::find_if(props.begin(), props.end(), [i, ext_list](const VkExtensionProperties& props) { return strcmp(props.extensionName, ext_list[i]) == 0; }); if (required_ext_found == props.end()) { continue; } const auto extension_was_added = std::find_if( out_extensions.begin(), out_extensions.end(), [i, &ext_list](const char* e) { return strcmp(e, ext_list[i]) == 0; }); if (extension_was_added == out_extensions.end()) { out_extensions.emplace_back(ext_list[i]); } } } void merge_layers_list(const std::vector<VkLayerProperties>& props, const char** l_list, uint32_t l_count, std::vector<const char*>& out_layers) { for (uint32_t i = 0; i < l_count; ++i) { const auto required_ext_found = std::find_if(props.begin(), props.end(), [i, l_list](const VkLayerProperties& props) { return strcmp(props.layerName, l_list[i]) == 0; }); if (required_ext_found == props.end()) { continue; } const auto layer_was_added = std::find_if( out_layers.begin(), out_layers.end(), [i, &l_list](const char* e) { return strcmp(e, l_list[i]) == 0; }); if (layer_was_added == out_layers.end()) { out_layers.emplace_back(l_list[i]); } } } bool check_device_extensions(VkPhysicalDevice device, const char** ext_names, uint32_t ext_count) { uint32_t curr_ext_count; vkEnumerateDeviceExtensionProperties(device, nullptr, &curr_ext_count, nullptr); std::vector<VkExtensionProperties> props{curr_ext_count}; vkEnumerateDeviceExtensionProperties(device, nullptr, &curr_ext_count, props.data()); for (int i = 0; i < ext_count; ++i) { const auto required_ext_found = std::find_if(props.begin(), props.end(), [i, ext_names](const VkExtensionProperties& props) { return strcmp(props.extensionName, ext_names[i]) == 0; }); if (required_ext_found == props.end()) { return false; } } return true; }; bool check_device_layers(VkPhysicalDevice device, const char** layers_names, uint32_t curr_layers_count) { uint32_t layers_count; vkEnumerateDeviceLayerProperties(device, &layers_count, nullptr); std::vector<VkLayerProperties> props{layers_count}; vkEnumerateDeviceLayerProperties(device, &layers_count, props.data()); for (int i = 0; i < curr_layers_count; ++i) { const auto required_ext_found = std::find_if(props.begin(), props.end(), [i, layers_names](const VkLayerProperties& props) { return strcmp(props.layerName, layers_names[i]) == 0; }); if (required_ext_found == props.end()) { return false; } } return true; }; bool check_device_queue_families(VkPhysicalDevice device, VkSurfaceKHR surface, vk_utils::context::queue_family_data* queue_families_indices) { uint32_t queue_families_count; vkGetPhysicalDeviceQueueFamilyProperties(device, &queue_families_count, nullptr); std::vector<VkQueueFamilyProperties> props{queue_families_count}; vkGetPhysicalDeviceQueueFamilyProperties(device, &queue_families_count, props.data()); for (int i = 0; i < queue_families_count; ++i) { auto& p = props[i]; VkBool32 surface_supported{}; vkGetPhysicalDeviceSurfaceSupportKHR(device, i, surface, &surface_supported); if (surface_supported && queue_families_indices[vk_utils::context::QUEUE_TYPE_PRESENT].index < 0) { queue_families_indices[vk_utils::context::QUEUE_TYPE_PRESENT].index = i; queue_families_indices[vk_utils::context::QUEUE_TYPE_PRESENT].max_queue_count = 1; } if (p.queueFlags & VK_QUEUE_GRAPHICS_BIT) { if (queue_families_indices[vk_utils::context::QUEUE_TYPE_GRAPHICS].index >= 0) { if (props[i].queueCount > props[queue_families_indices[vk_utils::context::QUEUE_TYPE_GRAPHICS].index].queueCount) { queue_families_indices[vk_utils::context::QUEUE_TYPE_GRAPHICS].index = i; queue_families_indices[vk_utils::context::QUEUE_TYPE_GRAPHICS].max_queue_count = props[i].queueCount; } } else { queue_families_indices[vk_utils::context::QUEUE_TYPE_GRAPHICS].index = i; queue_families_indices[vk_utils::context::QUEUE_TYPE_GRAPHICS].max_queue_count = props[i].queueCount; } } if (p.queueFlags & VK_QUEUE_COMPUTE_BIT) { if (queue_families_indices[vk_utils::context::QUEUE_TYPE_COMPUTE].index >= 0) { if (props[i].queueCount > props[queue_families_indices[vk_utils::context::QUEUE_TYPE_COMPUTE].index].queueCount) { queue_families_indices[vk_utils::context::QUEUE_TYPE_COMPUTE].index = i; queue_families_indices[vk_utils::context::QUEUE_TYPE_COMPUTE].max_queue_count = props[i].queueCount; } } else { queue_families_indices[vk_utils::context::QUEUE_TYPE_COMPUTE].index = i; queue_families_indices[vk_utils::context::QUEUE_TYPE_COMPUTE].max_queue_count = props[i].queueCount; } } if (p.queueFlags & VK_QUEUE_TRANSFER_BIT) { if (queue_families_indices[vk_utils::context::QUEUE_TYPE_TRANSFER].index >= 0) { if (props[i].queueCount > props[queue_families_indices[vk_utils::context::QUEUE_TYPE_TRANSFER].index].queueCount) { queue_families_indices[vk_utils::context::QUEUE_TYPE_TRANSFER].index = i; queue_families_indices[vk_utils::context::QUEUE_TYPE_TRANSFER].max_queue_count = props[i].queueCount; } } else { queue_families_indices[vk_utils::context::QUEUE_TYPE_TRANSFER].index = i; queue_families_indices[vk_utils::context::QUEUE_TYPE_TRANSFER].max_queue_count = props[i].queueCount; } } } for (int i = 0; i < vk_utils::context::QUEUE_TYPE_SIZE; ++i) { if (queue_families_indices[i].index < 0 && queue_families_indices[i].max_queue_count > 0) { return false; } } return true; }; const char* implicit_required_instance_layers[] = { "VK_LAYER_KHRONOS_validation"}; const char* implicit_required_instance_extensions[] = { VK_EXT_DEBUG_UTILS_EXTENSION_NAME}; const char* implicit_required_device_extensions[]{VK_KHR_SWAPCHAIN_EXTENSION_NAME}; const char* implicit_required_device_layers[] = { "VK_LAYER_KHRONOS_validation"}; } // namespace VkDevice vk_utils::context::device() const { return m_device; } const char* vk_utils::context::app_name() const { return m_app_name; } const vk_utils::context& vk_utils::context::get() { return *ctx; } VkInstance vk_utils::context::instance() const { return m_instance; } ERROR_TYPE vk_utils::context::init( const char* app_name, const context_init_info& context_init_info) { ctx.emplace(); ctx->m_app_name = app_name; PASS_ERROR(init_instance(app_name, context_init_info)); PASS_ERROR(init_debug_messenger(context_init_info)); VkSurfaceKHR sf{nullptr}; if (const auto err_code = context_init_info.surface_create_callback(ctx->m_instance, &sf); err_code != VK_SUCCESS) { RAISE_ERROR_FATAL(err_code, "Cannot init surface."); } ctx->m_surface.reset(ctx->m_instance, sf); PASS_ERROR(select_physical_device(context_init_info)); PASS_ERROR(init_device(context_init_info)); PASS_ERROR(init_memory_allocator()); PASS_ERROR(request_queues()); RAISE_ERROR_OK(); } ERROR_TYPE vk_utils::context::init_instance(const char* app_name, const vk_utils::context::context_init_info& context_init_info) { uint32_t api_version; vkEnumerateInstanceVersion(&api_version); auto messenger_create_info = get_debug_messenger_create_info(); VkApplicationInfo app_info{}; app_info.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; app_info.pNext = nullptr; app_info.pApplicationName = app_name; app_info.applicationVersion = VK_MAKE_VERSION(1, 0, 0); app_info.pEngineName = "no Engine"; app_info.engineVersion = VK_MAKE_VERSION(1, 0, 0); app_info.apiVersion = VK_API_VERSION_1_0; VkInstanceCreateInfo instance_info{}; instance_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; instance_info.pNext = nullptr; #ifdef USE_VALIDATION_LAYERS instance_info.pNext = &messenger_create_info; #else instance_info.pNext = nullptr; #endif uint32_t i_ext_props_size{0}; vkEnumerateInstanceExtensionProperties(nullptr, &i_ext_props_size, nullptr); std::vector<VkExtensionProperties> instance_extensions_props{i_ext_props_size}; vkEnumerateInstanceExtensionProperties(nullptr, &i_ext_props_size, instance_extensions_props.data()); std::vector<const char*> instance_extensions_list{}; for (int i = 0; i < context_init_info.required_instance_extensions.count; ++i) { const auto required_ext_found = std::find_if(instance_extensions_props.begin(), instance_extensions_props.end(), [i, &context_init_info](const VkExtensionProperties& props) { return strcmp(props.extensionName, context_init_info.required_instance_extensions.names[i]) == 0; }); if (required_ext_found == instance_extensions_props.end()) { RAISE_ERROR_FATAL(-1, std::string("cannot find required instance extension ") + context_init_info.required_instance_extensions.names[i]); } } merge_extensions_list( instance_extensions_props, context_init_info.required_instance_extensions.names, context_init_info.required_instance_extensions.count, instance_extensions_list); merge_extensions_list( instance_extensions_props, context_init_info.additional_instance_extensions.names, context_init_info.additional_instance_extensions.count, instance_extensions_list); merge_extensions_list( instance_extensions_props, implicit_required_instance_extensions, #ifdef USE_VALIDATION_LAYERS std::size(implicit_required_instance_extensions), #else 0, #endif instance_extensions_list); uint32_t i_layers_props_size{0}; vkEnumerateInstanceLayerProperties(&i_layers_props_size, nullptr); std::vector<VkLayerProperties> instance_layer_props{i_layers_props_size}; vkEnumerateInstanceLayerProperties(&i_ext_props_size, instance_layer_props.data()); std::vector<const char*> instance_layers_list{}; for (int i = 0; i < context_init_info.required_instance_layers.count; ++i) { const auto required_layer_found = std::find_if(instance_layer_props.begin(), instance_layer_props.end(), [i, &context_init_info](const VkLayerProperties& props) { return strcmp(props.layerName, context_init_info.required_instance_layers.names[i]) == 0; }); if (required_layer_found == instance_layer_props.end()) { RAISE_ERROR_FATAL(-1, std::string("cannot find required instance layer ") + context_init_info.required_instance_layers.names[i]); } } merge_layers_list( instance_layer_props, context_init_info.required_instance_layers.names, context_init_info.required_instance_layers.count, instance_layers_list); merge_layers_list( instance_layer_props, context_init_info.additional_instance_layers.names, context_init_info.additional_instance_layers.count, instance_layers_list); merge_layers_list( instance_layer_props, implicit_required_instance_layers, #ifdef USE_VALIDATION_LAYERS std::size(implicit_required_instance_layers), #else 0, #endif instance_layers_list); instance_info.ppEnabledLayerNames = instance_layers_list.data(); instance_info.enabledLayerCount = instance_layers_list.size(); instance_info.ppEnabledExtensionNames = instance_extensions_list.data(); instance_info.enabledExtensionCount = instance_extensions_list.size(); if (auto err_code = ctx->m_instance.init(&instance_info); err_code != VK_SUCCESS) { RAISE_ERROR_FATAL(err_code, "failed to initialize VK instance."); } RAISE_ERROR_OK(); } ERROR_TYPE vk_utils::context::init_debug_messenger(const vk_utils::context::context_init_info& info) { #ifndef USE_VALIDATION_LAYERS RAISE_ERROR_OK(); #else auto messenger_create_info = get_debug_messenger_create_info(); if (auto err_code = ctx->m_debug_messenger.init(context::get().instance(), &messenger_create_info); err_code != VK_SUCCESS) { RAISE_ERROR_FATAL(err_code, "cannot init debug messenger."); } RAISE_ERROR_OK(); #endif } ERROR_TYPE vk_utils::context::select_physical_device(const vk_utils::context::context_init_info& info) { uint32_t phys_devices_count; vkEnumeratePhysicalDevices(ctx->m_instance, &phys_devices_count, nullptr); std::vector<VkPhysicalDevice> physical_devices{phys_devices_count}; vkEnumeratePhysicalDevices(ctx->m_instance, &phys_devices_count, physical_devices.data()); auto try_select_device = [&physical_devices, &info](std::function<bool(const VkPhysicalDeviceProperties&)> cond) { for (const auto device : physical_devices) { VkPhysicalDeviceFeatures features{}; VkPhysicalDeviceProperties props{}; vkGetPhysicalDeviceFeatures(device, &features); vkGetPhysicalDeviceProperties(device, &props); if (cond(props)) { if (check_device_extensions(device, info.required_device_extensions.names, info.required_device_extensions.count) && check_device_layers(device, info.required_device_layers.names, info.required_device_layers.count) && check_device_queue_families(device, ctx->m_surface, ctx->m_queue_families_indices)) { ctx->m_physical_device = device; LOG_INFO(std::string(props.deviceName) + " device selected."); return true; } } } return false; }; if (info.device_name != nullptr) { memset(ctx->m_queue_families_indices, char(-1), sizeof(m_queue_families_indices)); if (try_select_device([](const VkPhysicalDeviceProperties&) { return true; })) { RAISE_ERROR_OK(); } } memset(ctx->m_queue_families_indices, char(-1), sizeof(m_queue_families_indices)); if (try_select_device([](const VkPhysicalDeviceProperties& props) { return props.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU; })) { RAISE_ERROR_OK(); } memset(ctx->m_queue_families_indices, char(-1), sizeof(m_queue_families_indices)); if (try_select_device([](const VkPhysicalDeviceProperties& props) { return true; })) { RAISE_ERROR_OK(); } RAISE_ERROR_FATAL(-1, "Cannot find suitable device."); } ERROR_TYPE vk_utils::context::init_device(const context_init_info& context_init_info) { uint32_t ext_props_size{0}; vkEnumerateDeviceExtensionProperties(context::get().gpu(), nullptr, &ext_props_size, nullptr); std::vector<VkExtensionProperties> device_extensions_props{ext_props_size}; vkEnumerateDeviceExtensionProperties(context::get().gpu(), nullptr, &ext_props_size, device_extensions_props.data()); uint32_t layers_props_size{0}; vkEnumerateDeviceLayerProperties(context::get().gpu(), &layers_props_size, nullptr); std::vector<VkLayerProperties> device_layers_props{layers_props_size}; vkEnumerateDeviceLayerProperties(context::get().gpu(), &layers_props_size, device_layers_props.data()); std::vector<const char*> device_extensions_list; std::vector<const char*> device_layers_list; merge_extensions_list( device_extensions_props, context_init_info.required_instance_extensions.names, context_init_info.required_instance_extensions.count, device_extensions_list); merge_extensions_list( device_extensions_props, context_init_info.additional_device_extensions.names, context_init_info.additional_device_extensions.count, device_extensions_list); merge_extensions_list( device_extensions_props, implicit_required_device_extensions, std::size(implicit_required_device_extensions), device_extensions_list); merge_layers_list( device_layers_props, context_init_info.required_device_layers.names, context_init_info.required_device_layers.count, device_layers_list); merge_layers_list( device_layers_props, context_init_info.additional_device_layers.names, context_init_info.additional_device_layers.count, device_layers_list); merge_layers_list( device_layers_props, implicit_required_device_layers, #ifdef USE_VALIDATION_LAYERS std::size(implicit_required_device_layers), #else 0, #endif device_layers_list); std::vector<VkDeviceQueueCreateInfo> out_infos{}; out_infos.reserve(QUEUE_TYPE_SIZE); std::vector<float> priorities(QUEUE_TYPE_SIZE, 1.0f); for (int i = 0; i < QUEUE_TYPE_SIZE; ++i) { auto it = std::find_if(out_infos.begin(), out_infos.end(), [i](const VkDeviceQueueCreateInfo& info) { return info.queueFamilyIndex == ctx->m_queue_families_indices[i].index; }); if (it != out_infos.end()) { it->queueCount = std::min(it->queueCount + 1, ctx->m_queue_families_indices[i].max_queue_count); ctx->m_queue_families_indices[i].queue_index = it->queueCount - 1; } else { out_infos.push_back(VkDeviceQueueCreateInfo{ .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, .pNext = nullptr, .flags = 0, .queueFamilyIndex = static_cast<uint32_t>(ctx->m_queue_families_indices[i].index), .pQueuePriorities = priorities.data(), }); ctx->m_queue_families_indices[i].queue_index = 0; } } VkDeviceCreateInfo device_info{}; device_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; device_info.pNext = nullptr; device_info.ppEnabledExtensionNames = device_extensions_list.data(); device_info.enabledExtensionCount = device_extensions_list.size(); device_info.ppEnabledLayerNames = device_layers_list.data(); device_info.enabledLayerCount = device_layers_list.size(); device_info.pQueueCreateInfos = out_infos.data(); device_info.queueCreateInfoCount = out_infos.size(); if (auto err = ctx->m_device.init(context::get().gpu(), &device_info); err != VK_SUCCESS) { RAISE_ERROR_FATAL(err, "cannot initialize logical device"); } RAISE_ERROR_OK(); } ERROR_TYPE vk_utils::context::init_memory_allocator() { VmaAllocatorCreateInfo allocator_create_info{}; allocator_create_info.device = ctx->device(); allocator_create_info.instance = ctx->instance(); allocator_create_info.physicalDevice = ctx->gpu(); allocator_create_info.vulkanApiVersion = VK_API_VERSION_1_0; if (auto err = ctx->m_allocator.init(&allocator_create_info); err != VK_SUCCESS) { RAISE_ERROR_FATAL(err, "cannot initialize allocator."); } RAISE_ERROR_OK(); } ERROR_TYPE vk_utils::context::request_queues() { uint32_t graphics_queue_index{0}; for (int i = 0; i < std::size(ctx->m_queue_families_indices); ++i) { if (ctx->m_queue_families_indices[i].index >= 0) { vkGetDeviceQueue(ctx->m_device, ctx->m_queue_families_indices[i].index, ctx->m_queue_families_indices[i].queue_index, &ctx->m_queues[i]); } } RAISE_ERROR_OK(); } vk_utils::context::~context() { m_allocator.destroy(); m_device.destroy(); m_surface.destroy(); m_debug_messenger.destroy(); m_instance.destroy(); } int32_t vk_utils::context::queue_family_index(vk_utils::context::queue_type t) const { return m_queue_families_indices[t].index; } VkPhysicalDevice vk_utils::context::gpu() const { return m_physical_device; } VkQueue vk_utils::context::queue(vk_utils::context::queue_type type) const { return m_queues[type]; } VkSurfaceKHR vk_utils::context::surface() const { return m_surface; } vk_utils::context::memory_alloc_info vk_utils::context::get_memory_alloc_info(VkBuffer buffer, VkMemoryPropertyFlags props_flags) const { VkPhysicalDeviceMemoryProperties properties; vkGetPhysicalDeviceMemoryProperties(m_physical_device, &properties); VkMemoryRequirements requirements; vkGetBufferMemoryRequirements(m_device, buffer, &requirements); memory_alloc_info res{}; res.allocation_size = requirements.size; res.allocation_alignment = requirements.alignment; for (int i = 0; i < properties.memoryTypeCount; ++i) { if (requirements.memoryTypeBits & (1 << i) && (props_flags & properties.memoryTypes[i].propertyFlags)) { res.memory_type_index = i; } } return res; } VkDebugUtilsMessengerCreateInfoEXT vk_utils::context::get_debug_messenger_create_info() { static auto cb = [](VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity, VkDebugUtilsMessageTypeFlagsEXT messageTypes, const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData, void* pUserData) -> uint32_t { if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) { LOG_ERROR(pCallbackData->pMessage); } else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT) { LOG_WARN(pCallbackData->pMessage); } else { LOG_INFO(pCallbackData->pMessage); } return 0; }; VkDebugUtilsMessengerCreateInfoEXT messenger_create_info{}; messenger_create_info.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT; messenger_create_info.pNext = nullptr; messenger_create_info.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT; messenger_create_info.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT; messenger_create_info.pfnUserCallback = cb; return messenger_create_info; } VmaAllocator vk_utils::context::allocator() const { return m_allocator; }
37.578626
237
0.687211
[ "vector" ]
67e119715fe5c64b8e4ccd355ce73efa8ac72543
693
cpp
C++
Arrays/largest_number.cpp
zerocod3r/InterviewQuestions
347383a405c4eac63552ab18e9a9104e4703db38
[ "MIT" ]
1
2017-11-18T17:02:32.000Z
2017-11-18T17:02:32.000Z
Arrays/largest_number.cpp
zerocod3r/InterviewQuestions
347383a405c4eac63552ab18e9a9104e4703db38
[ "MIT" ]
null
null
null
Arrays/largest_number.cpp
zerocod3r/InterviewQuestions
347383a405c4eac63552ab18e9a9104e4703db38
[ "MIT" ]
2
2017-08-25T08:42:34.000Z
2019-02-18T08:42:48.000Z
// Given a list of non negative integers, arrange them such that they form the largest number. int firstDigit(int n) { while (n >= 10) n /= 10; return n; } bool compare(int a, int b){ if(firstDigit(a) > firstDigit(b)) return 1; else if(firstDigit(a) == firstDigit(b)) return stoi(to_string(a)+to_string(b)) > stoi(to_string(b)+to_string(a)); else return 0; } string Solution::largestNumber(const vector<int> &A) { int n = A.size(); string s; vector<int> B = A; sort(B.begin(),B.end(),compare); for(int i=0;i<n;i++){ s+=to_string(B[i]); } if(s.front()=='0') return "0"; return s; }
23.896552
118
0.559885
[ "vector" ]
67e806391ea32f56da5c755c78f6b4636e9f1c65
37,997
hxx
C++
Components/Metrics/StatisticalShapePenalty/itkStatisticalShapePointPenalty.hxx
ViktorvdValk/elastix
5671dca8c8f0818cb46f18919092f1f52c65096e
[ "Apache-2.0" ]
null
null
null
Components/Metrics/StatisticalShapePenalty/itkStatisticalShapePointPenalty.hxx
ViktorvdValk/elastix
5671dca8c8f0818cb46f18919092f1f52c65096e
[ "Apache-2.0" ]
null
null
null
Components/Metrics/StatisticalShapePenalty/itkStatisticalShapePointPenalty.hxx
ViktorvdValk/elastix
5671dca8c8f0818cb46f18919092f1f52c65096e
[ "Apache-2.0" ]
null
null
null
/*========================================================================= * * Copyright UMC Utrecht and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.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. * *=========================================================================*/ #ifndef itkStatisticalShapePointPenalty_hxx #define itkStatisticalShapePointPenalty_hxx #include "itkStatisticalShapePointPenalty.h" #include <cmath> namespace itk { /** * ******************* Constructor ******************* */ template <class TFixedPointSet, class TMovingPointSet> StatisticalShapePointPenalty<TFixedPointSet, TMovingPointSet>::StatisticalShapePointPenalty() { this->m_MeanVector = nullptr; this->m_EigenVectors = nullptr; this->m_EigenValues = nullptr; this->m_EigenValuesRegularized = nullptr; this->m_ProposalDerivative = nullptr; this->m_InverseCovarianceMatrix = nullptr; this->m_ShrinkageIntensityNeedsUpdate = true; this->m_BaseVarianceNeedsUpdate = true; this->m_VariancesNeedsUpdate = true; } // end Constructor /** * ******************* Destructor ******************* */ template <class TFixedPointSet, class TMovingPointSet> StatisticalShapePointPenalty<TFixedPointSet, TMovingPointSet>::~StatisticalShapePointPenalty() { if (this->m_MeanVector != nullptr) { delete this->m_MeanVector; this->m_MeanVector = nullptr; } if (this->m_CovarianceMatrix != nullptr) { delete this->m_CovarianceMatrix; this->m_CovarianceMatrix = nullptr; } if (this->m_EigenVectors != nullptr) { delete this->m_EigenVectors; this->m_EigenVectors = nullptr; } if (this->m_EigenValues != nullptr) { delete this->m_EigenValues; this->m_EigenValues = nullptr; } if (this->m_EigenValuesRegularized != nullptr) { delete this->m_EigenValuesRegularized; this->m_EigenValuesRegularized = nullptr; } if (this->m_ProposalDerivative != nullptr) { delete this->m_ProposalDerivative; this->m_ProposalDerivative = nullptr; } if (this->m_InverseCovarianceMatrix != nullptr) { delete this->m_InverseCovarianceMatrix; this->m_InverseCovarianceMatrix = nullptr; } } // end Destructor /** * *********************** Initialize ***************************** */ template <class TFixedPointSet, class TMovingPointSet> void StatisticalShapePointPenalty<TFixedPointSet, TMovingPointSet>::Initialize(void) { /** Call the initialize of the superclass. */ this->Superclass::Initialize(); const unsigned int shapeLength = Self::FixedPointSetDimension * this->GetFixedPointSet()->GetNumberOfPoints(); if (this->m_NormalizedShapeModel) { this->m_ProposalLength = shapeLength + Self::FixedPointSetDimension + 1; /** Automatic selection of regularization variances. */ if (this->m_BaseVariance == -1.0 || this->m_CentroidXVariance == -1.0 || this->m_CentroidYVariance == -1.0 || this->m_CentroidZVariance == -1.0 || this->m_SizeVariance == -1.0) { vnl_vector<double> covDiagonal = this->m_CovarianceMatrix->get_diagonal(); if (this->m_BaseVariance == -1.0) { this->m_BaseVariance = covDiagonal.extract(shapeLength).mean(); } if (this->m_CentroidXVariance == -1.0) { this->m_CentroidXVariance = covDiagonal.get(shapeLength); } if (this->m_CentroidYVariance == -1.0) { this->m_CentroidYVariance = covDiagonal.get(shapeLength + 1); } if (this->m_CentroidZVariance == -1.0) { this->m_CentroidZVariance = covDiagonal.get(shapeLength + 2); } if (this->m_SizeVariance == -1.0) { this->m_SizeVariance = covDiagonal.get(shapeLength + 3); } } // End automatic selection of regularization variances. } else { this->m_ProposalLength = shapeLength; /** Automatic selection of regularization variances. */ if (this->m_BaseVariance == -1.0) { vnl_vector<double> covDiagonal = this->m_CovarianceMatrix->get_diagonal(); this->m_BaseVariance = covDiagonal.extract(shapeLength).mean(); } // End automatic selection of regularization variances. } switch (this->m_ShapeModelCalculation) { case 0: // full covariance { if (this->m_ShrinkageIntensityNeedsUpdate || this->m_BaseVarianceNeedsUpdate || (this->m_NormalizedShapeModel && this->m_VariancesNeedsUpdate)) { vnl_matrix<double> regularizedCovariance = (1 - this->m_ShrinkageIntensity) * (*this->m_CovarianceMatrix); vnl_vector<double> regCovDiagonal = regularizedCovariance.get_diagonal(); if (this->m_NormalizedShapeModel) { regCovDiagonal.update(this->m_ShrinkageIntensity * this->m_BaseVariance + regCovDiagonal.extract(shapeLength)); regCovDiagonal[shapeLength] += this->m_ShrinkageIntensity * this->m_CentroidXVariance; regCovDiagonal[shapeLength + 1] += this->m_ShrinkageIntensity * this->m_CentroidYVariance; regCovDiagonal[shapeLength + 2] += this->m_ShrinkageIntensity * this->m_CentroidZVariance; regCovDiagonal[shapeLength + 3] += this->m_ShrinkageIntensity * this->m_SizeVariance; } else { regCovDiagonal += this->m_ShrinkageIntensity * this->m_BaseVariance; } regularizedCovariance.set_diagonal(regCovDiagonal); /** If no regularization is applied, the user is responsible for providing an * invertible Covariance Matrix. For a Moore-Penrose pseudo inverse use * ShrinkageIntensity=0 and ShapeModelCalculation=1 or 2. */ this->m_InverseCovarianceMatrix = new vnl_matrix<double>(vnl_svd_inverse(regularizedCovariance)); } this->m_EigenValuesRegularized = nullptr; break; } case 1: // decomposed covariance (uniform regularization) { if (this->m_NormalizedShapeModel == true) { itkExceptionMacro(<< "ShapeModelCalculation option 1 is only implemented for NormalizedShapeModel = false"); } PCACovarianceType pcaCovariance(*this->m_CovarianceMatrix); typename VnlVectorType::iterator lambdaIt = pcaCovariance.lambdas().begin(); typename VnlVectorType::iterator lambdaEnd = pcaCovariance.lambdas().end(); unsigned int nonZeroLength = 0; for (; lambdaIt != lambdaEnd && (*lambdaIt) > 1e-14; ++lambdaIt, ++nonZeroLength) { } if (this->m_EigenValues != nullptr) { delete this->m_EigenValues; } this->m_EigenValues = new VnlVectorType(pcaCovariance.lambdas().extract(nonZeroLength)); if (this->m_EigenVectors != nullptr) { delete this->m_EigenVectors; } this->m_EigenVectors = new VnlMatrixType(pcaCovariance.V().get_n_columns(0, nonZeroLength)); if (this->m_EigenValuesRegularized == nullptr) { this->m_EigenValuesRegularized = new vnl_vector<double>(this->m_EigenValues->size()); } vnl_vector<double>::iterator regularizedValue; vnl_vector<double>::const_iterator eigenValue; // if there is regularization (>0), the eigenvalues are altered and stored in regularizedValue if (this->m_ShrinkageIntensity != 0) { for (regularizedValue = this->m_EigenValuesRegularized->begin(), eigenValue = this->m_EigenValues->begin(); regularizedValue != this->m_EigenValuesRegularized->end(); regularizedValue++, eigenValue++) { *regularizedValue = -this->m_ShrinkageIntensity * this->m_BaseVariance - this->m_ShrinkageIntensity * this->m_BaseVariance * this->m_ShrinkageIntensity * this->m_BaseVariance / (1.0 - this->m_ShrinkageIntensity) / *eigenValue; } } /** If there is no regularization (m_ShrinkageIntensity==0), a division by zero * is avoided by just copying the eigenvalues to regularizedValue. * However this will be handled correctly in the calculation of the value and derivative. * Providing a non-square eigenvector matrix, with associated eigen values that are * non-zero yields a Mahalanobis distance calculation with a pseudo inverse. */ else { for (regularizedValue = this->m_EigenValuesRegularized->begin(), eigenValue = this->m_EigenValues->begin(); regularizedValue != this->m_EigenValuesRegularized->end(); regularizedValue++, eigenValue++) { *regularizedValue = *eigenValue; } } this->m_InverseCovarianceMatrix = nullptr; } break; case 2: // decomposed scaled covariance (element specific regularization) { if (this->m_NormalizedShapeModel == false) { itkExceptionMacro(<< "ShapeModelCalculation option 2 is only implemented for NormalizedShapeModel = true"); } bool pcaNeedsUpdate = false; if (this->m_BaseVarianceNeedsUpdate || this->m_VariancesNeedsUpdate) { pcaNeedsUpdate = true; this->m_BaseStd = sqrt(this->m_BaseVariance); this->m_CentroidXStd = sqrt(this->m_CentroidXVariance); this->m_CentroidYStd = sqrt(this->m_CentroidYVariance); this->m_CentroidZStd = sqrt(this->m_CentroidZVariance); this->m_SizeStd = sqrt(this->m_SizeVariance); vnl_matrix<double> scaledCovariance(*this->m_CovarianceMatrix); scaledCovariance.set_columns(0, scaledCovariance.get_n_columns(0, shapeLength) / this->m_BaseStd); scaledCovariance.scale_column(shapeLength, 1.0 / this->m_CentroidXStd); scaledCovariance.scale_column(shapeLength + 1, 1.0 / this->m_CentroidYStd); scaledCovariance.scale_column(shapeLength + 2, 1.0 / this->m_CentroidZStd); scaledCovariance.scale_column(shapeLength + 3, 1.0 / this->m_SizeStd); scaledCovariance.update(scaledCovariance.get_n_rows(0, shapeLength) / this->m_BaseStd); scaledCovariance.scale_row(shapeLength, 1.0 / this->m_CentroidXStd); scaledCovariance.scale_row(shapeLength + 1, 1.0 / this->m_CentroidYStd); scaledCovariance.scale_row(shapeLength + 2, 1.0 / this->m_CentroidZStd); scaledCovariance.scale_row(shapeLength + 3, 1.0 / this->m_SizeStd); PCACovarianceType pcaCovariance(scaledCovariance); typename VnlVectorType::iterator lambdaIt = pcaCovariance.lambdas().begin(); typename VnlVectorType::iterator lambdaEnd = pcaCovariance.lambdas().end(); unsigned int nonZeroLength = 0; for (; lambdaIt != lambdaEnd && (*lambdaIt) > 1e-14; ++lambdaIt, ++nonZeroLength) { } if (this->m_EigenValues != nullptr) { delete this->m_EigenValues; } this->m_EigenValues = new VnlVectorType(pcaCovariance.lambdas().extract(nonZeroLength)); if (this->m_EigenVectors != nullptr) { delete this->m_EigenVectors; } this->m_EigenVectors = new VnlMatrixType(pcaCovariance.V().get_n_columns(0, nonZeroLength)); } if (this->m_ShrinkageIntensityNeedsUpdate || pcaNeedsUpdate) { if (this->m_EigenValuesRegularized != nullptr) { delete this->m_EigenValuesRegularized; } // if there is regularization (>0), the eigenvalues are altered and kept in regularizedValue if (this->m_ShrinkageIntensity != 0) { this->m_EigenValuesRegularized = new vnl_vector<double>(this->m_EigenValues->size()); typename vnl_vector<double>::iterator regularizedValue; typename vnl_vector<double>::const_iterator eigenValue; for (regularizedValue = this->m_EigenValuesRegularized->begin(), eigenValue = this->m_EigenValues->begin(); regularizedValue != this->m_EigenValuesRegularized->end(); regularizedValue++, eigenValue++) { *regularizedValue = -this->m_ShrinkageIntensity - this->m_ShrinkageIntensity * this->m_ShrinkageIntensity / (1.0 - this->m_ShrinkageIntensity) / *eigenValue; } } /** If there is no regularization (m_ShrinkageIntensity==0), * a division by zero is avoided by just copying the eigenvalues to regularizedValue. * However this will be handled correctly in the calculation of the value and derivative. * Providing a non-square eigenvector matrix, with associated eigen values that are * non-zero yields a Mahalanobis distance calculation with a pseudo inverse. */ else { this->m_EigenValuesRegularized = new VnlVectorType(*this->m_EigenValues); } } this->m_ShrinkageIntensityNeedsUpdate = false; this->m_BaseVarianceNeedsUpdate = false; this->m_VariancesNeedsUpdate = false; this->m_InverseCovarianceMatrix = nullptr; } break; default: this->m_InverseCovarianceMatrix = nullptr; this->m_EigenValuesRegularized = nullptr; } } // end Initialize() /** * ******************* GetValue ******************* */ template <class TFixedPointSet, class TMovingPointSet> typename StatisticalShapePointPenalty<TFixedPointSet, TMovingPointSet>::MeasureType StatisticalShapePointPenalty<TFixedPointSet, TMovingPointSet>::GetValue( const TransformParametersType & parameters) const { /** Sanity checks. */ FixedPointSetConstPointer fixedPointSet = this->GetFixedPointSet(); if (!fixedPointSet) { itkExceptionMacro(<< "Fixed point set has not been assigned"); } /** Initialize some variables */ // this->m_NumberOfPointsCounted = 0; MeasureType value = NumericTraits<MeasureType>::Zero; // InputPointType movingPoint; OutputPointType fixedPoint; /** Make sure the transform parameters are up to date. */ this->SetTransformParameters(parameters); const unsigned int shapeLength = Self::FixedPointSetDimension * (fixedPointSet->GetNumberOfPoints()); this->m_ProposalVector.set_size(this->m_ProposalLength); /** Part 1: * - Copy point positions in proposal vector */ /** Create iterators. */ PointIterator pointItFixed = fixedPointSet->GetPoints()->Begin(); PointIterator pointEnd = fixedPointSet->GetPoints()->End(); unsigned int vertexindex = 0; /** Loop over the corresponding points. */ while (pointItFixed != pointEnd) { fixedPoint = pointItFixed.Value(); this->FillProposalVector(fixedPoint, vertexindex); this->m_NumberOfPointsCounted++; ++pointItFixed; vertexindex += Self::FixedPointSetDimension; } // end loop over all corresponding points if (this->m_NormalizedShapeModel) { /** Part 2: * - Calculate shape centroid * - put centroid values in proposal * - update proposal vector with aligned shape */ this->UpdateCentroidAndAlignProposalVector(shapeLength); /** Part 3: * - Calculate l2-norm from aligned shapes * - put l2-norm value in proposal vector * - update proposal vector with size normalized shape */ this->UpdateL2(shapeLength); this->NormalizeProposalVector(shapeLength); } VnlVectorType differenceVector; VnlVectorType centerrotated; VnlVectorType eigrot; this->CalculateValue(value, differenceVector, centerrotated, eigrot); return value; } // end GetValue() /** * ******************* GetDerivative ******************* */ template <class TFixedPointSet, class TMovingPointSet> void StatisticalShapePointPenalty<TFixedPointSet, TMovingPointSet>::GetDerivative(const TransformParametersType & parameters, DerivativeType & derivative) const { /** When the derivative is calculated, all information for calculating * the metric value is available. It does not cost anything to calculate * the metric value now. Therefore, we have chosen to only implement the * GetValueAndDerivative(), supplying it with a dummy value variable. */ MeasureType dummyvalue = NumericTraits<MeasureType>::Zero; this->GetValueAndDerivative(parameters, dummyvalue, derivative); } // end GetDerivative() /** * ******************* GetValueAndDerivative ******************* */ template <class TFixedPointSet, class TMovingPointSet> void StatisticalShapePointPenalty<TFixedPointSet, TMovingPointSet>::GetValueAndDerivative( const TransformParametersType & parameters, MeasureType & value, DerivativeType & derivative) const { /** Sanity checks. */ FixedPointSetConstPointer fixedPointSet = this->GetFixedPointSet(); if (!fixedPointSet) { itkExceptionMacro(<< "Fixed point set has not been assigned"); } /** Initialize some variables */ // this->m_NumberOfPointsCounted = 0; value = NumericTraits<MeasureType>::Zero; derivative = DerivativeType(this->GetNumberOfParameters()); derivative.Fill(NumericTraits<DerivativeValueType>::ZeroValue()); // InputPointType movingPoint; OutputPointType fixedPoint; /** Make sure the transform parameters are up to date. */ this->SetTransformParameters(parameters); const unsigned int shapeLength = Self::FixedPointSetDimension * fixedPointSet->GetNumberOfPoints(); this->m_ProposalVector.set_size(this->m_ProposalLength); this->m_ProposalDerivative = new ProposalDerivativeType(this->GetNumberOfParameters(), nullptr); /** Part 1: * - Copy point positions in proposal vector * - Copy point derivatives in proposal derivative vector */ /** Create iterators. */ PointIterator pointItFixed = fixedPointSet->GetPoints()->Begin(); PointIterator pointEnd = fixedPointSet->GetPoints()->End(); unsigned int vertexindex = 0; /** Loop over the corresponding points. */ while (pointItFixed != pointEnd) { fixedPoint = pointItFixed.Value(); this->FillProposalVector(fixedPoint, vertexindex); this->FillProposalDerivative(fixedPoint, vertexindex); this->m_NumberOfPointsCounted++; ++pointItFixed; vertexindex += Self::FixedPointSetDimension; } // end loop over all corresponding points if (this->m_NormalizedShapeModel) { /** Part 2: * - Calculate shape centroid * - put centroid values in proposal * - update proposal vector with aligned shape * - Calculate centroid derivatives and update proposal derivative vectors * - put centroid derivatives values in proposal derivatives * - update proposal derivatives */ this->UpdateCentroidAndAlignProposalVector(shapeLength); this->UpdateCentroidAndAlignProposalDerivative(shapeLength); /** Part 3: * - Calculate l2-norm from aligned shapes * - put l2-norm value in proposal vector * - update proposal vector with size normalized shape * - Calculate l2-norm derivatice from updated proposal vector * - put l2-norm derivative value in proposal derivative vectors * - update proposal derivatives */ this->UpdateL2(shapeLength); this->UpdateL2AndNormalizeProposalDerivative(shapeLength); this->NormalizeProposalVector(shapeLength); } // end if(m_NormalizedShapeModel) // TODO this declaration instantiates a zero sized vector, but it will be reassigned anyways. VnlVectorType differenceVector; VnlVectorType centerrotated; VnlVectorType eigrot; this->CalculateValue(value, differenceVector, centerrotated, eigrot); if (value != 0.0) { this->CalculateDerivative(derivative, value, differenceVector, centerrotated, eigrot, shapeLength); } else { typename ProposalDerivativeType::iterator proposalDerivativeIt = this->m_ProposalDerivative->begin(); typename ProposalDerivativeType::iterator proposalDerivativeEnd = this->m_ProposalDerivative->end(); for (; proposalDerivativeIt != proposalDerivativeEnd; ++proposalDerivativeIt) { if (*proposalDerivativeIt != nullptr) { delete (*proposalDerivativeIt); } } } delete this->m_ProposalDerivative; this->m_ProposalDerivative = nullptr; this->CalculateCutOffValue(value); } // end GetValueAndDerivative() /** * ******************* FillProposalVector ******************* */ template <class TFixedPointSet, class TMovingPointSet> void StatisticalShapePointPenalty<TFixedPointSet, TMovingPointSet>::FillProposalVector(const OutputPointType & fixedPoint, const unsigned int vertexindex) const { OutputPointType mappedPoint; /** Get the current corresponding points. */ mappedPoint = this->m_Transform->TransformPoint(fixedPoint); /** Copy n-D coordinates into big Shape vector. Aligning the centroids is done later. */ for (unsigned int d = 0; d < Self::FixedPointSetDimension; ++d) { this->m_ProposalVector[vertexindex + d] = mappedPoint[d]; } } // end FillProposalVector() /** * ******************* FillProposalDerivative ******************* */ template <class TFixedPointSet, class TMovingPointSet> void StatisticalShapePointPenalty<TFixedPointSet, TMovingPointSet>::FillProposalDerivative( const OutputPointType & fixedPoint, const unsigned int vertexindex) const { /** * A (column) vector is constructed for each mu, only if that mu affects the shape penalty. * I.e. if there is at least one point of the mesh with non-zero derivatives, * a full column vector is instantiated (which can contain zeros for many other points) * * m_ProposalDerivative is a container with either full shape-vector-sized derivative vectors or NULL-s. Example: * * mu1: [ [ dx1/dmu1 , dy1/dmu1 , dz1/dmu1 ] , [ 0 , 0 , 0 ] , [ dx3/dmu1 , dy3/dmu1 , dz3/dmu1 ] , [...] ]^T * mu2: Null * mu3: [ [ 0 , 0 , 0 ] , [ dx2/dmu3 , dy2/dmu3 , dz2/dmu3 ] , [ dx3/dmu3 , dy3/dmu3 , dz3/dmu3 ] , [...] ]^T * */ NonZeroJacobianIndicesType nzji(this->m_Transform->GetNumberOfNonZeroJacobianIndices()); /** Get the TransformJacobian dT/dmu. */ TransformJacobianType jacobian; this->m_Transform->GetJacobian(fixedPoint, jacobian, nzji); for (unsigned int i = 0; i < nzji.size(); ++i) { const unsigned int mu = nzji[i]; if ((*this->m_ProposalDerivative)[mu] == nullptr) { /** Create the big column vector if it does not yet exist for this mu*/ (*this->m_ProposalDerivative)[mu] = new VnlVectorType(this->m_ProposalLength, 0.0); // memory will be freed in CalculateDerivative() } /** The column vector exists for this mu, so copy the jacobians for this point into the big vector. */ for (unsigned int d = 0; d < Self::FixedPointSetDimension; ++d) { (*(*this->m_ProposalDerivative)[mu])[vertexindex + d] = jacobian.get_column(i)[d]; } } } // end FillProposalVector() /** * ******************* UpdateCentroidAndAlignProposalVector ******************* */ template <class TFixedPointSet, class TMovingPointSet> void StatisticalShapePointPenalty<TFixedPointSet, TMovingPointSet>::UpdateCentroidAndAlignProposalVector( const unsigned int shapeLength) const { /** Aligning Shapes with their centroids */ for (unsigned int d = 0; d < Self::FixedPointSetDimension; ++d) { // Create an alias for the centroid elements in the proposal vector double & centroid_d = this->m_ProposalVector[shapeLength + d]; centroid_d = 0; // initialize centroid x,y,z to zero for (unsigned int index = 0; index < shapeLength; index += Self::FixedPointSetDimension) { // sum all x coordinates to centroid_x, y to centroid_y centroid_d += this->m_ProposalVector[index + d]; } // divide sum to get average centroid_d /= this->GetFixedPointSet()->GetNumberOfPoints(); for (unsigned int index = 0; index < shapeLength; index += Self::FixedPointSetDimension) { // subtract average this->m_ProposalVector[index + d] -= centroid_d; } } } // end UpdateCentroidAndAlignProposalVector() /** * ******************* UpdateCentroidAndAlignProposalDerivative ******************* */ template <class TFixedPointSet, class TMovingPointSet> void StatisticalShapePointPenalty<TFixedPointSet, TMovingPointSet>::UpdateCentroidAndAlignProposalDerivative( const unsigned int shapeLength) const { typename ProposalDerivativeType::iterator proposalDerivativeIt = m_ProposalDerivative->begin(); typename ProposalDerivativeType::iterator proposalDerivativeEnd = m_ProposalDerivative->end(); while (proposalDerivativeIt != proposalDerivativeEnd) { if (*proposalDerivativeIt != nullptr) { for (unsigned int d = 0; d < Self::FixedPointSetDimension; ++d) { double & centroid_dDerivative = (**proposalDerivativeIt)[shapeLength + d]; centroid_dDerivative = 0; // initialize accumulators to zero for (unsigned int index = 0; index < shapeLength; index += Self::FixedPointSetDimension) { centroid_dDerivative += (**proposalDerivativeIt)[index + d]; // sum all x derivatives } centroid_dDerivative /= this->GetFixedPointSet()->GetNumberOfPoints(); // divide sum to get average for (unsigned int index = 0; index < shapeLength; index += Self::FixedPointSetDimension) { (**proposalDerivativeIt)[index + d] -= centroid_dDerivative; // subtract average } } } ++proposalDerivativeIt; } } // end UpdateCentroidAndAlignProposalDerivative() /** * ******************* UpdateL2 ******************* */ template <class TFixedPointSet, class TMovingPointSet> void StatisticalShapePointPenalty<TFixedPointSet, TMovingPointSet>::UpdateL2(const unsigned int shapeLength) const { double & l2norm = this->m_ProposalVector[shapeLength + Self::FixedPointSetDimension]; // loop over all shape coordinates of the aligned shape l2norm = 0; // initialize l2norm to zero for (unsigned int index = 0; index < shapeLength; index++) { // accumulate squared distances l2norm += this->m_ProposalVector[index] * this->m_ProposalVector[index]; } l2norm = sqrt(l2norm / this->GetFixedPointSet()->GetNumberOfPoints()); } // end UpdateL2AndNormalizeProposalVector() /** * ******************* NormalizeProposalVector ******************* */ template <class TFixedPointSet, class TMovingPointSet> void StatisticalShapePointPenalty<TFixedPointSet, TMovingPointSet>::NormalizeProposalVector( const unsigned int shapeLength) const { double & l2norm = this->m_ProposalVector[shapeLength + Self::FixedPointSetDimension]; // loop over all shape coordinates of the aligned shape for (unsigned int index = 0; index < shapeLength; index++) { // normalize shape size by l2-norm this->m_ProposalVector[index] /= l2norm; } } // end NormalizeProposalVector() /** * ******************* UpdateL2AndNormalizeProposalDerivative ******************* */ template <class TFixedPointSet, class TMovingPointSet> void StatisticalShapePointPenalty<TFixedPointSet, TMovingPointSet>::UpdateL2AndNormalizeProposalDerivative( const unsigned int shapeLength) const { double & l2norm = this->m_ProposalVector[shapeLength + Self::FixedPointSetDimension]; typename ProposalDerivativeType::iterator proposalDerivativeIt = this->m_ProposalDerivative->begin(); typename ProposalDerivativeType::iterator proposalDerivativeEnd = this->m_ProposalDerivative->end(); while (proposalDerivativeIt != proposalDerivativeEnd) { if (*proposalDerivativeIt != nullptr) { double & l2normDerivative = (**proposalDerivativeIt)[shapeLength + Self::FixedPointSetDimension]; l2normDerivative = 0; // initialize to zero // loop over all shape coordinates of the aligned shape for (unsigned int index = 0; index < shapeLength; index++) { l2normDerivative += this->m_ProposalVector[index] * (**proposalDerivativeIt)[index]; } l2normDerivative /= (l2norm * sqrt((double)(this->GetFixedPointSet()->GetNumberOfPoints()))); // loop over all shape coordinates of the aligned shape for (unsigned int index = 0; index < shapeLength; index++) { // update normalized shape derivatives (**proposalDerivativeIt)[index] = (**proposalDerivativeIt)[index] / l2norm - this->m_ProposalVector[index] * l2normDerivative / (l2norm * l2norm); } } ++proposalDerivativeIt; } } // end UpdateL2AndNormalizeProposalDerivative() /** * ******************* CalculateValue ******************* */ template <class TFixedPointSet, class TMovingPointSet> void StatisticalShapePointPenalty<TFixedPointSet, TMovingPointSet>::CalculateValue(MeasureType & value, VnlVectorType & differenceVector, VnlVectorType & centerrotated, VnlVectorType & eigrot) const { differenceVector = this->m_ProposalVector - *m_MeanVector; switch (this->m_ShapeModelCalculation) { case 0: // full covariance { value = sqrt(bracket(differenceVector, *this->m_InverseCovarianceMatrix, differenceVector)); break; } case 1: // decomposed covariance (uniform regularization) { centerrotated = differenceVector * (*m_EigenVectors); /** diff^T * V */ eigrot = element_quotient(centerrotated, *m_EigenValuesRegularized); /** diff^T * V * Lambda^-1 */ if (this->m_ShrinkageIntensity != 0) { /** innerproduct diff^T * V * Lambda^-1 * V^T * diff + 1/(sigma_0*Beta)* diff^T*diff*/ value = sqrt(dot_product(eigrot, centerrotated) + dot_product(differenceVector, differenceVector) / (this->m_ShrinkageIntensity * this->m_BaseVariance)); } else { /** innerproduct diff^T * V * Lambda^-1 * V^T * diff*/ value = sqrt(dot_product(eigrot, centerrotated)); } break; } case 2: // decomposed scaled covariance (element specific regularization) { const unsigned int shapeLength = this->m_ProposalLength - Self::FixedPointSetDimension - 1; typename VnlVectorType::iterator diffElementIt = differenceVector.begin(); for (unsigned int diffElementIndex = 0; diffElementIndex < shapeLength; ++diffElementIndex, ++diffElementIt) { *diffElementIt /= this->m_BaseStd; } differenceVector[shapeLength] /= this->m_CentroidXStd; differenceVector[shapeLength + 1] /= this->m_CentroidYStd; differenceVector[shapeLength + 2] /= this->m_CentroidZStd; differenceVector[shapeLength + 3] /= this->m_SizeStd; centerrotated = differenceVector * (*this->m_EigenVectors); /** diff^T * V */ eigrot = element_quotient(centerrotated, *this->m_EigenValuesRegularized); /** diff^T * V * Lambda^-1 */ if (this->m_ShrinkageIntensity != 0) { /** innerproduct diff^T * ~V * I * ~V^T * diff + 1/(Beta)* diff^T*diff*/ value = sqrt(dot_product(eigrot, centerrotated) + differenceVector.squared_magnitude() / this->m_ShrinkageIntensity); } else { /** innerproduct diff^T * V * I * V^T * diff*/ value = sqrt(dot_product(eigrot, centerrotated)); } break; } default: break; } } // end CalculateValue() /** * ******************* CalculateDerivative ******************* */ template <class TFixedPointSet, class TMovingPointSet> void StatisticalShapePointPenalty<TFixedPointSet, TMovingPointSet>::CalculateDerivative( DerivativeType & derivative, const MeasureType & value, const VnlVectorType & differenceVector, const VnlVectorType & centerrotated, const VnlVectorType & eigrot, const unsigned int shapeLength) const { typename ProposalDerivativeType::iterator proposalDerivativeIt = this->m_ProposalDerivative->begin(); typename ProposalDerivativeType::iterator proposalDerivativeEnd = this->m_ProposalDerivative->end(); typename DerivativeType::iterator derivativeIt = derivative.begin(); for (; proposalDerivativeIt != proposalDerivativeEnd; ++proposalDerivativeIt, ++derivativeIt) { if (*proposalDerivativeIt != nullptr) { switch (this->m_ShapeModelCalculation) { case 0: // full covariance { /**innerproduct diff^T * Sigma^-1 * d/dmu (diff), where iterated over mu-s*/ *derivativeIt = bracket(differenceVector, *m_InverseCovarianceMatrix, (**proposalDerivativeIt)) / value; this->CalculateCutOffDerivative(*derivativeIt, value); break; } case 1: // decomposed covariance (uniform regularization) { if (this->m_ShrinkageIntensity != 0) { /** Innerproduct diff^T * V * Lambda^-1 * V^T * d/dmu(diff) * + 1/(Beta*sigma_0^2)*diff^T* d/dmu(diff), where iterated over mu-s */ *derivativeIt = (dot_product(eigrot, this->m_EigenVectors->transpose() * (**proposalDerivativeIt)) + dot_product(differenceVector, **proposalDerivativeIt) / (this->m_ShrinkageIntensity * this->m_BaseVariance)) / value; this->CalculateCutOffDerivative(*derivativeIt, value); } else // m_ShrinkageIntensity==0 { /**innerproduct diff^T * V * Lambda^-1 * V^T * d/dmu (diff), where iterated over mu-s*/ *derivativeIt = (dot_product(eigrot, this->m_EigenVectors->transpose() * (**proposalDerivativeIt))) / value; this->CalculateCutOffDerivative(*derivativeIt, value); } break; } case 2: // decomposed scaled covariance (element specific regularization) { // first scale proposalDerivatives with their sigma's in order to evaluate // with the EigenValues and EigenVectors of the scaled CovarianceMatrix typename VnlVectorType::iterator propDerivElementIt = (*proposalDerivativeIt)->begin(); for (unsigned int propDerivElementIndex = 0; propDerivElementIndex < shapeLength; ++propDerivElementIndex, ++propDerivElementIt) { (*propDerivElementIt) /= this->m_BaseStd; } (**proposalDerivativeIt)[shapeLength] /= this->m_CentroidXStd; (**proposalDerivativeIt)[shapeLength + 1] /= this->m_CentroidYStd; (**proposalDerivativeIt)[shapeLength + 2] /= this->m_CentroidZStd; (**proposalDerivativeIt)[shapeLength + 3] /= this->m_SizeStd; if (this->m_ShrinkageIntensity != 0) { /** innerproduct diff^T * V * Lambda^-1 * V^T * d/dmu(diff) * + 1/(Beta*sigma_0^2)*diff^T* d/dmu(diff), where iterated over mu-s */ *derivativeIt = (dot_product(eigrot, this->m_EigenVectors->transpose() * (**proposalDerivativeIt)) + dot_product(differenceVector, **proposalDerivativeIt) / this->m_ShrinkageIntensity) / value; this->CalculateCutOffDerivative(*derivativeIt, value); } else // m_ShrinkageIntensity==0 { /**innerproduct diff^T * V * Lambda^-1 * V^T * d/dmu (diff), where iterated over mu-s*/ *derivativeIt = (dot_product(eigrot, this->m_EigenVectors->transpose() * (**proposalDerivativeIt))) / value; this->CalculateCutOffDerivative(*derivativeIt, value); } break; } default: { } delete (*proposalDerivativeIt); // nzjacs++; } } } } // end CalculateDerivative() /** * ******************* CalculateCutOffValue ******************* */ template <class TFixedPointSet, class TMovingPointSet> void StatisticalShapePointPenalty<TFixedPointSet, TMovingPointSet>::CalculateCutOffValue(MeasureType & value) const { if (this->m_CutOffValue > 0.0) { value = std::log(std::exp(this->m_CutOffSharpness * value) + std::exp(this->m_CutOffSharpness * this->m_CutOffValue)) / this->m_CutOffSharpness; } } // end CalculateCutOffValue() /** * ******************* CalculateCutOffDerivative ******************* */ template <class TFixedPointSet, class TMovingPointSet> void StatisticalShapePointPenalty<TFixedPointSet, TMovingPointSet>::CalculateCutOffDerivative( typename DerivativeType::element_type & derivativeElement, const MeasureType & value) const { if (this->m_CutOffValue > 0.0) { derivativeElement *= 1.0 / (1.0 + std::exp(this->m_CutOffSharpness * (this->m_CutOffValue - value))); } } // end CalculateCutOffDerivative() /** * ******************* PrintSelf ******************* */ template <class TFixedPointSet, class TMovingPointSet> void StatisticalShapePointPenalty<TFixedPointSet, TMovingPointSet>::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); // \todo complete it // // if ( this->m_ComputeSquaredDistance ) // { // os << indent << "m_ComputeSquaredDistance: True"<< std::endl; // } // else // { // os << indent << "m_ComputeSquaredDistance: False"<< std::endl; // } } // end PrintSelf() } // end namespace itk #endif // end #ifndef itkStatisticalShapePointPenalty_hxx
37.583581
120
0.658394
[ "mesh", "shape", "vector", "transform" ]
67ed6af6066062d05187c2e69d8f20146c82b35f
5,869
cc
C++
skiko/src/jvmMain/cpp/windows/drawlayer.cc
dector/skiko
549014105b6a0fc89d39161090f190499bb691ec
[ "Apache-2.0" ]
null
null
null
skiko/src/jvmMain/cpp/windows/drawlayer.cc
dector/skiko
549014105b6a0fc89d39161090f190499bb691ec
[ "Apache-2.0" ]
null
null
null
skiko/src/jvmMain/cpp/windows/drawlayer.cc
dector/skiko
549014105b6a0fc89d39161090f190499bb691ec
[ "Apache-2.0" ]
null
null
null
// drawcanvas.cpp : Defines the exported functions for the DLL application. #include <SDKDDKVer.h> #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <gl/GL.h> #include <jawt_md.h> #include <set> #include <Shellscalingapi.h> #include <stdio.h> #include <Wingdi.h> using namespace std; JavaVM *jvm = NULL; extern "C" jboolean Skiko_GetAWT(JNIEnv *env, JAWT *awt); class LayerHandler { public: jobject canvasGlobalRef; HGLRC context; HDC device; void updateLayerContent() { draw(); } void disposeLayer(JNIEnv *env) { env->DeleteGlobalRef(canvasGlobalRef); canvasGlobalRef = NULL; context = NULL; device = NULL; } private: void draw() { if (jvm != NULL) { JNIEnv *env; jvm->GetEnv((void **)&env, JNI_VERSION_10); wglMakeCurrent(device, context); static jclass wndClass = NULL; if (!wndClass) wndClass = env->GetObjectClass(canvasGlobalRef); static jmethodID drawMethod = NULL; if (!drawMethod) drawMethod = env->GetMethodID(wndClass, "draw", "()V"); if (NULL == drawMethod) { fprintf(stderr, "The method Window.draw() not found!\n"); return; } env->CallVoidMethod(canvasGlobalRef, drawMethod); glFinish(); SwapBuffers(device); } } }; set<LayerHandler *> *layerStorage = NULL; LayerHandler *findByObject(JNIEnv *env, jobject object) { if (layerStorage == NULL) { return NULL; } for (auto &layer : *layerStorage) { if (env->IsSameObject(object, layer->canvasGlobalRef) == JNI_TRUE) { return layer; } } return NULL; } extern "C" { JNIEXPORT void JNICALL Java_org_jetbrains_skiko_HardwareLayer_updateLayer(JNIEnv *env, jobject canvas) { if (layerStorage != NULL) { LayerHandler *layer = findByObject(env, canvas); if (layer != NULL) { return; } } else { layerStorage = new set<LayerHandler *>(); } JAWT awt; JAWT_DrawingSurface *ds = NULL; JAWT_DrawingSurfaceInfo *dsi = NULL; PIXELFORMATDESCRIPTOR pixFormatDscr; HGLRC context = NULL; jboolean result = JNI_FALSE; jint lock = 0; JAWT_Win32DrawingSurfaceInfo *dsi_win; awt.version = (jint)JAWT_VERSION_9; result = Skiko_GetAWT(env, &awt); if (result == JNI_FALSE) { fprintf(stderr, "JAWT_GetAWT failed! Result is JNI_FALSE\n"); return; } if (jvm == NULL) { env->GetJavaVM(&jvm); } ds = awt.GetDrawingSurface(env, canvas); lock = ds->Lock(ds); dsi = ds->GetDrawingSurfaceInfo(ds); dsi_win = (JAWT_Win32DrawingSurfaceInfo *)dsi->platformInfo; HWND hwnd = dsi_win->hwnd; HDC device = GetDC(hwnd); if (dsi != NULL) { memset(&pixFormatDscr, 0, sizeof(PIXELFORMATDESCRIPTOR)); pixFormatDscr.nSize = sizeof(PIXELFORMATDESCRIPTOR); pixFormatDscr.nVersion = 1; pixFormatDscr.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; pixFormatDscr.iPixelType = PFD_TYPE_RGBA; pixFormatDscr.cColorBits = 32; int iPixelFormat = ChoosePixelFormat(device, &pixFormatDscr); SetPixelFormat(device, iPixelFormat, &pixFormatDscr); DescribePixelFormat(device, iPixelFormat, sizeof(PIXELFORMATDESCRIPTOR), &pixFormatDscr); context = wglCreateContext(device); LayerHandler *layer = new LayerHandler(); layerStorage->insert(layer); jobject canvasRef = env->NewGlobalRef(canvas); layer->canvasGlobalRef = canvasRef; layer->context = context; layer->device = device; } ds->FreeDrawingSurfaceInfo(dsi); ds->Unlock(ds); awt.FreeDrawingSurface(ds); } JNIEXPORT void JNICALL Java_org_jetbrains_skiko_HardwareLayer_redrawLayer(JNIEnv *env, jobject canvas) { LayerHandler *layer = findByObject(env, canvas); if (layer != NULL) { layer->updateLayerContent(); } } JNIEXPORT void JNICALL Java_org_jetbrains_skiko_HardwareLayer_disposeLayer(JNIEnv *env, jobject canvas) { LayerHandler *layer = findByObject(env, canvas); if (layer != NULL) { layerStorage->erase(layer); layer->disposeLayer(env); delete layer; } } JNIEXPORT jlong JNICALL Java_org_jetbrains_skiko_HardwareLayer_getWindowHandle(JNIEnv *env, jobject canvas) { JAWT awt; JAWT_DrawingSurface *ds = NULL; JAWT_DrawingSurfaceInfo *dsi = NULL; PIXELFORMATDESCRIPTOR pixFormatDscr; HGLRC context = NULL; jboolean result = JNI_FALSE; jint lock = 0; JAWT_Win32DrawingSurfaceInfo *dsi_win; awt.version = (jint)JAWT_VERSION_9; result = Skiko_GetAWT(env, &awt); if (result == JNI_FALSE) { fprintf(stderr, "JAWT_GetAWT failed! Result is JNI_FALSE\n"); return -1; } if (jvm == NULL) { env->GetJavaVM(&jvm); } ds = awt.GetDrawingSurface(env, canvas); lock = ds->Lock(ds); dsi = ds->GetDrawingSurfaceInfo(ds); dsi_win = (JAWT_Win32DrawingSurfaceInfo *)dsi->platformInfo; HWND hwnd = dsi_win->hwnd; ds->FreeDrawingSurfaceInfo(dsi); ds->Unlock(ds); awt.FreeDrawingSurface(ds); return (jlong)hwnd; } } // extern "C"
26.799087
111
0.581019
[ "object" ]
67faf0c658fd4ca6627408666879cf41d52b6934
9,260
cpp
C++
ui/copter3d.cpp
JeanCollas/Raspicop
d5460c2588914b129df2ce41939696af911974bc
[ "MIT" ]
null
null
null
ui/copter3d.cpp
JeanCollas/Raspicop
d5460c2588914b129df2ce41939696af911974bc
[ "MIT" ]
null
null
null
ui/copter3d.cpp
JeanCollas/Raspicop
d5460c2588914b129df2ce41939696af911974bc
[ "MIT" ]
null
null
null
// Raspicop@Jean Collas 2015-10-30 : config file, mainly hardware and clock configuration related // Code based on richardghirst/PiBits demo_3d example // modified to object-oriented C++ // remove internal MPU6050 reading // modified to allow external ypr values so that // the collecting data process is not dependent on the UI loop // it allows to update the UI at a lower speed, sparing the proc for more important things // removed offline option (not useful anymore as YPR can be defined outside the class) #include <stdio.h> #include <stdint.h> #include <unistd.h> #include <ctime> #include <cmath> #include <cairomm/context.h> #include <glibmm/main.h> #include <iostream> #include "copter3d.h" #include "geometry.h" using namespace std; Copter3D::Copter3D(float * YPR) : Copter3D() { ypr=YPR; } Copter3D::Copter3D() : m_line_width(0.05), m_radius(0.42) { objects=NULL; ypr=new float(3); ypr[0]=ypr[1]=ypr[2]=1; Glib::signal_timeout().connect( sigc::mem_fun(*this, &Copter3D::on_timeout), 40 ); #ifndef GLIBMM_DEFAULT_SIGNAL_HANDLERS_ENABLED //Connect the signal handler if it isn't already a virtual method override: signal_draw().connect(sigc::mem_fun(*this, &Copter3D::on_draw), false); #endif //GLIBMM_DEFAULT_SIGNAL_HANDLERS_ENABLED addCube((point_t){2,2,0.5},(point_t){0,0,0},(point_t){0,0,0}); addCube((point_t){0.5,0.5,1},(point_t){0,0,0},(point_t){0,0,0.75}); } // This adds a cube of size (1,1,1) centered at (0,0,0), then it // scales it up by (s) and moves it (d). (r) is its current rotation // around the axes, though it is ignored at present. void Copter3D::addCube(point_t s, point_t r, point_t d) { int i; object_t *o = (object_t *)malloc(sizeof(object_t)); memcpy(&o->r,&r,sizeof(r)); o->n = 8; o->p = (point_t *)malloc(sizeof(point_t)*o->n); o->q = (point_t *)malloc(sizeof(point_t)*o->n); point_t c[] = { { +0.5, -0.5, +0.5 }, { +0.5, +0.5, +0.5 }, { -0.5, +0.5, +0.5 }, { -0.5, -0.5, +0.5 }, { +0.5, -0.5, -0.5 }, { +0.5, +0.5, -0.5 }, { -0.5, +0.5, -0.5 }, { -0.5, -0.5, -0.5 } }; for (i = 0; i < 8; i++) { o->p[i].x = c[i].x * s.x + d.x; o->p[i].y = c[i].y * s.y + d.y; o->p[i].z = c[i].z * s.z + d.z; } memcpy(o->q,o->p,sizeof(point_t)*o->n); o->next = objects; objects = o; nbObjects++; } bool Copter3D::on_timeout() { // force our program to redraw the entire window. Glib::RefPtr<Gdk::Window> win = get_window(); object_t *o; o = objects; for (int i=0;i<nbObjects;i++) { memcpy(o->q,o->p,sizeof(point_t) * o->n); transform_x(o->q, 8, (ypr)[2]); transform_y(o->q, 8, (ypr)[1]); transform_z(o->q, 8, (ypr)[0]); transform_o(o->q, 8, 6); o = o->next; } if (win) { Gdk::Rectangle r(0, 0, get_allocation().get_width(), get_allocation().get_height()); win->invalidate_rect(r, false); } return true; } int Copter3D::get_quadrant(double *x, double *y) { if (*y >= 0) return *x >= 0 ? 0 : 1; else return *x >= 0 ? 3 : 2; } void Copter3D::set_quadrant(double *x, double *y, int quad) { if (quad >= 2) { *y = -fabs(*y); if (quad == 2) *x = -fabs(*x); else *x = fabs(*x); } else { *y = fabs(*y); if (quad == 1) *x = -fabs(*x); else *x = fabs(*x); } } void Copter3D::transform(double *x, double *y, double rot) { // Rotate round x axis, i.e. change y & z int quad = get_quadrant(x, y); //g_print("transform: y %f, z %f, q %d\n",p->y,p->z,quad); double angle = atan(fabs(*y / *x)); double hypot = sqrt(*y * *y + *x * *x); if (quad == 1 || quad == 3) angle = M_PI / 2 - angle; angle += quad * M_PI / 2; //g_print(" : a %f, h %f\n", angle, hypot); angle += rot; while (angle < 0) angle += 2 * M_PI; while (angle >= 2 * M_PI) angle -= 2 * M_PI; quad = (int)(angle*2/M_PI); *x = hypot * cos(angle); *y = hypot * sin(angle); set_quadrant(x, y, quad); //g_print(" : y %f, z %f, q %d\n",p->y,p->z,quad); } void Copter3D::transform_x(point_t *p, int n, double rot) { while (n--) { transform(&p->y, &p->z, rot); p++; } } void Copter3D::transform_y(point_t *p, int n, double rot) { while (n--) { transform(&p->x, &p->z, rot); p++; } } void Copter3D::transform_z(point_t *p, int n, double rot) { while (n--) { transform(&p->y, &p->x, rot); p++; } } void Copter3D::transform_o(point_t *p, int n, double o) { while (n--) { p->x += o; p++; } } bool Copter3D::on_draw(const Cairo::RefPtr<Cairo::Context>& cr) { object_t *o; // scale to unit square and translate (0, 0) to be (0.5, 0.5), i.e. // the center of the window cr->set_line_width(m_line_width); cr->save(); cr->set_source_rgba(0.337, 0.612, 0.117, 0.9); // green cr->paint(); cr->restore(); double seconds= (ypr)[2]; cr->save(); cr->set_line_cap(Cairo::LINE_CAP_ROUND); cr->save(); cr->set_line_width(3); cr->set_source_rgba(0.7, 0.7, 0.7, 0.8); // gray cr->move_to(0, 0); cr->line_to(sin(seconds) * (m_radius * 0.9), -cos(seconds) * (m_radius * 0.9)); cr->stroke(); reset_scale(cr); o = objects; for (int i=0;i<nbObjects;i++) { accum_scale(cr,o->q,o->n); o=o->next; } calc_scale(cr); o = objects; for (int i=0;i<nbObjects;i++) { // for (o = objects; o; o = o->next) { draw_3d8(cr,o->q); o=o->next; } cr->restore(); return true; } void Copter3D::calc_scale(const Cairo::RefPtr<Cairo::Context>& cr) { Gtk::Allocation allocation = get_allocation(); const double w = allocation.get_width() - 8; const double h = allocation.get_height() - 8; if (fabs(maxx - minx) > fabs(maxy - miny)) { scale = w / fabs(maxx - minx) * 0.7; } else { scale = h / fabs(maxy - miny) * 0.7; } xoff = -minx; yoff = -maxy; } void Copter3D::reset_scale(const Cairo::RefPtr<Cairo::Context>& cr) { minx = miny = 1000000; maxx = maxy = -1000000; //g_print("reset now %f - %f, %f - %f\n", minx,maxx,miny,maxy); } void Copter3D::accum_scale(const Cairo::RefPtr<Cairo::Context>& cr, point_t *p, int n) { double x,y; double vpd = 1; while (n--) { x = p->y * vpd / p->x; y = p->z * vpd / p->x; if (x < minx) minx = x; if (x > maxx) maxx = x; if (y < miny) miny = y; if (y > maxy) maxy = y; //g_print("accum %f %f, now %f - %f, %f - %f\n", p->y,p->z,minx,maxx,miny,maxy); p++; } } void Copter3D::cairo_move_to_scaled(const Cairo::RefPtr<Cairo::Context>& cr, point_t *p) { double x, y; double vpd = 1; x = (p->y * vpd / p->x + xoff) * scale + 4; y = (p->z * vpd / p->x + yoff) * scale * -1 + 4; //g_print("move_to(%f,%f)\n",x,y); cr->move_to(x, y); } void Copter3D::cairo_line_to_scaled(const Cairo::RefPtr<Cairo::Context>& cr, point_t *p) { double x, y; double vpd = 1; x = (p->y * vpd / p->x + xoff) * scale + 4; y = (p->z * vpd / p->x + yoff) * scale * -1 + 4; //g_print("line_to(%f,%f)\n",x,y); //cairo_set_source_rgb (cr, c, 0, 0); cr->line_to(x, y); } void Copter3D::draw_3d8(const Cairo::RefPtr<Cairo::Context>& cr, point_t *q) { int c; static double col = 0.01; static double step = 0.001; // cairo_set_source_rgb (cr, col, 0, 0); cairo_move_to_scaled(cr, q+3); for (c = 0; c < 4; c++) cairo_line_to_scaled(cr, q+c); cairo_move_to_scaled(cr, q+7); for (c = 4; c < 8; c++) cairo_line_to_scaled(cr, q+c); for (c = 0; c < 4; c++) { cairo_move_to_scaled(cr, q+c); cairo_line_to_scaled(cr, q+c+4); } cr->stroke(); col += step; if (col >= 1 || col <= 0) step = -step; }
26.763006
98
0.469222
[ "geometry", "object", "transform" ]
67fc407bd694bcd9f50d801642a681ff4f715688
49,280
cpp
C++
src/DrMaMP.cpp
zehuilu/DrMaMP-Distributed-Real-time-Multi-agent-Mission-Planning-Algorithm
894875ebddf7d1f6bbf7a47ce82f05d7be2bafdc
[ "Apache-2.0" ]
4
2022-02-22T05:12:18.000Z
2022-03-29T01:56:37.000Z
src/DrMaMP.cpp
zehuilu/DrMaMP-Distributed-Real-time-Multi-agent-Mission-Planning-Algorithm
894875ebddf7d1f6bbf7a47ce82f05d7be2bafdc
[ "Apache-2.0" ]
null
null
null
src/DrMaMP.cpp
zehuilu/DrMaMP-Distributed-Real-time-Multi-agent-Mission-Planning-Algorithm
894875ebddf7d1f6bbf7a47ce82f05d7be2bafdc
[ "Apache-2.0" ]
3
2022-02-23T03:14:56.000Z
2022-03-14T12:22:05.000Z
#include <iostream> #include <vector> #include <tuple> #include <array> #include <chrono> #include <cmath> #include <cstdlib> #include <math.h> #include <limits> #include <algorithm> #include <future> #include <pybind11/pybind11.h> #include <pybind11/stl.h> #include "../externals/Lazy-Theta-with-optimization-any-angle-pathfinding/include/tileadaptor.hpp" #include "../externals/Lazy-Theta-with-optimization-any-angle-pathfinding/include/utility.hpp" #include "../externals/Lazy-Theta-with-optimization-any-angle-pathfinding/include/get_combination.hpp" #include "../include/k_means.hpp" #include "../include/k_means_with_plus_plus.hpp" #include "../include/k_means_with_external_centroids.hpp" #include "ortools/constraint_solver/routing.h" #include "ortools/constraint_solver/routing_enums.pb.h" #include "ortools/constraint_solver/routing_index_manager.h" #include "ortools/constraint_solver/routing_parameters.h" #include "ortools/base/logging.h" #include "ortools/linear_solver/linear_solver.h" using namespace operations_research; constexpr int SCALE_FACTOR = 100; // to scale the distance matrix for solving TSP static constexpr float WEIGHT_PATH = 1E2; // weight for path finder /* PrintSolution: Print the solution of traveling salesman problem via or-tools on console. Examples shown in SolveOneAgent() or https://developers.google.com/optimization/routing/tsp#c++ Input: manager: RoutingIndexManager routing: RoutingModel solution: Assignment Output: void */ inline void PrintSolution( const RoutingIndexManager& manager, const RoutingModel& routing, const Assignment& solution) { // Inspect solution. LOG(INFO) << "Objective: " << solution.ObjectiveValue() / SCALE_FACTOR << " [unit]"; int64 index = routing.Start(0); LOG(INFO) << "Route:"; int64 distance{0}; std::stringstream route; while (routing.IsEnd(index) == false) { route << manager.IndexToNode(index).value() << " -> "; int64 previous_index = index; index = solution.Value(routing.NextVar(index)); distance += routing.GetArcCostForVehicle(previous_index, index, int64{0}); } // Skip the last one, because in my case, the last one is a dummy variable // so that the agent doesn't have to go back to the starting point. // LOG(INFO) << route.str() << manager.IndexToNode(index).value(); LOG(INFO) << route.str(); LOG(INFO) << "Route distance: " << distance / SCALE_FACTOR << "[unit]"; LOG(INFO) << ""; LOG(INFO) << "Advanced usage:"; LOG(INFO) << "Problem solved in " << routing.solver()->wall_time() << "ms"; } /* FindPathOneByOne: Find all the collision-free paths consecutively, i.e. the paths from a0~t0, t0~t1, t1~t2, ... Input: agent_position: 1D integer array [x, y] for the agent position targets_position: 1D integer array [x0,y0, x1,y1, x2,y2, ...] for the targets positions Map: 1D integer array for the map, flattened by a 2D array map; 0 for no obstacles, 255 for obstacles mapSizeX: integer for the width of the map mapSizeY: integer for the height of the map Output: path: 2D integer array for all the index paths, [[idx_x_0,idx_y_0, idx_x_1,idx_y_1, ...], [idx_x_0,idx_y_0, idx_x_1,idx_y_1, ...], ...] distance: 1D float array for all the distances of the paths */ inline std::tuple<std::vector<std::vector<int>>, std::vector<float>> FindPathOneByOne( const std::vector<int> &agent_position, const std::vector<int> &targets_position, const std::vector<int> &Map, const int &mapSizeX, const int &mapSizeY) { std::vector<std::vector<int>> path_many; std::vector<float> distances_many; int start[2]; int goal[2]; // Instantiating our path adaptor // passing the map size, and the map Vectori mapSize(mapSizeX, mapSizeY); TileAdaptor adaptor(mapSize, Map); // This is a bit of an exageration here for the weight, but it did make my performance test go from 8s to 2s Pathfinder pathfinder(adaptor, WEIGHT_PATH); if (targets_position.size() > 0) { // start is agent_position, goal is the first two elements of targets_position, doing the search // output: std::tuple<std::vector<int>, float> auto [path, distance] = pathfinder.search(agent_position[1]*mapSizeX+agent_position[0], targets_position[1]*mapSizeX+targets_position[0], mapSize); path_many.push_back(path); distances_many.push_back(distance); // Regenerate the neighbors for next run // if (idx < start_goal_pair.size()-1) pathfinder.generateNodes(); for (size_t idx = 2; idx < targets_position.size(); idx = idx + 2) { goal[0] = targets_position[idx]; goal[1] = targets_position[idx+1]; start[0] = targets_position[idx-2]; start[1] = targets_position[idx-1]; // start is the previous target, goal is the current target, doing the search // output: std::tuple<std::vector<int>, float> auto [path, distance] = pathfinder.search(start[1]*mapSizeX+start[0], goal[1]*mapSizeX+goal[0], mapSize); path_many.push_back(path); distances_many.push_back(distance); // Regenerate the neighbors for next run pathfinder.generateNodes(); } } // if targets_position is empty, return empty arrays return {path_many, distances_many}; } /* FindPathMany: Find all the collision-free paths from every element to another element in start+targets. Input: agent_position: 1D integer array [x, y] for the agent position targets_position: 1D integer array [x0,y0, x1,y1, x2,y2, ...] for the targets positions Map: 1D integer array for the map, flattened by a 2D array map; 0 for no obstacles, 255 for obstacles mapSizeX: integer for the width of the map mapSizeY: integer for the height of the map Output: path: 2D integer array for all the index paths, [[idx_x_0,idx_y_0, idx_x_1,idx_y_1, ...], [idx_x_0,idx_y_0, idx_x_1,idx_y_1, ...], ...] distance: 1D float array for all the distances of the paths */ inline std::tuple<std::vector<std::vector<int>>, std::vector<float>> FindPathMany( const std::vector<int> &agent_position, const std::vector<int> &targets_position, const std::vector<int> &Map, const int &mapSizeX, const int &mapSizeY) { std::vector<int> start_goal_pair = get_combination(targets_position.size()/2 + 1, 2); std::vector<std::vector<int>> path_many; std::vector<float> distances_many; int start[2]; int goal[2]; // Instantiating our path adaptor // passing the map size, and the map Vectori mapSize(mapSizeX, mapSizeY); TileAdaptor adaptor(mapSize, Map); // This is a bit of an exageration here for the weight, but it did make my performance test go from 8s to 2s Pathfinder pathfinder(adaptor, WEIGHT_PATH); for (size_t idx = 0; idx < start_goal_pair.size(); idx = idx + 2) { int start_idx = start_goal_pair[idx]; int goal_idx = start_goal_pair[idx+1]; if (start_idx != 0) { start[0] = targets_position[2*(start_idx-1)]; start[1] = targets_position[2*(start_idx-1)+1]; } else { start[0] = agent_position[0]; start[1] = agent_position[1]; } if (goal_idx != 0) { goal[0] = targets_position[2*(goal_idx-1)]; goal[1] = targets_position[2*(goal_idx-1)+1]; } else { goal[0] = agent_position[0]; goal[1] = agent_position[1]; } // doing the search // output: std::tuple<std::vector<int>, float> // when infeasible, path is empty, distance = 0 auto [path, distance] = pathfinder.search(start[1]*mapSizeX+start[0], goal[1]*mapSizeX+goal[0], mapSize); path_many.push_back(path); distances_many.push_back(distance); // Regenerate the neighbors for next run // if (idx < start_goal_pair.size()-1) pathfinder.generateNodes(); } return {path_many, distances_many}; } /* FindPath: Find a collision-free path from a start to a target. Input: startPoint: 1D integer array [x, y] for the start position endPoint: 1D integer array [x, y] for the goal position Map: 1D integer array for the map, flattened by a 2D array map; 0 for no obstacles, 255 for obstacles mapSizeX: integer for the width of the map mapSizeY: integer for the height of the map Output: path: 1D integer array for the index path from startPoint to endPoint, [idx_x_0,idx_y_0, idx_x_1,idx_y_1, idx_x_2,idx_y_2, ...] distance: float for the total distance of the path */ inline std::tuple<std::vector<int>, float> FindPath( const std::vector<int> &startPoint, const std::vector<int> &endPoint, const std::vector<int> &Map, const int &mapSizeX, const int &mapSizeY) { // Instantiating our path adaptor // passing the map size, and the map Vectori mapSize(mapSizeX, mapSizeY); TileAdaptor adaptor(mapSize, Map); // This is a bit of an exageration here for the weight, but it did make my performance test go from 8s to 2s Pathfinder pathfinder(adaptor, WEIGHT_PATH); // The map was edited so we need to regenerate teh neighbors // pathfinder.generateNodes(); // doing the search // merly to show the point of how it work // as it would have been way easier to simply transform the vector to id and pass it to search // output: std::tuple<std::vector<int>, float> // auto [path, distance] = pathfinder.search(startPoint[1]*mapSizeX+startPoint[0], endPoint[1]*mapSizeX+endPoint[0], mapSize); return pathfinder.search(startPoint[1]*mapSizeX+startPoint[0], endPoint[1]*mapSizeX+endPoint[0], mapSize); } inline std::tuple< std::vector<float>, std::vector<size_t>, std::vector<std::vector<size_t>>, std::vector<float> > KMeans( const std::vector<int>& targets_position, const size_t& num_cluster, const size_t& number_of_iterations) { std::vector<float> targets_position_float(targets_position.begin(), targets_position.end()); return k_means_with_plus_plus(targets_position_float, num_cluster, number_of_iterations); } inline std::tuple< std::vector<float>, std::vector<std::vector<size_t>>, std::vector<size_t> > AssignCluster( const std::vector<int>& agent_position, const std::vector<int>& targets_position, const size_t& num_cluster, const size_t& number_of_iterations) { // convert vector<int> to vector<float> std::vector<float> targets_position_float(targets_position.begin(), targets_position.end()); // K-means clustering auto [cluster_centers, assignments, points_idx_for_clusters, sum_distance_vec] = k_means_with_plus_plus(targets_position_float, num_cluster, number_of_iterations); size_t num_agents = agent_position.size()/2; // Solver // Create the mip solver with the SCIP backend. std::unique_ptr<MPSolver> solver(MPSolver::CreateSolver("SCIP")); // Create binary integer variables // x[i][j] is an array of 0-1 variables, which will be 1 if cluster i is assigned to agent j. std::vector<std::vector<const MPVariable*>> x(num_cluster, std::vector<const MPVariable*>(num_agents)); // Create the objective function MPObjective* const objective = solver->MutableObjective(); for (size_t i = 0; i < num_cluster; ++i) { // Create the constraints // Each cluster is assigned to at most one agent. LinearExpr cluster_sum; for (size_t j = 0; j < num_agents; ++j) { // for binary integer variables x[i][j] = solver->MakeIntVar(0, 1, ""); // for constraints cluster_sum += x[i][j]; // distance btw a cluster centroid and an agent plus the summation of distance btw this centroid and its associated points float cost = std::sqrt(std::pow(static_cast<float>(agent_position[2*j])-cluster_centers[2*i], 2) + std::pow(static_cast<float>(agent_position[2*j+1])-cluster_centers[2*i+1], 2)) + sum_distance_vec[i]; // // here estimate the distance by l1 norm // float cost = 1 * (abs( static_cast<float>(agent_position[2*j]) - cluster_centers[2*i] ) + // abs( static_cast<float>(agent_position[2*j+1]) - cluster_centers[2*i+1] )); // for the objective function objective->SetCoefficient(x[i][j], cost); } // for constraints solver->MakeRowConstraint(cluster_sum <= 1.0); } // for constraints objective->SetMinimization(); // Each task is assigned to exactly one worker. for (size_t j = 0; j < num_agents; ++j) { LinearExpr agent_sum; for (size_t i = 0; i < num_cluster; ++i) { agent_sum += x[i][j]; } solver->MakeRowConstraint(agent_sum == 1.0); } std::vector<size_t> cluster_assigned_idx(num_agents); // Solve const MPSolver::ResultStatus result_status = solver->Solve(); // Print solution. // Check that the problem has a feasible solution. if ( (result_status != MPSolver::OPTIMAL) & (result_status != MPSolver::FEASIBLE) ) { LOG(FATAL) << "No solution found."; } // LOG(INFO) << "Total cost = " << objective->Value() << "\n\n"; // std::cout << "Clusters and agents index start from 0" << std::endl; for (size_t i = 0; i < num_cluster; ++i) { for (size_t j = 0; j < num_agents; ++j) { // Test if x[i][j] is 0 or 1 (with tolerance for floating point arithmetic). if (x[i][j]->solution_value() > 0.5) { // float cost = 1 * ( std::pow( static_cast<float>(agent_position[2*j]-cluster_centers[2*i]), 2 ) + // std::pow( static_cast<float>(agent_position[2*j+1]-cluster_centers[2*i+1]), 2 ) ); // LOG(INFO) << "Cluster " << i << " assigned to agent " << j // << ". Cost = " << cost; // cluster_assigned_idx stores the cluster index for each agent // cluster_assigned_idx[3] = 5 means Cluster 5 is assigned to Agent 3 cluster_assigned_idx[j] = i; } } } return {cluster_centers, points_idx_for_clusters, cluster_assigned_idx}; } inline std::tuple< std::vector<float>, std::vector<std::vector<size_t>>, std::vector<int> > AssignClusterExternalCentroids( const std::vector<int>& agent_position, const std::vector<int>& targets_position, const std::vector<float>& centroids_prev, const size_t& num_cluster, const size_t& number_of_iterations) { // convert vector<int> to vector<float> std::vector<float> targets_position_float(targets_position.begin(), targets_position.end()); // K-means clustering auto [cluster_centers, assignments, points_idx_for_clusters, sum_distance_vec] = k_means_with_external_centroids(targets_position_float, num_cluster, number_of_iterations, centroids_prev); size_t num_agents = agent_position.size()/2; // the available cluster index vector; if cluster_centers[2*idx] < 0, no cluster std::vector<size_t> cluster_available_idx_vec; size_t num_cluster_available = 0; for (size_t idx = 0; idx < num_cluster; ++idx) { if (cluster_centers[2*idx] >= 0) { cluster_available_idx_vec.push_back(idx); num_cluster_available++; } } // Solver // Create the mip solver with the SCIP backend. std::unique_ptr<MPSolver> solver(MPSolver::CreateSolver("SCIP")); // Create binary integer variables // x[i][j] is an array of 0-1 variables, which will be 1 if agent i is assigned to cluster j. std::vector<std::vector<const MPVariable*>> x(num_agents, std::vector<const MPVariable*>(num_cluster_available)); // Create the objective function MPObjective* const objective = solver->MutableObjective(); for (size_t i = 0; i < num_agents; ++i) { // Create the constraints // Each agent is assigned to at most one cluster. LinearExpr agent_sum; for (size_t j = 0; j < num_cluster_available; ++j) { // for binary integer variables x[i][j] = solver->MakeIntVar(0, 1, ""); // for constraints agent_sum += x[i][j]; // distance btw an agent and a cluster, plus WCSS (within cluster sum of squares) float cost = std::sqrt(std::pow(static_cast<float>(agent_position[2*i])-cluster_centers[2*cluster_available_idx_vec[j]], 2) + std::pow(static_cast<float>(agent_position[2*i+1])-cluster_centers[2*cluster_available_idx_vec[j]+1], 2)) + sum_distance_vec[cluster_available_idx_vec[j]]; // for the objective function objective->SetCoefficient(x[i][j], cost); } // for constraints solver->MakeRowConstraint(agent_sum <= 1.0); } objective->SetMinimization(); // Each cluster is assigned to exactly one agent. for (size_t j = 0; j < num_cluster_available; ++j) { LinearExpr cluster_sum; for (size_t i = 0; i < num_agents; ++i) { cluster_sum += x[i][j]; } solver->MakeRowConstraint(cluster_sum == 1.0); } // cluster_assigned_idx stores the cluster index for each agent, all indices start from 0 // cluster_assigned_idx[3] = 5 means Cluster 5 is assigned to Agent 3 // -1 means this agent does not have a cluster std::vector<int> cluster_assigned_idx(num_agents, -1); // Solve const MPSolver::ResultStatus result_status = solver->Solve(); // Print solution. // Check that the problem has a feasible solution. if ( result_status != MPSolver::OPTIMAL && result_status != MPSolver::FEASIBLE ) { LOG(FATAL) << "No solution found."; } // LOG(INFO) << "Total cost = " << objective->Value() << "\n\n"; for (size_t i = 0; i < num_agents; ++i) { for (size_t j = 0; j < num_cluster_available; ++j) { // Test if x[i][j] is 0 or 1 (with tolerance for floating point arithmetic). if (x[i][j]->solution_value() > 0.5) { cluster_assigned_idx[i] = cluster_available_idx_vec[j]; } } } return {cluster_centers, points_idx_for_clusters, cluster_assigned_idx}; } /* SolveOneAgent: Find all the collision-free paths from every element to another element in start+targets, and return an optimal order for the agent to explore all the targets, and the concatenated path given the order. Input: agent_position: 1D integer array [x, y] for the agent position targets_position: 1D integer array [x0,y0, x1,y1, x2,y2, ...] for the targets positions Map: 1D integer array for the map, flattened by a 2D array map; 0 for no obstacles, 255 for obstacles mapSizeX: integer for the width of the map mapSizeY: integer for the height of the map Output: path_many_result: 2D integer array for all the index paths given the task allocation order, [[x0,y0, ..., x1,y1], [x1,y1, ..., x2,y2], [x2,y2, ..., x3,y3], ...] target_idx_order: 1D integer array for task allocation order, [0, 4, 3, 1, 2, 5] means the task allocation order is T0 -> T4 -> T3 -> T1 -> T2 -> T5, where T0 is the first task. */ inline std::tuple< std::vector<std::vector<int>>, std::vector<size_t> > SolveOneAgent( const std::vector<int> &agent_position, const std::vector<int> &targets_position, const std::vector<int> &Map, const int &mapSizeX, const int &mapSizeY) { int num_nodes = targets_position.size()/2 + 1; // number of targets + one agent std::vector<int> start_goal_pair = get_combination(num_nodes, 2); std::vector<std::vector<int>> path_many; std::vector<std::vector<int64_t>> distance_matrix(num_nodes+1, std::vector<int64_t>(num_nodes+1, 0)); int start[2]; int goal[2]; // about solving tsp constexpr int num_vehicles_tsp = 1; const std::vector<RoutingIndexManager::NodeIndex> start_tsp{ RoutingIndexManager::NodeIndex{0} }; // for example: 1 agent, 5 targets, num_nodes=6 (#0~#5), then add one more dummy node #6 const std::vector<RoutingIndexManager::NodeIndex> end_tsp{ RoutingIndexManager::NodeIndex{num_nodes} }; // Instantiating our path adaptor // passing the map size, and the map Vectori mapSize(mapSizeX, mapSizeY); TileAdaptor adaptor(mapSize, Map); // This is a bit of an exageration here for the weight, but it did make my performance test go from 8s to 2s Pathfinder pathfinder(adaptor, WEIGHT_PATH); for (size_t idx = 0; idx < start_goal_pair.size(); idx = idx + 2) { int start_idx = start_goal_pair[idx]; int goal_idx = start_goal_pair[idx+1]; if (start_idx != 0) { start[0] = targets_position[2*(start_idx-1)]; start[1] = targets_position[2*(start_idx-1)+1]; } else { start[0] = agent_position[0]; start[1] = agent_position[1]; } if (goal_idx != 0) { goal[0] = targets_position[2*(goal_idx-1)]; goal[1] = targets_position[2*(goal_idx-1)+1]; } else { goal[0] = agent_position[0]; goal[1] = agent_position[1]; } // doing the search, when infeasible, path is empty, distance = 0 // when start = goal, path = start and distance is empty // std::vector<int>, float auto [path, distance] = pathfinder.search(start[1]*mapSizeX+start[0], goal[1]*mapSizeX+goal[0], mapSize); // assign distance to distance matrix int i = num_nodes - 2 - floor(sqrt(-8*(idx/2) + 4*num_nodes*(num_nodes-1)-7)/2.0 - 0.5); int j = (idx/2) + i + 1 - (num_nodes*(num_nodes-1))/2 + ((num_nodes-i)*((num_nodes-i)-1))/2; if (path.size() > 2) { distance_matrix[i][j] = static_cast<int64_t>( floor(SCALE_FACTOR * distance) ); distance_matrix[j][i] = distance_matrix[i][j]; } else if (path.size() == 2) { // when start = goal, let path = {start, goal}, and distance = 0 path.push_back(path[0]); path.push_back(path[1]); distance_matrix[i][j] = static_cast<int64_t>( floor(SCALE_FACTOR * 0.0) ); distance_matrix[j][i] = distance_matrix[i][j]; } else { // if no feasible, set as a large number, but not the maximum of int64_t distance_matrix[i][j] = static_cast<int64_t>( std::numeric_limits<int>::max() / SCALE_FACTOR / SCALE_FACTOR ); distance_matrix[j][i] = distance_matrix[i][j]; } path_many.push_back(path); // Regenerate the neighbors for next run // if (idx < start_goal_pair.size()-1) pathfinder.generateNodes(); } // Create Routing Index Manager RoutingIndexManager manager(distance_matrix.size(), num_vehicles_tsp, start_tsp, end_tsp); // Create Routing Model. RoutingModel routing(manager); const int transit_callback_index = routing.RegisterTransitCallback( [&distance_matrix, &manager](int64 from_index, int64 to_index) -> int64 { // Convert from routing variable Index to distance matrix NodeIndex. auto from_node = manager.IndexToNode(from_index).value(); auto to_node = manager.IndexToNode(to_index).value(); return distance_matrix[from_node][to_node]; }); // Define cost of each arc. routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index); // Setting first solution heuristic. RoutingSearchParameters searchParameters = DefaultRoutingSearchParameters(); searchParameters.set_first_solution_strategy(FirstSolutionStrategy::AUTOMATIC); // Solve the problem. const Assignment* solution = routing.SolveWithParameters(searchParameters); // // Print solution on console. // PrintSolution(manager, routing, *solution); // std::cout << "This is distance_matrix: " << std::endl; // for (size_t i = 0; i < distance_matrix.size(); i++) // { // for (size_t j = 0; j < distance_matrix[i].size(); j++) // { // std::cout << distance_matrix[i][j] << ", "; // } // std::cout << std::endl; // } // parse the solution, index_route_vec is a vector of route node index, 0 means the agent, 1 ~ n means the fitst ~ n-th target // the last node is a dummy node to relax the constraint that the agent must go back to its original location, so skip the last node // example: index_route_vec = [0, 4, 3, 1, 2, 5], 0 means the agent, 1 ~ 5 means the fitst ~ 5-th target, // the task allocation order is agent 0 -> T4 -> T3 -> T1 -> T2 -> T5 std::vector<int> index_route_vec; int64 index_now = routing.Start(0); while (routing.IsEnd(index_now) == false) { index_route_vec.push_back(manager.IndexToNode(index_now).value()); index_now = solution->Value(routing.NextVar(index_now)); } // need to map index route to path index, if we have route x -> y, we want to map [x,y] to the corresponding index of path_many, // which indicates the route x -> y. // start_goal_pair is the start-goal index pair, path_many stores paths along entries of start_goal_pair // For example: there is 1 agent and 5 targers, start_goal_pair (row-major) = // [0,1, 0,2, 0,3, 0,4, 0,5, // 1,2, 1,3, 1,4, 1,5, // 2,3, 2,4, 2,5, // 3,4, 3,5, // 4,5] // Assume Route [x,y], x < y, is located in x-row, (y-x-1)-column, so there are (x-1) rows before [x,y], denote N = num_targets. // So the total number of elements before x-row is N + (N-1) + (N-2) + ... + (N-(x-1)) = (( N + (N-(x-1)) ) * x) / 2 = ( (2*N-x+1)*x ) / 2 // This formula also holds when x = 0. // And the number of elements in x-row before [x,y] is y - x - 1, note indices start from 0. // So the index of path_many corresponding to route [x,y] is (2*N-x+1)*x/2 + y-x-1 // size_t index_x_to_y = (2*N-x+1)*x/2 + y-x-1; // std::vector<int> path_x_to_y = path_many[index_x_to_y]; // When Route [x,y], x > y, locate the path index for route [y,x], then the path can be obtained by reversing the path of route [y,x]. int x, y; // the route index [x,y] size_t idx_path; // the corresponding path index for route [x,y] std::vector<std::vector<int>> path_many_result; // the paths given route [x,y] for (size_t i = 0; i < index_route_vec.size()-1; ++i) { if (index_route_vec[i] < index_route_vec[i+1]) { x = index_route_vec[i]; y = index_route_vec[i+1]; idx_path = static_cast<size_t>( (2*(num_nodes-1)-x+1)*x/2 + y-x-1 ); path_many_result.push_back(path_many[idx_path]); } else { x = index_route_vec[i+1]; y = index_route_vec[i]; idx_path = static_cast<size_t>( (2*(num_nodes-1)-x+1)*x/2 + y-x-1 ); std::vector<int> path_now = path_many[idx_path]; // if route [x,y], x > y, we need to reverse path_now // let path_now = [x0,y0, x1,y1, x2,y2], then path_reversed = [x2,y2, x1,y1, x0,y0] // so it's NOT an exact vector reverse // swap the first entry with the second to last, swap the second with the last // swap the third with the forth to last, swap the forth with the third to last // until met the central 2 entries, skip them // when the path is empty, do not swap for (int i = 0; i < static_cast<int>(path_now.size()/2) - 1; i = i + 2) { std::iter_swap(path_now.begin()+i, path_now.end()-i-2); std::iter_swap(path_now.begin()+i+1, path_now.end()-i-1); } path_many_result.push_back(path_now); } } // target_idx_order = [0, 3, 4, 2, 1] means the task allocation order is // T0 -> T3 -> T4 -> T2 -> T1, where T0 is the first task std::vector<size_t> target_idx_order; for (size_t i = 0; i < index_route_vec.size()-1; ++i) { target_idx_order.push_back(index_route_vec[i+1] - 1); } return {path_many_result, target_idx_order}; } template <typename T> inline std::tuple< std::vector<std::vector<int>>, std::vector<size_t> > mission_planning_one_agent( const size_t &idx_agent, const std::vector<int> &agent_position, const std::vector<int> &targets_position, const std::vector<T> &cluster_assigned_idx, const std::vector<std::vector<size_t>> &points_idx_for_clusters, const std::vector<int> &Map, const int &mapSizeX, const int &mapSizeY) { // the index of assigned cluster for every agent // [2, 0, 1] indicates that agent-0 with cluster-2, agent-1 with cluster-0, agent-2 with cluster-1 T cluster_idx = cluster_assigned_idx[idx_agent]; std::vector<std::vector<int>> path_many_each_agent; std::vector<size_t> target_idx_order; if (cluster_idx >= -0.5) { // each agent's position std::vector<int> agent_position_each_agent {agent_position[2*idx_agent], agent_position[2*idx_agent+1]}; // number of targets for each agent size_t num_targets_each_agent = points_idx_for_clusters[cluster_idx].size(); std::vector<int> targets_position_each_agent(2*num_targets_each_agent); for (size_t j = 0; j < num_targets_each_agent; ++j) { size_t target_id = points_idx_for_clusters[cluster_idx][j]; targets_position_each_agent[2*j] = targets_position[2*target_id]; targets_position_each_agent[2*j+1] = targets_position[2*target_id+1]; } // remember to add other agents as obstacles (this is the buffered version) // copy map to revise it for each thread std::vector<int> MapNew = Map; for (size_t idx_agent_ = 0; idx_agent_ < agent_position.size()/2; ++idx_agent_) { [[likely]] if (idx_agent_ != idx_agent) { // buffering the surrounding cells as well int x = agent_position[2*idx_agent_]; int y = agent_position[2*idx_agent_+1]; // for experiments // int half_length_x = 4; // int half_length_y = 4; // for simulations int half_length_x = 1; int half_length_y = 1; int x_min = std::max(0, x-half_length_x); int x_max = std::min(mapSizeX-1, x+half_length_x); int y_min = std::max(0, y-half_length_y); int y_max = std::min(mapSizeY-1, y+half_length_y); for (int idx_x = x_min; idx_x < x_max+1; ++idx_x ) { for (int idx_y = y_min; idx_y < y_max+1; ++idx_y ) MapNew[idx_y * mapSizeX + idx_x] = 255; } } } std::tuple< std::vector<std::vector<int>>, std::vector<size_t> > result_tuple_one_agent; if (num_targets_each_agent > 0) { result_tuple_one_agent = SolveOneAgent(agent_position_each_agent, targets_position_each_agent, MapNew, mapSizeX, mapSizeY); std::tie(path_many_each_agent, target_idx_order) = result_tuple_one_agent; } } // if no tasks assigned to this agent, target_idx_order is empty vectors return {path_many_each_agent, target_idx_order}; } /* MissionPlanning: for multiple agents, segment targets into clusters by K-means Clustering first, then assign clusters to agents, and run SolveOneAgent for each agent with multithreading to have the collision-free path and task allocation result. Input: agent_position: 1D integer array [x0,y0, x1,y1, x2,y2, ...] for the agents positions targets_position: 1D integer array [x0,y0, x1,y1, x2,y2, ...] for the targets positions num_cluster: positive integer for number of clusters you want to have for K-means Clustering number_of_iterations: positive integer for number of iterations for K-means Clustering Map: 1D integer array for the map, flattened by a 2D array map; 0 for no obstacles, 255 for obstacles mapSizeX: integer for the width of the map mapSizeY: integer for the height of the map Output: task_allocation_agents: 2D integer array, each sub-array is the task allocation for an agent exmaple: task_allocation_agents[1] = [0, 3, 2, 1] means the task allocation order for Agent 1 is T0 -> T3 -> T2 -> T1, where Agent 1 is the second agent, T0 is the first task */ inline std::tuple< std::vector<std::vector<std::vector<int>>>, std::vector<std::vector<size_t>>, std::vector<float>, std::vector<std::vector<size_t>>, std::vector<size_t> > MissionPlanning( const std::vector<int>& agent_position, const std::vector<int>& targets_position, const size_t& num_cluster, const size_t& number_of_iterations, const std::vector<int> &Map, const int &mapSizeX, const int &mapSizeY) { size_t num_agents = agent_position.size()/2; // std::tuple< std::vector<float>, std::vector<std::vector<size_t>>, std::vector<size_t> > auto [cluster_centers, points_idx_for_clusters, cluster_assigned_idx] = AssignCluster(agent_position, targets_position, num_cluster, number_of_iterations); // a 3D vector, each sub 2D vector is the path for each agent std::vector<std::vector<std::vector<int>>> path_all_agents; // a 2D vector, each sub 1D vector indicates the task allocation order for each agent // note that this index is for local target set std::vector<std::vector<size_t>> task_allocation_agents_local; // a vector of result of asynchronous operations std::vector<std::future< std::tuple<std::vector<std::vector<int>>, std::vector<size_t>> >> vec_async_op; for (size_t idx_agent = 0; idx_agent < num_agents; ++idx_agent) { vec_async_op.push_back(std::async(std::launch::async, &mission_planning_one_agent<size_t>, idx_agent, agent_position, targets_position, cluster_assigned_idx, points_idx_for_clusters, Map, mapSizeX, mapSizeY)); } for (auto &async_op : vec_async_op) { std::tuple<std::vector<std::vector<int>>, std::vector<size_t>> result_tuple_one_agent = async_op.get(); path_all_agents.push_back(std::get<0>(result_tuple_one_agent)); task_allocation_agents_local.push_back(std::get<1>(result_tuple_one_agent)); } // convert the local target index to the global target index std::vector<std::vector<size_t>> task_allocation_agents; for (size_t idx_agent = 0; idx_agent < num_agents; ++idx_agent) { // the cluster index for current agent size_t cluster_idx_this = cluster_assigned_idx[idx_agent]; // the associated targets set/pool std::vector<size_t> targets_pool_this = points_idx_for_clusters[cluster_idx_this]; // the global target index vector for current agent std::vector<size_t> task_allocation_this; for (size_t i = 0; i < targets_pool_this.size(); ++i) { // the global target index size_t task_id_this = task_allocation_agents_local[idx_agent][i]; // bundle this index by a given sequence task_allocation_this.push_back(targets_pool_this[task_id_this]); } task_allocation_agents.push_back(task_allocation_this); } return {path_all_agents, task_allocation_agents, cluster_centers, points_idx_for_clusters, cluster_assigned_idx}; } /* MissionPlanningIteratively: for multiple agents, segment targets into clusters by K-means Clustering first (the initialization of centroids is from external/previous centroids), then assign clusters to agents, and run SolveOneAgent for each agent with multithreading to have the collision-free path and task allocation result. Input: agent_position: 1D integer array [x0,y0, x1,y1, x2,y2, ...] for the agents positions targets_position: 1D integer array [x0,y0, x1,y1, x2,y2, ...] for the targets positions num_cluster: positive integer for number of clusters you want to have for K-means Clustering number_of_iterations: positive integer for number of iterations for K-means Clustering Map: 1D integer array for the map, flattened by a 2D array map; 0 for no obstacles, 255 for obstacles mapSizeX: integer for the width of the map mapSizeY: integer for the height of the map Output: task_allocation_agents: 2D integer array, each sub-array is the task allocation for an agent exmaple: task_allocation_agents[1] = [0, 3, 2, 1] means the task allocation order for Agent 1 is T0 -> T3 -> T2 -> T1, where Agent 1 is the second agent, T0 is the first task */ inline std::tuple< std::vector<std::vector<std::vector<int>>>, std::vector<std::vector<size_t>>, std::vector<float>, std::vector<std::vector<size_t>>, std::vector<int> > MissionPlanningIteratively( const std::vector<int>& agent_position, const std::vector<int>& targets_position, const std::vector<float>& centroids_prev, const size_t& num_cluster, const size_t& number_of_iterations, const std::vector<int> &Map, const int &mapSizeX, const int &mapSizeY) { size_t num_agents = agent_position.size()/2; // std::tuple< std::vector<float>, std::vector<std::vector<size_t>>, std::vector<int> > auto [cluster_centers, points_idx_for_clusters, cluster_assigned_idx] = AssignClusterExternalCentroids(agent_position, targets_position, centroids_prev, num_cluster, number_of_iterations); // a 3D vector, each sub 2D vector is the path for each agent std::vector<std::vector<std::vector<int>>> path_all_agents; // a 2D vector, each sub 1D vector indicates the task allocation order for each agent // note that this index is for local target set std::vector<std::vector<size_t>> task_allocation_agents_local; // a vector of result of asynchronous operations std::vector<std::future< std::tuple<std::vector<std::vector<int>>, std::vector<size_t>> >> vec_async_op; for (size_t idx_agent = 0; idx_agent < num_agents; ++idx_agent) { vec_async_op.push_back(std::async(std::launch::async, &mission_planning_one_agent<int>, idx_agent, agent_position, targets_position, cluster_assigned_idx, points_idx_for_clusters, Map, mapSizeX, mapSizeY)); } for (auto &async_op : vec_async_op) { std::tuple<std::vector<std::vector<int>>, std::vector<size_t>> result_tuple_one_agent = async_op.get(); path_all_agents.push_back(std::get<0>(result_tuple_one_agent)); task_allocation_agents_local.push_back(std::get<1>(result_tuple_one_agent)); } // convert the local target index to the global target index std::vector<std::vector<size_t>> task_allocation_agents; for (size_t idx_agent = 0; idx_agent < num_agents; ++idx_agent) { // the cluster index for current agent int cluster_idx_this = cluster_assigned_idx[idx_agent]; // the global target index vector for current agent std::vector<size_t> task_allocation_this; // if there is a cluster assigned to this agent if (cluster_idx_this >= -0.5) { // the associated targets set/pool std::vector<size_t> targets_pool_this = points_idx_for_clusters[cluster_idx_this]; for (size_t i = 0; i < targets_pool_this.size(); ++i) { // the global target index size_t task_id_this = task_allocation_agents_local[idx_agent][i]; // bundle this index by a given sequence task_allocation_this.push_back(targets_pool_this[task_id_this]); } } task_allocation_agents.push_back(task_allocation_this); } return {path_all_agents, task_allocation_agents, cluster_centers, points_idx_for_clusters, cluster_assigned_idx}; } inline std::vector<std::vector<int>> path_planning_one_agent_many_tasks( const size_t &idx_agent, const std::vector<int> &agent_position, const std::vector<std::vector<int>> &targets_position, const std::vector<int> &Map, const int &mapSizeX, const int &mapSizeY) { // copy map to revise it for each thread std::vector<int> MapNew = Map; // initialize start point as each agent's position int startPoint[2] = {agent_position[2*idx_agent], agent_position[2*idx_agent+1]}; // each agent's target list [x0,y0, x1,y1, x2,y2, ...] std::vector<int> targets_position_this_agent = targets_position[idx_agent]; std::vector<std::vector<int>> path_many; for (size_t idx_target = 0; idx_target < targets_position_this_agent.size()/2; ++idx_target) { int endPoint[2] = {targets_position_this_agent[2*idx_target], targets_position_this_agent[2*idx_target+1]}; // remember to add other agents as obstacles (this is the buffered version) for (size_t idx_agent_ = 0; idx_agent_ < agent_position.size()/2; ++idx_agent_) { [[likely]] if (idx_agent_ != idx_agent) { // buffering the surrounding cells as well int x = agent_position[2*idx_agent_]; int y = agent_position[2*idx_agent_+1]; // for experiments // int half_length_x = 3; // int half_length_y = 3; // for simulations int half_length_x = 1; int half_length_y = 1; int x_min = std::max(0, x-half_length_x); int x_max = std::min(mapSizeX-1, x+half_length_x); int y_min = std::max(0, y-half_length_y); int y_max = std::min(mapSizeY-1, y+half_length_y); for (int idx_x = x_min; idx_x < x_max+1; ++idx_x ) { for (int idx_y = y_min; idx_y < y_max+1; ++idx_y ) MapNew[idx_y * mapSizeX + idx_x] = 255; } } } // // remember to add other agents as obstacles // for (size_t idx_agent_ = 0; idx_agent_ < agent_position.size()/2; ++idx_agent_) { // MapNew[agent_position[2*idx_agent_+1] * mapSizeX + agent_position[2*idx_agent_]] = 255; // } // MapNew[agent_position[2*idx_agent+1] * mapSizeX + agent_position[2*idx_agent]] = 0; // Instantiating the path adaptor, passing the map size, and the map Vectori mapSize(mapSizeX, mapSizeY); TileAdaptor adaptor(mapSize, MapNew); Pathfinder pathfinder(adaptor, WEIGHT_PATH); // find the path, returned by std::tuple<std::vector<int>, float> auto [path, distance] = pathfinder.search(startPoint[1]*mapSizeX+startPoint[0], endPoint[1]*mapSizeX+endPoint[0], mapSize); // if the start == end, path only has [x0,y0], then make it empty if (path.size() < 4) { path = {}; } // initialize the start point of next iteration as the end point of this iteration startPoint[0] = targets_position_this_agent[2*idx_target]; startPoint[1] = targets_position_this_agent[2*idx_target+1]; // path for this start point to this end point path_many.push_back(path); } return path_many; } inline std::vector<std::vector<std::vector<int>>> PathPlanningMultiAgent( const std::vector<int>& agent_position, const std::vector<std::vector<int>>& targets_position, const std::vector<int> &Map, const int &mapSizeX, const int &mapSizeY) { size_t num_agents = agent_position.size()/2; // a 3D vector, each sub-vector is a path for each agent, from the agent position to target positions // path_all_agents[0] = [[x0,y0, ..., x1,y1], [x1,y1, ..., x2,y2], ...] is the path for agent 0 [x0,y0] to // task 0 [x1,y1], and task 0 [x1,y1] to task 1 [x2,y2], etc. std::vector<std::vector<std::vector<int>>> path_all_agents; // a vector of result of asynchronous operations std::vector<std::future< std::vector<std::vector<int>> >> vec_async_op; for (size_t idx_agent = 0; idx_agent < num_agents; ++idx_agent) { vec_async_op.push_back(std::async(std::launch::async, &path_planning_one_agent_many_tasks, idx_agent, agent_position, targets_position, Map, mapSizeX, mapSizeY)); } for (auto &async_op : vec_async_op) { std::vector<std::vector<int>> path_current = async_op.get(); path_all_agents.push_back(path_current); } return path_all_agents; } inline std::tuple< std::vector<std::vector<std::vector<int>>>, std::vector<std::vector<size_t>>, std::vector<float>, std::vector<std::vector<size_t>>, std::vector<size_t> > MissionPlanning_legacy( const std::vector<int>& agent_position, const std::vector<int>& targets_position, const size_t& num_cluster, const size_t& number_of_iterations, const std::vector<int> &Map, const int &mapSizeX, const int &mapSizeY) { size_t num_agents = agent_position.size()/2; // std::tuple< std::vector<float>, std::vector<std::vector<size_t>>, std::vector<size_t> > auto [cluster_centers, points_idx_for_clusters, cluster_assigned_idx] = AssignCluster(agent_position, targets_position, num_cluster, number_of_iterations); // a 3D vector, each sub 2D vector is the path for each agent std::vector<std::vector<std::vector<int>>> path_all_agents; // a 2D vector, each sub 1D vector indicates the task allocation order for each agent std::vector<std::vector<size_t>> task_allocation_agents; for (size_t idx_agent = 0; idx_agent < num_agents; ++idx_agent) { // the index of assigned cluster for every agent // [2, 0, 1] indicates that agent-0 with cluster-2, agent-1 with cluster-0, agent-2 with cluster-1 size_t cluster_idx = cluster_assigned_idx[idx_agent]; // each agent's position std::vector<int> agent_position_each_agent {agent_position[2*idx_agent], agent_position[2*idx_agent+1]}; // number of targets for each agent size_t num_targets_each_agent = points_idx_for_clusters[cluster_idx].size(); std::vector<int> targets_position_each_agent(2*num_targets_each_agent); for (size_t j = 0; j < num_targets_each_agent; ++j) { size_t target_id = points_idx_for_clusters[cluster_idx][j]; targets_position_each_agent[2*j] = targets_position[2*target_id]; targets_position_each_agent[2*j+1] = targets_position[2*target_id+1]; } // remember to add other agents as obstacles std::tuple< std::vector<std::vector<int>>, std::vector<size_t> > result_SolveOneAgent; std::vector<std::vector<int>> path_many_each_agent; std::vector<size_t> target_idx_order; if (num_targets_each_agent > 0) { result_SolveOneAgent = SolveOneAgent(agent_position_each_agent, targets_position_each_agent, Map, mapSizeX, mapSizeY); std::tie(path_many_each_agent, target_idx_order) = result_SolveOneAgent; } // no tasks assigned to this agent, pass empty vectors // targets_position_assigned_agents.push_back(targets_position_each_agent); path_all_agents.push_back(path_many_each_agent); task_allocation_agents.push_back(target_idx_order); } return {path_all_agents, task_allocation_agents, cluster_centers, points_idx_for_clusters, cluster_assigned_idx}; } inline PYBIND11_MODULE(DrMaMP, module) { module.doc() = "Python wrapper of DrMaMP Solver"; module.def("FindPath", &FindPath, "Find a collision-free path from a start to a target"); module.def("FindPathMany", &FindPathMany, "Find all the collision-free paths from every element to another element in start+targets"); module.def("FindPathOneByOne", &FindPathOneByOne, "Find all the collision-free paths consecutively"); module.def("SolveOneAgent", &SolveOneAgent, "Find all the collision-free paths from every element to another element in start+targets, and return an optimal order for the agent to explore all the targets, and the concatenated path given the order."); module.def("KMeans", &KMeans, "K-means Clustering to segment all the targets to several clusters"); module.def("AssignCluster", &AssignCluster, "K-means Clustering first, then assign clusters to agents, #clusters >= #agents"); module.def("MissionPlanning", &MissionPlanning, "K-means Clustering, then assign clusters to agents, and run SolveOneAgent for each agent (with multithreading)"); module.def("MissionPlanningIteratively", &MissionPlanningIteratively, "K-means Clustering with previous centroids, then assign clusters to agents, and run SolveOneAgent for each agent (with multithreading)"); module.def("PathPlanningMultiAgent", &PathPlanningMultiAgent, "Planning path for multiple agents, each agent is associated with a target"); module.def("MissionPlanning_legacy", &MissionPlanning_legacy, "Old version of MissionPlanning using for-loops (without multithreading)"); }
44.236984
221
0.656575
[ "vector", "model", "transform", "3d" ]
67ff496940e5ffe0a456ef81f77da0ea2e53b199
9,845
cc
C++
CondFormats/CastorObjects/src/CastorElectronicsMap.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
CondFormats/CastorObjects/src/CastorElectronicsMap.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
CondFormats/CastorObjects/src/CastorElectronicsMap.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
/** \class CastorElectronicsMap \author Fedor Ratnikov (UMd) POOL object to store mapping for Castor channels $Author: ratnikov $Date: 2008/01/22 18:58:47 $ $Revision: 1.23 $ Adapted for CASTOR by L. Mundim */ #include <iostream> #include <set> #include "CondFormats/CastorObjects/interface/CastorElectronicsMap.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" CastorElectronicsMap::CastorElectronicsMap() : mPItems(CastorElectronicsId::maxLinearIndex + 1), mTItems(CastorElectronicsId::maxLinearIndex + 1), mPItemsById(nullptr), mTItemsByTrigId(nullptr) {} namespace castor_impl { class LessById { public: bool operator()(const CastorElectronicsMap::PrecisionItem* a, const CastorElectronicsMap::PrecisionItem* b) { return a->mId < b->mId; } }; class LessByTrigId { public: bool operator()(const CastorElectronicsMap::TriggerItem* a, const CastorElectronicsMap::TriggerItem* b) { return a->mTrigId < b->mTrigId; } }; } // namespace castor_impl CastorElectronicsMap::~CastorElectronicsMap() { delete mPItemsById.load(); delete mTItemsByTrigId.load(); } // copy-ctor CastorElectronicsMap::CastorElectronicsMap(const CastorElectronicsMap& src) : mPItems(src.mPItems), mTItems(src.mTItems), mPItemsById(nullptr), mTItemsByTrigId(nullptr) {} // copy assignment operator CastorElectronicsMap& CastorElectronicsMap::operator=(const CastorElectronicsMap& rhs) { CastorElectronicsMap temp(rhs); temp.swap(*this); return *this; } // public swap function void CastorElectronicsMap::swap(CastorElectronicsMap& other) { std::swap(mPItems, other.mPItems); std::swap(mTItems, other.mTItems); other.mTItemsByTrigId.exchange(mTItemsByTrigId.exchange(other.mTItemsByTrigId)); other.mPItemsById.exchange(mPItemsById.exchange(other.mPItemsById)); } // move constructor CastorElectronicsMap::CastorElectronicsMap(CastorElectronicsMap&& other) : CastorElectronicsMap() { other.swap(*this); } const CastorElectronicsMap::PrecisionItem* CastorElectronicsMap::findById(unsigned long fId) const { PrecisionItem target(fId, 0); std::vector<const CastorElectronicsMap::PrecisionItem*>::const_iterator item; sortById(); item = std::lower_bound((*mPItemsById).begin(), (*mPItemsById).end(), &target, castor_impl::LessById()); if (item == (*mPItemsById).end() || (*item)->mId != fId) // throw cms::Exception ("Conditions not found") << "Unavailable Electronics map for cell " << fId; return nullptr; return *item; } const CastorElectronicsMap::PrecisionItem* CastorElectronicsMap::findPByElId(unsigned long fElId) const { CastorElectronicsId eid(fElId); const PrecisionItem* i = &(mPItems[eid.linearIndex()]); if (i != nullptr && i->mElId != fElId) i = nullptr; return i; } const CastorElectronicsMap::TriggerItem* CastorElectronicsMap::findTByElId(unsigned long fElId) const { CastorElectronicsId eid(fElId); const TriggerItem* i = &(mTItems[eid.linearIndex()]); if (i != nullptr && i->mElId != fElId) i = nullptr; return i; } const CastorElectronicsMap::TriggerItem* CastorElectronicsMap::findByTrigId(unsigned long fTrigId) const { TriggerItem target(fTrigId, 0); std::vector<const CastorElectronicsMap::TriggerItem*>::const_iterator item; sortByTriggerId(); item = std::lower_bound((*mTItemsByTrigId).begin(), (*mTItemsByTrigId).end(), &target, castor_impl::LessByTrigId()); if (item == (*mTItemsByTrigId).end() || (*item)->mTrigId != fTrigId) // throw cms::Exception ("Conditions not found") << "Unavailable Electronics map for cell " << fId; return nullptr; return *item; } const DetId CastorElectronicsMap::lookup(CastorElectronicsId fId) const { const PrecisionItem* item = findPByElId(fId.rawId()); return DetId(item ? item->mId : 0); } const CastorElectronicsId CastorElectronicsMap::lookup(DetId fId) const { const PrecisionItem* item = findById(fId.rawId()); return CastorElectronicsId(item ? item->mElId : 0); } const DetId CastorElectronicsMap::lookupTrigger(CastorElectronicsId fId) const { const TriggerItem* item = findTByElId(fId.rawId()); return DetId(item ? item->mTrigId : 0); } const CastorElectronicsId CastorElectronicsMap::lookupTrigger(DetId fId) const { const TriggerItem* item = findByTrigId(fId.rawId()); return CastorElectronicsId(item ? item->mElId : 0); } bool CastorElectronicsMap::lookup(const CastorElectronicsId pid, CastorElectronicsId& eid, HcalGenericDetId& did) const { const PrecisionItem* i = &(mPItems[pid.linearIndex()]); if (i != nullptr && i->mId != 0) { eid = CastorElectronicsId(i->mElId); did = HcalGenericDetId(i->mId); return true; } else return false; } bool CastorElectronicsMap::lookup(const CastorElectronicsId pid, CastorElectronicsId& eid, HcalTrigTowerDetId& did) const { const TriggerItem* i = &(mTItems[pid.linearIndex()]); if (i != nullptr && i->mTrigId != 0) { eid = CastorElectronicsId(i->mElId); did = HcalGenericDetId(i->mTrigId); return true; } else return false; } std::vector<CastorElectronicsId> CastorElectronicsMap::allElectronicsId() const { std::vector<CastorElectronicsId> result; for (std::vector<PrecisionItem>::const_iterator item = mPItems.begin(); item != mPItems.end(); item++) if (item->mElId) result.push_back(CastorElectronicsId(item->mElId)); for (std::vector<TriggerItem>::const_iterator item = mTItems.begin(); item != mTItems.end(); item++) if (item->mElId) result.push_back(CastorElectronicsId(item->mElId)); return result; } std::vector<CastorElectronicsId> CastorElectronicsMap::allElectronicsIdPrecision() const { std::vector<CastorElectronicsId> result; for (std::vector<PrecisionItem>::const_iterator item = mPItems.begin(); item != mPItems.end(); item++) if (item->mElId) result.push_back(CastorElectronicsId(item->mElId)); return result; } std::vector<CastorElectronicsId> CastorElectronicsMap::allElectronicsIdTrigger() const { std::vector<CastorElectronicsId> result; for (std::vector<TriggerItem>::const_iterator item = mTItems.begin(); item != mTItems.end(); item++) if (item->mElId) result.push_back(CastorElectronicsId(item->mElId)); return result; } std::vector<HcalGenericDetId> CastorElectronicsMap::allPrecisionId() const { std::vector<HcalGenericDetId> result; std::set<unsigned long> allIds; for (std::vector<PrecisionItem>::const_iterator item = mPItems.begin(); item != mPItems.end(); item++) if (item->mId) allIds.insert(item->mId); for (std::set<unsigned long>::const_iterator channel = allIds.begin(); channel != allIds.end(); channel++) { result.push_back(HcalGenericDetId(*channel)); } return result; } std::vector<HcalTrigTowerDetId> CastorElectronicsMap::allTriggerId() const { std::vector<HcalTrigTowerDetId> result; std::set<unsigned long> allIds; for (std::vector<TriggerItem>::const_iterator item = mTItems.begin(); item != mTItems.end(); item++) if (item->mTrigId) allIds.insert(item->mTrigId); for (std::set<unsigned long>::const_iterator channel = allIds.begin(); channel != allIds.end(); channel++) result.push_back(HcalTrigTowerDetId(*channel)); return result; } bool CastorElectronicsMap::mapEId2tId(CastorElectronicsId fElectronicsId, HcalTrigTowerDetId fTriggerId) { TriggerItem& item = mTItems[fElectronicsId.linearIndex()]; if (item.mElId == 0) item.mElId = fElectronicsId.rawId(); if (item.mTrigId == 0) { item.mTrigId = fTriggerId.rawId(); // just cast avoiding long machinery } else if (item.mTrigId != fTriggerId.rawId()) { edm::LogWarning("CASTOR") << "CastorElectronicsMap::mapEId2tId-> Electronics channel " << fElectronicsId << " already mapped to trigger channel " << (HcalTrigTowerDetId(item.mTrigId)) << ". New value " << fTriggerId << " is ignored"; return false; } return true; } bool CastorElectronicsMap::mapEId2chId(CastorElectronicsId fElectronicsId, DetId fId) { PrecisionItem& item = mPItems[fElectronicsId.linearIndex()]; if (item.mElId == 0) item.mElId = fElectronicsId.rawId(); if (item.mId == 0) { item.mId = fId.rawId(); } else if (item.mId != fId.rawId()) { edm::LogWarning("CASTOR") << "CastorElectronicsMap::mapEId2tId-> Electronics channel " << fElectronicsId << " already mapped to channel " << HcalGenericDetId(item.mId) << ". New value " << HcalGenericDetId(fId) << " is ignored"; return false; } return true; } void CastorElectronicsMap::sortById() const { if (!mPItemsById) { auto ptr = new std::vector<const PrecisionItem*>; for (auto i = mPItems.begin(); i != mPItems.end(); ++i) { if (i->mElId) (*ptr).push_back(&(*i)); } std::sort((*ptr).begin(), (*ptr).end(), castor_impl::LessById()); //atomically try to swap this to become mPItemsById std::vector<const PrecisionItem*>* expect = nullptr; bool exchanged = mPItemsById.compare_exchange_strong(expect, ptr); if (!exchanged) { delete ptr; } } } void CastorElectronicsMap::sortByTriggerId() const { if (!mTItemsByTrigId) { auto ptr = new std::vector<const TriggerItem*>; for (auto i = mTItems.begin(); i != mTItems.end(); ++i) { if (i->mElId) (*ptr).push_back(&(*i)); } std::sort((*ptr).begin(), (*ptr).end(), castor_impl::LessByTrigId()); //atomically try to swap this to become mTItemsByTrigId std::vector<const TriggerItem*>* expect = nullptr; bool exchanged = mTItemsByTrigId.compare_exchange_strong(expect, ptr); if (!exchanged) { delete ptr; } } }
37.011278
120
0.693448
[ "object", "vector" ]
db05e28e2abdcac2306b843fdfd0b11f9b799d74
9,145
hpp
C++
subversion/bindings/javahl/native/jniwrapper/jni_string_map.hpp
saurabhacellere/subversion
6e7a18e22d4d4cbfad917e18b784adf1912aa67f
[ "Apache-2.0" ]
3
2017-01-03T03:20:56.000Z
2018-12-24T22:05:09.000Z
subversion/bindings/javahl/native/jniwrapper/jni_string_map.hpp
saurabhacellere/subversion
6e7a18e22d4d4cbfad917e18b784adf1912aa67f
[ "Apache-2.0" ]
3
2016-06-12T17:02:25.000Z
2019-02-03T11:08:18.000Z
subversion/bindings/javahl/native/jniwrapper/jni_string_map.hpp
saurabhacellere/subversion
6e7a18e22d4d4cbfad917e18b784adf1912aa67f
[ "Apache-2.0" ]
3
2017-01-21T00:15:13.000Z
2020-11-04T07:23:50.000Z
/** * @copyright * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * @endcopyright */ #ifndef SVN_JAVAHL_JNIWRAPPER_STRING_MAP_HPP #define SVN_JAVAHL_JNIWRAPPER_STRING_MAP_HPP #include <string> #include "jni_env.hpp" #include "jni_object.hpp" #include "jni_iterator.hpp" namespace Java { /** * Non-template base for an immutable type-safe Java map with String keys. * * @since New in 1.9. */ class BaseImmutableMap : public Object { public: /** * Returns the number of elements in the map. */ jint length() const { return m_env.CallIntMethod(m_jthis, impl().m_mid_size); } /** * Checks if the map is empty. */ bool is_empty() const { return (length() == 0); } protected: /** * Constructs the map wrapper. */ explicit BaseImmutableMap(Env env, jobject jmap) : Object(env, ClassCache::get_map(env), jmap) {} /** * Constructor used by BaseMap. */ explicit BaseImmutableMap(Env env, const Object::ClassImpl* pimpl) : Object(env, pimpl) {} /** * Clears the contents of the map. */ void clear() { m_env.CallVoidMethod(m_jthis, impl().m_mid_clear); } /** * Inserts @a obj identified by @a key into the map. */ void put(const std::string& key, jobject obj) { m_env.CallObjectMethod(m_jthis, impl().m_mid_put, String(m_env, key).get(), obj); } /** * Returns the object reference identified by @a index. * @throw std::out_of_range if there is no such element. */ jobject operator[](const std::string& index) const; /** * This object's implementation details. */ class ClassImpl : public Object::ClassImpl { friend class ClassCacheImpl; protected: explicit ClassImpl(Env env, jclass cls); public: virtual ~ClassImpl(); const MethodID m_mid_put; const MethodID m_mid_clear; const MethodID m_mid_has_key; const MethodID m_mid_get; const MethodID m_mid_size; const MethodID m_mid_entry_set; }; const ClassImpl& impl() const { return *dynamic_cast<const ClassImpl*>(m_impl); } friend class ClassCacheImpl; static const char* const m_class_name; class Iterator : public BaseIterator { friend class BaseImmutableMap; explicit Iterator(Env env, jobject jiterator) : BaseIterator(env, jiterator) {} }; Iterator get_iterator() const; class Entry : public Object { public: explicit Entry(Env env, jobject jentry) : Object(env, ClassCache::get_map_entry(env), jentry) {} const std::string key() const { const jstring jkey = jstring(m_env.CallObjectMethod(m_jthis, impl().m_mid_get_key)); const String::Contents key(String(m_env, jkey)); return std::string(key.c_str()); } jobject value() const { return m_env.CallObjectMethod(m_jthis, impl().m_mid_get_value); } private: /** * This object's implementation details. */ class ClassImpl : public Object::ClassImpl { friend class ClassCacheImpl; protected: explicit ClassImpl(Env env, jclass cls); public: virtual ~ClassImpl(); const MethodID m_mid_get_key; const MethodID m_mid_get_value; }; friend class ClassCacheImpl; static const char* const m_class_name; const ClassImpl& impl() const { return *dynamic_cast<const ClassImpl*>(m_impl); } }; private: struct Set { /** * This object's implementation details. */ class ClassImpl : public Object::ClassImpl { friend class ClassCacheImpl; protected: explicit ClassImpl(Env env, jclass cls); public: virtual ~ClassImpl(); const MethodID m_mid_iterator; }; static const char* const m_class_name; static const ClassImpl& impl(Env env) { return *dynamic_cast<const ClassImpl*>(ClassCache::get_set(env)); } }; }; /** * Template wrapper for an immutable type-safe Java map. * * @since New in 1.9. */ template <typename T, typename NativeT=jobject> class ImmutableMap : public BaseImmutableMap { public: /** * Constructs the map wrapper, converting the contents to an * @c std::map. */ explicit ImmutableMap(Env env, jobject jmap) : BaseImmutableMap(env, jmap) {} /** * Returns a wrapper object for the object reference identified by @a index. * @throw std::out_of_range if there is no such element. */ T operator[](const std::string& index) const { return T(m_env, NativeT(BaseImmutableMap::operator[](index))); } /** * Iterates over the items in the map, calling @a function for * each item. * @see std::for_each * @note Unlike std::for_each, which invokes the functor with a * single @c value_type argument, this iterator calls * @a function with separate @c const references to the key * and value. */ template<typename F> F for_each(F function) const { Iterator iter(get_iterator()); while (iter.has_next()) { Entry entry(m_env, iter.next()); const std::string& key(entry.key()); function(key, T(m_env, NativeT(entry.value()))); } return function; } }; /** * Non-template base for a mutable type-safe Java map with String keys. * * @since New in 1.9. */ class BaseMap : public BaseImmutableMap { public: /** * Clears the contents of the map. */ void clear() { BaseImmutableMap::clear(); } protected: /** * Constructs the map wrapper, treating @a jmap as a @c java.util.Map. */ explicit BaseMap(Env env, jobject jmap) : BaseImmutableMap(env, jmap) {} /** * Constructs and wraps an empty map of type @c java.util.HashMap * with initial allocation size @a length. */ explicit BaseMap(Env env, jint length) : BaseImmutableMap(env, ClassCache::get_hash_map(env)) { set_this(env.NewObject(get_class(), impl().m_mid_ctor, length)); } private: /** * This object's implementation details. */ class ClassImpl : public BaseImmutableMap::ClassImpl { friend class ClassCacheImpl; protected: explicit ClassImpl(Env env, jclass cls); public: virtual ~ClassImpl(); const MethodID m_mid_ctor; }; const ClassImpl& impl() const { return *dynamic_cast<const ClassImpl*>(m_impl); } friend class ClassCacheImpl; static const char* const m_class_name; }; /** * Template wrapper for a mutable type-safe Java map. * * @since New in 1.9. */ template <typename T, typename NativeT=jobject> class Map : public BaseMap { public: /** * Constructs the map wrapper, deriving the class from @a jmap. */ explicit Map(Env env, jobject jmap) : BaseMap(env, jmap) {} /** * Constructs and wraps an empty map of type @c java.util.HashMap * with initial allocation size @a length. */ explicit Map(Env env, jint length = 0) : BaseMap(env, length) {} /** * Inserts @a obj identified by @a key into the map. */ void put(const std::string& key, const T& obj) { BaseMap::put(key, obj.get()); } /** * Returns a wrapper object for the object reference identified by @a index. * @throw std::out_of_range if there is no such element. */ T operator[](const std::string& index) const { return T(m_env, NativeT(BaseMap::operator[](index))); } /** * Iterates over the items in the map, calling @a function for * each item. * @see std::for_each * @note Unlike std::for_each, which invokes the functor with a * single @c value_type argument, this iterator calls * @a function with separate @c const references to the key * and value. */ template<typename F> F for_each(F function) const { Iterator iter(get_iterator()); while (iter.has_next()) { Entry entry(m_env, iter.next()); const std::string& key(entry.key()); function(key, T(m_env, NativeT(entry.value()))); } return function; } }; } // namespace Java #endif // SVN_JAVAHL_JNIWRAPPER_STRING_MAP_HPP
23.753247
78
0.631493
[ "object" ]
db05f085959b8627713ce968937f19028df7734c
381
cpp
C++
abc/abc213/b.cpp
takanori536/atcoder
9e10e5e09b39e064e14f03688c7cdddf6c13b505
[ "CC0-1.0" ]
null
null
null
abc/abc213/b.cpp
takanori536/atcoder
9e10e5e09b39e064e14f03688c7cdddf6c13b505
[ "CC0-1.0" ]
null
null
null
abc/abc213/b.cpp
takanori536/atcoder
9e10e5e09b39e064e14f03688c7cdddf6c13b505
[ "CC0-1.0" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #include <atcoder/all> using namespace atcoder; #define rep(i, n) for (int i = 0; i < (n); i++) using ll = long long; int main() { int n; cin >> n; vector<pair<int, int>> a(n); rep (i, n) cin >> a[i].first, a[i].second = i + 1; sort(a.rbegin(), a.rend()); cout << a[1].second << endl; return 0; }
19.05
47
0.538058
[ "vector" ]
db0e282458c89ff0286dd116035eaea32f9d7899
2,063
cpp
C++
stack/stackArr.cpp
1aman1/DS-implementations
35301dcb5e7642d32e06e01f2d70f3188806c995
[ "MIT" ]
3
2019-06-22T07:22:57.000Z
2021-05-06T10:34:02.000Z
stack/stackArr.cpp
1aman1/DS-implementations
35301dcb5e7642d32e06e01f2d70f3188806c995
[ "MIT" ]
1
2019-06-21T07:39:33.000Z
2019-06-21T07:39:33.000Z
stack/stackArr.cpp
1aman1/DS-implementations
35301dcb5e7642d32e06e01f2d70f3188806c995
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> #define SIZE 5 using namespace std; class _stack{ public: int capacity; int top; int* stackArr; }; void __function__(string p, string q ){ cout << setw(19)<< left << p << "\t\t[ " << q << " ]\n"; } _stack* createStack() { _stack* object = new _stack; if( !object ){ __function__("no Memory Available", __FUNCTION__ ); return NULL; } else{ object->top = -1; object->capacity = SIZE; object->stackArr = new int[object->capacity * sizeof(int)]; if( !object->stackArr ){ __function__("no Memory Available", __FUNCTION__ ); return NULL; } return object; } } void deleteStack( _stack* object ){ if( object ){ if( object->stackArr ) delete object->stackArr; delete object; } } bool isStackEmpty( _stack* object ){ return object->top == -1; } bool isStackFull( _stack* object ){ return object->top == object->capacity -1; } void push( _stack* object, int item ){ if( isStackFull( object ) ){ __function__("_stack full", __FUNCTION__ ); } else object->stackArr[++object->top] = item; } int pop( _stack* object ){ if( isStackEmpty( object ) ){ __function__("_stack full", __FUNCTION__ ); return INT_MIN; } else return object->stackArr[ object->top-- ]; } void topOfStack( _stack* object ){ if( isStackEmpty( object ) ){ __function__("_stack full", __FUNCTION__ ); } else cout << "top:" << object->stackArr[ object->top ] << endl; } /* void doubleStack( _stack* object ){ int arr[object->capacity]; copy_n( object->stackArr, object->capacity, arr ); object->capacity *= 2; object->stackArr = new int[object->capacity * sizeof(int)]; copy_n( arr, object->capacity /2, object->stackArr); } */ int main() { _stack* top = createStack(); push( top, 1 ); push( top, 2 ); push( top, 3 ); push( top, 4 ); //doubleStack( top ); push( top, 200 ); topOfStack( top ); cout << pop( top ) << endl; cout << pop( top ) << endl; cout << pop( top ) << endl; return 0; }
20.22549
63
0.60349
[ "object" ]
db1487d18b6c73a0eced15953d617cb6ac0787d6
886
cpp
C++
src/Tools/Converter/StdVector.cpp
NaokiTakahashi12/OpenHumanoidController
ce8da0cabc8bbeec86f16a36b9ba5e6a16c4a67d
[ "MIT" ]
1
2019-09-23T06:21:47.000Z
2019-09-23T06:21:47.000Z
src/Tools/Converter/StdVector.cpp
NaokiTakahashi12/hc-early
ce8da0cabc8bbeec86f16a36b9ba5e6a16c4a67d
[ "MIT" ]
12
2019-07-30T00:17:09.000Z
2019-12-09T23:00:43.000Z
src/Tools/Converter/StdVector.cpp
NaokiTakahashi12/OpenHumanoidController
ce8da0cabc8bbeec86f16a36b9ba5e6a16c4a67d
[ "MIT" ]
null
null
null
/** * * @file ConvertStdVector.cpp * **/ #include <Eigen/Geometry> #include "StdVector.hpp" namespace Tools { namespace Converter { namespace StdVector { template <> Eigen::Matrix<int, Eigen::Dynamic, 1> to_vector(std::vector<int> &vector_stl) { return Eigen::Map<Eigen::Matrix<int, Eigen::Dynamic, 1>, Eigen::Unaligned>(vector_stl.data(), vector_stl.size()).matrix(); } template <> Eigen::Matrix<float, Eigen::Dynamic, 1> to_vector(std::vector<float> &vector_stl) { return Eigen::Map<Eigen::Matrix<float, Eigen::Dynamic, 1>, Eigen::Unaligned>(vector_stl.data(), vector_stl.size()).matrix(); } template <> Eigen::Matrix<double, Eigen::Dynamic, 1> to_vector(std::vector<double> &vector_stl) { return Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, 1>, Eigen::Unaligned>(vector_stl.data(), vector_stl.size()).matrix(); } } } }
26.848485
129
0.668172
[ "geometry", "vector" ]
db15b8d3ccb6c5433131dbe02a5bd27f016d961e
8,764
cpp
C++
main.cpp
openbmc/phosphor-pid-control
457993f836338aa0c13a32af803fcbc5227c81f3
[ "Apache-2.0" ]
9
2018-09-19T10:26:53.000Z
2020-11-09T23:02:16.000Z
main.cpp
openbmc/phosphor-pid-control
457993f836338aa0c13a32af803fcbc5227c81f3
[ "Apache-2.0" ]
17
2018-08-13T10:34:26.000Z
2022-02-08T02:24:12.000Z
main.cpp
openbmc/phosphor-pid-control
457993f836338aa0c13a32af803fcbc5227c81f3
[ "Apache-2.0" ]
9
2019-03-23T03:08:32.000Z
2021-04-25T03:39:34.000Z
/** * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "config.h" #include "build/buildjson.hpp" #include "conf.hpp" #include "dbus/dbusconfiguration.hpp" #include "interfaces.hpp" #include "pid/builder.hpp" #include "pid/buildjson.hpp" #include "pid/pidloop.hpp" #include "pid/tuning.hpp" #include "pid/zone.hpp" #include "sensors/builder.hpp" #include "sensors/buildjson.hpp" #include "sensors/manager.hpp" #include "util.hpp" #include <CLI/CLI.hpp> #include <boost/asio/io_context.hpp> #include <boost/asio/steady_timer.hpp> #include <sdbusplus/asio/connection.hpp> #include <sdbusplus/bus.hpp> #include <sdbusplus/server/manager.hpp> #include <chrono> #include <filesystem> #include <iostream> #include <list> #include <map> #include <memory> #include <thread> #include <unordered_map> #include <utility> #include <vector> namespace pid_control { /* The configuration converted sensor list. */ std::map<std::string, conf::SensorConfig> sensorConfig = {}; /* The configuration converted PID list. */ std::map<int64_t, conf::PIDConf> zoneConfig = {}; /* The configuration converted Zone configuration. */ std::map<int64_t, conf::ZoneConfig> zoneDetailsConfig = {}; } // namespace pid_control /** the swampd daemon will check for the existence of this file. */ constexpr auto jsonConfigurationPath = "/usr/share/swampd/config.json"; std::string configPath = ""; /* async io context for operation */ boost::asio::io_context io; /* buses for system control */ static sdbusplus::asio::connection modeControlBus(io); static sdbusplus::asio::connection hostBus(io, sdbusplus::bus::new_system().release()); static sdbusplus::asio::connection passiveBus(io, sdbusplus::bus::new_system().release()); namespace pid_control { void restartControlLoops() { static SensorManager mgmr; static std::unordered_map<int64_t, std::shared_ptr<ZoneInterface>> zones; static std::vector<std::shared_ptr<boost::asio::steady_timer>> timers; static bool isCanceling = false; for (const auto& timer : timers) { timer->cancel(); } isCanceling = true; timers.clear(); if (zones.size() > 0 && zones.begin()->second.use_count() > 1) { throw std::runtime_error("wait for count back to 1"); } zones.clear(); isCanceling = false; const std::string& path = (configPath.length() > 0) ? configPath : jsonConfigurationPath; if (std::filesystem::exists(path)) { /* * When building the sensors, if any of the dbus passive ones aren't on * the bus, it'll fail immediately. */ try { auto jsonData = parseValidateJson(path); sensorConfig = buildSensorsFromJson(jsonData); std::tie(zoneConfig, zoneDetailsConfig) = buildPIDsFromJson(jsonData); } catch (const std::exception& e) { std::cerr << "Failed during building: " << e.what() << "\n"; exit(EXIT_FAILURE); /* fatal error. */ } } else { static boost::asio::steady_timer reloadTimer(io); if (!dbus_configuration::init(modeControlBus, reloadTimer, sensorConfig, zoneConfig, zoneDetailsConfig)) { return; // configuration not ready } } mgmr = buildSensors(sensorConfig, passiveBus, hostBus); zones = buildZones(zoneConfig, zoneDetailsConfig, mgmr, modeControlBus); if (0 == zones.size()) { std::cerr << "No zones defined, exiting.\n"; std::exit(EXIT_FAILURE); } for (const auto& i : zones) { std::shared_ptr<boost::asio::steady_timer> timer = timers.emplace_back( std::make_shared<boost::asio::steady_timer>(io)); std::cerr << "pushing zone " << i.first << "\n"; pidControlLoop(i.second, timer, &isCanceling); } } void tryRestartControlLoops(bool first) { static int count = 0; static const auto delayTime = std::chrono::seconds(10); static boost::asio::steady_timer timer(io); // try to start a control loop while the loop has been scheduled. if (first && count != 0) { std::cerr << "ControlLoops has been scheduled, refresh the loop count\n"; count = 1; return; } auto restartLbd = [](const boost::system::error_code& error) { if (error == boost::asio::error::operation_aborted) { return; } // for the last loop, don't elminate the failure of restartControlLoops. if (count >= 5) { restartControlLoops(); // reset count after succesful restartControlLoops() count = 0; return; } // retry when restartControlLoops() has some failure. try { restartControlLoops(); // reset count after succesful restartControlLoops() count = 0; } catch (const std::exception& e) { std::cerr << count << " Failed during restartControlLoops, try again: " << e.what() << "\n"; tryRestartControlLoops(false); } }; count++; // first time of trying to restart the control loop without a delay if (first) { boost::asio::post(io, std::bind(restartLbd, boost::system::error_code())); } // re-try control loop, set up a delay. else { timer.expires_after(delayTime); timer.async_wait(restartLbd); } return; } } // namespace pid_control int main(int argc, char* argv[]) { loggingPath = ""; loggingEnabled = false; tuningEnabled = false; CLI::App app{"OpenBMC Fan Control Daemon"}; app.add_option("-c,--conf", configPath, "Optional parameter to specify configuration at run-time") ->check(CLI::ExistingFile); app.add_option("-l,--log", loggingPath, "Optional parameter to specify logging folder") ->check(CLI::ExistingDirectory); app.add_flag("-t,--tuning", tuningEnabled, "Enable or disable tuning"); CLI11_PARSE(app, argc, argv); static constexpr auto loggingEnablePath = "/etc/thermal.d/logging"; static constexpr auto tuningEnablePath = "/etc/thermal.d/tuning"; // Set up default logging path, preferring command line if it was given std::string defLoggingPath(loggingPath); if (defLoggingPath.empty()) { defLoggingPath = std::filesystem::temp_directory_path(); } else { // Enable logging, if user explicitly gave path on command line loggingEnabled = true; } // If this file exists, enable logging at runtime std::ifstream fsLogging(loggingEnablePath); if (fsLogging) { // The first line of file might be a valid directory path std::getline(fsLogging, loggingPath); fsLogging.close(); // If so, use it, otherwise use default logging path instead if (!(std::filesystem::exists(loggingPath))) { loggingPath = defLoggingPath; } loggingEnabled = true; } if (loggingEnabled) { std::cerr << "Logging enabled: " << loggingPath << "\n"; } // If this file exists, enable tuning at runtime if (std::filesystem::exists(tuningEnablePath)) { tuningEnabled = true; } // This can also be enabled from the command line if (tuningEnabled) { std::cerr << "Tuning enabled\n"; } static constexpr auto modeRoot = "/xyz/openbmc_project/settings/fanctrl"; // Create a manager for the ModeBus because we own it. sdbusplus::server::manager::manager( static_cast<sdbusplus::bus::bus&>(modeControlBus), modeRoot); hostBus.request_name("xyz.openbmc_project.Hwmon.external"); modeControlBus.request_name("xyz.openbmc_project.State.FanCtrl"); sdbusplus::server::manager::manager objManager(modeControlBus, modeRoot); /* * All sensors are managed by one manager, but each zone has a pointer to * it. */ pid_control::tryRestartControlLoops(); io.run(); return 0; }
29.311037
80
0.629507
[ "vector" ]
db1bb967c619ebfde15f32065de2186035ab3f7b
10,828
cpp
C++
Tests/DiligentCoreAPITest/src/CopyTextureTest.cpp
dtcxzyw/DiligentCore
e3891d4936956bb6228f1e949ea57810ab7cb08c
[ "Apache-2.0" ]
15
2021-07-03T17:20:50.000Z
2022-03-20T23:39:09.000Z
Tests/DiligentCoreAPITest/src/CopyTextureTest.cpp
dtcxzyw/DiligentCore
e3891d4936956bb6228f1e949ea57810ab7cb08c
[ "Apache-2.0" ]
1
2021-08-09T15:10:17.000Z
2021-09-30T06:47:04.000Z
Tests/DiligentCoreAPITest/src/CopyTextureTest.cpp
dtcxzyw/DiligentCore
e3891d4936956bb6228f1e949ea57810ab7cb08c
[ "Apache-2.0" ]
9
2021-07-21T10:53:59.000Z
2022-03-03T10:27:33.000Z
/* * Copyright 2019-2020 Diligent Graphics LLC * Copyright 2015-2019 Egor Yusov * * 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. * * In no event and under no legal theory, whether in tort (including negligence), * contract, or otherwise, unless required by applicable law (such as deliberate * and grossly negligent acts) or agreed to in writing, shall any Contributor be * liable for any damages, including any direct, indirect, special, incidental, * or consequential damages of any character arising as a result of this License or * out of the use or inability to use the software (including but not limited to damages * for loss of goodwill, work stoppage, computer failure or malfunction, or any and * all other commercial damages or losses), even if such Contributor has been advised * of the possibility of such damages. */ #include "TestingEnvironment.hpp" #include "gtest/gtest.h" using namespace Diligent; using namespace Diligent::Testing; namespace { // clang-format off TEXTURE_FORMAT TestFormats[] = { TEX_FORMAT_RGBA32_FLOAT, TEX_FORMAT_RGBA32_UINT, TEX_FORMAT_RGBA32_SINT, TEX_FORMAT_RGBA16_FLOAT, TEX_FORMAT_RGBA16_UINT, TEX_FORMAT_RGBA16_SINT, TEX_FORMAT_RGBA8_UNORM, TEX_FORMAT_RGBA8_SNORM, TEX_FORMAT_RGBA8_UINT, TEX_FORMAT_RGBA8_SINT, TEX_FORMAT_RG32_FLOAT, TEX_FORMAT_RG32_UINT, TEX_FORMAT_RG32_SINT, TEX_FORMAT_RG16_FLOAT, TEX_FORMAT_RG16_UINT, TEX_FORMAT_RG16_SINT, TEX_FORMAT_RG8_UNORM, TEX_FORMAT_RG8_SNORM, TEX_FORMAT_RG8_UINT, TEX_FORMAT_RG8_SINT, TEX_FORMAT_R32_FLOAT, TEX_FORMAT_R32_UINT, TEX_FORMAT_R32_SINT, TEX_FORMAT_R16_FLOAT, TEX_FORMAT_R16_UINT, TEX_FORMAT_R16_SINT, TEX_FORMAT_R8_UNORM, TEX_FORMAT_R8_SNORM, TEX_FORMAT_R8_UINT, TEX_FORMAT_R8_SINT }; // clang-format on TEST(CopyTexture, Texture2D) { auto* pEnv = TestingEnvironment::GetInstance(); auto* pDevice = pEnv->GetDevice(); auto* pContext = pEnv->GetDeviceContext(); TestingEnvironment::ScopedReleaseResources EnvironmentAutoReset; for (auto f = 0; f < _countof(TestFormats); ++f) { auto Format = TestFormats[f]; TextureDesc TexDesc; TexDesc.Type = RESOURCE_DIM_TEX_2D; TexDesc.Format = Format; TexDesc.Width = 128; TexDesc.Height = 128; TexDesc.BindFlags = BIND_SHADER_RESOURCE; TexDesc.MipLevels = 5; TexDesc.Usage = USAGE_DEFAULT; Diligent::RefCntAutoPtr<ITexture> pSrcTex, pDstTex; auto FmtAttribs = pDevice->GetTextureFormatInfo(Format); auto TexelSize = Uint32{FmtAttribs.ComponentSize} * Uint32{FmtAttribs.NumComponents}; std::vector<uint8_t> DummyData(size_t{TexDesc.Width} * size_t{TexDesc.Height} * size_t{TexelSize}); TextureData InitData; InitData.NumSubresources = TexDesc.MipLevels; std::vector<TextureSubResData> SubResData(InitData.NumSubresources); for (Uint32 mip = 0; mip < TexDesc.MipLevels; ++mip) { SubResData[mip] = TextureSubResData{DummyData.data(), (TexDesc.Width >> mip) * TexelSize, 0}; } InitData.pSubResources = SubResData.data(); pDevice->CreateTexture(TexDesc, &InitData, &pSrcTex); pDevice->CreateTexture(TexDesc, nullptr, &pDstTex); CopyTextureAttribs CopyAttribs; CopyAttribs.pSrcTexture = pSrcTex; CopyAttribs.SrcMipLevel = 2; CopyAttribs.pDstTexture = pDstTex; CopyAttribs.DstMipLevel = 1; CopyAttribs.DstX = 32; CopyAttribs.DstY = 16; CopyAttribs.DstZ = 0; CopyAttribs.SrcTextureTransitionMode = RESOURCE_STATE_TRANSITION_MODE_TRANSITION; CopyAttribs.DstTextureTransitionMode = RESOURCE_STATE_TRANSITION_MODE_TRANSITION; pContext->CopyTexture(CopyAttribs); Box SrcBox; SrcBox.MinX = 3; SrcBox.MaxX = 19; SrcBox.MinY = 1; SrcBox.MaxY = 32; CopyAttribs.pSrcBox = &SrcBox; CopyAttribs.SrcTextureTransitionMode = RESOURCE_STATE_TRANSITION_MODE_VERIFY; CopyAttribs.DstTextureTransitionMode = RESOURCE_STATE_TRANSITION_MODE_VERIFY; pContext->CopyTexture(CopyAttribs); pEnv->ReleaseResources(); } } TEST(CopyTexture, Texture2DArray) { auto* pEnv = TestingEnvironment::GetInstance(); auto* pDevice = pEnv->GetDevice(); auto* pContext = pEnv->GetDeviceContext(); TestingEnvironment::ScopedReleaseResources EnvironmentAutoReset; for (auto f = 0; f < _countof(TestFormats); ++f) { auto Format = TestFormats[f]; TextureDesc TexDesc; TexDesc.Type = RESOURCE_DIM_TEX_2D_ARRAY; TexDesc.Format = Format; TexDesc.Width = 128; TexDesc.Height = 128; TexDesc.BindFlags = BIND_SHADER_RESOURCE; TexDesc.MipLevels = 5; TexDesc.ArraySize = 8; TexDesc.Usage = USAGE_DEFAULT; Diligent::RefCntAutoPtr<ITexture> pSrcTex, pDstTex; auto FmtAttribs = pDevice->GetTextureFormatInfo(Format); auto TexelSize = Uint32{FmtAttribs.ComponentSize} * Uint32{FmtAttribs.NumComponents}; std::vector<uint8_t> DummyData(size_t{TexDesc.Width} * size_t{TexDesc.Height} * size_t{TexelSize}); TextureData InitData; InitData.NumSubresources = TexDesc.MipLevels * TexDesc.ArraySize; std::vector<TextureSubResData> SubResData(InitData.NumSubresources); Uint32 subres = 0; for (Uint32 slice = 0; slice < TexDesc.ArraySize; ++slice) { for (Uint32 mip = 0; mip < TexDesc.MipLevels; ++mip) { SubResData[subres++] = TextureSubResData{DummyData.data(), (TexDesc.Width >> mip) * TexelSize, 0}; } } VERIFY_EXPR(subres == InitData.NumSubresources); InitData.pSubResources = SubResData.data(); pDevice->CreateTexture(TexDesc, &InitData, &pSrcTex); pDevice->CreateTexture(TexDesc, nullptr, &pDstTex); CopyTextureAttribs CopyAttribs; CopyAttribs.pSrcTexture = pSrcTex; CopyAttribs.SrcMipLevel = 2; CopyAttribs.SrcSlice = 3; CopyAttribs.pDstTexture = pDstTex; CopyAttribs.DstMipLevel = 1; CopyAttribs.DstSlice = 6; CopyAttribs.DstX = 32; CopyAttribs.DstY = 16; CopyAttribs.DstZ = 0; CopyAttribs.SrcTextureTransitionMode = RESOURCE_STATE_TRANSITION_MODE_TRANSITION; CopyAttribs.DstTextureTransitionMode = RESOURCE_STATE_TRANSITION_MODE_TRANSITION; pContext->CopyTexture(CopyAttribs); Box SrcBox; SrcBox.MinX = 3; SrcBox.MaxX = 19; SrcBox.MinY = 1; SrcBox.MaxY = 32; CopyAttribs.DstSlice = 5; CopyAttribs.pSrcBox = &SrcBox; CopyAttribs.SrcTextureTransitionMode = RESOURCE_STATE_TRANSITION_MODE_VERIFY; CopyAttribs.DstTextureTransitionMode = RESOURCE_STATE_TRANSITION_MODE_VERIFY; pContext->CopyTexture(CopyAttribs); pEnv->ReleaseResources(); } } TEST(CopyTexture, Texture3D) { auto* pEnv = TestingEnvironment::GetInstance(); auto* pDevice = pEnv->GetDevice(); auto* pContext = pEnv->GetDeviceContext(); TestingEnvironment::ScopedReleaseResources EnvironmentAutoReset; for (auto f = 0; f < _countof(TestFormats); ++f) { auto Format = TestFormats[f]; TextureDesc TexDesc; TexDesc.Type = RESOURCE_DIM_TEX_3D; TexDesc.Format = Format; TexDesc.Width = 64; TexDesc.Height = 64; TexDesc.Depth = 16; TexDesc.BindFlags = BIND_SHADER_RESOURCE; TexDesc.MipLevels = 4; TexDesc.Usage = USAGE_DEFAULT; Diligent::RefCntAutoPtr<ITexture> pSrcTex, pDstTex; auto FmtAttribs = pDevice->GetTextureFormatInfo(Format); auto TexelSize = Uint32{FmtAttribs.ComponentSize} * Uint32{FmtAttribs.NumComponents}; std::vector<uint8_t> DummyData(size_t{TexDesc.Width} * size_t{TexDesc.Height} * size_t{TexDesc.Depth} * size_t{TexelSize}); TextureData InitData; InitData.NumSubresources = TexDesc.MipLevels; std::vector<TextureSubResData> SubResData(InitData.NumSubresources); for (Uint32 mip = 0; mip < TexDesc.MipLevels; ++mip) { SubResData[mip] = TextureSubResData{DummyData.data(), (TexDesc.Width >> mip) * TexelSize, (TexDesc.Width >> mip) * (TexDesc.Height >> mip) * TexelSize}; } InitData.pSubResources = SubResData.data(); pDevice->CreateTexture(TexDesc, &InitData, &pSrcTex); pDevice->CreateTexture(TexDesc, nullptr, &pDstTex); CopyTextureAttribs CopyAttribs; CopyAttribs.pSrcTexture = pSrcTex; CopyAttribs.SrcMipLevel = 2; CopyAttribs.pDstTexture = pDstTex; CopyAttribs.DstMipLevel = 1; CopyAttribs.DstX = 16; CopyAttribs.DstY = 8; CopyAttribs.DstZ = 0; CopyAttribs.SrcTextureTransitionMode = RESOURCE_STATE_TRANSITION_MODE_TRANSITION; CopyAttribs.DstTextureTransitionMode = RESOURCE_STATE_TRANSITION_MODE_TRANSITION; pContext->CopyTexture(CopyAttribs); Box SrcBox; SrcBox.MinX = 3; SrcBox.MaxX = 19; SrcBox.MinY = 1; SrcBox.MaxY = 32; CopyAttribs.pSrcBox = &SrcBox; CopyAttribs.SrcMipLevel = 1; CopyAttribs.DstMipLevel = 0; CopyAttribs.DstX = 32; CopyAttribs.DstY = 16; CopyAttribs.DstZ = 0; pContext->CopyTexture(CopyAttribs); pEnv->ReleaseResources(); } } } // namespace
38.261484
164
0.635574
[ "vector" ]
db1f54d621b5fa75955aa6b6e277fa60bbeff66b
3,997
cpp
C++
Uranus/src/Uranus/Scene/Scene.cpp
zaka7024/Uranus
948312ae5b39c92b4f0c415afc39ca2b4ae636f0
[ "Apache-2.0" ]
4
2020-12-11T13:32:06.000Z
2021-01-05T16:10:21.000Z
Uranus/src/Uranus/Scene/Scene.cpp
zaka7024/Uranus
948312ae5b39c92b4f0c415afc39ca2b4ae636f0
[ "Apache-2.0" ]
null
null
null
Uranus/src/Uranus/Scene/Scene.cpp
zaka7024/Uranus
948312ae5b39c92b4f0c415afc39ca2b4ae636f0
[ "Apache-2.0" ]
null
null
null
#include "urpch.h" #include "Scene.h" #include "Components.h" #include "Uranus/Renderer/Renderer2D.h" #include "Uranus/Audio/AudioPlayer.h" #include "Entity.h" #include <glm/glm.hpp> namespace Uranus { Scene::Scene() { } Scene::~Scene() { } void Scene::OnUpdateRuntime(Timestep ts) { // Update And Create Scripts _Registry.view<NativeScriptComponent>().each([=](auto entity, auto& nsc) { if(!nsc.Instance) { nsc.Instance = nsc.InstantiateScript(); nsc.Instance->_Entity = Entity{ entity, this }; nsc.Instance->OnCreate(); } nsc.Instance->OnUpdate(ts); }); // Render Camera* mainCamera = nullptr; glm::mat4 cameraTransform; auto view = _Registry.view<CameraComponent, TransformComponent>(); for (auto entity : view) { auto& [camera, transform] = view.get<CameraComponent, TransformComponent>(entity); if (camera.Primary) { mainCamera = &camera.Camera; cameraTransform = transform.GetTransform(); break; } } if (mainCamera) { Uranus::Renderer2D::BeginScene(*mainCamera, cameraTransform); auto group = _Registry.group<TransformComponent, SpriteRendererComponent>(); for (auto entity : group) { auto& [transfrom, sprite] = group.get<TransformComponent, SpriteRendererComponent>(entity); Uranus::Renderer2D::DrawSprite(transfrom.GetTransform(), sprite, (int)entity); } Uranus::Renderer2D::EndScene(); } } void Scene::OnEditorStart() { auto audioView = _Registry.view<AudioSourceComponent>(); for (auto entity : audioView) { auto& as = audioView.get<AudioSourceComponent>(entity); if (as.AutoPlay) { AudioPlayer::Play(as.SoundFile); } } } void Scene::OnUpdateEditor(Timestep ts, EditorCamera& camera) { Uranus::Renderer2D::BeginScene(camera); auto group = _Registry.group<TransformComponent, SpriteRendererComponent>(); for (auto entity : group) { auto& [transfrom, sprite] = group.get<TransformComponent, SpriteRendererComponent>(entity); Uranus::Renderer2D::DrawSprite(transfrom.GetTransform(), sprite, (int)entity); } Uranus::Renderer2D::EndScene(); } void Scene::OnViewportResize(uint32_t width, uint32_t height) { _ViewPortWidth = width; _ViewPortHeight = height; auto view = _Registry.view<CameraComponent>(); for (auto entity : view) { auto& cameraComponent = view.get<CameraComponent>(entity); if (!cameraComponent.FixedAspectRatio) { cameraComponent.Camera.SetViewportSize(width, height); } } } Entity Scene::GetPrimaryCameraEntity() { auto view = _Registry.view<CameraComponent>(); for (auto entity : view) { const auto& camera = view.get<CameraComponent>(entity); if (camera.Primary) return Entity{ entity, this }; } return {}; } Entity Scene::CreateEntity(const std::string& name) { Entity entity = { _Registry.create() , this }; entity.AddComponent<TransformComponent>(); auto& tagComponent = entity.AddComponent<TagComponent>(); tagComponent.Tag = name.empty() ? "Entity" : name; return entity; } void Scene::DeleteEntity(Entity entity) { _Registry.destroy(entity); } template<typename T> void Scene::OnComponenetAdded(Entity entity, T& component) { static_assert(false); } template<> void Scene::OnComponenetAdded<CameraComponent>(Entity entity, CameraComponent& component) { component.Camera.SetViewportSize(_ViewPortWidth, _ViewPortHeight); } template<> void Scene::OnComponenetAdded<TagComponent>(Entity entity, TagComponent& component) { } template<> void Scene::OnComponenetAdded<TransformComponent>(Entity entity, TransformComponent& component) { } template<> void Scene::OnComponenetAdded<SpriteRendererComponent>(Entity entity, SpriteRendererComponent& component) { } template<> void Scene::OnComponenetAdded<NativeScriptComponent>(Entity entity, NativeScriptComponent& component) { } template<> void Scene::OnComponenetAdded<AudioSourceComponent>(Entity entity, AudioSourceComponent& component) { } }
24.078313
106
0.714536
[ "render", "transform" ]
db22d0d7fbee3ff1c820451ef51d8ee50499e0a0
46,729
hpp
C++
WhateverGreen/kern_igfx.hpp
RV-ABZ/WhateverGreen
8ebb2716c6efa24ad8088166f1b4c768a2f73130
[ "BSD-3-Clause" ]
1
2020-08-02T02:11:30.000Z
2020-08-02T02:11:30.000Z
WhateverGreen/kern_igfx.hpp
RV-ABZ/WhateverGreen
8ebb2716c6efa24ad8088166f1b4c768a2f73130
[ "BSD-3-Clause" ]
null
null
null
WhateverGreen/kern_igfx.hpp
RV-ABZ/WhateverGreen
8ebb2716c6efa24ad8088166f1b4c768a2f73130
[ "BSD-3-Clause" ]
null
null
null
// // kern_igfx.hpp // WhateverGreen // // Copyright © 2018 vit9696. All rights reserved. // #ifndef kern_igfx_hpp #define kern_igfx_hpp #include "kern_fb.hpp" #include <Headers/kern_patcher.hpp> #include <Headers/kern_devinfo.hpp> #include <Headers/kern_cpu.hpp> #include <Library/LegacyIOService.h> class IGFX { public: void init(); void deinit(); /** * Property patching routine * * @param patcher KernelPatcher instance * @param info device info */ void processKernel(KernelPatcher &patcher, DeviceInfo *info); /** * Patch kext if needed and prepare other patches * * @param patcher KernelPatcher instance * @param index kinfo handle * @param address kinfo load address * @param size kinfo memory size * * @return true if patched anything */ bool processKext(KernelPatcher &patcher, size_t index, mach_vm_address_t address, size_t size); private: /** * Framebuffer patch flags */ union FramebufferPatchFlags { struct FramebufferPatchFlagBits { uint8_t FPFFramebufferId :1; uint8_t FPFModelNameAddr :1; uint8_t FPFMobile :1; uint8_t FPFPipeCount :1; uint8_t FPFPortCount :1; uint8_t FPFFBMemoryCount :1; uint8_t FPFStolenMemorySize :1; uint8_t FPFFramebufferMemorySize :1; uint8_t FPFUnifiedMemorySize :1; uint8_t FPFFramebufferCursorSize :1; // Haswell only uint8_t FPFFlags :1; uint8_t FPFBTTableOffsetIndexSlice :1; uint8_t FPFBTTableOffsetIndexNormal :1; uint8_t FPFBTTableOffsetIndexHDMI :1; uint8_t FPFCamelliaVersion :1; uint8_t FPFNumTransactionsThreshold :1; uint8_t FPFVideoTurboFreq :1; uint8_t FPFBTTArraySliceAddr :1; uint8_t FPFBTTArrayNormalAddr :1; uint8_t FPFBTTArrayHDMIAddr :1; uint8_t FPFSliceCount :1; uint8_t FPFEuCount :1; } bits; uint32_t value; }; /** * Connector patch flags */ union ConnectorPatchFlags { struct ConnectorPatchFlagBits { uint8_t CPFIndex :1; uint8_t CPFBusId :1; uint8_t CPFPipe :1; uint8_t CPFType :1; uint8_t CPFFlags :1; } bits; uint32_t value; }; /** * Framebuffer find / replace patch struct */ struct FramebufferPatch { uint32_t framebufferId; OSData *find; OSData *replace; size_t count; }; /** * Framebuffer patching flags */ FramebufferPatchFlags framebufferPatchFlags {}; /** * Connector patching flags */ ConnectorPatchFlags connectorPatchFlags[MaxFramebufferConnectorCount] {}; /** * Framebuffer hard-code patch */ FramebufferICLLP framebufferPatch {}; /** * Patch value for fCursorMemorySize in Haswell framebuffer * This member is not present in FramebufferCFL, hence its addition here. */ uint32_t fPatchCursorMemorySize; /** * Maximum find / replace patches */ static constexpr size_t MaxFramebufferPatchCount = 10; /** * Backlight registers */ static constexpr uint32_t BXT_BLC_PWM_CTL1 = 0xC8250; static constexpr uint32_t BXT_BLC_PWM_FREQ1 = 0xC8254; static constexpr uint32_t BXT_BLC_PWM_DUTY1 = 0xC8258; /** * Number of SNB frames in a framebuffer kext */ static constexpr size_t SandyPlatformNum = 9; /** * SNB frame ids in a framebuffer kext */ uint32_t sandyPlatformId[SandyPlatformNum] { 0x00010000, 0x00020000, 0x00030010, 0x00030030, 0x00040000, 0xFFFFFFFF, 0xFFFFFFFF, 0x00030020, 0x00050000 }; /** * Framebuffer find / replace patches */ FramebufferPatch framebufferPatches[MaxFramebufferPatchCount] {}; /** * Framebuffer list, imported from the framebuffer kext */ void *gPlatformInformationList {nullptr}; /** * Framebuffer list is in Sandy Bridge format */ bool gPlatformListIsSNB {false}; /** * Private self instance for callbacks */ static IGFX *callbackIGFX; /** * Current graphics kext used for modification */ KernelPatcher::KextInfo *currentGraphics {nullptr}; /** * Current framebuffer kext used for modification */ KernelPatcher::KextInfo *currentFramebuffer {nullptr}; /** * Current framebuffer optional kext used for modification */ KernelPatcher::KextInfo *currentFramebufferOpt {nullptr}; /** * Original PAVP session callback function used for PAVP command handling */ mach_vm_address_t orgPavpSessionCallback {}; /** * Original AppleIntelFramebufferController::ComputeLaneCount function used for DP lane count calculation */ mach_vm_address_t orgComputeLaneCount {}; /** * Original IOService::copyExistingServices function from the kernel */ mach_vm_address_t orgCopyExistingServices {}; /** * Original IntelAccelerator::start function */ mach_vm_address_t orgAcceleratorStart {}; /** * Original AppleIntelFramebufferController::getOSInformation function */ mach_vm_address_t orgGetOSInformation {}; /** * Original IGHardwareGuC::loadGuCBinary function */ mach_vm_address_t orgLoadGuCBinary {}; /** * Original IGScheduler4::loadFirmware function */ mach_vm_address_t orgLoadFirmware {}; /** * Original IGHardwareGuC::initSchedControl function */ mach_vm_address_t orgInitSchedControl {}; /** * Original IGSharedMappedBuffer::withOptions function */ mach_vm_address_t orgIgBufferWithOptions {}; /** * Original IGMappedBuffer::getGPUVirtualAddress function */ mach_vm_address_t orgIgBufferGetGpuVirtualAddress {}; /** * Original AppleIntelFramebufferController::hwRegsNeedUpdate function */ mach_vm_address_t orgHwRegsNeedUpdate {}; /** * Original IntelFBClientControl::doAttribute function */ mach_vm_address_t orgFBClientDoAttribute {}; /** * Original AppleIntelFramebuffer::getDisplayStatus function */ mach_vm_address_t orgGetDisplayStatus {}; /** * Original AppleIntelFramebufferController::ReadRegister32 function */ uint32_t (*orgCflReadRegister32)(void *, uint32_t) {nullptr}; uint32_t (*orgKblReadRegister32)(void *, uint32_t) {nullptr}; /** * Original AppleIntelFramebufferController::WriteRegister32 function */ void (*orgCflWriteRegister32)(void *, uint32_t, uint32_t) {nullptr}; void (*orgKblWriteRegister32)(void *, uint32_t, uint32_t) {nullptr}; /** * Original AppleIntelFramebufferController::ReadAUX function */ IOReturn (*orgReadAUX)(void *, void *, uint32_t, uint16_t, void *, void *) {nullptr}; /** * Original AppleIntelFramebufferController::ReadI2COverAUX function */ IOReturn (*orgReadI2COverAUX)(void *, IORegistryEntry *, void *, uint32_t, uint16_t, uint8_t *, bool, uint8_t) {nullptr}; /** * Original AppleIntelFramebufferController::WriteI2COverAUX function */ IOReturn (*orgWriteI2COverAUX)(void *, IORegistryEntry *, void *, uint32_t, uint16_t, uint8_t *, bool) {nullptr}; /** * Original AppleIntelFramebufferController::GetDPCDInfo function */ IOReturn (*orgGetDPCDInfo)(void *, IORegistryEntry *, void *); /** * Set to true if a black screen ComputeLaneCount patch is required */ bool blackScreenPatch {false}; /** * Coffee Lake backlight patch configuration options */ enum class CoffeeBacklightPatch { Auto = -1, On = 1, Off = 0 }; /** * Set to On if Coffee Lake backlight patch type required * - boot-arg igfxcflbklt=0/1 forcibly turns patch on or off (override) * - IGPU property enable-cfl-backlight-fix turns patch on * - laptop with CFL CPU and CFL IGPU drivers turns patch on */ CoffeeBacklightPatch cflBacklightPatch {CoffeeBacklightPatch::Off}; /** * Patch the maximum link rate in the DPCD buffer read from the built-in display */ bool maxLinkRatePatch {false}; /** * Set to true to enable LSPCON driver support */ bool supportLSPCON {false}; /** * Set to true to enable verbose output in I2C-over-AUX transactions */ bool verboseI2C {false}; /** * Set to true to fix the infinite loop issue when computing dividers for HDMI connections */ bool hdmiP0P1P2Patch {false}; /** * Set to true if PAVP code should be disabled */ bool pavpDisablePatch {false}; /** * Set to true if read descriptor patch should be enabled */ bool readDescriptorPatch {false}; /** * Set to true to disable Metal support */ bool forceOpenGL {false}; /** * Set to true to enable Metal support for offline rendering */ bool forceMetal {false}; /** * Set to true if Sandy Bridge Gen6Accelerator should be renamed */ bool moderniseAccelerator {false}; /** * Disable AGDC configuration */ bool disableAGDC {false}; /** * GuC firmware loading scheme */ enum FirmwareLoad { FW_AUTO = -1 /* Use as is for Apple, disable for others */, FW_DISABLE = 0, /* Use host scheduler without GuC */ FW_GENERIC = 1, /* Use reference scheduler with GuC */ FW_APPLE = 2, /* Use Apple GuC scheduler */ }; /** * Set to true to avoid incompatible GPU firmware loading */ FirmwareLoad fwLoadMode {FW_AUTO}; /** * Requires framebuffer modifications */ bool applyFramebufferPatch {false}; /** * Perform framebuffer dump to /AppleIntelFramebufferNUM */ bool dumpFramebufferToDisk {false}; /** * Trace framebuffer logic */ bool debugFramebuffer {false}; /** * Per-framebuffer helper script. */ struct FramebufferModifer { bool supported {false}; // compatible CPU bool legacy {false}; // legacy CPU (Skylake) bool enable {false}; // enable the patch bool customised {false}; // override default patch behaviour uint8_t fbs[sizeof(uint64_t)] {}; // framebuffers to force modeset for on override bool inList(IORegistryEntry* fb) { uint32_t idx; if (AppleIntelFramebufferExplorer::getIndex(fb, idx)) for (auto i : fbs) if (i == idx) return true; return false; } }; /** * Ensure each modeset is a complete modeset. */ FramebufferModifer forceCompleteModeset; /** * Ensure each display is online. */ FramebufferModifer forceOnlineDisplay; /** * Perform platform table dump to ioreg */ bool dumpPlatformTable {false}; /** * Perform automatic DP -> HDMI replacement */ bool hdmiAutopatch {false}; /** * Supports GuC firmware */ bool supportsGuCFirmware {false}; /** * Currently loading GuC firmware */ bool performingFirmwareLoad {false}; /** * Framebuffer address space start */ uint8_t *framebufferStart {nullptr}; /** * Framebuffer address space size */ size_t framebufferSize {0}; /** * Pointer to the original GuC firmware */ uint8_t *gKmGen9GuCBinary {nullptr}; /** * Pointer to the original GuC firmware signature */ uint8_t *signaturePointer {nullptr}; /** * Pointer to GuC firmware upload size assignment */ uint32_t *firmwareSizePointer {nullptr}; /** * Dummy firmware buffer to store unused old firmware in */ uint8_t *dummyFirmwareBuffer {nullptr}; /** * Actual firmware buffer we store our new firmware in */ uint8_t *realFirmwareBuffer {nullptr}; /** * Actual intercepted binary sizes */ uint32_t realBinarySize {}; /** * Store backlight level */ uint32_t backlightLevel {}; /** * Fallback user-requested backlight frequency in case 0 was initially written to the register. */ static constexpr uint32_t FallbackTargetBacklightFrequency {120000}; /** * User-requested backlight frequency obtained from BXT_BLC_PWM_FREQ1 at system start. * Can be specified via max-backlight-freq property. */ uint32_t targetBacklightFrequency {}; /** * User-requested pwm control value obtained from BXT_BLC_PWM_CTL1. */ uint32_t targetPwmControl {}; /** * Driver-requested backlight frequency obtained from BXT_BLC_PWM_FREQ1 write attempt at system start. */ uint32_t driverBacklightFrequency {}; /** * The default DPCD address */ static constexpr uint32_t DPCD_DEFAULT_ADDRESS = 0x0000; /** * The extended DPCD address */ static constexpr uint32_t DPCD_EXTENDED_ADDRESS = 0x2200; /** * Represents the first 16 fields of the receiver capabilities defined in DPCD * * Main Reference: * - DisplayPort Specification Version 1.2 * * Side Reference: * - struct intel_dp @ line 1073 in intel_drv.h (Linux 4.19 Kernel) * - DP_RECEIVER_CAP_SIZE @ line 964 in drm_dp_helper.h */ struct DPCDCap16 { // 16 bytes // DPCD Revision (DP Config Version) // Value: 0x10, 0x11, 0x12, 0x13, 0x14 uint8_t revision; // Maximum Link Rate // Value: 0x1E (HBR3) 8.1 Gbps // 0x14 (HBR2) 5.4 Gbps // 0x0C (3_24) 3.24 Gbps // 0x0A (HBR) 2.7 Gbps // 0x06 (RBR) 1.62 Gbps // Reference: 0x0C is used by Apple internally. uint8_t maxLinkRate; // Maximum Number of Lanes // Value: 0x1 (HBR2) // 0x2 (HBR) // 0x4 (RBR) // Side Notes: // (1) Bit 7 is used to indicate whether the link is capable of enhanced framing. // (2) Bit 6 is used to indicate whether TPS3 is supported. uint8_t maxLaneCount; // Maximum Downspread uint8_t maxDownspread; // Other fields omitted in this struct // Detailed information can be found in the specification uint8_t others[12]; }; /** * User-specified maximum link rate value in the DPCD buffer * * Default value is 0x14 (5.4 Gbps, HBR2) for 4K laptop display */ uint32_t maxLinkRate {0x14}; /** * ReadAUX wrapper to modify the maximum link rate value in the DPCD buffer */ static IOReturn wrapReadAUX(void *that, IORegistryEntry *framebuffer, uint32_t address, uint16_t length, void *buffer, void *displayPath); /** * See function definition for explanation */ static bool wrapHwRegsNeedUpdate(void *controller, IOService *framebuffer, void *displayPath, void *crtParams, void *detailedInfo); /** * Reflect the `AppleIntelFramebufferController::CRTCParams` struct * * @note Unlike the Intel Linux Graphics Driver, * - Apple does not transform the `pdiv`, `qdiv` and `kdiv` fields. * - Apple records the final central frequency divided by 15625. * @ref static void skl_wrpll_params_populate(params:afe_clock:central_freq:p0:p1:p2:) * @seealso https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/drivers/gpu/drm/i915/intel_dpll_mgr.c?h=v5.1.13#n1171 */ struct CRTCParams { /// Uninvestigated fields uint8_t uninvestigated[32]; /// P0 [`CRTCParams` field offset 0x20] uint32_t pdiv; /// P1 [`CRTCParams` field offset 0x24] uint32_t qdiv; /// P2 [`CRTCParams` field offset 0x28] uint32_t kdiv; /// Difference in Hz [`CRTCParams` field offset 0x2C] uint32_t fraction; /// Multiplier of 24 MHz [`CRTCParams` field offset 0x30] uint32_t multiplier; /// Central Frequency / 15625 [`CRTCParams` field offset 0x34] uint32_t cf15625; /// The rest fields are not of interest }; static_assert(offsetof(CRTCParams, pdiv) == 0x20, "Invalid pdiv offset, please check your compiler."); static_assert(sizeof(CRTCParams) == 56, "Invalid size of CRTCParams struct, please check your compiler."); /** * Represents the current context of probing dividers for HDMI connections */ struct ProbeContext { /// The current minimum deviation uint64_t minDeviation; /// The current chosen central frequency uint64_t central; /// The current DCO frequency uint64_t frequency; /// The current selected divider uint32_t divider; /// The corresponding pdiv value [P0] uint32_t pdiv; /// The corresponding qdiv value [P1] uint32_t qdiv; /// The corresponding kqiv value [P2] uint32_t kdiv; }; /** * The maximum positive deviation from the DCO central frequency * * @note DCO frequency must be within +1% of the DCO central frequency. * @warning This is a hardware requirement. * See "Intel Graphics Programmer Reference Manual for Kaby Lake platform" * Volume 12 Display, Page 134, Formula for HDMI and DVI DPLL Programming * @link https://01.org/sites/default/files/documentation/intel-gfx-prm-osrc-kbl-vol12-display.pdf * @note This value is appropriate for graphics on Skylake, Kaby Lake and Coffee Lake platforms. * @seealso Intel Linux Graphics Driver * https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/drivers/gpu/drm/i915/intel_dpll_mgr.c?h=v5.1.13#n1080 */ static constexpr uint64_t SKL_DCO_MAX_POS_DEVIATION = 100; /** * The maximum negative deviation from the DCO central frequency * * @note DCO frequency must be within -6% of the DCO central frequency. * @seealso See `SKL_DCO_MAX_POS_DEVIATION` above for details. */ static constexpr uint64_t SKL_DCO_MAX_NEG_DEVIATION = 600; /** * [Helper] Compute the final P0, P1, P2 values based on the current frequency divider * * @param context The current context for probing P0, P1 and P2. * @note Implementation adopted from the Intel Graphics Programmer Reference Manual; * Volume 12 Display, Page 135, Algorithm to Find HDMI and DVI DPLL Programming. * Volume 12 Display, Page 135, Pseudo-code for HDMI and DVI DPLL Programming. * @ref static void skl_wrpll_get_multipliers(p:p0:p1:p2:) * @seealso Intel Linux Graphics Driver * https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/drivers/gpu/drm/i915/intel_dpll_mgr.c?h=v5.1.13#n1112 */ static void populateP0P1P2(struct ProbeContext* context); /** * Compute dividers for a HDMI connection with the given pixel clock * * @param that The hidden implicit `this` pointer * @param pixelClock The pixel clock value (in Hz) used for the HDMI connection * @param displayPath The corresponding display path * @param parameters CRTC parameters populated on return * @return Never used by its caller, so this method might return void. * @note Method Signature: `AppleIntelFramebufferController::ComputeHdmiP0P1P2(pixelClock:displayPath:parameters:)` */ static int wrapComputeHdmiP0P1P2(void *that, uint32_t pixelClock, void *displayPath, void *parameters); /** * Explore the framebuffer structure in Apple's Intel graphics driver */ struct AppleIntelFramebufferExplorer { /** * [Convenient] Retrieve the framebuffer index * * @param framebuffer An `AppleIntelFramebuffer` instance * @param index The framebuffer index on return * @return `true` on success, `false` if the index does not exist. */ static bool getIndex(IORegistryEntry *framebuffer, uint32_t &index) { auto idxnum = OSDynamicCast(OSNumber, framebuffer->getProperty("IOFBDependentIndex")); if (idxnum != nullptr) { index = idxnum->unsigned32BitValue(); return true; } return false; } }; /** * Represents the register layouts of DisplayPort++ adapter at I2C address 0x40 * * Specific to LSPCON DisplayPort 1.2 to HDMI 2.0 Adapter */ struct DisplayPortDualModeAdapterInfo { // first 128 bytes /// [0x00] HDMI ID /// /// Fixed Value: "DP-HDMI ADAPTOR\x04" uint8_t hdmiID[16]; /// [0x10] Adapter ID /// /// Bit Masks: /// - isType2 = 0xA0 /// - hasDPCD = 0x08 /// /// Sample Values: 0xA8 = Type 2 Adapter with DPCD uint8_t adapterID; /// [0x11] IEEE OUI /// /// Sample Value: 0x001CF8 [Parade] /// Reference: http://standards-oui.ieee.org/oui.txt uint8_t oui[3]; /// [0x14] Device ID /// /// Sample Value: 0x505331373530 = "PS1750" uint8_t deviceID[6]; /// [0x1A] Hardware Revision Number /// /// Sample Value: 0xB2 (B2 version) uint8_t revision; /// [0x1B] Firmware Major Revision uint8_t firmwareMajor; /// [0x1C] Firmware Minor Revision uint8_t firmwareMinor; /// [0x1D] Maximum TMDS Clock uint8_t maxTMDSClock; /// [0x1E] I2C Speed Capability uint8_t i2cSpeedCap; /// [0x1F] Unused/Reserved Field??? uint8_t reserved0; /// [0x20] TMDS Output Buffer State /// /// Bit Masks: /// - Disabled = 0x01 /// /// Sample Value: /// 0x00 = Enabled uint8_t tmdsOutputBufferState; /// [0x21] HDMI PIN CONTROL uint8_t hdmiPinCtrl; /// [0x22] I2C Speed Control uint8_t i2cSpeedCtrl; /// [0x23 - 0x3F] Unused/Reserved Fields uint8_t reserved1[29]; /// [0x40] [W] Set the new LSPCON mode uint8_t lspconChangeMode; /// [0x41] [R] Get the current LSPCON mode /// /// Bit Masks: /// - PCON = 0x01 /// /// Sample Value: /// 0x00 = LS /// 0x01 = PCON uint8_t lspconCurrentMode; /// [0x42 - 0x7F] Rest Unused/Reserved Fields uint8_t reserved2[62]; }; /** * Represents the onboard Level Shifter and Protocol Converter */ class LSPCON { public: /** * Represents all possible adapter modes */ enum class Mode: uint32_t { /// Level Shifter Mode (DP++ to HDMI 1.4) LevelShifter = 0x00, /// Protocol Converter Mode (DP++ to HDMI 2.0) ProtocolConverter = 0x01, /// Invalid Mode Invalid }; /** * [Mode Helper] Parse the adapter mode from the raw register value * * @param mode A raw register value read from the adapter. * @return The corresponding adapter mode on success, `invalid` otherwise. */ static inline Mode parseMode(uint8_t mode) { switch (mode & DP_DUAL_MODE_LSPCON_MODE_PCON) { case DP_DUAL_MODE_LSPCON_MODE_LS: return Mode::LevelShifter; case DP_DUAL_MODE_LSPCON_MODE_PCON: return Mode::ProtocolConverter; default: return Mode::Invalid; } } /** * [Mode Helper] Get the raw value of the given adapter mode * * @param mode A valid adapter mode * @return The corresponding register value on success. * If the given mode is `Invalid`, the raw value of `LS` mode will be returned. */ static inline uint8_t getModeValue(Mode mode) { switch (mode) { case Mode::LevelShifter: return DP_DUAL_MODE_LSPCON_MODE_LS; case Mode::ProtocolConverter: return DP_DUAL_MODE_LSPCON_MODE_PCON; default: return DP_DUAL_MODE_LSPCON_MODE_LS; } } /** * [Mode Helper] Get the string representation of the adapter mode */ static inline const char *getModeString(Mode mode) { switch (mode) { case Mode::LevelShifter: return "Level Shifter (DP++ to HDMI 1.4)"; case Mode::ProtocolConverter: return "Protocol Converter (DP++ to HDMI 2.0)"; default: return "Invalid"; } } /** * [Convenient] Create the LSPCON driver for the given framebuffer * * @param controller The opaque `AppleIntelFramebufferController` instance * @param framebuffer The framebuffer that owns this LSPCON chip * @param displayPath The corresponding opaque display path instance * @return A driver instance on success, `nullptr` otherwise. * @note This convenient initializer returns `nullptr` if it could not retrieve the framebuffer index. */ static LSPCON *create(void *controller, IORegistryEntry *framebuffer, void *displayPath) { // Guard: Framebuffer index should exist uint32_t index; if (!AppleIntelFramebufferExplorer::getIndex(framebuffer, index)) return nullptr; // Call the private constructor return new LSPCON(controller, framebuffer, displayPath, index); } /** * [Convenient] Destroy the LSPCON driver safely * * @param instance A nullable LSPCON driver instance */ static void deleter(LSPCON *instance NONNULL) { delete instance; } /** * Probe the onboard LSPCON chip * * @return `kIOReturnSuccess` on success, errors otherwise */ IOReturn probe(); /** * Get the current adapter mode * * @param mode The current adapter mode on return. * @return `kIOReturnSuccess` on success, errors otherwise. */ IOReturn getMode(Mode *mode); /** * Change the adapter mode * * @param newMode The new adapter mode * @return `kIOReturnSuccess` on success, errors otherwise. * @note This method will not return until `newMode` is effective. * @warning This method will return the result of the last attempt if timed out on waiting for `newMode` to be effective. */ IOReturn setMode(Mode newMode); /** * Change the adapter mode if necessary * * @param newMode The new adapter mode * @return `kIOReturnSuccess` on success, errors otherwise. * @note This method is a wrapper of `setMode` and will only set the new mode if `newMode` is not currently effective. * @seealso `setMode(newMode:)` */ IOReturn setModeIfNecessary(Mode newMode); /** * Wake up the native DisplayPort AUX channel for this adapter * * @return `kIOReturnSuccess` on success, other errors otherwise. */ IOReturn wakeUpNativeAUX(); /** * Return `true` if the adapter is running in the given mode * * @param mode The expected mode; one of `LS` and `PCON` */ inline bool isRunningInMode(Mode mode) { Mode currentMode; if (getMode(&currentMode) != kIOReturnSuccess) { DBGLOG("igfx", "LSPCON::isRunningInMode() Error: [FB%d] Failed to get the current adapter mode.", index); return false; } return mode == currentMode; } private: /// The 7-bit I2C slave address of the DisplayPort dual mode adapter static constexpr uint32_t DP_DUAL_MODE_ADAPTER_I2C_ADDR = 0x40; /// Register address to change the adapter mode static constexpr uint8_t DP_DUAL_MODE_LSPCON_CHANGE_MODE = 0x40; /// Register address to read the current adapter mode static constexpr uint8_t DP_DUAL_MODE_LSPCON_CURRENT_MODE = 0x41; /// Register value when the adapter is in **Level Shifter** mode static constexpr uint8_t DP_DUAL_MODE_LSPCON_MODE_LS = 0x00; /// Register value when the adapter is in **Protocol Converter** mode static constexpr uint8_t DP_DUAL_MODE_LSPCON_MODE_PCON = 0x01; /// IEEE OUI of Parade Technologies static constexpr uint32_t DP_DUAL_MODE_LSPCON_VENDOR_PARADE = 0x001CF8; /// IEEE OUI of MegaChips Corporation static constexpr uint32_t DP_DUAL_MODE_LSPCON_VENDOR_MEGACHIPS = 0x0060AD; /// Bit mask indicating that the DisplayPort dual mode adapter is of type 2 static constexpr uint8_t DP_DUAL_MODE_TYPE_IS_TYPE2 = 0xA0; /// Bit mask indicating that the DisplayPort dual mode adapter has DPCD (LSPCON case) static constexpr uint8_t DP_DUAL_MODE_TYPE_HAS_DPCD = 0x08; /** * Represents all possible chip vendors */ enum class Vendor { MegaChips, Parade, Unknown }; /// The opaque framebuffer controller instance void *controller; /// The framebuffer that owns this LSPCON chip IORegistryEntry *framebuffer; /// The corresponding opaque display path instance void *displayPath; /// The framebuffer index (for debugging purposes) uint32_t index; /** * Initialize the LSPCON chip for the given framebuffer * * @param controller The opaque `AppleIntelFramebufferController` instance * @param framebuffer The framebuffer that owns this LSPCON chip * @param displayPath The corresponding opaque display path instance * @param index The framebuffer index (only for debugging purposes) * @seealso LSPCON::create(controller:framebuffer:displayPath:) to create the driver instance. */ LSPCON(void *controller, IORegistryEntry *framebuffer, void *displayPath, uint32_t index) { this->controller = controller; this->framebuffer = framebuffer; this->displayPath = displayPath; this->index = index; } /** * [Vendor Helper] Parse the adapter vendor from the adapter info * * @param info A non-null DP++ adapter info instance * @return The vendor on success, `Unknown` otherwise. */ static inline Vendor parseVendor(DisplayPortDualModeAdapterInfo *info) { uint32_t oui = info->oui[0] << 16 | info->oui[1] << 8 | info->oui[2]; switch (oui) { case DP_DUAL_MODE_LSPCON_VENDOR_PARADE: return Vendor::Parade; case DP_DUAL_MODE_LSPCON_VENDOR_MEGACHIPS: return Vendor::MegaChips; default: return Vendor::Unknown; } } /** * [Vendor Helper] Get the string representation of the adapter vendor */ static inline const char *getVendorString(Vendor vendor) { switch (vendor) { case Vendor::Parade: return "Parade"; case Vendor::MegaChips: return "MegaChips"; default: return "Unknown"; } } /** * [DP++ Helper] Check whether this is a HDMI adapter based on the adapter info * * @param info A non-null DP++ adapter info instance * @return `true` if this is a HDMI adapter, `false` otherwise. */ static inline bool isHDMIAdapter(DisplayPortDualModeAdapterInfo *info) { return memcmp(info->hdmiID, "DP-HDMI ADAPTOR\x04", 16) == 0; } /** * [DP++ Helper] Check whether this is a LSPCON adapter based on the adapter info * * @param info A non-null DP++ adapter info instance * @return `true` if this is a LSPCON DP-HDMI adapter, `false` otherwise. */ static inline bool isLSPCONAdapter(DisplayPortDualModeAdapterInfo *info) { // Guard: Check whether it is a DP to HDMI adapter if (!isHDMIAdapter(info)) return false; // Onboard LSPCON adapter must be of type 2 and have DPCD info return info->adapterID == (DP_DUAL_MODE_TYPE_IS_TYPE2 | DP_DUAL_MODE_TYPE_HAS_DPCD); } }; /** * Represents the LSPCON chip info for a framebuffer */ struct FramebufferLSPCON { /** * Indicate whether this framebuffer has an onboard LSPCON chip * * @note This value will be read from the IGPU property `framebuffer-conX-has-lspcon`. * @warning If not specified, assuming no onboard LSPCON chip for this framebuffer. */ uint32_t hasLSPCON {0}; /** * User preferred LSPCON adapter mode * * @note This value will be read from the IGPU property `framebuffer-conX-preferred-lspcon-mode`. * @warning If not specified, assuming `PCON` mode is preferred. * @warning If invalid mode value found, assuming `PCON` mode */ LSPCON::Mode preferredMode {LSPCON::Mode::ProtocolConverter}; /** * The corresponding LSPCON driver; `NULL` if no onboard chip */ LSPCON *lspcon {nullptr}; }; /** * User-defined LSPCON chip info for all possible framebuffers */ FramebufferLSPCON lspcons[MaxFramebufferConnectorCount]; /// MARK:- Manage user-defined LSPCON chip info for all framebuffers /** * Setup the LSPCON driver for the given framebuffer * * @param that The opaque framebuffer controller instance * @param framebuffer The framebuffer that owns this LSPCON chip * @param displayPath The corresponding opaque display path instance * @note This method will update fields in `lspcons` accordingly on success. */ static void framebufferSetupLSPCON(void *that, IORegistryEntry *framebuffer, void *displayPath); /** * [Convenient] Check whether the given framebuffer has an onboard LSPCON chip * * @param index A **valid** framebuffer index; Must be less than `MaxFramebufferConnectorCount` * @return `true` if the framebuffer has an onboard LSPCON chip, `false` otherwise. */ static inline bool framebufferHasLSPCON(uint32_t index) { return callbackIGFX->lspcons[index].hasLSPCON; } /** * [Convenient] Check whether the given framebuffer already has LSPCON driver initialized * * @param index A **valid** framebuffer index; Must be less than `MaxFramebufferConnectorCount` * @return `true` if the LSPCON driver has already been initialized for this framebuffer, `false` otherwise. */ static inline bool framebufferHasLSPCONInitialized(uint32_t index) { return callbackIGFX->lspcons[index].lspcon != nullptr; } /** * [Convenient] Get the non-null LSPCON driver associated with the given framebuffer * * @param index A **valid** framebuffer index; Must be less than `MaxFramebufferConnectorCount` * @return The LSPCON driver instance. */ static inline LSPCON *framebufferGetLSPCON(uint32_t index) { return callbackIGFX->lspcons[index].lspcon; } /** * [Convenient] Set the non-null LSPCON driver for the given framebuffer * * @param index A **valid** framebuffer index; Must be less than `MaxFramebufferConnectorCount` * @param lspcon A non-null LSPCON driver instance associated with the given framebuffer */ static inline void framebufferSetLSPCON(uint32_t index, LSPCON *lspcon) { callbackIGFX->lspcons[index].lspcon = lspcon; } /** * [Convenient] Get the preferred LSPCON mode for the given framebuffer * * @param index A **valid** framebuffer index; Must be less than `MaxFramebufferConnectorCount` * @return The preferred adapter mode. */ static inline LSPCON::Mode framebufferLSPCONGetPreferredMode(uint32_t index) { return callbackIGFX->lspcons[index].preferredMode; } /// MARK:- I2C-over-AUX Transaction APIs /** * [Advanced] Reposition the offset for an I2C-over-AUX access * * @param that The hidden implicit `this` pointer * @param framebuffer A framebuffer instance * @param displayPath A display path instance * @param address The 7-bit address of an I2C slave * @param offset The address of the next register to access * @param flags A flag reserved by Apple. Currently always 0. * @return `kIOReturnSuccess` on success, other values otherwise. * @note Method Signature: `AppleIntelFramebufferController::advSeekI2COverAUX(framebuffer:displayPath:address:offset:flags:)` * @note Built upon Apple's original `ReadI2COverAUX()` and `WriteI2COverAUX()` APIs. */ static IOReturn advSeekI2COverAUX(void *that, IORegistryEntry *framebuffer, void *displayPath, uint32_t address, uint32_t offset, uint8_t flags); /** * [Advanced] Read from an I2C slave via the AUX channel * * @param that The hidden implicit `this` pointer * @param framebuffer A framebuffer instance * @param displayPath A display path instance * @param address The 7-bit address of an I2C slave * @param offset Address of the first register to read from * @param length The number of bytes requested to read starting from `offset` * @param buffer A non-null buffer to store the bytes * @param flags A flag reserved by Apple. Currently always 0. * @return `kIOReturnSuccess` on success, other values otherwise. * @note Method Signature: `AppleIntelFramebufferController::advReadI2COverAUX(framebuffer:displayPath:address:offset:length:buffer:flags:)` * @note Built upon Apple's original `ReadI2COverAUX()` and `WriteI2COverAUX()` APIs. */ static IOReturn advReadI2COverAUX(void *that, IORegistryEntry *framebuffer, void *displayPath, uint32_t address, uint32_t offset, uint16_t length, uint8_t *buffer, uint8_t flags); /** * [Advanced] Write to an I2C slave via the AUX channel * * @param that The hidden implicit `this` pointer * @param framebuffer A framebuffer instance * @param displayPath A display path instance * @param address The 7-bit address of an I2C slave * @param offset Address of the first register to write to * @param length The number of bytes requested to write starting from `offset` * @param buffer A non-null buffer containing the bytes to write * @param flags A flag reserved by Apple. Currently always 0. * @return `kIOReturnSuccess` on success, other values otherwise. * @note Method Signature: `AppleIntelFramebufferController::advWriteI2COverAUX(framebuffer:displayPath:address:offset:length:buffer:flags:)` * @note Built upon Apple's original `ReadI2COverAUX()` and `WriteI2COverAUX()` APIs. */ static IOReturn advWriteI2COverAUX(void *that, IORegistryEntry *framebuffer, void *displayPath, uint32_t address, uint32_t offset, uint16_t length, uint8_t *buffer, uint8_t flags); /** * [Basic] Read from an I2C slave via the AUX channel * * @param that The hidden implicit `this` pointer * @param framebuffer A framebuffer instance * @param displayPath A display path instance * @param address The 7-bit address of an I2C slave * @param length The number of bytes requested to read and must be <= 16 (See below) * @param buffer A buffer to store the read bytes (See below) * @param intermediate Set `true` if this is an intermediate read (See below) * @param flags A flag reserved by Apple; currently always 0. * @return `kIOReturnSuccess` on success, other values otherwise. * @note The number of bytes requested to read cannot be greater than 16, because the burst data size in * a single AUX transaction is 20 bytes, in which the first 4 bytes are used for the message header. * @note Passing a `0` buffer length and a `NULL` buffer will start or stop an I2C transaction. * @note When `intermediate` is `true`, the Middle-of-Transaction (MOT, bit 30 in the header) bit will be set to 1. * (See Section 2.7.5.1 I2C-over-AUX Request Transaction Command in VESA DisplayPort Specification 1.2) * @note Similar logic could be found at `intel_dp.c` (Intel Linux Graphics Driver; Linux Kernel) * static ssize_t intel_dp_aux_transfer(struct drm_dp_aux* aux, struct drm_dp_aux_msg* msg) * @note Method Signature: `AppleIntelFramebufferController::ReadI2COverAUX(framebuffer:displayPath:address:length:buffer:intermediate:flags:)` * @note This is a wrapper for Apple's original `AppleIntelFramebufferController::ReadI2COverAUX()` method. * @seealso See the actual implementation extracted from my reverse engineering research for detailed information. * @ref TODO: Add the link to the blog post. [Working In Progress] */ static IOReturn wrapReadI2COverAUX(void *that, IORegistryEntry *framebuffer, void *displayPath, uint32_t address, uint16_t length, uint8_t *buffer, bool intermediate, uint8_t flags); /** * [Basic] Write to an I2C adapter via the AUX channel * * @param that The hidden implicit `this` pointer * @param framebuffer A framebuffer instance * @param displayPath A display path instance * @param address The 7-bit address of an I2C slave * @param length The number of bytes requested to write and must be <= 16 (See below) * @param buffer A buffer that stores the bytes to write (See below) * @param intermediate Set `true` if this is an intermediate write (See below) * @param flags A flag reserved by Apple; currently always 0. * @return `kIOReturnSuccess` on success, other values otherwise. * @note The number of bytes requested to read cannot be greater than 16, because the burst data size in * a single AUX transaction is 20 bytes, in which the first 4 bytes are used for the message header. * @note Passing a `0` buffer length and a `NULL` buffer will start or stop an I2C transaction. * @note When `intermediate` is `true`, the Middle-of-Transaction (MOT, bit 30 in the header) bit will be set to 1. * (See Section 2.7.5.1 I2C-over-AUX Request Transaction Command in VESA DisplayPort Specification 1.2) * @note Similar logic could be found at `intel_dp.c` (Intel Linux Graphics Driver; Linux Kernel) * static ssize_t intel_dp_aux_transfer(struct drm_dp_aux* aux, struct drm_dp_aux_msg* msg) * @note Method Signature: `AppleIntelFramebufferController::WriteI2COverAUX(framebuffer:displayPath:address:length:buffer:intermediate:)` * @note This is a wrapper for Apple's original `AppleIntelFramebufferController::WriteI2COverAUX()` method. * @seealso See the actual implementation extracted from my reverse engineering research for detailed information. * @ref TODO: Add the link to the blog post. [Working In Progress] */ static IOReturn wrapWriteI2COverAUX(void *that, IORegistryEntry *framebuffer, void *displayPath, uint32_t address, uint16_t length, uint8_t *buffer, bool intermediate); /** * [Wrapper] Retrieve the DPCD info for a given framebuffer port * * @param that The hidden implicit `this` pointer * @param framebuffer A framebuffer instance * @param displayPath A display path instance * @return `kIOReturnSuccess` on success, other values otherwise. * @note This is a wrapper for Apple's original `AppleIntelFramebufferController::GetDPCDInfo()` method. * Used to inject code to initialize the driver for the onboard LSPCON chip. */ static IOReturn wrapGetDPCDInfo(void *that, IORegistryEntry *framebuffer, void *displayPath); /** * PAVP session callback wrapper used to prevent freezes on incompatible PAVP certificates */ static IOReturn wrapPavpSessionCallback(void *intelAccelerator, int32_t sessionCommand, uint32_t sessionAppId, uint32_t *a4, bool flag); /** * Global page table read wrapper for Kaby Lake. */ static bool globalPageTableRead(void *hardwareGlobalPageTable, uint64_t a1, uint64_t &a2, uint64_t &a3); /** * DP ComputeLaneCount wrapper to report success on non-DP screens to avoid black screen */ static bool wrapComputeLaneCount(void *that, void *timing, uint32_t bpp, int32_t availableLanes, int32_t *laneCount); /** * DP ComputeLaneCount wrapper to report success on non-DP screens to avoid black screen (10.14.1+ KBL/CFL version) */ static bool wrapComputeLaneCountNouveau(void *that, void *timing, int32_t availableLanes, int32_t *laneCount); /** * copyExistingServices wrapper used to rename Gen6Accelerator from userspace calls */ static OSObject *wrapCopyExistingServices(OSDictionary *matching, IOOptionBits inState, IOOptionBits options); /** * IntelAccelerator::start wrapper to support vesa mode, force OpenGL, prevent fw loading, etc. */ static bool wrapAcceleratorStart(IOService *that, IOService *provider); /** * Wrapped AppleIntelFramebufferController::WriteRegister32 function */ static void wrapCflWriteRegister32(void *that, uint32_t reg, uint32_t value); static void wrapKblWriteRegister32(void *that, uint32_t reg, uint32_t value); /** * AppleIntelFramebufferController::getOSInformation wrapper to patch framebuffer data */ static bool wrapGetOSInformation(void *that); /** * IGHardwareGuC::loadGuCBinary wrapper to feed updated (compatible GuC) */ static bool wrapLoadGuCBinary(void *that, bool flag); /** * Actual firmware loader * * @param that IGScheduler4 instance * * @return true on success */ static bool wrapLoadFirmware(IOService *that); /** * Handle sleep event * * @param that IGScheduler4 instance */ static void wrapSystemWillSleep(IOService *that); /** * Handle wake event * * @param that IGScheduler4 instance */ static void wrapSystemDidWake(IOService *that); /** * IGHardwareGuC::initSchedControl wrapper to avoid incompatibilities during GuC load */ static bool wrapInitSchedControl(void *that, void *ctrl); /** * IGSharedMappedBuffer::withOptions wrapper to prepare for GuC firmware loading */ static void *wrapIgBufferWithOptions(void *accelTask, unsigned long size, unsigned int type, unsigned int flags); /** * IGMappedBuffer::getGPUVirtualAddress wrapper to trick GuC firmware virtual addresses */ static uint64_t wrapIgBufferGetGpuVirtualAddress(void *that); /** * IntelFBClientControl::doAttribute wrapper to filter attributes like AGDC. */ static IOReturn wrapFBClientDoAttribute(void *fbclient, uint32_t attribute, unsigned long *unk1, unsigned long unk2, unsigned long *unk3, unsigned long *unk4, void *externalMethodArguments); /** * AppleIntelFramebuffer::getDisplayStatus to force display status on configured screens. */ static uint32_t wrapGetDisplayStatus(IOService *framebuffer, void *displayPath); /** * Load GuC-specific patches and hooks * * @param patcher KernelPatcher instance * @param index kinfo handle for graphics driver * @param address kinfo load address * @param size kinfo memory size */ void loadIGScheduler4Patches(KernelPatcher &patcher, size_t index, mach_vm_address_t address, size_t size); /** * Enable framebuffer debugging * * @param patcher KernelPatcher instance * @param index kinfo handle * @param address kinfo load address * @param size kinfo memory size */ void loadFramebufferDebug(KernelPatcher &patcher, size_t index, mach_vm_address_t address, size_t size); /** * Load user-specified arguments from IGPU device * * @param igpu IGPU device handle * @param currentFramebuffer current framebuffer id number * * @return true if there is anything to do */ bool loadPatchesFromDevice(IORegistryEntry *igpu, uint32_t currentFramebuffer); /** * Find the framebuffer id in data * * @param framebufferId Framebuffer id to search * @param startingAddress Start address of data to search * @param maxSize Maximum size of data to search * * @return pointer to address in data or nullptr */ uint8_t *findFramebufferId(uint32_t framebufferId, uint8_t *startingAddress, size_t maxSize); #ifdef DEBUG /** * Calculate total size of platform table list, including termination entry (FFFFFFFF 00000000) * * @param maxSize Maximum size of data to search * * @return size of data */ size_t calculatePlatformListSize(size_t maxSize); /** * Write platform table data to ioreg * * @param subKeyName ioreg subkey (under IOService://IOResources/WhateverGreen) */ void writePlatformListData(const char *subKeyName); #endif /** * Patch data without changing kernel protection * * @param patch KernelPatcher instance * @param startingAddress Start address of data to search * @param maxSize Maximum size of data to search * * @return true if patched anything */ bool applyPatch(const KernelPatcher::LookupPatch &patch, uint8_t *startingAddress, size_t maxSize); /** * Patch platformInformationList * * @param framebufferId Framebuffer id * @param platformInformationList PlatformInformationList pointer * * @return true if patched anything */ template <typename T> bool applyPlatformInformationListPatch(uint32_t framebufferId, T *platformInformationList); /** * Extended patching called from applyPlatformInformationListPatch * * @param frame pointer to Framebuffer data * */ template <typename T> void applyPlatformInformationPatchEx(T* frame); /** * Apply framebuffer patches */ void applyFramebufferPatches(); /** * Patch platformInformationList with DP to HDMI connector type replacements * * @param framebufferId Framebuffer id * @param platformInformationList PlatformInformationList pointer * * @return true if patched anything */ template <typename T> bool applyDPtoHDMIPatch(uint32_t framebufferId, T *platformInformationList); /** * Apply DP to HDMI automatic connector type changes */ void applyHdmiAutopatch(); }; #endif /* kern_igfx_hpp */
31.403898
191
0.710415
[ "transform" ]
db2d133e3f32a4d7e2b5cfb6f08f03964ccaf621
2,440
cpp
C++
lucida/djinntonic/dig/test/DIGClient.cpp
extremenelson/sirius
0bad428bb763fe404d01db5d9e08ee33a8f3776c
[ "BSD-3-Clause" ]
1,808
2015-12-23T09:38:57.000Z
2022-03-24T05:55:03.000Z
lucida/djinntonic/dig/test/DIGClient.cpp
extremenelson/sirius
0bad428bb763fe404d01db5d9e08ee33a8f3776c
[ "BSD-3-Clause" ]
164
2015-12-22T17:32:16.000Z
2022-01-30T16:19:28.000Z
lucida/djinntonic/dig/test/DIGClient.cpp
mrinformatics/lucida1604
f17fba20be9765c3464437f40e97278bba29b9d5
[ "BSD-3-Clause" ]
554
2015-12-23T11:29:34.000Z
2022-02-08T05:31:49.000Z
#include <cstdlib> #include <iostream> #include <unistd.h> #include <gflags/gflags.h> #include <iostream> #include <vector> #include <fstream> #include <sstream> #include <iomanip> #include <string> #include <folly/futures/Future.h> #include "gen-cpp2/LucidaService.h" #include <thrift/lib/cpp2/async/HeaderClientChannel.h> #include "boost/filesystem/operations.hpp" #include "boost/filesystem/path.hpp" #include <folly/init/Init.h> #include "../Parser.h" using namespace folly; using namespace apache::thrift; using namespace apache::thrift::async; using namespace cpp2; using namespace std; namespace fs = boost::filesystem; DEFINE_string(hostname, "127.0.0.1", "Hostname of the server (default: localhost)"); string getImageData(const string &image_path) { ifstream fin(image_path.c_str(), ios::binary); ostringstream ostrm; ostrm << fin.rdbuf(); string image(ostrm.str()); if (!fin) { cerr << "Could not open the file " << image_path << endl; exit(1); } return image; } int main(int argc, char* argv[]){ folly::init(&argc, &argv); EventBase event_base; Properties props; props.Read("../../../config.properties"); string portVal; int port; if (!props.GetValue("DIG_PORT", portVal)) { cout << "DIG port not defined" << endl; return -1; } else { port = atoi(portVal.c_str()); } std::shared_ptr<apache::thrift::async::TAsyncSocket> socket_t( TAsyncSocket::newSocket(&event_base, FLAGS_hostname, port)); LucidaServiceAsyncClient client( std::unique_ptr<HeaderClientChannel, DelayedDestruction::Destructor>( new HeaderClientChannel(socket_t))); int num_tests = 3; for (int i=0; i < num_tests; ++i){ string image = getImageData("test" + to_string(i) + ".jpg"); // Create a QuerySpec. QuerySpec query_spec; // Create a QueryInput for the query image and add it to the QuerySpec. QueryInput query_input; query_input.type = "image"; query_input.data.push_back(image); query_input.tags.push_back("localhost"); query_input.tags.push_back(to_string(port)); query_input.tags.push_back("0"); query_spec.content.push_back(query_input); cout << i << " Sending request to DIG at " << port << endl; auto result = client.future_infer("Johann", std::move(query_spec)).then( [=](folly::Try<std::string>&& t) mutable { cout << i << " result: " << t.value() << endl; return t.value(); }); } cout << "Going to loop" << endl; event_base.loop(); return 0; }
27.727273
74
0.696311
[ "vector" ]