hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
33d7a0bdc6fa364dbda6bbde191b68032f6b6315
9,778
cpp
C++
src/core/type/dynobject.cpp
eXl-Nic/eXl
a5a0f77f47db3179365c107a184bb38b80280279
[ "MIT" ]
null
null
null
src/core/type/dynobject.cpp
eXl-Nic/eXl
a5a0f77f47db3179365c107a184bb38b80280279
[ "MIT" ]
null
null
null
src/core/type/dynobject.cpp
eXl-Nic/eXl
a5a0f77f47db3179365c107a184bb38b80280279
[ "MIT" ]
null
null
null
/* Copyright 2009-2021 Nicolas Colombe 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 <core/type/dynobject.hpp> #include <core/type/type.hpp> #include <core/type/arraytype.hpp> #ifdef EXL_LUA #include <core/lua/luamanager.hpp> #endif #define MAKE_OWNER(x) (Type const*)((size_t)(x) | 1) #define GET_PTR(x) (Type const*)((size_t)(x) & ~3) #define IS_OWNER(x) (((size_t)(x) & 3)==1) namespace eXl { ConstDynObject::ConstDynObject() : m_Mem(nullptr) , m_Type(nullptr) { } ConstDynObject::ConstDynObject(const Type* iType,void const* iBuffer) : m_Mem((void*)iBuffer) , m_Type(iType) { } ConstDynObject::~ConstDynObject() { if(IS_OWNER(m_Type) && m_Type!=nullptr && m_Mem) { GetType()->Destroy(m_Mem); } } ConstDynObject ConstDynObject::ConstRef() const { ConstDynObject ref; ref.m_Type = GET_PTR(m_Type); ref.m_Mem = m_Mem; return std::move(ref); } void ConstDynObject::SetTypeConst(const Type* iType,void const* iMem) { if(IS_OWNER(m_Type) && m_Type!=nullptr && m_Mem) { GetType()->Destroy(m_Mem); } m_Mem = (void*)iMem; m_Type = iType; } const Type* ConstDynObject::GetType()const{return GET_PTR(m_Type);} Err ConstDynObject::GetField(unsigned int i,ConstDynObject& oObj)const { if(!IsValid()) RETURN_FAILURE; const TupleType* tupleType = GetType()->IsTuple(); if(tupleType!=nullptr) { Type const* fieldType; void const* field=tupleType->GetField(GetBuffer(),i,fieldType); if(field != nullptr) { oObj.SetTypeConst(fieldType,field); RETURN_SUCCESS; } } RETURN_FAILURE; } Err ConstDynObject::GetField(TypeFieldName iName,ConstDynObject& oObj)const { if(!IsValid()) RETURN_FAILURE; const TupleType* tupleType = GetType()->IsTuple(); if(tupleType!=nullptr) { Type const* fieldType; void const* field=tupleType->GetField(GetBuffer(), iName, fieldType); if(field != nullptr) { oObj.SetTypeConst(fieldType,field); RETURN_SUCCESS; } } RETURN_FAILURE; } Err ConstDynObject::GetField(unsigned int i,DynObject& oObj)const { RETURN_FAILURE; } Err ConstDynObject::GetField(TypeFieldName iName,DynObject& oObj)const { RETURN_FAILURE; } Err ConstDynObject::GetElement(unsigned int i,ConstDynObject& oObj)const { if(!IsValid()) RETURN_FAILURE; ArrayType const* arrayT = ArrayType::DynamicCast(GetType()); if(arrayT != nullptr) { void const* elem = arrayT->GetElement(GetBuffer(),i); if(elem != nullptr) { oObj.SetTypeConst(arrayT->GetElementType(),elem); RETURN_SUCCESS; } } RETURN_FAILURE; } Err ConstDynObject::GetElement(unsigned int i,DynObject& oObj)const { RETURN_FAILURE; } ConstDynObject::ConstDynObject(ConstDynObject&& iOther) { m_Type = iOther.m_Type; m_Mem = iOther.m_Mem; iOther.m_Mem = nullptr; iOther.m_Type = nullptr; } DynObject::DynObject():ConstDynObject(nullptr,nullptr){} DynObject::DynObject(const Type* iType,void* iBuffer) : ConstDynObject(iType,iBuffer) { } DynObject::~DynObject() { } DynObject::DynObject(DynObject&& iOther) : ConstDynObject(std::move(iOther)) { } DynObject& DynObject::operator=(DynObject&& iOther) { this->~DynObject(); new(this) DynObject(std::move(iOther)); return *this; } DynObject DynObject::Ref() const { DynObject ref; ref.m_Type = GET_PTR(m_Type); ref.m_Mem = m_Mem; return std::move(ref); } void DynObject::Release() { m_Type = nullptr; m_Mem = nullptr; } #ifdef EXL_LUA DynObject::DynObject(const Type* iType, luabind::object const& iObj):ConstDynObject(iType,nullptr) { FromLua(iType,iObj); } #endif void DynObject::Swap(DynObject& iOther) { void* tempMem = iOther.m_Mem; Type const* tempType = iOther.m_Type; iOther.m_Mem = m_Mem; iOther.m_Type = m_Type; m_Mem = tempMem; m_Type = tempType; } DynObject::DynObject(ConstDynObject const* iObj):ConstDynObject(nullptr,nullptr) { if(iObj != nullptr) { Type const* type = iObj->GetType(); void* data = nullptr; if(type != nullptr && iObj->IsValid()) { data = type->Alloc(); type->Assign_Uninit(type,iObj->GetBuffer(),data); } SetType(type,data,true); } } DynObject::DynObject(DynObject const& iObj) { Type const* type = iObj.GetType(); void* data = nullptr; if(type != nullptr && iObj.IsValid()) { data = type->Alloc(); type->Assign_Uninit(type,static_cast<ConstDynObject const&>(iObj).GetBuffer(), data); } SetType(type,data,true); } DynObject& DynObject::operator=(DynObject const& iObj) { Type const* type = iObj.GetType(); void* data = nullptr; if(type != nullptr && iObj.IsValid()) { data = type->Alloc(); type->Assign_Uninit(type,((ConstDynObject const&)iObj).GetBuffer(),data); } SetType(type,data,true); return *this; } bool DynObject::IsOwner()const{return IS_OWNER(m_Mem);} void DynObject::SetType(const Type* iType,void* iMem,bool makeOwner) { if(IS_OWNER(m_Type) && m_Type!=nullptr && m_Mem != nullptr) { GetType()->Destroy(m_Mem); } if(iType != nullptr && iMem != nullptr) { m_Mem = iMem; if(makeOwner && iMem!=nullptr) { m_Type = MAKE_OWNER(iType); } else { m_Type = iType; } } else { m_Type = iType; m_Mem = nullptr; } } Err DynObject::GetField(unsigned int i,DynObject& oObj) { if(!IsValid()) RETURN_FAILURE; const TupleType* tupleType = GetType()->IsTuple(); if(tupleType!=nullptr) { Type const* fieldType; void* field=tupleType->GetField(GetBuffer(),i,fieldType); if(field != nullptr) { oObj.SetType(fieldType,field,false); RETURN_SUCCESS; } } RETURN_FAILURE; } Err DynObject::GetField(TypeFieldName iName,DynObject& oObj) { if(!IsValid()) RETURN_FAILURE; const TupleType* tupleType = GetType()->IsTuple(); if(tupleType!=nullptr) { Type const* fieldType; void* field=tupleType->GetField(GetBuffer(),iName,fieldType); if(field != nullptr) { oObj.SetType(fieldType,field,false); RETURN_SUCCESS; } } RETURN_FAILURE; } Err DynObject::GetElement(unsigned int i,DynObject& oObj) { if(!IsValid()) RETURN_FAILURE; ArrayType const* arrayT = ArrayType::DynamicCast(GetType()); if(arrayT != nullptr) { void* elem = arrayT->GetElement(GetBuffer(),i); if(elem != nullptr) { oObj.SetType(arrayT->GetElementType(),elem,false); RETURN_SUCCESS; } } RETURN_FAILURE; } #ifdef EXL_LUA void DynObject::FromLua(const Type* iType, luabind::object const& iObj) { if(iType != nullptr && iObj.is_valid()) { if(!IsValid() || IsOwner()) { void* newMem = nullptr; Err err = iType->ConvertFromLua(iObj,newMem); if(err) { SetType(iType,newMem,true); } } else { if(iType == GetType()) { void* mem = GetBuffer(); Err err = iType->ConvertFromLua(iObj,mem); } else { LOG_WARNING << "Err : conversion failed" << "\n"; } } } } #endif /*void ConstDynObject::ToLua(luabind::object& iObj)const { lua_State* interpreter = iObj.interpreter(); if(interpreter == nullptr) { interpreter = LuaManager::GetLocalState(); } eXl_ASSERT_MSG(interpreter != nullptr, "Could not get interpreter"); if(interpreter != nullptr) { if(IsValid()) { iObj = GetType()->ConvertToLua(GetBuffer(),interpreter); } else { iObj = luabind::object(); } } }*/ #ifdef EXL_LUA luabind::object ConstDynObject::ToLua(lua_State* interpreter)const { /*lua_State* interpreter = iObj.interpreter(); if(interpreter == nullptr) { interpreter = LuaManager::GetLocalState(); }*/ eXl_ASSERT_MSG(interpreter != nullptr, "Could not get interpreter"); if(interpreter != nullptr) { if(IsValid()) { return GetType()->ConvertToLua(GetBuffer(),interpreter); } } return luabind::object(); } #endif Err DynObject::SetArraySize(unsigned int iSize) { ArrayType const* arrayType = ArrayType::DynamicCast(GetType()); if(arrayType == nullptr) RETURN_FAILURE; return arrayType->SetArraySize(GetBuffer(),iSize); } }
24.14321
460
0.629679
eXl-Nic
33d93ec2322125fa02ebf73b04c1ea4047fd8883
32,515
cpp
C++
src/biomolecules/spexpert/waittasklist.cpp
biomolecules/spexpert
929786ff9a1fb021b306bc705739405563cad46d
[ "BSD-3-Clause" ]
2
2022-01-14T17:58:41.000Z
2022-01-14T17:58:56.000Z
src/biomolecules/spexpert/waittasklist.cpp
biomolecules/spexpert
929786ff9a1fb021b306bc705739405563cad46d
[ "BSD-3-Clause" ]
10
2018-11-15T12:50:44.000Z
2018-11-21T11:32:57.000Z
src/biomolecules/spexpert/waittasklist.cpp
biomolecules/spexpert
929786ff9a1fb021b306bc705739405563cad46d
[ "BSD-3-Clause" ]
null
null
null
#include "waittasklist.h" #include "waittask.h" #include "waittasks.h" #include <QMutex> #include <QThread> #include <QTimer> /*! \namespace WaitTaskListTraits \brief Namespace containing WaitTaskList's enums and helper structures */ /*! \enum WaitTaskListTraits::WaitFor \brief This scoped enum contains the list of tasks for faster runtime identification. \sa TaskItem \var WaitTaskListTraits::None \brief None \var WaitTaskListTraits::Delay \brief DelayWaitTask \var WaitTaskListTraits::WinSpec \brief WinSpecWaitTask \var WaitTaskListTraits::Motor \brief StageControlWaitTask \var WaitTaskListTraits::Spectrograph \brief for future use \var WaitTaskListTraits::Other1 \brief for future use \var WaitTaskListTraits::Other2 \brief for future use \var WaitTaskListTraits::Other3 \brief for future use \var WaitTaskListTraits::Other4 \brief for future use \fn WaitTaskListTraits::operator|(WaitTaskListTraits::WaitFor a, WaitTaskListTraits::WaitFor b) \brief logical OR operator \fn WaitTaskListTraits::operator&(WaitTaskListTraits::WaitFor a, WaitTaskListTraits::WaitFor b) \brief logical AND operator \fn WaitTaskListTraits::operator~(WaitTaskListTraits::WaitFor a) \brief logical negation operator \fn WaitTaskListTraits::operator|=(WaitTaskListTraits::WaitFor& a, WaitTaskListTraits::WaitFor b) \brief logical assignment OR operator \fn WaitTaskListTraits::operator&=(WaitTaskListTraits::WaitFor& a, WaitTaskListTraits::WaitFor b) \brief logical assignment AND operator */ /*! \struct WaitTaskListTraits::TaskItem \brief Container for WaitTask attaching to it its type for faster runtime identification. \sa TaskType \var WaitTaskListTraits::TaskItem::task \brief the WaitTask \var WaitTaskListTraits::TaskItem::waitFor \brief the WaitFor \fn WaitTaskListTraits::TaskItem::TaskItem(WaitFor wf, WaitTask * wt) \brief Constructs the TaskItem stuct. \param wf type of the task \param wt a pointer to the task */ /*! \class WaitExpTask \brief This class contains the WaitTask in the WaitTaskListTraits::TaskItem, which will be submited to the list of tasks which will be waited for, when added to the WaitTaskList. Each WaitTask should be handled by some WaitingTask to have some effect, so there shouldn't be any WaitExpTask added to the WaitTaskList without WaitingTask added somewhere after it. */ /*! \brief Constructs WaitExpTask object. */ WaitExpTask::WaitExpTask(const WaitTaskListTraits::TaskItem & waitTask, QObject *parent) : ExpTask(parent), waitTaskItem(waitTask) { } /*! \brief Sets delayed destruction of the task also for the contained WaitTask. Viz ExpTask::setDelayedDelete() */ void WaitExpTask::setDelayedDelete(bool blDelayedDelete) { waitTaskItem.task->setDelayedDelete(blDelayedDelete); ExpTask::setDelayedDelete(blDelayedDelete); } /*! \fn WaitExpTask::getWaitTaskItem() \brief Returns contained WaitTaskListTraits::TaskItem. This method is used in WaitTaskList::addTask(), where the contained WaitTask obtaines its id. */ // signals /*! \fn WaitExpTask::startWaitTask(unsigned int id) \brief This signal is emited from the start() method, and in WaitTaskList is connected to the WaitTaskList::onStartWaitTask() which submits contained WaitTask to the WaitWorker. */ /*! \brief emits startWaitTask() signal, to start waiting for this task and finished() signal to finish this task. The waiting for the task is then handled by the WaitingTask. */ void WaitExpTask::start() { emit startWaitTask(waitTaskItem.task->id()); emit finished(); } /*! \brief stops adding of the WaitTask to the WaitWorker. Do not use it. */ void WaitExpTask::stop() { ExpTask::stop(); } /*! \brief WaitExpTask::~WaitExpTask */ WaitExpTask::~WaitExpTask() { } /*! \var WaitExpTask::waitTaskItem \brief contained WaitTaskItem */ /*! \class WaitingTask \brief Handles waiting for all WaitExpTask objects previously added to the WaitTaskList. */ /*! \brief Constructs WaitingTask object. \param parent Parent QObject in Qt's ownership system. */ WaitingTask::WaitingTask(QObject *parent) : ExpTask(parent) { } /*! \brief This method resets the number of planned executions of the WaitingTask resetting also the WaitTask objects which will be waited for. */ void WaitingTask::restartTimesExec() { currIds_ = ids_; ExpTask::restartTimesExec(); } /*! \fn WaitingTask::setIds(const QSet<unsigned int> & ids) \brief This method sets the ids of WaitTask objects which will be waited for. It is used in WaitTaskList::addWaitTask() method which is called from the WaitTaskList::addTask() method. \param ids list of ids of tasks which will be waited for. */ // signals /*! \fn WaitingTask::waitTaskFinished(unsigned int id) \brief This signal is emited from the onWaitTaskFinished() method and connected to the WaitTaskList::onWaitTaskFinished() in the WaitTaskList::addWaitTask() method which is called from the WaitTaskList::addTask() method. \param id of finished WaitTask */ // slots /*! \brief This slot is connected to all WaitTask object, which was added before the addition of this WaitingTask and not already handled by any preceeding WaitingTask. It emits waitTaskFinished() signal and if all WaitTask objects which are connected to this WaitingTask have been already executed, it emits finished() signal. */ void WaitingTask::onWaitTaskFinished(unsigned int id) { currIds_.remove(id); emit waitTaskFinished(id); if (currIds_.isEmpty()) { emit finished(); } } /*! \brief This method starts the waiting for all connected WaitTask objects. See onWaitTaskFinished() slot. */ void WaitingTask::start() { if (currIds_.isEmpty()) { emit finished(); } } /*! \brief Stops the waiting. */ void WaitingTask::stop() { ExpTask::stop(); } /*! \brief Destoryes WaitingTask object. */ WaitingTask::~WaitingTask() { } /*! \var WaitingTask::currIds_ \brief Ids of WaitTask object, which are or will be currently waited for. \var WaitingTask::ids_ \brief Ids of all WaitTask objects which are connected to this WaitingTask */ /*! \class WaitTaskList \brief This class provides interface for executing tasks which waits for some process to be finished. It behaves like ExpTaskList but for cases when tasks with special meaning is added: WaitExpTask, WaitingTask, ExpTaskList, ForkJoinTask. When WaitExpTask is added, the contained WaitTask is extracted by the WaitExpTask::getWaitTaskItem() method and unique id is attributed to this WaitTask and WaitExpTask::startWaitTask() signal is connected to the onStartWaitTask() slot. When WaitingTask is added, all the previously added WaitTask objects, which have not been handled by any WaitingTask are connected to this WaitingTask by adding their ids by WaitingTask::setIds() method and connecting their WaitTask::waitTaskFinished() to the WaitingTask::onWaitTaskFinished() slot. The WaitingTask's WaitingTask::waitTaskFinished() signal is connected to the WaitTaskList::onWaitTaskFinished() which handles clean up of WaitTask object of no further use. The added WaitTask is also set as handled by the WaitTask::setHandled() method. When ExpTaskList is added, all the contained ExpTask objects are extracted from it and submited recursively to the same process of ExpTask adding as described above. When ForkJoinTask is added, all the contained ExpTask objects from all the contained threads are extracted from it and submited recursively to the same process of ExpTask adding as described above. The threads is walked through succesively from the thread no. 0. This means, that all so far unhandled WaitTask objects will be handled by the first encounteder Waiting task in the thread with lowest number. When, the start() slot is invoked, the underlying QThread and ExpTaskList is started. When the WaitExpTask comes to execution, the WaitTaskList::onStartWaitTask() slot is executed, where the inner WaitTask connection to some WaitingTask is controlled and if so, the WaitTask is submited to the WaitWorker by emiting WaitTaskList::startWaitTaskInWorker() signal. WaitWorker waits WaitTask's WaitTask::initialDelay() and then runs WaitTask::start() slot. Then it periodically controlls WaitTask::running(). If it returns false, it executes WaitTask::finish() slot. This slot emits WaitTask::waitTaskFinished() signal which is connected to the WaitingTask::onWaitTaskFinished() slot in which the WaitTask is removed from the list of tasks, the WaitingTask is waiting for and then the WaitingTask emits WaitingTask::waitTaskFinished() signal which is connected to the WaitTaskList::onWaitTaskFinished() slot. In this slot, it is decided, if the WaitTask should be deleted instantly or the deletion will be delayed, see ExpTask::delayedDelete() and WaitTask::delayedDelete(). When the WaitingTask comes to execution, its execution will not be finished until the all WaitTask's connected to this WaitingTask is not finished. When the ForkJoinTask comes to execution, its execution will not be finished until all threads is not finished (this is a same behaviour of ForkJoinTask as if it is only in the ExpTaskList). When all ExpTasks are executed, the ExpTaskList's taskListFinished() method is reimplemented to delete the contained thread is deleted (only if the delayedDelete() is false and curTimesExec() is 1 or less). The execution can be stopped by the stop() slot. */ /*! \brief Creates WaitTaskList object. \param parent Parent in Qt's ownership system. */ WaitTaskList::WaitTaskList(QObject *parent) : ExpTaskList(parent) { thread = nullptr; blQuit_ = false; // variables, which are used when the execution is interupted to wait for // ending both the contained ExpTaskList and WaitWorker. blTaskListFinished_ = false; blWaitWorkerFinished_ = false; } /*! \brief Adds task to the list and calls the addWaitTask() method, which treats the special cases connected to the handling of WaitTask objects. */ void WaitTaskList::addTask(ExpTaskListTraits::TaskItem tsk) { if (tsk.task->currTimesExec() > 0) { addWaitTask(tsk); ExpTaskList::addTask(tsk); } } /*! \fn WaitTaskList::quit() \brief returns true if setQuit() was set to true. \fn WaitTaskList::taskListIsFinished() \brief returns true if setTaskListFinished() was set to true. \fn WaitTaskList::waitWorkerIsFinished() \brief returns true if setWaitWorkerFinished() was set to true. \fn WaitTaskList::setQuit(bool blQuit) \brief setQuit() \fn WaitTaskList::setTaskListFinished(bool blTaskListFinished) \brief setTaskListFinished() \fn WaitTaskList::setWaitWorkerFinished(bool blWaitWorkerFinished) \brief setWaitWorkerFinished() */ // signals /*! \fn WaitTaskList::startWaitTaskInWorker(WaitTaskListTraits::TaskItem waitTaskItem) \brief Emitted from the onStartWaitTask() method and connected to the WaitTaskList::waitWorker's WaitWorker::addWaitTask() slot. \fn WaitTaskList::stopWorker() \brief Emitted from the stop() slot and from the destructor, to stop WaitWorker. It is connected to the WaitWorker's WaitWorker::stop() slot. */ /*! \brief Starts execution of the ExpTask objects in WaitTaskList and builds the new thread, which can execute all WaitTask's which are wrapped in the WaitExpTask objects inserted in the WaitTaskList. The execution can be stopped by the stop() method. See addTask() for more details. */ void WaitTaskList::start() { if (!running()) { setTaskListFinished(false); setWaitWorkerFinished(false); if (thread) { ExpTaskList::start(); } else { buildThread(); ExpTaskList::start(); } } } /*! \brief Stops the WaitTaskList execution. */ void WaitTaskList::stop() { if (running()) { setQuit(true); if (thread) { emit stopWorker(); } ExpTaskList::stop(); } } /*! \brief This slot is connected to WaitExpTask::startWaitTask() signals of the all contained WaitExpTask objects and if the corresponding WaitTask is handled by some WaitingTask, it is added to the WaitWorker to be waited for. \param id Id of WaitTask in WaitTaskList's id system. */ void WaitTaskList::onStartWaitTask(unsigned int id) { WaitTaskListTraits::TaskItem waitTaskItem = waitTasks.value(id); // if (waitTaskItem.waitFor == WaitTaskListTraits::WaitFor::Delay) { // qDebug() << "WaitTaskList::onStartWaitTask: delay id" << id; // } // if (waitTaskItem.waitFor == WaitTaskListTraits::WaitFor::WinSpec) { // qDebug() << "WaitTaskList::onStartWaitTask: WinSpec id" << id; // } // if (waitTaskItem.waitFor == WaitTaskListTraits::WaitFor::Motor) { // qDebug() << "WaitTaskList::onStartWaitTask: motor id" << id; // } if (waitTaskItem.task->handled()) { emit startWaitTaskInWorker(waitTaskItem); } } /*! \brief This slot is connected to the WaitingTask::waitTaskFinished() signal which is emited from the current running WaitingTask::onWaitTaskFinished() slot connected to the WaitTask::waitTaskFinished() signal of the currently executed WaitTask objects. \param id Id of WaitTask in WaitTaskList's id system. */ void WaitTaskList::onWaitTaskFinished(unsigned int id) { WaitTaskListTraits::TaskItem waitTaskItem = waitTasks.value(id); if (currTimesExec() < 2 && !delayedDelete() && waitTaskItem.task && !waitTaskItem.task->delayedDelete()) { waitTasks.remove(id); delete waitTaskItem.task; } } /*! \brief This method is invoked only when the thread was quited by calling waitWorker's WaitWorker::stop() method in a reaction to the WaitWorker::quitFinished() signal. The WaitWorker::stop() method is called only after stop() is invoked and from the WaitTaskList::~WaitTaskList() destructor. It deletes thread and all the contained WaitTask objects. If this method is called earlier than the taskListFinished() (the taskListIsFinished() is false), the waitWorkerFinished() is set to true by the setWaitWorkerFinished(true) method. In the opposite case, the taskListFinished() method is called once more, to finish WaitTaskList finishing. */ void WaitTaskList::onWorkerQuitFinished() { // it controls if WaitWorker was finished by the WaitTaskList::stop() // method, which sets quit() to true or by the destructor, which leaves // quit at false value. if (quit()) { if (thread) { thread->quit(); thread->wait(); delete thread; thread = nullptr; } for (QMap<unsigned int, WaitTaskListTraits::TaskItem>::iterator it = waitTasks.begin(); it != waitTasks.end(); ++it) { delete it->task; } waitTasks.clear(); // this controls, if ExpTaskList has already finished. if (taskListIsFinished()) { setTaskListFinished(false); setQuit(false); ExpTaskList::taskListFinished(); } else { setWaitWorkerFinished(true); } } } /*! \brief This is reimplemented method of the ExpTaskList::taskListFinished(). If this method is invoked after all tasks was finished, the contained thread is deleted and all remaining WaitTask objects, which have been not connected to some WaitingTask is discarded (only when no repetetion of the execution of this task is planned or the delayedDelete() is not set. See ExpTask::delayedDelete() for more details). Then the finishing process is ended by executing ExpTaskList::taskListFinished(), which emits the finished() signal. If this method is invoked in consequence of stop() method calling (quit() is true), it is controlled if the onWorkerQuitFinished() method has already been executed. If no, the taskListFinished() is set to true (by the setTaskListFinished() method) and the finishing process waits for the WaitWorker to finish. If the onWorkerQuitFinished() has already been executed, the finishing process is ended by executing ExpTaskList::taskListFinished(), which emits the finished() signal. \warning This means, that these two methods can't be called from different threads and must be called only in connection to some signal. Else you risk the deadlock. */ void WaitTaskList::taskListFinished() { // controlls, if this is consequence to calling stop() method. if (quit()) { // controlls, if WaitWorker has already finished if (waitWorkerIsFinished()) { setWaitWorkerFinished(false); setQuit(false); ExpTaskList::taskListFinished(); } else { setTaskListFinished(true); } } else { // if it was last run of this WaitWorker, everything is cleaned up if (currTimesExec() < 2 && !delayedDelete()) { if (thread) { thread->quit(); thread->wait(); delete thread; thread = nullptr; } if (!waitTasks.isEmpty()) { for (QMap<unsigned int, WaitTaskListTraits::TaskItem>::iterator it = waitTasks.begin(); it != waitTasks.end(); ++it) { delete it->task; } waitTasks.clear(); } } ExpTaskList::taskListFinished(); } } /*! \brief This method is called from addTask() to controll, if new added task is not a case which requires special treatment (WaitExpTask, WaitingTask, ExpTaskList, ForkJoinTask). See description of the class for more details. \param tsk new task to be added \param currNewIds custom new ids list If you want your own new ids list, which is used for connecting new WaitTask objects to the WaitingTask, provide the optional parameter currNewIds. For example if you want to treat tasks from some list separately and do not want to connect external WaitTask object to WaitingTask object contained in this list Example of overriding of addWaitTask(): \code void WaitTaskList::addWaitTask(const ExpTaskListTraits::TaskItem &tsk, QSet<unsigned int> *currNewIds) { if (!currNewIds) { currNewIds = &newIds; } if (ForkJoinTask * forkJoinTask = dynamic_cast<ForkJoinTask*>(tsk.task)) { QList<ExpTaskListTraits::TaskItem> tasks; // if we define its own QSet with threadNewIds, the all waitTasks have // to be handled in its own thread. QSet<unsigned int> threadNewIds; for (unsigned int ii = 0; ii < forkJoinTask->getThreadsN(); ++ii) { tasks = forkJoinTask->getTasks(ii); for(QList<ExpTaskListTraits::TaskItem>::ConstIterator it = tasks.constBegin(); it != tasks.constEnd(); ++it) addWaitTask(*it, &threadNewIds); threadNewIds.clear(); } } else { WaitTaskList::addWaitTask(tsk, currNewIds) } } \endcode */ void WaitTaskList::addWaitTask(const ExpTaskListTraits::TaskItem &tsk, QSet<unsigned int> *currNewIds) { if (!currNewIds) { currNewIds = &newIds; } if (WaitExpTask * waitExpTask = dynamic_cast<WaitExpTask*>(tsk.task)) { unsigned int id = getId(); WaitTaskListTraits::TaskItem waitTaskItem = waitExpTask->getWaitTaskItem(); waitTaskItem.task->setId(id); waitTasks.insert(id,waitTaskItem); currNewIds->insert(id); connect(waitExpTask, &WaitExpTask::startWaitTask, this, &WaitTaskList::onStartWaitTask); } if (WaitingTask * waitingTask = dynamic_cast<WaitingTask*>(tsk.task)) { connect(waitingTask, &WaitingTask::waitTaskFinished, this, &WaitTaskList::onWaitTaskFinished); waitingTask->setIds(*currNewIds); for (QSet<unsigned int>::ConstIterator it = currNewIds->begin(); it != currNewIds->end(); ++it) { connect(waitTasks.value(*it).task, &WaitTask::waitTaskFinished, waitingTask, &WaitingTask::onWaitTaskFinished); waitTasks.value(*it).task->setHandled(true); } currNewIds->clear(); } { ExpTaskList * expTaskList; WaitTaskList * waitTaskList; if ((expTaskList = dynamic_cast<ExpTaskList*>(tsk.task)) && !(waitTaskList = dynamic_cast<WaitTaskList*>(tsk.task))) { QList<ExpTaskListTraits::TaskItem> tasks = expTaskList->getTasks(); for(QList<ExpTaskListTraits::TaskItem>::ConstIterator it = tasks.constBegin(); it != tasks.constEnd(); ++it) addWaitTask(*it); } } if (ForkJoinTask * forkJoinTask = dynamic_cast<ForkJoinTask*>(tsk.task)) { QList<ExpTaskListTraits::TaskItem> tasks; // if we define its own QSet with threadNewIds, the all waitTasks have // to be handled in its own thread. It is not necessary for the // functionality. // QSet<unsigned int> threadNewIds; for (unsigned int ii = 0; ii < forkJoinTask->getThreadsN(); ++ii) { tasks = forkJoinTask->getTasks(ii); for(QList<ExpTaskListTraits::TaskItem>::ConstIterator it = tasks.constBegin(); it != tasks.constEnd(); ++it) addWaitTask(*it); // addWaitTask(*it, &threadNewIds); // threadNewIds.clear(); } } } /*! \brief Gets unused id for WaitTaskList's WaitTask id system. \sa WaitTask::id(), WaitingTask::setIds() */ unsigned int WaitTaskList::getId() { unsigned int ii = 0; while (waitTasks.contains(ii)) ++ii; return ii; } /*! \brief Constructs a new QThread and connects the WaitTaskList::stopWorker() signal to the WaitWorker::stop(), WaitTaskList::startWaitTaskInWorker() signal to the WaitWorker::addWaitTask() and finally WaitWorker::quitFinished() signal to the WaitTaskList::onWorkerQuitFinished() slot. Then it starts thread. */ void WaitTaskList::buildThread() { // creating new thread thread = new QThread(this); // creating new worker and moving it to the thread waitWorker = new WaitWorker; waitWorker->moveToThread(thread); // the thread object is in the WaitTaskList's thread, whereas the // waitWorker is in the thread inside the QThread thread object, so it is // not safe to destroy it from WaitTaskList's thread and threrefore the // Qt's queued connection is used (it is chosen automatically if the signal // is emitted from the different thread than is the owner of the slot) to // the waitWorker's deleteLater() method. connect(thread, &QThread::finished, waitWorker, &QObject::deleteLater); // signals, which controlls the execution of the waitWorker connect(this, &WaitTaskList::stopWorker, waitWorker, &WaitWorker::stop); connect(waitWorker, &WaitWorker::quitFinished, this, &WaitTaskList::onWorkerQuitFinished); connect(this, &WaitTaskList::startWaitTaskInWorker, waitWorker, &WaitWorker::addWaitTask); // starting thread's event loop thread->start(); setWaitWorkerFinished(false); } /*! \brief Destroyes WaitTaskList. */ WaitTaskList::~WaitTaskList() { waitTasks.clear(); if (thread) { emit stopWorker(); thread->quit(); thread->wait(); } for (QMap<unsigned int, WaitTaskListTraits::TaskItem>::iterator it = waitTasks.begin(); it != waitTasks.end(); ++it) { delete it->task; } } /*! \var WaitTaskList::thread \brief The QThread object, which contains thread in which the WaitWorker object runs. \sa buildThread() \var WaitTaskList::waitWorker \brief The WaitWorker object, which controlls wheather the contained WaitTask's is running. \var WaitTaskList::waitTasks \brief List which contains all the added WaitTask objects and their ids. \var WaitTaskList::newIds \brief List containing ids of WaitTask objects which have not aready been handle by some WaitingTask. \var WaitTaskList::blQuit_ \brief Indicitas, if the execution of WaitTaskList was stopped by the stop() method. \var WaitTaskList::blTaskListFinished_ \brief Indicates, if the ExpTaskList object inside the WaitTaskList has already finished when the stop() method was invoked. \var WaitTaskList::blWaitWorkerFinished_ \brief Indicates, if the waitWorker has already finished when the stop() method was invoked. */ /*! \class WaitWorker \brief This class is intended for the internal use in the WaitTaskList for controlling if the processes controlled by WaitTask objects is running. It is executed in new thread. When the new WaitTask is added to the list of controlled tasks by the addWaitTask() method, it is checked if the task has some WaitTask::initialDelay(). If yes, the new DelayedStart object is created and the task is inserted inside it. The DelayedStart::addTask() signal is connected to the addDelayedWaitTask() method and then the QTimer::singleShot() method is connected to the DelayedStart::delayedAddWaitTask() slot, which emits DelayedStart::addTask() signal connected to addDelayedWaitTask() slot. If there is no WaitTask::initialDelay(), the addDelayedWaitTask() slot is invoked directly from this method. addDelayedWaitTask() controlls if any WaitTask is already beeing checked. If no, the internal QTimer is started with repetition rate of WaitWorker::refreshRate_ ms, the signal QTimer::timeout() of which is connected to the waitWorkerLoop() slot, and the WaitTask is inserted into the interanl list and its WaitTask::start() is invoked. In the waitWorkerLoop(), all WaitTask objects from the list is tested, if their WaitTask::running() are true and the WaitTask::finish() method is invoked for those which have already finished. The finished WaitTask objects are also removed from the internal list. If there is no WaitTask in the list, the internal QTimer is stopped. The waitWorkerLoop() execution can be stopped by invoking the stop method, which calls the quitLoop() method, which stops all the running task by the WaitTask::stop() method executin and then it removes all the added WaitTask objects from the internal list. At the end, it stops the internal QTimer and emits quitFinished() signal, which is connected to the WaitTaskList::onWorkerQuitFinished() slot. */ /*! \brief Construts the WaitWorker object. \param parent Parent QObject in the Qt's ownership system. */ WaitWorker::WaitWorker(QObject *parent) : QObject(parent) { timer = new QTimer(this); connect(timer, &QTimer::timeout, this, &WaitWorker::waitWorkerLoop); refreshRate_ = 300; } // signals /*! \fn WaitWorker::quitFinished() \brief This signal is emited only from the quitLoop() method. */ /*! \brief Stops the waitWorkerLoop() execution by calling the quitLoop() method. */ void WaitWorker::stop() { quitLoop(); } /*! \brief Adds WaitTask in the internal list. It controlls if the WaitTask does not have some WaitTask::initialDelay(). See description of WaitTask for more details. \sa addDelayedWaitTask, DelayedStart */ void WaitWorker::addWaitTask(const WaitTaskListTraits::TaskItem & wt) { if (wt.task->initialDelay() > 0) { DelayedStart * ds = new DelayedStart(wt, this); connect(ds, &DelayedStart::addTask, this, &WaitWorker::addDelayedWaitTask); QTimer::singleShot(wt.task->initialDelay(), ds, SLOT(delayedAddWaitTask())); } else { addDelayedWaitTask(wt); } } /*! \brief This method is called from the addWaitTask() method after the WaitTask::initialDelay() delay elapses and adds the WaitTask in the internal list and invokes its WaitTask::start() method. \param wt */ void WaitWorker::addDelayedWaitTask(const WaitTaskListTraits::TaskItem &wt) { if (wt.task->initialDelay() > 0) { DelayedStart * ds = static_cast<DelayedStart *>(QObject::sender()); delete ds; } if (waitTasks_.isEmpty()) { timer->start(refreshRate_); } waitTasks_.insert(wt.task->id(), wt); wt.task->start(); } /*! \brief This method controlls all the WaitTask objects from the internal list, wheather thei are running. If not, it executes their WaitTask::finish() method and removes them from the internal list. */ void WaitWorker::waitWorkerLoop() { for (QMap<unsigned int, WaitTaskListTraits::TaskItem>::ConstIterator it = waitTasks_.constBegin(); it != waitTasks_.constEnd(); ++it) { if (!it->task->running()) { markedForDelete.append(it->task->id()); it->task->finish(); } } if (!markedForDelete.isEmpty()) { for (QList<unsigned int>::ConstIterator it = markedForDelete.begin(); it != markedForDelete.end(); ++it) waitTasks_.remove(*it); markedForDelete.clear(); } if (waitTasks_.isEmpty()) { timer->stop(); } } /*! \brief This method is invoked by the stop() method to WaitTask::stop() all the contained WaitTask objects and to clear the list of the all contained WaitTask objeccts. At the end, it emits quitFinished() signal. */ void WaitWorker::quitLoop() { for (QMap<unsigned int, WaitTaskListTraits::TaskItem>::ConstIterator it = waitTasks_.constBegin(); it != waitTasks_.constEnd(); ++it) { it->task->stop(); } waitTasks_.clear(); timer->stop(); emit quitFinished(); } /*! \brief Destroys WaitWorker. */ WaitWorker::~WaitWorker() { } /*! \var WaitWorker::timer \brief Internal timer, the QTimer::timeout() method of which is connected to the waitWorkerLoop() slot and its repetition rate is set to the WaitWorker::refreshRate_ ms. \var WaitWorker::waitTasks_ \brief Internal list of all contained WaitTask objects. \var WaitWorker::markedForDelete \brief This variable enables using the iterators for deleting objects from QMap class, because QMap do not preserves iterator positions after any modification. This variable is used only in the waitWorkerLoop, but because the loop is rapidly recurently invoked it is created globaly to save computer resources. \var WaitWorker::refreshRate_ \brief The repetition rate in ms of WaitWorker::timer, which determines how often the contained WaitTask objects are controlled, if they are WaitTask::running() */ /*! \class DelayedStart \brief This class is helper class, which wraps the WaitTask object if it has some WaitTask::initialDelay() in the WaitWorker::delayedAddWaitTask() method. Its method is invoked by a QTimer after the initialy delay elapses. The delayedAddWaitTask() emits addTask() signal, which is connected to the WaitWorker::addDelayedWaitTask() method and then it destroyes itself. */ /*! \brief Constructs the DelayedStart object. \param waitTaskItem The WaitTask, which may be delayed. \param parent A parent in the Qt's ownership system. */ DelayedStart::DelayedStart(const WaitTaskListTraits::TaskItem &waitTaskItem, QObject *parent) : QObject(parent), waitTaskItem_(waitTaskItem) { } // signals /*! \fn DelayedStart::addTask(WaitTaskListTraits::TaskItem waitTaskItem) \brief This signal is emited from the delayedAddWaitTask() method and connected to the WaitWorker::addDelayedWaitTask() slot. */ // slots /*! \brief This slot is invoked by the QTimer from the WaitWorker::addWaitTask() method. It emits addTask() signal and deletes the DelayedStart object. */ void DelayedStart::delayedAddWaitTask() { emit addTask(waitTaskItem_); // delete this; } /*! \brief Destroyes DelayedStart objects. */ DelayedStart::~DelayedStart() { } /*! \var DelayedStart::waitTaskItem_ \brief contained WaitTask. */
34.516985
139
0.696356
biomolecules
33daa3cdcdca36dced4b13d096c62a6ce2c5bdf9
138
hxx
C++
src/Providers/UNIXProviders/RejectConnectionAction/UNIX_RejectConnectionAction_AIX.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
1
2020-10-12T09:00:09.000Z
2020-10-12T09:00:09.000Z
src/Providers/UNIXProviders/RejectConnectionAction/UNIX_RejectConnectionAction_AIX.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
null
null
null
src/Providers/UNIXProviders/RejectConnectionAction/UNIX_RejectConnectionAction_AIX.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
null
null
null
#ifdef PEGASUS_OS_AIX #ifndef __UNIX_REJECTCONNECTIONACTION_PRIVATE_H #define __UNIX_REJECTCONNECTIONACTION_PRIVATE_H #endif #endif
11.5
47
0.862319
brunolauze
33de4f928a465857743eb803c7a16ef3586cda78
34,062
cpp
C++
flinter/zookeeper/zookeeper.cpp
yiyuanzhong/flinter
c52655ea5f8e48244fdb59bdf34b915faee57a6e
[ "Apache-2.0" ]
29
2016-01-29T09:31:09.000Z
2021-07-11T12:00:31.000Z
flinter/zookeeper/zookeeper.cpp
yiyuanzhong/flinter
c52655ea5f8e48244fdb59bdf34b915faee57a6e
[ "Apache-2.0" ]
2
2015-03-30T09:59:51.000Z
2017-03-13T09:35:18.000Z
flinter/zookeeper/zookeeper.cpp
yiyuanzhong/flinter
c52655ea5f8e48244fdb59bdf34b915faee57a6e
[ "Apache-2.0" ]
17
2015-03-28T09:24:53.000Z
2021-08-07T10:09:10.000Z
/* Copyright 2015 yiyuanzhong@gmail.com (Yiyuan Zhong) * * 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 "flinter/zookeeper/zookeeper.h" #include <assert.h> #include <errno.h> #include <limits.h> #include <string.h> #include <vector> #include "flinter/thread/mutex_locker.h" #include "flinter/common.h" #include "flinter/logger.h" #include "flinter/msleep.h" #include "flinter/utility.h" #include "flinter/zookeeper/zookeeper_callback.h" #include "flinter/zookeeper/zookeeper_watcher.h" namespace flinter { namespace { static const ZooKeeper::Id ANYONE("world", "anyone"); static const ZooKeeper::Acl::value_type ANYONE_OPEN[] = { ZooKeeper::Acl::value_type(ANYONE, ZOO_PERM_ALL) }; static const ZooKeeper::Acl::value_type ANYONE_READ[] = { ZooKeeper::Acl::value_type(ANYONE, ZOO_PERM_READ) }; } // anonymous namespace const ZooKeeper::Acl ZooKeeper::ACL_ANYONE_OPEN(ANYONE_OPEN, ANYONE_OPEN + ARRAYSIZEOF(ANYONE_OPEN)); const ZooKeeper::Acl ZooKeeper::ACL_ANYONE_READ(ANYONE_READ, ANYONE_READ + ARRAYSIZEOF(ANYONE_READ)); ZooKeeper::ZooKeeper() : _resuming(false) , _session_pending(this) , _handle(NULL) , _connecting(false) , _timeout(-1) { memset(&_client_id, 0, sizeof(_client_id)); } ZooKeeper::~ZooKeeper() { Shutdown(); } void ZooKeeper::SetLog(FILE *stream, const ZooLogLevel &level) { zoo_set_log_stream(stream); zoo_set_debug_level(level); } void ZooKeeper::GlobalWatcher(zhandle_t * /*zh*/, int type, int state, const char *path, void *watcherCtx) { CLOG.Debug("ZooKeeper: GlobalWatcher(type=%d, state=%d, path=%s, watcherCtx=%p)", type, state, path, watcherCtx); assert(watcherCtx); Pending *p = reinterpret_cast<Pending *>(watcherCtx); assert(p->zk()); // Session events are special: they're triggered automatically and passively. if (p->op() == OP_SESSION) { if (type == ZOO_SESSION_EVENT) { // The global session watcher. p->zk()->OnSession(state); } return; } if (!p->zkw_detached()) { assert(p->zkw()); p->zkw()->OnEvent(type, state, path); } // Normal watchers are short lived. // But session event is an exception. if (type != ZOO_SESSION_EVENT) { p->clear_watcher(); p->zk()->ErasePending(p); } } void ZooKeeper::GlobalVoidCompletion(int rc, const void *data) { CLOG.Debug("ZooKeeper: GlobalVoidCompletion(rc=%d, data=%p)", rc, data); // Don't worry, it's born mutable. assert(data); void *mutable_data = const_cast<void *>(data); Pending *p = reinterpret_cast<Pending *>(mutable_data); assert(!p->zkw()); if (!p->zkc()) { CLOG.Debug("ZooKeeper: global completion: detached pending %p done, not deleted.", p); return; } if (p->op() == OP_DELETE) { p->zkc()->OnErase(rc, p->path()); } else if (p->op() == OP_SETA) { p->zkc()->OnSetAcl(rc, p->path()); } else { CLOG.Warn("ZooKeeper: global completion has got an invalid event."); } p->clear_callback(); p->zk()->ErasePending(p); } void ZooKeeper::GlobalStatCompletion(int rc, const struct Stat *stat, const void *data) { CLOG.Debug("ZooKeeper: GlobalStatCompletion(rc=%d, stat=%p, data=%p)", rc, stat, data); // Don't worry, it's born mutable. assert(data); void *mutable_data = const_cast<void *>(data); Pending *p = reinterpret_cast<Pending *>(mutable_data); if (!p->zkc()) { // It's OK, we're just resuming watchers. if (p->zkw_detached()) { CLOG.Debug("ZooKeeper: global completion: detached pending %p done, not deleted.", p); return; } assert(p->zkw()); assert(p->op() == OP_EXISTS); if (rc == ZOK) { CLOG.Trace("ZooKeeper: resumed EXISTS (pending=%p, path=%s)", p, p->path()); } else { CLOG.Warn("ZooKeeper: failed to resume EXISTS (pending=%p, path=%s, rc=%d)", p, p->path(), rc); p->zk()->ErasePending(p); } return; } if (p->op() == OP_EXISTS) { p->zkc()->OnExists(rc, p->path(), stat); } else if (p->op() == OP_SET) { p->zkc()->OnSet(rc, p->path(), stat); } else { CLOG.Warn("ZooKeeper: global completion has got an invalid event."); } p->clear_callback(); if (!p->zkw() && !p->zkw_detached()) { // Pending done. p->zk()->ErasePending(p); } } void ZooKeeper::GlobalDataCompletion(int rc, const char *value, int value_len, const struct Stat *stat, const void *data) { CLOG.Debug("ZooKeeper: GlobalDataCompletion(rc=%d, value=%p, value_len=%d, stat=%p, data=%p)", rc, value, value_len, stat, data); // Don't worry, it's born mutable. assert(data); void *mutable_data = const_cast<void *>(data); Pending *p = reinterpret_cast<Pending *>(mutable_data); if (!p->zkc()) { // It's OK, we're just resuming watchers. if (p->zkw_detached()) { CLOG.Debug("ZooKeeper: global completion: detached pending %p done, not deleted.", p); return; } assert(p->zkw()); assert(p->op() == OP_GET); if (rc == ZOK) { CLOG.Trace("ZooKeeper: resumed GET (pending=%p, path=%s)", p, p->path()); } else { CLOG.Warn("ZooKeeper: failed to resume GET (pending=%p, path=%s, rc=%d)", p, p->path(), rc); p->zk()->ErasePending(p); } return; } std::string buffer(value, value + value_len); if (p->op() == OP_GET) { p->zkc()->OnGet(rc, p->path(), buffer, stat); } else { CLOG.Warn("ZooKeeper: global completion has got an invalid event."); } p->clear_callback(); if (!p->zkw() && !p->zkw_detached()) { // Pending done. p->zk()->ErasePending(p); } } void ZooKeeper::GlobalStringsStatCompletion(int rc, const String_vector *strings, const struct Stat *stat, const void *data) { CLOG.Debug("ZooKeeper: GlobalStringsStatCompletion(rc=%d, strings=%p, stat=%p, data=%p)", rc, strings, stat, data); // Don't worry, it's born mutable. assert(data); void *mutable_data = const_cast<void *>(data); Pending *p = reinterpret_cast<Pending *>(mutable_data); if (!p->zkc()) { // It's OK, we're just resuming watchers. if (p->zkw_detached()) { CLOG.Debug("ZooKeeper: global completion: detached pending %p done, not deleted.", p); return; } assert(p->zkw()); assert(p->op() == OP_GETC); if (rc == ZOK) { CLOG.Trace("ZooKeeper: resumed GETC (pending=%p, path=%s)", p, p->path()); } else { CLOG.Warn("ZooKeeper: failed to resume GETC (pending=%p, path=%s, rc=%d)", p, p->path(), rc); p->zk()->ErasePending(p); } return; } std::list<std::string> buffer; if (strings) { for (int i = 0; i < strings->count; ++i) { buffer.push_back(strings->data[i]); } } if (p->op() == OP_GETC) { p->zkc()->OnGetChildren(rc, p->path(), buffer, stat); } else { CLOG.Warn("ZooKeeper: global completion has got an invalid event."); } p->clear_callback(); if (!p->zkw() && !p->zkw_detached()) { // Pending done. p->zk()->ErasePending(p); } } void ZooKeeper::GlobalStringCompletion(int rc, const char *value, const void *data) { CLOG.Debug("ZooKeeper: GlobalStringCompletion(rc=%d, value=%p, data=%p)", rc, value, data); // Don't worry, it's born mutable. assert(data); void *mutable_data = const_cast<void *>(data); Pending *p = reinterpret_cast<Pending *>(mutable_data); assert(!p->zkw()); if (!p->zkc()) { CLOG.Debug("ZooKeeper: global completion: detached pending %p done, not deleted.", p); return; } if (p->op() == OP_CREATE) { p->zkc()->OnCreate(rc, p->path(), value); } else if (p->op() == OP_SYNC) { p->zkc()->OnSync(rc, p->path(), value); } else { CLOG.Warn("ZooKeeper: global completion has got an invalid event."); } p->clear_callback(); if (!p->zkw() && !p->zkw_detached()) { // Pending done. p->zk()->ErasePending(p); } } void ZooKeeper::GlobalAclCompletion(int rc, struct ACL_vector *acl, struct Stat *stat, const void *data) { CLOG.Debug("ZooKeeper: GlobalAclCompletion(rc=%d, acl=%p, stat=%p, data=%p)", rc, acl, stat, data); // Don't worry, it's born mutable. assert(data); void *mutable_data = const_cast<void *>(data); Pending *p = reinterpret_cast<Pending *>(mutable_data); assert(!p->zkw()); if (!p->zkc()) { CLOG.Debug("ZooKeeper: global completion: detached pending %p done, not deleted.", p); return; } if (p->op() == OP_GETA) { Acl a; Translate(acl, &a); p->zkc()->OnGetAcl(rc, p->path(), a, stat); } else { CLOG.Warn("ZooKeeper: global completion has got an invalid event."); } p->clear_callback(); if (!p->zkw() && !p->zkw_detached()) { // Pending done. p->zk()->ErasePending(p); } } void ZooKeeper::Detach(ZooKeeperWatcher *zkw, ZooKeeperCallback *zkc) { MutexLocker locker(&_mutex); for (std::set<Pending *>::iterator p = _pending.begin(); p != _pending.end(); ++p) { Pending *pending = *p; if (zkc && pending->zkc() == zkc) { pending->clear_callback(); CLOG.Debug("ZooKeeper: detached callback: %p(%p)", pending, zkc); } if (zkw && pending->zkw() == zkw) { pending->detach_watcher(); CLOG.Debug("ZooKeeper: detached watcher: %p(%p)", pending, zkw); } } // Don't really erase pending. } void ZooKeeper::ErasePending(Pending *pending) { assert(pending); assert(!pending->zkc() && !pending->zkw() && !pending->zkw_detached()); CLOG.Debug("ZooKeeper: deleting %spending %p", pending->zkw_detached() ? "detached " : "", pending); MutexLocker locker(&_mutex); std::set<Pending *>::iterator p = _pending.find(pending); if (p != _pending.end()) { delete *p; _pending.erase(p); } } void ZooKeeper::ResumeSession(const std::set<Pending *> &pending) { CLOG.Info("ZooKeeper: try to resume session with %lu pendings...", pending.size()); int status = state(); size_t failed = 0; for (std::set<Pending *>::const_iterator i = pending.begin(); i != pending.end(); ++i) { Pending *p = *i; assert(p); if (!p->zkc() && (!p->zkw() || p->zkw_detached())) { CLOG.Debug("ZooKeeper: detached pending %p not resumed.", p); continue; } switch (p->op()) { case OP_CREATE: // TODO(yiyuanzhong): implement this. assert(p->zkc()); assert(!p->zkw()); CLOG.Debug("ZooKeeper: resuming CREATE (pending=%p, path=%s)", p, p->path()); break; case OP_DELETE: // TODO(yiyuanzhong): implement this. assert(p->zkc()); assert(!p->zkw()); CLOG.Debug("ZooKeeper: resuming DELETE (pending=%p, path=%s)", p, p->path()); break; case OP_EXISTS: assert(p->zkc() || p->zkw()); if (!p->zkc()) { // Force trigger the watcher. p->zkw()->OnEvent(ZOO_CREATED_EVENT, status, p->path()); } else if (AsyncExists(p->path(), p->zkc(), p->zkw()) == ZOK) { CLOG.Debug("ZooKeeper: resuming EXISTS (pending=%p, path=%s)", p, p->path()); } else { CLOG.Warn("ZooKeeper: failed to resume EXISTS (pending=%p, path=%s)", p, p->path()); p->zkc()->OnExists(ZSESSIONEXPIRED, p->path(), NULL); ++failed; } break; case OP_SYNC: // TODO(yiyuanzhong): implement this. assert(p->zkc()); assert(!p->zkw()); CLOG.Debug("ZooKeeper: resuming SYNC (pending=%p, path=%s)", p, p->path()); break; case OP_GET: assert(p->zkc() || p->zkw()); if (!p->zkc()) { // Force trigger the watcher. p->zkw()->OnEvent(ZOO_CHANGED_EVENT, status, p->path()); } else if (AsyncGet(p->path(), p->zkc(), p->zkw()) == ZOK) { CLOG.Debug("ZooKeeper: resuming GET (pending=%p, path=%s)", p, p->path()); } else { CLOG.Warn("ZooKeeper: failed to resume GET (pending=%p, path=%s)", p, p->path()); p->zkc()->OnGet(ZSESSIONEXPIRED, p->path(), std::string(), NULL); ++failed; } break; case OP_SET: // TODO(yiyuanzhong): implement this. assert(p->zkc()); assert(!p->zkw()); CLOG.Debug("ZooKeeper: resuming SET (pending=%p, path=%s)", p, p->path()); break; case OP_GETA: // TODO(yiyuanzhong): implement this. assert(p->zkc()); assert(!p->zkw()); CLOG.Debug("ZooKeeper: resuming GETA (pending=%p, path=%s)", p, p->path()); break; case OP_SETA: // TODO(yiyuanzhong): implement this. assert(p->zkc()); assert(!p->zkw()); CLOG.Debug("ZooKeeper: resuming SETA (pending=%p, path=%s)", p, p->path()); break; case OP_GETC: assert(p->zkc() || p->zkw()); if (!p->zkc()) { // Force trigger the watcher. p->zkw()->OnEvent(ZOO_CHILD_EVENT, status, p->path()); } else if (AsyncGetChildren(p->path(), p->zkc(), p->zkw()) == ZOK) { CLOG.Debug("ZooKeeper: resuming GETC (pending=%p, path=%s)", p, p->path()); } else { CLOG.Warn("ZooKeeper: failed to resume GETC (pending=%p, path=%s)", p, p->path()); p->zkc()->OnGetChildren(ZSESSIONEXPIRED, p->path(), std::list<std::string>(), NULL); ++failed; } break; default: assert(false); CLOG.Error("ZooKeeper: internal error with invalid pending data: %d", p->op()); break; } } for (std::set<Pending *>::const_iterator p = pending.begin(); p != pending.end(); ++p) { delete *p; } if (failed) { CLOG.Warn("ZooKeeper: erased %lu pending tasks that failed to resume.", failed); } } void ZooKeeper::OnConnected() { MutexLocker locker(&_mutex); if (!_handle) { CLOG.Warn("ZooKeeper: connected but the handle is NULL, maybe shutting down..."); assert(_connecting); return; } zhandle_t *handle = _handle; const clientid_t *cid = zoo_client_id(handle); assert(cid); if (!cid) { CLOG.Error("ZooKeeper: connected but the session id is invalid."); assert(false); Shutdown(); return; } _client_id = *cid; CLOG.Info("ZooKeeper: connected session 0x%016llx(%p)", static_cast<long long>(cid->client_id), handle); if (_resuming) { _resuming = false; if (!_pending.empty()) { std::set<Pending *> pending(_pending); _pending.clear(); locker.Unlock(); ResumeSession(pending); } } } void ZooKeeper::OnSession(int state) { /* * Reason unknown, but even on_session() is called within ZooKeeper C client library * completions, aka worker threads, calling zookeeper_close() inside this context will * not cause ZooKeeper to pthread_join() the worker. * * In one word, it's OK to operate on zhandle_t within here. */ if (state == ZOO_CONNECTING_STATE || state == ZOO_ASSOCIATING_STATE) { CLOG.Warn("ZooKeeper: connection interrupted, resuming..."); return; } if (state == ZOO_CONNECTED_STATE) { OnConnected(); } else if (state == ZOO_EXPIRED_SESSION_STATE) { CLOG.Warn("ZooKeeper: session expired, starting a new session..."); Reconnect(); } else if (state == ZOO_AUTH_FAILED_STATE) { CLOG.Error("ZooKeeper: authorization failed."); Shutdown(); } else { CLOG.Warn("ZooKeeper: unknown state: %d", state); } } int ZooKeeper::Set(const char *path, const std::string &data, struct Stat *stat, int version) { if (!path || path[0] != '/') { return ZBADARGUMENTS; } if (data.length() > INT_MAX) { return ZBADARGUMENTS; } MutexLocker locker(&_mutex); if (!_handle) { return ZINVALIDSTATE; } int length = static_cast<int>(data.length()); int error = ZOK; if (stat) { // You call version 2 with a non-null stat. error = zoo_set2(_handle, path, data.data(), length, version, stat); } else { // Or you call version 1. error = zoo_set(_handle, path, data.data(), length, version); } return error; } int ZooKeeper::Exists(const char *path, struct Stat *stat, ZooKeeperWatcher *watcher) { if (!path || path[0] != '/') { return ZBADARGUMENTS; } MutexLocker locker(&_mutex); if (!_handle) { return ZINVALIDSTATE; } int error = ZOK; if (watcher) { Pending *p = new Pending(this, OP_EXISTS, path, watcher, NULL); error = zoo_wexists(_handle, path, GlobalWatcher, p, stat); if (error == ZOK || error == ZNONODE) { // Birds out, keep track. _pending.insert(p); } else { delete p; } } else { error = zoo_exists(_handle, path, 0, stat); } return error; } int ZooKeeper::Get(const char *path, std::string *data, struct Stat *stat, ZooKeeperWatcher *watcher) { if (!path || path[0] != '/') { return ZBADARGUMENTS; } int length = 0; char *buffer = NULL; if (data) { size_t len = data->length(); if (!len) { len = 1024; data->resize(len); } else if (len > INT_MAX) { len = INT_MAX; } length = static_cast<int>(len); buffer = &data->at(0); } MutexLocker locker(&_mutex); if (!_handle) { return ZINVALIDSTATE; } int error = ZOK; if (watcher) { Pending *p = new Pending(this, OP_GET, path, watcher, NULL); error = zoo_wget(_handle, path, GlobalWatcher, p, buffer, &length, stat); if (error == ZOK) { // Birds out, keep track. _pending.insert(p); } else { delete p; } } else { error = zoo_get(_handle, path, 0, buffer, &length, stat); } if (data) { // Always good, but sometimes with data truncated. if (length < 0) { data->clear(); } else { data->resize(static_cast<size_t>(length)); } } return error; } int ZooKeeper::GetChildren(const char *path, std::list<std::string> *children, struct Stat *stat, ZooKeeperWatcher *watcher) { if (!path || path[0] != '/') { return ZBADARGUMENTS; } MutexLocker locker(&_mutex); if (!_handle) { return ZINVALIDSTATE; } int error = ZOK; struct Stat rstat, *pstat = stat ? stat : &rstat; struct String_vector strings; memset(&strings, 0, sizeof(strings)); if (watcher) { Pending *p = new Pending(this, OP_GETC, path, watcher, NULL); error = zoo_wget_children2(_handle, path, GlobalWatcher, p, &strings, pstat); if (error == ZOK) { // Birds out, keep track. _pending.insert(p); CLOG.Debug("ZooKeeper: get_children: inserted %p", p); } else { delete p; } } else { error = zoo_get_children2(_handle, path, 0, &strings, pstat); } if (error != ZOK) { return error; } if (!children) { // Easy one. deallocate_String_vector(&strings); return ZOK; } children->clear(); for (int i = 0; i < strings.count; ++i) { children->push_back(strings.data[i]); } deallocate_String_vector(&strings); return ZOK; } int ZooKeeper::Create(const char *path, const char *data, std::string *actual_path, bool ephemeral, bool sequence, const Acl &acl) { if (!path || path[0] != '/' || !data) { return ZBADARGUMENTS; } size_t plen = strlen(path); if (plen > INT_MAX - 16) { return ZBADARGUMENTS; } plen += 16; size_t dlen = strlen(data); if (dlen > INT_MAX) { return ZBADARGUMENTS; } struct ACL_vector av; Translate(acl, &av); int flags = 0; if (ephemeral) { flags |= ZOO_EPHEMERAL; } if (sequence) { flags |= ZOO_SEQUENCE; } MutexLocker locker(&_mutex); if (!_handle) { deallocate_ACL_vector(&av); return ZINVALIDSTATE; } // Theoretically the actual path is at most appended a %10d std::vector<char> actual(plen); int error = zoo_create(_handle, path, data, static_cast<int>(dlen), &av, flags, &actual[0], static_cast<int>(plen)); deallocate_ACL_vector(&av); if (error != ZOK) { return error; } if (actual_path) { *actual_path = &actual[0]; } return ZOK; } /// allocate_ACL_vector() is hidden by libzookeeper. void ZooKeeper::Translate(const Acl &acl, struct ACL_vector *result) { assert(result); if (acl.empty()) { result->count = 0; result->data = NULL; return; } int32_t i = 0; result->data = reinterpret_cast<struct ACL *>(calloc(sizeof(*result->data), acl.size())); if (!result->data) { throw std::bad_alloc(); } result->count = static_cast<int32_t>(acl.size()); for (Acl::const_iterator p = acl.begin(); p != acl.end(); ++p, ++i) { struct ACL &a = result->data[i]; a.perms = p->second; a.id.scheme = strdup(p->first.first.c_str()); a.id.id = strdup(p->first.second.c_str()); } } void ZooKeeper::Translate(const struct ACL_vector *acl, Acl *result) { assert(acl); assert(result); result->clear(); for (int32_t i = 0; i < acl->count; ++i) { struct ACL &a = acl->data[i]; Id id(a.id.scheme, a.id.id); Acl::iterator p = result->find(id); if (p != result->end()) { p->second |= a.perms; } else { result->insert(Acl::value_type(id, a.perms)); } } } int ZooKeeper::GetAcl(const char *path, Acl *acl, struct Stat *stat) { if (!path || path[0] != '/' || !acl) { return ZBADARGUMENTS; } struct ACL_vector av; memset(&av, 0, sizeof(av)); struct Stat rstat, *pstat = stat ? stat : &rstat; MutexLocker locker(&_mutex); if (!_handle) { return ZINVALIDSTATE; } int error = zoo_get_acl(_handle, path, &av, pstat); if (error != ZOK) { return error; } Translate(&av, acl); deallocate_ACL_vector(&av); return ZOK; } int ZooKeeper::SetAcl(const char *path, const Acl &acl, int version) { if (!path || path[0] != '/') { return ZBADARGUMENTS; } struct ACL_vector av; Translate(acl, &av); MutexLocker locker(&_mutex); if (!_handle) { return ZINVALIDSTATE; } int error = zoo_set_acl(_handle, path, version, &av); deallocate_ACL_vector(&av); return error; } int ZooKeeper::Erase(const char *path, int version) { if (!path || path[0] != '/') { return ZBADARGUMENTS; } MutexLocker locker(&_mutex); if (!_handle) { return ZINVALIDSTATE; } return zoo_delete(_handle, path, version); } int ZooKeeper::Reconnect() { MutexLocker locker(&_mutex); if (_connecting) { return ZOK; } zhandle_t *handle = _handle; _handle = NULL; if (handle) { _connecting = true; locker.Unlock(); Disconnect(handle); locker.Relock(); _connecting = false; } memset(&_client_id, 0, sizeof(_client_id)); _resuming = true; int ret = ReconnectNolock(); return ret; } int ZooKeeper::ReconnectNolock() { assert(!_handle); if (!_hosts.length() || _timeout < 0) { return ZBADARGUMENTS; } if (_client_id.client_id) { CLOG.Info("ZooKeeper: resuming session 0x%016llx...", static_cast<long long>(_client_id.client_id)); } else { CLOG.Info("ZooKeeper: starting new session..."); } int milliseconds = -1; if (_timeout >= 0) { milliseconds = static_cast<int>(_timeout / 1000000LL); } zhandle_t *zh = zookeeper_init(_hosts.c_str(), GlobalWatcher, milliseconds, &_client_id, &_session_pending, 0); int error = errno; if (!zh) { CLOG.Error("ZooKeeper: failed to start a session: %d: %s", error, strerror(error)); return error; } _handle = zh; CLOG.Info("ZooKeeper: session establishing..."); return ZOK; } int ZooKeeper::Initialize(const std::string &hosts, int64_t timeout) { MutexLocker locker(&_mutex); if (_handle) { return ZINVALIDSTATE; } else if (_connecting) { return ZOK; } _hosts = hosts; _timeout = timeout; _connecting = false; // Always initialize a new session. memset(&_client_id, 0, sizeof(_client_id)); return ReconnectNolock(); } int ZooKeeper::Disconnect(zhandle_t *handle) { if (!handle) { return ZOK; } int64_t id = 0; const clientid_t *cid = zoo_client_id(handle); if (cid) { id = cid->client_id; } int error = zookeeper_close(handle); if (error != ZOK) { CLOG.Warn("ZooKeeper: failed to disconnect session 0x%016llx(%p) " "cleanly, still disconnected: %d", static_cast<long long>(id), handle, error); return error; } CLOG.Info("ZooKeeper: session 0x%016llx(%p) disconnected.", static_cast<long long>(id), handle); return ZOK; } int ZooKeeper::Shutdown() { MutexLocker locker(&_mutex); if (!_handle) { return ZOK; } assert(!_connecting); memset(&_client_id, 0, sizeof(_client_id)); zhandle_t *handle = _handle; _handle = NULL; if (handle) { _connecting = true; locker.Unlock(); int error = Disconnect(handle); if (error != ZOK) { return error; } locker.Relock(); assert(!_handle); assert(_connecting); _connecting = false; } for (std::set<Pending *>::iterator p = _pending.begin(); p != _pending.end(); ++p) { CLOG.Debug("ZooKeeper: delete pending %p after shutdown.", *p); delete *p; } _pending.clear(); return ZOK; } int ZooKeeper::AsyncGet(const char *path, ZooKeeperCallback *zkc, ZooKeeperWatcher *watcher) { if (!path || path[0] != '/' || (!zkc && !watcher)) { return ZBADARGUMENTS; } MutexLocker locker(&_mutex); if (!_handle) { return ZINVALIDSTATE; } int error = ZOK; Pending *p = new Pending(this, OP_GET, path, watcher, zkc); if (watcher) { error = zoo_awget(_handle, path, GlobalWatcher, p, GlobalDataCompletion, p); } else { error = zoo_aget(_handle, path, 0, GlobalDataCompletion, p); } if (error != ZOK) { delete p; return error; } _pending.insert(p); return ZOK; } int ZooKeeper::AsyncExists(const char *path, ZooKeeperCallback *zkc, ZooKeeperWatcher *watcher) { if (!path || path[0] != '/' || (!zkc && !watcher)) { return ZBADARGUMENTS; } MutexLocker locker(&_mutex); if (!_handle) { return ZINVALIDSTATE; } int error = ZOK; Pending *p = new Pending(this, OP_EXISTS, path, watcher, zkc); if (watcher) { error = zoo_awexists(_handle, path, GlobalWatcher, p, GlobalStatCompletion, p); } else { error = zoo_aexists(_handle, path, 0, GlobalStatCompletion, p); } if (error != ZOK) { delete p; return error; } _pending.insert(p); return ZOK; } int ZooKeeper::AsyncGetChildren(const char *path, ZooKeeperCallback *zkc, ZooKeeperWatcher *watcher) { if (!path || path[0] != '/' || (!zkc && !watcher)) { return ZBADARGUMENTS; } MutexLocker locker(&_mutex); if (!_handle) { return ZINVALIDSTATE; } int error = ZOK; Pending *p = new Pending(this, OP_GETC, path, watcher, zkc); if (watcher) { error = zoo_awget_children2(_handle, path, GlobalWatcher, p, GlobalStringsStatCompletion, p); } else { error = zoo_aget_children2(_handle, path, 0, GlobalStringsStatCompletion, p); } if (error != ZOK) { delete p; return error; } _pending.insert(p); return ZOK; } int ZooKeeper::state() const { MutexLocker handle_locker(&_mutex); if (!_handle) { return ZINVALIDSTATE; } return zoo_state(_handle); } int ZooKeeper::is_connected() const { int s = state(); if (s == ZOO_CONNECTED_STATE) { return 0; } else if (s == ZOO_AUTH_FAILED_STATE) { return -1; } else { return 1; } } bool ZooKeeper::WaitUntilConnected(int64_t timeout) const { int64_t deadline = -1; if (timeout >= 0) { deadline = get_monotonic_timestamp() + timeout; } while (true) { int s = state(); if (s == ZOO_CONNECTED_STATE) { return true; } else if (s == ZOO_AUTH_FAILED_STATE) { return false; } msleep(100); if (deadline >= 0) { if (get_monotonic_timestamp() >= deadline) { return false; } } } } const char *ZooKeeper::strerror(int error) { switch (error) { case ZOK: return "Everything is OK"; case ZRUNTIMEINCONSISTENCY: return "A runtime inconsistency was found"; case ZDATAINCONSISTENCY: return "A data inconsistency was found"; case ZCONNECTIONLOSS: return "Connection to the server has been lost"; case ZMARSHALLINGERROR: return "Error while marshalling or unmarshalling data"; case ZUNIMPLEMENTED: return "Operation is unimplemented"; case ZOPERATIONTIMEOUT: return "Operation timeout"; case ZBADARGUMENTS: return "Invalid arguments"; case ZINVALIDSTATE: return "Invalid zhandle state"; case ZNONODE: return "Node does not exist"; case ZNOAUTH: return "Not authenticated"; case ZBADVERSION: return "Version conflict"; case ZNOCHILDRENFOREPHEMERALS: return "Ephemeral nodes may not have children"; case ZNODEEXISTS: return "The node already exists"; case ZNOTEMPTY: return "The node has children"; case ZSESSIONEXPIRED: return "The session has been expired by the server"; case ZINVALIDCALLBACK: return "Invalid callback specified"; case ZINVALIDACL: return "Invalid ACL specified"; case ZAUTHFAILED: return "Client authentication failed"; case ZCLOSING: return "ZooKeeper is closing"; case ZNOTHING: return "(not error) no server responses to process"; case ZSESSIONMOVED: return "Session moved to another server, so operation is ignored"; default: if (error < ZSYSTEMERROR && error > ZAPIERROR) { return "Unknown system and server-wide error."; } else if (error < ZAPIERROR) { return "Unknown API error"; } else { return "Unknown error"; } } } } // namespace flinter
27.381029
100
0.539487
yiyuanzhong
33e087df119e35543991f7d7f2fa36127dda491e
15,014
hpp
C++
include/libtorrent/peer_info.hpp
naftaly/libtorrent
dc030c9b9c5ad742bd6ba4b775d01a263f807730
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
include/libtorrent/peer_info.hpp
naftaly/libtorrent
dc030c9b9c5ad742bd6ba4b775d01a263f807730
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
include/libtorrent/peer_info.hpp
naftaly/libtorrent
dc030c9b9c5ad742bd6ba4b775d01a263f807730
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2003-2016, Arvid Norberg 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 author 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. */ #ifndef TORRENT_PEER_INFO_HPP_INCLUDED #define TORRENT_PEER_INFO_HPP_INCLUDED #include "libtorrent/socket.hpp" #include "libtorrent/deadline_timer.hpp" #include "libtorrent/peer_id.hpp" #include "libtorrent/config.hpp" #include "libtorrent/bitfield.hpp" #include "libtorrent/time.hpp" #include "libtorrent/units.hpp" namespace libtorrent { // holds information and statistics about one peer // that libtorrent is connected to struct TORRENT_EXPORT peer_info { // a string describing the software at the other end of the connection. // In some cases this information is not available, then it will contain // a string that may give away something about which software is running // in the other end. In the case of a web seed, the server type and // version will be a part of this string. std::string client; // a bitfield, with one bit per piece in the torrent. Each bit tells you // if the peer has that piece (if it's set to 1) or if the peer miss that // piece (set to 0). typed_bitfield<piece_index_t> pieces; // the total number of bytes downloaded from and uploaded to this peer. // These numbers do not include the protocol chatter, but only the // payload data. std::int64_t total_download; std::int64_t total_upload; // the time since we last sent a request to this peer and since any // transfer occurred with this peer time_duration last_request; time_duration last_active; // the time until all blocks in the request queue will be downloaded time_duration download_queue_time; // flags for the peer_info::flags field. Indicates various states // the peer may be in. These flags are not mutually exclusive, but // not every combination of them makes sense either. enum peer_flags_t { // **we** are interested in pieces from this peer. interesting = 0x1, // **we** have choked this peer. choked = 0x2, // the peer is interested in **us** remote_interested = 0x4, // the peer has choked **us**. remote_choked = 0x8, // means that this peer supports the // `extension protocol`__. // // __ extension_protocol.html supports_extensions = 0x10, // The connection was initiated by us, the peer has a // listen port open, and that port is the same as in the // address of this peer. If this flag is not set, this // peer connection was opened by this peer connecting to // us. local_connection = 0x20, // The connection is opened, and waiting for the // handshake. Until the handshake is done, the peer // cannot be identified. handshake = 0x40, // The connection is in a half-open state (i.e. it is // being connected). connecting = 0x80, #ifndef TORRENT_NO_DEPRECATE // The connection is currently queued for a connection // attempt. This may happen if there is a limit set on // the number of half-open TCP connections. queued = 0x100, #else // hidden deprecated__ = 0x100, #endif // The peer has participated in a piece that failed the // hash check, and is now "on parole", which means we're // only requesting whole pieces from this peer until // it either fails that piece or proves that it doesn't // send bad data. on_parole = 0x200, // This peer is a seed (it has all the pieces). seed = 0x400, // This peer is subject to an optimistic unchoke. It has // been unchoked for a while to see if it might unchoke // us in return an earn an upload/unchoke slot. If it // doesn't within some period of time, it will be choked // and another peer will be optimistically unchoked. optimistic_unchoke = 0x800, // This peer has recently failed to send a block within // the request timeout from when the request was sent. // We're currently picking one block at a time from this // peer. snubbed = 0x1000, // This peer has either explicitly (with an extension) // or implicitly (by becoming a seed) told us that it // will not downloading anything more, regardless of // which pieces we have. upload_only = 0x2000, // This means the last time this peer picket a piece, // it could not pick as many as it wanted because there // were not enough free ones. i.e. all pieces this peer // has were already requested from other peers. endgame_mode = 0x4000, // This flag is set if the peer was in holepunch mode // when the connection succeeded. This typically only // happens if both peers are behind a NAT and the peers // connect via the NAT holepunch mechanism. holepunched = 0x8000, // indicates that this socket is running on top of the // I2P transport. i2p_socket = 0x10000, // indicates that this socket is a uTP socket utp_socket = 0x20000, // indicates that this socket is running on top of an SSL // (TLS) channel ssl_socket = 0x40000, // this connection is obfuscated with RC4 rc4_encrypted = 0x100000, // the handshake of this connection was obfuscated // with a diffie-hellman exchange plaintext_encrypted = 0x200000 }; // tells you in which state the peer is in. It is set to // any combination of the peer_flags_t enum. std::uint32_t flags; // the flags indicating which sources a peer can // have come from. A peer may have been seen from // multiple sources enum peer_source_flags { // The peer was received from the tracker. tracker = 0x1, // The peer was received from the kademlia DHT. dht = 0x2, // The peer was received from the peer exchange // extension. pex = 0x4, // The peer was received from the local service // discovery (The peer is on the local network). lsd = 0x8, // The peer was added from the fast resume data. resume_data = 0x10, // we received an incoming connection from this peer incoming = 0x20 }; // a combination of flags describing from which sources this peer // was received. See peer_source_flags. std::uint32_t source; // the current upload and download speed we have to and from this peer // (including any protocol messages). updated about once per second int up_speed; int down_speed; // The transfer rates of payload data only updated about once per second int payload_up_speed; int payload_down_speed; // the peer's id as used in the bit torrent protocol. This id can be used // to extract 'fingerprints' from the peer. Sometimes it can tell you // which client the peer is using. See identify_client()_ peer_id pid; int queue_bytes; // the number of seconds until the current front piece request will time // out. This timeout can be adjusted through // ``settings_pack::request_timeout``. // -1 means that there is not outstanding request. int request_timeout; // the number of bytes allocated // and used for the peer's send buffer, respectively. int send_buffer_size; int used_send_buffer; // the number of bytes // allocated and used as receive buffer, respectively. int receive_buffer_size; int used_receive_buffer; int receive_buffer_watermark; // the number of pieces this peer has participated in sending us that // turned out to fail the hash check. int num_hashfails; // this is the number of requests we have sent to this peer that we // haven't got a response for yet int download_queue_length; // the number of block requests that have timed out, and are still in the // download queue int timed_out_requests; // the number of busy requests in the download queue. A budy request is a // request for a block we've also requested from a different peer int busy_requests; // the number of requests messages that are currently in the send buffer // waiting to be sent. int requests_in_buffer; // the number of requests that is tried to be maintained (this is // typically a function of download speed) int target_dl_queue_length; // the number of piece-requests we have received from this peer // that we haven't answered with a piece yet. int upload_queue_length; // the number of times this peer has "failed". i.e. failed to connect or // disconnected us. The failcount is decremented when we see this peer in // a tracker response or peer exchange message. int failcount; // You can know which piece, and which part of that piece, that is // currently being downloaded from a specific peer by looking at these // four members. ``downloading_piece_index`` is the index of the piece // that is currently being downloaded. This may be set to -1 if there's // currently no piece downloading from this peer. If it is >= 0, the // other three members are valid. ``downloading_block_index`` is the // index of the block (or sub-piece) that is being downloaded. // ``downloading_progress`` is the number of bytes of this block we have // received from the peer, and ``downloading_total`` is the total number // of bytes in this block. piece_index_t downloading_piece_index; int downloading_block_index; int downloading_progress; int downloading_total; // the kind of connection this is. Used for the connection_type field. enum connection_type_t { // Regular bittorrent connection standard_bittorrent = 0, // HTTP connection using the `BEP 19`_ protocol web_seed = 1, // HTTP connection using the `BEP 17`_ protocol http_seed = 2 }; // the kind of connection this peer uses. See connection_type_t. int connection_type; #ifndef TORRENT_NO_DEPRECATE // an estimate of the rate this peer is downloading at, in // bytes per second. int remote_dl_rate; #else int deprecated_remote_dl_rate; #endif // the number of bytes this peer has pending in the disk-io thread. // Downloaded and waiting to be written to disk. This is what is capped // by ``settings_pack::max_queued_disk_bytes``. int pending_disk_bytes; // number of outstanding bytes to read // from disk int pending_disk_read_bytes; // the number of bytes this peer has been assigned to be allowed to send // and receive until it has to request more quota from the bandwidth // manager. int send_quota; int receive_quota; // an estimated round trip time to this peer, in milliseconds. It is // estimated by timing the the tcp ``connect()``. It may be 0 for // incoming connections. int rtt; // the number of pieces this peer has. int num_pieces; // the highest download and upload rates seen on this connection. They // are given in bytes per second. This number is reset to 0 on reconnect. int download_rate_peak; int upload_rate_peak; // the progress of the peer in the range [0, 1]. This is always 0 when // floating point operations are disabled, instead use ``progress_ppm``. float progress; // [0, 1] // indicates the download progress of the peer in the range [0, 1000000] // (parts per million). int progress_ppm; // this is an estimation of the upload rate, to this peer, where it will // unchoke us. This is a coarse estimation based on the rate at which // we sent right before we were choked. This is primarily used for the // bittyrant choking algorithm. int estimated_reciprocation_rate; // the IP-address to this peer. The type is an asio endpoint. For // more info, see the asio_ documentation. // // .. _asio: http://asio.sourceforge.net/asio-0.3.8/doc/asio/reference.html tcp::endpoint ip; // the IP and port pair the socket is bound to locally. i.e. the IP // address of the interface it's going out over. This may be useful for // multi-homed clients with multiple interfaces to the internet. tcp::endpoint local_endpoint; // bits for the read_state and write_state enum bw_state { // The peer is not waiting for any external events to // send or receive data. bw_idle = 0, // The peer is waiting for the rate limiter. bw_limit = 1, // The peer has quota and is currently waiting for a // network read or write operation to complete. This is // the state all peers are in if there are no bandwidth // limits. bw_network = 2, // The peer is waiting for the disk I/O thread to catch // up writing buffers to disk before downloading more. bw_disk = 4 }; #ifndef TORRENT_NO_DEPRECATE enum bw_state_deprecated { bw_torrent = bw_limit, bw_global = bw_limit }; #endif // bitmasks indicating what state this peer // is in with regards to sending and receiving data. The states are declared in the // bw_state enum. char read_state; char write_state; #ifndef TORRENT_NO_DEPRECATE // the number of bytes per second we are allowed to send to or receive // from this peer. It may be -1 if there's no local limit on the peer. // The global limit and the torrent limit may also be enforced. int upload_limit; int download_limit; // a measurement of the balancing of free download (that we get) and free // upload that we give. Every peer gets a certain amount of free upload, // but this member says how much *extra* free upload this peer has got. // If it is a negative number it means that this was a peer from which we // have got this amount of free download. std::int64_t load_balancing; #endif }; // internal struct TORRENT_EXTRA_EXPORT peer_list_entry { // internal enum flags_t { banned = 1 }; // internal tcp::endpoint ip; // internal int flags; // internal std::uint8_t failcount; // internal std::uint8_t source; }; } #endif // TORRENT_PEER_INFO_HPP_INCLUDED
33.663677
85
0.722792
naftaly
33e60a5c2b62794381a9ff913be93edf563b3831
10,939
hpp
C++
include/UnityEngine/ResourceManagement/Util/ResourceManagerConfig.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/UnityEngine/ResourceManagement/Util/ResourceManagerConfig.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/UnityEngine/ResourceManagement/Util/ResourceManagerConfig.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "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" #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: Array class Array; // Forward declaring type: Type class Type; } // Forward declaring namespace: UnityEngine namespace UnityEngine { // Forward declaring type: Object class Object; } // Forward declaring namespace: System::Collections namespace System::Collections { // Forward declaring type: IList class IList; } // Completed forward declares // Type namespace: UnityEngine.ResourceManagement.Util namespace UnityEngine::ResourceManagement::Util { // Forward declaring type: ResourceManagerConfig class ResourceManagerConfig; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::UnityEngine::ResourceManagement::Util::ResourceManagerConfig); DEFINE_IL2CPP_ARG_TYPE(::UnityEngine::ResourceManagement::Util::ResourceManagerConfig*, "UnityEngine.ResourceManagement.Util", "ResourceManagerConfig"); // Type namespace: UnityEngine.ResourceManagement.Util namespace UnityEngine::ResourceManagement::Util { // Size: 0x10 #pragma pack(push, 1) // Autogenerated type: UnityEngine.ResourceManagement.Util.ResourceManagerConfig // [TokenAttribute] Offset: FFFFFFFF class ResourceManagerConfig : public ::Il2CppObject { public: // static System.Boolean ExtractKeyAndSubKey(System.Object keyObj, out System.String mainKey, out System.String subKey) // Offset: 0x1E9DE20 static bool ExtractKeyAndSubKey(::Il2CppObject* keyObj, ByRef<::StringW> mainKey, ByRef<::StringW> subKey); // static public System.Boolean IsPathRemote(System.String path) // Offset: 0x1E9C320 static bool IsPathRemote(::StringW path); // static public System.Boolean ShouldPathUseWebRequest(System.String path) // Offset: 0x1E9D18C static bool ShouldPathUseWebRequest(::StringW path); // static public System.Array CreateArrayResult(System.Type type, UnityEngine.Object[] allAssets) // Offset: 0x1E9EBF8 static ::System::Array* CreateArrayResult(::System::Type* type, ::ArrayW<::UnityEngine::Object*> allAssets); // static public TObject CreateArrayResult(UnityEngine.Object[] allAssets) // Offset: 0xFFFFFFFFFFFFFFFF template<class TObject> static TObject CreateArrayResult(::ArrayW<::UnityEngine::Object*> allAssets) { static auto ___internal__logger = ::Logger::get().WithContext("::UnityEngine::ResourceManagement::Util::ResourceManagerConfig::CreateArrayResult"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.ResourceManagement.Util", "ResourceManagerConfig", "CreateArrayResult", std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<TObject>::get()}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(allAssets)}))); static auto* ___generic__method = THROW_UNLESS(::il2cpp_utils::MakeGenericMethod(___internal__method, std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<TObject>::get()})); return ::il2cpp_utils::RunMethodRethrow<TObject, false>(static_cast<Il2CppObject*>(nullptr), ___generic__method, allAssets); } // static public System.Collections.IList CreateListResult(System.Type type, UnityEngine.Object[] allAssets) // Offset: 0x1E9EDC8 static ::System::Collections::IList* CreateListResult(::System::Type* type, ::ArrayW<::UnityEngine::Object*> allAssets); // static public TObject CreateListResult(UnityEngine.Object[] allAssets) // Offset: 0xFFFFFFFFFFFFFFFF template<class TObject> static TObject CreateListResult(::ArrayW<::UnityEngine::Object*> allAssets) { static auto ___internal__logger = ::Logger::get().WithContext("::UnityEngine::ResourceManagement::Util::ResourceManagerConfig::CreateListResult"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.ResourceManagement.Util", "ResourceManagerConfig", "CreateListResult", std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<TObject>::get()}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(allAssets)}))); static auto* ___generic__method = THROW_UNLESS(::il2cpp_utils::MakeGenericMethod(___internal__method, std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<TObject>::get()})); return ::il2cpp_utils::RunMethodRethrow<TObject, false>(static_cast<Il2CppObject*>(nullptr), ___generic__method, allAssets); } // static public System.Boolean IsInstance() // Offset: 0xFFFFFFFFFFFFFFFF template<class T1, class T2> static bool IsInstance() { static auto ___internal__logger = ::Logger::get().WithContext("::UnityEngine::ResourceManagement::Util::ResourceManagerConfig::IsInstance"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.ResourceManagement.Util", "ResourceManagerConfig", "IsInstance", std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T1>::get(), ::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T2>::get()}, ::std::vector<const Il2CppType*>{}))); static auto* ___generic__method = THROW_UNLESS((::il2cpp_utils::MakeGenericMethod(___internal__method, std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T1>::get(), ::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T2>::get()}))); return ::il2cpp_utils::RunMethodRethrow<bool, false>(static_cast<Il2CppObject*>(nullptr), ___generic__method); } }; // UnityEngine.ResourceManagement.Util.ResourceManagerConfig #pragma pack(pop) } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: UnityEngine::ResourceManagement::Util::ResourceManagerConfig::ExtractKeyAndSubKey // Il2CppName: ExtractKeyAndSubKey template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::Il2CppObject*, ByRef<::StringW>, ByRef<::StringW>)>(&UnityEngine::ResourceManagement::Util::ResourceManagerConfig::ExtractKeyAndSubKey)> { static const MethodInfo* get() { static auto* keyObj = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg; static auto* mainKey = &::il2cpp_utils::GetClassFromName("System", "String")->this_arg; static auto* subKey = &::il2cpp_utils::GetClassFromName("System", "String")->this_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::ResourceManagement::Util::ResourceManagerConfig*), "ExtractKeyAndSubKey", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{keyObj, mainKey, subKey}); } }; // Writing MetadataGetter for method: UnityEngine::ResourceManagement::Util::ResourceManagerConfig::IsPathRemote // Il2CppName: IsPathRemote template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::StringW)>(&UnityEngine::ResourceManagement::Util::ResourceManagerConfig::IsPathRemote)> { static const MethodInfo* get() { static auto* path = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::ResourceManagement::Util::ResourceManagerConfig*), "IsPathRemote", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{path}); } }; // Writing MetadataGetter for method: UnityEngine::ResourceManagement::Util::ResourceManagerConfig::ShouldPathUseWebRequest // Il2CppName: ShouldPathUseWebRequest template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::StringW)>(&UnityEngine::ResourceManagement::Util::ResourceManagerConfig::ShouldPathUseWebRequest)> { static const MethodInfo* get() { static auto* path = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::ResourceManagement::Util::ResourceManagerConfig*), "ShouldPathUseWebRequest", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{path}); } }; // Writing MetadataGetter for method: UnityEngine::ResourceManagement::Util::ResourceManagerConfig::CreateArrayResult // Il2CppName: CreateArrayResult template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Array* (*)(::System::Type*, ::ArrayW<::UnityEngine::Object*>)>(&UnityEngine::ResourceManagement::Util::ResourceManagerConfig::CreateArrayResult)> { static const MethodInfo* get() { static auto* type = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg; static auto* allAssets = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("UnityEngine", "Object"), 1)->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::ResourceManagement::Util::ResourceManagerConfig*), "CreateArrayResult", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type, allAssets}); } }; // Writing MetadataGetter for method: UnityEngine::ResourceManagement::Util::ResourceManagerConfig::CreateArrayResult // Il2CppName: CreateArrayResult // Cannot write MetadataGetter for generic methods! // Writing MetadataGetter for method: UnityEngine::ResourceManagement::Util::ResourceManagerConfig::CreateListResult // Il2CppName: CreateListResult template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Collections::IList* (*)(::System::Type*, ::ArrayW<::UnityEngine::Object*>)>(&UnityEngine::ResourceManagement::Util::ResourceManagerConfig::CreateListResult)> { static const MethodInfo* get() { static auto* type = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg; static auto* allAssets = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("UnityEngine", "Object"), 1)->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::ResourceManagement::Util::ResourceManagerConfig*), "CreateListResult", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type, allAssets}); } }; // Writing MetadataGetter for method: UnityEngine::ResourceManagement::Util::ResourceManagerConfig::CreateListResult // Il2CppName: CreateListResult // Cannot write MetadataGetter for generic methods! // Writing MetadataGetter for method: UnityEngine::ResourceManagement::Util::ResourceManagerConfig::IsInstance // Il2CppName: IsInstance // Cannot write MetadataGetter for generic methods!
71.032468
359
0.767438
RedBrumbler
33e7af76f8979940b9b763a5b99b417725373c6a
3,123
hpp
C++
api/python/enums_wrapper.hpp
ahawad/LIEF
88931ea405d9824faa5749731427533e0c27173e
[ "Apache-2.0" ]
null
null
null
api/python/enums_wrapper.hpp
ahawad/LIEF
88931ea405d9824faa5749731427533e0c27173e
[ "Apache-2.0" ]
null
null
null
api/python/enums_wrapper.hpp
ahawad/LIEF
88931ea405d9824faa5749731427533e0c27173e
[ "Apache-2.0" ]
null
null
null
/* Copyright 2017 - 2022 R. Thomas * Copyright 2017 - 2022 Quarkslab * * 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 PY_LIEF_ENUMS_WRAPPER_H_ #define PY_LIEF_ENUMS_WRAPPER_H_ #include <pybind11/pybind11.h> #include <pybind11/stl.h> #include "LIEF/visibility.h" namespace py = pybind11; namespace LIEF { template <class Type> class LIEF_LOCAL enum_ : public pybind11::enum_<Type> { public: using py::enum_<Type>::def; using py::enum_<Type>::def_property_readonly_static; using Scalar = typename py::enum_<Type>::Scalar; template <typename... Extra> enum_(const py::handle& scope, const char* name, const Extra&... extra) : py::enum_<Type>{scope, name, extra...} { constexpr bool is_arithmetic = py::detail::any_of<std::is_same<py::arithmetic, Extra>...>::value; def("__eq__", [](const Type& value, Scalar value2) { return (Scalar)value == value2; }); def("__ne__", [](const Type& value, Scalar value2) { return (Scalar)value != value2; }); if (is_arithmetic) { def("__lt__", [](const Type& value, Scalar value2) { return (Scalar)value < value2; }); def("__gt__", [](const Type& value, Scalar value2) { return (Scalar)value > value2; }); def("__le__", [](const Type& value, Scalar value2) { return (Scalar)value <= value2; }); def("__ge__", [](const Type& value, Scalar value2) { return (Scalar)value >= value2; }); def("__invert__", [](const Type& value) { return ~((Scalar)value); }); def("__and__", [](const Type& value, Scalar value2) { return (Scalar)value & value2; }); def("__or__", [](const Type& value, Scalar value2) { return (Scalar)value | value2; }); def("__xor__", [](const Type& value, Scalar value2) { return (Scalar)value ^ value2; }); def("__rand__", [](const Type& value, Scalar value2) { return (Scalar)value & value2; }); def("__ror__", [](const Type& value, Scalar value2) { return (Scalar)value | value2; }); def("__rxor__", [](const Type& value, Scalar value2) { return (Scalar)value ^ value2; }); def("__and__", [](const Type& value, const Type& value2) { return (Scalar)value & (Scalar)value2; }); def("__or__", [](const Type& value, const Type& value2) { return (Scalar)value | (Scalar)value2; }); def("__xor__", [](const Type& value, const Type& value2) { return (Scalar)value ^ (Scalar)value2; }); } } }; } // namespace LIEF #endif
33.580645
76
0.621198
ahawad
33e7d7e1a5e2e9d387a045cc5b5f8419ad582443
2,071
hpp
C++
include/qemu-link.hpp
redcathedral/qemulib
e88ad47c9563094a20c059d59466a34732f4d452
[ "Apache-2.0" ]
null
null
null
include/qemu-link.hpp
redcathedral/qemulib
e88ad47c9563094a20c059d59466a34732f4d452
[ "Apache-2.0" ]
null
null
null
include/qemu-link.hpp
redcathedral/qemulib
e88ad47c9563094a20c059d59466a34732f4d452
[ "Apache-2.0" ]
null
null
null
#ifndef __QEMU_LINK_HPP__ #define __QEMU_LINK_HPP__ #include <netinet/ether.h> #include <netlink/netlink.h> #include <netlink/route/link.h> #include <netlink/route/link/macvtap.h> #include <linux/if_tun.h> // for tun-devices. #include <linux/netlink.h> #include <net/if.h> #include <string> #include <iostream> #include <random> #include <memory> #include <sys/ioctl.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <sys/un.h> #include <qemu-hypervisor.hpp> std::ostream &operator<<(std::ostream &os, const struct Network &model); enum NetworkTopology { Bridge, Macvtap, Tuntap }; enum NetworkMacvtapMode { Private, VEPA, Bridged, Passthrough }; struct Network { NetworkTopology topology; NetworkMacvtapMode macvtapmode; std::string interface; std::string name; std::string net_namespace; std::string cidr; bool nat; std::string router; }; std::string QEMU_allocate_tun(QemuContext &ctx); std::string QEMU_allocate_macvtap(QemuContext &ctx, const struct Network &); std::string generateRandomMACAddress(); std::string QEMU_Generate_Link_Name(std::string prefix, int length); void QEMU_delete_link(QemuContext &ctx, std::string interface); int QEMU_OpenQMPSocket(QemuContext &ctx); int QEMU_OpenQMPSocketFromPath(std::string &guestid); int QEMU_OpenQGASocketFromPath(std::string &guestid); int QEMU_allocate_bridge(std::string bridge); void QEMU_enslave_interface(std::string bridge, std::string slave); int QEMU_tun_allocate(const std::string device); int QEMU_link_up(const std::string ifname); void QEMU_set_namespace(std::string namespace_path); void QEMU_set_default_namespace(); void QEMU_set_interface_address(const std::string device, const std::string address, const std::string cidr); std::string QEMU_get_interface_cidr(const std::string device); void QEMU_iptables_set_masquerade(std::string cidr); void QEMU_set_router(bool on); int macvtapModes(const enum NetworkMacvtapMode &net); std::string strMacvtapModes(const enum NetworkMacvtapMode &net); #endif
26.896104
109
0.765331
redcathedral
33e925400e621582ecd7a823f10c1887dc2dd163
234
hpp
C++
internal/include/dknn/__detail__/local_jobs.hpp
didrod/dknn
196092772bf7e8b602878b83983fb96f28665dae
[ "BSD-2-Clause" ]
null
null
null
internal/include/dknn/__detail__/local_jobs.hpp
didrod/dknn
196092772bf7e8b602878b83983fb96f28665dae
[ "BSD-2-Clause" ]
null
null
null
internal/include/dknn/__detail__/local_jobs.hpp
didrod/dknn
196092772bf7e8b602878b83983fb96f28665dae
[ "BSD-2-Clause" ]
null
null
null
#pragma once #include "dknn/typedefs.hpp" namespace dknn { knn_query_result_t nearest_k(size_t k, feature_t const& query_feature); knn_set_query_result_t nearest_k(size_t k, feature_set_t const& query_set); } // namespace dknn
26
77
0.786325
didrod
33ea2f511db83e311694cd2c091f243d8e28ff67
2,006
cpp
C++
testing_environmen/testing_environmen/src/camera.cpp
llGuy/gamedev
16aa203934fd767926c58558e021630288556399
[ "MIT" ]
null
null
null
testing_environmen/testing_environmen/src/camera.cpp
llGuy/gamedev
16aa203934fd767926c58558e021630288556399
[ "MIT" ]
4
2018-12-24T11:16:53.000Z
2018-12-24T11:20:29.000Z
testing_environmen/testing_environmen/src/camera.cpp
llGuy/gamedev
16aa203934fd767926c58558e021630288556399
[ "MIT" ]
null
null
null
#include "camera.h" #include "detail.h" #include <utility> #include "ecs/basic_components.h" #include <glm/gtx/transform.hpp> #define SENSITIVITY 0.02f auto look_fps(glm::vec2 const & cursor_dif, glm::vec3 const & direction, f32 elapsed) -> glm::vec3 { using detail::up; glm::vec3 res = direction; f32 x_angle = glm::radians(-cursor_dif.x) * SENSITIVITY;// *elapsed; f32 y_angle = glm::radians(-cursor_dif.y) * SENSITIVITY;// *elapsed; res = glm::mat3(glm::rotate(x_angle, up)) * res; glm::vec3 rotate_y = glm::cross(res, up); res = glm::mat3(glm::rotate(y_angle, rotate_y)) * res; return res; } auto pitch_yaw(std::pair<f32, f32> const & pair, glm::vec2 const & diff) -> std::pair<f32, f32> { f32 pitch_change = diff.y * SENSITIVITY; f32 new_pitch = pair.first + pitch_change; f32 yaw_change = diff.x * SENSITIVITY; f32 new_yaw = pair.second + yaw_change; return std::make_pair( new_pitch, new_yaw ); } auto invert_matrix(camera & cam) -> glm::mat4 { using detail::up; glm::vec3 inverted_position = cam.pos(); glm::vec3 inverted_direction = cam.dir(); inverted_position.y *= -1; inverted_direction.y *= -1; return glm::lookAt(inverted_position, inverted_position + inverted_direction, up); } auto camera::bind_entity(i32 index, vec_dd<entity> & entities) -> void { bound_entity_index = index; height_component_index = entities[bound_entity_index].get_component_index<height>(); } auto camera::update_view_matrix(vec_dd<entity> & entities, entity_cs & ecs) -> void { entity_data & data = entities[bound_entity_index].get_data(); if (bound_entity_index == -1) view_matrix = glm::lookAt(glm::vec3(0), glm::vec3(0.1, 0.1, 1.0), glm::vec3(0, 1, 0)); else { (position = data.pos).y += ecs.get_component<height>(height_component_index).value.val + 2.0f; direction = data.dir; view_matrix = glm::lookAt(position, position + direction, detail::up); } } auto camera::get_yaw(void) -> f32 & { return yaw; } auto camera::get_pitch(void) -> f32 & { return pitch; }
26.394737
117
0.700897
llGuy
33ec05b76ab96ef6d5002f86515c99588c89fb41
28,100
cpp
C++
src/pdf/SkPDFFont.cpp
kizerkizer/skia
87b57d083321a21b64979e0e3c92d34c8678e273
[ "BSD-3-Clause" ]
8
2019-04-20T09:12:17.000Z
2019-09-06T20:04:22.000Z
src/pdf/SkPDFFont.cpp
AzureMentor/skia
63b4d5880a5bb3553ce9283400152fa5ed9821f6
[ "BSD-3-Clause" ]
3
2019-04-29T06:34:00.000Z
2019-08-18T11:56:32.000Z
src/pdf/SkPDFFont.cpp
AzureMentor/skia
63b4d5880a5bb3553ce9283400152fa5ed9821f6
[ "BSD-3-Clause" ]
4
2019-04-19T04:17:34.000Z
2019-05-01T11:19:38.000Z
/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "include/core/SkBitmap.h" #include "include/core/SkData.h" #include "include/core/SkFont.h" #include "include/core/SkFontMetrics.h" #include "include/core/SkFontTypes.h" #include "include/core/SkImage.h" #include "include/core/SkImageInfo.h" #include "include/core/SkMatrix.h" #include "include/core/SkPaint.h" #include "include/core/SkPath.h" #include "include/core/SkPoint.h" #include "include/core/SkRect.h" #include "include/core/SkRefCnt.h" #include "include/core/SkScalar.h" #include "include/core/SkStream.h" #include "include/core/SkString.h" #include "include/core/SkSurfaceProps.h" #include "include/core/SkTypes.h" #include "include/docs/SkPDFDocument.h" #include "include/private/SkBitmaskEnum.h" #include "include/private/SkTHash.h" #include "include/private/SkTo.h" #include "src/core/SkGlyph.h" #include "src/core/SkImagePriv.h" #include "src/core/SkMakeUnique.h" #include "src/core/SkMask.h" #include "src/core/SkScalerContext.h" #include "src/core/SkStrike.h" #include "src/core/SkStrikeSpec.h" #include "src/pdf/SkPDFBitmap.h" #include "src/pdf/SkPDFDocumentPriv.h" #include "src/pdf/SkPDFFont.h" #include "src/pdf/SkPDFMakeCIDGlyphWidthsArray.h" #include "src/pdf/SkPDFMakeToUnicodeCmap.h" #include "src/pdf/SkPDFSubsetFont.h" #include "src/pdf/SkPDFType1Font.h" #include "src/pdf/SkPDFUtils.h" #include "src/utils/SkUTF.h" #include <limits.h> #include <initializer_list> #include <memory> #include <utility> void SkPDFFont::GetType1GlyphNames(const SkTypeface& face, SkString* dst) { face.getPostScriptGlyphNames(dst); } namespace { // PDF's notion of symbolic vs non-symbolic is related to the character set, not // symbols vs. characters. Rarely is a font the right character set to call it // non-symbolic, so always call it symbolic. (PDF 1.4 spec, section 5.7.1) static const int32_t kPdfSymbolic = 4; // scale from em-units to base-1000, returning as a SkScalar inline SkScalar from_font_units(SkScalar scaled, uint16_t emSize) { return emSize == 1000 ? scaled : scaled * 1000 / emSize; } inline SkScalar scaleFromFontUnits(int16_t val, uint16_t emSize) { return from_font_units(SkIntToScalar(val), emSize); } void setGlyphWidthAndBoundingBox(SkScalar width, SkIRect box, SkDynamicMemoryWStream* content) { // Specify width and bounding box for the glyph. SkPDFUtils::AppendScalar(width, content); content->writeText(" 0 "); content->writeDecAsText(box.fLeft); content->writeText(" "); content->writeDecAsText(box.fTop); content->writeText(" "); content->writeDecAsText(box.fRight); content->writeText(" "); content->writeDecAsText(box.fBottom); content->writeText(" d1\n"); } } // namespace /////////////////////////////////////////////////////////////////////////////// // class SkPDFFont /////////////////////////////////////////////////////////////////////////////// /* Resources are canonicalized and uniqueified by pointer so there has to be * some additional state indicating which subset of the font is used. It * must be maintained at the document granularity. */ SkPDFFont::~SkPDFFont() = default; SkPDFFont::SkPDFFont(SkPDFFont&&) = default; SkPDFFont& SkPDFFont::operator=(SkPDFFont&&) = default; static bool can_embed(const SkAdvancedTypefaceMetrics& metrics) { return !SkToBool(metrics.fFlags & SkAdvancedTypefaceMetrics::kNotEmbeddable_FontFlag); } const SkAdvancedTypefaceMetrics* SkPDFFont::GetMetrics(const SkTypeface* typeface, SkPDFDocument* canon) { SkASSERT(typeface); SkFontID id = typeface->uniqueID(); if (std::unique_ptr<SkAdvancedTypefaceMetrics>* ptr = canon->fTypefaceMetrics.find(id)) { return ptr->get(); // canon retains ownership. } int count = typeface->countGlyphs(); if (count <= 0 || count > 1 + SkTo<int>(UINT16_MAX)) { // Cache nullptr to skip this check. Use SkSafeUnref(). canon->fTypefaceMetrics.set(id, nullptr); return nullptr; } std::unique_ptr<SkAdvancedTypefaceMetrics> metrics = typeface->getAdvancedMetrics(); if (!metrics) { metrics = skstd::make_unique<SkAdvancedTypefaceMetrics>(); } if (0 == metrics->fStemV || 0 == metrics->fCapHeight) { SkFont font; font.setHinting(SkFontHinting::kNone); font.setTypeface(sk_ref_sp(typeface)); font.setSize(1000); // glyph coordinate system if (0 == metrics->fStemV) { // Figure out a good guess for StemV - Min width of i, I, !, 1. // This probably isn't very good with an italic font. int16_t stemV = SHRT_MAX; for (char c : {'i', 'I', '!', '1'}) { uint16_t g = font.unicharToGlyph(c); SkRect bounds; font.getBounds(&g, 1, &bounds, nullptr); stemV = SkTMin(stemV, SkToS16(SkScalarRoundToInt(bounds.width()))); } metrics->fStemV = stemV; } if (0 == metrics->fCapHeight) { // Figure out a good guess for CapHeight: average the height of M and X. SkScalar capHeight = 0; for (char c : {'M', 'X'}) { uint16_t g = font.unicharToGlyph(c); SkRect bounds; font.getBounds(&g, 1, &bounds, nullptr); capHeight += bounds.height(); } metrics->fCapHeight = SkToS16(SkScalarRoundToInt(capHeight / 2)); } } return canon->fTypefaceMetrics.set(id, std::move(metrics))->get(); } const std::vector<SkUnichar>& SkPDFFont::GetUnicodeMap(const SkTypeface* typeface, SkPDFDocument* canon) { SkASSERT(typeface); SkASSERT(canon); SkFontID id = typeface->uniqueID(); if (std::vector<SkUnichar>* ptr = canon->fToUnicodeMap.find(id)) { return *ptr; } std::vector<SkUnichar> buffer(typeface->countGlyphs()); typeface->getGlyphToUnicodeMap(buffer.data()); return *canon->fToUnicodeMap.set(id, std::move(buffer)); } SkAdvancedTypefaceMetrics::FontType SkPDFFont::FontType(const SkAdvancedTypefaceMetrics& metrics) { if (SkToBool(metrics.fFlags & SkAdvancedTypefaceMetrics::kMultiMaster_FontFlag) || SkToBool(metrics.fFlags & SkAdvancedTypefaceMetrics::kNotEmbeddable_FontFlag)) { // force Type3 fallback. return SkAdvancedTypefaceMetrics::kOther_Font; } return metrics.fType; } static SkGlyphID first_nonzero_glyph_for_single_byte_encoding(SkGlyphID gid) { return gid != 0 ? gid - (gid - 1) % 255 : 1; } SkPDFFont* SkPDFFont::GetFontResource(SkPDFDocument* doc, const SkGlyph* glyph, SkTypeface* face) { SkASSERT(doc); SkASSERT(face); // All SkPDFDevice::internalDrawText ensures this. const SkAdvancedTypefaceMetrics* fontMetrics = SkPDFFont::GetMetrics(face, doc); SkASSERT(fontMetrics); // SkPDFDevice::internalDrawText ensures the typeface is good. // GetMetrics only returns null to signify a bad typeface. const SkAdvancedTypefaceMetrics& metrics = *fontMetrics; SkAdvancedTypefaceMetrics::FontType type = SkPDFFont::FontType(metrics); if (!(glyph->isEmpty() || glyph->path())) { type = SkAdvancedTypefaceMetrics::kOther_Font; } bool multibyte = SkPDFFont::IsMultiByte(type); SkGlyphID subsetCode = multibyte ? 0 : first_nonzero_glyph_for_single_byte_encoding(glyph->getGlyphID()); uint64_t fontID = (static_cast<uint64_t>(SkTypeface::UniqueID(face)) << 16) | subsetCode; if (SkPDFFont* found = doc->fFontMap.find(fontID)) { SkASSERT(multibyte == found->multiByteGlyphs()); return found; } sk_sp<SkTypeface> typeface(sk_ref_sp(face)); SkASSERT(typeface); SkGlyphID lastGlyph = SkToU16(typeface->countGlyphs() - 1); // should be caught by SkPDFDevice::internalDrawText SkASSERT(glyph->getGlyphID() <= lastGlyph); SkGlyphID firstNonZeroGlyph; if (multibyte) { firstNonZeroGlyph = 1; } else { firstNonZeroGlyph = subsetCode; lastGlyph = SkToU16(SkTMin<int>((int)lastGlyph, 254 + (int)subsetCode)); } auto ref = doc->reserveRef(); return doc->fFontMap.set( fontID, SkPDFFont(std::move(typeface), firstNonZeroGlyph, lastGlyph, type, ref)); } SkPDFFont::SkPDFFont(sk_sp<SkTypeface> typeface, SkGlyphID firstGlyphID, SkGlyphID lastGlyphID, SkAdvancedTypefaceMetrics::FontType fontType, SkPDFIndirectReference indirectReference) : fTypeface(std::move(typeface)) , fGlyphUsage(firstGlyphID, lastGlyphID) , fIndirectReference(indirectReference) , fFontType(fontType) {} void SkPDFFont::PopulateCommonFontDescriptor(SkPDFDict* descriptor, const SkAdvancedTypefaceMetrics& metrics, uint16_t emSize, int16_t defaultWidth) { descriptor->insertName("FontName", metrics.fPostScriptName); descriptor->insertInt("Flags", (size_t)(metrics.fStyle | kPdfSymbolic)); descriptor->insertScalar("Ascent", scaleFromFontUnits(metrics.fAscent, emSize)); descriptor->insertScalar("Descent", scaleFromFontUnits(metrics.fDescent, emSize)); descriptor->insertScalar("StemV", scaleFromFontUnits(metrics.fStemV, emSize)); descriptor->insertScalar("CapHeight", scaleFromFontUnits(metrics.fCapHeight, emSize)); descriptor->insertInt("ItalicAngle", metrics.fItalicAngle); descriptor->insertObject("FontBBox", SkPDFMakeArray(scaleFromFontUnits(metrics.fBBox.left(), emSize), scaleFromFontUnits(metrics.fBBox.bottom(), emSize), scaleFromFontUnits(metrics.fBBox.right(), emSize), scaleFromFontUnits(metrics.fBBox.top(), emSize))); if (defaultWidth > 0) { descriptor->insertScalar("MissingWidth", scaleFromFontUnits(defaultWidth, emSize)); } } /////////////////////////////////////////////////////////////////////////////// // Type0Font /////////////////////////////////////////////////////////////////////////////// // if possible, make no copy. static sk_sp<SkData> stream_to_data(std::unique_ptr<SkStreamAsset> stream) { SkASSERT(stream); (void)stream->rewind(); SkASSERT(stream->hasLength()); size_t size = stream->getLength(); if (const void* base = stream->getMemoryBase()) { SkData::ReleaseProc proc = [](const void*, void* ctx) { delete (SkStreamAsset*)ctx; }; return SkData::MakeWithProc(base, size, proc, stream.release()); } return SkData::MakeFromStream(stream.get(), size); } static void emit_subset_type0(const SkPDFFont& font, SkPDFDocument* doc) { const SkAdvancedTypefaceMetrics* metricsPtr = SkPDFFont::GetMetrics(font.typeface(), doc); SkASSERT(metricsPtr); if (!metricsPtr) { return; } const SkAdvancedTypefaceMetrics& metrics = *metricsPtr; SkASSERT(can_embed(metrics)); SkAdvancedTypefaceMetrics::FontType type = font.getType(); SkTypeface* face = font.typeface(); SkASSERT(face); auto descriptor = SkPDFMakeDict("FontDescriptor"); uint16_t emSize = SkToU16(font.typeface()->getUnitsPerEm()); SkPDFFont::PopulateCommonFontDescriptor(descriptor.get(), metrics, emSize , 0); int ttcIndex; std::unique_ptr<SkStreamAsset> fontAsset = face->openStream(&ttcIndex); size_t fontSize = fontAsset ? fontAsset->getLength() : 0; if (0 == fontSize) { SkDebugf("Error: (SkTypeface)(%p)::openStream() returned " "empty stream (%p) when identified as kType1CID_Font " "or kTrueType_Font.\n", face, fontAsset.get()); } else { switch (type) { case SkAdvancedTypefaceMetrics::kTrueType_Font: { if (!SkToBool(metrics.fFlags & SkAdvancedTypefaceMetrics::kNotSubsettable_FontFlag)) { SkASSERT(font.firstGlyphID() == 1); sk_sp<SkData> subsetFontData = SkPDFSubsetFont( stream_to_data(std::move(fontAsset)), font.glyphUsage(), doc->metadata().fSubsetter, metrics.fFontName.c_str(), ttcIndex); if (subsetFontData) { std::unique_ptr<SkPDFDict> tmp = SkPDFMakeDict(); tmp->insertInt("Length1", SkToInt(subsetFontData->size())); descriptor->insertRef( "FontFile2", SkPDFStreamOut(std::move(tmp), SkMemoryStream::Make(std::move(subsetFontData)), doc, true)); break; } // If subsetting fails, fall back to original font data. fontAsset = face->openStream(&ttcIndex); SkASSERT(fontAsset); SkASSERT(fontAsset->getLength() == fontSize); if (!fontAsset || fontAsset->getLength() == 0) { break; } } std::unique_ptr<SkPDFDict> tmp = SkPDFMakeDict(); tmp->insertInt("Length1", fontSize); descriptor->insertRef("FontFile2", SkPDFStreamOut(std::move(tmp), std::move(fontAsset), doc, true)); break; } case SkAdvancedTypefaceMetrics::kType1CID_Font: { std::unique_ptr<SkPDFDict> tmp = SkPDFMakeDict(); tmp->insertName("Subtype", "CIDFontType0C"); descriptor->insertRef("FontFile3", SkPDFStreamOut(std::move(tmp), std::move(fontAsset), doc, true)); break; } default: SkASSERT(false); } } auto newCIDFont = SkPDFMakeDict("Font"); newCIDFont->insertRef("FontDescriptor", doc->emit(*descriptor)); newCIDFont->insertName("BaseFont", metrics.fPostScriptName); switch (type) { case SkAdvancedTypefaceMetrics::kType1CID_Font: newCIDFont->insertName("Subtype", "CIDFontType0"); break; case SkAdvancedTypefaceMetrics::kTrueType_Font: newCIDFont->insertName("Subtype", "CIDFontType2"); newCIDFont->insertName("CIDToGIDMap", "Identity"); break; default: SkASSERT(false); } auto sysInfo = SkPDFMakeDict(); sysInfo->insertString("Registry", "Adobe"); sysInfo->insertString("Ordering", "Identity"); sysInfo->insertInt("Supplement", 0); newCIDFont->insertObject("CIDSystemInfo", std::move(sysInfo)); SkScalar defaultWidth = 0; { std::unique_ptr<SkPDFArray> widths = SkPDFMakeCIDGlyphWidthsArray( *face, &font.glyphUsage(), &defaultWidth); if (widths && widths->size() > 0) { newCIDFont->insertObject("W", std::move(widths)); } newCIDFont->insertScalar("DW", defaultWidth); } //////////////////////////////////////////////////////////////////////////// SkPDFDict fontDict("Font"); fontDict.insertName("Subtype", "Type0"); fontDict.insertName("BaseFont", metrics.fPostScriptName); fontDict.insertName("Encoding", "Identity-H"); auto descendantFonts = SkPDFMakeArray(); descendantFonts->appendRef(doc->emit(*newCIDFont)); fontDict.insertObject("DescendantFonts", std::move(descendantFonts)); const std::vector<SkUnichar>& glyphToUnicode = SkPDFFont::GetUnicodeMap(font.typeface(), doc); SkASSERT(SkToSizeT(font.typeface()->countGlyphs()) == glyphToUnicode.size()); std::unique_ptr<SkStreamAsset> toUnicode = SkPDFMakeToUnicodeCmap(glyphToUnicode.data(), &font.glyphUsage(), font.multiByteGlyphs(), font.firstGlyphID(), font.lastGlyphID()); fontDict.insertRef("ToUnicode", SkPDFStreamOut(nullptr, std::move(toUnicode), doc)); doc->emit(fontDict, font.indirectReference()); } /////////////////////////////////////////////////////////////////////////////// // PDFType3Font /////////////////////////////////////////////////////////////////////////////// namespace { // returns [0, first, first+1, ... last-1, last] struct SingleByteGlyphIdIterator { SingleByteGlyphIdIterator(SkGlyphID first, SkGlyphID last) : fFirst(first), fLast(last) { SkASSERT(fFirst > 0); SkASSERT(fLast >= first); } struct Iter { void operator++() { fCurrent = (0 == fCurrent) ? fFirst : fCurrent + 1; } // This is an input_iterator SkGlyphID operator*() const { return (SkGlyphID)fCurrent; } bool operator!=(const Iter& rhs) const { return fCurrent != rhs.fCurrent; } Iter(SkGlyphID f, int c) : fFirst(f), fCurrent(c) {} private: const SkGlyphID fFirst; int fCurrent; // must be int to make fLast+1 to fit }; Iter begin() const { return Iter(fFirst, 0); } Iter end() const { return Iter(fFirst, (int)fLast + 1); } private: const SkGlyphID fFirst; const SkGlyphID fLast; }; } struct ImageAndOffset { sk_sp<SkImage> fImage; SkIPoint fOffset; }; static ImageAndOffset to_image(SkGlyphID gid, SkStrike* cache) { (void)cache->prepareImage(cache->glyph(gid)); SkMask mask = cache->glyph(gid)->mask(); if (!mask.fImage) { return {nullptr, {0, 0}}; } SkIRect bounds = mask.fBounds; SkBitmap bm; switch (mask.fFormat) { case SkMask::kBW_Format: bm.allocPixels(SkImageInfo::MakeA8(bounds.width(), bounds.height())); for (int y = 0; y < bm.height(); ++y) { for (int x8 = 0; x8 < bm.width(); x8 += 8) { uint8_t v = *mask.getAddr1(x8 + bounds.x(), y + bounds.y()); int e = SkTMin(x8 + 8, bm.width()); for (int x = x8; x < e; ++x) { *bm.getAddr8(x, y) = (v >> (x & 0x7)) & 0x1 ? 0xFF : 0x00; } } } bm.setImmutable(); return {SkImage::MakeFromBitmap(bm), {bounds.x(), bounds.y()}}; case SkMask::kA8_Format: bm.installPixels(SkImageInfo::MakeA8(bounds.width(), bounds.height()), mask.fImage, mask.fRowBytes); return {SkMakeImageFromRasterBitmap(bm, kAlways_SkCopyPixelsMode), {bounds.x(), bounds.y()}}; case SkMask::kARGB32_Format: bm.installPixels(SkImageInfo::MakeN32Premul(bounds.width(), bounds.height()), mask.fImage, mask.fRowBytes); return {SkMakeImageFromRasterBitmap(bm, kAlways_SkCopyPixelsMode), {bounds.x(), bounds.y()}}; case SkMask::k3D_Format: case SkMask::kLCD16_Format: default: SkASSERT(false); return {nullptr, {0, 0}}; } } static SkPDFIndirectReference type3_descriptor(SkPDFDocument* doc, const SkTypeface* typeface, SkStrike* cache) { if (SkPDFIndirectReference* ptr = doc->fType3FontDescriptors.find(typeface->uniqueID())) { return *ptr; } SkPDFDict descriptor("FontDescriptor"); int32_t fontDescriptorFlags = kPdfSymbolic; if (const SkAdvancedTypefaceMetrics* metrics = SkPDFFont::GetMetrics(typeface, doc)) { // Type3 FontDescriptor does not require all the same fields. descriptor.insertName("FontName", metrics->fPostScriptName); descriptor.insertInt("ItalicAngle", metrics->fItalicAngle); fontDescriptorFlags |= (int32_t)metrics->fStyle; // Adobe requests CapHeight, XHeight, and StemV be added // to "greatly help our workflow downstream". if (metrics->fCapHeight != 0) { descriptor.insertInt("CapHeight", metrics->fCapHeight); } if (metrics->fStemV != 0) { descriptor.insertInt("StemV", metrics->fStemV); } SkScalar xHeight = cache->getFontMetrics().fXHeight; if (xHeight != 0) { descriptor.insertScalar("XHeight", xHeight); } } descriptor.insertInt("Flags", fontDescriptorFlags); SkPDFIndirectReference ref = doc->emit(descriptor); doc->fType3FontDescriptors.set(typeface->uniqueID(), ref); return ref; } static void emit_subset_type3(const SkPDFFont& pdfFont, SkPDFDocument* doc) { SkTypeface* typeface = pdfFont.typeface(); SkGlyphID firstGlyphID = pdfFont.firstGlyphID(); SkGlyphID lastGlyphID = pdfFont.lastGlyphID(); const SkPDFGlyphUse& subset = pdfFont.glyphUsage(); SkASSERT(lastGlyphID >= firstGlyphID); // Remove unused glyphs at the end of the range. // Keep the lastGlyphID >= firstGlyphID invariant true. while (lastGlyphID > firstGlyphID && !subset.has(lastGlyphID)) { --lastGlyphID; } int unitsPerEm; SkStrikeSpec strikeSpec = SkStrikeSpec::MakePDFVector(*typeface, &unitsPerEm); auto cache = strikeSpec.findOrCreateExclusiveStrike(); SkASSERT(cache); SkScalar emSize = (SkScalar)unitsPerEm; SkPDFDict font("Font"); font.insertName("Subtype", "Type3"); // Flip about the x-axis and scale by 1/emSize. SkMatrix fontMatrix; fontMatrix.setScale(SkScalarInvert(emSize), -SkScalarInvert(emSize)); font.insertObject("FontMatrix", SkPDFUtils::MatrixToArray(fontMatrix)); auto charProcs = SkPDFMakeDict(); auto encoding = SkPDFMakeDict("Encoding"); auto encDiffs = SkPDFMakeArray(); // length(firstGlyphID .. lastGlyphID) == lastGlyphID - firstGlyphID + 1 // plus 1 for glyph 0; SkASSERT(firstGlyphID > 0); SkASSERT(lastGlyphID >= firstGlyphID); int glyphCount = lastGlyphID - firstGlyphID + 2; // one other entry for the index of first glyph. encDiffs->reserve(glyphCount + 1); encDiffs->appendInt(0); // index of first glyph auto widthArray = SkPDFMakeArray(); widthArray->reserve(glyphCount); SkIRect bbox = SkIRect::MakeEmpty(); std::vector<std::pair<SkGlyphID, SkPDFIndirectReference>> imageGlyphs; for (SkGlyphID gID : SingleByteGlyphIdIterator(firstGlyphID, lastGlyphID)) { bool skipGlyph = gID != 0 && !subset.has(gID); SkString characterName; SkScalar advance = 0.0f; SkIRect glyphBBox; if (skipGlyph) { characterName.set("g0"); } else { characterName.printf("g%X", gID); SkGlyph* glyph = cache->glyph(gID); advance = glyph->advanceX(); glyphBBox = glyph->iRect(); bbox.join(glyphBBox); const SkPath* path = cache->preparePath(glyph); SkDynamicMemoryWStream content; if (path && !path->isEmpty()) { setGlyphWidthAndBoundingBox(glyph->advanceX(), glyphBBox, &content); SkPDFUtils::EmitPath(*path, SkPaint::kFill_Style, &content); SkPDFUtils::PaintPath(SkPaint::kFill_Style, path->getFillType(), &content); } else { auto pimg = to_image(gID, cache.get()); if (!pimg.fImage) { setGlyphWidthAndBoundingBox(glyph->advanceX(), glyphBBox, &content); } else { imageGlyphs.emplace_back(gID, SkPDFSerializeImage(pimg.fImage.get(), doc)); SkPDFUtils::AppendScalar(glyph->advanceX(), &content); content.writeText(" 0 d0\n"); content.writeDecAsText(pimg.fImage->width()); content.writeText(" 0 0 "); content.writeDecAsText(-pimg.fImage->height()); content.writeText(" "); content.writeDecAsText(pimg.fOffset.x()); content.writeText(" "); content.writeDecAsText(pimg.fImage->height() + pimg.fOffset.y()); content.writeText(" cm\n/X"); content.write(characterName.c_str(), characterName.size()); content.writeText(" Do\n"); } } charProcs->insertRef(characterName, SkPDFStreamOut(nullptr, content.detachAsStream(), doc)); } encDiffs->appendName(std::move(characterName)); widthArray->appendScalar(advance); } if (!imageGlyphs.empty()) { auto d0 = SkPDFMakeDict(); for (const auto& pair : imageGlyphs) { d0->insertRef(SkStringPrintf("Xg%X", pair.first), pair.second); } auto d1 = SkPDFMakeDict(); d1->insertObject("XObject", std::move(d0)); font.insertObject("Resources", std::move(d1)); } encoding->insertObject("Differences", std::move(encDiffs)); font.insertInt("FirstChar", 0); font.insertInt("LastChar", lastGlyphID - firstGlyphID + 1); /* FontBBox: "A rectangle expressed in the glyph coordinate system, specifying the font bounding box. This is the smallest rectangle enclosing the shape that would result if all of the glyphs of the font were placed with their origins coincident and then filled." */ font.insertObject("FontBBox", SkPDFMakeArray(bbox.left(), bbox.bottom(), bbox.right(), bbox.top())); font.insertName("CIDToGIDMap", "Identity"); const std::vector<SkUnichar>& glyphToUnicode = SkPDFFont::GetUnicodeMap(typeface, doc); SkASSERT(glyphToUnicode.size() == SkToSizeT(typeface->countGlyphs())); auto toUnicodeCmap = SkPDFMakeToUnicodeCmap(glyphToUnicode.data(), &subset, false, firstGlyphID, lastGlyphID); font.insertRef("ToUnicode", SkPDFStreamOut(nullptr, std::move(toUnicodeCmap), doc)); font.insertRef("FontDescriptor", type3_descriptor(doc, typeface, cache.get())); font.insertObject("Widths", std::move(widthArray)); font.insertObject("Encoding", std::move(encoding)); font.insertObject("CharProcs", std::move(charProcs)); doc->emit(font, pdfFont.indirectReference()); } void SkPDFFont::emitSubset(SkPDFDocument* doc) const { SkASSERT(fFontType != SkPDFFont().fFontType); // not default value switch (fFontType) { case SkAdvancedTypefaceMetrics::kType1CID_Font: case SkAdvancedTypefaceMetrics::kTrueType_Font: return emit_subset_type0(*this, doc); #ifndef SK_PDF_DO_NOT_SUPPORT_TYPE_1_FONTS case SkAdvancedTypefaceMetrics::kType1_Font: return SkPDFEmitType1Font(*this, doc); #endif default: return emit_subset_type3(*this, doc); } } //////////////////////////////////////////////////////////////////////////////// bool SkPDFFont::CanEmbedTypeface(SkTypeface* typeface, SkPDFDocument* doc) { const SkAdvancedTypefaceMetrics* metrics = SkPDFFont::GetMetrics(typeface, doc); return metrics && can_embed(*metrics); }
42.383107
99
0.595907
kizerkizer
33ee331e7b48d315fe6826a4c2fd61e6f5b7e61f
730
cpp
C++
testing/test_loader.cpp
sanarea/pdfium
632a6cb844457a97dd48b97ad69ab365aeb17491
[ "Apache-2.0" ]
142
2019-11-12T02:20:39.000Z
2022-03-30T05:45:26.000Z
testing/test_loader.cpp
sanarea/pdfium
632a6cb844457a97dd48b97ad69ab365aeb17491
[ "Apache-2.0" ]
3
2020-10-22T10:40:55.000Z
2022-02-19T10:00:51.000Z
testing/test_loader.cpp
sanarea/pdfium
632a6cb844457a97dd48b97ad69ab365aeb17491
[ "Apache-2.0" ]
28
2019-12-24T09:30:32.000Z
2022-03-30T05:46:29.000Z
// Copyright 2019 PDFium 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 "testing/test_loader.h" #include <string.h> #include "third_party/base/logging.h" TestLoader::TestLoader(pdfium::span<const char> span) : m_Span(span) {} // static int TestLoader::GetBlock(void* param, unsigned long pos, unsigned char* pBuf, unsigned long size) { TestLoader* pLoader = static_cast<TestLoader*>(param); if (pos + size < pos || pos + size > pLoader->m_Span.size()) { NOTREACHED(); return 0; } memcpy(pBuf, &pLoader->m_Span[pos], size); return 1; }
27.037037
73
0.628767
sanarea
33ef3b43cad609fc0d1e70da3970a20fc38e7420
4,559
cxx
C++
vtk/8.1.0/src/ThirdParty/vtkm/vtk-m/vtkm/cont/RuntimeDeviceTracker.cxx
Fresher-Chen/tarsim
9d2ec1001ee82ca11325e4b1edb8f2843e36518b
[ "Apache-2.0" ]
1
2020-03-02T17:31:48.000Z
2020-03-02T17:31:48.000Z
vtk/8.1.0/src/ThirdParty/vtkm/vtk-m/vtkm/cont/RuntimeDeviceTracker.cxx
Fresher-Chen/tarsim
9d2ec1001ee82ca11325e4b1edb8f2843e36518b
[ "Apache-2.0" ]
1
2019-06-03T17:04:59.000Z
2019-06-05T15:13:28.000Z
ThirdParty/vtkm/vtk-m/vtkm/cont/RuntimeDeviceTracker.cxx
metux/vtk8
77f907913f20295e1eacdb3aba9ed72e2b3ae917
[ "BSD-3-Clause" ]
1
2020-07-20T06:43:49.000Z
2020-07-20T06:43:49.000Z
//============================================================================ // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.txt for details. // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notice for more information. // // Copyright 2016 National Technology & Engineering Solutions of Sandia, LLC (NTESS). // Copyright 2016 UT-Battelle, LLC. // Copyright 2016 Los Alamos National Security. // // Under the terms of Contract DE-NA0003525 with NTESS, // the U.S. Government retains certain rights in this software. // // Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National // Laboratory (LANL), the U.S. Government retains certain rights in // this software. //============================================================================ #include <vtkm/cont/RuntimeDeviceTracker.h> #include <vtkm/cont/DeviceAdapter.h> #include <vtkm/cont/DeviceAdapterListTag.h> #include <vtkm/cont/ErrorBadValue.h> #include <vtkm/cont/cuda/DeviceAdapterCuda.h> #include <vtkm/cont/serial/DeviceAdapterSerial.h> #include <vtkm/cont/tbb/DeviceAdapterTBB.h> #include <algorithm> #include <sstream> #define VTKM_MAX_DEVICE_ADAPTER_ID 8 namespace vtkm { namespace cont { namespace detail { struct RuntimeDeviceTrackerInternals { bool RuntimeValid[VTKM_MAX_DEVICE_ADAPTER_ID]; }; } VTKM_CONT RuntimeDeviceTracker::RuntimeDeviceTracker() : Internals(new detail::RuntimeDeviceTrackerInternals) { this->Reset(); } VTKM_CONT RuntimeDeviceTracker::~RuntimeDeviceTracker() { } VTKM_CONT void RuntimeDeviceTracker::CheckDevice(vtkm::cont::DeviceAdapterId deviceId, const vtkm::cont::DeviceAdapterNameType& deviceName) const { if ((deviceId < 0) || (deviceId >= VTKM_MAX_DEVICE_ADAPTER_ID)) { std::stringstream message; message << "Device '" << deviceName << "' has invalid ID of " << deviceId; throw vtkm::cont::ErrorBadValue(message.str()); } } VTKM_CONT bool RuntimeDeviceTracker::CanRunOnImpl(vtkm::cont::DeviceAdapterId deviceId, const vtkm::cont::DeviceAdapterNameType& deviceName) const { this->CheckDevice(deviceId, deviceName); return this->Internals->RuntimeValid[deviceId]; } VTKM_CONT void RuntimeDeviceTracker::SetDeviceState(vtkm::cont::DeviceAdapterId deviceId, const vtkm::cont::DeviceAdapterNameType& deviceName, bool state) { this->CheckDevice(deviceId, deviceName); this->Internals->RuntimeValid[deviceId] = state; } namespace { struct VTKM_NEVER_EXPORT RuntimeDeviceTrackerResetFunctor { vtkm::cont::RuntimeDeviceTracker Tracker; VTKM_CONT RuntimeDeviceTrackerResetFunctor(const vtkm::cont::RuntimeDeviceTracker& tracker) : Tracker(tracker) { } template <typename Device> VTKM_CONT void operator()(Device) { this->Tracker.ResetDevice(Device()); } }; } VTKM_CONT void RuntimeDeviceTracker::Reset() { std::fill_n(this->Internals->RuntimeValid, VTKM_MAX_DEVICE_ADAPTER_ID, false); RuntimeDeviceTrackerResetFunctor functor(*this); vtkm::ListForEach(functor, VTKM_DEFAULT_DEVICE_ADAPTER_LIST_TAG()); } VTKM_CONT vtkm::cont::RuntimeDeviceTracker RuntimeDeviceTracker::DeepCopy() const { vtkm::cont::RuntimeDeviceTracker dest; dest.DeepCopy(*this); return dest; } VTKM_CONT void RuntimeDeviceTracker::DeepCopy(const vtkm::cont::RuntimeDeviceTracker& src) { std::copy_n( src.Internals->RuntimeValid, VTKM_MAX_DEVICE_ADAPTER_ID, this->Internals->RuntimeValid); } VTKM_CONT void RuntimeDeviceTracker::ForceDeviceImpl(vtkm::cont::DeviceAdapterId deviceId, const vtkm::cont::DeviceAdapterNameType& deviceName, bool runtimeExists) { if (!runtimeExists) { std::stringstream message; message << "Cannot force to device '" << deviceName << "' because that device is not available on this system"; throw vtkm::cont::ErrorBadValue(message.str()); } this->CheckDevice(deviceId, deviceName); std::fill_n(this->Internals->RuntimeValid, VTKM_MAX_DEVICE_ADAPTER_ID, false); this->Internals->RuntimeValid[deviceId] = runtimeExists; } VTKM_CONT vtkm::cont::RuntimeDeviceTracker GetGlobalRuntimeDeviceTracker() { static vtkm::cont::RuntimeDeviceTracker globalTracker; return globalTracker; } } } // namespace vtkm::cont
27.969325
98
0.694451
Fresher-Chen
33f2e8f075c22670de7b4841f76ad41f171d074a
836
hpp
C++
sprout/bit/count.hpp
kariya-mitsuru/Sprout
8274f34db498b02bff12277bac5416ea72e018cd
[ "BSL-1.0" ]
null
null
null
sprout/bit/count.hpp
kariya-mitsuru/Sprout
8274f34db498b02bff12277bac5416ea72e018cd
[ "BSL-1.0" ]
null
null
null
sprout/bit/count.hpp
kariya-mitsuru/Sprout
8274f34db498b02bff12277bac5416ea72e018cd
[ "BSL-1.0" ]
null
null
null
/*============================================================================= Copyright (c) 2011-2017 Bolero MURAKAMI https://github.com/bolero-MURAKAMI/Sprout Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #ifndef SPROUT_BIT_COUNT_HPP #define SPROUT_BIT_COUNT_HPP #include <sprout/config.hpp> #include <sprout/bit/cntl0.hpp> #include <sprout/bit/cntt0.hpp> #include <sprout/bit/cntl1.hpp> #include <sprout/bit/cntt1.hpp> #include <sprout/bit/popcount.hpp> #include <sprout/bit/parity.hpp> #include <sprout/bit/clz.hpp> #include <sprout/bit/ctz.hpp> #include <sprout/bit/clrsb.hpp> #endif // #ifndef SPROUT_BIT_COUNT_HPP
36.347826
80
0.604067
kariya-mitsuru
33f404d29a6bc121eb1a2ad6a2461107efc1e111
2,052
cpp
C++
libbitcoin/test/oldtests/protst.cpp
mousewu/bcclient
64ee1f6f8337103d40a4a0c3dfb73cabcd09a04c
[ "MIT" ]
8
2019-05-31T01:37:08.000Z
2021-10-19T05:52:45.000Z
libbitcoin/test/oldtests/protst.cpp
mousewu/bcclient
64ee1f6f8337103d40a4a0c3dfb73cabcd09a04c
[ "MIT" ]
3
2017-12-18T17:27:09.000Z
2018-01-15T16:50:05.000Z
libbitcoin/test/oldtests/protst.cpp
mousewu/bcclient
64ee1f6f8337103d40a4a0c3dfb73cabcd09a04c
[ "MIT" ]
5
2018-01-09T15:05:55.000Z
2020-12-17T13:27:25.000Z
/* * Copyright (c) 2011-2013 libbitcoin developers (see AUTHORS) * * This file is part of libbitcoin. * * libbitcoin is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <bitcoin/bitcoin.hpp> using namespace libbitcoin; protocol* prot; void error_exit(const std::error_code& ec) { log_fatal() << "Error: " << ec.message(); exit(-1); } void handle_stop(const std::error_code& ec) { if (ec) error_exit(ec); log_debug() << "stopped"; } void handle_start(const std::error_code& ec) { if (ec) error_exit(ec); log_debug() << "started"; //prot->stop(handle_stop); } void display_num_conns(const std::error_code& ec, size_t num) { log_debug() << num << " CONNECTIONS"; } void mewcj(channel_ptr node) { log_debug() << "New channel!"; prot->subscribe_channel(mewcj); } int main() { threadpool pool(1); hosts hst(pool); handshake hs(pool); network net(pool); prot = new protocol(pool, hst, hs, net); prot->start(handle_start); prot->subscribe_channel(mewcj); //prot->bootstrap(handle_start); //std::cin.get(); //prot->stop(handle_stop); //log_debug() << "stopping."; std::cin.get(); //while (true) //{ // prot->fetch_connection_count(display_num_conns); // sleep(1); //} pool.stop(); pool.join(); delete prot; return 0; }
25.65
75
0.663255
mousewu
33fd7113acf8a2f1d8eb3fc2e724cf06457325ad
5,292
cpp
C++
src/bolson/cli.cpp
johanpel/bolson
2855cf7e371a968a7add4da0b4c2e6abe8bc0f4c
[ "Apache-2.0" ]
2
2021-12-08T22:18:53.000Z
2022-01-24T21:51:38.000Z
src/bolson/cli.cpp
johanpel/bolson
2855cf7e371a968a7add4da0b4c2e6abe8bc0f4c
[ "Apache-2.0" ]
7
2021-03-03T13:31:16.000Z
2021-06-10T17:23:58.000Z
src/bolson/cli.cpp
johanpel/bolson
2855cf7e371a968a7add4da0b4c2e6abe8bc0f4c
[ "Apache-2.0" ]
3
2021-03-09T13:32:38.000Z
2021-12-08T22:18:40.000Z
// Copyright 2020 Teratide B.V. // // 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 "bolson/cli.h" #include <arrow/io/api.h> #include <CLI/CLI.hpp> #include <algorithm> #include "bolson/convert/converter.h" #include "bolson/parse/implementations.h" #include "bolson/publish/publisher.h" #include "bolson/status.h" namespace bolson { static void AddClientOptionsToCLI(CLI::App* sub, illex::ClientOptions* client) { sub->add_option("--host", client->host, "JSON source TCP server hostname.") ->default_val("localhost"); sub->add_option("--port", client->port, "JSON source TCP server port.") ->default_val(ILLEX_DEFAULT_PORT); } static void AddConverterOptionsToCLI(CLI::App* sub, convert::ConverterOptions* opts) { sub->add_option("--max-rows", opts->max_batch_rows, "Maximum number of rows per RecordBatch.") ->default_val(1024); sub->add_option("--max-ipc", opts->max_ipc_size, "Maximum size of IPC messages in bytes.") ->default_val(BOLSON_DEFAULT_PULSAR_MAX_MSG_SIZE); sub->add_option("--threads", opts->num_threads, "Number of threads to use for conversion.") ->default_val(1); AddParserOptions(sub, &opts->parser); } static void AddBenchOptionsToCLI(CLI::App* bench, BenchOptions* out) { // 'bench client' subcommand. auto* bench_client = bench->add_subcommand("client", "Run TCP client interface microbenchmark."); AddClientOptionsToCLI(bench_client, &out->client); // 'bench convert' subcommand. auto* bench_conv = bench->add_subcommand("convert", "Run JSON to Arrow IPC convert microbenchmark."); AddConverterOptionsToCLI(bench_conv, &out->convert.converter); bench_conv ->add_option("--num-jsons", out->convert.num_jsons, "Number of JSONs to convert.") ->default_val(1024); bench_conv->add_option("--seed", out->convert.generate.seed, "Generation seed.") ->default_val(0); bench_conv->add_option("--latency", out->convert.latency_file, "Enable batch latency measurements and write to supplied file."); bench_conv->add_option("--metrics", out->convert.metrics_file, "Write other metrics to supplied file."); bench_conv ->add_option("--repeats", out->convert.repeats, "Number of time to repeat parsing the same input.") ->default_val(1); // 'bench queue' subcommand auto* bench_queue = bench->add_subcommand("queue", "Run queue microbenchmark."); bench_queue->add_option("m,-m,--num-items,", out->queue.num_items)->default_val(256); // 'bench pulsar' subcommand auto* bench_pulsar = bench->add_subcommand("pulsar", "Run Pulsar publishing microbenchmark."); AddPublishBenchToCLI(bench_pulsar, &out->pulsar); } auto AppOptions::FromArguments(int argc, char** argv, AppOptions* out) -> Status { CLI::App app{"bolson : A JSON to Arrow IPC converter and Pulsar publishing tool."}; app.require_subcommand(); app.get_formatter()->column_width(50); // 'stream' subcommand: auto* stream = app.add_subcommand("stream", "Produce Pulsar messages from a JSON TCP stream."); stream->add_option("--latency", out->stream.latency_file, "Enable batch latency measurements and write to supplied file."); stream->add_option("--metrics", out->stream.metrics_file, "Write metrics to supplied file."); AddConverterOptionsToCLI(stream, &out->stream.converter); AddPublishOptsToCLI(stream, &out->stream.pulsar); AddClientOptionsToCLI(stream, &out->stream.client); // 'bench' subcommand: auto* bench = app.add_subcommand("bench", "Run micro-benchmarks on isolated pipeline stages.") ->require_subcommand(); AddBenchOptionsToCLI(bench, &out->bench); // Attempt to parse the CLI arguments. try { app.parse(argc, argv); } catch (CLI::CallForHelp& e) { // User wants to see help. std::cout << app.help() << std::endl; return Status::OK(); } catch (CLI::Error& e) { // There is some CLI error. std::cerr << app.help() << std::endl; return Status(Error::CLIError, "CLI Error: " + e.get_name() + ":" + e.what()); } if (stream->parsed()) { out->sub = SubCommand::STREAM; } else if (bench->parsed()) { out->sub = SubCommand::BENCH; if (bench->get_subcommand_ptr("client")->parsed()) { out->bench.bench = Bench::CLIENT; } else if (bench->get_subcommand_ptr("convert")->parsed()) { out->bench.bench = Bench::CONVERT; } else if (bench->get_subcommand_ptr("pulsar")->parsed()) { out->bench.bench = Bench::PULSAR; } else if (bench->get_subcommand_ptr("queue")->parsed()) { out->bench.bench = Bench::QUEUE; } } return Status::OK(); } } // namespace bolson
38.347826
90
0.673658
johanpel
33fda50af6c50754715fde7469bff8345751f727
2,886
cpp
C++
Foundation/testsuite/src/ActivityTest.cpp
apollovideo/poco_src
12d4908dab166983448f5e7972dd17fd584e3e03
[ "BSL-1.0" ]
1
2021-01-22T07:50:53.000Z
2021-01-22T07:50:53.000Z
Foundation/testsuite/src/ActivityTest.cpp
apollovideo/poco_src
12d4908dab166983448f5e7972dd17fd584e3e03
[ "BSL-1.0" ]
null
null
null
Foundation/testsuite/src/ActivityTest.cpp
apollovideo/poco_src
12d4908dab166983448f5e7972dd17fd584e3e03
[ "BSL-1.0" ]
1
2017-03-24T07:58:13.000Z
2017-03-24T07:58:13.000Z
// // ActivityTest.cpp // // $Id: //poco/1.4/Foundation/testsuite/src/ActivityTest.cpp#1 $ // // Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "ActivityTest.h" #include "CppUnit/TestCaller.h" #include "CppUnit/TestSuite.h" #include "Poco/Activity.h" #include "Poco/Thread.h" using Poco::Activity; using Poco::Thread; namespace { class ActiveObject { public: ActiveObject(): _activity(this, &ActiveObject::run), _count(0) { } ~ActiveObject() { } Activity<ActiveObject>& activity() { return _activity; } int count() const { return _count; } protected: void run() { while (!_activity.isStopped()) ++_count; } private: Activity<ActiveObject> _activity; int _count; }; } ActivityTest::ActivityTest(const std::string& name): CppUnit::TestCase(name) { } ActivityTest::~ActivityTest() { } void ActivityTest::testActivity() { ActiveObject activeObj; assert (activeObj.activity().isStopped()); activeObj.activity().start(); assert (!activeObj.activity().isStopped()); Thread::sleep(1000); assert (activeObj.activity().isRunning()); activeObj.activity().stop(); activeObj.activity().wait(); assert (activeObj.count() > 0); } void ActivityTest::setUp() { } void ActivityTest::tearDown() { } CppUnit::Test* ActivityTest::suite() { CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ActivityTest"); CppUnit_addTest(pSuite, ActivityTest, testActivity); return pSuite; }
23.088
78
0.718642
apollovideo
33fdb4e914baa01ea5f9dcde4faeedc59540bd0c
10,152
cc
C++
iree/samples/custom_modules/custom_modules_test.cc
xinan-jiang/iree
334aa4a5ac033399255fbd836d4fbe807c741230
[ "Apache-2.0" ]
2
2021-10-03T15:58:09.000Z
2021-11-17T10:34:35.000Z
iree/samples/custom_modules/custom_modules_test.cc
3alireza32109/iree
fd32e47b1695f105d20c06b8b20a29ef65c5e54c
[ "Apache-2.0" ]
null
null
null
iree/samples/custom_modules/custom_modules_test.cc
3alireza32109/iree
fd32e47b1695f105d20c06b8b20a29ef65c5e54c
[ "Apache-2.0" ]
null
null
null
// Copyright 2019 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. // Tests that our bytecode module can call through into our native module. #include "absl/base/macros.h" #include "absl/strings/string_view.h" #include "iree/base/api.h" #include "iree/base/logging.h" #include "iree/hal/api.h" #include "iree/hal/vmla/registration/driver_module.h" #include "iree/modules/hal/hal_module.h" #include "iree/samples/custom_modules/custom_modules_test_module.h" #include "iree/samples/custom_modules/native_module.h" #include "iree/testing/gtest.h" #include "iree/testing/status_matchers.h" #include "iree/vm/api.h" #include "iree/vm/bytecode_module.h" #include "iree/vm/ref_cc.h" namespace { class CustomModulesTest : public ::testing::Test { protected: static void SetUpTestSuite() { IREE_CHECK_OK(iree_hal_vmla_driver_module_register( iree_hal_driver_registry_default())); } virtual void SetUp() { IREE_CHECK_OK(iree_vm_instance_create(iree_allocator_system(), &instance_)); // TODO(benvanik): move to instance-based registration. IREE_CHECK_OK(iree_hal_module_register_types()); // TODO(benvanik): make a 'don't care' helper method. iree_hal_driver_t* hal_driver = nullptr; IREE_CHECK_OK(iree_hal_driver_registry_try_create_by_name( iree_hal_driver_registry_default(), iree_make_cstring_view("vmla"), iree_allocator_system(), &hal_driver)); iree_hal_device_t* hal_device = nullptr; IREE_CHECK_OK(iree_hal_driver_create_default_device( hal_driver, iree_allocator_system(), &hal_device)); IREE_CHECK_OK(iree_hal_module_create(hal_device, iree_allocator_system(), &hal_module_)); hal_allocator_ = iree_hal_device_allocator(hal_device); iree_hal_device_release(hal_device); iree_hal_driver_release(hal_driver); IREE_CHECK_OK(iree_custom_native_module_register_types()); IREE_CHECK_OK(iree_custom_native_module_create(iree_allocator_system(), &native_module_)) << "Native module failed to init"; const auto* module_file_toc = iree::samples::custom_modules::custom_modules_test_module_create(); IREE_CHECK_OK(iree_vm_bytecode_module_create( iree_const_byte_span_t{ reinterpret_cast<const uint8_t*>(module_file_toc->data), module_file_toc->size}, iree_allocator_null(), iree_allocator_system(), &bytecode_module_)) << "Bytecode module failed to load"; std::vector<iree_vm_module_t*> modules = {hal_module_, native_module_, bytecode_module_}; IREE_CHECK_OK(iree_vm_context_create_with_modules( instance_, modules.data(), modules.size(), iree_allocator_system(), &context_)); } virtual void TearDown() { iree_vm_module_release(hal_module_); iree_vm_module_release(native_module_); iree_vm_module_release(bytecode_module_); iree_vm_context_release(context_); iree_vm_instance_release(instance_); } iree_vm_function_t LookupFunction(absl::string_view function_name) { iree_vm_function_t function; IREE_CHECK_OK(bytecode_module_->lookup_function( bytecode_module_->self, IREE_VM_FUNCTION_LINKAGE_EXPORT, iree_string_view_t{function_name.data(), function_name.size()}, &function)) << "Exported function '" << function_name << "' not found"; return function; } iree_vm_instance_t* instance_ = nullptr; iree_vm_context_t* context_ = nullptr; iree_vm_module_t* bytecode_module_ = nullptr; iree_vm_module_t* native_module_ = nullptr; iree_vm_module_t* hal_module_ = nullptr; iree_hal_allocator_t* hal_allocator_ = nullptr; }; TEST_F(CustomModulesTest, ReverseAndPrint) { // Allocate one of our custom message types to pass in. iree_custom_message_t* input_message = nullptr; IREE_ASSERT_OK( iree_custom_message_wrap(iree_make_cstring_view("hello world!"), iree_allocator_system(), &input_message)); iree_vm_value_t count = iree_vm_value_make_i32(5); // Pass in the message and number of times to print it. // TODO(benvanik): make a macro/magic. iree::vm::ref<iree_vm_list_t> inputs; IREE_ASSERT_OK(iree_vm_list_create(/*element_type=*/nullptr, 2, iree_allocator_system(), &inputs)); iree_vm_ref_t input_message_ref = iree_custom_message_move_ref(input_message); IREE_ASSERT_OK(iree_vm_list_push_ref_move(inputs.get(), &input_message_ref)); IREE_ASSERT_OK(iree_vm_list_push_value(inputs.get(), &count)); // Prepare outputs list to accept the results from the invocation. iree::vm::ref<iree_vm_list_t> outputs; IREE_ASSERT_OK(iree_vm_list_create(/*element_type=*/nullptr, 1, iree_allocator_system(), &outputs)); // Synchronously invoke the function. IREE_ASSERT_OK(iree_vm_invoke(context_, LookupFunction("reverseAndPrint"), /*policy=*/nullptr, inputs.get(), outputs.get(), iree_allocator_system())); // Read back the message that we reversed inside of the module. iree_custom_message_t* reversed_message = (iree_custom_message_t*)iree_vm_list_get_ref_deref( outputs.get(), 0, iree_custom_message_get_descriptor()); ASSERT_NE(nullptr, reversed_message); char result_buffer[256]; IREE_ASSERT_OK(iree_custom_message_read_value(reversed_message, result_buffer, IREE_ARRAYSIZE(result_buffer))); EXPECT_STREQ("!dlrow olleh", result_buffer); } TEST_F(CustomModulesTest, PrintTensor) { // Allocate the buffer we'll be printing. static float kBufferContents[2 * 4] = {0.0f, 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f}; iree_hal_buffer_t* buffer = nullptr; IREE_ASSERT_OK(iree_hal_allocator_wrap_buffer( hal_allocator_, IREE_HAL_MEMORY_TYPE_HOST_LOCAL, IREE_HAL_MEMORY_ACCESS_ALL, IREE_HAL_BUFFER_USAGE_ALL, iree_byte_span_t{reinterpret_cast<uint8_t*>(kBufferContents), sizeof(kBufferContents)}, iree_allocator_null(), &buffer)); // Pass in the tensor as an expanded HAL buffer. iree::vm::ref<iree_vm_list_t> inputs; IREE_ASSERT_OK(iree_vm_list_create(/*element_type=*/nullptr, 1, iree_allocator_system(), &inputs)); iree_vm_ref_t input_buffer_ref = iree_hal_buffer_move_ref(buffer); IREE_ASSERT_OK(iree_vm_list_push_ref_move(inputs.get(), &input_buffer_ref)); // Prepare outputs list to accept the results from the invocation. iree::vm::ref<iree_vm_list_t> outputs; IREE_ASSERT_OK(iree_vm_list_create(/*element_type=*/nullptr, 1, iree_allocator_system(), &outputs)); // Synchronously invoke the function. IREE_ASSERT_OK(iree_vm_invoke(context_, LookupFunction("printTensor"), /*policy=*/nullptr, inputs.get(), outputs.get(), iree_allocator_system())); // Read back the message that we printed inside of the module. iree_custom_message_t* printed_message = (iree_custom_message_t*)iree_vm_list_get_ref_deref( outputs.get(), 0, iree_custom_message_get_descriptor()); ASSERT_NE(nullptr, printed_message); char result_buffer[256]; IREE_ASSERT_OK(iree_custom_message_read_value(printed_message, result_buffer, IREE_ARRAYSIZE(result_buffer))); EXPECT_STREQ("2x4xf32=[0 1 2 3][4 5 6 7]", result_buffer); } TEST_F(CustomModulesTest, RoundTripTensor) { // Allocate the buffer we'll be printing/parsing. static float kBufferContents[2 * 4] = {0.0f, 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f}; iree_hal_buffer_t* buffer = nullptr; IREE_ASSERT_OK(iree_hal_allocator_wrap_buffer( hal_allocator_, IREE_HAL_MEMORY_TYPE_HOST_LOCAL, IREE_HAL_MEMORY_ACCESS_ALL, IREE_HAL_BUFFER_USAGE_ALL, iree_byte_span_t{reinterpret_cast<uint8_t*>(kBufferContents), sizeof(kBufferContents)}, iree_allocator_null(), &buffer)); // Pass in the tensor as an expanded HAL buffer. iree::vm::ref<iree_vm_list_t> inputs; IREE_ASSERT_OK(iree_vm_list_create(/*element_type=*/nullptr, 1, iree_allocator_system(), &inputs)); iree_vm_ref_t input_buffer_ref = iree_hal_buffer_move_ref(buffer); IREE_ASSERT_OK(iree_vm_list_push_ref_move(inputs.get(), &input_buffer_ref)); // Prepare outputs list to accept the results from the invocation. iree::vm::ref<iree_vm_list_t> outputs; IREE_ASSERT_OK(iree_vm_list_create(/*element_type=*/nullptr, 1, iree_allocator_system(), &outputs)); // Synchronously invoke the function. IREE_ASSERT_OK(iree_vm_invoke(context_, LookupFunction("roundTripTensor"), /*policy=*/nullptr, inputs.get(), outputs.get(), iree_allocator_system())); // Read back the message that's been moved around. iree_custom_message_t* printed_message = (iree_custom_message_t*)iree_vm_list_get_ref_deref( outputs.get(), 0, iree_custom_message_get_descriptor()); ASSERT_NE(nullptr, printed_message); char result_buffer[256]; IREE_ASSERT_OK(iree_custom_message_read_value(printed_message, result_buffer, IREE_ARRAYSIZE(result_buffer))); EXPECT_STREQ("2x4xf32=[0 1 2 3][4 5 6 7]", result_buffer); } } // namespace
44.920354
80
0.698779
xinan-jiang
d502067252666be125c2934892e508c1853fa56a
9,973
cpp
C++
cegui/src/RendererModules/OpenGLES/GeometryBuffer.cpp
aimoonchen/cegui
4720dd8e5f57bb213a9b462c9dfc87c591381fc3
[ "MIT" ]
null
null
null
cegui/src/RendererModules/OpenGLES/GeometryBuffer.cpp
aimoonchen/cegui
4720dd8e5f57bb213a9b462c9dfc87c591381fc3
[ "MIT" ]
null
null
null
cegui/src/RendererModules/OpenGLES/GeometryBuffer.cpp
aimoonchen/cegui
4720dd8e5f57bb213a9b462c9dfc87c591381fc3
[ "MIT" ]
null
null
null
/*********************************************************************** created: Thu Jan 8 2009 author: Paul D Turner *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team * * 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 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 "CEGUI/RendererModules/OpenGLES/GeometryBuffer.h" #include "CEGUI/RenderEffect.h" #include "CEGUI/RendererModules/OpenGLES/Texture.h" #include "CEGUI/Vertex.h" // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// OpenGLESGeometryBuffer::OpenGLESGeometryBuffer() : d_activeTexture(0), d_clippingActive(true), d_translation(0, 0, 0), d_rotation(0, 0, 0), d_pivot(0, 0, 0), d_effect(0), d_matrixValid(false) { //d_matrix does not need to be initialised here, we have d_matrixValid //for(unsigned int i = 0; i < 16;++i) // d_matrix[i]=0.0; } //----------------------------------------------------------------------------// void OpenGLESGeometryBuffer::appendVertex(const Vertex& vertex) { appendGeometry(&vertex, 1); } //----------------------------------------------------------------------------// void OpenGLESGeometryBuffer::draw(std::uint32_t drawModeMask) const { CEGUI_UNUSED(drawModeMask); // setup clip region GLint vp[4]; glGetIntegerv(GL_VIEWPORT, vp); glScissor(static_cast<GLint>(d_preparedClippingRegion.left()), static_cast<GLint>(vp[3] - d_preparedClippingRegion.bottom()), static_cast<GLint>(d_preparedClippingRegion.getWidth()), static_cast<GLint>(d_preparedClippingRegion.getHeight())); // apply the transformations we need to use. if (!d_matrixValid) updateMatrix(); glMatrixMode(GL_MODELVIEW); glLoadMatrixf(d_matrix); const int pass_count = d_effect ? d_effect->getPassCount() : 1; for (int pass = 0; pass < pass_count; ++pass) { // set up RenderEffect if (d_effect) d_effect->performPreRenderFunctions(pass); // draw the batches size_t pos = 0; BatchList::const_iterator i = d_batches.begin(); for ( ; i != d_batches.end(); ++i) { glBindTexture(GL_TEXTURE_2D, (*i).first); // set up pointers to the vertex element arrays glTexCoordPointer(2, GL_FLOAT, sizeof(GLVertex), &d_vertices[pos]); glColorPointer(4, GL_FLOAT, sizeof(GLVertex), &d_vertices[pos].colour[0]); glVertexPointer(3, GL_FLOAT, sizeof(GLVertex), &d_vertices[pos].position[0]); // draw the geometry glDrawArrays(GL_TRIANGLES, 0, (*i).second); pos += (*i).second; } } // clean up RenderEffect if (d_effect) d_effect->performPostRenderFunctions(); } //----------------------------------------------------------------------------// void OpenGLESGeometryBuffer::setTranslation(const glm::vec3& v) { d_translation = v; d_matrixValid = false; } //----------------------------------------------------------------------------// void OpenGLESGeometryBuffer::setRotation(const glm::quat& r) { d_rotation = r; d_matrixValid = false; } //----------------------------------------------------------------------------// void OpenGLESGeometryBuffer::setPivot(const glm::vec3& p) { d_pivot = p; d_matrixValid = false; } //----------------------------------------------------------------------------// void OpenGLESGeometryBuffer::appendGeometry(const Vertex* const vbuff, unsigned int vertex_count) { performBatchManagement(); // update size of current batch d_batches.back().second += vertex_count; // buffer these vertices GLVertex vd; const Vertex* vs = vbuff; for ((unsigned int i = 0; i < vertex_count; ++i, ++vs) { // copy vertex info the buffer, converting from CEGUI::Vertex to // something directly usable by OpenGLES as needed. vd.tex[0] = vs->tex_coords.d_x; vd.tex[1] = vs->tex_coords.d_y; vd.colour[0] = vs->colour_val.getRed(); vd.colour[1] = vs->colour_val.getGreen(); vd.colour[2] = vs->colour_val.getBlue(); vd.colour[3] = vs->colour_val.getAlpha(); vd.position[0] = vs->position.d_x; vd.position[1] = vs->position.d_y; vd.position[2] = vs->position.d_z; d_vertices.push_back(vd); } } //----------------------------------------------------------------------------// void OpenGLESGeometryBuffer::setActiveTexture(Texture* texture) { d_activeTexture = static_cast<OpenGLESTexture*>(texture); } //----------------------------------------------------------------------------// void OpenGLESGeometryBuffer::reset() { d_batches.clear(); d_vertices.clear(); d_activeTexture = 0; } //----------------------------------------------------------------------------// Texture* OpenGLESGeometryBuffer::getActiveTexture() const { return d_activeTexture; } //----------------------------------------------------------------------------// (unsigned int OpenGLESGeometryBuffer::getVertexCount() const { return d_vertices.size(); } //----------------------------------------------------------------------------// (unsigned int OpenGLESGeometryBuffer::getBatchCount() const { return d_batches.size(); } //----------------------------------------------------------------------------// void OpenGLESGeometryBuffer::performBatchManagement() { const GL(unsigned int gltex = d_activeTexture ? d_activeTexture->getOpenGLESTexture() : 0; // create a new batch if there are no batches yet, or if the active texture // differs from that used by the current batch. if (d_batches.empty() || (gltex != d_batches.back().first)) d_batches.push_back(BatchInfo(gltex, 0)); } //----------------------------------------------------------------------------// void OpenGLESGeometryBuffer::setRenderEffect(RenderEffect* effect) { d_effect = effect; } //----------------------------------------------------------------------------// RenderEffect* OpenGLESGeometryBuffer::getRenderEffect() { return d_effect; } //----------------------------------------------------------------------------// const float* OpenGLESGeometryBuffer::getMatrix() const { if (!d_matrixValid) updateMatrix(); return d_matrix; } //----------------------------------------------------------------------------// void OpenGLESGeometryBuffer::updateMatrix() const { glMatrixMode(GL_MODELVIEW); glPushMatrix(); const Vector3f final_trans = d_translation + d_pivot; glLoadIdentity(); glTranslatef(final_trans.x, final_trans.y, final_trans.z); float rotation_matrix[16]; rotation_matrix[ 0] = 1.0f - 2.0f * (d_rotation.d_y * d_rotation.d_y + d_rotation.d_z * d_rotation.d_z); rotation_matrix[ 1] = 2.0f * (d_rotation.d_x * d_rotation.d_y + d_rotation.d_z * d_rotation.d_w); rotation_matrix[ 2] = 2.0f * (d_rotation.d_x * d_rotation.d_z - d_rotation.d_y * d_rotation.d_w); rotation_matrix[ 3] = 0.0f; rotation_matrix[ 4] = 2.0f * (d_rotation.d_x * d_rotation.d_y - d_rotation.d_z * d_rotation.d_w); rotation_matrix[ 5] = 1.0f - 2.0f * (d_rotation.d_x * d_rotation.d_x + d_rotation.d_z * d_rotation.d_z); rotation_matrix[ 6] = 2.0f * (d_rotation.d_z * d_rotation.d_y + d_rotation.d_x * d_rotation.d_w); rotation_matrix[ 7] = 0.0f; rotation_matrix[ 8] = 2.0f * (d_rotation.d_x * d_rotation.d_z + d_rotation.d_y * d_rotation.d_w); rotation_matrix[ 9] = 2.0f * (d_rotation.d_y * d_rotation.d_z - d_rotation.d_x * d_rotation.d_w); rotation_matrix[10] = 1.0f - 2.0f * (d_rotation.d_x * d_rotation.d_x + d_rotation.d_y * d_rotation.d_y); rotation_matrix[11] = 0.0f; rotation_matrix[12] = 0.0f; rotation_matrix[13] = 0.0f; rotation_matrix[14] = 0.0f; rotation_matrix[15] = 1.0f; glMultMatrixf(rotation_matrix); glTranslatef(-d_pivot.x, -d_pivot.y, -d_pivot.z); glGetFloatv(GL_MODELVIEW_MATRIX, d_matrix); glPopMatrix(); d_matrixValid = true; } //----------------------------------------------------------------------------// void OpenGLESGeometryBuffer::setClippingActive(const bool active) { d_clippingActive = active; } //----------------------------------------------------------------------------// bool OpenGLESGeometryBuffer::isClippingActive() const { return d_clippingActive; } //----------------------------------------------------------------------------// } // End of CEGUI namespace section
35.874101
108
0.542866
aimoonchen
d502f83dd726f767bbe138ee4c42a6ad0279039b
6,279
hpp
C++
boost/math/special_functions/detail/airy_ai_bi_zero.hpp
ballisticwhisper/boost
f72119ab640b564c4b983bd457457046b52af9ee
[ "BSL-1.0" ]
159
2017-03-24T21:07:06.000Z
2022-03-20T13:44:40.000Z
boost/math/special_functions/detail/airy_ai_bi_zero.hpp
ballisticwhisper/boost
f72119ab640b564c4b983bd457457046b52af9ee
[ "BSL-1.0" ]
1,667
2017-03-27T14:41:22.000Z
2022-03-31T19:50:06.000Z
boost/math/special_functions/detail/airy_ai_bi_zero.hpp
ballisticwhisper/boost
f72119ab640b564c4b983bd457457046b52af9ee
[ "BSL-1.0" ]
95
2017-03-24T21:05:03.000Z
2022-03-08T17:30:22.000Z
// Copyright (c) 2013 Christopher Kormanyos // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // This work is based on an earlier work: // "Algorithm 910: A Portable C++ Multiple-Precision System for Special-Function Calculations", // in ACM TOMS, {VOL 37, ISSUE 4, (February 2011)} (C) ACM, 2011. http://doi.acm.org/10.1145/1916461.1916469 // // This header contains implementation details for estimating the zeros // of the Airy functions airy_ai and airy_bi on the negative real axis. // #ifndef _AIRY_AI_BI_ZERO_2013_01_20_HPP_ #define _AIRY_AI_BI_ZERO_2013_01_20_HPP_ #include <boost/math/constants/constants.hpp> #include <boost/math/special_functions/cbrt.hpp> namespace boost { namespace math { namespace detail { // Forward declarations of the needed Airy function implementations. template <class T, class Policy> T airy_ai_imp(T x, const Policy& pol); template <class T, class Policy> T airy_bi_imp(T x, const Policy& pol); template <class T, class Policy> T airy_ai_prime_imp(T x, const Policy& pol); template <class T, class Policy> T airy_bi_prime_imp(T x, const Policy& pol); namespace airy_zero { template<class T> T equation_as_10_4_105(const T& z) { const T one_over_z (T(1) / z); const T one_over_z_squared(one_over_z * one_over_z); const T z_pow_third (boost::math::cbrt(z)); const T z_pow_two_thirds(z_pow_third * z_pow_third); // Implement the top line of Eq. 10.4.105. const T fz(z_pow_two_thirds * ((((( + (T(162375596875.0) / 334430208UL) * one_over_z_squared - ( T(108056875.0) / 6967296UL)) * one_over_z_squared + ( T(77125UL) / 82944UL)) * one_over_z_squared - ( T(5U) / 36U)) * one_over_z_squared + ( T(5U) / 48U)) * one_over_z_squared + (1))); return fz; } namespace airy_ai_zero_detail { template<class T> T initial_guess(const unsigned m) { T guess; switch(m) { case 0U: { guess = T(0); break; } case 1U: { guess = T(-2.33810741045976703849); break; } case 2U: { guess = T(-4.08794944413097061664); break; } case 3U: { guess = T(-5.52055982809555105913); break; } case 4U: { guess = T(-6.78670809007175899878); break; } case 5U: { guess = T(-7.94413358712085312314); break; } case 6U: { guess = T(-9.02265085334098038016); break; } case 7U: { guess = T(-10.0401743415580859306); break; } case 8U: { guess = T(-11.0085243037332628932); break; } case 9U: { guess = T(-11.9360155632362625170); break; } case 10U:{ guess = T(-12.8287767528657572004); break; } default: { const T t(((boost::math::constants::pi<T>() * 3U) * ((T(m) * 4U) - 1)) / 8U); guess = -boost::math::detail::airy_zero::equation_as_10_4_105(t); break; } } return guess; } template<class T, class Policy> class function_object_ai_and_ai_prime { public: function_object_ai_and_ai_prime(const Policy pol) : my_pol(pol) { } boost::math::tuple<T, T> operator()(const T& x) const { // Return a tuple containing both Ai(x) and Ai'(x). return boost::math::make_tuple( boost::math::detail::airy_ai_imp (x, my_pol), boost::math::detail::airy_ai_prime_imp(x, my_pol)); } private: const Policy& my_pol; const function_object_ai_and_ai_prime& operator=(const function_object_ai_and_ai_prime&); }; } // namespace airy_ai_zero_detail namespace airy_bi_zero_detail { template<class T> T initial_guess(const unsigned m) { T guess; switch(m) { case 0U: { guess = T(0); break; } case 1U: { guess = T(-1.17371322270912792492); break; } case 2U: { guess = T(-3.27109330283635271568); break; } case 3U: { guess = T(-4.83073784166201593267); break; } case 4U: { guess = T(-6.16985212831025125983); break; } case 5U: { guess = T(-7.37676207936776371360); break; } case 6U: { guess = T(-8.49194884650938801345); break; } case 7U: { guess = T(-9.53819437934623888663); break; } case 8U: { guess = T(-10.5299135067053579244); break; } case 9U: { guess = T(-11.4769535512787794379); break; } case 10U:{ guess = T(-12.3864171385827387456); break; } default: { const T t(((boost::math::constants::pi<T>() * 3U) * ((T(m) * 4U) - 3)) / 8U); guess = -boost::math::detail::airy_zero::equation_as_10_4_105(t); break; } } return guess; } template<class T, class Policy> class function_object_bi_and_bi_prime { public: function_object_bi_and_bi_prime(const Policy pol) : my_pol(pol) { } boost::math::tuple<T, T> operator()(const T& x) const { // Return a tuple containing both Bi(x) and Bi'(x). return boost::math::make_tuple( boost::math::detail::airy_bi_imp (x, my_pol), boost::math::detail::airy_bi_prime_imp(x, my_pol)); } private: const Policy& my_pol; const function_object_bi_and_bi_prime& operator=(const function_object_bi_and_bi_prime&); }; } // namespace airy_bi_zero_detail } // namespace airy_zero } // namespace detail } // namespace math } // namespaces boost #endif // _AIRY_AI_BI_ZERO_2013_01_20_HPP_
39
108
0.556458
ballisticwhisper
d505e0a834f859bebd392f3e36edd7e77c883353
4,319
cpp
C++
torch/csrc/deploy/test_deploy.cpp
Gamrix/pytorch
b5b158a6c6de94dfb983b447fa33fea062358844
[ "Intel" ]
null
null
null
torch/csrc/deploy/test_deploy.cpp
Gamrix/pytorch
b5b158a6c6de94dfb983b447fa33fea062358844
[ "Intel" ]
null
null
null
torch/csrc/deploy/test_deploy.cpp
Gamrix/pytorch
b5b158a6c6de94dfb983b447fa33fea062358844
[ "Intel" ]
null
null
null
#include <gtest/gtest.h> #include <torch/csrc/deploy/deploy.h> #include <torch/script.h> #include <torch/torch.h> #include <future> #include <iostream> #include <string> int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); int rc = RUN_ALL_TESTS(); return rc; } void compare_torchpy_jit(const char* model_filename, const char* jit_filename) { // Test torch::deploy::InterpreterManager m(1); torch::deploy::Package p = m.load_package(model_filename); auto model = p.load_pickle("model", "model.pkl"); at::IValue eg; { auto I = p.acquire_session(); eg = I.self.attr("load_pickle")({"model", "example.pkl"}).toIValue(); } at::Tensor output = model(eg.toTuple()->elements()).toTensor(); // Reference auto ref_model = torch::jit::load(jit_filename); at::Tensor ref_output = ref_model.forward(eg.toTuple()->elements()).toTensor(); ASSERT_TRUE(ref_output.allclose(output, 1e-03, 1e-05)); } const char* simple = "torch/csrc/deploy/example/generated/simple"; const char* simple_jit = "torch/csrc/deploy/example/generated/simple_jit"; const char* path(const char* envname, const char* path) { const char* e = getenv(envname); return e ? e : path; } TEST(TorchpyTest, SimpleModel) { compare_torchpy_jit(path("SIMPLE", simple), path("SIMPLE_JIT", simple_jit)); } TEST(TorchpyTest, ResNet) { compare_torchpy_jit( path("RESNET", "torch/csrc/deploy/example/generated/resnet"), path("RESNET_JIT", "torch/csrc/deploy/example/generated/resnet_jit")); } TEST(TorchpyTest, Movable) { torch::deploy::InterpreterManager m(1); torch::deploy::ReplicatedObj obj; { auto I = m.acquire_one(); auto model = I.global("torch.nn", "Module")(std::vector<torch::deploy::Obj>()); obj = I.create_movable(model); } obj.acquire_session(); } TEST(TorchpyTest, MultiSerialSimpleModel) { torch::deploy::InterpreterManager manager(3); torch::deploy::Package p = manager.load_package(path("SIMPLE", simple)); auto model = p.load_pickle("model", "model.pkl"); auto ref_model = torch::jit::load(path("SIMPLE_JIT", simple_jit)); // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) auto input = torch::ones({10, 20}); size_t ninterp = 3; std::vector<at::Tensor> outputs; for (size_t i = 0; i < ninterp; i++) { outputs.push_back(model({input}).toTensor()); } // Generate reference auto ref_output = ref_model.forward({input}).toTensor(); // Compare all to reference for (size_t i = 0; i < ninterp; i++) { ASSERT_TRUE(ref_output.equal(outputs[i])); } // test kwargs api with args std::vector<c10::IValue> args; args.emplace_back(input); std::unordered_map<std::string, c10::IValue> kwargs_empty; auto jit_output_args = model.call_kwargs(args, kwargs_empty).toTensor(); ASSERT_TRUE(ref_output.equal(jit_output_args)); // and with kwargs only std::unordered_map<std::string, c10::IValue> kwargs; kwargs["input"] = input; auto jit_output_kwargs = model.call_kwargs(kwargs).toTensor(); ASSERT_TRUE(ref_output.equal(jit_output_kwargs)); } TEST(TorchpyTest, ThreadedSimpleModel) { size_t nthreads = 3; torch::deploy::InterpreterManager manager(nthreads); torch::deploy::Package p = manager.load_package(path("SIMPLE", simple)); auto model = p.load_pickle("model", "model.pkl"); auto ref_model = torch::jit::load(path("SIMPLE_JIT", simple_jit)); // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) auto input = torch::ones({10, 20}); std::vector<at::Tensor> outputs; std::vector<std::future<at::Tensor>> futures; for (size_t i = 0; i < nthreads; i++) { futures.push_back(std::async(std::launch::async, [&model]() { // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) auto input = torch::ones({10, 20}); // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) for (int i = 0; i < 100; ++i) { model({input}).toTensor(); } auto result = model({input}).toTensor(); return result; })); } for (size_t i = 0; i < nthreads; i++) { outputs.push_back(futures[i].get()); } // Generate reference auto ref_output = ref_model.forward({input}).toTensor(); // Compare all to reference for (size_t i = 0; i < nthreads; i++) { ASSERT_TRUE(ref_output.equal(outputs[i])); } }
30.631206
80
0.680019
Gamrix
d5070520a70b4f500001615a8aaad3a696ae8046
77,613
cpp
C++
RSDKv4/Debug.cpp
0xR00KIE/Decomp-for-S1F
c8ffedd211f25bb46803f9d637baf1b1fc635db0
[ "Unlicense" ]
2
2022-01-15T05:05:39.000Z
2022-03-19T07:36:31.000Z
RSDKv4/Debug.cpp
LittlePlanetCD/Decomp-for-S1F
c8ffedd211f25bb46803f9d637baf1b1fc635db0
[ "Unlicense" ]
null
null
null
RSDKv4/Debug.cpp
LittlePlanetCD/Decomp-for-S1F
c8ffedd211f25bb46803f9d637baf1b1fc635db0
[ "Unlicense" ]
null
null
null
#include "RetroEngine.hpp" bool endLine = true; int touchTimer = 0; int drawtemp = 0; int taListStore = 0; int modbgscroll = 0; int modbgtick = 0; void initDevMenu() { // DrawStageGFXHQ = 0; xScrollOffset = 0; yScrollOffset = 0; StopMusic(); StopAllSfx(); ReleaseStageSfx(); fadeMode = 0; playerListPos = 0; Engine.gameMode = ENGINE_DEVMENU; ClearGraphicsData(); ClearAnimationData(); SetActivePalette(0, 0, 256); textMenuSurfaceNo = SURFACE_MAX - 1; LoadGIFFile("Data/Game/SystemText.gif", SURFACE_MAX - 1); SetPaletteEntry(-1, 0xF0, 0x00, 0x00, 0x00); SetPaletteEntry(-1, 0xFF, 0xFF, 0xFF, 0xFF); setTextMenu(DEVMENU_MAIN); drawStageGFXHQ = false; touchTimer = 0; #if !RETRO_USE_ORIGINAL_CODE RemoveNativeObjectType(PauseMenu_Create, PauseMenu_Main); #endif #if RETRO_HARDWARE_RENDER render3DEnabled = false; UpdateHardwareTextures(); #endif } void initErrorMessage() { xScrollOffset = 0; yScrollOffset = 0; StopMusic(); StopAllSfx(); ReleaseStageSfx(); fadeMode = 0; playerListPos = 0; Engine.gameMode = ENGINE_DEVMENU; ClearGraphicsData(); ClearAnimationData(); SetActivePalette(0, 0, 256); textMenuSurfaceNo = SURFACE_MAX - 1; LoadGIFFile("Data/Game/SystemText.gif", SURFACE_MAX - 1); SetPaletteEntry(-1, 0xF0, 0x00, 0x00, 0x00); SetPaletteEntry(-1, 0xFF, 0xFF, 0xFF, 0xFF); gameMenu[0].alignment = 2; gameMenu[0].selectionCount = 1; gameMenu[0].selection1 = 0; gameMenu[1].visibleRowCount = 0; gameMenu[1].visibleRowOffset = 0; stageMode = DEVMENU_SCRIPTERROR; drawStageGFXHQ = false; touchTimer = 0; #if !RETRO_USE_ORIGINAL_CODE RemoveNativeObjectType(PauseMenu_Create, PauseMenu_Main); #endif #if RETRO_HARDWARE_RENDER render3DEnabled = false; UpdateHardwareTextures(); #endif } void processStageSelect() { ClearScreen(0xF0); CheckKeyDown(&keyDown); CheckKeyPress(&keyPress); #if defined RETRO_USING_MOUSE || defined RETRO_USING_TOUCH DrawSprite(32, 0x42, 16, 16, 78, 240, textMenuSurfaceNo); DrawSprite(32, 0xB2, 16, 16, 95, 240, textMenuSurfaceNo); DrawSprite(SCREEN_XSIZE - 32, SCREEN_YSIZE - 32, 16, 16, 112, 240, textMenuSurfaceNo); #endif if (!keyDown.start && !keyDown.up && !keyDown.down) { if (touches > 0) { if (touchDown[0] && !(touchTimer % 8)) { if (touchX[0] < SCREEN_CENTERX) { if (touchY[0] >= SCREEN_CENTERY) { if (!keyDown.down) keyPress.down = true; keyDown.down = true; } else { if (!keyDown.up) keyPress.up = true; keyDown.up = true; } } else if (touchX[0] > SCREEN_CENTERX) { if (touchY[0] > SCREEN_CENTERY) { if (!keyDown.start) keyPress.start = true; keyDown.start = true; } else { if (!keyDown.B) keyPress.B = true; keyDown.B = true; } } } } } touchTimer++; switch (stageMode) { case DEVMENU_MAIN: // Main Menu { if (keyPress.down) gameMenu[0].selection2 += 2; if (keyPress.up) gameMenu[0].selection2 -= 2; int count = 15; #if RETRO_USE_MOD_LOADER count += 2; #endif if (gameMenu[0].selection2 > count) gameMenu[0].selection2 = 9; if (gameMenu[0].selection2 < 9) gameMenu[0].selection2 = count; DrawTextMenu(&gameMenu[0], SCREEN_CENTERX, 72); if (keyPress.start || keyPress.A) { if (gameMenu[0].selection2 == 9) { ClearGraphicsData(); ClearAnimationData(); activeStageList = 0; stageMode = STAGEMODE_LOAD; Engine.gameMode = ENGINE_MAINGAME; stageListPosition = 0; } else if (gameMenu[0].selection2 == 11) { SetupTextMenu(&gameMenu[0], 0); AddTextMenuEntry(&gameMenu[0], "SELECT A PLAYER"); SetupTextMenu(&gameMenu[1], 0); LoadConfigListText(&gameMenu[1], 0); gameMenu[1].alignment = 0; gameMenu[1].selectionCount = 1; gameMenu[1].selection1 = 0; stageMode = DEVMENU_PLAYERSEL; } else if (gameMenu[0].selection2 == 13) { initStartMenu(0); } #if RETRO_USE_MOD_LOADER else if (gameMenu[0].selection2 == 15) { SetupTextMenu(&gameMenu[0], 0); AddTextMenuEntry(&gameMenu[0], "MOD LIST"); SetupTextMenu(&gameMenu[1], 0); initMods(); // reload mods char buffer[0x100]; for (int m = 0; m < modCount; ++m) { StrCopy(buffer, modList[m].name.c_str()); StrAdd(buffer, ": "); StrAdd(buffer, modList[m].active ? " Active" : "Inactive"); AddTextMenuEntry(&gameMenu[1], buffer); } gameMenu[1].alignment = 1; gameMenu[1].selectionCount = 3; gameMenu[1].selection1 = 0; if (gameMenu[1].rowCount > 18) gameMenu[1].visibleRowCount = 18; else gameMenu[1].visibleRowCount = 0; gameMenu[0].alignment = 2; gameMenu[0].selectionCount = 1; gameMenu[1].timer = 0; gameMenu[1].visibleRowOffset = 0; stageMode = DEVMENU_MODMENU; } #endif else { Engine.running = false; } } else if (keyPress.B) { ClearGraphicsData(); ClearAnimationData(); activeStageList = 0; stageMode = STAGEMODE_LOAD; Engine.gameMode = ENGINE_MAINGAME; stageListPosition = 0; } break; } case DEVMENU_PLAYERSEL: // Selecting Player { if (keyPress.down) ++gameMenu[1].selection1; if (keyPress.up) --gameMenu[1].selection1; if (gameMenu[1].selection1 == gameMenu[1].rowCount) gameMenu[1].selection1 = 0; if (gameMenu[1].selection1 < 0) gameMenu[1].selection1 = gameMenu[1].rowCount - 1; DrawTextMenu(&gameMenu[0], SCREEN_CENTERX - 4, 72); DrawTextMenu(&gameMenu[1], SCREEN_CENTERX - 40, 96); if (keyPress.start || keyPress.A) { playerListPos = gameMenu[1].selection1; setTextMenu(DEVMENU_STAGELISTSEL); } else if (keyPress.B) { setTextMenu(DEVMENU_MAIN); } break; } case DEVMENU_STAGELISTSEL: // Selecting Category { if (keyPress.down) gameMenu[0].selection2 += 2; if (keyPress.up) gameMenu[0].selection2 -= 2; if (gameMenu[0].selection2 > 9) gameMenu[0].selection2 = 3; if (gameMenu[0].selection2 < 3) gameMenu[0].selection2 = 9; DrawTextMenu(&gameMenu[0], SCREEN_CENTERX - 80, 72); bool nextMenu = false; switch (gameMenu[0].selection2) { case 3: // Presentation if (stageListCount[0] > 0) nextMenu = true; activeStageList = 0; break; case 5: // Regular if (stageListCount[1] > 0) nextMenu = true; activeStageList = 1; break; case 7: // Special if (stageListCount[3] > 0) nextMenu = true; activeStageList = 3; break; case 9: // Bonus if (stageListCount[2] > 0) nextMenu = true; activeStageList = 2; break; default: break; } if ((keyPress.start || keyPress.A) && nextMenu) { SetupTextMenu(&gameMenu[0], 0); AddTextMenuEntry(&gameMenu[0], "SELECT A STAGE"); SetupTextMenu(&gameMenu[1], 0); LoadConfigListText(&gameMenu[1], ((gameMenu[0].selection2 - 3) >> 1) + 1); gameMenu[1].alignment = 1; gameMenu[1].selectionCount = 3; gameMenu[1].selection1 = 0; if (gameMenu[1].rowCount > 18) gameMenu[1].visibleRowCount = 18; else gameMenu[1].visibleRowCount = 0; gameMenu[0].alignment = 2; gameMenu[0].selectionCount = 1; gameMenu[1].timer = 0; stageMode = DEVMENU_STAGESEL; } else if (keyPress.B) { SetupTextMenu(&gameMenu[0], 0); AddTextMenuEntry(&gameMenu[0], "SELECT A PLAYER"); SetupTextMenu(&gameMenu[1], 0); LoadConfigListText(&gameMenu[1], 0); gameMenu[0].alignment = 2; gameMenu[1].alignment = 0; gameMenu[1].selectionCount = 1; gameMenu[1].visibleRowCount = 0; gameMenu[1].visibleRowOffset = 0; gameMenu[1].selection1 = playerListPos; stageMode = DEVMENU_PLAYERSEL; } break; } case DEVMENU_STAGESEL: // Selecting Stage { if (keyDown.down) { gameMenu[1].timer += 1; if (gameMenu[1].timer > 8) { gameMenu[1].timer = 0; keyPress.down = true; } } else { if (keyDown.up) { gameMenu[1].timer -= 1; if (gameMenu[1].timer < -8) { gameMenu[1].timer = 0; keyPress.up = true; } } else { gameMenu[1].timer = 0; } } if (keyPress.down) { gameMenu[1].selection1++; if (gameMenu[1].selection1 - gameMenu[1].visibleRowOffset >= gameMenu[1].visibleRowCount) { gameMenu[1].visibleRowOffset += 1; } } if (keyPress.up) { gameMenu[1].selection1--; if (gameMenu[1].selection1 - gameMenu[1].visibleRowOffset < 0) { gameMenu[1].visibleRowOffset -= 1; } } if (gameMenu[1].selection1 == gameMenu[1].rowCount) { gameMenu[1].selection1 = 0; gameMenu[1].visibleRowOffset = 0; } if (gameMenu[1].selection1 < 0) { gameMenu[1].selection1 = gameMenu[1].rowCount - 1; gameMenu[1].visibleRowOffset = gameMenu[1].rowCount - gameMenu[1].visibleRowCount; } DrawTextMenu(&gameMenu[0], SCREEN_CENTERX - 4, 40); DrawTextMenu(&gameMenu[1], SCREEN_CENTERX + 100, 64); if (keyPress.start || keyPress.A) { debugMode = keyDown.A; stageMode = STAGEMODE_LOAD; Engine.gameMode = ENGINE_MAINGAME; stageListPosition = gameMenu[1].selection1; SetGlobalVariableByName("options.gameMode", 0); SetGlobalVariableByName("lampPostID", 0); // For S1 SetGlobalVariableByName("starPostID", 0); // For S2 } else if (keyPress.B) { setTextMenu(DEVMENU_STAGELISTSEL); } break; } case DEVMENU_SCRIPTERROR: // Script Error { DrawTextMenu(&gameMenu[0], SCREEN_CENTERX, 72); if (keyPress.start || keyPress.A) { setTextMenu(DEVMENU_MAIN); } else if (keyPress.B) { ClearGraphicsData(); ClearAnimationData(); activeStageList = 0; stageMode = DEVMENU_STAGESEL; Engine.gameMode = ENGINE_MAINGAME; stageListPosition = 0; } break; } #if RETRO_USE_MOD_LOADER case DEVMENU_MODMENU: // Mod Menu { if (keyDown.down) { gameMenu[1].timer += 1; if (gameMenu[1].timer > 8) { gameMenu[1].timer = 0; keyPress.down = true; } } else { if (keyDown.up) { gameMenu[1].timer -= 1; if (gameMenu[1].timer < -8) { gameMenu[1].timer = 0; keyPress.up = true; } } else { gameMenu[1].timer = 0; } } if (keyPress.down) { gameMenu[1].selection1++; if (gameMenu[1].selection1 - gameMenu[1].visibleRowOffset >= gameMenu[1].visibleRowCount) { gameMenu[1].visibleRowOffset += 1; } } if (keyPress.up) { gameMenu[1].selection1--; if (gameMenu[1].selection1 - gameMenu[1].visibleRowOffset < 0) { gameMenu[1].visibleRowOffset -= 1; } } if (gameMenu[1].selection1 >= gameMenu[1].rowCount) { gameMenu[1].selection1 = 0; gameMenu[1].visibleRowOffset = 0; } if (gameMenu[1].selection1 < 0) { gameMenu[1].selection1 = gameMenu[1].rowCount - 1; gameMenu[1].visibleRowOffset = gameMenu[1].rowCount - gameMenu[1].visibleRowCount; } gameMenu[1].selection2 = gameMenu[1].selection1; //its a bug fix LOL char buffer[0x100]; if (keyPress.A || keyPress.start || keyPress.left || keyPress.right) { modList[gameMenu[1].selection1].active ^= 1; StrCopy(buffer, modList[gameMenu[1].selection1].name.c_str()); StrAdd(buffer, ": "); StrAdd(buffer, (modList[gameMenu[1].selection1].active ? " Active" : "Inactive")); EditTextMenuEntry(&gameMenu[1], buffer, gameMenu[1].selection1); } if (keyPress.B) { // Reload entire engine Engine.LoadGameConfig("Data/Game/GameConfig.bin"); ReleaseStageSfx(); ReleaseGlobalSfx(); LoadGlobalSfx(); forceUseScripts = false; for (int m = 0; m < modCount; ++m) { if (modList[m].useScripts && modList[m].active) forceUseScripts = true; } saveMods(); setTextMenu(DEVMENU_MAIN); } DrawTextMenu(&gameMenu[0], SCREEN_CENTERX - 4, 40); DrawTextMenu(&gameMenu[1], SCREEN_CENTERX + 100, 64); break; } #endif default: break; } } void initStartMenu(int mode) { // DrawStageGFXHQ = 0; xScrollOffset = 0; yScrollOffset = 0; StopMusic(); StopAllSfx(); ReleaseStageSfx(); fadeMode = 0; playerListPos = 0; Engine.gameMode = ENGINE_STARTMENU; ClearGraphicsData(); ClearAnimationData(); SetActivePalette(0, 0, 256); textMenuSurfaceNo = 0; LoadGIFFile("Data/Game/SystemText.gif", 0); SetPaletteEntry(-1, 0xF0, 0x00, 0x00, 0x00); SetPaletteEntry(-1, 0xFF, 0xFF, 0xFF, 0xFF); ReadSaveRAMData(); if (saveRAM[0x100] != Engine.gameType) { saveRAM[0x100] = Engine.gameType; if (Engine.gameType == GAME_SONIC1) { saveRAM[0x101] = 1; saveRAM[0x102] = 0; saveRAM[0x103] = 0; saveRAM[0x104] = 0; saveRAM[0x105] = 0; } else { saveRAM[0x101] = 0; saveRAM[0x102] = 1; saveRAM[0x103] = 1; saveRAM[0x104] = 0; saveRAM[0x105] = 0; } WriteSaveRAMData(); } else { if (Engine.gameType == GAME_SONIC1) { SetGlobalVariableByName("options.spindash", saveRAM[0x101]); SetGlobalVariableByName("options.speedCap", saveRAM[0x102]); SetGlobalVariableByName("options.airSpeedCap", saveRAM[0x103]); SetGlobalVariableByName("options.spikeBehavior", saveRAM[0x104]); SetGlobalVariableByName("options.shieldType", saveRAM[0x105]); SetGlobalVariableByName("options.superStates", saveRAM[0x106]); } else { SetGlobalVariableByName("options.airSpeedCap", saveRAM[0x101]); SetGlobalVariableByName("options.tailsFlight", saveRAM[0x102]); SetGlobalVariableByName("options.superTails", saveRAM[0x103]); SetGlobalVariableByName("options.spikeBehavior", saveRAM[0x104]); SetGlobalVariableByName("options.shieldType", saveRAM[0x105]); } } if (mode == 0 || !GetGlobalVariableByName("timeAttack.result")) { setTextMenu(STARTMENU_MAIN); } else { // finished TA act int listPos = taListStore; int result = GetGlobalVariableByName("timeAttack.result"); if (result < saveRAM[3 * listPos + 0x40]) { saveRAM[3 * listPos + 0x42] = saveRAM[3 * listPos + 0x41]; saveRAM[3 * listPos + 0x41] = saveRAM[3 * listPos + 0x40]; saveRAM[3 * listPos + 0x40] = result; } else if (result < saveRAM[3 * listPos + 0x41]) { saveRAM[3 * listPos + 0x42] = saveRAM[3 * listPos + 0x41]; saveRAM[3 * listPos + 0x41] = result; } else if (result < saveRAM[3 * listPos + 0x42]) { saveRAM[3 * listPos + 0x42] = result; } WriteSaveRAMData(); char strBuffer[0x100]; SetupTextMenu(&gameMenu[0], 0); AddTextMenuEntry(&gameMenu[0], "BEST TIMES"); AddTextMenuEntry(&gameMenu[0], ""); StrCopy(strBuffer, "1ST: "); int mins = saveRAM[3 * (listPos) + 0x40] / 6000; int secs = saveRAM[3 * (listPos) + 0x40] / 100 % 60; int ms = saveRAM[3 * (listPos) + 0x40] % 100; if (mins < 10) AppendIntegerToString(strBuffer, 0); AppendIntegerToString(strBuffer, mins); StrAdd(strBuffer, ":"); if (secs < 10) AppendIntegerToString(strBuffer, 0); AppendIntegerToString(strBuffer, secs); StrAdd(strBuffer, ":"); if (ms < 10) AppendIntegerToString(strBuffer, 0); AppendIntegerToString(strBuffer, ms); AddTextMenuEntry(&gameMenu[0], strBuffer); AddTextMenuEntry(&gameMenu[0], ""); StrCopy(strBuffer, "2ND: "); mins = saveRAM[3 * (listPos) + 0x41] / 6000; secs = saveRAM[3 * (listPos) + 0x41] / 100 % 60; ms = saveRAM[3 * (listPos) + 0x41] % 100; if (mins < 10) AppendIntegerToString(strBuffer, 0); AppendIntegerToString(strBuffer, mins); StrAdd(strBuffer, ":"); if (secs < 10) AppendIntegerToString(strBuffer, 0); AppendIntegerToString(strBuffer, secs); StrAdd(strBuffer, ":"); if (ms < 10) AppendIntegerToString(strBuffer, 0); AppendIntegerToString(strBuffer, ms); AddTextMenuEntry(&gameMenu[0], strBuffer); AddTextMenuEntry(&gameMenu[0], ""); StrCopy(strBuffer, "3RD: "); mins = saveRAM[3 * (listPos) + 0x42] / 6000; secs = saveRAM[3 * (listPos) + 0x42] / 100 % 60; ms = saveRAM[3 * (listPos) + 0x42] % 100; if (mins < 10) AppendIntegerToString(strBuffer, 0); AppendIntegerToString(strBuffer, mins); StrAdd(strBuffer, ":"); if (secs < 10) AppendIntegerToString(strBuffer, 0); AppendIntegerToString(strBuffer, secs); StrAdd(strBuffer, ":"); if (ms < 10) AppendIntegerToString(strBuffer, 0); AppendIntegerToString(strBuffer, ms); AddTextMenuEntry(&gameMenu[0], strBuffer); AddTextMenuEntry(&gameMenu[0], ""); SetupTextMenu(&gameMenu[1], 0); AddTextMenuEntry(&gameMenu[1], "PLAY"); AddTextMenuEntry(&gameMenu[1], ""); AddTextMenuEntry(&gameMenu[1], "BACK"); AddTextMenuEntry(&gameMenu[1], ""); gameMenu[1].alignment = 2; gameMenu[1].selectionCount = 1; gameMenu[1].selection1 = 0; gameMenu[1].selection2 = listPos; gameMenu[1].visibleRowCount = 0; gameMenu[0].alignment = 2; gameMenu[0].selectionCount = 1; gameMenu[1].timer = 0; stageMode = STARTMENU_TACONFIRMSEL; } #if RETRO_HARDWARE_RENDER render3DEnabled = false; UpdateHardwareTextures(); #endif } void setTextMenu(int sm) { ushort strBuffer[0x100]; stageMode = sm; SetupTextMenu(&gameMenu[0], 0); SetupTextMenu(&gameMenu[1], 0); switch (sm) { case DEVMENU_MAIN: { AddTextMenuEntry(&gameMenu[0], "RETRO ENGINE DEV MENU"); AddTextMenuEntry(&gameMenu[0], " "); char version[0x80]; StrCopy(version, Engine.gameWindowText); StrAdd(version, " Version"); AddTextMenuEntry(&gameMenu[0], version); AddTextMenuEntry(&gameMenu[0], Engine.gameVersion); AddTextMenuEntry(&gameMenu[0], " "); AddTextMenuEntry(&gameMenu[0], " "); AddTextMenuEntry(&gameMenu[0], " "); AddTextMenuEntry(&gameMenu[0], " "); AddTextMenuEntry(&gameMenu[0], " "); AddTextMenuEntry(&gameMenu[0], "START GAME"); AddTextMenuEntry(&gameMenu[0], " "); AddTextMenuEntry(&gameMenu[0], "STAGE SELECT"); #if !RETRO_USE_ORIGINAL_CODE AddTextMenuEntry(&gameMenu[0], " "); AddTextMenuEntry(&gameMenu[0], "START MENU"); #if RETRO_USE_MOD_LOADER AddTextMenuEntry(&gameMenu[0], " "); AddTextMenuEntry(&gameMenu[0], "MODS"); #endif AddTextMenuEntry(&gameMenu[0], " "); AddTextMenuEntry(&gameMenu[0], "EXIT GAME"); #endif gameMenu[0].alignment = 2; gameMenu[0].selectionCount = 2; gameMenu[0].selection1 = 0; gameMenu[0].selection2 = 9; gameMenu[1].visibleRowCount = 0; gameMenu[1].visibleRowOffset = 0; break; } case DEVMENU_STAGELISTSEL: AddTextMenuEntry(&gameMenu[0], "SELECT A STAGE LIST"); AddTextMenuEntry(&gameMenu[0], " "); AddTextMenuEntry(&gameMenu[0], " "); AddTextMenuEntry(&gameMenu[0], " PRESENTATION"); AddTextMenuEntry(&gameMenu[0], " "); AddTextMenuEntry(&gameMenu[0], " REGULAR"); AddTextMenuEntry(&gameMenu[0], " "); AddTextMenuEntry(&gameMenu[0], " SPECIAL"); AddTextMenuEntry(&gameMenu[0], " "); AddTextMenuEntry(&gameMenu[0], " BONUS"); gameMenu[0].alignment = 0; gameMenu[0].selection2 = 3; gameMenu[0].selectionCount = 2; break; #if !RETRO_USE_ORIGINAL_CODE case STARTMENU_MAIN: { char title[0x80]; StringUpperCase(title, Engine.gameWindowText); StrAdd(title, " START MENU"); AddTextMenuEntry(&gameMenu[0], title); AddTextMenuEntry(&gameMenu[0], " "); AddTextMenuEntry(&gameMenu[0], Engine.gameVersion); AddTextMenuEntry(&gameMenu[0], " "); AddTextMenuEntry(&gameMenu[0], " "); AddTextMenuEntry(&gameMenu[0], " "); AddTextMenuEntry(&gameMenu[0], " "); AddTextMenuEntry(&gameMenu[0], " "); AddTextMenuEntry(&gameMenu[0], " "); AddTextMenuEntry(&gameMenu[0], "START GAME"); AddTextMenuEntry(&gameMenu[0], " "); AddTextMenuEntry(&gameMenu[0], "TIME ATTACK"); AddTextMenuEntry(&gameMenu[0], " "); AddTextMenuEntry(&gameMenu[0], "ACHIEVEMENTS"); AddTextMenuEntry(&gameMenu[0], " "); AddTextMenuEntry(&gameMenu[0], "LEADERBOARDS"); if (Engine.gameType == GAME_SONIC2) { AddTextMenuEntry(&gameMenu[0], " "); AddTextMenuEntry(&gameMenu[0], "2P VERSUS"); } #if RETRO_USE_MOD_LOADER AddTextMenuEntry(&gameMenu[0], " "); AddTextMenuEntry(&gameMenu[0], "MODS"); #endif LoadConfigListText(&gameMenu[1], 0); // to get the data stored gameMenu[0].alignment = 2; gameMenu[0].selectionCount = 2; gameMenu[0].selection1 = 0; gameMenu[0].selection2 = 9; gameMenu[1].visibleRowCount = 0; gameMenu[1].visibleRowOffset = 0; break; } case STARTMENU_SAVESEL: { AddTextMenuEntry(&gameMenu[0], "SELECT A SAVE FILE"); AddTextMenuEntry(&gameMenu[1], "GAME OPTIONS"); AddTextMenuEntry(&gameMenu[1], ""); AddTextMenuEntry(&gameMenu[1], "DELETE SAVE FILE"); AddTextMenuEntry(&gameMenu[1], ""); AddTextMenuEntryW(&gameMenu[1], strNoSave); for (int s = 0; s < 4; ++s) { AddTextMenuEntry(&gameMenu[1], ""); StrCopyW(strBuffer, "SAVE "); AppendIntegerToStringW(strBuffer, s + 1); StrAddW(strBuffer, " - "); int stagePos = saveRAM[s * 8 + 4]; if (stagePos) { if (stagePos >= 0x80) { StrAddW(strBuffer, playerListText[saveRAM[s * 8 + 0]]); StrAddW(strBuffer, "-"); StrAddW(strBuffer, "SPECIAL STAGE "); AppendIntegerToStringW(strBuffer, saveRAM[s * 8 + 6] + 1); } else { if (StrComp("STAGE MENU", stageList[STAGELIST_REGULAR][stagePos - 1].name)) { StrAddW(strBuffer, playerListText[saveRAM[s * 8 + 0]]); StrAddW(strBuffer, "-"); StrAddW(strBuffer, "COMPLETE"); } else { StrAddW(strBuffer, playerListText[saveRAM[s * 8 + 0]]); StrAddW(strBuffer, "-"); StrAddW(strBuffer, strSaveStageList[(saveRAM[s * 8 + 4] - 1)]); } } } else { StrAddW(strBuffer, strNewGame); } AddTextMenuEntryW(&gameMenu[1], strBuffer); } gameMenu[1].alignment = 0; gameMenu[1].selectionCount = 1; gameMenu[1].selection1 = 0; gameMenu[1].selection2 = 0; break; } case STARTMENU_TASTAGESEL: { AddTextMenuEntry(&gameMenu[0], "SELECT A STAGE"); int cnt = 0; for (int i = 0; i < stageStrCount; ++i) { if (strSaveStageList[i] && !StrCompW(strSaveStageList[i], "Complete") && !(Engine.gameType == GAME_SONIC2 && (StrCompW(strSaveStageList[i], "Special Stage 6") || StrCompW(strSaveStageList[i], "SKY CHASE ZONE") || StrCompW(strSaveStageList[i], "DEATH EGG ZONE")))) { AddTextMenuEntry(&gameMenu[1], ""); AddTextMenuEntryW(&gameMenu[1], strSaveStageList[i]); cnt++; } } gameMenu[1].alignment = 2; gameMenu[1].selectionCount = 1; gameMenu[1].selection1 = 1; gameMenu[1].selection2 = 0; if (gameMenu[1].rowCount > 18) gameMenu[1].visibleRowCount = 18; else gameMenu[1].visibleRowCount = 0; gameMenu[0].alignment = 2; gameMenu[0].selectionCount = 1; gameMenu[1].timer = 0; gameMenu[0].timer = cnt; break; } case STARTMENU_ACHIEVEMENTS: { AddTextMenuEntry(&gameMenu[0], "ACHIEVEMENTS LIST"); char strBuffer[0x80]; for (int i = 0; i < ACHIEVEMENT_MAX; ++i) { if (!StrComp(achievements[i].name, "")) { AddTextMenuEntry(&gameMenu[1], ""); StrCopy((char *)strBuffer, achievements[i].name); StrAdd((char *)strBuffer, ": "); StrAdd((char *)strBuffer, achievements[i].status == 100 ? "achieved" : "not achieved"); AddTextMenuEntry(&gameMenu[1], (char *)strBuffer); } } gameMenu[1].alignment = 0; gameMenu[1].selectionCount = 1; gameMenu[1].selection1 = 1; gameMenu[1].selection2 = 0; if (gameMenu[1].rowCount > 15) gameMenu[1].visibleRowCount = 15; else gameMenu[1].visibleRowCount = 0; gameMenu[0].alignment = 2; gameMenu[0].selectionCount = 1; gameMenu[1].timer = 0; break; } case STARTMENU_GAMEOPTS: { AddTextMenuEntry(&gameMenu[0], "GAME OPTIONS"); if (Engine.gameType == GAME_SONIC1) { if (GetGlobalVariableByName("options.spindash")) AddTextMenuEntry(&gameMenu[1], "SPINDASH: ENABLED"); else AddTextMenuEntry(&gameMenu[1], "SPINDASH: DISABLED"); AddTextMenuEntry(&gameMenu[1], ""); if (GetGlobalVariableByName("options.speedCap")) AddTextMenuEntry(&gameMenu[1], "GROUND SPEED CAP: ENABLED"); else AddTextMenuEntry(&gameMenu[1], "GROUND SPEED CAP: DISABLED"); AddTextMenuEntry(&gameMenu[1], ""); if (GetGlobalVariableByName("options.airSpeedCap")) AddTextMenuEntry(&gameMenu[1], "AIR SPEED CAP: ENABLED"); else AddTextMenuEntry(&gameMenu[1], "AIR SPEED CAP: DISABLED"); AddTextMenuEntry(&gameMenu[1], ""); if (GetGlobalVariableByName("options.spikeBehavior")) AddTextMenuEntry(&gameMenu[1], "S1 SPIKES: ENABLED"); else AddTextMenuEntry(&gameMenu[1], "S1 SPIKES: DISABLED"); AddTextMenuEntry(&gameMenu[1], ""); char itemBoxTypes[4][0x20] = { "ITEM TYPE: S1", "ITEM TYPE: S2", "ITEM TYPE: S1+S3", "ITEM TYPE: S2+S3" }; AddTextMenuEntry(&gameMenu[1], itemBoxTypes[GetGlobalVariableByName("options.shieldType")]); AddTextMenuEntry(&gameMenu[1], ""); if (GetGlobalVariableByName("options.superStates")) AddTextMenuEntry(&gameMenu[1], "SUPER FORMS: ENABLED"); else AddTextMenuEntry(&gameMenu[1], "SUPER FORMS: DISABLED"); } else { if (GetGlobalVariableByName("options.airSpeedCap")) AddTextMenuEntry(&gameMenu[1], "AIR SPEED CAP: ENABLED"); else AddTextMenuEntry(&gameMenu[1], "AIR SPEED CAP: DISABLED"); AddTextMenuEntry(&gameMenu[1], ""); if (GetGlobalVariableByName("options.tailsFlight")) AddTextMenuEntry(&gameMenu[1], "TAILS FLIGHT: ENABLED"); else AddTextMenuEntry(&gameMenu[1], "TAILS FLIGHT: DISABLED"); AddTextMenuEntry(&gameMenu[1], ""); if (GetGlobalVariableByName("options.superTails")) AddTextMenuEntry(&gameMenu[1], "SUPER TAILS: ENABLED"); else AddTextMenuEntry(&gameMenu[1], "SUPER TAILS: DISABLED"); AddTextMenuEntry(&gameMenu[1], ""); if (GetGlobalVariableByName("options.spikeBehavior")) AddTextMenuEntry(&gameMenu[1], "S1 SPIKES: ENABLED"); else AddTextMenuEntry(&gameMenu[1], "S1 SPIKES: DISABLED"); AddTextMenuEntry(&gameMenu[1], ""); char itemBoxTypes[4][0x20] = { "ITEM TYPE: S2", "ITEM TYPE: S2+S3", "ITEM TYPE: RANDOM", "ITEM TYPE: RANDOM+S3" }; AddTextMenuEntry(&gameMenu[1], itemBoxTypes[GetGlobalVariableByName("options.shieldType")]); } } #endif } } void processStartMenu() { ClearScreen(0xF0); keyDown.start = false; keyDown.B = false; keyDown.up = false; keyDown.down = false; CheckKeyDown(&keyDown); CheckKeyPress(&keyPress); if (!keyDown.start && !keyDown.up && !keyDown.down) { if (touches > 0) { if (touchDown[0] && !(touchTimer % 8)) { if (touchX[0] < SCREEN_CENTERX) { if (touchY[0] >= SCREEN_CENTERY) { if (!keyDown.down) keyPress.down = true; keyDown.down = true; } else { if (!keyDown.up) keyPress.up = true; keyDown.up = true; } } else if (touchX[0] > SCREEN_CENTERX) { if (touchY[0] > SCREEN_CENTERY) { if (!keyDown.start) keyPress.start = true; keyDown.start = true; } else { if (!keyDown.B) keyPress.B = true; keyDown.B = true; } } } } } touchTimer++; switch (stageMode) { case STARTMENU_MAIN: { if (keyPress.down) gameMenu[0].selection2 += 2; if (keyPress.up) gameMenu[0].selection2 -= 2; if (Engine.gameType == GAME_SONIC2) { int count = 17; #if RETRO_USE_MOD_LOADER count += 2; #endif if (gameMenu[0].selection2 > count) gameMenu[0].selection2 = 9; if (gameMenu[0].selection2 < 9) gameMenu[0].selection2 = count; } else { int count = 15; #if RETRO_USE_MOD_LOADER count += 2; #endif if (gameMenu[0].selection2 > count) gameMenu[0].selection2 = 9; if (gameMenu[0].selection2 < 9) gameMenu[0].selection2 = count; } DrawTextMenu(&gameMenu[0], SCREEN_CENTERX, 72); if (keyPress.start || keyPress.A) { if (gameMenu[0].selection2 == 9) { setTextMenu(STARTMENU_SAVESEL); } else if (gameMenu[0].selection2 == 11) { setTextMenu(STARTMENU_TASTAGESEL); } else if (gameMenu[0].selection2 == 13) { setTextMenu(STARTMENU_ACHIEVEMENTS); } else if (gameMenu[0].selection2 == 15) { PlaySFXByName("Hurt", 0); } #if RETRO_USE_MOD_LOADER else if ((gameMenu[0].selection2 == 17 && Engine.gameType != GAME_SONIC2) || (gameMenu[0].selection2 == 19 && Engine.gameType == GAME_SONIC2)) { SetupTextMenu(&gameMenu[0], 0); AddTextMenuEntry(&gameMenu[0], "MOD LIST"); SetupTextMenu(&gameMenu[1], 0); initMods(); // reload mods char buffer[0x100]; for (int m = 0; m < modCount; ++m) { StrCopy(buffer, modList[m].name.c_str()); StrAdd(buffer, ": "); StrAdd(buffer, modList[m].active ? " Active" : "Inactive"); AddTextMenuEntry(&gameMenu[1], buffer); } gameMenu[1].alignment = 1; gameMenu[1].selectionCount = 3; gameMenu[1].selection1 = 0; if (gameMenu[1].rowCount > 18) gameMenu[1].visibleRowCount = 18; else gameMenu[1].visibleRowCount = 0; gameMenu[0].alignment = 2; gameMenu[0].selectionCount = 1; gameMenu[1].timer = 0; gameMenu[1].visibleRowOffset = 0; stageMode = STARTMENU_MODMENU; } #endif else { PlaySFXByName("Hurt", 0); // TODO: add networking code and remove this if statement if (false) { // 2P VS SetGlobalVariableByName("options.saveSlot", 0); SetGlobalVariableByName("options.gameMode", 0); SetGlobalVariableByName("options.vsMode", 0); SetGlobalVariableByName("stage.player2Enabled", true); // 2P SetGlobalVariableByName("player.lives", 3); SetGlobalVariableByName("player.score", 0); SetGlobalVariableByName("player.scoreBonus", 50000); SetGlobalVariableByName("specialStage.listPos", 0); SetGlobalVariableByName("specialStage.emeralds", 0); SetGlobalVariableByName("specialStage.nextZone", 0); SetGlobalVariableByName("timeAttack.result", 0); SetGlobalVariableByName("lampPostID", 0); // For S1 SetGlobalVariableByName("starPostID", 0); // For S2 // if (Engine.onlineActive) InitStartingStage(STAGELIST_PRESENTATION, 3, 0); } } } else if (keyPress.B) { Engine.running = false; } break; } case STARTMENU_SAVESEL: { if (keyPress.down) gameMenu[1].selection1 += 2; if (keyPress.up) gameMenu[1].selection1 -= 2; if (gameMenu[1].selection1 > 12) gameMenu[1].selection1 = 0; if (gameMenu[1].selection1 < 0) gameMenu[1].selection1 = 12; DrawTextMenu(&gameMenu[0], SCREEN_CENTERX - 4, 72); DrawTextMenu(&gameMenu[1], 16, 96); if (keyPress.start || keyPress.A) { if (gameMenu[1].selection1 == 0) { setTextMenu(STARTMENU_GAMEOPTS); } else if (gameMenu[1].selection1 == 2) { if (!gameMenu[1].selection2) { SetTextMenuEntry(&gameMenu[1], "CANCEL", 2); gameMenu[1].selection2 ^= 1; } else { SetTextMenuEntry(&gameMenu[1], "DELETE SAVE FILE", 2); gameMenu[1].selection2 ^= 1; } } else { int saveSlot = (gameMenu[1].selection1 - 6) / 2; if (!gameMenu[1].selection2) { if (saveSlot >= 0 && saveSlot < 4) { int savePos = saveSlot << 3; if (saveRAM[savePos + 4]) { SetGlobalVariableByName("options.saveSlot", saveSlot); SetGlobalVariableByName("options.gameMode", 1); SetGlobalVariableByName("options.stageSelectFlag", 0); SetGlobalVariableByName("player.lives", saveRAM[savePos + 1]); SetGlobalVariableByName("player.score", saveRAM[savePos + 2]); SetGlobalVariableByName("player.scoreBonus", saveRAM[savePos + 3]); SetGlobalVariableByName("specialStage.emeralds", saveRAM[savePos + 5]); SetGlobalVariableByName("specialStage.listPos", saveRAM[savePos + 6]); SetGlobalVariableByName("stage.player2Enabled", saveRAM[savePos + 0] == 3); SetGlobalVariableByName("lampPostID", 0); // For S1 SetGlobalVariableByName("starPostID", 0); // For S2 SetGlobalVariableByName("options.vsMode", 0); int nextZone = saveRAM[savePos + 4]; if (nextZone > 127) { SetGlobalVariableByName("specialStage.nextZone", nextZone - 129); InitStartingStage(STAGELIST_SPECIAL, saveRAM[savePos + 6], saveRAM[savePos + 0]); } else { SetGlobalVariableByName("specialStage.nextZone", nextZone - 1); InitStartingStage(STAGELIST_REGULAR, saveRAM[savePos + 4] - 1, saveRAM[savePos + 0]); } } else { // new save SetupTextMenu(&gameMenu[0], 0); AddTextMenuEntry(&gameMenu[0], "SELECT A PLAYER"); SetupTextMenu(&gameMenu[1], 0); LoadConfigListText(&gameMenu[1], 0); gameMenu[1].alignment = 0; gameMenu[1].selectionCount = 1; gameMenu[1].selection1 = 0; gameMenu[1].selection2 = saveSlot; stageMode = STARTMENU_PLAYERSEL; } } else { // nosave SetupTextMenu(&gameMenu[0], 0); AddTextMenuEntry(&gameMenu[0], "SELECT A PLAYER"); SetupTextMenu(&gameMenu[1], 0); LoadConfigListText(&gameMenu[1], 0); gameMenu[1].alignment = 0; gameMenu[1].selectionCount = 1; gameMenu[1].selection1 = 0; gameMenu[1].selection2 = saveSlot; stageMode = STARTMENU_PLAYERSEL; } } else { if (saveSlot >= 0 && saveSlot < 4) { int savePos = saveSlot << 3; saveRAM[savePos + 0] = 0; saveRAM[savePos + 1] = 3; saveRAM[savePos + 2] = 0; saveRAM[savePos + 3] = 50000; saveRAM[savePos + 4] = 0; saveRAM[savePos + 5] = 0; saveRAM[savePos + 6] = 0; saveRAM[savePos + 7] = 0; ushort strBuffer[0x100]; StrCopyW(strBuffer, "SAVE "); AppendIntegerToStringW(strBuffer, saveSlot + 1); StrAddW(strBuffer, " - "); StrAddW(strBuffer, strNewGame); SetTextMenuEntryW(&gameMenu[1], strBuffer, gameMenu[1].selection1); } } } } else if (keyPress.B) { initStartMenu(0); } break; } case STARTMENU_PLAYERSEL: { if (keyPress.down) ++gameMenu[1].selection1; if (keyPress.up) --gameMenu[1].selection1; if (gameMenu[1].selection1 == gameMenu[1].rowCount) gameMenu[1].selection1 = 0; if (gameMenu[1].selection1 < 0) gameMenu[1].selection1 = gameMenu[1].rowCount - 1; DrawTextMenu(&gameMenu[0], SCREEN_CENTERX - 4, 72); DrawTextMenu(&gameMenu[1], SCREEN_CENTERX - 40, 96); if (keyPress.start || keyPress.A) { int saveSlot = gameMenu[1].selection2; int savePos = saveSlot << 3; if (saveSlot < 0) { SetGlobalVariableByName("options.gameMode", 0); saveSlot = 0; } else { SetGlobalVariableByName("options.gameMode", 1); SetGlobalVariableByName("options.stageSelectFlag", 0); } saveRAM[savePos + 0] = gameMenu[1].selection1; saveRAM[savePos + 1] = 3; saveRAM[savePos + 2] = 0; saveRAM[savePos + 3] = 50000; saveRAM[savePos + 4] = 1; saveRAM[savePos + 5] = 0; saveRAM[savePos + 6] = 0; saveRAM[savePos + 7] = 0; SetGlobalVariableByName("options.saveSlot", saveSlot); SetGlobalVariableByName("player.lives", saveRAM[savePos + 1]); SetGlobalVariableByName("player.score", saveRAM[savePos + 2]); SetGlobalVariableByName("player.scoreBonus", saveRAM[savePos + 3]); SetGlobalVariableByName("specialStage.emeralds", saveRAM[savePos + 5]); SetGlobalVariableByName("specialStage.listPos", saveRAM[savePos + 6]); SetGlobalVariableByName("stage.player2Enabled", saveRAM[savePos + 0] == 3); SetGlobalVariableByName("lampPostID", 0); // For S1 SetGlobalVariableByName("starPostID", 0); // For S2 SetGlobalVariableByName("options.vsMode", 0); WriteSaveRAMData(); InitStartingStage(STAGELIST_PRESENTATION, 0, saveRAM[savePos + 0]); } else if (keyPress.B) { setTextMenu(STARTMENU_SAVESEL); } break; } case STARTMENU_GAMEOPTS: { if (keyPress.down) gameMenu[1].selection1 += 2; if (keyPress.up) gameMenu[1].selection1 -= 2; if (gameMenu[1].selection1 >= gameMenu[1].rowCount) gameMenu[1].selection1 = 0; if (gameMenu[1].selection1 < 0) gameMenu[1].selection1 = gameMenu[1].rowCount - 1; DrawTextMenu(&gameMenu[0], SCREEN_CENTERX - 4, 72); DrawTextMenu(&gameMenu[1], SCREEN_CENTERX - 40, 96); if (keyPress.left || keyPress.right || keyPress.start) { if (Engine.gameType == GAME_SONIC1) { switch (gameMenu[1].selection1) { case 0: // Spindash SetGlobalVariableByName("options.spindash", GetGlobalVariableByName("options.spindash") ^ 1); if (GetGlobalVariableByName("options.spindash")) SetTextMenuEntry(&gameMenu[1], "SPINDASH: ENABLED", 0); else SetTextMenuEntry(&gameMenu[1], "SPINDASH: DISABLED", 0); break; case 2: // Ground Spd Cap SetGlobalVariableByName("options.speedCap", GetGlobalVariableByName("options.speedCap") ^ 1); if (GetGlobalVariableByName("options.speedCap")) SetTextMenuEntry(&gameMenu[1], "GROUND SPEED CAP: ENABLED", 2); else SetTextMenuEntry(&gameMenu[1], "GROUND SPEED CAP: DISABLED", 2); break; case 4: // Air Spd Cap SetGlobalVariableByName("options.airSpeedCap", GetGlobalVariableByName("options.airSpeedCap") ^ 1); if (GetGlobalVariableByName("options.airSpeedCap")) SetTextMenuEntry(&gameMenu[1], "AIR SPEED CAP: ENABLED", 4); else SetTextMenuEntry(&gameMenu[1], "AIR SPEED CAP: DISABLED", 4); break; case 6: // S1 Spikes SetGlobalVariableByName("options.spikeBehavior", GetGlobalVariableByName("options.spikeBehavior") ^ 1); if (GetGlobalVariableByName("options.spikeBehavior")) SetTextMenuEntry(&gameMenu[1], "S1 SPIKES: ENABLED", 6); else SetTextMenuEntry(&gameMenu[1], "S1 SPIKES: DISABLED", 6); break; case 8: { if (keyPress.left) { int var = (GetGlobalVariableByName("options.shieldType") - 1); if (var < 0) var = 3; SetGlobalVariableByName("options.shieldType", var); } else SetGlobalVariableByName("options.shieldType", (GetGlobalVariableByName("options.shieldType") + 1) % 4); int type = GetGlobalVariableByName("options.shieldType"); char itemBoxTypes[4][0x20] = { "ITEM TYPE: S1", "ITEM TYPE: S2", "ITEM TYPE: S1+S3", "ITEM TYPE: S2+S3" }; SetTextMenuEntry(&gameMenu[1], itemBoxTypes[type], 8); break; } case 10: // Super forms SetGlobalVariableByName("options.superStates", GetGlobalVariableByName("options.superStates") ^ 1); if (GetGlobalVariableByName("options.superStates")) SetTextMenuEntry(&gameMenu[1], "SUPER FORMS: ENABLED", 10); else SetTextMenuEntry(&gameMenu[1], "SUPER FORMS: DISABLED", 10); break; } } else { switch (gameMenu[1].selection1) { case 0: SetGlobalVariableByName("options.airSpeedCap", GetGlobalVariableByName("options.airSpeedCap") ^ 1); if (GetGlobalVariableByName("options.airSpeedCap")) SetTextMenuEntry(&gameMenu[1], "AIR SPEED CAP: ENABLED", 0); else SetTextMenuEntry(&gameMenu[1], "AIR SPEED CAP: DISABLED", 0); break; case 2: SetGlobalVariableByName("options.tailsFlight", GetGlobalVariableByName("options.tailsFlight") ^ 1); if (GetGlobalVariableByName("options.tailsFlight")) SetTextMenuEntry(&gameMenu[1], "TAILS FLIGHT: ENABLED", 2); else SetTextMenuEntry(&gameMenu[1], "TAILS FLIGHT: DISABLED", 2); break; case 4: SetGlobalVariableByName("options.superTails", GetGlobalVariableByName("options.superTails") ^ 1); if (GetGlobalVariableByName("options.superTails")) SetTextMenuEntry(&gameMenu[1], "SUPER TAILS: ENABLED", 4); else SetTextMenuEntry(&gameMenu[1], "SUPER TAILS: DISABLED", 4); break; case 6: SetGlobalVariableByName("options.spikeBehavior", GetGlobalVariableByName("options.spikeBehavior") ^ 1); if (GetGlobalVariableByName("options.spikeBehavior")) SetTextMenuEntry(&gameMenu[1], "S1 SPIKES: ENABLED", 6); else SetTextMenuEntry(&gameMenu[1], "S1 SPIKES: DISABLED", 6); break; case 8: { if (keyPress.left) { int var = (GetGlobalVariableByName("options.shieldType") - 1); if (var < 0) var = 3; SetGlobalVariableByName("options.shieldType", var); } else SetGlobalVariableByName("options.shieldType", (GetGlobalVariableByName("options.shieldType") + 1) % 4); int type = GetGlobalVariableByName("options.shieldType"); char itemBoxTypes[4][0x20] = { "ITEM TYPE: S2", "ITEM TYPE: S2+S3", "ITEM TYPE: RANDOM", "ITEM TYPE: RANDOM+S3" }; SetTextMenuEntry(&gameMenu[1], itemBoxTypes[type], 8); break; } } } } else if (keyPress.B) { setTextMenu(STARTMENU_SAVESEL); saveRAM[0x100] = Engine.gameType; if (Engine.gameType == GAME_SONIC1) { saveRAM[0x101] = GetGlobalVariableByName("options.spindash"); saveRAM[0x102] = GetGlobalVariableByName("options.speedCap"); saveRAM[0x103] = GetGlobalVariableByName("options.airSpeedCap"); saveRAM[0x104] = GetGlobalVariableByName("options.spikeBehavior"); saveRAM[0x105] = GetGlobalVariableByName("options.shieldType"); saveRAM[0x106] = GetGlobalVariableByName("options.superStates"); } else { saveRAM[0x101] = GetGlobalVariableByName("options.airSpeedCap"); saveRAM[0x102] = GetGlobalVariableByName("options.tailsFlight"); saveRAM[0x103] = GetGlobalVariableByName("options.superTails"); saveRAM[0x104] = GetGlobalVariableByName("options.spikeBehavior"); saveRAM[0x105] = GetGlobalVariableByName("options.shieldType"); } WriteSaveRAMData(); } break; } case STARTMENU_TASTAGESEL: { if (keyDown.down) { gameMenu[1].timer += 1; if (gameMenu[1].timer > 8) { gameMenu[1].timer = 0; keyPress.down = true; } } else { if (keyDown.up) { gameMenu[1].timer -= 1; if (gameMenu[1].timer < -8) { gameMenu[1].timer = 0; keyPress.up = true; } } else { gameMenu[1].timer = 0; } } if (keyPress.down) { gameMenu[1].selection1 += 2; if (gameMenu[1].selection1 - gameMenu[1].visibleRowOffset >= gameMenu[1].visibleRowCount) { gameMenu[1].visibleRowOffset += 2; } } if (keyPress.up) { gameMenu[1].selection1 -= 2; if (gameMenu[1].selection1 - gameMenu[1].visibleRowOffset < 0) { gameMenu[1].visibleRowOffset -= 2; } } if (gameMenu[1].selection1 >= gameMenu[1].rowCount) { gameMenu[1].selection1 = 1; gameMenu[1].visibleRowOffset = 0; } if (gameMenu[1].selection1 < 0) { gameMenu[1].selection1 = gameMenu[1].rowCount - 1; gameMenu[1].visibleRowOffset = gameMenu[1].rowCount - gameMenu[1].visibleRowCount; } DrawTextMenu(&gameMenu[0], SCREEN_CENTERX - 4, 40); DrawTextMenu(&gameMenu[1], SCREEN_CENTERX, 64); if (keyPress.start || keyPress.A) { int listPos = (gameMenu[1].selection1 - 1) / 2; int max = stageListCount[STAGELIST_REGULAR]; for (int s = 0; s < stageListCount[STAGELIST_REGULAR]; ++s) { if (StrComp(stageList[STAGELIST_REGULAR][s].name, "STAGE MENU")) { max = s; break; } } if (Engine.gameType == GAME_SONIC2) { if (listPos >= 17) listPos++; // SCZ patch if (listPos >= 19) listPos++; // DEZ patch } if (listPos < max) { activeStageList = STAGELIST_REGULAR; stageListPosition = listPos; } else { if (Engine.gameType == GAME_SONIC1) { activeStageList = STAGELIST_SPECIAL; stageListPosition = listPos - max; } else if (Engine.gameType == GAME_SONIC2) { activeStageList = STAGELIST_BONUS; stageListPosition = listPos - max; if (stageListPosition < 2) stageListPosition ^= 1; } } if (!saveRAM[0x40]) { for (int s = 0; s < (gameMenu[1].rowCount / 2) * 3; ++s) { saveRAM[s + 0x40] = 60000; } WriteSaveRAMData(); } if (!saveRAM[3 * (listPos) + 0x40]) { for (int s = 0; s < 3; ++s) { saveRAM[(3 * (listPos) + 0x40) + s] = 60000; } WriteSaveRAMData(); } if (Engine.gameType == GAME_SONIC2) { if (listPos >= 17) listPos--; // SCZ patch 2 if (listPos >= 19) listPos--; // DEZ patch 2 } char strBuffer[0x100]; SetupTextMenu(&gameMenu[0], 0); AddTextMenuEntry(&gameMenu[0], "BEST TIMES"); AddTextMenuEntry(&gameMenu[0], ""); StrCopy(strBuffer, "1ST: "); int mins = saveRAM[3 * (listPos) + 0x40] / 6000; int secs = saveRAM[3 * (listPos) + 0x40] / 100 % 60; int ms = saveRAM[3 * (listPos) + 0x40] % 100; if (mins < 10) AppendIntegerToString(strBuffer, 0); AppendIntegerToString(strBuffer, mins); StrAdd(strBuffer, ":"); if (secs < 10) AppendIntegerToString(strBuffer, 0); AppendIntegerToString(strBuffer, secs); StrAdd(strBuffer, ":"); if (ms < 10) AppendIntegerToString(strBuffer, 0); AppendIntegerToString(strBuffer, ms); AddTextMenuEntry(&gameMenu[0], strBuffer); AddTextMenuEntry(&gameMenu[0], ""); StrCopy(strBuffer, "2ND: "); mins = saveRAM[3 * (listPos) + 0x41] / 6000; secs = saveRAM[3 * (listPos) + 0x41] / 100 % 60; ms = saveRAM[3 * (listPos) + 0x41] % 100; if (mins < 10) AppendIntegerToString(strBuffer, 0); AppendIntegerToString(strBuffer, mins); StrAdd(strBuffer, ":"); if (secs < 10) AppendIntegerToString(strBuffer, 0); AppendIntegerToString(strBuffer, secs); StrAdd(strBuffer, ":"); if (ms < 10) AppendIntegerToString(strBuffer, 0); AppendIntegerToString(strBuffer, ms); AddTextMenuEntry(&gameMenu[0], strBuffer); AddTextMenuEntry(&gameMenu[0], ""); StrCopy(strBuffer, "3RD: "); mins = saveRAM[3 * (listPos) + 0x42] / 6000; secs = saveRAM[3 * (listPos) + 0x42] / 100 % 60; ms = saveRAM[3 * (listPos) + 0x42] % 100; if (mins < 10) AppendIntegerToString(strBuffer, 0); AppendIntegerToString(strBuffer, mins); StrAdd(strBuffer, ":"); if (secs < 10) AppendIntegerToString(strBuffer, 0); AppendIntegerToString(strBuffer, secs); StrAdd(strBuffer, ":"); if (ms < 10) AppendIntegerToString(strBuffer, 0); AppendIntegerToString(strBuffer, ms); AddTextMenuEntry(&gameMenu[0], strBuffer); AddTextMenuEntry(&gameMenu[0], ""); SetupTextMenu(&gameMenu[1], 0); AddTextMenuEntry(&gameMenu[1], "PLAY"); AddTextMenuEntry(&gameMenu[1], ""); AddTextMenuEntry(&gameMenu[1], "BACK"); AddTextMenuEntry(&gameMenu[1], ""); gameMenu[1].alignment = 2; gameMenu[1].selectionCount = 1; gameMenu[1].selection1 = 0; gameMenu[1].selection2 = listPos; gameMenu[1].visibleRowCount = 0; gameMenu[0].alignment = 2; gameMenu[0].selectionCount = 1; gameMenu[1].timer = 0; stageMode = STARTMENU_TACONFIRMSEL; } else if (keyPress.B) { initStartMenu(0); } break; } case STARTMENU_TACONFIRMSEL: { if (keyPress.down) gameMenu[1].selection1 += 2; if (keyPress.up) gameMenu[1].selection1 -= 2; if (gameMenu[1].selection1 > 3) gameMenu[1].selection1 = 0; if (gameMenu[1].selection1 < 0) gameMenu[1].selection1 = 2; DrawTextMenu(&gameMenu[0], SCREEN_CENTERX - 4, 40); DrawTextMenu(&gameMenu[1], SCREEN_CENTERX, SCREEN_CENTERY); if (keyPress.start || keyPress.A) { if (gameMenu[1].selection1 == 0) { SetGlobalVariableByName("options.saveSlot", 0); SetGlobalVariableByName("options.gameMode", 2); SetGlobalVariableByName("stage.player2Enabled", false); SetGlobalVariableByName("player.lives", 1); SetGlobalVariableByName("player.score", 0); SetGlobalVariableByName("player.scoreBonus", 50000); SetGlobalVariableByName("specialStage.listPos", 0); SetGlobalVariableByName("specialStage.emeralds", 0); SetGlobalVariableByName("specialStage.nextZone", 0); SetGlobalVariableByName("specialStage.nextZone", 0); SetGlobalVariableByName("lampPostID", 0); // For S1 SetGlobalVariableByName("starPostID", 0); // For S2 SetGlobalVariableByName("timeAttack.result", 0); if (Engine.gameType == GAME_SONIC1) { SetGlobalVariableByName("options.spindash", 1); SetGlobalVariableByName("options.speedCap", 0); SetGlobalVariableByName("options.airSpeedCap", 0); SetGlobalVariableByName("options.spikeBehavior", 0); SetGlobalVariableByName("options.shieldType", 0); SetGlobalVariableByName("options.superStates", 0); } else { SetGlobalVariableByName("options.airSpeedCap", 0); SetGlobalVariableByName("options.tailsFlight", 1); SetGlobalVariableByName("options.superTails", 1); SetGlobalVariableByName("options.spikeBehavior", 0); SetGlobalVariableByName("options.shieldType", 0); } taListStore = gameMenu[1].selection2; InitStartingStage(activeStageList, stageListPosition, 0); } else { // TA setTextMenu(STARTMENU_TASTAGESEL); } } break; } case STARTMENU_ACHIEVEMENTS: { if (keyDown.down) { gameMenu[1].timer += 1; if (gameMenu[1].timer > 8) { gameMenu[1].timer = 0; keyPress.down = true; } } else { if (keyDown.up) { gameMenu[1].timer -= 1; if (gameMenu[1].timer < -8) { gameMenu[1].timer = 0; keyPress.up = true; } } else { gameMenu[1].timer = 0; } } if (keyPress.down) { gameMenu[1].selection1 += 2; if (gameMenu[1].selection1 - gameMenu[1].visibleRowOffset >= gameMenu[1].visibleRowCount) { gameMenu[1].visibleRowOffset += 2; } } if (keyPress.up) { gameMenu[1].selection1 -= 2; if (gameMenu[1].selection1 - gameMenu[1].visibleRowOffset < 0) { gameMenu[1].visibleRowOffset -= 2; } } if (gameMenu[1].selection1 >= gameMenu[1].rowCount) { gameMenu[1].selection1 = 1; gameMenu[1].visibleRowOffset = 0; } if (gameMenu[1].selection1 < 0) { gameMenu[1].selection1 = gameMenu[1].rowCount - 1; gameMenu[1].visibleRowOffset = gameMenu[1].rowCount - gameMenu[1].visibleRowCount; } DrawTextMenu(&gameMenu[0], SCREEN_CENTERX - 4, 72); DrawTextMenu(&gameMenu[1], 16, 96); if (keyPress.B) { initStartMenu(0); } break; } #if RETRO_USE_MOD_LOADER case STARTMENU_MODMENU: // Mod Menu { if (keyDown.down) { gameMenu[1].timer += 1; if (gameMenu[1].timer > 20) { gameMenu[1].timer = 0; keyPress.down = true; } } else { if (keyDown.up) { gameMenu[1].timer -= 1; if (gameMenu[1].timer < -20) { gameMenu[1].timer = 0; keyPress.up = true; } } else { gameMenu[1].timer = 0; } } if (keyPress.down) { gameMenu[1].selection1++; if (gameMenu[1].selection1 - gameMenu[1].visibleRowOffset >= gameMenu[1].visibleRowCount) { gameMenu[1].visibleRowOffset += 1; } } if (keyPress.up) { gameMenu[1].selection1--; if (gameMenu[1].selection1 - gameMenu[1].visibleRowOffset < 0) { gameMenu[1].visibleRowOffset -= 1; } } if (gameMenu[1].selection1 >= gameMenu[1].rowCount) { gameMenu[1].selection1 = 0; gameMenu[1].visibleRowOffset = 0; } if (gameMenu[1].selection1 < 0) { gameMenu[1].selection1 = gameMenu[1].rowCount - 1; gameMenu[1].visibleRowOffset = gameMenu[1].rowCount - gameMenu[1].visibleRowCount; } gameMenu[1].selection2 = gameMenu[1].selection1; // its a bug fix LOL gameMenu[2].visibleRowOffset = gameMenu[1].visibleRowOffset; gameMenu[2].selection1 = gameMenu[1].selection1; EditTextMenuEntry(&gameMenu[0], modList[gameMenu[1].selection1].name.c_str(), 0); EditTextMenuEntry(&gameMenu[0], modList[gameMenu[1].selection1].author.c_str(), 1); EditTextMenuEntry(&gameMenu[0], modList[gameMenu[1].selection1].desc.c_str(), 2); char buffer[0x100]; if (keyPress.A || keyPress.start || keyPress.left || keyPress.right) { modList[gameMenu[1].selection1].active ^= 1; StrCopy(buffer, (modList[gameMenu[1].selection1].active ? " Active" : "Inactive")); EditTextMenuEntry(&gameMenu[2], buffer, gameMenu[1].selection1); } if (keyPress.B) { StopMusic(); // Reload entire engine Engine.LoadGameConfig("Data/Game/GameConfig.bin"); ReleaseStageSfx(); ReleaseGlobalSfx(); LoadGlobalSfx(); forceUseScripts = false; for (int m = 0; m < modCount; ++m) { if (modList[m].useScripts && modList[m].active) forceUseScripts = true; } saveMods(); //Go to Forever Main Menu activeStageList = 0; stageMode = STAGEMODE_LOAD; Engine.gameMode = ENGINE_MAINGAME; stageListPosition = 6; //setTextMenu(STARTMENU_MAIN); } SetActivePalette(7, 0, SCREEN_YSIZE); //Draw here //Background drawtemp = modbgscroll; while (drawtemp < SCREEN_XSIZE) { DrawSprite(drawtemp, 0, 12, 240, 1, 1, SURFACE_MAX - 1); drawtemp += 12; } modbgtick++; modbgtick %= 36; if (modbgtick % 3 == 0) { modbgscroll--; //modbgtick = 0; } if (modbgscroll < -11) { modbgscroll = 0; } //Stars /* switch (modbgtick / 3) { case 0: DrawSprite(SCREEN_XSIZE * 276 / 420, (SCREEN_YSIZE - 52) * 109 / 238, 5, 5, 39, 144, SURFACE_MAX - 1); DrawSprite(SCREEN_XSIZE * 214 / 420, (SCREEN_YSIZE - 52) * 132 / 238, 5, 5, 27, 144, SURFACE_MAX - 1); DrawSprite(SCREEN_XSIZE * 163 / 420, (SCREEN_YSIZE - 52) * 176 / 238, 5, 5, 15, 144, SURFACE_MAX - 1); break; case 1: DrawSprite(SCREEN_XSIZE * 214 / 420, (SCREEN_YSIZE - 52) * 132 / 238, 5, 5, 33, 144, SURFACE_MAX - 1); DrawSprite(SCREEN_XSIZE * 163 / 420, (SCREEN_YSIZE - 52) * 176 / 238, 5, 5, 21, 144, SURFACE_MAX - 1); break; case 2: DrawSprite(SCREEN_XSIZE * 214 / 420, (SCREEN_YSIZE - 52) * 132 / 238, 5, 5, 39, 144, SURFACE_MAX - 1); DrawSprite(SCREEN_XSIZE * 163 / 420, (SCREEN_YSIZE - 52) * 176 / 238, 5, 5, 27, 144, SURFACE_MAX - 1); DrawSprite(SCREEN_XSIZE * 381 / 420, (SCREEN_YSIZE - 52) * 223 / 238, 5, 5, 15, 144, SURFACE_MAX - 1); break; case 3: DrawSprite(SCREEN_XSIZE * 163 / 420, (SCREEN_YSIZE - 52) * 176 / 238, 5, 5, 33, 144, SURFACE_MAX - 1); DrawSprite(SCREEN_XSIZE * 381 / 420, (SCREEN_YSIZE - 52) * 223 / 238, 5, 5, 21, 144, SURFACE_MAX - 1); break; case 4: DrawSprite(SCREEN_XSIZE * 163 / 420, (SCREEN_YSIZE - 52) * 176 / 238, 5, 5, 39, 144, SURFACE_MAX - 1); DrawSprite(SCREEN_XSIZE * 381 / 420, (SCREEN_YSIZE - 52) * 223 / 238, 5, 5, 27, 144, SURFACE_MAX - 1); DrawSprite(SCREEN_XSIZE * 76 / 420, (SCREEN_YSIZE - 52) * 72 / 238, 5, 5, 15, 144, SURFACE_MAX - 1); break; case 5: DrawSprite(SCREEN_XSIZE * 381 / 420, (SCREEN_YSIZE - 52) * 223 / 238, 5, 5, 33, 144, SURFACE_MAX - 1); DrawSprite(SCREEN_XSIZE * 76 / 420, (SCREEN_YSIZE - 52) * 72 / 238, 5, 5, 21, 144, SURFACE_MAX - 1); break; case 6: DrawSprite(SCREEN_XSIZE * 381 / 420, (SCREEN_YSIZE - 52) * 223 / 238, 5, 5, 39, 144, SURFACE_MAX - 1); DrawSprite(SCREEN_XSIZE * 76 / 420, (SCREEN_YSIZE - 52) * 72 / 238, 5, 5, 27, 144, SURFACE_MAX - 1); DrawSprite(SCREEN_XSIZE * 108 / 420, (SCREEN_YSIZE - 52) * 190 / 238, 5, 5, 15, 144, SURFACE_MAX - 1); break; case 7: DrawSprite(SCREEN_XSIZE * 76 / 420, (SCREEN_YSIZE - 52) * 72 / 238, 5, 5, 33, 144, SURFACE_MAX - 1); DrawSprite(SCREEN_XSIZE * 108 / 420, (SCREEN_YSIZE - 52) * 190 / 238, 5, 5, 21, 144, SURFACE_MAX - 1); break; case 8: DrawSprite(SCREEN_XSIZE * 76 / 420, (SCREEN_YSIZE - 52) * 72 / 238, 5, 5, 39, 144, SURFACE_MAX - 1); DrawSprite(SCREEN_XSIZE * 108 / 420, (SCREEN_YSIZE - 52) * 190 / 238, 5, 5, 27, 144, SURFACE_MAX - 1); DrawSprite(SCREEN_XSIZE * 276 / 420, (SCREEN_YSIZE - 52) * 109 / 238, 5, 5, 15, 144, SURFACE_MAX - 1); break; case 9: DrawSprite(SCREEN_XSIZE * 108 / 420, (SCREEN_YSIZE - 52) * 190 / 238, 5, 5, 33, 144, SURFACE_MAX - 1); DrawSprite(SCREEN_XSIZE * 276 / 420, (SCREEN_YSIZE - 52) * 109 / 238, 5, 5, 21, 144, SURFACE_MAX - 1); break; case 10: DrawSprite(SCREEN_XSIZE * 108 / 420, (SCREEN_YSIZE - 52) * 190 / 238, 5, 5, 39, 144, SURFACE_MAX - 1); DrawSprite(SCREEN_XSIZE * 276 / 420, (SCREEN_YSIZE - 52) * 109 / 238, 5, 5, 27, 144, SURFACE_MAX - 1); DrawSprite(SCREEN_XSIZE * 214 / 420, (SCREEN_YSIZE - 52) * 132 / 238, 5, 5, 15, 144, SURFACE_MAX - 1); break; case 11: DrawSprite(SCREEN_XSIZE * 276 / 420, (SCREEN_YSIZE - 52) * 109 / 238, 5, 5, 33, 144, SURFACE_MAX - 1); DrawSprite(SCREEN_XSIZE * 214 / 420, (SCREEN_YSIZE - 52) * 132 / 238, 5, 5, 21, 144, SURFACE_MAX - 1); break; } */ //Title DrawSprite((SCREEN_XSIZE / 2 - 52), 10, 104, 18, 15, 1, SURFACE_MAX - 1); //Selection Bar for (int i = 10; i < SCREEN_XSIZE; i += 100) { DrawSprite(i, 40 + ((gameMenu[1].selection1 - gameMenu[1].visibleRowOffset) * 8), 110, 8, 15, 128, SURFACE_MAX - 1); } SetActivePalette(0, 0, SCREEN_YSIZE); //Here to move the text placement //Main Mod Menu DrawTextMenu(&gameMenu[1], 20, 40); DrawTextMenu(&gameMenu[2], SCREEN_XSIZE - 20, 40); SetActivePalette(7, 0, SCREEN_YSIZE); //Draw here //Bottom Segment drawtemp = 0; while (drawtemp < SCREEN_XSIZE) { DrawSprite(drawtemp, SCREEN_YSIZE - 52, 12, 52, 15, 75, SURFACE_MAX - 1); drawtemp += 12; } DrawSprite(SCREEN_XSIZE - 122, SCREEN_YSIZE - 52, 122, 52, 313, 75, SURFACE_MAX - 1); //Bottom Info DrawTextMenu(&gameMenu[0], 20, SCREEN_YSIZE - 41); SetActivePalette(0, 0, SCREEN_YSIZE); //Fade } #endif default: break; } if (Engine.gameMode == ENGINE_STARTMENU) { #if defined RETRO_USING_MOUSE || defined RETRO_USING_TOUCH DrawSprite(32, 0x42, 16, 16, 78, 240, textMenuSurfaceNo); DrawSprite(32, 0xB2, 16, 16, 95, 240, textMenuSurfaceNo); DrawSprite(SCREEN_XSIZE - 32, SCREEN_YSIZE - 32, 16, 16, 112, 240, textMenuSurfaceNo); #endif } }
42.856433
142
0.477755
0xR00KIE
d50809e6bcf52f8c53d2fd99967721e2c360c391
1,701
cpp
C++
src/Packets/Tag2/Sub31.cpp
httese/OpenPGP
7dce08dc8b72eeb0dcbf3df56d64606a6b957938
[ "MIT" ]
99
2015-01-06T01:53:26.000Z
2022-01-31T18:18:27.000Z
src/Packets/Tag2/Sub31.cpp
httese/OpenPGP
7dce08dc8b72eeb0dcbf3df56d64606a6b957938
[ "MIT" ]
27
2015-03-09T05:46:53.000Z
2020-05-06T02:52:18.000Z
src/Packets/Tag2/Sub31.cpp
httese/OpenPGP
7dce08dc8b72eeb0dcbf3df56d64606a6b957938
[ "MIT" ]
42
2015-03-18T03:44:43.000Z
2022-03-31T21:34:06.000Z
#include "Packets/Tag2/Sub31.h" namespace OpenPGP { namespace Subpacket { namespace Tag2 { void Sub31::actual_read(const std::string & data) { if (data.size() > 2) { set_pka(data[0]); set_hash_alg(data[1]); set_hash(data.substr(2, data.size() - 2)); } } void Sub31::show_contents(HumanReadable & hr) const { hr << "Public Key Algorithm: " + get_mapped(PKA::NAME, pka) + " (pka " + std::to_string(pka) + ")" << "Hash Algorithm: " + get_mapped(Hash::NAME, hash_alg) + " (hash " + std::to_string(hash_alg) + ")" << "Hash: " + hexlify(hash); } Status Sub31::actual_valid(const bool) const { if (PKA::NAME.find(pka) == PKA::NAME.end()) { return Status::INVALID_PUBLIC_KEY_ALGORITHM; } if (Hash::NAME.find(hash_alg) == Hash::NAME.end()) { return Status::INVALID_HASH_ALGORITHM; } if ((Hash::LENGTH.at(hash_alg) >> 3) != hash.size()) { return Status::INVALID_LENGTH; } return Status::SUCCESS; } Sub31::Sub31() : Sub(SIGNATURE_TARGET), pka(), hash_alg(), hash() {} Sub31::Sub31(const std::string & data) : Sub31() { read(data); } std::string Sub31::raw() const { return std::string(1, pka) + std::string(1, hash_alg) + hash; } uint8_t Sub31::get_pka() const { return pka; } uint8_t Sub31::get_hash_alg() const { return hash_alg; } std::string Sub31::get_hash() const { return hash; } void Sub31::set_pka(const uint8_t p) { pka = p; } void Sub31::set_hash_alg(const uint8_t h) { hash_alg = h; } void Sub31::set_hash(const std::string & h) { hash = h; } Sub::Ptr Sub31::clone() const { return std::make_shared <Sub31> (*this); } } } }
20.25
108
0.602587
httese
d5084eaba58ac4442ce9ac4e99489c8759287278
1,399
cpp
C++
src/snail/backends/sdl/window.cpp
Vorlent/ElonaFoobar
8e544af1f82377c9add6961589ddc99e22c5ed4c
[ "MIT" ]
84
2018-03-03T02:44:32.000Z
2019-07-14T16:16:24.000Z
src/snail/backends/sdl/window.cpp
Vorlent/ElonaFoobar
8e544af1f82377c9add6961589ddc99e22c5ed4c
[ "MIT" ]
685
2018-02-27T04:31:17.000Z
2019-07-12T13:43:00.000Z
src/snail/backends/sdl/window.cpp
nanbansenji/ElonaFoobar
ddbd6639db8698e89f09b2512526e855d8016e46
[ "MIT" ]
23
2019-07-26T08:52:38.000Z
2021-11-09T09:21:58.000Z
#include "../../window.hpp" namespace elona { namespace snail { void Window::move_to_center() { ::SDL_SetWindowPosition( ptr(), static_cast<int>(InitialPosition::centered), static_cast<int>(InitialPosition::centered)); } std::pair<int, int> Window::get_size() { int width, height; ::SDL_GetWindowSize(ptr(), &width, &height); return {width, height}; } void Window::set_size(int width, int height) { ::SDL_SetWindowSize(ptr(), width, height); } void Window::set_display_mode(::SDL_DisplayMode display_mode) { detail::enforce_sdl(::SDL_SetWindowDisplayMode(ptr(), &display_mode)); } ::SDL_DisplayMode Window::get_display_mode() { ::SDL_DisplayMode mode; detail::enforce_sdl(::SDL_GetWindowDisplayMode(ptr(), &mode)); return mode; } void Window::set_fullscreen_mode(FullscreenMode fullscreen_mode) { detail::enforce_sdl( ::SDL_SetWindowFullscreen(ptr(), static_cast<Uint32>(fullscreen_mode))); } Window::Window( const std::string& title, int x, int y, int width, int height, Flag flag) : _ptr( detail::enforce_sdl(::SDL_CreateWindow( title.c_str(), x, y, width, height, static_cast<SDL_WindowFlags>(flag))), ::SDL_DestroyWindow) { } } // namespace snail } // namespace elona
17.271605
80
0.626162
Vorlent
d508a9c5409c43b6064e84aa6792458e01eb50b9
12,532
cpp
C++
share/game/game_object.cpp
Ananfa/wukong
60abff35192d5182bb6ab560a5efc9d884549c6a
[ "Apache-2.0" ]
4
2022-02-22T07:58:40.000Z
2022-02-22T09:25:12.000Z
share/game/game_object.cpp
Ananfa/wukong
60abff35192d5182bb6ab560a5efc9d884549c6a
[ "Apache-2.0" ]
null
null
null
share/game/game_object.cpp
Ananfa/wukong
60abff35192d5182bb6ab560a5efc9d884549c6a
[ "Apache-2.0" ]
null
null
null
/* * Created by Xianke Liu on 2021/1/19. * * 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 "corpc_routine_env.h" #include "game_object.h" #include "game_center.h" #include "game_object_manager.h" #include "gateway_client.h" #include "record_client.h" #include "share/const.h" #include <sys/time.h> using namespace wukong; static void callDoneHandle(::google::protobuf::Message *request, Controller *controller) { delete controller; delete request; } GameObject::~GameObject() {} bool GameObject::setGatewayServerStub(ServerId sid) { if (!_gatewayServerStub || _gatewayId != sid) { _gatewayId = sid; _gatewayServerStub = g_GatewayClient.getStub(sid); } if (!_gatewayServerStub) { ERROR_LOG("GameObject::setGatewayServerStub -- user %d gateway server[sid: %d] not found\n", _userId, sid); return false; } return true; } bool GameObject::setRecordServerStub(ServerId sid) { if (!_recordServerStub || _recordId != sid) { _recordId = sid; _recordServerStub = g_RecordClient.getStub(sid); } if (!_recordServerStub) { ERROR_LOG("GameObject::setRecordServerStub -- user %d record server[sid: %d] not found\n", _userId, sid); return false; } return true; } void GameObject::start() { _running = true; { GameObjectRoutineArg *arg = new GameObjectRoutineArg(); arg->obj = shared_from_this(); RoutineEnvironment::startCoroutine(heartbeatRoutine, arg); } // 启动定期存盘协程(每隔一段时间将脏数据同步给记录服,协程中退出循环时也会执行一次) { GameObjectRoutineArg *arg = new GameObjectRoutineArg(); arg->obj = shared_from_this(); RoutineEnvironment::startCoroutine(syncRoutine, arg); } // 根据配置启动周期处理协程(执行周期更新逻辑) if (g_GameCenter.getGameObjectUpdatePeriod() > 0) { GameObjectRoutineArg *arg = new GameObjectRoutineArg(); arg->obj = shared_from_this(); RoutineEnvironment::startCoroutine(updateRoutine, arg); } } void GameObject::stop() { if (_running) { _running = false; _cond.broadcast(); // TODO: 在这里直接进行redis操作会有协程切换,导致一些流程同步问题,需要考虑一下是否需要换地方调用 redisContext *cache = g_GameCenter.getCachePool()->proxy.take(); if (!cache) { ERROR_LOG("GameObject::stop -- role[%d] connect to cache failed\n", _roleId); return; } // 删除record标签 redisReply *reply; if (g_GameCenter.removeLocationSha1().empty()) { reply = (redisReply *)redisCommand(cache, "EVAL %s 1 Location:%d %d", REMOVE_RECORD_CMD, _roleId, _lToken); } else { reply = (redisReply *)redisCommand(cache, "EVALSHA %s 1 Location:%d %d", g_GameCenter.removeLocationSha1().c_str(), _roleId, _lToken); } if (!reply) { g_GameCenter.getCachePool()->proxy.put(cache, true); ERROR_LOG("GameObject::stop -- role[%d] remove location failed", _roleId); return; } freeReplyObject(reply); g_GameCenter.getCachePool()->proxy.put(cache, false); } } void GameObject::send(int32_t type, uint16_t tag, const std::string &msg) { if (!_gatewayServerStub) { ERROR_LOG("GameObject::send -- gateway stub not set\n"); return; } pb::ForwardOutRequest *request = new pb::ForwardOutRequest(); Controller *controller = new Controller(); request->set_type(type); request->set_tag(tag); ::wukong::pb::ForwardOutTarget* target = request->add_targets(); target->set_userid(_userId); target->set_ltoken(_lToken); if (!msg.empty()) { request->set_rawmsg(msg); } _gatewayServerStub->forwardOut(controller, request, nullptr, google::protobuf::NewCallback<::google::protobuf::Message *>(&callDoneHandle, request, controller)); } void GameObject::send(int32_t type, uint16_t tag, google::protobuf::Message &msg) { if (!_gatewayServerStub) { ERROR_LOG("GameObject::send -- gateway stub not set\n"); return; } std::string bufStr(msg.ByteSizeLong(), 0); uint8_t *buf = (uint8_t *)bufStr.data(); msg.SerializeWithCachedSizesToArray(buf); send(type, tag, bufStr); } bool GameObject::reportGameObjectPos() { if (!_gatewayServerStub) { ERROR_LOG("GameObject::setGameObjectPos -- gateway stub not set\n"); return false; } pb::SetGameObjectPosRequest *request = new pb::SetGameObjectPosRequest(); pb::BoolValue *response = new pb::BoolValue(); Controller *controller = new Controller(); request->set_userid(_userId); request->set_ltoken(_lToken); request->set_servertype(g_GameCenter.getType()); request->set_serverid(_manager->getId()); _gatewayServerStub->setGameObjectPos(controller, request, response, nullptr); bool ret; if (controller->Failed()) { ERROR_LOG("Rpc Call Failed : %s\n", controller->ErrorText().c_str()); ret = false; } else { ret = response->value(); } delete controller; delete response; delete request; return ret; } bool GameObject::heartbeatToGateway() { if (!_gatewayServerStub) { ERROR_LOG("GameObject::heartbeatToGateway -- gateway stub not set\n"); return false; } pb::GSHeartbeatRequest *request = new pb::GSHeartbeatRequest(); pb::BoolValue *response = new pb::BoolValue(); Controller *controller = new Controller(); request->set_userid(_userId); request->set_ltoken(_lToken); _gatewayServerStub->heartbeat(controller, request, response, nullptr); bool ret; if (controller->Failed()) { ERROR_LOG("Rpc Call Failed : %s\n", controller->ErrorText().c_str()); ret = false; } else { ret = response->value(); } delete controller; delete response; delete request; return ret; } bool GameObject::sync(std::list<std::pair<std::string, std::string>> &datas, std::list<std::string> &removes) { if (!_recordServerStub) { ERROR_LOG("GameObject::sync -- record stub not set\n"); return false; } pb::SyncRequest *request = new pb::SyncRequest(); pb::BoolValue *response = new pb::BoolValue(); Controller *controller = new Controller(); request->set_ltoken(_lToken); request->set_roleid(_roleId); for (auto &d : datas) { auto data = request->add_datas(); data->set_key(d.first); data->set_value(d.second); } for (auto &r : removes) { request->add_removes(r); } _recordServerStub->sync(controller, request, response, nullptr); bool result = false; if (controller->Failed()) { ERROR_LOG("Rpc Call Failed : %s\n", controller->ErrorText().c_str()); } else { result = response->value(); } delete controller; delete response; delete request; return result; } bool GameObject::heartbeatToRecord() { if (!_recordServerStub) { ERROR_LOG("GameObject::heartbeatToRecord -- record stub not set\n"); return false; } pb::RSHeartbeatRequest *request = new pb::RSHeartbeatRequest(); pb::BoolValue *response = new pb::BoolValue(); Controller *controller = new Controller(); request->set_roleid(_roleId); request->set_ltoken(_lToken); _recordServerStub->heartbeat(controller, request, response, nullptr); bool ret; if (controller->Failed()) { ERROR_LOG("Rpc Call Failed : %s\n", controller->ErrorText().c_str()); ret = false; } else { ret = response->value(); } delete controller; delete response; delete request; return ret; } void *GameObject::heartbeatRoutine( void *arg ) { GameObjectRoutineArg* routineArg = (GameObjectRoutineArg*)arg; std::shared_ptr<GameObject> obj = std::move(routineArg->obj); delete routineArg; //int gwHeartbeatFailCount = 0; while (obj->_running) { // 目前只有心跳和停服会销毁游戏对象 obj->_cond.wait(TOKEN_HEARTBEAT_PERIOD); if (!obj->_running) { // 游戏对象已被销毁 break; } // 设置session超时 bool success = true; redisContext *cache = g_GameCenter.getCachePool()->proxy.take(); if (!cache) { ERROR_LOG("GameObject::heartbeatRoutine -- user %d role %d connect to cache failed\n", obj->_userId, obj->_roleId); success = false; } else { redisReply *reply; if (g_GameCenter.setLocationExpireSha1().empty()) { reply = (redisReply *)redisCommand(cache, "EVAL %s 1 Location:%d %d %d", SET_LOCATION_EXPIRE_CMD, obj->_roleId, obj->_lToken, TOKEN_TIMEOUT); } else { reply = (redisReply *)redisCommand(cache, "EVALSHA %s 1 Location:%d %d %d", g_GameCenter.setLocationExpireSha1().c_str(), obj->_roleId, obj->_lToken, TOKEN_TIMEOUT); } if (!reply) { g_GameCenter.getCachePool()->proxy.put(cache, true); ERROR_LOG("GameObject::heartbeatRoutine -- user %d role %d check session failed for db error\n", obj->_userId, obj->_roleId); success = false; } else { success = reply->integer == 1; freeReplyObject(reply); g_GameCenter.getCachePool()->proxy.put(cache, false); if (!success) { ERROR_LOG("GameObject::heartbeatRoutine -- user %d role %d check session failed\n", obj->_userId, obj->_roleId); } } } if (success) { // 对网关对象进行心跳 // 三次心跳不到gateway对象才销毁 if (!obj->heartbeatToGateway()) { obj->_gwHeartbeatFailCount++; if (obj->_gwHeartbeatFailCount >= 3) { WARN_LOG("GameObject::heartbeatRoutine -- user %d role %d heartbeat to gw failed\n", obj->_userId, obj->_roleId); success = false; } } else { obj->_gwHeartbeatFailCount = 0; } } if (success) { // 对记录对象进行心跳 success = obj->heartbeatToRecord(); if (!success) { WARN_LOG("GameObject::heartbeatRoutine -- user %d role %d heartbeat to record failed\n", obj->_userId, obj->_roleId); } } // 若设置超时不成功,销毁游戏对象 if (!success) { //exit(0); if (obj->_running) { if (!obj->_manager->remove(obj->_roleId)) { assert(false); ERROR_LOG("GameObject::heartbeatRoutine -- user %d role %d remove game object failed\n", obj->_userId, obj->_roleId); } obj->_running = false; } } } return nullptr; } void *GameObject::syncRoutine(void *arg) { GameObjectRoutineArg* routineArg = (GameObjectRoutineArg*)arg; std::shared_ptr<GameObject> obj = std::move(routineArg->obj); delete routineArg; std::list<std::pair<std::string, std::string>> syncDatas; std::list<std::string> removes; while (obj->_running) { obj->_cond.wait(SYNC_PERIOD); if (!obj->_running) { break; } // 向记录服同步数据(销毁前也应该将脏数据同步给记录服) obj->buildSyncDatas(syncDatas, removes); if (!syncDatas.empty() || !removes.empty()) { obj->sync(syncDatas, removes); syncDatas.clear(); removes.clear(); } } return nullptr; } void *GameObject::updateRoutine(void *arg) { GameObjectRoutineArg* routineArg = (GameObjectRoutineArg*)arg; std::shared_ptr<GameObject> obj = std::move(routineArg->obj); delete routineArg; struct timeval t; while (obj->_running) { obj->_cond.wait(g_GameCenter.getGameObjectUpdatePeriod()); if (!obj->_running) { // 游戏对象已被销毁 break; } gettimeofday(&t, NULL); obj->update(t.tv_sec); } return nullptr; }
30.19759
181
0.610517
Ananfa
d509cb541b1cd9ae5a633dbd2fcdf515949aaa7f
3,833
cpp
C++
exampleMultipleGraphicCards/src/testApp.cpp
gameoverhack/ofxFenster
4ba27757d2b1ded68813a06374de55a0332f003e
[ "MIT" ]
1
2020-12-18T00:31:38.000Z
2020-12-18T00:31:38.000Z
exampleMultipleGraphicCards/src/testApp.cpp
gameoverhack/ofxFenster
4ba27757d2b1ded68813a06374de55a0332f003e
[ "MIT" ]
null
null
null
exampleMultipleGraphicCards/src/testApp.cpp
gameoverhack/ofxFenster
4ba27757d2b1ded68813a06374de55a0332f003e
[ "MIT" ]
null
null
null
#include "testApp.h" //-------------------------------------------------------------- void testApp::setup() { ofSetFrameRate(60); ofBackground(0,0,0); //currently this only works on linux ofxDisplayList displays = ofxDisplayManager::get()->getDisplays(); cout << "NUMBER OF DISPLAYS FOUND " << displays.size()<< endl; ofxDisplay* display = displays[0]; if(displays.size()>1) display = displays[1]; ofxFensterManager::get()->setActiveDisplay(display); mousePos[ofxFensterManager::get()->getPrimaryWindow()->id]=ofVec2f(0,0); //when you don't have multiple cards connected, display->width can be a problem on ubuntu (all of linux?). I think it's because the menu and things need space too ofxFenster* win=ofxFensterManager::get()->createFenster(0, 0, display->width, display->height, OF_WINDOW); win->addListener(this); win->setBackgroundColor(ofRandom(255), ofRandom(255), ofRandom(255)); mousePos[win->id]=ofVec2f(0,0); if(displays.size()>2) display = displays[2]; ofxFensterManager::get()->setActiveDisplay(display); ofxFenster* win2=ofxFensterManager::get()->createFenster(0, 0, display->width, display->height, OF_WINDOW); ofAddListener(win2->events.mouseMoved, this, &testApp::mouseMovedEvent); win2->addListener(&imgWin); imgWin.setup(); ofImage icon; icon.loadImage("icon.png"); ofxFensterManager::get()->setIcon(icon.getPixelsRef()); } //-------------------------------------------------------------- void testApp::update() { if(ofGetFrameNum()%90 == 0) { iconCount++; iconCount = iconCount%4; ofImage icon; icon.loadImage("icon"+ofToString(iconCount)+".png"); //this only works partially in ubuntu 11.04 ofxFensterManager::get()->setIcon(icon.getPixelsRef()); } } //-------------------------------------------------------------- void testApp::draw() { ofNoFill(); ofSetRectMode(OF_RECTMODE_CENTER); ofSetColor(255); ofCircle(mouseX, mouseY, 10); ofSetRectMode(OF_RECTMODE_CORNER); ofFill(); ofSetColor(255); ofVec2f mp=mousePos[ofxFensterManager::get()->getActiveWindow()->id]; ofVec2f p; float dSquared=100*100; for(int x=0; x<ofGetWidth(); x+=40) { for(int y=0; y<ofGetHeight(); y+=40) { p.set(x, y); if(mp.distanceSquared(p)<dSquared) { ofRect(x+10, y+10, 20, 20); } } } ofSetColor(0); ofDrawBitmapString(ofToString(ofGetFrameRate()),20,20); } //-------------------------------------------------------------- void testApp::keyPressed(int key, ofxFenster* win) { } //-------------------------------------------------------------- void testApp::keyReleased(int key, ofxFenster* win) { //cout << (0x0400) << endl; //cout << (101 | OF_KEY_MODIFIER) << " " << key << endl; if(key=='f') win->toggleFullscreen(); if(key==' ') ofxFensterManager::get()->createFenster(0, 0, 400, 300, OF_WINDOW)->addListener(&imgWin); } void testApp::mouseMoved(int x, int y, ofxFenster* win) { mousePos[win->id].set(x, y); } //-------------------------------------------------------------- void testApp::mouseMoved(int x, int y ) { } //-------------------------------------------------------------- void testApp::mouseDragged(int x, int y, int button) { } //-------------------------------------------------------------- void testApp::mousePressed(int x, int y, int button) { } //-------------------------------------------------------------- void testApp::mouseReleased(int x, int y, int button) { } //-------------------------------------------------------------- void testApp::windowResized(int w, int h) { } //-------------------------------------------------------------- void testApp::gotMessage(ofMessage msg) { } //-------------------------------------------------------------- void testApp::dragEvent(ofDragInfo dragInfo) { } void testApp::mouseMovedEvent(ofMouseEventArgs &args) { //cout << "MOUSE WAS MOVED" << endl; }
27.978102
163
0.554396
gameoverhack
d509cde779606e95cd270eac567405a819025d04
26,007
cxx
C++
test/test_integration_crud.cxx
brett19/couchbase-cxx-client
0992b6f693366bb0481d3ebaed4f57bc8ef11882
[ "Apache-2.0" ]
null
null
null
test/test_integration_crud.cxx
brett19/couchbase-cxx-client
0992b6f693366bb0481d3ebaed4f57bc8ef11882
[ "Apache-2.0" ]
null
null
null
test/test_integration_crud.cxx
brett19/couchbase-cxx-client
0992b6f693366bb0481d3ebaed4f57bc8ef11882
[ "Apache-2.0" ]
null
null
null
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2020-2021 Couchbase, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "test_helper_integration.hxx" #include "utils/move_only_context.hxx" static const tao::json::value basic_doc = { { "a", 1.0 }, { "b", 2.0 }, }; static const std::string basic_doc_json = couchbase::utils::json::generate(basic_doc); TEST_CASE("integration: crud on default collection", "[integration]") { test::utils::integration_test_guard integration; test::utils::open_bucket(integration.cluster, integration.ctx.bucket); couchbase::document_id id{ integration.ctx.bucket, "_default", "_default", test::utils::uniq_id("foo") }; // create { couchbase::operations::insert_request req{ id, basic_doc_json }; auto resp = test::utils::execute(integration.cluster, req); INFO(resp.ctx.ec.message()) REQUIRE_FALSE(resp.ctx.ec); REQUIRE(!resp.cas.empty()); INFO("seqno=" << resp.token.sequence_number) REQUIRE(resp.token.sequence_number != 0); } // read { couchbase::operations::get_request req{ id }; auto resp = test::utils::execute(integration.cluster, req); REQUIRE(resp.value == basic_doc_json); } // update { auto doc = basic_doc; auto json = couchbase::utils::json::generate(doc); doc["a"] = 2.0; { couchbase::operations::replace_request req{ id, json }; auto resp = test::utils::execute(integration.cluster, req); REQUIRE_FALSE(resp.ctx.ec); } { couchbase::operations::get_request req{ id }; auto resp = test::utils::execute(integration.cluster, req); REQUIRE(resp.value == json); } { couchbase::operations::upsert_request req{ id, basic_doc_json }; auto resp = test::utils::execute(integration.cluster, req); REQUIRE_FALSE(resp.ctx.ec); } { couchbase::operations::get_request req{ id }; auto resp = test::utils::execute(integration.cluster, req); REQUIRE(resp.value == basic_doc_json); } } // delete { { couchbase::operations::remove_request req{ id }; auto resp = test::utils::execute(integration.cluster, req); REQUIRE_FALSE(resp.ctx.ec); } { couchbase::operations::get_request req{ id }; auto resp = test::utils::execute(integration.cluster, req); REQUIRE(resp.ctx.ec == couchbase::error::key_value_errc::document_not_found); } } } TEST_CASE("integration: get", "[integration]") { test::utils::integration_test_guard integration; test::utils::open_bucket(integration.cluster, integration.ctx.bucket); couchbase::document_id id{ integration.ctx.bucket, "_default", "_default", test::utils::uniq_id("get") }; SECTION("miss") { couchbase::operations::get_request req{ id }; auto resp = test::utils::execute(integration.cluster, req); INFO(resp.ctx.ec.message()); REQUIRE(resp.ctx.ec == couchbase::error::key_value_errc::document_not_found); } SECTION("hit") { auto flags = 0xdeadbeef; { couchbase::operations::insert_request req{ id, basic_doc_json }; req.flags = flags; auto resp = test::utils::execute(integration.cluster, req); REQUIRE_FALSE(resp.ctx.ec); } { couchbase::operations::get_request req{ id }; auto resp = test::utils::execute(integration.cluster, req); REQUIRE_FALSE(resp.ctx.ec); REQUIRE(resp.value == basic_doc_json); REQUIRE(resp.flags == flags); } } } TEST_CASE("integration: touch", "[integration]") { test::utils::integration_test_guard integration; test::utils::open_bucket(integration.cluster, integration.ctx.bucket); couchbase::document_id id{ integration.ctx.bucket, "_default", "_default", test::utils::uniq_id("touch") }; SECTION("miss") { couchbase::operations::touch_request req{ id }; req.expiry = 666; auto resp = test::utils::execute(integration.cluster, req); REQUIRE(resp.ctx.ec == couchbase::error::key_value_errc::document_not_found); } SECTION("hit") { { couchbase::operations::insert_request req{ id, basic_doc_json }; auto resp = test::utils::execute(integration.cluster, req); REQUIRE_FALSE(resp.ctx.ec); } { couchbase::operations::touch_request req{ id }; req.expiry = 666; auto resp = test::utils::execute(integration.cluster, req); REQUIRE_FALSE(resp.ctx.ec); } } } TEST_CASE("integration: pessimistic locking", "[integration]") { test::utils::integration_test_guard integration; test::utils::open_bucket(integration.cluster, integration.ctx.bucket); couchbase::document_id id{ integration.ctx.bucket, "_default", "_default", test::utils::uniq_id("locking") }; uint32_t lock_time = 10; couchbase::protocol::cas cas; { couchbase::operations::insert_request req{ id, basic_doc_json }; auto resp = test::utils::execute(integration.cluster, req); REQUIRE_FALSE(resp.ctx.ec); cas = resp.cas; } // lock and record CAS of the locked document { couchbase::operations::get_and_lock_request req{ id }; req.lock_time = lock_time; auto resp = test::utils::execute(integration.cluster, req); REQUIRE_FALSE(resp.ctx.ec); REQUIRE(cas != resp.cas); cas = resp.cas; } // real CAS is masked now and not visible by regular GET { couchbase::operations::get_request req{ id }; auto resp = test::utils::execute(integration.cluster, req); REQUIRE_FALSE(resp.ctx.ec); REQUIRE(cas != resp.cas); } // it is not allowed to lock the same key twice { couchbase::operations::get_and_lock_request req{ id }; req.lock_time = lock_time; auto resp = test::utils::execute(integration.cluster, req); REQUIRE(resp.ctx.ec == couchbase::error::common_errc::ambiguous_timeout); REQUIRE(resp.ctx.retry_reasons.count(couchbase::io::retry_reason::kv_locked) == 1); } // but unlock operation is not retried in this case, because it would never have succeeded { couchbase::operations::unlock_request req{ id }; req.cas = couchbase::protocol::cas{ cas.value - 1 }; auto resp = test::utils::execute(integration.cluster, req); REQUIRE(resp.ctx.ec == couchbase::error::key_value_errc::document_locked); REQUIRE(resp.ctx.retry_reasons.count(couchbase::io::retry_reason::kv_locked) == 0); } // but mutating the locked key is allowed with known cas { couchbase::operations::replace_request req{ id, basic_doc_json }; req.cas = cas; auto resp = test::utils::execute(integration.cluster, req); REQUIRE_FALSE(resp.ctx.ec); } { couchbase::operations::get_and_lock_request req{ id }; req.lock_time = lock_time; auto resp = test::utils::execute(integration.cluster, req); REQUIRE_FALSE(resp.ctx.ec); cas = resp.cas; } // to unlock key without mutation, unlock might be used { couchbase::operations::unlock_request req{ id }; req.cas = cas; auto resp = test::utils::execute(integration.cluster, req); REQUIRE_FALSE(resp.ctx.ec); } // now the key is not locked { couchbase::operations::upsert_request req{ id, basic_doc_json }; auto resp = test::utils::execute(integration.cluster, req); REQUIRE_FALSE(resp.ctx.ec); } } TEST_CASE("integration: lock/unlock without lock time", "[integration]") { test::utils::integration_test_guard integration; test::utils::open_bucket(integration.cluster, integration.ctx.bucket); couchbase::document_id id{ integration.ctx.bucket, "_default", "_default", test::utils::uniq_id("locking") }; { couchbase::operations::insert_request req{ id, basic_doc_json }; auto resp = test::utils::execute(integration.cluster, req); REQUIRE_FALSE(resp.ctx.ec); } couchbase::protocol::cas cas; { couchbase::operations::get_and_lock_request req{ id }; auto resp = test::utils::execute(integration.cluster, req); REQUIRE_FALSE(resp.ctx.ec); cas = resp.cas; } { couchbase::operations::unlock_request req{ id }; req.cas = cas; auto resp = test::utils::execute(integration.cluster, req); REQUIRE_FALSE(resp.ctx.ec); } } TEST_CASE("integration: touch with zero expiry resets expiry", "[integration]") { test::utils::integration_test_guard integration; test::utils::open_bucket(integration.cluster, integration.ctx.bucket); couchbase::document_id id{ integration.ctx.bucket, "_default", "_default", test::utils::uniq_id("get_reset_expiry_key") }; { couchbase::operations::insert_request req{ id, basic_doc_json }; auto resp = test::utils::execute(integration.cluster, req); REQUIRE_FALSE(resp.ctx.ec); } // set expiry with touch { couchbase::operations::touch_request req{ id }; req.expiry = 1; auto resp = test::utils::execute(integration.cluster, req); REQUIRE_FALSE(resp.ctx.ec); } // reset expiry { couchbase::operations::get_and_touch_request req{ id }; req.expiry = 0; auto resp = test::utils::execute(integration.cluster, req); REQUIRE_FALSE(resp.ctx.ec); } // wait for original expiry to pass std::this_thread::sleep_for(std::chrono::seconds(2)); // check that the key still exists { couchbase::operations::get_request req{ id }; auto resp = test::utils::execute(integration.cluster, req); REQUIRE_FALSE(resp.ctx.ec); REQUIRE(resp.value == basic_doc_json); } } TEST_CASE("integration: exists", "[integration]") { test::utils::integration_test_guard integration; test::utils::open_bucket(integration.cluster, integration.ctx.bucket); couchbase::document_id id{ integration.ctx.bucket, "_default", "_default", test::utils::uniq_id("exists") }; { couchbase::operations::exists_request req{ id }; auto resp = test::utils::execute(integration.cluster, req); REQUIRE_FALSE(resp.exists()); REQUIRE(resp.ctx.ec == couchbase::error::key_value_errc::document_not_found); REQUIRE_FALSE(resp.deleted); REQUIRE(resp.cas.empty()); REQUIRE(resp.sequence_number == 0); } { couchbase::operations::insert_request req{ id, basic_doc_json }; req.expiry = 1878422400; auto resp = test::utils::execute(integration.cluster, req); REQUIRE_FALSE(resp.ctx.ec); REQUIRE_FALSE(resp.cas.empty()); } { couchbase::operations::exists_request req{ id }; auto resp = test::utils::execute(integration.cluster, req); REQUIRE(resp.exists()); REQUIRE_FALSE(resp.ctx.ec); REQUIRE_FALSE(resp.deleted); REQUIRE_FALSE(resp.cas.empty()); REQUIRE(resp.sequence_number != 0); REQUIRE(resp.expiry == 1878422400); } { couchbase::operations::remove_request req{ id }; auto resp = test::utils::execute(integration.cluster, req); REQUIRE_FALSE(resp.ctx.ec); } { couchbase::operations::exists_request req{ id }; auto resp = test::utils::execute(integration.cluster, req); REQUIRE_FALSE(resp.exists()); REQUIRE_FALSE(resp.ctx.ec); REQUIRE(resp.deleted); REQUIRE_FALSE(resp.cas.empty()); REQUIRE(resp.sequence_number != 0); REQUIRE(resp.expiry != 0); } } TEST_CASE("integration: zero length value", "[integration]") { test::utils::integration_test_guard integration; test::utils::open_bucket(integration.cluster, integration.ctx.bucket); couchbase::document_id id{ integration.ctx.bucket, "_default", "_default", test::utils::uniq_id("zero_length_value") }; { couchbase::operations::insert_request req{ id, "" }; auto resp = test::utils::execute(integration.cluster, req); REQUIRE_FALSE(resp.ctx.ec); } { couchbase::operations::get_request req{ id }; auto resp = test::utils::execute(integration.cluster, req); REQUIRE_FALSE(resp.ctx.ec); REQUIRE(resp.value == ""); } } TEST_CASE("integration: ops on missing document", "[integration]") { test::utils::integration_test_guard integration; test::utils::open_bucket(integration.cluster, integration.ctx.bucket); couchbase::document_id id{ integration.ctx.bucket, "_default", "_default", "missing_key" }; SECTION("get") { couchbase::operations::get_request req{ id }; auto resp = test::utils::execute(integration.cluster, req); REQUIRE(resp.ctx.ec == couchbase::error::key_value_errc::document_not_found); } SECTION("remove") { couchbase::operations::remove_request req{ id }; auto resp = test::utils::execute(integration.cluster, req); REQUIRE(resp.ctx.ec == couchbase::error::key_value_errc::document_not_found); } SECTION("replace") { couchbase::operations::replace_request req{ id, "" }; auto resp = test::utils::execute(integration.cluster, req); REQUIRE(resp.ctx.ec == couchbase::error::key_value_errc::document_not_found); } } TEST_CASE("integration: cas replace", "[integration]") { test::utils::integration_test_guard integration; test::utils::open_bucket(integration.cluster, integration.ctx.bucket); couchbase::document_id id{ integration.ctx.bucket, "_default", "_default", test::utils::uniq_id("cas_replace") }; couchbase::protocol::cas cas; { couchbase::operations::insert_request req{ id, basic_doc_json }; auto resp = test::utils::execute(integration.cluster, req); REQUIRE_FALSE(resp.ctx.ec); cas = resp.cas; } SECTION("incorrect") { couchbase::operations::replace_request req{ id, "" }; req.cas = couchbase::protocol::cas{ cas.value + 1 }; auto resp = test::utils::execute(integration.cluster, req); REQUIRE(resp.ctx.ec == couchbase::error::common_errc::cas_mismatch); } SECTION("correct") { couchbase::operations::replace_request req{ id, "" }; req.cas = cas; auto resp = test::utils::execute(integration.cluster, req); REQUIRE_FALSE(resp.ctx.ec); } } TEST_CASE("integration: upsert preserve expiry", "[integration]") { test::utils::integration_test_guard integration; if (!integration.cluster_version().supports_preserve_expiry()) { return; } test::utils::open_bucket(integration.cluster, integration.ctx.bucket); couchbase::document_id id{ integration.ctx.bucket, "_default", "_default", test::utils::uniq_id("preserve_expiry") }; uint32_t expiry = std::numeric_limits<uint32_t>::max(); auto expiry_path = "$document.exptime"; { couchbase::operations::upsert_request req{ id, basic_doc_json }; req.expiry = expiry; auto resp = test::utils::execute(integration.cluster, req); REQUIRE_FALSE(resp.ctx.ec); } { couchbase::operations::lookup_in_request req{ id }; req.specs.add_spec(couchbase::protocol::subdoc_opcode::get, true, expiry_path); auto resp = test::utils::execute(integration.cluster, req); REQUIRE(expiry == std::stoul(resp.fields[0].value)); } { couchbase::operations::upsert_request req{ id, basic_doc_json }; req.preserve_expiry = true; auto resp = test::utils::execute(integration.cluster, req); REQUIRE_FALSE(resp.ctx.ec); } { couchbase::operations::lookup_in_request req{ id }; req.specs.add_spec(couchbase::protocol::subdoc_opcode::get, true, expiry_path); auto resp = test::utils::execute(integration.cluster, req); REQUIRE(expiry == std::stoul(resp.fields[0].value)); } { couchbase::operations::upsert_request req{ id, basic_doc_json }; auto resp = test::utils::execute(integration.cluster, req); REQUIRE_FALSE(resp.ctx.ec); } { couchbase::operations::lookup_in_request req{ id }; req.specs.add_spec(couchbase::protocol::subdoc_opcode::get, true, expiry_path); auto resp = test::utils::execute(integration.cluster, req); REQUIRE(0 == std::stoul(resp.fields[0].value)); } } TEST_CASE("integration: upsert with handler capturing non-copyable object", "[integration]") { test::utils::integration_test_guard integration; test::utils::open_bucket(integration.cluster, integration.ctx.bucket); { couchbase::document_id id{ integration.ctx.bucket, "_default", "_default", test::utils::uniq_id("foo") }; couchbase::operations::upsert_request req{ id, R"({"foo":"bar"})" }; auto barrier = std::make_shared<std::promise<couchbase::operations::upsert_response>>(); auto f = barrier->get_future(); test::utils::move_only_context ctx("foobar"); auto handler = [barrier, ctx = std::move(ctx)](couchbase::operations::upsert_response&& resp) { CHECK(ctx.payload() == "foobar"); barrier->set_value(std::move(resp)); }; integration.cluster->execute(req, std::move(handler)); auto resp = f.get(); INFO(resp.ctx.ec.message()) REQUIRE_FALSE(resp.ctx.ec); } } TEST_CASE("integration: upsert may trigger snappy compression", "[integration]") { test::utils::integration_test_guard integration; test::utils::open_bucket(integration.cluster, integration.ctx.bucket); couchbase::document_id id{ integration.ctx.bucket, "_default", "_default", test::utils::uniq_id("foo") }; std::string compressible_json = R"( { "name": "Emmy-lou Dickerson", "age": 26, "animals": ["cat", "dog", "parrot"], "attributes": { "hair": "brown", "dimensions": { "height": 67, "weight": 175 }, "hobbies": [ { "type": "winter sports", "name": "curling" }, { "type": "summer sports", "name": "water skiing", "details": { "location": { "lat": 49.282730, "long": -123.120735 } } } ] } } )"; // create { couchbase::operations::insert_request req{ id, compressible_json }; auto resp = test::utils::execute(integration.cluster, req); INFO(resp.ctx.ec.message()) REQUIRE_FALSE(resp.ctx.ec); } // read { couchbase::operations::get_request req{ id }; auto resp = test::utils::execute(integration.cluster, req); REQUIRE(resp.value == compressible_json); } } TEST_CASE("integration: multi-threaded open/close bucket", "[integration]") { test::utils::integration_test_guard integration; constexpr auto number_of_threads{ 100 }; std::vector<std::thread> threads; threads.reserve(number_of_threads); for (auto i = 0; i < number_of_threads; ++i) { threads.emplace_back([&integration]() { test::utils::open_bucket(integration.cluster, integration.ctx.bucket); }); } std::for_each(threads.begin(), threads.end(), [](auto& thread) { thread.join(); }); threads.clear(); for (auto i = 0; i < number_of_threads; ++i) { threads.emplace_back([&integration]() { couchbase::document_id id{ integration.ctx.bucket, "_default", "_default", test::utils::uniq_id("foo") }; couchbase::operations::upsert_request req{ id, basic_doc_json }; req.timeout = std::chrono::seconds{ 10 }; if (auto resp = test::utils::execute(integration.cluster, req); resp.ctx.ec) { if (resp.ctx.ec != couchbase::error::common_errc::ambiguous_timeout) { throw std::system_error(resp.ctx.ec); } } }); } std::for_each(threads.begin(), threads.end(), [](auto& thread) { thread.join(); }); threads.clear(); for (auto i = 0; i < number_of_threads; ++i) { threads.emplace_back([&integration]() { test::utils::close_bucket(integration.cluster, integration.ctx.bucket); }); } std::for_each(threads.begin(), threads.end(), [](auto& thread) { thread.join(); }); } TEST_CASE("integration: open bucket that does not exist", "[integration]") { test::utils::integration_test_guard integration; auto bucket_name = test::utils::uniq_id("missing_bucket"); auto barrier = std::make_shared<std::promise<std::error_code>>(); auto f = barrier->get_future(); integration.cluster->open_bucket(bucket_name, [barrier](std::error_code ec) mutable { barrier->set_value(ec); }); auto rc = f.get(); REQUIRE(rc == couchbase::error::common_errc::bucket_not_found); } TEST_CASE("integration: upsert returns valid mutation token", "[integration]") { test::utils::integration_test_guard integration; test::utils::open_bucket(integration.cluster, integration.ctx.bucket); couchbase::document_id id{ integration.ctx.bucket, "_default", "_default", test::utils::uniq_id("upsert_mt") }; couchbase::mutation_token token{}; { couchbase::operations::upsert_request req{ id, basic_doc_json }; auto resp = test::utils::execute(integration.cluster, req); token = resp.token; REQUIRE_FALSE(resp.ctx.ec); REQUIRE(token.bucket_name == integration.ctx.bucket); REQUIRE(token.partition_uuid > 0); REQUIRE(token.sequence_number > 0); } { couchbase::operations::lookup_in_request req{ id }; req.specs.add_spec(couchbase::protocol::subdoc_opcode::get, true, "$document.vbucket_uuid"); req.specs.add_spec(couchbase::protocol::subdoc_opcode::get, true, "$document.seqno"); auto resp = test::utils::execute(integration.cluster, req); REQUIRE_FALSE(resp.ctx.ec); REQUIRE(resp.fields[0].value.find("\"0x") == 0); REQUIRE(std::strtoull(resp.fields[0].value.data() + 3, nullptr, 16) == token.partition_uuid); REQUIRE(resp.fields[1].value.find("\"0x") == 0); REQUIRE(std::strtoull(resp.fields[1].value.data() + 3, nullptr, 16) == token.sequence_number); } { couchbase::operations::insert_request req{ id, basic_doc_json }; auto resp = test::utils::execute(integration.cluster, req); REQUIRE(resp.ctx.ec == couchbase::error::key_value_errc::document_exists); REQUIRE(resp.token.bucket_name.empty()); REQUIRE(resp.token.partition_id == 0); REQUIRE(resp.token.partition_uuid == 0); REQUIRE(resp.token.sequence_number == 0); } { couchbase::operations::mutate_in_request req{ id }; req.specs.add_spec(couchbase::protocol::subdoc_opcode::dict_upsert, false, true, false, "foo", "42"); req.store_semantics = couchbase::protocol::mutate_in_request_body::store_semantics_type::insert; auto resp = test::utils::execute(integration.cluster, req); REQUIRE(resp.ctx.ec == couchbase::error::key_value_errc::document_exists); REQUIRE(resp.token.bucket_name.empty()); REQUIRE(resp.token.partition_id == 0); REQUIRE(resp.token.partition_uuid == 0); REQUIRE(resp.token.sequence_number == 0); } { couchbase::operations::mutate_in_request req{ id }; req.specs.add_spec(couchbase::protocol::subdoc_opcode::dict_add, false, false, false, "a", "{}"); req.store_semantics = couchbase::protocol::mutate_in_request_body::store_semantics_type::replace; auto resp = test::utils::execute(integration.cluster, req); REQUIRE(resp.ctx.ec == couchbase::error::key_value_errc::path_exists); REQUIRE(resp.token.bucket_name.empty()); REQUIRE(resp.token.partition_id == 0); REQUIRE(resp.token.partition_uuid == 0); REQUIRE(resp.token.sequence_number == 0); REQUIRE(resp.first_error_index == 0); REQUIRE(resp.fields.size() == 1); REQUIRE(resp.fields[0].path == "a"); REQUIRE(resp.fields[0].status == couchbase::protocol::status::subdoc_path_exists); } } TEST_CASE("integration: upsert is cancelled immediately if the cluster was closed", "[integration]") { test::utils::integration_test_guard integration; test::utils::open_bucket(integration.cluster, integration.ctx.bucket); couchbase::document_id id{ integration.ctx.bucket, "_default", "_default", test::utils::uniq_id("foo") }; { couchbase::operations::upsert_request req{ id, basic_doc_json }; auto resp = test::utils::execute(integration.cluster, req); REQUIRE_FALSE(resp.ctx.ec); } test::utils::close_cluster(integration.cluster); { couchbase::operations::upsert_request req{ id, basic_doc_json }; auto resp = test::utils::execute(integration.cluster, req); REQUIRE(resp.ctx.ec == couchbase::error::network_errc::cluster_closed); } }
35.77304
126
0.635906
brett19
d50acca6f2cae36177964a83112baa00571d7fb7
6,209
cpp
C++
bam_ordered_reader.cpp
Yichen-Si/vt-topmed
e22e964a68e236b190b3038318ca9799f1922e0e
[ "MIT" ]
null
null
null
bam_ordered_reader.cpp
Yichen-Si/vt-topmed
e22e964a68e236b190b3038318ca9799f1922e0e
[ "MIT" ]
1
2019-12-26T09:34:03.000Z
2019-12-26T09:34:03.000Z
bam_ordered_reader.cpp
Yichen-Si/vt-topmed
e22e964a68e236b190b3038318ca9799f1922e0e
[ "MIT" ]
1
2021-09-18T18:23:00.000Z
2021-09-18T18:23:00.000Z
/* The MIT License Copyright (c) 2013 Adrian Tan <atks@umich.edu> 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 "bam_ordered_reader.h" /** * Initialize files, intervals and reference file. * * @file_name name of the input VCF file * @intervals list of intervals, if empty, all records are selected. * @ref_fasta_file reference FASTA file for CRAM */ BAMOrderedReader::BAMOrderedReader(std::string file_name, std::vector<GenomeInterval>& intervals, std::string ref_fasta_file) { this->file_name = (file_name=="+")? "-" : file_name; file = NULL; hdr = NULL; idx = NULL; itr = NULL; this->intervals = intervals; interval_index = 0; index_loaded = false; file = hts_open(this->file_name.c_str(), "r"); if (!file) { /* // if file starts with gs:// if ( this->file_name.find("gs://") == 0 ) { // refresh the environment variable // allow retry for up to give times; for(int32_t i=0; i < 5; ++i) { std::string oauth_token = exec_cmd("gcloud auth application-default print-access-token"); //notice("Debug message: refreshed OAUTH TOKEN to %s", oauth_token.c_str()); if ( setenv("GCS_OAUTH_TOKEN",oauth_token.c_str(),1) != 0 ) { error("Failed to update the environment variable GCS_OAUTH_TOKEN to %s", oauth_token.c_str()); } notice("Successfully refreshed OAUTH TOKEN"); file = hts_open(this->file_name.c_str(), "r"); if ( file ) break; } } */ if ( !file) { fprintf(stderr, "[%s:%d %s] Cannot open %s\n", __FILE__, __LINE__, __FUNCTION__, file_name.c_str()); exit(1); } } ftype = file->format; if (ftype.format!=sam && ftype.format!=bam && ftype.format!=cram) { fprintf(stderr, "[%s:%d %s] Not a SAM/BAM/CRAM file: %s\n", __FILE__, __LINE__, __FUNCTION__, file_name.c_str()); exit(1); } if (ref_fasta_file!="") { char* fai = samfaipath(ref_fasta_file.c_str()); hts_set_fai_filename(file, fai); free(fai); } hdr = sam_hdr_read(file); if ( !hdr ) { fprintf(stderr,"Failed to read the header of the file %s",file_name.c_str()); exit(1); } s = bam_init1(); idx = sam_index_load(file, file_name.c_str()); if (idx) { index_loaded = true; } else { fprintf(stderr,"Cannot load index for file %s\n",file_name.c_str()); if (intervals.size()) exit(1); } str = {0,0,0}; intervals_present = intervals.size()!=0; interval_index = 0; random_access_enabled = intervals_present && index_loaded; }; /** * Jump to interval. Returns false if not successful. * * @interval - string representation of interval. */ bool BAMOrderedReader::jump_to_interval(GenomeInterval& interval) { if (index_loaded) { intervals_present = true; random_access_enabled = true; intervals.clear(); intervals.push_back(interval); interval_index = 0; intervals[interval_index++].to_string(&str); itr = sam_itr_querys(idx, hdr, str.s); if (itr) { return true; } } return false; }; /** * Initialize next interval. * Returns false only if all intervals are accessed. */ bool BAMOrderedReader::initialize_next_interval() { while (interval_index!=intervals.size()) { intervals[interval_index++].to_string(&str); itr = sam_itr_querys(idx, hdr, str.s); if (itr) { return true; } fprintf(stderr, "Warning: invalid interval %s for file: %s\n", str.s, file_name.c_str()); } return false; }; /** * Reads next record, hides the random access of different regions from the user. */ bool BAMOrderedReader::read(bam1_t *s) { int res = 0; if (random_access_enabled) { while(true) { if (itr && (res = sam_itr_next(file, itr, s))>=0) { return true; } else if (res < -1) { fprintf(stderr, "[%s:%d %s] Error while reading %s\n", __FILE__, __LINE__, __FUNCTION__, file_name.c_str()); exit(1); } else if (!initialize_next_interval()) { return false; } } } else { if ((res = sam_read1(file, hdr, s))>=0) { return true; } else { if (res < -1) { fprintf(stderr, "[%s:%d %s] Error while reading %s\n", __FILE__, __LINE__, __FUNCTION__, file_name.c_str()); exit(1); } return false; } } return false; }; BAMOrderedReader::~BAMOrderedReader() { close(); } /** * Closes the file. */ void BAMOrderedReader::close() { if ( hdr ) bam_hdr_destroy(hdr); if ( itr ) bam_itr_destroy(itr); if ( idx ) hts_idx_destroy(idx); if ( s ) bam_destroy1(s); if ( file ) sam_close(file); if ( str.s ) free(str.s); hdr = nullptr; itr = nullptr; idx = nullptr; s = nullptr; file = nullptr; str.s = nullptr; }
26.995652
125
0.600741
Yichen-Si
d50df6912b8979383a0f046175cb9f9576a9d25c
2,436
cpp
C++
src/hssh/local_topological/events/area_transition.cpp
h2ssh/Vulcan
cc46ec79fea43227d578bee39cb4129ad9bb1603
[ "MIT" ]
6
2020-03-29T09:37:01.000Z
2022-01-20T08:56:31.000Z
src/hssh/local_topological/events/area_transition.cpp
h2ssh/Vulcan
cc46ec79fea43227d578bee39cb4129ad9bb1603
[ "MIT" ]
1
2021-03-05T08:00:50.000Z
2021-03-05T08:00:50.000Z
src/hssh/local_topological/events/area_transition.cpp
h2ssh/Vulcan
cc46ec79fea43227d578bee39cb4129ad9bb1603
[ "MIT" ]
11
2019-05-13T00:04:38.000Z
2022-01-20T08:56:38.000Z
/* Copyright (C) 2010-2019, The Regents of The University of Michigan. All rights reserved. This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an MIT-style License that can be found at "https://github.com/h2ssh/Vulcan". */ /** * \file area_transition.cpp * \author Collin Johnson * * Definition of AreaTransitionEvent. */ #include <hssh/local_topological/events/area_transition.h> #include <hssh/local_topological/area.h> #include <hssh/local_topological/event_visitor.h> #include <sstream> #include <cassert> namespace vulcan { namespace hssh { AreaTransitionEvent::AreaTransitionEvent(int64_t timestamp, const LocalPose& pose, std::shared_ptr<LocalArea> exited, std::shared_ptr<LocalArea> entered, const Gateway& gateway) : LocalAreaEvent(timestamp, pose, true) , entered_(entered) , exited_ (exited) , gateway_(gateway) { assert(exited_); assert(entered_); areaIds_.push_back(exited->id()); areaIds_.push_back(entered->id()); } AreaTransitionEvent::AreaTransitionEvent(int64_t timestamp, const LocalPose& pose, std::shared_ptr<LocalArea> entered) : LocalAreaEvent(timestamp, pose, true) , entered_(entered) , gateway_(boost::none) { areaIds_.push_back(entered->id()); } Id AreaTransitionEvent::exitedId(void) const { return exited_ ? exited_->id() : kInvalidId; } Id AreaTransitionEvent::enteredId(void) const { assert(entered_); return entered_->id(); } void AreaTransitionEvent::accept(LocalAreaEventVisitor& visitor) const { visitor.visitAreaTransition(*this); } std::string AreaTransitionEvent::description(void) const { std::ostringstream str; str << "AreaTransition " << sequenceId() << ": Exited " << (exited_? exited_->description() : "-1") << " Entered:" << entered_->description(); return str.str(); } LocalAreaEventPtr AreaTransitionEvent::clone(void) const { return LocalAreaEventPtr(new AreaTransitionEvent(*this)); } } // namespace hssh } // namespace vulcan
26.193548
95
0.634236
h2ssh
d50f8e1acb66185f49e911328ed76efb60558645
3,722
cpp
C++
simulatingMooreAndMealyMachine.cpp
antarixX/C-plus-plus-Finite-Automata
777f7c4bfe91414c81abd86b0851d0608f0116d0
[ "MIT" ]
null
null
null
simulatingMooreAndMealyMachine.cpp
antarixX/C-plus-plus-Finite-Automata
777f7c4bfe91414c81abd86b0851d0608f0116d0
[ "MIT" ]
null
null
null
simulatingMooreAndMealyMachine.cpp
antarixX/C-plus-plus-Finite-Automata
777f7c4bfe91414c81abd86b0851d0608f0116d0
[ "MIT" ]
null
null
null
// Static program to implement a Moore and an equivalent Mealy Machine for Parity Checker #include<iostream> #include<conio.h> #include<string> using namespace std; void main() { char mealy[5][4]; char moore[5][3]; int i, j; char curr_state, out; string a; cout << "\n\t\t\tMealy Machine for Odd Parity Checker"; // Initializing the mealy machine mealy[0][0] = 'X'; mealy[0][1] = 'I'; mealy[0][2] = 'O'; mealy[0][3] = 'T'; mealy[1][0] = 'p'; mealy[1][1] = '0'; mealy[1][2] = 'n'; mealy[1][3] = 'p'; mealy[2][0] = 'p'; mealy[2][1] = '1'; mealy[2][2] = 'y'; mealy[2][3] = 'q'; mealy[3][0] = 'q'; mealy[3][1] = '0'; mealy[3][2] = 'y'; mealy[3][3] = 'q'; mealy[4][0] = 'q'; mealy[4][1] = '1'; mealy[4][2] = 'n'; mealy[4][3] = 'p'; // Displaying Transition Table for the Mealy Machine. cout << endl << endl << " The Transition Table for the Mealy Machine is as follows: "; cout << endl << endl; for (i = 0; i <= 4; i++) { cout << " "; for (j = 0; j <= 3; j++) cout << mealy[i][j] << "\t"; cout << endl << endl; } cout << endl << endl << " Enter the binary no: "; cin >> a; // Performing Computation cout << endl << endl << " Mealy Machine Odd Parity Checker proceeds as follows: "; cout << endl << endl; curr_state = 'p'; cout << " ---> " << curr_state; for (i = 0; i <= a.size() - 1; i++) { if (curr_state == 'p') { if (a[i] == mealy[1][1]) { curr_state = 'p'; out = 'n'; } if (a[i] == mealy[2][1]) { curr_state = 'q'; out = 'y'; } } else if (curr_state == 'q') { if (a[i] == mealy[3][1]) { curr_state = 'q'; out = 'y'; } if (a[i] == mealy[4][1]) { curr_state = 'p'; out = 'n'; } } cout << " -(" << a[i] << "/" << out << ")-> " << curr_state; } if (curr_state == 'q') { cout << endl << "\n Output : y" << endl << " The binary number " << a << " is ACCEPTED by the odd parity checker."; } else { cout << endl << "\n Output : n" << endl << " The binary number " << a << " is REJECTED by the odd parity checker."; } cout << endl << endl << endl << "\t\t\tMoore Machine for Odd Parity Checker"; // Initializing the Moore Machine moore[0][0] = 'X'; moore[0][1] = 'I'; moore[0][2] = 'T'; moore[1][0] = 'p'; moore[1][1] = '0'; moore[1][2] = 'p'; moore[2][0] = 'p'; moore[2][1] = '1'; moore[2][2] = 'q'; moore[3][0] = 'q'; moore[3][1] = '0'; moore[3][2] = 'q'; moore[4][0] = 'q'; moore[4][1] = '1'; moore[4][2] = 'p'; // Displaying Transition Table for the Moore Machine. cout << endl << endl << " The Transition Table for the Moore Machine is as follows: "; cout << endl << endl; for (i = 0; i <= 4; i++) { cout << " "; for (j = 0; j <= 2; j++) cout << moore[i][j] << "\t"; cout << endl << endl; } cout << endl << endl << " Enter the binary no: "; cin >> a; // Performing Computation cout << endl << endl << " Moore Machine Odd Parity Checker proceeds as follows: "; cout << endl << endl; curr_state = 'p'; cout << " --> " << curr_state; for (i = 0; i <= a.size() - 1; i++) { if (curr_state == 'p') { if (a[i] == moore[1][1]) { curr_state = 'p'; } else if (a[i] == moore[2][1]) { curr_state = 'q'; } } else if (curr_state == 'q') { if (a[i] == moore[3][1]) { curr_state = 'q'; } else if (a[i] == moore[4][1]) { curr_state = 'p'; } } cout << " -(" << a[i] << ")-> " << curr_state; } if (curr_state == 'q') { cout << endl << "\n Output : y" << endl << " The binary number " << a << " is ACCEPTED by the odd parity checker."; } else { cout << endl << "\n Output : n" << endl << " The binary number " << a << " is REJECTED by the odd parity checker."; } getch(); }
24.649007
119
0.497313
antarixX
d50fe3c0040a99c4c6d1223ad1ac98ea00230e45
3,329
cpp
C++
detector_core/detectors/uninit/uninitrule_helper.cpp
zhlongfj/cppdetector
0907720cdb82661ae137e4883346fc33cb115794
[ "MIT" ]
2
2022-03-22T05:50:40.000Z
2022-03-22T06:00:42.000Z
detector_core/detectors/uninit/uninitrule_helper.cpp
zhlongfj/cppdetector
0907720cdb82661ae137e4883346fc33cb115794
[ "MIT" ]
null
null
null
detector_core/detectors/uninit/uninitrule_helper.cpp
zhlongfj/cppdetector
0907720cdb82661ae137e4883346fc33cb115794
[ "MIT" ]
null
null
null
#include "uninitrule_helper.h" bool UninitRuleVariableDefinitionHelper::detectCore(const ErrorFile& errorFile, const string& variableName) { //check "int32_t s;" //storeRuleError(errorFile); if (m_className.empty()) { return true; } m_definedVariables.insert({ m_className, { variableName, errorFile } }); return false; } std::vector<ErrorFile> UninitRuleVariableDefinitionHelper::resetData() { vector<ErrorFile> errorFiles; for (const auto& item : m_definedVariables) { if (auto ret = m_initializedVariables.find(item.first); ret != m_initializedVariables.end()) { if (ret->second.find(item.second.first) == ret->second.end()) { errorFiles.push_back(item.second.second); } } } resetEndOfClass(); m_initializedVariables.clear(); m_definedVariables.clear(); return errorFiles; } void UninitRuleVariableDefinitionHelper::checkClass(const string& code) { if (code == "};") { resetEndOfClass(); } auto codeTmp = code; if (auto className = DetectorHelper::checkClassDefinition(codeTmp); !className.empty()) { m_className = className; m_initializedVariables.insert({ className, set<string>() }); } if (m_initializedVariables.empty()) { return; } for (const auto& item : m_initializedVariables) { if (codeTmp.find(item.first) == string::npos || codeTmp.find("~") != string::npos) { //can not find class or find destructor continue; } if (codeTmp.find("= default") != string::npos || codeTmp.find("= delete") != string::npos) { continue; } auto className = item.first; if (auto ret = DetectorHelper::check(codeTmp, className + "\\(.*\\)"); !ret.empty()) { //constructor method m_findConstructor = true; codeTmp = ret[0].str(); m_className = className; break; } } if (!m_findConstructor && !m_inConstructor) { return; } if (codeTmp.find("{") != string::npos) { ++m_countOfLeftBrace; m_inConstructor = true; m_findConstructor = false; } if (codeTmp.find("}") != string::npos) { --m_countOfLeftBrace; } if (m_countOfLeftBrace <= 0) { auto tmp = codeTmp; while (true) { auto ret = DetectorHelper::check(tmp, "\\s*(\\w+)\\s*[\\(\\{]\\w+[\\)\\}]"); if (ret.empty()) { break; } m_initializedVariables[m_className].insert(ret[1].str()); tmp = tmp.substr(ret[0].length()); } if (m_inConstructor) { m_inConstructor = false; } } if (m_inConstructor && m_countOfLeftBrace > 0) { if (auto ret = DetectorHelper::check(codeTmp, "(\\w+)\\s*[\\(\\{=]"); !ret.empty()) { m_initializedVariables[m_className].insert(ret[1].str()); } } } void UninitRuleVariableDefinitionHelper::resetEndOfClass() { m_className.clear(); m_findConstructor = false; m_inConstructor = false; m_countOfLeftBrace = 0; }
25.030075
107
0.550616
zhlongfj
d5153fc681d50e5649714ee4c082eee0dcb68820
8,717
cpp
C++
src/nonedit.cpp
adhithyaarun/Plane-Game-3D
aa9c2ec75baa662f3d75d27bd5a5301a4fb99f21
[ "MIT" ]
null
null
null
src/nonedit.cpp
adhithyaarun/Plane-Game-3D
aa9c2ec75baa662f3d75d27bd5a5301a4fb99f21
[ "MIT" ]
null
null
null
src/nonedit.cpp
adhithyaarun/Plane-Game-3D
aa9c2ec75baa662f3d75d27bd5a5301a4fb99f21
[ "MIT" ]
null
null
null
#include <iostream> #include <cmath> #include <fstream> #include <vector> #include <GL/glew.h> #include <GLFW/glfw3.h> #define GLM_FORCE_RADIANS #include <glm/glm.hpp> #include <glm/gtx/transform.hpp> #include <glm/gtc/matrix_transform.hpp> #include "main.h" using namespace std; /* Initialise glfw window, I/O callbacks and the renderer to use */ /* Nothing to Edit here */ GLFWwindow*initGLFW(int width, int height) { GLFWwindow *window; // window desciptor/handle glfwSetErrorCallback(error_callback); if (!glfwInit()) { // exit(EXIT_FAILURE); } glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); window = glfwCreateWindow(width, height, "Fighter Jet Simulator", NULL, NULL); if (!window) { glfwTerminate(); // exit(EXIT_FAILURE); } glfwMakeContextCurrent(window); // Initialize GLEW, Needed in Core profile glewExperimental = GL_TRUE; GLenum err = glewInit(); if (err != GLEW_OK) { cout << "Error: Failed to initialise GLEW : " << glewGetErrorString(err) << endl; exit (1); } glfwSwapInterval(1); /* --- register callbacks with GLFW --- */ /* Register function to handle window resizes */ /* With Retina display on Mac OS X GLFW's FramebufferSize is different from WindowSize */ glfwSetFramebufferSizeCallback(window, reshapeWindow); glfwSetWindowSizeCallback(window, reshapeWindow); /* Register function to handle window close */ glfwSetWindowCloseCallback(window, quit); /* Register function to handle keyboard input */ glfwSetKeyCallback(window, keyboard); // general keyboard input glfwSetCharCallback(window, keyboardChar); // simpler specific character handling /* Register function to handle mouse click */ glfwSetMouseButtonCallback(window, mouseButton); // mouse button clicks glfwSetScrollCallback(window, scroll_callback); return window; } /* Function to load Shaders - Use it as it is */ GLuint LoadShaders(const char *vertex_file_path, const char *fragment_file_path) { // Create the shaders GLuint VertexShaderID = glCreateShader(GL_VERTEX_SHADER); GLuint FragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER); // Read the Vertex Shader code from the file std::string VertexShaderCode; std::ifstream VertexShaderStream(vertex_file_path, std::ios::in); if (VertexShaderStream.is_open()) { std::string Line = ""; while (getline(VertexShaderStream, Line)) VertexShaderCode += "\n" + Line; VertexShaderStream.close(); } // Read the Fragment Shader code from the file std::string FragmentShaderCode; std::ifstream FragmentShaderStream(fragment_file_path, std::ios::in); if (FragmentShaderStream.is_open()) { std::string Line = ""; while (getline(FragmentShaderStream, Line)) FragmentShaderCode += "\n" + Line; FragmentShaderStream.close(); } GLint Result = GL_FALSE; int InfoLogLength; // Compile Vertex Shader printf("Compiling shader : %s\n", vertex_file_path); char const *VertexSourcePointer = VertexShaderCode.c_str(); glShaderSource(VertexShaderID, 1, &VertexSourcePointer, NULL); glCompileShader(VertexShaderID); // Check Vertex Shader glGetShaderiv(VertexShaderID, GL_COMPILE_STATUS, &Result); glGetShaderiv(VertexShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength); std::vector<char> VertexShaderErrorMessage(InfoLogLength); glGetShaderInfoLog(VertexShaderID, InfoLogLength, NULL, &VertexShaderErrorMessage[0]); fprintf(stdout, "%s\n", &VertexShaderErrorMessage[0]); // Compile Fragment Shader printf("Compiling shader : %s\n", fragment_file_path); char const *FragmentSourcePointer = FragmentShaderCode.c_str(); glShaderSource(FragmentShaderID, 1, &FragmentSourcePointer, NULL); glCompileShader(FragmentShaderID); // Check Fragment Shader glGetShaderiv(FragmentShaderID, GL_COMPILE_STATUS, &Result); glGetShaderiv(FragmentShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength); std::vector<char> FragmentShaderErrorMessage(InfoLogLength); glGetShaderInfoLog(FragmentShaderID, InfoLogLength, NULL, &FragmentShaderErrorMessage[0]); fprintf(stdout, "%s\n", &FragmentShaderErrorMessage[0]); // Link the program fprintf(stdout, "Linking program\n"); GLuint ProgramID = glCreateProgram(); glAttachShader(ProgramID, VertexShaderID); glAttachShader(ProgramID, FragmentShaderID); glLinkProgram(ProgramID); // Check the program glGetProgramiv(ProgramID, GL_LINK_STATUS, &Result); glGetProgramiv(ProgramID, GL_INFO_LOG_LENGTH, &InfoLogLength); std::vector<char> ProgramErrorMessage(max(InfoLogLength, int(1))); glGetProgramInfoLog(ProgramID, InfoLogLength, NULL, &ProgramErrorMessage[0]); fprintf(stdout, "%s\n", &ProgramErrorMessage[0]); glDeleteShader(VertexShaderID); glDeleteShader(FragmentShaderID); return ProgramID; } /* Generate VAO, VBOs and return VAO handle */ struct VAO *create3DObject(GLenum primitive_mode, int numVertices, const GLfloat *vertex_buffer_data, const GLfloat *color_buffer_data, GLenum fill_mode) { struct VAO *vao = new struct VAO; vao->PrimitiveMode = primitive_mode; vao->NumVertices = numVertices; vao->FillMode = fill_mode; // Create Vertex Array Object // Should be done after CreateWindow and before any other GL calls glGenVertexArrays(1, &(vao->VertexArrayID)); // VAO glGenBuffers (1, &(vao->VertexBuffer)); // VBO - vertices glGenBuffers (1, &(vao->ColorBuffer)); // VBO - colors glBindVertexArray (vao->VertexArrayID); // Bind the VAO glBindBuffer (GL_ARRAY_BUFFER, vao->VertexBuffer); // Bind the VBO vertices glBufferData (GL_ARRAY_BUFFER, 3 * numVertices * sizeof(GLfloat), vertex_buffer_data, GL_STATIC_DRAW); // Copy the vertices into VBO glVertexAttribPointer( 0, // attribute 0. Vertices 3, // size (x,y,z) GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void *) 0 // array buffer offset ); glBindBuffer (GL_ARRAY_BUFFER, vao->ColorBuffer); // Bind the VBO colors glBufferData (GL_ARRAY_BUFFER, 3 * numVertices * sizeof(GLfloat), color_buffer_data, GL_STATIC_DRAW); // Copy the vertex colors glVertexAttribPointer( 1, // attribute 1. Color 3, // size (r,g,b) GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void *) 0 // array buffer offset ); return vao; } /* Generate VAO, VBOs and return VAO handle - Common Color for all vertices */ struct VAO *create3DObject(GLenum primitive_mode, int numVertices, const GLfloat *vertex_buffer_data, const GLfloat red, const GLfloat green, const GLfloat blue, GLenum fill_mode) { GLfloat *color_buffer_data = new GLfloat[3 * numVertices]; for (int i = 0; i < numVertices; i++) { color_buffer_data[3 * i] = red; color_buffer_data[3 * i + 1] = green; color_buffer_data[3 * i + 2] = blue; } return create3DObject(primitive_mode, numVertices, vertex_buffer_data, color_buffer_data, fill_mode); } struct VAO *create3DObject(GLenum primitive_mode, int numVertices, const GLfloat *vertex_buffer_data, const color_t color, GLenum fill_mode) { return create3DObject(primitive_mode, numVertices, vertex_buffer_data, color.r / 256.0, color.g / 256.0, color.b / 256.0, fill_mode); } /* Render the VBOs handled by VAO */ void draw3DObject(struct VAO *vao) { // Change the Fill Mode for this object glPolygonMode (GL_FRONT_AND_BACK, vao->FillMode); // Bind the VAO to use glBindVertexArray (vao->VertexArrayID); // Enable Vertex Attribute 0 - 3d Vertices glEnableVertexAttribArray(0); // Bind the VBO to use glBindBuffer(GL_ARRAY_BUFFER, vao->VertexBuffer); // Enable Vertex Attribute 1 - Color glEnableVertexAttribArray(1); // Bind the VBO to use glBindBuffer(GL_ARRAY_BUFFER, vao->ColorBuffer); // Draw the geometry ! glDrawArrays(vao->PrimitiveMode, 0, vao->NumVertices); // Starting from vertex 0; 3 vertices total -> 1 triangle }
38.570796
181
0.676494
adhithyaarun
d51678a2a3fe4f0b437b99d485c88b5df0499b39
25,340
hpp
C++
craam/Samples.hpp
marekpetrik/CRAAM
62cc392e876b5383faa5cb15ab1f6b70b26ff395
[ "MIT" ]
22
2015-09-28T14:41:00.000Z
2020-07-03T00:16:19.000Z
craam/Samples.hpp
marekpetrik/CRAAM
62cc392e876b5383faa5cb15ab1f6b70b26ff395
[ "MIT" ]
6
2017-08-10T18:35:40.000Z
2018-10-13T01:38:04.000Z
craam/Samples.hpp
marekpetrik/CRAAM
62cc392e876b5383faa5cb15ab1f6b70b26ff395
[ "MIT" ]
10
2016-09-19T18:31:07.000Z
2018-07-05T08:59:45.000Z
// This file is part of CRAAM, a C++ library for solving plain // and robust Markov decision processes. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #pragma once #include "definitions.hpp" #include "RMDP.hpp" #include "modeltools.hpp" #include <rm/range.hpp> #include <set> #include <memory> #include <unordered_map> #include <functional> #include <cassert> #include <utility> #include <vector> #include <string> namespace craam{ /// A namespace for handling sampling and simulation namespace msen{ using namespace util::lang; using namespace std; /** Represents a single transition between two states after taking an action: \f[ (s, a, s', r, w) \f] where: - \f$ s \f$ is the originating state - \f$ a \f$ is the action taken - \f$ s' \f$ is the target state - \f$ r \f$ is the reward - \f$ w \f$ is the weight (or importance) of the state. It is like probability, except it does not have to sum to 1. It must be non-negative. In addition, the sample also includes step and the run. These are used for example to compute the return from samples. \tparam State MDP state: \f$ s, s'\f$ \tparam Action MDP action: \f$ a \f$ */ template <class State, class Action> class Sample { public: Sample(State state_from, Action action, State state_to, prec_t reward, prec_t weight, long step, long run): _state_from(move(state_from)), _action(move(action)), _state_to(move(state_to)), _reward(reward), _weight(weight), _step(step), _run(run){ assert(weight >= 0);}; /** Original state */ State state_from() const {return _state_from;}; /** Action taken */ Action action() const {return _action;}; /** Destination state */ State state_to() const {return _state_to;}; /** Reward associated with the sample */ prec_t reward() const {return _reward;}; /// Sample weight prec_t weight() const {return _weight;}; /// Number of the step in an one execution of the simulation long step() const {return _step;}; /// Number of the actual execution long run() const {return _run;}; protected: /// Original state State _state_from; /// Action taken Action _action; /// Destination state State _state_to; /// Reward associated with the sample prec_t _reward; /// Sample weight prec_t _weight; /// Number of the step in an one execution of the simulation long _step; /// Number of the actual execution long _run; }; /** General representation of samples: \f[ \Sigma = (s_i, a_i, s_i', r_i, w_i)_{i=0}^{m-1} \f] See Sample for definitions of individual values. \tparam State Type defining states \tparam Action Type defining actions */ template <class State, class Action> class Samples { public: Samples(): states_from(), actions(), states_to(), rewards(), cumulative_rewards(), weights(), runs(), steps(), initial() {}; /** Adds an initial state */ void add_initial(const State& decstate){ this->initial.push_back(decstate); }; /** Adds an initial state */ void add_initial(State&& decstate){ this->initial.push_back(decstate); }; /** Adds a sample starting in a decision state */ void add_sample(const Sample<State,Action>& sample){ states_from.push_back(sample.state_from()); actions.push_back(sample.action()); states_to.push_back(sample.state_to()); rewards.push_back(sample.reward()); prec_t cumulative_reward_value = sample.reward(); if (runs.size() > 0 && *runs.rbegin() == sample.run()) cumulative_reward_value += *cumulative_rewards.rbegin(); cumulative_rewards.push_back(cumulative_reward_value); weights.push_back(sample.weight()); steps.push_back(sample.step()); runs.push_back(sample.run()); }; /** Adds a sample starting in a decision state */ void add_sample(State state_from, Action action, State state_to, prec_t reward, prec_t weight, long step, long run){ states_from.push_back(move(state_from)); actions.push_back(move(action)); states_to.push_back(move(state_to)); rewards.push_back(reward); prec_t cumulative_reward_value = reward; if (runs.size() > 0 && *runs.rbegin() == run) cumulative_reward_value += *cumulative_rewards.rbegin(); cumulative_rewards.push_back(cumulative_reward_value); weights.push_back(weight); steps.push_back(step); runs.push_back(run); } /** Computes the discounted mean return over all the samples \param discount Discount factor */ prec_t mean_return(prec_t discount){ prec_t result = 0; set<int> runs; for(size_t si : indices(*this)){ auto es = get_sample(si); result += es.reward() * pow(discount,es.step()); runs.insert(es.run()); } result /= runs.size(); return result; }; /** Number of samples */ size_t size() const {return states_from.size();}; /** Access to samples */ Sample<State,Action> get_sample(long i) const{ assert(i >=0 && size_t(i) < size()); return Sample<State,Action>(states_from[i],actions[i],states_to[i], rewards[i],weights[i],steps[i],runs[i]);}; /** Access to samples */ Sample<State,Action> operator[](long i) const{ return get_sample(i); }; /** List of initial states */ const vector<State>& get_initial() const{return initial;}; const vector<State>& get_states_from() const{return states_from;}; const vector<Action>& get_actions() const{return actions;}; const vector<State>& get_states_to() const{return states_to;}; const vector<prec_t>& get_rewards() const{return rewards;}; const vector<prec_t>& get_cumulative_rewards() const{return cumulative_rewards;}; const vector<prec_t>& get_weights() const{return weights;}; const vector<long>& get_runs() const{return runs;}; const vector<long>& get_steps() const{return steps;}; protected: vector<State> states_from; vector<Action> actions; vector<State> states_to; vector<prec_t> rewards; vector<prec_t> cumulative_rewards; vector<prec_t> weights; vector<long> runs; vector<long> steps; vector<State> initial; }; /** A helper function that constructs a samples object based on the simulator that is provided to it */ template<class Sim, class... U> Samples<typename Sim::State, typename Sim::Action> make_samples(U&&... u){ return Samples<typename Sim::State, typename Sim::Action>(forward<U>(u)...); } // ********************************************************************** // ****** Discrete simulation specialization ****************** // ********************************************************************** /** Samples in which the states and actions are identified by integers. */ using DiscreteSamples = Samples<long,long>; /** Integral expectation sample */ using DiscreteSample = Sample<long,long>; /** Turns arbitrary samples to discrete ones assuming that actions are \b state \b independent. That is the actions must have consistent names across states. This assumption can cause problems when some samples are missing. The internally-held discrete samples can be accessed and modified from the outside. Also, adding more samples will modify the discrete samples. See SampleDiscretizerSD for a version in which action names are dependent on states. A new hash function can be defined as follows: \code namespace std{ template<> struct hash<pair<int,int>>{ size_t operator()(pair<int,int> const& s) const{ boost::hash<pair<int,int>> h; return h(s); }; } }; \endcode \tparam State Type of state in the source samples \tparam Action Type of action in the source samples \tparam Shash Hash function for states \tparam Ahash Hash function for actions A hash function hash<type> for each sample type must exists. */ template< typename State, typename Action, typename SHash = std::hash<State>, typename AHash = std::hash<Action>> class SampleDiscretizerSI{ public: /** Constructs new internal discrete samples*/ SampleDiscretizerSI() : discretesamples(make_shared<DiscreteSamples>()), action_map(), state_map() {}; /** Adds samples to the discrete samples */ void add_samples(const Samples<State,Action>& samples){ // initial states for(const State& ins : samples.get_initial()){ discretesamples->add_initial(add_state(ins)); } // samples for(auto si : indices(samples)){ const auto ds = samples.get_sample(si); discretesamples->add_sample( add_state(ds.state_from()), add_action(ds.action()), add_state(ds.state_to()), ds.reward(), ds.weight(), ds.step(), ds.run()); } } /** Returns a state index, and creates a new one if it does not exists */ long add_state(const State& dstate){ auto iter = state_map.find(dstate); long index; if(iter == state_map.end()){ index = state_map.size(); state_map[dstate] = index; } else{ index = iter->second; } return index; } /** Returns a action index, and creates a new one if it does not exists */ long add_action(const Action& action){ auto iter = action_map.find(action); long index; if(iter == action_map.end()){ index = action_map.size(); action_map[action] = index; } else{ index = iter->second; } return index; } /** Returns a shared pointer to the discrete samples */ shared_ptr<DiscreteSamples> get_discrete(){return discretesamples;}; protected: shared_ptr<DiscreteSamples> discretesamples; unordered_map<Action,long,AHash> action_map; unordered_map<State,long,SHash> state_map; }; /** Turns arbitrary samples to discrete ones (with continuous numbers assigned to states) assuming that actions are \b state \b dependent. The internally-held discrete samples can be accessed and modified from the outside. Also, adding more samples will modify the discrete samples. See SampleDiscretizerSI for a version in which action names are independent of states. A new hash function can be defined as follows: \code namespace std{ template<> struct hash<pair<int,int>>{ size_t operator()(pair<int,int> const& s) const{ boost::hash<pair<int,int>> h; return h(s); }; } }; \endcode \tparam State Type of state in the source samples \tparam Action Type of action in the source samples \tparam SAhash Hash function for pair<State, Action> \tparam Shash Hash function for decision states A hash function hash<type> for each sample type must exists. */ template< typename State, typename Action, typename SAHash = std::hash<pair<State, Action>>, typename SHash = std::hash<State> > class SampleDiscretizerSD{ public: /** Constructs new internal discrete samples*/ SampleDiscretizerSD() : discretesamples(make_shared<DiscreteSamples>()), action_map(), action_count(), state_map() {}; /** Adds samples to the discrete samples */ void add_samples(const Samples<State,Action>& samples){ // initial states for(const auto& ins : samples.get_initial()){ discretesamples->add_initial(add_state(ins)); } // transition samples for(auto si : indices(samples)){ const auto es = samples.get_sample(si); discretesamples->add_sample(add_state(es.state_from()), add_action(es.state_from(), es.action()), add_state(es.state_to()), es.reward(), es.weight(), es.step(), es.run()); } } /** Returns a state index, and creates a new one if it does not exists */ long add_state(const State& dstate){ auto iter = state_map.find(dstate); long index; if(iter == state_map.end()){ index = state_map.size(); state_map[dstate] = index; } else{ index = iter->second; } return index; } /** Returns an action index, and creates a new one if it does not exists */ long add_action(const State& dstate, const Action& action){ auto da = make_pair(dstate, action); auto iter = action_map.find(da); long index; if(iter == action_map.end()){ index = (action_count[dstate]++); action_map[da] = index; } else{ index = iter->second; } return index; } /** Returns a shared pointer to the discrete samples */ shared_ptr<DiscreteSamples> get_discrete(){return discretesamples;}; protected: shared_ptr<DiscreteSamples> discretesamples; unordered_map<pair<State,Action>,long,SAHash> action_map; /** keeps the number of actions for each state */ unordered_map<State,long,SHash> action_count; unordered_map<State,long,SHash> state_map; }; /** Constructs an MDP from integer samples. Integer samples: All states and actions are identified by integers. \a Input: Sample set \f$ \Sigma = (s_i, a_i, s_i', r_i, w_i)_{i=0}^{m-1} \f$ \n \a Output: An MDP such that: - States: \f$ \mathcal{S} = \bigcup_{i=0}^{m-1} \{ s_i \} \cup \bigcup_{i=0}^{m-1} \{ s_i' \} \f$ - Actions: \f$ \mathcal{A} = \bigcup_{i=0}^{m-1} \{ a_i \} \f$ - Transition probabilities: \f[ P(s,a,s') = \frac{\sum_{i=0}^{m-1} w_i 1\{ s = s_i, a = a_i, s' = s_i' \} } { \sum_{i=0}^{m-1} w_i 1\{ s = s_i, a = a_i \} } \f] - Rewards: \f[ r(s,a,s') = \frac{\sum_{i=0}^{m-1} r_i w_i 1\{ s = s_i, a = a_i, s' = s_i' \} } { \sum_{i=0}^{m-1} w_i 1\{ s = s_i, a = a_i, s' = s_i' \} } \f] The class also tracks cumulative weights of state-action samples \f$ z \f$: \f[ z(s,a) = \sum_{i=0}^{m-1} w_i 1\{ s = s_i, a = a_i \} \f] If \f$ z(s,a) = 0 \f$ then the action \f$ a \f$ is marked as invalid. There is some extra memory penalty due to storing these weights. \a Important: Actions that are not sampled (no samples per that state and action pair) are labeled as invalid and are not included in the computation of value function or the solution. For example, if there is an action 1 in state zero but there are no samples that include action 0 then action 0 is still created, but is ignored when computing the value function. When sample sets are added by multiple calls of SampledMDP::add_samples, the results is the same as if all the individual sample sets were combined and added together. See SampledMDP::add_samples for more details. */ class SampledMDP{ public: /** Constructs an empty MDP from discrete samples */ SampledMDP(): mdp(make_shared<MDP>()), initial(), state_action_weights() {} /** Constructs or adds states and actions based on the provided samples. Sample sets can be added iteratively. Assume that the current transition probabilities are constructed based on a sample set \f$ \Sigma = (s_i, a_i, s_i', r_i, w_i)_{i=0}^{m-1} \f$ and add_samples is called with sample set \f$ \Sigma' = (s_j, a_j, s_j', r_j, w_j)_{i=m}^{n-1} \f$. The result is the same as if simultaneously adding samples \f$ 0 \ldots (n-1) \f$. New MDP values are updates as follows: - Cumulative state-action weights \f$ z'\f$: \f[ z'(s,a) = z(s,a) + \sum_{j=m}^{n-1} w_j 1\{ s = s_j, a = a_j \} \f] - Transition probabilities \f$ P \f$: \f{align*}{ P'(s,a,s') &= \frac{z(s,a) * P(s,a,s') + \sum_{j=m}^{n-1} w_j 1\{ s = s_j, a = a_j, s' = s_j' \} } { z'(s,a) } = \\ &= \frac{P(s,a,s') + (1 / z(s,a)) \sum_{j=m}^{n-1} w_j 1\{ s = s_j, a = a_j, s' = s_j' \} } { z'(s,a) / z(s,a) } \f} The denominator is computed implicitly by normalizing transition probabilities. - Rewards \f$ r' \f$: \f{align*} r'(s,a,s') &= \frac{r(s,a,s') z(s,a) P(s,a,s') + \sum_{j=m}^{n-1} r_j w_j 1\{ s = s_j, a = a_j, s' = s_j' \}} {z'(s,a)P'(s,a,s')} \\ r'(s,a,s') &= \frac{r(s,a,s') z(s,a) P(s,a,s') + \sum_{j=m}^{n-1} r_j w_j 1\{ s = s_j, a = a_j, s' = s_j' \}} {z'(s,a)P'(s,a,s')} \\ &= \frac{r(s,a,s') P(s,a,s') + \sum_{j=m}^{n-1}r_j (w_j/z(s,a)) 1\{ s = s_j, a = a_j, s' = s_j' \}} {z'(s,a)P'(s,a,s')/ z(s,a)} \\ &= \frac{r(s,a,s') P(s,a,s') + \sum_{j=m}^{n-1} r_j (w_j/z(s,a) 1\{ s = s_j, a = a_j, s' = s_j' \}} {P(s,a,s') + \sum_{j=m}^{n-1} (w_j/z(s,a)) 1\{ s = s_j, a = a_j, s' = s_j' \}} \f} The last line follows from the definition of \f$ P(s,a,s') \f$. This corresponds to the operation of Transition::add_sample repeatedly for \f$ j = m \ldots (n-1) \f$ with \f{align*} p &= (w_j/z(s,a)) 1\{ s = s_j, a = a_j, s' = s_j' \}\\ r &= r_j \f}. \param samples New sample set to add to transition probabilities and rewards */ void add_samples(const DiscreteSamples& samples){ // copy the state and action counts to be auto old_state_action_weights = state_action_weights; // add transition samples for(size_t si : indices(samples)){ DiscreteSample s = samples.get_sample(si); // ----------------- // Computes sample weights: // the idea is to normalize new samples by the same // value as the existing samples and then re-normalize // this is linear complexity // ----------------- // weight used to normalize old data prec_t weight = 1.0; // this needs to be initialized to 1.0 // whether the sample weight has been initialized bool weight_initialized = false; // resize transition counts // the actual values are updated later if((size_t) s.state_from() >= state_action_weights.size()){ state_action_weights.resize(s.state_from()+1); // we know that the value will not be found in old data weight_initialized = true; } // check if we have something for the action numvec& actioncount = state_action_weights[s.state_from()]; if((size_t)s.action() >= actioncount.size()){ actioncount.resize(s.action()+1); // we know that the value will not be found in old data weight_initialized = true; } // update the new count assert(size_t(s.state_from()) < state_action_weights.size()); assert(size_t(s.action()) < state_action_weights[s.state_from()].size()); state_action_weights[s.state_from()][s.action()] += s.weight(); // get number of existing transitions // this is only run when we do not know if we have any prior // sample if(!weight_initialized && (size_t(s.state_from()) < old_state_action_weights.size()) && (size_t(s.action()) < old_state_action_weights[s.state_from()].size())) { size_t cnt = old_state_action_weights[s.state_from()][s.action()]; // adjust the weight of the new sample to be consistent // with the previous normalization (use 1.0 if no previous action) weight = 1.0 / prec_t(cnt); } // --------------------- // adds a transition add_transition( *mdp, s.state_from(), s.action(), s.state_to(), weight*s.weight(), s.reward()); } // make sure to set action validity based on whether there have been // samples observed for the action for(size_t si : indices(*mdp)){ auto& state = mdp->get_state(si); // valid only if there are some samples for the action for(size_t ai : indices(state)){ state.set_valid(ai, state_action_weights[si][ai] > 0); } } // Normalize the transition probabilities and rewards mdp->normalize(); // set initial distribution (not normalized so it is updated correctly when adding more samples for(long state : samples.get_initial()){ if(state > state_count()) throw range_error("Initial state number larger than any transition state."); if(state < 0) throw range_error("Initial state with a negative index is invalid."); initial.add_sample(state, 1.0, 0.0); } } /** \returns A constant pointer to the internal MDP */ shared_ptr<const MDP> get_mdp() const {return const_pointer_cast<const MDP>(mdp);} /** \returns A modifiable pointer to the internal MDP. Take care when changing it. */ shared_ptr<MDP> get_mdp_mod() {return mdp;} /** \returns Initial distribution based on empirical sample data. Could be * somewhat expensive because it normalizes the transition. */ Transition get_initial() const {Transition t = initial; t.normalize(); return t;} /** \returns State-action cumulative weights \f$ z \f$. See class description for details. */ vector<vector<prec_t>> get_state_action_weights(){return state_action_weights;} /** Returns thenumber of states in the samples (the highest observed index. Some may be missing) \returns 0 when there are no samples */ long state_count(){return state_action_weights.size();} protected: /** Internal MDP representation */ shared_ptr<MDP> mdp; /** Initial distribution, not normalized */ Transition initial; /** Sample counts */ vector<vector<prec_t>> state_action_weights; }; /* Constructs a robust MDP from integer samples. In integer samples each decision state, expectation state, and action are identified by an integer. There is some extra memory penalty in this class over a plain MDP since it stores the number of samples observed for each state and action. Important: Actions that are not sampled (no samples per that state and action pair) are labeled as invalid and are not included in the computation of value function or the solution. */ //template<typename Model> //class SampledRMDP{ //public: // // /** Constructs an empty MDP from discrete samples */ // SampledRMDP(); // // /** // Constructs or adds states and actions based on the provided samples. Transition // probabilities of the existing samples are normalized. // // \param samples Source of the samples // */ // void add_samples(const DiscreteSamples& samples); // // /** \returns A constant pointer to the internal MDP */ // shared_ptr<const Model> get_rmdp() const {return const_pointer_cast<const Model>(mdp);} // // /** \returns A modifiable pointer to the internal MDP. // Take care when changing. */ // shared_ptr<Model> get_rmdp_mod() {return mdp;} // // /** Initial distribution */ // Transition get_initial() const {return initial;} // //protected: // // /** Internal MDP representation */ // shared_ptr<Model> mdp; // // /** Initial distribution */ // Transition initial; // // /** Sample counts */ // vector<vector<size_t>> state_action_counts; //}; } // end namespace msen } // end namespace craam
35
127
0.607064
marekpetrik
d5171ddc652a02062d5d0010c345143a91f4425a
7,846
cc
C++
src/error.cc
jiri/toggldesktop
38830a3bd19318b9684b2a6cdf4c15470a220442
[ "BSD-3-Clause" ]
null
null
null
src/error.cc
jiri/toggldesktop
38830a3bd19318b9684b2a6cdf4c15470a220442
[ "BSD-3-Clause" ]
null
null
null
src/error.cc
jiri/toggldesktop
38830a3bd19318b9684b2a6cdf4c15470a220442
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2014 Toggl Desktop developers. #include "error.h" #include <string> #include "const.h" namespace toggl { bool IsNetworkingError(const error &err) { if (noError == err) { return false; } if (err.find(kCannotConnectError) != std::string::npos) { return true; } if (err.find(kBackendIsDownError) != std::string::npos) { return true; } if (err.find(kCannotEstablishProxyConnection) != std::string::npos) { return true; } if (err.find(kCertificateVerifyFailed) != std::string::npos) { return true; } if (err.find(kProxyAuthenticationRequired) != std::string::npos) { return true; } if (err.find("Cannot assign requested address") != std::string::npos) { return true; } if (err.find(kCertificateValidationError) != std::string::npos) { return true; } if (err.find(kUnacceptableCertificate) != std::string::npos) { return true; } if (err.find("Host not found") != std::string::npos) { return true; } if (err.find(kCannotUpgradeToWebSocketConnection) != std::string::npos) { return true; } if (err.find("No message received") != std::string::npos) { return true; } if (err.find("Connection refused") != std::string::npos) { return true; } if (err.find("Connection timed out") != std::string::npos) { return true; } if (err.find("connect timed out") != std::string::npos) { return true; } if (err.find("SSL connection unexpectedly closed") != std::string::npos) { return true; } if (err.find("Network is down") != std::string::npos) { return true; } if (err.find("Network is unreachable") != std::string::npos) { return true; } if (err.find("Host is down") != std::string::npos) { return true; } if (err.find("No route to host") != std::string::npos) { return true; } if ((err.find("I/O error: 1") != std::string::npos) && (err.find(":443") != std::string::npos)) { return true; } if (err.find("The request timed out") != std::string::npos) { return true; } if (err.find("Could not connect to the server") != std::string::npos) { return true; } if (err.find("Connection reset by peer") != std::string::npos) { return true; } if (err.find("The Internet connection appears to be offline") != std::string::npos) { return true; } if (err.find("Timeout") != std::string::npos) { return true; } if (err.find(kSSLException) != std::string::npos) { return true; } if (err.find("An internal server error occurred.") != std::string::npos) { return true; } return false; } bool IsUserError(const error &err) { if (noError == err) { return false; } if (err.find(kErrorRuleAlreadyExists) != std::string::npos) { return true; } if (err.find(kCheckYourSignupError) != std::string::npos) { return true; } if (err.find(kEmailNotFoundCannotLogInOffline) != std::string::npos) { return true; } if (err.find(kInvalidPassword) != std::string::npos) { return true; } if (err.find(kPaymentRequiredError) != std::string::npos) { return true; } if (err.find("File not found") != std::string::npos) { return true; } if (err.find("SSL context exception") != std::string::npos) { return true; } if (err.find("Access to file denied") != std::string::npos) { return true; } if (err.find(kBadRequestError) != std::string::npos) { return true; } if (err.find(kUnauthorizedError) != std::string::npos) { return true; } if (err.find(kCannotWriteFile) != std::string::npos) { return true; } if (err.find(kIsSuspended) != std::string::npos) { return true; } if (err.find(kRequestToServerFailedWithStatusCode403) != std::string::npos) { return true; } if (err.find(kUnsupportedAppError) != std::string::npos) { return true; } if (err.find("Stop time must be after start time") != std::string::npos) { return true; } if (err.find("Invalid e-mail or password") != std::string::npos) { return true; } if (err.find("Maximum length for description") != std::string::npos) { return true; } if (err.find("Start time year must be between 2010 and 2100") != std::string::npos) { return true; } if (err.find(kMissingWorkspaceID) != std::string::npos) { return true; } if (err.find(kEndpointGoneError) != std::string::npos) { return true; } if (err.find("Password should be at least") != std::string::npos) { return true; } if (err.find("User with this email already exists") != std::string::npos) { return true; } if (err.find("Invalid e-mail") != std::string::npos) { return true; } if (err.find(kCannotAccessWorkspaceError) != std::string::npos) { return true; } if (err.find(kCannotSyncInTestEnv) != std::string::npos) { return true; } if (err.find(kCannotContinueDeletedTimeEntry) != std::string::npos) { return true; } if (err.find(kCannotDeleteDeletedTimeEntry) != std::string::npos) { return true; } if (err.find(kPleaseSelectAWorkspace) != std::string::npos) { return true; } if (err.find(kClientNameMustNotBeEmpty) != std::string::npos) { return true; } if (err.find(kProjectNameMustNotBeEmpty) != std::string::npos) { return true; } if (err.find(kClientNameAlreadyExists) != std::string::npos) { return true; } if (err.find(kProjectNameAlreadyExists) != std::string::npos) { return true; } if (err.find(kThisEntryCantBeSavedPleaseAdd) != std::string::npos) { return true; } return false; } std::string MakeErrorActionable(const error &err) { if (noError == err) { return err; } if (err.find(kCannotEstablishProxyConnection) != std::string::npos) { return kCheckYourProxySetup; } if (err.find(kCertificateVerifyFailed) != std::string::npos) { return kCheckYourFirewall; } if (err.find(kProxyAuthenticationRequired) != std::string::npos) { return kCheckYourProxySetup; } if (err.find(kCertificateValidationError) != std::string::npos) { return kCheckYourFirewall; } if (err.find(kUnacceptableCertificate) != std::string::npos) { return kCheckYourFirewall; } if (err.find(kCannotUpgradeToWebSocketConnection) != std::string::npos) { return kCheckYourFirewall; } if (err.find(kSSLException) != std::string::npos) { return kCheckYourFirewall; } if (err.find(kCannotWriteFile) != std::string::npos) { return "Check your user permissions"; } if (err.find(kIsSuspended) != std::string::npos) { return "The workspace is suspended, please check your payments"; } if (err.find(kRequestToServerFailedWithStatusCode403) != std::string::npos) { return "You do not have access to this workspace"; } if (err.find(kMissingWorkspaceID) != std::string::npos) { return "Please select a project"; } if (err.find(kDatabaseDiskMalformed) != std::string::npos) { return "Local database is corrupt. Please clear local data to recreate local database."; } if (err.find(kEndpointGoneError) != std::string::npos) { return kOutOfDatePleaseUpgrade; } return err; } } // namespace toggl
30.061303
96
0.583737
jiri
d517ae5cef38c055d56e799fd01cdaee86c9951d
897
cpp
C++
Kernel/Random.cpp
JamiKettunen/serenity
232da5cc188496f570ef55276a897f1095509c87
[ "BSD-2-Clause" ]
1
2020-01-07T06:21:11.000Z
2020-01-07T06:21:11.000Z
Kernel/Random.cpp
JamiKettunen/serenity
232da5cc188496f570ef55276a897f1095509c87
[ "BSD-2-Clause" ]
null
null
null
Kernel/Random.cpp
JamiKettunen/serenity
232da5cc188496f570ef55276a897f1095509c87
[ "BSD-2-Clause" ]
null
null
null
#include <Kernel/Arch/i386/CPU.h> #include <Kernel/Random.h> #include <Kernel/Devices/RandomDevice.h> static u32 random32() { if (g_cpu_supports_rdrand) { u32 value = 0; asm volatile( "1%=:\n" "rdrand %0\n" "jnc 1%=\n" : "=r"(value)); return value; } // FIXME: This sucks lol static u32 next = 1; next = next * 1103515245 + 12345; return next; } void get_good_random_bytes(u8* buffer, size_t buffer_size) { union { u8 bytes[4]; u32 value; } u; size_t offset = 4; for (size_t i = 0; i < buffer_size; ++i) { if (offset >= 4) { u.value = random32(); offset = 0; } buffer[i] = u.bytes[offset++]; } } void get_fast_random_bytes(u8* buffer, size_t buffer_size) { return get_good_random_bytes(buffer, buffer_size); }
21.357143
58
0.541806
JamiKettunen
d5196dddb00015bee4c17d4771e5a771efd09bff
5,064
cpp
C++
src/ComputerscareKnolyPobs.cpp
freddyz/computerscare-vcv-modules
f8e7b10e8b37a7f329f355d454e7aebed4b5cb5b
[ "BSD-3-Clause" ]
36
2018-07-31T08:38:58.000Z
2022-03-18T22:58:46.000Z
src/ComputerscareKnolyPobs.cpp
freddyz/computerscare-vcv-modules
f8e7b10e8b37a7f329f355d454e7aebed4b5cb5b
[ "BSD-3-Clause" ]
73
2018-08-20T10:12:25.000Z
2021-12-29T16:14:18.000Z
src/ComputerscareKnolyPobs.cpp
freddyz/computerscare-vcv-modules
f8e7b10e8b37a7f329f355d454e7aebed4b5cb5b
[ "BSD-3-Clause" ]
6
2019-07-08T02:09:57.000Z
2022-03-03T23:38:27.000Z
#include "Computerscare.hpp" #include "ComputerscarePolyModule.hpp" struct ComputerscareKnolyPobs; const int numKnobs = 16; const int numToggles = 16; struct ComputerscareKnolyPobs : ComputerscarePolyModule { ComputerscareSVGPanel* panelRef; enum ParamIds { KNOB, TOGGLES = KNOB + numKnobs, POLY_CHANNELS = TOGGLES + numToggles, GLOBAL_SCALE, GLOBAL_OFFSET, NUM_PARAMS }; enum InputIds { CHANNEL_INPUT, NUM_INPUTS }; enum OutputIds { POLY_OUTPUT, NUM_OUTPUTS }; enum LightIds { NUM_LIGHTS }; ComputerscareKnolyPobs() { config(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS); for (int i = 0; i < numKnobs; i++) { configParam(KNOB + i, 0.f, 10.f, 0.f, "Channel " + std::to_string(i + 1)); } configParam(POLY_CHANNELS, 1.f, 16.f, 16.f, "Poly Channels"); configParam(GLOBAL_SCALE, -2.f, 2.f, 1.f, "Scale"); configParam(GLOBAL_OFFSET, -10.f, 10.f, 0.f, "Offset", " volts"); } void process(const ProcessArgs &args) override { ComputerscarePolyModule::checkCounter(); float trim = params[GLOBAL_SCALE].getValue(); float offset = params[GLOBAL_OFFSET].getValue(); for (int i = 0; i < polyChannels; i++) { outputs[POLY_OUTPUT].setVoltage(params[KNOB + i].getValue()*trim + offset, i); } } void checkPoly() override { polyChannels = params[POLY_CHANNELS].getValue(); if (polyChannels == 0) { polyChannels = 16; params[POLY_CHANNELS].setValue(16); } outputs[POLY_OUTPUT].setChannels(polyChannels); } }; struct NoRandomSmallKnob : SmallKnob { NoRandomSmallKnob() { SmallKnob(); }; void randomize() override { return; } }; struct NoRandomMediumSmallKnob : RoundKnob { std::shared_ptr<Svg> enabledSvg = APP->window->loadSvg(asset::plugin(pluginInstance, "res/computerscare-medium-small-knob.svg")); NoRandomMediumSmallKnob() { setSvg(enabledSvg); RoundKnob(); }; void randomize() override { return; } }; struct DisableableSmoothKnob : RoundKnob { std::shared_ptr<Svg> enabledSvg = APP->window->loadSvg(asset::plugin(pluginInstance, "res/computerscare-medium-small-knob.svg")); std::shared_ptr<Svg> disabledSvg = APP->window->loadSvg(asset::plugin(pluginInstance, "res/computerscare-medium-small-knob-disabled.svg")); int channel = 0; bool disabled = false; ComputerscarePolyModule *module; DisableableSmoothKnob() { setSvg(enabledSvg); shadow->box.size = math::Vec(0, 0); shadow->opacity = 0.f; } void draw(const DrawArgs& args) override { if (module) { bool candidate = channel > module->polyChannels - 1; if (disabled != candidate) { setSvg(candidate ? disabledSvg : enabledSvg); dirtyValue = -20.f; disabled = candidate; } } else { } RoundKnob::draw(args); } }; struct ComputerscareKnolyPobsWidget : ModuleWidget { ComputerscareKnolyPobsWidget(ComputerscareKnolyPobs *module) { setModule(module); //setPanel(APP->window->loadSvg(asset::plugin(pluginInstance, "res/ComputerscareKnolyPobsPanel.svg"))); box.size = Vec(4 * 15, 380); { ComputerscareSVGPanel *panel = new ComputerscareSVGPanel(); panel->box.size = box.size; panel->setBackground(APP->window->loadSvg(asset::plugin(pluginInstance, "res/ComputerscareKnolyPobsPanel.svg"))); addChild(panel); } channelWidget = new PolyOutputChannelsWidget(Vec(1, 24), module, ComputerscareKnolyPobs::POLY_CHANNELS); addOutput(createOutput<PointingUpPentagonPort>(Vec(30, 22), module, ComputerscareKnolyPobs::POLY_OUTPUT)); addChild(channelWidget); addParam(createParam<NoRandomSmallKnob>(Vec(11, 54), module, ComputerscareKnolyPobs::GLOBAL_SCALE)); addParam(createParam<NoRandomMediumSmallKnob>(Vec(32, 57), module, ComputerscareKnolyPobs::GLOBAL_OFFSET)); float xx; float yy; float yInitial = 86; float ySpacing = 34; float yRightColumnOffset = 14.3 / 8; for (int i = 0; i < numKnobs; i++) { xx = 1.4f + 24.3 * (i - i % 8) / 8; yy = yInitial + ySpacing * (i % 8) + yRightColumnOffset * (i - i % 8) ; addLabeledKnob(std::to_string(i + 1), xx, yy, module, i, (i - i % 8) * 1.2 - 3 + (i == 8 ? 5 : 0), 2); } } void addLabeledKnob(std::string label, int x, int y, ComputerscareKnolyPobs *module, int index, float labelDx, float labelDy) { smallLetterDisplay = new SmallLetterDisplay(); smallLetterDisplay->box.size = Vec(5, 10); smallLetterDisplay->fontSize = 18; smallLetterDisplay->value = label; smallLetterDisplay->textAlign = 1; ParamWidget* pob = createParam<DisableableSmoothKnob>(Vec(x, y), module, ComputerscareKnolyPobs::KNOB + index); DisableableSmoothKnob* fader = dynamic_cast<DisableableSmoothKnob*>(pob); fader->module = module; fader->channel = index; addParam(fader); smallLetterDisplay->box.pos = Vec(x + labelDx, y - 12 + labelDy); addChild(smallLetterDisplay); } PolyOutputChannelsWidget* channelWidget; PolyChannelsDisplay* channelDisplay; DisableableSmoothKnob* fader; SmallLetterDisplay* smallLetterDisplay; }; Model *modelComputerscareKnolyPobs = createModel<ComputerscareKnolyPobs, ComputerscareKnolyPobsWidget>("computerscare-knolypobs");
28.449438
140
0.713863
freddyz
d51b24933749096659d55b0c829e2e8d7f77e053
660
hxx
C++
generated/include/vnx/addons/HttpComponent.hxx
MMX-World/vnx-addons
93dbf8d8cece4e127131fcaf2f15f92e74ed81e6
[ "MIT" ]
1
2021-09-11T04:05:14.000Z
2021-09-11T04:05:14.000Z
generated/include/vnx/addons/HttpComponent.hxx
MMX-World/vnx-addons
93dbf8d8cece4e127131fcaf2f15f92e74ed81e6
[ "MIT" ]
1
2022-02-18T12:27:09.000Z
2022-02-18T12:30:40.000Z
generated/include/vnx/addons/HttpComponent.hxx
MMX-World/vnx-addons
93dbf8d8cece4e127131fcaf2f15f92e74ed81e6
[ "MIT" ]
2
2020-09-25T05:11:28.000Z
2022-01-22T20:57:06.000Z
// AUTO GENERATED by vnxcppcodegen #ifndef INCLUDE_vnx_addons_HttpComponent_HXX_ #define INCLUDE_vnx_addons_HttpComponent_HXX_ #include <vnx/Type.h> #include <vnx/addons/package.hxx> #include <vnx/addons/HttpData.hxx> #include <vnx/addons/HttpRequest.hxx> #include <vnx/addons/HttpResponse.hxx> namespace vnx { namespace addons { struct HttpComponent { static const vnx::Hash64 VNX_TYPE_HASH; static const vnx::Hash64 VNX_CODE_HASH; static constexpr uint64_t VNX_TYPE_ID = 0x6ddcddab3925b2efull; HttpComponent() {} }; } // namespace vnx } // namespace addons namespace vnx { } // vnx #endif // INCLUDE_vnx_addons_HttpComponent_HXX_
16.5
63
0.768182
MMX-World
d5227f498e695a8a911b4396d0a4591609bc6724
356
hpp
C++
enginebase/enginecommon.hpp
krexspace/Vulkan
ad7ad71d224dc2e6edeb02ad84a6bd647fd4bf3a
[ "MIT" ]
1
2020-10-24T21:14:06.000Z
2020-10-24T21:14:06.000Z
enginebase/enginecommon.hpp
krexspace/Vulkan
ad7ad71d224dc2e6edeb02ad84a6bd647fd4bf3a
[ "MIT" ]
null
null
null
enginebase/enginecommon.hpp
krexspace/Vulkan
ad7ad71d224dc2e6edeb02ad84a6bd647fd4bf3a
[ "MIT" ]
null
null
null
#pragma once #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <vector> #define GLM_FORCE_RADIANS #define GLM_FORCE_DEPTH_ZERO_TO_ONE #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <vulkan/vulkan.h> #include "vulkanexamplebase.h" #include "VulkanTexture.hpp"
20.941176
39
0.769663
krexspace
d5245341aeb1e6134b1d061de8a75a7c3b891e0a
9,625
cpp
C++
quantitative_finance/L2/tests/MCEuropeanHestonEngine/src/test.cpp
KitAway/Vitis_Libraries
208ada169cd8ddeac0d26b2568343fab6f968331
[ "Apache-2.0" ]
1
2021-06-14T17:02:06.000Z
2021-06-14T17:02:06.000Z
quantitative_finance/L2/tests/MCEuropeanHestonEngine/src/test.cpp
KitAway/Vitis_Libraries
208ada169cd8ddeac0d26b2568343fab6f968331
[ "Apache-2.0" ]
null
null
null
quantitative_finance/L2/tests/MCEuropeanHestonEngine/src/test.cpp
KitAway/Vitis_Libraries
208ada169cd8ddeac0d26b2568343fab6f968331
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2019 Xilinx, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <iostream> #include "utils.hpp" #ifndef HLS_TEST #include "xcl2.hpp" #endif #define KN 1 #include <math.h> #include "kernel_mceuropeanengine.hpp" #define LENGTH(a) (sizeof(a) / sizeof(a[0])) #define XCL_BANK(n) (((unsigned int)(n)) | XCL_MEM_TOPOLOGY) #define XCL_BANK0 XCL_BANK(0) #define XCL_BANK1 XCL_BANK(1) #define XCL_BANK2 XCL_BANK(2) #define XCL_BANK3 XCL_BANK(3) #define XCL_BANK4 XCL_BANK(4) #define XCL_BANK5 XCL_BANK(5) #define XCL_BANK6 XCL_BANK(6) #define XCL_BANK7 XCL_BANK(7) #define XCL_BANK8 XCL_BANK(8) #define XCL_BANK9 XCL_BANK(9) #define XCL_BANK10 XCL_BANK(10) #define XCL_BANK11 XCL_BANK(11) #define XCL_BANK12 XCL_BANK(12) #define XCL_BANK13 XCL_BANK(13) #define XCL_BANK14 XCL_BANK(14) #define XCL_BANK15 XCL_BANK(15) class ArgParser { public: ArgParser(int& argc, const char** argv) { for (int i = 1; i < argc; ++i) mTokens.push_back(std::string(argv[i])); } bool getCmdOption(const std::string option, std::string& value) const { std::vector<std::string>::const_iterator itr; itr = std::find(this->mTokens.begin(), this->mTokens.end(), option); if (itr != this->mTokens.end() && ++itr != this->mTokens.end()) { value = *itr; return true; } return false; } private: std::vector<std::string> mTokens; }; bool print_result(double* out1, double golden, double tol, int loop_nm) { bool passed = true; for (int i = 0; i < loop_nm; ++i) { if (std::fabs(out1[i] - golden) > tol) { std::cout << "loop_nm: " << loop_nm << ", Expected value: " << golden << ::std::endl; std::cout << "FPGA result: " << out1[0] << std::endl; passed = false; } } return passed; } int main(int argc, const char* argv[]) { std::cout << "\n----------------------MC(European) Engine-----------------\n"; // cmd parser ArgParser parser(argc, argv); std::string xclbin_path; if (!parser.getCmdOption("-xclbin", xclbin_path)) { std::cout << "ERROR:xclbin path is not set!\n"; return 1; } struct timeval st_time, end_time; DtUsed* out0_a = aligned_alloc<DtUsed>(OUTDEP); DtUsed* out0_b = aligned_alloc<DtUsed>(OUTDEP); // test data unsigned int timeSteps = 12; DtUsed requiredTolerance = 0.02; DtUsed underlying = 36; DtUsed riskFreeRate = 0.06; DtUsed sigma = 0.001; DtUsed v0 = 0.04; DtUsed theta = 0.04; DtUsed kappa = 1.0; DtUsed rho = 0.0; DtUsed dividendYield = 0.0; DtUsed strike = 40; bool optionType = 1; DtUsed timeLength = 1; unsigned int requiredSamples = 48128; // 0;//1024;//0; unsigned int maxSamples = 0; // unsigned int loop_nm = 1; // 1000; DtUsed golden = 3.83; DtUsed tol = 0.02; #ifdef HLS_TEST int num_rep = 1; #else int num_rep = 1; std::string num_str; if (parser.getCmdOption("-rep", num_str)) { try { num_rep = std::stoi(num_str); } catch (...) { num_rep = 1; } } if (num_rep > 20) { num_rep = 20; std::cout << "WARNING: limited repeat to " << num_rep << " times\n."; } if (parser.getCmdOption("-p", num_str)) { try { requiredSamples = std::stoi(num_str); } catch (...) { requiredSamples = 48128; } } std::string mode_emu = "hw"; if (std::getenv("XCL_EMULATION_MODE") != nullptr) { mode_emu = std::getenv("XCL_EMULATION_MODE"); } std::cout << "[INFO]Running in " << mode_emu << " mode" << std::endl; if (mode_emu.compare("hw_emu") == 0) { requiredSamples = 1024; golden = 3.92513; tol = 1e-5; } #endif #ifdef HLS_TEST kernel_mc_0(loop_nm, underlying, riskFreeRate, sigma, v0, theta, kappa, rho, dividendYield, optionType, strike, timeLength, timeSteps, requiredSamples, maxSamples, requiredTolerance, out0_b); print_result(out0_b, golden, tol, 1); #else std::vector<cl::Device> devices = xcl::get_xil_devices(); cl::Device device = devices[0]; cl::Context context(device); #ifdef SW_EMU_TEST // hls::exp and hls::log have bug in multi-thread. cl::CommandQueue q(context, device, CL_QUEUE_PROFILING_ENABLE); // | CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE); #else cl::CommandQueue q(context, device, CL_QUEUE_PROFILING_ENABLE | CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE); #endif std::string devName = device.getInfo<CL_DEVICE_NAME>(); std::cout << "Selected Device " << devName << "\n"; cl::Program::Binaries xclbins = xcl::import_binary_file(xclbin_path); devices.resize(1); cl::Program program(context, devices, xclbins); cl::Kernel kernel0[2]; for (int i = 0; i < 2; ++i) { kernel0[i] = cl::Kernel(program, "kernel_mc_0"); } std::cout << "Kernel has been created\n"; cl_mem_ext_ptr_t mext_out_a[KN]; cl_mem_ext_ptr_t mext_out_b[KN]; #ifndef USE_HBM mext_out_a[0] = {XCL_MEM_DDR_BANK0, out0_a, 0}; mext_out_b[0] = {XCL_MEM_DDR_BANK0, out0_b, 0}; #else mext_out_a[0] = {XCL_BANK0, out0_a, 0}; mext_out_b[0] = {XCL_BANK0, out0_b, 0}; #endif cl::Buffer out_buff_a[KN]; cl::Buffer out_buff_b[KN]; for (int i = 0; i < KN; i++) { out_buff_a[i] = cl::Buffer(context, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE, (size_t)(OUTDEP * sizeof(DtUsed)), &mext_out_a[i]); out_buff_b[i] = cl::Buffer(context, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE, (size_t)(OUTDEP * sizeof(DtUsed)), &mext_out_b[i]); } std::vector<std::vector<cl::Event> > kernel_events(num_rep); std::vector<std::vector<cl::Event> > read_events(num_rep); for (int i = 0; i < num_rep; ++i) { kernel_events[i].resize(KN); read_events[i].resize(1); } int j = 0; kernel0[0].setArg(j++, loop_nm); kernel0[0].setArg(j++, underlying); kernel0[0].setArg(j++, riskFreeRate); kernel0[0].setArg(j++, sigma); kernel0[0].setArg(j++, v0); kernel0[0].setArg(j++, theta); kernel0[0].setArg(j++, kappa); kernel0[0].setArg(j++, rho); kernel0[0].setArg(j++, dividendYield); kernel0[0].setArg(j++, optionType); kernel0[0].setArg(j++, strike); kernel0[0].setArg(j++, timeLength); kernel0[0].setArg(j++, timeSteps); kernel0[0].setArg(j++, requiredSamples); kernel0[0].setArg(j++, maxSamples); kernel0[0].setArg(j++, requiredTolerance); kernel0[0].setArg(j++, out_buff_a[0]); j = 0; kernel0[1].setArg(j++, loop_nm); kernel0[1].setArg(j++, underlying); kernel0[1].setArg(j++, riskFreeRate); kernel0[1].setArg(j++, sigma); kernel0[1].setArg(j++, v0); kernel0[1].setArg(j++, theta); kernel0[1].setArg(j++, kappa); kernel0[1].setArg(j++, rho); kernel0[1].setArg(j++, dividendYield); kernel0[1].setArg(j++, optionType); kernel0[1].setArg(j++, strike); kernel0[1].setArg(j++, timeLength); kernel0[1].setArg(j++, timeSteps); kernel0[1].setArg(j++, requiredSamples); kernel0[1].setArg(j++, maxSamples); kernel0[1].setArg(j++, requiredTolerance); kernel0[1].setArg(j++, out_buff_b[0]); std::vector<cl::Memory> out_vec[2]; //{out_buff[0]}; for (int i = 0; i < KN; ++i) { out_vec[0].push_back(out_buff_a[i]); out_vec[1].push_back(out_buff_b[i]); } q.finish(); gettimeofday(&st_time, 0); for (int i = 0; i < num_rep; ++i) { int use_a = i & 1; if (use_a) { if (i > 1) { q.enqueueTask(kernel0[0], &read_events[i - 2], &kernel_events[i][0]); } else { q.enqueueTask(kernel0[0], nullptr, &kernel_events[i][0]); } } else { if (i > 1) { q.enqueueTask(kernel0[1], &read_events[i - 2], &kernel_events[i][0]); } else { q.enqueueTask(kernel0[1], nullptr, &kernel_events[i][0]); } } if (use_a) { q.enqueueMigrateMemObjects(out_vec[0], CL_MIGRATE_MEM_OBJECT_HOST, &kernel_events[i], &read_events[i][0]); } else { q.enqueueMigrateMemObjects(out_vec[1], CL_MIGRATE_MEM_OBJECT_HOST, &kernel_events[i], &read_events[i][0]); } } q.flush(); q.finish(); gettimeofday(&end_time, 0); int exec_time = tvdiff(&st_time, &end_time); std::cout << "FPGA execution time of " << num_rep << " runs:" << exec_time / 1000 << " ms\n" << "Average executiom per run: " << exec_time / num_rep / 1000 << " ms\n"; if (num_rep > 1) { bool passed = print_result(out0_a, golden, tol, loop_nm); if (!passed) { return -1; } } bool passed = print_result(out0_b, golden, tol, loop_nm); if (!passed) { return -1; } std::cout << "Execution time " << tvdiff(&st_time, &end_time) << std::endl; #endif return 0; }
33.189655
118
0.601247
KitAway
d524f356eed26aa374d23d86ea2106b36c77c829
4,084
cc
C++
runtime/onert/core/src/interp/operations/MaxPool2D.cc
wateret/ONE_private
9789c52633e665d2e10273d88d6f7970faa8aee9
[ "Apache-2.0" ]
null
null
null
runtime/onert/core/src/interp/operations/MaxPool2D.cc
wateret/ONE_private
9789c52633e665d2e10273d88d6f7970faa8aee9
[ "Apache-2.0" ]
null
null
null
runtime/onert/core/src/interp/operations/MaxPool2D.cc
wateret/ONE_private
9789c52633e665d2e10273d88d6f7970faa8aee9
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2019 Samsung Electronics Co., Ltd. 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 <cker/operation/MaxPool.h> #include "OperationUtil.h" #include "interp/Registration.h" #include "ir/operation/MaxPool2D.h" #include "util/Utils.h" #include "util/ShapeInference.h" #include "misc/polymorphic_downcast.h" namespace onert { namespace interp { namespace { void prepareMaxPool2D(ExecEnv *env, const ir::Operation &node) { const auto in_index = node.getInputs().at(0); const auto out_index = node.getOutputs().at(0); const auto in_tensor = env->tensorAt(in_index); assert(in_tensor->num_dimensions() == 4); UNUSED_RELEASE(in_tensor); const auto output_info = env->graph().operands().at(out_index).info(); if (output_info.total_size() == 0) { // Handle unspecified output shape const auto &maxpool_node = nnfw::misc::polymorphic_downcast<const ir::operation::MaxPool2D &>(node); const auto infered_output_shapes = shape_inference::inferMaxPoolShape(in_tensor->tensorInfo().shape(), maxpool_node.param()); env->allocateIfNeeded(out_index, {infered_output_shapes[0], output_info.typeInfo()}); } else { env->allocateIfNeeded(out_index, output_info); } auto out_tensor = env->tensorAt(out_index); UNUSED_RELEASE(out_tensor); // Handle same ifm & ofm data type only assert(in_tensor->data_type() == out_tensor->data_type()); assert(out_tensor->num_dimensions() == 4); } void invoke(const ITensor *in_tensor, const ITensor *out_tensor, const ir::operation::MaxPool2D::Param &param) { // TODO support NCHW frontend const auto ifm_shape = in_tensor->tensorInfo().shape().asFeature(ir::Layout::NHWC); const auto ofm_shape = out_tensor->tensorInfo().shape().asFeature(ir::Layout::NHWC); const auto padding = ir::calculatePadding(param.padding, ifm_shape, ofm_shape, param.stride, param.kw, param.kh); // Calculate nnfw::cker::PoolParams cker_param; calculateActivationRange(param.activation, &cker_param.float_activation_min, &cker_param.float_activation_max); cker_param.filter_width = param.kw; cker_param.filter_height = param.kh; cker_param.padding_values.width = padding.left; cker_param.padding_values.height = padding.top; cker_param.stride_width = param.stride.horizontal; cker_param.stride_height = param.stride.vertical; const auto in_shape = convertShape(in_tensor->tensorInfo().shape()); const auto out_shape = convertShape(out_tensor->tensorInfo().shape()); const float *in_ptr = reinterpret_cast<const float *>(in_tensor->bufferRO()); float *out_ptr = reinterpret_cast<float *>(out_tensor->buffer()); nnfw::cker::MaxPool(cker_param, in_shape, in_ptr, out_shape, out_ptr); } void invokeMaxPool2D(const ExecEnv *env, const ir::Operation &node) { const auto &maxpool_node = nnfw::misc::polymorphic_downcast<const ir::operation::MaxPool2D &>(node); const auto in_index = node.getInputs().at(0); const auto out_index = node.getOutputs().at(0); const auto in_tensor = env->tensorAt(in_index); const auto out_tensor = env->tensorAt(out_index); const auto data_type = in_tensor->data_type(); if (data_type == ir::DataType::FLOAT32) { invoke(in_tensor, out_tensor, maxpool_node.param()); } else { throw std::runtime_error{"NYI: Support float32 only"}; } } } // namespace OpKernel *getMaxPool2D() { static OpKernel kernel = {prepareMaxPool2D, invokeMaxPool2D}; return &kernel; } } // namespace interp } // namespace onert
32.672
98
0.724045
wateret
d5251f2b5357508d40fdcde5553292815c868768
3,120
cpp
C++
jni/src/gui/layout.cpp
soulthreads/asteroid-racing
85dfe18c3d6adf0e40c6b843e23c78ca7b7ee793
[ "BSD-2-Clause" ]
null
null
null
jni/src/gui/layout.cpp
soulthreads/asteroid-racing
85dfe18c3d6adf0e40c6b843e23c78ca7b7ee793
[ "BSD-2-Clause" ]
null
null
null
jni/src/gui/layout.cpp
soulthreads/asteroid-racing
85dfe18c3d6adf0e40c6b843e23c78ca7b7ee793
[ "BSD-2-Clause" ]
1
2019-10-19T04:27:38.000Z
2019-10-19T04:27:38.000Z
#include "layout.h" #include "element.h" #include "button.h" #include "list.h" Layout::Layout() { } void Layout::draw () { if (token != engine.token) init (); glUseProgram (program); glUniformMatrix4fv (u_MvpMatrixHandle, 1, GL_FALSE, value_ptr (engine.orthoMatrix)); vertices.clear (); for (auto &e : elements) { auto v = e->getVertices (); vertices.insert (end (vertices), begin (v), end (v)); for (auto &t : e->getTexts ()) { text->addText (t.text, t); } } text->addText ("name", name); glVertexAttribPointer (a_PositionHandle, 2, GL_FLOAT, GL_FALSE, Element::stride, &vertices[0]); glEnableVertexAttribArray (a_PositionHandle); glVertexAttribPointer (a_ColorHandle, 4, GL_FLOAT, GL_FALSE, Element::stride, &vertices[2]); glDisable (GL_DEPTH_TEST); glEnable (GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDrawArrays (GL_TRIANGLES, 0, vertices.size () / Element::components); glDisable (GL_BLEND); glEnable (GL_DEPTH_TEST); } void Layout::init () { token = engine.token; program = buildProgramFromAssets ("shaders/gui.vsh", "shaders/gui.fsh"); validateProgram (program); u_MvpMatrixHandle = glGetUniformLocation (program, "u_MvpMatrix"); a_PositionHandle = glGetAttribLocation (program, "a_Position"); a_ColorHandle = glGetAttribLocation (program, "a_Color"); } void Layout::touchDown (float x, float y) { int index = 0; for (auto &e : elements) { auto r = e->getRect (); if ((x >= r.x) && (x <= r.x+r.w) && (y >= r.y-r.h) && (y <= r.y)) { touchIndex = index; px = x; py = y; return; } index++; } touchIndex = -1; } void Layout::touchMove (float x, float y) { if ((touchIndex != -1) && (touchIndex < elements.size ()) && elements[touchIndex]->isScrollable ()) { elements[touchIndex]->move (x-px, y-py); px = x; py = y; } } void Layout::touchUp (float x, float y) { if ((touchIndex != -1) && (touchIndex < elements.size ())) { auto r = elements[touchIndex]->getRect (); if ((x >= r.x) && (x <= r.x+r.w) && (y >= r.y-r.h) && (y <= r.y)) { elements[touchIndex]->run (x, y); } } touchIndex = -1; } void Layout::addButton (const string &label, Rect rect, vec4 bgColor, vec4 fgColor, function<void()> f) { elements.push_back (unique_ptr<Element> (new Button (label, rect, bgColor, fgColor, f))); } void Layout::setName(const string layoutName) { name = textUnit {vec2 (0, 1), vec4 (1), 2, A_CENTER, A_PLUS, layoutName}; } void Layout::addList (const string name, const vector<string> listElements, Rect rect, vec4 bgColor, vec4 fgColor, function<void()> f) { elements.push_back (unique_ptr<Element> (new List (listElements, rect, bgColor, fgColor, f))); elements.back ()->setId (name); } Element& Layout::getById (const string id) { for (auto &e : elements) { if (e->getId () == id) { return *e; } } }
29.158879
105
0.593269
soulthreads
d525ab58ee9f269753a40b884dcf7dcc26dc82ef
563
hpp
C++
include/RED4ext/Scripting/Natives/Generated/quest/Int32FactDBProvider.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
42
2020-12-25T08:33:00.000Z
2022-03-22T14:47:07.000Z
include/RED4ext/Scripting/Natives/Generated/quest/Int32FactDBProvider.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
38
2020-12-28T22:36:06.000Z
2022-02-16T11:25:47.000Z
include/RED4ext/Scripting/Natives/Generated/quest/Int32FactDBProvider.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
20
2020-12-28T22:17:38.000Z
2022-03-22T17:19:01.000Z
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> #include <RED4ext/Common.hpp> #include <RED4ext/CName.hpp> #include <RED4ext/Scripting/Natives/Generated/quest/IInt32ValueProvider.hpp> namespace RED4ext { namespace quest { struct Int32FactDBProvider : quest::IInt32ValueProvider { static constexpr const char* NAME = "questInt32FactDBProvider"; static constexpr const char* ALIAS = NAME; CName factName; // 30 }; RED4EXT_ASSERT_SIZE(Int32FactDBProvider, 0x38); } // namespace quest } // namespace RED4ext
24.478261
76
0.765542
jackhumbert
d527719f40831b53b8bdfea0e8103dab12e34367
20,321
cpp
C++
AlloReceiver/RTSPCubemapSourceClient.cpp
tiborgo/AlloStreamer
bf91586a88c3aec8e5603e5606caf3c3d0d53139
[ "BSD-3-Clause" ]
5
2016-04-01T09:43:00.000Z
2019-06-09T19:04:18.000Z
AlloReceiver/RTSPCubemapSourceClient.cpp
tiborgo/AlloStreamer
bf91586a88c3aec8e5603e5606caf3c3d0d53139
[ "BSD-3-Clause" ]
null
null
null
AlloReceiver/RTSPCubemapSourceClient.cpp
tiborgo/AlloStreamer
bf91586a88c3aec8e5603e5606caf3c3d0d53139
[ "BSD-3-Clause" ]
3
2016-04-08T00:34:43.000Z
2019-11-15T19:21:13.000Z
#include <boost/algorithm/string.hpp> #include <boost/algorithm/string_regex.hpp> #include "H264NALUSink.hpp" #include "H264CubemapSource.h" #include "RTSPCubemapSourceClient.hpp" void RTSPCubemapSourceClient::setOnDidConnect(const std::function<void (RTSPCubemapSourceClient*, CubemapSource*)>& onDidConnect) { this->onDidConnect = onDidConnect; } void RTSPCubemapSourceClient::shutdown(int exitCode) { } void RTSPCubemapSourceClient::subsessionAfterPlaying(void* clientData) { // Begin by closing this media subsession's stream: MediaSubsession* subsession = (MediaSubsession*)clientData; Medium::close(subsession->sink); subsession->sink = NULL; // Next, check whether *all* subsessions' streams have now been closed: MediaSession& session = subsession->parentSession(); MediaSubsessionIterator iter(session); while ((subsession = iter.next()) != NULL) { if (subsession->sink != NULL) return; // this subsession is still active } // All subsessions' streams have now been closed //sessionAfterPlaying(); } void RTSPCubemapSourceClient::checkForPacketArrival(void* self_) { // RTSPCubemapSourceClient* self = (RTSPCubemapSourceClient*)self_; // //// Check each subsession, to see whether it has received data packets: //unsigned numSubsessionsChecked = 0; //unsigned numSubsessionsWithReceivedData = 0; //unsigned numSubsessionsThatHaveBeenSynced = 0; //MediaSubsessionIterator iter(*self->session); //MediaSubsession* subsession; //while ((subsession = iter.next()) != NULL) //{ // RTPSource* src = subsession->rtpSource(); // if (src == NULL) continue; // ++numSubsessionsChecked; // if (src->receptionStatsDB().numActiveSourcesSinceLastReset() > 0) // { // // At least one data packet has arrived // ++numSubsessionsWithReceivedData; // } // if (src->hasBeenSynchronizedUsingRTCP()) // { // ++numSubsessionsThatHaveBeenSynced; // } //} //unsigned numSubsessionsToCheck = numSubsessionsChecked; // struct timeval timeNow; // gettimeofday(&timeNow, NULL); // char timestampStr[100]; // sprintf(timestampStr, "%ld%03ld", timeNow.tv_sec, (long)(timeNow.tv_usec / 1000)); // self->envir() << "Data packets have begun arriving [" << timestampStr << "]\007\n"; // return; //// No luck, so reschedule this check again, after a delay: //int uSecsToDelay = 100000; // 100 ms //TaskToken arrivalCheckTimerTask = self->session->envir().taskScheduler().scheduleDelayedTask(uSecsToDelay, // (TaskFunc*)checkForPacketArrival, self); } void RTSPCubemapSourceClient::continueAfterDESCRIBE2(RTSPClient* self_, int resultCode, char* resultString) { RTSPCubemapSourceClient* self = (RTSPCubemapSourceClient*)self_; static int count = 0; char* sdpDescription = resultString; //self->envir() << "Opened URL \"" << self->url() << "\", returning a SDP description:\n" << sdpDescription << "\n"; if (count == 0) { self->sendDescribeCommand(continueAfterDESCRIBE2); } count++; } void RTSPCubemapSourceClient::continueAfterPLAY(RTSPClient* self_, int resultCode, char* resultString) { RTSPCubemapSourceClient* self = (RTSPCubemapSourceClient*)self_; if (resultCode != 0) { self->envir() << "Failed to start playing session: " << resultString << "\n"; delete[] resultString; self->shutdown(); return; } else { self->envir() << "Started playing session\n"; } delete[] resultString; // Figure out how long to delay (if at all) before shutting down, or // repeating the playing char const* actionString = "Data is being streamed"; self->envir() << actionString << "...\n"; // Watch for incoming packets (if desired): checkForPacketArrival(self); //checkInterPacketGaps(NULL); //ourClient->sendDescribeCommand(continueAfterDESCRIBE2); } void RTSPCubemapSourceClient::periodicQOSMeasurement(void* self_) { RTSPCubemapSourceClient* self = (RTSPCubemapSourceClient*)self_; double totalKBytes = 0.0; unsigned int totalPacketsReceived = 0; unsigned int totalPacketsExpected = 0; for (MediaSubsession* subsession : self->subsessions) { RTPSource* src = subsession->rtpSource(); RTPReceptionStatsDB::Iterator statsIter(src->receptionStatsDB()); RTPReceptionStats* stats; while ((stats = statsIter.next(True)) != NULL) { totalKBytes += stats->totNumKBytesReceived(); totalPacketsReceived += stats->totNumPacketsReceived(); totalPacketsExpected += stats->totNumPacketsExpected(); } } double totalKBytesInInterval = totalKBytes - self->lastTotalKBytes; unsigned int totalPacketsReceivedInInterval = totalPacketsReceived - self->lastTotalPacketsReceived; unsigned int totalPacketsExpectedInInterval = totalPacketsExpected - self->lastTotalPacketsExpected; self->lastTotalKBytes = totalKBytes; self->lastTotalPacketsReceived = totalPacketsReceived; self->lastTotalPacketsExpected = totalPacketsExpected; unsigned int totalPacketsLostInInterval = totalPacketsExpectedInInterval - totalPacketsReceivedInInterval; std::cout << "Client: " << std::setprecision(10) << std::setiosflags(std::ios::fixed) << std::setprecision(1) <<totalKBytesInInterval/10 * 8 / 1000 << " MBit/s; " << " packets received: " << totalPacketsReceivedInInterval << "; packets lost: " << totalPacketsLostInInterval << "; packet loss: " << std::setprecision(2) << (double)totalPacketsLostInInterval / totalPacketsReceivedInInterval * 100.0 << "%" << std::endl; self->envir().taskScheduler().scheduleDelayedTask(10000000, (TaskFunc*)RTSPCubemapSourceClient::periodicQOSMeasurement, self); } void RTSPCubemapSourceClient::subsessionByeHandler(void* clientData) { struct timeval timeNow; gettimeofday(&timeNow, NULL); MediaSubsession* subsession = (MediaSubsession*)clientData; subsession->sink->envir() << "Received RTCP \"BYE\" on \"" << subsession->mediumName() << "/" << subsession->codecName() << "\" subsession\n"; // Act now as if the subsession had closed: subsessionAfterPlaying(subsession); } void RTSPCubemapSourceClient::createOutputFiles(char const* periodicFilenameSuffix) { char outFileName[1000]; // Create and start "FileSink"s for each subsession: /*std::vector<MediaSubsession*> subsessions; for (MediaSession* session : sessions) { MediaSubsessionIterator iter(*session); MediaSubsession* subsession = iter.next(); if (subsession->readSource() == NULL) continue; // was not initiated // Create an output file for each desired stream: // Output file name is // "<filename-prefix><medium_name>-<codec_name>-<counter><periodicFilenameSuffix>" static unsigned streamCounter = 0; sprintf(outFileName, "%s-%s-%d%s", subsession->mediumName(), subsession->codecName(), ++streamCounter, periodicFilenameSuffix); subsessions.push_back(subsession); }*/ // Create CubemapSource based on discovered stream bool isH264 = true; for (MediaSubsession* subsession : subsessions) { if (strcmp(subsession->mediumName(), "video") != 0 || strcmp(subsession->codecName(), "H264") != 0) { isH264 = false; } } if (isH264) { std::vector<H264NALUSink*> h264Sinks; std::vector<MediaSink*> sinks; for (int i = 0; i < (std::min)(subsessions.size(), (size_t)(StereoCubemap::MAX_EYES_COUNT * Cubemap::MAX_FACES_COUNT)); i++) { H264NALUSink* sink = H264NALUSink::createNew(envir(), sinkBufferSize, format, subsessions[i], robustSyncing); subsessions[i]->sink = sink; h264Sinks.push_back(sink); sinks.push_back(sink); } if (onDidConnect) { onDidConnect(this, new H264CubemapSource(h264Sinks, format, matchStereoPairs, robustSyncing, maxFrameMapSize)); } } for (MediaSubsession* subsession : subsessions) { if (subsession->sink == NULL) { envir() << "Failed to create FileSink for \"" << outFileName << "\": " << subsession->parentSession().envir().getResultMsg() << "\n"; } else { envir() << "Outputting data from the \"" << subsession->mediumName() << "/" << subsession->codecName() << "\" subsession to \"" << outFileName << "\"\n"; subsession->sink->startPlaying(*(subsession->readSource()), subsessionAfterPlaying, subsession); // Also set a handler to be called if a RTCP "BYE" arrives // for this subsession: if (subsession->rtcpInstance() != NULL) { subsession->rtcpInstance()->setByeHandler(subsessionByeHandler, subsession); } } } } void RTSPCubemapSourceClient::setupStreams() { //static MediaSubsessionIterator* setupIter = NULL; static std::vector<MediaSubsession*>::iterator setupIter = subsessions.begin(); //if (setupIter == NULL) setupIter = new MediaSubsessionIterator(*session); //for (MediaSubsession* subsession : subsessions) // { while (setupIter != subsessions.end()) { subsession = *setupIter; // We have another subsession left to set up: if (subsession->clientPortNum() == 0) continue; // port # was not set //this->subsession = subsession; sendSetupCommand(*subsession, continueAfterSETUP); setupIter++; return; } // We're done setting up subsessions. //delete setupIter; // } // Create output files: createOutputFiles(""); for (MediaSubsession* subsession : subsessions) { // Finally, start playing each subsession, to start the data flow: double initialSeekTime = 0.0f; double duration = subsession->parentSession().playEndTime() - initialSeekTime; // use SDP end time double endTime; endTime = initialSeekTime; endTime = -1.0f; char* initialAbsoluteSeekTime = NULL; char const* absStartTime = initialAbsoluteSeekTime != NULL ? initialAbsoluteSeekTime : subsession->parentSession().absStartTime(); if (absStartTime != NULL) { // Either we or the server have specified that seeking should be done by 'absolute' time: sendPlayCommand(subsession->parentSession(), continueAfterPLAY, absStartTime, subsession->parentSession().absEndTime(), 1.0); } else { // Normal case: Seek by relative time (NPT): sendPlayCommand(subsession->parentSession(), continueAfterPLAY, initialSeekTime, endTime, 1.0); } } } void RTSPCubemapSourceClient::continueAfterSETUP(RTSPClient* self_, int resultCode, char* resultString) { static int setups = 0; setups++; RTSPCubemapSourceClient* self = (RTSPCubemapSourceClient*)self_; if (resultCode == 0) { self->envir() << "Setup \"" << self->subsession->mediumName() << "/" << self->subsession->codecName() << "\" subsession ("; if (self->subsession->rtcpIsMuxed()) { self->envir() << "client port " << self->subsession->clientPortNum(); } else { self->envir() << "client ports " << self->subsession->clientPortNum() << "-" << self->subsession->clientPortNum() + 1; } self->envir() << ")\n"; } else { self->envir() << "Failed to setup \"" << self->subsession->mediumName() << "/" << self->subsession->codecName() << "\" subsession: " << resultString << "\n"; } delete[] resultString; // Set up the next subsession, if any: self->setupStreams(); } void RTSPCubemapSourceClient::continueAfterDESCRIBE(RTSPClient* self_, int resultCode, char* resultString) { RTSPCubemapSourceClient* self = (RTSPCubemapSourceClient*)self_; if (resultCode != 0) { self->envir() << "Failed to get a SDP description for the URL \"" << self->url() << "\": " << resultString << "\n"; delete[] resultString; self->shutdown(); } char* sdpDescription = resultString; //self->envir() << "Opened URL \"" << self->url() << "\", returning a SDP description:\n" << sdpDescription << "\n"; // Parse SDP description and extract subsession information std::vector<std::string> sdpLines; boost::algorithm::split_regex(sdpLines, sdpDescription, boost::regex("\nm=")); std::string header = sdpLines[0]; sdpLines.erase(sdpLines.begin()); std::transform(sdpLines.begin(), sdpLines.end(), sdpLines.begin(), [](std::string &subsession){ return "m=" + subsession + "\n"; }); delete[] sdpDescription; for (int i = 0; i < sdpLines.size(); i++) { // Create a media session object from this SDP description: TaskScheduler* scheduler = BasicTaskScheduler::createNew(); BasicUsageEnvironment* env = BasicUsageEnvironment::createNew(*scheduler); self->envs.push_back(env); MediaSession* session = MediaSession::createNew(*env, (header + sdpLines[i]).c_str()); std::cout << "created session" << std::endl; if (session == NULL) { self->envir() << "Failed to create a MediaSession object from the SDP description: " << env->getResultMsg() << "\n"; self->shutdown(); } else if (!session->hasSubsessions()) { self->envir() << "This session has no media subsessions (i.e., no \"m=\" lines)\n"; self->shutdown(); } // Then, setup the "RTPSource"s for the session: MediaSubsessionIterator iter(*session); MediaSubsession *subsession; Boolean madeProgress = False; while ((subsession = iter.next()) != NULL) { self->subsessions.push_back(subsession); if (!subsession->initiate()) { self->envir() << "Unable to create receiver for \"" << subsession->mediumName() << "/" << subsession->codecName() << "\" subsession: " << env->getResultMsg() << "\n"; } else { self->envir() << "Created receiver for \"" << subsession->mediumName() << "/" << subsession->codecName() << "\" subsession ("; if (subsession->rtcpIsMuxed()) { self->envir() << "client port " << subsession->clientPortNum(); } else { self->envir() << "client ports " << subsession->clientPortNum() << "-" << subsession->clientPortNum() + 1; } self->envir() << ")\n"; madeProgress = True; if (subsession->rtpSource() != NULL) { // Because we're saving the incoming data, rather than playing // it in real time, allow an especially large time threshold // (1 second) for reordering misordered incoming packets: unsigned const thresh = 100000; // 1 second subsession->rtpSource()->setPacketReorderingThresholdTime(thresh); // Set the RTP source's OS socket buffer size as appropriate - either if we were explicitly asked (using -B), // or if the desired FileSink buffer size happens to be larger than the current OS socket buffer size. // (The latter case is a heuristic, on the assumption that if the user asked for a large FileSink buffer size, // then the input data rate may be large enough to justify increasing the OS socket buffer size also.) int socketNum = subsession->rtpSource()->RTPgs()->socketNum(); unsigned curBufferSize = getReceiveBufferSize(*env, socketNum); if (self->sinkBufferSize > curBufferSize) { unsigned newBufferSize = self->sinkBufferSize; newBufferSize = setReceiveBufferTo(*env, socketNum, newBufferSize); } } // } // } // else // { // if (subsession->clientPortNum() == 0) // { // *env << "No client port was specified for the \"" // << subsession->mediumName() // << "/" << subsession->codecName() // << "\" subsession. (Try adding the \"-p <portNum>\" option.)\n"; // } // else // { // madeProgress = True; // } } } //if (!madeProgress) shutdown(); } // Perform additional 'setup' on each subsession, before playing them: self->setupStreams(); self->envir().taskScheduler().scheduleDelayedTask(10000000, (TaskFunc*)RTSPCubemapSourceClient::periodicQOSMeasurement, self); for (int i = 0; i < self->envs.size(); i++) { boost::thread* abc = new boost::thread(boost::bind(&TaskScheduler::doEventLoop, &self->envs[i]->taskScheduler(), nullptr)); self->sessionThreads.push_back(boost::shared_ptr<boost::thread>(abc)); } } void RTSPCubemapSourceClient::continueAfterOPTIONS(RTSPClient* self_, int resultCode, char* resultString) { RTSPCubemapSourceClient* self = (RTSPCubemapSourceClient*)self_; delete[] resultString; // Next, get a SDP description for the stream: self->sendDescribeCommand(continueAfterDESCRIBE); } void RTSPCubemapSourceClient::networkLoop() { // Begin by sending an "OPTIONS" command: sendOptionsCommand(continueAfterOPTIONS); // All subsequent activity takes place within the event loop: envir().taskScheduler().doEventLoop(); // does not return } void RTSPCubemapSourceClient::connect() { networkThread = boost::thread(boost::bind(&RTSPCubemapSourceClient::networkLoop, this)); } RTSPCubemapSourceClient* RTSPCubemapSourceClient::create(char const* rtspURL, unsigned int sinkBufferSize, AVPixelFormat format, bool matchStereoPairs, bool robustSyncing, size_t maxFrameMapSize, const char* interfaceAddress, int verbosityLevel, char const* applicationName, portNumBits tunnelOverHTTPPortNum, int socketNumToServer) { NetAddressList addresses(interfaceAddress); if (addresses.numAddresses() == 0) { std::cout << "Inteface \"" << interfaceAddress << "\" does not exist" << std::endl; return nullptr; } ReceivingInterfaceAddr = *(unsigned*)(addresses.firstAddress()->data()); // Begin by setting up our usage environment: TaskScheduler* scheduler = BasicTaskScheduler::createNew(); BasicUsageEnvironment* env = BasicUsageEnvironment::createNew(*scheduler); return new RTSPCubemapSourceClient(*env, rtspURL, sinkBufferSize, format, matchStereoPairs, robustSyncing, maxFrameMapSize, verbosityLevel, applicationName, tunnelOverHTTPPortNum, socketNumToServer); } RTSPCubemapSourceClient::RTSPCubemapSourceClient(UsageEnvironment& env, char const* rtspURL, unsigned int sinkBufferSize, AVPixelFormat format, bool matchStereoPairs, bool robustSyncing, size_t maxFrameMapSize, int verbosityLevel, char const* applicationName, portNumBits tunnelOverHTTPPortNum, int socketNumToServer) : RTSPClient(env, rtspURL, verbosityLevel, applicationName, tunnelOverHTTPPortNum, socketNumToServer), sinkBufferSize(sinkBufferSize), format(format), lastTotalKBytes(0.0), lastTotalPacketsReceived(0), lastTotalPacketsExpected(0), matchStereoPairs(matchStereoPairs), robustSyncing(robustSyncing), maxFrameMapSize(maxFrameMapSize) { }
36.222816
169
0.62246
tiborgo
d527e9abe27059dedd59ec3865f0a655764b6330
8,405
cpp
C++
src/shogun/lib/SGNDArray.cpp
Arpit2601/shogun
e509f8c57f47dc74b3f791d450a70b770d11582a
[ "BSD-3-Clause" ]
1
2019-10-02T11:10:08.000Z
2019-10-02T11:10:08.000Z
src/shogun/lib/SGNDArray.cpp
Arpit2601/shogun
e509f8c57f47dc74b3f791d450a70b770d11582a
[ "BSD-3-Clause" ]
null
null
null
src/shogun/lib/SGNDArray.cpp
Arpit2601/shogun
e509f8c57f47dc74b3f791d450a70b770d11582a
[ "BSD-3-Clause" ]
1
2020-06-02T09:15:40.000Z
2020-06-02T09:15:40.000Z
/* * This software is distributed under BSD 3-clause license (see LICENSE file). * * Authors: Soeren Sonnenburg, Bjoern Esser, Weijie Lin, Sergey Lisitsyn, * Koen van de Sande, Jiaolong Xu */ #include <shogun/lib/common.h> #include <shogun/lib/SGNDArray.h> #include <shogun/lib/SGReferencedData.h> namespace shogun { template<class T> SGNDArray<T>::SGNDArray() : SGReferencedData() { init_data(); } template<class T> SGNDArray<T>::SGNDArray(T* a, index_t* d, index_t nd, bool ref_counting) : SGReferencedData(ref_counting) { array = a; dims = d; num_dims = nd; len_array = 1; for (int32_t i=0; i<num_dims; i++) len_array *= dims[i]; require(len_array>0, "Length of array ({}) must be greater than 0", len_array); } template<class T> SGNDArray<T>::SGNDArray(index_t* d, index_t nd, bool ref_counting) : SGReferencedData(ref_counting), dims(d), num_dims(nd) { len_array = 1; for (int32_t i=0; i<num_dims; i++) len_array *= dims[i]; require(len_array>0, "Length of array ({}) must be greater than 0", len_array); array = SG_MALLOC(T, len_array); } template<class T> SGNDArray<T>::SGNDArray(const SGVector<index_t> dimensions, bool ref_counting) : SGReferencedData(ref_counting) { num_dims = dimensions.size(); dims = SG_MALLOC(index_t, num_dims); len_array = 1; for (int32_t i=0; i<num_dims; i++) { dims[i] = dimensions[i]; len_array *= dims[i]; } require(len_array>0, "Length of array ({}) must be greater than 0", len_array); array = SG_MALLOC(T, len_array); } template<class T> SGNDArray<T>::SGNDArray(const SGNDArray &orig) : SGReferencedData(orig) { copy_data(orig); } template<class T> SGNDArray<T>::~SGNDArray() { unref(); } template<class T> void SGNDArray<T>::copy_data(const SGReferencedData &orig) { array = ((SGNDArray*)(&orig))->array; dims = ((SGNDArray*)(&orig))->dims; num_dims = ((SGNDArray*)(&orig))->num_dims; len_array = ((SGNDArray*)(&orig))->len_array; } template<class T> void SGNDArray<T>::init_data() { array = NULL; dims = NULL; num_dims = 0; len_array = 0; } template<class T> void SGNDArray<T>::free_data() { SG_FREE(array); SG_FREE(dims); array = NULL; dims = NULL; num_dims = 0; len_array = 0; } template<class T> SGNDArray<T> SGNDArray<T>::clone() const { SGNDArray<T> array_clone(get_dimensions()); sg_memcpy(array_clone.array, array, sizeof(T)*len_array); return array_clone; } template<class T> SGVector<index_t> SGNDArray<T>::get_dimensions() const { SGVector<index_t> dimensions(num_dims); for (int32_t i = 0; i < num_dims; i++) dimensions[i] = dims[i]; return dimensions; } template<class T> void SGNDArray<T>::transpose_matrix(index_t matIdx) const { require(array && dims, "Array is empty."); require(num_dims > 2, "Number of dimensions ({}) must be greater than 2.", num_dims); require(dims[2] > matIdx, "Provided index ({}) is out of range, must be smaller than {}", matIdx, dims[2]); T aux; // Index to acces directly the elements of the matrix of interest int64_t idx = int64_t(matIdx)*int64_t(dims[0])*dims[1]; for (int64_t i=0; i<dims[0]; i++) for (int64_t j=0; j<i-1; j++) { aux = array[idx + i + j*dims[0]]; array[idx + i + j*dims[0]] = array[idx + j + i*dims[0]]; array[idx + j + i*dims[1]] = aux; } // Swap the sizes of the two first dimensions index_t auxDim = dims[0]; dims[0] = dims[1]; dims[1] = auxDim; } template<class T> void SGNDArray<T>::set_const(T const_elem) { for (index_t i = 0; i < len_array; i++) array[i] = const_elem; } template<class T> SGNDArray<T>& SGNDArray<T>::operator*=(T val) { for (index_t i = 0; i < len_array; i++) array[i] *= val; return (*this); } template<> SGNDArray<bool>& SGNDArray<bool>::operator*=(bool val) { not_implemented(SOURCE_LOCATION);; return (*this); } template<> SGNDArray<char>& SGNDArray<char>::operator*=(char val) { not_implemented(SOURCE_LOCATION);; return (*this); } template<class T> SGNDArray<T>& SGNDArray<T>::operator+=(SGNDArray& ndarray) { require(len_array == ndarray.len_array, "The length of the given array ({}) does not match the length of internal array ({}).", ndarray.len_array, len_array); require(num_dims == ndarray.num_dims, "The provided number of dimensions ({}) does not match the internal number of dimensions ({}).", ndarray.num_dims, num_dims); for (index_t i = 0; i < len_array; i++) array[i] += ndarray.array[i]; return (*this); } template<> SGNDArray<bool>& SGNDArray<bool>::operator+=(SGNDArray& ndarray) { not_implemented(SOURCE_LOCATION);; return (*this); } template<> SGNDArray<char>& SGNDArray<char>::operator+=(SGNDArray& ndarray) { not_implemented(SOURCE_LOCATION);; return (*this); } template<class T> SGNDArray<T>& SGNDArray<T>::operator-=(SGNDArray& ndarray) { require(len_array == ndarray.len_array, "The length of the given array ({}) does not match the length of internal array ({}).", ndarray.len_array, len_array); require(num_dims == ndarray.num_dims, "The provided number of dimensions ({}) does not match the internal number of dimensions ({}).", ndarray.num_dims, num_dims); for (index_t i = 0; i < len_array; i++) array[i] -= ndarray.array[i]; return (*this); } template<> SGNDArray<bool>& SGNDArray<bool>::operator-=(SGNDArray& ndarray) { not_implemented(SOURCE_LOCATION);; return (*this); } template<> SGNDArray<char>& SGNDArray<char>::operator-=(SGNDArray& ndarray) { not_implemented(SOURCE_LOCATION);; return (*this); } template<class T> T SGNDArray<T>::max_element(int32_t &max_at) { require(len_array > 0, "Length of the array ({}) must be greater than 0.", len_array); T m = array[0]; max_at = 0; for (int32_t i = 1; i < len_array; i++) { if (array[i] >= m) { max_at = i; m = array[i]; } } return m; } template<> bool SGNDArray<bool>::max_element(int32_t &max_at) { not_implemented(SOURCE_LOCATION);; return false; } template<> char SGNDArray<char>::max_element(int32_t &max_at) { not_implemented(SOURCE_LOCATION);; return '\0'; } template<class T> T SGNDArray<T>::get_value(SGVector<index_t> index) const { int32_t y = 0; int32_t fact = 1; require(index.size() == num_dims, "Provided number of dimensions ({}) does not match internal number of dimensions ({}).", index.size(), num_dims); for (int32_t i = num_dims - 1; i >= 0; i--) { require(index[i] < dims[i], "Provided index ({}) on dimension {} must be smaller than {}. ", index[i], i, dims[i]); y += index[i] * fact; fact *= dims[i]; } return array[y]; } template<class T> void SGNDArray<T>::next_index(SGVector<index_t>& curr_index) const { require(curr_index.size() == num_dims, "The provided number of dimensions ({}) does not match the internal number of dimensions ({}).", curr_index.size(), num_dims); for (int32_t i = num_dims - 1; i >= 0; i--) { curr_index[i]++; if (curr_index[i] < dims[i]) break; curr_index[i] = 0; } } template<class T> void SGNDArray<T>::expand(SGNDArray &big_array, SGVector<index_t>& axes) { // TODO: A nice implementation would be a function like repmat in matlab require(axes.size() <= 2, "Provided axes size ({}) must be smaller than 2.", axes.size()); require(num_dims <= 2, "Number of dimensions ({}) must be smaller than 2. Only 1-d and 2-d array can be expanded currently.", num_dims); // Initialize indices in big array to zeros SGVector<index_t> inds_big(big_array.num_dims); inds_big.zero(); // Replicate the small array to the big one. // Go over the big one by one and take the corresponding value T* data_big = &big_array.array[0]; for (int32_t vi = 0; vi < big_array.len_array; vi++) { int32_t y = 0; if (axes.size() == 1) { y = inds_big[axes[0]]; } else if (axes.size() == 2) { int32_t ind1 = axes[0]; int32_t ind2 = axes[1]; y = inds_big[ind1] * dims[1] + inds_big[ind2]; } *data_big = array[y]; data_big++; // Move to the next index big_array.next_index(inds_big); } } template class SGNDArray<bool>; template class SGNDArray<char>; template class SGNDArray<int8_t>; template class SGNDArray<uint8_t>; template class SGNDArray<int16_t>; template class SGNDArray<uint16_t>; template class SGNDArray<int32_t>; template class SGNDArray<uint32_t>; template class SGNDArray<int64_t>; template class SGNDArray<uint64_t>; template class SGNDArray<float32_t>; template class SGNDArray<float64_t>; template class SGNDArray<floatmax_t>; }
24.014286
129
0.681023
Arpit2601
d5284a97d8d06271ab129a5edd7e16b12beb3a75
3,182
cpp
C++
sbg/src/libpdb/SMol.cpp
chaconlab/korpm
5a73b5ab385150b580b2fd3f1b2ad26fa3d55cf3
[ "MIT" ]
1
2022-01-02T01:48:05.000Z
2022-01-02T01:48:05.000Z
sbg/src/libpdb/SMol.cpp
chaconlab/korpm
5a73b5ab385150b580b2fd3f1b2ad26fa3d55cf3
[ "MIT" ]
1
2021-11-10T10:50:08.000Z
2021-11-10T10:50:08.000Z
sbg/src/libpdb/SMol.cpp
chaconlab/korpm
5a73b5ab385150b580b2fd3f1b2ad26fa3d55cf3
[ "MIT" ]
1
2021-12-03T03:29:39.000Z
2021-12-03T03:29:39.000Z
/* * SMol.cpp * * Created on: Feb 4, 2010 * Author: nacho */ #include <stdio.h> #include "SMol.h" ///Auxiliar function to find the position of an atom in a Smol int return_pos_aux_smol(SMol *smol,Atom *at); SMol::SMol(Tname name,int i_nid,int i_pos):Molecule(name,i_nid) { strcpy(id,name); npos=i_pos; bonds=NULL; num_bonds=0; } SMol::SMol(SMol *old, bool with_elements):Molecule(old,with_elements) { bonds=NULL; num_bonds=0; //INTRODUCE BONDS int i,pos_init,pos_final; Bond *bond,*new_bond; Atom *at_init,*at_final; //Find all bonds in old Smol and introduce in the new Smol for(i=0;i<old->get_numBonds();i++) { //Bond in old Smol //fprintf(stderr,"\n%d\n",i); //fprintf(stderr,"Bond in old Smol\n"); bond=old->getBond(i); //Positions of the bonded atoms in old SMol //fprintf(stderr,"Positions of the bonded atoms\n"); pos_init=return_pos_aux_smol(old,bond->getInit()); pos_final=return_pos_aux_smol(old,bond->getFinal()); //Corresponding Atoms bonded in new SMol //fprintf(stderr,"Atoms bonded (%d %d)\n",pos_init,pos_final); at_init=(Atom*)(this->getE(pos_init)); at_final=(Atom*)(this->getE(pos_final)); //Creation of new Bond //fprintf(stderr,"Creation of new Bond\n"); new_bond=new Bond(at_init,at_final,bond->getLink()); //Link the atoms to the bond //fprintf(stderr,"Link the atoms to the bond (%s %s)\n",at_init->getPdbName(),at_final->getPdbName()); at_init->insertBond(new_bond); at_final->insertBond(new_bond); //Introduction of the bond in Smol //fprintf(stderr,"Introduction of the bond in Smol\n"); this->insertBond(new_bond); } } SMol::SMol():Molecule() { strcpy(id,"SMolecule"); bonds=NULL; num_bonds=0; } SMol::~SMol() { int i; if(num_bonds>0) { for(i=0;i<num_bonds;i++) delete bonds[i]; free(bonds); } } int SMol::get_pos() { return npos; } TElement SMol::getClass() { return pdb_smol; } TMOL SMol::getMolType() { return tmol_smol; } void SMol::insertBond(Bond *b) { num_bonds++; bonds=(Bond**)realloc(bonds,sizeof(Bond*)*num_bonds); bonds[num_bonds-1]=b; } bool SMol::deleteBond(Bond *b) { int i,j; for(i=0;i<num_bonds;i++) { if(bonds[i]==b) { (b->getInit())->removeBond(b); (b->getFinal())->removeBond(b); for(j=i;j<num_bonds-1;j++) { bonds[j]=bonds[j+1]; } num_bonds--; bonds=(Bond**)realloc(bonds,sizeof(Bond*)*num_bonds); delete b; return true; } } return false; } void SMol::deleteHydrogenBonds() { int i; Bond *b; for(i=num_bonds-1;i>=0;i--) { b=getBond(i); // if( ((b->getFinal())->getElement())->symbol==H || ((b->getInit())->getElement())->symbol==H ) if( ((b->getFinal())->getElement())->symbol==H || ((b->getInit())->getElement())->symbol==H || ((b->getFinal())->getElement())->symbol==D || ((b->getInit())->getElement())->symbol==D ) deleteBond(b); } } Bond *SMol::getBond(int i) { if( i>num_bonds ) return NULL; else { return bonds[i]; } } int SMol::get_numBonds() { return num_bonds; } int return_pos_aux_smol(SMol *smol,Atom *at) { int i; Atom *at2; for(i=0;smol->getLimit();i++) { at2=(Atom*)smol->getE(i); if (at2==at) return i; } return -1; }
17.977401
186
0.642678
chaconlab
d52a5160e589f5e4b4b08a46136efe38e0255f48
9,953
cpp
C++
Kits/DirectXTK12/Src/Model.cpp
JSungMin/RenderEngine
e4a7475c6940a007a2318d13a523361441ff1dae
[ "MIT" ]
null
null
null
Kits/DirectXTK12/Src/Model.cpp
JSungMin/RenderEngine
e4a7475c6940a007a2318d13a523361441ff1dae
[ "MIT" ]
null
null
null
Kits/DirectXTK12/Src/Model.cpp
JSungMin/RenderEngine
e4a7475c6940a007a2318d13a523361441ff1dae
[ "MIT" ]
null
null
null
//-------------------------------------------------------------------------------------- // File: Model.cpp // // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved. // // http://go.microsoft.com/fwlink/?LinkID=615561 //-------------------------------------------------------------------------------------- #include "pch.h" #include "Model.h" #include "CommonStates.h" #include "DirectXHelpers.h" #include "Effects.h" #include "PlatformHelpers.h" #include "DescriptorHeap.h" using namespace DirectX; #ifndef _CPPRTTI #error Model requires RTTI #endif //-------------------------------------------------------------------------------------- // ModelMeshPart //-------------------------------------------------------------------------------------- ModelMeshPart::ModelMeshPart(uint32_t partIndex) : partIndex(partIndex), materialIndex(0), indexCount(0), startIndex(0), vertexOffset(0), vertexStride(0), vertexCount(0), primitiveType(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST), indexFormat(DXGI_FORMAT_R16_UINT) { } ModelMeshPart::~ModelMeshPart() { } _Use_decl_annotations_ void ModelMeshPart::Draw(_In_ ID3D12GraphicsCommandList* commandList) const { D3D12_VERTEX_BUFFER_VIEW vbv; vbv.BufferLocation = vertexBuffer.GpuAddress(); vbv.StrideInBytes = vertexStride; vbv.SizeInBytes = static_cast<UINT>(vertexBuffer.Size()); commandList->IASetVertexBuffers(0, 1, &vbv); D3D12_INDEX_BUFFER_VIEW ibv; ibv.BufferLocation = indexBuffer.GpuAddress(); ibv.SizeInBytes = static_cast<UINT>(indexBuffer.Size()); ibv.Format = indexFormat; commandList->IASetIndexBuffer(&ibv); commandList->IASetPrimitiveTopology(primitiveType); commandList->DrawIndexedInstanced( indexCount, 1, startIndex, vertexOffset, 0 ); } _Use_decl_annotations_ void ModelMeshPart::DrawMeshParts(ID3D12GraphicsCommandList* commandList, const ModelMeshPart::Collection& meshParts) { for ( auto it = meshParts.cbegin(); it != meshParts.cend(); ++it ) { auto part = (*it).get(); assert( part != 0 ); part->Draw(commandList); } } _Use_decl_annotations_ void ModelMeshPart::DrawMeshParts( ID3D12GraphicsCommandList* commandList, const ModelMeshPart::Collection& meshParts, ModelMeshPart::DrawCallback callback) { for ( auto it = meshParts.cbegin(); it != meshParts.cend(); ++it ) { auto part = (*it).get(); assert( part != 0 ); callback(commandList, *part); part->Draw(commandList); } } _Use_decl_annotations_ void ModelMeshPart::DrawMeshParts(ID3D12GraphicsCommandList* commandList, const ModelMeshPart::Collection& meshParts, IEffect* effect) { effect->Apply(commandList); DrawMeshParts(commandList, meshParts); } //-------------------------------------------------------------------------------------- // ModelMesh //-------------------------------------------------------------------------------------- ModelMesh::ModelMesh() { } ModelMesh::~ModelMesh() { } // Draw the mesh void __cdecl ModelMesh::DrawOpaque(_In_ ID3D12GraphicsCommandList* commandList) const { ModelMeshPart::DrawMeshParts(commandList, opaqueMeshParts); } void __cdecl ModelMesh::DrawAlpha(_In_ ID3D12GraphicsCommandList* commandList) const { ModelMeshPart::DrawMeshParts(commandList, alphaMeshParts); } // Draw the mesh with an effect void __cdecl ModelMesh::DrawOpaque(_In_ ID3D12GraphicsCommandList* commandList, _In_ IEffect* effect) const { ModelMeshPart::DrawMeshParts(commandList, opaqueMeshParts, effect); } void __cdecl ModelMesh::DrawAlpha(_In_ ID3D12GraphicsCommandList* commandList, _In_ IEffect* effect) const { ModelMeshPart::DrawMeshParts(commandList, alphaMeshParts, effect); } // Draw the mesh with a callback for each mesh part void __cdecl ModelMesh::DrawOpaque(_In_ ID3D12GraphicsCommandList* commandList, ModelMeshPart::DrawCallback callback) const { ModelMeshPart::DrawMeshParts(commandList, opaqueMeshParts, callback); } void __cdecl ModelMesh::DrawAlpha(_In_ ID3D12GraphicsCommandList* commandList, ModelMeshPart::DrawCallback callback) const { ModelMeshPart::DrawMeshParts(commandList, alphaMeshParts, callback); } //-------------------------------------------------------------------------------------- // Model //-------------------------------------------------------------------------------------- Model::Model() { } Model::~Model() { } // Load texture resources int Model::LoadTextures(IEffectTextureFactory& texFactory, int destinationDescriptorOffset) const { for (size_t i = 0; i < textureNames.size(); ++i) { texFactory.CreateTexture(textureNames[i].c_str(), destinationDescriptorOffset + static_cast<int>(i)); } return static_cast<int>(textureNames.size()); } // Load texture resources (helper function) _Use_decl_annotations_ std::unique_ptr<EffectTextureFactory> Model::LoadTextures( ID3D12Device* device, ResourceUploadBatch& resourceUploadBatch, const wchar_t* texturesPath, D3D12_DESCRIPTOR_HEAP_FLAGS flags) const { if (textureNames.empty()) return nullptr; std::unique_ptr<EffectTextureFactory> texFactory = std::make_unique<EffectTextureFactory>( device, resourceUploadBatch, textureNames.size(), flags); if (texturesPath != nullptr && *texturesPath != 0) { texFactory->SetDirectory(texturesPath); } LoadTextures(*texFactory); return texFactory; } // Create effects for each mesh piece std::vector<std::shared_ptr<IEffect>> Model::CreateEffects( IEffectFactory& fxFactory, const EffectPipelineStateDescription& opaquePipelineState, const EffectPipelineStateDescription& alphaPipelineState, int textureDescriptorOffset, int samplerDescriptorOffset) const { if (materials.empty()) { DebugTrace("ERROR: Model has no material information to create effects!\n"); throw std::exception("CreateEffects"); } std::vector<std::shared_ptr<IEffect>> effects; // Count the number of parts uint32_t partCount = 0; for (const auto& mesh : meshes) { for (const auto& part : mesh->opaqueMeshParts) partCount = std::max(part->partIndex + 1, partCount); for (const auto& part : mesh->alphaMeshParts) partCount = std::max(part->partIndex + 1, partCount); } if (partCount == 0) return effects; // Create an array of effects for each part. We need to have an effect per part because the part's vertex layout // combines with the material spec to create a unique effect. We rely on the EffectFactory to de-duplicate if it // wants to. effects.resize(partCount); for (const auto& mesh : meshes) { assert(mesh != nullptr); for (const auto& part : mesh->opaqueMeshParts) { assert(part != nullptr); if (part->materialIndex == uint32_t(-1)) continue; // If this fires, you have multiple parts with the same unique ID assert(effects[part->partIndex] == nullptr); effects[part->partIndex] = CreateEffectForMeshPart(fxFactory, opaquePipelineState, alphaPipelineState, textureDescriptorOffset, samplerDescriptorOffset, part.get()); } for (const auto& part : mesh->alphaMeshParts) { assert(part != nullptr); if (part->materialIndex == uint32_t(-1)) continue; // If this fires, you have multiple parts with the same unique ID assert(effects[part->partIndex] == nullptr); effects[part->partIndex] = CreateEffectForMeshPart(fxFactory, opaquePipelineState, alphaPipelineState, textureDescriptorOffset, samplerDescriptorOffset, part.get()); } } return effects; } // Creates an effect for a mesh part _Use_decl_annotations_ std::shared_ptr<IEffect> Model::CreateEffectForMeshPart( IEffectFactory& fxFactory, const EffectPipelineStateDescription& opaquePipelineState, const EffectPipelineStateDescription& alphaPipelineState, int textureDescriptorOffset, int samplerDescriptorOffset, const ModelMeshPart* part) const { assert(part->materialIndex < materials.size()); const auto& m = materials[part->materialIndex]; D3D12_INPUT_LAYOUT_DESC il = {}; il.NumElements = (uint32_t) part->vbDecl->size(); il.pInputElementDescs = part->vbDecl->data(); return fxFactory.CreateEffect(m, opaquePipelineState, alphaPipelineState, il, textureDescriptorOffset, samplerDescriptorOffset); } // Create effects for each mesh piece with the default factory _Use_decl_annotations_ std::vector<std::shared_ptr<IEffect>> Model::CreateEffects( const EffectPipelineStateDescription& opaquePipelineState, const EffectPipelineStateDescription& alphaPipelineState, ID3D12DescriptorHeap* textureDescriptorHeap, ID3D12DescriptorHeap* samplerDescriptorHeap, int textureDescriptorOffset, int samplerDescriptorOffset) const { EffectFactory fxFactory(textureDescriptorHeap, samplerDescriptorHeap); return CreateEffects(fxFactory, opaquePipelineState, alphaPipelineState, textureDescriptorOffset, samplerDescriptorOffset); } // Updates effect matrices (if applicable) void XM_CALLCONV Model::UpdateEffectMatrices( _In_ std::vector<std::shared_ptr<IEffect>>& effectList, DirectX::FXMMATRIX world, DirectX::CXMMATRIX view, DirectX::CXMMATRIX proj) { for (auto& fx : effectList) { IEffectMatrices* matFx = dynamic_cast<IEffectMatrices*>(fx.get()); if (matFx) { matFx->SetMatrices(world, view, proj); } } }
29.799401
177
0.663418
JSungMin
d52a9880900e9e92ce7aeeef3700551bbf25f6ef
2,734
cpp
C++
mp/src/old/cl_dll/c_te_beamring.cpp
MaartenS11/Team-Fortress-Invasion
f36b96d27f834d94e0db2d2a9470b05b42e9b460
[ "Unlicense" ]
1
2021-03-20T14:27:45.000Z
2021-03-20T14:27:45.000Z
mp/src/old/cl_dll/c_te_beamring.cpp
MaartenS11/Team-Fortress-Invasion
f36b96d27f834d94e0db2d2a9470b05b42e9b460
[ "Unlicense" ]
null
null
null
mp/src/old/cl_dll/c_te_beamring.cpp
MaartenS11/Team-Fortress-Invasion
f36b96d27f834d94e0db2d2a9470b05b42e9b460
[ "Unlicense" ]
null
null
null
//======== (C) Copyright 1999, 2000 Valve, L.L.C. All rights reserved. ======== // // The copyright to the contents herein is the property of Valve, L.L.C. // The contents may be used and/or copied only with the written permission of // Valve, L.L.C., or in accordance with the terms and conditions stipulated in // the agreement/contract under which the contents have been supplied. // // Purpose: // // $Workfile: $ // $Date: $ // //----------------------------------------------------------------------------- // $Log: $ // // $NoKeywords: $ //============================================================================= #include "cbase.h" #include "c_te_basebeam.h" #include "iviewrender_beams.h" //----------------------------------------------------------------------------- // Purpose: BeamRing TE //----------------------------------------------------------------------------- class C_TEBeamRing : public C_TEBaseBeam { public: DECLARE_CLASS( C_TEBeamRing, C_TEBaseBeam ); DECLARE_CLIENTCLASS(); C_TEBeamRing( void ); virtual ~C_TEBeamRing( void ); virtual void PostDataUpdate( DataUpdateType_t updateType ); public: int m_nStartEntity; int m_nEndEntity; }; //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- C_TEBeamRing::C_TEBeamRing( void ) { m_nStartEntity = 0; m_nEndEntity = 0; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- C_TEBeamRing::~C_TEBeamRing( void ) { } void TE_BeamRing( IRecipientFilter& filter, float delay, int start, int end, int modelindex, int haloindex, int startframe, int framerate, float life, float width, int spread, float amplitude, int r, int g, int b, int a, int speed ) { beams->CreateBeamRing( start, end, modelindex, haloindex, 0.0f, life, width, 0.1 * spread, 0.0f, amplitude, a, 0.1 * speed, startframe, 0.1 * framerate, r, g, b ); } //----------------------------------------------------------------------------- // Purpose: // Input : bool - //----------------------------------------------------------------------------- void C_TEBeamRing::PostDataUpdate( DataUpdateType_t updateType ) { beams->CreateBeamRing( m_nStartEntity, m_nEndEntity, m_nModelIndex, m_nHaloIndex, 0.0f, m_fLife, m_fWidth, m_fEndWidth, m_nFadeLength, m_fAmplitude, a, 0.1 * m_nSpeed, m_nStartFrame, 0.1 * m_nFrameRate, r, g, b ); } IMPLEMENT_CLIENTCLASS_EVENT_DT(C_TEBeamRing, DT_TEBeamRing, CTEBeamRing) RecvPropInt( RECVINFO(m_nStartEntity)), RecvPropInt( RECVINFO(m_nEndEntity)), END_RECV_TABLE()
33.753086
94
0.502195
MaartenS11
d52ada3d8ff4ea41c98496ad3c8f90f54767f4bd
2,251
hpp
C++
include/crypto/CTR.hpp
Jonas4420/Crypto
4fda1854c838407e6cbfb0ffaf862609eaac203a
[ "MIT" ]
null
null
null
include/crypto/CTR.hpp
Jonas4420/Crypto
4fda1854c838407e6cbfb0ffaf862609eaac203a
[ "MIT" ]
null
null
null
include/crypto/CTR.hpp
Jonas4420/Crypto
4fda1854c838407e6cbfb0ffaf862609eaac203a
[ "MIT" ]
null
null
null
#ifndef CRYPTO_CTR_H #define CRYPTO_CTR_H #include "crypto/CipherMode.hpp" #include "crypto/SymmetricCipher.hpp" #include <type_traits> #include <cstring> namespace Crypto { template <class SC> class CTR : public CipherMode { static_assert(std::is_base_of<SymmetricCipher, SC>::value, "Template argument should be a SymmetricCipher"); public: CTR(const uint8_t *key, std::size_t key_sz, uint8_t counter[SC::BLOCK_SIZE]) : sc_ctx(key, key_sz), limit_reached(false) { memcpy(this->begin, counter, BLOCK_SIZE); memcpy(this->counter, counter, BLOCK_SIZE); sc_ctx.encrypt(this->counter, stream); stream_sz = 0; } ~CTR(void) { zeroize(begin, sizeof(begin)); zeroize(counter, sizeof(counter)); zeroize(stream, sizeof(stream)); zeroize(&stream_sz, sizeof(stream_sz)); zeroize(&limit_reached, sizeof(limit_reached)); } int update(const uint8_t *input, std::size_t input_sz, uint8_t *output, std::size_t &output_sz) { if ( limit_reached ) { return CRYPTO_CIPHER_MODE_LENGTH_LIMIT; } // Check that output is large enough if ( output_sz < input_sz ) { output_sz = input_sz; return CRYPTO_CIPHER_MODE_INVALID_LENGTH; } // Process input output_sz = 0; for ( std::size_t i = 0 ; i < input_sz ; ++i ) { output[i] = input[i] ^ stream[stream_sz]; ++stream_sz; ++output_sz; if ( BLOCK_SIZE == stream_sz ) { inc_counter(counter); if ( 0 == memcmp(begin, counter, BLOCK_SIZE) ) { limit_reached = true; return CRYPTO_CIPHER_MODE_LENGTH_LIMIT; } sc_ctx.encrypt(counter, stream); stream_sz = 0; } } return CRYPTO_CIPHER_MODE_SUCCESS; } int finish(std::size_t &pad_sz) { pad_sz = 0; return CRYPTO_CIPHER_MODE_SUCCESS; } static const std::size_t BLOCK_SIZE = SC::BLOCK_SIZE; protected: static inline void inc_counter(uint8_t counter[BLOCK_SIZE]) { for ( std::size_t i = BLOCK_SIZE - 1 ; i < BLOCK_SIZE ; --i ) { if ( ++counter[i] != 0 ) { break; } } } SC sc_ctx; uint8_t begin[BLOCK_SIZE]; uint8_t counter[BLOCK_SIZE]; uint8_t stream[BLOCK_SIZE]; std::size_t stream_sz; bool limit_reached; }; } #endif
21.438095
97
0.653043
Jonas4420
d52cc36c23fb4b7c0c4da9c5cbff9d01bb4fa2bb
1,775
cpp
C++
OrbitClientServices/TracepointServiceClient.cpp
jaydipoo7/orbit
824ad7f8e1edab2d188426386c906148972c648c
[ "BSD-2-Clause" ]
1
2021-10-18T03:20:42.000Z
2021-10-18T03:20:42.000Z
OrbitClientServices/TracepointServiceClient.cpp
jaydipoo7/orbit
824ad7f8e1edab2d188426386c906148972c648c
[ "BSD-2-Clause" ]
3
2022-02-13T22:28:55.000Z
2022-02-27T11:05:02.000Z
OrbitClientServices/TracepointServiceClient.cpp
jaydipoo7/orbit
824ad7f8e1edab2d188426386c906148972c648c
[ "BSD-2-Clause" ]
1
2021-01-15T22:58:10.000Z
2021-01-15T22:58:10.000Z
// Copyright (c) 2020 The Orbit 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 "OrbitClientServices/TracepointServiceClient.h" #include "OrbitBase/Logging.h" using orbit_grpc_protos::GetTracepointListRequest; using orbit_grpc_protos::GetTracepointListResponse; using orbit_grpc_protos::TracepointInfo; using orbit_grpc_protos::TracepointService; TracepointServiceClient::TracepointServiceClient(const std::shared_ptr<grpc::Channel>& channel) : tracepoint_service_(TracepointService::NewStub(channel)) {} ErrorMessageOr<std::vector<TracepointInfo>> TracepointServiceClient::GetTracepointList() const { GetTracepointListRequest request; GetTracepointListResponse response; std::unique_ptr<grpc::ClientContext> context = std::make_unique<grpc::ClientContext>(); grpc::Status status = tracepoint_service_->GetTracepointList(context.get(), request, &response); if (!status.ok()) { const std::string& error_message = absl::StrFormat("gRPC call to GetTracepointList failed: %s (error_code=%d)", status.error_message(), status.error_code()); ERROR("gRPC call to GetTracepointList failed: %s (error_code=%d)", status.error_message(), status.error_code()); return ErrorMessage(error_message); } const auto& tracepoints = response.tracepoints(); return std::vector<TracepointInfo>{tracepoints.begin(), tracepoints.end()}; } std::unique_ptr<TracepointServiceClient> TracepointServiceClient::Create( const std::shared_ptr<grpc::Channel>& channel) { TracepointServiceClient* service = new TracepointServiceClient(channel); std::unique_ptr<TracepointServiceClient> client(service); return client; }
39.444444
98
0.764507
jaydipoo7
d52d5b15bfe6f1eea9162a34000af892037a9ade
1,451
cpp
C++
Libraries/ZilchShaders/ZilchSpirVDisassemblerBackend.cpp
RyanTylerRae/WelderEngineRevamp
3efdad59dd1821ddb1c09b59520e8e2d7023bb10
[ "MIT" ]
1
2019-07-13T03:36:11.000Z
2019-07-13T03:36:11.000Z
Libraries/ZilchShaders/ZilchSpirVDisassemblerBackend.cpp
RyanTylerRae/WelderEngineRevamp
3efdad59dd1821ddb1c09b59520e8e2d7023bb10
[ "MIT" ]
null
null
null
Libraries/ZilchShaders/ZilchSpirVDisassemblerBackend.cpp
RyanTylerRae/WelderEngineRevamp
3efdad59dd1821ddb1c09b59520e8e2d7023bb10
[ "MIT" ]
null
null
null
// MIT Licensed (see LICENSE.md). #include "Precompiled.hpp" namespace Zero { ZilchSpirVDisassemblerBackend::ZilchSpirVDisassemblerBackend() { mTargetEnv = SPV_ENV_UNIVERSAL_1_3; } String ZilchSpirVDisassemblerBackend::GetExtension() { return "spvtxt"; } bool ZilchSpirVDisassemblerBackend::RunTranslationPass(ShaderTranslationPassResult& inputData, ShaderTranslationPassResult& outputData) { mErrorLog.Clear(); ShaderByteStream& inputByteStream = inputData.mByteStream; uint32_t* data = (uint32_t*)inputByteStream.Data(); uint32 wordCount = inputByteStream.WordCount(); spv_text text; spv_diagnostic diagnostic = nullptr; uint32_t options = SPV_BINARY_TO_TEXT_OPTION_NONE | SPV_BINARY_TO_TEXT_OPTION_INDENT | SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES; spv_context context = spvContextCreate((spv_target_env)mTargetEnv); spv_result_t spvResult = spvBinaryToText(context, data, wordCount, options, &text, &diagnostic); spvContextDestroy(context); bool success = (spvResult == SPV_SUCCESS); if (!success) { if (diagnostic != nullptr) mErrorLog = diagnostic->error; return false; } outputData.mByteStream.Load(text->str, text->length); spvTextDestroy(text); outputData.mReflectionData = inputData.mReflectionData; return success; } String ZilchSpirVDisassemblerBackend::GetErrorLog() { return mErrorLog; } } // namespace Zero
25.910714
115
0.745003
RyanTylerRae
d531b66fe8fd2cc806e01e9ae06b97a99d5acd92
9,838
cpp
C++
gm/convexpolyclip.cpp
Rusino/skia
b3929a01f476c63e5358e97128ba7eb9f14e806e
[ "BSD-3-Clause" ]
1
2019-03-25T15:37:48.000Z
2019-03-25T15:37:48.000Z
gm/convexpolyclip.cpp
bryphe/esy-skia
9810a02f28270535de10b584bffc536182224c83
[ "BSD-3-Clause" ]
null
null
null
gm/convexpolyclip.cpp
bryphe/esy-skia
9810a02f28270535de10b584bffc536182224c83
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright 2014 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "ToolUtils.h" #include "gm.h" #include "SkBitmap.h" #include "SkFont.h" #include "SkGradientShader.h" #include "SkPath.h" #include "SkTLList.h" static SkBitmap make_bmp(int w, int h) { SkBitmap bmp; bmp.allocN32Pixels(w, h, true); SkCanvas canvas(bmp); SkScalar wScalar = SkIntToScalar(w); SkScalar hScalar = SkIntToScalar(h); SkPoint pt = { wScalar / 2, hScalar / 2 }; SkScalar radius = 3 * SkMaxScalar(wScalar, hScalar); SkColor colors[] = {SK_ColorDKGRAY, ToolUtils::color_to_565(0xFF222255), ToolUtils::color_to_565(0xFF331133), ToolUtils::color_to_565(0xFF884422), ToolUtils::color_to_565(0xFF000022), SK_ColorWHITE, ToolUtils::color_to_565(0xFFAABBCC)}; SkScalar pos[] = {0, SK_Scalar1 / 6, 2 * SK_Scalar1 / 6, 3 * SK_Scalar1 / 6, 4 * SK_Scalar1 / 6, 5 * SK_Scalar1 / 6, SK_Scalar1}; SkPaint paint; SkRect rect = SkRect::MakeWH(wScalar, hScalar); SkMatrix mat = SkMatrix::I(); for (int i = 0; i < 4; ++i) { paint.setShader(SkGradientShader::MakeRadial( pt, radius, colors, pos, SK_ARRAY_COUNT(colors), SkTileMode::kRepeat, 0, &mat)); canvas.drawRect(rect, paint); rect.inset(wScalar / 8, hScalar / 8); mat.preTranslate(6 * wScalar, 6 * hScalar); mat.postScale(SK_Scalar1 / 3, SK_Scalar1 / 3); } SkFont font(ToolUtils::create_portable_typeface(), wScalar / 2.2f); paint.setShader(nullptr); paint.setColor(SK_ColorLTGRAY); constexpr char kTxt[] = "Skia"; SkPoint texPos = { wScalar / 17, hScalar / 2 + font.getSize() / 2.5f }; canvas.drawSimpleText(kTxt, SK_ARRAY_COUNT(kTxt)-1, kUTF8_SkTextEncoding, texPos.fX, texPos.fY, font, paint); paint.setColor(SK_ColorBLACK); paint.setStyle(SkPaint::kStroke_Style); paint.setStrokeWidth(SK_Scalar1); canvas.drawSimpleText(kTxt, SK_ARRAY_COUNT(kTxt)-1, kUTF8_SkTextEncoding, texPos.fX, texPos.fY, font, paint); return bmp; } namespace skiagm { /** * This GM tests convex polygon clips. */ class ConvexPolyClip : public GM { public: ConvexPolyClip() { this->setBGColor(0xFFFFFFFF); } protected: SkString onShortName() override { return SkString("convex_poly_clip"); } SkISize onISize() override { // When benchmarking the saveLayer set of draws is skipped. int w = 435; if (kBench_Mode != this->getMode()) { w *= 2; } return SkISize::Make(w, 540); } void onOnceBeforeDraw() override { SkPath tri; tri.moveTo(5.f, 5.f); tri.lineTo(100.f, 20.f); tri.lineTo(15.f, 100.f); fClips.addToTail()->setPath(tri); SkPath hexagon; constexpr SkScalar kRadius = 45.f; const SkPoint center = { kRadius, kRadius }; for (int i = 0; i < 6; ++i) { SkScalar angle = 2 * SK_ScalarPI * i / 6; SkPoint point = { SkScalarCos(angle), SkScalarSin(angle) }; point.scale(kRadius); point = center + point; if (0 == i) { hexagon.moveTo(point); } else { hexagon.lineTo(point); } } fClips.addToTail()->setPath(hexagon); SkMatrix scaleM; scaleM.setScale(1.1f, 0.4f, kRadius, kRadius); hexagon.transform(scaleM); fClips.addToTail()->setPath(hexagon); fClips.addToTail()->setRect(SkRect::MakeXYWH(8.3f, 11.6f, 78.2f, 72.6f)); SkPath rotRect; SkRect rect = SkRect::MakeLTRB(10.f, 12.f, 80.f, 86.f); rotRect.addRect(rect); SkMatrix rotM; rotM.setRotate(23.f, rect.centerX(), rect.centerY()); rotRect.transform(rotM); fClips.addToTail()->setPath(rotRect); fBmp = make_bmp(100, 100); } void onDraw(SkCanvas* canvas) override { SkScalar y = 0; constexpr SkScalar kMargin = 10.f; SkPaint bgPaint; bgPaint.setAlpha(0x15); SkISize size = canvas->getBaseLayerSize(); canvas->drawBitmapRect(fBmp, SkRect::MakeIWH(size.fWidth, size.fHeight), &bgPaint); constexpr char kTxt[] = "Clip Me!"; SkFont font(ToolUtils::create_portable_typeface(), 23); SkScalar textW = font.measureText(kTxt, SK_ARRAY_COUNT(kTxt)-1, kUTF8_SkTextEncoding); SkPaint txtPaint; txtPaint.setColor(SK_ColorDKGRAY); SkScalar startX = 0; int testLayers = kBench_Mode != this->getMode(); for (int doLayer = 0; doLayer <= testLayers; ++doLayer) { for (ClipList::Iter iter(fClips, ClipList::Iter::kHead_IterStart); iter.get(); iter.next()) { const Clip* clip = iter.get(); SkScalar x = startX; for (int aa = 0; aa < 2; ++aa) { if (doLayer) { SkRect bounds; clip->getBounds(&bounds); bounds.outset(2, 2); bounds.offset(x, y); canvas->saveLayer(&bounds, nullptr); } else { canvas->save(); } canvas->translate(x, y); clip->setOnCanvas(canvas, kIntersect_SkClipOp, SkToBool(aa)); canvas->drawBitmap(fBmp, 0, 0); canvas->restore(); x += fBmp.width() + kMargin; } for (int aa = 0; aa < 2; ++aa) { SkPaint clipOutlinePaint; clipOutlinePaint.setAntiAlias(true); clipOutlinePaint.setColor(0x50505050); clipOutlinePaint.setStyle(SkPaint::kStroke_Style); clipOutlinePaint.setStrokeWidth(0); if (doLayer) { SkRect bounds; clip->getBounds(&bounds); bounds.outset(2, 2); bounds.offset(x, y); canvas->saveLayer(&bounds, nullptr); } else { canvas->save(); } canvas->translate(x, y); SkPath closedClipPath; clip->asClosedPath(&closedClipPath); canvas->drawPath(closedClipPath, clipOutlinePaint); clip->setOnCanvas(canvas, kIntersect_SkClipOp, SkToBool(aa)); canvas->scale(1.f, 1.8f); canvas->drawSimpleText(kTxt, SK_ARRAY_COUNT(kTxt)-1, kUTF8_SkTextEncoding, 0, 1.5f * font.getSize(), font, txtPaint); canvas->restore(); x += textW + 2 * kMargin; } y += fBmp.height() + kMargin; } y = 0; startX += 2 * fBmp.width() + SkScalarCeilToInt(2 * textW) + 6 * kMargin; } } bool runAsBench() const override { return true; } private: class Clip { public: enum ClipType { kNone_ClipType, kPath_ClipType, kRect_ClipType }; Clip () : fClipType(kNone_ClipType) {} void setOnCanvas(SkCanvas* canvas, SkClipOp op, bool aa) const { switch (fClipType) { case kPath_ClipType: canvas->clipPath(fPath, op, aa); break; case kRect_ClipType: canvas->clipRect(fRect, op, aa); break; case kNone_ClipType: SkDEBUGFAIL("Uninitialized Clip."); break; } } void asClosedPath(SkPath* path) const { switch (fClipType) { case kPath_ClipType: *path = fPath; path->close(); break; case kRect_ClipType: path->reset(); path->addRect(fRect); break; case kNone_ClipType: SkDEBUGFAIL("Uninitialized Clip."); break; } } void setPath(const SkPath& path) { fClipType = kPath_ClipType; fPath = path; } void setRect(const SkRect& rect) { fClipType = kRect_ClipType; fRect = rect; fPath.reset(); } ClipType getType() const { return fClipType; } void getBounds(SkRect* bounds) const { switch (fClipType) { case kPath_ClipType: *bounds = fPath.getBounds(); break; case kRect_ClipType: *bounds = fRect; break; case kNone_ClipType: SkDEBUGFAIL("Uninitialized Clip."); break; } } private: ClipType fClipType; SkPath fPath; SkRect fRect; }; typedef SkTLList<Clip, 1> ClipList; ClipList fClips; SkBitmap fBmp; typedef GM INHERITED; }; DEF_GM(return new ConvexPolyClip;) }
32.576159
94
0.498577
Rusino
d535c229d9b2d67a1597a85c13b9e110cc3e1250
736
cpp
C++
LeetCode/cpp/657.cpp
ZintrulCre/LeetCode_Archiver
de23e16ead29336b5ee7aa1898a392a5d6463d27
[ "MIT" ]
279
2019-02-19T16:00:32.000Z
2022-03-23T12:16:30.000Z
LeetCode/cpp/657.cpp
ZintrulCre/LeetCode_Archiver
de23e16ead29336b5ee7aa1898a392a5d6463d27
[ "MIT" ]
2
2019-03-31T08:03:06.000Z
2021-03-07T04:54:32.000Z
LeetCode/cpp/657.cpp
ZintrulCre/LeetCode_Crawler
de23e16ead29336b5ee7aa1898a392a5d6463d27
[ "MIT" ]
12
2019-01-29T11:45:32.000Z
2019-02-04T16:31:46.000Z
class Solution { public: bool judgeCircle(string moves) { int n = moves.size(); vector<int> hori, vert; for (int i = 0; i < n; ++i) { if (moves[i] == 'L' || moves[i] == 'R') { hori.push_back(moves[i]); if (hori.size() > 1 && hori[hori.size() - 1] != hori[hori.size() - 2]) hori.erase(hori.end() - 2, hori.end()); } else { vert.push_back(moves[i]); if (vert.size() > 1 && vert[vert.size() - 1] != vert[vert.size() - 2]) vert.erase(vert.end() - 2, vert.end()); } } if (!vert.size() && !hori.size()) return true; return false; } };
35.047619
86
0.414402
ZintrulCre
d53654f2e90a82cfdf0e7576464edb42cd4e6101
2,467
hpp
C++
include/ensmallen_bits/log.hpp
rcurtin/ensmallen
65c9b7c7861ec0d888d5cef39546ef70c7c5351d
[ "BSL-1.0", "BSD-3-Clause" ]
1
2020-06-28T10:05:58.000Z
2020-06-28T10:05:58.000Z
include/ensmallen_bits/log.hpp
rcurtin/ensmallen
65c9b7c7861ec0d888d5cef39546ef70c7c5351d
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
include/ensmallen_bits/log.hpp
rcurtin/ensmallen
65c9b7c7861ec0d888d5cef39546ef70c7c5351d
[ "BSL-1.0", "BSD-3-Clause" ]
1
2019-01-16T16:21:59.000Z
2019-01-16T16:21:59.000Z
/** * @file log.hpp * @author Marcus Edel * * Definition of the Info and Warn log functions. * * ensmallen is free software; you may redistribute it and/or modify it under * the terms of the 3-clause BSD license. You should have received a copy of * the 3-clause BSD license along with ensmallen. If not, see * http://www.opensource.org/licenses/BSD-3-Clause for more information. */ #ifndef ENSMALLEN_LOG_HPP #define ENSMALLEN_LOG_HPP namespace ens { /** * This class does nothing and should be optimized out entirely by the compiler. */ class NullOutStream { public: /** * Does nothing. */ NullOutStream() { } /** * Does nothing. */ NullOutStream(const NullOutStream& /* other */) { } //! Does nothing. NullOutStream& operator<<(bool) { return *this; } //! Does nothing. NullOutStream& operator<<(short) { return *this; } //! Does nothing. NullOutStream& operator<<(unsigned short) { return *this; } //! Does nothing. NullOutStream& operator<<(int) { return *this; } //! Does nothing. NullOutStream& operator<<(unsigned int) { return *this; } //! Does nothing. NullOutStream& operator<<(long) { return *this; } //! Does nothing. NullOutStream& operator<<(unsigned long) { return *this; } //! Does nothing. NullOutStream& operator<<(float) { return *this; } //! Does nothing. NullOutStream& operator<<(double) { return *this; } //! Does nothing. NullOutStream& operator<<(long double) { return *this; } //! Does nothing. NullOutStream& operator<<(void*) { return *this; } //! Does nothing. NullOutStream& operator<<(const char*) { return *this; } //! Does nothing. NullOutStream& operator<<(std::string&) { return *this; } //! Does nothing. NullOutStream& operator<<(std::streambuf*) { return *this; } //! Does nothing. NullOutStream& operator<<(std::ostream& (*) (std::ostream&)) { return *this; } //! Does nothing. NullOutStream& operator<<(std::ios& (*) (std::ios&)) { return *this; } //! Does nothing. NullOutStream& operator<<(std::ios_base& (*) (std::ios_base&)) { return *this; } //! Does nothing. template<typename T> NullOutStream& operator<<(const T&) { return *this; } }; #ifdef ENS_PRINT_INFO static std::ostream& Info = arma::get_cout_stream(); #else static NullOutStream Info; #endif #ifdef ENS_PRINT_WARN static std::ostream& Warn = arma::get_cerr_stream(); #else static NullOutStream Warn; #endif } // namespace ens #endif
28.034091
80
0.66437
rcurtin
d536bc61a035d1c0497873d9a3afb300f615c994
197,904
cc
C++
src/vnsw/agent/oper/vm_interface.cc
chnyda/contrail-controller
398f13bb5bad831550389be6ac3eb3e259642664
[ "Apache-2.0" ]
1
2019-01-11T06:16:30.000Z
2019-01-11T06:16:30.000Z
src/vnsw/agent/oper/vm_interface.cc
chnyda/contrail-controller
398f13bb5bad831550389be6ac3eb3e259642664
[ "Apache-2.0" ]
null
null
null
src/vnsw/agent/oper/vm_interface.cc
chnyda/contrail-controller
398f13bb5bad831550389be6ac3eb3e259642664
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved. */ #include <sys/types.h> #include <net/ethernet.h> #include <boost/uuid/uuid_io.hpp> #include "base/logging.h" #include "db/db.h" #include "db/db_entry.h" #include "db/db_table.h" #include "ifmap/ifmap_node.h" #include "net/address_util.h" #include <cfg/cfg_init.h> #include <cfg/cfg_interface.h> #include <cmn/agent.h> #include <init/agent_param.h> #include <oper/operdb_init.h> #include <oper/ifmap_dependency_manager.h> #include <oper/config_manager.h> #include <oper/route_common.h> #include <oper/vm.h> #include <oper/vn.h> #include <oper/vrf.h> #include <oper/nexthop.h> #include <oper/mpls.h> #include <oper/mirror_table.h> #include <oper/metadata_ip.h> #include <oper/interface_common.h> #include <oper/health_check.h> #include <oper/vrf_assign.h> #include <oper/vxlan.h> #include <oper/oper_dhcp_options.h> #include <oper/inet_unicast_route.h> #include <oper/physical_device_vn.h> #include <oper/ecmp_load_balance.h> #include <oper/global_vrouter.h> #include <oper/ifmap_dependency_manager.h> #include <oper/qos_config.h> #include <vnc_cfg_types.h> #include <oper/agent_sandesh.h> #include <oper/sg.h> #include <oper/bgp_as_service.h> #include <bgp_schema_types.h> #include "sandesh/sandesh_trace.h" #include "sandesh/common/vns_types.h" #include "sandesh/common/vns_constants.h" #include <filter/acl.h> using namespace std; using namespace boost::uuids; using namespace autogen; VmInterface::VmInterface(const boost::uuids::uuid &uuid) : Interface(Interface::VM_INTERFACE, uuid, "", NULL), vm_(NULL, this), vn_(NULL), primary_ip_addr_(0), mdata_ip_(NULL), subnet_bcast_addr_(0), primary_ip6_addr_(), vm_mac_(MacAddress::kZeroMac), policy_enabled_(false), mirror_entry_(NULL), mirror_direction_(MIRROR_RX_TX), cfg_name_(""), fabric_port_(true), need_linklocal_ip_(false), drop_new_flows_(false), dhcp_enable_(true), do_dhcp_relay_(false), vm_name_(), vm_project_uuid_(nil_uuid()), vxlan_id_(0), bridging_(false), layer3_forwarding_(true), flood_unknown_unicast_(false), mac_set_(false), ecmp_(false), ecmp6_(false), disable_policy_(false), tx_vlan_id_(kInvalidVlanId), rx_vlan_id_(kInvalidVlanId), parent_(NULL, this), local_preference_(VmInterface::INVALID), oper_dhcp_options_(), sg_list_(), floating_ip_list_(), alias_ip_list_(), service_vlan_list_(), static_route_list_(), allowed_address_pair_list_(), fat_flow_list_(), vrf_assign_rule_list_(), vrf_assign_acl_(NULL), vm_ip_service_addr_(0), device_type_(VmInterface::DEVICE_TYPE_INVALID), vmi_type_(VmInterface::VMI_TYPE_INVALID), configurer_(0), subnet_(0), subnet_plen_(0), ethernet_tag_(0), logical_interface_(nil_uuid()), nova_ip_addr_(0), nova_ip6_addr_(), dhcp_addr_(0), metadata_ip_map_(), hc_instance_set_(), ecmp_load_balance_(), service_health_check_ip_(), is_vn_qos_config_(false) { metadata_ip_active_ = false; metadata_l2_active_ = false; ipv4_active_ = false; ipv6_active_ = false; l2_active_ = false; l3_interface_nh_policy_.reset(); l2_interface_nh_policy_.reset(); l3_interface_nh_no_policy_.reset(); l2_interface_nh_no_policy_.reset(); } VmInterface::VmInterface(const boost::uuids::uuid &uuid, const std::string &name, const Ip4Address &addr, const MacAddress &mac, const std::string &vm_name, const boost::uuids::uuid &vm_project_uuid, uint16_t tx_vlan_id, uint16_t rx_vlan_id, Interface *parent, const Ip6Address &a6, DeviceType device_type, VmiType vmi_type) : Interface(Interface::VM_INTERFACE, uuid, name, NULL), vm_(NULL, this), vn_(NULL), primary_ip_addr_(addr), mdata_ip_(NULL), subnet_bcast_addr_(0), primary_ip6_addr_(a6), vm_mac_(mac), policy_enabled_(false), mirror_entry_(NULL), mirror_direction_(MIRROR_RX_TX), cfg_name_(""), fabric_port_(true), need_linklocal_ip_(false), drop_new_flows_(false), dhcp_enable_(true), do_dhcp_relay_(false), vm_name_(vm_name), vm_project_uuid_(vm_project_uuid), vxlan_id_(0), bridging_(false), layer3_forwarding_(true), flood_unknown_unicast_(false), mac_set_(false), ecmp_(false), ecmp6_(false), disable_policy_(false), tx_vlan_id_(tx_vlan_id), rx_vlan_id_(rx_vlan_id), parent_(parent, this), local_preference_(VmInterface::INVALID), oper_dhcp_options_(), sg_list_(), floating_ip_list_(), alias_ip_list_(), service_vlan_list_(), static_route_list_(), allowed_address_pair_list_(), vrf_assign_rule_list_(), vrf_assign_acl_(NULL), device_type_(device_type), vmi_type_(vmi_type), configurer_(0), subnet_(0), subnet_plen_(0), ethernet_tag_(0), logical_interface_(nil_uuid()), nova_ip_addr_(0), nova_ip6_addr_(), dhcp_addr_(0), metadata_ip_map_(), hc_instance_set_(), service_health_check_ip_(), is_vn_qos_config_(false) { metadata_ip_active_ = false; metadata_l2_active_ = false; ipv4_active_ = false; ipv6_active_ = false; l2_active_ = false; } VmInterface::~VmInterface() { mdata_ip_.reset(NULL); assert(metadata_ip_map_.empty()); assert(hc_instance_set_.empty()); } bool VmInterface::CmpInterface(const DBEntry &rhs) const { const VmInterface &intf=static_cast<const VmInterface &>(rhs); return uuid_ < intf.uuid_; } // Build one Floating IP entry for a virtual-machine-interface static void BuildFloatingIpList(Agent *agent, VmInterfaceConfigData *data, IFMapNode *node) { ConfigManager *cfg_manager= agent->config_manager(); if (cfg_manager->SkipNode(node)) { return; } // Find VRF for the floating-ip. Following path in graphs leads to VRF // virtual-machine-port <-> floating-ip <-> floating-ip-pool // <-> virtual-network <-> routing-instance IFMapAgentTable *fip_table = static_cast<IFMapAgentTable *>(node->table()); DBGraph *fip_graph = fip_table->GetGraph(); // Iterate thru links for floating-ip looking for floating-ip-pool node for (DBGraphVertex::adjacency_iterator fip_iter = node->begin(fip_graph); fip_iter != node->end(fip_graph); ++fip_iter) { IFMapNode *pool_node = static_cast<IFMapNode *>(fip_iter.operator->()); if (cfg_manager->SkipNode (pool_node, agent->cfg()->cfg_floatingip_pool_table())) { continue; } // Iterate thru links for floating-ip-pool looking for virtual-network IFMapAgentTable *pool_table = static_cast<IFMapAgentTable *> (pool_node->table()); DBGraph *pool_graph = pool_table->GetGraph(); for (DBGraphVertex::adjacency_iterator pool_iter = pool_node->begin(pool_graph); pool_iter != pool_node->end(pool_graph); ++pool_iter) { IFMapNode *vn_node = static_cast<IFMapNode *>(pool_iter.operator->()); if (cfg_manager->SkipNode (vn_node, agent->cfg()->cfg_vn_table())) { continue; } VirtualNetwork *cfg = static_cast <VirtualNetwork *> (vn_node->GetObject()); assert(cfg); autogen::IdPermsType id_perms = cfg->id_perms(); boost::uuids::uuid vn_uuid; CfgUuidSet(id_perms.uuid.uuid_mslong, id_perms.uuid.uuid_lslong, vn_uuid); IFMapAgentTable *vn_table = static_cast<IFMapAgentTable *> (vn_node->table()); DBGraph *vn_graph = vn_table->GetGraph(); // Iterate thru links for virtual-network looking for // routing-instance for (DBGraphVertex::adjacency_iterator vn_iter = vn_node->begin(vn_graph); vn_iter != vn_node->end(vn_graph); ++vn_iter) { IFMapNode *vrf_node = static_cast<IFMapNode *>(vn_iter.operator->()); if (cfg_manager->SkipNode (vrf_node, agent->cfg()->cfg_vrf_table())){ continue; } // Checking whether it is default vrf of not RoutingInstance *ri = static_cast<RoutingInstance *>(vrf_node->GetObject()); if(!(ri->is_default())) { continue; } FloatingIp *fip = static_cast<FloatingIp *>(node->GetObject()); assert(fip != NULL); LOG(DEBUG, "Add FloatingIP <" << fip->address() << ":" << vrf_node->name() << "> to interface " << node->name()); boost::system::error_code ec; IpAddress addr = IpAddress::from_string(fip->address(), ec); if (ec.value() != 0) { LOG(DEBUG, "Error decoding Floating IP address " << fip->address()); } else { IpAddress fixed_ip_addr = IpAddress::from_string(fip->fixed_ip_address(), ec); if (ec.value() != 0) { fixed_ip_addr = IpAddress(); } data->floating_ip_list_.list_.insert (VmInterface::FloatingIp(addr, vrf_node->name(), vn_uuid, fixed_ip_addr)); if (addr.is_v4()) { data->floating_ip_list_.v4_count_++; } else { data->floating_ip_list_.v6_count_++; } } break; } break; } break; } return; } // Build one Alias IP entry for a virtual-machine-interface static void BuildAliasIpList(InterfaceTable *intf_table, VmInterfaceConfigData *data, IFMapNode *node) { Agent *agent = intf_table->agent(); ConfigManager *cfg_manager= agent->config_manager(); if (cfg_manager->SkipNode(node)) { return; } // Find VRF for the alias-ip. Following path in graphs leads to VRF // virtual-machine-port <-> alias-ip <-> alias-ip-pool // <-> virtual-network <-> routing-instance IFMapAgentTable *aip_table = static_cast<IFMapAgentTable *>(node->table()); DBGraph *aip_graph = aip_table->GetGraph(); // Iterate thru links for alias-ip looking for alias-ip-pool node for (DBGraphVertex::adjacency_iterator aip_iter = node->begin(aip_graph); aip_iter != node->end(aip_graph); ++aip_iter) { IFMapNode *pool_node = static_cast<IFMapNode *>(aip_iter.operator->()); if (cfg_manager->SkipNode (pool_node, agent->cfg()->cfg_aliasip_pool_table())) { continue; } // Iterate thru links for alias-ip-pool looking for virtual-network IFMapAgentTable *pool_table = static_cast<IFMapAgentTable *> (pool_node->table()); DBGraph *pool_graph = pool_table->GetGraph(); for (DBGraphVertex::adjacency_iterator pool_iter = pool_node->begin(pool_graph); pool_iter != pool_node->end(pool_graph); ++pool_iter) { IFMapNode *vn_node = static_cast<IFMapNode *>(pool_iter.operator->()); if (cfg_manager->SkipNode (vn_node, agent->cfg()->cfg_vn_table())) { continue; } VirtualNetwork *cfg = static_cast <VirtualNetwork *> (vn_node->GetObject()); assert(cfg); autogen::IdPermsType id_perms = cfg->id_perms(); boost::uuids::uuid vn_uuid; CfgUuidSet(id_perms.uuid.uuid_mslong, id_perms.uuid.uuid_lslong, vn_uuid); IFMapAgentTable *vn_table = static_cast<IFMapAgentTable *> (vn_node->table()); DBGraph *vn_graph = vn_table->GetGraph(); // Iterate thru links for virtual-network looking for // routing-instance for (DBGraphVertex::adjacency_iterator vn_iter = vn_node->begin(vn_graph); vn_iter != vn_node->end(vn_graph); ++vn_iter) { IFMapNode *vrf_node = static_cast<IFMapNode *>(vn_iter.operator->()); if (cfg_manager->SkipNode (vrf_node, agent->cfg()->cfg_vrf_table())){ continue; } // Checking whether it is default vrf of not RoutingInstance *ri = static_cast<RoutingInstance *>(vrf_node->GetObject()); if(!(ri->is_default())) { continue; } AliasIp *aip = static_cast<AliasIp *>(node->GetObject()); assert(aip != NULL); boost::system::error_code ec; IpAddress addr = IpAddress::from_string(aip->address(), ec); if (ec.value() != 0) { OPER_TRACE_ENTRY(Trace, intf_table, "Error decoding Alias IP address " + aip->address()); } else { data->alias_ip_list_.list_.insert (VmInterface::AliasIp(addr, vrf_node->name(), vn_uuid)); if (addr.is_v4()) { data->alias_ip_list_.v4_count_++; } else { data->alias_ip_list_.v6_count_++; } } break; } break; } break; } return; } // Build list of static-routes on virtual-machine-interface static void BuildStaticRouteList(VmInterfaceConfigData *data, IFMapNode *node) { InterfaceRouteTable *entry = static_cast<InterfaceRouteTable*>(node->GetObject()); assert(entry); for (std::vector<RouteType>::const_iterator it = entry->routes().begin(); it != entry->routes().end(); it++) { int plen; boost::system::error_code ec; IpAddress ip; bool add = false; Ip4Address ip4; ec = Ip4PrefixParse(it->prefix, &ip4, &plen); if (ec.value() == 0) { ip = ip4; add = true; } else { Ip6Address ip6; ec = Inet6PrefixParse(it->prefix, &ip6, &plen); if (ec.value() == 0) { ip = ip6; add = true; } else { LOG(DEBUG, "Error decoding v4/v6 Static Route address " << it->prefix); } } IpAddress gw = IpAddress::from_string(it->next_hop, ec); if (ec) { gw = IpAddress::from_string("0.0.0.0", ec); } if (add) { data->static_route_list_.list_.insert (VmInterface::StaticRoute(data->vrf_name_, ip, plen, gw, it->community_attributes.community_attribute)); } } } static void BuildResolveRoute(VmInterfaceConfigData *data, IFMapNode *node) { Subnet *entry = static_cast<Subnet *>(node->GetObject()); assert(entry); Ip4Address ip; boost::system::error_code ec; ip = Ip4Address::from_string(entry->ip_prefix().ip_prefix, ec); if (ec.value() == 0) { data->subnet_ = ip; data->subnet_plen_ = entry->ip_prefix().ip_prefix_len; } } // Get VLAN if linked to physical interface and router static void BuildInterfaceConfigurationData(Agent *agent, VmInterfaceConfigData *data, IFMapNode *node, uint16_t *rx_vlan_id, uint16_t *tx_vlan_id, IFMapNode **phy_interface, IFMapNode **phy_device) { if (*phy_interface == NULL) { *phy_interface = agent->config_manager()-> FindAdjacentIFMapNode(node, "physical-interface"); } if (!(*phy_interface)) { *rx_vlan_id = VmInterface::kInvalidVlanId; *tx_vlan_id = VmInterface::kInvalidVlanId; return; } if (*phy_device == NULL) { *phy_device = agent->config_manager()->helper()-> FindLink("physical-router-physical-interface", *phy_interface); } if (!(*phy_device)) { *rx_vlan_id = VmInterface::kInvalidVlanId; *tx_vlan_id = VmInterface::kInvalidVlanId; return; } autogen::LogicalInterface *port = static_cast <autogen::LogicalInterface *>(node->GetObject()); if (port->IsPropertySet(autogen::LogicalInterface::VLAN_TAG)) { *rx_vlan_id = port->vlan_tag(); *tx_vlan_id = port->vlan_tag(); } } static void BuildAllowedAddressPairRouteList(VirtualMachineInterface *cfg, VmInterfaceConfigData *data) { for (std::vector<AllowedAddressPair>::const_iterator it = cfg->allowed_address_pairs().begin(); it != cfg->allowed_address_pairs().end(); ++it) { boost::system::error_code ec; int plen = it->ip.ip_prefix_len; IpAddress ip = Ip4Address::from_string(it->ip.ip_prefix, ec); if (ec.value() != 0) { ip = Ip6Address::from_string(it->ip.ip_prefix, ec); } if (ec.value() != 0) { continue; } MacAddress mac = MacAddress::FromString(it->mac, &ec); if (ec.value() != 0) { mac.Zero(); } if (ip.is_unspecified() && mac == MacAddress::kZeroMac) { continue; } bool ecmp = false; if (it->address_mode == "active-active") { ecmp = true; } VmInterface::AllowedAddressPair entry(data->vrf_name_, ip, plen, ecmp, mac); data->allowed_address_pair_list_.list_.insert(entry); } } // Build VM Interface VRF or one Service Vlan entry for VM Interface static void BuildVrfAndServiceVlanInfo(Agent *agent, VmInterfaceConfigData *data, IFMapNode *node) { ConfigManager *cfg_manager= agent->config_manager(); VirtualMachineInterfaceRoutingInstance *entry = static_cast<VirtualMachineInterfaceRoutingInstance*>(node->GetObject()); assert(entry); // Ignore node if direction is not yet set. An update will come later const PolicyBasedForwardingRuleType &rule = entry->data(); if (rule.direction == "") { return; } // Find VRF by looking for link // virtual-machine-interface-routing-instance <-> routing-instance IFMapAgentTable *table = static_cast<IFMapAgentTable *>(node->table()); DBGraph *graph = table->GetGraph(); // Iterate thru links looking for routing-instance node for (DBGraphVertex::adjacency_iterator iter = node->begin(graph); iter != node->end(graph); ++iter) { IFMapNode *vrf_node = static_cast<IFMapNode *>(iter.operator->()); if (cfg_manager->SkipNode (vrf_node, agent->cfg()->cfg_vrf_table())) { continue; } if (rule.vlan_tag == 0 && rule.protocol == "" && rule.service_chain_address == "") { data->vrf_name_ = vrf_node->name(); } else { if (!rule.service_chain_address.size() && !rule.ipv6_service_chain_address.size()) { LOG(DEBUG, "Service VLAN IP address not specified for " << node->name()); break; } boost::system::error_code ec; Ip4Address addr; bool ip_set = true, ip6_set = true; if (rule.service_chain_address.size()) { addr = Ip4Address::from_string (rule.service_chain_address, ec); if (ec.value() != 0) { ip_set = false; LOG(DEBUG, "Error decoding Service VLAN IP address " << rule.service_chain_address); } } Ip6Address addr6; if (rule.ipv6_service_chain_address.size()) { addr6 = Ip6Address::from_string (rule.ipv6_service_chain_address, ec); if (ec.value() != 0) { ip6_set = false; LOG(DEBUG, "Error decoding Service VLAN IP address " << rule.ipv6_service_chain_address); } } if (!ip_set && !ip6_set) { break; } if (rule.vlan_tag > 4093) { LOG(DEBUG, "Invalid VLAN Tag " << rule.vlan_tag); break; } LOG(DEBUG, "Add Service VLAN entry <" << rule.vlan_tag << " : " << rule.service_chain_address << " : " << vrf_node->name()); MacAddress smac(agent->vrrp_mac()); MacAddress dmac = MacAddress::FromString(Agent::BcastMac()); if (rule.src_mac != Agent::NullString()) { smac = MacAddress::FromString(rule.src_mac); } if (rule.src_mac != Agent::NullString()) { dmac = MacAddress::FromString(rule.dst_mac); } data->service_vlan_list_.list_.insert (VmInterface::ServiceVlan(rule.vlan_tag, vrf_node->name(), addr, addr6, smac, dmac)); } break; } return; } static void BuildFatFlowTable(Agent *agent, VmInterfaceConfigData *data, IFMapNode *node) { VirtualMachineInterface *cfg = static_cast <VirtualMachineInterface *> (node->GetObject()); for (FatFlowProtocols::const_iterator it = cfg->fat_flow_protocols().begin(); it != cfg->fat_flow_protocols().end(); it++) { uint16_t protocol = Agent::ProtocolStringToInt(it->protocol); data->fat_flow_list_.list_.insert(VmInterface::FatFlowEntry(protocol, it->port)); } } static void BuildInstanceIp(Agent *agent, VmInterfaceConfigData *data, IFMapNode *node) { InstanceIp *ip = static_cast<InstanceIp *>(node->GetObject()); boost::system::error_code err; IpAddress addr = IpAddress::from_string(ip->address(), err); bool is_primary = false; if (err.value() != 0) { return; } if (ip->secondary() != true && ip->service_instance_ip() != true && ip->service_health_check_ip() != true) { is_primary = true; if (addr.is_v4()) { if (addr == Ip4Address(0)) { return; } if (data->addr_ == Ip4Address(0) || data->addr_ > addr.to_v4()) { data->addr_ = addr.to_v4(); if (ip->mode() == "active-active") { data->ecmp_ = true; } else { data->ecmp_ = false; } } } else if (addr.is_v6()) { if (addr == Ip6Address()) { return; } if (data->ip6_addr_ == Ip6Address() || data->ip6_addr_ > addr.to_v6()) { data->ip6_addr_ = addr.to_v6(); } if (ip->mode() == "active-active") { data->ecmp6_ = true; } else { data->ecmp6_ = false; } } } if (ip->service_instance_ip()) { if (addr.is_v4()) { data->service_ip_ = addr.to_v4(); data->service_ip_ecmp_ = false; if (ip->mode() == "active-active") { data->service_ip_ecmp_ = true; } } else if (addr.is_v6()) { data->service_ip6_ = addr.to_v6(); data->service_ip_ecmp6_ = false; if (ip->mode() == "active-active") { data->service_ip_ecmp6_ = true; } } } bool ecmp = false; if (ip->mode() == "active-active") { ecmp = true; } IpAddress tracking_ip = Ip4Address(0); if (ip->secondary() || ip->service_instance_ip()) { tracking_ip = IpAddress::from_string( ip->secondary_ip_tracking_ip().ip_prefix, err); if (err.value() != 0) { tracking_ip = Ip4Address(0); } if (tracking_ip == addr) { tracking_ip = Ip4Address(0); } } if (ip->service_health_check_ip()) { // if instance ip is service health check ip along with adding // it to instance ip list to allow route export and save it // under service_health_check_ip_ to allow usage for health // check service data->service_health_check_ip_ = addr; } if (addr.is_v4()) { data->instance_ipv4_list_.list_.insert( VmInterface::InstanceIp(addr, Address::kMaxV4PrefixLen, ecmp, is_primary, ip->service_health_check_ip(), ip->local_ip(), tracking_ip)); } else { data->instance_ipv6_list_.list_.insert( VmInterface::InstanceIp(addr, Address::kMaxV6PrefixLen, ecmp, is_primary, ip->service_health_check_ip(), ip->local_ip(), tracking_ip)); } } static void BuildSgList(VmInterfaceConfigData *data, IFMapNode *node) { SecurityGroup *sg_cfg = static_cast<SecurityGroup *> (node->GetObject()); assert(sg_cfg); autogen::IdPermsType id_perms = sg_cfg->id_perms(); uint32_t sg_id = SgTable::kInvalidSgId; stringToInteger(sg_cfg->id(), sg_id); if (sg_id != SgTable::kInvalidSgId) { uuid sg_uuid = nil_uuid(); CfgUuidSet(id_perms.uuid.uuid_mslong, id_perms.uuid.uuid_lslong, sg_uuid); data->sg_list_.list_.insert (VmInterface::SecurityGroupEntry(sg_uuid)); } } static void BuildVn(VmInterfaceConfigData *data, IFMapNode *node, const boost::uuids::uuid &u, CfgIntEntry *cfg_entry) { VirtualNetwork *vn = static_cast<VirtualNetwork *> (node->GetObject()); assert(vn); autogen::IdPermsType id_perms = vn->id_perms(); CfgUuidSet(id_perms.uuid.uuid_mslong, id_perms.uuid.uuid_lslong, data->vn_uuid_); if (cfg_entry && (cfg_entry->GetVnUuid() != data->vn_uuid_)) { IFMAP_ERROR(InterfaceConfiguration, "Virtual-network UUID mismatch for interface:", UuidToString(u), "configuration VN uuid", UuidToString(data->vn_uuid_), "compute VN uuid", UuidToString(cfg_entry->GetVnUuid())); } } static void BuildQosConfig(VmInterfaceConfigData *data, IFMapNode *node) { autogen::QosConfig *qc = static_cast<autogen::QosConfig *> (node->GetObject()); assert(qc); autogen::IdPermsType id_perms = qc->id_perms(); CfgUuidSet(id_perms.uuid.uuid_mslong, id_perms.uuid.uuid_lslong, data->qos_config_uuid_); } static void BuildVm(VmInterfaceConfigData *data, IFMapNode *node, const boost::uuids::uuid &u, CfgIntEntry *cfg_entry) { VirtualMachine *vm = static_cast<VirtualMachine *> (node->GetObject()); assert(vm); autogen::IdPermsType id_perms = vm->id_perms(); CfgUuidSet(id_perms.uuid.uuid_mslong, id_perms.uuid.uuid_lslong, data->vm_uuid_); if (cfg_entry && (cfg_entry->GetVmUuid() != data->vm_uuid_)) { IFMAP_ERROR(InterfaceConfiguration, "Virtual-machine UUID mismatch for interface:", UuidToString(u), "configuration VM UUID is", UuidToString(data->vm_uuid_), "compute VM uuid is", UuidToString(cfg_entry->GetVmUuid())); } } // Get DHCP configuration static void ReadDhcpOptions(VirtualMachineInterface *cfg, VmInterfaceConfigData &data) { data.oper_dhcp_options_.set_options(cfg->dhcp_option_list()); data.oper_dhcp_options_.set_host_routes(cfg->host_routes()); } // Get interface mirror configuration. static void ReadAnalyzerNameAndCreate(Agent *agent, VirtualMachineInterface *cfg, VmInterfaceConfigData &data) { if (!cfg) { return; } MirrorActionType mirror_to = cfg->properties().interface_mirror.mirror_to; if (!mirror_to.analyzer_name.empty()) { boost::system::error_code ec; IpAddress dip = IpAddress::from_string(mirror_to.analyzer_ip_address, ec); if (ec.value() != 0) { return; } uint16_t dport; if (mirror_to.udp_port) { dport = mirror_to.udp_port; } else { dport = ContrailPorts::AnalyzerUdpPort(); } MirrorEntryData::MirrorEntryFlags mirror_flag = MirrorTable::DecodeMirrorFlag(mirror_to.nh_mode, mirror_to.juniper_header); // not using the vrf coming in; by setting this to empty, -1 will be // configured so that current VRF will be used (for leaked routes). if (mirror_flag == MirrorEntryData::DynamicNH_With_JuniperHdr) { agent->mirror_table()->AddMirrorEntry (mirror_to.analyzer_name, std::string(), agent->GetMirrorSourceIp(dip), agent->mirror_port(), dip, dport); } else if (mirror_flag == MirrorEntryData::DynamicNH_Without_JuniperHdr) { agent->mirror_table()->AddMirrorEntry(mirror_to.analyzer_name, mirror_to.routing_instance, agent->GetMirrorSourceIp(dip), agent->mirror_port(), dip, dport, 0, mirror_flag, MacAddress::FromString(mirror_to.analyzer_mac_address)); } else if (mirror_flag == MirrorEntryData::StaticNH_Without_JuniperHdr) { IpAddress vtep_dip = IpAddress::from_string(mirror_to.static_nh_header.vtep_dst_ip_address, ec); if (ec.value() != 0) { return; } agent->mirror_table()->AddMirrorEntry(mirror_to.analyzer_name, mirror_to.routing_instance, agent->GetMirrorSourceIp(dip), agent->mirror_port(), vtep_dip, dport, mirror_to.static_nh_header.vni, mirror_flag, MacAddress::FromString(mirror_to.static_nh_header.vtep_dst_mac_address)); } else { LOG(ERROR, "Mirror nh mode not supported"); } data.analyzer_name_ = mirror_to.analyzer_name; string traffic_direction = cfg->properties().interface_mirror.traffic_direction; if (traffic_direction.compare("egress") == 0) { data.mirror_direction_ = Interface::MIRROR_TX; } else if (traffic_direction.compare("ingress") == 0) { data.mirror_direction_ = Interface::MIRROR_RX; } else { data.mirror_direction_ = Interface::MIRROR_RX_TX; } } } static void BuildVrfAssignRule(VirtualMachineInterface *cfg, VmInterfaceConfigData *data) { uint32_t id = 1; for (std::vector<VrfAssignRuleType>::const_iterator iter = cfg->vrf_assign_table().begin(); iter != cfg->vrf_assign_table().end(); ++iter) { VmInterface::VrfAssignRule entry(id++, iter->match_condition, iter->routing_instance, iter->ignore_acl); data->vrf_assign_rule_list_.list_.insert(entry); } } static IFMapNode *FindTarget(IFMapAgentTable *table, IFMapNode *node, const std::string &node_type) { for (DBGraphVertex::adjacency_iterator it = node->begin(table->GetGraph()); it != node->end(table->GetGraph()); ++it) { IFMapNode *adj_node = static_cast<IFMapNode *>(it.operator->()); if (adj_node->table()->Typename() == node_type) return adj_node; } return NULL; } static void ReadDhcpEnable(Agent *agent, VmInterfaceConfigData *data, IFMapNode *node) { IFMapAgentTable *table = static_cast<IFMapAgentTable *>(node->table()); for (DBGraphVertex::adjacency_iterator it = node->begin(table->GetGraph()); it != node->end(table->GetGraph()); ++it) { IFMapNode *adj_node = static_cast<IFMapNode *>(it.operator->()); IFMapNode *ipam_node = NULL; if (adj_node->table() == agent->cfg()->cfg_vn_network_ipam_table() && (ipam_node = FindTarget(table, adj_node, "network-ipam"))) { VirtualNetworkNetworkIpam *ipam = static_cast<VirtualNetworkNetworkIpam *>(adj_node->GetObject()); assert(ipam); const VnSubnetsType &subnets = ipam->data(); boost::system::error_code ec; for (unsigned int i = 0; i < subnets.ipam_subnets.size(); ++i) { if (IsIp4SubnetMember(data->addr_, Ip4Address::from_string( subnets.ipam_subnets[i].subnet.ip_prefix, ec), subnets.ipam_subnets[i].subnet.ip_prefix_len)) { data->dhcp_enable_ = subnets.ipam_subnets[i].enable_dhcp; return; } } } } } // Check if VMI is a sub-interface. Sub-interface will have // sub_interface_vlan_tag property set to non-zero static bool IsVlanSubInterface(VirtualMachineInterface *cfg) { if (cfg->IsPropertySet(VirtualMachineInterface::PROPERTIES) == false) return false; if (cfg->properties().sub_interface_vlan_tag == 0) return false; return true; } // Builds parent for VMI (not to be confused with parent ifmap-node) // Possible values are, // - logical-interface : Incase of baremetals // - virtual-machine-interface : We support virtual-machine-interface // sub-interfaces. In this case, another virtual-machine-interface itself // can be a parent static PhysicalRouter *BuildParentInfo(Agent *agent, VmInterfaceConfigData *data, VirtualMachineInterface *cfg, IFMapNode *node, IFMapNode *logical_node, IFMapNode *parent_vmi_node, IFMapNode **phy_interface, IFMapNode **phy_device) { if (logical_node) { if ((*phy_interface) == NULL) { *phy_interface = agent->config_manager()-> FindAdjacentIFMapNode(logical_node, "physical-interface"); } agent->interface_table()-> LogicalInterfaceIFNodeToUuid(logical_node, data->logical_interface_); // Find phyiscal-interface for the VMI if (*phy_interface) { data->physical_interface_ = (*phy_interface)->name(); // Find vrouter for the physical interface if ((*phy_device) == NULL) { *phy_device = agent->config_manager()->helper()-> FindLink("physical-router-physical-interface", (*phy_interface)); } } if ((*phy_device) == NULL) return NULL; return static_cast<PhysicalRouter *>((*phy_device)->GetObject()); } // Check if this is VLAN sub-interface VMI if (IsVlanSubInterface(cfg) == false) { return NULL; } if (!parent_vmi_node) return NULL; // process Parent VMI for sub-interface VirtualMachineInterface *parent_cfg = static_cast <VirtualMachineInterface *> (parent_vmi_node->GetObject()); assert(parent_cfg); if (IsVlanSubInterface(parent_cfg)) { return NULL; } autogen::IdPermsType id_perms = parent_cfg->id_perms(); CfgUuidSet(id_perms.uuid.uuid_mslong, id_perms.uuid.uuid_lslong, data->parent_vmi_); data->rx_vlan_id_ = cfg->properties().sub_interface_vlan_tag; data->tx_vlan_id_ = cfg->properties().sub_interface_vlan_tag; return NULL; } static void BuildEcmpHashingIncludeFields(VirtualMachineInterface *cfg, IFMapNode *vn_node, VmInterfaceConfigData *data) { data->ecmp_load_balance_.set_use_global_vrouter(false); if (cfg->IsPropertySet (VirtualMachineInterface::ECMP_HASHING_INCLUDE_FIELDS) && (cfg->ecmp_hashing_include_fields().hashing_configured)) { data->ecmp_load_balance_.UpdateFields(cfg-> ecmp_hashing_include_fields()); } else { //Extract from VN if (!vn_node) { data->ecmp_load_balance_.reset(); data->ecmp_load_balance_.set_use_global_vrouter(true); return; } VirtualNetwork *vn_cfg = static_cast <VirtualNetwork *> (vn_node->GetObject()); if ((vn_cfg->IsPropertySet (VirtualNetwork::ECMP_HASHING_INCLUDE_FIELDS) == false) || (vn_cfg->ecmp_hashing_include_fields().hashing_configured == false)) { data->ecmp_load_balance_.set_use_global_vrouter(true); data->ecmp_load_balance_.reset(); return; } data->ecmp_load_balance_.UpdateFields(vn_cfg-> ecmp_hashing_include_fields()); } } static void BuildAttributes(Agent *agent, IFMapNode *node, VirtualMachineInterface *cfg, VmInterfaceConfigData *data) { //Extract the local preference if (cfg->IsPropertySet(VirtualMachineInterface::PROPERTIES)) { autogen::VirtualMachineInterfacePropertiesType prop = cfg->properties(); //Service instance also would have VirtualMachineInterface //properties field set, pick up local preference //value only when it has been initialized to proper //value, if its 0, ignore the local preference if (prop.local_preference) { data->local_preference_ = VmInterface::LOW; if (prop.local_preference == VmInterface::HIGH) { data->local_preference_ = VmInterface::HIGH; } } } ReadAnalyzerNameAndCreate(agent, cfg, *data); // Fill DHCP option data ReadDhcpOptions(cfg, *data); //Fill config data items data->cfg_name_ = node->name(); data->admin_state_ = cfg->id_perms().enable; BuildVrfAssignRule(cfg, data); BuildAllowedAddressPairRouteList(cfg, data); if (cfg->mac_addresses().size()) { data->vm_mac_ = cfg->mac_addresses().at(0); } data->disable_policy_ = cfg->disable_policy(); } static void UpdateAttributes(Agent *agent, VmInterfaceConfigData *data) { // Compute fabric_port_ and need_linklocal_ip_ flags data->fabric_port_ = false; data->need_linklocal_ip_ = true; if (data->vrf_name_ == agent->fabric_vrf_name() || data->vrf_name_ == agent->linklocal_vrf_name()) { data->fabric_port_ = true; data->need_linklocal_ip_ = false; } if (agent->isXenMode()) { data->need_linklocal_ip_ = false; } } static void ComputeTypeInfo(Agent *agent, VmInterfaceConfigData *data, CfgIntEntry *cfg_entry, PhysicalRouter *prouter, IFMapNode *node, IFMapNode *logical_node) { if (cfg_entry != NULL) { // Have got InstancePortAdd message. Treat it as VM_ON_TAP by default // TODO: Need to identify more cases here data->device_type_ = VmInterface::VM_ON_TAP; data->vmi_type_ = VmInterface::INSTANCE; return; } VirtualMachineInterface *cfg = static_cast <VirtualMachineInterface *> (node->GetObject()); const std::vector<KeyValuePair> &bindings = cfg->bindings(); for (std::vector<KeyValuePair>::const_iterator it = bindings.begin(); it != bindings.end(); ++it) { KeyValuePair kvp = *it; if ((kvp.key == "vnic_type") && (kvp.value == "direct")) { data->device_type_ = VmInterface::VM_SRIOV; data->vmi_type_ = VmInterface::SRIOV; return; } } data->device_type_ = VmInterface::DEVICE_TYPE_INVALID; data->vmi_type_ = VmInterface::VMI_TYPE_INVALID; // Does it have physical-interface if (data->physical_interface_.empty() == false) { // no physical-router connected. Should be transient case if (prouter == NULL) { // HACK : TSN/ToR agent only supports barements. So, set as // baremetal anyway if (agent->tsn_enabled() || agent->tor_agent_enabled()) { data->device_type_ = VmInterface::TOR; data->vmi_type_ = VmInterface::BAREMETAL; } return; } // VMI is either Baremetal or Gateway interface if (prouter->display_name() == agent->agent_name()) { // VMI connected to local vrouter. Treat it as GATEWAY / Remote VM. if (agent->server_gateway_mode()) { data->device_type_ = VmInterface::REMOTE_VM_VLAN_ON_VMI; data->vmi_type_ = VmInterface::REMOTE_VM; } else { data->device_type_ = VmInterface::LOCAL_DEVICE; data->vmi_type_ = VmInterface::GATEWAY; } if (logical_node) { autogen::LogicalInterface *port = static_cast <autogen::LogicalInterface *> (logical_node->GetObject()); data->rx_vlan_id_ = port->vlan_tag(); data->tx_vlan_id_ = port->vlan_tag(); } return; } else { // prouter does not match. Treat as baremetal data->device_type_ = VmInterface::TOR; data->vmi_type_ = VmInterface::BAREMETAL; return; } return; } // Physical router not specified. Check if this is VMI sub-interface if (data->parent_vmi_.is_nil() == false) { data->device_type_ = VmInterface::VM_VLAN_ON_VMI; data->vmi_type_ = VmInterface::INSTANCE; return; } return; } void VmInterface::SetConfigurer(VmInterface::Configurer type) { configurer_ |= (1 << type); } void VmInterface::ResetConfigurer(VmInterface::Configurer type) { configurer_ &= ~(1 << type); } bool VmInterface::IsConfigurerSet(VmInterface::Configurer type) { return ((configurer_ & (1 << type)) != 0); } bool VmInterface::IsFatFlow(uint8_t protocol, uint16_t port) const { if (fat_flow_list_.list_.find(FatFlowEntry(protocol, port)) != fat_flow_list_.list_.end()) { return true; } return false; } static bool DeleteVmi(InterfaceTable *table, const uuid &u, DBRequest *req) { int type = table->GetVmiToVmiType(u); if (type <= (int)VmInterface::VMI_TYPE_INVALID) return false; table->DelVmiToVmiType(u); // Process delete based on VmiType if (type == VmInterface::INSTANCE) { // INSTANCE type are not added by config. We only do RESYNC req->oper = DBRequest::DB_ENTRY_ADD_CHANGE; req->key.reset(new VmInterfaceKey(AgentKey::RESYNC, u, "")); req->data.reset(new VmInterfaceConfigData(NULL, NULL)); table->Enqueue(req); return false; } else { VmInterface::Delete(table, u, VmInterface::CONFIG); return false; } } bool InterfaceTable::VmiIFNodeToUuid(IFMapNode *node, boost::uuids::uuid &u) { VirtualMachineInterface *cfg = static_cast <VirtualMachineInterface *> (node->GetObject()); autogen::IdPermsType id_perms = cfg->id_perms(); CfgUuidSet(id_perms.uuid.uuid_mslong, id_perms.uuid.uuid_lslong, u); return true; } // Virtual Machine Interface is added or deleted into oper DB from Nova // messages. The Config notify is used only to change interface. extern IFMapNode *vn_test_node; extern IFMapNode *vmi_test_node; bool InterfaceTable::VmiProcessConfig(IFMapNode *node, DBRequest &req, const boost::uuids::uuid &u) { // Get interface UUID VirtualMachineInterface *cfg = static_cast <VirtualMachineInterface *> (node->GetObject()); assert(cfg); // Handle object delete if (node->IsDeleted()) { return false; } assert(!u.is_nil()); // Get the entry from Interface Config table CfgIntTable *cfg_table = agent_->interface_config_table(); CfgIntKey cfg_key(u); CfgIntEntry *cfg_entry = static_cast <CfgIntEntry *>(cfg_table->Find(&cfg_key)); // Update interface configuration req.oper = DBRequest::DB_ENTRY_ADD_CHANGE; VmInterfaceConfigData *data = new VmInterfaceConfigData(agent(), NULL); data->SetIFMapNode(node); BuildAttributes(agent_, node, cfg, data); // Graph walk to get interface configuration IFMapAgentTable *table = static_cast<IFMapAgentTable *>(node->table()); IFMapNode *vn_node = NULL; IFMapNode *li_node = NULL; IFMapNode *phy_interface = NULL; IFMapNode *phy_device = NULL; IFMapNode *parent_vmi_node = NULL; uint16_t rx_vlan_id = VmInterface::kInvalidVlanId; uint16_t tx_vlan_id = VmInterface::kInvalidVlanId; std::list<IFMapNode *> bgp_as_a_service_node_list; for (DBGraphVertex::adjacency_iterator iter = node->begin(table->GetGraph()); iter != node->end(table->GetGraph()); ++iter) { IFMapNode *adj_node = static_cast<IFMapNode *>(iter.operator->()); if (agent_->config_manager()->SkipNode(adj_node)) { continue; } if (adj_node->table() == agent_->cfg()->cfg_sg_table()) { BuildSgList(data, adj_node); } if (adj_node->table() == agent_->cfg()->cfg_vn_table()) { vn_node = adj_node; BuildVn(data, adj_node, u, cfg_entry); } if (adj_node->table() == agent_->cfg()->cfg_qos_table()) { BuildQosConfig(data, adj_node); } if (adj_node->table() == agent_->cfg()->cfg_vm_table()) { BuildVm(data, adj_node, u, cfg_entry); } if (adj_node->table() == agent_->cfg()->cfg_instanceip_table()) { BuildInstanceIp(agent_, data, adj_node); } if (adj_node->table() == agent_->cfg()->cfg_floatingip_table()) { BuildFloatingIpList(agent_, data, adj_node); } if (adj_node->table() == agent_->cfg()->cfg_aliasip_table()) { BuildAliasIpList(this, data, adj_node); } if (adj_node->table() == agent_->cfg()->cfg_vm_port_vrf_table()) { BuildVrfAndServiceVlanInfo(agent_, data, adj_node); } if (adj_node->table() == agent_->cfg()->cfg_route_table()) { BuildStaticRouteList(data, adj_node); } if (adj_node->table() == agent_->cfg()->cfg_subnet_table()) { BuildResolveRoute(data, adj_node); } if (adj_node->table() == agent_->cfg()->cfg_logical_port_table()) { li_node = adj_node; BuildInterfaceConfigurationData(agent(), data, adj_node, &rx_vlan_id, &tx_vlan_id, &phy_interface, &phy_device); } if (adj_node->table() == agent_->cfg()->cfg_vm_interface_table()) { parent_vmi_node = adj_node; } if (adj_node->table() == agent_->cfg()->cfg_logical_port_table()) { li_node = adj_node; } if (adj_node->table() == agent_->cfg()->cfg_vm_interface_table()) { parent_vmi_node = adj_node; } if (strcmp(adj_node->table()->Typename(), BGP_AS_SERVICE_CONFIG_NAME) == 0) { bgp_as_a_service_node_list.push_back(adj_node); } } agent_->oper_db()->bgp_as_a_service()->ProcessConfig(data->vrf_name_, bgp_as_a_service_node_list, u); UpdateAttributes(agent_, data); BuildFatFlowTable(agent_, data, node); // Get DHCP enable flag from subnet if (vn_node && data->addr_.to_ulong()) { ReadDhcpEnable(agent_, data, vn_node); } PhysicalRouter *prouter = NULL; // Build parent for the virtual-machine-interface prouter = BuildParentInfo(agent_, data, cfg, node, li_node, parent_vmi_node, &phy_interface, &phy_device); BuildEcmpHashingIncludeFields(cfg, vn_node, data); // Compute device-type and vmi-type for the interface ComputeTypeInfo(agent_, data, cfg_entry, prouter, node, li_node); InterfaceKey *key = NULL; if (data->device_type_ == VmInterface::VM_ON_TAP || data->device_type_ == VmInterface::DEVICE_TYPE_INVALID) { key = new VmInterfaceKey(AgentKey::RESYNC, u, ""); } else { key = new VmInterfaceKey(AgentKey::ADD_DEL_CHANGE, u, cfg->display_name()); } if (data->device_type_ != VmInterface::DEVICE_TYPE_INVALID) { AddVmiToVmiType(u, data->device_type_); } if (data->device_type_ == VmInterface::REMOTE_VM_VLAN_ON_VMI && (rx_vlan_id == VmInterface::kInvalidVlanId || tx_vlan_id == VmInterface::kInvalidVlanId)) { return false; } req.key.reset(key); req.data.reset(data); boost::uuids::uuid dev = nil_uuid(); if (prouter) { autogen::IdPermsType id_perms = prouter->id_perms(); CfgUuidSet(id_perms.uuid.uuid_mslong, id_perms.uuid.uuid_lslong, dev); } UpdatePhysicalDeviceVnEntry(u, dev, data->vn_uuid_, vn_node); vmi_ifnode_to_req_++; return true; } bool InterfaceTable::VmiIFNodeToReq(IFMapNode *node, DBRequest &req, const boost::uuids::uuid &u) { // Handle object delete if ((req.oper == DBRequest::DB_ENTRY_DELETE) || node->IsDeleted()) { agent_->oper_db()->bgp_as_a_service()->DeleteVmInterface(u); DelPhysicalDeviceVnEntry(u); return DeleteVmi(this, u, &req); } IFMapDependencyManager *dep = agent()->oper_db()->dependency_manager(); IFMapNodeState *state = dep->IFMapNodeGet(node); IFMapDependencyManager::IFMapNodePtr vm_node_ref; if (!state) { vm_node_ref = dep->SetState(node); state = dep->IFMapNodeGet(node); } if (state->uuid().is_nil()) state->set_uuid(u); agent()->config_manager()->AddVmiNode(node); return false; } ///////////////////////////////////////////////////////////////////////////// // Routines to manage VmiToPhysicalDeviceVnTree ///////////////////////////////////////////////////////////////////////////// VmiToPhysicalDeviceVnData::VmiToPhysicalDeviceVnData (const boost::uuids::uuid &dev, const boost::uuids::uuid &vn) : dev_(dev), vn_(vn) { } VmiToPhysicalDeviceVnData::~VmiToPhysicalDeviceVnData() { } void InterfaceTable::UpdatePhysicalDeviceVnEntry(const boost::uuids::uuid &vmi, boost::uuids::uuid &dev, boost::uuids::uuid &vn, IFMapNode *vn_node) { VmiToPhysicalDeviceVnTree::iterator iter = vmi_to_physical_device_vn_tree_.find(vmi); if (iter == vmi_to_physical_device_vn_tree_.end()) { vmi_to_physical_device_vn_tree_.insert (make_pair(vmi,VmiToPhysicalDeviceVnData(nil_uuid(), nil_uuid()))); iter = vmi_to_physical_device_vn_tree_.find(vmi); } if (iter->second.dev_ != dev || iter->second.vn_ != vn) { agent()->physical_device_vn_table()->DeleteConfigEntry (vmi, iter->second.dev_, iter->second.vn_); } iter->second.dev_ = dev; iter->second.vn_ = vn; agent()->physical_device_vn_table()->AddConfigEntry(vmi, dev, vn); } void InterfaceTable::DelPhysicalDeviceVnEntry(const boost::uuids::uuid &vmi) { VmiToPhysicalDeviceVnTree::iterator iter = vmi_to_physical_device_vn_tree_.find(vmi); if (iter == vmi_to_physical_device_vn_tree_.end()) return; agent()->physical_device_vn_table()->DeleteConfigEntry (vmi, iter->second.dev_, iter->second.vn_); vmi_to_physical_device_vn_tree_.erase(iter); } ///////////////////////////////////////////////////////////////////////////// // VM Port Key routines ///////////////////////////////////////////////////////////////////////////// VmInterfaceKey::VmInterfaceKey(AgentKey::DBSubOperation sub_op, const boost::uuids::uuid &uuid, const std::string &name) : InterfaceKey(sub_op, Interface::VM_INTERFACE, uuid, name, false) { } Interface *VmInterfaceKey::AllocEntry(const InterfaceTable *table) const { return new VmInterface(uuid_); } Interface *VmInterfaceKey::AllocEntry(const InterfaceTable *table, const InterfaceData *data) const { const VmInterfaceData *vm_data = static_cast<const VmInterfaceData *>(data); VmInterface *vmi = vm_data->OnAdd(table, this); return vmi; } InterfaceKey *VmInterfaceKey::Clone() const { return new VmInterfaceKey(*this); } ///////////////////////////////////////////////////////////////////////////// // VM Port Entry routines ///////////////////////////////////////////////////////////////////////////// string VmInterface::ToString() const { return "VM-PORT <" + name() + ">"; } DBEntryBase::KeyPtr VmInterface::GetDBRequestKey() const { InterfaceKey *key = new VmInterfaceKey(AgentKey::ADD_DEL_CHANGE, uuid_, name_); return DBEntryBase::KeyPtr(key); } const Peer *VmInterface::peer() const { return peer_.get(); } bool VmInterface::OnChange(VmInterfaceData *data) { InterfaceTable *table = static_cast<InterfaceTable *>(get_table()); return Resync(table, data); } // When VMInterface is added from Config (sub-interface, gateway interface etc.) // the RESYNC is not called and some of the config like VN and VRF are not // applied on the interface (See Add() API above). Force change to ensure // RESYNC is called void VmInterface::PostAdd() { InterfaceTable *table = static_cast<InterfaceTable *>(get_table()); DBRequest req; IFMapNode *node = ifmap_node(); if (node == NULL) return; boost::uuids::uuid u; table->IFNodeToUuid(node, u); if (table->IFNodeToReq(ifmap_node(), req, u) == true) { table->Process(req); } } // Handle RESYNC DB Request. Handles multiple sub-types, // - CONFIG : RESYNC from config message // - IP_ADDR: RESYNC due to learning IP from DHCP // - MIRROR : RESYNC due to change in mirror config bool VmInterface::Resync(const InterfaceTable *table, const VmInterfaceData *data) { bool ret = false; // Copy old values used to update config below bool old_ipv4_active = ipv4_active_; bool old_ipv6_active = ipv6_active_; bool old_l2_active = l2_active_; bool old_policy = policy_enabled_; VrfEntryRef old_vrf = vrf_; Ip4Address old_addr = primary_ip_addr_; Ip6Address old_v6_addr = primary_ip6_addr_; bool old_need_linklocal_ip = need_linklocal_ip_; bool force_update = false; Ip4Address old_subnet = subnet_; uint8_t old_subnet_plen = subnet_plen_; int old_ethernet_tag = ethernet_tag_; bool old_dhcp_enable = dhcp_enable_; bool old_layer3_forwarding = layer3_forwarding_; Ip4Address old_dhcp_addr = dhcp_addr_; bool old_metadata_ip_active = metadata_ip_active_; bool old_metadata_l2_active = metadata_l2_active_; bool old_bridging = bridging_; if (data) { ret = data->OnResync(table, this, &force_update); } metadata_ip_active_ = IsMetaDataIPActive(); metadata_l2_active_ = IsMetaDataL2Active(); ipv4_active_ = IsIpv4Active(); ipv6_active_ = IsIpv6Active(); l2_active_ = IsL2Active(); if (metadata_ip_active_ != old_metadata_ip_active) { ret = true; } if (metadata_l2_active_ != old_metadata_l2_active) { ret = true; } if (ipv4_active_ != old_ipv4_active) { InterfaceTable *intf_table = static_cast<InterfaceTable *>(get_table()); if (ipv4_active_) intf_table->incr_active_vmi_count(); else intf_table->decr_active_vmi_count(); ret = true; } if (ipv6_active_ != old_ipv6_active) { ret = true; } if (l2_active_ != old_l2_active) { ret = true; } policy_enabled_ = PolicyEnabled(); if (policy_enabled_ != old_policy) { ret = true; } // Apply config based on old and new values ApplyConfig(old_ipv4_active, old_l2_active, old_policy, old_vrf.get(), old_addr, old_ethernet_tag, old_need_linklocal_ip, old_ipv6_active, old_v6_addr, old_subnet, old_subnet_plen, old_dhcp_enable, old_layer3_forwarding, force_update, old_dhcp_addr, old_metadata_ip_active, old_bridging); return ret; } void VmInterface::Add() { peer_.reset(new LocalVmPortPeer(LOCAL_VM_PORT_PEER_NAME, id_)); } bool VmInterface::Delete(const DBRequest *req) { InterfaceTable *table = static_cast<InterfaceTable *>(get_table()); const VmInterfaceData *vm_data = static_cast<const VmInterfaceData *> (req->data.get()); vm_data->OnDelete(table, this); if (configurer_) { return false; } table->DeleteDhcpSnoopEntry(name_); return true; } void VmInterface::UpdateL3MetadataIp(VrfEntry *old_vrf, bool force_update, bool policy_change, bool old_metadata_ip_active) { assert(metadata_ip_active_); UpdateL3TunnelId(force_update, policy_change); UpdateMetadataRoute(old_metadata_ip_active, old_vrf); } void VmInterface::DeleteL3MetadataIp(VrfEntry *old_vrf, bool force_update, bool policy_change, bool old_metadata_ip_active, bool old_need_linklocal_ip) { assert(!metadata_ip_active_); DeleteL3TunnelId(); DeleteMetadataRoute(old_metadata_ip_active, old_vrf, old_need_linklocal_ip); } void VmInterface::UpdateL3(bool old_ipv4_active, VrfEntry *old_vrf, const Ip4Address &old_addr, int old_ethernet_tag, bool force_update, bool policy_change, bool old_ipv6_active, const Ip6Address &old_v6_addr, const Ip4Address &old_subnet, const uint8_t old_subnet_plen, const Ip4Address &old_dhcp_addr) { if (ipv4_active_) { if (do_dhcp_relay_) { UpdateIpv4InterfaceRoute(old_ipv4_active, force_update||policy_change, old_vrf, old_dhcp_addr); } UpdateIpv4InstanceIp(force_update, policy_change, false, old_ethernet_tag, old_vrf); UpdateFloatingIp(force_update, policy_change, false, old_ethernet_tag); UpdateAliasIp(force_update, policy_change); UpdateResolveRoute(old_ipv4_active, force_update, policy_change, old_vrf, old_subnet, old_subnet_plen); } if (ipv6_active_) { UpdateIpv6InstanceIp(force_update, policy_change, false, old_ethernet_tag); } UpdateServiceVlan(force_update, policy_change, old_ipv4_active, old_ipv6_active); UpdateAllowedAddressPair(force_update, policy_change, false, false, false); UpdateVrfAssignRule(); UpdateStaticRoute(force_update||policy_change); } void VmInterface::DeleteL3(bool old_ipv4_active, VrfEntry *old_vrf, const Ip4Address &old_addr, bool old_need_linklocal_ip, bool old_ipv6_active, const Ip6Address &old_v6_addr, const Ip4Address &old_subnet, const uint8_t old_subnet_plen, int old_ethernet_tag, const Ip4Address &old_dhcp_addr, bool force_update) { // trigger delete instance ip v4/v6 unconditionally, it internally // handles cases where delete is already processed DeleteIpv4InstanceIp(false, old_ethernet_tag, old_vrf, force_update); DeleteIpv4InstanceIp(true, old_ethernet_tag, old_vrf, force_update); DeleteIpv6InstanceIp(false, old_ethernet_tag, old_vrf, force_update); DeleteIpv6InstanceIp(true, old_ethernet_tag, old_vrf, force_update); if (old_ipv4_active) { if (old_dhcp_addr != Ip4Address(0)) { DeleteIpv4InterfaceRoute(old_vrf, old_dhcp_addr); } } // Process following deletes only if any of old ipv4 or ipv6 // was active if ((old_ipv4_active || old_ipv6_active)) { DeleteFloatingIp(false, old_ethernet_tag); DeleteAliasIp(); DeleteServiceVlan(); DeleteStaticRoute(); DeleteAllowedAddressPair(false); DeleteVrfAssignRule(); DeleteResolveRoute(old_vrf, old_subnet, old_subnet_plen); } } void VmInterface::UpdateVxLan() { int new_vxlan_id = vn_.get() ? vn_->GetVxLanId() : 0; if (l2_active_ && ((vxlan_id_ == 0) || (vxlan_id_ != new_vxlan_id))) { vxlan_id_ = new_vxlan_id; } ethernet_tag_ = IsVxlanMode() ? vxlan_id_ : 0; } void VmInterface::AddL2ReceiveRoute(bool old_bridging) { if (BridgingActivated(old_bridging)) { InterfaceTable *table = static_cast<InterfaceTable *>(get_table()); Agent *agent = table->agent(); BridgeAgentRouteTable *l2_table = static_cast<BridgeAgentRouteTable *>( vrf_->GetRouteTable(Agent::BRIDGE)); l2_table->AddBridgeReceiveRoute(peer_.get(), vrf_->GetName(), 0, GetVifMac(agent), vn_->GetName()); } } void VmInterface::UpdateBridgeRoutes(bool old_bridging, VrfEntry *old_vrf, int old_ethernet_tag, bool force_update, bool policy_change, const Ip4Address &old_v4_addr, const Ip6Address &old_v6_addr, bool old_layer3_forwarding) { if (device_type() == VmInterface::TOR || device_type() == VmInterface::DEVICE_TYPE_INVALID) return; UpdateL2InterfaceRoute(old_bridging, force_update, old_vrf, Ip4Address(), Ip6Address(), old_ethernet_tag, old_layer3_forwarding, policy_change, Ip4Address(), Ip6Address(), vm_mac_, Ip4Address(0)); UpdateIpv4InstanceIp(force_update, policy_change, true, old_ethernet_tag, old_vrf); UpdateIpv6InstanceIp(force_update, policy_change, true, old_ethernet_tag); UpdateFloatingIp(force_update, policy_change, true, old_ethernet_tag); UpdateAllowedAddressPair(force_update, policy_change, true, old_bridging, old_layer3_forwarding); //If the interface is Gateway we need to add a receive route, //such the packet gets routed. Bridging on gateway //interface is not supported if ((vmi_type() == GATEWAY || vmi_type() == REMOTE_VM) && BridgingActivated(old_bridging)) { AddL2ReceiveRoute(old_bridging); } } void VmInterface::UpdateL2(bool old_l2_active, bool policy_change) { if (device_type() == VmInterface::TOR || device_type() == VmInterface::DEVICE_TYPE_INVALID) return; UpdateVxLan(); //Update label only if new entry is to be created, so //no force update on same. UpdateL2TunnelId(false, policy_change); } void VmInterface::DeleteBridgeRoutes(bool old_bridging, VrfEntry *old_vrf, int old_ethernet_tag, const Ip4Address &old_v4_addr, const Ip6Address &old_v6_addr, bool old_layer3_forwarding, bool force_update) { DeleteIpv4InstanceIp(true, old_ethernet_tag, old_vrf, force_update); DeleteIpv6InstanceIp(true, old_ethernet_tag, old_vrf, force_update); if (old_bridging) { DeleteL2InterfaceRoute(old_bridging, old_vrf, Ip4Address(0), Ip6Address(), old_ethernet_tag, vm_mac_); DeleteFloatingIp(true, old_ethernet_tag); DeleteL2ReceiveRoute(old_vrf, old_bridging); DeleteAllowedAddressPair(true); } } void VmInterface::DeleteL2(bool old_l2_active) { DeleteL2TunnelId(); } const MacAddress& VmInterface::GetVifMac(const Agent *agent) const { if (parent()) { if (device_type_ == VM_VLAN_ON_VMI) { const VmInterface *vmi = static_cast<const VmInterface *>(parent_.get()); return vmi->GetVifMac(agent); } return parent()->mac(); } else { return agent->vrrp_mac(); } } bool VmInterface::InstallBridgeRoutes() const { return (l2_active_ & is_hc_active_); } void VmInterface::ApplyConfigCommon(const VrfEntry *old_vrf, bool old_l2_active, bool old_dhcp_enable) { //DHCP MAC IP binding ApplyMacVmBindingConfig(old_vrf, old_l2_active, old_dhcp_enable); //Security Group update if (IsActive()) { UpdateSecurityGroup(); UpdateFatFlow(); } else { DeleteSecurityGroup(); DeleteFatFlow(); } } /* * L2 nexthops: * These L2 nexthop are used by multicast and bridge. * Presence of multicast forces it to be present in * ipv4 mode(l3-only). * * L3 nexthops: * Also creates L3 interface NH, if layer3_forwarding is set. * It does not depend on oper state of ip forwarding. * Needed as health check can disable oper ip_active and will result in flow key * pointing to L2 interface NH. This has to be avoided as interface still points * to l3 nh and flow should use same. For this fix it is also required that l3 * i/f nh is also created on seeing config and not oper state of l3. Reason * being if vmi(irrespective of health check) is coming up and transitioning * from ipv4_inactive to ip4_active and during this transition a flow is added * then flow_key in vmi will return null because l3 config is set and interface * nh not created yet. */ void VmInterface::UpdateCommonNextHop() { UpdateL2NextHop(); UpdateL3NextHop(); } void VmInterface::DeleteCommonNextHop() { DeleteL2NextHop(); DeleteL3NextHop(); } void VmInterface::ApplyMacVmBindingConfig(const VrfEntry *old_vrf, bool old_active, bool old_dhcp_enable) { if (!IsActive() || old_vrf != vrf()) { DeleteMacVmBinding(old_vrf); } //Update DHCP and DNS flag in Interface Class. if (dhcp_enable_) { dhcp_enabled_ = true; dns_enabled_ = true; } else { dhcp_enabled_ = false; dns_enabled_ = false; } if (!IsActive()) return; UpdateMacVmBinding(); } // Apply the latest configuration void VmInterface::ApplyConfig(bool old_ipv4_active, bool old_l2_active, bool old_policy, VrfEntry *old_vrf, const Ip4Address &old_addr, int old_ethernet_tag, bool old_need_linklocal_ip, bool old_ipv6_active, const Ip6Address &old_v6_addr, const Ip4Address &old_subnet, uint8_t old_subnet_plen, bool old_dhcp_enable, bool old_layer3_forwarding, bool force_update, const Ip4Address &old_dhcp_addr, bool old_metadata_ip_active, bool old_bridging) { //For SRIOV we dont generate any things lile l2 routes, l3 routes //etc if (device_type_ == VmInterface::VM_SRIOV) { return; } ApplyConfigCommon(old_vrf, old_l2_active, old_dhcp_enable); //Need not apply config for TOR VMI as it is more of an inidicative //interface. No route addition or NH addition happens for this interface. //Also, when parent is not updated for a non-Nova interface, device type //remains invalid. if ((device_type_ == VmInterface::TOR || device_type_ == VmInterface::DEVICE_TYPE_INVALID) && (old_subnet.is_unspecified() && old_subnet_plen == 0)) { return; } bool policy_change = (policy_enabled_ != old_policy); if (vrf_ && vmi_type() == GATEWAY) { vrf_->CreateTableLabel(); } //Update common prameters if (IsActive()) { UpdateCommonNextHop(); } // Add/Update L3 Metadata if (metadata_ip_active_) { UpdateL3MetadataIp(old_vrf, force_update, policy_change, old_metadata_ip_active); } // Add/Del/Update L3 if ((ipv4_active_ || ipv6_active_) && layer3_forwarding_) { UpdateL3(old_ipv4_active, old_vrf, old_addr, old_ethernet_tag, force_update, policy_change, old_ipv6_active, old_v6_addr, old_subnet, old_subnet_plen, old_dhcp_addr); } else { DeleteL3(old_ipv4_active, old_vrf, old_addr, old_need_linklocal_ip, old_ipv6_active, old_v6_addr, old_subnet, old_subnet_plen, old_ethernet_tag, old_dhcp_addr, (force_update || policy_change)); } // Del L3 Metadata after deleting L3 if (!metadata_ip_active_ && old_metadata_ip_active) { DeleteL3MetadataIp(old_vrf, force_update, policy_change, old_metadata_ip_active, old_need_linklocal_ip); } // Add/Update L2 if (l2_active_) { UpdateL2(old_l2_active, policy_change); } if (InstallBridgeRoutes()) { UpdateBridgeRoutes(old_l2_active, old_vrf, old_ethernet_tag, force_update, policy_change, old_addr, old_v6_addr, old_layer3_forwarding); } else { DeleteBridgeRoutes(old_l2_active, old_vrf, old_ethernet_tag, old_addr, old_v6_addr, old_layer3_forwarding, (force_update || policy_change)); } // Delete L2 if (!l2_active_ && old_l2_active) { DeleteL2(old_l2_active); } UpdateFlowKeyNextHop(); // Remove floating-ip entries marked for deletion CleanupFloatingIpList(); // Remove Alias-ip entries marked for deletion CleanupAliasIpList(); if (!IsActive()) { DeleteCommonNextHop(); } InterfaceTable *table = static_cast<InterfaceTable *>(get_table()); if (old_l2_active != l2_active_) { if (l2_active_) { SendTrace(table, ACTIVATED_L2); } else { SendTrace(table, DEACTIVATED_L2); } } if (old_ipv4_active != ipv4_active_) { if (ipv4_active_) { SendTrace(table, ACTIVATED_IPV4); } else { SendTrace(table, DEACTIVATED_IPV4); } } if (old_ipv6_active != ipv6_active_) { if (ipv6_active_) { SendTrace(table, ACTIVATED_IPV6); } else { SendTrace(table, DEACTIVATED_IPV6); } } } bool VmInterface::CopyIpAddress(Ip4Address &addr) { bool ret = false; InterfaceTable *table = static_cast<InterfaceTable *>(get_table()); // Support DHCP relay for fabric-ports if IP address is not configured do_dhcp_relay_ = (fabric_port_ && addr.to_ulong() == 0 && vrf() && vrf()->GetName() == table->agent()->fabric_vrf_name()); if (do_dhcp_relay_) { // Set config_seen flag on DHCP SNoop entry table->DhcpSnoopSetConfigSeen(name_); // IP Address not know. Get DHCP Snoop entry. // Also sets the config_seen_ flag for DHCP Snoop entry addr = table->GetDhcpSnoopEntry(name_); dhcp_addr_ = addr; } // Retain the old if new IP could not be got if (addr.to_ulong() == 0) { addr = primary_ip_addr_; } if (primary_ip_addr_ != addr) { primary_ip_addr_ = addr; ret = true; } return ret; } ///////////////////////////////////////////////////////////////////////////// // VmInterfaceConfigData routines ///////////////////////////////////////////////////////////////////////////// VmInterfaceConfigData::VmInterfaceConfigData(Agent *agent, IFMapNode *node) : VmInterfaceData(agent, node, CONFIG, Interface::TRANSPORT_INVALID), addr_(0), ip6_addr_(), vm_mac_(""), cfg_name_(""), vm_uuid_(), vm_name_(), vn_uuid_(), vrf_name_(""), fabric_port_(true), need_linklocal_ip_(false), bridging_(true), layer3_forwarding_(true), mirror_enable_(false), ecmp_(false), ecmp6_(false), dhcp_enable_(true), admin_state_(true), disable_policy_(false), analyzer_name_(""), local_preference_(VmInterface::INVALID), oper_dhcp_options_(), mirror_direction_(Interface::UNKNOWN), sg_list_(), floating_ip_list_(), alias_ip_list_(), service_vlan_list_(), static_route_list_(), allowed_address_pair_list_(), device_type_(VmInterface::DEVICE_TYPE_INVALID), vmi_type_(VmInterface::VMI_TYPE_INVALID), physical_interface_(""), parent_vmi_(), subnet_(0), subnet_plen_(0), rx_vlan_id_(VmInterface::kInvalidVlanId), tx_vlan_id_(VmInterface::kInvalidVlanId), logical_interface_(nil_uuid()), ecmp_load_balance_(), service_health_check_ip_(), service_ip_(0), service_ip_ecmp_(false), service_ip6_(), service_ip_ecmp6_(false), qos_config_uuid_(){ } VmInterface *VmInterfaceConfigData::OnAdd(const InterfaceTable *table, const VmInterfaceKey *key) const { Interface *parent = NULL; if (device_type_ == VmInterface::REMOTE_VM_VLAN_ON_VMI) { if (rx_vlan_id_ == VmInterface::kInvalidVlanId || tx_vlan_id_ == VmInterface::kInvalidVlanId) return NULL; if (physical_interface_ != Agent::NullString()) { PhysicalInterfaceKey key_1(physical_interface_); parent = static_cast<Interface *> (table->agent()->interface_table()->FindActiveEntry(&key_1)); } if (parent == NULL) return NULL; } boost::system::error_code ec; MacAddress mac = MacAddress::FromString(vm_mac_, &ec); if (ec.value() != 0) { mac.Zero(); } VmInterface *vmi = new VmInterface(key->uuid_, key->name_, addr_, mac, vm_name_, nil_uuid(), tx_vlan_id_, rx_vlan_id_, parent, ip6_addr_, device_type_, vmi_type_); vmi->SetConfigurer(VmInterface::CONFIG); return vmi; } bool VmInterfaceConfigData::OnDelete(const InterfaceTable *table, VmInterface *vmi) const { if (vmi->IsConfigurerSet(VmInterface::CONFIG) == false) return true; VmInterfaceConfigData data(NULL, NULL); vmi->Resync(table, &data); vmi->ResetConfigurer(VmInterface::CONFIG); return true; } bool VmInterfaceConfigData::OnResync(const InterfaceTable *table, VmInterface *vmi, bool *force_update) const { bool sg_changed = false; bool ecmp_changed = false; bool local_pref_changed = false; bool ecmp_load_balance_changed = false; bool static_route_config_changed = false; bool ret = false; ret = vmi->CopyConfig(table, this, &sg_changed, &ecmp_changed, &local_pref_changed, &ecmp_load_balance_changed, &static_route_config_changed); if (sg_changed || ecmp_changed || local_pref_changed || ecmp_load_balance_changed || static_route_config_changed) *force_update = true; vmi->SetConfigurer(VmInterface::CONFIG); return ret; } // Copies configuration from DB-Request data. The actual applying of // configuration, like adding/deleting routes must be done with ApplyConfig() bool VmInterface::CopyConfig(const InterfaceTable *table, const VmInterfaceConfigData *data, bool *sg_changed, bool *ecmp_changed, bool *local_pref_changed, bool *ecmp_load_balance_changed, bool *static_route_config_changed) { bool ret = false; if (table) { VmEntry *vm = table->FindVmRef(data->vm_uuid_); if (vm_.get() != vm) { vm_ = vm; ret = true; } bool drop_new_flows = (vm_.get() != NULL) ? vm_->drop_new_flows() : false; if (drop_new_flows_ != drop_new_flows) { drop_new_flows_ = drop_new_flows; ret = true; } VrfEntry *vrf = table->FindVrfRef(data->vrf_name_); if (vrf_.get() != vrf) { vrf_ = vrf; ret = true; } MirrorEntry *mirror = table->FindMirrorRef(data->analyzer_name_); if (mirror_entry_.get() != mirror) { mirror_entry_ = mirror; ret = true; } } MirrorDirection mirror_direction = data->mirror_direction_; if (mirror_direction_ != mirror_direction) { mirror_direction_ = mirror_direction; ret = true; } string cfg_name = data->cfg_name_; if (cfg_name_ != cfg_name) { cfg_name_ = cfg_name; ret = true; } // Read ifindex for the interface if (table) { VnEntry *vn = table->FindVnRef(data->vn_uuid_); if (vn_.get() != vn) { vn_ = vn; ret = true; } bool val = vn ? vn->layer3_forwarding() : false; if (layer3_forwarding_ != val) { layer3_forwarding_ = val; ret = true; } val = vn ? vn->bridging() : false; if (bridging_ != val) { bridging_ = val; ret = true; } int vxlan_id = vn ? vn->GetVxLanId() : 0; if (vxlan_id_ != vxlan_id) { vxlan_id_ = vxlan_id; ret = true; } bool flood_unknown_unicast = vn ? vn->flood_unknown_unicast(): false; if (flood_unknown_unicast_ != flood_unknown_unicast) { flood_unknown_unicast_ = flood_unknown_unicast; ret = true; } AgentQosConfigTable *qos_table = table->agent()->qos_config_table(); AgentQosConfigKey qos_key(data->qos_config_uuid_); const AgentQosConfig *qos_config = static_cast<AgentQosConfig *>( qos_table->FindActiveEntry(&qos_key)); bool is_vn_qos_config = false; if (qos_config == NULL) { if (vn && vn->qos_config()) { qos_config = vn->qos_config(); is_vn_qos_config = true; } } if (qos_config_ != qos_config) { qos_config_ = qos_config; ret = true; } if (is_vn_qos_config != is_vn_qos_config_) { is_vn_qos_config_ = is_vn_qos_config; ret = true; } } if (local_preference_ != data->local_preference_) { local_preference_ = data->local_preference_; *local_pref_changed = true; ret = true; } if (need_linklocal_ip_ != data->need_linklocal_ip_) { need_linklocal_ip_ = data->need_linklocal_ip_; ret = true; } // CopyIpAddress uses fabric_port_. So, set it before CopyIpAddresss if (fabric_port_ != data->fabric_port_) { fabric_port_ = data->fabric_port_; ret = true; } if (service_health_check_ip_ != data->service_health_check_ip_) { service_health_check_ip_ = data->service_health_check_ip_; ret = true; } //If nova gives a instance-ip then retain that //ip address as primary ip address //Else choose the ip address to be old //primary ip address as long as its present in //new configuration also Ip4Address ipaddr = data->addr_; if (nova_ip_addr_ != Ip4Address(0)) { ipaddr = nova_ip_addr_; } if (CopyIpAddress(ipaddr)) { ret = true; } Ip6Address ip6_addr = data->ip6_addr_; if (nova_ip6_addr_ != Ip6Address()) { ip6_addr = nova_ip6_addr_; } if (CopyIp6Address(ip6_addr)) { ret = true; } if (dhcp_enable_ != data->dhcp_enable_) { dhcp_enable_ = data->dhcp_enable_; ret = true; } if (disable_policy_ != data->disable_policy_) { disable_policy_ = data->disable_policy_; ret = true; } bool mac_set = true; if (vm_mac_ == MacAddress::kZeroMac) { mac_set = false; } if (mac_set_ != mac_set) { mac_set_ = mac_set; ret = true; } if (admin_state_ != data->admin_state_) { admin_state_ = data->admin_state_; ret = true; } if (subnet_ != data->subnet_ || subnet_plen_ != data->subnet_plen_) { subnet_ = data->subnet_; subnet_plen_ = data->subnet_plen_; } // Copy DHCP options; ret is not modified as there is no dependent action oper_dhcp_options_ = data->oper_dhcp_options_; // Audit operational and config floating-ip list FloatingIpSet &old_fip_list = floating_ip_list_.list_; const FloatingIpSet &new_fip_list = data->floating_ip_list_.list_; if (AuditList<FloatingIpList, FloatingIpSet::iterator> (floating_ip_list_, old_fip_list.begin(), old_fip_list.end(), new_fip_list.begin(), new_fip_list.end())) { ret = true; assert(floating_ip_list_.list_.size() == (floating_ip_list_.v4_count_ + floating_ip_list_.v6_count_)); } // Audit operational and config alias-ip list AliasIpSet &old_aip_list = alias_ip_list_.list_; const AliasIpSet &new_aip_list = data->alias_ip_list_.list_; if (AuditList<AliasIpList, AliasIpSet::iterator> (alias_ip_list_, old_aip_list.begin(), old_aip_list.end(), new_aip_list.begin(), new_aip_list.end())) { ret = true; assert(alias_ip_list_.list_.size() == (alias_ip_list_.v4_count_ + alias_ip_list_.v6_count_)); } // Audit operational and config Service VLAN list ServiceVlanSet &old_service_list = service_vlan_list_.list_; const ServiceVlanSet &new_service_list = data->service_vlan_list_.list_; if (AuditList<ServiceVlanList, ServiceVlanSet::iterator> (service_vlan_list_, old_service_list.begin(), old_service_list.end(), new_service_list.begin(), new_service_list.end())) { ret = true; } // Audit operational and config Static Route list StaticRouteSet &old_route_list = static_route_list_.list_; const StaticRouteSet &new_route_list = data->static_route_list_.list_; if (AuditList<StaticRouteList, StaticRouteSet::iterator> (static_route_list_, old_route_list.begin(), old_route_list.end(), new_route_list.begin(), new_route_list.end())) { *static_route_config_changed = true; ret = true; } // Audit operational and config allowed address pair AllowedAddressPairSet &old_aap_list = allowed_address_pair_list_.list_; const AllowedAddressPairSet &new_aap_list = data-> allowed_address_pair_list_.list_; if (AuditList<AllowedAddressPairList, AllowedAddressPairSet::iterator> (allowed_address_pair_list_, old_aap_list.begin(), old_aap_list.end(), new_aap_list.begin(), new_aap_list.end())) { ret = true; } // Audit operational and config Security Group list SecurityGroupEntrySet &old_sg_list = sg_list_.list_; const SecurityGroupEntrySet &new_sg_list = data->sg_list_.list_; *sg_changed = AuditList<SecurityGroupEntryList, SecurityGroupEntrySet::iterator> (sg_list_, old_sg_list.begin(), old_sg_list.end(), new_sg_list.begin(), new_sg_list.end()); if (*sg_changed) { ret = true; } VrfAssignRuleSet &old_vrf_assign_list = vrf_assign_rule_list_.list_; const VrfAssignRuleSet &new_vrf_assign_list = data-> vrf_assign_rule_list_.list_; if (AuditList<VrfAssignRuleList, VrfAssignRuleSet::iterator> (vrf_assign_rule_list_, old_vrf_assign_list.begin(), old_vrf_assign_list.end(), new_vrf_assign_list.begin(), new_vrf_assign_list.end())) { ret = true; } FatFlowEntrySet &old_fat_flow_entry_list = fat_flow_list_.list_; const FatFlowEntrySet &new_fat_flow_entry_list = data->fat_flow_list_.list_; if (AuditList<FatFlowList, FatFlowEntrySet::iterator> (fat_flow_list_, old_fat_flow_entry_list.begin(), old_fat_flow_entry_list.end(), new_fat_flow_entry_list.begin(), new_fat_flow_entry_list.end())) { ret = true; } InstanceIpSet &old_ipv4_list = instance_ipv4_list_.list_; InstanceIpSet new_ipv4_list = data->instance_ipv4_list_.list_; //Native ip of instance should be advertised even if //config is not present, so manually add that entry if (nova_ip_addr_ != Ip4Address(0) && data->vrf_name_ != Agent::NullString()) { new_ipv4_list.insert( VmInterface::InstanceIp(nova_ip_addr_, Address::kMaxV4PrefixLen, data->ecmp_, true, false, false, Ip4Address(0))); } if (AuditList<InstanceIpList, InstanceIpSet::iterator> (instance_ipv4_list_, old_ipv4_list.begin(), old_ipv4_list.end(), new_ipv4_list.begin(), new_ipv4_list.end())) { ret = true; } InstanceIpSet &old_ipv6_list = instance_ipv6_list_.list_; InstanceIpSet new_ipv6_list = data->instance_ipv6_list_.list_; if (nova_ip6_addr_ != Ip6Address() && data->vrf_name_ != Agent::NullString()) { new_ipv6_list.insert( VmInterface::InstanceIp(nova_ip6_addr_, Address::kMaxV6PrefixLen, data->ecmp6_, true, false, false, Ip4Address(0))); } if (AuditList<InstanceIpList, InstanceIpSet::iterator> (instance_ipv6_list_, old_ipv6_list.begin(), old_ipv6_list.end(), new_ipv6_list.begin(), new_ipv6_list.end())) { ret = true; } if (data->addr_ != Ip4Address(0) && ecmp_ != data->ecmp_) { ecmp_ = data->ecmp_; *ecmp_changed = true; } if (!data->ip6_addr_.is_unspecified() && ecmp6_ != data->ecmp6_) { ecmp6_ = data->ecmp6_; *ecmp_changed = true; } if (service_ip_ecmp_ != data->service_ip_ecmp_ || service_ip_ != data->service_ip_) { service_ip_ecmp_ = data->service_ip_ecmp_; service_ip_ = data->service_ip_; *ecmp_changed = true; ret = true; } if (service_ip_ecmp6_ != data->service_ip_ecmp6_ || service_ip6_ != data->service_ip6_) { service_ip_ecmp6_ = data->service_ip_ecmp6_; service_ip6_ = data->service_ip6_; *ecmp_changed = true; ret = true; } if (data->device_type_ != VmInterface::DEVICE_TYPE_INVALID && device_type_ != data->device_type_) { device_type_= data->device_type_; ret = true; } if (device_type_ == LOCAL_DEVICE || device_type_ == REMOTE_VM_VLAN_ON_VMI || device_type_ == VM_VLAN_ON_VMI) { if (rx_vlan_id_ != data->rx_vlan_id_) { rx_vlan_id_ = data->rx_vlan_id_; ret = true; } if (tx_vlan_id_ != data->tx_vlan_id_) { tx_vlan_id_ = data->tx_vlan_id_; ret = true; } } if (logical_interface_ != data->logical_interface_) { logical_interface_ = data->logical_interface_; ret = true; } Interface *new_parent = NULL; if (data->physical_interface_.empty() == false) { PhysicalInterfaceKey key(data->physical_interface_); new_parent = static_cast<Interface *> (table->agent()->interface_table()->FindActiveEntry(&key)); } else if (data->parent_vmi_.is_nil() == false) { VmInterfaceKey key(AgentKey::RESYNC, data->parent_vmi_, ""); new_parent = static_cast<Interface *> (table->agent()->interface_table()->FindActiveEntry(&key)); } else { new_parent = parent_.get(); } if (parent_ != new_parent) { parent_ = new_parent; ret = true; } if (table) { if (os_index_ == kInvalidIndex) { GetOsParams(table->agent()); if (os_index_ != kInvalidIndex) ret = true; } } if (ecmp_load_balance_ != data->ecmp_load_balance_) { ecmp_load_balance_.Copy(data->ecmp_load_balance_); *ecmp_load_balance_changed = true; ret = true; } return ret; } ///////////////////////////////////////////////////////////////////////////// // VmInterfaceNovaData routines ///////////////////////////////////////////////////////////////////////////// VmInterfaceNovaData::VmInterfaceNovaData() : VmInterfaceData(NULL, NULL, INSTANCE_MSG, Interface::TRANSPORT_INVALID), ipv4_addr_(), ipv6_addr_(), mac_addr_(), vm_name_(), vm_uuid_(), vm_project_uuid_(), physical_interface_(), tx_vlan_id_(), rx_vlan_id_() { } VmInterfaceNovaData::VmInterfaceNovaData(const Ip4Address &ipv4_addr, const Ip6Address &ipv6_addr, const std::string &mac_addr, const std::string vm_name, boost::uuids::uuid vm_uuid, boost::uuids::uuid vm_project_uuid, const std::string &physical_interface, uint16_t tx_vlan_id, uint16_t rx_vlan_id, VmInterface::DeviceType device_type, VmInterface::VmiType vmi_type, Interface::Transport transport) : VmInterfaceData(NULL, NULL, INSTANCE_MSG, transport), ipv4_addr_(ipv4_addr), ipv6_addr_(ipv6_addr), mac_addr_(mac_addr), vm_name_(vm_name), vm_uuid_(vm_uuid), vm_project_uuid_(vm_project_uuid), physical_interface_(physical_interface), tx_vlan_id_(tx_vlan_id), rx_vlan_id_(rx_vlan_id), device_type_(device_type), vmi_type_(vmi_type) { } VmInterfaceNovaData::~VmInterfaceNovaData() { } VmInterface *VmInterfaceNovaData::OnAdd(const InterfaceTable *table, const VmInterfaceKey *key) const { Interface *parent = NULL; if (tx_vlan_id_ != VmInterface::kInvalidVlanId && rx_vlan_id_ != VmInterface::kInvalidVlanId && physical_interface_ != Agent::NullString()) { PhysicalInterfaceKey key_1(physical_interface_); parent = static_cast<Interface *> (table->agent()->interface_table()->FindActiveEntry(&key_1)); assert(parent != NULL); } boost::system::error_code ec; MacAddress mac = MacAddress::FromString(mac_addr_, &ec); if (ec.value() != 0) { mac.Zero(); } VmInterface *vmi = new VmInterface(key->uuid_, key->name_, ipv4_addr_, mac, vm_name_, vm_project_uuid_, tx_vlan_id_, rx_vlan_id_, parent, ipv6_addr_, device_type_, vmi_type_); vmi->SetConfigurer(VmInterface::INSTANCE_MSG); vmi->nova_ip_addr_ = ipv4_addr_; vmi->nova_ip6_addr_ = ipv6_addr_; return vmi; } bool VmInterfaceNovaData::OnDelete(const InterfaceTable *table, VmInterface *vmi) const { if (vmi->IsConfigurerSet(VmInterface::INSTANCE_MSG) == false) return true; VmInterfaceConfigData data(NULL, NULL); vmi->Resync(table, &data); vmi->ResetConfigurer(VmInterface::CONFIG); vmi->ResetConfigurer(VmInterface::INSTANCE_MSG); return true; } bool VmInterfaceNovaData::OnResync(const InterfaceTable *table, VmInterface *vmi, bool *force_update) const { bool ret = false; if (vmi->vm_project_uuid_ != vm_project_uuid_) { vmi->vm_project_uuid_ = vm_project_uuid_; ret = true; } if (vmi->tx_vlan_id_ != tx_vlan_id_) { vmi->tx_vlan_id_ = tx_vlan_id_; ret = true; } if (vmi->rx_vlan_id_ != rx_vlan_id_) { vmi->rx_vlan_id_ = rx_vlan_id_; ret = true; } if (vmi->nova_ip_addr_ != ipv4_addr_) { vmi->nova_ip_addr_ = ipv4_addr_; ret = true; } if (vmi->nova_ip6_addr_ != ipv6_addr_) { vmi->nova_ip6_addr_ = ipv6_addr_; ret = true; } vmi->SetConfigurer(VmInterface::INSTANCE_MSG); return ret; } ///////////////////////////////////////////////////////////////////////////// // VmInterfaceMirrorData routines ///////////////////////////////////////////////////////////////////////////// bool VmInterfaceMirrorData::OnResync(const InterfaceTable *table, VmInterface *vmi, bool *force_update) const { bool ret = false; MirrorEntry *mirror_entry = NULL; if (mirror_enable_ == true) { mirror_entry = table->FindMirrorRef(analyzer_name_); } if (vmi->mirror_entry_ != mirror_entry) { vmi->mirror_entry_ = mirror_entry; ret = true; } return ret; } ///////////////////////////////////////////////////////////////////////////// // VmInterfaceIpAddressData routines ///////////////////////////////////////////////////////////////////////////// // Update for VM IP address only // For interfaces in IP Fabric VRF, we send DHCP requests to external servers // if config doesnt provide an address. This address is updated here. bool VmInterfaceIpAddressData::OnResync(const InterfaceTable *table, VmInterface *vmi, bool *force_update) const { bool ret = false; if (vmi->os_index_ == VmInterface::kInvalidIndex) { vmi->GetOsParams(table->agent()); if (vmi->os_index_ != VmInterface::kInvalidIndex) ret = true; } // Ignore IP address change if L3 Forwarding not enabled if (!vmi->layer3_forwarding_) { return ret; } Ip4Address addr = Ip4Address(0); if (vmi->CopyIpAddress(addr)) { ret = true; } return ret; } ///////////////////////////////////////////////////////////////////////////// // VmInterfaceOsOperStateData routines ///////////////////////////////////////////////////////////////////////////// // Resync oper-state for the interface bool VmInterfaceOsOperStateData::OnResync(const InterfaceTable *table, VmInterface *vmi, bool *force_update) const { bool ret = false; uint32_t old_os_index = vmi->os_index_; bool old_ipv4_active = vmi->ipv4_active_; bool old_ipv6_active = vmi->ipv6_active_; vmi->GetOsParams(table->agent()); if (vmi->os_index_ != old_os_index) ret = true; vmi->ipv4_active_ = vmi->IsIpv4Active(); if (vmi->ipv4_active_ != old_ipv4_active) ret = true; vmi->ipv6_active_ = vmi->IsIpv6Active(); if (vmi->ipv6_active_ != old_ipv6_active) ret = true; // Resync the Oper data for SubInterfaces if attached to parent interface. if (ret == true) vmi->UpdateOperStateOfSubIntf(table); return ret; } bool VmInterfaceGlobalVrouterData::OnResync(const InterfaceTable *table, VmInterface *vmi, bool *force_update) const { bool ret = false; if (layer3_forwarding_ != vmi->layer3_forwarding_) { vmi->layer3_forwarding_ = layer3_forwarding_; *force_update = true; ret = true; } if (bridging_ != vmi->bridging_) { vmi->bridging_= bridging_; *force_update = true; ret = true; } if (vxlan_id_ != vmi->vxlan_id_) ret = true; if (vmi->ecmp_load_balance().use_global_vrouter()) { *force_update = true; ret = true; } return ret; } VmInterfaceHealthCheckData::VmInterfaceHealthCheckData() : VmInterfaceData(NULL, NULL, HEALTH_CHECK, Interface::TRANSPORT_INVALID) { } VmInterfaceHealthCheckData::~VmInterfaceHealthCheckData() { } bool VmInterfaceHealthCheckData::OnResync(const InterfaceTable *table, VmInterface *vmi, bool *force_update) const { return vmi->UpdateIsHealthCheckActive(); } VmInterfaceNewFlowDropData::VmInterfaceNewFlowDropData(bool drop_new_flows) : VmInterfaceData(NULL, NULL, DROP_NEW_FLOWS, Interface::TRANSPORT_INVALID), drop_new_flows_(drop_new_flows) { } VmInterfaceNewFlowDropData::~VmInterfaceNewFlowDropData() { } bool VmInterfaceNewFlowDropData::OnResync(const InterfaceTable *table, VmInterface *vmi, bool *force_update) const { if (vmi->drop_new_flows_ != drop_new_flows_) { vmi->drop_new_flows_ = drop_new_flows_; return true; } return false; } ///////////////////////////////////////////////////////////////////////////// // VM Port Entry utility routines ///////////////////////////////////////////////////////////////////////////// // Does the VMInterface need a physical device to be present bool VmInterface::NeedDevice() const { bool ret = true; if (device_type_ == TOR) ret = false; if (device_type_ == VM_VLAN_ON_VMI) ret = false; if (subnet_.is_unspecified() == false) { ret = false; } if (transport_ != TRANSPORT_ETHERNET) { ret = false; } if (rx_vlan_id_ != VmInterface::kInvalidVlanId) { ret = false; } else { // Sanity check. rx_vlan_id is set, make sure tx_vlan_id is also set assert(tx_vlan_id_ == VmInterface::kInvalidVlanId); } return ret; } void VmInterface::GetOsParams(Agent *agent) { if (NeedDevice()) { Interface::GetOsParams(agent); return; } os_index_ = Interface::kInvalidIndex; mac_ = agent->vrrp_mac(); os_oper_state_ = true; } // A VM Interface is L3 active under following conditions, // - If interface is deleted, it is inactive // - VN, VRF are set // - If sub_interface VMIs, parent_ should be set // (We dont track parent_ and activate sub-interfaces. So, we only check // parent_ is present and not necessarily active) // - For non-VMWARE hypervisors, // The tap interface must be created. This is verified by os_index_ // - MAC address set for the interface bool VmInterface::IsActive() const { if (IsDeleted()) { return false; } if (!admin_state_) { return false; } // If sub_interface VMIs, parent_vmi_ should be set // (We dont track parent_ and activate sub-interfaces. So, we only check // paremt_vmi is present and not necessarily active) // Check if parent is not active set the SubInterface also not active const VmInterface *parentIntf = static_cast<const VmInterface *>(parent()); if (device_type_ == VM_VLAN_ON_VMI) { if (parentIntf == NULL) return false; else if (parentIntf->IsActive() == false) { return false; } } if (device_type_ == REMOTE_VM_VLAN_ON_VMI) { if (tx_vlan_id_ == VmInterface::kInvalidVlanId || rx_vlan_id_ == VmInterface::kInvalidVlanId || parent_.get() == NULL) return false; } if ((vn_.get() == NULL) || (vrf_.get() == NULL)) { return false; } if (!vn_.get()->admin_state()) { return false; } if (NeedDevice() == false) { return true; } if (os_index_ == kInvalidIndex) return false; if (os_oper_state_ == false) return false; return mac_set_; } bool VmInterface::IsMetaDataIPActive() const { if (!layer3_forwarding()) { return false; } if (primary_ip6_addr_.is_unspecified()) { if (subnet_.is_unspecified() && primary_ip_addr_.to_ulong() == 0) { return false; } if (subnet_.is_unspecified() == false && parent_ == NULL) { return false; } } return IsActive(); } bool VmInterface::IsMetaDataL2Active() const { if (!bridging()) { return false; } return IsActive(); } bool VmInterface::IsIpv4Active() const { if (!layer3_forwarding()) { return false; } if (subnet_.is_unspecified() && primary_ip_addr_.to_ulong() == 0) { return false; } if (subnet_.is_unspecified() == false && parent_ == NULL) { return false; } if (!is_hc_active_) { return false; } return IsActive(); } bool VmInterface::IsIpv6Active() const { if (!layer3_forwarding() || (primary_ip6_addr_.is_unspecified())) { return false; } if (!is_hc_active_) { return false; } return IsActive(); } bool VmInterface::IsL2Active() const { if (!bridging()) { return false; } if (!is_hc_active_) { return false; } return IsActive(); } bool VmInterface::WaitForTraffic() const { // do not continue if the interface is inactive or if the VRF is deleted if (IsActive() == false || vrf_->IsDeleted()) { return false; } //Get the instance ip route and its corresponding traffic seen status InetUnicastRouteKey rt_key(peer_.get(), vrf_->GetName(), primary_ip_addr_, 32); const InetUnicastRouteEntry *rt = static_cast<const InetUnicastRouteEntry *>( vrf_->GetInet4UnicastRouteTable()->FindActiveEntry(&rt_key)); if (!rt) { return false; } if (rt->FindPath(peer_.get()) == false) { return false; } return rt->FindPath(peer_.get())->path_preference().wait_for_traffic(); } // Policy is disabled only if user explicitly sets disable policy. // If user changes to disable policy. only policy will be enabled in case of // link local services & BGP as a service. bool VmInterface::PolicyEnabled() const { if (disable_policy_) { return false; } return true; } // VN is in VXLAN mode if, // - Tunnel type computed is VXLAN and // - vxlan_id_ set in VN is non-zero bool VmInterface::IsVxlanMode() const { if (TunnelType::ComputeType(TunnelType::AllType()) != TunnelType::VXLAN) return false; return vxlan_id_ != 0; } // Allocate MPLS Label for Layer3 routes void VmInterface::AllocL3MplsLabel(bool force_update, bool policy_change, uint32_t new_label) { if (fabric_port_) return; bool new_entry = false; Agent *agent = static_cast<InterfaceTable *>(get_table())->agent(); if (label_ == MplsTable::kInvalidLabel) { if (new_label == MplsTable::kInvalidLabel) { label_ = agent->mpls_table()->AllocLabel(); } else { label_ = new_label; } new_entry = true; UpdateMetaDataIpInfo(); } if (force_update || policy_change || new_entry) MplsLabel::CreateVPortLabel(agent, label_, GetUuid(), policy_enabled_, InterfaceNHFlags::INET4, vm_mac_); } // Delete MPLS Label for Layer3 routes void VmInterface::DeleteL3MplsLabel() { if (label_ == MplsTable::kInvalidLabel) { return; } Agent *agent = static_cast<InterfaceTable *>(get_table())->agent(); MplsLabel::Delete(agent, label_); label_ = MplsTable::kInvalidLabel; UpdateMetaDataIpInfo(); } // Allocate MPLS Label for Bridge entries void VmInterface::AllocL2MplsLabel(bool force_update, bool policy_change) { bool new_entry = false; if (l2_label_ == MplsTable::kInvalidLabel) { Agent *agent = static_cast<InterfaceTable *>(get_table())->agent(); l2_label_ = agent->mpls_table()->AllocLabel(); new_entry = true; } Agent *agent = static_cast<InterfaceTable *>(get_table())->agent(); if (force_update || policy_change || new_entry) MplsLabel::CreateVPortLabel(agent, l2_label_, GetUuid(), policy_enabled_, InterfaceNHFlags::BRIDGE, vm_mac_); } // Delete MPLS Label for Bridge Entries void VmInterface::DeleteL2MplsLabel() { if (l2_label_ == MplsTable::kInvalidLabel) { return; } Agent *agent = static_cast<InterfaceTable *>(get_table())->agent(); MplsLabel::Delete(agent, l2_label_); l2_label_ = MplsTable::kInvalidLabel; } void VmInterface::UpdateL3TunnelId(bool force_update, bool policy_change) { //Currently only MPLS encap ind no VXLAN is supported for L3. //Unconditionally create a label if (policy_change && (label_ != MplsTable::kInvalidLabel)) { /* We delete the existing label and add new one whenever policy changes * to ensure that leaked routes point to NH with correct policy * status. This is to handle the case when after leaking the route, if * policy is disabled on VMI, the leaked route was still pointing to * policy enabled NH */ /* Fetch new label before we delete the existing label */ Agent *agent = static_cast<InterfaceTable *>(get_table())->agent(); uint32_t new_label = agent->mpls_table()->AllocLabel(); DeleteL3MplsLabel(); AllocL3MplsLabel(force_update, policy_change, new_label); } else { AllocL3MplsLabel(force_update, policy_change, MplsTable::kInvalidLabel); } } void VmInterface::DeleteL3TunnelId() { if (!metadata_ip_active_) { DeleteL3MplsLabel(); } } //Check if interface transitioned from inactive to active layer 2 forwarding bool VmInterface::L2Activated(bool old_l2_active) { if (old_l2_active == false && l2_active_ == true) { return true; } return false; } // check if interface transitioned from inactive to active for bridging bool VmInterface::BridgingActivated(bool old_bridging) { if (old_bridging == false && bridging_ == true) { return true; } return false; } //Check if interface transitioned from inactive to active IP forwarding bool VmInterface::Ipv4Activated(bool old_ipv4_active) { if (old_ipv4_active == false && ipv4_active_ == true) { return true; } return false; } bool VmInterface::Ipv6Activated(bool old_ipv6_active) { if (old_ipv6_active == false && ipv6_active_ == true) { return true; } return false; } //Check if interface transitioned from active bridging to inactive state bool VmInterface::L2Deactivated(bool old_l2_active) { if (old_l2_active == true && l2_active_ == false) { return true; } return false; } //Check if interface transitioned from active bridging to inactive state bool VmInterface::BridgingDeactivated(bool old_bridging) { if (old_bridging == true && bridging_ == false) { return true; } return false; } //Check if interface transitioned from active IP forwarding to inactive state bool VmInterface::Ipv4Deactivated(bool old_ipv4_active) { if (old_ipv4_active == true && ipv4_active_ == false) { return true; } return false; } bool VmInterface::Ipv6Deactivated(bool old_ipv6_active) { if (old_ipv6_active == true && ipv6_active_ == false) { return true; } return false; } void VmInterface::UpdateFlowKeyNextHop() { if (!IsActive()) { flow_key_nh_.reset(); return; } InterfaceTable *table = static_cast<InterfaceTable *>(get_table()); Agent *agent = table->agent(); //If Layer3 forwarding is configured irrespective of ipv4/v6 status, //flow_key_nh should be l3 based. if (layer3_forwarding()) { InterfaceNHKey key(new VmInterfaceKey(AgentKey::ADD_DEL_CHANGE, GetUuid(), ""), true, InterfaceNHFlags::INET4, vm_mac_); flow_key_nh_ = static_cast<const NextHop *>( agent->nexthop_table()->FindActiveEntry(&key)); return; } //L2 mode is identified if layer3_forwarding is diabled. InterfaceNHKey key(new VmInterfaceKey(AgentKey::ADD_DEL_CHANGE, GetUuid(), ""), true, InterfaceNHFlags::BRIDGE, vm_mac_); flow_key_nh_ = static_cast<const NextHop *>( agent->nexthop_table()->FindActiveEntry(&key)); } void VmInterface::UpdateMacVmBinding() { BridgeAgentRouteTable *table = static_cast<BridgeAgentRouteTable *> (vrf_->GetBridgeRouteTable()); Agent *agent = table->agent(); table->AddMacVmBindingRoute(agent->mac_vm_binding_peer(), vrf_->GetName(), vm_mac_, this); } void VmInterface::UpdateL3NextHop() { InterfaceTable *table = static_cast<InterfaceTable *>(get_table()); Agent *agent = table->agent(); //layer3_forwarding config is not set, so delete as i/f is active. if (!layer3_forwarding_) { if ((l3_interface_nh_policy_.get() != NULL) || (l3_interface_nh_no_policy_.get() != NULL)) { DeleteL3NextHop(); } return; } InterfaceNH::CreateL3VmInterfaceNH(GetUuid(), vm_mac_, vrf_->GetName()); InterfaceNHKey key1(new VmInterfaceKey(AgentKey::ADD_DEL_CHANGE, GetUuid(), ""), true, InterfaceNHFlags::INET4, vm_mac_); l3_interface_nh_policy_ = static_cast<NextHop *>(agent->nexthop_table()->FindActiveEntry(&key1)); InterfaceNHKey key2(new VmInterfaceKey(AgentKey::ADD_DEL_CHANGE, GetUuid(), ""), false, InterfaceNHFlags::INET4, vm_mac_); l3_interface_nh_no_policy_ = static_cast<NextHop *>(agent->nexthop_table()->FindActiveEntry(&key2)); } void VmInterface::DeleteL3NextHop() { InterfaceNH::DeleteL3InterfaceNH(GetUuid(), vm_mac_); l3_interface_nh_policy_.reset(); l3_interface_nh_no_policy_.reset(); } //Create these NH irrespective of mode, as multicast uses l2 NH. void VmInterface::UpdateL2NextHop() { InterfaceTable *table = static_cast<InterfaceTable *>(get_table()); Agent *agent = table->agent(); if (l2_interface_nh_policy_.get() == NULL) { InterfaceNH::CreateL2VmInterfaceNH(GetUuid(), vm_mac_, vrf_->GetName()); InterfaceNHKey key(new VmInterfaceKey(AgentKey::ADD_DEL_CHANGE, GetUuid(), ""), true, InterfaceNHFlags::BRIDGE, vm_mac_); l2_interface_nh_policy_ = static_cast<NextHop *>(agent-> nexthop_table()->FindActiveEntry(&key)); } if (l2_interface_nh_no_policy_.get() == NULL) { InterfaceNHKey key(new VmInterfaceKey(AgentKey::ADD_DEL_CHANGE, GetUuid(), ""), false, InterfaceNHFlags::BRIDGE, vm_mac_); l2_interface_nh_no_policy_ = static_cast<NextHop *>(agent-> nexthop_table()->FindActiveEntry(&key)); } } void VmInterface::DeleteMacVmBinding(const VrfEntry *old_vrf) { if (old_vrf == NULL) return; BridgeAgentRouteTable *table = static_cast<BridgeAgentRouteTable *> (old_vrf->GetBridgeRouteTable()); if (table == NULL) return; Agent *agent = table->agent(); table->DeleteMacVmBindingRoute(agent->mac_vm_binding_peer(), old_vrf->GetName(), vm_mac_, this); } void VmInterface::DeleteL2NextHop() { InterfaceNH::DeleteL2InterfaceNH(GetUuid(), vm_mac_); if (l2_interface_nh_policy_.get() != NULL) l2_interface_nh_policy_.reset(); if (l2_interface_nh_no_policy_.get() != NULL) l2_interface_nh_no_policy_.reset(); } void VmInterface::DeleteL2ReceiveRoute(const VrfEntry *old_vrf, bool old_bridging) { if (old_vrf) { InterfaceTable *table = static_cast<InterfaceTable *>(get_table()); Agent *agent = table->agent(); BridgeAgentRouteTable::Delete(peer_.get(), old_vrf->GetName(), GetVifMac(agent), 0); } } bool VmInterface::UpdateIsHealthCheckActive() { bool is_hc_active = true; HealthCheckInstanceSet::iterator it = hc_instance_set_.begin(); while (it != hc_instance_set_.end()) { if ((*it)->active() == false) { // if any of the health check instance reports not active // status mark interface health check status inactive is_hc_active = false; break; } it++; } if (is_hc_active_ != is_hc_active) { is_hc_active_ = is_hc_active; return true; } return false; } IpAddress VmInterface::GetServiceIp(const IpAddress &vm_ip) const { IpAddress ip; if (vm_ip.is_v4()) { ip = Ip4Address(0); } else if (vm_ip.is_v6()) { ip = Ip6Address(); } if (vn_.get() == NULL) { return ip; } const VnIpam *ipam = NULL; if (subnet_.is_unspecified()) { ipam = vn_->GetIpam(vm_ip); } else { ipam = vn_->GetIpam(subnet_); } if (ipam) { if ((vm_ip.is_v4() && ipam->dns_server.is_v4()) || (vm_ip.is_v6() && ipam->dns_server.is_v6())) { return ipam->dns_server; } } return ip; } // Add/Update route. Delete old route if VRF or address changed void VmInterface::UpdateIpv4InterfaceRoute(bool old_ipv4_active, bool force_update, VrfEntry * old_vrf, const Ip4Address &old_addr) { Ip4Address ip = GetServiceIp(primary_ip_addr_).to_v4(); // If interface was already active earlier and there is no force_update or // policy_change, return if (old_ipv4_active == true && force_update == false && old_addr == primary_ip_addr_ && vm_ip_service_addr_ == ip) { return; } // We need to have valid IP and VRF to add route if (primary_ip_addr_.to_ulong() != 0 && vrf_.get() != NULL) { // Add route if old was inactive or force_update is set if (old_ipv4_active == false || force_update == true || old_addr != primary_ip_addr_ || vm_ip_service_addr_ != ip) { vm_ip_service_addr_ = ip; AddRoute(vrf_->GetName(), primary_ip_addr_, 32, vn_->GetName(), false, ecmp_, false, false, vm_ip_service_addr_, Ip4Address(0), CommunityList(), label_); } } // If there is change in VRF or IP address, delete old route if (old_vrf != vrf_.get() || primary_ip_addr_ != old_addr) { DeleteIpv4InterfaceRoute(old_vrf, old_addr); } } void VmInterface::UpdateResolveRoute(bool old_ipv4_active, bool force_update, bool policy_change, VrfEntry * old_vrf, const Ip4Address &old_addr, uint8_t old_plen) { if (old_ipv4_active == true && force_update == false && policy_change == false && old_addr == subnet_ && subnet_plen_ == old_plen) { return; } if (old_vrf && (old_vrf != vrf_.get() || old_addr != subnet_ || subnet_plen_ != old_plen)) { DeleteResolveRoute(old_vrf, old_addr, old_plen); } if (subnet_.to_ulong() != 0 && vrf_.get() != NULL && vn_.get() != NULL) { SecurityGroupList sg_id_list; CopySgIdList(&sg_id_list); VmInterfaceKey vm_intf_key(AgentKey::ADD_DEL_CHANGE, GetUuid(), ""); InetUnicastAgentRouteTable::AddResolveRoute(peer_.get(), vrf_->GetName(), Address::GetIp4SubnetAddress(subnet_, subnet_plen_), subnet_plen_, vm_intf_key, vrf_->table_label(), policy_enabled_, vn_->GetName(), sg_id_list); } } void VmInterface::DeleteResolveRoute(VrfEntry *old_vrf, const Ip4Address &old_addr, const uint8_t plen) { DeleteRoute(old_vrf->GetName(), old_addr, plen); } void VmInterface::DeleteIpv4InterfaceRoute(VrfEntry *old_vrf, const Ip4Address &old_addr) { if ((old_vrf == NULL) || (old_addr.to_ulong() == 0)) return; DeleteRoute(old_vrf->GetName(), old_addr, 32); } // Add meta-data route if linklocal_ip is needed void VmInterface::UpdateMetadataRoute(bool old_metadata_ip_active, VrfEntry *old_vrf) { if (metadata_ip_active_ == false || old_metadata_ip_active == true) return; if (!need_linklocal_ip_) { return; } InterfaceTable *table = static_cast<InterfaceTable *>(get_table()); Agent *agent = table->agent(); if (mdata_ip_.get() == NULL) { mdata_ip_.reset(new MetaDataIp(agent->metadata_ip_allocator(), this, id())); } //mdata_ip_->set_nat_src_ip(Ip4Address(METADATA_IP_ADDR)); mdata_ip_->set_active(true); } // Delete meta-data route void VmInterface::DeleteMetadataRoute(bool old_active, VrfEntry *old_vrf, bool old_need_linklocal_ip) { if (!old_need_linklocal_ip) { return; } if (mdata_ip_.get() != NULL) { mdata_ip_->set_active(false); } } void VmInterface::CleanupFloatingIpList() { FloatingIpSet::iterator it = floating_ip_list_.list_.begin(); while (it != floating_ip_list_.list_.end()) { FloatingIpSet::iterator prev = it++; if (prev->del_pending_ == false) continue; if (prev->floating_ip_.is_v4()) { floating_ip_list_.v4_count_--; assert(floating_ip_list_.v4_count_ >= 0); } else { floating_ip_list_.v6_count_--; assert(floating_ip_list_.v6_count_ >= 0); } floating_ip_list_.list_.erase(prev); } } void VmInterface::UpdateFloatingIp(bool force_update, bool policy_change, bool l2, uint32_t old_ethernet_tag) { FloatingIpSet::iterator it = floating_ip_list_.list_.begin(); while (it != floating_ip_list_.list_.end()) { FloatingIpSet::iterator prev = it++; if (prev->del_pending_) { prev->DeActivate(this, l2, old_ethernet_tag); } else { prev->Activate(this, force_update||policy_change, l2, old_ethernet_tag); } } } void VmInterface::DeleteFloatingIp(bool l2, uint32_t old_ethernet_tag) { FloatingIpSet::iterator it = floating_ip_list_.list_.begin(); while (it != floating_ip_list_.list_.end()) { FloatingIpSet::iterator prev = it++; prev->DeActivate(this, l2, old_ethernet_tag); } } void VmInterface::CleanupAliasIpList() { AliasIpSet::iterator it = alias_ip_list_.list_.begin(); while (it != alias_ip_list_.list_.end()) { AliasIpSet::iterator prev = it++; if (prev->del_pending_ == false) continue; if (prev->alias_ip_.is_v4()) { alias_ip_list_.v4_count_--; assert(alias_ip_list_.v4_count_ >= 0); } else { alias_ip_list_.v6_count_--; assert(alias_ip_list_.v6_count_ >= 0); } alias_ip_list_.list_.erase(prev); } } void VmInterface::UpdateAliasIp(bool force_update, bool policy_change) { AliasIpSet::iterator it = alias_ip_list_.list_.begin(); while (it != alias_ip_list_.list_.end()) { AliasIpSet::iterator prev = it++; if (prev->del_pending_) { prev->DeActivate(this); } else { prev->Activate(this, force_update||policy_change); } } } void VmInterface::DeleteAliasIp() { AliasIpSet::iterator it = alias_ip_list_.list_.begin(); while (it != alias_ip_list_.list_.end()) { AliasIpSet::iterator prev = it++; prev->DeActivate(this); } } void VmInterface::UpdateServiceVlan(bool force_update, bool policy_change, bool old_ipv4_active, bool old_ipv6_active) { ServiceVlanSet::iterator it = service_vlan_list_.list_.begin(); while (it != service_vlan_list_.list_.end()) { ServiceVlanSet::iterator prev = it++; if (prev->del_pending_) { prev->DeActivate(this); service_vlan_list_.list_.erase(prev); } else { prev->Activate(this, force_update, old_ipv4_active, old_ipv6_active); } } } void VmInterface::DeleteServiceVlan() { ServiceVlanSet::iterator it = service_vlan_list_.list_.begin(); while (it != service_vlan_list_.list_.end()) { ServiceVlanSet::iterator prev = it++; prev->DeActivate(this); if (prev->del_pending_) { service_vlan_list_.list_.erase(prev); } } } void VmInterface::UpdateStaticRoute(bool force_update) { StaticRouteSet::iterator it = static_route_list_.list_.begin(); while (it != static_route_list_.list_.end()) { StaticRouteSet::iterator prev = it++; /* V4 static routes should be enabled only if ipv4_active_ is true * V6 static routes should be enabled only if ipv6_active_ is true */ if ((!ipv4_active_ && prev->addr_.is_v4()) || (!ipv6_active_ && prev->addr_.is_v6())) { continue; } if (prev->del_pending_) { prev->DeActivate(this); static_route_list_.list_.erase(prev); } else { prev->Activate(this, force_update); } } } void VmInterface::DeleteStaticRoute() { StaticRouteSet::iterator it = static_route_list_.list_.begin(); while (it != static_route_list_.list_.end()) { StaticRouteSet::iterator prev = it++; prev->DeActivate(this); if (prev->del_pending_) { static_route_list_.list_.erase(prev); } } } void VmInterface::UpdateAllowedAddressPair(bool force_update, bool policy_change, bool l2, bool old_layer2_forwarding, bool old_layer3_forwarding) { AllowedAddressPairSet::iterator it = allowed_address_pair_list_.list_.begin(); while (it != allowed_address_pair_list_.list_.end()) { AllowedAddressPairSet::iterator prev = it++; if (prev->del_pending_) { prev->L2DeActivate(this); prev->DeActivate(this); allowed_address_pair_list_.list_.erase(prev); } } for (it = allowed_address_pair_list_.list_.begin(); it != allowed_address_pair_list_.list_.end(); it++) { /* V4 AAP entries should be enabled only if ipv4_active_ is true * V6 AAP entries should be enabled only if ipv6_active_ is true */ if ((!ipv4_active_ && it->addr_.is_v4()) || (!ipv6_active_ && it->addr_.is_v6())) { continue; } if (l2) { it->L2Activate(this, force_update, policy_change, old_layer2_forwarding, old_layer3_forwarding); } else { it->Activate(this, force_update, policy_change); } } } void VmInterface::DeleteAllowedAddressPair(bool l2) { AllowedAddressPairSet::iterator it = allowed_address_pair_list_.list_.begin(); while (it != allowed_address_pair_list_.list_.end()) { AllowedAddressPairSet::iterator prev = it++; if (l2) { prev->L2DeActivate(this); } else { prev->DeActivate(this); } if (prev->del_pending_) { prev->L2DeActivate(this); prev->DeActivate(this); allowed_address_pair_list_.list_.erase(prev); } } } void VmInterface::UpdateVrfAssignRule() { Agent *agent = static_cast<InterfaceTable *>(get_table())->agent(); //Erase all delete marked entry VrfAssignRuleSet::iterator it = vrf_assign_rule_list_.list_.begin(); while (it != vrf_assign_rule_list_.list_.end()) { VrfAssignRuleSet::iterator prev = it++; if (prev->del_pending_) { vrf_assign_rule_list_.list_.erase(prev); } } if (vrf_assign_rule_list_.list_.size() == 0 && vrf_assign_acl_.get() != NULL) { DeleteVrfAssignRule(); return; } if (vrf_assign_rule_list_.list_.size() == 0) { return; } AclSpec acl_spec; acl_spec.acl_id = uuid_; //Create the ACL it = vrf_assign_rule_list_.list_.begin(); uint32_t id = 0; for (;it != vrf_assign_rule_list_.list_.end();it++) { //Go thru all match condition and create ACL entry AclEntrySpec ace_spec; ace_spec.id = id++; if (ace_spec.Populate(&(it->match_condition_)) == false) { continue; } /* Add both v4 and v6 rules regardless of whether interface is * ipv4_active_/ipv6_active_ */ ActionSpec vrf_translate_spec; vrf_translate_spec.ta_type = TrafficAction::VRF_TRANSLATE_ACTION; vrf_translate_spec.simple_action = TrafficAction::VRF_TRANSLATE; vrf_translate_spec.vrf_translate.set_vrf_name(it->vrf_name_); vrf_translate_spec.vrf_translate.set_ignore_acl(it->ignore_acl_); ace_spec.action_l.push_back(vrf_translate_spec); acl_spec.acl_entry_specs_.push_back(ace_spec); } DBRequest req; AclKey *key = new AclKey(acl_spec.acl_id); AclData *data = new AclData(agent, NULL, acl_spec); req.oper = DBRequest::DB_ENTRY_ADD_CHANGE; req.key.reset(key); req.data.reset(data); agent->acl_table()->Process(req); AclKey entry_key(uuid_); AclDBEntry *acl = static_cast<AclDBEntry *>( agent->acl_table()->FindActiveEntry(&entry_key)); assert(acl); vrf_assign_acl_ = acl; } void VmInterface::DeleteVrfAssignRule() { Agent *agent = static_cast<InterfaceTable *>(get_table())->agent(); VrfAssignRuleSet::iterator it = vrf_assign_rule_list_.list_.begin(); while (it != vrf_assign_rule_list_.list_.end()) { VrfAssignRuleSet::iterator prev = it++; if (prev->del_pending_) { vrf_assign_rule_list_.list_.erase(prev); } } if (vrf_assign_acl_ != NULL) { vrf_assign_acl_ = NULL; DBRequest req; AclKey *key = new AclKey(uuid_); req.oper = DBRequest::DB_ENTRY_DELETE; req.key.reset(key); req.data.reset(NULL); agent->acl_table()->Process(req); } } void VmInterface::UpdateSecurityGroup() { SecurityGroupEntrySet::iterator it = sg_list_.list_.begin(); while (it != sg_list_.list_.end()) { SecurityGroupEntrySet::iterator prev = it++; if (prev->del_pending_) { sg_list_.list_.erase(prev); } else { prev->Activate(this); } } } void VmInterface::DeleteSecurityGroup() { SecurityGroupEntrySet::iterator it = sg_list_.list_.begin(); while (it != sg_list_.list_.end()) { SecurityGroupEntrySet::iterator prev = it++; if (prev->del_pending_) { sg_list_.list_.erase(prev); } } } void VmInterface::UpdateFatFlow() { DeleteFatFlow(); } void VmInterface::DeleteFatFlow() { FatFlowEntrySet::iterator it = fat_flow_list_.list_.begin(); while (it != fat_flow_list_.list_.end()) { FatFlowEntrySet::iterator prev = it++; if (prev->del_pending_) { fat_flow_list_.list_.erase(prev); } } } void VmInterface::UpdateL2TunnelId(bool force_update, bool policy_change) { AllocL2MplsLabel(force_update, policy_change); } void VmInterface::DeleteL2TunnelId() { DeleteL2MplsLabel(); } void VmInterface::UpdateL2InterfaceRoute(bool old_bridging, bool force_update, VrfEntry *old_vrf, const Ip4Address &old_v4_addr, const Ip6Address &old_v6_addr, int old_ethernet_tag, bool old_layer3_forwarding, bool policy_changed, const Ip4Address &new_ip_addr, const Ip6Address &new_ip6_addr, const MacAddress &mac, const IpAddress &dependent_ip) const { if (ethernet_tag_ != old_ethernet_tag) { force_update = true; } if (old_layer3_forwarding != layer3_forwarding_) { force_update = true; } if (old_vrf && old_vrf != vrf()) { force_update = true; } //Encap change will result in force update of l2 routes. if (force_update) { DeleteL2InterfaceRoute(true, old_vrf, old_v4_addr, old_v6_addr, old_ethernet_tag, mac); } else { if (new_ip_addr != old_v4_addr) { force_update = true; DeleteL2InterfaceRoute(true, old_vrf, old_v4_addr, Ip6Address(), old_ethernet_tag, mac); } if (new_ip6_addr != old_v6_addr) { force_update = true; DeleteL2InterfaceRoute(true, old_vrf, Ip4Address(), old_v6_addr, old_ethernet_tag, mac); } } assert(peer_.get()); EvpnAgentRouteTable *table = static_cast<EvpnAgentRouteTable *> (vrf_->GetEvpnRouteTable()); SecurityGroupList sg_id_list; CopySgIdList(&sg_id_list); PathPreference path_preference; SetPathPreference(&path_preference, false, dependent_ip); if (policy_changed == true) { //Resync the nexthop table->ResyncVmRoute(peer_.get(), vrf_->GetName(), mac, new_ip_addr, ethernet_tag_, NULL); table->ResyncVmRoute(peer_.get(), vrf_->GetName(), mac, new_ip6_addr, ethernet_tag_, NULL); } if (old_bridging && force_update == false) return; if (new_ip_addr.is_unspecified() || layer3_forwarding_ == true) { table->AddLocalVmRoute(peer_.get(), vrf_->GetName(), mac, this, new_ip_addr, l2_label_, vn_->GetName(), sg_id_list, path_preference, ethernet_tag_); } if (new_ip6_addr.is_unspecified() == false && layer3_forwarding_ == true) { table->AddLocalVmRoute(peer_.get(), vrf_->GetName(), mac, this, new_ip6_addr, l2_label_, vn_->GetName(), sg_id_list, path_preference, ethernet_tag_); } } void VmInterface::DeleteL2InterfaceRoute(bool old_bridging, VrfEntry *old_vrf, const Ip4Address &old_v4_addr, const Ip6Address &old_v6_addr, int old_ethernet_tag, const MacAddress &mac) const { if (old_bridging == false) return; if (old_vrf == NULL) return; EvpnAgentRouteTable *table = static_cast<EvpnAgentRouteTable *> (old_vrf->GetEvpnRouteTable()); if (table == NULL) return; table->DelLocalVmRoute(peer_.get(), old_vrf->GetName(), mac, this, old_v4_addr, old_ethernet_tag); table->DelLocalVmRoute(peer_.get(), old_vrf->GetName(), mac, this, old_v6_addr, old_ethernet_tag); } // Copy the SG List for VM Interface. Used to add route for interface void VmInterface::CopySgIdList(SecurityGroupList *sg_id_list) const { SecurityGroupEntrySet::const_iterator it; for (it = sg_list_.list_.begin(); it != sg_list_.list_.end(); ++it) { if (it->del_pending_) continue; if (it->sg_.get() == NULL) continue; sg_id_list->push_back(it->sg_->GetSgId()); } } // Set path-preference information for the route void VmInterface::SetPathPreference(PathPreference *pref, bool ecmp, const IpAddress &dependent_ip) const { pref->set_ecmp(ecmp); if (local_preference_ != INVALID) { pref->set_static_preference(true); } if (local_preference_ == HIGH || ecmp == true) { pref->set_preference(PathPreference::HIGH); } pref->set_dependent_ip(dependent_ip); pref->set_vrf(vrf()->GetName()); } void VmInterface::SetServiceVlanPathPreference(PathPreference *pref, const IpAddress &service_ip) const { bool ecmp_mode = false; IpAddress dependent_ip; //Logic for setting ecmp and tracking IP on Service chain route //Service vlan route can be active when interface is either //IPV4 active or IPV6 active, hence we have to consider both //IPV6 and IPV4 IP //If Service vlan is for Ipv4 route, then priority is as below //1> Service IP for v4 //3> Primary IP for v4 if (service_ip.is_v4()) { if (service_ip_ != Ip4Address(0)) { dependent_ip = service_ip_; ecmp_mode = service_ip_ecmp_; } else { dependent_ip = primary_ip_addr_; ecmp_mode = ecmp_; } } //If Service vlan is for Ipv6 route, then priority is as below //1> Service IP for v6 //3> Primary IP for v6 if (service_ip.is_v6()) { if (service_ip6_ != Ip6Address()) { dependent_ip = service_ip6_; ecmp_mode = service_ip_ecmp6_; } else { dependent_ip = primary_ip6_addr_; ecmp_mode = ecmp6_; } } pref->set_ecmp(ecmp_mode); if (local_preference_ != INVALID) { pref->set_static_preference(true); } if (local_preference_ == HIGH) { pref->set_preference(PathPreference::HIGH); } else { pref->set_preference(PathPreference::LOW); } pref->set_dependent_ip(dependent_ip); pref->set_vrf(vrf()->GetName()); } void VmInterface::CopyEcmpLoadBalance(EcmpLoadBalance &ecmp_load_balance) { if (ecmp_load_balance_.use_global_vrouter() == false) return ecmp_load_balance.Copy(ecmp_load_balance_); return ecmp_load_balance.Copy(agent()->oper_db()->global_vrouter()-> ecmp_load_balance()); } //Add a route for VM port //If ECMP route, add new composite NH and mpls label for same void VmInterface::AddRoute(const std::string &vrf_name, const IpAddress &addr, uint32_t plen, const std::string &dest_vn, bool force_policy, bool ecmp, bool is_local, bool is_health_check_service, const IpAddress &service_ip, const IpAddress &dependent_rt, const CommunityList &communities, uint32_t label) { SecurityGroupList sg_id_list; CopySgIdList(&sg_id_list); PathPreference path_preference; SetPathPreference(&path_preference, ecmp, dependent_rt); VnListType vn_list; vn_list.insert(dest_vn); EcmpLoadBalance ecmp_load_balance; CopyEcmpLoadBalance(ecmp_load_balance); InetUnicastAgentRouteTable::AddLocalVmRoute(peer_.get(), vrf_name, addr, plen, GetUuid(), vn_list, label, sg_id_list, communities, force_policy, path_preference, service_ip, ecmp_load_balance, is_local, is_health_check_service); return; } void VmInterface::ResolveRoute(const std::string &vrf_name, const Ip4Address &addr, uint32_t plen, const std::string &dest_vn, bool policy) { SecurityGroupList sg_id_list; CopySgIdList(&sg_id_list); VmInterfaceKey vm_intf_key(AgentKey::ADD_DEL_CHANGE, GetUuid(), ""); InetUnicastAgentRouteTable::AddResolveRoute(peer_.get(), vrf_name, Address::GetIp4SubnetAddress(addr, plen), plen, vm_intf_key, vrf_->table_label(), policy, dest_vn, sg_id_list); } void VmInterface::DeleteRoute(const std::string &vrf_name, const IpAddress &addr, uint32_t plen) { InetUnicastAgentRouteTable::Delete(peer_.get(), vrf_name, addr, plen); return; } // DHCP options applicable to the Interface bool VmInterface::GetInterfaceDhcpOptions( std::vector<autogen::DhcpOptionType> *options) const { if (oper_dhcp_options().are_dhcp_options_set()) { *options = oper_dhcp_options().dhcp_options(); return true; } return false; } // DHCP options applicable to the Subnet to which the interface belongs bool VmInterface::GetSubnetDhcpOptions( std::vector<autogen::DhcpOptionType> *options, bool ipv6) const { if (vn()) { const std::vector<VnIpam> &vn_ipam = vn()->GetVnIpam(); uint32_t index; for (index = 0; index < vn_ipam.size(); ++index) { if (!ipv6 && vn_ipam[index].IsSubnetMember(primary_ip_addr())) { break; } if (ipv6 && vn_ipam[index].IsSubnetMember(primary_ip6_addr())) { break; } } if (index < vn_ipam.size() && vn_ipam[index].oper_dhcp_options.are_dhcp_options_set()) { *options = vn_ipam[index].oper_dhcp_options.dhcp_options(); return true; } } return false; } // DHCP options applicable to the Ipam to which the interface belongs bool VmInterface::GetIpamDhcpOptions( std::vector<autogen::DhcpOptionType> *options, bool ipv6) const { if (vn()) { std::string ipam_name; autogen::IpamType ipam_type; if (!ipv6 && vn()->GetIpamData(primary_ip_addr(), &ipam_name, &ipam_type)) { *options = ipam_type.dhcp_option_list.dhcp_option; return true; } if (ipv6 && vn()->GetIpamData(primary_ip6_addr(), &ipam_name, &ipam_type)) { *options = ipam_type.dhcp_option_list.dhcp_option; return true; } } return false; } ///////////////////////////////////////////////////////////////////////////// // InstanceIp routines ///////////////////////////////////////////////////////////////////////////// VmInterface::InstanceIp::InstanceIp() : ListEntry(), ip_(), plen_(), ecmp_(false), l2_installed_(false), old_ecmp_(false), is_primary_(false), is_service_health_check_ip_(false), is_local_(false), old_tracking_ip_(), tracking_ip_() { } VmInterface::InstanceIp::InstanceIp(const InstanceIp &rhs) : ListEntry(rhs.installed_, rhs.del_pending_), ip_(rhs.ip_), plen_(rhs.plen_), ecmp_(rhs.ecmp_), l2_installed_(rhs.l2_installed_), old_ecmp_(rhs.old_ecmp_), is_primary_(rhs.is_primary_), is_service_health_check_ip_(rhs.is_service_health_check_ip_), is_local_(rhs.is_local_), old_tracking_ip_(rhs.old_tracking_ip_), tracking_ip_(rhs.tracking_ip_) { } VmInterface::InstanceIp::InstanceIp(const IpAddress &addr, uint8_t plen, bool ecmp, bool is_primary, bool is_service_health_check_ip, bool is_local, const IpAddress &tracking_ip) : ListEntry(), ip_(addr), plen_(plen), ecmp_(ecmp), l2_installed_(false), old_ecmp_(false), is_primary_(is_primary), is_service_health_check_ip_(is_service_health_check_ip), is_local_(is_local), tracking_ip_(tracking_ip) { } VmInterface::InstanceIp::~InstanceIp() { } bool VmInterface::InstanceIp::operator() (const InstanceIp &lhs, const InstanceIp &rhs) const { return lhs.IsLess(&rhs); } bool VmInterface::InstanceIp::IsLess(const InstanceIp *rhs) const { return ip_ < rhs->ip_; } void VmInterface::InstanceIp::L3Activate(VmInterface *interface, bool force_update) const { if (old_ecmp_ != ecmp_) { force_update = true; old_ecmp_ = ecmp_; } if (old_tracking_ip_ != tracking_ip_) { force_update = true; } // Add route if not installed or if force requested if (installed_ && force_update == false) { return; } // Add route only when vn IPAM exists if (!interface->vn()->GetIpam(ip_)) { return; } // Set prefix len for instance_ip based on Alloc-unit in VnIPAM SetPrefixForAllocUnitIpam(interface); if (ip_.is_v4()) { interface->AddRoute(interface->vrf()->GetName(), ip_.to_v4(), plen_, interface->vn()->GetName(), is_force_policy(), ecmp_, is_local_, is_service_health_check_ip_, interface->GetServiceIp(ip_), tracking_ip_, CommunityList(), interface->label()); } else if (ip_.is_v6()) { interface->AddRoute(interface->vrf()->GetName(), ip_.to_v6(), plen_, interface->vn()->GetName(), is_force_policy(), ecmp_, is_local_, is_service_health_check_ip_, interface->GetServiceIp(ip_), tracking_ip_, CommunityList(), interface->label()); } installed_ = true; } void VmInterface::InstanceIp::L3DeActivate(VmInterface *interface, VrfEntry *old_vrf) const { if (installed_ == false) { return; } if (ip_.is_v4()) { interface->DeleteRoute(old_vrf->GetName(), ip_, plen_); } else if (ip_.is_v6()) { interface->DeleteRoute(old_vrf->GetName(), ip_, plen_); } installed_ = false; } void VmInterface::InstanceIp::L2Activate(VmInterface *interface, bool force_update, uint32_t old_ethernet_tag) const { Ip4Address ipv4(0); Ip6Address ipv6; if (IsL3Only()) { return; } if (ip_.is_v4()) { // check if L3 route is already installed or not if (installed_ == false) { return; } ipv4 = ip_.to_v4(); } else { // check if L3 route is already installed or not if (installed_ == false) { return; } ipv6 = ip_.to_v6(); } if (tracking_ip_ != old_tracking_ip_) { force_update = true; } if (l2_installed_ == false || force_update) { interface->UpdateL2InterfaceRoute(false, force_update, interface->vrf(), ipv4, ipv6, old_ethernet_tag, false, false, ipv4, ipv6, interface->vm_mac(), tracking_ip_); l2_installed_ = true; } } void VmInterface::InstanceIp::L2DeActivate(VmInterface *interface, VrfEntry *old_vrf, uint32_t old_ethernet_tag) const { if (l2_installed_ == false) { return; } Ip4Address ipv4(0); Ip6Address ipv6; if (ip_.is_v4()) { ipv4 = ip_.to_v4(); } else { ipv6 = ip_.to_v6(); } interface->DeleteL2InterfaceRoute(true, old_vrf, ipv4, ipv6, old_ethernet_tag, interface->vm_mac()); l2_installed_ = false; } void VmInterface::InstanceIp::Activate(VmInterface *interface, bool force_update, bool l2, int old_ethernet_tag) const { if (l2) { L2Activate(interface, force_update, old_ethernet_tag); } else { L3Activate(interface, force_update); } } void VmInterface::InstanceIp::DeActivate(VmInterface *interface, bool l2, VrfEntry *old_vrf, uint32_t old_ethernet_tag) const { if (l2) { L2DeActivate(interface, old_vrf, old_ethernet_tag); } else { L3DeActivate(interface, old_vrf); } } void VmInterface::InstanceIp::SetPrefixForAllocUnitIpam( VmInterface *interface) const { uint32_t alloc_unit = interface->vn()->GetAllocUnitFromIpam(ip_); uint8_t alloc_prefix = 0; if (alloc_unit > 0) { alloc_prefix = log2(alloc_unit); } if (ip_.is_v4()) { plen_ = Address::kMaxV4PrefixLen - alloc_prefix; } else if (ip_.is_v6()) { plen_ = Address::kMaxV6PrefixLen - alloc_prefix; } } void VmInterface::InstanceIpList::Insert(const InstanceIp *rhs) { list_.insert(*rhs); } void VmInterface::InstanceIpList::Update(const InstanceIp *lhs, const InstanceIp *rhs) { if (lhs->ecmp_ != rhs->ecmp_) { lhs->ecmp_ = rhs->ecmp_; } lhs->is_service_health_check_ip_ = rhs->is_service_health_check_ip_; lhs->is_local_ = rhs->is_local_; lhs->old_tracking_ip_ = lhs->tracking_ip_; lhs->tracking_ip_ = rhs->tracking_ip_; lhs->set_del_pending(false); } void VmInterface::InstanceIpList::Remove(InstanceIpSet::iterator &it) { it->set_del_pending(true); } void VmInterface::FatFlowList::Insert(const FatFlowEntry *rhs) { list_.insert(*rhs); } void VmInterface::FatFlowList::Update(const FatFlowEntry *lhs, const FatFlowEntry *rhs) { } void VmInterface::FatFlowList::Remove(FatFlowEntrySet::iterator &it) { it->set_del_pending(true); } ///////////////////////////////////////////////////////////////////////////// // FloatingIp routines ///////////////////////////////////////////////////////////////////////////// VmInterface::FloatingIp::FloatingIp() : ListEntry(), floating_ip_(), vn_(NULL), vrf_(NULL, this), vrf_name_(""), vn_uuid_(), l2_installed_(false), fixed_ip_(), force_l3_update_(false), force_l2_update_(false) { } VmInterface::FloatingIp::FloatingIp(const FloatingIp &rhs) : ListEntry(rhs.installed_, rhs.del_pending_), floating_ip_(rhs.floating_ip_), vn_(rhs.vn_), vrf_(rhs.vrf_, this), vrf_name_(rhs.vrf_name_), vn_uuid_(rhs.vn_uuid_), l2_installed_(rhs.l2_installed_), fixed_ip_(rhs.fixed_ip_), force_l3_update_(rhs.force_l3_update_), force_l2_update_(rhs.force_l2_update_) { } VmInterface::FloatingIp::FloatingIp(const IpAddress &addr, const std::string &vrf, const boost::uuids::uuid &vn_uuid, const IpAddress &fixed_ip) : ListEntry(), floating_ip_(addr), vn_(NULL), vrf_(NULL, this), vrf_name_(vrf), vn_uuid_(vn_uuid), l2_installed_(false), fixed_ip_(fixed_ip), force_l3_update_(false), force_l2_update_(false){ } VmInterface::FloatingIp::~FloatingIp() { } bool VmInterface::FloatingIp::operator() (const FloatingIp &lhs, const FloatingIp &rhs) const { return lhs.IsLess(&rhs); } // Compare key for FloatingIp. Key is <floating_ip_ and vrf_name_> for both // Config and Operational processing bool VmInterface::FloatingIp::IsLess(const FloatingIp *rhs) const { if (floating_ip_ != rhs->floating_ip_) return floating_ip_ < rhs->floating_ip_; return (vrf_name_ < rhs->vrf_name_); } void VmInterface::FloatingIp::L3Activate(VmInterface *interface, bool force_update) const { // Add route if not installed or if force requested if (installed_ && force_update == false && force_l3_update_ == false) { return; } if (fixed_ip_.is_v4() && fixed_ip_ == Ip4Address(0)) { fixed_ip_ = GetFixedIp(interface); } InterfaceTable *table = static_cast<InterfaceTable *>(interface->get_table()); if (floating_ip_.is_v4()) { interface->AddRoute(vrf_.get()->GetName(), floating_ip_.to_v4(), Address::kMaxV4PrefixLen, vn_->GetName(), false, interface->ecmp(), false, false, Ip4Address(0), GetFixedIp(interface), CommunityList(), interface->label()); if (table->update_floatingip_cb().empty() == false) { table->update_floatingip_cb()(interface, vn_.get(), floating_ip_.to_v4(), false); } } else if (floating_ip_.is_v6()) { interface->AddRoute(vrf_.get()->GetName(), floating_ip_.to_v6(), Address::kMaxV6PrefixLen, vn_->GetName(), false, interface->ecmp6(), false, false, Ip6Address(), GetFixedIp(interface), CommunityList(), interface->label()); //TODO:: callback for DNS handling } installed_ = true; force_l3_update_ = false; } void VmInterface::FloatingIp::L3DeActivate(VmInterface *interface) const { if (installed_ == false) return; if (floating_ip_.is_v4()) { interface->DeleteRoute(vrf_.get()->GetName(), floating_ip_, Address::kMaxV4PrefixLen); InterfaceTable *table = static_cast<InterfaceTable *>(interface->get_table()); if (table->update_floatingip_cb().empty() == false) { table->update_floatingip_cb()(interface, vn_.get(), floating_ip_.to_v4(), true); } } else if (floating_ip_.is_v6()) { interface->DeleteRoute(vrf_.get()->GetName(), floating_ip_, Address::kMaxV6PrefixLen); //TODO:: callback for DNS handling } installed_ = false; } void VmInterface::FloatingIp::L2Activate(VmInterface *interface, bool force_update, uint32_t old_ethernet_tag) const { // Add route if not installed or if force requested if (l2_installed_ && force_update == false && force_l2_update_ == false) { return; } SecurityGroupList sg_id_list; interface->CopySgIdList(&sg_id_list); PathPreference path_preference; interface->SetPathPreference(&path_preference, false, GetFixedIp(interface)); EvpnAgentRouteTable *evpn_table = static_cast<EvpnAgentRouteTable *> (vrf_->GetEvpnRouteTable()); //Agent *agent = evpn_table->agent(); if (old_ethernet_tag != interface->ethernet_tag()) { L2DeActivate(interface, old_ethernet_tag); } evpn_table->AddReceiveRoute(interface->peer_.get(), vrf_->GetName(), interface->l2_label(), interface->vm_mac(), floating_ip_, interface->ethernet_tag(), vn_->GetName(), path_preference); l2_installed_ = true; force_l2_update_ = false; } void VmInterface::FloatingIp::L2DeActivate(VmInterface *interface, uint32_t ethernet_tag) const { if (l2_installed_ == false) return; EvpnAgentRouteTable *evpn_table = static_cast<EvpnAgentRouteTable *> (vrf_->GetEvpnRouteTable()); if (evpn_table) { evpn_table->DelLocalVmRoute(interface->peer_.get(), vrf_->GetName(), interface->vm_mac(), interface, floating_ip_, ethernet_tag); } //Reset the interface ethernet_tag l2_installed_ = false; } void VmInterface::FloatingIp::Activate(VmInterface *interface, bool force_update, bool l2, uint32_t old_ethernet_tag) const { InterfaceTable *table = static_cast<InterfaceTable *>(interface->get_table()); if (vn_.get() == NULL) { vn_ = table->FindVnRef(vn_uuid_); assert(vn_.get()); } if (vrf_.get() == NULL) { vrf_ = table->FindVrfRef(vrf_name_); assert(vrf_.get()); } if (l2) L2Activate(interface, force_update, old_ethernet_tag); else L3Activate(interface, force_update); } void VmInterface::FloatingIp::DeActivate(VmInterface *interface, bool l2, uint32_t old_ethernet_tag) const{ if (l2) L2DeActivate(interface, old_ethernet_tag); else L3DeActivate(interface); if (installed_ == false && l2_installed_ == false) vrf_ = NULL; } const IpAddress VmInterface::FloatingIp::GetFixedIp(const VmInterface *interface) const { if (fixed_ip_.is_unspecified()) { if (floating_ip_.is_v4() == true) { return interface->primary_ip_addr(); } else { return interface->primary_ip6_addr(); } } return fixed_ip_; } void VmInterface::FloatingIpList::Insert(const FloatingIp *rhs) { std::pair<FloatingIpSet::iterator, bool> ret = list_.insert(*rhs); if (ret.second) { if (rhs->floating_ip_.is_v4()) { v4_count_++; } else { v6_count_++; } } } void VmInterface::FloatingIpList::Update(const FloatingIp *lhs, const FloatingIp *rhs) { if (lhs->fixed_ip_ != rhs->fixed_ip_) { lhs->fixed_ip_ = rhs->fixed_ip_; lhs->force_l3_update_ = true; lhs->force_l2_update_ = true; } lhs->set_del_pending(false); } void VmInterface::FloatingIpList::Remove(FloatingIpSet::iterator &it) { it->set_del_pending(true); } ///////////////////////////////////////////////////////////////////////////// // AliasIp routines ///////////////////////////////////////////////////////////////////////////// VmInterface::AliasIp::AliasIp() : ListEntry(), alias_ip_(), vn_(NULL), vrf_(NULL, this), vrf_name_(""), vn_uuid_(), force_update_(false) { } VmInterface::AliasIp::AliasIp(const AliasIp &rhs) : ListEntry(rhs.installed_, rhs.del_pending_), alias_ip_(rhs.alias_ip_), vn_(rhs.vn_), vrf_(rhs.vrf_, this), vrf_name_(rhs.vrf_name_), vn_uuid_(rhs.vn_uuid_), force_update_(rhs.force_update_) { } VmInterface::AliasIp::AliasIp(const IpAddress &addr, const std::string &vrf, const boost::uuids::uuid &vn_uuid) : ListEntry(), alias_ip_(addr), vn_(NULL), vrf_(NULL, this), vrf_name_(vrf), vn_uuid_(vn_uuid), force_update_(false) { } VmInterface::AliasIp::~AliasIp() { } bool VmInterface::AliasIp::operator() (const AliasIp &lhs, const AliasIp &rhs) const { return lhs.IsLess(&rhs); } // Compare key for AliasIp. Key is <alias_ip_ and vrf_name_> for both // Config and Operational processing bool VmInterface::AliasIp::IsLess(const AliasIp *rhs) const { if (alias_ip_ != rhs->alias_ip_) return alias_ip_ < rhs->alias_ip_; return (vrf_name_ < rhs->vrf_name_); } void VmInterface::AliasIp::Activate(VmInterface *interface, bool force_update) const { InterfaceTable *table = static_cast<InterfaceTable *>(interface->get_table()); if (vn_.get() == NULL) { vn_ = table->FindVnRef(vn_uuid_); assert(vn_.get()); } if (vrf_.get() == NULL) { vrf_ = table->FindVrfRef(vrf_name_); assert(vrf_.get()); } // Add route if not installed or if force requested if (installed_ && force_update == false && force_update_ == false) { return; } if (alias_ip_.is_v4()) { interface->AddRoute(vrf_.get()->GetName(), alias_ip_.to_v4(), 32, vn_->GetName(), false, interface->ecmp(), false, false, Ip4Address(0), Ip4Address(0), CommunityList(), interface->label()); } else if (alias_ip_.is_v6()) { interface->AddRoute(vrf_.get()->GetName(), alias_ip_.to_v6(), 128, vn_->GetName(), false, interface->ecmp6(), false, false, Ip6Address(), Ip6Address(), CommunityList(), interface->label()); } installed_ = true; force_update_ = false; } void VmInterface::AliasIp::DeActivate(VmInterface *interface) const { if (installed_) { if (alias_ip_.is_v4()) { interface->DeleteRoute(vrf_.get()->GetName(), alias_ip_, 32); } else if (alias_ip_.is_v6()) { interface->DeleteRoute(vrf_.get()->GetName(), alias_ip_, 128); } installed_ = false; } vrf_ = NULL; } void VmInterface::AliasIpList::Insert(const AliasIp *rhs) { std::pair<AliasIpSet::iterator, bool> ret = list_.insert(*rhs); if (ret.second) { if (rhs->alias_ip_.is_v4()) { v4_count_++; } else { v6_count_++; } } } void VmInterface::AliasIpList::Update(const AliasIp *lhs, const AliasIp *rhs) { lhs->set_del_pending(false); } void VmInterface::AliasIpList::Remove(AliasIpSet::iterator &it) { it->set_del_pending(true); } ///////////////////////////////////////////////////////////////////////////// // StaticRoute routines ///////////////////////////////////////////////////////////////////////////// VmInterface::StaticRoute::StaticRoute() : ListEntry(), vrf_(""), addr_(), plen_(0), gw_(), communities_() { } VmInterface::StaticRoute::StaticRoute(const StaticRoute &rhs) : ListEntry(rhs.installed_, rhs.del_pending_), vrf_(rhs.vrf_), addr_(rhs.addr_), plen_(rhs.plen_), gw_(rhs.gw_), communities_(rhs.communities_) { } VmInterface::StaticRoute::StaticRoute(const std::string &vrf, const IpAddress &addr, uint32_t plen, const IpAddress &gw, const CommunityList &communities) : ListEntry(), vrf_(vrf), addr_(addr), plen_(plen), gw_(gw), communities_(communities) { } VmInterface::StaticRoute::~StaticRoute() { } bool VmInterface::StaticRoute::operator() (const StaticRoute &lhs, const StaticRoute &rhs) const { return lhs.IsLess(&rhs); } bool VmInterface::StaticRoute::IsLess(const StaticRoute *rhs) const { #if 0 //Enable once we can add static routes across vrf if (vrf_name_ != rhs->vrf_name_) return vrf_name_ < rhs->vrf_name_; #endif if (addr_ != rhs->addr_) return addr_ < rhs->addr_; if (plen_ != rhs->plen_) { return plen_ < rhs->plen_; } return gw_ < rhs->gw_; } void VmInterface::StaticRoute::Activate(VmInterface *interface, bool force_update) const { if (installed_ && force_update == false) return; if (vrf_ != interface->vrf()->GetName()) { vrf_ = interface->vrf()->GetName(); } if (installed_ == false || force_update) { Ip4Address gw_ip(0); if (gw_.is_v4() && addr_.is_v4() && gw_.to_v4() != gw_ip) { SecurityGroupList sg_id_list; interface->CopySgIdList(&sg_id_list); InetUnicastAgentRouteTable::AddGatewayRoute(interface->peer_.get(), vrf_, addr_.to_v4(), plen_, gw_.to_v4(), interface->vn_->GetName(), interface->vrf_->table_label(), sg_id_list, communities_); } else { IpAddress dependent_ip; bool ecmp = false; if (addr_.is_v4()) { dependent_ip = interface->primary_ip_addr(); ecmp = interface->ecmp(); } else if (addr_.is_v6()) { dependent_ip = interface->primary_ip6_addr(); ecmp = interface->ecmp6(); } interface->AddRoute(vrf_, addr_, plen_, interface->vn_->GetName(), false, ecmp, false, false, IpAddress(), dependent_ip, communities_, interface->label()); } } installed_ = true; } void VmInterface::StaticRoute::DeActivate(VmInterface *interface) const { if (installed_ == false) return; interface->DeleteRoute(vrf_, addr_, plen_); installed_ = false; } void VmInterface::StaticRouteList::Insert(const StaticRoute *rhs) { list_.insert(*rhs); } void VmInterface::StaticRouteList::Update(const StaticRoute *lhs, const StaticRoute *rhs) { if (lhs->communities_ != rhs->communities_) { (const_cast<StaticRoute *>(lhs))->communities_ = rhs->communities_; } lhs->set_del_pending(false); } void VmInterface::StaticRouteList::Remove(StaticRouteSet::iterator &it) { it->set_del_pending(true); } /////////////////////////////////////////////////////////////////////////////// //Allowed addresss pair route /////////////////////////////////////////////////////////////////////////////// VmInterface::AllowedAddressPair::AllowedAddressPair() : ListEntry(), vrf_(""), addr_(), plen_(0), ecmp_(false), mac_(), l2_entry_installed_(false), ecmp_config_changed_(false), ethernet_tag_(0), vrf_ref_(NULL, this), service_ip_(), label_(MplsTable::kInvalidLabel), policy_enabled_nh_(NULL), policy_disabled_nh_(NULL) { } VmInterface::AllowedAddressPair::AllowedAddressPair( const AllowedAddressPair &rhs) : ListEntry(rhs.installed_, rhs.del_pending_), vrf_(rhs.vrf_), addr_(rhs.addr_), plen_(rhs.plen_), ecmp_(rhs.ecmp_), mac_(rhs.mac_), l2_entry_installed_(rhs.l2_entry_installed_), ecmp_config_changed_(rhs.ecmp_config_changed_), ethernet_tag_(rhs.ethernet_tag_), vrf_ref_(rhs.vrf_ref_, this), service_ip_(rhs.service_ip_), label_(rhs.label_), policy_enabled_nh_(rhs.policy_enabled_nh_), policy_disabled_nh_(rhs.policy_disabled_nh_) { } VmInterface::AllowedAddressPair::AllowedAddressPair(const std::string &vrf, const IpAddress &addr, uint32_t plen, bool ecmp, const MacAddress &mac) : ListEntry(), vrf_(vrf), addr_(addr), plen_(plen), ecmp_(ecmp), mac_(mac), l2_entry_installed_(false), ecmp_config_changed_(false), ethernet_tag_(0), vrf_ref_(NULL, this), label_(MplsTable::kInvalidLabel), policy_enabled_nh_(NULL), policy_disabled_nh_(NULL) { } VmInterface::AllowedAddressPair::~AllowedAddressPair() { } bool VmInterface::AllowedAddressPair::operator() (const AllowedAddressPair &lhs, const AllowedAddressPair &rhs) const { return lhs.IsLess(&rhs); } bool VmInterface::AllowedAddressPair::IsLess(const AllowedAddressPair *rhs) const { #if 0 //Enable once we can add static routes across vrf if (vrf_name_ != rhs->vrf_name_) return vrf_name_ < rhs->vrf_name_; #endif if (addr_ != rhs->addr_) return addr_ < rhs->addr_; if (plen_ != rhs->plen_) { return plen_ < rhs->plen_; } return mac_ < rhs->mac_; } void VmInterface::AllowedAddressPair::L2Activate(VmInterface *interface, bool force_update, bool policy_change, bool old_layer2_forwarding, bool old_layer3_forwarding) const { if (mac_ == MacAddress::kZeroMac) { return; } if (l2_entry_installed_ && force_update == false && policy_change == false && ethernet_tag_ == interface->ethernet_tag() && old_layer3_forwarding == interface->layer3_forwarding() && ecmp_config_changed_ == false) { return; } if (vrf_ != interface->vrf()->GetName()) { vrf_ = interface->vrf()->GetName(); } vrf_ref_ = interface->vrf(); if (old_layer3_forwarding != interface->layer3_forwarding() || l2_entry_installed_ == false || ecmp_config_changed_) { force_update = true; } if (ethernet_tag_ != interface->ethernet_tag()) { force_update = true; } if (l2_entry_installed_ == false || force_update || policy_change) { IpAddress dependent_rt; Ip4Address v4ip(0); Ip6Address v6ip; if (addr_.is_v4()) { dependent_rt = Ip4Address(0); v4ip = addr_.to_v4(); } else if (addr_.is_v6()) { dependent_rt = Ip6Address(); v6ip = addr_.to_v6(); } if (interface->bridging()) { interface->UpdateL2InterfaceRoute(old_layer2_forwarding, force_update, interface->vrf(), v4ip, v6ip, ethernet_tag_, old_layer3_forwarding, policy_change, v4ip, v6ip, mac_, dependent_rt); } ethernet_tag_ = interface->ethernet_tag(); //If layer3 forwarding is disabled // * IP + mac allowed address pair should not be published // * Only mac allowed address pair should be published //Logic for same is present in UpdateL2InterfaceRoute if (interface->layer3_forwarding() || addr_.is_unspecified() == true) { l2_entry_installed_ = true; } else { l2_entry_installed_ = false; } ecmp_config_changed_ = false; } } void VmInterface::AllowedAddressPair::L2DeActivate(VmInterface *interface) const{ if (mac_ == MacAddress::kZeroMac) { return; } if (l2_entry_installed_ == false) { return; } Ip4Address v4ip(0); Ip6Address v6ip; if (addr_.is_v4()) { v4ip = addr_.to_v4(); } else if (addr_.is_v6()) { v6ip = addr_.to_v6(); } interface->DeleteL2InterfaceRoute(true, vrf_ref_.get(), v4ip, v6ip, ethernet_tag_, mac_); l2_entry_installed_ = false; vrf_ref_ = NULL; } void VmInterface::AllowedAddressPair::CreateLabelAndNH(Agent *agent, VmInterface *interface, bool policy_change) const { uint32_t old_label = MplsTable::kInvalidLabel; //Allocate a new L3 label with proper layer 2 //rewrite information if (label_ == MplsTable::kInvalidLabel) { label_ = agent->mpls_table()->AllocLabel(); } else if (policy_change) { old_label = label_; label_ = agent->mpls_table()->AllocLabel(); MplsLabel::Delete(interface->agent(), old_label); } InterfaceNH::CreateL3VmInterfaceNH(interface->GetUuid(), mac_, interface->vrf_->GetName()); VmInterfaceKey vmi_key(AgentKey::ADD_DEL_CHANGE, interface->GetUuid(), interface->name()); InterfaceNHKey key(vmi_key.Clone(), false, InterfaceNHFlags::INET4, mac_); InterfaceNH *nh = static_cast<InterfaceNH *>(agent->nexthop_table()-> FindActiveEntry(&key)); policy_disabled_nh_ = nh; //Ensure nexthop to be deleted upon refcount falling to 0 nh->set_delete_on_zero_refcount(true); InterfaceNHKey key1(vmi_key.Clone(), true, InterfaceNHFlags::INET4, mac_); nh = static_cast<InterfaceNH *>(agent-> nexthop_table()->FindActiveEntry(&key1)); //Ensure nexthop to be deleted upon refcount falling to 0 nh->set_delete_on_zero_refcount(true); policy_enabled_nh_ = nh; MplsLabel::CreateVPortLabel(agent, label_, interface->GetUuid(), interface->policy_enabled(), InterfaceNHFlags::INET4, mac_); } void VmInterface::AllowedAddressPair::Activate(VmInterface *interface, bool force_update, bool policy_change) const { IpAddress ip = interface->GetServiceIp(addr_); if (installed_ && force_update == false && service_ip_ == ip && policy_change == false && ecmp_config_changed_ == false) { return; } Agent *agent = interface->agent(); if (vrf_ != interface->vrf()->GetName()) { vrf_ = interface->vrf()->GetName(); } if (installed_ == false || force_update || service_ip_ != ip || policy_change || ecmp_config_changed_) { service_ip_ = ip; if (mac_ == MacAddress::kZeroMac || mac_ == interface->vm_mac_) { interface->AddRoute(vrf_, addr_, plen_, interface->vn_->GetName(), false, ecmp_, false, false, service_ip_, Ip4Address(0), CommunityList(), interface->label()); } else { CreateLabelAndNH(agent, interface, policy_change); interface->AddRoute(vrf_, addr_, plen_, interface->vn_->GetName(), false, ecmp_, false, false, service_ip_, Ip6Address(), CommunityList(), label_); } } installed_ = true; ecmp_config_changed_ = false; } void VmInterface::AllowedAddressPair::DeActivate(VmInterface *interface) const { if (installed_ == false) return; interface->DeleteRoute(vrf_, addr_, plen_); MplsLabel::Delete(interface->agent(), label_); label_ = MplsTable::kInvalidLabel; policy_enabled_nh_ = NULL; policy_disabled_nh_ = NULL; installed_ = false; } void VmInterface::AllowedAddressPairList::Insert(const AllowedAddressPair *rhs) { list_.insert(*rhs); } void VmInterface::AllowedAddressPairList::Update(const AllowedAddressPair *lhs, const AllowedAddressPair *rhs) { lhs->set_del_pending(false); if (lhs->ecmp_ != rhs->ecmp_) { lhs->ecmp_ = rhs->ecmp_; lhs->ecmp_config_changed_ = true; } } void VmInterface::AllowedAddressPairList::Remove(AllowedAddressPairSet::iterator &it) { it->set_del_pending(true); } ///////////////////////////////////////////////////////////////////////////// // SecurityGroup routines ///////////////////////////////////////////////////////////////////////////// VmInterface::SecurityGroupEntry::SecurityGroupEntry() : ListEntry(), uuid_(nil_uuid()) { } VmInterface::SecurityGroupEntry::SecurityGroupEntry (const SecurityGroupEntry &rhs) : ListEntry(rhs.installed_, rhs.del_pending_), uuid_(rhs.uuid_) { } VmInterface::SecurityGroupEntry::SecurityGroupEntry(const uuid &u) : ListEntry(), uuid_(u) { } VmInterface::SecurityGroupEntry::~SecurityGroupEntry() { } bool VmInterface::SecurityGroupEntry::operator == (const SecurityGroupEntry &rhs) const { return uuid_ == rhs.uuid_; } bool VmInterface::SecurityGroupEntry::operator() (const SecurityGroupEntry &lhs, const SecurityGroupEntry &rhs) const { return lhs.IsLess(&rhs); } bool VmInterface::SecurityGroupEntry::IsLess (const SecurityGroupEntry *rhs) const { return uuid_ < rhs->uuid_; } void VmInterface::SecurityGroupEntry::Activate(VmInterface *interface) const { if (sg_.get() != NULL) return; Agent *agent = static_cast<InterfaceTable *> (interface->get_table())->agent(); SgKey sg_key(uuid_); sg_ = static_cast<SgEntry *> (agent->sg_table()->FindActiveEntry(&sg_key)); } void VmInterface::SecurityGroupEntry::DeActivate(VmInterface *interface) const { } void VmInterface::SecurityGroupEntryList::Insert (const SecurityGroupEntry *rhs) { list_.insert(*rhs); } void VmInterface::SecurityGroupEntryList::Update (const SecurityGroupEntry *lhs, const SecurityGroupEntry *rhs) { } void VmInterface::SecurityGroupEntryList::Remove (SecurityGroupEntrySet::iterator &it) { it->set_del_pending(true); } ///////////////////////////////////////////////////////////////////////////// // ServiceVlan routines ///////////////////////////////////////////////////////////////////////////// VmInterface::ServiceVlan::ServiceVlan() : ListEntry(), tag_(0), vrf_name_(""), addr_(0), addr6_(), smac_(), dmac_(), vrf_(NULL, this), label_(MplsTable::kInvalidLabel), v4_rt_installed_(false), v6_rt_installed_(false) { } VmInterface::ServiceVlan::ServiceVlan(const ServiceVlan &rhs) : ListEntry(rhs.installed_, rhs.del_pending_), tag_(rhs.tag_), vrf_name_(rhs.vrf_name_), addr_(rhs.addr_), addr6_(rhs.addr6_), smac_(rhs.smac_), dmac_(rhs.dmac_), vrf_(rhs.vrf_, this), label_(rhs.label_), v4_rt_installed_(rhs.v4_rt_installed_), v6_rt_installed_(rhs.v6_rt_installed_) { } VmInterface::ServiceVlan::ServiceVlan(uint16_t tag, const std::string &vrf_name, const Ip4Address &addr, const Ip6Address &addr6, const MacAddress &smac, const MacAddress &dmac) : ListEntry(), tag_(tag), vrf_name_(vrf_name), addr_(addr), addr6_(addr6), smac_(smac), dmac_(dmac), vrf_(NULL, this), label_(MplsTable::kInvalidLabel) , v4_rt_installed_(false), v6_rt_installed_(false) { } VmInterface::ServiceVlan::~ServiceVlan() { } bool VmInterface::ServiceVlan::operator() (const ServiceVlan &lhs, const ServiceVlan &rhs) const { return lhs.IsLess(&rhs); } bool VmInterface::ServiceVlan::IsLess(const ServiceVlan *rhs) const { return tag_ < rhs->tag_; } void VmInterface::ServiceVlan::Activate(VmInterface *interface, bool force_update, bool old_ipv4_active, bool old_ipv6_active) const { InterfaceTable *table = static_cast<InterfaceTable *>(interface->get_table()); VrfEntry *vrf = table->FindVrfRef(vrf_name_); if (!vrf) { /* If vrf is delete marked VMI will eventually get delete of link which * will trigger ServiceVlan::DeActivate */ return; } //Change in VRF, delete and readd the entry if (vrf_.get() != vrf) { DeActivate(interface); vrf_ = vrf; } if (label_ == MplsTable::kInvalidLabel) { VlanNH::Create(interface->GetUuid(), tag_, vrf_name_, smac_, dmac_); label_ = table->agent()->mpls_table()->AllocLabel(); MplsLabel::CreateVlanNh(table->agent(), label_, interface->GetUuid(), tag_); VrfAssignTable::CreateVlan(interface->GetUuid(), vrf_name_, tag_); } if (!interface->ipv4_active() && !interface->ipv6_active() && (old_ipv4_active || old_ipv6_active)) { V4RouteDelete(interface->peer()); V6RouteDelete(interface->peer()); } if (!old_ipv4_active && !old_ipv6_active && (interface->ipv4_active() || interface->ipv6_active())) { installed_ = false; } if (installed_ && force_update == false) return; interface->ServiceVlanRouteAdd(*this, force_update); installed_ = true; } void VmInterface::ServiceVlan::V4RouteDelete(const Peer *peer) const { if (v4_rt_installed_) { InetUnicastAgentRouteTable::Delete(peer, vrf_->GetName(), addr_, Address::kMaxV4PrefixLen); v4_rt_installed_ = false; } } void VmInterface::ServiceVlan::V6RouteDelete(const Peer *peer) const { if (v6_rt_installed_) { InetUnicastAgentRouteTable::Delete(peer, vrf_->GetName(), addr6_, Address::kMaxV6PrefixLen); v6_rt_installed_ = false; } } void VmInterface::ServiceVlan::DeActivate(VmInterface *interface) const { if (label_ != MplsTable::kInvalidLabel) { VrfAssignTable::DeleteVlan(interface->GetUuid(), tag_); interface->ServiceVlanRouteDel(*this); Agent *agent = static_cast<InterfaceTable *>(interface->get_table())->agent(); MplsLabel::Delete(agent, label_); label_ = MplsTable::kInvalidLabel; VlanNH::Delete(interface->GetUuid(), tag_); vrf_ = NULL; } installed_ = false; return; } void VmInterface::ServiceVlanList::Insert(const ServiceVlan *rhs) { list_.insert(*rhs); } void VmInterface::ServiceVlanList::Update(const ServiceVlan *lhs, const ServiceVlan *rhs) { lhs->vrf_name_ = rhs->vrf_name_; lhs->set_del_pending(false); } void VmInterface::ServiceVlanList::Remove(ServiceVlanSet::iterator &it) { it->set_del_pending(true); } const MacAddress& VmInterface::GetIpMac(const IpAddress &ip, uint8_t plen) const { AllowedAddressPairSet::const_iterator it = allowed_address_pair_list_.list_.begin(); while (it != allowed_address_pair_list_.list_.end()) { if (it->addr_ == ip && it->plen_ == plen && it->mac_ != MacAddress::kZeroMac) { return it->mac_; } it++; } return vm_mac_; } uint32_t VmInterface::GetServiceVlanLabel(const VrfEntry *vrf) const { ServiceVlanSet::const_iterator it = service_vlan_list_.list_.begin(); while (it != service_vlan_list_.list_.end()) { if (it->vrf_.get() == vrf) { return it->label_; } it++; } return 0; } uint32_t VmInterface::GetServiceVlanTag(const VrfEntry *vrf) const { ServiceVlanSet::const_iterator it = service_vlan_list_.list_.begin(); while (it != service_vlan_list_.list_.end()) { if (it->vrf_.get() == vrf) { return it->tag_; } it++; } return 0; } const VrfEntry* VmInterface::GetServiceVlanVrf(uint16_t vlan_tag) const { ServiceVlanSet::const_iterator it = service_vlan_list_.list_.begin(); while (it != service_vlan_list_.list_.end()) { if (it->tag_ == vlan_tag) { return it->vrf_.get(); } it++; } return NULL; } void VmInterface::ServiceVlanRouteAdd(const ServiceVlan &entry, bool force_update) { if (vrf_.get() == NULL || vn_.get() == NULL) { return; } if (!ipv4_active_ && !ipv6_active_) { return; } SecurityGroupList sg_id_list; CopySgIdList(&sg_id_list); // With IRB model, add L2 Receive route for SMAC and DMAC to ensure // packets from service vm go thru routing BridgeAgentRouteTable *table = static_cast<BridgeAgentRouteTable *> (vrf_->GetBridgeRouteTable()); table->AddBridgeReceiveRoute(peer_.get(), entry.vrf_->GetName(), 0, entry.dmac_, vn()->GetName()); table->AddBridgeReceiveRoute(peer_.get(), entry.vrf_->GetName(), 0, entry.smac_, vn()->GetName()); VnListType vn_list; vn_list.insert(vn()->GetName()); if (force_update || (!entry.v4_rt_installed_ && !entry.addr_.is_unspecified())) { PathPreference path_preference; SetServiceVlanPathPreference(&path_preference, entry.addr_); InetUnicastAgentRouteTable::AddVlanNHRoute (peer_.get(), entry.vrf_->GetName(), entry.addr_, Address::kMaxV4PrefixLen, GetUuid(), entry.tag_, entry.label_, vn_list, sg_id_list, path_preference); entry.v4_rt_installed_ = true; } if ((!entry.v6_rt_installed_ && !entry.addr6_.is_unspecified()) || force_update) { PathPreference path_preference; SetServiceVlanPathPreference(&path_preference, entry.addr6_); InetUnicastAgentRouteTable::AddVlanNHRoute (peer_.get(), entry.vrf_->GetName(), entry.addr6_, Address::kMaxV6PrefixLen, GetUuid(), entry.tag_, entry.label_, vn_list, sg_id_list, path_preference); entry.v6_rt_installed_ = true; } entry.installed_ = true; return; } void VmInterface::ServiceVlanRouteDel(const ServiceVlan &entry) { if (entry.installed_ == false) { return; } entry.V4RouteDelete(peer_.get()); entry.V6RouteDelete(peer_.get()); // Delete the L2 Recive routes added for smac_ and dmac_ BridgeAgentRouteTable *table = static_cast<BridgeAgentRouteTable *> (entry.vrf_->GetBridgeRouteTable()); if (table) { table->Delete(peer_.get(), entry.vrf_->GetName(), entry.dmac_, 0); table->Delete(peer_.get(), entry.vrf_->GetName(), entry.smac_, 0); } entry.installed_ = false; return; } bool VmInterface::HasFloatingIp(Address::Family family) const { if (family == Address::INET) { return floating_ip_list_.v4_count_ > 0; } else { return floating_ip_list_.v6_count_ > 0; } } bool VmInterface::HasFloatingIp() const { return floating_ip_list_.list_.size() != 0; } bool VmInterface::IsFloatingIp(const IpAddress &ip) const { VmInterface::FloatingIpSet::const_iterator it = floating_ip_list_.list_.begin(); while(it != floating_ip_list_.list_.end()) { if ((*it).floating_ip_ == ip) { return true; } it++; } return false; } VrfEntry *VmInterface::GetAliasIpVrf(const IpAddress &ip) const { // Look for matching Alias IP VmInterface::AliasIpSet::const_iterator it = alias_ip_list_.list_.begin(); for (; it != alias_ip_list_.list_.end(); ++it) { if (it->vrf_.get() == NULL) { continue; } if (ip == it->alias_ip_) { return it->vrf_.get(); } } return NULL; } Ip4Address VmInterface::mdata_ip_addr() const { if (mdata_ip_.get() == NULL) { return Ip4Address(0); } return mdata_ip_->GetLinkLocalIp(); } MetaDataIp *VmInterface::GetMetaDataIp(const Ip4Address &ip) const { MetaDataIpMap::const_iterator it = metadata_ip_map_.find(ip); if (it != metadata_ip_map_.end()) { return it->second; } return NULL; } void VmInterface::InsertMetaDataIpInfo(MetaDataIp *mip) { std::pair<MetaDataIpMap::iterator, bool> ret; ret = metadata_ip_map_.insert(std::pair<Ip4Address, MetaDataIp*> (mip->GetLinkLocalIp(), mip)); assert(ret.second); } void VmInterface::DeleteMetaDataIpInfo(MetaDataIp *mip) { std::size_t ret = metadata_ip_map_.erase(mip->GetLinkLocalIp()); assert(ret != 0); } void VmInterface::UpdateMetaDataIpInfo() { MetaDataIpMap::iterator it = metadata_ip_map_.begin(); while (it != metadata_ip_map_.end()) { it->second->UpdateInterfaceCb(); it++; } } void VmInterface::InsertHealthCheckInstance(HealthCheckInstance *hc_inst) { std::pair<HealthCheckInstanceSet::iterator, bool> ret; ret = hc_instance_set_.insert(hc_inst); assert(ret.second); } void VmInterface::DeleteHealthCheckInstance(HealthCheckInstance *hc_inst) { std::size_t ret = hc_instance_set_.erase(hc_inst); assert(ret != 0); } const VmInterface::HealthCheckInstanceSet & VmInterface::hc_instance_set() const { return hc_instance_set_; } //////////////////////////////////////////////////////////////////////////// // VRF assign rule routines //////////////////////////////////////////////////////////////////////////// VmInterface::VrfAssignRule::VrfAssignRule(): ListEntry(), id_(0), vrf_name_(" "), ignore_acl_(false) { } VmInterface::VrfAssignRule::VrfAssignRule(const VrfAssignRule &rhs): ListEntry(rhs.installed_, rhs.del_pending_), id_(rhs.id_), vrf_name_(rhs.vrf_name_), ignore_acl_(rhs.ignore_acl_), match_condition_(rhs.match_condition_) { } VmInterface::VrfAssignRule::VrfAssignRule(uint32_t id, const autogen::MatchConditionType &match_condition, const std::string &vrf_name, bool ignore_acl): ListEntry(), id_(id), vrf_name_(vrf_name), ignore_acl_(ignore_acl), match_condition_(match_condition) { } VmInterface::VrfAssignRule::~VrfAssignRule() { } bool VmInterface::VrfAssignRule::operator() (const VrfAssignRule &lhs, const VrfAssignRule &rhs) const { return lhs.IsLess(&rhs); } bool VmInterface::VrfAssignRule::IsLess(const VrfAssignRule *rhs) const { return id_ < rhs->id_; } void VmInterface::VrfAssignRuleList::Insert(const VrfAssignRule *rhs) { list_.insert(*rhs); } void VmInterface::VrfAssignRuleList::Update(const VrfAssignRule *lhs, const VrfAssignRule *rhs) { lhs->set_del_pending(false); lhs->match_condition_ = rhs->match_condition_; lhs->ignore_acl_ = rhs->ignore_acl_; lhs->vrf_name_ = rhs->vrf_name_; } void VmInterface::VrfAssignRuleList::Remove(VrfAssignRuleSet::iterator &it) { it->set_del_pending(true); } const string VmInterface::GetAnalyzer() const { if (mirror_entry()) { return mirror_entry()->GetAnalyzerName(); } else { return std::string(); } } void VmInterface::SendTrace(const AgentDBTable *table, Trace event) const { InterfaceInfo intf_info; intf_info.set_name(name_); intf_info.set_index(id_); switch(event) { case ACTIVATED_IPV4: intf_info.set_op("IPV4 Activated"); break; case DEACTIVATED_IPV4: intf_info.set_op("IPV4 Deactivated"); break; case ACTIVATED_IPV6: intf_info.set_op("IPV6 Activated"); break; case DEACTIVATED_IPV6: intf_info.set_op("IPV6 Deactivated"); break; case ACTIVATED_L2: intf_info.set_op("L2 Activated"); break; case DEACTIVATED_L2: intf_info.set_op("L2 Deactivated"); break; case ADD: intf_info.set_op("Add"); break; case DELETE: intf_info.set_op("Delete"); break; case FLOATING_IP_CHANGE: { intf_info.set_op("Floating IP change"); std::vector<FloatingIPInfo> fip_list; FloatingIpSet::iterator it = floating_ip_list_.list_.begin(); while (it != floating_ip_list_.list_.end()) { const FloatingIp &ip = *it; FloatingIPInfo fip; fip.set_ip_address(ip.floating_ip_.to_string()); fip.set_vrf_name(ip.vrf_->GetName()); fip_list.push_back(fip); it++; } intf_info.set_fip(fip_list); break; } case SERVICE_CHANGE: break; } intf_info.set_ip_address(primary_ip_addr_.to_string()); if (vm_) { intf_info.set_vm(UuidToString(vm_->GetUuid())); } if (vn_) { intf_info.set_vn(vn_->GetName()); } if (vrf_) { intf_info.set_vrf(vrf_->GetName()); } intf_info.set_vm_project(UuidToString(vm_project_uuid_)); OPER_TRACE_ENTRY(Interface, table, intf_info); } ///////////////////////////////////////////////////////////////////////////// // VM Interface DB Table utility functions ///////////////////////////////////////////////////////////////////////////// // Add a VM-Interface void VmInterface::NovaAdd(InterfaceTable *table, const uuid &intf_uuid, const string &os_name, const Ip4Address &addr, const string &mac, const string &vm_name, const uuid &vm_project_uuid, uint16_t tx_vlan_id, uint16_t rx_vlan_id, const std::string &parent, const Ip6Address &ip6, Interface::Transport transport) { DBRequest req(DBRequest::DB_ENTRY_ADD_CHANGE); req.key.reset(new VmInterfaceKey(AgentKey::ADD_DEL_CHANGE, intf_uuid, os_name)); req.data.reset(new VmInterfaceNovaData(addr, ip6, mac, vm_name, nil_uuid(), vm_project_uuid, parent, tx_vlan_id, rx_vlan_id, VmInterface::VM_ON_TAP, VmInterface::INSTANCE, transport)); table->Enqueue(&req); } // Delete a VM-Interface void VmInterface::Delete(InterfaceTable *table, const uuid &intf_uuid, VmInterface::Configurer configurer) { DBRequest req(DBRequest::DB_ENTRY_DELETE); req.key.reset(new VmInterfaceKey(AgentKey::ADD_DEL_CHANGE, intf_uuid, "")); if (configurer == VmInterface::CONFIG) { req.data.reset(new VmInterfaceConfigData(NULL, NULL)); } else if (configurer == VmInterface::INSTANCE_MSG) { req.data.reset(new VmInterfaceNovaData()); } else { assert(0); } table->Enqueue(&req); } bool VmInterface::CopyIp6Address(const Ip6Address &addr) { bool ret = false; // Retain the old if new IP could not be got if (addr.is_unspecified()) { return false; } if (primary_ip6_addr_ != addr) { primary_ip6_addr_ = addr; ret = true; } return ret; } void VmInterface::UpdateIpv4InstanceIp(bool force_update, bool policy_change, bool l2, uint32_t old_ethernet_tag, VrfEntry *old_vrf) { if (l2 && old_ethernet_tag != ethernet_tag()) { force_update = true; } InstanceIpSet::iterator it = instance_ipv4_list_.list_.begin(); while (it != instance_ipv4_list_.list_.end()) { InstanceIpSet::iterator prev = it++; if (prev->del_pending_) { prev->DeActivate(this, l2, vrf(), old_ethernet_tag); if (prev->installed() == false) { instance_ipv4_list_.list_.erase(prev); } } else { if (old_vrf && (old_vrf != vrf())) { prev->DeActivate(this, l2, old_vrf, old_ethernet_tag); } prev->Activate(this, force_update||policy_change, l2, old_ethernet_tag); } } } void VmInterface::DeleteIpv4InstanceIp(bool l2, uint32_t old_ethernet_tag, VrfEntry *old_vrf_entry, bool force_update) { if (l2 && old_ethernet_tag != ethernet_tag()) { force_update = true; } InstanceIpSet::iterator it = instance_ipv4_list_.list_.begin(); while (it != instance_ipv4_list_.list_.end()) { InstanceIpSet::iterator prev = it++; if (prev->is_service_health_check_ip_) { // for service health check instance ip do not withdraw // the route till it is marked del_pending // interface itself is not active bool interface_active = false; if (l2) { interface_active = metadata_l2_active_; } else { interface_active = metadata_ip_active_; } if (!prev->del_pending_ && interface_active) { prev->Activate(this, force_update, l2, old_ethernet_tag); continue; } } prev->DeActivate(this, l2, old_vrf_entry, old_ethernet_tag); if (prev->del_pending_ && prev->installed() == false) { instance_ipv4_list_.list_.erase(prev); } } } void VmInterface::UpdateIpv6InstanceIp(bool force_update, bool policy_change, bool l2, uint32_t old_ethernet_tag) { if (l2 && old_ethernet_tag != ethernet_tag()) { force_update = true; } InstanceIpSet::iterator it = instance_ipv6_list_.list_.begin(); while (it != instance_ipv6_list_.list_.end()) { InstanceIpSet::iterator prev = it++; if (prev->del_pending_) { prev->DeActivate(this, l2, vrf(), old_ethernet_tag); if (prev->installed() == false) { instance_ipv6_list_.list_.erase(prev); } } else { prev->Activate(this, force_update||policy_change, l2, old_ethernet_tag); } } } void VmInterface::DeleteIpv6InstanceIp(bool l2, uint32_t old_ethernet_tag, VrfEntry *old_vrf_entry, bool force_update) { if (l2 && old_ethernet_tag != ethernet_tag()) { force_update = true; } InstanceIpSet::iterator it = instance_ipv6_list_.list_.begin(); while (it != instance_ipv6_list_.list_.end()) { InstanceIpSet::iterator prev = it++; if (prev->is_service_health_check_ip_) { // for service health check instance ip do not withdraw // the route till it is marked del_pending // interface itself is not active bool interface_active = false; if (l2) { interface_active = metadata_l2_active_; } else { interface_active = metadata_ip_active_; } if (!prev->del_pending_ && interface_active) { prev->Activate(this, force_update, l2, old_ethernet_tag); continue; } } prev->DeActivate(this, l2, old_vrf_entry, old_ethernet_tag); if (prev->del_pending_ && prev->installed() == false) { instance_ipv6_list_.list_.erase(prev); } } } void VmInterface::BuildIpStringList(Address::Family family, std::vector<std::string> *vect) const { InstanceIpSet list; if (family == Address::INET) { list = instance_ipv4_list_.list_; } else { list = instance_ipv6_list_.list_; } InstanceIpSet::iterator it = list.begin(); while (it != list.end()) { const VmInterface::InstanceIp &rt = *it; it++; vect->push_back(rt.ip_.to_string()); } } void AddVmiQosConfig::HandleRequest() const { QosResponse *resp = new QosResponse(); resp->set_context(context()); boost::uuids::uuid vmi_uuid = StringToUuid(std::string(get_vmi_uuid())); boost::uuids::uuid qos_config_uuid = StringToUuid(std::string(get_qos_config_uuid())); DBTable *table = Agent::GetInstance()->interface_table(); DBRequest req; req.oper = DBRequest::DB_ENTRY_ADD_CHANGE; req.key.reset(new VmInterfaceKey(AgentKey::RESYNC, vmi_uuid, "")); req.data.reset(new InterfaceQosConfigData(NULL, NULL, qos_config_uuid)); table->Enqueue(&req); resp->set_resp("Success"); resp->Response(); }
35.664804
93
0.586875
chnyda
d5374e6a7e7681a1ecae767a26ce3e6de4b28794
4,104
hpp
C++
src/common/reorder_pd.hpp
BAEsquivel/mkl-dnn
a090094a8ab90e7bebd2c7227177d737529c9bd5
[ "Apache-2.0" ]
1
2020-02-21T07:00:06.000Z
2020-02-21T07:00:06.000Z
src/common/reorder_pd.hpp
BAEsquivel/mkl-dnn
a090094a8ab90e7bebd2c7227177d737529c9bd5
[ "Apache-2.0" ]
null
null
null
src/common/reorder_pd.hpp
BAEsquivel/mkl-dnn
a090094a8ab90e7bebd2c7227177d737529c9bd5
[ "Apache-2.0" ]
null
null
null
/******************************************************************************* * Copyright 2016-2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #ifndef REORDER_PD_HPP #define REORDER_PD_HPP #include <assert.h> #include "c_types_map.hpp" #include "engine.hpp" #include "primitive_attr.hpp" #include "primitive_desc.hpp" #include "type_helpers.hpp" #include "utils.hpp" namespace dnnl { namespace impl { struct reorder_pd_t : public primitive_desc_t { reorder_pd_t(engine_t *engine, const primitive_attr_t *attr, engine_t *src_engine, const memory_desc_t *src_md, engine_t *dst_engine, const memory_desc_t *dst_md) : primitive_desc_t(engine, attr, primitive_kind::reorder) , src_engine_(src_engine) , dst_engine_(dst_engine) , scratchpad_engine_(nullptr) , src_md_(*src_md) , dst_md_(*dst_md) { // Fill a desc that is intended for internal use only desc_ = reorder_desc_t(); desc_.primitive_kind = primitive_kind::reorder; desc_.src_md = src_md_; desc_.dst_md = dst_md_; desc_.src_engine_kind = src_engine_->kind(); desc_.dst_engine_kind = dst_engine_->kind(); } const reorder_desc_t *desc() const { return &desc_; } virtual const op_desc_t *op_desc() const override { return reinterpret_cast<const op_desc_t *>(this->desc()); } virtual arg_usage_t arg_usage(int arg) const override { if (arg == DNNL_ARG_FROM) return arg_usage_t::input; if (arg == DNNL_ARG_TO) return arg_usage_t::output; return primitive_desc_t::arg_usage(arg); } virtual const memory_desc_t *arg_md(int arg) const override { switch (arg) { case DNNL_ARG_FROM: return src_md(0); case DNNL_ARG_TO: return dst_md(0); default: return primitive_desc_t::arg_md(arg); } } virtual const memory_desc_t *src_md(int index = 0) const override { return index == 0 ? &src_md_ : &glob_zero_md; } virtual const memory_desc_t *dst_md(int index = 0) const override { return index == 0 ? &dst_md_ : &glob_zero_md; } virtual int n_inputs() const override { return 1; } virtual int n_outputs() const override { return 1; } float alpha() const { return attr()->output_scales_.scales_[0]; } float beta() const { const int sum_idx = attr()->post_ops_.find(primitive_kind::sum); return sum_idx == -1 ? 0 : attr()->post_ops_.entry_[sum_idx].sum.scale; } engine_t *src_engine() const { return src_engine_; } engine_t *dst_engine() const { return dst_engine_; } virtual dnnl::impl::engine_t *scratchpad_engine() const override { return scratchpad_engine_; } virtual status_t query(query_t what, int idx, void *result) const override { switch (what) { case query::reorder_src_engine: *(engine_t **)result = src_engine(); break; case query::reorder_dst_engine: *(engine_t **)result = dst_engine(); break; default: return primitive_desc_t::query(what, idx, result); } return status::success; } protected: reorder_desc_t desc_; engine_t *src_engine_; engine_t *dst_engine_; engine_t *scratchpad_engine_; memory_desc_t src_md_; memory_desc_t dst_md_; }; } // namespace impl } // namespace dnnl #endif // vim: et ts=4 sw=4 cindent cino+=l0,\:4,N-s
32.832
80
0.635721
BAEsquivel
d539a7c8ee0c1437f18e4ca8c4809c3014ab9aa2
9,512
hpp
C++
src/OpenLoco/Interop/Interop.hpp
aw20368/OpenLoco
ce37179813b0036b38061c604581e70f8d41873f
[ "MIT" ]
null
null
null
src/OpenLoco/Interop/Interop.hpp
aw20368/OpenLoco
ce37179813b0036b38061c604581e70f8d41873f
[ "MIT" ]
null
null
null
src/OpenLoco/Interop/Interop.hpp
aw20368/OpenLoco
ce37179813b0036b38061c604581e70f8d41873f
[ "MIT" ]
null
null
null
#pragma once #include "../Utility/String.hpp" #include <cstddef> #include <cstdint> #include <cstdio> #include <stdexcept> #include <vector> #define assert_struct_size(x, y) static_assert(sizeof(x) == (y), "Improper struct size") #if defined(__clang__) #define FORCE_ALIGN_ARG_POINTER __attribute__((force_align_arg_pointer)) #else #define FORCE_ALIGN_ARG_POINTER #endif constexpr int32_t DEFAULT_REG_VAL = 0xCCCCCCCC; namespace OpenLoco::Interop { #pragma pack(push, 1) /** * x86 register structure, only used for easy interop to Locomotion code. */ struct registers { union { int32_t eax{ DEFAULT_REG_VAL }; int16_t ax; struct { int8_t al; int8_t ah; }; }; union { int32_t ebx{ DEFAULT_REG_VAL }; int16_t bx; struct { int8_t bl; int8_t bh; }; }; union { int32_t ecx{ DEFAULT_REG_VAL }; int16_t cx; struct { int8_t cl; int8_t ch; }; }; union { int32_t edx{ DEFAULT_REG_VAL }; int16_t dx; struct { int8_t dl; int8_t dh; }; }; union { int32_t esi{ DEFAULT_REG_VAL }; int16_t si; }; union { int32_t edi{ DEFAULT_REG_VAL }; int16_t di; }; union { int32_t ebp{ DEFAULT_REG_VAL }; int16_t bp; }; }; assert_struct_size(registers, 7 * 4); #pragma pack(pop) #ifndef USE_MMAP constexpr uintptr_t GOOD_PLACE_FOR_DATA_SEGMENT = 0x008A4000; #else #if defined(PLATFORM_32BIT) constexpr uintptr_t GOOD_PLACE_FOR_DATA_SEGMENT = 0x09000000; #elif defined(PLATFORM_64BIT) constexpr uintptr_t GOOD_PLACE_FOR_DATA_SEGMENT = 0x200000000; #else #error "Unknown platform" #endif #endif constexpr uintptr_t remapAddress(uintptr_t locoAddress) { return GOOD_PLACE_FOR_DATA_SEGMENT - 0x008A4000 + locoAddress; } template<uint32_t TAddress, typename T> constexpr T& addr() { return *((T*)remapAddress(TAddress)); } /** * Returns the flags register * * Flags register is as follows: * 0bSZ0A_0P0C_0000_0000 * S = Signed flag * Z = Zero flag * C = Carry flag * A = Adjust flag * P = Parity flag * All other bits are undefined. */ int32_t call(int32_t address); int32_t call(int32_t address, registers& registers); template<typename T, uintptr_t TAddress> struct loco_global { public: typedef T type; typedef type* pointer; typedef type& reference; typedef const type& const_reference; private: pointer _Myptr; public: loco_global() { _Myptr = &(addr<TAddress, T>()); } operator reference() { return addr<TAddress, T>(); } loco_global& operator=(const_reference v) { addr<TAddress, T>() = v; return *this; } loco_global& operator+=(const_reference v) { addr<TAddress, T>() += v; return *this; } loco_global& operator|=(const_reference v) { addr<TAddress, T>() |= v; return *this; } loco_global& operator&=(const_reference v) { addr<TAddress, T>() &= v; return *this; } loco_global& operator^=(const_reference v) { addr<TAddress, T>() ^= v; return *this; } loco_global& operator-=(const_reference v) { addr<TAddress, T>() -= v; return *this; } loco_global& operator++() { addr<TAddress, T>()++; return *this; } T operator++(int) { reference ref = addr<TAddress, T>(); T temp = ref; ref++; return temp; } loco_global& operator--() { addr<TAddress, T>()--; return *this; } T operator--(int) { reference ref = addr<TAddress, T>(); T temp = ref; ref--; return temp; } reference operator*() { return addr<TAddress, T>(); } pointer operator->() { return &(addr<TAddress, T>()); } constexpr size_t size() const { return sizeof(T); } }; template<typename T> struct loco_global_iterator { private: T* _ptr; public: loco_global_iterator(T* p) : _ptr(p) { } loco_global_iterator& operator++() { ++_ptr; return *this; } loco_global_iterator operator++(int) { auto temp = *this; ++_ptr; return temp; } loco_global_iterator& operator--() { --_ptr; return *this; } loco_global_iterator operator--(int) { auto temp = *this; --_ptr; return temp; } bool operator==(const loco_global_iterator& rhs) { return _ptr == rhs._ptr; } bool operator!=(const loco_global_iterator& rhs) { return _ptr != rhs._ptr; } T& operator*() { return *_ptr; } }; template<typename T, size_t TCount, uintptr_t TAddress> struct loco_global<T[TCount], TAddress> { public: typedef T type; typedef type* pointer; typedef type& reference; typedef const type& const_reference; typedef loco_global_iterator<T> iterator; private: pointer _Myfirst; pointer _Mylast; public: loco_global() { _Myfirst = get(); _Mylast = _Myfirst + TCount; } operator pointer() { return get(); } pointer get() const { return reinterpret_cast<pointer>(&addr<TAddress, type>()); } reference operator[](int idx) { #ifndef NDEBUG if (idx < 0 || static_cast<size_t>(idx) >= size()) { throw std::out_of_range("loco_global: bounds check violation!"); } #endif return get()[idx]; } constexpr size_t size() const { return TCount; } iterator begin() const { return iterator(&addr<TAddress, T>()); } iterator end() const { const pointer ptrEnd = (&addr<TAddress, T>()) + TCount; return iterator(ptrEnd); } }; enum { X86_FLAG_CARRY = 1 << 0, X86_FLAG_PARITY = 1 << 2, X86_FLAG_ADJUST = 1 << 4, X86_FLAG_ZERO = 1 << 6, X86_FLAG_SIGN = 1 << 7, }; class save_state { private: uintptr_t begin = 0; uintptr_t end = 0; std::vector<std::byte> state; public: const std::vector<std::byte>& getState() const { return state; } save_state(uintptr_t begin, uintptr_t end); void reset(); static void logDiff(const save_state& lhs, const save_state& rhs); }; bool operator==(const save_state& lhs, const save_state& rhs); bool operator!=(const save_state& lhs, const save_state& rhs); void readMemory(uint32_t address, void* data, size_t size); void writeMemory(uint32_t address, const void* data, size_t size); using hook_function = uint8_t (*)(registers& regs); void registerHook(uintptr_t address, hook_function function); void writeRet(uint32_t address); void writeJmp(uint32_t address, void* fn); void writeNop(uint32_t address, size_t count); void hookDump(uint32_t address, void* fn); void hookLib(uint32_t address, void* fn); void registerHooks(); void loadSections(); } // these safe string function convenience overloads are located in this header, rather than in Utility/String.hpp, // so that Utility/String.hpp doesn't needlessly have to include this header just for the definition of loco_global // (and so that we don't have to use type traits SFINAE template wizardry to get around not having the definition available) namespace OpenLoco::Utility { template<size_t TCount, uintptr_t TAddress> void strcpy_safe(OpenLoco::Interop::loco_global<char[TCount], TAddress>& dest, const char* src) { (void)strlcpy(dest, src, dest.size()); } template<size_t TCount, uintptr_t TAddress> void strcat_safe(OpenLoco::Interop::loco_global<char[TCount], TAddress>& dest, const char* src) { (void)strlcat(dest, src, dest.size()); } template<size_t TCount, uintptr_t TAddress, typename... Args> int sprintf_safe(OpenLoco::Interop::loco_global<char[TCount], TAddress>& dest, const char* fmt, Args&&... args) { return std::snprintf(dest, TCount, fmt, std::forward<Args>(args)...); } }
23.544554
124
0.527754
aw20368
d53cd281f8899da06b1fa256f27b36cd7e13851b
38,185
cpp
C++
eqgame_dll/MQ2Windows.cpp
Natedog2012/dll
5fb9414a5ebddf9c37809517eaf378a26b422d61
[ "MIT" ]
3
2021-06-25T00:03:25.000Z
2021-11-30T19:45:27.000Z
eqgame_dll/MQ2Windows.cpp
Natedog2012/dll
5fb9414a5ebddf9c37809517eaf378a26b422d61
[ "MIT" ]
null
null
null
eqgame_dll/MQ2Windows.cpp
Natedog2012/dll
5fb9414a5ebddf9c37809517eaf378a26b422d61
[ "MIT" ]
3
2021-09-21T23:33:31.000Z
2022-02-18T08:13:20.000Z
/***************************************************************************** MQ2Main.dll: MacroQuest2's extension DLL for EverQuest Copyright (C) 2002-2003 Plazmic, 2003-2005 Lax This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation. 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. ******************************************************************************/ #if !defined(CINTERFACE) //#error /DCINTERFACE #endif #define DBG_SPEW //#define DEBUG_TRY #include "MQ2Main.h" #include <map> #include <string> #include <algorithm> using namespace std; map<string,unsigned long> WindowMap; PCHAR szClickNotification[] = { "leftmouse", //0 "leftmouseup", //1 "leftmouseheld", //2 "leftmouseheldup", //3 "rightmouse", //4 "rightmouseup", //5 "rightmouseheld", //6 "rightmouseheldup", //7 }; struct _WindowInfo { char Name[128]; CXWnd *pWnd; CXWnd **ppWnd; }; CIndex <_WindowInfo*> WindowList(10); bool GenerateMQUI(); void DestroyMQUI(); #if 0 class SetScreenHook { public: void SetScreen_Detour(CXStr *pName) { CHAR Name[MAX_STRING]={0}; GetCXStr(pName->Ptr,Name,MAX_STRING); string WindowName=Name; MakeLower((WindowName)); unsigned long N=WindowMap[WindowName]; if (N) { N--; _WindowInfo *pWnd = WindowList[N]; pWnd->pWnd=(CXWnd*)this; pWnd->ppWnd=0; //DebugSpew("Updating WndNotification target '%s'",Name); } else { _WindowInfo *pWnd = new _WindowInfo; strcpy(pWnd->Name,Name); pWnd->pWnd=(CXWnd*)this; pWnd->ppWnd=0; N=WindowList.GetUnused(); WindowList[N]=pWnd; WindowMap[WindowName]=N+1; //DebugSpew("Adding WndNotification target '%s'",Name); } SetScreen_Trampoline(pName); } void SetScreen_Trampoline(CXStr*); }; DETOUR_TRAMPOLINE_EMPTY(void SetScreenHook::SetScreen_Trampoline(CXStr*)); #endif class CSidlInitHook { public: void Init_Trampoline(class CXStr*pName,int A); void Init_Detour(class CXStr*pName,int A) { CHAR Name[MAX_STRING]={0}; GetCXStr(pName->Ptr,Name,MAX_STRING); string WindowName=Name; MakeLower((WindowName)); unsigned long N=WindowMap[WindowName]; if (N) { N--; _WindowInfo *pWnd = WindowList[N]; pWnd->pWnd=(CXWnd*)this; pWnd->ppWnd=0; DebugSpew("Updating WndNotification target '%s'",Name); } else { _WindowInfo *pWnd = new _WindowInfo; strcpy(pWnd->Name,Name); pWnd->pWnd=(CXWnd*)this; pWnd->ppWnd=0; N=WindowList.GetUnused(); WindowList[N]=pWnd; WindowMap[WindowName]=N+1; DebugSpew("Adding WndNotification target '%s'",Name); } Init_Trampoline(pName, A); } }; DETOUR_TRAMPOLINE_EMPTY(void CSidlInitHook::Init_Trampoline(class CXStr*,int)); class CXWndManagerHook { public: int RemoveWnd_Detour(class CXWnd *pWnd) { if (pWnd) { for (unsigned long N = 0 ; N < WindowList.Size ; N++) if (_WindowInfo* pInfo=WindowList[N]) { if (pWnd==pInfo->pWnd) { //DebugSpew("Removing WndNotification target '%s'",pInfo->Name); string Name=pInfo->Name; MakeLower(Name); WindowMap[Name]=0; delete pInfo; WindowList[N]=0; break; } } } return RemoveWnd_Trampoline(pWnd); } int RemoveWnd_Trampoline(class CXWnd *); }; DETOUR_TRAMPOLINE_EMPTY(int CXWndManagerHook::RemoveWnd_Trampoline(class CXWnd *)); class CXMLSOMDocumentBaseHook { public: int XMLRead(CXStr *A, CXStr *B, CXStr *C, CXStr *D) { char Temp[256]={0}; GetCXStr(C->Ptr,Temp,256); DebugSpew("XMLRead(%s)",Temp); if (!stricmp("EQUI.xml",Temp)) { if (GenerateMQUI()) { SetCXStr(&C->Ptr,"MQUI.xml"); int Ret=XMLRead_Trampoline(A,B,C,D); DestroyMQUI(); return Ret; } } return XMLRead_Trampoline(A,B,C,D); } int XMLRead_Trampoline(CXStr *A, CXStr *B, CXStr *C, CXStr *D); }; DETOUR_TRAMPOLINE_EMPTY(int CXMLSOMDocumentBaseHook::XMLRead_Trampoline(CXStr *A, CXStr *B, CXStr *C, CXStr *D)); #ifndef ISXEQ VOID ListWindows(PSPAWNINFO pChar, PCHAR szLine); VOID WndNotify(PSPAWNINFO pChar, PCHAR szLine); VOID ItemNotify(PSPAWNINFO pChar, PCHAR szLine); VOID ListItemSlots(PSPAWNINFO pChar, PCHAR szLine); #else int ListWindows(int argc, char *argv[]); int WndNotify(int argc, char *argv[]); int ItemNotify(int argc, char *argv[]); int ListItemSlots(int argc, char *argv[]); #endif #ifndef ISXEQ_LEGACY void InitializeMQ2Windows() { int i; DebugSpew("Initializing MQ2 Windows"); extern PCHAR szItemSlot[]; for(i=0;i<NUM_INV_SLOTS;i++) ItemSlotMap[szItemSlot[i]]=i; CHAR szOut[MAX_STRING]={0}; #define AddSlotArray(name,count,start) \ for (i = 0 ; i < count ; i++)\ {\ sprintf(szOut,#name"%d",i+1);\ ItemSlotMap[szOut]=start+i;\ } AddSlotArray(bank,24,2000); AddSlotArray(sharedbank,2,2500); AddSlotArray(trade,16,3000); AddSlotArray(world,10,4000); AddSlotArray(enviro,10,4000); AddSlotArray(loot,31,5000); AddSlotArray(merchant,80,6000); AddSlotArray(bazaar,80,7000); AddSlotArray(inspect,31,8000); #undef AddSlotArray EzDetour(CXMLSOMDocumentBase__XMLRead,&CXMLSOMDocumentBaseHook::XMLRead,&CXMLSOMDocumentBaseHook::XMLRead_Trampoline); EzDetour(CSidlScreenWnd__Init1,&CSidlInitHook::Init_Detour,&CSidlInitHook::Init_Trampoline); EzDetour(CXWndManager__RemoveWnd,&CXWndManagerHook::RemoveWnd_Detour,&CXWndManagerHook::RemoveWnd_Trampoline); #ifndef ISXEQ AddCommand("/windows",ListWindows,false,true,false); AddCommand("/notify",WndNotify,false,true,false); AddCommand("/itemnotify",ItemNotify,false,true,false); AddCommand("/itemslots",ListItemSlots,false,true,false); #else pISInterface->AddCommand("EQWindows",ListWindows); pISInterface->AddCommand("EQNotify",WndNotify); pISInterface->AddCommand("EQItemNotify",ItemNotify); pISInterface->AddCommand("EQItemSlots",ListItemSlots); #endif if (pWndMgr) { CHAR Name[MAX_STRING]={0}; PCSIDLWND *ppWnd=((_CXWNDMGR*)pWndMgr)->pWindows; PCSIDLWND pWnd=*ppWnd; DWORD count = ((_CXWNDMGR*)pWndMgr)->Count; while(pWnd = *ppWnd) { if(count-- == 0) break; // process window if (CXMLData *pXMLData=((CXWnd*)pWnd)->GetXMLData()) { if (pXMLData->Type==UI_Screen) { GetCXStr(pXMLData->Name.Ptr,Name,MAX_STRING); string WindowName=Name; MakeLower((WindowName)); unsigned long N=WindowMap[WindowName]; if (N) { N--; _WindowInfo *pNewWnd = WindowList[N]; pNewWnd->pWnd=(CXWnd*)pWnd; pNewWnd->ppWnd=0; //DebugSpew("Updating WndNotification target '%s'",Name); } else { _WindowInfo *pNewWnd = new _WindowInfo; strcpy(pNewWnd->Name,Name); pNewWnd->pWnd=(CXWnd*)pWnd; pNewWnd->ppWnd=0; N=WindowList.GetUnused(); WindowList[N]=pNewWnd; WindowMap[WindowName]=N+1; //DebugSpew("Adding WndNotification target '%s'",Name); } } } ppWnd++; } } } void ShutdownMQ2Windows() { DebugSpew("Shutting down MQ2 Windows"); #ifndef ISXEQ RemoveCommand("/windows"); RemoveCommand("/notify"); RemoveCommand("/itemnotify"); RemoveCommand("/itemslots"); #else pISInterface->RemoveCommand("EQWindows"); pISInterface->RemoveCommand("EQNotify"); pISInterface->RemoveCommand("EQItemNotify"); pISInterface->RemoveCommand("EQItemSlots"); #endif RemoveDetour(CXMLSOMDocumentBase__XMLRead); RemoveDetour(CSidlScreenWnd__Init1); RemoveDetour(CXWndManager__RemoveWnd); WindowList.Cleanup(); } bool GenerateMQUI() { // create EverQuest\uifiles\default\MQUI.xml PCHARINFO pCharInfo = NULL; CHAR szFilename[MAX_PATH] = { 0 }; CHAR szOrgFilename[MAX_PATH] = { 0 }; CHAR UISkin[MAX_STRING] = { 0 }; char Buffer[2048]; FILE *forg, *fnew; if (!pXMLFiles) { DebugSpew ("GenerateMQUI::Not Generating MQUI.xml, no files in our list"); return false; } sprintf(UISkin, "default"); sprintf(szOrgFilename, "%s\\uifiles\\%s\\EQUI.xml", gszEQPath, UISkin); sprintf(szFilename, "%s\\uifiles\\%s\\MQUI.xml", gszEQPath, UISkin); DebugSpew("GenerateMQUI::Generating %s", szFilename); forg = fopen(szOrgFilename, "rt"); if (!forg) { DebugSpew("GenerateMQUI::could not open %s", szOrgFilename); return false; } fnew = fopen(szFilename, "wt"); if (!fnew) { DebugSpew("GenerateMQUI::could not open %s", szFilename); fclose(forg); return false; } while (fgets(Buffer, 2048, forg)) { if (strstr(Buffer, "</Composite>")) { DebugSpew("GenerateMQUI::Inserting our xml files"); PMQXMLFILE pFile = pXMLFiles; while (pFile) { DebugSpew("GenerateMQUI::Inserting %s",pFile->szFilename); fprintf(fnew, "<Include>%s</Include>\n", pFile->szFilename); pFile = pFile->pNext; } } fprintf(fnew, "%s", Buffer); } fclose(fnew); fclose(forg); if ((pCharInfo = GetCharInfo()) != NULL) { sprintf(szFilename, "%s\\UI_%s_%s.ini", gszEQPath, pCharInfo->Name, EQADDR_SERVERNAME); GetPrivateProfileString("Main", "UISkin", "default", UISkin, MAX_STRING, szFilename); if (strcmp(UISkin, "default")) { sprintf(szOrgFilename, "%s\\uifiles\\%s\\EQUI.xml", gszEQPath, UISkin); sprintf(szFilename, "%s\\uifiles\\%s\\MQUI.xml", gszEQPath, UISkin); DebugSpew("GenerateMQUI::Generating %s", szFilename); forg = fopen(szOrgFilename, "rt"); if (!forg) { DebugSpew("GenerateMQUI::could not open %s (non-fatal)", szOrgFilename); sprintf(szOrgFilename, "%s\\uifiles\\%s\\EQUI.xml", gszEQPath, "default"); forg = fopen(szOrgFilename, "rt"); if (!forg) { DebugSpew("GenerateMQUI::could not open %s", szOrgFilename); DebugSpew("GenerateMQUI::giving up"); return false; } } fnew = fopen(szFilename, "wt"); if (!fnew) { DebugSpew("GenerateMQUI::could not open %s", szFilename); fclose(forg); return false; } while (fgets(Buffer, 2048, forg)) { if (strstr(Buffer, "</Composite>")) { //DebugSpew("GenerateMQUI::Inserting our xml files"); PMQXMLFILE pFile = pXMLFiles; while (pFile) { //DebugSpew("GenerateMQUI::Inserting %s",pFile->szFilename); fprintf(fnew, "<Include>%s</Include>\n", pFile->szFilename); pFile = pFile->pNext; } } fprintf(fnew, "%s", Buffer); } fclose(fnew); fclose(forg); } } return true; } void DestroyMQUI() { // delete MQUI.xml files. PCHARINFO pCharInfo = NULL; CHAR szFilename[MAX_PATH] = { 0 }; CHAR UISkin[MAX_STRING] = { 0 }; sprintf(szFilename, "%s\\uifiles\\%s\\MQUI.xml", gszEQPath, "default"); DebugSpew("DestroyMQUI: removing file %s", szFilename); remove(szFilename); if ((pCharInfo = GetCharInfo()) != NULL) { sprintf(szFilename, "%s\\UI_%s_%s.ini", gszEQPath, pCharInfo->Name, EQADDR_SERVERNAME); //DebugSpew("UI File: %s", szFilename); GetPrivateProfileString("Main", "UISkin", "default", UISkin, MAX_STRING, szFilename); //DebugSpew("UISkin=%s", UISkin); sprintf(szFilename, "%s\\uifiles\\%s\\MQUI.xml", gszEQPath, UISkin); DebugSpew("DestroyMQUI: removing file %s", szFilename); remove(szFilename); } } void AddXMLFile(const char *filename) { PMQXMLFILE pFile = pXMLFiles; PMQXMLFILE pLast = 0; while (pFile) { if (!stricmp(pFile->szFilename, filename)) return; // already there. pLast = pFile; pFile = pFile->pNext; } CHAR szBuffer[MAX_PATH] = { 0 }; PCHARINFO pCharInfo = NULL; CHAR szFilename[MAX_PATH] = { 0 }; CHAR UISkin[MAX_STRING] = { 0 }; sprintf(UISkin, "default"); if ((pCharInfo = GetCharInfo()) != NULL) { sprintf(szFilename, "%s\\UI_%s_%s.ini", gszEQPath, pCharInfo->Name, EQADDR_SERVERNAME); GetPrivateProfileString("Main", "UISkin", "default", UISkin, MAX_STRING, szFilename); } sprintf(szBuffer, "%s\\uifiles\\%s\\%s", gszEQPath, UISkin, filename); if (!_FileExists(szBuffer)) { sprintf(szBuffer, "%s\\uifiles\\%s\\%s", gszEQPath, "default", filename); if (!_FileExists(szBuffer)) { WriteChatf ("UI file %s not found in either uifiles\\%s or uifiles\\default. Please copy it there, reload the UI, and reload this plugin.", filename, UISkin); return; } } DebugSpew("Adding XML File %s", filename); if (gGameState == GAMESTATE_INGAME) { WriteChatf ("UI file %s added, you must reload your UI for this to take effect.", filename); } pFile = new MQXMLFILE; pFile->pLast = pLast; if (pLast) pLast->pNext = pFile; else pXMLFiles = pFile; pFile->pNext = 0; strcpy(pFile->szFilename, filename); } void RemoveXMLFile(const char *filename) { PMQXMLFILE pFile = pXMLFiles; while (pFile) { if (!stricmp(pFile->szFilename, filename)) { DebugSpew("Removing XML File %s", filename); if (pFile->pLast) pFile->pLast->pNext = pFile->pNext; else pXMLFiles = pFile->pNext; if (pFile->pNext) pFile->pNext->pLast = pFile->pLast; delete pFile; return; } pFile = pFile->pNext; } } CXWnd *FindMQ2Window(PCHAR WindowName) { _WindowInfo *pInfo = NULL; string Name=WindowName; MakeLower(Name); unsigned long N = WindowMap[Name]; if (!N) { PCONTENTS pPack=0; if (!strnicmp(WindowName,"bank",4)) { unsigned long nPack=atoi(&WindowName[4]); if (nPack && nPack<=NUM_BANK_SLOTS) { pPack=((PCHARINFO)pCharData)->pBankArray->Bank[nPack-1]; } } else if (!strnicmp(WindowName,"pack",4)) { unsigned long nPack=atoi(&WindowName[4]); if (nPack && nPack<=10) { pPack=GetCharInfo2()->pInventoryArray->Inventory.Pack[nPack-1]; } } else if (!stricmp(WindowName,"enviro")) { pPack=((PEQ_CONTAINERWND_MANAGER)pContainerMgr)->pWorldContents; } if (!pPack) { return 0; } return (CXWnd*)FindContainerForContents(pPack); } N--; pInfo=WindowList[N]; if (!pInfo) { WindowMap[Name]=0; return 0; } if (pInfo->pWnd) { return pInfo->pWnd; } else { if (pInfo->ppWnd) { return *pInfo->ppWnd; } else { WindowMap[Name]=0; delete pInfo; WindowList[N]=0; WindowMap[Name]=0; return 0; } } return 0; } bool SendWndClick2(CXWnd *pWnd, PCHAR ClickNotification) { if (!pWnd) return false; for (unsigned long i = 0 ; i < 8 ; i++) { if (!stricmp(szClickNotification[i],ClickNotification)) { DebugTry(CXRect rect= pWnd->GetScreenRect()); DebugTry(CXPoint pt=rect.CenterPoint()); switch(i) { case 0: DebugTry(pWnd->HandleLButtonDown(&pt,0)); break; case 1: DebugTry(pWnd->HandleLButtonDown(&pt,0)); DebugTry(pWnd->HandleLButtonUp(&pt,0)); break; case 2: DebugTry(pWnd->HandleLButtonDown(&pt,0)); DebugTry(pWnd->HandleLButtonHeld(&pt,0)); break; case 3: DebugTry(pWnd->HandleLButtonDown(&pt,0)); DebugTry(pWnd->HandleLButtonHeld(&pt,0)); DebugTry(pWnd->HandleLButtonUpAfterHeld(&pt,0)); break; case 4: DebugTry(pWnd->HandleRButtonDown(&pt,0)); break; case 5: DebugTry(pWnd->HandleRButtonDown(&pt,0)); DebugTry(pWnd->HandleRButtonUp(&pt,0)); break; case 6: DebugTry(pWnd->HandleRButtonDown(&pt,0)); DebugTry(pWnd->HandleRButtonHeld(&pt,0)); break; case 7: DebugTry(pWnd->HandleRButtonDown(&pt,0)); DebugTry(pWnd->HandleRButtonHeld(&pt,0)); DebugTry(pWnd->HandleRButtonUpAfterHeld(&pt,0)); break; default: return false; }; gMouseEventTime = GetFastTime(); return true; } } return false; } #define MacroError printf bool SendWndClick(PCHAR WindowName, PCHAR ScreenID, PCHAR ClickNotification) { CXWnd *pWnd=FindMQ2Window(WindowName); if (!pWnd) { MacroError("Window '%s' not available.",WindowName); return false; } if (ScreenID && ScreenID[0] && ScreenID[0]!='0') { CXWnd *pButton=((CSidlScreenWnd*)(pWnd))->GetChildItem(ScreenID); if (!pButton) { MacroError("Window '%s' child '%s' not found.",WindowName,ScreenID); return false; } pWnd=pButton; } for (unsigned long i = 0 ; i < 8 ; i++) { if (!stricmp(szClickNotification[i],ClickNotification)) { CXRect rect= pWnd->GetScreenRect(); CXPoint pt=rect.CenterPoint(); switch(i) { case 0: pWnd->HandleLButtonDown(&pt,0); break; case 1: pWnd->HandleLButtonDown(&pt,0); pWnd->HandleLButtonUp(&pt,0); break; case 2: pWnd->HandleLButtonHeld(&pt,0); break; case 3: pWnd->HandleLButtonDown(&pt,0); pWnd->HandleLButtonHeld(&pt,0); pWnd->HandleLButtonUpAfterHeld(&pt,0); break; case 4: pWnd->HandleRButtonDown(&pt,0); break; case 5: pWnd->HandleRButtonDown(&pt,0); pWnd->HandleRButtonUp(&pt,0); break; case 6: pWnd->HandleRButtonDown(&pt,0); pWnd->HandleRButtonHeld(&pt,0); break; case 7: pWnd->HandleRButtonDown(&pt,0); pWnd->HandleRButtonHeld(&pt,0); pWnd->HandleRButtonUpAfterHeld(&pt,0); break; default: return false; }; gMouseEventTime = GetFastTime(); return true; } } return false; } bool SendListSelect(PCHAR WindowName, PCHAR ScreenID, DWORD Value) { CXWnd *pWnd=FindMQ2Window(WindowName); CXWnd *pParentWnd = 0; if (!pWnd) { MacroError("Window '%s' not available.",WindowName); return false; } if (ScreenID && ScreenID[0] && ScreenID[0]!='0') { CListWnd *pList=(CListWnd*)((CSidlScreenWnd*)(pWnd))->GetChildItem(ScreenID); if (!pList) { MacroError("Window '%s' child '%s' not found.",WindowName,ScreenID); return false; } if (((CXWnd*)pList)->GetType()==UI_Listbox) { pList->SetCurSel(Value); if(pParentWnd = GetParentWnd((CXWnd*)pList)) { pParentWnd->WndNotification((CXWnd*)pList, XWM_LCLICK, (void*)Value); } gMouseEventTime = GetFastTime(); } else if (((CXWnd*)pList)->GetType()==UI_Combobox) { ((CComboWnd*)pList)->SetChoice(Value); if(pParentWnd = GetParentWnd((CXWnd*)pList)) { pParentWnd->WndNotification((CXWnd*)pList, XWM_LCLICK, (void*)Value); } gMouseEventTime = GetFastTime(); } else { MacroError("Window '%s' child '%s' cannot accept this notification.",WindowName,ScreenID); return false; } return true; } return false; } bool SendTabSelect(PCHAR WindowName, PCHAR ScreenID, DWORD Value) { CXWnd *pWnd=FindMQ2Window(WindowName); if (!pWnd) { MacroError("Window '%s' not available.",WindowName); return false; } if (ScreenID && ScreenID[0] && ScreenID[0]!='0') { CTabWnd *pTab = (CTabWnd*)((CSidlScreenWnd*)(pWnd))->GetChildItem(ScreenID); if (!pTab) { MacroError("Window '%s' child '%s' not found.",WindowName,ScreenID); return false; } if (((CXWnd*)pTab)->GetType()==UI_TabBox) { pTab->SetPage(Value, true); gMouseEventTime = GetFastTime(); } else { MacroError("Window '%s' child '%s' cannot accept this notification.",WindowName,ScreenID); return false; } return true; } return false; } bool SendWndNotification(PCHAR WindowName, PCHAR ScreenID, DWORD Notification, VOID *Data) { CHAR szOut[MAX_STRING] = {0}; CXWnd *pWnd=FindMQ2Window(WindowName); if (!pWnd) { sprintf(szOut,"Window '%s' not available.",WindowName); WriteChatColor(szOut,USERCOLOR_DEFAULT); return false; } CXWnd *pButton=0; if (ScreenID && ScreenID[0]) { pButton=((CSidlScreenWnd*)(pWnd))->GetChildItem(ScreenID); if (!pButton) { sprintf(szOut,"Window '%s' child '%s' not found.",WindowName,ScreenID); WriteChatColor(szOut,USERCOLOR_DEFAULT); return false; } } ((CXWnd*)(pWnd))->WndNotification(pButton,Notification,Data); gMouseEventTime = GetFastTime(); return true; } void AddWindow(char *WindowName, CXWnd **ppWindow) { string Name=WindowName; MakeLower(Name); unsigned long N=WindowMap[Name]; if (N) { N--; _WindowInfo *pWnd = WindowList[N]; pWnd->pWnd=0; pWnd->ppWnd=ppWindow; //DebugSpew("Updating WndNotification target '%s'",WindowName); } else { _WindowInfo *pWnd = new _WindowInfo; strcpy(pWnd->Name,WindowName); pWnd->pWnd=0; pWnd->ppWnd=ppWindow; N=WindowList.GetUnused(); WindowList[N]=pWnd; WindowMap[WindowName]=N+1; //DebugSpew("Adding WndNotification target '%s'",Name); } } void RemoveWindow(char *WindowName) { string Name=WindowName; MakeLower(Name); unsigned long N=WindowMap[Name]; if (N) { N--; WindowMap[Name]=0; if (_WindowInfo *pInfo=WindowList[N]) { delete pInfo; WindowList[N]=0; } } } #endif #ifndef ISXEQ #define RETURN(x) return; #else #define RETURN(x) return x; #endif CHAR tmpName[MAX_STRING]={0}; CHAR tmpAltName[MAX_STRING]={0}; CHAR tmpType[MAX_STRING]={0}; int RecurseAndListWindows(PCSIDLWND pWnd) { int Count = 0; if (CXMLData *pXMLData=((CXWnd*)pWnd)->GetXMLData()) { Count++; GetCXStr(pXMLData->TypeName.Ptr,tmpType,MAX_STRING); GetCXStr(pXMLData->Name.Ptr,tmpName,MAX_STRING); GetCXStr(pXMLData->ScreenID.Ptr,tmpAltName,MAX_STRING); if (tmpAltName[0] && stricmp(tmpName,tmpAltName)) WriteChatf("[\ay%s\ax] [\at%s\ax] [Custom UI-specific: \at%s\ax]",tmpType,tmpName,tmpAltName); else WriteChatf("[\ay%s\ax] [\at%s\ax]",tmpType,tmpName); } if (pWnd->pFirstChildWnd) Count += RecurseAndListWindows(pWnd->pFirstChildWnd); if (pWnd->pNextSiblingWnd) Count += RecurseAndListWindows(pWnd->pNextSiblingWnd); return Count; } #ifndef ISXEQ VOID ListWindows(PSPAWNINFO pChar, PCHAR szLine) { #else int ListWindows(int argc, char *argv[]) { PCHAR szLine = NULL; if (argc>0) szLine = argv[1]; #endif unsigned long Count=0; if (!szLine || !szLine[0]) { WriteChatColor("List of available windows"); WriteChatColor("-------------------------"); for (unsigned long N = 0 ; N < WindowList.Size ; N++) if (_WindowInfo *pInfo=WindowList[N]) { WriteChatf("%s",pInfo->Name); Count++; } WriteChatf("%d available windows",Count); } else { // list children of.. string WindowName=szLine; MakeLower(WindowName); unsigned long N = WindowMap[WindowName]; if (!N) { WriteChatf("Window '%s' not available",szLine); RETURN(0); } N--; WriteChatf("Listing child windows of '%s'",szLine); WriteChatColor("-------------------------"); if (_WindowInfo *pInfo=WindowList[N]) { PCSIDLWND pWnd= pInfo->pWnd->pFirstChildWnd; if (pWnd) Count = RecurseAndListWindows(pWnd); WriteChatf("%d child windows",Count); } } RETURN(0); } PCHAR szWndNotification[] = { 0, //0 "leftmouse", //1 "leftmouseup", //2 "rightmouse", //3 0, //4 0, //5 "enter", //6 0, //7 0, //8 "help", //9 "close", //10 0, //11 0, //12 0, //13 "newvalue", //14 0, //15 0, //16 0, //17 0, //18 0, //19 "contextmenu", //20 "mouseover", //21 "history", //22 "leftmousehold", //23 0, //24 0, //25 0, //26 "link", //27 0, //28 "resetdefaultposition", //29 }; #ifndef ISXEQ VOID WndNotify(PSPAWNINFO pChar, PCHAR szLine) { #else int WndNotify(int argc, char *argv[]) { PSPAWNINFO pChar = (PSPAWNINFO)pLocalPlayer; #endif unsigned long Data=0; #ifndef ISXEQ CHAR szArg1[MAX_STRING] = {0}; CHAR szArg2[MAX_STRING] = {0}; CHAR szArg3[MAX_STRING] = {0}; CHAR szArg4[MAX_STRING] = {0}; GetArg(szArg1, szLine, 1); GetArg(szArg2, szLine, 2); GetArg(szArg3, szLine, 3); GetArg(szArg4, szLine, 4); if (!szArg3[0]) { SyntaxError("Syntax: /notify <window|\"item\"> <control|0> <notification> [notification data]"); return; } if (szArg4[0]) Data=atoi(szArg4); #else if (argc<3) { printf("%s syntax: %s <window|\"item\"> <control|0> <notification> [notification data]",argv[0],argv[0]); RETURN(0); } if (argc>4) Data=atoi(argv[4]); CHAR *szArg1=argv[1]; CHAR *szArg2=argv[2]; CHAR *szArg3=argv[3]; CHAR *szArg4=argv[4]; #endif if (!stricmp(szArg3,"link")) { DebugSpewAlways("WndNotify: link found, Data = 1"); Data = 1; } if (Data==0 && SendWndClick(szArg1,szArg2,szArg3)) RETURN(0); if (!stricmp(szArg3,"listselect")) { SendListSelect(szArg1,szArg2,Data-1); RETURN(0); } if (!stricmp(szArg3,"tabselect")) { SendTabSelect(szArg1,szArg2, Data-1); RETURN(0); } for (unsigned long i = 0 ; i < sizeof(szWndNotification)/sizeof(szWndNotification[0]) ; i++) { if (szWndNotification[i] && !stricmp(szWndNotification[i],szArg3)) { if (i==XWM_LINK) { if (!SendWndNotification(szArg1,szArg2,i,(void*)szArg4)) { MacroError("Could not send notification to %s %s",szArg1,szArg2); } RETURN(0); } if (szArg2[0]=='0') { if (!SendWndNotification(szArg1,0,i,(void*)Data)) { MacroError("Could not send notification to %s %s",szArg1,szArg2); } } else if (!SendWndNotification(szArg1,szArg2,i,(void*)Data)) { MacroError("Could not send notification to %s %s",szArg1,szArg2); } RETURN(0); } } MacroError("Invalid notification '%s'",szArg3); RETURN(0); } // item slots: // 2000-2015 bank window // 2500-2501 shared bank // 5000-5031 loot window // 3000-30017 trade window (including npc) 3000-3007 are your slots, 3008-3015 are other character's slots // 4000-4008 world container window // 6000-6080 merchant window // 7000-7080 bazaar window // 8000-8031 inspect window #ifndef ISXEQ VOID ItemNotify(PSPAWNINFO pChar, PCHAR szLine) { CHAR szArg1[MAX_STRING] = {0}; CHAR szArg2[MAX_STRING] = {0}; CHAR szArg3[MAX_STRING] = {0}; CHAR szArg4[MAX_STRING] = {0}; GetArg(szArg1, szLine, 1); GetArg(szArg2, szLine, 2); GetArg(szArg3, szLine, 3); GetArg(szArg4, szLine, 4); if (!szArg2[0]) { WriteChatColor("Syntax: /itemnotify <slot|#> <notification>"); WriteChatColor(" or /itemnotify in <bag slot> <slot # in bag> <notification>"); RETURN(0); } #else int ItemNotify(int argc, char *argv[]) { if (argc!=3 && argc != 5) { //WriteChatf("ItemNotify got %d args", argc); WriteChatColor("Syntax: /itemnotify <slot|#> <notification>"); WriteChatColor(" or /itemnotify in <bag slot> <slot # in bag> <notification>"); RETURN(0); } char *szArg1=argv[1]; char *szArg2=argv[2]; char *szArg3=""; char *szArg4=""; if (argc==5) { szArg3=argv[3]; szArg4=argv[4]; } PSPAWNINFO pChar = (PSPAWNINFO)pLocalPlayer; #endif PCHAR pNotification=&szArg2[0]; EQINVSLOT *pSlot=NULL; DWORD i; PEQINVSLOTMGR pInvMgr=(PEQINVSLOTMGR)pInvSlotMgr; int bagslot = -1; int invslot = -1; int type = -1; if (!stricmp(szArg1,"in")) { if (!szArg4[0]) { WriteChatColor("Syntax: /itemnotify <slot|#> <notification>"); WriteChatColor(" or /itemnotify in <bag slot> <slot # in bag> <notification>"); RETURN(0); } #if 0 PCONTENTS pPack=0; PCONTENTS pItem=0; if (!strnicmp(szArg2,"bank",4)) { unsigned long nPack=atoi(&szArg2[4]); if (nPack && nPack<=NUM_BANK_SLOTS) { pPack=GetCharInfo()->pBankArray->Bank[nPack-1]; } } else if (!strnicmp(szArg2,"sharedbank",10)) { unsigned long nPack=atoi(&szArg2[10]); if (nPack && nPack<=2) { pPack=GetCharInfo()->pSharedBankArray->SharedBank[nPack-1]; } } else if (!strnicmp(szArg2,"pack",4)) { unsigned long nPack=atoi(&szArg2[4]); if (nPack && nPack<=10) { pPack=GetCharInfo2()->pInventoryArray->Inventory.Pack[nPack-1]; } } else if (!stricmp(szArg2,"enviro")) { pPack=((PEQ_CONTAINERWND_MANAGER)pContainerMgr)->pWorldContents; } if (!pPack) { WriteChatf("No item at '%s'",szArg2); RETURN(0); } if (GetItemFromContents(pPack)->Type == ITEMTYPE_PACK) { unsigned long N = atoi(szArg3)-1; if (N<GetItemFromContents(pPack)->Slots && pPack->pContentsArray) { pItem = pPack->pContentsArray->Contents[N]; } if (pItem) { unsigned long nSlot=FindInvSlotForContents(pItem); PEQINVSLOTMGR pInvMgr=(PEQINVSLOTMGR)pInvSlotMgr; pSlot = pInvMgr->SlotArray[nSlot]; } } #endif if (!strnicmp(szArg2,"bank",4)) { invslot=atoi(&szArg2[4])-1; bagslot=atoi(szArg3)-1; type=1; } else if (!strnicmp(szArg2,"sharedbank",10)) { invslot=atoi(&szArg2[10])-1; bagslot=atoi(szArg3)-1; type=2; } else if (!strnicmp(szArg2,"pack",4)) { invslot=atoi(&szArg2[4])-1+23; bagslot=atoi(szArg3)-1; type=0; } for (i=0;i<pInvMgr->TotalSlots;i++) { pSlot = pInvMgr->SlotArray[i]; if ((pSlot->Valid) && (pSlot->pInvSlotWnd->WindowType == type) && (pSlot->pInvSlotWnd->InvSlotForBag == invslot) && (pSlot->pInvSlotWnd->BagSlot == bagslot)) { break; } } if (i == pInvMgr->TotalSlots) pSlot = NULL; pNotification=&szArg4[0]; } else { unsigned long Slot=atoi(szArg1); if (Slot==0) { Slot=ItemSlotMap[strlwr(szArg1)]; if (Slot<NUM_INV_SLOTS) { DebugTry(pSlot=(EQINVSLOT *)pInvSlotMgr->FindInvSlot(Slot)); } else { if (!strnicmp(szArg1, "loot", 4)) { invslot = atoi(szArg1+4) - 1; type = 11; } else if (!strnicmp(szArg1, "enviro", 6)) { invslot = atoi(szArg1+6) - 1; type = 4; } else if (!strnicmp(szArg1, "pack", 4)) { invslot = atoi(szArg1+4) - 1 + 23; type = 0; } else if (!strnicmp(szArg1, "bank", 4)) { invslot = atoi(szArg1+4) - 1; type = 1; } else if (!strnicmp(szArg1, "sharedbank", 10)) { invslot = atoi(szArg1+10) - 1; type = 2; } else if (!strnicmp(szArg1, "trade", 5)) { invslot = atoi(szArg1+5) - 1; type = 3; } for (i=0;i<pInvMgr->TotalSlots;i++) { pSlot = pInvMgr->SlotArray[i]; if ((pSlot->Valid) && (pSlot->pInvSlotWnd->WindowType == type) && (pSlot->pInvSlotWnd->InvSlotForBag == invslot)) { Slot = 1; break; } } if (i == pInvMgr->TotalSlots) Slot = 0; } } if (Slot==0 && szArg1[0]!='0' && stricmp(szArg1,"charm")) { WriteChatf("Invalid item slot '%s'",szArg1); RETURN(0); } else if (Slot && !pSlot) { pSlot = pInvMgr->SlotArray[Slot]; } } if (!pSlot) { WriteChatf("SLOT IS NULL: Could not send notification to %s %s",szArg1,szArg2); RETURN(0); } DebugSpew("ItemNotify: Calling SendWndClick"); if (!pSlot->pInvSlotWnd || !SendWndClick2((CXWnd*)pSlot->pInvSlotWnd,pNotification)) { WriteChatf("Could not send notification to %s %s",szArg1,szArg2); } RETURN(0); } #ifndef ISXEQ VOID ListItemSlots(PSPAWNINFO pChar, PCHAR szLine) #else int ListItemSlots(int argc, char *argv[]) #endif { PEQINVSLOTMGR pMgr=(PEQINVSLOTMGR)pInvSlotMgr; if (!pMgr) RETURN(0); //CHAR szOut[MAX_STRING]={0}; unsigned long Count=0; WriteChatColor("List of available item slots"); WriteChatColor("-------------------------"); for (unsigned long N = 0 ; N < 0x800 ; N++) if (PEQINVSLOT pSlot=pMgr->SlotArray[N]) { if (pSlot->pInvSlotWnd) { WriteChatf("%d %d %d", N, pSlot->pInvSlotWnd->WindowType, pSlot->InvSlot); Count++; } else if (pSlot->InvSlot) { WriteChatf("%d %d", N, pSlot->InvSlot); } } WriteChatf("%d available item slots",Count); RETURN(0) }
29.126621
145
0.524918
Natedog2012
d53db508990fe48081e9c3a826dec8f2e2a57e76
5,850
cpp
C++
src/fields/SoMFVec4ub.cpp
montylab3d/coin
46dec7c01e553815dc6903475116444a1a6e78f5
[ "BSD-3-Clause" ]
158
2019-12-27T16:39:35.000Z
2022-03-28T19:04:39.000Z
src/fields/SoMFVec4ub.cpp
montylab3d/coin
46dec7c01e553815dc6903475116444a1a6e78f5
[ "BSD-3-Clause" ]
261
2019-12-23T19:23:28.000Z
2022-03-23T10:11:01.000Z
src/fields/SoMFVec4ub.cpp
montylab3d/coin
46dec7c01e553815dc6903475116444a1a6e78f5
[ "BSD-3-Clause" ]
63
2019-12-27T21:18:29.000Z
2022-03-16T02:11:16.000Z
/**************************************************************************\ * Copyright (c) Kongsberg Oil & Gas Technologies AS * 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 holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \**************************************************************************/ /*! \class SoMFVec4ub SoMFVec4ub.h Inventor/fields/SoMFVec4ub.h \brief The SoMFVec4ub class is a container for SbVec4ub vectors. \ingroup coin_fields This field is used where nodes, engines or other field containers need to store an array of vectors with four elements. This field supports application data sharing through a setValuesPointer() method. See SoMField documentation for information on how to use this function. \sa SbVec4ub, SoSFVec4ub \COIN_CLASS_EXTENSION \since Coin 2.5 */ // ************************************************************************* #include <Inventor/fields/SoMFVec4ub.h> #include <cassert> #include <Inventor/SoInput.h> #include <Inventor/errors/SoDebugError.h> #include "fields/SoSubFieldP.h" #include "fields/shared.h" // ************************************************************************* SO_MFIELD_SOURCE(SoMFVec4ub, SbVec4ub, SbVec4ub); SO_MFIELD_SETVALUESPOINTER_SOURCE(SoMFVec4ub, SbVec4ub, SbVec4ub); SO_MFIELD_SETVALUESPOINTER_SOURCE(SoMFVec4ub, SbVec4ub, uint8_t); // ************************************************************************* /*! \copydetails SoField::initClass(void) */ void SoMFVec4ub::initClass(void) { SO_MFIELD_INTERNAL_INIT_CLASS(SoMFVec4ub); } // ************************************************************************* // No need to document readValue() and writeValue() here, as the // necessary information is provided by the documentation of the // parent classes. #ifndef DOXYGEN_SKIP_THIS SbBool SoMFVec4ub::read1Value(SoInput * in, int idx) { assert(idx < this->maxNum); return in->readByte(this->values[idx][0]) && in->readByte(this->values[idx][1]) && in->readByte(this->values[idx][2]) && in->readByte(this->values[idx][3]); } void SoMFVec4ub::write1Value(SoOutput * out, int idx) const { sosfvec4ub_write_value(out, (*this)[idx]); } #endif // DOXYGEN_SKIP_THIS // ************************************************************************* /*! Set \a num vector array elements from \a xyzw, starting at index \a start. */ void SoMFVec4ub::setValues(int start, int numarg, const uint8_t xyzw[][4]) { if(start+numarg > this->maxNum) this->allocValues(start+numarg); else if(start+numarg > this->num) this->num = start+numarg; for(int i=0; i < numarg; i++) this->values[i+start].setValue(xyzw[i]); this->valueChanged(); } /*! Set the vector at \a idx. */ void SoMFVec4ub::set1Value(int idx, uint8_t x, uint8_t y, uint8_t z, uint8_t w) { this->set1Value(idx, SbVec4ub(x, y, z, w)); } /*! Set the vector at \a idx. */ void SoMFVec4ub::set1Value(int idx, const uint8_t xyzw[4]) { this->set1Value(idx, SbVec4ub(xyzw)); } /*! Set this field to contain a single vector with the given element values. */ void SoMFVec4ub::setValue(uint8_t x, uint8_t y, uint8_t z, uint8_t w) { this->setValue(SbVec4ub(x,y,z,w)); } /*! Set this field to contain a single vector with the given element values. */ void SoMFVec4ub::setValue(const uint8_t xyzw[4]) { if (xyzw == NULL) this->setNum(0); else this->setValue(SbVec4ub(xyzw)); } // ************************************************************************* #ifdef COIN_TEST_SUITE BOOST_AUTO_TEST_CASE(initialized) { SoMFVec4ub field; BOOST_CHECK_MESSAGE(field.getTypeId() != SoType::badType(), "missing class initialization"); BOOST_CHECK_EQUAL(field.getNum(), 0); } BOOST_AUTO_TEST_CASE(textinput) { SbBool ok; SoMFVec4ub field; ok = field.set("[]"); BOOST_CHECK_EQUAL(ok, TRUE); BOOST_CHECK_EQUAL(field.getNum(), 0); ok = field.set("1 2 3 4"); BOOST_CHECK_EQUAL(ok, TRUE); BOOST_CHECK_EQUAL(field.getNum(), 1); ok = field.set("[1 2 3 4]"); BOOST_CHECK_EQUAL(ok, TRUE); BOOST_CHECK_EQUAL(field.getNum(), 1); ok = field.set("[1 2 3 4 1 2 3 4]"); BOOST_CHECK_EQUAL(ok, TRUE); BOOST_CHECK_EQUAL(field.getNum(), 2); BOOST_CHECK_EQUAL(field[0], field[1]); ok = field.set("[1 2 3 4, 1 2 3 4,]"); BOOST_CHECK_EQUAL(ok, TRUE); BOOST_CHECK_EQUAL(field.getNum(), 2); BOOST_CHECK_EQUAL(field[0], field[1]); } #endif // COIN_TEST_SUITE
29.545455
76
0.650256
montylab3d
d53e4279dcb9c89f039ef4a9ef62bf957019cefa
11,722
hpp
C++
libs/core/schedulers/include/hpx/schedulers/queue_holder_numa.hpp
sudo-panda/hpx
1527f3ba8055f795f701ddf89368f4a24199f79e
[ "BSL-1.0" ]
1
2021-02-03T09:17:55.000Z
2021-02-03T09:17:55.000Z
libs/core/schedulers/include/hpx/schedulers/queue_holder_numa.hpp
sudo-panda/hpx
1527f3ba8055f795f701ddf89368f4a24199f79e
[ "BSL-1.0" ]
null
null
null
libs/core/schedulers/include/hpx/schedulers/queue_holder_numa.hpp
sudo-panda/hpx
1527f3ba8055f795f701ddf89368f4a24199f79e
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2019 John Biddiscombe // // SPDX-License-Identifier: BSL-1.0 // 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) #pragma once #include <hpx/config.hpp> #include <hpx/schedulers/lockfree_queue_backends.hpp> #include <hpx/schedulers/thread_queue_mc.hpp> #include <hpx/threading_base/print.hpp> #include <hpx/threading_base/thread_data.hpp> // #include <hpx/modules/logging.hpp> #include <hpx/thread_support/unlock_guard.hpp> #include <hpx/type_support/unused.hpp> // #include <hpx/schedulers/queue_holder_thread.hpp> // #include <cmath> #include <cstddef> #include <cstdint> #include <list> #include <map> #include <unordered_set> #include <vector> #include <atomic> #include <exception> #include <functional> #include <memory> #include <mutex> #include <string> #include <utility> #if !defined(QUEUE_HOLDER_NUMA_DEBUG) #if defined(HPX_DEBUG) #define QUEUE_HOLDER_NUMA_DEBUG false #else #define QUEUE_HOLDER_NUMA_DEBUG false #endif #endif namespace hpx { static hpx::debug::enable_print<QUEUE_HOLDER_NUMA_DEBUG> nq_deb("QH_NUMA"); } // ------------------------------------------------------------//////// namespace hpx { namespace threads { namespace policies { // ---------------------------------------------------------------- // Helper class to hold a set of thread queue holders. // ---------------------------------------------------------------- template <typename QueueType> struct queue_holder_numa { // ---------------------------------------------------------------- using ThreadQueue = queue_holder_thread<QueueType>; using mutex_type = typename QueueType::mutex_type; // ---------------------------------------------------------------- queue_holder_numa() : num_queues_(0) , domain_(0) { } // ---------------------------------------------------------------- ~queue_holder_numa() { for (auto& q : queues_) delete q; queues_.clear(); } // ---------------------------------------------------------------- void init(std::size_t domain, std::size_t queues) { num_queues_ = queues; domain_ = domain; // start with unset queue pointers queues_.resize(num_queues_, nullptr); } // ---------------------------------------------------------------- inline std::size_t size() const { return queues_.size(); } // ---------------------------------------------------------------- inline ThreadQueue* thread_queue(std::size_t id) const { return queues_[id]; } // ---------------------------------------------------------------- inline bool get_next_thread_HP(std::size_t qidx, threads::thread_data*& thrd, bool stealing, bool core_stealing) { // loop over queues and take one task, std::size_t q = qidx; for (std::size_t i = 0; i < num_queues_; ++i, q = fast_mod((qidx + i), num_queues_)) { if (queues_[q]->get_next_thread_HP( thrd, (stealing || (i > 0)), i == 0)) { // clang-format off nq_deb.debug(debug::str<>("HP/BP get_next") , "D", debug::dec<2>(domain_) , "Q", debug::dec<3>(q) , "Qidx", debug::dec<3>(qidx) , ((i==0 && !stealing) ? "taken" : "stolen from") , typename ThreadQueue::queue_data_print(queues_[q]) , debug::threadinfo<threads::thread_data*>(thrd)); // clang-format on return true; } // if stealing disabled, do not check other queues if (!core_stealing) return false; } return false; } // ---------------------------------------------------------------- inline bool get_next_thread(std::size_t qidx, threads::thread_data*& thrd, bool stealing, bool core_stealing) { // loop over queues and take one task, // starting with the requested queue std::size_t q = qidx; for (std::size_t i = 0; i < num_queues_; ++i, q = fast_mod((qidx + i), num_queues_)) { // if we got a thread, return it, only allow stealing if i>0 if (queues_[q]->get_next_thread(thrd, (stealing || (i > 0)))) { nq_deb.debug(debug::str<>("get_next"), "D", debug::dec<2>(domain_), "Q", debug::dec<3>(q), "Qidx", debug::dec<3>(qidx), ((i == 0 && !stealing) ? "taken" : "stolen from"), typename ThreadQueue::queue_data_print(queues_[q]), debug::threadinfo<threads::thread_data*>(thrd)); return true; } // if stealing disabled, do not check other queues if (!core_stealing) return false; } return false; } // ---------------------------------------------------------------- bool add_new_HP(ThreadQueue* receiver, std::size_t qidx, std::size_t& added, bool stealing, bool allow_stealing) { // loop over queues and take one task, std::size_t q = qidx; for (std::size_t i = 0; i < num_queues_; ++i, q = fast_mod((qidx + i), num_queues_)) { added = receiver->add_new_HP(64, queues_[q], (stealing || (i > 0))); if (added > 0) { // clang-format off nq_deb.debug(debug::str<>("HP/BP add_new") , "added", debug::dec<>(added) , "D", debug::dec<2>(domain_) , "Q", debug::dec<3>(q) , "Qidx", debug::dec<3>(qidx) , ((i==0 && !stealing) ? "taken" : "stolen from") , typename ThreadQueue::queue_data_print(queues_[q])); // clang-format on return true; } // if stealing disabled, do not check other queues if (!allow_stealing) return false; } return false; } // ---------------------------------------------------------------- bool add_new(ThreadQueue* receiver, std::size_t qidx, std::size_t& added, bool stealing, bool allow_stealing) { // loop over queues and take one task, std::size_t q = qidx; for (std::size_t i = 0; i < num_queues_; ++i, q = fast_mod((qidx + i), num_queues_)) { added = receiver->add_new(64, queues_[q], (stealing || (i > 0))); if (added > 0) { // clang-format off nq_deb.debug(debug::str<>("add_new") , "added", debug::dec<>(added) , "D", debug::dec<2>(domain_) , "Q", debug::dec<3>(q) , "Qidx", debug::dec<3>(qidx) , ((i==0 && !stealing) ? "taken" : "stolen from") , typename ThreadQueue::queue_data_print(queues_[q])); // clang-format on return true; } // if stealing disabled, do not check other queues if (!allow_stealing) return false; } return false; } // ---------------------------------------------------------------- inline std::size_t get_new_tasks_queue_length() const { std::size_t len = 0; for (auto& q : queues_) len += q->new_tasks_count_; return len; } // ---------------------------------------------------------------- inline std::int64_t get_thread_count( thread_schedule_state state = thread_schedule_state::unknown, thread_priority priority = thread_priority::default_) const { std::size_t len = 0; for (auto& q : queues_) len += q->get_thread_count(state, priority); return len; } // ---------------------------------------------------------------- void abort_all_suspended_threads() { for (auto& q : queues_) q->abort_all_suspended_threads(); } // ---------------------------------------------------------------- bool enumerate_threads( util::function_nonser<bool(thread_id_type)> const& f, thread_schedule_state state) const { bool result = true; for (auto& q : queues_) result = q->enumerate_threads(f, state) && result; return result; } // ---------------------------------------------------------------- // ---------------------------------------------------------------- // ---------------------------------------------------------------- std::size_t num_queues_; std::size_t domain_; std::vector<ThreadQueue*> queues_; public: // // ------------------------------------------------------------ // // This returns the current length of the pending queue // std::int64_t get_pending_queue_length() const // { // return work_items_count_; // } // // This returns the current length of the staged queue // std::int64_t get_staged_queue_length( // std::memory_order order = std::memory_order_seq_cst) const // { // return new_tasks_count_.load(order); // } void increment_num_pending_misses(std::size_t /* num */ = 1) {} void increment_num_pending_accesses(std::size_t /* num */ = 1) {} void increment_num_stolen_from_pending(std::size_t /* num */ = 1) {} void increment_num_stolen_from_staged(std::size_t /* num */ = 1) {} void increment_num_stolen_to_pending(std::size_t /* num */ = 1) {} void increment_num_stolen_to_staged(std::size_t /* num */ = 1) {} // ------------------------------------------------------------ bool dump_suspended_threads(std::size_t /* num_thread */, std::int64_t& /* idle_loop_count */, bool /* running */) { return false; } // ------------------------------------------------------------ void debug_info() { for (auto& q : queues_) q->debug_info(); } // ------------------------------------------------------------ void on_start_thread(std::size_t /* num_thread */) {} void on_stop_thread(std::size_t /* num_thread */) {} void on_error( std::size_t /* num_thread */, std::exception_ptr const& /* e */) { } }; }}} // namespace hpx::threads::policies
38.18241
81
0.424672
sudo-panda
d540d1800f09d16a635826522473f00e73a2597c
2,497
cpp
C++
opencl/test/unit_test/os_interface/linux/mock_performance_counters_linux.cpp
scott-snyder/compute-runtime
9b3dd97f8190167482116f36a7f2458ba4705fbf
[ "MIT" ]
1
2020-09-03T17:10:38.000Z
2020-09-03T17:10:38.000Z
opencl/test/unit_test/os_interface/linux/mock_performance_counters_linux.cpp
scott-snyder/compute-runtime
9b3dd97f8190167482116f36a7f2458ba4705fbf
[ "MIT" ]
null
null
null
opencl/test/unit_test/os_interface/linux/mock_performance_counters_linux.cpp
scott-snyder/compute-runtime
9b3dd97f8190167482116f36a7f2458ba4705fbf
[ "MIT" ]
null
null
null
/* * Copyright (C) 2017-2020 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "mock_performance_counters_linux.h" #include "opencl/test/unit_test/os_interface/linux/drm_mock.h" #include "opencl/test/unit_test/os_interface/linux/mock_os_time_linux.h" #include "opencl/test/unit_test/os_interface/mock_performance_counters.h" namespace NEO { ////////////////////////////////////////////////////// // MockPerformanceCountersLinux::MockPerformanceCountersLinux ////////////////////////////////////////////////////// MockPerformanceCountersLinux::MockPerformanceCountersLinux(Device *device) : PerformanceCountersLinux() { } ////////////////////////////////////////////////////// // MockPerformanceCounters::create ////////////////////////////////////////////////////// std::unique_ptr<PerformanceCounters> MockPerformanceCounters::create(Device *device) { auto performanceCounters = std::unique_ptr<PerformanceCounters>(new MockPerformanceCountersLinux(device)); auto metricsLibrary = std::make_unique<MockMetricsLibrary>(); auto metricsLibraryDll = std::make_unique<MockMetricsLibraryDll>(); metricsLibrary->api = std::make_unique<MockMetricsLibraryValidInterface>(); metricsLibrary->osLibrary = std::move(metricsLibraryDll); performanceCounters->setMetricsLibraryInterface(std::move(metricsLibrary)); return performanceCounters; } ////////////////////////////////////////////////////// // PerformanceCountersFixture::createPerfCounters ////////////////////////////////////////////////////// void PerformanceCountersFixture::createPerfCounters() { performanceCountersBase = MockPerformanceCounters::create(&device->getDevice()); } ////////////////////////////////////////////////////// // PerformanceCountersFixture::SetUp ////////////////////////////////////////////////////// void PerformanceCountersFixture::SetUp() { device = std::make_unique<MockClDevice>(new MockDevice()); context = std::make_unique<MockContext>(device.get()); queue = std::make_unique<MockCommandQueue>(context.get(), device.get(), &queueProperties); osInterface = std::unique_ptr<OSInterface>(new OSInterface()); osInterface->get()->setDrm(new DrmMock()); device->setOSTime(new MockOSTimeLinux(osInterface.get())); } ////////////////////////////////////////////////////// // PerformanceCountersFixture::TearDown ////////////////////////////////////////////////////// void PerformanceCountersFixture::TearDown() { } } // namespace NEO
40.274194
110
0.611133
scott-snyder
d543e97a9a106beaef4bb35cea189b8731791435
3,224
cpp
C++
muse_mcl_2d_gridmaps/src/models/likelihood_field_model_amcl_normalized.cpp
doge-of-the-day/muse_mcl_2d
4cb53120e78780ccc7a7a62d40278fd075d2a54d
[ "BSD-3-Clause" ]
4
2019-06-01T14:08:29.000Z
2019-11-07T02:01:53.000Z
muse_mcl_2d_gridmaps/src/models/likelihood_field_model_amcl_normalized.cpp
cogsys-tuebingen/muse_mcl_2d
dc053c61208a6ec740b70cea81aaf3c466c1c3b4
[ "BSD-3-Clause" ]
null
null
null
muse_mcl_2d_gridmaps/src/models/likelihood_field_model_amcl_normalized.cpp
cogsys-tuebingen/muse_mcl_2d
dc053c61208a6ec740b70cea81aaf3c466c1c3b4
[ "BSD-3-Clause" ]
6
2019-03-04T01:46:02.000Z
2020-09-30T01:58:22.000Z
#include "likelihood_field_model_amcl_normalized.h" #include <muse_mcl_2d_gridmaps/maps/distance_gridmap.h> #include <class_loader/register_macro.hpp> #include <cslibs_plugins_data/types/laserscan.hpp> CLASS_LOADER_REGISTER_CLASS( muse_mcl_2d_gridmaps::LikelihoodFieldModelAMCLNormalized, muse_mcl_2d::UpdateModel2D) namespace muse_mcl_2d_gridmaps { LikelihoodFieldModelAMCLNormalized::LikelihoodFieldModelAMCLNormalized() {} void LikelihoodFieldModelAMCLNormalized::apply( const std::shared_ptr<data_t const> &data, const std::shared_ptr<state_space_t const> &map, sample_set_t::weight_iterator_t set) { if (!map->isType<DistanceGridmap>()) { return; } if (ps_.size() != set.capacity()) { ps_.resize(set.capacity()); } std::fill(ps_.begin(), ps_.end(), 0.0); using laserscan_t = cslibs_plugins_data::types::Laserscan2d; const DistanceGridmap::map_t &gridmap = *(map->as<DistanceGridmap>().data()); const laserscan_t &laser_data = data->as<laserscan_t>(); const laserscan_t::rays_t &laser_rays = laser_data.getRays(); /// laser to base transform transform_t b_T_l; transform_t m_T_w; if (!tf_->lookupTransform(robot_base_frame_, laser_data.frame(), ros::Time(laser_data.timeFrame().end.seconds()), b_T_l, tf_timeout_)) return; if (!tf_->lookupTransform(world_frame_, map->getFrame(), ros::Time(laser_data.timeFrame().end.seconds()), m_T_w, tf_timeout_)) return; const laserscan_t::rays_t rays = laser_data.getRays(); const auto end = set.end(); const auto const_end = set.const_end(); const std::size_t rays_size = rays.size(); const std::size_t ray_step = std::max(1ul, (rays_size - 1) / (max_beams_ - 1)); const double range_max = laser_data.getLinearMax(); const double p_rand = z_rand_ * 1.0 / range_max; auto p_hit = [this](const double z) { return z_hit_ * std::exp(-z * z * denominator_hit_); }; auto it_ps = ps_.begin(); double p_max = std::numeric_limits<double>::lowest(); for (auto it = set.const_begin(); it != const_end; ++it, ++it_ps) { const state_t m_T_l = m_T_w * it->state() * b_T_l; /// laser scanner pose in map coordinates double p = 1.0; for (std::size_t i = 0; i < rays_size; i += ray_step) { const auto &ray = laser_rays[i]; const point_t ray_end_point = m_T_l * ray.end_point; const double pz = ray.valid() ? p_hit(gridmap.at(ray_end_point)) + p_rand : 0.0; p += pz * pz * pz; } *it_ps = p; p_max = p >= p_max ? p : p_max; } it_ps = ps_.begin(); for (auto it = set.begin(); it != end; ++it, ++it_ps) { *it *= *it_ps / p_max; } } void LikelihoodFieldModelAMCLNormalized::doSetup(ros::NodeHandle &nh) { auto param_name = [this](const std::string &name) { return name_ + "/" + name; }; max_beams_ = nh.param(param_name("max_beams"), 30); z_hit_ = nh.param(param_name("z_hit"), 0.8); z_rand_ = nh.param(param_name("z_rand"), 0.05); sigma_hit_ = nh.param(param_name("sigma_hit"), 0.15); denominator_hit_ = 0.5 * 1.0 / (sigma_hit_ * sigma_hit_); } } // namespace muse_mcl_2d_gridmaps
35.043478
79
0.658189
doge-of-the-day
d54443f3c9f64f237e8a49074abdd0f2e9594d0c
5,396
cc
C++
src/operator/numpy/np_polynomial_op.cc
wms2537/incubator-mxnet
b7d7e02705deb1dc4942bf39efc19f133e2181f7
[ "Apache-2.0", "MIT" ]
1
2019-12-20T11:25:06.000Z
2019-12-20T11:25:06.000Z
src/operator/numpy/np_polynomial_op.cc
wms2537/incubator-mxnet
b7d7e02705deb1dc4942bf39efc19f133e2181f7
[ "Apache-2.0", "MIT" ]
null
null
null
src/operator/numpy/np_polynomial_op.cc
wms2537/incubator-mxnet
b7d7e02705deb1dc4942bf39efc19f133e2181f7
[ "Apache-2.0", "MIT" ]
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. */ /*! * Copyright (c) 202o by Contributors * \file np_polynomial_op.cc */ #include <cmath> #include "np_polynomial_op-inl.h" namespace mxnet { namespace op { template <int req> struct polyval_backward_x { template <typename DType> MSHADOW_XINLINE static void Map(index_t i, const DType* p_dptr, const DType* x_dptr, DType* igrad_x_dptr, const DType* ograd_dptr, const index_t p_size) { DType igrad_x = 0; index_t j = p_size - 1; while (j > 0) { igrad_x = igrad_x * x_dptr[i] + p_dptr[p_size - j - 1] * j; j--; } KERNEL_ASSIGN(igrad_x_dptr[i], req, igrad_x * ograd_dptr[i]); } }; template <int req> struct polyval_backward_p { template <typename DType> MSHADOW_XINLINE static void Map(index_t i, const DType* p_dptr, const DType* x_dptr, DType* igrad_p_dptr, const DType* ograd_dptr, const index_t p_size, const index_t x_size) { DType igrad_p = 0; index_t j = x_size - 1; while (j >= 0) { igrad_p += pow(x_dptr[j], static_cast<DType>(p_size) - static_cast<DType>(i + 1)) * ograd_dptr[j]; j--; } KERNEL_ASSIGN(igrad_p_dptr[i], req, igrad_p); } }; void NumpyPolyvalBackwardCPU(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { CHECK_EQ(inputs.size(), 3U); CHECK_EQ(outputs.size(), 2U); CHECK_NE(req[0], kWriteInplace); if (inputs[1].type_flag_ != inputs[2].type_flag_ || !common::is_float(inputs[1].type_flag_) || !common::is_float(inputs[2].type_flag_)) { return; } mshadow::Stream<cpu>* s = ctx.get_stream<cpu>(); const TBlob& ograd = inputs[0]; const TBlob& p = inputs[1]; const TBlob& x = inputs[2]; const TBlob& igrad_p = outputs[0]; const TBlob& igrad_x = outputs[1]; const size_t p_size = p.Size(); using namespace mxnet_op; MSHADOW_REAL_TYPE_SWITCH(ograd.type_flag_, DType, { MXNET_ASSIGN_REQ_SWITCH(req[0], req_type, { Kernel<polyval_backward_x<req_type>, cpu>::Launch(s, ograd.Size(), p.dptr<DType>(), x.dptr<DType>(), igrad_x.dptr<DType>(), ograd.dptr<DType>(), p_size); Kernel<polyval_backward_p<req_type>, cpu>::Launch(s, p_size, p.dptr<DType>(), x.dptr<DType>(), igrad_p.dptr<DType>(), ograd.dptr<DType>(), p_size, x.Size()); }); }); } NNVM_REGISTER_OP(_npi_polyval) .set_num_inputs(2) .set_num_outputs(1) .add_argument("p", "NDArray-or-Symbol", "polynomial coefficients") .add_argument("x", "NDArray-or-Symbol", "variables") .set_attr<nnvm::FListInputNames>("FListInputNames", [](const NodeAttrs& attrs) { return std::vector<std::string>{"p", "x"}; }) .set_attr<mxnet::FInferShape>("FInferShape", NumpyPolyvalShape) .set_attr<nnvm::FInferType>("FInferType", mxnet::op::ElemwiseType<2, 1>) .set_attr<mxnet::FCompute>("FCompute<cpu>", NumpyPolyvalForward<cpu>) .set_attr<nnvm::FGradient>("FGradient", ElemwiseGradUseIn{"_npi_backward_polyval"}); NNVM_REGISTER_OP(_npi_backward_polyval) .set_num_inputs(3) .set_num_outputs(2) .set_attr<nnvm::TIsBackward>("TIsBackward", true) .set_attr<mxnet::FCompute>("FCompute<cpu>", NumpyPolyvalBackwardCPU); } // namespace op } // namespace mxnet
39.386861
97
0.519274
wms2537
d5455d2ab3963de900d3b66d83e89248e050923d
8,279
hpp
C++
ares/component/processor/z80/z80.hpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
153
2020-07-25T17:55:29.000Z
2021-10-01T23:45:01.000Z
ares/component/processor/z80/z80.hpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
245
2021-10-08T09:14:46.000Z
2022-03-31T08:53:13.000Z
ares/component/processor/z80/z80.hpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
44
2020-07-25T08:51:55.000Z
2021-09-25T16:09:01.000Z
#pragma once //Zilog Z80 namespace ares { struct Z80 { struct Bus { virtual auto read(n16 address) -> n8 = 0; virtual auto write(n16 address, n8 data) -> void = 0; virtual auto in(n16 address) -> n8 = 0; virtual auto out(n16 address, n8 data) -> void = 0; }; virtual auto step(u32 clocks) -> void = 0; virtual auto synchronizing() const -> bool = 0; //CMOS: out (c) writes 0x00 //NMOS: out (c) writes 0xff; if an interrupt fires during "ld a,i" or "ld a,r", PF is cleared enum class MOSFET : u32 { CMOS, NMOS }; //z80.cpp auto power(MOSFET = MOSFET::NMOS) -> void; auto irq(bool maskable, n16 vector = 0x0000, n8 extbus = 0xff) -> bool; auto parity(n8) const -> bool; //memory.cpp auto wait(u32 clocks = 1) -> void; auto opcode() -> n8; auto operand() -> n8; auto operands() -> n16; auto push(n16) -> void; auto pop() -> n16; auto displace(n16&) -> n16; auto read(n16 address) -> n8; auto write(n16 address, n8 data) -> void; auto in(n16 address) -> n8; auto out(n16 address, n8 data) -> void; //instruction.cpp auto instruction() -> void; auto instruction(n8 code) -> void; auto instructionCB(n8 code) -> void; auto instructionCBd(n16 address, n8 code) -> void; auto instructionED(n8 code) -> void; //algorithms.cpp auto ADD(n8, n8, bool = false) -> n8; auto AND(n8, n8) -> n8; auto BIT(n3, n8) -> n8; auto CP (n8, n8) -> void; auto DEC(n8) -> n8; auto IN (n8) -> n8; auto INC(n8) -> n8; auto OR (n8, n8) -> n8; auto RES(n3, n8) -> n8; auto RL (n8) -> n8; auto RLC(n8) -> n8; auto RR (n8) -> n8; auto RRC(n8) -> n8; auto SET(n3, n8) -> n8; auto SLA(n8) -> n8; auto SLL(n8) -> n8; auto SRA(n8) -> n8; auto SRL(n8) -> n8; auto SUB(n8, n8, bool = false) -> n8; auto XOR(n8, n8) -> n8; //instructions.cpp auto instructionADC_a_irr(n16&) -> void; auto instructionADC_a_n() -> void; auto instructionADC_a_r(n8&) -> void; auto instructionADC_hl_rr(n16&) -> void; auto instructionADD_a_irr(n16&) -> void; auto instructionADD_a_n() -> void; auto instructionADD_a_r(n8&) -> void; auto instructionADD_hl_rr(n16&) -> void; auto instructionAND_a_irr(n16&) -> void; auto instructionAND_a_n() -> void; auto instructionAND_a_r(n8&) -> void; auto instructionBIT_o_irr(n3, n16&) -> void; auto instructionBIT_o_irr_r(n3, n16&, n8&) -> void; auto instructionBIT_o_r(n3, n8&) -> void; auto instructionCALL_c_nn(bool c) -> void; auto instructionCALL_nn() -> void; auto instructionCCF() -> void; auto instructionCP_a_irr(n16& x) -> void; auto instructionCP_a_n() -> void; auto instructionCP_a_r(n8& x) -> void; auto instructionCPD() -> void; auto instructionCPDR() -> void; auto instructionCPI() -> void; auto instructionCPIR() -> void; auto instructionCPL() -> void; auto instructionDAA() -> void; auto instructionDEC_irr(n16&) -> void; auto instructionDEC_r(n8&) -> void; auto instructionDEC_rr(n16&) -> void; auto instructionDI() -> void; auto instructionDJNZ_e() -> void; auto instructionEI() -> void; auto instructionEX_irr_rr(n16&, n16&) -> void; auto instructionEX_rr_rr(n16&, n16&) -> void; auto instructionEXX() -> void; auto instructionHALT() -> void; auto instructionIM_o(n2) -> void; auto instructionIN_a_in() -> void; auto instructionIN_r_ic(n8&) -> void; auto instructionIN_ic() -> void; auto instructionINC_irr(n16&) -> void; auto instructionINC_r(n8&) -> void; auto instructionINC_rr(n16&) -> void; auto instructionIND() -> void; auto instructionINDR() -> void; auto instructionINI() -> void; auto instructionINIR() -> void; auto instructionJP_c_nn(bool) -> void; auto instructionJP_rr(n16&) -> void; auto instructionJR_c_e(bool) -> void; auto instructionLD_a_inn() -> void; auto instructionLD_a_irr(n16& x) -> void; auto instructionLD_inn_a() -> void; auto instructionLD_inn_rr(n16&) -> void; auto instructionLD_irr_a(n16&) -> void; auto instructionLD_irr_n(n16&) -> void; auto instructionLD_irr_r(n16&, n8&) -> void; auto instructionLD_r_n(n8&) -> void; auto instructionLD_r_irr(n8&, n16&) -> void; auto instructionLD_r_r(n8&, n8&) -> void; auto instructionLD_r_r1(n8&, n8&) -> void; auto instructionLD_r_r2(n8&, n8&) -> void; auto instructionLD_rr_inn(n16&) -> void; auto instructionLD_rr_nn(n16&) -> void; auto instructionLD_sp_rr(n16&) -> void; auto instructionLDD() -> void; auto instructionLDDR() -> void; auto instructionLDI() -> void; auto instructionLDIR() -> void; auto instructionNEG() -> void; auto instructionNOP() -> void; auto instructionOR_a_irr(n16&) -> void; auto instructionOR_a_n() -> void; auto instructionOR_a_r(n8&) -> void; auto instructionOTDR() -> void; auto instructionOTIR() -> void; auto instructionOUT_ic_r(n8&) -> void; auto instructionOUT_ic() -> void; auto instructionOUT_in_a() -> void; auto instructionOUTD() -> void; auto instructionOUTI() -> void; auto instructionPOP_rr(n16&) -> void; auto instructionPUSH_rr(n16&) -> void; auto instructionRES_o_irr(n3, n16&) -> void; auto instructionRES_o_irr_r(n3, n16&, n8&) -> void; auto instructionRES_o_r(n3, n8&) -> void; auto instructionRET() -> void; auto instructionRET_c(bool c) -> void; auto instructionRETI() -> void; auto instructionRETN() -> void; auto instructionRL_irr(n16&) -> void; auto instructionRL_irr_r(n16&, n8&) -> void; auto instructionRL_r(n8&) -> void; auto instructionRLA() -> void; auto instructionRLC_irr(n16&) -> void; auto instructionRLC_irr_r(n16&, n8&) -> void; auto instructionRLC_r(n8&) -> void; auto instructionRLCA() -> void; auto instructionRLD() -> void; auto instructionRR_irr(n16&) -> void; auto instructionRR_irr_r(n16&, n8&) -> void; auto instructionRR_r(n8&) -> void; auto instructionRRA() -> void; auto instructionRRC_irr(n16&) -> void; auto instructionRRC_irr_r(n16&, n8&) -> void; auto instructionRRC_r(n8&) -> void; auto instructionRRCA() -> void; auto instructionRRD() -> void; auto instructionRST_o(n3) -> void; auto instructionSBC_a_irr(n16&) -> void; auto instructionSBC_a_n() -> void; auto instructionSBC_a_r(n8&) -> void; auto instructionSBC_hl_rr(n16&) -> void; auto instructionSCF() -> void; auto instructionSET_o_irr(n3, n16&) -> void; auto instructionSET_o_irr_r(n3, n16&, n8&) -> void; auto instructionSET_o_r(n3, n8&) -> void; auto instructionSLA_irr(n16&) -> void; auto instructionSLA_irr_r(n16&, n8&) -> void; auto instructionSLA_r(n8&) -> void; auto instructionSLL_irr(n16&) -> void; auto instructionSLL_irr_r(n16&, n8&) -> void; auto instructionSLL_r(n8&) -> void; auto instructionSRA_irr(n16&) -> void; auto instructionSRA_irr_r(n16&, n8&) -> void; auto instructionSRA_r(n8&) -> void; auto instructionSRL_irr(n16&) -> void; auto instructionSRL_irr_r(n16&, n8&) -> void; auto instructionSRL_r(n8&) -> void; auto instructionSUB_a_irr(n16&) -> void; auto instructionSUB_a_n() -> void; auto instructionSUB_a_r(n8&) -> void; auto instructionXOR_a_irr(n16&) -> void; auto instructionXOR_a_n() -> void; auto instructionXOR_a_r(n8&) -> void; //serialization.cpp auto serialize(serializer&) -> void; //disassembler.cpp noinline auto disassembleInstruction(maybe<n16> pc = {}) -> string; noinline auto disassembleContext() -> string; auto disassemble(n16 pc, n8 prefix, n8 code) -> string; auto disassembleCB(n16 pc, n8 prefix, n8 code) -> string; auto disassembleCBd(n16 pc, n8 prefix, i8 d, n8 code) -> string; auto disassembleED(n16 pc, n8 prefix, n8 code) -> string; MOSFET mosfet = MOSFET::NMOS; enum class Prefix : u32 { hl, ix, iy } prefix = Prefix::hl; union Pair { Pair() : word(0) {} n16 word; struct Byte { n8 order_msb2(hi, lo); } byte; }; Pair af, af_; Pair bc, bc_; Pair de, de_; Pair hl, hl_; Pair ix; Pair iy; Pair ir; Pair wz; n16 SP; n16 PC; b1 EI; //"ei" executed last b1 P; //"ld a,i" or "ld a,r" executed last b1 Q; //opcode that updated flag registers executed last b1 HALT; //"halt" instruction executed b1 IFF1; //interrupt flip-flop 1 b1 IFF2; //interrupt flip-flop 2 n2 IM; //interrupt mode (0-2) Bus* bus = nullptr; }; }
32.853175
95
0.662157
CasualPokePlayer
d54c20ec9dc935223a5f327662bd1c784436feac
1,635
cpp
C++
postfix.cpp
Madhuraaaaa/cpp-stl_assignments
9f59a5611251f4f0cf607fe0059e4ef29f025b99
[ "BSD-2-Clause" ]
null
null
null
postfix.cpp
Madhuraaaaa/cpp-stl_assignments
9f59a5611251f4f0cf607fe0059e4ef29f025b99
[ "BSD-2-Clause" ]
null
null
null
postfix.cpp
Madhuraaaaa/cpp-stl_assignments
9f59a5611251f4f0cf607fe0059e4ef29f025b99
[ "BSD-2-Clause" ]
null
null
null
#include <string> #include <list> #include <iterator> #include <iostream> #include <utility> #include <algorithm> #include <bits/stdc++.h> using namespace std; float getNum(char ch) { int value; value = ch; return float(value - '0'); } int isOperator(char ch) { if (ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '^') return 1; //character is an operator return -1; //not an operator } int Operand(char ch) { if (ch >= '0' && ch <= '9') return 1; //character is an operand return -1; //not an operand } float operation(int a, int b, char op) { //Perform operation if (op == '+') return b + a; else if (op == '-') return b - a; else if (op == '*') return b * a; else if (op == '/') return b / a; else if (op == '^') return pow(b, a); //find b^a else return INT_MIN; //return negative infinity } float postfix(string post) { int a, b; stack<float> s; string::iterator it; for (it = post.begin(); it != post.end(); it++) { //read elements and perform postfix evaluation if (isOperator(*it) != -1) { a = s.top(); s.pop(); b = s.top(); s.pop(); s.push(operation(a, b, *it)); } else if (Operand(*it) > 0) { s.push(getNum(*it)); } } return s.top(); } int main() { string post; cout << "Enter the expression: "; cin >> post; cout << "Output: " << postfix(post); }
22.708333
71
0.463609
Madhuraaaaa
d54c6c51db4162a649317d301150a6d43de97997
6,792
cpp
C++
Source/Urho3D/Graphics/OpenGL/OGLIndexBuffer.cpp
jayrulez/alimer-1
3b40798cbf21650ba37e9750dd24d8aa7efadf22
[ "MIT" ]
null
null
null
Source/Urho3D/Graphics/OpenGL/OGLIndexBuffer.cpp
jayrulez/alimer-1
3b40798cbf21650ba37e9750dd24d8aa7efadf22
[ "MIT" ]
null
null
null
Source/Urho3D/Graphics/OpenGL/OGLIndexBuffer.cpp
jayrulez/alimer-1
3b40798cbf21650ba37e9750dd24d8aa7efadf22
[ "MIT" ]
null
null
null
// // Copyright (c) 2008-2022 the Urho3D project. // Copyright (c) 2022 Amer Koleci and Contributors. // // 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 "../../Precompiled.h" #include "../../Core/Context.h" #include "../../Graphics/Graphics.h" #include "../../Graphics/GraphicsImpl.h" #include "../../Graphics/IndexBuffer.h" #include "../../IO/Log.h" #include "../../DebugNew.h" using namespace Urho3D; void IndexBuffer::OnDeviceLost() { if (object_.name_ && !graphics_->IsDeviceLost()) glDeleteBuffers(1, &object_.name_); GPUObject::OnDeviceLost(); } void IndexBuffer::OnDeviceReset() { if (!object_.name_) { Create(); dataLost_ = !UpdateToGPU(); } else if (dataPending_) dataLost_ = !UpdateToGPU(); dataPending_ = false; } void IndexBuffer::Release() { Unlock(); if (object_.name_) { if (!graphics_) return; if (!graphics_->IsDeviceLost()) { if (graphics_->GetIndexBuffer() == this) graphics_->SetIndexBuffer(nullptr); glDeleteBuffers(1, &object_.name_); } object_.name_ = 0; } } bool IndexBuffer::SetData(const void* data) { if (!data) { URHO3D_LOGERROR("Null pointer for index buffer data"); return false; } if (!indexSize_) { URHO3D_LOGERROR("Index size not defined, can not set index buffer data"); return false; } if (shadowData_ && data != shadowData_.Get()) memcpy(shadowData_.Get(), data, indexCount_ * (size_t)indexSize_); if (object_.name_) { if (!graphics_->IsDeviceLost()) { graphics_->SetIndexBuffer(this); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexCount_ * (size_t)indexSize_, data, dynamic_ ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW); } else { URHO3D_LOGWARNING("Index buffer data assignment while device is lost"); dataPending_ = true; } } dataLost_ = false; return true; } bool IndexBuffer::SetDataRange(const void* data, unsigned start, unsigned count, bool discard) { if (start == 0 && count == indexCount_) return SetData(data); if (!data) { URHO3D_LOGERROR("Null pointer for index buffer data"); return false; } if (!indexSize_) { URHO3D_LOGERROR("Index size not defined, can not set index buffer data"); return false; } if (start + count > indexCount_) { URHO3D_LOGERROR("Illegal range for setting new index buffer data"); return false; } if (!count) return true; if (shadowData_ && shadowData_.Get() + start * indexSize_ != data) memcpy(shadowData_.Get() + start * indexSize_, data, count * (size_t)indexSize_); if (object_.name_) { if (!graphics_->IsDeviceLost()) { graphics_->SetIndexBuffer(this); if (!discard || start != 0) glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, start * (size_t)indexSize_, count * indexSize_, data); else glBufferData(GL_ELEMENT_ARRAY_BUFFER, count * (size_t)indexSize_, data, dynamic_ ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW); } else { URHO3D_LOGWARNING("Index buffer data assignment while device is lost"); dataPending_ = true; } } return true; } void* IndexBuffer::Lock(unsigned start, unsigned count, bool discard) { if (lockState_ != LOCK_NONE) { URHO3D_LOGERROR("Index buffer already locked"); return nullptr; } if (!indexSize_) { URHO3D_LOGERROR("Index size not defined, can not lock index buffer"); return nullptr; } if (start + count > indexCount_) { URHO3D_LOGERROR("Illegal range for locking index buffer"); return nullptr; } if (!count) return nullptr; lockStart_ = start; lockCount_ = count; discardLock_ = discard; if (shadowData_) { lockState_ = LOCK_SHADOW; return shadowData_.Get() + start * indexSize_; } else if (graphics_) { lockState_ = LOCK_SCRATCH; lockScratchData_ = graphics_->ReserveScratchBuffer(count * indexSize_); return lockScratchData_; } else return nullptr; } void IndexBuffer::Unlock() { switch (lockState_) { case LOCK_SHADOW: SetDataRange(shadowData_.Get() + lockStart_ * indexSize_, lockStart_, lockCount_, discardLock_); lockState_ = LOCK_NONE; break; case LOCK_SCRATCH: SetDataRange(lockScratchData_, lockStart_, lockCount_, discardLock_); if (graphics_) graphics_->FreeScratchBuffer(lockScratchData_); lockScratchData_ = nullptr; lockState_ = LOCK_NONE; break; default: break; } } bool IndexBuffer::Create() { if (!indexCount_) { Release(); return true; } if (graphics_) { if (graphics_->IsDeviceLost()) { URHO3D_LOGWARNING("Index buffer creation while device is lost"); return true; } if (!object_.name_) glGenBuffers(1, &object_.name_); if (!object_.name_) { URHO3D_LOGERROR("Failed to create index buffer"); return false; } graphics_->SetIndexBuffer(this); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexCount_ * (size_t)indexSize_, nullptr, dynamic_ ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW); } return true; } bool IndexBuffer::UpdateToGPU() { if (object_.name_ && shadowData_) return SetData(shadowData_.Get()); return false; }
25.727273
135
0.621614
jayrulez
d54e440cad08caecca7304e137df4779b98b0b64
10,030
hpp
C++
DiligentCore/Graphics/GraphicsEngineVulkan/include/ShaderVariableVk.hpp
Romanovich1311/DEngine-pcsx4
65d28b15e9428d77963de95412aaceeb5930d29d
[ "Apache-2.0" ]
15
2021-07-03T17:20:50.000Z
2022-03-20T23:39:09.000Z
DiligentCore/Graphics/GraphicsEngineVulkan/include/ShaderVariableVk.hpp
Romanovich1311/DEngine-pcsx4
65d28b15e9428d77963de95412aaceeb5930d29d
[ "Apache-2.0" ]
1
2021-08-09T15:10:17.000Z
2021-09-30T06:47:04.000Z
DiligentCore/Graphics/GraphicsEngineVulkan/include/ShaderVariableVk.hpp
Romanovich1311/DEngine-pcsx4
65d28b15e9428d77963de95412aaceeb5930d29d
[ "Apache-2.0" ]
9
2021-07-21T10:53:59.000Z
2022-03-03T10:27:33.000Z
/* * Copyright 2019-2020 Diligent Graphics LLC * Copyright 2015-2019 Egor Yusov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * In no event and under no legal theory, whether in tort (including negligence), * contract, or otherwise, unless required by applicable law (such as deliberate * and grossly negligent acts) or agreed to in writing, shall any Contributor be * liable for any damages, including any direct, indirect, special, incidental, * or consequential damages of any character arising as a result of this License or * out of the use or inability to use the software (including but not limited to damages * for loss of goodwill, work stoppage, computer failure or malfunction, or any and * all other commercial damages or losses), even if such Contributor has been advised * of the possibility of such damages. */ #pragma once /// \file /// Declaration of Diligent::ShaderVariableManagerVk and Diligent::ShaderVariableVkImpl classes // // * ShaderVariableManagerVk keeps list of variables of specific types // * Every ShaderVariableVkImpl references VkResource from ShaderResourceLayoutVk // * ShaderVariableManagerVk keeps reference to ShaderResourceCacheVk // * ShaderVariableManagerVk is used by PipelineStateVkImpl to manage static resources and by // ShaderResourceBindingVkImpl to manage mutable and dynamic resources // // __________________________ __________________________________________________________________________ // | | | | | | // .----| ShaderVariableManagerVk |---------------->| ShaderVariableVkImpl[0] | ShaderVariableVkImpl[1] | ... | // | |__________________________| |___________________________|____________________________|_________________| // | \ | // | Ref Ref // | \ | // | ___________________________ ______________________V_______________________V____________________________ // | | | unique_ptr | | | | | // | | ShaderResourceLayoutVk |--------------->| VkResource[0] | VkResource[1] | ... | VkResource[s+m+d-1] | // | |___________________________| |___________________|_________________|_______________|_____________________| // | | | // | | | // | | (DescriptorSet, CacheOffset) / (DescriptorSet, CacheOffset) // | \ / // | __________________________ ________V_______________________________________________________V_______ // | | | | | // '--->| ShaderResourceCacheVk |---------------->| Resources | // |__________________________| |________________________________________________________________________| // // #include <memory> #include "ShaderResourceLayoutVk.hpp" #include "ShaderResourceVariableBase.hpp" namespace Diligent { class ShaderVariableVkImpl; // sizeof(ShaderVariableManagerVk) == 32 (x64, msvc, Release) class ShaderVariableManagerVk { public: ShaderVariableManagerVk(IObject& Owner, const ShaderResourceLayoutVk& SrcLayout, IMemoryAllocator& Allocator, const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, Uint32 NumAllowedTypes, ShaderResourceCacheVk& ResourceCache); ~ShaderVariableManagerVk(); void DestroyVariables(IMemoryAllocator& Allocator); ShaderVariableVkImpl* GetVariable(const Char* Name); ShaderVariableVkImpl* GetVariable(Uint32 Index); void BindResources(IResourceMapping* pResourceMapping, Uint32 Flags); static size_t GetRequiredMemorySize(const ShaderResourceLayoutVk& Layout, const SHADER_RESOURCE_VARIABLE_TYPE* AllowedVarTypes, Uint32 NumAllowedTypes, Uint32& NumVariables); Uint32 GetVariableCount() const { return m_NumVariables; } private: friend ShaderVariableVkImpl; Uint32 GetVariableIndex(const ShaderVariableVkImpl& Variable); IObject& m_Owner; // Variable mgr is owned by either Pipeline state object (in which case m_ResourceCache references // static resource cache owned by the same PSO object), or by SRB object (in which case // m_ResourceCache references the cache in the SRB). Thus the cache and the resource layout // (which the variables reference) are guaranteed to be alive while the manager is alive. ShaderResourceCacheVk& m_ResourceCache; // Memory is allocated through the allocator provided by the pipeline state. If allocation granularity > 1, fixed block // memory allocator is used. This ensures that all resources from different shader resource bindings reside in // continuous memory. If allocation granularity == 1, raw allocator is used. ShaderVariableVkImpl* m_pVariables = nullptr; Uint32 m_NumVariables = 0; #ifdef _DEBUG IMemoryAllocator& m_DbgAllocator; #endif }; // sizeof(ShaderVariableVkImpl) == 24 (x64) class ShaderVariableVkImpl final : public IShaderResourceVariable { public: ShaderVariableVkImpl(ShaderVariableManagerVk& ParentManager, const ShaderResourceLayoutVk::VkResource& Resource) : m_ParentManager{ParentManager}, m_Resource{Resource} {} // clang-format off ShaderVariableVkImpl (const ShaderVariableVkImpl&) = delete; ShaderVariableVkImpl (ShaderVariableVkImpl&&) = delete; ShaderVariableVkImpl& operator= (const ShaderVariableVkImpl&) = delete; ShaderVariableVkImpl& operator= (ShaderVariableVkImpl&&) = delete; // clang-format on virtual IReferenceCounters* DILIGENT_CALL_TYPE GetReferenceCounters() const override final { return m_ParentManager.m_Owner.GetReferenceCounters(); } virtual Atomics::Long DILIGENT_CALL_TYPE AddRef() override final { return m_ParentManager.m_Owner.AddRef(); } virtual Atomics::Long DILIGENT_CALL_TYPE Release() override final { return m_ParentManager.m_Owner.Release(); } void DILIGENT_CALL_TYPE QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface) override final { if (ppInterface == nullptr) return; *ppInterface = nullptr; if (IID == IID_ShaderResourceVariable || IID == IID_Unknown) { *ppInterface = this; (*ppInterface)->AddRef(); } } virtual SHADER_RESOURCE_VARIABLE_TYPE DILIGENT_CALL_TYPE GetType() const override final { return m_Resource.GetVariableType(); } virtual void DILIGENT_CALL_TYPE Set(IDeviceObject* pObject) override final { m_Resource.BindResource(pObject, 0, m_ParentManager.m_ResourceCache); } virtual void DILIGENT_CALL_TYPE SetArray(IDeviceObject* const* ppObjects, Uint32 FirstElement, Uint32 NumElements) override final { VerifyAndCorrectSetArrayArguments(m_Resource.SpirvAttribs.Name, m_Resource.SpirvAttribs.ArraySize, FirstElement, NumElements); for (Uint32 Elem = 0; Elem < NumElements; ++Elem) m_Resource.BindResource(ppObjects[Elem], FirstElement + Elem, m_ParentManager.m_ResourceCache); } virtual void DILIGENT_CALL_TYPE GetResourceDesc(ShaderResourceDesc& ResourceDesc) const override final { ResourceDesc = m_Resource.SpirvAttribs.GetResourceDesc(); } virtual Uint32 DILIGENT_CALL_TYPE GetIndex() const override final { return m_ParentManager.GetVariableIndex(*this); } virtual bool DILIGENT_CALL_TYPE IsBound(Uint32 ArrayIndex) const override final { return m_Resource.IsBound(ArrayIndex, m_ParentManager.m_ResourceCache); } const ShaderResourceLayoutVk::VkResource& GetResource() const { return m_Resource; } private: friend ShaderVariableManagerVk; ShaderVariableManagerVk& m_ParentManager; const ShaderResourceLayoutVk::VkResource& m_Resource; }; } // namespace Diligent
46.651163
153
0.599103
Romanovich1311
d55032be19d49e5bb97540a93d2e4e0fdd88f005
20,399
cpp
C++
gpu/kinfu/src/kinfu.cpp
zhangxaochen/CuFusion
e8bab7a366b1f2c85a80b95093d195d9f0774c11
[ "MIT" ]
52
2017-09-05T13:31:44.000Z
2022-03-14T08:48:29.000Z
gpu/kinfu/src/kinfu.cpp
GucciPrada/CuFusion
522920bcf316d1ddf9732fc71fa457174168d2fb
[ "MIT" ]
4
2018-05-17T22:45:35.000Z
2020-02-01T21:46:42.000Z
gpu/kinfu/src/kinfu.cpp
GucciPrada/CuFusion
522920bcf316d1ddf9732fc71fa457174168d2fb
[ "MIT" ]
21
2015-07-27T13:00:36.000Z
2022-01-17T08:18:41.000Z
/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2011, Willow Garage, Inc. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ #include <iostream> #include <algorithm> #include <pcl/common/time.h> #include <pcl/gpu/kinfu/kinfu.h> #include "internal.h" #include <Eigen/Core> #include <Eigen/SVD> #include <Eigen/Cholesky> #include <Eigen/Geometry> #include <Eigen/LU> #ifdef HAVE_OPENCV #include <opencv2/opencv.hpp> #include <opencv2/gpu/gpu.hpp> #include <pcl/gpu/utils/timers_opencv.hpp> #endif using namespace std; using namespace pcl::device; using namespace pcl::gpu; using Eigen::AngleAxisf; using Eigen::Array3f; using Eigen::Vector3i; using Eigen::Vector3f; namespace pcl { namespace gpu { Eigen::Vector3f rodrigues2(const Eigen::Matrix3f& matrix); } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// pcl::gpu::KinfuTracker::KinfuTracker (int rows, int cols) : rows_(rows), cols_(cols), global_time_(0), max_icp_distance_(0), integration_metric_threshold_(0.f) { const Vector3f volume_size = Vector3f::Constant (VOLUME_SIZE); const Vector3i volume_resolution(VOLUME_X, VOLUME_Y, VOLUME_Z); tsdf_volume_ = TsdfVolume::Ptr( new TsdfVolume(volume_resolution) ); tsdf_volume_->setSize(volume_size); setDepthIntrinsics (525.f, 525.f); // default values, can be overwritten init_Rcam_ = Eigen::Matrix3f::Identity ();// * AngleAxisf(-30.f/180*3.1415926, Vector3f::UnitX()); init_tcam_ = volume_size * 0.5f - Vector3f (0, 0, volume_size (2) / 2 * 1.2f); const int iters[] = {10, 5, 4}; std::copy (iters, iters + LEVELS, icp_iterations_); const float default_distThres = 0.10f; //meters const float default_angleThres = sin (20.f * 3.14159254f / 180.f); const float default_tranc_dist = 0.03f; //meters setIcpCorespFilteringParams (default_distThres, default_angleThres); tsdf_volume_->setTsdfTruncDist (default_tranc_dist); allocateBufffers (rows, cols); rmats_.reserve (30000); tvecs_.reserve (30000); reset (); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void pcl::gpu::KinfuTracker::setDepthIntrinsics (float fx, float fy, float cx, float cy) { fx_ = fx; fy_ = fy; cx_ = (cx == -1) ? cols_/2-0.5f : cx; cy_ = (cy == -1) ? rows_/2-0.5f : cy; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void pcl::gpu::KinfuTracker::setInitalCameraPose (const Eigen::Affine3f& pose) { init_Rcam_ = pose.rotation (); init_tcam_ = pose.translation (); reset (); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void pcl::gpu::KinfuTracker::setDepthTruncationForICP (float max_icp_distance) { max_icp_distance_ = max_icp_distance; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void pcl::gpu::KinfuTracker::setCameraMovementThreshold(float threshold) { integration_metric_threshold_ = threshold; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void pcl::gpu::KinfuTracker::setIcpCorespFilteringParams (float distThreshold, float sineOfAngle) { distThres_ = distThreshold; //mm angleThres_ = sineOfAngle; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// int pcl::gpu::KinfuTracker::cols () { return (cols_); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// int pcl::gpu::KinfuTracker::rows () { return (rows_); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void pcl::gpu::KinfuTracker::reset() { if (global_time_) cout << "Reset" << endl; global_time_ = 0; rmats_.clear (); tvecs_.clear (); rmats_.push_back (init_Rcam_); tvecs_.push_back (init_tcam_); tsdf_volume_->reset(); if (color_volume_) // color integration mode is enabled color_volume_->reset(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void pcl::gpu::KinfuTracker::allocateBufffers (int rows, int cols) { depths_curr_.resize (LEVELS); vmaps_g_curr_.resize (LEVELS); nmaps_g_curr_.resize (LEVELS); vmaps_g_prev_.resize (LEVELS); nmaps_g_prev_.resize (LEVELS); vmaps_curr_.resize (LEVELS); nmaps_curr_.resize (LEVELS); coresps_.resize (LEVELS); for (int i = 0; i < LEVELS; ++i) { int pyr_rows = rows >> i; int pyr_cols = cols >> i; depths_curr_[i].create (pyr_rows, pyr_cols); vmaps_g_curr_[i].create (pyr_rows*3, pyr_cols); nmaps_g_curr_[i].create (pyr_rows*3, pyr_cols); vmaps_g_prev_[i].create (pyr_rows*3, pyr_cols); nmaps_g_prev_[i].create (pyr_rows*3, pyr_cols); vmaps_curr_[i].create (pyr_rows*3, pyr_cols); nmaps_curr_[i].create (pyr_rows*3, pyr_cols); coresps_[i].create (pyr_rows, pyr_cols); } depthRawScaled_.create (rows, cols); // see estimate tranform for the magic numbers gbuf_.create (27, 20*60); sumbuf_.create (27); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool pcl::gpu::KinfuTracker::operator() (const DepthMap& depth_raw) { device::Intr intr (fx_, fy_, cx_, cy_); { //ScopeTime time(">>> Bilateral, pyr-down-all, create-maps-all"); //depth_raw.copyTo(depths_curr[0]); device::bilateralFilter (depth_raw, depths_curr_[0]); if (max_icp_distance_ > 0) device::truncateDepth(depths_curr_[0], max_icp_distance_); for (int i = 1; i < LEVELS; ++i) device::pyrDown (depths_curr_[i-1], depths_curr_[i]); for (int i = 0; i < LEVELS; ++i) { device::createVMap (intr(i), depths_curr_[i], vmaps_curr_[i]); //device::createNMap(vmaps_curr_[i], nmaps_curr_[i]); computeNormalsEigen (vmaps_curr_[i], nmaps_curr_[i]); } pcl::device::sync (); } //can't perform more on first frame if (global_time_ == 0) { Matrix3frm init_Rcam = rmats_[0]; // [Ri|ti] - pos of camera, i.e. Vector3f init_tcam = tvecs_[0]; // transform from camera to global coo space for (i-1)th camera pose Mat33& device_Rcam = device_cast<Mat33> (init_Rcam); float3& device_tcam = device_cast<float3>(init_tcam); Matrix3frm init_Rcam_inv = init_Rcam.inverse (); Mat33& device_Rcam_inv = device_cast<Mat33> (init_Rcam_inv); float3 device_volume_size = device_cast<const float3>(tsdf_volume_->getSize()); //integrateTsdfVolume(depth_raw, intr, device_volume_size, device_Rcam_inv, device_tcam, tranc_dist, volume_); device::integrateTsdfVolume(depth_raw, intr, device_volume_size, device_Rcam_inv, device_tcam, tsdf_volume_->getTsdfTruncDist(), tsdf_volume_->data(), depthRawScaled_); for (int i = 0; i < LEVELS; ++i) device::tranformMaps (vmaps_curr_[i], nmaps_curr_[i], device_Rcam, device_tcam, vmaps_g_prev_[i], nmaps_g_prev_[i]); ++global_time_; return (false); } /////////////////////////////////////////////////////////////////////////////////////////// // Iterative Closest Point Matrix3frm Rprev = rmats_[global_time_ - 1]; // [Ri|ti] - pos of camera, i.e. Vector3f tprev = tvecs_[global_time_ - 1]; // tranfrom from camera to global coo space for (i-1)th camera pose Matrix3frm Rprev_inv = Rprev.inverse (); //Rprev.t(); //Mat33& device_Rprev = device_cast<Mat33> (Rprev); Mat33& device_Rprev_inv = device_cast<Mat33> (Rprev_inv); float3& device_tprev = device_cast<float3> (tprev); Matrix3frm Rcurr = Rprev; // tranform to global coo for ith camera pose Vector3f tcurr = tprev; { //ScopeTime time("icp-all"); for (int level_index = LEVELS-1; level_index>=0; --level_index) { int iter_num = icp_iterations_[level_index]; MapArr& vmap_curr = vmaps_curr_[level_index]; MapArr& nmap_curr = nmaps_curr_[level_index]; //MapArr& vmap_g_curr = vmaps_g_curr_[level_index]; //MapArr& nmap_g_curr = nmaps_g_curr_[level_index]; MapArr& vmap_g_prev = vmaps_g_prev_[level_index]; MapArr& nmap_g_prev = nmaps_g_prev_[level_index]; //CorespMap& coresp = coresps_[level_index]; for (int iter = 0; iter < iter_num; ++iter) { Mat33& device_Rcurr = device_cast<Mat33> (Rcurr); float3& device_tcurr = device_cast<float3>(tcurr); Eigen::Matrix<double, 6, 6, Eigen::RowMajor> A; Eigen::Matrix<double, 6, 1> b; #if 0 device::tranformMaps(vmap_curr, nmap_curr, device_Rcurr, device_tcurr, vmap_g_curr, nmap_g_curr); findCoresp(vmap_g_curr, nmap_g_curr, device_Rprev_inv, device_tprev, intr(level_index), vmap_g_prev, nmap_g_prev, distThres_, angleThres_, coresp); device::estimateTransform(vmap_g_prev, nmap_g_prev, vmap_g_curr, coresp, gbuf_, sumbuf_, A.data(), b.data()); //cv::gpu::GpuMat ma(coresp.rows(), coresp.cols(), CV_32S, coresp.ptr(), coresp.step()); //cv::Mat cpu; //ma.download(cpu); //cv::imshow(names[level_index] + string(" --- coresp white == -1"), cpu == -1); #else estimateCombined (device_Rcurr, device_tcurr, vmap_curr, nmap_curr, device_Rprev_inv, device_tprev, intr (level_index), vmap_g_prev, nmap_g_prev, distThres_, angleThres_, gbuf_, sumbuf_, A.data (), b.data ()); #endif //checking nullspace double det = A.determinant (); if (fabs (det) < 1e-15 || pcl_isnan (det)) { if (pcl_isnan (det)) cout << "qnan" << endl; reset (); return (false); } //float maxc = A.maxCoeff(); Eigen::Matrix<float, 6, 1> result = A.llt ().solve (b).cast<float>(); //Eigen::Matrix<float, 6, 1> result = A.jacobiSvd(ComputeThinU | ComputeThinV).solve(b); float alpha = result (0); float beta = result (1); float gamma = result (2); Eigen::Matrix3f Rinc = (Eigen::Matrix3f)AngleAxisf (gamma, Vector3f::UnitZ ()) * AngleAxisf (beta, Vector3f::UnitY ()) * AngleAxisf (alpha, Vector3f::UnitX ()); Vector3f tinc = result.tail<3> (); //compose tcurr = Rinc * tcurr + tinc; Rcurr = Rinc * Rcurr; } } } //save tranform rmats_.push_back (Rcurr); tvecs_.push_back (tcurr); /////////////////////////////////////////////////////////////////////////////////////////// // Integration check - We do not integrate volume if camera does not move. float rnorm = rodrigues2(Rcurr.inverse() * Rprev).norm(); float tnorm = (tcurr - tprev).norm(); const float alpha = 1.f; bool integrate = (rnorm + alpha * tnorm)/2 >= integration_metric_threshold_; /////////////////////////////////////////////////////////////////////////////////////////// // Volume integration float3 device_volume_size = device_cast<const float3> (tsdf_volume_->getSize()); Matrix3frm Rcurr_inv = Rcurr.inverse (); Mat33& device_Rcurr_inv = device_cast<Mat33> (Rcurr_inv); float3& device_tcurr = device_cast<float3> (tcurr); if (integrate) { //ScopeTime time("tsdf"); //integrateTsdfVolume(depth_raw, intr, device_volume_size, device_Rcurr_inv, device_tcurr, tranc_dist, volume_); integrateTsdfVolume (depth_raw, intr, device_volume_size, device_Rcurr_inv, device_tcurr, tsdf_volume_->getTsdfTruncDist(), tsdf_volume_->data(), depthRawScaled_); } /////////////////////////////////////////////////////////////////////////////////////////// // Ray casting Mat33& device_Rcurr = device_cast<Mat33> (Rcurr); { //ScopeTime time("ray-cast-all"); raycast (intr, device_Rcurr, device_tcurr, tsdf_volume_->getTsdfTruncDist(), device_volume_size, tsdf_volume_->data(), vmaps_g_prev_[0], nmaps_g_prev_[0]); for (int i = 1; i < LEVELS; ++i) { resizeVMap (vmaps_g_prev_[i-1], vmaps_g_prev_[i]); resizeNMap (nmaps_g_prev_[i-1], nmaps_g_prev_[i]); } pcl::device::sync (); } ++global_time_; return (true); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Eigen::Affine3f pcl::gpu::KinfuTracker::getCameraPose (int time) const { if (time > (int)rmats_.size () || time < 0) time = rmats_.size () - 1; Eigen::Affine3f aff; aff.linear () = rmats_[time]; aff.translation () = tvecs_[time]; return (aff); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// size_t pcl::gpu::KinfuTracker::getNumberOfPoses () const { return rmats_.size(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// const TsdfVolume& pcl::gpu::KinfuTracker::volume() const { return *tsdf_volume_; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// TsdfVolume& pcl::gpu::KinfuTracker::volume() { return *tsdf_volume_; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// const ColorVolume& pcl::gpu::KinfuTracker::colorVolume() const { return *color_volume_; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ColorVolume& pcl::gpu::KinfuTracker::colorVolume() { return *color_volume_; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void pcl::gpu::KinfuTracker::getImage (View& view) const { //Eigen::Vector3f light_source_pose = tsdf_volume_->getSize() * (-3.f); Eigen::Vector3f light_source_pose = tvecs_[tvecs_.size () - 1]; device::LightSource light; light.number = 1; light.pos[0] = device_cast<const float3>(light_source_pose); view.create (rows_, cols_); generateImage (vmaps_g_prev_[0], nmaps_g_prev_[0], light, view); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void pcl::gpu::KinfuTracker::getLastFrameCloud (DeviceArray2D<PointType>& cloud) const { cloud.create (rows_, cols_); DeviceArray2D<float4>& c = (DeviceArray2D<float4>&)cloud; device::convert (vmaps_g_prev_[0], c); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void pcl::gpu::KinfuTracker::getLastFrameNormals (DeviceArray2D<NormalType>& normals) const { normals.create (rows_, cols_); DeviceArray2D<float8>& n = (DeviceArray2D<float8>&)normals; device::convert (nmaps_g_prev_[0], n); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void pcl::gpu::KinfuTracker::initColorIntegration(int max_weight) { color_volume_ = pcl::gpu::ColorVolume::Ptr( new ColorVolume(*tsdf_volume_, max_weight) ); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool pcl::gpu::KinfuTracker::operator() (const DepthMap& depth, const View& colors) { bool res = (*this)(depth); if (res && color_volume_) { const float3 device_volume_size = device_cast<const float3> (tsdf_volume_->getSize()); device::Intr intr(fx_, fy_, cx_, cy_); Matrix3frm R_inv = rmats_.back().inverse(); Vector3f t = tvecs_.back(); Mat33& device_Rcurr_inv = device_cast<Mat33> (R_inv); float3& device_tcurr = device_cast<float3> (t); device::updateColorVolume(intr, tsdf_volume_->getTsdfTruncDist(), device_Rcurr_inv, device_tcurr, vmaps_g_prev_[0], colors, device_volume_size, color_volume_->data(), color_volume_->getMaxWeight()); } return res; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace pcl { namespace gpu { PCL_EXPORTS void paint3DView(const KinfuTracker::View& rgb24, KinfuTracker::View& view, float colors_weight = 0.5f) { device::paint3DView(rgb24, view, colors_weight); } PCL_EXPORTS void mergePointNormal(const DeviceArray<PointXYZ>& cloud, const DeviceArray<Normal>& normals, DeviceArray<PointNormal>& output) { const size_t size = min(cloud.size(), normals.size()); output.create(size); const DeviceArray<float4>& c = (const DeviceArray<float4>&)cloud; const DeviceArray<float8>& n = (const DeviceArray<float8>&)normals; const DeviceArray<float12>& o = (const DeviceArray<float12>&)output; device::mergePointNormal(c, n, o); } Eigen::Vector3f rodrigues2(const Eigen::Matrix3f& matrix) { Eigen::JacobiSVD<Eigen::Matrix3f> svd(matrix, Eigen::ComputeFullV | Eigen::ComputeFullU); Eigen::Matrix3f R = svd.matrixU() * svd.matrixV().transpose(); double rx = R(2, 1) - R(1, 2); double ry = R(0, 2) - R(2, 0); double rz = R(1, 0) - R(0, 1); double s = sqrt((rx*rx + ry*ry + rz*rz)*0.25); double c = (R.trace() - 1) * 0.5; c = c > 1. ? 1. : c < -1. ? -1. : c; double theta = acos(c); if( s < 1e-5 ) { double t; if( c > 0 ) rx = ry = rz = 0; else { t = (R(0, 0) + 1)*0.5; rx = sqrt( std::max(t, 0.0) ); t = (R(1, 1) + 1)*0.5; ry = sqrt( std::max(t, 0.0) ) * (R(0, 1) < 0 ? -1.0 : 1.0); t = (R(2, 2) + 1)*0.5; rz = sqrt( std::max(t, 0.0) ) * (R(0, 2) < 0 ? -1.0 : 1.0); if( fabs(rx) < fabs(ry) && fabs(rx) < fabs(rz) && (R(1, 2) > 0) != (ry*rz > 0) ) rz = -rz; theta /= sqrt(rx*rx + ry*ry + rz*rz); rx *= theta; ry *= theta; rz *= theta; } } else { double vth = 1/(2*s); vth *= theta; rx *= vth; ry *= vth; rz *= vth; } return Eigen::Vector3d(rx, ry, rz).cast<float>(); } } }
35.353553
173
0.544831
zhangxaochen
d5530d9a9c22dbf92bb732ee867c2a22be3809cd
2,656
cpp
C++
libsrc/gmsg/GMsg_AgentLogin.cpp
christywear/UlServer
44d090ab266f7de0096b8f55c0906f21522243ff
[ "BSD-3-Clause" ]
5
2018-08-17T17:16:50.000Z
2019-07-01T12:54:01.000Z
libsrc/gmsg/GMsg_AgentLogin.cpp
christywear/UlServer
44d090ab266f7de0096b8f55c0906f21522243ff
[ "BSD-3-Clause" ]
2
2019-01-06T15:32:09.000Z
2019-01-18T06:03:26.000Z
libsrc/gmsg/GMsg_AgentLogin.cpp
christywear/UlServer
44d090ab266f7de0096b8f55c0906f21522243ff
[ "BSD-3-Clause" ]
4
2018-08-16T15:41:15.000Z
2020-06-22T06:09:10.000Z
// GMsg_AgentLogin.cpp -*- C++ -*- // $Id: GMsg_AgentLogin.cpp,v 1.1 1997-10-15 16:22:40-07 jason Exp $ // Copyright 1996-1997 Lyra LLC, All rights reserved. // // message implementation #ifdef __GNUC__ #pragma implementation "GMsg_AgentLogin.h" #endif #ifdef WIN32 #define STRICT #include "unix.h" #include <winsock2.h> #else /* !WIN32 */ #include <sys/types.h> #include <netinet/in.h> #endif /* WIN32 */ #include <stdio.h> #include <string.h> #include "GMsg_AgentLogin.h" #include "LyraDefs.h" #include "GMsg.h" #ifndef USE_INLINE #include "GMsg_AgentLogin.i" #endif //// // constructor //// GMsg_AgentLogin::GMsg_AgentLogin() : LmMesg(GMsg::AGENTLOGIN, sizeof(data_t), sizeof(data_t), &data_) { // initialize default message data values Init(DEFAULT_VERSION, _T("name"), Lyra::PORT_UNKNOWN, 0, 0); } //// // destructor //// GMsg_AgentLogin::~GMsg_AgentLogin() { // empty } //// // Init //// void GMsg_AgentLogin::Init(int version, const TCHAR* playername, int serv_port, lyra_id_t billing_id, short tcp_only) { SetVersion(version); SetPlayerName(playername); SetServerPort(serv_port); SetBillingID(billing_id); SetTCPOnly(tcp_only); } //// // hton //// void GMsg_AgentLogin::hton() { HTONL(data_.version); HTONL(data_.serv_port); HTONL(data_.billing_id); HTONS( data_.tcp_only ); // no conversion: playername, hash } //// // ntoh //// void GMsg_AgentLogin::ntoh() { NTOHL(data_.version); NTOHL(data_.serv_port); NTOHL(data_.billing_id); NTOHS(data_.tcp_only); // no conversion: playername, hash } //// // Dump: print to FILE stream //// #ifdef USE_DEBUG void GMsg_AgentLogin::Dump(FILE* f, int indent) const { INDENT(indent, f); _ftprintf(f, _T("<GMsg_AgentLogin[%p,%d]: "), this, sizeof(GMsg_AgentLogin)); if (ByteOrder() == ByteOrder::HOST) { _ftprintf(f, _T("billing_id=%u version=%d name='%s' hash=<NOT PRINTED> servport=%d tcp_only=%d>\n"), BillingID(), Version(), PlayerName(), ServerPort(), TCPOnly()); } else { _ftprintf(f, _T("(network order)>\n")); } // print out base class LmMesg::Dump(f, indent + 1); } #endif /* USE_DEBUG */ //// // SetPlayerName //// void GMsg_AgentLogin::SetPlayerName(const TCHAR* playername) { _tcsnccpy(data_.playername, playername, sizeof(data_.playername)); TRUNC(data_.playername, sizeof(data_.playername)); } /* void GMsg_AgentLogin::SetPassword(const TCHAR* password) { _tcsnccpy(data_.password, password, sizeof(data_.password)); TRUNC(data_.password, sizeof(data_.password)); } */ //// // SetHash //// void GMsg_AgentLogin::SetHash(const MD5Hash_t hash) { memcpy((void*)data_.hash, (void*)hash, sizeof(MD5Hash_t)); }
19.529412
117
0.685617
christywear
d5588e303c843a470e2b922deb092e0defc42bae
1,933
hpp
C++
worker/include/RTC/RemoteBitrateEstimator/OveruseDetector.hpp
maytrue/mediasoup
11c0ae83d8cb0e238c91bc43132825a7bafcba80
[ "ISC" ]
13
2018-04-04T18:53:19.000Z
2021-07-16T00:18:27.000Z
worker/include/RTC/RemoteBitrateEstimator/OveruseDetector.hpp
maytrue/mediasoup
11c0ae83d8cb0e238c91bc43132825a7bafcba80
[ "ISC" ]
3
2019-04-23T18:30:03.000Z
2020-09-18T23:41:03.000Z
worker/include/RTC/RemoteBitrateEstimator/OveruseDetector.hpp
maytrue/mediasoup
11c0ae83d8cb0e238c91bc43132825a7bafcba80
[ "ISC" ]
3
2018-06-19T23:01:40.000Z
2020-04-01T13:30:58.000Z
/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #ifndef MS_RTC_REMOTE_BITRATE_ESTIMATOR_OVERUSE_DETECTOR_HPP #define MS_RTC_REMOTE_BITRATE_ESTIMATOR_OVERUSE_DETECTOR_HPP #include "common.hpp" #include "RTC/RemoteBitrateEstimator/BandwidthUsage.hpp" #include "RTC/RemoteBitrateEstimator/RateControlRegion.hpp" #include <list> namespace RTC { class OveruseDetector { private: static constexpr double OverUsingTimeThreshold{ 10 }; public: OveruseDetector() = default; // Update the detection state based on the estimated inter-arrival time delta // offset. |timestampDelta| is the delta between the last timestamp which the // estimated offset is based on and the last timestamp on which the last // offset was based on, representing the time between detector updates. // |numOfDeltas| is the number of deltas the offset estimate is based on. // Returns the state after the detection update. BandwidthUsage Detect(double offset, double tsDelta, int numOfDeltas, int64_t nowMs); // Returns the current detector state. BandwidthUsage State() const; private: void UpdateThreshold(double modifiedOffset, int64_t nowMs); private: double up{ 0.0087 }; double down{ 0.039 }; double overusingTimeThreshold{ OverUsingTimeThreshold }; double threshold{ 12.5 }; int64_t lastUpdateMs{ -1 }; double prevOffset{ 0.0 }; double timeOverUsing{ -1 }; int overuseCounter{ 0 }; BandwidthUsage hypothesis{ BW_NORMAL }; }; inline BandwidthUsage OveruseDetector::State() const { return this->hypothesis; } } // namespace RTC #endif
32.216667
87
0.758924
maytrue
d55a44b0d526da6c3e63d14a9936592c6c799dcb
322
cpp
C++
HHKBPC2020/TaskA.cpp
zhouyium/AtCoder
af66b02dc1faa317879d9a85d2458a009bef6dbd
[ "MIT" ]
null
null
null
HHKBPC2020/TaskA.cpp
zhouyium/AtCoder
af66b02dc1faa317879d9a85d2458a009bef6dbd
[ "MIT" ]
null
null
null
HHKBPC2020/TaskA.cpp
zhouyium/AtCoder
af66b02dc1faa317879d9a85d2458a009bef6dbd
[ "MIT" ]
null
null
null
//https://atcoder.jp/contests/hhkb2020/tasks/hhkb2020_a //HHKB Programming Contest 2020 //A - Keyboard #include <iostream> using namespace std; int main() { char s; char ch; cin>>s>>ch; if ('Y'==s) { cout<<(char)(ch-32); } else { cout<<ch; } cout<<"\n"; return 0; }
14.636364
55
0.540373
zhouyium
d55c222fd9d0f1a1615e2fb88b5111b14ef6951d
20,077
cpp
C++
SpecularAA 2/SampleFramework11/GraphicsTypes.cpp
TheRealMJP/SpecularAA
d8e8e3ce2ec2208f6d1eeee8c2f4f06e8a7b1b68
[ "MIT" ]
71
2018-05-13T00:40:42.000Z
2022-03-23T21:16:07.000Z
SpecularAA 2/SampleFramework11/GraphicsTypes.cpp
TheRealMJP/SpecularAA
d8e8e3ce2ec2208f6d1eeee8c2f4f06e8a7b1b68
[ "MIT" ]
null
null
null
SpecularAA 2/SampleFramework11/GraphicsTypes.cpp
TheRealMJP/SpecularAA
d8e8e3ce2ec2208f6d1eeee8c2f4f06e8a7b1b68
[ "MIT" ]
19
2018-05-14T01:16:16.000Z
2022-03-23T21:16:10.000Z
//================================================================================================= // // MJP's DX11 Sample Framework // http://mynameismjp.wordpress.com/ // // All code and content licensed under Microsoft Public License (Ms-PL) // //================================================================================================= #include "PCH.h" #include "GraphicsTypes.h" #include "Exceptions.h" #include "Utility.h" #include "Serialization.h" #include "FileIO.h" namespace SampleFramework11 { // == RenderTarget2D ============================================================================== RenderTarget2D::RenderTarget2D() : Width(0), Height(0), Format(DXGI_FORMAT_UNKNOWN), NumMipLevels(0), MultiSamples(0), MSQuality(0), AutoGenMipMaps(false), UAView(NULL), ArraySize(1) { } void RenderTarget2D::Initialize(ID3D11Device* device, uint32 width, uint32 height, DXGI_FORMAT format, uint32 numMipLevels, uint32 multiSamples, uint32 msQuality, bool32 autoGenMipMaps, bool32 createUAV, uint32 arraySize, bool32 cubeMap) { D3D11_TEXTURE2D_DESC desc; desc.Width = width; desc.Height = height; desc.ArraySize = arraySize; desc.BindFlags = D3D11_BIND_SHADER_RESOURCE|D3D11_BIND_RENDER_TARGET; if(createUAV) desc.BindFlags |= D3D11_BIND_UNORDERED_ACCESS; desc.CPUAccessFlags = 0; desc.Format = format; desc.MipLevels = numMipLevels; desc.MiscFlags = (autoGenMipMaps && numMipLevels != 1) ? D3D11_RESOURCE_MISC_GENERATE_MIPS : 0; desc.SampleDesc.Count = multiSamples; desc.SampleDesc.Quality = msQuality; desc.Usage = D3D11_USAGE_DEFAULT; if(cubeMap) { _ASSERT(arraySize == 6); desc.MiscFlags = D3D11_RESOURCE_MISC_TEXTURECUBE; } DXCall(device->CreateTexture2D(&desc, NULL, &Texture)); RTVArraySlices.clear(); for(uint32 i = 0; i < arraySize; ++i) { ID3D11RenderTargetViewPtr rtView; D3D11_RENDER_TARGET_VIEW_DESC rtDesc; rtDesc.Format = format; if(arraySize == 1) { if(multiSamples > 1) { rtDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DMS; } else { rtDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D; rtDesc.Texture2D.MipSlice = 0; } } else { if(multiSamples > 1) { rtDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DMSARRAY; rtDesc.Texture2DMSArray.ArraySize = 1; rtDesc.Texture2DMSArray.FirstArraySlice = i; } else { rtDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DARRAY; rtDesc.Texture2DArray.ArraySize = 1; rtDesc.Texture2DArray.FirstArraySlice = i; rtDesc.Texture2DArray.MipSlice = 0; } } DXCall(device->CreateRenderTargetView(Texture, &rtDesc, &rtView)); RTVArraySlices.push_back(rtView); } RTView = RTVArraySlices[0]; DXCall(device->CreateShaderResourceView(Texture, NULL, &SRView)); SRVArraySlices.clear(); for(uint32 i = 0; i < arraySize; ++i) { ID3D11ShaderResourceViewPtr srView; D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc; srvDesc.Format = format; if(arraySize == 1) { if(multiSamples > 1) { srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DMS; } else { srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; srvDesc.Texture2D.MipLevels = -1; srvDesc.Texture2D.MostDetailedMip = 0; } } else { if(multiSamples > 1) { srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DMSARRAY; srvDesc.Texture2DMSArray.ArraySize = 1; srvDesc.Texture2DMSArray.FirstArraySlice = i; } else { srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DARRAY; srvDesc.Texture2DArray.ArraySize = 1; srvDesc.Texture2DArray.FirstArraySlice = i; srvDesc.Texture2DArray.MipLevels = -1; srvDesc.Texture2DArray.MostDetailedMip = 0; } } DXCall(device->CreateShaderResourceView(Texture, &srvDesc, &srView)); SRVArraySlices.push_back(srView); } Width = width; Height = height; NumMipLevels = numMipLevels; MultiSamples = multiSamples; Format = format; AutoGenMipMaps = autoGenMipMaps; ArraySize = arraySize; CubeMap = cubeMap; if(createUAV) DXCall(device->CreateUnorderedAccessView(Texture, NULL, &UAView)); }; // == DepthStencilBuffer ========================================================================== DepthStencilBuffer::DepthStencilBuffer() : Width(0), Height(0), MultiSamples(0), MSQuality(0), Format(DXGI_FORMAT_UNKNOWN), ArraySize(1) { } void DepthStencilBuffer::Initialize(ID3D11Device* device, uint32 width, uint32 height, DXGI_FORMAT format, bool32 useAsShaderResource, uint32 multiSamples, uint32 msQuality, uint32 arraySize) { uint32 bindFlags = D3D11_BIND_DEPTH_STENCIL; if (useAsShaderResource) bindFlags |= D3D11_BIND_SHADER_RESOURCE; DXGI_FORMAT dsTexFormat; if (!useAsShaderResource) dsTexFormat = format; else if (format == DXGI_FORMAT_D16_UNORM) dsTexFormat = DXGI_FORMAT_R16_TYPELESS; else if(format == DXGI_FORMAT_D24_UNORM_S8_UINT) dsTexFormat = DXGI_FORMAT_R24G8_TYPELESS; else dsTexFormat = DXGI_FORMAT_R32_TYPELESS; D3D11_TEXTURE2D_DESC desc; desc.Width = width; desc.Height = height; desc.ArraySize = arraySize; desc.BindFlags = bindFlags; desc.CPUAccessFlags = 0; desc.Format = dsTexFormat; desc.MipLevels = 1; desc.MiscFlags = 0; desc.SampleDesc.Count = multiSamples; desc.SampleDesc.Quality = msQuality; desc.Usage = D3D11_USAGE_DEFAULT; DXCall(device->CreateTexture2D(&desc, NULL, &Texture)); ArraySlices.clear(); for (uint32 i = 0; i < arraySize; ++i) { D3D11_DEPTH_STENCIL_VIEW_DESC dsvDesc; ID3D11DepthStencilViewPtr dsView; dsvDesc.Format = format; if (arraySize == 1) { dsvDesc.ViewDimension = multiSamples > 1 ? D3D11_DSV_DIMENSION_TEXTURE2DMS : D3D11_DSV_DIMENSION_TEXTURE2D; dsvDesc.Texture2D.MipSlice = 0; } else { if(multiSamples > 1) { dsvDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2DMSARRAY; dsvDesc.Texture2DMSArray.ArraySize = 1; dsvDesc.Texture2DMSArray.FirstArraySlice = i; } else { dsvDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2DARRAY; dsvDesc.Texture2DArray.ArraySize = 1; dsvDesc.Texture2DArray.FirstArraySlice = i; dsvDesc.Texture2DArray.MipSlice = 0; } } dsvDesc.Flags = 0; DXCall(device->CreateDepthStencilView(Texture, &dsvDesc, &dsView)); ArraySlices.push_back(dsView); if (i == 0) { // Also create a read-only DSV dsvDesc.Flags = D3D11_DSV_READ_ONLY_DEPTH; if (format == DXGI_FORMAT_D24_UNORM_S8_UINT || format == DXGI_FORMAT_D32_FLOAT_S8X24_UINT) dsvDesc.Flags |= D3D11_DSV_READ_ONLY_STENCIL; DXCall(device->CreateDepthStencilView(Texture, &dsvDesc, &ReadOnlyDSView)); dsvDesc.Flags = 0; } } DSView = ArraySlices[0]; if (useAsShaderResource) { DXGI_FORMAT dsSRVFormat; if (format == DXGI_FORMAT_D16_UNORM) dsSRVFormat = DXGI_FORMAT_R16_UNORM; else if(format == DXGI_FORMAT_D24_UNORM_S8_UINT) dsSRVFormat = DXGI_FORMAT_R24_UNORM_X8_TYPELESS ; else dsSRVFormat = DXGI_FORMAT_R32_FLOAT; D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc; srvDesc.Format = dsSRVFormat; if (arraySize == 1) { srvDesc.ViewDimension = multiSamples > 1 ? D3D11_SRV_DIMENSION_TEXTURE2DMS : D3D11_SRV_DIMENSION_TEXTURE2D; srvDesc.Texture2D.MipLevels = 1; srvDesc.Texture2D.MostDetailedMip = 0; } else { srvDesc.ViewDimension = multiSamples > 1 ? D3D11_SRV_DIMENSION_TEXTURE2DMSARRAY : D3D11_SRV_DIMENSION_TEXTURE2DARRAY; srvDesc.Texture2DArray.ArraySize = arraySize; srvDesc.Texture2DArray.FirstArraySlice = 0; srvDesc.Texture2DArray.MipLevels = 1; srvDesc.Texture2DArray.MostDetailedMip = 0; } DXCall(device->CreateShaderResourceView(Texture, &srvDesc, &SRView)); } else SRView = NULL; Width = width; Height = height; MultiSamples = multiSamples; Format = format; ArraySize = arraySize; } // == RWBuffer ==================================================================================== RWBuffer::RWBuffer() : Size(0), Stride(0), NumElements(0), Format(DXGI_FORMAT_UNKNOWN), RawBuffer(false) { } void RWBuffer::Initialize(ID3D11Device* device, DXGI_FORMAT format, uint32 stride, uint32 numElements, bool32 rawBuffer) { Format = format; Size = stride * numElements; Stride = stride; NumElements = numElements; RawBuffer = rawBuffer; if(rawBuffer) { _ASSERT(stride == 4); Format = DXGI_FORMAT_R32_TYPELESS; } D3D11_BUFFER_DESC bufferDesc; bufferDesc.ByteWidth = stride * numElements; bufferDesc.Usage = D3D11_USAGE_DEFAULT; bufferDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_UNORDERED_ACCESS; bufferDesc.CPUAccessFlags = 0; bufferDesc.MiscFlags = rawBuffer ? D3D11_RESOURCE_MISC_BUFFER_ALLOW_RAW_VIEWS : 0; bufferDesc.StructureByteStride = 0; DXCall(device->CreateBuffer(&bufferDesc, NULL, &Buffer)); D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc; srvDesc.Format = Format; if(rawBuffer) { srvDesc.ViewDimension = D3D11_SRV_DIMENSION_BUFFEREX; srvDesc.BufferEx.FirstElement = 0; srvDesc.BufferEx.NumElements = numElements; srvDesc.BufferEx.Flags = D3D11_BUFFEREX_SRV_FLAG_RAW; } else { srvDesc.ViewDimension = D3D11_SRV_DIMENSION_BUFFER; srvDesc.Buffer.ElementOffset = 0; srvDesc.Buffer.ElementWidth = numElements; } DXCall(device->CreateShaderResourceView(Buffer, &srvDesc, &SRView)); D3D11_UNORDERED_ACCESS_VIEW_DESC uavDesc; uavDesc.Format = format; uavDesc.ViewDimension = D3D11_UAV_DIMENSION_BUFFER; uavDesc.Buffer.FirstElement = 0; uavDesc.Buffer.NumElements = numElements; uavDesc.Buffer.Flags = rawBuffer ? D3D11_BUFFER_UAV_FLAG_RAW : 0; DXCall(device->CreateUnorderedAccessView(Buffer, &uavDesc, &UAView)); } // == StructuredBuffer ============================================================================ StructuredBuffer::StructuredBuffer() : Size(0), Stride(0), NumElements(0) { } void StructuredBuffer::Initialize(ID3D11Device* device, uint32 stride, uint32 numElements, bool32 useAsUAV, bool32 appendConsume, bool32 useAsDrawIndirect, const void* initData) { Size = stride * numElements; Stride = stride; NumElements = numElements; if(appendConsume || useAsDrawIndirect) useAsUAV = true; D3D11_BUFFER_DESC bufferDesc; bufferDesc.ByteWidth = stride * numElements; bufferDesc.Usage = useAsUAV ? D3D11_USAGE_DEFAULT : D3D11_USAGE_IMMUTABLE; bufferDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE; bufferDesc.BindFlags |= useAsUAV ? D3D11_BIND_UNORDERED_ACCESS : 0; bufferDesc.CPUAccessFlags = 0; bufferDesc.MiscFlags = D3D11_RESOURCE_MISC_BUFFER_STRUCTURED; bufferDesc.MiscFlags |= useAsDrawIndirect ? D3D11_RESOURCE_MISC_DRAWINDIRECT_ARGS : 0; bufferDesc.StructureByteStride = stride; D3D11_SUBRESOURCE_DATA subresourceData; subresourceData.pSysMem = initData; subresourceData.SysMemPitch = 0; subresourceData.SysMemSlicePitch = 0; DXCall(device->CreateBuffer(&bufferDesc, initData != NULL ? &subresourceData : NULL, &Buffer)); D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc; srvDesc.Format = DXGI_FORMAT_UNKNOWN; srvDesc.ViewDimension = D3D11_SRV_DIMENSION_BUFFER; srvDesc.Buffer.FirstElement = 0; srvDesc.Buffer.NumElements = numElements; DXCall(device->CreateShaderResourceView(Buffer, &srvDesc, &SRView)); if(useAsUAV) { D3D11_UNORDERED_ACCESS_VIEW_DESC uavDesc; uavDesc.Format = DXGI_FORMAT_UNKNOWN; uavDesc.ViewDimension = D3D11_UAV_DIMENSION_BUFFER; uavDesc.Buffer.FirstElement = 0; uavDesc.Buffer.Flags = appendConsume ? D3D11_BUFFER_UAV_FLAG_APPEND : 0; uavDesc.Buffer.NumElements = numElements; DXCall(device->CreateUnorderedAccessView(Buffer, &uavDesc, &UAView)); } } void StructuredBuffer::WriteToFile(const wchar* path, ID3D11Device* device, ID3D11DeviceContext* context) { _ASSERT(Buffer != NULL); // Get the buffer info D3D11_BUFFER_DESC desc; Buffer->GetDesc(&desc); uint32 useAsUAV = (desc.BindFlags & D3D11_BIND_UNORDERED_ACCESS) ? 1 : 0; uint32 useAsDrawIndirect = (desc.MiscFlags & D3D11_RESOURCE_MISC_DRAWINDIRECT_ARGS) ? 1 : 0; uint32 appendConsume = 0; if(useAsUAV) { D3D11_UNORDERED_ACCESS_VIEW_DESC uavDesc; UAView->GetDesc(&uavDesc); appendConsume = (uavDesc.Format & D3D11_BUFFER_UAV_FLAG_APPEND) ? 1 : 0; } // If the exists, delete it if(FileExists(path)) Win32Call(DeleteFile(path)); // Create the file HANDLE fileHandle = CreateFile(path, GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL); if(fileHandle == INVALID_HANDLE_VALUE) Win32Call(false); // Write the buffer info DWORD bytesWritten = 0; Win32Call(WriteFile(fileHandle, &Size, 4, &bytesWritten, NULL)); Win32Call(WriteFile(fileHandle, &Stride, 4, &bytesWritten, NULL)); Win32Call(WriteFile(fileHandle, &NumElements, 4, &bytesWritten, NULL)); Win32Call(WriteFile(fileHandle, &useAsUAV, 4, &bytesWritten, NULL)); Win32Call(WriteFile(fileHandle, &useAsDrawIndirect, 4, &bytesWritten, NULL)); Win32Call(WriteFile(fileHandle, &appendConsume, 4, &bytesWritten, NULL)); // Get the buffer data StagingBuffer stagingBuffer; stagingBuffer.Initialize(device, Size); context->CopyResource(stagingBuffer.Buffer, Buffer); const void* bufferData= stagingBuffer.Map(context); // Write the data to the file Win32Call(WriteFile(fileHandle, bufferData, Size, &bytesWritten, NULL)); // Un-map the staging buffer stagingBuffer.Unmap(context); // Close the file Win32Call(CloseHandle(fileHandle)); } void StructuredBuffer::ReadFromFile(const wchar* path, ID3D11Device* device) { // Open the file HANDLE fileHandle = CreateFile(path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if(fileHandle == INVALID_HANDLE_VALUE) Win32Call(false); // Read the buffer info bool32 useAsUAV, useAsDrawIndirect, appendConsume; DWORD bytesRead = 0; Win32Call(ReadFile(fileHandle, &Size, 4, &bytesRead, NULL)); Win32Call(ReadFile(fileHandle, &Stride, 4, &bytesRead, NULL)); Win32Call(ReadFile(fileHandle, &NumElements, 4, &bytesRead, NULL)); Win32Call(ReadFile(fileHandle, &useAsUAV, 4, &bytesRead, NULL)); Win32Call(ReadFile(fileHandle, &useAsDrawIndirect, 4, &bytesRead, NULL)); Win32Call(ReadFile(fileHandle, &appendConsume, 4, &bytesRead, NULL)); // Read the buffer data UINT8* bufferData = new UINT8[Size]; Win32Call(ReadFile(fileHandle, bufferData, Size, &bytesRead, NULL)); // Close the file Win32Call(CloseHandle(fileHandle)); // Init Initialize(device, Stride, NumElements, useAsUAV, appendConsume, useAsDrawIndirect, bufferData); // Clean up delete [] bufferData; } // == StagingBuffer =============================================================================== StagingBuffer::StagingBuffer() : Size(0) { } void StagingBuffer::Initialize(ID3D11Device* device, uint32 size) { Size = size; D3D11_BUFFER_DESC bufferDesc; bufferDesc.ByteWidth = Size; bufferDesc.Usage = D3D11_USAGE_STAGING; bufferDesc.BindFlags = 0; bufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; bufferDesc.MiscFlags = 0; bufferDesc.StructureByteStride = 0; DXCall(device->CreateBuffer(&bufferDesc, NULL, &Buffer)); } void* StagingBuffer::Map(ID3D11DeviceContext* context) { D3D11_MAPPED_SUBRESOURCE mapped; DXCall(context->Map(Buffer, 0, D3D11_MAP_READ, 0, &mapped)); return mapped.pData; } void StagingBuffer::Unmap(ID3D11DeviceContext* context) { context->Unmap(Buffer, 0); } // == StagingTexture2D ============================================================================ StagingTexture2D::StagingTexture2D() : Width(0), Height(0), Format(DXGI_FORMAT_UNKNOWN), NumMipLevels(0), MultiSamples(0), MSQuality(0), ArraySize(1) { } void StagingTexture2D::Initialize(ID3D11Device* device, uint32 width, uint32 height, DXGI_FORMAT format, uint32 numMipLevels, uint32 multiSamples, uint32 msQuality, uint32 arraySize) { D3D11_TEXTURE2D_DESC desc; desc.Width = width; desc.Height = height; desc.ArraySize = arraySize; desc.BindFlags = 0; desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; desc.Format = format; desc.MipLevels = numMipLevels; desc.MiscFlags = 0; desc.SampleDesc.Count = multiSamples; desc.SampleDesc.Quality = msQuality; desc.Usage = D3D11_USAGE_STAGING; DXCall(device->CreateTexture2D(&desc, NULL, &Texture)); Width = width; Height = height; NumMipLevels = numMipLevels; MultiSamples = multiSamples; Format = format; ArraySize = arraySize; }; void* StagingTexture2D::Map(ID3D11DeviceContext* context, uint32 subResourceIndex, uint32& pitch) { D3D11_MAPPED_SUBRESOURCE mapped; DXCall(context->Map(Texture, subResourceIndex, D3D11_MAP_READ, 0, &mapped)); pitch = mapped.RowPitch; return mapped.pData; } void StagingTexture2D::Unmap(ID3D11DeviceContext* context, uint32 subResourceIndex) { context->Unmap(Texture, subResourceIndex); } }
33.971235
129
0.599841
TheRealMJP
f65c2dbc6041eacfb4391cfa93c7da0b5f2dfbac
12,042
cpp
C++
Components/8530/z8530.cpp
ivanizag/CLK
e5d364c4ce20aaf6dbdf19ddce1879e91f4ddbc8
[ "MIT" ]
2
2018-09-11T14:59:09.000Z
2018-09-12T09:39:46.000Z
Components/8530/z8530.cpp
MaddTheSane/CLK
6252859ef5631c7ccbc33e95cf4d888727ff3856
[ "MIT" ]
null
null
null
Components/8530/z8530.cpp
MaddTheSane/CLK
6252859ef5631c7ccbc33e95cf4d888727ff3856
[ "MIT" ]
null
null
null
// // 8530.cpp // Clock Signal // // Created by Thomas Harte on 07/06/2019. // Copyright © 2019 Thomas Harte. All rights reserved. // #include "z8530.hpp" #define LOG_PREFIX "[SCC] " #include "../../Outputs/Log.hpp" using namespace Zilog::SCC; void z8530::reset() { // TODO. } bool z8530::get_interrupt_line() const { return (master_interrupt_control_ & 0x8) && ( channels_[0].get_interrupt_line() || channels_[1].get_interrupt_line() ); } /* Per the standard defined in the header file, this implementation follows an addressing convention of: A0 = A/B (i.e. channel select) A1 = C/D (i.e. control or data) */ std::uint8_t z8530::read(int address) { if(address & 2) { // Read data register for channel. return channels_[address & 1].read(true, pointer_); } else { // Read control register for channel. uint8_t result = 0; switch(pointer_) { default: result = channels_[address & 1].read(false, pointer_); break; case 2: // Handled non-symmetrically between channels. if(address & 1) { LOG("Unimplemented: register 2 status bits"); } else { result = interrupt_vector_; // Modify the vector if permitted. // if(master_interrupt_control_ & 1) { for(int port = 0; port < 2; ++port) { // TODO: the logic below assumes that DCD is the only implemented interrupt. Fix. if(channels_[port].get_interrupt_line()) { const uint8_t shift = 1 + 3*((master_interrupt_control_ & 0x10) >> 4); const uint8_t mask = uint8_t(~(7 << shift)); result = uint8_t( (result & mask) | ((1 | ((port == 1) ? 4 : 0)) << shift) ); break; } } // } } break; } // Cf. the two-step control register selection process in ::write. Since this // definitely wasn't a *write* to register 0, it follows that the next selected // control register will be 0. pointer_ = 0; update_delegate(); return result; } return 0x00; } void z8530::write(int address, std::uint8_t value) { if(address & 2) { // Write data register for channel. This is completely independent // of whatever is going on over in the control realm. channels_[address & 1].write(true, pointer_, value); } else { // Write control register for channel; there's a two-step sequence // here for the programmer. Initially the selected register // (i.e. `pointer_`) is zero. That register includes a field to // set the next selected register. After any other register has // been written to, register 0 is selected again. // Most registers are per channel, but a couple are shared; // sever them here, send the rest to the appropriate chnanel. switch(pointer_) { default: channels_[address & 1].write(false, pointer_, value); break; case 2: // Interrupt vector register; used only by Channel B. // So there's only one of these. interrupt_vector_ = value; LOG("Interrupt vector set to " << PADHEX(2) << int(value)); break; case 9: // Master interrupt and reset register; there is also only one of these. LOG("Master interrupt and reset register: " << PADHEX(2) << int(value)); master_interrupt_control_ = value; break; } // The pointer number resets to 0 after every access, but if it is zero // then crib at least the next set of pointer bits (which, similarly, are shared // between the two channels). if(pointer_) { pointer_ = 0; } else { // The lowest three bits are the lowest three bits of the pointer. pointer_ = value & 7; // If the command part of the byte is a 'point high', also set the // top bit of the pointer. Channels themselves therefore need not // (/should not) respond to the point high command. if(((value >> 3)&7) == 1) { pointer_ |= 8; } } } update_delegate(); } void z8530::set_dcd(int port, bool level) { channels_[port].set_dcd(level); update_delegate(); } // MARK: - Channel implementations uint8_t z8530::Channel::read(bool data, uint8_t pointer) { // If this is a data read, just return it. if(data) { return data_; } else { LOG("Control read from register " << int(pointer)); // Otherwise, this is a control read... switch(pointer) { default: return 0x00; case 0x0: // Read Register 0; see p.37 (PDF p.45). // b0: Rx character available. // b1: zero count. // b2: Tx buffer empty. // b3: DCD. // b4: sync/hunt. // b5: CTS. // b6: Tx underrun/EOM. // b7: break/abort. return dcd_ ? 0x8 : 0x0; case 0x1: // Read Register 1; see p.37 (PDF p.45). // b0: all sent. // b1: residue code 0. // b2: residue code 1. // b3: residue code 2. // b4: parity error. // b5: Rx overrun error. // b6: CRC/framing error. // b7: end of frame (SDLC). return 0x01; case 0x2: // Read Register 2; see p.37 (PDF p.45). // Interrupt vector — modified by status information in B channel. return 0x00; case 0x3: // Read Register 3; see p.37 (PDF p.45). // B channel: all bits are 0. // A channel: // b0: Channel B ext/status IP. // b1: Channel B Tx IP. // b2: Channel B Rx IP. // b3: Channel A ext/status IP. // b4: Channel A Tx IP. // b5: Channel A Rx IP. // b6, b7: 0. return 0x00; case 0xa: // Read Register 10; see p.37 (PDF p.45). // b0: 0 // b1: On loop. // b2: 0 // b3: 0 // b4: Loop sending. // b5: 0 // b6: Two clocks missing. // b7: One clock missing. return 0x00; case 0xc: // Read Register 12; see p.37 (PDF p.45). // Lower byte of time constant. return 0x00; case 0xd: // Read Register 13; see p.38 (PDF p.46). // Upper byte of time constant. return 0x00; case 0xf: // Read Register 15; see p.38 (PDF p.46). // External interrupt status: // b0: 0 // b1: Zero count. // b2: 0 // b3: DCD. // b4: Sync/hunt. // b5: CTS. // b6: Tx underrun/EOM. // b7: Break/abort. return external_interrupt_status_; } } return 0x00; } void z8530::Channel::write(bool data, uint8_t pointer, uint8_t value) { if(data) { data_ = value; return; } else { LOG("Control write: " << PADHEX(2) << int(value) << " to register " << int(pointer)); switch(pointer) { default: LOG("Unrecognised control write: " << PADHEX(2) << int(value) << " to register " << int(pointer)); break; case 0x0: // Write register 0 — CRC reset and other functions. // Decode CRC reset instructions. switch(value >> 6) { default: /* Do nothing. */ break; case 1: LOG("TODO: reset Rx CRC checker."); break; case 2: LOG("TODO: reset Tx CRC checker."); break; case 3: LOG("TODO: reset Tx underrun/EOM latch."); break; } // Decode command code. switch((value >> 3)&7) { default: /* Do nothing. */ break; case 2: // LOG("reset ext/status interrupts."); external_status_interrupt_ = false; external_interrupt_status_ = 0; break; case 3: LOG("TODO: send abort (SDLC)."); break; case 4: LOG("TODO: enable interrupt on next Rx character."); break; case 5: LOG("TODO: reset Tx interrupt pending."); break; case 6: LOG("TODO: reset error."); break; case 7: LOG("TODO: reset highest IUS."); break; } break; case 0x1: // Write register 1 — Transmit/Receive Interrupt and Data Transfer Mode Definition. interrupt_mask_ = value; /* b7 = 0 => Wait/Request output is inactive; 1 => output is informative. b6 = Wait/request output is for... 0 => wait: floating when inactive, low if CPU is attempting to transfer data the SCC isn't yet ready for. 1 => request: high if inactive, low if SCC is ready to transfer data. b5 = 1 => wait/request is relative to read buffer; 0 => relative to write buffer. b4/b3: 00 = disable receive interrupt 01 = interrupt on first character or special condition 10 = interrupt on all characters and special conditions 11 = interrupt only upon special conditions. b2 = 1 => parity error is a special condition; 0 => it isn't. b1 = 1 => transmit buffer empty interrupt is enabled; 0 => it isn't. b0 = 1 => external interrupt is enabled; 0 => it isn't. */ LOG("Interrupt mask: " << PADHEX(2) << int(value)); break; case 0x2: // Write register 2 - interrupt vector. break; case 0x3: { // Write register 3 — Receive Parameters and Control. // Get bit count. int receive_bit_count = 8; switch(value >> 6) { default: receive_bit_count = 5; break; case 1: receive_bit_count = 7; break; case 2: receive_bit_count = 6; break; case 3: receive_bit_count = 8; break; } LOG("Receive bit count: " << receive_bit_count); (void)receive_bit_count; /* b7,b6: 00 = 5 receive bits per character 01 = 7 bits 10 = 6 bits 11 = 8 bits b5 = 1 => DCD and CTS outputs are set automatically; 0 => they're inputs to read register 0. (DCD is ignored in local loopback; CTS is ignored in both auto echo and local loopback). b4: enter hunt mode (if set to 1, presumably?) b3 = 1 => enable receiver CRC generation; 0 => don't. b2: address search mode (SDLC) b1: sync character load inhibit. b0: Rx enable. */ } break; case 0x4: // Write register 4 — Transmit/Receive Miscellaneous Parameters and Modes. // Bits 0 and 1 select parity mode. if(!(value&1)) { parity_ = Parity::Off; } else { parity_ = (value&2) ? Parity::Even : Parity::Odd; } // Bits 2 and 3 select stop bits. switch((value >> 2)&3) { default: stop_bits_ = StopBits::Synchronous; break; case 1: stop_bits_ = StopBits::OneBit; break; case 2: stop_bits_ = StopBits::OneAndAHalfBits; break; case 3: stop_bits_ = StopBits::TwoBits; break; } // Bits 4 and 5 pick a sync mode. switch((value >> 4)&3) { default: sync_mode_ = Sync::Monosync; break; case 1: sync_mode_ = Sync::Bisync; break; case 2: sync_mode_ = Sync::SDLC; break; case 3: sync_mode_ = Sync::External; break; } // Bits 6 and 7 select a clock rate multiplier, unless synchronous // mode is enabled (and this is ignored if sync mode is external). if(stop_bits_ == StopBits::Synchronous) { clock_rate_multiplier_ = 1; } else { switch((value >> 6)&3) { default: clock_rate_multiplier_ = 1; break; case 1: clock_rate_multiplier_ = 16; break; case 2: clock_rate_multiplier_ = 32; break; case 3: clock_rate_multiplier_ = 64; break; } } break; case 0x5: // b7: DTR // b6/b5: // 00 = Tx 5 bits (or less) per character // 01 = Tx 7 bits per character // 10 = Tx 6 bits per character // 11 = Tx 8 bits per character // b4: send break. // b3: Tx enable. // b2: SDLC (if 0) / CRC-16 (if 1) // b1: RTS // b0: Tx CRC enable. break; case 0x6: break; case 0xf: // Write register 15 — External/Status Interrupt Control. external_interrupt_mask_ = value; break; } } } void z8530::Channel::set_dcd(bool level) { if(dcd_ == level) return; dcd_ = level; if(external_interrupt_mask_ & 0x8) { external_status_interrupt_ = true; external_interrupt_status_ |= 0x8; } } bool z8530::Channel::get_interrupt_line() const { return (interrupt_mask_ & 1) && external_status_interrupt_; // TODO: other potential causes of an interrupt. } /*! Evaluates the new level of the interrupt line and notifies the delegate if both: (i) there is one; and (ii) the interrupt line has changed since last the delegate was notified. */ void z8530::update_delegate() { const bool interrupt_line = get_interrupt_line(); if(interrupt_line != previous_interrupt_line_) { previous_interrupt_line_ = interrupt_line; if(delegate_) delegate_->did_change_interrupt_status(this, interrupt_line); } }
28.135514
111
0.622156
ivanizag
f65d0d7164d56ad7eeb7552cc973392652703046
4,455
cpp
C++
Audio/src/Sample.cpp
guusw/unnamed-sdvx-clone
76e85fe219c9e87c8d9d06d6db32d40701e0a47f
[ "MIT" ]
65
2016-06-04T18:04:46.000Z
2022-03-06T21:53:12.000Z
Audio/src/Sample.cpp
HEY-WhoTookMyUsername/hello-world
76e85fe219c9e87c8d9d06d6db32d40701e0a47f
[ "MIT" ]
24
2016-06-17T09:23:11.000Z
2021-10-13T10:27:16.000Z
Audio/src/Sample.cpp
HEY-WhoTookMyUsername/unnamed-sdvx-clone
76e85fe219c9e87c8d9d06d6db32d40701e0a47f
[ "MIT" ]
16
2016-07-22T09:10:41.000Z
2022-02-13T02:30:19.000Z
#include "stdafx.h" #include "Sample.hpp" #include "Audio_Impl.hpp" #include "Audio.hpp" // Fixed point format for resampling static uint64 fp_sampleStep = 1ull << 48; struct WavHeader { char id[4]; uint32 nLength; bool operator ==(const char* rhs) const { return strncmp(id, rhs, 4) == 0; } bool operator !=(const char* rhs) const { return !(*this == rhs); } }; struct WavFormat { uint16 nFormat; uint16 nChannels; uint32 nSampleRate; uint32 nByteRate; uint16 nBlockAlign; uint16 nBitsPerSample; }; BinaryStream& operator <<(BinaryStream& stream, WavHeader& hdr) { stream.SerializeObject(hdr.id); stream << hdr.nLength; return stream; } BinaryStream& operator <<(BinaryStream& stream, WavFormat& fmt) { stream.SerializeObject(fmt); return stream; } class Sample_Impl : public SampleRes { public: Audio* m_audio; Buffer m_pcm; WavFormat m_format = { 0 }; mutex m_lock; // Resampling values uint64 m_sampleStep = 0; uint64 m_sampleStepIncrement = 0; uint64 m_playbackPointer = 0; uint64 m_length = 0; bool m_playing = false; public: ~Sample_Impl() { Deregister(); } virtual void Play() override { m_lock.lock(); m_playing = true; m_playbackPointer = 0; m_lock.unlock(); } bool Init(const String& path) { File file; if(!file.OpenRead(path)) return false; FileReader stream = FileReader(file); WavHeader riff; stream << riff; if(riff != "RIFF") return false; char riffType[4]; stream.SerializeObject(riffType); if(strncmp(riffType, "WAVE", 4) != 0) return false; while(stream.Tell() < stream.GetSize()) { WavHeader chunkHdr; stream << chunkHdr; if(chunkHdr == "fmt ") { stream << m_format; //Logf("Sample format: %s", Logger::Info, (m_format.nFormat == 1) ? "PCM" : "Unknown"); //Logf("Channels: %d", Logger::Info, m_format.nChannels); //Logf("Sample rate: %d", Logger::Info, m_format.nSampleRate); //Logf("Bps: %d", Logger::Info, m_format.nBitsPerSample); } else if(chunkHdr == "data") // data Chunk { // validate header if(m_format.nFormat != 1) return false; if(m_format.nChannels > 2 || m_format.nChannels == 0) return false; if(m_format.nBitsPerSample != 16) return false; // Read data m_length = chunkHdr.nLength / sizeof(short); m_pcm.resize(chunkHdr.nLength); stream.Serialize(m_pcm.data(), chunkHdr.nLength); } else { stream.Skip(chunkHdr.nLength); } } // Calculate the sample step if the rate is not the same as the output rate double sampleStep = (double)m_format.nSampleRate / (double)m_audio->GetSampleRate(); m_sampleStepIncrement = (uint64)(sampleStep * (double)fp_sampleStep); return true; } virtual void Process(float* out, uint32 numSamples) override { if(!m_playing) return; m_lock.lock(); if(m_format.nChannels == 2) { // Mix stereo sample for(uint32 i = 0; i < numSamples; i++) { if(m_playbackPointer >= m_length) { // Playback ended m_playing = false; break; } int16* src = ((int16*)m_pcm.data()) + m_playbackPointer; out[i * 2] = (float)src[0] / (float)0x7FFF; out[i * 2 + 1] = (float)src[1] / (float)0x7FFF; // Increment source sample with resampling m_sampleStep += m_sampleStepIncrement; while(m_sampleStep >= fp_sampleStep) { m_playbackPointer += 2; m_sampleStep -= fp_sampleStep; } } } else { // Mix mono sample for(uint32 i = 0; i < numSamples; i++) { if(m_playbackPointer >= m_length) { // Playback ended m_playing = false; break; } int16* src = ((int16*)m_pcm.data()) + m_playbackPointer; out[i * 2] = (float)src[0] / (float)0x7FFF; out[i * 2 + 1] = (float)src[0] / (float)0x7FFF; // Increment source sample with resampling m_sampleStep += m_sampleStepIncrement; while(m_sampleStep >= fp_sampleStep) { m_playbackPointer += 1; m_sampleStep -= fp_sampleStep; } } } m_lock.unlock(); } const Buffer& GetData() const { return m_pcm; } uint32 GetBitsPerSample() const { return m_format.nBitsPerSample; } uint32 GetNumChannels() const { return m_format.nChannels; } }; Sample SampleRes::Create(Audio* audio, const String& path) { Sample_Impl* res = new Sample_Impl(); res->m_audio = audio; if(!res->Init(path)) { delete res; return Sample(); } audio->GetImpl()->Register(res); return Sample(res); }
20.43578
91
0.647811
guusw
f660ea7f203555c42f01e4c24b9fa2111b3742e0
15,082
cpp
C++
src/LocalHost.cpp
RalfOGit/speedwire-lib
226be6f2d7ec82c9b7e095d2f1c2cd12644f0fd1
[ "MIT" ]
6
2021-03-28T11:11:26.000Z
2022-01-26T11:26:20.000Z
src/LocalHost.cpp
RalfOGit/speedwire-lib
226be6f2d7ec82c9b7e095d2f1c2cd12644f0fd1
[ "MIT" ]
2
2021-04-25T10:13:47.000Z
2021-12-24T11:25:41.000Z
src/LocalHost.cpp
RalfOGit/speedwire-lib
226be6f2d7ec82c9b7e095d2f1c2cd12644f0fd1
[ "MIT" ]
1
2021-04-24T06:43:30.000Z
2021-04-24T06:43:30.000Z
#define _WINSOCK_DEPRECATED_NO_WARNINGS #include <cstring> #include <stdio.h> #include <time.h> #ifdef _WIN32 #include <Winsock2.h> #include <Ws2tcpip.h> #include <iphlpapi.h> #include <chrono> #else #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <netinet/in.h> #include <netdb.h> #include <ifaddrs.h> #include <arpa/inet.h> #include <net/if.h> #endif #include <LocalHost.hpp> #include <AddressConversion.hpp> using namespace libspeedwire; LocalHost *LocalHost::instance = NULL; /** * Constructor */ LocalHost::LocalHost(void) {} /** * Destructor */ LocalHost::~LocalHost(void) {} /** * Get singleton instance. The cache of the returned instance cache is fully initialized. */ LocalHost& LocalHost::getInstance(void) { // check if instance has been instanciated if (instance == NULL) { // instanciate instance instance = new LocalHost(); #ifdef _WIN32 // initialize Windows Socket API with given VERSION. WSADATA wsaData; if (WSAStartup(MAKEWORD(2, 2), &wsaData)) { perror("WSAStartup failure"); } #endif // query hostname instance->cacheHostname(LocalHost::queryHostname()); // query interfaces instance->cacheLocalIPAddresses(LocalHost::queryLocalIPAddresses()); // query interface information, such as interface names, mac addresses and local ip addressesl and interface indexes const std::vector<LocalHost::InterfaceInfo> infos = LocalHost::queryLocalInterfaceInfos(); instance->cacheLocalInterfaceInfos(infos); } return *instance; } /** * Getter for cached hostname */ const std::string &LocalHost::getHostname(void) const { return hostname; } /** * Setter to cache the hostname */ void LocalHost::cacheHostname(const std::string &hostname) { this->hostname = hostname; } /** * Getter for cached ipv4 and ipv6 interface names */ const std::vector<std::string>& LocalHost::getLocalIPAddresses(void) const { return local_ip_addresses; } /** * Getter for cached ipv4 interface names */ const std::vector<std::string>& LocalHost::getLocalIPv4Addresses(void) const { return local_ipv4_addresses; } /** * Getter for cached ipv6 interface names */ const std::vector<std::string>& LocalHost::getLocalIPv6Addresses(void) const { return local_ipv6_addresses; } /** * Setter to cache the interface names */ void LocalHost::cacheLocalIPAddresses(const std::vector<std::string> &local_ip_addresses) { this->local_ip_addresses = local_ip_addresses; local_ipv4_addresses.clear(); local_ipv6_addresses.clear(); for (auto& a : local_ip_addresses) { if (AddressConversion::isIpv4(a) == true) { local_ipv4_addresses.push_back(a); } else if (AddressConversion::isIpv6(a) == true) { local_ipv6_addresses.push_back(a); } } } /** * Getter for cached interface informations */ const std::vector<LocalHost::InterfaceInfo> &LocalHost::getLocalInterfaceInfos(void) const { return local_interface_infos; } /** * Setter to cache the interface informations */ void LocalHost::cacheLocalInterfaceInfos(const std::vector<LocalHost::InterfaceInfo> &infos) { local_interface_infos = infos; } /** * Getter for obtaining the mac address for a given ip address that is associated with a local interface */ const std::string LocalHost::getMacAddress(const std::string &local_ip_address) const { for (auto &info : local_interface_infos) { for (auto &addr : info.ip_addresses) { if (local_ip_address == addr) { return info.mac_address; } } } return ""; } /** * Getter for obtaining the interface name for a given ip address that is associated with a local interface */ const std::string LocalHost::getInterfaceName(const std::string& local_ip_address) const { for (auto& info : local_interface_infos) { for (auto& addr : info.ip_addresses) { if (local_ip_address == addr) { return info.if_name; } } } return ""; } /** * Getter for obtaining the interface index for a given ip address that is associated with a local interface. * This is needed for setting up ipv6 multicast sockets. */ const uint32_t LocalHost::getInterfaceIndex(const std::string & local_ip_address) const { for (auto& info : local_interface_infos) { for (auto &addr : info.ip_addresses) { if (addr == local_ip_address) { return info.if_index; } } } return (uint32_t)-1; } /** * Getter for obtaining the interface address prefix length for a given ip address that is associated with a local interface. */ const uint32_t LocalHost::getInterfacePrefixLength(const std::string& local_ip_address) const { for (auto& info : local_interface_infos) { auto it = info.ip_address_prefix_lengths.find(local_ip_address); if (it != info.ip_address_prefix_lengths.end()) { return it->second; } } return (uint32_t)-1; } /** * Query the local hostname from the operating system. */ const std::string LocalHost::queryHostname(void) { char buffer[256]; if (gethostname(buffer, sizeof(buffer)) != 0) { perror("gethostname() failure"); return std::string(); } return std::string(buffer); } /** * Query all local ipv4 and ipv6 addresses from the operating system. */ std::vector<std::string> LocalHost::queryLocalIPAddresses(void) { std::vector<std::string> interfaces; char hostname[256]; if (gethostname(hostname, sizeof(hostname)) != 0) { perror("gethostname"); return interfaces; } struct addrinfo *info = NULL; if (getaddrinfo(hostname, NULL, NULL, &info) != 0) { perror("getaddrinfo"); return interfaces; } while (info != NULL) { if (info->ai_protocol == 0 && (info->ai_family == AF_INET || info->ai_family == AF_INET6)) { interfaces.push_back(AddressConversion::toString(*info->ai_addr)); } info = info->ai_next; } freeaddrinfo(info); return interfaces; } /** * Query information related to all local interfaces from the operating system. */ std::vector<LocalHost::InterfaceInfo> LocalHost::queryLocalInterfaceInfos(void) { std::vector<LocalHost::InterfaceInfo> addresses; #ifdef _WIN32 PIP_ADAPTER_ADDRESSES AdapterAdresses; DWORD dwBufLen = sizeof(PIP_ADAPTER_ADDRESSES); AdapterAdresses = (IP_ADAPTER_ADDRESSES *)malloc(sizeof(IP_ADAPTER_ADDRESSES)); if (AdapterAdresses == NULL) { perror("Error allocating memory needed to call GetAdaptersAddresses\n"); return addresses; } // Make an initial call to GetAdaptersAddresses to get the necessary size into the dwBufLen variable if (GetAdaptersAddresses(AF_UNSPEC, 0, NULL, AdapterAdresses, &dwBufLen) == ERROR_BUFFER_OVERFLOW) { free(AdapterAdresses); AdapterAdresses = (IP_ADAPTER_ADDRESSES *)malloc(dwBufLen); if (AdapterAdresses == NULL) { perror("Error allocating memory needed to call GetAdaptersAddresses\n"); return addresses; } } if (GetAdaptersAddresses(AF_UNSPEC, 0, NULL, AdapterAdresses, &dwBufLen) == NO_ERROR) { PIP_ADAPTER_ADDRESSES pAdapterAddresses = AdapterAdresses; while (pAdapterAddresses != NULL) { if (pAdapterAddresses->OperStatus == IF_OPER_STATUS::IfOperStatusUp && pAdapterAddresses->PhysicalAddressLength == 6) { // PhysicalAddressLength == 0 for loopback interfaces char mac_addr[18]; snprintf(mac_addr, sizeof(mac_addr), "%02X:%02X:%02X:%02X:%02X:%02X", pAdapterAddresses->PhysicalAddress[0], pAdapterAddresses->PhysicalAddress[1], pAdapterAddresses->PhysicalAddress[2], pAdapterAddresses->PhysicalAddress[3], pAdapterAddresses->PhysicalAddress[4], pAdapterAddresses->PhysicalAddress[5]); LocalHost::InterfaceInfo info; char friendly[256]; snprintf(friendly, sizeof(friendly), "%S", pAdapterAddresses->FriendlyName); info.if_name = std::string(friendly); info.if_index = pAdapterAddresses->Ipv6IfIndex; info.mac_address = mac_addr; PIP_ADAPTER_UNICAST_ADDRESS_LH unicast_address = pAdapterAddresses->FirstUnicastAddress; do { std::string ip_name = AddressConversion::toString(*(sockaddr*)(unicast_address->Address.lpSockaddr)); info.ip_addresses.push_back(ip_name); info.ip_address_prefix_lengths[ip_name] = unicast_address->OnLinkPrefixLength; fprintf(stdout, "address: %28.*s prefixlength: %d mac: %s name: \"%s\"\n", (int)ip_name.length(), ip_name.c_str(), unicast_address->OnLinkPrefixLength, mac_addr, info.if_name.c_str()); unicast_address = unicast_address->Next; } while (unicast_address != NULL); addresses.push_back(info); } pAdapterAddresses = pAdapterAddresses->Next; } } free(AdapterAdresses); #else int s = socket(PF_INET, SOCK_DGRAM, 0); struct ifconf ifc; struct ifreq* ifr; char buf[16384]; ifc.ifc_len = sizeof(buf); ifc.ifc_buf = buf; if (ioctl(s, SIOCGIFCONF, &ifc) == 0) { ifr = ifc.ifc_req; for (int i = 0; i < ifc.ifc_len;) { struct ifreq buffer; memset(&buffer, 0x00, sizeof(buffer)); strcpy(buffer.ifr_name, ifr->ifr_name); InterfaceInfo info; info.if_name = std::string(buffer.ifr_name); info.if_index = if_nametoindex(buffer.ifr_name); std::string ip_name = AddressConversion::toString(ifr->ifr_ifru.ifru_addr); info.ip_addresses.push_back(ip_name); #ifndef __APPLE__ if (ioctl(s, SIOCGIFHWADDR, &buffer) == 0) { struct sockaddr saddr = buffer.ifr_ifru.ifru_hwaddr; char mac_addr[18]; snprintf(mac_addr, sizeof(mac_addr), "%02X:%02X:%02X:%02X:%02X:%02X", (uint8_t)saddr.sa_data[0], (uint8_t)saddr.sa_data[1], (uint8_t)saddr.sa_data[2], (uint8_t)saddr.sa_data[3], (uint8_t)saddr.sa_data[4], (uint8_t)saddr.sa_data[5]); info.mac_address = mac_addr; } size_t len = sizeof(struct ifreq); /* try to get network mask */ uint32_t prefix = 0; if (ioctl(s, SIOCGIFNETMASK, &buffer) == 0) { struct sockaddr smask = buffer.ifr_ifru.ifru_netmask; if (smask.sa_family == AF_INET) { struct sockaddr_in& smaskv4 = AddressConversion::toSockAddrIn(smask); uint32_t saddr = smaskv4.sin_addr.s_addr; for (int i = 0; i < 32; ++i) { if ((saddr & (1u << i)) == 0) break; ++prefix; } } else if (smask.sa_family == AF_INET6) { struct sockaddr_in6 smaskv6 = AddressConversion::toSockAddrIn6(smask); for (int i = 0; i < sizeof(smaskv6.sin6_addr.s6_addr); ++i) { uint8_t b = smaskv6.sin6_addr.s6_addr[i]; for (int j = 0; j < 8; ++j) { if ((b & (1u << j)) == 0) break; ++prefix; } } } } info.ip_address_prefix_lengths[ip_name] = prefix; fprintf(stdout, "address: %28.*s prefixlength: %d mac: %s name: \"%s\"\n", (int)ip_name.length(), ip_name.c_str(), prefix, info.mac_address.c_str(), info.if_name.c_str()); #else size_t len = IFNAMSIZ + ifr->ifr_addr.sa_len; #endif addresses.push_back(info); ifr = (struct ifreq*)((char*)ifr + len); i += len; } } close(s); #endif return addresses; } /** * Platform neutral sleep method. */ void LocalHost::sleep(uint32_t millis) { #ifdef _WIN32 Sleep(millis); #else ::sleep(millis / 1000); #endif } /** * Platform neutral method to get a tick count provided in ms ticks; this is useful for timing purposes. */ uint64_t LocalHost::getTickCountInMs(void) { // return a tick counter with ms resolution #ifdef _WIN32 return GetTickCount64(); #else struct timespec spec; if (clock_gettime(CLOCK_MONOTONIC, &spec) == -1) { abort(); } return spec.tv_sec * 1000 + spec.tv_nsec / 1e6; #endif } /** * Platform neutral method to get the unix epoch time in ms. */ uint64_t LocalHost::getUnixEpochTimeInMs(void) { #ifdef _WIN32 std::chrono::system_clock::duration time = std::chrono::system_clock::now().time_since_epoch(); std::chrono::system_clock::period period = std::chrono::system_clock::period(); return (time.count() * period.num) / (period.den/1000); #else struct timespec spec; if (clock_gettime(CLOCK_REALTIME, &spec) == -1) { abort(); } return spec.tv_sec * 1000 + spec.tv_nsec / 1e6; #endif } /** * Match given ip address to local interface ip address that resides on the same subnet. */ const std::string LocalHost::getMatchingLocalIPAddress(std::string ip_address) const { if (AddressConversion::isIpv4(ip_address) == true) { struct in_addr in_ip_address = AddressConversion::toInAddress(ip_address); for (auto& if_addr : local_ipv4_addresses) { struct in_addr in_if_addr = AddressConversion::toInAddress(if_addr); uint32_t if_prefix_length = LocalHost::getInterfacePrefixLength(if_addr); if (AddressConversion::resideOnSameSubnet(in_if_addr, in_ip_address, if_prefix_length) == true) { return if_addr; } } } else if (AddressConversion::isIpv6(ip_address) == true) { struct in6_addr in_ip_address = AddressConversion::toIn6Address(ip_address); for (auto& if_addr : local_ipv6_addresses) { struct in6_addr in_if_addr = AddressConversion::toIn6Address(if_addr); uint32_t if_prefix_length = LocalHost::getInterfacePrefixLength(if_addr); if (AddressConversion::resideOnSameSubnet(in_if_addr, in_ip_address, if_prefix_length) == true) { return if_addr; } } } return ""; }
34.671264
208
0.612717
RalfOGit
f6635f4eacffc353f82acd3b6dfca6a505eaffcf
1,854
cpp
C++
folly/test/MemcpyTest.cpp
tedjp/folly
243fbe8d9331c61ac2b29e80b623c80b8226fe6c
[ "Apache-2.0" ]
1
2021-07-17T07:06:28.000Z
2021-07-17T07:06:28.000Z
folly/test/MemcpyTest.cpp
tedjp/folly
243fbe8d9331c61ac2b29e80b623c80b8226fe6c
[ "Apache-2.0" ]
null
null
null
folly/test/MemcpyTest.cpp
tedjp/folly
243fbe8d9331c61ac2b29e80b623c80b8226fe6c
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2016 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <folly/Portability.h> #include <gtest/gtest.h> namespace { constexpr size_t kSize = 4096 * 4; char src[kSize]; char dst[kSize]; void init() { for (size_t i = 0; i < kSize; ++i) { src[i] = static_cast<char>(i); dst[i] = static_cast<char>(255 - i); } } } TEST(memcpy, zero_len) UBSAN_DISABLE("nonnull-attribute") { // If length is 0, we shouldn't touch any memory. So this should // not crash. char* srcNull = nullptr; char* dstNull = nullptr; memcpy(dstNull, srcNull, 0); } // Test copy `len' bytes and verify that exactly `len' bytes are copied. void testLen(size_t len) { if (len > kSize) { return; } init(); memcpy(dst, src, len); for (size_t i = 0; i < len; ++i) { EXPECT_EQ(src[i], static_cast<char>(i)); EXPECT_EQ(src[i], dst[i]); } if (len < kSize) { EXPECT_EQ(src[len], static_cast<char>(len)); EXPECT_EQ(dst[len], static_cast<char>(255 - len)); } } TEST(memcpy, small) { for (size_t len = 1; len < 8; ++len) { testLen(len); } } TEST(memcpy, main) { for (size_t len = 8; len < 128; ++len) { testLen(len); } for (size_t len = 128; len < kSize; len += 128) { testLen(len); } for (size_t len = 128; len < kSize; len += 73) { testLen(len); } }
23.468354
75
0.639159
tedjp
f6645b48d78a9bd0fa4b716b3ab55f039175f2e9
58,765
cxx
C++
SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimFlowPlant_ChillerHeater_PerformanceElectricEIR.cxx
EnEff-BIM/EnEffBIM-Framework
6328d39b498dc4065a60b5cc9370b8c2a9a1cddf
[ "MIT" ]
3
2016-05-30T15:12:16.000Z
2022-03-22T08:11:13.000Z
SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimFlowPlant_ChillerHeater_PerformanceElectricEIR.cxx
EnEff-BIM/EnEffBIM-Framework
6328d39b498dc4065a60b5cc9370b8c2a9a1cddf
[ "MIT" ]
21
2016-06-13T11:33:45.000Z
2017-05-23T09:46:52.000Z
SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimFlowPlant_ChillerHeater_PerformanceElectricEIR.cxx
EnEff-BIM/EnEffBIM-Framework
6328d39b498dc4065a60b5cc9370b8c2a9a1cddf
[ "MIT" ]
null
null
null
// Copyright (c) 2005-2014 Code Synthesis Tools CC // // This program was generated by CodeSynthesis XSD, an XML Schema to // C++ data binding compiler. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as // published by the Free Software Foundation. // // 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 St, Fifth Floor, Boston, MA 02110-1301 USA // // In addition, as a special exception, Code Synthesis Tools CC gives // permission to link this program with the Xerces-C++ library (or with // modified versions of Xerces-C++ that use the same license as Xerces-C++), // and distribute linked combinations including the two. You must obey // the GNU General Public License version 2 in all respects for all of // the code used other than Xerces-C++. If you modify this copy of the // program, you may extend this exception to your version of the program, // but you are not obligated to do so. If you do not wish to do so, delete // this exception statement from your version. // // Furthermore, Code Synthesis Tools CC makes a special exception for // the Free/Libre and Open Source Software (FLOSS) which is described // in the accompanying FLOSSE file. // // Begin prologue. // // // End prologue. #include <xsd/cxx/pre.hxx> #include "SimFlowPlant_ChillerHeater_PerformanceElectricEIR.hxx" namespace schema { namespace simxml { namespace MepModel { // SimFlowPlant_ChillerHeater_PerformanceElectricEIR // const SimFlowPlant_ChillerHeater_PerformanceElectricEIR::SimFlowPlant_RefCoolModeEvaporatorCap_optional& SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_RefCoolModeEvaporatorCap () const { return this->SimFlowPlant_RefCoolModeEvaporatorCap_; } SimFlowPlant_ChillerHeater_PerformanceElectricEIR::SimFlowPlant_RefCoolModeEvaporatorCap_optional& SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_RefCoolModeEvaporatorCap () { return this->SimFlowPlant_RefCoolModeEvaporatorCap_; } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_RefCoolModeEvaporatorCap (const SimFlowPlant_RefCoolModeEvaporatorCap_type& x) { this->SimFlowPlant_RefCoolModeEvaporatorCap_.set (x); } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_RefCoolModeEvaporatorCap (const SimFlowPlant_RefCoolModeEvaporatorCap_optional& x) { this->SimFlowPlant_RefCoolModeEvaporatorCap_ = x; } const SimFlowPlant_ChillerHeater_PerformanceElectricEIR::SimFlowPlant_RefCoolModeCOP_optional& SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_RefCoolModeCOP () const { return this->SimFlowPlant_RefCoolModeCOP_; } SimFlowPlant_ChillerHeater_PerformanceElectricEIR::SimFlowPlant_RefCoolModeCOP_optional& SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_RefCoolModeCOP () { return this->SimFlowPlant_RefCoolModeCOP_; } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_RefCoolModeCOP (const SimFlowPlant_RefCoolModeCOP_type& x) { this->SimFlowPlant_RefCoolModeCOP_.set (x); } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_RefCoolModeCOP (const SimFlowPlant_RefCoolModeCOP_optional& x) { this->SimFlowPlant_RefCoolModeCOP_ = x; } const SimFlowPlant_ChillerHeater_PerformanceElectricEIR::SimFlowPlant_RefCoolModeLeavingChilledWaterTemp_optional& SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_RefCoolModeLeavingChilledWaterTemp () const { return this->SimFlowPlant_RefCoolModeLeavingChilledWaterTemp_; } SimFlowPlant_ChillerHeater_PerformanceElectricEIR::SimFlowPlant_RefCoolModeLeavingChilledWaterTemp_optional& SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_RefCoolModeLeavingChilledWaterTemp () { return this->SimFlowPlant_RefCoolModeLeavingChilledWaterTemp_; } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_RefCoolModeLeavingChilledWaterTemp (const SimFlowPlant_RefCoolModeLeavingChilledWaterTemp_type& x) { this->SimFlowPlant_RefCoolModeLeavingChilledWaterTemp_.set (x); } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_RefCoolModeLeavingChilledWaterTemp (const SimFlowPlant_RefCoolModeLeavingChilledWaterTemp_optional& x) { this->SimFlowPlant_RefCoolModeLeavingChilledWaterTemp_ = x; } const SimFlowPlant_ChillerHeater_PerformanceElectricEIR::SimFlowPlant_RefCoolModeEnteringCondFluidTemp_optional& SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_RefCoolModeEnteringCondFluidTemp () const { return this->SimFlowPlant_RefCoolModeEnteringCondFluidTemp_; } SimFlowPlant_ChillerHeater_PerformanceElectricEIR::SimFlowPlant_RefCoolModeEnteringCondFluidTemp_optional& SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_RefCoolModeEnteringCondFluidTemp () { return this->SimFlowPlant_RefCoolModeEnteringCondFluidTemp_; } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_RefCoolModeEnteringCondFluidTemp (const SimFlowPlant_RefCoolModeEnteringCondFluidTemp_type& x) { this->SimFlowPlant_RefCoolModeEnteringCondFluidTemp_.set (x); } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_RefCoolModeEnteringCondFluidTemp (const SimFlowPlant_RefCoolModeEnteringCondFluidTemp_optional& x) { this->SimFlowPlant_RefCoolModeEnteringCondFluidTemp_ = x; } const SimFlowPlant_ChillerHeater_PerformanceElectricEIR::SimFlowPlant_RefCoolModeLeavingCondWaterTemp_optional& SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_RefCoolModeLeavingCondWaterTemp () const { return this->SimFlowPlant_RefCoolModeLeavingCondWaterTemp_; } SimFlowPlant_ChillerHeater_PerformanceElectricEIR::SimFlowPlant_RefCoolModeLeavingCondWaterTemp_optional& SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_RefCoolModeLeavingCondWaterTemp () { return this->SimFlowPlant_RefCoolModeLeavingCondWaterTemp_; } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_RefCoolModeLeavingCondWaterTemp (const SimFlowPlant_RefCoolModeLeavingCondWaterTemp_type& x) { this->SimFlowPlant_RefCoolModeLeavingCondWaterTemp_.set (x); } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_RefCoolModeLeavingCondWaterTemp (const SimFlowPlant_RefCoolModeLeavingCondWaterTemp_optional& x) { this->SimFlowPlant_RefCoolModeLeavingCondWaterTemp_ = x; } const SimFlowPlant_ChillerHeater_PerformanceElectricEIR::SimFlowPlant_RefHeatModeCoolCapRatio_optional& SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_RefHeatModeCoolCapRatio () const { return this->SimFlowPlant_RefHeatModeCoolCapRatio_; } SimFlowPlant_ChillerHeater_PerformanceElectricEIR::SimFlowPlant_RefHeatModeCoolCapRatio_optional& SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_RefHeatModeCoolCapRatio () { return this->SimFlowPlant_RefHeatModeCoolCapRatio_; } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_RefHeatModeCoolCapRatio (const SimFlowPlant_RefHeatModeCoolCapRatio_type& x) { this->SimFlowPlant_RefHeatModeCoolCapRatio_.set (x); } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_RefHeatModeCoolCapRatio (const SimFlowPlant_RefHeatModeCoolCapRatio_optional& x) { this->SimFlowPlant_RefHeatModeCoolCapRatio_ = x; } const SimFlowPlant_ChillerHeater_PerformanceElectricEIR::SimFlowPlant_RefHeatModeCoolPwrInputRatio_optional& SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_RefHeatModeCoolPwrInputRatio () const { return this->SimFlowPlant_RefHeatModeCoolPwrInputRatio_; } SimFlowPlant_ChillerHeater_PerformanceElectricEIR::SimFlowPlant_RefHeatModeCoolPwrInputRatio_optional& SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_RefHeatModeCoolPwrInputRatio () { return this->SimFlowPlant_RefHeatModeCoolPwrInputRatio_; } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_RefHeatModeCoolPwrInputRatio (const SimFlowPlant_RefHeatModeCoolPwrInputRatio_type& x) { this->SimFlowPlant_RefHeatModeCoolPwrInputRatio_.set (x); } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_RefHeatModeCoolPwrInputRatio (const SimFlowPlant_RefHeatModeCoolPwrInputRatio_optional& x) { this->SimFlowPlant_RefHeatModeCoolPwrInputRatio_ = x; } const SimFlowPlant_ChillerHeater_PerformanceElectricEIR::SimFlowPlant_RefHeatModeLeavingChilledWaterTemp_optional& SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_RefHeatModeLeavingChilledWaterTemp () const { return this->SimFlowPlant_RefHeatModeLeavingChilledWaterTemp_; } SimFlowPlant_ChillerHeater_PerformanceElectricEIR::SimFlowPlant_RefHeatModeLeavingChilledWaterTemp_optional& SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_RefHeatModeLeavingChilledWaterTemp () { return this->SimFlowPlant_RefHeatModeLeavingChilledWaterTemp_; } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_RefHeatModeLeavingChilledWaterTemp (const SimFlowPlant_RefHeatModeLeavingChilledWaterTemp_type& x) { this->SimFlowPlant_RefHeatModeLeavingChilledWaterTemp_.set (x); } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_RefHeatModeLeavingChilledWaterTemp (const SimFlowPlant_RefHeatModeLeavingChilledWaterTemp_optional& x) { this->SimFlowPlant_RefHeatModeLeavingChilledWaterTemp_ = x; } const SimFlowPlant_ChillerHeater_PerformanceElectricEIR::SimFlowPlant_RefHeatModeLeavingCondWaterTemp_optional& SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_RefHeatModeLeavingCondWaterTemp () const { return this->SimFlowPlant_RefHeatModeLeavingCondWaterTemp_; } SimFlowPlant_ChillerHeater_PerformanceElectricEIR::SimFlowPlant_RefHeatModeLeavingCondWaterTemp_optional& SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_RefHeatModeLeavingCondWaterTemp () { return this->SimFlowPlant_RefHeatModeLeavingCondWaterTemp_; } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_RefHeatModeLeavingCondWaterTemp (const SimFlowPlant_RefHeatModeLeavingCondWaterTemp_type& x) { this->SimFlowPlant_RefHeatModeLeavingCondWaterTemp_.set (x); } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_RefHeatModeLeavingCondWaterTemp (const SimFlowPlant_RefHeatModeLeavingCondWaterTemp_optional& x) { this->SimFlowPlant_RefHeatModeLeavingCondWaterTemp_ = x; } const SimFlowPlant_ChillerHeater_PerformanceElectricEIR::SimFlowPlant_RefHeatModeEnteringCondFluidTemp_optional& SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_RefHeatModeEnteringCondFluidTemp () const { return this->SimFlowPlant_RefHeatModeEnteringCondFluidTemp_; } SimFlowPlant_ChillerHeater_PerformanceElectricEIR::SimFlowPlant_RefHeatModeEnteringCondFluidTemp_optional& SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_RefHeatModeEnteringCondFluidTemp () { return this->SimFlowPlant_RefHeatModeEnteringCondFluidTemp_; } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_RefHeatModeEnteringCondFluidTemp (const SimFlowPlant_RefHeatModeEnteringCondFluidTemp_type& x) { this->SimFlowPlant_RefHeatModeEnteringCondFluidTemp_.set (x); } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_RefHeatModeEnteringCondFluidTemp (const SimFlowPlant_RefHeatModeEnteringCondFluidTemp_optional& x) { this->SimFlowPlant_RefHeatModeEnteringCondFluidTemp_ = x; } const SimFlowPlant_ChillerHeater_PerformanceElectricEIR::SimFlowPlant_HeatModeEnteringChilledWaterTempLowLimit_optional& SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_HeatModeEnteringChilledWaterTempLowLimit () const { return this->SimFlowPlant_HeatModeEnteringChilledWaterTempLowLimit_; } SimFlowPlant_ChillerHeater_PerformanceElectricEIR::SimFlowPlant_HeatModeEnteringChilledWaterTempLowLimit_optional& SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_HeatModeEnteringChilledWaterTempLowLimit () { return this->SimFlowPlant_HeatModeEnteringChilledWaterTempLowLimit_; } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_HeatModeEnteringChilledWaterTempLowLimit (const SimFlowPlant_HeatModeEnteringChilledWaterTempLowLimit_type& x) { this->SimFlowPlant_HeatModeEnteringChilledWaterTempLowLimit_.set (x); } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_HeatModeEnteringChilledWaterTempLowLimit (const SimFlowPlant_HeatModeEnteringChilledWaterTempLowLimit_optional& x) { this->SimFlowPlant_HeatModeEnteringChilledWaterTempLowLimit_ = x; } const SimFlowPlant_ChillerHeater_PerformanceElectricEIR::SimFlowPlant_ChilledWaterFlowModeType_optional& SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_ChilledWaterFlowModeType () const { return this->SimFlowPlant_ChilledWaterFlowModeType_; } SimFlowPlant_ChillerHeater_PerformanceElectricEIR::SimFlowPlant_ChilledWaterFlowModeType_optional& SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_ChilledWaterFlowModeType () { return this->SimFlowPlant_ChilledWaterFlowModeType_; } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_ChilledWaterFlowModeType (const SimFlowPlant_ChilledWaterFlowModeType_type& x) { this->SimFlowPlant_ChilledWaterFlowModeType_.set (x); } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_ChilledWaterFlowModeType (const SimFlowPlant_ChilledWaterFlowModeType_optional& x) { this->SimFlowPlant_ChilledWaterFlowModeType_ = x; } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_ChilledWaterFlowModeType (::std::auto_ptr< SimFlowPlant_ChilledWaterFlowModeType_type > x) { this->SimFlowPlant_ChilledWaterFlowModeType_.set (x); } const SimFlowPlant_ChillerHeater_PerformanceElectricEIR::SimFlowPlant_CmprssrMotorEffic_optional& SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_CmprssrMotorEffic () const { return this->SimFlowPlant_CmprssrMotorEffic_; } SimFlowPlant_ChillerHeater_PerformanceElectricEIR::SimFlowPlant_CmprssrMotorEffic_optional& SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_CmprssrMotorEffic () { return this->SimFlowPlant_CmprssrMotorEffic_; } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_CmprssrMotorEffic (const SimFlowPlant_CmprssrMotorEffic_type& x) { this->SimFlowPlant_CmprssrMotorEffic_.set (x); } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_CmprssrMotorEffic (const SimFlowPlant_CmprssrMotorEffic_optional& x) { this->SimFlowPlant_CmprssrMotorEffic_ = x; } const SimFlowPlant_ChillerHeater_PerformanceElectricEIR::SimFlowPlant_CoolModeTempCurveCondWaterIndependentVar_optional& SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_CoolModeTempCurveCondWaterIndependentVar () const { return this->SimFlowPlant_CoolModeTempCurveCondWaterIndependentVar_; } SimFlowPlant_ChillerHeater_PerformanceElectricEIR::SimFlowPlant_CoolModeTempCurveCondWaterIndependentVar_optional& SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_CoolModeTempCurveCondWaterIndependentVar () { return this->SimFlowPlant_CoolModeTempCurveCondWaterIndependentVar_; } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_CoolModeTempCurveCondWaterIndependentVar (const SimFlowPlant_CoolModeTempCurveCondWaterIndependentVar_type& x) { this->SimFlowPlant_CoolModeTempCurveCondWaterIndependentVar_.set (x); } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_CoolModeTempCurveCondWaterIndependentVar (const SimFlowPlant_CoolModeTempCurveCondWaterIndependentVar_optional& x) { this->SimFlowPlant_CoolModeTempCurveCondWaterIndependentVar_ = x; } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_CoolModeTempCurveCondWaterIndependentVar (::std::auto_ptr< SimFlowPlant_CoolModeTempCurveCondWaterIndependentVar_type > x) { this->SimFlowPlant_CoolModeTempCurveCondWaterIndependentVar_.set (x); } const SimFlowPlant_ChillerHeater_PerformanceElectricEIR::SimFlowPlant_CoolModeCoolCapFuncofTempCurveName_optional& SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_CoolModeCoolCapFuncofTempCurveName () const { return this->SimFlowPlant_CoolModeCoolCapFuncofTempCurveName_; } SimFlowPlant_ChillerHeater_PerformanceElectricEIR::SimFlowPlant_CoolModeCoolCapFuncofTempCurveName_optional& SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_CoolModeCoolCapFuncofTempCurveName () { return this->SimFlowPlant_CoolModeCoolCapFuncofTempCurveName_; } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_CoolModeCoolCapFuncofTempCurveName (const SimFlowPlant_CoolModeCoolCapFuncofTempCurveName_type& x) { this->SimFlowPlant_CoolModeCoolCapFuncofTempCurveName_.set (x); } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_CoolModeCoolCapFuncofTempCurveName (const SimFlowPlant_CoolModeCoolCapFuncofTempCurveName_optional& x) { this->SimFlowPlant_CoolModeCoolCapFuncofTempCurveName_ = x; } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_CoolModeCoolCapFuncofTempCurveName (::std::auto_ptr< SimFlowPlant_CoolModeCoolCapFuncofTempCurveName_type > x) { this->SimFlowPlant_CoolModeCoolCapFuncofTempCurveName_.set (x); } const SimFlowPlant_ChillerHeater_PerformanceElectricEIR::SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofTempCurveName_optional& SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofTempCurveName () const { return this->SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofTempCurveName_; } SimFlowPlant_ChillerHeater_PerformanceElectricEIR::SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofTempCurveName_optional& SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofTempCurveName () { return this->SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofTempCurveName_; } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofTempCurveName (const SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofTempCurveName_type& x) { this->SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofTempCurveName_.set (x); } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofTempCurveName (const SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofTempCurveName_optional& x) { this->SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofTempCurveName_ = x; } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofTempCurveName (::std::auto_ptr< SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofTempCurveName_type > x) { this->SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofTempCurveName_.set (x); } const SimFlowPlant_ChillerHeater_PerformanceElectricEIR::SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName_optional& SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName () const { return this->SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName_; } SimFlowPlant_ChillerHeater_PerformanceElectricEIR::SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName_optional& SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName () { return this->SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName_; } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName (const SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName_type& x) { this->SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName_.set (x); } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName (const SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName_optional& x) { this->SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName_ = x; } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName (::std::auto_ptr< SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName_type > x) { this->SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName_.set (x); } const SimFlowPlant_ChillerHeater_PerformanceElectricEIR::SimFlowPlant_CoolModeCoolCapOptPartLoadRatio_optional& SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_CoolModeCoolCapOptPartLoadRatio () const { return this->SimFlowPlant_CoolModeCoolCapOptPartLoadRatio_; } SimFlowPlant_ChillerHeater_PerformanceElectricEIR::SimFlowPlant_CoolModeCoolCapOptPartLoadRatio_optional& SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_CoolModeCoolCapOptPartLoadRatio () { return this->SimFlowPlant_CoolModeCoolCapOptPartLoadRatio_; } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_CoolModeCoolCapOptPartLoadRatio (const SimFlowPlant_CoolModeCoolCapOptPartLoadRatio_type& x) { this->SimFlowPlant_CoolModeCoolCapOptPartLoadRatio_.set (x); } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_CoolModeCoolCapOptPartLoadRatio (const SimFlowPlant_CoolModeCoolCapOptPartLoadRatio_optional& x) { this->SimFlowPlant_CoolModeCoolCapOptPartLoadRatio_ = x; } const SimFlowPlant_ChillerHeater_PerformanceElectricEIR::SimFlowPlant_HeatModeTempCurveCondWaterIndependentVar_optional& SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_HeatModeTempCurveCondWaterIndependentVar () const { return this->SimFlowPlant_HeatModeTempCurveCondWaterIndependentVar_; } SimFlowPlant_ChillerHeater_PerformanceElectricEIR::SimFlowPlant_HeatModeTempCurveCondWaterIndependentVar_optional& SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_HeatModeTempCurveCondWaterIndependentVar () { return this->SimFlowPlant_HeatModeTempCurveCondWaterIndependentVar_; } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_HeatModeTempCurveCondWaterIndependentVar (const SimFlowPlant_HeatModeTempCurveCondWaterIndependentVar_type& x) { this->SimFlowPlant_HeatModeTempCurveCondWaterIndependentVar_.set (x); } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_HeatModeTempCurveCondWaterIndependentVar (const SimFlowPlant_HeatModeTempCurveCondWaterIndependentVar_optional& x) { this->SimFlowPlant_HeatModeTempCurveCondWaterIndependentVar_ = x; } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_HeatModeTempCurveCondWaterIndependentVar (::std::auto_ptr< SimFlowPlant_HeatModeTempCurveCondWaterIndependentVar_type > x) { this->SimFlowPlant_HeatModeTempCurveCondWaterIndependentVar_.set (x); } const SimFlowPlant_ChillerHeater_PerformanceElectricEIR::SimFlowPlant_HeatModeCoolCapFuncofTempCurveName_optional& SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_HeatModeCoolCapFuncofTempCurveName () const { return this->SimFlowPlant_HeatModeCoolCapFuncofTempCurveName_; } SimFlowPlant_ChillerHeater_PerformanceElectricEIR::SimFlowPlant_HeatModeCoolCapFuncofTempCurveName_optional& SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_HeatModeCoolCapFuncofTempCurveName () { return this->SimFlowPlant_HeatModeCoolCapFuncofTempCurveName_; } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_HeatModeCoolCapFuncofTempCurveName (const SimFlowPlant_HeatModeCoolCapFuncofTempCurveName_type& x) { this->SimFlowPlant_HeatModeCoolCapFuncofTempCurveName_.set (x); } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_HeatModeCoolCapFuncofTempCurveName (const SimFlowPlant_HeatModeCoolCapFuncofTempCurveName_optional& x) { this->SimFlowPlant_HeatModeCoolCapFuncofTempCurveName_ = x; } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_HeatModeCoolCapFuncofTempCurveName (::std::auto_ptr< SimFlowPlant_HeatModeCoolCapFuncofTempCurveName_type > x) { this->SimFlowPlant_HeatModeCoolCapFuncofTempCurveName_.set (x); } const SimFlowPlant_ChillerHeater_PerformanceElectricEIR::SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofTempCurveName_optional& SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofTempCurveName () const { return this->SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofTempCurveName_; } SimFlowPlant_ChillerHeater_PerformanceElectricEIR::SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofTempCurveName_optional& SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofTempCurveName () { return this->SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofTempCurveName_; } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofTempCurveName (const SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofTempCurveName_type& x) { this->SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofTempCurveName_.set (x); } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofTempCurveName (const SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofTempCurveName_optional& x) { this->SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofTempCurveName_ = x; } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofTempCurveName (::std::auto_ptr< SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofTempCurveName_type > x) { this->SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofTempCurveName_.set (x); } const SimFlowPlant_ChillerHeater_PerformanceElectricEIR::SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName_optional& SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName () const { return this->SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName_; } SimFlowPlant_ChillerHeater_PerformanceElectricEIR::SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName_optional& SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName () { return this->SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName_; } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName (const SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName_type& x) { this->SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName_.set (x); } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName (const SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName_optional& x) { this->SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName_ = x; } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName (::std::auto_ptr< SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName_type > x) { this->SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName_.set (x); } const SimFlowPlant_ChillerHeater_PerformanceElectricEIR::SimFlowPlant_HeatModeCoolCapOptPartLoadRatio_optional& SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_HeatModeCoolCapOptPartLoadRatio () const { return this->SimFlowPlant_HeatModeCoolCapOptPartLoadRatio_; } SimFlowPlant_ChillerHeater_PerformanceElectricEIR::SimFlowPlant_HeatModeCoolCapOptPartLoadRatio_optional& SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_HeatModeCoolCapOptPartLoadRatio () { return this->SimFlowPlant_HeatModeCoolCapOptPartLoadRatio_; } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_HeatModeCoolCapOptPartLoadRatio (const SimFlowPlant_HeatModeCoolCapOptPartLoadRatio_type& x) { this->SimFlowPlant_HeatModeCoolCapOptPartLoadRatio_.set (x); } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_HeatModeCoolCapOptPartLoadRatio (const SimFlowPlant_HeatModeCoolCapOptPartLoadRatio_optional& x) { this->SimFlowPlant_HeatModeCoolCapOptPartLoadRatio_ = x; } } } } #include <xsd/cxx/xml/dom/parsing-source.hxx> #include <xsd/cxx/tree/type-factory-map.hxx> namespace _xsd { static const ::xsd::cxx::tree::type_factory_plate< 0, char > type_factory_plate_init; } namespace schema { namespace simxml { namespace MepModel { // SimFlowPlant_ChillerHeater_PerformanceElectricEIR // SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_ChillerHeater_PerformanceElectricEIR () : ::schema::simxml::MepModel::SimFlowPlant_ChillerHeater (), SimFlowPlant_RefCoolModeEvaporatorCap_ (this), SimFlowPlant_RefCoolModeCOP_ (this), SimFlowPlant_RefCoolModeLeavingChilledWaterTemp_ (this), SimFlowPlant_RefCoolModeEnteringCondFluidTemp_ (this), SimFlowPlant_RefCoolModeLeavingCondWaterTemp_ (this), SimFlowPlant_RefHeatModeCoolCapRatio_ (this), SimFlowPlant_RefHeatModeCoolPwrInputRatio_ (this), SimFlowPlant_RefHeatModeLeavingChilledWaterTemp_ (this), SimFlowPlant_RefHeatModeLeavingCondWaterTemp_ (this), SimFlowPlant_RefHeatModeEnteringCondFluidTemp_ (this), SimFlowPlant_HeatModeEnteringChilledWaterTempLowLimit_ (this), SimFlowPlant_ChilledWaterFlowModeType_ (this), SimFlowPlant_CmprssrMotorEffic_ (this), SimFlowPlant_CoolModeTempCurveCondWaterIndependentVar_ (this), SimFlowPlant_CoolModeCoolCapFuncofTempCurveName_ (this), SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofTempCurveName_ (this), SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName_ (this), SimFlowPlant_CoolModeCoolCapOptPartLoadRatio_ (this), SimFlowPlant_HeatModeTempCurveCondWaterIndependentVar_ (this), SimFlowPlant_HeatModeCoolCapFuncofTempCurveName_ (this), SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofTempCurveName_ (this), SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName_ (this), SimFlowPlant_HeatModeCoolCapOptPartLoadRatio_ (this) { } SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_ChillerHeater_PerformanceElectricEIR (const RefId_type& RefId) : ::schema::simxml::MepModel::SimFlowPlant_ChillerHeater (RefId), SimFlowPlant_RefCoolModeEvaporatorCap_ (this), SimFlowPlant_RefCoolModeCOP_ (this), SimFlowPlant_RefCoolModeLeavingChilledWaterTemp_ (this), SimFlowPlant_RefCoolModeEnteringCondFluidTemp_ (this), SimFlowPlant_RefCoolModeLeavingCondWaterTemp_ (this), SimFlowPlant_RefHeatModeCoolCapRatio_ (this), SimFlowPlant_RefHeatModeCoolPwrInputRatio_ (this), SimFlowPlant_RefHeatModeLeavingChilledWaterTemp_ (this), SimFlowPlant_RefHeatModeLeavingCondWaterTemp_ (this), SimFlowPlant_RefHeatModeEnteringCondFluidTemp_ (this), SimFlowPlant_HeatModeEnteringChilledWaterTempLowLimit_ (this), SimFlowPlant_ChilledWaterFlowModeType_ (this), SimFlowPlant_CmprssrMotorEffic_ (this), SimFlowPlant_CoolModeTempCurveCondWaterIndependentVar_ (this), SimFlowPlant_CoolModeCoolCapFuncofTempCurveName_ (this), SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofTempCurveName_ (this), SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName_ (this), SimFlowPlant_CoolModeCoolCapOptPartLoadRatio_ (this), SimFlowPlant_HeatModeTempCurveCondWaterIndependentVar_ (this), SimFlowPlant_HeatModeCoolCapFuncofTempCurveName_ (this), SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofTempCurveName_ (this), SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName_ (this), SimFlowPlant_HeatModeCoolCapOptPartLoadRatio_ (this) { } SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_ChillerHeater_PerformanceElectricEIR (const SimFlowPlant_ChillerHeater_PerformanceElectricEIR& x, ::xml_schema::flags f, ::xml_schema::container* c) : ::schema::simxml::MepModel::SimFlowPlant_ChillerHeater (x, f, c), SimFlowPlant_RefCoolModeEvaporatorCap_ (x.SimFlowPlant_RefCoolModeEvaporatorCap_, f, this), SimFlowPlant_RefCoolModeCOP_ (x.SimFlowPlant_RefCoolModeCOP_, f, this), SimFlowPlant_RefCoolModeLeavingChilledWaterTemp_ (x.SimFlowPlant_RefCoolModeLeavingChilledWaterTemp_, f, this), SimFlowPlant_RefCoolModeEnteringCondFluidTemp_ (x.SimFlowPlant_RefCoolModeEnteringCondFluidTemp_, f, this), SimFlowPlant_RefCoolModeLeavingCondWaterTemp_ (x.SimFlowPlant_RefCoolModeLeavingCondWaterTemp_, f, this), SimFlowPlant_RefHeatModeCoolCapRatio_ (x.SimFlowPlant_RefHeatModeCoolCapRatio_, f, this), SimFlowPlant_RefHeatModeCoolPwrInputRatio_ (x.SimFlowPlant_RefHeatModeCoolPwrInputRatio_, f, this), SimFlowPlant_RefHeatModeLeavingChilledWaterTemp_ (x.SimFlowPlant_RefHeatModeLeavingChilledWaterTemp_, f, this), SimFlowPlant_RefHeatModeLeavingCondWaterTemp_ (x.SimFlowPlant_RefHeatModeLeavingCondWaterTemp_, f, this), SimFlowPlant_RefHeatModeEnteringCondFluidTemp_ (x.SimFlowPlant_RefHeatModeEnteringCondFluidTemp_, f, this), SimFlowPlant_HeatModeEnteringChilledWaterTempLowLimit_ (x.SimFlowPlant_HeatModeEnteringChilledWaterTempLowLimit_, f, this), SimFlowPlant_ChilledWaterFlowModeType_ (x.SimFlowPlant_ChilledWaterFlowModeType_, f, this), SimFlowPlant_CmprssrMotorEffic_ (x.SimFlowPlant_CmprssrMotorEffic_, f, this), SimFlowPlant_CoolModeTempCurveCondWaterIndependentVar_ (x.SimFlowPlant_CoolModeTempCurveCondWaterIndependentVar_, f, this), SimFlowPlant_CoolModeCoolCapFuncofTempCurveName_ (x.SimFlowPlant_CoolModeCoolCapFuncofTempCurveName_, f, this), SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofTempCurveName_ (x.SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofTempCurveName_, f, this), SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName_ (x.SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName_, f, this), SimFlowPlant_CoolModeCoolCapOptPartLoadRatio_ (x.SimFlowPlant_CoolModeCoolCapOptPartLoadRatio_, f, this), SimFlowPlant_HeatModeTempCurveCondWaterIndependentVar_ (x.SimFlowPlant_HeatModeTempCurveCondWaterIndependentVar_, f, this), SimFlowPlant_HeatModeCoolCapFuncofTempCurveName_ (x.SimFlowPlant_HeatModeCoolCapFuncofTempCurveName_, f, this), SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofTempCurveName_ (x.SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofTempCurveName_, f, this), SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName_ (x.SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName_, f, this), SimFlowPlant_HeatModeCoolCapOptPartLoadRatio_ (x.SimFlowPlant_HeatModeCoolCapOptPartLoadRatio_, f, this) { } SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: SimFlowPlant_ChillerHeater_PerformanceElectricEIR (const ::xercesc::DOMElement& e, ::xml_schema::flags f, ::xml_schema::container* c) : ::schema::simxml::MepModel::SimFlowPlant_ChillerHeater (e, f | ::xml_schema::flags::base, c), SimFlowPlant_RefCoolModeEvaporatorCap_ (this), SimFlowPlant_RefCoolModeCOP_ (this), SimFlowPlant_RefCoolModeLeavingChilledWaterTemp_ (this), SimFlowPlant_RefCoolModeEnteringCondFluidTemp_ (this), SimFlowPlant_RefCoolModeLeavingCondWaterTemp_ (this), SimFlowPlant_RefHeatModeCoolCapRatio_ (this), SimFlowPlant_RefHeatModeCoolPwrInputRatio_ (this), SimFlowPlant_RefHeatModeLeavingChilledWaterTemp_ (this), SimFlowPlant_RefHeatModeLeavingCondWaterTemp_ (this), SimFlowPlant_RefHeatModeEnteringCondFluidTemp_ (this), SimFlowPlant_HeatModeEnteringChilledWaterTempLowLimit_ (this), SimFlowPlant_ChilledWaterFlowModeType_ (this), SimFlowPlant_CmprssrMotorEffic_ (this), SimFlowPlant_CoolModeTempCurveCondWaterIndependentVar_ (this), SimFlowPlant_CoolModeCoolCapFuncofTempCurveName_ (this), SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofTempCurveName_ (this), SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName_ (this), SimFlowPlant_CoolModeCoolCapOptPartLoadRatio_ (this), SimFlowPlant_HeatModeTempCurveCondWaterIndependentVar_ (this), SimFlowPlant_HeatModeCoolCapFuncofTempCurveName_ (this), SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofTempCurveName_ (this), SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName_ (this), SimFlowPlant_HeatModeCoolCapOptPartLoadRatio_ (this) { if ((f & ::xml_schema::flags::base) == 0) { ::xsd::cxx::xml::dom::parser< char > p (e, true, false, true); this->parse (p, f); } } void SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: parse (::xsd::cxx::xml::dom::parser< char >& p, ::xml_schema::flags f) { this->::schema::simxml::MepModel::SimFlowPlant_ChillerHeater::parse (p, f); for (; p.more_content (); p.next_content (false)) { const ::xercesc::DOMElement& i (p.cur_element ()); const ::xsd::cxx::xml::qualified_name< char > n ( ::xsd::cxx::xml::dom::name< char > (i)); // SimFlowPlant_RefCoolModeEvaporatorCap // if (n.name () == "SimFlowPlant_RefCoolModeEvaporatorCap" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { if (!this->SimFlowPlant_RefCoolModeEvaporatorCap_) { this->SimFlowPlant_RefCoolModeEvaporatorCap_.set (SimFlowPlant_RefCoolModeEvaporatorCap_traits::create (i, f, this)); continue; } } // SimFlowPlant_RefCoolModeCOP // if (n.name () == "SimFlowPlant_RefCoolModeCOP" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { if (!this->SimFlowPlant_RefCoolModeCOP_) { this->SimFlowPlant_RefCoolModeCOP_.set (SimFlowPlant_RefCoolModeCOP_traits::create (i, f, this)); continue; } } // SimFlowPlant_RefCoolModeLeavingChilledWaterTemp // if (n.name () == "SimFlowPlant_RefCoolModeLeavingChilledWaterTemp" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { if (!this->SimFlowPlant_RefCoolModeLeavingChilledWaterTemp_) { this->SimFlowPlant_RefCoolModeLeavingChilledWaterTemp_.set (SimFlowPlant_RefCoolModeLeavingChilledWaterTemp_traits::create (i, f, this)); continue; } } // SimFlowPlant_RefCoolModeEnteringCondFluidTemp // if (n.name () == "SimFlowPlant_RefCoolModeEnteringCondFluidTemp" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { if (!this->SimFlowPlant_RefCoolModeEnteringCondFluidTemp_) { this->SimFlowPlant_RefCoolModeEnteringCondFluidTemp_.set (SimFlowPlant_RefCoolModeEnteringCondFluidTemp_traits::create (i, f, this)); continue; } } // SimFlowPlant_RefCoolModeLeavingCondWaterTemp // if (n.name () == "SimFlowPlant_RefCoolModeLeavingCondWaterTemp" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { if (!this->SimFlowPlant_RefCoolModeLeavingCondWaterTemp_) { this->SimFlowPlant_RefCoolModeLeavingCondWaterTemp_.set (SimFlowPlant_RefCoolModeLeavingCondWaterTemp_traits::create (i, f, this)); continue; } } // SimFlowPlant_RefHeatModeCoolCapRatio // if (n.name () == "SimFlowPlant_RefHeatModeCoolCapRatio" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { if (!this->SimFlowPlant_RefHeatModeCoolCapRatio_) { this->SimFlowPlant_RefHeatModeCoolCapRatio_.set (SimFlowPlant_RefHeatModeCoolCapRatio_traits::create (i, f, this)); continue; } } // SimFlowPlant_RefHeatModeCoolPwrInputRatio // if (n.name () == "SimFlowPlant_RefHeatModeCoolPwrInputRatio" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { if (!this->SimFlowPlant_RefHeatModeCoolPwrInputRatio_) { this->SimFlowPlant_RefHeatModeCoolPwrInputRatio_.set (SimFlowPlant_RefHeatModeCoolPwrInputRatio_traits::create (i, f, this)); continue; } } // SimFlowPlant_RefHeatModeLeavingChilledWaterTemp // if (n.name () == "SimFlowPlant_RefHeatModeLeavingChilledWaterTemp" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { if (!this->SimFlowPlant_RefHeatModeLeavingChilledWaterTemp_) { this->SimFlowPlant_RefHeatModeLeavingChilledWaterTemp_.set (SimFlowPlant_RefHeatModeLeavingChilledWaterTemp_traits::create (i, f, this)); continue; } } // SimFlowPlant_RefHeatModeLeavingCondWaterTemp // if (n.name () == "SimFlowPlant_RefHeatModeLeavingCondWaterTemp" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { if (!this->SimFlowPlant_RefHeatModeLeavingCondWaterTemp_) { this->SimFlowPlant_RefHeatModeLeavingCondWaterTemp_.set (SimFlowPlant_RefHeatModeLeavingCondWaterTemp_traits::create (i, f, this)); continue; } } // SimFlowPlant_RefHeatModeEnteringCondFluidTemp // if (n.name () == "SimFlowPlant_RefHeatModeEnteringCondFluidTemp" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { if (!this->SimFlowPlant_RefHeatModeEnteringCondFluidTemp_) { this->SimFlowPlant_RefHeatModeEnteringCondFluidTemp_.set (SimFlowPlant_RefHeatModeEnteringCondFluidTemp_traits::create (i, f, this)); continue; } } // SimFlowPlant_HeatModeEnteringChilledWaterTempLowLimit // if (n.name () == "SimFlowPlant_HeatModeEnteringChilledWaterTempLowLimit" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { if (!this->SimFlowPlant_HeatModeEnteringChilledWaterTempLowLimit_) { this->SimFlowPlant_HeatModeEnteringChilledWaterTempLowLimit_.set (SimFlowPlant_HeatModeEnteringChilledWaterTempLowLimit_traits::create (i, f, this)); continue; } } // SimFlowPlant_ChilledWaterFlowModeType // if (n.name () == "SimFlowPlant_ChilledWaterFlowModeType" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { ::std::auto_ptr< SimFlowPlant_ChilledWaterFlowModeType_type > r ( SimFlowPlant_ChilledWaterFlowModeType_traits::create (i, f, this)); if (!this->SimFlowPlant_ChilledWaterFlowModeType_) { this->SimFlowPlant_ChilledWaterFlowModeType_.set (r); continue; } } // SimFlowPlant_CmprssrMotorEffic // if (n.name () == "SimFlowPlant_CmprssrMotorEffic" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { if (!this->SimFlowPlant_CmprssrMotorEffic_) { this->SimFlowPlant_CmprssrMotorEffic_.set (SimFlowPlant_CmprssrMotorEffic_traits::create (i, f, this)); continue; } } // SimFlowPlant_CoolModeTempCurveCondWaterIndependentVar // if (n.name () == "SimFlowPlant_CoolModeTempCurveCondWaterIndependentVar" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { ::std::auto_ptr< SimFlowPlant_CoolModeTempCurveCondWaterIndependentVar_type > r ( SimFlowPlant_CoolModeTempCurveCondWaterIndependentVar_traits::create (i, f, this)); if (!this->SimFlowPlant_CoolModeTempCurveCondWaterIndependentVar_) { this->SimFlowPlant_CoolModeTempCurveCondWaterIndependentVar_.set (r); continue; } } // SimFlowPlant_CoolModeCoolCapFuncofTempCurveName // if (n.name () == "SimFlowPlant_CoolModeCoolCapFuncofTempCurveName" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { ::std::auto_ptr< SimFlowPlant_CoolModeCoolCapFuncofTempCurveName_type > r ( SimFlowPlant_CoolModeCoolCapFuncofTempCurveName_traits::create (i, f, this)); if (!this->SimFlowPlant_CoolModeCoolCapFuncofTempCurveName_) { this->SimFlowPlant_CoolModeCoolCapFuncofTempCurveName_.set (r); continue; } } // SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofTempCurveName // if (n.name () == "SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofTempCurveName" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { ::std::auto_ptr< SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofTempCurveName_type > r ( SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofTempCurveName_traits::create (i, f, this)); if (!this->SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofTempCurveName_) { this->SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofTempCurveName_.set (r); continue; } } // SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName // if (n.name () == "SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { ::std::auto_ptr< SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName_type > r ( SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName_traits::create (i, f, this)); if (!this->SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName_) { this->SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName_.set (r); continue; } } // SimFlowPlant_CoolModeCoolCapOptPartLoadRatio // if (n.name () == "SimFlowPlant_CoolModeCoolCapOptPartLoadRatio" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { if (!this->SimFlowPlant_CoolModeCoolCapOptPartLoadRatio_) { this->SimFlowPlant_CoolModeCoolCapOptPartLoadRatio_.set (SimFlowPlant_CoolModeCoolCapOptPartLoadRatio_traits::create (i, f, this)); continue; } } // SimFlowPlant_HeatModeTempCurveCondWaterIndependentVar // if (n.name () == "SimFlowPlant_HeatModeTempCurveCondWaterIndependentVar" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { ::std::auto_ptr< SimFlowPlant_HeatModeTempCurveCondWaterIndependentVar_type > r ( SimFlowPlant_HeatModeTempCurveCondWaterIndependentVar_traits::create (i, f, this)); if (!this->SimFlowPlant_HeatModeTempCurveCondWaterIndependentVar_) { this->SimFlowPlant_HeatModeTempCurveCondWaterIndependentVar_.set (r); continue; } } // SimFlowPlant_HeatModeCoolCapFuncofTempCurveName // if (n.name () == "SimFlowPlant_HeatModeCoolCapFuncofTempCurveName" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { ::std::auto_ptr< SimFlowPlant_HeatModeCoolCapFuncofTempCurveName_type > r ( SimFlowPlant_HeatModeCoolCapFuncofTempCurveName_traits::create (i, f, this)); if (!this->SimFlowPlant_HeatModeCoolCapFuncofTempCurveName_) { this->SimFlowPlant_HeatModeCoolCapFuncofTempCurveName_.set (r); continue; } } // SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofTempCurveName // if (n.name () == "SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofTempCurveName" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { ::std::auto_ptr< SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofTempCurveName_type > r ( SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofTempCurveName_traits::create (i, f, this)); if (!this->SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofTempCurveName_) { this->SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofTempCurveName_.set (r); continue; } } // SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName // if (n.name () == "SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { ::std::auto_ptr< SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName_type > r ( SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName_traits::create (i, f, this)); if (!this->SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName_) { this->SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName_.set (r); continue; } } // SimFlowPlant_HeatModeCoolCapOptPartLoadRatio // if (n.name () == "SimFlowPlant_HeatModeCoolCapOptPartLoadRatio" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { if (!this->SimFlowPlant_HeatModeCoolCapOptPartLoadRatio_) { this->SimFlowPlant_HeatModeCoolCapOptPartLoadRatio_.set (SimFlowPlant_HeatModeCoolCapOptPartLoadRatio_traits::create (i, f, this)); continue; } } break; } } SimFlowPlant_ChillerHeater_PerformanceElectricEIR* SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: _clone (::xml_schema::flags f, ::xml_schema::container* c) const { return new class SimFlowPlant_ChillerHeater_PerformanceElectricEIR (*this, f, c); } SimFlowPlant_ChillerHeater_PerformanceElectricEIR& SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: operator= (const SimFlowPlant_ChillerHeater_PerformanceElectricEIR& x) { if (this != &x) { static_cast< ::schema::simxml::MepModel::SimFlowPlant_ChillerHeater& > (*this) = x; this->SimFlowPlant_RefCoolModeEvaporatorCap_ = x.SimFlowPlant_RefCoolModeEvaporatorCap_; this->SimFlowPlant_RefCoolModeCOP_ = x.SimFlowPlant_RefCoolModeCOP_; this->SimFlowPlant_RefCoolModeLeavingChilledWaterTemp_ = x.SimFlowPlant_RefCoolModeLeavingChilledWaterTemp_; this->SimFlowPlant_RefCoolModeEnteringCondFluidTemp_ = x.SimFlowPlant_RefCoolModeEnteringCondFluidTemp_; this->SimFlowPlant_RefCoolModeLeavingCondWaterTemp_ = x.SimFlowPlant_RefCoolModeLeavingCondWaterTemp_; this->SimFlowPlant_RefHeatModeCoolCapRatio_ = x.SimFlowPlant_RefHeatModeCoolCapRatio_; this->SimFlowPlant_RefHeatModeCoolPwrInputRatio_ = x.SimFlowPlant_RefHeatModeCoolPwrInputRatio_; this->SimFlowPlant_RefHeatModeLeavingChilledWaterTemp_ = x.SimFlowPlant_RefHeatModeLeavingChilledWaterTemp_; this->SimFlowPlant_RefHeatModeLeavingCondWaterTemp_ = x.SimFlowPlant_RefHeatModeLeavingCondWaterTemp_; this->SimFlowPlant_RefHeatModeEnteringCondFluidTemp_ = x.SimFlowPlant_RefHeatModeEnteringCondFluidTemp_; this->SimFlowPlant_HeatModeEnteringChilledWaterTempLowLimit_ = x.SimFlowPlant_HeatModeEnteringChilledWaterTempLowLimit_; this->SimFlowPlant_ChilledWaterFlowModeType_ = x.SimFlowPlant_ChilledWaterFlowModeType_; this->SimFlowPlant_CmprssrMotorEffic_ = x.SimFlowPlant_CmprssrMotorEffic_; this->SimFlowPlant_CoolModeTempCurveCondWaterIndependentVar_ = x.SimFlowPlant_CoolModeTempCurveCondWaterIndependentVar_; this->SimFlowPlant_CoolModeCoolCapFuncofTempCurveName_ = x.SimFlowPlant_CoolModeCoolCapFuncofTempCurveName_; this->SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofTempCurveName_ = x.SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofTempCurveName_; this->SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName_ = x.SimFlowPlant_CoolModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName_; this->SimFlowPlant_CoolModeCoolCapOptPartLoadRatio_ = x.SimFlowPlant_CoolModeCoolCapOptPartLoadRatio_; this->SimFlowPlant_HeatModeTempCurveCondWaterIndependentVar_ = x.SimFlowPlant_HeatModeTempCurveCondWaterIndependentVar_; this->SimFlowPlant_HeatModeCoolCapFuncofTempCurveName_ = x.SimFlowPlant_HeatModeCoolCapFuncofTempCurveName_; this->SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofTempCurveName_ = x.SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofTempCurveName_; this->SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName_ = x.SimFlowPlant_HeatModeElecInputtoCoolOutputRatioFuncofPartLoadRatioCurveName_; this->SimFlowPlant_HeatModeCoolCapOptPartLoadRatio_ = x.SimFlowPlant_HeatModeCoolCapOptPartLoadRatio_; } return *this; } SimFlowPlant_ChillerHeater_PerformanceElectricEIR:: ~SimFlowPlant_ChillerHeater_PerformanceElectricEIR () { } } } } #include <istream> #include <xsd/cxx/xml/sax/std-input-source.hxx> #include <xsd/cxx/tree/error-handler.hxx> namespace schema { namespace simxml { namespace MepModel { } } } #include <xsd/cxx/post.hxx> // Begin epilogue. // // // End epilogue.
50.140785
200
0.763141
EnEff-BIM
f66731e0b210c8a0f2e4865efde2bc9ff7657e22
13,621
cpp
C++
tests/convergence/prates.cpp
benzwick/mfem
4d5fdfd553b24ff37716f736f83df2d238d9a696
[ "BSD-3-Clause" ]
1
2019-03-24T04:35:42.000Z
2019-03-24T04:35:42.000Z
tests/convergence/prates.cpp
benzwick/mfem
4d5fdfd553b24ff37716f736f83df2d238d9a696
[ "BSD-3-Clause" ]
1
2019-04-24T21:18:24.000Z
2019-04-25T18:00:45.000Z
tests/convergence/prates.cpp
benzwick/mfem
4d5fdfd553b24ff37716f736f83df2d238d9a696
[ "BSD-3-Clause" ]
1
2021-09-26T01:49:50.000Z
2021-09-26T01:49:50.000Z
// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. // // --------------------------------- // Convergence Rates Test (Parallel) // --------------------------------- // // Compile with: make prates // // Sample runs: mpirun -np 4 prates -m ../../data/inline-segment.mesh -sr 1 -pr 4 -prob 0 -o 1 // mpirun -np 4 prates -m ../../data/inline-quad.mesh -sr 1 -pr 3 -prob 0 -o 2 // mpirun -np 4 prates -m ../../data/inline-quad.mesh -sr 1 -pr 3 -prob 1 -o 2 // mpirun -np 4 prates -m ../../data/inline-quad.mesh -sr 1 -pr 3 -prob 2 -o 2 // mpirun -np 4 prates -m ../../data/inline-tri.mesh -sr 1 -pr 3 -prob 2 -o 3 // mpirun -np 4 prates -m ../../data/star.mesh -sr 1 -pr 2 -prob 1 -o 4 // mpirun -np 4 prates -m ../../data/fichera.mesh -sr 1 -pr 2 -prob 2 -o 2 // mpirun -np 4 prates -m ../../data/inline-wedge.mesh -sr 0 -pr 2 -prob 0 -o 2 // mpirun -np 4 prates -m ../../data/inline-hex.mesh -sr 0 -pr 1 -prob 1 -o 3 // mpirun -np 4 prates -m ../../data/square-disc.mesh -sr 1 -pr 2 -prob 1 -o 2 // mpirun -np 4 prates -m ../../data/star.mesh -sr 1 -pr 2 -prob 3 -o 2 // mpirun -np 4 prates -m ../../data/star.mesh -sr 1 -pr 2 -prob 3 -o 2 -j 0 // mpirun -np 4 prates -m ../../data/inline-hex.mesh -sr 1 -pr 1 -prob 3 -o 2 // // Description: This example code demonstrates the use of MFEM to define and // solve finite element problem for various discretizations and // provide convergence rates in parallel. // // prob 0: H1 projection: // (grad u, grad v) + (u,v) = (grad u_exact, grad v) + (u_exact, v) // prob 1: H(curl) projection // (curl u, curl v) + (u,v) = (curl u_exact, curl v) + (u_exact, v) // prob 2: H(div) projection // (div u, div v) + (u,v) = (div u_exact, div v) + (u_exact, v) // prob 3: DG discretization for the Poisson problem // -Delta u = f #include "mfem.hpp" #include <fstream> #include <iostream> using namespace std; using namespace mfem; // Exact solution parameters: double sol_s[3] = { -0.32, 0.15, 0.24 }; double sol_k[3] = { 1.21, 1.45, 1.37 }; // H1 double scalar_u_exact(const Vector &x); double rhs_func(const Vector &x); void gradu_exact(const Vector &x, Vector &gradu); // Vector FE void vector_u_exact(const Vector &x, Vector & vector_u); // H(curl) void curlu_exact(const Vector &x, Vector &curlu); // H(div) double divu_exact(const Vector &x); int dim; int prob=0; int main(int argc, char *argv[]) { // 1. Initialize MPI. int num_procs, myid; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &num_procs); MPI_Comm_rank(MPI_COMM_WORLD, &myid); // 2. Parse command-line options. const char *mesh_file = "../../data/inline-quad.mesh"; int order = 1; bool visualization = 1; int sr = 1; int pr = 1; int jump_scaling_type = 1; double sigma = -1.0; double kappa = -1.0; OptionsParser args(argc, argv); args.AddOption(&mesh_file, "-m", "--mesh", "Mesh file to use."); args.AddOption(&order, "-o", "--order", "Finite element order (polynomial degree)"); args.AddOption(&prob, "-prob", "--problem", "Problem kind: 0: H1, 1: H(curl), 2: H(div), 3: DG "); args.AddOption(&sigma, "-s", "--sigma", "One of the two DG penalty parameters, typically +1/-1." " See the documentation of class DGDiffusionIntegrator."); args.AddOption(&kappa, "-k", "--kappa", "One of the two DG penalty parameters, should be positive." " Negative values are replaced with (order+1)^2."); args.AddOption(&jump_scaling_type, "-j", "--jump-scaling", "Scaling of the jump error for DG methods: " "0: no scaling, 1: 1/h, 2: p^2/h"); args.AddOption(&sr, "-sr", "--serial_ref", "Number of serial refinements."); args.AddOption(&pr, "-pr", "--parallel_ref", "Number of parallel refinements."); args.AddOption(&visualization, "-vis", "--visualization", "-no-vis", "--no-visualization", "Enable or disable GLVis visualization."); args.Parse(); if (!args.Good()) { if (myid == 0) { args.PrintUsage(cout); } MPI_Finalize(); return 1; } if (prob >3 || prob <0) prob = 0; // default problem = H1 if (prob == 3) { if (kappa < 0) { kappa = (order+1)*(order+1); } } if (myid == 0) { args.PrintOptions(cout); } // 3. Read the (serial) mesh from the given mesh file on all processors. We // can handle triangular, quadrilateral, tetrahedral, hexahedral, surface // and volume meshes with the same code. Mesh *mesh = new Mesh(mesh_file, 1, 1); dim = mesh->Dimension(); // 4. Refine the serial mesh on all processors to increase the resolution. for (int i = 0; i < sr; i++ ) { mesh->UniformRefinement(); } // 5. Define a parallel mesh by a partitioning of the serial mesh. Once the // parallel mesh is defined, the serial mesh can be deleted. ParMesh *pmesh = new ParMesh(MPI_COMM_WORLD, *mesh); delete mesh; // 6. Define a parallel finite element space on the parallel mesh. FiniteElementCollection *fec=nullptr; switch (prob) { case 0: fec = new H1_FECollection(order,dim); break; case 1: fec = new ND_FECollection(order,dim); break; case 2: fec = new RT_FECollection(order-1,dim); break; case 3: fec = new DG_FECollection(order,dim); break; default: break; } ParFiniteElementSpace *fespace = new ParFiniteElementSpace(pmesh, fec); // 7. Define the solution vector x as a parallel finite element grid function // corresponding to fespace. ParGridFunction x(fespace); x = 0.0; // 8. Set up the parallel linear form b(.) and the parallel bilinear form // a(.,.). FunctionCoefficient *f=nullptr; FunctionCoefficient *scalar_u=nullptr; FunctionCoefficient *divu=nullptr; VectorFunctionCoefficient *vector_u=nullptr; VectorFunctionCoefficient *gradu=nullptr; VectorFunctionCoefficient *curlu=nullptr; ConstantCoefficient one(1.0); ParLinearForm b(fespace); ParBilinearForm a(fespace); switch (prob) { case 0: //(grad u_ex, grad v) + (u_ex,v) scalar_u = new FunctionCoefficient(scalar_u_exact); gradu = new VectorFunctionCoefficient(dim,gradu_exact); b.AddDomainIntegrator(new DomainLFGradIntegrator(*gradu)); b.AddDomainIntegrator(new DomainLFIntegrator(*scalar_u)); // (grad u, grad v) + (u,v) a.AddDomainIntegrator(new DiffusionIntegrator(one)); a.AddDomainIntegrator(new MassIntegrator(one)); break; case 1: //(curl u_ex, curl v) + (u_ex,v) vector_u = new VectorFunctionCoefficient(dim,vector_u_exact); curlu = new VectorFunctionCoefficient((dim==3)?dim:1,curlu_exact); b.AddDomainIntegrator(new VectorFEDomainLFCurlIntegrator(*curlu)); b.AddDomainIntegrator(new VectorFEDomainLFIntegrator(*vector_u)); // (curl u, curl v) + (u,v) a.AddDomainIntegrator(new CurlCurlIntegrator(one)); a.AddDomainIntegrator(new VectorFEMassIntegrator(one)); break; case 2: //(div u_ex, div v) + (u_ex,v) vector_u = new VectorFunctionCoefficient(dim,vector_u_exact); divu = new FunctionCoefficient(divu_exact); b.AddDomainIntegrator(new VectorFEDomainLFDivIntegrator(*divu)); b.AddDomainIntegrator(new VectorFEDomainLFIntegrator(*vector_u)); // (div u, div v) + (u,v) a.AddDomainIntegrator(new DivDivIntegrator(one)); a.AddDomainIntegrator(new VectorFEMassIntegrator(one)); break; case 3: scalar_u = new FunctionCoefficient(scalar_u_exact); f = new FunctionCoefficient(rhs_func); gradu = new VectorFunctionCoefficient(dim,gradu_exact); b.AddDomainIntegrator(new DomainLFIntegrator(*f)); b.AddBdrFaceIntegrator( new DGDirichletLFIntegrator(*scalar_u, one, sigma, kappa)); a.AddDomainIntegrator(new DiffusionIntegrator(one)); a.AddInteriorFaceIntegrator(new DGDiffusionIntegrator(one, sigma, kappa)); a.AddBdrFaceIntegrator(new DGDiffusionIntegrator(one, sigma, kappa)); break; default: break; } // 9. Perform successive parallel refinements, compute the L2 error and the // corresponding rate of convergence. ConvergenceStudy rates; for (int l = 0; l <= pr; l++) { b.Assemble(); a.Assemble(); a.Finalize(); HypreParMatrix *A = a.ParallelAssemble(); HypreParVector *B = b.ParallelAssemble(); HypreParVector *X = x.ParallelProject(); Solver *prec = nullptr; IterativeSolver *solver = nullptr; switch (prob) { case 0: case 3: prec = new HypreBoomerAMG(*A); dynamic_cast<HypreBoomerAMG *>(prec)->SetPrintLevel(0); break; case 1: prec = new HypreAMS(*A, fespace); dynamic_cast<HypreAMS *>(prec)->SetPrintLevel(0); break; case 2: if (dim == 2) { prec = new HypreAMS(*A, fespace); dynamic_cast<HypreAMS *>(prec)->SetPrintLevel(0); } else { prec = new HypreADS(*A, fespace); dynamic_cast<HypreADS *>(prec)->SetPrintLevel(0); } break; default: break; } if (prob==3 && sigma !=-1.0) { solver = new GMRESSolver(MPI_COMM_WORLD); } else { solver = new CGSolver(MPI_COMM_WORLD); } solver->SetRelTol(1e-12); solver->SetMaxIter(2000); solver->SetPrintLevel(0); solver->SetPreconditioner(*prec); solver->SetOperator(*A); solver->Mult(*B, *X); delete prec; delete solver; x = *X; JumpScaling js(1.0, jump_scaling_type == 2 ? JumpScaling::P_SQUARED_OVER_H : jump_scaling_type == 1 ? JumpScaling::ONE_OVER_H : JumpScaling::CONSTANT); switch (prob) { case 0: rates.AddH1GridFunction(&x,scalar_u,gradu); break; case 1: rates.AddHcurlGridFunction(&x,vector_u,curlu); break; case 2: rates.AddHdivGridFunction(&x,vector_u,divu); break; case 3: rates.AddL2GridFunction(&x,scalar_u,gradu,&one,js); break; } delete X; delete B; delete A; if (l==pr) break; pmesh->UniformRefinement(); fespace->Update(); a.Update(); b.Update(); x.Update(); } rates.Print(); // 10. Send the solution by socket to a GLVis server. if (visualization) { char vishost[] = "localhost"; int visport = 19916; socketstream sol_sock(vishost, visport); sol_sock << "parallel " << num_procs << " " << myid << "\n"; sol_sock.precision(8); sol_sock << "solution\n" << *pmesh << x << "window_title 'Numerical Pressure (real part)' " << flush; } // 11. Free the used memory. delete scalar_u; delete divu; delete vector_u; delete gradu; delete curlu; delete fespace; delete fec; delete pmesh; MPI_Finalize(); return 0; } double rhs_func(const Vector &x) { double val = 1.0, lap = 0.0; for (int d = 0; d < x.Size(); d++) { const double f = sin(M_PI*(sol_s[d]+sol_k[d]*x(d))); val *= f; lap = lap*f + val*M_PI*M_PI*sol_k[d]*sol_k[d]; } return lap; } double scalar_u_exact(const Vector &x) { double val = 1.0; for (int d = 0; d < x.Size(); d++) { val *= sin(M_PI*(sol_s[d]+sol_k[d]*x(d))); } return val; } void gradu_exact(const Vector &x, Vector &grad) { grad.SetSize(x.Size()); double *g = grad.GetData(); double val = 1.0; for (int d = 0; d < x.Size(); d++) { const double y = M_PI*(sol_s[d]+sol_k[d]*x(d)); const double f = sin(y); for (int j = 0; j < d; j++) { g[j] *= f; } g[d] = val*M_PI*sol_k[d]*cos(y); val *= f; } } void vector_u_exact(const Vector &x, Vector & vector_u) { vector_u.SetSize(x.Size()); vector_u=0.0; vector_u[0] = scalar_u_exact(x); } // H(curl) void curlu_exact(const Vector &x, Vector &curlu) { Vector grad; gradu_exact(x,grad); int n = (x.Size()==3)?3:1; curlu.SetSize(n); if (x.Size()==3) { curlu[0] = 0.0; curlu[1] = grad[2]; curlu[2] = -grad[1]; } else if (x.Size()==2) { curlu[0] = -grad[1]; } } // H(div) double divu_exact(const Vector &x) { Vector grad; gradu_exact(x,grad); return grad[0]; }
32.664269
95
0.578078
benzwick
f667343f459920e05bca01d4d95a0c43b75a4d75
846
cpp
C++
src/gCode/split.cpp
jgert/grblController
e5026b1e5d972f3e67b07c3fb80dad276bae2c17
[ "MIT" ]
2
2021-12-19T19:15:28.000Z
2022-01-03T10:29:32.000Z
src/gCode/split.cpp
jgert/grblController
e5026b1e5d972f3e67b07c3fb80dad276bae2c17
[ "MIT" ]
12
2020-06-09T21:10:10.000Z
2022-02-25T14:11:17.000Z
src/gCode/split.cpp
jgert/grblController
e5026b1e5d972f3e67b07c3fb80dad276bae2c17
[ "MIT" ]
1
2020-08-13T04:00:55.000Z
2020-08-13T04:00:55.000Z
// // Created by Jakub Gert on 03/10/2020. // #include <sstream> #include <vector> #include <regex> #include "split.h" namespace gCode { size_t countMatchInRegex(const std::string &s, const regex &pattern) { auto words_begin = std::sregex_iterator(s.begin(), s.end(), pattern); auto words_end = std::sregex_iterator(); return std::distance(words_begin, words_end); } vector<string> splitByPattern(const string &s, const regex &pattern) { vector<string> items; items.reserve(countMatchInRegex(s, pattern)+1); copy(sregex_token_iterator(s.begin(), s.end(), pattern, -1), sregex_token_iterator(), back_inserter(items)); return items; } vector<string> splitByNewLine(const string &s) { return splitByPattern(s, regex("(\n)|(\r\n)")); } }
25.636364
77
0.634752
jgert
f671249cad341d980dc308ce3a90736f92a0fb33
220
cpp
C++
Queue.cpp
samplec0de/StringCalculator
88ca8ff044f43ebdde6a590d5582baea9d336c77
[ "MIT" ]
1
2022-01-17T21:45:01.000Z
2022-01-17T21:45:01.000Z
Queue.cpp
samplec0de/StringCalculator
88ca8ff044f43ebdde6a590d5582baea9d336c77
[ "MIT" ]
null
null
null
Queue.cpp
samplec0de/StringCalculator
88ca8ff044f43ebdde6a590d5582baea9d336c77
[ "MIT" ]
1
2020-04-19T19:04:53.000Z
2020-04-19T19:04:53.000Z
// // Queue.cpp // Алгоритм Дейкстры для перевода из инфиксной в постфиксную формы // // Created by Андрей Москалёв on 18/09/2019. // Copyright © 2019 Андрей Москалёв. All rights reserved. // #include "Queue.hpp"
22
69
0.704545
samplec0de
f673db5bb8b886a2b0c73995f717b52543f1fb05
230
cpp
C++
Easy/Interval Intersection.cpp
Safwaan21/Binarysearch.io-Solutions
024389dc4193f4e2b98369e0bacb714d757f2991
[ "MIT" ]
null
null
null
Easy/Interval Intersection.cpp
Safwaan21/Binarysearch.io-Solutions
024389dc4193f4e2b98369e0bacb714d757f2991
[ "MIT" ]
null
null
null
Easy/Interval Intersection.cpp
Safwaan21/Binarysearch.io-Solutions
024389dc4193f4e2b98369e0bacb714d757f2991
[ "MIT" ]
null
null
null
vector<int> solve(vector<vector<int>>& intervals) { vector<int> ans{intervals[0][0],intervals[0][1]}; for(auto& u : intervals){ ans[0] = max(ans[0],u[0]); ans[1] = min(ans[1],u[1]); } return ans; }
25.555556
53
0.53913
Safwaan21
f6742751d0b16382160857ab0200e1c28d80130a
6,438
cpp
C++
libgpopt/src/operators/CPhysicalMotionHashDistribute.cpp
davidli2010/gporca
4c946e5e41051c832736b2fce712c37ca651ddf5
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
libgpopt/src/operators/CPhysicalMotionHashDistribute.cpp
davidli2010/gporca
4c946e5e41051c832736b2fce712c37ca651ddf5
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
libgpopt/src/operators/CPhysicalMotionHashDistribute.cpp
davidli2010/gporca
4c946e5e41051c832736b2fce712c37ca651ddf5
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
//--------------------------------------------------------------------------- // Greenplum Database // Copyright (C) 2011 EMC Corp. // // @filename: // CPhysicalMotionHashDistribute.cpp // // @doc: // Implementation of hash distribute motion operator //--------------------------------------------------------------------------- #include "gpos/base.h" #include "gpopt/operators/CExpressionHandle.h" #include "gpopt/operators/CPhysicalMotionHashDistribute.h" #include "gpopt/base/CDistributionSpecHashedNoOp.h" using namespace gpopt; //--------------------------------------------------------------------------- // @function: // CPhysicalMotionHashDistribute::CPhysicalMotionHashDistribute // // @doc: // Ctor // //--------------------------------------------------------------------------- CPhysicalMotionHashDistribute::CPhysicalMotionHashDistribute ( CMemoryPool *mp, CDistributionSpecHashed *pdsHashed ) : CPhysicalMotion(mp), m_pdsHashed(pdsHashed), m_pcrsRequiredLocal(NULL) { GPOS_ASSERT(NULL != pdsHashed); GPOS_ASSERT(0 != pdsHashed->Pdrgpexpr()->Size()); m_pcrsRequiredLocal = m_pdsHashed->PcrsUsed(mp); } //--------------------------------------------------------------------------- // @function: // CPhysicalMotionHashDistribute::~CPhysicalMotionHashDistribute // // @doc: // Dtor // //--------------------------------------------------------------------------- CPhysicalMotionHashDistribute::~CPhysicalMotionHashDistribute() { m_pdsHashed->Release(); m_pcrsRequiredLocal->Release(); } //--------------------------------------------------------------------------- // @function: // CPhysicalMotionHashDistribute::Matches // // @doc: // Match operators // //--------------------------------------------------------------------------- BOOL CPhysicalMotionHashDistribute::Matches ( COperator *pop ) const { if (Eopid() != pop->Eopid()) { return false; } CPhysicalMotionHashDistribute *popHashDistribute = CPhysicalMotionHashDistribute::PopConvert(pop); return m_pdsHashed->Equals(popHashDistribute->m_pdsHashed); } //--------------------------------------------------------------------------- // @function: // CPhysicalMotionHashDistribute::PcrsRequired // // @doc: // Compute required columns of the n-th child; // //--------------------------------------------------------------------------- CColRefSet * CPhysicalMotionHashDistribute::PcrsRequired ( CMemoryPool *mp, CExpressionHandle &exprhdl, CColRefSet *pcrsRequired, ULONG child_index, CDrvdProp2dArray *, // pdrgpdpCtxt ULONG // ulOptReq ) { GPOS_ASSERT(0 == child_index); CColRefSet *pcrs = GPOS_NEW(mp) CColRefSet(mp, *m_pcrsRequiredLocal); pcrs->Union(pcrsRequired); CColRefSet *pcrsChildReqd = PcrsChildReqd(mp, exprhdl, pcrs, child_index, gpos::ulong_max); pcrs->Release(); return pcrsChildReqd; } //--------------------------------------------------------------------------- // @function: // CPhysicalMotionHashDistribute::FProvidesReqdCols // // @doc: // Check if required columns are included in output columns // //--------------------------------------------------------------------------- BOOL CPhysicalMotionHashDistribute::FProvidesReqdCols ( CExpressionHandle &exprhdl, CColRefSet *pcrsRequired, ULONG // ulOptReq ) const { return FUnaryProvidesReqdCols(exprhdl, pcrsRequired); } //--------------------------------------------------------------------------- // @function: // CPhysicalMotionHashDistribute::EpetOrder // // @doc: // Return the enforcing type for order property based on this operator // //--------------------------------------------------------------------------- CEnfdProp::EPropEnforcingType CPhysicalMotionHashDistribute::EpetOrder ( CExpressionHandle &, // exprhdl const CEnfdOrder * // peo ) const { return CEnfdProp::EpetRequired; } //--------------------------------------------------------------------------- // @function: // CPhysicalMotionHashDistribute::PosRequired // // @doc: // Compute required sort order of the n-th child // //--------------------------------------------------------------------------- COrderSpec * CPhysicalMotionHashDistribute::PosRequired ( CMemoryPool *mp, CExpressionHandle &, // exprhdl COrderSpec *,//posInput ULONG #ifdef GPOS_DEBUG child_index #endif // GPOS_DEBUG , CDrvdProp2dArray *, // pdrgpdpCtxt ULONG // ulOptReq ) const { GPOS_ASSERT(0 == child_index); return GPOS_NEW(mp) COrderSpec(mp); } //--------------------------------------------------------------------------- // @function: // CPhysicalMotionHashDistribute::PosDerive // // @doc: // Derive sort order // //--------------------------------------------------------------------------- COrderSpec * CPhysicalMotionHashDistribute::PosDerive ( CMemoryPool *mp, CExpressionHandle & // exprhdl ) const { return GPOS_NEW(mp) COrderSpec(mp); } //--------------------------------------------------------------------------- // @function: // CPhysicalMotionHashDistribute::OsPrint // // @doc: // Debug print // //--------------------------------------------------------------------------- IOstream & CPhysicalMotionHashDistribute::OsPrint ( IOstream &os ) const { os << SzId() << " "; return m_pdsHashed->OsPrint(os); } //--------------------------------------------------------------------------- // @function: // CPhysicalMotionHashDistribute::PopConvert // // @doc: // Conversion function // //--------------------------------------------------------------------------- CPhysicalMotionHashDistribute * CPhysicalMotionHashDistribute::PopConvert ( COperator *pop ) { GPOS_ASSERT(NULL != pop); GPOS_ASSERT(EopPhysicalMotionHashDistribute == pop->Eopid()); return dynamic_cast<CPhysicalMotionHashDistribute*>(pop); } CDistributionSpec * CPhysicalMotionHashDistribute::PdsRequired ( CMemoryPool *mp, CExpressionHandle &exprhdl, CDistributionSpec *pdsRequired, ULONG child_index, CDrvdProp2dArray *pdrgpdpCtxt, ULONG ulOptReq ) const { CDistributionSpecHashedNoOp* pdsNoOp = dynamic_cast<CDistributionSpecHashedNoOp*>(m_pdsHashed); if (NULL == pdsNoOp) { return CPhysicalMotion::PdsRequired(mp, exprhdl, pdsRequired, child_index, pdrgpdpCtxt, ulOptReq); } else { CExpressionArray *pdrgpexpr = pdsNoOp->Pdrgpexpr(); pdrgpexpr->AddRef(); CDistributionSpecHashed* pdsHashed = GPOS_NEW(mp) CDistributionSpecHashed(pdrgpexpr, pdsNoOp->FNullsColocated()); return pdsHashed; } } // EOF
23.669118
115
0.546598
davidli2010
f677f6cf06982a246c8dcae9c446cc3471324778
240
cpp
C++
src/smtlibsolver.cpp
akgperson/partial-function
4925c40c88e65e6fe4a21f713e6d997b6154b344
[ "BSD-3-Clause" ]
6
2020-03-05T01:07:28.000Z
2021-05-25T19:49:22.000Z
src/smtlibsolver.cpp
akgperson/partial-function
4925c40c88e65e6fe4a21f713e6d997b6154b344
[ "BSD-3-Clause" ]
null
null
null
src/smtlibsolver.cpp
akgperson/partial-function
4925c40c88e65e6fe4a21f713e6d997b6154b344
[ "BSD-3-Clause" ]
2
2020-07-27T17:13:09.000Z
2021-04-20T20:45:35.000Z
#include "smtlibsolver.h" using namespace std; namespace lbv2i { SmtLibSolver::SmtLibSolver(smt::SmtSolver & solver) : super(solver) {} SmtLibSolver::~SmtLibSolver() {} void SmtLibSolver::run(string filename) {} } // namespace lbv2i
17.142857
70
0.729167
akgperson
f67ac604827f18ca656f8fac58e9235a94d15289
1,319
hpp
C++
Board.hpp
mor234/cpp_ex2_part2_message_board
29a117aea79d265c347f6ed04532881088235635
[ "MIT" ]
null
null
null
Board.hpp
mor234/cpp_ex2_part2_message_board
29a117aea79d265c347f6ed04532881088235635
[ "MIT" ]
null
null
null
Board.hpp
mor234/cpp_ex2_part2_message_board
29a117aea79d265c347f6ed04532881088235635
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <map> #include "Direction.hpp" namespace ariel { class Board{ private: std::map<unsigned int, std::map< unsigned int,char>> board_map; bool isFirstTime=true; unsigned int max_row=0; unsigned int min_row=0; unsigned int max_col=0; unsigned int min_col=0; const char EMPTY_CHAR='_'; void initializesFirstTime (unsigned int row, unsigned int column); void update_min_max_raw_col(unsigned int row, unsigned int column); void postHorizontal(unsigned int row, unsigned int column, std::string const & message); void postVertical(unsigned int row, unsigned int column, std::string const & message); char charInLoc(unsigned int row,unsigned int column); std::string readHorizontal(unsigned int row, unsigned int column, unsigned int length); std::string readVertical(unsigned int row, unsigned int column, unsigned int length); public: void post(unsigned int row, unsigned int column,Direction direction,std::string const & message); std::string read(unsigned int row, unsigned int column, Direction direction, unsigned int length ); void show(); }; }
43.966667
112
0.644428
mor234
f67d46f7c37cc6112f548bf0bad77de1bbbbb005
532
cpp
C++
acm/hdu/1597.cpp
xiaohuihuigh/cpp
c28bdb79ecb86f44a92971ac259910546dba29a7
[ "MIT" ]
17
2016-01-01T12:57:25.000Z
2022-02-06T09:55:12.000Z
acm/hdu/1597.cpp
xiaohuihuigh/cpp
c28bdb79ecb86f44a92971ac259910546dba29a7
[ "MIT" ]
null
null
null
acm/hdu/1597.cpp
xiaohuihuigh/cpp
c28bdb79ecb86f44a92971ac259910546dba29a7
[ "MIT" ]
8
2018-12-27T01:31:49.000Z
2022-02-06T09:55:12.000Z
#include<iostream> using namespace std; typedef long long ll; int main(){ ll n; int t; cin>>t; while(t--){ cin>>n; n*=2; ll l = 0;ll r = 1<<16; //no_left,ok_right while(l<r){ ll mid = (l+r-1)/2+1; if(mid*(mid+1)<=n) l = mid; else r = mid-1; } // cout<<"l"<<l<<endl; int t = (n - l*(l+1))/2; if(t == 0){ cout<<(l-1)%9+1<<endl; } else{ cout<<(t-1)%9+1<<endl; } } }
17.733333
39
0.366541
xiaohuihuigh
f68095bf980b666cac4223f6177d238f101547e9
4,108
hpp
C++
sph/include/sph/data_util.hpp
OsmanSeckinSimsek/SPH-EXA
b617012277e349036e852c67f919c4b96445be93
[ "MIT" ]
null
null
null
sph/include/sph/data_util.hpp
OsmanSeckinSimsek/SPH-EXA
b617012277e349036e852c67f919c4b96445be93
[ "MIT" ]
null
null
null
sph/include/sph/data_util.hpp
OsmanSeckinSimsek/SPH-EXA
b617012277e349036e852c67f919c4b96445be93
[ "MIT" ]
null
null
null
/* * MIT License * * Copyright (c) 2021 CSCS, ETH Zurich * 2021 University of Basel * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /*! @file * @brief Utility functions to resolve names of particle fields to pointers */ #pragma once #include <vector> #include <variant> #include "traits.hpp" namespace sphexa { /*! @brief look up indices of field names * * @tparam Array * @param[in] allNames array of strings with names of all fields * @param[in] subsetNames array of strings of field names to look up in @p allNames * @return the indices of @p subsetNames in @p allNames */ template<class Array> std::vector<int> fieldStringsToInt(const Array& allNames, const std::vector<std::string>& subsetNames) { std::vector<int> subsetIndices; subsetIndices.reserve(subsetNames.size()); for (const auto& field : subsetNames) { auto it = std::find(allNames.begin(), allNames.end(), field); if (it == allNames.end()) { throw std::runtime_error("Field " + field + " does not exist\n"); } size_t fieldIndex = it - allNames.begin(); subsetIndices.push_back(fieldIndex); } return subsetIndices; } //! @brief extract a vector of pointers to particle fields for file output template<class Dataset> auto getOutputArrays(Dataset& dataset) { using T = typename Dataset::RealType; auto fieldPointers = dataset.data(); using FieldType = std::variant<const float*, const double*, const int*>; std::vector<FieldType> outputFields; outputFields.reserve(dataset.outputFields.size()); for (int i : dataset.outputFields) { std::visit([&outputFields](auto& arg) { outputFields.push_back(arg->data()); }, fieldPointers[i]); } return outputFields; } /*! @brief resizes all active particles fields of @p d to the specified size * * Important Note: this only resizes the fields that are listed either as conserved or dependent. * The conserved/dependent list may be set at runtime, depending on the need of the simulation! */ template<class Dataset> void resize(Dataset& d, size_t size) { double growthRate = 1.05; auto data_ = d.data(); for (int i : d.conservedFields) { std::visit([size, growthRate](auto& arg) { reallocate(*arg, size, growthRate); }, data_[i]); } for (int i : d.dependentFields) { std::visit([size, growthRate](auto& arg) { reallocate(*arg, size, growthRate); }, data_[i]); } reallocate(d.codes, size, growthRate); reallocate(d.neighborsCount, size, growthRate); d.devPtrs.resize(size); } //! resizes the neighbors list, only used in the CPU version template<class Dataset> void resizeNeighbors(Dataset& d, size_t size) { double growthRate = 1.05; //! If we have a GPU, neighbors are calculated on-the-fly, so we don't need space to store them reallocate(d.neighbors, HaveGpu<typename Dataset::AcceleratorType>{} ? 0 : size, growthRate); } } // namespace sphexa
33.398374
103
0.685248
OsmanSeckinSimsek
f6825726361bb267c6938d6942002c68aa149483
4,077
hpp
C++
csapex_point_cloud/src/clustering/storage/storage_ops.hpp
AdrianZw/csapex_core_plugins
1b23c90af7e552c3fc37c7dda589d751d2aae97f
[ "BSD-3-Clause" ]
2
2016-09-02T15:33:22.000Z
2019-05-06T22:09:33.000Z
csapex_point_cloud/src/clustering/storage/storage_ops.hpp
AdrianZw/csapex_core_plugins
1b23c90af7e552c3fc37c7dda589d751d2aae97f
[ "BSD-3-Clause" ]
1
2021-02-14T19:53:30.000Z
2021-02-14T19:53:30.000Z
csapex_point_cloud/src/clustering/storage/storage_ops.hpp
AdrianZw/csapex_core_plugins
1b23c90af7e552c3fc37c7dda589d751d2aae97f
[ "BSD-3-Clause" ]
6
2016-10-12T00:55:23.000Z
2021-02-10T17:49:25.000Z
#pragma once #include "../data/voxel_data.hpp" #include <cslibs_indexed_storage/backend/array/array_options.hpp> #include <pcl/PointIndices.h> #include <pcl/point_cloud.h> namespace csapex { namespace clustering { class StorageOperation { public: // dynamic sized case -> simply add every point to the storage template <typename PointT, typename Storage> static void init(const pcl::PointCloud<PointT>& cloud, const pcl::PointIndices::ConstPtr& indices, const VoxelIndex& indexer, Storage& storage, std::vector<typename Storage::data_t>&, std::false_type /*not_fixed_size*/) { const auto add_point = [&storage, &cloud, &indexer](std::size_t id) { const PointT& point = cloud.at(id); if (indexer.isValid(point)) storage.insert(point, indexer.createIndex(point), id); }; if (indices) { for (auto id : indices->indices) add_point(id); } else { for (std::size_t id = 0; id < cloud.size(); ++id) add_point(id); } } // fixed size case // - create each point in the data_storage // - calculate size // - initialize storage to size // - add non_owning references to storage template <typename PointT, typename Storage> static void init(const pcl::PointCloud<PointT>& cloud, const pcl::PointIndices::ConstPtr& indices, const VoxelIndex& indexer, Storage& storage, std::vector<typename Storage::data_t>& data_storage, std::true_type /*fixed_size*/) { const auto add_point = [&data_storage, &cloud, &indexer](std::size_t id) { const PointT& point = cloud.at(id); if (indexer.isValid(point)) data_storage.emplace_back(point, indexer.createIndex(point), id); }; if (indices) { data_storage.reserve(indices->indices.size()); for (auto id : indices->indices) add_point(id); } else { data_storage.reserve(cloud.size()); for (std::size_t id = 0; id < cloud.size(); ++id) add_point(id); } VoxelIndex::Type min; min.fill(std::numeric_limits<int>::max()); VoxelIndex::Type max; max.fill(std::numeric_limits<int>::min()); for (const auto& data : data_storage) VoxelIndex::minmax(data.index, min, max); VoxelIndex::Type size; for (std::size_t i = 0; i < 3; ++i) size[i] = max[i] - min[i] + 1; storage.template set<cslibs_indexed_storage::option::tags::array_offset>(min[0], min[1], min[2]); storage.template set<cslibs_indexed_storage::option::tags::array_size>(static_cast<std::size_t>(size[0]), static_cast<std::size_t>(size[1]), static_cast<std::size_t>(size[2])); for (auto& data : data_storage) storage.insert(&data); } template <typename Storage, typename ClusterOp> static void extract(const Storage& storage, const ClusterOp& cluster_op, std::vector<pcl::PointIndices>& accepted, std::vector<pcl::PointIndices>& rejected) { using Data = typename Storage::data_t; using Index = typename Storage::index_t; if (auto count = cluster_op.getClusterCount()) { accepted.resize(count); rejected.resize(count); storage.traverse([&accepted, &rejected](const Index& index, const Data& data) { if (data.cluster < 0) return; if (data.state == VoxelState::ACCEPTED) { auto& indices = accepted[data.cluster].indices; indices.insert(indices.end(), data.indices.begin(), data.indices.end()); } else if (data.state == VoxelState::REJECTED) { auto& indices = rejected[data.cluster].indices; indices.insert(indices.end(), data.indices.begin(), data.indices.end()); } }); } } }; } // namespace clustering } // namespace csapex
38.462264
200
0.591857
AdrianZw
f682917275d88d20a07e36cf9059144a2f0a93d9
5,412
hpp
C++
dep/win/include/boost/gil/concepts/image.hpp
Netis/packet-agent
70da3479051a07e3c235abe7516990f9fd21a18a
[ "BSD-3-Clause" ]
995
2018-06-22T10:39:18.000Z
2022-03-25T01:22:14.000Z
dep/win/include/boost/gil/concepts/image.hpp
Netis/packet-agent
70da3479051a07e3c235abe7516990f9fd21a18a
[ "BSD-3-Clause" ]
32
2018-06-23T14:19:37.000Z
2022-03-29T10:20:37.000Z
dep/win/include/boost/gil/concepts/image.hpp
Netis/packet-agent
70da3479051a07e3c235abe7516990f9fd21a18a
[ "BSD-3-Clause" ]
172
2018-06-22T11:12:00.000Z
2022-03-29T07:44:33.000Z
// // Copyright 2005-2007 Adobe Systems Incorporated // // Distributed under the Boost Software License, Version 1.0 // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt // #ifndef BOOST_GIL_CONCEPTS_IMAGE_HPP #define BOOST_GIL_CONCEPTS_IMAGE_HPP #include <boost/gil/concepts/basic.hpp> #include <boost/gil/concepts/concept_check.hpp> #include <boost/gil/concepts/fwd.hpp> #include <boost/gil/concepts/image_view.hpp> #include <boost/gil/concepts/point.hpp> #include <boost/mpl/size.hpp> #if defined(BOOST_CLANG) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-local-typedefs" #endif #if defined(BOOST_GCC) && (BOOST_GCC >= 40600) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-local-typedefs" #endif namespace boost { namespace gil { /// \ingroup ImageConcept /// \brief N-dimensional container of values /// /// \code /// concept RandomAccessNDImageConcept<typename Image> : Regular<Image> /// { /// typename view_t; where MutableRandomAccessNDImageViewConcept<view_t>; /// typename const_view_t = view_t::const_t; /// typename point_t = view_t::point_t; /// typename value_type = view_t::value_type; /// typename allocator_type; /// /// Image::Image(point_t dims, std::size_t alignment=1); /// Image::Image(point_t dims, value_type fill_value, std::size_t alignment); /// /// void Image::recreate(point_t new_dims, std::size_t alignment=1); /// void Image::recreate(point_t new_dims, value_type fill_value, std::size_t alignment); /// /// const point_t& Image::dimensions() const; /// const const_view_t& const_view(const Image&); /// const view_t& view(Image&); /// }; /// \endcode template <typename Image> struct RandomAccessNDImageConcept { void constraints() { gil_function_requires<Regular<Image>>(); using view_t = typename Image::view_t; gil_function_requires<MutableRandomAccessNDImageViewConcept<view_t>>(); using const_view_t = typename Image::const_view_t; using pixel_t = typename Image::value_type; using point_t = typename Image::point_t; gil_function_requires<PointNDConcept<point_t>>(); const_view_t cv = const_view(image); ignore_unused_variable_warning(cv); view_t v = view(image); ignore_unused_variable_warning(v); pixel_t fill_value; point_t pt = image.dimensions(); Image image1(pt); Image image2(pt, 1); Image image3(pt, fill_value, 1); image.recreate(pt); image.recreate(pt, 1); image.recreate(pt, fill_value, 1); } Image image; }; /// \ingroup ImageConcept /// \brief 2-dimensional container of values /// /// \code /// concept RandomAccess2DImageConcept<RandomAccessNDImageConcept Image> /// { /// typename x_coord_t = const_view_t::x_coord_t; /// typename y_coord_t = const_view_t::y_coord_t; /// /// Image::Image(x_coord_t width, y_coord_t height, std::size_t alignment=1); /// Image::Image(x_coord_t width, y_coord_t height, value_type fill_value, std::size_t alignment); /// /// x_coord_t Image::width() const; /// y_coord_t Image::height() const; /// /// void Image::recreate(x_coord_t width, y_coord_t height, std::size_t alignment=1); /// void Image::recreate(x_coord_t width, y_coord_t height, value_type fill_value, std::size_t alignment); /// }; /// \endcode template <typename Image> struct RandomAccess2DImageConcept { void constraints() { gil_function_requires<RandomAccessNDImageConcept<Image>>(); using x_coord_t = typename Image::x_coord_t; using y_coord_t = typename Image::y_coord_t; using value_t = typename Image::value_type; gil_function_requires<MutableRandomAccess2DImageViewConcept<typename Image::view_t>>(); x_coord_t w=image.width(); y_coord_t h=image.height(); value_t fill_value; Image im1(w,h); Image im2(w,h,1); Image im3(w,h,fill_value,1); image.recreate(w,h); image.recreate(w,h,1); image.recreate(w,h,fill_value,1); } Image image; }; /// \ingroup ImageConcept /// \brief 2-dimensional image whose value type models PixelValueConcept /// /// \code /// concept ImageConcept<RandomAccess2DImageConcept Image> /// { /// where MutableImageViewConcept<view_t>; /// typename coord_t = view_t::coord_t; /// }; /// \endcode template <typename Image> struct ImageConcept { void constraints() { gil_function_requires<RandomAccess2DImageConcept<Image>>(); gil_function_requires<MutableImageViewConcept<typename Image::view_t>>(); using coord_t = typename Image::coord_t; static_assert(num_channels<Image>::value == mpl::size<typename color_space_type<Image>::type>::value, ""); static_assert(is_same<coord_t, typename Image::x_coord_t>::value, ""); static_assert(is_same<coord_t, typename Image::y_coord_t>::value, ""); } Image image; }; }} // namespace boost::gil #if defined(BOOST_CLANG) #pragma clang diagnostic pop #endif #if defined(BOOST_GCC) && (BOOST_GCC >= 40600) #pragma GCC diagnostic pop #endif #endif
32.214286
115
0.666297
Netis
f6829174a438ec0f1c4709a8b26eca6dd2d5bd0d
14,876
cc
C++
src/video/Display.cc
imulilla/openMSX_TSXadv_nofork
4ee003d87a44633c14c054bd59ec2bfd866e5d9f
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
src/video/Display.cc
imulilla/openMSX_TSXadv_nofork
4ee003d87a44633c14c054bd59ec2bfd866e5d9f
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
src/video/Display.cc
imulilla/openMSX_TSXadv_nofork
4ee003d87a44633c14c054bd59ec2bfd866e5d9f
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
#include "Display.hh" #include "RendererFactory.hh" #include "Layer.hh" #include "VideoSystem.hh" #include "VideoLayer.hh" #include "EventDistributor.hh" #include "FinishFrameEvent.hh" #include "FileOperations.hh" #include "FileContext.hh" #include "InputEvents.hh" #include "CliComm.hh" #include "Timer.hh" #include "BooleanSetting.hh" #include "IntegerSetting.hh" #include "EnumSetting.hh" #include "Reactor.hh" #include "MSXMotherBoard.hh" #include "HardwareConfig.hh" #include "TclArgParser.hh" #include "XMLElement.hh" #include "VideoSystemChangeListener.hh" #include "CommandException.hh" #include "StringOp.hh" #include "Version.hh" #include "build-info.hh" #include "checked_cast.hh" #include "outer.hh" #include "ranges.hh" #include "stl.hh" #include "unreachable.hh" #include "view.hh" #include <cassert> using std::string; using std::vector; namespace openmsx { Display::Display(Reactor& reactor_) : RTSchedulable(reactor_.getRTScheduler()) , screenShotCmd(reactor_.getCommandController()) , fpsInfo(reactor_.getOpenMSXInfoCommand()) , osdGui(reactor_.getCommandController(), *this) , reactor(reactor_) , renderSettings(reactor.getCommandController()) , commandConsole(reactor.getGlobalCommandController(), reactor.getEventDistributor(), *this) , currentRenderer(RenderSettings::UNINITIALIZED) , switchInProgress(false) { frameDurationSum = 0; for (unsigned i = 0; i < NUM_FRAME_DURATIONS; ++i) { frameDurations.addFront(20); frameDurationSum += 20; } prevTimeStamp = Timer::getTime(); EventDistributor& eventDistributor = reactor.getEventDistributor(); eventDistributor.registerEventListener(OPENMSX_FINISH_FRAME_EVENT, *this); eventDistributor.registerEventListener(OPENMSX_SWITCH_RENDERER_EVENT, *this); eventDistributor.registerEventListener(OPENMSX_MACHINE_LOADED_EVENT, *this); eventDistributor.registerEventListener(OPENMSX_EXPOSE_EVENT, *this); #if PLATFORM_ANDROID eventDistributor.registerEventListener(OPENMSX_FOCUS_EVENT, *this); #endif renderSettings.getRendererSetting().attach(*this); renderSettings.getFullScreenSetting().attach(*this); renderSettings.getScaleFactorSetting().attach(*this); renderFrozen = false; } Display::~Display() { renderSettings.getRendererSetting().detach(*this); renderSettings.getFullScreenSetting().detach(*this); renderSettings.getScaleFactorSetting().detach(*this); EventDistributor& eventDistributor = reactor.getEventDistributor(); #if PLATFORM_ANDROID eventDistributor.unregisterEventListener(OPENMSX_FOCUS_EVENT, *this); #endif eventDistributor.unregisterEventListener(OPENMSX_EXPOSE_EVENT, *this); eventDistributor.unregisterEventListener(OPENMSX_MACHINE_LOADED_EVENT, *this); eventDistributor.unregisterEventListener(OPENMSX_SWITCH_RENDERER_EVENT, *this); eventDistributor.unregisterEventListener(OPENMSX_FINISH_FRAME_EVENT, *this); resetVideoSystem(); assert(listeners.empty()); } void Display::createVideoSystem() { assert(!videoSystem); assert(currentRenderer == RenderSettings::UNINITIALIZED); assert(!switchInProgress); currentRenderer = renderSettings.getRenderer(); switchInProgress = true; doRendererSwitch(); } VideoSystem& Display::getVideoSystem() { assert(videoSystem); return *videoSystem; } OutputSurface* Display::getOutputSurface() { return videoSystem ? videoSystem->getOutputSurface() : nullptr; } void Display::resetVideoSystem() { videoSystem.reset(); // At this point all layers except for the Video9000 layer // should be gone. //assert(layers.empty()); } CliComm& Display::getCliComm() const { return reactor.getCliComm(); } void Display::attach(VideoSystemChangeListener& listener) { assert(!contains(listeners, &listener)); listeners.push_back(&listener); } void Display::detach(VideoSystemChangeListener& listener) { move_pop_back(listeners, rfind_unguarded(listeners, &listener)); } Layer* Display::findActiveLayer() const { for (auto& l : layers) { if (l->getZ() == Layer::Z_MSX_ACTIVE) { return l; } } return nullptr; } Display::Layers::iterator Display::baseLayer() { // Note: It is possible to cache this, but since the number of layers is // low at the moment, it's not really worth it. auto it = end(layers); while (true) { if (it == begin(layers)) { // There should always be at least one opaque layer. // TODO: This is not true for DummyVideoSystem. // Anyway, a missing layer will probably stand out visually, // so do we really have to assert on it? //UNREACHABLE; return it; } --it; if ((*it)->getCoverage() == Layer::COVER_FULL) return it; } } void Display::executeRT() { videoSystem->repaint(); } int Display::signalEvent(const std::shared_ptr<const Event>& event) { if (event->getType() == OPENMSX_FINISH_FRAME_EVENT) { auto& ffe = checked_cast<const FinishFrameEvent&>(*event); if (ffe.needRender()) { videoSystem->repaint(); reactor.getEventDistributor().distributeEvent( std::make_shared<SimpleEvent>( OPENMSX_FRAME_DRAWN_EVENT)); } } else if (event->getType() == OPENMSX_SWITCH_RENDERER_EVENT) { doRendererSwitch(); } else if (event->getType() == OPENMSX_MACHINE_LOADED_EVENT) { videoSystem->updateWindowTitle(); } else if (event->getType() == OPENMSX_EXPOSE_EVENT) { // Don't render too often, and certainly not when the screen // will anyway soon be rendered. repaintDelayed(100 * 1000); // 10fps } else if (PLATFORM_ANDROID && event->getType() == OPENMSX_FOCUS_EVENT) { // On Android, the rendering must be frozen when the app is sent to // the background, because Android takes away all graphics resources // from the app. It simply destroys the entire graphics context. // Though, a repaint() must happen within the focus-lost event // so that the SDL Android port realises that the graphix context // is gone and will re-build it again on the first flush to the // surface after the focus has been regained. // Perform a repaint before updating the renderFrozen flag: // -When loosing the focus, this repaint will flush a last // time the SDL surface, making sure that the Android SDL // port discovers that the graphics context is gone. // -When gaining the focus, this repaint does nothing as // the renderFrozen flag is still false videoSystem->repaint(); auto& focusEvent = checked_cast<const FocusEvent&>(*event); ad_printf("Setting renderFrozen to %d", !focusEvent.getGain()); renderFrozen = !focusEvent.getGain(); } return 0; } string Display::getWindowTitle() { string title = Version::full(); if (!Version::RELEASE) { strAppend(title, " [", BUILD_FLAVOUR, ']'); } if (MSXMotherBoard* motherboard = reactor.getMotherBoard()) { if (const HardwareConfig* machine = motherboard->getMachineConfig()) { const XMLElement& config = machine->getConfig(); strAppend(title, " - ", config.getChild("info").getChildData("manufacturer"), ' ', config.getChild("info").getChildData("code")); } } return title; } void Display::update(const Setting& setting) { if (&setting == &renderSettings.getRendererSetting()) { checkRendererSwitch(); } else if (&setting == &renderSettings.getFullScreenSetting()) { checkRendererSwitch(); } else if (&setting == &renderSettings.getScaleFactorSetting()) { checkRendererSwitch(); } else { UNREACHABLE; } } void Display::checkRendererSwitch() { if (switchInProgress) { // This method only queues a request to switch renderer (see // comments below why). If there already is such a request // queued we don't need to do it again. return; } auto newRenderer = renderSettings.getRenderer(); if ((newRenderer != currentRenderer) || !getVideoSystem().checkSettings()) { currentRenderer = newRenderer; // don't do the actual switching in the Tcl callback // it seems creating and destroying Settings (= Tcl vars) // causes problems??? switchInProgress = true; reactor.getEventDistributor().distributeEvent( std::make_shared<SimpleEvent>( OPENMSX_SWITCH_RENDERER_EVENT)); } } void Display::doRendererSwitch() { assert(switchInProgress); bool success = false; while (!success) { try { doRendererSwitch2(); success = true; } catch (MSXException& e) { auto& rendererSetting = renderSettings.getRendererSetting(); string errorMsg = strCat( "Couldn't activate renderer ", rendererSetting.getString(), ": ", e.getMessage()); // now try some things that might work against this: if (rendererSetting.getEnum() != RenderSettings::SDL) { errorMsg += "\nTrying to switch to SDL renderer instead..."; rendererSetting.setEnum(RenderSettings::SDL); currentRenderer = RenderSettings::SDL; } else { auto& scaleFactorSetting = renderSettings.getScaleFactorSetting(); unsigned curval = scaleFactorSetting.getInt(); if (curval == 1) { throw MSXException( e.getMessage(), " (and I have no other ideas to try...)"); // give up and die... :( } strAppend(errorMsg, "\nTrying to decrease scale_factor setting from ", curval, " to ", curval - 1, "..."); scaleFactorSetting.setInt(curval - 1); } getCliComm().printWarning(errorMsg); } } switchInProgress = false; } void Display::doRendererSwitch2() { for (auto& l : listeners) { l->preVideoSystemChange(); } resetVideoSystem(); videoSystem = RendererFactory::createVideoSystem(reactor); for (auto& l : listeners) { l->postVideoSystemChange(); } } void Display::repaint() { if (switchInProgress) { // The checkRendererSwitch() method will queue a // SWITCH_RENDERER_EVENT, but before that event is handled // we shouldn't do any repaints (with inconsistent setting // values and render objects). This can happen when this // method gets called because of a DELAYED_REPAINT_EVENT // (DELAYED_REPAINT_EVENT was already queued before // SWITCH_RENDERER_EVENT is queued). return; } cancelRT(); // cancel delayed repaint if (!renderFrozen) { assert(videoSystem); if (OutputSurface* surface = videoSystem->getOutputSurface()) { repaint(*surface); videoSystem->flush(); } } // update fps statistics auto now = Timer::getTime(); auto duration = now - prevTimeStamp; prevTimeStamp = now; frameDurationSum += duration - frameDurations.removeBack(); frameDurations.addFront(duration); } void Display::repaint(OutputSurface& surface) { for (auto it = baseLayer(); it != end(layers); ++it) { if ((*it)->getCoverage() != Layer::COVER_NONE) { (*it)->paint(surface); } } } void Display::repaintDelayed(uint64_t delta) { if (isPendingRT()) { // already a pending repaint return; } scheduleRT(unsigned(delta)); } void Display::addLayer(Layer& layer) { int z = layer.getZ(); auto it = ranges::find_if(layers, [&](Layer* l) { return l->getZ() > z; }); layers.insert(it, &layer); layer.setDisplay(*this); } void Display::removeLayer(Layer& layer) { layers.erase(rfind_unguarded(layers, &layer)); } void Display::updateZ(Layer& layer) { // Remove at old Z-index... removeLayer(layer); // ...and re-insert at new Z-index. addLayer(layer); } // ScreenShotCmd Display::ScreenShotCmd::ScreenShotCmd(CommandController& commandController_) : Command(commandController_, "screenshot") { } void Display::ScreenShotCmd::execute(span<const TclObject> tokens, TclObject& result) { std::string_view prefix = "openmsx"; bool rawShot = false; bool msxOnly = false; bool doubleSize = false; bool withOsd = false; ArgsInfo info[] = { valueArg("-prefix", prefix), flagArg("-raw", rawShot), flagArg("-msxonly", msxOnly), flagArg("-doublesize", doubleSize), flagArg("-with-osd", withOsd) }; auto arguments = parseTclArgs(getInterpreter(), tokens.subspan(1), info); auto& display = OUTER(Display, screenShotCmd); if (msxOnly) { display.getCliComm().printWarning( "The -msxonly option has been deprecated and will " "be removed in a future release. Instead, use the " "-raw option for the same effect."); rawShot = true; } if (doubleSize && !rawShot) { throw CommandException("-doublesize option can only be used in " "combination with -raw"); } if (rawShot && withOsd) { throw CommandException("-with-osd cannot be used in " "combination with -raw"); } std::string_view fname; switch (arguments.size()) { case 0: // nothing break; case 1: fname = arguments[0].getString(); break; default: throw SyntaxError(); } string filename = FileOperations::parseCommandFileArgument( fname, "screenshots", prefix, ".png"); if (!rawShot) { // include all layers (OSD stuff, console) try { display.getVideoSystem().takeScreenShot(filename, withOsd); } catch (MSXException& e) { throw CommandException( "Failed to take screenshot: ", e.getMessage()); } } else { auto videoLayer = dynamic_cast<VideoLayer*>( display.findActiveLayer()); if (!videoLayer) { throw CommandException( "Current renderer doesn't support taking screenshots."); } unsigned height = doubleSize ? 480 : 240; try { videoLayer->takeRawScreenShot(height, filename); } catch (MSXException& e) { throw CommandException( "Failed to take screenshot: ", e.getMessage()); } } display.getCliComm().printInfo("Screen saved to ", filename); result = filename; } string Display::ScreenShotCmd::help(const vector<string>& /*tokens*/) const { // Note: -no-sprites option is implemented in Tcl return "screenshot Write screenshot to file \"openmsxNNNN.png\"\n" "screenshot <filename> Write screenshot to indicated file\n" "screenshot -prefix foo Write screenshot to file \"fooNNNN.png\"\n" "screenshot -raw 320x240 raw screenshot (of MSX screen only)\n" "screenshot -raw -doublesize 640x480 raw screenshot (of MSX screen only)\n" "screenshot -with-osd Include OSD elements in the screenshot\n" "screenshot -no-sprites Don't include sprites in the screenshot\n"; } void Display::ScreenShotCmd::tabCompletion(vector<string>& tokens) const { static constexpr const char* const extra[] = { "-prefix", "-raw", "-doublesize", "-with-osd", "-no-sprites", }; completeFileName(tokens, userFileContext(), extra); } // FpsInfoTopic Display::FpsInfoTopic::FpsInfoTopic(InfoCommand& openMSXInfoCommand) : InfoTopic(openMSXInfoCommand, "fps") { } void Display::FpsInfoTopic::execute(span<const TclObject> /*tokens*/, TclObject& result) const { auto& display = OUTER(Display, fpsInfo); result = 1000000.0f * Display::NUM_FRAME_DURATIONS / display.frameDurationSum; } string Display::FpsInfoTopic::help(const vector<string>& /*tokens*/) const { return "Returns the current rendering speed in frames per second."; } } // namespace openmsx
28.552783
85
0.710406
imulilla
f682e3037523b1c210b5ba36246556518f261e1b
4,199
hpp
C++
include/mesos/slave/isolator.hpp
em-mcg/cse223b-mesos
e7d0867d5bf67dbc28117f52babc73dd43d0bb4c
[ "Apache-2.0" ]
null
null
null
include/mesos/slave/isolator.hpp
em-mcg/cse223b-mesos
e7d0867d5bf67dbc28117f52babc73dd43d0bb4c
[ "Apache-2.0" ]
null
null
null
include/mesos/slave/isolator.hpp
em-mcg/cse223b-mesos
e7d0867d5bf67dbc28117f52babc73dd43d0bb4c
[ "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. #ifndef __MESOS_SLAVE_ISOLATOR_HPP__ #define __MESOS_SLAVE_ISOLATOR_HPP__ #include <list> #include <string> #include <mesos/resources.hpp> #include <mesos/slave/containerizer.hpp> #include <process/dispatch.hpp> #include <process/future.hpp> #include <process/owned.hpp> #include <process/process.hpp> #include <stout/hashset.hpp> #include <stout/option.hpp> #include <stout/try.hpp> namespace mesos { namespace slave { class Isolator { public: virtual ~Isolator() {} // Returns true if this isolator supports nested containers. This // method is designed to allow isolators to opt-in to support nested // containers. virtual bool supportsNesting() { return false; } virtual bool supportsStandalone() { return false; } // Recover containers from the run states and the orphan containers // (known to the launcher but not known to the slave) detected by // the launcher. virtual process::Future<Nothing> recover( const std::list<ContainerState>& states, const hashset<ContainerID>& orphans) { return Nothing(); } // Prepare for isolation of the executor. Any steps that require // execution in the containerized context (e.g. inside a network // namespace) can be returned in the optional CommandInfo and they // will be run by the Launcher. // TODO(idownes): Any URIs or Environment in the CommandInfo will be // ignored; only the command value is used. virtual process::Future<Option<ContainerLaunchInfo>> prepare( const ContainerID& containerId, const ContainerConfig& containerConfig) { return None(); } // Isolate the executor. virtual process::Future<Nothing> isolate( const ContainerID& containerId, pid_t pid) { return Nothing(); } // Watch the containerized executor and report if any resource // constraint impacts the container, e.g., the kernel killing some // processes. virtual process::Future<ContainerLimitation> watch( const ContainerID& containerId) { return process::Future<ContainerLimitation>(); } // Update the resources allocated to the container. virtual process::Future<Nothing> update( const ContainerID& containerId, const Resources& resources) { return Nothing(); } // Gather resource usage statistics for the container. virtual process::Future<ResourceStatistics> usage( const ContainerID& containerId) { return ResourceStatistics(); } // Get the run-time status of isolator specific properties // associated with the container. virtual process::Future<ContainerStatus> status( const ContainerID& containerId) { return ContainerStatus(); } // Clean up a terminated container. This is called after the // executor and all processes in the container have terminated. // It's likely that isolator `cleanup` is called for an unknown // container (see MESOS-6059). Therefore, the isolator should ignore // the cleanup is the container is unknown to it. In any case, the // `cleanup` won't be called multiple times for a container. Also, // if `prepare` is called, the cleanup is guaranteed to be called // after `prepare` finishes (or fails). virtual process::Future<Nothing> cleanup( const ContainerID& containerId) { return Nothing(); } }; } // namespace slave { } // namespace mesos { #endif // __MESOS_SLAVE_ISOLATOR_HPP__
30.208633
75
0.72422
em-mcg
f68360ea03cdaf07f9c504c7a9a3ac5423bd4881
2,483
cpp
C++
samples/blackfin/gcc/bf533/6-round-robin/src/utils/hwinit.cpp
diamondx131/scmrtos-sample-projects
3b34a485b6ca4b16705c250383ae5d30c81966f1
[ "MIT" ]
9
2015-10-07T15:27:27.000Z
2021-04-07T06:13:24.000Z
samples/blackfin/gcc/bf533/6-round-robin/src/utils/hwinit.cpp
diamondx131/scmrtos-sample-projects
3b34a485b6ca4b16705c250383ae5d30c81966f1
[ "MIT" ]
4
2017-07-04T10:51:51.000Z
2019-09-25T11:20:24.000Z
samples/blackfin/gcc/bf533/6-round-robin/src/utils/hwinit.cpp
diamondx131/scmrtos-sample-projects
3b34a485b6ca4b16705c250383ae5d30c81966f1
[ "MIT" ]
9
2015-12-04T15:34:32.000Z
2020-07-01T16:10:59.000Z
//****************************************************************************** //* //* PURPOSE: Hardware Initialization Code //* //* PROCESSOR: ADSP-BF533 (Analog Devices Inc.) //* //* TOOLKIT: bfin-elf (GCC) //* //* Version: v5.2.0 //* //* Copyright (c) 2003-2021, Harry E. Zhurov //* //****************************************************************************** //--------------------------------------------------------------------------- #include <stdint.h> #include <device_def.h> #include <macro.h> extern "C" void hwinit(); //--------------------------------------------------------------------------- void hwinit() { //------------------------------------------------------------------------ // // AMC // MMR16(EBIU_AMGCTL) = AMBEN_B0_B1; //------------------------------------------------------------------------ // // DMA and SDRAM // MMR16(EBIU_SDRRC) = 700; // Refresh rate = 700 cycles @ 10 ns per cycle ssync(); MMR32(EBIU_SDGCTL) = SCTLE // Enable CLKOUT, SRAS, SCAS, SWE, SDQM[1:0] | CL_2 // CAS latency = 2 cycles | TRAS_6 // tRAS = 6 cycles | TRP_2 // PRECHARGE command period = 2 cycles | TRCD_2 // ACTIVE to READ or WRITE delay = 2 cycles | TWR_2 // WRITE recovery time = 2 cycles | PSS // Enables SDRAM powerup sequence on next SDRAM access | EMREN // Extended mode register loading enable | CDDBG; // Control disable during bus grant ssync(); MMR16(EBIU_SDBCTL) = EBE // SDRAM external bank enable | EBSZ_32 // SDRAM external bank size = 32M | EBCAW_9; // SDRAM external bank column = 9 bits ssync(); uint16_t dummy = MMR16(0); // Initialize SDRAM Mode Register ssync(); } //--------------------------------------------------------------------------- void SetCoreVoltage(uint8_t x) { //MMR16(FIO_FLAG_S) = (1 << 5); uint16_t vr = MMR16(VR_CTL) & ~0x00f0; vr |= x << 4; MMR16(VR_CTL) = vr; asm( "cli r0; idle; sti r0;"); //MMR16(FIO_FLAG_C) = (1 << 5); } //---------------------------------------------------------------------------
34.971831
97
0.358035
diamondx131
f685648c370fc5b5ce086174df2c9328a0fba836
3,124
cpp
C++
test/btunittest/HTNTest/htntravelunittest.cpp
nefeithu/behaviac
3c8b09b5dc64e0090bf02e273687c6d94f328ad3
[ "BSD-3-Clause" ]
2,504
2016-11-11T17:12:12.000Z
2022-03-30T10:39:05.000Z
test/btunittest/HTNTest/htntravelunittest.cpp
mlik5hao/behaviac
a280fe24b3e7c357e607c397287a76a8bec33de3
[ "BSD-3-Clause" ]
127
2016-12-28T04:54:08.000Z
2022-03-17T10:26:55.000Z
test/btunittest/HTNTest/htntravelunittest.cpp
mlik5hao/behaviac
a280fe24b3e7c357e607c397287a76a8bec33de3
[ "BSD-3-Clause" ]
821
2016-11-11T11:15:24.000Z
2022-03-30T15:06:18.000Z
///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Tencent is pleased to support the open source community by making behaviac available. // // Copyright (C) 2015-2017 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at http://opensource.org/licenses/BSD-3-Clause // // 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 "../btloadtestsuite.h" #include "behaviac/common/profiler/profiler.h" #if BEHAVIAC_USE_HTN static HTNAgentTravel* initTestEnvHTNTravel(const char* treePath, behaviac::Workspace::EFileFormat format) { behaviac::Profiler::CreateInstance(); behaviac::Config::SetSocketing(false); //behaviac::Config::SetLogging(false); registerAllTypes(); HTNAgentTravel* testAgent = HTNAgentTravel::DynamicCast(behaviac::Agent::Create<HTNAgentTravel>()); behaviac::Agent::SetIdMask(1); testAgent->SetIdFlag(1); testAgent->btload(treePath); testAgent->btsetcurrent(treePath); return testAgent; } static void finlTestEnvHTNTravel(HTNAgentTravel* testAgent) { BEHAVIAC_DELETE(testAgent); unregisterAllTypes(); behaviac::Profiler::DestroyInstance(); } /** unit test for htn travel */ LOAD_TEST(btunittest, test_build_travel) { behaviac::Config::SetLogging(true); HTNAgentTravel* testAgent = initTestEnvHTNTravel("node_test/htn/travel/root", format); testAgent->resetProperties(); behaviac::Workspace::GetInstance()->DebugUpdate(); behaviac::Workspace::GetInstance()->DebugUpdate(); testAgent->SetStartFinish(testAgent->sh_td, testAgent->sz_td); testAgent->btexec(); behaviac::Config::SetLogging(false); CHECK_EQUAL(3, testAgent->Path().size()); CHECK_EQUAL("ride_taxi", testAgent->Path()[0].name); CHECK_EQUAL(testAgent->sh_td, testAgent->Path()[0].x); CHECK_EQUAL(testAgent->airport_sh_hongqiao, testAgent->Path()[0].y); CHECK_EQUAL("fly", testAgent->Path()[1].name); CHECK_EQUAL(testAgent->airport_sh_hongqiao, testAgent->Path()[1].x); CHECK_EQUAL(testAgent->airport_sz_baoan, testAgent->Path()[1].y); CHECK_EQUAL("ride_taxi", testAgent->Path()[2].name); CHECK_EQUAL(testAgent->airport_sz_baoan, testAgent->Path()[2].x); CHECK_EQUAL(testAgent->sz_td, testAgent->Path()[2].y); // testAgent->resetProperties(); testAgent->SetStartFinish(testAgent->sh_td, testAgent->sh_home); testAgent->btexec(); CHECK_EQUAL(1, testAgent->Path().size()); CHECK_EQUAL("ride_taxi", testAgent->Path()[0].name); CHECK_EQUAL(testAgent->sh_td, testAgent->Path()[0].x); CHECK_EQUAL(testAgent->sh_home, testAgent->Path()[0].y); finlTestEnvHTNTravel(testAgent); } #endif
37.190476
113
0.702305
nefeithu
f68564954112f67d675cfee82b396690d13d2517
19,236
cpp
C++
ThorEngine/Source Code/M_Editor.cpp
markitus18/Thor-Engine
d89c75f803357d6493cd018450bceb384d2dd265
[ "Unlicense" ]
12
2019-10-07T12:30:12.000Z
2021-09-25T13:05:26.000Z
ThorEngine/Source Code/M_Editor.cpp
markitus18/Thor-Engine
d89c75f803357d6493cd018450bceb384d2dd265
[ "Unlicense" ]
15
2017-06-14T13:10:06.000Z
2020-11-21T11:27:54.000Z
ThorEngine/Source Code/M_Editor.cpp
markitus18/Thor-Engine
d89c75f803357d6493cd018450bceb384d2dd265
[ "Unlicense" ]
4
2019-12-17T11:48:45.000Z
2020-11-13T19:09:59.000Z
#include "Engine.h" #include "Config.h" #include "M_Editor.h" #include "M_Window.h" #include "M_Input.h" //Windows #include "WF_SceneEditor.h" #include "WF_ParticleEditor.h" #include "W_Console.h" #include "W_EngineConfig.h" #include "M_SceneManager.h" #include "M_FileSystem.h" #include "M_Resources.h" #include "M_Renderer3D.h" #include "R_Scene.h" #include "GameObject.h" #include "Resource.h" #include "OpenGL.h" #include "ImGui/imgui.h" #include "ImGui/imgui_internal.h" #include "ImGui/imgui_impl_sdl.h" #include "ImGui/imgui_impl_opengl3.h" #include "Time.h" M_Editor::M_Editor(bool start_enabled) : Module("Editor", start_enabled) { } M_Editor::~M_Editor() {} bool M_Editor::Init(Config& config) { IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; io.ConfigViewportsNoDecoration = false; io.ConfigViewportsNoAutoMerge = true; io.ConfigWindowsMoveFromTitleBarOnly = true; io.ConfigDockingTransparentPayload = true; // When viewports are enabled we tweak WindowRounding/WindowBg so platform windows can look identical to regular ones. ImGuiStyle& style = ImGui::GetStyle(); if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) { style.WindowRounding = 0.0f; style.Colors[ImGuiCol_WindowBg].w = 1.0f; } style.Colors[ImGuiCol_DragDropTarget] = ImVec4(0.0f, 1.0f, 1.0f, 1.0f); ImGui_ImplSDL2_InitForOpenGL(Engine->window->window, Engine->renderer3D->context); ImGui_ImplOpenGL3_Init(); io.IniFilename = "Engine/imgui.ini"; io.MouseDrawCursor = false; int screen_width = GetSystemMetrics(SM_CXSCREEN); int screen_height = GetSystemMetrics(SM_CYSCREEN); //TODO: not sure if this should be done here too, but it's kinda valid LoadConfig(config); return true; } bool M_Editor::Start() { frameWindowClass = new ImGuiWindowClass(); frameWindowClass->ClassId = 1; frameWindowClass->DockNodeFlagsOverrideSet |= ImGuiDockNodeFlags_NoSplit; normalWindowClass = new ImGuiWindowClass(); normalWindowClass->ClassId = 2; if (TryLoadEditorState() == false) { uint64 sceneID = Engine->moduleResources->FindResourceBase("Engine/Assets/Defaults/Untitled.scene")->ID; OpenWindowFromResource(sceneID); } ImGuiIO& io = ImGui::GetIO(); return true; } update_status M_Editor::PreUpdate() { for (uint i = 0; i < windowFrames.size(); ++i) { //Handle any window frame close requests if (!windowFrames[i]->IsActive()) { CloseWindow(windowFrames[i]); --i; } } //Begin new ImGui Frame ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplSDL2_NewFrame(Engine->window->window); ImGui::NewFrame(); //Update ImGui input usage ImGuiIO& io = ImGui::GetIO(); using_keyboard = io.WantCaptureKeyboard; using_mouse = io.WantCaptureMouse; return UPDATE_CONTINUE; } void M_Editor::LoadLayout_Default(WindowFrame* windowFrame) { ImGuiID dockspace_id = ImGui::GetID("Main Dockspace"); windowFrame->LoadLayout_Default(dockspace_id); windowFrame->pendingLoadLayout = false; } void M_Editor::LoadLayout(WindowFrame* windowFrame, const char* layout) { //TODO: This is meant to be added when the user can generate new custom layouts } void M_Editor::SaveEditorState() { Config file; Config_Array arr = file.SetArray("Windows"); for (uint i = 0; i < windowFrames.size(); ++i) { Config node = arr.AddNode(); node.SetNumber("ID", windowFrames[i]->GetID()); node.SetNumber("Resource ID", windowFrames[i]->GetResourceID()); } char* buffer = nullptr; if (uint size = file.Serialize(&buffer)) { Engine->fileSystem->Save("Engine/EditorState.json", buffer, size); } } bool M_Editor::TryLoadEditorState() { char* buffer = nullptr; if (uint size = Engine->fileSystem->Load("Engine/EditorState.json", &buffer)) { Config file(buffer); Config_Array arr = file.GetArray("Windows"); for (uint i = 0; i < arr.GetSize(); ++i) { Config windowNode = arr.GetNode(i); OpenWindowFromResource(windowNode.GetNumber("Resource ID"), windowNode.GetNumber("ID")); } return true; } return false; } bool M_Editor::IsWindowLayoutSaved(WindowFrame* windowFrame) const { //Windows frames are saved as [Window][###<window_name>_<window_id>]] std::string windowStrID = std::string("[Window][###") + windowFrame->GetName() + ("_") + std::to_string(windowFrame->GetID()); if (!Engine->fileSystem->Exists("Engine/imgui.ini")) return false; //Parsing imgui.ini. We mimic ImGui's logic (function LoadIniSettingsFromMemory in imgui.cpp) char* buffer = nullptr; if (uint fileSize = Engine->fileSystem->Load("Engine/imgui.ini", &buffer)) { char* buffer_end = buffer + fileSize - 1; char* line = buffer; char* line_end = nullptr; while (Ini_FindNextEntry(line, line_end, buffer_end)) { if (strncmp(windowStrID.c_str(), line, windowStrID.size()) == 0) //<-- 'line' is the beginning of the line, and 'line_end' was set to '0' return true; line = line_end + 1; } RELEASE_ARRAY(buffer); } return false; } void M_Editor::ClearWindowFromIni(WindowFrame* windowFrame) { const std::vector<Window*> childWindows = windowFrame->GetWindows(); std::string winStrID = std::string("###") + windowFrame->GetName() + ("_") + std::to_string(windowFrame->GetID()); //Remove window and dock data from imgui.ini file if (!Engine->fileSystem->Exists("Engine/imgui.ini")) return; char* buffer = nullptr; uint64 fileSize = Engine->fileSystem->Load("Engine/imgui.ini", &buffer); //Parsing imgui.ini. We mimic ImGui's logic (function LoadIniSettingsFromMemory in imgui.cpp) char* buffer_end = buffer + fileSize - 1; char* line_end = nullptr; char* line = buffer; while (Ini_FindNextEntry(line, line_end, buffer_end)) { if (strncmp(line, "[Window]", 8) == 0) //Found a window entry! Iterate all windows to find a matching ID { //TODO: This could be simplified by checking only for ID! bool matchingEntry = false; if (strncmp(line + 9, winStrID.c_str(), (line_end - 1) - (line + 9)) == 0) matchingEntry = true; for (uint i = 0u; i < childWindows.size() && !matchingEntry; ++i) { if (strncmp(line + 9, childWindows[i]->GetWindowStrID(), (line_end - 1) - (line + 9)) == 0) matchingEntry = true; } if (matchingEntry) { char* next_line = line_end + 1; char* next_line_end = line_end; Ini_FindNextEntry(next_line, next_line_end, buffer_end); //<-- no need to check return as dock entry will always be after windows //Remove from current entry until next entry uint removeSize = next_line - line; for (uint i = 0u; next_line + i <= buffer_end; ++i) line[i] = next_line[i]; fileSize -= removeSize; buffer_end -= removeSize; buffer_end[1] = '\0'; } else line = line_end + 1; } else if (strncmp(line, "[Docking]", 9) == 0) //Found the docking entry { while (Ini_FindNextDockEntry(line, line_end, buffer_end)) { char* cursor = line + strlen("DockSpace"); while (*cursor == ' ' || *cursor == '\t') cursor++; uint ID, windowID; int r; if (sscanf(cursor, "ID=0x%08X Window=0x%08X%n", &ID, &windowID, &r) != 2) { line = line_end + 1; continue; } bool matchingEntry = false; if (strcmp(ImGui::FindWindowByID(windowID)->Name, windowFrame->GetWindowStrID()) == 0) matchingEntry = true; for (uint i = 0u; i < childWindows.size() && !matchingEntry; ++i) { if (strcmp(ImGui::FindWindowByID(windowID)->Name, childWindows[i]->GetWindowStrID()) == 0) matchingEntry = true; } if (matchingEntry) { char* next_line = line_end + 1; char* next_line_end = line_end; if (Ini_FindNextDockEntry(next_line, next_line_end, buffer_end)) { //Remove from current entry until next entry uint removeSize = next_line - line; for (uint i = 0u; next_line + i <= buffer_end; ++i) line[i] = next_line[i]; fileSize -= removeSize; buffer_end -= removeSize; buffer_end[1] = '\0'; } else //End of file! { line[0] = '\n'; line[1] = '\n'; line[2] = '\0'; uint removeSize = (buffer_end - line); fileSize -= removeSize; buffer_end -= removeSize; } } else line = line_end + 1; } } else line = line_end + 1; } Engine->fileSystem->Save("Engine/imgui.ini", buffer, fileSize); RELEASE_ARRAY(buffer); } bool M_Editor::Ini_FindNextEntry(char*& line, char*& line_end, char*& buffer_end) const { while (line_end < buffer_end) { // Skip new lines markers, then find end of the line while (*line == '\n' || *line == '\r') line++; line_end = line; while (line_end < buffer_end && *line_end != '\n' && *line_end != '\r') line_end++; if (line[0] == '[' && line_end > line && line_end[-1] == ']') return true; else line = line_end + 1; } return false; } bool M_Editor::Ini_FindNextDockEntry(char*& line, char*& line_end, char*& buffer_end) const { // Skip new lines markers, then find end of the line while (line_end < buffer_end) { while (*line == '\n' || *line == '\r' || *line == ' ' || *line == '\t') //<-- here we also skip blanks line++; line_end = line; while (line_end < buffer_end && *line_end != '\n' && *line_end != '\r') line_end++; if (strncmp(line, "DockSpace", 9) == 0) return true; else line = line_end + 1; } return false; } void M_Editor::Draw() { if (Engine->input->GetKey(SDL_SCANCODE_DELETE) == KEY_DOWN) { DeleteSelected(); } if (dragging == true && (Engine->input->GetMouseButton(SDL_BUTTON_LEFT) == KEY_UP || Engine->input->GetMouseButton(SDL_BUTTON_LEFT) == KEY_IDLE)) { toDragGOs.clear(); FinishDrag(true, false); dragging = false; } ImGuiWindowFlags frameWindow_flags = ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus; ImGuiViewport* viewport = ImGui::GetMainViewport(); ImGui::SetNextWindowPos(viewport->GetWorkPos()); ImGui::SetNextWindowSize(viewport->GetWorkSize()); ImGui::SetNextWindowViewport(viewport->ID); ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); ImGui::SetNextWindowClass(frameWindowClass); ImGui::Begin("Main Window", nullptr, frameWindow_flags); ImGui::PopStyleVar(); ImGuiID dockspace_id = ImGui::GetID("Main Dockspace"); ImGui::DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), ImGuiDockNodeFlags_NoSplit, frameWindowClass); for (uint i = 0; i < windowFrames.size(); ++i) windowFrames[i]->Draw(); //Layouts are loaded after draw so the draw call on docks does not happen twice in the same frame for (uint i = 0; i < windowFrames.size(); ++i) if (windowFrames[i]->pendingLoadLayout) LoadLayout_Default(windowFrames[i]); ImGui::End(); ImGui::Render(); ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); ImGuiIO& io = ImGui::GetIO(); if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) { SDL_Window* backup_current_window = SDL_GL_GetCurrentWindow(); SDL_GLContext backup_current_context = SDL_GL_GetCurrentContext(); ImGui::UpdatePlatformWindows(); ImGui::RenderPlatformWindowsDefault(); SDL_GL_MakeCurrent(backup_current_window, backup_current_context); } } bool M_Editor::CleanUp() { SaveEditorState(); ImGui_ImplOpenGL3_Shutdown(); ImGui_ImplSDL2_Shutdown(); ImGui::DestroyContext(); return true; } void M_Editor::Log(const char* input) { if (windowFrames.size() > 0) { W_Console* w_console = (W_Console*)GetWindowFrame(WF_SceneEditor::GetName())->GetWindow(W_Console::GetName()); if (w_console) w_console->AddLog(input); } } void M_Editor::GetEvent(SDL_Event* event) { ImGui_ImplSDL2_ProcessEvent(event); } void M_Editor::ShowFileNameWindow() { ImGui::SetNextWindowSize(ImVec2(400, 100)); ImGui::Begin("File Name", &show_fileName_window, ImGuiWindowFlags_NoResize); if (ImGui::InputText("", fileName, 50, ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_EnterReturnsTrue)) { Engine->moduleResources->SaveResourceAs(Engine->sceneManager->hCurrentScene.Get(), "Assets/Scenes", fileName); show_fileName_window = false; } if (ImGui::Button("Accept")) { Engine->moduleResources->SaveResourceAs(Engine->sceneManager->hCurrentScene.Get(), "Assets/Scenes", fileName); show_fileName_window = false; } ImGui::SameLine(); if (ImGui::Button("Cancel")) { show_fileName_window = false; } ImGui::End(); } void M_Editor::OpenFileNameWindow() { show_fileName_window = true; std::string file, extension; Engine->fileSystem->SplitFilePath(Engine->sceneManager->hCurrentScene.Get()->GetAssetsFile(), nullptr, &file, &extension); std::string str = file; if (extension != "") file.append("." + extension); strcpy_s(fileName, 50, str.c_str()); } WindowFrame* M_Editor::GetWindowFrame(const char* name) { for (uint i = 0; i < windowFrames.size(); ++i) if (strcmp(windowFrames[i]->GetName(), name) == 0) return windowFrames[i]; return nullptr; } void M_Editor::UpdateFPSData(int fps, int ms) { if (windowFrames.size() > 0) { W_EngineConfig* w_engineConfig = (W_EngineConfig*)GetWindowFrame(WF_SceneEditor::GetName())->GetWindow(W_EngineConfig::GetName()); if (w_engineConfig) w_engineConfig->UpdateFPSData(fps, ms); } } void M_Editor::OnResize(int screen_width, int screen_height) { ImGuiContext& g = *ImGui::GetCurrentContext(); float iconbar_size = 30.0f; } bool M_Editor::OpenWindowFromResource(uint64 resourceID, uint64 forceWindowID) { ResourceHandle<Resource> newResourceHandle(resourceID); Resource* resource = newResourceHandle.Get(); if (resource == nullptr) return false; WindowFrame* windowFrame = nullptr; switch (resource->GetType()) { case(ResourceType::SCENE): { if (windowFrame = GetWindowFrame(WF_SceneEditor::GetName())) { windowFrame->SetResource(resourceID); return true; } else windowFrame = new WF_SceneEditor(this, frameWindowClass, normalWindowClass, forceWindowID ? forceWindowID : random.Int()); break; } case (ResourceType::MATERIAL): { //Yeah, I wish (: break; } case(ResourceType::PARTICLESYSTEM): { windowFrame = new WF_ParticleEditor(this, frameWindowClass, normalWindowClass, forceWindowID ? forceWindowID : random.Int()); break; } } if (windowFrame != nullptr) { windowFrame->SetResource(resourceID); windowFrames.push_back(windowFrame); //If the window layout is not saved in ImGui.ini file, we will load the default layout in the next frame if (forceWindowID == 0 || !IsWindowLayoutSaved(windowFrame)) windowFrame->pendingLoadLayout = true; } } void M_Editor::CloseWindow(WindowFrame* windowFrame) { //TODO: Remove data from ImGui's memory ClearWindowFromIni(windowFrame); windowFrames.erase(std::find(windowFrames.begin(), windowFrames.end(), windowFrame)); RELEASE(windowFrame); } //Selection---------------------------- void M_Editor::SelectSingle(TreeNode* node, bool openTree) { UnselectAll(); if (node) { node->Select(); lastSelected = node; selectedGameObjects.push_back(node); if (openTree) { //Opening tree hierarchy node TreeNode* it = node->GetParentNode(); while (it != nullptr) { it->beenSelected = true; it = it->GetParentNode(); } } } } void M_Editor::AddSelect(TreeNode* node, bool openTree) { UnselectResources(); if (node && node->IsSelected() == false) { node->Select(); selectedGameObjects.push_back(node); if (openTree) { //Opening tree hierarchy node TreeNode* it = node->GetParentNode(); while (it != nullptr) { it->beenSelected = true; it = it->GetParentNode(); } } } } void M_Editor::AddToSelect(TreeNode* node) { toSelectGOs.push_back(node); } void M_Editor::UnselectSingle(TreeNode* node) { node->Unselect(); std::vector<TreeNode*>::iterator it = selectedGameObjects.begin(); while (it != selectedGameObjects.end()) { if ((*it) == node) { selectedGameObjects.erase(it); break; } it++; } } void M_Editor::UnselectAll() { UnselectResources(); UnselectGameObjects(); } void M_Editor::UnselectGameObjects() { for (uint i = 0; i < selectedGameObjects.size(); i++) { selectedGameObjects[i]->Unselect(); } selectedGameObjects.clear(); } void M_Editor::UnselectResources() { hSelectedResource.Set((uint64)0); } void M_Editor::DeleteSelected() { //Warning: iterator is not moved because GameObject will be erased from vector on "OnRemove" call for (uint i = 0; i < selectedGameObjects.size(); ) { selectedGameObjects[i]->Unselect(); if (selectedGameObjects[i]->GetType() == GAMEOBJECT) { Engine->sceneManager->DeleteGameObject((GameObject*)selectedGameObjects[i]); } else { //TODO: delete resource //Engine->moduleResources-> } } selectedGameObjects.clear(); UnselectResources(); } //Endof Selection ----------------------- void M_Editor::FinishDrag(bool drag, bool selectDrag) { std::vector<TreeNode*>::const_iterator it; for (it = toUnselectGOs.begin(); it != toUnselectGOs.end(); it++) { UnselectSingle(*it); } if (drag == true) { if (selectDrag == true) { for (it = toDragGOs.begin(); it != toDragGOs.end(); it++) { AddSelect(*it); } } } else { for (it = toSelectGOs.begin(); it != toSelectGOs.end(); it++) { AddSelect(*it); } } toDragGOs.clear(); toSelectGOs.clear(); toUnselectGOs.clear(); } void M_Editor::SaveConfig(Config& config) const { config.SetBool("Show Debug Info", showDebugInfo); /* std::vector<Window*>::const_iterator it; for (it = windows.begin(); it != windows.end(); ++it) { (*it)->SaveConfig(config.SetNode((*it)->name.c_str())); } */ } void M_Editor::LoadConfig(Config& config) { showDebugInfo = config.GetBool("Show Debug Info", false); /* std::vector<Window*>::const_iterator it; for (it = windows.begin(); it != windows.end(); ++it) { (*it)->LoadConfig(config.GetNode((*it)->name.c_str())); } */ } void M_Editor::LoadScene(const char* path, bool tmp) { ResetScene(); uint64 sceneID = Engine->sceneManager->LoadScene(path); WF_SceneEditor* sceneEditor = (WF_SceneEditor*)GetWindowFrame(WF_SceneEditor::GetName()); sceneEditor->SetResource(sceneID); } void M_Editor::ResetScene() { selectedGameObjects.clear(); toSelectGOs.clear(); toUnselectGOs.clear(); toDragGOs.clear(); dragging = false; } void M_Editor::OnRemoveGameObject(GameObject* gameObject) { for (std::vector<TreeNode*>::iterator it = selectedGameObjects.begin(); it != selectedGameObjects.end();) { if (*it == gameObject) { it = selectedGameObjects.erase(it); break; } else { it++; } } if (lastSelected == gameObject) lastSelected = nullptr; } void M_Editor::OnViewportClosed(uint32_t SDLWindowID) { ImGuiViewport* viewport = ImGui::FindViewportByPlatformHandle((void*)SDL_GetWindowFromID(SDLWindowID)); for (uint i = 0u; i < windowFrames.size(); ++i) { ImGuiWindow* window = ImGui::FindWindowByName(windowFrames[i]->GetWindowStrID()); if (window->Viewport == viewport) { //This function will be called from Input's PreUpdate so it's safe to destroy the windows here CloseWindow(windowFrames[i]); --i; } } } //------------------------------------
25.716578
146
0.690528
markitus18
f689482858c43f5b675710f979cbbb242096caf8
2,826
hpp
C++
include/hipSYCL/runtime/inorder_queue.hpp
illuhad/SYCU
4ff58f347d7bbdcf56704d2d011ecde7fa9dc621
[ "BSD-2-Clause" ]
null
null
null
include/hipSYCL/runtime/inorder_queue.hpp
illuhad/SYCU
4ff58f347d7bbdcf56704d2d011ecde7fa9dc621
[ "BSD-2-Clause" ]
null
null
null
include/hipSYCL/runtime/inorder_queue.hpp
illuhad/SYCU
4ff58f347d7bbdcf56704d2d011ecde7fa9dc621
[ "BSD-2-Clause" ]
null
null
null
/* * This file is part of hipSYCL, a SYCL implementation based on CUDA/HIP * * Copyright (c) 2019-2020 Aksel Alpay and 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. * * 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. */ #ifndef HIPSYCL_INORDER_QUEUE_HPP #define HIPSYCL_INORDER_QUEUE_HPP #include <memory> #include <string> #include "dag_node.hpp" #include "hints.hpp" #include "operations.hpp" #include "error.hpp" #include "code_object_invoker.hpp" namespace hipsycl { namespace rt { class inorder_queue { public: /// Inserts an event into the stream virtual std::shared_ptr<dag_node_event> insert_event() = 0; virtual result submit_memcpy(memcpy_operation&, dag_node_ptr) = 0; virtual result submit_kernel(kernel_operation&, dag_node_ptr) = 0; virtual result submit_prefetch(prefetch_operation &, dag_node_ptr) = 0; virtual result submit_memset(memset_operation&, dag_node_ptr) = 0; /// Causes the queue to wait until an event on another queue has occured. /// the other queue must be from the same backend virtual result submit_queue_wait_for(std::shared_ptr<dag_node_event> evt) = 0; virtual result submit_external_wait_for(dag_node_ptr node) = 0; virtual device_id get_device() const = 0; /// Return native type if supported, nullptr otherwise virtual void* get_native_type() const = 0; /// Get a code object invoker to launch kernels from code object images, /// if the backend supports this. Returns nullptr if unsupported. virtual code_object_invoker* get_code_object_invoker() = 0; virtual ~inorder_queue(){} }; } } #endif
37.68
82
0.765039
illuhad
f68c18f9ad4ba5b1d4e894211656bee89711aa1b
1,886
cpp
C++
DeepSkyStacker/CometStacking.cpp
lcsteyn/DSS
7991c8ddbeb7b2626234cd8ba1e9cb336bbf97c9
[ "BSD-3-Clause" ]
497
2019-06-20T09:52:58.000Z
2022-03-31T12:56:49.000Z
DeepSkyStacker/CometStacking.cpp
lcsteyn/DSS
7991c8ddbeb7b2626234cd8ba1e9cb336bbf97c9
[ "BSD-3-Clause" ]
58
2019-06-19T10:53:49.000Z
2022-02-14T22:43:18.000Z
DeepSkyStacker/CometStacking.cpp
lcsteyn/DSS
7991c8ddbeb7b2626234cd8ba1e9cb336bbf97c9
[ "BSD-3-Clause" ]
57
2019-07-08T16:08:01.000Z
2022-03-12T15:00:04.000Z
#include <algorithm> using std::min; using std::max; #include <atomic> #define _WIN32_WINNT _WIN32_WINNT_WIN7 #include <afx.h> #include "CometStacking.h" #include "ui/ui_CometStacking.h" #include "DSSCommon.h" #include "Workspace.h" CometStacking::CometStacking(QWidget *parent) : QWidget(parent), ui(new Ui::CometStacking), workspace(new CWorkspace()) { ui->setupUi(this); } CometStacking::~CometStacking() { delete ui; } void CometStacking::onSetActive() { m_CometStackingMode = static_cast<COMETSTACKINGMODE> (workspace->value("Stacking/CometStackingMode", (uint)CSM_STANDARD).toUInt()); switch (m_CometStackingMode) { case CSM_STANDARD: ui->modeStandard->setChecked(true); break; case CSM_COMETONLY: ui->modeComet->setChecked(true); break; case CSM_COMETSTAR: ui->modeAdvanced->setChecked(true); break; } updateImage(); } void CometStacking::setCometStackingMode(COMETSTACKINGMODE mode) { if (mode != m_CometStackingMode) { m_CometStackingMode = mode; workspace->setValue("Stacking/CometStackingMode", static_cast<uint>(mode)); updateImage(); } } void CometStacking::on_modeStandard_clicked() { setCometStackingMode(CSM_STANDARD); } void CometStacking::on_modeComet_clicked() { setCometStackingMode(CSM_COMETONLY); } void CometStacking::on_modeAdvanced_clicked() { setCometStackingMode(CSM_COMETSTAR); } void CometStacking::updateImage() { if (m_CometStackingMode == CSM_STANDARD) { if (standardPix.isNull()) { standardPix.load(":/comet/normal.bmp"); } ui->laComet->setPixmap(standardPix); } else if (m_CometStackingMode == CSM_COMETONLY) { if (cometPix.isNull()) { cometPix.load(":/comet/trails.bmp"); } ui->laComet->setPixmap(cometPix); } else { if (advancedPix.isNull()) { advancedPix.load(":/comet/freeze.bmp"); } ui->laComet->setPixmap(advancedPix); } }
19.050505
80
0.718452
lcsteyn
f68de332b44ec9eea0aee54c2ee3ef7b74d01e45
103,919
cpp
C++
mm/mm/lex.mm.cpp
Mirv/MM-Lib
df94e6549baf561e49bb4c3b85934ded5761b27e
[ "Unlicense" ]
27
2015-01-20T17:55:55.000Z
2021-11-28T16:29:02.000Z
mm/mm/lex.mm.cpp
Mirv/MM-Lib
df94e6549baf561e49bb4c3b85934ded5761b27e
[ "Unlicense" ]
null
null
null
mm/mm/lex.mm.cpp
Mirv/MM-Lib
df94e6549baf561e49bb4c3b85934ded5761b27e
[ "Unlicense" ]
4
2016-04-21T16:05:21.000Z
2018-03-28T21:31:35.000Z
#line 2 "lex.mm.cpp" #line 4 "lex.mm.cpp" #define YY_INT_ALIGNED short int /* A lexical scanner generated by flex */ #define FLEX_SCANNER #define YY_FLEX_MAJOR_VERSION 2 #define YY_FLEX_MINOR_VERSION 5 #define YY_FLEX_SUBMINOR_VERSION 35 #if YY_FLEX_SUBMINOR_VERSION > 0 #define FLEX_BETA #endif /* First, we deal with platform-specific or compiler-specific issues. */ /* begin standard C headers. */ #include <stdio.h> #include <string.h> #include <errno.h> #include <stdlib.h> /* end standard C headers. */ /* flex integer type definitions */ #ifndef FLEXINT_H #define FLEXINT_H /* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */ #if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 says to define __STDC_LIMIT_MACROS before including stdint.h, * if you want the limit (max/min) macros for int types. */ #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS 1 #endif #include <inttypes.h> typedef int8_t flex_int8_t; typedef uint8_t flex_uint8_t; typedef int16_t flex_int16_t; typedef uint16_t flex_uint16_t; typedef int32_t flex_int32_t; typedef uint32_t flex_uint32_t; #else typedef signed char flex_int8_t; typedef short int flex_int16_t; typedef int flex_int32_t; typedef unsigned char flex_uint8_t; typedef unsigned short int flex_uint16_t; typedef unsigned int flex_uint32_t; /* Limits of integral types. */ #ifndef INT8_MIN #define INT8_MIN (-128) #endif #ifndef INT16_MIN #define INT16_MIN (-32767-1) #endif #ifndef INT32_MIN #define INT32_MIN (-2147483647-1) #endif #ifndef INT8_MAX #define INT8_MAX (127) #endif #ifndef INT16_MAX #define INT16_MAX (32767) #endif #ifndef INT32_MAX #define INT32_MAX (2147483647) #endif #ifndef UINT8_MAX #define UINT8_MAX (255U) #endif #ifndef UINT16_MAX #define UINT16_MAX (65535U) #endif #ifndef UINT32_MAX #define UINT32_MAX (4294967295U) #endif #endif /* ! C99 */ #endif /* ! FLEXINT_H */ #ifdef __cplusplus /* The "const" storage-class-modifier is valid. */ #define YY_USE_CONST #else /* ! __cplusplus */ /* C99 requires __STDC__ to be defined as 1. */ #if defined (__STDC__) #define YY_USE_CONST #endif /* defined (__STDC__) */ #endif /* ! __cplusplus */ #ifdef YY_USE_CONST #define yyconst const #else #define yyconst #endif /* Returned upon end-of-file. */ #define YY_NULL 0 /* Promotes a possibly negative, possibly signed char to an unsigned * integer for use as an array index. If the signed char is negative, * we want to instead treat it as an 8-bit unsigned char, hence the * double cast. */ #define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c) /* Enter a start condition. This macro really ought to take a parameter, * but we do it the disgusting crufty way forced on us by the ()-less * definition of BEGIN. */ #define BEGIN (yy_start) = 1 + 2 * /* Translate the current start state into a value that can be later handed * to BEGIN to return to the state. The YYSTATE alias is for lex * compatibility. */ #define YY_START (((yy_start) - 1) / 2) #define YYSTATE YY_START /* Action number for EOF rule of a given start state. */ #define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) /* Special action meaning "start processing a new file". */ #define YY_NEW_FILE yyrestart(yyin ) #define YY_END_OF_BUFFER_CHAR 0 /* Size of default input buffer. */ #ifndef YY_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k. * Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case. * Ditto for the __ia64__ case accordingly. */ #define YY_BUF_SIZE 32768 #else #define YY_BUF_SIZE 16384 #endif /* __ia64__ */ #endif /* The state buf must be large enough to hold one state per character in the main buffer. */ #define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type)) #ifndef YY_TYPEDEF_YY_BUFFER_STATE #define YY_TYPEDEF_YY_BUFFER_STATE typedef struct yy_buffer_state *YY_BUFFER_STATE; #endif extern int yyleng; extern FILE *yyin, *yyout; #define EOB_ACT_CONTINUE_SCAN 0 #define EOB_ACT_END_OF_FILE 1 #define EOB_ACT_LAST_MATCH 2 #define YY_LESS_LINENO(n) /* Return all but the first "n" matched characters back to the input stream. */ #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ *yy_cp = (yy_hold_char); \ YY_RESTORE_YY_MORE_OFFSET \ (yy_c_buf_p) = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \ YY_DO_BEFORE_ACTION; /* set up yytext again */ \ } \ while ( 0 ) #define unput(c) yyunput( c, (yytext_ptr) ) #ifndef YY_TYPEDEF_YY_SIZE_T #define YY_TYPEDEF_YY_SIZE_T typedef size_t yy_size_t; #endif #ifndef YY_STRUCT_YY_BUFFER_STATE #define YY_STRUCT_YY_BUFFER_STATE struct yy_buffer_state { FILE *yy_input_file; char *yy_ch_buf; /* input buffer */ char *yy_buf_pos; /* current position in input buffer */ /* Size of input buffer in bytes, not including room for EOB * characters. */ yy_size_t yy_buf_size; /* Number of characters read into yy_ch_buf, not including EOB * characters. */ int yy_n_chars; /* Whether we "own" the buffer - i.e., we know we created it, * and can realloc() it to grow it, and should free() it to * delete it. */ int yy_is_our_buffer; /* Whether this is an "interactive" input source; if so, and * if we're using stdio for input, then we want to use getc() * instead of fread(), to make sure we stop fetching input after * each newline. */ int yy_is_interactive; /* Whether we're considered to be at the beginning of a line. * If so, '^' rules will be active on the next match, otherwise * not. */ int yy_at_bol; int yy_bs_lineno; /**< The line count. */ int yy_bs_column; /**< The column count. */ /* Whether to try to fill the input buffer when we reach the * end of it. */ int yy_fill_buffer; int yy_buffer_status; #define YY_BUFFER_NEW 0 #define YY_BUFFER_NORMAL 1 /* When an EOF's been seen but there's still some text to process * then we mark the buffer as YY_EOF_PENDING, to indicate that we * shouldn't try reading from the input source any more. We might * still have a bunch of tokens to match, though, because of * possible backing-up. * * When we actually see the EOF, we change the status to "new" * (via yyrestart()), so that the user can continue scanning by * just pointing yyin at a new input file. */ #define YY_BUFFER_EOF_PENDING 2 }; #endif /* !YY_STRUCT_YY_BUFFER_STATE */ /* Stack of input buffers. */ static size_t yy_buffer_stack_top = 0; /**< index of top of stack. */ static size_t yy_buffer_stack_max = 0; /**< capacity of stack. */ static YY_BUFFER_STATE * yy_buffer_stack = 0; /**< Stack as an array. */ /* We provide macros for accessing buffer states in case in the * future we want to put the buffer states in a more general * "scanner state". * * Returns the top of the stack, or NULL. */ #define YY_CURRENT_BUFFER ( (yy_buffer_stack) \ ? (yy_buffer_stack)[(yy_buffer_stack_top)] \ : NULL) /* Same as previous macro, but useful when we know that the buffer stack is not * NULL or when we need an lvalue. For internal use only. */ #define YY_CURRENT_BUFFER_LVALUE (yy_buffer_stack)[(yy_buffer_stack_top)] /* yy_hold_char holds the character lost when yytext is formed. */ static char yy_hold_char; static int yy_n_chars; /* number of characters read into yy_ch_buf */ int yyleng; /* Points to current character in buffer. */ static char *yy_c_buf_p = (char *) 0; static int yy_init = 0; /* whether we need to initialize */ static int yy_start = 0; /* start state number */ /* Flag which is used to allow yywrap()'s to do buffer switches * instead of setting up a fresh yyin. A bit of a hack ... */ static int yy_did_buffer_switch_on_eof; void yyrestart (FILE *input_file ); void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ); YY_BUFFER_STATE yy_create_buffer (FILE *file,int size ); void yy_delete_buffer (YY_BUFFER_STATE b ); void yy_flush_buffer (YY_BUFFER_STATE b ); void yypush_buffer_state (YY_BUFFER_STATE new_buffer ); void yypop_buffer_state (void ); static void yyensure_buffer_stack (void ); static void yy_load_buffer_state (void ); static void yy_init_buffer (YY_BUFFER_STATE b,FILE *file ); #define YY_FLUSH_BUFFER yy_flush_buffer(YY_CURRENT_BUFFER ) YY_BUFFER_STATE yy_scan_buffer (char *base,yy_size_t size ); YY_BUFFER_STATE yy_scan_string (yyconst char *yy_str ); YY_BUFFER_STATE yy_scan_bytes (yyconst char *bytes,int len ); void *yyalloc (yy_size_t ); void *yyrealloc (void *,yy_size_t ); void yyfree (void * ); #define yy_new_buffer yy_create_buffer #define yy_set_interactive(is_interactive) \ { \ if ( ! YY_CURRENT_BUFFER ){ \ yyensure_buffer_stack (); \ YY_CURRENT_BUFFER_LVALUE = \ yy_create_buffer(yyin,YY_BUF_SIZE ); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \ } #define yy_set_bol(at_bol) \ { \ if ( ! YY_CURRENT_BUFFER ){\ yyensure_buffer_stack (); \ YY_CURRENT_BUFFER_LVALUE = \ yy_create_buffer(yyin,YY_BUF_SIZE ); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \ } #define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol) /* Begin user sect3 */ #define yywrap(n) 1 #define YY_SKIP_YYWRAP typedef unsigned char YY_CHAR; FILE *yyin = (FILE *) 0, *yyout = (FILE *) 0; typedef int yy_state_type; extern int yylineno; int yylineno = 1; extern char *yytext; #define yytext_ptr yytext static yy_state_type yy_get_previous_state (void ); static yy_state_type yy_try_NUL_trans (yy_state_type current_state ); static int yy_get_next_buffer (void ); static void yy_fatal_error (yyconst char msg[] ); /* Done after the current pattern has been matched and before the * corresponding action - sets up yytext. */ #define YY_DO_BEFORE_ACTION \ (yytext_ptr) = yy_bp; \ yyleng = (size_t) (yy_cp - yy_bp); \ (yy_hold_char) = *yy_cp; \ *yy_cp = '\0'; \ (yy_c_buf_p) = yy_cp; #define YY_NUM_RULES 88 #define YY_END_OF_BUFFER 89 /* This struct is not used in this scanner, but its presence is necessary. */ struct yy_trans_info { flex_int32_t yy_verify; flex_int32_t yy_nxt; }; static yyconst flex_int16_t yy_accept[396] = { 0, 0, 0, 0, 0, 87, 87, 87, 87, 0, 0, 0, 0, 89, 88, 1, 2, 32, 88, 37, 88, 30, 31, 27, 26, 24, 23, 28, 80, 36, 21, 29, 22, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 34, 33, 35, 25, 87, 87, 87, 5, 4, 6, 10, 9, 11, 18, 0, 78, 12, 16, 14, 15, 7, 3, 0, 80, 19, 17, 20, 81, 0, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 13, 87, 0, 87, 85, 0, 87, 8, 79, 82, 83, 81, 81, 81, 81, 81, 52, 52, 52, 52, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 53, 53, 53, 53, 81, 81, 81, 63, 63, 63, 63, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 66, 66, 66, 66, 81, 81, 81, 81, 84, 85, 86, 79, 81, 64, 64, 64, 64, 46, 46, 46, 46, 47, 47, 47, 47, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 51, 51, 51, 51, 81, 54, 54, 54, 54, 81, 81, 81, 81, 81, 81, 57, 57, 57, 57, 81, 81, 81, 81, 81, 81, 81, 81, 81, 48, 48, 48, 48, 81, 81, 58, 58, 58, 58, 81, 81, 81, 81, 71, 71, 71, 71, 81, 65, 65, 65, 65, 41, 41, 41, 41, 81, 81, 81, 40, 40, 40, 40, 81, 81, 44, 44, 44, 44, 43, 43, 43, 43, 81, 81, 77, 77, 77, 77, 81, 61, 61, 61, 61, 49, 49, 49, 49, 81, 81, 81, 81, 81, 81, 81, 39, 39, 39, 39, 81, 81, 60, 60, 60, 60, 55, 55, 55, 55, 81, 81, 81, 81, 81, 50, 50, 50, 50, 81, 81, 81, 59, 59, 59, 59, 67, 67, 67, 67, 81, 68, 68, 68, 68, 81, 74, 74, 74, 74, 56, 56, 56, 56, 76, 76, 76, 76, 81, 81, 81, 38, 38, 38, 38, 81, 81, 81, 81, 73, 73, 73, 73, 45, 45, 45, 45, 72, 72, 72, 72, 62, 62, 62, 62, 75, 75, 75, 75, 69, 69, 69, 69, 70, 70, 70, 70, 81, 42, 42, 42, 42, 0 } ; static yyconst flex_int32_t yy_ec[256] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 1, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 4, 5, 1, 1, 6, 7, 1, 8, 9, 10, 11, 1, 12, 13, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 16, 1, 17, 18, 19, 1, 1, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 1, 1, 1, 1, 21, 1, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 31, 32, 33, 34, 35, 36, 31, 37, 38, 39, 40, 41, 31, 42, 43, 31, 44, 45, 46, 47, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } ; static yyconst flex_int32_t yy_meta[48] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 3, 4, 1, 1, 5, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1 } ; static yyconst flex_int16_t yy_base[406] = { 0, 0, 0, 0, 0, 47, 0, 75, 0, 116, 117, 118, 119, 2300, 2301, 2301, 2301, 2281, 2293, 2301, 2290, 2301, 2301, 2301, 2301, 2277, 113, 113, 120, 2301, 2277, 2276, 2275, 135, 159, 2257, 159, 152, 165, 2269, 2256, 166, 163, 170, 2263, 165, 171, 2250, 2257, 2301, 2241, 2301, 2301, 0, 196, 2272, 2301, 2301, 2301, 2301, 2301, 2270, 2301, 2278, 2301, 2301, 2301, 2301, 2301, 2301, 2301, 2267, 198, 2301, 2301, 2301, 2301, 0, 0, 2279, 2241, 2254, 2246, 2234, 2238, 213, 2236, 2240, 2241, 237, 2250, 2249, 2231, 232, 2234, 2229, 275, 2225, 2241, 322, 2226, 2226, 2228, 237, 233, 2235, 2221, 244, 369, 94, 2234, 2224, 2301, 0, 0, 256, 2256, 0, 2244, 2301, 2241, 2301, 2253, 2224, 416, 463, 510, 2227, 2301, 0, 0, 2250, 2216, 2209, 2223, 2222, 2225, 2216, 2222, 2218, 2211, 2204, 2208, 2214, 2301, 0, 0, 2237, 2198, 557, 2207, 2301, 0, 0, 2234, 604, 2197, 2202, 2192, 2191, 2199, 2201, 651, 2192, 2191, 2191, 2301, 0, 0, 2224, 2197, 2198, 2186, 2190, 2301, 2219, 2301, 2301, 2179, 2301, 0, 0, 2217, 2301, 0, 0, 2216, 2301, 0, 0, 2215, 2179, 698, 2189, 2175, 745, 2190, 2178, 2179, 2173, 792, 2183, 839, 886, 2169, 2301, 0, 0, 2205, 2179, 2301, 0, 0, 2203, 2174, 933, 2177, 2180, 980, 1027, 2301, 0, 0, 2199, 2176, 2160, 1074, 2170, 1121, 1168, 2175, 1194, 2157, 2301, 0, 0, 2193, 2157, 2167, 2301, 0, 0, 2190, 2159, 1220, 2164, 2155, 2301, 0, 0, 2186, 1267, 2301, 0, 0, 2185, 2301, 0, 0, 2184, 1314, 2142, 2143, 2301, 0, 0, 2181, 2148, 2142, 2301, 0, 0, 2178, 2301, 0, 0, 2177, 2152, 1361, 2301, 0, 0, 2175, 2150, 2301, 0, 0, 2173, 2301, 0, 0, 2172, 2134, 2133, 1408, 1455, 2132, 1502, 2144, 2301, 0, 0, 2167, 1549, 1596, 2301, 0, 0, 2166, 2301, 0, 0, 2165, 1643, 2140, 2126, 2138, 1690, 2301, 0, 0, 2161, 2125, 2135, 2134, 2301, 0, 0, 2157, 2301, 0, 0, 2156, 2131, 2301, 0, 0, 2154, 1737, 2301, 0, 0, 2153, 2301, 0, 0, 2152, 2301, 0, 0, 2151, 1784, 1831, 1878, 2301, 0, 0, 2150, 1925, 1972, 2019, 2114, 2301, 0, 0, 1217, 2301, 0, 0, 1216, 2301, 0, 0, 1215, 2301, 0, 0, 272, 2301, 0, 0, 271, 2301, 0, 0, 266, 2301, 0, 0, 193, 2066, 2301, 0, 0, 123, 2301, 2113, 2118, 2123, 2128, 93, 2132, 2135, 2138, 2142, 2146 } ; static yyconst flex_int16_t yy_def[406] = { 0, 395, 1, 396, 396, 395, 5, 5, 7, 397, 397, 398, 398, 395, 395, 395, 395, 395, 399, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 395, 395, 395, 395, 400, 401, 402, 395, 395, 395, 395, 395, 395, 395, 399, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 403, 33, 395, 33, 33, 33, 33, 33, 395, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 395, 33, 33, 395, 33, 33, 33, 33, 33, 33, 33, 33, 395, 33, 33, 33, 395, 400, 404, 401, 395, 405, 402, 395, 395, 395, 395, 33, 395, 395, 395, 33, 395, 403, 33, 395, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 395, 403, 33, 395, 33, 395, 33, 395, 403, 33, 395, 395, 33, 33, 33, 33, 33, 33, 395, 33, 33, 33, 395, 403, 33, 395, 33, 33, 33, 33, 395, 395, 395, 395, 33, 395, 403, 33, 395, 395, 403, 33, 395, 395, 403, 33, 395, 33, 395, 33, 33, 395, 33, 33, 33, 33, 395, 33, 395, 395, 33, 395, 403, 33, 395, 33, 395, 403, 33, 395, 33, 395, 33, 33, 395, 395, 395, 403, 33, 395, 33, 33, 395, 33, 395, 395, 33, 33, 33, 395, 403, 33, 395, 33, 33, 395, 403, 33, 395, 33, 395, 33, 33, 395, 403, 33, 395, 395, 395, 403, 33, 395, 395, 403, 33, 395, 395, 33, 33, 395, 403, 33, 395, 33, 33, 395, 403, 33, 395, 395, 403, 33, 395, 33, 395, 395, 403, 33, 395, 33, 395, 403, 33, 395, 395, 403, 33, 395, 33, 33, 395, 395, 33, 395, 33, 395, 403, 33, 395, 395, 395, 395, 403, 33, 395, 395, 403, 33, 395, 395, 33, 33, 33, 395, 395, 403, 33, 395, 33, 33, 33, 395, 403, 33, 395, 395, 403, 33, 395, 33, 395, 403, 33, 395, 395, 395, 403, 33, 395, 395, 403, 33, 395, 395, 403, 33, 395, 395, 395, 395, 395, 403, 33, 395, 395, 395, 395, 33, 395, 403, 33, 395, 395, 403, 33, 395, 395, 403, 33, 395, 395, 403, 33, 395, 395, 403, 33, 395, 395, 403, 33, 395, 395, 403, 33, 395, 395, 395, 403, 33, 395, 0, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395 } ; static yyconst flex_int16_t yy_nxt[2349] = { 0, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 14, 34, 33, 35, 36, 37, 38, 39, 33, 40, 33, 33, 41, 33, 42, 43, 44, 45, 46, 47, 48, 33, 33, 49, 50, 51, 52, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 53, 14, 14, 14, 14, 54, 53, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 14, 14, 14, 14, 55, 113, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 57, 57, 60, 60, 69, 170, 122, 67, 70, 61, 61, 58, 58, 68, 71, 171, 72, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 77, 76, 78, 79, 76, 76, 76, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 76, 76, 76, 76, 80, 81, 88, 91, 93, 97, 89, 99, 82, 101, 83, 92, 122, 90, 84, 85, 86, 106, 98, 94, 100, 107, 102, 108, 103, 109, 114, 104, 71, 116, 72, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 129, 128, 130, 131, 128, 128, 128, 130, 130, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 128, 128, 128, 128, 135, 140, 158, 141, 160, 164, 159, 122, 114, 165, 161, 116, 122, 122, 136, 144, 144, 144, 144, 144, 144, 144, 144, 144, 144, 144, 144, 145, 144, 146, 147, 144, 144, 144, 146, 146, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 148, 78, 78, 78, 78, 78, 78, 78, 78, 144, 144, 144, 144, 151, 151, 151, 151, 151, 151, 151, 151, 151, 151, 151, 151, 152, 151, 153, 154, 151, 151, 151, 153, 153, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 151, 151, 151, 151, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 167, 166, 168, 169, 166, 166, 166, 168, 168, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 166, 166, 166, 166, 179, 179, 179, 179, 179, 179, 179, 179, 179, 179, 179, 179, 180, 179, 181, 182, 179, 179, 179, 181, 181, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 179, 179, 179, 179, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 184, 183, 185, 186, 183, 183, 183, 185, 185, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 183, 183, 183, 183, 187, 187, 187, 187, 187, 187, 187, 187, 187, 187, 187, 187, 188, 187, 189, 190, 187, 187, 187, 189, 189, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 187, 187, 187, 187, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 206, 205, 207, 208, 205, 205, 205, 207, 207, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 205, 205, 205, 205, 210, 210, 210, 210, 210, 210, 210, 210, 210, 210, 210, 210, 211, 210, 212, 213, 210, 210, 210, 212, 212, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 210, 210, 210, 210, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 221, 220, 222, 223, 220, 220, 220, 222, 222, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 220, 220, 220, 220, 233, 233, 233, 233, 233, 233, 233, 233, 233, 233, 233, 233, 234, 233, 235, 236, 233, 233, 233, 235, 235, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 233, 233, 233, 233, 239, 239, 239, 239, 239, 239, 239, 239, 239, 239, 239, 239, 240, 239, 241, 242, 239, 239, 239, 241, 241, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 239, 239, 239, 239, 247, 247, 247, 247, 247, 247, 247, 247, 247, 247, 247, 247, 248, 247, 249, 250, 247, 247, 247, 249, 249, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 247, 247, 247, 247, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 253, 252, 254, 255, 252, 252, 252, 254, 254, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 252, 252, 252, 252, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 257, 256, 258, 259, 256, 256, 256, 258, 258, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 256, 256, 256, 256, 263, 263, 263, 263, 263, 263, 263, 263, 263, 263, 263, 263, 264, 263, 265, 266, 263, 263, 263, 265, 265, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 263, 263, 263, 263, 269, 269, 269, 269, 269, 269, 269, 269, 269, 269, 269, 269, 270, 269, 271, 272, 269, 269, 269, 271, 271, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 269, 269, 269, 269, 273, 273, 273, 273, 273, 273, 273, 273, 273, 273, 273, 273, 274, 273, 275, 276, 273, 273, 273, 275, 275, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 273, 273, 273, 273, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 280, 279, 281, 282, 279, 279, 279, 281, 281, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 279, 279, 279, 279, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 285, 284, 286, 287, 284, 284, 284, 286, 286, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 284, 284, 284, 284, 288, 288, 288, 288, 288, 288, 288, 288, 288, 288, 288, 288, 289, 288, 290, 291, 288, 288, 288, 290, 290, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 288, 288, 288, 288, 293, 122, 122, 122, 294, 299, 299, 299, 299, 299, 299, 299, 299, 299, 299, 299, 299, 300, 299, 301, 302, 299, 299, 299, 301, 301, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 299, 299, 299, 299, 305, 305, 305, 305, 305, 305, 305, 305, 305, 305, 305, 305, 306, 305, 307, 308, 305, 305, 305, 307, 307, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 305, 305, 305, 305, 309, 309, 309, 309, 309, 309, 309, 309, 309, 309, 309, 309, 310, 309, 311, 312, 309, 309, 309, 311, 311, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 309, 309, 309, 309, 318, 318, 318, 318, 318, 318, 318, 318, 318, 318, 318, 318, 319, 318, 320, 321, 318, 318, 318, 320, 320, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 318, 318, 318, 318, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 326, 325, 327, 328, 325, 325, 325, 327, 327, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 325, 325, 325, 325, 329, 329, 329, 329, 329, 329, 329, 329, 329, 329, 329, 329, 330, 329, 331, 332, 329, 329, 329, 331, 331, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 329, 329, 329, 329, 334, 334, 334, 334, 334, 334, 334, 334, 334, 334, 334, 334, 335, 334, 336, 337, 334, 334, 334, 336, 336, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 334, 334, 334, 334, 339, 339, 339, 339, 339, 339, 339, 339, 339, 339, 339, 339, 340, 339, 341, 342, 339, 339, 339, 341, 341, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 339, 339, 339, 339, 343, 343, 343, 343, 343, 343, 343, 343, 343, 343, 343, 343, 344, 343, 345, 346, 343, 343, 343, 345, 345, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 343, 343, 343, 343, 347, 347, 347, 347, 347, 347, 347, 347, 347, 347, 347, 347, 348, 347, 349, 350, 347, 347, 347, 349, 349, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 347, 347, 347, 347, 354, 354, 354, 354, 354, 354, 354, 354, 354, 354, 354, 354, 355, 354, 356, 357, 354, 354, 354, 356, 356, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 354, 354, 354, 354, 362, 362, 362, 362, 362, 362, 362, 362, 362, 362, 362, 362, 363, 362, 364, 365, 362, 362, 362, 364, 364, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 362, 362, 362, 362, 366, 366, 366, 366, 366, 366, 366, 366, 366, 366, 366, 366, 367, 366, 368, 369, 366, 366, 366, 368, 368, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 366, 366, 366, 366, 370, 370, 370, 370, 370, 370, 370, 370, 370, 370, 370, 370, 371, 370, 372, 373, 370, 370, 370, 372, 372, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 370, 370, 370, 370, 374, 374, 374, 374, 374, 374, 374, 374, 374, 374, 374, 374, 375, 374, 376, 377, 374, 374, 374, 376, 376, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 374, 374, 374, 374, 378, 378, 378, 378, 378, 378, 378, 378, 378, 378, 378, 378, 379, 378, 380, 381, 378, 378, 378, 380, 380, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 378, 378, 378, 378, 382, 382, 382, 382, 382, 382, 382, 382, 382, 382, 382, 382, 383, 382, 384, 385, 382, 382, 382, 384, 384, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 382, 382, 382, 382, 386, 386, 386, 386, 386, 386, 386, 386, 386, 386, 386, 386, 387, 386, 388, 389, 386, 386, 386, 388, 388, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 386, 386, 386, 386, 391, 391, 391, 391, 391, 391, 391, 391, 391, 391, 391, 391, 392, 391, 393, 394, 391, 391, 391, 393, 393, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 391, 391, 391, 391, 14, 14, 14, 14, 14, 56, 56, 56, 56, 56, 59, 59, 59, 59, 59, 63, 63, 63, 63, 63, 115, 115, 115, 118, 118, 121, 121, 121, 121, 174, 174, 174, 174, 176, 176, 176, 176, 390, 122, 122, 122, 122, 122, 361, 122, 122, 360, 359, 358, 122, 353, 352, 351, 122, 122, 122, 338, 333, 324, 323, 122, 122, 322, 122, 317, 122, 122, 316, 315, 122, 314, 313, 122, 122, 122, 304, 303, 298, 122, 297, 296, 122, 295, 292, 283, 278, 277, 122, 268, 267, 262, 122, 261, 122, 260, 251, 246, 245, 244, 243, 238, 237, 232, 122, 122, 122, 231, 175, 230, 229, 228, 227, 122, 226, 225, 224, 219, 218, 217, 216, 215, 214, 122, 209, 204, 122, 203, 202, 201, 200, 199, 198, 197, 196, 195, 194, 193, 192, 122, 191, 178, 122, 177, 117, 175, 173, 172, 163, 162, 157, 156, 155, 150, 149, 143, 142, 139, 138, 137, 134, 133, 132, 127, 126, 125, 124, 123, 122, 120, 64, 119, 117, 112, 111, 110, 105, 96, 95, 87, 75, 74, 73, 66, 65, 64, 62, 395, 13, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395 } ; static yyconst flex_int16_t yy_chk[2349] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 7, 400, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 9, 10, 11, 12, 27, 109, 394, 26, 27, 11, 12, 9, 10, 26, 28, 109, 28, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 34, 34, 36, 37, 38, 41, 36, 42, 34, 43, 34, 37, 389, 36, 34, 34, 34, 45, 41, 38, 42, 45, 43, 46, 43, 46, 54, 43, 72, 54, 72, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 89, 93, 103, 93, 104, 107, 103, 385, 115, 107, 104, 115, 381, 377, 89, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 162, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 195, 195, 195, 195, 195, 195, 195, 195, 195, 195, 195, 195, 195, 195, 195, 195, 195, 195, 195, 195, 195, 195, 195, 195, 195, 195, 195, 195, 195, 195, 195, 195, 195, 195, 195, 195, 195, 195, 195, 195, 195, 195, 195, 195, 195, 195, 195, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 215, 215, 215, 215, 215, 215, 215, 215, 215, 215, 215, 215, 215, 215, 215, 215, 215, 215, 215, 215, 215, 215, 215, 215, 215, 215, 215, 215, 215, 215, 215, 215, 215, 215, 215, 215, 215, 215, 215, 215, 215, 215, 215, 215, 215, 215, 215, 218, 218, 218, 218, 218, 218, 218, 218, 218, 218, 218, 218, 218, 218, 218, 218, 218, 218, 218, 218, 218, 218, 218, 218, 218, 218, 218, 218, 218, 218, 218, 218, 218, 218, 218, 218, 218, 218, 218, 218, 218, 218, 218, 218, 218, 218, 218, 219, 219, 219, 219, 219, 219, 219, 219, 219, 219, 219, 219, 219, 219, 219, 219, 219, 219, 219, 219, 219, 219, 219, 219, 219, 219, 219, 219, 219, 219, 219, 219, 219, 219, 219, 219, 219, 219, 219, 219, 219, 219, 219, 219, 219, 219, 219, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 228, 228, 228, 228, 228, 228, 228, 228, 228, 228, 228, 228, 228, 228, 228, 228, 228, 228, 228, 228, 228, 228, 228, 228, 228, 228, 228, 228, 228, 228, 228, 228, 228, 228, 228, 228, 228, 228, 228, 228, 228, 228, 228, 228, 228, 228, 228, 229, 229, 229, 229, 229, 229, 229, 229, 229, 229, 229, 229, 229, 229, 229, 229, 229, 229, 229, 229, 229, 229, 229, 229, 229, 229, 229, 229, 229, 229, 229, 229, 229, 229, 229, 229, 229, 229, 229, 229, 229, 229, 229, 229, 229, 229, 229, 231, 373, 369, 365, 231, 244, 244, 244, 244, 244, 244, 244, 244, 244, 244, 244, 244, 244, 244, 244, 244, 244, 244, 244, 244, 244, 244, 244, 244, 244, 244, 244, 244, 244, 244, 244, 244, 244, 244, 244, 244, 244, 244, 244, 244, 244, 244, 244, 244, 244, 244, 244, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 260, 260, 260, 260, 260, 260, 260, 260, 260, 260, 260, 260, 260, 260, 260, 260, 260, 260, 260, 260, 260, 260, 260, 260, 260, 260, 260, 260, 260, 260, 260, 260, 260, 260, 260, 260, 260, 260, 260, 260, 260, 260, 260, 260, 260, 260, 260, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 294, 294, 294, 294, 294, 294, 294, 294, 294, 294, 294, 294, 294, 294, 294, 294, 294, 294, 294, 294, 294, 294, 294, 294, 294, 294, 294, 294, 294, 294, 294, 294, 294, 294, 294, 294, 294, 294, 294, 294, 294, 294, 294, 294, 294, 294, 294, 295, 295, 295, 295, 295, 295, 295, 295, 295, 295, 295, 295, 295, 295, 295, 295, 295, 295, 295, 295, 295, 295, 295, 295, 295, 295, 295, 295, 295, 295, 295, 295, 295, 295, 295, 295, 295, 295, 295, 295, 295, 295, 295, 295, 295, 295, 295, 297, 297, 297, 297, 297, 297, 297, 297, 297, 297, 297, 297, 297, 297, 297, 297, 297, 297, 297, 297, 297, 297, 297, 297, 297, 297, 297, 297, 297, 297, 297, 297, 297, 297, 297, 297, 297, 297, 297, 297, 297, 297, 297, 297, 297, 297, 297, 303, 303, 303, 303, 303, 303, 303, 303, 303, 303, 303, 303, 303, 303, 303, 303, 303, 303, 303, 303, 303, 303, 303, 303, 303, 303, 303, 303, 303, 303, 303, 303, 303, 303, 303, 303, 303, 303, 303, 303, 303, 303, 303, 303, 303, 303, 303, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 313, 313, 313, 313, 313, 313, 313, 313, 313, 313, 313, 313, 313, 313, 313, 313, 313, 313, 313, 313, 313, 313, 313, 313, 313, 313, 313, 313, 313, 313, 313, 313, 313, 313, 313, 313, 313, 313, 313, 313, 313, 313, 313, 313, 313, 313, 313, 317, 317, 317, 317, 317, 317, 317, 317, 317, 317, 317, 317, 317, 317, 317, 317, 317, 317, 317, 317, 317, 317, 317, 317, 317, 317, 317, 317, 317, 317, 317, 317, 317, 317, 317, 317, 317, 317, 317, 317, 317, 317, 317, 317, 317, 317, 317, 338, 338, 338, 338, 338, 338, 338, 338, 338, 338, 338, 338, 338, 338, 338, 338, 338, 338, 338, 338, 338, 338, 338, 338, 338, 338, 338, 338, 338, 338, 338, 338, 338, 338, 338, 338, 338, 338, 338, 338, 338, 338, 338, 338, 338, 338, 338, 351, 351, 351, 351, 351, 351, 351, 351, 351, 351, 351, 351, 351, 351, 351, 351, 351, 351, 351, 351, 351, 351, 351, 351, 351, 351, 351, 351, 351, 351, 351, 351, 351, 351, 351, 351, 351, 351, 351, 351, 351, 351, 351, 351, 351, 351, 351, 352, 352, 352, 352, 352, 352, 352, 352, 352, 352, 352, 352, 352, 352, 352, 352, 352, 352, 352, 352, 352, 352, 352, 352, 352, 352, 352, 352, 352, 352, 352, 352, 352, 352, 352, 352, 352, 352, 352, 352, 352, 352, 352, 352, 352, 352, 352, 353, 353, 353, 353, 353, 353, 353, 353, 353, 353, 353, 353, 353, 353, 353, 353, 353, 353, 353, 353, 353, 353, 353, 353, 353, 353, 353, 353, 353, 353, 353, 353, 353, 353, 353, 353, 353, 353, 353, 353, 353, 353, 353, 353, 353, 353, 353, 358, 358, 358, 358, 358, 358, 358, 358, 358, 358, 358, 358, 358, 358, 358, 358, 358, 358, 358, 358, 358, 358, 358, 358, 358, 358, 358, 358, 358, 358, 358, 358, 358, 358, 358, 358, 358, 358, 358, 358, 358, 358, 358, 358, 358, 358, 358, 359, 359, 359, 359, 359, 359, 359, 359, 359, 359, 359, 359, 359, 359, 359, 359, 359, 359, 359, 359, 359, 359, 359, 359, 359, 359, 359, 359, 359, 359, 359, 359, 359, 359, 359, 359, 359, 359, 359, 359, 359, 359, 359, 359, 359, 359, 359, 360, 360, 360, 360, 360, 360, 360, 360, 360, 360, 360, 360, 360, 360, 360, 360, 360, 360, 360, 360, 360, 360, 360, 360, 360, 360, 360, 360, 360, 360, 360, 360, 360, 360, 360, 360, 360, 360, 360, 360, 360, 360, 360, 360, 360, 360, 360, 390, 390, 390, 390, 390, 390, 390, 390, 390, 390, 390, 390, 390, 390, 390, 390, 390, 390, 390, 390, 390, 390, 390, 390, 390, 390, 390, 390, 390, 390, 390, 390, 390, 390, 390, 390, 390, 390, 390, 390, 390, 390, 390, 390, 390, 390, 390, 396, 396, 396, 396, 396, 397, 397, 397, 397, 397, 398, 398, 398, 398, 398, 399, 399, 399, 399, 399, 401, 401, 401, 402, 402, 403, 403, 403, 403, 404, 404, 404, 404, 405, 405, 405, 405, 361, 357, 350, 346, 342, 337, 333, 332, 328, 324, 323, 322, 321, 316, 315, 314, 312, 308, 302, 298, 296, 293, 292, 291, 287, 283, 282, 277, 276, 272, 268, 267, 266, 262, 261, 259, 255, 250, 246, 245, 243, 242, 238, 237, 236, 232, 230, 227, 225, 224, 223, 217, 216, 214, 213, 209, 208, 204, 201, 199, 198, 197, 196, 194, 193, 191, 190, 186, 182, 178, 175, 173, 172, 171, 170, 169, 165, 164, 163, 161, 160, 159, 158, 157, 156, 154, 150, 148, 147, 143, 142, 141, 140, 139, 138, 137, 136, 135, 134, 133, 132, 131, 127, 123, 122, 120, 118, 116, 111, 110, 106, 105, 102, 101, 100, 98, 97, 95, 94, 92, 91, 90, 88, 87, 86, 84, 83, 82, 81, 80, 79, 71, 63, 61, 55, 50, 48, 47, 44, 40, 39, 35, 32, 31, 30, 25, 20, 18, 17, 13, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395 } ; static yy_state_type yy_last_accepting_state; static char *yy_last_accepting_cpos; extern int yy_flex_debug; int yy_flex_debug = 0; /* The intent behind this definition is that it'll catch * any uses of REJECT which flex missed. */ #define REJECT reject_used_but_not_detected #define yymore() yymore_used_but_not_detected #define YY_MORE_ADJ 0 #define YY_RESTORE_YY_MORE_OFFSET char *yytext; #line 1 "mm.lpp" /****************************************************************************** * Copyright (c) 2013-2014, Amsterdam University of Applied Sciences (HvA) and * Centrum Wiskunde & Informatica (CWI) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Contributors: * * Riemer van Rozen - rozen@cwi.nl - HvA / CWI ******************************************************************************/ #line 36 "mm.lpp" /* * * * * * * * * * * * * * * DEFINITIONS * * * * * * * * * * * * * * */ #line 42 "mm.lpp" #include "YYLTYPE.h" #include "mm.h" #define LEX_ID_SIZE 256 #ifdef _MSC_VER #include "mm.tab.hpp" #define YY_NO_UNISTD_H #include "io.h" #else #include "y.tab.h" #endif //FIXME: globals should be instance data //TODO: add a Parser abstraction (a.k.a. re-entrant parsing) int yycolumn = 1; //TODO: attribute of parser char yyid[256] = { 0 }; //TODO: attribute of parser char yystr[256] = { 0 }; //TODO: attribute of parser int yyidpos = 0; //TODO: attribute of parser bool inID = false; //TODO: attribute of parser //added for missing line-break at end of file bool _t = false; #define yyterminate() return (_t = !_t) ? END : YY_NULL #define YY_USER_ACTION \ if(inID == false) \ { \ yylloc.first_line = (int) yylineno; \ yylloc.first_column = (int) yycolumn; \ yylloc.last_line = (int) yylineno; \ } \ yylloc.last_column = (int) yycolumn + (int) yyleng - 1; \ yycolumn += yyleng; //%option yylineno #line 81 "mm.lpp" /* * * * * * * * * * * * * STATES * * * * * * * * * * * * */ #line 1191 "lex.mm.cpp" #define INITIAL 0 #define ERROR 1 #define IDPART 2 #define IDPART2 3 #define IN_S_COMMENT 4 #define IN_M_COMMENT 5 #ifndef YY_NO_UNISTD_H /* Special case for "unistd.h", since it is non-ANSI. We include it way * down here because we want the user's section 1 to have been scanned first. * The user has a chance to override it with an option. */ #include <unistd.h> #endif #ifndef YY_EXTRA_TYPE #define YY_EXTRA_TYPE void * #endif static int yy_init_globals (void ); /* Accessor methods to globals. These are made visible to non-reentrant scanners for convenience. */ int yylex_destroy (void ); int yyget_debug (void ); void yyset_debug (int debug_flag ); YY_EXTRA_TYPE yyget_extra (void ); void yyset_extra (YY_EXTRA_TYPE user_defined ); FILE *yyget_in (void ); void yyset_in (FILE * in_str ); FILE *yyget_out (void ); void yyset_out (FILE * out_str ); int yyget_leng (void ); char *yyget_text (void ); int yyget_lineno (void ); void yyset_lineno (int line_number ); /* Macros after this point can all be overridden by user definitions in * section 1. */ #ifndef YY_SKIP_YYWRAP #ifdef __cplusplus extern "C" int yywrap (void ); #else extern int yywrap (void ); #endif #endif static void yyunput (int c,char *buf_ptr ); #ifndef yytext_ptr static void yy_flex_strncpy (char *,yyconst char *,int ); #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * ); #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (void ); #else static int input (void ); #endif #endif /* Amount of stuff to slurp up with each read. */ #ifndef YY_READ_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k */ #define YY_READ_BUF_SIZE 16384 #else #define YY_READ_BUF_SIZE 8192 #endif /* __ia64__ */ #endif /* Copy whatever the last rule matched to the standard output. */ #ifndef ECHO /* This used to be an fputs(), but since the string might contain NUL's, * we now use fwrite(). */ #define ECHO do { if (fwrite( yytext, yyleng, 1, yyout )) {} } while (0) #endif /* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, * is returned in "result". */ #ifndef YY_INPUT #define YY_INPUT(buf,result,max_size) \ if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \ { \ int c = '*'; \ size_t n; \ for ( n = 0; n < max_size && \ (c = getc( yyin )) != EOF && c != '\n'; ++n ) \ buf[n] = (char) c; \ if ( c == '\n' ) \ buf[n++] = (char) c; \ if ( c == EOF && ferror( yyin ) ) \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ result = n; \ } \ else \ { \ errno=0; \ while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \ { \ if( errno != EINTR) \ { \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ break; \ } \ errno=0; \ clearerr(yyin); \ } \ }\ \ #endif /* No semi-colon after return; correct usage is to write "yyterminate();" - * we don't want an extra ';' after the "return" because that will cause * some compilers to complain about unreachable statements. */ #ifndef yyterminate #define yyterminate() return YY_NULL #endif /* Number of entries by which start-condition stack grows. */ #ifndef YY_START_STACK_INCR #define YY_START_STACK_INCR 25 #endif /* Report a fatal error. */ #ifndef YY_FATAL_ERROR #define YY_FATAL_ERROR(msg) yy_fatal_error( msg ) #endif /* end tables serialization structures and prototypes */ /* Default declaration of generated scanner - a define so the user can * easily add parameters. */ #ifndef YY_DECL #define YY_DECL_IS_OURS 1 extern int yylex (void); #define YY_DECL int yylex (void) #endif /* !YY_DECL */ /* Code executed at the beginning of each rule, after yytext and yyleng * have been set up. */ #ifndef YY_USER_ACTION #define YY_USER_ACTION #endif /* Code executed at the end of each rule. */ #ifndef YY_BREAK #define YY_BREAK break; #endif #define YY_RULE_SETUP \ YY_USER_ACTION /** The main scanner function which does all the work. */ YY_DECL { register yy_state_type yy_current_state; register char *yy_cp, *yy_bp; register int yy_act; #line 91 "mm.lpp" /* * * * * * * * * * * * RULES * * * * * * * * * * * */ #line 1392 "lex.mm.cpp" if ( !(yy_init) ) { (yy_init) = 1; #ifdef YY_USER_INIT YY_USER_INIT; #endif if ( ! (yy_start) ) (yy_start) = 1; /* first start state */ if ( ! yyin ) yyin = stdin; if ( ! yyout ) yyout = stdout; if ( ! YY_CURRENT_BUFFER ) { yyensure_buffer_stack (); YY_CURRENT_BUFFER_LVALUE = yy_create_buffer(yyin,YY_BUF_SIZE ); } yy_load_buffer_state( ); } while ( 1 ) /* loops until end-of-file is reached */ { yy_cp = (yy_c_buf_p); /* Support of yytext. */ *yy_cp = (yy_hold_char); /* yy_bp points to the position in yy_ch_buf of the start of * the current run. */ yy_bp = yy_cp; yy_current_state = (yy_start); yy_match: do { register YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)]; if ( yy_accept[yy_current_state] ) { (yy_last_accepting_state) = yy_current_state; (yy_last_accepting_cpos) = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 396 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; ++yy_cp; } while ( yy_base[yy_current_state] != 2301 ); yy_find_action: yy_act = yy_accept[yy_current_state]; if ( yy_act == 0 ) { /* have to back up */ yy_cp = (yy_last_accepting_cpos); yy_current_state = (yy_last_accepting_state); yy_act = yy_accept[yy_current_state]; } YY_DO_BEFORE_ACTION; do_action: /* This label is used only to access EOF actions. */ switch ( yy_act ) { /* beginning of action switch */ case 0: /* must back up */ /* undo the effects of YY_DO_BEFORE_ACTION */ *yy_cp = (yy_hold_char); yy_cp = (yy_last_accepting_cpos); yy_current_state = (yy_last_accepting_state); goto yy_find_action; case 1: YY_RULE_SETUP #line 99 "mm.lpp" { inID = false; /*ignore*/ } YY_BREAK case 2: /* rule 2 can match eol */ YY_RULE_SETUP #line 100 "mm.lpp" { inID = false; yylineno++; yycolumn = 1; } YY_BREAK case 3: YY_RULE_SETUP #line 102 "mm.lpp" { inID = false; BEGIN(IN_S_COMMENT); } YY_BREAK case 4: /* rule 4 can match eol */ YY_RULE_SETUP #line 103 "mm.lpp" { inID = false; yylineno++; yycolumn = 1; BEGIN(INITIAL); } YY_BREAK case 5: /* rule 5 can match eol */ YY_RULE_SETUP #line 104 "mm.lpp" { inID = false; } YY_BREAK case 6: YY_RULE_SETUP #line 105 "mm.lpp" { inID = false; } YY_BREAK case 7: YY_RULE_SETUP #line 108 "mm.lpp" { inID = false; BEGIN(IN_M_COMMENT); } YY_BREAK case 8: YY_RULE_SETUP #line 109 "mm.lpp" { inID = false; BEGIN(INITIAL); } YY_BREAK case 9: /* rule 9 can match eol */ YY_RULE_SETUP #line 110 "mm.lpp" { inID = false; yylineno++; yycolumn = 1; } YY_BREAK case 10: /* rule 10 can match eol */ YY_RULE_SETUP #line 111 "mm.lpp" { inID = false; } YY_BREAK case 11: YY_RULE_SETUP #line 112 "mm.lpp" { inID = false; } YY_BREAK case 12: YY_RULE_SETUP #line 114 "mm.lpp" { inID = false; return AND; } YY_BREAK case 13: YY_RULE_SETUP #line 115 "mm.lpp" { inID = false; return OR; } YY_BREAK case 14: YY_RULE_SETUP #line 116 "mm.lpp" { inID = false; return RANGE; } YY_BREAK case 15: YY_RULE_SETUP #line 117 "mm.lpp" { inID = false; return DOT_GT; } YY_BREAK case 16: YY_RULE_SETUP #line 118 "mm.lpp" { inID = false; return SUB_GT; } YY_BREAK case 17: YY_RULE_SETUP #line 119 "mm.lpp" { inID = false; return EQ; } YY_BREAK case 18: YY_RULE_SETUP #line 120 "mm.lpp" { inID = false; return NE; } YY_BREAK case 19: YY_RULE_SETUP #line 121 "mm.lpp" { inID = false; return LE; } YY_BREAK case 20: YY_RULE_SETUP #line 122 "mm.lpp" { inID = false; return GE; } YY_BREAK case 21: YY_RULE_SETUP #line 123 "mm.lpp" { inID = false; return LT; } YY_BREAK case 22: YY_RULE_SETUP #line 124 "mm.lpp" { inID = false; return GT; } YY_BREAK case 23: YY_RULE_SETUP #line 125 "mm.lpp" { inID = false; return DOT; } YY_BREAK case 24: YY_RULE_SETUP #line 126 "mm.lpp" { inID = false; return SUB; } YY_BREAK case 25: YY_RULE_SETUP #line 127 "mm.lpp" { inID = false; return UNM; } YY_BREAK case 26: YY_RULE_SETUP #line 128 "mm.lpp" { inID = false; return ADD; } YY_BREAK case 27: YY_RULE_SETUP #line 129 "mm.lpp" { inID = false; return MUL; } YY_BREAK case 28: YY_RULE_SETUP #line 130 "mm.lpp" { inID = false; return DIV; } YY_BREAK case 29: YY_RULE_SETUP #line 131 "mm.lpp" { inID = false; return ALIAS; } YY_BREAK case 30: YY_RULE_SETUP #line 132 "mm.lpp" { inID = false; return LPAREN; } YY_BREAK case 31: YY_RULE_SETUP #line 133 "mm.lpp" { inID = false; return RPAREN; } YY_BREAK case 32: YY_RULE_SETUP #line 134 "mm.lpp" { inID = false; return NOT; } YY_BREAK case 33: YY_RULE_SETUP #line 135 "mm.lpp" { inID = false; return PER; } YY_BREAK case 34: YY_RULE_SETUP #line 136 "mm.lpp" { inID = false; return LCURLY; } YY_BREAK case 35: YY_RULE_SETUP #line 137 "mm.lpp" { inID = false; return RCURLY; } YY_BREAK case 36: YY_RULE_SETUP #line 138 "mm.lpp" { inID = false; return COLON; } YY_BREAK case 37: YY_RULE_SETUP #line 139 "mm.lpp" { inID = false; return PERCENT; } YY_BREAK case 38: /* rule 38 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up yytext */ (yy_c_buf_p) = yy_cp = yy_bp + 6; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 140 "mm.lpp" { inID = false; return SOURCE; } YY_BREAK case 39: /* rule 39 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up yytext */ (yy_c_buf_p) = yy_cp = yy_bp + 5; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 141 "mm.lpp" { inID = false; return DRAIN; } YY_BREAK case 40: /* rule 40 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up yytext */ (yy_c_buf_p) = yy_cp = yy_bp + 4; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 142 "mm.lpp" { inID = false; return POOL; } YY_BREAK case 41: /* rule 41 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up yytext */ (yy_c_buf_p) = yy_cp = yy_bp + 4; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 143 "mm.lpp" { inID = false; return GATE; } YY_BREAK case 42: /* rule 42 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up yytext */ (yy_c_buf_p) = yy_cp = yy_bp + 9; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 144 "mm.lpp" { inID = false; return CONVERTER; } YY_BREAK case 43: /* rule 43 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up yytext */ (yy_c_buf_p) = yy_cp = yy_bp + 4; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 145 "mm.lpp" { inID = false; return PUSH; } YY_BREAK case 44: /* rule 44 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up yytext */ (yy_c_buf_p) = yy_cp = yy_bp + 4; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 146 "mm.lpp" { inID = false; return PULL; } YY_BREAK case 45: /* rule 45 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up yytext */ (yy_c_buf_p) = yy_cp = yy_bp + 7; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 147 "mm.lpp" { inID = false; return PASSIVE; } YY_BREAK case 46: /* rule 46 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up yytext */ (yy_c_buf_p) = yy_cp = yy_bp + 3; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 148 "mm.lpp" { inID = false; return ALL; } YY_BREAK case 47: /* rule 47 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up yytext */ (yy_c_buf_p) = yy_cp = yy_bp + 3; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 149 "mm.lpp" { inID = false; return ANY; } YY_BREAK case 48: /* rule 48 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up yytext */ (yy_c_buf_p) = yy_cp = yy_bp + 4; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 150 "mm.lpp" { inID = false; return AUTO; } YY_BREAK case 49: /* rule 49 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up yytext */ (yy_c_buf_p) = yy_cp = yy_bp + 4; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 151 "mm.lpp" { inID = false; return USER; } YY_BREAK case 50: /* rule 50 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up yytext */ (yy_c_buf_p) = yy_cp = yy_bp + 5; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 152 "mm.lpp" { inID = false; return START; } YY_BREAK case 51: /* rule 51 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up yytext */ (yy_c_buf_p) = yy_cp = yy_bp + 3; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 153 "mm.lpp" { inID = false; return MAX; } YY_BREAK case 52: /* rule 52 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up yytext */ (yy_c_buf_p) = yy_cp = yy_bp + 2; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 154 "mm.lpp" { inID = false; return AT; } YY_BREAK case 53: /* rule 53 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up yytext */ (yy_c_buf_p) = yy_cp = yy_bp + 2; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 155 "mm.lpp" { inID = false; return IN; } YY_BREAK case 54: /* rule 54 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up yytext */ (yy_c_buf_p) = yy_cp = yy_bp + 3; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 156 "mm.lpp" { inID = false; return OUT; } YY_BREAK case 55: /* rule 55 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up yytext */ (yy_c_buf_p) = yy_cp = yy_bp + 5; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 157 "mm.lpp" { inID = false; return INOUT; } YY_BREAK case 56: /* rule 56 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up yytext */ (yy_c_buf_p) = yy_cp = yy_bp + 6; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 158 "mm.lpp" { inID = false; return EXTERN; } YY_BREAK case 57: /* rule 57 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up yytext */ (yy_c_buf_p) = yy_cp = yy_bp + 3; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 159 "mm.lpp" { inID = false; return REF; } YY_BREAK case 58: /* rule 58 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up yytext */ (yy_c_buf_p) = yy_cp = yy_bp + 4; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 160 "mm.lpp" { inID = false; return DICE; } YY_BREAK case 59: /* rule 59 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up yytext */ (yy_c_buf_p) = yy_cp = yy_bp + 6; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 161 "mm.lpp" { inID = false; return ACTIVE; } YY_BREAK case 60: /* rule 60 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up yytext */ (yy_c_buf_p) = yy_cp = yy_bp + 5; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 162 "mm.lpp" { inID = false; return FALSE; } YY_BREAK case 61: /* rule 61 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up yytext */ (yy_c_buf_p) = yy_cp = yy_bp + 4; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 163 "mm.lpp" { inID = false; return TRUE; } YY_BREAK case 62: /* rule 62 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up yytext */ (yy_c_buf_p) = yy_cp = yy_bp + 7; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 164 "mm.lpp" { inID = false; return PRIVATE; } YY_BREAK case 63: /* rule 63 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up yytext */ (yy_c_buf_p) = yy_cp = yy_bp + 2; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 165 "mm.lpp" { inID = false; return OF; } YY_BREAK case 64: /* rule 64 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up yytext */ (yy_c_buf_p) = yy_cp = yy_bp + 3; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 166 "mm.lpp" { inID = false; return ADDITION; } YY_BREAK case 65: /* rule 65 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up yytext */ (yy_c_buf_p) = yy_cp = yy_bp + 4; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 167 "mm.lpp" { inID = false; return FROM; } YY_BREAK case 66: /* rule 66 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up yytext */ (yy_c_buf_p) = yy_cp = yy_bp + 2; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 168 "mm.lpp" { inID = false; return TO; } YY_BREAK case 67: /* rule 67 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up yytext */ (yy_c_buf_p) = yy_cp = yy_bp + 6; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 169 "mm.lpp" { inID = false; return ASSERT; } YY_BREAK case 68: /* rule 68 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up yytext */ (yy_c_buf_p) = yy_cp = yy_bp + 6; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 170 "mm.lpp" { inID = false; return DELETE; } YY_BREAK case 69: /* rule 69 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up yytext */ (yy_c_buf_p) = yy_cp = yy_bp + 7; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 171 "mm.lpp" { inID = false; return VIOLATE; } YY_BREAK case 70: /* rule 70 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up yytext */ (yy_c_buf_p) = yy_cp = yy_bp + 8; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 172 "mm.lpp" { inID = false; return ACTIVATE; } YY_BREAK case 71: /* rule 71 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up yytext */ (yy_c_buf_p) = yy_cp = yy_bp + 4; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 173 "mm.lpp" { inID = false; return FAIL; } YY_BREAK case 72: /* rule 72 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up yytext */ (yy_c_buf_p) = yy_cp = yy_bp + 7; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 174 "mm.lpp" { inID = false; return PREVENT; } YY_BREAK case 73: /* rule 73 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up yytext */ (yy_c_buf_p) = yy_cp = yy_bp + 7; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 175 "mm.lpp" { inID = false; return DISABLE; } YY_BREAK case 74: /* rule 74 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up yytext */ (yy_c_buf_p) = yy_cp = yy_bp + 6; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 176 "mm.lpp" { inID = false; return DISABLE; } YY_BREAK case 75: /* rule 75 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up yytext */ (yy_c_buf_p) = yy_cp = yy_bp + 7; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 177 "mm.lpp" { inID = false; return TRIGGER; } YY_BREAK case 76: /* rule 76 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up yytext */ (yy_c_buf_p) = yy_cp = yy_bp + 6; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 178 "mm.lpp" { inID = false; return MODIFY; } YY_BREAK case 77: /* rule 77 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up yytext */ (yy_c_buf_p) = yy_cp = yy_bp + 4; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 179 "mm.lpp" { inID = false; return STEP; } YY_BREAK case 78: /* rule 78 can match eol */ YY_RULE_SETUP #line 181 "mm.lpp" { inID = false; yylval.str = strdup(yytext); //copy string in yyval.str MM_printf("line %d col %d endline %d endcol %d : [%s]\n", yylloc.first_line, yylloc.first_column, yylloc.last_line, yylloc.last_column, yylval.str); return STRING; } YY_BREAK case 79: YY_RULE_SETUP #line 192 "mm.lpp" { inID = false; yylval.val = atol(yytext) * 100; //store integer size_t size = strcspn(yytext, "."); if(size < yyleng) { yylval.val += atol(yytext+size+1); //store fraction } return FPVAL; } YY_BREAK case 80: YY_RULE_SETUP #line 203 "mm.lpp" { inID = false; yylval.val = atol(yytext) * 100; //store integer return FPVAL; } YY_BREAK case 81: /* rule 81 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up yytext */ (yy_c_buf_p) = yy_cp -= 1; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 209 "mm.lpp" { inID = false; //NOTE: this buffer is freed in the parser yylval.str = strdup(yytext); //printf("ID [%s]\n", yytext); //yylloc.first_line = (int) yylineno; //yylloc.first_column = (int) yycolumn; //yylloc.last_line = (int) yylineno; //printf("first part [%s]\n", yytext); return ID; } YY_BREAK case 82: /* rule 82 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up yytext */ (yy_c_buf_p) = yy_cp -= 1; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 224 "mm.lpp" { inID = true; sprintf(yyid + yyidpos, "%s", yytext); //store remainder of the ID in global yyid yyidpos += strlen(yytext); //printf("IDPART [%s]\n", yytext); BEGIN(IDPART); } YY_BREAK case 83: YY_RULE_SETUP #line 235 "mm.lpp" { inID = true; sprintf(yyid + yyidpos, "%s", yytext); //store remainder of the ID in global yyid yyidpos += strlen(yytext); //printf("IDPART [%s]\n", yytext); BEGIN(IDPART2); } YY_BREAK case 84: /* rule 84 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up yytext */ (yy_c_buf_p) = yy_cp -= 1; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 246 "mm.lpp" { inID = true; //printf("%s\n", yytext); sprintf(yyid + yyidpos, "%s", yytext); //store remainder of the ID in global yyid yyidpos += strlen(yytext); //printf("IDPART [%s]\n", yytext); BEGIN(IDPART); } YY_BREAK case 85: YY_RULE_SETUP #line 257 "mm.lpp" { inID = true; //printf("%s\n", yytext); sprintf(yyid + yyidpos, "%s", yytext); //store remainder of the ID in global yyid yyidpos += strlen(yytext); //printf("IDPART [%s]\n", yytext); BEGIN(IDPART2); } YY_BREAK case 86: /* rule 86 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up yytext */ (yy_c_buf_p) = yy_cp -= 1; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 268 "mm.lpp" { inID = true; //printf("%s\n", yytext); sprintf(yyid + yyidpos, "%s", yytext); //store remainder of the ID in global yyid yyidpos += strlen(yytext); //printf("IDPART [%s]\n", yytext); BEGIN(IDPART2); } YY_BREAK case 87: YY_RULE_SETUP #line 279 "mm.lpp" { ///[^.] inID = false; sprintf(yyid + yyidpos, "%s", yytext); //store remainder of the ID in global yyid yyidpos += strlen(yytext); //NOTE: this buffer is freed in the parser yylval.str = (MM::CHAR*) malloc(yyidpos + 2); //allocate memory memset(yylval.str, 0, yyidpos + 2); //clear memory snprintf(yylval.str, yyidpos + 2, "%s",yyid); //store identifier //printf("part [%s]\n", yylval.str); yyidpos = 0; memset(yyid, 0, LEX_ID_SIZE); BEGIN(INITIAL); return ID; } YY_BREAK case 88: YY_RULE_SETUP #line 299 "mm.lpp" ECHO; YY_BREAK #line 2195 "lex.mm.cpp" case YY_STATE_EOF(INITIAL): case YY_STATE_EOF(ERROR): case YY_STATE_EOF(IDPART): case YY_STATE_EOF(IDPART2): case YY_STATE_EOF(IN_S_COMMENT): case YY_STATE_EOF(IN_M_COMMENT): yyterminate(); case YY_END_OF_BUFFER: { /* Amount of text matched not including the EOB char. */ int yy_amount_of_matched_text = (int) (yy_cp - (yytext_ptr)) - 1; /* Undo the effects of YY_DO_BEFORE_ACTION. */ *yy_cp = (yy_hold_char); YY_RESTORE_YY_MORE_OFFSET if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW ) { /* We're scanning a new file or input source. It's * possible that this happened because the user * just pointed yyin at a new source and called * yylex(). If so, then we have to assure * consistency between YY_CURRENT_BUFFER and our * globals. Here is the right place to do so, because * this is the first action (other than possibly a * back-up) that will match for the new input source. */ (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL; } /* Note that here we test for yy_c_buf_p "<=" to the position * of the first EOB in the buffer, since yy_c_buf_p will * already have been incremented past the NUL character * (since all states make transitions on EOB to the * end-of-buffer state). Contrast this with the test * in input(). */ if ( (yy_c_buf_p) <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] ) { /* This was really a NUL. */ yy_state_type yy_next_state; (yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( ); /* Okay, we're now positioned to make the NUL * transition. We couldn't have * yy_get_previous_state() go ahead and do it * for us because it doesn't know how to deal * with the possibility of jamming (and we don't * want to build jamming into it because then it * will run more slowly). */ yy_next_state = yy_try_NUL_trans( yy_current_state ); yy_bp = (yytext_ptr) + YY_MORE_ADJ; if ( yy_next_state ) { /* Consume the NUL. */ yy_cp = ++(yy_c_buf_p); yy_current_state = yy_next_state; goto yy_match; } else { yy_cp = (yy_c_buf_p); goto yy_find_action; } } else switch ( yy_get_next_buffer( ) ) { case EOB_ACT_END_OF_FILE: { (yy_did_buffer_switch_on_eof) = 0; if ( yywrap( ) ) { /* Note: because we've taken care in * yy_get_next_buffer() to have set up * yytext, we can now set up * yy_c_buf_p so that if some total * hoser (like flex itself) wants to * call the scanner after we return the * YY_NULL, it'll still work - another * YY_NULL will get returned. */ (yy_c_buf_p) = (yytext_ptr) + YY_MORE_ADJ; yy_act = YY_STATE_EOF(YY_START); goto do_action; } else { if ( ! (yy_did_buffer_switch_on_eof) ) YY_NEW_FILE; } break; } case EOB_ACT_CONTINUE_SCAN: (yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( ); yy_cp = (yy_c_buf_p); yy_bp = (yytext_ptr) + YY_MORE_ADJ; goto yy_match; case EOB_ACT_LAST_MATCH: (yy_c_buf_p) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)]; yy_current_state = yy_get_previous_state( ); yy_cp = (yy_c_buf_p); yy_bp = (yytext_ptr) + YY_MORE_ADJ; goto yy_find_action; } break; } default: YY_FATAL_ERROR( "fatal flex scanner internal error--no action found" ); } /* end of action switch */ } /* end of scanning one token */ } /* end of yylex */ /* yy_get_next_buffer - try to read in a new buffer * * Returns a code representing an action: * EOB_ACT_LAST_MATCH - * EOB_ACT_CONTINUE_SCAN - continue scanning from current position * EOB_ACT_END_OF_FILE - end of file */ static int yy_get_next_buffer (void) { register char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf; register char *source = (yytext_ptr); register int number_to_move, i; int ret_val; if ( (yy_c_buf_p) > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] ) YY_FATAL_ERROR( "fatal flex scanner internal error--end of buffer missed" ); if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 ) { /* Don't try to fill the buffer, so this is an EOF. */ if ( (yy_c_buf_p) - (yytext_ptr) - YY_MORE_ADJ == 1 ) { /* We matched a single character, the EOB, so * treat this as a final EOF. */ return EOB_ACT_END_OF_FILE; } else { /* We matched some text prior to the EOB, first * process it. */ return EOB_ACT_LAST_MATCH; } } /* Try to read more data. */ /* First move last chars to start of buffer. */ number_to_move = (int) ((yy_c_buf_p) - (yytext_ptr)) - 1; for ( i = 0; i < number_to_move; ++i ) *(dest++) = *(source++); if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING ) /* don't do the read, it's not guaranteed to return an EOF, * just force an EOF */ YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars) = 0; else { int num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; while ( num_to_read <= 0 ) { /* Not enough room in the buffer - grow it. */ /* just a shorter name for the current buffer */ YY_BUFFER_STATE b = YY_CURRENT_BUFFER; int yy_c_buf_p_offset = (int) ((yy_c_buf_p) - b->yy_ch_buf); if ( b->yy_is_our_buffer ) { int new_size = b->yy_buf_size * 2; if ( new_size <= 0 ) b->yy_buf_size += b->yy_buf_size / 8; else b->yy_buf_size *= 2; b->yy_ch_buf = (char *) /* Include room in for 2 EOB chars. */ yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ); } else /* Can't grow it, we don't own it. */ b->yy_ch_buf = 0; if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "fatal error - scanner input buffer overflow" ); (yy_c_buf_p) = &b->yy_ch_buf[yy_c_buf_p_offset]; num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; } if ( num_to_read > YY_READ_BUF_SIZE ) num_to_read = YY_READ_BUF_SIZE; /* Read in more data. */ YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]), (yy_n_chars), (size_t) num_to_read ); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); } if ( (yy_n_chars) == 0 ) { if ( number_to_move == YY_MORE_ADJ ) { ret_val = EOB_ACT_END_OF_FILE; yyrestart(yyin ); } else { ret_val = EOB_ACT_LAST_MATCH; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_EOF_PENDING; } } else ret_val = EOB_ACT_CONTINUE_SCAN; if ((yy_size_t) ((yy_n_chars) + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) { /* Extend the array by 50%, plus the number we really need. */ yy_size_t new_size = (yy_n_chars) + number_to_move + ((yy_n_chars) >> 1); YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ); if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" ); } (yy_n_chars) += number_to_move; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] = YY_END_OF_BUFFER_CHAR; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] = YY_END_OF_BUFFER_CHAR; (yytext_ptr) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0]; return ret_val; } /* yy_get_previous_state - get the state just before the EOB char was reached */ static yy_state_type yy_get_previous_state (void) { register yy_state_type yy_current_state; register char *yy_cp; yy_current_state = (yy_start); for ( yy_cp = (yytext_ptr) + YY_MORE_ADJ; yy_cp < (yy_c_buf_p); ++yy_cp ) { register YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); if ( yy_accept[yy_current_state] ) { (yy_last_accepting_state) = yy_current_state; (yy_last_accepting_cpos) = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 396 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; } return yy_current_state; } /* yy_try_NUL_trans - try to make a transition on the NUL character * * synopsis * next_state = yy_try_NUL_trans( current_state ); */ static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state ) { register int yy_is_jam; register char *yy_cp = (yy_c_buf_p); register YY_CHAR yy_c = 1; if ( yy_accept[yy_current_state] ) { (yy_last_accepting_state) = yy_current_state; (yy_last_accepting_cpos) = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 396 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; yy_is_jam = (yy_current_state == 395); return yy_is_jam ? 0 : yy_current_state; } static void yyunput (int c, register char * yy_bp ) { register char *yy_cp; yy_cp = (yy_c_buf_p); /* undo effects of setting up yytext */ *yy_cp = (yy_hold_char); if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 ) { /* need to shift things up to make room */ /* +2 for EOB chars. */ register int number_to_move = (yy_n_chars) + 2; register char *dest = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[ YY_CURRENT_BUFFER_LVALUE->yy_buf_size + 2]; register char *source = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]; while ( source > YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) *--dest = *--source; yy_cp += (int) (dest - source); yy_bp += (int) (dest - source); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_buf_size; if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 ) YY_FATAL_ERROR( "flex scanner push-back overflow" ); } *--yy_cp = (char) c; (yytext_ptr) = yy_bp; (yy_hold_char) = *yy_cp; (yy_c_buf_p) = yy_cp; } #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (void) #else static int input (void) #endif { int c; *(yy_c_buf_p) = (yy_hold_char); if ( *(yy_c_buf_p) == YY_END_OF_BUFFER_CHAR ) { /* yy_c_buf_p now points to the character we want to return. * If this occurs *before* the EOB characters, then it's a * valid NUL; if not, then we've hit the end of the buffer. */ if ( (yy_c_buf_p) < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] ) /* This was really a NUL. */ *(yy_c_buf_p) = '\0'; else { /* need more input */ int offset = (yy_c_buf_p) - (yytext_ptr); ++(yy_c_buf_p); switch ( yy_get_next_buffer( ) ) { case EOB_ACT_LAST_MATCH: /* This happens because yy_g_n_b() * sees that we've accumulated a * token and flags that we need to * try matching the token before * proceeding. But for input(), * there's no matching to consider. * So convert the EOB_ACT_LAST_MATCH * to EOB_ACT_END_OF_FILE. */ /* Reset buffer status. */ yyrestart(yyin ); /*FALLTHROUGH*/ case EOB_ACT_END_OF_FILE: { if ( yywrap( ) ) return EOF; if ( ! (yy_did_buffer_switch_on_eof) ) YY_NEW_FILE; #ifdef __cplusplus return yyinput(); #else return input(); #endif } case EOB_ACT_CONTINUE_SCAN: (yy_c_buf_p) = (yytext_ptr) + offset; break; } } } c = *(unsigned char *) (yy_c_buf_p); /* cast for 8-bit char's */ *(yy_c_buf_p) = '\0'; /* preserve yytext */ (yy_hold_char) = *++(yy_c_buf_p); return c; } #endif /* ifndef YY_NO_INPUT */ /** Immediately switch to a different input stream. * @param input_file A readable stream. * * @note This function does not reset the start condition to @c INITIAL . */ void yyrestart (FILE * input_file ) { if ( ! YY_CURRENT_BUFFER ){ yyensure_buffer_stack (); YY_CURRENT_BUFFER_LVALUE = yy_create_buffer(yyin,YY_BUF_SIZE ); } yy_init_buffer(YY_CURRENT_BUFFER,input_file ); yy_load_buffer_state( ); } /** Switch to a different input buffer. * @param new_buffer The new input buffer. * */ void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ) { /* TODO. We should be able to replace this entire function body * with * yypop_buffer_state(); * yypush_buffer_state(new_buffer); */ yyensure_buffer_stack (); if ( YY_CURRENT_BUFFER == new_buffer ) return; if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *(yy_c_buf_p) = (yy_hold_char); YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); } YY_CURRENT_BUFFER_LVALUE = new_buffer; yy_load_buffer_state( ); /* We don't actually know whether we did this switch during * EOF (yywrap()) processing, but the only time this flag * is looked at is after yywrap() is called, so it's safe * to go ahead and always set it. */ (yy_did_buffer_switch_on_eof) = 1; } static void yy_load_buffer_state (void) { (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; (yytext_ptr) = (yy_c_buf_p) = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos; yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file; (yy_hold_char) = *(yy_c_buf_p); } /** Allocate and initialize an input buffer state. * @param file A readable stream. * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE. * * @return the allocated buffer state. */ YY_BUFFER_STATE yy_create_buffer (FILE * file, int size ) { YY_BUFFER_STATE b; b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state ) ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); b->yy_buf_size = size; /* yy_ch_buf has to be 2 characters longer than the size given because * we need to put in 2 end-of-buffer characters. */ b->yy_ch_buf = (char *) yyalloc(b->yy_buf_size + 2 ); if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); b->yy_is_our_buffer = 1; yy_init_buffer(b,file ); return b; } /** Destroy the buffer. * @param b a buffer created with yy_create_buffer() * */ void yy_delete_buffer (YY_BUFFER_STATE b ) { if ( ! b ) return; if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */ YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0; if ( b->yy_is_our_buffer ) yyfree((void *) b->yy_ch_buf ); yyfree((void *) b ); } #ifndef __cplusplus extern int isatty (int ); #endif /* __cplusplus */ /* Initializes or reinitializes a buffer. * This function is sometimes called more than once on the same buffer, * such as during a yyrestart() or at EOF. */ static void yy_init_buffer (YY_BUFFER_STATE b, FILE * file ) { int oerrno = errno; yy_flush_buffer(b ); b->yy_input_file = file; b->yy_fill_buffer = 1; /* If b is the current buffer, then yy_init_buffer was _probably_ * called from yyrestart() or through yy_get_next_buffer. * In that case, we don't want to reset the lineno or column. */ if (b != YY_CURRENT_BUFFER){ b->yy_bs_lineno = 1; b->yy_bs_column = 0; } b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0; errno = oerrno; } /** Discard all buffered characters. On the next scan, YY_INPUT will be called. * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER. * */ void yy_flush_buffer (YY_BUFFER_STATE b ) { if ( ! b ) return; b->yy_n_chars = 0; /* We always need two end-of-buffer characters. The first causes * a transition to the end-of-buffer state. The second causes * a jam in that state. */ b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; b->yy_buf_pos = &b->yy_ch_buf[0]; b->yy_at_bol = 1; b->yy_buffer_status = YY_BUFFER_NEW; if ( b == YY_CURRENT_BUFFER ) yy_load_buffer_state( ); } /** Pushes the new state onto the stack. The new state becomes * the current state. This function will allocate the stack * if necessary. * @param new_buffer The new state. * */ void yypush_buffer_state (YY_BUFFER_STATE new_buffer ) { if (new_buffer == NULL) return; yyensure_buffer_stack(); /* This block is copied from yy_switch_to_buffer. */ if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *(yy_c_buf_p) = (yy_hold_char); YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); } /* Only push if top exists. Otherwise, replace top. */ if (YY_CURRENT_BUFFER) (yy_buffer_stack_top)++; YY_CURRENT_BUFFER_LVALUE = new_buffer; /* copied from yy_switch_to_buffer. */ yy_load_buffer_state( ); (yy_did_buffer_switch_on_eof) = 1; } /** Removes and deletes the top of the stack, if present. * The next element becomes the new top. * */ void yypop_buffer_state (void) { if (!YY_CURRENT_BUFFER) return; yy_delete_buffer(YY_CURRENT_BUFFER ); YY_CURRENT_BUFFER_LVALUE = NULL; if ((yy_buffer_stack_top) > 0) --(yy_buffer_stack_top); if (YY_CURRENT_BUFFER) { yy_load_buffer_state( ); (yy_did_buffer_switch_on_eof) = 1; } } /* Allocates the stack if it does not exist. * Guarantees space for at least one push. */ static void yyensure_buffer_stack (void) { int num_to_alloc; if (!(yy_buffer_stack)) { /* First allocation is just for 2 elements, since we don't know if this * scanner will even need a stack. We use 2 instead of 1 to avoid an * immediate realloc on the next call. */ num_to_alloc = 1; (yy_buffer_stack) = (struct yy_buffer_state**)yyalloc (num_to_alloc * sizeof(struct yy_buffer_state*) ); if ( ! (yy_buffer_stack) ) YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" ); memset((yy_buffer_stack), 0, num_to_alloc * sizeof(struct yy_buffer_state*)); (yy_buffer_stack_max) = num_to_alloc; (yy_buffer_stack_top) = 0; return; } if ((yy_buffer_stack_top) >= ((yy_buffer_stack_max)) - 1){ /* Increase the buffer to prepare for a possible push. */ int grow_size = 8 /* arbitrary grow size */; num_to_alloc = (yy_buffer_stack_max) + grow_size; (yy_buffer_stack) = (struct yy_buffer_state**)yyrealloc ((yy_buffer_stack), num_to_alloc * sizeof(struct yy_buffer_state*) ); if ( ! (yy_buffer_stack) ) YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" ); /* zero only the new slots.*/ memset((yy_buffer_stack) + (yy_buffer_stack_max), 0, grow_size * sizeof(struct yy_buffer_state*)); (yy_buffer_stack_max) = num_to_alloc; } } /** Setup the input buffer state to scan directly from a user-specified character buffer. * @param base the character buffer * @param size the size in bytes of the character buffer * * @return the newly allocated buffer state object. */ YY_BUFFER_STATE yy_scan_buffer (char * base, yy_size_t size ) { YY_BUFFER_STATE b; if ( size < 2 || base[size-2] != YY_END_OF_BUFFER_CHAR || base[size-1] != YY_END_OF_BUFFER_CHAR ) /* They forgot to leave room for the EOB's. */ return 0; b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state ) ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" ); b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */ b->yy_buf_pos = b->yy_ch_buf = base; b->yy_is_our_buffer = 0; b->yy_input_file = 0; b->yy_n_chars = b->yy_buf_size; b->yy_is_interactive = 0; b->yy_at_bol = 1; b->yy_fill_buffer = 0; b->yy_buffer_status = YY_BUFFER_NEW; yy_switch_to_buffer(b ); return b; } /** Setup the input buffer state to scan a string. The next call to yylex() will * scan from a @e copy of @a str. * @param yystr a NUL-terminated string to scan * * @return the newly allocated buffer state object. * @note If you want to scan bytes that may contain NUL values, then use * yy_scan_bytes() instead. */ YY_BUFFER_STATE yy_scan_string (yyconst char * yystr ) { return yy_scan_bytes(yystr,strlen(yystr) ); } /** Setup the input buffer state to scan the given bytes. The next call to yylex() will * scan from a @e copy of @a bytes. * @param yybytes the byte buffer to scan * @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes. * * @return the newly allocated buffer state object. */ YY_BUFFER_STATE yy_scan_bytes (yyconst char * yybytes, int _yybytes_len ) { YY_BUFFER_STATE b; char *buf; yy_size_t n; int i; /* Get memory for full buffer, including space for trailing EOB's. */ n = _yybytes_len + 2; buf = (char *) yyalloc(n ); if ( ! buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" ); for ( i = 0; i < _yybytes_len; ++i ) buf[i] = yybytes[i]; buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR; b = yy_scan_buffer(buf,n ); if ( ! b ) YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" ); /* It's okay to grow etc. this buffer, and we should throw it * away when we're done. */ b->yy_is_our_buffer = 1; return b; } #ifndef YY_EXIT_FAILURE #define YY_EXIT_FAILURE 2 #endif static void yy_fatal_error (yyconst char* msg ) { (void) fprintf( stderr, "%s\n", msg ); exit( YY_EXIT_FAILURE ); } /* Redefine yyless() so it works in section 3 code. */ #undef yyless #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ yytext[yyleng] = (yy_hold_char); \ (yy_c_buf_p) = yytext + yyless_macro_arg; \ (yy_hold_char) = *(yy_c_buf_p); \ *(yy_c_buf_p) = '\0'; \ yyleng = yyless_macro_arg; \ } \ while ( 0 ) /* Accessor methods (get/set functions) to struct members. */ /** Get the current line number. * */ int yyget_lineno (void) { return yylineno; } /** Get the input stream. * */ FILE *yyget_in (void) { return yyin; } /** Get the output stream. * */ FILE *yyget_out (void) { return yyout; } /** Get the length of the current token. * */ int yyget_leng (void) { return yyleng; } /** Get the current token. * */ char *yyget_text (void) { return yytext; } /** Set the current line number. * @param line_number * */ void yyset_lineno (int line_number ) { yylineno = line_number; } /** Set the input stream. This does not discard the current * input buffer. * @param in_str A readable stream. * * @see yy_switch_to_buffer */ void yyset_in (FILE * in_str ) { yyin = in_str ; } void yyset_out (FILE * out_str ) { yyout = out_str ; } int yyget_debug (void) { return yy_flex_debug; } void yyset_debug (int bdebug ) { yy_flex_debug = bdebug ; } static int yy_init_globals (void) { /* Initialization is the same as for the non-reentrant scanner. * This function is called from yylex_destroy(), so don't allocate here. */ (yy_buffer_stack) = 0; (yy_buffer_stack_top) = 0; (yy_buffer_stack_max) = 0; (yy_c_buf_p) = (char *) 0; (yy_init) = 0; (yy_start) = 0; /* Defined in main.c */ #ifdef YY_STDINIT yyin = stdin; yyout = stdout; #else yyin = (FILE *) 0; yyout = (FILE *) 0; #endif /* For future reference: Set errno on error, since we are called by * yylex_init() */ return 0; } /* yylex_destroy is for both reentrant and non-reentrant scanners. */ int yylex_destroy (void) { /* Pop the buffer stack, destroying each element. */ while(YY_CURRENT_BUFFER){ yy_delete_buffer(YY_CURRENT_BUFFER ); YY_CURRENT_BUFFER_LVALUE = NULL; yypop_buffer_state(); } /* Destroy the stack itself. */ yyfree((yy_buffer_stack) ); (yy_buffer_stack) = NULL; /* Reset the globals. This is important in a non-reentrant scanner so the next time * yylex() is called, initialization will occur. */ yy_init_globals( ); return 0; } /* * Internal utility routines. */ #ifndef yytext_ptr static void yy_flex_strncpy (char* s1, yyconst char * s2, int n ) { register int i; for ( i = 0; i < n; ++i ) s1[i] = s2[i]; } #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * s ) { register int n; for ( n = 0; s[n]; ++n ) ; return n; } #endif void *yyalloc (yy_size_t size ) { return (void *) malloc( size ); } void *yyrealloc (void * ptr, yy_size_t size ) { /* The cast to (char *) in the following accommodates both * implementations that use char* generic pointers, and those * that use void* generic pointers. It works with the latter * because both ANSI C and C++ allow castless assignment from * any pointer type to void*, and deal with argument conversions * as though doing an assignment. */ return (void *) realloc( (char *) ptr, size ); } void yyfree (void * ptr ) { free( (char *) ptr ); /* see yyrealloc() for (char *) cast */ } #define YYTABLES_NAME "yytables" #line 299 "mm.lpp"
32.454403
116
0.56341
Mirv
f696f446810c5cf7ab7369b5355ee31acdc07ef4
199
cpp
C++
codeforces/630C.cpp
cosmicray001/Online_judge_Solutions-
5dc6f90d3848eb192e6edea8e8c731f41a1761dd
[ "MIT" ]
3
2018-01-08T02:52:51.000Z
2021-03-03T01:08:44.000Z
codeforces/630C.cpp
cosmicray001/Online_judge_Solutions-
5dc6f90d3848eb192e6edea8e8c731f41a1761dd
[ "MIT" ]
null
null
null
codeforces/630C.cpp
cosmicray001/Online_judge_Solutions-
5dc6f90d3848eb192e6edea8e8c731f41a1761dd
[ "MIT" ]
1
2020-08-13T18:07:35.000Z
2020-08-13T18:07:35.000Z
#include <bits/stdc++.h> #define ll long long int using namespace std; int main(){ ll a, sum = 0; cin >> a; for(ll i = 1; i < a + 1; i++) sum += pow(2, i); cout << sum << endl; return 0; }
18.090909
49
0.537688
cosmicray001
f69c916bb43a2ae390f02d12a15a246165c5a53e
5,753
cpp
C++
src/packettable.cpp
marcusbirkin/ETCDmxTool
33f9aafcb7f0f78f59fc8ad3441878762202330a
[ "Apache-2.0" ]
12
2019-03-26T22:19:06.000Z
2022-03-14T07:59:37.000Z
src/packettable.cpp
marcusbirkin/ETCDmxTool
33f9aafcb7f0f78f59fc8ad3441878762202330a
[ "Apache-2.0" ]
5
2019-05-18T16:45:45.000Z
2020-05-12T23:46:10.000Z
src/packettable.cpp
marcusbirkin/ETCDmxTool
33f9aafcb7f0f78f59fc8ad3441878762202330a
[ "Apache-2.0" ]
5
2019-02-26T13:23:43.000Z
2021-10-01T11:24:26.000Z
// Copyright (c) 2017 Electronic Theatre Controls, Inc., http://www.etcconnect.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 "packettable.h" #include <QDateTime> PacketTable::PacketTable(QObject *parent) : QAbstractTableModel(parent), m_timeFormat(DATE_AND_TIME) { emit timeFormatChange(); } PacketTable::~PacketTable() { } int PacketTable::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return m_packets.count(); } int PacketTable::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent); return COLCOUNT; } QVariant PacketTable::headerData(int section, Qt::Orientation orientation, int role) const { if (role != Qt::DisplayRole) return QVariant(); if (orientation == Qt::Vertical) return section; switch(section) { case Timestamp : return tr("Timestamp"); case Source : return tr("Source"); case Destination : return tr("Destination"); case Protocol : return tr("Protocol"); case Info : return tr("Information"); } return QVariant(); } QVariant PacketTable::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); int row = index.row(); if ((row >=0) && (row < rowCount())) { DissectorPlugin *dissector = m_dissectors->getDissector(m_packets.at(row)); quint64 timestamp=0, previous=0, first=0; timestamp = m_packets.at(row).timestamp; if(row>0) previous = m_packets.at(row-1).timestamp; first = m_packets.at(0).timestamp; if (dissector == Q_NULLPTR) { // Fallthrough to handle unknown data switch (index.column()) { case Timestamp : if (role == Qt::DisplayRole) return formatTime(timestamp, previous, first); break; case Protocol : if (role == Qt::DisplayRole && m_packets.at(row).length()>0) return tr("Unknown (0x%1)").arg(m_packets.at(row)[0], 2, 16, QLatin1Char('0')); if (role == Qt::DisplayRole && m_packets.at(row).length()==0) return tr("Empty"); break; } return QVariant(); } switch (index.column()) { case Timestamp : if (role == Qt::DisplayRole) return formatTime(timestamp, previous, first); break; case Source : if (role == Qt::DisplayRole) return dissector->getSource(m_packets.at(row)); break; case Destination : if (role == Qt::DisplayRole) return dissector->getDestination(m_packets.at(row)); break; case Protocol : if (role == Qt::DisplayRole) return dissector->getProtocolName(); break; case Info : if (role == Qt::DisplayRole) return dissector->getInfo(m_packets.at(row)); break; default:; } } return QVariant(); } void PacketTable::clearAll() { beginResetModel(); m_packets.clear(); endResetModel(); } void PacketTable::appendPacket(Packet &packet) { DissectorPlugin *dissector = Q_NULLPTR; if (m_dissectors) dissector = m_dissectors->getDissector(packet); decltype(m_packets) newPackets; int startRow = rowCount(); int endRow = startRow; if(dissector) endRow = startRow - 1 + dissector->preprocessPacket(packet, newPackets); else newPackets << packet; if (endRow >= startRow) { beginInsertRows(QModelIndex(), startRow, endRow); m_packets.append(newPackets); endInsertRows(); } emit newPacket(); } const Packet &PacketTable::getPacket(int row) const { return m_packets.at(row); } Packet PacketTable::takePacket(int row) { return m_packets.takeAt(row); } void PacketTable::registerProtocolDissectors(dissectors *dissectors) { m_dissectors = dissectors; } QString PacketTable::formatTime(quint64 time, quint64 previous, quint64 start) const { QDateTime dt = QDateTime::fromMSecsSinceEpoch(time); switch(m_timeFormat) { case DATE_AND_TIME: return dt.toString("yyyy-MM-dd hh:mm:ss.zzz"); case TIME_OF_DAY: return dt.toString("hh:mm:ss.zzz"); case SECONDS_SINCE_CAPTURE_START: return QString::number((time - start)/1000.0); case SECONDS_SINCE_PREVIOUS_PACKET: return QString::number((time - previous)/1000.0); } return QString::number(time); } void PacketTable::discardDmxData() { beginResetModel(); QMutableListIterator<Packet>i(m_packets); while(i.hasNext()) { Packet p = i.next(); if(p.at(0)==00) i.remove(); } endResetModel(); }
29.963542
156
0.644881
marcusbirkin
f69f2be60d0e72334adfa7084ac432c7ac3190ec
3,679
cxx
C++
Testing/Code/Review/itkImageReadComplexWriteMagnitudeAndPhaseTest.cxx
dtglidden/ITK
ef0c16fee4fac904d6ab706b8f7d438d4062cd96
[ "BSD-3-Clause" ]
1
2017-07-31T18:41:02.000Z
2017-07-31T18:41:02.000Z
Testing/Code/Review/itkImageReadComplexWriteMagnitudeAndPhaseTest.cxx
dtglidden/ITK
ef0c16fee4fac904d6ab706b8f7d438d4062cd96
[ "BSD-3-Clause" ]
null
null
null
Testing/Code/Review/itkImageReadComplexWriteMagnitudeAndPhaseTest.cxx
dtglidden/ITK
ef0c16fee4fac904d6ab706b8f7d438d4062cd96
[ "BSD-3-Clause" ]
null
null
null
/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkImageReadComplexWriteMagnitudeAndPhaseTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #ifdef __BORLANDC__ #define ITK_LEAN_AND_MEAN #endif /** Example illustrating use of functions to convert between complex valued * voxels, magnitude and phase, and real and imaginary representations. * * \author Simon K. Warfield simon.warfield@childrens.harvard.edu * * \note Attribution Notice. This research work was made possible by Grant * Number R01 RR021885 (PI Simon K. Warfield, Ph.D.) from * the National Center for Research Resources (NCRR), a component of the * National Institutes of Health (NIH). Its contents are solely the * responsibility of the authors and do not necessarily represent the * official view of NCRR or NIH. * */ // Software Guide : BeginCodeSnippet #include "itkImage.h" #include "itkComplexToModulusImageFilter.h" #include "itkComplexToPhaseImageFilter.h" // Software Guide : EndCodeSnippet #include "itkImageFileReader.h" #include "itkImageFileWriter.h" int itkImageReadComplexWriteMagnitudeAndPhaseTest( int argc, char * argv [] ) { if( argc < 4 ) { std::cerr << "Usage: " << argv[0] << " inputComplexImage outputMagnitudePartOfComplexImage " << "outputPhasePartOfComplexImage" << std::endl; } const unsigned int Dimension = 2; typedef float InputPixelType; typedef float OutputPixelType; typedef itk::Image< std::complex<InputPixelType>, Dimension > InputImageType; typedef itk::Image< OutputPixelType, Dimension > OutputImageType; typedef itk::ImageFileReader< InputImageType > ReaderType; typedef itk::ComplexToModulusImageFilter< InputImageType, OutputImageType > ModulusFilterType; typedef itk::ComplexToPhaseImageFilter< InputImageType, OutputImageType > PhaseFilterType; typedef itk::ImageFileWriter< OutputImageType > WriterType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( argv[1] ); ModulusFilterType::Pointer modulusFilter = ModulusFilterType::New(); modulusFilter->SetInput( reader->GetOutput() ); WriterType::Pointer writerM = WriterType::New(); writerM->SetInput(modulusFilter->GetOutput()); writerM->SetFileName( argv[2] ); try { writerM->Update(); } catch( itk::ExceptionObject & excp ) { std::cerr << "Error writing the magnitude image: " << std::endl; std::cerr << excp << std::endl; return EXIT_FAILURE; } PhaseFilterType::Pointer phaseFilter = PhaseFilterType::New(); phaseFilter->SetInput( reader->GetOutput() ); WriterType::Pointer writerP = WriterType::New(); writerP->SetInput(phaseFilter->GetOutput()); writerP->SetFileName( argv[3] ); try { writerP->Update(); } catch( itk::ExceptionObject & excp ) { std::cerr << "Error writing the phase image: " << std::endl; std::cerr << excp << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }
31.991304
84
0.670834
dtglidden
f6a0a117b18517bbb1175a8752d6ff531add8bdd
92,834
hpp
C++
externals/boost/boost/math/special_functions/prime.hpp
YuukiTsuchida/v8_embeded
c6e18f4e91fcc50607f8e3edc745a3afa30b2871
[ "MIT" ]
995
2018-06-22T10:39:18.000Z
2022-03-25T01:22:14.000Z
jeff/common/include/boost/math/special_functions/prime.hpp
jeffphi/advent-of-code-2018
8e54bd23ebfe42fcbede315f0ab85db903551532
[ "MIT" ]
32
2018-06-23T14:19:37.000Z
2022-03-29T10:20:37.000Z
jeff/common/include/boost/math/special_functions/prime.hpp
jeffphi/advent-of-code-2018
8e54bd23ebfe42fcbede315f0ab85db903551532
[ "MIT" ]
172
2018-06-22T11:12:00.000Z
2022-03-29T07:44:33.000Z
// Copyright 2008 John Maddock // // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt // or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_MATH_SF_PRIME_HPP #define BOOST_MATH_SF_PRIME_HPP #include <boost/cstdint.hpp> #include <boost/math/policies/error_handling.hpp> #include <boost/math/special_functions/math_fwd.hpp> #ifdef BOOST_MATH_HAVE_CONSTEXPR_TABLES #include <array> #else #include <boost/array.hpp> #endif namespace boost{ namespace math{ template <class Policy> BOOST_MATH_CONSTEXPR_TABLE_FUNCTION boost::uint32_t prime(unsigned n, const Policy& pol) { // // This is basically three big tables which together // occupy 19946 bytes, we use the smallest type which // will handle each value, and store the final set of // values in a uint16_t with the values offset by 0xffff. // That gives us the first 10000 primes with the largest // being 104729: // #ifdef BOOST_MATH_HAVE_CONSTEXPR_TABLES constexpr unsigned b1 = 53; constexpr unsigned b2 = 6541; constexpr unsigned b3 = 10000; constexpr std::array<unsigned char, 54> a1 = {{ #else static const unsigned b1 = 53; static const unsigned b2 = 6541; static const unsigned b3 = 10000; static const boost::array<unsigned char, 54> a1 = {{ #endif 2u, 3u, 5u, 7u, 11u, 13u, 17u, 19u, 23u, 29u, 31u, 37u, 41u, 43u, 47u, 53u, 59u, 61u, 67u, 71u, 73u, 79u, 83u, 89u, 97u, 101u, 103u, 107u, 109u, 113u, 127u, 131u, 137u, 139u, 149u, 151u, 157u, 163u, 167u, 173u, 179u, 181u, 191u, 193u, 197u, 199u, 211u, 223u, 227u, 229u, 233u, 239u, 241u, 251u }}; #ifdef BOOST_MATH_HAVE_CONSTEXPR_TABLES constexpr std::array<boost::uint16_t, 6488> a2 = {{ #else static const boost::array<boost::uint16_t, 6488> a2 = {{ #endif 257u, 263u, 269u, 271u, 277u, 281u, 283u, 293u, 307u, 311u, 313u, 317u, 331u, 337u, 347u, 349u, 353u, 359u, 367u, 373u, 379u, 383u, 389u, 397u, 401u, 409u, 419u, 421u, 431u, 433u, 439u, 443u, 449u, 457u, 461u, 463u, 467u, 479u, 487u, 491u, 499u, 503u, 509u, 521u, 523u, 541u, 547u, 557u, 563u, 569u, 571u, 577u, 587u, 593u, 599u, 601u, 607u, 613u, 617u, 619u, 631u, 641u, 643u, 647u, 653u, 659u, 661u, 673u, 677u, 683u, 691u, 701u, 709u, 719u, 727u, 733u, 739u, 743u, 751u, 757u, 761u, 769u, 773u, 787u, 797u, 809u, 811u, 821u, 823u, 827u, 829u, 839u, 853u, 857u, 859u, 863u, 877u, 881u, 883u, 887u, 907u, 911u, 919u, 929u, 937u, 941u, 947u, 953u, 967u, 971u, 977u, 983u, 991u, 997u, 1009u, 1013u, 1019u, 1021u, 1031u, 1033u, 1039u, 1049u, 1051u, 1061u, 1063u, 1069u, 1087u, 1091u, 1093u, 1097u, 1103u, 1109u, 1117u, 1123u, 1129u, 1151u, 1153u, 1163u, 1171u, 1181u, 1187u, 1193u, 1201u, 1213u, 1217u, 1223u, 1229u, 1231u, 1237u, 1249u, 1259u, 1277u, 1279u, 1283u, 1289u, 1291u, 1297u, 1301u, 1303u, 1307u, 1319u, 1321u, 1327u, 1361u, 1367u, 1373u, 1381u, 1399u, 1409u, 1423u, 1427u, 1429u, 1433u, 1439u, 1447u, 1451u, 1453u, 1459u, 1471u, 1481u, 1483u, 1487u, 1489u, 1493u, 1499u, 1511u, 1523u, 1531u, 1543u, 1549u, 1553u, 1559u, 1567u, 1571u, 1579u, 1583u, 1597u, 1601u, 1607u, 1609u, 1613u, 1619u, 1621u, 1627u, 1637u, 1657u, 1663u, 1667u, 1669u, 1693u, 1697u, 1699u, 1709u, 1721u, 1723u, 1733u, 1741u, 1747u, 1753u, 1759u, 1777u, 1783u, 1787u, 1789u, 1801u, 1811u, 1823u, 1831u, 1847u, 1861u, 1867u, 1871u, 1873u, 1877u, 1879u, 1889u, 1901u, 1907u, 1913u, 1931u, 1933u, 1949u, 1951u, 1973u, 1979u, 1987u, 1993u, 1997u, 1999u, 2003u, 2011u, 2017u, 2027u, 2029u, 2039u, 2053u, 2063u, 2069u, 2081u, 2083u, 2087u, 2089u, 2099u, 2111u, 2113u, 2129u, 2131u, 2137u, 2141u, 2143u, 2153u, 2161u, 2179u, 2203u, 2207u, 2213u, 2221u, 2237u, 2239u, 2243u, 2251u, 2267u, 2269u, 2273u, 2281u, 2287u, 2293u, 2297u, 2309u, 2311u, 2333u, 2339u, 2341u, 2347u, 2351u, 2357u, 2371u, 2377u, 2381u, 2383u, 2389u, 2393u, 2399u, 2411u, 2417u, 2423u, 2437u, 2441u, 2447u, 2459u, 2467u, 2473u, 2477u, 2503u, 2521u, 2531u, 2539u, 2543u, 2549u, 2551u, 2557u, 2579u, 2591u, 2593u, 2609u, 2617u, 2621u, 2633u, 2647u, 2657u, 2659u, 2663u, 2671u, 2677u, 2683u, 2687u, 2689u, 2693u, 2699u, 2707u, 2711u, 2713u, 2719u, 2729u, 2731u, 2741u, 2749u, 2753u, 2767u, 2777u, 2789u, 2791u, 2797u, 2801u, 2803u, 2819u, 2833u, 2837u, 2843u, 2851u, 2857u, 2861u, 2879u, 2887u, 2897u, 2903u, 2909u, 2917u, 2927u, 2939u, 2953u, 2957u, 2963u, 2969u, 2971u, 2999u, 3001u, 3011u, 3019u, 3023u, 3037u, 3041u, 3049u, 3061u, 3067u, 3079u, 3083u, 3089u, 3109u, 3119u, 3121u, 3137u, 3163u, 3167u, 3169u, 3181u, 3187u, 3191u, 3203u, 3209u, 3217u, 3221u, 3229u, 3251u, 3253u, 3257u, 3259u, 3271u, 3299u, 3301u, 3307u, 3313u, 3319u, 3323u, 3329u, 3331u, 3343u, 3347u, 3359u, 3361u, 3371u, 3373u, 3389u, 3391u, 3407u, 3413u, 3433u, 3449u, 3457u, 3461u, 3463u, 3467u, 3469u, 3491u, 3499u, 3511u, 3517u, 3527u, 3529u, 3533u, 3539u, 3541u, 3547u, 3557u, 3559u, 3571u, 3581u, 3583u, 3593u, 3607u, 3613u, 3617u, 3623u, 3631u, 3637u, 3643u, 3659u, 3671u, 3673u, 3677u, 3691u, 3697u, 3701u, 3709u, 3719u, 3727u, 3733u, 3739u, 3761u, 3767u, 3769u, 3779u, 3793u, 3797u, 3803u, 3821u, 3823u, 3833u, 3847u, 3851u, 3853u, 3863u, 3877u, 3881u, 3889u, 3907u, 3911u, 3917u, 3919u, 3923u, 3929u, 3931u, 3943u, 3947u, 3967u, 3989u, 4001u, 4003u, 4007u, 4013u, 4019u, 4021u, 4027u, 4049u, 4051u, 4057u, 4073u, 4079u, 4091u, 4093u, 4099u, 4111u, 4127u, 4129u, 4133u, 4139u, 4153u, 4157u, 4159u, 4177u, 4201u, 4211u, 4217u, 4219u, 4229u, 4231u, 4241u, 4243u, 4253u, 4259u, 4261u, 4271u, 4273u, 4283u, 4289u, 4297u, 4327u, 4337u, 4339u, 4349u, 4357u, 4363u, 4373u, 4391u, 4397u, 4409u, 4421u, 4423u, 4441u, 4447u, 4451u, 4457u, 4463u, 4481u, 4483u, 4493u, 4507u, 4513u, 4517u, 4519u, 4523u, 4547u, 4549u, 4561u, 4567u, 4583u, 4591u, 4597u, 4603u, 4621u, 4637u, 4639u, 4643u, 4649u, 4651u, 4657u, 4663u, 4673u, 4679u, 4691u, 4703u, 4721u, 4723u, 4729u, 4733u, 4751u, 4759u, 4783u, 4787u, 4789u, 4793u, 4799u, 4801u, 4813u, 4817u, 4831u, 4861u, 4871u, 4877u, 4889u, 4903u, 4909u, 4919u, 4931u, 4933u, 4937u, 4943u, 4951u, 4957u, 4967u, 4969u, 4973u, 4987u, 4993u, 4999u, 5003u, 5009u, 5011u, 5021u, 5023u, 5039u, 5051u, 5059u, 5077u, 5081u, 5087u, 5099u, 5101u, 5107u, 5113u, 5119u, 5147u, 5153u, 5167u, 5171u, 5179u, 5189u, 5197u, 5209u, 5227u, 5231u, 5233u, 5237u, 5261u, 5273u, 5279u, 5281u, 5297u, 5303u, 5309u, 5323u, 5333u, 5347u, 5351u, 5381u, 5387u, 5393u, 5399u, 5407u, 5413u, 5417u, 5419u, 5431u, 5437u, 5441u, 5443u, 5449u, 5471u, 5477u, 5479u, 5483u, 5501u, 5503u, 5507u, 5519u, 5521u, 5527u, 5531u, 5557u, 5563u, 5569u, 5573u, 5581u, 5591u, 5623u, 5639u, 5641u, 5647u, 5651u, 5653u, 5657u, 5659u, 5669u, 5683u, 5689u, 5693u, 5701u, 5711u, 5717u, 5737u, 5741u, 5743u, 5749u, 5779u, 5783u, 5791u, 5801u, 5807u, 5813u, 5821u, 5827u, 5839u, 5843u, 5849u, 5851u, 5857u, 5861u, 5867u, 5869u, 5879u, 5881u, 5897u, 5903u, 5923u, 5927u, 5939u, 5953u, 5981u, 5987u, 6007u, 6011u, 6029u, 6037u, 6043u, 6047u, 6053u, 6067u, 6073u, 6079u, 6089u, 6091u, 6101u, 6113u, 6121u, 6131u, 6133u, 6143u, 6151u, 6163u, 6173u, 6197u, 6199u, 6203u, 6211u, 6217u, 6221u, 6229u, 6247u, 6257u, 6263u, 6269u, 6271u, 6277u, 6287u, 6299u, 6301u, 6311u, 6317u, 6323u, 6329u, 6337u, 6343u, 6353u, 6359u, 6361u, 6367u, 6373u, 6379u, 6389u, 6397u, 6421u, 6427u, 6449u, 6451u, 6469u, 6473u, 6481u, 6491u, 6521u, 6529u, 6547u, 6551u, 6553u, 6563u, 6569u, 6571u, 6577u, 6581u, 6599u, 6607u, 6619u, 6637u, 6653u, 6659u, 6661u, 6673u, 6679u, 6689u, 6691u, 6701u, 6703u, 6709u, 6719u, 6733u, 6737u, 6761u, 6763u, 6779u, 6781u, 6791u, 6793u, 6803u, 6823u, 6827u, 6829u, 6833u, 6841u, 6857u, 6863u, 6869u, 6871u, 6883u, 6899u, 6907u, 6911u, 6917u, 6947u, 6949u, 6959u, 6961u, 6967u, 6971u, 6977u, 6983u, 6991u, 6997u, 7001u, 7013u, 7019u, 7027u, 7039u, 7043u, 7057u, 7069u, 7079u, 7103u, 7109u, 7121u, 7127u, 7129u, 7151u, 7159u, 7177u, 7187u, 7193u, 7207u, 7211u, 7213u, 7219u, 7229u, 7237u, 7243u, 7247u, 7253u, 7283u, 7297u, 7307u, 7309u, 7321u, 7331u, 7333u, 7349u, 7351u, 7369u, 7393u, 7411u, 7417u, 7433u, 7451u, 7457u, 7459u, 7477u, 7481u, 7487u, 7489u, 7499u, 7507u, 7517u, 7523u, 7529u, 7537u, 7541u, 7547u, 7549u, 7559u, 7561u, 7573u, 7577u, 7583u, 7589u, 7591u, 7603u, 7607u, 7621u, 7639u, 7643u, 7649u, 7669u, 7673u, 7681u, 7687u, 7691u, 7699u, 7703u, 7717u, 7723u, 7727u, 7741u, 7753u, 7757u, 7759u, 7789u, 7793u, 7817u, 7823u, 7829u, 7841u, 7853u, 7867u, 7873u, 7877u, 7879u, 7883u, 7901u, 7907u, 7919u, 7927u, 7933u, 7937u, 7949u, 7951u, 7963u, 7993u, 8009u, 8011u, 8017u, 8039u, 8053u, 8059u, 8069u, 8081u, 8087u, 8089u, 8093u, 8101u, 8111u, 8117u, 8123u, 8147u, 8161u, 8167u, 8171u, 8179u, 8191u, 8209u, 8219u, 8221u, 8231u, 8233u, 8237u, 8243u, 8263u, 8269u, 8273u, 8287u, 8291u, 8293u, 8297u, 8311u, 8317u, 8329u, 8353u, 8363u, 8369u, 8377u, 8387u, 8389u, 8419u, 8423u, 8429u, 8431u, 8443u, 8447u, 8461u, 8467u, 8501u, 8513u, 8521u, 8527u, 8537u, 8539u, 8543u, 8563u, 8573u, 8581u, 8597u, 8599u, 8609u, 8623u, 8627u, 8629u, 8641u, 8647u, 8663u, 8669u, 8677u, 8681u, 8689u, 8693u, 8699u, 8707u, 8713u, 8719u, 8731u, 8737u, 8741u, 8747u, 8753u, 8761u, 8779u, 8783u, 8803u, 8807u, 8819u, 8821u, 8831u, 8837u, 8839u, 8849u, 8861u, 8863u, 8867u, 8887u, 8893u, 8923u, 8929u, 8933u, 8941u, 8951u, 8963u, 8969u, 8971u, 8999u, 9001u, 9007u, 9011u, 9013u, 9029u, 9041u, 9043u, 9049u, 9059u, 9067u, 9091u, 9103u, 9109u, 9127u, 9133u, 9137u, 9151u, 9157u, 9161u, 9173u, 9181u, 9187u, 9199u, 9203u, 9209u, 9221u, 9227u, 9239u, 9241u, 9257u, 9277u, 9281u, 9283u, 9293u, 9311u, 9319u, 9323u, 9337u, 9341u, 9343u, 9349u, 9371u, 9377u, 9391u, 9397u, 9403u, 9413u, 9419u, 9421u, 9431u, 9433u, 9437u, 9439u, 9461u, 9463u, 9467u, 9473u, 9479u, 9491u, 9497u, 9511u, 9521u, 9533u, 9539u, 9547u, 9551u, 9587u, 9601u, 9613u, 9619u, 9623u, 9629u, 9631u, 9643u, 9649u, 9661u, 9677u, 9679u, 9689u, 9697u, 9719u, 9721u, 9733u, 9739u, 9743u, 9749u, 9767u, 9769u, 9781u, 9787u, 9791u, 9803u, 9811u, 9817u, 9829u, 9833u, 9839u, 9851u, 9857u, 9859u, 9871u, 9883u, 9887u, 9901u, 9907u, 9923u, 9929u, 9931u, 9941u, 9949u, 9967u, 9973u, 10007u, 10009u, 10037u, 10039u, 10061u, 10067u, 10069u, 10079u, 10091u, 10093u, 10099u, 10103u, 10111u, 10133u, 10139u, 10141u, 10151u, 10159u, 10163u, 10169u, 10177u, 10181u, 10193u, 10211u, 10223u, 10243u, 10247u, 10253u, 10259u, 10267u, 10271u, 10273u, 10289u, 10301u, 10303u, 10313u, 10321u, 10331u, 10333u, 10337u, 10343u, 10357u, 10369u, 10391u, 10399u, 10427u, 10429u, 10433u, 10453u, 10457u, 10459u, 10463u, 10477u, 10487u, 10499u, 10501u, 10513u, 10529u, 10531u, 10559u, 10567u, 10589u, 10597u, 10601u, 10607u, 10613u, 10627u, 10631u, 10639u, 10651u, 10657u, 10663u, 10667u, 10687u, 10691u, 10709u, 10711u, 10723u, 10729u, 10733u, 10739u, 10753u, 10771u, 10781u, 10789u, 10799u, 10831u, 10837u, 10847u, 10853u, 10859u, 10861u, 10867u, 10883u, 10889u, 10891u, 10903u, 10909u, 10937u, 10939u, 10949u, 10957u, 10973u, 10979u, 10987u, 10993u, 11003u, 11027u, 11047u, 11057u, 11059u, 11069u, 11071u, 11083u, 11087u, 11093u, 11113u, 11117u, 11119u, 11131u, 11149u, 11159u, 11161u, 11171u, 11173u, 11177u, 11197u, 11213u, 11239u, 11243u, 11251u, 11257u, 11261u, 11273u, 11279u, 11287u, 11299u, 11311u, 11317u, 11321u, 11329u, 11351u, 11353u, 11369u, 11383u, 11393u, 11399u, 11411u, 11423u, 11437u, 11443u, 11447u, 11467u, 11471u, 11483u, 11489u, 11491u, 11497u, 11503u, 11519u, 11527u, 11549u, 11551u, 11579u, 11587u, 11593u, 11597u, 11617u, 11621u, 11633u, 11657u, 11677u, 11681u, 11689u, 11699u, 11701u, 11717u, 11719u, 11731u, 11743u, 11777u, 11779u, 11783u, 11789u, 11801u, 11807u, 11813u, 11821u, 11827u, 11831u, 11833u, 11839u, 11863u, 11867u, 11887u, 11897u, 11903u, 11909u, 11923u, 11927u, 11933u, 11939u, 11941u, 11953u, 11959u, 11969u, 11971u, 11981u, 11987u, 12007u, 12011u, 12037u, 12041u, 12043u, 12049u, 12071u, 12073u, 12097u, 12101u, 12107u, 12109u, 12113u, 12119u, 12143u, 12149u, 12157u, 12161u, 12163u, 12197u, 12203u, 12211u, 12227u, 12239u, 12241u, 12251u, 12253u, 12263u, 12269u, 12277u, 12281u, 12289u, 12301u, 12323u, 12329u, 12343u, 12347u, 12373u, 12377u, 12379u, 12391u, 12401u, 12409u, 12413u, 12421u, 12433u, 12437u, 12451u, 12457u, 12473u, 12479u, 12487u, 12491u, 12497u, 12503u, 12511u, 12517u, 12527u, 12539u, 12541u, 12547u, 12553u, 12569u, 12577u, 12583u, 12589u, 12601u, 12611u, 12613u, 12619u, 12637u, 12641u, 12647u, 12653u, 12659u, 12671u, 12689u, 12697u, 12703u, 12713u, 12721u, 12739u, 12743u, 12757u, 12763u, 12781u, 12791u, 12799u, 12809u, 12821u, 12823u, 12829u, 12841u, 12853u, 12889u, 12893u, 12899u, 12907u, 12911u, 12917u, 12919u, 12923u, 12941u, 12953u, 12959u, 12967u, 12973u, 12979u, 12983u, 13001u, 13003u, 13007u, 13009u, 13033u, 13037u, 13043u, 13049u, 13063u, 13093u, 13099u, 13103u, 13109u, 13121u, 13127u, 13147u, 13151u, 13159u, 13163u, 13171u, 13177u, 13183u, 13187u, 13217u, 13219u, 13229u, 13241u, 13249u, 13259u, 13267u, 13291u, 13297u, 13309u, 13313u, 13327u, 13331u, 13337u, 13339u, 13367u, 13381u, 13397u, 13399u, 13411u, 13417u, 13421u, 13441u, 13451u, 13457u, 13463u, 13469u, 13477u, 13487u, 13499u, 13513u, 13523u, 13537u, 13553u, 13567u, 13577u, 13591u, 13597u, 13613u, 13619u, 13627u, 13633u, 13649u, 13669u, 13679u, 13681u, 13687u, 13691u, 13693u, 13697u, 13709u, 13711u, 13721u, 13723u, 13729u, 13751u, 13757u, 13759u, 13763u, 13781u, 13789u, 13799u, 13807u, 13829u, 13831u, 13841u, 13859u, 13873u, 13877u, 13879u, 13883u, 13901u, 13903u, 13907u, 13913u, 13921u, 13931u, 13933u, 13963u, 13967u, 13997u, 13999u, 14009u, 14011u, 14029u, 14033u, 14051u, 14057u, 14071u, 14081u, 14083u, 14087u, 14107u, 14143u, 14149u, 14153u, 14159u, 14173u, 14177u, 14197u, 14207u, 14221u, 14243u, 14249u, 14251u, 14281u, 14293u, 14303u, 14321u, 14323u, 14327u, 14341u, 14347u, 14369u, 14387u, 14389u, 14401u, 14407u, 14411u, 14419u, 14423u, 14431u, 14437u, 14447u, 14449u, 14461u, 14479u, 14489u, 14503u, 14519u, 14533u, 14537u, 14543u, 14549u, 14551u, 14557u, 14561u, 14563u, 14591u, 14593u, 14621u, 14627u, 14629u, 14633u, 14639u, 14653u, 14657u, 14669u, 14683u, 14699u, 14713u, 14717u, 14723u, 14731u, 14737u, 14741u, 14747u, 14753u, 14759u, 14767u, 14771u, 14779u, 14783u, 14797u, 14813u, 14821u, 14827u, 14831u, 14843u, 14851u, 14867u, 14869u, 14879u, 14887u, 14891u, 14897u, 14923u, 14929u, 14939u, 14947u, 14951u, 14957u, 14969u, 14983u, 15013u, 15017u, 15031u, 15053u, 15061u, 15073u, 15077u, 15083u, 15091u, 15101u, 15107u, 15121u, 15131u, 15137u, 15139u, 15149u, 15161u, 15173u, 15187u, 15193u, 15199u, 15217u, 15227u, 15233u, 15241u, 15259u, 15263u, 15269u, 15271u, 15277u, 15287u, 15289u, 15299u, 15307u, 15313u, 15319u, 15329u, 15331u, 15349u, 15359u, 15361u, 15373u, 15377u, 15383u, 15391u, 15401u, 15413u, 15427u, 15439u, 15443u, 15451u, 15461u, 15467u, 15473u, 15493u, 15497u, 15511u, 15527u, 15541u, 15551u, 15559u, 15569u, 15581u, 15583u, 15601u, 15607u, 15619u, 15629u, 15641u, 15643u, 15647u, 15649u, 15661u, 15667u, 15671u, 15679u, 15683u, 15727u, 15731u, 15733u, 15737u, 15739u, 15749u, 15761u, 15767u, 15773u, 15787u, 15791u, 15797u, 15803u, 15809u, 15817u, 15823u, 15859u, 15877u, 15881u, 15887u, 15889u, 15901u, 15907u, 15913u, 15919u, 15923u, 15937u, 15959u, 15971u, 15973u, 15991u, 16001u, 16007u, 16033u, 16057u, 16061u, 16063u, 16067u, 16069u, 16073u, 16087u, 16091u, 16097u, 16103u, 16111u, 16127u, 16139u, 16141u, 16183u, 16187u, 16189u, 16193u, 16217u, 16223u, 16229u, 16231u, 16249u, 16253u, 16267u, 16273u, 16301u, 16319u, 16333u, 16339u, 16349u, 16361u, 16363u, 16369u, 16381u, 16411u, 16417u, 16421u, 16427u, 16433u, 16447u, 16451u, 16453u, 16477u, 16481u, 16487u, 16493u, 16519u, 16529u, 16547u, 16553u, 16561u, 16567u, 16573u, 16603u, 16607u, 16619u, 16631u, 16633u, 16649u, 16651u, 16657u, 16661u, 16673u, 16691u, 16693u, 16699u, 16703u, 16729u, 16741u, 16747u, 16759u, 16763u, 16787u, 16811u, 16823u, 16829u, 16831u, 16843u, 16871u, 16879u, 16883u, 16889u, 16901u, 16903u, 16921u, 16927u, 16931u, 16937u, 16943u, 16963u, 16979u, 16981u, 16987u, 16993u, 17011u, 17021u, 17027u, 17029u, 17033u, 17041u, 17047u, 17053u, 17077u, 17093u, 17099u, 17107u, 17117u, 17123u, 17137u, 17159u, 17167u, 17183u, 17189u, 17191u, 17203u, 17207u, 17209u, 17231u, 17239u, 17257u, 17291u, 17293u, 17299u, 17317u, 17321u, 17327u, 17333u, 17341u, 17351u, 17359u, 17377u, 17383u, 17387u, 17389u, 17393u, 17401u, 17417u, 17419u, 17431u, 17443u, 17449u, 17467u, 17471u, 17477u, 17483u, 17489u, 17491u, 17497u, 17509u, 17519u, 17539u, 17551u, 17569u, 17573u, 17579u, 17581u, 17597u, 17599u, 17609u, 17623u, 17627u, 17657u, 17659u, 17669u, 17681u, 17683u, 17707u, 17713u, 17729u, 17737u, 17747u, 17749u, 17761u, 17783u, 17789u, 17791u, 17807u, 17827u, 17837u, 17839u, 17851u, 17863u, 17881u, 17891u, 17903u, 17909u, 17911u, 17921u, 17923u, 17929u, 17939u, 17957u, 17959u, 17971u, 17977u, 17981u, 17987u, 17989u, 18013u, 18041u, 18043u, 18047u, 18049u, 18059u, 18061u, 18077u, 18089u, 18097u, 18119u, 18121u, 18127u, 18131u, 18133u, 18143u, 18149u, 18169u, 18181u, 18191u, 18199u, 18211u, 18217u, 18223u, 18229u, 18233u, 18251u, 18253u, 18257u, 18269u, 18287u, 18289u, 18301u, 18307u, 18311u, 18313u, 18329u, 18341u, 18353u, 18367u, 18371u, 18379u, 18397u, 18401u, 18413u, 18427u, 18433u, 18439u, 18443u, 18451u, 18457u, 18461u, 18481u, 18493u, 18503u, 18517u, 18521u, 18523u, 18539u, 18541u, 18553u, 18583u, 18587u, 18593u, 18617u, 18637u, 18661u, 18671u, 18679u, 18691u, 18701u, 18713u, 18719u, 18731u, 18743u, 18749u, 18757u, 18773u, 18787u, 18793u, 18797u, 18803u, 18839u, 18859u, 18869u, 18899u, 18911u, 18913u, 18917u, 18919u, 18947u, 18959u, 18973u, 18979u, 19001u, 19009u, 19013u, 19031u, 19037u, 19051u, 19069u, 19073u, 19079u, 19081u, 19087u, 19121u, 19139u, 19141u, 19157u, 19163u, 19181u, 19183u, 19207u, 19211u, 19213u, 19219u, 19231u, 19237u, 19249u, 19259u, 19267u, 19273u, 19289u, 19301u, 19309u, 19319u, 19333u, 19373u, 19379u, 19381u, 19387u, 19391u, 19403u, 19417u, 19421u, 19423u, 19427u, 19429u, 19433u, 19441u, 19447u, 19457u, 19463u, 19469u, 19471u, 19477u, 19483u, 19489u, 19501u, 19507u, 19531u, 19541u, 19543u, 19553u, 19559u, 19571u, 19577u, 19583u, 19597u, 19603u, 19609u, 19661u, 19681u, 19687u, 19697u, 19699u, 19709u, 19717u, 19727u, 19739u, 19751u, 19753u, 19759u, 19763u, 19777u, 19793u, 19801u, 19813u, 19819u, 19841u, 19843u, 19853u, 19861u, 19867u, 19889u, 19891u, 19913u, 19919u, 19927u, 19937u, 19949u, 19961u, 19963u, 19973u, 19979u, 19991u, 19993u, 19997u, 20011u, 20021u, 20023u, 20029u, 20047u, 20051u, 20063u, 20071u, 20089u, 20101u, 20107u, 20113u, 20117u, 20123u, 20129u, 20143u, 20147u, 20149u, 20161u, 20173u, 20177u, 20183u, 20201u, 20219u, 20231u, 20233u, 20249u, 20261u, 20269u, 20287u, 20297u, 20323u, 20327u, 20333u, 20341u, 20347u, 20353u, 20357u, 20359u, 20369u, 20389u, 20393u, 20399u, 20407u, 20411u, 20431u, 20441u, 20443u, 20477u, 20479u, 20483u, 20507u, 20509u, 20521u, 20533u, 20543u, 20549u, 20551u, 20563u, 20593u, 20599u, 20611u, 20627u, 20639u, 20641u, 20663u, 20681u, 20693u, 20707u, 20717u, 20719u, 20731u, 20743u, 20747u, 20749u, 20753u, 20759u, 20771u, 20773u, 20789u, 20807u, 20809u, 20849u, 20857u, 20873u, 20879u, 20887u, 20897u, 20899u, 20903u, 20921u, 20929u, 20939u, 20947u, 20959u, 20963u, 20981u, 20983u, 21001u, 21011u, 21013u, 21017u, 21019u, 21023u, 21031u, 21059u, 21061u, 21067u, 21089u, 21101u, 21107u, 21121u, 21139u, 21143u, 21149u, 21157u, 21163u, 21169u, 21179u, 21187u, 21191u, 21193u, 21211u, 21221u, 21227u, 21247u, 21269u, 21277u, 21283u, 21313u, 21317u, 21319u, 21323u, 21341u, 21347u, 21377u, 21379u, 21383u, 21391u, 21397u, 21401u, 21407u, 21419u, 21433u, 21467u, 21481u, 21487u, 21491u, 21493u, 21499u, 21503u, 21517u, 21521u, 21523u, 21529u, 21557u, 21559u, 21563u, 21569u, 21577u, 21587u, 21589u, 21599u, 21601u, 21611u, 21613u, 21617u, 21647u, 21649u, 21661u, 21673u, 21683u, 21701u, 21713u, 21727u, 21737u, 21739u, 21751u, 21757u, 21767u, 21773u, 21787u, 21799u, 21803u, 21817u, 21821u, 21839u, 21841u, 21851u, 21859u, 21863u, 21871u, 21881u, 21893u, 21911u, 21929u, 21937u, 21943u, 21961u, 21977u, 21991u, 21997u, 22003u, 22013u, 22027u, 22031u, 22037u, 22039u, 22051u, 22063u, 22067u, 22073u, 22079u, 22091u, 22093u, 22109u, 22111u, 22123u, 22129u, 22133u, 22147u, 22153u, 22157u, 22159u, 22171u, 22189u, 22193u, 22229u, 22247u, 22259u, 22271u, 22273u, 22277u, 22279u, 22283u, 22291u, 22303u, 22307u, 22343u, 22349u, 22367u, 22369u, 22381u, 22391u, 22397u, 22409u, 22433u, 22441u, 22447u, 22453u, 22469u, 22481u, 22483u, 22501u, 22511u, 22531u, 22541u, 22543u, 22549u, 22567u, 22571u, 22573u, 22613u, 22619u, 22621u, 22637u, 22639u, 22643u, 22651u, 22669u, 22679u, 22691u, 22697u, 22699u, 22709u, 22717u, 22721u, 22727u, 22739u, 22741u, 22751u, 22769u, 22777u, 22783u, 22787u, 22807u, 22811u, 22817u, 22853u, 22859u, 22861u, 22871u, 22877u, 22901u, 22907u, 22921u, 22937u, 22943u, 22961u, 22963u, 22973u, 22993u, 23003u, 23011u, 23017u, 23021u, 23027u, 23029u, 23039u, 23041u, 23053u, 23057u, 23059u, 23063u, 23071u, 23081u, 23087u, 23099u, 23117u, 23131u, 23143u, 23159u, 23167u, 23173u, 23189u, 23197u, 23201u, 23203u, 23209u, 23227u, 23251u, 23269u, 23279u, 23291u, 23293u, 23297u, 23311u, 23321u, 23327u, 23333u, 23339u, 23357u, 23369u, 23371u, 23399u, 23417u, 23431u, 23447u, 23459u, 23473u, 23497u, 23509u, 23531u, 23537u, 23539u, 23549u, 23557u, 23561u, 23563u, 23567u, 23581u, 23593u, 23599u, 23603u, 23609u, 23623u, 23627u, 23629u, 23633u, 23663u, 23669u, 23671u, 23677u, 23687u, 23689u, 23719u, 23741u, 23743u, 23747u, 23753u, 23761u, 23767u, 23773u, 23789u, 23801u, 23813u, 23819u, 23827u, 23831u, 23833u, 23857u, 23869u, 23873u, 23879u, 23887u, 23893u, 23899u, 23909u, 23911u, 23917u, 23929u, 23957u, 23971u, 23977u, 23981u, 23993u, 24001u, 24007u, 24019u, 24023u, 24029u, 24043u, 24049u, 24061u, 24071u, 24077u, 24083u, 24091u, 24097u, 24103u, 24107u, 24109u, 24113u, 24121u, 24133u, 24137u, 24151u, 24169u, 24179u, 24181u, 24197u, 24203u, 24223u, 24229u, 24239u, 24247u, 24251u, 24281u, 24317u, 24329u, 24337u, 24359u, 24371u, 24373u, 24379u, 24391u, 24407u, 24413u, 24419u, 24421u, 24439u, 24443u, 24469u, 24473u, 24481u, 24499u, 24509u, 24517u, 24527u, 24533u, 24547u, 24551u, 24571u, 24593u, 24611u, 24623u, 24631u, 24659u, 24671u, 24677u, 24683u, 24691u, 24697u, 24709u, 24733u, 24749u, 24763u, 24767u, 24781u, 24793u, 24799u, 24809u, 24821u, 24841u, 24847u, 24851u, 24859u, 24877u, 24889u, 24907u, 24917u, 24919u, 24923u, 24943u, 24953u, 24967u, 24971u, 24977u, 24979u, 24989u, 25013u, 25031u, 25033u, 25037u, 25057u, 25073u, 25087u, 25097u, 25111u, 25117u, 25121u, 25127u, 25147u, 25153u, 25163u, 25169u, 25171u, 25183u, 25189u, 25219u, 25229u, 25237u, 25243u, 25247u, 25253u, 25261u, 25301u, 25303u, 25307u, 25309u, 25321u, 25339u, 25343u, 25349u, 25357u, 25367u, 25373u, 25391u, 25409u, 25411u, 25423u, 25439u, 25447u, 25453u, 25457u, 25463u, 25469u, 25471u, 25523u, 25537u, 25541u, 25561u, 25577u, 25579u, 25583u, 25589u, 25601u, 25603u, 25609u, 25621u, 25633u, 25639u, 25643u, 25657u, 25667u, 25673u, 25679u, 25693u, 25703u, 25717u, 25733u, 25741u, 25747u, 25759u, 25763u, 25771u, 25793u, 25799u, 25801u, 25819u, 25841u, 25847u, 25849u, 25867u, 25873u, 25889u, 25903u, 25913u, 25919u, 25931u, 25933u, 25939u, 25943u, 25951u, 25969u, 25981u, 25997u, 25999u, 26003u, 26017u, 26021u, 26029u, 26041u, 26053u, 26083u, 26099u, 26107u, 26111u, 26113u, 26119u, 26141u, 26153u, 26161u, 26171u, 26177u, 26183u, 26189u, 26203u, 26209u, 26227u, 26237u, 26249u, 26251u, 26261u, 26263u, 26267u, 26293u, 26297u, 26309u, 26317u, 26321u, 26339u, 26347u, 26357u, 26371u, 26387u, 26393u, 26399u, 26407u, 26417u, 26423u, 26431u, 26437u, 26449u, 26459u, 26479u, 26489u, 26497u, 26501u, 26513u, 26539u, 26557u, 26561u, 26573u, 26591u, 26597u, 26627u, 26633u, 26641u, 26647u, 26669u, 26681u, 26683u, 26687u, 26693u, 26699u, 26701u, 26711u, 26713u, 26717u, 26723u, 26729u, 26731u, 26737u, 26759u, 26777u, 26783u, 26801u, 26813u, 26821u, 26833u, 26839u, 26849u, 26861u, 26863u, 26879u, 26881u, 26891u, 26893u, 26903u, 26921u, 26927u, 26947u, 26951u, 26953u, 26959u, 26981u, 26987u, 26993u, 27011u, 27017u, 27031u, 27043u, 27059u, 27061u, 27067u, 27073u, 27077u, 27091u, 27103u, 27107u, 27109u, 27127u, 27143u, 27179u, 27191u, 27197u, 27211u, 27239u, 27241u, 27253u, 27259u, 27271u, 27277u, 27281u, 27283u, 27299u, 27329u, 27337u, 27361u, 27367u, 27397u, 27407u, 27409u, 27427u, 27431u, 27437u, 27449u, 27457u, 27479u, 27481u, 27487u, 27509u, 27527u, 27529u, 27539u, 27541u, 27551u, 27581u, 27583u, 27611u, 27617u, 27631u, 27647u, 27653u, 27673u, 27689u, 27691u, 27697u, 27701u, 27733u, 27737u, 27739u, 27743u, 27749u, 27751u, 27763u, 27767u, 27773u, 27779u, 27791u, 27793u, 27799u, 27803u, 27809u, 27817u, 27823u, 27827u, 27847u, 27851u, 27883u, 27893u, 27901u, 27917u, 27919u, 27941u, 27943u, 27947u, 27953u, 27961u, 27967u, 27983u, 27997u, 28001u, 28019u, 28027u, 28031u, 28051u, 28057u, 28069u, 28081u, 28087u, 28097u, 28099u, 28109u, 28111u, 28123u, 28151u, 28163u, 28181u, 28183u, 28201u, 28211u, 28219u, 28229u, 28277u, 28279u, 28283u, 28289u, 28297u, 28307u, 28309u, 28319u, 28349u, 28351u, 28387u, 28393u, 28403u, 28409u, 28411u, 28429u, 28433u, 28439u, 28447u, 28463u, 28477u, 28493u, 28499u, 28513u, 28517u, 28537u, 28541u, 28547u, 28549u, 28559u, 28571u, 28573u, 28579u, 28591u, 28597u, 28603u, 28607u, 28619u, 28621u, 28627u, 28631u, 28643u, 28649u, 28657u, 28661u, 28663u, 28669u, 28687u, 28697u, 28703u, 28711u, 28723u, 28729u, 28751u, 28753u, 28759u, 28771u, 28789u, 28793u, 28807u, 28813u, 28817u, 28837u, 28843u, 28859u, 28867u, 28871u, 28879u, 28901u, 28909u, 28921u, 28927u, 28933u, 28949u, 28961u, 28979u, 29009u, 29017u, 29021u, 29023u, 29027u, 29033u, 29059u, 29063u, 29077u, 29101u, 29123u, 29129u, 29131u, 29137u, 29147u, 29153u, 29167u, 29173u, 29179u, 29191u, 29201u, 29207u, 29209u, 29221u, 29231u, 29243u, 29251u, 29269u, 29287u, 29297u, 29303u, 29311u, 29327u, 29333u, 29339u, 29347u, 29363u, 29383u, 29387u, 29389u, 29399u, 29401u, 29411u, 29423u, 29429u, 29437u, 29443u, 29453u, 29473u, 29483u, 29501u, 29527u, 29531u, 29537u, 29567u, 29569u, 29573u, 29581u, 29587u, 29599u, 29611u, 29629u, 29633u, 29641u, 29663u, 29669u, 29671u, 29683u, 29717u, 29723u, 29741u, 29753u, 29759u, 29761u, 29789u, 29803u, 29819u, 29833u, 29837u, 29851u, 29863u, 29867u, 29873u, 29879u, 29881u, 29917u, 29921u, 29927u, 29947u, 29959u, 29983u, 29989u, 30011u, 30013u, 30029u, 30047u, 30059u, 30071u, 30089u, 30091u, 30097u, 30103u, 30109u, 30113u, 30119u, 30133u, 30137u, 30139u, 30161u, 30169u, 30181u, 30187u, 30197u, 30203u, 30211u, 30223u, 30241u, 30253u, 30259u, 30269u, 30271u, 30293u, 30307u, 30313u, 30319u, 30323u, 30341u, 30347u, 30367u, 30389u, 30391u, 30403u, 30427u, 30431u, 30449u, 30467u, 30469u, 30491u, 30493u, 30497u, 30509u, 30517u, 30529u, 30539u, 30553u, 30557u, 30559u, 30577u, 30593u, 30631u, 30637u, 30643u, 30649u, 30661u, 30671u, 30677u, 30689u, 30697u, 30703u, 30707u, 30713u, 30727u, 30757u, 30763u, 30773u, 30781u, 30803u, 30809u, 30817u, 30829u, 30839u, 30841u, 30851u, 30853u, 30859u, 30869u, 30871u, 30881u, 30893u, 30911u, 30931u, 30937u, 30941u, 30949u, 30971u, 30977u, 30983u, 31013u, 31019u, 31033u, 31039u, 31051u, 31063u, 31069u, 31079u, 31081u, 31091u, 31121u, 31123u, 31139u, 31147u, 31151u, 31153u, 31159u, 31177u, 31181u, 31183u, 31189u, 31193u, 31219u, 31223u, 31231u, 31237u, 31247u, 31249u, 31253u, 31259u, 31267u, 31271u, 31277u, 31307u, 31319u, 31321u, 31327u, 31333u, 31337u, 31357u, 31379u, 31387u, 31391u, 31393u, 31397u, 31469u, 31477u, 31481u, 31489u, 31511u, 31513u, 31517u, 31531u, 31541u, 31543u, 31547u, 31567u, 31573u, 31583u, 31601u, 31607u, 31627u, 31643u, 31649u, 31657u, 31663u, 31667u, 31687u, 31699u, 31721u, 31723u, 31727u, 31729u, 31741u, 31751u, 31769u, 31771u, 31793u, 31799u, 31817u, 31847u, 31849u, 31859u, 31873u, 31883u, 31891u, 31907u, 31957u, 31963u, 31973u, 31981u, 31991u, 32003u, 32009u, 32027u, 32029u, 32051u, 32057u, 32059u, 32063u, 32069u, 32077u, 32083u, 32089u, 32099u, 32117u, 32119u, 32141u, 32143u, 32159u, 32173u, 32183u, 32189u, 32191u, 32203u, 32213u, 32233u, 32237u, 32251u, 32257u, 32261u, 32297u, 32299u, 32303u, 32309u, 32321u, 32323u, 32327u, 32341u, 32353u, 32359u, 32363u, 32369u, 32371u, 32377u, 32381u, 32401u, 32411u, 32413u, 32423u, 32429u, 32441u, 32443u, 32467u, 32479u, 32491u, 32497u, 32503u, 32507u, 32531u, 32533u, 32537u, 32561u, 32563u, 32569u, 32573u, 32579u, 32587u, 32603u, 32609u, 32611u, 32621u, 32633u, 32647u, 32653u, 32687u, 32693u, 32707u, 32713u, 32717u, 32719u, 32749u, 32771u, 32779u, 32783u, 32789u, 32797u, 32801u, 32803u, 32831u, 32833u, 32839u, 32843u, 32869u, 32887u, 32909u, 32911u, 32917u, 32933u, 32939u, 32941u, 32957u, 32969u, 32971u, 32983u, 32987u, 32993u, 32999u, 33013u, 33023u, 33029u, 33037u, 33049u, 33053u, 33071u, 33073u, 33083u, 33091u, 33107u, 33113u, 33119u, 33149u, 33151u, 33161u, 33179u, 33181u, 33191u, 33199u, 33203u, 33211u, 33223u, 33247u, 33287u, 33289u, 33301u, 33311u, 33317u, 33329u, 33331u, 33343u, 33347u, 33349u, 33353u, 33359u, 33377u, 33391u, 33403u, 33409u, 33413u, 33427u, 33457u, 33461u, 33469u, 33479u, 33487u, 33493u, 33503u, 33521u, 33529u, 33533u, 33547u, 33563u, 33569u, 33577u, 33581u, 33587u, 33589u, 33599u, 33601u, 33613u, 33617u, 33619u, 33623u, 33629u, 33637u, 33641u, 33647u, 33679u, 33703u, 33713u, 33721u, 33739u, 33749u, 33751u, 33757u, 33767u, 33769u, 33773u, 33791u, 33797u, 33809u, 33811u, 33827u, 33829u, 33851u, 33857u, 33863u, 33871u, 33889u, 33893u, 33911u, 33923u, 33931u, 33937u, 33941u, 33961u, 33967u, 33997u, 34019u, 34031u, 34033u, 34039u, 34057u, 34061u, 34123u, 34127u, 34129u, 34141u, 34147u, 34157u, 34159u, 34171u, 34183u, 34211u, 34213u, 34217u, 34231u, 34253u, 34259u, 34261u, 34267u, 34273u, 34283u, 34297u, 34301u, 34303u, 34313u, 34319u, 34327u, 34337u, 34351u, 34361u, 34367u, 34369u, 34381u, 34403u, 34421u, 34429u, 34439u, 34457u, 34469u, 34471u, 34483u, 34487u, 34499u, 34501u, 34511u, 34513u, 34519u, 34537u, 34543u, 34549u, 34583u, 34589u, 34591u, 34603u, 34607u, 34613u, 34631u, 34649u, 34651u, 34667u, 34673u, 34679u, 34687u, 34693u, 34703u, 34721u, 34729u, 34739u, 34747u, 34757u, 34759u, 34763u, 34781u, 34807u, 34819u, 34841u, 34843u, 34847u, 34849u, 34871u, 34877u, 34883u, 34897u, 34913u, 34919u, 34939u, 34949u, 34961u, 34963u, 34981u, 35023u, 35027u, 35051u, 35053u, 35059u, 35069u, 35081u, 35083u, 35089u, 35099u, 35107u, 35111u, 35117u, 35129u, 35141u, 35149u, 35153u, 35159u, 35171u, 35201u, 35221u, 35227u, 35251u, 35257u, 35267u, 35279u, 35281u, 35291u, 35311u, 35317u, 35323u, 35327u, 35339u, 35353u, 35363u, 35381u, 35393u, 35401u, 35407u, 35419u, 35423u, 35437u, 35447u, 35449u, 35461u, 35491u, 35507u, 35509u, 35521u, 35527u, 35531u, 35533u, 35537u, 35543u, 35569u, 35573u, 35591u, 35593u, 35597u, 35603u, 35617u, 35671u, 35677u, 35729u, 35731u, 35747u, 35753u, 35759u, 35771u, 35797u, 35801u, 35803u, 35809u, 35831u, 35837u, 35839u, 35851u, 35863u, 35869u, 35879u, 35897u, 35899u, 35911u, 35923u, 35933u, 35951u, 35963u, 35969u, 35977u, 35983u, 35993u, 35999u, 36007u, 36011u, 36013u, 36017u, 36037u, 36061u, 36067u, 36073u, 36083u, 36097u, 36107u, 36109u, 36131u, 36137u, 36151u, 36161u, 36187u, 36191u, 36209u, 36217u, 36229u, 36241u, 36251u, 36263u, 36269u, 36277u, 36293u, 36299u, 36307u, 36313u, 36319u, 36341u, 36343u, 36353u, 36373u, 36383u, 36389u, 36433u, 36451u, 36457u, 36467u, 36469u, 36473u, 36479u, 36493u, 36497u, 36523u, 36527u, 36529u, 36541u, 36551u, 36559u, 36563u, 36571u, 36583u, 36587u, 36599u, 36607u, 36629u, 36637u, 36643u, 36653u, 36671u, 36677u, 36683u, 36691u, 36697u, 36709u, 36713u, 36721u, 36739u, 36749u, 36761u, 36767u, 36779u, 36781u, 36787u, 36791u, 36793u, 36809u, 36821u, 36833u, 36847u, 36857u, 36871u, 36877u, 36887u, 36899u, 36901u, 36913u, 36919u, 36923u, 36929u, 36931u, 36943u, 36947u, 36973u, 36979u, 36997u, 37003u, 37013u, 37019u, 37021u, 37039u, 37049u, 37057u, 37061u, 37087u, 37097u, 37117u, 37123u, 37139u, 37159u, 37171u, 37181u, 37189u, 37199u, 37201u, 37217u, 37223u, 37243u, 37253u, 37273u, 37277u, 37307u, 37309u, 37313u, 37321u, 37337u, 37339u, 37357u, 37361u, 37363u, 37369u, 37379u, 37397u, 37409u, 37423u, 37441u, 37447u, 37463u, 37483u, 37489u, 37493u, 37501u, 37507u, 37511u, 37517u, 37529u, 37537u, 37547u, 37549u, 37561u, 37567u, 37571u, 37573u, 37579u, 37589u, 37591u, 37607u, 37619u, 37633u, 37643u, 37649u, 37657u, 37663u, 37691u, 37693u, 37699u, 37717u, 37747u, 37781u, 37783u, 37799u, 37811u, 37813u, 37831u, 37847u, 37853u, 37861u, 37871u, 37879u, 37889u, 37897u, 37907u, 37951u, 37957u, 37963u, 37967u, 37987u, 37991u, 37993u, 37997u, 38011u, 38039u, 38047u, 38053u, 38069u, 38083u, 38113u, 38119u, 38149u, 38153u, 38167u, 38177u, 38183u, 38189u, 38197u, 38201u, 38219u, 38231u, 38237u, 38239u, 38261u, 38273u, 38281u, 38287u, 38299u, 38303u, 38317u, 38321u, 38327u, 38329u, 38333u, 38351u, 38371u, 38377u, 38393u, 38431u, 38447u, 38449u, 38453u, 38459u, 38461u, 38501u, 38543u, 38557u, 38561u, 38567u, 38569u, 38593u, 38603u, 38609u, 38611u, 38629u, 38639u, 38651u, 38653u, 38669u, 38671u, 38677u, 38693u, 38699u, 38707u, 38711u, 38713u, 38723u, 38729u, 38737u, 38747u, 38749u, 38767u, 38783u, 38791u, 38803u, 38821u, 38833u, 38839u, 38851u, 38861u, 38867u, 38873u, 38891u, 38903u, 38917u, 38921u, 38923u, 38933u, 38953u, 38959u, 38971u, 38977u, 38993u, 39019u, 39023u, 39041u, 39043u, 39047u, 39079u, 39089u, 39097u, 39103u, 39107u, 39113u, 39119u, 39133u, 39139u, 39157u, 39161u, 39163u, 39181u, 39191u, 39199u, 39209u, 39217u, 39227u, 39229u, 39233u, 39239u, 39241u, 39251u, 39293u, 39301u, 39313u, 39317u, 39323u, 39341u, 39343u, 39359u, 39367u, 39371u, 39373u, 39383u, 39397u, 39409u, 39419u, 39439u, 39443u, 39451u, 39461u, 39499u, 39503u, 39509u, 39511u, 39521u, 39541u, 39551u, 39563u, 39569u, 39581u, 39607u, 39619u, 39623u, 39631u, 39659u, 39667u, 39671u, 39679u, 39703u, 39709u, 39719u, 39727u, 39733u, 39749u, 39761u, 39769u, 39779u, 39791u, 39799u, 39821u, 39827u, 39829u, 39839u, 39841u, 39847u, 39857u, 39863u, 39869u, 39877u, 39883u, 39887u, 39901u, 39929u, 39937u, 39953u, 39971u, 39979u, 39983u, 39989u, 40009u, 40013u, 40031u, 40037u, 40039u, 40063u, 40087u, 40093u, 40099u, 40111u, 40123u, 40127u, 40129u, 40151u, 40153u, 40163u, 40169u, 40177u, 40189u, 40193u, 40213u, 40231u, 40237u, 40241u, 40253u, 40277u, 40283u, 40289u, 40343u, 40351u, 40357u, 40361u, 40387u, 40423u, 40427u, 40429u, 40433u, 40459u, 40471u, 40483u, 40487u, 40493u, 40499u, 40507u, 40519u, 40529u, 40531u, 40543u, 40559u, 40577u, 40583u, 40591u, 40597u, 40609u, 40627u, 40637u, 40639u, 40693u, 40697u, 40699u, 40709u, 40739u, 40751u, 40759u, 40763u, 40771u, 40787u, 40801u, 40813u, 40819u, 40823u, 40829u, 40841u, 40847u, 40849u, 40853u, 40867u, 40879u, 40883u, 40897u, 40903u, 40927u, 40933u, 40939u, 40949u, 40961u, 40973u, 40993u, 41011u, 41017u, 41023u, 41039u, 41047u, 41051u, 41057u, 41077u, 41081u, 41113u, 41117u, 41131u, 41141u, 41143u, 41149u, 41161u, 41177u, 41179u, 41183u, 41189u, 41201u, 41203u, 41213u, 41221u, 41227u, 41231u, 41233u, 41243u, 41257u, 41263u, 41269u, 41281u, 41299u, 41333u, 41341u, 41351u, 41357u, 41381u, 41387u, 41389u, 41399u, 41411u, 41413u, 41443u, 41453u, 41467u, 41479u, 41491u, 41507u, 41513u, 41519u, 41521u, 41539u, 41543u, 41549u, 41579u, 41593u, 41597u, 41603u, 41609u, 41611u, 41617u, 41621u, 41627u, 41641u, 41647u, 41651u, 41659u, 41669u, 41681u, 41687u, 41719u, 41729u, 41737u, 41759u, 41761u, 41771u, 41777u, 41801u, 41809u, 41813u, 41843u, 41849u, 41851u, 41863u, 41879u, 41887u, 41893u, 41897u, 41903u, 41911u, 41927u, 41941u, 41947u, 41953u, 41957u, 41959u, 41969u, 41981u, 41983u, 41999u, 42013u, 42017u, 42019u, 42023u, 42043u, 42061u, 42071u, 42073u, 42083u, 42089u, 42101u, 42131u, 42139u, 42157u, 42169u, 42179u, 42181u, 42187u, 42193u, 42197u, 42209u, 42221u, 42223u, 42227u, 42239u, 42257u, 42281u, 42283u, 42293u, 42299u, 42307u, 42323u, 42331u, 42337u, 42349u, 42359u, 42373u, 42379u, 42391u, 42397u, 42403u, 42407u, 42409u, 42433u, 42437u, 42443u, 42451u, 42457u, 42461u, 42463u, 42467u, 42473u, 42487u, 42491u, 42499u, 42509u, 42533u, 42557u, 42569u, 42571u, 42577u, 42589u, 42611u, 42641u, 42643u, 42649u, 42667u, 42677u, 42683u, 42689u, 42697u, 42701u, 42703u, 42709u, 42719u, 42727u, 42737u, 42743u, 42751u, 42767u, 42773u, 42787u, 42793u, 42797u, 42821u, 42829u, 42839u, 42841u, 42853u, 42859u, 42863u, 42899u, 42901u, 42923u, 42929u, 42937u, 42943u, 42953u, 42961u, 42967u, 42979u, 42989u, 43003u, 43013u, 43019u, 43037u, 43049u, 43051u, 43063u, 43067u, 43093u, 43103u, 43117u, 43133u, 43151u, 43159u, 43177u, 43189u, 43201u, 43207u, 43223u, 43237u, 43261u, 43271u, 43283u, 43291u, 43313u, 43319u, 43321u, 43331u, 43391u, 43397u, 43399u, 43403u, 43411u, 43427u, 43441u, 43451u, 43457u, 43481u, 43487u, 43499u, 43517u, 43541u, 43543u, 43573u, 43577u, 43579u, 43591u, 43597u, 43607u, 43609u, 43613u, 43627u, 43633u, 43649u, 43651u, 43661u, 43669u, 43691u, 43711u, 43717u, 43721u, 43753u, 43759u, 43777u, 43781u, 43783u, 43787u, 43789u, 43793u, 43801u, 43853u, 43867u, 43889u, 43891u, 43913u, 43933u, 43943u, 43951u, 43961u, 43963u, 43969u, 43973u, 43987u, 43991u, 43997u, 44017u, 44021u, 44027u, 44029u, 44041u, 44053u, 44059u, 44071u, 44087u, 44089u, 44101u, 44111u, 44119u, 44123u, 44129u, 44131u, 44159u, 44171u, 44179u, 44189u, 44201u, 44203u, 44207u, 44221u, 44249u, 44257u, 44263u, 44267u, 44269u, 44273u, 44279u, 44281u, 44293u, 44351u, 44357u, 44371u, 44381u, 44383u, 44389u, 44417u, 44449u, 44453u, 44483u, 44491u, 44497u, 44501u, 44507u, 44519u, 44531u, 44533u, 44537u, 44543u, 44549u, 44563u, 44579u, 44587u, 44617u, 44621u, 44623u, 44633u, 44641u, 44647u, 44651u, 44657u, 44683u, 44687u, 44699u, 44701u, 44711u, 44729u, 44741u, 44753u, 44771u, 44773u, 44777u, 44789u, 44797u, 44809u, 44819u, 44839u, 44843u, 44851u, 44867u, 44879u, 44887u, 44893u, 44909u, 44917u, 44927u, 44939u, 44953u, 44959u, 44963u, 44971u, 44983u, 44987u, 45007u, 45013u, 45053u, 45061u, 45077u, 45083u, 45119u, 45121u, 45127u, 45131u, 45137u, 45139u, 45161u, 45179u, 45181u, 45191u, 45197u, 45233u, 45247u, 45259u, 45263u, 45281u, 45289u, 45293u, 45307u, 45317u, 45319u, 45329u, 45337u, 45341u, 45343u, 45361u, 45377u, 45389u, 45403u, 45413u, 45427u, 45433u, 45439u, 45481u, 45491u, 45497u, 45503u, 45523u, 45533u, 45541u, 45553u, 45557u, 45569u, 45587u, 45589u, 45599u, 45613u, 45631u, 45641u, 45659u, 45667u, 45673u, 45677u, 45691u, 45697u, 45707u, 45737u, 45751u, 45757u, 45763u, 45767u, 45779u, 45817u, 45821u, 45823u, 45827u, 45833u, 45841u, 45853u, 45863u, 45869u, 45887u, 45893u, 45943u, 45949u, 45953u, 45959u, 45971u, 45979u, 45989u, 46021u, 46027u, 46049u, 46051u, 46061u, 46073u, 46091u, 46093u, 46099u, 46103u, 46133u, 46141u, 46147u, 46153u, 46171u, 46181u, 46183u, 46187u, 46199u, 46219u, 46229u, 46237u, 46261u, 46271u, 46273u, 46279u, 46301u, 46307u, 46309u, 46327u, 46337u, 46349u, 46351u, 46381u, 46399u, 46411u, 46439u, 46441u, 46447u, 46451u, 46457u, 46471u, 46477u, 46489u, 46499u, 46507u, 46511u, 46523u, 46549u, 46559u, 46567u, 46573u, 46589u, 46591u, 46601u, 46619u, 46633u, 46639u, 46643u, 46649u, 46663u, 46679u, 46681u, 46687u, 46691u, 46703u, 46723u, 46727u, 46747u, 46751u, 46757u, 46769u, 46771u, 46807u, 46811u, 46817u, 46819u, 46829u, 46831u, 46853u, 46861u, 46867u, 46877u, 46889u, 46901u, 46919u, 46933u, 46957u, 46993u, 46997u, 47017u, 47041u, 47051u, 47057u, 47059u, 47087u, 47093u, 47111u, 47119u, 47123u, 47129u, 47137u, 47143u, 47147u, 47149u, 47161u, 47189u, 47207u, 47221u, 47237u, 47251u, 47269u, 47279u, 47287u, 47293u, 47297u, 47303u, 47309u, 47317u, 47339u, 47351u, 47353u, 47363u, 47381u, 47387u, 47389u, 47407u, 47417u, 47419u, 47431u, 47441u, 47459u, 47491u, 47497u, 47501u, 47507u, 47513u, 47521u, 47527u, 47533u, 47543u, 47563u, 47569u, 47581u, 47591u, 47599u, 47609u, 47623u, 47629u, 47639u, 47653u, 47657u, 47659u, 47681u, 47699u, 47701u, 47711u, 47713u, 47717u, 47737u, 47741u, 47743u, 47777u, 47779u, 47791u, 47797u, 47807u, 47809u, 47819u, 47837u, 47843u, 47857u, 47869u, 47881u, 47903u, 47911u, 47917u, 47933u, 47939u, 47947u, 47951u, 47963u, 47969u, 47977u, 47981u, 48017u, 48023u, 48029u, 48049u, 48073u, 48079u, 48091u, 48109u, 48119u, 48121u, 48131u, 48157u, 48163u, 48179u, 48187u, 48193u, 48197u, 48221u, 48239u, 48247u, 48259u, 48271u, 48281u, 48299u, 48311u, 48313u, 48337u, 48341u, 48353u, 48371u, 48383u, 48397u, 48407u, 48409u, 48413u, 48437u, 48449u, 48463u, 48473u, 48479u, 48481u, 48487u, 48491u, 48497u, 48523u, 48527u, 48533u, 48539u, 48541u, 48563u, 48571u, 48589u, 48593u, 48611u, 48619u, 48623u, 48647u, 48649u, 48661u, 48673u, 48677u, 48679u, 48731u, 48733u, 48751u, 48757u, 48761u, 48767u, 48779u, 48781u, 48787u, 48799u, 48809u, 48817u, 48821u, 48823u, 48847u, 48857u, 48859u, 48869u, 48871u, 48883u, 48889u, 48907u, 48947u, 48953u, 48973u, 48989u, 48991u, 49003u, 49009u, 49019u, 49031u, 49033u, 49037u, 49043u, 49057u, 49069u, 49081u, 49103u, 49109u, 49117u, 49121u, 49123u, 49139u, 49157u, 49169u, 49171u, 49177u, 49193u, 49199u, 49201u, 49207u, 49211u, 49223u, 49253u, 49261u, 49277u, 49279u, 49297u, 49307u, 49331u, 49333u, 49339u, 49363u, 49367u, 49369u, 49391u, 49393u, 49409u, 49411u, 49417u, 49429u, 49433u, 49451u, 49459u, 49463u, 49477u, 49481u, 49499u, 49523u, 49529u, 49531u, 49537u, 49547u, 49549u, 49559u, 49597u, 49603u, 49613u, 49627u, 49633u, 49639u, 49663u, 49667u, 49669u, 49681u, 49697u, 49711u, 49727u, 49739u, 49741u, 49747u, 49757u, 49783u, 49787u, 49789u, 49801u, 49807u, 49811u, 49823u, 49831u, 49843u, 49853u, 49871u, 49877u, 49891u, 49919u, 49921u, 49927u, 49937u, 49939u, 49943u, 49957u, 49991u, 49993u, 49999u, 50021u, 50023u, 50033u, 50047u, 50051u, 50053u, 50069u, 50077u, 50087u, 50093u, 50101u, 50111u, 50119u, 50123u, 50129u, 50131u, 50147u, 50153u, 50159u, 50177u, 50207u, 50221u, 50227u, 50231u, 50261u, 50263u, 50273u, 50287u, 50291u, 50311u, 50321u, 50329u, 50333u, 50341u, 50359u, 50363u, 50377u, 50383u, 50387u, 50411u, 50417u, 50423u, 50441u, 50459u, 50461u, 50497u, 50503u, 50513u, 50527u, 50539u, 50543u, 50549u, 50551u, 50581u, 50587u, 50591u, 50593u, 50599u, 50627u, 50647u, 50651u, 50671u, 50683u, 50707u, 50723u, 50741u, 50753u, 50767u, 50773u, 50777u, 50789u, 50821u, 50833u, 50839u, 50849u, 50857u, 50867u, 50873u, 50891u, 50893u, 50909u, 50923u, 50929u, 50951u, 50957u, 50969u, 50971u, 50989u, 50993u, 51001u, 51031u, 51043u, 51047u, 51059u, 51061u, 51071u, 51109u, 51131u, 51133u, 51137u, 51151u, 51157u, 51169u, 51193u, 51197u, 51199u, 51203u, 51217u, 51229u, 51239u, 51241u, 51257u, 51263u, 51283u, 51287u, 51307u, 51329u, 51341u, 51343u, 51347u, 51349u, 51361u, 51383u, 51407u, 51413u, 51419u, 51421u, 51427u, 51431u, 51437u, 51439u, 51449u, 51461u, 51473u, 51479u, 51481u, 51487u, 51503u, 51511u, 51517u, 51521u, 51539u, 51551u, 51563u, 51577u, 51581u, 51593u, 51599u, 51607u, 51613u, 51631u, 51637u, 51647u, 51659u, 51673u, 51679u, 51683u, 51691u, 51713u, 51719u, 51721u, 51749u, 51767u, 51769u, 51787u, 51797u, 51803u, 51817u, 51827u, 51829u, 51839u, 51853u, 51859u, 51869u, 51871u, 51893u, 51899u, 51907u, 51913u, 51929u, 51941u, 51949u, 51971u, 51973u, 51977u, 51991u, 52009u, 52021u, 52027u, 52051u, 52057u, 52067u, 52069u, 52081u, 52103u, 52121u, 52127u, 52147u, 52153u, 52163u, 52177u, 52181u, 52183u, 52189u, 52201u, 52223u, 52237u, 52249u, 52253u, 52259u, 52267u, 52289u, 52291u, 52301u, 52313u, 52321u, 52361u, 52363u, 52369u, 52379u, 52387u, 52391u, 52433u, 52453u, 52457u, 52489u, 52501u, 52511u, 52517u, 52529u, 52541u, 52543u, 52553u, 52561u, 52567u, 52571u, 52579u, 52583u, 52609u, 52627u, 52631u, 52639u, 52667u, 52673u, 52691u, 52697u, 52709u, 52711u, 52721u, 52727u, 52733u, 52747u, 52757u, 52769u, 52783u, 52807u, 52813u, 52817u, 52837u, 52859u, 52861u, 52879u, 52883u, 52889u, 52901u, 52903u, 52919u, 52937u, 52951u, 52957u, 52963u, 52967u, 52973u, 52981u, 52999u, 53003u, 53017u, 53047u, 53051u, 53069u, 53077u, 53087u, 53089u, 53093u, 53101u, 53113u, 53117u, 53129u, 53147u, 53149u, 53161u, 53171u, 53173u, 53189u, 53197u, 53201u, 53231u, 53233u, 53239u, 53267u, 53269u, 53279u, 53281u, 53299u, 53309u, 53323u, 53327u, 53353u, 53359u, 53377u, 53381u, 53401u, 53407u, 53411u, 53419u, 53437u, 53441u, 53453u, 53479u, 53503u, 53507u, 53527u, 53549u, 53551u, 53569u, 53591u, 53593u, 53597u, 53609u, 53611u, 53617u, 53623u, 53629u, 53633u, 53639u, 53653u, 53657u, 53681u, 53693u, 53699u, 53717u, 53719u, 53731u, 53759u, 53773u, 53777u, 53783u, 53791u, 53813u, 53819u, 53831u, 53849u, 53857u, 53861u, 53881u, 53887u, 53891u, 53897u, 53899u, 53917u, 53923u, 53927u, 53939u, 53951u, 53959u, 53987u, 53993u, 54001u, 54011u, 54013u, 54037u, 54049u, 54059u, 54083u, 54091u, 54101u, 54121u, 54133u, 54139u, 54151u, 54163u, 54167u, 54181u, 54193u, 54217u, 54251u, 54269u, 54277u, 54287u, 54293u, 54311u, 54319u, 54323u, 54331u, 54347u, 54361u, 54367u, 54371u, 54377u, 54401u, 54403u, 54409u, 54413u, 54419u, 54421u, 54437u, 54443u, 54449u, 54469u, 54493u, 54497u, 54499u, 54503u, 54517u, 54521u, 54539u, 54541u, 54547u, 54559u, 54563u, 54577u, 54581u, 54583u, 54601u, 54617u, 54623u, 54629u, 54631u, 54647u, 54667u, 54673u, 54679u, 54709u, 54713u, 54721u, 54727u, 54751u, 54767u, 54773u, 54779u, 54787u, 54799u, 54829u, 54833u, 54851u, 54869u, 54877u, 54881u, 54907u, 54917u, 54919u, 54941u, 54949u, 54959u, 54973u, 54979u, 54983u, 55001u, 55009u, 55021u, 55049u, 55051u, 55057u, 55061u, 55073u, 55079u, 55103u, 55109u, 55117u, 55127u, 55147u, 55163u, 55171u, 55201u, 55207u, 55213u, 55217u, 55219u, 55229u, 55243u, 55249u, 55259u, 55291u, 55313u, 55331u, 55333u, 55337u, 55339u, 55343u, 55351u, 55373u, 55381u, 55399u, 55411u, 55439u, 55441u, 55457u, 55469u, 55487u, 55501u, 55511u, 55529u, 55541u, 55547u, 55579u, 55589u, 55603u, 55609u, 55619u, 55621u, 55631u, 55633u, 55639u, 55661u, 55663u, 55667u, 55673u, 55681u, 55691u, 55697u, 55711u, 55717u, 55721u, 55733u, 55763u, 55787u, 55793u, 55799u, 55807u, 55813u, 55817u, 55819u, 55823u, 55829u, 55837u, 55843u, 55849u, 55871u, 55889u, 55897u, 55901u, 55903u, 55921u, 55927u, 55931u, 55933u, 55949u, 55967u, 55987u, 55997u, 56003u, 56009u, 56039u, 56041u, 56053u, 56081u, 56087u, 56093u, 56099u, 56101u, 56113u, 56123u, 56131u, 56149u, 56167u, 56171u, 56179u, 56197u, 56207u, 56209u, 56237u, 56239u, 56249u, 56263u, 56267u, 56269u, 56299u, 56311u, 56333u, 56359u, 56369u, 56377u, 56383u, 56393u, 56401u, 56417u, 56431u, 56437u, 56443u, 56453u, 56467u, 56473u, 56477u, 56479u, 56489u, 56501u, 56503u, 56509u, 56519u, 56527u, 56531u, 56533u, 56543u, 56569u, 56591u, 56597u, 56599u, 56611u, 56629u, 56633u, 56659u, 56663u, 56671u, 56681u, 56687u, 56701u, 56711u, 56713u, 56731u, 56737u, 56747u, 56767u, 56773u, 56779u, 56783u, 56807u, 56809u, 56813u, 56821u, 56827u, 56843u, 56857u, 56873u, 56891u, 56893u, 56897u, 56909u, 56911u, 56921u, 56923u, 56929u, 56941u, 56951u, 56957u, 56963u, 56983u, 56989u, 56993u, 56999u, 57037u, 57041u, 57047u, 57059u, 57073u, 57077u, 57089u, 57097u, 57107u, 57119u, 57131u, 57139u, 57143u, 57149u, 57163u, 57173u, 57179u, 57191u, 57193u, 57203u, 57221u, 57223u, 57241u, 57251u, 57259u, 57269u, 57271u, 57283u, 57287u, 57301u, 57329u, 57331u, 57347u, 57349u, 57367u, 57373u, 57383u, 57389u, 57397u, 57413u, 57427u, 57457u, 57467u, 57487u, 57493u, 57503u, 57527u, 57529u, 57557u, 57559u, 57571u, 57587u, 57593u, 57601u, 57637u, 57641u, 57649u, 57653u, 57667u, 57679u, 57689u, 57697u, 57709u, 57713u, 57719u, 57727u, 57731u, 57737u, 57751u, 57773u, 57781u, 57787u, 57791u, 57793u, 57803u, 57809u, 57829u, 57839u, 57847u, 57853u, 57859u, 57881u, 57899u, 57901u, 57917u, 57923u, 57943u, 57947u, 57973u, 57977u, 57991u, 58013u, 58027u, 58031u, 58043u, 58049u, 58057u, 58061u, 58067u, 58073u, 58099u, 58109u, 58111u, 58129u, 58147u, 58151u, 58153u, 58169u, 58171u, 58189u, 58193u, 58199u, 58207u, 58211u, 58217u, 58229u, 58231u, 58237u, 58243u, 58271u, 58309u, 58313u, 58321u, 58337u, 58363u, 58367u, 58369u, 58379u, 58391u, 58393u, 58403u, 58411u, 58417u, 58427u, 58439u, 58441u, 58451u, 58453u, 58477u, 58481u, 58511u, 58537u, 58543u, 58549u, 58567u, 58573u, 58579u, 58601u, 58603u, 58613u, 58631u, 58657u, 58661u, 58679u, 58687u, 58693u, 58699u, 58711u, 58727u, 58733u, 58741u, 58757u, 58763u, 58771u, 58787u, 58789u, 58831u, 58889u, 58897u, 58901u, 58907u, 58909u, 58913u, 58921u, 58937u, 58943u, 58963u, 58967u, 58979u, 58991u, 58997u, 59009u, 59011u, 59021u, 59023u, 59029u, 59051u, 59053u, 59063u, 59069u, 59077u, 59083u, 59093u, 59107u, 59113u, 59119u, 59123u, 59141u, 59149u, 59159u, 59167u, 59183u, 59197u, 59207u, 59209u, 59219u, 59221u, 59233u, 59239u, 59243u, 59263u, 59273u, 59281u, 59333u, 59341u, 59351u, 59357u, 59359u, 59369u, 59377u, 59387u, 59393u, 59399u, 59407u, 59417u, 59419u, 59441u, 59443u, 59447u, 59453u, 59467u, 59471u, 59473u, 59497u, 59509u, 59513u, 59539u, 59557u, 59561u, 59567u, 59581u, 59611u, 59617u, 59621u, 59627u, 59629u, 59651u, 59659u, 59663u, 59669u, 59671u, 59693u, 59699u, 59707u, 59723u, 59729u, 59743u, 59747u, 59753u, 59771u, 59779u, 59791u, 59797u, 59809u, 59833u, 59863u, 59879u, 59887u, 59921u, 59929u, 59951u, 59957u, 59971u, 59981u, 59999u, 60013u, 60017u, 60029u, 60037u, 60041u, 60077u, 60083u, 60089u, 60091u, 60101u, 60103u, 60107u, 60127u, 60133u, 60139u, 60149u, 60161u, 60167u, 60169u, 60209u, 60217u, 60223u, 60251u, 60257u, 60259u, 60271u, 60289u, 60293u, 60317u, 60331u, 60337u, 60343u, 60353u, 60373u, 60383u, 60397u, 60413u, 60427u, 60443u, 60449u, 60457u, 60493u, 60497u, 60509u, 60521u, 60527u, 60539u, 60589u, 60601u, 60607u, 60611u, 60617u, 60623u, 60631u, 60637u, 60647u, 60649u, 60659u, 60661u, 60679u, 60689u, 60703u, 60719u, 60727u, 60733u, 60737u, 60757u, 60761u, 60763u, 60773u, 60779u, 60793u, 60811u, 60821u, 60859u, 60869u, 60887u, 60889u, 60899u, 60901u, 60913u, 60917u, 60919u, 60923u, 60937u, 60943u, 60953u, 60961u, 61001u, 61007u, 61027u, 61031u, 61043u, 61051u, 61057u, 61091u, 61099u, 61121u, 61129u, 61141u, 61151u, 61153u, 61169u, 61211u, 61223u, 61231u, 61253u, 61261u, 61283u, 61291u, 61297u, 61331u, 61333u, 61339u, 61343u, 61357u, 61363u, 61379u, 61381u, 61403u, 61409u, 61417u, 61441u, 61463u, 61469u, 61471u, 61483u, 61487u, 61493u, 61507u, 61511u, 61519u, 61543u, 61547u, 61553u, 61559u, 61561u, 61583u, 61603u, 61609u, 61613u, 61627u, 61631u, 61637u, 61643u, 61651u, 61657u, 61667u, 61673u, 61681u, 61687u, 61703u, 61717u, 61723u, 61729u, 61751u, 61757u, 61781u, 61813u, 61819u, 61837u, 61843u, 61861u, 61871u, 61879u, 61909u, 61927u, 61933u, 61949u, 61961u, 61967u, 61979u, 61981u, 61987u, 61991u, 62003u, 62011u, 62017u, 62039u, 62047u, 62053u, 62057u, 62071u, 62081u, 62099u, 62119u, 62129u, 62131u, 62137u, 62141u, 62143u, 62171u, 62189u, 62191u, 62201u, 62207u, 62213u, 62219u, 62233u, 62273u, 62297u, 62299u, 62303u, 62311u, 62323u, 62327u, 62347u, 62351u, 62383u, 62401u, 62417u, 62423u, 62459u, 62467u, 62473u, 62477u, 62483u, 62497u, 62501u, 62507u, 62533u, 62539u, 62549u, 62563u, 62581u, 62591u, 62597u, 62603u, 62617u, 62627u, 62633u, 62639u, 62653u, 62659u, 62683u, 62687u, 62701u, 62723u, 62731u, 62743u, 62753u, 62761u, 62773u, 62791u, 62801u, 62819u, 62827u, 62851u, 62861u, 62869u, 62873u, 62897u, 62903u, 62921u, 62927u, 62929u, 62939u, 62969u, 62971u, 62981u, 62983u, 62987u, 62989u, 63029u, 63031u, 63059u, 63067u, 63073u, 63079u, 63097u, 63103u, 63113u, 63127u, 63131u, 63149u, 63179u, 63197u, 63199u, 63211u, 63241u, 63247u, 63277u, 63281u, 63299u, 63311u, 63313u, 63317u, 63331u, 63337u, 63347u, 63353u, 63361u, 63367u, 63377u, 63389u, 63391u, 63397u, 63409u, 63419u, 63421u, 63439u, 63443u, 63463u, 63467u, 63473u, 63487u, 63493u, 63499u, 63521u, 63527u, 63533u, 63541u, 63559u, 63577u, 63587u, 63589u, 63599u, 63601u, 63607u, 63611u, 63617u, 63629u, 63647u, 63649u, 63659u, 63667u, 63671u, 63689u, 63691u, 63697u, 63703u, 63709u, 63719u, 63727u, 63737u, 63743u, 63761u, 63773u, 63781u, 63793u, 63799u, 63803u, 63809u, 63823u, 63839u, 63841u, 63853u, 63857u, 63863u, 63901u, 63907u, 63913u, 63929u, 63949u, 63977u, 63997u, 64007u, 64013u, 64019u, 64033u, 64037u, 64063u, 64067u, 64081u, 64091u, 64109u, 64123u, 64151u, 64153u, 64157u, 64171u, 64187u, 64189u, 64217u, 64223u, 64231u, 64237u, 64271u, 64279u, 64283u, 64301u, 64303u, 64319u, 64327u, 64333u, 64373u, 64381u, 64399u, 64403u, 64433u, 64439u, 64451u, 64453u, 64483u, 64489u, 64499u, 64513u, 64553u, 64567u, 64577u, 64579u, 64591u, 64601u, 64609u, 64613u, 64621u, 64627u, 64633u, 64661u, 64663u, 64667u, 64679u, 64693u, 64709u, 64717u, 64747u, 64763u, 64781u, 64783u, 64793u, 64811u, 64817u, 64849u, 64853u, 64871u, 64877u, 64879u, 64891u, 64901u, 64919u, 64921u, 64927u, 64937u, 64951u, 64969u, 64997u, 65003u, 65011u, 65027u, 65029u, 65033u, 65053u, 65063u, 65071u, 65089u, 65099u, 65101u, 65111u, 65119u, 65123u, 65129u, 65141u, 65147u, 65167u, 65171u, 65173u, 65179u, 65183u, 65203u, 65213u, 65239u, 65257u, 65267u, 65269u, 65287u, 65293u, 65309u, 65323u, 65327u, 65353u, 65357u, 65371u, 65381u, 65393u, 65407u, 65413u, 65419u, 65423u, 65437u, 65447u, 65449u, 65479u, 65497u, 65519u, 65521u }}; #ifdef BOOST_MATH_HAVE_CONSTEXPR_TABLES constexpr std::array<boost::uint16_t, 3458> a3 = {{ #else static const boost::array<boost::uint16_t, 3458> a3 = {{ #endif 2u, 4u, 8u, 16u, 22u, 28u, 44u, 46u, 52u, 64u, 74u, 82u, 94u, 98u, 112u, 116u, 122u, 142u, 152u, 164u, 166u, 172u, 178u, 182u, 184u, 194u, 196u, 226u, 242u, 254u, 274u, 292u, 296u, 302u, 304u, 308u, 316u, 332u, 346u, 364u, 386u, 392u, 394u, 416u, 422u, 428u, 446u, 448u, 458u, 494u, 502u, 506u, 512u, 532u, 536u, 548u, 554u, 568u, 572u, 574u, 602u, 626u, 634u, 638u, 644u, 656u, 686u, 704u, 736u, 758u, 766u, 802u, 808u, 812u, 824u, 826u, 838u, 842u, 848u, 868u, 878u, 896u, 914u, 922u, 928u, 932u, 956u, 964u, 974u, 988u, 994u, 998u, 1006u, 1018u, 1034u, 1036u, 1052u, 1058u, 1066u, 1082u, 1094u, 1108u, 1118u, 1148u, 1162u, 1166u, 1178u, 1186u, 1198u, 1204u, 1214u, 1216u, 1228u, 1256u, 1262u, 1274u, 1286u, 1306u, 1316u, 1318u, 1328u, 1342u, 1348u, 1354u, 1384u, 1388u, 1396u, 1408u, 1412u, 1414u, 1424u, 1438u, 1442u, 1468u, 1486u, 1498u, 1508u, 1514u, 1522u, 1526u, 1538u, 1544u, 1568u, 1586u, 1594u, 1604u, 1606u, 1618u, 1622u, 1634u, 1646u, 1652u, 1654u, 1676u, 1678u, 1682u, 1684u, 1696u, 1712u, 1726u, 1736u, 1738u, 1754u, 1772u, 1804u, 1808u, 1814u, 1834u, 1856u, 1864u, 1874u, 1876u, 1886u, 1892u, 1894u, 1898u, 1912u, 1918u, 1942u, 1946u, 1954u, 1958u, 1964u, 1976u, 1988u, 1996u, 2002u, 2012u, 2024u, 2032u, 2042u, 2044u, 2054u, 2066u, 2072u, 2084u, 2096u, 2116u, 2144u, 2164u, 2174u, 2188u, 2198u, 2206u, 2216u, 2222u, 2224u, 2228u, 2242u, 2248u, 2254u, 2266u, 2272u, 2284u, 2294u, 2308u, 2318u, 2332u, 2348u, 2356u, 2366u, 2392u, 2396u, 2398u, 2404u, 2408u, 2422u, 2426u, 2432u, 2444u, 2452u, 2458u, 2488u, 2506u, 2518u, 2524u, 2536u, 2552u, 2564u, 2576u, 2578u, 2606u, 2612u, 2626u, 2636u, 2672u, 2674u, 2678u, 2684u, 2692u, 2704u, 2726u, 2744u, 2746u, 2776u, 2794u, 2816u, 2836u, 2854u, 2864u, 2902u, 2908u, 2912u, 2914u, 2938u, 2942u, 2948u, 2954u, 2956u, 2966u, 2972u, 2986u, 2996u, 3004u, 3008u, 3032u, 3046u, 3062u, 3076u, 3098u, 3104u, 3124u, 3134u, 3148u, 3152u, 3164u, 3176u, 3178u, 3194u, 3202u, 3208u, 3214u, 3232u, 3236u, 3242u, 3256u, 3278u, 3284u, 3286u, 3328u, 3344u, 3346u, 3356u, 3362u, 3364u, 3368u, 3374u, 3382u, 3392u, 3412u, 3428u, 3458u, 3466u, 3476u, 3484u, 3494u, 3496u, 3526u, 3532u, 3538u, 3574u, 3584u, 3592u, 3608u, 3614u, 3616u, 3628u, 3656u, 3658u, 3662u, 3668u, 3686u, 3698u, 3704u, 3712u, 3722u, 3724u, 3728u, 3778u, 3782u, 3802u, 3806u, 3836u, 3844u, 3848u, 3854u, 3866u, 3868u, 3892u, 3896u, 3904u, 3922u, 3928u, 3932u, 3938u, 3946u, 3956u, 3958u, 3962u, 3964u, 4004u, 4022u, 4058u, 4088u, 4118u, 4126u, 4142u, 4156u, 4162u, 4174u, 4202u, 4204u, 4226u, 4228u, 4232u, 4244u, 4274u, 4286u, 4292u, 4294u, 4298u, 4312u, 4322u, 4324u, 4342u, 4364u, 4376u, 4394u, 4396u, 4406u, 4424u, 4456u, 4462u, 4466u, 4468u, 4474u, 4484u, 4504u, 4516u, 4526u, 4532u, 4544u, 4564u, 4576u, 4582u, 4586u, 4588u, 4604u, 4606u, 4622u, 4628u, 4642u, 4646u, 4648u, 4664u, 4666u, 4672u, 4688u, 4694u, 4702u, 4706u, 4714u, 4736u, 4754u, 4762u, 4774u, 4778u, 4786u, 4792u, 4816u, 4838u, 4844u, 4846u, 4858u, 4888u, 4894u, 4904u, 4916u, 4922u, 4924u, 4946u, 4952u, 4954u, 4966u, 4972u, 4994u, 5002u, 5014u, 5036u, 5038u, 5048u, 5054u, 5072u, 5084u, 5086u, 5092u, 5104u, 5122u, 5128u, 5132u, 5152u, 5174u, 5182u, 5194u, 5218u, 5234u, 5248u, 5258u, 5288u, 5306u, 5308u, 5314u, 5318u, 5332u, 5342u, 5344u, 5356u, 5366u, 5378u, 5384u, 5386u, 5402u, 5414u, 5416u, 5422u, 5434u, 5444u, 5446u, 5456u, 5462u, 5464u, 5476u, 5488u, 5504u, 5524u, 5534u, 5546u, 5554u, 5584u, 5594u, 5608u, 5612u, 5618u, 5626u, 5632u, 5636u, 5656u, 5674u, 5698u, 5702u, 5714u, 5722u, 5726u, 5728u, 5752u, 5758u, 5782u, 5792u, 5794u, 5798u, 5804u, 5806u, 5812u, 5818u, 5824u, 5828u, 5852u, 5854u, 5864u, 5876u, 5878u, 5884u, 5894u, 5902u, 5908u, 5918u, 5936u, 5938u, 5944u, 5948u, 5968u, 5992u, 6002u, 6014u, 6016u, 6028u, 6034u, 6058u, 6062u, 6098u, 6112u, 6128u, 6136u, 6158u, 6164u, 6172u, 6176u, 6178u, 6184u, 6206u, 6226u, 6242u, 6254u, 6272u, 6274u, 6286u, 6302u, 6308u, 6314u, 6326u, 6332u, 6344u, 6346u, 6352u, 6364u, 6374u, 6382u, 6398u, 6406u, 6412u, 6428u, 6436u, 6448u, 6452u, 6458u, 6464u, 6484u, 6496u, 6508u, 6512u, 6518u, 6538u, 6542u, 6554u, 6556u, 6566u, 6568u, 6574u, 6604u, 6626u, 6632u, 6634u, 6638u, 6676u, 6686u, 6688u, 6692u, 6694u, 6716u, 6718u, 6734u, 6736u, 6742u, 6752u, 6772u, 6778u, 6802u, 6806u, 6818u, 6832u, 6844u, 6848u, 6886u, 6896u, 6926u, 6932u, 6934u, 6946u, 6958u, 6962u, 6968u, 6998u, 7012u, 7016u, 7024u, 7042u, 7078u, 7082u, 7088u, 7108u, 7112u, 7114u, 7126u, 7136u, 7138u, 7144u, 7154u, 7166u, 7172u, 7184u, 7192u, 7198u, 7204u, 7228u, 7232u, 7262u, 7282u, 7288u, 7324u, 7334u, 7336u, 7348u, 7354u, 7358u, 7366u, 7372u, 7376u, 7388u, 7396u, 7402u, 7414u, 7418u, 7424u, 7438u, 7442u, 7462u, 7474u, 7478u, 7484u, 7502u, 7504u, 7508u, 7526u, 7528u, 7544u, 7556u, 7586u, 7592u, 7598u, 7606u, 7646u, 7654u, 7702u, 7708u, 7724u, 7742u, 7756u, 7768u, 7774u, 7792u, 7796u, 7816u, 7826u, 7828u, 7834u, 7844u, 7852u, 7882u, 7886u, 7898u, 7918u, 7924u, 7936u, 7942u, 7948u, 7982u, 7988u, 7994u, 8012u, 8018u, 8026u, 8036u, 8048u, 8054u, 8062u, 8072u, 8074u, 8078u, 8102u, 8108u, 8116u, 8138u, 8144u, 8146u, 8158u, 8164u, 8174u, 8186u, 8192u, 8216u, 8222u, 8236u, 8248u, 8284u, 8288u, 8312u, 8314u, 8324u, 8332u, 8342u, 8348u, 8362u, 8372u, 8404u, 8408u, 8416u, 8426u, 8438u, 8464u, 8482u, 8486u, 8492u, 8512u, 8516u, 8536u, 8542u, 8558u, 8564u, 8566u, 8596u, 8608u, 8614u, 8624u, 8626u, 8632u, 8642u, 8654u, 8662u, 8666u, 8668u, 8674u, 8684u, 8696u, 8722u, 8744u, 8752u, 8758u, 8762u, 8776u, 8782u, 8788u, 8818u, 8822u, 8828u, 8842u, 8846u, 8848u, 8876u, 8878u, 8884u, 8906u, 8914u, 8918u, 8936u, 8954u, 8972u, 8974u, 8986u, 8992u, 8996u, 9016u, 9026u, 9032u, 9038u, 9052u, 9062u, 9074u, 9076u, 9088u, 9118u, 9152u, 9164u, 9172u, 9178u, 9182u, 9184u, 9194u, 9196u, 9212u, 9224u, 9226u, 9236u, 9244u, 9262u, 9286u, 9292u, 9296u, 9308u, 9322u, 9326u, 9334u, 9338u, 9352u, 9356u, 9362u, 9368u, 9388u, 9394u, 9398u, 9406u, 9424u, 9476u, 9478u, 9482u, 9494u, 9502u, 9506u, 9544u, 9548u, 9574u, 9598u, 9614u, 9626u, 9632u, 9634u, 9646u, 9658u, 9674u, 9676u, 9682u, 9688u, 9692u, 9704u, 9718u, 9734u, 9742u, 9754u, 9772u, 9788u, 9794u, 9802u, 9812u, 9818u, 9832u, 9842u, 9854u, 9856u, 9866u, 9868u, 9872u, 9896u, 9902u, 9944u, 9968u, 9976u, 9986u, 9992u, 9998u, 10004u, 10006u, 10018u, 10022u, 10036u, 10042u, 10048u, 10076u, 10082u, 10084u, 10094u, 10106u, 10118u, 10124u, 10144u, 10148u, 10154u, 10168u, 10172u, 10174u, 10186u, 10196u, 10208u, 10232u, 10238u, 10246u, 10252u, 10258u, 10262u, 10286u, 10298u, 10318u, 10334u, 10348u, 10378u, 10396u, 10402u, 10406u, 10432u, 10444u, 10448u, 10454u, 10456u, 10462u, 10466u, 10468u, 10496u, 10504u, 10544u, 10546u, 10556u, 10564u, 10568u, 10588u, 10594u, 10612u, 10622u, 10624u, 10628u, 10672u, 10678u, 10696u, 10708u, 10714u, 10718u, 10724u, 10726u, 10748u, 10754u, 10768u, 10798u, 10808u, 10832u, 10834u, 10844u, 10852u, 10868u, 10886u, 10888u, 10906u, 10928u, 10936u, 10946u, 10952u, 10958u, 10972u, 10976u, 10984u, 11002u, 11006u, 11008u, 11026u, 11044u, 11062u, 11068u, 11072u, 11096u, 11114u, 11116u, 11132u, 11138u, 11144u, 11162u, 11182u, 11198u, 11218u, 11222u, 11236u, 11242u, 11246u, 11266u, 11284u, 11294u, 11296u, 11302u, 11312u, 11336u, 11338u, 11348u, 11372u, 11378u, 11384u, 11408u, 11414u, 11426u, 11428u, 11456u, 11468u, 11482u, 11488u, 11494u, 11506u, 11512u, 11534u, 11546u, 11558u, 11566u, 11602u, 11606u, 11618u, 11632u, 11636u, 11656u, 11666u, 11678u, 11702u, 11704u, 11708u, 11714u, 11726u, 11728u, 11732u, 11734u, 11744u, 11756u, 11782u, 11788u, 11804u, 11812u, 11816u, 11824u, 11834u, 11842u, 11848u, 11882u, 11884u, 11896u, 11912u, 11936u, 11942u, 11944u, 11954u, 11956u, 11974u, 11978u, 11986u, 11992u, 12008u, 12014u, 12016u, 12022u, 12028u, 12034u, 12038u, 12052u, 12056u, 12076u, 12082u, 12086u, 12106u, 12112u, 12124u, 12146u, 12152u, 12154u, 12164u, 12176u, 12178u, 12184u, 12188u, 12196u, 12208u, 12212u, 12226u, 12238u, 12248u, 12262u, 12266u, 12278u, 12304u, 12314u, 12328u, 12332u, 12358u, 12364u, 12394u, 12398u, 12416u, 12434u, 12442u, 12448u, 12464u, 12472u, 12482u, 12496u, 12506u, 12514u, 12524u, 12544u, 12566u, 12586u, 12602u, 12604u, 12622u, 12628u, 12632u, 12638u, 12644u, 12656u, 12658u, 12668u, 12694u, 12698u, 12706u, 12724u, 12742u, 12748u, 12766u, 12772u, 12776u, 12782u, 12806u, 12812u, 12832u, 12866u, 12892u, 12902u, 12904u, 12932u, 12944u, 12952u, 12962u, 12974u, 12976u, 12982u, 13004u, 13006u, 13018u, 13034u, 13036u, 13042u, 13048u, 13058u, 13072u, 13088u, 13108u, 13114u, 13118u, 13156u, 13162u, 13172u, 13178u, 13186u, 13202u, 13244u, 13246u, 13252u, 13256u, 13262u, 13268u, 13274u, 13288u, 13304u, 13318u, 13322u, 13342u, 13352u, 13354u, 13358u, 13366u, 13384u, 13394u, 13406u, 13442u, 13444u, 13454u, 13496u, 13504u, 13508u, 13528u, 13552u, 13568u, 13576u, 13598u, 13604u, 13612u, 13616u, 13618u, 13624u, 13646u, 13652u, 13658u, 13666u, 13694u, 13696u, 13706u, 13724u, 13738u, 13744u, 13748u, 13766u, 13774u, 13784u, 13798u, 13802u, 13814u, 13822u, 13832u, 13844u, 13858u, 13862u, 13864u, 13876u, 13888u, 13892u, 13898u, 13916u, 13946u, 13958u, 13996u, 14002u, 14014u, 14024u, 14026u, 14044u, 14054u, 14066u, 14074u, 14078u, 14086u, 14092u, 14096u, 14098u, 14122u, 14134u, 14152u, 14156u, 14158u, 14162u, 14164u, 14222u, 14234u, 14242u, 14266u, 14276u, 14278u, 14282u, 14288u, 14294u, 14306u, 14308u, 14312u, 14326u, 14332u, 14338u, 14354u, 14366u, 14368u, 14372u, 14404u, 14408u, 14432u, 14438u, 14444u, 14452u, 14462u, 14464u, 14486u, 14504u, 14516u, 14536u, 14542u, 14572u, 14576u, 14606u, 14612u, 14614u, 14618u, 14632u, 14638u, 14642u, 14656u, 14672u, 14674u, 14686u, 14696u, 14698u, 14704u, 14716u, 14728u, 14738u, 14744u, 14752u, 14774u, 14782u, 14794u, 14806u, 14812u, 14828u, 14834u, 14852u, 14872u, 14894u, 14912u, 14914u, 14936u, 14938u, 14954u, 14956u, 14978u, 14992u, 15002u, 15022u, 15032u, 15064u, 15068u, 15076u, 15086u, 15092u, 15094u, 15116u, 15122u, 15134u, 15136u, 15142u, 15146u, 15148u, 15152u, 15166u, 15178u, 15202u, 15212u, 15214u, 15226u, 15242u, 15244u, 15248u, 15254u, 15268u, 15274u, 15284u, 15296u, 15298u, 15314u, 15328u, 15362u, 15374u, 15376u, 15382u, 15388u, 15394u, 15398u, 15418u, 15428u, 15454u, 15466u, 15478u, 15482u, 15484u, 15488u, 15496u, 15506u, 15508u, 15512u, 15514u, 15536u, 15542u, 15548u, 15562u, 15566u, 15584u, 15596u, 15622u, 15628u, 15638u, 15646u, 15662u, 15664u, 15668u, 15688u, 15698u, 15704u, 15746u, 15748u, 15758u, 15764u, 15772u, 15796u, 15808u, 15814u, 15818u, 15824u, 15836u, 15838u, 15866u, 15874u, 15886u, 15904u, 15922u, 15928u, 15974u, 15982u, 15992u, 15998u, 16012u, 16016u, 16018u, 16024u, 16028u, 16034u, 16076u, 16084u, 16094u, 16102u, 16112u, 16114u, 16132u, 16136u, 16142u, 16154u, 16166u, 16168u, 16172u, 16192u, 16202u, 16214u, 16226u, 16234u, 16238u, 16264u, 16282u, 16304u, 16312u, 16318u, 16334u, 16348u, 16364u, 16366u, 16384u, 16394u, 16396u, 16402u, 16408u, 16418u, 16432u, 16436u, 16438u, 16468u, 16472u, 16474u, 16478u, 16486u, 16496u, 16502u, 16504u, 16516u, 16532u, 16538u, 16594u, 16604u, 16606u, 16618u, 16628u, 16636u, 16648u, 16654u, 16658u, 16672u, 16682u, 16684u, 16688u, 16696u, 16702u, 16706u, 16726u, 16732u, 16744u, 16766u, 16772u, 16804u, 16814u, 16816u, 16826u, 16838u, 16852u, 16858u, 16886u, 16922u, 16928u, 16934u, 16936u, 16948u, 16952u, 16958u, 16964u, 16972u, 16994u, 16996u, 17014u, 17024u, 17026u, 17032u, 17036u, 17056u, 17066u, 17074u, 17078u, 17084u, 17098u, 17116u, 17122u, 17164u, 17186u, 17188u, 17192u, 17194u, 17222u, 17224u, 17228u, 17246u, 17252u, 17258u, 17264u, 17276u, 17278u, 17302u, 17312u, 17348u, 17354u, 17356u, 17368u, 17378u, 17404u, 17428u, 17446u, 17462u, 17468u, 17474u, 17488u, 17512u, 17524u, 17528u, 17536u, 17542u, 17554u, 17558u, 17566u, 17582u, 17602u, 17642u, 17668u, 17672u, 17684u, 17686u, 17692u, 17696u, 17698u, 17708u, 17722u, 17732u, 17734u, 17738u, 17764u, 17776u, 17804u, 17806u, 17822u, 17848u, 17854u, 17864u, 17866u, 17872u, 17882u, 17888u, 17896u, 17902u, 17908u, 17914u, 17924u, 17936u, 17942u, 17962u, 18002u, 18022u, 18026u, 18028u, 18044u, 18056u, 18062u, 18074u, 18082u, 18086u, 18104u, 18106u, 18118u, 18128u, 18154u, 18166u, 18182u, 18184u, 18202u, 18226u, 18238u, 18242u, 18256u, 18278u, 18298u, 18308u, 18322u, 18334u, 18338u, 18356u, 18368u, 18376u, 18386u, 18398u, 18404u, 18434u, 18448u, 18452u, 18476u, 18482u, 18512u, 18518u, 18524u, 18526u, 18532u, 18554u, 18586u, 18592u, 18596u, 18602u, 18608u, 18628u, 18644u, 18646u, 18656u, 18664u, 18676u, 18686u, 18688u, 18694u, 18704u, 18712u, 18728u, 18764u, 18772u, 18778u, 18782u, 18784u, 18812u, 18814u, 18842u, 18854u, 18856u, 18866u, 18872u, 18886u, 18896u, 18902u, 18908u, 18914u, 18922u, 18928u, 18932u, 18946u, 18964u, 18968u, 18974u, 18986u, 18988u, 18998u, 19016u, 19024u, 19054u, 19094u, 19096u, 19114u, 19118u, 19124u, 19138u, 19156u, 19162u, 19166u, 19178u, 19184u, 19196u, 19202u, 19216u, 19226u, 19252u, 19258u, 19274u, 19276u, 19292u, 19322u, 19324u, 19334u, 19336u, 19378u, 19384u, 19412u, 19426u, 19432u, 19442u, 19444u, 19456u, 19474u, 19486u, 19492u, 19502u, 19514u, 19526u, 19546u, 19552u, 19556u, 19558u, 19568u, 19574u, 19586u, 19598u, 19612u, 19624u, 19658u, 19664u, 19666u, 19678u, 19688u, 19694u, 19702u, 19708u, 19712u, 19724u, 19762u, 19768u, 19778u, 19796u, 19798u, 19826u, 19828u, 19834u, 19846u, 19876u, 19892u, 19894u, 19904u, 19912u, 19916u, 19918u, 19934u, 19952u, 19978u, 19982u, 19988u, 19996u, 20014u, 20036u, 20042u, 20062u, 20066u, 20072u, 20084u, 20086u, 20092u, 20104u, 20108u, 20126u, 20132u, 20134u, 20156u, 20168u, 20176u, 20182u, 20198u, 20216u, 20246u, 20258u, 20282u, 20284u, 20294u, 20296u, 20302u, 20308u, 20312u, 20318u, 20354u, 20368u, 20374u, 20396u, 20398u, 20456u, 20464u, 20476u, 20482u, 20492u, 20494u, 20534u, 20542u, 20548u, 20576u, 20578u, 20582u, 20596u, 20602u, 20608u, 20626u, 20636u, 20644u, 20648u, 20662u, 20666u, 20674u, 20704u, 20708u, 20714u, 20722u, 20728u, 20734u, 20752u, 20756u, 20758u, 20762u, 20776u, 20788u, 20806u, 20816u, 20818u, 20822u, 20834u, 20836u, 20846u, 20854u, 20864u, 20878u, 20888u, 20906u, 20918u, 20926u, 20932u, 20942u, 20956u, 20966u, 20974u, 20996u, 20998u, 21004u, 21026u, 21038u, 21044u, 21052u, 21064u, 21092u, 21094u, 21142u, 21154u, 21158u, 21176u, 21184u, 21194u, 21208u, 21218u, 21232u, 21236u, 21248u, 21278u, 21302u, 21308u, 21316u, 21322u, 21326u, 21334u, 21388u, 21392u, 21394u, 21404u, 21416u, 21424u, 21434u, 21446u, 21458u, 21476u, 21478u, 21502u, 21506u, 21514u, 21536u, 21548u, 21568u, 21572u, 21584u, 21586u, 21598u, 21614u, 21616u, 21644u, 21646u, 21652u, 21676u, 21686u, 21688u, 21716u, 21718u, 21722u, 21742u, 21746u, 21758u, 21764u, 21778u, 21782u, 21788u, 21802u, 21824u, 21848u, 21868u, 21872u, 21886u, 21892u, 21898u, 21908u, 21938u, 21946u, 21956u, 21974u, 21976u, 21982u, 21988u, 22004u, 22006u, 22012u, 22018u, 22022u, 22024u, 22048u, 22052u, 22054u, 22078u, 22088u, 22094u, 22096u, 22106u, 22108u, 22114u, 22136u, 22144u, 22148u, 22156u, 22162u, 22166u, 22184u, 22186u, 22204u, 22208u, 22216u, 22232u, 22258u, 22262u, 22268u, 22276u, 22298u, 22318u, 22334u, 22342u, 22346u, 22352u, 22376u, 22382u, 22396u, 22408u, 22424u, 22426u, 22438u, 22442u, 22456u, 22466u, 22468u, 22472u, 22484u, 22502u, 22534u, 22544u, 22558u, 22582u, 22594u, 22634u, 22642u, 22676u, 22688u, 22702u, 22706u, 22724u, 22726u, 22754u, 22766u, 22786u, 22792u, 22802u, 22804u, 22844u, 22862u, 22876u, 22888u, 22892u, 22928u, 22934u, 22936u, 22958u, 22964u, 22978u, 22988u, 23012u, 23054u, 23056u, 23072u, 23074u, 23108u, 23116u, 23122u, 23126u, 23128u, 23132u, 23146u, 23186u, 23194u, 23206u, 23212u, 23236u, 23254u, 23258u, 23264u, 23266u, 23272u, 23276u, 23278u, 23282u, 23284u, 23308u, 23318u, 23326u, 23332u, 23338u, 23348u, 23362u, 23368u, 23384u, 23402u, 23416u, 23434u, 23458u, 23462u, 23468u, 23474u, 23482u, 23486u, 23506u, 23516u, 23522u, 23534u, 23536u, 23548u, 23552u, 23566u, 23572u, 23578u, 23584u, 23588u, 23602u, 23618u, 23654u, 23668u, 23674u, 23678u, 23692u, 23696u, 23702u, 23726u, 23734u, 23738u, 23758u, 23768u, 23782u, 23794u, 23828u, 23836u, 23846u, 23852u, 23858u, 23864u, 23878u, 23882u, 23896u, 23908u, 23914u, 23924u, 23942u, 23956u, 23966u, 23978u, 23984u, 23986u, 23992u, 23998u, 24026u, 24028u, 24032u, 24056u, 24062u, 24064u, 24068u, 24076u, 24092u, 24098u, 24118u, 24122u, 24124u, 24134u, 24136u, 24146u, 24154u, 24218u, 24224u, 24232u, 24244u, 24248u, 24262u, 24274u, 24284u, 24286u, 24298u, 24304u, 24314u, 24332u, 24356u, 24362u, 24364u, 24374u, 24382u, 24388u, 24404u, 24424u, 24428u, 24442u, 24448u, 24454u, 24466u, 24472u, 24476u, 24482u, 24484u, 24488u, 24496u, 24518u, 24524u, 24532u, 24536u, 24538u, 24554u, 24572u, 24586u, 24592u, 24614u, 24628u, 24638u, 24652u, 24656u, 24662u, 24664u, 24668u, 24682u, 24692u, 24704u, 24712u, 24728u, 24736u, 24746u, 24754u, 24778u, 24818u, 24824u, 24836u, 24838u, 24844u, 24862u, 24866u, 24868u, 24872u, 24902u, 24904u, 24934u, 24938u, 24946u, 24964u, 24976u, 24988u, 24992u, 24994u, 24998u, 25012u, 25048u, 25064u, 25082u, 25084u, 25096u, 25106u, 25112u, 25124u, 25142u, 25144u, 25162u, 25168u, 25174u, 25196u, 25214u, 25252u, 25258u, 25268u, 25286u, 25288u, 25298u, 25306u, 25312u, 25328u, 25352u, 25366u, 25372u, 25376u, 25382u, 25396u, 25412u, 25436u, 25442u, 25454u, 25462u, 25474u, 25484u, 25498u, 25544u, 25546u, 25562u, 25564u, 25586u, 25592u, 25594u, 25604u, 25606u, 25616u, 25618u, 25624u, 25628u, 25648u, 25658u, 25664u, 25694u, 25702u, 25708u, 25714u, 25718u, 25748u, 25756u, 25762u, 25768u, 25774u, 25796u, 25832u, 25834u, 25838u, 25846u, 25852u, 25858u, 25862u, 25876u, 25888u, 25898u, 25918u, 25922u, 25924u, 25928u, 25958u, 25964u, 25978u, 25994u, 26006u, 26036u, 26038u, 26042u, 26048u, 26056u, 26086u, 26096u, 26104u, 26138u, 26156u, 26168u, 26176u, 26198u, 26218u, 26222u, 26236u, 26246u, 26266u, 26272u, 26276u, 26278u, 26288u, 26302u, 26306u, 26332u, 26338u, 26374u, 26386u, 26404u, 26408u, 26416u, 26422u, 26426u, 26432u, 26434u, 26462u, 26468u, 26474u, 26498u, 26506u, 26516u, 26542u, 26548u, 26572u, 26576u, 26584u, 26608u, 26618u, 26638u, 26642u, 26644u, 26654u, 26668u, 26684u, 26686u, 26692u, 26698u, 26702u, 26708u, 26716u, 26734u, 26762u, 26776u, 26782u, 26798u, 26812u, 26818u, 26822u, 26828u, 26834u, 26842u, 26846u, 26848u, 26852u, 26864u, 26866u, 26878u, 26884u, 26896u, 26924u, 26926u, 26932u, 26944u, 26954u, 26968u, 26972u, 27016u, 27022u, 27032u, 27034u, 27046u, 27058u, 27088u, 27092u, 27104u, 27106u, 27112u, 27122u, 27134u, 27136u, 27146u, 27148u, 27158u, 27164u, 27172u, 27182u, 27188u, 27202u, 27218u, 27226u, 27232u, 27244u, 27254u, 27256u, 27266u, 27274u, 27286u, 27296u, 27314u, 27322u, 27326u, 27328u, 27332u, 27358u, 27364u, 27386u, 27392u, 27406u, 27416u, 27422u, 27424u, 27452u, 27458u, 27466u, 27512u, 27518u, 27524u, 27542u, 27548u, 27554u, 27562u, 27568u, 27578u, 27596u, 27598u, 27604u, 27616u, 27634u, 27644u, 27652u, 27664u, 27694u, 27704u, 27706u, 27716u, 27718u, 27722u, 27728u, 27746u, 27748u, 27752u, 27772u, 27784u, 27788u, 27794u, 27802u, 27836u, 27842u, 27848u, 27872u, 27884u, 27892u, 27928u, 27944u, 27946u, 27952u, 27956u, 27958u, 27962u, 27968u, 27988u, 27994u, 28018u, 28022u, 28024u, 28028u, 28046u, 28066u, 28072u, 28094u, 28102u, 28148u, 28166u, 28168u, 28184u, 28204u, 28226u, 28228u, 28252u, 28274u, 28276u, 28292u, 28316u, 28336u, 28352u, 28354u, 28358u, 28366u, 28376u, 28378u, 28388u, 28402u, 28406u, 28414u, 28432u, 28436u, 28444u, 28448u, 28462u, 28472u, 28474u, 28498u, 28514u, 28522u, 28528u, 28544u, 28564u, 28574u, 28576u, 28582u, 28586u, 28616u, 28618u, 28634u, 28666u, 28672u, 28684u, 28694u, 28718u, 28726u, 28738u, 28756u, 28772u, 28774u, 28786u, 28792u, 28796u, 28808u, 28814u, 28816u, 28844u, 28862u, 28864u, 28886u, 28892u, 28898u, 28904u, 28906u, 28912u, 28928u, 28942u, 28948u, 28978u, 28994u, 28996u, 29006u, 29008u, 29012u, 29024u, 29026u, 29038u, 29048u, 29062u, 29068u, 29078u, 29086u, 29114u, 29116u, 29152u, 29158u, 29174u, 29188u, 29192u, 29212u, 29236u, 29242u, 29246u, 29254u, 29258u, 29276u, 29284u, 29288u, 29302u, 29306u, 29312u, 29314u, 29338u, 29354u, 29368u, 29372u, 29398u, 29414u, 29416u, 29426u, 29458u, 29464u, 29468u, 29474u, 29486u, 29492u, 29528u, 29536u, 29548u, 29552u, 29554u, 29558u, 29566u, 29572u, 29576u, 29596u, 29608u, 29618u, 29642u, 29654u, 29656u, 29668u, 29678u, 29684u, 29696u, 29698u, 29704u, 29722u, 29726u, 29732u, 29738u, 29744u, 29752u, 29776u, 29782u, 29792u, 29804u, 29834u, 29848u, 29858u, 29866u, 29878u, 29884u, 29894u, 29906u, 29908u, 29926u, 29932u, 29936u, 29944u, 29948u, 29972u, 29992u, 29996u, 30004u, 30014u, 30026u, 30034u, 30046u, 30062u, 30068u, 30082u, 30086u, 30094u, 30098u, 30116u, 30166u, 30172u, 30178u, 30182u, 30188u, 30196u, 30202u, 30212u, 30238u, 30248u, 30254u, 30256u, 30266u, 30268u, 30278u, 30284u, 30322u, 30334u, 30338u, 30346u, 30356u, 30376u, 30382u, 30388u, 30394u, 30412u, 30422u, 30424u, 30436u, 30452u, 30454u, 30466u, 30478u, 30482u, 30508u, 30518u, 30524u, 30544u, 30562u, 30602u, 30614u, 30622u, 30632u, 30644u, 30646u, 30664u, 30676u, 30686u, 30688u, 30698u, 30724u, 30728u, 30734u, 30746u, 30754u, 30758u, 30788u, 30794u, 30796u, 30802u, 30818u, 30842u, 30866u, 30884u, 30896u, 30908u, 30916u, 30922u, 30926u, 30934u, 30944u, 30952u, 30958u, 30962u, 30982u, 30992u, 31018u, 31022u, 31046u, 31052u, 31054u, 31066u, 31108u, 31126u, 31132u, 31136u, 31162u, 31168u, 31196u, 31202u, 31204u, 31214u, 31222u, 31228u, 31234u, 31244u, 31252u, 31262u, 31264u, 31286u, 31288u, 31292u, 31312u, 31316u, 31322u, 31358u, 31372u, 31376u, 31396u, 31418u, 31424u, 31438u, 31444u, 31454u, 31462u, 31466u, 31468u, 31472u, 31486u, 31504u, 31538u, 31546u, 31568u, 31582u, 31592u, 31616u, 31622u, 31624u, 31634u, 31636u, 31642u, 31652u, 31678u, 31696u, 31706u, 31724u, 31748u, 31766u, 31768u, 31792u, 31832u, 31834u, 31838u, 31844u, 31846u, 31852u, 31862u, 31888u, 31894u, 31906u, 31918u, 31924u, 31928u, 31964u, 31966u, 31976u, 31988u, 32012u, 32014u, 32018u, 32026u, 32036u, 32042u, 32044u, 32048u, 32072u, 32074u, 32078u, 32114u, 32116u, 32138u, 32152u, 32176u, 32194u, 32236u, 32242u, 32252u, 32254u, 32278u, 32294u, 32306u, 32308u, 32312u, 32314u, 32324u, 32326u, 32336u, 32344u, 32348u, 32384u, 32392u, 32396u, 32408u, 32426u, 32432u, 32438u, 32452u, 32474u, 32476u, 32482u, 32506u, 32512u, 32522u, 32546u, 32566u, 32588u, 32594u, 32608u, 32644u, 32672u, 32678u, 32686u, 32692u, 32716u, 32722u, 32734u, 32762u, 32764u, 32782u, 32786u, 32788u, 32792u, 32812u, 32834u, 32842u, 32852u, 32854u, 32872u, 32876u, 32884u, 32894u, 32908u, 32918u, 32924u, 32932u, 32938u, 32944u, 32956u, 32972u, 32984u, 32998u, 33008u, 33026u, 33028u, 33038u, 33062u, 33086u, 33092u, 33104u, 33106u, 33128u, 33134u, 33154u, 33176u, 33178u, 33182u, 33194u, 33196u, 33202u, 33238u, 33244u, 33266u, 33272u, 33274u, 33302u, 33314u, 33332u, 33334u, 33338u, 33352u, 33358u, 33362u, 33364u, 33374u, 33376u, 33392u, 33394u, 33404u, 33412u, 33418u, 33428u, 33446u, 33458u, 33464u, 33478u, 33482u, 33488u, 33506u, 33518u, 33544u, 33548u, 33554u, 33568u, 33574u, 33584u, 33596u, 33598u, 33602u, 33604u, 33614u, 33638u, 33646u, 33656u, 33688u, 33698u, 33706u, 33716u, 33722u, 33724u, 33742u, 33754u, 33782u, 33812u, 33814u, 33832u, 33836u, 33842u, 33856u, 33862u, 33866u, 33874u, 33896u, 33904u, 33934u, 33952u, 33962u, 33988u, 33992u, 33994u, 34016u, 34024u, 34028u, 34036u, 34042u, 34046u, 34072u, 34076u, 34088u, 34108u, 34126u, 34132u, 34144u, 34154u, 34172u, 34174u, 34178u, 34184u, 34186u, 34198u, 34226u, 34232u, 34252u, 34258u, 34274u, 34282u, 34288u, 34294u, 34298u, 34304u, 34324u, 34336u, 34342u, 34346u, 34366u, 34372u, 34388u, 34394u, 34426u, 34436u, 34454u, 34456u, 34468u, 34484u, 34508u, 34514u, 34522u, 34534u, 34568u, 34574u, 34594u, 34616u, 34618u, 34634u, 34648u, 34654u, 34658u, 34672u, 34678u, 34702u, 34732u, 34736u, 34744u, 34756u, 34762u, 34778u, 34798u, 34808u, 34822u, 34826u, 34828u, 34844u, 34856u, 34858u, 34868u, 34876u, 34882u, 34912u, 34924u, 34934u, 34948u, 34958u, 34966u, 34976u, 34982u, 34984u, 34988u, 35002u, 35012u, 35014u, 35024u, 35056u, 35074u, 35078u, 35086u, 35114u, 35134u, 35138u, 35158u, 35164u, 35168u, 35198u, 35206u, 35212u, 35234u, 35252u, 35264u, 35266u, 35276u, 35288u, 35294u, 35312u, 35318u, 35372u, 35378u, 35392u, 35396u, 35402u, 35408u, 35422u, 35446u, 35452u, 35464u, 35474u, 35486u, 35492u, 35516u, 35528u, 35546u, 35554u, 35572u, 35576u, 35578u, 35582u, 35584u, 35606u, 35614u, 35624u, 35626u, 35638u, 35648u, 35662u, 35668u, 35672u, 35674u, 35686u, 35732u, 35738u, 35744u, 35746u, 35752u, 35758u, 35788u, 35798u, 35806u, 35812u, 35824u, 35828u, 35842u, 35848u, 35864u, 35876u, 35884u, 35894u, 35914u, 35932u, 35942u, 35948u, 35954u, 35966u, 35968u, 35978u, 35992u, 35996u, 35998u, 36002u, 36026u, 36038u, 36046u, 36064u, 36068u, 36076u, 36092u, 36106u, 36118u, 36128u, 36146u, 36158u, 36166u, 36184u, 36188u, 36202u, 36206u, 36212u, 36214u, 36236u, 36254u, 36262u, 36272u, 36298u, 36302u, 36304u, 36328u, 36334u, 36338u, 36344u, 36356u, 36382u, 36386u, 36394u, 36404u, 36422u, 36428u, 36442u, 36452u, 36464u, 36466u, 36478u, 36484u, 36488u, 36496u, 36508u, 36524u, 36526u, 36536u, 36542u, 36544u, 36566u, 36568u, 36572u, 36586u, 36604u, 36614u, 36626u, 36646u, 36656u, 36662u, 36664u, 36668u, 36682u, 36694u, 36698u, 36706u, 36716u, 36718u, 36724u, 36758u, 36764u, 36766u, 36782u, 36794u, 36802u, 36824u, 36832u, 36862u, 36872u, 36874u, 36898u, 36902u, 36916u, 36926u, 36946u, 36962u, 36964u, 36968u, 36988u, 36998u, 37004u, 37012u, 37016u, 37024u, 37028u, 37052u, 37058u, 37072u, 37076u, 37108u, 37112u, 37118u, 37132u, 37138u, 37142u, 37144u, 37166u, 37226u, 37228u, 37234u, 37258u, 37262u, 37276u, 37294u, 37306u, 37324u, 37336u, 37342u, 37346u, 37376u, 37378u, 37394u, 37396u, 37418u, 37432u, 37448u, 37466u, 37472u, 37508u, 37514u, 37532u, 37534u, 37544u, 37552u, 37556u, 37558u, 37564u, 37588u, 37606u, 37636u, 37642u, 37648u, 37682u, 37696u, 37702u, 37754u, 37756u, 37772u, 37784u, 37798u, 37814u, 37822u, 37852u, 37856u, 37858u, 37864u, 37874u, 37886u, 37888u, 37916u, 37922u, 37936u, 37948u, 37976u, 37994u, 38014u, 38018u, 38026u, 38032u, 38038u, 38042u, 38048u, 38056u, 38078u, 38084u, 38108u, 38116u, 38122u, 38134u, 38146u, 38152u, 38164u, 38168u, 38188u, 38234u, 38252u, 38266u, 38276u, 38278u, 38302u, 38306u, 38308u, 38332u, 38354u, 38368u, 38378u, 38384u, 38416u, 38428u, 38432u, 38434u, 38444u, 38446u, 38456u, 38458u, 38462u, 38468u, 38474u, 38486u, 38498u, 38512u, 38518u, 38524u, 38552u, 38554u, 38572u, 38578u, 38584u, 38588u, 38612u, 38614u, 38626u, 38638u, 38644u, 38648u, 38672u, 38696u, 38698u, 38704u, 38708u, 38746u, 38752u, 38762u, 38774u, 38776u, 38788u, 38792u, 38812u, 38834u, 38846u, 38848u, 38858u, 38864u, 38882u, 38924u, 38936u, 38938u, 38944u, 38956u, 38978u, 38992u, 39002u, 39008u, 39014u, 39016u, 39026u, 39044u, 39058u, 39062u, 39088u, 39104u, 39116u, 39124u, 39142u, 39146u, 39148u, 39158u, 39166u, 39172u, 39176u, 39182u, 39188u, 39194u }}; if(n <= b1) return a1[n]; if(n <= b2) return a2[n - b1 - 1]; if(n >= b3) { return boost::math::policies::raise_domain_error<boost::uint32_t>( "boost::math::prime<%1%>", "Argument n out of range: got %1%", n, pol); } return static_cast<boost::uint32_t>(a3[n - b2 - 1]) + 0xFFFFu; } inline BOOST_MATH_CONSTEXPR_TABLE_FUNCTION boost::uint32_t prime(unsigned n) { return boost::math::prime(n, boost::math::policies::policy<>()); } static const unsigned max_prime = 10000; }} // namespace boost and math #endif // BOOST_MATH_SF_PRIME_HPP
74.866129
92
0.637622
YuukiTsuchida
f6a3b299d21d40f197ad836a73ff57cdec195c0e
7,860
cpp
C++
tests/Graph/KShortestPathsFinder.cpp
sonali-mishra-22/arangodb
0fb224af784247252e164f5ab9a83702ac80772c
[ "Apache-2.0" ]
1
2019-10-09T08:58:38.000Z
2019-10-09T08:58:38.000Z
tests/Graph/KShortestPathsFinder.cpp
sonali-mishra-22/arangodb
0fb224af784247252e164f5ab9a83702ac80772c
[ "Apache-2.0" ]
null
null
null
tests/Graph/KShortestPathsFinder.cpp
sonali-mishra-22/arangodb
0fb224af784247252e164f5ab9a83702ac80772c
[ "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2019-2019 ArangoDB GmbH, Cologne, Germany /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Markus Pfeiffer //////////////////////////////////////////////////////////////////////////////// #include "gtest/gtest.h" #include "fakeit.hpp" #include "Aql/AqlFunctionFeature.h" #include "Aql/Ast.h" #include "Aql/ExecutionPlan.h" #include "Aql/OptimizerRulesFeature.h" #include "Aql/Query.h" #include "ClusterEngine/ClusterEngine.h" #include "Graph/KShortestPathsFinder.h" #include "Graph/ShortestPathOptions.h" #include "Graph/ShortestPathResult.h" #include "Random/RandomGenerator.h" #include "RestServer/AqlFeature.h" #include "RestServer/DatabaseFeature.h" #include "RestServer/DatabasePathFeature.h" #include "RestServer/QueryRegistryFeature.h" #include "RestServer/SystemDatabaseFeature.h" #include "RestServer/TraverserEngineRegistryFeature.h" #include "StorageEngine/EngineSelectorFeature.h" #include "Transaction/Methods.h" #include "Transaction/StandaloneContext.h" #include "Utils/SingleCollectionTransaction.h" #include "VocBase/LogicalCollection.h" #include <velocypack/Builder.h> #include <velocypack/Slice.h> #include <velocypack/velocypack-aliases.h> // test setup #include "../Mocks/Servers.h" #include "../Mocks/StorageEngineMock.h" #include "GraphTestTools.h" #include "IResearch/common.h" using namespace arangodb; using namespace arangodb::aql; using namespace arangodb::graph; using namespace arangodb::velocypack; namespace arangodb { namespace tests { namespace graph { class KShortestPathsFinderTest : public ::testing::Test { protected: GraphTestSetup s; MockGraphDatabase gdb; arangodb::aql::Query* query; arangodb::graph::ShortestPathOptions* spo; KShortestPathsFinder* finder; KShortestPathsFinderTest() : gdb("testVocbase") { gdb.addVertexCollection("v", 100); gdb.addEdgeCollection( "e", "v", {{1, 2}, {2, 3}, {3, 4}, {5, 4}, {6, 5}, {7, 6}, {8, 7}, {1, 10}, {10, 11}, {11, 12}, {12, 4}, {12, 5}, {21, 22}, {22, 23}, {23, 24}, {24, 25}, {21, 26}, {26, 27}, {27, 28}, {28, 25}, {30, 31}, {31, 32}, {32, 33}, {33, 34}, {34, 35}, {32, 30}, {33, 35}, {40, 41}, {41, 42}, {41, 43}, {42, 44}, {43, 44}, {44, 45}, {45, 46}, {46, 47}, {48, 47}, {49, 47}, {50, 47}, {48, 46}, {50, 46}, {50, 47}, {48, 46}, {50, 46}, {40, 60}, {60, 61}, {61, 62}, {62, 63}, {63, 64}, {64, 47}, {70, 71}, {70, 71}, {70, 71}}); query = gdb.getQuery("RETURN 1"); spo = gdb.getShortestPathOptions(query); finder = new KShortestPathsFinder(*spo); } ~KShortestPathsFinderTest() { delete finder; } }; TEST_F(KShortestPathsFinderTest, path_from_vertex_to_itself) { auto start = velocypack::Parser::fromJson("\"v/0\""); auto end = velocypack::Parser::fromJson("\"v/0\""); ShortestPathResult result; finder->startKShortestPathsTraversal(start->slice(), end->slice()); ASSERT_TRUE(true == finder->getNextPathShortestPathResult(result)); ASSERT_TRUE(false == finder->getNextPathShortestPathResult(result)); } TEST_F(KShortestPathsFinderTest, no_path_exists) { auto start = velocypack::Parser::fromJson("\"v/0\""); auto end = velocypack::Parser::fromJson("\"v/1\""); ShortestPathResult result; finder->startKShortestPathsTraversal(start->slice(), end->slice()); ASSERT_TRUE(false == finder->getNextPathShortestPathResult(result)); // Repeat to see that we keep returning false and don't crash ASSERT_TRUE(false == finder->getNextPathShortestPathResult(result)); } TEST_F(KShortestPathsFinderTest, path_of_length_1) { auto start = velocypack::Parser::fromJson("\"v/1\""); auto end = velocypack::Parser::fromJson("\"v/2\""); ShortestPathResult result; std::string msgs; finder->startKShortestPathsTraversal(start->slice(), end->slice()); ASSERT_TRUE(true == finder->getNextPathShortestPathResult(result)); auto cpr = checkPath(spo, result, {"1", "2"}, {{}, {"v/1", "v/2"}}, msgs); ASSERT_TRUE(cpr) << msgs; } TEST_F(KShortestPathsFinderTest, path_of_length_4) { auto start = velocypack::Parser::fromJson("\"v/1\""); auto end = velocypack::Parser::fromJson("\"v/4\""); ShortestPathResult result; std::string msgs; finder->startKShortestPathsTraversal(start->slice(), end->slice()); ASSERT_TRUE(true == finder->getNextPathShortestPathResult(result)); auto cpr = checkPath(spo, result, {"1", "2", "3", "4"}, {{}, {"v/1", "v/2"}, {"v/2", "v/3"}, {"v/3", "v/4"}}, msgs); ASSERT_TRUE(cpr) << msgs; } TEST_F(KShortestPathsFinderTest, path_of_length_5_with_loops_to_start_end) { auto start = velocypack::Parser::fromJson("\"v/30\""); auto end = velocypack::Parser::fromJson("\"v/35\""); ShortestPathResult result; finder->startKShortestPathsTraversal(start->slice(), end->slice()); ASSERT_TRUE(true == finder->getNextPathShortestPathResult(result)); ASSERT_TRUE(result.length() == 5); } TEST_F(KShortestPathsFinderTest, two_paths_of_length_5) { auto start = velocypack::Parser::fromJson("\"v/21\""); auto end = velocypack::Parser::fromJson("\"v/25\""); ShortestPathResult result; std::string msgs; finder->startKShortestPathsTraversal(start->slice(), end->slice()); ASSERT_TRUE(true == finder->getNextPathShortestPathResult(result)); auto cpr = checkPath(spo, result, {"21", "22", "23", "24", "25"}, {{}, {"v/21", "v/22"}, {"v/22", "v/23"}, {"v/23", "v/24"}, {"v/24", "v/25"}}, msgs) || checkPath(spo, result, {"21", "26", "27", "28", "25"}, {{}, {"v/21", "v/26"}, {"v/26", "v/27"}, {"v/27", "v/28"}, {"v/28", "v/25"}}, msgs); ASSERT_TRUE(cpr) << msgs; ASSERT_TRUE(true == finder->getNextPathShortestPathResult(result)); cpr = checkPath(spo, result, {"21", "22", "23", "24", "25"}, {{}, {"v/21", "v/22"}, {"v/22", "v/23"}, {"v/23", "v/24"}, {"v/24", "v/25"}}, msgs) || checkPath(spo, result, {"21", "26", "27", "28", "25"}, {{}, {"v/21", "v/26"}, {"v/26", "v/27"}, {"v/27", "v/28"}, {"v/28", "v/25"}}, msgs); ASSERT_TRUE(cpr) << msgs; } TEST_F(KShortestPathsFinderTest, many_edges_between_two_nodes) { auto start = velocypack::Parser::fromJson("\"v/70\""); auto end = velocypack::Parser::fromJson("\"v/71\""); ShortestPathResult result; finder->startKShortestPathsTraversal(start->slice(), end->slice()); ASSERT_TRUE(true == finder->getNextPathShortestPathResult(result)); ASSERT_TRUE(true == finder->getNextPathShortestPathResult(result)); ASSERT_TRUE(true == finder->getNextPathShortestPathResult(result)); ASSERT_TRUE(false == finder->getNextPathShortestPathResult(result)); } } // namespace graph } // namespace tests } // namespace arangodb
36.055046
83
0.611705
sonali-mishra-22