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
81f72731a4816adcc47f73fe3887b930270aa0b8
3,675
cpp
C++
mr.Sadman/Classes/GameAct/Objects/Physical/Pendulum/Pendulum.cpp
1pkg/dump
0ee579cb6a97ae64d5367cc624b2407d7d4b1c7b
[ "MIT" ]
null
null
null
mr.Sadman/Classes/GameAct/Objects/Physical/Pendulum/Pendulum.cpp
1pkg/dump
0ee579cb6a97ae64d5367cc624b2407d7d4b1c7b
[ "MIT" ]
3
2020-12-11T10:01:27.000Z
2022-02-13T22:12:05.000Z
mr.Sadman/Classes/GameAct/Objects/Physical/Pendulum/Pendulum.cpp
1pkg/dump
0ee579cb6a97ae64d5367cc624b2407d7d4b1c7b
[ "MIT" ]
null
null
null
#include "Director.hpp" #include "GameAct/Act.hpp" #include "GameAct/Objects/Factories/ObjectsFactory.hpp" #include "Pendulum.hpp" namespace GameAct { namespace Physical { Pendulum::Pendulum() : _pivot( Director::getInstance().getGameAct()->getObjectsFactory()->create( "Pivot" ) ) { } void Pendulum::initialize() { Object::initialize(); getBody()->setDynamic( false ); } std::string Pendulum::getResourcesName() const { return "Pendulum"; } void Pendulum::setPosition( cocos2d::Vec2 position ) { _position = position; cocos2d::Vec2 pivotPosit = position; float delta = _pivot->getSize().width / 2.0f; float deltaX = delta * sin( CC_DEGREES_TO_RADIANS( _angle + 90.0f ) ); float deltaY = delta * cos( CC_DEGREES_TO_RADIANS( _angle + 90.0f ) ); pivotPosit.x += deltaX; pivotPosit.y += deltaY; _pivot->setPosition( pivotPosit ); delta = getSize().width * _lenth; deltaX = delta * sin( CC_DEGREES_TO_RADIANS( _angle + 90.0f ) ); deltaY = delta * cos( CC_DEGREES_TO_RADIANS( _angle + 90.0f ) ); position.x += deltaX; position.y += deltaY; Object::setPosition( position ); } void Pendulum::setSize( cocos2d::Size size ) { cocos2d::Size pivotSize = size; pivotSize.width *= _lenth; _pivot->setSize( pivotSize ); Object::setSize( size ); } void Pendulum::setAdditionalParam( std::string additionalParam ) { std::string lenth = ThirdParty::readToken( additionalParam ); _lenth = atof( lenth.data() ); std::string time = ThirdParty::readToken( additionalParam ); _time = atof( time.data() ); _pivot->setAdditionalParam( time ); Object::setAdditionalParam( additionalParam ); } void Pendulum::setRotation( float angle ) { _angle = angle; _pivot->setRotation( angle ); Object::setRotation( angle ); } void Pendulum::hide() { _pivot->hide(); Object::hide(); } void Pendulum::show() { _pivot->show(); Object::show(); } void Pendulum::attachToChunk( Chunk & chunk, int zIndex ) { _pivot->attachToChunk( chunk, zIndex - 1 ); Object::attachToChunk( chunk, zIndex ); } void Pendulum::runAction( const std::string & action ) { if( action == "Move" || action == "On" ) { cocos2d::Vec2 center = _position; cocos2d::Vector< cocos2d::FiniteTimeAction * > rotatePnt; cocos2d::Vec2 posit = getPosition(); for( int i = 0; i < 60; ++i ) { rotatePnt.pushBack( cocos2d::MoveTo::create( _time / 240, posit ) ); posit = rotatePoint( posit, center, 1.0f ); } for( int i = 0; i < 120; ++i ) { rotatePnt.pushBack( cocos2d::MoveTo::create( _time / 240, posit ) ); posit = rotatePoint( posit, center, -1.0f ); } for( int i = 0; i < 60; ++i ) { rotatePnt.pushBack( cocos2d::MoveTo::create( _time / 240, posit ) ); posit = rotatePoint( posit, center, 1.0f ); } auto action = cocos2d::RepeatForever::create( cocos2d::Sequence::create( rotatePnt ) ); _representation->runAction( action ); _pivot->runAction( "FluctuatePendulum" ); return; } /*if( action == "Stop" || action == "Off" ) { _representation->stopAllActions(); _pivot->runAction( "Stop" ); return; }*/ Object::runAction( action ); } cocos2d::Vec2 Pendulum::rotatePoint( cocos2d::Vec2 point, cocos2d::Vec2 center, float angle ) const { angle = CC_DEGREES_TO_RADIANS( angle ); float rotatedX = cos( angle ) * (point.x - center.x) + sin( angle ) * ( point.y - center.y ) + center.x; float rotatedY = -sin( angle ) * ( point.x - center.x ) + cos( angle ) * ( point.y - center.y ) + center.y; return cocos2d::Vec2( rotatedX, rotatedY ); } } }
22.272727
112
0.63619
[ "object", "vector" ]
81f7de63e39817f968e33cbda57c6e95706dd32a
3,980
hh
C++
plugins/MudPlugin.hh
SamFerwerda/Gazebo10-commits
b33ac5982fb75cac894fa145f7268146d44e0724
[ "ECL-2.0", "Apache-2.0" ]
3
2018-07-17T00:17:13.000Z
2020-05-26T08:39:25.000Z
plugins/MudPlugin.hh
SamFerwerda/Gazebo10-commits
b33ac5982fb75cac894fa145f7268146d44e0724
[ "ECL-2.0", "Apache-2.0" ]
1
2020-06-04T10:26:04.000Z
2020-06-04T10:26:04.000Z
plugins/MudPlugin.hh
SamFerwerda/Gazebo10-commits
b33ac5982fb75cac894fa145f7268146d44e0724
[ "ECL-2.0", "Apache-2.0" ]
2
2019-11-10T07:19:09.000Z
2019-11-21T19:11:11.000Z
/* * Copyright (C) 2012 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef GAZEBO_PLUGINS_MUDPLUGIN_HH_ #define GAZEBO_PLUGINS_MUDPLUGIN_HH_ #include <mutex> #include <string> #include <vector> #include <ignition/transport/Node.hh> #include "gazebo/common/Plugin.hh" #include "gazebo/physics/physics.hh" #include "gazebo/transport/TransportTypes.hh" #include "gazebo/util/system.hh" namespace gazebo { class GAZEBO_VISIBLE MudPlugin : public ModelPlugin { /// \brief Constructor. public: MudPlugin(); // Documentation Inherited. public: virtual void Load(physics::ModelPtr _model, sdf::ElementPtr _sdf); // Documentation Inherited. public: virtual void Init(); /// \brief Callback for receipt of contact sensor messages. /// \param[in] _msg Contacts message from contact sensor. private: void OnContact(ConstContactsPtr &_msg); /// \brief Callback for World Update events. private: void OnUpdate(); /// \brief Transport node used for subscribing to contact sensor messages. private: transport::NodePtr node; /// \brief Subscriber to contact sensor messages. private: transport::SubscriberPtr contactSub; /// \brief Connection to World Update events. private: event::ConnectionPtr updateConnection; /// \brief Pointer to world. private: physics::WorldPtr world; /// \brief Pointer to physics engine. private: physics::PhysicsEnginePtr physics; /// \brief Pointer to model containing plugin. private: physics::ModelPtr model; /// \brief Name of model containing plugin. private: std::string modelName; /// \brief Pointer to canonical link in mud model. It is assumed that /// the canonical link has the contact sensor. private: physics::LinkPtr link; /// \brief Name of contact sensor relative to model, scoped with '/', private: std::string contactSensorName; /// \brief Mutex to protect reads and writes. private: mutable std::mutex mutex; /// \brief Store newest contacts message. private: msgs::Contacts newestContactsMsg; /// \brief Flag to indicate new contact message. private: bool newMsg; /// \brief Number of updates without having a new contacts message. private: unsigned int newMsgWait; /// \brief Stiffness parameter, used in conjunction with damping /// to compute joint erp, cfm private: double stiffness; /// \brief Damping parameter, used in conjunction with stiffness /// to compute joint erp, cfm private: double damping; /// \brief Names of allowed target links, specified in sdf parameters. private: std::vector<std::string> allowedLinks; /// \brief Pointer to link currently targeted by mud joint. private: std::vector<physics::LinkPtr> links; /// \brief Dynamically created joint for simulating mud forces. private: std::vector<physics::JointPtr> joints; /// \brief Custom bitmask associated to collision surface of allowed links private: unsigned int contactSurfaceBitmask; /// \brief SDF for this plugin; private: sdf::ElementPtr sdf; // Place ignition::transport objects at the end of this file to // guarantee they are destructed first. /// \brief Ignition transport node used for subscribing to /// contact sensor messages. private: ignition::transport::Node nodeIgn; }; } #endif // ifndef _MUD_PLUGIN_HH_
32.622951
78
0.709296
[ "vector", "model" ]
81f9153d890f11b17e90d93f5c81ae855ac51809
12,034
cpp
C++
vbox/src/VBox/HostServices/SharedOpenGL/crserverlib/presenter/display_window.cpp
Nurzamal/rest_api_docker
a9cc01dfc235467d490d9663755b33ef6990bdd8
[ "MIT" ]
null
null
null
vbox/src/VBox/HostServices/SharedOpenGL/crserverlib/presenter/display_window.cpp
Nurzamal/rest_api_docker
a9cc01dfc235467d490d9663755b33ef6990bdd8
[ "MIT" ]
null
null
null
vbox/src/VBox/HostServices/SharedOpenGL/crserverlib/presenter/display_window.cpp
Nurzamal/rest_api_docker
a9cc01dfc235467d490d9663755b33ef6990bdd8
[ "MIT" ]
null
null
null
/* $Id: display_window.cpp 69500 2017-10-28 15:14:05Z vboxsync $ */ /** @file * Presenter API: CrFbDisplayWindow class implementation -- display content into host GUI window. */ /* * Copyright (C) 2014-2017 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. */ #include "server_presenter.h" CrFbDisplayWindow::CrFbDisplayWindow(const RTRECT *pViewportRect, uint64_t parentId) : mpWindow(NULL), mViewportRect(*pViewportRect), mu32Screen(~0), mParentId(parentId) { mFlags.u32Value = 0; } CrFbDisplayWindow::~CrFbDisplayWindow() { if (mpWindow) delete mpWindow; } int CrFbDisplayWindow::UpdateBegin(struct CR_FRAMEBUFFER *pFb) { int rc = mpWindow ? mpWindow->UpdateBegin() : VINF_SUCCESS; if (RT_SUCCESS(rc)) { rc = CrFbDisplayBase::UpdateBegin(pFb); if (RT_SUCCESS(rc)) return VINF_SUCCESS; else { WARN(("err")); if (mpWindow) mpWindow->UpdateEnd(); } } else WARN(("err")); return rc; } void CrFbDisplayWindow::UpdateEnd(struct CR_FRAMEBUFFER *pFb) { CrFbDisplayBase::UpdateEnd(pFb); if (mpWindow) mpWindow->UpdateEnd(); } int CrFbDisplayWindow::RegionsChanged(struct CR_FRAMEBUFFER *pFb) { int rc = CrFbDisplayBase::RegionsChanged(pFb); if (!RT_SUCCESS(rc)) { WARN(("err")); return rc; } if (mpWindow && mpWindow->GetParentId()) { rc = mpWindow->Create(); if (!RT_SUCCESS(rc)) { WARN(("err")); return rc; } } return VINF_SUCCESS; } int CrFbDisplayWindow::EntryCreated(struct CR_FRAMEBUFFER *pFb, HCR_FRAMEBUFFER_ENTRY hEntry) { int rc = CrFbDisplayBase::EntryCreated(pFb, hEntry); if (!RT_SUCCESS(rc)) { WARN(("err")); return rc; } if (mpWindow && mpWindow->GetParentId()) { rc = mpWindow->Create(); if (!RT_SUCCESS(rc)) { WARN(("err")); return rc; } } return VINF_SUCCESS; } int CrFbDisplayWindow::EntryReplaced(struct CR_FRAMEBUFFER *pFb, HCR_FRAMEBUFFER_ENTRY hNewEntry, HCR_FRAMEBUFFER_ENTRY hReplacedEntry) { int rc = CrFbDisplayBase::EntryReplaced(pFb, hNewEntry, hReplacedEntry); if (!RT_SUCCESS(rc)) { WARN(("err")); return rc; } if (mpWindow && mpWindow->GetParentId()) { rc = mpWindow->Create(); if (!RT_SUCCESS(rc)) { WARN(("err")); return rc; } } return VINF_SUCCESS; } int CrFbDisplayWindow::EntryTexChanged(struct CR_FRAMEBUFFER *pFb, HCR_FRAMEBUFFER_ENTRY hEntry) { int rc = CrFbDisplayBase::EntryTexChanged(pFb, hEntry); if (!RT_SUCCESS(rc)) { WARN(("err")); return rc; } if (mpWindow && mpWindow->GetParentId()) { rc = mpWindow->Create(); if (!RT_SUCCESS(rc)) { WARN(("err")); return rc; } } return VINF_SUCCESS; } int CrFbDisplayWindow::FramebufferChanged(struct CR_FRAMEBUFFER *pFb) { int rc = CrFbDisplayBase::FramebufferChanged(pFb); if (!RT_SUCCESS(rc)) { WARN(("err")); return rc; } return screenChanged(); } const RTRECT* CrFbDisplayWindow::getViewportRect() { return &mViewportRect; } int CrFbDisplayWindow::setViewportRect(const RTRECT *pViewportRect) { if (!isUpdating()) { WARN(("not updating!")); return VERR_INVALID_STATE; } // always call SetPosition to ensure window is adjustep properly // if (pViewportRect->xLeft != mViewportRect.xLeft || pViewportRect->yTop != mViewportRect.yTop) if (mpWindow) { const RTRECT* pRect = getRect(); int rc = mpWindow->SetPosition(pRect->xLeft - pViewportRect->xLeft, pRect->yTop - pViewportRect->yTop); if (!RT_SUCCESS(rc)) { WARN(("SetPosition failed")); return rc; } } mViewportRect = *pViewportRect; return VINF_SUCCESS; } CrFbWindow * CrFbDisplayWindow::windowDetach(bool fCleanup) { if (isUpdating()) { WARN(("updating!")); return NULL; } CrFbWindow * pWindow = mpWindow; if (mpWindow) { if (fCleanup) windowCleanup(); mpWindow = NULL; } return pWindow; } CrFbWindow * CrFbDisplayWindow::windowAttach(CrFbWindow * pNewWindow) { if (isUpdating()) { WARN(("updating!")); return NULL; } CrFbWindow * pOld = mpWindow; if (mpWindow) windowDetach(); mpWindow = pNewWindow; if (pNewWindow) windowSync(); return mpWindow; } int CrFbDisplayWindow::reparent(uint64_t parentId) { if (!isUpdating()) { WARN(("not updating!")); return VERR_INVALID_STATE; } crDebug("CrFbDisplayWindow: change parent from %p to %p.", mParentId, parentId); mParentId = parentId; int rc = VINF_SUCCESS; /* Force notify Render SPU about parent window ID change in order to prevent * crashes when it tries to access already deallocated parent window. * Previously, we also used isActive() here, however it might become FALSE for the case * when VM Window goes fullscreen mode and back. */ if ( /* isActive() && */ mpWindow) { rc = mpWindow->Reparent(parentId); if (!RT_SUCCESS(rc)) WARN(("window reparent failed")); mFlags.fNeForce = 1; } return rc; } bool CrFbDisplayWindow::isVisible() { HCR_FRAMEBUFFER hFb = getFramebuffer(); if (!hFb) return false; const struct VBOXVR_SCR_COMPOSITOR* pCompositor = CrFbGetCompositor(hFb); return !CrVrScrCompositorIsEmpty(pCompositor); } int CrFbDisplayWindow::winVisibilityChanged() { HCR_FRAMEBUFFER hFb = getFramebuffer(); if (!hFb || !CrFbIsEnabled(hFb)) { Assert(!mpWindow || !mpWindow->IsVisivle()); return VINF_SUCCESS; } int rc = VINF_SUCCESS; if (mpWindow) { rc = mpWindow->UpdateBegin(); if (RT_SUCCESS(rc)) { rc = mpWindow->SetVisible(!g_CrPresenter.fWindowsForceHidden); if (!RT_SUCCESS(rc)) WARN(("SetVisible failed, rc %d", rc)); mpWindow->UpdateEnd(); } else WARN(("UpdateBegin failed, rc %d", rc)); } return rc; } CrFbWindow* CrFbDisplayWindow::getWindow() { return mpWindow; } void CrFbDisplayWindow::onUpdateEnd() { CrFbDisplayBase::onUpdateEnd(); bool fVisible = isVisible(); if (mFlags.fNeVisible != fVisible || mFlags.fNeForce) { crVBoxServerNotifyEvent(mu32Screen, fVisible? VBOX3D_NOTIFY_EVENT_TYPE_3DDATA_VISIBLE: VBOX3D_NOTIFY_EVENT_TYPE_3DDATA_HIDDEN, NULL, 0); mFlags.fNeVisible = fVisible; mFlags.fNeForce = 0; } } void CrFbDisplayWindow::ueRegions() { if (mpWindow) mpWindow->SetVisibleRegionsChanged(); } int CrFbDisplayWindow::screenChanged() { if (!isUpdating()) { WARN(("not updating!")); return VERR_INVALID_STATE; } int rc = windowDimensionsSync(); if (!RT_SUCCESS(rc)) { WARN(("windowDimensionsSync failed rc %d", rc)); return rc; } return VINF_SUCCESS; } int CrFbDisplayWindow::windowSetCompositor(bool fSet) { if (!mpWindow) return VINF_SUCCESS; if (fSet) { const struct VBOXVR_SCR_COMPOSITOR* pCompositor = CrFbGetCompositor(getFramebuffer()); return mpWindow->SetCompositor(pCompositor); } return mpWindow->SetCompositor(NULL); } int CrFbDisplayWindow::windowCleanup() { if (!mpWindow) return VINF_SUCCESS; int rc = mpWindow->UpdateBegin(); if (!RT_SUCCESS(rc)) { WARN(("err")); return rc; } rc = windowDimensionsSync(true); if (!RT_SUCCESS(rc)) { WARN(("err")); mpWindow->UpdateEnd(); return rc; } rc = windowSetCompositor(false); if (!RT_SUCCESS(rc)) { WARN(("err")); mpWindow->UpdateEnd(); return rc; } mpWindow->UpdateEnd(); return VINF_SUCCESS; } int CrFbDisplayWindow::fbCleanup() { int rc = windowCleanup(); if (!RT_SUCCESS(rc)) { WARN(("windowCleanup failed")); return rc; } return CrFbDisplayBase::fbCleanup(); } bool CrFbDisplayWindow::isActive() { HCR_FRAMEBUFFER hFb = getFramebuffer(); return hFb && CrFbIsEnabled(hFb); } int CrFbDisplayWindow::windowDimensionsSync(bool fForceCleanup) { int rc = VINF_SUCCESS; if (!mpWindow) return VINF_SUCCESS; //HCR_FRAMEBUFFER hFb = getFramebuffer(); if (!fForceCleanup && isActive()) { const RTRECT* pRect = getRect(); if (mpWindow->GetParentId() != mParentId) { rc = mpWindow->Reparent(mParentId); if (!RT_SUCCESS(rc)) { WARN(("err")); return rc; } } rc = mpWindow->SetPosition(pRect->xLeft - mViewportRect.xLeft, pRect->yTop - mViewportRect.yTop); if (!RT_SUCCESS(rc)) { WARN(("err")); return rc; } setRegionsChanged(); rc = mpWindow->SetSize((uint32_t)(pRect->xRight - pRect->xLeft), (uint32_t)(pRect->yBottom - pRect->yTop)); if (!RT_SUCCESS(rc)) { WARN(("err")); return rc; } rc = mpWindow->SetVisible(!g_CrPresenter.fWindowsForceHidden); if (!RT_SUCCESS(rc)) { WARN(("err")); return rc; } } else { rc = mpWindow->SetVisible(false); if (!RT_SUCCESS(rc)) { WARN(("err")); return rc; } #if 0 rc = mpWindow->Reparent(mDefaultParentId); if (!RT_SUCCESS(rc)) { WARN(("err")); return rc; } #endif } return rc; } int CrFbDisplayWindow::windowSync() { if (!mpWindow) return VINF_SUCCESS; int rc = mpWindow->UpdateBegin(); if (!RT_SUCCESS(rc)) { WARN(("err")); return rc; } rc = windowSetCompositor(true); if (!RT_SUCCESS(rc)) { WARN(("err")); mpWindow->UpdateEnd(); return rc; } rc = windowDimensionsSync(); if (!RT_SUCCESS(rc)) { WARN(("err")); mpWindow->UpdateEnd(); return rc; } mpWindow->UpdateEnd(); return rc; } int CrFbDisplayWindow::fbSync() { int rc = CrFbDisplayBase::fbSync(); if (!RT_SUCCESS(rc)) { WARN(("err")); return rc; } HCR_FRAMEBUFFER hFb = getFramebuffer(); mu32Screen = CrFbGetScreenInfo(hFb)->u32ViewIndex; rc = windowSync(); if (!RT_SUCCESS(rc)) { WARN(("windowSync failed %d", rc)); return rc; } if (CrFbHas3DData(hFb)) { if (mpWindow && mpWindow->GetParentId()) { rc = mpWindow->Create(); if (!RT_SUCCESS(rc)) { WARN(("err")); return rc; } } } return VINF_SUCCESS; } const struct RTRECT* CrFbDisplayWindow::getRect() { const struct VBOXVR_SCR_COMPOSITOR* pCompositor = CrFbGetCompositor(getFramebuffer()); return CrVrScrCompositorRectGet(pCompositor); }
20.928696
135
0.576949
[ "render" ]
3b49005ddd2c277f7f467b7b90362c1710f1d3c6
8,853
cpp
C++
src/PixelSort.cpp
SEED264/PixelSorter_s
bd6b3d952d5487e022b8a749c431f9316417009c
[ "MIT" ]
9
2018-10-20T02:57:26.000Z
2022-03-23T17:07:34.000Z
src/PixelSort.cpp
SEED264/PixelSorter_s
bd6b3d952d5487e022b8a749c431f9316417009c
[ "MIT" ]
null
null
null
src/PixelSort.cpp
SEED264/PixelSorter_s
bd6b3d952d5487e022b8a749c431f9316417009c
[ "MIT" ]
1
2020-05-31T00:05:52.000Z
2020-05-31T00:05:52.000Z
#ifndef NOMINMAX #define NOMINMAX 1 #endif // NOMINMAX #include "lua.hpp" #include <Windows.h> #include <algorithm> #include <functional> #include <string> #include <vector> #include "Trans.h" #include"PixelSort_struct.h" #include "UtilFunc.h" #define DebugCode(x) #ifdef _DEBUG #include <chrono> #include <iostream> #define DebugCode(x) x #endif // _DEBUG using namespace std; float(*const comp_func[])(Pixel_BGRA*) = { UtilFunc::comp_luminance, UtilFunc::comp_average, UtilFunc::comp_multiply, UtilFunc::comp_min, UtilFunc::comp_max, UtilFunc::comp_xor }; inline unsigned int calpos(unsigned int x, unsigned int y, unsigned int w, byte mag){ return y*mag*w + min(UtilFunc::clamp(x, 0, w)*mag, w); }; int PixelSort_Func(lua_State *L){ int b = UtilFunc::clamp((int)lua_tointeger(L, 1), 0, 4096); int d = UtilFunc::clamp((int)lua_tointeger(L, 2), 0, 4096); int r = UtilFunc::clamp((int)lua_tointeger(L, 3), 1, 4); byte dsize = (int)lua_tointeger(L, 4); bool conf = (bool)lua_toboolean(L, 5); int stretch_direction = UtilFunc::clamp((int)lua_tointeger(L, 6), 1, 4); float stretch_length = UtilFunc::clamp((float)lua_tonumber(L, 7)/100.f, 0.f, 1.f); byte comp = UtilFunc::clamp((byte)lua_tonumber(L, 8)-1, 0, 5); bool bi = (bool)lua_tonumber(L, 9); byte sr = r; DebugCode( chrono::system_clock::time_point start = chrono::system_clock::now(); ); lua_getglobal(L, "obj"); lua_getfield(L, -1, "getpixeldata"); lua_call(L, 0, 3); int h = lua_tointeger(L, -1); lua_pop(L, 1); int w = lua_tointeger(L, -1); lua_pop(L, 1); Pixel_BGRA *sourcedata = new Pixel_BGRA[w*h]; memcpy(sourcedata, lua_touserdata(L, -1), sizeof(Pixel_BGRA)*w*h); lua_pop(L, 1); lua_getfield(L, -1, "effect"); lua_pushstring(L, "ルミナンスキー"); lua_pushstring(L, "type"); lua_pushnumber(L, 4); lua_pushstring(L, "基準輝度"); lua_pushnumber(L, b); lua_pushstring(L, "ぼかし"); lua_pushnumber(L, d); lua_call(L, 7, 0); lua_getfield(L, -1, "getpixeldata"); lua_call(L, 0, 3); Pixel_BGRA *data = (Pixel_BGRA*)lua_touserdata(L, -3); lua_pop(L, 1); lua_pop(L, 1); lua_pop(L, 1); const int size = w*h; int dw = ceil((float)w / (float)dsize); int dh = ceil((float)h / (float)dsize); Pixel_BGRA *sdata = new Pixel_BGRA[dw*dh]; Pixel_BGRA *odata = (bi) ? sourcedata : new Pixel_BGRA[size]; isize orig_isize(w, h); isize shr_isize(dw, dh); if (r<3){ Trans::Shrink_r(data, sdata, orig_isize, shr_isize, dsize); }else{ Trans::Shrink(data, sdata, orig_isize, shr_isize, dsize); } Pixel_map *map = new Pixel_map[dw*dh]; #pragma omp parallel for for (long i = 0; i < dw*dh; i++) { Pixel_map *m = &map[i]; m->pix = sdata[i]; m->sort_key = comp_func[comp](&m->pix); } int vw = (r < 3) ? dh : dw; int vh = (r < 3) ? dw : dh; if(!conf){ #pragma omp parallel for for (long y = 0; y < vh; y++){ vector<Pixel_map> pix; unsigned long x = 0; unsigned long offsetpos = 0; for (; x < vw; x++) { unsigned long pos = y*vw + x; byte a = map[pos].pix.a; if (a){ if (!pix.size()){ offsetpos = pos; } pix.push_back(map[pos]); }else if(pix.size()){ if (sr == 2 || sr == 4) { sort(pix.begin(), pix.end(), greater<Pixel_map>()); } else { sort(pix.begin(), pix.end()); } #pragma omp parallel for for (long i = 0; i < pix.size(); i++) { sdata[offsetpos + i] = pix[i].pix; } pix.clear(); offsetpos = 0; } if (x==(vw-1)){ if (sr == 2 || sr == 4) { sort(pix.begin(), pix.end(), greater<Pixel_map>()); } else { sort(pix.begin(), pix.end()); } #pragma omp parallel for for (long i = 0; i < pix.size(); i++) { sdata[offsetpos + i] = pix[i].pix; } pix.clear(); offsetpos = 0; } } } } else { #pragma omp parallel for for (long i = 0; i < vw*vh; i++){ Pixel_BGRA p = sdata[i]; if (p.a){ p.r = 0; p.g = 255; p.b = 0; sdata[i] = p; } } } if (bi) odata = sourcedata; if (r < 3){ Trans::Restore_r(sdata, odata, shr_isize, orig_isize, dsize, stretch_direction, stretch_length, bi); } else { Trans::Restore(sdata, odata, shr_isize, orig_isize, dsize, stretch_direction, stretch_length, bi); } lua_getglobal(L, "obj"); lua_getfield(L, -1, "putpixeldata"); lua_pushlightuserdata(L, odata); lua_call(L, 1, 0); DebugCode( chrono::system_clock::time_point end = chrono::system_clock::now(); double duration = chrono::duration_cast<chrono::nanoseconds>(end - start).count() / 1000000.0; OutputDebugString(("Process time : " + to_string(duration) + "ms").c_str()); ); delete[] sdata; delete[] map; if (!bi)delete[] odata; delete[] sourcedata; return 0; } int Instructions(lua_State *L) { const byte Max_page = 2; byte pagenum = UtilFunc::clamp((byte)lua_tointeger(L, 1)-1, 0, Max_page-1); string version = "1.61"; string Inst[Max_page]; Inst[0] = "基準輝度 : 画像切り出しの基準となる輝度です。\n" "輝度幅 : 基準輝度からの輝度の幅です。\n" "方向 : 元となったバージョンから減って4種類になりました。縦横2方向ずつなのでこれが一番だと思います。\n" "引き伸ばし : ソート後の画像を指定した方向に引き延ばします。\n" "引伸方向 : 引き伸ばしの方向を右、左、下、上の4種類から選べます。\n" "ソート基準 : ソートの基準値の計算式を選べます(全6種類)。\n" "サイズ : ピクセルのモザイク化のサイズです。小さければ小さいほど重いです。逆に大きいと結構軽いです。\n" "領域を確認 : 選択した範囲を緑で表示します。\n" "元画像と合成 : ソースの画像を後ろに合成します。\n"; Inst[1] = "<s36>ソート基準式 [1-6]\n<s>" " 1 : Luminance (輝度基準)\n" " 2 : Average (RGBの平均)\n" " 3 : Multiply (正規化したRGBを乗算)\n" " 4 : Min (RGBの最小値)\n" " 5 : Max (RGBの最大値)\n" " 6 : XOR (RGBでXOR演算)"; string info = "<s40>PixelSorter_s 簡易説明書 - Page : " + to_string(pagenum+1) + "<s>\nVersion : " + version + "\n\n"; info += Inst[pagenum]; lua_getglobal(L, "obj"); lua_getfield(L, -1, "effect"); lua_call(L, 0, 0); lua_getfield(L, -1, "draw"); lua_call(L, 0, 0); lua_getfield(L, -1, "load"); lua_pushstring(L, "figure"); lua_pushstring(L, "四角形"); lua_pushinteger(L, 0); lua_pushinteger(L, 1920); lua_call(L, 4, 0); lua_getfield(L, -1, "effect"); lua_pushstring(L, "リサイズ"); lua_pushstring(L, "Y"); lua_pushnumber(L, 55); lua_call(L, 3, 0); lua_getfield(L, -1, "draw"); lua_pushinteger(L, 0); lua_pushinteger(L, 0); lua_pushinteger(L, 0); lua_pushinteger(L, 1); lua_pushnumber(L, 0.75); lua_call(L, 5, 0); lua_getfield(L, -1, "load"); lua_pushstring(L, "figure"); lua_pushstring(L, "四角形"); lua_pushinteger(L, 0xaaaaaa); lua_pushinteger(L, 1870); lua_call(L, 4, 0); lua_getfield(L, -1, "effect"); lua_pushstring(L, "リサイズ"); lua_pushstring(L, "Y"); lua_pushnumber(L, 50); lua_call(L, 3, 0); lua_getfield(L, -1, "draw"); lua_pushinteger(L, 0); lua_pushinteger(L, 0); lua_pushinteger(L, 0); lua_pushinteger(L, 1); lua_pushnumber(L, 0.3); lua_call(L, 5, 0); lua_getfield(L, -1, "setfont"); lua_pushstring(L, "メイリオ"); lua_pushinteger(L, 30); lua_pushinteger(L, 1); lua_pushinteger(L, 0xffffff); lua_pushinteger(L, 0x444444); lua_call(L, 5, 0); lua_getfield(L, -1, "load"); lua_pushstring(L, "text"); lua_pushstring(L, info.c_str()); lua_call(L, 2, 0); lua_getfield(L, -1, "draw"); lua_pushinteger(L, 0); lua_pushinteger(L, 0); lua_pushinteger(L, 0); lua_pushinteger(L, 1); lua_pushnumber(L, 1); lua_call(L, 5, 0); return 0; } static luaL_Reg PixelSorter_s[] = { { "PixelSort", PixelSort_Func }, { "Instructions", Instructions }, { NULL, NULL } }; /* ここでdllを定義します 別のものを作る場合は luaopen_PixelSort の部分を新しい名前に変えてください */ extern "C"{ __declspec(dllexport) int luaopen_PixelSorter_s(lua_State *L) { luaL_register(L, "PixelSorter_s", PixelSorter_s); return 1; } }
28.743506
117
0.536654
[ "vector" ]
3b493bf484a9a0b26b64fab3bf9543990322a581
10,265
cpp
C++
src/pancake/AlignerKSW2.cpp
PacificBiosciences/pancake
3f099cee41668ff830ea69609e83322fece498dc
[ "BSD-3-Clause-Clear", "BSL-1.0", "BSD-3-Clause", "MIT" ]
8
2020-11-18T20:39:36.000Z
2022-03-02T19:14:14.000Z
src/pancake/AlignerKSW2.cpp
PacificBiosciences/pancake
3f099cee41668ff830ea69609e83322fece498dc
[ "BSD-3-Clause-Clear", "BSL-1.0", "BSD-3-Clause", "MIT" ]
4
2020-12-01T15:47:46.000Z
2021-09-02T14:53:23.000Z
src/pancake/AlignerKSW2.cpp
PacificBiosciences/pancake
3f099cee41668ff830ea69609e83322fece498dc
[ "BSD-3-Clause-Clear", "BSL-1.0", "BSD-3-Clause", "MIT" ]
5
2020-11-19T18:24:05.000Z
2021-03-18T16:08:23.000Z
// Authors: Ivan Sovic #include <pacbio/alignment/AlignmentTools.h> #include <pacbio/pancake/AlignerKSW2.h> #include <pacbio/pancake/Lookups.h> #include <array> #include <cstring> #include <iostream> namespace PacBio { namespace Pancake { mm_tbuf_t* mm_tbuf_init(void) { mm_tbuf_t* b; b = (mm_tbuf_t*)calloc(1, sizeof(mm_tbuf_t)); // if (!(mm_dbg_flag & 1)) b->km = km_init(); // This flag means: #define MM_DBG_NO_KALLOC 0x1 return b; } void mm_tbuf_destroy(mm_tbuf_t* b) { if (b == 0) return; km_destroy(b->km); free(b); } std::shared_ptr<AlignerBase> CreateAlignerKSW2(const AlignmentParameters& opt) { return std::shared_ptr<AlignerBase>(new AlignerKSW2(opt)); } AlignerKSW2::AlignerKSW2(const AlignmentParameters& opt) : opt_(opt), buffer_(mm_tbuf_init(), mm_tbuf_destroy) { // Minimap2 alignment matrix. // From Minimap2: int sc_ambi; // score when one or both bases are "N" const int32_t scAmbi = 1; GenerateSimpleMatrix_(5, mat_, opt.matchScore, opt.mismatchPenalty, scAmbi); } AlignerKSW2::~AlignerKSW2() = default; AlignmentResult AlignerKSW2::Global(const char* qseq, int64_t qlen, const char* tseq, int64_t tlen) { if (qlen == 0 || tlen == 0) { AlignmentResult ret = EdgeCaseAlignmentResult( qlen, tlen, opt_.matchScore, opt_.mismatchPenalty, opt_.gapOpen1, opt_.gapExtend1); return ret; } const int32_t extra_flag = 0; // Bandwidth heuristic, as it is in Minimap2. const int32_t bw = (int)(opt_.alignBandwidth * 1.5 + 1.); // Memory allocations required for KSW2. // Convert the subsequence's alphabet from ACTG to [0123]. const std::vector<uint8_t> qseqInt = ConvertSeqAlphabet_(qseq, qlen, &BaseToTwobit[0]); const std::vector<uint8_t> tseqInt = ConvertSeqAlphabet_(tseq, tlen, &BaseToTwobit[0]); // Compute the actual bandwidth. If this was a long join, we need to allow more room. const int32_t longestSpan = std::max(qlen, tlen); const int32_t spanDiff = std::abs(tlen - qlen); // This is slighlty modified compared to how it is in Minimap2: // const int32_t actualBandwidth = // (h2.CheckFlagLongJoin() || spanDiff > (bw / 2)) ? longestSpan : bw; const int32_t actualBandwidth = (spanDiff > (bw / 2)) ? longestSpan : bw; AlignmentResult ret; std::vector<int32_t> bws; if (opt_.dynamicBandwidth) { bws.reserve(5); for (const int32_t curBw : (longestSpan < 500) ? std::vector<int32_t>{50, 100, 250} : std::vector<int32_t>{250, 500}) { if (curBw < actualBandwidth) { bws.emplace_back(curBw); } } } bws.emplace_back(actualBandwidth); bws.emplace_back(longestSpan); for (int32_t curBw : bws) { ret = AlignmentResult{}; ksw_extz_t ez; memset(&ez, 0, sizeof(ksw_extz_t)); AlignPair_(buffer_->km, qlen, &qseqInt[0], tlen, &tseqInt[0], mat_, curBw, -1, -1, extra_flag | KSW_EZ_APPROX_MAX, &ez, opt_.gapOpen1, opt_.gapExtend1, opt_.gapOpen2, opt_.gapExtend2); PacBio::Data::Cigar currCigar; int32_t qAlnLen = 0; int32_t tAlnLen = 0; ConvertMinimap2CigarToPbbam_(ez.cigar, ez.n_cigar, qseqInt, tseqInt, currCigar, qAlnLen, tAlnLen, ret.diffs); // If full-width bandwidth is used, don't run the check. const bool isSuboptimal = (curBw != longestSpan) ? CheckAlignmentOutOfBand(currCigar, curBw) : false; ret.valid = !isSuboptimal && !ez.zdropped && (ez.n_cigar != 0) && (qAlnLen == qlen) && (tAlnLen == tlen); if (ret.valid) { ret.cigar = std::move(currCigar); } ret.lastQueryPos = qlen; ret.lastTargetPos = tlen; ret.maxQueryPos = ez.max_q; ret.maxTargetPos = ez.max_t; ret.score = ez.score; ret.maxScore = ez.max; ret.zdropped = ez.zdropped; // Free KSW2 memory. kfree(buffer_->km, ez.cigar); // Early return if bandwidth lead to an optimal alignment if (ret.valid) { break; } } return ret; } AlignmentResult AlignerKSW2::Extend(const char* qseq, int64_t qlen, const char* tseq, int64_t tlen) { if (qlen == 0 || tlen == 0) { AlignmentResult ret = EdgeCaseAlignmentResult( qlen, tlen, opt_.matchScore, opt_.mismatchPenalty, opt_.gapOpen1, opt_.gapExtend1); return ret; } const int32_t extra_flag = 0; // Bandwidth heuristic, as it is in Minimap2. const int32_t bw = (int)(opt_.alignBandwidth * 1.5 + 1.); // Memory allocations required for KSW2. ksw_extz_t ez; memset(&ez, 0, sizeof(ksw_extz_t)); // Convert the subsequence's alphabet from ACTG to [0123]. const std::vector<uint8_t> qseqInt = ConvertSeqAlphabet_(qseq, qlen, &BaseToTwobit[0]); const std::vector<uint8_t> tseqInt = ConvertSeqAlphabet_(tseq, tlen, &BaseToTwobit[0]); AlignPair_(buffer_->km, qlen, &qseqInt[0], tlen, &tseqInt[0], mat_, bw, opt_.endBonus, opt_.zdrop, extra_flag | KSW_EZ_EXTZ_ONLY | KSW_EZ_RIGHT, &ez, opt_.gapOpen1, opt_.gapExtend1, opt_.gapOpen2, opt_.gapExtend2); AlignmentResult ret; PacBio::Data::Cigar currCigar; int32_t qAlnLen = 0; int32_t tAlnLen = 0; ConvertMinimap2CigarToPbbam_(ez.cigar, ez.n_cigar, qseqInt, tseqInt, currCigar, qAlnLen, tAlnLen, ret.diffs); ret.cigar = std::move(currCigar); ret.valid = true; ret.lastQueryPos = (ez.reach_end ? qlen : ez.max_q + 1); ret.lastTargetPos = (ez.reach_end ? ez.mqe_t + 1 : ez.max_t + 1); ret.maxQueryPos = ez.max_q; ret.maxTargetPos = ez.max_t; ret.zdropped = ez.zdropped; ret.maxScore = ez.max; ret.score = std::max(ret.maxScore, ez.score); // Free KSW2 memory. kfree(buffer_->km, ez.cigar); return ret; } std::vector<uint8_t> AlignerKSW2::ConvertSeqAlphabet_(const char* seq, size_t seqlen, const int8_t* conv_table) { std::vector<uint8_t> ret(seqlen); for (size_t i = 0; i < seqlen; i++) { ret[i] = (int8_t)conv_table[(uint8_t)seq[i]]; } return ret; } void AlignerKSW2::ConvertMinimap2CigarToPbbam_( uint32_t* mm2Cigar, int32_t cigarLen, const std::vector<uint8_t>& qseq, const std::vector<uint8_t>& tseq, PacBio::Data::Cigar& retCigar, int32_t& retQueryAlignmentLen, int32_t& retTargetAlignmentLen, Alignment::DiffCounts& retDiffs) { retCigar.clear(); retDiffs.Clear(); retQueryAlignmentLen = 0; retTargetAlignmentLen = 0; std::array<int32_t, 9> counts{0, 0, 0, 0, 0, 0, 0, 0, 0}; int32_t qPos = 0; int32_t tPos = 0; for (int32_t opId = 0; opId < cigarLen; ++opId) { char op = "MIDNSH"[mm2Cigar[opId] & 0xf]; int32_t count = mm2Cigar[opId] >> 4; // cigar.emplace_back(Data::CigarOperation(op, count)); if (op == 'M') { // std::cerr << "[opId = " << opId << "] op: " << count << op << "\n"; char prevOp = 'u'; int32_t span = 0; for (int32_t m = 0; m < count; ++m) { char currOp = 'X'; if (qseq[qPos + m] == tseq[tPos + m]) { currOp = '='; } if (currOp == prevOp) { ++span; } else { if (span > 0) { retCigar.emplace_back(Data::CigarOperation(prevOp, span)); counts[CigarCharToNum[static_cast<int32_t>(prevOp)]] += span; // std::cerr << " -> Added (mid): " << span << prevOp << "\n"; } span = 1; } prevOp = currOp; // ++qPos; // ++tPos; } if (span > 0) { retCigar.emplace_back(Data::CigarOperation(prevOp, span)); counts[CigarCharToNum[static_cast<int32_t>(prevOp)]] += span; // std::cerr << " -> Added (last): " << span << prevOp << "\n"; } qPos += count; tPos += count; } else if (op == '=' || op == 'X') { retCigar.emplace_back(Data::CigarOperation(op, count)); counts[CigarCharToNum[static_cast<int32_t>(op)]] += count; qPos += count; tPos += count; } else if (op == 'I' || op == 'S') { retCigar.emplace_back(Data::CigarOperation(op, count)); counts[CigarCharToNum[static_cast<int32_t>(op)]] += count; qPos += count; } else if (op == 'D' || op == 'N') { retCigar.emplace_back(Data::CigarOperation(op, count)); counts[CigarCharToNum[static_cast<int32_t>(op)]] += count; tPos += count; } } retQueryAlignmentLen = qPos; retTargetAlignmentLen = tPos; retDiffs.numEq = counts[CIGAR_OP_EQ]; retDiffs.numX = counts[CIGAR_OP_X]; retDiffs.numI = counts[CIGAR_OP_I]; retDiffs.numD = counts[CIGAR_OP_D]; } void AlignerKSW2::AlignPair_(void* km, int qlen, const uint8_t* qseq, int tlen, const uint8_t* tseq, const int8_t* mat, int w, int endBonus, int zdrop, int flag, ksw_extz_t* ez, int q, int e, int q2, int e2) { if (q == q2 && e == e2) ksw_extz2_simde(km, qlen, qseq, tlen, tseq, 5, mat, q, e, w, zdrop, endBonus, flag, ez); else ksw_extd2_simde(km, qlen, qseq, tlen, tseq, 5, mat, q, e, q2, e2, w, zdrop, endBonus, flag, ez); } void AlignerKSW2::GenerateSimpleMatrix_(int m, int8_t* mat, int8_t a, int8_t b, int8_t scAmbi) { int i, j; a = a < 0 ? -a : a; b = b > 0 ? -b : b; scAmbi = scAmbi > 0 ? -scAmbi : scAmbi; for (i = 0; i < m - 1; ++i) { for (j = 0; j < m - 1; ++j) mat[i * m + j] = i == j ? a : b; mat[i * m + m - 1] = scAmbi; } for (j = 0; j < m; ++j) mat[(m - 1) * m + j] = scAmbi; } } // namespace Pancake } // namespace PacBio
35.519031
115
0.572138
[ "vector" ]
3b4a597dd25557796b3d8ee6624ca7bc4d2c0613
5,107
hpp
C++
include/verilog/ieee1364_2001/actions/module.hpp
qedalab/vcd_assert
40da307e60600fc4a814d4bba4679001f49f4375
[ "BSD-2-Clause" ]
1
2019-04-30T17:56:23.000Z
2019-04-30T17:56:23.000Z
include/verilog/ieee1364_2001/actions/module.hpp
qedalab/vcd_assert
40da307e60600fc4a814d4bba4679001f49f4375
[ "BSD-2-Clause" ]
null
null
null
include/verilog/ieee1364_2001/actions/module.hpp
qedalab/vcd_assert
40da307e60600fc4a814d4bba4679001f49f4375
[ "BSD-2-Clause" ]
4
2018-08-01T08:32:00.000Z
2019-12-18T06:34:33.000Z
// ============================================================================ // Copyright 2018 Paul le Roux and Calvin Maree // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // ============================================================================ #ifndef LIBVERILOG_IEEE1364_2001_ACTIONS_MODULE_HPP #define LIBVERILOG_IEEE1364_2001_ACTIONS_MODULE_HPP #include "base.hpp" #include "commands.hpp" #include "../../types/commands.hpp" #include "../../types/design_reader.hpp" #include "../../util/parse_input.hpp" #include "../grammar/grammar_hacked.hpp" #include <parse/actions/command/inner_action_then_apply.hpp> #include <parse/actions/make_pegtl_template.hpp> #include <parse/util/debug_printing.hpp> #include <tao/pegtl/memory_input.hpp> namespace Verilog { namespace IEEE1364_2001 { namespace Actions { // clang-format off struct ModuleInstanceIdentifierAction : single_dispatch< Grammar::module_instance_identifier, inner_action_passthrough< IdentifierAction > > { using state = std::string; }; struct ModuleInstanceAction : single_dispatch< Grammar::name_of_instance, inner_action_passthrough< ModuleInstanceIdentifierAction> > { using state = std::string; }; struct StringStringMapping { std::string type; std::string name; }; struct ModuleEvent { std::string module_identifier; std::vector<StringStringMapping> instances; std::vector<Command> commands; }; struct ModuleInstantiationAction : multi_dispatch< Grammar::module_identifier, inner_action< IdentifierAction, Storage::member<&StringStringMapping::type> >, Grammar::module_instance, inner_action< ModuleInstanceAction, Storage::member<&StringStringMapping::name> > > { using state = StringStringMapping; }; struct ModuleInstantiationArrayAction : single_dispatch< Grammar::module_instantiation, inner_action< ModuleInstantiationAction, Storage::push_back > > { using state = std::vector<StringStringMapping>; }; struct CommandArrayAction : single_dispatch< Grammar::sdf_annotate_task, inner_action< SDFAnnotateTaskAction, Storage::push_back > > { using state = std::vector<Command>; }; struct ModuleDeclarationAction : multi_dispatch< Grammar::module_identifier, inner_action< IdentifierAction, Storage::member<&ModuleEvent::module_identifier> >, Grammar::module_instantiation, inner_action< ModuleInstantiationArrayAction, Storage::member<&ModuleEvent::instances> >, Grammar::sdf_annotate_task, inner_action< CommandArrayAction, Storage::member<&ModuleEvent::commands> > > { using state = ModuleEvent; }; struct ModuleDescriptionAction: single_dispatch< Grammar::_module_declaration_, inner_action_passthrough< ModuleDeclarationAction > > { using state = ModuleEvent; }; struct ModuleDescriptionApply{ // clang-format on template <class Rule, class ActionInput> static bool apply(const ActionInput &input, ModuleEvent data, DesignReader &reader, Util::InputMap &/*inputmap*/, bool first_pass){ if(first_pass){ Parse::Util::debug_puts("DEBUG: found new module"); reader.module(data.module_identifier, input.position().source); }else{ Parse::Util::debug_puts("DEBUG: next module"); //increment internal counter reader.next_module(); for (auto&& instance : data.instances ){ reader.instance(NetType::module, instance.name, instance.type); } for (auto&& command : data.commands ){ reader.command(command); } } return true; } }; // clang-format off // clang-format on } // namespace Actions } // namespace IEEE1364_2001 } // namespace Verilog #endif // LIBVERILOG_IEEE1364_2001_ACTIONS_MODULE_HPP
30.041176
79
0.706873
[ "vector" ]
3b4b5d1547e40ddabd3a234c346b9cd2d8491d89
4,805
cpp
C++
src/visualization/shaders/abstract_shader.cpp
mtao/balsa
1552f3a367a80dfc41fffc50b5628b46ba716ab8
[ "MIT" ]
null
null
null
src/visualization/shaders/abstract_shader.cpp
mtao/balsa
1552f3a367a80dfc41fffc50b5628b46ba716ab8
[ "MIT" ]
null
null
null
src/visualization/shaders/abstract_shader.cpp
mtao/balsa
1552f3a367a80dfc41fffc50b5628b46ba716ab8
[ "MIT" ]
null
null
null
#include "balsa/visualization/shaders/abstract_shader.hpp" #include "shaderc/status.h" #include <QtCore/QTextStream> #include <spdlog/spdlog.h> #include <QtCore/QFile> #include <iostream> #include <shaderc/shaderc.hpp> #include <vulkan/vulkan_core.h> void balsa_visualization_shaders_initialize_resources() { Q_INIT_RESOURCE(glsl); } namespace balsa::visualization::shaders { namespace { const std::string &get_shader_type_name(AbstractShader::ShaderType type) { const static std::string v0 = "Vertex"; const static std::string v1 = "Fragment"; switch (type) { case AbstractShader::ShaderType::Vertex: return v0; case AbstractShader::ShaderType::Fragment: return v1; } } const std::string &shaderc_compilation_status_name(shaderc_compilation_status status) { const static std::string e0 = "Success"; const static std::string e1 = "Invalid Stage"; const static std::string e2 = "Compilation Error"; const static std::string e3 = "Internal Error"; const static std::string e4 = "Null Result Object"; const static std::string e5 = "Invalid Assembly"; const static std::string e6 = "Validation Error"; const static std::string e7 = "Transformation Error"; const static std::string e8 = "Configuration Error"; switch (status) { case shaderc_compilation_status_success: return e0; case shaderc_compilation_status_invalid_stage: return e1;// error stage deduction case shaderc_compilation_status_compilation_error: return e2; case shaderc_compilation_status_internal_error: return e3;// unexpected failure case shaderc_compilation_status_null_result_object: return e4; case shaderc_compilation_status_invalid_assembly: return e5; case shaderc_compilation_status_validation_error: return e6; case shaderc_compilation_status_transformation_error: return e7; case shaderc_compilation_status_configuration_error: return e8; } } }// namespace AbstractShader::AbstractShader() { balsa_visualization_shaders_initialize_resources(); } std::vector<uint32_t> AbstractShader::compile_glsl(const std::string &glsl, ShaderType type) const { const std::string &stage_name = get_shader_type_name(type); shaderc_shader_kind kind; switch (type) { case ShaderType::Vertex: kind = shaderc_glsl_default_vertex_shader; break; case ShaderType::Fragment: kind = shaderc_glsl_default_fragment_shader; break; } shaderc::Compiler compiler; shaderc::CompileOptions compile_options; add_compile_options(compile_options); auto result = compiler.CompileGlslToSpv(glsl.data(), glsl.size(), kind, stage_name.c_str(), "main", compile_options); auto status = result.GetCompilationStatus(); if (status != shaderc_compilation_status_success) { const std::string &status_name = shaderc_compilation_status_name(status); const std::string &stage_name = get_shader_type_name(type); spdlog::error("shaderc failed to build {} shader due to a ({}) with {} errors and {} warnings:\n {}", stage_name, status_name, result.GetNumErrors(), result.GetNumWarnings(), result.GetErrorMessage()); return {}; } if (result.GetNumWarnings() > 0) { spdlog::warn("shaderc caught {} warnings when compilng {}\n {}", result.GetNumWarnings(), stage_name, result.GetErrorMessage()); } std::vector<uint32_t> ret{ result.begin(), result.end() }; return ret; } std::vector<uint32_t> AbstractShader::compile_glsl_from_path(const std::string &path, ShaderType type) const { QFile file(path.c_str()); if (!file.open(QFile::ReadOnly | QIODevice::Text)) { spdlog::error("Was unable to read []", path); return {}; } QTextStream _ts(&file); QString data = _ts.readAll(); return compile_glsl(data.toStdString(), type); } namespace { VkShaderModule make_shader_module(const std::vector<uint32_t> &spirv) { VkShaderModuleCreateInfo createInfo{ .sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, .codeSize = sizeof(uint32_t) * spirv.size(), .pCode = spirv.data() }; VkShaderModule module; if (vkCreateShaderModule(device, &createInfo, nullptr, &module) != VK_SUCCESS) { } } }// namespace void AbstractShader::make_shader() { auto vs_spirv = vert_spirv(); auto fs_spirv = frag_spirv(); auto vs_module = make_shader_module(vs_spirv); auto fs_module = make_shader_module(fs_spirv); } }// namespace balsa::visualization::shaders
36.401515
209
0.678668
[ "object", "vector" ]
3b4dc950297cec4deefd30523f4518d6e98c291d
9,450
cpp
C++
src/optimization/models/LAV.cpp
sg0/Elemental
614f02509690449b553451e36bc78e7e132ea517
[ "BSD-3-Clause" ]
1
2015-12-08T22:54:37.000Z
2015-12-08T22:54:37.000Z
src/optimization/models/LAV.cpp
sg0/Elemental
614f02509690449b553451e36bc78e7e132ea517
[ "BSD-3-Clause" ]
null
null
null
src/optimization/models/LAV.cpp
sg0/Elemental
614f02509690449b553451e36bc78e7e132ea517
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2009-2015, Jack Poulson All rights reserved. This file is part of Elemental and is under the BSD 2-Clause License, which can be found in the LICENSE file in the root directory, or at http://opensource.org/licenses/BSD-2-Clause */ #include "El.hpp" // Least Absolute Value (LAV) regression minimizes the one norm of the // residual of a system of equations, i.e., // // min || A x - b ||_1. // // Real instances of the problem are expressable as a Linear Program [1] via // // min 1^T (u + v) // s.t. [A, I, -I] [x; u; v] = b, u, v >= 0 // // which, in affine standard form, becomes // // min [0; 1; 1]^T [x; u; v] // s.t. [A, I, -I] | x | = b, | 0 -I 0 | | x | <= | 0 |. // | u | | 0 0 -I | | u | | 0 | // | v | | v | // // [1] // A. Charnes, W. W. Cooper, and R. O. Ferguson, // "Optimal estimation of executive compensation by linear programming", // Management Science, Vol. 1, No. 2, pp. 138--151, 1955. // namespace El { template<typename Real> void LAV ( const Matrix<Real>& A, const Matrix<Real>& b, Matrix<Real>& x, const lp::affine::Ctrl<Real>& ctrl ) { DEBUG_ONLY(CallStackEntry cse("LAV")) const Int m = A.Height(); const Int n = A.Width(); const Range<Int> xInd(0,n), uInd(n,n+m), vInd(n+m,n+2*m); Matrix<Real> c, AHat, G, h; // c := [0;1;1] // ============ Zeros( c, n+2*m, 1 ); auto cuv = c( IR(n,n+2*m), IR(0,1) ); Fill( cuv, Real(1) ); // \hat A := [A, I, -I] // ==================== Zeros( AHat, m, n+2*m ); auto AHatx = AHat( IR(0,m), xInd ); auto AHatu = AHat( IR(0,m), uInd ); auto AHatv = AHat( IR(0,m), vInd ); AHatx = A; FillDiagonal( AHatu, Real( 1) ); FillDiagonal( AHatv, Real(-1) ); // G := | 0 -I 0 | // | 0 0 -I | // ================ Zeros( G, 2*m, n+2*m ); auto Guv = G( IR(0,2*m), IR(n,n+2*m) ); FillDiagonal( Guv, Real(-1) ); // h := | 0 | // | 0 | // ========== Zeros( h, 2*m, 1 ); // Solve the affine linear program // =============================== Matrix<Real> xHat, y, z, s; LP( AHat, G, b, c, h, xHat, y, z, s, ctrl ); // Extract x // ========== x = xHat( xInd, IR(0,1) ); } template<typename Real> void LAV ( const AbstractDistMatrix<Real>& A, const AbstractDistMatrix<Real>& b, AbstractDistMatrix<Real>& x, const lp::affine::Ctrl<Real>& ctrl ) { DEBUG_ONLY(CallStackEntry cse("LAV")) const Int m = A.Height(); const Int n = A.Width(); const Grid& g = A.Grid(); const Range<Int> xInd(0,n), uInd(n,n+m), vInd(n+m,n+2*m); DistMatrix<Real> c(g), AHat(g), G(g), h(g); // c := [0;1;1] // ============ Zeros( c, n+2*m, 1 ); auto cuv = c( IR(n,n+2*m), IR(0,1) ); Fill( cuv, Real(1) ); // \hat A := [A, I, -I] // ==================== Zeros( AHat, m, n+2*m ); auto AHatx = AHat( IR(0,m), xInd ); auto AHatu = AHat( IR(0,m), uInd ); auto AHatv = AHat( IR(0,m), vInd ); AHatx = A; FillDiagonal( AHatu, Real( 1) ); FillDiagonal( AHatv, Real(-1) ); // G := | 0 -I 0 | // | 0 0 -I | // ================ Zeros( G, 2*m, n+2*m ); auto Guv = G( IR(0,2*m), IR(n,n+2*m) ); FillDiagonal( Guv, Real(-1) ); // h := | 0 | // | 0 | // ========== Zeros( h, 2*m, 1 ); // Solve the affine linear program // =============================== DistMatrix<Real> xHat(g), y(g), z(g), s(g); LP( AHat, G, b, c, h, xHat, y, z, s, ctrl ); // Extract x // ========= Copy( xHat( xInd, IR(0,1) ), x ); } template<typename Real> void LAV ( const SparseMatrix<Real>& A, const Matrix<Real>& b, Matrix<Real>& x, const lp::affine::Ctrl<Real>& ctrl ) { DEBUG_ONLY(CallStackEntry cse("LAV")) const Int m = A.Height(); const Int n = A.Width(); const Range<Int> xInd(0,n), uInd(n,n+m), vInd(n+m,n+2*m); SparseMatrix<Real> AHat, G; Matrix<Real> c, h; // c := [0;1;1] // ============ Zeros( c, n+2*m, 1 ); auto cuv = c( IR(n,n+2*m), IR(0,1) ); Fill( cuv, Real(1) ); // \hat A := [A, I, -I] // ==================== Zeros( AHat, m, n+2*m ); const Int numEntriesA = A.NumEntries(); AHat.Reserve( numEntriesA + 2*m ); for( Int e=0; e<numEntriesA; ++e ) AHat.QueueUpdate( A.Row(e), A.Col(e), A.Value(e) ); for( Int i=0; i<m; ++i ) { AHat.QueueUpdate( i, i+n, Real( 1) ); AHat.QueueUpdate( i, i+n+m, Real(-1) ); } AHat.MakeConsistent(); // G := | 0 -I 0 | // | 0 0 -I | // ================ Zeros( G, 2*m, n+2*m ); G.Reserve( G.Height() ); for( Int i=0; i<2*m; ++i ) G.QueueUpdate( i, i+n, Real(-1) ); G.MakeConsistent(); // h := | 0 | // | 0 | // ========== Zeros( h, 2*m, 1 ); // Solve the affine linear program // =============================== Matrix<Real> xHat, y, z, s; LP( AHat, G, b, c, h, xHat, y, z, s, ctrl ); // Extract x // ========= x = xHat( xInd, IR(0,1) ); } template<typename Real> void LAV ( const DistSparseMatrix<Real>& A, const DistMultiVec<Real>& b, DistMultiVec<Real>& x, const lp::affine::Ctrl<Real>& ctrl ) { DEBUG_ONLY(CallStackEntry cse("LAV")) const Int m = A.Height(); const Int n = A.Width(); mpi::Comm comm = A.Comm(); DistSparseMatrix<Real> AHat(comm), G(comm); DistMultiVec<Real> c(comm), h(comm); // c := [0;1;1] // ============ Zeros( c, n+2*m, 1 ); for( Int iLoc=0; iLoc<c.LocalHeight(); ++iLoc ) if( c.GlobalRow(iLoc) >= n ) c.SetLocal( iLoc, 0, Real(1) ); // \hat A := [A, I, -I] // ==================== Zeros( AHat, m, n+2*m ); const Int numLocalEntriesA = A.NumLocalEntries(); AHat.Reserve( numLocalEntriesA + 2*AHat.LocalHeight() ); for( Int e=0; e<numLocalEntriesA; ++e ) AHat.QueueLocalUpdate ( A.Row(e)-AHat.FirstLocalRow(), A.Col(e), A.Value(e) ); for( Int iLoc=0; iLoc<AHat.LocalHeight(); ++iLoc ) { const Int i = AHat.GlobalRow(iLoc); AHat.QueueLocalUpdate( iLoc, i+n, Real( 1) ); AHat.QueueLocalUpdate( iLoc, i+n+m, Real(-1) ); } AHat.MakeConsistent(); // G := | 0 -I 0 | // | 0 0 -I | // ================ Zeros( G, 2*m, n+2*m ); G.Reserve( G.LocalHeight() ); for( Int iLoc=0; iLoc<G.LocalHeight(); ++iLoc ) G.QueueLocalUpdate( iLoc, G.GlobalRow(iLoc)+n, Real(-1) ); G.MakeConsistent(); // h := | 0 | // | 0 | // ========== Zeros( h, 2*m, 1 ); // Solve the affine QP // =================== DistMultiVec<Real> xHat(comm), y(comm), z(comm), s(comm); LP( AHat, G, b, c, h, xHat, y, z, s, ctrl ); // Extract x // ========= Zeros( x, n, 1 ); // Determine the send and recv counts/offsets // ------------------------------------------ const Int commSize = mpi::Size(comm); vector<int> sendCounts(commSize,0); for( Int iLoc=0; iLoc<xHat.LocalHeight(); ++iLoc ) { const Int i = xHat.GlobalRow(iLoc); if( i < n ) ++sendCounts[ x.RowOwner(i) ]; else break; } vector<int> recvCounts(commSize); mpi::AllToAll( sendCounts.data(), 1, recvCounts.data(), 1, comm ); vector<int> sendOffsets, recvOffsets; const int totalSend = Scan( sendCounts, sendOffsets ); const int totalRecv = Scan( recvCounts, recvOffsets ); // Pack the data // ------------- vector<Int> sSendBuf(totalSend); vector<Real> vSendBuf(totalSend); auto offsets = sendOffsets; for( Int iLoc=0; iLoc<xHat.LocalHeight(); ++iLoc ) { const Int i = xHat.GlobalRow(iLoc); if( i < n ) { const int owner = x.RowOwner(i); sSendBuf[offsets[owner]] = i; vSendBuf[offsets[owner]] = xHat.GetLocal(iLoc,0); ++offsets[owner]; } else break; } // Exchange the data // ----------------- vector<Int> sRecvBuf(totalRecv); vector<Real> vRecvBuf(totalRecv); mpi::AllToAll ( sSendBuf.data(), sendCounts.data(), sendOffsets.data(), sRecvBuf.data(), recvCounts.data(), recvOffsets.data(), comm ); mpi::AllToAll ( vSendBuf.data(), sendCounts.data(), sendOffsets.data(), vRecvBuf.data(), recvCounts.data(), recvOffsets.data(), comm ); // Unpack the data // --------------- for( Int e=0; e<totalRecv; ++e ) x.UpdateLocal( sRecvBuf[e]-x.FirstLocalRow(), 0, vRecvBuf[e] ); } #define PROTO(Real) \ template void LAV \ ( const Matrix<Real>& A, const Matrix<Real>& b, \ Matrix<Real>& x, \ const lp::affine::Ctrl<Real>& ctrl ); \ template void LAV \ ( const AbstractDistMatrix<Real>& A, const AbstractDistMatrix<Real>& b, \ AbstractDistMatrix<Real>& x, \ const lp::affine::Ctrl<Real>& ctrl ); \ template void LAV \ ( const SparseMatrix<Real>& A, const Matrix<Real>& b, \ Matrix<Real>& x, \ const lp::affine::Ctrl<Real>& ctrl ); \ template void LAV \ ( const DistSparseMatrix<Real>& A, const DistMultiVec<Real>& b, \ DistMultiVec<Real>& x, \ const lp::affine::Ctrl<Real>& ctrl ); #define EL_NO_INT_PROTO #define EL_NO_COMPLEX_PROTO #include "El/macros/Instantiate.h" } // namepace elem
28.98773
77
0.499577
[ "vector" ]
3b595f2a985206d92aa6ae145d371b1ab0d68aa0
33,224
cpp
C++
code/scripting/scripting.cpp
the-maddin/fs2open.github.com
866a7c40df5d6674a50788e56b605c172b7a5163
[ "Unlicense" ]
1
2015-04-24T12:37:48.000Z
2015-04-24T12:37:48.000Z
code/scripting/scripting.cpp
JohnAFernandez/fs2open.github.com
c0bb5bc8eb640c3932aefd3dfad1fd4758571cff
[ "Unlicense" ]
4
2015-03-30T20:33:03.000Z
2020-06-03T08:48:35.000Z
code/scripting/scripting.cpp
JohnAFernandez/fs2open.github.com
c0bb5bc8eb640c3932aefd3dfad1fd4758571cff
[ "Unlicense" ]
1
2015-01-05T12:19:23.000Z
2015-01-05T12:19:23.000Z
#include "scripting/scripting.h" #include "globalincs/systemvars.h" #include "globalincs/version.h" #include "ade.h" #include "ade_args.h" #include "freespace.h" #include "hook_api.h" #include "bmpman/bmpman.h" #include "controlconfig/controlsconfig.h" #include "gamesequence/gamesequence.h" #include "hud/hud.h" #include "io/key.h" #include "mission/missioncampaign.h" #include "parse/parselo.h" #include "scripting/doc_html.h" #include "scripting/doc_json.h" #include "scripting/scripting_doc.h" #include "ship/ship.h" #include "tracing/tracing.h" #include "weapon/beam.h" #include "weapon/weapon.h" using namespace scripting; // tehe. Declare the main event script_state Script_system("FS2_Open Scripting"); bool Output_scripting_meta = false; bool Output_scripting_json = false; flag_def_list Script_conditions[] = { {"State", CHC_STATE, 0}, {"Campaign", CHC_CAMPAIGN, 0}, {"Mission", CHC_MISSION, 0}, {"Object Type", CHC_OBJECTTYPE, 0}, {"Ship", CHC_SHIP, 0}, {"Ship class", CHC_SHIPCLASS, 0}, {"Ship type", CHC_SHIPTYPE, 0}, {"Weapon class", CHC_WEAPONCLASS, 0}, {"KeyPress", CHC_KEYPRESS, 0}, {"Action", CHC_ACTION, 0}, {"Version", CHC_VERSION, 0}, {"Application", CHC_APPLICATION, 0}, }; int Num_script_conditions = sizeof(Script_conditions) / sizeof(flag_def_list); class BuiltinHook : public scripting::HookBase { public: BuiltinHook(SCP_string hookName, int32_t hookId) : HookBase(std::move(hookName), SCP_string(), SCP_vector<HookVariableDocumentation>(), hookId) { } ~BuiltinHook() override = default; bool isOverridable() const override { return true; } }; // clang-format off static USED_VARIABLE SCP_vector<std::shared_ptr<BuiltinHook>> Script_actions { std::make_shared<BuiltinHook>("On Game Init", CHA_GAMEINIT ), std::make_shared<BuiltinHook>("On Splash Screen", CHA_SPLASHSCREEN ), std::make_shared<BuiltinHook>("On State Start", CHA_ONSTATESTART ), std::make_shared<BuiltinHook>("On Action", CHA_ONACTION ), std::make_shared<BuiltinHook>("On Action Stopped", CHA_ONACTIONSTOPPED ), std::make_shared<BuiltinHook>("On Key Pressed", CHA_KEYPRESSED ), std::make_shared<BuiltinHook>("On Key Released", CHA_KEYRELEASED ), std::make_shared<BuiltinHook>("On Mouse Moved", CHA_MOUSEMOVED ), std::make_shared<BuiltinHook>("On Mouse Pressed", CHA_MOUSEPRESSED ), std::make_shared<BuiltinHook>("On Mouse Released", CHA_MOUSERELEASED ), std::make_shared<BuiltinHook>("On State End", CHA_ONSTATEEND ), std::make_shared<BuiltinHook>("On Mission Start", CHA_MISSIONSTART ), std::make_shared<BuiltinHook>("On HUD Draw", CHA_HUDDRAW ), std::make_shared<BuiltinHook>("On Ship Collision", CHA_COLLIDESHIP ), std::make_shared<BuiltinHook>("On Weapon Collision", CHA_COLLIDEWEAPON ), std::make_shared<BuiltinHook>("On Debris Collision", CHA_COLLIDEDEBRIS ), std::make_shared<BuiltinHook>("On Asteroid Collision", CHA_COLLIDEASTEROID ), std::make_shared<BuiltinHook>("On Object Render", CHA_OBJECTRENDER ), std::make_shared<BuiltinHook>("On Death", CHA_DEATH ), std::make_shared<BuiltinHook>("On Mission End", CHA_MISSIONEND ), std::make_shared<BuiltinHook>("On Weapon Delete", CHA_ONWEAPONDELETE ), std::make_shared<BuiltinHook>("On Weapon Equipped", CHA_ONWPEQUIPPED ), std::make_shared<BuiltinHook>("On Weapon Fired", CHA_ONWPFIRED ), std::make_shared<BuiltinHook>("On Weapon Selected", CHA_ONWPSELECTED ), std::make_shared<BuiltinHook>("On Weapon Deselected", CHA_ONWPDESELECTED ), std::make_shared<BuiltinHook>("On Gameplay Start", CHA_GAMEPLAYSTART ), std::make_shared<BuiltinHook>("On Turret Fired", CHA_ONTURRETFIRED ), std::make_shared<BuiltinHook>("On Primary Fire", CHA_PRIMARYFIRE ), std::make_shared<BuiltinHook>("On Secondary Fire", CHA_SECONDARYFIRE ), std::make_shared<BuiltinHook>("On Ship Arrive", CHA_ONSHIPARRIVE ), std::make_shared<BuiltinHook>("On Beam Collision", CHA_COLLIDEBEAM ), std::make_shared<BuiltinHook>("On Afterburner Engage", CHA_AFTERBURNSTART ), std::make_shared<BuiltinHook>("On Afterburner Stop", CHA_AFTERBURNEND ), std::make_shared<BuiltinHook>("On Beam Fire", CHA_BEAMFIRE ), std::make_shared<BuiltinHook>("On Simulation", CHA_SIMULATION ), std::make_shared<BuiltinHook>("On Load Screen", CHA_LOADSCREEN ), std::make_shared<BuiltinHook>("On Campaign Mission Accept", CHA_CMISSIONACCEPT ), std::make_shared<BuiltinHook>("On Ship Depart", CHA_ONSHIPDEPART ), std::make_shared<BuiltinHook>("On Weapon Created", CHA_ONWEAPONCREATED ), std::make_shared<BuiltinHook>("On Waypoints Done", CHA_ONWAYPOINTSDONE ), std::make_shared<BuiltinHook>("On Subsystem Destroyed", CHA_ONSUBSYSDEATH ), std::make_shared<BuiltinHook>("On Goals Cleared", CHA_ONGOALSCLEARED ), std::make_shared<BuiltinHook>("On Briefing Stage", CHA_ONBRIEFSTAGE ), // DO NOT ADD NEW HOOKS HERE, see scripting.h for a more in-depth explanation }; static HookVariableDocumentation GlobalVariables[] = { { "Player", "object", "The player object in a mission. Does not need to be a ship (e.g. in multiplayer). Not " "present if not in a game play state." }, }; // clang-format on int scripting_state_inited = 0; //*************************Scripting init and handling************************* // ditto bool script_hook_valid(script_hook* hook) { return hook->hook_function.function.isValid(); } void script_parse_table(const char* filename) { script_state* st = &Script_system; try { read_file_text(filename, CF_TYPE_TABLES); reset_parse(); if (optional_string("#Global Hooks")) { if (optional_string("$Global:")) { st->ParseGlobalChunk(CHA_ONFRAME, "Global"); } if (optional_string("$Splash:")) { st->ParseGlobalChunk(CHA_SPLASHSCREEN, "Splash"); } if (optional_string("$GameInit:")) { st->ParseGlobalChunk(CHA_GAMEINIT, "GameInit"); } if (optional_string("$Simulation:")) { st->ParseGlobalChunk(CHA_SIMULATION, "Simulation"); } if (optional_string("$HUD:")) { st->ParseGlobalChunk(CHA_HUDDRAW, "HUD"); } required_string("#End"); } if (optional_string("#Conditional Hooks")) { while (st->ParseCondition(filename)); required_string("#End"); } } catch (const parse::ParseException& e) { mprintf(("TABLES: Unable to parse '%s'! Error message = %s.\n", filename, e.what())); return; } } void script_parse_lua_script(const char *filename) { using namespace luacpp; CFILE *cfp = cfopen(filename, "rb", CFILE_NORMAL, CF_TYPE_TABLES); if(cfp == nullptr) { Warning(LOCATION, "Could not open lua script file '%s'", filename); return; } int len = cfilelength(cfp); SCP_string source; source.resize((size_t) len); cfread(&source[0], len, 1, cfp); cfclose(cfp); try { auto function = LuaFunction::createFromCode(Script_system.GetLuaSession(), source, filename); function.setErrorFunction(LuaFunction::createFromCFunction(Script_system.GetLuaSession(), ade_friendly_error)); script_function func; func.language = SC_LUA; func.function = function; Script_system.AddGameInitFunction(func); } catch (const LuaException& e) { LuaError(Script_system.GetLuaSession(), "Failed to parse %s: %s", filename, e.what()); } } // Initializes the (global) scripting system, as well as any subsystems. // script_close is handled by destructors void script_init() { mprintf(("SCRIPTING: Beginning initialization sequence...\n")); mprintf(("SCRIPTING: Beginning Lua initialization...\n")); Script_system.CreateLuaState(); if (Output_scripting_meta || Output_scripting_json) { const auto doc = Script_system.OutputDocumentation([](const SCP_string& error) { mprintf(("Scripting documentation: Error while parsing\n%s(This is only relevant for coders)\n\n", error.c_str())); }); if (Output_scripting_meta) { mprintf(("SCRIPTING: Outputting scripting metadata...\n")); scripting::output_html_doc(doc, "scripting.html"); } if (Output_scripting_json) { mprintf(("SCRIPTING: Outputting scripting metadata in JSON format...\n")); scripting::output_json_doc(doc, "scripting.json"); } } mprintf(("SCRIPTING: Beginning main hook parse sequence....\n")); script_parse_table("scripting.tbl"); parse_modular_table(NOX("*-sct.tbm"), script_parse_table); mprintf(("SCRIPTING: Parsing pure Lua scripts\n")); parse_modular_table(NOX("*-sct.lua"), script_parse_lua_script); mprintf(("SCRIPTING: Inititialization complete.\n")); } /* //WMC - Doesn't work as debug console interferes with any non-alphabetic chars. DCF(script, "Evaluates a line of scripting") { if(Dc_command) { dc_get_arg(ARG_STRING); Script_system.EvalString(Dc_arg); } if(Dc_help) { dc_printf("Usage: script <script\n"); dc_printf("<script> -- Scripting to evaluate.\n"); } } */ //*************************CLASS: ConditionedScript************************* extern char Game_current_mission_filename[]; bool ConditionedHook::AddCondition(script_condition *sc) { //Since string comparisons are expensive and these hooks have to be checked very frequently //where possible whatever string comparison is done here and the outcome stored for later //nature of value stored depends on condition type. switch (sc->condition_type) { case CHC_SHIPCLASS: sc->condition_cached_value = ship_info_lookup(sc->condition_string.c_str()); break; case CHC_STATE: sc->condition_cached_value = gameseq_get_state_idx(sc->condition_string.c_str()); break; case CHC_WEAPONCLASS: sc->condition_cached_value = weapon_info_lookup(sc->condition_string.c_str()); break; case CHC_OBJECTTYPE: for (int i = 0; i < MAX_OBJECT_TYPES; i++) { if (stricmp(Object_type_names[i], sc->condition_string.c_str()) == 0) { sc->condition_cached_value = i; break; } } break; case CHC_VERSION: { char buf[32]; sc->condition_cached_value = 0; sprintf(buf, "%i.%i.%i", FS_VERSION_MAJOR, FS_VERSION_MINOR, FS_VERSION_BUILD); if (stricmp(buf, sc->condition_string.c_str()) == 0) { sc->condition_cached_value = 1; } else if (FS_VERSION_BUILD == 0) //In case some people are lazy and say "3.7" instead of "3.7.0" or something { sprintf(buf, "%i.%i", FS_VERSION_MAJOR, FS_VERSION_MINOR); if (stricmp(buf, sc->condition_string.c_str()) == 0) { sc->condition_cached_value = 1; } } break; } case CHC_APPLICATION: { sc->condition_cached_value = 1; if (Fred_running) { if (stricmp("FRED2_Open", sc->condition_string.c_str()) != 0 && stricmp("FRED2Open", sc->condition_string.c_str()) != 0 && stricmp("FRED 2", sc->condition_string.c_str()) != 0 && stricmp("FRED", sc->condition_string.c_str()) != 0) sc->condition_cached_value = 0; } else { if (stricmp("FS2_Open", sc->condition_string.c_str()) != 0 && stricmp("FS2Open", sc->condition_string.c_str()) != 0 && stricmp("Freespace 2", sc->condition_string.c_str()) != 0 && stricmp("Freespace", sc->condition_string.c_str()) != 0) sc->condition_cached_value = 0; } break; } default: break; } Conditions.push_back(*sc); return true; } bool ConditionedHook::AddAction(script_action *sa) { if(!script_hook_valid(&sa->hook)) return false; Actions.push_back(*sa); return true; } bool ConditionedHook::ConditionsValid(int action, object *objp, int more_data) { //Return false if any conditions are not met //Never return true inside the loop, or you will be potentially skipping other conditions on the hook. ship_info *sip; for(auto & scp : Conditions) { switch(scp.condition_type) { case CHC_STATE: if(gameseq_get_depth() < 0) return false; if(gameseq_get_state() != scp.condition_cached_value) return false; break; case CHC_SHIPTYPE: if(objp == NULL || objp->type != OBJ_SHIP) return false; sip = &Ship_info[Ships[objp->instance].ship_info_index]; if(sip->class_type < 0) return false; if(stricmp(Ship_types[sip->class_type].name, scp.condition_string.c_str()) != 0) return false; break; case CHC_SHIPCLASS: //scp.condition_cached_value holds the weapon_info_index of the requested weapon class if(objp == NULL || objp->type != OBJ_SHIP) return false; if(!(Ships[objp->instance].ship_info_index == scp.condition_cached_value)) return false; break; case CHC_SHIP: if(objp == NULL || objp->type != OBJ_SHIP) return false; if(stricmp(Ships[objp->instance].ship_name, scp.condition_string.c_str()) != 0) return false; break; case CHC_MISSION: { //WMC - Get mission filename with Mission_filename //I don't use Game_current_mission_filename, because //Mission_filename is valid in both fs2_open and FRED size_t len = strlen(Mission_filename); if(!len) return false; if(len > 4 && !stricmp(&Mission_filename[len-4], ".fs2")) len -= 4; if(strnicmp(scp.condition_string.c_str(), Mission_filename, len) != 0) return false; break; } case CHC_CAMPAIGN: { size_t len = strlen(Campaign.filename); if(!len) return false; if(len > 4 && !stricmp(&Mission_filename[len-4], ".fc2")) len -= 4; if(strnicmp(scp.condition_string.c_str(), Mission_filename, len) != 0) return false; break; } case CHC_WEAPONCLASS: { //scp.condition_cached_value holds the weapon_info_index of the requested weapon class if (action == CHA_COLLIDEWEAPON) { return(more_data == scp.condition_cached_value); } else if (!(action == CHA_ONWPSELECTED || action == CHA_ONWPDESELECTED || action == CHA_ONWPEQUIPPED || action == CHA_ONWPFIRED || action == CHA_ONTURRETFIRED )) { if (objp == NULL || (objp->type != OBJ_WEAPON && objp->type != OBJ_BEAM)) return false; else if (objp->type == OBJ_WEAPON && !(Weapons[objp->instance].weapon_info_index == scp.condition_cached_value)) return false; else if (objp->type == OBJ_BEAM && !(Weapons[objp->instance].weapon_info_index == scp.condition_cached_value)) return false; } else if (objp == NULL || objp->type != OBJ_SHIP) { return false; } else if (action == CHA_ONWEAPONCREATED) { if (objp == nullptr || objp->type != OBJ_WEAPON) return false; } else { // Okay, if we're still here, then objp is both valid and a ship ship* shipp = &Ships[objp->instance]; bool primary = false, secondary = false, prev_primary = false, prev_secondary = false; switch (action) { case CHA_ONWPSELECTED: { if (shipp->weapons.current_primary_bank >= 0) { primary = shipp->weapons.primary_bank_weapons[shipp->weapons.current_primary_bank] == scp.condition_cached_value; } if (shipp->weapons.current_secondary_bank >= 0) { secondary = shipp->weapons.secondary_bank_weapons[shipp->weapons.current_secondary_bank] == scp.condition_cached_value; } if (!(primary || secondary)) { return false; } if ((shipp->flags[Ship::Ship_Flags::Primary_linked]) && primary && (Weapon_info[shipp->weapons.primary_bank_weapons[shipp->weapons.current_primary_bank]].wi_flags[Weapon::Info_Flags::Nolink])) { return false; } break; } case CHA_ONWPDESELECTED: { if (shipp->weapons.current_primary_bank >= 0) { primary = shipp->weapons.primary_bank_weapons[shipp->weapons.current_primary_bank] == scp.condition_cached_value; } if (shipp->weapons.previous_primary_bank >= 0) { prev_primary = shipp->weapons.primary_bank_weapons[shipp->weapons.previous_primary_bank] == scp.condition_cached_value; } if (shipp->weapons.current_secondary_bank >= 0) { secondary = shipp->weapons.secondary_bank_weapons[shipp->weapons.current_secondary_bank] == scp.condition_cached_value; } if (shipp->weapons.previous_secondary_bank >= 0) { prev_secondary = shipp->weapons.secondary_bank_weapons[shipp->weapons.previous_secondary_bank] == scp.condition_cached_value; } if (!( (shipp->flags[Ship::Ship_Flags::Primary_linked]) && prev_primary && (Weapon_info[shipp->weapons.primary_bank_weapons[shipp->weapons.previous_primary_bank]].wi_flags[Weapon::Info_Flags::Nolink]) )) { return false; } if (!prev_secondary && !secondary && !prev_primary && !primary) return false; if ((!prev_secondary && !secondary) && (prev_primary && primary)) return false; if ((!prev_secondary && !secondary) && (!prev_primary && primary)) return false; if ((!prev_primary && !primary) && (prev_secondary && secondary)) return false; if ((!prev_primary && !primary) && (!prev_secondary && secondary)) return false; break; } case CHA_ONWPEQUIPPED: { bool equipped = false; for (int j = 0; j < MAX_SHIP_PRIMARY_BANKS && !equipped; j++) { if (shipp->weapons.primary_bank_weapons[j] > 0 && shipp->weapons.primary_bank_weapons[j] < weapon_info_size()) { equipped = shipp->weapons.primary_bank_weapons[j] == scp.condition_cached_value; } } for (int j = 0; j < MAX_SHIP_SECONDARY_BANKS && !equipped; j++) { if (shipp->weapons.secondary_bank_weapons[j] >= 0 && (shipp->weapons.secondary_bank_weapons[j] < weapon_info_size())) { equipped = shipp->weapons.secondary_bank_weapons[j] == scp.condition_cached_value; } } if (!equipped) { return false; } break; } case CHA_ONWPFIRED: { if (more_data == 1) { primary = shipp->weapons.primary_bank_weapons[shipp->weapons.current_primary_bank] == scp.condition_cached_value; secondary = false; } else { primary = false; secondary = shipp->weapons.secondary_bank_weapons[shipp->weapons.current_secondary_bank] == scp.condition_cached_value; } if ( (shipp->flags[Ship::Ship_Flags::Primary_linked]) && primary && (Weapon_info[shipp->weapons.primary_bank_weapons[shipp->weapons.current_primary_bank]].wi_flags[Weapon::Info_Flags::Nolink])) { return false; } if (more_data == 1 && !primary) { return false; } else if (more_data != 1 && !secondary) { return false; } break; } case CHA_ONTURRETFIRED: { if(shipp->last_fired_turret->last_fired_weapon_info_index != scp.condition_cached_value) return false; break; } case CHA_PRIMARYFIRE: { if (shipp->weapons.primary_bank_weapons[shipp->weapons.current_primary_bank] != scp.condition_cached_value) return false; break; } case CHA_SECONDARYFIRE: { if(shipp->weapons.secondary_bank_weapons[shipp->weapons.current_secondary_bank] != scp.condition_cached_value) return false; break; } case CHA_BEAMFIRE: { if(more_data != scp.condition_cached_value) return false; break; } default: break; } } // case CHC_WEAPONCLASS break; } case CHC_OBJECTTYPE: if(objp == NULL) return false; if(objp->type != scp.condition_cached_value) return false; break; case CHC_KEYPRESS: { extern int Current_key_down; if(gameseq_get_depth() < 0) return false; if(Current_key_down == 0) return false; //WMC - could be more efficient, but whatever. if(stricmp(textify_scancode(Current_key_down), scp.condition_string.c_str()) != 0) return false; break; } case CHC_ACTION: { if(gameseq_get_depth() < 0) return false; int action_index = more_data; if (action_index <= 0 || stricmp(scp.condition_string.c_str(), Control_config[action_index].text.c_str()) != 0) return false; break; } case CHC_VERSION: { //Already evaluated on script load, stored value is 1 if application matches condition, 0 if not. if(scp.condition_cached_value == 0) { return false; } break; } case CHC_APPLICATION: { //Already evaluated on script load, stored value is 1 if application matches condition, 0 if not. if(scp.condition_cached_value == 0) { return false; } } default: break; } } return true; } bool ConditionedHook::IsOverride(script_state* sys, int action) { Assert(sys != NULL); // bool b = false; //Do the actions for(SCP_vector<script_action>::iterator sap = Actions.begin(); sap != Actions.end(); ++sap) { if (sap->action_type == action) { if (sys->IsOverride(sap->hook)) return true; } } return false; } bool ConditionedHook::Run(class script_state* sys, int action) { Assert(sys != NULL); // Do the actions for (auto & Action : Actions) { if (Action.action_type == action) { sys->RunBytecode(Action.hook.hook_function); } } return true; } //*************************CLASS: script_state************************* //Most of the icky stuff is here. Lots of #ifdefs //WMC - defined in parse/scripting.h void script_state::SetHookObject(const char *name, object *objp) { SetHookObjects(1, name, objp); } void script_state::SetHookObjects(int num, ...) { if (LuaState == nullptr) { return; } va_list vl; va_start(vl, num); for (int i = 0; i < num; i++) { char* name = va_arg(vl, char*); object* objp = va_arg(vl, object*); ade_set_object_with_breed(LuaState, OBJ_INDEX(objp)); auto reference = luacpp::UniqueLuaReference::create(LuaState); lua_pop(LuaState, 1); // Remove object value from the stack HookVariableValues[name].push_back(std::move(reference)); } va_end(vl); } void script_state::RemHookVar(const char* name) { this->RemHookVars({name}); } void script_state::RemHookVars(std::initializer_list<SCP_string> names) { if (LuaState != nullptr) { for (const auto& hookVar : names) { if (HookVariableValues[hookVar].empty()) { // Nothing to do continue; } HookVariableValues[hookVar].pop_back(); } } } const SCP_unordered_map<SCP_string, SCP_vector<luacpp::LuaReference>>& script_state::GetHookVariableReferences() { return HookVariableValues; } int script_state::LoadBm(const char* name) { for(int i = 0; i < (int)ScriptImages.size(); i++) { if(!stricmp(name, ScriptImages[i].fname)) return ScriptImages[i].handle; } image_desc id; int idx = bm_load(name); if(idx > -1) { id.handle = idx; strcpy_s(id.fname, name); ScriptImages.push_back(id); } return idx; } void script_state::UnloadImages() { for(int i = 0; i < (int)ScriptImages.size(); i++) { bm_release(ScriptImages[i].handle); } ScriptImages.clear(); } int script_state::RunCondition(int action, object* objp, int more_data) { TRACE_SCOPE(tracing::LuaHooks); int num = 0; if (LuaState == nullptr) { return num; } for(SCP_vector<ConditionedHook>::iterator chp = ConditionalHooks.begin(); chp != ConditionalHooks.end(); ++chp) { if(chp->ConditionsValid(action, objp, more_data)) { chp->Run(this, action); num++; } } return num; } bool script_state::IsConditionOverride(int action, object *objp) { //bool b = false; for(SCP_vector<ConditionedHook>::iterator chp = ConditionalHooks.begin(); chp != ConditionalHooks.end(); ++chp) { if(chp->ConditionsValid(action, objp)) { if(chp->IsOverride(this, action)) return true; } } return false; } void script_state::EndFrame() { EndLuaFrame(); } void script_state::Clear() { // Free all lua value references ConditionalHooks.clear(); HookVariableValues.clear(); if (LuaState != nullptr) { OnStateDestroy(LuaState); lua_close(LuaState); } StateName[0] = '\0'; Langs = 0; //Don't close this yet LuaState = NULL; LuaLibs = NULL; } script_state::script_state(const char *name) { auto len = sizeof(StateName); strncpy(StateName, name, len); StateName[len - 1] = 0; Langs = 0; LuaState = NULL; LuaLibs = NULL; } script_state::~script_state() { Clear(); } void script_state::SetLuaSession(lua_State *L) { if (LuaState != nullptr) { lua_close(LuaState); } LuaState = L; if (LuaState != nullptr) { Langs |= SC_LUA; } else if(Langs & SC_LUA) { Langs &= ~SC_LUA; } } ScriptingDocumentation script_state::OutputDocumentation(const scripting::DocumentationErrorReporter& errorReporter) { ScriptingDocumentation doc; doc.name = StateName; // Conditions doc.conditions.reserve(static_cast<size_t>(Num_script_conditions)); for (int32_t i = 0; i < Num_script_conditions; i++) { doc.conditions.emplace_back(Script_conditions[i].name); } // Global variables doc.globalVariables.assign(std::begin(GlobalVariables), std::end(GlobalVariables)); // Actions auto sortedHooks = scripting::getHooks(); std::sort(sortedHooks.begin(), sortedHooks.end(), [](const scripting::HookBase* left, const scripting::HookBase* right) { return left->getHookName() < right->getHookName(); }); for (const auto& hook : sortedHooks) { doc.actions.push_back( {hook->getHookName(), hook->getDescription(), hook->getParameters(), hook->isOverridable()}); } OutputLuaDocumentation(doc, errorReporter); return doc; } void script_state::ParseChunkSub(script_function& script_func, const char* debug_str) { using namespace luacpp; Assert(debug_str != NULL); //Lua script_func.language = SC_LUA; std::string source; std::string function_name(debug_str); if(check_for_string("[[")) { //Lua from file char *filename = alloc_block("[[", "]]"); //Load from file CFILE *cfp = cfopen(filename, "rb", CFILE_NORMAL, CF_TYPE_SCRIPTS ); //WMC - use filename instead of debug_str so that the filename gets passed. function_name = filename; vm_free(filename); if(cfp == NULL) { Warning(LOCATION, "Could not load lua script file '%s'", function_name.c_str()); return; } else { int len = cfilelength(cfp); source.resize((size_t) len); cfread(&source[0], len, 1, cfp); cfclose(cfp); } } else if(check_for_string("[")) { //Lua string // Determine the current line in the file so that the Lua source can begin at the same line as in the table // This will make sure that the line in the error message matches the line number in the table. auto line = get_line_num(); //Allocate raw script char* raw_lua = alloc_block("[", "]", 1); //WMC - minor hack to make sure that the last line gets //executed properly. In testing, I couldn't reproduce Nuke's //crash, so this is here just to be on the safe side. strcat(raw_lua, "\n"); for (auto i = 0; i <= line; ++i) { source += "\n"; } source += raw_lua; vm_free(raw_lua); } else { std::string buf; //Stuff it stuff_string(buf, F_RAW); source = "return "; source += buf; } try { auto function = LuaFunction::createFromCode(LuaState, source, function_name); function.setErrorFunction(LuaFunction::createFromCFunction(LuaState, ade_friendly_error)); script_func.function = function; } catch (const LuaException& e) { LuaError(GetLuaSession(), "%s", e.what()); } } void script_state::ParseChunk(script_hook *dest, const char *debug_str) { static int total_parse_calls = 0; char debug_buf[128]; total_parse_calls++; //DANGER! This code means the debug_str must be used only before parsing if(debug_str == NULL) { sprintf(debug_buf, "script_parse() count %d", total_parse_calls); debug_str = debug_buf; } ParseChunkSub(dest->hook_function, debug_str); if(optional_string("+Override:")) { size_t bufSize = strlen(debug_str) + 10; char *debug_str_over = (char*)vm_malloc(bufSize); strcpy_s(debug_str_over, bufSize, debug_str); strcat_s(debug_str_over, bufSize, " override"); ParseChunkSub(dest->override_function, debug_str_over); vm_free(debug_str_over); } } bool script_state::EvalString(const char* string, const char* debug_str) { using namespace luacpp; size_t string_size = strlen(string); char lastchar = string[string_size - 1]; if (string[0] == '{') { return false; } if (string[0] == '[' && lastchar != ']') { return false; } size_t s_bufSize = string_size + 8; std::string s; s.reserve(s_bufSize); if (string[0] != '[') { s += string; } else { s.assign(string + 1, string + string_size); } SCP_string debug_name; if (debug_str == nullptr) { debug_name = "String: "; debug_name += s; } else { debug_name = debug_str; } try { auto function = LuaFunction::createFromCode(LuaState, s, debug_name); function.setErrorFunction(LuaFunction::createFromCFunction(LuaState, scripting::ade_friendly_error)); try { function.call(LuaState); } catch (const LuaException&) { return false; } } catch (const LuaException& e) { LuaError(GetLuaSession(), "%s", e.what()); return false; } return true; } int script_state::RunBytecode(script_function& hd) { using namespace luacpp; if (!hd.function.isValid()) { return 1; } GR_DEBUG_SCOPE("Lua code"); try { hd.function.call(LuaState); } catch (const LuaException&) { return 0; } return 1; } ConditionalType script_parse_condition() { char buf[NAME_LENGTH]; for (int i = 0; i < Num_script_conditions; i++) { sprintf(buf, "$%s:", Script_conditions[i].name); if(optional_string(buf)) return static_cast<ConditionalType>(Script_conditions[i].def); } return CHC_NONE; } const scripting::HookBase* script_parse_action() { for (const auto& action : scripting::getHooks()) { SCP_string buf; sprintf(buf, "$%s:", action->getHookName().c_str()); if (optional_string(buf.c_str())) return action; } return nullptr; } int32_t scripting_string_to_action(const char* action) { for (const auto& hook : scripting::getHooks()) { if (hook->getHookName() == action) return hook->getHookId(); } return CHA_NONE; } ConditionalType scripting_string_to_condition(const char* condition) { for (int i = 0; i < Num_script_conditions; i++) { if (!stricmp(Script_conditions[i].name, condition)) { return static_cast<ConditionalType>(Script_conditions[i].def); } } return CHC_NONE; } void script_state::ParseGlobalChunk(ConditionalActions hookType, const char* debug_str) { ConditionedHook hook; script_action sat; sat.action_type = hookType; ParseChunk(&sat.hook, debug_str); //Add the action hook.AddAction(&sat); ConditionalHooks.push_back(hook); } bool script_state::ParseCondition(const char *filename) { ConditionedHook *chp = nullptr; for(auto condition = script_parse_condition(); condition != CHC_NONE; condition = script_parse_condition()) { script_condition sct; sct.condition_type = condition; switch(condition) { case CHC_STATE: case CHC_SHIPCLASS: case CHC_SHIPTYPE: case CHC_SHIP: case CHC_MISSION: case CHC_CAMPAIGN: case CHC_WEAPONCLASS: case CHC_OBJECTTYPE: case CHC_VERSION: case CHC_APPLICATION: default: stuff_string(sct.condition_string, F_NAME); break; } if (chp == nullptr) { ConditionalHooks.push_back(ConditionedHook()); chp = &ConditionalHooks[ConditionalHooks.size() - 1]; } if (!chp->AddCondition(&sct)) { Warning(LOCATION, "Could not add condition to conditional hook in file '%s'; you may have more than %d", filename, MAX_HOOK_CONDITIONS); } } if (chp == NULL) { return false; } bool actions_added = false; for (const auto* action = script_parse_action(); action != nullptr; action = script_parse_action()) { script_action sat; sat.action_type = action->getHookId(); // WMC - build error string SCP_string buf; sprintf(buf, "%s - %s", filename, action->getHookName().c_str()); ParseChunk(&sat.hook, buf.c_str()); // Add the action if (chp->AddAction(&sat)) actions_added = true; } if(!actions_added) { Warning(LOCATION, "No actions specified for conditional hook in file '%s'", filename); ConditionalHooks.pop_back(); return false; } return true; } void script_state::AddConditionedHook(ConditionedHook hook) { ConditionalHooks.push_back(std::move(hook)); } void script_state::AddGameInitFunction(script_function func) { GameInitFunctions.push_back(std::move(func)); } //*************************CLASS: script_state************************* bool script_state::IsOverride(script_hook &hd) { if(!hd.hook_function.function.isValid()) return false; bool b=false; RunBytecode(hd.override_function, 'b', &b); return b; } void script_state::RunInitFunctions() { for (const auto& initFunc : GameInitFunctions) { initFunc.function(LuaState); } // We don't need this anymore so no need to keep references to those functions around anymore GameInitFunctions.clear(); } void scripting_state_init() { // nothing to do here if (scripting_state_inited) return; gr_set_clear_color(0, 0, 0); scripting_state_inited = 1; } void scripting_state_close() { if (!scripting_state_inited) return; game_flush(); scripting_state_inited = 0; } void scripting_state_do_frame(float /*frametime*/) { // just incase something is wrong if (!scripting_state_inited) return; gr_reset_clip(); gr_clear(); gr_flip(); // process keys int k = game_check_key() & ~KEY_DEBUGGED; switch (k) { case KEY_ESC: gameseq_post_event(GS_EVENT_MAIN_MENU); return; } }
27.571784
239
0.683422
[ "render", "object" ]
3b5acc1656cd73cb2820fd2bcda2a87169fa9ae5
1,816
cpp
C++
Marlin/src/HAL/NATIVE_SIM/u8g/LCD_pin_routines.cpp
tom-2273/Tronxy_SKR_mini_E3_V20
bc4a8dc2c6c627e4bd7aa423794246f5b051448d
[ "CC0-1.0" ]
null
null
null
Marlin/src/HAL/NATIVE_SIM/u8g/LCD_pin_routines.cpp
tom-2273/Tronxy_SKR_mini_E3_V20
bc4a8dc2c6c627e4bd7aa423794246f5b051448d
[ "CC0-1.0" ]
null
null
null
Marlin/src/HAL/NATIVE_SIM/u8g/LCD_pin_routines.cpp
tom-2273/Tronxy_SKR_mini_E3_V20
bc4a8dc2c6c627e4bd7aa423794246f5b051448d
[ "CC0-1.0" ]
null
null
null
/** * Marlin 3D Printer Firmware * Copyright (c) 2021 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ /** * Low level pin manipulation routines - used by all the drivers. * * These are based on the LPC1768 pinMode, digitalRead & digitalWrite routines. * * Couldn't just call exact copies because the overhead killed the LCD update speed * With an intermediate level the softspi was running in the 10-20kHz range which * resulted in using about about 25% of the CPU's time. */ #ifdef __PLAT_NATIVE_SIM__ #include "../fastio.h" #include "LCD_pin_routines.h" #ifdef __cplusplus extern "C" { #endif void u8g_SetPinOutput(uint8_t internal_pin_number){SET_DIR_OUTPUT(internal_pin_number);} void u8g_SetPinInput(uint8_t internal_pin_number){SET_DIR_INPUT(internal_pin_number);} void u8g_SetPinLevel(uint8_t pin, uint8_t pin_status){WRITE_PIN(pin, pin_status);} uint8_t u8g_GetPinLevel(uint8_t pin){return READ_PIN(pin);} void usleep(uint64_t microsec){ assert(false); // why we here? } #ifdef __cplusplus } #endif #endif // __PLAT_NATIVE_SIM__
34.264151
88
0.756608
[ "3d" ]
3b5c07d06b4a7f0f7f686224774f882256491c37
2,590
cc
C++
tensorflow_serving/core/aspired_version_policy_test.cc
lapolonio/serving
71c0a2b3aa312ffa1accbf3092fc7a6a84f58a33
[ "Apache-2.0" ]
106
2021-06-24T06:47:27.000Z
2022-03-11T01:52:19.000Z
tensorflow_serving/core/aspired_version_policy_test.cc
lapolonio/serving
71c0a2b3aa312ffa1accbf3092fc7a6a84f58a33
[ "Apache-2.0" ]
5
2019-09-09T22:23:36.000Z
2019-10-22T03:34:48.000Z
tensorflow_serving/core/aspired_version_policy_test.cc
zendesk/serving
142d0adb5e2975689d80d8fc608c9684e96de078
[ "Apache-2.0" ]
12
2021-06-24T02:14:04.000Z
2021-11-15T05:47:01.000Z
/* Copyright 2017 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow_serving/core/aspired_version_policy.h" #include <vector> #include <gtest/gtest.h> #include "tensorflow_serving/core/loader_harness.h" #include "tensorflow_serving/core/servable_id.h" #include "tensorflow_serving/util/optional.h" namespace tensorflow { namespace serving { class AspiredVersionPolicyTest : public ::testing::Test { public: // Expose the protected AspiredVersionPolicy::GetHighestAspiredNewServableId() // method. optional<ServableId> GetHighestAspiredNewServableId( const std::vector<AspiredServableStateSnapshot>& all_versions) { return AspiredVersionPolicy::GetHighestAspiredNewServableId(all_versions); } }; TEST_F(AspiredVersionPolicyTest, NoHighestAspiredNewServableId) { // No new aspired versions. std::vector<AspiredServableStateSnapshot> versions; versions.push_back({{"test", 10}, LoaderHarness::State::kNew, false}); versions.push_back({{"test", 9}, LoaderHarness::State::kUnloading, true}); optional<ServableId> highest_aspired_new = GetHighestAspiredNewServableId(versions); ASSERT_FALSE(highest_aspired_new); } TEST_F(AspiredVersionPolicyTest, HighestAspiredNewServableId) { // Three new aspired versions and two other versions. std::vector<AspiredServableStateSnapshot> versions; versions.push_back({{"test", 10}, LoaderHarness::State::kNew, false}); versions.push_back({{"test", 9}, LoaderHarness::State::kUnloading, true}); versions.push_back({{"test", 1}, LoaderHarness::State::kNew, true}); versions.push_back({{"test", 5}, LoaderHarness::State::kNew, true}); versions.push_back({{"test", 3}, LoaderHarness::State::kNew, true}); optional<ServableId> highest_aspired_new = GetHighestAspiredNewServableId(versions); ASSERT_TRUE(highest_aspired_new); EXPECT_EQ("test", highest_aspired_new.value().name); EXPECT_EQ(5, highest_aspired_new.value().version); } } // namespace serving } // namespace tensorflow
39.846154
80
0.749035
[ "vector" ]
3b5cb25aea150acd31ee141464df3bb4199d56e5
28,077
cc
C++
components/data_reduction_proxy/core/browser/data_reduction_proxy_test_utils.cc
google-ar/chromium
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
777
2017-08-29T15:15:32.000Z
2022-03-21T05:29:41.000Z
components/data_reduction_proxy/core/browser/data_reduction_proxy_test_utils.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
66
2017-08-30T18:31:18.000Z
2021-08-02T10:59:35.000Z
components/data_reduction_proxy/core/browser/data_reduction_proxy_test_utils.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
123
2017-08-30T01:19:34.000Z
2022-03-17T22:55:31.000Z
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_test_utils.h" #include <map> #include <utility> #include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/run_loop.h" #include "base/threading/thread_task_runner_handle.h" #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_compression_stats.h" #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_config_service_client.h" #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_config_test_utils.h" #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_configurator.h" #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_interceptor.h" #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_io_data.h" #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_mutable_config_values.h" #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_network_delegate.h" #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_prefs.h" #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_settings.h" #include "components/data_reduction_proxy/core/browser/data_store.h" #include "components/data_reduction_proxy/core/common/data_reduction_proxy_event_creator.h" #include "components/data_reduction_proxy/core/common/data_reduction_proxy_event_storage_delegate_test_utils.h" #include "components/data_reduction_proxy/core/common/data_reduction_proxy_event_store.h" #include "components/data_reduction_proxy/core/common/data_reduction_proxy_params.h" #include "components/data_reduction_proxy/core/common/data_reduction_proxy_params_test_utils.h" #include "components/data_reduction_proxy/core/common/data_reduction_proxy_pref_names.h" #include "components/data_reduction_proxy/core/common/data_reduction_proxy_server.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/testing_pref_service.h" #include "net/proxy/proxy_config.h" #include "net/proxy/proxy_info.h" #include "net/proxy/proxy_list.h" #include "net/socket/socket_test_util.h" #include "net/url_request/url_request_context_storage.h" #include "net/url_request/url_request_intercepting_job_factory.h" #include "net/url_request/url_request_job_factory_impl.h" #include "net/url_request/url_request_test_util.h" #include "url/gurl.h" namespace { const char kTestKey[] = "test-key"; // Name of the preference that governs enabling the Data Reduction Proxy. const char kDataReductionProxyEnabled[] = "data_reduction_proxy.enabled"; const net::BackoffEntry::Policy kTestBackoffPolicy = { 0, // num_errors_to_ignore 10 * 1000, // initial_delay_ms 2, // multiply_factor 0, // jitter_factor 30 * 60 * 1000, // maximum_backoff_ms -1, // entry_lifetime_ms true, // always_use_initial_delay }; } // namespace namespace data_reduction_proxy { TestDataReductionProxyRequestOptions::TestDataReductionProxyRequestOptions( Client client, const std::string& version, DataReductionProxyConfig* config) : DataReductionProxyRequestOptions(client, version, config) { } std::string TestDataReductionProxyRequestOptions::GetDefaultKey() const { return kTestKey; } base::Time TestDataReductionProxyRequestOptions::Now() const { return base::Time::UnixEpoch() + now_offset_; } void TestDataReductionProxyRequestOptions::RandBytes(void* output, size_t length) const { char* c = static_cast<char*>(output); for (size_t i = 0; i < length; ++i) { c[i] = 'a'; } } // Time after the unix epoch that Now() reports. void TestDataReductionProxyRequestOptions::set_offset( const base::TimeDelta& now_offset) { now_offset_ = now_offset; } MockDataReductionProxyRequestOptions::MockDataReductionProxyRequestOptions( Client client, DataReductionProxyConfig* config) : TestDataReductionProxyRequestOptions(client, "1.2.3.4", config) {} MockDataReductionProxyRequestOptions::~MockDataReductionProxyRequestOptions() { } TestDataReductionProxyConfigServiceClient:: TestDataReductionProxyConfigServiceClient( std::unique_ptr<DataReductionProxyParams> params, DataReductionProxyRequestOptions* request_options, DataReductionProxyMutableConfigValues* config_values, DataReductionProxyConfig* config, DataReductionProxyEventCreator* event_creator, DataReductionProxyIOData* io_data, net::NetLog* net_log, ConfigStorer config_storer) : DataReductionProxyConfigServiceClient(std::move(params), kTestBackoffPolicy, request_options, config_values, config, event_creator, io_data, net_log, config_storer), #if defined(OS_ANDROID) is_application_state_background_(false), #endif tick_clock_(base::Time::UnixEpoch()), test_backoff_entry_(&kTestBackoffPolicy, &tick_clock_) { } TestDataReductionProxyConfigServiceClient:: ~TestDataReductionProxyConfigServiceClient() { } void TestDataReductionProxyConfigServiceClient::SetNow(const base::Time& time) { tick_clock_.SetTime(time); } void TestDataReductionProxyConfigServiceClient::SetCustomReleaseTime( const base::TimeTicks& release_time) { test_backoff_entry_.SetCustomReleaseTime(release_time); } base::TimeDelta TestDataReductionProxyConfigServiceClient::GetDelay() const { return config_refresh_timer_.GetCurrentDelay(); } int TestDataReductionProxyConfigServiceClient::GetBackoffErrorCount() { return test_backoff_entry_.failure_count(); } void TestDataReductionProxyConfigServiceClient::SetConfigServiceURL( const GURL& service_url) { config_service_url_ = service_url; } int32_t TestDataReductionProxyConfigServiceClient::failed_attempts_before_success() const { return failed_attempts_before_success_; } base::Time TestDataReductionProxyConfigServiceClient::Now() { return tick_clock_.Now(); } net::BackoffEntry* TestDataReductionProxyConfigServiceClient::GetBackoffEntry() { return &test_backoff_entry_; } TestDataReductionProxyConfigServiceClient::TestTickClock::TestTickClock( const base::Time& initial_time) : time_(initial_time) { } base::TimeTicks TestDataReductionProxyConfigServiceClient::TestTickClock::NowTicks() { return base::TimeTicks::UnixEpoch() + (time_ - base::Time::UnixEpoch()); } base::Time TestDataReductionProxyConfigServiceClient::TestTickClock::Now() { return time_; } void TestDataReductionProxyConfigServiceClient::TestTickClock::SetTime( const base::Time& time) { time_ = time; } #if defined(OS_ANDROID) bool TestDataReductionProxyConfigServiceClient::IsApplicationStateBackground() const { return is_application_state_background_; } void TestDataReductionProxyConfigServiceClient:: TriggerApplicationStatusToForeground() { OnApplicationStateChange( base::android::APPLICATION_STATE_HAS_RUNNING_ACTIVITIES); } #endif MockDataReductionProxyService::MockDataReductionProxyService( DataReductionProxySettings* settings, PrefService* prefs, net::URLRequestContextGetter* request_context, const scoped_refptr<base::SingleThreadTaskRunner>& task_runner) : DataReductionProxyService(settings, prefs, request_context, base::MakeUnique<TestDataStore>(), task_runner, task_runner, task_runner, base::TimeDelta()) {} MockDataReductionProxyService::~MockDataReductionProxyService() { } TestDataReductionProxyIOData::TestDataReductionProxyIOData( const scoped_refptr<base::SingleThreadTaskRunner>& task_runner, std::unique_ptr<DataReductionProxyConfig> config, std::unique_ptr<DataReductionProxyEventCreator> event_creator, std::unique_ptr<TestDataReductionProxyRequestOptions> request_options, std::unique_ptr<DataReductionProxyConfigurator> configurator, net::NetLog* net_log, bool enabled) : DataReductionProxyIOData(), service_set_(false), pingback_reporting_fraction_(0.0f), test_request_options_(request_options.get()) { io_task_runner_ = task_runner; ui_task_runner_ = task_runner; config_ = std::move(config); event_creator_ = std::move(event_creator); request_options_ = std::move(request_options); configurator_ = std::move(configurator); net_log_ = net_log; bypass_stats_.reset(new DataReductionProxyBypassStats( config_.get(), base::Bind(&DataReductionProxyIOData::SetUnreachable, base::Unretained(this)))); enabled_ = enabled; } TestDataReductionProxyIOData::~TestDataReductionProxyIOData() { } void TestDataReductionProxyIOData::SetPingbackReportingFraction( float pingback_reporting_fraction) { pingback_reporting_fraction_ = pingback_reporting_fraction; } void TestDataReductionProxyIOData::SetDataReductionProxyService( base::WeakPtr<DataReductionProxyService> data_reduction_proxy_service) { if (!service_set_) DataReductionProxyIOData::SetDataReductionProxyService( data_reduction_proxy_service); service_set_ = true; } TestDataStore::TestDataStore() {} TestDataStore::~TestDataStore() {} DataStore::Status TestDataStore::Get(base::StringPiece key, std::string* value) { auto value_iter = map_.find(key.as_string()); if (value_iter == map_.end()) return NOT_FOUND; value->assign(value_iter->second); return OK; } DataStore::Status TestDataStore::Put( const std::map<std::string, std::string>& map) { for (auto iter = map.begin(); iter != map.end(); ++iter) map_[iter->first] = iter->second; return OK; } DataStore::Status TestDataStore::Delete(base::StringPiece key) { map_.erase(key.as_string()); return OK; } DataReductionProxyTestContext::Builder::Builder() : params_flags_(DataReductionProxyParams::kPromoAllowed), params_definitions_(TestDataReductionProxyParams::HAS_EVERYTHING), client_(Client::UNKNOWN), request_context_(nullptr), mock_socket_factory_(nullptr), use_mock_config_(false), use_mock_service_(false), use_mock_request_options_(false), use_config_client_(false), use_test_config_client_(false), skip_settings_initialization_(false) {} DataReductionProxyTestContext::Builder::~Builder() {} DataReductionProxyTestContext::Builder& DataReductionProxyTestContext::Builder::WithParamsFlags(int params_flags) { params_flags_ = params_flags; return *this; } DataReductionProxyTestContext::Builder& DataReductionProxyTestContext::Builder::WithParamsDefinitions( unsigned int params_definitions) { params_definitions_ = params_definitions; return *this; } DataReductionProxyTestContext::Builder& DataReductionProxyTestContext::Builder::WithURLRequestContext( net::URLRequestContext* request_context) { request_context_ = request_context; return *this; } DataReductionProxyTestContext::Builder& DataReductionProxyTestContext::Builder::WithMockClientSocketFactory( net::MockClientSocketFactory* mock_socket_factory) { mock_socket_factory_ = mock_socket_factory; return *this; } DataReductionProxyTestContext::Builder& DataReductionProxyTestContext::Builder::WithClient(Client client) { client_ = client; return *this; } DataReductionProxyTestContext::Builder& DataReductionProxyTestContext::Builder::WithMockConfig() { use_mock_config_ = true; return *this; } DataReductionProxyTestContext::Builder& DataReductionProxyTestContext::Builder::WithMockDataReductionProxyService() { use_mock_service_ = true; return *this; } DataReductionProxyTestContext::Builder& DataReductionProxyTestContext::Builder::WithMockRequestOptions() { use_mock_request_options_ = true; return *this; } DataReductionProxyTestContext::Builder& DataReductionProxyTestContext::Builder::WithConfigClient() { use_config_client_ = true; return *this; } DataReductionProxyTestContext::Builder& DataReductionProxyTestContext::Builder::WithTestConfigClient() { use_config_client_ = true; use_test_config_client_ = true; return *this; } DataReductionProxyTestContext::Builder& DataReductionProxyTestContext::Builder::SkipSettingsInitialization() { skip_settings_initialization_ = true; return *this; } DataReductionProxyTestContext::Builder& DataReductionProxyTestContext::Builder::WithProxiesForHttp( const std::vector<DataReductionProxyServer>& proxy_servers) { DCHECK(!proxy_servers.empty()); proxy_servers_ = proxy_servers; return *this; } std::unique_ptr<DataReductionProxyTestContext> DataReductionProxyTestContext::Builder::Build() { // Check for invalid builder combinations. DCHECK(!(use_mock_config_ && use_config_client_)); unsigned int test_context_flags = 0; scoped_refptr<base::SingleThreadTaskRunner> task_runner = base::ThreadTaskRunnerHandle::Get(); scoped_refptr<net::URLRequestContextGetter> request_context_getter; std::unique_ptr<TestingPrefServiceSimple> pref_service( new TestingPrefServiceSimple()); std::unique_ptr<net::TestNetLog> net_log(new net::TestNetLog()); std::unique_ptr<TestConfigStorer> config_storer( new TestConfigStorer(pref_service.get())); if (request_context_) { request_context_getter = new net::TrivialURLRequestContextGetter( request_context_, task_runner); } else { std::unique_ptr<net::TestURLRequestContext> test_request_context( new net::TestURLRequestContext(true)); if (mock_socket_factory_) test_request_context->set_client_socket_factory(mock_socket_factory_); test_request_context->Init(); request_context_getter = new net::TestURLRequestContextGetter( task_runner, std::move(test_request_context)); } std::unique_ptr<TestDataReductionProxyEventStorageDelegate> storage_delegate( new TestDataReductionProxyEventStorageDelegate()); std::unique_ptr<DataReductionProxyEventCreator> event_creator( new DataReductionProxyEventCreator(storage_delegate.get())); std::unique_ptr<DataReductionProxyConfigurator> configurator( new DataReductionProxyConfigurator(net_log.get(), event_creator.get())); std::unique_ptr<TestDataReductionProxyConfig> config; std::unique_ptr<DataReductionProxyConfigServiceClient> config_client; DataReductionProxyMutableConfigValues* raw_mutable_config = nullptr; std::unique_ptr<TestDataReductionProxyParams> params( new TestDataReductionProxyParams(params_flags_, params_definitions_)); TestDataReductionProxyParams* raw_params = params.get(); if (use_config_client_) { test_context_flags |= USE_CONFIG_CLIENT; std::unique_ptr<DataReductionProxyMutableConfigValues> mutable_config = DataReductionProxyMutableConfigValues::CreateFromParams(params.get()); if (!proxy_servers_.empty()) { mutable_config->UpdateValues(proxy_servers_); } raw_mutable_config = mutable_config.get(); config.reset(new TestDataReductionProxyConfig( std::move(mutable_config), task_runner, net_log.get(), configurator.get(), event_creator.get())); } else if (use_mock_config_) { test_context_flags |= USE_MOCK_CONFIG; config.reset(new MockDataReductionProxyConfig( std::move(params), task_runner, net_log.get(), configurator.get(), event_creator.get())); } else { if (!proxy_servers_.empty()) { params->SetProxiesForHttp(proxy_servers_); } config.reset(new TestDataReductionProxyConfig( std::move(params), task_runner, net_log.get(), configurator.get(), event_creator.get())); } std::unique_ptr<TestDataReductionProxyRequestOptions> request_options; if (use_mock_request_options_) { test_context_flags |= USE_MOCK_REQUEST_OPTIONS; request_options.reset( new MockDataReductionProxyRequestOptions(client_, config.get())); } else { request_options.reset(new TestDataReductionProxyRequestOptions( client_, "1.2.3.4", config.get())); } std::unique_ptr<DataReductionProxySettings> settings( new DataReductionProxySettings()); if (skip_settings_initialization_) { settings->set_data_reduction_proxy_enabled_pref_name_for_test( kDataReductionProxyEnabled); test_context_flags |= SKIP_SETTINGS_INITIALIZATION; } if (use_mock_service_) test_context_flags |= USE_MOCK_SERVICE; pref_service->registry()->RegisterBooleanPref(kDataReductionProxyEnabled, false); RegisterSimpleProfilePrefs(pref_service->registry()); std::unique_ptr<TestDataReductionProxyIOData> io_data( new TestDataReductionProxyIOData( task_runner, std::move(config), std::move(event_creator), std::move(request_options), std::move(configurator), net_log.get(), true /* enabled */)); io_data->SetSimpleURLRequestContextGetter(request_context_getter); if (use_test_config_client_) { test_context_flags |= USE_TEST_CONFIG_CLIENT; config_client.reset(new TestDataReductionProxyConfigServiceClient( std::move(params), io_data->request_options(), raw_mutable_config, io_data->config(), io_data->event_creator(), io_data.get(), net_log.get(), base::Bind(&TestConfigStorer::StoreSerializedConfig, base::Unretained(config_storer.get())))); } else if (use_config_client_) { config_client.reset(new DataReductionProxyConfigServiceClient( std::move(params), GetBackoffPolicy(), io_data->request_options(), raw_mutable_config, io_data->config(), io_data->event_creator(), io_data.get(), net_log.get(), base::Bind(&TestConfigStorer::StoreSerializedConfig, base::Unretained(config_storer.get())))); } io_data->set_config_client(std::move(config_client)); io_data->set_proxy_delegate(base::WrapUnique(new DataReductionProxyDelegate( io_data->config(), io_data->configurator(), io_data->event_creator(), io_data->bypass_stats(), net_log.get()))); std::unique_ptr<DataReductionProxyTestContext> test_context( new DataReductionProxyTestContext( task_runner, std::move(pref_service), std::move(net_log), request_context_getter, mock_socket_factory_, std::move(io_data), std::move(settings), std::move(storage_delegate), std::move(config_storer), raw_params, test_context_flags)); if (!skip_settings_initialization_) test_context->InitSettingsWithoutCheck(); return test_context; } DataReductionProxyTestContext::DataReductionProxyTestContext( const scoped_refptr<base::SingleThreadTaskRunner>& task_runner, std::unique_ptr<TestingPrefServiceSimple> simple_pref_service, std::unique_ptr<net::TestNetLog> net_log, scoped_refptr<net::URLRequestContextGetter> request_context_getter, net::MockClientSocketFactory* mock_socket_factory, std::unique_ptr<TestDataReductionProxyIOData> io_data, std::unique_ptr<DataReductionProxySettings> settings, std::unique_ptr<TestDataReductionProxyEventStorageDelegate> storage_delegate, std::unique_ptr<TestConfigStorer> config_storer, TestDataReductionProxyParams* params, unsigned int test_context_flags) : test_context_flags_(test_context_flags), task_runner_(task_runner), simple_pref_service_(std::move(simple_pref_service)), net_log_(std::move(net_log)), request_context_getter_(request_context_getter), mock_socket_factory_(mock_socket_factory), io_data_(std::move(io_data)), settings_(std::move(settings)), storage_delegate_(std::move(storage_delegate)), config_storer_(std::move(config_storer)), params_(params) {} DataReductionProxyTestContext::~DataReductionProxyTestContext() { DestroySettings(); } const char* DataReductionProxyTestContext::GetDataReductionProxyEnabledPrefName() const { return kDataReductionProxyEnabled; } void DataReductionProxyTestContext::RegisterDataReductionProxyEnabledPref() { simple_pref_service_->registry()->RegisterBooleanPref( kDataReductionProxyEnabled, false); } void DataReductionProxyTestContext::SetDataReductionProxyEnabled(bool enabled) { simple_pref_service_->SetBoolean(kDataReductionProxyEnabled, enabled); } bool DataReductionProxyTestContext::IsDataReductionProxyEnabled() const { return simple_pref_service_->GetBoolean(kDataReductionProxyEnabled); } void DataReductionProxyTestContext::RunUntilIdle() { base::RunLoop().RunUntilIdle(); } void DataReductionProxyTestContext::InitSettings() { DCHECK(test_context_flags_ & DataReductionProxyTestContext::SKIP_SETTINGS_INITIALIZATION); InitSettingsWithoutCheck(); } void DataReductionProxyTestContext::DestroySettings() { // Force destruction of |DBDataOwner|, which lives on DB task runner and is // indirectly owned by |settings_|. if (settings_.get()) { settings_.reset(); RunUntilIdle(); } } void DataReductionProxyTestContext::InitSettingsWithoutCheck() { settings_->InitDataReductionProxySettings( kDataReductionProxyEnabled, simple_pref_service_.get(), io_data_.get(), CreateDataReductionProxyServiceInternal(settings_.get())); storage_delegate_->SetStorageDelegate( settings_->data_reduction_proxy_service()->event_store()); io_data_->SetDataReductionProxyService( settings_->data_reduction_proxy_service()->GetWeakPtr()); if (io_data_->config_client()) io_data_->config_client()->InitializeOnIOThread( request_context_getter_.get()); settings_->data_reduction_proxy_service()->SetIOData(io_data_->GetWeakPtr()); } std::unique_ptr<DataReductionProxyService> DataReductionProxyTestContext::CreateDataReductionProxyService( DataReductionProxySettings* settings) { DCHECK(test_context_flags_ & DataReductionProxyTestContext::SKIP_SETTINGS_INITIALIZATION); return CreateDataReductionProxyServiceInternal(settings); } std::unique_ptr<DataReductionProxyService> DataReductionProxyTestContext::CreateDataReductionProxyServiceInternal( DataReductionProxySettings* settings) { if (test_context_flags_ & DataReductionProxyTestContext::USE_MOCK_SERVICE) { return base::MakeUnique<MockDataReductionProxyService>( settings, simple_pref_service_.get(), request_context_getter_.get(), task_runner_); } else { return base::MakeUnique<DataReductionProxyService>( settings, simple_pref_service_.get(), request_context_getter_.get(), base::WrapUnique(new TestDataStore()), task_runner_, task_runner_, task_runner_, base::TimeDelta()); } } void DataReductionProxyTestContext::AttachToURLRequestContext( net::URLRequestContextStorage* request_context_storage) const { DCHECK(request_context_storage); // |request_context_storage| takes ownership of the network delegate. std::unique_ptr<DataReductionProxyNetworkDelegate> network_delegate = io_data()->CreateNetworkDelegate( base::MakeUnique<net::TestNetworkDelegate>(), true); request_context_storage->set_network_delegate(std::move(network_delegate)); request_context_storage->set_job_factory( base::MakeUnique<net::URLRequestInterceptingJobFactory>( std::unique_ptr<net::URLRequestJobFactory>( new net::URLRequestJobFactoryImpl()), io_data()->CreateInterceptor())); } void DataReductionProxyTestContext:: EnableDataReductionProxyWithSecureProxyCheckSuccess() { DCHECK(mock_socket_factory_); // |settings_| needs to have been initialized, since a // |DataReductionProxyService| is needed in order to issue the secure proxy // check. DCHECK(data_reduction_proxy_service()); // Enable the Data Reduction Proxy, simulating a successful secure proxy // check. net::MockRead mock_reads[] = { net::MockRead("HTTP/1.1 200 OK\r\n\r\n"), net::MockRead("OK"), net::MockRead(net::SYNCHRONOUS, net::OK), }; net::StaticSocketDataProvider socket_data_provider( mock_reads, arraysize(mock_reads), nullptr, 0); mock_socket_factory_->AddSocketDataProvider(&socket_data_provider); // Set the pref to cause the secure proxy check to be issued. pref_service()->SetBoolean(kDataReductionProxyEnabled, true); RunUntilIdle(); } MockDataReductionProxyConfig* DataReductionProxyTestContext::mock_config() const { DCHECK(test_context_flags_ & DataReductionProxyTestContext::USE_MOCK_CONFIG); return reinterpret_cast<MockDataReductionProxyConfig*>(io_data_->config()); } DataReductionProxyService* DataReductionProxyTestContext::data_reduction_proxy_service() const { return settings_->data_reduction_proxy_service(); } MockDataReductionProxyService* DataReductionProxyTestContext::mock_data_reduction_proxy_service() const { DCHECK(!(test_context_flags_ & DataReductionProxyTestContext::SKIP_SETTINGS_INITIALIZATION)); DCHECK(test_context_flags_ & DataReductionProxyTestContext::USE_MOCK_SERVICE); return reinterpret_cast<MockDataReductionProxyService*>( data_reduction_proxy_service()); } MockDataReductionProxyRequestOptions* DataReductionProxyTestContext::mock_request_options() const { DCHECK(test_context_flags_ & DataReductionProxyTestContext::USE_MOCK_REQUEST_OPTIONS); return reinterpret_cast<MockDataReductionProxyRequestOptions*>( io_data_->request_options()); } TestDataReductionProxyConfig* DataReductionProxyTestContext::config() const { return reinterpret_cast<TestDataReductionProxyConfig*>(io_data_->config()); } DataReductionProxyMutableConfigValues* DataReductionProxyTestContext::mutable_config_values() { DCHECK(test_context_flags_ & DataReductionProxyTestContext::USE_CONFIG_CLIENT); return reinterpret_cast<DataReductionProxyMutableConfigValues*>( config()->config_values()); } TestDataReductionProxyConfigServiceClient* DataReductionProxyTestContext::test_config_client() { DCHECK(test_context_flags_ & DataReductionProxyTestContext::USE_TEST_CONFIG_CLIENT); return reinterpret_cast<TestDataReductionProxyConfigServiceClient*>( io_data_->config_client()); } DataReductionProxyBypassStats::UnreachableCallback DataReductionProxyTestContext::unreachable_callback() const { return base::Bind(&DataReductionProxySettings::SetUnreachable, base::Unretained(settings_.get())); } DataReductionProxyTestContext::TestConfigStorer::TestConfigStorer( PrefService* prefs) : prefs_(prefs) { DCHECK(prefs); } void DataReductionProxyTestContext::TestConfigStorer::StoreSerializedConfig( const std::string& serialized_config) { prefs_->SetString(prefs::kDataReductionProxyConfig, serialized_config); } std::vector<net::ProxyServer> DataReductionProxyTestContext::GetConfiguredProxiesForHttp() const { const GURL kHttpUrl("http://test_http_url.net"); // The test URL shouldn't match any of the bypass rules in the proxy rules. DCHECK(!configurator()->GetProxyConfig().proxy_rules().bypass_rules.Matches( kHttpUrl)); net::ProxyInfo proxy_info; configurator()->GetProxyConfig().proxy_rules().Apply(kHttpUrl, &proxy_info); std::vector<net::ProxyServer> proxies_without_direct; for (const net::ProxyServer& proxy : proxy_info.proxy_list().GetAll()) if (proxy.is_valid() && !proxy.is_direct()) proxies_without_direct.push_back(proxy); return proxies_without_direct; } } // namespace data_reduction_proxy
37.788694
111
0.760302
[ "vector" ]
3b5ea90d45986f5623354b2451f185c794d44cf8
11,046
cpp
C++
source/blender/collada/SkinInfo.cpp
juangea/B28_boneMaster
6be9d19951ed460829d379aa90953b14a9f281f2
[ "Naumen", "Condor-1.1", "MS-PL" ]
2
2019-06-03T02:47:42.000Z
2020-04-03T10:23:33.000Z
source/blender/collada/SkinInfo.cpp
juangea/B28_boneMaster
6be9d19951ed460829d379aa90953b14a9f281f2
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
source/blender/collada/SkinInfo.cpp
juangea/B28_boneMaster
6be9d19951ed460829d379aa90953b14a9f281f2
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
/* * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** \file * \ingroup collada */ #include <algorithm> #if !defined(WIN32) # include <stdint.h> #endif /* COLLADABU_ASSERT, may be able to remove later */ #include "COLLADABUPlatform.h" #include "BLI_listbase.h" #include "BLI_math.h" #include "BLI_compiler_attrs.h" #include "DNA_armature_types.h" #include "DNA_modifier_types.h" #include "DNA_scene_types.h" #include "BKE_action.h" #include "BKE_object.h" #include "BKE_object_deform.h" #include "ED_mesh.h" #include "ED_object.h" #include "SkinInfo.h" #include "collada_utils.h" /* use name, or fall back to original id if name not present (name is optional) */ template<class T> static const char *bc_get_joint_name(T *node) { const std::string &id = node->getName(); return id.size() ? id.c_str() : node->getOriginalId().c_str(); } /* This is used to store data passed in write_controller_data. * Arrays from COLLADAFW::SkinControllerData lose ownership, so do this class members * so that arrays don't get freed until we free them explicitly. */ SkinInfo::SkinInfo() { /* pass */ } SkinInfo::SkinInfo(const SkinInfo &skin) : weights(skin.weights), joint_data(skin.joint_data), unit_converter(skin.unit_converter), ob_arm(skin.ob_arm), controller_uid(skin.controller_uid), parent(skin.parent) { copy_m4_m4(bind_shape_matrix, (float(*)[4])skin.bind_shape_matrix); transfer_uint_array_data_const(skin.joints_per_vertex, joints_per_vertex); transfer_uint_array_data_const(skin.weight_indices, weight_indices); transfer_int_array_data_const(skin.joint_indices, joint_indices); } SkinInfo::SkinInfo(UnitConverter *conv) : unit_converter(conv), ob_arm(NULL), parent(NULL) { } /* nobody owns the data after this, so it should be freed manually with releaseMemory */ template<class T> void SkinInfo::transfer_array_data(T &src, T &dest) { dest.setData(src.getData(), src.getCount()); src.yieldOwnerShip(); dest.yieldOwnerShip(); } /* when src is const we cannot src.yieldOwnerShip, this is used by copy constructor */ void SkinInfo::transfer_int_array_data_const(const COLLADAFW::IntValuesArray &src, COLLADAFW::IntValuesArray &dest) { dest.setData((int *)src.getData(), src.getCount()); dest.yieldOwnerShip(); } void SkinInfo::transfer_uint_array_data_const(const COLLADAFW::UIntValuesArray &src, COLLADAFW::UIntValuesArray &dest) { dest.setData((unsigned int *)src.getData(), src.getCount()); dest.yieldOwnerShip(); } void SkinInfo::borrow_skin_controller_data(const COLLADAFW::SkinControllerData *skin) { transfer_array_data((COLLADAFW::UIntValuesArray &)skin->getJointsPerVertex(), joints_per_vertex); transfer_array_data((COLLADAFW::UIntValuesArray &)skin->getWeightIndices(), weight_indices); transfer_array_data((COLLADAFW::IntValuesArray &)skin->getJointIndices(), joint_indices); // transfer_array_data(skin->getWeights(), weights); /* cannot transfer data for FloatOrDoubleArray, copy values manually */ const COLLADAFW::FloatOrDoubleArray &weight = skin->getWeights(); for (unsigned int i = 0; i < weight.getValuesCount(); i++) weights.push_back(bc_get_float_value(weight, i)); unit_converter->dae_matrix_to_mat4_(bind_shape_matrix, skin->getBindShapeMatrix()); } void SkinInfo::free() { joints_per_vertex.releaseMemory(); weight_indices.releaseMemory(); joint_indices.releaseMemory(); // weights.releaseMemory(); } /* using inverse bind matrices to construct armature * it is safe to invert them to get the original matrices * because if they are inverse matrices, they can be inverted */ void SkinInfo::add_joint(const COLLADABU::Math::Matrix4 &matrix) { JointData jd; unit_converter->dae_matrix_to_mat4_(jd.inv_bind_mat, matrix); joint_data.push_back(jd); } void SkinInfo::set_controller(const COLLADAFW::SkinController *co) { controller_uid = co->getUniqueId(); /* fill in joint UIDs */ const COLLADAFW::UniqueIdArray &joint_uids = co->getJoints(); for (unsigned int i = 0; i < joint_uids.getCount(); i++) { joint_data[i].joint_uid = joint_uids[i]; /* store armature pointer */ // JointData& jd = joint_index_to_joint_info_map[i]; // jd.ob_arm = ob_arm; /* now we'll be able to get inv bind matrix from joint id */ // joint_id_to_joint_index_map[joint_ids[i]] = i; } } /* called from write_controller */ Object *SkinInfo::create_armature(Main *bmain, Scene *scene, ViewLayer *view_layer) { ob_arm = bc_add_object(bmain, scene, view_layer, OB_ARMATURE, NULL); return ob_arm; } Object *SkinInfo::set_armature(Object *ob_arm) { if (this->ob_arm) return this->ob_arm; this->ob_arm = ob_arm; return ob_arm; } bool SkinInfo::get_joint_inv_bind_matrix(float inv_bind_mat[4][4], COLLADAFW::Node *node) { const COLLADAFW::UniqueId &uid = node->getUniqueId(); std::vector<JointData>::iterator it; for (it = joint_data.begin(); it != joint_data.end(); it++) { if ((*it).joint_uid == uid) { copy_m4_m4(inv_bind_mat, (*it).inv_bind_mat); return true; } } return false; } Object *SkinInfo::BKE_armature_from_object() { return ob_arm; } const COLLADAFW::UniqueId &SkinInfo::get_controller_uid() { return controller_uid; } /* check if this skin controller references a joint or any descendant of it * * some nodes may not be referenced by SkinController, * in this case to determine if the node belongs to this armature, * we need to search down the tree */ bool SkinInfo::uses_joint_or_descendant(COLLADAFW::Node *node) { const COLLADAFW::UniqueId &uid = node->getUniqueId(); std::vector<JointData>::iterator it; for (it = joint_data.begin(); it != joint_data.end(); it++) { if ((*it).joint_uid == uid) return true; } COLLADAFW::NodePointerArray &children = node->getChildNodes(); for (unsigned int i = 0; i < children.getCount(); i++) { if (uses_joint_or_descendant(children[i])) return true; } return false; } void SkinInfo::link_armature(bContext *C, Object *ob, std::map<COLLADAFW::UniqueId, COLLADAFW::Node *> &joint_by_uid, TransformReader *tm) { Main *bmain = CTX_data_main(C); Scene *scene = CTX_data_scene(C); ModifierData *md = ED_object_modifier_add(NULL, bmain, scene, ob, NULL, eModifierType_Armature); ArmatureModifierData *amd = (ArmatureModifierData *)md; amd->object = ob_arm; #if 1 /* XXX Why do we enforce objects to be children of Armatures if they weren't so before ?*/ if (!BKE_object_is_child_recursive(ob_arm, ob)) { bc_set_parent(ob, ob_arm, C); } #else Object workob; ob->parent = ob_arm; ob->partype = PAROBJECT; BKE_object_workob_calc_parent(scene, ob, &workob); invert_m4_m4(ob->parentinv, workob.obmat); DEG_id_tag_update(&obn->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY); #endif copy_m4_m4(ob->obmat, bind_shape_matrix); BKE_object_apply_mat4(ob, ob->obmat, 0, 0); amd->deformflag = ARM_DEF_VGROUP; /* create all vertex groups */ std::vector<JointData>::iterator it; int joint_index; for (it = joint_data.begin(), joint_index = 0; it != joint_data.end(); it++, joint_index++) { const char *name = "Group"; /* skip joints that have invalid UID */ if ((*it).joint_uid == COLLADAFW::UniqueId::INVALID) continue; /* name group by joint node name */ if (joint_by_uid.find((*it).joint_uid) != joint_by_uid.end()) { name = bc_get_joint_name(joint_by_uid[(*it).joint_uid]); } BKE_object_defgroup_add_name(ob, name); } /* <vcount> - number of joints per vertex - joints_per_vertex * <v> - [[bone index, weight index] * joints per vertex] * vertices - weight indices * ^ bone index can be -1 meaning weight toward bind shape, how to express this in Blender? * * for each vertex in weight indices * for each bone index in vertex * add vertex to group at group index * treat group index -1 specially * * get def group by index with BLI_findlink */ for (unsigned int vertex = 0, weight = 0; vertex < joints_per_vertex.getCount(); vertex++) { unsigned int limit = weight + joints_per_vertex[vertex]; for (; weight < limit; weight++) { int joint = joint_indices[weight], joint_weight = weight_indices[weight]; /* -1 means "weight towards the bind shape", we just don't assign it to any group */ if (joint != -1) { bDeformGroup *def = (bDeformGroup *)BLI_findlink(&ob->defbase, joint); ED_vgroup_vert_add(ob, def, vertex, weights[joint_weight], WEIGHT_REPLACE); } } } } bPoseChannel *SkinInfo::get_pose_channel_from_node(COLLADAFW::Node *node) { return BKE_pose_channel_find_name(ob_arm->pose, bc_get_joint_name(node)); } void SkinInfo::set_parent(Object *_parent) { parent = _parent; } Object *SkinInfo::get_parent() { return parent; } void SkinInfo::find_root_joints(const std::vector<COLLADAFW::Node *> &root_joints, std::map<COLLADAFW::UniqueId, COLLADAFW::Node *> &joint_by_uid, std::vector<COLLADAFW::Node *> &result) { std::vector<COLLADAFW::Node *>::const_iterator it; /* for each root_joint */ for (it = root_joints.begin(); it != root_joints.end(); it++) { COLLADAFW::Node *root = *it; std::vector<JointData>::iterator ji; /* for each joint_data in this skin */ for (ji = joint_data.begin(); ji != joint_data.end(); ji++) { if (joint_by_uid.find((*ji).joint_uid) != joint_by_uid.end()) { /* get joint node from joint map */ COLLADAFW::Node *joint = joint_by_uid[(*ji).joint_uid]; /* find if joint node is in the tree belonging to the root_joint */ if (find_node_in_tree(joint, root)) { if (std::find(result.begin(), result.end(), root) == result.end()) result.push_back(root); } } } } } bool SkinInfo::find_node_in_tree(COLLADAFW::Node *node, COLLADAFW::Node *tree_root) { if (node == tree_root) return true; COLLADAFW::NodePointerArray &children = tree_root->getChildNodes(); for (unsigned int i = 0; i < children.getCount(); i++) { if (find_node_in_tree(node, children[i])) return true; } return false; }
31.56
99
0.691653
[ "object", "shape", "vector" ]
3b692e3ffaff0714c462a96921aafc5cb93bbb33
6,289
cpp
C++
Code/GeometryWidgets/dialogMakeSweep.cpp
baojunli/FastCAE
a3f99f6402da564df87fcef30674ce5f44379962
[ "BSD-3-Clause" ]
2
2020-02-21T01:04:35.000Z
2020-02-21T03:35:37.000Z
Code/GeometryWidgets/dialogMakeSweep.cpp
Sunqia/FastCAE
cbc023fe07b6e306ceefae8b8bd7c12bc1562acb
[ "BSD-3-Clause" ]
1
2020-03-06T04:49:42.000Z
2020-03-06T04:49:42.000Z
Code/GeometryWidgets/dialogMakeSweep.cpp
Sunqia/FastCAE
cbc023fe07b6e306ceefae8b8bd7c12bc1562acb
[ "BSD-3-Clause" ]
null
null
null
#include "dialogMakeSweep.h" #include "ui_dialogMakeSweep.h" #include "settings/busAPI.h" #include "settings/GraphOption.h" #include <vtkActor.h> #include <vtkProperty.h> #include <QMessageBox> #include "geometry/geometrySet.h" #include "GeometryCommand/GeoCommandList.h" #include "GeometryCommand/GeoCommandMakeSweep.h" #include "python/PyAgent.h" #include "geometry/geometryParaSweep.h" namespace GeometryWidget { SweepDialog::SweepDialog(GUI::MainWindow* m, MainWidget::PreWindow* p) : GeoDialogBase(m, p) { _ui = new Ui::SweepDialog; _ui->setupUi(this); this->translateButtonBox(_ui->buttonBox); } SweepDialog::SweepDialog(GUI::MainWindow* m, MainWidget::PreWindow* pre, Geometry::GeometrySet* set) : GeoDialogBase(m, pre) { _ui = new Ui::SweepDialog; _ui->setupUi(this); this->translateButtonBox(_ui->buttonBox); _isEdit = true; _editSet = set; init(); } SweepDialog::~SweepDialog() { if (_ui != nullptr) delete _ui; emit setSelectMode((int)ModuleBase::None); emit updateGraphOptions(); } void SweepDialog::init() { if (_editSet == nullptr) return; Geometry::GeometryModelParaBase* bp = _editSet->getParameter(); Geometry::GeometryParaSweep* p = dynamic_cast<Geometry::GeometryParaSweep*>(bp); if (p == nullptr) return; emit hideGeometry(_editSet); _pathEdge = p->getPath(); _sectionEdgeHash = p->getShapeHash(); _solid = p->getSloid(); _ui->solidCheckBox->setChecked(_solid); QList<Geometry::GeometrySet*> setList = _sectionEdgeHash.uniqueKeys(); for (int i = 0; i < setList.size(); ++i) { Geometry::GeometrySet* set = setList.at(i); QList<int> edlist = _sectionEdgeHash.values(set); if (set == nullptr) return; for(int var : edlist) { emit highLightGeometryEdge(set, var, &_sectionActors); } } QList<vtkActor*> acs; emit highLightGeometryEdge(_pathEdge.first, _pathEdge.second,&acs); _pathActor = acs.at(0); QString label = QString(tr("Selected edge(%1)")).arg(_sectionEdgeHash.size()); _ui->edglabel->setText(label); if (_pathEdge.first != nullptr) { QString label = QString(tr("Selected edge(%1)")).arg(1); _ui->pathlabel->setText(label); } } void SweepDialog::closeEvent(QCloseEvent *e) { QDialog::closeEvent(e); delete this; } void SweepDialog::accept() { bool ok = true; if (_pathActor == nullptr || _sectionActors.size() < 1||_pathEdge.first==nullptr) ok = false; if (!ok) { QMessageBox::warning(this, tr("Warning"), tr("Input Wrong !")); return; } /* Command::GeoCommandMakeSweep* command = new Command::GeoCommandMakeSweep(_mainWindow, _preWindow); command->setSection(_sectionEdgeHash); command->setPath(_pathEdge); command->isSolid(isSolid); bool success = Command::GeoComandList::getInstance()->executeCommand(command); if (!success) { QMessageBox::warning(this, tr("Warning"), tr("Create failed ! ")); return; }*/ QStringList codes{}; codes += QString("sweep = CAD.Sweep()"); if (_isEdit) codes += QString("sweep.setEditID(%1)").arg(_editSet->getID()); QList<Geometry::GeometrySet*> sets = _sectionEdgeHash.uniqueKeys(); for (int i = 0; i < sets.size(); ++i) { auto s = sets.at(i); int id = s->getID(); QList<int> indexs = _sectionEdgeHash.values(s); for(int var : indexs) codes += QString("sweep.appendEdge(%1,%2)").arg(id).arg(var); } int pathedge = _pathEdge.second; int pathset = _pathEdge.first->getID(); codes += QString("sweep.setPath(%1,%2)").arg(pathset).arg(pathedge); QString solidstr{}; _solid = _ui->solidCheckBox->isChecked(); if (_solid) solidstr = "Yes"; else solidstr = "No"; codes += QString("sweep.isSolid('%1')").arg(solidstr); if (_isEdit) codes += QString("sweep.edit()"); else codes += QString("sweep.create()"); _pyAgent->submit(codes); QDialog::accept(); this->close(); } void SweepDialog::reject() { if (_isEdit) { if (_editSet == nullptr) return; emit showGeometry(_editSet); } QDialog::reject(); this->close(); } void SweepDialog::selectActorShape(vtkActor* ac, int shape, Geometry::GeometrySet* set) { if (_selectPath && !_selectSection) selectPath(ac, shape, set); else if (_selectSection && !_selectPath) selectSection(ac, shape, set); } void SweepDialog::on_geoSelectCurve_clicked() { _selectPath = false; _selectSection = true; emit setSelectMode((int)ModuleBase::GeometryCurve); } void SweepDialog::on_geoSelectCurve_1_clicked() { _selectPath = true; _selectSection = false; emit setSelectMode((int)ModuleBase::GeometryCurve); } void SweepDialog::selectSection(vtkActor* ac, int index, Geometry::GeometrySet* set) { QColor color; if (_sectionActors.contains(ac)) { color = Setting::BusAPI::instance()->getGraphOption()->getGeometryCurveColor(); _sectionActors.removeOne(ac); _sectionEdgeHash.remove(set, index); } else { color = Setting::BusAPI::instance()->getGraphOption()->getHighLightColor(); _sectionActors.append(ac); _sectionEdgeHash.insert(set, index); } ac->GetProperty()->SetColor(color.redF(), color.greenF(), color.blueF()); QString label = QString(tr("Selected edge(%1)")).arg(_sectionActors.size()); _ui->edglabel->setText(label); } void SweepDialog::selectPath(vtkActor* ac, int shape, Geometry::GeometrySet* set) { if (ac == nullptr) return; if (_sectionActors.contains(ac)) return; QColor color; if (_pathActor != nullptr) { color = Setting::BusAPI::instance()->getGraphOption()->getGeometryCurveColor(); _pathActor ->GetProperty()->SetColor(color.redF(), color.greenF(), color.blueF()); _pathActor = nullptr; _pathEdge.first = nullptr; _pathEdge.second = shape; } color = Setting::BusAPI::instance()->getGraphOption()->getHighLightColor(); _pathActor = ac; _pathEdge.first = set; _pathEdge.second = shape; _pathActor->GetProperty()->SetColor(color.redF(), color.greenF(), color.blueF()); QString label = QString(tr("Selected edge(%1)")).arg(1); _ui->pathlabel->setText(label); } }
27.343478
102
0.659087
[ "cad", "geometry", "shape" ]
3b69e8966d5beee515348dbf6fd503520f9f0ce4
65,363
cpp
C++
src/cpu/x64/brgemm/jit_brgemm_amx_uker.cpp
intel/mkl-dnn
42a583db82325ff24e140fcbff13f720a8b164ab
[ "Apache-2.0" ]
1,327
2018-01-25T21:23:47.000Z
2020-04-03T09:39:30.000Z
src/cpu/x64/brgemm/jit_brgemm_amx_uker.cpp
intel/mkl-dnn
42a583db82325ff24e140fcbff13f720a8b164ab
[ "Apache-2.0" ]
498
2018-01-25T00:14:48.000Z
2020-04-03T16:21:44.000Z
src/cpu/x64/brgemm/jit_brgemm_amx_uker.cpp
intel/mkl-dnn
42a583db82325ff24e140fcbff13f720a8b164ab
[ "Apache-2.0" ]
365
2018-01-29T16:12:36.000Z
2020-04-03T08:32:27.000Z
/******************************************************************************* * Copyright 2021-2022 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include <memory> #include "common/c_types_map.hpp" #include "common/nstl.hpp" #include "common/type_helpers.hpp" #include "common/utils.hpp" #include "cpu/platform.hpp" #include "cpu/x64/brgemm/brgemm.hpp" #include "cpu/x64/brgemm/brgemm_types.hpp" #include "cpu/x64/injectors/jit_uni_postops_injector.hpp" #include "cpu/x64/jit_generator.hpp" #define GET_OFF(field) offsetof(brgemm_kernel_params_t, field) #define GET_OFF_BATCH_ELEMENT(field) offsetof(brgemm_batch_element_t, field) namespace dnnl { namespace impl { namespace cpu { namespace x64 { using namespace dnnl::impl::utils; using namespace Xbyak; struct jit_brgemm_amx_uker_base_t : public jit_generator { jit_brgemm_amx_uker_base_t(const brgemm_t &abrg) : jit_generator(jit_name(), nullptr, MAX_CODE_SIZE, true, avx512_core) , brg(abrg) , postops_injector_(nullptr) { if (brg.with_eltwise || brg.with_binary || brg.with_sum) { static constexpr bool preserve_gpr = true; // we don't use zmm1 for storing vectors // so we don't need to preserve vmm static constexpr bool preserve_vmm = false; static constexpr bool use_exact_tail_scalar_bcast = false; const auto dst_md_wrapper = memory_desc_wrapper(brg.dst_md); static const bcast_set_t enabled_bcast_strategy = {broadcasting_strategy_t::scalar, broadcasting_strategy_t::per_oc, broadcasting_strategy_t::per_oc_spatial, broadcasting_strategy_t::per_mb_spatial, broadcasting_strategy_t::per_mb_w, broadcasting_strategy_t::per_w, broadcasting_strategy_t::no_broadcast}; const binary_injector::rhs_arg_static_params_t rhs_sp { static_cast<size_t>(Xbyak::Zmm(1).getIdx()), this->r14, this->r15, preserve_gpr, preserve_vmm, GET_OFF(post_ops_binary_rhs_arg_vec), GET_OFF(data_C_ptr_), dst_md_wrapper, static_cast<size_t>(brg.ldb_tail), ld_tail_mask, use_exact_tail_scalar_bcast}; const binary_injector::static_params_t bsp { this->param1, enabled_bcast_strategy, rhs_sp}; eltwise_injector::static_params_t esp; esp.preserve_vmm = preserve_vmm; esp.preserve_p_table = false; postops_injector_ = utils::make_unique< injector::jit_uni_postops_injector_t<avx512_core>>( this, brg.attr->post_ops_, bsp, esp); using namespace dnnl::impl::cpu::binary_injector_utils; std::tie(with_binary_per_oc_bcast_, with_binary_per_oc_sp_bcast_, with_binary_channel_bcast_, with_binary_per_mb_w_bcast_, with_binary_per_w_bcast_, with_binary_no_bcast_) = bcast_strategies_present_tup(brg.attr->post_ops_.entry_, dst_md_wrapper, broadcasting_strategy_t::per_oc, broadcasting_strategy_t::per_oc_spatial, broadcasting_strategy_t::per_mb_spatial, broadcasting_strategy_t::per_mb_w, broadcasting_strategy_t::per_w, broadcasting_strategy_t::no_broadcast); handle_binary_po_offset_ = with_binary_per_oc_bcast_ || with_binary_per_oc_sp_bcast_ || with_binary_channel_bcast_ || with_binary_per_mb_w_bcast_ || with_binary_per_w_bcast_ || with_binary_no_bcast_; } use_ils_ = brg.brgattr.use_interleave_stores; } DECLARE_CPU_JIT_AUX_FUNCTIONS(jit_brgemm_amx_uker_base_t) brgemm_t brg; private: std::unique_ptr<injector::jit_uni_postops_injector_t<avx512_core>> postops_injector_; using reg64_t = const Xbyak::Reg64; enum { simd_w = 16, zmm_width_in_bytes = cpu_isa_traits<avx512_core>::vlen, tile_size = 1024 }; enum matrix_kind_t { matrix_A, matrix_B }; // Register decomposition const reg64_t param1 = abi_param1; const reg64_t reg_addr_batch = r13; const reg64_t reg_aux1_batch = rbp; const reg64_t reg_aux_A = r11; const reg64_t reg_aux_B = r10; const reg64_t reg_stride_lda = r14; const reg64_t reg_stride_ldb = abi_not_param1; const reg64_t reg_C = r15; const reg64_t reg_D = r12; const reg64_t reg_buf = r8; const reg64_t reg_BS = rbx; const reg64_t reg_BS_loop = r9; const reg64_t reg_bias = rbx; const reg64_t reg_scales = rbx; const reg64_t reg_stride_ld_block = rdx; const reg64_t reg_do_post_ops = rbx; const reg64_t reg_tmp_gpr = rbx; const reg64_t reg_ptr_sum_scale = rbx; const reg64_t reg_zp_comp_a = rbx; const reg64_t reg_aux_zp_comp_a = rbx; const reg64_t reg_zp_comp_b = rbx; const reg64_t reg_zp_c_values = rbx; const reg64_t reg_ptr_sum_zp = r9; const reg64_t reg_bf32_stride = rsi; constexpr static int abi_param1_offs_ = 0; constexpr static int reg_zp_comp_a_offs_ = 8; constexpr static int reg_zp_comp_b_offs_ = 16; constexpr static int reg_zp_c_values_offs_ = 24; constexpr static int stack_space_needed_ = 32; bool are_post_ops_applicable_ = false; bool need_to_apply_alpha_beta_ = false; bool may_load_accumulators_ = false; bool handle_binary_po_offset_ = false; bool with_binary_per_oc_bcast_ = false; bool with_binary_per_oc_sp_bcast_ = false; bool with_binary_channel_bcast_ = false; bool with_binary_per_mb_w_bcast_ = false; bool with_binary_per_w_bcast_ = false; bool with_binary_no_bcast_ = false; bool prepare_post_ops_registers_once_ = false; size_t b_offset_ = 0; char *bd_mask_buffer_ptr_ = nullptr; std::vector<size_t> adj_bd_mask_buffer_; size_t *adj_bd_mask_buffer_ptr_ = nullptr; std::vector<size_t> skipped_bd_mask_buffer_; size_t *skipped_bd_mask_buffer_ptr_ = nullptr; palette_config_t palette_; // used to store offsets within wsp buffer where the data is // transformed(downconverted), to reuse when needed. std::unordered_map<std::string, size_t> transform_buf_map_A_; std::unordered_map<std::string, size_t> transform_buf_map_B_; size_t LDA_size_, LDA2_size_; size_t LDB_size_, LDB2_size_; size_t LDC_size_, LDC2_size_M_, LDC2_size_N_; size_t LDD_size_; size_t ld_block_B_size_; size_t ld_block_C_size_; size_t ld_block_D_size_; size_t ld_block_bias_size_; size_t ld_block_scales_size_; size_t ld_block_zp_size_; size_t ldb_tail_B_size_; size_t ldb_tail_C_size_; size_t ldb_tail_D_size_; size_t ldb_tail_zp_size_; // variables of bd loop size_t inp_bd_; // interleave stores bool use_ils_ = false; int ils_store_ops_ = 0, ils_vecs_per_store_ = 0; bool ils_buffer_ready_ = false; // saved parameters for storing int ils_bd_block2_ = 0, ils_ld_block2_ = 0, ils_inp_bd_ = 0, ils_ldb_ind_ = 0, ils_apply_post_ops_ = 0, ils_is_ld_tail_ = 0; // current storing coordinates int ils_vec_ = 0, ils_bdb_ = 0, ils_ldb_ = 0, ils_bd_start_ = 0, ils_bd_step_ = 0; int pfo_vec_ = 0, pfo_vecs_per_store_ = 0; bool dt_requires_saturation_; Xbyak::Opmask ld_full_mask = Xbyak::Opmask(2); Xbyak::Opmask ld_tail_mask = Xbyak::Opmask(3); Xbyak::Opmask bf32_col_mask = Xbyak::Opmask(4); int adjusted_bd_block(int bdb) const noexcept { return (brg.is_M_tail && bdb == brg.bd_block2 - 1) ? brg.bdb_tail : brg.bd_block; } Xbyak::Zmm accm(int bd) { assert(bd < 16); return Xbyak::Zmm(31 - bd); } const Xbyak::Zmm &zmm_tmp_1() const noexcept { return this->zmm0; } const Xbyak::Zmm &zmm_tmp_2() const noexcept { return this->zmm1; } const Xbyak::Zmm &zmm_tmp_3() const noexcept { return this->zmm2; } Xbyak::Zmm zmm_bias(int ldb) { assert(ldb < 3); // zmm6, zmm7, zmm8 return Xbyak::Zmm(6 + ldb); } Xbyak::Zmm zmm_scales(int ldb) { assert(ldb < 3); // zmm9, zmm10, zmm11 return Xbyak::Zmm(9 + ldb); } const Xbyak::Zmm zmm_bf32_pemute = zmm12; const Xbyak::Zmm zmm_zp_comp_a = zmm12; const Xbyak::Zmm zmm_zp_c = zmm13; const Xbyak::Zmm zmm_lbound = zmm14; const Xbyak::Zmm zmm_ubound = zmm15; Xbyak::Zmm zmm_mask(const Xbyak::Zmm zmm_in, bool mask_flag, bool store, Xbyak::Opmask ktail_mask) const; Xbyak::Ymm ymm_mask(const Xbyak::Ymm ymm_in, bool mask_flag, bool store, Xbyak::Opmask ktail_mask) const; void cvt2ps(data_type_t type_in, const Xbyak::Zmm zmm_in, const Xbyak::Operand &op, bool mask_flag, bool store, Xbyak::Opmask ktail_mask); void read_params(); void load_accumulators( int bd_block2, int ld_block, bool is_ld_tail, int ldb_ind); void maybe_saturation(Xbyak::Zmm &zmm); void apply_alpha_beta_to_vector( const int idx, const Address &addr, bool is_ld_tail); void apply_post_ops_to_vector(const int idx, const Address &addr, const int bd, const int ldb, bool is_ld_tail); void apply_post_ops_to_range(int bd_start, int bd_finish, int bd_inp_bdb, int ldb, bool is_ld_tail); void store_vector_with_post_ops(const int idx, const Address &addr, const int bd, const int ldb, bool is_ld_tail); void prepare_post_ops_registers_ldb( int ldb, bool is_ld_tail, bool apply_post_ops); void prepare_post_ops_registers( int ldb_ind, int ld_block2, bool is_ld_tail, bool apply_post_ops); void prefetch_output_range(int bd_start, int bd_finish, int bd_inp_bdb, int ldb, bool apply_post_ops); void process_output_range(int bd_start, int bd_finish, int bd_inp_bdb, int bdb, int ldb_ind, int ldb, bool is_ld_tail, bool apply_post_ops); void store_vector_without_post_ops( const int idx, const Address &addr, bool is_ld_tail); void store_vector(const int idx, const int bd, const int ldb, const bool apply_post_ops, bool is_ld_tail); void prefetch_output_data(int ldb_ind, int bd_block2, int ld_block2); void interleave_store(bool store_all); void store_accumulators(int bd_block2, int ld_block, bool is_ld_tail, int ldb_ind, bool apply_post_ops); void set_A_B_matrices(int bs); void set_A_B_matrices(); void bf32_downconvert(int num_rows, int tile_num_col_bytes, reg64_t reg_data, int offset, reg64_t reg_data_stride, reg64_t reg_buf, bool is_rd_tail); void bf32_downconvert_to_vnni(int num_rows, int tile_num_col_bytes, reg64_t reg_data, int offset, reg64_t reg_data_stride, reg64_t reg_buf, bool is_rd_tail); void maybe_pre_process_data(const Tmm &t1, reg64_t reg_base, size_t offset, reg64_t reg_stride, int bs, int rbd, matrix_kind_t mk, bool is_rd_tail); void maybe_tileloadd_nt(matrix_kind_t mk, int bs, int xdb, int rdb, size_t offset, bool is_rd_tail); void tdpbxxd(int bdb_idx, int ldb_idx, int bd_block2, int ld_block2, int ldb_ind); void gemm_microkernel_amx(int bs, int bd_block2, int ldb_ind, int ld_block2, bool is_rd_tail, bool is_ld_tail); void ldb_loop(int bd_block2, int ld_block, int ldb_loop_length, bool is_reg_tail, bool is_ld_tail, size_t c_offset, size_t d_offset, int ldb_ind, bool apply_post_ops); void bdb_loop(bool apply_post_ops); void generate() override; void prepare_bd_mask() noexcept; int skipped_bd_mask(int inp_bd) noexcept; size_t A_offset(int bdb) const noexcept; size_t B_offset(int ldb) const noexcept; size_t C_offset(int bd, int ldb) const noexcept; size_t C_block_offset(int bd, int ldb) const noexcept; size_t D_offset(int bd, int ldb) const noexcept; size_t lda() const noexcept; size_t ldb() const noexcept; size_t rdb_A_offset() const noexcept; size_t rdb_B_offset() const noexcept; size_t ldb_B_offset(int ld_block2, bool is_tail = false) const noexcept; size_t ldb_C_offset(int ld_block2, bool is_tail = false) const noexcept; size_t ldb_D_offset(int ld_block2, bool is_tail = false) const noexcept; size_t bias_offset(int ldb) const noexcept; size_t scales_offset(int ldb) const noexcept; size_t zp_comp_a_offset(int ldb) const noexcept; size_t zp_comp_b_offset(int bd) const noexcept; size_t zp_c_values_offset(int ldb, bool is_tail = false) const noexcept; int get_out_bd(int bd_inp_bdb, int bd) const; }; void jit_brgemm_amx_uker_base_t::prepare_bd_mask() noexcept { if (!brg.brgattr.bd_mask_level) return; bd_mask_buffer_ptr_ = brg.brgattr.bd_mask; const auto bd_mask_size = brg.bcast_dim; adj_bd_mask_buffer_.resize(bd_mask_size); adj_bd_mask_buffer_ptr_ = adj_bd_mask_buffer_.data(); skipped_bd_mask_buffer_.resize(bd_mask_size); skipped_bd_mask_buffer_ptr_ = skipped_bd_mask_buffer_.data(); if (!utils::any_null(bd_mask_buffer_ptr_, adj_bd_mask_buffer_ptr_)) { int out_ibd = 0; for (int i = 0; i < bd_mask_size; i++) { adj_bd_mask_buffer_ptr_[i] = out_ibd; out_ibd += bd_mask_buffer_ptr_[i]; skipped_bd_mask_buffer_ptr_[i] = i; for (auto ii = i; ii < bd_mask_size; ii++) { if (bd_mask_buffer_ptr_[ii]) { skipped_bd_mask_buffer_ptr_[i] = ii; break; } } } } else assert(!"struct nullptr error"); } int jit_brgemm_amx_uker_base_t::skipped_bd_mask(int inp_bd) noexcept { if (brg.brgattr.bd_mask_level != 2) return inp_bd; else return skipped_bd_mask_buffer_ptr_[inp_bd]; } size_t jit_brgemm_amx_uker_base_t::A_offset(int bdb) const noexcept { return bdb * LDA2_size_; } size_t jit_brgemm_amx_uker_base_t::B_offset(int ldb) const noexcept { return (brg.is_blocked ? 1 : brg.rd_step) * ldb * ld_block_B_size_; } size_t jit_brgemm_amx_uker_base_t::C_offset(int bd, int ldb) const noexcept { return bd * LDC_size_ + ldb * ld_block_C_size_; } size_t jit_brgemm_amx_uker_base_t::C_block_offset(int bd, int ldb) const noexcept { return (size_t)bd * LDC2_size_M_ + (size_t)ldb * LDC2_size_N_; } size_t jit_brgemm_amx_uker_base_t::D_offset(int bd, int ldb) const noexcept { return bd * LDD_size_ + ldb * ld_block_D_size_; } size_t jit_brgemm_amx_uker_base_t::lda() const noexcept { return LDA_size_; } size_t jit_brgemm_amx_uker_base_t::ldb() const noexcept { return LDB_size_ * brg.rd_step; } size_t jit_brgemm_amx_uker_base_t::rdb_A_offset() const noexcept { return brg.typesize_A * brg.rd_block; } size_t jit_brgemm_amx_uker_base_t::rdb_B_offset() const noexcept { return brg.rd_block * LDB_size_; } size_t jit_brgemm_amx_uker_base_t::ldb_B_offset( int ld_block2, bool is_tail) const noexcept { return (is_tail) ? ldb_tail_B_size_ * brg.ld_step : ld_block2 * ld_block_B_size_ * brg.ld_step; } size_t jit_brgemm_amx_uker_base_t::ldb_C_offset( int ld_block2, bool is_tail) const noexcept { return (is_tail) ? ldb_tail_C_size_ : ld_block2 * ld_block_C_size_; } size_t jit_brgemm_amx_uker_base_t::ldb_D_offset( int ld_block2, bool is_tail) const noexcept { return (is_tail) ? ldb_tail_D_size_ : ld_block2 * ld_block_D_size_; } size_t jit_brgemm_amx_uker_base_t::bias_offset(int ldb) const noexcept { return ldb * ld_block_bias_size_; } size_t jit_brgemm_amx_uker_base_t::scales_offset(int ldb) const noexcept { return brg.is_oc_scale * ldb * ld_block_scales_size_; } size_t jit_brgemm_amx_uker_base_t::zp_comp_a_offset(int ldb) const noexcept { return ldb * ld_block_zp_size_; } size_t jit_brgemm_amx_uker_base_t::zp_comp_b_offset(int bd) const noexcept { return sizeof(int32_t) * bd; } size_t jit_brgemm_amx_uker_base_t::zp_c_values_offset( int ldb, bool is_tail) const noexcept { if (brg.zp_type_c == brgemm_broadcast_t::per_n) { return (is_tail) ? ldb_tail_zp_size_ : ldb * ld_block_zp_size_; } return 0; } int jit_brgemm_amx_uker_base_t::get_out_bd(int bd_inp_bdb, int bd) const { const auto bd_out_bd = bd_inp_bdb + bd; if (brg.brgattr.bd_mask_level && !bd_mask_buffer_ptr_[bd_out_bd]) return -1; else { if (brg.brgattr.bd_mask_level) return adj_bd_mask_buffer_ptr_[bd_out_bd]; else return bd_out_bd; } } Xbyak::Zmm jit_brgemm_amx_uker_base_t::zmm_mask(const Xbyak::Zmm zmm_in, bool mask_flag, bool store, Xbyak::Opmask ktail_mask) const { return mask_flag ? (store ? zmm_in | ktail_mask : zmm_in | ktail_mask | T_z) : zmm_in; } Xbyak::Ymm jit_brgemm_amx_uker_base_t::ymm_mask(const Xbyak::Ymm ymm_in, bool mask_flag, bool store, Xbyak::Opmask ktail_mask) const { return mask_flag ? (store ? ymm_in | ktail_mask : ymm_in | ktail_mask | T_z) : ymm_in; } void jit_brgemm_amx_uker_base_t::cvt2ps(data_type_t type_in, const Xbyak::Zmm zmm_in, const Xbyak::Operand &op, bool mask_flag, bool store, Xbyak::Opmask ktail_mask) { const Xbyak::Zmm zmm = zmm_mask(zmm_in, mask_flag, store, ktail_mask); switch (type_in) { case data_type::f32: case data_type::s32: vmovups(zmm, op); break; case data_type::bf16: vpmovzxwd(zmm, op); vpslld(zmm, zmm, 16); break; case data_type::s8: vpmovsxbd(zmm, op); break; case data_type::u8: vpmovzxbd(zmm, op); break; default: assert(!"unsupported data type"); } if (!one_of(type_in, data_type::f32, data_type::bf16)) vcvtdq2ps(zmm_in, zmm_in); } void jit_brgemm_amx_uker_base_t::read_params() { Label label_done; mov(reg_C, ptr[param1 + GET_OFF(ptr_C)]); mov(reg_D, ptr[param1 + GET_OFF(ptr_D)]); mov(reg_BS, ptr[param1 + GET_OFF(BS)]); mov(reg_addr_batch, ptr[param1 + GET_OFF(batch)]); mov(reg_buf, ptr[param1 + GET_OFF(ptr_buf)]); if (brg.zp_type_a != brgemm_broadcast_t::none) { mov(reg_zp_comp_a, ptr[param1 + GET_OFF(a_zp_compensations)]); mov(ptr[rsp + reg_zp_comp_a_offs_], reg_zp_comp_a); } if (brg.zp_type_b != brgemm_broadcast_t::none) { mov(reg_zp_comp_b, ptr[param1 + GET_OFF(b_zp_compensations)]); mov(ptr[rsp + reg_zp_comp_b_offs_], reg_zp_comp_b); } if (brg.zp_type_c != brgemm_broadcast_t::none) { mov(reg_zp_c_values, ptr[param1 + GET_OFF(c_zp_values)]); mov(ptr[rsp + reg_zp_c_values_offs_], reg_zp_c_values); } } void jit_brgemm_amx_uker_base_t::load_accumulators( int bd_block2, int ld_block2, bool is_ld_tail, int ldb_ind) { assert(IMPLICATION(is_ld_tail, ld_block2 == 1)); if (may_load_accumulators_) mov(reg_stride_ld_block, LDC_size_); int bd_inp_bdb = inp_bd_; for (int bdb = 0; bdb < bd_block2; bdb++) { for (int ldb = 0; ldb < ld_block2; ldb++) { int idx = (is_ld_tail) ? brg.ld_block2 : ldb; if (may_load_accumulators_) { const auto bd_out_bdb = get_out_bd(bd_inp_bdb, 0); const auto c_offset = C_block_offset(bd_out_bdb, ldb_ind + ldb); tileloadd(Tmm(brg.get_C_tensor(bdb, idx)), ptr[reg_C + c_offset + reg_stride_ld_block]); } else { tilezero(Tmm(brg.get_C_tensor(bdb, idx))); } } bd_inp_bdb += brg.bd_block; bd_inp_bdb = skipped_bd_mask(bd_inp_bdb); } } void jit_brgemm_amx_uker_base_t::apply_alpha_beta_to_vector( const int idx, const Address &addr, bool is_ld_tail) { auto k_mask = (!is_ld_tail) ? ld_full_mask : ld_tail_mask; auto zmm = Zmm(idx); auto zmm_beta = zmm_tmp_1(); auto zmm_alpha = zmm_tmp_2(); auto zmm_prev_dst = zmm_tmp_3(); const bool apply_alpha = brg.alpha != 1.f; const bool apply_beta = brg.beta != 0.f; if (!apply_alpha && !apply_beta) return; const bool dq2ps_required = brg.is_int8 && (apply_alpha || brg.beta != 1.f); const bool use_vadd_for_beta = brg.beta == 1.f && !dq2ps_required; if (apply_beta && !use_vadd_for_beta) { mov(reg_tmp_gpr, float2int(static_cast<float>(brg.beta))); movq(Xmm(zmm_beta.getIdx()), reg_tmp_gpr); vbroadcastss(zmm_beta, Xmm(zmm_beta.getIdx())); } if (apply_alpha) { mov(reg_tmp_gpr, float2int(static_cast<float>(brg.alpha))); movq(Xmm(zmm_alpha.getIdx()), reg_tmp_gpr); vbroadcastss(zmm_alpha, Xmm(zmm_alpha.getIdx())); } if (dq2ps_required) vcvtdq2ps(zmm, zmm); if (apply_alpha) vmulps(zmm, zmm, zmm_alpha); if (apply_beta) { if (use_vadd_for_beta) { auto zmm_masked = zmm | k_mask | T_z; if (brg.is_int8) vpaddd(zmm_masked, zmm, addr); else vaddps(zmm_masked, zmm, addr); } else { cvt2ps(brg.dt_c, zmm_prev_dst, addr, true, false, k_mask); vfmadd231ps(zmm, zmm_prev_dst, zmm_beta); } } } void jit_brgemm_amx_uker_base_t::apply_post_ops_to_vector(const int idx, const Address &addr, const int bd, const int ldb, bool is_ld_tail) { binary_injector::rhs_arg_dynamic_params_t rhs_arg_params; auto zmm = Zmm(idx); if (brg.with_binary) { if (handle_binary_po_offset_) { rhs_arg_params.vmm_idx_to_out_reg.emplace(idx, reg_D); rhs_arg_params.vmm_idx_to_out_elem_off_val.emplace( idx, D_offset(bd, ldb)); if (is_ld_tail) rhs_arg_params.vmm_tail_idx_.emplace(idx); } } const auto sum_injector = [&] { const float *p_sum_scale = &brg.sum_scale; const bool p_sum_scale_reg_set = *p_sum_scale != 1.f; const int32_t *p_sum_zp = &brg.sum_zp; const bool p_sum_zp_reg_set = *p_sum_zp != 0; if (p_sum_scale_reg_set) mov(reg_ptr_sum_scale, (size_t)p_sum_scale); const auto &zmm_sum_zp = zmm_tmp_2(); if (p_sum_zp_reg_set) { mov(reg_ptr_sum_zp, reinterpret_cast<size_t>(p_sum_zp)); vcvtdq2ps(zmm_sum_zp, ptr_b[reg_ptr_sum_zp]); } const auto k_mask = (!is_ld_tail) ? ld_full_mask : ld_tail_mask; const auto zmm_prev_dst = Xbyak::Zmm(0); cvt2ps(brg.sum_dt, zmm_prev_dst, addr, true, false, k_mask); if (p_sum_zp_reg_set) vsubps(zmm_prev_dst, zmm_sum_zp); if (!p_sum_scale_reg_set) vaddps(zmm, zmm_prev_dst); else vfmadd231ps(zmm, zmm_prev_dst, zword_b[reg_ptr_sum_scale]); }; if (brg.with_sum) { postops_injector_->set_lambda_injector( primitive_kind::sum, sum_injector); } postops_injector_->compute_vector(zmm.getIdx(), rhs_arg_params); } void jit_brgemm_amx_uker_base_t::apply_post_ops_to_range( int bd_start, int bd_finish, int bd_inp_bdb, int ldb, bool is_ld_tail) { binary_injector::rhs_arg_dynamic_params_t rhs_arg_params; if (brg.with_binary) { if (handle_binary_po_offset_) { for (int bd = bd_start; bd < bd_finish; bd++) { // We have no way to tell the injector to skip some vectors. // Therefore, we must set parameters correctly for all registers. // TODO: Make it possible to specify "skipped" vectors to injector const auto idx = accm(bd).getIdx(); if (is_ld_tail) rhs_arg_params.vmm_tail_idx_.emplace(idx); rhs_arg_params.vmm_idx_to_out_reg.emplace(idx, reg_D); const auto bd_out_bd = get_out_bd(bd_inp_bdb, bd); if (bd_out_bd == -1) continue; const auto d_offset = D_offset(bd_out_bd, ldb); rhs_arg_params.vmm_idx_to_out_elem_off_val.emplace( idx, d_offset); } } } const auto sum_injector = [&] { const float *p_sum_scale = &brg.sum_scale; const int32_t *p_sum_zp = &brg.sum_zp; const bool p_sum_scale_reg_set = *p_sum_scale != 1.f; const bool p_sum_zp_reg_set = *p_sum_zp != 0; { if (p_sum_scale_reg_set) mov(reg_ptr_sum_scale, reinterpret_cast<size_t>(p_sum_scale)); const auto &zmm_sum_zp = zmm_tmp_2(); if (p_sum_zp_reg_set) { mov(reg_ptr_sum_zp, reinterpret_cast<size_t>(p_sum_zp)); vcvtdq2ps(zmm_sum_zp, ptr_b[reg_ptr_sum_zp]); } const auto k_mask = (!is_ld_tail) ? ld_full_mask : ld_tail_mask; const auto zmm_prev_dst = Xbyak::Zmm(0); for (int bd = bd_start; bd < bd_finish; bd++) { const auto bd_out_bd = get_out_bd(bd_inp_bdb, bd); if (bd_out_bd == -1) continue; auto zmm = accm(bd); const auto d_offset = D_offset(bd_out_bd, ldb); auto addr = EVEX_compress_addr(reg_D, d_offset); cvt2ps(brg.sum_dt, zmm_prev_dst, addr, true, false, k_mask); if (p_sum_zp_reg_set) vsubps(zmm_prev_dst, zmm_sum_zp); if (!p_sum_scale_reg_set) vaddps(zmm, zmm_prev_dst); else vfmadd231ps(zmm, zmm_prev_dst, zword_b[reg_ptr_sum_scale]); } } }; if (brg.with_sum) { postops_injector_->set_lambda_injector( primitive_kind::sum, sum_injector); } postops_injector_->compute_vector_range( 32 - bd_finish, 32 - bd_start, rhs_arg_params); } void jit_brgemm_amx_uker_base_t::maybe_saturation(Xbyak::Zmm &zmm) { if (!dt_requires_saturation_) return; saturate_f32(zmm, zmm_lbound, zmm_ubound, brg.dt_d); vcvtps2dq(zmm, zmm); } void jit_brgemm_amx_uker_base_t::prepare_post_ops_registers_ldb( int ldb, bool is_ld_tail, bool apply_post_ops) { if (!apply_post_ops) return; auto k_mask = (!is_ld_tail) ? ld_full_mask : ld_tail_mask; if (brg.zp_type_a != brgemm_broadcast_t::none) { mov(reg_aux_zp_comp_a, ptr[rsp + reg_zp_comp_a_offs_]); int zp_comp_a_off = zp_comp_a_offset(ldb); auto zp_comp_a_addr = EVEX_compress_addr(reg_aux_zp_comp_a, zp_comp_a_off); cvt2ps(data_type::s32, zmm_zp_comp_a, zp_comp_a_addr, true, false, k_mask); } if (brg.zp_type_c != brgemm_broadcast_t::none) { mov(reg_zp_c_values, ptr[rsp + reg_zp_c_values_offs_]); if (brg.zp_type_c == brgemm_broadcast_t::per_tensor) { vcvtdq2ps(zmm_zp_c, EVEX_compress_addr(reg_zp_c_values, 0, true)); } if (brg.zp_type_c == brgemm_broadcast_t::per_n) { int zp_c_off = zp_c_values_offset(ldb, is_ld_tail); auto zp_c_addr = EVEX_compress_addr(reg_zp_c_values, zp_c_off); cvt2ps(data_type::s32, zmm_zp_c, zp_c_addr, true, false, k_mask); } } } void jit_brgemm_amx_uker_base_t::prepare_post_ops_registers( int ldb_ind, int ld_block2, bool is_ld_tail, bool apply_post_ops) { if (!apply_post_ops) return; auto k_mask = (!is_ld_tail) ? ld_full_mask : ld_tail_mask; if (brg.with_bias) { mov(reg_bias, ptr[param1 + GET_OFF(ptr_bias)]); for (int ldb = 0; ldb < ld_block2; ldb++) { auto ptr_bias = EVEX_compress_addr(reg_bias, bias_offset(ldb_ind + ldb)); cvt2ps(brg.dt_bias, zmm_bias(ldb), ptr_bias, true, false, k_mask); } } if (brg.with_scales) { mov(reg_scales, ptr[param1 + GET_OFF(ptr_scales)]); for (int ldb = 0; ldb < ld_block2; ldb++) { auto scales_ptr = EVEX_compress_addr( reg_scales, scales_offset(ldb_ind + ldb)); vmovups(zmm_scales(ldb) | k_mask | T_z, scales_ptr); } } } void jit_brgemm_amx_uker_base_t::prefetch_output_range(int bd_start, int bd_finish, int bd_inp_bdb, int ldb, bool apply_post_ops) { for (int bd = bd_start; bd < bd_finish; bd++) { const auto bd_out_bd = get_out_bd(bd_inp_bdb, bd); if (bd_out_bd == -1) continue; if (apply_post_ops) { const auto d_offset = D_offset(bd_out_bd, ldb); auto ptr_D = EVEX_compress_addr(reg_D, d_offset); prefetcht1(ptr_D); } else if (are_post_ops_applicable_) { const auto c_offset = C_offset(bd_out_bd, ldb); auto ptr_C = EVEX_compress_addr(reg_C, c_offset); prefetcht1(ptr_C); } else { const auto d_offset = D_offset(bd_out_bd, ldb); auto ptr_D = EVEX_compress_addr(reg_D, d_offset); prefetcht1(ptr_D); } } } void jit_brgemm_amx_uker_base_t::process_output_range(int bd_start, int bd_finish, int bd_inp_bdb, int bdb, int ldb_ind, int ldb, bool is_ld_tail, bool apply_post_ops) { const int wsp_offset = use_ils_ ? (bdb * ils_ld_block2_ + ldb) * brg.bd_block * ld_block_C_size_ : 0; auto k_mask = (!is_ld_tail) ? ld_full_mask : ld_tail_mask; // if (brg.is_int8 && alpha_or_beta_applicable && !beta_uses_vadd) -> // accumulated values are already converted to ps in apply_alpha_beta() const bool alpha_or_beta_applicable = brg.alpha != 1.0f || brg.beta != 0.f; const bool beta_uses_vadd = brg.beta == 1.f && IMPLICATION(brg.is_int8, brg.alpha == 1.0f); const bool dq2ps_required = brg.is_int8 && IMPLICATION(alpha_or_beta_applicable, beta_uses_vadd); bool some_bd_mask = false; for (int bd = bd_start; bd < bd_finish; bd++) { auto zmm = accm(bd); const auto bd_out_bd = get_out_bd(bd_inp_bdb, bd); if (bd_out_bd == -1) continue; auto vreg_acc = is_ld_tail ? accm(bd) | ld_tail_mask | T_z : accm(bd); some_bd_mask = true; size_t buf_offset = bd * ld_block_C_size_; vmovups(vreg_acc, ptr[reg_buf + buf_offset + wsp_offset]); const auto c_offset = C_offset(bd_out_bd, ldb_ind + ldb); auto ptr_C = EVEX_compress_addr(reg_C, c_offset); if (need_to_apply_alpha_beta_) apply_alpha_beta_to_vector(zmm.getIdx(), ptr_C, is_ld_tail); if (!apply_post_ops) continue; if (dq2ps_required) vcvtdq2ps(zmm, zmm); } if (!apply_post_ops || !some_bd_mask) return; if (brg.with_bias) { for (int bd = bd_start; bd < bd_finish; bd++) { const auto bd_out_bd = get_out_bd(bd_inp_bdb, bd); if (bd_out_bd == -1) continue; auto zmm = accm(bd); vaddps(zmm, zmm, zmm_bias(ldb)); } } if (brg.zp_type_a != brgemm_broadcast_t::none) { for (int bd = bd_start; bd < bd_finish; bd++) { const auto bd_out_bd = get_out_bd(bd_inp_bdb, bd); if (bd_out_bd == -1) continue; auto zmm = accm(bd); vaddps(zmm, zmm, zmm_zp_comp_a); } } if (brg.zp_type_b != brgemm_broadcast_t::none) { mov(reg_zp_comp_b, ptr[rsp + reg_zp_comp_b_offs_]); auto zmm_zp_comp_b = zmm_tmp_1(); for (int bd = bd_start; bd < bd_finish; bd++) { const auto bd_out_bd = get_out_bd(bd_inp_bdb, bd); if (bd_out_bd == -1) continue; auto zmm = accm(bd); int zp_comp_b_off = zp_comp_b_offset(bd_out_bd); vcvtdq2ps(zmm_zp_comp_b, EVEX_compress_addr(reg_zp_comp_b, zp_comp_b_off, true)); vaddps(zmm, zmm, zmm_zp_comp_b); } } if (brg.with_scales) { for (int bd = bd_start; bd < bd_finish; bd++) { const auto bd_out_bd = get_out_bd(bd_inp_bdb, bd); if (bd_out_bd == -1) continue; auto zmm = accm(bd); const Xbyak::Zmm scaled_zmm = zmm_mask(zmm, true, false, k_mask); vmulps(scaled_zmm, scaled_zmm, zmm_scales(ldb)); } } if (postops_injector_) { apply_post_ops_to_range( bd_start, bd_finish, bd_inp_bdb, ldb_ind + ldb, is_ld_tail); } } void jit_brgemm_amx_uker_base_t::store_vector_with_post_ops(const int idx, const Address &addr, const int bd, const int ldb, bool is_ld_tail) { auto zmm = Zmm(idx); auto k_mask = (!is_ld_tail) ? ld_full_mask : ld_tail_mask; if (brg.zp_type_c != brgemm_broadcast_t::none) vaddps(zmm, zmm, zmm_zp_c); maybe_saturation(zmm); auto ymm = Xbyak::Ymm(idx); const Xbyak::Zmm r_zmm = zmm_mask(zmm, true, true, k_mask); const Xbyak::Ymm r_ymm = ymm_mask(ymm, true, true, k_mask); switch (brg.dt_d) { case data_type::f32: case data_type::s32: vmovups(addr, r_zmm); break; case data_type::bf16: vcvtneps2bf16(ymm, zmm); vmovdqu16(addr, r_ymm); break; case data_type::s8: vpmovsdb(addr, r_zmm); break; case data_type::u8: vpmovusdb(addr, r_zmm); break; default: assert(!"unknown dst_dt"); } } void jit_brgemm_amx_uker_base_t::store_vector_without_post_ops( const int idx, const Address &addr, bool is_ld_tail) { auto zmm = Zmm(idx); maybe_saturation(zmm); if (is_ld_tail) vmovups(addr | ld_tail_mask | T_z, zmm); else vmovups(addr, zmm); } void jit_brgemm_amx_uker_base_t::store_vector(const int idx, const int bd, const int ldb, const bool apply_post_ops, bool is_ld_tail) { const auto c_offset = C_offset(bd, ldb); const auto d_offset = D_offset(bd, ldb); auto ptr_C = EVEX_compress_addr(reg_C, c_offset); auto ptr_D = EVEX_compress_addr(reg_D, d_offset); if (apply_post_ops) store_vector_with_post_ops(idx, ptr_D, bd, ldb, is_ld_tail); else if (are_post_ops_applicable_) store_vector_without_post_ops(idx, ptr_C, is_ld_tail); else store_vector_without_post_ops(idx, ptr_D, is_ld_tail); } void jit_brgemm_amx_uker_base_t::prefetch_output_data( int ldb_ind, int bd_block2, int ld_block2) { if (brg.brgattr.hint_prefetching != brgemm_kernel_prefetching_t::brgemm_prf_output1) return; // last bd_block may be bd_tail const auto last_bd_block = adjusted_bd_block(bd_block2 - 1); const auto bdb_row = brg.bd_block * ld_block2; const auto tot_vecs = (bd_block2 - 1) * bdb_row + last_bd_block * ld_block2; const auto nvecs = nstl::min(pfo_vecs_per_store_, tot_vecs - pfo_vec_); for (int vec = 0; vec < nvecs && pfo_vec_ < tot_vecs; vec++) { int bdb = pfo_vec_ / bdb_row; auto adj_bd_block = adjusted_bd_block(bdb); auto vec_in_bdb_row = pfo_vec_ - bdb * bdb_row; int ldb = vec_in_bdb_row / adj_bd_block; int bd = vec_in_bdb_row % adj_bd_block; auto bd_inp_bdb = skipped_bd_mask(inp_bd_); for (int ibdb = 0; ibdb < bdb; ibdb++) { bd_inp_bdb += brg.bd_block; bd_inp_bdb = skipped_bd_mask(bd_inp_bdb); } prefetch_output_range( 0, 1, bd_inp_bdb + bd, ldb_ind + ldb, ils_apply_post_ops_); pfo_vec_++; } } void jit_brgemm_amx_uker_base_t::interleave_store(bool store_all) { if (!use_ils_) return; if (!ils_buffer_ready_) return; const auto need_apply_post_ops = are_post_ops_applicable_ && ils_apply_post_ops_; if (!need_to_apply_alpha_beta_ && !need_apply_post_ops && !brg.brgattr.bd_mask_level) return; int bd_inp_bdb = ils_inp_bd_; auto cur_bdb = ils_bdb_; auto cur_ldb = ils_ldb_; ils_bd_step_ = 3; // heuristic value // if first block if (ils_vec_ == 0) { if (!prepare_post_ops_registers_once_) prepare_post_ops_registers(ils_ldb_ind_, ils_ld_block2_, ils_is_ld_tail_, ils_apply_post_ops_); prepare_post_ops_registers_ldb( ils_ldb_ind_, ils_is_ld_tail_, ils_apply_post_ops_); ils_bd_start_ = 0; auto bd_finish = nstl::min(ils_bd_step_, adjusted_bd_block(cur_bdb)); process_output_range(0, bd_finish, bd_inp_bdb, cur_bdb, ils_ldb_ind_, cur_ldb, ils_is_ld_tail_, ils_apply_post_ops_); } // last bd_block may be bd_tail const auto last_bd_block = adjusted_bd_block(ils_bd_block2_ - 1); const auto bdb_row = brg.bd_block * ils_ld_block2_; const auto total_vectors = (ils_bd_block2_ - 1) * bdb_row + last_bd_block * ils_ld_block2_; const auto nvecs = store_all ? total_vectors : ils_vecs_per_store_; for (int vec = 0; vec < nvecs && ils_vec_ < total_vectors; vec++) { int bdb = ils_vec_ / bdb_row; auto adj_bd_block = adjusted_bd_block(bdb); auto vec_in_bdb_row = ils_vec_ - bdb * bdb_row; int ldb = vec_in_bdb_row / adj_bd_block; int bd = vec_in_bdb_row % adj_bd_block; auto bd_inp_bdb = ils_inp_bd_; for (int ibdb = 0; ibdb < bdb; ibdb++) { bd_inp_bdb += brg.bd_block; bd_inp_bdb = skipped_bd_mask(bd_inp_bdb); } if (ldb != cur_ldb) prepare_post_ops_registers_ldb( ils_ldb_ind_ + ldb, ils_is_ld_tail_, ils_apply_post_ops_); if (bdb != cur_bdb || ldb != cur_ldb || rnd_dn(bd, ils_bd_step_) != ils_bd_start_) { ils_bd_start_ = rnd_dn(bd, ils_bd_step_); auto bd_finish = nstl::min(ils_bd_start_ + ils_bd_step_, adj_bd_block); process_output_range(ils_bd_start_, bd_finish, bd_inp_bdb, bdb, ils_ldb_ind_, ldb, ils_is_ld_tail_, ils_apply_post_ops_); } const auto bd_out_bd = get_out_bd(bd_inp_bdb, bd); if (bd_out_bd != -1) { auto vreg_acc = ils_is_ld_tail_ ? accm(bd) | ld_tail_mask | T_z : accm(bd); store_vector(vreg_acc.getIdx(), bd_out_bd, ils_ldb_ind_ + ldb, ils_apply_post_ops_, ils_is_ld_tail_); } cur_bdb = bdb; cur_ldb = ldb; ils_vec_++; } ils_ldb_ = cur_ldb; ils_bdb_ = cur_bdb; } void jit_brgemm_amx_uker_base_t::store_accumulators(int bd_block2, int ld_block2, bool is_ld_tail, int ldb_ind, bool apply_post_ops) { const bool need_to_apply_post_ops = are_post_ops_applicable_ && apply_post_ops; const auto store_by_vectors = need_to_apply_alpha_beta_ || need_to_apply_post_ops || brg.brgattr.bd_mask_level; if (store_by_vectors) mov(reg_stride_ld_block, ld_block_C_size_); else mov(reg_stride_ld_block, LDC_size_); int bd_inp_bdb = inp_bd_; ils_bd_block2_ = bd_block2; ils_ld_block2_ = ld_block2; ils_inp_bd_ = inp_bd_; ils_ldb_ind_ = ldb_ind; ils_apply_post_ops_ = apply_post_ops; ils_is_ld_tail_ = is_ld_tail; ils_vec_ = 0; ils_bdb_ = 0; ils_ldb_ = 0; ils_buffer_ready_ = true; ils_store_ops_ = ld_block2 * bd_block2 * brg.bd_block; pfo_vec_ = 0; if (store_by_vectors && !use_ils_ && !prepare_post_ops_registers_once_) prepare_post_ops_registers( ldb_ind, ld_block2, is_ld_tail, apply_post_ops); for (int bdb = 0; bdb < bd_block2; bdb++) { int adj_bd_block = adjusted_bd_block(bdb); for (int ldb = 0; ldb < ld_block2; ldb++) { int idx = (is_ld_tail) ? brg.ld_block2 : ldb; const int wsp_offset = use_ils_ ? (bdb * ld_block2 + ldb) * brg.bd_block * ld_block_C_size_ : 0; if (store_by_vectors) { tilestored(ptr[reg_buf + reg_stride_ld_block + wsp_offset], Tmm(brg.get_C_tensor(bdb, idx))); if (use_ils_) continue; prepare_post_ops_registers_ldb( ldb_ind + ldb, is_ld_tail, apply_post_ops); process_output_range(0, adj_bd_block, bd_inp_bdb, bdb, ldb_ind, ldb, is_ld_tail, apply_post_ops); for (int bd = 0; bd < adj_bd_block; bd++) { const auto bd_out_bd = get_out_bd(bd_inp_bdb, bd); if (bd_out_bd == -1) continue; auto vreg_acc = is_ld_tail ? accm(bd) | ld_tail_mask | T_z : accm(bd); store_vector(vreg_acc.getIdx(), bd_out_bd, ldb_ind + ldb, apply_post_ops, is_ld_tail); } } else { const auto bd_out_bdb = get_out_bd(bd_inp_bdb, 0); const auto c_offset = C_block_offset(bd_out_bdb, ldb_ind + ldb); tilestored(ptr[reg_C + c_offset + reg_stride_ld_block], Tmm(brg.get_C_tensor(bdb, idx))); } } bd_inp_bdb += brg.bd_block; bd_inp_bdb = skipped_bd_mask(bd_inp_bdb); } } void jit_brgemm_amx_uker_base_t::set_A_B_matrices(int bs) { assert(brg.type == brgemm_addr); auto batch_offset = (size_t)bs * sizeof(brgemm_batch_element_t); if (brg.layout == brgemm_row_major) { mov(reg_aux_A, EVEX_compress_addr(reg_addr_batch, batch_offset + GET_OFF_BATCH_ELEMENT(ptr.A))); mov(reg_aux_B, EVEX_compress_addr(reg_addr_batch, batch_offset + GET_OFF_BATCH_ELEMENT(ptr.B))); } else { mov(reg_aux_A, EVEX_compress_addr(reg_addr_batch, batch_offset + GET_OFF_BATCH_ELEMENT(ptr.B))); mov(reg_aux_B, EVEX_compress_addr(reg_addr_batch, batch_offset + GET_OFF_BATCH_ELEMENT(ptr.A))); } } void jit_brgemm_amx_uker_base_t::set_A_B_matrices() { assert(brg.type == brgemm_addr); assert(brg.brgattr.var_bs); if (brg.layout == brgemm_row_major) { mov(reg_aux_A, ptr[reg_aux1_batch + GET_OFF_BATCH_ELEMENT(ptr.A)]); mov(reg_aux_B, ptr[reg_aux1_batch + GET_OFF_BATCH_ELEMENT(ptr.B)]); } else { mov(reg_aux_A, ptr[reg_aux1_batch + GET_OFF_BATCH_ELEMENT(ptr.B)]); mov(reg_aux_B, ptr[reg_aux1_batch + GET_OFF_BATCH_ELEMENT(ptr.A)]); } } void jit_brgemm_amx_uker_base_t::maybe_tileloadd_nt(matrix_kind_t mk, int bs, int xdb, int rdb, size_t offset, bool is_rd_tail) { const bool try_load_nt_A = (brg.brgattr.hint_innermost_loop == brgemm_bd_loop_innermost); const bool try_load_nt_B = (brg.brgattr.hint_innermost_loop == brgemm_ld_loop_innermost); const bool is_A = mk == matrix_kind_t::matrix_A; bool try_load_nt = is_A ? try_load_nt_A : try_load_nt_B; try_load_nt = try_load_nt && (static_cast<size_t>(brg.typesize_A) * brg.brgattr.hint_expected_A_size + static_cast<size_t>(brg.typesize_B) * brg.brgattr.hint_expected_B_size + static_cast<size_t>(brg.typesize_C) * brg.brgattr.hint_expected_C_size) >= platform::get_per_core_cache_size(1); auto t1 = Tmm(is_A ? brg.get_A_tensor(xdb) : brg.get_B_tensor(xdb)); auto reg_base = is_A ? reg_aux_A : reg_aux_B; auto reg_stride = is_A ? reg_stride_lda : reg_stride_ldb; if (brg.is_bf32) // try_load_nt is not supported in maybe_pre_process_data as there is // no guarantee that the data is cacheline aligned. maybe_pre_process_data( t1, reg_base, offset, reg_stride, bs, rdb, mk, is_rd_tail); else if (try_load_nt) tileloaddt1(t1, ptr[reg_base + offset + reg_stride]); else tileloadd(t1, ptr[reg_base + offset + reg_stride]); } void jit_brgemm_amx_uker_base_t::tdpbxxd( int bdb_idx, int ldb_idx, int bd_block2, int ld_block2, int ldb_ind) { prefetch_output_data(ldb_ind, bd_block2, ld_block2); const Tmm &x1 = Tmm(brg.get_C_tensor(bdb_idx, ldb_idx)); const Tmm &x2 = Tmm(brg.get_A_tensor(bdb_idx)); const Tmm &x3 = Tmm(brg.get_B_tensor(ldb_idx)); if (brg.is_bf32 || (brg.dt_a == data_type::bf16 && brg.dt_b == data_type::bf16)) { tdpbf16ps(x1, x2, x3); } else if (brg.dt_a == data_type::u8 && brg.dt_b == data_type::u8) { tdpbuud(x1, x2, x3); } else if (brg.dt_a == data_type::u8 && brg.dt_b == data_type::s8) { tdpbusd(x1, x2, x3); } else if (brg.dt_a == data_type::s8 && brg.dt_b == data_type::u8) { tdpbsud(x1, x2, x3); } else if (brg.dt_a == data_type::s8 && brg.dt_b == data_type::s8) { tdpbssd(x1, x2, x3); } else { assert(!"unsupported combination"); } interleave_store(false); } // This method down-converts the data from f32 to bf16 and saves at reg_buf. // Generally used by matrix_A, where no vnni transformation of data is needed. void jit_brgemm_amx_uker_base_t::bf32_downconvert(int num_rows, int tile_num_col_bytes, reg64_t reg_data, int offset, reg64_t reg_data_stride, reg64_t reg_buf, bool is_rd_tail) { const int rd_block = is_rd_tail ? brg.rdb_tail : brg.rd_block; const int max_num_cols = nstl::min<int>(tile_num_col_bytes / sizeof(bfloat16_t), rd_block); const int col_tail = max_num_cols % simd_w; auto zmm_1 = zmm_tmp_1(); auto zmm_2 = zmm_tmp_2(); auto zmm_2_masked = col_tail ? zmm_2 | bf32_col_mask | T_z : zmm_2; assert(max_num_cols > 0); if (col_tail) { const int tail_mask = (1 << col_tail) - 1; auto reg_tmp_32 = reg_tmp_gpr.cvt32(); mov(reg_tmp_32, tail_mask); kmovw(bf32_col_mask, reg_tmp_32); } // Note: using the same register used in col_tail, so order is important const auto reg_data_aux = reg_tmp_gpr; lea(reg_data_aux, ptr[reg_data + offset]); for (int r = 0; r < num_rows; ++r) { if (max_num_cols > 16) { vmovups(zmm_1, ptr[reg_data_aux]); vmovups(zmm_2_masked, ptr[reg_data_aux + zmm_width_in_bytes]); vcvtne2ps2bf16(zmm_1, zmm_2, zmm_1); // we assume enough padding space is available. vmovups(ptr[reg_buf + r * zmm_width_in_bytes], zmm_1); } else { auto ymm_1 = Ymm(zmm_1.getIdx()); auto ymm_1_masked = max_num_cols == 16 ? ymm_1 : ymm_1 | bf32_col_mask | T_z; vcvtneps2bf16(ymm_1_masked, ptr[reg_data_aux]); vmovups(ptr[reg_buf + r * zmm_width_in_bytes], ymm_1); } add(reg_data_aux, reg_data_stride); } } // This method down-converts and transforms the data from f32 to bf16_vnni // format. Generally used by matrix_B. void jit_brgemm_amx_uker_base_t::bf32_downconvert_to_vnni(int num_rows, int tile_num_col_bytes, reg64_t reg_data, int offset, reg64_t reg_data_stride, reg64_t reg_buf, bool is_rd_tail) { const int num_cols_ele = tile_num_col_bytes / sizeof(bfloat16_t); const int num_N = num_cols_ele / sizeof(bfloat16_t); const int col_tail = num_N % simd_w; const auto zmm_1 = zmm_tmp_1(); const auto zmm_2 = zmm_tmp_2(); assert(num_N > 0); auto load = [&](Zmm zmm, Address addr) { if (col_tail) vmovups(zmm | bf32_col_mask | T_z, addr); else vmovups(zmm, addr); }; if (col_tail) { const int tail_mask = (1 << col_tail) - 1; auto reg_tmp_32 = reg_tmp_gpr.cvt32(); mov(reg_tmp_32, tail_mask); kmovw(bf32_col_mask, reg_tmp_32); } // Note: using the same register used in col_tail, so order is important const auto reg_data_aux = reg_tmp_gpr; lea(reg_data_aux, ptr[reg_data + offset]); const int rd_block = is_rd_tail ? brg.rdb_tail : brg.rd_block; const int vnni_granularity = data_type_vnni_granularity(data_type_t::dnnl_bf16); const int r_end = nstl::min(utils::div_up(rd_block, vnni_granularity), num_rows); for (int r = 0; r < r_end; ++r) { load(zmm_1, ptr[reg_data_aux]); if (r * vnni_granularity + 1 >= rd_block) { vpxord(zmm_2, zmm_2, zmm_2); } else { load(zmm_2, ptr[reg_data_aux + reg_data_stride]); } vcvtne2ps2bf16(zmm_1, zmm_2, zmm_1); vpermw(zmm_1, zmm_bf32_pemute, zmm_1); vmovups(ptr[reg_buf + r * zmm_width_in_bytes], zmm_1); lea(reg_data_aux, ptr[reg_data_aux + vnni_granularity * reg_data_stride]); } // zero rest of the tile data if (r_end < num_rows) { vpxord(zmm_2, zmm_2, zmm_2); for (int r = r_end; r < num_rows; ++r) vmovups(ptr[reg_buf + r * zmm_width_in_bytes], zmm_2); } } void jit_brgemm_amx_uker_base_t::maybe_pre_process_data(const Tmm &t1, reg64_t reg_base, size_t offset, reg64_t reg_stride, int bs, int rdb, matrix_kind_t mk, bool is_rd_tail) { auto should_save_transform = [&](matrix_kind_t mk) { // save if there is a reuse if (mk == matrix_A) { return brg.ldb + (brg.ldb_tail != 0) > brg.ld_block2; } else { return brg.bdb + (brg.bdb_tail != 0) > brg.bd_block2; } }; const bool is_A = mk == matrix_A; auto &transform_buf = is_A ? transform_buf_map_A_ : transform_buf_map_B_; const int transform_offset = use_ils_ ? brg.get_num_C_tiles() * tile_size : 0; const int max_bdb2 = brg.bd_block2; const int max_rdb = brg.rdb + (brg.rdb_tail != 0); const int matrix_a_offset = transform_offset; const int matrix_b_offset = transform_offset + tile_size * (nstl::max<int>(should_save_transform(mk), should_save_transform(matrix_A) * brg.brgattr.max_bs * max_bdb2 * max_rdb)); const int matrix_offset = is_A ? matrix_a_offset : matrix_b_offset; const std::string key = std::to_string(bs) + "_" + std::to_string(offset); if (transform_buf.find(key) != transform_buf.end()) { auto buf_idx = transform_buf[key]; auto offt = matrix_offset + buf_idx * tile_size; tileloadd(t1, ptr[reg_buf + reg_bf32_stride + offt]); return; } int buf_offt = matrix_offset; // save offset of the transformation if required. if (should_save_transform(mk)) { auto buf_idx = transform_buf.size(); buf_offt = matrix_offset + buf_idx * tile_size; transform_buf[key] = buf_idx; } if (buf_offt) add(reg_buf, buf_offt); mov(reg_bf32_stride, zmm_width_in_bytes); const int num_rows = palette_.rows[t1.getIdx()]; const int num_col_bytes = palette_.cols[t1.getIdx()]; if (is_A) { bf32_downconvert(num_rows, num_col_bytes, reg_base, offset, reg_stride, reg_buf, is_rd_tail); } else { bf32_downconvert_to_vnni(num_rows, num_col_bytes, reg_base, offset, reg_stride, reg_buf, is_rd_tail); } // load into tmm from the transformed data. tileloadd(t1, ptr[reg_buf + reg_bf32_stride]); // reset buf pointer. if (buf_offt) sub(reg_buf, buf_offt); } void jit_brgemm_amx_uker_base_t::gemm_microkernel_amx(int bs, int bd_block2, int ldb_ind, int ld_block2, bool is_rd_tail, bool is_ld_tail) { int rbd_block = 0; size_t a_offset = 0, b_offset = 0; if (is_rd_tail) { rbd_block = 1; if (brg.rdb > 0) { a_offset = brg.rdb * rdb_A_offset(); b_offset = brg.rdb * rdb_B_offset(); } } else { rbd_block = brg.rdb; b_offset = a_offset = 0; } for (int rdb = 0; rdb < rbd_block; rdb++) { int bd_inp_bdb = inp_bd_; const size_t rdb_A_off = static_cast<size_t>(rdb) * rdb_A_offset() + a_offset; const size_t rdb_B_off = static_cast<size_t>(rdb) * rdb_B_offset() + b_offset_ + b_offset; for (int bdb = 0; bdb < bd_block2; bdb++) { maybe_tileloadd_nt(matrix_kind_t::matrix_A, bs, bdb, rdb, rdb_A_off + A_offset(bd_inp_bdb), is_rd_tail); bd_inp_bdb += brg.bd_block; bd_inp_bdb = skipped_bd_mask(bd_inp_bdb); for (int ldb = 0; ldb < ld_block2; ldb++) { if (bdb == 0) { const int ldb_idx = (is_ld_tail) ? brg.ld_block2 : ldb; maybe_tileloadd_nt(matrix_kind_t::matrix_B, bs, ldb_idx, rdb, rdb_B_off + B_offset(ldb), is_rd_tail); } if (ldb == 0) { if (bdb > 0) { const int ldb_idx = (is_ld_tail) ? brg.ld_block2 : ld_block2 - 1; const int bdb_idx = bdb - 1; tdpbxxd(bdb_idx, ldb_idx, bd_block2, ld_block2, ldb_ind); } } else { const int ldb_idx = (is_ld_tail) ? brg.ld_block2 : (ldb - 1); const int bdb_idx = bdb; tdpbxxd(bdb_idx, ldb_idx, bd_block2, ld_block2, ldb_ind); } } } // last tdpbxxd { const int ldb_idx = (is_ld_tail) ? brg.ld_block2 : (ld_block2 - 1); const int bdb_idx = bd_block2 - 1; tdpbxxd(bdb_idx, ldb_idx, bd_block2, ld_block2, ldb_ind); } } } void jit_brgemm_amx_uker_base_t::ldb_loop(int bd_block2, int ld_block2, int ldb_loop_length, bool is_reg_tail, bool is_ld_tail, size_t c_offset, size_t d_offset, int ldb_ind, bool apply_post_ops) { if (!is_reg_tail) b_offset_ = 0; for (int l_ldb = 0; l_ldb < ldb_loop_length; l_ldb++) { int calc_ops = brg.brgattr.max_bs * (brg.rdb + (brg.rdb_tail ? 1 : 0)) * ld_block2 * bd_block2; ils_vecs_per_store_ = (calc_ops) ? div_up(ils_store_ops_, calc_ops) : 0; pfo_vecs_per_store_ = ils_vecs_per_store_; const auto l_ldb_ind = l_ldb * (is_ld_tail ? brg.ldb_tail : ld_block2); load_accumulators( bd_block2, ld_block2, is_ld_tail, ldb_ind + l_ldb_ind); if (brg.alpha != 0.f) { if (brg.brgattr.var_bs) { Label BS_loop_label, end_BS_loop_label; mov(reg_BS_loop, reg_BS); cmp(reg_BS_loop, 0); jz(end_BS_loop_label, T_NEAR); mov(reg_aux1_batch, reg_addr_batch); L_aligned(BS_loop_label, 64); { set_A_B_matrices(); add(reg_aux1_batch, sizeof(brgemm_batch_element_t)); prefetcht0(ptr[reg_aux1_batch]); gemm_microkernel_amx(0, bd_block2, ldb_ind, ld_block2, false, is_ld_tail); if (brg.rdb_tail != 0) { gemm_microkernel_amx(0, bd_block2, ldb_ind, ld_block2, true, is_ld_tail); } dec(reg_BS_loop); cmp(reg_BS_loop, 0); jg(BS_loop_label, T_NEAR); } L(end_BS_loop_label); } else { for (int bs = 0; bs < brg.brgattr.max_bs; bs++) { set_A_B_matrices(bs); gemm_microkernel_amx(bs, bd_block2, ldb_ind, ld_block2, false, is_ld_tail); if (brg.rdb_tail != 0) { gemm_microkernel_amx(bs, bd_block2, ldb_ind, ld_block2, true, is_ld_tail); } } } } store_accumulators(bd_block2, ld_block2, is_ld_tail, ldb_ind + l_ldb_ind, apply_post_ops); b_offset_ += (is_ld_tail) ? ldb_B_offset(1, true) : ldb_B_offset(ld_block2); } } void jit_brgemm_amx_uker_base_t::bdb_loop(bool apply_post_ops) { ils_buffer_ready_ = false; ils_apply_post_ops_ = apply_post_ops; // for many primitives which use brgemm the brg.ldb2 is equal or less than 1 // so we can read post ops data only once per brgemm call if (brg.ldb2 > 1) { prepare_post_ops_registers_once_ = false; } else if (brg.ldb2 == 1) { if (brg.ldb2_tail == 0 && brg.ldb_tail == 0) { prepare_post_ops_registers_once_ = true; prepare_post_ops_registers(0, brg.ld_block2, false, apply_post_ops); } } else if (brg.ldb2_tail > 0) { if (brg.ldb_tail == 0) { prepare_post_ops_registers_once_ = true; prepare_post_ops_registers(0, brg.ldb2_tail, false, apply_post_ops); } } else { prepare_post_ops_registers_once_ = true; prepare_post_ops_registers(0, 1, true, apply_post_ops); } if (apply_post_ops) dt_requires_saturation_ = one_of( brg.dt_d, data_type::u8, data_type::s8, data_type::s32); else { // if (brg.is_int8 && alpha_or_beta_applicable && !beta_uses_vadd) -> // accumulated values are converted to ps in apply_alpha_beta() const bool alpha_or_beta_applicable = brg.alpha != 1.0f || brg.beta != 0.f; const bool beta_uses_vadd = brg.beta == 1.f && IMPLICATION(brg.is_int8, brg.alpha == 1.0f); dt_requires_saturation_ = brg.is_int8 && !IMPLICATION(alpha_or_beta_applicable, beta_uses_vadd); } if (dt_requires_saturation_) { init_saturate_f32( zmm_lbound, zmm_ubound, reg_tmp_gpr, data_type::f32, brg.dt_d); } auto do_ldb_loop = [=](int bd_block2, bool apply_post_ops) { size_t c_offset = 0; size_t d_offset = 0; int ldb_ind = 0; // clear the transform cache for A, as the existing data is invalid as // we move to next bdb2 block. transform_buf_map_A_.clear(); if (brg.ldb2 > 0) { const bool is_ld_reg_tail = false; const bool is_ld_tail = false; ldb_loop(bd_block2, brg.ld_block2, brg.ldb2, is_ld_reg_tail, is_ld_tail, c_offset, d_offset, ldb_ind, apply_post_ops); c_offset += brg.ldb2 * ldb_C_offset(brg.ld_block2); d_offset += brg.ldb2 * ldb_D_offset(brg.ld_block2); ldb_ind += brg.ldb2 * brg.ld_block2; } if (brg.ldb2_tail > 0) { const bool is_ld_reg_tail = (brg.ldb2 == 0) ? false : true; const bool is_ld_tail = false; ldb_loop(bd_block2, brg.ldb2_tail, 1, is_ld_reg_tail, is_ld_tail, c_offset, d_offset, ldb_ind, apply_post_ops); c_offset += ldb_C_offset(brg.ldb2_tail); d_offset += ldb_D_offset(brg.ldb2_tail); ldb_ind += brg.ldb2_tail; } if (brg.ldb_tail > 0) { const bool is_ld_reg_tail = (brg.ldb2 == 0 && brg.ldb2_tail == 0) ? false : true; const bool is_ld_tail = true; ldb_loop(bd_block2, 1, 1, is_ld_reg_tail, is_ld_tail, c_offset, d_offset, ldb_ind, apply_post_ops); c_offset += ldb_C_offset(1, true); d_offset += ldb_D_offset(1, true); ldb_ind += 1; } // rewind inp_bd for (int bdb = 0; bdb < bd_block2; bdb++) { inp_bd_ = skipped_bd_mask(inp_bd_); inp_bd_ += brg.bd_block; } inp_bd_ = skipped_bd_mask(inp_bd_); }; inp_bd_ = skipped_bd_mask(0); for (int bdb2 = 0; bdb2 < brg.bdb2 && brg.bd_block2 > 1; bdb2++) { do_ldb_loop(brg.bd_block2, apply_post_ops); } if (brg.bdb2_tail > 0) { do_ldb_loop(brg.bdb2_tail, apply_post_ops); } if (!brg.is_M_tail && brg.bdb_tail > 0) do_ldb_loop(1, apply_post_ops); interleave_store(true); } void jit_brgemm_amx_uker_base_t::generate() { preamble(); sub(rsp, stack_space_needed_); const auto full_mask = size_t {0xffffffffffffffff}; const auto tail_mask = size_t((1 << brg.ldb_tail) - 1); LDA_size_ = brg.typesize_A * brg.LDA; LDB_size_ = brg.typesize_B * brg.LDB; LDC_size_ = brg.typesize_C * brg.LDC; LDD_size_ = brg.typesize_D * brg.LDD; LDA2_size_ = brg.typesize_A * brg.LDA2; LDB2_size_ = brg.typesize_B * brg.LDB2; LDC2_size_M_ = brg.typesize_C * brg.LDC2_M; LDC2_size_N_ = brg.typesize_C * brg.LDC2_N; ld_block_B_size_ = brg.typesize_B * ((brg.brgattr.LDB2 != 0) ? brg.brgattr.LDB2 : brg.ld_block); ld_block_C_size_ = brg.typesize_C * brg.ld_block; ld_block_D_size_ = brg.typesize_D * brg.ld_block; ld_block_bias_size_ = brg.typesize_bias * brg.ld_block; ld_block_scales_size_ = sizeof(float) * brg.ld_block; ld_block_zp_size_ = sizeof(int32_t) * brg.ld_block; ldb_tail_B_size_ = brg.typesize_B * brg.ldb_tail; ldb_tail_C_size_ = brg.typesize_C * brg.ldb_tail; ldb_tail_D_size_ = brg.typesize_D * brg.ldb_tail; ldb_tail_zp_size_ = sizeof(int32_t) * brg.ldb_tail; // if beta == 1 and C datatype is f32 it is better to perform addition by // reading tiles directly from C instead of by reading/writing by vectors may_load_accumulators_ = (brg.beta == 1.f && brg.dt_c == data_type::f32 && !brg.is_bf32); need_to_apply_alpha_beta_ = (brg.beta != 0.f && !may_load_accumulators_) || brg.alpha != 1.f; const bool has_zero_points = !everyone_is(brgemm_broadcast_t::none, brg.zp_type_a, brg.zp_type_b, brg.zp_type_c); are_post_ops_applicable_ = one_of(true, brg.with_eltwise, brg.with_binary, brg.with_scales, brg.with_bias, brg.with_sum, brg.dt_d != brg.dt_c, has_zero_points); // second level blocking eligible only if we don't use store by vectors for now assert(IMPLICATION(are_post_ops_applicable_ || need_to_apply_alpha_beta_ || brg.brgattr.bd_mask_level, !brg.is_blocked && !brg.brgattr.var_bs)); //! 'maybe_pre_process_data' for 'is_bf32' uses 'bs' value, //! so we can't support var_bs for is_bf32 for this moment assert(IMPLICATION(brg.brgattr.var_bs, !brg.is_bf32)); Label permute_index_table; if (brg.is_bf32) { brgemm_init_tiles(brg, (char *)(&palette_)); mov(reg_tmp_gpr, permute_index_table); vmovups(zmm_bf32_pemute, ptr[reg_tmp_gpr]); } reg64_t reg_mask = rax; mov(reg_mask, full_mask); kmovq(ld_full_mask, reg_mask); mov(reg_mask, tail_mask); kmovq(ld_tail_mask, reg_mask); mov(reg_stride_lda, lda()); mov(reg_stride_ldb, ldb()); read_params(); prepare_bd_mask(); Label label_to_ret; if (are_post_ops_applicable_) { Label label_store_without_post_ops; mov(reg_do_post_ops, ptr[param1 + GET_OFF(do_post_ops)]); cmp(reg_do_post_ops, 0); jz(label_store_without_post_ops, T_NEAR); bdb_loop(true); jmp(label_to_ret, T_NEAR); transform_buf_map_A_.clear(); transform_buf_map_B_.clear(); L(label_store_without_post_ops); } bdb_loop(false); L(label_to_ret); add(rsp, stack_space_needed_); postamble(); if (brg.with_eltwise) postops_injector_->prepare_table(); if (brg.is_bf32) { align(64); L(permute_index_table); const uint16_t _idx[32] = {0, 16, 1, 17, 2, 18, 3, 19, 4, 20, 5, 21, 6, 22, 7, 23, 8, 24, 9, 25, 10, 26, 11, 27, 12, 28, 13, 29, 14, 30, 15, 31}; for (size_t i = 0; i < 32; ++i) dw(_idx[i]); } } brgemm_amx_uker_t::brgemm_amx_uker_t(const brgemm_t abrd) { brgemm_kernel_ = new jit_brgemm_amx_uker_base_t(abrd); } status_t brgemm_amx_uker_t::create_kernel() { return brgemm_kernel_->create_kernel(); } void brgemm_amx_uker_t::operator()(brgemm_kernel_params_t *params) const { (*brgemm_kernel_)(params); } brgemm_amx_uker_t::~brgemm_amx_uker_t() { delete brgemm_kernel_; } } // namespace x64 } // namespace cpu } // namespace impl } // namespace dnnl // vim: et ts=4 sw=4 cindent cino+=l0,\:4,N-s
38.023851
83
0.6295
[ "vector", "transform" ]
3b6b5f0141a0fe613fe1f9106282d75a1d149d3b
4,128
cpp
C++
td/telegram/files/FileBitmask.cpp
lccxz/td
6cdda6a2f3be4d0379f00a07fcd49f330da731fb
[ "BSL-1.0" ]
4,829
2017-12-31T21:15:19.000Z
2022-03-31T14:58:07.000Z
td/telegram/files/FileBitmask.cpp
lccxz/td
6cdda6a2f3be4d0379f00a07fcd49f330da731fb
[ "BSL-1.0" ]
1,872
2018-01-01T18:35:37.000Z
2022-03-31T15:46:00.000Z
td/telegram/files/FileBitmask.cpp
lccxz/td
6cdda6a2f3be4d0379f00a07fcd49f330da731fb
[ "BSL-1.0" ]
1,117
2018-01-01T15:02:49.000Z
2022-03-30T12:40:11.000Z
// // Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2021 // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "td/telegram/files/FileBitmask.h" #include "td/utils/common.h" #include "td/utils/misc.h" #include "td/utils/ScopeGuard.h" namespace td { Bitmask::Bitmask(Decode, Slice data) : data_(zero_one_decode(data)) { } Bitmask::Bitmask(Ones, int64 count) : data_(narrow_cast<size_t>((count + 7) / 8), '\0') { for (int64 i = 0; i < count; i++) { set(i); } } Bitmask Bitmask::compress(int k) const { Bitmask res; for (int64 i = 0; i * k < size(); i++) { bool f = true; for (int64 j = 0; j < k && f; j++) { f &= get(i * k + j); } if (f) { res.set(i); } } return res; } std::string Bitmask::encode(int32 prefix_count) { // remove zeroes in the end to make encoding deterministic Slice data(data_); int save_i = -1; char save_c; if (prefix_count != -1) { auto truncated_size = (prefix_count + 7) / 8; data.truncate(truncated_size); if (prefix_count % 8 != 0) { save_i = truncated_size - 1; save_c = data_[save_i]; auto mask = 0xff >> (8 - prefix_count % 8); data_[save_i] = static_cast<char>(data_[save_i] & mask); } } SCOPE_EXIT { if (save_i != -1) { data_[save_i] = save_c; } }; while (!data.empty() && data.back() == '\0') { data.remove_suffix(1); } return zero_one_encode(data); } int64 Bitmask::get_ready_prefix_size(int64 offset, int64 part_size, int64 file_size) const { if (offset < 0) { return 0; } if (part_size == 0) { return 0; } CHECK(part_size > 0); auto offset_part = offset / part_size; auto ones = get_ready_parts(offset_part); if (ones == 0) { return 0; } auto ready_parts_end = (offset_part + ones) * part_size; if (file_size != 0 && ready_parts_end > file_size) { ready_parts_end = file_size; if (offset > file_size) { offset = file_size; } } auto res = ready_parts_end - offset; CHECK(res >= 0); return res; } int64 Bitmask::get_total_size(int64 part_size, int64 file_size) const { int64 res = 0; for (int64 i = 0; i < size(); i++) { if (get(i)) { auto from = i * part_size; auto to = from + part_size; if (file_size != 0 && file_size < to) { to = file_size; } if (from < to) { res += to - from; } } } return res; } bool Bitmask::get(int64 offset_part) const { if (offset_part < 0) { return false; } auto index = narrow_cast<size_t>(offset_part / 8); if (index >= data_.size()) { return false; } return (static_cast<uint8>(data_[index]) & (1 << static_cast<int>(offset_part % 8))) != 0; } int64 Bitmask::get_ready_parts(int64 offset_part) const { int64 res = 0; while (get(offset_part + res)) { res++; } return res; } std::vector<int32> Bitmask::as_vector() const { std::vector<int32> res; auto size = narrow_cast<int32>(data_.size() * 8); for (int32 i = 0; i < size; i++) { if (get(i)) { res.push_back(i); } } return res; } void Bitmask::set(int64 offset_part) { CHECK(offset_part >= 0); auto need_size = narrow_cast<size_t>(offset_part / 8 + 1); if (need_size > data_.size()) { data_.resize(need_size, '\0'); } data_[need_size - 1] = static_cast<char>(data_[need_size - 1] | (1 << (offset_part % 8))); } int64 Bitmask::size() const { return static_cast<int64>(data_.size()) * 8; } StringBuilder &operator<<(StringBuilder &sb, const Bitmask &mask) { bool prev = false; int32 cnt = 0; for (int64 i = 0; i <= mask.size(); i++) { bool cur = mask.get(i); if (cur != prev) { // zeros at the end are intentionally skipped if (cnt < 5) { while (cnt > 0) { sb << (prev ? '1' : '0'); cnt--; } } else { sb << (prev ? '1' : '0') << "(x" << cnt << ')'; cnt = 0; } } prev = cur; cnt++; } return sb; } } // namespace td
23.861272
96
0.583576
[ "vector" ]
3b6f8b7187f7d126017b5503828bb5650b8a4b20
638
cpp
C++
16.07/vrct1.cpp
dengxianglong/cplusplusprimerplusstudy
eefc5d7bf5ab31186c04171fadade3552838f4b2
[ "MIT" ]
null
null
null
16.07/vrct1.cpp
dengxianglong/cplusplusprimerplusstudy
eefc5d7bf5ab31186c04171fadade3552838f4b2
[ "MIT" ]
null
null
null
16.07/vrct1.cpp
dengxianglong/cplusplusprimerplusstudy
eefc5d7bf5ab31186c04171fadade3552838f4b2
[ "MIT" ]
1
2018-08-29T07:40:20.000Z
2018-08-29T07:40:20.000Z
#include <iostream> #include <string> #include <vector> const int NUM = 5; int main() { using namespace std; vector<int>ratings(NUM); vector<string>titles(NUM); cout << "You will do exactly as told. You will enter\n" <<NUM << " Book titles and your ratings (0 -10)>\n"; int i; for ( i = 0; i < NUM; i++) { cout << "ENter title #" << i + 1 << ": "; getline(cin,titles[i]); cout << "enter your rating (0 - 10) : "; cin >> ratings[i]; cin.get(); } cout << "Thank you. You entered the following:\n" << "Rating\tBook\n"; for ( i = 0; i < NUM; i++) { cout << ratings[i] << "\t" << titles[i] << endl; } return 0; }
21.266667
56
0.565831
[ "vector" ]
3b729e4acf3ec4891475e6215256532d740b20d1
1,540
hh
C++
raster_datasource.hh
baiyicanggou/mapnik_mvt
9bde52fa9958d81361c015c816858534ec0931bb
[ "Apache-2.0" ]
null
null
null
raster_datasource.hh
baiyicanggou/mapnik_mvt
9bde52fa9958d81361c015c816858534ec0931bb
[ "Apache-2.0" ]
null
null
null
raster_datasource.hh
baiyicanggou/mapnik_mvt
9bde52fa9958d81361c015c816858534ec0931bb
[ "Apache-2.0" ]
null
null
null
#pragma once #include <mapnik/coord.hpp> #include <mapnik/datasource.hpp> #include <mapnik/feature.hpp> #include <mapnik/feature_layer_desc.hpp> #include <mapnik/params.hpp> #include <mapnik/query.hpp> #include <boost/optional.hpp> #include <memory> #include <string> #include <unordered_map> #include <vector> #include "virtual_datasource.hh" namespace flywave { namespace nik { class raster_data; typedef std::shared_ptr<raster_data> raster_data_ptr; typedef std::vector<raster_data_ptr> raster_tiled_data; class raster_datasource : public virtual_datasource { public: raster_datasource(raster_data_ptr ds, unsigned tile_size); raster_datasource(raster_tiled_data datas, mapnik::box2d<double> extent, unsigned row, unsigned col, unsigned tile_size); virtual ~raster_datasource(); datasource::datasource_t type() const; mapnik::featureset_ptr features(const mapnik::query &q) const; mapnik::featureset_ptr features_at_point(mapnik::coord2d const &pt, double tol = 0) const; mapnik::box2d<double> envelope() const; boost::optional<mapnik::datasource_geometry_t> get_geometry_type() const; mapnik::layer_descriptor get_descriptor() const; private: mapnik::layer_descriptor desc_; raster_data_ptr data_; raster_tiled_data datas_; mapnik::box2d<double> extent_; bool extent_initialized_; bool multi_tiles_; unsigned tile_size_; unsigned width_; unsigned height_; unsigned tile_stride_; }; } // namespace nik } // namespace flywave
27.017544
75
0.748701
[ "vector" ]
3b74851dbd4f384ea0dae61e2fdeb22c607f3b5e
60,877
cpp
C++
src/main/cpp/Config/Config.cpp
JamesTerm/FRC2019
2794d3cc4f2b4702c59e402904db2f4cdc2ab68d
[ "BSD-3-Clause" ]
1
2021-11-12T04:34:31.000Z
2021-11-12T04:34:31.000Z
src/main/cpp/Config/Config.cpp
JamesTerm/FRC2019
2794d3cc4f2b4702c59e402904db2f4cdc2ab68d
[ "BSD-3-Clause" ]
null
null
null
src/main/cpp/Config/Config.cpp
JamesTerm/FRC2019
2794d3cc4f2b4702c59e402904db2f4cdc2ab68d
[ "BSD-3-Clause" ]
null
null
null
/****************************** Header ******************************\ Class Name: Config File Name: Config.h Summary: Manages and loads the configuration file. Project: BroncBotzFRC2019 Copyright (c) BroncBotz. All rights reserved. Author(s): Ryan Cooper, Dylan Watson, Chris Weeks Email: cooper.ryan@centaurisoftware.co, dylantrwatson@gmail.com, chrisrweeks@aol.com \********************************************************************/ #include "Config.h" #include <string.h> #include <stdio.h> using namespace std; using namespace System; using namespace Configuration; using namespace pugi; using namespace frc; /** * Load in the document * Config Version and Comment (different from the Robot.cpp Version and Comment) * * Verbose Output: Need to give Ian the logging TODO first * ? AutonEnabled * Secondary Camera Server * * Vision Initialization -> need vision working with that * Allocate Components *TODO: Encoders-> Add encoders to motors * DI *TODO: *DO-> Write the abstraction classes *TODO:*AI-> Write the abstraction classes *TODO:*AO-> Write the abstraction classes *TODO: Lower and Upper Limit for DAI * Motors *? Drive class integration? Probably Post-Season * Solenoids *? Relays * Potentiometers * *Allocate the Joysticks via the XML * *Allocate Controls (make another method for this, prolly one for each joystick) * **/ Config::Config(ActiveCollection *_activeCollection, Drive *_drive) { //? make doc a member variable? _activeCollection->DeleteAll(); _drive->DeleteAll(); xml_document doc; xml_parse_result result = doc.load_file("config.xml"); m_activeCollection = _activeCollection; m_drive = _drive; if (result) { Log::General("XML Config parsed without errors"); LoadValues(doc); } else { try { Log::General("xml not found...loading backup config"); backupConfig *_Backup = new backupConfig(_activeCollection, _drive); } catch(...) { Log::Error("XML Config and backup config parsed with errors"); string desc = result.description(); Log::Error("Error description: " + desc); Log::Error("Error offset: " + result.offset); Log::Error("No config available, returning to Robot.cpp\nTHIS IS A BIG ERROR!"); //In simulation we should really get the message across #ifdef _Win32 assert(false); #endif } } } void Config::LoadValues(xml_document &doc){ xml_node root = doc.child("Robot"); if(root){ Log::General("Config Root found"); } else{ Log::General("Robot was not found in Config! I hope you didn't intend to configure anything! Returning to Robot.cpp"); return; } #pragma region MetaData #pragma region Comp bool comp = root.child("Competition").attribute("AtComp").as_bool(); if(comp) { Log::atComp = comp; } else { Log::atComp = false; } #pragma endregion Comp #pragma region Version xml_attribute version = root.child("Version").attribute("version"); if(version) Log::General("Config Version: " + version.as_int(), true); else Log::Error("Config Version not found"); #pragma endregion Version #pragma region Comment xml_attribute comment = root.child("Comment").attribute("comment"); if(comment){ string comm = comment.as_string(); Log::General("Comment: " + comm, true); } else Log::Error("Comment not found"); #pragma endregion Comment #pragma region TimeLoop xml_attribute Loop = root.child("Time").attribute("seconds"); if(Loop){ double timeL = Loop.as_double(); m_activeCollection->SetLoopTime(timeL); Log::General("Loop Time set: " + to_string(timeL), true); } else Log::Error("Comment not found"); #pragma endregion TimeLoop #pragma region NavX xml_attribute useNavX = root.child("UseNavX").attribute("value"); //TODO: Addition of other NavX ports if(useNavX){ if(useNavX.as_bool()){ m_activeCollection->Add(new NavX()); Log::General("NavX detected"); } else Log::General("Failed to load the NavX: Disabling NavX by default"); } else Log::Error("UseNavX not found. Disabling by default"); #pragma endregion NavX #pragma region PDB if (root.child("PDBManager")) { xml_attribute MaxCur = root.child("PDBManager").attribute("MaxCurrrent"); xml_attribute TimeOut = root.child("PDBManager").attribute("TimeOut"); xml_attribute Lower = root.child("PDBManager").attribute("LowerAmountBy"); xml_attribute Run = root.child("PDBManager").attribute("Update"); if (MaxCur && TimeOut) { m_activeCollection->SetPDP(TimeOut.as_double(), MaxCur.as_double(), Lower.as_double(), Run.as_bool()); } } #pragma endregion PDB #pragma region AutoSelection xml_node AtoE = root.child("Selected_Auto"); if(AtoE) { xml_attribute Ato = AtoE.attribute("OverrideDS"); if(Ato) { string AtoFile = Ato.as_string(); Log::General("Selected Auto: " + AtoFile); m_activeCollection->SetAuto(AtoFile); } xml_attribute AtoOverride = AtoE.attribute("OverrideDS"); if(AtoOverride) { bool AtoOver = AtoOverride.as_bool(); m_activeCollection->SetAutoOverride(AtoOver); } xml_attribute AtoScale = AtoE.attribute("Scale"); if(AtoScale) { double Scale = AtoOverride.as_double(); m_activeCollection->SetAutoScale(Scale); } xml_attribute Drive = AtoE.attribute("Swerve"); if(Drive) { bool TypeDrive = Drive.as_bool(); m_activeCollection->SetIsSwerveDrive(TypeDrive); } } else { Log::Error("Auto not found"); } #pragma endregion AutoSelection #pragma region ColorSen xml_node CS = root.child("ColorSensor"); if(CS){ REVColorSensorV3 *tmp; if(CS.attribute("name")) tmp = new REVColorSensorV3(CS.attribute("name").as_string()); else tmp = new REVColorSensorV3("Color"); m_activeCollection->Add(tmp); Log::General("Added Color Sensor"); } else{ Log::Error("Color Sensor definitions not found in config, skipping..."); } #pragma endregion ColorSen #pragma region SecondaryCameraServer //TODO: make it so we can mess with the camera during the running of the robot: ie, switch which stream we are using xml_node enableSecondaryCamera = root.child("RobotCameraServer"); if(enableSecondaryCamera) { //TODO: chris dum //CameraServer::GetInstance()->StartAutomaticCapture(0); if(enableSecondaryCamera.attribute("enabled").as_bool()) { for(xml_node camera = enableSecondaryCamera.first_child(); camera; camera = camera.next_sibling()) { Log::General("first for loop"); if(camera) { xml_attribute enabled = camera.attribute("enabled"); if(enabled.as_bool()) { xml_attribute port = camera.attribute("port"); xml_attribute fps = camera.attribute("fps"); xml_attribute width = camera.attribute("width"); xml_attribute height = camera.attribute("height"); int iport, ifps, iwidth, iheight; if(port) { iport = port.as_int(); } else { Log::Error("CAMERA IS MISSING PORT! DISABLED!"); continue; } if(fps) { ifps = fps.as_int(); } else { Log::Error("Camera FPS Missing! Using default value!"); ifps = 15; } if(width && height) { iwidth = width.as_int(); iheight = height.as_int(); } else { Log::Error("Camera Width or Height Missing! Using default values!"); iwidth = 160; iheight = 120; } Log::General("iport" + iport,true); cs::UsbCamera cam = CameraServer::GetInstance()->StartAutomaticCapture(iport); cam.SetFPS(ifps); cam.SetResolution(iwidth,iheight); //cam; } else { Log::General("Camera Disabled"); } } } } } #pragma endregion SecondaryCameraServer #pragma region Vision shared_ptr<NetworkTable> vision_table = nt::NetworkTableInstance::GetDefault().GetTable("VISION_2019"); xml_node vision = root.child("Vision"); if(vision) { //LS if(vision.attribute("LS")) { vision_table->PutNumber("LS",vision.attribute("LS").as_int()); } else { Log::Error("Vision LS not found! Vision server does not have proper values to work with and will likely fail!"); } //US if(vision.attribute("US")) { vision_table->PutNumber("US",vision.attribute("US").as_int()); } else { Log::Error("Vision US not found! Vision server does not have proper values to work with and will likely fail!"); } //LH if(vision.attribute("LH")) { vision_table->PutNumber("LH",vision.attribute("LH").as_int()); } else { Log::Error("Vision LH not found! Vision server does not have proper values to work with and will likely fail!"); } //UH if(vision.attribute("UH")) { vision_table->PutNumber("UH",vision.attribute("UH").as_int()); } else { Log::Error("Vision UH not found! Vision server does not have proper values to work with and will likely fail!"); } //LV if(vision.attribute("LV")) { vision_table->PutNumber("LV",vision.attribute("LV").as_int()); } else { Log::Error("Vision LV not found! Vision server does not have proper values to work with and will likely fail!"); } //UV if(vision.attribute("UV")) { vision_table->PutNumber("UV",vision.attribute("UV").as_int()); } else { Log::Error("Vision UV not found! Vision server does not have proper values to work with and will likely fail!"); } //MinA if(vision.attribute("MinA")) { vision_table->PutNumber("MinA",vision.attribute("MinA").as_int()); } else { Log::Error("Vision MinA not found! Vision server does not have proper values to work with and will likely fail!"); } //MaxA if(vision.attribute("MaxA")) { vision_table->PutNumber("MaxA",vision.attribute("MaxA").as_int()); } else { Log::Error("Vision MaxA not found! Vision server does not have proper values to work with and will likely fail!"); } //MaxO if(vision.attribute("MaxO")) { vision_table->PutNumber("MaxO",vision.attribute("MaxO").as_int()); } else { Log::Error("Vision MaxO not found! Vision server does not have proper values to work with and will likely fail!"); } //Lower bound if(vision.attribute("LOWER_BOUND")) { vision_table->PutNumber("LOWER_BOUND",vision.attribute("LOWER_BOUND").as_int()); } else { Log::Error("Vision Lower bound not found! Vision server does not have proper values to work with and will likely fail!"); } //upper bound if(vision.attribute("UPPER_BOUND")) { vision_table->PutNumber("UPPER_BOUND",vision.attribute("UPPER_BOUND").as_int()); } else { Log::Error("Vision Upper bound not found! Vision server does not have proper values to work with and will likely fail!"); } //left bound if(vision.attribute("LEFT_BOUND")) { vision_table->PutNumber("LEFT_BOUND",vision.attribute("LEFT_BOUND").as_int()); } else { Log::Error("Vision left bound not found! Vision server does not have proper values to work with and will likely fail!"); } //right bound if(vision.attribute("RIGHT_BOUND")) { vision_table->PutNumber("RIGHT_BOUND",vision.attribute("RIGHT_BOUND").as_int()); } else { Log::Error("Vision right bound not found! Vision server does not have proper values to work with and will likely fail!"); } } else { Log::Error("Vision not found. Vision server does not have proper values to work with and will likely fail!"); } #pragma endregion Vision #pragma endregion MetaData AllocateComponents(root); xml_node controls = root.child("Controls"); if(controls){ Log::General("Controls tag found"); } else{ Log::Error("Control definitions were not found in Config! Returning to Robot.cpp"); return; } #pragma region LimeLight xml_node LM = root.child("limeLight"); if(LM) { limelight* lime = new limelight(); m_activeCollection->Add(lime); Log::General("Added Limelight"); } else { Log::Error("No limelight in RobotConfig...we need that"); } #pragma endregion LimeLight AllocateDriverControls(controls); AllocateOperatorControls(controls); } void Config::AllocateComponents(xml_node &root){ xml_node robot = root.child("RobotConfig"); if(!robot){ Log::General("RobotConfig was not found in Config! I hope you didn't intend to allocate any components! Returning to Config::LoadValues()"); return; } //TODO: When/if we create a drivetrain class, we will need drive/aux motors //TODO: Look into setting encoders to motors like we used to do in the C# code //TODO: Upper and lower limits that can be either AI or DI #pragma region VictorSP xml_node VictorSP = robot.child("VictorSP"); if(VictorSP){ for(xml_node victorSp = VictorSP.first_child(); victorSp; victorSp = victorSp.next_sibling()){ string name = victorSp.name(); xml_attribute channel = victorSp.attribute("channel"); bool reversed = victorSp.attribute("reversed").as_bool(); int pdbChannel = victorSp.attribute("pdbChannel") ? victorSp.attribute("pdbChannel").as_int() : -1; if(channel){ VictorSPItem *tmp = new VictorSPItem(name, channel.as_int(), reversed); m_activeCollection->Add(tmp); string channel_print = channel.as_string(); string reversed_print = reversed ? "true" : "false" ; Log::General("Added VictorSP " + name + ", Channel: " + channel_print + ", Reversed: " + reversed_print); if(pdbChannel != -1){ string pdbChannel_print = to_string(pdbChannel); Log::General("Allocated PDBChannel " + pdbChannel_print + " for VictorSP " + name); tmp->SetPDBChannel(pdbChannel); } int MotorGroup = victorSp.attribute("Group") ? victorSp.attribute("Group").as_int() : -1; if (MotorGroup != -1) { m_activeCollection->GetPDBManager()->SetMotorGroup(tmp, MotorGroup); } double PersonalLowerRate = victorSp.attribute("LowerRate") ? victorSp.attribute("LowerRate").as_double() : -1; if (PersonalLowerRate != -1) { tmp->SetLowerRate(PersonalLowerRate); } double PersonalRegenRate = victorSp.attribute("RegenRate") ? victorSp.attribute("RegenRate").as_double() : -1; if (PersonalRegenRate != -1) { tmp->SetRegenRate(PersonalRegenRate); } } else{ Log::Error("Failed to load VictorSP " + name + ". This may cause a fatal runtime error!"); } } } else{ Log::Error("VictorSP definitions not found in config, skipping..."); } #pragma endregion VictorSP #pragma region VictorSPX xml_node VictorSPX = robot.child("VictorSPX"); if(VictorSPX){ for(xml_node victorSpx = VictorSPX.first_child(); victorSpx; victorSpx = victorSpx.next_sibling()){ string name = victorSpx.name(); xml_attribute channel = victorSpx.attribute("channel"); //TODO: Fix this line after comp and fix robot configs bool reversed = victorSpx.attribute("reversed");//.as_bool(); int pdbChannel = victorSpx.attribute("pdbChannel") ? victorSpx.attribute("pdbChannel").as_int() : -1; if(channel){ VictorSPXItem *tmp = new VictorSPXItem(channel.as_int(), name, reversed); m_activeCollection->Add(tmp); string reversed_print = reversed ? "true" : "false"; Log::General("Added VictorSPX " + name + ", Channel: " + to_string(channel.as_int()) + ", Reversed: " + reversed_print); if(pdbChannel != -1){ Log::General("Allocated PDBChannel " + to_string(pdbChannel) + " for VictorSPX " + name); tmp->SetPDBChannel(pdbChannel); } int MotorGroup = victorSpx.attribute("Group") ? victorSpx.attribute("Group").as_int() : -1; if (MotorGroup != -1) { m_activeCollection->GetPDBManager()->SetMotorGroup(tmp, MotorGroup); } double PersonalLowerRate = victorSpx.attribute("LowerRate") ? victorSpx.attribute("LowerRate").as_double() : -1; if (PersonalLowerRate != -1) { tmp->SetLowerRate(PersonalLowerRate); } double PersonalRegenRate = victorSpx.attribute("RegenRate") ? victorSpx.attribute("RegenRate").as_double() : -1; if (PersonalRegenRate != -1) { tmp->SetRegenRate(PersonalRegenRate); } } else{ Log::Error("Failed to load VictorSPX " + name + ". This may cause a fatal runtime error!"); } } } else{ Log::Error("VictorSPX definitions not found in config, skipping..."); } #pragma endregion SparkMax #pragma region SparkMax xml_node SparkMax = robot.child("SparkMax"); if(SparkMax){ for(xml_node sparkMax = SparkMax.first_child(); sparkMax; sparkMax = sparkMax.next_sibling()){ string name = sparkMax.name(); xml_attribute channel = sparkMax.attribute("channel"); //TODO: Fix this line after comp and fix robot configs bool reversed = sparkMax.attribute("reversed").as_bool(); int pdbChannel = sparkMax.attribute("pdbChannel") ? sparkMax.attribute("pdbChannel").as_int() : -1; if(channel){ SparkMaxItem *tmp = new SparkMaxItem(channel.as_int(), name, reversed, true); m_activeCollection->Add(tmp); string reversed_print = reversed ? "true" : "false"; Log::General("Added SparkMax " + name + ", Channel: " + to_string(channel.as_int()) + ", Reversed: " + reversed_print); if(pdbChannel != -1){ Log::General("Allocated PDBChannel " + to_string(pdbChannel) + " for SparkMax " + name); tmp->SetPDBChannel(pdbChannel); } int MotorGroup = sparkMax.attribute("Group") ? sparkMax.attribute("Group").as_int() : -1; if (MotorGroup != -1) { m_activeCollection->GetPDBManager()->SetMotorGroup(tmp, MotorGroup); } double PersonalLowerRate = sparkMax.attribute("LowerRate") ? sparkMax.attribute("LowerRate").as_double() : -1; if (PersonalLowerRate != -1) { tmp->SetLowerRate(PersonalLowerRate); } double PersonalRegenRate = sparkMax.attribute("RegenRate") ? sparkMax.attribute("RegenRate").as_double() : -1; if (PersonalRegenRate != -1) { tmp->SetRegenRate(PersonalRegenRate); } } else{ Log::Error("Failed to load SparkMax " + name + ". This may cause a fatal runtime error!"); } } } else{ Log::Error("SparkMax definitions not found in config, skipping..."); } #pragma endregion SparkMax #pragma region TalonSRX xml_node TalonSRX = robot.child("TalonSRX"); if(TalonSRX){ for(xml_node talonSrx = TalonSRX.first_child(); talonSrx; talonSrx = talonSrx.next_sibling()){ string name = talonSrx.name(); xml_attribute channel = talonSrx.attribute("channel"); bool reversed = talonSrx.attribute("reversed").as_bool(); bool enableEncoder = talonSrx.attribute("enableEncoder").as_bool(); int pdbChannel = talonSrx.attribute("pdbChannel") ? talonSrx.attribute("pdbChannel").as_int() : -1; if(channel){ TalonSRXItem *tmp = new TalonSRXItem(channel.as_int(), name, reversed, enableEncoder, true); m_activeCollection->Add(tmp); string reversed_print = reversed ? "true" : "false" ; string enableEncoder_print = enableEncoder ? "true" : "false" ; Log::General("Added TalonSRX " + name + ", Channel: " + to_string(channel.as_int()) + ", Reversed: " + reversed_print + ", EnableEncoder: " + enableEncoder_print); if(pdbChannel != -1){ Log::General("Allocated PDBChannel " + to_string(pdbChannel) + " for TalonSRX " + name); tmp->SetPDBChannel(pdbChannel); } int MotorGroup = talonSrx.attribute("Group") ? talonSrx.attribute("Group").as_int() : -1; if (MotorGroup != -1) { m_activeCollection->GetPDBManager()->SetMotorGroup(tmp, MotorGroup); } double PersonalLowerRate = talonSrx.attribute("LowerRate") ? talonSrx.attribute("LowerRate").as_double() : -1; if (PersonalLowerRate != -1) { tmp->SetLowerRate(PersonalLowerRate); } double PersonalRegenRate = talonSrx.attribute("RegenRate") ? talonSrx.attribute("RegenRate").as_double() : -1; if (PersonalRegenRate != -1) { tmp->SetRegenRate(PersonalRegenRate); } } else{ Log::Error("Failed to load TalonSRX " + name + ". This may cause a fatal runtime error!"); } } } else{ Log::Error("TalonSRX definitions not found in config, skipping..."); } #pragma endregion TalonSRX #pragma region Potentiometer xml_node Pot = robot.child("Potentiometer"); if(Pot){ for(xml_node pot = Pot.first_child(); pot; pot = pot.next_sibling()){ string name = pot.name(); xml_attribute channel = pot.attribute("channel"); if(channel){ PotentiometerItem *tmp = new PotentiometerItem(channel.as_int(), name, true); m_activeCollection->Add(tmp); Log::General("Added Potentiometer " + name + ", Channel: " + to_string(channel.as_int())); } else{ Log::Error("Failed to load Potentiometer " + name + ". This may cause a fatal runtime error!"); } } } else{ Log::Error("Potentiometer definitions not found in config, skipping..."); } #pragma endregion Potentiometer #pragma region Encoder xml_node Encoder = robot.child("Encoder"); if(Encoder){ for(xml_node encoder = Encoder.first_child(); encoder; encoder = encoder.next_sibling()){ string name = encoder.name(); xml_attribute aChannel = encoder.attribute("aChannel"); xml_attribute bChannel = encoder.attribute("bChannel"); bool reversed = encoder.attribute("reversed").as_bool(); if(aChannel && bChannel){ EncoderItem *tmp = new EncoderItem(name, aChannel.as_int(), bChannel.as_int(), reversed, true); m_activeCollection->Add(tmp); string reversed_print = reversed ? "true" : "false" ; Log::General("Added Encoder " + name + ", A-Channel: " + to_string(aChannel.as_int()) + ", B-Channel: " + to_string(bChannel.as_int()) + ", Reversed: " + reversed_print); } else{ Log::General("Failed to load Encoder " + name + ". This may cause a fatal runtime error!"); } } } else{ Log::Error("Encoder definitions not found in config, skipping..."); } #pragma endregion Encoder #pragma region Servo xml_node Servo = robot.child("Servo"); if(Servo){ for(xml_node servo = Servo.first_child(); servo; servo = servo.next_sibling()){ string name = servo.name(); xml_attribute port = servo.attribute("port"); xml_attribute angle = servo.attribute("Max"); string typeS = servo.attribute("Type").as_string(); if(port && angle){ ServoItem *tmp = new ServoItem(name, port.as_int(), angle.as_double(), typeS.compare("Limited") == 0 ? ServoItem::ServoType::Limited : ServoItem::ServoType::Continuous, true); m_activeCollection->Add(tmp); string _print = typeS.compare("Limited") == 0 ? "Limited" : "Continuous" ; Log::General("Added Encoder " + name + ", Port: " + to_string(port.as_int()) + ", Max Angle: " + to_string(angle.as_double()) + ", Type: " + _print); } else{ Log::General("Failed to load Servo " + name + ". This may cause a fatal runtime error!"); } } } else{ Log::Error("Servo definitions not found in config, skipping..."); } #pragma endregion Servo #pragma region DoubleSolenoid xml_node Solenoid = robot.child("DoubleSolenoid"); if(Solenoid){ for(xml_node solenoid = Solenoid.first_child(); solenoid; solenoid = solenoid.next_sibling()){ string name = solenoid.name(); xml_attribute fChannel = solenoid.attribute("fChannel"); xml_attribute rChannel = solenoid.attribute("rChannel"); bool reversed = solenoid.attribute("reversed").as_bool(); xml_attribute _default = solenoid.attribute("default"); DoubleSolenoid::Value _def; if(_default){ if(strcmp(_default.as_string(),"reverse") == 0) _def = DoubleSolenoid::Value::kReverse; else if(strcmp(_default.as_string(),"forward") == 0) _def = DoubleSolenoid::Value::kForward; else{ _def = DoubleSolenoid::Value::kOff; } }else{ _def = DoubleSolenoid::Value::kOff; } string reversed_print = reversed ? "true" : "false"; if(fChannel && rChannel){ DoubleSolenoidItem *tmp = new DoubleSolenoidItem(name , fChannel.as_int(), rChannel.as_int(), _def, reversed, true); m_activeCollection->Add(tmp); Log::General("Added DoubleSolenoid " + name + ", F-Channel: " + to_string(fChannel.as_int()) + ", R-Channel: " + to_string(rChannel.as_int()) + ", Default: " + to_string(_def) + ", Reversed: " + reversed_print); } else{ Log::Error("Failed to load DoubleSolenoid " + name + ". This may cause a fatal runtime error!"); } } } else{ Log::Error("DoubleSolenoid definitions not found in config, skipping..."); } #pragma endregion DoubleSolenoid #pragma region DigitalInput xml_node DI = robot.child("DigitalInput"); if(DI){ for(xml_node di = DI.first_child(); di; di = di.next_sibling()){ string name = di.name(); xml_attribute channel = di.attribute("channel"); if(channel){ DigitalInputItem *tmp = new DigitalInputItem(channel.as_int(), name, true); m_activeCollection->Add(tmp); Log::General("Added DigitalInput " + name + ", Channel: " + to_string(channel.as_int())); } else{ Log::Error("Failed to load DigitalInput " + name + ". This may cause a fatal runtime error!"); } } } else{ Log::Error("DigitalInput definitions not found in config, skipping..."); } #pragma endregion DigitalInput #pragma region SwerveModule xml_node Modules = robot.child("SwerveModules"); if (Modules) { for(xml_node module = Modules.first_child(); module; module = module.next_sibling()) { string name = module.name(); string SwivelName = module.attribute("swivel").as_string(); string WheelName = module.attribute("wheel").as_string(); if (m_activeCollection->Get(SwivelName) != nullptr && m_activeCollection->Get(WheelName) != nullptr) { double Ticksperrev = module.attribute("swivelTicks").as_double(); double WheelTicksperrev = module.attribute("wheelTicks").as_double(); xml_attribute Location = module.attribute("location"); if(Location) { SwerveModule *tmp = new SwerveModule(name, (Motor*)m_activeCollection->Get(SwivelName), (Motor*)m_activeCollection->Get(WheelName), Ticksperrev, WheelTicksperrev); tmp->SetLocation(Config::GetLocation(Location.as_string())); m_activeCollection->Add(tmp); Log::General("Added Swerve Module :" + name); } else { Log::Error("Swerve Module " + name + " cannot find location specified in the config!"); } } else { Log::Error("Swerve Module " + name + " cannot find one or both motors specified in the config!"); } } } #pragma endregion SwerveModule #pragma region SwerveManager if (Modules) { xml_node Man = robot.child("SwerveManager"); if (Man) { string name = Man.attribute("name").as_string(); bool WaitB = Man.attribute("wait").as_bool(); double MaxPower = Man.attribute("Max").as_double(); xml_attribute SwerveModules = Man.attribute("modules"); double length = Man.attribute("length").as_double(); double width = Man.attribute("width").as_double(); if (SwerveModules) { istringstream ss(SwerveModules.as_string()); string word; vector<SwerveModule*> Parts; bool AllHere = true; while (ss >> word) { if(m_activeCollection->Get(word) != nullptr) { Parts.push_back((SwerveModule*)m_activeCollection->Get(word)); } else { AllHere = false; } } if (AllHere) { SwerveManager *Manager = new SwerveManager(name, WaitB, Parts, m_activeCollection->GetNavX(), length, width, (Man.attribute("WheelDiameter") ? Man.attribute("WheelDiameter").as_double() : 1), (Man.attribute("Scale") ? Man.attribute("Scale").as_double() : 1)); Manager->SetMaxPow(MaxPower); m_activeCollection->Add(Manager); Log::General("Added Swerve Manager with location"); } else { Log::Error("One or modules not found!"); } } else { Log::Error("Swerve Manager cannot find one or more swerve modules specified in the code!"); } } } #pragma endregion SwerveManager #pragma region _PID xml_node Profiles = robot.child("Profiles"); if(Profiles){ for(xml_node P = Profiles.first_child(); P; P = P.next_sibling()){ string name = P.name(); xml_attribute Pval = P.attribute("P"); xml_attribute Ival = P.attribute("I"); xml_attribute Dval = P.attribute("D"); xml_attribute MaxChange = P.attribute("Change"); xml_attribute Bias = P.attribute("Bias"); xml_attribute Min = P.attribute("Min"); xml_attribute Max = P.attribute("Max"); xml_attribute IMin = P.attribute("InnerMin"); xml_attribute IMax = P.attribute("InnerMax"); xml_attribute Thres = P.attribute("Threshold"); xml_attribute Index = P.attribute("Index"); if(Pval && Ival && Dval) { if(MaxChange && Bias) { if(Min) { if(Max) { if(Index) { if(IMin && IMax && Thres) m_activeCollection->CreateAndAddProfile(name, Pval.as_double(), Ival.as_double(), Dval.as_double(), MaxChange.as_double(), Bias.as_double(), IMin.as_double(), IMax.as_double(), Min.as_double(), Max.as_double(), Thres.as_double(), Index.as_int()); else m_activeCollection->CreateAndAddProfile(name, Pval.as_double(), Ival.as_double(), Dval.as_double(), MaxChange.as_double(), Bias.as_double(), Min.as_double(), Max.as_double(), Index.as_int()); } else m_activeCollection->CreateAndAddProfile(name, Pval.as_double(), Ival.as_double(), Dval.as_double(), MaxChange.as_double(), Bias.as_double(), Min.as_double(), Max.as_double()); } else m_activeCollection->CreateAndAddProfile(name, Pval.as_double(), Ival.as_double(), Dval.as_double(), MaxChange.as_double(), Bias.as_double(), Min.as_double()); } else { m_activeCollection->CreateAndAddProfile(name, Pval.as_double(), Ival.as_double(), Dval.as_double(), MaxChange.as_double(), Bias.as_double()); } } else { m_activeCollection->CreateAndAddProfile(name, Pval.as_double(), Ival.as_double(), Dval.as_double()); } } else { Log::Error("Profile not complete"); } } } else{ Log::Error("PID Profiles definitions not found in config, skipping..."); } #pragma endregion _PID #pragma region Link_PID_Power xml_node PowerProfiles = robot.child("PowerLinks"); if(PowerProfiles){ for(xml_node P = PowerProfiles.first_child(); P; P = P.next_sibling()){ string name = P.name(); xml_attribute MotorName = P.attribute("Motor"); xml_attribute ProfileName = P.attribute("Profile"); xml_attribute ProfileIndex = P.attribute("ProfileIndex"); if(MotorName) { if(ProfileName) { string Name = MotorName.as_string(); Motor* MotorPtr = (Motor*)m_activeCollection->Get(Name); if(MotorPtr != nullptr) { MotorPtr->SetPowerProfile(m_activeCollection->GetProfile(ProfileName.as_string())); Log::General("Correctly Set Motor: " + Name + " to PID numbers from: " + Name); } else { Log::Error("Motor " + Name + " does not exist!"); } } else if(ProfileIndex) { string Name = MotorName.as_string(); Motor* MotorPtr = (Motor*)m_activeCollection->Get(Name); if(MotorPtr != nullptr) { MotorPtr->SetPowerProfile(m_activeCollection->GetProfile(ProfileIndex.as_int())); Log::General("Correctly Set Motor: " + Name + " to PID numbers from index: " + Name); } else { Log::Error("Motor " + Name + " does not exist!"); } } else { Log::Error("Link not complete!"); } } else { Log::Error("Link not complete!"); } } } else{ Log::Error("Power Link definitions not found in config, skipping..."); } #pragma endregion Link_PID_Power #pragma region Link_PID_Position xml_node PositionProfiles = robot.child("PositionLinks"); if(PositionProfiles){ for(xml_node P = PositionProfiles.first_child(); P; P = P.next_sibling()){ string name = P.name(); xml_attribute MotorName = P.attribute("Motor"); xml_attribute ProfileName = P.attribute("Profile"); xml_attribute ProfileIndex = P.attribute("ProfileIndex"); if(MotorName) { if(ProfileName) { string Name = MotorName.as_string(); Motor* MotorPtr = (Motor*)m_activeCollection->Get(Name); if(MotorPtr != nullptr) { MotorPtr->SetPositonProfile(m_activeCollection->GetProfile(ProfileName.as_string())); Log::General("Correctly Set Motor: " + Name + " to PID numbers from: " + Name); } else { Log::Error("Motor " + Name + " does not exist!"); } } else if(ProfileIndex) { string Name = MotorName.as_string(); Motor* MotorPtr = (Motor*)m_activeCollection->Get(Name); if(MotorPtr != nullptr) { MotorPtr->SetPositonProfile(m_activeCollection->GetProfile(ProfileIndex.as_int())); Log::General("Correctly Set Motor: " + Name + " to PID numbers from index: " + Name); } else { Log::Error("Motor " + Name + " does not exist!"); } } else { Log::Error("Link not complete!"); } } else { Log::Error("Link not complete!"); } } } else{ Log::Error("Position Link definitions not found in config, skipping..."); } #pragma endregion Link_PID_Position #pragma region Encoder_Links xml_node EncoderLinks = robot.child("EncoderLinks"); if(EncoderLinks){ for(xml_node P = EncoderLinks.first_child(); P; P = P.next_sibling()){ string name = P.name(); xml_attribute MotorName = P.attribute("Motor"); xml_attribute EncoderName = P.attribute("Encoder"); if(MotorName) { if(EncoderName) { string MotName = MotorName.as_string(); string EncName = EncoderName.as_string(); if (m_activeCollection->GetEncoder(EncName) != nullptr) { if(m_activeCollection->Get(MotName) != nullptr) { ((Motor*)m_activeCollection->Get(MotName))->SetLinkedEncoder(m_activeCollection->GetEncoder(EncName)); } else { Log::Error(MotName + " doesnt exist!"); } } else { Log::Error(EncName + " doesnt exist!"); } } else { Log::Error("Link not complete!"); } } else { Log::Error("Link not complete!"); } } } else{ Log::Error("Encoder Link definitions not found in config, skipping..."); } #pragma endregion Encoder_Links } void Config::AllocateDriverControls(xml_node &controls){ xml_node drive = controls.child("Driver"); if(!drive){ Log::Error("Drive Control definitions not found in config! Skipping..."); return; } int slot = drive.attribute("slot").as_int(); Log::General("Configured Driver Joystick at slot " + slot, true); m_driveJoy = new Joystick(slot); #pragma region AxisControl xml_node AxisControls = drive.child("AxisControls"); if(AxisControls){ for(xml_node axis = AxisControls.first_child(); axis; axis = axis.next_sibling()){ string name = axis.name(); xml_attribute channel = axis.attribute("axis"); if(channel){ bool reversed = axis.attribute("reversed").as_bool(); bool useOverdrive = axis.attribute("useOverdrive").as_bool(); double deadZone; double multiply; xml_attribute deadZone_xml = axis.attribute("deadZone"); xml_attribute multiply_xml = axis.attribute("powerMultiplier"); bool isLift = axis.attribute("isLift").as_bool(); if(!deadZone_xml){ Log::Error("No DeadZone detected for AxisControl " + name + ". Defaulting to 0.085. This may cause driving errors!"); deadZone = 0.085; } else deadZone = deadZone_xml.as_double(); if(!multiply_xml){ Log::Error("No Power Multiplier detected for AxisControl " + name + ". Defaulting to 1.0. This may cause driving errors!"); multiply = 1.0; } else multiply = multiply_xml.as_double(); AxisControl *tmp = new AxisControl(m_driveJoy, name, channel.as_int(), deadZone, reversed, multiply, m_activeCollection, useOverdrive); m_drive->AddControlDrive(tmp); string reversed_print = reversed ? "true" : "false" ; Log::General("Added AxisControl " + name + ", Axis: " + to_string(channel.as_int()) + ", DeadZone: " + to_string(deadZone) + ", Reversed: " + reversed_print + ", Power Multiplier: " + to_string(multiply) + "Is Lift: " + to_string(isLift)); xml_attribute bindings = axis.attribute("bindings"); if(bindings){ string bind_string = bindings.as_string(); vector<string> bind_vector = getBindingStringList(bind_string); setBindingsToControl(bind_vector, tmp); } else{ Log::Error("Control bindings not found for " + name + ". Did you intend to bind this control to anything?"); } if(isLift) tmp->SetLift(1.5, m_activeCollection); xml_attribute bind_event_xml = axis.attribute("bindEvent"); bool bind_event = bind_event_xml.as_bool(); if(!bind_event_xml || bind_event){ m_activeCollection->AddEvent(&(tmp->ValueChanged)); } } else{ Log::Error("Failed to load AxisControl " + name + ". This may cause a fatal runtime error!"); } } } else{ Log::Error("Axis Control Driver definitions not found! Skipping..."); } #pragma endregion AxisControl #pragma region ButtonControl xml_node ButtonControls = drive.child("ButtonControls"); if(ButtonControls){ for(xml_node button = ButtonControls.first_child(); button; button = button.next_sibling()){ string name = button.name(); xml_attribute channel = button.attribute("button"); if(channel){ bool reversed = button.attribute("reversed").as_bool(); double multiply; xml_attribute multiply_xml = button.attribute("powerMultiplier"); bool actOnRelease = button.attribute("actOnRelease").as_bool(); bool isSolenoid = button.attribute("isSolenoid").as_bool(); bool isAmpLimited = button.attribute("isAmpLimited").as_bool(); bool isRamp = button.attribute("isRamp").as_bool(); bool isOverdrive = button.attribute("isOverdrive").as_bool(); if(!multiply_xml){ Log::Error("No Power Multiplier detected for ButtonControl " + name + ". Defaulting to 1.0. This may cause driving errors!"); multiply = 1.0; } else multiply = multiply_xml.as_double(); ButtonControl *tmp = new ButtonControl(m_driveJoy, name, channel.as_int(), actOnRelease, reversed, multiply, isSolenoid, m_activeCollection, isOverdrive); m_drive->AddControlDrive(tmp); string actOnRelease_print = actOnRelease ? "true" : "false"; string reversed_print = reversed ? "true" : "false"; string isSolenoid_print = isSolenoid ? "true" : "false"; string isOverdrive_print = isOverdrive ? "true" : "false"; Log::General("Added Button Control " + name + ", Button: " + to_string(channel.as_int()) + ", ActOnRelease: " + actOnRelease_print + ", Reversed: " + reversed_print + ", PowerMultiplier: " + to_string(multiply) + ", IsSolenoid: " + isSolenoid_print + ", IsOverdrive: " + isOverdrive_print); xml_attribute bindings = button.attribute("bindings"); if(bindings){ string bind_string = bindings.as_string(); vector<string> bind_vector = getBindingStringList(bind_string); setBindingsToControl(bind_vector, tmp); } else{ Log::Error("Control bindings not found for " + name + ". Did you intend to bind this control to anything?"); } if(isAmpLimited) tmp->SetAmpRegulation(11, 30); if (isRamp) tmp->SetRamp(0.1); //TODO: make this work lol xml_attribute bind_event_xml = button.attribute("bindEvent"); bool bind_event = bind_event_xml.as_bool(); if(!bind_event_xml || bind_event){ m_activeCollection->AddEvent(&(tmp->ValueChanged)); } } else{ Log::Error("Failed to load ButtonControl " + name + ". This may cause a fatal runtime error!"); } } } else{ Log::Error("Button Control Driver definitions not found! Skipping..."); } #pragma endregion ButtonControl #pragma region ToggleButtonControl xml_node ToggleButtonControls = drive.child("ToggleButtonControls"); if(ToggleButtonControls){ for(xml_node button = ToggleButtonControls.first_child(); button; button = button.next_sibling()){ string name = button.name(); xml_attribute channel = button.attribute("button"); if(channel){ bool reversed = button.attribute("reversed").as_bool(); double multiply; xml_attribute multiply_xml = button.attribute("powerMultiplier"); if(!multiply_xml){ Log::Error("No Power Multiplier detected for ToggleButtonControl " + name + ". Defaulting to 1.0. This may cause driving errors!"); multiply = 1.0; } else multiply = multiply_xml.as_double(); ToggleButtonControl *tmp = new ToggleButtonControl(m_driveJoy, name, channel.as_int(), reversed, multiply, m_activeCollection); m_drive->AddControlDrive(tmp); xml_attribute bindings = button.attribute("bindings"); if(bindings){ string bind_string = bindings.as_string(); vector<string> bind_vector = getBindingStringList(bind_string); setBindingsToControl(bind_vector, tmp); } else{ Log::Error("Control bindings not found for " + name + ". Did you intend to bind this control to anything?"); } xml_attribute bind_event_xml = button.attribute("bindEvent"); bool bind_event = bind_event_xml.as_bool(); if(!bind_event_xml || bind_event){ m_activeCollection->AddEvent(&(tmp->ValueChanged)); } } else{ Log::Error("Failed to load ToggleButtonControl " + name + ". This may cause a fatal runtime error!"); } } } else{ Log::Error("Toggle Button Control Driver definitions not found! Skipping..."); } #pragma endregion ToggleButtonControl #pragma region GoalButtonControl xml_node GoalButtonControls = drive.child("GoalButtonControls"); if(GoalButtonControls){ for(xml_node button = GoalButtonControls.first_child(); button; button = button.next_sibling()){ string name = button.name(); xml_attribute channel = button.attribute("button"); if(channel){ xml_attribute goal = button.attribute("goal"); xml_attribute params = button.attribute("params"); xml_attribute ID = button.attribute("ID"); xml_attribute OtherKeys = button.attribute("RemoveKeys"); if(goal && params && ID && OtherKeys){ TeleOpGoal goalToAdd = getTeleOpGoal(goal.as_string()); if(goalToAdd != TeleOpGoal::eNone){ vector<int> RemKeys; vector<string> bind_vector_Key = getBindingStringList(OtherKeys.as_string()); for(int i = 0; i < bind_vector_Key.size(); i++) RemKeys.push_back(stoi(bind_vector_Key.at(i))); GoalButtonControl* tmp = new GoalButtonControl(m_driveJoy, name, channel.as_int(), m_activeCollection, goalToAdd, params.as_double(), ID.as_int(), RemKeys); m_drive->AddControlDrive(tmp); Log::General("Added GoalButtonControl " + name + ", Button: " + to_string(channel.as_int()) + ", Goal: " + goal.as_string() + ", Params: " + params.as_string()); xml_attribute bind_event_xml = button.attribute("bindEvent"); bool bind_event = bind_event_xml.as_bool(); if(!bind_event_xml || bind_event){ m_activeCollection->AddEvent(&(tmp->ValueChanged)); } } else { Log::Error("Failed to load GoalButtonControl " + name + ". This may cause a fatal runtime eror!"); } } else{ Log::Error("Failed to load GoalButtonControl " + name + ". This may cause a fatal runtime eror!"); } } else{ Log::Error("Failed to load GoalButtonControl " + name + ". This may cause a fatal runtime eror!"); } } } else{ Log::Error("Goal Button Control Driver definitions not found! Skipping..."); } #pragma endregion #pragma region GoalAxisControl xml_node GoalAxisControls = drive.child("GoalAxisControls"); if(GoalAxisControls){ for(xml_node button = GoalAxisControls.first_child(); button; button = button.next_sibling()){ string name = button.name(); xml_attribute goal = button.attribute("goal"); xml_attribute repeat = button.attribute("repeat"); xml_attribute ID = button.attribute("ID"); xml_attribute IndexStart = button.attribute("StartIndex"); xml_attribute OtherKeys = button.attribute("RemoveKeys"); xml_attribute AxisNumbers = button.attribute("Axis"); xml_attribute StringsData = button.attribute("StringData"); xml_attribute DeadZ = button.attribute("DeadZone"); xml_attribute Mult = button.attribute("mult"); if(goal && repeat && ID && OtherKeys && AxisNumbers && StringsData && DeadZ && Mult){ TeleOpGoal goalToAdd = getTeleOpGoal(goal.as_string()); if(goalToAdd != TeleOpGoal::eNone){ vector<int> RemKeys; vector<string> bind_vector_Key = getBindingStringList(OtherKeys.as_string()); for(int i = 0; i < bind_vector_Key.size(); i++) RemKeys.push_back(stoi(bind_vector_Key.at(i))); vector<int> Axis; vector<string> bind_vector_Axis = getBindingStringList(AxisNumbers.as_string()); for(int i = 0; i < bind_vector_Axis.size(); i++) RemKeys.push_back(stoi(bind_vector_Axis.at(i))); vector<string> StringDataVector = getBindingStringList(StringsData.as_string()); GoalAxisControl* tmp = new GoalAxisControl(m_driveJoy, name, Axis, m_activeCollection, goalToAdd, StringDataVector, IndexStart.as_int(), ID.as_int(), RemKeys, repeat.as_bool(), DeadZ.as_double(), Mult.as_double()); m_drive->AddControlOperate(tmp); Log::General("Added GoalAxisControl " + name + ", Goal: " + goal.as_string()); xml_attribute bind_event_xml = button.attribute("bindEvent"); bool bind_event = bind_event_xml.as_bool(); if(!bind_event_xml || bind_event){ m_activeCollection->AddEvent(&(tmp->ValueChanged)); } } else { Log::Error("Failed to load GoalAxisControl " + name + ". This may cause a fatal runtime eror!"); } } else{ Log::Error("Failed to load GoalAxisControl " + name + ". This may cause a fatal runtime eror!"); } } } else{ Log::Error("GoalAxisControl Driver definitions not found! Skipping..."); } #pragma endregion #pragma region SwerveControl xml_node Swerve = drive.child("SwerveControl"); if (Swerve) { string drivemode = Swerve.attribute("driveMode").as_string(); string name = Swerve.attribute("name").as_string(); int H = Swerve.attribute("H-Axis").as_int(); int V = Swerve.attribute("V-Axis").as_int(); int S = Swerve.attribute("S-Axis").as_int(); double dz = Swerve.attribute("deadZone").as_double(); double mult = Swerve.attribute("powerMultiplier").as_double(); bool reversed = Swerve.attribute("reversed").as_bool(); string ManagerName = Swerve.attribute("manager").as_string(); SwerveControl::DriveCalculation Cal; if (drivemode.compare("Field") == 0) { Cal = SwerveControl::DriveCalculation::Field_Oriented; } else if (drivemode.compare("Robot") == 0) { Cal = SwerveControl::DriveCalculation::Robot_Oriented; } else if (drivemode.compare("Warthog") == 0) { Cal = SwerveControl::DriveCalculation::Warthog; } else if (drivemode.compare("Field_Warthog") == 0) { Cal = SwerveControl::DriveCalculation::Warthog_Field_Oriented; } else { Cal = SwerveControl::DriveCalculation::Robot_Oriented; } if (m_activeCollection->Get(ManagerName) != nullptr) { SwerveControl *Control = new SwerveControl(m_driveJoy, Cal, name, V, H, S, dz, reversed, mult, m_activeCollection, (SwerveManager*)m_activeCollection->Get(ManagerName)); m_drive->AddControlDrive(Control); Log::General("Added swerve control that is " + drivemode + " oriented"); } else { Log::Error("Swerve control cannot find manager with name " + ManagerName); } } #pragma endregion SwerveControl } void Config::AllocateOperatorControls(xml_node &controls){ xml_node _operator = controls.child("Operator"); if(!_operator){ Log::Error("Operator Control definitions not found in config! Skipping..."); return; } int slot = _operator.attribute("slot").as_int(); Log::General("Configured Operator Joystick at slot " + to_string(slot), true); m_operatorJoy = new Joystick(slot); #pragma region AxisControl xml_node AxisControls = _operator.child("AxisControls"); if(AxisControls){ for(xml_node axis = AxisControls.first_child(); axis; axis = axis.next_sibling()){ string name = axis.name(); xml_attribute channel = axis.attribute("axis"); if(channel){ bool reversed = axis.attribute("reversed").as_bool(); double deadZone; double multiply; xml_attribute deadZone_xml = axis.attribute("deadZone"); xml_attribute multiply_xml = axis.attribute("powerMultiplier"); bool isLift = axis.attribute("isLift").as_bool(); if(!deadZone_xml){ Log::Error("No DeadZone detected for AxisControl " + name + ". Defaulting to 0.085. This may cause driving errors!"); deadZone = 0.085; } else deadZone = deadZone_xml.as_double(); if(!multiply_xml){ Log::Error("No Power Multiplier detected for AxisControl " + name + ". Defaulting to 1.0. This may cause driving errors!"); multiply = 1.0; } else multiply = multiply_xml.as_double(); AxisControl *tmp = new AxisControl(m_operatorJoy, name, channel.as_int(), deadZone, reversed, multiply, m_activeCollection); m_drive->AddControlOperate(tmp); string reversed_print = reversed ? "true" : "false" ; Log::General("Added AxisControl " + name + ", Axis: " + to_string(channel.as_int()) + ", DeadZone: " + to_string(deadZone) + ", Reversed: " + reversed_print + ", Power Multiplier: " + to_string(multiply) + "Is Lift: " + to_string(isLift)); xml_attribute bindings = axis.attribute("bindings"); if(bindings){ string bind_string = bindings.as_string(); vector<string> bind_vector = getBindingStringList(bind_string); setBindingsToControl(bind_vector, tmp); } else{ Log::Error("Control bindings not found for " + name + ". Did you intend to bind this control to anything?"); } xml_attribute bind_event_xml = axis.attribute("bindEvent"); bool bind_event = bind_event_xml.as_bool(); if(!bind_event_xml || bind_event){ m_activeCollection->AddEvent(&(tmp->ValueChanged)); } if(isLift){ tmp->SetLift(6.9, m_activeCollection); Log::General("SET LIFT"); } } else{ Log::Error("Failed to load AxisControl " + name + ". This may cause a fatal runtime error!"); } } } else{ Log::Error("Axis Control Operator definitions not found! Skipping..."); } #pragma endregion AxisControl #pragma region ButtonControl xml_node ButtonControls = _operator.child("ButtonControls"); if(ButtonControls){ for(xml_node button = ButtonControls.first_child(); button; button = button.next_sibling()){ string name = button.name(); xml_attribute channel = button.attribute("button"); if(channel){ bool reversed = button.attribute("reversed").as_bool(); double multiply; xml_attribute multiply_xml = button.attribute("powerMultiplier"); bool actOnRelease = button.attribute("actOnRelease").as_bool(); bool isSolenoid = button.attribute("isSolenoid").as_bool(); bool isAmpLimited = button.attribute("isAmpLimited").as_bool(); bool isRamp = button.attribute("isRamp").as_bool(); if(!multiply_xml){ Log::Error("No Power Multiplier detected for ButtonControl " + name + ". Defaulting to 1.0. This may cause driving errors!"); multiply = 1.0; } else multiply = multiply_xml.as_double(); ButtonControl *tmp = new ButtonControl(m_operatorJoy, name, channel.as_int(), actOnRelease, reversed, multiply, isSolenoid, m_activeCollection); m_drive->AddControlOperate(tmp); xml_attribute bindings = button.attribute("bindings"); if(bindings){ string bind_string = bindings.as_string(); vector<string> bind_vector = getBindingStringList(bind_string); setBindingsToControl(bind_vector, tmp); } else{ Log::Error("Control bindings not found for " + name + ". Did you intend to bind this control to anything?"); } if(isAmpLimited) tmp->SetAmpRegulation(11, 30); if(isRamp) tmp->SetRamp(0.1); xml_attribute bind_event_xml = button.attribute("bindEvent"); bool bind_event = bind_event_xml.as_bool(); if(!bind_event_xml || bind_event){ m_activeCollection->AddEvent(&(tmp->ValueChanged)); } } else{ Log::Error("Failed to load ButtonControl " + name + ". This may cause a fatal runtime error!"); } } } else{ Log::Error("Button Control Operator definitions not found! Skipping..."); } #pragma endregion ButtonControl #pragma region ToggleButtonControl xml_node ToggleButtonControls = _operator.child("ToggleButtonControls"); if(ToggleButtonControls){ for(xml_node button = ToggleButtonControls.first_child(); button; button = button.next_sibling()){ string name = button.name(); xml_attribute channel = button.attribute("button"); if(channel){ bool reversed = button.attribute("reversed").as_bool(); double multiply; xml_attribute multiply_xml = button.attribute("powerMultiplier"); if(!multiply_xml){ Log::Error("No Power Multiplier detected for ToggleButtonControl " + name + ". Defaulting to 1.0. This may cause driving errors!"); multiply = 1.0; } else multiply = multiply_xml.as_double(); ToggleButtonControl *tmp = new ToggleButtonControl(m_operatorJoy, name, channel.as_int(), reversed, multiply, m_activeCollection); m_drive->AddControlOperate(tmp); xml_attribute bindings = button.attribute("bindings"); if(bindings){ string bind_string = bindings.as_string(); vector<string> bind_vector = getBindingStringList(bind_string); setBindingsToControl(bind_vector, tmp); } else{ Log::Error("Control bindings not found for " + name + ". Did you intend to bind this control to anything?"); } xml_attribute bind_event_xml = button.attribute("bindEvent"); bool bind_event = bind_event_xml.as_bool(); if(!bind_event_xml || bind_event){ m_activeCollection->AddEvent(&(tmp->ValueChanged)); } } else{ Log::Error("Failed to load ToggleButtonControl " + name + ". This may cause a fatal runtime error!"); } } } else{ Log::Error("Toggle Button Control Driver definitions not found! Skipping..."); } #pragma endregion ToggleButtonControl #pragma region GoalButtonControl xml_node GoalButtonControls = _operator.child("GoalButtonControls"); if(GoalButtonControls){ for(xml_node button = GoalButtonControls.first_child(); button; button = button.next_sibling()){ string name = button.name(); xml_attribute channel = button.attribute("button"); if(channel){ xml_attribute goal = button.attribute("goal"); xml_attribute params = button.attribute("params"); xml_attribute ID = button.attribute("ID"); xml_attribute OtherKeys = button.attribute("RemoveKeys"); if(goal && params && ID && OtherKeys){ TeleOpGoal goalToAdd = getTeleOpGoal(goal.as_string()); if(goalToAdd != TeleOpGoal::eNone){ vector<int> RemKeys; vector<string> bind_vector_Key = getBindingStringList(OtherKeys.as_string()); for(int i = 0; i < bind_vector_Key.size(); i++) RemKeys.push_back(stoi(bind_vector_Key.at(i))); GoalButtonControl* tmp = new GoalButtonControl(m_operatorJoy, name, channel.as_int(), m_activeCollection, goalToAdd, params.as_double(), ID.as_int(), RemKeys); m_drive->AddControlOperate(tmp); Log::General("Added GoalButtonControl " + name + ", Button: " + to_string(channel.as_int()) + ", Goal: " + goal.as_string() + ", Params: " + params.as_string()); xml_attribute bind_event_xml = button.attribute("bindEvent"); bool bind_event = bind_event_xml.as_bool(); if(!bind_event_xml || bind_event){ m_activeCollection->AddEvent(&(tmp->ValueChanged)); } } else { Log::Error("Failed to load GoalButtonControl " + name + ". This may cause a fatal runtime eror!"); } } else{ Log::Error("Failed to load GoalButtonControl " + name + ". This may cause a fatal runtime eror!"); } } else{ Log::Error("Failed to load GoalButtonControl " + name + ". This may cause a fatal runtime eror!"); } } } else{ Log::Error("Goal Button Control Operator definitions not found! Skipping..."); } #pragma endregion #pragma region GoalAxisControl xml_node GoalAxisControls = _operator.child("GoalAxisControls"); if(GoalAxisControls){ for(xml_node button = GoalAxisControls.first_child(); button; button = button.next_sibling()){ string name = button.name(); xml_attribute goal = button.attribute("goal"); xml_attribute repeat = button.attribute("repeat"); xml_attribute ID = button.attribute("ID"); xml_attribute IndexStart = button.attribute("StartIndex"); xml_attribute OtherKeys = button.attribute("RemoveKeys"); xml_attribute AxisNumbers = button.attribute("Axis"); xml_attribute StringsData = button.attribute("StringData"); xml_attribute DeadZ = button.attribute("DeadZone"); xml_attribute Mult = button.attribute("mult"); if(goal && repeat && ID && OtherKeys && AxisNumbers && StringsData && DeadZ && Mult){ TeleOpGoal goalToAdd = getTeleOpGoal(goal.as_string()); if(goalToAdd != TeleOpGoal::eNone){ vector<int> RemKeys; vector<string> bind_vector_Key = getBindingStringList(OtherKeys.as_string()); for(int i = 0; i < bind_vector_Key.size(); i++) RemKeys.push_back(stoi(bind_vector_Key.at(i))); vector<int> Axis; vector<string> bind_vector_Axis = getBindingStringList(AxisNumbers.as_string()); for(int i = 0; i < bind_vector_Axis.size(); i++) RemKeys.push_back(stoi(bind_vector_Axis.at(i))); vector<string> StringDataVector = getBindingStringList(StringsData.as_string()); GoalAxisControl* tmp = new GoalAxisControl(m_operatorJoy, name, Axis, m_activeCollection, goalToAdd, StringDataVector, IndexStart.as_int(), ID.as_int(), RemKeys, repeat.as_bool(), DeadZ.as_double(), Mult.as_double()); m_drive->AddControlOperate(tmp); Log::General("Added GoalAxisControl " + name + ", Goal: " + goal.as_string()); xml_attribute bind_event_xml = button.attribute("bindEvent"); bool bind_event = bind_event_xml.as_bool(); if(!bind_event_xml || bind_event){ m_activeCollection->AddEvent(&(tmp->ValueChanged)); } } else { Log::Error("Failed to load GoalAxisControl " + name + ". This may cause a fatal runtime eror!"); } } else{ Log::Error("Failed to load GoalAxisControl " + name + ". This may cause a fatal runtime eror!"); } } } else{ Log::Error("GoalAxisControl Operator definitions not found! Skipping..."); } #pragma endregion } vector<string> Config::getBindingStringList(string bindings){ vector<char*> tmp; vector<string> ret; //char * pch; //unreferenced char * bindings_char = new char[bindings.length() + 1]; strcpy(bindings_char, bindings.c_str()); tmp.push_back(strtok(bindings_char, " ,")); while(tmp.back() != NULL){ tmp.push_back(strtok(NULL, " ,")); } tmp.pop_back(); for(int i = 0; i<(int)tmp.size(); i++){ string add(tmp[i]); ret.push_back(add); } return ret; } bool Config::setBindingsToControl(vector<string> bindings, ControlItem *control){ bool success = true; for(int i = 0; i<(int)bindings.size(); i++){ string binding = bindings[i]; OutputComponent *component; try{ component = (OutputComponent*)(m_activeCollection->Get(binding)); control->AddComponent(component); Log::General("Allocated Component " + binding + " to Control " + control->name); } catch(...){ Log::Error("Failed to bind component " + binding + " to the control " + control->name + ". This can cause fatal runtime errors!"); success = false; } } if(!success) Log::Error("One or more bindings failed to allocate for control " + control->name + ". Please check the Config!"); return success; } TeleOpGoal Config::getTeleOpGoal(string goalString){ if(goalString.compare("ElevatorControl") == 0){ return TeleOpGoal::eElevatorControl; } else if (goalString.compare("Timer") == 0) { return TeleOpGoal::eTimer; } else if(goalString.compare("DriveWithTimer") == 0) { return TeleOpGoal::eDriveWithTimer; } else if(goalString.compare("RelativeElevatorControl") == 0) { return TeleOpGoal::eRelativeElevatorControl; } else if(goalString.compare("ShooterGoal") == 0) { return TeleOpGoal::eShooter; } else if(goalString.compare("MotorPosition") == 0) { return TeleOpGoal::eMotorPosition; } else{ Log::Error("Error registering teleop goal " + goalString + ". Skipping this control..."); return TeleOpGoal::eNone; } } int Config::GetLocation(string Loc) { if(Loc.compare("Front_Left") == 0){ return 0; } else if(Loc.compare("Front_Right") == 0) { return 1; } else if(Loc.compare("Back_Left") == 0) { return 2; } else if(Loc.compare("Back_Right") == 0) { return 3; } else{ Log::Error("Defaulting location to SwerveModule::Location::Front_Left"); return 0; } } Config::~Config(){}
32.906486
294
0.676134
[ "vector" ]
3b79b5e53556002df6ccedf6a9717fe399d062ee
4,197
cpp
C++
src/khorne/Wrathmongers.cpp
rweyrauch/AoSSimulator
d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b
[ "MIT" ]
5
2019-02-01T01:41:19.000Z
2021-06-17T02:16:13.000Z
src/khorne/Wrathmongers.cpp
rweyrauch/AoSSimulator
d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b
[ "MIT" ]
2
2020-01-14T16:57:42.000Z
2021-04-01T00:53:18.000Z
src/khorne/Wrathmongers.cpp
rweyrauch/AoSSimulator
d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b
[ "MIT" ]
1
2019-03-02T20:03:51.000Z
2019-03-02T20:03:51.000Z
/* * Warhammer Age of Sigmar battle simulator. * * Copyright (C) 2019 by Rick Weyrauch - rpweyrauch@gmail.com * * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) */ #include <khorne/Wrathmongers.h> #include <UnitFactory.h> #include <Board.h> #include "KhornePrivate.h" namespace Khorne { static const int g_basesize = 40; static const int g_wounds = 3; static const int g_minUnitSize = 5; static const int g_maxUnitSize = 15; static const int g_pointsPerBlock = 155; static const int g_pointsMaxUnitSize = g_pointsPerBlock * 3; bool Wrathmongers::s_registered = false; Wrathmongers::Wrathmongers(SlaughterHost host, int numModels, int points) : KhorneBase("Wrathmongers", 5, g_wounds, 7, 5, false, points) { m_keywords = {CHAOS, MORTAL, KHORNE, BLOODBOUND, WRATHMONGERS}; m_weapons = {&m_wrathflails, &m_wrathflailsMaster}; s_globalAttackMod.connect(this, &Wrathmongers::crimsonHaze, &m_hazeSlot); setSlaughterHost(host); auto master = new Model(g_basesize, wounds()); master->addMeleeWeapon(&m_wrathflailsMaster); addModel(master); for (auto i = 1; i < numModels; i++) { auto model = new Model(g_basesize, wounds()); model->addMeleeWeapon(&m_wrathflails); addModel(model); } } Wrathmongers::~Wrathmongers() { m_hazeSlot.disconnect(); } Unit *Wrathmongers::Create(const ParameterList &parameters) { int numModels = GetIntParam("Models", parameters, g_minUnitSize); auto host = (SlaughterHost) GetEnumParam("Slaughter Host", parameters, g_slaughterHost[0]); return new Wrathmongers(host, numModels, ComputePoints(parameters)); } void Wrathmongers::Init() { if (!s_registered) { static FactoryMethod factoryMethod = { Wrathmongers::Create, KhorneBase::ValueToString, KhorneBase::EnumStringToInt, Wrathmongers::ComputePoints, { IntegerParameter("Models", g_minUnitSize, g_minUnitSize, g_maxUnitSize, g_minUnitSize), EnumParameter("Slaughter Host", g_slaughterHost[0], g_slaughterHost) }, CHAOS, {KHORNE} }; s_registered = UnitFactory::Register("Wrathmongers", factoryMethod); } } int Wrathmongers::toHitModifier(const Weapon *weapon, const Unit *target) const { int modifier = KhorneBase::toHitModifier(weapon, target); // Furious Assault if (m_charged) { modifier += 1; } return modifier; } int Wrathmongers::ComputePoints(const ParameterList& parameters) { int numModels = GetIntParam("Models", parameters, g_minUnitSize); auto points = numModels / g_minUnitSize * g_pointsPerBlock; if (numModels == g_maxUnitSize) { points = g_pointsMaxUnitSize; } return points; } int Wrathmongers::crimsonHaze(const Unit *attacker, const Model * /*attackingModel*/, const Weapon * /*weapon*/, const Unit *target) { // Crimson Haze if (!attacker->hasKeyword(WRATHMONGERS) && (distanceTo(target) <= 8.0)) { return 1; } return 0; } void Wrathmongers::onFriendlyModelSlain(int numSlain, Unit *attacker, Wounds::Source source) { KhorneBase::onFriendlyModelSlain(numSlain, attacker, source); // Bloodfury auto units = Board::Instance()->getUnitsWithin(this, GetEnemyId(owningPlayer()), 1.0); auto mod = 0; if (units.size() >= 2) mod = 1; for (auto unit : units) { int roll = Dice::RollD6() + mod; if (roll >= 2 && roll <= 5) { unit->applyDamage({0, 1, Wounds::Source::Ability, nullptr}, this); } else if (roll >= 6) { unit->applyDamage({0, Dice::RollD3(), Wounds::Source::Ability, nullptr}, this); } } } } //namespace Khorne
35.268908
115
0.597808
[ "model" ]
3b7acb22a1ec35ee2b5cfe7fbe82fd83f5b0bcfe
6,958
cpp
C++
src/demos/core/demo_CH_stream.cpp
zzhou292/chrono-collision
c2a20e171bb0eb8819636d370887aa32d68547c6
[ "BSD-3-Clause" ]
1
2021-12-09T05:24:42.000Z
2021-12-09T05:24:42.000Z
src/demos/core/demo_CH_stream.cpp
zzhou292/chrono-collision
c2a20e171bb0eb8819636d370887aa32d68547c6
[ "BSD-3-Clause" ]
7
2021-10-20T04:43:35.000Z
2021-12-24T08:44:31.000Z
src/demos/core/demo_CH_stream.cpp
zzhou292/chrono-collision
c2a20e171bb0eb8819636d370887aa32d68547c6
[ "BSD-3-Clause" ]
2
2021-12-09T05:32:31.000Z
2021-12-12T17:31:18.000Z
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Alessandro Tasora // ============================================================================= // // Demo code about streams // // ============================================================================= #include <cmath> #include <sstream> #include "chrono/core/ChGlobal.h" #include "chrono/core/ChLog.h" #include "chrono/core/ChMatrix.h" #include "chrono/core/ChVector.h" #include "chrono/core/ChClassFactory.h" #include "chrono/core/ChException.h" #include "chrono_thirdparty/filesystem/path.h" using namespace chrono; // NOTE: the old serialization method, based on ChStream and StreamIN and StreamOUT methods // has been replaced with the new serialization based on ChArchive and ArchiveIN and ArchiveOUT methods, // so if you are interested on object serialization look rather at // demo_archive.cpp int main(int argc, char* argv[]) { GetLog() << "Copyright (c) 2017 projectchrono.org\nChrono version: " << CHRONO_VERSION << "\n\n"; // To write something to the console, use the chrono::GetLog() // statement, which returns a global output stream to the console (just // like the std::out stream). GetLog() << "\nCHRONO foundation classes demo: streaming and serialization\n\n"; // Create (if needed) output directory const std::string out_dir = GetChronoOutputPath() + "DEMO_STREAM"; if (!filesystem::create_directory(filesystem::path(out_dir))) { std::cout << "Error creating directory " << out_dir << std::endl; return 1; } /* * TEST SOME BASIC FILE I/O , AS ASCII FILE WRITE/SAVE * */ // Chrono stream classes use exceptions for error handling, // so you should use the try-catch mechanism. // Exceptions thrown are of class ChException. try { // Open a file of class "ChStreamOutAsciiFile" for writing ascii std::string asciifile = out_dir + "/foo_file.txt"; ChStreamOutAsciiFile mfileo(asciifile.c_str()); // Write some items, space-separated, inside the ascii file. // The class ChStreamOutAsciiFile implements the << operator for most // basic types (double, int, string, etc.). mfileo << "test_token " << 123 << " " << 0.123437; } catch (ChException myex) { // Ops.. file could not be opened or written.. echo what happened! GetLog() << "ERROR: " << myex.what(); } // Ok, you wrote something in your pollo_file.txt file, // so now try to load from it... try { // Open a file for reading ascii: the ChStreamInAsciiFile has // some minimal parsing capabilities... std::string asciifile = out_dir + "/foo_file.txt"; ChStreamInAsciiFile mfilei(asciifile.c_str()); // Try to load some text tokens and convert them (at least each token // separated by space or linefeed..) char sbuff[200]; int mint; double mdouble; mfilei >> sbuff >> mint >> mdouble; // Write to the console the values which have been read from file.. GetLog() << "\nResult of ascii I/O: " << sbuff << " " << mint << " " << mdouble << "\n"; } catch (ChException myex) { // Ops.. file could not be opened or read.. echo what happened! GetLog() << "ERROR: " << myex.what(); } /* * TEST BINARY STREAMING */ // Streams inherited from the base class ChStreamOutBinary can be // used to serialize, and streams inherited from ChStreamInBinary // can be used to get them back. For example, file streams like // ChStreamOutBinaryFile and ChStreamInBinaryFile can be used for this // purpose. // All basic primitives (strings, int,etc.) and objects implementing the << // operator can be streamed into ChStreamOutBinary streams like in the // following example. try { // Open a file of class "ChStreamOutBinaryFile" for serializing std::string binfile = out_dir + "/foo_archive.dat"; ChStreamOutBinaryFile mfileo(binfile.c_str()); // Write from transient data into persistent binary file char m_text[] = "foo_string"; double m_double = 5.7766; int m_int = -348; std::string m_string = "hey! stl string"; mfileo << m_text; // store data n.1 mfileo << m_double; // store data n.2 mfileo << m_int; // store data n.3 mfileo << m_string; // store data n.4 } catch (ChException myex) { GetLog() << "ERROR: " << myex.what(); } // Well, now try to load data back, to see if things worked ok... try { // Open a file of class "ChStreamOutBinaryFile" for deserializing std::string binfile = out_dir + "/foo_archive.dat"; ChStreamInBinaryFile mfilei(binfile.c_str()); // Read from persistent binary file to transient data char m_text[200]; int m_int; double m_double; std::string m_string; mfilei >> m_text; // retrieve data n.1 mfilei >> m_double; // retrieve data n.2 mfilei >> m_int; // retrieve data n.3 mfilei >> m_string; // retrieve data n.4 GetLog() << "\nResult of binary I/O: " << m_text << " " << m_int << " " << m_double << "\n"; } catch (ChException myex) { // Ops.. file could not be opened or read.. echo what happened! GetLog() << "ERROR: " << myex.what(); } /* * TEST std:: STREAM WRAPPING */ // In the previous examples we showed how to use Chrono::Engine // file streams such as ChStreamInBinaryFile and ChStreamOutBinaryFile, // but in the following we show that we can also wrap whatever object // of type std::istream or std::ostream (already opened files, string streams, // console logs, etc), thank to ChStreamOutBinaryStream and // ChStreamInBinaryStream. All the concepts learned until now, such as // serialization through << and >> , are still possible. try { std::stringstream mstream; ChStreamOutBinaryStream mchstreamo(&mstream); double md_out = 12.5; mchstreamo << md_out; double md_in; ChStreamInBinaryStream mchstreami(&mstream); mchstreami >> md_in; GetLog() << "\nResult of binary I/O from wrapped std::stream: " << md_in << "\n"; } catch (ChException myex) { // Ops.. some error.. echo what happened! GetLog() << "ERROR: " << myex.what(); } return 0; }
36.814815
104
0.601897
[ "object" ]
3b7cdf8a10523ef567eaf2e00867d2b60b37cf03
5,218
cc
C++
mysqlx_expression.cc
DusanZokic/pecl-database-mysql_xdevapi-trunk
e49aef311ba04ea3e70190c026d0c9ee8d1d3947
[ "PHP-3.01" ]
14
2017-11-16T03:13:31.000Z
2022-03-10T14:59:53.000Z
mysqlx_expression.cc
DusanZokic/pecl-database-mysql_xdevapi-trunk
e49aef311ba04ea3e70190c026d0c9ee8d1d3947
[ "PHP-3.01" ]
8
2018-03-02T06:08:27.000Z
2022-01-18T10:34:43.000Z
mysqlx_expression.cc
DusanZokic/pecl-database-mysql_xdevapi-trunk
e49aef311ba04ea3e70190c026d0c9ee8d1d3947
[ "PHP-3.01" ]
18
2018-03-01T13:45:16.000Z
2022-03-10T06:30:02.000Z
/* +----------------------------------------------------------------------+ | PHP Version 7 | +----------------------------------------------------------------------+ | Copyright (c) The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andrey Hristov <andrey@php.net> | +----------------------------------------------------------------------+ */ #include "php_api.h" #include "mysqlnd_api.h" #include "xmysqlnd/xmysqlnd.h" #include "xmysqlnd/xmysqlnd_crud_collection_commands.h" #include "php_mysqlx.h" #include "mysqlx_class_properties.h" #include "mysqlx_expression.h" #include "util/allocator.h" #include "util/arguments.h" #include "util/functions.h" #include "util/object.h" namespace mysqlx { namespace devapi { using namespace drv; static zend_class_entry * mysqlx_expression_class_entry; struct st_mysqlx_expression : public util::custom_allocable { util::zvalue expression; }; ZEND_BEGIN_ARG_INFO_EX(arginfo_mysqlx_expression__construct, 0, ZEND_RETURN_VALUE, 1) ZEND_ARG_TYPE_INFO(no_pass_by_ref, expression, IS_STRING, dont_allow_null) ZEND_END_ARG_INFO() MYSQL_XDEVAPI_PHP_METHOD(mysqlx_expression, __construct) { UNUSED(return_value); util::raw_zval* object_zv{nullptr}; util::arg_string expression; DBG_ENTER("mysqlx_expression::__construct"); if (FAILURE == util::get_method_arguments(execute_data, getThis(), "Os", &object_zv, mysqlx_expression_class_entry, &(expression.str), &(expression.len))) { DBG_VOID_RETURN; } DBG_INF_FMT("expression=[%*s]", expression.length(), expression.data()); st_mysqlx_expression& data_object = util::fetch_data_object<st_mysqlx_expression>(object_zv); data_object.expression = expression; DBG_VOID_RETURN; } static const zend_function_entry mysqlx_expression_methods[] = { PHP_ME(mysqlx_expression, __construct, arginfo_mysqlx_expression__construct, ZEND_ACC_PUBLIC) {nullptr, nullptr, nullptr} }; MYSQL_XDEVAPI_PHP_FUNCTION(mysql_xdevapi__expression) { util::arg_string expression; DBG_ENTER("mysql_xdevapi__Expression"); if (FAILURE == util::get_function_arguments(execute_data, "s", &expression.str, &expression.len)) { DBG_VOID_RETURN; } create_expression(expression.to_view()).move_to(return_value); DBG_VOID_RETURN; } static zend_object_handlers mysqlx_object_expression_handlers; static HashTable mysqlx_expression_properties; const st_mysqlx_property_entry mysqlx_expression_property_entries[] = { {std::string_view{}, nullptr, nullptr} }; static void mysqlx_expression_free_storage(zend_object* object) { util::free_object<st_mysqlx_expression>(object); } static zend_object * php_mysqlx_expression_object_allocator(zend_class_entry* class_type) { DBG_ENTER("php_mysqlx_expression_object_allocator"); st_mysqlx_object* mysqlx_object = util::alloc_object<st_mysqlx_expression>( class_type, &mysqlx_object_expression_handlers, &mysqlx_expression_properties); DBG_RETURN(&mysqlx_object->zo); } void mysqlx_register_expression_class(UNUSED_INIT_FUNC_ARGS, zend_object_handlers* mysqlx_std_object_handlers) { MYSQL_XDEVAPI_REGISTER_CLASS( mysqlx_expression_class_entry, "Expression", mysqlx_std_object_handlers, mysqlx_object_expression_handlers, php_mysqlx_expression_object_allocator, mysqlx_expression_free_storage, mysqlx_expression_methods, mysqlx_expression_properties, mysqlx_expression_property_entries); /* The following is needed for the Reflection API */ zend_declare_property_null(mysqlx_expression_class_entry, "name", sizeof("name") - 1, ZEND_ACC_PUBLIC); } void mysqlx_unregister_expression_class(UNUSED_SHUTDOWN_FUNC_ARGS) { zend_hash_destroy(&mysqlx_expression_properties); } util::zvalue create_expression(const util::string_view& expression) { DBG_ENTER("create_expression"); util::zvalue expression_obj; st_mysqlx_expression& data_object{ util::init_object<st_mysqlx_expression>(mysqlx_expression_class_entry, expression_obj) }; data_object.expression = expression; DBG_RETURN(expression_obj); } bool is_expression_object(const util::zvalue& value) { return value.is_instance_of(mysqlx_expression_class_entry); } util::zvalue get_expression_object(const util::zvalue& value) { DBG_ENTER("get_expression_object"); assert(is_expression_object(value)); st_mysqlx_expression& data_object = util::fetch_data_object<st_mysqlx_expression>(value); DBG_RETURN(data_object.expression); } } // namespace devapi } // namespace mysqlx
30.51462
105
0.706209
[ "object" ]
3b7f0c91b476b8023108da0c1bd977dcb40f2fb6
10,671
cc
C++
mindspore/ccsrc/backend/kernel_compiler/tbe/tbe_adapter.cc
GuoSuiming/mindspore
48afc4cfa53d970c0b20eedfb46e039db2a133d5
[ "Apache-2.0" ]
55
2020-12-17T10:26:06.000Z
2022-03-28T07:18:26.000Z
mindspore/ccsrc/backend/kernel_compiler/tbe/tbe_adapter.cc
forwhat461/mindspore
59a277756eb4faad9ac9afcc7fd526e8277d4994
[ "Apache-2.0" ]
null
null
null
mindspore/ccsrc/backend/kernel_compiler/tbe/tbe_adapter.cc
forwhat461/mindspore
59a277756eb4faad9ac9afcc7fd526e8277d4994
[ "Apache-2.0" ]
14
2021-01-29T02:39:47.000Z
2022-03-23T05:00:26.000Z
/** * Copyright 2020 Huawei Technologies Co., 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. */ #include "backend/kernel_compiler/tbe/tbe_adapter.h" #include <map> #include <unordered_set> #include <string> #include <memory> #include <vector> #include <algorithm> #include "backend/session/anf_runtime_algorithm.h" #include "backend/kernel_compiler/oplib/opinfo.h" namespace mindspore { namespace kernel { namespace tbe { std::unordered_set<std::string> input_order_adjusted_ops = { "Conv2DBackpropInput", "Conv2DBackpropFilter", "LogSoftmaxGrad", "LayerNormGrad", "LayerNormXBackprop", "LayerNormBetaGammaBackprop", "MinimumGrad", "MaximumGrad", "ApplyCenteredRMSProp"}; void TbeAdapter::InputOrderPass(const std::string &op_name, std::vector<std::vector<nlohmann::json>> const &inputs_list, nlohmann::json *inputs_json) { MS_EXCEPTION_IF_NULL(inputs_json); if (input_order_adjusted_ops.find(op_name) == input_order_adjusted_ops.end()) { (void)std::copy(inputs_list.begin(), inputs_list.end(), std::back_inserter((*inputs_json))); } else { if (op_name == "MinimumGrad" || op_name == "MaximumGrad") { inputs_json->push_back(inputs_list[2]); inputs_json->push_back(inputs_list[0]); inputs_json->push_back(inputs_list[1]); for (size_t i = 3; i < inputs_list.size(); ++i) { inputs_json->push_back(inputs_list[i]); } } else if (op_name == "ApplyCenteredRMSProp") { // Parameter order of ApplyCenteredRMSProp's TBE implementation is different from python API, so map // TBE parameter to correspond python API parameter by latter's index using hardcode inputs_json->push_back(inputs_list[0]); inputs_json->push_back(inputs_list[1]); inputs_json->push_back(inputs_list[2]); inputs_json->push_back(inputs_list[3]); inputs_json->push_back(inputs_list[5]); inputs_json->push_back(inputs_list[6]); inputs_json->push_back(inputs_list[7]); inputs_json->push_back(inputs_list[8]); inputs_json->push_back(inputs_list[4]); } else { inputs_json->push_back(inputs_list[1]); inputs_json->push_back(inputs_list[0]); for (size_t i = 2; i < inputs_list.size(); ++i) { inputs_json->push_back(inputs_list[i]); } } } } void TbeAdapter::FusionInputOrderPass(const std::string &op_name, const std::vector<nlohmann::json> &inputs_list, std::vector<nlohmann::json> *inputs_json) { MS_EXCEPTION_IF_NULL(inputs_json); if (input_order_adjusted_ops.find(op_name) == input_order_adjusted_ops.end()) { (void)std::copy(inputs_list.begin(), inputs_list.end(), std::back_inserter((*inputs_json))); } else { if (op_name == "MinimumGrad" || op_name == "MaximumGrad") { inputs_json->emplace_back(inputs_list[2]); inputs_json->emplace_back(inputs_list[0]); inputs_json->emplace_back(inputs_list[1]); for (size_t i = 3; i < inputs_list.size(); ++i) { inputs_json->emplace_back(inputs_list[i]); } } else { inputs_json->emplace_back(inputs_list[1]); inputs_json->emplace_back(inputs_list[0]); for (size_t i = 2; i < inputs_list.size(); ++i) { inputs_json->emplace_back(inputs_list[i]); } } } } void TbeAdapter::FusionDataOrderPass(const std::string &op_name, const std::vector<AnfNodePtr> &data_layer, std::vector<AnfNodePtr> *reorder_data_layer) { MS_EXCEPTION_IF_NULL(reorder_data_layer); if (input_order_adjusted_ops.find(op_name) == input_order_adjusted_ops.end()) { (void)std::copy(data_layer.begin(), data_layer.end(), std::back_inserter((*reorder_data_layer))); } else { if (op_name == "MinimumGrad" || op_name == "MaximumGrad") { reorder_data_layer->emplace_back(data_layer[2]); reorder_data_layer->emplace_back(data_layer[0]); reorder_data_layer->emplace_back(data_layer[1]); for (size_t i = 3; i < data_layer.size(); ++i) { reorder_data_layer->emplace_back(data_layer[i]); } } else { reorder_data_layer->emplace_back(data_layer[1]); reorder_data_layer->emplace_back(data_layer[0]); for (size_t i = 2; i < data_layer.size(); ++i) { reorder_data_layer->emplace_back(data_layer[i]); } } } } std::map<std::string, FAttrsPass> TbeAdapter::build_json_attr_pass_map_ = { {"MaximumGrad", TbeAdapter::MaximumGradAttrJsonPass}, {"MinimumGrad", TbeAdapter::MinimumGradAttrJsonPass}, {"Cast", TbeAdapter::CastAttrJsonPass}}; bool TbeAdapter::RunAttrPass(const mindspore::AnfNodePtr &anf_node, const std::vector<std::shared_ptr<mindspore::kernel::OpAttr>> &op_info_attrs, nlohmann::json *attrs_json) { MS_EXCEPTION_IF_NULL(attrs_json); auto cnode_name = AnfAlgo::GetCNodeName(anf_node); auto FPass = build_json_attr_pass_map_.find(cnode_name); if (FPass != build_json_attr_pass_map_.end()) { FPass->second(anf_node, op_info_attrs, attrs_json); return true; } return false; } void TbeAdapter::MaximumGradAttrJsonPass(const mindspore::AnfNodePtr &anf_node, const std::vector<std::shared_ptr<mindspore::kernel::OpAttr>> &op_info_attrs, nlohmann::json *attrs_json) { MS_EXCEPTION_IF_NULL(anf_node); MS_EXCEPTION_IF_NULL(attrs_json); auto attr_num = op_info_attrs.size(); auto primitive = AnfAlgo::GetCNodePrimitive(anf_node); MS_EXCEPTION_IF_NULL(primitive); for (size_t i = 0; i < attr_num; i++) { nlohmann::json attr_obj; MS_EXCEPTION_IF_NULL(op_info_attrs[i]); std::string attr_name = op_info_attrs[i]->name(); auto value = primitive->GetAttr(attr_name); if (value != nullptr) { bool attr_value = GetValue<bool>(value); attr_obj["value"] = attr_value; attr_obj["valid"] = true; } else { attr_obj["valid"] = false; } attr_obj["name"] = attr_name; attrs_json->push_back(attr_obj); } MS_LOG(INFO) << "MaximumGradAttrJsonPass done."; } void TbeAdapter::MinimumGradAttrJsonPass(const mindspore::AnfNodePtr &anf_node, const std::vector<std::shared_ptr<mindspore::kernel::OpAttr>> &op_info_attrs, nlohmann::json *attrs_json) { MS_EXCEPTION_IF_NULL(anf_node); MS_EXCEPTION_IF_NULL(attrs_json); auto attr_num = op_info_attrs.size(); auto primitive = AnfAlgo::GetCNodePrimitive(anf_node); MS_EXCEPTION_IF_NULL(primitive); for (size_t i = 0; i < attr_num; i++) { nlohmann::json attr_obj; MS_EXCEPTION_IF_NULL(op_info_attrs[i]); std::string attr_name = op_info_attrs[i]->name(); auto value = primitive->GetAttr(attr_name); if (value != nullptr) { bool attr_value = GetValue<bool>(value); attr_obj["value"] = attr_value; attr_obj["valid"] = true; } else { attr_obj["valid"] = false; } attr_obj["name"] = attr_name; attrs_json->push_back(attr_obj); } MS_LOG(INFO) << "MinimumGradAttrJsonPass done."; } static int TypeStrToDstType(const std::string &type_str) { int ret = -1; if (type_str == "Float" || type_str == "Float32") { ret = 0; } else if (type_str == "Float16") { ret = 1; } else if (type_str == "Int8") { ret = 2; } else if (type_str == "Int32") { ret = 3; } else if (type_str == "UInt8") { ret = 4; } else if (type_str == "UInt64") { ret = 10; } else if (type_str == "Bool") { ret = 12; } else { MS_LOG(INFO) << "Error type str is invailed: " << type_str; } return ret; } void TbeAdapter::CastAttrJsonPass(const mindspore::AnfNodePtr &anf_node, const std::vector<std::shared_ptr<mindspore::kernel::OpAttr>> &op_info_attrs, nlohmann::json *attrs_json) { MS_EXCEPTION_IF_NULL(anf_node); MS_EXCEPTION_IF_NULL(attrs_json); if (op_info_attrs.size() != 1) { MS_LOG(INFO) << "cast node should has dst_type attr"; return; } auto attr_name = op_info_attrs[0]->name(); auto type_ptr = std::make_shared<TensorType>(TypeIdToType(AnfAlgo::GetOutputDeviceDataType(anf_node, 0))); MS_EXCEPTION_IF_NULL(type_ptr); auto type_element = type_ptr->element(); MS_EXCEPTION_IF_NULL(type_element); auto dtype = type_element->ToString(); auto dst_type_value = TypeStrToDstType(dtype); nlohmann::json attr_obj; attr_obj["value"] = dst_type_value; attr_obj["valid"] = true; attr_obj["name"] = attr_name; attrs_json->push_back(attr_obj); MS_LOG(INFO) << "CastAttrJsonPass done."; } void TbeAdapter::GenTopKV2IndicesTensorInfo(const std::shared_ptr<mindspore::AnfNode> &anf_node, size_t real_input_index, std::vector<nlohmann::json> *input_list, mindspore::kernel::kCreaterType creater_type) { MS_EXCEPTION_IF_NULL(anf_node); MS_EXCEPTION_IF_NULL(input_list); auto input_x_shape = AnfAlgo::GetOutputInferShape(anf_node, 0); size_t last_dim = input_x_shape[input_x_shape.size() - 1]; std::vector<size_t> tensor_shape = {last_dim}; std::vector<size_t> tensor_origin_shape = {last_dim}; std::string tensor_format = AnfAlgo::GetInputFormat(anf_node, static_cast<const size_t &>(real_input_index)); if (tensor_format == kOpFormat_DEFAULT) { tensor_format = kOpFormat_NCHW; } std::string tensor_origin_format = kOpFormat_NCHW; std::string tensor_dtype = "float16"; nlohmann::json input_desc_json; input_desc_json["dtype"] = tensor_dtype; input_desc_json["name"] = AnfAlgo::GetCNodeName(anf_node); input_desc_json["ori_shape"] = tensor_origin_shape; input_desc_json["ori_format"] = tensor_origin_format; input_desc_json["shape"] = tensor_shape; if (creater_type == OP_SELECT_FORMAT) { input_desc_json["format"] = tensor_origin_format; } else { input_desc_json["format"] = tensor_format; } input_desc_json["valid"] = true; input_list->emplace_back(input_desc_json); } } // namespace tbe } // namespace kernel } // namespace mindspore
40.267925
120
0.672945
[ "shape", "vector" ]
3b8668d85ff0fb4104e3e190a9dfac81c8f84bc6
13,340
cc
C++
cc/raster/raster_buffer_provider_unittest.cc
google-ar/chromium
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
777
2017-08-29T15:15:32.000Z
2022-03-21T05:29:41.000Z
cc/raster/raster_buffer_provider_unittest.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
66
2017-08-30T18:31:18.000Z
2021-08-02T10:59:35.000Z
cc/raster/raster_buffer_provider_unittest.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
123
2017-08-30T01:19:34.000Z
2022-03-17T22:55:31.000Z
// Copyright 2013 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 "cc/raster/raster_buffer_provider.h" #include <stddef.h> #include <stdint.h> #include <algorithm> #include <limits> #include <vector> #include "base/cancelable_callback.h" #include "base/location.h" #include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/message_loop/message_loop.h" #include "base/single_thread_task_runner.h" #include "base/threading/thread_task_runner_handle.h" #include "cc/base/unique_notifier.h" #include "cc/raster/bitmap_raster_buffer_provider.h" #include "cc/raster/gpu_raster_buffer_provider.h" #include "cc/raster/one_copy_raster_buffer_provider.h" #include "cc/raster/synchronous_task_graph_runner.h" #include "cc/raster/zero_copy_raster_buffer_provider.h" #include "cc/resources/platform_color.h" #include "cc/resources/resource_pool.h" #include "cc/resources/resource_provider.h" #include "cc/resources/scoped_resource.h" #include "cc/test/fake_raster_source.h" #include "cc/test/fake_resource_provider.h" #include "cc/test/test_context_provider.h" #include "cc/test/test_gpu_memory_buffer_manager.h" #include "cc/test/test_shared_bitmap_manager.h" #include "cc/test/test_web_graphics_context_3d.h" #include "cc/tiles/tile_task_manager.h" #include "gpu/GLES2/gl2extchromium.h" #include "testing/gtest/include/gtest/gtest.h" namespace cc { namespace { const size_t kMaxBytesPerCopyOperation = 1000U; const size_t kMaxStagingBuffers = 32U; enum RasterBufferProviderType { RASTER_BUFFER_PROVIDER_TYPE_ZERO_COPY, RASTER_BUFFER_PROVIDER_TYPE_ONE_COPY, RASTER_BUFFER_PROVIDER_TYPE_GPU, RASTER_BUFFER_PROVIDER_TYPE_BITMAP }; class TestRasterTaskCompletionHandler { public: virtual void OnRasterTaskCompleted( std::unique_ptr<RasterBuffer> raster_buffer, unsigned id, bool was_canceled) = 0; }; class TestRasterTaskImpl : public TileTask { public: TestRasterTaskImpl(TestRasterTaskCompletionHandler* completion_handler, std::unique_ptr<ScopedResource> resource, unsigned id, std::unique_ptr<RasterBuffer> raster_buffer, TileTask::Vector* dependencies) : TileTask(true, dependencies), completion_handler_(completion_handler), resource_(std::move(resource)), id_(id), raster_buffer_(std::move(raster_buffer)), raster_source_(FakeRasterSource::CreateFilled(gfx::Size(1, 1))) {} // Overridden from Task: void RunOnWorkerThread() override { // Don't use the image hijack canvas for these tests, as they have no image // decode controller. RasterSource::PlaybackSettings settings; settings.use_image_hijack_canvas = false; uint64_t new_content_id = 0; raster_buffer_->Playback(raster_source_.get(), gfx::Rect(1, 1), gfx::Rect(1, 1), new_content_id, 1.f, settings); } // Overridden from TileTask: void OnTaskCompleted() override { completion_handler_->OnRasterTaskCompleted(std::move(raster_buffer_), id_, state().IsCanceled()); } protected: ~TestRasterTaskImpl() override {} private: TestRasterTaskCompletionHandler* completion_handler_; std::unique_ptr<ScopedResource> resource_; unsigned id_; std::unique_ptr<RasterBuffer> raster_buffer_; scoped_refptr<RasterSource> raster_source_; DISALLOW_COPY_AND_ASSIGN(TestRasterTaskImpl); }; class BlockingTestRasterTaskImpl : public TestRasterTaskImpl { public: BlockingTestRasterTaskImpl( TestRasterTaskCompletionHandler* completion_handler, std::unique_ptr<ScopedResource> resource, unsigned id, std::unique_ptr<RasterBuffer> raster_buffer, base::Lock* lock, TileTask::Vector* dependencies) : TestRasterTaskImpl(completion_handler, std::move(resource), id, std::move(raster_buffer), dependencies), lock_(lock) {} // Overridden from Task: void RunOnWorkerThread() override { base::AutoLock lock(*lock_); TestRasterTaskImpl::RunOnWorkerThread(); } protected: ~BlockingTestRasterTaskImpl() override {} private: base::Lock* lock_; DISALLOW_COPY_AND_ASSIGN(BlockingTestRasterTaskImpl); }; class RasterBufferProviderTest : public TestRasterTaskCompletionHandler, public testing::TestWithParam<RasterBufferProviderType> { public: struct RasterTaskResult { unsigned id; bool canceled; }; typedef std::vector<scoped_refptr<TileTask>> RasterTaskVector; enum NamedTaskSet { REQUIRED_FOR_ACTIVATION, REQUIRED_FOR_DRAW, ALL }; RasterBufferProviderTest() : all_tile_tasks_finished_( base::ThreadTaskRunnerHandle::Get().get(), base::Bind(&RasterBufferProviderTest::AllTileTasksFinished, base::Unretained(this))), timeout_seconds_(5), timed_out_(false) {} // Overridden from testing::Test: void SetUp() override { switch (GetParam()) { case RASTER_BUFFER_PROVIDER_TYPE_ZERO_COPY: Create3dResourceProvider(); raster_buffer_provider_ = ZeroCopyRasterBufferProvider::Create( resource_provider_.get(), PlatformColor::BestTextureFormat()); break; case RASTER_BUFFER_PROVIDER_TYPE_ONE_COPY: Create3dResourceProvider(); raster_buffer_provider_ = base::MakeUnique<OneCopyRasterBufferProvider>( base::ThreadTaskRunnerHandle::Get().get(), context_provider_.get(), worker_context_provider_.get(), resource_provider_.get(), kMaxBytesPerCopyOperation, false, kMaxStagingBuffers, PlatformColor::BestTextureFormat(), false); break; case RASTER_BUFFER_PROVIDER_TYPE_GPU: Create3dResourceProvider(); raster_buffer_provider_ = base::MakeUnique<GpuRasterBufferProvider>( context_provider_.get(), worker_context_provider_.get(), resource_provider_.get(), false, 0, false); break; case RASTER_BUFFER_PROVIDER_TYPE_BITMAP: CreateSoftwareResourceProvider(); raster_buffer_provider_ = BitmapRasterBufferProvider::Create(resource_provider_.get()); break; } DCHECK(raster_buffer_provider_); tile_task_manager_ = TileTaskManagerImpl::Create(&task_graph_runner_); } void TearDown() override { tile_task_manager_->Shutdown(); tile_task_manager_->CheckForCompletedTasks(); raster_buffer_provider_->Shutdown(); } void AllTileTasksFinished() { tile_task_manager_->CheckForCompletedTasks(); base::MessageLoop::current()->QuitWhenIdle(); } void RunMessageLoopUntilAllTasksHaveCompleted() { task_graph_runner_.RunUntilIdle(); tile_task_manager_->CheckForCompletedTasks(); } void ScheduleTasks() { graph_.Reset(); size_t priority = 0; for (RasterTaskVector::const_iterator it = tasks_.begin(); it != tasks_.end(); ++it) { graph_.nodes.emplace_back(it->get(), 0 /* group */, priority++, 0 /* dependencies */); } raster_buffer_provider_->OrderingBarrier(); tile_task_manager_->ScheduleTasks(&graph_); } void AppendTask(unsigned id, const gfx::Size& size) { std::unique_ptr<ScopedResource> resource( ScopedResource::Create(resource_provider_.get())); resource->Allocate(size, ResourceProvider::TEXTURE_HINT_IMMUTABLE, RGBA_8888, gfx::ColorSpace()); // The raster buffer has no tile ids associated with it for partial update, // so doesn't need to provide a valid dirty rect. std::unique_ptr<RasterBuffer> raster_buffer = raster_buffer_provider_->AcquireBufferForRaster(resource.get(), 0, 0); TileTask::Vector empty; tasks_.push_back(new TestRasterTaskImpl(this, std::move(resource), id, std::move(raster_buffer), &empty)); } void AppendTask(unsigned id) { AppendTask(id, gfx::Size(1, 1)); } void AppendBlockingTask(unsigned id, base::Lock* lock) { const gfx::Size size(1, 1); std::unique_ptr<ScopedResource> resource( ScopedResource::Create(resource_provider_.get())); resource->Allocate(size, ResourceProvider::TEXTURE_HINT_IMMUTABLE, RGBA_8888, gfx::ColorSpace()); std::unique_ptr<RasterBuffer> raster_buffer = raster_buffer_provider_->AcquireBufferForRaster(resource.get(), 0, 0); TileTask::Vector empty; tasks_.push_back(new BlockingTestRasterTaskImpl( this, std::move(resource), id, std::move(raster_buffer), lock, &empty)); } const std::vector<RasterTaskResult>& completed_tasks() const { return completed_tasks_; } void LoseContext(ContextProvider* context_provider) { if (!context_provider) return; context_provider->ContextGL()->LoseContextCHROMIUM( GL_GUILTY_CONTEXT_RESET_ARB, GL_INNOCENT_CONTEXT_RESET_ARB); context_provider->ContextGL()->Flush(); } void OnRasterTaskCompleted(std::unique_ptr<RasterBuffer> raster_buffer, unsigned id, bool was_canceled) override { raster_buffer_provider_->ReleaseBufferForRaster(std::move(raster_buffer)); RasterTaskResult result; result.id = id; result.canceled = was_canceled; completed_tasks_.push_back(result); } private: void Create3dResourceProvider() { context_provider_ = TestContextProvider::Create(); context_provider_->BindToCurrentThread(); worker_context_provider_ = TestContextProvider::CreateWorker(); TestWebGraphicsContext3D* context3d = context_provider_->TestContext3d(); context3d->set_support_sync_query(true); resource_provider_ = FakeResourceProvider::Create( context_provider_.get(), &shared_bitmap_manager_, &gpu_memory_buffer_manager_); } void CreateSoftwareResourceProvider() { resource_provider_ = FakeResourceProvider::Create( nullptr, &shared_bitmap_manager_, &gpu_memory_buffer_manager_); } void OnTimeout() { timed_out_ = true; base::MessageLoop::current()->QuitWhenIdle(); } protected: scoped_refptr<TestContextProvider> context_provider_; scoped_refptr<TestContextProvider> worker_context_provider_; std::unique_ptr<ResourceProvider> resource_provider_; std::unique_ptr<TileTaskManager> tile_task_manager_; std::unique_ptr<RasterBufferProvider> raster_buffer_provider_; TestGpuMemoryBufferManager gpu_memory_buffer_manager_; TestSharedBitmapManager shared_bitmap_manager_; SynchronousTaskGraphRunner task_graph_runner_; base::CancelableClosure timeout_; UniqueNotifier all_tile_tasks_finished_; int timeout_seconds_; bool timed_out_; RasterTaskVector tasks_; std::vector<RasterTaskResult> completed_tasks_; TaskGraph graph_; }; TEST_P(RasterBufferProviderTest, Basic) { AppendTask(0u); AppendTask(1u); ScheduleTasks(); RunMessageLoopUntilAllTasksHaveCompleted(); ASSERT_EQ(2u, completed_tasks().size()); EXPECT_FALSE(completed_tasks()[0].canceled); EXPECT_FALSE(completed_tasks()[1].canceled); } TEST_P(RasterBufferProviderTest, FailedMapResource) { if (GetParam() == RASTER_BUFFER_PROVIDER_TYPE_BITMAP) return; TestWebGraphicsContext3D* context3d = context_provider_->TestContext3d(); context3d->set_times_map_buffer_chromium_succeeds(0); AppendTask(0u); ScheduleTasks(); RunMessageLoopUntilAllTasksHaveCompleted(); ASSERT_EQ(1u, completed_tasks().size()); EXPECT_FALSE(completed_tasks()[0].canceled); } // This test checks that replacing a pending raster task with another does // not prevent the DidFinishRunningTileTasks notification from being sent. TEST_P(RasterBufferProviderTest, FalseThrottling) { base::Lock lock; // Schedule a task that is prevented from completing with a lock. lock.Acquire(); AppendBlockingTask(0u, &lock); ScheduleTasks(); // Schedule another task to replace the still-pending task. Because the old // task is not a throttled task in the new task set, it should not prevent // DidFinishRunningTileTasks from getting signaled. RasterTaskVector tasks; tasks.swap(tasks_); AppendTask(1u); ScheduleTasks(); // Unblock the first task to allow the second task to complete. lock.Release(); RunMessageLoopUntilAllTasksHaveCompleted(); } TEST_P(RasterBufferProviderTest, LostContext) { LoseContext(context_provider_.get()); LoseContext(worker_context_provider_.get()); AppendTask(0u); AppendTask(1u); ScheduleTasks(); RunMessageLoopUntilAllTasksHaveCompleted(); ASSERT_EQ(2u, completed_tasks().size()); EXPECT_FALSE(completed_tasks()[0].canceled); EXPECT_FALSE(completed_tasks()[1].canceled); } INSTANTIATE_TEST_CASE_P(RasterBufferProviderTests, RasterBufferProviderTest, ::testing::Values(RASTER_BUFFER_PROVIDER_TYPE_ZERO_COPY, RASTER_BUFFER_PROVIDER_TYPE_ONE_COPY, RASTER_BUFFER_PROVIDER_TYPE_GPU, RASTER_BUFFER_PROVIDER_TYPE_BITMAP)); } // namespace } // namespace cc
33.857868
80
0.715367
[ "vector" ]
3b875a4dc71d9acab415eae3f0cd3c2ab9402d7d
40,959
cpp
C++
src/ofxGrtTimeseriesPlot.cpp
damellis/ofxGrt
4bccca400e7b91c081eba11823a2273c5335c9f4
[ "MIT" ]
1
2021-04-25T13:23:06.000Z
2021-04-25T13:23:06.000Z
src/ofxGrtTimeseriesPlot.cpp
damellis/ofxGrt
4bccca400e7b91c081eba11823a2273c5335c9f4
[ "MIT" ]
null
null
null
src/ofxGrtTimeseriesPlot.cpp
damellis/ofxGrt
4bccca400e7b91c081eba11823a2273c5335c9f4
[ "MIT" ]
null
null
null
#include "ofxGrtTimeseriesPlot.h" #include <algorithm> using namespace GRT; ofxGrtTimeseriesPlot::ofxGrtTimeseriesPlot(){ config = ofxGrtSettings::GetInstance().get(); plotTitle = ""; font = &config.get()->fontNormal; initialized = false; lockRanges = false; linkRanges = false; dynamicScale = false; drawOrderInverted = false; globalMin = std::numeric_limits<float>::max(); globalMax = -std::numeric_limits<float>::max(); constrainValuesToGraph = true; drawInfoText = true; drawPlotTitle = true; drawPlotValues = true; drawGrid = true; textColor = config->activeTextColor; backgroundColor = config->backgroundColor; gridColor = config->gridColor; axisColor = config->axisColor; errorLog.setProceedingText("[ERROR ofxGrtTimeseriesPlot]"); xAxisInfo = "X"; yAxisInfo = " Y"; insetPlotByInfoMarginX = true; insetPlotByInfoMarginY = true; } ofxGrtTimeseriesPlot::~ofxGrtTimeseriesPlot(){ } bool ofxGrtTimeseriesPlot::setup( const unsigned int timeseriesLength, const unsigned int numChannels, const std::string title ){ std::unique_lock<std::mutex> lock( mtx ); initialized = false; //Cleanup the old memory dataBuffer.clear(); highlightBuffer.clear(); labelBuffer.clear(); if( timeseriesLength == 0 || numChannels == 0 ) return false; //Setup the memory for the new buffer this->timeseriesLength = timeseriesLength; this->numChannels = numChannels; this->plotTitle = title; dataBuffer.resize(timeseriesLength, vector<float>(numChannels,-1)); highlightBuffer.resize(timeseriesLength, 0); labelBuffer.resize(timeseriesLength, ""); //Fill the buffer with empty values for(unsigned int i=0; i<timeseriesLength; i++) { dataBuffer.push_back(vector<float>(numChannels,-1)); highlightBuffer.push_back(0); labelBuffer.push_back(""); } lockRanges = false; linkRanges = false; dynamicScale = false; globalMin = std::numeric_limits<float>::max(); globalMax = -std::numeric_limits<float>::max(); channelRanges.resize( numChannels, std::pair<float,float>(globalMin,globalMax) ); channelNames.resize(numChannels,""); // labelPlotcolors channelVisible.resize(numChannels,true); initialized = true; labelPlotColors.resize(10); labelPlotColors[0].background = {16, 16, 16, 40}; labelPlotColors[0].label = {0, 0, 0, 255}; labelPlotColors[1].background = {16, 16, 16, 40}; labelPlotColors[1].label = {0, 0, 0, 255}; labelPlotColors[2].background = {16, 16, 16, 40}; labelPlotColors[2].label = {0, 0, 0, 255}; labelPlotColors[3].background = {16, 16, 16, 40}; labelPlotColors[3].label = {0, 0, 0, 255}; labelPlotColors[4].background = {16, 16, 16, 40}; labelPlotColors[4].label = {0, 0, 0, 255}; labelPlotColors[5].background = {16, 16, 16, 40}; labelPlotColors[5].label = {0, 0, 0, 255}; labelPlotColors[6].background = {16, 16, 16, 40}; labelPlotColors[6].label = {0, 0, 0, 255}; labelPlotColors[7].background = {16, 16, 16, 40}; labelPlotColors[7].label = {0, 0, 0, 255}; labelPlotColors[8].background = {16, 16, 16, 40}; labelPlotColors[8].label = {0, 0, 0, 255}; labelPlotColors[9].background = {16, 16, 16, 40}; labelPlotColors[9].label = {0, 0, 0, 255}; labelPlotColors = { {config.get()->activeTextColor,{0, 0, 0, 255}}, {{255, 127, 0, 255},{255,255,255,255}}, {{31, 120, 180, 255},{255,255,255,255}}, {{210, 189, 26, 255},{255,255,255,255}}, {{227, 26, 28, 255},{255,255,255,255}}, {{80, 160, 44, 255},{255,255,255,255}}, {{106, 61, 154, 255},{255,255,255,255}}, {{177, 89, 40, 255},{255,255,255,255}}, {{9, 152, 146, 255},{255,255,255,255}}, {{227, 26, 150, 255},{255,255,255,255}} }; colors.resize(numChannels); //Setup the default colors if( numChannels >= 1 ) colors[0] = ofColor(255,0,0); //red if( numChannels >= 2 ) colors[1] = ofColor(0,255,0); //green if( numChannels >= 3 ) colors[2] = ofColor(0,0,255); //blue if( numChannels >= 4 ) colors[3] = ofColor(255,255,0); //yellow if( numChannels >= 5 ) colors[4] = ofColor(255,0,255); //purple if( numChannels >= 6 ) colors[5] = ofColor(255,255,255); //white //Randomize the remaining colors for(unsigned int n=6; n<numChannels; n++){ colors[n][0] = ofRandom(100,255); colors[n][1] = ofRandom(100,255); colors[n][2] = ofRandom(100,255); } int i=0; for(auto &c:colors) { c=labelPlotColors[i].background; i++; } return true; } void ofxGrtTimeseriesPlot::setAxisTitle(const std::string x, const std::string y) { xAxisInfo = x; yAxisInfo = y; } bool ofxGrtTimeseriesPlot::reset(){ std::unique_lock<std::mutex> lock( mtx ); if( !initialized ) return false; if( !lockRanges ){ globalMin = std::numeric_limits<float>::max(); globalMax = -std::numeric_limits<float>::max(); for(size_t i=0; i<channelRanges.size(); i++){ channelRanges[i].first = globalMin; channelRanges[i].second = globalMax; } } //Clear the buffer dataBuffer.setAllValues(vector<float>(numChannels,-1)); highlightBuffer.setAllValues(0); labelBuffer.setAllValues(""); return true; } bool ofxGrtTimeseriesPlot::setRanges( const float globalMin, const float globalMax, const vector<labelPlotColor> labelPlotColors, const bool lockRanges, const bool linkRanges, const bool dynamicScale ){ std::unique_lock<std::mutex> lock( mtx ); if( globalMin == globalMax ){ return false; } this->globalMin = globalMin; this->globalMax = globalMax; this->lockRanges = lockRanges; this->linkRanges = linkRanges; this->dynamicScale = dynamicScale; for(size_t i=0; i<channelRanges.size(); i++){ channelRanges[i].first = globalMin; channelRanges[i].second = globalMax; } if(labelPlotColors.size()>0) this->labelPlotColors = labelPlotColors; return true; } bool ofxGrtTimeseriesPlot::setRanges( const float globalMin, const float globalMax, const bool lockRanges, const bool linkRanges, const bool dynamicScale ){ std::unique_lock<std::mutex> lock( mtx ); if( globalMin == globalMax ){ return false; } this->globalMin = globalMin; this->globalMax = globalMax; this->lockRanges = lockRanges; this->linkRanges = linkRanges; this->dynamicScale = dynamicScale; for(size_t i=0; i<channelRanges.size(); i++){ channelRanges[i].first = globalMin; channelRanges[i].second = globalMax; } return true; } bool ofxGrtTimeseriesPlot::setRanges( const vector< GRT::MinMax > &ranges, const vector<labelPlotColor> labelPlotColors, const bool lockRanges, const bool linkRanges, const bool dynamicScale ){ std::unique_lock<std::mutex> lock( mtx ); if( ranges.size() != channelRanges.size() ){ return false; } this->lockRanges = lockRanges; this->linkRanges = linkRanges; this->dynamicScale = dynamicScale; globalMin = std::numeric_limits<float>::max(); globalMax = -std::numeric_limits<float>::max(); for(size_t i=0; i<channelRanges.size(); i++){ channelRanges[i].first = ranges[i].minValue; channelRanges[i].second = ranges[i].maxValue; if( channelRanges[i].first < globalMin ){ globalMin = channelRanges[i].first; } else if( channelRanges[i].second > globalMax ){ globalMax = channelRanges[i].second; } } if(labelPlotColors.size()>0) this->labelPlotColors = labelPlotColors; return true; } bool ofxGrtTimeseriesPlot::setRanges( const vector< GRT::MinMax > &ranges, const bool lockRanges, const bool linkRanges, const bool dynamicScale ){ std::unique_lock<std::mutex> lock( mtx ); if( ranges.size() != channelRanges.size() ){ return false; } this->lockRanges = lockRanges; this->linkRanges = linkRanges; this->dynamicScale = dynamicScale; globalMin = std::numeric_limits<float>::max(); globalMax = -std::numeric_limits<float>::max(); for(size_t i=0; i<channelRanges.size(); i++){ channelRanges[i].first = ranges[i].minValue; channelRanges[i].second = ranges[i].maxValue; if( channelRanges[i].first < globalMin ){ globalMin = channelRanges[i].first; } else if( channelRanges[i].second > globalMax ){ globalMax = channelRanges[i].second; } } return true; } bool ofxGrtTimeseriesPlot::setData( const vector<float> &data ){ std::unique_lock<std::mutex> lock( mtx ); const unsigned int M = (unsigned int)data.size(); if( numChannels != 1 ) return false; if( M != timeseriesLength ) return false; dataBuffer.reset(); highlightBuffer.reset(); labelBuffer.reset(); if( !lockRanges ){ globalMin = std::numeric_limits<float>::max(); globalMax = -std::numeric_limits<float>::max(); for(size_t i=0; i<channelRanges.size(); i++){ channelRanges[i].first = globalMin; channelRanges[i].second = globalMax; } } for(size_t i=0; i<M; i++){ dataBuffer(i)[0] = data[i]; //Check the min and max values if( !lockRanges ){ //Update the global min/max if( data[i] < globalMin ){ globalMin = data[i]; } else if( data[i] > globalMax ){ globalMax = data[i]; } //Update the channel min/max for(size_t j=0; j<channelRanges.size(); j++){ if( data[i] < channelRanges[j].first ){ channelRanges[j].first = data[i]; } else if( data[i] > channelRanges[j].second ){ channelRanges[j].second = data[i]; } } } } return true; } bool ofxGrtTimeseriesPlot::setData( const vector<double> &data ){ std::unique_lock<std::mutex> lock( mtx ); const unsigned int M = (unsigned int)data.size(); if( numChannels != 1 ) return false; if( M != timeseriesLength ) return false; dataBuffer.reset(); highlightBuffer.reset(); labelBuffer.reset(); if( !lockRanges ){ globalMin = std::numeric_limits<double>::max(); globalMax = -std::numeric_limits<double>::max(); for(size_t i=0; i<channelRanges.size(); i++){ channelRanges[i].first = globalMin; channelRanges[i].second = globalMax; } } for(unsigned int i=0; i<M; i++){ dataBuffer(i)[0] = data[i]; highlightBuffer[i] = 0; //Check the min and max values if( !lockRanges ){ //Update the global min/max if( data[i] < globalMin ){ globalMin = data[i]; } else if( data[i] > globalMax ){ globalMax = data[i]; } //Update the channel min/max for(size_t j=0; j<channelRanges.size(); j++){ if( data[i] < channelRanges[j].first ){ channelRanges[j].first = data[i]; } else if( data[i] > channelRanges[j].second ){ channelRanges[j].second = data[i]; } } } } return true; } /* bool ofxGrtTimeseriesPlot::setData( const vector< vector<float> > &data, const bool rowsAreChannels ){ std::unique_lock<std::mutex> lock( mtx ); if( rowsAreChannels ){ //The outer vector (rows) should contain the channel data //The inner vector (cols) should contain the timeseries data for channel n const unsigned int N = (unsigned int)data.size(); if( N != numChannels ) return false; dataBuffer.reset(); if( !lockRanges ){ globalMin = std::numeric_limits<float>::max(); globalMax = -std::numeric_limits<float>::max(); for(size_t i=0; i<channelRanges.size(); i++){ channelRanges[i].first = globalMin; channelRanges[i].second = globalMax; } } for(unsigned int i=0; i<N; i++){ if( data[i].size() != timeseriesLength ){ return false; } for(unsigned int j=0; j<timeseriesLength; j++){ dataBuffer(j)[i] = data[i][j]; //Check the min and max values if( !lockRanges ){ //Update the global min/max if( data[i][j] < globalMin ){ globalMin = data[i][j]; } else if( data[i][j] > globalMax ){ globalMax = data[i][j]; } //Update the channel min/max if( data[i][j] < channelRanges[i].first ){ channelRanges[i].first = data[i][j]; } else if( data[i][j] > channelRanges[i].second ){ channelRanges[i].second = data[i][j]; } } } } }else{ } return true; */ bool ofxGrtTimeseriesPlot::setData( const vector< vector<float> > &data, const bool rowsAreChannels ){ std::unique_lock<std::mutex> lock( mtx ); const unsigned int M = (unsigned int)data.size(); dataBuffer.reset(); highlightBuffer.reset(); labelBuffer.reset(); if( !lockRanges ){ globalMin = std::numeric_limits<float>::max(); globalMax = -std::numeric_limits<float>::max(); const size_t numChannels = channelRanges.size(); for(size_t i=0; i<numChannels; i++){ channelRanges[i].first = globalMin; channelRanges[i].second = globalMax; } } if( rowsAreChannels ){ //The outer vector (rows) should contain the channel data //The inner vector (cols) should contain the timeseries data for channel n const size_t numRows = data.size(); if( numRows != numChannels ) return false; for(size_t i=0; i<numRows; i++){ if( data[i].size() != timeseriesLength ){ return false; } for(unsigned int j=0; j<timeseriesLength; j++){ dataBuffer(j)[i] = data[i][j]; //Check the min and max values if( !lockRanges ){ //Update the global min/max if( data[i][j] < globalMin ){ globalMin = data[i][j]; } else if( data[i][j] > globalMax ){ globalMax = data[i][j]; } //Update the channel min/max if( data[i][j] < channelRanges[i].first ){ channelRanges[i].first = data[i][j]; } else if( data[i][j] > channelRanges[i].second ){ channelRanges[i].second = data[i][j]; } } } } return true; }else{ //The outer vector (rows) should contain the timeseries data for channel n //The inner vector (cols) should contain the channel data const size_t numRows = data.size(); if( numRows != timeseriesLength ) return false; for(size_t i=0; i<numRows; i++){ if( data[i].size() != numChannels ){ return false; } for(size_t j=0; j<numChannels; j++){ dataBuffer(i)[j] = data[i][j]; highlightBuffer[i] = 0; //Check the min and max values if( !lockRanges ){ //Update the global min/max if( data[i][j] < globalMin ){ globalMin = data[i][j]; } else if( data[i][j] > globalMax ){ globalMax = data[i][j]; } //Update the channel min/max if( data[i][j] < channelRanges[j].first ){ channelRanges[j].first = data[i][j]; } else if( data[i][j] > channelRanges[j].second ){ channelRanges[j].second = data[i][j]; } } } } return true; } return false; } bool ofxGrtTimeseriesPlot::setData( const Matrix<float> &data ){ std::unique_lock<std::mutex> lock( mtx ); const unsigned int M = data.getNumRows(); const unsigned int N = data.getNumCols(); if( N != numChannels ){ errorLog << "setData( const MatrixFloat &data ) - The number of dimensions in the data does not match the number of dimensions in the graph!" << endl; return false; } dataBuffer.reset(); highlightBuffer.reset(); labelBuffer.reset(); if( !lockRanges ){ globalMin = std::numeric_limits<float>::max(); globalMax = -std::numeric_limits<float>::max(); for(size_t i=0; i<channelRanges.size(); i++){ channelRanges[i].first = globalMin; channelRanges[i].second = globalMax; } } for(unsigned int i=0; i<M; i++){ for(unsigned int j=0; j<numChannels; j++){ dataBuffer(i)[j] = data[i][j]; highlightBuffer[i] = 0; //Check the min and max values if( !lockRanges ){ //Update the global min/max if( data[i][j] < globalMin ){ globalMin = data[i][j]; } else if( data[i][j] > globalMax ){ globalMax = data[i][j]; } //Update the channel min/max if( data[i][j] < channelRanges[j].first ){ channelRanges[j].first = data[i][j]; } else if( data[i][j] > channelRanges[j].second ){ channelRanges[j].second = data[i][j]; } } } } return true; } bool ofxGrtTimeseriesPlot::setData( const Matrix<double> &data ){ std::unique_lock<std::mutex> lock( mtx ); const unsigned int M = data.getNumRows(); const unsigned int N = data.getNumCols(); if( N != numChannels ){ errorLog << "setData( const MatrixDouble &data ) - The number of dimensions in the data does not match the number of dimensions in the graph!" << endl; return false; } dataBuffer.reset(); highlightBuffer.reset(); labelBuffer.reset(); if( !lockRanges ){ globalMin = std::numeric_limits<double>::max(); globalMax = -std::numeric_limits<double>::max(); for(size_t i=0; i<channelRanges.size(); i++){ channelRanges[i].first = globalMin; channelRanges[i].second = globalMax; } } for(unsigned int i=0; i<M; i++){ for(unsigned int j=0; j<numChannels; j++){ dataBuffer(i)[j] = data[i][j]; highlightBuffer[i] = 0; //Check the min and max values if( !lockRanges ){ //Update the global min/max if( data[i][j] < globalMin ){ globalMin = data[i][j]; } else if( data[i][j] > globalMax ){ globalMax = data[i][j]; } //Update the channel min/max if( data[i][j] < channelRanges[j].first ){ channelRanges[j].first = data[i][j]; } else if( data[i][j] > channelRanges[j].second ){ channelRanges[j].second = data[i][j]; } } } } return true; } bool ofxGrtTimeseriesPlot::setChannelVisible(const int idx, bool visible) { try{ channelVisible.at(idx) = visible; return true; }catch(const std::exception& e) { std::cout << " a standard exception was caught, with message '" << e.what() << "'\n"; return false; } } bool ofxGrtTimeseriesPlot::setNamesForChannels(const vector<std::string> names) { if(names.size()==channelNames.size()) { channelNames=names; return true; } return false; } vector< std::string > ofxGrtTimeseriesPlot::getChannelNames() { return channelNames; } bool ofxGrtTimeseriesPlot::update(){ std::unique_lock<std::mutex> lock( mtx ); //If the buffer has not been initialised then return false, otherwise update the buffer if( !initialized ) return false; //Repeat the previos value dataBuffer.push_back( dataBuffer[timeseriesLength-1] ); highlightBuffer.push_back( highlightBuffer[timeseriesLength - 1] ); labelBuffer.push_back( labelBuffer[timeseriesLength - 1] ); return true; } bool ofxGrtTimeseriesPlot::update( const vector<float> &data, bool highlight, std::string label ){ std::unique_lock<std::mutex> lock( mtx ); const unsigned int N = data.size(); //If the buffer has not been initialised then return false, otherwise update the buffer if( !initialized || N != numChannels ) return false; //Add the new value to the buffer dataBuffer.push_back( data ); highlightBuffer.push_back( highlight ); labelBuffer.push_back( label ); //Check the min and max values if( !lockRanges ){ for(unsigned int j=0; j<channelRanges.size(); j++){ //Update the global min/max if( data[j] < globalMin ){ globalMin = data[j]; } else if( data[j] > globalMax ){ globalMax = data[j]; } //Update the channel min/max if( data[j] < channelRanges[j].first ){ channelRanges[j].first = data[j]; } else if( data[j] > channelRanges[j].second ){ channelRanges[j].second = data[j]; } } } return true; } bool ofxGrtTimeseriesPlot::update( const vector<double> &data, bool highlight, std::string label ){ const size_t N = data.size(); vector<float> tmp(N); for(size_t i=0; i<N; i++){ tmp[i] = data[i]; } return update( tmp, highlight, label ); } bool ofxGrtTimeseriesPlot::update( const vector<float> &data, std::string label ) { std::unique_lock<std::mutex> lock( mtx ); const unsigned int N = data.size(); //If the buffer has not been initialised then return false, otherwise update the buffer if( !initialized || N != numChannels ) return false; //Add the new value to the buffer dataBuffer.push_back( data ); highlightBuffer.push_back( false ); labelBuffer.push_back( label ); //Check the min and max values if( !lockRanges ){ for(unsigned int j=0; j<channelRanges.size(); j++){ //Update the global min/max if( data[j] < globalMin ){ globalMin = data[j]; } else if( data[j] > globalMax ){ globalMax = data[j]; } //Update the channel min/max if( data[j] < channelRanges[j].first ){ channelRanges[j].first = data[j]; } else if( data[j] > channelRanges[j].second ){ channelRanges[j].second = data[j]; } } } return true; } bool ofxGrtTimeseriesPlot::update( const vector<double> &data, std::string label ) { const size_t N = data.size(); vector<float> tmp(N); for(size_t i=0; i<N; i++){ tmp[i] = data[i]; } return update( tmp, label ); } bool ofxGrtTimeseriesPlot::draw( int x, int y, int w, int h ){ std::unique_lock<std::mutex> lock( mtx ); if( !initialized ) return false; float minY = 0; float maxY = 0; if( dynamicScale ){ globalMin = std::numeric_limits<double>::max(); globalMax = -std::numeric_limits<double>::max(); for(size_t i=0; i<channelRanges.size(); i++){ channelRanges[i].first = globalMin; channelRanges[i].second = globalMax; } for(unsigned int i=0; i<timeseriesLength; i++){ for(unsigned int j=0; j<numChannels; j++){ //Update the global min/max if( dataBuffer[i][j] < globalMin ){ globalMin = dataBuffer[i][j]; } else if( dataBuffer[i][j] > globalMax ){ globalMax = dataBuffer[i][j]; } //Update the channel min/max if( dataBuffer[i][j] < channelRanges[j].first ){ channelRanges[j].first = dataBuffer[i][j]; } else if( dataBuffer[i][j] > channelRanges[j].second ){ channelRanges[j].second = dataBuffer[i][j]; } } } //Add a small percentage to the min/max values so the plot sits nicely in the graph for(unsigned int j=0; j<numChannels; j++){ float range = channelRanges[j].first - channelRanges[j].second; if( range != 0 ){ range = range * 0.1; channelRanges[j].first -= range; channelRanges[j].second += range; } } } //Bad things happen if the min and max values are the NAN or the same (as we can't scale the plots correctly) //So add a small value to the max if needed if( grt_isnan(globalMin) || grt_isinf(globalMin) ){ globalMin = 0; } if( grt_isnan(globalMax) || grt_isinf(globalMax) ){ globalMax = 1; } if( globalMin == globalMax ){ globalMax += 1.0e-10; } if( !linkRanges ){ for(size_t i=0; i<channelRanges.size(); i++){ if( grt_isnan(channelRanges[i].first) || grt_isinf(channelRanges[i].first) ){ channelRanges[i].first = 0; } if( grt_isnan(channelRanges[i].second) || grt_isinf(channelRanges[i].second) ){ channelRanges[i].second = 0; } if( channelRanges[i].first == channelRanges[i].second ){ channelRanges[i].second += 1.0e-10; } } } if (!insetPlotByInfoMarginX) { x -= config->info_margin; w += config->info_margin; } if (!insetPlotByInfoMarginY) { y -= config->info_margin; h += config->info_margin; } ofPushMatrix(); ofEnableAlphaBlending(); ofTranslate(x, y); //Draw the background ofFill(); ofSetColor(backgroundColor); ofDrawRectangle(config->info_margin,0,w-config->info_margin,h-config->info_margin); //Draw the grid if required if( drawGrid ){ ofSetColor(gridColor); unsigned int numVLines = 20; unsigned int numHLines = 10; //Draw the horizontal lines for(unsigned int i=0; i<=numHLines; i++){ float xStart = config->info_margin; float xEnd = w; float yStart = ofMap(i,0,numHLines,0,h-config->info_margin); float yEnd = yStart; ofDrawLine(xStart,yStart,xEnd,yEnd); } //Draw the vertical lines for(unsigned int i=0; i<=numVLines; i++){ float xStart = ofMap(i,0,numVLines,config->info_margin,w); float xEnd = xStart; float yStart = 0; float yEnd = h-config->info_margin; ofDrawLine(xStart,yStart,xEnd,yEnd); } } //Draw the axis lines ofSetColor(axisColor); ofDrawLine(-5+config->info_margin,h-config->info_margin,w+5,h-config->info_margin); //X Axis ofDrawLine(0+config->info_margin,-5,0+config->info_margin,h+5-config->info_margin); //Y Axis ofSetColor(textColor[0],textColor[1],textColor[2]); //Draw axis info if(font) { const float posX = -5+config->info_margin; const float posY = h; font->drawString(xAxisInfo, posX, posY); ofPushMatrix(); { ofRotateZ(-90.0f); const float posY = -float(h)+font->stringWidth(yAxisInfo)-config->info_margin; const float posX = font->stringHeight(yAxisInfo); font->drawString(yAxisInfo, posY, posX); } ofPopMatrix(); } //draw axis ticks { ofSetColor(axisColor); unsigned int numVTicks = 20; unsigned int numHTicks = 10; //Draw the horizontal lines for(unsigned int i=0; i<=numHTicks; i++){ float xStart = -config->axisTicksSize+config->info_margin; float xEnd = config->axisTicksSize+config->info_margin; float yStart = ofMap(i,0,numHTicks,0,h-config->info_margin); float yEnd = yStart; ofDrawLine(xStart,yStart,xEnd,yEnd); } //Draw the vertical lines for(unsigned int i=0; i<=numVTicks; i++){ float xStart = ofMap(i,0,numVTicks,config->info_margin,w); float xEnd = xStart; float yStart = h-config->info_margin; float yEnd = h+5-config->info_margin; ofDrawLine(xStart,yStart,xEnd,yEnd); } } //Draw the timeseries if( globalMin != globalMax ){ float xPos = config->info_margin; float xStep = (w-config->info_margin) / (float)timeseriesLength; ofSetColor(32); for(unsigned int i=0; i<highlightBuffer.getNumValuesInBuffer(); i++){ if (highlightBuffer[i]) ofDrawRectangle( xPos, 0, xStep, h-config->info_margin ); xPos += xStep; } std::string label = ""; xPos = config->info_margin; ofSetColor(255); ofFill(); for(unsigned int i=0; i<highlightBuffer.getNumValuesInBuffer(); i++){ if (highlightBuffer[i]) { if (labelBuffer[i] != label) { ofDrawBitmapString(labelBuffer[i], xPos, h-config->info_margin); label = labelBuffer[i]; } } else { label = ""; } xPos += xStep; } unsigned int index = 0; unsigned int channelIndex = 0; ofNoFill(); for(unsigned int n=0; n<numChannels; n++){ xPos = config->info_margin; index = 0; channelIndex = drawOrderInverted ? numChannels-1-n : n; if( channelVisible[ channelIndex ] ){ minY = linkRanges ? globalMin : channelRanges[ channelIndex ].first; maxY = linkRanges ? globalMax : channelRanges[ channelIndex ].second; ofSetColor( colors[ channelIndex ][0],colors[ channelIndex ][1],colors[ channelIndex ][2] ); ofBeginShape(); for(unsigned int i=0; i<timeseriesLength; i++){ ofVertex( xPos, ofMap(dataBuffer[i][ channelIndex ], minY, maxY, h-config->info_margin, 0, constrainValuesToGraph) ); xPos += xStep; } ofEndShape(false); } } } //Disabled alpha blending before we draw any text ofDisableAlphaBlending(); //Only draw the text if the font has been loaded if( font ){ if( !font->isLoaded() ) return false; if( drawInfoText ){ ofRectangle bounds = font->getStringBoundingBox(plotTitle, 0, 0); int textX = config->info_margin; int textY = -config->titleTextSpacer; // int textSpacer = bounds.height + 5; if( plotTitle != "" && drawPlotTitle ){ ofSetColor(textColor); font->drawString( plotTitle, textX, textY ); // } textY += font->getLineHeight(); if( drawPlotValues ){ std::stringstream info; info.precision( 2 ); for(unsigned int n=0; n<numChannels; n++){ if( channelVisible[n] ){ minY = linkRanges ? globalMin : channelRanges[n].first; maxY = linkRanges ? globalMax : channelRanges[n].second; ofSetColor(colors[n][0],colors[n][1],colors[n][2]); info.str(""); info << "[" << n+1 << "]: " << channelNames[n] << " "; info << dataBuffer[timeseriesLength-1][n] << " [" << minY << " " << maxY << "]" << endl; bounds = font->getStringBoundingBox(info.str(), 0, 0); font->drawString(info.str(),textX,textY); textY += bounds.height + 5; } } } } } ofPopMatrix(); return true; } bool ofxGrtTimeseriesPlot::drawLabeledGraph( const unsigned int x, const unsigned int y, const unsigned int w, const unsigned int h, const int chanNum){ std::unique_lock<std::mutex> lock( mtx ); if( !initialized ) return false; float minY = 0; float maxY = 0; if( dynamicScale ){ globalMin = std::numeric_limits<double>::max(); globalMax = -std::numeric_limits<double>::max(); for(size_t i=0; i<channelRanges.size(); i++){ channelRanges[i].first = globalMin; channelRanges[i].second = globalMax; } for(unsigned int i=0; i<timeseriesLength; i++){ for(unsigned int j=0; j<numChannels; j++){ //Update the global min/max if( dataBuffer[i][j] < globalMin ){ globalMin = dataBuffer[i][j]; } else if( dataBuffer[i][j] > globalMax ){ globalMax = dataBuffer[i][j]; } //Update the channel min/max if( dataBuffer[i][j] < channelRanges[j].first ){ channelRanges[j].first = dataBuffer[i][j]; } else if( dataBuffer[i][j] > channelRanges[j].second ){ channelRanges[j].second = dataBuffer[i][j]; } } } //Add a small percentage to the min/max values so the plot sits nicely in the graph for(unsigned int j=0; j<numChannels; j++){ float range = channelRanges[j].first - channelRanges[j].second; if( range != 0 ){ range = range * 0.1; channelRanges[j].first -= range; channelRanges[j].second += range; } } } //Bad things happen if the min and max values are the NAN or the same (as we can't scale the plots correctly) //So add a small value to the max if needed if( grt_isnan(globalMin) || grt_isinf(globalMin) ){ globalMin = 0; } if( grt_isnan(globalMax) || grt_isinf(globalMax) ){ globalMax = 1; } if( globalMin == globalMax ){ globalMax += 1.0e-10; } if( !linkRanges ){ for(size_t i=0; i<channelRanges.size(); i++){ if( grt_isnan(channelRanges[i].first) || grt_isinf(channelRanges[i].first) ){ channelRanges[i].first = 0; } if( grt_isnan(channelRanges[i].second) || grt_isinf(channelRanges[i].second) ){ channelRanges[i].second = 0; } if( channelRanges[i].first == channelRanges[i].second ){ channelRanges[i].second += 1.0e-10; } } } ofPushMatrix(); ofEnableAlphaBlending(); ofTranslate(x, y); //Draw the background ofFill(); ofSetColor(backgroundColor[0],backgroundColor[1],backgroundColor[2]); ofDrawRectangle(config->info_margin,config->info_margin,w-config->info_margin,h-config->info_margin*2); //Draw the grid if required if( drawGrid ){ ofSetColor(gridColor[0],gridColor[1],gridColor[2],gridColor[3]); unsigned int numVLines = 20; unsigned int numHLines = 10; //Draw the horizontal lines for(unsigned int i=0; i<=numChannels; i++){ float xStart = config->info_margin; float xEnd = w; float yStart = ofMap(i,0,numChannels,config->info_margin,h-config->info_margin); float yEnd = yStart; ofDrawLine(xStart,yStart,xEnd,yEnd); } //Draw the vertical lines for(unsigned int i=0; i<=numVLines; i++){ float xStart = ofMap(i,0,numVLines,config->info_margin,w); float xEnd = xStart; float yStart = config->info_margin; float yEnd = h-config->info_margin; ofDrawLine(xStart,yStart,xEnd,yEnd); } } //Draw the axis lines ofSetColor(axisColor); ofDrawLine(-5+config->info_margin,h-config->info_margin,w+5,h-config->info_margin); //X Axis ofDrawLine(0+config->info_margin,-5+config->info_margin,0+config->info_margin,h+5-config->info_margin); //Y Axis ofSetColor(textColor); //Draw axis info if(font) { const float posX = -5+config->info_margin; const float posY = h; font->drawString(xAxisInfo, posX, posY); ofPushMatrix(); { const float posY = -float(h)+font->stringWidth(yAxisInfo)+config->info_margin/2; const float posX = font->stringHeight(yAxisInfo); ofRotateZ(-90.0f); font->drawString(yAxisInfo, posY, posX); } ofPopMatrix(); } //draw axis ticks { ofSetColor(gridColor); unsigned int numVTicks = 20; unsigned int numHTicks = 1; //Draw the horizontal lines for(unsigned int i=0; i<=numHTicks; i++){ float xStart = -config->axisTicksSize+config->info_margin; float xEnd = 0+config->info_margin; float yStart = ofMap(i,0,numHTicks,config->info_margin,h-config->info_margin); float yEnd = yStart; ofDrawLine(xStart,yStart,xEnd,yEnd); } //Draw the vertical lines for(unsigned int i=0; i<=numVTicks; i++){ float xStart = ofMap(i,0,numVTicks,config->info_margin,w); float xEnd = xStart; float yStart = h-config->info_margin; float yEnd = h+config->axisTicksSize-config->info_margin; ofDrawLine(xStart,yStart,xEnd,yEnd); } } //Draw the timeseries if( globalMin != globalMax ){ float xPos = config->info_margin; const float yPos = config->info_margin; const float xStep = (w-config->info_margin) / (float)timeseriesLength; ofSetColor(32); vector<string> labels; vector<ofPoint> positions; vector<ofColor> colors; for(unsigned int i=0; i<labelBuffer.getNumValuesInBuffer(); i++) { const int colorIdx = dataBuffer[i][chanNum]; if(colorIdx<0) { ofSetColor(0,0,0,0); ofDrawRectangle( xPos, yPos, xStep, h-config->info_margin*2 ); } else { ofSetColor(labelPlotColors[colorIdx].background); ofDrawRectangle( xPos, yPos, xStep, h-config->info_margin*2 ); const int prevIdx = max<int>(0,i-1); if(dataBuffer[i][chanNum]!=dataBuffer[prevIdx][chanNum] || i==0) { labels.push_back(to_string((int)dataBuffer[i][chanNum])); positions.push_back(ofPoint(xPos+2, config->info_margin+(h-config->info_margin*2+font->stringHeight(to_string((int)dataBuffer[i][chanNum])))*0.5)); colors.push_back(labelPlotColors[dataBuffer[i][chanNum]].label); } } xPos += xStep; } for(int i=0;i<labels.size();i++) { ofSetColor( colors[i] ); if(font) font->drawString(labels[i], positions[i].x,positions[i].y); else ofDrawBitmapString(labels[i], positions[i].x,positions[i].y); } } //Only draw the text if the font has been loaded if( font ){ if( !font->isLoaded() ) return false; if( drawInfoText ){ ofRectangle bounds = font->getStringBoundingBox(plotTitle, 0, 0); int textX = config->info_margin; int textY = bounds.height; int textSpacer = bounds.height + 5; if( plotTitle != "" && drawPlotTitle ){ ofSetColor(textColor[0],textColor[1],textColor[2]); font->drawString( plotTitle, textX, textY ); textY += textSpacer; } if( drawPlotValues ){ std::stringstream info; info.precision( 2 ); for(unsigned int n=0; n<numChannels; n++){ if( channelVisible[n] ){ minY = linkRanges ? globalMin : channelRanges[n].first; maxY = linkRanges ? globalMax : channelRanges[n].second; ofSetColor(colors[n][0],colors[n][1],colors[n][2]); info.str(""); info << "[" << n+1 << "]: " << channelNames[n] << " "; info << dataBuffer[timeseriesLength-1][n] << " [" << minY << " " << maxY << "]" << endl; bounds = font->getStringBoundingBox(info.str(), 0, 0); font->drawString(info.str(),textX,textY); textY += bounds.height + 5; } } } } } ofPopMatrix(); return true; }
33.962687
202
0.558607
[ "vector" ]
3b8887ab80a287268a34c48aff2a901e32e50713
591
hpp
C++
include/eve/arch/cpu/detection.hpp
orao/eve
a8bdc6a9cab06d905e8749354cde63776ab76846
[ "MIT" ]
null
null
null
include/eve/arch/cpu/detection.hpp
orao/eve
a8bdc6a9cab06d905e8749354cde63776ab76846
[ "MIT" ]
null
null
null
include/eve/arch/cpu/detection.hpp
orao/eve
a8bdc6a9cab06d905e8749354cde63776ab76846
[ "MIT" ]
null
null
null
//================================================================================================== /** EVE - Expressive Vector Engine Copyright : EVE Contributors & Maintainers SPDX-License-Identifier: MIT **/ //================================================================================================== #pragma once #include <eve/arch/cpu/tags.hpp> namespace eve { //================================================================================================ // Runtime detection of CPU support inline bool is_supported(cpu_ const &) noexcept { return true; } }
32.833333
100
0.350254
[ "vector" ]
3b8a20c6b567cdea0b28de282e86d9971fc713f1
6,464
cc
C++
power_manager/tools/dump_intel_rapl_consumption.cc
kalyankondapally/chromiumos-platform2
5e5337009a65b1c9aa9e0ea565f567438217e91f
[ "BSD-3-Clause" ]
null
null
null
power_manager/tools/dump_intel_rapl_consumption.cc
kalyankondapally/chromiumos-platform2
5e5337009a65b1c9aa9e0ea565f567438217e91f
[ "BSD-3-Clause" ]
null
null
null
power_manager/tools/dump_intel_rapl_consumption.cc
kalyankondapally/chromiumos-platform2
5e5337009a65b1c9aa9e0ea565f567438217e91f
[ "BSD-3-Clause" ]
1
2020-11-04T22:31:45.000Z
2020-11-04T22:31:45.000Z
// Copyright 2017 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This utility reports power consumption for certain Intel SoCs, calculated by // averaging the running energy consumption counter provided by Linux powercap // driver subset of Intel RAPL (Running Average Power Limit) energy report. // RAPL provides info per Power Domain: DRAM and PKG. PKG refers to the // processor die, and includes the PP0 (cores) and PP1 (graphics) subdomains. // // MSRs reference can be found in "Sec. 14.9 Platform Specific Power Management // Support" of the "Intel 64 and IA-32 Architectures Software Developer’s // Manual Volume 3B: System Programming Guide, Part 2" [1]. // Info of Linux powercap driver can be reached in kernel documentation [2]. // // [1] // https://www.intel.com/content/www/us/en/architecture-and-technology/64-ia-32-architectures-software-developer-vol-3b-part-2-manual.html // [2] // https://github.com/torvalds/linux/blob/master/Documentation/power/powercap/powercap.rst #include <inttypes.h> #include <math.h> #include <base/files/file.h> #include <base/files/file_enumerator.h> #include <base/files/file_path.h> #include <base/files/file_util.h> #include <base/logging.h> #include <base/strings/string_util.h> #include <base/strings/stringprintf.h> #include <base/system/sys_info.h> #include <base/threading/platform_thread.h> #include <base/time/time.h> #include <brillo/flag_helper.h> #include <brillo/syslog_logging.h> #include "power_manager/common/util.h" namespace { // Path to the powercap driver sysfs interface, if it doesn't exist, // either the kernel is old w/o powercap driver, or it is not configured. constexpr const char kPowercapPath[] = "/sys/class/powercap"; // Cap of a maximal reasonable power in Watts constexpr const double kMaxWatts = 1e3; struct PowerDomain { base::FilePath file_path; std::string name; uint64_t max_energy; bool operator<(const PowerDomain& that) const { return file_path < that.file_path; } }; } // namespace int main(int argc, char** argv) { DEFINE_int32(interval_ms, 1000, "Interval to collect consumption (ms)."); DEFINE_bool(repeat, false, "Repeat forever."); DEFINE_bool(verbose, false, "Verbose logging."); brillo::FlagHelper::Init( argc, argv, "Print average power consumption per domain for Intel SoCs"); brillo::InitLog(brillo::kLogToStderr); // Kernel v3.13+ supports powercap, it also requires a proper configuration // enabling it; leave a verbose footprint of the kernel string, and examine // whether or not the system supports the powercap driver. if (FLAGS_verbose) { const base::SysInfo sys; printf("OS version: %s\n", sys.OperatingSystemVersion().c_str()); } base::FilePath powercap_file_path(kPowercapPath); PCHECK(base::PathExists(powercap_file_path)) << "No powercap driver sysfs interface, couldn't find " << powercap_file_path.value(); std::vector<PowerDomain> power_domains; std::string domain_name; // Probe the power domains and sub-domains base::FilePath powercap_path(kPowercapPath); base::FileEnumerator dirs(powercap_path, false, base::FileEnumerator::DIRECTORIES, FILE_PATH_LITERAL("intel-rapl:*")); for (base::FilePath dir = dirs.Next(); !dir.empty(); dir = dirs.Next()) { base::FilePath domain_file_path = dir.Append("name"); base::FilePath energy_file_path = dir.Append("energy_uj"); base::FilePath maxeng_file_path = dir.Append("max_energy_range_uj"); uint64_t max_energy_uj; if (!base::PathExists(domain_file_path)) { fprintf(stderr, "Unable to find %s\n", domain_file_path.value().c_str()); continue; } if (!base::PathExists(energy_file_path)) { fprintf(stderr, "Unable to find %s\n", energy_file_path.value().c_str()); continue; } if (!base::PathExists(maxeng_file_path)) { fprintf(stderr, "Unable to find %s\n", maxeng_file_path.value().c_str()); continue; } power_manager::util::ReadStringFile(domain_file_path, &domain_name); power_manager::util::ReadUint64File(maxeng_file_path, &max_energy_uj); power_domains.push_back({energy_file_path, domain_name, max_energy_uj}); if (FLAGS_verbose) printf("Found domain %-10s (max %" PRIu64 " uj) at %s\n", domain_name.c_str(), max_energy_uj, dir.value().c_str()); } PCHECK(!power_domains.empty()) << "No power domain found at " << powercap_file_path.value(); // As the enumeration above does not guarantee the order, transform the // paths in lexicographical order, make the collecting data in a style // of domain follows by sub-domain, it can be done by sorting. // e.g., package-0 psys core ... -> package-0 core ... psys sort(power_domains.begin(), power_domains.end()); for (const auto& domain : power_domains) printf("%10s ", domain.name.c_str()); printf(" (Note: Values in Watts)\n"); uint32_t num_domains = power_domains.size(); std::vector<uint64_t> energy_before(num_domains); std::vector<uint64_t> energy_after(num_domains); do { for (int i = 0; i < num_domains; ++i) power_manager::util::ReadUint64File(power_domains[i].file_path, &energy_before[i]); const base::TimeTicks ticks_before = base::TimeTicks::Now(); base::PlatformThread::Sleep( base::TimeDelta::FromMilliseconds(FLAGS_interval_ms)); for (int i = 0; i < num_domains; ++i) power_manager::util::ReadUint64File(power_domains[i].file_path, &energy_after[i]); const base::TimeDelta time_delta = base::TimeTicks::Now() - ticks_before; for (int i = 0; i < num_domains; ++i) { uint64_t energy_delta = (energy_after[i] >= energy_before[i]) ? energy_after[i] - energy_before[i] : power_domains[i].max_energy - energy_before[i] + energy_after[i]; double average_power = energy_delta / (time_delta.InSecondsF() * 1e6); // Skip enormous sample if the counter is reset during suspend-to-RAM if (average_power > kMaxWatts) { printf("%10s ", "skip"); continue; } printf("%10.6f ", average_power); } printf("\n"); } while (FLAGS_repeat); return 0; }
39.175758
138
0.683014
[ "vector", "transform" ]
3b8b5eec3bc11e89dd5c46b1175e5ddb83514ca2
4,019
cpp
C++
roborts_detection/apriltags_detection/apriltags_detection_node.cpp
XDRM-IRobot/RTS2019
5541377862330ba1905ec8f210059536430e83e8
[ "BSD-2-Clause" ]
2
2019-04-16T08:01:01.000Z
2019-07-21T12:02:35.000Z
roborts_detection/apriltags_detection/apriltags_detection_node.cpp
XDRM-IRobot/RTS2019
5541377862330ba1905ec8f210059536430e83e8
[ "BSD-2-Clause" ]
null
null
null
roborts_detection/apriltags_detection/apriltags_detection_node.cpp
XDRM-IRobot/RTS2019
5541377862330ba1905ec8f210059536430e83e8
[ "BSD-2-Clause" ]
3
2019-04-16T08:05:38.000Z
2020-05-15T13:32:16.000Z
#include <unistd.h> #include "apriltags_detection_node.h" namespace roborts_detection { TagsDetectionNode::TagsDetectionNode(): node_state_(roborts_common::IDLE), initialized_(false), detected_tag_(false), as_(nh_, "tag_detection_node_action", boost::bind(&TagsDetectionNode::ActionCB, this, _1), false) { if (Init().IsOK()) { initialized_ = true; node_state_ = roborts_common::IDLE; } else { ROS_ERROR("apriltags_detection_node initalized failed!"); node_state_ = roborts_common::FAILURE; } as_.start(); } ErrorInfo TagsDetectionNode::Init() { return ErrorInfo(ErrorCode::OK); } void TagsDetectionNode::ActionCB(const roborts_msgs::TagDetectionGoal::ConstPtr &data) { roborts_msgs::TagDetectionFeedback feedback; roborts_msgs::TagDetectionResult result; bool undetected_msg_published = false; if(!initialized_){ feedback.error_code = error_info_.error_code(); feedback.error_msg = error_info_.error_msg(); as_.publishFeedback(feedback); as_.setAborted(result, feedback.error_msg); ROS_INFO("Initialization Failed, Failed to execute action!"); return; } switch (data->command) { case 1: StartThread(); break; case 2: PauseThread(); break; case 3: StopThread(); break; default: break; } ros::Rate rate(100); while(ros::ok()) { if(as_.isPreemptRequested()) { as_.setPreempted(); return; } { std::lock_guard<std::mutex> guard(mutex_); feedback.enemy_pos.clear(); feedback.error_code = error_info_.error_code(); feedback.error_msg = error_info_.error_msg(); if (detected_tag_){ feedback.detected = true; for (int i = 0; i != targets_3d_.size(); ++i) { geometry_msgs::Point temp; temp.x = targets_3d_[i].x; temp.y = targets_3d_[i].y; temp.z = targets_3d_[i].z; feedback.enemy_pos.push_back(temp); } }else{ feedback.detected = false; } as_.publishFeedback(feedback); } rate.sleep(); } } void TagsDetectionNode::ExecuteLoop() { while(running_) { usleep(1); if (node_state_ == NodeState::RUNNING) { std::vector<cv::Point3f> targets_3d; ErrorInfo error_info = armor_detector_->DetectArmor(detected_tag_, targets_3d); { std::lock_guard<std::mutex> guard(mutex_); targets_3d_ = targets_3d; error_info_ = error_info; } } else if (node_state_ == NodeState::PAUSE) // 如果暂停 { std::unique_lock<std::mutex> lock(mutex_); condition_var_.wait(lock); // stop here } } } void TagsDetectionNode::StartThread() { ROS_INFO("Armor detection node started!"); running_ = true; armor_detector_->SetThreadState(true); if(node_state_ == NodeState::IDLE) { armor_detection_thread_ = std::thread(&TagsDetectionNode::ExecuteLoop, this); } node_state_ = NodeState::RUNNING; condition_var_.notify_one(); } void TagsDetectionNode::PauseThread() { ROS_INFO("Armor detection thread paused!"); node_state_ = NodeState::PAUSE; } void TagsDetectionNode::StopThread() { node_state_ = NodeState::IDLE; running_ = false; armor_detector_->SetThreadState(false); if (armor_detection_thread_.joinable()) { armor_detection_thread_.join(); } } TagsDetectionNode::~TagsDetectionNode() { StopThread(); } } //namespace roborts_detection void SignalHandler(int signal){ if(ros::isInitialized() && ros::isStarted() && ros::ok() && !ros::isShuttingDown()){ ros::shutdown(); } } int main(int argc, char **argv) { signal(SIGINT, SignalHandler); signal(SIGTERM,SignalHandler); ros::init(argc, argv, "apriltags_detection_node", ros::init_options::NoSigintHandler); roborts_detection::TagsDetectionNode armor_detection; ros::AsyncSpinner async_spinner(1); async_spinner.start(); ros::waitForShutdown(); armor_detection.StopThread(); return 0; }
25.27673
102
0.660363
[ "vector" ]
3b8f11dce5a8c4f798be3378f61bd2beef57af79
3,103
cpp
C++
src/external/boost/boost_1_68_0/libs/graph/example/adjacency_list.cpp
Bpowers4/turicreate
73dad213cc1c4f74337b905baea2b3a1e5a0266c
[ "BSD-3-Clause" ]
11,356
2017-12-08T19:42:32.000Z
2022-03-31T16:55:25.000Z
src/external/boost/boost_1_68_0/libs/graph/example/adjacency_list.cpp
Bpowers4/turicreate
73dad213cc1c4f74337b905baea2b3a1e5a0266c
[ "BSD-3-Clause" ]
2,402
2017-12-08T22:31:01.000Z
2022-03-28T19:25:52.000Z
src/external/boost/boost_1_68_0/libs/graph/example/adjacency_list.cpp
Bpowers4/turicreate
73dad213cc1c4f74337b905baea2b3a1e5a0266c
[ "BSD-3-Clause" ]
1,343
2017-12-08T19:47:19.000Z
2022-03-26T11:31:36.000Z
//======================================================================= // Copyright 1997, 1998, 1999, 2000 University of Notre Dame. // Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <boost/config.hpp> #include <iostream> #include <vector> #include <utility> #include <string> #include <boost/graph/adjacency_list.hpp> #include <boost/graph/graph_utility.hpp> #include <boost/property_map/property_map.hpp> /* Sample Output graph name: foo 0 --joe--> 1 1 --joe--> 0 --curly--> 2 --dick--> 3 2 --curly--> 1 --tom--> 4 3 --dick--> 1 --harry--> 4 4 --tom--> 2 --harry--> 3 (0,1) (1,2) (1,3) (2,4) (3,4) removing edge (1,3): 0 --joe--> 1 1 --joe--> 0 --curly--> 2 2 --curly--> 1 --tom--> 4 3 --harry--> 4 4 --tom--> 2 --harry--> 3 (0,1) (1,2) (2,4) (3,4) */ struct EdgeProperties { EdgeProperties(const std::string& n) : name(n) { } std::string name; }; struct VertexProperties { std::size_t index; boost::default_color_type color; }; int main(int , char* []) { using namespace boost; using namespace std; typedef adjacency_list<vecS, listS, undirectedS, VertexProperties, EdgeProperties> Graph; const int V = 5; Graph g(V); property_map<Graph, std::size_t VertexProperties::*>::type id = get(&VertexProperties::index, g); property_map<Graph, std::string EdgeProperties::*>::type name = get(&EdgeProperties::name, g); boost::graph_traits<Graph>::vertex_iterator vi, viend; int vnum = 0; for (boost::tie(vi,viend) = vertices(g); vi != viend; ++vi) id[*vi] = vnum++; add_edge(vertex(0, g), vertex(1, g), EdgeProperties("joe"), g); add_edge(vertex(1, g), vertex(2, g), EdgeProperties("curly"), g); add_edge(vertex(1, g), vertex(3, g), EdgeProperties("dick"), g); add_edge(vertex(2, g), vertex(4, g), EdgeProperties("tom"), g); add_edge(vertex(3, g), vertex(4, g), EdgeProperties("harry"), g); graph_traits<Graph>::vertex_iterator i, end; graph_traits<Graph>::out_edge_iterator ei, edge_end; for (boost::tie(i,end) = vertices(g); i != end; ++i) { cout << id[*i] << " "; for (boost::tie(ei,edge_end) = out_edges(*i, g); ei != edge_end; ++ei) cout << " --" << name[*ei] << "--> " << id[target(*ei, g)] << " "; cout << endl; } print_edges(g, id); cout << endl << "removing edge (1,3): " << endl; remove_edge(vertex(1, g), vertex(3, g), g); ei = out_edges(vertex(1, g), g).first; cout << "removing edge (" << id[source(*ei, g)] << "," << id[target(*ei, g)] << ")" << endl; remove_edge(ei, g); for(boost::tie(i,end) = vertices(g); i != end; ++i) { cout << id[*i] << " "; for (boost::tie(ei,edge_end) = out_edges(*i, g); ei != edge_end; ++ei) cout << " --" << name[*ei] << "--> " << id[target(*ei, g)] << " "; cout << endl; } print_edges(g, id); return 0; }
28.731481
74
0.56107
[ "vector" ]
3b9527ca2c4c105966bc5bb57fbed35c0f6b5508
12,334
cc
C++
src/attributes/WrepJSonAttributes.cc
dvuckovic/magics
1c99a6cd78448b498fe97d3abe2b60fab46ba1b0
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/attributes/WrepJSonAttributes.cc
dvuckovic/magics
1c99a6cd78448b498fe97d3abe2b60fab46ba1b0
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/attributes/WrepJSonAttributes.cc
dvuckovic/magics
1c99a6cd78448b498fe97d3abe2b60fab46ba1b0
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/****************************** LICENSE ******************************* * (C) Copyright 1996-2017 ECMWF. * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. * In applying this licence, ECMWF does not waive the privileges and immunities * granted to it by virtue of its status as an intergovernmental organisation nor * does it submit to any jurisdiction. ******************************* LICENSE *******************************/ /*! \\file WrepJSonAttributes.h \\brief Definition of WrepJSon Attributes class. This file is automatically generated. Do Not Edit! */ #include "WrepJSonAttributes.h" #include "MagicsParameter.h" #include "ParameterSettings.h" using namespace magics; WrepJSonAttributes::WrepJSonAttributes(): path_(ParameterManager::getString("wrepjson_input_filename")), param_info_(ParameterManager::getString("wrepjson_parameter_information")), title_(ParameterManager::getBool("wrepjson_title")), position_info_(ParameterManager::getBool("wrepjson_position_information")), product_info_(ParameterManager::getString("wrepjson_product_information")), family_(ParameterManager::getString("wrepjson_family")), key_(ParameterManager::getString("wrepjson_key")), plumes_(ParameterManager::getDouble("wrepjson_plumes_interval")), information_(ParameterManager::getBool("wrepjson_information")), keyword_(ParameterManager::getString("wrepjson_keyword")), station_name_(ParameterManager::getString("wrepjson_station_name")), param_(ParameterManager::getString("wrepjson_parameter")), param_scaling_factor_(ParameterManager::getDouble("wrepjson_parameter_scaling_factor")), param_offset_factor_(ParameterManager::getDouble("wrepjson_parameter_offset_factor")), clim_param_(ParameterManager::getString("wrepjson_clim_parameter")), clim_step_(ParameterManager::getInt("wrepjson_clim_step")), steps_(ParameterManager::getIntArray("wrepjson_steps")), percentile_(ParameterManager::getDouble("wrepjson_y_axis_percentile")), threshold_(ParameterManager::getDouble("wrepjson_y_axis_threshold")), y_max_threshold_(ParameterManager::getDouble("wrepjson_y_max_threshold")), y_percent_(ParameterManager::getDouble("wrepjson_y_percentage")), correction_(ParameterManager::getBool("wrepjson_temperature_correction")), missing_value_(ParameterManager::getDouble("wrepjson_missing_value")), ignore_keys_(ParameterManager::getStringArray("wrepjson_ignore_keys")), profile_quantile_(ParameterManager::getString("wrepjson_profile_quantile")), hodograph_grid_(ParameterManager::getBool("wrepjson_hodograph_grid")), hodograph_tephi_(ParameterManager::getBool("wrepjson_hodograph_tephi")), hodograph_member_(ParameterManager::getInt("wrepjson_hodograph_member")) { } WrepJSonAttributes::~WrepJSonAttributes() { } void WrepJSonAttributes::set(const std::map<string, string>& params) { vector<string> prefix(1); int i = 0; prefix[i++] = "wrepjson"; setAttribute(prefix, "wrepjson_input_filename", path_, params); setAttribute(prefix, "wrepjson_parameter_information", param_info_, params); setAttribute(prefix, "wrepjson_title", title_, params); setAttribute(prefix, "wrepjson_position_information", position_info_, params); setAttribute(prefix, "wrepjson_product_information", product_info_, params); setAttribute(prefix, "wrepjson_family", family_, params); setAttribute(prefix, "wrepjson_key", key_, params); setAttribute(prefix, "wrepjson_plumes_interval", plumes_, params); setAttribute(prefix, "wrepjson_information", information_, params); setAttribute(prefix, "wrepjson_keyword", keyword_, params); setAttribute(prefix, "wrepjson_station_name", station_name_, params); setAttribute(prefix, "wrepjson_parameter", param_, params); setAttribute(prefix, "wrepjson_parameter_scaling_factor", param_scaling_factor_, params); setAttribute(prefix, "wrepjson_parameter_offset_factor", param_offset_factor_, params); setAttribute(prefix, "wrepjson_clim_parameter", clim_param_, params); setAttribute(prefix, "wrepjson_clim_step", clim_step_, params); setAttribute(prefix, "wrepjson_steps", steps_, params); setAttribute(prefix, "wrepjson_y_axis_percentile", percentile_, params); setAttribute(prefix, "wrepjson_y_axis_threshold", threshold_, params); setAttribute(prefix, "wrepjson_y_max_threshold", y_max_threshold_, params); setAttribute(prefix, "wrepjson_y_percentage", y_percent_, params); setAttribute(prefix, "wrepjson_temperature_correction", correction_, params); setAttribute(prefix, "wrepjson_missing_value", missing_value_, params); setAttribute(prefix, "wrepjson_ignore_keys", ignore_keys_, params); setAttribute(prefix, "wrepjson_profile_quantile", profile_quantile_, params); setAttribute(prefix, "wrepjson_hodograph_grid", hodograph_grid_, params); setAttribute(prefix, "wrepjson_hodograph_tephi", hodograph_tephi_, params); setAttribute(prefix, "wrepjson_hodograph_member", hodograph_member_, params); } void WrepJSonAttributes::copy(const WrepJSonAttributes& other) { path_ = other.path_; param_info_ = other.param_info_; title_ = other.title_; position_info_ = other.position_info_; product_info_ = other.product_info_; family_ = other.family_; key_ = other.key_; plumes_ = other.plumes_; information_ = other.information_; keyword_ = other.keyword_; station_name_ = other.station_name_; param_ = other.param_; param_scaling_factor_ = other.param_scaling_factor_; param_offset_factor_ = other.param_offset_factor_; clim_param_ = other.clim_param_; clim_step_ = other.clim_step_; steps_ = other.steps_; percentile_ = other.percentile_; threshold_ = other.threshold_; y_max_threshold_ = other.y_max_threshold_; y_percent_ = other.y_percent_; correction_ = other.correction_; missing_value_ = other.missing_value_; ignore_keys_ = other.ignore_keys_; profile_quantile_ = other.profile_quantile_; hodograph_grid_ = other.hodograph_grid_; hodograph_tephi_ = other.hodograph_tephi_; hodograph_member_ = other.hodograph_member_; } bool WrepJSonAttributes::accept(const string& node) { if ( magCompare(node, "wrepjson") ) return true; return false; } void WrepJSonAttributes::set(const XmlNode& node) { bool apply = false; if ( this->accept(node.name()) == false ) return; if ( magCompare(node.name(), "wrepjson") ) apply = true; if ( apply ) set(node.attributes()); else { } for (auto &elt : node.elements()) { } } void WrepJSonAttributes::print(ostream& out) const { out << "Attributes["; out << " path = " << path_; out << " param_info = " << param_info_; out << " title = " << title_; out << " position_info = " << position_info_; out << " product_info = " << product_info_; out << " family = " << family_; out << " key = " << key_; out << " plumes = " << plumes_; out << " information = " << information_; out << " keyword = " << keyword_; out << " station_name = " << station_name_; out << " param = " << param_; out << " param_scaling_factor = " << param_scaling_factor_; out << " param_offset_factor = " << param_offset_factor_; out << " clim_param = " << clim_param_; out << " clim_step = " << clim_step_; out << " steps = " << steps_; out << " percentile = " << percentile_; out << " threshold = " << threshold_; out << " y_max_threshold = " << y_max_threshold_; out << " y_percent = " << y_percent_; out << " correction = " << correction_; out << " missing_value = " << missing_value_; out << " ignore_keys = " << ignore_keys_; out << " profile_quantile = " << profile_quantile_; out << " hodograph_grid = " << hodograph_grid_; out << " hodograph_tephi = " << hodograph_tephi_; out << " hodograph_member = " << hodograph_member_; out << "]" << "\n"; } void WrepJSonAttributes::toxml(ostream& out) const { out << "\"wrepjson\""; out << ", \"wrepjson_input_filename\":"; niceprint(out,path_); out << ", \"wrepjson_parameter_information\":"; niceprint(out,param_info_); out << ", \"wrepjson_title\":"; niceprint(out,title_); out << ", \"wrepjson_position_information\":"; niceprint(out,position_info_); out << ", \"wrepjson_product_information\":"; niceprint(out,product_info_); out << ", \"wrepjson_family\":"; niceprint(out,family_); out << ", \"wrepjson_key\":"; niceprint(out,key_); out << ", \"wrepjson_plumes_interval\":"; niceprint(out,plumes_); out << ", \"wrepjson_information\":"; niceprint(out,information_); out << ", \"wrepjson_keyword\":"; niceprint(out,keyword_); out << ", \"wrepjson_station_name\":"; niceprint(out,station_name_); out << ", \"wrepjson_parameter\":"; niceprint(out,param_); out << ", \"wrepjson_parameter_scaling_factor\":"; niceprint(out,param_scaling_factor_); out << ", \"wrepjson_parameter_offset_factor\":"; niceprint(out,param_offset_factor_); out << ", \"wrepjson_clim_parameter\":"; niceprint(out,clim_param_); out << ", \"wrepjson_clim_step\":"; niceprint(out,clim_step_); out << ", \"wrepjson_steps\":"; niceprint(out,steps_); out << ", \"wrepjson_y_axis_percentile\":"; niceprint(out,percentile_); out << ", \"wrepjson_y_axis_threshold\":"; niceprint(out,threshold_); out << ", \"wrepjson_y_max_threshold\":"; niceprint(out,y_max_threshold_); out << ", \"wrepjson_y_percentage\":"; niceprint(out,y_percent_); out << ", \"wrepjson_temperature_correction\":"; niceprint(out,correction_); out << ", \"wrepjson_missing_value\":"; niceprint(out,missing_value_); out << ", \"wrepjson_ignore_keys\":"; niceprint(out,ignore_keys_); out << ", \"wrepjson_profile_quantile\":"; niceprint(out,profile_quantile_); out << ", \"wrepjson_hodograph_grid\":"; niceprint(out,hodograph_grid_); out << ", \"wrepjson_hodograph_tephi\":"; niceprint(out,hodograph_tephi_); out << ", \"wrepjson_hodograph_member\":"; niceprint(out,hodograph_member_); } static MagicsParameter<string> wrepjson_input_filename("wrepjson_input_filename", ""); static MagicsParameter<string> wrepjson_parameter_information("wrepjson_parameter_information", ""); static MagicsParameter<string> wrepjson_title("wrepjson_title", "on"); static MagicsParameter<string> wrepjson_position_information("wrepjson_position_information", "on"); static MagicsParameter<string> wrepjson_product_information("wrepjson_product_information", ""); static MagicsParameter<string> wrepjson_family("wrepjson_family", "eps"); static MagicsParameter<string> wrepjson_key("wrepjson_key", ""); static MagicsParameter<double> wrepjson_plumes_interval("wrepjson_plumes_interval", 1); static MagicsParameter<string> wrepjson_information("wrepjson_information", "on"); static MagicsParameter<string> wrepjson_keyword("wrepjson_keyword", ""); static MagicsParameter<string> wrepjson_station_name("wrepjson_station_name", ""); static MagicsParameter<string> wrepjson_parameter("wrepjson_parameter", "1"); static MagicsParameter<double> wrepjson_parameter_scaling_factor("wrepjson_parameter_scaling_factor", 1); static MagicsParameter<double> wrepjson_parameter_offset_factor("wrepjson_parameter_offset_factor", 0); static MagicsParameter<string> wrepjson_clim_parameter("wrepjson_clim_parameter", ""); static MagicsParameter<int> wrepjson_clim_step("wrepjson_clim_step", 36); static MagicsParameter<intarray> wrepjson_steps("wrepjson_steps", intarray()); static MagicsParameter<double> wrepjson_y_axis_percentile("wrepjson_y_axis_percentile", 1); static MagicsParameter<double> wrepjson_y_axis_threshold("wrepjson_y_axis_threshold", 50); static MagicsParameter<double> wrepjson_y_max_threshold("wrepjson_y_max_threshold", INT_MAX); static MagicsParameter<double> wrepjson_y_percentage("wrepjson_y_percentage", 0.01); static MagicsParameter<string> wrepjson_temperature_correction("wrepjson_temperature_correction", "off"); static MagicsParameter<double> wrepjson_missing_value("wrepjson_missing_value", -9999); static MagicsParameter<stringarray> wrepjson_ignore_keys("wrepjson_ignore_keys", stringarray()); static MagicsParameter<string> wrepjson_profile_quantile("wrepjson_profile_quantile", ""); static MagicsParameter<string> wrepjson_hodograph_grid("wrepjson_hodograph_grid", "off"); static MagicsParameter<string> wrepjson_hodograph_tephi("wrepjson_hodograph_tephi", "off"); static MagicsParameter<int> wrepjson_hodograph_member("wrepjson_hodograph_member", -1);
41.668919
105
0.757013
[ "vector" ]
3b9652e95b376008b42d206b36ca278dd900c478
6,520
cc
C++
code/addons/db/filterset.cc
sirAgg/nebula
3fbccc73779944aa3e56b9e8acdd6fedd1d38006
[ "BSD-2-Clause" ]
377
2018-10-24T08:34:21.000Z
2022-03-31T23:37:49.000Z
code/addons/db/filterset.cc
sirAgg/nebula
3fbccc73779944aa3e56b9e8acdd6fedd1d38006
[ "BSD-2-Clause" ]
11
2020-01-22T13:34:46.000Z
2022-03-07T10:07:34.000Z
code/addons/db/filterset.cc
sirAgg/nebula
3fbccc73779944aa3e56b9e8acdd6fedd1d38006
[ "BSD-2-Clause" ]
23
2019-07-13T16:28:32.000Z
2022-03-20T09:00:59.000Z
//------------------------------------------------------------------------------ // filterset.cc // (C) 2006 Radon Labs GmbH // (C) 2013-2016 Individual contributors, see AUTHORS file //------------------------------------------------------------------------------ #include "foundation/stdneb.h" #include "db/filterset.h" namespace Db { __ImplementClass(Db::FilterSet, 'DBFS', Core::RefCounted); using namespace Util; //------------------------------------------------------------------------------ /** */ FilterSet::FilterSet() : curToken(0), isDirty(false) { this->curToken = &this->tokens.Root(); } //------------------------------------------------------------------------------ /** */ FilterSet::~FilterSet() { this->curToken = 0; } //------------------------------------------------------------------------------ /** */ void FilterSet::Clear() { this->tokens.Root().Clear(); this->bindAttrs.Clear(); this->curToken = &this->tokens.Root(); this->isDirty = true; } //------------------------------------------------------------------------------ /** This starts a new statement block (think of it as opening brackets) and makes it current token. All following statements will go below this block, until the method End() is called. */ void FilterSet::BeginBlock() { n_assert(0 != this->curToken); this->curToken->Append(Token(Token::Block)); this->curToken = &(this->curToken->Back()); this->isDirty = true; } //------------------------------------------------------------------------------ /** This ends the current statement block. The method will make sure that there is no dangling And/Or token, and that the root level isn't reached yet. */ void FilterSet::EndBlock() { n_assert(0 != this->curToken); n_assert(this->curToken->HasParent()); n_assert(this->curToken->Value().GetType() != Token::Root); n_assert(this->curToken->Front().Value().GetType() != Token::And); n_assert(this->curToken->Front().Value().GetType() != Token::Or); n_assert(this->curToken->Back().Value().GetType() != Token::And); n_assert(this->curToken->Back().Value().GetType() != Token::Or); n_assert(this->curToken->Back().Value().GetType() != Token::Not); this->curToken = &this->curToken->Parent(); this->isDirty = true; } //------------------------------------------------------------------------------ /** This adds an equal-check to the filter, where the attribute's id defines the column, and the attribute's value is the value to check the column's contents against. */ void FilterSet::AddEqualCheck(const Attr::Attribute& attr) { n_assert(0 != this->curToken); this->curToken->Append(Token(Token::Equal, attr)); this->bindAttrs.Append(attr); this->isDirty = true; } //------------------------------------------------------------------------------ /** This adds an greater-check to the filter, where the attribute's id defines the column, and the attribute's value is the value to check the column's contents against. */ void FilterSet::AddGreaterThenCheck(const Attr::Attribute& attr) { n_assert(0 != this->curToken); this->curToken->Append(Token(Token::Greater, attr)); this->bindAttrs.Append(attr); this->isDirty = true; } //------------------------------------------------------------------------------ /** This adds a less-check to the filter, where the attribute's id defines the column, and the attribute's value is the value to check the column's contents against. */ void FilterSet::AddLessThenCheck(const Attr::Attribute& attr) { n_assert(0 != this->curToken); this->curToken->Append(Token(Token::Less, attr)); this->bindAttrs.Append(attr); this->isDirty = true; } //------------------------------------------------------------------------------ /** This adds a greater-equal-check to the filter, where the attribute's id defines the column, and the attribute's value is the value to check the column's contents against. */ void FilterSet::AddGreaterOrEqualCheck(const Attr::Attribute& attr) { n_assert(0 != this->curToken); this->curToken->Append(Token(Token::GreaterEqual, attr)); this->bindAttrs.Append(attr); this->isDirty = true; } //------------------------------------------------------------------------------ /** This adds a less-equal-check to the filter, where the attribute's id defines the column, and the attribute's value is the value to check the column's contents against. */ void FilterSet::AddLessOrEqualCheck(const Attr::Attribute& attr) { n_assert(0 != this->curToken); this->curToken->Append(Token(Token::LessEqual, attr)); this->bindAttrs.Append(attr); this->isDirty = true; } //------------------------------------------------------------------------------ /** This adds an AND boolean operation. This may not be the first or last token in a block (this is checked by the next End()). */ void FilterSet::AddAnd() { n_assert(0 != this->curToken); this->curToken->Append(Token(Token::And)); this->isDirty = true; } //------------------------------------------------------------------------------ /** This adds an OR boolean operation. This may not be the first or last token in a block (this is checked by the next End()). */ void FilterSet::AddOr() { n_assert(0 != this->curToken); this->curToken->Append(Token(Token::Or)); this->isDirty = true; } //------------------------------------------------------------------------------ /** This adds an NOT boolean operation. This may not be last token in a block (this is checked by the next End()). */ void FilterSet::AddNot() { n_assert(0 != this->curToken); this->curToken->Append(Token(Token::Not)); this->isDirty = true; } //------------------------------------------------------------------------------ /** This method should return a string fragment which contains the part behind an SQL WHERE representing the condition tree encoded in this Filter object. */ String FilterSet::AsSqlWhere() const { n_error("Db::FilterSet::AsSqlWhere() called!"); return ""; } //------------------------------------------------------------------------------ /** This methods binds the actual WHERE values to a compiled command. */ void FilterSet::BindValuesToCommand(const Ptr<Command>& cmd, IndexT wildcardStartIndex) { n_error("Db::FilterSet::BindValuesToCommand() called!"); } } // namespace Db
29.771689
82
0.530215
[ "object" ]
3b98952f5914670d930cc55727232ec67b3c5de7
21,522
cc
C++
src/examples/fuse/main.cc
polonaise/polonaise
33315aeebd0980f96096558a6ca1ada3b8cb80b7
[ "Apache-2.0" ]
2
2017-10-22T16:27:29.000Z
2017-10-22T16:28:27.000Z
src/examples/fuse/main.cc
polonaise/polonaise
33315aeebd0980f96096558a6ca1ada3b8cb80b7
[ "Apache-2.0" ]
null
null
null
src/examples/fuse/main.cc
polonaise/polonaise
33315aeebd0980f96096558a6ca1ada3b8cb80b7
[ "Apache-2.0" ]
null
null
null
/* * 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. */ #include <stdio.h> #include <unistd.h> #include <sys/time.h> #include <memory> #include <mutex> #include <boost/make_shared.hpp> #include <fuse.h> #include <fuse/fuse_lowlevel.h> #include <fuse/fuse_opt.h> #include <polonaise/Polonaise.h> #include <polonaise/polonaise_constants.h> #include <thrift/protocol/TBinaryProtocol.h> #include <thrift/transport/TSocket.h> #include <thrift/transport/TTransportUtils.h> using namespace polonaise; // A pool of Thrift Clients (ie. a pool of connections with some server) template <typename Client> class ThriftClientPool { public: // Behaves like a Thrift Client (see operator->), but returns itself to a // client pool when destroyed. class Entry { public: Entry(ThriftClientPool& pool, std::unique_ptr<Client> client) : pool_(pool), client_(std::move(client)) { } Entry(Entry&& other) : pool_(other.pool_), client_(std::move(other.client_)) { } ~Entry() { if (client_ != nullptr) { pool_.put(std::move(client_)); } } // Marks client as unusable (eg. after losing a connection). // Prevents it from being returned to the pool. void markAsUnusable() { client_.reset(); } Client* operator->() { return client_.get(); } private: std::unique_ptr<Client> client_; ThriftClientPool& pool_; }; ThriftClientPool(int maxSize) : maxSize_(maxSize), host_("localhost"), port_(9090) { } void setHost(std::string host) { host_ = std::move(host); } void setPort(int port) { port_ = port; } // Adds a new client to the pool. It will be returned back on destruction. void put(std::unique_ptr<Client> client) { std::unique_lock<std::mutex> lock(mutex_); clients_.push_back(std::move(client)); } // Gets a client from the pool or creates a new client if the pool is empty Entry get() { using namespace apache::thrift; using namespace apache::thrift::protocol; using namespace apache::thrift::transport; std::unique_lock<std::mutex> lock(mutex_); while (clients_.size() > maxSize_) { clients_.pop_front(); } if (clients_.empty()) { lock.unlock(); // No clients in the pool; create a new connection fprintf(stderr, "Opening a new connection to %s:%d\n", host_.c_str(), port_); auto socket = boost::make_shared<TSocket>(host_, port_); auto transport = boost::make_shared<TBufferedTransport>(socket, 512 * 1024, 4096); auto protocol = boost::make_shared<TBinaryProtocol>(transport); auto client = std::unique_ptr<Client>(new Client(protocol)); socket->setNoDelay(true); transport->open(); return Entry(*this, std::move(client)); } // Take the first one form the pool Entry entry(*this, std::move(clients_.front())); clients_.pop_front(); return entry; } private: int maxSize_; std::string host_; int port_; std::mutex mutex_; std::list<std::unique_ptr<Client>> clients_; }; ThriftClientPool<PolonaiseClient> gClientPool(30); static SessionId gSessionId; // Obtains session ID. Returns true iff successful. bool polonaise_init() { try { gSessionId = gClientPool.get()->initSession(); return true; } catch (apache::thrift::TException& tx) { fprintf(stderr, "ERROR: %s\n", tx.what()); return false; } } void polonaise_term() { } // FUSE to Polonaise conversions Descriptor get_descriptor(struct fuse_file_info *fi) { return fi ? static_cast<Descriptor>(fi->fh) : g_polonaise_constants.kNullDescriptor; } Context get_context(fuse_req_t& req) { const fuse_ctx *ctx = fuse_req_ctx(req); Context ret; ret.sessionId = gSessionId; ret.uid = ctx->uid; ret.gid = ctx->gid; ret.pid = ctx->pid; ret.umask = ctx->umask; return ret; } int get_open_flags(int posixFlags) { static std::pair<int, int> mappings[] = { {O_CREAT, OpenFlags::kCreate}, {O_EXCL, OpenFlags::kExclusive}, {O_APPEND, OpenFlags::kAppend}, {O_TRUNC, OpenFlags::kTrunc}, }; int polonaiseFlags = 0; for (const auto& mapping : mappings) { if (posixFlags & mapping.first) { polonaiseFlags |= mapping.second; } } switch (posixFlags & O_ACCMODE) { case O_RDONLY: polonaiseFlags |= OpenFlags::kRead; break; case O_WRONLY: polonaiseFlags |= OpenFlags::kWrite; break; case O_RDWR: polonaiseFlags |= (OpenFlags::kRead | OpenFlags::kWrite); break; } return polonaiseFlags; } int get_access_mask(int posixMask) { static std::pair<int, int> mappings[] = { {001, AccessMask::kExecute}, {002, AccessMask::kWrite}, {004, AccessMask::kRead}, }; int polonaiseMask = 0; for (const auto& mapping : mappings) { if (posixMask & mapping.first) { polonaiseMask |= mapping.second; } } return polonaiseMask; } Mode get_mode(int posixMode) { Mode result; result.ownerMask = get_access_mask((posixMode >> 6) & 07); result.groupMask = get_access_mask((posixMode >> 3) & 07); result.otherMask = get_access_mask((posixMode >> 0) & 07); result.sticky = (posixMode & S_ISVTX); result.setUid = (posixMode & S_ISUID); result.setGid = (posixMode & S_ISGID); return result; } FileType::type get_file_type(int posixMode) { if (S_ISREG(posixMode)) { return FileType::kRegular; } if (S_ISDIR(posixMode)) { return FileType::kDirectory; } if (S_ISLNK(posixMode)) { return FileType::kSymlink; } if (S_ISFIFO(posixMode)) { return FileType::kFifo; } if (S_ISBLK(posixMode)) { return FileType::kBlockDevice; } if (S_ISCHR(posixMode)) { return FileType::kCharDevice; } if (S_ISSOCK(posixMode)) { return FileType::kSocket; } Failure failure; failure.message = "client: Unknown file type in get_file_type"; throw failure; } // Polonaise to FUSE conversions int make_mode(const Mode& mode) { int ret = 0; ret |= (get_access_mask(mode.otherMask) << 0); ret |= (get_access_mask(mode.groupMask) << 3); ret |= (get_access_mask(mode.ownerMask) << 6); ret |= (mode.sticky ? S_ISVTX : 0); ret |= (mode.setUid ? S_ISUID : 0); ret |= (mode.setGid ? S_ISGID : 0); return ret; } struct stat make_stbuf(const FileStat& fs) { struct stat stbuf{}; switch (fs.type) { case FileType::kRegular: stbuf.st_mode = S_IFREG; break; case FileType::kDirectory: stbuf.st_mode = S_IFDIR; break; case FileType::kSymlink: stbuf.st_mode = S_IFLNK; break; case FileType::kFifo: stbuf.st_mode = S_IFIFO; break; case FileType::kBlockDevice: stbuf.st_mode = S_IFBLK; break; case FileType::kCharDevice: stbuf.st_mode = S_IFCHR; break; case FileType::kSocket: stbuf.st_mode = S_IFSOCK; break; } stbuf.st_dev = fs.dev; stbuf.st_ino = fs.inode; stbuf.st_nlink = fs.nlink; stbuf.st_mode |= make_mode(fs.mode); stbuf.st_uid = fs.uid; stbuf.st_gid = fs.gid; stbuf.st_rdev = fs.rdev; stbuf.st_size = fs.size; stbuf.st_blocks = fs.blocks; stbuf.st_blksize = fs.blockSize; stbuf.st_atime = fs.atime; stbuf.st_mtime = fs.mtime; stbuf.st_ctime = fs.ctime; #ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME stbuf.st_birthtime = stbuf.st_ctime; #endif return stbuf; } fuse_entry_param make_fuse_entry_param(const EntryReply& entry) { fuse_entry_param fep{}; fep.ino = entry.inode; fep.generation = entry.generation; fep.attr = make_stbuf(entry.attributes); fep.attr_timeout = entry.attributesTimeout; fep.entry_timeout = entry.entryTimeout; return fep; } int make_error_number(StatusCode::type status) { switch(status) { case StatusCode::kE2BIG: return E2BIG; case StatusCode::kEACCES: return EACCES; case StatusCode::kEAGAIN: return EAGAIN; case StatusCode::kEBADF: return EBADF; case StatusCode::kEBUSY: return EBUSY; case StatusCode::kECHILD: return ECHILD; case StatusCode::kEDOM: return EDOM; case StatusCode::kEEXIST: return EEXIST; case StatusCode::kEFAULT: return EFAULT; case StatusCode::kEFBIG: return EFBIG; case StatusCode::kEINTR: return EINTR; case StatusCode::kEINVAL: return EINVAL; case StatusCode::kEIO: return EIO; case StatusCode::kEISDIR: return EISDIR; case StatusCode::kEMFILE: return EMFILE; case StatusCode::kEMLINK: return EMLINK; case StatusCode::kENAMETOOLONG: return ENAMETOOLONG; case StatusCode::kENFILE: return ENFILE; case StatusCode::kENODATA: return ENODATA; case StatusCode::kENODEV: return ENODEV; case StatusCode::kENOENT: return ENOENT; case StatusCode::kENOEXEC: return ENOEXEC; case StatusCode::kENOMEM: return ENOMEM; case StatusCode::kENOSPC: return ENOSPC; case StatusCode::kENOSYS: return ENOSYS; case StatusCode::kENOTBLK: return ENOTBLK; case StatusCode::kENOTDIR: return ENOTDIR; case StatusCode::kENOTEMPTY: return ENOTEMPTY; case StatusCode::kENOTTY: return ENOTTY; case StatusCode::kENXIO: return ENXIO; case StatusCode::kEPERM: return EPERM; case StatusCode::kEPIPE: return EPIPE; case StatusCode::kERANGE: return ERANGE; case StatusCode::kEROFS: return EROFS; case StatusCode::kESPIPE: return ESPIPE; case StatusCode::kESRCH: return ESRCH; case StatusCode::kETIMEDOUT: return ETIMEDOUT; case StatusCode::kETXTBSY: return ETXTBSY; case StatusCode::kEXDEV: return EXDEV; case StatusCode::kEDQUOT: return EDQUOT; } return EIO; } // Implementation of FUSE callbacks #define HANDLE_POLONAISE_EXCEPTION_BEGIN \ try { \ auto polonaiseClient = gClientPool.get(); \ try { #define HANDLE_POLONAISE_EXCEPTION_END \ } catch (Status& s) { \ fuse_reply_err(req, make_error_number(s.statusCode)); \ } catch (Failure& f) { \ fprintf(stderr, "(%s) failure: %s\n", __FUNCTION__, f.message.c_str()); \ fuse_reply_err(req, EIO); \ } catch (apache::thrift::TException& e) { \ fprintf(stderr, "(%s) connection error: %s\n", __FUNCTION__, e.what()); \ fuse_reply_err(req, EIO); \ polonaiseClient.markAsUnusable(); \ } \ } catch (apache::thrift::TException& e) /* gClientPool.get() may throw this */ { \ fprintf(stderr, "(%s) connection error: %s\n", __FUNCTION__, e.what()); \ fuse_reply_err(req, EIO); \ } void do_init(void *userdata, struct fuse_conn_info *conn) { conn->want |= FUSE_CAP_DONT_MASK; } void do_getattr(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi) { HANDLE_POLONAISE_EXCEPTION_BEGIN AttributesReply reply; polonaiseClient->getattr(reply, get_context(req), ino, get_descriptor(fi)); const struct stat stbuf = make_stbuf(reply.attributes); fuse_reply_attr(req, &stbuf, reply.attributesTimeout); HANDLE_POLONAISE_EXCEPTION_END } void do_opendir(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi) { HANDLE_POLONAISE_EXCEPTION_BEGIN Descriptor descriptor = polonaiseClient->opendir(get_context(req), ino); fi->fh = static_cast<uint64_t>(descriptor); fuse_reply_open(req, fi); HANDLE_POLONAISE_EXCEPTION_END } void do_readdir(fuse_req_t req, fuse_ino_t ino, size_t size, off_t off, struct fuse_file_info *fi) { HANDLE_POLONAISE_EXCEPTION_BEGIN std::vector<DirectoryEntry> reply; polonaiseClient->readdir(reply, get_context(req), ino, off, 1 + size / 32, get_descriptor(fi)); char buffer[65536]; if (size > 65536) { size = 65536; } size_t written = 0; for (const auto& entry : reply) { const struct stat stbuf = make_stbuf(entry.attributes); size_t entrySize = fuse_add_direntry(req, buffer + written, size, entry.name.c_str(), &stbuf, entry.nextEntryOffset); if (entrySize > size) { break; } written += entrySize; size -= entrySize; } fuse_reply_buf(req, buffer, written); HANDLE_POLONAISE_EXCEPTION_END } void do_releasedir(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi) { HANDLE_POLONAISE_EXCEPTION_BEGIN polonaiseClient->releasedir(get_context(req), ino, get_descriptor(fi)); fi->fh = static_cast<uint64_t>(-2); fuse_reply_err(req, 0); HANDLE_POLONAISE_EXCEPTION_END } void do_lookup(fuse_req_t req, fuse_ino_t parent, const char *name) { HANDLE_POLONAISE_EXCEPTION_BEGIN EntryReply reply; polonaiseClient->lookup(reply, get_context(req), parent, name); const fuse_entry_param fep = make_fuse_entry_param(reply); fuse_reply_entry(req, &fep); HANDLE_POLONAISE_EXCEPTION_END } void do_access(fuse_req_t req, fuse_ino_t ino, int mask) { HANDLE_POLONAISE_EXCEPTION_BEGIN polonaiseClient->access(get_context(req), ino, get_access_mask(mask)); fuse_reply_err(req, 0); HANDLE_POLONAISE_EXCEPTION_END } void do_open(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi) { HANDLE_POLONAISE_EXCEPTION_BEGIN OpenReply reply; polonaiseClient->open(reply, get_context(req), ino, get_open_flags(fi->flags)); fi->direct_io = reply.directIo; fi->keep_cache = reply.keepCache; fi->nonseekable = reply.nonSeekable; fi->fh = static_cast<uint64_t>(reply.descriptor); if (fuse_reply_open(req, fi) == -ENONET) { polonaiseClient->release(get_context(req), ino, reply.descriptor); fi->fh = static_cast<uint64_t>(-2); } HANDLE_POLONAISE_EXCEPTION_END } void do_read(fuse_req_t req, fuse_ino_t ino, size_t size, off_t off, struct fuse_file_info *fi) { HANDLE_POLONAISE_EXCEPTION_BEGIN std::string buffer; polonaiseClient->read(buffer, get_context(req), ino, off, size, get_descriptor(fi)); fuse_reply_buf(req, buffer.data(), buffer.size()); HANDLE_POLONAISE_EXCEPTION_END } void do_flush(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi) { HANDLE_POLONAISE_EXCEPTION_BEGIN polonaiseClient->flush(get_context(req), ino, get_descriptor(fi)); fuse_reply_err(req, 0); HANDLE_POLONAISE_EXCEPTION_END } void do_release(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi) { HANDLE_POLONAISE_EXCEPTION_BEGIN polonaiseClient->release(get_context(req), ino, get_descriptor(fi)); fi->fh = static_cast<uint64_t>(-2); fuse_reply_err(req, 0); HANDLE_POLONAISE_EXCEPTION_END } void do_statfs(fuse_req_t req, fuse_ino_t ino) { HANDLE_POLONAISE_EXCEPTION_BEGIN StatFsReply reply; polonaiseClient->statfs(reply, get_context(req), ino); struct statvfs s; s.f_fsid = reply.filesystemId; s.f_namemax = reply.maxNameLength; s.f_frsize = s.f_bsize = reply.blockSize; s.f_blocks = reply.totalBlocks; s.f_bfree = reply.freeBlocks; s.f_bavail = reply.availableBlocks; s.f_files = reply.totalFiles; s.f_ffree = reply.freeFiles; s.f_favail = reply.availableFiles; fuse_reply_statfs(req, &s); HANDLE_POLONAISE_EXCEPTION_END } void do_symlink(fuse_req_t req, const char *link, fuse_ino_t parent, const char *name) { HANDLE_POLONAISE_EXCEPTION_BEGIN EntryReply reply; polonaiseClient->symlink(reply, get_context(req), link, parent, name); const fuse_entry_param fep = make_fuse_entry_param(reply); fuse_reply_entry(req, &fep); HANDLE_POLONAISE_EXCEPTION_END } void do_readlink(fuse_req_t req, fuse_ino_t ino) { HANDLE_POLONAISE_EXCEPTION_BEGIN std::string reply; polonaiseClient->readlink(reply, get_context(req), ino); fuse_reply_readlink(req, reply.c_str()); HANDLE_POLONAISE_EXCEPTION_END } void do_write(fuse_req_t req, fuse_ino_t ino, const char *buf, size_t size, off_t off, struct fuse_file_info *fi) { HANDLE_POLONAISE_EXCEPTION_BEGIN std::string data(buf, size); int64_t count = polonaiseClient->write(get_context(req), ino, off, size, data, get_descriptor(fi)); fuse_reply_write(req, count); HANDLE_POLONAISE_EXCEPTION_END } void do_fsync(fuse_req_t req, fuse_ino_t ino, int datasync, struct fuse_file_info *fi) { HANDLE_POLONAISE_EXCEPTION_BEGIN polonaiseClient->fsync(get_context(req), ino, datasync, get_descriptor(fi)); fuse_reply_err(req, 0); HANDLE_POLONAISE_EXCEPTION_END } void do_setattr(fuse_req_t req, fuse_ino_t ino, struct stat *attr, int to_set, struct fuse_file_info *fi) { HANDLE_POLONAISE_EXCEPTION_BEGIN int32_t toSet = 0; toSet |= (to_set & FUSE_SET_ATTR_MODE) ? ToSet::kMode : 0; toSet |= (to_set & FUSE_SET_ATTR_UID) ? ToSet::kUid : 0; toSet |= (to_set & FUSE_SET_ATTR_GID) ? ToSet::kGid : 0; toSet |= (to_set & FUSE_SET_ATTR_SIZE) ? ToSet::kSize : 0; toSet |= (to_set & FUSE_SET_ATTR_ATIME) ? ToSet::kAtime : 0; toSet |= (to_set & FUSE_SET_ATTR_MTIME) ? ToSet::kMtime : 0; toSet |= (to_set & FUSE_SET_ATTR_ATIME_NOW) ? ToSet::kAtimeNow : 0; toSet |= (to_set & FUSE_SET_ATTR_MTIME_NOW) ? ToSet::kMtimeNow : 0; FileStat attributes; attributes.type = FileType::kFifo; // anything, server has to ignore it anyway if (toSet & ToSet::kMode) { attributes.mode = get_mode(attr->st_mode); } attributes.uid = (toSet & ToSet::kUid) ? attr->st_uid : 0; attributes.gid = (toSet & ToSet::kGid) ? attr->st_gid : 0; attributes.size = (toSet & ToSet::kSize) ? attr->st_size : 0; attributes.atime = (toSet & ToSet::kAtime) ? attr->st_atime : 0; attributes.mtime = (toSet & ToSet::kMtime) ? attr->st_mtime : 0; AttributesReply reply; polonaiseClient->setattr(reply, get_context(req), ino, attributes, toSet, get_descriptor(fi)); const struct stat stbuf = make_stbuf(reply.attributes); fuse_reply_attr(req, &stbuf, reply.attributesTimeout); HANDLE_POLONAISE_EXCEPTION_END } void do_create(fuse_req_t req, fuse_ino_t parent, const char *name, mode_t mode, struct fuse_file_info *fi) { HANDLE_POLONAISE_EXCEPTION_BEGIN CreateReply reply; polonaiseClient->create(reply, get_context(req), parent, name, get_mode(mode), get_open_flags(fi->flags)); const fuse_entry_param fep = make_fuse_entry_param(reply.entry); fi->fh = static_cast<uint64_t>(reply.descriptor); fi->direct_io = reply.directIo; fi->keep_cache = reply.keepCache; fuse_reply_create(req, &fep, fi); HANDLE_POLONAISE_EXCEPTION_END } void do_mknod(fuse_req_t req, fuse_ino_t parent, const char *name, mode_t mode, dev_t rdev) { HANDLE_POLONAISE_EXCEPTION_BEGIN EntryReply reply; polonaiseClient->mknod(reply, get_context(req), parent, name, get_file_type(mode), get_mode(mode), rdev); const fuse_entry_param fep = make_fuse_entry_param(reply); fuse_reply_entry(req, &fep); HANDLE_POLONAISE_EXCEPTION_END } void do_mkdir(fuse_req_t req, fuse_ino_t parent, const char *name, mode_t mode) { HANDLE_POLONAISE_EXCEPTION_BEGIN EntryReply reply; polonaiseClient->mkdir(reply, get_context(req), parent, name, FileType::kDirectory, get_mode(mode)); const fuse_entry_param fep = make_fuse_entry_param(reply); fuse_reply_entry(req, &fep); HANDLE_POLONAISE_EXCEPTION_END } void do_rmdir(fuse_req_t req, fuse_ino_t parent, const char *name) { HANDLE_POLONAISE_EXCEPTION_BEGIN polonaiseClient->rmdir(get_context(req), parent, name); fuse_reply_err(req, 0); HANDLE_POLONAISE_EXCEPTION_END } void do_link(fuse_req_t req, fuse_ino_t ino, fuse_ino_t newparent, const char *newname) { HANDLE_POLONAISE_EXCEPTION_BEGIN EntryReply reply; polonaiseClient->link(reply, get_context(req), ino, newparent, newname); const fuse_entry_param fep = make_fuse_entry_param(reply); fuse_reply_entry(req, &fep); HANDLE_POLONAISE_EXCEPTION_END } void do_unlink(fuse_req_t req, fuse_ino_t parent, const char *name) { HANDLE_POLONAISE_EXCEPTION_BEGIN polonaiseClient->unlink(get_context(req), parent, name); fuse_reply_err(req, 0); HANDLE_POLONAISE_EXCEPTION_END } void do_rename(fuse_req_t req, fuse_ino_t parent, const char *name, fuse_ino_t newparent, const char *newname) { HANDLE_POLONAISE_EXCEPTION_BEGIN polonaiseClient->rename(get_context(req), parent, name, newparent, newname); fuse_reply_err(req, 0); HANDLE_POLONAISE_EXCEPTION_END } int main(int argc, char** argv) { gClientPool.setHost(getenv("POLONAISE_SERVER") ? getenv("POLONAISE_SERVER") : "localhost"); gClientPool.setPort(getenv("POLONAISE_PORT") ? atoi(getenv("POLONAISE_PORT")) : 9090); if (!polonaise_init()) { fprintf(stderr, "Server connection failed.\n"); return 1; } struct fuse_lowlevel_ops ops{}; ops.init = do_init; ops.getattr = do_getattr; ops.opendir = do_opendir; ops.readdir = do_readdir; ops.releasedir = do_releasedir; ops.lookup = do_lookup; ops.access = do_access; ops.open = do_open; ops.read = do_read; ops.flush = do_flush; ops.release = do_release; ops.statfs = do_statfs; ops.symlink = do_symlink; ops.readlink = do_readlink; ops.write = do_write; ops.fsync = do_fsync; ops.setattr = do_setattr; ops.create = do_create; ops.mknod = do_mknod; ops.mkdir = do_mkdir; ops.rmdir = do_rmdir; ops.link = do_link; ops.unlink = do_unlink; ops.rename = do_rename; struct fuse_args args = FUSE_ARGS_INIT(argc, argv); char *mp; int mt; if (fuse_parse_cmdline(&args, &mp, &mt, NULL) < 0) { perror("fuse_parse_cmdline"); return 1; } fuse_chan *channel = fuse_mount(mp, &args); if (!channel) { perror("fuse_mount"); return 1; } fuse_session *session = fuse_lowlevel_new(&args, &ops, sizeof(ops), NULL); if (!session) { perror("fuse_lowlevel_new"); return 1; } fuse_session_add_chan(session, channel); fuse_set_signal_handlers(session); if (mt) { fuse_session_loop_mt(session); } else { fuse_session_loop(session); } fuse_remove_signal_handlers(session); return 0; }
29.401639
115
0.735015
[ "vector" ]
3b9bc9d11ebb623a4098b011016e2d1ac861a411
25,536
cxx
C++
scioniguruma/OnigurumaRegExEngine.cxx
hugepants/Notepad3
696d04d681f6616e2b1236f8d9dde8ff747df135
[ "BSD-3-Clause" ]
1
2020-04-28T08:07:29.000Z
2020-04-28T08:07:29.000Z
scioniguruma/OnigurumaRegExEngine.cxx
hugepants/Notepad3
696d04d681f6616e2b1236f8d9dde8ff747df135
[ "BSD-3-Clause" ]
null
null
null
scioniguruma/OnigurumaRegExEngine.cxx
hugepants/Notepad3
696d04d681f6616e2b1236f8d9dde8ff747df135
[ "BSD-3-Clause" ]
null
null
null
// encoding: UTF-8 /** * @file OnigurumaRegExEngine.cxx * @brief integrate Oniguruma regex engine for Scintilla library * (Scintilla Lib is copyright 1998-2017 by Neil Hodgson <neilh@scintilla.org>) * * uses Oniguruma - Regular Expression Engine (v6.9.0) (oniguruma.h) - https://github.com/kkos/oniguruma * * See also the Wiki page: https://github.com/kkos/oniguruma/wiki * * * @autor Rainer Kottenhoff (RaiKoHoff) * * TODO: add interface to onig_scan() API (mark occ, hyperlink) */ #ifdef SCI_OWNREGEX #include <cstdlib> #include <string> #include <vector> #include <sstream> #include <mbstring.h> #define VC_EXTRALEAN 1 #include <windows.h> #include "Platform.h" #include "Scintilla.h" #include "ILexer.h" #include "SplitVector.h" #include "Partitioning.h" #include "CellBuffer.h" #include "CaseFolder.h" #include "RunStyles.h" #include "Decoration.h" #include "CharClassify.h" #include "Document.h" // --------------------------------------------------------------- #ifdef ONIG_ESCAPE_UCHAR_COLLISION #undef ONIG_ESCAPE_UCHAR_COLLISION #endif #include "oniguruma.h" // Oniguruma - Regular Expression Engine (v6.9.2) // --------------------------------------------------------------- #define UCharPtr(pchar) reinterpret_cast<OnigUChar*>(pchar) #define UCharCPtr(pchar) reinterpret_cast<const OnigUChar*>(pchar) using namespace Scintilla; #define SciPos(pos) static_cast<Sci::Position>(pos) #define SciLn(line) static_cast<Sci::Line>(line) #define SciPosExt(pos) static_cast<Sci_Position>(pos) // ============================================================================ // *** Oningmo configuration *** // ============================================================================ enum class EOLmode : int { CRLF = SC_EOL_CRLF, CR = SC_EOL_CR, LF = SC_EOL_LF }; static OnigEncoding s_UsedEncodingsTypes[] = { ONIG_ENCODING_UTF8, ONIG_ENCODING_UTF8_CR, ONIG_ENCODING_UTF8_CRLF }; // ============================================================================ // ============================================================================ // ------------------------------------ // --- Onigmo Engine Simple Options --- // ------------------------------------ static void SetSimpleOptions(OnigOptionType& onigOptions, EOLmode eolMode, const bool caseSensitive, const bool forwardSearch, const int searchFlags = 0) { // fixed options onigOptions = ONIG_OPTION_DEFAULT; // Notepad3 forced options ONIG_OPTION_OFF(onigOptions, ONIG_OPTION_EXTEND); ONIG_OPTION_OFF(onigOptions, ONIG_OPTION_SINGLELINE); ONIG_OPTION_ON(onigOptions, ONIG_OPTION_NEGATE_SINGLELINE); ONIG_OPTION_OFF(onigOptions, ONIG_OPTION_FIND_LONGEST); //ONIG_OPTION_OFF(onigOptions, ONIG_OPTION_ASCII_RANGE); //ONIG_OPTION_OFF(onigOptions, ONIG_OPTION_CAPTURE_GROUP); // dynamic options switch (eolMode) { case EOLmode::CR: case EOLmode::LF: case EOLmode::CRLF: default: break; } if (searchFlags & SCFIND_DOT_MATCH_ALL) { ONIG_OPTION_ON(onigOptions, ONIG_SYN_OP_DOT_ANYCHAR); ONIG_OPTION_ON(onigOptions, ONIG_OPTION_MULTILINE); } else { ONIG_OPTION_OFF(onigOptions, ONIG_SYN_OP_DOT_ANYCHAR); ONIG_OPTION_OFF(onigOptions, ONIG_OPTION_MULTILINE); } if (caseSensitive) { ONIG_OPTION_OFF(onigOptions, ONIG_OPTION_IGNORECASE); } else { ONIG_OPTION_ON(onigOptions, ONIG_OPTION_IGNORECASE); } if (forwardSearch) { } else { } } // ============================================================================ class OnigurumaRegExEngine : public RegexSearchBase { public: explicit OnigurumaRegExEngine(CharClassify* charClassTable) : m_OnigSyntax(*ONIG_SYNTAX_DEFAULT) , m_CmplOptions(ONIG_OPTION_DEFAULT) , m_RegExpr(nullptr) , m_Region({0,0,nullptr,nullptr,nullptr}) , m_ErrorInfo() , m_MatchPos(ONIG_MISMATCH) , m_MatchLen(0) { m_OnigSyntax.op |= ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END; // xcluded from ONIG_SYNTAX_DEFAULT ? onig_initialize(s_UsedEncodingsTypes, _ARRAYSIZE(s_UsedEncodingsTypes)); onig_region_init(&m_Region); } ~OnigurumaRegExEngine() override { onig_region_free(&m_Region, 0); /* 1:free self, 0:free contents only */ onig_free(m_RegExpr); onig_end(); } Sci::Position FindText(Document* doc, Sci::Position minPos, Sci::Position maxPos, const char* pattern, bool caseSensitive, bool word, bool wordStart, int searchFlags, Sci::Position* length) override; const char* SubstituteByPosition(Document* doc, const char* text, Sci::Position* length) override; const OnigRegion& GetRegion() const { return m_Region; }; private: std::string& translateRegExpr(std::string& regExprStr, bool wholeWord, bool wordStart, int eolMode, OnigOptionType& rxOptions); std::string& convertReplExpr(std::string& replStr); //void regexFindAndReplace(std::string& inputStr_inout, const std::string& patternStr, const std::string& replStr); private: std::string m_RegExprStrg; OnigSyntaxType m_OnigSyntax; OnigOptionType m_CmplOptions; OnigRegex m_RegExpr; OnigRegion m_Region; char m_ErrorInfo[ONIG_MAX_ERROR_MESSAGE_LEN]; Sci::Position m_MatchPos; Sci::Position m_MatchLen; public: std::string m_SubstBuffer; }; // ============================================================================ RegexSearchBase *Scintilla::CreateRegexSearch(CharClassify *charClassTable) { return new OnigurumaRegExEngine(charClassTable); } // ============================================================================ // ============================================================================ // Some Helpers // ============================================================================ /****************************************************************************** * * UnSlash functions * Mostly taken from SciTE, (c) Neil Hodgson, http://www.scintilla.org * * Is the character an octal digit? */ constexpr bool IsOctalDigit(char ch) { return ((ch >= '0') && (ch <= '7')); } // ---------------------------------------------------------------------------- /** * If the character is an hex digit, get its value. */ constexpr int GetHexDigit(char ch) { if ((ch >= '0') && (ch <= '9')) { return (ch - '0'); } if ((ch >= 'A') && (ch <= 'F')) { return (ch - 'A' + 10); } if ((ch >= 'a') && (ch <= 'f')) { return (ch - 'a' + 10); } return -1; } // ---------------------------------------------------------------------------- static void replaceAll(std::string& source, const std::string& from, const std::string& to) { std::string newString; newString.reserve(source.length() * 2); // avoids a few memory allocations std::string::size_type lastPos = 0; std::string::size_type findPos; while (std::string::npos != (findPos = source.find(from, lastPos))) { newString.append(source, lastPos, findPos - lastPos); newString += to; lastPos = findPos + from.length(); } // Care for the rest after last occurrence newString += source.substr(lastPos); source.swap(newString); } // ---------------------------------------------------------------------------- /** * Find text in document, supporting both forward and backward * searches (just pass minPos > maxPos to do a backward search) * Has not been tested with backwards DBCS searches yet. */ Sci::Position OnigurumaRegExEngine::FindText(Document* doc, Sci::Position minPos, Sci::Position maxPos, const char *pattern, bool caseSensitive, bool word, bool wordStart, int searchFlags, Sci::Position *length) { if (!(pattern && (strlen(pattern) > 0))) { *length = 0; return SciPos(-1); } auto const docLen = SciPos(doc->Length()); EOLmode const eolMode = static_cast<EOLmode>(doc->eolMode); bool const findForward = (minPos <= maxPos); int const increment = findForward ? 1 : -1; // Range endpoints should not be inside DBCS characters, but just in case, move them. minPos = doc->MovePositionOutsideChar(minPos, increment, false); maxPos = doc->MovePositionOutsideChar(maxPos, increment, false); if (!findForward) { minPos = doc->MovePositionOutsideChar(minPos - 1, increment, false); } Sci::Position const rangeBeg = (findForward) ? minPos : maxPos; Sci::Position const rangeEnd = (findForward) ? maxPos : minPos; Sci::Position const rangeLen = (rangeEnd - rangeBeg); OnigOptionType onigOptions; SetSimpleOptions(onigOptions, eolMode, caseSensitive, findForward, searchFlags); ONIG_OPTION_ON(onigOptions, (rangeBeg != 0) ? ONIG_OPTION_NOTBOL : ONIG_OPTION_NONE); ONIG_OPTION_ON(onigOptions, (rangeEnd != docLen) ? ONIG_OPTION_NOTEOL : ONIG_OPTION_NONE); std::string sPattern(pattern); std::string const & sRegExprStrg = translateRegExpr(sPattern, word, wordStart, doc->eolMode, onigOptions); bool const bReCompile = (m_RegExpr == nullptr) || (m_CmplOptions != onigOptions) || (m_RegExprStrg.compare(sRegExprStrg) != 0); if (bReCompile) { m_RegExprStrg.clear(); m_RegExprStrg = sRegExprStrg; m_CmplOptions = onigOptions; m_ErrorInfo[0] = '\0'; try { OnigErrorInfo einfo; onig_free(m_RegExpr); OnigEncoding const onigEncType = (eolMode == EOLmode::LF) ? ONIG_ENCODING_UTF8 : ((eolMode == EOLmode::CR) ? ONIG_ENCODING_UTF8_CR : ONIG_ENCODING_UTF8_CRLF); int res = onig_new(&m_RegExpr, UCharCPtr(m_RegExprStrg.c_str()), UCharCPtr(m_RegExprStrg.c_str() + m_RegExprStrg.length()), m_CmplOptions, onigEncType, &m_OnigSyntax, &einfo); if (res != ONIG_NORMAL) { onig_error_code_to_str(UCharPtr(m_ErrorInfo), res, &einfo); return SciPos(-2); // -1 is normally used for not found, -2 is used here for invalid regex } } catch (...) { return SciPos(-2); } } m_MatchPos = SciPos(ONIG_MISMATCH); // not found m_MatchLen = SciPos(0); // --- search document range for pattern match --- // !!! Performance issue: Scintilla: moving Gap needs memcopy - high costs for find/replace in large document auto const docBegPtr = UCharCPtr(doc->RangePointer(0, docLen)); auto const docEndPtr = UCharCPtr(doc->RangePointer(docLen, 0)); auto const rangeBegPtr = UCharCPtr(doc->RangePointer(rangeBeg, rangeLen)); auto const rangeEndPtr = UCharCPtr(doc->RangePointer(rangeEnd, 0)); OnigPosition result = ONIG_MISMATCH; try { onig_region_free(&m_Region, 0); /* 1:free self, 0:free contents only */ onig_region_init(&m_Region); if (findForward) result = onig_search(m_RegExpr, docBegPtr, docEndPtr, rangeBegPtr, rangeEndPtr, &m_Region, onigOptions); else // X // result = onig_search(m_RegExpr, docBegPtr, docEndPtr, rangeEndPtr, rangeBegPtr, &m_Region, onigOptions); } catch (...) { return SciPos(-3); // -1 is normally used for not found, -3 is used here for exception } if (result < ONIG_MISMATCH) { onig_error_code_to_str(UCharPtr(m_ErrorInfo), result); return SciPos(-3); } if ((result >= 0) && (rangeBegPtr <= rangeEndPtr)) { //~m_MatchPos = SciPos(result); // m_MatchPos = SciPos(m_Region.beg[0]); //~m_MatchLen = SciPos(m_Region.end[0] - result); m_MatchLen = SciPos(m_Region.end[0]) - SciPos(m_Region.beg[0]); } //NOTE: potential 64-bit-size issue at interface here: *length = m_MatchLen; return m_MatchPos; } // ============================================================================ ////static int GrpNameCallback(const UChar* name, const UChar* name_end, //// int ngroup_num, int* group_nums, regex_t* reg, void* arg) ////{ //// OnigurumaRegExEngine* pRegExInstance = dynamic_cast<OnigurumaRegExEngine*>(arg); //// //// const OnigRegion& region = pRegExInstance->GetRegion(); //// //// for (int i = 0; i < ngroup_num; i++) //// { //// int grpNum = group_nums[i]; //// //// int ref = onig_name_to_backref_number(reg, name, name_end, &region); //// //// if (ref == grpNum) { //// //// Sci::Position rBeg = SciPos(region.beg[grpNum]); //// Sci::Position len = SciPos(region.end[grpNum] - rBeg); //// //// (pRegExInstance->m_SubstBuffer).append(doc->RangePointer(rBeg, len), (size_t)len); //// //// } //// } //// return 0; /* 0: continue */ ////} //// called by: int r = onig_foreach_name(m_RegExpr, GrpNameCallback, (void*)this); // ============================================================================ const char* OnigurumaRegExEngine::SubstituteByPosition(Document* doc, const char* text, Sci::Position* length) { if (m_MatchPos < 0) { *length = SciPos(-1); return nullptr; } std::string sText(text, *length); std::string const & rawReplStrg = convertReplExpr(sText); m_SubstBuffer.clear(); for (size_t j = 0; j < rawReplStrg.length(); ++j) { bool bReplaced = false; if ((rawReplStrg[j] == '$') || (rawReplStrg[j] == '\\')) { if ((rawReplStrg[j + 1] >= '0') && (rawReplStrg[j + 1] <= '9')) { // group # limit = 99 / TODO: allow for arbitrary number of groups/regions bool const digit2nd = ((rawReplStrg[j + 2] >= '0') && (rawReplStrg[j + 2] <= '9')) && (m_Region.num_regs > 10); int const grpNum = digit2nd ? (rawReplStrg[j + 1] - '0') * 10 + (rawReplStrg[j + 2] - '0') : (rawReplStrg[j + 1] - '0'); if (grpNum < m_Region.num_regs) { auto const rBeg = SciPos(m_Region.beg[grpNum]); auto const len = SciPos(m_Region.end[grpNum] - rBeg); m_SubstBuffer.append(doc->RangePointer(rBeg, len), static_cast<size_t>(len)); } bReplaced = true; j += digit2nd ? 2 : 1; } else if (rawReplStrg[j] == '$') { size_t k = ((rawReplStrg[j + 1] == '+') && (rawReplStrg[j + 2] == '{')) ? (j + 3) : ((rawReplStrg[j + 1] == '{') ? (j + 2) : 0); if (k > 0) { // named group replacement auto const name_beg = UCharCPtr(&(rawReplStrg[k])); while (rawReplStrg[k] && IsCharAlphaNumericA(rawReplStrg[k])) { ++k; } if (rawReplStrg[k] == '}') { int const grpNum = onig_name_to_backref_number(m_RegExpr, name_beg, UCharCPtr(&(rawReplStrg[k])), &m_Region); if ((grpNum >= 0) && (grpNum < m_Region.num_regs)) { auto const rBeg = SciPos(m_Region.beg[grpNum]); auto const len = SciPos(m_Region.end[grpNum] - rBeg); m_SubstBuffer.append(doc->RangePointer(rBeg, len), static_cast<size_t>(len)); } bReplaced = true; j = k; } } } else if ((rawReplStrg[j + 1] == '$') || (rawReplStrg[j + 1] == '\\')) { ++j; // '\$' -> '$' or '\\' -> '\' } } if (!bReplaced) { m_SubstBuffer.push_back(rawReplStrg[j]); } } //NOTE: potential 64-bit-size issue at interface here: *length = SciPos(m_SubstBuffer.length()); return m_SubstBuffer.c_str(); } // ============================================================================ // ============================================================================ // // private methods // // ============================================================================ /* void OnigurumaRegExEngine::regexFindAndReplace(std::string& inputStr_inout, const std::string& patternStr, const std::string& replStr) { OnigRegex oRegExpr; OnigRegion oRegion; const UChar* pattern = (UChar*)patternStr.c_str(); OnigErrorInfo einfo; int res = onig_new(&oRegExpr, pattern, pattern + strlen((char*)pattern), ONIG_OPTION_DEFAULT, ONIG_ENCODING_ASCII, ONIG_SYNTAX_DEFAULT, &einfo); if (res != ONIG_NORMAL) { return; } const UChar* strg = (UChar*)inputStr_inout.c_str(); const UChar* start = strg; const UChar* end = (start + patternStr.length()); const UChar* range = end; onig_region_init(&oRegion); OnigPosition pos = onig_search(oRegExpr, strg, end, start, range, &oRegion, ONIG_OPTION_DEFAULT); if (pos >= 0) { std::string replace = replStr; // copy for (int i = 1; i < oRegion.num_regs; i++) { std::ostringstream nr; nr << R"(\)" << i; std::string regio((char*)(strg + oRegion.beg[i]), (oRegion.end[i] - oRegion.beg[i])); replaceAll(replace, nr.str(), regio); } inputStr_inout.replace(oRegion.beg[0], (oRegion.end[0] - oRegion.beg[0]), replace); } onig_region_free(&oRegion, 0); // 1:free self, 0:free contents only onig_free(oRegExpr); } // ---------------------------------------------------------------------------- */ std::string& OnigurumaRegExEngine::translateRegExpr(std::string& regExprStr, bool wholeWord, bool wordStart, int eolMode, OnigOptionType& rxOptions) { std::string tmpStr; bool bUseTmpStrg = false; if (wholeWord || wordStart) { // push '\b' at the begin of regexpr tmpStr.push_back('\\'); tmpStr.push_back('b'); tmpStr.append(regExprStr); if (wholeWord) { // push '\b' at the end of regexpr tmpStr.push_back('\\'); tmpStr.push_back('b'); } replaceAll(tmpStr, ".", R"(\w)"); bUseTmpStrg = true; } else { tmpStr.append(regExprStr); } // Oniguruma supports LTGT word boundary by: ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END // //~replaceAll(tmpStr, R"(\<)", R"((?<!\w)(?=\w))"); // word begin //~replaceAll(tmpStr, R"(\(?<!\w)(?=\w))", R"(\\<)"); // esc'd //~replaceAll(tmpStr, R"(\>)", R"((?<=\w)(?!\w))"); // word end //~replaceAll(tmpStr, R"(\(?<=\w)(?!\w))", R"(\\>)"); // esc'd //~bUseTmpStrg = true; // EOL modes switch (eolMode) { case SC_EOL_LF: case SC_EOL_CR: //ONIG_OPTION_OFF(rxOptions, ONIG_OPTION_CRLF_AS_LINE_SEPARATOR); break; case SC_EOL_CRLF: //ONIG_OPTION_ON(rxOptions, ONIG_OPTION_CRLF_AS_LINE_SEPARATOR); break; } if (bUseTmpStrg) { std::swap(regExprStr, tmpStr); } return regExprStr; } // ---------------------------------------------------------------------------- std::string& OnigurumaRegExEngine::convertReplExpr(std::string& replStr) { std::string tmpStr; for (size_t i = 0; i < replStr.length(); ++i) { char ch = replStr[i]; if (ch == '\\') { ch = replStr[++i]; // next char if (ch >= '1' && ch <= '9') { // former behavior convenience: // change "\\<n>" to deelx's group reference ($<n>) tmpStr.push_back('$'); tmpStr.push_back(ch); continue; } switch (ch) { // check for escape seq: case 'a': tmpStr.push_back('\a'); break; case 'b': tmpStr.push_back('\x1B'); break; case 'f': tmpStr.push_back('\f'); break; case 'n': tmpStr.push_back('\n'); break; case 'r': tmpStr.push_back('\r'); break; case 't': tmpStr.push_back('\t'); break; case 'v': tmpStr.push_back('\v'); break; case '\\': tmpStr.push_back('\\'); // preserve escd "\" tmpStr.push_back('\\'); break; case 'x': case 'u': { bool bShort = (ch == 'x'); char buf[8] = { '\0' }; char *pch = buf; WCHAR val[2] = L""; int hex; val[0] = 0; ++i; hex = GetHexDigit(replStr[i]); if (hex >= 0) { ++i; val[0] = static_cast<WCHAR>(hex); hex = GetHexDigit(replStr[i]); if (hex >= 0) { ++i; val[0] *= 16; val[0] += static_cast<WCHAR>(hex); if (!bShort) { hex = GetHexDigit(replStr[i]); if (hex >= 0) { ++i; val[0] *= 16; val[0] += static_cast<WCHAR>(hex); hex = GetHexDigit(replStr[i]); if (hex >= 0) { ++i; val[0] *= 16; val[0] += static_cast<WCHAR>(hex); } } } } if (val[0]) { val[1] = 0; WideCharToMultiByte(CP_UTF8, 0, val, -1, buf, ARRAYSIZE(val), nullptr, nullptr); tmpStr.push_back(*pch++); while (*pch) tmpStr.push_back(*pch++); } else tmpStr.push_back(ch); // unknown hex seq } else tmpStr.push_back(ch); // unknown hex seq } break; default: // unknown ctrl seq tmpStr.push_back('\\'); // revert tmpStr.push_back(ch); break; } } else { tmpStr.push_back(ch); } } //for std::swap(replStr,tmpStr); return replStr; } // ============================================================================ // ============================================================================ // ============================================================================ class SimpleRegExEngine { public: explicit SimpleRegExEngine(const EOLmode eolMode) : m_EOLmode(eolMode) , m_OnigSyntax(*ONIG_SYNTAX_DEFAULT) , m_Options(ONIG_OPTION_DEFAULT) , m_RegExpr(nullptr) , m_Region({ 0,0,nullptr,nullptr,nullptr }) , m_ErrorInfo() , m_MatchPos(ONIG_MISMATCH) , m_MatchLen(0) { m_OnigSyntax.op |= ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END; // xcluded from ONIG_SYNTAX_DEFAULT ? onig_initialize(s_UsedEncodingsTypes, _ARRAYSIZE(s_UsedEncodingsTypes)); onig_region_init(&m_Region); } ~SimpleRegExEngine() noexcept { onig_region_free(&m_Region, 0); /* 1:free self, 0:free contents only */ onig_free(m_RegExpr); onig_end(); } OnigPosition Find(const OnigUChar* pattern, const OnigUChar* document, const bool caseSensitive); const OnigPosition GetMatchPos() const { return m_MatchPos; }; const OnigPosition GetMatchLen() const { return m_MatchLen; }; const OnigRegion& GetRegion() const { return m_Region; }; private: //void regexFindAndReplace(std::string& inputStr_inout, const std::string& patternStr, const std::string& replStr); private: EOLmode m_EOLmode; OnigSyntaxType m_OnigSyntax; OnigOptionType m_Options; OnigRegex m_RegExpr; OnigRegion m_Region; OnigUChar m_ErrorInfo[ONIG_MAX_ERROR_MESSAGE_LEN]; OnigPosition m_MatchPos; OnigPosition m_MatchLen; }; // ============================================================================ OnigPosition SimpleRegExEngine::Find(const OnigUChar* pattern, const OnigUChar* document, const bool caseSensitive) { auto const patternLen = (pattern) ? OnigPosition(_mbslen(pattern)) : 0; if (patternLen == 0) { return OnigPosition(-1); } auto const stringLen = (document) ? OnigPosition(_mbslen(document)) : 0; if (stringLen == 0) { return OnigPosition(-1); } // init search options SetSimpleOptions(m_Options, m_EOLmode, caseSensitive, true); m_ErrorInfo[0] = '\0'; try { onig_free(m_RegExpr); OnigEncoding const onigEncType = (m_EOLmode == EOLmode::LF) ? ONIG_ENCODING_UTF8 : ((m_EOLmode == EOLmode::CR) ? ONIG_ENCODING_UTF8_CR : ONIG_ENCODING_UTF8_CRLF); OnigErrorInfo einfo; int res = onig_new(&m_RegExpr, pattern, (pattern + patternLen), m_Options, onigEncType, &m_OnigSyntax, &einfo); if (res != ONIG_NORMAL) { //onig_error_code_to_str(m_ErrorInfo, res, &einfo); return OnigPosition(-111); } onig_region_free(&m_Region, 0); onig_region_init(&m_Region); const UChar* strgBeg = document; const UChar* strgEnd = document + stringLen; const UChar* rangeBeg = strgBeg; const UChar* rangeEnd = strgEnd; // start search OnigPosition result = onig_search(m_RegExpr, strgBeg, strgEnd, rangeBeg, rangeEnd, &m_Region, m_Options); if (result < ONIG_MISMATCH) { //onig_error_code_to_str(m_ErrorInfo, result); return OnigPosition(-3); } m_MatchPos = OnigPosition(ONIG_MISMATCH); // not found m_MatchLen = OnigPosition(0); if (result >= 0) // found { //~m_MatchPos = result; // m_MatchPos = m_Region.beg[0]; //~m_MatchLen = (m_Region.end[0] - result); m_MatchLen = (m_Region.end[0] - m_Region.beg[0]); } //else if (result == ONIG_MISMATCH) // not found //{ // m_MatchPos = result; // m_MatchLen = OnigPosition(0); //} else if (result < ONIG_MISMATCH) { //onig_error_code_to_str(m_ErrorInfo, result); m_MatchPos = result; m_MatchLen = OnigPosition(0); } } catch (...) { // -1 is normally used for not found, -666 is used here for exception return OnigPosition(-666); } return m_MatchPos; } // ============================================================================ extern "C" #ifdef SCINTILLA_DLL __declspec(dllexport) #endif ptrdiff_t WINAPI OnigRegExFind(const char* pchPattern, const char* pchText, const bool caseSensitive, const int eolMode) { const UChar* pattern = reinterpret_cast<const UChar*>(pchPattern); const UChar* string = reinterpret_cast<const UChar*>(pchText); SimpleRegExEngine ModuleRegExEngine(static_cast<EOLmode>(eolMode)); return static_cast<ptrdiff_t>(ModuleRegExEngine.Find(pattern, string, caseSensitive)); } // ============================================================================ #endif //SCI_OWNREGEX
31.255814
148
0.57323
[ "vector" ]
3b9f55459c0144885fe7429a1aa52c48771dc812
14,155
cpp
C++
dvo_benchmark/src/experiment.cpp
aginika/dvo_slam
d25b65bff58860bb5a3a39a742459db3ba98eaa6
[ "MIT" ]
566
2015-01-22T20:58:45.000Z
2022-03-29T22:34:55.000Z
dvo_benchmark/src/experiment.cpp
aginika/dvo_slam
d25b65bff58860bb5a3a39a742459db3ba98eaa6
[ "MIT" ]
57
2015-01-01T08:03:21.000Z
2022-02-19T16:14:35.000Z
dvo_benchmark/src/experiment.cpp
aginika/dvo_slam
d25b65bff58860bb5a3a39a742459db3ba98eaa6
[ "MIT" ]
291
2015-01-22T23:51:21.000Z
2022-03-12T13:26:17.000Z
#include <opencv2/opencv.hpp> #include <vector> #include <fstream> #include <ros/ros.h> #include <dvo/core/rgbd_image.h> #include <dvo/core/surface_pyramid.h> #include <dvo/visualization/visualizer.h> #include <dvo/util/id_generator.h> #include <dvo/dense_tracking.h> #include <dvo/dense_tracking_impl.h> #include <dvo_benchmark/file_reader.h> #include <dvo_benchmark/rgbd_pair.h> #include <dvo_benchmark/groundtruth.h> #include <dvo_benchmark/tools.h> double calculateSampledFrustumMetric(const Eigen::Affine3d& pose, const dvo::core::IntrinsicMatrix& intrinsics) { Eigen::Matrix<double, 9, 2> pixels; pixels << 50, 50, 50, 240, 50, 430, 320, 50, 320, 240, 320, 430, 590, 50, 590, 240, 590, 430; Eigen::Matrix<double, 4, 3 * 9> points; for (int d = 1; d < 4; ++d) { for (int idx = 0; idx < 9; ++idx) { points(0, (d - 1) * 9 + idx) = (pixels(idx, 0) - intrinsics.ox()) / intrinsics.fx() * d; // x points(1, (d - 1) * 9 + idx) = (pixels(idx, 1) - intrinsics.oy()) / intrinsics.fy() * d; // y points(2, (d - 1) * 9 + idx) = d; // z points(3, (d - 1) * 9 + idx) = 1.0; // w } } Eigen::Matrix<double, 4, 3 * 9> transformed = pose * points; double sum = 0.0; for (int idx = 0; idx < points.cols(); ++idx) { double u1 = points(0, idx) / points(3, idx) * intrinsics.fx() + intrinsics.ox(); double v1 = points(1, idx) / points(3, idx) * intrinsics.fy() + intrinsics.oy(); double u2 = transformed(0, idx) / transformed(3, idx) * intrinsics.fx() + intrinsics.ox(); double v2 = transformed(1, idx) / transformed(3, idx) * intrinsics.fy() + intrinsics.oy(); sum += std::sqrt((u1 - u2) * (u1 - u2) + (v1 - v2) * (v1 - v2)); } sum /= points.cols(); //Eigen::Matrix<double, 4, 3 * 9> diff = transformed - points; // diff.colwise().norm().sum() return sum; } dvo::core::RgbdImagePyramid::Ptr load(std::string rgb_file, std::string depth_file) { cv::Mat rgb, grey, grey_s16, depth, depth_inpainted, depth_mask, depth_mono, depth_float; bool rgb_available = false; rgb = cv::imread(rgb_file, 1); depth = cv::imread(depth_file, -1); if(rgb.type() != CV_32FC1) { if(rgb.type() == CV_8UC3) { cv::cvtColor(rgb, grey, CV_BGR2GRAY); rgb_available = true; } else { grey = rgb; } grey.convertTo(grey_s16, CV_32F); } else { grey_s16 = rgb; } if(depth.type() != CV_32FC1) { dvo::core::SurfacePyramid::convertRawDepthImageSse(depth, depth_float, 1.0f / 5000.0f); } else { depth_float = depth; } dvo::core::RgbdImagePyramid::Ptr result(new dvo::core::RgbdImagePyramid(grey_s16, depth_float)); if(rgb_available) rgb.convertTo(result->level(0).rgb, CV_32FC3); return result; } struct FindNearestPosePredicate { FindNearestPosePredicate(const dvo_benchmark::RgbdPair& entry) : entry_(entry) { } bool operator() (const dvo_benchmark::Groundtruth& left, const dvo_benchmark::Groundtruth& right) const { return left.Timestamp() <= entry_.RgbTimestamp() && right.Timestamp() >= entry_.RgbTimestamp(); } private: const dvo_benchmark::RgbdPair& entry_; }; // Jensen-Bregman LogDet Divergence template <typename Derived> double JenBreLogDetDiv(const Eigen::MatrixBase<Derived>& a, const Eigen::MatrixBase<Derived>& b) { return std::log(((a + b) / 2.0).determinant()) - 0.5 * std::log((a * b).determinant()); } int main(int argc, char **argv) { ros::init(argc, argv, "experiments", ros::init_options::AnonymousName); ros::NodeHandle nh("~"); std::string dataset; if(!nh.getParam("dataset", dataset)) { std::cerr << "Missing 'dataset' parameter!" << std::endl; return -1; } std::string assoc = dataset + "/assoc.txt"; std::string groundtruth = dataset + "/groundtruth.txt"; std::vector<dvo_benchmark::RgbdPair> pairs; std::vector<dvo_benchmark::Groundtruth> poses; dvo::visualization::Visualizer::instance() .enabled(true) .useExternalWaitKey(true) .save(true); dvo_benchmark::FileReader<dvo_benchmark::RgbdPair> pair_reader(assoc); pair_reader.skipComments(); pair_reader.readAllEntries(pairs); dvo_benchmark::FileReader<dvo_benchmark::Groundtruth> groundtruth_reader(groundtruth); groundtruth_reader.skipComments(); groundtruth_reader.readAllEntries(poses); dvo::core::RgbdImagePyramid::Ptr reference, current; dvo::core::IntrinsicMatrix intrinsics = dvo::core::IntrinsicMatrix::create(525.0f, 525.0f, 320.0f, 240.0f); dvo::DenseTracker::Config cfg = dvo::DenseTracker::getDefaultConfig(); cfg.UseWeighting = false; cfg.UseInitialEstimate = true; cfg.FirstLevel = 3; cfg.LastLevel = 1; cfg.MaxIterationsPerLevel = 100; dvo::DenseTracker tracker(intrinsics, cfg); Eigen::Affine3d reference_pose, current_pose, relative_pose; Eigen::Matrix<double, 6, 6> first_info, current_info; Eigen::Matrix2d first_error_precision; /* for (std::vector<dvo_benchmark::RgbdPair>::iterator it = pairs.begin(); it != pairs.end() && ros::ok(); ++it) { reference = load(dataset + "/" + it->RgbFile(), dataset + "/" + it->DepthFile()); std::vector<dvo_benchmark::Groundtruth>::iterator nearest = std::adjacent_find(poses.begin(), poses.end(), FindNearestPosePredicate(*it)); if(nearest == poses.end()) continue; dvo_benchmark::toPoseEigen(*nearest, reference_pose); relative_pose.setIdentity(); bool first = true; for (std::vector<dvo_benchmark::RgbdPair>::iterator it_inner = pairs.begin(); it_inner != pairs.end() && ros::ok(); ++it_inner) { std::vector<dvo_benchmark::Groundtruth>::iterator nearest = std::adjacent_find(poses.begin(), poses.end(), FindNearestPosePredicate(*it_inner)); if(nearest == poses.end()) continue; dvo_benchmark::toPoseEigen(*nearest, current_pose); current = load(dataset + "/" + it_inner->RgbFile(), dataset + "/" + it_inner->DepthFile()); relative_pose = relative_pose.inverse(); tracker.match(*reference, *current, relative_pose); <<<<<<< HEAD for (std::vector<dvo_benchmark::RgbdPair>::iterator it = pairs.begin() + 49; it != pairs.begin() + 52 && ros::ok(); ++it) ======= double translation_dist = (current_pose.inverse() * reference_pose).translation().norm(); double translation_error = ((current_pose.inverse() * reference_pose) * relative_pose).translation().norm(); double error_entropy = std::log(tracker.itctx_.Precision.determinant()); std::cout << translation_dist << " " << translation_error << " " << error_entropy << std::endl; } std::cerr << (pairs.end() - it) << " "; } */ /* for (std::vector<dvo_benchmark::RgbdPair>::iterator it = pairs.begin(); it != pairs.end() && ros::ok(); ++it) { reference = current; current = load(dataset + "/" + it->RgbFile(), dataset + "/" + it->DepthFile()); if(!reference) continue; relative_pose.setIdentity(); tracker.match(*reference, *current, relative_pose); std::cerr << tracker.itctx_.NumConstraints << " " << tracker.itctx_.Mean(0) << " " << tracker.itctx_.Mean(1) << " " << tracker.itctx_.Precision(0, 0) << " " << tracker.itctx_.Precision(1, 1) << std::endl; } */ for (std::vector<dvo_benchmark::RgbdPair>::iterator it = pairs.begin(); it != pairs.begin() +1 && ros::ok(); ++it) >>>>>>> b03cf72f26093998d182440c467fe0e5ff327d1c { reference = load(dataset + "/" + it->RgbFile(), dataset + "/" + it->DepthFile()); std::vector<dvo_benchmark::Groundtruth>::iterator nearest = std::adjacent_find(poses.begin(), poses.end(), FindNearestPosePredicate(*it)); if(nearest == poses.end()) continue; dvo_benchmark::toPoseEigen(*nearest, reference_pose); relative_pose.setIdentity(); bool first = true; int k = 0; <<<<<<< HEAD for (std::vector<dvo_benchmark::RgbdPair>::iterator it_inner = pairs.begin(); it_inner != pairs.end() && ros::ok(); ++it_inner, ++k) ======= for (std::vector<dvo_benchmark::RgbdPair>::iterator it_inner = it + 1; it_inner != pairs.end() && ros::ok(); ++it_inner, ++k) >>>>>>> b03cf72f26093998d182440c467fe0e5ff327d1c { std::vector<dvo_benchmark::Groundtruth>::iterator nearest = std::adjacent_find(poses.begin(), poses.end(), FindNearestPosePredicate(*it_inner)); if(nearest == poses.end()) continue; dvo_benchmark::toPoseEigen(*nearest, current_pose); current = load(dataset + "/" + it_inner->RgbFile(), dataset + "/" + it_inner->DepthFile()); relative_pose.setIdentity(); tracker.match(*reference, *current, relative_pose); if(first) { tracker.getInformationEstimate(first_info); first_error_precision = tracker.itctx_.Precision; first = false; } tracker.getInformationEstimate(current_info); double pose_entropy = std::log(current_info.determinant()); double loglikelihood = tracker.itctx_.Error; double err_i = tracker.itctx_.Mean(0); double err_z = tracker.itctx_.Mean(1); double translation_error = ((current_pose.inverse() * reference_pose) * relative_pose).translation().norm(); double translation_dist = (current_pose.inverse() * reference_pose).translation().norm(); std::cout << k << " " << pose_entropy << " " //<< loglikelihood << " " //<< err_i << " " //<< err_z << " " << translation_error << " " << translation_dist << " " << std::endl; } std::cerr << (pairs.begin() + 52 - it) << " "; } /* for (std::vector<dvo_benchmark::RgbdPair>::iterator it_inner = it + 1; it_inner != it + 100 && ros::ok(); ++it_inner, ++k) { std::vector<dvo_benchmark::Groundtruth>::iterator nearest = std::adjacent_find(poses.begin(), poses.end(), FindNearestPosePredicate(*it_inner)); if(nearest == poses.end()) continue; dvo_benchmark::toPoseEigen(*nearest, current_pose); current = load(dataset + "/" + it_inner->RgbFile(), dataset + "/" + it_inner->DepthFile()); cv::Scalar cur_avg_depth = cv::mean(current->level(0).depth, current->level(0).depth == current->level(0).depth); Eigen::Affine3d a1; a1.setIdentity(); Eigen::Matrix<double, 6, 6> fisher; tracker.match(*last, *current, a1); tracker.getInformationEstimate(fisher); current_se3 = Sophus::SE3(a1.rotation(), a1.translation()); accumulated_odom = accumulated_odom * a1; accumulated_se3 = Sophus::SE3(accumulated_odom.rotation(), accumulated_odom.translation()); propagated_cov = current_se3.Adj() * propagated_cov * current_se3.Adj().transpose() + fisher.inverse(); relative_pose = relative_pose.inverse(); tracker.match(*reference, *current, relative_pose); if(first) { tracker.getInformationEstimate(first_info); first_error_precision = tracker.itctx_.Precision; first = false; } tracker.getInformationEstimate(current_info); keyframe_cov = current_info.inverse(); current_se3 = Sophus::SE3(relative_pose.rotation(), relative_pose.translation()); Eigen::Matrix<double, 6, 1> diff = current_se3.log() - accumulated_se3.log(); double kl_divergence = 0.5 * ((keyframe_cov.inverse() * propagated_cov).trace() + diff.transpose() * keyframe_cov * diff - 2 - std::log(propagated_cov.determinant() / keyframe_cov.determinant())); double constraints = tracker.itctx_.NumConstraints; double pose_entropy = std::log(current_info.determinant()); double pose_normalized_entropy = std::log((current_info / constraints).determinant()); double error_entropy = std::log(tracker.itctx_.Precision.determinant()); <<<<<<< HEAD double translation_dist = relative_pose.translation().norm(); double true_translation_dist = (current_pose.inverse() * reference_pose).translation().norm(); double translation_error = ((current_pose.inverse() * reference_pose) * relative_pose).translation().norm(); std::cout << ref_avg_depth(0) << " " << cur_avg_depth(0) << " " << translation_dist << " " << translation_error << " " << constraints << " " << pose_entropy << " " << pose_normalized_entropy << " " << error_entropy << " " << true_translation_dist << " " << kl_divergence << " " << std::endl; last = current; ======= //double param_entropy_ratio = std::log(current_info.determinant()) / std::log(first_info.determinant()); double error_entropy_ratio = std::log(tracker.itctx_.Precision.determinant());// / std::log(first_error_precision.determinant()); //double param_divergence = JenBreLogDetDiv(first_info, current_info); //double error_divergence = JenBreLogDetDiv(first_error_precision, tracker.itctx_.Precision); double translation_dist = (current_pose.inverse() * reference_pose).translation().norm(); double translation_error = ((current_pose.inverse() * reference_pose) * relative_pose).translation().norm(); double frustum_metric = calculateSampledFrustumMetric(relative_pose, intrinsics); //std::cerr << (current_pose.inverse() * reference_pose).matrix() << std::endl << std::endl; //std::cerr << relative_pose.matrix() << std::endl << std::endl; //std::cerr << ((current_pose.inverse() * reference_pose) * relative_pose).matrix() << std::endl << std::endl; // //std::string tmp; //std::cin >> tmp; //std::cout << k << " " << translation_dist << " " << translation_error << " " << param_entropy_ratio << " " << param_divergence << " " << error_entropy_ratio << " " << error_divergence << std::endl; std::cout << k << " " << translation_dist << " " << translation_error << " " << error_entropy_ratio << " " << tracker.itctx_.Mean(0) << " " << tracker.itctx_.Mean(1) << " " << frustum_metric << std::endl; >>>>>>> b03cf72f26093998d182440c467fe0e5ff327d1c } std::cerr << (pairs.end() - 100 - it) << " "; } <<<<<<< HEAD */ ======= >>>>>>> b03cf72f26093998d182440c467fe0e5ff327d1c std::cerr << std::endl; //while(true) // cv::waitKey(10); }
36.294872
210
0.643942
[ "vector" ]
3ba2245415a69c184283ed274951c8370e7291b7
1,687
hpp
C++
homeworks/HW4Source/HW4/header/Acrobot.hpp
anshuman1811/cs687-reinforcementlearning
cf30cc0ab2b0e515cd4b643fc55c60cc5f38a481
[ "MIT" ]
null
null
null
homeworks/HW4Source/HW4/header/Acrobot.hpp
anshuman1811/cs687-reinforcementlearning
cf30cc0ab2b0e515cd4b643fc55c60cc5f38a481
[ "MIT" ]
null
null
null
homeworks/HW4Source/HW4/header/Acrobot.hpp
anshuman1811/cs687-reinforcementlearning
cf30cc0ab2b0e515cd4b643fc55c60cc5f38a481
[ "MIT" ]
null
null
null
#pragma once #include <stdafx.h> // Acrobot MDP - see Gridworld.hpp for comments regarding the general structure of these environment/MDP objects class Acrobot { public: Acrobot(); int getStateDim() const; int getNumActions() const; double update(const int & action, std::mt19937_64 & generator); std::vector<double> getState(std::mt19937_64 & generator); bool inTerminalState() const; void newEpisode(std::mt19937_64 & generator); private: // Standard parameters for the acrobot domain const double m1 = 1; // Mass of the first link const double m2 = 1; // Mass of the second link const double l1 = 1; // Length of the first link const double l2 = 1; // Length of the second link const double lc1 = .5; const double lc2 = .5; const double i1 = 1; const double i2 = 1; const double g = 9.8; // Acceleration due to gravity const double fmax = 1; // Maximum (and -minimum) force that can be applied const double dt = 0.2; // Time step duration const double integShritte = 10; // The larger this is, the more accurate the Runge-Kutta approximation double t; // Time into the episode double theta1; // Joint angle closest to the pivot double theta2; // Joint angle of the 'elbow' double theta1Dot; // Time derivative of theta1 double theta2Dot; // Time derivative of theta2 // Function used by the Runge-Kutta approximation void f(double s[4], double tau, double * buff); // Vars used by Runge-Kutta approx double s0_dot[4]; double s1_dot[4]; double s2_dot[4]; double s3_dot[4]; double hilf[4]; double ss[4]; double s1[4]; double s2[4]; double s3[4]; };
33.74
113
0.676349
[ "vector" ]
3ba34c028c7b14a9ac45f00e5bd06df384b6101a
2,342
cpp
C++
client/Classes/Model/Attacks/Projectiles/IceProjectile.cpp
plankes-projects/BaseWar
693f7d02fa324b917b28be58d33bb77a18d77f26
[ "Apache-2.0" ]
60
2015-01-03T07:31:14.000Z
2021-12-17T02:39:17.000Z
client/Classes/Model/Attacks/Projectiles/IceProjectile.cpp
plankes-projects/BaseWar
693f7d02fa324b917b28be58d33bb77a18d77f26
[ "Apache-2.0" ]
1
2018-08-17T09:59:30.000Z
2018-08-17T09:59:30.000Z
client/Classes/Model/Attacks/Projectiles/IceProjectile.cpp
plankes-projects/BaseWar
693f7d02fa324b917b28be58d33bb77a18d77f26
[ "Apache-2.0" ]
27
2015-01-22T06:55:10.000Z
2021-12-17T02:39:23.000Z
/* * ArrowProjectile.cpp * * Created on: 30.05.2013 * Author: Planke */ #include "IceProjectile.h" #include "../../../Tools/Tools.h" #include "../../Effects/IceEffect.h" #include "../../Model.h" IceProjectile::IceProjectile(std::string image, float height, float damage, DamageType damageType, float flightSpeed, float slowMultiplicatorBy, float slowDuration, std::string info, int numOfSlowedTargets, float rangeOfSlow) : Projectile(image, height, damage, damageType, flightSpeed) { initAnimations(); //loading the pictures and set the animations _slowMultiplicatorBy = slowMultiplicatorBy; _slowDuration = slowDuration; _projectileInfo = info; _numOfSlowedTargets = numOfSlowedTargets; _rangeOfSlow = rangeOfSlow; } IceProjectile::IceProjectile(float slowMultiplicatorBy, float slowDuration) : Projectile("iceProjectile.png", 20, MAGIC) { _slowMultiplicatorBy = slowMultiplicatorBy; _slowDuration = slowDuration; _projectileInfo = " - Slowing enemy by " + Tools::toString((int) (_slowMultiplicatorBy * 100)) + "% for " + Tools::toString((int) (_slowDuration / 1000)) + " sec."; _numOfSlowedTargets = 1; _rangeOfSlow = 200; } Projectile* IceProjectile::cloneWithDamage(float dmg) { return new IceProjectile(_image, _height, dmg, _damageType, _flightSpeed, _slowMultiplicatorBy, _slowDuration, _projectileInfo, _numOfSlowedTargets, _rangeOfSlow); } IceProjectile::~IceProjectile() { } void IceProjectile::onHit(Unit* target) { target->Receivedamage(_damage, _damageType); int numOfSlow = _numOfSlowedTargets; if (numOfSlow > 0) { target->applyEffect(new IceEffect(_slowDuration, _slowMultiplicatorBy, _slowMultiplicatorBy)); numOfSlow--; } //case of normal frost mage if (numOfSlow == 0) return; //slow rest units std::list<Unit*> enemyUnits = Model::getInstance()->getMyArmy(target->getArmyType())->getUnits(); for (std::list<Unit*>::iterator it = enemyUnits.begin(); it != enemyUnits.end(); ++it) { if (numOfSlow == 0) break; if ((*it) != target && (*it)->getHitpoints() > 0 && target->distanceTo((*it)) <= _rangeOfSlow) { numOfSlow--; (*it)->applyEffect(new IceEffect(_slowDuration, _slowMultiplicatorBy, _slowMultiplicatorBy)); } } } void IceProjectile::fillMoveAnimationPictures() { }
32.082192
155
0.706661
[ "model" ]
3ba37048755876a9e7dde23be1a8712be9c68b54
3,325
hpp
C++
src/util/tsv.hpp
ssameerr/pytubes
6b4a839b7503780930b667cf12053089bc66c027
[ "MIT" ]
null
null
null
src/util/tsv.hpp
ssameerr/pytubes
6b4a839b7503780930b667cf12053089bc66c027
[ "MIT" ]
null
null
null
src/util/tsv.hpp
ssameerr/pytubes
6b4a839b7503780930b667cf12053089bc66c027
[ "MIT" ]
null
null
null
#pragma once #include <cstdio> #include <vector> #include "error.hpp" #include "slice.hpp" #include "array.hpp" #include "../bytes.hpp" #include "skiplist.hpp" namespace ss { struct TsvHeader; struct TsvRow; struct TsvValueIter { ByteSlice row; ByteSlice cur; TsvValueIter(ByteSlice row) : row(row) { cur = row.slice_to_ptr(row.find_first('\t')); } inline void operator++() { if (cur.end() == row.end()) { row = ByteSlice::Null(); cur = ByteSlice::Null(); } else { row = row.slice_from(cur.len+1); cur = row.slice_to_ptr(row.find_first('\t')); } } inline ByteSlice operator*() const { return cur; } inline bool operator==(const TsvValueIter &other) const { return row.is(other.row); } inline bool operator!=(const TsvValueIter &other) const { return !row.is(other.row); } }; struct TsvRow{ using iterator = TsvValueIter; using const_iterator = const TsvValueIter; ByteSlice row; TsvHeader *header; TsvRow() {} TsvRow(ByteSlice row, TsvHeader *header) : row(row), header(header) {} inline iterator begin() const { return iterator(row); } inline iterator end() const { return iterator(ByteSlice::Null()); } inline void populate_slots(SkipList<ByteSlice> &skips) const { auto value = begin(); for (auto &skip : skips) { size_t to_skip = skip.skip; while(to_skip--){ ++value; if (value == end()) { return; } } *(skip.destination) = *value; } } }; struct TsvHeader { Array<ByteSlice> fields; Array<ByteString> stored_fields; bool have_headers = false; void read(TsvRow &row) { std::vector<ByteString> field_vec; throw_if(ValueError, have_headers, "Trying to read header row, but already have headers"); for (auto val : row) { field_vec.emplace_back(val); } stored_fields = field_vec; fields = Array<ByteSlice>(stored_fields.size); std::transform(stored_fields.begin(), stored_fields.end(), fields.begin(), [](ByteString &x){ return ByteSlice(x); }); have_headers = true; } SkipList<ByteSlice> make_skip_list(const Array<ByteSlice> &out_fields, const Array<ByteSlice> &slots) { SkipList<ByteSlice> skips; throw_if(ValueError, out_fields.size != slots.size, "Tried to apply TSV header with incorrect values"); throw_if(ValueError, !have_headers, "Tried to apply uninitialized TSV header"); // This is N*M, but /probably/ doesn't matter, I'm happy to be wrong about this size_t last_header_index = 0; for (size_t header_index = 0; header_index < stored_fields.size; ++header_index){ for (size_t slot_index = 0; slot_index < slots.size; ++slot_index){ auto &out_field = out_fields[slot_index]; if (out_field == fields[header_index]) { size_t skip = header_index - last_header_index; skips.emplace_back(skip, &slots[slot_index]); last_header_index = header_index; break; } } } return skips; } }; }
28.913043
126
0.59188
[ "vector", "transform" ]
3ba6c86a9ec68cd7f8eeb844453f013ed0a838a7
27,312
cpp
C++
src/webots/nodes/WbMotor.cpp
HarpieRapace45/webots
ec3caee701c50b82925e76c638018d79de0067ea
[ "Apache-2.0" ]
327
2018-11-05T14:10:11.000Z
2019-09-03T04:21:17.000Z
src/webots/nodes/WbMotor.cpp
HarpieRapace45/webots
ec3caee701c50b82925e76c638018d79de0067ea
[ "Apache-2.0" ]
712
2018-12-18T08:07:35.000Z
2019-09-02T14:47:03.000Z
src/webots/nodes/WbMotor.cpp
HarpieRapace45/webots
ec3caee701c50b82925e76c638018d79de0067ea
[ "Apache-2.0" ]
146
2018-12-18T09:09:43.000Z
2019-09-03T08:00:33.000Z
// Copyright 1996-2021 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. // // WbMotor.cpp // #include "WbMotor.hpp" #include "WbDownloader.hpp" #include "WbField.hpp" #include "WbFieldChecker.hpp" #include "WbJoint.hpp" #include "WbJointParameters.hpp" #include "WbMuscle.hpp" #include "WbPropeller.hpp" #include "WbRobot.hpp" #include "WbSensor.hpp" #include "WbSolid.hpp" #include "WbSoundEngine.hpp" #include "WbTrack.hpp" #include "WbUrl.hpp" #include <ode/ode.h> #include <QtCore/QDataStream> #include <QtCore/QUrl> #include <cassert> #include <cmath> #include "../../controller/c/messages.h" // contains the definitions for the macros C_SET_SAMPLING_PERIOD, C_MOTOR_SET_POSITION, C_MOTOR_SET_VELOCITY ... QList<const WbMotor *> WbMotor::cMotors; void WbMotor::init() { mHasAllocatedJointFeedback = false; mForceOrTorqueSensor = NULL; mNeedToConfigure = false; mSoundClip = NULL; mForceOrTorqueLastValue = 0.0; mKinematicVelocitySign = 0; mRequestedDeviceTag = NULL; mCoupledMotors.clear(); mMotorForceOrTorque = 0.0; mTargetVelocity = 0.0; mTargetPosition = 0.0; mCurrentVelocity = 0.0; mRawInput = 0.0; mUserControl = false; mErrorIntegral = 0.0; mPreviousError = 0.0; mMaxForceOrTorque = NULL; mAcceleration = findSFDouble("acceleration"); mConsumptionFactor = findSFDouble("consumptionFactor"); mControlPID = findSFVector3("controlPID"); mMinPosition = findSFDouble("minPosition"); mMaxPosition = findSFDouble("maxPosition"); mMaxVelocity = findSFDouble("maxVelocity"); mMultiplier = findSFDouble("multiplier"); mSound = findSFString("sound"); mMuscles = findMFNode("muscles"); mDownloader = NULL; } WbMotor::WbMotor(const QString &modelName, WbTokenizer *tokenizer) : WbJointDevice(modelName, tokenizer) { init(); } WbMotor::WbMotor(const WbMotor &other) : WbJointDevice(other), mChangedAssociatedDevices() { init(); } WbMotor::WbMotor(const WbNode &other) : WbJointDevice(other) { init(); } WbMotor::~WbMotor() { delete mForceOrTorqueSensor; // notify siblings about removal for (int i = 0; i < mCoupledMotors.size(); ++i) mCoupledMotors[i]->removeFromCoupledMotors(this); cMotors.removeAll(this); } void WbMotor::downloadAssets() { const QString &sound = mSound->value(); if (WbUrl::isWeb(sound)) { mDownloader = new WbDownloader(this); if (isPostFinalizedCalled()) connect(mDownloader, &WbDownloader::complete, this, &WbMotor::updateSound); mDownloader->download(QUrl(sound)); } } void WbMotor::preFinalize() { WbJointDevice::preFinalize(); cMotors << this; // note: only parameter validity check has to occur in preFinalize, validity across couplings must be done in postFinalize updateMaxVelocity(); updateMaxAcceleration(); updateControlPID(); updateMinAndMaxPosition(); updateMultiplier(); updateSound(); mForceOrTorqueSensor = new WbSensor(); const WbJoint *const j = joint(); mTargetPosition = j ? position() : 0.0; mMotorForceOrTorque = mMaxForceOrTorque->value(); updateMaxForceOrTorque(); } void WbMotor::postFinalize() { WbJointDevice::postFinalize(); assert(robot()); if (!mMuscles->isEmpty() || robot()->maxEnergy() > 0) setupJointFeedback(); inferMotorCouplings(); // it also checks consistency across couplings // must be done in the postFinalize step as the coupled motor consistency check could change the values mTargetVelocity = mMaxVelocity->value(); mNeedToConfigure = true; // notify libController about the changes done by the check WbMFIterator<WbMFNode, WbNode *> it(mMuscles); while (it.hasNext()) dynamic_cast<WbMuscle *>(it.next())->postFinalize(); connect(mMultiplier, &WbSFDouble::changed, this, &WbMotor::updateMultiplier); connect(mMaxVelocity, &WbSFDouble::changed, this, &WbMotor::updateMaxVelocity); connect(mAcceleration, &WbSFDouble::changed, this, &WbMotor::updateMaxAcceleration); connect(mControlPID, &WbSFVector3::changed, this, &WbMotor::updateControlPID); connect(mMinPosition, &WbSFDouble::changed, this, &WbMotor::updateMinAndMaxPosition); connect(mMaxPosition, &WbSFDouble::changed, this, &WbMotor::updateMinAndMaxPosition); connect(mMinPosition, &WbSFDouble::changed, this, &WbMotor::minPositionChanged); connect(mMaxPosition, &WbSFDouble::changed, this, &WbMotor::maxPositionChanged); connect(mSound, &WbSFString::changed, this, &WbMotor::updateSound); connect(mMuscles, &WbSFNode::changed, this, &WbMotor::updateMuscles); connect(mMaxForceOrTorque, &WbSFDouble::changed, this, &WbMotor::updateMaxForceOrTorque); connect(mDeviceName, &WbSFString::changed, this, &WbMotor::inferMotorCouplings); } void WbMotor::createWrenObjects() { WbJointDevice::createWrenObjects(); WbMFIterator<WbMFNode, WbNode *> it(mMuscles); while (it.hasNext()) dynamic_cast<WbMuscle *>(it.next())->createWrenObjects(); } void WbMotor::setupJointFeedback() { const WbJoint *const j = joint(); if (!j) return; dJointID jID = j->jointID(); if (!jID) return; // check whether a feedback structure was already registered by a physics plugin // or a wb_motor_enable_force_feedback/wb_motor_enable_torque_feedback call, // otherwise create own structure dJointFeedback *fb = dJointGetFeedback(jID); if (fb) // already set return; fb = new dJointFeedback; dJointSetFeedback(jID, fb); } double WbMotor::energyConsumption() const { if (dynamic_cast<WbTrack *>(parentNode())) return 0.0; return fabs(computeFeedback()) * mConsumptionFactor->value(); } void WbMotor::inferMotorCouplings() { // remove the reference to this motor from any of the siblings (necessary in the event of name changes from the interface) for (int i = 0; i < mCoupledMotors.size(); ++i) mCoupledMotors[i]->removeFromCoupledMotors(this); // clear references to my siblings mCoupledMotors.clear(); // rebuild the sibling list const QStringList nameChunks = deviceName().split("::"); if (nameChunks.size() != 2) // name structure: "motor name::specifier name". Coupling is determined by the motor name part return; for (int i = 0; i < cMotors.size(); ++i) { QStringList otherNameChunks = cMotors[i]->deviceName().split("::"); if (otherNameChunks.size() != 2) continue; if (robot() == cMotors[i]->robot() && cMotors[i]->tag() != tag() && nameChunks[0] == otherNameChunks[0] && !mCoupledMotors.contains(const_cast<WbMotor *>(cMotors[i]))) { mCoupledMotors.append(const_cast<WbMotor *>(cMotors[i])); mCoupledMotors.last()->addToCoupledMotors(this); // add myself to the newly added sibling } } if (deviceName().contains("::") && mCoupledMotors.size() == 0) parsingWarn(tr("Motor '%1' uses the coupled motor name structure but does not have any siblings.").arg(deviceName())); checkMultiplierAcrossCoupledMotors(); // it calls all the other checks implicitly } ///////////// // Updates // ///////////// void WbMotor::updateMinAndMaxPosition() { enforceMotorLimitsInsideJointLimits(); if (isPreFinalizedCalled()) checkMinAndMaxPositionAcrossCoupledMotors(); mNeedToConfigure = true; } void WbMotor::updateMaxForceOrTorque() { WbFieldChecker::resetDoubleIfNegative(this, mMaxForceOrTorque, 10.0); mNeedToConfigure = true; } void WbMotor::updateMaxVelocity() { WbFieldChecker::resetDoubleIfNegative(this, mMaxVelocity, -mMaxVelocity->value()); if (mCoupledMotors.size() > 0 && isPreFinalizedCalled()) checkMaxVelocityAcrossCoupledMotors(); mNeedToConfigure = true; } void WbMotor::updateMultiplier() { if (multiplier() == 0.0) { parsingWarn(tr("The value of 'multiplier' cannot be 0. Value reverted to 1.")); mMultiplier->setValue(1.0); } if (isPreFinalizedCalled()) { checkMultiplierAcrossCoupledMotors(); } mNeedToConfigure = true; } void WbMotor::updateControlPID() { const WbVector3 &pid = mControlPID->value(); const double p = pid.x(); if (p <= 0.0) parsingWarn(tr("'controlP' (currently %1) must be positive.").arg(p)); const double i = pid.y(); if (i < 0.0) parsingWarn(tr("'controlI' (currently %1) must be non-negative.").arg(i)); const double d = pid.z(); if (d < 0.0) parsingWarn(tr("'controlD' (currently %1) must be non-negative.").arg(d)); mErrorIntegral = 0.0; mPreviousError = 0.0; mNeedToConfigure = true; } void WbMotor::updateSound() { const QString &sound = mSound->value(); if (sound.isEmpty()) mSoundClip = NULL; else if (isPostFinalizedCalled() && WbUrl::isWeb(sound) && mDownloader == NULL) { downloadAssets(); return; } else if (!mDownloader) mSoundClip = WbSoundEngine::sound(WbUrl::computePath(this, "sound", sound)); else { if (mDownloader->error().isEmpty()) mSoundClip = WbSoundEngine::sound(sound, mDownloader->device()); else { mSoundClip = NULL; warn(mDownloader->error()); } delete mDownloader; mDownloader = NULL; } WbSoundEngine::clearAllMotorSoundSources(); } void WbMotor::updateMuscles() { setupJointFeedback(); } void WbMotor::updateMaxAcceleration() { WbFieldChecker::resetDoubleIfNegativeAndNotDisabled(this, mAcceleration, -1, -1); mNeedToConfigure = true; } /////////////////// // Plain setters // /////////////////// void WbMotor::setMaxVelocity(double v) { mMaxVelocity->setValue(v); awake(); } void WbMotor::setMaxAcceleration(double acc) { mAcceleration->setValue(acc); awake(); } ///////////////// // API setters // ///////////////// void WbMotor::setTargetPosition(double position) { const double maxp = mMaxPosition->value(); const double minp = mMinPosition->value(); const bool velocityControl = std::isinf(position); // negative multipliers could turn the +inf into a -inf mTargetPosition = velocityControl ? position : position * multiplier(); if (maxp != minp && !velocityControl) { if (mTargetPosition > maxp) { mTargetPosition = maxp; warn(QString("too big requested position: %1 > %2").arg(position).arg(maxp)); } else if (mTargetPosition < minp) { mTargetPosition = minp; warn(QString("too low requested position: %1 < %2").arg(position).arg(minp)); } } mUserControl = false; mNeedToConfigure = true; // each sibling has to notify libcontroller about velocityControl/positionControl awake(); } void WbMotor::setVelocity(double velocity) { mTargetVelocity = velocity * multiplier(); const double m = mMaxVelocity->value(); if (fabs(mTargetVelocity) > m) { warn(tr("The requested velocity %1 exceeds 'maxVelocity' = %2.").arg(mTargetVelocity).arg(m)); mTargetVelocity = mTargetVelocity >= 0.0 ? m : -m; } mNeedToConfigure = true; // each sibling has to notify libcontroller about velocityControl/positionControl awake(); } void WbMotor::setAcceleration(double acceleration) { // note: a check is performed on libController side for negative values mAcceleration->setValue(acceleration); // mAcceleration specifies maximal acceleration, hence it isn't multiplied awake(); } void WbMotor::setForceOrTorque(double forceOrTorque) { if (!mUserControl) // we were previously using motor force turnOffMotor(); mUserControl = true; mRawInput = forceOrTorque * multiplier(); if (fabs(mRawInput) > mMotorForceOrTorque) { if (mCoupledMotors.size() == 0) { // silence warning for coupled motors if (nodeType() == WB_NODE_ROTATIONAL_MOTOR) warn(tr("The requested motor torque %1 exceeds 'maxTorque' = %2").arg(mRawInput).arg(mMotorForceOrTorque)); else warn(tr("The requested motor force %1 exceeds 'maxForce' = %2").arg(mRawInput).arg(mMotorForceOrTorque)); } mRawInput = mRawInput >= 0.0 ? mMotorForceOrTorque : -mMotorForceOrTorque; } awake(); } void WbMotor::setAvailableForceOrTorque(double availableForceOrTorque) { // note: a check is performed on libController side for negative values mMotorForceOrTorque = availableForceOrTorque; const double m = mMaxForceOrTorque->value(); if (mMotorForceOrTorque > m) { if (mCoupledMotors.size() == 0) { // silence warning for coupled motors if (nodeType() == WB_NODE_ROTATIONAL_MOTOR) warn(tr("The requested available motor torque %1 exceeds 'maxTorque' = %2").arg(mMotorForceOrTorque).arg(m)); else warn(tr("The requested available motor force %1 exceeds 'maxForce' = %2").arg(mMotorForceOrTorque).arg(m)); } mMotorForceOrTorque = m; } awake(); } double WbMotor::computeCurrentDynamicVelocity(double ms, double position) { if (mMotorForceOrTorque == 0.0) { // no control mCurrentVelocity = 0.0; return mCurrentVelocity; } // compute required velocity double velocity = -mTargetVelocity; if (!std::isinf(mTargetPosition)) { // PID-position control const double error = mTargetPosition - position; const double ts = ms * 0.001; mErrorIntegral += error * ts; const double errorDerivative = (error - mPreviousError) / ts; const double outputValue = mControlPID->value().x() * error + mControlPID->value().y() * mErrorIntegral + mControlPID->value().z() * errorDerivative; mPreviousError = error; if (fabs(outputValue) < fabs(mTargetVelocity)) velocity = -outputValue; else velocity = outputValue > 0.0 ? -fabs(mTargetVelocity) : fabs(mTargetVelocity); } // try to get closer to velocity double acc = mAcceleration->value(); if (acc == -1.0) mCurrentVelocity = velocity; // use maximum force/torque else { const double ts = ms * 0.001; double d = fabs(velocity - mCurrentVelocity) / ts; // requested acceleration if (d < acc) acc = d; if (velocity > mCurrentVelocity) mCurrentVelocity += acc * ts; else mCurrentVelocity -= acc * ts; } return mCurrentVelocity; } // run control without physics simulation bool WbMotor::runKinematicControl(double ms, double &position) { static const double TARGET_POSITION_THRESHOLD = 1e-6; bool doNothing = false; if (std::isinf(mTargetPosition)) { // velocity control const double maxp = mMaxPosition->value(); const double minp = mMinPosition->value(); doNothing = maxp != minp && ((position >= maxp && mTargetVelocity >= 0.0) || (position <= minp && mTargetVelocity <= 0.0)); } else doNothing = fabs(mTargetPosition - position) < TARGET_POSITION_THRESHOLD; if (doNothing) { mCurrentVelocity = 0.0; mKinematicVelocitySign = 0; return false; } const double ts = ms * 0.001; double acc = mAcceleration->value(); if (acc == -1.0 || acc > mMotorForceOrTorque) acc = mMotorForceOrTorque; static const double TARGET_VELOCITY_THRESHOLD = 1e-6; if (fabs(mTargetVelocity - mCurrentVelocity) > TARGET_VELOCITY_THRESHOLD) { // didn't reach the target velocity yet if (mTargetVelocity > mCurrentVelocity) { mCurrentVelocity += acc * ts; if (mCurrentVelocity > mTargetVelocity) mCurrentVelocity = mTargetVelocity; } else { mCurrentVelocity -= acc * ts; if (mCurrentVelocity < mTargetVelocity) mCurrentVelocity = mTargetVelocity; } } if (mTargetPosition > position) { mKinematicVelocitySign = 1; position += mCurrentVelocity * ts; if (position > mTargetPosition) position = mTargetPosition; } else { mKinematicVelocitySign = -1; position -= mCurrentVelocity * ts; if (position < mTargetPosition) position = mTargetPosition; } return true; } void WbMotor::powerOn(bool e) { // called when running out of energy with e=false WbDevice::powerOn(e); if (!e) mMotorForceOrTorque = 0.0; else mMotorForceOrTorque = mMaxForceOrTorque->value(); } bool WbMotor::isConfigureDone() const { return robot()->isConfigureDone(); } void WbMotor::checkMinAndMaxPositionAcrossCoupledMotors() { // if the position is unlimited for this motor, the coupled ones must also be for (int i = 0; i < mCoupledMotors.size(); ++i) { if (isPositionUnlimited() && !mCoupledMotors[i]->isPositionUnlimited()) { parsingWarn( tr("For coupled motors, if one has unlimited position, its siblings must have unlimited position as well. Adjusting " "'minPosition' and 'maxPosition' to 0 for motor '%1'.") .arg(deviceName())); mCoupledMotors[i]->setMinPosition(0); mCoupledMotors[i]->setMaxPosition(0); } } // if the position is limited for this motor, adjust the limits of the siblings accordingly if (!isPositionUnlimited()) { for (int i = 0; i < mCoupledMotors.size(); ++i) { double potentialMinimalPosition = minPosition() * mCoupledMotors[i]->multiplier() / multiplier(); double potentialMaximalPosition = maxPosition() * mCoupledMotors[i]->multiplier() / multiplier(); if (potentialMaximalPosition < potentialMinimalPosition) { // swap values for consistency const double tmp = potentialMaximalPosition; potentialMaximalPosition = potentialMinimalPosition; potentialMinimalPosition = tmp; } if (mCoupledMotors[i]->minPosition() != potentialMinimalPosition) { parsingWarn(tr("When using coupled motors, 'minPosition' must be consistent across devices. Adjusting 'minPosition' " "from %1 to %2 for motor '%3'.") .arg(mCoupledMotors[i]->minPosition()) .arg(potentialMinimalPosition) .arg(deviceName())); mCoupledMotors[i]->setMinPosition(potentialMinimalPosition); } if (mCoupledMotors[i]->maxPosition() != potentialMaximalPosition) { parsingWarn(tr("When using coupled motors, 'maxPosition' must be consistent across devices. Adjusting 'maxPosition' " "from %1 to %2 for motor '%3'.") .arg(mCoupledMotors[i]->maxPosition()) .arg(potentialMaximalPosition) .arg(deviceName())); mCoupledMotors[i]->setMaxPosition(potentialMaximalPosition); } } } } void WbMotor::enforceMotorLimitsInsideJointLimits() { if (isPositionUnlimited()) return; WbJoint *parentJoint = dynamic_cast<WbJoint *>(parentNode()); double p = 0.0; if (parentJoint) { if (positionIndex() == 1 && parentJoint->parameters()) p = parentJoint->parameters()->position(); if (positionIndex() == 2 && parentJoint->parameters2()) p = parentJoint->parameters2()->position(); if (positionIndex() == 3 && parentJoint->parameters3()) p = parentJoint->parameters3()->position(); } // current joint position should lie between min and max position WbFieldChecker::resetDoubleIfLess(this, mMaxPosition, p, p); WbFieldChecker::resetDoubleIfGreater(this, mMinPosition, p, p); } void WbMotor::checkMaxVelocityAcrossCoupledMotors() { // assume this motor is pushed to its limit, ensure the sibling limits aren't broken for (int i = 0; i < mCoupledMotors.size(); ++i) { const double potentialMaximalVelocity = maxVelocity() * fabs(mCoupledMotors[i]->multiplier()) / fabs(multiplier()); if (mCoupledMotors[i]->maxVelocity() != potentialMaximalVelocity) { parsingWarn(tr("When using coupled motors, velocity limits must be consistent across devices. Adjusted 'maxVelocity' " "from %1 to %2 for motor '%3'.") .arg(mCoupledMotors[i]->maxVelocity()) .arg(potentialMaximalVelocity) .arg(deviceName())); mCoupledMotors[i]->setMaxVelocity(potentialMaximalVelocity); } } } void WbMotor::checkMultiplierAcrossCoupledMotors() { if (mCoupledMotors.size() == 0) return; checkMinAndMaxPositionAcrossCoupledMotors(); checkMaxVelocityAcrossCoupledMotors(); } ///////////// // Control // ///////////// void WbMotor::addConfigureToStream(QDataStream &stream) { stream << (unsigned short)tag(); stream << (unsigned char)C_CONFIGURE; stream << (int)type(); stream << (double)mMinPosition->value(); stream << (double)mMaxPosition->value(); stream << (double)mMaxVelocity->value(); stream << (double)mAcceleration->value(); stream << (double)mMaxForceOrTorque->value(); stream << (double)mControlPID->value().x(); stream << (double)mControlPID->value().y(); stream << (double)mControlPID->value().z(); stream << (double)mTargetPosition; stream << (double)mTargetVelocity; stream << (double)mMultiplier->value(); mNeedToConfigure = false; } void WbMotor::writeConfigure(QDataStream &stream) { if (mForceOrTorqueSensor) mForceOrTorqueSensor->connectToRobotSignal(robot()); addConfigureToStream(stream); } void WbMotor::enableMotorFeedback(int rate) { const WbJoint *const j = joint(); if (j == NULL) { warn(tr("Feedback is available for motorized joints only")); return; } const WbSolid *const s = j->solidEndPoint(); if (s == NULL) { warn(nodeType() == WB_NODE_ROTATIONAL_MOTOR ? tr("wb_motor_enable_torque_feedback(): cannot be invoked for a Joint with no end point.") : tr("wb_motor_enable_force_feedback(): cannot be invoked for a Joint with no end point.")); return; } if (s->physics() == NULL) { warn(nodeType() == WB_NODE_ROTATIONAL_MOTOR ? tr("wb_motor_enable_torque_feedback(): cannot be invoked for a Joint whose end point has no Physics node.") : tr("wb_motor_enable_force_feedback(): cannot be invoked for a Joint whose end point has no Physics node.")); return; } const WbSolid *const us = j->upperSolid(); if (us->physics() == NULL) { warn(nodeType() == WB_NODE_ROTATIONAL_MOTOR ? tr("wb_motor_enable_torque_feedback(): cannot be invoked because the parent Solid has no Physics node.") : tr("wb_motor_enable_force_feedback(): cannot be invoked because the parent Solid has no Physics node.")); return; } dJointID jID = j->jointID(); if (!mForceOrTorqueSensor->isEnabled() && rate) { // switch on feedback // check if a feedback structure was already registered by the physics plugin // or some energy measurement requirement, otherwise create own structure dJointFeedback *fb = dJointGetFeedback(jID); if (!fb) { fb = new dJointFeedback; dJointSetFeedback(jID, fb); mHasAllocatedJointFeedback = true; } } else if (mForceOrTorqueSensor->isEnabled() && !rate) { // switching off feedback if (mHasAllocatedJointFeedback) { const dJointFeedback *const fb = dJointGetFeedback(jID); delete fb; dJointSetFeedback(jID, NULL); mHasAllocatedJointFeedback = false; } } mForceOrTorqueSensor->setRefreshRate(rate); } void WbMotor::handleMessage(QDataStream &stream) { short command; stream >> command; switch (command) { case C_MOTOR_SET_POSITION: { double position; stream >> position; setTargetPosition(position); // relay target position to coupled motors, if any for (int i = 0; i < mCoupledMotors.size(); ++i) mCoupledMotors[i]->setTargetPosition(position); break; } case C_MOTOR_SET_VELOCITY: { double velocity; stream >> velocity; setVelocity(velocity); // relay target velocity to coupled motors, if any for (int i = 0; i < mCoupledMotors.size(); ++i) mCoupledMotors[i]->setVelocity(velocity); break; } case C_MOTOR_SET_ACCELERATION: { double acceleration; stream >> acceleration; setAcceleration(acceleration); break; } case C_MOTOR_SET_FORCE: { double forceOrTorque; stream >> forceOrTorque; setForceOrTorque(forceOrTorque); for (int i = 0; i < mCoupledMotors.size(); ++i) mCoupledMotors[i]->setForceOrTorque(forceOrTorque); break; } case C_MOTOR_SET_AVAILABLE_FORCE: { double availableForceOrTorque; stream >> availableForceOrTorque; setAvailableForceOrTorque(availableForceOrTorque); break; } case C_MOTOR_SET_CONTROL_PID: { double controlP, controlI, controlD; stream >> controlP; stream >> controlI; stream >> controlD; mControlPID->setValue(controlP, controlI, controlD); awake(); break; } case C_MOTOR_FEEDBACK: { short rate; stream >> rate; enableMotorFeedback(rate); break; } case C_MOTOR_GET_ASSOCIATED_DEVICE: { short deviceType; stream >> deviceType; assert(mRequestedDeviceTag == NULL); mRequestedDeviceTag = new WbDeviceTag[1]; WbLogicalDevice *device = getSiblingDeviceByType(deviceType); mRequestedDeviceTag[0] = device ? device->tag() : 0; break; } default: assert(0); // Invalid command. } } void WbMotor::writeAnswer(QDataStream &stream) { if (mForceOrTorqueSensor && (refreshSensorIfNeeded() || mForceOrTorqueSensor->hasPendingValue())) { stream << tag(); stream << (unsigned char)C_MOTOR_FEEDBACK; stream << (double)mForceOrTorqueLastValue; mForceOrTorqueSensor->resetPendingValue(); } if (mRequestedDeviceTag != NULL) { stream << tag(); stream << (unsigned char)C_MOTOR_GET_ASSOCIATED_DEVICE; stream << (unsigned short)mRequestedDeviceTag[0]; delete[] mRequestedDeviceTag; mRequestedDeviceTag = NULL; } if (mNeedToConfigure) addConfigureToStream(stream); } bool WbMotor::refreshSensorIfNeeded() { if (isPowerOn() && mForceOrTorqueSensor && mForceOrTorqueSensor->needToRefresh()) { mForceOrTorqueLastValue = computeFeedback(); mForceOrTorqueSensor->updateTimer(); return true; } return false; } void WbMotor::reset(const QString &id) { WbJointDevice::reset(id); turnOffMotor(); mTargetVelocity = mMaxVelocity->value(); mCurrentVelocity = 0.0; mUserControl = false; mRawInput = 0.0; const WbJoint *const j = joint(); mTargetPosition = j ? position() : 0.0; mErrorIntegral = 0.0; mPreviousError = 0.0; mMotorForceOrTorque = mMaxForceOrTorque->value(); } void WbMotor::awake() const { const WbJoint *const j = joint(); if (j) { WbSolid *const s = j->solidEndPoint(); if (s) s->awake(); return; } const WbPropeller *const p = propeller(); const WbTrack *const t = dynamic_cast<WbTrack *>(parentNode()); if (p || t) { WbSolid *const s = upperSolid(); assert(s); s->awake(); } } void WbMotor::addToCoupledMotors(WbMotor *motor) { if (!mCoupledMotors.contains(motor)) mCoupledMotors.append(motor); } void WbMotor::resetPhysics() { mCurrentVelocity = 0; } QList<const WbBaseNode *> WbMotor::findClosestDescendantNodesWithDedicatedWrenNode() const { QList<const WbBaseNode *> list; WbMFIterator<WbMFNode, WbNode *> it(mMuscles); while (it.hasNext()) list << static_cast<WbBaseNode *>(it.next()); return list; }
32.826923
154
0.684681
[ "solid" ]
3baa02bb1958009d8120475c2cba3d2fc53488a9
6,637
cpp
C++
testbed/tests/character_collision.cpp
CriticalCreator/box2d
1025f9a10949b963d6311995910bdd04f72dae6c
[ "MIT" ]
4
2021-04-09T06:07:18.000Z
2021-11-22T08:02:51.000Z
testbed/tests/character_collision.cpp
CriticalCreator/box2d
1025f9a10949b963d6311995910bdd04f72dae6c
[ "MIT" ]
null
null
null
testbed/tests/character_collision.cpp
CriticalCreator/box2d
1025f9a10949b963d6311995910bdd04f72dae6c
[ "MIT" ]
2
2021-04-23T16:52:44.000Z
2021-06-04T03:24:46.000Z
// MIT License // Copyright (c) 2019 Erin Catto // 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 "test.h" /// This is a test of typical character collision scenarios. This does not /// show how you should implement a character in your application. /// Instead this is used to test smooth collision on edge chains. class CharacterCollision : public Test { public: CharacterCollision() { // Ground body { b2BodyDef bd; b2Body* ground = m_world->CreateBody(&bd); b2EdgeShape shape; shape.Set(b2Vec2(-20.0f, 0.0f), b2Vec2(20.0f, 0.0f)); ground->CreateFixture(&shape, 0.0f); } // Collinear edges with no adjacency information. // This shows the problematic case where a box shape can hit // an internal vertex. { b2BodyDef bd; b2Body* ground = m_world->CreateBody(&bd); b2EdgeShape shape; shape.Set(b2Vec2(-8.0f, 1.0f), b2Vec2(-6.0f, 1.0f)); ground->CreateFixture(&shape, 0.0f); shape.Set(b2Vec2(-6.0f, 1.0f), b2Vec2(-4.0f, 1.0f)); ground->CreateFixture(&shape, 0.0f); shape.Set(b2Vec2(-4.0f, 1.0f), b2Vec2(-2.0f, 1.0f)); ground->CreateFixture(&shape, 0.0f); } // Chain shape { b2BodyDef bd; bd.angle = 0.25f * b2_pi; b2Body* ground = m_world->CreateBody(&bd); b2Vec2 vs[4]; vs[0].Set(5.0f, 7.0f); vs[1].Set(6.0f, 8.0f); vs[2].Set(7.0f, 8.0f); vs[3].Set(8.0f, 7.0f); b2ChainShape shape; shape.CreateChain(vs, 4); ground->CreateFixture(&shape, 0.0f); } // Square tiles. This shows that adjacency shapes may // have non-smooth collision. There is no solution // to this problem. { b2BodyDef bd; b2Body* ground = m_world->CreateBody(&bd); b2PolygonShape shape; shape.SetAsBox(1.0f, 1.0f, b2Vec2(4.0f, 3.0f), 0.0f); ground->CreateFixture(&shape, 0.0f); shape.SetAsBox(1.0f, 1.0f, b2Vec2(6.0f, 3.0f), 0.0f); ground->CreateFixture(&shape, 0.0f); shape.SetAsBox(1.0f, 1.0f, b2Vec2(8.0f, 3.0f), 0.0f); ground->CreateFixture(&shape, 0.0f); } // Square made from an edge loop. Collision should be smooth. { b2BodyDef bd; b2Body* ground = m_world->CreateBody(&bd); b2Vec2 vs[4]; vs[0].Set(-1.0f, 3.0f); vs[1].Set(1.0f, 3.0f); vs[2].Set(1.0f, 5.0f); vs[3].Set(-1.0f, 5.0f); b2ChainShape shape; shape.CreateLoop(vs, 4); ground->CreateFixture(&shape, 0.0f); } // Edge loop. Collision should be smooth. { b2BodyDef bd; bd.position.Set(-10.0f, 4.0f); b2Body* ground = m_world->CreateBody(&bd); b2Vec2 vs[10]; vs[0].Set(0.0f, 0.0f); vs[1].Set(6.0f, 0.0f); vs[2].Set(6.0f, 2.0f); vs[3].Set(4.0f, 1.0f); vs[4].Set(2.0f, 2.0f); vs[5].Set(0.0f, 2.0f); vs[6].Set(-2.0f, 2.0f); vs[7].Set(-4.0f, 3.0f); vs[8].Set(-6.0f, 2.0f); vs[9].Set(-6.0f, 0.0f); b2ChainShape shape; shape.CreateLoop(vs, 10); ground->CreateFixture(&shape, 0.0f); } // Square character 1 { b2BodyDef bd; bd.position.Set(-3.0f, 8.0f); bd.type = b2_dynamicBody; bd.fixedRotation = true; bd.allowSleep = false; b2Body* body = m_world->CreateBody(&bd); b2PolygonShape shape; shape.SetAsBox(0.5f, 0.5f); b2FixtureDef fd; fd.shape = &shape; fd.density = 20.0f; body->CreateFixture(&fd); } // Square character 2 { b2BodyDef bd; bd.position.Set(-5.0f, 5.0f); bd.type = b2_dynamicBody; bd.fixedRotation = true; bd.allowSleep = false; b2Body* body = m_world->CreateBody(&bd); b2PolygonShape shape; shape.SetAsBox(0.25f, 0.25f); b2FixtureDef fd; fd.shape = &shape; fd.density = 20.0f; body->CreateFixture(&fd); } // Hexagon character { b2BodyDef bd; bd.position.Set(-5.0f, 8.0f); bd.type = b2_dynamicBody; bd.fixedRotation = true; bd.allowSleep = false; b2Body* body = m_world->CreateBody(&bd); float angle = 0.0f; float delta = b2_pi / 3.0f; b2Vec2 vertices[6]; for (int32 i = 0; i < 6; ++i) { vertices[i].Set(0.5f * cosf(angle), 0.5f * sinf(angle)); angle += delta; } b2PolygonShape shape; shape.Set(vertices, 6); b2FixtureDef fd; fd.shape = &shape; fd.density = 20.0f; body->CreateFixture(&fd); } // Circle character { b2BodyDef bd; bd.position.Set(3.0f, 5.0f); bd.type = b2_dynamicBody; bd.fixedRotation = true; bd.allowSleep = false; b2Body* body = m_world->CreateBody(&bd); b2CircleShape shape; shape.m_radius = 0.5f; b2FixtureDef fd; fd.shape = &shape; fd.density = 20.0f; body->CreateFixture(&fd); } // Circle character { b2BodyDef bd; bd.position.Set(-7.0f, 6.0f); bd.type = b2_dynamicBody; bd.allowSleep = false; m_character = m_world->CreateBody(&bd); b2CircleShape shape; shape.m_radius = 0.25f; b2FixtureDef fd; fd.shape = &shape; fd.density = 20.0f; fd.friction = 1.0f; m_character->CreateFixture(&fd); } } void Step(Settings& settings) override { b2Vec2 v = m_character->GetLinearVelocity(); v.x = -5.0f; m_character->SetLinearVelocity(v); Test::Step(settings); g_debugDraw.DrawString(5, m_textLine, "This tests various character collision shapes."); m_textLine += m_textIncrement; g_debugDraw.DrawString(5, m_textLine, "Limitation: square and hexagon can snag on aligned boxes."); m_textLine += m_textIncrement; g_debugDraw.DrawString(5, m_textLine, "Feature: edge chains have smooth collision inside and out."); m_textLine += m_textIncrement; } static Test* Create() { return new CharacterCollision; } b2Body* m_character; }; static int testIndex = RegisterTest("Examples", "Character Collision", CharacterCollision::Create);
25.824903
102
0.658581
[ "shape" ]
3baa3211f3df4b3468d8861743f5adeae863b2f9
3,184
cpp
C++
libarea/kbool/src/lpoint.cpp
JohnyEngine/CNC
e4c77250ab2b749d3014022cbb5eb9924e939993
[ "Apache-2.0" ]
null
null
null
libarea/kbool/src/lpoint.cpp
JohnyEngine/CNC
e4c77250ab2b749d3014022cbb5eb9924e939993
[ "Apache-2.0" ]
null
null
null
libarea/kbool/src/lpoint.cpp
JohnyEngine/CNC
e4c77250ab2b749d3014022cbb5eb9924e939993
[ "Apache-2.0" ]
null
null
null
/*! \file kbool/src/lpoint.cpp \brief Definition of GDSII LPoint type structure \author Klaas Holwerda Copyright: 2001-2004 (C) Klaas Holwerda Licence: see kboollicense.txt RCS-ID: $Id: lpoint.cpp,v 1.4 2005/05/24 19:13:39 titato Exp $ */ #ifdef __GNUG__ #pragma implementation #endif #include "kbool/include/lpoint.h" #include <math.h> // Constructors LPoint::LPoint() { _x = 0; _y = 0; } LPoint::LPoint(B_INT const X, B_INT const Y) { _x = X; _y = Y; } LPoint::LPoint(LPoint* const a_point) { if (!a_point) throw Bool_Engine_Error("Cannot copy a NULL Point Object.\n\nCould not create a LPoint Object.", "Fatal Creation Error", 0, 1); _x = a_point->_x; _y = a_point->_y; } B_INT LPoint::GetX() { return _x; } B_INT LPoint::GetY() { return _y; } void LPoint::SetX(B_INT a_point_x) { _x = a_point_x; } void LPoint::SetY(B_INT a_point_y) { _y = a_point_y; } LPoint LPoint::GetPoint() { return *this; } void LPoint::Set(const B_INT X,const B_INT Y) { _x = X; _y = Y; } void LPoint::Set(const LPoint &a_point) { _x = a_point._x; _y =a_point._y; } bool LPoint::Equal(const LPoint a_point, B_INT Marge) { B_INT delta_x, delta_y; delta_x = babs((_x - a_point._x)); delta_y = babs((_y - a_point._y)); if ((delta_x <= Marge) && (delta_y <= Marge)) return true; else return false; } bool LPoint::Equal(const B_INT X, const B_INT Y, B_INT Marge) { return (bool)((babs(_x - X) <= Marge) && (babs(_y - Y) <= Marge)); } bool LPoint::ShorterThan(const LPoint a_point, B_INT Marge) { double a,b; a = (double) (a_point._x - _x); a*= a; b = (double) (a_point._y - _y); b*= b; return (bool) ( (a+b) <= Marge*Marge ? true : false ) ; } bool LPoint::ShorterThan(const B_INT X, const B_INT Y, B_INT Marge) { double a,b; a = (double) (X - _x); a*= a; b = (double) (Y - _y); b*= b; return (bool) ( a+b <= Marge*Marge ? true : false ) ; } // overload the assign (=) operator // usage : a_point = another_point; LPoint &LPoint::operator=(const LPoint &other_point) { _x = other_point._x; _y = other_point._y; return *this; } // overload the + operator // usage : a_point = point1 + point2; LPoint &LPoint::operator+(const LPoint &other_point) { _x += other_point._x; _y += other_point._y; return *this; } // overload the - operator // usage : a_point = point1 - point2; LPoint &LPoint::operator-(const LPoint &other_point) { _x -= other_point._x; _y -= other_point._y; return *this; } // overload the * operator // usage: a_point = point1 * 100; LPoint &LPoint::operator*(int factor) { _x *= factor; _y *= factor; return *this; } // overload the / operator // usage: a_point = point1 / 100; LPoint &LPoint::operator/(int factor) { _x /= factor; _y /= factor; return *this; } // overload the compare (==) operator // usage: if (point1 == point2) { }; int LPoint::operator==(const LPoint &other_point) const { return ((other_point._x == _x) && (other_point._y == _y)); } // overload the diffrent (!=) operator // usage: if (point1 != point2) { }; int LPoint::operator!=(const LPoint &other_point) const { return ((other_point._x != _x) || (other_point._y != _y)); }
15.607843
98
0.639447
[ "object" ]
3bb2aa0867d46435e0c4c2b6cb0beccccfe44f2f
39,387
cxx
C++
main/sd/source/ui/slidesorter/view/SlsButtonBar.cxx
Alan-love/openoffice
09be380f1ebba053dbf269468ff884f5d26ce1e4
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/sd/source/ui/slidesorter/view/SlsButtonBar.cxx
Alan-love/openoffice
09be380f1ebba053dbf269468ff884f5d26ce1e4
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/sd/source/ui/slidesorter/view/SlsButtonBar.cxx
Alan-love/openoffice
09be380f1ebba053dbf269468ff884f5d26ce1e4
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #include "precompiled_sd.hxx" #include "view/SlsButtonBar.hxx" #include "SlideSorter.hxx" #include "model/SlsPageDescriptor.hxx" #include "model/SlideSorterModel.hxx" #include "view/SlsTheme.hxx" #include "view/SlideSorterView.hxx" #include "view/SlsToolTip.hxx" #include "controller/SlideSorterController.hxx" #include "controller/SlsSlotManager.hxx" #include "controller/SlsCurrentSlideManager.hxx" #include "controller/SlsPageSelector.hxx" #include "controller/SlsAnimator.hxx" #include "controller/SlsAnimationFunction.hxx" #include "app.hrc" #include "drawdoc.hxx" #include "sddll.hxx" #include "optsitem.hxx" #include <svx/svxids.hrc> #include <sfx2/dispatch.hxx> #include <vcl/bmpacc.hxx> #include <vcl/virdev.hxx> #include <basegfx/polygon/b2dpolygontools.hxx> #include <basegfx/polygon/b2dpolygon.hxx> #include <basegfx/numeric/ftools.hxx> #include <com/sun/star/presentation/XPresentation2.hpp> #include <boost/bind.hpp> using ::com::sun::star::uno::Any; using ::com::sun::star::uno::Reference; using ::com::sun::star::uno::Sequence; using ::com::sun::star::beans::PropertyValue; using ::com::sun::star::presentation::XPresentation2; namespace sd { namespace slidesorter { namespace view { /** Base class for the painter of the background bar onto which the buttons are painted. It also provides some size information. */ class ButtonBar::BackgroundTheme { public: BackgroundTheme( const ::boost::shared_ptr<Theme>& rpTheme, const ::std::vector<SharedButton>& rButtons); /** Set the preview bounding box, the maximal area in which to display buttons. A call to this method triggers a call to Layout(). */ void SetPreviewBoundingBox (const Rectangle& rPreviewBoundingBox); Button::IconSize GetIconSize (void) const; virtual BitmapEx CreateBackground ( const OutputDevice& rTemplateDevice, const bool bIsButtonDown) const = 0; virtual Point GetBackgroundLocation (void) = 0; virtual Rectangle GetButtonArea (void) = 0; protected: ::boost::shared_ptr<Theme> mpTheme; Rectangle maPreviewBoundingBox; Size maMinimumLargeButtonAreaSize; Size maMinimumMediumButtonAreaSize; Size maMinimumSmallButtonAreaSize; Button::IconSize meIconSize; virtual void Layout (void) = 0; private: void UpdateMinimumIconSizes(const ::std::vector<SharedButton>& rButtons); }; namespace { /** Rectangular button bar that covers the whole width of the preview. */ class RectangleBackgroundTheme : public ButtonBar::BackgroundTheme { public: RectangleBackgroundTheme( const ::boost::shared_ptr<Theme>& rpTheme, const ::std::vector<SharedButton>& rButtons); virtual BitmapEx CreateBackground ( const OutputDevice& rTemplateDevice, const bool bIsButtonDown) const; virtual Point GetBackgroundLocation (void); virtual Rectangle GetButtonArea (void); protected: virtual void Layout (void); private: sal_Int32 mnBarHeight; }; /** Button bar is composed of three images, the left and right end of the bar and the center image. Buttons are only placed over the center image. The center image is painted as is, it is not scaled. */ class BitmapBackgroundTheme : public ButtonBar::BackgroundTheme { public: BitmapBackgroundTheme( const ::boost::shared_ptr<Theme>& rpTheme, const ::std::vector<SharedButton>& rButtons); virtual BitmapEx CreateBackground ( const OutputDevice& rTemplateDevice, const bool bIsButtonDown) const; virtual Point GetBackgroundLocation (void); virtual Rectangle GetButtonArea (void); protected: virtual void Layout (void); private: Rectangle maButtonArea; Point maBackgroundLocation; }; /** The source mask is essentially multiplied with the given alpha value. The result is written to the result mask. */ void AdaptTransparency (AlphaMask& rMask, const AlphaMask& rSourceMask, const double nAlpha) { BitmapWriteAccess* pBitmap = rMask.AcquireWriteAccess(); const BitmapReadAccess* pSourceBitmap = const_cast<AlphaMask&>(rSourceMask).AcquireReadAccess(); if (pBitmap!=NULL && pSourceBitmap!=NULL) { const sal_Int32 nWidth (pBitmap->Width()); const sal_Int32 nHeight (pBitmap->Height()); for (sal_Int32 nY = 0; nY<nHeight; ++nY) for (sal_Int32 nX = 0; nX<nWidth; ++nX) { const sal_uInt8 nValue (255 - pSourceBitmap->GetPixel(nY, nX).GetBlueOrIndex()); const sal_Int32 nNewValue (::basegfx::clamp<sal_Int32>( static_cast<sal_Int32>(nValue * (1-nAlpha)), 0, 255)); pBitmap->SetPixelIndex(nY, nX, static_cast<sal_uInt8>(255-nNewValue)); } } } } // end of anonymous namespace //===== ButtonBar::Lock ======================================================= ButtonBar::Lock::Lock (SlideSorter& rSlideSorter) : mrButtonBar(rSlideSorter.GetView().GetButtonBar()) { mrButtonBar.AcquireLock(); } ButtonBar::Lock::~Lock (void) { mrButtonBar.ReleaseLock(); } //===== ButtonBar ============================================================= ButtonBar::ButtonBar (SlideSorter& rSlideSorter) : mrSlideSorter(rSlideSorter), maPageObjectSize(0,0), maButtonBoundingBox(), maBackgroundLocation(), mpDescriptor(), mbIsExcluded(false), mpButtonUnderMouse(), mpDownButton(), maRegularButtons(), maExcludedButtons(), maNormalBackground(), maButtonDownBackground(), mbIsMouseOverBar(false), mpBackgroundTheme(), mnLockCount(0) { HandleDataChangeEvent(); } ButtonBar::~ButtonBar (void) { } void ButtonBar::ProcessButtonDownEvent ( const model::SharedPageDescriptor& rpDescriptor, const Point aMouseModelLocation) { SetButtonUnderMouse(GetButtonAt(aMouseModelLocation)); if (mpButtonUnderMouse) mpButtonUnderMouse->SetState(Button::State_Down); mpDownButton = mpButtonUnderMouse; mrSlideSorter.GetView().RequestRepaint(rpDescriptor); } void ButtonBar::ProcessButtonUpEvent ( const model::SharedPageDescriptor& rpDescriptor, const Point aMouseModelLocation) { SetButtonUnderMouse(GetButtonAt(aMouseModelLocation)); if (mpButtonUnderMouse) { mpButtonUnderMouse->SetState(Button::State_Hover); if (mpButtonUnderMouse == mpDownButton) { // This is done only when the buttons are sufficiently visible. if (mpDescriptor->GetVisualState().GetButtonAlpha()<0.7) { mpButtonUnderMouse->ProcessClick(mpDescriptor); mbIsExcluded = mpDescriptor->HasState(model::PageDescriptor::ST_Excluded); ProcessMouseMotionEvent (rpDescriptor, aMouseModelLocation, false); } } } mpDownButton.reset(); mrSlideSorter.GetView().RequestRepaint(rpDescriptor); } void ButtonBar::ProcessMouseMotionEvent ( const model::SharedPageDescriptor& rpDescriptor, const Point aMouseModelLocation, const bool bIsMouseButtonDown) { model::SharedPageDescriptor pOldDescriptor (mpDescriptor); bool bPageHasChanged (false); bool bButtonHasChanged (false); bool bButtonStateHasChanged (false); // Update the page object for which to manage the buttons. bPageHasChanged = SetPage(rpDescriptor); mbIsMouseOverBar = IsMouseOverBar(aMouseModelLocation); // Update button under mouse. if (rpDescriptor) { bButtonHasChanged = SetButtonUnderMouse(GetButtonAt(aMouseModelLocation)); if (mpButtonUnderMouse) { // When the mouse button is down, mark the button under the // mouse only as pressed when it is the same button the mouse // button was pressed over, and where the button release would // lead to a click action. if (bIsMouseButtonDown) { if (mpButtonUnderMouse==mpDownButton) bButtonStateHasChanged = mpButtonUnderMouse->SetState(Button::State_Down); } else bButtonStateHasChanged = mpButtonUnderMouse->SetState(Button::State_Hover); } } // Show a quick help text when the mouse is over a button. if (bButtonHasChanged) { SharedSdWindow pWindow (mrSlideSorter.GetContentWindow()); if (pWindow) { if (mpButtonUnderMouse) mrSlideSorter.GetView().GetToolTip().ShowHelpText(mpButtonUnderMouse->GetHelpText()); else mrSlideSorter.GetView().GetToolTip().ShowDefaultHelpText(); } } if (bPageHasChanged || bButtonHasChanged || bButtonStateHasChanged) { if (pOldDescriptor) mrSlideSorter.GetView().RequestRepaint(pOldDescriptor); if (mpDescriptor && pOldDescriptor!=mpDescriptor) mrSlideSorter.GetView().RequestRepaint(mpDescriptor); } } void ButtonBar::ResetPage (void) { SetPage(model::SharedPageDescriptor()); } bool ButtonBar::SetPage (const model::SharedPageDescriptor& rpDescriptor) { if (mpDescriptor != rpDescriptor) { mpDescriptor = rpDescriptor; if (mpDescriptor) mbIsExcluded = mpDescriptor->HasState(model::PageDescriptor::ST_Excluded); else mbIsExcluded = false; SetButtonUnderMouse(); mpDownButton.reset(); return true; } else return false; } sal_Int32 ButtonBar::GetButtonCount (const bool bIsExcluded) const { if (bIsExcluded) return maExcludedButtons.size(); else return maRegularButtons.size(); } ::boost::shared_ptr<Button> ButtonBar::GetButton ( const bool bIsExcluded, const sal_Int32 nIndex) const { const ::std::vector<boost::shared_ptr<Button> >& rButtons (bIsExcluded ? maExcludedButtons : maRegularButtons); if (nIndex<0 || sal_uInt32(nIndex)>=rButtons.size()) { OSL_ASSERT(nIndex<0 || sal_uInt32(nIndex)>=rButtons.size()); return ::boost::shared_ptr<Button>(); } else return rButtons[sal_uInt32(nIndex)]; } SharedButton ButtonBar::GetButtonAt (const Point aModelLocation) { if (IsMouseOverBar(aModelLocation)) { const Point aLocalLocation (aModelLocation - mpDescriptor->GetBoundingBox().TopLeft()); ::std::vector<SharedButton>& rButtons ( mbIsExcluded ? maExcludedButtons : maRegularButtons); for (sal_uInt32 nIndex=0; nIndex<rButtons.size(); ++nIndex) { if (rButtons[sal_uInt32(nIndex)]->GetBoundingBox().IsInside(aLocalLocation)) { if (rButtons[sal_uInt32(nIndex)]->IsEnabled()) return rButtons[sal_uInt32(nIndex)]; else return SharedButton(); } } } return SharedButton(); } bool ButtonBar::IsMouseOverBar (void) const { return mbIsMouseOverBar; } bool ButtonBar::SetButtonUnderMouse (const SharedButton& rButton) { if (mpButtonUnderMouse != rButton) { if (mpButtonUnderMouse) mpButtonUnderMouse->SetState(Button::State_Normal); mpButtonUnderMouse = rButton; return true; } else return false; } void ButtonBar::Paint ( OutputDevice& rDevice, const model::SharedPageDescriptor& rpDescriptor) { if ( ! rpDescriptor) return; const double nButtonBarAlpha (rpDescriptor->GetVisualState().GetButtonBarAlpha()); if (nButtonBarAlpha >= 1) return; LayoutButtons(rpDescriptor->GetBoundingBox().GetSize()); const Point aOffset (rpDescriptor->GetBoundingBox().TopLeft()); // Paint the background. PaintButtonBackground(rDevice, rpDescriptor, aOffset); // Paint the buttons. const ::std::vector<SharedButton>& rButtons ( rpDescriptor->HasState(model::PageDescriptor::ST_Excluded) ? maExcludedButtons : maRegularButtons); const double nButtonAlpha (rpDescriptor->GetVisualState().GetButtonAlpha()); for (sal_uInt32 nIndex=0; nIndex<rButtons.size(); ++nIndex) rButtons[nIndex]->Paint( rDevice, aOffset, nButtonAlpha, mrSlideSorter.GetTheme()); } bool ButtonBar::IsMouseOverButton (void) const { return (mpButtonUnderMouse.get() != NULL); } void ButtonBar::PaintButtonBackground ( OutputDevice& rDevice, const model::SharedPageDescriptor& rpDescriptor, const Point aOffset) { BitmapEx* pBitmap = NULL; if (maButtonDownBackground.IsEmpty() || maNormalBackground.IsEmpty()) { if (mpBackgroundTheme) { maButtonDownBackground = mpBackgroundTheme->CreateBackground(rDevice, true); maNormalBackground = mpBackgroundTheme->CreateBackground(rDevice, false); } } if (mpButtonUnderMouse && mpButtonUnderMouse->IsDown()) pBitmap = &maButtonDownBackground; else pBitmap = &maNormalBackground; if (pBitmap != NULL) { AlphaMask aMask (pBitmap->GetSizePixel()); AdaptTransparency( aMask, pBitmap->GetAlpha(), rpDescriptor->GetVisualState().GetButtonBarAlpha()); rDevice.DrawBitmapEx(maBackgroundLocation+aOffset, BitmapEx(pBitmap->GetBitmap(), aMask)); } } bool ButtonBar::IsMouseOverBar (const Point aModelLocation) const { if ( ! mpDescriptor || ! mpDescriptor->GetBoundingBox().IsInside(aModelLocation)) return false; if ( ! maButtonBoundingBox.IsInside(aModelLocation - mpDescriptor->GetBoundingBox().TopLeft())) return false; return true; } void ButtonBar::RequestLayout (void) { maPageObjectSize = Size(0,0); } void ButtonBar::LayoutButtons (const Size aPageObjectSize) { if (maPageObjectSize != aPageObjectSize) { maPageObjectSize = aPageObjectSize; if (mpBackgroundTheme) { mpBackgroundTheme->SetPreviewBoundingBox( mrSlideSorter.GetView().GetLayouter().GetPageObjectLayouter()->GetBoundingBox( Point(0,0), PageObjectLayouter::Preview, PageObjectLayouter::ModelCoordinateSystem)); LayoutButtons(); } // Release the background bitmaps so that on the next paint // they are created anew in the right size. maNormalBackground.SetEmpty(); maButtonDownBackground.SetEmpty(); } } bool ButtonBar::LayoutButtons (void) { const sal_Int32 nGap (mrSlideSorter.GetTheme()->GetIntegerValue(Theme::Integer_ButtonGap)); const sal_Int32 nBorder (mrSlideSorter.GetTheme()->GetIntegerValue(Theme::Integer_ButtonBorder)); const Button::IconSize eIconSize (mpBackgroundTheme->GetIconSize()); // Tell buttons which size they are. for (sal_uInt32 nIndex=0; nIndex<maExcludedButtons.size(); ++nIndex) maExcludedButtons[nIndex]->SetIconSize(eIconSize); for (sal_uInt32 nIndex=0; nIndex<maRegularButtons.size(); ++nIndex) maRegularButtons[nIndex]->SetIconSize(eIconSize); // Determine maximal height and total width of the buttons. // Start with the buttons used for the excluded state. sal_Int32 nMaximumHeight (0); sal_Int32 nExcludedTotalWidth ((maExcludedButtons.size()-1) * nGap + 2*nBorder); for (sal_uInt32 nIndex=0; nIndex<maExcludedButtons.size(); ++nIndex) { const Size aSize (maExcludedButtons[nIndex]->GetSize()); if (aSize.Height() > nMaximumHeight) nMaximumHeight = aSize.Height(); nExcludedTotalWidth += aSize.Width(); } // Do the same for the regular buttons. sal_Int32 nRegularTotalWidth ((maRegularButtons.size()-1) * nGap + 2*nBorder); for (sal_uInt32 nIndex=0; nIndex<maRegularButtons.size(); ++nIndex) { const Size aSize (maRegularButtons[nIndex]->GetSize()); if (aSize.Height() > nMaximumHeight) nMaximumHeight = aSize.Height(); nRegularTotalWidth += aSize.Width(); } nMaximumHeight += 2*nBorder; // Set up the bounding box of the button bar. maButtonBoundingBox = mpBackgroundTheme->GetButtonArea(); maBackgroundLocation = mpBackgroundTheme->GetBackgroundLocation(); if (mrSlideSorter.GetTheme()->GetIntegerValue(Theme::Integer_ButtonPaintType) == 1) { // Center the buttons. maButtonBoundingBox.Left() += (maButtonBoundingBox.GetWidth() - nRegularTotalWidth)/2; maButtonBoundingBox.Right() = maButtonBoundingBox.Left() + nRegularTotalWidth - 1; } // Place the buttons. Rectangle aBox (maButtonBoundingBox); aBox.Right() -= nBorder; for (sal_Int32 nIndex=maRegularButtons.size()-1; nIndex>=0; --nIndex) { maRegularButtons[nIndex]->Place(aBox); aBox.Right() = maRegularButtons[nIndex]->GetBoundingBox().Left() - nGap; } // For slides excluded from the show there is only one icon placed // exactly like the second of the regular icons. if (maRegularButtons.size()>=2 && maExcludedButtons.size()>=1) { aBox = maRegularButtons[1]->GetBoundingBox(); maExcludedButtons[0]->Place(aBox); } // We return true only when there is no inactive button. for (sal_uInt32 nIndex=0; nIndex<maExcludedButtons.size(); ++nIndex) if ( ! maExcludedButtons[nIndex]->IsActive()) return false; for (sal_uInt32 nIndex=0; nIndex<maRegularButtons.size(); ++nIndex) if ( ! maRegularButtons[nIndex]->IsActive()) return false; return true; } void ButtonBar::RequestFadeIn ( const model::SharedPageDescriptor& rpDescriptor, const bool bAnimate) { if ( ! rpDescriptor) return; if (mnLockCount > 0) return; const double nMinAlpha (0); if ( ! bAnimate) { rpDescriptor->GetVisualState().SetButtonAlpha(nMinAlpha); rpDescriptor->GetVisualState().SetButtonBarAlpha(nMinAlpha); } else StartFadeAnimation(rpDescriptor, nMinAlpha, true); } void ButtonBar::RequestFadeOut ( const model::SharedPageDescriptor& rpDescriptor, const bool bAnimate) { if ( ! rpDescriptor) return; if (mnLockCount > 0) return; const double nMaxAlpha (1); if ( ! bAnimate) { rpDescriptor->GetVisualState().SetButtonAlpha(nMaxAlpha); rpDescriptor->GetVisualState().SetButtonBarAlpha(nMaxAlpha); } else StartFadeAnimation(rpDescriptor, nMaxAlpha, false); } bool ButtonBar::IsVisible (const model::SharedPageDescriptor& rpDescriptor) { const double nMaxAlpha (1); return rpDescriptor && rpDescriptor->GetVisualState().GetButtonBarAlpha() < nMaxAlpha; } void ButtonBar::HandleDataChangeEvent (void) { maExcludedButtons.clear(); maExcludedButtons.push_back(::boost::shared_ptr<Button>(new UnhideButton(mrSlideSorter))); maRegularButtons.clear(); maRegularButtons.push_back(::boost::shared_ptr<Button>(new StartShowButton(mrSlideSorter))); maRegularButtons.push_back(::boost::shared_ptr<Button>(new HideButton(mrSlideSorter))); maRegularButtons.push_back(::boost::shared_ptr<Button>(new DuplicateButton(mrSlideSorter))); mpBackgroundTheme.reset( new BitmapBackgroundTheme( mrSlideSorter.GetTheme(), maRegularButtons)); // Force layout on next Paint(). maPageObjectSize = Size(0,0); } void ButtonBar::StartFadeAnimation ( const model::SharedPageDescriptor& rpDescriptor, const double nTargetAlpha, const bool bFadeIn) { model::SharedPageDescriptor pDescriptor (rpDescriptor); const double nCurrentButtonAlpha (pDescriptor->GetVisualState().GetButtonAlpha()); const double nCurrentButtonBarAlpha (pDescriptor->GetVisualState().GetButtonBarAlpha()); // Stop a running animation. const controller::Animator::AnimationId nId ( pDescriptor->GetVisualState().GetButtonAlphaAnimationId()); if (nId != controller::Animator::NotAnAnimationId) mrSlideSorter.GetController().GetAnimator()->RemoveAnimation(nId); // Prepare the blending functors that translate [0,1] animation // times into alpha values of buttons and button bar. const ::boost::function<double(double)> aButtonBlendFunctor ( ::boost::bind( controller::AnimationFunction::Blend, nCurrentButtonAlpha, nTargetAlpha, ::boost::bind(controller::AnimationFunction::Linear, _1))); const ::boost::function<double(double)> aButtonBarBlendFunctor ( ::boost::bind( controller::AnimationFunction::Blend, nCurrentButtonBarAlpha, nTargetAlpha, ::boost::bind(controller::AnimationFunction::Linear, _1))); // Delay the fade in a little bit when the buttons are not visible at // all so that we do not leave a trail of half-visible buttons when the // mouse is moved across the screen. No delay on fade out or when the // buttons are already showing. Fade out is faster than fade in. const sal_Int32 nDelay (nCurrentButtonBarAlpha>0 && nCurrentButtonBarAlpha<1 ? 0 : (mrSlideSorter.GetTheme()->GetIntegerValue(bFadeIn ? Theme::Integer_ButtonFadeInDelay : Theme::Integer_ButtonFadeOutDelay))); const sal_Int32 nDuration (mrSlideSorter.GetTheme()->GetIntegerValue(bFadeIn ? Theme::Integer_ButtonFadeInDuration : Theme::Integer_ButtonFadeOutDuration)); pDescriptor->GetVisualState().SetButtonAlphaAnimationId( mrSlideSorter.GetController().GetAnimator()->AddAnimation( ::boost::bind( controller::AnimationFunction::ApplyButtonAlphaChange, pDescriptor, ::boost::ref(mrSlideSorter.GetView()), ::boost::bind(aButtonBlendFunctor, _1), ::boost::bind(aButtonBarBlendFunctor, _1)), nDelay, nDuration, ::boost::bind( &model::VisualState::SetButtonAlphaAnimationId, ::boost::ref(pDescriptor->GetVisualState()), controller::Animator::NotAnAnimationId) )); } void ButtonBar::AcquireLock (void) { if (mnLockCount == 0 && mpDescriptor) RequestFadeOut(mpDescriptor, true); ++mnLockCount; } void ButtonBar::ReleaseLock (void) { --mnLockCount; if (mnLockCount == 0 && mpDescriptor) RequestFadeIn(mpDescriptor, true); } //===== BackgroundTheme ===================================================== ButtonBar::BackgroundTheme::BackgroundTheme ( const ::boost::shared_ptr<Theme>& rpTheme, const ::std::vector<SharedButton>& rButtons) : mpTheme(rpTheme) { UpdateMinimumIconSizes(rButtons); } void ButtonBar::BackgroundTheme::SetPreviewBoundingBox (const Rectangle& rPreviewBoundingBox) { maPreviewBoundingBox = rPreviewBoundingBox; Layout(); } void ButtonBar::BackgroundTheme::UpdateMinimumIconSizes ( const ::std::vector<SharedButton>& rButtons) { OSL_ASSERT(mpTheme); sal_Int32 nMaximumHeightLarge (0); sal_Int32 nMaximumHeightMedium (0); sal_Int32 nMaximumHeightSmall (0); const sal_Int32 nGap (mpTheme->GetIntegerValue(Theme::Integer_ButtonGap)); const sal_Int32 nBorder (mpTheme->GetIntegerValue(Theme::Integer_ButtonBorder)); sal_Int32 nTotalWidthLarge ((rButtons.size()-1) * nGap + 2*nBorder); sal_Int32 nTotalWidthMedium ((rButtons.size()-1) * nGap + 2*nBorder); sal_Int32 nTotalWidthSmall ((rButtons.size()-1) * nGap + 2*nBorder); for (sal_uInt32 nIndex=0; nIndex<rButtons.size(); ++nIndex) { // Update large size. Size aSize = rButtons[nIndex]->GetSize(Button::IconSize_Large); if (aSize.Height() > nMaximumHeightLarge) nMaximumHeightLarge = aSize.Height(); nTotalWidthLarge += aSize.Width(); // Update medium size. aSize = rButtons[nIndex]->GetSize(Button::IconSize_Medium); if (aSize.Height() > nMaximumHeightMedium) nMaximumHeightMedium = aSize.Height(); nTotalWidthMedium += aSize.Width(); // Update small size. aSize = rButtons[nIndex]->GetSize(Button::IconSize_Small); if (aSize.Height() > nMaximumHeightSmall) nMaximumHeightSmall = aSize.Height(); nTotalWidthSmall += aSize.Width(); } maMinimumLargeButtonAreaSize = Size(nTotalWidthLarge, nMaximumHeightLarge+2*nBorder); maMinimumMediumButtonAreaSize = Size(nTotalWidthMedium, nMaximumHeightMedium+2*nBorder); maMinimumSmallButtonAreaSize = Size(nTotalWidthSmall, nMaximumHeightSmall+2*nBorder); } Button::IconSize ButtonBar::BackgroundTheme::GetIconSize (void) const { return meIconSize; } //===== RectangleBackgroundTheme ============================================ RectangleBackgroundTheme::RectangleBackgroundTheme ( const ::boost::shared_ptr<Theme>& rpTheme, const ::std::vector<SharedButton>& rButtons) : BackgroundTheme(rpTheme, rButtons), mnBarHeight(0) { } BitmapEx RectangleBackgroundTheme::CreateBackground ( const OutputDevice& rTemplateDevice, const bool bIsButtonDown) const { OSL_ASSERT(mpTheme); // Setup background color. Color aTopFillColor (mpTheme->GetGradientColor( Theme::Gradient_ButtonBackground, Theme::Fill1)); Color aTopBorderColor (mpTheme->GetGradientColor( Theme::Gradient_ButtonBackground, Theme::Border1)); Color aBottomFillColor (mpTheme->GetGradientColor( Theme::Gradient_ButtonBackground, Theme::Fill2)); Color aBottomBorderColor (mpTheme->GetGradientColor( Theme::Gradient_ButtonBackground, Theme::Border2)); if (bIsButtonDown) { aTopFillColor.DecreaseLuminance(50); aTopBorderColor.DecreaseLuminance(50); aBottomFillColor.DecreaseLuminance(50); aBottomBorderColor.DecreaseLuminance(50); } const int nWidth (maPreviewBoundingBox.GetWidth()+2); const int nHeight (mnBarHeight); const int nCenter (nHeight / 2); VirtualDevice aDevice (rTemplateDevice, 0, 8); aDevice.SetOutputSizePixel(Size(nWidth,nHeight)); // Fill upper and lower half. aDevice.SetLineColor(); aDevice.SetFillColor(aTopFillColor); aDevice.DrawRect(Rectangle(0,0,nWidth-1,nCenter)); aDevice.SetFillColor(aBottomFillColor); aDevice.DrawRect(Rectangle(0,nCenter,nWidth-1,nHeight-1)); // Draw border. aDevice.SetFillColor(); aDevice.SetLineColor(aTopBorderColor); aDevice.DrawLine(Point(0,nCenter),Point(0,0)); aDevice.DrawLine(Point(0,0), Point(nWidth-1,0)); aDevice.DrawLine(Point(nWidth-1,0),Point(nWidth-1,nCenter)); aDevice.SetLineColor(aBottomBorderColor); aDevice.DrawLine(Point(0,nCenter),Point(0,nHeight-1)); aDevice.DrawLine(Point(0,nHeight-1), Point(nWidth-1,nHeight-1)); aDevice.DrawLine(Point(nWidth-1,nHeight-1),Point(nWidth-1,nCenter)); return aDevice.GetBitmapEx(Point(0,0), Size(nWidth,nHeight)); } Point RectangleBackgroundTheme::GetBackgroundLocation (void) { return Point( maPreviewBoundingBox.Left()-1, maPreviewBoundingBox.Bottom() - mnBarHeight + 2); } Rectangle RectangleBackgroundTheme::GetButtonArea (void) { return Rectangle( maPreviewBoundingBox.Left(), maPreviewBoundingBox.Bottom() - mnBarHeight + 2, maPreviewBoundingBox.Right(), maPreviewBoundingBox.Bottom()); } void RectangleBackgroundTheme::Layout (void) { if (maPreviewBoundingBox.GetWidth() < maMinimumLargeButtonAreaSize.Width()) if (maPreviewBoundingBox.GetWidth() < maMinimumMediumButtonAreaSize.Width()) { meIconSize = Button::IconSize_Small; mnBarHeight = maMinimumSmallButtonAreaSize.Height(); } else { meIconSize = Button::IconSize_Medium; mnBarHeight = maMinimumMediumButtonAreaSize.Height(); } else { meIconSize = Button::IconSize_Large; mnBarHeight = maMinimumLargeButtonAreaSize.Height(); } } //===== BitmapBackgroundTheme ================================================= BitmapBackgroundTheme::BitmapBackgroundTheme ( const ::boost::shared_ptr<Theme>& rpTheme, const ::std::vector<SharedButton>& rButtons) : BackgroundTheme(rpTheme, rButtons), maButtonArea(), maBackgroundLocation() { } BitmapEx BitmapBackgroundTheme::CreateBackground ( const OutputDevice& rTemplateDevice, const bool bIsButtonDown) const { (void)rTemplateDevice; (void)bIsButtonDown; OSL_ASSERT(mpTheme); // Get images. switch (meIconSize) { case Button::IconSize_Large: default: return mpTheme->GetIcon(Theme::Icon_ButtonBarLarge); case Button::IconSize_Medium: return mpTheme->GetIcon(Theme::Icon_ButtonBarMedium); case Button::IconSize_Small: return mpTheme->GetIcon(Theme::Icon_ButtonBarSmall); } } Point BitmapBackgroundTheme::GetBackgroundLocation (void) { return maBackgroundLocation; } Rectangle BitmapBackgroundTheme::GetButtonArea (void) { return maButtonArea; } void BitmapBackgroundTheme::Layout (void) { Size aImageSize (mpTheme->GetIcon(Theme::Icon_ButtonBarLarge).GetSizePixel()); if (aImageSize.Width() >= maPreviewBoundingBox.GetWidth()) { aImageSize = mpTheme->GetIcon(Theme::Icon_ButtonBarMedium).GetSizePixel(); if (aImageSize.Width() >= maPreviewBoundingBox.GetWidth()) { meIconSize = Button::IconSize_Small; aImageSize = mpTheme->GetIcon(Theme::Icon_ButtonBarSmall).GetSizePixel(); } else meIconSize = Button::IconSize_Medium; } else { meIconSize = Button::IconSize_Large; } maBackgroundLocation = Point( maPreviewBoundingBox.Left() + (maPreviewBoundingBox.GetWidth()-aImageSize.Width())/2, maPreviewBoundingBox.Bottom() - aImageSize.Height()); maButtonArea = Rectangle(maBackgroundLocation, aImageSize); } //===== Button ================================================================ Button::Button ( SlideSorter& rSlideSorter, const ::rtl::OUString& rsHelpText) : mrSlideSorter(rSlideSorter), meState(State_Normal), maBoundingBox(), msHelpText(rsHelpText), mbIsActive(false), meIconSize(IconSize_Large) { } Button::~Button (void) { } bool Button::SetState (const State eState) { if (meState != eState) { meState = eState; return true; } else return false; } Button::State Button::GetState (void) const { return meState; } Rectangle Button::GetBoundingBox (void) const { if (mbIsActive) return maBoundingBox; else return Rectangle(); } ::rtl::OUString Button::GetHelpText (void) const { if (mbIsActive) return msHelpText; else return ::rtl::OUString(); } bool Button::IsDown (void) const { return mbIsActive && meState==State_Down; } void Button::SetActiveState (const bool bIsActive) { mbIsActive = bIsActive; } bool Button::IsActive (void) const { return mbIsActive; } void Button::SetIconSize (const IconSize eIconSize) { meIconSize = eIconSize; } Button::IconSize Button::GetIconSize (void) const { return meIconSize; } bool Button::IsEnabled (void) const { return true; } //===== TextButton ============================================================ TextButton::TextButton ( SlideSorter& rSlideSorter, const ::rtl::OUString& rsText, const ::rtl::OUString& rsHelpText) : Button(rSlideSorter, rsHelpText), msText(rsText) { } void TextButton::Place (const Rectangle aButtonBarBox) { maBoundingBox = aButtonBarBox; SetActiveState(true); } void TextButton::Paint ( OutputDevice& rDevice, const Point aOffset, const double nAlpha, const ::boost::shared_ptr<Theme>& rpTheme) const { (void)nAlpha; if (mbIsActive) { // Paint text over the button background. if (meState == State_Normal) rDevice.SetTextColor(rpTheme->GetColor(Theme::Color_ButtonText)); else rDevice.SetTextColor(rpTheme->GetColor(Theme::Color_ButtonTextHover)); Rectangle aBox (maBoundingBox); aBox += aOffset; rDevice.DrawText(aBox, msText, TEXT_DRAW_CENTER | TEXT_DRAW_VCENTER); } } Size TextButton::GetSize (void) const { return Size(); } Size TextButton::GetSize (const Button::IconSize) const { return Size(); } //===== ImageButon ============================================================ ImageButton::ImageButton ( SlideSorter& rSlideSorter, const BitmapEx& rLargeIcon, const BitmapEx& rLargeHoverIcon, const BitmapEx& rMediumIcon, const BitmapEx& rMediumHoverIcon, const BitmapEx& rSmallIcon, const BitmapEx& rSmallHoverIcon, const ::rtl::OUString& rsHelpText) : Button(rSlideSorter, rsHelpText), maLargeIcon(rLargeIcon), maLargeHoverIcon(rLargeHoverIcon.IsEmpty() ? rLargeIcon : rLargeHoverIcon), maMediumIcon(rMediumIcon), maMediumHoverIcon(rMediumHoverIcon.IsEmpty() ? rMediumIcon : rMediumHoverIcon), maSmallIcon(rSmallIcon), maSmallHoverIcon(rSmallHoverIcon.IsEmpty() ? rSmallIcon : rSmallHoverIcon) { } void ImageButton::Place (const Rectangle aButtonBarBox) { const sal_Int32 nWidth (GetSize().Width()); maBoundingBox = Rectangle( aButtonBarBox.Right() - nWidth, aButtonBarBox.Top(), aButtonBarBox.Right(), aButtonBarBox.Bottom()); SetActiveState(aButtonBarBox.IsInside(maBoundingBox)); } void ImageButton::Paint ( OutputDevice& rDevice, const Point aOffset, const double nAlpha, const ::boost::shared_ptr<Theme>& rpTheme) const { (void)rpTheme; if ( ! mbIsActive) return; const sal_uInt16 nSavedAntialiasingMode (rDevice.GetAntialiasing()); rDevice.SetAntialiasing(nSavedAntialiasingMode | ANTIALIASING_ENABLE_B2DDRAW); rDevice.SetLineColor(); // Choose icon. BitmapEx aIcon; switch (meIconSize) { case IconSize_Large: default: if (meState == State_Normal) aIcon = maLargeIcon; else aIcon = maLargeHoverIcon; break; case IconSize_Medium: if (meState == State_Normal) aIcon = maMediumIcon; else aIcon = maMediumHoverIcon; break; case IconSize_Small: if (meState == State_Normal) aIcon = maSmallIcon; else aIcon = maSmallHoverIcon; break; } // Paint icon. if ( ! aIcon.IsEmpty()) { AlphaMask aMask (aIcon.GetSizePixel()); AdaptTransparency(aMask, aIcon.GetAlpha(), nAlpha); rDevice.DrawBitmapEx( Point( maBoundingBox.Left() + aOffset.X() + (maBoundingBox.GetWidth()-aIcon.GetSizePixel().Width())/2, maBoundingBox.Top() + aOffset.Y() + (maBoundingBox.GetHeight()-aIcon.GetSizePixel().Height())/2), BitmapEx(aIcon.GetBitmap(), aMask)); } rDevice.SetAntialiasing(nSavedAntialiasingMode); } Size ImageButton::GetSize (void) const { return GetSize(meIconSize); } Size ImageButton::GetSize (const Button::IconSize eIconSize) const { switch (eIconSize) { case IconSize_Large: default: return maLargeIcon.GetSizePixel(); case IconSize_Medium: return maMediumIcon.GetSizePixel(); case IconSize_Small: return maSmallIcon.GetSizePixel(); } } //===== UnhideButton ========================================================== UnhideButton::UnhideButton (SlideSorter& rSlideSorter) : ImageButton( rSlideSorter, rSlideSorter.GetTheme()->GetIcon(Theme::Icon_Command2BLarge), rSlideSorter.GetTheme()->GetIcon(Theme::Icon_Command2BLargeHover), rSlideSorter.GetTheme()->GetIcon(Theme::Icon_Command2BMedium), rSlideSorter.GetTheme()->GetIcon(Theme::Icon_Command2BMediumHover), rSlideSorter.GetTheme()->GetIcon(Theme::Icon_Command2BSmall), rSlideSorter.GetTheme()->GetIcon(Theme::Icon_Command2BSmallHover), rSlideSorter.GetTheme()->GetString(Theme::String_Command2B)) { } void UnhideButton::ProcessClick (const model::SharedPageDescriptor& rpDescriptor) { if ( ! rpDescriptor) return; mrSlideSorter.GetController().GetSlotManager()->ChangeSlideExclusionState( (rpDescriptor->HasState(model::PageDescriptor::ST_Selected) ? model::SharedPageDescriptor() : rpDescriptor), false); } //===== StartSlideShowButton ================================================== StartShowButton::StartShowButton (SlideSorter& rSlideSorter) : ImageButton( rSlideSorter, rSlideSorter.GetTheme()->GetIcon(Theme::Icon_Command1Large), rSlideSorter.GetTheme()->GetIcon(Theme::Icon_Command1LargeHover), rSlideSorter.GetTheme()->GetIcon(Theme::Icon_Command1Medium), rSlideSorter.GetTheme()->GetIcon(Theme::Icon_Command1MediumHover), rSlideSorter.GetTheme()->GetIcon(Theme::Icon_Command1Small), rSlideSorter.GetTheme()->GetIcon(Theme::Icon_Command1SmallHover), rSlideSorter.GetTheme()->GetString(Theme::String_Command1)) { } bool StartShowButton::IsEnabled (void) const { ViewShell* pViewShell = mrSlideSorter.GetViewShell(); if (pViewShell == NULL) return false; SfxDispatcher* pDispatcher = pViewShell->GetDispatcher(); if (pDispatcher == NULL) return false; const SfxPoolItem* pState = NULL; const SfxItemState eState (pDispatcher->QueryState(SID_PRESENTATION, pState)); return (eState & SFX_ITEM_DISABLED) == 0; } void StartShowButton::ProcessClick (const model::SharedPageDescriptor& rpDescriptor) { // Hide the tool tip early, while the slide show still initializes. mrSlideSorter.GetView().GetToolTip().SetPage(model::SharedPageDescriptor()); Reference< XPresentation2 > xPresentation( mrSlideSorter.GetModel().GetDocument()->getPresentation()); if (xPresentation.is()) { Sequence<PropertyValue> aProperties (1); aProperties[0].Name = ::rtl::OUString::createFromAscii("FirstPage"); const ::rtl::OUString sName (rpDescriptor->GetPage()->GetName()); aProperties[0].Value = Any(sName); // We have to temporarily change the options value // StartWithActualPage to make the slide show use the // specified first page. const DocumentType eType (mrSlideSorter.GetModel().GetDocument()->GetDocumentType()); const sal_Bool bSavedState (SD_MOD()->GetSdOptions(eType)->IsStartWithActualPage()); SD_MOD()->GetSdOptions(eType)->SetStartWithActualPage(sal_False); xPresentation->startWithArguments(aProperties); // Restore previous StartWithActualPage value. SD_MOD()->GetSdOptions(eType)->SetStartWithActualPage(bSavedState); } } //===== HideButton ============================================================ HideButton::HideButton (SlideSorter& rSlideSorter) : ImageButton( rSlideSorter, rSlideSorter.GetTheme()->GetIcon(Theme::Icon_Command2Large), rSlideSorter.GetTheme()->GetIcon(Theme::Icon_Command2LargeHover), rSlideSorter.GetTheme()->GetIcon(Theme::Icon_Command2Medium), rSlideSorter.GetTheme()->GetIcon(Theme::Icon_Command2MediumHover), rSlideSorter.GetTheme()->GetIcon(Theme::Icon_Command2Small), rSlideSorter.GetTheme()->GetIcon(Theme::Icon_Command2SmallHover), rSlideSorter.GetTheme()->GetString(Theme::String_Command2)) { } void HideButton::ProcessClick (const model::SharedPageDescriptor& rpDescriptor) { if ( ! rpDescriptor) return; mrSlideSorter.GetController().GetSlotManager()->ChangeSlideExclusionState( (rpDescriptor->HasState(model::PageDescriptor::ST_Selected) ? model::SharedPageDescriptor() : rpDescriptor), true); } //===== DuplicateButton ======================================================= DuplicateButton::DuplicateButton (SlideSorter& rSlideSorter) : ImageButton( rSlideSorter, rSlideSorter.GetTheme()->GetIcon(Theme::Icon_Command3Large), rSlideSorter.GetTheme()->GetIcon(Theme::Icon_Command3LargeHover), rSlideSorter.GetTheme()->GetIcon(Theme::Icon_Command3Medium), rSlideSorter.GetTheme()->GetIcon(Theme::Icon_Command3MediumHover), rSlideSorter.GetTheme()->GetIcon(Theme::Icon_Command3Small), rSlideSorter.GetTheme()->GetIcon(Theme::Icon_Command3SmallHover), rSlideSorter.GetTheme()->GetString(Theme::String_Command3)) { } bool DuplicateButton::IsEnabled (void) const { ViewShell* pViewShell = mrSlideSorter.GetViewShell(); if (pViewShell == NULL) return false; SfxDispatcher* pDispatcher = pViewShell->GetDispatcher(); if (pDispatcher == NULL) return false; const SfxPoolItem* pState = NULL; const SfxItemState eState (pDispatcher->QueryState( SID_DUPLICATE_PAGE, pState)); return (eState & SFX_ITEM_DISABLED) == 0; } void DuplicateButton::ProcessClick (const model::SharedPageDescriptor& rpDescriptor) { if ( ! rpDescriptor) return; mrSlideSorter.GetView().SetPageUnderMouse(model::SharedPageDescriptor(),false); // When the page under the button is not selected then set the // selection to just this page. if ( ! rpDescriptor->HasState(model::PageDescriptor::ST_Selected)) { mrSlideSorter.GetController().GetPageSelector().DeselectAllPages(); mrSlideSorter.GetController().GetPageSelector().SelectPage(rpDescriptor); } // Duplicate the selected pages. Insert the new pages right // after the current selection and select them if (mrSlideSorter.GetViewShell() != NULL && mrSlideSorter.GetViewShell()->GetDispatcher() != NULL) { mrSlideSorter.GetViewShell()->GetDispatcher()->Execute( SID_DUPLICATE_PAGE, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD); } } } } } // end of namespace ::sd::slidesorter::view
25.055344
98
0.732881
[ "object", "vector", "model" ]
3bb4f721fc7433adc30f2ff94722b076e8bcd651
113,289
cpp
C++
third_party/libSBML-5.10.2-Source/src/sbml/packages/comp/validator/constraints/CompConsistencyConstraints.cpp
gitter-badger/sbmlsolver
c92936832297ea1d2ad7f17223b68ada43c8f0b2
[ "Apache-2.0" ]
null
null
null
third_party/libSBML-5.10.2-Source/src/sbml/packages/comp/validator/constraints/CompConsistencyConstraints.cpp
gitter-badger/sbmlsolver
c92936832297ea1d2ad7f17223b68ada43c8f0b2
[ "Apache-2.0" ]
null
null
null
third_party/libSBML-5.10.2-Source/src/sbml/packages/comp/validator/constraints/CompConsistencyConstraints.cpp
gitter-badger/sbmlsolver
c92936832297ea1d2ad7f17223b68ada43c8f0b2
[ "Apache-2.0" ]
null
null
null
/** * @cond doxygenLibsbmlInternal * * @file IdentifierConsistencyConstraints.cpp * @brief IdentifierConsistency check constraints. See SBML Wiki * @author Sarah Keating * * <!-------------------------------------------------------------------------- * This file is part of libSBML. Please visit http://sbml.org for more * information about SBML, and the latest version of libSBML. * * Copyright (C) 2013-2014 jointly by the following organizations: * 1. California Institute of Technology, Pasadena, CA, USA * 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK * 3. University of Heidelberg, Heidelberg, Germany * * Copyright 2011-2012 jointly by the following organizations: * 1. California Institute of Technology, Pasadena, CA, USA * 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation. A copy of the license agreement is provided * in the file named "LICENSE.txt" included with this software distribution * and also available online as http://sbml.org/software/libsbml/license.html * ---------------------------------------------------------------------- -->*/ #ifndef AddingConstraintsToValidator #include <sbml/validator/VConstraint.h> #include <sbml/packages/comp/validator/CompSBMLError.h> #include <sbml/packages/comp/util/SBMLResolverRegistry.h> #include <sbml/packages/comp/util/SBMLUri.h> #include <sbml/SBMLTypes.h> #include <sbml/packages/comp/common/CompExtensionTypes.h> #include <sbml/util/MetaIdFilter.h> #include <sbml/util/IdFilter.h> #include "ExtModelReferenceCycles.h" #include "SubmodelReferenceCycles.h" #include "UniquePortReferences.h" #include "UniqueReplacedReferences.h" #include "ClassReplacements.h" #include "PackageIdReplacementCheck.h" #endif #include <sbml/common/libsbml-namespace.h> #include <sbml/validator/ConstraintMacros.h> /** @cond doxygenIgnored */ using namespace std; LIBSBML_CPP_NAMESPACE_USE /** @endcond */ class ReferencedModel { public: ReferencedModel(const Model & m, const Port & p) { referencedModel = static_cast<const Model*>(p.getAncestorOfType(SBML_MODEL, "core")); if (referencedModel == NULL) { referencedModel = static_cast<const Model*> (p.getAncestorOfType(SBML_COMP_MODELDEFINITION, "comp")); } } ReferencedModel(const Model & m, const Deletion & d) { referencedModel = NULL; const Submodel * sub = static_cast<const Submodel*> (d.getAncestorOfType(SBML_COMP_SUBMODEL, "comp")); if (sub != NULL) { std::string modelId = sub->getModelRef(); const SBMLDocument * doc = d.getSBMLDocument(); bool found = false; while (doc != NULL && found == false) { CompSBMLDocumentPlugin * docPlug = (CompSBMLDocumentPlugin*)(doc->getPlugin("comp")); if (docPlug != NULL) { referencedModel = docPlug->getModelDefinition(modelId); if (referencedModel == NULL) { // may be an external model ExternalModelDefinition * emd = docPlug->getExternalModelDefinition(modelId); pre (emd != NULL); string locationURI = doc->getLocationURI(); string uri = emd->getSource(); const SBMLResolverRegistry& registry = SBMLResolverRegistry::getInstance(); doc = registry.resolve(uri, locationURI); if (doc != NULL) { if (emd->isSetModelRef() == false) { referencedModel = doc->getModel(); found = true; } else if (doc->getModel() != NULL && doc->getModel()->isSetId() == true && emd->getModelRef() == doc->getModel()->getId()) { referencedModel = doc->getModel(); found = true; } else { modelId = emd->getModelRef(); } } } else { found = true; } } else { found = true; } } } } ReferencedModel(const Model & m, const ReplacedElement & repE) { referencedModel = NULL; CompModelPlugin *plug = (CompModelPlugin*)(m.getPlugin("comp")); if ((plug != NULL) && (plug->getSubmodel(repE.getSubmodelRef()) != NULL)) { std::string modelId = (plug->getSubmodel(repE.getSubmodelRef()))->getModelRef(); const SBMLDocument * doc = repE.getSBMLDocument(); bool found = false; while (doc != NULL && found == false) { CompSBMLDocumentPlugin * docPlug = (CompSBMLDocumentPlugin*)(doc->getPlugin("comp")); if (docPlug != NULL) { referencedModel = docPlug->getModelDefinition(modelId); if (referencedModel == NULL) { // may be an external model ExternalModelDefinition * emd = docPlug->getExternalModelDefinition(modelId); pre (emd != NULL); string locationURI = doc->getLocationURI(); string uri = emd->getSource(); const SBMLResolverRegistry& registry = SBMLResolverRegistry::getInstance(); doc = registry.resolve(uri, locationURI); if (doc != NULL) { if (emd->isSetModelRef() == false) { referencedModel = doc->getModel(); found = true; } else if (doc->getModel() != NULL && doc->getModel()->isSetId() == true && emd->getModelRef() == doc->getModel()->getId()) { referencedModel = doc->getModel(); found = true; } else { modelId = emd->getModelRef(); } } } else { found = true; } } else { found = true; } } } } ReferencedModel(const Model & m, const ReplacedBy & repBy) { referencedModel = NULL; CompModelPlugin *plug = (CompModelPlugin*)(m.getPlugin("comp")); if ((plug != NULL) && (plug->getSubmodel(repBy.getSubmodelRef()) != NULL)) { std::string modelId = (plug->getSubmodel(repBy.getSubmodelRef()))->getModelRef(); const SBMLDocument * doc = repBy.getSBMLDocument(); bool found = false; while (doc != NULL && found == false) { CompSBMLDocumentPlugin * docPlug = (CompSBMLDocumentPlugin*)(doc->getPlugin("comp")); if (docPlug != NULL) { referencedModel = docPlug->getModelDefinition(modelId); if (referencedModel == NULL) { // may be an external model ExternalModelDefinition * emd = docPlug->getExternalModelDefinition(modelId); pre (emd != NULL); string locationURI = doc->getLocationURI(); string uri = emd->getSource(); const SBMLResolverRegistry& registry = SBMLResolverRegistry::getInstance(); doc = registry.resolve(uri, locationURI); if (doc != NULL) { if (emd->isSetModelRef() == false) { referencedModel = doc->getModel(); found = true; } else if (doc->getModel() != NULL && doc->getModel()->isSetId() == true && emd->getModelRef() == doc->getModel()->getId()) { referencedModel = doc->getModel(); found = true; } else { modelId = emd->getModelRef(); } } } else { found = true; } } else { found = true; } } } } ReferencedModel(const Model & m, const SBaseRef & sbRef) { referencedModel = NULL; if (sbRef.getParentSBMLObject() != NULL) { int tc = sbRef.getParentSBMLObject()->getTypeCode(); //const SBMLDocument * doc = sbRef.getSBMLDocument(); ReferencedModel *ref; std::string idRef; std::string metaIdRef; std::string modelId; const Model* parentRefModel = NULL; const ReplacedElement * repE = NULL; const ReplacedBy* repBy = NULL; const Deletion * del = NULL; const Port * port = NULL; const SBaseRef * parent = NULL; const SBaseRef * grandParent = NULL; int tc1; switch (tc) { case SBML_COMP_REPLACEDELEMENT: repE = static_cast<const ReplacedElement*>(sbRef.getParentSBMLObject()); ref = new ReferencedModel(m, *(repE)); parentRefModel = ref->getReferencedModel(); idRef = repE->getIdRef(); metaIdRef = repE->getMetaIdRef(); break; case SBML_COMP_REPLACEDBY: repBy = static_cast<const ReplacedBy*>(sbRef.getParentSBMLObject()); ref = new ReferencedModel(m, *(repBy)); parentRefModel = ref->getReferencedModel(); idRef = repBy->getIdRef(); metaIdRef = repBy->getMetaIdRef(); break; case SBML_COMP_PORT: port = static_cast<const Port*>(sbRef.getParentSBMLObject()); ref = new ReferencedModel(m, *(port)); parentRefModel = ref->getReferencedModel(); idRef = port->getIdRef(); metaIdRef = port->getMetaIdRef(); break; case SBML_COMP_DELETION: del = static_cast<const Deletion*>(sbRef.getParentSBMLObject()); ref = new ReferencedModel(m, *(del)); parentRefModel = ref->getReferencedModel(); idRef = del->getIdRef(); metaIdRef = del->getMetaIdRef(); break; case SBML_COMP_SBASEREF: parent = static_cast<const SBaseRef*>(sbRef.getParentSBMLObject()); idRef = parent->getIdRef(); metaIdRef = parent->getMetaIdRef(); if (idRef.empty() == false) { mReferences.push_back(make_pair(idRef, "id")); } else { mReferences.push_back(make_pair(metaIdRef, "metaid")); } grandParent = static_cast<const SBaseRef*> (parent->getParentSBMLObject()); tc1 = grandParent->getTypeCode(); while (tc1 == SBML_COMP_SBASEREF) { idRef = grandParent->getIdRef(); metaIdRef = grandParent->getMetaIdRef(); if (idRef.empty() == false) { mReferences.push_back(make_pair(idRef, "id")); } else { mReferences.push_back(make_pair(metaIdRef, "metaid")); } grandParent = static_cast<const SBaseRef*> (grandParent->getParentSBMLObject()); tc1 = grandParent->getTypeCode(); } switch (tc1) { case SBML_COMP_REPLACEDELEMENT: repE = static_cast<const ReplacedElement*>(grandParent); ref = new ReferencedModel(m, *(repE)); parentRefModel = ref->getReferencedModel(); idRef = repE->getIdRef(); metaIdRef = repE->getMetaIdRef(); break; case SBML_COMP_REPLACEDBY: repBy = static_cast<const ReplacedBy*>(grandParent); ref = new ReferencedModel(m, *(repBy)); parentRefModel = ref->getReferencedModel(); idRef = repBy->getIdRef(); metaIdRef = repBy->getMetaIdRef(); break; case SBML_COMP_PORT: port = static_cast<const Port*>(grandParent); ref = new ReferencedModel(m, *(port)); parentRefModel = ref->getReferencedModel(); idRef = port->getIdRef(); metaIdRef = port->getMetaIdRef(); break; case SBML_COMP_DELETION: del = static_cast<const Deletion*>(grandParent); ref = new ReferencedModel(m, *(del)); parentRefModel = ref->getReferencedModel(); idRef = del->getIdRef(); metaIdRef = del->getMetaIdRef(); break; } break; } if (parentRefModel != NULL) { const SBMLDocument* doc = parentRefModel->getSBMLDocument(); CompSBMLDocumentPlugin* docPlug = (CompSBMLDocumentPlugin*)(doc->getPlugin("comp")); CompModelPlugin *plug1 = (CompModelPlugin*)(parentRefModel->getPlugin("comp")); if (docPlug != NULL && plug1 != NULL) { if (idRef.empty() == false) { pre (plug1->getSubmodel(idRef) != NULL); modelId = (plug1->getSubmodel(idRef))->getModelRef(); } else { for (unsigned int i = 0; i < plug1->getNumSubmodels(); i++) { if (plug1->getSubmodel(i)->getMetaId() == metaIdRef) { modelId = plug1->getSubmodel(i)->getModelRef(); break; } } } referencedModel = docPlug->getModelDefinition(modelId); if (referencedModel == NULL) { /* may be an external model */ ExternalModelDefinition * emd = docPlug->getExternalModelDefinition(modelId); pre (emd != NULL); string locationURI = doc->getLocationURI(); string uri = emd->getSource(); const SBMLResolverRegistry& registry = SBMLResolverRegistry::getInstance(); SBMLDocument *newDoc = registry.resolve(uri, locationURI); pre(newDoc != NULL); referencedModel = newDoc->getModel(); } while (mReferences.empty() == false) { size_t numRefs = mReferences.size(); if (mReferences.at(numRefs - 1).second == "id") { idRef = mReferences.at(numRefs -1 ).first; metaIdRef = ""; } else { metaIdRef = mReferences.at(numRefs -1 ).first; idRef = ""; } CompModelPlugin *plug1 = (CompModelPlugin*)(referencedModel->getPlugin("comp")); if (docPlug != NULL && plug1 != NULL) { if (idRef.empty() == false) { pre (plug1->getSubmodel(idRef) != NULL); modelId = (plug1->getSubmodel(idRef))->getModelRef(); } else { for (unsigned int i = 0; i < plug1->getNumSubmodels(); i++) { if (plug1->getSubmodel(i)->getMetaId() == metaIdRef) { modelId = plug1->getSubmodel(i)->getModelRef(); break; } } } referencedModel = docPlug->getModelDefinition(modelId); if (referencedModel == NULL) { /* may be an external model */ ExternalModelDefinition * emd = docPlug->getExternalModelDefinition(modelId); pre (emd != NULL); string locationURI = doc->getLocationURI(); string uri = emd->getSource(); const SBMLResolverRegistry& registry = SBMLResolverRegistry::getInstance(); SBMLDocument *newDoc = registry.resolve(uri, locationURI); pre(newDoc != NULL); referencedModel = newDoc->getModel(); } } mReferences.erase(mReferences.end()-1); } } } } } const Model * getReferencedModel() { return referencedModel; } private: const Model* referencedModel; vector< pair< std::string, std::string > > mReferences; }; //************************************* //SBase constraints // 20101 - caught at read // 20102 - caught at read // 20103 - caught at read // 20104 - caught at read // 20105 - caught at read //************************************* //SBML class constraints // 20201 - caught at read // 20202 - caught at read // 20203 - caught by checkConsistency // 20204 - caught by checkConsistency // 20205 - caught at read // 20206 - caught at read // 20207 - caught at read // 20208 - caught at read // 20209 - caught at read // 20210 - caught at read // 20211 - caught at read //************************************* //ExternalModelDefinition constraints // 20301 - caught at read // 20302 - caught at read // 20303 - caught at read //20304 START_CONSTRAINT (CompReferenceMustBeL3, ExternalModelDefinition, emd) { pre (emd.isSetSource() == true); pre (emd.isSetId() == true); bool fail = false; msg = "<externalModelDefinition> '"; msg += emd.getId(); msg += "' refers to a URI '"; msg += emd.getSource(); msg += "' which is not an SBML Level 3 document."; const SBMLResolverRegistry& registry = SBMLResolverRegistry::getInstance(); const SBMLDocument* doc = emd.getSBMLDocument(); pre(doc != NULL); string locationURI = doc->getLocationURI(); string uri = emd.getSource(); doc = NULL; doc = registry.resolve(uri, locationURI); pre (doc != NULL); if (doc->getLevel() != 3) { fail = true; } delete doc; inv(fail == false); } END_CONSTRAINT //20305 START_CONSTRAINT (CompModReferenceMustIdOfModel, ExternalModelDefinition, emd) { pre (emd.isSetSource() == true); pre (emd.isSetId() == true); pre (emd.isSetModelRef() == true); bool fail = false; msg = "<externalModelDefinition> '"; msg += emd.getId() ; msg += "' refers to a model with id '"; msg += emd.getModelRef(); msg += "' that does not exist in the referenced document."; const SBMLResolverRegistry& registry = SBMLResolverRegistry::getInstance(); const SBMLDocument* doc = emd.getSBMLDocument(); pre(doc != NULL); string locationURI = doc->getLocationURI(); string uri = emd.getSource(); //SBMLUri* resolved = registry.resolveUri(uri, locationURI); //pre(resolved != NULL ) //string resolvedURI = resolved->getUri(); //delete resolved; doc = registry.resolve(uri, locationURI); pre(doc != NULL); pre(doc->getLevel() == 3); const CompSBMLDocumentPlugin* csdp = static_cast<const CompSBMLDocumentPlugin*>(doc->getPlugin("comp")); if (csdp == NULL) { const Model* model = doc->getModel(); if (model==NULL || (model->getId() != emd.getModelRef())) { fail = true; } } else { const SBase* referencedmod = csdp->getModel(emd.getModelRef()); if (referencedmod == NULL) { fail = true; } } delete doc; inv(fail == false); } END_CONSTRAINT //TODO: 20306 - caught at read md5 // 20307 - caught at read anyURI // 20308 - caught at read // 20309 - string // 20310 EXTERN_CONSTRAINT( CompCircularExternalModelReference, ExtModelReferenceCycles) //90101 START_CONSTRAINT (CompUnresolvedReference, ExternalModelDefinition, emd) { pre (emd.isSetSource() == true); const SBMLDocument* doc = emd.getSBMLDocument(); pre(doc != NULL); string locationURI = doc->getLocationURI(); string uri = emd.getSource(); const SBMLResolverRegistry& registry = SBMLResolverRegistry::getInstance(); SBMLUri* resolved = registry.resolveUri(uri, locationURI); bool fail = false; msg = "<externalModelDefinition> '"; msg += emd.getId() ; msg += "' refers to a source '"; msg += emd.getSource(); msg += "' that cannot be accessed from here. Further checks relating to"; msg += " this document cannot be performed."; if (resolved == NULL) { fail = true; } inv(fail == false); } END_CONSTRAINT //************************************* // 204xx - not used //************************************* //Model constraints //20501 - caught at read //20502 - caught at read //20503 - caught at read //20504 - caught at read //20505 - caught at read //20506 - caught at read //************************************* //Submodel constraints //20601 - caught at read //20602 - caught at read //20603 - caught at read //20604 - caught at read //20605 - caught at read //20606 - caught at read //20607 - caught at read //20608 - caught at read //20609-20612 - non existant //20613 - caught at read //20614 - caught at read //20615 START_CONSTRAINT (CompSubmodelMustReferenceModel, Submodel, s) { pre (s.isSetModelRef() == true); bool fail = true; msg = "<submodel> '"; msg += s.getId() ; msg += "' in "; const Model* mod = static_cast<const Model*> (s.getAncestorOfType(SBML_MODEL, "core")); if (mod == NULL) { mod = static_cast<const Model*> (s.getAncestorOfType(SBML_COMP_MODELDEFINITION, "comp")); } if (mod == NULL || !mod->isSetId()) { msg += "the main model in the document"; } else { msg += "the model '"; msg += mod->getId(); msg += "'"; } msg += " refers to a model with id '"; msg += s.getModelRef(); msg += "' that does not exist in the referenced document."; // do we reference the actual model // do not report this here as it is another error if (s.getModelRef() == m.getId()) { fail = false; } if (fail == true) { // do we refernce an external modelDefinition CompSBMLDocumentPlugin *docPlug = (CompSBMLDocumentPlugin*) (m.getSBMLDocument()->getPlugin("comp")); pre (docPlug != NULL); ModelDefinition * md = docPlug->getModelDefinition(s.getModelRef()); if (md == NULL) { ExternalModelDefinition * ext = docPlug->getExternalModelDefinition(s.getModelRef()); if (ext != NULL) { fail = false; } } else { fail = false; } } inv(fail == false); } END_CONSTRAINT //20616 START_CONSTRAINT (CompSubmodelCannotReferenceSelf, Submodel, s) { pre (s.isSetModelRef() == true); bool fail = false; msg = "<submodel> '"; msg += s.getId() ; msg += "' in "; const Model* mod = static_cast<const Model*> (s.getAncestorOfType(SBML_MODEL, "core")); if (mod == NULL) { mod = static_cast<const Model*> (s.getAncestorOfType(SBML_COMP_MODELDEFINITION, "comp")); } if (mod == NULL || !mod->isSetId()) { msg += "the main model in the document"; } else { msg += "the model '"; msg += mod->getId(); msg += "'"; } msg += " refers to the enclosing model with id '"; msg += s.getModelRef(); msg += "'."; if (m.getId() == s.getModelRef()) { fail = true; } inv(fail == false); } END_CONSTRAINT // 20617 EXTERN_CONSTRAINT( CompModCannotCircularlyReferenceSelf, SubmodelReferenceCycles) // 20618 - 20621 non existant //20622 START_CONSTRAINT (CompTimeConversionMustBeParameter, Submodel, s) { pre (s.isSetTimeConversionFactor() == true); bool fail = false; msg = "The 'timeConversionFactor' of <submodel> '"; msg += s.getId() ; msg += "' in "; const Model* mod = static_cast<const Model*> (s.getAncestorOfType(SBML_MODEL, "core")); if (mod == NULL) { mod = static_cast<const Model*> (s.getAncestorOfType(SBML_COMP_MODELDEFINITION, "comp")); } if (mod == NULL || !mod->isSetId()) { msg += "the main model in the document"; } else { msg += "the model '"; msg += mod->getId(); msg += "'"; } msg += " is set to '"; msg += s.getTimeConversionFactor(); msg += "' which is not a <parameter> within the <model>."; if (m.getParameter(s.getTimeConversionFactor()) == NULL) { fail = true; } inv(fail == false); } END_CONSTRAINT //20623 START_CONSTRAINT (CompExtentConversionMustBeParameter, Submodel, s) { pre (s.isSetExtentConversionFactor() == true); bool fail = false; msg = "The 'extentConversionFactor' of <submodel> '"; msg += s.getId() ; msg += "' in "; const Model* mod = static_cast<const Model*> (s.getAncestorOfType(SBML_MODEL, "core")); if (mod == NULL) { mod = static_cast<const Model*> (s.getAncestorOfType(SBML_COMP_MODELDEFINITION, "comp")); } if (mod == NULL || !mod->isSetId()) { msg += "the main model in the document"; } else { msg += "the model '"; msg += mod->getId(); msg += "'"; } msg += " is set to '"; msg += s.getExtentConversionFactor(); msg += "' which is not a <parameter> within the <model>."; if (m.getParameter(s.getExtentConversionFactor()) == NULL) { fail = true; } inv(fail == false); } END_CONSTRAINT //************************************* //SBaseRef constraints // - need to implement for each object that derives from SBaseRef // Port; Deletion; ReplacedElement; ReplacedBy //20701 // Port doesnt have portRef // 20701 - deletion START_CONSTRAINT (CompPortRefMustReferencePort, Deletion, d) { pre(d.isSetPortRef()); bool fail = false; const Submodel * sub = static_cast<const Submodel*> (d.getAncestorOfType(SBML_COMP_SUBMODEL, "comp")); pre (sub != NULL); msg = "The 'portRef' of a <deletion>"; msg += " is set to '"; msg += d.getPortRef(); msg += "' which is not a <port> within the <model> referenced by "; msg += "submodel '"; msg += sub->getId(); msg += "'."; ReferencedModel *ref = new ReferencedModel(m, d); const Model* referencedModel = ref->getReferencedModel(); pre (referencedModel != NULL); CompModelPlugin *plug1 = (CompModelPlugin*)(referencedModel->getPlugin("comp")); pre (plug1 != NULL); if (plug1->getPort(d.getPortRef()) == NULL) { /* take out for now since I was right the first time * the reference should be there without need to instantiate */ //// it is possible that the referenced model needs to actually instantiate //// its submodels to find the reference //// we are not going to do that here so if there are submodels //// give it the benefit of the doubt and do not report the id as missing //const CompModelPlugin * plug = static_cast<const CompModelPlugin*> // (referencedModel->getPlugin("comp")); //if (plug == NULL || plug->getNumSubmodels() == 0) //{ // fail = true; //} fail = true; } inv(fail == false); } END_CONSTRAINT // 20701 - replacedElement START_CONSTRAINT (CompPortRefMustReferencePort, ReplacedElement, repE) { pre(repE.isSetPortRef()); pre(repE.isSetSubmodelRef()); bool fail = false; msg = "The 'portRef' of a <replacedElement>"; msg += " is set to '"; msg += repE.getPortRef(); msg += "' which is not a <port> within the <model> referenced by "; msg += "submodel '"; msg += repE.getSubmodelRef(); msg += "'."; /* need to be using the correct model */ ReferencedModel *ref = new ReferencedModel(m, repE); const Model* referencedModel = ref->getReferencedModel(); pre (referencedModel != NULL); CompModelPlugin *plug1 = (CompModelPlugin*)(referencedModel->getPlugin("comp")); pre (plug1 != NULL); if (plug1->getPort(repE.getPortRef()) == NULL) { /* take out for now since I was right the first time * the reference should be there without need to instantiate */ //// it is possible that the referenced model needs to actually instantiate //// its submodels to find the reference //// we are not going to do that here so if there are submodels //// give it the benefit of the doubt and do not report the id as missing //const CompModelPlugin * plug = static_cast<const CompModelPlugin*> // (referencedModel->getPlugin("comp")); //if (plug == NULL || plug->getNumSubmodels() == 0) //{ // fail = true; //} fail = true; } inv(fail == false); } END_CONSTRAINT // 20701 - replacedBy START_CONSTRAINT (CompPortRefMustReferencePort, ReplacedBy, repBy) { pre(repBy.isSetPortRef()); pre(repBy.isSetSubmodelRef()); bool fail = false; msg = "The 'portRef' of a <replacedBy>"; msg += " is set to '"; msg += repBy.getPortRef(); msg += "' which is not a <port> within the <model> referenced by "; msg += "submodel '"; msg += repBy.getSubmodelRef(); msg += "'."; /* need to be using the correct model */ ReferencedModel *ref = new ReferencedModel(m, repBy); const Model* referencedModel = ref->getReferencedModel(); pre (referencedModel != NULL); CompModelPlugin *plug1 = (CompModelPlugin*)(referencedModel->getPlugin("comp")); pre (plug1 != NULL); if (plug1->getPort(repBy.getPortRef()) == NULL) { /* take out for now since I was right the first time * the reference should be there without need to instantiate */ //// it is possible that the referenced model needs to actually instantiate //// its submodels to find the reference //// we are not going to do that here so if there are submodels //// give it the benefit of the doubt and do not report the id as missing //const CompModelPlugin * plug = static_cast<const CompModelPlugin*> // (referencedModel->getPlugin("comp")); //if (plug == NULL || plug->getNumSubmodels() == 0) //{ // fail = true; //} fail = true; } inv(fail == false); } END_CONSTRAINT // 20701 - sBaseRef START_CONSTRAINT (CompPortRefMustReferencePort, SBaseRef, sbRef) { pre(sbRef.isSetPortRef()); bool fail = false; pre (sbRef.getParentSBMLObject() != NULL); int tc = sbRef.getParentSBMLObject()->getTypeCode(); msg = "The 'portRef' of a <sBaseRef>"; msg += " is set to '"; msg += sbRef.getPortRef(); msg += "' which is not a <port> within the <model> referenced by "; if (tc == SBML_COMP_REPLACEDELEMENT) { msg += "the submodel '"; msg += static_cast<const ReplacedElement*>(sbRef.getParentSBMLObject()) ->getSubmodelRef(); msg += "'."; } else if (tc == SBML_COMP_REPLACEDBY) { msg += "the submodel '"; msg += static_cast<const ReplacedBy*>(sbRef.getParentSBMLObject()) ->getSubmodelRef(); msg += "'."; } else if (tc == SBML_COMP_PORT) { msg += "port '"; msg += sbRef.getParentSBMLObject()->getId(); msg += "'."; } else if (tc == SBML_COMP_DELETION) { const Submodel * sub = static_cast<const Submodel*> (sbRef.getParentSBMLObject() ->getAncestorOfType(SBML_COMP_SUBMODEL, "comp")); pre (sub != NULL); msg += "the submodel '"; msg += sub->getId(); msg += "'."; } else if (tc == SBML_COMP_SBASEREF) { msg += "the parent sBaseRef."; } /* need to be using the correct model */ ReferencedModel *ref = new ReferencedModel(m, sbRef); const Model* referencedModel = ref->getReferencedModel(); pre (referencedModel != NULL); CompModelPlugin *plug1 = (CompModelPlugin*)(referencedModel->getPlugin("comp")); pre (plug1 != NULL); if (plug1->getPort(sbRef.getPortRef()) == NULL) { /* take out for now since I was right the first time * the reference should be there without need to instantiate */ //// it is possible that the referenced model needs to actually instantiate //// its submodels to find the reference //// we are not going to do that here so if there are submodels //// give it the benefit of the doubt and do not report the id as missing //const CompModelPlugin * plug = static_cast<const CompModelPlugin*> // (referencedModel->getPlugin("comp")); //if (plug == NULL || plug->getNumSubmodels() == 0) //{ // fail = true; //} fail = true; } inv(fail == false); } END_CONSTRAINT // 20702 //20702 - port START_CONSTRAINT (CompIdRefMustReferenceObject, Port, p) { pre(p.isSetIdRef()); /* only log this if there are no unknown packages present */ const SBMLDocument *doc = m.getSBMLDocument(); SBMLErrorLog *errlog = const_cast<SBMLErrorLog*>(doc->getErrorLog()); bool unknownPackagePresent = false; if (errlog->contains(UnrequiredPackagePresent) || errlog->contains(RequiredPackagePresent)) { unknownPackagePresent = true; } pre ( unknownPackagePresent == false); bool fail = false; msg = "The 'idRef' of a <port>"; msg += " is set to '"; msg += p.getIdRef(); msg += "' which is not an element within the <model>."; IdList mIds; // create the filter we want to use IdFilter filter; ReferencedModel *ref = new ReferencedModel(m, p); const Model* mod = ref->getReferencedModel(); pre (mod != NULL); List* allElements = const_cast<Model*>(mod)->getAllElements(&filter); for (unsigned int i = 0; i < allElements->getSize(); i++) { mIds.append(static_cast<SBase*>(allElements->get(i))->getId()); } delete allElements; if (mIds.contains(p.getIdRef()) == false) { /* take out for now since I was right the first time * the reference should be there without need to instantiate */ //// it is possible that the referenced model needs to actually instantiate //// its submodels to find the reference //// we are not going to do that here so if there are submodels //// give it the benefit of the doubt and do not report the id as missing //const CompModelPlugin * plug = static_cast<const CompModelPlugin*> // (referencedModel->getPlugin("comp")); //if (plug == NULL || plug->getNumSubmodels() == 0) //{ // fail = true; //} fail = true; } inv(fail == false); } END_CONSTRAINT // 20702 - deletion START_CONSTRAINT (CompIdRefMustReferenceObject, Deletion, d) { pre(d.isSetIdRef()); /* only log this if there are no unknown packages present */ const SBMLDocument *doc = m.getSBMLDocument(); SBMLErrorLog *errlog = const_cast<SBMLErrorLog*>(doc->getErrorLog()); bool unknownPackagePresent = false; if (errlog->contains(UnrequiredPackagePresent) || errlog->contains(RequiredPackagePresent)) { unknownPackagePresent = true; } pre ( unknownPackagePresent == false); bool fail = false; const Submodel * sub = static_cast<const Submodel*> (d.getAncestorOfType(SBML_COMP_SUBMODEL, "comp")); pre (sub != NULL); msg = "The 'idRef' of a <deletion>"; msg += " is set to '"; msg += d.getIdRef(); msg += "' which is not an element within the <model> referenced by "; msg += "submodel '"; msg += sub->getId(); msg += "'."; ReferencedModel *ref = new ReferencedModel(m, d); const Model* referencedModel = ref->getReferencedModel(); pre (referencedModel != NULL); IdList mIds; // create the filter we want to use IdFilter filter; // get a list of all elements with an id List* allElements = const_cast<Model*> (referencedModel)->getAllElements(&filter); for (unsigned int i = 0; i < allElements->getSize(); i++) { mIds.append(static_cast<SBase*>(allElements->get(i))->getId()); } delete allElements; if (mIds.contains(d.getIdRef()) == false) { /* take out for now since I was right the first time * the reference should be there without need to instantiate */ //// it is possible that the referenced model needs to actually instantiate //// its submodels to find the reference //// we are not going to do that here so if there are submodels //// give it the benefit of the doubt and do not report the id as missing //const CompModelPlugin * plug = static_cast<const CompModelPlugin*> // (referencedModel->getPlugin("comp")); //if (plug == NULL || plug->getNumSubmodels() == 0) //{ // fail = true; //} fail = true; } inv(fail == false); } END_CONSTRAINT // 20702 - replacedElement START_CONSTRAINT (CompIdRefMustReferenceObject, ReplacedElement, repE) { pre(repE.isSetIdRef()); pre(repE.isSetSubmodelRef()); /* only log this if there are no unknown packages present */ const SBMLDocument *doc = m.getSBMLDocument(); SBMLErrorLog *errlog = const_cast<SBMLErrorLog*>(doc->getErrorLog()); bool unknownPackagePresent = false; if (errlog->contains(UnrequiredPackagePresent) || errlog->contains(RequiredPackagePresent)) { unknownPackagePresent = true; } pre ( unknownPackagePresent == false); bool fail = false; msg = "The 'idRef' of a <replacedElement>"; msg += " is set to '"; msg += repE.getIdRef(); msg += "' which is not an element within the <model> referenced by "; msg += "submodel '"; msg += repE.getSubmodelRef(); msg += "'."; /* need to be using the correct model */ ReferencedModel ref(m, repE); const Model* referencedModel = ref.getReferencedModel(); pre (referencedModel != NULL); IdList mIds; // create the filter we want to use IdFilter filter; // get a list of all elements with an id List* allElements = const_cast<Model*> (referencedModel)->getAllElements(&filter); for (unsigned int i = 0; i < allElements->getSize(); i++) { mIds.append(static_cast<SBase*>(allElements->get(i))->getId()); } delete allElements; if (mIds.contains(repE.getIdRef()) == false) { /* take out for now since I was right the first time * the reference should be there without need to instantiate */ //// it is possible that the referenced model needs to actually instantiate //// its submodels to find the reference //// we are not going to do that here so if there are submodels //// give it the benefit of the doubt and do not report the id as missing //const CompModelPlugin * plug = static_cast<const CompModelPlugin*> // (referencedModel->getPlugin("comp")); //if (plug == NULL || plug->getNumSubmodels() == 0) //{ // fail = true; //} fail = true; } inv(fail == false); } END_CONSTRAINT // 20702 - replacedBy START_CONSTRAINT (CompIdRefMustReferenceObject, ReplacedBy, repBy) { pre(repBy.isSetIdRef()); pre(repBy.isSetSubmodelRef()); bool fail = false; msg = "The 'idRef' of a <replacedBy>"; msg += " is set to '"; msg += repBy.getIdRef(); msg += "' which is not an element within the <model> referenced by "; msg += "submodel '"; msg += repBy.getSubmodelRef(); msg += "'."; /* need to be using the correct model */ ReferencedModel *ref = new ReferencedModel(m, repBy); const Model* referencedModel = ref->getReferencedModel(); pre (referencedModel != NULL); IdList mIds; // create the filter we want to use IdFilter filter; // get a list of all elements with an id List* allElements = const_cast<Model*> (referencedModel)->getAllElements(&filter); for (unsigned int i = 0; i < allElements->getSize(); i++) { mIds.append(static_cast<SBase*>(allElements->get(i))->getId()); } delete allElements; if (mIds.contains(repBy.getIdRef()) == false) { /* take out for now since I was right the first time * the reference should be there without need to instantiate */ //// it is possible that the referenced model needs to actually instantiate //// its submodels to find the reference //// we are not going to do that here so if there are submodels //// give it the benefit of the doubt and do not report the id as missing //const CompModelPlugin * plug = static_cast<const CompModelPlugin*> // (referencedModel->getPlugin("comp")); //if (plug == NULL || plug->getNumSubmodels() == 0) //{ // fail = true; //} fail = true; } inv(fail == false); } END_CONSTRAINT // 20702 - sBaseRef START_CONSTRAINT (CompIdRefMustReferenceObject, SBaseRef, sbRef) { pre(sbRef.isSetIdRef()); /* only log this if there are no unknown packages present */ const SBMLDocument *doc = m.getSBMLDocument(); SBMLErrorLog *errlog = const_cast<SBMLErrorLog*>(doc->getErrorLog()); bool unknownPackagePresent = false; if (errlog->contains(UnrequiredPackagePresent) || errlog->contains(RequiredPackagePresent)) { unknownPackagePresent = true; } pre ( unknownPackagePresent == false); bool fail = false; pre (sbRef.getParentSBMLObject() != NULL); int tc = sbRef.getParentSBMLObject()->getTypeCode(); msg = "The 'idRef' of a <sBaseRef>"; msg += " is set to '"; msg += sbRef.getIdRef(); msg += "' which is not an element within the <model> referenced by "; if (tc == SBML_COMP_REPLACEDELEMENT) { msg += "the submodel '"; msg += static_cast<const ReplacedElement*>(sbRef.getParentSBMLObject()) ->getSubmodelRef(); msg += "'."; } else if (tc == SBML_COMP_REPLACEDBY) { msg += "the submodel '"; msg += static_cast<const ReplacedBy*>(sbRef.getParentSBMLObject()) ->getSubmodelRef(); msg += "'."; } else if (tc == SBML_COMP_PORT) { msg += "port '"; msg += sbRef.getParentSBMLObject()->getId(); msg += "'."; } else if (tc == SBML_COMP_DELETION) { const Submodel * sub = static_cast<const Submodel*> (sbRef.getParentSBMLObject() ->getAncestorOfType(SBML_COMP_SUBMODEL, "comp")); pre (sub != NULL); msg += "the submodel '"; msg += sub->getId(); msg += "'."; } else if (tc == SBML_COMP_SBASEREF) { msg += "the parent sBaseRef."; } /* need to be using the correct model */ ReferencedModel *ref = new ReferencedModel(m, sbRef); const Model* referencedModel = ref->getReferencedModel(); pre (referencedModel != NULL); IdList mIds; // create the filter we want to use IdFilter filter; // get a list of all elements with an id List* allElements = const_cast<Model*> (referencedModel)->getAllElements(&filter); for (unsigned int i = 0; i < allElements->getSize(); i++) { mIds.append(static_cast<SBase*>(allElements->get(i))->getId()); } delete allElements; if (mIds.contains(sbRef.getIdRef()) == false) { /* take out for now since I was right the first time * the reference should be there without need to instantiate */ //// it is possible that the referenced model needs to actually instantiate //// its submodels to find the reference //// we are not going to do that here so if there are submodels //// give it the benefit of the doubt and do not report the id as missing //const CompModelPlugin * plug = static_cast<const CompModelPlugin*> // (referencedModel->getPlugin("comp")); //if (plug == NULL || plug->getNumSubmodels() == 0) //{ // fail = true; //} fail = true; } inv(fail == false); } END_CONSTRAINT // 20703 //20703 - port START_CONSTRAINT (CompUnitRefMustReferenceUnitDef, Port, p) { pre(p.isSetUnitRef()); bool fail = false; msg = "The 'unitRef' of a <port>"; msg += " is set to '"; msg += p.getUnitRef(); msg += "' which is not a <unitDefinition> within the <model>."; if (m.getUnitDefinition(p.getUnitRef()) == NULL) { /* take out for now since I was right the first time * the reference should be there without need to instantiate */ //// it is possible that the referenced model needs to actually instantiate //// its submodels to find the reference //// we are not going to do that here so if there are submodels //// give it the benefit of the doubt and do not report the id as missing //const CompModelPlugin * plug = static_cast<const CompModelPlugin*> // (referencedModel->getPlugin("comp")); //if (plug == NULL || plug->getNumSubmodels() == 0) //{ // fail = true; //} fail = true; } inv(fail == false); } END_CONSTRAINT // 20703 - deletion START_CONSTRAINT (CompUnitRefMustReferenceUnitDef, Deletion, d) { pre(d.isSetUnitRef()); bool fail = false; const Submodel * sub = static_cast<const Submodel*> (d.getAncestorOfType(SBML_COMP_SUBMODEL, "comp")); pre (sub != NULL); msg = "The 'unitRef' of a <deletion>"; msg += " is set to '"; msg += d.getUnitRef(); msg += "' which is not a <unitDefinition> within the <model> referenced by "; msg += "submodel '"; msg += sub->getId(); msg += "'."; ReferencedModel *ref = new ReferencedModel(m, d); const Model* referencedModel = ref->getReferencedModel(); pre (referencedModel != NULL); if (referencedModel->getUnitDefinition(d.getUnitRef()) == NULL) { /* take out for now since I was right the first time * the reference should be there without need to instantiate */ //// it is possible that the referenced model needs to actually instantiate //// its submodels to find the reference //// we are not going to do that here so if there are submodels //// give it the benefit of the doubt and do not report the id as missing //const CompModelPlugin * plug = static_cast<const CompModelPlugin*> // (referencedModel->getPlugin("comp")); //if (plug == NULL || plug->getNumSubmodels() == 0) //{ // fail = true; //} fail = true; } inv(fail == false); } END_CONSTRAINT // 20703 - replacedElement START_CONSTRAINT (CompUnitRefMustReferenceUnitDef, ReplacedElement, repE) { pre(repE.isSetUnitRef()); pre(repE.isSetSubmodelRef()); bool fail = false; msg = "The 'unitRef' of a <replacedElement>"; msg += " is set to '"; msg += repE.getUnitRef(); msg += "' which is not a <unitDefinition> within the <model> referenced by "; msg += "submodel '"; msg += repE.getSubmodelRef(); msg += "'."; /* need to be using the correct model */ ReferencedModel *ref = new ReferencedModel(m, repE); const Model* referencedModel = ref->getReferencedModel(); pre (referencedModel != NULL); if (referencedModel->getUnitDefinition(repE.getUnitRef()) == NULL) { /* take out for now since I was right the first time * the reference should be there without need to instantiate */ //// it is possible that the referenced model needs to actually instantiate //// its submodels to find the reference //// we are not going to do that here so if there are submodels //// give it the benefit of the doubt and do not report the id as missing //const CompModelPlugin * plug = static_cast<const CompModelPlugin*> // (referencedModel->getPlugin("comp")); //if (plug == NULL || plug->getNumSubmodels() == 0) //{ // fail = true; //} fail = true; } inv(fail == false); } END_CONSTRAINT // 20703 - replacedBy START_CONSTRAINT (CompUnitRefMustReferenceUnitDef, ReplacedBy, repBy) { pre(repBy.isSetUnitRef()); pre(repBy.isSetSubmodelRef()); bool fail = false; msg = "The 'unitRef' of a <replacedBy>"; msg += " is set to '"; msg += repBy.getUnitRef(); msg += "' which is not a <unitDefinition> within the <model> referenced by "; msg += "submodel '"; msg += repBy.getSubmodelRef(); msg += "'."; /* need to be using the correct model */ ReferencedModel *ref = new ReferencedModel(m, repBy); const Model* referencedModel = ref->getReferencedModel(); pre (referencedModel != NULL); if (referencedModel->getUnitDefinition(repBy.getUnitRef()) == NULL) { /* take out for now since I was right the first time * the reference should be there without need to instantiate */ //// it is possible that the referenced model needs to actually instantiate //// its submodels to find the reference //// we are not going to do that here so if there are submodels //// give it the benefit of the doubt and do not report the id as missing //const CompModelPlugin * plug = static_cast<const CompModelPlugin*> // (referencedModel->getPlugin("comp")); //if (plug == NULL || plug->getNumSubmodels() == 0) //{ // fail = true; //} fail = true; } inv(fail == false); } END_CONSTRAINT // 20703 - sBaseRef START_CONSTRAINT (CompUnitRefMustReferenceUnitDef, SBaseRef, sbRef) { pre(sbRef.isSetUnitRef()); bool fail = false; pre (sbRef.getParentSBMLObject() != NULL); int tc = sbRef.getParentSBMLObject()->getTypeCode(); msg = "The 'unitRef' of a <sBaseRef>"; msg += " is set to '"; msg += sbRef.getUnitRef(); msg += "' which is not a <unitDefinition> within the <model> referenced by "; if (tc == SBML_COMP_REPLACEDELEMENT) { msg += "the submodel '"; msg += static_cast<const ReplacedElement*>(sbRef.getParentSBMLObject()) ->getSubmodelRef(); msg += "'."; } else if (tc == SBML_COMP_REPLACEDBY) { msg += "the submodel '"; msg += static_cast<const ReplacedBy*>(sbRef.getParentSBMLObject()) ->getSubmodelRef(); msg += "'."; } else if (tc == SBML_COMP_PORT) { msg += "port '"; msg += sbRef.getParentSBMLObject()->getId(); msg += "'."; } else if (tc == SBML_COMP_DELETION) { const Submodel * sub = static_cast<const Submodel*> (sbRef.getParentSBMLObject() ->getAncestorOfType(SBML_COMP_SUBMODEL, "comp")); pre (sub != NULL); msg += "the submodel '"; msg += sub->getId(); msg += "'."; } else if (tc == SBML_COMP_SBASEREF) { msg += "the parent sBaseRef."; } /* need to be using the correct model */ ReferencedModel *ref = new ReferencedModel(m, sbRef); const Model* referencedModel = ref->getReferencedModel(); pre (referencedModel != NULL); if (referencedModel->getUnitDefinition(sbRef.getUnitRef()) == NULL) { /* take out for now since I was right the first time * the reference should be there without need to instantiate */ //// it is possible that the referenced model needs to actually instantiate //// its submodels to find the reference //// we are not going to do that here so if there are submodels //// give it the benefit of the doubt and do not report the id as missing //const CompModelPlugin * plug = static_cast<const CompModelPlugin*> // (referencedModel->getPlugin("comp")); //if (plug == NULL || plug->getNumSubmodels() == 0) //{ // fail = true; //} fail = true; } inv(fail == false); } END_CONSTRAINT // 20704 //20704 - port START_CONSTRAINT (CompMetaIdRefMustReferenceObject, Port, p) { pre(p.isSetMetaIdRef()); /* only log this if there are no unknown packages present */ const SBMLDocument *doc = m.getSBMLDocument(); SBMLErrorLog *errlog = const_cast<SBMLErrorLog*>(doc->getErrorLog()); bool unknownPackagePresent = false; if (errlog->contains(UnrequiredPackagePresent) || errlog->contains(RequiredPackagePresent)) { unknownPackagePresent = true; } pre ( unknownPackagePresent == false); bool fail = false; msg = "The 'metaIdRef' of a <port>"; msg += " is set to '"; msg += p.getMetaIdRef(); msg += "' which is not an element within the <model>."; IdList mIds; // create the filter we want to use MetaIdFilter filter; // get a list of all elements with an id ReferencedModel *ref = new ReferencedModel(m, p); const Model* mod = ref->getReferencedModel(); pre (mod != NULL); List* allElements = const_cast<Model*>(mod)->getAllElements(&filter); for (unsigned int i = 0; i < allElements->getSize(); i++) { mIds.append(static_cast<SBase*>(allElements->get(i))->getMetaId()); } if (mIds.contains(p.getMetaIdRef()) == false) { /* take out for now since I was right the first time * the reference should be there without need to instantiate */ //// it is possible that the referenced model needs to actually instantiate //// its submodels to find the reference //// we are not going to do that here so if there are submodels //// give it the benefit of the doubt and do not report the id as missing //const CompModelPlugin * plug = static_cast<const CompModelPlugin*> // (referencedModel->getPlugin("comp")); //if (plug == NULL || plug->getNumSubmodels() == 0) //{ // fail = true; //} fail = true; } inv(fail == false); } END_CONSTRAINT // 20704 - deletion START_CONSTRAINT (CompMetaIdRefMustReferenceObject, Deletion, d) { pre(d.isSetMetaIdRef()); /* only log this if there are no unknown packages present */ const SBMLDocument *doc = m.getSBMLDocument(); SBMLErrorLog *errlog = const_cast<SBMLErrorLog*>(doc->getErrorLog()); bool unknownPackagePresent = false; if (errlog->contains(UnrequiredPackagePresent) || errlog->contains(RequiredPackagePresent)) { unknownPackagePresent = true; } pre ( unknownPackagePresent == false); bool fail = false; const Submodel * sub = static_cast<const Submodel*> (d.getAncestorOfType(SBML_COMP_SUBMODEL, "comp")); pre (sub != NULL); msg = "The 'metaIdRef' of a <deletion>"; msg += " is set to '"; msg += d.getMetaIdRef(); msg += "' which is not an element within the <model> referenced by "; msg += "submodel '"; msg += sub->getId(); msg += "'."; ReferencedModel *ref = new ReferencedModel(m, d); const Model* referencedModel = ref->getReferencedModel(); pre (referencedModel != NULL); IdList mIds; // create the filter we want to use MetaIdFilter filter; // get a list of all elements with an id List* allElements = const_cast<Model*> (referencedModel)->getAllElements(&filter); for (unsigned int i = 0; i < allElements->getSize(); i++) { mIds.append(static_cast<SBase*>(allElements->get(i))->getMetaId()); } delete allElements; if (mIds.contains(d.getMetaIdRef()) == false) { /* take out for now since I was right the first time * the reference should be there without need to instantiate */ //// it is possible that the referenced model needs to actually instantiate //// its submodels to find the reference //// we are not going to do that here so if there are submodels //// give it the benefit of the doubt and do not report the id as missing //const CompModelPlugin * plug = static_cast<const CompModelPlugin*> // (referencedModel->getPlugin("comp")); //if (plug == NULL || plug->getNumSubmodels() == 0) //{ // fail = true; //} fail = true; } inv(fail == false); } END_CONSTRAINT // 20704 - replacedElement START_CONSTRAINT (CompMetaIdRefMustReferenceObject, ReplacedElement, repE) { pre(repE.isSetMetaIdRef()); pre(repE.isSetSubmodelRef()); /* only log this if there are no unknown packages present */ const SBMLDocument *doc = m.getSBMLDocument(); SBMLErrorLog *errlog = const_cast<SBMLErrorLog*>(doc->getErrorLog()); bool unknownPackagePresent = false; if (errlog->contains(UnrequiredPackagePresent) || errlog->contains(RequiredPackagePresent)) { unknownPackagePresent = true; } pre ( unknownPackagePresent == false); bool fail = false; msg = "The 'metaidRef' of a <replacedElement>"; msg += " is set to '"; msg += repE.getMetaIdRef(); msg += "' which is not an element within the <model> referenced by "; msg += "submodel '"; msg += repE.getSubmodelRef(); msg += "'."; /* need to be using the correct model */ ReferencedModel *ref = new ReferencedModel(m, repE); const Model* referencedModel = ref->getReferencedModel(); pre (referencedModel != NULL); IdList mIds; // create the filter we want to use MetaIdFilter filter; // get a list of all elements with an id List* allElements = const_cast<Model*> (referencedModel)->getAllElements(&filter); for (unsigned int i = 0; i < allElements->getSize(); i++) { mIds.append(static_cast<SBase*>(allElements->get(i))->getMetaId()); } delete allElements; if (mIds.contains(repE.getMetaIdRef()) == false) { /* take out for now since I was right the first time * the reference should be there without need to instantiate */ //// it is possible that the referenced model needs to actually instantiate //// its submodels to find the reference //// we are not going to do that here so if there are submodels //// give it the benefit of the doubt and do not report the id as missing //const CompModelPlugin * plug = static_cast<const CompModelPlugin*> // (referencedModel->getPlugin("comp")); //if (plug == NULL || plug->getNumSubmodels() == 0) //{ // fail = true; //} fail = true; } inv(fail == false); } END_CONSTRAINT // 20704 - replacedBy START_CONSTRAINT (CompMetaIdRefMustReferenceObject, ReplacedBy, repBy) { pre(repBy.isSetMetaIdRef()); pre(repBy.isSetSubmodelRef()); bool fail = false; msg = "The 'metaIdRef' of a <replacedBy>"; msg += " is set to '"; msg += repBy.getMetaIdRef(); msg += "' which is not an element within the <model> referenced by "; msg += "submodel '"; msg += repBy.getSubmodelRef(); msg += "'."; /* need to be using the correct model */ ReferencedModel *ref = new ReferencedModel(m, repBy); const Model* referencedModel = ref->getReferencedModel(); pre (referencedModel != NULL); IdList mIds; // create the filter we want to use MetaIdFilter filter; // get a list of all elements with an id List* allElements = const_cast<Model*> (referencedModel)->getAllElements(&filter); for (unsigned int i = 0; i < allElements->getSize(); i++) { mIds.append(static_cast<SBase*>(allElements->get(i))->getMetaId()); } delete allElements; if (mIds.contains(repBy.getMetaIdRef()) == false) { /* take out for now since I was right the first time * the reference should be there without need to instantiate */ //// it is possible that the referenced model needs to actually instantiate //// its submodels to find the reference //// we are not going to do that here so if there are submodels //// give it the benefit of the doubt and do not report the id as missing //const CompModelPlugin * plug = static_cast<const CompModelPlugin*> // (referencedModel->getPlugin("comp")); //if (plug == NULL || plug->getNumSubmodels() == 0) //{ // fail = true; //} fail = true; } inv(fail == false); } END_CONSTRAINT // 20704 - sBaseRef START_CONSTRAINT (CompMetaIdRefMustReferenceObject, SBaseRef, sbRef) { pre(sbRef.isSetMetaIdRef()); /* only log this if there are no unknown packages present */ const SBMLDocument *doc = m.getSBMLDocument(); SBMLErrorLog *errlog = const_cast<SBMLErrorLog*>(doc->getErrorLog()); bool unknownPackagePresent = false; if (errlog->contains(UnrequiredPackagePresent) || errlog->contains(RequiredPackagePresent)) { unknownPackagePresent = true; } pre ( unknownPackagePresent == false); bool fail = false; pre (sbRef.getParentSBMLObject() != NULL); int tc = sbRef.getParentSBMLObject()->getTypeCode(); msg = "The 'metaIdRef' of a <sBaseRef>"; msg += " is set to '"; msg += sbRef.getMetaIdRef(); msg += "' which is not an element within the <model> referenced by "; if (tc == SBML_COMP_REPLACEDELEMENT) { msg += "the submodel '"; msg += static_cast<const ReplacedElement*>(sbRef.getParentSBMLObject()) ->getSubmodelRef(); msg += "'."; } else if (tc == SBML_COMP_REPLACEDBY) { msg += "the submodel '"; msg += static_cast<const ReplacedBy*>(sbRef.getParentSBMLObject()) ->getSubmodelRef(); msg += "'."; } else if (tc == SBML_COMP_PORT) { msg += "port '"; msg += sbRef.getParentSBMLObject()->getId(); msg += "'."; } else if (tc == SBML_COMP_DELETION) { const Submodel * sub = static_cast<const Submodel*> (sbRef.getParentSBMLObject() ->getAncestorOfType(SBML_COMP_SUBMODEL, "comp")); pre (sub != NULL); msg += "the submodel '"; msg += sub->getId(); msg += "'."; } else if (tc == SBML_COMP_SBASEREF) { msg += "the parent sBaseRef."; } /* need to be using the correct model */ ReferencedModel *ref = new ReferencedModel(m, sbRef); const Model* referencedModel = ref->getReferencedModel(); pre (referencedModel != NULL); IdList mIds; // create the filter we want to use MetaIdFilter filter; // get a list of all elements with an id List* allElements = const_cast<Model*> (referencedModel)->getAllElements(&filter); for (unsigned int i = 0; i < allElements->getSize(); i++) { mIds.append(static_cast<SBase*>(allElements->get(i))->getMetaId()); } delete allElements; if (mIds.contains(sbRef.getMetaIdRef()) == false) { /* take out for now since I was right the first time * the reference should be there without need to instantiate */ //// it is possible that the referenced model needs to actually instantiate //// its submodels to find the reference //// we are not going to do that here so if there are submodels //// give it the benefit of the doubt and do not report the id as missing //const CompModelPlugin * plug = static_cast<const CompModelPlugin*> // (referencedModel->getPlugin("comp")); //if (plug == NULL || plug->getNumSubmodels() == 0) //{ // fail = true; //} fail = true; } inv(fail == false); } END_CONSTRAINT // 20705 // 20705 - port START_CONSTRAINT (CompParentOfSBRefChildMustBeSubmodel, Port, port) { pre (port.isSetSBaseRef()); bool fail = false; if (port.isSetIdRef() == true || port.isSetMetaIdRef() == true) { if (port.isSetIdRef() == true) { msg = "The 'idRef' of a <replacedElement>"; msg += " is set to '"; msg += port.getIdRef(); } else { msg = "The 'metaIdRef' of a <replacedElement>"; msg += " is set to '"; msg += port.getMetaIdRef(); } msg += "' which is not a submodel within the <model>."; /* need to be using the correct model */ ReferencedModel *ref = new ReferencedModel(m, port); const Model* mod = ref->getReferencedModel(); pre (mod != NULL); CompModelPlugin *plug = (CompModelPlugin*)(mod->getPlugin("comp")); pre (plug != NULL); if (port.isSetIdRef() == true) { if (plug->getSubmodel(port.getIdRef()) == NULL) { fail = true; } } else { // must be a metaidref std::string ref = port.getMetaIdRef(); bool found = false; unsigned int i = 0; while (found == false && i < plug->getNumSubmodels()) { if (ref == plug->getSubmodel(i)->getMetaId()) { found = true; } i++; } if (found == false) { fail = true; } } } else { fail = true; if (port.isSetUnitRef() == true) { msg = "The 'unitRef' of a <replacedElement>"; msg += " is set to '"; msg += port.getUnitRef(); } msg += "' which is not a submodel within the <model>."; } inv(fail == false); } END_CONSTRAINT // 20705 - deletion START_CONSTRAINT (CompParentOfSBRefChildMustBeSubmodel, Deletion, del) { pre (del.isSetSBaseRef()); bool fail = false; const Submodel * sub = static_cast<const Submodel*> (del.getAncestorOfType(SBML_COMP_SUBMODEL, "comp")); pre (sub != NULL); if (del.isSetIdRef() == true || del.isSetMetaIdRef() == true || del.isSetPortRef() == true) { if (del.isSetIdRef() == true) { msg = "The 'idRef' of a <deletion>"; msg += " is set to '"; msg += del.getIdRef(); } else if (del.isSetPortRef() == true) { msg = "The 'portRef' of a <deletion>"; msg += " is set to '"; msg += del.getPortRef(); } else { msg = "The 'metaIdRef' of a <deletion>"; msg += " is set to '"; msg += del.getMetaIdRef(); } msg += "' which is not a submodel within the <model> referenced by "; msg += "submodel '"; msg += sub->getId(); msg += "'."; /* need to be using the correct model */ ReferencedModel *ref = new ReferencedModel(m, del); const Model* referencedModel = ref->getReferencedModel(); pre (referencedModel != NULL); CompModelPlugin *plug1 = (CompModelPlugin*)(referencedModel->getPlugin("comp")); pre (plug1 != NULL); if (del.isSetIdRef() == true) { if (plug1->getSubmodel(del.getIdRef()) == NULL) { fail = true; } } else if (del.isSetPortRef() == true) { bool found = false; Port* port = plug1->getPort(del.getPortRef()); if (port->isSetIdRef() == true) { if (plug1->getSubmodel(port->getIdRef()) != NULL) { found = true; } } else if (port->isSetMetaIdRef() == true) { unsigned int i = 0; while (found == false && i < plug1->getNumSubmodels()) { if (port->getMetaIdRef() == plug1->getSubmodel(i)->getMetaId()) { found = true; } i++; } } if (found == false) { fail = true; } } else { // must be a metaidref std::string ref = del.getMetaIdRef(); bool found = false; unsigned int i = 0; while (found == false && i < plug1->getNumSubmodels()) { if (ref == plug1->getSubmodel(i)->getMetaId()) { found = true; } i++; } if (found == false) { fail = true; } } } else { fail = true; msg = "The 'unitRef' of a <deletion>"; msg += " is set to '"; msg += del.getUnitRef(); msg += "' which is not a submodel within the <model> referenced by "; msg += "submodel '"; msg += sub->getId(); msg += "'."; } inv(fail == false); } END_CONSTRAINT // 20705 - replacedElement START_CONSTRAINT (CompParentOfSBRefChildMustBeSubmodel, ReplacedElement, repE) { pre (repE.isSetSBaseRef()); bool fail = false; if (repE.isSetIdRef() == true || repE.isSetMetaIdRef() == true || repE.isSetPortRef() == true) { if (repE.isSetIdRef() == true) { msg = "The 'idRef' of a <replacedElement>"; msg += " is set to '"; msg += repE.getIdRef(); } else if (repE.isSetMetaIdRef() == true) { msg = "The 'metaIdRef' of a <replacedElement>"; msg += " is set to '"; msg += repE.getMetaIdRef(); } else { msg = "The 'portRef' of a <replacedElement>"; msg += " is set to '"; msg += repE.getPortRef(); } msg += "' which is not a submodel within the <model> referenced by "; msg += "submodel '"; msg += repE.getSubmodelRef(); msg += "'."; /* need to be using the correct model */ ReferencedModel *ref = new ReferencedModel(m, repE); const Model* referencedModel = ref->getReferencedModel(); pre (referencedModel != NULL); CompModelPlugin *plug1 = (CompModelPlugin*)(referencedModel->getPlugin("comp")); pre (plug1 != NULL); if (repE.isSetIdRef() == true) { if (plug1->getSubmodel(repE.getIdRef()) == NULL) { fail = true; } } else if (repE.isSetPortRef() == true) { bool found = false; Port* port = plug1->getPort(repE.getPortRef()); if (port->isSetIdRef() == true) { if (plug1->getSubmodel(port->getIdRef()) != NULL) { found = true; } } else if (port->isSetMetaIdRef() == true) { unsigned int i = 0; while (found == false && i < plug1->getNumSubmodels()) { if (port->getMetaIdRef() == plug1->getSubmodel(i)->getMetaId()) { found = true; } i++; } } if (found == false) { fail = true; } } else { // must be a metaidref std::string ref = repE.getMetaIdRef(); bool found = false; unsigned int i = 0; while (found == false && i < plug1->getNumSubmodels()) { if (ref == plug1->getSubmodel(i)->getMetaId()) { found = true; } i++; } if (found == false) { fail = true; } } } else { fail = true; msg = "The 'unitRef' of a <replacedElement>"; msg += " is set to '"; msg += repE.getUnitRef(); msg += "' which is not a submodel within the <model> referenced by "; msg += "submodel '"; msg += repE.getSubmodelRef(); msg += "'."; } inv(fail == false); } END_CONSTRAINT // 20705 - replacedBy START_CONSTRAINT (CompParentOfSBRefChildMustBeSubmodel, ReplacedBy, repE) { pre (repE.isSetSBaseRef()); bool fail = false; if (repE.isSetIdRef() == true || repE.isSetMetaIdRef() == true || repE.isSetPortRef() == true) { if (repE.isSetIdRef() == true) { msg = "The 'idRef' of a <replacedBy>"; msg += " is set to '"; msg += repE.getIdRef(); } else if (repE.isSetMetaIdRef() == true) { msg = "The 'metaIdRef' of a <replacedBy>"; msg += " is set to '"; msg += repE.getMetaIdRef(); } else { msg = "The 'portRef' of a <replacedBy>"; msg += " is set to '"; msg += repE.getPortRef(); } msg += "' which is not a submodel within the <model> referenced by "; msg += "submodel '"; msg += repE.getSubmodelRef(); msg += "'."; /* need to be using the correct model */ ReferencedModel *ref = new ReferencedModel(m, repE); const Model* referencedModel = ref->getReferencedModel(); pre (referencedModel != NULL); CompModelPlugin *plug1 = (CompModelPlugin*)(referencedModel->getPlugin("comp")); pre (plug1 != NULL); if (repE.isSetIdRef() == true) { if (plug1->getSubmodel(repE.getIdRef()) == NULL) { fail = true; } } else if (repE.isSetPortRef() == true) { bool found = false; Port* port = plug1->getPort(repE.getPortRef()); if (port->isSetIdRef() == true) { if (plug1->getSubmodel(port->getIdRef()) != NULL) { found = true; } } else if (port->isSetMetaIdRef() == true) { unsigned int i = 0; while (found == false && i < plug1->getNumSubmodels()) { if (port->getMetaIdRef() == plug1->getSubmodel(i)->getMetaId()) { found = true; } i++; } } if (found == false) { fail = true; } } else { // must be a metaidref std::string ref = repE.getMetaIdRef(); bool found = false; unsigned int i = 0; while (found == false && i < plug1->getNumSubmodels()) { if (ref == plug1->getSubmodel(i)->getMetaId()) { found = true; } i++; } if (found == false) { fail = true; } } } else { fail = true; msg = "The 'unitRef' of a <replacedBy>"; msg += " is set to '"; msg += repE.getUnitRef(); msg += "' which is not a submodel within the <model> referenced by "; msg += "submodel '"; msg += repE.getSubmodelRef(); msg += "'."; } inv(fail == false); } END_CONSTRAINT // 20705 - sBaseRef START_CONSTRAINT (CompParentOfSBRefChildMustBeSubmodel, SBaseRef, sbRef) { pre (sbRef.isSetSBaseRef()); bool fail = false; if (sbRef.isSetIdRef() == true || sbRef.isSetMetaIdRef() == true || sbRef.isSetPortRef() == true) { if (sbRef.isSetIdRef() == true) { msg = "The 'idRef' of a <sBaseRef>"; msg += " is set to '"; msg += sbRef.getIdRef(); } else if (sbRef.isSetPortRef() == true) { msg = "The 'portRef' of a <sBaseRef>"; msg += " is set to '"; msg += sbRef.getPortRef(); } else { msg = "The 'metaIdRef' of a <sbaseRef>"; msg += " is set to '"; msg += sbRef.getMetaIdRef(); } msg += "' which is not a submodel within the referenced <model>."; /* need to be using the correct model */ /* need to be using the correct model */ ReferencedModel *ref = new ReferencedModel(m, sbRef); const Model* referencedModel = ref->getReferencedModel(); pre (referencedModel != NULL); CompModelPlugin *plug = (CompModelPlugin*) (referencedModel->getPlugin("comp")); pre (plug != NULL); if (sbRef.isSetIdRef() == true) { if (plug->getSubmodel(sbRef.getIdRef()) == NULL) { fail = true; } } else if (sbRef.isSetPortRef() == true) { bool found = false; Port* port = plug->getPort(sbRef.getPortRef()); if (port->isSetIdRef() == true) { if (plug->getSubmodel(port->getIdRef()) != NULL) { found = true; } } else if (port->isSetMetaIdRef() == true) { unsigned int i = 0; while (found == false && i < plug->getNumSubmodels()) { if (port->getMetaIdRef() == plug->getSubmodel(i)->getMetaId()) { found = true; } i++; } } if (found == false) { fail = true; } } else { // must be a metaidref std::string ref = sbRef.getMetaIdRef(); bool found = false; unsigned int i = 0; while (found == false && i < plug->getNumSubmodels()) { if (ref == plug->getSubmodel(i)->getMetaId()) { found = true; } i++; } if (found == false) { fail = true; } } } else { fail = true; if (sbRef.isSetUnitRef() == true) { msg = "The 'unitRef' of a <sBaseRef>"; msg += " is set to '"; msg += sbRef.getUnitRef(); } msg += "' which is not a submodel within the <model>."; } inv(fail == false); } END_CONSTRAINT //20706 - caught at read //20707 - caught at read //20708 - caught at read //20709 - caught at read //20710 - caught at read //20711 - caught at read //20712 START_CONSTRAINT (CompSBaseRefMustReferenceObject, SBaseRef, sbRef) { bool idRef = sbRef.isSetIdRef(); bool unitRef = sbRef.isSetUnitRef(); bool metaidRef = sbRef.isSetMetaIdRef(); bool portRef = sbRef.isSetPortRef(); msg = "<sBaseRef> in "; const Model* mod = static_cast<const Model*> (sbRef.getAncestorOfType(SBML_MODEL, "core")); if (mod == NULL) { mod = static_cast<const Model*> (sbRef.getAncestorOfType(SBML_COMP_MODELDEFINITION, "comp")); } if (mod == NULL || !mod->isSetId()) { msg += "the main model in the document"; } else { msg += "the model '"; msg += mod->getId(); msg += "'"; } msg += " does not refer to another object."; bool fail = true; if (idRef == true) { fail = false; } else if (unitRef == true) { fail = false; } else if (metaidRef == true) { fail = false; } else if (portRef == true) { fail = false; } inv(fail == false); } END_CONSTRAINT //20713 START_CONSTRAINT (CompSBaseRefMustReferenceOnlyOneObject, SBaseRef, sbRef) { bool idRef = sbRef.isSetIdRef(); bool unitRef = sbRef.isSetUnitRef(); bool metaidRef = sbRef.isSetMetaIdRef(); bool portRef = sbRef.isSetPortRef(); bool fail = false; msg = "<sBaseRef> in "; const Model* mod = static_cast<const Model*> (sbRef.getAncestorOfType(SBML_MODEL, "core")); if (mod == NULL) { mod = static_cast<const Model*> (sbRef.getAncestorOfType(SBML_COMP_MODELDEFINITION, "comp")); } if (mod == NULL || !mod->isSetId()) { msg += "the main model in the document"; } else { msg += "the model '"; msg += mod->getId(); msg += "'"; } msg += " refers to "; if (idRef == true) { msg += "object with id '"; msg += sbRef.getIdRef(); msg += "'"; if (unitRef == true) { fail = true; msg += "and also unit with id '"; msg += sbRef.getUnitRef(); msg += "'"; if ( metaidRef == true) { msg += "and also object with metaid '"; msg += sbRef.getMetaIdRef(); msg += "'"; } if (portRef == true) { msg += "and also port with id '"; msg += sbRef.getPortRef(); msg += "'"; } msg += "."; } else if (metaidRef == true) { fail = true; msg += "and also object with metaid '"; msg += sbRef.getMetaIdRef(); msg += "'"; if (portRef == true) { msg += "and also port with id '"; msg += sbRef.getPortRef(); msg += "'"; } msg += "."; } else if (portRef == true) { fail = true; msg += "and also object with metaid '"; msg += sbRef.getMetaIdRef(); msg += "'."; } } else if (unitRef == true) { msg += "unit with id '"; msg += sbRef.getUnitRef(); msg += "' and also "; if (metaidRef == true) { fail = true; msg += "and also object with metaid '"; msg += sbRef.getMetaIdRef(); msg += "'"; if (portRef == true) { msg += "and also port with id '"; msg += sbRef.getPortRef(); msg += "'"; } msg += "."; } else if (portRef == true) { fail = true; msg += "and also object with metaid '"; msg += sbRef.getMetaIdRef(); msg += "'."; } } else if (metaidRef == true) { msg += "object with metaid '"; msg += sbRef.getMetaIdRef(); msg += "'"; if (portRef == true) { fail = true; msg += "and also port with id '"; msg += sbRef.getPortRef(); msg += "'"; } msg += "."; } inv(fail == false); } END_CONSTRAINT //************************************* //Port constraints //20801 START_CONSTRAINT (CompPortMustReferenceObject, Port, p) { pre (p.isSetId()); bool idRef = p.isSetIdRef(); bool unitRef = p.isSetUnitRef(); bool metaidRef = p.isSetMetaIdRef(); msg = "<port> '"; msg += p.getId() ; msg += "' in "; const Model* mod = static_cast<const Model*> (p.getAncestorOfType(SBML_MODEL, "core")); if (mod == NULL) { mod = static_cast<const Model*> (p.getAncestorOfType(SBML_COMP_MODELDEFINITION, "comp")); } if (mod == NULL || !mod->isSetId()) { msg += "the main model in the document"; } else { msg += "the model '"; msg += mod->getId(); msg += "'"; } msg += " does not refer to another object."; bool fail = true; if (idRef == true) { fail = false; } else if (unitRef == true) { fail = false; } else if (metaidRef == true) { fail = false; } inv(fail == false); } END_CONSTRAINT //20802 START_CONSTRAINT (CompPortMustReferenceOnlyOneObject, Port, p) { pre (p.isSetId()); bool idRef = p.isSetIdRef(); bool unitRef = p.isSetUnitRef(); bool metaidRef = p.isSetMetaIdRef(); bool fail = false; msg = "<port> '"; msg += p.getId() ; msg += "' in "; const Model* mod = static_cast<const Model*> (p.getAncestorOfType(SBML_MODEL, "core")); if (mod == NULL) { mod = static_cast<const Model*> (p.getAncestorOfType(SBML_COMP_MODELDEFINITION, "comp")); } if (mod == NULL || !mod->isSetId()) { msg += "the main model in the document"; } else { msg += "the model '"; msg += mod->getId(); msg += "'"; } msg += " refers to "; if (idRef == true) { msg += "object with id '"; msg += p.getIdRef(); msg += "' and also "; if (unitRef == true) { fail = true; msg += "unit with id '"; msg += p.getUnitRef(); msg += "'"; if ( metaidRef == true) { msg += "and also object with metaid '"; msg += p.getMetaIdRef(); msg += "'."; } } else if (metaidRef == true) { fail = true; msg += "and also object with metaid '"; msg += p.getMetaIdRef(); msg += "'."; } } else if (unitRef == true) { msg += "unit with id '"; msg += p.getUnitRef(); msg += "' and also "; if (metaidRef == true) { fail = true; msg += "object with metaid '"; msg += p.getMetaIdRef(); msg += "'."; } } inv(fail == false); } END_CONSTRAINT //20803 - caught at read //20804 EXTERN_CONSTRAINT( CompPortReferencesUnique, UniquePortReferences) //************************************* //Deletion constraints //20901 START_CONSTRAINT (CompDeletionMustReferenceObject, Deletion, d) { //pre (d.isSetId()); bool idRef = d.isSetIdRef(); bool unitRef = d.isSetUnitRef(); bool metaidRef = d.isSetMetaIdRef(); bool portRef = d.isSetPortRef(); msg = "<Deletion> '"; msg += d.getId() ; msg += "' in "; const Model* mod = static_cast<const Model*> (d.getAncestorOfType(SBML_MODEL, "core")); if (mod == NULL) { mod = static_cast<const Model*> (d.getAncestorOfType(SBML_COMP_MODELDEFINITION, "comp")); } if (mod == NULL || !mod->isSetId()) { msg += "the main model in the document"; } else { msg += "the model '"; msg += mod->getId(); msg += "'"; } msg += " does not refer to another object."; bool fail = true; if (idRef == true) { fail = false; } else if (unitRef == true) { fail = false; } else if (metaidRef == true) { fail = false; } else if (portRef == true) { fail = false; } inv(fail == false); } END_CONSTRAINT //20902 START_CONSTRAINT (CompDeletionMustReferOnlyOneObject, Deletion, d) { //pre (d.isSetId()); bool idRef = d.isSetIdRef(); bool unitRef = d.isSetUnitRef(); bool metaidRef = d.isSetMetaIdRef(); bool portRef = d.isSetPortRef(); bool fail = false; msg = "<Deletion> '"; msg += d.getId() ; msg += "' in "; const Model* mod = static_cast<const Model*> (d.getAncestorOfType(SBML_MODEL, "core")); if (mod == NULL) { mod = static_cast<const Model*> (d.getAncestorOfType(SBML_COMP_MODELDEFINITION, "comp")); } if (mod == NULL || !mod->isSetId()) { msg += "the main model in the document"; } else { msg += "the model '"; msg += mod->getId(); msg += "'"; } msg += " refers to "; if (idRef == true) { msg += "object with id '"; msg += d.getIdRef(); msg += "'"; if (unitRef == true) { fail = true; msg += "and also unit with id '"; msg += d.getUnitRef(); msg += "'"; if ( metaidRef == true) { msg += "and also object with metaid '"; msg += d.getMetaIdRef(); msg += "'"; } if (portRef == true) { msg += "and also port with id '"; msg += d.getPortRef(); msg += "'"; } msg += "."; } else if (metaidRef == true) { fail = true; msg += "and also object with metaid '"; msg += d.getMetaIdRef(); msg += "'"; if (portRef == true) { msg += "and also port with id '"; msg += d.getPortRef(); msg += "'"; } msg += "."; } else if (portRef == true) { fail = true; msg += "and also object with metaid '"; msg += d.getMetaIdRef(); msg += "'."; } } else if (unitRef == true) { msg += "unit with id '"; msg += d.getUnitRef(); msg += "' and also "; if (metaidRef == true) { fail = true; msg += "and also object with metaid '"; msg += d.getMetaIdRef(); msg += "'"; if (portRef == true) { msg += "and also port with id '"; msg += d.getPortRef(); msg += "'"; } msg += "."; } else if (portRef == true) { fail = true; msg += "and also object with metaid '"; msg += d.getMetaIdRef(); msg += "'."; } } else if (metaidRef == true) { msg += "object with metaid '"; msg += d.getMetaIdRef(); msg += "'"; if (portRef == true) { fail = true; msg += "and also port with id '"; msg += d.getPortRef(); msg += "'"; } msg += "."; } inv(fail == false); } END_CONSTRAINT //20903 - caught at read //************************************* //ReplacedElement constraints //21001 START_CONSTRAINT (CompReplacedElementMustRefObject, ReplacedElement, repE) { pre (repE.isSetSubmodelRef()); bool idRef = repE.isSetIdRef(); bool unitRef = repE.isSetUnitRef(); bool metaidRef = repE.isSetMetaIdRef(); bool portRef = repE.isSetPortRef(); bool deletion = repE.isSetDeletion(); msg = "A <replacedElement> in "; const Model* mod = static_cast<const Model*> (repE.getAncestorOfType(SBML_MODEL, "core")); if (mod == NULL) { mod = static_cast<const Model*> (repE.getAncestorOfType(SBML_COMP_MODELDEFINITION, "comp")); } if (mod == NULL || !mod->isSetId()) { msg += "the main model in the document"; } else { msg += "the model '"; msg += mod->getId(); msg += "'"; } msg = " does not refer to another object."; bool fail = true; if (idRef == true) { fail = false; } else if (unitRef == true) { fail = false; } else if (metaidRef == true) { fail = false; } else if (portRef == true) { fail = false; } else if (deletion == true) { fail = false; } inv(fail == false); } END_CONSTRAINT //21002 START_CONSTRAINT (CompReplacedElementMustRefOnlyOne, ReplacedElement, repE) { pre (repE.isSetSubmodelRef()); bool idRef = repE.isSetIdRef(); bool unitRef = repE.isSetUnitRef(); bool metaidRef = repE.isSetMetaIdRef(); bool portRef = repE.isSetPortRef(); bool deletion = repE.isSetDeletion(); bool fail = false; msg = "<replacedElement> '"; msg += repE.getId() ; msg += "' in "; const Model* mod = static_cast<const Model*> (repE.getAncestorOfType(SBML_MODEL, "core")); if (mod == NULL) { mod = static_cast<const Model*> (repE.getAncestorOfType(SBML_COMP_MODELDEFINITION, "comp")); } if (mod == NULL || !mod->isSetId()) { msg += "the main model in the document"; } else { msg += "the model '"; msg += mod->getId(); msg += "'"; } msg += " refers to "; if (idRef == true) { msg += "object with id '"; msg += repE.getIdRef(); msg += "'"; if (unitRef == true) { fail = true; msg += "and also unit with id '"; msg += repE.getUnitRef(); msg += "'"; if ( metaidRef == true) { msg += "and also object with metaid '"; msg += repE.getMetaIdRef(); msg += "'"; } if (portRef == true) { msg += "and also port with id '"; msg += repE.getPortRef(); msg += "'"; } if (deletion == true) { msg += "and also deletion object '"; msg += repE.getDeletion(); msg += "'"; } msg += "."; } else if (metaidRef == true) { fail = true; msg += "and also object with metaid '"; msg += repE.getMetaIdRef(); msg += "'"; if (portRef == true) { msg += "and also port with id '"; msg += repE.getPortRef(); msg += "'"; } if (deletion == true) { msg += "and also deletion object '"; msg += repE.getDeletion(); msg += "'"; } msg += "."; } else if (portRef == true) { fail = true; msg += "and also object with metaid '"; msg += repE.getMetaIdRef(); if (deletion == true) { msg += "and also deletion object '"; msg += repE.getDeletion(); msg += "'"; } msg += "'."; } else if (deletion == true) { fail = true; msg += "and also deletion object '"; msg += repE.getDeletion(); msg += "'."; } } else if (unitRef == true) { msg += "unit with id '"; msg += repE.getUnitRef(); msg += "' and also "; if (metaidRef == true) { fail = true; msg += "and also object with metaid '"; msg += repE.getMetaIdRef(); msg += "'"; if (portRef == true) { msg += "and also port with id '"; msg += repE.getPortRef(); msg += "'"; } if (deletion == true) { msg += "and also deletion object '"; msg += repE.getDeletion(); msg += "'"; } msg += "."; } else if (portRef == true) { fail = true; msg += "and also object with metaid '"; msg += repE.getMetaIdRef(); if (deletion == true) { msg += "and also deletion object '"; msg += repE.getDeletion(); msg += "'"; } msg += "'."; } else if (deletion == true) { fail = true; msg += "and also deletion object '"; msg += repE.getDeletion(); msg += "'."; } } else if (metaidRef == true) { msg += "object with metaid '"; msg += repE.getMetaIdRef(); msg += "'"; if (portRef == true) { fail = true; msg += "and also port with id '"; msg += repE.getPortRef(); msg += "'"; } if (deletion == true) { msg += "and also deletion object '"; msg += repE.getDeletion(); msg += "'"; } msg += "."; } else if (portRef == true) { msg += "port with id '"; msg += repE.getPortRef(); msg += "'"; if (deletion == true) { fail = true; msg += "and also deletion object '"; msg += repE.getDeletion(); msg += "'"; } msg += "."; } inv(fail == false); } END_CONSTRAINT //21003 - caught at read //21004 START_CONSTRAINT (CompReplacedElementSubModelRef, ReplacedElement, repE) { pre (repE.isSetSubmodelRef()); msg = "The <replacedElement> refers to the submodel '"; msg += repE.getSubmodelRef(); msg += "' that is not part of the parent model."; bool fail = false; const CompModelPlugin * plug = static_cast<const CompModelPlugin*>(m.getPlugin("comp")); if (plug != NULL && plug->getSubmodel(repE.getSubmodelRef()) == NULL) { fail = true; } inv(fail == false); } END_CONSTRAINT //21005 START_CONSTRAINT (CompReplacedElementDeletionRef, ReplacedElement, repE) { pre (repE.isSetSubmodelRef()); pre (repE.isSetDeletion()); msg = "A <replacedElement> in "; const Model* mod = static_cast<const Model*> (repE.getAncestorOfType(SBML_MODEL, "core")); if (mod == NULL) { mod = static_cast<const Model*> (repE.getAncestorOfType(SBML_COMP_MODELDEFINITION, "comp")); } if (mod == NULL || !mod->isSetId()) { msg += "the main model in the document"; } else { msg += "the model '"; msg += mod->getId(); msg += "'"; } msg = " refers to the deletion '"; msg += repE.getDeletion(); msg += "' that is not part of the parent model."; bool fail = false; const CompModelPlugin * plug = static_cast<const CompModelPlugin*>(m.getPlugin("comp")); if (plug != NULL) { const Submodel * sub = plug->getSubmodel(repE.getSubmodelRef()); if (sub != NULL && sub->getDeletion(repE.getDeletion()) == NULL) { fail = true; } } inv(fail == false); } END_CONSTRAINT //21006 START_CONSTRAINT (CompReplacedElementConvFactorRef, ReplacedElement, repE) { pre (repE.isSetSubmodelRef()); pre (repE.isSetConversionFactor()); msg = "The 'conversionFactor' of a <replacedElement> in "; const Model* mod = static_cast<const Model*> (repE.getAncestorOfType(SBML_MODEL, "core")); if (mod == NULL) { mod = static_cast<const Model*> (repE.getAncestorOfType(SBML_COMP_MODELDEFINITION, "comp")); } if (mod == NULL || !mod->isSetId()) { msg += "the main model in the document"; } else { msg += "the model '"; msg += mod->getId(); msg += "'"; } msg = " is set to '"; msg += repE.getConversionFactor(); msg += "' which is not a <parameter> within the model."; bool fail = false; if (m.getParameter(repE.getConversionFactor()) == NULL) { fail = true; } inv(fail == false); } END_CONSTRAINT //21007 - repeat of 10308 //21008 - repeat of 10309 //21009 - repeat of 10310 //21010 EXTERN_CONSTRAINT( CompReplacedElementSameReference, UniqueReplacedReferences) //21011 START_CONSTRAINT (CompReplacedElementNoDelAndConvFact, ReplacedElement, repE) { pre (repE.isSetDeletion()); bool fail = false; if (repE.isSetConversionFactor() == true) { fail = true; } inv(fail == false); } END_CONSTRAINT //************************************* //ReplacedBy constraints //21101 START_CONSTRAINT (CompReplacedByMustRefObject, ReplacedBy, repBy) { pre (repBy.isSetSubmodelRef()); bool idRef = repBy.isSetIdRef(); bool unitRef = repBy.isSetUnitRef(); bool metaidRef = repBy.isSetMetaIdRef(); bool portRef = repBy.isSetPortRef(); msg = "A <replacedBy> in "; const Model* mod = static_cast<const Model*> (repBy.getAncestorOfType(SBML_MODEL, "core")); if (mod == NULL) { mod = static_cast<const Model*> (repBy.getAncestorOfType(SBML_COMP_MODELDEFINITION, "comp")); } if (mod == NULL || !mod->isSetId()) { msg += "the main model in the document"; } else { msg += "the model '"; msg += mod->getId(); msg += "'"; } msg += " does not refer to another object."; bool fail = true; if (idRef == true) { fail = false; } else if (unitRef == true) { fail = false; } else if (metaidRef == true) { fail = false; } else if (portRef == true) { fail = false; } inv(fail == false); } END_CONSTRAINT //21102 START_CONSTRAINT (CompReplacedByMustRefOnlyOne, ReplacedBy, repBy) { pre (repBy.isSetSubmodelRef()); bool idRef = repBy.isSetIdRef(); bool unitRef = repBy.isSetUnitRef(); bool metaidRef = repBy.isSetMetaIdRef(); bool portRef = repBy.isSetPortRef(); bool fail = false; msg = "A <replacedBy> object in "; const Model* mod = static_cast<const Model*> (repBy.getAncestorOfType(SBML_MODEL, "core")); if (mod == NULL) { mod = static_cast<const Model*> (repBy.getAncestorOfType(SBML_COMP_MODELDEFINITION, "comp")); } if (mod == NULL || !mod->isSetId()) { msg += "the main model in the document"; } else { msg += "the model '"; msg += mod->getId(); msg += "'"; } msg += " refers to "; if (idRef == true) { msg += "object with id '"; msg += repBy.getIdRef(); msg += "'"; if (unitRef == true) { fail = true; msg += "and also unit with id '"; msg += repBy.getUnitRef(); msg += "'"; if ( metaidRef == true) { msg += "and also object with metaid '"; msg += repBy.getMetaIdRef(); msg += "'"; } if (portRef == true) { msg += "and also port with id '"; msg += repBy.getPortRef(); msg += "'"; } msg += "."; } else if (metaidRef == true) { fail = true; msg += "and also object with metaid '"; msg += repBy.getMetaIdRef(); msg += "'"; if (portRef == true) { msg += "and also port with id '"; msg += repBy.getPortRef(); msg += "'"; } msg += "."; } else if (portRef == true) { fail = true; msg += "and also object with metaid '"; msg += repBy.getMetaIdRef(); msg += "'."; } } else if (unitRef == true) { msg += "unit with id '"; msg += repBy.getUnitRef(); msg += "' and also "; if (metaidRef == true) { fail = true; msg += "and also object with metaid '"; msg += repBy.getMetaIdRef(); msg += "'"; if (portRef == true) { msg += "and also port with id '"; msg += repBy.getPortRef(); msg += "'"; } msg += "."; } else if (portRef == true) { fail = true; msg += "and also object with metaid '"; msg += repBy.getMetaIdRef(); msg += "'."; } } else if (metaidRef == true) { msg += "object with metaid '"; msg += repBy.getMetaIdRef(); msg += "'"; if (portRef == true) { fail = true; msg += "and also port with id '"; msg += repBy.getPortRef(); msg += "'"; } msg += "."; } inv(fail == false); } END_CONSTRAINT //21103 - caught at read //21104 START_CONSTRAINT (CompReplacedBySubModelRef, ReplacedBy, repBy) { pre (repBy.isSetSubmodelRef()); msg = "A <replacedBy> in "; const Model* mod = static_cast<const Model*> (repBy.getAncestorOfType(SBML_MODEL, "core")); if (mod == NULL) { mod = static_cast<const Model*> (repBy.getAncestorOfType(SBML_COMP_MODELDEFINITION, "comp")); } if (mod == NULL || !mod->isSetId()) { msg += "the main model in the document"; } else { msg += "the model '"; msg += mod->getId(); msg += "'"; } msg += " refers to the submodel '"; msg += repBy.getSubmodelRef(); msg += "' that is not part of the parent model."; bool fail = false; const CompModelPlugin * plug = static_cast<const CompModelPlugin*>(m.getPlugin("comp")); if (plug != NULL && plug->getSubmodel(repBy.getSubmodelRef()) == NULL) { fail = true; } inv(fail == false); } END_CONSTRAINT //21201 EXTERN_CONSTRAINT( CompMustReplaceSameClass, ClassReplacements) //21202 - caught during flattening //21203 - caught during flattening //21204 EXTERN_CONSTRAINT(CompMustReplacePackageIDs, PackageIdReplacementCheck) // 90115 (note not on a replacedBy) // 90115 - port START_CONSTRAINT (CompIdRefMayReferenceUnknownPackage, Port, p) { pre(p.isSetIdRef()); /* only log this if there are unknown packages present */ const SBMLDocument *doc = m.getSBMLDocument(); SBMLErrorLog *errlog = const_cast<SBMLErrorLog*>(doc->getErrorLog()); bool unknownPackagePresent = false; if (errlog->contains(UnrequiredPackagePresent) || errlog->contains(RequiredPackagePresent)) { unknownPackagePresent = true; } pre ( unknownPackagePresent == true); msg = "The 'idRef' of a <port>"; msg += " is set to '"; msg += p.getIdRef(); msg += "' which is not an element within the <model>."; msg += " However it may be an identifier of an object within an "; msg += "unrecognised package. "; IdList mIds; // create the filter we want to use IdFilter filter; ReferencedModel *ref = new ReferencedModel(m, p); const Model* mod = ref->getReferencedModel(); pre (mod != NULL); List* allElements = const_cast<Model*>(mod)->getAllElements(&filter); for (unsigned int i = 0; i < allElements->getSize(); i++) { mIds.append(static_cast<SBase*>(allElements->get(i))->getId()); } delete allElements; inv(mIds.contains(p.getIdRef())) } END_CONSTRAINT // 90115 - deletion START_CONSTRAINT (CompIdRefMayReferenceUnknownPackage, Deletion, d) { /* only log this if there are unknown packages present */ const SBMLDocument *doc = m.getSBMLDocument(); SBMLErrorLog *errlog = const_cast<SBMLErrorLog*>(doc->getErrorLog()); bool unknownPackagePresent = false; if (errlog->contains(UnrequiredPackagePresent) || errlog->contains(RequiredPackagePresent)) { unknownPackagePresent = true; } pre ( unknownPackagePresent == true); pre(d.isSetIdRef()); const Submodel * sub = static_cast<const Submodel*> (d.getAncestorOfType(SBML_COMP_SUBMODEL, "comp")); pre (sub != NULL); msg = "The 'idRef' of a <deletion>"; msg += " is set to '"; msg += d.getIdRef(); msg += "' which is not an element within the <model> referenced by "; msg += "submodel '"; msg += sub->getId(); msg += "'. However it may be an identifier of an object within an "; msg += "unrecognised package. "; IdList mIds; // create the filter we want to use IdFilter filter; ReferencedModel *ref = new ReferencedModel(m, d); const Model* mod = ref->getReferencedModel(); pre (mod != NULL); List* allElements = const_cast<Model*>(mod)->getAllElements(&filter); for (unsigned int i = 0; i < allElements->getSize(); i++) { mIds.append(static_cast<SBase*>(allElements->get(i))->getId()); } delete allElements; inv(mIds.contains(d.getIdRef())) } END_CONSTRAINT // 90115 - replacedElement START_CONSTRAINT (CompIdRefMayReferenceUnknownPackage, ReplacedElement, repE) { pre(repE.isSetIdRef()); pre(repE.isSetSubmodelRef()); /* only log this if there are unknown packages present */ const SBMLDocument *doc = m.getSBMLDocument(); SBMLErrorLog *errlog = const_cast<SBMLErrorLog*>(doc->getErrorLog()); bool unknownPackagePresent = false; if (errlog->contains(UnrequiredPackagePresent) || errlog->contains(RequiredPackagePresent)) { unknownPackagePresent = true; } pre ( unknownPackagePresent == true); msg = "The 'idRef' of a <replacedElement>"; msg += " is set to '"; msg += repE.getIdRef(); msg += "' which is not an element within the <model> referenced by "; msg += "submodel '"; msg += repE.getSubmodelRef(); msg += "'. However it may be an identifier of an object within an "; msg += "unrecognised package. "; IdList mIds; // create the filter we want to use IdFilter filter; ReferencedModel *ref = new ReferencedModel(m, repE); const Model* mod = ref->getReferencedModel(); pre (mod != NULL); List* allElements = const_cast<Model*>(mod)->getAllElements(&filter); for (unsigned int i = 0; i < allElements->getSize(); i++) { mIds.append(static_cast<SBase*>(allElements->get(i))->getId()); } delete allElements; inv(mIds.contains(repE.getIdRef())) } END_CONSTRAINT // 90115 - sBaseRef START_CONSTRAINT (CompIdRefMayReferenceUnknownPackage, SBaseRef, sbRef) { pre(sbRef.isSetIdRef()); /* only log this if there are unknown packages present */ const SBMLDocument *doc = m.getSBMLDocument(); SBMLErrorLog *errlog = const_cast<SBMLErrorLog*>(doc->getErrorLog()); bool unknownPackagePresent = false; if (errlog->contains(UnrequiredPackagePresent) || errlog->contains(RequiredPackagePresent)) { unknownPackagePresent = true; } pre ( unknownPackagePresent == true); pre (sbRef.getParentSBMLObject() != NULL); int tc = sbRef.getParentSBMLObject()->getTypeCode(); msg = "The 'idRef' of a <sBaseRef>"; msg += " is set to '"; msg += sbRef.getIdRef(); msg += "' which is not an element within the <model> referenced by "; if (tc == SBML_COMP_REPLACEDELEMENT) { msg += "the submodel '"; msg += static_cast<const ReplacedElement*>(sbRef.getParentSBMLObject()) ->getSubmodelRef(); msg += "'."; } else if (tc == SBML_COMP_REPLACEDBY) { msg += "the submodel '"; msg += static_cast<const ReplacedBy*>(sbRef.getParentSBMLObject()) ->getSubmodelRef(); msg += "'."; } else if (tc == SBML_COMP_PORT) { msg += "port '"; msg += sbRef.getParentSBMLObject()->getId(); msg += "'."; } else if (tc == SBML_COMP_DELETION) { const Submodel * sub = static_cast<const Submodel*> (sbRef.getParentSBMLObject() ->getAncestorOfType(SBML_COMP_SUBMODEL, "comp")); pre (sub != NULL); msg += "the submodel '"; msg += sub->getId(); msg += "'."; } else if (tc == SBML_COMP_SBASEREF) { msg += "the parent sBaseRef."; } msg += "However it may be an identifier of an object within an "; msg += "unrecognised package. "; IdList mIds; // create the filter we want to use IdFilter filter; ReferencedModel *ref = new ReferencedModel(m, sbRef); const Model* mod = ref->getReferencedModel(); pre (mod != NULL); List* allElements = const_cast<Model*>(mod)->getAllElements(&filter); for (unsigned int i = 0; i < allElements->getSize(); i++) { mIds.append(static_cast<SBase*>(allElements->get(i))->getId()); } delete allElements; inv(mIds.contains(sbRef.getIdRef())) } END_CONSTRAINT // 90116 //90116 - port START_CONSTRAINT (CompMetaIdRefMayReferenceUnknownPkg, Port, p) { pre(p.isSetMetaIdRef()); /* only log this if there are unknown packages present */ const SBMLDocument *doc = m.getSBMLDocument(); SBMLErrorLog *errlog = const_cast<SBMLErrorLog*>(doc->getErrorLog()); bool unknownPackagePresent = false; if (errlog->contains(UnrequiredPackagePresent) || errlog->contains(RequiredPackagePresent)) { unknownPackagePresent = true; } pre ( unknownPackagePresent == true); msg = "The 'metaIdRef' of a <port>"; msg += " is set to '"; msg += p.getMetaIdRef(); msg += "' which is not an element within the <model>. "; msg += "However it may be the 'metaid' of an object within an "; msg += "unrecognised package. "; IdList mIds; // create the filter we want to use MetaIdFilter filter; // get a list of all elements with an id ReferencedModel *ref = new ReferencedModel(m, p); const Model* mod = ref->getReferencedModel(); pre (mod != NULL); List* allElements = const_cast<Model*>(mod)->getAllElements(&filter); for (unsigned int i = 0; i < allElements->getSize(); i++) { mIds.append(static_cast<SBase*>(allElements->get(i))->getMetaId()); } delete allElements; inv(mIds.contains(p.getMetaIdRef())) } END_CONSTRAINT // 90116 - deletion START_CONSTRAINT (CompMetaIdRefMayReferenceUnknownPkg, Deletion, d) { pre(d.isSetMetaIdRef()); /* only log this if there are unknown packages present */ const SBMLDocument *doc = m.getSBMLDocument(); SBMLErrorLog *errlog = const_cast<SBMLErrorLog*>(doc->getErrorLog()); bool unknownPackagePresent = false; if (errlog->contains(UnrequiredPackagePresent) || errlog->contains(RequiredPackagePresent)) { unknownPackagePresent = true; } pre ( unknownPackagePresent == true); const Submodel * sub = static_cast<const Submodel*> (d.getAncestorOfType(SBML_COMP_SUBMODEL, "comp")); pre (sub != NULL); msg = "The 'metaIdRef' of a <deletion>"; msg += " is set to '"; msg += d.getMetaIdRef(); msg += "' which is not an element within the <model> referenced by "; msg += "submodel '"; msg += sub->getId(); msg += "'. "; msg += "However it may be the 'metaid' of an object within an "; msg += "unrecognised package. "; IdList mIds; // create the filter we want to use MetaIdFilter filter; // get a list of all elements with an id ReferencedModel *ref = new ReferencedModel(m, d); const Model* mod = ref->getReferencedModel(); pre (mod != NULL); List* allElements = const_cast<Model*>(mod)->getAllElements(&filter); for (unsigned int i = 0; i < allElements->getSize(); i++) { mIds.append(static_cast<SBase*>(allElements->get(i))->getMetaId()); } delete allElements; inv(mIds.contains(d.getMetaIdRef())) } END_CONSTRAINT // 90116 - replacedElement START_CONSTRAINT (CompMetaIdRefMayReferenceUnknownPkg, ReplacedElement, repE) { pre(repE.isSetMetaIdRef()); pre(repE.isSetSubmodelRef()); /* only log this if there are unknown packages present */ const SBMLDocument *doc = m.getSBMLDocument(); SBMLErrorLog *errlog = const_cast<SBMLErrorLog*>(doc->getErrorLog()); bool unknownPackagePresent = false; if (errlog->contains(UnrequiredPackagePresent) || errlog->contains(RequiredPackagePresent)) { unknownPackagePresent = true; } pre ( unknownPackagePresent == true); msg = "The 'metaidRef' of a <replacedElement>"; msg += " is set to '"; msg += repE.getMetaIdRef(); msg += "' which is not an element within the <model> referenced by "; msg += "submodel '"; msg += repE.getSubmodelRef(); msg += "'. "; msg += "However it may be the 'metaid' of an object within an "; msg += "unrecognised package. "; IdList mIds; // create the filter we want to use MetaIdFilter filter; // get a list of all elements with an id ReferencedModel *ref = new ReferencedModel(m, repE); const Model* mod = ref->getReferencedModel(); pre (mod != NULL); List* allElements = const_cast<Model*>(mod)->getAllElements(&filter); for (unsigned int i = 0; i < allElements->getSize(); i++) { mIds.append(static_cast<SBase*>(allElements->get(i))->getMetaId()); } delete allElements; inv(mIds.contains(repE.getMetaIdRef())) } END_CONSTRAINT // 90116 - sBaseRef START_CONSTRAINT (CompMetaIdRefMayReferenceUnknownPkg, SBaseRef, sbRef) { pre(sbRef.isSetMetaIdRef()); /* only log this if there are unknown packages present */ const SBMLDocument *doc = m.getSBMLDocument(); SBMLErrorLog *errlog = const_cast<SBMLErrorLog*>(doc->getErrorLog()); bool unknownPackagePresent = false; if (errlog->contains(UnrequiredPackagePresent) || errlog->contains(RequiredPackagePresent)) { unknownPackagePresent = true; } pre ( unknownPackagePresent == true); pre (sbRef.getParentSBMLObject() != NULL); int tc = sbRef.getParentSBMLObject()->getTypeCode(); msg = "The 'metaIdRef' of a <sBaseRef>"; msg += " is set to '"; msg += sbRef.getMetaIdRef(); msg += "' which is not an element within the <model> referenced by "; if (tc == SBML_COMP_REPLACEDELEMENT) { msg += "the submodel '"; msg += static_cast<const ReplacedElement*>(sbRef.getParentSBMLObject()) ->getSubmodelRef(); msg += "'."; } else if (tc == SBML_COMP_REPLACEDBY) { msg += "the submodel '"; msg += static_cast<const ReplacedBy*>(sbRef.getParentSBMLObject()) ->getSubmodelRef(); msg += "'."; } else if (tc == SBML_COMP_PORT) { msg += "port '"; msg += sbRef.getParentSBMLObject()->getId(); msg += "'."; } else if (tc == SBML_COMP_DELETION) { const Submodel * sub = static_cast<const Submodel*> (sbRef.getParentSBMLObject() ->getAncestorOfType(SBML_COMP_SUBMODEL, "comp")); pre (sub != NULL); msg += "the submodel '"; msg += sub->getId(); msg += "'."; } else if (tc == SBML_COMP_SBASEREF) { msg += "the parent sBaseRef."; } msg += " However it may be the 'metaid' of an object within an "; msg += "unrecognised package. "; IdList mIds; // create the filter we want to use MetaIdFilter filter; // get a list of all elements with an id ReferencedModel *ref = new ReferencedModel(m, sbRef); const Model* mod = ref->getReferencedModel(); pre (mod != NULL); List* allElements = const_cast<Model*>(mod)->getAllElements(&filter); for (unsigned int i = 0; i < allElements->getSize(); i++) { mIds.append(static_cast<SBase*>(allElements->get(i))->getMetaId()); } delete allElements; inv(mIds.contains(sbRef.getMetaIdRef())) } END_CONSTRAINT /** @endcond */
26.163741
92
0.574054
[ "object", "vector", "model" ]
3bb6aa9dfca2238b0b291a3667ff8ab04a44adf9
43,952
cpp
C++
third_party/misc/def/def/def_keywords.cpp
jesec/livehd
1a82dbea1d86dbd1511de588609de320aa4ef6ed
[ "BSD-3-Clause" ]
115
2019-09-28T13:39:41.000Z
2022-03-24T11:08:53.000Z
third_party/misc/def/def/def_keywords.cpp
jesec/livehd
1a82dbea1d86dbd1511de588609de320aa4ef6ed
[ "BSD-3-Clause" ]
120
2018-05-16T23:11:09.000Z
2019-09-25T18:52:49.000Z
third_party/misc/def/def/def_keywords.cpp
jesec/livehd
1a82dbea1d86dbd1511de588609de320aa4ef6ed
[ "BSD-3-Clause" ]
44
2019-09-28T07:53:21.000Z
2022-02-13T23:21:12.000Z
// ***************************************************************************** // ***************************************************************************** // Copyright 2013 - 2016, Cadence Design Systems // // This file is part of the Cadence LEF/DEF Open Source // Distribution, Product Version 5.8. // // 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. // // For updates, support, or to become part of the LEF/DEF Community, // check www.openeda.org for details. // // $Author: icftcm $ // $Revision: #2 $ // $Date: 2017/08/28 $ // $State: $ // ***************************************************************************** // ***************************************************************************** /* */ /* Revision: */ /* 03-15-2000 Wanda da Rosa - Add code to support 5.4, add keywords */ /* for PINS + USE, SPECIALNETS + SHAPE */ /* and other keywords */ #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include "defiDebug.hpp" #include "defiDefs.hpp" #include "defrCallBacks.hpp" #include "defrData.hpp" #include "defrSettings.hpp" #include "lex.h" #ifdef WIN32 #include <direct.h> #else /* not WIN32 */ #include <unistd.h> #endif /* WIN32 */ using namespace std; BEGIN_LEFDEF_PARSER_NAMESPACE #include "def.tab.hpp" int defrData::defGetKeyword(const char *name, int *result) { map<const char *, int, defCompareCStrings>::const_iterator search = settings->Keyword_set.find(name); if (search != settings->Keyword_set.end()) { *result = search->second; return TRUE; } return FALSE; } int defrData::defGetAlias(const string &name, string &result) { map<string, string, defCompareStrings>::iterator search = def_alias_set.find(name); if (search != def_alias_set.end()) { result = search->second; return TRUE; } return FALSE; } int defrData::defGetDefine(const string &name, string &result) { map<string, string, defCompareStrings>::iterator search = def_defines_set.find(name); if (search != def_defines_set.end()) { result = search->second; return TRUE; } return FALSE; } // lex.cpph starts here /* User defined if log file should be in append from the previous run */ /* User defined if property string value should be process */ /* Varible from lex.cpph to keep track of invalid nonEnglish character */ /* in def file */ /************Some simple file reading routines since ungetc() proves ****/ /************to be quite slow, and we don't need multiple chars of pushback */ #ifndef WIN32 #include <unistd.h> #endif void defrData::reload_buffer() { int nb = 0; if (first_buffer) { first_buffer = 0; if (settings->ReadFunction) { if ((nb = (*settings->ReadFunction)(File, buffer, 4)) != 4) { next = NULL; return; } } else { if ((nb = fread(buffer, 1, 4, File)) != 4) { next = NULL; return; } } } if (nb == 0) { if (settings->ReadFunction) nb = (*settings->ReadFunction)(File, buffer, IN_BUF_SIZE); else /* This is a normal file so just read some bytes. */ nb = fread(buffer, 1, IN_BUF_SIZE, File); } if (nb <= 0) { next = NULL; } else { next = buffer; last = buffer + nb - 1; } } int defrData::GETC() { // Remove '\r' symbols from Windows streams. for (;;) { if (next > last) reload_buffer(); if (next == NULL) return EOF; int ch = *next++; if (ch != '\r') return ch; } } void defrData::UNGETC(char ch) { if (next <= buffer) { defError(6111, "UNGETC: buffer access violation."); } else { *(--next) = ch; } } /* Return a copy of the string allocated from the ring buffer. * We will keep several strings in the buffer and just reuse them. * This could cause problems if we need to use more strings than we * have in the buffer. */ char *defrData::ringCopy(const char *string) { int len = strlen(string) + 1; if (++(ringPlace) >= RING_SIZE) ringPlace = 0; if (len > ringSizes[ringPlace]) { free(ring[ringPlace]); ring[ringPlace] = (char *)malloc(len); ringSizes[ringPlace] = len; } strcpy(ring[ringPlace], string); return ring[ringPlace]; } int defrData::DefGetTokenFromStack(char *s) { const char *ch; /* utility variable */ char * prS = NULL; /* pointing to the previous char or s */ while (input_level >= 0) { for (ch = stack[input_level].c_str(); *ch != 0; ch++) /* skip white space */ if (*ch != ' ' && *ch != '\t' && (nl_token || *ch != '\n')) break; /* did we find anything? If not, decrement level and try again */ if (*ch == 0) input_level--; else if (*ch == '\n') { *s++ = *ch; *s = 0; return TRUE; } else { /* we found something */ for (;; ch++) { if (*ch == ' ' || *ch == '\t' || *ch == '\n' || *ch == 0) { /* 10/10/2000 - Wanda da Rosa, pcr 341032 ** Take out the last '"', the 1st will be skip later */ if (*prS == '"') { *prS = '\0'; } else *s++ = '\0'; stack[input_level] = ch; return TRUE; } /* 10/10/2000 - Wanda da Rosa, pcr 341032 ** Save the location of the previous s */ prS = s; *s++ = *ch; } } } return FALSE; /* if we get here, we ran out of input levels */ } void defrData::print_lines(long long lines) { if (lines % settings->defiDeltaNumberLines) { return; } if (settings->ContextLineNumberFunction) { settings->ContextLineNumberFunction(session->UserData, (int)lines); } else if (settings->ContextLongLineNumberFunction) { settings->ContextLongLineNumberFunction(session->UserData, lines); } if (settings->LineNumberFunction) { settings->LineNumberFunction((int)lines); } else if (settings->LongLineNumberFunction) { settings->LongLineNumberFunction(lines); } } const char *defrData::lines2str(long long lines) { #ifdef _WIN32 sprintf(lineBuffer, "%I64d", lines); #else sprintf(lineBuffer, "%lld", lines); #endif return lineBuffer; } // Increment current position of buffer pointer. // Double buffer size if curPos is out of boundary. void defrData::IncCurPos(char **curPos, char **buffer, int *bufferSize) { (*curPos)++; if (*curPos - *buffer < *bufferSize) { return; } long offset = *curPos - *buffer; *bufferSize *= 2; *buffer = (char *)realloc(*buffer, *bufferSize); *curPos = *buffer + offset; } int defrData::DefGetToken(char **buf, int *bufferSize) { char *s = *buf; int ch; ntokens++; defInvalidChar = 0; if (input_level >= 0) { /* if we are expanding an alias */ if (DefGetTokenFromStack(s)) /* try to get a token from it */ return TRUE; /* if we get one, return it */ } /* but if not, continue */ /* skip blanks and count lines */ while ((ch = GETC()) != EOF) { if (ch == '\n') { print_lines(++nlines); } if (ch != ' ' && ch != '\t' && (nl_token || ch != '\n')) break; } if (ch == EOF) return FALSE; if (ch == '\n') { *s = ch; IncCurPos(&s, buf, bufferSize); *s = '\0'; return TRUE; } /* now get the token */ if (ch == '"') { do { /* 5/5/2008 - CCR 556818 ** Check if the ch is a valid ascii character 0 =< ch < 128 ** If not write out an error */ /* 8/7/2008 - CCR 586175 ** Some files may not end with \n or \0 or EOF as the last character ** The parser allows this char instead of error out */ if ((ch < -1) || (ch > 127)) { defInvalidChar = 1; } /* 8/22/2000 - Wanda da Rosa, pcr 333334 ** save the previous char to allow backslash quote within quote */ if (!settings->DisPropStrProcess) { /* 3/4/2008 - CCR 523879 - convert \\ to \, \" to ", \x to x */ if (ch == '\\') { /* got a \, save the next char only */ ch = GETC(); if ((ch == '\n') || (ch == EOF)) { /* senaty check */ *s = '\0'; return FALSE; } } } *s = ch; IncCurPos(&s, buf, bufferSize); ch = GETC(); if (ch == EOF) { *s = '\0'; return FALSE; } } while (ch != '"'); *s = '\0'; return TRUE; } if (names_case_sensitive) { for (;; ch = GETC()) { /* 5/5/2008 - CCR 556818 ** Check if the ch is a valid ascii character 0 =< ch < 128 ** If not write out an error */ if ((ch < -1) || (ch > 127)) { defInvalidChar = 1; } if (ch == ' ' || ch == '\t' || ch == '\n' || ch == EOF) break; *s = ch; IncCurPos(&s, buf, bufferSize); } } else { /* we are case insensitive, use a different loop */ for (;; ch = GETC()) { /* 5/5/2008 - CCR 556818 ** Check if the ch is a valid ascii character 0 =< ch < 128 ** If not write out an error */ if ((ch < -1) || (ch > 127)) { defInvalidChar = 1; } if (ch == ' ' || ch == '\t' || ch == '\n' || ch == EOF) break; *s = (ch >= 'a' && ch <= 'z') ? (ch - 'a' + 'A') : ch; IncCurPos(&s, buf, bufferSize); } } /* If we got this far, the last char was whitespace */ *s = '\0'; if (ch != EOF) /* shouldn't ungetc an EOF */ UNGETC((char)ch); return TRUE; } /* creates an upper case copy of an array */ void defrData::uc_array(char *source, char *dest) { for (; *source != 0;) *dest++ = toupper(*source++); *dest = 0; } void defrData::StoreAlias() { int tokenSize = TOKEN_SIZE; char *aname = (char *)malloc(tokenSize); DefGetToken(&aname, &tokenSize); char *line = (char *)malloc(tokenSize); DefGetToken(&line, &tokenSize); char *uc_line = (char *)malloc(tokenSize); string so_far; /* contains alias contents as we build it */ if (strcmp(line, "=") != 0) { defError(6000, "Expecting '='"); return; } /* now keep getting lines till we get one that contains &ENDALIAS */ for (char *p = NULL; p == NULL;) { int i; char *s = line; for (i = 0; i < tokenSize - 1; i++) { int ch = GETC(); if (ch == EOF) { defError(6001, "End of file in &ALIAS"); return; } *s++ = ch; if (ch == '\n') { print_lines(++nlines); break; } } *s = '\0'; uc_array(line, uc_line); /* make upper case copy */ p = strstr(uc_line, "&ENDALIAS"); /* look for END_ALIAS */ if (p != NULL) /* if we find it */ *(line + (p - uc_line)) = 0; /* remove it from the line */ so_far += line; } def_alias_set[aname] = so_far; free(aname); free(line); free(uc_line); } /* The main routine called by the YACC parser to get the next token. * Returns 0 if no more tokens are available. * Returns an integer for keywords (see the yacc_defines.h for values) * Returns the character itself for punctuation * Returns NUMBER for numeric looking tokens * Returns T_STRING for anything else * If the global "dumb_mode" is > 0, it reads the next token in "dumb mode". * In this case, it does not do keyword lookup, or attempt to read a token * as a number; if the token is not punctuation, it's a T_STRING. Each token * read decrements dumb_mode, so you can instruct the the lexer to read the * next N tokens in dumb mode by setting "dumb_mode" to that value. * * Newlines are in general silently ignored. If the global nl_token is * true, however, they are returned as the token K_NL. */ int defrData::defyylex(YYSTYPE *pYylval) { int v = sublex(pYylval); if (defPrintTokens) { if (v == 0) { printf("yylex NIL\n"); } else if (v < 256) { printf("yylex char %c\n", v); } else if (v == QSTRING) { printf("yylex quoted string '%s'\n", pYylval->string); } else if (v == T_STRING) { printf("yylex string '%s'\n", pYylval->string); } else if (v == NUMBER) { printf("yylex number %f\n", pYylval->dval); } else { printf("yylex keyword %s\n", defrData::defkywd(v)); } } if ((v == 0) && (!doneDesign)) { defError(6002, "Incomplete def file."); // Stop printing error messages after the EOF. hasFatalError = 1; return (-1); } return v; } int defrData::sublex(YYSTYPE *pYylval) { char fc; double numVal; char * outMsg; pv_deftoken = (char *)realloc(pv_deftoken, deftokenLength); strcpy(pv_deftoken, deftoken); /* First, we eat all the things the parser should be unaware of. * This includes: * a) Comments * b) &alias definitions * c) &alias expansions */ for (;;) { if (!DefGetToken(&deftoken, &deftokenLength)) { /* get a raw token */ return 0; } fc = deftoken[0]; uc_token = (char *)realloc(uc_token, deftokenLength); /* first, check for # comments or &alias statements. # comments we ignore, and &alias statements are eaten and recorded by the lexer. */ if (fc == settings->CommentChar) { // The code isn't work in correct way, no way to fix it exits // but keep it for compatibility reasons. int magic_count = -1; for (fc = GETC();; fc = GETC()) { /* so skip to the end of line */ magic_count++; if ((magic_count < (int)strlen(magic)) && (fc == magic[magic_count])) { if ((int)strlen(magic) == (magic_count + 1)) { if (settings->MagicCommentFoundFunction) { settings->MagicCommentFoundFunction(); } } } if (fc == EOF) return 0; if (fc == '\n') { print_lines(++nlines); break; } } } else if (fc == '&') { /* begins with &. If &alias, read contents and */ /* store them. Otherwise it's a define, or a macro use. */ string alias; uc_array(deftoken, uc_token); if (strcmp(uc_token, "&ALIAS") == 0) StoreAlias(); /* read and store the alias */ else if (defGetAlias(deftoken, alias)) stack[++input_level] = alias; else break; /* begins with &, but not an &alias defn. or use. */ } else break; /* does not begin with commentChar or '&' */ } if (defInvalidChar) { outMsg = (char *)malloc(500 + strlen(deftoken)); sprintf(outMsg, "Invalid characters found in \'%s\'.\nThese characters might be using the character types other than English.\nCreate " "characters by specifying valid characters types.", deftoken); defError(6008, outMsg); free(outMsg); hasFatalError = 1; return 0; } if (doneDesign) { fc = EOF; defInfo(8000, "There are still data after the END DESIGN statement"); return 0; } if (fc == '\"') { pYylval->string = ringCopy(&(deftoken[1])); return QSTRING; } /* at this point we've read a token */ /* printf("Token is %s\n", deftoken); */ // Protect the token counting variables form the decrement overflow. if (dumb_mode >= 0) { dumb_mode--; } if (no_num >= 0) { no_num--; } if (isdigit(fc) || fc == '.' || (fc == '-' && deftoken[1] != '\0')) { char *ch; /* 6/12/2003 - The following switching to use strtol first is a fix */ /* for FE for performance improvement. */ /* Adding the flag "parsing_property" is for pcr 594214, need to call */ /* strtod first to handle double number inside PROPERTY. Only */ /* property has real number (large number) */ if (!real_num) { pYylval->dval = strtol(deftoken, &ch, 10); /* try string to long first */ if (no_num < 0 && *ch == '\0') { /* did we use the whole string? */ return NUMBER; } else { /* failed strtol, try double */ numVal = pYylval->dval = strtod(deftoken, &ch); if (no_num < 0 && *ch == '\0') { /* did we use the whole string? */ /* check if the integer has exceed the limit */ if ((numVal >= lVal) && (numVal <= rVal)) return NUMBER; /* YES, it's really a number */ else { char *str = (char *)malloc(strlen(deftoken) + strlen(session->FileName) + 350); sprintf(str, "<Number has exceed the limit for an integer> in %s at line %s\n", session->FileName, lines2str(nlines)); fflush(stdout); defiError(1, 0, str); free(str); errors++; return NUMBER; } } else { pYylval->string = ringCopy(deftoken); /* NO, it's a string */ return T_STRING; } } } else { /* handling PROPERTY, do strtod first instead of strtol */ numVal = pYylval->dval = strtod(deftoken, &ch); if (no_num < 0 && *ch == '\0') { /* did we use the whole string? */ /* check if the integer has exceed the limit */ if (real_num) /* this is for PROPERTYDEF with REAL */ return NUMBER; if ((numVal >= lVal) && (numVal <= rVal)) return NUMBER; /* YES, it's really a number */ else { char *str = (char *)malloc(strlen(deftoken) + strlen(session->FileName) + 350); sprintf(str, "<Number has exceed the limit for an integer> in %s at line %s\n", session->FileName, lines2str(nlines)); fflush(stdout); defiError(1, 0, str); free(str); errors++; return NUMBER; } } else { /* failed integer conversion, try floating point */ pYylval->dval = strtol(deftoken, &ch, 10); if (no_num < 0 && *ch == '\0') /* did we use the whole string? */ return NUMBER; else { pYylval->string = ringCopy(deftoken); /* NO, it's a string */ return T_STRING; } } } } /* if we are dumb mode, all we return is punctuation and strings & numbers*/ /* until we see the next '+' or ';' deftoken */ if (dumb_mode >= 0) { if (deftoken[1] == '\0' && (fc == '(' || fc == ')' || fc == '+' || fc == ';' || fc == '*')) { if (fc == ';' || fc == '+') { dumb_mode = 0; no_num = 0; } return (int)fc; } if (by_is_keyword && ((strcmp(deftoken, "BY") == 0) || (strcmp(deftoken, "by") == 0))) { return K_BY; /* even in dumb mode, we must see the BY deftoken */ } if (do_is_keyword && ((strcmp(deftoken, "DO") == 0) || (strcmp(deftoken, "do") == 0))) { return K_DO; /* even in dumb mode, we must see the DO deftoken */ } if (new_is_keyword && ((strcmp(deftoken, "NEW") == 0) || (strcmp(deftoken, "new") == 0))) { return K_NEW; /* even in dumb mode, we must see the NEW deftoken */ } if (nondef_is_keyword && ((strcmp(deftoken, "NONDEFAULTRULE") == 0) || (strcmp(deftoken, "nondefaultrule") == 0))) { return K_NONDEFAULTRULE; /* even in dumb mode, we must see the */ /* NONDEFAULTRULE deftoken */ } if (mustjoin_is_keyword && ((strcmp(deftoken, "MUSTJOIN") == 0) || (strcmp(deftoken, "mustjoin") == 0))) { return K_MUSTJOIN; /* even in dumb mode, we must see the */ /* MUSTJOIN deftoken */ } if (step_is_keyword && ((strcmp(deftoken, "STEP") == 0) || (strcmp(deftoken, "step") == 0))) { return K_STEP; /* even in dumb mode, we must see the STEP deftoken */ } if (fixed_is_keyword && ((strcmp(deftoken, "FIXED") == 0) || (strcmp(deftoken, "fixed") == 0))) { return K_FIXED; /* even in dumb mode, we must see the FIXED deftoken */ } if (cover_is_keyword && ((strcmp(deftoken, "COVER") == 0) || (strcmp(deftoken, "cover") == 0))) { return K_COVER; /* even in dumb mode, we must see the COVER deftoken */ } if (routed_is_keyword && ((strcmp(deftoken, "ROUTED") == 0) || (strcmp(deftoken, "rounted") == 0))) { return K_ROUTED; /* even in dumb mode, we must see the */ /* ROUTED deftoken */ } if (virtual_is_keyword && ((strcmp(deftoken, "VIRTUAL") == 0) || (strcmp(deftoken, "virtual") == 0))) { return K_VIRTUAL; } if (rect_is_keyword && ((strcmp(deftoken, "RECT") == 0) || (strcmp(deftoken, "rect") == 0))) { return K_RECT; } if (virtual_is_keyword && ((strcmp(deftoken, "MASK") == 0) || (strcmp(deftoken, "mask") == 0))) { return K_MASK; } if (orient_is_keyword) { int result; uc_array(deftoken, uc_token); if (defGetKeyword(uc_token, &result)) { if (K_N == result) return K_N; if (K_W == result) return K_W; if (K_S == result) return K_S; if (K_E == result) return K_E; if (K_FN == result) return K_FN; if (K_FW == result) return K_FW; if (K_FS == result) return K_FS; if (K_FE == result) if (strcmp(deftoken, "FE") == 0) return K_FE; } } pYylval->string = ringCopy(deftoken); return T_STRING; } /* if we get here we are in smart mode. Parse deftoken */ /* 2/19/2004 - add _ since name can starts with '_' */ /* 2/23/2004 - add the following characters which a name can starts with */ /* ! $ | : , @ ~ = < . ? { ' ^ " */ if (isalpha(fc) || fc == '&' || fc == '_') { int result; History_text.resize(0); uc_array(deftoken, uc_token); if (defGetKeyword(uc_token, &result)) { if (K_HISTORY == result) { /* history - get up to ';' */ int n; int c; int prev; n = 0; prev = ' '; while (1) { c = GETC(); if (c == EOF) { defError(6015, "Unexpected end of the DEF file."); break; } if (c == ';' && (prev == ' ' || prev == '\t' || prev == '\n')) break; if (c == '\n') { print_lines(++nlines); } prev = c; History_text.push_back(c); } History_text.push_back('\0'); } else if (K_BEGINEXT == result) { /* extension, get up to end */ int nn; int cc; int foundTag = 0; int notEmpTag = 0; int begQuote = 0; nn = 0; /* First make sure there is a name after BEGINEXT within quote */ /* BEGINEXT "name" */ while (1) { cc = GETC(); if (cc == EOF) { defError(6015, "Unexpected end of the DEF file."); break; } if (cc == '\n') { if (!foundTag) { defError(6003, "tag is missing for BEGINEXT"); break; } } else { History_text.push_back(cc); if (cc != ' ') { if (cc == '\"') { /* found a quote */ if (!begQuote) begQuote = 1; else if (notEmpTag) { foundTag = 1; break; /* Found the quoted tag */ } else { defError(6004, "The BEGINEXT tag is empty. Specify a value for the tag and try again."); break; } } else if (!begQuote) { /* anything but a quote */ defError(6005, "The '\"' is missing within the tag. Specify the '\"' in the tag and then try again."); break; } else /* anything but a quote and there */ notEmpTag = 1; /* is already a quote */ } } } if (foundTag) { /* We have handle with the tag, just read the rest until */ /* ENDEXT */ begQuote = 0; while (1) { cc = GETC(); if (cc == EOF) { defError(6015, "Unexpected end of the DEF file."); break; } if (cc == '\n') { print_lines(++nlines); } else if (cc == '\"') { if (!begQuote) begQuote = 1; else begQuote = 0; } History_text.push_back(cc); int histTextSize = History_text.size(); if (histTextSize >= 6 && memcmp(&History_text[histTextSize - 6], "ENDEXT", 6) == 0) { if (begQuote) defError(6006, "The ending '\"' is missing in the tag. Specify the ending '\"' in the tag and then try again."); break; } else if (histTextSize >= 10 && memcmp(&History_text[histTextSize - 10], "END DESIGN", 10) == 0) { defError(6007, "The ENDEXT statement is missing in the DEF file. Include the statement and then try again."); nlines--; break; } } } History_text.push_back('\0'); } return result; /* YES, return its value */ } else { /* we don't have a keyword. */ if (fc == '&') return amper_lookup(pYylval, deftoken); pYylval->string = ringCopy(deftoken); /* NO, it's a string */ return T_STRING; } } else { /* it should be a punctuation character */ if (deftoken[1] != '\0') { if (strcmp(deftoken, ">=") == 0) return K_GE; if (strcmp(deftoken, "<=") == 0) return K_LE; if (strcmp(deftoken, "<>") == 0) return K_NE; defError(6017, "Odd punctuation found."); hasFatalError = 1; } else if (strlen(deftoken) > 2 || strlen(deftoken) == 0) { defError(6017, "Odd punctuation found."); hasFatalError = 1; } return (int)deftoken[0]; } } /* We have found a deftoken beginning with '&'. If it has been previously defined, substitute the definition. Otherwise return it. */ int defrData::amper_lookup(YYSTYPE *pYylval, char *tkn) { string defValue; /* printf("Amper_lookup: %s\n", tkn); */ /* &defines returns a T_STRING */ if (defGetDefine(tkn, defValue)) { int value; if (defGetKeyword(defValue.c_str(), &value)) return value; if (defValue.c_str()[0] == '"') pYylval->string = ringCopy(defValue.c_str() + 1); else pYylval->string = ringCopy(defValue.c_str()); return (defValue.c_str()[0] == '\"' ? QSTRING : T_STRING); } /* if none of the above, just return the deftoken. */ pYylval->string = ringCopy(tkn); return T_STRING; } void defrData::defError(int msgNum, const char *s) { char * str; const char *curToken = isgraph(deftoken[0]) ? deftoken : "<unprintable>"; const char *pvToken = isgraph(pv_deftoken[0]) ? pv_deftoken : "<unprintable>"; int len = strlen(curToken) - 1; int pvLen = strlen(pvToken) - 1; if (hasFatalError) return; if ((settings->totalDefMsgLimit > 0) && (defMsgPrinted >= settings->totalDefMsgLimit)) return; if (settings->MsgLimit[msgNum - 5000] > 0) { if (msgLimit[msgNum - 5000] >= settings->MsgLimit[msgNum - 5000]) return; /* over the limit */ msgLimit[msgNum - 5000] = msgLimit[msgNum - 5000] + 1; } /* PCR 690679, probably missing space before a ';' */ if (strcmp(s, "parse error") == 0) { if ((len > 1) && (deftoken[len] == ';')) { str = (char *)malloc(len + strlen(s) + strlen(session->FileName) + 350); sprintf(str, "ERROR (DEFPARS-%d): %s, file %s at line %s\nLast token was <%s>, space is missing before <;>\n", msgNum, s, session->FileName, lines2str(nlines), curToken); } else if ((pvLen > 1) && (pv_deftoken[pvLen] == ';')) { str = (char *)malloc(pvLen + strlen(s) + strlen(session->FileName) + 350); sprintf(str, "ERROR (DEFPARS-%d): %s, file %s at line %s\nLast token was <%s>, space is missing before <;>\n", msgNum, s, session->FileName, lines2str(nlines - 1), pvToken); } else { str = (char *)malloc(len + strlen(session->FileName) + 350); sprintf(str, "ERROR (DEFPARS-%d): Def parser has encountered an error in file %s at line %s, on token %s.\nProblem can be syntax " "error on the def file or an invalid parameter name.\nDouble check the syntax on the def file with the LEFDEF " "Reference Manual.\n", msgNum, session->FileName, lines2str(nlines), curToken); } } else if (strcmp(s, "syntax error") == 0) { if ((len > 1) && (deftoken[len] == ';')) { str = (char *)malloc(len + strlen(s) + strlen(session->FileName) + 350); sprintf(str, "ERROR (DEFPARS-%d): %s, file %s at line %s\nLast token was <%s>, space is missing before <;>\n", msgNum, s, session->FileName, lines2str(nlines), curToken); } else if ((pvLen > 1) && (pv_deftoken[pvLen] == ';')) { str = (char *)malloc(pvLen + strlen(s) + strlen(session->FileName) + 350); sprintf(str, "ERROR (DEFPARS-%d): %s, file %s at line %s\nLast token was <%s>, space is missing before <;>\n", msgNum, s, session->FileName, lines2str(nlines - 1), pvToken); } else { str = (char *)malloc(len + strlen(session->FileName) + 350); sprintf(str, "ERROR (DEFPARS-%d): Def parser has encountered an error in file %s at line %s, on token %s.\nProblem can be syntax " "error on the def file or an invalid parameter name.\nDouble check the syntax on the def file with the LEFDEF " "Reference Manual.\n", msgNum, session->FileName, lines2str(nlines), curToken); } } else { str = (char *)malloc(len + strlen(s) + strlen(session->FileName) + 350); sprintf( str, "ERROR (DEFPARS-%d): %s Error in file %s at line %s, on token %s.\nUpdate the def file before parsing the file again.\n", msgNum, s, session->FileName, lines2str(nlines), curToken); } fflush(stdout); defiError(1, msgNum, str); free(str); errors++; } /* yydeferror is called by bison.simple */ void defrData::defyyerror(const char *s) { defError(defMsgCnt++, s); } /* All info starts with 8000 */ /* All info within defInfo starts with 8500 */ void defrData::defInfo(int msgNum, const char *s) { int i; for (i = 0; i < settings->nDDMsgs; i++) { /* check if info has been disable */ if (settings->disableDMsgs[i] == msgNum) return; /* don't print out any info since msg has been disabled */ } if (settings->ContextWarningLogFunction) { char *str = (char *)malloc(strlen(deftoken) + strlen(s) + strlen(session->FileName) + 350); sprintf(str, "INFO (DEFPARS-%d): %s See file %s at line %s.\n", msgNum, s, session->FileName, lines2str(nlines)); (*settings->ContextWarningLogFunction)(session->UserData, str); free(str); } else if (settings->WarningLogFunction) { char *str = (char *)malloc(strlen(deftoken) + strlen(s) + strlen(session->FileName) + 350); sprintf(str, "INFO (DEFPARS-%d): %s See file %s at line %s.\n", msgNum, s, session->FileName, lines2str(nlines)); (*settings->WarningLogFunction)(str); free(str); } else if (defrLog) { fprintf(defrLog, "INFO (DEFPARS-%d): %s See file %s at line %s\n", msgNum, s, session->FileName, lines2str(nlines)); } else { if (!hasOpenedDefLogFile) { if ((defrLog = fopen("defRWarning.log", "w")) == 0) { printf("WARNING(DEFPARS-8500): Unable to open the file defRWarning.log in %s.\n", getcwd(NULL, 64)); printf("Info messages will not be printed.\n"); } else { hasOpenedDefLogFile = 1; fprintf(defrLog, "Info from file: %s\n\n", session->FileName); fprintf(defrLog, "INFO (DEFPARS-%d): %s See file %s at line %s\n", msgNum, s, session->FileName, lines2str(nlines)); } } else { if ((defrLog = fopen("defRWarning.log", "a")) == 0) { printf("WARNING (DEFPARS-8500): Unable to open the file defRWarning.log in %s.\n", getcwd(NULL, 64)); printf("Info messages will not be printed.\n"); } else { hasOpenedDefLogFile = 1; fprintf(defrLog, "\nInfo from file: %s\n\n", session->FileName); fprintf(defrLog, "INFO (DEFPARS-%d): %s See file %s at line %s\n", msgNum, s, session->FileName, lines2str(nlines)); } } } } /* All warning starts with 7000 */ /* All warning within defWarning starts with 7500 */ void defrData::defWarning(int msgNum, const char *s) { int i; for (i = 0; i < settings->nDDMsgs; i++) { /* check if warning has been disable */ if (settings->disableDMsgs[i] == msgNum) return; /* don't print out any warning since msg has been disabled */ } if (settings->ContextWarningLogFunction) { char *str = (char *)malloc(strlen(deftoken) + strlen(s) + strlen(session->FileName) + 350); sprintf(str, "WARNING (DEFPARS-%d): %s See file %s at line %s.\n", msgNum, s, session->FileName, lines2str(nlines)); (*settings->ContextWarningLogFunction)(session->UserData, str); free(str); } else if (settings->WarningLogFunction) { char *str = (char *)malloc(strlen(deftoken) + strlen(s) + strlen(session->FileName) + 350); sprintf(str, "WARNING (DEFPARS-%d): %s See file %s at line %s.\n", msgNum, s, session->FileName, lines2str(nlines)); (*settings->WarningLogFunction)(str); free(str); } else if (defrLog) { fprintf(defrLog, "WARNING (DEFPARS-%d): %s See file %s at line %s\n", msgNum, s, session->FileName, lines2str(nlines)); } else { if (!hasOpenedDefLogFile) { if ((defrLog = fopen("defRWarning.log", "w")) == 0) { printf("WARNING (DEFPARS-7500): Unable to open the file defRWarning.log in %s.\n", getcwd(NULL, 64)); printf("Warning messages will not be printed.\n"); } else { hasOpenedDefLogFile = 1; fprintf(defrLog, "Warnings from file: %s\n\n", session->FileName); fprintf(defrLog, "WARNING (DEFPARS-%d): %s See file %s at line %s\n", msgNum, s, session->FileName, lines2str(nlines)); } } else { if ((defrLog = fopen("defRWarning.log", "a")) == 0) { printf("WARNING (DEFAPRS-7501): Unable to open the file defRWarning.log in %s.\n", getcwd(NULL, 64)); printf("Warning messages will not be printed.\n"); } else { hasOpenedDefLogFile = 1; fprintf(defrLog, "\nWarnings from file: %s\n\n", session->FileName); fprintf(defrLog, "WARNING (DEFPARS-%d): %s See file %s at line %s\n", msgNum, s, session->FileName, lines2str(nlines)); } } } def_warnings++; } const char *defrData::defkywd(int num) { switch (num) { case QSTRING: return "QSTRING"; case T_STRING: return "T_STRING"; case SITE_PATTERN: return "SITE_PATTERN"; case NUMBER: return "NUMBER"; case K_ALIGN: return "ALIGN"; case K_AND: return "AND"; case K_ARRAY: return "ARRAY"; case K_ASSERTIONS: return "ASSERTIONS"; case K_BEGINEXT: return "BEGINEXT"; case K_BOTTOMLEFT: return "BOTTOMLEFT"; case K_BUSBITCHARS: return "BUSBITCHARS"; case K_BY: return "BY"; case K_CANNOTOCCUPY: return "CANNOTOCCUPY"; case K_CANPLACE: return "CANPLACE"; case K_CAPACITANCE: return "CAPACITANCE"; case K_COMMONSCANPINS: return "COMMONSCANPINS"; case K_COMPONENT: return "COMPONENT"; case K_COMPONENTPIN: return "COMPONENTPIN"; case K_COMPS: return "COMPS"; case K_COMP_GEN: return "COMP_GEN"; case K_CONSTRAINTS: return "CONSTRAINTS"; case K_COVER: return "COVER"; case K_CUTSIZE: return "CUTSIZE"; case K_CUTSPACING: return "CUTSPACING"; case K_DEFAULTCAP: return "DEFAULTCAP"; case K_DEFINE: return "DEFINE"; case K_DEFINES: return "DEFINES"; case K_DEFINEB: return "DEFINEB"; case K_DESIGN: return "DESIGN"; case K_DESIGNRULEWIDTH: return "DESIGNRULEWIDTH"; case K_DIAGWIDTH: return "DIAGWIDTH"; case K_DIEAREA: return "DIEAREA"; case K_DIFF: return "DIFF"; case K_DIRECTION: return "DIRECTION"; case K_DIST: return "DIST"; case K_DISTANCE: return "DISTANCE"; case K_DIVIDERCHAR: return "DIVIDERCHAR"; case K_DO: return "DO"; case K_DRIVECELL: return "DRIVECELL"; case K_E: return "E"; case K_EEQMASTER: return "EEQMASTER"; case K_ELSE: return "ELSE"; case K_ENCLOSURE: return "ENCLOSURE"; case K_END: return "END"; case K_ENDEXT: return "ENDEXT"; case K_EQ: return "EQ"; case K_EQUAL: return "EQUAL"; case K_ESTCAP: return "ESTCAP"; case K_FE: return "FE"; case K_FALL: return "FALL"; case K_FALLMAX: return "FALLMAX"; case K_FALLMIN: return "FALLMIN"; case K_FALSE: return "FALSE"; case K_FIXED: return "FIXED"; case K_FLOATING: return "FLOATING"; case K_FLOORPLAN: return "FLOORPLAN"; case K_FN: return "FN"; case K_FOREIGN: return "FOREIGN"; case K_FPC: return "FPC"; case K_FROMCLOCKPIN: return "FROMCLOCKPIN"; case K_FROMCOMPPIN: return "FROMCOMPPIN"; case K_FROMPIN: return "FROMPIN"; case K_FROMIOPIN: return "FROMIOPIN"; case K_FS: return "FS"; case K_FW: return "FW"; case K_GCELLGRID: return "GCELLGRID"; case K_GE: return "GE"; case K_GT: return "GT"; case K_GROUND: return "GROUND"; case K_GROUNDSENSITIVITY: return "GROUNDSENSITIVITY"; case K_GROUP: return "GROUP"; case K_GROUPS: return "GROUPS"; case K_HALO: return "HALO"; case K_HARDSPACING: return "HARDSPACING"; case K_HISTORY: return "HISTORY"; case K_HOLDRISE: return "HOLDRISE"; case K_HOLDFALL: return "HOLDFALL"; case K_HORIZONTAL: return "HORIZONTAL"; case K_IF: return "IF"; case K_IN: return "IN"; case K_INTEGER: return "INTEGER"; case K_IOTIMINGS: return "IOTIMINGS"; case K_LAYER: return "LAYER"; case K_LAYERS: return "LAYERS"; case K_LE: return "LE"; case K_LT: return "LT"; case K_MACRO: return "MACRO"; case K_MASK: return "MASK"; case K_MAX: return "MAX"; case K_MAXDIST: return "MAXDIST"; case K_MAXHALFPERIMETER: return "MAXHALFPERIMETER"; case K_MAXX: return "MAXX"; case K_MAXY: return "MAXY"; case K_MICRONS: return "MICRONS"; case K_MIN: return "MIN"; case K_MINCUTS: return "MINCUTS"; case K_MINPINS: return "MINPINS"; case K_MUSTJOIN: return "MUSTJOIN"; case K_N: return "N"; case K_NAMESCASESENSITIVE: return "NAMESCASESENSITIVE"; case K_NAMEMAPSTRING: return "NAMEMAPSTRING"; case K_NE: return "NE"; case K_NET: return "NET"; case K_NETEXPR: return "NETEXPR"; case K_NETLIST: return "NETLIST"; case K_NETS: return "NETS"; case K_NEW: return "NEW"; case K_NONDEFAULTRULE: return "NONDEFAULTRULE"; case K_NOSHIELD: return "NOSHIELD"; case K_NOT: return "NOT"; case K_OFF: return "OFF"; case K_OFFSET: return "OFFSET"; case K_ON: return "ON"; case K_OR: return "OR"; case K_ORDERED: return "ORDERED"; case K_ORIGIN: return "ORIGIN"; case K_ORIGINAL: return "ORIGINAL"; case K_OUT: return "OUT"; case K_PARALLEL: return "PARALLEL"; case K_PARTITIONS: return "PARTITIONS"; case K_PATH: return "PATH"; case K_PATTERN: return "PATTERN"; case K_PATTERNNAME: return "PATTERNNAME"; case K_PINPROPERTIES: return "PINPROPERTIES"; case K_PINS: return "PINS"; case K_PLACED: return "PLACED"; case K_PIN: return "PIN"; case K_POLYGON: return "POLYGON"; case K_PROPERTY: return "PROPERTY"; case K_PROPERTYDEFINITIONS: return "PROPERTYDEFINITIONS"; case K_RANGE: return "RANGE"; case K_REAL: return "REAL"; case K_RECT: return "RECT"; case K_REENTRANTPATHS: return "REREENTRANTPATHS"; case K_REGION: return "REGION"; case K_REGIONS: return "REGIONS"; case K_RISE: return "RISE"; case K_RISEMAX: return "RISEMAX"; case K_RISEMIN: return "RISEMIN"; case K_ROUTED: return "ROUTED"; case K_ROW: return "ROW"; case K_ROWCOL: return "ROWCOL"; case K_ROWS: return "ROWS"; case K_S: return "S"; case K_SCANCHAINS: return "SCANCHAINS"; case K_SETUPRISE: return "SETUPRISE"; case K_SETUPFALL: return "SETUPFALL"; case K_SHAPE: return "SHAPE"; case K_SITE: return "SITE"; case K_SLEWRATE: return "SLEWRATE"; case K_SNET: return "SNET"; case K_SNETS: return "SNETS"; case K_SOURCE: return "SOURCE"; case K_SOFT: return "SOFT"; case K_SPACING: return "SPACING"; case K_SPECIAL: return "SPECIAL"; case K_START: return "START"; case K_START_NET: return "START_NET"; case K_STEP: return "STEP"; case K_STRING: return "STRING"; case K_STOP: return "STOP"; case K_SUBNET: return "SUBNET"; case K_SUM: return "SUM"; case K_SUPPLYSENSITIVITY: return "SUPPLYSENSITIVITY"; case K_STYLE: return "STYLE"; case K_STYLES: return "STYLES"; case K_SYNTHESIZED: return "SYNTHESIZED"; case K_TAPER: return "TAPER"; case K_TAPERRULE: return "TAPERRULE"; case K_THEN: return "THEN"; case K_THRUPIN: return "THRUPIN"; case K_TIMING: return "TIMING"; case K_TIMINGDISABLES: return "TIMINGDISABLES"; case K_TOCLOCKPIN: return "TOCLOCKPIN"; case K_TOCOMPPIN: return "TOCOMPPIN"; case K_TOIOPIN: return "TOIOPIN"; case K_TOPIN: return "TOPIN"; case K_TOPRIGHT: return "TOPRIGHT"; case K_TRACKS: return "TRACKS"; case K_TRUE: return "TRUE"; case K_TURNOFF: return "TURNOFF"; case K_VARIABLE: return "VARIABLE"; case K_VIA: return "VIA"; case K_VIARULE: return "VIARULE"; case K_VIAS: return "VIAS"; case K_VOLTAGE: return "VOLTAGE"; case K_TECH: return "TECH"; case K_UNITS: return "UNITS"; case K_UNPLACED: return "UNPLACED"; case K_USE: return "USE"; case K_USER: return "USER"; case K_VERSION: return "VERSION"; case K_VIRTUAL: return "VIRTUAL"; case K_VERTICAL: return "VERTICAL"; case K_VPIN: return "VPIN"; case K_W: return "W"; case K_WIRECAP: return "WIRECAP"; case K_WEIGHT: return "WEIGHT"; case K_WIDTH: return "WIDTH"; case K_WIREDLOGIC: return "WIREDLOGIC"; case K_WIREEXT: return "WIREEXT"; case K_XTALK: return "XTALK"; case K_X: return "X"; case K_Y: return "Y"; default: return "bogus"; } } const char *defrData::DEFCASE(const char *ch) { return names_case_sensitive ? ch : upperCase(ch); } void defrData::pathIsDone(int sh, int reset, int osNet, int *needCbk) { if ((callbacks->NetCbk || callbacks->SNetCbk) && settings->AddPathToNet) { // PathObj.reverseOrder(); if (Subnet) { // if (sh) // defrSubnet->addShieldPath(defrPath); // else Subnet->addWirePath(&PathObj, reset, osNet, needCbk); } else { if (sh) Net.addShieldPath(&PathObj, reset, osNet, needCbk); else Net.addWirePath(&PathObj, reset, osNet, needCbk); } } else if (callbacks->PathCbk) { // defrPath->reverseOrder(); (*callbacks->PathCbk)(defrPathCbkType, &PathObj, session->UserData); PathObj.Destroy(); free((char *)&PathObj); } PathObj.Init(); } END_LEFDEF_PARSER_NAMESPACE
33.525553
131
0.568347
[ "shape" ]
3bb730d00f550e279c19b90b0c2ea55704d5de2c
3,192
cpp
C++
Source/Node/VGNode.cpp
IppClub/Dorothy-SSR
2fb74673e76e5cef0218788757ce2de3c588ed33
[ "MIT" ]
57
2016-12-08T07:29:44.000Z
2019-12-25T13:15:50.000Z
Source/Node/VGNode.cpp
IppClub/Dorothy-SSR
2fb74673e76e5cef0218788757ce2de3c588ed33
[ "MIT" ]
3
2018-06-07T06:31:39.000Z
2019-10-04T07:16:15.000Z
Source/Node/VGNode.cpp
IppClub/Dorothy-SSR
2fb74673e76e5cef0218788757ce2de3c588ed33
[ "MIT" ]
16
2016-12-08T07:39:15.000Z
2020-01-03T06:54:25.000Z
/* Copyright (c) 2022 Jin Li, dragon-fly@qq.com 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 "Const/Header.h" #include "Node/VGNode.h" #include "Node/Sprite.h" #include "Basic/VGRender.h" #include "Basic/View.h" #include "nanovg/nanovg_bgfx.h" NS_DOROTHY_BEGIN VGNode::VGNode(float width, float height, float scale, int edgeAA): _frameWidth(width), _frameHeight(height), _frameScale(scale), _edgeAA(edgeAA) { } Sprite* VGNode::getSurface() const { return _surface; } bool VGNode::init() { if (!Node::init()) return false; NVGcontext* context = nvgCreate(_edgeAA, 0); NVGLUframebuffer* framebuffer = nvgluCreateFramebuffer(context, s_cast<int>(_frameWidth * _frameScale), s_cast<int>(_frameHeight * _frameScale), 0); bgfx::TextureInfo info; bgfx::calcTextureSize(info, s_cast<uint16_t>(_frameWidth * _frameScale), s_cast<uint16_t>(_frameHeight * _frameScale), 0, false, false, 1, bgfx::TextureFormat::RGBA8); uint64_t flags = BGFX_TEXTURE_RT | BGFX_SAMPLER_U_CLAMP | BGFX_SAMPLER_V_CLAMP; _surface = Sprite::create(VGTexture::create(context, framebuffer, info, flags)); _surface->addTo(this); return true; } void VGNode::cleanup() { if (_flags.isOff(Node::Cleanup)) { _surface = nullptr; Node::cleanup(); } } void VGNode::render(const std::function<void()>& func) { VGTexture* texture = s_cast<VGTexture*>(_surface->getTexture()); NVGLUframebuffer* framebuffer = texture->getFramebuffer(); NVGcontext* context = texture->getContext(); SharedView.pushFront("VGNode"_slice, [&]() { bgfx::ViewId viewId = SharedView.getId(); bgfx::setViewClear(viewId, BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH | BGFX_CLEAR_STENCIL, 0x0); nvgluSetViewFramebuffer(viewId, framebuffer); nvgluBindFramebuffer(framebuffer); nvgBeginFrame(context, _frameWidth, _frameHeight, _frameScale); nvg::BindContext(context); switch (bgfx::getCaps()->rendererType) { case bgfx::RendererType::OpenGL: case bgfx::RendererType::OpenGLES: nvgScale(context, 1.0f, -1.0f); nvgTranslate(context, 0.0f, -_frameHeight); break; default: break; } func(); nvg::BindContext(nullptr); nvgEndFrame(context); nvgluBindFramebuffer(nullptr); }); } NS_DOROTHY_END
35.466667
463
0.753133
[ "render" ]
3bbb20edabef1c0abbfe25ba512b8b5056137ea1
1,317
cpp
C++
OrionRenderer/src/main.cpp
Krusto/OrionRenderer
4d48363fb9353d863a002f786edfcaeff0135d4f
[ "Apache-2.0" ]
1
2021-01-28T22:51:24.000Z
2021-01-28T22:51:24.000Z
OrionRenderer/src/main.cpp
Krusto/OrionRenderer
4d48363fb9353d863a002f786edfcaeff0135d4f
[ "Apache-2.0" ]
null
null
null
OrionRenderer/src/main.cpp
Krusto/OrionRenderer
4d48363fb9353d863a002f786edfcaeff0135d4f
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <chrono> #include "Orion.h" using namespace Orion; void OnWindowClose(GLFWwindow* window) { glfwSetWindowShouldClose(window, true); } int main() { Window window("Title", { 1280,720 }, { 1280,720 }); glfwMakeContextCurrent(window); window.OnWindowClose(OnWindowClose); std::vector<Orion::Extension> extensionsToLoad{ Extension::DEBUG_REPORT, Extension::DEBUG_UTILS, Extension::KHR_SURFACE, Extension::KHR_WIN32_SURFACE }; Orion::Renderer::Init(&window, extensionsToLoad, VkPhysicalDeviceType::VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU); Orion::VertexLayout layout{ {"position",Orion::ShaderDataType::type::vec3},{"color",Orion::ShaderDataType::type::vec3} }; std::vector<Orion::Vertex> vertices { {{0.0f, -0.5f,0.0f}, {1.0f, 0.0f, 0.0f}}, {{0.5f, 0.5f,0.0f}, {0.0f, 1.0f, 0.0f}}, {{-0.5f, 0.5f,0.0f}, {0.0f, 0.0f, 1.0f}} }; while (window.IsOpen()) { auto start = std::chrono::steady_clock::now(); window.Begin(); Renderer::DrawFrame(); window.End(); auto end = std::chrono::steady_clock::now(); OrionLog("%dFPS",(1.0 / (double)std::chrono::duration_cast<std::chrono::duration<double, std::milli>>(end - start).count())*1000.0); glfwPollEvents(); } glfwDestroyWindow(window); glfwTerminate(); Orion::Renderer::Destroy(); return 0; }
23.517857
134
0.686409
[ "vector" ]
3bbde9d70495ee3c8e9332a0f5fb396f1a501f38
6,170
cc
C++
google/cloud/datacatalog/data_catalog_connection_idempotency_policy.cc
sydney-munro/google-cloud-cpp
374b52e5cec78962358bdd5913d4118a47af1952
[ "Apache-2.0" ]
null
null
null
google/cloud/datacatalog/data_catalog_connection_idempotency_policy.cc
sydney-munro/google-cloud-cpp
374b52e5cec78962358bdd5913d4118a47af1952
[ "Apache-2.0" ]
null
null
null
google/cloud/datacatalog/data_catalog_connection_idempotency_policy.cc
sydney-munro/google-cloud-cpp
374b52e5cec78962358bdd5913d4118a47af1952
[ "Apache-2.0" ]
null
null
null
// Copyright 2022 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. // See the License for the specific language governing permissions and // limitations under the License. // Generated by the Codegen C++ plugin. // If you make any local changes, they will be lost. // source: google/cloud/datacatalog/v1/datacatalog.proto #include "google/cloud/datacatalog/data_catalog_connection_idempotency_policy.h" #include "absl/memory/memory.h" #include <memory> namespace google { namespace cloud { namespace datacatalog { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN using ::google::cloud::Idempotency; DataCatalogConnectionIdempotencyPolicy:: ~DataCatalogConnectionIdempotencyPolicy() = default; namespace { class DefaultDataCatalogConnectionIdempotencyPolicy : public DataCatalogConnectionIdempotencyPolicy { public: ~DefaultDataCatalogConnectionIdempotencyPolicy() override = default; /// Create a new copy of this object. std::unique_ptr<DataCatalogConnectionIdempotencyPolicy> clone() const override { return absl::make_unique<DefaultDataCatalogConnectionIdempotencyPolicy>( *this); } Idempotency SearchCatalog( google::cloud::datacatalog::v1::SearchCatalogRequest) override { return Idempotency::kNonIdempotent; } Idempotency CreateEntryGroup( google::cloud::datacatalog::v1::CreateEntryGroupRequest const&) override { return Idempotency::kNonIdempotent; } Idempotency GetEntryGroup( google::cloud::datacatalog::v1::GetEntryGroupRequest const&) override { return Idempotency::kIdempotent; } Idempotency UpdateEntryGroup( google::cloud::datacatalog::v1::UpdateEntryGroupRequest const&) override { return Idempotency::kNonIdempotent; } Idempotency DeleteEntryGroup( google::cloud::datacatalog::v1::DeleteEntryGroupRequest const&) override { return Idempotency::kNonIdempotent; } Idempotency ListEntryGroups( google::cloud::datacatalog::v1::ListEntryGroupsRequest) override { return Idempotency::kIdempotent; } Idempotency CreateEntry( google::cloud::datacatalog::v1::CreateEntryRequest const&) override { return Idempotency::kNonIdempotent; } Idempotency UpdateEntry( google::cloud::datacatalog::v1::UpdateEntryRequest const&) override { return Idempotency::kNonIdempotent; } Idempotency DeleteEntry( google::cloud::datacatalog::v1::DeleteEntryRequest const&) override { return Idempotency::kNonIdempotent; } Idempotency GetEntry( google::cloud::datacatalog::v1::GetEntryRequest const&) override { return Idempotency::kIdempotent; } Idempotency LookupEntry( google::cloud::datacatalog::v1::LookupEntryRequest const&) override { return Idempotency::kIdempotent; } Idempotency ListEntries( google::cloud::datacatalog::v1::ListEntriesRequest) override { return Idempotency::kIdempotent; } Idempotency CreateTagTemplate( google::cloud::datacatalog::v1::CreateTagTemplateRequest const&) override { return Idempotency::kNonIdempotent; } Idempotency GetTagTemplate( google::cloud::datacatalog::v1::GetTagTemplateRequest const&) override { return Idempotency::kIdempotent; } Idempotency UpdateTagTemplate( google::cloud::datacatalog::v1::UpdateTagTemplateRequest const&) override { return Idempotency::kNonIdempotent; } Idempotency DeleteTagTemplate( google::cloud::datacatalog::v1::DeleteTagTemplateRequest const&) override { return Idempotency::kNonIdempotent; } Idempotency CreateTagTemplateField( google::cloud::datacatalog::v1::CreateTagTemplateFieldRequest const&) override { return Idempotency::kNonIdempotent; } Idempotency UpdateTagTemplateField( google::cloud::datacatalog::v1::UpdateTagTemplateFieldRequest const&) override { return Idempotency::kNonIdempotent; } Idempotency RenameTagTemplateField( google::cloud::datacatalog::v1::RenameTagTemplateFieldRequest const&) override { return Idempotency::kNonIdempotent; } Idempotency RenameTagTemplateFieldEnumValue( google::cloud::datacatalog::v1:: RenameTagTemplateFieldEnumValueRequest const&) override { return Idempotency::kNonIdempotent; } Idempotency DeleteTagTemplateField( google::cloud::datacatalog::v1::DeleteTagTemplateFieldRequest const&) override { return Idempotency::kNonIdempotent; } Idempotency CreateTag( google::cloud::datacatalog::v1::CreateTagRequest const&) override { return Idempotency::kNonIdempotent; } Idempotency UpdateTag( google::cloud::datacatalog::v1::UpdateTagRequest const&) override { return Idempotency::kNonIdempotent; } Idempotency DeleteTag( google::cloud::datacatalog::v1::DeleteTagRequest const&) override { return Idempotency::kNonIdempotent; } Idempotency ListTags( google::cloud::datacatalog::v1::ListTagsRequest) override { return Idempotency::kIdempotent; } Idempotency SetIamPolicy( google::iam::v1::SetIamPolicyRequest const&) override { return Idempotency::kNonIdempotent; } Idempotency GetIamPolicy( google::iam::v1::GetIamPolicyRequest const&) override { return Idempotency::kNonIdempotent; } Idempotency TestIamPermissions( google::iam::v1::TestIamPermissionsRequest const&) override { return Idempotency::kNonIdempotent; } }; } // namespace std::unique_ptr<DataCatalogConnectionIdempotencyPolicy> MakeDefaultDataCatalogConnectionIdempotencyPolicy() { return absl::make_unique<DefaultDataCatalogConnectionIdempotencyPolicy>(); } GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace datacatalog } // namespace cloud } // namespace google
30.097561
80
0.746677
[ "object" ]
3bbe31713c085588a59c908d6388eded9e74b43e
819
hpp
C++
src/gnb/app/task.hpp
aligungr/ue-ran-sim
564f9d228723f03adfa2b02df2ea019bdf305085
[ "MIT" ]
16
2020-04-16T02:07:37.000Z
2020-07-23T10:48:27.000Z
src/gnb/app/task.hpp
aligungr/ue-ran-sim
564f9d228723f03adfa2b02df2ea019bdf305085
[ "MIT" ]
8
2020-07-13T17:11:35.000Z
2020-08-03T16:46:31.000Z
src/gnb/app/task.hpp
aligungr/ue-ran-sim
564f9d228723f03adfa2b02df2ea019bdf305085
[ "MIT" ]
9
2020-03-04T15:05:08.000Z
2020-07-30T06:18:18.000Z
// // This file is a part of UERANSIM open source project. // Copyright (c) 2021 ALİ GÜNGÖR. // // The software and all associated files are licensed under GPL-3.0 // and subject to the terms and conditions defined in LICENSE file. // #pragma once #include <memory> #include <thread> #include <unordered_map> #include <vector> #include <gnb/types.hpp> #include <utils/logger.hpp> #include <utils/nts.hpp> namespace nr::gnb { class GnbAppTask : public NtsTask { private: TaskBase *m_base; std::unique_ptr<Logger> m_logger; GnbStatusInfo m_statusInfo; friend class GnbCmdHandler; public: explicit GnbAppTask(TaskBase *base); ~GnbAppTask() override = default; protected: void onStart() override; void onLoop() override; void onQuit() override; }; } // namespace nr::gnb
18.613636
67
0.702076
[ "vector" ]
3bc04c8d50f1d63baa203ddd3a1d51c1d2e03d2c
2,153
cpp
C++
Graph/TopologicalSorting/TopologicalSorting.cpp
PrachieNaik/DSA
083522bb3c8a0694adec1f2856d4d4cd0fb51722
[ "MIT" ]
null
null
null
Graph/TopologicalSorting/TopologicalSorting.cpp
PrachieNaik/DSA
083522bb3c8a0694adec1f2856d4d4cd0fb51722
[ "MIT" ]
null
null
null
Graph/TopologicalSorting/TopologicalSorting.cpp
PrachieNaik/DSA
083522bb3c8a0694adec1f2856d4d4cd0fb51722
[ "MIT" ]
null
null
null
/* Problem statement: Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering of vertices such that for every directed edge u v, vertex u comes before v in the ordering. Topological Sorting for a graph is not possible if the graph is not a DAG. In DFS, we start from a vertex, we first print it and then recursively call DFS for its adjacent vertices. In topological sorting, we use a temporary stack. We don’t print the vertex immediately, we first recursively call topological sorting for all its adjacent vertices, then push it to a stack. Finally, print contents of the stack. Note that a vertex is pushed to stack only when all of its adjacent vertices (and their adjacent vertices and so on) are already in the stack. Here, we can also use vector instead of the stack. If the vector is used then print the elements in reverse order to get the topological sorting. Applications: Topological Sorting is mainly used for scheduling jobs from the given dependencies among jobs. In computer science, applications of this type arise in instruction scheduling, ordering of formula cell evaluation when recomputing formula values in spreadsheets, logic synthesis, determining the order of compilation tasks to perform in make files, data serialization, and resolving symbol dependencies in linkers Complexity Analysis: Time Complexity: O(V+E). The above algorithm is simply DFS with an extra stack. So time complexity is the same as DFS which is. Auxiliary space: O(V). The extra space is needed for the stack. */ void topoSortUtil(vector<int> &ans,vector<int> &vis, vector<int> adj[],int index) { vis[index] = 1; for(auto i = adj[index].begin(); i != adj[index].end(); ++i) { if(vis[*i] == 0) { topoSortUtil(ans,vis,adj,*i); } } ans.push_back(index); } vector<int> topoSort(int V, vector<int> adj[]) { vector<int> ans; vector<int> vis; for(int i = 0 ;i < V;i++) { vis.push_back(0); } for(int i = 0 ;i < V;i++) { if(vis[i] == 0) { topoSortUtil(ans,vis,adj,i); } } reverse(ans.begin(),ans.end()); return ans; }
43.938776
165
0.709707
[ "vector" ]
3bc361b8e2522f76d3af49200ce63e1ae744d024
57,039
cpp
C++
src/game/client/swarm/vgui/asw_hud_minimap.cpp
BenLubar/SwarmDirector2
78685d03eaa0d35e87c638ffa78f46f3aa8379a6
[ "Apache-2.0" ]
3
2015-05-17T02:33:00.000Z
2016-10-08T07:02:40.000Z
src/game/client/swarm/vgui/asw_hud_minimap.cpp
BenLubar/SwarmDirector2
78685d03eaa0d35e87c638ffa78f46f3aa8379a6
[ "Apache-2.0" ]
null
null
null
src/game/client/swarm/vgui/asw_hud_minimap.cpp
BenLubar/SwarmDirector2
78685d03eaa0d35e87c638ffa78f46f3aa8379a6
[ "Apache-2.0" ]
1
2019-10-16T15:21:56.000Z
2019-10-16T15:21:56.000Z
#include "cbase.h" #include "hud.h" #include "hud_macros.h" #include "view.h" //#include "kbutton.h" #include "input.h" #include "iclientmode.h" #define PAIN_NAME "sprites/%d_pain.vmt" #include <KeyValues.h> #include <vgui/ISurface.h> #include <vgui/ISystem.h> #include <vgui_controls/AnimationController.h> #include <vgui_controls/ImagePanel.h> #include <vgui/ILocalize.h> using namespace vgui; #include "filesystem.h" #include <keyvalues.h> #include "asw_hud_minimap.h" #include "c_asw_player.h" #include "c_asw_marine.h" #include "asw_marine_profile.h" #include "c_asw_marine_resource.h" #include "c_asw_game_resource.h" #include "c_asw_scanner_info.h" #include "vgui/ISurface.h" #include <vgui/IInput.h> #include "fx.h" #include "tier0/vprof.h" #include "asw_gamerules.h" #include "ScanLinePanel.h" #include "c_asw_scanner_noise.h" #include "SoftLine.h" #include "c_asw_objective.h" #include "ConVar.h" #include "stats_report.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" extern ConVar asw_draw_hud; extern ConVar asw_hud_alpha; extern ConVar asw_hud_scale; ConVar asw_map_range("asw_map_range", "1200", FCVAR_CHEAT, "Range in world units of the minimap"); ConVar asw_scanner_ring_scale("asw_scanner_ring_scale", "1.0f", FCVAR_CHEAT, "Overdraw in the scanner ring size from the blip boundary"); ConVar asw_scanner_pitch_change("asw_scanner_pitch_change", "0.2f", FCVAR_NONE, "Change in pitch (from 0 to 1.0) of scanner blips depending on distance from the tech marine"); ConVar asw_scanner_pitch_base("asw_scanner_pitch_base", "1.2f", FCVAR_NONE, "Starting pitch"); ConVar asw_scanner_warning_volume("asw_scanner_warning_volume", "0.3f", FCVAR_NONE, "Volume of scanner warning beeps"); ConVar asw_scanner_idle_volume("asw_scanner_idle_volume", "0.4f", FCVAR_NONE, "Volume of scanner idle loop"); ConVar asw_scanner_scanline_alpha("asw_scanner_scanline_alpha", "80", 0, "Alpha of scanlines on the scanner"); ConVar asw_scanner_scanline_double("asw_scanner_scanline_double", "0", 0, "Whether scanlines should be single or double pixel"); ConVar asw_scanner_interlace_alpha("asw_scanner_interlace_alpha", "0", 0, "Alpha of interlace effect on the scanner"); ConVar asw_scanner_noise_alpha("asw_scanner_noise_alpha", "0", 0, "Alpha of noise effect on the scanner"); ConVar asw_scanner_idle_sound("asw_scanner_idle_sound", "3", 0, "Which scanner idle sound is used (from 1 to 4)"); ConVar asw_scanner_warning_sound("asw_scanner_warning_sound", "1", 0, "Which scanner warning sound is used (from 1 to 3)"); ConVar asw_debug_scanner_sound("asw_debug_scanner_sound", "0", FCVAR_CHEAT, "Prints debug output on scanner pulses"); ConVar asw_minimap_clicks("asw_minimap_clicks", "1", FCVAR_ARCHIVE, "Is enabled, clicking on the minimap will draw on it. If disabled, clicking there will fire your weapon as normal"); ConVar asw_scanner_background("asw_scanner_background", "1", FCVAR_NONE, "Draw black background behind minimap" ); ConVar asw_scanner_classic("asw_scanner_classic", "0", FCVAR_NONE, "Scanner has white blips, is always pinging." ); // was 0.75f.. #define ASW_SCREENSHOT_SCALE 1.0f MapLine::MapLine() { worldpos.Init(0,0); player_index = 0; linkpos.Init(0,0); created_time = 0; bSetLinkBlipCentre = false; bSetBlipCentre = false; blipcentre.Init(0,0); linkblipcentre.Init(0,0); bLink = false; } class CASWHudMinimap; class CASWHudMinimapLinePanel : public vgui::Panel { DECLARE_CLASS_SIMPLE( CASWHudMinimapLinePanel, vgui::Panel ); public: CASWHudMinimapLinePanel(Panel *parent, const char *panelName, CASWHudMinimap* pMap); void TextureToLinePanel(CASWHudMinimap* pMap, const Vector2D &blip_centre, float &x, float &y); virtual void Paint(); void PaintFollowLine(C_BaseEntity *pMarine, C_BaseEntity *pTarget); void PaintFollowLines(); virtual void PaintScannerRing(); CPanelAnimationVarAliasType( int, m_nScannerRingTexture, "ScannerRingTexture", "vgui/swarm/HUD/ScannerRing", "textureid" ); CASWHudMinimap* m_pMap; }; class CASWHudMinimapFramePanel : public vgui::Panel { DECLARE_CLASS_SIMPLE( CASWHudMinimapFramePanel, vgui::Panel ); public: CASWHudMinimapFramePanel(Panel *parent, const char *panelName); virtual void Paint(); }; DECLARE_HUDELEMENT( CASWHudMinimap ); CASWHudMinimapLinePanel::CASWHudMinimapLinePanel(Panel *parent, const char *panelName, CASWHudMinimap* pMap) : vgui::Panel(parent, panelName), m_pMap(pMap) { } CASWHudMinimapFramePanel::CASWHudMinimapFramePanel(Panel *parent, const char *panelName) : vgui::Panel(parent, panelName) { } void MsgFunc_ASWMapLine(bf_read &msg) { int linetype = msg.ReadByte(); int player_index = msg.ReadByte(); int world_x = msg.ReadLong(); int world_y = msg.ReadLong(); C_ASW_Player *local = C_ASW_Player::GetLocalASWPlayer(); if ( local ) { // figure out the position of this map line dot Vector vecMapLinePos = vec3_origin; vecMapLinePos.x = world_x; vecMapLinePos.y = world_y; CASWHudMinimap *pMiniMap = GET_HUDELEMENT(CASWHudMinimap); if (!pMiniMap) return; // make the HUD store it MapLine line; line.player_index = player_index; line.worldpos.x = world_x; line.worldpos.y = world_y; line.created_time = gpGlobals->curtime; if (linetype == 1) // links to a previous { line.bLink = true; } else { if (gpGlobals->curtime > pMiniMap->m_fLastMinimapDrawSound + 5.0f) { CLocalPlayerFilter filter; C_BaseEntity::EmitSound( filter, -1, "ASWScanner.Drawing" ); pMiniMap->m_fLastMinimapDrawSound = gpGlobals->curtime; } } pMiniMap->m_MapLines.AddToTail(line); } } ////////// // CASWMap ////////// // converts a world coord into map texture coords (0->1023) Vector2D CASWMap::WorldToMapTexture( const Vector &worldpos ) { if ( !m_pMinimap ) { m_pMinimap = GET_HUDELEMENT( CASWHudMinimap ); if ( !m_pMinimap ) { return vec2_origin; } } Vector2D offset( worldpos.x - m_pMinimap->m_MapOrigin.x, worldpos.y - m_pMinimap->m_MapOrigin.y); offset.x /= m_pMinimap->m_fMapScale; offset.y /= -m_pMinimap->m_fMapScale; offset.x -= 128; // I'd be lying if I knew why this needs to be here return offset; } void CASWMap::AddBlip( const MapBlip_t &blip ) { m_MapBlips.AddToTail( blip ); } void CASWMap::ClearBlips( void ) { m_MapBlips.RemoveAll(); } void CASWMap::PaintMarineBlips() { C_ASW_Game_Resource *pGameResource = ASWGameResource(); if ( pGameResource ) { // paint the blips for ( int i= 0; i < ASW_MAX_MARINE_RESOURCES; i++ ) { C_ASW_Marine_Resource *pMR = pGameResource->GetMarineResource(i); if ( pMR ) { C_ASW_Marine *pMarine = pMR->GetMarineEntity(); if ( pMarine && pMarine->GetHealth() > 0 ) { PaintWorldBlip( pMarine->GetAbsOrigin(), pMarine->GetBlipStrength(), Color(0,192,0,255) ); PaintWorldFacingArc(pMarine->GetAbsOrigin(), pMarine->ASWEyeAngles().y, Color(0,192,0,255 - 127.0f * pMarine->GetBlipStrength())); } } } } } void CASWMap::PaintExtraBlips() { for ( int i= 0; i < m_MapBlips.Count(); i++ ) { PaintWorldBlip( m_MapBlips[ i ].vWorldPos, sinf( gpGlobals->curtime * 8.0f ) * 0.25 + 0.25f, m_MapBlips[ i ].rgbaColor, m_MapBlips[ i ].nTextureType ); } } void CASWMap::PaintWorldBlip(const Vector &worldpos, float fBlipStrength, Color BlipColor, MapBlipTexture_t nBlipTexture /*= MAP_BLIP_TEXTURE_NORMAL*/ ) { int nStrengthIndex = clamp<int>( fBlipStrength * 7, 0, 7 ); if ( nStrengthIndex >= 7 || !m_nBlipTexture[ nStrengthIndex ] ) return; Vector2D blip_centre = WorldToMapTexture(worldpos); // convert from world coords to the pixel on the 0->1023 map texture //blip_centre = blip_centre - m_MapCentre + m_MapCentreInPanel; blip_centre = MapTextureToPanel(blip_centre); // convert from the map texture to its position on the panel Vector2D vMapCornerInPanel = GetMapCornerInPanel(); // don't draw out of bounds if ( blip_centre.x < vMapCornerInPanel.x || blip_centre.x > vMapCornerInPanel.x + GetMapSize() || blip_centre.y < vMapCornerInPanel.y || blip_centre.y > vMapCornerInPanel.y + GetMapSize() ) return; surface()->DrawSetColor( BlipColor ); int nTextureID; int iBlipSize = GetBlipSize(); switch ( nBlipTexture ) { case MAP_BLIP_TEXTURE_USABLE: nTextureID = m_nTriBlipTexture[ nStrengthIndex ]; break; case MAP_BLIP_TEXTURE_DEATH: nTextureID = m_nBlipTextureDeath; iBlipSize *= 1.5; break; case MAP_BLIP_TEXTURE_NORMAL: default: nTextureID = m_nBlipTexture[ nStrengthIndex ]; break; } surface()->DrawSetTexture( nTextureID ); float Dest1X = blip_centre.x - (iBlipSize * 0.5f); float Dest1Y = blip_centre.y - (iBlipSize * 0.5f); float Dest2X = Dest1X + iBlipSize; float Dest2Y = Dest1Y + iBlipSize; Vertex_t points[4] = { Vertex_t( Vector2D(Dest1X, Dest1Y), Vector2D(0,0) ), Vertex_t( Vector2D(Dest2X, Dest1Y), Vector2D(1,0) ), Vertex_t( Vector2D(Dest2X, Dest2Y), Vector2D(1,1) ), Vertex_t( Vector2D(Dest1X, Dest2Y), Vector2D(0,1) ) }; surface()->DrawTexturedPolygon( 4, points ); } void CASWMap::PaintWorldFacingArc(const Vector &worldpos, float fFacingYaw, Color FacingColor) { if ( GetFacingArcTexture() == -1) return; Vector2D blip_centre = WorldToMapTexture(worldpos); // convert from world coords to the pixel on the 0->1023 map texture blip_centre = MapTextureToPanel(blip_centre); // convert from the map texture to its position on the panel Vector2D vMapCornerInPanel = GetMapCornerInPanel(); // don't draw out of bounds if ( blip_centre.x < vMapCornerInPanel.x || blip_centre.y < vMapCornerInPanel.y || blip_centre.x > vMapCornerInPanel.x + GetMapSize() || blip_centre.y > vMapCornerInPanel.y + GetMapSize() ) return; int iFacingSize = GetArcSize(); // set up a square to the right int xoffset = -2; // temp? to make the arc look nice next to blips.. int yoffset = 1; Vector vecCornerTL(xoffset, iFacingSize * -0.5f + yoffset, 0); Vector vecCornerTR(iFacingSize + xoffset, iFacingSize * -0.5f+ yoffset, 0); Vector vecCornerBR(iFacingSize + xoffset, iFacingSize * 0.5f+ yoffset, 0); Vector vecCornerBL(xoffset, iFacingSize * 0.5f+ yoffset, 0); Vector vecCornerTL_rotated, vecCornerTR_rotated, vecCornerBL_rotated, vecCornerBR_rotated; // rotate it by our facing yaw QAngle angFacing(0, -fFacingYaw, 0); VectorRotate(vecCornerTL, angFacing, vecCornerTL_rotated); VectorRotate(vecCornerTR, angFacing, vecCornerTR_rotated); VectorRotate(vecCornerBR, angFacing, vecCornerBR_rotated); VectorRotate(vecCornerBL, angFacing, vecCornerBL_rotated); surface()->DrawSetColor(FacingColor); surface()->DrawSetTexture( GetFacingArcTexture() ); //surface()->DrawTexturedRect(Dest1X,Dest1Y,Dest2X,Dest2Y); Vertex_t points[4] = { Vertex_t( Vector2D(blip_centre.x + vecCornerTL_rotated.x, blip_centre.y + vecCornerTL_rotated.y), Vector2D(0,0) ), Vertex_t( Vector2D(blip_centre.x + vecCornerTR_rotated.x, blip_centre.y + vecCornerTR_rotated.y), Vector2D(1,0) ), Vertex_t( Vector2D(blip_centre.x + vecCornerBR_rotated.x, blip_centre.y + vecCornerBR_rotated.y), Vector2D(1,1) ), Vertex_t( Vector2D(blip_centre.x + vecCornerBL_rotated.x, blip_centre.y + vecCornerBL_rotated.y), Vector2D(0,1) ) }; surface()->DrawTexturedPolygon( 4, points ); } void CASWMap::LoadBlipTextures() { char buffer[64]; for (int i=0;i<7;i++) { m_nBlipTexture[i] = vgui::surface()->CreateNewTextureID(); Q_snprintf(buffer, sizeof(buffer), "%s%d", "vgui/swarm/HUD/blip", i+1); vgui::surface()->DrawSetTextureFile( m_nBlipTexture[i], buffer, true, false); m_nTriBlipTexture[i] = vgui::surface()->CreateNewTextureID(); Q_snprintf(buffer, sizeof(buffer), "%s%d", "vgui/swarm/HUD/triblip", i+1); vgui::surface()->DrawSetTextureFile( m_nTriBlipTexture[i], buffer, true, false); } m_nBlipTextureDeath = vgui::surface()->CreateNewTextureID(); vgui::surface()->DrawSetTextureFile( m_nBlipTextureDeath, "vgui/swarm/Briefing/deadmarine", true, false); m_nBlipTextureFriendlyDamage = m_nBlipTextureKill = m_nBlipTextureHeal = m_nBlipTextureFoundAmmo = m_nBlipTextureNoAmmo = m_nBlipTexture[ 0 ]; } CASWHudMinimap::CASWHudMinimap( const char *pElementName ) : CASW_HudElement( pElementName ), CHudNumericDisplay(NULL, "ASWHudMinimap"), CASW_VGUI_Ingame_Panel() { SetHiddenBits( HIDEHUD_PLAYERDEAD | HIDEHUD_REMOTE_TURRET); vgui::HScheme scheme = vgui::scheme()->LoadSchemeFromFile("resource/SwarmSchemeNew.res", "SwarmSchemeNew"); SetScheme(scheme); m_pLinePanel = new CASWHudMinimapLinePanel(this, "CASWHudMinimapLinePanel", this); //m_pFramePanel = new CASWHudMinimapFramePanel(this, "CASWHudMinimapFramePanel"); m_nWhiteTexture = vgui::surface()->CreateNewTextureID(); vgui::surface()->DrawSetTextureFile( m_nWhiteTexture, "vgui/white" , true, false); m_pScanLinePanel = new ScanLinePanel(this, "ScanlinePanel", false); m_pInterlacePanel = new vgui::ImagePanel(this, "InterlacePanel"); m_pNoisePanel = new vgui::ImagePanel(this, "NoisePanel"); if ( asw_scanner_background.GetBool() ) { m_pBackdrop = new CASWHudMinimap_Border(GetParent(), "MapBackdrop", this); } else { m_pBackdrop = NULL; } if (m_pBackdrop) { m_pBackdrop->SetPaintBackgroundEnabled(true); m_pBackdrop->SetPaintBackgroundType(0); m_pBackdrop->SetBgColor(Color(0,0,0,asw_hud_alpha.GetInt())); MoveToFront(); } m_bHasOverview = false; m_szServerName[0] = '\0'; Q_snprintf(m_szMissionTitle, sizeof(m_szMissionTitle), ""); } CASWHudMinimap::~CASWHudMinimap() { if ( m_MapKeyValues ) m_MapKeyValues->deleteThis(); if (m_pLinePanel) m_pLinePanel->MarkForDeletion(); } void CASWHudMinimap::PerformLayout() { BaseClass::PerformLayout(); int wide, tall, x, y; GetBounds(x, y, wide, tall); int ox, oy; GetScaledOffset(ox, oy); wide *= asw_hud_scale.GetFloat(); tall *= asw_hud_scale.GetFloat(); m_iMapSize = wide * 0.7f; m_MapCornerInPanel.x = int(wide - m_iMapSize) + ox; m_MapCornerInPanel.y = int(tall - m_iMapSize) + oy; int black_border = m_iMapSize * 0.0455f; if (m_pBackdrop) { m_pBackdrop->SetBounds(x + m_MapCornerInPanel.x - black_border, y + m_MapCornerInPanel.y - black_border, m_iMapSize + black_border * 2 + 1, m_iMapSize + black_border * 2 + 1); m_pBackdrop->SetBgColor(Color(0,0,0,asw_hud_alpha.GetInt())); } m_pScanLinePanel->SetBounds(m_MapCornerInPanel.x, m_MapCornerInPanel.y, m_iMapSize, m_iMapSize); m_pInterlacePanel->SetBounds(m_MapCornerInPanel.x, m_MapCornerInPanel.y, m_iMapSize, m_iMapSize); m_pNoisePanel->SetBounds(m_MapCornerInPanel.x, m_MapCornerInPanel.y, m_iMapSize, m_iMapSize); } void CASWHudMinimap::Init() { gameeventmanager->AddListener(this, "game_newmap", false ); gameeventmanager->AddListener(this, "server_spawn", false); m_pMinimap = this; m_nMapTextureID = -1; m_bHasOverview = false; m_MapKeyValues = NULL; m_bDrawingMapLines = false; m_MapOrigin = Vector( 0, 0, 0 ); m_fMapScale = 1.0f; m_fLastMapLine = 0; m_fLastBlipSpeechTime = -100.0f; m_fLastBlipHitTime = 0.0f; m_MapCentre = Vector2D( 0, 0 ); m_MapCentreInPanel = Vector2D( 0, 0 ); Reset(); usermessages->HookMessage( "ASWMapLine", MsgFunc_ASWMapLine ); } void CASWHudMinimap::Reset() { SetLabelText(L" "); m_bDrawingMapLines = false; m_fLastMapLine = 0; m_fLastMinimapDrawSound = 0; SetShouldDisplayValue(false); } void CASWHudMinimap::VidInit() { Reset(); } void CASWHudMinimap::OnThink() { VPROF_BUDGET( "CASWHudMinimap::OnThink", VPROF_BUDGETGROUP_ASW_CLIENT ); if (m_pScanLinePanel) { m_pScanLinePanel->SetAlpha(asw_scanner_scanline_alpha.GetInt()); m_pScanLinePanel->m_bDouble = asw_scanner_scanline_double.GetBool(); } if (m_pInterlacePanel) { m_pInterlacePanel->SetAlpha(asw_scanner_interlace_alpha.GetInt()); } // remove any map lines that have faded out for (int i=0;i<m_MapLines.Count();i++) { if (gpGlobals->curtime - m_MapLines[i].created_time > MAP_LINE_SOLID_TIME + MAP_LINE_FADE_TIME) m_MapLines.Remove(i); } C_ASW_Player *local = C_ASW_Player::GetLocalASWPlayer(); if ( local ) { if (m_bDrawingMapLines && gpGlobals->curtime >= m_fLastMapLine + MAP_LINE_INTERVAL) { if (IsWithinMapBounds(m_iMouseX,m_iMouseY)) { int ox, oy; GetScaledOffset(ox, oy); SendMapLine(m_iMouseX + ox,m_iMouseY + oy,false); } else { m_bDrawingMapLines = false; } } C_ASW_Marine *marine = local->GetViewMarine(); if (marine) { if (m_pNoisePanel) { float fScannerNoise = g_pScannerNoise ? g_pScannerNoise->GetScannerNoiseAt(marine->GetAbsOrigin()) : 0; m_pNoisePanel->SetAlpha(float(asw_scanner_noise_alpha.GetInt()) * fScannerNoise); } } else { m_pNoisePanel->SetAlpha(0); } } } void CASWHudMinimap::ApplySchemeSettings(IScheme *pScheme) { BaseClass::ApplySchemeSettings(pScheme); SetBgColor(Color(255,255,255,0)); m_pInterlacePanel->SetImage("swarm/Computer/ComputerCameraBlack"); m_pInterlacePanel->SetShouldScaleImage(true); m_pNoisePanel->SetImage("swarm/Computer/TVNoise"); m_pNoisePanel->SetShouldScaleImage(true); } void CASWHudMinimapFramePanel::Paint() { VPROF_BUDGET( "CASWHudMinimapFramePanel::Paint", VPROF_BUDGETGROUP_ASW_CLIENT ); if (ASWGameRules()) { if (ASWGameRules()->IsIntroMap() || ASWGameRules()->IsOutroMap()) return; } CASWHudMinimap *m_pMap = dynamic_cast<CASWHudMinimap*>(GetParent()); if ( !m_pMap || !asw_draw_hud.GetBool() ) return; int x, y, wide, tall; m_pMap->GetBounds(x,y,wide,tall); wide *= asw_hud_scale.GetFloat(); tall *= asw_hud_scale.GetFloat(); int ox, oy; m_pMap->GetScaledOffset(ox, oy); SetPos(ox,oy); SetSize(wide, tall); //if ( m_pMap->m_nFrameTexture == -1 ) //return; //surface()->DrawSetColor(m_pMap->GetBgColor()); //surface()->DrawSetTexture(m_pMap->m_nFrameTexture); //surface()->DrawTexturedRect(0, 0, wide, tall); } void CASWHudMinimap::GetScaledOffset(int &ox, int &oy) { int wide, tall; GetSize(wide,tall); int scaled_wide = wide * asw_hud_scale.GetFloat(); int scaled_tall = tall * asw_hud_scale.GetFloat(); ox = wide - scaled_wide; oy = tall - scaled_tall; } void CASWHudMinimap::PaintMapSection() { int wide, tall; GetSize(wide,tall); wide *= asw_hud_scale.GetFloat(); tall *= asw_hud_scale.GetFloat(); int ox, oy; GetScaledOffset(ox, oy); m_iMapSize = wide * 0.7f; m_MapCornerInPanel.x = int(wide - m_iMapSize) + ox; m_MapCornerInPanel.y = int(tall - m_iMapSize) + oy; m_MapCentreInPanel.x = m_MapCornerInPanel.x + m_iMapSize * 0.5f; m_MapCentreInPanel.y = m_MapCornerInPanel.y + m_iMapSize * 0.5f; m_pLinePanel->SetBounds(m_MapCornerInPanel.x, m_MapCornerInPanel.y, m_MapCornerInPanel.x + m_iMapSize, m_MapCornerInPanel.y + m_iMapSize); C_ASW_Player *local = C_ASW_Player::GetLocalASWPlayer(); if ( local ) { C_ASW_Marine *marine = local->GetViewMarine(); if (marine) { m_MapCentre = WorldToMapTexture(marine->GetAbsOrigin()); //Msg("Centering minimap at %f,%f\n", m_MapCentre.x, m_MapCentre.y); if ( m_nMapTextureID == -1 ) return; // source should be a fixed number of world units around the centre float source_size = asw_map_range.GetFloat() * ASW_SCREENSHOT_SCALE / m_fMapScale; int map_left = m_MapCornerInPanel.x; int map_right = wide + ox; int map_top = m_MapCornerInPanel.y; int map_bottom = tall + oy; if (m_bHasOverview) // draw a section of the minimap { float Source1X = m_MapCentre.x - source_size; float Source1Y = m_MapCentre.y - source_size; float Source2X = m_MapCentre.x + source_size; float Source2Y = m_MapCentre.y + source_size; // if we're off an edge of the map texture, pull in our draw coords so we don't get stretching if (Source1X < 0) { map_left -= (Source1X / source_size) * (m_iMapSize * 0.5f); } if (Source2X > 1023) { map_right -= ((Source2X - 1023) / source_size) * (m_iMapSize * 0.5f); } if (Source1Y < 0) { map_top -= (Source1Y / source_size) * (m_iMapSize * 0.5f); } if (Source2Y > 1023) { map_bottom -= ((Source2Y - 1023) / source_size) * (m_iMapSize * 0.5f); } // clamp uvs Source1X = MAX(0, Source1X); Source1Y = MAX(0, Source1Y); Source2X = MIN(1024, Source2X); Source2Y = MIN(1024, Source2Y); surface()->DrawSetColor(Color(255,255,255,255)); surface()->DrawSetTexture(m_nMapTextureID); Vertex_t points[4] = { Vertex_t( Vector2D(map_left, map_top), Vector2D(Source1X/1024.0f,Source1Y/1024.0f) ), Vertex_t( Vector2D(map_right, map_top), Vector2D(Source2X/1024.0f,Source1Y/1024.0f) ), Vertex_t( Vector2D(map_right, map_bottom), Vector2D(Source2X/1024.0f,Source2Y/1024.0f) ), Vertex_t( Vector2D(map_left, map_bottom), Vector2D(Source1X/1024.0f,Source2Y/1024.0f) ) }; surface()->DrawTexturedPolygon( 4, points ); } else { // no overview, we're just drawing our scanner texture surface()->DrawSetColor(Color(255,255,255,255)); surface()->DrawSetTexture(m_nMapTextureID); Vertex_t points[4] = { Vertex_t( Vector2D(map_left, map_top), Vector2D(0,0) ), Vertex_t( Vector2D(map_right, map_top), Vector2D(1,0) ), Vertex_t( Vector2D(map_right, map_bottom), Vector2D(1,1) ), Vertex_t( Vector2D(map_left, map_bottom), Vector2D(0,1) ) }; surface()->DrawTexturedPolygon( 4, points ); } } } } void CASWHudMinimap::Paint() { VPROF_BUDGET( "CASWHudMinimap::Paint", VPROF_BUDGETGROUP_ASW_CLIENT ); BaseClass::Paint(); PaintMapSection(); PaintObjectiveMarkers(); if (ASWGameRules() && ASWGameRules()->GetGameState() == ASW_GS_INGAME) { // hack to make our child panel draw the follow lines underneath the marine blips painted by this panel if (m_pLinePanel) { vgui::VPANEL vpanel = m_pLinePanel->GetVPanel(); vgui::surface()->PushMakeCurrent( vpanel, true ); m_pLinePanel->PaintFollowLines(); vgui::surface()->PopMakeCurrent( vpanel ); } PaintBlips(); } else { C_ASW_Game_Resource* pGameResource = ASWGameResource(); if (!pGameResource) return; C_ASW_Scanner_Info* pScanner = pGameResource->GetScannerInfo(); if (!pScanner) return; // fade blips out pScanner->CopyServerBlips(); pScanner->FadeBlips(); } //PaintFrame(); } void CASWHudMinimap::PaintObjectiveMarkers() { const int nMaxMarks = 3; ObjectiveMapMark *(pMarks[ nMaxMarks ]); float fMarkDistances[ nMaxMarks ]; int nMarks = 0; for ( int nObjective = 0; nObjective < ASW_MAX_OBJECTIVES; ++nObjective ) { C_ASW_Objective *pObjective = ASWGameResource()->GetObjective( nObjective ); if ( pObjective ) { if ( pObjective->IsObjectiveComplete() || pObjective->IsObjectiveFailed() || pObjective->IsObjectiveHidden() || pObjective->IsObjectiveDummy() ) { continue; } int iNumMapMarks = pObjective->GetMapMarkingsCount(); ObjectiveMapMark *m_pMapMarks = pObjective->GetMapMarkings(); for ( int i = 0; i < iNumMapMarks; ++i ) { if ( m_pMapMarks[ i ].bComplete || !m_pMapMarks[ i ].bEnabled ) { // Don't draw completed or hidden ones continue; } float fDist = m_MapCentre.DistTo( Vector2D( m_pMapMarks[ i ].x + m_pMapMarks[ i ].w / 2, m_pMapMarks[ i ].y + m_pMapMarks[ i ].h / 2 ) ); if ( nMarks < nMaxMarks ) { pMarks[ nMarks ] = &( m_pMapMarks[ i ] ); fMarkDistances[ nMarks ] = fDist; ++nMarks; } else { int nFarthest = 0; float fFarthestDist = fMarkDistances[ 0 ]; for ( int nMark = 1; nMark < nMarks; ++nMark ) { if ( fFarthestDist < fMarkDistances[ nMark ] ) { fFarthestDist = fMarkDistances[ nMark ]; nFarthest = nMark; } } if ( fDist < fMarkDistances[ nFarthest ] ) { pMarks[ nFarthest ] = &( m_pMapMarks[ i ] ); fMarkDistances[ nFarthest ] = fDist; } } } } } int nAlpha = 50.0f + 100.0f * ( sinf( gpGlobals->curtime * 5.0f ) + 2.0f ) * 0.5f; for ( int nMark = 0; nMark < nMarks; ++nMark ) { PaintRect( pMarks[ nMark ]->x, pMarks[ nMark ]->y, pMarks[ nMark ]->w, pMarks[ nMark ]->h, Color( 230, 192, 0, nAlpha ) ); } } void CASWHudMinimap::PaintBlips() { PaintMarineBlips(); PaintScannerBlips(); } void CASWHudMinimap::PaintScannerBlips() { C_ASW_Game_Resource* pGameResource = ASWGameResource(); if (!pGameResource) return; C_ASW_Scanner_Info* pScanner = pGameResource->GetScannerInfo(); if (!pScanner) return; // draw blips blindly from server for now pScanner->CopyServerBlips(); pScanner->FadeBlips(); Color red(250,110,110,255); Color blue(66,142,192,255); Color white(255,255,255,255); for (int i=0;i<ASW_SCANNER_MAX_BLIPS;i++) //todo: draw overflow blips { if (pScanner->m_ClientBlipIndex[i] != 0) { Vector vecWorldPos(0,0,0); C_BaseEntity* pClientEnt = C_BaseEntity::Instance(pScanner->m_ClientBlipIndex[i]); if (pClientEnt) { vecWorldPos.x = pClientEnt->GetAbsOrigin().x; vecWorldPos.y = pClientEnt->GetAbsOrigin().y; } else { vecWorldPos.x = pScanner->m_fClientBlipX[i]; vecWorldPos.y = pScanner->m_fClientBlipY[i]; } //float f = abs(0.5f - pScanner->m_fBlipStrength[i]) * 2.0f; // fade in/out float f = 1.0f - pScanner->m_fBlipStrength[i]; // just fade out PaintWorldBlip( vecWorldPos, f, ( pScanner->m_BlipType[i] == 1 ) ? blue : ( asw_scanner_classic.GetBool() ? white : red ), MapBlipTexture_t( pScanner->m_BlipType[ i ] ) ); // draw the blip in blue triangle if it's a computer/button panel } } } // paints the scanner ring and strengthens any blips the ring passes #define ASW_SCANNER_MAX_SOUND_DIST 1324 void CASWHudMinimapLinePanel::PaintScannerRing() { // skip scanner ring if we're not ingame if (!ASWGameRules() || ASWGameRules()->GetGameState() != ASW_GS_INGAME) return; if (m_nScannerRingTexture == -1) return; C_ASW_Player* pPlayer = C_ASW_Player::GetLocalASWPlayer(); if (!pPlayer) return; C_ASW_Game_Resource* pGameResource = ASWGameResource(); if (!pGameResource) return; C_ASW_Scanner_Info* pScanner = pGameResource->GetScannerInfo(); if (!pScanner) return; // each tech marine has his own time and ring, so go through them for (int i=0;i<pGameResource->GetMaxMarineResources();i++) { C_ASW_Marine_Resource* pMR = pGameResource->GetMarineResource(i); if (pMR && pMR->GetProfile() && pMR->GetProfile()->CanScanner() && pMR->GetMarineEntity() && pMR->GetHealthPercent() > 0) { bool bCheckRing = (pMR->m_fScannerTime <= 1.0f); pMR->m_fScannerTime += gpGlobals->frametime * 2.2f; if (bCheckRing) { float fScannerRangeWorldUnits = MarineSkills()->GetSkillBasedValueByMarineResource(pMR, ASW_MARINE_SKILL_SCANNER); // asw_scanner_range.GetFloat() float scanner_range = m_pMap->WorldDistanceToPixelDistance(fScannerRangeWorldUnits) * pMR->m_fScannerTime * asw_scanner_ring_scale.GetFloat(); Vector2D marine_pos(0,0); Vector marine_world_pos = pMR->GetMarineEntity()->GetAbsOrigin(); // check for refreshing the strength of any blips the ring just passed float ring_world_distance = fScannerRangeWorldUnits * MIN(pMR->m_fScannerTime, 1.0f) * asw_scanner_ring_scale.GetFloat(); float ring_world_distance_sq = ring_world_distance * ring_world_distance; // square it to save doing any square roots below for (int k=0;k<ASW_SCANNER_MAX_BLIPS;k++) { if (pScanner->m_ClientBlipIndex[k] != 0 && pScanner->m_fBlipStrength[k]==0) { float xdiff = pScanner->m_fClientBlipX[k] - marine_world_pos.x; float ydiff = pScanner->m_fClientBlipY[k] - marine_world_pos.y; float dist = xdiff * xdiff + ydiff * ydiff; if (dist < ring_world_distance_sq) { // our ring is outside this dot, so refresh it pScanner->m_fBlipStrength[k] = 1.0f; // check for making the first blip sound if (!pMR->m_bPlayedBlipSound && pScanner->m_BlipType[k] != 1) // don't blip on computers/buttons { pMR->m_bPlayedBlipSound = true; CLocalPlayerFilter filter; EmitSound_t ep; ep.m_nChannel = CHAN_AUTO; static char szWarningSound[32]; Q_snprintf(szWarningSound, sizeof(szWarningSound), "ASWScanner.Warning%d", asw_scanner_warning_sound.GetInt()); ep.m_pSoundName = szWarningSound; ep.m_flVolume = asw_scanner_warning_volume.GetFloat(); ep.m_SoundLevel = SNDLVL_NORM; ep.m_nFlags |= SND_CHANGE_PITCH; ep.m_nFlags |= SND_CHANGE_VOL; float max_ring_dist = fScannerRangeWorldUnits * asw_scanner_ring_scale.GetFloat(); if (max_ring_dist <= 0) ep.m_nPitch = 1.0f * 100.0f; else { float fPitchScale = (asw_scanner_pitch_base.GetFloat() - asw_scanner_pitch_change.GetFloat() * (sqrt(dist)/max_ring_dist)); ep.m_nPitch = fPitchScale * 100.0f; } //Msg("Pitch is = %d\n", ep.m_nPitch); // adjust volume by distance to tech marine if (pPlayer->GetViewMarine()) { float dist_to_tech = pPlayer->GetViewMarine()->GetAbsOrigin().DistTo(marine_world_pos); float fraction = dist_to_tech / ASW_SCANNER_MAX_SOUND_DIST; if (fraction > 0.3f) // give a buffer of max volume ep.m_flVolume *= (1.0f - ((fraction-0.3f)*0.7f)); } if (ep.m_flVolume>0) { m_pMap->m_fLastBlipHitTime = gpGlobals->curtime; C_BaseEntity::EmitSound( filter, -1 /*SOUND_FROM_LOCAL_PLAYER*/, ep); // if the tech is ours, then check for saying something about the incoming aliens if (pPlayer->entindex() == pMR->GetCommanderIndex() && m_pMap && pScanner->m_BlipType[k] == 0) // only do the speech when it's an alien, not a door { //Msg("client checking blip speech %d\n", i); m_pMap->CheckBlipSpeech(i); } } } } } } if ( pMR->m_fScannerTime <= 1.0f && ( gpGlobals->curtime < m_pMap->m_fLastBlipHitTime + 3.0f || asw_scanner_classic.GetBool() ) ) { // fade the ring out at the ends if (pMR->m_fScannerTime < 0.5f) surface()->DrawSetColor(Color(255,255,255,255)); else { float f = (1.0f - pMR->m_fScannerTime) * 2; surface()->DrawSetColor(Color(255,255,255,255.0f * f)); } surface()->DrawSetTexture(m_nScannerRingTexture); marine_pos = m_pMap->WorldToMapTexture(marine_world_pos); float ring_center_x = 0; float ring_center_y = 0; TextureToLinePanel(m_pMap, marine_pos, ring_center_x, ring_center_y); Vertex_t points[4] = { Vertex_t( Vector2D(ring_center_x - scanner_range, ring_center_y - scanner_range), Vector2D(0,0) ), Vertex_t( Vector2D(ring_center_x + scanner_range, ring_center_y - scanner_range), Vector2D(1,0) ), Vertex_t( Vector2D(ring_center_x + scanner_range, ring_center_y + scanner_range), Vector2D(1,1) ), Vertex_t( Vector2D(ring_center_x - scanner_range, ring_center_y + scanner_range), Vector2D(0,1) ) }; surface()->DrawTexturedPolygon( 4, points ); } } // check for resetting the ring to center again if (pMR->m_fScannerTime > 2.2f) { // play idle sound pMR->m_iScannerSoundSkip++; //if ((pMR->m_iScannerSoundSkip % 4) == 0) { if (asw_debug_scanner_sound.GetBool()) Msg("%f: Playing scanner sound! (not mod 4).\n", gpGlobals->curtime); pMR->m_iScannerSoundSkip = 0; if ( asw_scanner_classic.GetBool() || gpGlobals->curtime < m_pMap->m_fLastBlipHitTime + 3.0f ) { CLocalPlayerFilter filter; EmitSound_t ep; ep.m_nChannel = CHAN_AUTO; static char szIdleSound[32]; Q_snprintf(szIdleSound, sizeof(szIdleSound), "ASWScanner.Idle%d", asw_scanner_idle_sound.GetInt()); ep.m_pSoundName = szIdleSound; ep.m_flVolume = asw_scanner_idle_volume.GetFloat(); ep.m_nFlags |= SND_CHANGE_VOL; ep.m_SoundLevel = SNDLVL_NORM; // adjust volume by distance to tech marine if (pPlayer->GetViewMarine()) { float dist_to_tech = pPlayer->GetViewMarine()->GetAbsOrigin().DistTo(pMR->GetMarineEntity()->GetAbsOrigin()); float fraction = dist_to_tech / ASW_SCANNER_MAX_SOUND_DIST; if (fraction > 0.3f) // give a buffer of max volume ep.m_flVolume *= (1.0f - ((fraction-0.3f)*0.7f)); } if (ep.m_flVolume > 0) { if (asw_debug_scanner_sound.GetBool()) Msg("emitting scanner idle sound with volume %f\n", ep.m_flVolume); C_BaseEntity::StopSound( -1, ep.m_pSoundName ); C_BaseEntity::EmitSound( filter, -1 /*SOUND_FROM_LOCAL_PLAYER*/, ep ); } } } pMR->m_bPlayedBlipSound = false; //todo: what effect does this have with multi tech marines? pMR->m_fScannerTime = 0; } } } } void CASWHudMinimapLinePanel::Paint() { //CASWHudMinimap *m_pMap = dynamic_cast<CASWHudMinimap*>(GetParent()); if (!m_pMap) return; if (!ASWGameRules() && ASWGameRules()->GetGameState() < ASW_GS_INGAME) return; // paint a black outline over the lines for (int i=0;i<m_pMap->m_MapLines.Count();i++) { float x,y; if (!m_pMap->m_MapLines[i].bSetBlipCentre) { Vector vecBlipPos; vecBlipPos.x = m_pMap->m_MapLines[i].worldpos.x; vecBlipPos.y = m_pMap->m_MapLines[i].worldpos.y; vecBlipPos.z = 0; m_pMap->m_MapLines[i].blipcentre = m_pMap->WorldToMapTexture(vecBlipPos); m_pMap->m_MapLines[i].bSetBlipCentre = true; } Vector2D vecBlipCentre = m_pMap->m_MapLines[i].blipcentre; TextureToLinePanel(m_pMap, vecBlipCentre, x, y); if (m_pMap->m_MapLines[i].bLink) { bool bFound = false; if (i>1) { for (int k=i-1; k>0; k--) // find the previous line from this player, if any { if (m_pMap->m_MapLines[i].player_index == m_pMap->m_MapLines[k].player_index) { m_pMap->m_MapLines[i].linkpos = m_pMap->m_MapLines[k].worldpos; bFound = true; break; } } } if (bFound) { float x2,y2; if (!m_pMap->m_MapLines[i].bSetLinkBlipCentre) { Vector vecBlipPos2; vecBlipPos2.x = m_pMap->m_MapLines[i].linkpos.x; vecBlipPos2.y = m_pMap->m_MapLines[i].linkpos.y; vecBlipPos2.z = 0; m_pMap->m_MapLines[i].linkblipcentre = m_pMap->WorldToMapTexture(vecBlipPos2); m_pMap->m_MapLines[i].bSetLinkBlipCentre = true; } Vector2D vecBlipCentre2 = m_pMap->m_MapLines[i].linkblipcentre; TextureToLinePanel(m_pMap, vecBlipCentre2, x2, y2); float t = gpGlobals->curtime - m_pMap->m_MapLines[i].created_time; int alpha = 255; if (t < MAP_LINE_SOLID_TIME) { } else if (t < MAP_LINE_SOLID_TIME + MAP_LINE_FADE_TIME) { alpha = 255 - ((t - MAP_LINE_SOLID_TIME) / MAP_LINE_FADE_TIME) * 255.0f; } else { continue; } surface()->DrawSetTexture(m_pMap->m_nWhiteTexture); vgui::Vertex_t start, end; // draw black outline around the line to give it some softness surface()->DrawSetColor(Color(0,0,0, alpha)); start.Init(Vector2D(x - 1.50f,y - 1.50f), Vector2D(0,0)); end.Init(Vector2D(x2 - 1.50f,y2 - 1.50f), Vector2D(1,1)); SoftLine::DrawPolygonLine(start, end); start.Init(Vector2D(x + 1.50f,y - 1.50f), Vector2D(0,0)); end.Init(Vector2D(x2 + 1.50f,y2 - 1.50f), Vector2D(1,1)); SoftLine::DrawPolygonLine(start, end); start.Init(Vector2D(x - 1.50f,y + 1.50f), Vector2D(0,0)); end.Init(Vector2D(x2 - 1.50f,y2 + 1.50f), Vector2D(1,1)); SoftLine::DrawPolygonLine(start, end); start.Init(Vector2D(x + 1.50f,y + 1.50f), Vector2D(0,0)); end.Init(Vector2D(x2 + 1.50f,y2 + 1.50f), Vector2D(1,1)); SoftLine::DrawPolygonLine(start, end); } } } // paint map line dots for (int i=0;i<m_pMap->m_MapLines.Count();i++) { //m_pMap->PaintWorldBlip(vecBlipPos, 0.5f, Color(0,255,0,255)); float x,y; if (!m_pMap->m_MapLines[i].bSetBlipCentre) { Vector vecBlipPos; vecBlipPos.x = m_pMap->m_MapLines[i].worldpos.x; vecBlipPos.y = m_pMap->m_MapLines[i].worldpos.y; vecBlipPos.z = 0; m_pMap->m_MapLines[i].blipcentre = m_pMap->WorldToMapTexture(vecBlipPos); m_pMap->m_MapLines[i].bSetBlipCentre = true; } Vector2D vecBlipCentre = m_pMap->m_MapLines[i].blipcentre; TextureToLinePanel(m_pMap, vecBlipCentre, x, y); if (m_pMap->m_MapLines[i].bLink) { bool bFound = false; if (i>1) { for (int k=i-1; k>0; k--) // find the previous line from this player, if any { if (m_pMap->m_MapLines[i].player_index == m_pMap->m_MapLines[k].player_index) { m_pMap->m_MapLines[i].linkpos = m_pMap->m_MapLines[k].worldpos; bFound = true; break; } } } if (bFound) { float x2,y2; if (!m_pMap->m_MapLines[i].bSetLinkBlipCentre) { Vector vecBlipPos2; vecBlipPos2.x = m_pMap->m_MapLines[i].linkpos.x; vecBlipPos2.y = m_pMap->m_MapLines[i].linkpos.y; vecBlipPos2.z = 0; m_pMap->m_MapLines[i].linkblipcentre = m_pMap->WorldToMapTexture(vecBlipPos2); m_pMap->m_MapLines[i].bSetLinkBlipCentre = true; } Vector2D vecBlipCentre2 = m_pMap->m_MapLines[i].linkblipcentre; TextureToLinePanel(m_pMap, vecBlipCentre2, x2, y2); float t = gpGlobals->curtime - m_pMap->m_MapLines[i].created_time; int alpha = 255; if (t < MAP_LINE_SOLID_TIME) { //surface()->DrawSetColor(Color(255,255,255,255)); //surface()->DrawLine(x,y,x2,y2); } else if (t < MAP_LINE_SOLID_TIME + MAP_LINE_FADE_TIME) { alpha = 255 - ((t - MAP_LINE_SOLID_TIME) / MAP_LINE_FADE_TIME) * 255.0f; } else { continue; } surface()->DrawSetTexture(m_pMap->m_nWhiteTexture); vgui::Vertex_t start, end; const Color &playerColor = g_rgbaStatsReportPlayerColors[m_pMap->m_MapLines[i].player_index]; // draw main line surface()->DrawSetColor(Color(playerColor.r(), playerColor.g(), playerColor.b(), 0.5f * alpha)); //surface()->DrawLine(x,y,x2,y2); start.Init(Vector2D(x,y), Vector2D(0,0)); end.Init(Vector2D(x2,y2), Vector2D(1,1)); SoftLine::DrawPolygonLine(start, end); // draw translucent ones around it to give it some softness surface()->DrawSetColor(Color(playerColor.r(), playerColor.g(), playerColor.b(), 0.5f * alpha)); start.Init(Vector2D(x - 0.50f,y - 0.50f), Vector2D(0,0)); end.Init(Vector2D(x2 - 0.50f,y2 - 0.50f), Vector2D(1,1)); SoftLine::DrawPolygonLine(start, end); start.Init(Vector2D(x + 0.50f,y - 0.50f), Vector2D(0,0)); end.Init(Vector2D(x2 + 0.50f,y2 - 0.50f), Vector2D(1,1)); SoftLine::DrawPolygonLine(start, end); start.Init(Vector2D(x - 0.50f,y + 0.50f), Vector2D(0,0)); end.Init(Vector2D(x2 - 0.50f,y2 + 0.50f), Vector2D(1,1)); SoftLine::DrawPolygonLine(start, end); start.Init(Vector2D(x + 0.50f,y + 0.50f), Vector2D(0,0)); end.Init(Vector2D(x2 + 0.50f,y2 + 0.50f), Vector2D(1,1)); SoftLine::DrawPolygonLine(start, end); } } } // paint the frame over the top //int wide, tall; //m_pMap->GetSize(wide,tall); //if ( m_pMap->m_nFrameTexture == -1 ) //return; //surface()->DrawSetColor(m_pMap->GetBgColor()); //surface()->DrawSetTexture(m_pMap->m_nFrameTexture); //surface()->DrawTexturedRect(-20, -20, wide, tall); //surface()->DrawTexturedSubRect(0, 0, wide, tall,); //-m_pMap->m_MapCornerInPanel.x*2, -m_pMap->m_MapCornerInPanel.y*2, wide, tall); //surface()->DrawTexturedSubRect(m_MapCornerInPanel.x, m_MapCornerInPanel.y, wide, tall, //Source1X/1024.0, Source1Y/1024.0, Source2X/1024.0, Source2Y/1024.0); PaintScannerRing(); } void CASWHudMinimapLinePanel::PaintFollowLines() { C_ASW_Game_Resource* pGameResource = ASWGameResource(); if (!pGameResource) return; // paint follow lines for (int i=0;i<ASW_MAX_MARINE_RESOURCES;i++) { C_ASW_Marine_Resource* pMR = pGameResource->GetMarineResource(i); if (pMR && pMR->GetMarineEntity()) { C_ASW_Marine* pMarine = pMR->GetMarineEntity(); if (pMarine && pMarine->m_hMarineFollowTarget && !pMarine->IsInhabited()) { PaintFollowLine(pMarine, pMarine->m_hMarineFollowTarget); } } } } void CASWHudMinimap::PaintRect( int nX, int nY, int nWidth, int nHeight, Color color ) { Vector2D rectCorner1; Vector2D rectCorner2; rectCorner1.x = nX; rectCorner1.y = nY; rectCorner2.x = nX + nWidth; rectCorner2.y = nY + nHeight; rectCorner1 = MapTextureToPanel( rectCorner1 ); rectCorner2 = MapTextureToPanel( rectCorner2 ); if ( rectCorner1.x > m_MapCornerInPanel.x + m_iMapSize || rectCorner1.y > m_MapCornerInPanel.y + m_iMapSize || rectCorner2.x < m_MapCornerInPanel.x || rectCorner2.y < m_MapCornerInPanel.y ) { // Out of bounds Vector2D vArrowCenter = Vector2D( ( rectCorner1.x + rectCorner2.x ) / 2, ( rectCorner1.y + rectCorner2.y ) / 2 ); Vector2D vPanelCenter = Vector2D( m_MapCornerInPanel.x + m_iMapSize / 2, m_MapCornerInPanel.y + m_iMapSize / 2 ); Vector2D vDirection = vArrowCenter - vPanelCenter; Vector2DNormalize( vDirection ); float fFacingYaw = RAD2DEG( atanf( vDirection.y / vDirection.x ) ) - ( vDirection.x < 0.0f ? 0.0f : 180.0f ); int iFacingSize = GetWide() * 0.05f * asw_hud_scale.GetFloat(); vArrowCenter.x = clamp( vArrowCenter.x, m_MapCornerInPanel.x, m_MapCornerInPanel.x + m_iMapSize - iFacingSize / 2 ); vArrowCenter.y = clamp( vArrowCenter.y, m_MapCornerInPanel.y, m_MapCornerInPanel.y + m_iMapSize - iFacingSize / 2 ); vArrowCenter -= vDirection * 4.0f * ( sinf( gpGlobals->curtime * 7.0f ) + 1.0f ); // set up a square to the right int xoffset = -2; // temp? to make the arc look nice next to blips.. int yoffset = 1; Vector vecCornerTL(xoffset, iFacingSize * -0.5f + yoffset, 0); Vector vecCornerTR(iFacingSize + xoffset, iFacingSize * -0.5f+ yoffset, 0); Vector vecCornerBR(iFacingSize + xoffset, iFacingSize * 0.5f+ yoffset, 0); Vector vecCornerBL(xoffset, iFacingSize * 0.5f+ yoffset, 0); Vector vecCornerTL_rotated, vecCornerTR_rotated, vecCornerBL_rotated, vecCornerBR_rotated; // rotate it by our facing yaw QAngle angFacing( 0, fFacingYaw, 0 ); VectorRotate(vecCornerTL, angFacing, vecCornerTL_rotated); VectorRotate(vecCornerTR, angFacing, vecCornerTR_rotated); VectorRotate(vecCornerBR, angFacing, vecCornerBR_rotated); VectorRotate(vecCornerBL, angFacing, vecCornerBL_rotated); surface()->DrawSetColor( color ); surface()->DrawSetTexture(m_nFacingArcTexture); //surface()->DrawTexturedRect(Dest1X,Dest1Y,Dest2X,Dest2Y); Vertex_t points[4] = { Vertex_t( Vector2D(vArrowCenter.x + vecCornerTL_rotated.x, vArrowCenter.y + vecCornerTL_rotated.y), Vector2D(0,0) ), Vertex_t( Vector2D(vArrowCenter.x + vecCornerTR_rotated.x, vArrowCenter.y + vecCornerTR_rotated.y), Vector2D(1,0) ), Vertex_t( Vector2D(vArrowCenter.x + vecCornerBR_rotated.x, vArrowCenter.y + vecCornerBR_rotated.y), Vector2D(1,1) ), Vertex_t( Vector2D(vArrowCenter.x + vecCornerBL_rotated.x, vArrowCenter.y + vecCornerBL_rotated.y), Vector2D(0,1) ) }; surface()->DrawTexturedPolygon( 4, points ); } else { rectCorner1.x = MAX( rectCorner1.x, m_MapCornerInPanel.x ); rectCorner1.y = MAX( rectCorner1.y, m_MapCornerInPanel.y ); rectCorner2.x = MIN( rectCorner2.x, m_MapCornerInPanel.x + m_iMapSize ); rectCorner2.y = MIN( rectCorner2.y, m_MapCornerInPanel.y + m_iMapSize ); surface()->DrawSetColor( color ); surface()->DrawOutlinedRect( rectCorner1.x, rectCorner1.y, rectCorner2.x, rectCorner2.y ); color[ 3 ] /= 8; surface()->DrawSetColor( color ); surface()->DrawFilledRect( rectCorner1.x, rectCorner1.y, rectCorner2.x, rectCorner2.y ); } } // fixme: blips should be sent from the server.. per player? // so as to be sent information about things you can't see (i.e. to give the tracker some range) // change networking to send entities to players if they're near his current marine // (and perhaps near any he's controlling?) // then we can send blips from server->client only if they're outside this range // these blips will be static // we'll also drops blips of every alien/marine entity the client knows about, these can move //void CASWHudMinimap::CreateBlips() //{ //m_iNumBlips = 0; //#define MAX_BLIPS 64 //int m_iBlipX[MAX_BLIPS]; //int m_iBlipY[MAX_BLIPS]; //int m_iNumBlips; //} float CASWHudMinimap::WorldDistanceToPixelDistance(float fWorldDistance) { // convert to texture scale float result = fWorldDistance / m_fMapScale; result *= ASW_SCREENSHOT_SCALE; // find how many pixels on the texture correspond to the map panel halfwidth: float source_size = asw_map_range.GetFloat() * ASW_SCREENSHOT_SCALE / m_fMapScale; // find what fraction our offset is compared to the full texture width of the map: result /= source_size; // multiply that out by the pixel halfwidth of this panel: result *= (m_iMapSize * 0.5f); return result; } // loads in the script file for a particular map to set scale/origin void CASWHudMinimap::SetMap(const char * levelname) { // load new KeyValues //Msg("minimap SetMap: %s\n", levelname); if ( m_MapKeyValues && Q_strcmp( levelname, m_MapKeyValues->GetName() ) == 0 ) { return; // map didn't change } if ( m_MapKeyValues ) m_MapKeyValues->deleteThis(); m_MapKeyValues = new KeyValues( levelname ); char tempfile[MAX_PATH]; Q_snprintf( tempfile, sizeof( tempfile ), "resource/overviews/%s.txt", levelname ); if ( !m_MapKeyValues->LoadFromFile( filesystem, tempfile, "GAME" ) || !m_MapKeyValues->GetBool( "use_overview", true ) ) { //DevMsg( 1, "CASWHudMinimap::SetMap: couldn't load overview file for map %s.\n", levelname ); m_nMapTextureID = surface()->CreateNewTextureID(); surface()->DrawSetTextureFile( m_nMapTextureID, "vgui/swarm/hud/scanner", true, false); // put in some default numbers so the scanner works m_MapOrigin.x = 0; m_MapOrigin.y = 0; m_fMapScale = 25.0f; Q_snprintf(m_szMissionTitle, sizeof(m_szMissionTitle), m_MapKeyValues->GetString("missiontitle", "Unnamed Mission")); m_bHasOverview = false; return; } // TODO release old texture ? m_nMapTextureID = surface()->CreateNewTextureID(); //if we have not uploaded yet, lets go ahead and do so surface()->DrawSetTextureFile( m_nMapTextureID, m_MapKeyValues->GetString("material"), true, false); m_MapOrigin.x = m_MapKeyValues->GetInt("pos_x"); m_MapOrigin.y = m_MapKeyValues->GetInt("pos_y"); m_fMapScale = m_MapKeyValues->GetFloat("scale", 1.0f); Q_snprintf(m_szMissionTitle, sizeof(m_szMissionTitle),m_MapKeyValues->GetString("missiontitle")); m_bHasOverview = true; } void CASWHudMinimap::FireGameEvent( IGameEvent * event ) { const char * type = event->GetName(); //Msg("Minimap firegameevent %s\n", type); if ( Q_strcmp(type, "game_newmap") == 0 ) { SetMap( event->GetString("mapname") ); m_MapLines.RemoveAll(); m_fLastBlipSpeechTime = -100.0f; } else if ( Q_strcmp(type, "server_spawn") == 0 ) { const char *hostname = event->GetString( "hostname" ); Q_snprintf(m_szServerName, sizeof(m_szServerName), "%s", hostname); } CASW_HudElement::FireGameEvent(event); } bool CASWHudMinimap::MouseClick(int x, int y, bool bRightClick, bool bDown) { if (!ShouldDraw() || !asw_minimap_clicks.GetBool()) return false; if (!bDown) { m_bDrawingMapLines = false; return false; } if (bRightClick) return false; if (!IsWithinMapBounds(x,y)) return false; int ox, oy; GetScaledOffset(ox, oy); SendMapLine(x+ox,y+oy,true); m_bDrawingMapLines = true; return true; } bool CASWHudMinimap::IsWithinMapBounds(int x, int y) { //int wide, tall; int posx, posy; if (m_nMapTextureID == -1) return false; GetPos(posx,posy); //int ox, oy; //GetScaledOffset(ox, oy); //posx += ox; //posy += oy; //GetSize(wide,tall); //wide *= asw_hud_scale.GetFloat(); //tall *= asw_hud_scale.GetFloat(); x -= posx; y -= posy; return (x >= m_MapCornerInPanel.x && y >= m_MapCornerInPanel.y && x <= (m_MapCornerInPanel.x + m_iMapSize) && y <= (m_MapCornerInPanel.y + m_iMapSize)); } void CASWHudMinimap::ClipToMapBounds(int &x, int &y) { int wide, tall; int posx, posy; GetPos(posx,posy); int ox, oy; GetScaledOffset(ox, oy); posx += ox; posy += oy; GetSize(wide,tall); wide *= asw_hud_scale.GetFloat(); tall *= asw_hud_scale.GetFloat(); if (x > m_MapCornerInPanel.x + posx + wide) x = m_MapCornerInPanel.x + posx + wide; if (x < m_MapCornerInPanel.x + posx) x = m_MapCornerInPanel.x + posx; if (y > m_MapCornerInPanel.y + posy + tall) y = m_MapCornerInPanel.y + posy + tall; if (y < m_MapCornerInPanel.y + posy) y = m_MapCornerInPanel.y + posy; } // drawing a map line at point x and y on the hud element void CASWHudMinimap::SendMapLine(int x, int y, bool bInitial) { C_ASW_Player *local = C_ASW_Player::GetLocalASWPlayer(); if ( local ) { C_ASW_Marine *marine = local->GetMarine(); if (marine) { int wide, tall, posx, posy; GetSize(wide,tall); wide *= asw_hud_scale.GetFloat(); tall *= asw_hud_scale.GetFloat(); GetPos(posx, posy); int ox, oy; GetScaledOffset(ox, oy); posx += ox; posy += oy; x -= posx; y -= posy; Vector vecMapCentre = marine->GetAbsOrigin(); // pixel difference between where we clicked and the centre of the panel int diff_x = x - m_MapCentreInPanel.x; int diff_y = m_MapCentreInPanel.y - y; // find the world position we clicked on Vector vecMapLinePos; // world difference should be: ( diff_x / panel size ) * map range vecMapLinePos.x = vecMapCentre.x + (diff_x / (m_iMapSize*0.5f)) * asw_map_range.GetFloat(); vecMapLinePos.y = vecMapCentre.y + (diff_y / (m_iMapSize*0.5f)) * asw_map_range.GetFloat(); //vecMapLinePos.x = vecMapCentre.x + (diff_x * m_fMapScale / ASW_SCREENSHOT_SCALE); //vecMapLinePos.y = vecMapCentre.y + (diff_y * m_fMapScale / ASW_SCREENSHOT_SCALE); vecMapLinePos.z = marine->GetAbsOrigin().z; //Msg("vecMapCentre = %f %f\n", vecMapCentre.x, vecMapCentre.y); //Msg("VecMapLinePos = %f %f %f\n", vecMapLinePos.x, vecMapLinePos.y, vecMapLinePos.z); //FX_MicroExplosion(vecMapLinePos, Vector(0,0,1)); // notify the server of this! char buffer[64]; int linetype = bInitial ? 0 : 1; Q_snprintf(buffer, sizeof(buffer), "cl_mapline %d %d %d", linetype, (int) vecMapLinePos.x, (int) vecMapLinePos.y); engine->ClientCmd(buffer); m_fLastMapLine = gpGlobals->curtime; // short circuit add it to your own list MapLine line; line.player_index = local->entindex(); line.worldpos.x = (int) vecMapLinePos.x; line.worldpos.y = (int) vecMapLinePos.y; line.created_time = gpGlobals->curtime; if (linetype == 1) // links to a previous { line.bLink = true; } else { if (gpGlobals->curtime > m_fLastMinimapDrawSound + 5.0f) { CLocalPlayerFilter filter; C_BaseEntity::EmitSound( filter, -1, "ASWScanner.Drawing" ); m_fLastMinimapDrawSound = gpGlobals->curtime; } } m_MapLines.AddToTail(line); } } } // converts a coord from 0->1023 map texture into x+y in this panel Vector2D CASWHudMinimap::MapTextureToPanel( const Vector2D &texturepos ) { if ( !m_pMinimap ) { m_pMinimap = GET_HUDELEMENT( CASWHudMinimap ); if ( !m_pMinimap ) { return vec2_origin; } } Vector2D offset(texturepos); // find how many pixels on the texture correspond to the map panel halfwidth: float source_size = asw_map_range.GetFloat() * ASW_SCREENSHOT_SCALE / m_pMinimap->m_fMapScale; // convert our tex coords to an offset from the map pixel at the centre of the panel: offset -= m_pMinimap->m_MapCentre; // find what fraction our offset is compared to the full texture width of the map: offset /= source_size; // multiply that out by the pixel halfwidth of this panel: offset *= (GetMapSize() * 0.5f); offset += m_pMinimap->m_MapCentreInPanel; return offset; } int CASWHudMinimap::GetArcSize( void ) { return GetWidth() * 0.1f * asw_hud_scale.GetFloat(); } //void CASWHudMinimapLinePanel::TextureToLinePanel(CASWHudMinimap* pMap, const Vector &worldpos, int &x, int &y) // converts a 0->1024 map texture coord to the x/y in the panel coord void CASWHudMinimapLinePanel::TextureToLinePanel(CASWHudMinimap* pMap, const Vector2D &blip_centre, float &x, float &y) { if (!pMap) return; Vector2D result = pMap->MapTextureToPanel(blip_centre); int wx, wy; GetPos(wx,wy); int ox, oy; pMap->GetScaledOffset(ox, oy); //wx += ox; //wy += oy; x = result.x - wx; y = result.y - wy; //int w, t; //GetSize(w, t); //Vector2D blip_centre = pMap->WorldToMapTexture(worldpos); //float source_size = asw_map_range.GetFloat() * ASW_SCREENSHOT_SCALE / pMap->m_fMapScale; //x = blip_centre.x - pMap->m_MapCentre.x + source_size; //y = blip_centre.y - pMap->m_MapCentre.y + source_size; //x = blip_centre.x - pMap->m_MapCentre.x + pMap->m_iMapSize * 0.5f; //y = blip_centre.y - pMap->m_MapCentre.y + pMap->m_iMapSize * 0.5f; } bool CASWHudMinimap::UseDrawCrosshair(float x, float y) { C_ASW_Player *pPlayer = C_ASW_Player::GetLocalASWPlayer(); if (!pPlayer || !pPlayer->GetMarine() || !asw_minimap_clicks.GetBool()) return false; return IsWithinMapBounds(x,y); } void CASWHudMinimap::CheckBlipSpeech(int iMarine) { // check if it's been a while since we had any movement if (gpGlobals->curtime - m_fLastBlipSpeechTime > ASW_BLIP_SPEECH_INTERVAL) { C_ASW_Player *pPlayer = C_ASW_Player::GetLocalASWPlayer(); pPlayer->SendBlipSpeech(iMarine); } m_fLastBlipSpeechTime = gpGlobals->curtime; // bump the time to current evne if we didn't say anything, so we don't continually say movement when there are blips all the time } void CASWHudMinimapLinePanel::PaintFollowLine(C_BaseEntity *pMarine, C_BaseEntity *pTarget) { if (!pMarine || !pTarget) return; surface()->DrawSetTexture(m_pMap->m_nWhiteTexture); vgui::Vertex_t start, end; Vector2D startTexturePos = m_pMap->WorldToMapTexture(pMarine->GetAbsOrigin()); Vector2D endTexturePos = m_pMap->WorldToMapTexture(pTarget->GetAbsOrigin()); Vector2D start2D, end2D; TextureToLinePanel(m_pMap, startTexturePos, start2D.x, start2D.y); TextureToLinePanel(m_pMap, endTexturePos, end2D.x, end2D.y); //Vector2D start2D = m_pMap->MapTextureToPanel(startTexturePos); //Vector2D end2D = m_pMap->MapTextureToPanel(endTexturePos); float x, y, x2,y2; x = start2D.x; y = start2D.y; x2 = end2D.x; y2 = end2D.y; float alpha = 255; // draw black outline around the line to give it some softness surface()->DrawSetColor(Color(0,0,0, alpha)); start.Init(Vector2D(x - 1.50f,y - 1.50f), Vector2D(0,0)); end.Init(Vector2D(x2 - 1.50f,y2 - 1.50f), Vector2D(1,1)); SoftLine::DrawPolygonLine(start, end); start.Init(Vector2D(x + 1.50f,y - 1.50f), Vector2D(0,0)); end.Init(Vector2D(x2 + 1.50f,y2 - 1.50f), Vector2D(1,1)); SoftLine::DrawPolygonLine(start, end); start.Init(Vector2D(x - 1.50f,y + 1.50f), Vector2D(0,0)); end.Init(Vector2D(x2 - 1.50f,y2 + 1.50f), Vector2D(1,1)); SoftLine::DrawPolygonLine(start, end); start.Init(Vector2D(x + 1.50f,y + 1.50f), Vector2D(0,0)); end.Init(Vector2D(x2 + 1.50f,y2 + 1.50f), Vector2D(1,1)); SoftLine::DrawPolygonLine(start, end); // draw main line surface()->DrawSetColor(Color(255,0,0, 0.5f * alpha)); //surface()->DrawLine(x,y,x2,y2); start.Init(Vector2D(x,y), Vector2D(0,0)); end.Init(Vector2D(x2,y2), Vector2D(1,1)); SoftLine::DrawPolygonLine(start, end); // draw translucent ones around it to give it some softness surface()->DrawSetColor(Color(255,0,0, 0.5f * alpha)); start.Init(Vector2D(x - 0.50f,y - 0.50f), Vector2D(0,0)); end.Init(Vector2D(x2 - 0.50f,y2 - 0.50f), Vector2D(1,1)); SoftLine::DrawPolygonLine(start, end); start.Init(Vector2D(x + 0.50f,y - 0.50f), Vector2D(0,0)); end.Init(Vector2D(x2 + 0.50f,y2 - 0.50f), Vector2D(1,1)); SoftLine::DrawPolygonLine(start, end); start.Init(Vector2D(x - 0.50f,y + 0.50f), Vector2D(0,0)); end.Init(Vector2D(x2 - 0.50f,y2 + 0.50f), Vector2D(1,1)); SoftLine::DrawPolygonLine(start, end); start.Init(Vector2D(x + 0.50f,y + 0.50f), Vector2D(0,0)); end.Init(Vector2D(x2 + 0.50f,y2 + 0.50f), Vector2D(1,1)); SoftLine::DrawPolygonLine(start, end); } CASWHudMinimap_Border::CASWHudMinimap_Border(vgui::Panel *pParent, const char *pElementName, CASWHudMinimap *pMinimap) : vgui::Panel(pParent, pElementName) { m_pMinimap = pMinimap; } void CASWHudMinimap_Border::PaintBackground() { if (ASWGameRules()) { if (ASWGameRules()->IsIntroMap() || ASWGameRules()->IsOutroMap()) return; } if (m_pMinimap && !m_pMinimap->ShouldDraw()) return; if ( !asw_draw_hud.GetBool() || m_nBlackBarTexture == -1 ) { return; } if ( !asw_scanner_background.GetBool() ) return; //BaseClass::PaintBackground(); vgui::surface()->DrawSetColor(Color(255,255,255,asw_hud_alpha.GetInt())); vgui::surface()->DrawSetTexture(m_nBlackBarTexture); vgui::Vertex_t points[4] = { vgui::Vertex_t( Vector2D(0, 0), Vector2D(0,0) ), vgui::Vertex_t( Vector2D(GetWide(), 0), Vector2D(1,0) ), vgui::Vertex_t( Vector2D(GetWide(), GetTall()), Vector2D(1,1) ), vgui::Vertex_t( Vector2D(0, GetTall()), Vector2D(0,1) ) }; vgui::surface()->DrawTexturedPolygon( 4, points ); }
32.894464
185
0.697418
[ "vector" ]
3bc73386f4f9cbf688b43d3b36df6cfbf8be05be
1,925
cc
C++
face_detector.cc
ahmdrz/face
3e839b4b75572910564cb25fb776464e4a9d8c4b
[ "MIT" ]
2
2019-07-31T06:27:46.000Z
2020-05-03T10:31:28.000Z
face_detector.cc
ahmdrz/face
3e839b4b75572910564cb25fb776464e4a9d8c4b
[ "MIT" ]
null
null
null
face_detector.cc
ahmdrz/face
3e839b4b75572910564cb25fb776464e4a9d8c4b
[ "MIT" ]
null
null
null
#include <shared_mutex> #include <dlib/image_loader/image_loader.h> #include <dlib/image_processing/frontal_face_detector.h> #include "face_detector.h" #include "jpeg_mem_loader.h" using namespace dlib; static const size_t RECT_LEN = 4; static const size_t RECT_SIZE = RECT_LEN * sizeof(long); class FaceDetector { public: FaceDetector() { detector_ = get_frontal_face_detector(); } std::vector<rectangle> detect(const matrix<rgb_pixel> &img) { std::lock_guard<std::mutex> lock(detector_mutex_); std::vector<rectangle> rects = detector_(img); return std::move(rects); } private: std::mutex detector_mutex_; frontal_face_detector detector_; }; // Plain C interface for Go. facedetector *facedetector_init() { facedetector *rec = (facedetector *)calloc(1, sizeof(facedetector)); try { FaceDetector *cls = new FaceDetector(); rec->cls = (void *)cls; } catch (serialization_error &e) { rec->err_str = strdup(e.what()); rec->err_code = SERIALIZATION_ERROR; } catch (std::exception &e) { rec->err_str = strdup(e.what()); rec->err_code = UNKNOWN_ERROR; } return rec; } returnvalue* facedetector_detect(facedetector *det, const uint8_t* img_data, int len) { returnvalue* ret = (returnvalue*)calloc(1, sizeof(returnvalue)); FaceDetector* cls = (FaceDetector*)(det->cls); matrix<rgb_pixel> img; load_mem_jpeg(img, img_data, len); std::vector<rectangle> rects = cls->detect(img); int size = rects.size(); if (size == 0) { return ret; } ret->length = size; ret->rectangles = (long*)malloc(size * RECT_SIZE); for (int i = 0; i < size; i++) { long* dst = ret->rectangles + i * 4; dst[0] = rects[i].left(); dst[1] = rects[i].top(); dst[2] = rects[i].right(); dst[3] = rects[i].bottom(); } return ret; } void facedetector_free(facedetector *rec) { if (rec->cls) { FaceDetector *cls = (FaceDetector *)(rec->cls); delete cls; rec->cls = NULL; } free(rec); }
21.388889
85
0.685714
[ "vector" ]
3bca252fef13b0e12db6305279565daedef40b74
7,094
hpp
C++
SAX2HandlerMusicXML.hpp
adct-the-experimenter/MusicXML-to-hex
73edd406407333b4570f875bb349a71720ad698e
[ "BSD-3-Clause" ]
1
2019-06-04T03:45:52.000Z
2019-06-04T03:45:52.000Z
SAX2HandlerMusicXML.hpp
adct-the-experimenter/MusicXML-to-Hex
73edd406407333b4570f875bb349a71720ad698e
[ "BSD-3-Clause" ]
null
null
null
SAX2HandlerMusicXML.hpp
adct-the-experimenter/MusicXML-to-Hex
73edd406407333b4570f875bb349a71720ad698e
[ "BSD-3-Clause" ]
null
null
null
#ifndef SAX2HANDLERMUSICXML_H #define SAX2HANDLERMUSICXML_H #include <xercesc/sax2/ContentHandler.hpp> //header file for default handler which implements content & error handler #include <xercesc/sax2/Attributes.hpp> //attributes defintion #include <xercesc/sax/SAXParseException.hpp> #include <vector> //header for vector container class #include <sstream> //header for string stream processing #include <string> #include "note.h" #include <stack> using namespace xercesc; class SAX2HandlerMusicXML : public ContentHandler { public: /*Important Note: Instruments such as piano have more than 1 staff which means multiple note elements as being in staff 1 or staff 2. haha pun */ //constructor SAX2HandlerMusicXML(); //destructor ~SAX2HandlerMusicXML(); //function to pass vector of notes to SAX2HandlerMusicXML object void addPointerToNotes(std::vector<Note> &notesVec); //function to free pointer to vector of notes void freePointerToNotes(); //functions derived from ContentHandler //what to do at start of each element virtual void startElement( const XMLCh* const uri, const XMLCh* const localname, const XMLCh* const qname, const Attributes& attrs ); //what to do at an error virtual void fatalError(const SAXParseException&); virtual void characters ( const XMLCh* const chars , const XMLSize_t length ); virtual void endDocument (); virtual void endElement ( const XMLCh* const uri, const XMLCh* const localname, const XMLCh* const qname ); virtual void ignorableWhitespace ( const XMLCh* const chars , const XMLSize_t length ); virtual void processingInstruction ( const XMLCh* const target , const XMLCh* const data ); virtual void setDocumentLocator(const Locator* const locator); virtual void startDocument(); virtual void startPrefixMapping ( const XMLCh* const prefix, const XMLCh* const uri ); virtual void endPrefixMapping ( const XMLCh* const prefix ); virtual void skippedEntity ( const XMLCh* const name ); private: //function to run start element processes void startElementRoutine(char* localname_char, const Attributes& attributes); //function to run characters processes void charactersRoutine(char* chars_local); //function to run end element processes void endElementRoutine(char* localname_char); /* ******************************************************** ********************** Note **************************** ******************************************************** */ //pointer to vector of notes std::vector<Note> *notesVectorPtr; Note thisNote; //constantly changing note object Note* currentNote; /* ********************************************************* **************** Music XML Elements ********************* ********************************************************* */ //Instrument Note::Instrument noteInstrument; void setNoteInstrument(Note::Instrument thisInstrument); Note::Instrument getNoteInstrument(); void runPartNameStartElementEvent(char* localname_char); void runPartNameCharEvent(char* char_local); void runPartNameEndElementEvent(char* localname_char); // *** Note Type: Note or Rest *** //Note element processes int noteElementCounter; //different enum cases for state of note enum NoteState{ NO_STATE = 0, NOTE_STATE, REST_STATE, BACKUP_STATE }; SAX2HandlerMusicXML::NoteState noteState; void setNoteState( SAX2HandlerMusicXML::NoteState state); SAX2HandlerMusicXML::NoteState getNoteState(); //enum cases for elements found enum Element {NO_ELEMENT = 0, PART_NAME, NOTE,REST,BACKUP,CHORD, MEASURE, BEATS,BEAT_TYPE, STEP,OCTAVE, DURATION, STAFF}; SAX2HandlerMusicXML::Element currentElement; //std::stack <SAX2HandlerMusicXML::Element> elementStack; void pushElement(SAX2HandlerMusicXML::Element element); void popCurrentElement(); SAX2HandlerMusicXML::Element getCurrentElement(); //function to run if note element found in start element void runNoteStartElementEvent(char* localname_char,const Attributes& attributes); void runNoteEndElementEvent(char* localname_char); //back up element is important because it allows us to // distinguish from real note and copy note void runBackUpStartElementEvent(char* localname_char); void runBackUpEndElementEvent(char* localname_char); // *** Time Signature *** //Beats and beat type element processes //function to run if beats element found void runBeatsStartElementEvent(char* localname_char); void runBeatsEndElementEvent(char* localname_char); int beat; void setBeat(int thisBeat); int getBeat(); //function to run if beat-type element found void runBeatTypeStartElementEvent(char* localname_char); void runBeatTypeEndElementEvent(char* localname_char); int beatType; void setBeatType(int thisBeatType); int getBeatType(); // *** Measure Number *** int measureNumberCounter; void incrementMeasureNumberCounter(); void setMeasureNumberCount(int number); int getMeasureNumberCount(); void resetMeasureNumberCounter(); void runMeasureStartElementEvent(char* localname_char); void runMeasureEndElementEvent(char* localname_char); // *** Duration *** int duration; void setDuration(int thisDuration); int getDuration(); void runDurationStartElementEvent(char* localname_char); void runDurationEndElementEvent(char* localname_char); // *** Pitch *** char step; void setStep(char thisStep); char getStep(); void runStepStartElementEvent(char* localname_char); void runStepEndElementEvent(char* localname_char); int octave; void setOctave(int thisOctave); int getOctave(); void runOctaveStartElementEvent(char* localname_char); void runOctaveEndElementEvent(char* localname_char); /* ********** Staff *********** */ int noteStaff; void setNoteStaff(int thisStaff); int getNoteStaff(); void runStaffStartElementEvent(char* localname_char); void runStaffEndElementEvent(char* localname_char); /* ********** Chord ************ */ void runChordStartElementEvent(char* localname_char); //function to finalize note attributes void checkFinalNote(); }; #endif
28.039526
117
0.62278
[ "object", "vector" ]
3bccdd6ed2955cbb34821a8212173311033d560d
6,538
cpp
C++
tests/functor/test_from_foldable.cpp
dkormalev/cefal
95b583ad569274172ae53c14511861f602051dd8
[ "BSD-3-Clause" ]
52
2020-03-31T23:53:45.000Z
2021-10-25T00:00:27.000Z
tests/functor/test_from_foldable.cpp
dkormalev/cefal
95b583ad569274172ae53c14511861f602051dd8
[ "BSD-3-Clause" ]
4
2020-04-01T00:15:32.000Z
2020-06-06T23:45:34.000Z
tests/functor/test_from_foldable.cpp
dkormalev/cefal
95b583ad569274172ae53c14511861f602051dd8
[ "BSD-3-Clause" ]
5
2020-03-31T23:53:50.000Z
2021-10-25T00:00:28.000Z
/* Copyright 2020, Dennis Kormalev * 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 copyright holders nor the names of its contributors may be used to * endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include "counter.h" #include "cefal/everything.h" #include "catch2/catch.hpp" #include <deque> #include <list> #include <set> #include <string> #include <unordered_set> #include <vector> using namespace cefal; template <typename T> struct TemplatedWithFunctions : public Counter { TemplatedWithFunctions() : Counter() {} TemplatedWithFunctions(T value) : Counter(), value(value) {} T value = T(); static TemplatedWithFunctions empty() { addCustom("empty"); return TemplatedWithFunctions(); } TemplatedWithFunctions append(const TemplatedWithFunctions& other) const& { addCustom("lvalue_append"); return TemplatedWithFunctions(value + other.value); } TemplatedWithFunctions append(TemplatedWithFunctions&& other) && { addCustom("rvalue_append"); value += other.value; return std::move(*this); } template <typename Result, typename Func> Result foldLeft(Result&& init, Func&& f) const& { addCustom("lvalue_foldLeft"); return f(std::move(init), value); } template <typename Result, typename Func> Result foldLeft(Result&& init, Func&& f) && { addCustom("rvalue_foldLeft"); return f(std::move(init), std::move(value)); } }; TEMPLATE_PRODUCT_TEST_CASE("ops::unit()", "", (std::vector, std::list, std::deque, std::set, std::unordered_set, std::multiset, std::unordered_multiset), (int)) { TestType result = ops::unit<TestType>(42); REQUIRE(result.size() == 1); CHECK(*result.begin() == 42); } TEMPLATE_PRODUCT_TEST_CASE("ops::unit()", "", (std::map, std::unordered_map, std::multimap, std::unordered_multimap), ((std::string, int))) { TestType result; SECTION("pair") { result = ops::unit<TestType>(std::make_pair(std::string("abc"), 42)); } SECTION("tuple") { result = ops::unit<TestType>(std::make_tuple(std::string("abc"), 42)); } REQUIRE(result.size() == 1); CHECK(result.begin()->first == "abc"); CHECK(result.begin()->second == 42); } TEST_CASE("ops::unit() - TemplatedWithFunctions<int>") { auto result = ops::unit<TemplatedWithFunctions>(42); CHECK(result.value == 42); } TEMPLATE_PRODUCT_TEST_CASE("ops::map()", "", (std::vector, std::list, std::deque, std::set, std::unordered_set, std::multiset, std::unordered_multiset), (std::string)) { WithInnerType_T<TestType, int> result; SECTION("Lvalue") { auto func = [](const std::string& s) { return std::stoi(s); }; const auto left = TestType{"1", "2", "3"}; SECTION("Pipe") { result = left | ops::map(func); } SECTION("Curried") { result = ops::map(func)(left); } } SECTION("Rvalue") { auto func = [](std::string&& s) { return std::stoi(std::move(s)); }; auto left = TestType{"1", "2", "3"}; SECTION("Pipe") { result = std::move(left) | ops::map(func); } SECTION("Curried") { result = ops::map(func)(std::move(left)); } } CHECK(result == WithInnerType_T<TestType, int>{1, 2, 3}); } TEMPLATE_PRODUCT_TEST_CASE("ops::map()", "", (std::map, std::unordered_map, std::multimap, std::unordered_multimap), ((std::string, int))) { WithInnerType_T<TestType, std::pair<int, std::string>> result; SECTION("Lvalue") { auto func = [](const std::pair<std::string, int>& x) { return make_pair(x.second, x.first); }; const auto left = TestType{{"abc", 1}, {"de", 2}, {"f", 3}}; SECTION("Pipe") { result = left | ops::map(func); } SECTION("Curried") { result = ops::map(func)(left); } } SECTION("Rvalue") { auto func = [](std::pair<std::string, int>&& x) { return make_pair(x.second, std::move(x.first)); }; auto left = TestType{{"abc", 1}, {"de", 2}, {"f", 3}}; SECTION("Pipe") { result = std::move(left) | ops::map(func); } SECTION("Curried") { result = ops::map(func)(std::move(left)); } } CHECK(result == WithInnerType_T<TestType, std::pair<int, std::string>>{{1, "abc"}, {2, "de"}, {3, "f"}}); } TEST_CASE("ops::map() - TemplatedWithFunctions<std::string>") { TemplatedWithFunctions<int> result; SECTION("Lvalue") { auto func = [](const std::string& s) { return std::stoi(s); }; const auto left = TemplatedWithFunctions<std::string>("3"); SECTION("Pipe") { result = left | ops::map(func); } SECTION("Curried") { result = ops::map(func)(left); } } SECTION("Rvalue") { auto func = [](std::string&& s) { return std::stoi(std::move(s)); }; auto left = TemplatedWithFunctions<std::string>("3"); SECTION("Pipe") { result = std::move(left) | ops::map(func); } SECTION("Curried") { result = ops::map(func)(std::move(left)); } } CHECK(result.value == 3); }
42.454545
117
0.626032
[ "vector" ]
3bce2126b36e7b98667e7379b318bfbd417806ca
5,220
cpp
C++
software/protoDUNE/generic/PrbsRx.cpp
slaclab/proto-dune
e487ee6d40359b40776098410d7fd302b9631448
[ "BSD-3-Clause-LBNL" ]
null
null
null
software/protoDUNE/generic/PrbsRx.cpp
slaclab/proto-dune
e487ee6d40359b40776098410d7fd302b9631448
[ "BSD-3-Clause-LBNL" ]
2
2017-05-11T04:22:27.000Z
2018-09-18T16:10:29.000Z
software/protoDUNE/generic/PrbsRx.cpp
slaclab/proto-dune
e487ee6d40359b40776098410d7fd302b9631448
[ "BSD-3-Clause-LBNL" ]
2
2017-04-03T21:59:53.000Z
2020-12-13T00:14:20.000Z
//----------------------------------------------------------------------------- // File : PrbsRx.cpp // Author : Ben Reese <bareese@slac.stanford.edu> // Created : 11/14/2013 // Project : HPS SVT //----------------------------------------------------------------------------- // Description : // Device container for AxiVersion.vhd //----------------------------------------------------------------------------- // This file is part of 'SLAC Generic DAQ Software'. // It is subject to the license terms in the LICENSE.txt file found in the // top-level directory of this distribution and at: // https://confluence.slac.stanford.edu/display/ppareg/LICENSE.html. // No part of 'SLAC Generic DAQ Software', including this file, // may be copied, modified, propagated, or distributed except according to // the terms contained in the LICENSE.txt file. // Proprietary and confidential to SLAC. //----------------------------------------------------------------------------- // Modification history : // 11/14/2013: created //----------------------------------------------------------------------------- #include <PrbsRx.h> #include <Register.h> #include <RegisterLink.h> #include <Variable.h> #include <Command.h> #include <sstream> #include <iostream> #include <string> #include <iomanip> #include <stdint.h> using namespace std; // Constructor PrbsRx::PrbsRx ( uint32_t linkConfig, uint32_t baseAddress, uint32_t index, Device *parent, uint32_t addrSize ) : Device(linkConfig,baseAddress,"PrbsRx",index,parent) { RegisterLink *l; Variable *v; Command *c; // Description desc_ = "Firmware Version object."; cout << "PrbsRx: baseAddress: " << hex << baseAddress << endl; // Create Registers: name, address addRegisterLink(l = new RegisterLink("MissedPacketCount", baseAddress_ + 0x00*addrSize, Variable::Status)); l->getVariable()->setDescription("Number of missed packets"); l->setPollEnable(true); addRegisterLink(l = new RegisterLink("LengthErrorCount", baseAddress_ + 0x01*addrSize, Variable::Status)); l->getVariable()->setDescription("Number of packets that were the wrong length"); l->setPollEnable(true); addRegisterLink(l = new RegisterLink("EofeErrorCount", baseAddress_ + 0x02*addrSize, Variable::Status)); l->getVariable()->setDescription("Number of EOFE errors"); l->setPollEnable(true); addRegisterLink(l = new RegisterLink("DataBusErrorCount", baseAddress_ + 0x03*addrSize, Variable::Status)); l->getVariable()->setDescription("Number of data bus errors"); l->setPollEnable(true); addRegisterLink(l = new RegisterLink("WordStrbErrorCount", baseAddress_ + 0x04*addrSize, Variable::Status)); l->getVariable()->setDescription("Number of word errors"); l->setPollEnable(true); addRegisterLink(l = new RegisterLink("BitStrbErrorCount", baseAddress_ + 0x05*addrSize, Variable::Status)); l->getVariable()->setDescription("Number of bit errors"); l->setPollEnable(true); addRegisterLink(l = new RegisterLink("RxFifoOverflowCount", baseAddress_ + 0x06*addrSize, Variable::Status)); addRegisterLink(l = new RegisterLink("RxFifoPauseCount", baseAddress_ + 0x07*addrSize, Variable::Status)); addRegisterLink(l = new RegisterLink("TxFifoOverflowCount", baseAddress_ + 0x08*addrSize, Variable::Status)); addRegisterLink(l = new RegisterLink("TxFifoPauseCount", baseAddress_ + 0x09*addrSize, Variable::Status)); addRegisterLink(l = new RegisterLink("Dummy", baseAddress_ + 0x0a*addrSize, Variable::Configuration)); l->getVariable()->setPerInstance(true); cout << "PrbsRx:Status:address: " << hex << baseAddress_ + 0x70*addrSize << endl; addRegisterLink(l = new RegisterLink("Status", baseAddress_ + 0x70*addrSize, Variable::Status)); addRegisterLink(l = new RegisterLink("PacketLength", baseAddress_ + 0x71*addrSize, Variable::Status)); l->setPollEnable(true); addRegisterLink(l = new RegisterLink("PacketRate", baseAddress_ + 0x72*addrSize, Variable::Status)); l->setPollEnable(true); addRegisterLink(l = new RegisterLink("BitErrorCount", baseAddress_ + 0x73*addrSize, Variable::Status)); l->setPollEnable(true); addRegisterLink(l = new RegisterLink("WordErrorCount", baseAddress_ + 0x74*addrSize, Variable::Status)); l->setPollEnable(true); addRegisterLink(l = new RegisterLink("RolloverEnable", baseAddress_ + 0xF0*addrSize, Variable::Configuration)); l->getVariable()->setPerInstance(true); addRegister(new Register("CountReset", baseAddress_ + 0xFF*addrSize)); v = getVariable("Enabled"); v->set("True"); v->setHidden(true); c = new Command("ResetCounters"); c->setDescription("Reset all the error and rate counters"); addCommand(c); } // Deconstructor PrbsRx::~PrbsRx ( ) { } // Process Commands void PrbsRx::command(string name, string arg) { Register *r; if (name == "ResetCounters") { REGISTER_LOCK r = getRegister("CountReset"); r->set(0x1); r->setStale(); writeRegister(r, true, false); REGISTER_UNLOCK } } void PrbsRx::countReset() { command("ResetCounters",""); Device::countReset(); }
38.955224
114
0.651341
[ "object" ]
3bd19f58e14154a9d3b7de7d83fa14fbd83d4417
1,094
cpp
C++
constrained_ik/examples/constraints_from_yaml_example.cpp
DavidMerzJr/industrial_moveit
d108e817ad36a67af65ec8c0a3eee1ed4e1e65ad
[ "Apache-2.0" ]
97
2015-09-02T03:32:44.000Z
2022-02-20T16:42:03.000Z
constrained_ik/examples/constraints_from_yaml_example.cpp
DavidMerzJr/industrial_moveit
d108e817ad36a67af65ec8c0a3eee1ed4e1e65ad
[ "Apache-2.0" ]
77
2015-08-26T15:58:13.000Z
2021-09-29T12:38:30.000Z
constrained_ik/examples/constraints_from_yaml_example.cpp
DavidMerzJr/industrial_moveit
d108e817ad36a67af65ec8c0a3eee1ed4e1e65ad
[ "Apache-2.0" ]
62
2015-04-24T16:17:21.000Z
2021-11-22T13:54:11.000Z
#include "constrained_ik/constrained_ik.h" #include "constrained_ik/enum_types.h" #include "example_utils.h" #include <moveit/robot_model_loader/robot_model_loader.h> using namespace constrained_ik; using namespace constrained_ik::basic_kin; using namespace Eigen; /** * @brief This is an example shows how to add constraint/constraints * using a yaml file loaded to the ros param server. */ int main(int argc, char *argv[]) { ros::init(argc, argv, "constraints_from_yaml_example"); Constrained_IK ik; BasicKin kin; robot_model_loader::RobotModelLoaderPtr loader; planning_scene::PlanningScenePtr planning_scene; // Load example robot model planning_scene = getExampleRobotData(loader); // Initialize kinematic model kin.init(loader->getModel()->getJointModelGroup("manipulator")); // Add constraint/constraints from ros parameter server std::string param = "example_yaml/constraints"; ik.addConstraintsFromParamServer(param); // Initialize Solver ik.init(kin); // Calculate IK for sample case evaluteExampleIK(kin, ik, planning_scene); return 0; }
27.35
68
0.767824
[ "model" ]
3bd33ef271733a0fc8bda29fd9319e196ccb66b2
1,935
cpp
C++
USACO Training/1.2/gift1.cpp
aldew5/Competitve-Programming
eb0b93a35af3bd5e806aedc44b835830af01d496
[ "MIT" ]
2
2020-05-09T15:54:18.000Z
2021-01-23T22:32:53.000Z
USACO Training/1.2/gift1.cpp
aldew5/Competitive-Programming
fc93723fae739d0b06bcf2dbe3b9274584a79a66
[ "MIT" ]
null
null
null
USACO Training/1.2/gift1.cpp
aldew5/Competitive-Programming
fc93723fae739d0b06bcf2dbe3b9274584a79a66
[ "MIT" ]
null
null
null
/* ID: alec3 LANG: C++14 PROG: gift1 CLASSIFICATION: Ad Hoc */ #include <iostream> #include <vector> #include <fstream> using namespace std; // define a function to find a friends index in balance int FindIndex(string person, vector<string> list) { for (int i = 0; i < list.size(); i++){ if (list[i] == person){ return i; } } // not in the list return -1; } int main() { int num_friends; vector <string> members; ofstream fout("gift1.out"); ifstream fin("gift1.in"); fin >> num_friends; // declare a vector of length num friends where each //friend's balance is 0 vector<int> balance(num_friends, 0); // create a vector of all the names for (int i = 0; i < num_friends; i++){ string member; fin >> member; members.push_back(member); } // get data for a person for (int i = 0; i < members.size(); i++) { string name; int total; int num_gifts; fin >> name >> total >> num_gifts; int giver_index; giver_index = FindIndex(name, members); // not giving zero gifts if (!(num_gifts == 0)){ // take off the remainder because that person keeps it total = (total - (total % num_gifts)); // subtract what they're actually giving (no remainder) balance[giver_index] -= total; // add to the people that recieved the gift for (int i = 0; i < num_gifts; i ++){ string person; fin >> person; int person_index = FindIndex(person, members); // add the value of the gift balance[person_index] += (total / num_gifts); } } } //output the names and their balances for (int i = 0; i < num_friends; i++){ fout << members[i] << " " << balance[i] << "\n"; } return 0; }
24.1875
67
0.541602
[ "vector" ]
3bd5785444a0b2c382ac4947c3fe8e0eba8825d0
5,826
cpp
C++
src/editor/systems/scene_camera.cpp
Caravetta/Engine
6e2490a68727dc731b466335499f3204490acc5f
[ "MIT" ]
2
2018-05-21T02:12:50.000Z
2019-04-23T20:56:00.000Z
src/editor/systems/scene_camera.cpp
Caravetta/Engine
6e2490a68727dc731b466335499f3204490acc5f
[ "MIT" ]
12
2018-05-30T13:15:25.000Z
2020-02-02T21:29:42.000Z
src/editor/systems/scene_camera.cpp
Caravetta/Engine
6e2490a68727dc731b466335499f3204490acc5f
[ "MIT" ]
2
2018-06-14T19:03:29.000Z
2018-12-30T07:37:22.000Z
#include <algorithm> #include "scene_camera.h" #include "editor_context.h" static void glm_mat_to_engine_mat( Engine::Matrix4f& engine_mat, glm::mat4& glm_mat ) { const float *pSource1 = (const float*)glm::value_ptr(glm_mat); engine_mat.x.x = pSource1[0]; engine_mat.x.y = pSource1[1]; engine_mat.x.z = pSource1[2]; engine_mat.x.w = pSource1[3]; engine_mat.y.x = pSource1[4]; engine_mat.y.y = pSource1[5]; engine_mat.y.z = pSource1[6]; engine_mat.y.w = pSource1[7]; engine_mat.z.x = pSource1[8]; engine_mat.z.y = pSource1[9]; engine_mat.z.z = pSource1[10]; engine_mat.z.w = pSource1[11]; engine_mat.t.x = pSource1[12]; engine_mat.t.y = pSource1[13]; engine_mat.t.z = pSource1[14]; engine_mat.t.w = pSource1[15]; } void Scene_Camera::init( void ) { Editor_Context* editor_context = Editor_Context::get_instance(); scene_camera.window = editor_context->window; width = (float)scene_camera.window->width(); height = (float)scene_camera.window->height(); position = glm::vec3(0, 0, 1); focal_point = glm::vec3(0, 0, 0); pitch = 0; yaw = 0; distance = glm::distance(position, focal_point); glm::mat4 per_test = glm::perspectiveFov(glm::radians(45.0f), width, height, 0.1f, 1000.0f); glm_mat_to_engine_mat(scene_camera.perspective, per_test); glm::mat4 view_test = glm::inverse(glm::translate(glm::mat4(1.0f), position)); LOG("%s", glm::to_string(view_test).c_str()); glm_mat_to_engine_mat(scene_camera.view, view_test); scene_camera.view.log(); editor_context->scene_camera = &scene_camera; Engine::set_active_camera(scene_camera); } void Scene_Camera::update( float time_step ) { Editor_Context* editor_context = Editor_Context::get_instance(); if ( width != (float)scene_camera.window->width() || height != (float)scene_camera.window->height() ) { width = (float)scene_camera.window->width(); height = (float)scene_camera.window->height(); glm::mat4 per_test = glm::perspectiveFov(glm::radians(45.0f), width, height, 0.1f, 1000.0f); glm_mat_to_engine_mat(scene_camera.perspective, per_test); } float mouse_x = Engine::mouse_x_position(); float mouse_y = Engine::mouse_y_position(); float delta_x = mouse_x - cur_mouse_x; float delta_y = mouse_y - cur_mouse_y; delta_y *= 0.01f * -1.0f; delta_x *= 0.01f * -1.0f; cur_mouse_x = mouse_x; cur_mouse_y = mouse_y; if ( Engine::is_key_pressed(Engine::KEY_W) ) { zoom(delta_y); } if ( Engine::is_key_pressed(Engine::KEY_A) ) { pan(-delta_x, delta_y); } if ( Engine::is_key_pressed(Engine::KEY_D) ) { rotate(-delta_x, delta_y); } if ( Engine::is_key_pressed(Engine::KEY_F) ) { if ( editor_context->entity_selected ) { Engine::Entity selected_ent = editor_context->entity_manager.get_entity(editor_context->selected_entity); Engine::Transform* entity_transform = Engine::get_component<Engine::Transform>(selected_ent); if ( entity_transform != NULL ) { position.x = entity_transform->position.x; position.y = entity_transform->position.y; position.z = entity_transform->position.z; position.z += 2; focal_point = position; focal_point.z -= 1.0f; distance = glm::distance(position, focal_point); yaw = 0; pitch = 0; } } } position = calc_position(); glm::quat orient = orientation(); glm::mat4 view_test = glm::translate(glm::mat4(1.0f), position) * glm::toMat4(orient); view_test = glm::inverse(view_test); glm_mat_to_engine_mat(scene_camera.view, view_test); } void Scene_Camera::shutdown( void ) { // nothing to do } void Scene_Camera::pan( float x_delta, float y_delta ) { glm::vec3 speed = pan_speed(); focal_point += -right_direction() * x_delta * speed.x * distance; focal_point += up_direction() * y_delta * speed.y * distance; } void Scene_Camera::zoom( float delta ) { distance -= delta * zoom_speed(); if ( distance < 1.0f ) { focal_point += forward_direction(); distance = glm::distance(position, focal_point); } } void Scene_Camera::rotate( float x_delta, float y_delta ) { float yaw_sign = up_direction().y < 0 ? -1.0f : 1.0f; yaw += yaw_sign * x_delta * 0.8f; pitch += y_delta * 0.8f; } glm::quat Scene_Camera::orientation( void ) { return glm::quat(glm::vec3(-pitch, -yaw, 0.0f)); } glm::vec3 Scene_Camera::calc_position( void ) { return focal_point - forward_direction() * distance; } glm::vec3 Scene_Camera::forward_direction( void ) { return glm::rotate(orientation(), glm::vec3(0.0f, 0.0f, -1.0f)); } glm::vec3 Scene_Camera::right_direction( void ) { return glm::rotate(orientation(), glm::vec3(1.0f, 0.0f, 0.0f)); } glm::vec3 Scene_Camera::up_direction( void ) { return glm::rotate(orientation(), glm::vec3(0.0f, 1.0f, 0.0f)); } glm::vec3 Scene_Camera::pan_speed( void ) { float x = std::min(width / 1000.0f, 2.4f); // max = 2.4f float xFactor = 0.0366f * (x * x) - 0.1778f * x + 0.3021f; float y = std::min(height / 1000.0f, 2.4f); // max = 2.4f float yFactor = 0.0366f * (y * y) - 0.1778f * y + 0.3021f; return glm::vec3(xFactor, yFactor, 0); } float Scene_Camera::zoom_speed( void ) { float dis = distance * 0.2f; dis = std::max(dis, 0.0f); float speed = dis * dis; speed = std::min(speed, 100.0f); // max speed = 100 return speed; }
27.611374
120
0.614487
[ "transform" ]
3bd66b8a89c3135681551791cae6584c6f1bc8b1
10,341
cpp
C++
inou/yosys/inou_yosys_api.cpp
jesec/livehd
1a82dbea1d86dbd1511de588609de320aa4ef6ed
[ "BSD-3-Clause" ]
null
null
null
inou/yosys/inou_yosys_api.cpp
jesec/livehd
1a82dbea1d86dbd1511de588609de320aa4ef6ed
[ "BSD-3-Clause" ]
null
null
null
inou/yosys/inou_yosys_api.cpp
jesec/livehd
1a82dbea1d86dbd1511de588609de320aa4ef6ed
[ "BSD-3-Clause" ]
null
null
null
// This file is distributed under the BSD 3-Clause License. See LICENSE for details. #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> //#include <ext/stdio_filebuf.h> #include <fstream> #include <iostream> #include <stdexcept> #include "eprp_utils.hpp" #include "inou_yosys_api.hpp" #include "kernel/yosys.h" #include "lgraph.hpp" #include "mustache.hpp" static void log_error_atexit() { throw std::runtime_error("yosys finished"); } void setup_inou_yosys() { Yosys::log_error_stderr = true; Yosys::log_cmd_error_throw = true; Yosys::log_errfile = stderr; Yosys::log_error_atexit = log_error_atexit; Inou_yosys_api::setup(); } Inou_yosys_api::Inou_yosys_api(Eprp_var &var, bool do_read) : Pass("inou.yosys", var) { set_script_yosys(var, do_read); } void Inou_yosys_api::set_script_yosys(const Eprp_var &var, bool do_read) { auto script = var.get("script"); auto main_path = Eprp_utils::get_exe_path(); fmt::print("path:{}\n", main_path); std::vector<std::string> alt_paths{"/../pass/mockturtle/mt_test.sh.runfiles/livehd/inou/yosys/", "/../pass/lnast_fromlg/lgtoln_verif_from_verilog.sh.runfiles/livehd/inou/yosys/", "/../pass/lnast_fromlg/lgtoln_verif_from_pyrope.sh.runfiles/livehd/inou/yosys/", "/../pass/sample/sample_test1.sh.runfiles/livehd/inou/yosys/", "/main_test.runfiles/livehd/inou/yosys/", "/verilog.sh.runfiles/livehd/inou/yosys/", "/verilog.sh-long.runfiles/livehd/inou/yosys/", "/lgshell.runfiles/livehd/inou/yosys/", "/../inou/pyrope/lnast_prp_test.sh.runfiles/livehd/inou/yosys/", "/../share/livehd/inou/yosys/", "/../inou/yosys/", "/inou/yosys/"}; if (script.empty()) { std::string do_read_str; if (do_read) do_read_str = "inou_yosys_read.ys"; else do_read_str = "inou_yosys_write.ys"; for (const auto &e : alt_paths) { auto test = main_path + e + do_read_str; if (access(test.c_str(), R_OK) != -1) { script_file = test; break; } } } if (access(std::string(script_file).c_str(), R_OK) != F_OK) { error("yosys setup could not find the provided script:{} file", script_file); return; } } void Inou_yosys_api::call_yosys(mustache::data &vars) { std::ifstream inFile; inFile.open(std::string(script_file)); if (!inFile.good()) error("inou_yosys_api: could not open {}", script_file); std::stringstream strStream; strStream << inFile.rdbuf(); // read the whole file mustache::mustache tmpl(strStream.str()); tmpl.set_custom_escape([](const std::string &s) { return s; }); // No HTML escape const std::string yosys_all_cmds = tmpl.render(vars); Yosys::RTLIL::Design design; auto cmd_list = absl::StrSplit(yosys_all_cmds, '\n'); for (const auto &c : cmd_list) { auto x = std::find_if(c.begin(), c.end(), [](char ch) { return std::isalnum(ch); }); if (x == c.end()) continue; // skip empty (or just space lines) std::string cmd{c}; // yosys call needs std::string fmt::print("yosys cmd:{}\n", cmd); try { Yosys::Pass::call(&design, cmd); } catch (...) { err_tracker::err_logger("inou.yosys cmd:{} failed\n", cmd); error("inou.yosys cmd:{} failed\n", cmd); } } #if 0 char filename[1024]; strcpy(filename, "yosys_script.XXXXXX"); int fd = mkstemp(filename); if (fd < 0) { error("Could not create yosys_script.XXXXXX file\n"); return -1; } int sz_check = write(fd, yosys_cmd.c_str(), yosys_cmd.size()); I(sz_check == yosys_cmd.size()); close(fd); fmt::print("yosys {} synthesis cmd: {} using {}\n", filename, yosys, script_file); int pid = fork(); if (pid < 0) { error("unable to fork??"); return -1; } if (pid == 0) { // Child char filename2[1024 + 32]; sprintf(filename2, "%s.log", filename); int fd_out = open(filename2, O_CREAT | O_WRONLY | O_TRUNC, 0644); if (fd_out < 0) { fprintf(stderr, "ERROR inou_yosys_api could not create %s file\n", filename); exit(-3); } sprintf(filename2, "%s.err", filename); int fd_err = open(filename2, O_CREAT | O_WRONLY | O_TRUNC, 0644); if (fd_err < 0) { fprintf(stderr, "ERROR inou_yosys_api could not create %s file\n", filename); exit(-3); } dup2(fd_out, STDOUT_FILENO); dup2(fd_err, STDERR_FILENO); close(fd_err); close(fd_out); char *argv[] = {strdup(yosys.c_str()), strdup("-q"), strdup("-s"), strdup(filename), 0}; if (execvp(yosys.c_str(), argv) < 0) { error("execvp fail with {}", strerror(errno)); exit(-3); } exit(0); } int wstatus; #if 1 do { int w = waitpid(pid, &wstatus, WUNTRACED | WCONTINUED); if (w == -1) { error("waitpid fail with {}", strerror(errno)); return errno; } if (WIFEXITED(wstatus)) { printf("exited, status=%d\n", WEXITSTATUS(wstatus)); if (wstatus != 0) { std::string errpath = filename; errpath.append(".err"); std::ifstream errfile; errfile.open(errpath, std::ios::in); std::string errtext; getline(errfile, errtext); std::cout << "\nyosys output: " << errtext << std::endl; errfile.close(); } } else if (WIFSIGNALED(wstatus)) { printf("killed by signal %d\n", WTERMSIG(wstatus)); } else if (WIFSTOPPED(wstatus)) { printf("stopped by signal %d\n", WSTOPSIG(wstatus)); } else if (WIFCONTINUED(wstatus)) { printf("continued\n"); } } while (!WIFEXITED(wstatus) && !WIFSIGNALED(wstatus)); #else wait(&wstatus); #endif return wstatus; #endif } void Inou_yosys_api::tolg(Eprp_var &var) { Inou_yosys_api p(var, true); p.do_tolg(var); } void Inou_yosys_api::do_tolg(Eprp_var &var) { if (files.empty()) { error("files can not be empty"); return; } const std::string techmap{var.get("techmap")}; const std::string abc{var.get("abc")}; const std::string top{var.get("top")}; const std::string lib{var.get("liberty")}; mustache::data vars; vars.set("path", std::string(path)); mustache::data filelist{mustache::data::type::list}; for (const auto &f : absl::StrSplit(files, ',')) { filelist << mustache::data{"input", std::string(f)}; } vars.set("filelist", filelist); if (!top.empty()) { vars.set("hierarchy", mustache::data::type::bool_true); if (top != "-auto-top") { vars.set("top", "-top " + top); } else { vars.set("top", top); } } else { vars.set("hierarchy", mustache::data::type::bool_false); } if (!techmap.empty()) { if (techmap == "alumacc") { vars.set("techmap_alumacc", mustache::data::type::bool_true); } else if (techmap == "full") { vars.set("techmap_full", mustache::data::type::bool_true); } else { error("unrecognized techmap {} option. Either full or alumacc", techmap); return; } } if (abc == "true" || abc == "1") { vars.set("abc_in_yosys", mustache::data::type::bool_true); } else if (abc == "false" || abc == "0") { // Nothing to do } else { error("unrecognized abc {} option. Either true or false", techmap); } auto gl = Graph_library::instance(path); uint32_t max_version = gl->get_max_version(); Yosys::yosys_setup(); call_yosys(vars); std::vector<Lgraph *> lgs; gl->each_lgraph([&lgs, gl, max_version, this](Lg_type_id id, std::string_view name) { (void)name; if (gl->get_version(id) > max_version) { Lgraph *lg = Lgraph::open(path, id); if (lg == 0) { warn("could not open graph lgid:{} in path:{}", (int)id, path); } else { lgs.push_back(lg); } } }); // Yosys::memhasher_off(); // Yosys::yosys_shutdown(); var.add(lgs); } void Inou_yosys_api::fromlg(Eprp_var &var) { Inou_yosys_api p(var, false); Yosys::yosys_setup(); for (auto &lg : var.lgs) { mustache::data vars; vars.set("path", std::string(p.path)); vars.set("odir", std::string(p.odir)); auto file = absl::StrCat(p.odir, "/", lg->get_name(), ".v"); vars.set("file", std::string(file)); vars.set("name", std::string(lg->get_name())); auto hier = var.get("hier"); if (!hier.empty() && (hier == "1" || hier == "true")) { vars.set("hier", mustache::data::type::bool_true); } else { vars.set("hier", mustache::data::type::bool_false); } p.call_yosys(vars); } } void Inou_yosys_api::setup() { Eprp_method m1("inou.yosys.tolg", "read verilog using yosys to lgraph", &Inou_yosys_api::tolg); m1.add_label_required("files", "verilog files to process (comma separated)"); m1.add_label_optional("path", "path to build the lgraph[s]", "lgdb"); m1.add_label_optional("techmap", "Either full or alumac techmap or none from yosys. Cannot be used with liberty", ""); m1.add_label_optional("liberty", "Liberty file for technology mapping. Cannot be used with techmap, will call abc for tmap", ""); m1.add_label_optional("abc", "run ABC inside yosys before loading lgraph", "false"); m1.add_label_optional("script", "alternative custom inou_yosys_read.ys command"); m1.add_label_optional("yosys", "path for yosys command", ""); m1.add_label_optional("top", "define top module, will call yosys hierarchy pass (-auto-top allowed)"); register_inou("yosys", m1); Eprp_method m2("inou.yosys.fromlg", "write verilog using yosys from lgraph", &Inou_yosys_api::fromlg); m2.add_label_optional("path", "path to read the lgraph[s]", "lgdb"); m2.add_label_optional("odir", "output directory for generated verilog files", "."); m2.add_label_optional("script", "alternative custom inou_yosys_write.ys command"); m2.add_label_optional("yosys", "path for yosys command", ""); m2.add_label_optional("hier", "hierarchy pass in LiveHD (like flat in yosys)"); register_inou("yosys", m2); }
31.054054
131
0.604487
[ "render", "vector" ]
3bdf2fe672e807767420bf798161a7110f339a41
286
hpp
C++
external/frozenbubble/FBLevels.hpp
allegrofb/Allegrofb
0f4b29d3b783ccc5bacda98bd2c1c11c716a1d9e
[ "BSD-3-Clause" ]
null
null
null
external/frozenbubble/FBLevels.hpp
allegrofb/Allegrofb
0f4b29d3b783ccc5bacda98bd2c1c11c716a1d9e
[ "BSD-3-Clause" ]
null
null
null
external/frozenbubble/FBLevels.hpp
allegrofb/Allegrofb
0f4b29d3b783ccc5bacda98bd2c1c11c716a1d9e
[ "BSD-3-Clause" ]
null
null
null
#ifndef FBLEVELS_H #define FBLEVELS_H #include <vector> class FBLevels { public: static FBLevels* LoadFrom(const char* filename); ~FBLevels(); const int* GetLevel(int i); int GetMax(); private: void Add(int*); FBLevels(); std::vector<int*> levels; }; #endif //FBLEVELS_H
13
49
0.692308
[ "vector" ]
3be1d6f4cf37d7e550e98984c47bc87306d78ba5
2,597
cpp
C++
Applications/Utils/FileConverter/FEFLOW2OGS.cpp
HaibingShao/ogs6_ufz
d4acfe7132eaa2010157122da67c7a4579b2ebae
[ "BSD-4-Clause" ]
null
null
null
Applications/Utils/FileConverter/FEFLOW2OGS.cpp
HaibingShao/ogs6_ufz
d4acfe7132eaa2010157122da67c7a4579b2ebae
[ "BSD-4-Clause" ]
null
null
null
Applications/Utils/FileConverter/FEFLOW2OGS.cpp
HaibingShao/ogs6_ufz
d4acfe7132eaa2010157122da67c7a4579b2ebae
[ "BSD-4-Clause" ]
null
null
null
/** * \copyright * Copyright (c) 2012-2017, OpenGeoSys Community (http://www.opengeosys.org) * Distributed under a Modified BSD License. * See accompanying file LICENSE.txt or * http://www.opengeosys.org/project/license * */ #include <string> #include <memory> // ThirdParty #include <tclap/CmdLine.h> #include "Applications/ApplicationsLib/LogogSetup.h" // BaseLib #include "BaseLib/FileTools.h" #include "BaseLib/RunTime.h" #ifndef WIN32 #include "BaseLib/MemWatch.h" #endif // FileIO #include "Applications/FileIO/FEFLOW/FEFLOWMeshInterface.h" #include "MeshLib/IO/writeMeshToFile.h" #include "MeshLib/IO/Legacy/MeshIO.h" #include "MeshLib/IO/VtkIO/VtuInterface.h" #include "MeshLib/Mesh.h" int main (int argc, char* argv[]) { ApplicationsLib::LogogSetup logog_setup; TCLAP::CmdLine cmd("Converting a mesh in FEFLOW file format (ASCII, version 5.4) to a vtk unstructured grid file (new OGS file format) or to the old OGS file format - see options.", ' ', "0.1"); TCLAP::ValueArg<std::string> ogs_mesh_arg( "o", "out", "filename for output mesh (if extension is msh, old OGS fileformat is written)", true, "", "filename as string"); cmd.add(ogs_mesh_arg); TCLAP::ValueArg<std::string> feflow_mesh_arg( "i", "in", "FEFLOW input file (*.fem)", true, "", "filename as string"); cmd.add(feflow_mesh_arg); cmd.parse(argc, argv); // *** read mesh INFO("Reading %s.", feflow_mesh_arg.getValue().c_str()); #ifndef WIN32 BaseLib::MemWatch mem_watch; unsigned long mem_without_mesh (mem_watch.getVirtMemUsage()); #endif BaseLib::RunTime run_time; run_time.start(); FileIO::FEFLOWMeshInterface feflowIO; std::unique_ptr<MeshLib::Mesh const> mesh( feflowIO.readFEFLOWFile(feflow_mesh_arg.getValue())); if (mesh == nullptr) { INFO("Could not read mesh from %s.", feflow_mesh_arg.getValue().c_str()); return EXIT_FAILURE; } #ifndef WIN32 unsigned long mem_with_mesh (mem_watch.getVirtMemUsage()); INFO("Mem for mesh: %i MB", (mem_with_mesh - mem_without_mesh)/(1024*1024)); #endif INFO("Time for reading: %f seconds.", run_time.elapsed()); INFO("Read %d nodes and %d elements.", mesh->getNumberOfNodes(), mesh->getNumberOfElements()); std::string ogs_mesh_fname(ogs_mesh_arg.getValue()); INFO("Writing %s.", ogs_mesh_fname.c_str()); MeshLib::IO::writeMeshToFile(*mesh, ogs_mesh_fname); INFO("\tDone."); return EXIT_SUCCESS; }
29.179775
198
0.663073
[ "mesh" ]
3be28acded4363c274fa7a2b7f71cc9feed821c3
1,340
cpp
C++
svca_limix/src/limix/io/split.cpp
DenisSch/svca
bd029c120ca8310f43311253e4d7ce19bc08350c
[ "Apache-2.0" ]
65
2015-01-20T20:46:26.000Z
2021-06-27T14:40:35.000Z
svca_limix/src/limix/io/split.cpp
DenisSch/svca
bd029c120ca8310f43311253e4d7ce19bc08350c
[ "Apache-2.0" ]
29
2015-02-01T22:35:17.000Z
2017-08-07T08:18:23.000Z
svca_limix/src/limix/io/split.cpp
DenisSch/svca
bd029c120ca8310f43311253e4d7ce19bc08350c
[ "Apache-2.0" ]
35
2015-02-01T17:26:50.000Z
2019-09-13T07:06:16.000Z
// Copyright(c) 2014, The LIMIX developers(Christoph Lippert, Paolo Francesco Casale, Oliver Stegle) // //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 "split.h" std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) { std::string delims = std::string(1, delim); tokenize(s, elems, delims); return elems; } std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> elems; return split(s, delim, elems); } std::vector<std::string> &split(const std::string &s, const std::string& delims, std::vector<std::string> &elems) { tokenize(s, elems, delims); return elems; } std::vector<std::string> split(const std::string &s, const std::string& delims) { std::vector<std::string> elems; return split(s, delims, elems); }
35.263158
115
0.707463
[ "vector" ]
3be44139e65a23d0297e163f264ba49f411856fe
6,907
cc
C++
Engine/Source/Runtime/Renderer/StaticModel.cc
rodrigobmg/YumeEngine
67c525c84616a5167b5bae45f36641e90227c281
[ "MIT" ]
129
2016-05-05T23:34:44.000Z
2022-03-07T20:17:18.000Z
Engine/Source/Runtime/Renderer/StaticModel.cc
rodrigobmg/YumeEngine
67c525c84616a5167b5bae45f36641e90227c281
[ "MIT" ]
1
2017-05-07T16:09:41.000Z
2017-05-08T15:35:50.000Z
Engine/Source/Runtime/Renderer/StaticModel.cc
rodrigobmg/YumeEngine
67c525c84616a5167b5bae45f36641e90227c281
[ "MIT" ]
20
2016-02-24T20:40:08.000Z
2022-02-04T23:48:18.000Z
//---------------------------------------------------------------------------- //Yume Engine //Copyright (C) 2015 arkenthera //This program is free software; you can redistribute it and/or modify //it under the terms of the GNU General Public License as published by //the Free Software Foundation; either version 2 of the License, or //(at your option) any later version. //This program is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //GNU General Public License for more details. //You should have received a copy of the GNU General Public License along //with this program; if not, write to the Free Software Foundation, Inc., //51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.*/ //---------------------------------------------------------------------------- // // File : <Filename> // Date : <Date> // Comments : // //---------------------------------------------------------------------------- #include "YumeHeaders.h" #include "StaticModel.h" #include "Logging/logging.h" #include "Core/YumeFile.h" #include "YumeRHI.h" #include "YumeVertexBuffer.h" #include "YumeIndexBuffer.h" namespace YumeEngine { StaticModel::StaticModel(const YumeString& model) : SceneNode(GT_STATIC),modelName_(model) { LoadFromFile(model); } StaticModel::~StaticModel() { } bool StaticModel::LoadFromFile(const YumeString& file) { SharedPtr<YumeFile> f = gYume->pResourceManager->GetFile(file); YumeString fullPath = gYume->pResourceManager->GetFullPath(file); YumeString pathName,fileName,extension; SplitPath(fullPath,pathName,fileName,extension); SharedPtr<YumeFile> m(new YumeFile(pathName + fileName + ".material")); YumeString material = m->GetFileExtension(); unsigned materialCount = m->ReadUInt(); YumeString fileType = f->GetFileExtension(); unsigned meshCount = f->ReadUInt(); for(int i=0; i < meshCount; ++i) { //Read this mesh's vertex buffer unsigned vertexCount = f->ReadUInt(); unsigned elementMask = f->ReadUInt(); unsigned vertexSize = f->ReadUInt(); SharedPtr<YumeVertexBuffer> vb(gYume->pRHI->CreateVertexBuffer()); vb->SetShadowed(true); vb->SetSize(vertexCount,elementMask); void* vbbuffer = vb->Lock(0,vertexCount); f->Read(vbbuffer,vertexCount * vertexSize); vb->Unlock(); unsigned indexCount = f->ReadUInt(); unsigned indexSize = f->ReadUInt(); SharedPtr<YumeIndexBuffer> ib(gYume->pRHI->CreateIndexBuffer()); ib->SetShadowed(true); ib->SetSize(indexCount,true); void* ibbuffer = ib->Lock(0,indexCount); f->Read(ibbuffer,(indexCount)* indexSize); ib->Unlock(); YumeGeometry* geo(new YumeGeometry); geo->SetVertexBuffer(0,vb); geo->SetIndexBuffer(ib); geo->SetDrawRange(TRIANGLE_LIST,0,ib->GetIndexCount()); //Read bounding box float bbMaxX = f->ReadFloat(); float bbMaxY = f->ReadFloat(); float bbMaxZ = f->ReadFloat(); float bbMinX = f->ReadFloat(); float bbMinY= f->ReadFloat(); float bbMinZ = f->ReadFloat(); DirectX::XMFLOAT3 bbMin(bbMinX,bbMinY,bbMinZ); DirectX::XMFLOAT3 bbMax(bbMaxX,bbMaxY,bbMaxZ); geo->SetBoundingBox(bbMin,bbMax); DirectX::XMFLOAT4 diffuseColor = m->ReadVector4(); DirectX::XMFLOAT4 emissiveColor = m->ReadVector4(); DirectX::XMFLOAT4 specularColor = m->ReadVector4(); float shadingmMode = m->ReadFloat(); float roughness = m->ReadFloat(); float refractiveIndex = m->ReadFloat(); roughness = 1; YumeString diffuse_tex = m->ReadString(); YumeString alpha_tex = m->ReadString(); YumeString emissive_tex = m->ReadString(); YumeString specular_tex = m->ReadString(); YumeString normal_tex = m->ReadString(); YumeString roughness_tex = m->ReadString(); SharedPtr<Material> material(new Material); if(i == 0 && modelName_ == "Models/Primitives/HighPlane.yume") { floorMaterial_ = material; specularColor = DirectX::XMFLOAT4(1,1,1,1); } if(!diffuse_tex.Compare("textures_pbr\\Sponza_Floor_diffuse.tga")) { floorMaterial_ = material; shadingmMode = 0.0f; specularColor = DirectX::XMFLOAT4(1,1,1,1); } else shadingmMode = 0.0f; if(modelName_ == "Models/DarkSouls/Ornstein/c5270outout.yume") //Whoops.. { diffuseColor = DirectX::XMFLOAT4(0,0,0,1); } material->SetShaderParameter("DiffuseColor",diffuseColor); material->SetShaderParameter("EmissiveColor",emissiveColor); material->SetShaderParameter("SpecularColor",specularColor); material->SetShaderParameter("ShadingMode",shadingmMode); material->SetShaderParameter("Roughness",roughness); material->SetShaderParameter("FloorRoughness",roughness); material->SetShaderParameter("has_diffuse_tex",true); material->SetShaderParameter("has_alpha_tex",true); material->SetShaderParameter("has_specular_tex",true); material->SetShaderParameter("has_normal_tex",true); material->SetShaderParameter("has_roughness_tex",true); if(!material->HasTexture(diffuse_tex)) material->SetShaderParameter("has_diffuse_tex",false); else material->SetTexture(MT_DIFFUSE,gYume->pResourceManager->PrepareResource<YumeTexture2D>(diffuse_tex)); if(!material->HasTexture(roughness_tex)) material->SetShaderParameter("has_roughness_tex",false); else material->SetTexture(MT_ROUGHNESS,gYume->pResourceManager->PrepareResource<YumeTexture2D>(roughness_tex)); if(!material->HasTexture(alpha_tex)) material->SetShaderParameter("has_alpha_tex",false); else material->SetTexture(MT_ALPHA,gYume->pResourceManager->PrepareResource<YumeTexture2D>(alpha_tex)); if(!material->HasTexture(specular_tex)) material->SetShaderParameter("has_specular_tex",false); else material->SetTexture(MT_SPECULAR,gYume->pResourceManager->PrepareResource<YumeTexture2D>(specular_tex)); if(!material->HasTexture(normal_tex)) material->SetShaderParameter("has_normal_tex",false); else material->SetTexture(MT_NORMAL,gYume->pResourceManager->PrepareResource<YumeTexture2D>(normal_tex)); SharedPtr<RenderBatch> batch(new RenderBatch); batch->geo_ = geo; batch->material_ = material; batches_.push_back(batch); } DirectX::XMFLOAT3 meshBbMin = f->ReadVector3(); DirectX::XMFLOAT3 meshBbMax = f->ReadVector3(); SetBoundingBox(meshBbMin,meshBbMax); return true; } void StaticModel::SetFloorRoughness(float f) { floorMaterial_->SetShaderParameter("Roughness",f); } void StaticModel::SetMaterial(MaterialPtr ptr) { for(int i=0; i < batches_.size(); ++i) batches_[i]->material_ = ptr; } void StaticModel::Initialize() { SetWorld(DirectX::XMMatrixIdentity()); } void StaticModel::UpdateBb(const DirectX::XMFLOAT3& V) { SetBoundingBox(dmin(V,GetBbMin()),dmax(V,GetBbMax())); //on LPV bb_min_ doesnt work fix } }
29.14346
110
0.699001
[ "mesh", "model" ]
3be9d70d6b3cf77ad90a6c596b923979135b1126
1,859
cpp
C++
game/server/entities/NPCs/CBabyCrab.cpp
xalalau/HLEnhanced
f108222ab7d303c9ed5a8e81269f9e949508e78e
[ "Unlicense" ]
83
2016-06-10T20:49:23.000Z
2022-02-13T18:05:11.000Z
game/server/entities/NPCs/CBabyCrab.cpp
xalalau/HLEnhanced
f108222ab7d303c9ed5a8e81269f9e949508e78e
[ "Unlicense" ]
26
2016-06-16T22:27:24.000Z
2019-04-30T19:25:51.000Z
game/server/entities/NPCs/CBabyCrab.cpp
xalalau/HLEnhanced
f108222ab7d303c9ed5a8e81269f9e949508e78e
[ "Unlicense" ]
58
2016-06-10T23:52:33.000Z
2021-12-30T02:30:50.000Z
/*** * * Copyright (c) 1996-2001, Valve LLC. All rights reserved. * * This product contains software technology licensed from Id * Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. * All Rights Reserved. * * This source code contains proprietary and confidential information of * Valve LLC and its suppliers. Access to this code is restricted to * persons who have executed a written SDK license with Valve. Any access, * use or distribution of this code by or to any unlicensed person is illegal. * ****/ #include "extdll.h" #include "util.h" #include "cbase.h" #include "Monsters.h" #include "CBabyCrab.h" LINK_ENTITY_TO_CLASS( monster_babycrab, CBabyCrab ); void CBabyCrab::Spawn( void ) { CHeadCrab::Spawn(); SetModel( "models/baby_headcrab.mdl" ); SetRenderMode( kRenderTransTexture ); SetRenderAmount( 192 ); SetSize( Vector( -12, -12, 0 ), Vector( 12, 12, 24 ) ); SetHealth( gSkillData.GetHeadcrabHealth() * 0.25 ); // less health than full grown } void CBabyCrab::Precache( void ) { PRECACHE_MODEL( "models/baby_headcrab.mdl" ); CHeadCrab::Precache(); } void CBabyCrab::UpdateYawSpeed() { SetYawSpeed( 120 ); } bool CBabyCrab::CheckRangeAttack1( float flDot, float flDist ) { if( GetFlags().Any( FL_ONGROUND ) ) { auto pGroundEntity = GetGroundEntity(); if( pGroundEntity && pGroundEntity->GetFlags().Any( FL_CLIENT | FL_MONSTER ) ) return true; // A little less accurate, but jump from closer if( flDist <= 180 && flDot >= 0.55 ) return true; } return false; } Schedule_t* CBabyCrab::GetScheduleOfType( int Type ) { switch( Type ) { case SCHED_FAIL: // If you fail, try to jump! if( m_hEnemy != NULL ) return slHCRangeAttack1Fast; break; case SCHED_RANGE_ATTACK1: { return slHCRangeAttack1Fast; } break; } return CHeadCrab::GetScheduleOfType( Type ); }
23.2375
83
0.705756
[ "vector" ]
3bf13f25bb9a786629df8b43c90bdd99f777d9d4
59,123
cpp
C++
Unix/tests/pal/test_pal.cpp
Beguiled/omi
1c824681ee86f32314f430db972e5d3938f10fd4
[ "MIT" ]
165
2016-08-18T22:06:39.000Z
2019-05-05T11:09:37.000Z
Unix/tests/pal/test_pal.cpp
snchennapragada/omi
4fa565207d3445d1f44bfc7b890f9ea5ea7b41d0
[ "MIT" ]
409
2016-08-18T20:52:56.000Z
2019-05-06T10:03:11.000Z
Unix/tests/pal/test_pal.cpp
snchennapragada/omi
4fa565207d3445d1f44bfc7b890f9ea5ea7b41d0
[ "MIT" ]
72
2016-08-23T02:30:08.000Z
2019-04-30T22:57:03.000Z
/* **============================================================================== ** ** Copyright (c) Microsoft Corporation. All rights reserved. See file LICENSE ** for license information. ** **============================================================================== */ #include <cassert> #include <cstdio> #include <string> #include <vector> #include <list> #include <iostream> #include <algorithm> #include <ut/ut.h> #include <pal/atomic.h> #include <pal/thread.h> #include <pal/tls.h> #include <pal/sleep.h> #include <pal/once.h> #include <pal/lock.h> #include <pal/cpu.h> #include <pal/shlib.h> #include <pal/slist.h> #include <pal/sem.h> #include <pal/shmem.h> #include <pal/strings.h> #include <pal/dir.h> #include <pal/file.h> #include <pal/hashmap.h> #include <pal/format.h> #include "test_pal_strings.h" using namespace std; //============================================================================== // // TestSemSize() // //============================================================================== NitsTest(TestSemSize) { /* Validate that Sem fits in a ptrdiff_t. Otherwise, the semaphore pool in * CondLock will have problems. */ NitsAssert(sizeof(Sem) <= sizeof(ptrdiff_t), PAL_T("Check Sem size")); } NitsEndTest //============================================================================== // // TestPal32Bit() // //============================================================================== #ifdef PAL_32BIT NitsTest(TestPal32Bit) { NitsAssert(sizeof(void*) == 4, PAL_T("Check 32-bit pointer size")); } NitsEndTest #endif //============================================================================== // // TestPal64Bit() // //============================================================================== #ifdef PAL_64BIT NitsTest(TestPal64Bit) { NitsAssert(sizeof(void*) == 8, PAL_T("Check 64-bit pointer size")); } NitsEndTest #endif //============================================================================== // // TestAtomic() // //============================================================================== NitsTest(TestAtomic) // Atomic_Inc() { volatile ptrdiff_t x = 0; ptrdiff_t r = Atomic_Inc(&x); TEST_ASSERT(r == 1); TEST_ASSERT(x == 1); r = Atomic_Inc(&x); TEST_ASSERT(r == 2); TEST_ASSERT(x == 2); } // Atomic_Dec() { volatile ptrdiff_t x = 2; ptrdiff_t r = Atomic_Dec(&x); TEST_ASSERT(r == 1); TEST_ASSERT(x == 1); r = Atomic_Dec(&x); TEST_ASSERT(r == 0); TEST_ASSERT(x == 0); } // Atomic_CompareAndSwap() { volatile ptrdiff_t x = 2; ptrdiff_t r = Atomic_CompareAndSwap(&x, 2, 10); TEST_ASSERT(r == 2); TEST_ASSERT(x == 10); } // Atomic_CompareAndSwap() { volatile ptrdiff_t x = 2; ptrdiff_t r = Atomic_CompareAndSwap(&x, 500, 10); TEST_ASSERT(r == 2); TEST_ASSERT(x == 2); } // Atomic_Swap() { volatile ptrdiff_t x = 100; ptrdiff_t r = Atomic_Swap(&x, 200); TEST_ASSERT(r == 100); TEST_ASSERT(x == 200); } NitsEndTest //============================================================================== // // TestThread() // //============================================================================== NITS_EXTERN_C PAL_Uint32 THREAD_API TestThread1(void* arg) { const char* name = (const char*)arg; TEST_ASSERT(strcmp(name, "TestThread1") == 0); return 1001; } NITS_EXTERN_C PAL_Uint32 THREAD_API TestThread2(void* arg) { const char* name = (const char*)arg; TEST_ASSERT(strcmp(name, "TestThread2") == 0); return 1002; } NitsTest(TestThread) Thread t1; int t1_created = PAL_FALSE; t1_created = (Thread_CreateJoinable(&t1, TestThread1, NULL, (char*)"TestThread1") == 0); TEST_ASSERT(t1_created); Thread t2; int t2_created = PAL_FALSE; t2_created = (Thread_CreateJoinable(&t2, TestThread2, NULL, (char*)"TestThread2") == 0); TEST_ASSERT(t2_created); if (t1_created) { PAL_Uint32 arg1; Thread_Join(&t1, &arg1); Thread_Destroy(&t1); TEST_ASSERT(arg1 == 1001); } if (t2_created) { PAL_Uint32 arg2; Thread_Join(&t2, &arg2); Thread_Destroy(&t2); TEST_ASSERT(arg2 == 1002); } NitsEndTest //============================================================================== // // TestTLS() // //============================================================================== NITS_EXTERN_C PAL_Uint32 THREAD_API TestTLS1(void* arg) { TLS* tls = (TLS*)arg; for (ptrdiff_t i = 0; i < 100; i++) { TLS_Set(tls, i); Sleep_Milliseconds(5); ptrdiff_t x = TLS_Get(tls); TEST_ASSERT(x == i); } return 0; } NITS_EXTERN_C PAL_Uint32 THREAD_API TestTLS2(void* arg) { TLS* tls = (TLS*)arg; for (ptrdiff_t i = 100; i < 200; i++) { TLS_Set(tls, i); Sleep_Milliseconds(5); ptrdiff_t x = TLS_Get(tls); TEST_ASSERT(x == i); } return 0; } NitsTest(TestTLS) Thread t1; int t1_created = PAL_FALSE; TLS tls; int r = TLS_Init(&tls); TEST_ASSERT(r == 0); if (r != 0) return; t1_created = (Thread_CreateJoinable(&t1, TestTLS1, NULL, &tls) == 0); TEST_ASSERT(t1_created); Thread t2; int t2_created = PAL_FALSE; t2_created = (Thread_CreateJoinable(&t2, TestTLS2, NULL, &tls) == 0); TEST_ASSERT(t2_created); Sleep_Milliseconds(10); if (t1_created) { PAL_Uint32 arg1; Thread_Join(&t1, &arg1); Thread_Destroy(&t1); } if (t2_created) { PAL_Uint32 arg2; Thread_Join(&t2, &arg2); Thread_Destroy(&t2); } TLS_Destroy(&tls); NitsEndTest //============================================================================== // // TestOnce() // //============================================================================== typedef struct _TestOnce_Data { Once once; int count; } TestOnce_Data; _Success_(return == 0) NITS_EXTERN_C int IncrementCount(_In_ void* arg, _Outptr_result_maybenull_ void** value) { TestOnce_Data* data = (TestOnce_Data*) arg; data->count++; *value = NULL; return 0; } NITS_EXTERN_C PAL_Uint32 THREAD_API TestOnce1(void* arg) { TestOnce_Data* data = (TestOnce_Data*) arg; for (ptrdiff_t i = 0; i < 100; i++) { Sleep_Milliseconds(5); Once_Invoke(&data->once, IncrementCount, data); } return 0; } NITS_EXTERN_C PAL_Uint32 THREAD_API TestOnce2(void* arg) { TestOnce_Data* data = (TestOnce_Data*) arg; for (ptrdiff_t i = 0; i < 100; i++) { Sleep_Milliseconds(5); Once_Invoke(&data->once, IncrementCount, data); } return 0; } NitsTest(TestOnce) Thread t1; int t1_created = PAL_FALSE; TestOnce_Data data = { ONCE_INITIALIZER, 0 }; t1_created = (Thread_CreateJoinable(&t1, TestOnce1, NULL, &data) == 0); TEST_ASSERT(t1_created); Thread t2; int t2_created = PAL_FALSE; t2_created = (Thread_CreateJoinable(&t2, TestOnce2, NULL, &data) == 0); TEST_ASSERT(t2_created); Sleep_Milliseconds(10); if (t1_created) { PAL_Uint32 arg1; Thread_Join(&t1, &arg1); Thread_Destroy(&t1); } if (t2_created) { PAL_Uint32 arg2; Thread_Join(&t2, &arg2); Thread_Destroy(&t2); } TEST_ASSERT(data.count == 1); NitsEndTest _Success_(return == 0) NITS_EXTERN_C int IncrementCount_FailIfCountIsZero( _In_ void* arg, _Outptr_result_maybenull_ void** value) { TestOnce_Data* data = (TestOnce_Data*) arg; *value = NULL; if ((data->count++) == 0) { return 1; } else { return 0; } } NitsTest(TestOnce_ReturnValueTest) TestOnce_Data data = { ONCE_INITIALIZER, 0 }; int ret; ret = Once_Invoke(&data.once, IncrementCount_FailIfCountIsZero, &data); NitsCompare(ret, 1, PAL_T("1st Once_Invoke should return 1")); NitsCompare(data.count, 1, PAL_T("1st Once_Invoke should set count=1")); ret = Once_Invoke(&data.once, IncrementCount_FailIfCountIsZero, &data); NitsCompare(ret, 0, PAL_T("2nd Once_Invoke should return 0")); NitsCompare(data.count, 2, PAL_T("2nd Once_Invoke should set count=2")); ret = Once_Invoke(&data.once, IncrementCount_FailIfCountIsZero, &data); NitsCompare(ret, 0, PAL_T("subsequent Once_Invoke(s) should keep returning 0")); NitsCompare(data.count, 2, PAL_T("subsequent Once_Invoke(s) should not increment count")); NitsEndTest _Success_(return == 0) NITS_EXTERN_C int IncrementCount_SlowFailIfCountIsZero( _In_ void* arg, _Outptr_result_maybenull_ void** value) { TestOnce_Data* data = (TestOnce_Data*) arg; *value = NULL; Sleep_Milliseconds(1); if ((data->count++) == 0) { return 1; } else { return 0; } } NITS_EXTERN_C PAL_Uint32 THREAD_API TestOnce_FailureRaceTest_Thread(void* arg) { TestOnce_Data* data = (TestOnce_Data*)arg; int ret; ret = Once_Invoke(&data->once, IncrementCount_SlowFailIfCountIsZero, data); NitsAssert((data->count == 1) || (data->count == 2), PAL_T("At most one failure and one success")); return (PAL_Uint32)ret; } NitsTest(TestOnce_FailureRaceTest) TestOnce_Data data = { ONCE_INITIALIZER, 0 }; Thread t1; PAL_Uint32 t1_created = PAL_FALSE; PAL_Uint32 t1_result = 0; t1_created = (Thread_CreateJoinable(&t1, TestOnce_FailureRaceTest_Thread, NULL, &data) == 0); TEST_ASSERT(t1_created); Thread t2; PAL_Uint32 t2_created = PAL_FALSE; PAL_Uint32 t2_result = 0; t2_created = (Thread_CreateJoinable(&t2, TestOnce_FailureRaceTest_Thread, NULL, &data) == 0); TEST_ASSERT(t2_created); if (t1_created) { Thread_Join(&t1, &t1_result); Thread_Destroy(&t1); } if (t2_created) { Thread_Join(&t2, &t2_result); Thread_Destroy(&t2); } if (t1_created && t2_created) { NitsAssert( ((t1_result == 0) && (t2_result == 1)) || ((t2_result == 0) && (t1_result == 1)), PAL_T("One thread should fail and the other should succeed")); } NitsEndTest //============================================================================== // // TestMutex() // //============================================================================== static Lock s_mutex = LOCK_INITIALIZER; NITS_EXTERN_C PAL_Uint32 THREAD_API TestMutex1(void* arg) { size_t* countPtr = (size_t*)arg; for (ptrdiff_t i = 0; i < 100; i++) { Lock_Acquire(&s_mutex); size_t count = *countPtr; Sleep_Milliseconds(1); count++; Sleep_Milliseconds(1); *countPtr = count; Lock_Release(&s_mutex); } return 0; } NITS_EXTERN_C PAL_Uint32 THREAD_API TestMutex2(void* arg) { size_t* countPtr = (size_t*)arg; for (ptrdiff_t i = 0; i < 100; i++) { Lock_Acquire(&s_mutex); size_t count = *countPtr; Sleep_Milliseconds(1); count++; Sleep_Milliseconds(1); *countPtr = count; Lock_Release(&s_mutex); } return 0; } NitsTest(TestMutex) { Thread t1; int t1_created = PAL_FALSE; size_t count = 0; t1_created = (Thread_CreateJoinable(&t1, TestMutex1, NULL, &count) == 0); TEST_ASSERT(t1_created); Thread t2; int t2_created = PAL_FALSE; t2_created = (Thread_CreateJoinable(&t2, TestMutex2, NULL, &count) == 0); TEST_ASSERT(t2_created); Sleep_Milliseconds(10); if (t1_created) { PAL_Uint32 arg1; Thread_Join(&t1, &arg1); Thread_Destroy(&t1); } if (t2_created) { PAL_Uint32 arg2; Thread_Join(&t2, &arg2); Thread_Destroy(&t2); } TEST_ASSERT(count == 200); } NitsEndTest NITS_EXTERN_C PAL_Uint32 THREAD_API TestLockMiniStressWorker(void* param) { static char buf1[10000]; static char buf2[10000]; Lock* lock = (Lock*)param; int i, j; for (i = -25; i < 50; i++) { for (j = -25; j < 50; j++) { Lock_Acquire(lock); if (i > 0) memcpy(buf1, buf2, i); Lock_Release(lock); if (j > 0) memcpy(buf1, buf2, j); } } return 0; } /* * This is a regression test for Win Blue Bugs #562349 * (lock corruption leading to a hang) */ NitsTest(TestLockMiniStress) { Lock lock; Thread t[10]; int r[10]; int i; Lock_Init(&lock); for (i = 0; i < 10; i++) { r[i] = Thread_CreateJoinable( t + i, TestLockMiniStressWorker, NULL, /* no thread destructor */ &lock); /* no thread parameter */ NitsCompare(r[i], 0, MI_T("Thread_CreateJoinable")); } for (i = 0; i < 10; i++) { if (r[i] == 0) { MI_Uint32 threadRet; MI_Uint32 joinRet; joinRet = Thread_Join(t + i, &threadRet); NitsCompare(joinRet, 0, MI_T("Thread_Join")); NitsCompare(threadRet, 0, MI_T("TestLockMiniStressWorker")); Thread_Destroy(t + i); } } } NitsEndTest //============================================================================== // // TestReadWriteLock() // //============================================================================== /* ATTN: broken */ #if 0 static ReadWriteLock s_readWriteLock = READWRITELOCK_INITIALIZER; static unsigned long s_readWriteLockData = 0; NITS_EXTERN_C PAL_Uint32 THREAD_API TestReadWriteLock_Writer(void* arg) { for (ptrdiff_t i = 0; i < 100; i++) { ReadWriteLock_AcquireWrite(&s_readWriteLock); s_readWriteLockData = 1; Thread_Yield(); Sleep_Milliseconds(10); s_readWriteLockData = 0; ReadWriteLock_ReleaseWrite(&s_readWriteLock); } return 0; } NITS_EXTERN_C PAL_Uint32 THREAD_API TestReadWriteLock_Reader(void* arg) { for (ptrdiff_t i = 0; i < 100; i++) { ReadWriteLock_AcquireRead(&s_readWriteLock); TEST_ASSERT(s_readWriteLockData == 0); ReadWriteLock_ReleaseRead(&s_readWriteLock); } return 0; } NitsTest(TestReadWriteLock) { Thread t1; if (Thread_CreateJoinable(&t1, TestReadWriteLock_Writer, NULL) != 0) TEST_ASSERT(false); Thread t2; if (Thread_CreateJoinable(&t2, TestReadWriteLock_Reader, NULL) != 0) TEST_ASSERT(false); Sleep_Milliseconds(10); PAL_Uint32 arg1; Thread_Join(&t1, &arg1); Thread_Destroy(&t1); PAL_Uint32 arg2; Thread_Join(&t2, &arg2); Thread_Destroy(&t2); } NitsEndTest #endif //============================================================================== // // TestCachedLock() // //============================================================================== /* ATTN: broken */ #if 0 static CachedLock s_cachedLock; NITS_EXTERN_C PAL_Uint32 THREAD_API TestCachedLock1(void* arg) { size_t* countPtr = (size_t*)arg; for (ptrdiff_t i = 0; i < 100; i++) { CachedLock_AcquireWrite(&s_cachedLock); size_t count = *countPtr; Sleep_Milliseconds(1); count++; Sleep_Milliseconds(1); *countPtr = count; CachedLock_ReleaseWrite(&s_cachedLock); } return 0; } NITS_EXTERN_C PAL_Uint32 THREAD_API TestCachedLock2(void* arg) { size_t* countPtr = (size_t*)arg; for (ptrdiff_t i = 0; i < 100; i++) { CachedLock_AcquireWrite(&s_cachedLock); size_t count = *countPtr; Sleep_Milliseconds(1); count++; Sleep_Milliseconds(1); *countPtr = count; CachedLock_ReleaseWrite(&s_cachedLock); } return 0; } NitsTest(TestCachedLock) { Thread t1; size_t count = 0; CachedLock_Init(&s_cachedLock, 0); if (Thread_CreateJoinable(&t1, TestCachedLock1, &count) != 0) TEST_ASSERT(false); Thread t2; if (Thread_CreateJoinable(&t2, TestCachedLock2, &count) != 0) TEST_ASSERT(false); Sleep_Milliseconds(10); PAL_Uint32 arg1; Thread_Join(&t1, &arg1); Thread_Destroy(&t1); PAL_Uint32 arg2; Thread_Join(&t2, &arg2); Thread_Destroy(&t2); TEST_ASSERT(count == 200); CachedLock_Destroy(&s_cachedLock); } NitsEndTest #endif //============================================================================== // // TestRecursiveLock() // //============================================================================== static RecursiveLock s_recursiveLock = RECURSIVELOCK_INITIALIZER; NITS_EXTERN_C PAL_Uint32 THREAD_API TestRecursiveLock1(void* arg) { size_t* countPtr = (size_t*)arg; for (ptrdiff_t i = 0; i < 100; i++) { RecursiveLock_Acquire(&s_recursiveLock); size_t count = *countPtr; Sleep_Milliseconds(1); count++; Sleep_Milliseconds(1); *countPtr = count; RecursiveLock_Release(&s_recursiveLock); } return 0; } NITS_EXTERN_C PAL_Uint32 THREAD_API TestRecursiveLock2(void* arg) { size_t* countPtr = (size_t*)arg; for (ptrdiff_t i = 0; i < 100; i++) { RecursiveLock_Acquire(&s_recursiveLock); size_t count = *countPtr; Sleep_Milliseconds(1); count++; Sleep_Milliseconds(1); *countPtr = count; RecursiveLock_Release(&s_recursiveLock); } return 0; } NitsTest(TestRecursiveLock) { Thread t1; int t1_created = PAL_FALSE; size_t count = 0; t1_created = (Thread_CreateJoinable(&t1, TestRecursiveLock1, NULL, &count) == 0); TEST_ASSERT(t1_created); Thread t2; int t2_created = PAL_FALSE; t2_created = (Thread_CreateJoinable(&t2, TestRecursiveLock2, NULL, &count) == 0); TEST_ASSERT(t2_created); Sleep_Milliseconds(10); if (t1_created) { PAL_Uint32 arg1; Thread_Join(&t1, &arg1); Thread_Destroy(&t1); } if (t2_created) { PAL_Uint32 arg2; Thread_Join(&t2, &arg2); Thread_Destroy(&t2); } TEST_ASSERT(count == 200); } NitsEndTest //============================================================================== // // TestCond() // //============================================================================== /* ATTN: broken */ #if 0 class Queue { public: Queue() { Lock_Init(&m_lock); m_size = 0; m_notEmpty = 0xDEADBEEF; m_notFull = 0xF00DFACE; } ~Queue() { } void Put(unsigned int x) { // Wait for size != SIZE (not full): for (;;) { CondLock_Wait(m_notFull, &m_size, SIZE, SPINCOUNT); Lock_Acquire(&m_lock); if (m_size == SIZE) { Lock_Release(&m_lock); continue; } else { m_data.push_back(x); m_size++; Lock_Release(&m_lock); CondLock_Signal(m_notEmpty); break; } } } void Get(unsigned int& x) { // Wait for size != 0 (not empty): for (;;) { CondLock_Wait(m_notEmpty, &m_size, 0, SPINCOUNT); Lock_Acquire(&m_lock); if (m_size == 0) { Lock_Release(&m_lock); continue; } else { x = m_data.front(); m_data.pop_front(); m_size--; Lock_Release(&m_lock); CondLock_Signal(m_notFull); break; } } } private: enum { SIZE = 100 }; Lock m_lock; ptrdiff_t m_notEmpty; ptrdiff_t m_notFull; ptrdiff_t m_size; static const size_t SPINCOUNT; list<unsigned int> m_data; }; const size_t Queue::SPINCOUNT = CONDLOCK_DEFAULT_SPINCOUNT; static const size_t NREADERS = 20; static const size_t NPUTS = 10000; static ptrdiff_t s_sum = 0; static Lock s_sumLock = 0; NITS_EXTERN_C PAL_Uint32 THREAD_API TestCondReader(void* arg) { Queue* queue = (Queue*)arg; for (;;) { unsigned int x; queue->Get(x); if (x == 0) break; Lock_Acquire(&s_sumLock); s_sum += x; Lock_Release(&s_sumLock); } printf("TestCondReader() done\n"); return 0; } NITS_EXTERN_C PAL_Uint32 THREAD_API TestCondWriter(void* arg) { Queue* queue = (Queue*)arg; for (unsigned int i = 1; i <= NPUTS; i++) { queue->Put(i); } printf("TestCondWriter() closing down readers\n"); for (size_t i = 0; i < NREADERS; i++) { queue->Put(0); } printf("TestCondWriter() done\n"); return 0; } NitsTest(TestCond) { // Create the queue: Queue queue; // Calculate the expected sum: static ptrdiff_t expectedSum = 0; for (unsigned int i = 1; i <= NPUTS; i++) expectedSum += i; // Create writer thread: Thread t1; if (Thread_CreateJoinable(&t1, TestCondWriter, &queue) != 0) TEST_ASSERT(false); // Create reader threads: vector<Thread> readers; for (size_t i = 0; i < NREADERS; i++) { Thread t; if (Thread_CreateJoinable(&t, TestCondReader, &queue) != 0) TEST_ASSERT(false); readers.push_back(t); } // Join with writer: PAL_Uint32 arg1; Thread_Join(&t1, &arg1); Thread_Destroy(&t1); // Join with readers: for (size_t i = 0; i < NREADERS; i++) { PAL_Uint32 arg2; Thread_Join(&readers[i], &arg2); Thread_Destroy(&readers[i]); } // Verify that the sum is right: TEST_ASSERT(s_sum == expectedSum); } NitsEndTest #endif //============================================================================== // // TestCPU() // //============================================================================== NitsTest(TestCPU) int count = CPU_GetCount(); TEST_ASSERT(count >= 1); int current = CPU_GetCurrent(); TEST_ASSERT(current >= 0); if (count == 1) TEST_ASSERT(current == 0); PAL_Datetime now; int result = CPU_GetLocalTimestamp(&now); TEST_ASSERT(result == 0); TEST_ASSERT(now.isTimestamp == PAL_TRUE); TEST_ASSERT(now.u.timestamp.year >= 2012); TEST_ASSERT(now.u.timestamp.month >= 1); TEST_ASSERT(now.u.timestamp.month <= 12); TEST_ASSERT(now.u.timestamp.day <= 31); TEST_ASSERT(now.u.timestamp.day >= 1); NitsEndTest //============================================================================== // // TestShlib() // //============================================================================== /* ATTN: fix this test */ #if 0 static void TestShlib() { // ATTN: Shlib* shlib = Shlib_Open(CONFIG_LIBDIR "/libtestshlib.so"); TEST_ASSERT(shlib != NULL); typedef const char* (*Function)(); Function func = (Function)Shlib_Sym(shlib, "TestShlib"); TEST_ASSERT(func != NULL); const char* str = (*func)(); TEST_ASSERT(strcmp(str, "TestShlib") == 0); } #endif //============================================================================== // // TestSList() // //============================================================================== static const int NINTEGERS = 10000; struct IntegerEntry { SListEntry entry; int x; }; NITS_EXTERN_C PAL_Uint32 THREAD_API TestListPush(void* arg) { SListHead* head = (SListHead*)arg; for (int i = 0; i < NINTEGERS; i++) { IntegerEntry* p = new IntegerEntry; p->x = i; SList_PushAtomic(head, &p->entry); } return 0; } NITS_EXTERN_C PAL_Uint32 THREAD_API TestListPop(void* arg) { SListHead* head = (SListHead*)arg; for (int i = 0; i < NINTEGERS; i++) { IntegerEntry* p = (IntegerEntry*)SList_PopAtomic(head); TEST_ASSERT(p != NULL); if (p) delete p; } return 0; } NitsTest(TestSList) /* Test push */ { Thread t1; int t1_created = PAL_FALSE; SListHead head; SList_Init(&head); t1_created = (Thread_CreateJoinable(&t1, TestListPush, NULL, &head) == 0); TEST_ASSERT(t1_created); Thread t2; int t2_created = PAL_FALSE; t2_created = (Thread_CreateJoinable(&t2, TestListPush, NULL, &head) == 0); TEST_ASSERT(t2_created); if (t1_created) { PAL_Uint32 arg1; Thread_Join(&t1, &arg1); Thread_Destroy(&t1); } if (t2_created) { PAL_Uint32 arg2; Thread_Join(&t2, &arg2); Thread_Destroy(&t2); } // Check the list: int expect = 0; for (int i = 0; i < NINTEGERS; i++) { expect += i; expect += i; } SListEntry* first = SList_FlushAtomic(&head); int total = 0; size_t size = 0; for (SListEntry* p = first; p; ) { SListEntry* next = SList_Next(p); IntegerEntry* entry = (IntegerEntry*)p; total += entry->x; delete entry; p = next; size++; } TEST_ASSERT(size == 2 * NINTEGERS); TEST_ASSERT(expect == total); } /* Test pop */ { SListHead head; SList_Init(&head); // Push phase: { Thread t1; int t1_created = PAL_FALSE; t1_created = (Thread_CreateJoinable(&t1, TestListPush, NULL, &head) == 0); TEST_ASSERT(t1_created); Thread t2; int t2_created = PAL_FALSE; t2_created = (Thread_CreateJoinable(&t2, TestListPush, NULL, &head) == 0); TEST_ASSERT(t2_created); if (t1_created) { PAL_Uint32 arg1; Thread_Join(&t1, &arg1); Thread_Destroy(&t1); } if (t2_created) { PAL_Uint32 arg2; Thread_Join(&t2, &arg2); Thread_Destroy(&t2); } } // Pop phase: { Thread t1; int t1_created = PAL_FALSE; t1_created = (Thread_CreateJoinable(&t1, TestListPop, NULL, &head) == 0); TEST_ASSERT(t1_created); Thread t2; int t2_created = PAL_FALSE; t2_created = (Thread_CreateJoinable(&t2, TestListPop, NULL, &head) == 0); TEST_ASSERT(t2_created); if (t1_created) { PAL_Uint32 arg1; Thread_Join(&t1, &arg1); Thread_Destroy(&t1); } if (t2_created) { PAL_Uint32 arg2; Thread_Join(&t2, &arg2); Thread_Destroy(&t2); } } // Check that the list is empty: SListEntry* first = SList_FlushAtomic(&head); TEST_ASSERT(first == NULL); } NitsEndTest //============================================================================== // // TestSem() // //============================================================================== struct TestSemData { Sem sem; unsigned int sum; unsigned int count; }; NITS_EXTERN_C PAL_Uint32 THREAD_API TestSemThread(void* arg) { TestSemData* data = (TestSemData*)arg; for (unsigned int i = 0; i < data->count; i++) { Sem_Wait(&data->sem); size_t tmp = data->sum; Sleep_Milliseconds(1); tmp++; Sleep_Milliseconds(1); data->sum = (unsigned int)tmp; Sleep_Milliseconds(1); Sem_Post(&data->sem, 1); } return 0; } NitsTest(TestSem) { Thread t1; int t1_created = PAL_FALSE; TestSemData data; data.sum = 0; data.count = 0; int r = Sem_Init(&data.sem, SEM_USER_ACCESS_DEFAULT, 1); if(!TEST_ASSERT(r == 0)) NitsReturn; t1_created = (Thread_CreateJoinable(&t1, TestSemThread, NULL, &data) == 0); TEST_ASSERT(t1_created); Thread t2; int t2_created = PAL_FALSE; t2_created = (Thread_CreateJoinable(&t2, TestSemThread, NULL, &data) == 0); TEST_ASSERT(t2_created); if (t1_created) { PAL_Uint32 arg1; Thread_Join(&t1, &arg1); Thread_Destroy(&t1); } if (t2_created) { PAL_Uint32 arg2; Thread_Join(&t2, &arg2); Thread_Destroy(&t2); } Sem_Destroy(&data.sem); // Check the result: TEST_ASSERT(data.sum == 2 * data.count); } NitsEndTest //============================================================================== // // TestNamedSem() // //============================================================================== # define SEMAPHORE_NAME PAL_T(CONFIG_SHMNAMELOCALPREFIX) PAL_T("PALTestSem") struct TestNamedSemData { unsigned int sum; unsigned int count; }; NITS_EXTERN_C PAL_Uint32 THREAD_API TestNamedSemThread(void* arg) { TestNamedSemData* data = (TestNamedSemData*)arg; // Open or create the name semaphore: NamedSem sem; const PAL_Char *semaphoreName = SEMAPHORE_NAME; int r = NamedSem_Open(&sem, SEM_USER_ACCESS_DEFAULT, 1, semaphoreName, NAMEDSEM_FLAG_CREATE); TEST_ASSERT(r == 0); if (r != 0) return 0; for (unsigned int i = 0; i < data->count; i++) { NamedSem_Wait(&sem); size_t tmp = data->sum; Sleep_Milliseconds(1); tmp++; Sleep_Milliseconds(1); data->sum = (unsigned int)tmp; Sleep_Milliseconds(1); NamedSem_Post(&sem, 1); } NamedSem_Close(&sem); NamedSem_Destroy(&sem); return 0; } NitsTest(TestNamedSem) { Thread t1; int t1_created = PAL_FALSE; TestNamedSemData data; data.sum = 0; data.count = 0; t1_created = (Thread_CreateJoinable(&t1, TestNamedSemThread, NULL, &data) == 0); TEST_ASSERT(t1_created); Thread t2; int t2_created = PAL_FALSE; t2_created = (Thread_CreateJoinable(&t2, TestNamedSemThread, NULL, &data) == 0); TEST_ASSERT(t2_created); if (t1_created) { PAL_Uint32 arg1; Thread_Join(&t1, &arg1); Thread_Destroy(&t1); } if (t2_created) { PAL_Uint32 arg2; Thread_Join(&t2, &arg2); Thread_Destroy(&t2); } // Check the result: TEST_ASSERT(data.sum == 2 * data.count); } NitsEndTest //============================================================================== // // TestShmem() // //============================================================================== # define SHMEM_NAME PAL_T(CONFIG_SHMNAMELOCALPREFIX PAL_T("PALTestShmem")) typedef struct _TestShmemData { unsigned long sum; } TestShmemData; NITS_EXTERN_C PAL_Uint32 THREAD_API TestShmemThread(void* arg) { TestShmemData* data = (TestShmemData*)arg; Shmem shmem; const PAL_Char *shmemName = SHMEM_NAME; // Get the size size of the shared memory: size_t size = 16 * Shmem_Granularity(); // Open the shared memory segment: int r = Shmem_Open(&shmem, shmemName, SHMEM_ACCESS_READWRITE, SHMEM_USER_ACCESS_DEFAULT, size); TEST_ASSERT(r == 0); // Map a shared memory region: unsigned char* p = (unsigned char*)Shmem_Map( &shmem, SHMEM_ACCESS_READWRITE, 0, size); TEST_ASSERT(p != NULL); // Write some data to the shared memory: for (size_t i = 0; i < size; i++) { TEST_ASSERT(p[i] == i % 256); data->sum += p[i]; p[i] = 0xDD; } // Unmap the shared memory: Shmem_Unmap(&shmem, p, size); // Close the shared memory: Shmem_Close(&shmem); return 0; } NitsTest(TestShmem) { Thread t; int t_created = PAL_FALSE; Shmem shmem; const PAL_Char *shmemName = SHMEM_NAME; size_t size = 16 * Shmem_Granularity(); // Open the shared memory segment: int r = Shmem_Open(&shmem, shmemName, SHMEM_ACCESS_READWRITE, SHMEM_USER_ACCESS_DEFAULT, size); TEST_ASSERT(r == 0); // Map a shared memory region: unsigned char* p = (unsigned char*)Shmem_Map( &shmem, SHMEM_ACCESS_READWRITE, 0, size); TEST_ASSERT(p != NULL); memset(p, 0xAA, size); // Write some data to the shared memory: unsigned long sum = 0; for (size_t i = 0; i < size; i++) { p[i] = i % 256; sum += p[i]; } // Unmap the shared memory: Shmem_Unmap(&shmem, p, size); // Create the other thread: TestShmemData data; data.sum = 0; t_created = (Thread_CreateJoinable(&t, TestShmemThread, NULL, &data) == 0); TEST_ASSERT(t_created); // Join with the other thread: if (t_created) { PAL_Uint32 arg1; Thread_Join(&t, &arg1); Thread_Destroy(&t); } p = (unsigned char*)Shmem_Map( &shmem, SHMEM_ACCESS_READWRITE, 0, size); TEST_ASSERT(p != NULL); // Compare the sums: TEST_ASSERT(data.sum == sum); // The other thread should have cleared the memory (to 0xDD's): for (size_t i = 0; i < size; i++) { TEST_ASSERT(p[i] == 0xDD); } // Unmap the shared memory: Shmem_Unmap(&shmem, p, size); // Close the shared memory: Shmem_Close(&shmem); } NitsEndTest //============================================================================== // // TestStrings() // //============================================================================== #define FUNCTION TestStringsStr #define CHAR char #define STRCMP Strcmp #define STRLCPY Strlcpy #define STRLCAT Strlcat #define LIT(STR) STR #include "TestStringsAux.h" #undef FUNCTION #undef CHAR #undef STRCMP #undef STRLCPY #undef STRLCAT #undef LIT #define FUNCTION TestStringsTcs #define CHAR TChar #define STRCMP Tcscmp #define STRLCPY Tcslcpy #define STRLCAT Tcslcat #define LIT(STR) PAL_T(STR) #include "TestStringsAux.h" #undef FUNCTION #undef CHAR #undef STRCMP #undef STRLCPY #undef STRLCAT #undef LIT NitsTest(TestStrings) { TestStringsStr(); TestStringsTcs(); } NitsEndTest NitsTest(TestStrings_ToUpper) { TEST_ASSERT(PAL_tolower(PAL_T('a')) == PAL_T('a')); TEST_ASSERT(PAL_tolower(PAL_T('A')) == PAL_T('a')); TEST_ASSERT(PAL_tolower(PAL_T('z')) == PAL_T('z')); TEST_ASSERT(PAL_tolower(PAL_T('Z')) == PAL_T('z')); /* characters before 'a','A' and after 'z','Z' */ TEST_ASSERT(PAL_tolower(PAL_T('`')) == PAL_T('`')); TEST_ASSERT(PAL_tolower(PAL_T('@')) == PAL_T('@')); TEST_ASSERT(PAL_tolower(PAL_T('{')) == PAL_T('{')); TEST_ASSERT(PAL_tolower(PAL_T('[')) == PAL_T('[')); } NitsEndTest //============================================================================== // // TestDir() // //============================================================================== const char* TmpName( _Pre_writable_size_(PAL_MAX_PATH_SIZE) char buf[PAL_MAX_PATH_SIZE], const char* suffix) { const char TMPDIR[] = "/tmp"; Strlcpy(buf, TMPDIR, PAL_MAX_PATH_SIZE); Strlcat(buf, suffix, PAL_MAX_PATH_SIZE); return buf; } static void EnsureTmpExists() { } static void TestDirCleanup() { char buf[PAL_MAX_PATH_SIZE]; Rmdir(TmpName(buf, "/pal/TestDir/dir1")); Rmdir(TmpName(buf, "/pal/TestDir/dir2")); File_Remove(TmpName(buf, "/pal/TestDir/file1")); File_Remove(TmpName(buf, "/pal/TestDir/file2")); File_Remove(TmpName(buf, "/pal/TestDir/file3")); Rmdir(TmpName(buf, "/pal/TestDir")); Rmdir(TmpName(buf, "/pal")); } NitsTest(TestDir) { char buf[PAL_MAX_PATH_SIZE]; EnsureTmpExists(); TestDirCleanup(); // Create directories and files: TEST_ASSERT(Mkdir(TmpName(buf, "/pal/"), 0700) == 0); TEST_ASSERT(Mkdir(TmpName(buf, "/pal/TestDir"), 0700) == 0); TEST_ASSERT(Mkdir(TmpName(buf, "/pal/TestDir/dir1"), 0700) == 0); TEST_ASSERT(Mkdir(TmpName(buf, "/pal/TestDir/dir2"), 0700) == 0); TEST_ASSERT(File_Touch(TmpName(buf, "/pal/TestDir/file1")) == 0); TEST_ASSERT(File_Touch(TmpName(buf, "/pal/TestDir/file2")) == 0); TEST_ASSERT(File_Touch(TmpName(buf, "/pal/TestDir/file3")) == 0); Dir* dir = Dir_Open(TmpName(buf, "/pal/TestDir")); TEST_ASSERT(dir != NULL); if (dir != NULL) { vector<string> names1; for (;;) { DirEnt* ent = Dir_Read(dir); if (!ent) break; if (strcmp(ent->name, "..") == 0 || strcmp(ent->name, ".") == 0) continue; names1.push_back(ent->name); } sort(names1.begin(), names1.end()); vector<string> names2; names2.push_back("dir1"); names2.push_back("dir2"); names2.push_back("file1"); names2.push_back("file2"); names2.push_back("file3"); TEST_ASSERT(names1.size() == 5); TEST_ASSERT(names2.size() == 5); TEST_ASSERT(names1 == names2); Dir_Close(dir); } TestDirCleanup(); } NitsEndTest //============================================================================== // // TestFile() // //============================================================================== NitsTest(TestFile) { const char* FILENAME = "/PalTestFile.txt"; char buf[PAL_MAX_PATH_SIZE]; EnsureTmpExists(); File_Remove(TmpName(buf, FILENAME)); // Create a file with the contents "hello" { FILE* fp = File_Open(TmpName(buf, FILENAME), "w"); TEST_ASSERT(fp != NULL); size_t n = fwrite("hello", 1, 5, fp); TEST_ASSERT(n == 5); File_Close(fp); } // Open file and read contents: { FILE* fp = File_Open(TmpName(buf, FILENAME), "r"); TEST_ASSERT(fp != NULL); char data[1024]; size_t n = fread(data, 1, sizeof(data), fp); TEST_ASSERT(n == 5); TEST_ASSERT(memcmp(data, "hello", 5) == 0); File_Close(fp); } // Clean up: File_Remove(TmpName(buf, FILENAME)); } NitsEndTest //============================================================================== // // TestHashMap() // //============================================================================== typedef struct _TestBucket /* derives from HashBucket */ { struct _TestBucket* next; PAL_Char* key; long data; } TestBucket; NITS_EXTERN_C size_t TestHash( const HashBucket* bucket_) { /* Note: this algorithm has a poor distribution */ TestBucket* bucket = (TestBucket*)bucket_; size_t h = 0; PAL_Char* key = bucket->key; while (*key) { h += 5 * *key++; } return h; } NITS_EXTERN_C int TestEqual( const HashBucket* bucket1_, const HashBucket* bucket2_) { TestBucket* bucket1 = (TestBucket*)bucket1_; TestBucket* bucket2 = (TestBucket*)bucket2_; return Tcscmp(bucket1->key, bucket2->key) == 0; } NITS_EXTERN_C void TestRelease( HashBucket* bucket_) { TestBucket* bucket = (TestBucket*)bucket_; PAL_Free(bucket->key); PAL_Free(bucket); } NitsTest(TestHashMap1) { HashMap map; int r; TestBucket* b; r = HashMap_Init(&map, 1, TestHash, TestEqual, TestRelease); TEST_ASSERT(r == 0); /* Insert some buckets */ { /* Insert RED=1 */ { b = (TestBucket*)PAL_Calloc(1, sizeof(TestBucket)); if(TEST_ASSERT(b != 0)) { b->key = PAL_Tcsdup(PAL_T("RED")); b->data = 1; r = HashMap_Insert(&map, (HashBucket*)b); TEST_ASSERT(r == 0); } } /* Insert GREEN=2 */ { b = (TestBucket*)PAL_Calloc(1, sizeof(TestBucket)); if(TEST_ASSERT(b != 0)) { b->key = PAL_Tcsdup(PAL_T("GREEN")); b->data = 2; r = HashMap_Insert(&map, (HashBucket*)b); TEST_ASSERT(r == 0); } } /* Insert BLUE=3 */ { b = (TestBucket*)PAL_Calloc(1, sizeof(TestBucket)); if(TEST_ASSERT(b != 0)) { b->key = PAL_Tcsdup(PAL_T("BLUE")); b->data = 3; r = HashMap_Insert(&map, (HashBucket*)b); TEST_ASSERT(r == 0); /* Insert BLUE=3 again (should fail) */ r = HashMap_Insert(&map, (HashBucket*)b); TEST_ASSERT(r == 1); } } /* Find RED=1 */ { TestBucket key; key.key = (PAL_Char*)PAL_T("RED"); b = (TestBucket*)HashMap_Find(&map, (const HashBucket*)&key); if(TEST_ASSERT(b != 0)) { TEST_ASSERT(Tcscmp(b->key, PAL_T("RED")) == 0); TEST_ASSERT(b->data == 1); } } /* Find GREEN=2 */ { TestBucket key; key.key = (PAL_Char*)PAL_T("GREEN"); b = (TestBucket*)HashMap_Find(&map, (const HashBucket*)&key); if(TEST_ASSERT(b != 0)) { TEST_ASSERT(Tcscmp(b->key, PAL_T("GREEN")) == 0); TEST_ASSERT(b->data == 2); } } /* Find BLUE=3 */ { TestBucket key; key.key = (PAL_Char*)PAL_T("BLUE"); b = (TestBucket*)HashMap_Find(&map, (const HashBucket*)&key); if(TEST_ASSERT(b != 0)) { TEST_ASSERT(Tcscmp(b->key, PAL_T("BLUE")) == 0); TEST_ASSERT(b->data == 3); } } /* Find YELLOW=4 (should fail) */ { TestBucket key; key.key = (PAL_Char*)PAL_T("YELLOW"); b = (TestBucket*)HashMap_Find(&map, (const HashBucket*)&key); TEST_ASSERT(b == 0); } /* Remove RED */ { TestBucket key; key.key = (PAL_Char*)PAL_T("RED"); r = HashMap_Remove(&map, (const HashBucket*)&key); TEST_ASSERT(r == 0); /* Remove should fail now */ r = HashMap_Remove(&map, (const HashBucket*)&key); TEST_ASSERT(r == -1); } /* Remove GREEN */ { TestBucket key; key.key = (PAL_Char*)PAL_T("GREEN"); r = HashMap_Remove(&map, (const HashBucket*)&key); TEST_ASSERT(r == 0); /* Remove should fail now */ r = HashMap_Remove(&map, (const HashBucket*)&key); TEST_ASSERT(r == -1); } /* Remove BLUE */ { TestBucket key; key.key = (PAL_Char*)PAL_T("BLUE"); r = HashMap_Remove(&map, (const HashBucket*)&key); TEST_ASSERT(r == 0); /* Remove should fail now */ r = HashMap_Remove(&map, (const HashBucket*)&key); TEST_ASSERT(r == -1); } /* Remove YELLOW (should fail) */ { TestBucket key; key.key = (PAL_Char*)PAL_T("YELLOW"); r = HashMap_Remove(&map, (const HashBucket*)&key); TEST_ASSERT(r == -1); } } /* Release all the memroy */ HashMap_Destroy(&map); } NitsEndTest NitsTest(TestHashMap2) { HashMap map; int r; size_t i; const size_t N = 10000; /* Create the hash map */ r = HashMap_Init(&map, 63, TestHash, TestEqual, TestRelease); TEST_ASSERT(r == 0); /* Insert N buckets into hash map */ for (i = 0; i < N; i++) { PAL_Char buf[32]; TestBucket* b; Stprintf(buf, PAL_COUNT(buf), PAL_T("%u"), (unsigned int)i); b = (TestBucket*)PAL_Calloc(1, sizeof(TestBucket)); TEST_ASSERT(b != 0); if (b == 0) NitsReturn; b->key = PAL_Tcsdup(buf); b->data = (long)i; r = HashMap_Insert(&map, (HashBucket*)b); TEST_ASSERT(r == 0); } /* Verify that each number is in the hash map */ for (i = 0; i < N; i++) { PAL_Char buf[32]; TestBucket* b; TestBucket kb; kb.key = buf; Stprintf(buf, PAL_COUNT(buf), PAL_T("%u"), (unsigned int)i); /* Find it */ b = (TestBucket*)HashMap_Find(&map, (const HashBucket*)&kb); TEST_ASSERT(b != 0); /* Check it */ TEST_ASSERT(Tcscmp(b->key, buf) == 0); } /* Delete all the buckets */ for (i = 0; i < N; i++) { PAL_Char buf[32]; TestBucket kb; int r; kb.key = buf; Stprintf(buf, PAL_COUNT(buf), PAL_T("%u"), (unsigned int)i); /* Find it */ r = HashMap_Remove(&map, (const HashBucket*)&kb); TEST_ASSERT(r == 0); } /* Release all the memroy */ HashMap_Destroy(&map); } NitsEndTest NitsTest(TestHashMap2_preallocated) { HashMap map; int r; size_t i; const size_t N = 10000; void* hashMapBuckets[63]; /* Create the hash map */ HashMap_Construct(&map, 63, hashMapBuckets, TestHash, TestEqual, TestRelease); /* Insert N buckets into hash map */ for (i = 0; i < N; i++) { PAL_Char buf[32]; TestBucket* b; Stprintf(buf, PAL_COUNT(buf), PAL_T("%u"), (unsigned int)i); b = (TestBucket*)PAL_Calloc(1, sizeof(TestBucket)); TEST_ASSERT(b != 0); if (b == 0) NitsReturn; b->key = PAL_Tcsdup(buf); b->data = (long)i; r = HashMap_Insert(&map, (HashBucket*)b); TEST_ASSERT(r == 0); } /* Verify that each number is in the hash map */ for (i = 0; i < N; i++) { PAL_Char buf[32]; TestBucket* b; TestBucket kb; kb.key = buf; Stprintf(buf, PAL_COUNT(buf), PAL_T("%u"), (unsigned int)i); /* Find it */ b = (TestBucket*)HashMap_Find(&map, (const HashBucket*)&kb); TEST_ASSERT(b != 0); /* Check it */ TEST_ASSERT(Tcscmp(b->key, buf) == 0); } /* Delete all the buckets */ for (i = 0; i < N; i++) { PAL_Char buf[32]; TestBucket kb; int r; kb.key = buf; Stprintf(buf, PAL_COUNT(buf), PAL_T("%u"), (unsigned int)i); /* Find it */ r = HashMap_Remove(&map, (const HashBucket*)&kb); TEST_ASSERT(r == 0); } /* Release all the memroy */ HashMap_Destroy(&map); } NitsEndTest NitsTest(TestHashMap_HashProc_PalStringCaseInsensitive) { TEST_ASSERT( HashMap_HashProc_PalStringCaseInsensitive(PAL_T("")) == HashMap_HashProc_PalStringCaseInsensitive(PAL_T(""))); TEST_ASSERT( HashMap_HashProc_PalStringCaseInsensitive(PAL_T("foo")) == HashMap_HashProc_PalStringCaseInsensitive(PAL_T("foo"))); TEST_ASSERT( HashMap_HashProc_PalStringCaseInsensitive(PAL_T("fooBARbaz")) == HashMap_HashProc_PalStringCaseInsensitive(PAL_T("FOObarBAZ"))); TEST_ASSERT( HashMap_HashProc_PalStringCaseInsensitive(PAL_T("foo")) != HashMap_HashProc_PalStringCaseInsensitive(PAL_T("bar"))); } NitsEndTest NitsTest(TestHashMap_HashProc_AnsiString) { TEST_ASSERT( HashMap_HashProc_AnsiString("") == HashMap_HashProc_AnsiString("")); TEST_ASSERT( HashMap_HashProc_AnsiString("foo") == HashMap_HashProc_AnsiString("foo")); TEST_ASSERT( HashMap_HashProc_AnsiString("fooBARbaz") != HashMap_HashProc_AnsiString("FOObarBAZ")); TEST_ASSERT( HashMap_HashProc_AnsiString("foo") != HashMap_HashProc_AnsiString("bar")); } NitsEndTest //============================================================================== // // Tests for format.placeholders.h // - PAL_PRItstr // - PAL_PRI64d // //============================================================================== NitsTest(TestFormat_64bitFormatQualifiers_d) { TChar buf[1024] = {0}; Stprintf( buf, PAL_COUNT(buf), PAL_T("%") PAL_T(PAL_PRId64), PAL_SINT64_MIN); TEST_ASSERT(Tcscmp(buf, PAL_T("-9223372036854775808")) == 0); } NitsEndTest NitsTest(TestFormat_64bitFormatQualifiers_u) { TChar buf[1024] = {0}; Stprintf( buf, PAL_COUNT(buf), PAL_T("%") PAL_T(PAL_PRIu64), PAL_UINT64_MAX); TEST_ASSERT(Tcscmp(buf, PAL_T("18446744073709551615")) == 0); } NitsEndTest NitsTest(TestFormat_PalCharSpecifier) { TChar buf[1024] = {0}; Stprintf( buf, PAL_COUNT(buf), PAL_T("foo=%") PAL_T(PAL_PRItstr), PAL_T("bar")); TEST_ASSERT(Tcscmp(buf, PAL_T("foo=bar")) == 0); } NitsEndTest //============================================================================== // // Tests for format.c / format.h // - Stprintf // - Stprintf_StrDup // - Stprintf_CultureInvariant // - Stscanf // //============================================================================== NitsTest(TestFormat_Stprintf) { TChar buf[1024]; Stprintf( buf, PAL_COUNT(buf), PAL_T("%T %s"), tcs(PAL_T("Red")), scs("Blue")); TEST_ASSERT(Tcscmp(buf, PAL_T("Red Blue")) == 0); } NitsEndTest NitsTest(TestFormat_Stprintf_Strdup) { TChar* result = NULL; result = Stprintf_StrDup(PAL_T("test = %d"), 12345); TEST_ASSERT(result != NULL); if (result != NULL) { TEST_ASSERT(Tcscmp(result, PAL_T("test = 12345")) == 0); } PAL_Free(result); } NitsEndTest #include <locale.h> NitsTest(TestFormat_Stprintf_CultureInvariant) { TChar buf[1024] = {0}; char oldLocale[128]; char testLocale[128]; char *currentLocale = NULL; Strlcpy(oldLocale, setlocale(LC_ALL, NULL), PAL_COUNT(oldLocale)); currentLocale = setlocale(LC_ALL, "polish"); if(currentLocale) { Strlcpy(testLocale, currentLocale, PAL_COUNT(testLocale)); Stprintf( buf, PAL_COUNT(buf), PAL_T("%g"), 1.23); NitsAssert( Tcscmp(buf, PAL_T("1,23")) == 0, PAL_T("Sanity check that polish locale uses a comma instead of a dot for decimal point")); } else { /* ATTN: alternate implementation needed to test the functionality! */ NitsAssert(true, PAL_T("test skipped")); } Stprintf_CultureInvariant( buf, PAL_COUNT(buf), PAL_T("%g"), 1.23); TEST_ASSERT(Tcscmp(buf, PAL_T("1.23")) == 0); if(currentLocale) { NitsAssert( 0 == Strcmp(testLocale, setlocale(LC_ALL, NULL)), PAL_T("Invocation of Stprintf_CultureInvariant shouldn't change current locale")); } setlocale(LC_ALL, oldLocale); } NitsEndTest NitsTest(TestFormat_Stscanf_CultureInvariant) { int result = 0; double number = 0.0; char oldLocale[128]; char testLocale[128]; char *currentLocale = NULL; Strlcpy(oldLocale, setlocale(LC_ALL, NULL), PAL_COUNT(oldLocale)); currentLocale = setlocale(LC_ALL, "polish"); if(currentLocale) { Strlcpy(testLocale, currentLocale, PAL_COUNT(testLocale)); result = Stscanf_CultureInvariant( PAL_T("1.23"), PAL_T("%lg"), &number); NitsAssert( (1.22 < number) && (number < 1.24), PAL_T("Sanity check that polish locale uses a comma instead of a dot for decimal point")); NitsAssert( result == 1, PAL_T("Scanf should return the number of elements it consumed")); NitsAssert( 0 == Strcmp(testLocale, setlocale(LC_ALL, NULL)), PAL_T("Invocation of Stscanf_CultureInvariant shouldn't change current locale")); } else { /* ATTN: alternate implementation needed to test the functionality! */ NitsAssert(true, PAL_T("test skipped")); } setlocale(LC_ALL, oldLocale); } NitsEndTest //============================================================================== // // TestCondLock() // //============================================================================== struct TestCondLockData { ptrdiff_t key; ptrdiff_t predicate; Lock lock; }; NITS_EXTERN_C PAL_Uint32 THREAD_API TestCondLockReader(void* arg) { TestCondLockData* data = (TestCondLockData*)arg; // Wait on the condition variable: for (;;) { // Wait while predicate == 0: CondLock_Wait( data->key, &data->predicate, 0, CONDLOCK_DEFAULT_SPINCOUNT); Lock_Acquire(&data->lock); // If predicate not satisfied, continue: if (data->predicate == 0) { Lock_Release(&data->lock); continue; } // Check the predicate: TEST_ASSERT(data->predicate == 12345678); Lock_Release(&data->lock); break; } return 0; } NITS_EXTERN_C PAL_Uint32 THREAD_API TestCondLockWriter(void* arg) { TestCondLockData* data = (TestCondLockData*)arg; // Wait one second for reader to start: Sleep_Milliseconds(1000); // Update the predicate: Lock_Acquire(&data->lock); data->predicate = 12345678; Lock_Release(&data->lock); // Signal the reader: CondLock_Signal(data->key); return 0; } NitsTest(TestCondLock) { // Initialize the data: TestCondLockData data; data.key = 1001; data.predicate = 0; Lock_Init(&data.lock); // Create writer thread: Thread writer; int writer_created = PAL_FALSE; writer_created = (Thread_CreateJoinable(&writer, TestCondLockWriter, NULL, &data) == 0); TEST_ASSERT(writer_created); // Create reader threads: Thread reader; int reader_created = PAL_FALSE; reader_created = (Thread_CreateJoinable(&reader, TestCondLockReader, NULL, &data) == 0); TEST_ASSERT(reader_created); if (writer_created) { PAL_Uint32 arg; Thread_Join(&writer, &arg); Thread_Destroy(&writer); } else { Lock_Acquire(&data.lock); data.predicate = 0xdeadbeef; Lock_Release(&data.lock); CondLock_Signal(data.key); } if (reader_created) { PAL_Uint32 arg; Thread_Join(&reader, &arg); Thread_Destroy(&reader); } } NitsEndTest //============================================================================== // // Tests for Intlstr // //============================================================================== NitsTest(TestIntlstr_SimpleString) { Intlstr result = Intlstr_Null; result = Intlstr_TestPal_SimpleString(); NitsAssert(result.str != NULL, PAL_T("Could we get a localized string? (if not, double-check if mui file is deployed correctly)")); if (result.str != NULL) { TEST_ASSERT(Tcscmp(result.str, PAL_T("My simple string")) == 0); } Intlstr_Free(result); } NitsEndTest NitsTest(TestIntlstr_ReorderablePlaceholders) { Intlstr result = Intlstr_Null; result = Intlstr_TestPal_ReorderablePlaceholders(123, 456); NitsAssert(result.str != NULL, PAL_T("Could we get a localized string? (if not, double-check if mui file is deployed correctly)")); if (result.str != NULL) { TEST_ASSERT(Tcscmp(result.str, PAL_T("Second integer = 456, First integer = 123")) == 0); } Intlstr_Free(result); } NitsEndTest NitsTest(TestIntlstr_OnePlaceholder) { Intlstr result = Intlstr_Null; result = Intlstr_TestPal_OnePlaceholder(1); NitsAssert(result.str != NULL, PAL_T("Could we get a localized string? (if not, double-check if mui file is deployed correctly)")); if (result.str != NULL) { TEST_ASSERT(Tcscmp(result.str, PAL_T("p1=1")) == 0); } Intlstr_Free(result); } NitsEndTest NitsTest(TestIntlstr_TwoPlaceholders) { Intlstr result = Intlstr_Null; result = Intlstr_TestPal_TwoPlaceholders(1,2); NitsAssert(result.str != NULL, PAL_T("Could we get a localized string? (if not, double-check if mui file is deployed correctly)")); if (result.str != NULL) { TEST_ASSERT(Tcscmp(result.str, PAL_T("p1=1, p2=2")) == 0); } Intlstr_Free(result); } NitsEndTest NitsTest(TestIntlstr_ThreePlaceholders) { Intlstr result = Intlstr_Null; result = Intlstr_TestPal_ThreePlaceholders(1,2,3); NitsAssert(result.str != NULL, PAL_T("Could we get a localized string? (if not, double-check if mui file is deployed correctly)")); if (result.str != NULL) { TEST_ASSERT(Tcscmp(result.str, PAL_T("p1=1, p2=2, p3=3")) == 0); } Intlstr_Free(result); } NitsEndTest NitsTest(TestIntlstr_Specifier_d) { Intlstr result = Intlstr_Null; result = Intlstr_TestPal_Specifier_d(123); NitsAssert(result.str != NULL, PAL_T("Could we get a localized string? (if not, double-check if mui file is deployed correctly)")); if (result.str != NULL) { TEST_ASSERT(Tcscmp(result.str, PAL_T("p1=123")) == 0); } Intlstr_Free(result); } NitsEndTest NitsTest(TestIntlstr_Specifier_tstr) { Intlstr result = Intlstr_Null; result = Intlstr_TestPal_Specifier_tstr(PAL_T("foo")); NitsAssert(result.str != NULL, PAL_T("Could we get a localized string? (if not, double-check if mui file is deployed correctly)")); if (result.str != NULL) { TEST_ASSERT(Tcscmp(result.str, PAL_T("p1=foo")) == 0); } Intlstr_Free(result); } NitsEndTest NitsTest(TestIntlstr_Specifier_tchr) { Intlstr result = Intlstr_Null; result = Intlstr_TestPal_Specifier_tchr(PAL_T('f')); NitsAssert(result.str != NULL, PAL_T("Could we get a localized string? (if not, double-check if mui file is deployed correctly)")); if (result.str != NULL) { TEST_ASSERT(Tcscmp(result.str, PAL_T("char=f")) == 0); } Intlstr_Free(result); } NitsEndTest NitsTest(TestIntlstr_Specifier_x) { Intlstr result = Intlstr_Null; result = Intlstr_TestPal_Specifier_x(0x12345678); NitsAssert(result.str != NULL, PAL_T("Could we get a localized string? (if not, double-check if mui file is deployed correctly)")); if (result.str != NULL) { TEST_ASSERT(Tcscmp(result.str, PAL_T("p1=0x12345678")) == 0); } Intlstr_Free(result); } NitsEndTest #if defined(USE_ALLOCATOR) NitsTest(TestAlloc) { void* ptrs[1024]; size_t n = sizeof(ptrs) / sizeof(ptrs[0]); size_t i; AllocStats stats = PAL_GetAllocStats(); size_t numAllocs = stats.numAllocs; size_t numFrees = stats.numFrees; size_t usage = stats.usage; size_t extraUsage = 0; for (i = 0; i < n; i++) { ptrs[i] = PAL_Malloc(i+1); extraUsage += i + 1; } stats = PAL_GetAllocStats(); TEST_ASSERT(stats.numAllocs == numAllocs + n); TEST_ASSERT(stats.usage == usage + extraUsage); for (i = 0; i < n; i++) { PAL_Free(ptrs[i]); } stats = PAL_GetAllocStats(); TEST_ASSERT(stats.numFrees == numFrees + n); TEST_ASSERT(stats.usage == usage); } NitsEndTest #endif /* defined(USE_ALLOCATOR) */
23.313486
145
0.541228
[ "vector" ]
3bf4a88bbb3c38fed65dc66dacafd3bbd858f2c4
11,340
cpp
C++
isis/src/base/objs/Histogram/unitTest.cpp
robotprogrammer22/ISIS3
8a2ec4bb3c91969c81d75c681051a1fe77028788
[ "CC0-1.0" ]
null
null
null
isis/src/base/objs/Histogram/unitTest.cpp
robotprogrammer22/ISIS3
8a2ec4bb3c91969c81d75c681051a1fe77028788
[ "CC0-1.0" ]
null
null
null
isis/src/base/objs/Histogram/unitTest.cpp
robotprogrammer22/ISIS3
8a2ec4bb3c91969c81d75c681051a1fe77028788
[ "CC0-1.0" ]
null
null
null
#include <QString> #include <QList> #include "QRegularExpression" #include "Histogram.h" #include "IException.h" #include "Preference.h" #include "LineManager.h" #include "ControlNet.h" #include "ControlMeasure.h" #include "Progress.h" #include "IException.h" #include "FileName.h" using namespace std; #include <iostream> #include <vector> #include <algorithm> #include <fstream> void arrayDisplay(double *array, int size ); void histogramMembers(Isis::Histogram *h); void statCounters(Isis::Histogram *h); void histDisplay(Isis::Histogram *h); int main(int argc, char *argv[]) { // Old unit test begins here Isis::Preference::Preferences(true); Isis::Histogram h(-10.0, 10.0, 20); double low, high; try { double a[9]; a[0] = 1.0; a[1] = 2.0; a[2] = 3.0; a[3] = Isis::NULL8; a[4] = Isis::HIGH_REPR_SAT8; a[5] = Isis::LOW_REPR_SAT8; a[6] = Isis::HIGH_INSTR_SAT8; a[7] = Isis::LOW_INSTR_SAT8; a[8] = 2.0; h.AddData(a, 9); cout << "Median: " << h.Median() << endl; cout << "Mode: " << h.Mode() << endl; cout << "Skew: " << h.Skew() << endl; cout << "Percent(0.5): " << h.Percent(0.5) << endl; cout << "Percent(99.5): " << h.Percent(99.5) << endl; cout << "Bins: " << h.Bins() << endl; cout << "BinSize: " << h.BinSize() << endl; cout << "BinMiddle: " << h.BinMiddle(0) << endl; h.BinRange(0, low, high); cout << "BinRange(0,low): " << low << endl; cout << "BinRange(0,high): " << high << endl; cout << "BinCount(0): " << h.BinCount(0) << endl; h.BinRange(19, low, high); cout << "BinRange(20,low): " << low << endl; cout << "BinRange(20,high): " << high << endl; cout << "BinCount(20): " << h.BinCount(19) << endl; cout << endl; h.RemoveData(a, 3); double b[4]; b[0] = -11.0; b[1] = 11.0; b[2] = 5.0; b[3] = 5.0; h.AddData(b, 4); cout << "Average: " << h.Average() << endl; cout << "Median: " << h.Median() << endl; cout << "Mode: " << h.Mode() << endl; cout << "Skew: " << h.Skew() << endl; cout << "Percent(0.5): " << h.Percent(0.5) << endl; cout << "Percent(99.5): " << h.Percent(99.5) << endl; cout << "BinCount(0): " << h.BinCount(0) << endl; cout << "BinCount(20): " << h.BinCount(19) << endl; cout << endl; } catch(Isis::IException &e) { e.print(); } try { Isis::Histogram g(1.0, 0.0); } catch(Isis::IException &e) { e.print(); } try { h.Percent(-1.0); } catch(Isis::IException &e) { e.print(); } try { h.Percent(101.0); } catch(Isis::IException &e) { e.print(); } try { h.BinCount(-1); } catch(Isis::IException &e) { e.print(); } try { h.BinCount(1024); } catch(Isis::IException &e) { e.print(); } try { h.BinMiddle(-1); } catch(Isis::IException &e) { e.print(); } try { h.BinMiddle(1024); } catch(Isis::IException &e) { e.print(); } try { h.BinRange(-1, low, high); } catch(Isis::IException &e) { e.print(); } try { h.BinRange(1024, low, high); } catch(Isis::IException &e) { e.print(); } //End old unit test cout << endl; cout << "End old unit test." << endl; QList<QString> flist; Isis::Progress progress; Isis::FileName netName("$ISISTESTDATA/isis/src/base/unitTestData/enceladus_sp-Jig.net"); flist.append(netName.expanded()); cout << netName.toString().replace(QRegularExpression("(\\/[\\w\\-\\. ]*)+\\/*Data"), "data").toStdString() << endl; Isis::ControlNet net(flist[0], &progress); Isis::Histogram *hist1, *hist2; try { hist1 = new Isis::Histogram(net, &Isis::ControlMeasure::GetResidualMagnitude, 19); cout << endl; cout << "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" <<endl; cout << endl; cout << "Constructor1: " << endl; cout << "Histogram(net, &Isis::ControlMeasure::GetResidualMagnitude,numbins)" << endl; cout << endl; cout << "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" <<endl; histogramMembers(hist1); statCounters(hist1); cout << "Resetting bin range to (0.1469787,0.3299682)" << endl; hist1 ->SetValidRange(0.1469787,0.3299682); histogramMembers(hist1); statCounters(hist1); delete(hist1); cout << endl; } catch (Isis::IException &e) { e.print(); } try { hist2 = new Isis::Histogram(net, &Isis::ControlMeasure::GetResidualMagnitude, .01); cout << endl; cout << "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" <<endl; cout << "Constructor2: " << endl; cout << "Histogram(net, &Isis::ControlMeasure::GetResidualMagnitude,double binwidth)" << endl; cout << endl; cout << "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" <<endl; histogramMembers(hist2); statCounters(hist2); cout << "Resetting bin range to (0.1469787,0.3299682)" << endl; hist2 ->SetValidRange(0.1469787,0.3299682); histogramMembers(hist2); statCounters(hist2); delete(hist2); cout << endl; } catch (Isis::IException &e) { e.print(); } double low1 = -10; double high1 = 10; int nbins = 5; Isis::Histogram *ahist, *bhist; ahist = new Isis::Histogram (low1,high1,nbins); bhist = new Isis::Histogram (low1,high1,nbins); double a[9]; a[0] = 1.0; a[1] = 2.0; a[2] = 3.0; a[3] = Isis::NULL8; a[4] = Isis::HIGH_REPR_SAT8; a[5] = Isis::LOW_REPR_SAT8; a[6] = Isis::HIGH_INSTR_SAT8; a[7] = Isis::LOW_INSTR_SAT8; a[8] = 2.0; double b[9]; b[0] = -9.0; b[1] = -7.0; b[2] = -5.0; b[3] = 5.5; b[4] = 2.3; b[5] = -0.5; b[6] = 7.1; b[7] = 8.2; b[8] = 8.3; try{ cout << "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" <<endl; cout << endl; cout << "Constructor4: " << endl; cout << "Histogram(double mim, double max,int nbins)" << endl; cout << endl; cout << "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" <<endl; ahist->AddData(a,9); bhist->AddData(b,9); // Data output cout << "Data Vector a: " << endl; arrayDisplay(a,9); cout << endl; statCounters(ahist); histogramMembers(ahist); cout << "**********************Data Vector A Histogram**********************" << endl; histDisplay(ahist); cout << "*******************************************************************" << endl; cout << endl; cout << "Data Vector b: " << endl; arrayDisplay(b,9); cout << endl; statCounters(bhist); histogramMembers(bhist); cout << "**********************Data Vector B Histogram**********************" << endl; histDisplay(bhist); cout << "*******************************************************************" << endl; int remove = 3; bhist->RemoveData(b,remove); cout <<"Removing: "; for(int i = 0; i < remove -1; i++){ cout << b[i] << ","; } cout << b[remove-1] << endl; cout << "**********************Data Vector B Histogram**********************" << endl; histDisplay(bhist); cout << "*******************************************************************" << endl; histogramMembers(bhist); bhist->SetValidRange(0,10); cout << "Changing BinRange for b-vector's histogram..." << endl; statCounters(bhist); histogramMembers(bhist); cout << endl; delete(ahist); delete(bhist); }//end try block catch(Isis::IException &e){ e.print(); } }//end main //Simple function for outputting a sorted vector void arrayDisplay(double *array, int size ){ vector<double> v(size); for (int i=0; i < size; i++ ) v[i]= array[i]; sort (v.begin(),v.end() ); cout << "[ " ; for (std::vector<double>::iterator it = v.begin(); it != v.end(); it++) cout << *it << " "; cout << "]" << endl; } void histDisplay(Isis::Histogram *h){ double low, high; for (int i = 0; i < h->Bins(); i++){ h->BinRange(i,low,high); cout <<"Bin " << i << ": [" << low << "," << high << "], Count = " << h->BinCount(i) << endl; } } void histogramMembers(Isis::Histogram *h){ try{ cout << endl; cout << "+++++++++++++++++++ Histogram Members +++++++++++++++++++" << endl; cout << endl; cout << "Stats Range: (" << h->ValidMinimum() << "," << h->ValidMaximum() << ")" << endl; cout << "Bin Range: (" << h->BinRangeStart() <<","<< h->BinRangeEnd()<<")" << endl; cout << "Average: "; cout << h-> Average() << endl; cout << "Std Deviation: "; cout << h->StandardDeviation() << endl; cout << "Variance: "; cout << h->Variance() <<endl; cout << "Median: "; cout << h->Median() << endl; cout << "Mode: "; cout << h->Mode() << endl; cout << "Skew: "; cout << h->Skew() << endl; cout << "Percent(0.5): "; cout << h->Percent(0.5) << endl; cout << "Percent(99.5): "; cout << h->Percent(99.5) << endl; cout << "Minimum: "; cout << h-> Minimum() << endl; cout << "Maximum: "; cout << h-> Maximum() << endl; cout << "# Bins: "; cout << h->Bins() << endl; cout << "BinWidth: "; cout << h->BinSize() << endl; cout << "MaxBinCount: "; cout << h->MaxBinCount() << endl; cout << endl; cout << "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++" << endl; } catch(Isis::IException &e){ e.print(); } } void statCounters(Isis::Histogram *h){ cout << endl; cout << "++++++++++++++++++ Statistics Counters ++++++++++++++++++" << endl; cout << endl; cout << "Total pixels: " << h->TotalPixels() << endl; cout << "Valid pixels: " << h->ValidPixels() << endl; cout << "Over Range pixels: " << h->OverRangePixels() << endl; cout << "Under Range pixels: " << h->UnderRangePixels() << endl; cout << "Null pixels: " << h->NullPixels() << endl; cout << "Lis pixels: " << h->LisPixels() << endl; cout << "His pixels: " << h->HisPixels() << endl; cout << "Lrs pixels: " << h->LrsPixels() << endl; cout << "Hrs pixels: " << h->HrsPixels() << endl; cout << "Out of range pixels: " << h->OutOfRangePixels() << endl; cout << "Minimum: " << h->Minimum() << endl; cout << "Maximum: " << h->Maximum() << endl; cout << "Valid Minimum: " << h->ValidMinimum() << endl; cout << "Valid Maximum: " << h->ValidMaximum() << endl; cout << "Sum: " << h->Sum() << endl; cout << "Sum Square: " << h->SumSquare() << endl; cout << endl; cout << "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++" << endl; }
26.808511
118
0.460229
[ "vector" ]
3bf4d4d997c23a815b54ebe43f78f70deb5934d5
30,034
cpp
C++
aten/src/ATen/native/vulkan/ops/Tensor.cpp
WBobby/pytorch
655960460ccca936fa5c06df6bbafd25b5582115
[ "Intel" ]
24
2020-11-02T21:25:12.000Z
2022-03-17T07:20:33.000Z
aten/src/ATen/native/vulkan/ops/Tensor.cpp
WBobby/pytorch
655960460ccca936fa5c06df6bbafd25b5582115
[ "Intel" ]
1
2019-08-01T00:17:43.000Z
2019-09-12T01:31:53.000Z
aten/src/ATen/native/vulkan/ops/Tensor.cpp
WBobby/pytorch
655960460ccca936fa5c06df6bbafd25b5582115
[ "Intel" ]
12
2020-11-06T05:00:37.000Z
2022-01-30T19:17:36.000Z
#include <ATen/native/vulkan/ops/Tensor.h> #include <ATen/native/vulkan/ops/Common.h> #include <c10/util/accumulate.h> namespace at { namespace native { namespace vulkan { namespace ops { namespace { using namespace api::utils; uvec3 image_extents(IntArrayRef); bool requires_image(IntArrayRef); bool requires_staging(const api::Adapter*); VkFormat vk_format(const caffe2::TypeMeta dtype) { switch (c10::typeMetaToScalarType(dtype)) { case kFloat: #ifdef USE_VULKAN_FP16_INFERENCE return VK_FORMAT_R16G16B16A16_SFLOAT; #else return VK_FORMAT_R32G32B32A32_SFLOAT; #endif /* USE_VULKAN_FP16_INFERENCE */ default: TORCH_CHECK( false, "Vulkan tensor format not supported!"); } return VK_FORMAT_UNDEFINED; } VkExtent3D vk_extent(const uvec3& extent) { return { extent.data[0u], extent.data[1u], extent.data[2u], }; } vTensor::Access::Flags access( const VkAccessFlags vk_access) { vTensor::Access::Flags access = 0u; constexpr VkAccessFlags kRead = VK_ACCESS_HOST_READ_BIT | VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_UNIFORM_READ_BIT; constexpr VkAccessFlags kWrite = VK_ACCESS_HOST_WRITE_BIT | VK_ACCESS_MEMORY_WRITE_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT; if (vk_access & kRead) { access |= vTensor::Access::Read; } if (vk_access & kWrite) { access |= vTensor::Access::Write; } return access; } VkAccessFlags vk_access( const vTensor::Stage::Flags stage, const vTensor::Access::Flags access) { VkAccessFlags vk_access = 0u; if (access & vTensor::Access::Read) { if (stage & vTensor::Stage::Compute) { vk_access |= VK_ACCESS_SHADER_READ_BIT; } if (stage & vTensor::Stage::Host) { vk_access |= VK_ACCESS_HOST_READ_BIT; } if (stage & vTensor::Stage::Transfer) { vk_access |= VK_ACCESS_TRANSFER_READ_BIT; } } if (access & vTensor::Access::Write) { if (stage & vTensor::Stage::Compute) { vk_access |= VK_ACCESS_SHADER_WRITE_BIT; } if (stage & vTensor::Stage::Host) { vk_access |= VK_ACCESS_HOST_WRITE_BIT; } if (stage & vTensor::Stage::Transfer) { vk_access |= VK_ACCESS_TRANSFER_WRITE_BIT; } } return vk_access; } VkImageLayout vk_layout( const vTensor::Stage::Flags stage, const vTensor::Access::Flags access) { switch (stage) { case vTensor::Stage::Compute: switch (access) { case vTensor::Access::Read: return VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; default: return VK_IMAGE_LAYOUT_GENERAL; } break; case vTensor::Stage::Transfer: switch (access) { case vTensor::Access::Read: return VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; case vTensor::Access::Write: return VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; default: TORCH_INTERNAL_ASSERT(false, "Invalid!"); } break; default: TORCH_INTERNAL_ASSERT(false, "Invalid!"); } return VK_IMAGE_LAYOUT_UNDEFINED; } VkPipelineStageFlags vk_stage( const vTensor::Stage::Flags stage) { VkPipelineStageFlags vk_stage = 0u; if (stage & vTensor::Stage::Compute) { vk_stage |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; } if (stage & vTensor::Stage::Host) { vk_stage |= VK_PIPELINE_STAGE_HOST_BIT; } if (stage & vTensor::Stage::Transfer) { vk_stage |= VK_PIPELINE_STAGE_TRANSFER_BIT; } return vk_stage; } VkDeviceSize buffer_bytes( const IntArrayRef sizes, const caffe2::TypeMeta dtype) { VkDeviceSize size = c10::elementSize(c10::typeMetaToScalarType(dtype)); if (requires_image(sizes)) { const uvec3 extents = image_extents(sizes); size *= extents.data[0u] * extents.data[1u] * (4u * extents.data[2u]); } else { size *= c10::multiply_integers(sizes); } return size; } vTensor::Buffer allocate_buffer( const api::Adapter* const adapter, api::Resource::Pool* const pool, const IntArrayRef sizes, const TensorOptions& options) { TORCH_INTERNAL_ASSERT_DEBUG_ONLY( adapter, "Invalid Vulkan adapter!"); TORCH_INTERNAL_ASSERT_DEBUG_ONLY( pool, "Invalid Vulkan resource pool!"); TORCH_CHECK(!sizes.empty(), "Invalid Vulkan tensor size!"); verify(options); const VkFlags usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; const auto memory = [adapter]() -> api::Resource::Memory::Descriptor { if (requires_staging(adapter)) { return { VMA_MEMORY_USAGE_GPU_ONLY, 0u, 0u, }; } return { VMA_MEMORY_USAGE_GPU_TO_CPU, 0u, VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, }; }(); return pool->buffer({ buffer_bytes(sizes, options.dtype()), // Usage { usage, memory, }, }); } bool requires_image(const IntArrayRef sizes) { return (1u <= sizes.size()) && (sizes.size() <= 4u); } uvec3 image_extents(const IntArrayRef sizes) { int64_t width = 1; int64_t height = 1; int64_t depth = 1; switch (sizes.size()) { case 1: width = sizes[0]; break; case 2: width = sizes[1]; height = sizes[0]; break; case 3: width = sizes[2]; height = sizes[1]; depth = sizes[0]; break; case 4: width = sizes[3]; height = sizes[2]; depth = sizes[0] * sizes[1]; break; default: TORCH_INTERNAL_ASSERT( false, "Only Tensors with 1 <= dim <= 4 can be represented as a Vulkan Image!"); } return { safe_downcast<uint32_t>(width), safe_downcast<uint32_t>(height), safe_downcast<uint32_t>(div_up(depth, INT64_C(4))), }; } vTensor::Image allocate_image( api::Resource::Pool* const pool, const VkExtent3D& extents, const TensorOptions& options) { TORCH_INTERNAL_ASSERT_DEBUG_ONLY( pool, "Invalid Vulkan resource pool!"); verify(options); return pool->image({ extents.depth == 1 ? VK_IMAGE_TYPE_2D : VK_IMAGE_TYPE_3D, vk_format(options.dtype()), extents, // Usage { VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT, { VMA_MEMORY_USAGE_GPU_ONLY, 0u, 0u, }, }, // View { extents.depth == 1 ? VK_IMAGE_VIEW_TYPE_2D : VK_IMAGE_VIEW_TYPE_3D, vk_format(options.dtype()), }, // Sampler { VK_FILTER_NEAREST, VK_SAMPLER_MIPMAP_MODE_NEAREST, VK_SAMPLER_ADDRESS_MODE_REPEAT, VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK, }, }); } bool requires_staging(const api::Adapter* const adapter) { TORCH_INTERNAL_ASSERT_DEBUG_ONLY( adapter, "Invalid Vulkan adapter!"); return !adapter->has_unified_memory(); } vTensor::Buffer allocate_staging( const api::Adapter* const adapter, api::Resource::Pool* const pool, const IntArrayRef sizes, const TensorOptions& options) { TORCH_INTERNAL_ASSERT_DEBUG_ONLY( adapter, "Invalid Vulkan adapter!"); TORCH_INTERNAL_ASSERT_DEBUG_ONLY( pool, "Invalid Vulkan resource pool!"); TORCH_CHECK(!sizes.empty(), "Invalid Vulkan tensor size!"); verify(options); return pool->buffer({ buffer_bytes(sizes, options.dtype()), // Usage { VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, { VMA_MEMORY_USAGE_CPU_COPY, 0u, 0u, }, }, }); } vTensor::Fence allocate_fence(api::Resource::Pool* const pool) { TORCH_INTERNAL_ASSERT_DEBUG_ONLY( pool, "Invalid Vulkan resource pool!"); return pool->fence(); } enum class Barrier { None, Exectution, Memory, }; Barrier categorize( const VkAccessFlags vk_src_access, const VkAccessFlags vk_dst_access) { if (0u == vk_src_access) { return Barrier::None; } const vTensor::Access::Flags src_access = access(vk_src_access); const vTensor::Access::Flags dst_access = access(vk_dst_access); if ((src_access & vTensor::Access::Read) == src_access) { if ((dst_access & vTensor::Access::Read) == dst_access) { // RAR (Read after Read) return Barrier::None; } // WAR (Write after Read) return Barrier::Exectution; } // RAW (Read after Write), or WAW (Write after Write) return Barrier::Memory; }; Barrier categorize( const VkAccessFlags vk_src_access, const VkAccessFlags vk_dst_access, const VkImageLayout vk_src_layout, const VkImageLayout vk_dst_layout) { if (vk_src_layout != vk_dst_layout) { return Barrier::Memory; } return categorize(vk_src_access, vk_dst_access); } } // namespace vTensor::vTensor( api::Context* const context, const IntArrayRef sizes, const TensorOptions& options) : vTensor( context, &context->resource().pool, sizes, options) { } vTensor::vTensor( api::Context* const context, api::Resource::Pool* const pool, const IntArrayRef sizes, const TensorOptions& options) : view_(new View{ context, pool, sizes, options, }) { } const vTensor* vTensor::host( api::Command::Buffer& command_buffer) const { view_->staging(command_buffer, Stage::Host, Access::Read); return this; } vTensor* vTensor::host( api::Command::Buffer& command_buffer, const Access::Flags access) { view_->staging(command_buffer, Stage::Host, access); return this; } vTensor::Buffer::Object vTensor::buffer( api::Command::Buffer& command_buffer, const Stage::Flags stage) const & { return view_->buffer( command_buffer, stage, Access::Read).object; } vTensor::Buffer::Object vTensor::buffer( api::Command::Buffer& command_buffer, const Stage::Flags stage, const Access::Flags access) & { return view_->buffer( command_buffer, stage, access).object; } vTensor::Image::Object vTensor::image( api::Command::Buffer& command_buffer, const Stage::Flags stage) const & { return view_->image( command_buffer, stage, Access::Read).object; } vTensor::Image::Object vTensor::image( api::Command::Buffer& command_buffer, const Stage::Flags stage, const Access::Flags access) & { return view_->image( command_buffer, stage, access).object; } vTensor::View::View() // Resources : buffer_{}, image_{}, staging_{}, fence_{}, // Context context_(nullptr), pool_(nullptr), // State state_{}, // Metadata extents_{} { } vTensor::View::View( api::Context* const context, api::Resource::Pool* const pool, const IntArrayRef sizes, const TensorOptions& options) // Resources : buffer_{}, image_{}, staging_{}, fence_{}, // Context context_(context), pool_(pool), // State state_(context->gpu().adapter, sizes), // Metadata extents_(image_extents(sizes)), options_(options), sizes_(sizes), strides_(sizes.size()) { ops::verify(options); } class vTensor::View::CMD final { public: CMD(const View&, api::Command::Buffer&); CMD(const CMD&) = delete; CMD& operator=(const CMD&) = delete; CMD(CMD&&) = delete; CMD& operator=(CMD&&) = delete; ~CMD() = default; typedef api::Resource::Buffer Buffer; typedef api::Resource::Image Image; typedef api::Resource::Fence Fence; void barrier(State::Transition transition); void copy_buffer_to_staging( State& state, const Buffer::Object& buffer, Buffer::Object& staging); void copy_staging_to_buffer( State& state, const Buffer::Object& staging, Buffer::Object& buffer); void copy_buffer_to_image( State& state, const Buffer::Object& buffer, Image::Object& image); void copy_image_to_buffer( State& state, const Image::Object& image, Buffer::Object& buffer); void submit(Fence fence); private: const View& view_; api::Command::Buffer& command_buffer_; }; vTensor::View::CMD::CMD( const View& view, api::Command::Buffer& command_buffer) : view_(view), command_buffer_(command_buffer) { } void vTensor::View::CMD::barrier(State::Transition transition) { // Buffer and Staging are just an alias for the same memory region on UMA. if (view_.state_.is_uma()) { transition.first.buffer.stage |= transition.first.staging.stage; transition.first.buffer.access |= transition.first.staging.access; transition.first.staging = {}; transition.second.buffer.stage |= transition.second.staging.stage; transition.second.buffer.access |= transition.second.staging.access; transition.second.staging = {}; } // Filter out host dependencies out of source, per Vulkan spec host write ordering guarantees: // https://www.khronos.org/registry/vulkan/specs/1.2/html/vkspec.html#synchronization-submission-host-writes const auto filter_stage =[](VkPipelineStageFlags& stage) { stage &= ~VK_PIPELINE_STAGE_HOST_BIT; }; filter_stage(transition.first.buffer.stage); filter_stage(transition.first.staging.stage); const auto filter_access =[](VkAccessFlags& access) { access &= ~(VK_ACCESS_HOST_READ_BIT | VK_ACCESS_HOST_WRITE_BIT); }; filter_access(transition.first.buffer.access); filter_access(transition.first.staging.access); api::Pipeline::Barrier barrier{}; if (transition.second.staging) { const State::Bundle::Buffer from = transition.first.staging; const State::Bundle::Buffer to = transition.second.staging; const Barrier category = categorize( from.access, to.access); if (Barrier::None != category) { barrier.stage.src |= from.stage; barrier.stage.dst |= to.stage; if (Barrier::Memory == category) { barrier.buffers.push_back({ view_.staging().object, { from.access, to.access, }, }); } } } if (transition.second.buffer) { const State::Bundle::Buffer from = transition.first.buffer; const State::Bundle::Buffer to = transition.second.buffer; const Barrier category = categorize( from.access, to.access); if (Barrier::None != category) { barrier.stage.src |= from.stage; barrier.stage.dst |= to.stage; if (Barrier::Memory == category) { barrier.buffers.push_back({ view_.buffer().object, { from.access, to.access, }, }); } } } if (transition.second.image) { const State::Bundle::Image from = transition.first.image; const State::Bundle::Image to = transition.second.image; const Barrier category = categorize( from.access, to.access, from.layout, to.layout); if (Barrier::None != category) { barrier.stage.src |= from.stage; barrier.stage.dst |= to.stage; if (Barrier::Memory == category) { TORCH_INTERNAL_ASSERT( from.layout == view_.image().object.layout, "Invalid image layout!"); barrier.images.push_back({ view_.image().object, { from.access, to.access, }, { from.layout, to.layout, }, }); view_.image().object.layout = to.layout; } } } // If we are left with anything meaningful, insert a barrier. if (barrier) { if (0u == barrier.stage.src) { barrier.stage.src = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; } if (0u == barrier.stage.dst) { barrier.stage.src = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; } command_buffer_.barrier(barrier); } } void vTensor::View::CMD::copy_buffer_to_staging( State& state, const Buffer::Object& buffer, Buffer::Object& staging) { if (state.is_clean(Component::Staging) || state.is_uma()) { return; } barrier( state.transition({ // Staging { vk_stage(Stage::Transfer), vk_access(Stage::Transfer, Access::Write), }, // Buffer { vk_stage(Stage::Transfer), vk_access(Stage::Transfer, Access::Read), }, // Image {}, })); command_buffer_.copy(buffer, staging); } void vTensor::View::CMD::copy_staging_to_buffer( State& state, const Buffer::Object& staging, Buffer::Object& buffer) { if (state.is_clean(Component::Buffer) || state.is_uma()) { return; } barrier( state.transition({ // Staging { vk_stage(Stage::Transfer), vk_access(Stage::Transfer, Access::Read), }, // Buffer { vk_stage(Stage::Transfer), vk_access(Stage::Transfer, Access::Write), }, // Image {}, })); command_buffer_.copy(staging, buffer); } void vTensor::View::CMD::copy_buffer_to_image( State& state, const Buffer::Object& buffer, Image::Object& image) { if (state.is_clean(Component::Image)) { return; } barrier( state.transition({ // Staging {}, // Buffer { vk_stage(Stage::Compute), vk_access(Stage::Compute, Access::Read), }, // Image { vk_stage(Stage::Compute), vk_access(Stage::Compute, Access::Write), vk_layout(Stage::Compute, Access::Write), }, })); const uvec3 extents = view_.extents(); const uint32_t plane = extents.data[0u] * extents.data[1u]; const struct Block final { uvec3 extents; uint32_t block; uvec4 offset; } block { extents, 4u * plane, { 0u * plane, 1u * plane, 2u * plane, 3u * plane, }, }; view_.context_->dispatch( command_buffer_, { VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, }, VK_KERNEL(nchw_to_image), extents, adaptive_work_group_size(extents), // Shader parameters block, // Textures image, buffer); } void vTensor::View::CMD::copy_image_to_buffer( State& state, const Image::Object& image, Buffer::Object& buffer) { if (state.is_clean(Component::Buffer)) { return; } barrier( state.transition({ // Staging {}, // Buffer { vk_stage(Stage::Compute), vk_access(Stage::Compute, Access::Write), }, // Image { vk_stage(Stage::Compute), vk_access(Stage::Compute, Access::Read), vk_layout(Stage::Compute, Access::Read), }, })); const uvec3 extents = view_.extents(); const uint32_t plane = extents.data[0u] * extents.data[1u]; const struct Block final { uvec3 extents; uint32_t block; uvec4 offset; } block { extents, 4u * plane, { 0u * plane, 1u * plane, 2u * plane, 3u * plane, }, }; view_.context_->dispatch( command_buffer_, { VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, }, VK_KERNEL(image_to_nchw), view_.extents(), adaptive_work_group_size(view_.extents()), // Shader parameters block, // Textures image, buffer); } void vTensor::View::CMD::submit(const api::Resource::Fence fence) { view_.context_->command().pool.submit( view_.context_->gpu().queue, command_buffer_, fence); } vTensor::Buffer& vTensor::View::buffer() const { if (!buffer_) { buffer_ = allocate_buffer( context_->gpu().adapter, pool_, sizes(), options()); } return buffer_; } vTensor::Buffer& vTensor::View::buffer( api::Command::Buffer& command_buffer, const Stage::Flags stage, const Access::Flags access) const { CMD cmd(*this, command_buffer); return buffer(cmd, stage, access); } vTensor::Buffer& vTensor::View::buffer( CMD& cmd, const Stage::Flags stage, const Access::Flags access) const { if ((access & Access::Read) && state_.is_dirty(Component::Buffer)) { if (state_.is_clean(Component::Staging)) { cmd.copy_staging_to_buffer( state_, staging(cmd, Stage::Transfer, Access::Read).object, buffer().object); } else if (state_.is_clean(Component::Image)) { cmd.copy_image_to_buffer( state_, image(cmd, Stage::Compute, Access::Read).object, buffer().object); } else { TORCH_INTERNAL_ASSERT( false, "Invalid state!"); } } cmd.barrier( state_.transition({ // Staging {}, // Buffer { vk_stage(stage), vk_access(stage, access), }, // Image {}, })); if (access & Access::Write) { state_.set_dirty(Component::All); } state_.set_clean(Component::Buffer); return buffer(); } vTensor::Image& vTensor::View::image() const { if (!image_ && state_.is_available(Component::Image)) { image_ = allocate_image( pool_, vk_extent(extents()), options()); } return image_; } vTensor::Image& vTensor::View::image( api::Command::Buffer& command_buffer, const Stage::Flags stage, const Access::Flags access) const { CMD cmd(*this, command_buffer); return image(cmd, stage, access); } vTensor::Image& vTensor::View::image( CMD& cmd, const Stage::Flags stage, const Access::Flags access) const { if ((access & Access::Read) && state_.is_dirty(Component::Image)) { cmd.copy_buffer_to_image( state_, buffer(cmd, stage, Access::Read).object, image().object); } cmd.barrier( state_.transition({ // Staging {}, // Buffer {}, // Image { vk_stage(stage), vk_access(stage, access), vk_layout(stage, access), }, })); if (access & Access::Write) { state_.set_dirty(Component::All); } state_.set_clean(Component::Image); return image(); } vTensor::Buffer& vTensor::View::staging() const { if (!state_.is_available(Component::Staging)) { return buffer(); } if (!staging_) { staging_ = allocate_staging( context_->gpu().adapter, pool_, sizes(), options()); } return staging_; } vTensor::Buffer& vTensor::View::staging( api::Command::Buffer& command_buffer, const Stage::Flags stage, const Access::Flags access) const { CMD cmd(*this, command_buffer); Buffer& staging = this->staging(cmd, stage, access); cmd.submit(fence(access)); return staging; } vTensor::Buffer& vTensor::View::staging( CMD& cmd, const Stage::Flags stage, const Access::Flags access) const { if ((access & Access::Read) && state_.is_dirty(Component::Staging)) { cmd.copy_buffer_to_staging( state_, buffer(cmd, Stage::Transfer, Access::Read).object, staging().object); } cmd.barrier( state_.transition({ // Staging { vk_stage(stage), vk_access(stage, access), }, // Buffer {}, // Image {}, })); if (access & Access::Write) { state_.set_dirty(Component::All); } state_.set_clean(Component::Staging); return staging(); } vTensor::Fence& vTensor::View::fence(const Access::Flags access) const { if (access & Access::Read) { fence_ = allocate_fence(&context_->resource().pool); } return fence_; } vTensor::Memory& vTensor::View::wait() const { if (fence_) { fence_.wait(); } return staging().memory; } void vTensor::View::verify() const { TORCH_INTERNAL_ASSERT(!image_ || state_.is_available(Component::Image)); TORCH_INTERNAL_ASSERT(!staging_ || state_.is_discrete()); } vTensor::View::State::State() : available_{}, dirty_{}, bundle_{} { } vTensor::View::State::State( const api::Adapter* const adapter, const IntArrayRef sizes) : available_{}, dirty_{}, bundle_{} { TORCH_INTERNAL_ASSERT_DEBUG_ONLY( adapter, "Invalid Vulkan adapter!"); available_ |= Component::Buffer; if (requires_image(sizes)) { available_ |= Component::Image; } if (requires_staging(adapter)) { available_ |= Component::Staging; } } #ifdef VULKAN_TENSOR_DEBUG std::ostream& operator<<( std::ostream&, const vTensor::View::State::Bundle&); #endif /* VULKAN_TENSOR_DEBUG */ vTensor::View::State::Transition vTensor::View::State::transition(const Bundle bundle) { const Bundle from = bundle_; Bundle& to = bundle_; if (bundle.staging) { to.staging = bundle.staging; } if (bundle.buffer) { to.buffer = bundle.buffer; } if (bundle.image) { to.image = bundle.image; } #ifdef VULKAN_TENSOR_DEBUG std::cout << "From:" << std::endl << from << std::endl; std::cout << "To:" << std::endl << to << std::endl; #endif /* VULKAN_TENSOR_DEBUG */ return Transition{ from, to, }; } void verify(const TensorOptions& options) { TORCH_CHECK( !options.has_requires_grad() || !options.requires_grad(), "'requires_grad' tensor option is not yet supported under Vulkan!"); TORCH_CHECK( !options.has_pinned_memory() || !options.pinned_memory(), "'pinned_memory' tensor option is not yet supported under Vulkan!"); TORCH_CHECK( !options.has_layout() || (c10::kStrided == options.layout()), "'layout' tensor option is not yet supported under Vulkan!"); TORCH_CHECK( !options.has_memory_format() || (c10::MemoryFormat::Contiguous == options.memory_format_opt()), "'memory_format' tensor option is not yet supported under Vulkan!"); } // // Debug // #ifdef VULKAN_TENSOR_DEBUG namespace { // Considering that VkAccessFlags is a weak typedef of a built-in data type, we // need to introduce a new type to allow overload resolution distinguish between // the two. struct Access final { VkAccessFlags value; }; std::ostream& operator<<( std::ostream& stream, const Access& access) { stream << "Access: "; if (0u == access.value) { return stream << " 0"; } if (access.value & VK_ACCESS_HOST_READ_BIT) { stream << " VK_ACCESS_HOST_READ_BIT"; } if (access.value & VK_ACCESS_HOST_WRITE_BIT) { stream << " VK_ACCESS_HOST_WRITE_BIT"; } if (access.value & VK_ACCESS_MEMORY_READ_BIT) { stream << " VK_ACCESS_MEMORY_READ_BIT"; } if (access.value & VK_ACCESS_MEMORY_WRITE_BIT) { stream << " VK_ACCESS_MEMORY_WRITE_BIT"; } if (access.value & VK_ACCESS_SHADER_READ_BIT) { stream << " VK_ACCESS_SHADER_READ_BIT"; } if (access.value & VK_ACCESS_SHADER_WRITE_BIT) { stream << " VK_ACCESS_SHADER_WRITE_BIT"; } if (access.value & VK_ACCESS_TRANSFER_READ_BIT) { stream << " VK_ACCESS_TRANSFER_READ_BIT"; } if (access.value & VK_ACCESS_TRANSFER_WRITE_BIT) { stream << " VK_ACCESS_TRANSFER_WRITE_BIT"; } return stream; } // Considering that VkImageLayout is a weak typedef of a built-in data type, // we need to introduce a new type to allow overload resolution distinguish // between the two. struct Image final { struct Layout final { VkImageLayout value; }; }; std::ostream& operator<<( std::ostream& stream, const Image::Layout& layout) { stream << "Layout: "; switch (layout.value) { case VK_IMAGE_LAYOUT_UNDEFINED: stream << " VK_IMAGE_LAYOUT_UNDEFINED"; break; case VK_IMAGE_LAYOUT_GENERAL: stream << " VK_IMAGE_LAYOUT_GENERAL"; break; case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL: stream << " VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL"; break; default: stream << " Unknown!"; break; }; return stream; } // Considering that VkPipelineStageFlags is a weak typedef of a built-in data // type, we need to introduce a new type to allow overload resolution distinguish // between the two. struct Stage final { VkPipelineStageFlags value; }; std::ostream& operator<<( std::ostream& stream, const Stage& stage) { stream << "Stage: "; if (0u == stage.value) { return stream << " 0"; } if (stage.value & VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT) { stream << " VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT"; } if (stage.value & VK_PIPELINE_STAGE_HOST_BIT) { stream << " VK_PIPELINE_STAGE_HOST_BIT"; } if (stage.value & VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT) { stream << " VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT"; } if (stage.value & VK_PIPELINE_STAGE_TRANSFER_BIT) { stream << " VK_PIPELINE_STAGE_TRANSFER_BIT"; } return stream; } } // namespace std::ostream& operator<<( std::ostream& stream, const vTensor::View::State::Bundle& bundle) { stream << "Staging\n " << Stage{ bundle.staging.stage, } << "\n " << Access{ bundle.staging.access, } << std::endl; stream << "Buffer\n " << Stage{ bundle.buffer.stage, } << "\n " << Access{ bundle.buffer.access, } << std::endl; stream << "Image\n " << Stage{ bundle.image.stage, } << "\n " << Access{ bundle.image.access, } << "\n " << Image::Layout{ bundle.image.layout, } << std::endl; return stream; } #endif /* VULKAN_TENSOR_DEBUG */ } // namespace ops } // namespace vulkan } // namespace native } // namespace at
22.718608
110
0.62043
[ "object" ]
3bf64c767c90a70e51373bafdaef9fe242e7d7b7
1,420
cc
C++
JetMETCorrections/Modules/src/JetCorrectionESChain.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-24T19:10:26.000Z
2019-02-19T11:45:32.000Z
JetMETCorrections/Modules/src/JetCorrectionESChain.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-23T13:40:24.000Z
2019-12-05T21:16:03.000Z
JetMETCorrections/Modules/src/JetCorrectionESChain.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
5
2018-08-21T16:37:52.000Z
2020-01-09T13:33:17.000Z
// // Original Author: Fedor Ratnikov // Created: Dec. 28, 2006 // // #include "JetMETCorrections/Modules/interface/JetCorrectionESChain.h" #include "JetMETCorrections/Objects/interface/ChainedJetCorrector.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/Utilities/interface/Exception.h" #include "FWCore/Framework/interface/ESHandle.h" #include "JetMETCorrections/Objects/interface/JetCorrectionsRecord.h" #include <algorithm> JetCorrectionESChain::JetCorrectionESChain(edm::ParameterSet const& fParameters) : mCorrectors (fParameters.getParameter < std::vector<std::string> > ("correctors")) { std::string label(fParameters.getParameter<std::string>("@module_label")); if (std::find(mCorrectors.begin(), mCorrectors.end(), label) != mCorrectors.end()) { throw cms::Exception("Recursion is not allowed") << "JetCorrectionESChain: corrector " << label << " is chained to itself"; } setWhatProduced(this, label); } JetCorrectionESChain::~JetCorrectionESChain() {} std::unique_ptr<JetCorrector> JetCorrectionESChain::produce(JetCorrectionsRecord const& fRecord) { std::unique_ptr<ChainedJetCorrector> corrector{ new ChainedJetCorrector}; corrector->clear (); for (size_t i = 0; i < mCorrectors.size(); ++i) { edm::ESHandle <JetCorrector> handle; fRecord.get(mCorrectors[i], handle); corrector->push_back(&*handle); } return corrector; }
36.410256
98
0.743662
[ "vector" ]
0ec238fa3952d1123a5eccd4a1417fee868bdc33
8,495
cpp
C++
hackathon/linus/rinside/inst/examples/wt/wtdensity.cpp
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
1
2021-12-27T19:14:03.000Z
2021-12-27T19:14:03.000Z
hackathon/linus/rinside/inst/examples/wt/wtdensity.cpp
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
null
null
null
hackathon/linus/rinside/inst/examples/wt/wtdensity.cpp
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
null
null
null
// -*- mode: C++; c-indent-level: 4; c-basic-offset: 4; tab-width: 8; -*- // // Wt usage example for RInside, inspired by the standard 'density sliders' example // // Copyright (C) 2011 Dirk Eddelbuettel and Romain Francois // // This file is licensed under GPL 2 or later, as are the rest of RInside and Rcpp // // Derived from hello.C in the Wt sources // Copyright (C) 2008 Emweb bvba, Heverlee, Belgium. #include <cstdio> #include <Wt/WApplication> #include <Wt/WBreak> #include <Wt/WContainerWidget> #include <Wt/WLineEdit> #include <Wt/WPushButton> #include <Wt/WText> #include <Wt/WImage> #include <Wt/WSpinBox> #include <Wt/WGroupBox> #include <Wt/WButtonGroup> #include <Wt/WRadioButton> #include <Wt/WHBoxLayout> #include <Wt/WEnvironment> #include <Wt/WFileResource> #include <RInside.h> using namespace Wt; class DensityApp : public WApplication { public: DensityApp(const WEnvironment& env, RInside & R); private: WLineEdit *codeEdit_; // to edit the RNG draw expression WButtonGroup *group_; // holds the radiobuttons WSpinBox *spin_; // selects the density bandwidth WImage *img_; // displays the image WFileResource *imgfile_; // controls the file resources WText *greeting_; // text label for status message void reportButton(); // called when new button selected void reportEdit(); // called when RNG expression edited void reportSpinner(); // called when bandwidth changed void plot(); // to call R for new plot enum Kernel { Gaussian = 0, Epanechnikov = 1, Rectangular = 2, Triangular = 3, Cosine = 4 }; RInside & R_; // reference to embedded R instance std::string tempfile_; // name of file used by R for plots int bw_, kernel_; // parameters used to estimate the density std::string cmd_; // random draw command string Rcpp::NumericVector Yvec_; // the random draw }; // The env argument contains information about the new session, and the initial request. // It must be passed to the WApplication // constructor so it is typically also an argument // for your custom application constructor. DensityApp::DensityApp(const WEnvironment& env, RInside & R) : WApplication(env), R_(R) { setTitle("Witty WebApp With RInside"); // application title setCssTheme("polished"); messageResourceBundle().use(appRoot() + "wtdensity"); new WText(WString::tr("overview"), root()); std::string tfcmd = "tfile <- tempfile(pattern=\"img\", tmpdir=\"/tmp\", fileext=\".png\")"; tempfile_ = Rcpp::as<std::string>(R_.parseEval(tfcmd)); // assign to 'tfile' in R, and report back bw_ = 100; kernel_ = 0; // parameters used to estimate the density cmd_ = "c(rnorm(100,0,1), rnorm(50,5,1))"; // random draw command string new WText(WString::tr("user input"), root()); Wt::WContainerWidget *wc = new Wt::WContainerWidget(root()); wc->setStyleClass("box"); Wt::WHBoxLayout *layout = new Wt::WHBoxLayout(); Wt::WContainerWidget *midbox = new Wt::WContainerWidget(root()); layout->addWidget(midbox); Wt::WContainerWidget *container = new Wt::WContainerWidget(root()); layout->addWidget(container); wc->setLayout(layout, AlignTop | AlignJustify); midbox->addWidget(new WText("Density estimation scale factor (div. by 100)")); midbox->addWidget(new WBreak()); // insert a line break spin_ = new WSpinBox(midbox); spin_->setRange(5, 200); spin_->setValue(bw_); spin_->valueChanged().connect(this, &DensityApp::reportSpinner); midbox->addWidget(new WBreak()); // insert a line break midbox->addWidget(new WText("R Command for data generation")); // show some text midbox->addWidget(new WBreak()); // insert a line break codeEdit_ = new WLineEdit(midbox); // allow text input codeEdit_->setTextSize(30); codeEdit_->setText(cmd_); codeEdit_->setFocus(); // give focus codeEdit_->enterPressed().connect(this, &DensityApp::reportEdit); group_ = new Wt::WButtonGroup(container); // use button group to arrange radio buttons Wt::WRadioButton *button; button = new Wt::WRadioButton("Gaussian", container); new Wt::WBreak(container); group_->addButton(button, Gaussian); button = new Wt::WRadioButton("Epanechnikov", container); new Wt::WBreak(container); group_->addButton(button, Epanechnikov); button = new Wt::WRadioButton("Rectangular", container); new Wt::WBreak(container); group_->addButton(button, Rectangular); button = new Wt::WRadioButton("Triangular", container); new Wt::WBreak(container); group_->addButton(button, Triangular); button = new Wt::WRadioButton("Cosine", container); new Wt::WBreak(container); group_->addButton(button, Cosine); group_->setCheckedButton(group_->button(kernel_)); group_->checkedChanged().connect(this, &DensityApp::reportButton); new WText(WString::tr("r result"), root()); Wt::WContainerWidget *botbox = new Wt::WContainerWidget(root()); botbox->setStyleClass("box"); imgfile_ = new Wt::WFileResource("image/png", tempfile_); imgfile_->suggestFileName("density.png"); // name the clients sees of datafile img_ = new Wt::WImage(imgfile_, "PNG version", botbox); new WText(WString::tr("browser info"), root()); Wt::WContainerWidget *stbox = new Wt::WContainerWidget(root()); stbox->setStyleClass("box"); greeting_ = new WText(stbox); // empty text greeting_->setText("Setting up..."); useStyleSheet("wtdensity.css"); // set our style sheet last reportEdit(); // create a new RNG draw in Yvec_ plot(); // and draw a new density plot } void DensityApp::reportButton() { kernel_ = group_->checkedId(); // get id of selected kernel plot(); } void DensityApp::reportEdit() { cmd_ = codeEdit_->text().toUTF8(); // get text written in box, as UTF-8, assigned to string std::string rng = "y2 <- " + cmd_ + "; y <- y2"; R_.parseEvalQNT(rng); // evaluates expression, assigns to 'y' Yvec_ = R_["y"]; // cache the y vector plot(); } void DensityApp::reportSpinner() { bw_ = spin_->value(); // get the value of the spin selector plot(); } void DensityApp::plot() { const char *kernelstr[] = { "gaussian", "epanechnikov", "rectangular", "triangular", "cosine" }; greeting_->setText("Starting R call"); R_["tfile"] = tempfile_; R_["bw"] = bw_; R_["kernel"] = kernelstr[kernel_]; // passes the string to R R_["y"] = Yvec_; std::string cmd0 = "png(filename=tfile,width=600,height=400); plot(density(y, bw=bw/100, kernel=kernel), xlim=range(y)+c(-2,2), main=\"Kernel: "; std::string cmd1 = "\"); points(y, rep(0, length(y)), pch=16, col=rgb(0,0,0,1/4)); dev.off()"; std::string cmd = cmd0 + kernelstr[kernel_] + cmd1; // stick the selected kernel in the middle R_.parseEvalQ(cmd); // evaluate command -- generates new density plot imgfile_->setChanged(); // important: tells consumer that image has changed, forces refresh greeting_->setText("Finished request from " + this->environment().clientAddress() + " using " + this->environment().userAgent()) ; } WApplication *createApplication(const WEnvironment& env) { // You could read information from the environment to decide whether // the user has permission to start a new application // // We grab an instance of the embedded R. Note we can start only one, // so resource conflicts have to be managed (eg add mutexes etc) // return new DensityApp(env, RInside::instance()); } int main(int argc, char **argv) { RInside R(argc, argv); // create the one embedded R instance // Your main method may set up some shared resources, but should then // start the server application (FastCGI or httpd) that starts listening // for requests, and handles all of the application life cycles. // // The last argument to WRun specifies the function that will instantiate // new application objects. That function is executed when a new user surfs // to the Wt application, and after the library has negotiated browser // support. The function should return a newly instantiated application // object. return WRun(argc, argv, createApplication); }
40.645933
149
0.661919
[ "object", "vector" ]
0ec2c3958048f8388728fbda1cf106fdb47419b0
5,896
cpp
C++
Task5/combinations.cpp
AGritsevich/Luxoft_gdansk_test_task
40b209903ddd44ee6e544cc8b1b346e29a8ab138
[ "MIT" ]
null
null
null
Task5/combinations.cpp
AGritsevich/Luxoft_gdansk_test_task
40b209903ddd44ee6e544cc8b1b346e29a8ab138
[ "MIT" ]
null
null
null
Task5/combinations.cpp
AGritsevich/Luxoft_gdansk_test_task
40b209903ddd44ee6e544cc8b1b346e29a8ab138
[ "MIT" ]
null
null
null
// Task 5 // Task: Combinations // Need to implement a simple console application which takes a text file as an input. Input's file format: // 1st line - integer number (N) // 2nd line - space-separted words // As an output it prints into all combinations of the words from it with up to N words. The output is printed into output file is specified as a second parameter. // Constraints: // 1. combinations should not be duplicated - i.e. combinations like "X Y" and "Y X" are treated as the same ones. // 2. words should not be duplicated - i.e. combinations like "A A" or "B B B" should be skipped. // An order of the combinations in file is up to the author. // It is expected that the code will show a good design approach, with possibilities of extensibility, algorithm implementation is effective and some basic test coverage is provided. // Please send the result in form of MS Visual Studio solution. #include <string> #include <fstream> #include <iostream> #include <sstream> #include <vector> #include <set> #include <assert.h> namespace CombiSpace{ class Combinations { public: explicit Combinations(std::string in_file, std::string out_file) : path_to_input_file_(in_file), path_to_output_file_(out_file), count_of_combinations_(0) {} bool Read_file() { std::ifstream infile(path_to_input_file_); if (!infile) { return false; } if (!(infile >> count_of_combinations_)) { return false; } std::string word; while(infile >> word) { words_.push_back(word); } infile.close(); return true; } void Combinate() { Recursive_Combinator(0); combination_word_.empty(); } bool Save_file() { std::ofstream output_file(path_to_output_file_); if (!output_file) { return false; } for (auto line:possible_combinations_) { output_file << line << std::endl; } output_file.close(); return true; } size_t GetCountOfCombinations() {return possible_combinations_.size();} private: Combinations &operator=(const Combinations&) {return *this;} void Recursive_Combinator(const unsigned int start_position) { for (auto i = start_position; i < words_.size(); i++) { combination_word_ += words_[i]; possible_combinations_.insert(combination_word_); if (i < words_.size() && combination_word_.length() < count_of_combinations_) { Recursive_Combinator(i + 1); } combination_word_.erase(combination_word_.length() - 1); } } const std::string path_to_input_file_; const std::string path_to_output_file_; unsigned int count_of_combinations_; std::vector<std::string> words_; std::set<std::string> possible_combinations_; std::string combination_word_; }; } // namespace Combinations int main_flow(int argc, char* argv[] ) { using namespace CombiSpace; if (argc < 3 || !strcmp(argv[1], "help")) { std::cout << "Help message:\n" \ << " task5.exe [in_path] [out_path]" \ << " in_path - path to file with conditions to task" \ << " out_path - path with name to output file" \ << std::endl; return 1; } Combinations combinator(argv[1], argv[2]); if (!combinator.Read_file()) { std::cout << "Unable to open file: " << argv[1] << std::endl; return 1; } combinator.Combinate(); if (!combinator.Save_file()) { std::cout << "Unable to save file: " << argv[2] << std::endl; return 1; } return 0; } void SelfTest() { { char *argv[] = {"Self", "input_normal.txt", "output.txt"}; assert(!main_flow(3, argv) && "Normal flow"); } { char *argv[] = {"Self", "file_do_not_exist.txt", "output.txt"}; assert(main_flow(3, argv) && "No input file"); } { char *argv[] = {"Self", "input_empy.txt", "output.txt"}; assert(main_flow(3, argv) && "Input file is empty"); } { char *argv[] = {"Self", "input_normal.txt", ""}; assert(main_flow(3, argv) && "No output file"); } { CombiSpace::Combinations combinator("input_empty.txt", "output_empty.txt"); assert(combinator.Read_file() && "Input empty: open file"); combinator.Combinate(); assert(combinator.GetCountOfCombinations() != 0 && "Input empty: open file"); assert(combinator.Save_file() && "Input empty: save file"); } { CombiSpace::Combinations combinator("input_empty.txt", "output_empty.txt"); assert(combinator.Read_file() && "Input empty: open file"); combinator.Combinate(); assert(combinator.GetCountOfCombinations() != 0 && "Input empty: open file"); assert(combinator.Save_file() && "Input empty: save file"); } { CombiSpace::Combinations combinator("input_empty.txt", "output_empty.txt"); assert(combinator.Read_file() && "Input empty: open file"); combinator.Combinate(); assert(combinator.GetCountOfCombinations() != 0 && "Input empty: open file"); assert(combinator.Save_file() && "Input empty: save file"); } { CombiSpace::Combinations combinator("input_empty.txt", "output_empty.txt"); assert(combinator.Read_file() && "Input empty: open file"); combinator.Combinate(); assert(combinator.GetCountOfCombinations() != 0 && "Input empty: open file"); assert(combinator.Save_file() && "Input empty: save file"); } { CombiSpace::Combinations combinator("input_empty.txt", "output_empty.txt"); assert(combinator.Read_file() && "Input empty: open file"); combinator.Combinate(); assert(combinator.GetCountOfCombinations() != 0 && "Input empty: open file"); assert(combinator.Save_file() && "Input empty: save file"); } { CombiSpace::Combinations combinator("input_empty.txt", "output_empty.txt"); assert(combinator.Read_file() && "Input empty: open file"); combinator.Combinate(); assert(combinator.GetCountOfCombinations() != 0 && "Input empty: open file"); assert(combinator.Save_file() && "Input empty: save file"); } } int main(int argc, char* argv[] ) { if (argc == 2 && !strcmp(argv[1], "test")) { SelfTest(); } else { main_flow(argc, argv); } }
30.86911
182
0.681479
[ "vector" ]
0ec397e3dfaea39d446ab360aeb747428c3216cc
8,562
cpp
C++
src/set49mode.cpp
mahuti/Set49Mode
588c34aa572be6bd4fded43199f6153aa7d6ff44
[ "MIT" ]
2
2020-07-06T16:45:44.000Z
2021-11-05T08:32:10.000Z
src/set49mode.cpp
mahuti/set49mode
588c34aa572be6bd4fded43199f6153aa7d6ff44
[ "MIT" ]
null
null
null
src/set49mode.cpp
mahuti/set49mode
588c34aa572be6bd4fded43199f6153aa7d6ff44
[ "MIT" ]
null
null
null
/* set49mode sets the mode of Groovy Game Gear's 49-way Joystick. This script is based off of De Waegeneer Gijsbrecht's 2018 SetUltrastik360 script This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. contact: mahuti@gmail.com */ #include <chrono> #include <cstring> #include <iostream> #include <libusb-1.0/libusb.h> #include <sstream> #include <thread> #include <vector> #include <algorithm> #define UM_REQUEST_TYPE 0x21 #define UM_REQUEST 9 #define UM_TIMEOUT 2000 #define J_VENDOR_ID 0xFAFA #define J_REPORT 0x0200 #define J_MESG_LENGTH 2 #define J_INTERFACE 0 #define KERNEL_DRIVER_ATTACHED 1 #define VERSION "1.0.0" void cleanup(libusb_context * context, libusb_device_handle * devicehandle ) { if (devicehandle) { libusb_close(devicehandle); } if (context) { libusb_exit(context); } } [[noreturn]] void errorhandler(libusb_context * context, libusb_device_handle * devicehandle, const std::string & errorMessage) { std::cerr << "ERROR: " << errorMessage << "\n"; cleanup(context, devicehandle); exit(EXIT_FAILURE); } [[noreturn]] void errorhandler(libusb_context * context, libusb_device_handle * devicehandle, int rc) { std::cerr << "ERROR: " << libusb_error_name(rc) << " - " << libusb_strerror(static_cast<libusb_error>(rc)) << "\n"; cleanup(context, devicehandle); exit(EXIT_FAILURE); } auto apply49mode(unsigned char modeId, unsigned char product_id) { libusb_context * context(nullptr); libusb_device * device(nullptr); libusb_device_handle * devicehandle(nullptr); libusb_device ** devices; auto rc = libusb_init(&context); if (rc != LIBUSB_SUCCESS) { errorhandler(context, devicehandle, rc); } #if LIBUSB_API_VERSION >= 0x01000106 libusb_set_option(context, LIBUSB_OPTION_LOG_LEVEL, LIBUSB_LOG_LEVEL_WARNING); #else libusb_set_debug(context, LIBUSB_LOG_LEVEL_WARNING); #endif auto deviceCount = libusb_get_device_list(context, &devices); for (auto deviceIndex(0); deviceIndex < deviceCount; deviceIndex++) { device = devices[deviceIndex]; libusb_device_descriptor descriptor = {}; rc = libusb_get_device_descriptor(device, &descriptor); if (rc != LIBUSB_SUCCESS) { std::cout << "WARNING: " << libusb_error_name(rc) << " - " << libusb_strerror(static_cast<libusb_error>(rc)) << " - trying to proceed...\n"; } else { if ((descriptor.idVendor == J_VENDOR_ID) && (descriptor.idProduct == product_id)) { break; } } device = nullptr; } if (device == nullptr) { std::cout << "GPWiz49Way Device id# " << static_cast<unsigned>(product_id) << " not found\n"; cleanup(context, devicehandle); return 0; // errorhandler(context, devicehandle, ss.str()); } else { // good to go rc = libusb_open(device, &devicehandle); if (rc != LIBUSB_SUCCESS) { errorhandler(context, devicehandle, rc); } if (devicehandle) { if (libusb_kernel_driver_active(devicehandle, J_INTERFACE) == KERNEL_DRIVER_ATTACHED) { rc = libusb_detach_kernel_driver(devicehandle, J_INTERFACE); libusb_claim_interface(devicehandle,J_INTERFACE); if (rc != LIBUSB_SUCCESS) { errorhandler(context, devicehandle, rc); } } unsigned char message[J_MESG_LENGTH] = { 204, modeId }; rc = libusb_control_transfer(devicehandle, UM_REQUEST_TYPE, UM_REQUEST, J_REPORT, J_INTERFACE, message, J_MESG_LENGTH, UM_TIMEOUT); std::cout << "GPWiz49way Device id# " << static_cast<unsigned>(product_id) << ((rc == sizeof(message)) ? " successfully converted " : " failed to convert ") << "to mode# " << static_cast<unsigned>(modeId) << "\n"; } } libusb_release_interface(devicehandle, J_INTERFACE); rc = libusb_attach_kernel_driver(devicehandle, J_INTERFACE); libusb_free_device_list(devices, 1); cleanup(context, devicehandle); return 0; } int main(int argc, char *argv[]) { unsigned char modeId(1); long int joystick(0); switch (argc) { case 3: try { joystick = std::stol(argv[2], nullptr, 10); if (joystick < 0 || joystick > 1) { joystick = 0; } } catch (std::exception &) { joystick = 0; } case 2: try { modeId = std::stol(argv[1], nullptr, 10); if (modeId < 1 || modeId > 8) { modeId = 1; } } catch (std::exception &) { modeId = 1; } break; default: std::cout << "GPWiz49 switcher Version " << VERSION << "\n\n" << "This software is to set the joystick mode for the GPWiz49 Joystick from GroovyGameGear. \n" << "https://groovygamegear.com/webstore/index.php?main_page=product_info&cPath=76_81&products_id=233\n" << "This script will not work on the other GGG 49way encoders, just the GPWiz49,\n" << "though it should be easy to change the product ID to support other encoders\n" << "\n" << "=====================================\n" << "\n" << "Note: To use the GGG GPWiz49 on a Raspberry Pi, you will need to set some HID quirks.\n" << "1. Create file /etc/modprobe.d/usbhid.conf with the following:\n" << " options usbhid quirks=0xFAFA:0x0007:0x00000020,0xFAFA:0x0008:0x00000020\n" << "2. Add a hid quirk to the end of boot script: sudo pico /boot/cmdline.txt\n" << " usbhid.quirks=0xFAFA:0x0007:0x00000020,0xFAFA:0x0008:0x00000020\n" << "If you want to use one of the other GGG products, you will need to change the existing product id: 0x0007\n" << "3. You will also need to add a UDEV rule so that this app can be run without ROOT privileges\n" << " sudo pico :/etc/udev/rules.d/50-set49mode.rules\n" << "Add this:\n" << " ACTION=='add', SUBSYSTEMS=='usb', ATTRS{idVendor}=='fafa', ATTRS{idProduct}=='00ff', MODE:='666' \n" << "After saving and closing the UDEV rule, Reload UDEV\n" << " sudo udevadm control --reload\n" << "\n" << "====================================\n" << "\n" << "Usage\n" << "set49mode <joystick-mode> <joystick-type>\n" << "modes:\n" << "1: 49-way (default)\n" << "2: Progressive 49\n" << "3: 8-Way\n" << "4: 4-Way\n" << "5: 4-Way Diagonal\n" << "6: 2-Way Horizontal\n" << "7: 2-Way Vertical\n" << "8: 16-Way / Large dead zone in center\n" << "\n" << "joystick types:\n" << "0: Happs (default doesn't need to be passed in)\n" << "1: Williams\n" << "\n" << "examples\n" << " set49mode 5 1\n" << "GPWiz49 will switch to 4-Way Diagonal on a Williams stick\n" << " set49mode 8\n" << "Will switch to 16-Way on a Happs stick\n" << "\n" << "====================================\n" << "\n" << "This program comes with ABSOLUTELY NO WARRANTY. This is free software,\nand you are welcome to redistribute it under certain conditions.\n" << "license: GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007\nCopyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n"; return EXIT_SUCCESS; } // williams stick, just add 10. if (joystick) { modeId+=10; } apply49mode(modeId, 0x0007); apply49mode(modeId, 0x0008); apply49mode(modeId, 0x0009); apply49mode(modeId, 0x000a); return EXIT_SUCCESS; }
37.552632
222
0.590049
[ "vector" ]
0ecad235af01f1adb33a7be27b0594f43f2fc700
4,512
cpp
C++
demo/ngraph.native.demo/ngraph.native.demo/main.cpp
MisterDev/ngraph.native
bd5b6a6f753be2488d5e5e31bd11e6987649c930
[ "MIT" ]
47
2015-05-23T00:00:25.000Z
2021-09-20T16:30:06.000Z
demo/ngraph.native.demo/ngraph.native.demo/main.cpp
MisterDev/ngraph.native
bd5b6a6f753be2488d5e5e31bd11e6987649c930
[ "MIT" ]
13
2015-07-29T23:31:21.000Z
2021-05-19T08:07:59.000Z
demo/ngraph.native.demo/ngraph.native.demo/main.cpp
MisterDev/ngraph.native
bd5b6a6f753be2488d5e5e31bd11e6987649c930
[ "MIT" ]
34
2015-09-30T22:02:17.000Z
2021-05-21T06:50:57.000Z
// reading an entire binary file #include <iostream> #include <fstream> #include <string> #include <sstream> #include <regex> #include <unistd.h> #include "layout.h" using namespace std; void save(int i, std::vector<Body> *bodies) { std::stringstream ss; ss << i << ".bin"; std::ofstream outfile (ss.str(), std::ofstream::binary); char block[3 * 4]; int *triplet = (int *)&block; for (vector<Body>::iterator body = bodies->begin() ; body != bodies->end(); ++body) { triplet[0] = floor(body->pos.x + 0.5); triplet[1] = floor(body->pos.y + 0.5); triplet[2] = floor(body->pos.z + 0.5); // cout << triplet[0] << "," << triplet[1] << "," << triplet[2] << " <- node" << endl; outfile.write(block, 3 * 4); } outfile.close(); } typedef struct { int *content; long size; } FileContent; FileContent* readFile(const char *fileName) { streampos size; char * memblock; ifstream file (fileName, ios::in|ios::binary|ios::ate); if (file.is_open()) { size = file.tellg(); memblock = new char [size]; file.seekg(0, ios::beg); file.read(memblock, size); file.close(); FileContent *result = new FileContent(); result->size = size/4; result->content = (int *) memblock; return result; } else { return nullptr; } } int getIterationNumberFromPositionFileName(const char *positionFileName) { cmatch match; regex pattern(".*?(\\d+)\\.bin$"); regex_match(positionFileName, match, pattern); if (match.size() == 2) { try { return stoi(match[1]) + 1; } catch (...) { return 0; } } return 0; } int main(int argc, const char * argv[]) { if (argc < 2) { cout << "Usage: " << endl << " layout++ links.bin [positions.bin]" << endl << "Where" << endl << " `links.bin` is a path to the serialized graph. See " << endl << " https://github.com/anvaka/ngraph.tobinary for format description" << endl << " `positions.bin` is optional file with previously saved positions. " << endl << " This file should match `links.bin` graph, otherwise bad things " << endl << " will happen" << endl; return -1; } const char * graphFileName = argv[1]; srand(42); char cwd[1024]; if (getcwd(cwd, 1024) != NULL) { cout << cwd << endl; } else { cout << errno; } cout << "Loading links from " << graphFileName << "... " << endl; FileContent *graphFilePtr = readFile(graphFileName); if (graphFilePtr == nullptr) { throw "Could not read links file"; } FileContent graphFile = *graphFilePtr; Layout graphLayout; int startFrom = 0; if (argc < 3) { graphLayout.init(graphFile.content, graphFile.size); cout << "Done. " << endl; cout << "Loaded " << graphLayout.getBodiesCount() << " bodies;" << endl; } else { const char * posFileName = argv[2]; startFrom = getIterationNumberFromPositionFileName(posFileName); cout << "Loading positions from " << posFileName << "... "; FileContent *positions = readFile(posFileName); if (positions == nullptr) throw "Positions file could not be read"; cout << "Done." << endl; graphLayout.init(graphFile.content, graphFile.size, positions->content, positions->size); cout << "Loaded " << graphLayout.getBodiesCount() << " bodies;" << endl; } // TODO: This should be done via arguments, but doing it inline now: // If current folder containsfil 'weights.bin' we will try to assign // nodes weights from this file FileContent *weights = readFile("weights.bin"); if (weights != nullptr) { cout << "Detected weights.bin file in the current folder." << endl; cout << "Assuming each node has assigned body weight. Reading weights..." << endl; cout << "Size: " << weights->size; graphLayout.setBodiesWeight(weights->content); } cout << "Starting layout from " << startFrom << " iteration;" << endl; for (int i = startFrom; i < 10000; ++i) { cout << "Step " << i << endl; bool done = graphLayout.step(); if (done) { cout << "Done!" << endl; break; } if (i % 5 == 0) { save(i, graphLayout.getBodies()); } } delete[] graphFile.content; }
30.90411
97
0.561835
[ "vector" ]
0ecdc060d1d1b068d88c291fc33f9615914e89ea
11,688
cpp
C++
LR/LRParser.cpp
jhxqy/LL-1-analyzer
ccd299a84e5698044a852be8c6fce7d6f655778b
[ "MIT" ]
2
2020-11-11T14:44:01.000Z
2020-12-20T12:39:18.000Z
LR/LRParser.cpp
jhxqy/LL-SLR-analyzer
ccd299a84e5698044a852be8c6fce7d6f655778b
[ "MIT" ]
null
null
null
LR/LRParser.cpp
jhxqy/LL-SLR-analyzer
ccd299a84e5698044a852be8c6fce7d6f655778b
[ "MIT" ]
null
null
null
// // LRParser.cpp // LL1 // // Created by 贾皓翔 on 2019/9/11. // Copyright © 2019 贾皓翔. All rights reserved. // #include "LRParser.hpp" #include <stack> GeneratingExprPool::GeneratingExprPool(){} GeneratingExprPool::~GeneratingExprPool(){ for(auto i:data){ delete i.second; } } int GeneratingExprPool::id_=0; int GeneratingExprPool::CreateExpr(const std::string &nonTerminal, std::vector<std::string> expr){ auto *p=new GeneratingExpr(nonTerminal,expr); int id=id_++; data.insert(std::make_pair(id,p)); return id; } GeneratingExpr& GeneratingExprPool::Get(int id){ return *(data[id]); } LRItem::LRItem(int e,int p,GeneratingExprPool &po):exprId(e),pointPosition(p),pool(po){ } bool LRItem::operator==(const LRItem& a) const{ return exprId==a.exprId&&pointPosition==a.pointPosition; } std::size_t LRItemHash::operator()(const LRItem &a) const{ auto h=std::hash<int>(); return h(a.exprId)^(h(a.pointPosition)<<2); } LRCollection LRParser::Closure(const LRCollection &I){ LRCollection J=I; J.collectionId=I.collectionId+1; int count=0; int n=0; do{ n=count; for(auto i:J.collection){ if (!i.End()) { for(auto j:pr[i.NextExpr()]){ LRItem l=LRItem(j,0,pool); if (!J.collection.count(l)) { J.collection.insert(l); n++; } } } } }while(n!=count); return J; } void LRCollection::PrintLRC(const LRCollection &c){ using namespace std; cout<<"id:"<<c.collectionId<<endl; for(auto i:c.collection){ string nonTem=i.pool.Get(i.exprId).nonTerminal; cout<<nonTem<<" -> "; vector<string> v=i.pool.Get(i.exprId).Expr; for(size_t j=0;j<v.size();j++){ if (j==i.pointPosition) { cout<<". "; } cout<<v[j]<<" "; } if(i.pointPosition==v.size()){ cout<<"."; } cout<<endl; } cout<<endl; } LRParser::LRParser(const std::string &startSymbol_,std::basic_istream<char> &ss,std::unordered_set<std::string> t):startSymbol(startSymbol_),Terminals(t){ std::string tmp; while (std::getline(ss,tmp)) { if (tmp.empty()) { continue; } if (!tmp.compare("end")) { break; } std::vector<std::string> v; JSTR::StringUtils::Split(tmp, v, ' '); if (pr.count(v[0])==0) { pr[v[0]]=std::vector<int>(); } nonTerminals.insert(v[0]); std::vector<std::string> expr; for (int i=2;i<v.size();i++){ if (!v[i].compare("|")) { pr[v[0]].push_back(pool.CreateExpr(v[0], expr)); expr.clear(); }else{ if (!Terminals.count(v[i])&&!nonTerminals.count(v[i])) { nonTerminals.insert(v[i]); } expr.push_back(v[i]); if (i==v.size()-1) { pr[v[0]].push_back(pool.CreateExpr(v[0], expr)); } } } } pr[startSymbol_+"'"].push_back(pool.CreateExpr(startSymbol_+"'", std::vector<std::string>{startSymbol_})); } LRCollection LRParser::GOTO(const LRCollection &I,const std::string &X){ LRCollection J; J.collectionId=I.collectionId+1; for(auto i:I.collection){ if(!i.End()&&i.NextExpr().compare(X)==0){ LRItem item(i.exprId,i.pointPosition+1,i.pool); J.collection.insert(item); } } return J; } void LRParser::_First(const std::string&X){ for(auto i:Terminals){ firstMap[i]=std::unordered_set<std::string>{i}; } for(auto i:nonTerminals){ for(auto j:pr[i]){ std::unordered_set<std::string> last{"ε"}; const std::vector<std::string> &expr=pool.Get(j).Expr; if (expr.size()==1&&expr[0].compare("ε")==0){ if(firstMap.count(i)==0){ firstMap[i]=std::unordered_set<std::string>(); } firstMap[i].insert("ε"); }else{ for(auto k:expr){ if(last.count("ε")){ for(auto l:firstMap[k]){ firstMap[i].insert(l); } } last=firstMap[k]; } } } } } std::unordered_set<std::string> LRParser::First(const std::string &start){ static bool finish=false; if(finish){ return firstMap[start]; } int count=0,n=0; for(auto i:firstMap){ n+=i.second.size(); } do{ count=n; _First(startSymbol); n=0; for(auto i:firstMap){ n+=i.second.size(); } }while(count!=n); finish=true; return First(start); } std::unordered_set<std::string> LRParser::Follow(const std::string &start){ static bool finish=false; if(finish){ return followMap[start]; } int count=0,n=0; for(auto i:followMap){ n+=i.second.size(); } do{ count=n; _Follow(startSymbol); n=0; for(auto i:followMap){ n+=i.second.size(); } }while(count!=n); finish=true; return Follow(start); } void LRParser::_Follow(const std::string &start){ if (!followMap.count(start)) { followMap.insert(std::make_pair(start,std::unordered_set<std::string>())); followMap[start].insert("$"); } for(auto CA:pr){ for(auto eachCA:CA.second){ const std::vector<std::string> &v=pool.Get(eachCA).Expr; for (int i=0; i<v.size(); i++) { if (nonTerminals.count(v[i])) { if (i!=v.size()-1) { for (auto x:First(v[i+1])) { if (x!="ε") { followMap[v[i]].insert(x); }else if(i==v.size()-2){ for(auto c:followMap[CA.first]){ followMap[v[i]].insert(c); } } } }else{ for(auto c:followMap[CA.first]){ followMap[v[i]].insert(c); } } }else{ } } } } } std::unordered_set<LRCollection,LRCollectionHash> LRParser::Items(){ std::unordered_set<LRCollection,LRCollectionHash> C; LRCollection c1=LRCollection(); c1.collection.insert(LRItem(pr[startSymbol+"'"][0], 0, pool)); c1=Closure(c1); c1.collectionId=0; C.insert(c1); int count=0; int n=0; int id=c1.collectionId+1; do{ count=n; for(auto I:C){ for(auto X:Terminals){ if(!X.compare("ε")){ continue; } // LRCollection::PrintLRC(I); LRCollection tmp=GOTO(I, X); tmp=Closure(tmp); if (tmp.collection.size()!=0&&C.count(tmp)==0) { tmp.collectionId=id++; C.insert(tmp); n++; } } for(auto X:nonTerminals){ LRCollection tmp=GOTO(I, X); tmp=Closure(tmp); if (tmp.collection.size()!=0&&C.count(tmp)==0) { tmp.collectionId=id++; C.insert(tmp); n++; } } } }while(n!=count); return C; } std::pair<ActionMap, GotoMap> LRParser::ActionAndGoto(){ std::unordered_set<LRCollection,LRCollectionHash> states=Items(); auto T=Terminals; T.insert("$"); ActionMap am(Sequence(0, int(states.size()-1)),T); GotoMap gm(Sequence(0, int(states.size()-1)),nonTerminals); // for(auto i:states){ // LRCollection::PrintLRC(i); // } for(LRCollection lrCollection:states){ std::unordered_set<LRItem,LRItemHash> &collection=lrCollection.collection; for(LRItem item:collection){ GeneratingExpr &e=pool.Get(item.exprId); if (!item.End()&&Terminals.count(item.NextExpr())) { LRCollection lr=GOTO(lrCollection, item.NextExpr()); lr=Closure(lr); auto existedState=states.find(lr); if(existedState!=states.end()){ am[lrCollection.collectionId][item.NextExpr()]=ActionStatus(ActionStatus::Action::SHIFT,existedState->collectionId); } }else if(item.End()&&e.nonTerminal.compare(startSymbol+"'")!=0){ // if(lrCollection.collectionId==11){ // std::cout<<"1"<<std::endl; // } for(std::string t:Follow(e.nonTerminal)){ am[lrCollection.collectionId][t]=ActionStatus(ActionStatus::Action::REDICE,item.exprId); } }else if(item.End()&&e.nonTerminal.compare(startSymbol+"'")==0){ am[lrCollection.collectionId]["$"]=ActionStatus(ActionStatus::Action::ACCEPT); }else{ LRCollection lr=GOTO(lrCollection, item.NextExpr()); lr=Closure(lr); auto existedState=states.find(lr); if(existedState!=states.end()){ gm[lrCollection.collectionId][item.NextExpr()]=existedState->collectionId; } } } } // am.printTable(); // std::cout<<std::endl; // gm.printTable(); return std::make_pair(am, gm); } void LRParser::Parse(const std::string &w){ std::unordered_set<LRCollection,LRCollectionHash> states=Items(); auto pair=ActionAndGoto(); ActionMap ACTION=pair.first; GotoMap GOTO=pair.second; LRCollection start; for(auto s:states){ bool f=false; for(auto i:s.collection){ if(i.exprId==pr[startSymbol+"'"][0]&&i.pointPosition==0){ f=true; start=s; break; } } if(f){ break; } } std::stack<int> stack; stack.push(start.collectionId); //初始化初始状态-1 std::vector<std::string> inputBuf; JSTR::StringUtils::Split(w, inputBuf, ' '); inputBuf.push_back("$"); int a=0; while (1) { int s=stack.top(); ActionStatus state=ACTION[s][inputBuf[a]]; if(state.a==ActionStatus::Action::SHIFT){ stack.push(state.shiftTo); a++; }else if(state.a==ActionStatus::Action::REDICE){ std::vector<std::string> rediceExpr=pool.Get(state.exprID).Expr; int RediceNumber=(int)rediceExpr.size(); while (RediceNumber--) { stack.pop(); } int t=stack.top(); stack.push(GOTO[t][pool.Get(state.exprID).nonTerminal]); std::cout<<pool.Get(state.exprID).nonTerminal<<" -> "; for(auto i:rediceExpr){ std::cout<<i<<" "; } std::cout<<std::endl; }else if(state.a==ActionStatus::Action::ACCEPT){ std::cout<<"Accept!"<<std::endl; break; }else { throw std::runtime_error("parse error!"); } } }
29.515152
154
0.489562
[ "vector" ]
0ed63533d06000c191acaed52ede6015563785ad
9,059
cpp
C++
rai/rai_token/token.cpp
raicoincommunity/Raicoin
22dd5f16d299ced2b14f321682153b9e477c1609
[ "MIT" ]
94
2019-09-25T05:57:44.000Z
2021-12-30T09:08:06.000Z
rai/rai_token/token.cpp
raicoincommunity/Raicoin
22dd5f16d299ced2b14f321682153b9e477c1609
[ "MIT" ]
4
2020-05-06T10:10:14.000Z
2021-12-26T09:35:16.000Z
rai/rai_token/token.cpp
raicoincommunity/Raicoin
22dd5f16d299ced2b14f321682153b9e477c1609
[ "MIT" ]
13
2019-09-25T05:57:52.000Z
2022-02-24T02:09:03.000Z
#include <rai/rai_token/token.hpp> rai::TokenError::TokenError() : return_code_(rai::ErrorCode::SUCCESS) { } rai::TokenError::TokenError(rai::ErrorCode error_code) : return_code_(error_code) { } rai::Token::Token(rai::ErrorCode& error_code, boost::asio::io_service& service, const boost::filesystem::path& data_path, rai::Alarm& alarm, const rai::TokenConfig& config) : App(error_code, service, data_path / "token_data.ldb", alarm, config.app_, subscribe_, rai::Token::BlockTypes(), rai::Token::Provide()), service_(service), alarm_(alarm), config_(config), subscribe_(*this) { IF_NOT_SUCCESS_RETURN_VOID(error_code); error_code = InitLedger_(); } rai::ErrorCode rai::Token::PreBlockAppend( rai::Transaction& transaction, const std::shared_ptr<rai::Block>& block, bool confirmed) { if (confirmed) { return rai::ErrorCode::SUCCESS; } do { if (block->Extensions().empty()) { break; } rai::Extensions extensions; rai::ErrorCode error_code = extensions.FromBytes(block->Extensions()); if (error_code != rai::ErrorCode::SUCCESS) { break; } if (extensions.Count(rai::ExtensionType::TOKEN) > 0) { return rai::ErrorCode::APP_PROCESS_CONFIRM_REQUIRED; } } while (0); // todo: check swap waitings return rai::ErrorCode::SUCCESS; } rai::ErrorCode rai::Token::AfterBlockAppend( rai::Transaction& transaction, const std::shared_ptr<rai::Block>& block, bool confirmed) { do { if (block->Extensions().empty()) { break; } rai::Extensions extensions; rai::ErrorCode error_code = extensions.FromBytes(block->Extensions()); if (error_code != rai::ErrorCode::SUCCESS) { break; } if (extensions.Count(rai::ExtensionType::TOKEN) == 0) { break; } if (!confirmed) { rai::Log::Error( "Alias::AfterBlockAppend: unexpected unconfirmed block"); return rai::ErrorCode::APP_PROCESS_CONFIRM_REQUIRED; } error_code = Process(transaction, block, extensions); IF_NOT_SUCCESS_RETURN(error_code); } while (0); // todo: process swap waitings // todo: process swap timeout return rai::ErrorCode::SUCCESS; } rai::ErrorCode rai::Token::Process(rai::Transaction& transaction, const std::shared_ptr<rai::Block>& block, const rai::Extensions& extensions) { rai::Account account = block->Account(); uint64_t height = block->Height(); rai::AccountTokensInfo info; bool error = ledger_.AccountTokensInfoGet(transaction, account, info); if (!error && info.head_ >= height) { rai::Log::Error(rai::ToString("Token::Process: block re-entry, hash=", block->Hash().StringHex())); return rai::ErrorCode::SUCCESS; } if (extensions.Count(rai::ExtensionType::TOKEN) != 1) { return UpdateLedgerCommon_(transaction, block, rai::ErrorCode::TOKEN_MULTI_EXTENSIONS); } rai::ExtensionToken token; rai::ErrorCode error_code = token.FromExtension(extensions.Get(rai::ExtensionType::TOKEN)); if (error_code != rai::ErrorCode::SUCCESS) { return UpdateLedgerCommon_(transaction, block, error_code); } if (token.op_data_ == nullptr) { rai::Log::Error( rai::ToString("Token::Process: op_data is null, hash=", block->Hash().StringHex())); return rai::ErrorCode::APP_PROCESS_UNEXPECTED; } using Op = rai::ExtensionToken::Op; rai::TokenError token_error; switch (token.op_) { case Op::CREATE: { token_error = ProcessCreate_(transaction, block, token); break; } default: { rai::Log::Error( rai::ToString("Token::Process: unknown token operation, hash=", block->Hash().StringHex())); return rai::ErrorCode::APP_PROCESS_UNEXPECTED; } } error_code = ProcessError_(transaction, token_error); IF_NOT_SUCCESS_RETURN(error_code); return rai::ErrorCode::SUCCESS; } rai::ErrorCode rai::Token::UpdateLedgerCommon_( rai::Transaction& transaction, const std::shared_ptr<rai::Block>& block, rai::ErrorCode status, const std::vector<rai::TokenKey>& tokens) { rai::Account account = block->Account(); uint64_t height = block->Height(); rai::AccountTokensInfo info; bool error = ledger_.AccountTokensInfoGet(transaction, account, info); if (error) { info = rai::AccountTokensInfo(); } else { if (height <= info.head_) { rai::Log::Error(rai::ToString( "Token::UpateLedgerCommon_: unexpected block height, hash=", block->Hash().StringHex())); return rai::ErrorCode::APP_PROCESS_UNEXPECTED; } } rai::TokenBlock token_block(info.head_, block->Hash(), status); error = ledger_.TokenBlockPut(transaction, account, height, token_block); if (error) { rai::Log::Error( rai::ToString("Token::UpateLedgerCommon_: put token block, hash=", block->Hash().StringHex())); return rai::ErrorCode::APP_PROCESS_LEDGER_PUT; } info.head_ = height; info.blocks_ += 1; info.last_active_ = block->Timestamp(); error = ledger_.AccountTokensInfoPut(transaction, account, info); if (error) { rai::Log::Error(rai::ToString( "Token::UpateLedgerCommon_: put account tokens info, hash=", block->Hash().StringHex())); return rai::ErrorCode::APP_PROCESS_LEDGER_PUT; } for (const auto& token : tokens) { rai::AccountTokenInfo account_token_info; error = ledger_.AccountTokenInfoGet(transaction, account, token.chain_, token.address_, account_token_info); if (error) { account_token_info = rai::AccountTokenInfo(); } else { if (height <= account_token_info.head_) { rai::Log::Error(rai::ToString( "Token::UpateLedgerCommon_: unexpected block height, hash=", block->Hash().StringHex())); return rai::ErrorCode::APP_PROCESS_UNEXPECTED; } } rai::AccountTokenLink link(account, token.chain_, token.address_, height); error = ledger_.AccountTokenLinkPut(transaction, link, account_token_info.head_); if (error) { rai::Log::Error(rai::ToString( "Token::UpateLedgerCommon_: put account token link, hash=", block->Hash().StringHex())); return rai::ErrorCode::APP_PROCESS_LEDGER_PUT; } account_token_info.head_ = height; account_token_info.blocks_ += 1; error = ledger_.AccountTokenInfoPut(transaction, account, token.chain_, token.address_, account_token_info); if (error) { rai::Log::Error(rai::ToString( "Token::UpateLedgerCommon_: put account token info, hash=", block->Hash().StringHex())); return rai::ErrorCode::APP_PROCESS_LEDGER_PUT; } } } std::vector<rai::BlockType> rai::Token::BlockTypes() { std::vector<rai::BlockType> types{rai::BlockType::TX_BLOCK, rai::BlockType::REP_BLOCK}; return types; } rai::Provider::Info rai::Token::Provide() { using P = rai::Provider; P::Info info; info.id_ = P::Id::TOKEN; info.filters_.push_back(P::Filter::APP_ACCOUNT); info.actions_.push_back(P::Action::APP_SERVICE_SUBSCRIBE); info.actions_.push_back(P::Action::APP_ACCOUNT_SYNC); // todo: return info; } rai::ErrorCode rai::Token::InitLedger_() { rai::ErrorCode error_code = rai::ErrorCode::SUCCESS; rai::Transaction transaction(error_code, ledger_, true); IF_NOT_SUCCESS_RETURN(error_code); uint32_t version = 0; bool error = ledger_.VersionGet(transaction, version); if (error) { error = ledger_.VersionPut(transaction, rai::Token::CURRENT_LEDGER_VERSION); IF_ERROR_RETURN(error, rai::ErrorCode::TOKEN_LEDGER_PUT); return rai::ErrorCode::SUCCESS; } if (version > rai::Token::CURRENT_LEDGER_VERSION) { std::cout << "[Error] Ledger version=" << version << std::endl; return rai::ErrorCode::LEDGER_VERSION; } return rai::ErrorCode::SUCCESS; }
29.996689
80
0.58119
[ "vector" ]
0edcc3e99089c5f1888165c876b11e31bc877280
583
cpp
C++
tests/src/test_unroll.cpp
JPenuchot/cpp-sak
fda3fbdfd4094151ffb9260b922fdc5929f9637e
[ "MIT" ]
3
2018-12-02T12:09:31.000Z
2020-01-23T12:51:28.000Z
tests/src/test_unroll.cpp
JPenuchot/cpp-sak
fda3fbdfd4094151ffb9260b922fdc5929f9637e
[ "MIT" ]
null
null
null
tests/src/test_unroll.cpp
JPenuchot/cpp-sak
fda3fbdfd4094151ffb9260b922fdc5929f9637e
[ "MIT" ]
null
null
null
#include <vector> #include <testing.hpp> #include <jpp/unroll.hpp> void test_unroll() { int i = 0; jpp::unroll<5>([&](auto I) { static_assert(I >= 0 /* I is ALWAYS >= 0*/, "Unroll index not constexpr"); i += I; }); assert(i == 10, "Unroll test failed."); for(size_t i = 0; i < 32; i++) { std::vector<int> vec(i, 0); jpp::unrolled_for_each<4>(vec.begin(), vec.end(), [](auto& elmt) { elmt++; }); std::for_each(vec.begin(), vec.end(), [](auto& elmt) { assert(elmt == 1, "unrolled_for_each test failed."); }); } }
17.147059
78
0.530017
[ "vector" ]
0edd2d7a6c6e40a229eb163ab94c7160b753514e
1,228
cpp
C++
src/regions/iberia.cpp
rwalroth/claudius_cpp_game
10205faa0a572e75823d4da472eb280879e22e4c
[ "MIT" ]
null
null
null
src/regions/iberia.cpp
rwalroth/claudius_cpp_game
10205faa0a572e75823d4da472eb280879e22e4c
[ "MIT" ]
null
null
null
src/regions/iberia.cpp
rwalroth/claudius_cpp_game
10205faa0a572e75823d4da472eb280879e22e4c
[ "MIT" ]
null
null
null
#include "iberia.h" Iberia::Iberia(Army _local_army, std::shared_ptr<int> _bi) : Region{_local_army} { pBarbariansInvaded = _bi; messages = { { "As you make camp in Iberia just beyond the mountains", "you receive dire news. Barbarians have invaded Gaul!", "This is a great misfortune, though a fresh victory", "may bring more renown..." }, { "The Iberian peninsula is mercifully peaceful. You briefly", "allow yourself to think about quiet retirement, but the", "the war beckons." } }; move_menu = Menu(); move_menu.set_prompt({ "\nWhere will you go?", "G - Gaul", "Q - Quit the game" }); move_menu.set_valid_choices({'G', 'Q'}); } Iberia::Iberia(std::string file_name, std::shared_ptr<int> bi_) : Region{file_name}, pBarbariansInvaded{bi_} {} std::tuple<std::vector<std::string>, Phase> Iberia::location_events(Army &claudius) { int out_index {1}; if (*(this->pBarbariansInvaded) == 0) { out_index = 0; *(this->pBarbariansInvaded) = 1; } return std::make_tuple(this->messages.at(out_index), Phase::playing); }
33.189189
111
0.590391
[ "vector" ]
0ee006f16fdca80d66ee39e49a866e279a2aac3c
6,363
cpp
C++
src/tests/class_tests/openms/source/MultiplexClustering_test.cpp
mrurik/OpenMS
3bf48247423dc28a7df7b12b72fbc7751965c321
[ "Zlib", "Apache-2.0" ]
1
2018-03-06T14:12:09.000Z
2018-03-06T14:12:09.000Z
src/tests/class_tests/openms/source/MultiplexClustering_test.cpp
mrurik/OpenMS
3bf48247423dc28a7df7b12b72fbc7751965c321
[ "Zlib", "Apache-2.0" ]
null
null
null
src/tests/class_tests/openms/source/MultiplexClustering_test.cpp
mrurik/OpenMS
3bf48247423dc28a7df7b12b72fbc7751965c321
[ "Zlib", "Apache-2.0" ]
null
null
null
// -------------------------------------------------------------------------- // OpenMS -- Open-Source Mass Spectrometry // -------------------------------------------------------------------------- // Copyright The OpenMS Team -- Eberhard Karls University Tuebingen, // ETH Zurich, and Freie Universitaet Berlin 2002-2016. // // This software is released under a three-clause BSD license: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of any author or any participating institution // may be used to endorse or promote products derived from this software // without specific prior written permission. // For a full list of authors, refer to the file AUTHORS. // -------------------------------------------------------------------------- // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING // INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // -------------------------------------------------------------------------- // $Maintainer: Lars Nilse $ // $Authors: Lars Nilse $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> #include <OpenMS/TRANSFORMATIONS/FEATUREFINDER/MultiplexDeltaMasses.h> #include <OpenMS/TRANSFORMATIONS/FEATUREFINDER/MultiplexFilterResult.h> #include <OpenMS/TRANSFORMATIONS/FEATUREFINDER/MultiplexFilterResultRaw.h> #include <OpenMS/TRANSFORMATIONS/FEATUREFINDER/MultiplexFilterResultPeak.h> #include <OpenMS/TRANSFORMATIONS/FEATUREFINDER/MultiplexFilteringProfile.h> #include <OpenMS/TRANSFORMATIONS/FEATUREFINDER/MultiplexClustering.h> using namespace OpenMS; START_TEST(MultiplexFilteringProfile, "$Id$") // read data MSExperiment<Peak1D> exp; MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("MultiplexClustering.mzML"), exp); exp.updateRanges(); // pick data PeakPickerHiRes picker; Param param = picker.getParameters(); param.setValue("ms_levels", ListUtils::create<Int>("1")); param.setValue("signal_to_noise", 0.0); picker.setParameters(param); std::vector<PeakPickerHiRes::PeakBoundary> boundaries; std::vector<std::vector<PeakPickerHiRes::PeakBoundary> > boundaries_exp_s; std::vector<std::vector<PeakPickerHiRes::PeakBoundary> > boundaries_exp_c; MSExperiment<Peak1D> exp_picked; picker.pickExperiment(exp, exp_picked, boundaries_exp_s, boundaries_exp_c); // set parameters int charge_min = 1; int charge_max = 4; int peaks_per_peptide_min = 3; int peaks_per_peptide_max = 6; bool missing_peaks = false; double intensity_cutoff = 10.0; double peptide_similarity = 0.8; double averagine_similarity = 0.75; double averagine_similarity_scaling = 0.75; double mz_tolerance = 40; bool mz_tolerance_unit = true; // ppm (true), Da (false) double rt_typical = 90; double rt_minimum = 5; // construct list of peak patterns MultiplexDeltaMasses shifts1; shifts1.getDeltaMasses().push_back(MultiplexDeltaMasses::DeltaMass(0, "no_label")); shifts1.getDeltaMasses().push_back(MultiplexDeltaMasses::DeltaMass(8.0443702794, "Arg8")); MultiplexDeltaMasses shifts2; shifts2.getDeltaMasses().push_back(MultiplexDeltaMasses::DeltaMass(0, "no_label")); MultiplexDeltaMasses::LabelSet label_set; label_set.insert("Arg8"); label_set.insert("Arg8"); shifts2.getDeltaMasses().push_back(MultiplexDeltaMasses::DeltaMass(2*8.0443702794, label_set)); std::vector<MultiplexIsotopicPeakPattern> patterns; for (int c = charge_max; c >= charge_min; --c) { MultiplexIsotopicPeakPattern pattern1(c, peaks_per_peptide_max, shifts1, 0); patterns.push_back(pattern1); MultiplexIsotopicPeakPattern pattern2(c, peaks_per_peptide_max, shifts2, 1); patterns.push_back(pattern2); } MultiplexFilteringProfile filtering(exp, exp_picked, boundaries_exp_s, patterns, peaks_per_peptide_min, peaks_per_peptide_max, missing_peaks, intensity_cutoff, mz_tolerance, mz_tolerance_unit, peptide_similarity, averagine_similarity, averagine_similarity_scaling); std::vector<MultiplexFilterResult> filter_results = filtering.filter(); MultiplexClustering* nullPointer = 0; MultiplexClustering* ptr; START_SECTION(MultiplexClustering(const MSExperiment<Peak1D>& exp_profile, const MSExperiment<Peak1D>& exp_picked, const std::vector<std::vector<PeakPickerHiRes::PeakBoundary> >& boundaries, double rt_typical, double rt_minimum)) MultiplexClustering clustering(exp, exp_picked, boundaries_exp_s, rt_typical, rt_minimum); std::vector<std::map<int,GridBasedCluster> > cluster_results = clustering.cluster(filter_results); ptr = new MultiplexClustering(exp, exp_picked, boundaries_exp_s, rt_typical, rt_minimum); TEST_NOT_EQUAL(ptr, nullPointer); delete ptr; END_SECTION MultiplexClustering clustering(exp, exp_picked, boundaries_exp_s, rt_typical, rt_minimum); START_SECTION(std::vector<std::map<int GridBasedCluster> > cluster(const std::vector<MultiplexFilterResult>& filter_results)) std::vector<std::map<int,GridBasedCluster> > cluster_results = clustering.cluster(filter_results); TEST_EQUAL(cluster_results[0].size(), 0); TEST_EQUAL(cluster_results[1].size(), 0); TEST_EQUAL(cluster_results[2].size(), 0); TEST_EQUAL(cluster_results[3].size(), 0); TEST_EQUAL(cluster_results[4].size(), 2); TEST_EQUAL(cluster_results[5].size(), 0); TEST_EQUAL(cluster_results[6].size(), 0); TEST_EQUAL(cluster_results[7].size(), 0); END_SECTION END_TEST
49.325581
265
0.738645
[ "vector" ]
0ee54d5fa9153daf0ffa1074552b216af657d1ac
2,919
cpp
C++
aws-cpp-sdk-medialive/source/model/UdpGroupSettings.cpp
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
2
2019-03-11T15:50:55.000Z
2020-02-27T11:40:27.000Z
aws-cpp-sdk-medialive/source/model/UdpGroupSettings.cpp
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-medialive/source/model/UdpGroupSettings.cpp
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
1
2019-01-18T13:03:55.000Z
2019-01-18T13:03:55.000Z
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/medialive/model/UdpGroupSettings.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace MediaLive { namespace Model { UdpGroupSettings::UdpGroupSettings() : m_inputLossAction(InputLossActionForUdpOut::NOT_SET), m_inputLossActionHasBeenSet(false), m_timedMetadataId3Frame(UdpTimedMetadataId3Frame::NOT_SET), m_timedMetadataId3FrameHasBeenSet(false), m_timedMetadataId3Period(0), m_timedMetadataId3PeriodHasBeenSet(false) { } UdpGroupSettings::UdpGroupSettings(JsonView jsonValue) : m_inputLossAction(InputLossActionForUdpOut::NOT_SET), m_inputLossActionHasBeenSet(false), m_timedMetadataId3Frame(UdpTimedMetadataId3Frame::NOT_SET), m_timedMetadataId3FrameHasBeenSet(false), m_timedMetadataId3Period(0), m_timedMetadataId3PeriodHasBeenSet(false) { *this = jsonValue; } UdpGroupSettings& UdpGroupSettings::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("inputLossAction")) { m_inputLossAction = InputLossActionForUdpOutMapper::GetInputLossActionForUdpOutForName(jsonValue.GetString("inputLossAction")); m_inputLossActionHasBeenSet = true; } if(jsonValue.ValueExists("timedMetadataId3Frame")) { m_timedMetadataId3Frame = UdpTimedMetadataId3FrameMapper::GetUdpTimedMetadataId3FrameForName(jsonValue.GetString("timedMetadataId3Frame")); m_timedMetadataId3FrameHasBeenSet = true; } if(jsonValue.ValueExists("timedMetadataId3Period")) { m_timedMetadataId3Period = jsonValue.GetInteger("timedMetadataId3Period"); m_timedMetadataId3PeriodHasBeenSet = true; } return *this; } JsonValue UdpGroupSettings::Jsonize() const { JsonValue payload; if(m_inputLossActionHasBeenSet) { payload.WithString("inputLossAction", InputLossActionForUdpOutMapper::GetNameForInputLossActionForUdpOut(m_inputLossAction)); } if(m_timedMetadataId3FrameHasBeenSet) { payload.WithString("timedMetadataId3Frame", UdpTimedMetadataId3FrameMapper::GetNameForUdpTimedMetadataId3Frame(m_timedMetadataId3Frame)); } if(m_timedMetadataId3PeriodHasBeenSet) { payload.WithInteger("timedMetadataId3Period", m_timedMetadataId3Period); } return payload; } } // namespace Model } // namespace MediaLive } // namespace Aws
28.067308
143
0.785886
[ "model" ]
0ee5f627a40eb7f4a672b5c4e6b9ff16178eb343
22,265
cpp
C++
libstorage/SQLBasicAccess.cpp
imtypist/FISCO-BCOS
30a281d31e83ca666ef203193963a6d32e39e36a
[ "Apache-2.0" ]
null
null
null
libstorage/SQLBasicAccess.cpp
imtypist/FISCO-BCOS
30a281d31e83ca666ef203193963a6d32e39e36a
[ "Apache-2.0" ]
null
null
null
libstorage/SQLBasicAccess.cpp
imtypist/FISCO-BCOS
30a281d31e83ca666ef203193963a6d32e39e36a
[ "Apache-2.0" ]
null
null
null
/* * @CopyRight: * FISCO-BCOS is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * FISCO-BCOS is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with FISCO-BCOS. If not, see <http://www.gnu.org/licenses/> * (c) 2016-2019 fisco-dev contributors. */ /** @file SQLBasicAccess.cpp * @author darrenyin * @date 2019-04-24 */ #include "SQLBasicAccess.h" #include "SQLConnectionPool.h" #include "StorageException.h" #include "libconfig/GlobalConfigure.h" #include <boost/algorithm/string.hpp> #include <boost/algorithm/string/classification.hpp> #include <boost/algorithm/string/split.hpp> #include <boost/dynamic_bitset.hpp> using namespace dev::storage; using namespace std; SQLBasicAccess::SQLBasicAccess() { if (g_BCOSConfig.version() >= V2_6_0) { // supported_version >= v2.6.0, enable compress m_rowFormat = " ROW_FORMAT=COMPRESSED "; } } int SQLBasicAccess::Select(int64_t, const string& _table, const string&, Condition::Ptr _condition, vector<map<string, string>>& _values) { string sql = this->BuildQuerySql(_table, _condition); Connection_T conn = m_connPool->GetConnection(); uint32_t retryCnt = 0; uint32_t retryMax = 10; while (conn == NULL && retryCnt++ < retryMax) { SQLBasicAccess_LOG(WARNING) << "table:" << _table << "sql:" << sql << " get connection failed"; sleep(1); conn = m_connPool->GetConnection(); } if (conn == NULL) { SQLBasicAccess_LOG(ERROR) << "table:" << _table << "sql:" << sql << " get connection failed"; return -1; } TRY { PreparedStatement_T _prepareStatement = Connection_prepareStatement(conn, "%s", sql.c_str()); if (_condition) { uint32_t index = 0; for (auto& it : *(_condition)) { PreparedStatement_setString( _prepareStatement, ++index, it.second.right.second.c_str()); } } ResultSet_T result = PreparedStatement_executeQuery(_prepareStatement); int32_t columnCnt = ResultSet_getColumnCount(result); bool tableWithBlobField = isBlobType(_table); while (ResultSet_next(result)) { map<string, string> value; for (int32_t index = 1; index <= columnCnt; ++index) { auto fieldName = ResultSet_getColumnName(result, index); if (tableWithBlobField) { int size; auto bytes = ResultSet_getBlob(result, index, &size); // Note: Since the field may not be set, it must be added here to determine // whether the value of the obtained field is nullptr if (bytes) { value[fieldName] = string((char*)bytes, size); } } else { auto selectResult = ResultSet_getString(result, index); if (selectResult) { value[fieldName] = selectResult; } } } _values.push_back(move(value)); } } CATCH(SQLException) { m_connPool->ReturnConnection(conn); // Note: when select exception caused by table doesn't exist and sql error, // here must return 0, in case of the DB is normal but the sql syntax error or the // table will be created later SQLBasicAccess_LOG(ERROR) << "select exception for sql error:" << Exception_frame.message; return 0; } END_TRY; m_connPool->ReturnConnection(conn); return 0; } string SQLBasicAccess::BuildQuerySql(string _table, Condition::Ptr _condition) { _table = boost::algorithm::replace_all_copy(_table, "\\", "\\\\"); _table = boost::algorithm::replace_all_copy(_table, "`", "\\`"); string sql = "select * from `"; sql.append(_table).append("`"); if (_condition) { bool hasWhereClause = false; for (auto it = _condition->begin(); it != _condition->end(); ++it) { if (!hasWhereClause) { hasWhereClause = true; sql.append(BuildConditionSql(" where", it, _condition)); } else { sql.append(BuildConditionSql(" and", it, _condition)); } } } return sql; } string SQLBasicAccess::BuildConditionSql(const string& _strPrefix, map<string, Condition::Range>::const_iterator& _it, Condition::Ptr _condition) { string strConditionSql = _strPrefix; if (_it->second.left.second == _it->second.right.second && _it->second.left.first && _it->second.right.first) { strConditionSql.append(" `").append(_it->first).append("`=").append("?"); } else { if (_it->second.left.second != _condition->unlimitedField()) { if (_it->second.left.first) { strConditionSql.append(" `").append(_it->first).append("`>=").append("?"); } else { strConditionSql.append(" `").append(_it->first).append("`>").append("?"); } } if (_it->second.right.second != _condition->unlimitedField()) { if (_it->second.right.first) { strConditionSql.append(" `").append(_it->first).append("`<=").append("?"); } else { strConditionSql.append(" `").append(_it->first).append("`<").append("?"); } } } return strConditionSql; } SQLFieldType SQLBasicAccess::getFieldType(std::string const& _tableName) { // _sys_hash_2_block_ or _sys_block_2_nonce, the SYS_VALUE field is blob if (_tableName == SYS_HASH_2_BLOCK || _tableName == SYS_BLOCK_2_NONCES || _tableName == SYS_CNS) { if (g_BCOSConfig.version() >= V2_6_0) { return SQLFieldType::LongBlobType; } return SQLFieldType::LongStringType; } // _sys_hash_2_blockheader_, the SYS_VALUE and SYS_SIG_LIST are blob if (_tableName == SYS_HASH_2_BLOCKHEADER) { return SQLFieldType::LongBlobType; } // contract table, all the fields are blob type if (boost::starts_with(_tableName, string("c_"))) { if (g_BCOSConfig.version() >= V2_5_0) { return SQLFieldType::MediumBlobType; } } // supported_version >= v2.6.0, all the field type of user created table is mediumblob if (g_BCOSConfig.version() >= V2_6_0) { return SQLFieldType::MediumBlobType; } // supported_version < v2.6.0, the user created table is mediumtext return SQLFieldType::MediumStringType; } string SQLBasicAccess::BuildCreateTableSql( const string& _tableName, const string& _keyField, const string& _valueField) { stringstream ss; ss << "CREATE TABLE IF NOT EXISTS `" << _tableName << "`(\n"; ss << " `_id_` BIGINT unsigned auto_increment,\n"; if (g_BCOSConfig.version() <= V2_1_0) { ss << " `_hash_` varchar(128) DEFAULT NULL,\n"; } ss << " `_num_` BIGINT not null,\n"; ss << " `_status_` int not null,\n"; ss << "`" << _keyField << "` varchar(255) default '',\n"; SQLBasicAccess_LOG(DEBUG) << "valuefield:" << _valueField; vector<string> vecSplit; boost::split(vecSplit, _valueField, boost::is_any_of(",")); auto it = vecSplit.begin(); auto fieldType = getFieldType(_tableName); std::string fieldTypeName = SQLFieldTypeName[fieldType]; for (; it != vecSplit.end(); ++it) { *it = boost::algorithm::replace_all_copy(*it, "\\", "\\\\"); *it = boost::algorithm::replace_all_copy(*it, "`", "\\`"); ss << "`" << *it << "` " << fieldTypeName << ",\n"; } ss << " PRIMARY KEY( `_id_` ),\n"; ss << " KEY(`" << _keyField << "`(191)),\n"; ss << " KEY(`_num_`)\n"; // supported_version >= v2.6.0, enable compress ss << ") " << m_rowFormat << " ENGINE=InnoDB default charset=utf8mb4;"; return ss.str(); } string SQLBasicAccess::BuildCreateTableSql(const Entry::Ptr& _entry) { string tableName(_entry->getField("table_name")); string keyField(_entry->getField("key_field")); string valueField(_entry->getField("value_field")); tableName = boost::algorithm::replace_all_copy(tableName, "\\", "\\\\"); tableName = boost::algorithm::replace_all_copy(tableName, "`", "\\`"); keyField = boost::algorithm::replace_all_copy(keyField, "\\", "\\\\"); keyField = boost::algorithm::replace_all_copy(keyField, "`", "\\`"); string sql = BuildCreateTableSql(tableName, keyField, valueField); SQLBasicAccess_LOG(DEBUG) << "create table:" << tableName << " keyfield:" << keyField << " value field:" << valueField << " sql:" << sql; return sql; } void SQLBasicAccess::GetCommitFieldNameAndValueEachTable(const string& _num, const Entries::Ptr& _data, const vector<size_t>& _indexList, string& _fieldStr, vector<string>& _valueList) { bool isFirst = true; for (auto index : _indexList) { const auto& entry = _data->get(index); for (auto fieldIt : *entry) { if (fieldIt.first == NUM_FIELD || fieldIt.first == "_hash_" || fieldIt.first == ID_FIELD || fieldIt.first == STATUS) { continue; } if (isFirst) { _fieldStr.append("`").append(fieldIt.first).append("`,"); } _valueList.push_back(fieldIt.second); } if (g_BCOSConfig.version() <= V2_1_0) { _valueList.push_back("0"); } _valueList.push_back(_num); _valueList.push_back(boost::lexical_cast<string>(entry->getID())); _valueList.push_back(boost::lexical_cast<string>(entry->getStatus())); isFirst = false; } if (!_fieldStr.empty()) { if (g_BCOSConfig.version() <= V2_1_0) { _fieldStr.append("`_hash_`,"); } _fieldStr.append("`").append(NUM_FIELD).append("`,"); _fieldStr.append("`").append(ID_FIELD).append("`,"); _fieldStr.append("`").append(STATUS).append("`"); } } void SQLBasicAccess::GetCommitFieldNameAndValue( const Entries::Ptr& _data, const string& _num, map<string, vector<string>>& _field2Values) { set<string> keySet; for (size_t i = 0; i < _data->size(); ++i) { const auto& entry = _data->get(i); for (auto fieldIt : *entry) { if (fieldIt.first == NUM_FIELD || fieldIt.first == "_hash_" || fieldIt.first == ID_FIELD || fieldIt.first == STATUS) { continue; } keySet.insert(fieldIt.first); } } map<string, vector<size_t>> groupedEntries; map<string, uint32_t> field2Position; uint32_t currentFieldPostion = 0; for (size_t i = 0; i < _data->size(); ++i) { boost::dynamic_bitset<> keyVec(keySet.size(), 0); const auto& entry = _data->get(i); for (const auto& fieldIt : *entry) { if (fieldIt.first == NUM_FIELD || fieldIt.first == "_hash_" || fieldIt.first == ID_FIELD || fieldIt.first == STATUS) { continue; } if (field2Position.find(fieldIt.first) == field2Position.end()) { field2Position[fieldIt.first] = currentFieldPostion; keyVec[currentFieldPostion] = 1; ++currentFieldPostion; } else { keyVec[field2Position[fieldIt.first]] = 1; } } string key; boost::to_string(keyVec, key); groupedEntries[key].push_back(i); } for (const auto& it : groupedEntries) { string fieldStr; vector<string> valueList; GetCommitFieldNameAndValueEachTable(_num, _data, it.second, fieldStr, valueList); _field2Values[fieldStr].insert(_field2Values[fieldStr].end(), make_move_iterator(valueList.begin()), make_move_iterator(valueList.end())); } } int SQLBasicAccess::Commit(int64_t _num, const vector<TableData::Ptr>& _datas) { string errorMsg; volatile uint32_t retryCnt = 0; uint32_t retryMax = 10; volatile int ret = 0; TRY { ret = CommitDo(_num, _datas, errorMsg); while (ret < 0 && ++retryCnt < retryMax) { sleep(1); ret = CommitDo(_num, _datas, errorMsg); } if (ret < 0) { SQLBasicAccess_LOG(ERROR) << "commit failed error message:" << errorMsg; return -1; } } ELSE { SQLBasicAccess_LOG(ERROR) << "commit failed just return"; return -1; } END_TRY; return ret; } int SQLBasicAccess::CommitDo(int64_t _num, const vector<TableData::Ptr>& _datas, string& _errorMsg) { SQLBasicAccess_LOG(INFO) << " commit num:" << _num; string strNum = to_string(_num); if (_datas.size() == 0) { SQLBasicAccess_LOG(DEBUG) << "empty data just return"; return 0; } /*execute commit operation*/ Connection_T conn = m_connPool->GetConnection(); TRY { for (auto tableDataPtr : _datas) { if (tableDataPtr->info->name == SYS_TABLES) { for (size_t i = 0; i < tableDataPtr->newEntries->size(); ++i) { Entry::Ptr entry = tableDataPtr->newEntries->get(i); string sql = BuildCreateTableSql(entry); Connection_execute(conn, "%s", sql.c_str()); } } } } CATCH(SQLException) { _errorMsg = Exception_frame.message; SQLBasicAccess_LOG(ERROR) << "create table exception:" << _errorMsg; m_connPool->ReturnConnection(conn); return -1; } END_TRY; volatile int32_t rowCount = 0; m_connPool->BeginTransaction(conn); TRY { for (auto data : _datas) { auto tableInfo = data->info; string tableName = tableInfo->name; map<string, vector<string>> field2Values; this->GetCommitFieldNameAndValue(data->dirtyEntries, strNum, field2Values); this->GetCommitFieldNameAndValue(data->newEntries, strNum, field2Values); SQLBasicAccess_LOG(DEBUG) << "table:" << tableName << " split to " << field2Values.size() << " parts to commit"; tableName = boost::algorithm::replace_all_copy(tableName, "\\", "\\\\"); tableName = boost::algorithm::replace_all_copy(tableName, "`", "\\`"); auto tableWithBlobField = isBlobType(tableName); for (auto item : field2Values) { const auto& name = item.first; const auto& values = item.second; vector<SQLPlaceholderItem> sqlPlaceholders = this->BuildCommitSql(tableName, name, values); auto itValue = values.begin(); for (auto& placeholder : sqlPlaceholders) { PreparedStatement_T preStatement = Connection_prepareStatement(conn, "%s", placeholder.sql.c_str()); SQLBasicAccess_LOG(TRACE) << "table:" << tableName << " sql:" << placeholder.sql; uint32_t index = 0; for (; itValue != values.end(); ++itValue) { if (tableWithBlobField) { PreparedStatement_setBlob( preStatement, ++index, itValue->c_str(), itValue->size()); } else { PreparedStatement_setString(preStatement, ++index, itValue->c_str()); SQLBasicAccess_LOG(TRACE) << " index:" << index << " num:" << _num << " setString:" << itValue->c_str(); } if (index == placeholder.placeholderCnt) { PreparedStatement_execute(preStatement); rowCount += (int32_t)PreparedStatement_rowsChanged(preStatement); ++itValue; break; } } } } } } CATCH(SQLException) { _errorMsg = Exception_frame.message; SQLBasicAccess_LOG(ERROR) << "insert data exception:" << _errorMsg; SQLBasicAccess_LOG(DEBUG) << "active connections:" << m_connPool->GetActiveConnections() << " max connetions:" << m_connPool->GetMaxConnections() << " now connections:" << m_connPool->GetTotalConnections(); m_connPool->RollBack(conn); m_connPool->ReturnConnection(conn); return -1; } END_TRY; SQLBasicAccess_LOG(INFO) << "commit now active connections:" << m_connPool->GetActiveConnections() << " max connections:" << m_connPool->GetMaxConnections(); m_connPool->Commit(conn); m_connPool->ReturnConnection(conn); return rowCount; } vector<SQLPlaceholderItem> SQLBasicAccess::BuildCommitSql( const string& _table, const string& _fieldStr, const vector<string>& _fieldValues) { vector<string> fieldNames; boost::split(fieldNames, _fieldStr, boost::is_any_of(",")); vector<SQLPlaceholderItem> sqlPlaceholders; if (fieldNames.size() == 0 || _fieldValues.size() == 0 || (_fieldValues.size() % fieldNames.size())) { /*throw exception*/ SQLBasicAccess_LOG(ERROR) << "table name:" << _table << "field size:" << fieldNames.size() << " value size:" << _fieldValues.size() << " field size and value should be greate than 0"; THROW(SQLException, "PreparedStatement_executeQuery"); } string sqlHeader = "replace into `"; sqlHeader.append(_table).append("`("); sqlHeader.append(_fieldStr); sqlHeader.append(") values"); SQLBasicAccess_LOG(INFO) << "table name:" << _table << "field size:" << fieldNames.size() << " value size:" << _fieldValues.size(); string sql = sqlHeader; uint32_t placeholderCnt = 0; uint32_t valueSize = _fieldValues.size(); uint32_t columnSize = fieldNames.size(); for (uint32_t index = 0; index < valueSize; ++index) { ++placeholderCnt; if (index % columnSize == 0) { sql.append("(?,"); } else { sql.append("?,"); } if (index % columnSize == (columnSize - 1)) { sql = sql.substr(0, sql.size() - 1); sql.append("),"); /* if placeholders count is great than 65535 sql will execute failed so we need to execute in multiple sqls */ if (placeholderCnt >= maxPlaceHolderCnt) { sql = sql.substr(0, sql.size() - 1); SQLPlaceholderItem item; item.sql = sql; item.placeholderCnt = placeholderCnt; sqlPlaceholders.emplace_back(item); sql = sqlHeader; placeholderCnt = 0; } } } if (placeholderCnt > 0) { sql = sql.substr(0, sql.size() - 1); SQLPlaceholderItem item; item.sql = sql; item.placeholderCnt = placeholderCnt; sqlPlaceholders.emplace_back(item); } return sqlPlaceholders; } void SQLBasicAccess::setConnPool(SQLConnectionPool::Ptr& _connPool) { this->m_connPool = _connPool; } void SQLBasicAccess::ExecuteSql(const string& _sql) { Connection_T conn = m_connPool->GetConnection(); if (conn == NULL) { SQLBasicAccess_LOG(ERROR) << "get connection failed sql:" << _sql; THROW(SQLException, "PreparedStatement_executeQuery"); } TRY { Connection_execute(conn, "%s", _sql.c_str()); } CATCH(SQLException) { SQLBasicAccess_LOG(ERROR) << "execute sql failed sql:" << _sql; m_connPool->ReturnConnection(conn); throw StorageException(-1, "execute sql failed sql:" + _sql); } END_TRY; SQLBasicAccess_LOG(INFO) << "execute sql success sql:" << _sql << " now active connection:" << m_connPool->GetActiveConnections() << " max connection :" << m_connPool->GetMaxConnections(); m_connPool->ReturnConnection(conn); }
35.91129
101
0.539052
[ "vector" ]
0eea75b22e87c850201fff14bb404b961dfa7f4b
6,458
hpp
C++
include/UnityOSC/OSCBundle.hpp
RedBrumbler/virtuoso-codegen
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
[ "Unlicense" ]
null
null
null
include/UnityOSC/OSCBundle.hpp
RedBrumbler/virtuoso-codegen
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
[ "Unlicense" ]
null
null
null
include/UnityOSC/OSCBundle.hpp
RedBrumbler/virtuoso-codegen
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
[ "Unlicense" ]
null
null
null
// 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: UnityOSC.OSCPacket #include "UnityOSC/OSCPacket.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" #include "beatsaber-hook/shared/utils/typedefs-array.hpp" #include "beatsaber-hook/shared/utils/typedefs-string.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System namespace System { // Forward declaring type: String class String; } // Completed forward declares // Type namespace: UnityOSC namespace UnityOSC { // Forward declaring type: OSCBundle class OSCBundle; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::UnityOSC::OSCBundle); DEFINE_IL2CPP_ARG_TYPE(::UnityOSC::OSCBundle*, "UnityOSC", "OSCBundle"); // Type namespace: UnityOSC namespace UnityOSC { // Size: 0x30 #pragma pack(push, 1) // Autogenerated type: UnityOSC.OSCBundle // [TokenAttribute] Offset: FFFFFFFF class OSCBundle : public ::UnityOSC::OSCPacket { public: // static field const value: static private System.String BUNDLE static constexpr const char* BUNDLE = "#bundle"; // Get static field: static private System.String BUNDLE static ::StringW _get_BUNDLE(); // Set static field: static private System.String BUNDLE static void _set_BUNDLE(::StringW value); // public System.Void .ctor(System.Int64 timestamp) // Offset: 0xA16668 template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static OSCBundle* New_ctor(int64_t timestamp) { static auto ___internal__logger = ::Logger::get().WithContext("::UnityOSC::OSCBundle::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<OSCBundle*, creationType>(timestamp))); } // static public UnityOSC.OSCBundle Unpack(System.Byte[] data, ref System.Int32 start, System.Int32 end) // Offset: 0xA16724 static ::UnityOSC::OSCBundle* Unpack(::ArrayW<uint8_t> data, ByRef<int> start, int end); // public System.Void .ctor() // Offset: 0xA16598 // Implemented from: UnityOSC.OSCPacket // Base method: System.Void OSCPacket::.ctor() // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static OSCBundle* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("::UnityOSC::OSCBundle::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<OSCBundle*, creationType>())); } // public override System.Boolean IsBundle() // Offset: 0xA166C8 // Implemented from: UnityOSC.OSCPacket // Base method: System.Boolean OSCPacket::IsBundle() bool IsBundle(); // public override System.Void Pack() // Offset: 0xA166D0 // Implemented from: UnityOSC.OSCPacket // Base method: System.Void OSCPacket::Pack() void Pack(); // public override System.Void Append(T msgvalue) // Offset: 0xFFFFFFFFFFFFFFFF // Implemented from: UnityOSC.OSCPacket // Base method: System.Void OSCPacket::Append(T msgvalue) template<class T> void Append(T msgvalue) { static auto ___internal__logger = ::Logger::get().WithContext("::UnityOSC::OSCBundle::Append"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Append", std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(msgvalue)}))); auto* ___generic__method = THROW_UNLESS(::il2cpp_utils::MakeGenericMethod(___internal__method, std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()})); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___generic__method, msgvalue); } }; // UnityOSC.OSCBundle #pragma pack(pop) } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: UnityOSC::OSCBundle::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: UnityOSC::OSCBundle::Unpack // Il2CppName: Unpack template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::UnityOSC::OSCBundle* (*)(::ArrayW<uint8_t>, ByRef<int>, int)>(&UnityOSC::OSCBundle::Unpack)> { static const MethodInfo* get() { static auto* data = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Byte"), 1)->byval_arg; static auto* start = &::il2cpp_utils::GetClassFromName("System", "Int32")->this_arg; static auto* end = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityOSC::OSCBundle*), "Unpack", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{data, start, end}); } }; // Writing MetadataGetter for method: UnityOSC::OSCBundle::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: UnityOSC::OSCBundle::IsBundle // Il2CppName: IsBundle template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (UnityOSC::OSCBundle::*)()>(&UnityOSC::OSCBundle::IsBundle)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityOSC::OSCBundle*), "IsBundle", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityOSC::OSCBundle::Pack // Il2CppName: Pack template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityOSC::OSCBundle::*)()>(&UnityOSC::OSCBundle::Pack)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityOSC::OSCBundle*), "Pack", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityOSC::OSCBundle::Append // Il2CppName: Append // Cannot write MetadataGetter for generic methods!
50.062016
259
0.724218
[ "object", "vector" ]
0eea81b308bbee26cc607bcb95ffbf2d3f6abe0f
5,959
cc
C++
tensorflow/compiler/tf2xla/kernels/variable_ops.cc
DEVESHTARASIA/tensorflow
d3edb8c60ed4fd831d62833ed22f5c23486c561c
[ "Apache-2.0" ]
384
2017-02-21T18:38:04.000Z
2022-02-22T07:30:25.000Z
tensorflow/compiler/tf2xla/kernels/variable_ops.cc
DEVESHTARASIA/tensorflow
d3edb8c60ed4fd831d62833ed22f5c23486c561c
[ "Apache-2.0" ]
15
2017-03-01T20:18:43.000Z
2020-05-07T10:33:51.000Z
tensorflow/compiler/tf2xla/kernels/variable_ops.cc
DEVESHTARASIA/tensorflow
d3edb8c60ed4fd831d62833ed22f5c23486c561c
[ "Apache-2.0" ]
81
2017-02-21T19:31:19.000Z
2022-02-22T07:30:24.000Z
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/tf2xla/kernels/cwise_ops.h" #include "tensorflow/compiler/tf2xla/shape_util.h" #include "tensorflow/compiler/tf2xla/xla_helpers.h" #include "tensorflow/compiler/tf2xla/xla_op_registry.h" #include "tensorflow/compiler/xla/client/computation_builder.h" #include "tensorflow/compiler/xla/literal_util.h" #include "tensorflow/core/framework/kernel_def_builder.h" #include "tensorflow/core/framework/types.h" #include "tensorflow/core/kernels/no_op.h" namespace tensorflow { namespace { class VarIsInitializedOp : public XlaOpKernel { public: explicit VarIsInitializedOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} void Compile(XlaOpKernelContext* ctx) override { xla::ComputationDataHandle handle; bool initialized = ctx->ReadVariableInput(0, &handle).ok(); ctx->SetOutput(0, ctx->builder()->ConstantR0<bool>(initialized)); } }; REGISTER_XLA_OP(Name("VarIsInitializedOp"), VarIsInitializedOp); class ReadVariableOp : public XlaOpKernel { public: explicit ReadVariableOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} void Compile(XlaOpKernelContext* ctx) override { xla::ComputationDataHandle handle; OP_REQUIRES_OK(ctx, ctx->ReadVariableInput(0, &handle)); ctx->SetOutput(0, handle); } }; REGISTER_XLA_OP(Name("ReadVariableOp"), ReadVariableOp); REGISTER_XLA_OP(Name("_UnsafeReadVariable"), ReadVariableOp); class AssignVariableOp : public XlaOpKernel { public: explicit AssignVariableOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} void Compile(XlaOpKernelContext* ctx) override { OP_REQUIRES_OK(ctx, ctx->AssignVariable(0, ctx->input_type(1), ctx->Input(1))); } }; REGISTER_XLA_OP(Name("AssignVariableOp"), AssignVariableOp); class AssignAddVariableOp : public XlaOpKernel { public: explicit AssignAddVariableOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} void Compile(XlaOpKernelContext* ctx) override { xla::ComputationDataHandle handle; OP_REQUIRES_OK(ctx, ctx->ReadVariableInput(0, &handle)); handle = ctx->builder()->Add(handle, ctx->Input(1)); OP_REQUIRES_OK(ctx, ctx->AssignVariable(0, ctx->input_type(1), handle)); } }; REGISTER_XLA_OP( Name("AssignAddVariableOp").TypeConstraint("dtype", kNumericTypes), AssignAddVariableOp); class AssignSubVariableOp : public XlaOpKernel { public: explicit AssignSubVariableOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} void Compile(XlaOpKernelContext* ctx) override { xla::ComputationDataHandle handle; OP_REQUIRES_OK(ctx, ctx->ReadVariableInput(0, &handle)); handle = ctx->builder()->Sub(handle, ctx->Input(1)); OP_REQUIRES_OK(ctx, ctx->AssignVariable(0, ctx->input_type(1), handle)); } }; REGISTER_XLA_OP( Name("AssignSubVariableOp").TypeConstraint("dtype", kNumericTypes), AssignSubVariableOp); class ResourceGatherOp : public XlaOpKernel { public: explicit ResourceGatherOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} void Compile(XlaOpKernelContext* ctx) override { xla::ComputationBuilder* builder = ctx->builder(); // Get the shape of the resource tensor. TensorShape resource_shape; DataType resource_dtype; OP_REQUIRES_OK( ctx, ctx->GetVariableTypeAndShape(0, &resource_dtype, &resource_shape)); DataType expected_output_dtype = ctx->expected_output_dtype(0); OP_REQUIRES(ctx, resource_dtype == expected_output_dtype, errors::InvalidArgument( "Variable dtype is ", DataTypeString(resource_dtype), " but expected output dtype is ", DataTypeString(expected_output_dtype), ".")); xla::ComputationDataHandle resource_handle; OP_REQUIRES_OK(ctx, ctx->ReadVariableInput(0, &resource_handle)); auto indices = ctx->Input(1); auto indices_shape = ctx->InputShape(1); const int num_indices = indices_shape.num_elements(); // Flatten the indices into 1-D. auto indices_1d = builder->Reshape(indices, {num_indices}); // Compute the slice for each of these indices separately. std::vector<xla::ComputationDataHandle> slices(num_indices); for (int i = 0; i < num_indices; ++i) { auto index = builder->Slice(indices_1d, {i}, {i + 1}, {1}); auto start_indices = XlaHelpers::PadWithZeros(builder, index, resource_shape.dims() - 1); auto slice_shape = resource_shape.dim_sizes(); slice_shape[0] = 1LL; slices[i] = builder->DynamicSlice(resource_handle, start_indices, slice_shape); } // Concatenate the slices into one tensor. xla::ComputationDataHandle concat = builder->ConcatInDim(slices, 0); // Compute the shape of the result tensor, which is: // indices.shape + resource.shape[1:] TensorShape gather_shape = indices_shape; gather_shape.AppendShape(resource_shape); gather_shape.RemoveDim(indices_shape.dims()); // Reshape the concatenated slices into the shape expected of the result // tensor. xla::ComputationDataHandle gather = builder->Reshape(concat, gather_shape.dim_sizes()); ctx->SetOutput(0, gather); } }; REGISTER_XLA_OP(Name("ResourceGather").TypeConstraint("dtype", kNumericTypes), ResourceGatherOp); } // namespace } // namespace tensorflow
38.198718
80
0.719752
[ "shape", "vector" ]
0eeb29d47d67399553a427ca245639ddd5caf890
6,172
cpp
C++
Gems/EMotionFX/Code/EMotionFX/Pipeline/RCExt/ExportContexts.cpp
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
11
2021-07-08T09:58:26.000Z
2022-03-17T17:59:26.000Z
Gems/EMotionFX/Code/EMotionFX/Pipeline/RCExt/ExportContexts.cpp
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
29
2021-07-06T19:33:52.000Z
2022-03-22T10:27:49.000Z
Gems/EMotionFX/Code/EMotionFX/Pipeline/RCExt/ExportContexts.cpp
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
4
2021-07-06T19:24:43.000Z
2022-03-31T12:42:27.000Z
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <SceneAPIExt/Groups/MotionGroup.h> #include <SceneAPIExt/Groups/IActorGroup.h> #include <RCExt/ExportContexts.h> namespace EMotionFX { namespace Pipeline { //========================================================================== // Motion //========================================================================== MotionGroupExportContext::MotionGroupExportContext(AZ::SceneAPI::Events::ExportEventContext& parent, const Group::IMotionGroup& group, AZ::RC::Phase phase) : m_products(parent.GetProductList()) , m_scene(parent.GetScene()) , m_outputDirectory(parent.GetOutputDirectory()) , m_group(group) , m_phase(phase) { } MotionGroupExportContext::MotionGroupExportContext(AZ::SceneAPI::Events::ExportProductList& products, const AZ::SceneAPI::Containers::Scene& scene, const AZStd::string& outputDirectory, const Group::IMotionGroup& group, AZ::RC::Phase phase) : m_products(products) , m_scene(scene) , m_outputDirectory(outputDirectory) , m_group(group) , m_phase(phase) { } MotionGroupExportContext::MotionGroupExportContext(const MotionGroupExportContext& copyContext, AZ::RC::Phase phase) : m_products(copyContext.m_products) , m_scene(copyContext.m_scene) , m_outputDirectory(copyContext.m_outputDirectory) , m_group(copyContext.m_group) , m_phase(phase) { } //========================================================================== MotionDataBuilderContext::MotionDataBuilderContext(const AZ::SceneAPI::Containers::Scene& scene, const Group::IMotionGroup& motionGroup, EMotionFX::Motion& motion, AZ::RC::Phase phase) : m_scene(scene) , m_group(motionGroup) , m_motion(motion) , m_phase(phase) { } MotionDataBuilderContext::MotionDataBuilderContext(const MotionDataBuilderContext& copyContext, AZ::RC::Phase phase) : m_scene(copyContext.m_scene) , m_group(copyContext.m_group) , m_motion(copyContext.m_motion) , m_phase(phase) { } //========================================================================== // Actor //========================================================================== ActorGroupExportContext::ActorGroupExportContext(AZ::SceneAPI::Events::ExportEventContext& parent, const Group::IActorGroup& group, AZ::RC::Phase phase) : m_products(parent.GetProductList()) , m_scene(parent.GetScene()) , m_outputDirectory(parent.GetOutputDirectory()) , m_group(group) , m_phase(phase) { } ActorGroupExportContext::ActorGroupExportContext(AZ::SceneAPI::Events::ExportProductList& products, const AZ::SceneAPI::Containers::Scene & scene, const AZStd::string& outputDirectory, const Group::IActorGroup & group, AZ::RC::Phase phase) : m_products(products) , m_scene(scene) , m_outputDirectory(outputDirectory) , m_group(group) , m_phase(phase) { } ActorGroupExportContext::ActorGroupExportContext(const ActorGroupExportContext & copyContext, AZ::RC::Phase phase) : m_products(copyContext.m_products) , m_scene(copyContext.m_scene) , m_outputDirectory(copyContext.m_outputDirectory) , m_group(copyContext.m_group) , m_phase(phase) { } //========================================================================== ActorBuilderContext::ActorBuilderContext(const AZ::SceneAPI::Containers::Scene& scene, const AZStd::string& outputDirectory, const Group::IActorGroup& actorGroup, EMotionFX::Actor* actor, AZStd::vector<AZStd::string>& materialReferences, AZ::RC::Phase phase) : m_scene(scene) , m_outputDirectory(outputDirectory) , m_group(actorGroup) , m_actor(actor) , m_phase(phase) , m_materialReferences(materialReferences) { } ActorBuilderContext::ActorBuilderContext(const ActorBuilderContext & copyContext, AZ::RC::Phase phase) : m_scene(copyContext.m_scene) , m_outputDirectory(copyContext.m_outputDirectory) , m_group(copyContext.m_group) , m_actor(copyContext.m_actor) , m_phase(phase) , m_materialReferences(copyContext.m_materialReferences) { } //========================================================================== ActorMorphBuilderContext::ActorMorphBuilderContext(const AZ::SceneAPI::Containers::Scene& scene, AZStd::vector<AZ::u32>* meshNodeIndices, const Group::IActorGroup& actorGroup, EMotionFX::Actor* actor, AZ::SceneAPI::CoordinateSystemConverter& coordinateSystemConverter, AZ::RC::Phase phase) : m_scene(scene) , m_meshNodeIndices(meshNodeIndices) , m_group(actorGroup) , m_actor(actor) , m_coordinateSystemConverter(coordinateSystemConverter) , m_phase(phase) { } ActorMorphBuilderContext::ActorMorphBuilderContext(const ActorMorphBuilderContext & copyContext, AZ::RC::Phase phase) : m_scene(copyContext.m_scene) , m_meshNodeIndices(copyContext.m_meshNodeIndices) , m_group(copyContext.m_group) , m_actor(copyContext.m_actor) , m_coordinateSystemConverter(copyContext.m_coordinateSystemConverter) , m_phase(phase) { } } }
40.339869
193
0.567725
[ "vector", "3d" ]
0eebc9beed127cc7c981981a1bf2999171a132c6
13,908
cpp
C++
libs/vm/src/object.cpp
chr15murray/ledger
85be05221f19598de8c6c58652139a1f2d9e362f
[ "Apache-2.0" ]
1
2019-09-30T12:22:46.000Z
2019-09-30T12:22:46.000Z
libs/vm/src/object.cpp
chr15murray/ledger
85be05221f19598de8c6c58652139a1f2d9e362f
[ "Apache-2.0" ]
null
null
null
libs/vm/src/object.cpp
chr15murray/ledger
85be05221f19598de8c6c58652139a1f2d9e362f
[ "Apache-2.0" ]
1
2020-02-10T18:28:05.000Z
2020-02-10T18:28:05.000Z
//------------------------------------------------------------------------------ // // Copyright 2018-2020 Fetch.AI Limited // // 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 "vm/variant.hpp" #include "vm/vm.hpp" #include <cstddef> #include <string> namespace fetch { namespace vm { void Object::RuntimeError(std::string const &message) { vm_->RuntimeError(message); } TypeInfo Object::GetTypeInfo(TypeId type_id) { return vm_->GetTypeInfo(type_id); } bool Object::GetNonNegativeInteger(Variant const &v, std::size_t &index) { bool ok = true; switch (v.type_id) { case TypeIds::Int8: { index = std::size_t(v.primitive.i8); ok = v.primitive.i8 >= 0; break; } case TypeIds::UInt8: { index = std::size_t(v.primitive.ui8); break; } case TypeIds::Int16: { index = std::size_t(v.primitive.i16); ok = v.primitive.i16 >= 0; break; } case TypeIds::UInt16: { index = std::size_t(v.primitive.ui16); break; } case TypeIds::Int32: { index = std::size_t(v.primitive.i32); ok = v.primitive.i32 >= 0; break; } case TypeIds::UInt32: { index = std::size_t(v.primitive.ui32); break; } case TypeIds::Int64: { index = std::size_t(v.primitive.i64); ok = v.primitive.i64 >= 0; break; } case TypeIds::UInt64: { index = std::size_t(v.primitive.ui64); break; } default: { ok = false; break; } } // switch return ok; } std::size_t Object::GetHashCode() { return std::hash<const void *>()(this); } bool Object::IsEqual(Ptr<Object> const & /* lhso */, Ptr<Object> const & /* rhso */) { RuntimeError(std::string(__func__) + ": operator not implemented"); return false; } bool Object::IsNotEqual(Ptr<Object> const & /* lhso */, Ptr<Object> const & /* rhso */) { RuntimeError(std::string(__func__) + ": operator not implemented"); return false; } bool Object::IsLessThan(Ptr<Object> const & /* lhso */, Ptr<Object> const & /* rhso */) { RuntimeError(std::string(__func__) + ": operator not implemented"); return false; } bool Object::IsLessThanOrEqual(Ptr<Object> const & /* lhso */, Ptr<Object> const & /* rhso */) { RuntimeError(std::string(__func__) + ": operator not implemented"); return false; } bool Object::IsGreaterThan(Ptr<Object> const & /* lhso */, Ptr<Object> const & /* rhso */) { RuntimeError(std::string(__func__) + ": operator not implemented"); return false; } bool Object::IsGreaterThanOrEqual(Ptr<Object> const & /* lhso */, Ptr<Object> const & /* rhso */) { RuntimeError(std::string(__func__) + ": operator not implemented"); return false; } void Object::Negate(Ptr<Object> & /* object */) { RuntimeError(std::string(__func__) + ": operator not implemented"); } void Object::Add(Ptr<Object> & /* lhso */, Ptr<Object> & /* rhso */) { RuntimeError(std::string(__func__) + ": operator not implemented"); } void Object::LeftAdd(Variant & /* lhsv */, Variant & /* objectv */) { RuntimeError(std::string(__func__) + ": operator not implemented"); } void Object::RightAdd(Variant & /* objectv */, Variant & /* rhsv */) { RuntimeError(std::string(__func__) + ": operator not implemented"); } void Object::InplaceAdd(Ptr<Object> const & /* lhso */, Ptr<Object> const & /* rhso */) { RuntimeError(std::string(__func__) + ": operator not implemented"); } void Object::InplaceRightAdd(Ptr<Object> const & /* lhso */, Variant const & /* rhsv */) { RuntimeError(std::string(__func__) + ": operator not implemented"); } void Object::Subtract(Ptr<Object> & /* lhso */, Ptr<Object> & /* rhso */) { RuntimeError(std::string(__func__) + ": operator not implemented"); } void Object::LeftSubtract(Variant & /* lhsv */, Variant & /* objectv */) { RuntimeError(std::string(__func__) + ": operator not implemented"); } void Object::RightSubtract(Variant & /* objectv */, Variant & /* rhsv */) { RuntimeError(std::string(__func__) + ": operator not implemented"); } void Object::InplaceSubtract(Ptr<Object> const & /* lhso */, Ptr<Object> const & /* rhso */) { RuntimeError(std::string(__func__) + ": operator not implemented"); } void Object::InplaceRightSubtract(Ptr<Object> const & /* lhso */, Variant const & /* rhsv */) { RuntimeError(std::string(__func__) + ": operator not implemented"); } void Object::Multiply(Ptr<Object> & /* lhso */, Ptr<Object> & /* rhso */) { RuntimeError(std::string(__func__) + ": operator not implemented"); } void Object::LeftMultiply(Variant & /* lhsv */, Variant & /* objectv */) { RuntimeError(std::string(__func__) + ": operator not implemented"); } void Object::RightMultiply(Variant & /* objectv */, Variant & /* rhsv */) { RuntimeError(std::string(__func__) + ": operator not implemented"); } void Object::InplaceMultiply(Ptr<Object> const & /* lhso */, Ptr<Object> const & /* rhso */) { RuntimeError(std::string(__func__) + ": operator not implemented"); } void Object::InplaceRightMultiply(Ptr<Object> const & /* lhso */, Variant const & /* rhsv */) { RuntimeError(std::string(__func__) + ": operator not implemented"); } void Object::Divide(Ptr<Object> & /* lhso */, Ptr<Object> & /* rhso */) { RuntimeError(std::string(__func__) + ": operator not implemented"); } void Object::LeftDivide(Variant & /* lhsv */, Variant & /* objectv */) { RuntimeError(std::string(__func__) + ": operator not implemented"); } void Object::RightDivide(Variant & /* objectv */, Variant & /* rhsv */) { RuntimeError(std::string(__func__) + ": operator not implemented"); } void Object::InplaceDivide(Ptr<Object> const & /* lhso */, Ptr<Object> const & /* rhso */) { RuntimeError(std::string(__func__) + ": operator not implemented"); } void Object::InplaceRightDivide(Ptr<Object> const & /* lhso*/, Variant const & /* rhsv */) { RuntimeError(std::string(__func__) + ": operator not implemented"); } ChargeAmount Object::IsEqualChargeEstimator(Ptr<Object> const & /* lhso */, Ptr<Object> const & /* rhso */) { RuntimeError(std::string(__func__) + ": estimator not implemented"); return 1; } ChargeAmount Object::IsNotEqualChargeEstimator(Ptr<Object> const & /* lhso */, Ptr<Object> const & /* rhso */) { RuntimeError(std::string(__func__) + ": estimator not implemented"); return 1; } ChargeAmount Object::IsLessThanChargeEstimator(Ptr<Object> const & /* lhso */, Ptr<Object> const & /* rhso */) { RuntimeError(std::string(__func__) + ": estimator not implemented"); return 1; } ChargeAmount Object::IsLessThanOrEqualChargeEstimator(Ptr<Object> const & /* lhso */, Ptr<Object> const & /* rhso */) { RuntimeError(std::string(__func__) + ": estimator not implemented"); return 1; } ChargeAmount Object::IsGreaterThanChargeEstimator(Ptr<Object> const & /* lhso */, Ptr<Object> const & /* rhso */) { RuntimeError(std::string(__func__) + ": estimator not implemented"); return 1; } ChargeAmount Object::IsGreaterThanOrEqualChargeEstimator(Ptr<Object> const & /* lhso */, Ptr<Object> const & /* rhso */) { RuntimeError(std::string(__func__) + ": estimator not implemented"); return 1; } ChargeAmount Object::NegateChargeEstimator(Ptr<Object> const & /* object */) { RuntimeError(std::string(__func__) + ": estimator not implemented"); return 1; } ChargeAmount Object::AddChargeEstimator(Ptr<Object> const & /* lhso */, Ptr<Object> const & /* rhso */) { RuntimeError(std::string(__func__) + ": estimator not implemented"); return 1; } ChargeAmount Object::LeftAddChargeEstimator(Variant const & /* lhsv */, Variant const & /* objectv */) { RuntimeError(std::string(__func__) + ": estimator not implemented"); return 1; } ChargeAmount Object::RightAddChargeEstimator(Variant const & /* objectv */, Variant const & /* rhsv */) { RuntimeError(std::string(__func__) + ": estimator not implemented"); return 1; } ChargeAmount Object::InplaceAddChargeEstimator(Ptr<Object> const & /* lhso */, Ptr<Object> const & /* rhso */) { RuntimeError(std::string(__func__) + ": estimator not implemented"); return 1; } ChargeAmount Object::InplaceRightAddChargeEstimator(Ptr<Object> const & /* lhso */, Variant const & /* rhsv */) { RuntimeError(std::string(__func__) + ": estimator not implemented"); return 1; } ChargeAmount Object::SubtractChargeEstimator(Ptr<Object> const & /* lhso */, Ptr<Object> const & /* rhso */) { RuntimeError(std::string(__func__) + ": estimator not implemented"); return 1; } ChargeAmount Object::LeftSubtractChargeEstimator(Variant const & /* lhsv */, Variant const & /* objectv */) { RuntimeError(std::string(__func__) + ": estimator not implemented"); return 1; } ChargeAmount Object::RightSubtractChargeEstimator(Variant const & /* objectv */, Variant const & /* rhsv */) { RuntimeError(std::string(__func__) + ": estimator not implemented"); return 1; } ChargeAmount Object::InplaceSubtractChargeEstimator(Ptr<Object> const & /* lhso */, Ptr<Object> const & /* rhso */) { RuntimeError(std::string(__func__) + ": estimator not implemented"); return 1; } ChargeAmount Object::InplaceRightSubtractChargeEstimator(Ptr<Object> const & /* lhso */, Variant const & /* rhsv */) { RuntimeError(std::string(__func__) + ": estimator not implemented"); return 1; } ChargeAmount Object::MultiplyChargeEstimator(Ptr<Object> const & /* lhso */, Ptr<Object> const & /* rhso */) { RuntimeError(std::string(__func__) + ": estimator not implemented"); return 1; } ChargeAmount Object::LeftMultiplyChargeEstimator(Variant const & /* lhsv */, Variant const & /* objectv */) { RuntimeError(std::string(__func__) + ": estimator not implemented"); return 1; } ChargeAmount Object::RightMultiplyChargeEstimator(Variant const & /* objectv */, Variant const & /* rhsv */) { RuntimeError(std::string(__func__) + ": estimator not implemented"); return 1; } ChargeAmount Object::InplaceMultiplyChargeEstimator(Ptr<Object> const & /* lhso */, Ptr<Object> const & /* rhso */) { RuntimeError(std::string(__func__) + ": estimator not implemented"); return 1; } ChargeAmount Object::InplaceRightMultiplyChargeEstimator(Ptr<Object> const & /* lhso */, Variant const & /* rhsv */) { RuntimeError(std::string(__func__) + ": estimator not implemented"); return 1; } ChargeAmount Object::DivideChargeEstimator(Ptr<Object> const & /* lhso */, Ptr<Object> const & /* rhso */) { RuntimeError(std::string(__func__) + ": estimator not implemented"); return 1; } ChargeAmount Object::LeftDivideChargeEstimator(Variant const & /* lhsv */, Variant const & /* objectv */) { RuntimeError(std::string(__func__) + ": estimator not implemented"); return 1; } ChargeAmount Object::RightDivideChargeEstimator(Variant const & /* objectv */, Variant const & /* rhsv */) { RuntimeError(std::string(__func__) + ": estimator not implemented"); return 1; } ChargeAmount Object::InplaceDivideChargeEstimator(Ptr<Object> const & /* lhso */, Ptr<Object> const & /* rhso */) { RuntimeError(std::string(__func__) + ": estimator not implemented"); return 1; } ChargeAmount Object::InplaceRightDivideChargeEstimator(Ptr<Object> const & /* lhso*/, Variant const & /* rhsv */) { RuntimeError(std::string(__func__) + ": estimator not implemented"); return 1; } bool Object::SerializeTo(MsgPackSerializer & /*buffer*/) { vm_->RuntimeError("Serializer for " + GetTypeName() + " is not defined."); return false; } bool Object::DeserializeFrom(MsgPackSerializer & /*buffer*/) { vm_->RuntimeError("Deserializer for " + GetTypeName() + " is not defined."); return false; } std::string Object::GetTypeName() const { return vm_->GetTypeName(type_id_); } bool Object::ToJSON(JSONVariant &variant) { variant = "JSON serializer for " + GetTypeName() + " is not defined."; vm_->RuntimeError("JSON serializer for " + GetTypeName() + " is not defined."); return false; } bool Object::FromJSON(JSONVariant const & /*variant*/) { vm_->RuntimeError("JSON deserializer for " + GetTypeName() + " is not defined."); return false; } } // namespace vm } // namespace fetch
30.103896
97
0.606126
[ "object" ]
0eed784cd0b49b7f4c64b1cba3a3d264d25d8ec4
1,481
hpp
C++
src/app/ext/media/gfx/ext/gfx-surface.hpp
indigoabstract/techno-globe
1f01b231bece534282344fa660d5f9a8cc07262e
[ "MIT" ]
null
null
null
src/app/ext/media/gfx/ext/gfx-surface.hpp
indigoabstract/techno-globe
1f01b231bece534282344fa660d5f9a8cc07262e
[ "MIT" ]
null
null
null
src/app/ext/media/gfx/ext/gfx-surface.hpp
indigoabstract/techno-globe
1f01b231bece534282344fa660d5f9a8cc07262e
[ "MIT" ]
null
null
null
#pragma once #include "gfx-vxo.hpp" class gfx_debug_vxo : public gfx_vxo { public: gfx_debug_vxo(vx_info ivxi, bool iis_submesh = false); virtual void render_mesh(shared_ptr<gfx_camera> icamera); }; class gfx_obj_vxo : public gfx_vxo { public: gfx_obj_vxo(); void operator=(const std::string& imesh_name); //virtual void render_mesh(shared_ptr<gl_camera> icamera); //std::vector<shared_ptr<gl_mesh> > mesh_list; bool is_loaded; }; class gfx_plane : public gfx_vxo { public: gfx_plane(std::shared_ptr<gfx> i_gi = nullptr); virtual void set_dimensions(float idx, float idy); }; class gfx_billboard : public gfx_plane { public: gfx_billboard(); }; class gfx_grid : public gfx_vxo { public: gfx_grid(); virtual void set_dimensions(int i_h_point_count, int i_v_point_count); }; class gfx_box : public gfx_vxo { public: gfx_box(); void set_dimensions(float idx, float idy, float idz); }; class gfx_icosahedron : public gfx_vxo { public: gfx_icosahedron(); void set_dimensions(float iradius); }; // variable polygon count class gfx_vpc_box : public gfx_vxo { public: gfx_vpc_box(); void set_dimensions(float iradius, int isegments); }; class gfx_vpc_kubic_sphere : public gfx_vxo { public: gfx_vpc_kubic_sphere(); void set_dimensions(float iradius, int isegments); }; class gfx_vpc_ring_sphere : public gfx_vxo { public: gfx_vpc_ring_sphere(); void set_dimensions(float iradius, int igrid_point_count); };
18.060976
73
0.733964
[ "vector" ]
0efbcb0e040b47eb47cff303bafc62ed4fc7731e
18,103
cpp
C++
src/percept/mesh/geometry/recovery/GeometryRecoverySplineFit.cpp
jrood-nrel/percept
363cdd0050443760d54162f140b2fb54ed9decf0
[ "BSD-2-Clause" ]
3
2017-08-08T21:06:02.000Z
2020-01-08T13:23:36.000Z
src/percept/mesh/geometry/recovery/GeometryRecoverySplineFit.cpp
jrood-nrel/percept
363cdd0050443760d54162f140b2fb54ed9decf0
[ "BSD-2-Clause" ]
2
2016-12-17T00:18:56.000Z
2019-08-09T15:29:25.000Z
src/percept/mesh/geometry/recovery/GeometryRecoverySplineFit.cpp
jrood-nrel/percept
363cdd0050443760d54162f140b2fb54ed9decf0
[ "BSD-2-Clause" ]
2
2017-11-30T07:02:41.000Z
2019-08-05T17:07:04.000Z
// Copyright 2002 - 2008, 2010, 2011 National Technology Engineering // Solutions of Sandia, LLC (NTESS). Under the terms of Contract // DE-NA0003525 with NTESS, the U.S. Government retains certain rights // in this software. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. #include <percept/PerceptMesh.hpp> #include <percept/mesh/geometry/recovery/GeometryRecoverySplineFit.hpp> #if defined( STK_PERCEPT_HAS_GEOMETRY ) #include <percept/mesh/geometry/stk_geom/LocalCubicSplineFit.hpp> #endif #include <stk_mesh/base/MeshUtils.hpp> #define APRINTLN(a) do { if (debug_print) std::cout << #a << " = " << a << std::endl; } while(0) #define APRINTLN2(a,b) do { if (debug_print) std::cout << #a << " = " << a << " " << #b << " = " << b << std::endl; } while(0) #define DEBUG_PRINT 0 namespace percept { #if defined( STK_PERCEPT_HAS_GEOMETRY ) stk::mesh::Part& GeometryRecoverySplineFit::create_clone_part(const std::string& clone_name, const stk::mesh::EntityRank rank_to_clone, bool make_part_io_part ) { stk::mesh::Part& clone = m_eMesh.get_fem_meta_data()->declare_part(clone_name, rank_to_clone); if (make_part_io_part && clone.attribute<Ioss::GroupingEntity>() == NULL) { stk::io::put_io_part_attribute(clone); } return clone; } stk::mesh::Part& GeometryRecoverySplineFit::clone_part_bulk(const stk::mesh::Part& part, const std::string& clone_name, const stk::mesh::EntityRank rank_to_clone, bool make_part_io_part ) { stk::mesh::Part * clone_p = m_eMesh.get_fem_meta_data()->get_part(clone_name); if (!clone_p) throw std::runtime_error("GeometryRecoverySplineFit::clone_part: no part named: "+clone_name); stk::mesh::Part& clone = *clone_p; stk::mesh::Selector this_part(part); std::vector<stk::mesh::Entity> entities; stk::mesh::PartVector add_parts(1,&clone), remove_parts; const stk::mesh::BucketVector & entity_buckets = m_eMesh.get_bulk_data()->buckets( rank_to_clone ); for ( stk::mesh::BucketVector::const_iterator k = entity_buckets.begin() ; k != entity_buckets.end() ; ++k ) { stk::mesh::Bucket & bucket = **k ; if (this_part(bucket)) { const unsigned num_entities_in_bucket = bucket.size(); for (unsigned i_entity = 0; i_entity < num_entities_in_bucket; i_entity++) { stk::mesh::Entity entity = bucket[i_entity]; entities.push_back(entity); } } } for (unsigned ii=0; ii < entities.size(); ii++) { m_eMesh.get_bulk_data()->change_entity_parts( entities[ii], add_parts, remove_parts ); } return clone; } void GeometryRecoverySplineFit::get_sorted_curve_node_entities_and_split(stk::mesh::Part& part, std::vector< std::vector<stk::mesh::Entity> >& sorted_nodes_all, std::vector<bool>& isClosed_all) { bool debug_print = false || DEBUG_PRINT; sorted_nodes_all.resize(0); isClosed_all.resize(0); stk::mesh::Selector this_part(part); stk::mesh::Entity edge_first = stk::mesh::Entity(); SetOfEntities edge_set(*m_eMesh.get_bulk_data()); const stk::mesh::BucketVector & edge_buckets = m_eMesh.get_bulk_data()->buckets( m_eMesh.edge_rank() ); for ( stk::mesh::BucketVector::const_iterator k = edge_buckets.begin() ; k != edge_buckets.end() ; ++k ) { if (this_part(**k)) { stk::mesh::Bucket & bucket = **k ; for (unsigned iedge=0; iedge < bucket.size(); iedge++) { stk::mesh::Entity edge = bucket[iedge]; edge_set.insert(edge); } } } unsigned iloop=0; while (iloop < 10000) { edge_first = *edge_set.begin(); std::vector<stk::mesh::Entity> sorted_nodes; bool closed = get_sorted_curve_node_entities(part, edge_first, sorted_nodes); sorted_nodes_all.push_back(sorted_nodes); isClosed_all.push_back(closed); if (debug_print) std::cout << "tmp srk init iloop = " << iloop << " sorted_nodes.size()= " << sorted_nodes.size() << " edge_set.size= " << edge_set.size() << std::endl; for (unsigned ii=0; ii < sorted_nodes.size(); ++ii) { const MyPairIterRelation node_edges(*m_eMesh.get_bulk_data(), sorted_nodes[ii], m_eMesh.edge_rank() ); for (unsigned jj=0; jj < node_edges.size(); jj++) { edge_set.erase(node_edges[jj].entity()); } } if (debug_print) std::cout << "tmp srk after iloop = " << iloop << " sorted_nodes.size()= " << sorted_nodes.size() << " edge_set.size= " << edge_set.size() << std::endl; if (edge_set.size() == 0) { if (debug_print) std::cout << "tmp srk found end of (possible) multiple closed loops, iloop = " << iloop << std::endl; break; } if (debug_print) std::cout << "tmp srk found multiple closed loops, iloop = " << iloop << std::endl; ++iloop; } } /// returns true if closed found bool GeometryRecoverySplineFit::get_sorted_curve_node_entities(stk::mesh::Part& part, stk::mesh::Entity edge_first, std::vector<stk::mesh::Entity>& sorted_nodes) { bool debug_print = false || DEBUG_PRINT; bool closed = false; if (debug_print) std::cout << "GeometryRecoverySplineFit::get_sorted_curve_node_entities: processing part = " << part.name() << std::endl; VERIFY_OP_ON(part.primary_entity_rank(), ==, m_eMesh.edge_rank(), "bad part"); stk::mesh::Selector this_part(part); typedef std::list<stk::mesh::Entity> ListOfEntities; ListOfEntities node_list; const MyPairIterRelation edge_nodes(*m_eMesh.get_bulk_data(), edge_first, m_eMesh.node_rank() ); VERIFY_OP_ON(edge_nodes.size(), ==, 2, "bad edge"); for (unsigned idir=0; idir < 2; idir++) { stk::mesh::Entity current_edge = edge_first; stk::mesh::Entity last_node = stk::mesh::Entity(); bool continue_proc=true; while(continue_proc) { const MyPairIterRelation current_edge_nodes(*m_eMesh.get_bulk_data(), current_edge, m_eMesh.node_rank() ); unsigned JDIR=0; if (current_edge == edge_first) JDIR = idir; else { for (unsigned jdir=0; jdir < 2; jdir++) { if (current_edge_nodes[jdir].entity() != last_node) { JDIR = jdir; break; } } } last_node = current_edge_nodes[JDIR].entity(); bool is_not_in_list = std::find(node_list.begin(), node_list.end(), last_node) == node_list.end(); VERIFY_OP_ON(is_not_in_list, ==, true, "bad node list"); bool is_node_in_part = this_part(m_eMesh.bucket(last_node)); VERIFY_OP_ON(is_node_in_part, ==, true, "bad node not in part"); if (idir==0) node_list.push_back(last_node); else node_list.push_front(last_node); is_not_in_list = std::find(node_list.begin(), node_list.end(), last_node) == node_list.end(); VERIFY_OP_ON(is_not_in_list, ==, false, "bad node list 2"); const MyPairIterRelation last_node_edges(*m_eMesh.get_bulk_data(), last_node, m_eMesh.edge_rank() ); bool found_new_edge = false; for (unsigned kdir=0; kdir < 2; kdir++) { if (last_node_edges[kdir].entity() != current_edge && this_part(m_eMesh.bucket(last_node_edges[kdir].entity() ))) { current_edge = last_node_edges[kdir].entity(); // check for closed if (idir == 0 && current_edge == edge_first) { if (debug_print) std::cout << "GeometryRecoverySplineFit::get_sorted_curve_node_entities: found closed condition..." << std::endl; VERIFY_OP_ON(last_node, ==, edge_nodes[1].entity(), "integrity check failed"); node_list.push_front(edge_nodes[1].entity()); ++idir; //force loop exit } else { found_new_edge = true; } break; } } if (!found_new_edge) continue_proc = false; } } APRINTLN(node_list.size()); if (node_list.front() == node_list.back()) { // closed case closed = true; sorted_nodes.resize(0); sorted_nodes.assign(node_list.begin(), node_list.end()); } else { sorted_nodes.resize(0); sorted_nodes.assign(node_list.begin(), node_list.end()); } return closed; } void GeometryRecoverySplineFit::fit_geometry_create_parts_meta() { //bool debug_print = false; const stk::mesh::PartVector & parts = m_eMesh.get_fem_meta_data()->get_parts(); m_surface_parts.resize(0); m_topo_parts.resize(0); int n_topo = 10000; unsigned nparts = parts.size(); for (unsigned ipart=0; ipart < nparts; ipart++) { stk::mesh::Part& part = *parts[ipart]; if (stk::mesh::is_auto_declared_part(part) ) //|| (part.name().find("oldElem") != std::string::npos)) continue; const AutoPart *side_auto_part = part.attribute<AutoPart>(); if (side_auto_part) continue; if (part.primary_entity_rank() != m_eMesh.edge_rank()) continue; if (part.subsets().size() == 0) // skip parts like surface_quad4_edge2_4 continue; std::string clone_name = "tbc_curve_block_"+toString(n_topo++); stk::mesh::Part& clone = create_clone_part(clone_name, m_eMesh.node_rank()); m_topo_parts.push_back(&clone); m_surface_parts.push_back(&part); } } } namespace geom { int check_for_corners(geom::Vectors2D& Qin, double alpha, std::vector<int>& corners, bool isClosed) { geom::Vectors2D Q = Qin; if (DEBUG_PRINT) std::cout << "check_for_corners: Qin=\n" << Q << std::endl; int n = Q.size()-1; if (isClosed) { double arclen = 0.0; for (int k=1; k <= n; k++) { arclen += (Q[k] - Q[k-1]).Length(); } // decide if points are closed double reltol = 1.e-8; double tol = reltol*arclen; geom::Vector2D diff = Q[0]; diff -= Q[n]; VERIFY_OP_ON(diff.Length(), <, tol, "isClosed check failed"); } corners.resize(0); geom::Vectors2D T(n+1); int iend = n-1; if (isClosed) iend = n; for (int i=0; i <= iend; i++) { if (isClosed) { T[i] = Q[i == n ? 1 : (i+1)]-Q[i]; } else { T[i] = Q[i+1]-Q[i]; } double tl = T[i].Length(); if (tl < 1.e-12) throw std::runtime_error("can't normalize T"); T[i] /= tl; } if (DEBUG_PRINT) std::cout << "n = " << n << " T =\n" << T << std::endl; corners.resize(n+1); corners.assign(n+1,0); int nc=0; int istart = 1; iend = n-1; if (isClosed) { istart = 0; iend = n; } for (int i=istart; i <= iend; i++) { int im = i-1; int ii = i; if (isClosed) { im = (i == 0 ? n - 1 : i - 1); } double included_angle = M_PI - std::acos(T[im]*T[ii]); if (included_angle < alpha) { corners[i] = 1; if (DEBUG_PRINT) std::cout << "tmp srk found corner at i= " << i << " x,y= " << Q[i].x << ", " << Q[i].y << std::endl; ++nc; } } return nc; } } namespace percept { void GeometryRecoverySplineFit::fit_geometry(const std::string& filename) { using namespace geom; bool debug_print = false || DEBUG_PRINT; SplineFit::s_debug_print = debug_print; ON::Begin(); FILE* file = ON::OpenFile( filename.c_str(), "wb" ); if (!file) throw std::runtime_error("couldn't open file: "+filename+" in fit_geometry"); // allow additional parts to be added ONX_Model model; // set revision history information model.m_properties.m_RevisionHistory.NewRevision(); // set application information model.m_properties.m_Application.m_application_name = "Percept"; model.m_properties.m_Application.m_application_URL = "http://www.sandia.gov"; model.m_properties.m_Application.m_application_details = "Fit cubic splines."; // some notes model.m_properties.m_Notes.m_notes = "notes"; model.m_properties.m_Notes.m_bVisible = true; // file settings (units, tolerances, views, ...) model.m_settings.m_ModelUnitsAndTolerances.m_unit_system = ON::inches; //ON::meters; //ON::inches; model.m_settings.m_ModelUnitsAndTolerances.m_absolute_tolerance = 0.001; model.m_settings.m_ModelUnitsAndTolerances.m_angle_tolerance = ON_PI/180.0; // radians model.m_settings.m_ModelUnitsAndTolerances.m_relative_tolerance = 0.01; // 1% // layer table { // OPTIONAL - define some layers ON_Layer layer[1]; layer[0].SetLayerName("Default"); layer[0].SetVisible(true); layer[0].SetLocked(false); layer[0].SetColor( ON_Color(0,0,0) ); model.m_layer_table.Append(layer[0]); } // object table { //const stk::mesh::PartVector & parts = m_eMesh.get_fem_meta_data()->get_parts(); //stk::mesh::PartVector m_surface_parts; //stk::mesh::PartVector m_topo_parts; m_eMesh.get_bulk_data()->modification_begin(); unsigned nparts = m_topo_parts.size(); for (unsigned ipart=0; ipart < nparts; ipart++) { clone_part_bulk(*m_surface_parts[ipart], m_topo_parts[ipart]->name(), m_eMesh.node_rank()); } stk::mesh::fixup_ghosted_to_shared_nodes(*m_eMesh.get_bulk_data()); m_eMesh.get_bulk_data()->modification_end(); nparts = m_topo_parts.size(); for (unsigned ipart=0; ipart < nparts; ipart++) { stk::mesh::Part& part = *m_topo_parts[ipart]; std::vector< std::vector<stk::mesh::Entity> > sorted_nodes_all; std::vector<bool> isClosed_all; get_sorted_curve_node_entities_and_split(*m_surface_parts[ipart], sorted_nodes_all, isClosed_all); if (debug_print) std::cout << "found " << sorted_nodes_all.size() << " loops " << std::endl; for (unsigned iloop=0; iloop < sorted_nodes_all.size(); iloop++) { bool isClosed = isClosed_all[iloop]; std::vector<stk::mesh::Entity>& sorted_nodes = sorted_nodes_all[iloop]; LocalCubicSplineFit cf; if (isClosed) { // FIXME default is to assume a smooth seam at the closed/repeated node cf.setIsPeriodic(false); } int n = sorted_nodes.size(); Vectors2D Q(n); for (int i=0; i < n; i++) { double *cdata = m_eMesh.field_data(m_eMesh.get_coordinates_field(), sorted_nodes[i]); Q[i] = Vector2D(cdata[0], cdata[1]); } double alpha = m_angle_criterion*M_PI/180.0; std::vector<int> corners; int nc = geom::check_for_corners(Q, alpha, corners, isClosed); DPRINTLN(corners); DPRINTLN(Q); if (nc) { std::cout << "Part = " << part.name() << " ncorners= " << nc << std::endl; cf.setIsCorner(corners); } ON_Curve *curve = cf.fit(Q); if (debug_print) { std::cout << "Part = " << part.name() << std::endl; cf.print(); //if (nc) exit(1); } if ( curve->IsValid() ) { ONX_Model_Object& mo = model.m_object_table.AppendNew(); mo.m_object = curve; mo.m_bDeleteObject = true; mo.m_attributes.m_layer_index = 0; // use the same name for each geometry object - hopefully this is ok - geometry kernel will // then loop over all objects and find closest projection mo.m_attributes.m_name = part.name().c_str(); } else delete curve; } } } // start section comments const char* sStartSectionComment = __FILE__ "PerceptMesh::fit_geometry" __DATE__; ON_BinaryFile archive( ON::write3dm, file ); // Set uuid's, indices, etc. model.Polish(); // writes model to archive int version = 5; // File can be read by Rhino 5 ON_TextLog error_log; bool ok = model.Write(archive, version, sStartSectionComment, &error_log ); VERIFY_OP_ON(ok,==,true,"failed write of 3dm file"); ON::End(); } #endif }
38.435244
197
0.547644
[ "mesh", "geometry", "object", "vector", "model" ]
1600306c5cf54043f6e6531d0bd5a8af0447f681
6,262
cc
C++
server/core/resultset.cc
nephtyws/MaxScale
312469dca2721666d9fff310b6c3166b0d05d2a3
[ "MIT" ]
null
null
null
server/core/resultset.cc
nephtyws/MaxScale
312469dca2721666d9fff310b6c3166b0d05d2a3
[ "MIT" ]
null
null
null
server/core/resultset.cc
nephtyws/MaxScale
312469dca2721666d9fff310b6c3166b0d05d2a3
[ "MIT" ]
null
null
null
/* * Copyright (c) 2016 MariaDB Corporation Ab * * Use of this software is governed by the Business Source License included * in the LICENSE.TXT file and at www.mariadb.com/bsl11. * * Change Date: 2023-01-01 * * On the date above, in accordance with the Business Source License, use * of this software will be governed by version 2 or later of the General * Public License. */ #include <string.h> #include <ctype.h> #include <numeric> #include <maxbase/alloc.h> #include <maxscale/resultset.hh> #include <maxscale/buffer.hh> #include <maxscale/dcb.hh> #include <maxscale/mysql_binlog.h> #include <maxscale/protocol/mysql.hh> /** * Send the field count packet in a response packet sequence. * * @param dcb DCB of connection to send result set to * @param count Number of columns in the result set * @return Non-zero on success */ static int mysql_send_fieldcount(DCB* dcb, int count) { GWBUF* pkt; uint8_t* ptr; if ((pkt = gwbuf_alloc(5)) == NULL) { return 0; } ptr = GWBUF_DATA(pkt); *ptr++ = 0x01; // Payload length *ptr++ = 0x00; *ptr++ = 0x00; *ptr++ = 0x01; // Sequence number in response *ptr++ = count; // Length of result string return dcb->func.write(dcb, pkt); } /** * Send the column definition packet in a response packet sequence. * * @param dcb The DCB of the connection * @param name Name of the column * @param type Column type * @param len Column length * @param seqno Packet sequence number * @return Non-zero on success */ static int mysql_send_columndef(DCB* dcb, const std::string& name, uint8_t seqno) { GWBUF* pkt = gwbuf_alloc(26 + name.length()); if (pkt == NULL) { return 0; } int len = 255; // Column type length e.g. VARCHAR(255) uint8_t* ptr = GWBUF_DATA(pkt); int plen = 22 + name.length(); *ptr++ = plen & 0xff; *ptr++ = (plen >> 8) & 0xff; *ptr++ = (plen >> 16) & 0xff; *ptr++ = seqno; // Sequence number in response *ptr++ = 3; // Catalog is always def *ptr++ = 'd'; *ptr++ = 'e'; *ptr++ = 'f'; *ptr++ = 0; // Schema name length *ptr++ = 0; // virtual table name length *ptr++ = 0; // Table name length *ptr++ = name.length(); // Column name length; memcpy(ptr, name.c_str(), name.length()); ptr += name.length(); *ptr++ = 0; // Original column name *ptr++ = 0x0c; // Length of next fields always 12 *ptr++ = 0x3f; // Character set *ptr++ = 0; *ptr++ = len & 0xff; // Length of column *ptr++ = (len >> 8) & 0xff; *ptr++ = (len >> 16) & 0xff; *ptr++ = (len >> 24) & 0xff; *ptr++ = TABLE_COL_TYPE_VARCHAR; *ptr++ = 0x81; // Two bytes of flags *ptr++ = 0x00; *ptr++ = 0; *ptr++ = 0; *ptr++ = 0; return dcb->func.write(dcb, pkt); } /** * Send an EOF packet in a response packet sequence. * * @param dcb The client connection * @param seqno The sequence number of the EOF packet * @return Non-zero on success */ static int mysql_send_eof(DCB* dcb, int seqno) { GWBUF* pkt = gwbuf_alloc(9); if (pkt == NULL) { return 0; } uint8_t* ptr = GWBUF_DATA(pkt); *ptr++ = 0x05; *ptr++ = 0x00; *ptr++ = 0x00; *ptr++ = seqno; // Sequence number in response *ptr++ = 0xfe; // Length of result string *ptr++ = 0x00; // No Errors *ptr++ = 0x00; *ptr++ = 0x02; // Autocommit enabled *ptr++ = 0x00; return dcb->func.write(dcb, pkt); } /** * Send a row packet in a response packet sequence. * * @param dcb The client connection * @param row The row to send * @param seqno The sequence number of the EOF packet * @return Non-zero on success */ static int mysql_send_row(DCB* dcb, const std::vector<std::string>& row, int seqno) { auto acc = [](int l, const std::string& s) { return l + s.length() + 1; }; int len = std::accumulate(row.begin(), row.end(), MYSQL_HEADER_LEN, acc); GWBUF* pkt = gwbuf_alloc(len); if (pkt == NULL) { return 0; } uint8_t* ptr = GWBUF_DATA(pkt); len -= MYSQL_HEADER_LEN; *ptr++ = len & 0xff; *ptr++ = (len >> 8) & 0xff; *ptr++ = (len >> 16) & 0xff; *ptr++ = seqno; for (const auto& a : row) { *ptr++ = a.length(); memcpy(ptr, a.c_str(), a.length()); ptr += a.length(); } return dcb->func.write(dcb, pkt); } ResultSet::ResultSet(std::initializer_list<std::string> names) : m_columns(names) { } std::unique_ptr<ResultSet> ResultSet::create(std::initializer_list<std::string> names) { return std::unique_ptr<ResultSet>(new(std::nothrow) ResultSet(names)); } void ResultSet::add_row(std::initializer_list<std::string> values) { mxb_assert(values.size() == m_columns.size()); m_rows.emplace_back(values); } void ResultSet::write(DCB* dcb) { mysql_send_fieldcount(dcb, m_columns.size()); uint8_t seqno = 2; // The second packet after field count for (const auto& c : m_columns) { mysql_send_columndef(dcb, c, seqno++); } mysql_send_eof(dcb, seqno++); for (const auto& r : m_rows) { mysql_send_row(dcb, r, seqno++); } mysql_send_eof(dcb, seqno); } void ResultSet::write_as_json(DCB* dcb) { json_t* arr = json_array(); for (const auto& row : m_rows) { json_t* obj = json_object(); for (size_t i = 0; i < row.size(); i++) { json_object_set_new(obj, m_columns[i].c_str(), json_string(row[i].c_str())); } json_array_append_new(arr, obj); } char* js = json_dumps(arr, JSON_INDENT(4)); dcb_printf(dcb, "%s", js); MXS_FREE(js); }
27.108225
88
0.539923
[ "vector" ]
16033458a497c4ec737f136614e57426e64ca2e2
3,399
cpp
C++
sources/SBFramework/SBDynamicData/SBDynamicData.cpp
podgorskiy/ProceduralSky
386d091be8e8f4d7b5a838506c5b481779e56e42
[ "MIT" ]
3
2016-11-04T16:16:24.000Z
2019-04-14T07:24:00.000Z
sources/SBFramework/SBDynamicData/SBDynamicData.cpp
podgorskiy/ProceduralSky
386d091be8e8f4d7b5a838506c5b481779e56e42
[ "MIT" ]
null
null
null
sources/SBFramework/SBDynamicData/SBDynamicData.cpp
podgorskiy/ProceduralSky
386d091be8e8f4d7b5a838506c5b481779e56e42
[ "MIT" ]
null
null
null
#include "SBDynamicData.h" #include "SBDynamicDataValues.h" #include "SBFileSystem/SBCFile.h" #include <pugixml.hpp> using namespace SB; DynamicLighteningProperties::DynamicLighteningProperties() {}; void DynamicLighteningProperties::Load(IFile* file) { char* buffer = new char[file->GetSize()]; file->Read(buffer, file->GetSize()); pugi::xml_document doc; pugi::xml_parse_result result = doc.load_buffer(buffer, file->GetSize()); pugi::xml_node node = doc.child("data"); for (pugi::xml_node groupNode = node.child("group"); groupNode; groupNode = groupNode.next_sibling("group")) { Group* group = new Group(this, groupNode.attribute("name").value()); group->Load(groupNode); m_groups.push_back(group); } delete[] buffer; } void DynamicLighteningProperties::Unload() { DeleteDynamicDataValues(m_float); DeleteDynamicDataValues(m_vec2); DeleteDynamicDataValues(m_vec3); DeleteDynamicDataValues(m_vec4); } void DynamicLighteningProperties::UpdateMaterialsValues(float time) { UpdateDynamicDataValues(time, m_float); UpdateDynamicDataValues(time, m_vec2); UpdateDynamicDataValues(time, m_vec3); UpdateDynamicDataValues(time, m_vec4); }; DynamicLighteningProperties::ValueID DynamicLighteningProperties::registerValue(std::string name, ValueID id) { std::pair<std::map<std::string, ValueID>::iterator, bool> result = m_idLookupTable.insert(std::make_pair(name, id)); return result.first->second; }; DynamicLighteningProperties::ValueID DynamicLighteningProperties::GetValueID(const std::string name) const { std::map<std::string, ValueID>::const_iterator it = m_idLookupTable.find(name); if (it != m_idLookupTable.end()) { return it->second; } return -1; } template<typename T> T DynamicLighteningProperties::GetValueByID(ValueID id, float time) const { unsigned int pos = id >> Group::ValueTypeOffset; ASSERT(Group::GetValueType< Value<T> >() == (id & Group::ValueTypeMask), "Wrong value type!!!"); const std::vector< Value<T>* >& vec = GetValuesVector< Value<T> >(); if (vec.size() > pos) { const Value<T>* value = vec[pos]; if (value != NULL) { T valueAtTime = value->GetValue(time); return valueAtTime; } } ASSERT(false, "value is missing") return T(); } template<> const std::vector<FloatValue*>& DynamicLighteningProperties::GetValuesVector<FloatValue>() const { return m_float; } template<> const std::vector<Vec2Value*>& DynamicLighteningProperties::GetValuesVector<Vec2Value>() const { return m_vec2; } template<> const std::vector<Vec3Value*>& DynamicLighteningProperties::GetValuesVector<Vec3Value>() const { return m_vec3; } template<> const std::vector<Vec4Value*>& DynamicLighteningProperties::GetValuesVector<Vec4Value>() const { return m_vec4; } template<> const std::vector<QuaternionValue*>& DynamicLighteningProperties::GetValuesVector<QuaternionValue>() const { return m_quat; } template float SB::DynamicLighteningProperties::GetValueByID<float>(ValueID id, float time) const; template glm::vec2 SB::DynamicLighteningProperties::GetValueByID<glm::vec2>(ValueID id, float time) const; template glm::vec3 SB::DynamicLighteningProperties::GetValueByID<glm::vec3>(ValueID id, float time) const; template glm::vec4 SB::DynamicLighteningProperties::GetValueByID<glm::vec4>(ValueID id, float time) const; template glm::quat SB::DynamicLighteningProperties::GetValueByID<glm::quat>(ValueID id, float time) const;
29.051282
117
0.758753
[ "vector" ]
1604bd360c377bb22fb41904d98742ce4dad2a28
13,565
hpp
C++
VSDataReduction/VBFRunInfo.hpp
sfegan/ChiLA
916bdd95348c2df2ecc736511d5f5b2bfb4a831e
[ "BSD-3-Clause" ]
1
2018-04-17T14:03:36.000Z
2018-04-17T14:03:36.000Z
VSDataReduction/VBFRunInfo.hpp
sfegan/ChiLA
916bdd95348c2df2ecc736511d5f5b2bfb4a831e
[ "BSD-3-Clause" ]
null
null
null
VSDataReduction/VBFRunInfo.hpp
sfegan/ChiLA
916bdd95348c2df2ecc736511d5f5b2bfb4a831e
[ "BSD-3-Clause" ]
null
null
null
//-*-mode:c++; mode:font-lock;-*- /*! \file VBFRunInfo.hpp Extract some information from run \author Stephen Fegan \n UCLA \n sfegan@astro.ucla.edu \n \version 1.0 \date 10/11/2006 $Id: VBFRunInfo.hpp,v 3.19 2008/09/24 20:03:42 matthew Exp $ */ #ifndef VBFRUNINFO_HPP #define VBFRUNINFO_HPP #include <vector> #include <SphericalCoords.h> #include <VSSimpleVBF.hpp> #include <VSOctaveIO.hpp> #include <VSDataReductionTypes.hpp> #include <VSSimCoordTransform.hpp> #include <VSSimpleStat.hpp> #include <VSAAlgebra.hpp> namespace VERITAS { class VSPointing; class VBFRunInfo: public VSSimpleVBFVisitor { public: VBFRunInfo(bool copy_pedestal_packets, double sim_wobble_phi_rad); virtual ~VBFRunInfo(); virtual void visitFile(const char* filename, unsigned npacket); virtual void leaveFile(); virtual void visitPacket(bool& veto_packet, void*& user_data, uint32_t seq_packet_number, uint32_t vbf_packet_number, bool has_array_event, bool has_sim_header, bool has_sim_event, uint32_t num_overflow_datum, const VBFPacket* packet); virtual void visitArrayEvent(bool& veto_array_event, void* user_data, uint32_t num_scope_events, bool has_array_trigger, bool has_event_number, uint32_t event_num, bool has_good_event_time, const VSTime& best_event_time, EventType event_type, uint32_t l2_trigger_mask, const VArrayEvent* array_event); virtual void leaveArrayEvent(bool veto_array_event, void* user_data); virtual void visitArrayTrigger(bool& veto_array_event, void* user_data, uint32_t event_num, const VEventType& event_type, uint32_t trigger_mask, uint32_t flags, const VSTime& raw_time, uint32_t at_flags, uint32_t config_mask, uint32_t num_telescopes, uint32_t num_trigger_telescopes, uint32_t run_number, const uint32_t* ten_mhz_clocks, const uint32_t* cal_count, const uint32_t* ped_count, const VArrayTrigger* trigger); virtual void visitArrayTriggerScope(bool& veto_array_event, void* user_data, uint32_t telescope_num, bool triggered, uint32_t event_type, float altitude, float azimuth, uint32_t tdc, uint32_t shower_delay, uint32_t comp_delay, const uint32_t* l2_counts, const uint32_t* cal_counts); virtual void visitScopeEvent(bool& veto_scope_event, void* user_data, uint32_t event_num, uint32_t telescope_num, const VEventType& event_type, uint32_t trigger_mask, uint32_t flags, const VSTime& raw_time, uint32_t num_samples, uint32_t num_channels_saved, uint32_t num_channels_total, uint32_t num_clock_trigger, const VEvent* event); virtual void visitSimulationHeader(void* user_data, uint32_t run_number, const VSTime& date_of_sims, uint32_t simulation_package, const std::string& simulator_name, const VSTime& date_of_array, uint32_t corsika_atm_model, float obs_altitude_m, const std::vector<VArrayConfiguration>& array, const std::string& stringified_config); virtual void visitSimulationEvent(bool& veto_packet, void* user_data, uint32_t run_number, uint32_t event_num, uint32_t corsika_particle_id, float energy_gev, float obs_zenith_deg, float obs_azimuth_deg, float primary_zenith_deg, float primary_azimuth_deg, float ref_zenith_deg, float ref_azimuth_deg, float ref_position_angle_deg, float core_east_m, float core_south_m, float core_elevation_asl_m); virtual void visitChiLAHeader(void* user_data, const std::string& database_name, const std::vector<VChiLASimParamTable>& sim_param_tables, const std::vector<VChiLAOpticsConfiguration>& optics_configurations, const std::vector<VChiLAElectronicsConfiguration>& electronics_configurations); virtual void visitChiLAEvent(bool& veto_packet, void* user_data, uint32_t table_index, uint32_t electronics_id, uint32_t table_event_index, float a_omega, float a_omega_var); virtual void visitKascadeHeader(void* user_data, uint32_t corsika_particle_id, float energy_gev, uint32_t shower_id, float x_area_width_m, float y_area_width_m, uint32_t north_south_grid); virtual void visitKascadeEvent(bool& veto_packet, void* user_data, int32_t nx, int32_t ny, int32_t direction_index, float emission_altitude_m, float emission_altitude_sigma, float muon_ratio, float a_omega, float rel_tel_trigger_time_ns, float differential_rate_per_event_hz, float integral_rate_per_event_hz); class Data { public: Data(): got_run_number(), run_number(), nevents(), first_event_time(), first_event_vbf_packet_num(), lo_event_num(), hi_event_num(), lo_event_time(), hi_event_time(), ra_mean_deg(), dec_mean_deg(), ra_rms_deg(), dec_rms_deg(), zn_mean_deg(), az_mean_deg(), zn_rms_deg(), az_rms_deg(), mean_zn_1dim_deg(), config_mask(), nsample(), nchan() { /* nothing to see here */ } bool got_run_number; unsigned run_number; unsigned nevents; VSTime first_event_time; unsigned first_event_vbf_packet_num; unsigned lo_event_num; unsigned hi_event_num; VSTime lo_event_time; VSTime hi_event_time; double ra_mean_deg; double dec_mean_deg; double ra_rms_deg; double dec_rms_deg; double zn_mean_deg; double az_mean_deg; double zn_rms_deg; double az_rms_deg; double mean_zn_1dim_deg; std::vector<bool> config_mask; std::vector<unsigned> nsample; std::vector<unsigned> nchan; static void _compose(VSOctaveH5CompositeDefinition& c) { H5_ADDMEMBER(c,Data,got_run_number); H5_ADDMEMBER(c,Data,run_number); H5_ADDMEMBER(c,Data,nevents); H5_ADDSIMPLECOMPOSITE(c,Data,first_event_time); H5_ADDMEMBER(c,Data,first_event_vbf_packet_num); H5_ADDMEMBER(c,Data,lo_event_num); H5_ADDMEMBER(c,Data,hi_event_num); H5_ADDSIMPLECOMPOSITE(c,Data,lo_event_time); H5_ADDSIMPLECOMPOSITE(c,Data,hi_event_time); H5_ADDMEMBER(c,Data,ra_mean_deg); H5_ADDMEMBER(c,Data,dec_mean_deg); H5_ADDMEMBER(c,Data,ra_rms_deg); H5_ADDMEMBER(c,Data,dec_rms_deg); H5_ADDMEMBER(c,Data,zn_mean_deg); H5_ADDMEMBER(c,Data,az_mean_deg); H5_ADDMEMBER(c,Data,zn_rms_deg); H5_ADDMEMBER(c,Data,az_rms_deg); H5_ADDMEMBER(c,Data,mean_zn_1dim_deg); } void clear(); void load(VSOctaveH5ReaderStruct* reader); void save(VSOctaveH5WriterStruct* writer) const; void calculateMeanPointing(VSPointing& pointing, const SEphem::SphericalCoords& earth_position); }; class SimData { public: SimData(): package(SP_UNKNOWN), src_ra_deg(), src_dec_deg(), obs_ra_deg(), obs_dec_deg(), wobble_theta_deg(), wobble_phi_deg(), particle_spectrum(), scope_positions() { /* nothing to see here */ } enum SimPackage { SP_UNKNOWN, SP_CHILA, SP_KASCADE, SP_GRISU, SP_MCGILL }; class ParticleSpectrum { public: ParticleSpectrum(): corsika_particle_id(), min_energy_tev(), max_energy_tev(), dlog_energy(), discrete_binning_start() { /* nothing to see here */ } uint32_t corsika_particle_id; double min_energy_tev; double max_energy_tev; double dlog_energy; double discrete_binning_start; static void _compose(VSOctaveH5CompositeDefinition& c) { H5_ADDMEMBER(c,SimData::ParticleSpectrum,corsika_particle_id); H5_ADDMEMBER(c,SimData::ParticleSpectrum,min_energy_tev); H5_ADDMEMBER(c,SimData::ParticleSpectrum,max_energy_tev); H5_ADDMEMBER(c,SimData::ParticleSpectrum,dlog_energy); H5_ADDMEMBER(c,SimData::ParticleSpectrum,discrete_binning_start); } }; SimPackage package; double src_ra_deg; double src_dec_deg; double obs_ra_deg; double obs_dec_deg; double wobble_theta_deg; double wobble_phi_deg; std::vector<ParticleSpectrum> particle_spectrum; std::vector<pos_type> scope_positions; static void _compose(VSOctaveH5CompositeDefinition& c) { H5_ADDMEMBER(c,SimData,package); H5_ADDMEMBER(c,SimData,src_ra_deg); H5_ADDMEMBER(c,SimData,src_dec_deg); H5_ADDMEMBER(c,SimData,obs_ra_deg); H5_ADDMEMBER(c,SimData,obs_dec_deg); H5_ADDMEMBER(c,SimData,wobble_theta_deg); H5_ADDMEMBER(c,SimData,wobble_phi_deg); } void clear(); void load(VSOctaveH5ReaderStruct* reader); void save(VSOctaveH5WriterStruct* writer) const; }; struct EventTime { EventTime(): event_time(), event_found(false) { } EventTime(const VSTime& _time): event_time(_time), event_found(true) { } VSTime event_time; bool event_found; }; struct Slice { Slice(): event_num_lo(), event_num_hi(), event_time_lo(), event_time_hi() { } unsigned event_num_lo; unsigned event_num_hi; VSTime event_time_lo; VSTime event_time_hi; static void load(VSOctaveH5ReaderStruct* reader, std::vector<Slice>& slice); static void save(VSOctaveH5WriterStruct* writer, const std::vector<Slice>& slice); }; void getData(Data& data) const; SimData* getSimData() const; double getSliceWidthForNSlice(unsigned nslice) const; double getSliceWidthForApproxWidth(double approx_slice_width) const; std::vector<Slice> getTimeSlices(double slice_width) const; std::vector<Slice> getEventSlices(unsigned num_events) const; const std::vector<EventTime>& getEventTimes() const; unsigned dispatchPedestals(VSSimpleVBFDispatcher& dispatcher) const; private: VBFRunInfo(const VBFRunInfo&); VBFRunInfo& operator= (const VBFRunInfo&); // SETTINGS --------------------------------------------------------------- bool m_copy_pedestal_packets; double m_sim_wobble_phi_rad; // DATA ------------------------------------------------------------------- unsigned m_run_number; unsigned m_nevents; VSTime m_first_event_time; unsigned m_first_event_vbf_packet_num; unsigned m_lo_event_num; unsigned m_hi_event_num; VSTime m_lo_event_time; VSTime m_hi_event_time; std::vector<bool> m_config_mask; std::vector<unsigned> m_nsample; std::vector<unsigned> m_nchan; std::vector<EventTime> m_event_time; std::list<VBFPacket*> m_pedestals; std::map<unsigned,std::pair<float,float> > m_sim_energy_limits; std::map<unsigned,std::set<float> > m_sim_energy; SimData* m_sim_data; // INTERMEDIATE ----------------------------------------------------------- unsigned m_got_run_number; bool m_got_first_event; bool m_got_first_event_time; unsigned m_vbf_packet_num; bool m_has_good_event_time; VSAAlgebra::Vec3D m_sim_src_radec; VSAAlgebra::Vec3D m_sim_obs_radec; unsigned m_sim_nevent; VSSimCoordTransform* m_sim_transform; VSTime m_best_event_time; unsigned m_event_num; bool m_is_ped_event; const VBFPacket* m_packet; }; DEFINE_H5ENUM(VBFRunInfo::SimData::SimPackage); } // namespace VERITAS #endif // not defined VBFRUNINFO_HPP
35.233766
79
0.588795
[ "vector" ]
1605e9197eb1b9125f91486c72067b658627afd7
17,257
cxx
C++
srcscintilla/scintilla375/src/MarginView.cxx
hleuwer/iup
6bafeb94b652c2a3ea1ef8ef3a9de6fd819e6b6e
[ "MIT" ]
64
2016-02-19T18:58:38.000Z
2022-03-16T17:51:09.000Z
srcscintilla/scintilla375/src/MarginView.cxx
hleuwer/iup
6bafeb94b652c2a3ea1ef8ef3a9de6fd819e6b6e
[ "MIT" ]
34
2017-04-14T01:12:21.000Z
2018-10-26T05:30:24.000Z
srcscintilla/scintilla375/src/MarginView.cxx
hleuwer/iup
6bafeb94b652c2a3ea1ef8ef3a9de6fd819e6b6e
[ "MIT" ]
8
2016-01-25T00:24:01.000Z
2021-03-10T20:20:51.000Z
// Scintilla source code edit control /** @file MarginView.cxx ** Defines the appearance of the editor margin. **/ // Copyright 1998-2014 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #include <cstddef> #include <cstdlib> #include <cassert> #include <cstring> #include <cctype> #include <cstdio> #include <cmath> #include <stdexcept> #include <string> #include <vector> #include <map> #include <algorithm> #include <memory> #include "Platform.h" #include "ILexer.h" #include "Scintilla.h" #include "StringCopy.h" #include "Position.h" #include "UniqueString.h" #include "SplitVector.h" #include "Partitioning.h" #include "RunStyles.h" #include "ContractionState.h" #include "CellBuffer.h" #include "KeyMap.h" #include "Indicator.h" #include "XPM.h" #include "LineMarker.h" #include "Style.h" #include "ViewStyle.h" #include "CharClassify.h" #include "Decoration.h" #include "CaseFolder.h" #include "Document.h" #include "UniConversion.h" #include "Selection.h" #include "PositionCache.h" #include "EditModel.h" #include "MarginView.h" #include "EditView.h" #ifdef SCI_NAMESPACE using namespace Scintilla; #endif #ifdef SCI_NAMESPACE namespace Scintilla { #endif void DrawWrapMarker(Surface *surface, PRectangle rcPlace, bool isEndMarker, ColourDesired wrapColour) { surface->PenColour(wrapColour); enum { xa = 1 }; // gap before start int w = static_cast<int>(rcPlace.right - rcPlace.left) - xa - 1; const bool xStraight = isEndMarker; // x-mirrored symbol for start marker const int x0 = static_cast<int>(xStraight ? rcPlace.left : rcPlace.right - 1); const int y0 = static_cast<int>(rcPlace.top); int dy = static_cast<int>(rcPlace.bottom - rcPlace.top) / 5; int y = static_cast<int>(rcPlace.bottom - rcPlace.top) / 2 + dy; struct Relative { Surface *surface; int xBase; int xDir; int yBase; int yDir; void MoveTo(int xRelative, int yRelative) { surface->MoveTo(xBase + xDir * xRelative, yBase + yDir * yRelative); } void LineTo(int xRelative, int yRelative) { surface->LineTo(xBase + xDir * xRelative, yBase + yDir * yRelative); } }; Relative rel = { surface, x0, xStraight ? 1 : -1, y0, 1 }; // arrow head rel.MoveTo(xa, y); rel.LineTo(xa + 2 * w / 3, y - dy); rel.MoveTo(xa, y); rel.LineTo(xa + 2 * w / 3, y + dy); // arrow body rel.MoveTo(xa, y); rel.LineTo(xa + w, y); rel.LineTo(xa + w, y - 2 * dy); rel.LineTo(xa - 1, // on windows lineto is exclusive endpoint, perhaps GTK not... y - 2 * dy); } MarginView::MarginView() { wrapMarkerPaddingRight = 3; customDrawWrapMarker = NULL; } void MarginView::DropGraphics(bool freeObjects) { if (freeObjects) { pixmapSelMargin.reset(); pixmapSelPattern.reset(); pixmapSelPatternOffset1.reset(); } else { if (pixmapSelMargin) pixmapSelMargin->Release(); if (pixmapSelPattern) pixmapSelPattern->Release(); if (pixmapSelPatternOffset1) pixmapSelPatternOffset1->Release(); } } void MarginView::AllocateGraphics(const ViewStyle &vsDraw) { if (!pixmapSelMargin) pixmapSelMargin.reset(Surface::Allocate(vsDraw.technology)); if (!pixmapSelPattern) pixmapSelPattern.reset(Surface::Allocate(vsDraw.technology)); if (!pixmapSelPatternOffset1) pixmapSelPatternOffset1.reset(Surface::Allocate(vsDraw.technology)); } void MarginView::RefreshPixMaps(Surface *surfaceWindow, WindowID wid, const ViewStyle &vsDraw) { if (!pixmapSelPattern->Initialised()) { const int patternSize = 8; pixmapSelPattern->InitPixMap(patternSize, patternSize, surfaceWindow, wid); pixmapSelPatternOffset1->InitPixMap(patternSize, patternSize, surfaceWindow, wid); // This complex procedure is to reproduce the checkerboard dithered pattern used by windows // for scroll bars and Visual Studio for its selection margin. The colour of this pattern is half // way between the chrome colour and the chrome highlight colour making a nice transition // between the window chrome and the content area. And it works in low colour depths. PRectangle rcPattern = PRectangle::FromInts(0, 0, patternSize, patternSize); // Initialize default colours based on the chrome colour scheme. Typically the highlight is white. ColourDesired colourFMFill = vsDraw.selbar; ColourDesired colourFMStripes = vsDraw.selbarlight; if (!(vsDraw.selbarlight == ColourDesired(0xff, 0xff, 0xff))) { // User has chosen an unusual chrome colour scheme so just use the highlight edge colour. // (Typically, the highlight colour is white.) colourFMFill = vsDraw.selbarlight; } if (vsDraw.foldmarginColour.isSet) { // override default fold margin colour colourFMFill = vsDraw.foldmarginColour; } if (vsDraw.foldmarginHighlightColour.isSet) { // override default fold margin highlight colour colourFMStripes = vsDraw.foldmarginHighlightColour; } pixmapSelPattern->FillRectangle(rcPattern, colourFMFill); pixmapSelPatternOffset1->FillRectangle(rcPattern, colourFMStripes); for (int y = 0; y < patternSize; y++) { for (int x = y % 2; x < patternSize; x += 2) { PRectangle rcPixel = PRectangle::FromInts(x, y, x + 1, y + 1); pixmapSelPattern->FillRectangle(rcPixel, colourFMStripes); pixmapSelPatternOffset1->FillRectangle(rcPixel, colourFMFill); } } } } static int SubstituteMarkerIfEmpty(int markerCheck, int markerDefault, const ViewStyle &vs) { if (vs.markers[markerCheck].markType == SC_MARK_EMPTY) return markerDefault; return markerCheck; } void MarginView::PaintMargin(Surface *surface, Sci::Line topLine, PRectangle rc, PRectangle rcMargin, const EditModel &model, const ViewStyle &vs) { PRectangle rcSelMargin = rcMargin; rcSelMargin.right = rcMargin.left; if (rcSelMargin.bottom < rc.bottom) rcSelMargin.bottom = rc.bottom; Point ptOrigin = model.GetVisibleOriginInMain(); FontAlias fontLineNumber = vs.styles[STYLE_LINENUMBER].font; for (size_t margin = 0; margin < vs.ms.size(); margin++) { if (vs.ms[margin].width > 0) { rcSelMargin.left = rcSelMargin.right; rcSelMargin.right = rcSelMargin.left + vs.ms[margin].width; if (vs.ms[margin].style != SC_MARGIN_NUMBER) { if (vs.ms[margin].mask & SC_MASK_FOLDERS) { // Required because of special way brush is created for selection margin // Ensure patterns line up when scrolling with separate margin view // by choosing correctly aligned variant. const bool invertPhase = static_cast<int>(ptOrigin.y) & 1; surface->FillRectangle(rcSelMargin, invertPhase ? *pixmapSelPattern : *pixmapSelPatternOffset1); } else { ColourDesired colour; switch (vs.ms[margin].style) { case SC_MARGIN_BACK: colour = vs.styles[STYLE_DEFAULT].back; break; case SC_MARGIN_FORE: colour = vs.styles[STYLE_DEFAULT].fore; break; case SC_MARGIN_COLOUR: colour = vs.ms[margin].back; break; default: colour = vs.styles[STYLE_LINENUMBER].back; break; } surface->FillRectangle(rcSelMargin, colour); } } else { surface->FillRectangle(rcSelMargin, vs.styles[STYLE_LINENUMBER].back); } const int lineStartPaint = static_cast<int>(rcMargin.top + ptOrigin.y) / vs.lineHeight; Sci::Line visibleLine = model.TopLineOfMain() + lineStartPaint; Sci::Position yposScreen = lineStartPaint * vs.lineHeight - static_cast<Sci::Position>(ptOrigin.y); // Work out whether the top line is whitespace located after a // lessening of fold level which implies a 'fold tail' but which should not // be displayed until the last of a sequence of whitespace. bool needWhiteClosure = false; if (vs.ms[margin].mask & SC_MASK_FOLDERS) { const int level = model.pdoc->GetLevel(model.cs.DocFromDisplay(visibleLine)); if (level & SC_FOLDLEVELWHITEFLAG) { Sci::Line lineBack = model.cs.DocFromDisplay(visibleLine); int levelPrev = level; while ((lineBack > 0) && (levelPrev & SC_FOLDLEVELWHITEFLAG)) { lineBack--; levelPrev = model.pdoc->GetLevel(lineBack); } if (!(levelPrev & SC_FOLDLEVELHEADERFLAG)) { if (LevelNumber(level) < LevelNumber(levelPrev)) needWhiteClosure = true; } } if (highlightDelimiter.isEnabled) { Sci::Line lastLine = model.cs.DocFromDisplay(topLine + model.LinesOnScreen()) + 1; model.pdoc->GetHighlightDelimiters(highlightDelimiter, model.pdoc->LineFromPosition(model.sel.MainCaret()), lastLine); } } // Old code does not know about new markers needed to distinguish all cases const int folderOpenMid = SubstituteMarkerIfEmpty(SC_MARKNUM_FOLDEROPENMID, SC_MARKNUM_FOLDEROPEN, vs); const int folderEnd = SubstituteMarkerIfEmpty(SC_MARKNUM_FOLDEREND, SC_MARKNUM_FOLDER, vs); while ((visibleLine < model.cs.LinesDisplayed()) && yposScreen < rc.bottom) { PLATFORM_ASSERT(visibleLine < model.cs.LinesDisplayed()); const Sci::Line lineDoc = model.cs.DocFromDisplay(visibleLine); PLATFORM_ASSERT(model.cs.GetVisible(lineDoc)); const Sci::Line firstVisibleLine = model.cs.DisplayFromDoc(lineDoc); const Sci::Line lastVisibleLine = model.cs.DisplayLastFromDoc(lineDoc); const bool firstSubLine = visibleLine == firstVisibleLine; const bool lastSubLine = visibleLine == lastVisibleLine; int marks = model.pdoc->GetMark(lineDoc); if (!firstSubLine) marks = 0; bool headWithTail = false; if (vs.ms[margin].mask & SC_MASK_FOLDERS) { // Decide which fold indicator should be displayed const int level = model.pdoc->GetLevel(lineDoc); const int levelNext = model.pdoc->GetLevel(lineDoc + 1); const int levelNum = LevelNumber(level); const int levelNextNum = LevelNumber(levelNext); if (level & SC_FOLDLEVELHEADERFLAG) { if (firstSubLine) { if (levelNum < levelNextNum) { if (model.cs.GetExpanded(lineDoc)) { if (levelNum == SC_FOLDLEVELBASE) marks |= 1 << SC_MARKNUM_FOLDEROPEN; else marks |= 1 << folderOpenMid; } else { if (levelNum == SC_FOLDLEVELBASE) marks |= 1 << SC_MARKNUM_FOLDER; else marks |= 1 << folderEnd; } } else if (levelNum > SC_FOLDLEVELBASE) { marks |= 1 << SC_MARKNUM_FOLDERSUB; } } else { if (levelNum < levelNextNum) { if (model.cs.GetExpanded(lineDoc)) { marks |= 1 << SC_MARKNUM_FOLDERSUB; } else if (levelNum > SC_FOLDLEVELBASE) { marks |= 1 << SC_MARKNUM_FOLDERSUB; } } else if (levelNum > SC_FOLDLEVELBASE) { marks |= 1 << SC_MARKNUM_FOLDERSUB; } } needWhiteClosure = false; const Sci::Line firstFollowupLine = model.cs.DocFromDisplay(model.cs.DisplayFromDoc(lineDoc + 1)); const int firstFollowupLineLevel = model.pdoc->GetLevel(firstFollowupLine); const int secondFollowupLineLevelNum = LevelNumber(model.pdoc->GetLevel(firstFollowupLine + 1)); if (!model.cs.GetExpanded(lineDoc)) { if ((firstFollowupLineLevel & SC_FOLDLEVELWHITEFLAG) && (levelNum > secondFollowupLineLevelNum)) needWhiteClosure = true; if (highlightDelimiter.IsFoldBlockHighlighted(firstFollowupLine)) headWithTail = true; } } else if (level & SC_FOLDLEVELWHITEFLAG) { if (needWhiteClosure) { if (levelNext & SC_FOLDLEVELWHITEFLAG) { marks |= 1 << SC_MARKNUM_FOLDERSUB; } else if (levelNextNum > SC_FOLDLEVELBASE) { marks |= 1 << SC_MARKNUM_FOLDERMIDTAIL; needWhiteClosure = false; } else { marks |= 1 << SC_MARKNUM_FOLDERTAIL; needWhiteClosure = false; } } else if (levelNum > SC_FOLDLEVELBASE) { if (levelNextNum < levelNum) { if (levelNextNum > SC_FOLDLEVELBASE) { marks |= 1 << SC_MARKNUM_FOLDERMIDTAIL; } else { marks |= 1 << SC_MARKNUM_FOLDERTAIL; } } else { marks |= 1 << SC_MARKNUM_FOLDERSUB; } } } else if (levelNum > SC_FOLDLEVELBASE) { if (levelNextNum < levelNum) { needWhiteClosure = false; if (levelNext & SC_FOLDLEVELWHITEFLAG) { marks |= 1 << SC_MARKNUM_FOLDERSUB; needWhiteClosure = true; } else if (lastSubLine) { if (levelNextNum > SC_FOLDLEVELBASE) { marks |= 1 << SC_MARKNUM_FOLDERMIDTAIL; } else { marks |= 1 << SC_MARKNUM_FOLDERTAIL; } } else { marks |= 1 << SC_MARKNUM_FOLDERSUB; } } else { marks |= 1 << SC_MARKNUM_FOLDERSUB; } } } marks &= vs.ms[margin].mask; PRectangle rcMarker = rcSelMargin; rcMarker.top = static_cast<XYPOSITION>(yposScreen); rcMarker.bottom = static_cast<XYPOSITION>(yposScreen + vs.lineHeight); if (vs.ms[margin].style == SC_MARGIN_NUMBER) { if (firstSubLine) { char number[100] = ""; if (lineDoc >= 0) sprintf(number, "%d", lineDoc + 1); if (model.foldFlags & (SC_FOLDFLAG_LEVELNUMBERS | SC_FOLDFLAG_LINESTATE)) { if (model.foldFlags & SC_FOLDFLAG_LEVELNUMBERS) { const int lev = model.pdoc->GetLevel(lineDoc); sprintf(number, "%c%c %03X %03X", (lev & SC_FOLDLEVELHEADERFLAG) ? 'H' : '_', (lev & SC_FOLDLEVELWHITEFLAG) ? 'W' : '_', LevelNumber(lev), lev >> 16 ); } else { const int state = model.pdoc->GetLineState(lineDoc); sprintf(number, "%0X", state); } } PRectangle rcNumber = rcMarker; // Right justify XYPOSITION width = surface->WidthText(fontLineNumber, number, static_cast<int>(strlen(number))); XYPOSITION xpos = rcNumber.right - width - vs.marginNumberPadding; rcNumber.left = xpos; DrawTextNoClipPhase(surface, rcNumber, vs.styles[STYLE_LINENUMBER], rcNumber.top + vs.maxAscent, number, static_cast<int>(strlen(number)), drawAll); } else if (vs.wrapVisualFlags & SC_WRAPVISUALFLAG_MARGIN) { PRectangle rcWrapMarker = rcMarker; rcWrapMarker.right -= wrapMarkerPaddingRight; rcWrapMarker.left = rcWrapMarker.right - vs.styles[STYLE_LINENUMBER].aveCharWidth; if (customDrawWrapMarker == NULL) { DrawWrapMarker(surface, rcWrapMarker, false, vs.styles[STYLE_LINENUMBER].fore); } else { customDrawWrapMarker(surface, rcWrapMarker, false, vs.styles[STYLE_LINENUMBER].fore); } } } else if (vs.ms[margin].style == SC_MARGIN_TEXT || vs.ms[margin].style == SC_MARGIN_RTEXT) { const StyledText stMargin = model.pdoc->MarginStyledText(lineDoc); if (stMargin.text && ValidStyledText(vs, vs.marginStyleOffset, stMargin)) { if (firstSubLine) { surface->FillRectangle(rcMarker, vs.styles[stMargin.StyleAt(0) + vs.marginStyleOffset].back); if (vs.ms[margin].style == SC_MARGIN_RTEXT) { int width = WidestLineWidth(surface, vs, vs.marginStyleOffset, stMargin); rcMarker.left = rcMarker.right - width - 3; } DrawStyledText(surface, vs, vs.marginStyleOffset, rcMarker, stMargin, 0, stMargin.length, drawAll); } else { // if we're displaying annotation lines, color the margin to match the associated document line const int annotationLines = model.pdoc->AnnotationLines(lineDoc); if (annotationLines && (visibleLine > lastVisibleLine - annotationLines)) { surface->FillRectangle(rcMarker, vs.styles[stMargin.StyleAt(0) + vs.marginStyleOffset].back); } } } } if (marks) { for (int markBit = 0; (markBit < 32) && marks; markBit++) { if (marks & 1) { LineMarker::typeOfFold tFold = LineMarker::undefined; if ((vs.ms[margin].mask & SC_MASK_FOLDERS) && highlightDelimiter.IsFoldBlockHighlighted(lineDoc)) { if (highlightDelimiter.IsBodyOfFoldBlock(lineDoc)) { tFold = LineMarker::body; } else if (highlightDelimiter.IsHeadOfFoldBlock(lineDoc)) { if (firstSubLine) { tFold = headWithTail ? LineMarker::headWithTail : LineMarker::head; } else { if (model.cs.GetExpanded(lineDoc) || headWithTail) { tFold = LineMarker::body; } else { tFold = LineMarker::undefined; } } } else if (highlightDelimiter.IsTailOfFoldBlock(lineDoc)) { tFold = LineMarker::tail; } } vs.markers[markBit].Draw(surface, rcMarker, fontLineNumber, tFold, vs.ms[margin].style); } marks >>= 1; } } visibleLine++; yposScreen += vs.lineHeight; } } } PRectangle rcBlankMargin = rcMargin; rcBlankMargin.left = rcSelMargin.right; surface->FillRectangle(rcBlankMargin, vs.styles[STYLE_DEFAULT].back); } #ifdef SCI_NAMESPACE } #endif
36.639066
124
0.658342
[ "vector", "model" ]
160697fb2e53302d40f70d2e6ec5aeee199d3713
1,632
cpp
C++
BashuOJ-Code/3124.cpp
magicgh/algorithm-contest-code
c21a90b11f73535c61e6363a4305b74cff24a85b
[ "MIT" ]
null
null
null
BashuOJ-Code/3124.cpp
magicgh/algorithm-contest-code
c21a90b11f73535c61e6363a4305b74cff24a85b
[ "MIT" ]
null
null
null
BashuOJ-Code/3124.cpp
magicgh/algorithm-contest-code
c21a90b11f73535c61e6363a4305b74cff24a85b
[ "MIT" ]
null
null
null
#include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<iomanip> #include<algorithm> #include<queue> #include<stack> #include<vector> #define ri register int using namespace std; const int INF=0x7fffffff/2; int dx[]={-1,1,0,0,-1,-1,1,1},dy[]={0,0,-1,1,-1,1,-1,1}; int n,k,map[1005][1005],dist[1005][1005]; bool vst[1005][1005]; struct heap { int x,y,dis; bool operator <(const heap &rhs)const{return dis>rhs.dis;} }; priority_queue<heap>q; inline int getint() { int num=0,bj=1; char c=getchar(); while(c<'0'||c>'9')bj=(c=='-'||bj==-1)?-1:1,c=getchar(); while(c>='0'&&c<='9')num=num*10+c-'0',c=getchar(); return num*bj; } void FloodFill() { for(ri i=1;i<=n;i++) for(ri j=1;j<=n;j++)dist[i][j]=INF/2; for(ri i=1;i<=n;i++)//来自边界的FloodFill { q.push((heap){0,i,0}); q.push((heap){i,0,0}); q.push((heap){n+1,0,0}); q.push((heap){0,n+1,0}); } while(!q.empty()) { heap now=q.top();q.pop(); if(vst[now.x][now.y])continue; vst[now.x][now.y]=1; for(ri k=0;k<8;k++) { heap next=(heap){now.x+dx[k],now.y+dy[k]}; if(next.x>=1&&next.x<=n&&next.y>=1&&next.y<=n) { int val=(map[now.x][now.y]&&!map[next.x][next.y]); if(dist[next.x][next.y]>dist[now.x][now.y]+val) { dist[next.x][next.y]=dist[now.x][now.y]+val; q.push((heap){next.x,next.y,dist[next.x][next.y]}); } } } } } int main() { char ch; n=getint(),k=getint(); for(ri i=1;i<=n;i++) for(ri j=1;j<=n;j++) { while(ch=getchar())if(isdigit(ch))break; map[i][j]=ch-'0'; } FloodFill(); for(ri i=1;i<=k;i++) { int x=getint(),y=getint(); printf("%d ",dist[x][y]); } return 0; }
20.4
59
0.568627
[ "vector" ]
1606cf0ea7d1ab9a7326e400ce11eef43c760a26
24,123
cpp
C++
JobScheduler.cpp
privacore/open-source-search-engine
dac28de673068039381ca3f66521ea4c1eaf6a1e
[ "Apache-2.0" ]
134
2016-05-30T13:29:37.000Z
2021-06-18T02:13:51.000Z
JobScheduler.cpp
mehmet-biter/open-source-search-engine
dac28de673068039381ca3f66521ea4c1eaf6a1e
[ "Apache-2.0" ]
65
2016-10-31T16:02:28.000Z
2020-04-30T14:18:57.000Z
JobScheduler.cpp
mehmet-biter/open-source-search-engine
dac28de673068039381ca3f66521ea4c1eaf6a1e
[ "Apache-2.0" ]
22
2016-05-30T13:29:39.000Z
2020-06-30T08:43:38.000Z
#include "JobScheduler.h" #include "ScopedLock.h" #include "BigFile.h" //for FileState definition #include "Errno.h" #include <pthread.h> #include <vector> #include <list> #include <algorithm> #include <stdexcept> #include <assert.h> #include <sys/time.h> #include <stdio.h> namespace { //return current time expressed as milliseconds since 1970 static uint64_t now_ms() { struct timeval tv; gettimeofday(&tv,0); return tv.tv_sec*1000 + tv.tv_usec/1000; } //A job (queued, running or finished) struct JobEntry { start_routine_t start_routine; finish_routine_t finish_callback; void *state; bool is_io_job; //for scheduling: uint64_t start_deadline; //latest time when this job must be started bool is_io_write_job; //valid for I/O jobs: mostly read or mostly write? int initial_priority; //priority when queued //for statistics: thread_type_t thread_type; uint64_t queue_enter_time; //when this job was queued uint64_t start_time; //when this job started running uint64_t stop_time; //when this job stopped running uint64_t finish_time; //when the finish callback was called uint64_t exit_time; //when this job was finished, including finish-callback }; //a set of jobs, prioritized class JobQueue : public std::vector<JobEntry> { public: pthread_cond_t cond_not_empty; unsigned potential_worker_threads; JobQueue() : vector(), cond_not_empty PTHREAD_COND_INITIALIZER, potential_worker_threads(0) { } ~JobQueue() { pthread_cond_destroy(&cond_not_empty); } void add(const JobEntry &e) { push_back(e); pthread_cond_signal(&cond_not_empty); } JobEntry pop_top_priority(); }; JobEntry JobQueue::pop_top_priority() { assert(!empty()); //todo: age old entries std::vector<JobEntry>::iterator best_iter = begin(); std::vector<JobEntry>::iterator iter = best_iter; ++iter; for( ; iter!=end(); ++iter) if(iter->initial_priority<best_iter->initial_priority) best_iter = iter; JobEntry tmp = *best_iter; erase(best_iter); return tmp; } typedef std::vector<std::pair<JobEntry,job_exit_t>> ExitSet; typedef std::list<JobEntry> RunningSet; //parameters given to a pool thread struct PoolThreadParameters { JobQueue *job_queue; //queue to fetch jobs from RunningSet *running_set; //set to store the job in while executing it ExitSet *exit_set; //set to store the finished job+exit-cause in unsigned *num_io_write_jobs_running; //global counter for scheduling pthread_mutex_t *mtx; //mutex covering above 3 containers job_done_notify_t job_done_notify; //notifycation callback whenever a job returns bool stop; }; extern "C" { static void *job_pool_thread_function(void *pv) { PoolThreadParameters *ptp= static_cast<PoolThreadParameters*>(pv); pthread_mutex_lock(ptp->mtx); while(!ptp->stop) { if(ptp->job_queue->empty()) pthread_cond_wait(&ptp->job_queue->cond_not_empty,ptp->mtx); if(ptp->stop) break; if(ptp->job_queue->empty()) //spurious wakeup continue; //take the top-priority job and move it into the running set RunningSet::iterator iter = ptp->running_set->insert(ptp->running_set->begin(),ptp->job_queue->pop_top_priority()); if(iter->is_io_job && iter->is_io_write_job) ++*(ptp->num_io_write_jobs_running); pthread_mutex_unlock(ptp->mtx); job_exit_t job_exit; uint64_t now = now_ms(); iter->start_time = now; if(iter->start_deadline==0 || iter->start_deadline>now) { // Clear g_errno so the thread/job starts with a clean slate g_errno = 0; iter->start_routine(iter->state); iter->stop_time = now_ms(); job_exit = job_exit_normal; } else { job_exit = job_exit_deadline; } pthread_mutex_lock(ptp->mtx); if(iter->is_io_job && iter->is_io_write_job) --*(ptp->num_io_write_jobs_running); //copy+delete it into the exit queue ptp->exit_set->push_back(std::make_pair(*iter,job_exit)); ptp->running_set->erase(iter); pthread_mutex_unlock(ptp->mtx); (ptp->job_done_notify)(); pthread_mutex_lock(ptp->mtx); } pthread_mutex_unlock(ptp->mtx); return 0; } } static void job_done_notify_noop() { } class ThreadPool { public: ThreadPool(const char *thread_name_prefix, unsigned num_threads, JobQueue *job_queue, RunningSet *running_set, ExitSet *exit_set, unsigned *num_io_write_jobs_running, pthread_mutex_t *mtx, job_done_notify_t job_done_notify_); void initiate_stop(); void join_all(); ~ThreadPool(); private: PoolThreadParameters ptp; std::vector<pthread_t> tid; }; ThreadPool::ThreadPool(const char *thread_name_prefix, unsigned num_threads, JobQueue *job_queue, RunningSet *running_set, ExitSet *exit_set, unsigned *num_io_write_jobs_running, pthread_mutex_t *mtx, job_done_notify_t job_done_notify_) : tid(num_threads) { job_queue->potential_worker_threads += num_threads; ptp.job_queue = job_queue; ptp.running_set = running_set; ptp.exit_set = exit_set; ptp.num_io_write_jobs_running = num_io_write_jobs_running; ptp.mtx = mtx; ptp.job_done_notify = job_done_notify_?job_done_notify_:job_done_notify_noop; ptp.stop = false; for(unsigned i=0; i<tid.size(); i++) { int rc = pthread_create(&tid[i], NULL, job_pool_thread_function, &ptp); if(rc!=0) throw std::runtime_error("pthread_create() failed"); char thread_name[16]; //hard limit snprintf(thread_name,sizeof(thread_name),"%s %u", thread_name_prefix,i); rc = pthread_setname_np(tid[i],thread_name); if(rc!=0) throw std::runtime_error("pthread_setname_np() failed"); } } void ThreadPool::initiate_stop() { for(unsigned i=0; i<tid.size(); i++) ptp.stop = true; } void ThreadPool::join_all() { for(unsigned i=0; i<tid.size(); i++) pthread_join(tid[i],NULL); tid.clear(); } ThreadPool::~ThreadPool() { join_all(); } } //anonymous namespace //////////////////////////////////////////////////////////////////////////////// // JobScheduler implementation class JobScheduler_impl { mutable pthread_mutex_t mtx; JobQueue coordinator_job_queue; JobQueue cpu_job_queue; JobQueue summary_job_queue; JobQueue io_job_queue; JobQueue external_job_queue; JobQueue file_meta_job_queue; JobQueue merge_job_queue; RunningSet running_set; ExitSet exit_set; unsigned num_io_write_jobs_running; ThreadPool coordinator_thread_pool; ThreadPool cpu_thread_pool; ThreadPool summary_thread_pool; ThreadPool io_thread_pool; ThreadPool external_thread_pool; ThreadPool file_meta_thread_pool; ThreadPool merge_thread_pool; bool no_threads; bool new_jobs_allowed; std::map<thread_type_t,JobTypeStatistics> job_statistics; bool submit(thread_type_t thread_type, JobEntry &e); void cancel_queued_jobs(JobQueue &jq, job_exit_t job_exit); public: JobScheduler_impl(unsigned num_coordinator_threads, unsigned num_cpu_threads, unsigned num_summary_threads, unsigned num_io_threads, unsigned num_external_threads, unsigned num_file_meta_threads, unsigned num_merge_threads, job_done_notify_t job_done_notify) : mtx PTHREAD_MUTEX_INITIALIZER, coordinator_job_queue(), cpu_job_queue(), summary_job_queue(), io_job_queue(), external_job_queue(), file_meta_job_queue(), merge_job_queue(), running_set(), exit_set(), num_io_write_jobs_running(0), coordinator_thread_pool("coord",num_coordinator_threads,&coordinator_job_queue,&running_set,&exit_set,&num_io_write_jobs_running,&mtx,job_done_notify), cpu_thread_pool("cpu",num_cpu_threads,&cpu_job_queue,&running_set,&exit_set,&num_io_write_jobs_running,&mtx,job_done_notify), summary_thread_pool("summary",num_summary_threads,&summary_job_queue,&running_set,&exit_set,&num_io_write_jobs_running,&mtx,job_done_notify), io_thread_pool("io",num_io_threads,&io_job_queue,&running_set,&exit_set,&num_io_write_jobs_running,&mtx,job_done_notify), external_thread_pool("ext",num_external_threads,&external_job_queue,&running_set,&exit_set,&num_io_write_jobs_running,&mtx,job_done_notify), file_meta_thread_pool("file",num_file_meta_threads,&file_meta_job_queue,&running_set,&exit_set,&num_io_write_jobs_running,&mtx,job_done_notify), merge_thread_pool("merge",num_merge_threads,&merge_job_queue,&running_set,&exit_set,&num_io_write_jobs_running,&mtx,job_done_notify), no_threads(num_cpu_threads==0 && num_summary_threads==0 && num_io_threads==0 && num_external_threads==0 && num_file_meta_threads==0), new_jobs_allowed(true) { } ~JobScheduler_impl(); bool submit(start_routine_t start_routine, finish_routine_t finish_callback, void *state, thread_type_t thread_type, int priority, uint64_t start_deadline=0); bool submit_io(start_routine_t start_routine, finish_routine_t finish_callback, FileState *fstate, thread_type_t thread_type, int priority, bool is_write_job, uint64_t start_deadline=0); bool are_io_write_jobs_running() const; void cancel_file_read_jobs(const BigFile *bf); //void nice page for html and administation() bool is_reading_file(const BigFile *bf); void allow_new_jobs() { new_jobs_allowed = true; } void disallow_new_jobs() { new_jobs_allowed = false; } bool are_new_jobs_allowed() const { return new_jobs_allowed && !no_threads; } void cancel_all_jobs_for_shutdown(); unsigned num_queued_jobs() const; void cleanup_finished_jobs(); std::vector<JobDigest> query_job_digests() const; std::map<thread_type_t,JobTypeStatistics> query_job_statistics(bool clear); }; JobScheduler_impl::~JobScheduler_impl() { //First prevent new jobs from being submitted new_jobs_allowed = false; //Then tell the worker threads to stop executing more jobs coordinator_thread_pool.initiate_stop(); cpu_thread_pool.initiate_stop(); summary_thread_pool.initiate_stop(); io_thread_pool.initiate_stop(); external_thread_pool.initiate_stop(); file_meta_thread_pool.initiate_stop(); merge_thread_pool.initiate_stop(); //Then wake them if they are sleeping pthread_cond_broadcast(&coordinator_job_queue.cond_not_empty); pthread_cond_broadcast(&cpu_job_queue.cond_not_empty); pthread_cond_broadcast(&summary_job_queue.cond_not_empty); pthread_cond_broadcast(&io_job_queue.cond_not_empty); pthread_cond_broadcast(&external_job_queue.cond_not_empty); pthread_cond_broadcast(&file_meta_job_queue.cond_not_empty); pthread_cond_broadcast(&merge_job_queue.cond_not_empty); //Then cancel all outstanding non-started jobs by moving them from the pending queues to the exit-set { ScopedLock sl(mtx); cancel_queued_jobs(coordinator_job_queue,job_exit_program_exit); cancel_queued_jobs(cpu_job_queue,job_exit_program_exit); cancel_queued_jobs(summary_job_queue,job_exit_program_exit); cancel_queued_jobs(io_job_queue,job_exit_program_exit); cancel_queued_jobs(external_job_queue,job_exit_program_exit); cancel_queued_jobs(file_meta_job_queue,job_exit_program_exit); cancel_queued_jobs(merge_job_queue,job_exit_program_exit); } //Call finish-callbacks for all the exited / cancelled threads //We "know" that this function (finalize) is only called from the main thread, *cough* *cough* cleanup_finished_jobs(); //Then wait for worker threads to finished coordinator_thread_pool.join_all(); cpu_thread_pool.join_all(); summary_thread_pool.join_all(); io_thread_pool.join_all(); file_meta_thread_pool.join_all(); merge_thread_pool.join_all(); external_thread_pool.join_all(); pthread_mutex_destroy(&mtx); } bool JobScheduler_impl::submit(thread_type_t thread_type, JobEntry &e) { if(!new_jobs_allowed) //note: unprotected read return false; e.thread_type = thread_type; //Determine which queue to put the job into //i/o jobs should have the is_io_job=true, but if they don't we will //just treat them as CPU-bound. All this looks over-engineered but we //need some flexibility to make experiments. JobQueue *job_queue; if(e.is_io_job) job_queue = &io_job_queue; else { switch(thread_type) { case thread_type_query_coordinator: job_queue = &coordinator_job_queue; break; case thread_type_query_read: job_queue = &cpu_job_queue; break; case thread_type_query_constrain: job_queue = &cpu_job_queue; break; case thread_type_query_merge: job_queue = &cpu_job_queue; break; case thread_type_query_intersect: job_queue = &cpu_job_queue; break; case thread_type_query_summary: job_queue = &summary_job_queue; break; case thread_type_spider_read: job_queue = &cpu_job_queue; break; case thread_type_spider_write: job_queue = &cpu_job_queue; break; case thread_type_spider_filter: job_queue = &external_job_queue; break; case thread_type_spider_query: job_queue = &cpu_job_queue; break; case thread_type_spider_index: job_queue = &cpu_job_queue; break; case thread_type_merge_filter: job_queue = &merge_job_queue; break; case thread_type_replicate_write: job_queue = &cpu_job_queue; break; case thread_type_replicate_read: job_queue = &cpu_job_queue; break; case thread_type_file_merge: job_queue = &merge_job_queue; break; case thread_type_file_meta_data: job_queue = &file_meta_job_queue;break; case thread_type_index_merge: job_queue = &cpu_job_queue; break; case thread_type_index_generate: job_queue = &merge_job_queue; break; case thread_type_verify_data: job_queue = &cpu_job_queue; break; case thread_type_statistics: job_queue = &cpu_job_queue; break; case thread_type_unspecified_io: job_queue = &cpu_job_queue; break; case thread_type_generate_thumbnail: job_queue = &external_job_queue; break; case thread_type_config_load: job_queue = &cpu_job_queue; break; case thread_type_page_process: job_queue = &cpu_job_queue; break; default: assert(false); } } if(job_queue->potential_worker_threads==0) return false; e.queue_enter_time = now_ms(); ScopedLock sl(mtx); job_queue->add(e); return true; } void JobScheduler_impl::cancel_queued_jobs(JobQueue &jq, job_exit_t job_exit) { while(!jq.empty()) { exit_set.push_back(std::make_pair(jq.back(),job_exit)); jq.pop_back(); } } bool JobScheduler_impl::submit(start_routine_t start_routine, finish_routine_t finish_callback, void *state, thread_type_t thread_type, int priority, uint64_t start_deadline) { JobEntry e; memset(&e, 0, sizeof(JobEntry)); e.start_routine = start_routine; e.finish_callback = finish_callback; e.state = state; e.is_io_job = false; e.start_deadline = start_deadline; e.is_io_write_job = false; e.initial_priority = priority; return submit(thread_type,e); } bool JobScheduler_impl::submit_io(start_routine_t start_routine, finish_routine_t finish_callback, FileState *fstate, thread_type_t thread_type, int priority, bool is_write_job, uint64_t start_deadline) { JobEntry e; memset(&e, 0, sizeof(JobEntry)); e.start_routine = start_routine; e.finish_callback = finish_callback; e.state = fstate; e.is_io_job = true; e.start_deadline = start_deadline; e.is_io_write_job = is_write_job; e.initial_priority = priority; return submit(thread_type,e); } bool JobScheduler_impl::are_io_write_jobs_running() const { ScopedLock sl(mtx); return num_io_write_jobs_running != 0; } void JobScheduler_impl::cancel_file_read_jobs(const BigFile *bf) { ScopedLock sl(mtx); for(JobQueue::iterator iter = io_job_queue.begin(); iter!=io_job_queue.end(); ) { if(iter->is_io_job && !iter->is_io_write_job) { const FileState *fstate = reinterpret_cast<const FileState*>(iter->state); if(fstate->m_bigfile==bf) { exit_set.push_back(std::make_pair(*iter,job_exit_cancelled)); iter = io_job_queue.erase(iter); continue; } } ++iter; } } bool JobScheduler_impl::is_reading_file(const BigFile *bf) { //The old thread stuff tested explicitly if the start_routine was //readwriteWrapper_r() in BigFile.cpp but that is fragile. Besides, //we have the 'is_io_write_job' field. ScopedLock sl(mtx); for(const auto &e : io_job_queue) { if(e.is_io_job && !e.is_io_write_job) { const FileState *fstate = reinterpret_cast<const FileState*>(e.state); if(fstate->m_bigfile==bf) return true; } } for(const auto &e : running_set) { if(e.is_io_job && !e.is_io_write_job) { const FileState *fstate = reinterpret_cast<const FileState*>(e.state); if(fstate->m_bigfile==bf) return true; } } return false; } void JobScheduler_impl::cancel_all_jobs_for_shutdown() { ScopedLock sl(mtx); cancel_queued_jobs(coordinator_job_queue,job_exit_program_exit); cancel_queued_jobs(cpu_job_queue,job_exit_program_exit); cancel_queued_jobs(summary_job_queue,job_exit_program_exit); cancel_queued_jobs(io_job_queue,job_exit_program_exit); cancel_queued_jobs(external_job_queue,job_exit_program_exit); cancel_queued_jobs(file_meta_job_queue,job_exit_program_exit); cancel_queued_jobs(merge_job_queue,job_exit_program_exit); } unsigned JobScheduler_impl::num_queued_jobs() const { ScopedLock sl(mtx); return cpu_job_queue.size() + summary_job_queue.size() + io_job_queue.size() + external_job_queue.size() + file_meta_job_queue.size() + merge_job_queue.size(); } void JobScheduler_impl::cleanup_finished_jobs() { ExitSet es; ScopedLock sl(mtx); es.swap(exit_set); sl.unlock(); for(auto e : es) { e.first.finish_time = now_ms(); if(e.first.finish_callback) e.first.finish_callback(e.first.state,e.second); e.first.exit_time = now_ms(); JobTypeStatistics &s = job_statistics[e.first.thread_type]; s.job_count++; s.queue_time += e.first.start_time - e.first.queue_enter_time; s.running_time += e.first.stop_time - e.first.start_time; s.done_time += e.first.finish_time - e.first.stop_time; s.cleanup_time += e.first.exit_time - e.first.finish_time; } } static JobDigest job_entry_to_job_digest(const JobEntry& je, JobDigest::job_state_t job_state) { JobDigest jd; jd.thread_type = je.thread_type; jd.start_routine = je.start_routine; jd.finish_callback = je.finish_callback; jd.job_state = job_state; jd.start_deadline = je.start_deadline; jd.queue_enter_time = je.queue_enter_time; jd.start_time = je.start_time; jd.stop_time = je.stop_time; return jd; } std::vector<JobDigest> JobScheduler_impl::query_job_digests() const { std::vector<JobDigest> v; ScopedLock sl(mtx); //v.reserve(cpu_job_queue.size() + io_job_queue.size() + external_job_queue.size() + file_meta_job_queue.size() + running_set().size() + exit_set().size()); for(const auto &je : coordinator_job_queue) v.push_back(job_entry_to_job_digest(je,JobDigest::job_state_queued)); for(const auto &je : cpu_job_queue) v.push_back(job_entry_to_job_digest(je,JobDigest::job_state_queued)); for(const auto &je : summary_job_queue) v.push_back(job_entry_to_job_digest(je,JobDigest::job_state_queued)); for(const auto &je : io_job_queue) v.push_back(job_entry_to_job_digest(je,JobDigest::job_state_queued)); for(const auto &je : external_job_queue) v.push_back(job_entry_to_job_digest(je,JobDigest::job_state_queued)); for(const auto &je : file_meta_job_queue) v.push_back(job_entry_to_job_digest(je,JobDigest::job_state_queued)); for(const auto &je : merge_job_queue) v.push_back(job_entry_to_job_digest(je,JobDigest::job_state_queued)); for(const auto &je : running_set) v.push_back(job_entry_to_job_digest(je,JobDigest::job_state_running)); for(const auto &je : exit_set) v.push_back(job_entry_to_job_digest(je.first,JobDigest::job_state_stopped)); return v; } std::map<thread_type_t,JobTypeStatistics> JobScheduler_impl::query_job_statistics(bool clear) { if(clear) { std::map<thread_type_t,JobTypeStatistics> tmp; tmp.swap(job_statistics); return tmp; } else return job_statistics; } //////////////////////////////////////////////////////////////////////////////// // bridge JobScheduler::JobScheduler() : impl(0) { } JobScheduler::~JobScheduler() { delete impl; impl = 0; } bool JobScheduler::initialize(unsigned num_coordinator_threads, unsigned num_cpu_threads, unsigned num_summary_threads, unsigned num_io_threads, unsigned num_external_threads, unsigned num_file_meta_threads, unsigned num_merge_threads, job_done_notify_t job_done_notify) { assert(!impl); impl = new JobScheduler_impl(num_coordinator_threads,num_cpu_threads,num_summary_threads,num_io_threads,num_external_threads,num_file_meta_threads,num_merge_threads,job_done_notify); return true; } void JobScheduler::finalize() { assert(impl); delete impl; impl = 0; } bool JobScheduler::submit(start_routine_t start_routine, finish_routine_t finish_callback, void *state, thread_type_t thread_type, int priority, uint64_t start_deadline) { if(impl) return impl->submit(start_routine,finish_callback,state,thread_type,priority,start_deadline); else return false; } bool JobScheduler::submit_io(start_routine_t start_routine, finish_routine_t finish_callback, FileState *fstate, thread_type_t thread_type, int priority, bool is_write_job, uint64_t start_deadline) { if(impl) return impl->submit_io(start_routine,finish_callback,fstate,thread_type,priority,is_write_job,start_deadline); else return false; } bool JobScheduler::are_io_write_jobs_running() const { if(impl) return impl->are_io_write_jobs_running(); else return false; } void JobScheduler::cancel_file_read_jobs(const BigFile *bf) { if(impl) impl->cancel_file_read_jobs(bf); } //void nice page for html and administation() bool JobScheduler::is_reading_file(const BigFile *bf) { if(impl) return impl->is_reading_file(bf); else return false; } void JobScheduler::allow_new_jobs() { if(impl) impl->allow_new_jobs(); } void JobScheduler::disallow_new_jobs() { if(impl) impl->disallow_new_jobs(); } bool JobScheduler::are_new_jobs_allowed() const { if(impl) return impl->are_new_jobs_allowed(); else return false; } void JobScheduler::cancel_all_jobs_for_shutdown() { if(impl) impl->cancel_all_jobs_for_shutdown(); } unsigned JobScheduler::num_queued_jobs() const { if(impl) return impl->num_queued_jobs(); else return 0; } void JobScheduler::cleanup_finished_jobs() { if(impl) impl->cleanup_finished_jobs(); } std::vector<JobDigest> JobScheduler::query_job_digests() const { if(impl) return impl->query_job_digests(); else return std::vector<JobDigest>(); } std::map<thread_type_t,JobTypeStatistics> JobScheduler::query_job_statistics(bool clear) { if(impl) return impl->query_job_statistics(clear); else return std::map<thread_type_t,JobTypeStatistics>(); } //////////////////////////////////////////////////////////////////////////////// // The global one-and-only scheduler JobScheduler g_jobScheduler;
30.191489
270
0.712639
[ "vector" ]
160e19bb13e39c8664aaa888b0f8787d3b55fb59
307
cpp
C++
Dynamic Programming/Suffix_prefix dp/Max Product Subarray.cpp
cenation092/InterviewBit-Solutions
ac4510a10d965fb681f7b3c80990407e18bc2668
[ "MIT" ]
7
2019-06-29T08:57:07.000Z
2021-02-13T06:43:40.000Z
Dynamic Programming/Suffix_prefix dp/Max Product Subarray.cpp
cenation092/InterviewBit-Solutions
ac4510a10d965fb681f7b3c80990407e18bc2668
[ "MIT" ]
null
null
null
Dynamic Programming/Suffix_prefix dp/Max Product Subarray.cpp
cenation092/InterviewBit-Solutions
ac4510a10d965fb681f7b3c80990407e18bc2668
[ "MIT" ]
3
2020-06-17T04:26:26.000Z
2021-02-12T04:51:40.000Z
int Solution::maxProduct(const vector<int> &A) { int Min = A[0], Max = A[0]; int Ans = A[0]; for( int i = 1; i < A.size(); i++ ){ if( A[i] < 0 )swap(Min, Max); Min = min( A[i], Min*A[i] ); Max = max( A[i], Max*A[i] ); Ans = max( Ans, Max); } return Ans; }
27.909091
48
0.436482
[ "vector" ]
1617c2cae2df26c413ef993101334c55b9276ec3
37,830
cpp
C++
03_Tutorial/T02_XMCocos2D-v3/Source/PhysicsTest/PhysicsTest.cpp
mcodegeeks/OpenKODE-Framework
d4382d781da7f488a0e7667362a89e8e389468dd
[ "MIT" ]
2
2017-08-03T07:15:00.000Z
2018-06-18T10:32:53.000Z
03_Tutorial/T02_XMCocos2D-v3/Source/PhysicsTest/PhysicsTest.cpp
mcodegeeks/OpenKODE-Framework
d4382d781da7f488a0e7667362a89e8e389468dd
[ "MIT" ]
null
null
null
03_Tutorial/T02_XMCocos2D-v3/Source/PhysicsTest/PhysicsTest.cpp
mcodegeeks/OpenKODE-Framework
d4382d781da7f488a0e7667362a89e8e389468dd
[ "MIT" ]
2
2019-03-04T22:57:42.000Z
2020-03-06T01:32:26.000Z
#include "PhysicsTest.h" #include <cmath> #include "../testResource.h" USING_NS_CC; namespace { static std::function<Layer*()> createFunctions[] = { CL(PhysicsDemoLogoSmash), CL(PhysicsDemoPyramidStack), CL(PhysicsDemoClickAdd), CL(PhysicsDemoRayCast), CL(PhysicsDemoJoints), CL(PhysicsDemoActions), CL(PhysicsDemoPump), CL(PhysicsDemoOneWayPlatform), CL(PhysicsDemoSlice), }; static int sceneIdx=-1; #define MAX_LAYER (sizeof(createFunctions) / sizeof(createFunctions[0])) static Layer* next() { sceneIdx++; sceneIdx = sceneIdx % MAX_LAYER; auto layer = (createFunctions[sceneIdx])(); layer->init(); layer->autorelease(); return layer; } static Layer* back() { sceneIdx--; int total = MAX_LAYER; if( sceneIdx < 0 ) sceneIdx += total; auto layer = (createFunctions[sceneIdx])(); layer->init(); layer->autorelease(); return layer; } static Layer* restart() { auto layer = (createFunctions[sceneIdx])(); layer->init(); layer->autorelease(); return layer; } static const Color4F STATIC_COLOR(1.0f, 0.0f, 0.0f, 1.0f); static const int DRAG_BODYS_TAG = 0x80; } void PhysicsTestScene::runThisTest() { #ifdef CC_USE_PHYSICS sceneIdx = -1; addChild(next()); Director::getInstance()->replaceScene(this); #else #endif } void PhysicsTestScene::toggleDebug() { _debugDraw = !_debugDraw; getPhysicsWorld()->setDebugDrawMask(_debugDraw ? PhysicsWorld::DEBUGDRAW_ALL : PhysicsWorld::DEBUGDRAW_NONE); } PhysicsDemo::PhysicsDemo() : _scene(nullptr) , _spriteTexture(nullptr) , _ball(nullptr) { } PhysicsDemo::~PhysicsDemo() { } std::string PhysicsDemo::title() { return "PhysicsTest"; } std::string PhysicsDemo::subtitle() { return ""; } void PhysicsDemo::restartCallback(Object* sender) { auto s = new PhysicsTestScene(); s->addChild( restart() ); Director::getInstance()->replaceScene(s); s->release(); } void PhysicsDemo::nextCallback(Object* sender) { auto s = new PhysicsTestScene(); s->addChild( next() ); Director::getInstance()->replaceScene(s); s->release(); } void PhysicsDemo::backCallback(Object* sender) { auto s = new PhysicsTestScene(); s->addChild( back() ); Director::getInstance()->replaceScene(s); s->release(); } void PhysicsDemo::onEnter() { BaseTest::onEnter(); _scene = dynamic_cast<PhysicsTestScene*>(this->getParent()); _spriteTexture = SpriteBatchNode::create("Images/grossini_dance_atlas.png", 100)->getTexture(); #ifdef CC_USE_PHYSICS // menu for debug layer MenuItemFont::setFontSize(18); auto item = MenuItemFont::create("Toggle debug", CC_CALLBACK_1(PhysicsDemo::toggleDebugCallback, this)); auto menu = Menu::create(item, NULL); this->addChild(menu); menu->setPosition(Point(VisibleRect::right().x-50, VisibleRect::top().y-10)); #else #endif } Sprite* PhysicsDemo::addGrossiniAtPosition(Point p, float scale/* = 1.0*/) { #ifdef CC_USE_PHYSICS CCLOG("Add sprite %0.2f x %02.f",p.x,p.y); int posx, posy; posx = CCRANDOM_0_1() * 200.0f; posy = CCRANDOM_0_1() * 200.0f; posx = (posx % 4) * 85; posy = (posy % 3) * 121; auto sp = Sprite::createWithTexture(_spriteTexture, Rect(posx, posy, 85, 121)); sp->setScale(scale); sp->setPhysicsBody(PhysicsBody::createBox(Size(48.0f * scale, 108.0f * scale))); this->addChild(sp); sp->setPosition(p); return sp; #endif } void PhysicsDemo::toggleDebugCallback(Object* sender) { #ifdef CC_USE_PHYSICS if (_scene != nullptr) { _scene->toggleDebug(); } #endif } PhysicsDemoClickAdd::~PhysicsDemoClickAdd() { Device::setAccelerometerEnabled(false); } void PhysicsDemoClickAdd::onEnter() { PhysicsDemo::onEnter(); #ifdef CC_USE_PHYSICS auto touchListener = EventListenerTouchAllAtOnce::create(); touchListener->onTouchesEnded = CC_CALLBACK_2(PhysicsDemoClickAdd::onTouchesEnded, this); m_pEventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); Device::setAccelerometerEnabled(true); auto accListener = EventListenerAcceleration::create(CC_CALLBACK_2(PhysicsDemoClickAdd::onAcceleration, this)); m_pEventDispatcher->addEventListenerWithSceneGraphPriority(accListener, this); auto node = Node::create(); node->setPhysicsBody(PhysicsBody::createEdgeBox(VisibleRect::getVisibleRect().size)); node->setPosition(VisibleRect::center()); this->addChild(node); addGrossiniAtPosition(VisibleRect::center()); #else auto label = LabelTTF::create("Should define CC_USE_BOX2D or CC_USE_CHIPMUNK\n to run this test case", "Arial", 18); auto size = Director::getInstance()->getWinSize(); label->setPosition(Point(size.width/2, size.height/2)); addChild(label); #endif } std::string PhysicsDemoClickAdd::subtitle() { return "multi touch to add grossini"; } void PhysicsDemoClickAdd::onTouchesEnded(const std::vector<Touch*>& touches, Event* event) { //Add a new body/atlas sprite at the touched location for( auto &touch: touches) { auto location = touch->getLocation(); addGrossiniAtPosition( location ); } } void PhysicsDemoClickAdd::onAcceleration(Acceleration* acc, Event* event) { #ifdef CC_USE_PHYSICS static float prevX=0, prevY=0; #define kFilterFactor 0.05f float accelX = (float) acc->x * kFilterFactor + (1- kFilterFactor)*prevX; float accelY = (float) acc->y * kFilterFactor + (1- kFilterFactor)*prevY; prevX = accelX; prevY = accelY; auto v = Point( accelX, accelY); v = v * 200; if(_scene != nullptr) { _scene->getPhysicsWorld()->setGravity(v); } #endif } namespace { static const int logo_width = 188; static const int logo_height = 35; static const int logo_row_length = 24; static const char logo_image[] = { 15,-16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,7,-64,15,63,-32,-2,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,31,-64,15,127,-125,-1,-128,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,127,-64,15,127,15,-1,-64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,-1,-64,15,-2, 31,-1,-64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,-1,-64,0,-4,63,-1,-32,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,1,-1,-64,15,-8,127,-1,-32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,-1,-64,0,-8,-15,-1,-32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,-31,-1,-64,15,-8,-32, -1,-32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,7,-15,-1,-64,9,-15,-32,-1,-32,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,31,-15,-1,-64,0,-15,-32,-1,-32,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,63,-7,-1,-64,9,-29,-32,127,-61,-16,63,15,-61,-1,-8,31,-16,15,-8,126,7,-31, -8,31,-65,-7,-1,-64,9,-29,-32,0,7,-8,127,-97,-25,-1,-2,63,-8,31,-4,-1,15,-13, -4,63,-1,-3,-1,-64,9,-29,-32,0,7,-8,127,-97,-25,-1,-2,63,-8,31,-4,-1,15,-13, -2,63,-1,-3,-1,-64,9,-29,-32,0,7,-8,127,-97,-25,-1,-1,63,-4,63,-4,-1,15,-13, -2,63,-33,-1,-1,-32,9,-25,-32,0,7,-8,127,-97,-25,-1,-1,63,-4,63,-4,-1,15,-13, -1,63,-33,-1,-1,-16,9,-25,-32,0,7,-8,127,-97,-25,-1,-1,63,-4,63,-4,-1,15,-13, -1,63,-49,-1,-1,-8,9,-57,-32,0,7,-8,127,-97,-25,-8,-1,63,-2,127,-4,-1,15,-13, -1,-65,-49,-1,-1,-4,9,-57,-32,0,7,-8,127,-97,-25,-8,-1,63,-2,127,-4,-1,15,-13, -1,-65,-57,-1,-1,-2,9,-57,-32,0,7,-8,127,-97,-25,-8,-1,63,-2,127,-4,-1,15,-13, -1,-1,-57,-1,-1,-1,9,-57,-32,0,7,-1,-1,-97,-25,-8,-1,63,-1,-1,-4,-1,15,-13,-1, -1,-61,-1,-1,-1,-119,-57,-32,0,7,-1,-1,-97,-25,-8,-1,63,-1,-1,-4,-1,15,-13,-1, -1,-61,-1,-1,-1,-55,-49,-32,0,7,-1,-1,-97,-25,-8,-1,63,-1,-1,-4,-1,15,-13,-1, -1,-63,-1,-1,-1,-23,-49,-32,127,-57,-1,-1,-97,-25,-1,-1,63,-1,-1,-4,-1,15,-13, -1,-1,-63,-1,-1,-1,-16,-49,-32,-1,-25,-1,-1,-97,-25,-1,-1,63,-33,-5,-4,-1,15, -13,-1,-1,-64,-1,-9,-1,-7,-49,-32,-1,-25,-8,127,-97,-25,-1,-1,63,-33,-5,-4,-1, 15,-13,-1,-1,-64,-1,-13,-1,-32,-49,-32,-1,-25,-8,127,-97,-25,-1,-2,63,-49,-13, -4,-1,15,-13,-1,-1,-64,127,-7,-1,-119,-17,-15,-1,-25,-8,127,-97,-25,-1,-2,63, -49,-13,-4,-1,15,-13,-3,-1,-64,127,-8,-2,15,-17,-1,-1,-25,-8,127,-97,-25,-1, -8,63,-49,-13,-4,-1,15,-13,-3,-1,-64,63,-4,120,0,-17,-1,-1,-25,-8,127,-97,-25, -8,0,63,-57,-29,-4,-1,15,-13,-4,-1,-64,63,-4,0,15,-17,-1,-1,-25,-8,127,-97, -25,-8,0,63,-57,-29,-4,-1,-1,-13,-4,-1,-64,31,-2,0,0,103,-1,-1,-57,-8,127,-97, -25,-8,0,63,-57,-29,-4,-1,-1,-13,-4,127,-64,31,-2,0,15,103,-1,-1,-57,-8,127, -97,-25,-8,0,63,-61,-61,-4,127,-1,-29,-4,127,-64,15,-8,0,0,55,-1,-1,-121,-8, 127,-97,-25,-8,0,63,-61,-61,-4,127,-1,-29,-4,63,-64,15,-32,0,0,23,-1,-2,3,-16, 63,15,-61,-16,0,31,-127,-127,-8,31,-1,-127,-8,31,-128,7,-128,0,0 }; static inline int get_pixel(int x, int y) { return (logo_image[(x>>3) + y*logo_row_length]>>(~x&0x7)) & 1; } static inline float fkdRand(void) { return kdRand()/KD_RAND_MAX; } } Sprite* PhysicsDemo::makeBall(Point point, float radius, PhysicsMaterial material) { Sprite* ball = nullptr; if (_ball != nullptr) { ball = Sprite::createWithTexture(_ball->getTexture()); }else { ball = Sprite::create("Images/ball.png"); } ball->setScale(0.13f * radius); auto body = PhysicsBody::createCircle(radius, material); ball->setPhysicsBody(body); ball->setPosition(Point(point.x, point.y)); return ball; } Sprite* PhysicsDemo::makeBox(Point point, Size size, PhysicsMaterial material) { auto box = CCRANDOM_0_1() > 0.5f ? Sprite::create("Images/YellowSquare.png") : Sprite::create("Images/CyanSquare.png"); box->setScaleX(size.width/100.0f); box->setScaleY(size.height/100.0f); auto body = PhysicsBody::createBox(size); box->setPhysicsBody(body); box->setPosition(Point(point.x, point.y)); return box; } Sprite* PhysicsDemo::makeTriangle(Point point, Size size, PhysicsMaterial material) { auto triangle = CCRANDOM_0_1() > 0.5f ? Sprite::create("Images/YellowTriangle.png") : Sprite::create("Images/CyanTriangle.png"); if(size.height == 0) { triangle->setScale(size.width/100.0f); }else { triangle->setScaleX(size.width/50.0f); triangle->setScaleY(size.height/43.5f); } Point vers[] = { Point(0, size.height/2), Point(size.width/2, -size.height/2), Point(-size.width/2, -size.height/2)}; auto body = PhysicsBody::createPolygon(vers, 3); triangle->setPhysicsBody(body); triangle->setPosition(Point(point.x, point.y)); return triangle; } bool PhysicsDemo::onTouchBegan(Touch* touch, Event* event) { auto location = touch->getLocation(); Array* arr = _scene->getPhysicsWorld()->getShapes(location); PhysicsBody* body = nullptr; for (Object* obj : *arr) { if ((dynamic_cast<PhysicsShape*>(obj)->getBody()->getTag() & DRAG_BODYS_TAG) != 0) { body = dynamic_cast<PhysicsShape*>(obj)->getBody(); break; } } if (body != nullptr) { Node* mouse = Node::create(); mouse->setPhysicsBody(PhysicsBody::create(PHYSICS_INFINITY, PHYSICS_INFINITY)); mouse->getPhysicsBody()->setDynamic(false); mouse->setPosition(location); this->addChild(mouse); PhysicsJointPin* joint = PhysicsJointPin::construct(mouse->getPhysicsBody(), body, location); joint->setMaxForce(5000.0f * body->getMass()); _scene->getPhysicsWorld()->addJoint(joint); _mouses.insert(std::make_pair(touch->getID(), mouse)); return true; } return false; } void PhysicsDemo::onTouchMoved(Touch* touch, Event* event) { auto it = _mouses.find(touch->getID()); if (it != _mouses.end()) { it->second->getPhysicsBody()->setVelocity((touch->getLocation() - it->second->getPosition()) * 60.0f); it->second->setPosition(touch->getLocation()); } } void PhysicsDemo::onTouchEnded(Touch* touch, Event* event) { auto it = _mouses.find(touch->getID()); if (it != _mouses.end()) { this->removeChild(it->second); _mouses.erase(it); } } void PhysicsDemoLogoSmash::onEnter() { PhysicsDemo::onEnter(); _scene->getPhysicsWorld()->setGravity(Point(0, 0)); _ball = SpriteBatchNode::create("Images/ball.png", sizeof(logo_image)/sizeof(logo_image[0])); addChild(_ball); for (int y = 0; y < logo_height; ++y) { for (int x = 0; x < logo_width; ++x) { if (get_pixel(x, y)) { float x_jitter = 0.05*fkdRand(); float y_jitter = 0.05*fkdRand(); Node* ball = makeBall(Point(2*(x - logo_width/2 + x_jitter) + VisibleRect::getVisibleRect().size.width/2, 2*(logo_height-y + y_jitter) + VisibleRect::getVisibleRect().size.height/2 - logo_height/2), 0.95f, PhysicsMaterial(0.01f, 0.0f, 0.0f)); ball->getPhysicsBody()->setMass(1.0); ball->getPhysicsBody()->setMoment(PHYSICS_INFINITY); _ball->addChild(ball); } } } auto bullet = makeBall(Point(400, 0), 10, PhysicsMaterial(PHYSICS_INFINITY, 0, 0)); bullet->getPhysicsBody()->setVelocity(Point(400, 0)); bullet->setPosition(Point(-1000, VisibleRect::getVisibleRect().size.height/2)); _ball->addChild(bullet); } std::string PhysicsDemoLogoSmash::title() { return "Logo Smash"; }void PhysicsDemoPyramidStack::onEnter() { PhysicsDemo::onEnter(); auto touchListener = EventListenerTouchOneByOne::create(); touchListener->onTouchBegan = CC_CALLBACK_2(PhysicsDemoPyramidStack::onTouchBegan, this); touchListener->onTouchMoved = CC_CALLBACK_2(PhysicsDemoPyramidStack::onTouchMoved, this); touchListener->onTouchEnded = CC_CALLBACK_2(PhysicsDemoPyramidStack::onTouchEnded, this); m_pEventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); auto node = Node::create(); node->setPhysicsBody(PhysicsBody::createEdgeSegment(VisibleRect::leftBottom() + Point(0, 50), VisibleRect::rightBottom() + Point(0, 50))); this->addChild(node); auto ball = Sprite::create("Images/ball.png"); ball->setScale(1); ball->setPhysicsBody(PhysicsBody::createCircle(10)); ball->setPosition(VisibleRect::bottom() + Point(0, 60)); this->addChild(ball); for(int i=0; i<14; i++) { for(int j=0; j<=i; j++) { auto sp = addGrossiniAtPosition(VisibleRect::bottom() + Point((i/2 - j) * 11, (14 - i) * 23 + 100), 0.2f); sp->getPhysicsBody()->setTag(DRAG_BODYS_TAG); } } } std::string PhysicsDemoPyramidStack::title() { return "Pyramid Stack"; } PhysicsDemoRayCast::PhysicsDemoRayCast() : _angle(0.0f) , _node(nullptr) , _mode(0) {} void PhysicsDemoRayCast::onEnter() { PhysicsDemo::onEnter(); auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesEnded = CC_CALLBACK_2(PhysicsDemoRayCast::onTouchesEnded, this); m_pEventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); _scene->getPhysicsWorld()->setGravity(Point::ZERO); auto node = DrawNode::create(); node->setPhysicsBody(PhysicsBody::createEdgeSegment(VisibleRect::leftBottom() + Point(0, 50), VisibleRect::rightBottom() + Point(0, 50))); node->drawSegment(VisibleRect::leftBottom() + Point(0, 50), VisibleRect::rightBottom() + Point(0, 50), 1, STATIC_COLOR); this->addChild(node); MenuItemFont::setFontSize(18); auto item = MenuItemFont::create("Change Mode(any)", CC_CALLBACK_1(PhysicsDemoRayCast::changeModeCallback, this)); auto menu = Menu::create(item, NULL); this->addChild(menu); menu->setPosition(Point(VisibleRect::left().x+100, VisibleRect::top().y-10)); scheduleUpdate(); } void PhysicsDemoRayCast::changeModeCallback(Object* sender) { _mode = (_mode + 1) % 3; switch (_mode) { case 0: ((MenuItemFont*)sender)->setString("Change Mode(any)"); break; case 1: ((MenuItemFont*)sender)->setString("Change Mode(nearest)"); break; case 2: ((MenuItemFont*)sender)->setString("Change Mode(multiple)"); break; default: break; } } bool PhysicsDemoRayCast::anyRay(PhysicsWorld& world, const PhysicsRayCastInfo& info, void* data) { *((Point*)data) = info.contact; return false; } void PhysicsDemoRayCast::update(float delta) { float L = 150.0f; Point point1 = VisibleRect::center(); Point d(L * kdCosf(_angle), L * kdSinf(_angle)); Point point2 = point1 + d; removeChild(_node); _node = DrawNode::create(); switch (_mode) { case 0: { Point point3 = point2; auto func = CC_CALLBACK_3(PhysicsDemoRayCast::anyRay, this); _scene->getPhysicsWorld()->rayCast(func, point1, point2, &point3); _node->drawSegment(point1, point3, 1, STATIC_COLOR); if (point2 != point3) { _node->drawDot(point3, 2, Color4F(1.0f, 1.0f, 1.0f, 1.0f)); } addChild(_node); break; } case 1: { Point point3 = point2; float friction = 1.0f; PhysicsRayCastCallbackFunc func = [&point3, &friction](PhysicsWorld& world, const PhysicsRayCastInfo& info, void* data)->bool { if (friction > info.fraction) { point3 = info.contact; friction = info.fraction; } return true; }; _scene->getPhysicsWorld()->rayCast(func, point1, point2, nullptr); _node->drawSegment(point1, point3, 1, STATIC_COLOR); if (point2 != point3) { _node->drawDot(point3, 2, Color4F(1.0f, 1.0f, 1.0f, 1.0f)); } addChild(_node); break; } case 2: { #define MAX_MULTI_RAYCAST_NUM 5 Point points[MAX_MULTI_RAYCAST_NUM]; int num = 0; PhysicsRayCastCallbackFunc func = [&points, &num](PhysicsWorld& world, const PhysicsRayCastInfo& info, void* data)->bool { if (num < MAX_MULTI_RAYCAST_NUM) { points[num++] = info.contact; } return true; }; _scene->getPhysicsWorld()->rayCast(func, point1, point2, nullptr); _node->drawSegment(point1, point2, 1, STATIC_COLOR); for (int i = 0; i < num; ++i) { _node->drawDot(points[i], 2, Color4F(1.0f, 1.0f, 1.0f, 1.0f)); } addChild(_node); break; } default: break; } _angle += 0.25f * KD_PI_F / 180.0f; } void PhysicsDemoRayCast::onTouchesEnded(const std::vector<Touch*>& touches, Event* event) { //Add a new body/atlas sprite at the touched location for( auto &touch: touches) { auto location = touch->getLocation(); float r = CCRANDOM_0_1(); if (r < 1.0f/3.0f) { addChild(makeBall(location, 5 + CCRANDOM_0_1()*10)); }else if(r < 2.0f/3.0f) { addChild(makeBox(location, Size(10 + CCRANDOM_0_1()*15, 10 + CCRANDOM_0_1()*15))); }else { addChild(makeTriangle(location, Size(10 + CCRANDOM_0_1()*20, 10 + CCRANDOM_0_1()*20))); } } } std::string PhysicsDemoRayCast::title() { return "Ray Cast"; } void PhysicsDemoJoints::onEnter() { PhysicsDemo::onEnter(); _scene->toggleDebug(); auto listener = EventListenerTouchOneByOne::create(); listener->onTouchBegan = CC_CALLBACK_2(PhysicsDemoJoints::onTouchBegan, this); listener->onTouchMoved = CC_CALLBACK_2(PhysicsDemoJoints::onTouchMoved, this); listener->onTouchEnded = CC_CALLBACK_2(PhysicsDemoJoints::onTouchEnded, this); m_pEventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); //_scene->getPhysicsWorld()->setGravity(Point::ZERO); float width = (VisibleRect::getVisibleRect().size.width - 10) / 4; float height = (VisibleRect::getVisibleRect().size.height - 50) / 4; Node* node = Node::create(); PhysicsBody* box = PhysicsBody::create(); node->setPhysicsBody(box); box->setDynamic(false); node->setPosition(Point::ZERO); this->addChild(node); for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { Point offset(VisibleRect::leftBottom().x + 5 + j * width + width/2, VisibleRect::leftBottom().y + 50 + i * height + height/2); box->addShape(PhysicsShapeEdgeBox::create(Size(width, height), PHYSICSSHAPE_MATERIAL_DEFAULT, 1, offset)); switch (i*4 + j) { case 0: { auto sp1 = makeBall(offset - Point(30, 0), 10); sp1->getPhysicsBody()->setTag(DRAG_BODYS_TAG); auto sp2 = makeBall(offset + Point(30, 0), 10); sp2->getPhysicsBody()->setTag(DRAG_BODYS_TAG); PhysicsJointPin* joint = PhysicsJointPin::construct(sp1->getPhysicsBody(), sp2->getPhysicsBody(), offset); _scene->getPhysicsWorld()->addJoint(joint); this->addChild(sp1); this->addChild(sp2); break; } case 1: { auto sp1 = makeBall(offset - Point(30, 0), 10); sp1->getPhysicsBody()->setTag(DRAG_BODYS_TAG); auto sp2 = makeBox(offset + Point(30, 0), Size(30, 10)); sp2->getPhysicsBody()->setTag(DRAG_BODYS_TAG); PhysicsJointFixed* joint = PhysicsJointFixed::construct(sp1->getPhysicsBody(), sp2->getPhysicsBody(), offset); _scene->getPhysicsWorld()->addJoint(joint); this->addChild(sp1); this->addChild(sp2); break; } case 2: { auto sp1 = makeBall(offset - Point(30, 0), 10); sp1->getPhysicsBody()->setTag(DRAG_BODYS_TAG); auto sp2 = makeBox(offset + Point(30, 0), Size(30, 10)); sp2->getPhysicsBody()->setTag(DRAG_BODYS_TAG); PhysicsJointDistance* joint = PhysicsJointDistance::construct(sp1->getPhysicsBody(), sp2->getPhysicsBody(), Point::ZERO, Point::ZERO); _scene->getPhysicsWorld()->addJoint(joint); this->addChild(sp1); this->addChild(sp2); break; } case 3: { auto sp1 = makeBall(offset - Point(30, 0), 10); sp1->getPhysicsBody()->setTag(DRAG_BODYS_TAG); auto sp2 = makeBox(offset + Point(30, 0), Size(30, 10)); sp2->getPhysicsBody()->setTag(DRAG_BODYS_TAG); PhysicsJointLimit* joint = PhysicsJointLimit::construct(sp1->getPhysicsBody(), sp2->getPhysicsBody(), Point::ZERO, Point::ZERO); joint->setMin(30.0f); joint->setMax(60.0f); _scene->getPhysicsWorld()->addJoint(joint); this->addChild(sp1); this->addChild(sp2); break; } default: break; } } } } std::string PhysicsDemoJoints::title() { return "Joints"; } void PhysicsDemoActions::onEnter() { PhysicsDemo::onEnter(); auto touchListener = EventListenerTouchOneByOne::create(); touchListener->onTouchBegan = CC_CALLBACK_2(PhysicsDemoActions::onTouchBegan, this); touchListener->onTouchMoved = CC_CALLBACK_2(PhysicsDemoActions::onTouchMoved, this); touchListener->onTouchEnded = CC_CALLBACK_2(PhysicsDemoActions::onTouchEnded, this); m_pEventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); auto node = Node::create(); node->setPhysicsBody(PhysicsBody::createEdgeBox(VisibleRect::getVisibleRect().size)); node->setPosition(VisibleRect::center()); this->addChild(node); Sprite* sp1 = addGrossiniAtPosition(VisibleRect::center()); Sprite* sp2 = addGrossiniAtPosition(VisibleRect::left() + Point(50, 0)); Sprite* sp3 = addGrossiniAtPosition(VisibleRect::right() - Point(20, 0)); Sprite* sp4 = addGrossiniAtPosition(VisibleRect::leftTop() + Point(50, -50)); sp4->getPhysicsBody()->setGravityEnable(false); auto actionTo = JumpTo::create(2, Point(100,100), 50, 4); auto actionBy = JumpBy::create(2, Point(300,0), 50, 4); auto actionUp = JumpBy::create(2, Point(0,50), 80, 4); auto actionByBack = actionBy->reverse(); sp1->runAction(RepeatForever::create(actionUp)); sp2->runAction(RepeatForever::create(Sequence::create(actionBy, actionByBack, NULL))); sp3->runAction(actionTo); sp4->runAction(RepeatForever::create(Sequence::create(actionBy->clone(), actionByBack->clone(), NULL))); } std::string PhysicsDemoActions::title() { return "Actions"; } void PhysicsDemoPump::onEnter() { PhysicsDemo::onEnter(); _scene->toggleDebug(); _distance = 0.0f; _rotationV = 0.0f; auto touchListener = EventListenerTouchOneByOne::create(); touchListener->onTouchBegan = CC_CALLBACK_2(PhysicsDemoPump::onTouchBegan, this); touchListener->onTouchMoved = CC_CALLBACK_2(PhysicsDemoPump::onTouchMoved, this); touchListener->onTouchEnded = CC_CALLBACK_2(PhysicsDemoPump::onTouchEnded, this); m_pEventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); scheduleUpdate(); auto node = Node::create(); auto body = PhysicsBody::create(); body->setDynamic(false); PhysicsMaterial staticMaterial(PHYSICS_INFINITY, 0, 0.5f); body->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Point(50, 0), VisibleRect::leftTop() + Point(50, -130), staticMaterial, 2.0f)); body->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Point(190, 0), VisibleRect::leftTop() + Point(100, -50), staticMaterial, 2.0f)); body->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Point(100, -50), VisibleRect::leftTop() + Point(100, -90), staticMaterial, 2.0f)); body->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Point(50, -130), VisibleRect::leftTop() + Point(100, -145), staticMaterial, 2.0f)); body->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Point(100, -145), VisibleRect::leftBottom() + Point(100, 80), staticMaterial, 2.0f)); body->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Point(150, -80), VisibleRect::leftBottom() + Point(150, 80), staticMaterial, 2.0f)); body->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Point(150, -80), VisibleRect::rightTop() + Point(-100, -150), staticMaterial, 2.0f)); body->setCategoryBitmask(0x01); // balls for (int i = 0; i < 6; ++i) { auto ball = makeBall(VisibleRect::leftTop() + Point(75 + CCRANDOM_0_1() * 90, 0), 22, PhysicsMaterial(0.05f, 0.0f, 0.1f)); ball->getPhysicsBody()->setTag(DRAG_BODYS_TAG); addChild(ball); } node->setPhysicsBody(body); this->addChild(node); Point vec[4] = { VisibleRect::leftTop() + Point(102, -148), VisibleRect::leftTop() + Point(148, -161), VisibleRect::leftBottom() + Point(148, 20), VisibleRect::leftBottom() + Point(102, 20) }; auto _world = _scene->getPhysicsWorld(); // small gear auto sgear = Node::create(); auto sgearB = PhysicsBody::createCircle(44); sgear->setPhysicsBody(sgearB); sgear->setPosition(VisibleRect::leftBottom() + Point(125, 0)); this->addChild(sgear); sgearB->setCategoryBitmask(0x04); sgearB->setCollisionBitmask(0x04); sgearB->setTag(1); _world->addJoint(PhysicsJointPin::construct(body, sgearB, sgearB->getPosition())); // big gear auto bgear = Node::create(); auto bgearB = PhysicsBody::createCircle(100); bgear->setPhysicsBody(bgearB); bgear->setPosition(VisibleRect::leftBottom() + Point(275, 0)); this->addChild(bgear); bgearB->setCategoryBitmask(0x04); _world->addJoint(PhysicsJointPin::construct(body, bgearB, bgearB->getPosition())); // pump auto pump = Node::create(); auto center = PhysicsShape::getPolyonCenter(vec, 4); pump->setPosition(center); auto pumpB = PhysicsBody::createPolygon(vec, 4, PHYSICSBODY_MATERIAL_DEFAULT, -center); pump->setPhysicsBody(pumpB); this->addChild(pump); pumpB->setCategoryBitmask(0x02); pumpB->setGravityEnable(false); _world->addJoint(PhysicsJointDistance::construct(pumpB, sgearB, Point(0, 0), Point(0, -44))); // plugger Point seg[] = {VisibleRect::leftTop() + Point(75, -120), VisibleRect::leftBottom() + Point(75, -100)}; Point segCenter = (seg[1] + seg[0])/2; seg[1] -= segCenter; seg[0] -= segCenter; auto plugger = Node::create(); auto pluggerB = PhysicsBody::createEdgeSegment(seg[0], seg[1], PhysicsMaterial(0.01f, 0.0f, 0.5f), 20); pluggerB->setDynamic(true); pluggerB->setMass(30); pluggerB->setMoment(100000); plugger->setPhysicsBody(pluggerB); plugger->setPosition(segCenter); this->addChild(plugger); pluggerB->setCategoryBitmask(0x02); sgearB->setCollisionBitmask(0x04 | 0x01); _world->addJoint(PhysicsJointPin::construct(body, pluggerB, VisibleRect::leftBottom() + Point(75, -90))); _world->addJoint(PhysicsJointDistance::construct(pluggerB, sgearB, pluggerB->world2Local(VisibleRect::leftBottom() + Point(75, 0)), Point(44, 0))); } void PhysicsDemoPump::update(float delta) { for (auto obj : *_scene->getPhysicsWorld()->getAllBodies()) { PhysicsBody* body = dynamic_cast<PhysicsBody*>(obj); if (body->getTag() == DRAG_BODYS_TAG && body->getPosition().y < 0.0f) { body->getNode()->setPosition(VisibleRect::leftTop() + Point(75 + CCRANDOM_0_1() * 90, 0)); body->setVelocity(Point(0, 0)); } } PhysicsBody* gear = _scene->getPhysicsWorld()->getBody(1); if (gear != nullptr) { if (_distance != 0.0f) { _rotationV += _distance/2500.0f; if (_rotationV > 30) _rotationV = 30.0f; if (_rotationV < -30) _rotationV = -30.0f; } gear->setAngularVelocity(_rotationV); _rotationV *= 0.995f; } } bool PhysicsDemoPump::onTouchBegan(Touch* touch, Event* event) { PhysicsDemo::onTouchBegan(touch, event); _distance = touch->getLocation().x - VisibleRect::center().x; return true; } void PhysicsDemoPump::onTouchMoved(Touch* touch, Event* event) { PhysicsDemo::onTouchMoved(touch, event); _distance = touch->getLocation().x - VisibleRect::center().x; } void PhysicsDemoPump::onTouchEnded(Touch* touch, Event* event) { PhysicsDemo::onTouchEnded(touch, event); _distance = 0; } std::string PhysicsDemoPump::title() { return "Pump"; } std::string PhysicsDemoPump::subtitle() { return "touch screen on left or right"; } void PhysicsDemoOneWayPlatform::onEnter() { PhysicsDemo::onEnter(); auto touchListener = EventListenerTouchOneByOne::create(); touchListener->onTouchBegan = CC_CALLBACK_2(PhysicsDemoOneWayPlatform::onTouchBegan, this); touchListener->onTouchMoved = CC_CALLBACK_2(PhysicsDemoOneWayPlatform::onTouchMoved, this); touchListener->onTouchEnded = CC_CALLBACK_2(PhysicsDemoOneWayPlatform::onTouchEnded, this); m_pEventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); auto ground = Node::create(); ground->setPhysicsBody(PhysicsBody::createEdgeSegment(VisibleRect::leftBottom() + Point(0, 50), VisibleRect::rightBottom() + Point(0, 50))); this->addChild(ground); auto platform = makeBox(VisibleRect::center(), Size(200, 50)); platform->getPhysicsBody()->setDynamic(false); this->addChild(platform); auto ball = makeBall(VisibleRect::center() - Point(0, 50), 20); ball->getPhysicsBody()->setVelocity(Point(0, 150)); ball->getPhysicsBody()->setTag(DRAG_BODYS_TAG); ball->getPhysicsBody()->setMass(1.0f); this->addChild(ball); auto contactListener = EventListenerPhysicsContactWithBodies::create(platform->getPhysicsBody(), ball->getPhysicsBody()); contactListener->onContactBegin = CC_CALLBACK_2(PhysicsDemoOneWayPlatform::onContactBegin, this); m_pEventDispatcher->addEventListenerWithSceneGraphPriority(contactListener, this); } bool PhysicsDemoOneWayPlatform::onContactBegin(EventCustom* event, const PhysicsContact& contact) { return contact.getContactData()->normal.y < 0; } std::string PhysicsDemoOneWayPlatform::title() { return "One Way Platform"; } void PhysicsDemoSlice::onEnter() { PhysicsDemo::onEnter(); _scene->toggleDebug(); _sliceTag = 1; auto touchListener = EventListenerTouchOneByOne::create(); touchListener->onTouchBegan = [](Touch* touch, Event* event)->bool{ return true; }; touchListener->onTouchEnded = CC_CALLBACK_2(PhysicsDemoSlice::onTouchEnded, this); m_pEventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); auto ground = Node::create(); ground->setPhysicsBody(PhysicsBody::createEdgeSegment(VisibleRect::leftBottom() + Point(0, 50), VisibleRect::rightBottom() + Point(0, 50))); this->addChild(ground); auto box = Node::create(); Point points[4] = {Point(-100, -100), Point(-100, 100), Point(100, 100), Point(100, -100)}; box->setPhysicsBody(PhysicsBody::createPolygon(points, 4)); box->setPosition(VisibleRect::center()); box->getPhysicsBody()->setTag(_sliceTag); addChild(box); } bool PhysicsDemoSlice::slice(PhysicsWorld &world, const PhysicsRayCastInfo& info, void *data) { if (info.shape->getBody()->getTag() != _sliceTag) { return true; } if (!info.shape->containsPoint(info.start) && !info.shape->containsPoint(info.end)) { Point normal = info.end - info.start; normal = normal.getPerp().normalize(); float dist = info.start.dot(normal); dist = dist; clipPoly(dynamic_cast<PhysicsShapePolygon*>(info.shape), normal, dist); clipPoly(dynamic_cast<PhysicsShapePolygon*>(info.shape), -normal, -dist); info.shape->getBody()->removeFromWorld(); } return true; } void PhysicsDemoSlice::clipPoly(PhysicsShapePolygon* shape, Point normal, float distance) { PhysicsBody* body = shape->getBody(); int count = shape->getPointsCount(); int pointsCount = 0; Point* points = new Point[count + 1]; for (int i=0, j=count-1; i<count; j=i, ++i) { Point a = body->local2World(shape->getPoint(j)); float aDist = a.dot(normal) - distance; if (aDist < 0.0f) { points[pointsCount] = a; ++pointsCount; } Point b = body->local2World(shape->getPoint(i)); float bDist = b.dot(normal) - distance; if (aDist*bDist < 0.0f) { float t = std::fabs(aDist)/(std::fabs(aDist) + std::fabs(bDist)); points[pointsCount] = a.lerp(b, t); ++pointsCount; } } Point center = PhysicsShape::getPolyonCenter(points, pointsCount); Node* node = Node::create(); PhysicsBody* polyon = PhysicsBody::createPolygon(points, pointsCount, PHYSICSBODY_MATERIAL_DEFAULT, -center); node->setPosition(center); node->setPhysicsBody(polyon); polyon->setVelocity(body->getVelocityAtWorldPoint(center)); polyon->setAngularVelocity(body->getAngularVelocity()); polyon->setTag(_sliceTag); addChild(node); delete[] points; } void PhysicsDemoSlice::onTouchEnded(Touch *touch, Event *event) { auto func = CC_CALLBACK_3(PhysicsDemoSlice::slice, this); _scene->getPhysicsWorld()->rayCast(func, touch->getStartLocation(), touch->getLocation(), nullptr); } std::string PhysicsDemoSlice::title() { return "Slice"; } std::string PhysicsDemoSlice::subtitle() { return "click and drag to slice up the block"; }
33.656584
161
0.598414
[ "object", "shape", "vector" ]
161a700a895e860fc0b5f20e5f15eb7769c0b417
1,634
hpp
C++
src/base/buffer_back_insert_iterator.hpp
GeniusVentures/SuperGenius
ae43304f4a2475498ef56c971296175acb88d0ee
[ "MIT" ]
1
2021-07-10T21:25:03.000Z
2021-07-10T21:25:03.000Z
src/base/buffer_back_insert_iterator.hpp
GeniusVentures/SuperGenius
ae43304f4a2475498ef56c971296175acb88d0ee
[ "MIT" ]
null
null
null
src/base/buffer_back_insert_iterator.hpp
GeniusVentures/SuperGenius
ae43304f4a2475498ef56c971296175acb88d0ee
[ "MIT" ]
null
null
null
#include "base/buffer.hpp" using sgns::base::Buffer; namespace std { /* * std::back_insert_iterator is an output iterator * that appends to a container for which it was constructed. */ template <> class back_insert_iterator<Buffer> { public: using value_type = Buffer::value_type; using difference_type = typename std::vector<uint8_t>::difference_type; using pointer = Buffer::pointer; using reference = typename std::vector<uint8_t>::reference; using iterator_category = std::random_access_iterator_tag; constexpr explicit back_insert_iterator(Buffer &c): buf_ {c} { } back_insert_iterator<Buffer>(const back_insert_iterator<Buffer>& a):buf_{a.buf_} { } back_insert_iterator<Buffer>& operator=(const back_insert_iterator<Buffer>& a) { buf_ = a.buf_ ; return *this; } back_insert_iterator<Buffer>& operator=(uint8_t value) { buf_.putUint8(value); return *this; } back_insert_iterator<Buffer>& operator=(uint32_t value) { buf_.putUint32(value); return *this; } back_insert_iterator<Buffer>& operator=(std::string_view value) { buf_.put(value); return *this; } back_insert_iterator<Buffer>& operator=(gsl::span<const uint8_t> s) { buf_.put(s); return *this; } back_insert_iterator<Buffer>& operator=(const std::vector<uint8_t>& v) { buf_.put(v); return *this; } constexpr back_insert_iterator& operator*() { return *this; } constexpr back_insert_iterator& operator++() { return *this; } constexpr back_insert_iterator& operator++(int) { return *this; } private: Buffer& buf_; }; }
20.683544
84
0.69033
[ "vector" ]
161b64348866c3bdcbb385dc8e4aa3179e4c8235
25,287
cc
C++
components/autofill_assistant/browser/basic_interactions.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-10-18T02:33:40.000Z
2020-10-18T02:33:40.000Z
components/autofill_assistant/browser/basic_interactions.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
3
2021-05-17T16:28:52.000Z
2021-05-21T22:42:22.000Z
components/autofill_assistant/browser/basic_interactions.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2020 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 "components/autofill_assistant/browser/basic_interactions.h" #include <algorithm> #include "base/callback_helpers.h" #include "base/i18n/time_formatting.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "components/autofill/core/browser/autofill_data_util.h" #include "components/autofill_assistant/browser/field_formatter.h" #include "components/autofill_assistant/browser/script_executor_delegate.h" #include "components/autofill_assistant/browser/trigger_context.h" #include "components/autofill_assistant/browser/user_model.h" namespace autofill_assistant { namespace { bool BooleanAnd(UserModel* user_model, const std::string& result_model_identifier, const BooleanAndProto& proto) { auto values = user_model->GetValues(proto.values()); if (!values.has_value()) { DVLOG(2) << "Failed to find values in user model"; return false; } if (!AreAllValuesOfType(*values, ValueProto::kBooleans) || !AreAllValuesOfSize(*values, 1)) { DVLOG(2) << "All values must be 'boolean' and contain exactly 1 value each"; return false; } bool result = true; for (const auto& value : *values) { result &= value.booleans().values(0); } user_model->SetValue(result_model_identifier, SimpleValue(result, ContainsClientOnlyValue(*values))); return true; } bool BooleanOr(UserModel* user_model, const std::string& result_model_identifier, const BooleanOrProto& proto) { auto values = user_model->GetValues(proto.values()); if (!values.has_value()) { DVLOG(2) << "Failed to find values in user model"; return false; } if (!AreAllValuesOfType(*values, ValueProto::kBooleans) || !AreAllValuesOfSize(*values, 1)) { DVLOG(2) << "All values must be 'boolean' and contain exactly 1 value each"; return false; } bool result = false; for (const auto& value : *values) { result |= value.booleans().values(0); } user_model->SetValue(result_model_identifier, SimpleValue(result, ContainsClientOnlyValue(*values))); return true; } bool BooleanNot(UserModel* user_model, const std::string& result_model_identifier, const BooleanNotProto& proto) { auto value = user_model->GetValue(proto.value()); if (!value.has_value()) { DVLOG(2) << "Error evaluating " << __func__ << ": " << proto.value() << " not found in model"; return false; } if (value->booleans().values().size() != 1) { DVLOG(2) << "Error evaluating " << __func__ << ": expected single boolean, but got " << *value; return false; } user_model->SetValue( result_model_identifier, SimpleValue(!value->booleans().values(0), value->is_client_side_only())); return true; } bool ValueToString(UserModel* user_model, const std::string& result_model_identifier, const ToStringProto& proto) { auto value = user_model->GetValue(proto.value()); if (!value.has_value()) { DVLOG(2) << "Error evaluating " << __func__ << ": " << proto.value() << " not found in model"; return false; } if (GetValueSize(*value) == 0) { DVLOG(2) << "Error evaluating " << __func__ << ": input value empty"; return false; } switch (value->kind_case()) { case ValueProto::kUserActions: case ValueProto::kLoginOptions: case ValueProto::kCreditCardResponse: case ValueProto::kServerPayload: DVLOG(2) << "Error evaluating " << __func__ << ": does not support values of type " << value->kind_case(); return false; default: break; } ValueProto result; result.set_is_client_side_only(value->is_client_side_only()); for (int i = 0; i < GetValueSize(*value); ++i) { switch (value->kind_case()) { case ValueProto::kStrings: result.mutable_strings()->add_values(value->strings().values(i)); break; case ValueProto::kBooleans: result.mutable_strings()->add_values( value->booleans().values(i) ? "true" : "false"); break; case ValueProto::kInts: result.mutable_strings()->add_values( base::NumberToString(value->ints().values(i))); break; case ValueProto::kDates: { if (proto.date_format().date_format().empty()) { DVLOG(2) << "Error evaluating " << __func__ << ": date_format not set"; return false; } auto date = value->dates().values(i); base::Time::Exploded exploded_time = {date.year(), date.month(), /* day_of_week = */ -1, date.day(), /* hour = */ 0, /* minute = */ 0, /* second = */ 0, /* millisecond = */ 0}; base::Time time; if (!base::Time::FromLocalExploded(exploded_time, &time)) { DVLOG(2) << "Error evaluating " << __func__ << ": invalid date " << *value; return false; } result.mutable_strings()->add_values( base::UTF16ToUTF8(base::TimeFormatWithPattern( time, proto.date_format().date_format().c_str()))); break; } case ValueProto::kCreditCards: { if (proto.autofill_format().value_expression().chunk().empty()) { DVLOG(2) << "Error evaluating " << __func__ << ": pattern not set"; return false; } auto* credit_card = user_model->GetCreditCard(value->credit_cards().values(i)); if (!credit_card) { DVLOG(2) << "Error evaluating " << __func__ << ": credit card not found"; return false; } std::string formatted_string; auto format_status = field_formatter::FormatExpression( proto.autofill_format().value_expression(), field_formatter::CreateAutofillMappings( *credit_card, proto.autofill_format().locale()), /* quote_meta= */ false, &formatted_string); if (!format_status.ok()) { DVLOG(2) << "Error evaluating " << __func__ << ": error formatting pattern '" << proto.autofill_format().value_expression() << "'"; return false; } result.mutable_strings()->add_values(formatted_string); break; } case ValueProto::kProfiles: { if (proto.autofill_format().value_expression().chunk().empty()) { DVLOG(2) << "Error evaluating " << __func__ << ": pattern not set"; return false; } auto* profile = user_model->GetProfile(value->profiles().values(i)); if (!profile) { DVLOG(2) << "Error evaluating " << __func__ << ": profile not found"; return false; } std::string formatted_string; auto format_status = field_formatter::FormatExpression( proto.autofill_format().value_expression(), field_formatter::CreateAutofillMappings( *profile, proto.autofill_format().locale()), /* quote_meta= */ false, &formatted_string); if (!format_status.ok()) { DVLOG(2) << "Error evaluating " << __func__ << ": error formatting pattern '" << proto.autofill_format().value_expression() << "'"; return false; } result.mutable_strings()->add_values(formatted_string); break; } case ValueProto::kUserActions: case ValueProto::kLoginOptions: case ValueProto::kCreditCardResponse: case ValueProto::kServerPayload: case ValueProto::KIND_NOT_SET: NOTREACHED(); return false; } } user_model->SetValue(result_model_identifier, result); return true; } bool Compare(UserModel* user_model, const std::string& result_model_identifier, const ValueComparisonProto& proto) { auto value_a = user_model->GetValue(proto.value_a()); if (!value_a.has_value()) { DVLOG(2) << "Error evaluating " << __func__ << ": " << proto.value_a() << " not found in model"; return false; } auto value_b = user_model->GetValue(proto.value_b()); if (!value_b.has_value()) { DVLOG(2) << "Error evaluating " << __func__ << ": " << proto.value_b() << " not found in model"; return false; } if (proto.mode() == ValueComparisonProto::UNDEFINED) { DVLOG(2) << "Error evaluating " << __func__ << ": mode not set"; return false; } if (proto.mode() == ValueComparisonProto::EQUAL) { user_model->SetValue( result_model_identifier, SimpleValue(*value_a == *value_b, ContainsClientOnlyValue({*value_a, *value_b}))); return true; } if (proto.mode() == ValueComparisonProto::NOT_EQUAL) { user_model->SetValue( result_model_identifier, SimpleValue(*value_a != *value_b, ContainsClientOnlyValue({*value_a, *value_b}))); return true; } // All modes except EQUAL require a size of 1 and a common value type and // are only supported for a subset of value types. if (!AreAllValuesOfSize({*value_a, *value_b}, 1)) { DVLOG(2) << "Error evaluating " << __func__ << ": comparison mode " << proto.mode() << "requires all input values to have size 1"; return false; } if (!AreAllValuesOfType({*value_a, *value_b}, value_a->kind_case())) { DVLOG(2) << "Error evaluating " << __func__ << ": comparison mode " << proto.mode() << "requires all input values to share the same type, but got " << value_a->kind_case() << " and " << value_b->kind_case(); return false; } if (value_a->kind_case() != ValueProto::kInts && value_a->kind_case() != ValueProto::kDates && value_a->kind_case() != ValueProto::kStrings) { DVLOG(2) << "Error evaluating " << __func__ << ": the selected comparison mode is only supported for " "integers, strings, and dates"; return false; } bool result = false; switch (proto.mode()) { case ValueComparisonProto::LESS: result = *value_a < *value_b; break; case ValueComparisonProto::LESS_OR_EQUAL: result = *value_a < *value_b || value_a == value_b; break; case ValueComparisonProto::GREATER_OR_EQUAL: result = *value_a > *value_b || value_a == value_b; break; case ValueComparisonProto::GREATER: result = *value_a > *value_b; break; case ValueComparisonProto::EQUAL: case ValueComparisonProto::NOT_EQUAL: case ValueComparisonProto::UNDEFINED: NOTREACHED(); return false; } user_model->SetValue( result_model_identifier, SimpleValue(result, ContainsClientOnlyValue({*value_a, *value_b}))); return true; } bool IntegerSum(UserModel* user_model, const std::string& result_model_identifier, const IntegerSumProto& proto) { auto values = user_model->GetValues(proto.values()); if (!values.has_value()) { DVLOG(2) << "Error evaluating " << __func__ << ": " << "Failed to find values in user model"; return false; } if (!AreAllValuesOfSize(*values, 1) || !AreAllValuesOfType(*values, ValueProto::kInts)) { DVLOG(2) << "Error evaluating " << __func__ << ": " << "all input values must be single integers"; return false; } int sum = 0; for (const auto& value : *values) { sum += value.ints().values(0); } user_model->SetValue(result_model_identifier, SimpleValue(sum, ContainsClientOnlyValue(*values))); return true; } bool CreateCreditCardResponse(UserModel* user_model, const std::string& result_model_identifier, const CreateCreditCardResponseProto& proto) { auto value = user_model->GetValue(proto.value()); if (!value.has_value()) { DVLOG(2) << "Failed to find value in user model"; return false; } if (value->credit_cards().values().size() != 1) { DVLOG(2) << "Error evaluating " << __func__ << ": expected single CreditCardProto, but got " << *value; return false; } auto* credit_card = user_model->GetCreditCard(value->credit_cards().values(0)); if (!credit_card) { DVLOG(2) << "Error evaluating " << __func__ << ": card not found for guid " << value->credit_cards().values(0).guid(); return false; } // The result is intentionally not client_side_only, irrespective of input. ValueProto result; result.mutable_credit_card_response()->set_network( autofill::data_util::GetPaymentRequestData(credit_card->network()) .basic_card_issuer_network); user_model->SetValue(result_model_identifier, result); return true; } bool CreateLoginOptionResponse(UserModel* user_model, const std::string& result_model_identifier, const CreateLoginOptionResponseProto& proto) { auto value = user_model->GetValue(proto.value()); if (!value.has_value()) { DVLOG(2) << "Failed to find value in user model"; return false; } if (value->login_options().values().size() != 1) { DVLOG(2) << "Error evaluating " << __func__ << ": expected single LoginOptionProto, but got " << *value; return false; } // The result is intentionally not client_side_only, irrespective of input. ValueProto result; result.set_server_payload(value->login_options().values(0).payload()); user_model->SetValue(result_model_identifier, result); return true; } bool StringEmpty(UserModel* user_model, const std::string& result_model_identifier, const StringEmptyProto& proto) { auto value = user_model->GetValue(proto.value()); if (!value.has_value()) { DVLOG(2) << "Failed to find value in user model"; return false; } if (value->strings().values().size() != 1) { DVLOG(2) << "Error evaluating " << __func__ << ": expected single string, but got " << *value; return false; } user_model->SetValue(result_model_identifier, SimpleValue(value->strings().values(0).empty(), ContainsClientOnlyValue({*value}))); return true; } } // namespace base::WeakPtr<BasicInteractions> BasicInteractions::GetWeakPtr() { return weak_ptr_factory_.GetWeakPtr(); } BasicInteractions::BasicInteractions(ScriptExecutorDelegate* delegate) : delegate_(delegate) {} BasicInteractions::~BasicInteractions() {} bool BasicInteractions::SetValue(const SetModelValueProto& proto) { if (proto.model_identifier().empty()) { DVLOG(2) << "Error setting value: model_identifier empty"; return false; } auto value = delegate_->GetUserModel()->GetValue(proto.value()); if (!value.has_value()) { DVLOG(2) << "Error setting value: " << proto.value() << " not found"; return false; } delegate_->GetUserModel()->SetValue(proto.model_identifier(), *value); return true; } bool BasicInteractions::ComputeValue(const ComputeValueProto& proto) { if (proto.result_model_identifier().empty()) { DVLOG(2) << "Error computing value: result_model_identifier empty"; return false; } switch (proto.kind_case()) { case ComputeValueProto::kBooleanAnd: if (proto.boolean_and().values().size() == 0) { DVLOG(2) << "Error computing ComputeValue::BooleanAnd: no " "values specified"; return false; } return BooleanAnd(delegate_->GetUserModel(), proto.result_model_identifier(), proto.boolean_and()); case ComputeValueProto::kBooleanOr: if (proto.boolean_or().values().size() == 0) { DVLOG(2) << "Error computing ComputeValue::BooleanOr: no " "values specified"; return false; } return BooleanOr(delegate_->GetUserModel(), proto.result_model_identifier(), proto.boolean_or()); case ComputeValueProto::kBooleanNot: if (!proto.boolean_not().has_value()) { DVLOG(2) << "Error computing ComputeValue::BooleanNot: " "value not specified"; return false; } return BooleanNot(delegate_->GetUserModel(), proto.result_model_identifier(), proto.boolean_not()); case ComputeValueProto::kToString: if (!proto.to_string().has_value()) { DVLOG(2) << "Error computing ComputeValue::ToString: " "value not specified"; return false; } return ValueToString(delegate_->GetUserModel(), proto.result_model_identifier(), proto.to_string()); case ComputeValueProto::kComparison: return Compare(delegate_->GetUserModel(), proto.result_model_identifier(), proto.comparison()); case ComputeValueProto::kIntegerSum: if (proto.integer_sum().values().size() == 0) { DVLOG(2) << "Error computing ComputeValue::IntegerSum: " "no values specified"; return false; } return IntegerSum(delegate_->GetUserModel(), proto.result_model_identifier(), proto.integer_sum()); case ComputeValueProto::kCreateCreditCardResponse: if (!proto.create_credit_card_response().has_value()) { DVLOG(2) << "Error computing ComputeValue::CreateCreditCardResponse: " "no value specified"; return false; } return CreateCreditCardResponse(delegate_->GetUserModel(), proto.result_model_identifier(), proto.create_credit_card_response()); case ComputeValueProto::kCreateLoginOptionResponse: if (!proto.create_login_option_response().has_value()) { DVLOG(2) << "Error computing ComputeValue::CreateLoginOptionResponse: " "no value specified"; return false; } return CreateLoginOptionResponse(delegate_->GetUserModel(), proto.result_model_identifier(), proto.create_login_option_response()); break; case ComputeValueProto::kStringEmpty: if (!proto.string_empty().has_value()) { DVLOG(2) << "Error computing ComputeValue::StringEmpty: no value specified"; return false; } return StringEmpty(delegate_->GetUserModel(), proto.result_model_identifier(), proto.string_empty()); case ComputeValueProto::KIND_NOT_SET: DVLOG(2) << "Error computing value: kind not set"; return false; } } bool BasicInteractions::SetUserActions(const SetUserActionsProto& proto) { if (!proto.has_user_actions()) { DVLOG(2) << "Error setting user actions: user_actions not set"; return false; } auto user_actions_value = delegate_->GetUserModel()->GetValue(proto.user_actions()); if (!user_actions_value.has_value()) { DVLOG(2) << "Error setting user actions: " << proto.user_actions() << " not found in model"; return false; } if (!user_actions_value->has_user_actions()) { DVLOG(2) << "Error setting user actions: Expected " << proto.user_actions() << " to hold UserActions, but found " << user_actions_value->kind_case() << " instead"; return false; } auto user_actions = std::make_unique<std::vector<UserAction>>(); for (const auto& user_action : user_actions_value->user_actions().values()) { user_actions->push_back({user_action}); // No callback needed, the framework relies on generic events which will // be fired automatically when user actions are called. user_actions->back().SetCallback( base::DoNothing::Once<std::unique_ptr<TriggerContext>>()); } delegate_->SetUserActions(std::move(user_actions)); return true; } bool BasicInteractions::ToggleUserAction(const ToggleUserActionProto& proto) { auto user_actions_value = delegate_->GetUserModel()->GetValue( proto.user_actions_model_identifier()); if (!user_actions_value.has_value()) { DVLOG(2) << "Error evaluating " << __func__ << ": " << proto.user_actions_model_identifier() << " not found in model"; return false; } if (!user_actions_value->has_user_actions()) { DVLOG(2) << "Error evaluating " << __func__ << ": expected user_actions_model_identifier to contain user " "actions, but was " << *user_actions_value; return false; } auto enabled_value = delegate_->GetUserModel()->GetValue(proto.enabled()); if (!enabled_value.has_value()) { DVLOG(2) << "Error evaluating " << __func__ << ": " << proto.enabled() << " not found in model"; return false; } if (enabled_value->booleans().values().size() != 1) { DVLOG(2) << "Error evaluating " << __func__ << ": expected enabled to contain a single bool, but was " << *enabled_value; return false; } auto user_action_it = std::find_if( user_actions_value->user_actions().values().cbegin(), user_actions_value->user_actions().values().cend(), [&](const UserActionProto& user_action) { return user_action.identifier() == proto.user_action_identifier(); }); if (user_action_it == user_actions_value->user_actions().values().cend()) { DVLOG(2) << "Error evaluating " << __func__ << ": " << proto.user_action_identifier() << " not found in " << *user_actions_value; return false; } auto user_action_index = user_action_it - user_actions_value->user_actions().values().cbegin(); user_actions_value->mutable_user_actions() ->mutable_values(user_action_index) ->set_enabled(enabled_value->booleans().values(0)); delegate_->GetUserModel()->SetValue(proto.user_actions_model_identifier(), *user_actions_value); return true; } bool BasicInteractions::EndAction(const ClientStatus& status) { if (!end_action_callback_) { DVLOG(2) << "Failed to EndAction: no callback set"; return false; } // It is possible for the action to end before view inflation was finished. // In that case, the action can end directly and does not need to receive this // callback. view_inflation_finished_callback_.Reset(); std::move(end_action_callback_).Run(status); return true; } bool BasicInteractions::NotifyViewInflationFinished( const ClientStatus& status) { if (!view_inflation_finished_callback_) { return false; } std::move(view_inflation_finished_callback_).Run(status); return true; } bool BasicInteractions::NotifyPersistentViewInflationFinished( const ClientStatus& status) { if (!persistent_view_inflation_finished_callback_) { return false; } std::move(persistent_view_inflation_finished_callback_).Run(status); return true; } void BasicInteractions::ClearCallbacks() { end_action_callback_.Reset(); view_inflation_finished_callback_.Reset(); } void BasicInteractions::ClearPersistentUiCallbacks() { persistent_view_inflation_finished_callback_.Reset(); } void BasicInteractions::SetEndActionCallback( base::OnceCallback<void(const ClientStatus&)> end_action_callback) { end_action_callback_ = std::move(end_action_callback); } void BasicInteractions::SetViewInflationFinishedCallback( base::OnceCallback<void(const ClientStatus&)> view_inflation_finished_callback) { view_inflation_finished_callback_ = std::move(view_inflation_finished_callback); } void BasicInteractions::SetPersistentViewInflationFinishedCallback( base::OnceCallback<void(const ClientStatus&)> persistent_view_inflation_finished_callback) { persistent_view_inflation_finished_callback_ = std::move(persistent_view_inflation_finished_callback); } bool BasicInteractions::RunConditionalCallback( const std::string& condition_identifier, base::RepeatingCallback<void()> callback) { auto condition_value = delegate_->GetUserModel()->GetValue(condition_identifier); if (!condition_value.has_value()) { DVLOG(2) << "Error evaluating " << __func__ << ": " << condition_identifier << " not found in model"; return false; } if (condition_value->booleans().values().size() != 1) { DVLOG(2) << "Error evaluating " << __func__ << ": expected " << condition_identifier << " to contain a single bool, but was " << *condition_value; return false; } if (condition_value->booleans().values(0)) { callback.Run(); } return true; } } // namespace autofill_assistant
36.861516
80
0.626923
[ "vector", "model" ]
161d84e73e7722cac013450f4934e453a0a8230f
7,099
hpp
C++
src/utilities/data/Matrix.hpp
muehleisen/OpenStudio
3bfe89f6c441d1e61e50b8e94e92e7218b4555a0
[ "blessing" ]
354
2015-01-10T17:46:11.000Z
2022-03-29T10:00:00.000Z
src/utilities/data/Matrix.hpp
muehleisen/OpenStudio
3bfe89f6c441d1e61e50b8e94e92e7218b4555a0
[ "blessing" ]
3,243
2015-01-02T04:54:45.000Z
2022-03-31T17:22:22.000Z
src/utilities/data/Matrix.hpp
jmarrec/OpenStudio
5276feff0d8dbd6c8ef4e87eed626bc270a19b14
[ "blessing" ]
157
2015-01-07T15:59:55.000Z
2022-03-30T07:46:09.000Z
/*********************************************************************************************************************** * OpenStudio(R), Copyright (c) 2008-2021, Alliance for Sustainable Energy, LLC, and other contributors. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following * disclaimer. * * (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the distribution. * * (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products * derived from this software without specific prior written permission from the respective party. * * (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works * may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior * written permission from Alliance for Sustainable Energy, LLC. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY 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(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED * STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, 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 UTILITIES_DATA_MATRIX_HPP #define UTILITIES_DATA_MATRIX_HPP #include "Vector.hpp" #include "../UtilitiesAPI.hpp" #include "../core/Logger.hpp" #include <boost/numeric/ublas/matrix.hpp> #include <boost/numeric/ublas/io.hpp> #include <boost/numeric/ublas/lu.hpp> namespace openstudio { /// Matrix typedef boost::numeric::ublas::matrix<double> Matrix; ////////////////////////////////////////////////////////////////////////// // Begin SWIG'able, copy and paste into Matrix.i ////////////////////////////////////////////////////////////////////////// /// new operators UTILITIES_API bool operator==(const Matrix& lhs, const Matrix& rhs); UTILITIES_API bool operator!=(const Matrix& lhs, const Matrix& rhs); /// common methods /// linear interpolation of the function v = f(x, y) at point xi, yi /// assumes that x and y are strictly increasing UTILITIES_API double interp(const Vector& x, const Vector& y, const Matrix& v, double xi, double yi, InterpMethod interpMethod = LinearInterp, ExtrapMethod extrapMethod = NoneExtrap); /// linear interpolation of the function v = f(x, y) at points xi, yi /// assumes that x and y are strictly increasing UTILITIES_API Vector interp(const Vector& x, const Vector& y, const Matrix& v, const Vector& xi, double yi, InterpMethod interpMethod = LinearInterp, ExtrapMethod extrapMethod = NoneExtrap); /// linear interpolation of the function v = f(x, y) at points xi, yi /// assumes that x and y are strictly increasing UTILITIES_API Vector interp(const Vector& x, const Vector& y, const Matrix& v, double xi, const Vector& yi, InterpMethod interpMethod = LinearInterp, ExtrapMethod extrapMethod = NoneExtrap); /// linear interpolation of the function v = f(x, y) at points xi, yi /// assumes that x and y are strictly increasing UTILITIES_API Matrix interp(const Vector& x, const Vector& y, const Matrix& v, const Vector& xi, const Vector& yi, InterpMethod interpMethod = LinearInterp, ExtrapMethod extrapMethod = NoneExtrap); /// matrix product UTILITIES_API Matrix prod(const Matrix& lop, const Matrix& rop); /// vector product UTILITIES_API Vector prod(const Matrix& m, const Vector& v); /// outer product UTILITIES_API Matrix outerProd(const Vector& lhs, const Vector& rhs); /// take the natural logarithm of Matrix elements, componentwise UTILITIES_API Matrix log(const Matrix& v); /// take the logarithm of Matrix elements with respect to base, componentwise UTILITIES_API Matrix log(const Matrix& v, double base); /// generates a M x N Matrix whose elements come from the uniform distribution on [a,b]. UTILITIES_API Matrix randMatrix(double a, double b, unsigned M, unsigned N); /// sum of all elements UTILITIES_API double sum(const Matrix& matrix); /// maximum of all elements UTILITIES_API double maximum(const Matrix& matrix); /// minimum of all elements UTILITIES_API double minimum(const Matrix& matrix); /// mean of all elements UTILITIES_API double mean(const Matrix& matrix); /// get the connected components from an NxN adjacency matrix (1.0 for i-j connected, 0.0 for i-j not connected) UTILITIES_API std::vector<std::vector<unsigned>> findConnectedComponents(const Matrix& matrix); // from the boost vault: // The following code inverts the matrix input using LU-decomposition with backsubstitution of unit vectors. Reference: Numerical Recipes in C, 2nd ed., by Press, Teukolsky, Vetterling & Flannery. /// Matrix inversion routine, using lu_factorize and lu_substitute in uBLAS to invert a matrix */ template <class T> bool invert(const boost::numeric::ublas::matrix<T>& input, boost::numeric::ublas::matrix<T>& inverse) { // create a working copy of the input boost::numeric::ublas::matrix<T> A(input); // create a permutation matrix for the LU-factorization boost::numeric::ublas::permutation_matrix<std::size_t> pm(A.size1()); // perform LU-factorization typename boost::numeric::ublas::matrix<T>::size_type res = boost::numeric::ublas::lu_factorize(A, pm); if (res != 0) { LOG_FREE(Info, "boost.ublas", "boost::numeric::ublas::lu_factorize returned res = " << res << ", A = " << A << ", pm = " << pm << " for input = " << input); return false; } // create identity matrix of "inverse" inverse.assign(boost::numeric::ublas::identity_matrix<T>(A.size1())); // backsubstitute to get the inverse try { boost::numeric::ublas::lu_substitute(A, pm, inverse); } catch (std::exception& e) { LOG_FREE(Info, "boost.ublas", "boost::numeric::ublas::lu_substitute threw exception '" << e.what() << "' for A = " << A << ", pm = " << pm); return false; } return true; } } // namespace openstudio #endif //UTILITIES_DATA_MATRIX_HPP
48.292517
196
0.695027
[ "vector" ]
161dbda9514b08c76f6f2098c44aadf32383b612
820
cpp
C++
C++/StringStream/stringstream.cpp
IsaacAsante/hackerrank
76c430b341ce1e2ab427eda57508eb309d3b215b
[ "MIT" ]
108
2021-03-29T05:04:16.000Z
2022-03-19T15:11:52.000Z
C++/StringStream/stringstream.cpp
IsaacAsante/hackerrank
76c430b341ce1e2ab427eda57508eb309d3b215b
[ "MIT" ]
null
null
null
C++/StringStream/stringstream.cpp
IsaacAsante/hackerrank
76c430b341ce1e2ab427eda57508eb309d3b215b
[ "MIT" ]
32
2021-03-30T03:56:54.000Z
2022-03-27T14:41:32.000Z
/* Author: Isaac Asante * HackerRank URL for this exercise: https://www.hackerrank.com/challenges/c-tutorial-stringstream/problem * Original video explanation: https://www.youtube.com/watch?v=D-qwtgg6CJs * Last verified on: April 17, 2021 */ /* IMPORTANT: * This is the full code for the solution. */ #include <sstream> #include <vector> #include <iostream> using namespace std; vector<int> parseInts(string str) { // Complete this function vector<int> v; stringstream ss(str); int n; char skip; while (ss) { if (ss >> n) v.push_back(n); ss >> skip; } return v; } int main() { string str; cin >> str; vector<int> integers = parseInts(str); for (int i = 0; i < integers.size(); i++) { cout << integers[i] << "\n"; } return 0; }
20
106
0.612195
[ "vector" ]
161ec84583b95baf19a36009ef80eefec8bfe8d6
13,378
hpp
C++
applications/FemToDemApplication/custom_elements/generic_small_strain_femdem_element.hpp
Jacklwln/Kratos
12ffe332622d7e8ea3e4a10bc061beb9d8e6e8de
[ "BSD-4-Clause" ]
1
2019-08-01T09:01:08.000Z
2019-08-01T09:01:08.000Z
applications/FemToDemApplication/custom_elements/generic_small_strain_femdem_element.hpp
Jacklwln/Kratos
12ffe332622d7e8ea3e4a10bc061beb9d8e6e8de
[ "BSD-4-Clause" ]
null
null
null
applications/FemToDemApplication/custom_elements/generic_small_strain_femdem_element.hpp
Jacklwln/Kratos
12ffe332622d7e8ea3e4a10bc061beb9d8e6e8de
[ "BSD-4-Clause" ]
null
null
null
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ \. // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics FemDem Application // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: Alejandro Cornejo Velazquez // #if !defined(KRATOS_GENERIC_SMALL_STRAIN_FEMDEM_ELEMENT_H_INCLUDED) #define KRATOS_GENERIC_SMALL_STRAIN_FEMDEM_ELEMENT_H_INCLUDED // System includes // External include // Project includes #include "custom_elements/solid_elements/small_displacement_element.hpp" #include "custom_utilities/constitutive_law_utilities.h" namespace Kratos { ///@name Kratos Globals ///@{ ///@} ///@name Type Definitions ///@{ ///@} ///@name Enum's ///@{ ///@} ///@name Functions ///@{ ///@} ///@name Kratos Classes ///@{ /** * @class GenericSmallStrainFemDemElement * @ingroup FemToDemApplication * @brief Small Displacement element for the 2D and 3D cases * @author Alejandro Cornejo */ template<unsigned int TDim, unsigned int TyieldSurf> class GenericSmallStrainFemDemElement : public SmallDisplacementElement // Derived Element from SolidMechanics { public: ///@name Type Definitions ///@{ ///definition of element type typedef Element ElementType; ///base type: an GeometricalObject that automatically has a unique number typedef GeometricalObject BaseType; ///definition of node type (default is: Node<3>) typedef Node < 3 > NodeType; /** * Properties are used to store any parameters * related to the constitutive law */ typedef Properties PropertiesType; ///definition of the geometry type with given NodeType typedef Geometry<NodeType> GeometryType; ///definition of nodes container type, redefined from GeometryType typedef Geometry<NodeType>::PointsArrayType NodesArrayType; typedef Vector VectorType; typedef Matrix MatrixType; typedef std::size_t IndexType; typedef std::size_t SizeType; typedef std::vector<std::size_t> EquationIdVectorType; typedef std::vector< Dof<double>::Pointer > DofsVectorType; typedef PointerVectorSet<Dof<double>, IndexedObject> DofsArrayType; typedef GeometryData GeometryDataType; /// We define the dimension static constexpr SizeType VoigtSize = (TDim == 3) ? 6 : 3; /// We define the number of edges static constexpr SizeType NumberOfEdges = (TDim == 3) ? 6 : 3; ///Pointer type for constitutive laws typedef ConstitutiveLawType::Pointer ConstitutiveLawPointerType; /// The zero tolerance static constexpr double tolerance = std::numeric_limits<double>::epsilon(); /// Counted pointer of GenericSmallStrainFemDemElement KRATOS_CLASS_INTRUSIVE_POINTER_DEFINITION(GenericSmallStrainFemDemElement); ///@} ///@name Life Cycle ///@{ /// Default constructors GenericSmallStrainFemDemElement(IndexType NewId, GeometryType::Pointer pGeometry); GenericSmallStrainFemDemElement(IndexType NewId, GeometryType::Pointer pGeometry, PropertiesType::Pointer pProperties); ///Copy constructor GenericSmallStrainFemDemElement(GenericSmallStrainFemDemElement const &rOther); /// Destructor. virtual ~GenericSmallStrainFemDemElement(); /// Assignment operator. GenericSmallStrainFemDemElement &operator=(GenericSmallStrainFemDemElement const &rOther); Element::Pointer Create(IndexType NewId, NodesArrayType const &ThisNodes, PropertiesType::Pointer pProperties) const override; Element::Pointer Clone(IndexType NewId, NodesArrayType const &ThisNodes) const override; GenericSmallStrainFemDemElement() { } /** * this is called in the beginning of each solution step */ void InitializeSolutionStep(ProcessInfo& rCurrentProcessInfo) override; /** * this is called at the end of each solution step */ void FinalizeSolutionStep(ProcessInfo& rCurrentProcessInfo) override; /** * this is called for non-linear analysis at the beginning of the iteration process */ void InitializeNonLinearIteration(ProcessInfo& rCurrentProcessInfo) override; /** * this is called for non-linear analysis at the end of the iteration process */ void FinalizeNonLinearIteration(ProcessInfo& CurrentProcessInfo) override; /** * this is called during the assembling process in order * to calculate all elemental contributions to the global system * matrix and the right hand side * @param rLeftHandSideMatrix the elemental left hand side matrix * @param rRightHandSideVector the elemental right hand side * @param rCurrentProcessInfo the current process info instance */ void CalculateLocalSystem(MatrixType& rLeftHandSideMatrix, VectorType& rRightHandSideVector, ProcessInfo& rCurrentProcessInfo) override; /** * this is called during the assembling process in order * to calculate the elemental left hand side matrix only * @param rLeftHandSideMatrix the elemental left hand side matrix * @param rCurrentProcessInfo the current process info instance */ void CalculateLeftHandSide(MatrixType& rLeftHandSideMatrix, ProcessInfo& rCurrentProcessInfo) override; /** * this is called during the assembling process in order * to calculate the elemental right hand side vector only * @param rRightHandSideVector the elemental right hand side vector * @param rCurrentProcessInfo the current process info instance */ void CalculateRightHandSide(VectorType& rRightHandSideVector, ProcessInfo& rCurrentProcessInfo) override; /** * this computes the elements that share an edge -> fills the mEdgeNeighboursContainer */ void ComputeEdgeNeighbours(ProcessInfo& rCurrentProcessInfo); void AuxComputeEdgeNeighbours(ProcessInfo& rCurrentProcessInfo); std::vector<Element*> GetEdgeNeighbourElements(const int edge) {return mEdgeNeighboursContainer[edge];} /** * this storages the mEdgeNeighboursContainer */ void SaveEdgeNeighboursContainer(const std::vector<std::vector<Element*>>& rtoSave) {mEdgeNeighboursContainer = rtoSave;} void SetNodeIndexes(Matrix& rMatrix) // Defines the numbering of the edges with the corresponding nodes { rMatrix.resize(6, 2); rMatrix(0, 0) = 0; rMatrix(0, 1) = 1; rMatrix(1, 0) = 0; rMatrix(1, 1) = 2; rMatrix(2, 0) = 0; rMatrix(2, 1) = 3; rMatrix(3, 0) = 1; rMatrix(3, 1) = 2; rMatrix(4, 0) = 1; rMatrix(4, 1) = 3; rMatrix(5, 0) = 2; rMatrix(5, 1) = 3; } /** * this imposes the damage/threshold to be equal * at the edges */ void InitializeInternalVariablesAfterMapping(); /** * this saves the converged values with the later non-conv values */ void UpdateDataBase(); /** * this computes the damage of the FE */ double CalculateElementalDamage(const Vector& rEdgeDamages); double CalculateElementalDamage3D(const Vector& rEdgeDamages); double CalculateElementalDamage2D(const Vector& rEdgeDamages); /** * this computes the average vector on the edge for a certain variable */ void CalculateAverageVariableOnEdge(const Element* pCurrentElement, const Variable<Vector> ThisVariable, Vector& rAverageStress, const int edge); void CalculateAverageVariableOnEdge2D(const Element* pCurrentElement, const Variable<Vector> ThisVariable, Vector& rAverageStress, const int edge); void CalculateAverageVariableOnEdge3D(const Element* pCurrentElement, const Variable<Vector> ThisVariable, Vector& rAverageStress, const int edge); /** * this integrates the constitutive law */ void IntegrateStressDamageMechanics(double& rThreshold,double& rDamage, const Vector& rStrainVector, const Vector& rStressVector, const int Edge, const double CharacteristicLength, ConstitutiveLaw::Parameters& rValues, bool& rIsDamaging); /** * this evaluates the constitutive law */ void CalculateEquivalentStress(const array_1d<double, VoigtSize>& rPredictiveStressVector, const Vector& rStrainVector, double& rEquivalentStress, ConstitutiveLaw::Parameters& rValues); /** * this gets the initial threshold of the yield surface */ void GetInitialUniaxialThreshold(ConstitutiveLaw::Parameters& rValues, double& rThreshold); /** * this computes the damage parameter "A" */ void CalculateDamageParameter(ConstitutiveLaw::Parameters& rValues, double& rAParameter, const double CharacteristicLength); /** * this computes the CharacteristicLength of the element */ double CalculateCharacteristicLength(GenericSmallStrainFemDemElement *pCurrentElement); /** * this computes VolumeForce of the element */ Vector& CalculateVolumeForce(Vector& rVolumeForce, const Vector& rN); /** * this computes the damage according to a exp softening */ void CalculateExponentialDamage(double& rDamage, const double DamageParameter, const double UniaxialStress, const double InitialThrehsold); // ************** Methods to compute the tangent constitutive tensor via numerical derivation ************** /** * this computes the Tangent tensor via numerical derivation (perturbations) */ void CalculateTangentTensor(Matrix& rTangentTensor,const Vector& rStrainVectorGP,const Vector& rStressVectorGP,const Matrix& rElasticMatrix, ConstitutiveLaw::Parameters& rValues); /** * this computes the perturbation to the strain */ void CalculatePerturbation(const Vector& rStrainVectorGP, double& rPerturbation, const int Component); /** * this perturbates the strain vector */ void PerturbateStrainVector(Vector& rPerturbedStrainVector, const Vector& rStrainVectorGP, const double Perturbation, const int Component); /** * this integrated the perturbed strain */ void IntegratePerturbedStrain(Vector& rPerturbedStressVector, const Vector& rPerturbedStrainVector, const Matrix& rElasticMatrix, ConstitutiveLaw::Parameters& rValues); /** * this assings the components to the tangent tensor */ void AssignComponentsToTangentTensor(Matrix& rTangentTensor, const Vector& rDeltaStress, const double Perturbation, const int Component); // ***************************************************************** /** * Access for variables on Integration points. * This gives access to variables stored in the constitutive law on each integration point. * Specializations of element must specify the actual interface to the integration points! * Note, that these functions expect a std::vector of values for the specified variable type that * contains a value for each integration point! * SetValueOnIntegrationPoints: set the values for given Variable. * GetValueOnIntegrationPoints: get the values for given Variable. * these methods are: OPTIONAL */ void GetValueOnIntegrationPoints(const Variable<double>& rVariable, std::vector<double>& rValues, const ProcessInfo& rCurrentProcessInfo) override; void GetValueOnIntegrationPoints(const Variable<Vector>& rVariable, std::vector<Vector>& rValues, const ProcessInfo& rCurrentProcessInfo) override; void GetValueOnIntegrationPoints(const Variable<Matrix>& rVariable, std::vector<Matrix>& rValues, const ProcessInfo& rCurrentProcessInfo) override; /** * Calculate variables on Integration points. * This gives access to variables computed in the constitutive law on each integration point. * Specialisations of element must specify the actual interface to the integration points! * Note, that these functions expect a std::vector of values for the specified variable type that * contains a value for each integration point! * CalculateValueOnIntegrationPoints: calculates the values of given Variable. * these methods are: OPTIONAL */ void CalculateOnIntegrationPoints(const Variable<Vector>& rVariable, std::vector<Vector>& rOutput, const ProcessInfo& rCurrentProcessInfo) override; void CalculateOnIntegrationPoints(const Variable<double>& rVariable, std::vector<double>& rOutput, const ProcessInfo& rCurrentProcessInfo) override; void CalculateOnIntegrationPoints(const Variable<Matrix>& rVariable, std::vector<Matrix>& rOutput, const ProcessInfo& rCurrentProcessInfo) override; protected: ///@name Static Member Variables ///@{ ///@} ///@name Member Variables ///@{ Vector mNonConvergedThresholds; // Equivalent stress Vector mThresholds; // Stress mThreshold on edge Vector mDamages; // Converged Damage on each edge Vector mNonConvergedDamages; // Damages at edges of "i" iteration double mThreshold = 0.0; // Converged Threshold double mDamage = 0.0; // Converged Damage // Vector to storage the neigh elements sharing a certain edge std::vector<std::vector<Element*>> mEdgeNeighboursContainer; ///@} ///@name Private Operators ///@{ ///@} ///@name Private Operations ///@{ ///@} ///@name Private Access ///@{ ///@} ///@} ///@name Serialization ///@{ }; // Class GenericSmallStrainFemDemElement ///@} ///@name Type Definitions ///@{ ///@} ///@name Input and output ///@{ ///@} } // namespace Kratos. #endif
36.452316
189
0.717671
[ "geometry", "vector", "3d" ]
16262c7de6c04363e6a60d826657ba3ebc1c2599
2,403
hpp
C++
include/Solver.hpp
Yaohui1996/Yaohui-Master-Thesis
e76f92990c2ce641f3394e7dad789543421878bd
[ "MIT" ]
null
null
null
include/Solver.hpp
Yaohui1996/Yaohui-Master-Thesis
e76f92990c2ce641f3394e7dad789543421878bd
[ "MIT" ]
null
null
null
include/Solver.hpp
Yaohui1996/Yaohui-Master-Thesis
e76f92990c2ce641f3394e7dad789543421878bd
[ "MIT" ]
null
null
null
#ifndef YAOHUI_MASTER_THESIS_SOLVER_HPP #define YAOHUI_MASTER_THESIS_SOLVER_HPP #include "Individual.hpp" #include <cmath> #include <fstream> #include <future> #include <iostream> #include <random> #include <string> #include <vector> namespace yaohui { class Solver { private: size_t gene_cnt_ = 200; // 进化次数 size_t population_cnt_ = 50; // 种群规模 double cross_p_ = 0.8; // 交叉概率 double mutate_p_ = 0.01; // 变异概率 double alpha_ = 0.05; // 选择参数alpha size_t thread_cnt_ = 8; // 线程数目 std::vector<double> weights_; // 选择权重 std::vector<Individual> population_; // 初始种群 Individual first_best_individual_; // 初代最好的解 Individual last_best_individual_; // 末代最好的解 std::vector<double> max_fitness_vec_; // 每代最大的适应度构成的数组 std::vector<double> min_fitness_vec_; // 每代最小适应度构成的数组 std::vector<double> avg_fitness_vec_; // 每代平均适应度构成的数组 std::vector<std::vector<double>> fitness_vec_; // 每代所有适应度 public: Solver() = delete; // 默认构造 Solver(const Solver &) = delete; // 拷贝构造 Solver(Solver &&) = delete; // 移动构造 Solver &operator=(const Solver &) = delete; // 拷贝赋值 Solver &operator=(Solver &&) = delete; // 移动赋值 ~Solver() = default; // 默认析构 Solver(size_t gene_cnt, size_t population_cnt, double cross_p, double mutate_p, double alpha, size_t thread_cnt); const Individual &individual_before_optimize() const; const Individual &individual_after_optimize() const; void do_optimization(); void output_optimization_result(std::string f_name = "processing-data.csv"); private: static bool is_better(const Individual &lhs, const Individual &rhs); void init_weights(); void init_population(); static Individual random_choose(const std::vector<Individual> &population, const std::vector<double> &weight); static void parents_cross(Individual &father, Individual &mother); static std::vector<Individual> birth_single_threading(const std::vector<Individual> &population, const std::vector<double> &weights, double cross_p, size_t child_cnt); std::vector<Individual> birth_multi_threading() const; void child_mutate(Individual &child) const; }; } // namespace yaohui #endif // YAOHUI_MASTER_THESIS_SOLVER_HPP
36.969231
78
0.663337
[ "vector" ]
1629cad69b4b6cd106c100ae85946ce4b03f3e3c
2,676
cpp
C++
source/direct3d9/VertexBufferDescription.cpp
HeavenWu/slimdx
e014bb34b89bbf694d01c8f6d6b6dfa3cba58aac
[ "MIT" ]
85
2015-04-06T05:37:10.000Z
2022-03-22T19:53:03.000Z
source/direct3d9/VertexBufferDescription.cpp
HeavenWu/slimdx
e014bb34b89bbf694d01c8f6d6b6dfa3cba58aac
[ "MIT" ]
10
2016-03-17T11:18:24.000Z
2021-05-11T09:21:43.000Z
source/direct3d9/VertexBufferDescription.cpp
HeavenWu/slimdx
e014bb34b89bbf694d01c8f6d6b6dfa3cba58aac
[ "MIT" ]
45
2015-09-14T03:54:01.000Z
2022-03-22T19:53:09.000Z
#include "stdafx.h" /* * Copyright (c) 2007-2012 SlimDX Group * * 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 <d3d9.h> #include <d3dx9.h> #include "VertexBufferDescription.h" using namespace System; namespace SlimDX { namespace Direct3D9 { bool VertexBufferDescription::operator == ( VertexBufferDescription left, VertexBufferDescription right ) { return VertexBufferDescription::Equals( left, right ); } bool VertexBufferDescription::operator != ( VertexBufferDescription left, VertexBufferDescription right ) { return !VertexBufferDescription::Equals( left, right ); } int VertexBufferDescription::GetHashCode() { return Format.GetHashCode() + Type.GetHashCode() + Usage.GetHashCode() + Pool.GetHashCode() + SizeInBytes.GetHashCode() + FVF.GetHashCode(); } bool VertexBufferDescription::Equals( Object^ value ) { if( value == nullptr ) return false; if( value->GetType() != GetType() ) return false; return Equals( safe_cast<VertexBufferDescription>( value ) ); } bool VertexBufferDescription::Equals( VertexBufferDescription value ) { return ( Format == value.Format && Type == value.Type && Usage == value.Usage && Pool == value.Pool && SizeInBytes == value.SizeInBytes && FVF == value.FVF ); } bool VertexBufferDescription::Equals( VertexBufferDescription% value1, VertexBufferDescription% value2 ) { return ( value1.Format == value2.Format && value1.Type == value2.Type && value1.Usage == value2.Usage && value1.Pool == value2.Pool && value1.SizeInBytes == value2.SizeInBytes && value1.FVF == value2.FVF ); } } }
36.657534
109
0.723468
[ "object" ]
162b07406eac46b0d9c0506a09d88b71ee33fa43
3,649
cpp
C++
Gems/Atom/RHI/Code/Source/RHI/Fence.cpp
BreakerOfThings/o3de
f4c59f868c726470ec910623facd836047d059c3
[ "Apache-2.0", "MIT" ]
11
2021-07-08T09:58:26.000Z
2022-03-17T17:59:26.000Z
Gems/Atom/RHI/Code/Source/RHI/Fence.cpp
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
29
2021-07-06T19:33:52.000Z
2022-03-22T10:27:49.000Z
Gems/Atom/RHI/Code/Source/RHI/Fence.cpp
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
4
2021-07-06T19:24:43.000Z
2022-03-31T12:42:27.000Z
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <Atom/RHI/Fence.h> #include <AzCore/Debug/Profiler.h> namespace AZ { namespace RHI { Fence::~Fence() {} bool Fence::ValidateIsInitialized() const { if (Validation::IsEnabled()) { if (!IsInitialized()) { AZ_Error("Fence", false, "Fence is not initialized!"); return false; } } return true; } ResultCode Fence::Init(Device& device, FenceState initialState) { if (Validation::IsEnabled()) { if (IsInitialized()) { AZ_Error("Fence", false, "Fence is already initialized!"); return ResultCode::InvalidOperation; } } const ResultCode resultCode = InitInternal(device, initialState); if (resultCode == ResultCode::Success) { DeviceObject::Init(device); } return resultCode; } void Fence::Shutdown() { if (IsInitialized()) { if (m_waitThread.joinable()) { m_waitThread.join(); } ShutdownInternal(); DeviceObject::Shutdown(); } } ResultCode Fence::SignalOnCpu() { if (!ValidateIsInitialized()) { return ResultCode::InvalidOperation; } SignalOnCpuInternal(); return ResultCode::Success; } ResultCode Fence::WaitOnCpu() const { if (!ValidateIsInitialized()) { return ResultCode::InvalidOperation; } AZ_PROFILE_SCOPE(RHI, "Fence: WaitOnCpu"); WaitOnCpuInternal(); return ResultCode::Success; } ResultCode Fence::WaitOnCpuAsync(SignalCallback callback) { if (!ValidateIsInitialized()) { return ResultCode::InvalidOperation; } if (!callback) { AZ_Error("Fence", false, "Callback is null."); return ResultCode::InvalidOperation; } if (m_waitThread.joinable()) { m_waitThread.join(); } AZStd::thread_desc threadDesc{ "Fence WaitOnCpu Thread" }; m_waitThread = AZStd::thread(threadDesc, [this, callback]() { ResultCode resultCode = WaitOnCpu(); if (resultCode != ResultCode::Success) { AZ_Error("Fence", false, "Failed to call WaitOnCpu in async thread."); } callback(); }); return ResultCode::Success; } ResultCode Fence::Reset() { if (!ValidateIsInitialized()) { return ResultCode::InvalidOperation; } ResetInternal(); return ResultCode::Success; } FenceState Fence::GetFenceState() const { if (!ValidateIsInitialized()) { return FenceState::Reset; } return GetFenceStateInternal(); } } }
24.993151
100
0.468347
[ "3d" ]
16350f0a0a0d88a770aaf2743613d88cd1b956c1
11,072
cpp
C++
src/cs-core/GraphicsEngine.cpp
FellegaraR/cosmoscout-vr
e04e1ac9c531106693a965bb03d3064f3a6179c6
[ "BSL-1.0", "Apache-2.0", "MIT" ]
302
2019-03-05T08:05:03.000Z
2022-03-16T22:35:21.000Z
src/cs-core/GraphicsEngine.cpp
FellegaraR/cosmoscout-vr
e04e1ac9c531106693a965bb03d3064f3a6179c6
[ "BSL-1.0", "Apache-2.0", "MIT" ]
230
2019-07-30T13:26:09.000Z
2022-03-11T11:21:06.000Z
src/cs-core/GraphicsEngine.cpp
FellegaraR/cosmoscout-vr
e04e1ac9c531106693a965bb03d3064f3a6179c6
[ "BSL-1.0", "Apache-2.0", "MIT" ]
24
2019-07-22T08:00:49.000Z
2022-01-25T10:55:17.000Z
//////////////////////////////////////////////////////////////////////////////////////////////////// // This file is part of CosmoScout VR // // and may be used under the terms of the MIT license. See the LICENSE file for details. // // Copyright: (c) 2019 German Aerospace Center (DLR) // //////////////////////////////////////////////////////////////////////////////////////////////////// #include "GraphicsEngine.hpp" #include "../cs-graphics/ClearHDRBufferNode.hpp" #include "../cs-graphics/ToneMappingNode.hpp" #include "../cs-utils/utils.hpp" #include "logger.hpp" #include <GL/glew.h> #include <VistaKernel/DisplayManager/VistaDisplayManager.h> #include <VistaKernel/DisplayManager/VistaProjection.h> #include <VistaKernel/DisplayManager/VistaViewport.h> #include <VistaKernel/DisplayManager/VistaWindow.h> #include <VistaKernel/GraphicsManager/VistaOpenGLNode.h> #include <VistaKernel/GraphicsManager/VistaSceneGraph.h> #include <VistaKernel/VistaSystem.h> #include <VistaKernelOpenSGExt/VistaOpenSGMaterialTools.h> namespace cs::core { //////////////////////////////////////////////////////////////////////////////////////////////////// GraphicsEngine::GraphicsEngine(std::shared_ptr<core::Settings> settings) : mSettings(std::move(settings)) , mShadowMap(std::make_shared<graphics::ShadowMap>()) { // Tell the user what's going on. logger().debug("Creating GraphicsEngine."); logger().info("OpenGL Vendor: {}", glGetString(GL_VENDOR)); logger().info("OpenGL Version: {}", glGetString(GL_VERSION)); auto* pSG = GetVistaSystem()->GetGraphicsManager()->GetSceneGraph(); mSettings->mGraphics.pEnableVsync.connect([](bool value) { GetVistaSystem() ->GetDisplayManager() ->GetWindows() .begin() ->second->GetWindowProperties() ->SetVSyncEnabled(value); }); // setup shadows --------------------------------------------------------------------------------- mShadowMap->setEnabled(false); mShadowMap->setResolution(static_cast<uint32_t>(mSettings->mGraphics.pShadowMapResolution.get())); mShadowMap->setBias(mSettings->mGraphics.pShadowMapBias.get() * 0.0001F); pSG->NewOpenGLNode(pSG->GetRoot(), mShadowMap.get()); calculateCascades(); mSettings->mGraphics.pEnableShadows.connect([this](bool val) { mShadowMap->setEnabled(val); }); mSettings->mGraphics.pEnableShadowsFreeze.connect( [this](bool val) { mShadowMap->setFreezeCascades(val); }); mSettings->mGraphics.pShadowMapResolution.connect( [this](int val) { mShadowMap->setResolution(static_cast<uint32_t>(val)); }); mSettings->mGraphics.pShadowMapCascades.connect([this](int /*unused*/) { calculateCascades(); }); mSettings->mGraphics.pShadowMapBias.connect( [this](float val) { mShadowMap->setBias(val * 0.0001f); }); mSettings->mGraphics.pShadowMapSplitDistribution.connect( [this](float /*unused*/) { calculateCascades(); }); mSettings->mGraphics.pShadowMapRange.connect( [this](glm::vec2 /*unused*/) { calculateCascades(); }); mSettings->mGraphics.pShadowMapExtension.connect( [this](glm::vec2 /*unused*/) { calculateCascades(); }); // setup HDR buffer ------------------------------------------------------------------------------ int multiSamples = GetVistaSystem() ->GetDisplayManager() ->GetWindows() .begin() ->second->GetWindowProperties() ->GetMultiSamples(); mHDRBuffer = std::make_shared<graphics::HDRBuffer>(multiSamples); // Create a node which clears the HDRBuffer at the beginning of a frame (this will be enabled only // if HDR rendering is enabled). mClearNode = std::make_shared<graphics::ClearHDRBufferNode>(mHDRBuffer); auto* clearGLNode = pSG->NewOpenGLNode(pSG->GetRoot(), mClearNode.get()); VistaOpenSGMaterialTools::SetSortKeyOnSubtree( clearGLNode, static_cast<int>(utils::DrawOrder::eClearHDRBuffer)); // Create a node which performas tonemapping of the HDRBuffer at the end of a frame (this will be // enabled only if HDR rendering is enabled). mToneMappingNode = std::make_shared<graphics::ToneMappingNode>(mHDRBuffer); auto* toneMappingGLNode = pSG->NewOpenGLNode(pSG->GetRoot(), mToneMappingNode.get()); VistaOpenSGMaterialTools::SetSortKeyOnSubtree( toneMappingGLNode, static_cast<int>(utils::DrawOrder::eToneMapping)); mSettings->mGraphics.pGlareIntensity.connectAndTouch( [this](float val) { mToneMappingNode->setGlareIntensity(val); }); mSettings->mGraphics.pGlareQuality.connectAndTouch( [this](uint32_t val) { mHDRBuffer->setGlareQuality(val); }); mSettings->mGraphics.pGlareMode.connectAndTouch( [this](graphics::HDRBuffer::GlareMode mode) { mHDRBuffer->setGlareMode(mode); }); mSettings->mGraphics.pToneMappingMode.connectAndTouch( [this](graphics::ToneMappingNode::ToneMappingMode mode) { mToneMappingNode->setToneMappingMode(mode); }); mSettings->mGraphics.pEnableBicubicGlareFilter.connectAndTouch( [this](bool enable) { mToneMappingNode->setEnableBicubicGlareFilter(enable); }); mSettings->mGraphics.pExposureCompensation.connectAndTouch( [this](float val) { mToneMappingNode->setExposureCompensation(val); }); mSettings->mGraphics.pExposureAdaptionSpeed.connectAndTouch( [this](float val) { mToneMappingNode->setExposureAdaptionSpeed(val); }); mSettings->mGraphics.pAutoExposureRange.connectAndTouch([this](glm::vec2 val) { mToneMappingNode->setMinAutoExposure(val[0]); mToneMappingNode->setMaxAutoExposure(val[1]); }); mSettings->mGraphics.pEnableHDR.connectAndTouch([clearGLNode, toneMappingGLNode](bool enabled) { clearGLNode->SetIsEnabled(enabled); toneMappingGLNode->SetIsEnabled(enabled); }); mSettings->mGraphics.pEnableAutoExposure.connectAndTouch( [this](bool enabled) { mToneMappingNode->setEnableAutoExposure(enabled); }); mSettings->mGraphics.pExposure.connectAndTouch([this](float value) { if (!mSettings->mGraphics.pEnableAutoExposure.get()) { mToneMappingNode->setExposure(value); } }); } //////////////////////////////////////////////////////////////////////////////////////////////////// GraphicsEngine::~GraphicsEngine() { try { // Tell the user what's going on. logger().debug("Deleting GraphicsEngine."); } catch (...) {} } //////////////////////////////////////////////////////////////////////////////////////////////////// void GraphicsEngine::registerCaster(graphics::ShadowCaster* caster) { mShadowMap->registerCaster(caster); } //////////////////////////////////////////////////////////////////////////////////////////////////// void GraphicsEngine::unregisterCaster(graphics::ShadowCaster* caster) { mShadowMap->deregisterCaster(caster); } //////////////////////////////////////////////////////////////////////////////////////////////////// void GraphicsEngine::update(glm::vec3 const& sunDirection) { mShadowMap->setSunDirection(VistaVector3D(sunDirection.x, sunDirection.y, sunDirection.z)); // Update projection. When the sensor size control is enabled, we will calculate the projection // plane extents based on the screens aspect ratio, the given sensor diagonal and sensor focal // length. if (mSettings->pEnableSensorSizeControl.get()) { VistaViewport* pViewport(GetVistaSystem()->GetDisplayManager()->GetViewports().begin()->second); int sizeX = 0; int sizeY = 0; pViewport->GetViewportProperties()->GetSize(sizeX, sizeY); double aspect = 1.0 * sizeX / sizeY; VistaProjection::VistaProjectionProperties* pProjProps = pViewport->GetProjection()->GetProjectionProperties(); double height = mSettings->mGraphics.pSensorDiagonal.get() / std::sqrt(std::pow(aspect, 2.0) + 1.0); height /= mSettings->mGraphics.pFocalLength.get(); double width = aspect * height; pProjProps->SetProjPlaneExtents(-width / 2, width / 2, -height / 2, height / 2); pProjProps->SetProjPlaneMidpoint(0, 0, -1); } // Update exposure. If auto exposure is enabled, the property will reflect the exposure chosen by // the tonemapping node. if (mSettings->mGraphics.pEnableAutoExposure.get()) { mSettings->mGraphics.pExposure = mToneMappingNode->getExposure(); } if (mSettings->mGraphics.pEnableHDR.get()) { pAverageLuminance = mToneMappingNode->getLastAverageLuminance(); pMaximumLuminance = mToneMappingNode->getLastMaximumLuminance(); } } //////////////////////////////////////////////////////////////////////////////////////////////////// std::shared_ptr<graphics::ShadowMap> GraphicsEngine::getShadowMap() const { return mShadowMap; } //////////////////////////////////////////////////////////////////////////////////////////////////// std::shared_ptr<graphics::HDRBuffer> GraphicsEngine::getHDRBuffer() const { return mHDRBuffer; } //////////////////////////////////////////////////////////////////////////////////////////////////// bool glDebugOnlyErrors = true; void GLAPIENTRY oglMessageCallback(GLenum /*source*/, GLenum type, GLuint /*id*/, GLenum severity, GLsizei /*length*/, const GLchar* message, const void* /*userParam*/) { if (type == GL_DEBUG_TYPE_ERROR || GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR) { if (severity == GL_DEBUG_SEVERITY_HIGH) { logger().critical(message); } else { logger().error(message); } } else if (!glDebugOnlyErrors) { if (severity == GL_DEBUG_SEVERITY_NOTIFICATION) { logger().debug(message); } else { logger().warn(message); } } } void GraphicsEngine::enableGLDebug(bool onlyErrors) { glDebugOnlyErrors = onlyErrors; glEnable(GL_DEBUG_OUTPUT); glDebugMessageCallback(oglMessageCallback, nullptr); } void GraphicsEngine::disableGLDebug() { glDisable(GL_DEBUG_OUTPUT); glDebugMessageCallback(nullptr, nullptr); } //////////////////////////////////////////////////////////////////////////////////////////////////// void GraphicsEngine::calculateCascades() { float nearEnd = mSettings->mGraphics.pShadowMapRange.get().x; float farEnd = mSettings->mGraphics.pShadowMapRange.get().y; int count = mSettings->mGraphics.pShadowMapCascades.get(); std::vector<float> splits(count + 1); for (size_t i(0); i < splits.size(); ++i) { float alpha = static_cast<float>(i) / static_cast<float>(count); alpha = std::pow(alpha, mSettings->mGraphics.pShadowMapSplitDistribution.get()); splits[i] = glm::mix(nearEnd, farEnd, alpha); } mShadowMap->setCascadeSplits(splits); mShadowMap->setSunNearClipOffset(mSettings->mGraphics.pShadowMapExtension.get().x); mShadowMap->setSunFarClipOffset(mSettings->mGraphics.pShadowMapExtension.get().y); } //////////////////////////////////////////////////////////////////////////////////////////////////// } // namespace cs::core
41.007407
100
0.619039
[ "vector" ]