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
9068d9dc5f44f41a912c3b0f30b5604817200057
48,623
cpp
C++
consensus/server/src/consensusobject.cpp
joydit/solidframe
0539b0a1e77663ac4c701a88f56723d3e3688e8c
[ "BSL-1.0" ]
null
null
null
consensus/server/src/consensusobject.cpp
joydit/solidframe
0539b0a1e77663ac4c701a88f56723d3e3688e8c
[ "BSL-1.0" ]
null
null
null
consensus/server/src/consensusobject.cpp
joydit/solidframe
0539b0a1e77663ac4c701a88f56723d3e3688e8c
[ "BSL-1.0" ]
null
null
null
// consensus/server/src/consensusobject.cpp // // Copyright (c) 2011, 2012 Valentin Palade (vipalade @ gmail . com) // // This file is part of SolidFrame framework. // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt. // #include <deque> #include <queue> #include <vector> #include <algorithm> #include "system/common.hpp" #include "system/exception.hpp" #ifdef HAS_CPP11 #include <unordered_map> #include <unordered_set> #else #include <map> #include <set> #endif #include "system/timespec.hpp" #include "serialization/binary.hpp" #include "frame/object.hpp" #include "frame/manager.hpp" #include "frame/message.hpp" #include "frame/ipc/ipcservice.hpp" #include "utility/stack.hpp" #include "utility/queue.hpp" #include "utility/timerqueue.hpp" #include "consensus/consensusregistrar.hpp" #include "consensus/consensusrequest.hpp" #include "consensus/server/consensusobject.hpp" #include "consensusmessages.hpp" using namespace std; namespace solid{ namespace consensus{ namespace server{ struct TimerValue{ TimerValue( uint32 _idx = 0, uint16 _uid = 0, uint16 _val = 0 ):index(_idx), uid(_uid), value(_val){} uint32 index; uint16 uid; uint16 value; }; typedef TimerQueue<TimerValue> TimerQueueT; typedef DynamicPointer<consensus::WriteRequestMessage> WriteRequestMessagePointerT; //======================================================== struct RequestStub{ enum{ InitState = 0, WaitProposeState, WaitProposeConfirmState, WaitAcceptState, WaitAcceptConfirmState, AcceptWaitRequestState, AcceptState, AcceptPendingState, AcceptRunState, EraseState, }; enum{ SignaledEvent = 1, TimeoutEvent = 2, }; enum{ HaveRequestFlag = 1, HaveProposeFlag = 2, HaveAcceptFlag = 4, }; RequestStub( ): evs(0), flags(0), proposeid(0xffffffff/2), acceptid(-1), timerid(0), recvpropconf(0), recvpropdecl(0), st(InitState){} RequestStub( DynamicPointer<consensus::WriteRequestMessage> &_rmsgptr ): msgptr(_rmsgptr), evs(0), flags(0), proposeid(-1), acceptid(-1), timerid(0), recvpropconf(0), recvpropdecl(0), st(InitState){} bool hasRequest()const{ return flags & HaveRequestFlag; } void reinit(){ evs = 0; flags = 0; st = InitState; proposeid = -1; acceptid = -1; recvpropconf = 0; } void state(uint8 _st); uint8 state()const{ return st; } bool isValidProposeState()const; bool isValidProposeConfirmState()const; bool isValidProposeDeclineState()const; bool isValidAcceptState()const; bool isValidFastAcceptState()const; bool isValidAcceptConfirmState()const; bool isValidAcceptDeclineState()const; WriteRequestMessagePointerT msgptr; uint16 evs; uint16 flags; uint32 proposeid; uint32 acceptid; uint16 timerid; uint8 recvpropconf;//received accepts for propose uint8 recvpropdecl;//received accepts for propose private: uint8 st; }; void RequestStub::state(uint8 _st){ //checking the safetyness of state change switch(_st){ //case WaitProposeState: //case WaitProposeConfirmState: //case WaitAcceptConfirmState: //case AcceptWaitRequestState: case AcceptState: if( st == InitState || st == WaitProposeState || st == WaitAcceptConfirmState || st == WaitAcceptState || st == AcceptPendingState ){ break; }else{ THROW_EXCEPTION_EX("Invalid state for request ", (int)st); break; } //case AcceptPendingState: //case EraseState: default: break; } st = _st; } inline bool RequestStub::isValidProposeState()const{ switch(st){ case InitState: case WaitProposeState: case WaitProposeConfirmState: case WaitAcceptConfirmState: case WaitAcceptState: return true; default: return false; } } inline bool RequestStub::isValidProposeConfirmState()const{ switch(st){ case InitState: case WaitProposeState: return false; case WaitProposeConfirmState: return true; case WaitAcceptConfirmState: case WaitAcceptState: default: return false; } } inline bool RequestStub::isValidProposeDeclineState()const{ return isValidProposeConfirmState(); } inline bool RequestStub::isValidAcceptState()const{ switch(st){ case WaitAcceptState: return true; case AcceptWaitRequestState: case AcceptState: case AcceptPendingState: default: return false; } } inline bool RequestStub::isValidFastAcceptState()const{ switch(st){ case InitState: case WaitProposeState: case WaitProposeConfirmState: return true; case WaitAcceptConfirmState: case WaitAcceptState: default: return false; } } inline bool RequestStub::isValidAcceptConfirmState()const{ switch(st){ case InitState: case WaitProposeState: case WaitProposeConfirmState: return false; case WaitAcceptConfirmState: return true; case WaitAcceptState: default: return false; } } inline bool RequestStub::isValidAcceptDeclineState()const{ return isValidAcceptConfirmState(); } typedef std::deque<RequestStub> RequestStubVectorT; typedef DynamicPointer<Configuration> ConfigurationPointerT; struct Object::Data{ enum{ ProposeOperation = 1, ProposeConfirmOperation, ProposeDeclineOperation, AcceptOperation, FastAcceptOperation, AcceptConfirmOperation, AcceptDeclineOperation, }; struct ReqCmpEqual{ bool operator()(const consensus::RequestId* const & _req1, const consensus::RequestId* const & _req2)const; }; struct ReqCmpLess{ bool operator()(const consensus::RequestId* const & _req1, const consensus::RequestId* const & _req2)const; }; struct ReqHash{ size_t operator()(const consensus::RequestId* const & _req1)const; }; struct SenderCmpEqual{ bool operator()(const consensus::RequestId & _req1, const consensus::RequestId& _req2)const; }; struct SenderCmpLess{ bool operator()(const consensus::RequestId& _req1, const consensus::RequestId& _req2)const; }; struct SenderHash{ size_t operator()(const consensus::RequestId& _req1)const; }; #ifdef HAS_CPP11 typedef std::unordered_map<const consensus::RequestId*, size_t, ReqHash, ReqCmpEqual> RequestStubMapT; typedef std::unordered_set<consensus::RequestId, SenderHash, SenderCmpEqual> SenderSetT; #else typedef std::map<const consensus::RequestId*, size_t, ReqCmpLess> RequestStubMapT; typedef std::set<consensus::RequestId, SenderCmpLess> SenderSetT; #endif typedef Stack<size_t> SizeTStackT; typedef Queue<size_t> SizeTQueueT; typedef std::vector<DynamicPointer<> > DynamicPointerVectorT; //methods: Data(DynamicPointer<Configuration> &_rcfgptr); ~Data(); bool insertRequestStub(DynamicPointer<WriteRequestMessage> &_rmsgptr, size_t &_ridx); void eraseRequestStub(const size_t _idx); RequestStub& requestStub(const size_t _idx); RequestStub& safeRequestStub(const consensus::RequestId &_reqid, size_t &_rreqidx); RequestStub* requestStubPointer(const consensus::RequestId &_reqid, size_t &_rreqidx); const RequestStub& requestStub(const size_t _idx)const; bool checkAlreadyReceived(DynamicPointer<WriteRequestMessage> &_rmsgptr); bool isCoordinator()const; bool canSendFastAccept()const; void coordinatorId(int8 _coordid); //data: ConfigurationPointerT cfgptr; DynamicPointerVectorT dv; uint32 proposeid; frame::IndexT srvidx; uint32 acceptid; uint32 proposedacceptid; uint32 confirmedacceptid; uint32 continuousacceptedproposes; size_t pendingacceptwaitidx; int8 coordinatorid; int8 distancefromcoordinator; uint8 acceptpendingcnt;//the number of stubs in waitrequest state bool isnotjuststarted; TimeSpec lastaccepttime; RequestStubMapT reqmap; RequestStubVectorT reqvec; SizeTQueueT reqq; SizeTStackT freeposstk; SenderSetT senderset; TimerQueueT timerq; int state; }; inline bool Object::Data::ReqCmpEqual::operator()( const consensus::RequestId* const & _req1, const consensus::RequestId* const & _req2 )const{ return *_req1 == *_req2; } inline bool Object::Data::ReqCmpLess::operator()( const consensus::RequestId* const & _req1, const consensus::RequestId* const & _req2 )const{ return *_req1 < *_req2; } inline size_t Object::Data::ReqHash::operator()( const consensus::RequestId* const & _req1 )const{ return _req1->hash(); } inline bool Object::Data::SenderCmpEqual::operator()( const consensus::RequestId & _req1, const consensus::RequestId& _req2 )const{ return _req1.senderEqual(_req2); } inline bool Object::Data::SenderCmpLess::operator()( const consensus::RequestId& _req1, const consensus::RequestId& _req2 )const{ return _req1.senderLess(_req2); } inline size_t Object::Data::SenderHash::operator()( const consensus::RequestId& _req1 )const{ return _req1.senderHash(); } /* NOTE: the 0 value for proposeid is only valid for the beginning of the algorithm. A replica should only accept a proposeid==0 if its proposeid is 0. On overflow, the proposeid should skip the 0 value. */ Object::Data::Data(DynamicPointer<Configuration> &_rcfgptr): cfgptr(_rcfgptr), proposeid(0), srvidx(INVALID_INDEX), acceptid(0), proposedacceptid(0), confirmedacceptid(0), continuousacceptedproposes(0), pendingacceptwaitidx(-1), coordinatorid(-2), distancefromcoordinator(-1), acceptpendingcnt(0), isnotjuststarted(false) { if(cfgptr->crtidx){ coordinatorId(0); }else{ coordinatorId(-1); } } Object::Data::~Data(){ } void Object::Data::coordinatorId(int8 _coordid){ coordinatorid = _coordid; if(_coordid != (int8)-1){ int8 maxsz(cfgptr->addrvec.size()); distancefromcoordinator = circular_distance(static_cast<int8>(cfgptr->crtidx), coordinatorid, maxsz); idbg("non-coordinator with distance from coordinator: "<<(int)distancefromcoordinator); }else{ distancefromcoordinator = -1; idbg("coordinator"); } } bool Object::Data::insertRequestStub(DynamicPointer<WriteRequestMessage> &_rmsgptr, size_t &_ridx){ RequestStubMapT::iterator it(reqmap.find(&_rmsgptr->consensusRequestId())); if(it != reqmap.end()){ _ridx = it->second; reqmap.erase(it); RequestStub &rreq(requestStub(_ridx)); if(rreq.flags & RequestStub::HaveRequestFlag){ edbg("conflict "<<_rmsgptr->consensusRequestId()<<" against existing "<<rreq.msgptr->consensusRequestId()<<" idx = "<<_ridx); } cassert(!(rreq.flags & RequestStub::HaveRequestFlag)); rreq.msgptr = _rmsgptr; reqmap[&rreq.msgptr->consensusRequestId()] = _ridx; return false; } if(freeposstk.size()){ _ridx = freeposstk.top(); freeposstk.pop(); RequestStub &rreq(requestStub(_ridx)); rreq.reinit(); rreq.msgptr = _rmsgptr; }else{ _ridx = reqvec.size(); reqvec.push_back(RequestStub(_rmsgptr)); } reqmap[&requestStub(_ridx).msgptr->consensusRequestId()] = _ridx; return true; } void Object::Data::eraseRequestStub(const size_t _idx){ RequestStub &rreq(requestStub(_idx)); //cassert(rreq.sig.get()); if(rreq.msgptr.get()){ reqmap.erase(&rreq.msgptr->consensusRequestId()); } rreq.msgptr.clear(); rreq.state(RequestStub::InitState); ++rreq.timerid; freeposstk.push(_idx); } inline RequestStub& Object::Data::requestStub(const size_t _idx){ cassert(_idx < reqvec.size()); return reqvec[_idx]; } inline const RequestStub& Object::Data::requestStub(const size_t _idx)const{ cassert(_idx < reqvec.size()); return reqvec[_idx]; } inline bool Object::Data::isCoordinator()const{ return coordinatorid == -1; } bool Object::Data::checkAlreadyReceived(DynamicPointer<WriteRequestMessage> &_rmsgptr){ SenderSetT::iterator it(senderset.find(_rmsgptr->consensusRequestId())); if(it != senderset.end()){ if(overflow_safe_less(_rmsgptr->consensusRequestId().requid, it->requid)){ return true; } senderset.erase(it); senderset.insert(_rmsgptr->consensusRequestId()); }else{ senderset.insert(_rmsgptr->consensusRequestId()); } return false; } bool Object::Data::canSendFastAccept()const{ TimeSpec ct(frame::Object::currentTime()); ct -= lastaccepttime; idbg("continuousacceptedproposes = "<<continuousacceptedproposes<<" ct.sec = "<<ct.seconds()); return (continuousacceptedproposes >= 5) && ct.seconds() < 60; } struct DummyWriteRequestMessage: public WriteRequestMessage{ DummyWriteRequestMessage(const consensus::RequestId &_reqid):WriteRequestMessage(_reqid){} /*virtual*/ void consensusNotifyServerWithThis(){} /*virtual*/ void consensusNotifyClientWithThis(){} /*virtual*/ void consensusNotifyClientWithFail(){} }; RequestStub& Object::Data::safeRequestStub(const consensus::RequestId &_reqid, size_t &_rreqidx){ RequestStubMapT::const_iterator it(reqmap.find(&_reqid)); if(it != reqmap.end()){ _rreqidx = it->second; }else{ DynamicPointer<WriteRequestMessage> reqsig(new DummyWriteRequestMessage(_reqid)); insertRequestStub(reqsig, _rreqidx); } return requestStub(_rreqidx); } RequestStub* Object::Data::requestStubPointer(const consensus::RequestId &_reqid, size_t &_rreqidx){ RequestStubMapT::const_iterator it(reqmap.find(&_reqid)); if(it != reqmap.end()){ _rreqidx = it->second; return &requestStub(it->second); }else{ return NULL; } } //======================================================== //Runntime data struct Object::RunData{ enum{ OperationCapacity = 32 }; struct OperationStub{ size_t reqidx; uint8 operation; uint32 proposeid; uint32 acceptid; }; RunData( ulong _sig, TimeSpec const &_rts, int8 _coordinatorid ):signals(_sig), rtimepos(_rts), coordinatorid(_coordinatorid), opcnt(0), crtacceptincrement(1){} bool isOperationsTableFull()const{ return opcnt == OperationCapacity; } bool isCoordinator()const{ return coordinatorid == -1; } ulong signals; TimeSpec const &rtimepos; int8 coordinatorid; size_t opcnt; size_t crtacceptincrement; OperationStub ops[OperationCapacity]; }; //======================================================== Object::DynamicMapperT Object::dm; /*static*/ void Object::dynamicRegister(){ dm.insert<WriteRequestMessage, Object>(); dm.insert<ReadRequestMessage, Object>(); dm.insert<OperationMessage<1>, Object>(); dm.insert<OperationMessage<2>, Object>(); dm.insert<OperationMessage<4>, Object>(); dm.insert<OperationMessage<8>, Object>(); dm.insert<OperationMessage<16>, Object>(); dm.insert<OperationMessage<32>, Object>(); //TODO: add here the other consensus Messages } /*static*/ void Object::registerMessages(frame::ipc::Service &_ripcsvc){ _ripcsvc.registerMessageType<OperationMessage<1> >(); _ripcsvc.registerMessageType<OperationMessage<2> >(); _ripcsvc.registerMessageType<OperationMessage<4> >(); _ripcsvc.registerMessageType<OperationMessage<8> >(); _ripcsvc.registerMessageType<OperationMessage<16> >(); _ripcsvc.registerMessageType<OperationMessage<32> >(); } Object::Object(DynamicPointer<Configuration> &_rcfgptr):d(*(new Data(_rcfgptr))){ idbg((void*)this); } //--------------------------------------------------------- Object::~Object(){ Registrar::the().unregisterObject(d.srvidx); delete &d; idbg((void*)this); } //--------------------------------------------------------- void Object::state(int _st){ d.state = _st; } //--------------------------------------------------------- int Object::state()const{ return d.state; } //--------------------------------------------------------- void Object::serverIndex(const frame::IndexT &_ridx){ d.srvidx = _ridx; } //--------------------------------------------------------- frame::IndexT Object::serverIndex()const{ return d.srvidx; } //--------------------------------------------------------- bool Object::isRecoveryState()const{ return state() >= PrepareRecoveryState && state() <= LastRecoveryState; } //--------------------------------------------------------- void Object::dynamicHandle(DynamicPointer<> &_dp, RunData &_rrd){ } //--------------------------------------------------------- void Object::dynamicHandle(DynamicPointer<WriteRequestMessage> &_rmsgptr, RunData &_rrd){ if(d.checkAlreadyReceived(_rmsgptr)) return; size_t idx; bool alreadyexisted(!d.insertRequestStub(_rmsgptr, idx)); RequestStub &rreq(d.requestStub(idx)); idbg("adding new request "<<rreq.msgptr->consensusRequestId()<<" on idx = "<<idx<<" existing = "<<alreadyexisted); rreq.flags |= RequestStub::HaveRequestFlag; if(!(rreq.evs & RequestStub::SignaledEvent)){ rreq.evs |= RequestStub::SignaledEvent; d.reqq.push(idx); } } void Object::dynamicHandle(DynamicPointer<ReadRequestMessage> &_rmsgptr, RunData &_rrd){ } void Object::dynamicHandle(DynamicPointer<OperationMessage<1> > &_rmsgptr, RunData &_rrd){ idbg("opcount = 1"); doExecuteOperation(_rrd, _rmsgptr->replicaidx, _rmsgptr->op); } void Object::dynamicHandle(DynamicPointer<OperationMessage<2> > &_rmsgptr, RunData &_rrd){ idbg("opcount = 2"); doExecuteOperation(_rrd, _rmsgptr->replicaidx, _rmsgptr->op[0]); doExecuteOperation(_rrd, _rmsgptr->replicaidx, _rmsgptr->op[1]); } void Object::dynamicHandle(DynamicPointer<OperationMessage<4> > &_rmsgptr, RunData &_rrd){ idbg("opcount = "<<_rmsgptr->opsz); for(size_t i(0); i < _rmsgptr->opsz; ++i){ doExecuteOperation(_rrd, _rmsgptr->replicaidx, _rmsgptr->op[i]); } } void Object::dynamicHandle(DynamicPointer<OperationMessage<8> > &_rmsgptr, RunData &_rrd){ idbg("opcount = "<<_rmsgptr->opsz); for(size_t i(0); i < _rmsgptr->opsz; ++i){ doExecuteOperation(_rrd, _rmsgptr->replicaidx, _rmsgptr->op[i]); } } void Object::dynamicHandle(DynamicPointer<OperationMessage<16> > &_rmsgptr, RunData &_rrd){ idbg("opcount = "<<_rmsgptr->opsz); for(size_t i(0); i < _rmsgptr->opsz; ++i){ doExecuteOperation(_rrd, _rmsgptr->replicaidx, _rmsgptr->op[i]); } } void Object::dynamicHandle(DynamicPointer<OperationMessage<32> > &_rmsgptr, RunData &_rrd){ idbg("opcount = "<<_rmsgptr->opsz); for(size_t i(0); i < _rmsgptr->opsz; ++i){ doExecuteOperation(_rrd, _rmsgptr->replicaidx, _rmsgptr->op[i]); } } void Object::doExecuteOperation(RunData &_rd, const uint8 _replicaidx, OperationStub &_rop){ switch(_rop.operation){ case Data::ProposeOperation: doExecuteProposeOperation(_rd, _replicaidx, _rop); break; case Data::ProposeConfirmOperation: doExecuteProposeConfirmOperation(_rd, _replicaidx, _rop); break; case Data::ProposeDeclineOperation: doExecuteProposeDeclineOperation(_rd, _replicaidx, _rop); break; case Data::AcceptOperation: doExecuteAcceptOperation(_rd, _replicaidx, _rop); break; case Data::FastAcceptOperation: doExecuteFastAcceptOperation(_rd, _replicaidx, _rop); break; case Data::AcceptConfirmOperation: doExecuteAcceptConfirmOperation(_rd, _replicaidx, _rop); break; case Data::AcceptDeclineOperation: doExecuteAcceptDeclineOperation(_rd, _replicaidx, _rop); break; default: THROW_EXCEPTION_EX("Unknown operation ", (int)_rop.operation); } } //on replica void Object::doExecuteProposeOperation(RunData &_rd, const uint8 _replicaidx, OperationStub &_rop){ idbg("op = ("<<(int)_rop.operation<<' '<<_rop.proposeid<<' '<<'('<<_rop.reqid<<')'<<" crtproposeid = "<<d.proposeid); if(!_rop.proposeid && d.proposeid/* && !isRecoveryState()*/){ idbg(""); doSendDeclinePropose(_rd, _replicaidx, _rop); return; } if(overflow_safe_less(_rop.proposeid, d.proposeid)/* && !isRecoveryState()*/){ idbg(""); //we cannot accept the propose doSendDeclinePropose(_rd, _replicaidx, _rop); return; } size_t reqidx; //we can accept the propose d.proposeid = _rop.proposeid; d.isnotjuststarted = true; RequestStub &rreq(d.safeRequestStub(_rop.reqid, reqidx)); if(!rreq.isValidProposeState() && !isRecoveryState()){ wdbg("Invalid state "<<rreq.state()<<" for reqidx "<<reqidx); return; } rreq.proposeid = d.proposeid; rreq.flags |= RequestStub::HaveProposeFlag; if(!(rreq.flags & RequestStub::HaveAcceptFlag)){ ++d.proposedacceptid; rreq.acceptid = d.proposedacceptid; } rreq.state(RequestStub::WaitAcceptState); ++rreq.timerid; TimeSpec ts(frame::Object::currentTime()); ts += 10 * 1000;//ms d.timerq.push(ts, TimerValue(reqidx, rreq.timerid)); doSendConfirmPropose(_rd, _replicaidx, reqidx); } //on coordinator void Object::doExecuteProposeConfirmOperation(RunData &_rd, const uint8 _replicaidx, OperationStub &_rop){ idbg("op = ("<<(int)_rop.operation<<' '<<_rop.proposeid<<' '<<'('<<_rop.reqid<<')'); if(isRecoveryState()){ idbg("Recovery state!!!"); return; } size_t reqidx; RequestStub *preq(d.requestStubPointer(_rop.reqid, reqidx)); if(!preq){ idbg("no such request"); return; } if(preq->proposeid != _rop.proposeid){ idbg("req->proposeid("<<preq->proposeid<<") != _rop.proposeid("<<_rop.proposeid<<")"); return; } if(!preq->isValidProposeConfirmState()){ wdbg("Invalid state "<<(int)preq->state()<<" for reqidx "<<reqidx); return; } cassert(preq->flags & RequestStub::HaveAcceptFlag); cassert(preq->flags & RequestStub::HaveProposeFlag); const uint32 tmpaccid = overflow_safe_max(preq->acceptid, _rop.acceptid); // if(_rop.acceptid != tmpaccid){ // idbg("ignore a propose confirm operation from an outdated replica "<<tmpaccid<<" > "<<_rop.acceptid); // return; // } preq->acceptid = tmpaccid; ++preq->recvpropconf; if(preq->recvpropconf == d.cfgptr->quorum){ ++d.continuousacceptedproposes; preq->state(RequestStub::WaitAcceptConfirmState); TimeSpec ts(frame::Object::currentTime()); ts += 60 * 1000;//ms ++preq->timerid; d.timerq.push(ts, TimerValue(reqidx, preq->timerid)); doSendAccept(_rd, reqidx); } } //on coordinator void Object::doExecuteProposeDeclineOperation(RunData &_rd, const uint8 _replicaidx, OperationStub &_rop){ idbg("op = ("<<(int)_rop.operation<<' '<<_rop.proposeid<<' '<<'('<<_rop.reqid<<')'); if(isRecoveryState()){ idbg("Recovery state!!!"); return; } size_t reqidx; RequestStub *preq(d.requestStubPointer(_rop.reqid, reqidx)); if(!preq){ idbg("no such request"); return; } if(!preq->isValidProposeDeclineState()){ wdbg("Invalid state "<<(int)preq->state()<<" for reqidx "<<reqidx); return; } if( preq->proposeid == 0 && preq->proposeid != _rop.proposeid && d.acceptid != _rop.acceptid ){ idbg("req->proposeid("<<preq->proposeid<<") != _rop.proposeid("<<_rop.proposeid<<")"); doEnterRecoveryState(); return; } ++preq->recvpropdecl; if(preq->recvpropdecl == d.cfgptr->quorum){ ++preq->timerid; preq->state(RequestStub::InitState); d.continuousacceptedproposes = 0; if(!(preq->evs & RequestStub::SignaledEvent)){ preq->evs |= RequestStub::SignaledEvent; d.reqq.push(reqidx); } } return; } //on replica void Object::doExecuteAcceptOperation(RunData &_rd, const uint8 _replicaidx, OperationStub &_rop){ idbg("op = ("<<(int)_rop.operation<<' '<<_rop.proposeid<<' '<<'('<<_rop.reqid<<')'); size_t reqidx; RequestStub *preq(d.requestStubPointer(_rop.reqid, reqidx)); if(!preq){ idbg("no such request"); if(!isRecoveryState()){ doSendDeclineAccept(_rd, _replicaidx, _rop); } return; } if(preq->proposeid != _rop.proposeid && !isRecoveryState()){ idbg("req->proposeid("<<preq->proposeid<<") != _rop.proposeid("<<_rop.proposeid<<")"); doSendDeclineAccept(_rd, _replicaidx, _rop); return; } if(!preq->isValidAcceptState() && !isRecoveryState()){ wdbg("Invalid state "<<(int)preq->state()<<" for reqidx "<<reqidx); return; } preq->acceptid = _rop.acceptid; preq->flags |= RequestStub::HaveAcceptFlag; preq->state(RequestStub::AcceptState); if(!(preq->evs & RequestStub::SignaledEvent)){ preq->evs |= RequestStub::SignaledEvent; d.reqq.push(reqidx); } doSendConfirmAccept(_rd, _replicaidx, reqidx); } //on replica void Object::doExecuteFastAcceptOperation(RunData &_rd, const uint8 _replicaidx, OperationStub &_rop){ idbg("op = ("<<(int)_rop.operation<<' '<<_rop.proposeid<<' '<<'('<<_rop.reqid<<')'); if(!isRecoveryState() && !overflow_safe_less(d.proposeid, _rop.proposeid)){ //we cannot accept the propose doSendDeclineAccept(_rd, _replicaidx, _rop); return; } size_t reqidx; //we can accept the propose d.proposeid = _rop.proposeid; RequestStub &rreq(d.safeRequestStub(_rop.reqid, reqidx)); if(!rreq.isValidFastAcceptState() && !isRecoveryState()){ wdbg("Invalid state "<<(int)rreq.state()<<" for reqidx "<<reqidx); return; } rreq.proposeid = _rop.proposeid; rreq.acceptid = _rop.acceptid; d.proposedacceptid = overflow_safe_max(d.proposedacceptid, _rop.acceptid); rreq.flags |= (RequestStub::HaveProposeFlag | RequestStub::HaveAcceptFlag); rreq.state(RequestStub::AcceptState); if(!(rreq.evs & RequestStub::SignaledEvent)){ rreq.evs |= RequestStub::SignaledEvent; d.reqq.push(reqidx); } doSendConfirmAccept(_rd, _replicaidx, reqidx); } //on coordinator void Object::doExecuteAcceptConfirmOperation(RunData &_rd, const uint8 _replicaidx, OperationStub &_rop){ idbg("op = ("<<(int)_rop.operation<<' '<<_rop.proposeid<<' '<<'('<<_rop.reqid<<')'); if(isRecoveryState()){ idbg("Recovery state!!!"); return; } size_t reqidx; RequestStub *preq(d.requestStubPointer(_rop.reqid, reqidx)); if(!preq){ idbg("no such request"); return; } if(preq->proposeid != _rop.proposeid || preq->acceptid != _rop.acceptid){ idbg("req->proposeid("<<preq->proposeid<<") != _rop.proposeid("<<_rop.proposeid<<")"); return; } if(preq->acceptid != _rop.acceptid){ idbg("req->acceptid("<<preq->acceptid<<") != _rop.acceptid("<<_rop.acceptid<<")"); return; } if(!preq->isValidAcceptConfirmState()){ wdbg("Invalid state "<<(int)preq->state()<<" for reqidx "<<reqidx); return; } preq->state(RequestStub::AcceptState); if(!(preq->evs & RequestStub::SignaledEvent)){ preq->evs |= RequestStub::SignaledEvent; d.reqq.push(reqidx); } } //on coordinator void Object::doExecuteAcceptDeclineOperation(RunData &_rd, const uint8 _replicaidx, OperationStub &_rop){ idbg("op = ("<<(int)_rop.operation<<' '<<_rop.proposeid<<' '<<'('<<_rop.reqid<<')'); if(isRecoveryState()){ idbg("Recovery state!!!"); return; } size_t reqidx; RequestStub *preq(d.requestStubPointer(_rop.reqid, reqidx)); if(!preq){ idbg("no such request"); return; } if(preq->proposeid != _rop.proposeid || preq->acceptid != _rop.acceptid){ idbg("req->proposeid("<<preq->proposeid<<") != _rop.proposeid("<<_rop.proposeid<<")"); return; } if(preq->acceptid != _rop.acceptid){ idbg("req->acceptid("<<preq->acceptid<<") != _rop.acceptid("<<_rop.acceptid<<")"); return; } if(!preq->isValidAcceptConfirmState()){ wdbg("Invalid state "<<preq->state()<<" for reqidx "<<reqidx); return; } //do nothing for now return; } //--------------------------------------------------------- /*virtual*/ bool Object::notify(DynamicPointer<frame::Message> &_rmsgptr){ if(this->state() < 0){ _rmsgptr.clear(); return false;//no reason to raise the pool thread!! } DynamicPointer<> dp(_rmsgptr); d.dv.push_back(dp); return frame::Object::notify(frame::S_SIG | frame::S_RAISE); } //--------------------------------------------------------- /*virtual*/ void Object::init(){ } //--------------------------------------------------------- /*virtual*/ void Object::prepareRun(){ } //--------------------------------------------------------- /*virtual*/ void Object::prepareRecovery(){ } //--------------------------------------------------------- /*virtual*/ void Object::execute(ExecuteContext &_rexectx){ frame::Manager &rm(frame::Manager::specific()); RunData rd(_rexectx.eventMask(), _rexectx.currentTime(), d.coordinatorid); if(notified()){//we've received a signal ulong sm(0); DynamicHandler<DynamicMapperT> dh(dm); if(state() != InitState && state() != PrepareRunState && state() != PrepareRecoveryState){ Locker<Mutex> lock(rm.mutex(*this)); sm = grabSignalMask(0);//grab all bits of the signal mask if(sm & frame::S_KILL){ _rexectx.close(); return; } if(sm & frame::S_SIG){//we have signals dh.init(d.dv.begin(), d.dv.end()); d.dv.clear(); } } if(sm & frame::S_SIG){//we've grabed signals, execute them for(size_t i = 0; i < dh.size(); ++i){ dh.handle(*this, i, rd); } } } AsyncE rv; switch(state()){ case InitState: rv = doInit(rd); break; case PrepareRunState: rv = doPrepareRun(rd); break; case RunState: rv = doRun(rd); break; case PrepareRecoveryState: rv = doPrepareRecovery(rd); break; default: if(state() >= FirstRecoveryState && state() <= LastRecoveryState){ rv = doRecovery(rd); } break; } if(rv == AsyncSuccess){ _rexectx.reschedule(); }else if(rv == AsyncError){ _rexectx.close(); }else if(d.timerq.size()){ if(d.timerq.isHit(_rexectx.currentTime())){ _rexectx.reschedule(); return; } _rexectx.waitUntil(d.timerq.frontTime()); } } //--------------------------------------------------------- bool Object::isCoordinator()const{ return d.isCoordinator(); } uint32 Object::acceptId()const{ return d.acceptid; } uint32 Object::proposeId()const{ return d.proposeid; } //--------------------------------------------------------- AsyncE Object::doInit(RunData &_rd){ this->init(); state(PrepareRunState); return AsyncSuccess; } //--------------------------------------------------------- AsyncE Object::doPrepareRun(RunData &_rd){ this->prepareRun(); state(RunState); return AsyncSuccess; } //--------------------------------------------------------- AsyncE Object::doRun(RunData &_rd){ idbg(""); //first we scan for timeout: while(d.timerq.isHit(_rd.rtimepos)){ RequestStub &rreq(d.requestStub(d.timerq.frontValue().index)); if(rreq.timerid == d.timerq.frontValue().uid){ rreq.evs |= RequestStub::TimeoutEvent; if(!(rreq.evs & RequestStub::SignaledEvent)){ rreq.evs |= RequestStub::SignaledEvent; d.reqq.push(d.timerq.frontValue().index); } } d.timerq.pop(); } //next we process all requests size_t cnt(d.reqq.size()); while(cnt--){ size_t pos(d.reqq.front()); d.reqq.pop(); doProcessRequest(_rd, pos); } doFlushOperations(_rd); if(d.reqq.size()) return AsyncSuccess; return AsyncWait; } //--------------------------------------------------------- AsyncE Object::doPrepareRecovery(RunData &_rd){ //erase all requests in erase state for(RequestStubVectorT::const_iterator it(d.reqvec.begin()); it != d.reqvec.end(); ++it){ const RequestStub &rreq(*it); if(rreq.state() == RequestStub::EraseState){ d.eraseRequestStub(it - d.reqvec.begin()); } } prepareRecovery(); state(FirstRecoveryState); return AsyncSuccess; } //--------------------------------------------------------- AsyncE Object::doRecovery(RunData &_rd){ idbg(""); return recovery(); } //--------------------------------------------------------- void Object::doProcessRequest(RunData &_rd, const size_t _reqidx){ RequestStub &rreq(d.requestStub(_reqidx)); uint32 events = rreq.evs; rreq.evs = 0; switch(rreq.state()){ case RequestStub::InitState://any if(d.isCoordinator()){ if(d.canSendFastAccept()){ idbg("InitState coordinator - send fast accept for "<<rreq.msgptr->consensusRequestId()); doSendFastAccept(_rd, _reqidx); rreq.state(RequestStub::WaitAcceptConfirmState); }else{ idbg("InitState coordinator - send propose for "<<rreq.msgptr->consensusRequestId()); doSendPropose(_rd, _reqidx); rreq.state(RequestStub::WaitProposeConfirmState); TimeSpec ts(frame::Object::currentTime()); ts += 60 * 1000;//ms d.timerq.push(ts, TimerValue(_reqidx, rreq.timerid)); rreq.recvpropconf = 1;//one is the propose_accept from current coordinator } }else{ idbg("InitState non-coordinator - wait propose/accept for "<<rreq.msgptr->consensusRequestId()) rreq.state(RequestStub::WaitProposeState); TimeSpec ts(frame::Object::currentTime()); ts += d.distancefromcoordinator * 1000;//ms d.timerq.push(ts, TimerValue(_reqidx, rreq.timerid)); } break; case RequestStub::WaitProposeState://on replica idbg("WaitProposeState for "<<rreq.msgptr->consensusRequestId()); if(events & RequestStub::TimeoutEvent){ idbg("WaitProposeState - timeout for "<<rreq.msgptr->consensusRequestId()); doSendPropose(_rd, _reqidx); rreq.state(RequestStub::WaitProposeConfirmState); TimeSpec ts(frame::Object::currentTime()); ts += 60 * 1000;//ms d.timerq.push(ts, TimerValue(_reqidx, rreq.timerid)); rreq.recvpropconf = 1;//one is the propose_accept from current coordinator break; } break; case RequestStub::WaitProposeConfirmState://on coordinator idbg("WaitProposeAcceptState for "<<rreq.msgptr->consensusRequestId()); if(events & RequestStub::TimeoutEvent){ idbg("WaitProposeAcceptState - timeout: erase request "<<rreq.msgptr->consensusRequestId()); doEraseRequest(_rd, _reqidx); break; } break; case RequestStub::WaitAcceptState://on replica if(events & RequestStub::TimeoutEvent){ idbg("WaitAcceptState - timeout "<<rreq.msgptr->consensusRequestId()); rreq.state(RequestStub::WaitProposeState); TimeSpec ts(frame::Object::currentTime()); ts += d.distancefromcoordinator * 1000;//ms ++rreq.timerid; d.timerq.push(ts, TimerValue(_reqidx, rreq.timerid)); break; } break; case RequestStub::WaitAcceptConfirmState://on coordinator idbg("WaitProposeAcceptConfirmState "<<rreq.msgptr->consensusRequestId()); if(events & RequestStub::TimeoutEvent){ idbg("WaitProposeAcceptConfirmState - timeout: erase request "<<rreq.msgptr->consensusRequestId()); doEraseRequest(_rd, _reqidx); break; } break; case RequestStub::AcceptWaitRequestState://any idbg("AcceptWaitRequestState "<<rreq.msgptr->consensusRequestId()); if(events & RequestStub::TimeoutEvent){ idbg("AcceptWaitRequestState - timeout: enter recovery state "<<rreq.msgptr->consensusRequestId()); doEnterRecoveryState(); break; } if(!(rreq.flags & RequestStub::HaveRequestFlag)){ break; } case RequestStub::AcceptState://any idbg("AcceptState "<<_reqidx<<" "<<rreq.msgptr->consensusRequestId()<<" rreq.acceptid = "<<rreq.acceptid<<" d.acceptid = "<<d.acceptid<<" acceptpendingcnt = "<<(int)d.acceptpendingcnt); ++rreq.timerid; //for recovery reasons, we do this check before //haverequestflag check if(overflow_safe_less(rreq.acceptid, d.acceptid + 1)){ doEraseRequest(_rd, _reqidx); break; } if(!(rreq.flags & RequestStub::HaveRequestFlag)){ idbg("norequestflag "<<_reqidx<<" acceptpendingcnt "<<(int)d.acceptpendingcnt); rreq.state(RequestStub::AcceptWaitRequestState); TimeSpec ts(frame::Object::currentTime()); ts.add(60);//60 secs d.timerq.push(ts, TimerValue(_reqidx, rreq.timerid)); if(d.acceptpendingcnt < 255){ ++d.acceptpendingcnt; } break; } if(d.acceptid + _rd.crtacceptincrement != rreq.acceptid){ idbg("enterpending "<<_reqidx); rreq.state(RequestStub::AcceptPendingState); if(d.acceptpendingcnt < 255){ ++d.acceptpendingcnt; } if(d.acceptpendingcnt == 1){ cassert(d.pendingacceptwaitidx == -1); d.pendingacceptwaitidx = _reqidx; TimeSpec ts(frame::Object::currentTime()); ts.add(2*60);//2 mins d.timerq.push(ts, TimerValue(_reqidx, rreq.timerid)); if(d.acceptpendingcnt < 255){ ++d.acceptpendingcnt; } } break; } d.lastaccepttime = frame::Object::currentTime(); ++_rd.crtacceptincrement; //we cannot do erase or Accept here, we must wait for the //send operations to be flushed away rreq.state(RequestStub::AcceptRunState); if(!(rreq.evs & RequestStub::SignaledEvent)){ rreq.evs |= RequestStub::SignaledEvent; d.reqq.push(_reqidx); } break; case RequestStub::AcceptPendingState: idbg("AcceptPendingState "<<rreq.msgptr->consensusRequestId()); if(events & RequestStub::TimeoutEvent){ idbg("AcceptPendingState - timeout: enter recovery state "<<rreq.msgptr->consensusRequestId()); doEnterRecoveryState(); break; } //the status is changed within doScanPendingRequests break; case RequestStub::AcceptRunState: doAcceptRequest(_rd, _reqidx); if(d.acceptpendingcnt){ if(d.pendingacceptwaitidx == _reqidx){ d.pendingacceptwaitidx = -1; } doScanPendingRequests(_rd); } case RequestStub::EraseState: doEraseRequest(_rd, _reqidx); break; default: THROW_EXCEPTION_EX("Unknown state ",rreq.state()); } } void Object::doSendAccept(RunData &_rd, const size_t _reqidx){ if(isRecoveryState()){ idbg("recovery state: no sends"); return; } if(!_rd.isCoordinator()){ idbg(""); doFlushOperations(_rd); _rd.coordinatorid = -1; } d.coordinatorId(-1); RequestStub &rreq(d.requestStub(_reqidx)); idbg(""<<_reqidx<<" rreq.proposeid = "<<rreq.proposeid<<" rreq.acceptid = "<<rreq.acceptid<<" "<<rreq.msgptr->consensusRequestId()); _rd.ops[_rd.opcnt].operation = Data::AcceptOperation; _rd.ops[_rd.opcnt].acceptid = rreq.acceptid; _rd.ops[_rd.opcnt].proposeid = rreq.proposeid; _rd.ops[_rd.opcnt].reqidx = _reqidx; ++_rd.opcnt; if(_rd.isOperationsTableFull()){ idbg(""); doFlushOperations(_rd); } } void Object::doSendFastAccept(RunData &_rd, const size_t _reqidx){ if(isRecoveryState()){ idbg("recovery state: no sends"); return; } if(!_rd.isCoordinator()){ doFlushOperations(_rd); _rd.coordinatorid = -1; } RequestStub &rreq(d.requestStub(_reqidx)); ++d.proposeid; if(!d.proposeid) d.proposeid = 1; ++d.proposedacceptid; rreq.acceptid = d.proposedacceptid; rreq.proposeid = d.proposeid; rreq.flags |= (RequestStub::HaveProposeFlag | RequestStub::HaveAcceptFlag); idbg(""<<_reqidx<<" rreq.proposeid = "<<rreq.proposeid<<" rreq.acceptid = "<<rreq.acceptid<<" "<<rreq.msgptr->consensusRequestId()); _rd.ops[_rd.opcnt].operation = Data::FastAcceptOperation; _rd.ops[_rd.opcnt].acceptid = rreq.acceptid; _rd.ops[_rd.opcnt].proposeid = rreq.proposeid; _rd.ops[_rd.opcnt].reqidx = _reqidx; ++_rd.opcnt; if(_rd.isOperationsTableFull()){ doFlushOperations(_rd); } } void Object::doSendPropose(RunData &_rd, const size_t _reqidx){ idbg(""<<_reqidx); if(isRecoveryState()){ idbg("recovery state: no sends"); return; } if(!_rd.isCoordinator()){ doFlushOperations(_rd); _rd.coordinatorid = -1; } RequestStub &rreq(d.requestStub(_reqidx)); if(d.isnotjuststarted){ ++d.proposeid; if(!d.proposeid) d.proposeid = 1; }else{ d.isnotjuststarted = true; } ++d.proposedacceptid; rreq.acceptid = d.proposedacceptid; rreq.proposeid = d.proposeid; rreq.flags |= (RequestStub::HaveProposeFlag | RequestStub::HaveAcceptFlag); idbg("sendpropose: proposeid = "<<rreq.proposeid<<" acceptid = "<<rreq.acceptid<<" "<<rreq.msgptr->consensusRequestId()); _rd.ops[_rd.opcnt].operation = Data::ProposeOperation; _rd.ops[_rd.opcnt].acceptid = rreq.acceptid; _rd.ops[_rd.opcnt].proposeid = rreq.proposeid; _rd.ops[_rd.opcnt].reqidx = _reqidx; ++_rd.opcnt; if(_rd.isOperationsTableFull()){ doFlushOperations(_rd); } } void Object::doSendConfirmPropose(RunData &_rd, const uint8 _replicaidx, const size_t _reqidx){ if(isRecoveryState()){ idbg("recovery state: no sends"); return; } if(_rd.coordinatorid != _replicaidx){ doFlushOperations(_rd); _rd.coordinatorid = _replicaidx; } RequestStub &rreq(d.requestStub(_reqidx)); idbg(""<<_reqidx<<" "<<(int)_replicaidx<<" "<<rreq.msgptr->consensusRequestId()); //rreq.state = _rd.ops[_rd.opcnt].operation = Data::ProposeConfirmOperation; _rd.ops[_rd.opcnt].acceptid = rreq.acceptid; _rd.ops[_rd.opcnt].proposeid = rreq.proposeid; _rd.ops[_rd.opcnt].reqidx = _reqidx; ++_rd.opcnt; if(_rd.isOperationsTableFull()){ doFlushOperations(_rd); } } void Object::doSendDeclinePropose(RunData &_rd, const uint8 _replicaidx, const OperationStub &_rop){ idbg(""<<(int)_replicaidx<<" "<<_rop.reqid); if(isRecoveryState()){ idbg("recovery state: no sends"); return; } OperationMessage<1> *po(new OperationMessage<1>); po->replicaidx = d.cfgptr->crtidx; po->srvidx = serverIndex(); po->op.operation = Data::ProposeDeclineOperation; po->op.proposeid = d.proposeid; po->op.acceptid = d.acceptid; po->op.reqid = _rop.reqid; DynamicPointer<frame::ipc::Message> msgptr(po); this->doSendMessage(msgptr, d.cfgptr->addrvec[_replicaidx]); } void Object::doSendConfirmAccept(RunData &_rd, const uint8 _replicaidx, const size_t _reqidx){ if(isRecoveryState()){ idbg("recovery state: no sends"); return; } if(_rd.coordinatorid != _replicaidx){ doFlushOperations(_rd); _rd.coordinatorid = _replicaidx; } d.coordinatorId(_replicaidx); RequestStub &rreq(d.requestStub(_reqidx)); idbg(""<<(int)_replicaidx<<" "<<_reqidx<<" "<<rreq.msgptr->consensusRequestId()); _rd.ops[_rd.opcnt].operation = Data::AcceptConfirmOperation; _rd.ops[_rd.opcnt].acceptid = rreq.acceptid; _rd.ops[_rd.opcnt].proposeid = rreq.proposeid; _rd.ops[_rd.opcnt].reqidx = _reqidx; ++_rd.opcnt; if(_rd.isOperationsTableFull()){ doFlushOperations(_rd); } } void Object::doSendDeclineAccept(RunData &_rd, const uint8 _replicaidx, const OperationStub &_rop){ idbg(""<<(int)_replicaidx<<" "<<_rop.reqid); if(isRecoveryState()){ idbg("recovery state: no sends"); return; } OperationMessage<1> *po(new OperationMessage<1>); po->replicaidx = d.cfgptr->crtidx; po->srvidx = serverIndex(); po->op.operation = Data::AcceptDeclineOperation; po->op.proposeid = d.proposeid; po->op.acceptid = d.acceptid; po->op.reqid = _rop.reqid; DynamicPointer<frame::ipc::Message> msgptr(po); this->doSendMessage(msgptr, d.cfgptr->addrvec[_replicaidx]); } void Object::doFlushOperations(RunData &_rd){ idbg(""); Message *pm(NULL); OperationStub *pos(NULL); const size_t opcnt = _rd.opcnt; _rd.opcnt = 0; if(opcnt == 0){ return; }else if(opcnt == 1){ OperationMessage<1> *po(new OperationMessage<1>); RequestStub &rreq(d.requestStub(_rd.ops[0].reqidx)); pm = po; po->replicaidx = d.cfgptr->crtidx; po->srvidx = serverIndex(); po->op.operation = _rd.ops[0].operation; po->op.acceptid = _rd.ops[0].acceptid; po->op.proposeid = _rd.ops[0].proposeid; po->op.reqid = rreq.msgptr->consensusRequestId(); }else if(opcnt == 2){ OperationMessage<2> *po(new OperationMessage<2>); pm = po; po->replicaidx = d.cfgptr->crtidx; po->srvidx = serverIndex(); pos = po->op; }else if(opcnt <= 4){ OperationMessage<4> *po(new OperationMessage<4>); pm = po; po->replicaidx = d.cfgptr->crtidx; po->srvidx = serverIndex(); po->opsz = opcnt; pos = po->op; }else if(opcnt <= 8){ OperationMessage<8> *po(new OperationMessage<8>); pm = po; po->replicaidx = d.cfgptr->crtidx; po->srvidx = serverIndex(); po->opsz = opcnt; pos = po->op; }else if(opcnt <= 16){ OperationMessage<16> *po(new OperationMessage<16>); pm = po; po->replicaidx = d.cfgptr->crtidx; po->srvidx = serverIndex(); po->opsz = opcnt; pos = po->op; }else if(opcnt <= 32){ OperationMessage<32> *po(new OperationMessage<32>); pm = po; po->replicaidx = d.cfgptr->crtidx; po->srvidx = serverIndex(); po->opsz = opcnt; pos = po->op; }else{ THROW_EXCEPTION_EX("invalid opcnt ",opcnt); } if(pos){ for(size_t i(0); i < opcnt; ++i){ RequestStub &rreq(d.requestStub(_rd.ops[i].reqidx)); //po->oparr.push_back(OperationStub()); pos[i].operation = _rd.ops[i].operation; pos[i].acceptid = _rd.ops[i].acceptid; pos[i].proposeid = _rd.ops[i].proposeid; pos[i].reqid = rreq.msgptr->consensusRequestId(); idbg("pos["<<i<<"].operation = "<<(int)pos[i].operation<<" proposeid = "<<pos[i].proposeid); } } if(_rd.isCoordinator()){ DynamicSharedPointer<Message> sharedmsgptr(pm); idbg("broadcast to other replicas"); //broadcast to replicas for(uint i(0); i < d.cfgptr->addrvec.size(); ++i){ if(i != d.cfgptr->crtidx){ DynamicPointer<frame::ipc::Message> msgptr(sharedmsgptr); this->doSendMessage(msgptr, d.cfgptr->addrvec[i]); } } }else{ idbg("send to "<<(int)_rd.coordinatorid); DynamicPointer<frame::ipc::Message> msgptr(pm); this->doSendMessage(msgptr, d.cfgptr->addrvec[_rd.coordinatorid]); } } /* Scans all the requests for acceptpending requests, and pushes em onto d.reqq */ struct RequestStubAcceptCmp{ const RequestStubVectorT &rreqvec; RequestStubAcceptCmp(const RequestStubVectorT &_rreqvec):rreqvec(_rreqvec){} bool operator()(const size_t &_ridx1, const size_t &_ridx2)const{ return overflow_safe_less(rreqvec[_ridx1].acceptid, rreqvec[_ridx2].acceptid); } }; void Object::doScanPendingRequests(RunData &_rd){ idbg(""<<(int)d.acceptpendingcnt); const size_t accpendcnt = d.acceptpendingcnt; size_t cnt(0); d.acceptpendingcnt = 0; if(accpendcnt != 255){ size_t posarr[256]; size_t idx(0); for(RequestStubVectorT::const_iterator it(d.reqvec.begin()); it != d.reqvec.end(); ++it){ const RequestStub &rreq(*it); if( rreq.state() == RequestStub::AcceptPendingState ){ posarr[idx] = it - d.reqvec.begin(); ++idx; }else if(rreq.state() == RequestStub::AcceptWaitRequestState){ ++cnt; } } RequestStubAcceptCmp cmp(d.reqvec); std::sort(posarr, posarr + idx, cmp); uint32 crtacceptid(d.acceptid); for(size_t i(0); i < idx; ++i){ RequestStub &rreq(d.reqvec[posarr[i]]); ++crtacceptid; if(crtacceptid == rreq.acceptid){ if(!(rreq.evs & RequestStub::SignaledEvent)){ rreq.evs |= RequestStub::SignaledEvent; d.reqq.push(posarr[i]); } rreq.state(RequestStub::AcceptState); if(d.pendingacceptwaitidx == posarr[i]){ d.pendingacceptwaitidx = -1; } }else{ const size_t tmp = cnt + idx - i; d.acceptpendingcnt = tmp <= 255 ? tmp : 255; if(tmp != cnt && d.pendingacceptwaitidx == -1){ //we have at least one pending request wich is not in waitrequest state RequestStub &rreq(d.requestStub(posarr[i])); TimeSpec ts(frame::Object::currentTime()); ts.add(2*60);//2 mins d.timerq.push(ts, TimerValue(posarr[i], rreq.timerid)); d.pendingacceptwaitidx = posarr[i]; } break; } } idbg("d.acceptpendingcnt = "<<(int)d.acceptpendingcnt<<" d.pendingacceptwaitidx = "<<d.pendingacceptwaitidx); }else{ std::deque<size_t> posvec; for(RequestStubVectorT::const_iterator it(d.reqvec.begin()); it != d.reqvec.end(); ++it){ const RequestStub &rreq(*it); if(rreq.state() == RequestStub::AcceptPendingState){ posvec.push_back(it - d.reqvec.begin()); }else if(rreq.state() == RequestStub::AcceptWaitRequestState){ ++cnt; } } RequestStubAcceptCmp cmp(d.reqvec); std::sort(posvec.begin(), posvec.end(), cmp); uint32 crtacceptid(d.acceptid); for(std::deque<size_t>::const_iterator it(posvec.begin()); it != posvec.end(); ++it){ RequestStub &rreq(d.reqvec[*it]); ++crtacceptid; if(crtacceptid == rreq.acceptid){ if(!(rreq.evs & RequestStub::SignaledEvent)){ rreq.evs |= RequestStub::SignaledEvent; d.reqq.push(*it); } if(d.pendingacceptwaitidx == *it){ d.pendingacceptwaitidx = -1; } rreq.state(RequestStub::AcceptState); }else{ size_t sz(it - posvec.begin()); size_t tmp = cnt + posvec.size() - sz; d.acceptpendingcnt = tmp <= 255 ? tmp : 255;; if(tmp != cnt && d.pendingacceptwaitidx == -1){ //we have at least one pending request wich is not in waitrequest state RequestStub &rreq(d.requestStub(*it)); TimeSpec ts(frame::Object::currentTime()); ts.add(2*60);//2 mins d.timerq.push(ts, TimerValue(*it, rreq.timerid)); d.pendingacceptwaitidx = *it; } break; } } } } void Object::doAcceptRequest(RunData &_rd, const size_t _reqidx){ idbg(""<<_reqidx); RequestStub &rreq(d.requestStub(_reqidx)); cassert(rreq.flags & RequestStub::HaveRequestFlag); cassert(rreq.acceptid == d.acceptid + 1); ++d.acceptid; d.reqmap.erase(&rreq.msgptr->consensusRequestId()); this->accept(rreq.msgptr); rreq.msgptr.clear(); rreq.flags &= (~RequestStub::HaveRequestFlag); } void Object::doEraseRequest(RunData &_rd, const size_t _reqidx){ idbg(""<<_reqidx); if(d.pendingacceptwaitidx == _reqidx){ d.pendingacceptwaitidx = -1; } d.eraseRequestStub(_reqidx); } void Object::doStartCoordinate(RunData &_rd, const size_t _reqidx){ idbg(""<<_reqidx); } void Object::doEnterRecoveryState(){ idbg("ENTER RECOVERY STATE"); state(PrepareRecoveryState); } void Object::enterRunState(){ idbg(""); state(PrepareRunState); } //======================================================== }//namespace server }//namespace consensus }//namespace distributed
29.612058
188
0.682681
joydit
906e1cfa9e83c695cee152ea62736128521e988b
1,632
hpp
C++
include/GlobalNamespace/IMultiplayerRichPresenceData.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/IMultiplayerRichPresenceData.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/IMultiplayerRichPresenceData.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes // Including type: IRichPresenceData #include "GlobalNamespace/IRichPresenceData.hpp" // Completed includes // Begin il2cpp-utils forward declares struct Il2CppString; // Completed il2cpp-utils forward declares // Type namespace: namespace GlobalNamespace { // Size: 0x0 #pragma pack(push, 1) // Autogenerated type: IMultiplayerRichPresenceData class IMultiplayerRichPresenceData/*, public GlobalNamespace::IRichPresenceData*/ { public: // Creating value type constructor for type: IMultiplayerRichPresenceData IMultiplayerRichPresenceData() noexcept {} // Creating interface conversion operator: operator GlobalNamespace::IRichPresenceData operator GlobalNamespace::IRichPresenceData() noexcept { return *reinterpret_cast<GlobalNamespace::IRichPresenceData*>(this); } // public System.String get_multiplayerLobbyCode() // Offset: 0xFFFFFFFF ::Il2CppString* get_multiplayerLobbyCode(); // public System.Void set_multiplayerLobbyCode(System.String value) // Offset: 0xFFFFFFFF void set_multiplayerLobbyCode(::Il2CppString* value); // public System.Boolean get_isJoinable() // Offset: 0xFFFFFFFF bool get_isJoinable(); }; // IMultiplayerRichPresenceData #pragma pack(pop) } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::IMultiplayerRichPresenceData*, "", "IMultiplayerRichPresenceData");
41.846154
108
0.718137
darknight1050
906e2d942116c7f284b401c3a8afdab5b092e0ae
1,345
hpp
C++
impl/jamtemplate/common/camera.hpp
Thunraz/JamTemplateCpp
ee516d8a57dcfa6e7997585ab9bd7ff7df3640ea
[ "CC0-1.0" ]
null
null
null
impl/jamtemplate/common/camera.hpp
Thunraz/JamTemplateCpp
ee516d8a57dcfa6e7997585ab9bd7ff7df3640ea
[ "CC0-1.0" ]
null
null
null
impl/jamtemplate/common/camera.hpp
Thunraz/JamTemplateCpp
ee516d8a57dcfa6e7997585ab9bd7ff7df3640ea
[ "CC0-1.0" ]
null
null
null
#ifndef GUARD_JAMTEMPLATE_CAMERA_HPP_GUARD #define GUARD_JAMTEMPLATE_CAMERA_HPP_GUARD #include "cam_interface.hpp" #include <functional> namespace jt { class Camera : public CamInterface { public: /// Constructor explicit Camera(float zoom = 1.0f); jt::Vector2 getCamOffset() override; void setCamOffset(jt::Vector2 const& ofs) override; void move(jt::Vector2 const& v) override; float getZoom() const override; void setZoom(float zoom) override; void shake(float t, float strength, float shakeInterval = 0.005f) override; jt::Vector2 getShakeOffset() override; void reset() override; void update(float elapsed) override; /// Set random function that will be used to determine the cam displacement /// \param randomFunction the random function void setRandomFunction(std::function<float(float)> randomFunction); private: jt::Vector2 m_CamOffset { 0.0f, 0.0f }; float m_zoom { 1.0f }; float m_shakeTimer { -1.0f }; float m_shakeStrength { 0.0f }; float m_shakeInterval { 0.0f }; float m_shakeIntervalMax { 0.0f }; jt::Vector2 m_shakeOffset { 0, 0 }; std::function<float(float)> m_randomFunc = nullptr; virtual void updateShake(float elapsed); virtual void resetShake(); void setDefaultRandomFunction(); }; } // namespace jt #endif
26.372549
79
0.704833
Thunraz
90753cdc2933595a3400c49ac5ef9b130ffd0061
4,593
cpp
C++
2019/cpp/day_3.cpp
rmottus/advent-of-code
6b803ed61867125375028ce8943c919b1d8ae365
[ "MIT" ]
null
null
null
2019/cpp/day_3.cpp
rmottus/advent-of-code
6b803ed61867125375028ce8943c919b1d8ae365
[ "MIT" ]
null
null
null
2019/cpp/day_3.cpp
rmottus/advent-of-code
6b803ed61867125375028ce8943c919b1d8ae365
[ "MIT" ]
null
null
null
#include <vector> #include <utility> #include <iostream> #include <sstream> #include <climits> using namespace std; typedef pair<int, int> intpair; // This is using a much better algorithm that I did used in python // Instead of creating an array tracking each point each wire covers, then looping over these for both wires to find cross points, // we just track the endpoints of each movement of each wire, then calculate intersection points between them vector<string> tokenize(const string &str) { vector<string> tokens; stringstream splitter(str); string token; while(getline(splitter, token, ',')) { tokens.push_back(token); } return tokens; } vector<intpair> create_wire_points(const vector<string> &path) { vector<intpair> wire = { {0, 0} }; int x = 0, y = 0; for (auto s: path) { char dir = s[0]; int dist = stoi((char *)&s[1]); switch(dir) { case 'U': y += dist; wire.push_back({ x, y }); break; case 'D': y -= dist; wire.push_back({ x, y }); break; case 'L': x -= dist; wire.push_back({ x, y }); break; case 'R': x += dist; wire.push_back({ x, y }); break; default: throw "Unkown direction"; } } return wire; } bool is_between(const int &i, const int &j, const int &k) { if (i <= j) { return i <= k && k <= j; } return j <= k && k <= i; } vector<intpair> find_cp(const vector<intpair> &first_wire, const vector<intpair> &second_wire) { vector<intpair> result; int a_dist = 0; for (int i = 0; i < first_wire.size() - 1; i++) { intpair a_first_point = first_wire[i], a_second_point = first_wire[i+1]; int a_x_1 = a_first_point.first, a_y_1 = a_first_point.second; int a_x_2 = a_second_point.first, a_y_2 = a_second_point.second; bool a_vert = a_x_1 == a_x_2; int b_dist = 0; for (int j = 0; j < second_wire.size() - 1; j++) { intpair b_first_point = second_wire[j], b_second_point = second_wire[j+1]; int b_x_1 = b_first_point.first, b_y_1 = b_first_point.second; int b_x_2 = b_second_point.first, b_y_2 = b_second_point.second; bool b_vert = b_x_1 == b_x_2; if (a_vert != b_vert) { if (a_vert) { // intpair cp = { a_x_1, b_y_1 }; if (is_between(b_x_1, b_x_2, a_x_1) && is_between(a_y_1, a_y_2, b_y_1)) { result.push_back({ abs(a_x_1) + abs(b_y_1), a_dist + abs(a_y_1 - b_y_1) + b_dist + abs(b_x_1 - a_x_1) }); } } else { // intpair cp = { b_x_1, a_y_1 }; if (is_between(a_x_1, a_x_2, b_x_1) && is_between(b_y_1, b_y_2, a_y_1)) { result.push_back({ abs(b_x_1) + abs(a_y_1), a_dist + abs(a_x_1 - b_x_1) + b_dist + abs(b_y_1 - a_y_1) }); } } } b_dist += (b_vert ? abs(b_y_1 - b_y_2) : abs(b_x_1 - b_x_2)); } a_dist += (a_vert ? abs(a_y_1 - a_y_2) : abs(a_x_1 - a_x_2)); } return result; } int main() { string first_line, second_line; getline(cin, first_line); getline(cin, second_line); auto first_path = tokenize(first_line); auto second_path = tokenize(second_line); auto first_wire = create_wire_points(first_path); auto second_wire = create_wire_points(second_path); std::cout << first_wire.size() << " " << second_wire.size() << endl; auto crosspoints = find_cp(first_wire, second_wire); int man_min = INT_MAX; int len_min = INT_MAX; for (auto cp: crosspoints) { int man_dist = cp.first; if (man_dist < man_min) { man_min = man_dist; } int len_dist = cp.second; if (len_dist < len_min) { len_min = len_dist; } } std::cout << "The nearest cross intpair by Manhatten distance is this far away: " << man_min << endl; std::cout << "The nearest cross intpair by wire length is this far away: " << len_min << endl; }
31.033784
131
0.515567
rmottus
9076137103080706ca67045aa9119ec3eeb43666
4,669
cpp
C++
OgreMain/src/Compositor/Pass/OgreCompositorPassDef.cpp
jondo2010/ogre
c1e836d453b2bca0d4e2eb6a32424fe967092b52
[ "MIT" ]
null
null
null
OgreMain/src/Compositor/Pass/OgreCompositorPassDef.cpp
jondo2010/ogre
c1e836d453b2bca0d4e2eb6a32424fe967092b52
[ "MIT" ]
null
null
null
OgreMain/src/Compositor/Pass/OgreCompositorPassDef.cpp
jondo2010/ogre
c1e836d453b2bca0d4e2eb6a32424fe967092b52
[ "MIT" ]
null
null
null
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd 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 "OgreStableHeaders.h" #include "Compositor/Pass/OgreCompositorPassDef.h" #include "Compositor/Pass/PassClear/OgreCompositorPassClearDef.h" #include "Compositor/Pass/PassCompute/OgreCompositorPassComputeDef.h" #include "Compositor/Pass/PassDepthCopy/OgreCompositorPassDepthCopyDef.h" #include "Compositor/Pass/PassMipmap/OgreCompositorPassMipmapDef.h" #include "Compositor/Pass/PassQuad/OgreCompositorPassQuadDef.h" #include "Compositor/Pass/PassScene/OgreCompositorPassSceneDef.h" #include "Compositor/Pass/PassStencil/OgreCompositorPassStencilDef.h" #include "Compositor/Pass/PassUav/OgreCompositorPassUavDef.h" #include "Compositor/OgreCompositorNodeDef.h" #include "Compositor/OgreCompositorManager2.h" #include "Compositor/Pass/OgreCompositorPassProvider.h" namespace Ogre { CompositorTargetDef::~CompositorTargetDef() { CompositorPassDefVec::const_iterator itor = mCompositorPasses.begin(); CompositorPassDefVec::const_iterator end = mCompositorPasses.end(); while( itor != end ) { OGRE_DELETE *itor; ++itor; } mCompositorPasses.clear(); } //----------------------------------------------------------------------------------- CompositorPassDef* CompositorTargetDef::addPass( CompositorPassType passType, IdString customId ) { CompositorPassDef *retVal = 0; switch( passType ) { case PASS_CLEAR: retVal = OGRE_NEW CompositorPassClearDef( mRtIndex ); break; case PASS_QUAD: retVal = OGRE_NEW CompositorPassQuadDef( mParentNodeDef, mRtIndex ); break; case PASS_SCENE: retVal = OGRE_NEW CompositorPassSceneDef( mRtIndex ); break; case PASS_STENCIL: retVal = OGRE_NEW CompositorPassStencilDef( mRtIndex ); break; case PASS_DEPTHCOPY: retVal = OGRE_NEW CompositorPassDepthCopyDef( mParentNodeDef, mRtIndex ); break; case PASS_UAV: retVal = OGRE_NEW CompositorPassUavDef( mParentNodeDef, mRtIndex ); break; case PASS_MIPMAP: retVal = OGRE_NEW CompositorPassMipmapDef(); break; case PASS_COMPUTE: retVal = OGRE_NEW CompositorPassComputeDef( mParentNodeDef, mRtIndex ); break; case PASS_CUSTOM: { CompositorPassProvider *passProvider = mParentNodeDef->getCompositorManager()-> getCompositorPassProvider(); if( !passProvider ) { OGRE_EXCEPT( Exception::ERR_INVALID_STATE, "Using custom compositor passes but no provider is set", "CompositorTargetDef::addPass" ); } retVal = passProvider->addPassDef( passType, customId, mRtIndex, mParentNodeDef ); } break; default: break; } mParentNodeDef->postInitializePassDef( retVal ); mCompositorPasses.push_back( retVal ); return retVal; } //----------------------------------------------------------------------------------- }
40.25
101
0.627758
jondo2010
907aee87765ac5d6b56251594e16ce2c64ea646b
1,477
cpp
C++
fibercore/lib_utils.cpp
Wiladams/fiberdyne
916a257f6f00a5fa639a627240423e6d16961199
[ "Apache-2.0" ]
null
null
null
fibercore/lib_utils.cpp
Wiladams/fiberdyne
916a257f6f00a5fa639a627240423e6d16961199
[ "Apache-2.0" ]
null
null
null
fibercore/lib_utils.cpp
Wiladams/fiberdyne
916a257f6f00a5fa639a627240423e6d16961199
[ "Apache-2.0" ]
null
null
null
#include "utils.h" #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> /** * Check to see if the input starts with "0x"; if it does, return the decoded * bytes of the following data (presumed to be hex coded). If not, just return * the contents. This routine allocates memory, so has to be free'd. */ bool hex_decode( const uint8_t *input, uint8_t **decoded, uint64_t &len) { if (!decoded) return false; uint8_t *output = *decoded; if (output == nullptr) return false; if ((input[0] != '0') && (input[1] != 'x')) { len = strlen((char *)input); *decoded = (uint8_t *)calloc(1, (size_t)len+1); memcpy(*decoded, input, (size_t)len); } else { len = ( strlen((const char *)input ) >> 1 ) - 1; *decoded = (uint8_t *)malloc( (size_t)len ); for ( size_t i = 2; i < strlen( (const char *)input ); i += 2 ) { output[ ( ( i / 2 ) - 1 ) ] = ( ( ( input[ i ] <= '9' ) ? input[ i ] - '0' : ( ( tolower( input[ i ] ) ) - 'a' + 10 ) ) << 4 ) | ( ( input[ i + 1 ] <= '9' ) ? input[ i + 1 ] - '0' : ( ( tolower( input[ i + 1 ] ) ) - 'a' + 10 ) ); } } return true; } bool hex_print( const uint8_t *data, uint64_t length ) { while ( length-- ) { printf( "%.02x", *data++ ); } return true; } bool hex_puts( const uint8_t *data, uint64_t length ) { hex_print(data, length); printf("\n"); return true; }
25.912281
78
0.525389
Wiladams
907d8fcf48b8be9db4026a6dbf17b57af31bfb53
3,964
cpp
C++
modules/boost/simd/sdk/unit/memory/utility/make_aligned.cpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
34
2017-05-19T18:10:17.000Z
2022-01-04T02:18:13.000Z
modules/boost/simd/sdk/unit/memory/utility/make_aligned.cpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
null
null
null
modules/boost/simd/sdk/unit/memory/utility/make_aligned.cpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
7
2017-12-02T12:59:17.000Z
2021-07-31T12:46:14.000Z
//============================================================================== // Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2011 LRI UMR 8623 CNRS/Univ Paris Sud XI // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #include <boost/simd/sdk/config/types.hpp> #include <boost/simd/memory/allocate.hpp> #include <boost/simd/memory/align_ptr.hpp> #include <boost/simd/memory/deallocate.hpp> #include <boost/simd/memory/is_aligned.hpp> #include <boost/simd/preprocessor/aligned_type.hpp> #include <boost/simd/meta/align_ptr.hpp> #include <nt2/sdk/unit/module.hpp> #include <nt2/sdk/unit/tests/basic.hpp> #include <nt2/sdk/unit/tests/relation.hpp> //////////////////////////////////////////////////////////////////////////////// // Test make_aligned on simple type //////////////////////////////////////////////////////////////////////////////// NT2_TEST_CASE(make_aligned) { using boost::simd::is_aligned; BOOST_SIMD_ALIGNED_TYPE(double ) ad; BOOST_SIMD_ALIGNED_TYPE(float ) af; BOOST_SIMD_ALIGNED_TYPE(boost::simd::uint64_t) aui64; BOOST_SIMD_ALIGNED_TYPE(boost::simd::uint32_t) aui32; BOOST_SIMD_ALIGNED_TYPE(boost::simd::uint16_t) aui16; BOOST_SIMD_ALIGNED_TYPE(boost::simd::uint8_t ) aui8; BOOST_SIMD_ALIGNED_TYPE(boost::simd::int64_t ) ai64; BOOST_SIMD_ALIGNED_TYPE(boost::simd::int32_t ) ai32; BOOST_SIMD_ALIGNED_TYPE(boost::simd::int16_t ) ai16; BOOST_SIMD_ALIGNED_TYPE(boost::simd::int8_t ) ai8; BOOST_SIMD_ALIGNED_TYPE(bool ) ab; NT2_TEST( is_aligned(&ad) ); NT2_TEST( is_aligned(&af) ); NT2_TEST( is_aligned(&aui64) ); NT2_TEST( is_aligned(&aui32) ); NT2_TEST( is_aligned(&aui16) ); NT2_TEST( is_aligned(&aui8) ); NT2_TEST( is_aligned(&ai64) ); NT2_TEST( is_aligned(&ai32) ); NT2_TEST( is_aligned(&ai16) ); NT2_TEST( is_aligned(&ai8) ); NT2_TEST( is_aligned(&ab) ); } //////////////////////////////////////////////////////////////////////////////// // Test make_aligned on array type //////////////////////////////////////////////////////////////////////////////// NT2_TEST_CASE(make_aligned_array) { using boost::simd::is_aligned; BOOST_SIMD_ALIGNED_TYPE(double ) ad[3]; BOOST_SIMD_ALIGNED_TYPE(float ) af[3]; BOOST_SIMD_ALIGNED_TYPE(boost::simd::uint64_t) aui64[3]; BOOST_SIMD_ALIGNED_TYPE(boost::simd::uint32_t) aui32[3]; BOOST_SIMD_ALIGNED_TYPE(boost::simd::uint16_t) aui16[3]; BOOST_SIMD_ALIGNED_TYPE(boost::simd::uint8_t ) aui8[3]; BOOST_SIMD_ALIGNED_TYPE(boost::simd::int64_t ) ai64[3]; BOOST_SIMD_ALIGNED_TYPE(boost::simd::int32_t ) ai32[3]; BOOST_SIMD_ALIGNED_TYPE(boost::simd::int16_t ) ai16[3]; BOOST_SIMD_ALIGNED_TYPE(boost::simd::int8_t ) ai8[3]; BOOST_SIMD_ALIGNED_TYPE(bool ) ab[3]; NT2_TEST( is_aligned(&ad[0]) ); NT2_TEST( is_aligned(&af[0]) ); NT2_TEST( is_aligned(&aui64[0]) ); NT2_TEST( is_aligned(&aui32[0]) ); NT2_TEST( is_aligned(&aui16[0]) ); NT2_TEST( is_aligned(&aui8[0]) ); NT2_TEST( is_aligned(&ai64[0]) ); NT2_TEST( is_aligned(&ai32[0]) ); NT2_TEST( is_aligned(&ai16[0]) ); NT2_TEST( is_aligned(&ai8[0]) ); NT2_TEST( is_aligned(&ab[0]) ); } //////////////////////////////////////////////////////////////////////////////// // Test make_aligned metafunction //////////////////////////////////////////////////////////////////////////////// NT2_TEST_CASE(align_ptr) { using boost::simd::is_aligned; using boost::simd::align_ptr; using boost::simd::allocate; using boost::simd::deallocate; void* ptr = allocate(15, 32); boost::simd::meta::align_ptr<void, 32>::type p = align_ptr<32>(ptr); NT2_TEST( is_aligned(p, 32) ); NT2_TEST_EQUAL(p, ptr); deallocate(ptr); }
38.862745
80
0.589051
psiha
907fa619951534d8911fe1f039e67a7a9e814c0f
792
cpp
C++
Source/EstCore/Private/EstCore.cpp
edgarbarney/Estranged.Core
289c672da77f30789f19c317815ea8f973885a25
[ "MIT" ]
23
2018-10-28T00:47:58.000Z
2021-06-07T04:54:32.000Z
Source/EstCore/Private/EstCore.cpp
edgarbarney/Estranged.Core
289c672da77f30789f19c317815ea8f973885a25
[ "MIT" ]
null
null
null
Source/EstCore/Private/EstCore.cpp
edgarbarney/Estranged.Core
289c672da77f30789f19c317815ea8f973885a25
[ "MIT" ]
3
2020-04-11T17:19:43.000Z
2021-09-21T10:47:26.000Z
#include "EstCore.h" #include "Modules/ModuleManager.h" extern ENGINE_API float GAverageFPS; IMPLEMENT_GAME_MODULE(FEstCoreModule, EstCore); // Default to something low so we don't start at zero float FEstCoreModule::LongAverageFrameRate = 25.f; void FEstCoreModule::StartupModule() { TickDelegate = FTickerDelegate::CreateRaw(this, &FEstCoreModule::Tick); TickDelegateHandle = FTicker::GetCoreTicker().AddTicker(TickDelegate); } bool FEstCoreModule::Tick(float DeltaTime) { LongAverageFrameRate = LongAverageFrameRate * .99f + GAverageFPS * .01f; return true; } void FEstCoreModule::ShutdownModule() { FTicker::GetCoreTicker().RemoveTicker(TickDelegateHandle); } DEFINE_LOG_CATEGORY(LogEstGeneral); ESTCORE_API const FEstImpactEffect FEstImpactEffect::None = FEstImpactEffect();
26.4
79
0.79798
edgarbarney
9082f1387eeb7e26821d0043d1af9626a3b86c24
3,521
cpp
C++
Core/MAGESLAM/Source/Image/OrbFeatureDetector.cpp
syntheticmagus/mageslam
ba79a4e6315689c072c29749de18d70279a4c5e4
[ "MIT" ]
70
2020-05-07T03:09:09.000Z
2022-02-11T01:04:54.000Z
Core/MAGESLAM/Source/Image/OrbFeatureDetector.cpp
syntheticmagus/mageslam
ba79a4e6315689c072c29749de18d70279a4c5e4
[ "MIT" ]
3
2020-06-01T00:34:01.000Z
2020-10-08T07:43:32.000Z
Core/MAGESLAM/Source/Image/OrbFeatureDetector.cpp
syntheticmagus/mageslam
ba79a4e6315689c072c29749de18d70279a4c5e4
[ "MIT" ]
16
2020-05-07T03:09:13.000Z
2022-03-31T15:36:49.000Z
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //------------------------------------------------------------------------------ // OrbFeatureDetector.cpp // // The feature detector detects the orb features in an image and // also computes the BRIEF descriptors for them. The init settings // control the properties of the features. //------------------------------------------------------------------------------ #include "OrbFeatureDetector.h" #include "MageSettings.h" #include <opencv2/core/core.hpp> #include <opencv2/features2d/features2d.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/core.hpp> #include "Utils/Logging.h" #include "OpenCVModified.h" #include "Analysis/DataFlow.h" #include <gsl/gsl_algorithm> namespace mage { void OrbFeatureDetector::UndistortKeypoints( gsl::span<cv::KeyPoint> inoutKeypoints, const CameraCalibration& distortedCalibration, const CameraCalibration& undistortedCalibration, thread_memory memory) { SCOPE_TIMER(OrbFeatureDetector::UndistortKeypoints); assert(distortedCalibration.GetDistortionType() != mage::calibration::DistortionType::None && "expecting distorted keypoints to undistort"); if (inoutKeypoints.empty()) { return; } auto sourceMem = memory.stack_buffer<cv::Point2f>(inoutKeypoints.size()); for (size_t i = 0; i < sourceMem.size(); ++i) { sourceMem[i] = inoutKeypoints[i].pt; } cv::Mat distortedPointsMat{ (int)sourceMem.size(), 1, CV_32FC2, sourceMem.data() }; auto destMem = memory.stack_buffer<cv::Point2f>(inoutKeypoints.size()); cv::Mat undistortedPointsMat{ (int)destMem.size(), 1, CV_32FC2, destMem.data() }; undistortPoints(distortedPointsMat, undistortedPointsMat, distortedCalibration.GetCameraMatrix(), distortedCalibration.GetCVDistortionCoeffs(), cv::noArray(), undistortedCalibration.GetCameraMatrix()); // now adjust the points in undistorted for (size_t i = 0; i < destMem.size(); ++i) { inoutKeypoints[i].pt = destMem[i]; } } OrbFeatureDetector::OrbFeatureDetector(const FeatureExtractorSettings& settings) : m_detector{ settings.GaussianKernelSize, (unsigned int)settings.NumFeatures, settings.ScaleFactor, settings.NumLevels, settings.PatchSize, settings.FastThreshold, settings.UseOrientation, settings.FeatureFactor, settings.FeatureStrength, settings.StrongResponse, settings.MinRobustnessFactor, settings.MaxRobustnessFactor, settings.NumCellsX, settings.NumCellsY } { } void OrbFeatureDetector::Process(const CameraCalibration& distortedCalibration, const CameraCalibration& undistortedCalibration, thread_memory memory, ImageHandle& imageData, const cv::Mat& image) { SCOPE_TIMER(OrbFeatureDetector::Process); assert(undistortedCalibration.GetDistortionType() == calibration::DistortionType::None && "Expecting undistorted cal to be undistorted"); DATAFLOW( DF_OUTPUT(imageData->GetKeypoints()) ); m_detector.DetectAndCompute(memory, *imageData, image); if(distortedCalibration != undistortedCalibration) { UndistortKeypoints(imageData->GetKeypoints(), distortedCalibration, undistortedCalibration, memory); } } }
34.519608
210
0.652087
syntheticmagus
9087a52c279a863d67cda2f3404293017382bd0b
32,049
cc
C++
Lodestar/io/proto/ls.proto.systems.pb.cc
helkebir/Lodestar
6b325d3e7a388676ed31d44eac1146630ee4bb2c
[ "BSD-3-Clause" ]
4
2020-06-05T14:08:23.000Z
2021-06-26T22:15:31.000Z
Lodestar/io/proto/ls.proto.systems.pb.cc
helkebir/Lodestar
6b325d3e7a388676ed31d44eac1146630ee4bb2c
[ "BSD-3-Clause" ]
2
2021-06-25T15:14:01.000Z
2021-07-01T17:43:20.000Z
Lodestar/io/proto/ls.proto.systems.pb.cc
helkebir/Lodestar
6b325d3e7a388676ed31d44eac1146630ee4bb2c
[ "BSD-3-Clause" ]
1
2021-06-16T03:15:23.000Z
2021-06-16T03:15:23.000Z
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: ls.proto.systems.proto #include "ls.proto.systems.pb.h" #include <algorithm> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/extension_set.h> #include <google/protobuf/wire_format_lite.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) #include <google/protobuf/port_def.inc> PROTOBUF_PRAGMA_INIT_SEG namespace ls { namespace proto { namespace systems { constexpr StateSpace::StateSpace( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : a_(nullptr) , b_(nullptr) , c_(nullptr) , d_(nullptr) , dt_(0) , isdiscrete_(false){} struct StateSpaceDefaultTypeInternal { constexpr StateSpaceDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~StateSpaceDefaultTypeInternal() {} union { StateSpace _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT StateSpaceDefaultTypeInternal _StateSpace_default_instance_; constexpr TransferFunction::TransferFunction( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : num_(nullptr) , den_(nullptr){} struct TransferFunctionDefaultTypeInternal { constexpr TransferFunctionDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~TransferFunctionDefaultTypeInternal() {} union { TransferFunction _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT TransferFunctionDefaultTypeInternal _TransferFunction_default_instance_; } // namespace systems } // namespace proto } // namespace ls static ::PROTOBUF_NAMESPACE_ID::Metadata file_level_metadata_ls_2eproto_2esystems_2eproto[2]; static constexpr ::PROTOBUF_NAMESPACE_ID::EnumDescriptor const** file_level_enum_descriptors_ls_2eproto_2esystems_2eproto = nullptr; static constexpr ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor const** file_level_service_descriptors_ls_2eproto_2esystems_2eproto = nullptr; const ::PROTOBUF_NAMESPACE_ID::uint32 TableStruct_ls_2eproto_2esystems_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { PROTOBUF_FIELD_OFFSET(::ls::proto::systems::StateSpace, _has_bits_), PROTOBUF_FIELD_OFFSET(::ls::proto::systems::StateSpace, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::ls::proto::systems::StateSpace, a_), PROTOBUF_FIELD_OFFSET(::ls::proto::systems::StateSpace, b_), PROTOBUF_FIELD_OFFSET(::ls::proto::systems::StateSpace, c_), PROTOBUF_FIELD_OFFSET(::ls::proto::systems::StateSpace, d_), PROTOBUF_FIELD_OFFSET(::ls::proto::systems::StateSpace, isdiscrete_), PROTOBUF_FIELD_OFFSET(::ls::proto::systems::StateSpace, dt_), 0, 1, 2, 3, 5, 4, PROTOBUF_FIELD_OFFSET(::ls::proto::systems::TransferFunction, _has_bits_), PROTOBUF_FIELD_OFFSET(::ls::proto::systems::TransferFunction, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::ls::proto::systems::TransferFunction, num_), PROTOBUF_FIELD_OFFSET(::ls::proto::systems::TransferFunction, den_), 0, 1, }; static const ::PROTOBUF_NAMESPACE_ID::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { { 0, 11, sizeof(::ls::proto::systems::StateSpace)}, { 17, 24, sizeof(::ls::proto::systems::TransferFunction)}, }; static ::PROTOBUF_NAMESPACE_ID::Message const * const file_default_instances[] = { reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::ls::proto::systems::_StateSpace_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::ls::proto::systems::_TransferFunction_default_instance_), }; const char descriptor_table_protodef_ls_2eproto_2esystems_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = "\n\026ls.proto.systems.proto\022\020ls.proto.syste" "ms\032\024ls.proto.eigen.proto\"\214\002\n\nStateSpace\022" "(\n\001A\030\001 \001(\0132\030.ls.proto.eigen.MatrixXdH\000\210\001" "\001\022(\n\001B\030\002 \001(\0132\030.ls.proto.eigen.MatrixXdH\001" "\210\001\001\022(\n\001C\030\003 \001(\0132\030.ls.proto.eigen.MatrixXd" "H\002\210\001\001\022(\n\001D\030\004 \001(\0132\030.ls.proto.eigen.Matrix" "XdH\003\210\001\001\022\027\n\nisDiscrete\030\005 \001(\010H\004\210\001\001\022\017\n\002dt\030\006" " \001(\001H\005\210\001\001B\004\n\002_AB\004\n\002_BB\004\n\002_CB\004\n\002_DB\r\n\013_is" "DiscreteB\005\n\003_dt\"z\n\020TransferFunction\022*\n\003n" "um\030\001 \001(\0132\030.ls.proto.eigen.VectorXdH\000\210\001\001\022" "*\n\003den\030\002 \001(\0132\030.ls.proto.eigen.VectorXdH\001" "\210\001\001B\006\n\004_numB\006\n\004_denb\006proto3" ; static const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable*const descriptor_table_ls_2eproto_2esystems_2eproto_deps[1] = { &::descriptor_table_ls_2eproto_2eeigen_2eproto, }; static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_ls_2eproto_2esystems_2eproto_once; const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_ls_2eproto_2esystems_2eproto = { false, false, 467, descriptor_table_protodef_ls_2eproto_2esystems_2eproto, "ls.proto.systems.proto", &descriptor_table_ls_2eproto_2esystems_2eproto_once, descriptor_table_ls_2eproto_2esystems_2eproto_deps, 1, 2, schemas, file_default_instances, TableStruct_ls_2eproto_2esystems_2eproto::offsets, file_level_metadata_ls_2eproto_2esystems_2eproto, file_level_enum_descriptors_ls_2eproto_2esystems_2eproto, file_level_service_descriptors_ls_2eproto_2esystems_2eproto, }; PROTOBUF_ATTRIBUTE_WEAK const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable* descriptor_table_ls_2eproto_2esystems_2eproto_getter() { return &descriptor_table_ls_2eproto_2esystems_2eproto; } // Force running AddDescriptors() at dynamic initialization time. PROTOBUF_ATTRIBUTE_INIT_PRIORITY static ::PROTOBUF_NAMESPACE_ID::internal::AddDescriptorsRunner dynamic_init_dummy_ls_2eproto_2esystems_2eproto(&descriptor_table_ls_2eproto_2esystems_2eproto); namespace ls { namespace proto { namespace systems { // =================================================================== class StateSpace::_Internal { public: using HasBits = decltype(std::declval<StateSpace>()._has_bits_); static const ::ls::proto::eigen::MatrixXd& a(const StateSpace* msg); static void set_has_a(HasBits* has_bits) { (*has_bits)[0] |= 1u; } static const ::ls::proto::eigen::MatrixXd& b(const StateSpace* msg); static void set_has_b(HasBits* has_bits) { (*has_bits)[0] |= 2u; } static const ::ls::proto::eigen::MatrixXd& c(const StateSpace* msg); static void set_has_c(HasBits* has_bits) { (*has_bits)[0] |= 4u; } static const ::ls::proto::eigen::MatrixXd& d(const StateSpace* msg); static void set_has_d(HasBits* has_bits) { (*has_bits)[0] |= 8u; } static void set_has_isdiscrete(HasBits* has_bits) { (*has_bits)[0] |= 32u; } static void set_has_dt(HasBits* has_bits) { (*has_bits)[0] |= 16u; } }; const ::ls::proto::eigen::MatrixXd& StateSpace::_Internal::a(const StateSpace* msg) { return *msg->a_; } const ::ls::proto::eigen::MatrixXd& StateSpace::_Internal::b(const StateSpace* msg) { return *msg->b_; } const ::ls::proto::eigen::MatrixXd& StateSpace::_Internal::c(const StateSpace* msg) { return *msg->c_; } const ::ls::proto::eigen::MatrixXd& StateSpace::_Internal::d(const StateSpace* msg) { return *msg->d_; } void StateSpace::clear_a() { if (a_ != nullptr) a_->Clear(); _has_bits_[0] &= ~0x00000001u; } void StateSpace::clear_b() { if (b_ != nullptr) b_->Clear(); _has_bits_[0] &= ~0x00000002u; } void StateSpace::clear_c() { if (c_ != nullptr) c_->Clear(); _has_bits_[0] &= ~0x00000004u; } void StateSpace::clear_d() { if (d_ != nullptr) d_->Clear(); _has_bits_[0] &= ~0x00000008u; } StateSpace::StateSpace(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:ls.proto.systems.StateSpace) } StateSpace::StateSpace(const StateSpace& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); if (from._internal_has_a()) { a_ = new ::ls::proto::eigen::MatrixXd(*from.a_); } else { a_ = nullptr; } if (from._internal_has_b()) { b_ = new ::ls::proto::eigen::MatrixXd(*from.b_); } else { b_ = nullptr; } if (from._internal_has_c()) { c_ = new ::ls::proto::eigen::MatrixXd(*from.c_); } else { c_ = nullptr; } if (from._internal_has_d()) { d_ = new ::ls::proto::eigen::MatrixXd(*from.d_); } else { d_ = nullptr; } ::memcpy(&dt_, &from.dt_, static_cast<size_t>(reinterpret_cast<char*>(&isdiscrete_) - reinterpret_cast<char*>(&dt_)) + sizeof(isdiscrete_)); // @@protoc_insertion_point(copy_constructor:ls.proto.systems.StateSpace) } void StateSpace::SharedCtor() { ::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( reinterpret_cast<char*>(&a_) - reinterpret_cast<char*>(this)), 0, static_cast<size_t>(reinterpret_cast<char*>(&isdiscrete_) - reinterpret_cast<char*>(&a_)) + sizeof(isdiscrete_)); } StateSpace::~StateSpace() { // @@protoc_insertion_point(destructor:ls.proto.systems.StateSpace) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void StateSpace::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); if (this != internal_default_instance()) delete a_; if (this != internal_default_instance()) delete b_; if (this != internal_default_instance()) delete c_; if (this != internal_default_instance()) delete d_; } void StateSpace::ArenaDtor(void* object) { StateSpace* _this = reinterpret_cast< StateSpace* >(object); (void)_this; } void StateSpace::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void StateSpace::SetCachedSize(int size) const { _cached_size_.Set(size); } void StateSpace::Clear() { // @@protoc_insertion_point(message_clear_start:ls.proto.systems.StateSpace) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x0000000fu) { if (cached_has_bits & 0x00000001u) { GOOGLE_DCHECK(a_ != nullptr); a_->Clear(); } if (cached_has_bits & 0x00000002u) { GOOGLE_DCHECK(b_ != nullptr); b_->Clear(); } if (cached_has_bits & 0x00000004u) { GOOGLE_DCHECK(c_ != nullptr); c_->Clear(); } if (cached_has_bits & 0x00000008u) { GOOGLE_DCHECK(d_ != nullptr); d_->Clear(); } } if (cached_has_bits & 0x00000030u) { ::memset(&dt_, 0, static_cast<size_t>( reinterpret_cast<char*>(&isdiscrete_) - reinterpret_cast<char*>(&dt_)) + sizeof(isdiscrete_)); } _has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* StateSpace::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); switch (tag >> 3) { // optional .ls.proto.eigen.MatrixXd A = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { ptr = ctx->ParseMessage(_internal_mutable_a(), ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional .ls.proto.eigen.MatrixXd B = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) { ptr = ctx->ParseMessage(_internal_mutable_b(), ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional .ls.proto.eigen.MatrixXd C = 3; case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26)) { ptr = ctx->ParseMessage(_internal_mutable_c(), ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional .ls.proto.eigen.MatrixXd D = 4; case 4: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 34)) { ptr = ctx->ParseMessage(_internal_mutable_d(), ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional bool isDiscrete = 5; case 5: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 40)) { _Internal::set_has_isdiscrete(&has_bits); isdiscrete_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional double dt = 6; case 6: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 49)) { _Internal::set_has_dt(&has_bits); dt_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<double>(ptr); ptr += sizeof(double); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* StateSpace::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:ls.proto.systems.StateSpace) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // optional .ls.proto.eigen.MatrixXd A = 1; if (_internal_has_a()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage( 1, _Internal::a(this), target, stream); } // optional .ls.proto.eigen.MatrixXd B = 2; if (_internal_has_b()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage( 2, _Internal::b(this), target, stream); } // optional .ls.proto.eigen.MatrixXd C = 3; if (_internal_has_c()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage( 3, _Internal::c(this), target, stream); } // optional .ls.proto.eigen.MatrixXd D = 4; if (_internal_has_d()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage( 4, _Internal::d(this), target, stream); } // optional bool isDiscrete = 5; if (_internal_has_isdiscrete()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(5, this->_internal_isdiscrete(), target); } // optional double dt = 6; if (_internal_has_dt()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteDoubleToArray(6, this->_internal_dt(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:ls.proto.systems.StateSpace) return target; } size_t StateSpace::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:ls.proto.systems.StateSpace) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x0000003fu) { // optional .ls.proto.eigen.MatrixXd A = 1; if (cached_has_bits & 0x00000001u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( *a_); } // optional .ls.proto.eigen.MatrixXd B = 2; if (cached_has_bits & 0x00000002u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( *b_); } // optional .ls.proto.eigen.MatrixXd C = 3; if (cached_has_bits & 0x00000004u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( *c_); } // optional .ls.proto.eigen.MatrixXd D = 4; if (cached_has_bits & 0x00000008u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( *d_); } // optional double dt = 6; if (cached_has_bits & 0x00000010u) { total_size += 1 + 8; } // optional bool isDiscrete = 5; if (cached_has_bits & 0x00000020u) { total_size += 1 + 1; } } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void StateSpace::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:ls.proto.systems.StateSpace) GOOGLE_DCHECK_NE(&from, this); const StateSpace* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<StateSpace>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:ls.proto.systems.StateSpace) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:ls.proto.systems.StateSpace) MergeFrom(*source); } } void StateSpace::MergeFrom(const StateSpace& from) { // @@protoc_insertion_point(class_specific_merge_from_start:ls.proto.systems.StateSpace) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 0x0000003fu) { if (cached_has_bits & 0x00000001u) { _internal_mutable_a()->::ls::proto::eigen::MatrixXd::MergeFrom(from._internal_a()); } if (cached_has_bits & 0x00000002u) { _internal_mutable_b()->::ls::proto::eigen::MatrixXd::MergeFrom(from._internal_b()); } if (cached_has_bits & 0x00000004u) { _internal_mutable_c()->::ls::proto::eigen::MatrixXd::MergeFrom(from._internal_c()); } if (cached_has_bits & 0x00000008u) { _internal_mutable_d()->::ls::proto::eigen::MatrixXd::MergeFrom(from._internal_d()); } if (cached_has_bits & 0x00000010u) { dt_ = from.dt_; } if (cached_has_bits & 0x00000020u) { isdiscrete_ = from.isdiscrete_; } _has_bits_[0] |= cached_has_bits; } } void StateSpace::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:ls.proto.systems.StateSpace) if (&from == this) return; Clear(); MergeFrom(from); } void StateSpace::CopyFrom(const StateSpace& from) { // @@protoc_insertion_point(class_specific_copy_from_start:ls.proto.systems.StateSpace) if (&from == this) return; Clear(); MergeFrom(from); } bool StateSpace::IsInitialized() const { return true; } void StateSpace::InternalSwap(StateSpace* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); ::PROTOBUF_NAMESPACE_ID::internal::memswap< PROTOBUF_FIELD_OFFSET(StateSpace, isdiscrete_) + sizeof(StateSpace::isdiscrete_) - PROTOBUF_FIELD_OFFSET(StateSpace, a_)>( reinterpret_cast<char*>(&a_), reinterpret_cast<char*>(&other->a_)); } ::PROTOBUF_NAMESPACE_ID::Metadata StateSpace::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_ls_2eproto_2esystems_2eproto_getter, &descriptor_table_ls_2eproto_2esystems_2eproto_once, file_level_metadata_ls_2eproto_2esystems_2eproto[0]); } // =================================================================== class TransferFunction::_Internal { public: using HasBits = decltype(std::declval<TransferFunction>()._has_bits_); static const ::ls::proto::eigen::VectorXd& num(const TransferFunction* msg); static void set_has_num(HasBits* has_bits) { (*has_bits)[0] |= 1u; } static const ::ls::proto::eigen::VectorXd& den(const TransferFunction* msg); static void set_has_den(HasBits* has_bits) { (*has_bits)[0] |= 2u; } }; const ::ls::proto::eigen::VectorXd& TransferFunction::_Internal::num(const TransferFunction* msg) { return *msg->num_; } const ::ls::proto::eigen::VectorXd& TransferFunction::_Internal::den(const TransferFunction* msg) { return *msg->den_; } void TransferFunction::clear_num() { if (num_ != nullptr) num_->Clear(); _has_bits_[0] &= ~0x00000001u; } void TransferFunction::clear_den() { if (den_ != nullptr) den_->Clear(); _has_bits_[0] &= ~0x00000002u; } TransferFunction::TransferFunction(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:ls.proto.systems.TransferFunction) } TransferFunction::TransferFunction(const TransferFunction& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); if (from._internal_has_num()) { num_ = new ::ls::proto::eigen::VectorXd(*from.num_); } else { num_ = nullptr; } if (from._internal_has_den()) { den_ = new ::ls::proto::eigen::VectorXd(*from.den_); } else { den_ = nullptr; } // @@protoc_insertion_point(copy_constructor:ls.proto.systems.TransferFunction) } void TransferFunction::SharedCtor() { ::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( reinterpret_cast<char*>(&num_) - reinterpret_cast<char*>(this)), 0, static_cast<size_t>(reinterpret_cast<char*>(&den_) - reinterpret_cast<char*>(&num_)) + sizeof(den_)); } TransferFunction::~TransferFunction() { // @@protoc_insertion_point(destructor:ls.proto.systems.TransferFunction) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void TransferFunction::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); if (this != internal_default_instance()) delete num_; if (this != internal_default_instance()) delete den_; } void TransferFunction::ArenaDtor(void* object) { TransferFunction* _this = reinterpret_cast< TransferFunction* >(object); (void)_this; } void TransferFunction::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void TransferFunction::SetCachedSize(int size) const { _cached_size_.Set(size); } void TransferFunction::Clear() { // @@protoc_insertion_point(message_clear_start:ls.proto.systems.TransferFunction) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { GOOGLE_DCHECK(num_ != nullptr); num_->Clear(); } if (cached_has_bits & 0x00000002u) { GOOGLE_DCHECK(den_ != nullptr); den_->Clear(); } } _has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* TransferFunction::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); switch (tag >> 3) { // optional .ls.proto.eigen.VectorXd num = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { ptr = ctx->ParseMessage(_internal_mutable_num(), ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional .ls.proto.eigen.VectorXd den = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) { ptr = ctx->ParseMessage(_internal_mutable_den(), ptr); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* TransferFunction::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:ls.proto.systems.TransferFunction) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // optional .ls.proto.eigen.VectorXd num = 1; if (_internal_has_num()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage( 1, _Internal::num(this), target, stream); } // optional .ls.proto.eigen.VectorXd den = 2; if (_internal_has_den()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage( 2, _Internal::den(this), target, stream); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:ls.proto.systems.TransferFunction) return target; } size_t TransferFunction::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:ls.proto.systems.TransferFunction) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000003u) { // optional .ls.proto.eigen.VectorXd num = 1; if (cached_has_bits & 0x00000001u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( *num_); } // optional .ls.proto.eigen.VectorXd den = 2; if (cached_has_bits & 0x00000002u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( *den_); } } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void TransferFunction::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:ls.proto.systems.TransferFunction) GOOGLE_DCHECK_NE(&from, this); const TransferFunction* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<TransferFunction>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:ls.proto.systems.TransferFunction) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:ls.proto.systems.TransferFunction) MergeFrom(*source); } } void TransferFunction::MergeFrom(const TransferFunction& from) { // @@protoc_insertion_point(class_specific_merge_from_start:ls.proto.systems.TransferFunction) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { _internal_mutable_num()->::ls::proto::eigen::VectorXd::MergeFrom(from._internal_num()); } if (cached_has_bits & 0x00000002u) { _internal_mutable_den()->::ls::proto::eigen::VectorXd::MergeFrom(from._internal_den()); } } } void TransferFunction::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:ls.proto.systems.TransferFunction) if (&from == this) return; Clear(); MergeFrom(from); } void TransferFunction::CopyFrom(const TransferFunction& from) { // @@protoc_insertion_point(class_specific_copy_from_start:ls.proto.systems.TransferFunction) if (&from == this) return; Clear(); MergeFrom(from); } bool TransferFunction::IsInitialized() const { return true; } void TransferFunction::InternalSwap(TransferFunction* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); ::PROTOBUF_NAMESPACE_ID::internal::memswap< PROTOBUF_FIELD_OFFSET(TransferFunction, den_) + sizeof(TransferFunction::den_) - PROTOBUF_FIELD_OFFSET(TransferFunction, num_)>( reinterpret_cast<char*>(&num_), reinterpret_cast<char*>(&other->num_)); } ::PROTOBUF_NAMESPACE_ID::Metadata TransferFunction::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_ls_2eproto_2esystems_2eproto_getter, &descriptor_table_ls_2eproto_2esystems_2eproto_once, file_level_metadata_ls_2eproto_2esystems_2eproto[1]); } // @@protoc_insertion_point(namespace_scope) } // namespace systems } // namespace proto } // namespace ls PROTOBUF_NAMESPACE_OPEN template<> PROTOBUF_NOINLINE ::ls::proto::systems::StateSpace* Arena::CreateMaybeMessage< ::ls::proto::systems::StateSpace >(Arena* arena) { return Arena::CreateMessageInternal< ::ls::proto::systems::StateSpace >(arena); } template<> PROTOBUF_NOINLINE ::ls::proto::systems::TransferFunction* Arena::CreateMaybeMessage< ::ls::proto::systems::TransferFunction >(Arena* arena) { return Arena::CreateMessageInternal< ::ls::proto::systems::TransferFunction >(arena); } PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) #include <google/protobuf/port_undef.inc>
37.136732
192
0.714718
helkebir
9087e0d2276d874818d343f315eff0fe1715ea4c
4,155
cpp
C++
test/main.cpp
AdamYuan/VulkanQueueSelector
e6c51175cfbb887d08c48a285126c8e9ea2fa033
[ "Unlicense" ]
1
2021-01-24T10:37:25.000Z
2021-01-24T10:37:25.000Z
test/main.cpp
AdamYuan/VulkanQueueSelector
e6c51175cfbb887d08c48a285126c8e9ea2fa033
[ "Unlicense" ]
1
2022-03-28T16:10:27.000Z
2022-03-29T02:53:23.000Z
test/main.cpp
AdamYuan/VulkanQueueSelector
e6c51175cfbb887d08c48a285126c8e9ea2fa033
[ "Unlicense" ]
null
null
null
#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN #include "doctest.h" #include "vk_queue_selector.h" #include <cstdio> #include <vector> static void fakeGetPhysicalDeviceQueueFamilyProperties0(VkPhysicalDevice, uint32_t *pQueueFamilyPropertyCount, VkQueueFamilyProperties *pQueueFamilyProperties) { if(pQueueFamilyPropertyCount) *pQueueFamilyPropertyCount = 4; if(pQueueFamilyProperties) { pQueueFamilyProperties[0].queueFlags = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT | VK_QUEUE_TRANSFER_BIT; pQueueFamilyProperties[0].queueCount = 10; pQueueFamilyProperties[1].queueFlags = VK_QUEUE_GRAPHICS_BIT; pQueueFamilyProperties[1].queueCount = 3; pQueueFamilyProperties[2].queueFlags = VK_QUEUE_TRANSFER_BIT; pQueueFamilyProperties[2].queueCount = 2; pQueueFamilyProperties[3].queueFlags = VK_QUEUE_COMPUTE_BIT; pQueueFamilyProperties[3].queueCount = 1; } } static VkResult fakeGetPhysicalDeviceSurfaceSupportKHR0(VkPhysicalDevice, uint32_t queueFamilyIndex, VkSurfaceKHR, VkBool32 *pSupported) { constexpr VkBool32 kSurfaceSupport[] = {0, 1, 0, 0}; *pSupported = kSurfaceSupport[queueFamilyIndex]; return VK_SUCCESS; } TEST_CASE("Large requirements and different priorities") { VqsVulkanFunctions functions = {}; functions.vkGetPhysicalDeviceQueueFamilyProperties = fakeGetPhysicalDeviceQueueFamilyProperties0; functions.vkGetPhysicalDeviceSurfaceSupportKHR = fakeGetPhysicalDeviceSurfaceSupportKHR0; VqsQueryCreateInfo createInfo = {}; createInfo.physicalDevice = NULL; VqsQueueRequirements requirements[] = { {VK_QUEUE_GRAPHICS_BIT, 1.0f, (VkSurfaceKHR)(main)}, {VK_QUEUE_GRAPHICS_BIT, 0.8f, (VkSurfaceKHR)(main)}, {VK_QUEUE_COMPUTE_BIT, 1.0f, (VkSurfaceKHR)(main)}, {VK_QUEUE_COMPUTE_BIT, 0.5f, nullptr}, {VK_QUEUE_COMPUTE_BIT, 0.5f, nullptr}, {VK_QUEUE_COMPUTE_BIT, 0.5f, nullptr}, {VK_QUEUE_COMPUTE_BIT, 0.5f, nullptr}, {VK_QUEUE_COMPUTE_BIT, 0.5f, nullptr}, {VK_QUEUE_COMPUTE_BIT, 0.5f, nullptr}, {VK_QUEUE_COMPUTE_BIT, 0.5f, nullptr}, {VK_QUEUE_COMPUTE_BIT, 0.5f, nullptr}, {VK_QUEUE_COMPUTE_BIT, 1.0f, nullptr}, {VK_QUEUE_COMPUTE_BIT, 0.5f, nullptr}, {VK_QUEUE_COMPUTE_BIT, 0.5f, nullptr}, {VK_QUEUE_COMPUTE_BIT, 0.5f, nullptr}, {VK_QUEUE_COMPUTE_BIT, 0.5f, nullptr}, {VK_QUEUE_COMPUTE_BIT, 0.5f, nullptr}, {VK_QUEUE_COMPUTE_BIT, 0.5f, nullptr}, {VK_QUEUE_COMPUTE_BIT, 0.5f, nullptr}, {VK_QUEUE_COMPUTE_BIT, 0.5f, nullptr}, {VK_QUEUE_TRANSFER_BIT, 1.0f, nullptr}, {VK_QUEUE_TRANSFER_BIT, 1.0f, nullptr}, {VK_QUEUE_TRANSFER_BIT, 1.0f, nullptr}, {VK_QUEUE_TRANSFER_BIT, 1.0f, nullptr}, }; createInfo.queueRequirementCount = std::size(requirements); createInfo.pQueueRequirements = requirements; createInfo.pVulkanFunctions = &functions; VqsQuery query; REQUIRE( vqsCreateQuery(&createInfo, &query) == VK_SUCCESS ); REQUIRE( vqsPerformQuery(query) == VK_SUCCESS ); std::vector<VqsQueueSelection> selections; selections.resize(std::size(requirements)); vqsGetQueueSelections(query, selections.data()); printf("Selections:\n"); for(const VqsQueueSelection &i : selections) { printf("{familyIndex:%d, queueIndex:%d, presentFamilyIndex:%d, presentQueueIndex:%d}\n", i.queueFamilyIndex, i.queueIndex, i.presentQueueFamilyIndex, i.presentQueueIndex); } uint32_t queueCreateInfoCount, queuePriorityCount; vqsEnumerateDeviceQueueCreateInfos(query, &queueCreateInfoCount, nullptr, &queuePriorityCount, nullptr); std::vector<VkDeviceQueueCreateInfo> queueCreateInfos(queueCreateInfoCount); std::vector<float> queuePriorities(queuePriorityCount); vqsEnumerateDeviceQueueCreateInfos(query, &queueCreateInfoCount, queueCreateInfos.data(), &queuePriorityCount, queuePriorities.data()); printf("Creations:\n"); for(const VkDeviceQueueCreateInfo &i : queueCreateInfos) { printf("{familyIndex:%u, queueCount:%u, queuePriorities:[", i.queueFamilyIndex, i.queueCount); for(uint32_t j = 0; j < i.queueCount; ++j) { printf("%.2f", i.pQueuePriorities[j]); if(j < i.queueCount - 1) printf(", "); } printf("]}\n"); } vqsDestroyQuery(query); REQUIRE( queueCreateInfos[2].queueCount == 2 ); REQUIRE( selections[11].queueFamilyIndex == 3 ); }
39.951923
161
0.776895
AdamYuan
908b760caceee96667e33459d10e09fa0cb5b640
501
cpp
C++
Versuch07/Add.cpp
marvinklimke/rwth-prit1
dc070a5caa3ebd6e7604345a2c4d898d6442be96
[ "MIT" ]
1
2021-07-12T10:01:50.000Z
2021-07-12T10:01:50.000Z
Versuch07/Add.cpp
marvinklimke/rwth-prit1
dc070a5caa3ebd6e7604345a2c4d898d6442be96
[ "MIT" ]
null
null
null
Versuch07/Add.cpp
marvinklimke/rwth-prit1
dc070a5caa3ebd6e7604345a2c4d898d6442be96
[ "MIT" ]
null
null
null
/* * Add.cpp * * Created on: 02.05.2016 * Author: mklimke */ /** * \file Add.cpp * \brief This file contains the method definitions for Add-class. */ #include "Add.h" Add::Add(Expression* summand1, Expression* summand2) : left(summand1), right(summand2) { } Add::~Add() { delete left; delete right; } double Add::evaluate() const { return left->evaluate() + right->evaluate(); } std::string Add::print() const { return ("( " + left->print() + " + " + right->print() + " )"); }
14.735294
86
0.60479
marvinklimke
908e482e4512c43e8cb68f893b57c508a9a6df1f
1,706
hpp
C++
include/boost/url/rfc/host_rule.hpp
vgrigoriu/url
8911d05c35123f978e90321fea863385b63525d4
[ "BSL-1.0" ]
null
null
null
include/boost/url/rfc/host_rule.hpp
vgrigoriu/url
8911d05c35123f978e90321fea863385b63525d4
[ "BSL-1.0" ]
2
2022-01-14T23:51:59.000Z
2022-02-19T19:28:35.000Z
include/boost/url/rfc/host_rule.hpp
vgrigoriu/url
8911d05c35123f978e90321fea863385b63525d4
[ "BSL-1.0" ]
null
null
null
// // Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com) // // 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) // // Official repository: https://github.com/CPPAlliance/url // #ifndef BOOST_URL_RFC_HOST_RULE_HPP #define BOOST_URL_RFC_HOST_RULE_HPP #include <boost/url/detail/config.hpp> #include <boost/url/error_code.hpp> #include <boost/url/host_type.hpp> #include <boost/url/pct_encoding_types.hpp> #include <boost/url/string_view.hpp> #include <boost/url/ipv4_address.hpp> #include <boost/url/ipv6_address.hpp> #include <boost/url/grammar/parse_tag.hpp> namespace boost { namespace urls { /** Rule for host @par BNF @code host = IP-literal / IPv4address / reg-name @endcode @par Specification @li <a href="https://datatracker.ietf.org/doc/html/rfc3986#section-3.2.2" >3.2.2. Host (rfc3986)</a> @see @ref host_type, @ref ipv4_address, @ref ipv6_address. */ struct host_rule { urls::host_type host_type = urls::host_type::none; pct_encoded_str name; ipv4_address ipv4; ipv6_address ipv6; string_view ipvfuture; string_view host_part; friend void tag_invoke( grammar::parse_tag const&, char const*& it, char const* const end, error_code& ec, host_rule& t) noexcept { return parse(it, end, ec, t); } private: BOOST_URL_DECL static void parse( char const*& it, char const* const end, error_code& ec, host_rule& t) noexcept; }; } // urls } // boost #endif
21.871795
79
0.654748
vgrigoriu
90960b1bf3754291437e7a15a3ecad2378ed7eb3
2,339
cpp
C++
VigenerFrequencyAnalysis.cpp
baa-lamb/Kritografia01-Vigener_Frequency_Analysis
28634658969892711be3d8e1187aa34aa6d1e9c1
[ "MIT" ]
null
null
null
VigenerFrequencyAnalysis.cpp
baa-lamb/Kritografia01-Vigener_Frequency_Analysis
28634658969892711be3d8e1187aa34aa6d1e9c1
[ "MIT" ]
null
null
null
VigenerFrequencyAnalysis.cpp
baa-lamb/Kritografia01-Vigener_Frequency_Analysis
28634658969892711be3d8e1187aa34aa6d1e9c1
[ "MIT" ]
null
null
null
#include "VigenerFrequencyAnalysis.h" VigenerFrequencyAnalysis::VigenerFrequencyAnalysis(std::string pathIn, std::string pathOut, std::string pathExample, int keySize) { finEncrypt_.open(pathIn); finExample_.open(pathExample); foutOutput_.open(pathOut); keySize_ = keySize; } VigenerFrequencyAnalysis::~VigenerFrequencyAnalysis() { finExample_.close(); finEncrypt_.close(); foutOutput_.close(); } int VigenerFrequencyAnalysis::getMax(std::map<unsigned char, double> statistic) { double max = -1.000; int symbol = 0; for (auto it = statistic.begin(); it != statistic.end(); it++) { if (max < it->second) { max = it->second; symbol = it->first; } } return symbol; } std::map<unsigned char, double> VigenerFrequencyAnalysis::getStatistics(std::ifstream &file, int start, int step) { file.clear(); file.seekg(0, std::ios::beg); std::map<unsigned char, double> statistics; int symbol = 0; int count = -1; while ((symbol = file.get()) != EOF) { count++; if (count != start) continue; start += step; if (statistics.find(symbol) == statistics.end()) statistics.insert(std::pair<unsigned char, double>(symbol, 1.000)); else statistics[symbol]++; } for (auto it = statistics.begin(); it != statistics.end(); ++it) it->second = ((it->second * 100.000) / (double) count); return statistics; } std::string VigenerFrequencyAnalysis::decipherByAnalisis() { if (!finExample_.is_open()) std::cout << "example file can't open" << std::endl; else { std::map<unsigned char, double> statisticExample = getStatistics(finExample_, 0, 1); int maxSymbolExamle = getMax(statisticExample); std::string key = ""; for (int i = 0; i < keySize_; i++) { std::map<unsigned char, double> statisticEncrypt = getStatistics(finEncrypt_, i, keySize_); int maxSymbolEncrypt = getMax(statisticEncrypt); int newSymbolInKey = (maxSymbolEncrypt - maxSymbolExamle - 32) % 223; while(newSymbolInKey < 0) newSymbolInKey += 223; key += (char) newSymbolInKey; } return key; } }
33.898551
115
0.598119
baa-lamb
909636dcae0e0a32d1cdf0ff3f84fc33c4e83185
3,794
cpp
C++
src/client/graphical/gui/gui_button.cpp
arthurmco/familyline
849eee40cff266af9a3f848395ed139b7ce66197
[ "MIT" ]
6
2018-05-11T23:16:02.000Z
2019-06-13T01:35:07.000Z
src/client/graphical/gui/gui_button.cpp
arthurmco/familyline
849eee40cff266af9a3f848395ed139b7ce66197
[ "MIT" ]
33
2018-05-11T14:12:22.000Z
2022-03-12T00:55:25.000Z
src/client/graphical/gui/gui_button.cpp
arthurmco/familyline
849eee40cff266af9a3f848395ed139b7ce66197
[ "MIT" ]
1
2018-12-06T23:39:55.000Z
2018-12-06T23:39:55.000Z
#include <chrono> #include <client/graphical/gui/gui_button.hpp> using namespace familyline::graphics::gui; using namespace familyline::input; Button::Button(unsigned width, unsigned height, std::string text) : width_(width), height_(height), label_(Label{1, 1, ""}) { // We set the text after we set the resize callback, so we can get the // text size correctly already when we build the button class label_.setResizeCallback([&](Control* c, size_t w, size_t h) { label_width_ = w; label_height_ = h; cairo_surface_destroy(l_canvas_); cairo_destroy(l_context_); l_canvas_ = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, w, h); l_context_ = cairo_create(l_canvas_); }); ControlAppearance ca = label_.getAppearance(); ca.fontFace = "Arial"; ca.fontSize = 20; ca.foreground = {1.0, 1.0, 1.0, 1.0}; label_.setAppearance(ca); ca.background = {0.0, 0.0, 0.0, 0.5}; ca.borderColor = {0.0, 0.0, 0.0, 1.0}; appearance_ = ca; l_canvas_ = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, width, height); l_context_ = cairo_create(l_canvas_); label_.update(l_context_, l_canvas_); label_.setText(text); } bool Button::update(cairo_t* context, cairo_surface_t* canvas) { size_t label_x = width_ / 2 - label_width_ / 2; size_t label_y = height_ / 2 - label_height_ / 2; auto [br, bg, bb, ba] = this->appearance_.background; auto [bor, bog, bob, boa] = this->appearance_.borderColor; // draw the background if (clicked_ || std::chrono::steady_clock::now() - last_click_ < std::chrono::milliseconds(100)) { cairo_set_source_rgba(context, br, bg, bb, ba * 4); } else if (hovered_) { cairo_set_source_rgba(context, br, bg, bb, ba * 2); } else { cairo_set_source_rgba(context, br, bg, bb, ba); } cairo_set_operator(context, CAIRO_OPERATOR_SOURCE); cairo_paint(context); // draw a border cairo_set_line_width(context, 6); cairo_set_source_rgba(context, bor, bog, bob, boa); cairo_rectangle(context, 0, 0, width_, height_); cairo_stroke(context); label_.update(l_context_, l_canvas_); cairo_set_operator(context, CAIRO_OPERATOR_OVER); cairo_set_source_surface(context, l_canvas_, label_x, label_y); cairo_paint(context); return true; } std::tuple<int, int> Button::getNeededSize(cairo_t* parent_context) const { return std::tie(width_, height_); } void Button::receiveEvent(const familyline::input::HumanInputAction& ev, CallbackQueue& cq) { if (std::holds_alternative<ClickAction>(ev.type)) { auto ca = std::get<ClickAction>(ev.type); clicked_ = ca.isPressed; } if (clicked_) { click_active_ = true; this->enqueueCallback(cq, click_cb_); /// BUG: if the line below is uncommented, the game crashes, probably due to some /// cross-thread access. /// /// Maybe make the GUI run in its own thread, and run the callbacks on the main thread. // click_fut_ = std::async(this->click_cb_, this); clicked_ = false; } // Separating the click action (the clicked_ variable) from the "is clicked" question // allows us to set the last click only when the user releases the click. This is a better // and more reliable way than activating it on the button down event, or when the clicked_ // is false if (click_active_) { if (!clicked_) { last_click_ = std::chrono::steady_clock::now(); click_active_ = false; } } } void Button::setText(std::string v) { label_.setText(v); } Button::~Button() { cairo_surface_destroy(l_canvas_); cairo_destroy(l_context_); }
31.616667
95
0.653927
arthurmco
90983a837d2b7730f7e5ed007ab2428911176269
377
cpp
C++
core/src/main/cpp/cv/Output.cpp
CJBuchel/NeuralNet
946ad04dacbd36ad2a7bd7489bc5d562897c06a1
[ "MIT" ]
1
2021-04-20T08:51:47.000Z
2021-04-20T08:51:47.000Z
core/src/main/cpp/cv/Output.cpp
CJBuchel/NeuralNet
946ad04dacbd36ad2a7bd7489bc5d562897c06a1
[ "MIT" ]
null
null
null
core/src/main/cpp/cv/Output.cpp
CJBuchel/NeuralNet
946ad04dacbd36ad2a7bd7489bc5d562897c06a1
[ "MIT" ]
null
null
null
#include "cv/Output.h" void Output::display(Image *image) { if (image->data.empty()) { std::cerr << "Display Error: Image empty" << std::endl; } else { // Temp (imshow doesn't work without GUI. << Coprocessor error) #ifdef COPROC // Use other means of displaying image. (Web Stream) #else cv::imshow(image->name, image->data); #endif } cv::waitKey(30); }
23.5625
66
0.639257
CJBuchel
90987ed250dfc06d8a845394343cb85ff058e03c
55,600
cpp
C++
src/game/server/tf/player_vs_environment/tf_populators.cpp
TF2V/Tf2Vintage
983d652c338dc017dca51f5bc4eee1a3d4b7ac2e
[ "Unlicense" ]
null
null
null
src/game/server/tf/player_vs_environment/tf_populators.cpp
TF2V/Tf2Vintage
983d652c338dc017dca51f5bc4eee1a3d4b7ac2e
[ "Unlicense" ]
null
null
null
src/game/server/tf/player_vs_environment/tf_populators.cpp
TF2V/Tf2Vintage
983d652c338dc017dca51f5bc4eee1a3d4b7ac2e
[ "Unlicense" ]
null
null
null
//========= Copyright � Valve LLC, All rights reserved. ======================= // // Purpose: // // $NoKeywords: $ //============================================================================= #include "cbase.h" #include "nav_mesh/tf_nav_mesh.h" #include "tf_team.h" #include "tf_obj_teleporter.h" #include "tf_obj_sentrygun.h" #include "tf_populators.h" #include "tf_population_manager.h" #include "eventqueue.h" #include "tier1/UtlSortVector.h" #include "tf_objective_resource.h" #include "tf_tank_boss.h" #include "tf_mann_vs_machine_stats.h" extern ConVar tf_populator_debug; extern ConVar tf_populator_active_buffer_range; ConVar tf_mvm_engineer_teleporter_uber_duration( "tf_mvm_engineer_teleporter_uber_duration", "5.0", FCVAR_CHEAT | FCVAR_DEVELOPMENTONLY ); ConVar tf_mvm_currency_bonus_ratio_min( "tf_mvm_currency_bonus_ratio_min", "0.95f", FCVAR_CHEAT | FCVAR_DEVELOPMENTONLY, "The minimum percentage of wave money players must collect in order to qualify for min bonus - 0.1 to 1.0. Half the bonus amount will be awarded when reaching min ratio, and half when reaching max.", true, 0.1, true, 1.0 ); ConVar tf_mvm_currency_bonus_ratio_max( "tf_mvm_currency_bonus_ratio_max", "1.f", FCVAR_CHEAT | FCVAR_DEVELOPMENTONLY, "The highest percentage of wave money players must collect in order to qualify for max bonus - 0.1 to 1.0. Half the bonus amount will be awarded when reaching min ratio, and half when reaching max.", true, 0.1, true, 1.0 ); static CHandle<CBaseEntity> s_lastTeleporter = NULL; static float s_flLastTeleportTime = -1; LINK_ENTITY_TO_CLASS( populator_internal_spawn_point, CPopulatorInternalSpawnPoint ); CHandle<CPopulatorInternalSpawnPoint> g_internalSpawnPoint = NULL; class CTFNavAreaIncursionLess { public: bool Less( const CTFNavArea *a, const CTFNavArea *b, void *pCtx ) { return a->GetIncursionDistance( TF_TEAM_BLUE ) < b->GetIncursionDistance( TF_TEAM_BLUE ); } }; //----------------------------------------------------------------------------- // Purpose: Fire off output events //----------------------------------------------------------------------------- void FireEvent( EventInfo *eventInfo, const char *eventName ) { if ( eventInfo ) { CBaseEntity *targetEntity = gEntList.FindEntityByName( NULL, eventInfo->m_target ); if ( !targetEntity ) { Warning( "WaveSpawnPopulator: Can't find target entity '%s' for %s\n", eventInfo->m_target.Access(), eventName ); } else { g_EventQueue.AddEvent( targetEntity, eventInfo->m_action, 0.0f, NULL, NULL ); } } } //----------------------------------------------------------------------------- // Purpose: Create output event pairings //----------------------------------------------------------------------------- EventInfo *ParseEvent( KeyValues *data ) { EventInfo *eventInfo = new EventInfo(); FOR_EACH_SUBKEY( data, pSubKey ) { const char *pszKey = pSubKey->GetName(); if ( !Q_stricmp( pszKey, "Target" ) ) { eventInfo->m_target.sprintf( "%s", pSubKey->GetString() ); } else if ( !Q_stricmp( pszKey, "Action" ) ) { eventInfo->m_action.sprintf( "%s", pSubKey->GetString() ); } else { Warning( "Unknown field '%s' in WaveSpawn event definition.\n", pSubKey->GetString() ); delete eventInfo; return NULL; } } return eventInfo; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- SpawnLocationResult DoTeleporterOverride( CBaseEntity *spawnEnt, Vector *vSpawnPosition, bool bClosestPointOnNav ) { CUtlVector<CBaseEntity *> activeTeleporters; FOR_EACH_VEC( IBaseObjectAutoList::AutoList(), i ) { CBaseObject *pObj = static_cast<CBaseObject *>( IBaseObjectAutoList::AutoList()[i] ); if ( pObj->GetType() != OBJ_TELEPORTER || pObj->GetTeamNumber() != TF_TEAM_MVM_BOTS ) continue; if ( pObj->IsBuilding() || pObj->HasSapper() || pObj->IsDisabled() ) continue; CObjectTeleporter *teleporter = assert_cast<CObjectTeleporter *>( pObj ); const CUtlStringList &teleportWhereNames = teleporter->m_TeleportWhere; const char *pszSpawnPointName = STRING( spawnEnt->GetEntityName() ); for ( int iTelePoints =0; iTelePoints < teleportWhereNames.Count(); ++iTelePoints ) { if ( !V_stricmp( teleportWhereNames[ iTelePoints ], pszSpawnPointName ) ) { activeTeleporters.AddToTail( teleporter ); break; } } } if ( activeTeleporters.Count() > 0 ) { int which = RandomInt( 0, activeTeleporters.Count() - 1 ); *vSpawnPosition = activeTeleporters[ which ]->WorldSpaceCenter(); s_lastTeleporter = activeTeleporters[ which ]; return SPAWN_LOCATION_TELEPORTER; } CTFNavArea *pArea = (CTFNavArea *)TheNavMesh->GetNearestNavArea( spawnEnt->WorldSpaceCenter() ); if ( pArea ) { if ( bClosestPointOnNav ) { pArea->GetClosestPointOnArea( spawnEnt->WorldSpaceCenter(), vSpawnPosition ); } else { *vSpawnPosition = pArea->GetCenter(); } return SPAWN_LOCATION_NORMAL; } return SPAWN_LOCATION_NOT_FOUND; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void OnBotTeleported( CTFBot *pBot ) { if ( gpGlobals->curtime - s_flLastTeleportTime > 0.1f ) { s_lastTeleporter->EmitSound( "MVM.Robot_Teleporter_Deliver" ); s_flLastTeleportTime = gpGlobals->curtime; } // force bot to face in the direction specified by the teleporter Vector vForward; AngleVectors( s_lastTeleporter->GetAbsAngles(), &vForward, NULL, NULL ); pBot->GetLocomotionInterface()->FaceTowards( pBot->GetAbsOrigin() + 50 * vForward ); // spy shouldn't get any effect from the teleporter if ( !pBot->IsPlayerClass( TF_CLASS_SPY ) ) { pBot->TeleportEffect(); // invading bots get uber while they leave their spawn so they don't drop their cash where players can't pick it up float flUberTime = tf_mvm_engineer_teleporter_uber_duration.GetFloat(); pBot->m_Shared.AddCond( TF_COND_INVULNERABLE, flUberTime ); pBot->m_Shared.AddCond( TF_COND_INVULNERABLE_WEARINGOFF, flUberTime ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CSpawnLocation::CSpawnLocation() { m_nRandomSeed = RandomInt( 0, 9999 ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CSpawnLocation::Parse( KeyValues *data ) { const char *pszKey = data->GetName(); const char *pszValue = data->GetString(); if ( !V_stricmp( pszKey, "Where" ) || !V_stricmp( pszKey, "ClosestPoint" ) ) { if ( !V_stricmp( pszValue, "Ahead" ) ) { m_eRelative = AHEAD; } else if ( !V_stricmp( pszValue, "Behind" ) ) { m_eRelative = BEHIND; } else if ( !V_stricmp( pszValue, "Anywhere" ) ) { m_eRelative = ANYWHERE; } else { m_bClosestPointOnNav = V_stricmp( pszKey, "ClosestPoint" ) == 0; // collect entities with given name bool bFound = false; for ( int i=0; i < ITFTeamSpawnAutoList::AutoList().Count(); ++i ) { CTFTeamSpawn *pTeamSpawn = static_cast<CTFTeamSpawn *>( ITFTeamSpawnAutoList::AutoList()[i] ); if ( !V_stricmp( STRING( pTeamSpawn->GetEntityName() ), pszValue ) ) { m_TeamSpawns.AddToTail( pTeamSpawn ); bFound = true; } } if ( !bFound ) { Warning( "Invalid Where argument '%s'\n", pszValue ); return false; } } return true; } return false; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- SpawnLocationResult CSpawnLocation::FindSpawnLocation( Vector *vSpawnPosition ) { CUtlVector< CHandle<CTFTeamSpawn> > activeSpawns; FOR_EACH_VEC( m_TeamSpawns, i ) { if ( m_TeamSpawns[i]->IsDisabled() ) continue; activeSpawns.AddToTail( m_TeamSpawns[i] ); } if ( m_nSpawnCount >= activeSpawns.Count() ) { m_nRandomSeed = RandomInt( 0, 9999 ); m_nSpawnCount = 0; } CUniformRandomStream randomSpawn; randomSpawn.SetSeed( m_nRandomSeed ); activeSpawns.Shuffle( &randomSpawn ); if ( activeSpawns.Count() > 0 ) { SpawnLocationResult result = DoTeleporterOverride( activeSpawns[ m_nSpawnCount ], vSpawnPosition, m_bClosestPointOnNav ); if ( result != SPAWN_LOCATION_NOT_FOUND ) { m_nSpawnCount++; return result; } } CTFNavArea *spawnArea = SelectSpawnArea(); if ( spawnArea ) { *vSpawnPosition = spawnArea->GetCenter(); return SPAWN_LOCATION_NORMAL; } return SPAWN_LOCATION_NOT_FOUND; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CTFNavArea *CSpawnLocation::SelectSpawnArea( void ) const { VPROF_BUDGET( __FUNCTION__, "NextBot" ); if ( m_eRelative == UNDEFINED ) return nullptr; CUtlSortVector<CTFNavArea *, CTFNavAreaIncursionLess> theaterAreas; CUtlVector<INextBot *> bots; TheNextBots().CollectAllBots( &bots ); CTFNavArea::MakeNewTFMarker(); FOR_EACH_VEC( bots, i ) { CTFBot *pBot = ToTFBot( bots[i]->GetEntity() ); if ( pBot == nullptr ) continue; if ( !pBot->IsAlive() ) continue; if ( !pBot->GetLastKnownArea() ) continue; CUtlVector<CTFNavArea *> nearbyAreas; CollectSurroundingAreas( &nearbyAreas, pBot->GetLastKnownArea(), tf_populator_active_buffer_range.GetFloat() ); FOR_EACH_VEC( nearbyAreas, j ) { CTFNavArea *pArea = nearbyAreas[i]; if ( !pArea->IsTFMarked() ) { pArea->TFMark(); if ( pArea->IsPotentiallyVisibleToTeam( TF_TEAM_BLUE ) ) continue; if ( !pArea->IsValidForWanderingPopulation() ) continue; theaterAreas.Insert( pArea ); if ( tf_populator_debug.GetBool() ) TheNavMesh->AddToSelectedSet( pArea ); } } } if ( theaterAreas.Count() == 0 ) { if ( tf_populator_debug.GetBool() ) DevMsg( "%3.2f: SelectSpawnArea: Empty theater!\n", gpGlobals->curtime ); return nullptr; } for ( int i=0; i < 5; ++i ) { int which = 0; switch ( m_eRelative ) { case AHEAD: which = Max( RandomFloat( 0.0f, 1.0f ), RandomFloat( 0.0f, 1.0f ) ) * theaterAreas.Count(); break; case BEHIND: which = ( 1.0f - Max( RandomFloat( 0.0f, 1.0f ), RandomFloat( 0.0f, 1.0f ) ) ) * theaterAreas.Count(); break; case ANYWHERE: which = RandomFloat( 0.0f, 1.0f ) * theaterAreas.Count(); break; } if ( which >= theaterAreas.Count() ) which = theaterAreas.Count() - 1; return theaterAreas[which]; } return nullptr; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CMissionPopulator::CMissionPopulator( CPopulationManager *pManager ) : m_pManager( pManager ), m_pSpawner( NULL ) { } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CMissionPopulator::~CMissionPopulator() { if ( m_pSpawner ) { delete m_pSpawner; m_pSpawner = NULL; } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CMissionPopulator::Parse( KeyValues *data ) { int nWaveDuration = 99999; FOR_EACH_SUBKEY( data, pSubKey ) { const char *pszKey = pSubKey->GetName(); if ( !V_stricmp( pszKey, "Objective" ) ) { if ( !V_stricmp( pSubKey->GetString(), "DestroySentries" ) ) { m_eMission = CTFBot::MissionType::DESTROY_SENTRIES; } else if ( !V_stricmp( pSubKey->GetString(), "Sniper" ) ) { m_eMission = CTFBot::MissionType::SNIPER; } else if ( !V_stricmp( pSubKey->GetString(), "Spy" ) ) { m_eMission = CTFBot::MissionType::SPY; } else if ( !V_stricmp( pSubKey->GetString(), "Engineer" ) ) { m_eMission = CTFBot::MissionType::ENGINEER; } else if ( !V_stricmp( pSubKey->GetString(), "SeekAndDestroy" ) ) { m_eMission = CTFBot::MissionType::DESTROY_SENTRIES; } else { Warning( "Invalid mission '%s'\n", data->GetString() ); return false; } } else if ( !V_stricmp( pszKey, "InitialCooldown" ) ) { m_flInitialCooldown = data->GetFloat(); } else if ( !V_stricmp( pszKey, "CooldownTime" ) ) { m_flCooldownDuration = data->GetFloat(); } else if ( !V_stricmp( pszKey, "BeginAtWave" ) ) { m_nStartWave = data->GetInt() - 1; } else if ( !V_stricmp( pszKey, "RunForThisManyWaves" ) ) { nWaveDuration = data->GetInt(); } else if ( !V_stricmp( pszKey, "DesiredCount" ) ) { m_nDesiredCount = data->GetInt(); } else { m_pSpawner = IPopulationSpawner::ParseSpawner( this, pSubKey ); if ( m_pSpawner == NULL ) { Warning( "Unknown attribute '%s' in Mission definition.\n", pszKey ); } } } m_nEndWave = m_nStartWave + nWaveDuration; return true; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CMissionPopulator::Update( void ) { VPROF_BUDGET( __FUNCTION__, "NextBot" ); if ( TFGameRules()->InSetup() || TFObjectiveResource()->GetMannVsMachineIsBetweenWaves() ) { m_eState = NOT_STARTED; return; } if ( m_pManager->m_nCurrentWaveIndex < m_nStartWave || m_pManager->m_nCurrentWaveIndex >= m_nEndWave ) { m_eState = NOT_STARTED; return; } if ( m_eState == NOT_STARTED ) { if ( m_flInitialCooldown > 0.0f ) { m_eState = INITIAL_COOLDOWN; m_cooldownTimer.Start( m_flInitialCooldown ); return; } m_eState = RUNNING; m_cooldownTimer.Invalidate(); } else if ( m_eState == INITIAL_COOLDOWN ) { if ( !m_cooldownTimer.IsElapsed() ) { return; } m_eState = RUNNING; m_cooldownTimer.Invalidate(); } if ( m_eMission == CTFBot::MissionType::DESTROY_SENTRIES ) { UpdateMissionDestroySentries(); } else if ( m_eMission >= CTFBot::MissionType::SNIPER && m_eMission <= CTFBot::MissionType::ENGINEER ) { UpdateMission( m_eMission ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CMissionPopulator::UnpauseSpawning( void ) { m_cooldownTimer.Start( m_flCooldownDuration ); m_checkSentriesTimer.Start( RandomFloat( 5.0f, 10.0f ) ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CMissionPopulator::UpdateMission( CTFBot::MissionType mission ) { VPROF_BUDGET( __FUNCTION__, "NextBot" ); // TODO: Move away from depending on players CUtlVector<CTFPlayer *> bots; CollectPlayers( &bots, TF_TEAM_MVM_BOTS, true ); int nActiveMissions = 0; FOR_EACH_VEC( bots, i ) { CTFBot *pBot = ToTFBot( bots[i] ); if ( pBot ) { if ( pBot->HasMission( mission ) ) nActiveMissions++; } } if ( g_pPopulationManager->IsSpawningPaused() ) return false; if ( nActiveMissions > 0 ) { m_cooldownTimer.Start( m_flCooldownDuration ); return false; } if ( !m_cooldownTimer.IsElapsed() ) return false; int nCurrentBotCount = GetGlobalTeam( TF_TEAM_MVM_BOTS )->GetNumPlayers(); if ( nCurrentBotCount + m_nDesiredCount > k_nMvMBotTeamSize ) { if ( tf_populator_debug.GetBool() ) { DevMsg( "MANN VS MACHINE: %3.2f: Waiting for slots to spawn mission.\n", gpGlobals->curtime ); } return false; } if ( tf_populator_debug.GetBool() ) { DevMsg( "MANN VS MACHINE: %3.2f: <<<< Spawning Mission >>>>\n", gpGlobals->curtime ); } int nSniperCount = 0; FOR_EACH_VEC( bots, i ) { CTFBot *pBot = ToTFBot( bots[i] ); if ( pBot && pBot->IsPlayerClass( TF_CLASS_SNIPER ) ) nSniperCount++; } for ( int i=0; i < m_nDesiredCount; ++i ) { Vector vecSpawnPos; SpawnLocationResult spawnLocationResult = m_where.FindSpawnLocation( &vecSpawnPos ); if ( spawnLocationResult != SPAWN_LOCATION_NOT_FOUND ) { CUtlVector<EHANDLE> spawnedBots; if ( m_pSpawner && m_pSpawner->Spawn( vecSpawnPos, &spawnedBots ) ) { FOR_EACH_VEC( spawnedBots, j ) { CTFBot *pBot = ToTFBot( spawnedBots[j] ); if ( pBot == NULL ) continue; pBot->SetFlagTarget( NULL ); pBot->SetMission( mission ); if ( TFObjectiveResource() ) { unsigned int iFlags = MVM_CLASS_FLAG_MISSION; if ( pBot->IsMiniBoss() ) { iFlags |= MVM_CLASS_FLAG_MINIBOSS; } if ( pBot->HasAttribute( CTFBot::AttributeType::ALWAYSCRIT ) ) { iFlags |= MVM_CLASS_FLAG_ALWAYSCRIT; } TFObjectiveResource()->IncrementMannVsMachineWaveClassCount( m_pSpawner->GetClassIcon( j ), iFlags ); } if ( TFGameRules()->IsMannVsMachineMode() ) { if ( pBot->HasMission( CTFBot::MissionType::SNIPER ) ) { nSniperCount++; if ( nSniperCount == 1 ) TFGameRules()->HaveAllPlayersSpeakConceptIfAllowed( MP_CONCEPT_MVM_SNIPER_CALLOUT, TF_TEAM_MVM_BOTS ); } } if ( spawnLocationResult == SPAWN_LOCATION_TELEPORTER ) OnBotTeleported( pBot ); } } } else if ( tf_populator_debug.GetBool() ) { Warning( "MissionPopulator: %3.2f: Skipped a member - can't find a place to spawn\n", gpGlobals->curtime ); } } m_cooldownTimer.Start( m_flCooldownDuration ); return true; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CMissionPopulator::UpdateMissionDestroySentries( void ) { VPROF_BUDGET( __FUNCTION__, "NextBot" ); if ( !m_cooldownTimer.IsElapsed() || !m_checkSentriesTimer.IsElapsed() ) return false; if ( g_pPopulationManager->IsSpawningPaused() ) return false; m_checkSentriesTimer.Start( RandomFloat( 5.0f, 10.0f ) ); int nDmgLimit = 0; int nKillLimit = 0; m_pManager->GetSentryBusterDamageAndKillThreshold( nDmgLimit, nKillLimit ); CUtlVector<CObjectSentrygun *> dangerousSentries; FOR_EACH_VEC( IBaseObjectAutoList::AutoList(), i ) { CBaseObject *pObj = static_cast<CBaseObject *>( IBaseObjectAutoList::AutoList()[i] ); if ( pObj->ObjectType() != OBJ_SENTRYGUN ) continue; if ( pObj->IsDisposableBuilding() ) continue; if ( pObj->GetTeamNumber() != TF_TEAM_MVM_BOTS ) continue; CTFPlayer *pOwner = pObj->GetOwner(); if ( pOwner ) { int nDmgDone = pOwner->GetAccumulatedSentryGunDamageDealt(); int nKillsMade = pOwner->GetAccumulatedSentryGunKillCount(); if ( nDmgDone >= nDmgLimit || nKillsMade >= nKillLimit ) { dangerousSentries.AddToTail( static_cast<CObjectSentrygun *>( pObj ) ); } } } // TODO: Move away from depending on players CUtlVector<CTFPlayer *> bots; CollectPlayers( &bots, TF_TEAM_MVM_BOTS, true ); bool bSpawned = false; FOR_EACH_VEC( dangerousSentries, i ) { CObjectSentrygun *pSentry = dangerousSentries[i]; int nValidCount = 0; FOR_EACH_VEC( bots, j ) { CTFBot *pBot = ToTFBot( bots[j] ); if ( pBot ) { if ( pBot->HasMission( CTFBot::MissionType::DESTROY_SENTRIES ) && pBot->GetMissionTarget() == pSentry ) break; } nValidCount++; } if ( nValidCount < bots.Count() ) continue; Vector vecSpawnPos; SpawnLocationResult spawnLocationResult = m_where.FindSpawnLocation( &vecSpawnPos ); if ( spawnLocationResult != SPAWN_LOCATION_NOT_FOUND ) { CUtlVector<EHANDLE> spawnedBots; if ( m_pSpawner && m_pSpawner->Spawn( vecSpawnPos, &spawnedBots ) ) { if ( tf_populator_debug.GetBool() ) { DevMsg( "MANN VS MACHINE: %3.2f: <<<< Spawning Sentry Busting Mission >>>>\n", gpGlobals->curtime ); } FOR_EACH_VEC( spawnedBots, k ) { CTFBot *pBot = ToTFBot( spawnedBots[k] ); if ( pBot == NULL ) continue; bSpawned = true; pBot->SetMission( CTFBot::MissionType::DESTROY_SENTRIES ); pBot->SetMissionTarget( pSentry ); pBot->SetFlagTarget( NULL ); pBot->SetBloodColor( DONT_BLEED ); pBot->Update(); pBot->GetPlayerClass()->SetCustomModel( "models/bots/demo/bot_sentry_buster.mdl", true ); pBot->UpdateModel(); if ( TFObjectiveResource() ) { unsigned int iFlags = MVM_CLASS_FLAG_MISSION; if ( pBot->IsMiniBoss() ) iFlags |= MVM_CLASS_FLAG_MINIBOSS; if ( pBot->HasAttribute( CTFBot::AttributeType::ALWAYSCRIT ) ) iFlags |= MVM_CLASS_FLAG_ALWAYSCRIT; TFObjectiveResource()->IncrementMannVsMachineWaveClassCount( m_pSpawner->GetClassIcon( k ), iFlags ); } if ( TFGameRules() ) TFGameRules()->HaveAllPlayersSpeakConceptIfAllowed( MP_CONCEPT_MVM_SENTRY_BUSTER, TF_TEAM_MVM_BOTS ); if ( spawnLocationResult == SPAWN_LOCATION_TELEPORTER ) OnBotTeleported( pBot ); } } } else if ( tf_populator_debug.GetBool() ) { Warning( "MissionPopulator: %3.2f: Can't find a place to spawn a sentry destroying squad\n", gpGlobals->curtime ); } } if ( bSpawned ) { float flCoolDown = m_flCooldownDuration; CWave *pWave = m_pManager->GetCurrentWave(); if ( pWave ) { pWave->m_nNumSentryBustersKilled++; if ( TFGameRules() ) { if ( pWave->m_nNumSentryBustersKilled > 1 ) { TFGameRules()->BroadcastSound( 255, "Announcer.MVM_Sentry_Buster_Alert_Another" ); } else { TFGameRules()->BroadcastSound( 255, "Announcer.MVM_Sentry_Buster_Alert" ); } } flCoolDown = m_flCooldownDuration + pWave->m_nNumSentryBustersKilled * m_flCooldownDuration; pWave->m_nNumSentryBustersKilled = 0;; } m_cooldownTimer.Start( flCoolDown ); } return bSpawned; } int CWaveSpawnPopulator::sm_reservedPlayerSlotCount = 0; //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CWaveSpawnPopulator::CWaveSpawnPopulator( CPopulationManager *pManager ) : m_pManager( pManager ), m_pSpawner( NULL ) { m_iMaxActive = 999; m_nSpawnCount = 1; m_iTotalCurrency = -1; m_startWaveEvent = NULL; m_firstSpawnEvent = NULL; m_lastSpawnEvent = NULL; m_doneEvent = NULL; m_parentWave = NULL; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CWaveSpawnPopulator::~CWaveSpawnPopulator() { if ( m_pSpawner ) { delete m_pSpawner; m_pSpawner = NULL; } delete m_startWaveEvent; delete m_firstSpawnEvent; delete m_lastSpawnEvent; delete m_doneEvent; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CWaveSpawnPopulator::Parse( KeyValues *data ) { KeyValues *pTemplate = data->FindKey( "Template" ); if ( pTemplate ) { KeyValues *pTemplateKV = m_pManager->GetTemplate( pTemplate->GetString() ); if ( pTemplateKV ) { if ( !Parse( pTemplateKV ) ) return false; } else { Warning( "Unknown Template '%s' in WaveSpawn definition\n", pTemplate->GetString() ); } } FOR_EACH_SUBKEY( data, pSubKey ) { if ( m_where.Parse( pSubKey ) ) continue; const char *pszKey = pSubKey->GetName(); if ( !V_stricmp( pszKey, "TotalCount" ) ) { m_iTotalCount = data->GetInt(); } else if ( !V_stricmp( pszKey, "MaxActive" ) ) { m_iMaxActive = data->GetInt(); } else if ( !V_stricmp( pszKey, "SpawnCount" ) ) { m_nSpawnCount = data->GetInt(); } else if ( !V_stricmp( pszKey, "WaitBeforeStarting" ) ) { m_flWaitBeforeStarting = data->GetFloat(); } else if ( !V_stricmp( pszKey, "WaitBetweenSpawns" ) ) { if ( m_flWaitBetweenSpawns != 0 && m_bWaitBetweenSpawnsAfterDeath ) { Warning( "Already specified WaitBetweenSpawnsAfterDeath time, WaitBetweenSpawns won't be used\n" ); continue; } m_flWaitBetweenSpawns = data->GetFloat(); } else if ( !V_stricmp( pszKey, "WaitBetweenSpawnsAfterDeath" ) ) { if ( m_flWaitBetweenSpawns != 0 ) { Warning( "Already specified WaitBetweenSpawns time, WaitBetweenSpawnsAfterDeath won't be used\n" ); continue; } m_bWaitBetweenSpawnsAfterDeath = true; m_flWaitBetweenSpawns = data->GetFloat(); } else if ( !V_stricmp( pszKey, "StartWaveWarningSound" ) ) { m_startWaveWarningSound.sprintf( "%s", data->GetString() ); } else if ( !V_stricmp( pszKey, "StartWaveOutput" ) ) { m_startWaveEvent = ParseEvent( data ); } else if ( !V_stricmp( pszKey, "FirstSpawnWarningSound" ) ) { m_firstSpawnWarningSound.sprintf( "%s", data->GetString() ); } else if ( !V_stricmp( pszKey, "FirstSpawnOutput" ) ) { m_firstSpawnEvent = ParseEvent( data ); } else if ( !V_stricmp( pszKey, "LastSpawnWarningSound" ) ) { m_lastSpawnWarningSound.sprintf( "%s", data->GetString() ); } else if ( !V_stricmp( pszKey, "LastSpawnOutput" ) ) { m_lastSpawnEvent = ParseEvent( data ); } else if ( !V_stricmp( pszKey, "DoneWarningSound" ) ) { m_doneWarningSound.sprintf( "%s", data->GetString() ); } else if ( !V_stricmp( pszKey, "DoneOutput" ) ) { m_doneEvent = ParseEvent( data ); } else if ( !V_stricmp( pszKey, "TotalCurrency" ) ) { m_iTotalCurrency = data->GetInt(); } else if ( !V_stricmp( pszKey, "Name" ) ) { m_name = data->GetString(); } else if ( !V_stricmp( pszKey, "WaitForAllSpawned" ) ) { m_szWaitForAllSpawned = data->GetString(); } else if ( !V_stricmp( pszKey, "WaitForAllDead" ) ) { m_szWaitForAllDead = data->GetString(); } else if ( !V_stricmp( pszKey, "Support" ) ) { m_bLimitedSupport = !V_stricmp( data->GetString(), "Limited" ); m_bSupportWave = true; } else if ( !V_stricmp( pszKey, "RandomSpawn" ) ) { m_bRandomSpawn = data->GetBool(); } else { m_pSpawner = IPopulationSpawner::ParseSpawner( this, data ); if ( m_pSpawner == NULL ) { Warning( "Unknown attribute '%s' in WaveSpawn definition.\n", pszKey ); } } m_iRemainingCurrency = m_iTotalCurrency; m_iRemainingCount = m_iTotalCount; } return true; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWaveSpawnPopulator::Update( void ) { VPROF_BUDGET( __FUNCTION__, "NextBot" ); switch ( m_eState ) { case PENDING: { m_timer.Start( m_flWaitBeforeStarting ); SetState( PRE_SPAWN_DELAY ); sm_reservedPlayerSlotCount = 0; if ( m_startWaveWarningSound.Length() > 0 ) TFGameRules()->BroadcastSound( 255, m_startWaveWarningSound ); FireEvent( m_startWaveEvent, "StartWaveOutput" ); if ( tf_populator_debug.GetBool() ) { DevMsg( "%3.2f: WaveSpawn(%s) started PRE_SPAWN_DELAY\n", gpGlobals->curtime, m_name.IsEmpty() ? "" : m_name.Get() ); } } break; case PRE_SPAWN_DELAY: { if ( !m_timer.IsElapsed() ) return; m_nNumSpawnedSoFar = 0; m_nReservedPlayerSlots = 0; SetState( SPAWNING ); if ( m_firstSpawnWarningSound.Length() > 0 ) TFGameRules()->BroadcastSound( 255, m_firstSpawnWarningSound ); FireEvent( m_firstSpawnEvent, "FirstSpawnOutput" ); if ( tf_populator_debug.GetBool() ) { DevMsg( "%3.2f: WaveSpawn(%s) started SPAWNING\n", gpGlobals->curtime, m_name.IsEmpty() ? "" : m_name.Get() ); } } break; case SPAWNING: { if ( !m_timer.IsElapsed() || g_pPopulationManager->IsSpawningPaused() ) return; if ( !m_pSpawner ) { Warning( "Invalid spawner\n" ); SetState( DONE ); return; } int nNumActive = 0; FOR_EACH_VEC( m_activeSpawns, i ) { if ( m_activeSpawns[i] && m_activeSpawns[i]->IsAlive() ) nNumActive++; } if ( m_bWaitBetweenSpawnsAfterDeath ) { if ( nNumActive != 0 ) { return; } else { if ( m_spawnLocationResult ) { m_spawnLocationResult = SPAWN_LOCATION_NOT_FOUND; if ( m_flWaitBetweenSpawns > 0 ) m_timer.Start( m_flWaitBetweenSpawns ); return; } } } if ( nNumActive >= m_iMaxActive ) return; if ( m_nReservedPlayerSlots <= 0 ) { if ( nNumActive - m_iMaxActive < m_nSpawnCount ) return; int nTotalBotCount = GetGlobalTeam( TF_TEAM_MVM_BOTS )->GetNumPlayers(); if ( nTotalBotCount + m_nSpawnCount + sm_reservedPlayerSlotCount > k_nMvMBotTeamSize ) return; sm_reservedPlayerSlotCount += m_nSpawnCount; m_nReservedPlayerSlots = m_nSpawnCount; } Vector vecSpawnPos = vec3_origin; if ( m_pSpawner && m_pSpawner->IsWhereRequired() ) { if ( m_spawnLocationResult == SPAWN_LOCATION_NOT_FOUND || m_spawnLocationResult == SPAWN_LOCATION_TELEPORTER ) { m_spawnLocationResult = m_where.FindSpawnLocation( &m_vecSpawnPosition ); if ( m_spawnLocationResult == SPAWN_LOCATION_NOT_FOUND ) return; } vecSpawnPos = m_vecSpawnPosition; if ( m_bRandomSpawn ) m_spawnLocationResult = SPAWN_LOCATION_NOT_FOUND; } CUtlVector<EHANDLE> spawnedBots; if ( m_pSpawner && m_pSpawner->Spawn( vecSpawnPos, &spawnedBots ) ) { FOR_EACH_VEC( spawnedBots, i ) { CTFBot *pBot = ToTFBot( spawnedBots[i] ); if ( pBot ) { pBot->SetCurrency( 0 ); pBot->m_pWaveSpawnPopulator = this; TFObjectiveResource()->SetMannVsMachineWaveClassActive( pBot->GetPlayerClass()->GetClassIconName() ); if ( m_bLimitedSupport ) pBot->m_bLimitedSupport = true; if ( m_spawnLocationResult == SPAWN_LOCATION_TELEPORTER ) OnBotTeleported( pBot ); } else { CTFTankBoss *pTank = dynamic_cast<CTFTankBoss *>( spawnedBots[i].Get() ); if ( pTank ) { pTank->SetCurrencyValue( 0 ); pTank->SetWaveSpawnPopulator( this ); m_parentWave->m_nNumTanksSpawned++; } } } int nNumSpawned = spawnedBots.Count(); m_nNumSpawnedSoFar += nNumSpawned; int nNumSlotsToFree = ( nNumSpawned <= m_nReservedPlayerSlots ) ? nNumSpawned : m_nReservedPlayerSlots; m_nReservedPlayerSlots -= nNumSlotsToFree; sm_reservedPlayerSlotCount -= nNumSlotsToFree; FOR_EACH_VEC( spawnedBots, i ) { CBaseEntity *pEntity = spawnedBots[i]; FOR_EACH_VEC( m_activeSpawns, j ) { if ( m_activeSpawns[j] && m_activeSpawns[j]->entindex() == pEntity->entindex() ) { Warning( "WaveSpawn duplicate entry in active vector\n" ); continue; } } m_activeSpawns.AddToTail( pEntity ); } if ( IsFinishedSpawning() ) { SetState( WAIT_FOR_ALL_DEAD ); return; } if ( m_nReservedPlayerSlots <= 0 && !m_bWaitBetweenSpawnsAfterDeath ) { m_spawnLocationResult = SPAWN_LOCATION_NOT_FOUND; if ( m_flWaitBetweenSpawns > 0 ) m_timer.Start( m_flWaitBetweenSpawns ); } return; } m_timer.Start( 1.0f ); } break; case WAIT_FOR_ALL_DEAD: { FOR_EACH_VEC( m_activeSpawns, i ) { if ( m_activeSpawns[i] && m_activeSpawns[i]->IsAlive() ) return; } SetState( DONE ); } break; } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWaveSpawnPopulator::OnPlayerKilled( CTFPlayer *pPlayer ) { m_activeSpawns.FindAndFastRemove( pPlayer ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWaveSpawnPopulator::ForceFinish( void ) { if ( m_eState < WAIT_FOR_ALL_DEAD ) { SetState( WAIT_FOR_ALL_DEAD ); } else if ( m_eState != WAIT_FOR_ALL_DEAD ) { SetState( DONE ); } FOR_EACH_VEC( m_activeSpawns, i ) { CTFBot *pBot = ToTFBot( m_activeSpawns[i] ); if ( pBot ) { pBot->ChangeTeam( TEAM_SPECTATOR, false, true ); } else { m_activeSpawns[i]->Remove(); } } m_activeSpawns.Purge(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- int CWaveSpawnPopulator::GetCurrencyAmountPerDeath( void ) { int nCurrency = 0; if ( m_bSupportWave ) { if ( m_eState == WAIT_FOR_ALL_DEAD ) m_iRemainingCount = m_activeSpawns.Count(); } if ( m_iRemainingCurrency > 0 ) { m_iRemainingCount = m_iRemainingCount <= 0 ? 1 : m_iRemainingCount; nCurrency = m_iRemainingCurrency / m_iRemainingCount--; m_iRemainingCurrency -= nCurrency; } return nCurrency; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CWaveSpawnPopulator::IsFinishedSpawning( void ) { if ( m_bSupportWave && !m_bLimitedSupport ) return false; return ( m_nNumSpawnedSoFar >= m_iTotalCount ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWaveSpawnPopulator::OnNonSupportWavesDone( void ) { if ( m_bSupportWave ) { switch ( m_eState ) { case PENDING: case PRE_SPAWN_DELAY: SetState( DONE ); break; case SPAWNING: case WAIT_FOR_ALL_DEAD: if ( TFGameRules() && ( m_iRemainingCurrency > 0 ) ) { TFGameRules()->DistributeCurrencyAmount( m_iRemainingCurrency, NULL, true, true ); m_iRemainingCurrency = 0; } SetState( WAIT_FOR_ALL_DEAD ); break; } } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWaveSpawnPopulator::SetState( InternalStateType eState ) { m_eState = eState; if ( eState == WAIT_FOR_ALL_DEAD ) { if ( m_lastSpawnWarningSound.Length() > 0 ) { TFGameRules()->BroadcastSound( 255, m_lastSpawnWarningSound ); } FireEvent( m_lastSpawnEvent, "LastSpawnOutput" ); if ( tf_populator_debug.GetBool() ) { DevMsg( "%3.2f: WaveSpawn(%s) started WAIT_FOR_ALL_DEAD\n", gpGlobals->curtime, m_name.IsEmpty() ? "" : m_name.Get() ); } } else if ( eState == DONE ) { if ( m_doneWarningSound.Length() > 0 ) { TFGameRules()->BroadcastSound( 255, m_doneWarningSound ); } FireEvent( m_doneEvent, "DoneOutput" ); if ( tf_populator_debug.GetBool() ) { DevMsg( "%3.2f: WaveSpawn(%s) DONE\n", gpGlobals->curtime, m_name.IsEmpty() ? "" : m_name.Get() ); } } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CPeriodicSpawnPopulator::CPeriodicSpawnPopulator( CPopulationManager *pManager ) : m_pManager( pManager ), m_pSpawner( NULL ) { m_flMinInterval = 30.0f; m_flMaxInterval = 30.0f; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CPeriodicSpawnPopulator::~CPeriodicSpawnPopulator() { if ( m_pSpawner ) { delete m_pSpawner; m_pSpawner = NULL; } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CPeriodicSpawnPopulator::Parse( KeyValues *data ) { FOR_EACH_SUBKEY( data, pSubKey ) { if ( m_where.Parse( pSubKey ) ) continue; const char *pszKey = pSubKey->GetName(); if ( !V_stricmp( pszKey, "When" ) ) { if ( pSubKey->GetFirstSubKey() ) { FOR_EACH_SUBKEY( pSubKey, pWhenSubKey ) { if ( !V_stricmp( pWhenSubKey->GetName(), "MinInterval" ) ) { m_flMinInterval = pWhenSubKey->GetFloat(); } else if ( !V_stricmp( pWhenSubKey->GetName(), "MaxInterval" ) ) { m_flMaxInterval = pWhenSubKey->GetFloat(); } else { Warning( "Invalid field '%s' encountered in When\n", pWhenSubKey->GetName() ); return false; } } } else { m_flMinInterval = pSubKey->GetFloat(); m_flMaxInterval = m_flMinInterval; } } else { m_pSpawner = IPopulationSpawner::ParseSpawner( this, pSubKey ); if ( m_pSpawner == NULL ) { Warning( "Unknown attribute '%s' in PeriodicSpawn definition.\n", pszKey ); } } } return true; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CPeriodicSpawnPopulator::PostInitialize( void ) { m_timer.Start( RandomFloat( m_flMinInterval, m_flMaxInterval ) ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CPeriodicSpawnPopulator::Update( void ) { if ( !m_timer.IsElapsed() || g_pPopulationManager->IsSpawningPaused() ) return; Vector vecSpawnPos; SpawnLocationResult spawnLocationResult = m_where.FindSpawnLocation( &vecSpawnPos ); if ( spawnLocationResult != SPAWN_LOCATION_NOT_FOUND ) { CUtlVector<EHANDLE> spawnedBots; if ( m_pSpawner && m_pSpawner->Spawn( vecSpawnPos, &spawnedBots ) ) { m_timer.Start( RandomFloat( m_flMinInterval, m_flMaxInterval ) ); FOR_EACH_VEC( spawnedBots, k ) { CTFBot *pBot = ToTFBot( spawnedBots[k] ); if ( pBot && spawnLocationResult == SPAWN_LOCATION_TELEPORTER ) OnBotTeleported( pBot ); } return; } } m_timer.Start( 2.0f ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CPeriodicSpawnPopulator::UnpauseSpawning( void ) { m_timer.Start( RandomFloat( m_flMinInterval, m_flMaxInterval ) ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CRandomPlacementPopulator::CRandomPlacementPopulator( CPopulationManager *pManager ) : m_pManager( pManager ), m_pSpawner( NULL ) { } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CRandomPlacementPopulator::~CRandomPlacementPopulator() { if ( m_pSpawner ) { delete m_pSpawner; m_pSpawner = NULL; } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CRandomPlacementPopulator::Parse( KeyValues *data ) { FOR_EACH_SUBKEY( data, pSubKey ) { const char *pszKey = pSubKey->GetName(); if ( !V_stricmp( pszKey, "Count" ) ) { m_iCount = pSubKey->GetInt(); } else if ( !V_stricmp( pszKey, "MinimumSeparation" ) ) { m_flMinSeparation = pSubKey->GetFloat(); } else if ( !V_stricmp( pszKey, "NavAreaFilter" ) ) { if ( !V_stricmp( pSubKey->GetString(), "SENTRY_SPOT" ) ) { m_nNavAreaFilter = TF_NAV_SENTRY_SPOT; } else if ( !V_stricmp( pSubKey->GetString(), "SNIPER_SPOT" ) ) { m_nNavAreaFilter = TF_NAV_SNIPER_SPOT; } else { Warning( "Unknown NavAreaFilter value '%s'\n", pSubKey->GetString() ); } } else { m_pSpawner = IPopulationSpawner::ParseSpawner( this, pSubKey ); if ( m_pSpawner == NULL ) { Warning( "Unknown attribute '%s' in RandomPlacement definition.\n", pszKey ); } } } return true; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CRandomPlacementPopulator::PostInitialize( void ) { CUtlVector<CTFNavArea *> markedAreas;; FOR_EACH_VEC( TheNavAreas, i ) { CTFNavArea *pArea = (CTFNavArea *)TheNavAreas[i]; if ( pArea->HasTFAttributes( m_nNavAreaFilter ) ) markedAreas.AddToTail( pArea ); } CUtlVector<CTFNavArea *> selectedAreas; SelectSeparatedShuffleSet< CTFNavArea >( m_iCount, m_flMinSeparation, markedAreas, &selectedAreas ); if ( m_pSpawner ) { FOR_EACH_VEC( selectedAreas, i ) { m_pSpawner->Spawn( selectedAreas[i]->GetCenter() ); } } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CWave::CWave( CPopulationManager *pManager ) : m_pManager( pManager ), m_pSpawner( NULL ) { m_startWaveEvent = NULL; m_doneEvent = NULL; m_initWaveEvent = NULL; m_bCheckBonusCreditsMin = true; m_bCheckBonusCreditsMax = true; m_doneTimer.Invalidate(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CWave::~CWave() { if ( m_pSpawner ) { delete m_pSpawner; m_pSpawner = NULL; } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CWave::Parse( KeyValues *data ) { FOR_EACH_SUBKEY( data, pSubKey ) { const char *pszKey = pSubKey->GetName(); if ( !V_stricmp( pszKey, "WaveSpawn" ) ) { CWaveSpawnPopulator *pWavePopulator = new CWaveSpawnPopulator( m_pManager ); if ( !pWavePopulator->Parse( pSubKey ) ) { Warning( "Error reading WaveSpawn definition\n" ); return false; } if ( !pWavePopulator->m_bSupportWave ) m_nTotalEnemyCount += pWavePopulator->m_iTotalCount; m_iTotalCurrency += pWavePopulator->m_iTotalCurrency; pWavePopulator->m_parentWave = this; m_WaveSpawns.AddToTail( pWavePopulator ); if ( pWavePopulator->GetSpawner() ) { if ( pWavePopulator->GetSpawner()->IsVarious() ) { for ( int i = 0; i < pWavePopulator->m_iTotalCount; ++i ) { unsigned int iFlags = pWavePopulator->m_bSupportWave ? MVM_CLASS_FLAG_SUPPORT : MVM_CLASS_FLAG_NORMAL; if ( pWavePopulator->GetSpawner()->IsMiniBoss( i ) ) iFlags |= MVM_CLASS_FLAG_MINIBOSS; if ( pWavePopulator->GetSpawner()->HasAttribute( CTFBot::AttributeType::ALWAYSCRIT, i ) ) iFlags |= MVM_CLASS_FLAG_ALWAYSCRIT; if ( pWavePopulator->m_bLimitedSupport ) iFlags |= MVM_CLASS_FLAG_SUPPORT_LIMITED; AddClassType( pWavePopulator->GetSpawner()->GetClassIcon( i ), 1, iFlags ); } } else { unsigned int iFlags = pWavePopulator->m_bSupportWave ? MVM_CLASS_FLAG_SUPPORT : MVM_CLASS_FLAG_NORMAL; if ( pWavePopulator->GetSpawner()->IsMiniBoss() ) iFlags |= MVM_CLASS_FLAG_MINIBOSS; if ( pWavePopulator->GetSpawner()->HasAttribute( CTFBot::AttributeType::ALWAYSCRIT ) ) iFlags |= MVM_CLASS_FLAG_ALWAYSCRIT; if ( pWavePopulator->m_bLimitedSupport ) iFlags |= MVM_CLASS_FLAG_SUPPORT_LIMITED; AddClassType( pWavePopulator->GetSpawner()->GetClassIcon(), pWavePopulator->m_iTotalCount, iFlags ); } } } else if ( !V_stricmp( pszKey, "Sound" ) ) { m_soundName.sprintf( "%s", pSubKey->GetString() ); } else if ( !V_stricmp( pszKey, "Description" ) ) { m_description.sprintf( "%s", pSubKey->GetString() ); } else if ( !V_stricmp( pszKey, "WaitWhenDone" ) ) { m_flWaitWhenDone = pSubKey->GetFloat(); } else if ( !V_stricmp( pszKey, "Checkpoint" ) ) { } else if ( !V_stricmp( pszKey, "StartWaveOutput" ) ) { m_startWaveEvent = ParseEvent( pSubKey ); } else if ( !V_stricmp( pszKey, "DoneOutput" ) ) { m_doneEvent = ParseEvent( pSubKey ); } else if ( !V_stricmp( pszKey, "InitWaveOutput" ) ) { m_initWaveEvent = ParseEvent( pSubKey ); } else { Warning( "Unknown attribute '%s' in Wave definition.\n", pszKey ); } } return true; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWave::Update( void ) { VPROF_BUDGET( __FUNCTION__, "NextBot" ); if ( TFGameRules()->State_Get() == GR_STATE_RND_RUNNING ) { ActiveWaveUpdate(); } else if ( TFGameRules()->State_Get() == GR_STATE_BETWEEN_RNDS || TFGameRules()->State_Get() == GR_STATE_TEAM_WIN ) { WaveIntermissionUpdate(); } if ( m_bEveryWaveSpawnDone && TFGameRules()->State_Get() == GR_STATE_RND_RUNNING ) { if ( m_pManager->byte58A ) { if ( m_pManager->ehandle58C && m_pManager->ehandle58C->IsAlive() ) return; } WaveCompleteUpdate(); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWave::OnPlayerKilled( CTFPlayer *pPlayer ) { FOR_EACH_VEC( m_WaveSpawns, i ) { m_WaveSpawns[i]->OnPlayerKilled( pPlayer ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CWave::HasEventChangeAttributes( const char *pszEventName ) const { bool bHasEventChangeAttributes = false; FOR_EACH_VEC( m_WaveSpawns, i ) { bHasEventChangeAttributes |= m_WaveSpawns[i]->HasEventChangeAttributes( pszEventName ); } return bHasEventChangeAttributes; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWave::AddClassType( string_t iszClassIconName, int nCount, unsigned int iFlags ) { int nIndex = -1; FOR_EACH_VEC( m_WaveClassCounts, i ) { WaveClassCount_t const &count = m_WaveClassCounts[i]; if ( ( count.iszClassIconName == iszClassIconName ) && ( count.iFlags & iFlags ) ) { nIndex = i; break; } } if ( nIndex == -1 ) { nIndex = m_WaveClassCounts.AddToTail( {0, iszClassIconName, MVM_CLASS_FLAG_NONE} ); } m_WaveClassCounts[ nIndex ].nClassCount += nCount; m_WaveClassCounts[ nIndex ].iFlags |= iFlags; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CWaveSpawnPopulator *CWave::FindWaveSpawnPopulator( const char *name ) { FOR_EACH_VEC( m_WaveSpawns, i ) { CWaveSpawnPopulator *pPopulator = m_WaveSpawns[i]; if ( !V_stricmp( pPopulator->m_name, name ) ) return pPopulator; } return nullptr; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWave::ForceFinish() { FOR_EACH_VEC( m_WaveSpawns, i ) { m_WaveSpawns[i]->ForceFinish(); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWave::ForceReset() { m_bStarted = false; m_bFiredInitWaveOutput = false; m_bEveryWaveSpawnDone = false; m_flStartTime = 0; m_doneTimer.Invalidate(); FOR_EACH_VEC( m_WaveSpawns, i ) { m_WaveSpawns[i]->m_iRemainingCurrency = m_WaveSpawns[i]->m_iTotalCurrency; m_WaveSpawns[i]->m_iRemainingCount = m_WaveSpawns[i]->m_iTotalCount; m_WaveSpawns[i]->m_eState = CWaveSpawnPopulator::PENDING; } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CWave::IsDoneWithNonSupportWaves( void ) { FOR_EACH_VEC( m_WaveSpawns, i ) { CWaveSpawnPopulator *pPopulator = m_WaveSpawns[i]; if ( pPopulator->m_bSupportWave && pPopulator->m_eState != CWaveSpawnPopulator::DONE ) return false; } return true; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWave::ActiveWaveUpdate( void ) { VPROF_BUDGET( __FUNCTION__, "NextBot" ); if ( !m_bStarted ) { if ( m_pManager->IsInEndlessWaves() && m_flStartTime > gpGlobals->curtime ) return; m_bStarted = true; FireEvent( m_startWaveEvent, "StartWaveOutput" ); if ( m_soundName.Length() > 0 ) TFGameRules()->BroadcastSound( 255, m_soundName ); m_pManager->AdjustMinPlayerSpawnTime(); } m_bEveryWaveSpawnDone = true; FOR_EACH_VEC( m_WaveSpawns, i ) { CWaveSpawnPopulator *pPopulator = m_WaveSpawns[i]; bool bWaiting = false; if ( !pPopulator->m_szWaitForAllSpawned.IsEmpty() ) { FOR_EACH_VEC( m_WaveSpawns, j ) { CWaveSpawnPopulator *pWaitingPopulator = m_WaveSpawns[j]; if ( pWaitingPopulator == NULL ) continue; if ( V_stricmp( pWaitingPopulator->m_name, pPopulator->m_szWaitForAllSpawned ) ) continue; if ( pWaitingPopulator->m_eState <= CWaveSpawnPopulator::SPAWNING ) { bWaiting = true; break; } } } if ( !bWaiting && !pPopulator->m_szWaitForAllDead.IsEmpty() ) { FOR_EACH_VEC( m_WaveSpawns, j ) { CWaveSpawnPopulator *pWaitingPopulator = m_WaveSpawns[j]; if ( pWaitingPopulator == NULL ) continue; if ( V_stricmp( pWaitingPopulator->m_name, pPopulator->m_szWaitForAllSpawned ) ) continue; if ( pWaitingPopulator->m_eState != CWaveSpawnPopulator::DONE ) { bWaiting = true; break; } } } if ( bWaiting ) continue; pPopulator->Update(); m_bEveryWaveSpawnDone &= ( pPopulator->m_eState == CWaveSpawnPopulator::DONE ); } if ( IsDoneWithNonSupportWaves() ) { FOR_EACH_VEC( m_WaveSpawns, i ) { m_WaveSpawns[i]->OnNonSupportWavesDone(); } for ( int i = 0; i <= gpGlobals->maxClients; ++i ) { CTFPlayer *pPlayer = ToTFPlayer( UTIL_PlayerByIndex( i ) ); if ( !pPlayer || !pPlayer->IsAlive() ) continue; if ( pPlayer->GetTeamNumber() != TF_TEAM_MVM_BOTS ) continue; pPlayer->CommitSuicide( true ); } } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWave::WaveCompleteUpdate( void ) { FireEvent( m_doneEvent, "DoneOutput" ); bool bAdvancedPopfile = ( g_pPopulationManager ? g_pPopulationManager->IsAdvanced() : false ); IGameEvent *event = gameeventmanager->CreateEvent( "mvm_wave_complete" ); if ( event ) { event->SetBool( "advanced", bAdvancedPopfile ); gameeventmanager->FireEvent( event ); } if ( TFGameRules() && TFGameRules()->IsMannVsMachineMode() && bAdvancedPopfile ) { CTeamControlPointMaster *pMaster = g_hControlPointMasters.Count() ? g_hControlPointMasters[0] : NULL; if ( pMaster && ( pMaster->GetNumPoints() > 0 ) ) { if ( pMaster->GetNumPointsOwnedByTeam( TF_TEAM_MVM_BOTS ) == pMaster->GetNumPoints() ) { IGameEvent *event = gameeventmanager->CreateEvent( "mvm_adv_wave_complete_no_gates" ); if ( event ) { event->SetInt( "index", m_pManager->m_nCurrentWaveIndex ); gameeventmanager->FireEvent( event ); } } } } if ( ( m_pManager->m_nCurrentWaveIndex + 1 ) >= m_pManager->m_Waves.Count() && !m_pManager->IsInEndlessWaves() ) { m_pManager->MvMVictory(); if ( TFGameRules() ) { /*if ( GTFGCClientSystem()->dword3B8 && GTFGCClientSystem()->dword3B8->dword10 == 1 ) TFGameRules()->BroadcastSound( 255, "Announcer.MVM_Manned_Up_Wave_End" ); else*/ TFGameRules()->BroadcastSound( 255, "Announcer.MVM_Final_Wave_End" ); TFGameRules()->BroadcastSound( 255, "music.mvm_end_last_wave" ); } event = gameeventmanager->CreateEvent( "mvm_mission_complete" ); if ( event ) { event->SetString( "mission", m_pManager->GetPopulationFilename() ); gameeventmanager->FireEvent( event ); } } else { if ( TFGameRules() ) { TFGameRules()->BroadcastSound( 255, "Announcer.MVM_Wave_End" ); if ( m_nNumTanksSpawned >= 1 ) TFGameRules()->BroadcastSound( 255, "music.mvm_end_tank_wave" ); else if ( ( m_pManager->m_nCurrentWaveIndex + 1 ) >= ( m_pManager->m_Waves.Count() / 2 ) ) TFGameRules()->BroadcastSound( 255, "music.mvm_end_mid_wave" ); else TFGameRules()->BroadcastSound( 255, "music.mvm_end_wave" ); } } CReliableBroadcastRecipientFilter filter; UserMessageBegin( filter, "MVMAnnouncement" ); WRITE_CHAR( MVM_ANNOUNCEMENT_WAVE_COMPLETE ); WRITE_CHAR( m_pManager->m_nCurrentWaveIndex ); MessageEnd(); // Why does this care about the resource? if ( TFObjectiveResource() ) { CUtlVector<CTFPlayer *> players; CollectPlayers( &players, TF_TEAM_MVM_PLAYERS ); FOR_EACH_VEC( players, i ) { if ( !players[i]->IsAlive() ) players[i]->ForceRespawn(); players[i]->m_nAccumulatedSentryGunDamageDealt = 0; players[i]->m_nAccumulatedSentryGunKillCount = 0; } } m_pManager->WaveEnd( true ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWave::WaveIntermissionUpdate( void ) { if ( !m_bFiredInitWaveOutput ) { FireEvent( m_initWaveEvent, "InitWaveOutput" ); m_bFiredInitWaveOutput = true; } if ( m_upgradeAlertTimer.HasStarted() && m_upgradeAlertTimer.IsElapsed() ) { if ( ( m_bCheckBonusCreditsMin || m_bCheckBonusCreditsMax ) && gpGlobals->curtime > m_flBonusCreditsTime ) { int nWaveNum = m_pManager->m_nCurrentWaveIndex - 1; int nDropped = MannVsMachineStats_GetDroppedCredits( nWaveNum ); int nAcquired = MannVsMachineStats_GetAcquiredCredits( nWaveNum, false ); float flRatioCollected = clamp( ( (float)nAcquired / (float)nDropped ), 0.1f, 1.f ); float flMinBonus = tf_mvm_currency_bonus_ratio_min.GetFloat(); float flMaxBonus = tf_mvm_currency_bonus_ratio_max.GetFloat(); if ( m_bCheckBonusCreditsMax && nDropped > 0 && flRatioCollected >= flMaxBonus ) { int nAmount = TFGameRules()->CalculateCurrencyAmount_ByType( CURRENCY_WAVE_COLLECTION_BONUS ); TFGameRules()->DistributeCurrencyAmount( (float)nAmount * 0.5f, NULL, true, false, true ); TFGameRules()->BroadcastSound( 255, "Announcer.MVM_Bonus" ); IGameEvent *event = gameeventmanager->CreateEvent( "mvm_creditbonus_wave" ); if ( event ) { gameeventmanager->FireEvent( event ); } m_bCheckBonusCreditsMax = false; m_upgradeAlertTimer.Reset(); } if ( m_bCheckBonusCreditsMin && nDropped > 0 && flRatioCollected >= fminf( flMinBonus, flMaxBonus ) ) { int nAmount = TFGameRules()->CalculateCurrencyAmount_ByType( CURRENCY_WAVE_COLLECTION_BONUS ); TFGameRules()->DistributeCurrencyAmount( (float)nAmount * 0.5f, NULL, true, false, true ); TFGameRules()->BroadcastSound( 255, "Announcer.MVM_Bonus" ); IGameEvent *event = gameeventmanager->CreateEvent( "mvm_creditbonus_wave" ); if ( event ) { gameeventmanager->FireEvent( event ); } m_bCheckBonusCreditsMin = false; } m_flBonusCreditsTime = gpGlobals->curtime + 0.25f; } } if ( m_doneTimer.HasStarted() && m_doneTimer.IsElapsed() ) { m_doneTimer.Invalidate(); m_pManager->StartCurrentWave(); } }
27.228208
345
0.581691
TF2V
90988967ffcba91de30826913ed51391104c44d4
1,437
cc
C++
lib/dfuds-trie.cc
rockeet/taiju
90f152d5e66b1741d35b9d871f7a5db68699d48d
[ "BSD-3-Clause" ]
null
null
null
lib/dfuds-trie.cc
rockeet/taiju
90f152d5e66b1741d35b9d871f7a5db68699d48d
[ "BSD-3-Clause" ]
null
null
null
lib/dfuds-trie.cc
rockeet/taiju
90f152d5e66b1741d35b9d871f7a5db68699d48d
[ "BSD-3-Clause" ]
null
null
null
#include <taiju/dfuds-trie.h> namespace taiju { UInt64 DfudsTrie::size() const { return sizeof(TrieType) + sizeof(UInt64) + dfuds_.size() + labels_.size() + is_terminals_.size(); } void DfudsTrie::clear() { num_keys_ = 0; dfuds_.clear(); labels_.clear(); is_terminals_.clear(); } void DfudsTrie::swap(DfudsTrie *target) { std::swap(num_keys_, target->num_keys_); dfuds_.swap(&target->dfuds_); labels_.swap(&target->labels_); is_terminals_.swap(&target->is_terminals_); } const void *DfudsTrie::map(Mapper mapper, bool checks_type) { DfudsTrie temp; if (checks_type) { if (*mapper.map<TrieType>() != type()) TAIJU_THROW("failed to map DfudsTrie: wrong TrieType"); } temp.num_keys_ = *mapper.map<UInt64>(); mapper = temp.dfuds_.map(mapper); mapper = temp.labels_.map(mapper); mapper = temp.is_terminals_.map(mapper); swap(&temp); return mapper.address(); } void DfudsTrie::read(Reader reader, bool checks_type) { DfudsTrie temp; if (checks_type) { TrieType trie_type; reader.read(&trie_type); if (trie_type != type()) TAIJU_THROW("failed to read DfudsTrie: wrong TrieType"); } reader.read(&temp.num_keys_); temp.dfuds_.read(reader); temp.labels_.read(reader); temp.is_terminals_.read(reader); swap(&temp); } void DfudsTrie::write(Writer writer) const { writer.write(num_keys_); dfuds_.write(writer); labels_.write(writer); is_terminals_.write(writer); } } // namespace taiju
18.907895
59
0.707029
rockeet
909b277e2c4083b785b27724de54c5568c0e2345
1,433
cpp
C++
src/victoryconnect/cpp/packet.cpp
victoryforphil/VictoryConnect-ClientCPP
6ad06edcd6339df933af337f2fa9d111c83d6e2d
[ "MIT" ]
null
null
null
src/victoryconnect/cpp/packet.cpp
victoryforphil/VictoryConnect-ClientCPP
6ad06edcd6339df933af337f2fa9d111c83d6e2d
[ "MIT" ]
null
null
null
src/victoryconnect/cpp/packet.cpp
victoryforphil/VictoryConnect-ClientCPP
6ad06edcd6339df933af337f2fa9d111c83d6e2d
[ "MIT" ]
null
null
null
#include "packet.hpp" #include "utils.hpp" using namespace VictoryConnect; Packet::Packet(PacketType type, std::string path){ mPacketType = type; mPath = path; } Packet::Packet(PacketType type, std::string path, std::vector<std::string> data){ mPacketType = type; mPath = path; mData = data; } void Packet::addData(std::string dataToAdd){ mData.push_back(dataToAdd); } void Packet::setProtocol(std::string protocol){ mProtocol = protocol; } void Packet::setRaw(std::string raw){ mRaw = raw; } void Packet::setPath(std::string path){ mPath = path; } void Packet::setType(PacketType type){ mPacketType = type; } // Get Functions std::string Packet::getString(){ std::string final = std::to_string(mPacketType); final += " " + mPath + " " + "{"; final += Utils::vectorJoin(mData, ";"); final += "}~\n"; return final; } std::string Packet::toString(){ std::string final = getProtocol() + "->"; final += std::to_string(mPacketType); final += " " + mPath + " " + "{"; final += Utils::vectorJoin(mData, ";"); final += "}~\n"; return final; } std::string Packet::getPath(){ return mPath; } std::string Packet::getRaw(){ return mRaw; } std::string Packet::getProtocol(){ return mProtocol; } std::vector<std::string> Packet::getData(){ return mData; } PacketType Packet::getType(){ return mPacketType; }
19.630137
81
0.620377
victoryforphil
90a0153d9cd3a22ac72408efb5db7ab486547fb5
1,308
cpp
C++
NeoMathEngine/src/CrtAllocatedObject.cpp
AlinaKalyakina/neoml
328eac0d23e45faedb07a336ebfaf36288bb0db9
[ "ECL-2.0", "Apache-2.0" ]
1
2020-12-25T08:04:55.000Z
2020-12-25T08:04:55.000Z
NeoMathEngine/src/CrtAllocatedObject.cpp
AlinaKalyakina/neoml
328eac0d23e45faedb07a336ebfaf36288bb0db9
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
NeoMathEngine/src/CrtAllocatedObject.cpp
AlinaKalyakina/neoml
328eac0d23e45faedb07a336ebfaf36288bb0db9
[ "ECL-2.0", "Apache-2.0" ]
1
2020-11-05T06:46:19.000Z
2020-11-05T06:46:19.000Z
/* Copyright © 2017-2020 ABBYY Production 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 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 <common.h> #pragma hdrstop #include <stdlib.h> #include <NeoMathEngine/CrtAllocatedObject.h> #include <MathEngineCommon.h> namespace NeoML { void* CCrtAllocatedObject::operator new(size_t size) { void* result = malloc(size); if( result == 0 ) { THROW_MEMORY_EXCEPTION; } return result; } void CCrtAllocatedObject::operator delete(void* ptr) { free(ptr); } void* CCrtAllocatedObject::operator new[](size_t size) { void* result = malloc(size); if( result == 0 ) { THROW_MEMORY_EXCEPTION; } return result; } void CCrtAllocatedObject::operator delete[](void* ptr) { free(ptr); } } // namespace NeoML
24.222222
112
0.687309
AlinaKalyakina
90ace3edcc12858a6ac7a6733bbe33a075efbcc0
1,766
cpp
C++
02_estructuras_selectivas/20_pizzeria.cpp
gemboedu/ejercicios-basicos-c-
648e2abe4c8e7f51bbfb1d21032eeeee3f5b9343
[ "MIT" ]
1
2021-12-03T03:37:04.000Z
2021-12-03T03:37:04.000Z
02_estructuras_selectivas/20_pizzeria.cpp
gemboedu/ejercicios-basicos-c-
648e2abe4c8e7f51bbfb1d21032eeeee3f5b9343
[ "MIT" ]
null
null
null
02_estructuras_selectivas/20_pizzeria.cpp
gemboedu/ejercicios-basicos-c-
648e2abe4c8e7f51bbfb1d21032eeeee3f5b9343
[ "MIT" ]
null
null
null
/* 20. La pizzería Bella Rita ofrece pizzas vegetarianas y no vegetarianas a sus clientes. Los ingredientes para cada tipo de pizza aparecen a continuación. • Ingredientes vegetarianos: Pimiento y tofu. • Ingredientes no vegetarianos: Peperoni, Jamón y Salmón. Escribir un programa que pregunte al usuario si quiere una pizza vegetariana o no, y en función de su respuesta le muestre un menú con los ingredientes disponibles para que elija. Solo se puede eligir un ingrediente además de la mozzarella y el tomate que están en todas las pizzas. Al final se debe mostrar por pantalla si la pizza elegida es vegetariana o no y todos los ingredientes que lleva. */ #include <iostream> using namespace std; int main() { int tipo, ingrediente; cout << "Bienvenido a la pizzeria Bella Rita.\nTipos de pizza\n\t1- Vegetariana\n\t2- No vegetariana\n" << endl; cout << "Introduce el numero correspondiente al tipo de pizza que quieres: "; cin >> tipo; if (tipo == 1) { cout << "Ingredientes de pizzas vegetarianas\n\t1- Pimiento\n\t2- Tofu\n" << endl; cout << "Introduce el ingrediente que deseas: "; cin >> ingrediente; cout << "Pizza vegetariana con mozzarella, tomate y "; ingrediente == 1 ? cout << "pimiento" : cout << "tofu\n\n"; } else { cout << "Ingredientes de pizzas no vegetarianas\n\t1- Peperoni\n\t2- Jamon\n\t3- Salmon\n"; cout << "Introduce el ingrediente que deseas: "; cin >> ingrediente; cout << "Pizza no vegetarina con mozarrella, tomate y "; ingrediente == 1 ? cout << "peperoni" : ingrediente == 2 ? cout << "jamon" : cout << "salmon\n\n"; } return 0; }
51.941176
396
0.651755
gemboedu
90b01b0d728e3bd8671d8c7b7c7442cdb07da9b6
1,583
cpp
C++
codeforce3/505C. Mr. Kitayuta, the Treasure Hunter.cpp
khaled-farouk/My_problem_solving_solutions
46ed6481fc9b424d0714bc717cd0ba050a6638ef
[ "MIT" ]
null
null
null
codeforce3/505C. Mr. Kitayuta, the Treasure Hunter.cpp
khaled-farouk/My_problem_solving_solutions
46ed6481fc9b424d0714bc717cd0ba050a6638ef
[ "MIT" ]
null
null
null
codeforce3/505C. Mr. Kitayuta, the Treasure Hunter.cpp
khaled-farouk/My_problem_solving_solutions
46ed6481fc9b424d0714bc717cd0ba050a6638ef
[ "MIT" ]
null
null
null
/* Idea: - Dynamic Programming. - The regular DP using NxN time and memory complexity does not work. It is give correct solutions, but it does not fit the time and memory limits. - To change this solution to accepted one we need to reduce the size of our DP, we need the index where we are now, but the distance we want to jump we can always write it as d + offset, where d is the original d from the question and offset if some value maybe negative or positive. Now we can take the offset with us in the DP and leave d, but what is the lower and upper limits for offset? - To calculate this imagine that we always take the +1 step, so in the first step we are add d then add d + 1, d + 2, ..., d + x. - x value equals to ~245, why? because (d + (d + 1) + (d + 2) + ... + (d + 245)) = 30135 > 30001 (d = 1), so we can take the offset in the DP array and solve the problem. */ #include <bits/stdc++.h> using namespace std; int const N = 3e4 + 10; int n, d, a[N], dp[N][600]; int rec(int cur, int off) { if(cur >= N) return 0; int &ret = dp[cur][300 + off]; if(ret != -1) return ret; ret = 0; if(cur + d + off - 1 > cur) ret = max(ret, rec(cur + (d + off - 1), off - 1) + a[cur]); ret = max(ret, rec(cur + d + off, off) + a[cur]); ret = max(ret, rec(cur + (d + off + 1), off + 1) + a[cur]); return ret; } int main() { scanf("%d %d", &n, &d); for(int i = 0, tmp; i < n; ++i) { scanf("%d", &tmp); ++a[tmp]; } memset(dp, -1, sizeof dp); printf("%d\n", rec(d, 0)); return 0; }
31.039216
135
0.588756
khaled-farouk
ff96d791f1f830a2f1b60d637fc390d4b0c34c17
598
hpp
C++
engine/calculators/include/BlindedCalculator.hpp
sidav/shadow-of-the-wyrm
747afdeebed885b1a4f7ab42f04f9f756afd3e52
[ "MIT" ]
60
2019-08-21T04:08:41.000Z
2022-03-10T13:48:04.000Z
engine/calculators/include/BlindedCalculator.hpp
cleancoindev/shadow-of-the-wyrm
51b23e98285ecb8336324bfd41ebf00f67b30389
[ "MIT" ]
3
2021-03-18T15:11:14.000Z
2021-10-20T12:13:07.000Z
engine/calculators/include/BlindedCalculator.hpp
cleancoindev/shadow-of-the-wyrm
51b23e98285ecb8336324bfd41ebf00f67b30389
[ "MIT" ]
8
2019-11-16T06:29:05.000Z
2022-01-23T17:33:43.000Z
#pragma once #include "StatusEffectCalculator.hpp" #include "Creature.hpp" // Class used to determine whether a creature is blinded (typically by // the smoke from a flaming attack), and if so, for how long. class BlindedCalculator : public StatusEffectCalculator { public: int calculate_pct_chance_effect(CreaturePtr creature) const override; int calculate_duration_in_minutes(CreaturePtr creature) const override; protected: static const int BASE_BLINDED_DURATION_MEAN; static const int BASE_BLINDED_PCT_CHANCE; static const int BASE_BLINDED_CHANCE_HEALTH_MODIFIER; };
31.473684
75
0.795987
sidav
ff977a89d025b5e486659bc33b39ad4fd3cf31db
4,259
cpp
C++
hydra_api/SystemWin.cpp
Ray-Tracing-Systems/HydraAPI
17e812d5026b7d09df7e419658cf3a781162df55
[ "MIT" ]
18
2018-01-08T17:55:09.000Z
2021-08-02T11:22:30.000Z
hydra_api/SystemWin.cpp
Ray-Tracing-Systems/HydraAPI
17e812d5026b7d09df7e419658cf3a781162df55
[ "MIT" ]
null
null
null
hydra_api/SystemWin.cpp
Ray-Tracing-Systems/HydraAPI
17e812d5026b7d09df7e419658cf3a781162df55
[ "MIT" ]
6
2018-10-07T13:46:22.000Z
2019-07-04T09:13:14.000Z
#include "HydraAPI.h" #include "HydraInternal.h" #include <memory> #include <vector> #include <string> #include <sstream> #include <map> #ifdef WIN32 #include <direct.h> #else #endif int hr_mkdir(const char* a_folder) { return _mkdir(a_folder); } int hr_mkdir(const wchar_t* a_folder) { return _wmkdir(a_folder); } int hr_cleardir(const char* a_folder) { std::string tempFolder = std::string(a_folder) + "/"; std::string tempName = tempFolder + "*"; WIN32_FIND_DATAA fd; HANDLE hFind = ::FindFirstFileA(tempName.c_str(), &fd); if (hFind != INVALID_HANDLE_VALUE) { do { std::string tempName2 = tempFolder + fd.cFileName; DeleteFileA(tempName2.c_str()); } while (::FindNextFileA(hFind, &fd)); ::FindClose(hFind); } return 0; } int hr_cleardir(const wchar_t* a_folder) { std::wstring tempFolder = std::wstring(a_folder) + L"/"; std::wstring tempName = tempFolder + L"*"; WIN32_FIND_DATAW fd; HANDLE hFind = ::FindFirstFileW(tempName.c_str(), &fd); if (hFind != INVALID_HANDLE_VALUE) { do { std::wstring tempName2 = tempFolder + fd.cFileName; DeleteFileW(tempName2.c_str()); } while (::FindNextFileW(hFind, &fd)); ::FindClose(hFind); } return 0; } std::vector<std::wstring> hr_listfiles(const wchar_t* a_folder, bool excludeFolders) { std::vector<std::wstring> result; std::wstring tempFolder = std::wstring(a_folder) + L"/"; std::wstring tempName = tempFolder + L"*"; WIN32_FIND_DATAW fd; HANDLE hFind = ::FindFirstFileW(tempName.c_str(), &fd); if (hFind != INVALID_HANDLE_VALUE) { do { std::wstring tempName2 = tempFolder + fd.cFileName; result.push_back(tempName2); } while (::FindNextFileW(hFind, &fd)); ::FindClose(hFind); } return result; } std::vector<std::string> hr_listfiles(const char* a_folder, bool excludeFolders) { std::vector<std::string> result; std::string tempFolder = std::string(a_folder) + "/"; std::string tempName = tempFolder + "*"; WIN32_FIND_DATAA fd; HANDLE hFind = ::FindFirstFileA(tempName.c_str(), &fd); if (hFind != INVALID_HANDLE_VALUE) { do { std::string tempName2 = tempFolder + fd.cFileName; result.push_back(tempName2); } while (::FindNextFileA(hFind, &fd)); ::FindClose(hFind); } return result; } void hr_copy_file(const char* a_file1, const char* a_file2) { CopyFileA(a_file1, a_file2, FALSE); } void hr_copy_file(const wchar_t* a_file1, const wchar_t* a_file2) { CopyFileW(a_file1, a_file2, FALSE); } void hr_deletefile(const wchar_t* a_file) { DeleteFileW(a_file); } void hr_deletefile(const char* a_file) { DeleteFileA(a_file); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct HRSystemMutex { HANDLE mutex; std::string name; bool owner; }; HRSystemMutex* hr_create_system_mutex(const char* a_mutexName) { HRSystemMutex* a_mutex = new HRSystemMutex; a_mutex->mutex = OpenMutexA(MUTEX_ALL_ACCESS, FALSE, a_mutexName); if (a_mutex->mutex == NULL || a_mutex->mutex == INVALID_HANDLE_VALUE) a_mutex->mutex = CreateMutexA(NULL, FALSE, a_mutexName); return a_mutex; } void hr_free_system_mutex(HRSystemMutex*& a_mutex) // logic of this function is not strictly correct, but its ok for our usage case. { if(a_mutex == nullptr) return; if (a_mutex->mutex != INVALID_HANDLE_VALUE && a_mutex->mutex != NULL) { CloseHandle(a_mutex->mutex); a_mutex->mutex = NULL; } delete a_mutex; a_mutex = nullptr; } bool hr_lock_system_mutex(HRSystemMutex* a_mutex, int a_msToWait) { if (a_mutex == nullptr) return false; const DWORD res = WaitForSingleObject(a_mutex->mutex, a_msToWait); if (res == WAIT_TIMEOUT || res == WAIT_FAILED) return false; else return true; } void hr_unlock_system_mutex(HRSystemMutex* a_mutex) { if (a_mutex == nullptr) return; ReleaseMutex(a_mutex->mutex); } #include <fstream> void hr_ifstream_open(std::ifstream& a_stream, const wchar_t* a_fileName) { a_stream.open(a_fileName, std::ios::binary); } void hr_ofstream_open(std::ofstream& a_stream, const wchar_t* a_fileName) { a_stream.open(a_fileName, std::ios::binary); }
20.980296
132
0.666354
Ray-Tracing-Systems
ff9e8a84e79f46e7e4016ee7940334ea11585f37
10,107
cpp
C++
Alien Engine/Alien Engine/ComponentPhysics.cpp
OverPowered-Team/Alien-GameEngine
713a8846a95fdf253d0869bdcad4ecd006b2e166
[ "MIT" ]
7
2020-02-20T15:11:11.000Z
2020-05-19T00:29:04.000Z
Alien Engine/Alien Engine/ComponentPhysics.cpp
OverPowered-Team/Alien-GameEngine
713a8846a95fdf253d0869bdcad4ecd006b2e166
[ "MIT" ]
125
2020-02-29T17:17:31.000Z
2020-05-06T19:50:01.000Z
Alien Engine/Alien Engine/ComponentPhysics.cpp
OverPowered-Team/Alien-GameEngine
713a8846a95fdf253d0869bdcad4ecd006b2e166
[ "MIT" ]
1
2020-05-19T00:29:06.000Z
2020-05-19T00:29:06.000Z
#include "Application.h" #include "ComponentCharacterController.h" #include "ComponentTransform.h" #include "ComponentPhysics.h" #include "ComponentCollider.h" #include "ComponentRigidBody.h" #include "ComponentScript.h" #include "ImGuizmos/ImGuizmo.h" #include "CollisionLayers.h" #include "GameObject.h" #include "Alien.h" #include "Event.h" #include "Time.h" #include "RandomHelper.h" ComponentPhysics::ComponentPhysics(GameObject* go) : Component(go) { this->go = go; serialize = false; // Not save & load ID = (PxU32)Random::GetRandom32ID(); transform = go->GetComponent<ComponentTransform>(); state = PhysicState::DISABLED; layers = &App->physx->layers; scale = GetValidPhysicScale(); std::vector<ComponentScript*> found_script = go->GetComponents<ComponentScript>(); for (ComponentScript* script : found_script) if (script->need_alien == true) scripts.push_back(script); } ComponentPhysics::~ComponentPhysics() { if (actor) // Dettach and Delete Actor { PxU32 num_shapes = actor->getNbShapes(); PxShape* shapes[10]; actor->getShapes(shapes, num_shapes); for (PxU32 i = 0; i < num_shapes; ++i) actor->detachShape(*shapes[i]); App->physx->RemoveBody(actor); actor = nullptr; } rigid_body = nullptr; } ComponentRigidBody* ComponentPhysics::GetRigidBody() { return (rigid_body && IsDynamic()) ? rigid_body : nullptr; } void ComponentPhysics::OnEnable() { if (CheckChangeState()) UpdateBody(); } void ComponentPhysics::OnDisable() { if (CheckChangeState()) UpdateBody(); } void ComponentPhysics::Update() { GizmoManipulation(); // Check if gizmo is selected UpdatePositioning(); // Move body or gameobject } void ComponentPhysics::PostUpdate() { float3 current_scale = GetValidPhysicScale(); if (!scale.Equals(current_scale)) { scale = current_scale; go->SendAlientEventThis(this, AlienEventType::PHYSICS_SCALE_CHANGED); } } void ComponentPhysics::HandleAlienEvent(const AlienEvent& e) { switch (e.type) { case AlienEventType::SCRIPT_ADDED: { ComponentScript* script = (ComponentScript*)e.object; if (script->game_object_attached == game_object_attached && script->need_alien == true) scripts.push_back(script); break; } case AlienEventType::SCRIPT_DELETED: { ComponentScript* script = (ComponentScript*)e.object; if (script->game_object_attached == game_object_attached && script->need_alien == true) scripts.remove(script); break; } case AlienEventType::COLLIDER_DELETED: { ComponentCollider* object = (ComponentCollider*)e.object; RemoveCollider(object); break; } case AlienEventType::RIGIDBODY_DELETED: { ComponentRigidBody* object = (ComponentRigidBody*)e.object; RemoveRigidBody(object); break; } case AlienEventType::CHARACTER_CTRL_DELETED: { ComponentCharacterController* object = (ComponentCharacterController*)e.object; RemoveController(object); break; } } } bool ComponentPhysics::AddRigidBody(ComponentRigidBody* rb) { if (CheckRigidBody(rb)) { rigid_body = rb; if (CheckChangeState()) UpdateBody(); return true; } return true; } bool ComponentPhysics::RemoveRigidBody(ComponentRigidBody* rb) { if (rb == rigid_body) { rigid_body = nullptr; if (CheckChangeState()) UpdateBody(); return true; } return true; } void ComponentPhysics::SwitchedRigidBody(ComponentRigidBody* rb) { if (rb == rigid_body) if (CheckChangeState()) UpdateBody(); } void ComponentPhysics::AttachCollider(ComponentCollider* collider, bool only_update) { bool do_attach = false; if (!only_update && CheckCollider(collider) && collider->IsEnabled()) { if (CheckChangeState()) UpdateBody(); else do_attach = true; } if (actor && (do_attach || only_update)) { if (!ShapeAttached(collider->shape)) actor->attachShape(*collider->shape); WakeUp(); } } void ComponentPhysics::DettachCollider(ComponentCollider* collider, bool only_update) { bool do_dettach = false; if (!only_update && CheckCollider(collider) && !collider->IsEnabled()) { if (CheckChangeState()) UpdateBody(); else do_dettach = true; } if (actor && (do_dettach || only_update)) { if (ShapeAttached(collider->shape)) actor->detachShape(*collider->shape); WakeUp(); } } // Add Collider from Phisic System bool ComponentPhysics::AddCollider(ComponentCollider* collider) { if (CheckCollider(collider)) { if (!FindCollider(collider)) // Add Collider if is not found colliders.push_back(collider); if (CheckChangeState()) // Check if added collider change state UpdateBody(); else // Else only attach { AttachCollider(collider, true); } return true; } return false; } // Remove Collider from Phisic System bool ComponentPhysics::RemoveCollider(ComponentCollider* collider) { if (FindCollider(collider)) { colliders.remove(collider); if (CheckChangeState()) UpdateBody(); else { DettachCollider(collider, true); } return true; } return false; } bool ComponentPhysics::FindCollider(ComponentCollider* collider) { return (std::find(colliders.begin(), colliders.end(), collider) != colliders.end()); } bool ComponentPhysics::CheckCollider(ComponentCollider* collider) { return (collider != nullptr && collider->game_object_attached == game_object_attached); } bool ComponentPhysics::CheckRigidBody(ComponentRigidBody* rb) { return (rb != nullptr && rb->game_object_attached == game_object_attached); } // Controller Logic ------------------------------- bool ComponentPhysics::AddController(ComponentCharacterController* ctrl) { if (CheckController(ctrl)) // TODO: review this { character_ctrl = ctrl; return true; } return false; } bool ComponentPhysics::RemoveController(ComponentCharacterController* ctrl) { if (ctrl == character_ctrl) // TODO: review this { character_ctrl = nullptr; if (CheckChangeState()) UpdateBody(); return true; } return false; } bool ComponentPhysics::CheckController(ComponentCharacterController* ctrl) { return (ctrl != nullptr && ctrl->game_object_attached == game_object_attached); } bool ComponentPhysics::CheckChangeState() { if ( !character_ctrl && !rigid_body && colliders.empty()) { // Delete if not has physic components Destroy(); state = PhysicState::DISABLED; return true; } PhysicState new_state = PhysicState::DISABLED; if (!go->IsEnabled()) { new_state = PhysicState::DISABLED; } else if (rigid_body /*&& rigid_body->IsEnabled()*/) { new_state = PhysicState::DYNAMIC; } else if (HasEnabledColliders()) { new_state = PhysicState::STATIC; } if (new_state != state) { // If state is different state = new_state; return true; } return false; } void ComponentPhysics::UpdateBody() { if (actor) // Dettach and Delete Actor { PxU32 num_shapes = actor->getNbShapes(); PxShape* shapes[10]; // Buffer Shapes actor->getShapes(shapes, num_shapes); for (PxU32 i = 0; i < num_shapes; ++i) actor->detachShape(*shapes[i]); App->physx->RemoveBody(actor); actor = nullptr; } if (state == PhysicState::STATIC || state == PhysicState::DYNAMIC) { actor = App->physx->CreateBody(transform->GetGlobalMatrix(), IsDynamic()); if (actor == nullptr) { LOG_ENGINE("PhyX Rigid Actor Created at Infinite Transform (Scale x,y,z = 0 ? )"); state == PhysicState::INVALID_TRANS; return; } for (ComponentCollider* collider : colliders) if (collider->enabled && collider->shape) // TODO: check this actor->attachShape(*collider->shape); if (IsDynamic()) rigid_body->SetBodyProperties(); } } float3 ComponentPhysics::GetValidPhysicScale() { float3 scale = transform->GetGlobalScale(); for (int i = 0; i < 3; ++i) if (scale[i] == 0.f) scale[i] = 0.01f; return scale; } void ComponentPhysics::GizmoManipulation() { bool is_using_gizmo = ImGuizmo::IsUsing() && game_object_attached->IsSelected(); if (gizmo_selected) { if (!is_using_gizmo) { WakeUp(); gizmo_selected = false; } else PutToSleep(); } else if (is_using_gizmo) gizmo_selected = true; } void ComponentPhysics::UpdateActorTransform() { PxTransform trans; if (!F4X4_TO_PXTRANS(transform->GetGlobalMatrix(), trans)) { LOG_ENGINE("Error! GameObject %s transform is NaN or Infinite -> Physics Can't be updated "); return; } actor->setGlobalPose(trans); } void ComponentPhysics::UpdatePositioning() { if (IsDisabled()) return; if (character_ctrl && character_ctrl->IsEnabled()) { UpdateActorTransform(); PutToSleep(); return; } if ( !Time::IsPlaying() || gizmo_selected) { UpdateActorTransform(); } else { if (IsDynamic()) { PxTransform trans = actor->getGlobalPose(); // Get Controller Position transform->SetGlobalPosition(PXVEC3_TO_F3(trans.p)); transform->SetGlobalRotation(PXQUAT_TO_QUAT(trans.q)); } else { PxTransform trans; if (!F4X4_TO_PXTRANS(transform->GetGlobalMatrix(), trans)) { LOG_ENGINE("Error! GameObject %s transform is NaN or Infinite -> Physics Can't be updated "); return; } actor->setGlobalPose(trans); } } } void ComponentPhysics::WakeUp() { if (IsDynamic() && !IsKinematic()) actor->is<PxRigidDynamic>()->wakeUp(); } void ComponentPhysics::PutToSleep() { if (IsDynamic() && !IsKinematic()) actor->is<PxRigidDynamic>()->putToSleep(); } void ComponentPhysics::ChangedFilters() { if (IsDisabled()) return; //App->physx->px_scene->resetFiltering(*actor); } bool ComponentPhysics::HasEnabledColliders() { for (ComponentCollider* collider : colliders) if (collider->enabled) return true; return false; } bool ComponentPhysics::ShapeAttached(PxShape* shape) { bool ret = false; PxU32 num_shapes = actor->getNbShapes(); PxShape* shapes[10]; // Buffer Shapes actor->getShapes(shapes, num_shapes); for (PxU32 i = 0; i < num_shapes; i++) if (shapes[i] == shape) { ret = true; break; } return ret; } bool ComponentPhysics::IsDynamic() { return state == PhysicState::DYNAMIC; } bool ComponentPhysics::IsKinematic() { return state == PhysicState::DYNAMIC && rigid_body->is_kinematic; } bool ComponentPhysics::IsDisabled() { return state == PhysicState::DISABLED; }
22.661435
106
0.708519
OverPowered-Team
ff9eabb1f38c0c1d8b78ac9284894dbaabf43a6c
710
cpp
C++
gamelib/src/engine/GameTimer.cpp
alexBraidwood/my_first_game_engine
7a2d87fdef841e633ca40eae38536fd7d2b70032
[ "Zlib", "MIT" ]
null
null
null
gamelib/src/engine/GameTimer.cpp
alexBraidwood/my_first_game_engine
7a2d87fdef841e633ca40eae38536fd7d2b70032
[ "Zlib", "MIT" ]
null
null
null
gamelib/src/engine/GameTimer.cpp
alexBraidwood/my_first_game_engine
7a2d87fdef841e633ca40eae38536fd7d2b70032
[ "Zlib", "MIT" ]
null
null
null
// // Created by alex on 12/12/15. // #include <GameTimer.h> #include <chrono> using namespace engine::sdl2; using namespace std::chrono; auto Game_timer::start() -> void { is_running = true; start_time = high_resolution_clock::now(); last_dt = start_time; } auto Game_timer::stop() -> void { is_running = false; stop_time = start_time; start_time = timestamp(); } auto Game_timer::delta_time() -> float { auto current_dt = high_resolution_clock::now(); auto diff = duration_cast<nanoseconds>(current_dt - last_dt); last_dt = current_dt; float dt = diff.count() / 1000000000.f; return dt; } auto Game_timer::stopped() const -> bool { return !is_running; };
19.189189
65
0.669014
alexBraidwood
ff9f68afc3080fac603b390fbce70d02ad9b62ec
1,455
cpp
C++
qt5/group.cpp
kristjanbb/libui
e381e6b45fc421daeea6f1ed5c29a84aad13271b
[ "MIT" ]
3
2016-07-12T12:06:15.000Z
2021-05-24T22:06:45.000Z
qt5/group.cpp
kristjanbb/libui
e381e6b45fc421daeea6f1ed5c29a84aad13271b
[ "MIT" ]
null
null
null
qt5/group.cpp
kristjanbb/libui
e381e6b45fc421daeea6f1ed5c29a84aad13271b
[ "MIT" ]
null
null
null
#include "uipriv_qt5.hpp" #include <QGroupBox> #include <QVBoxLayout> struct uiGroup : public uiQt5Control {}; char *uiGroupTitle(uiGroup *g) { if (auto groupBox = uiValidateAndCastObjTo<QGroupBox>(g)) { return uiQt5StrdupQString(groupBox->title()); } return nullptr; } void uiGroupSetTitle(uiGroup *g, const char *text) { if (auto groupBox = uiValidateAndCastObjTo<QGroupBox>(g)) { groupBox->setTitle(QString::fromUtf8(text)); } } void uiGroupSetChild(uiGroup *g, uiControl *child) { if (auto groupBox = uiValidateAndCastObjTo<QGroupBox>(g)) { auto obj = uiValidateAndCastObjTo<QObject>(child); if (groupBox->layout()) { groupBox->layout()->deleteLater(); } if (auto layout = qobject_cast<QLayout*>(obj)) { groupBox->setLayout(layout); } else if (auto widget = qobject_cast<QWidget*>(obj)) { auto layout = new QVBoxLayout; layout->setMargin(0); // ? layout->addWidget(widget); groupBox->setLayout(layout); } else { qWarning("object is neither layout nor widget"); } } } int uiGroupMargined(uiGroup *g) { qWarning("TODO: %p", (void*)g); return 0; } void uiGroupSetMargined(uiGroup *g, int margined) { qWarning("TODO: %p, %d", (void*)g, margined); } uiGroup *uiNewGroup(const char *text) { auto groupBox = new QGroupBox(QString::fromUtf8(text)); // note styling is being set in main.cpp -> styleSheet return uiAllocQt5ControlType(uiGroup,groupBox,uiQt5Control::DeleteControlOnQObjectFree); }
22.734375
89
0.706529
kristjanbb
ffa088e80959e36dea0fc2b365cb86413e4f88fa
1,866
cpp
C++
HDP_HSMM/internals/cpp_eigen_code/hsmm_intnegbinvariant_sample_forwards.cpp
GUZHIXIANG/DAA_taguchi
5c77f0a326b53e0cc908cf08714fd470870877ec
[ "MIT" ]
null
null
null
HDP_HSMM/internals/cpp_eigen_code/hsmm_intnegbinvariant_sample_forwards.cpp
GUZHIXIANG/DAA_taguchi
5c77f0a326b53e0cc908cf08714fd470870877ec
[ "MIT" ]
null
null
null
HDP_HSMM/internals/cpp_eigen_code/hsmm_intnegbinvariant_sample_forwards.cpp
GUZHIXIANG/DAA_taguchi
5c77f0a326b53e0cc908cf08714fd470870877ec
[ "MIT" ]
null
null
null
using namespace Eigen; using namespace std; // inputs Map<ArrayXXd> eAT(A,M,M); Map<ArrayXXd> eaBl(aBl,M,T); Map<ArrayXXd> ebetal(betal,rtot,T); Map<ArrayXXd> esuperbetal(superbetal,M,T); // locals int t, state, substate, end; double total, pi; ArrayXd logdomain(M); ArrayXd nextstate_unsmoothed(M); ArrayXd nextstate_distr(M); ArrayXd pair(2); // code! // sample first state // logdomain = esuperbetal.col(0) + eaBl.col(0); // nextstate_distr = (logdomain - logdomain.maxCoeff()).exp() * epi0; // total = nextstate_distr.sum() * (((double)random())/((double)RAND_MAX)); // for (state=0; (total -= nextstate_distr(state)) > 0; state++) ; // stateseq[0] = state; t = 0; state = initial_superstate; substate = initial_substate; pi = ps[state]; end = end_indices[state]; while (t < T) { // loop inside the substates while ((substate < end) && (t < T)) { pair = eaBl(state,t) + ebetal.col(t).segment(substate,2); pair = (pair - pair.maxCoeff()).exp(); total = (1.0-pi)*pair(1) / ((1.0-pi)*pair(1) + pi*pair(0)); substate += (((double)random())/((double)RAND_MAX)) < total; stateseq[t] = state; t += 1; } // sample the 'end' row just like a regular HMM transition nextstate_unsmoothed = eAT.col(state); int current_state = state; while ((state == current_state) && (t < T)) { logdomain = esuperbetal.col(t) + eaBl.col(t); logdomain(state) = ebetal(end,t) + eaBl(state,t); nextstate_distr = (logdomain - logdomain.maxCoeff()).exp() * nextstate_unsmoothed; total = nextstate_distr.sum() * (((double)random())/((double)RAND_MAX)); for (state=0; (total -= nextstate_distr(state)) > 0; state++) ; stateseq[t] = current_state; t += 1; } substate = start_indices[state]; end = end_indices[state]; pi = ps[state]; }
27.441176
90
0.617363
GUZHIXIANG
ffa0e449b12fb8dae6e7a8384dce1979e101047f
1,323
cpp
C++
util/image_loader.cpp
Seviel/rinvid
0b8fbb1c0a6a5180acd9846cbf953126c05756a4
[ "BSD-2-Clause" ]
1
2020-12-31T13:36:56.000Z
2020-12-31T13:36:56.000Z
util/image_loader.cpp
Seviel/rinvid
0b8fbb1c0a6a5180acd9846cbf953126c05756a4
[ "BSD-2-Clause" ]
3
2020-11-12T21:37:03.000Z
2021-03-28T13:07:40.000Z
util/image_loader.cpp
Seviel/rinvid
0b8fbb1c0a6a5180acd9846cbf953126c05756a4
[ "BSD-2-Clause" ]
null
null
null
/********************************************************************** * Copyright (c) 2021, Filip Vasiljevic * All rights reserved. * * This file is subject to the terms and conditions of the BSD 2-Clause * License. See the file LICENSE in the root directory of the Rinvid * repository for more details. **********************************************************************/ #include <cstdint> #include <iostream> #include <string> #include <vector> #include "extern/include/stb_image.h" #include "util/include/error_handler.h" #include "util/include/image_loader.h" namespace rinvid { bool load_image(const char* file_name, std::vector<std::uint8_t>& image_data, std::int32_t& width, std::int32_t& height) { std::int32_t number_of_channels; std::uint8_t* data = stbi_load(file_name, &width, &height, &number_of_channels, STBI_rgb_alpha); if (data == NULL) { std::string error_description = "STBI: Image loading failed because: "; error_description += stbi_failure_reason(); rinvid::errors::put_error_to_log(error_description); return false; } for (std::int32_t i{0}; i < width * height * STBI_rgb_alpha; ++i) { image_data.push_back(data[i]); } stbi_image_free(data); return true; } } // namespace rinvid
27
100
0.606954
Seviel
ffa25e8758d5c9b5e23f5a4e89d10d8ead8cebca
711
cpp
C++
app/text/j.cpp
Na6ezh6a/rymanceva-testings-lab2
ce2433d3cdd2946fcc38730b5d9a7cfa721425f2
[ "MIT" ]
null
null
null
app/text/j.cpp
Na6ezh6a/rymanceva-testings-lab2
ce2433d3cdd2946fcc38730b5d9a7cfa721425f2
[ "MIT" ]
null
null
null
app/text/j.cpp
Na6ezh6a/rymanceva-testings-lab2
ce2433d3cdd2946fcc38730b5d9a7cfa721425f2
[ "MIT" ]
null
null
null
#include "_text.h" int j(text txt) { std::list<std::string>::iterator cursor_line = txt->cursor->line; std::list<std::string>::iterator cursor_next = txt->cursor->line; cursor_next++; /* Проверка на последнюю строку */ if (cursor_next == txt->lines->end()) { printf ("Невозможно. Текущая строка последняя\n"); return -1; } // /* Присоединяем следующую строку */ // strcat(cursor_line->contents, cursor_next->contents); if (cursor_next != txt->lines->end()) { /*Запоминаем указатель на следующую строку для последующего очищения */ *cursor_line += *cursor_next; txt->lines->erase(cursor_next); } return 0; }
23.7
79
0.609001
Na6ezh6a
ffa4df1e653c3200b5ca0febd08e1496988c1e7d
478
hpp
C++
include/Input/Actuator.hpp
InDieTasten/IDT.EXP
6d6229d5638297ba061b188edbbe394df33d70b0
[ "MIT" ]
null
null
null
include/Input/Actuator.hpp
InDieTasten/IDT.EXP
6d6229d5638297ba061b188edbbe394df33d70b0
[ "MIT" ]
56
2015-04-04T00:09:38.000Z
2015-08-02T23:39:13.000Z
include/Input/Actuator.hpp
InDieTasten-Legacy/--EXP-old-
6d6229d5638297ba061b188edbbe394df33d70b0
[ "MIT" ]
1
2015-05-08T19:23:51.000Z
2015-05-08T19:23:51.000Z
#ifndef _Actuator_hpp_ #define _Actuator_hpp_ #include <Utilities\Logger.hpp> #include <Utilities\Conversion.hpp> class Actuator { protected: sf::Mutex confmtx; private: virtual float getRawVector() = 0; float multiplier; float adjustment; public: Actuator(); ~Actuator(); float getControlVector(); void setMultiplier(float); void setAdjustment(float); float getMultiplier(); float getAdjustment(); }; #endif // !_Actuator_hpp_
15.419355
36
0.698745
InDieTasten
ffaf0c5b42e75c192e2d820737f4a0432e602b9f
2,297
cpp
C++
Graphs/FordFulkerson.cpp
mayukhsen1301/algos
60db47ad9e7dc28271c1ce32ca705a771e682cda
[ "MIT" ]
687
2015-02-23T17:31:00.000Z
2022-03-27T02:57:23.000Z
Graphs/FordFulkerson.cpp
mayukhsen1301/algos
60db47ad9e7dc28271c1ce32ca705a771e682cda
[ "MIT" ]
9
2018-08-27T06:41:24.000Z
2020-12-17T13:39:07.000Z
Graphs/FordFulkerson.cpp
mayukhsen1301/algos
60db47ad9e7dc28271c1ce32ca705a771e682cda
[ "MIT" ]
253
2015-03-16T00:42:18.000Z
2022-03-23T06:01:36.000Z
/******************************************************************************** MaxFlow Ford-Fulkerson algorithm. O(M|f|), |f| - maxflow value Based on problem 2783 from informatics.mccme.ru http://informatics.mccme.ru/mod/statements/view3.php?chapterid=2783#1 ********************************************************************************/ #include <iostream> #include <fstream> #include <cmath> #include <algorithm> #include <vector> #include <set> #include <map> #include <stack> #include <queue> #include <cstdlib> #include <cstdio> #include <string> #include <cstring> #include <cassert> #include <utility> #include <iomanip> using namespace std; const int MAXN = 1050; const int INF = (int) 1e9; struct edge { int from, to, f, cap; }; int n, m; vector <edge> e; vector <int> g[MAXN]; bool used[MAXN]; int s, t; int ans; void addEdge(int from, int to, int cap) { edge ed; ed.from = from; ed.to = to; ed.f = 0; ed.cap = cap; e.push_back(ed); g[from].push_back((int) e.size() - 1); ed.from = to; ed.to = from; ed.f = cap; ed.cap = cap; e.push_back(ed); g[to].push_back((int) e.size() - 1); } int pushFlow(int v, int flow = INF) { used[v] = true; if (v == t) return flow; for (int i = 0; i < (int) g[v].size(); i++) { int ind = g[v][i]; int to = e[ind].to; int f = e[ind].f; int cap = e[ind].cap; if (used[to] || cap - f == 0) continue; int pushed = pushFlow(to, min(flow, cap - f)); if (pushed > 0) { e[ind].f += pushed; e[ind ^ 1].f -= pushed; return pushed; } } return 0; } int main() { //assert(freopen("input.txt","r",stdin)); //assert(freopen("output.txt","w",stdout)); scanf("%d %d", &n, &m); s = 1; t = n; for (int i = 1; i <= m; i++) { int from, to, cap; scanf("%d %d %d", &from, &to, &cap); addEdge(from, to, cap); } while (true) { memset(used, 0, sizeof(used)); int add = pushFlow(s); if (add == 0) break; ans += add; } printf("%d\n", ans); return 0; }
21.87619
82
0.462342
mayukhsen1301
ffafe770a92b6aec62c6a1ba2819fb2ff5a60d78
936
cpp
C++
src/ArgParser.cpp
canzarlab/fortuna
62109f879a640d7154bda66ee21d9396c0d637ea
[ "BSD-2-Clause" ]
null
null
null
src/ArgParser.cpp
canzarlab/fortuna
62109f879a640d7154bda66ee21d9396c0d637ea
[ "BSD-2-Clause" ]
null
null
null
src/ArgParser.cpp
canzarlab/fortuna
62109f879a640d7154bda66ee21d9396c0d637ea
[ "BSD-2-Clause" ]
null
null
null
#include <map> #include <string> #include <iostream> typedef std::map<std::string, std::string>::const_iterator it_type; class ArgParser { public: ArgParser(const int argc, char* const argv[]) { for (int i = 0; i < argc; i++) { std::string str = argv[i]; if (str[0] != '-') continue; if (str[1] == '-') index[str.substr(2, str.length() - 2)] = " "; else if (i < argc - 1) index[str.substr(1, str.length() - 1)] = argv[++i]; } } std::string operator()(const std::string key) { if (exists(key)) return index[key]; return ""; } bool exists(const std::string key) { return index.count(key); } private: std::map<std::string, std::string> index; friend std::ostream& operator<<(std::ostream& os, const ArgParser& ap) { for(auto& it : ap.index) { os << it.first << " " << it.second << std::endl; } return os; } ArgParser() { } };
17.333333
71
0.553419
canzarlab
ffbaf092363092b9cff8f77ac40cda9f51042fdb
877
cxx
C++
test/nick4.cxx
paulwratt/cin-5.34.00
036a8202f11a4a0e29ccb10d3c02f304584cda95
[ "MIT" ]
10
2018-03-26T07:41:44.000Z
2021-11-06T08:33:24.000Z
test/nick4.cxx
paulwratt/cin-5.34.00
036a8202f11a4a0e29ccb10d3c02f304584cda95
[ "MIT" ]
null
null
null
test/nick4.cxx
paulwratt/cin-5.34.00
036a8202f11a4a0e29ccb10d3c02f304584cda95
[ "MIT" ]
1
2020-11-17T03:17:00.000Z
2020-11-17T03:17:00.000Z
/* -*- C++ -*- */ /************************************************************************* * Copyright(c) 1995~2005 Masaharu Goto ([email protected]) * * For the licensing terms see the file COPYING * ************************************************************************/ #include <stdio.h> class A { int a; public: A() { a=123; } #ifdef DEST ~A() { printf("~A() %d\n",a); } #endif int get() {return a;} }; class B { A **ppa; public: B() { #ifndef DEST ppa = NULL; #endif } void test() { ppa = new A*[3]; for(int i=0;i<3;i++) { ppa[i] = new A[i+1]; } } void disp() { for(int i=0;i<3;i++) { for(int j=0;j<i+1;j++) printf("%d\n",ppa[i][j].get()); } } ~B() { for(int i=0;i<3;i++) { delete[] ppa[i]; } delete[] ppa; } }; int main() { B b; b.test(); b.disp(); return 0; }
15.945455
74
0.380844
paulwratt
ffbb5fbcfe6fc522126c653eb4e7752067d9ad0d
2,095
cpp
C++
source/bxdf/GlossySpecular.cpp
xzrunner/raytracing
c130691a92fab2cc9605f04534f42ca9b99e6fde
[ "MIT" ]
null
null
null
source/bxdf/GlossySpecular.cpp
xzrunner/raytracing
c130691a92fab2cc9605f04534f42ca9b99e6fde
[ "MIT" ]
null
null
null
source/bxdf/GlossySpecular.cpp
xzrunner/raytracing
c130691a92fab2cc9605f04534f42ca9b99e6fde
[ "MIT" ]
null
null
null
#include "raytracing/bxdf/GlossySpecular.h" #include "raytracing/utilities/ShadeRec.h" #include "raytracing/sampler/MultiJittered.h" namespace rt { GlossySpecular::GlossySpecular() : m_cs(1, 1, 1) { } // ----------------------------------------------------------------------------------- f // no sampling here: just use the Phong formula // this is used for direct illumination only // explained on page 284 RGBColor GlossySpecular::f(const ShadeRec& sr, const Vector3D& wo, const Vector3D& wi) const { RGBColor L; float ndotwi = static_cast<float>(sr.normal * wi); Vector3D r(-wi + 2.0f * sr.normal * ndotwi); // mirror reflection direction float rdotwo = static_cast<float>(r * wo); if (rdotwo > 0.0) L = m_ks * m_cs * pow(rdotwo, m_exp); return (L); } RGBColor GlossySpecular::rho(const ShadeRec& sr, const Vector3D& wo) const { return BLACK; } RGBColor GlossySpecular::sample_f(const ShadeRec& sr, const Vector3D& wo, Vector3D& wi, float& pdf) const { float ndotwo = static_cast<float>(sr.normal * wo); Vector3D r = -wo + 2.0f * sr.normal * ndotwo; // direction of mirror reflection Vector3D w = r; Vector3D u = Vector3D(0.00424, 1, 0.00764) ^ w; u.Normalize(); Vector3D v = u ^ w; Point3D sp = m_sampler->SampleHemisphere(); wi = sp.x * u + sp.y * v + sp.z * w; // reflected ray direction if (sr.normal * wi < 0.0) // reflected ray is below tangent plane wi = -sp.x * u - sp.y * v + sp.z * w; float phong_lobe = pow((float)(r * wi), (float)m_exp); pdf = static_cast<float>(phong_lobe * (sr.normal * wi)); return (m_ks * m_cs * phong_lobe); } void GlossySpecular::SetKs(float ks) { m_ks = ks; } void GlossySpecular::SetExp(float e) { m_exp = e; } void GlossySpecular::SetCs(const RGBColor& c) { m_cs = c; } void GlossySpecular::SetSamples(int num_samples, float exp) { m_sampler = std::make_shared<MultiJittered>(num_samples); m_sampler->MapSamplesToHemisphere(exp); } void GlossySpecular::SetSampler(const std::shared_ptr<Sampler>& sampler, float exp) { m_sampler = sampler; m_sampler->MapSamplesToHemisphere(exp); } }
24.940476
105
0.661098
xzrunner
ffbcac18fe91c8b1262c48270b66f2b73ad1ac92
3,062
cc
C++
src/trap-handler/handler-outside-posix.cc
xtuc/v8
86894d98bfe79f46c51e27b0699f7bfcc07fe0b2
[ "BSD-3-Clause" ]
1
2019-05-21T13:21:59.000Z
2019-05-21T13:21:59.000Z
src/trap-handler/handler-outside-posix.cc
xtuc/v8
86894d98bfe79f46c51e27b0699f7bfcc07fe0b2
[ "BSD-3-Clause" ]
null
null
null
src/trap-handler/handler-outside-posix.cc
xtuc/v8
86894d98bfe79f46c51e27b0699f7bfcc07fe0b2
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2018 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // PLEASE READ BEFORE CHANGING THIS FILE! // // This file implements the support code for the out of bounds signal handler. // Nothing in here actually runs in the signal handler, but the code here // manipulates data structures used by the signal handler so we still need to be // careful. In order to minimize this risk, here are some rules to follow. // // 1. Avoid introducing new external dependencies. The files in src/trap-handler // should be as self-contained as possible to make it easy to audit the code. // // 2. Any changes must be reviewed by someone from the crash reporting // or security team. Se OWNERS for suggested reviewers. // // For more information, see https://goo.gl/yMeyUY. // // For the code that runs in the signal handler itself, see handler-inside.cc. #include <signal.h> #include "src/trap-handler/handler-inside-posix.h" #include "src/trap-handler/trap-handler-internal.h" namespace v8 { namespace internal { namespace trap_handler { #if V8_TRAP_HANDLER_SUPPORTED namespace { struct sigaction g_old_handler; // When using the default signal handler, we save the old one to restore in case // V8 chooses not to handle the signal. bool g_is_default_signal_handler_registered; } // namespace bool RegisterDefaultTrapHandler() { CHECK(!g_is_default_signal_handler_registered); struct sigaction action; action.sa_sigaction = HandleSignal; action.sa_flags = SA_SIGINFO; sigemptyset(&action.sa_mask); // {sigaction} installs a new custom segfault handler. On success, it returns // 0. If we get a nonzero value, we report an error to the caller by returning // false. if (sigaction(SIGSEGV, &action, &g_old_handler) != 0) { return false; } // Sanitizers often prevent us from installing our own signal handler. Attempt // to detect this and if so, refuse to enable trap handling. // // TODO(chromium:830894): Remove this once all bots support custom signal // handlers. #if defined(ADDRESS_SANITIZER) || defined(MEMORY_SANITIZER) || \ defined(THREAD_SANITIZER) || defined(LEAK_SANITIZER) || \ defined(UNDEFINED_SANITIZER) struct sigaction installed_handler; CHECK_EQ(sigaction(SIGSEGV, NULL, &installed_handler), 0); // If the installed handler does not point to HandleSignal, then // allow_user_segv_handler is 0. if (installed_handler.sa_sigaction != HandleSignal) { printf( "WARNING: sanitizers are preventing signal handler installation. " "Trap handlers are disabled.\n"); return false; } #endif g_is_default_signal_handler_registered = true; return true; } void RemoveTrapHandler() { if (g_is_default_signal_handler_registered) { if (sigaction(SIGSEGV, &g_old_handler, nullptr) == 0) { g_is_default_signal_handler_registered = false; } } } #endif // V8_TRAP_HANDLER_SUPPORTED } // namespace trap_handler } // namespace internal } // namespace v8
33.648352
80
0.743305
xtuc
ffc4a530dedd6b539b37018ee68a8e942c3a4c0e
4,809
hpp
C++
src/setup/info.hpp
kennethmyhra/innoextract
6e6d9559b500a6ddeb918a019d794b67396f1c82
[ "Zlib" ]
8
2018-04-04T06:44:51.000Z
2020-02-27T01:51:41.000Z
src/setup/info.hpp
hanul93/innoextract
6cc1708445d9848d4e88a65ef1c0df084bff31d5
[ "Zlib" ]
null
null
null
src/setup/info.hpp
hanul93/innoextract
6cc1708445d9848d4e88a65ef1c0df084bff31d5
[ "Zlib" ]
1
2018-05-02T18:10:42.000Z
2018-05-02T18:10:42.000Z
/* * Copyright (C) 2011-2014 Daniel Scharrer * * This software is provided 'as-is', without any express or implied * warranty. In no event will the author(s) be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ /*! * \file * * Central point to load all the different headers in the correct order. */ #ifndef INNOEXTRACT_SETUP_INFO_HPP #define INNOEXTRACT_SETUP_INFO_HPP #include <vector> #include <iosfwd> #include "setup/header.hpp" #include "setup/version.hpp" #include "util/flags.hpp" namespace setup { struct component_entry; struct data_entry; struct delete_entry; struct directory_entry; struct file_entry; struct icon_entry; struct ini_entry; struct language_entry; struct message_entry; struct permission_entry; struct registry_entry; struct run_entry; struct task_entry; struct type_entry; /*! * Class used to hold and load the various \ref setup headers. */ struct info { info(); ~info(); FLAGS(entry_types, Components, DataEntries, DeleteEntries, UninstallDeleteEntries, Directories, Files, Icons, IniEntries, Languages, Messages, Permissions, RegistryEntries, RunEntries, UninstallRunEntries, Tasks, Types, WizardImages, DecompressorDll, DecryptDll, NoSkip ); setup::version version; setup::header header; std::vector<component_entry> components; //! \c Components std::vector<data_entry> data_entries; //! \c DataEntries std::vector<delete_entry> delete_entries; //! \c DeleteEntries std::vector<delete_entry> uninstall_delete_entries; //! \c UninstallDeleteEntries std::vector<directory_entry> directories; //! \c Directories std::vector<file_entry> files; //! \c Files std::vector<icon_entry> icons; //! \c Icons std::vector<ini_entry> ini_entries; //! \c IniEntries std::vector<language_entry> languages; //! \c Languages std::vector<message_entry> messages; //! \c Messages std::vector<permission_entry> permissions; //! \c Permissions std::vector<registry_entry> registry_entries; //! \c RegistryEntries std::vector<run_entry> run_entries; //! \c RunEntries std::vector<run_entry> uninstall_run_entries; //! \c UninstallRunEntries std::vector<task_entry> tasks; //! \c Tasks std::vector<type_entry> types; //! \c Types //! Images displayed in the installer UI. //! Loading enabled by \c WizardImages std::string wizard_image; std::string wizard_image_small; //! Contents of the helper DLL used to decompress setup data in some versions. //! Loading enabled by \c DecompressorDll std::string decompressor_dll; //! Contents of the helper DLL used to decrypt setup data. //! Loading enabled by \c DecryptDll std::string decrypt_dll; /*! * Load setup headers. * * \param is The input stream to load the setup headers from. * It must already be positioned at start of \ref setup::version * identifier whose position is given by * \ref loader::offsets::header_offset. * \param entries What kinds of entries to load. */ void load(std::istream & is, entry_types entries); /*! * Load setup headers for a specific version. * * \param is The input stream to load the setup headers from. * It must already be positioned at start of the compressed headers. * The compressed headers start directly after the \ref setup::version * identifier whose position is given by * \ref loader::offsets::header_offset. * \param entries What kinds of entries to load. * \param version The setup data version of the headers. * * This function does not set the \ref version member. */ void load(std::istream & is, entry_types entries, const setup::version & version); }; } // namespace setup FLAGS_OVERLOADS(setup::info::entry_types) #endif // INNOEXTRACT_SETUP_INFO_HPP
31.847682
86
0.678519
kennethmyhra
ffc52c354efa906f952ebe3e0ef549ef25305455
861
cpp
C++
OwNetClient/cache/gdsfclock.cpp
OwNet/qtownet
bcddc85401a279e850f269cdd14e2d08dff5e02e
[ "MIT" ]
2
2016-09-28T02:23:07.000Z
2019-07-13T15:53:47.000Z
OwNetClient/cache/gdsfclock.cpp
OwNet/qtownet
bcddc85401a279e850f269cdd14e2d08dff5e02e
[ "MIT" ]
null
null
null
OwNetClient/cache/gdsfclock.cpp
OwNet/qtownet
bcddc85401a279e850f269cdd14e2d08dff5e02e
[ "MIT" ]
null
null
null
#include "gdsfclock.h" #include "qmath.h" #include "databasesettings.h" #include <QVariant> GDSFClock::GDSFClock(QObject *parent) : QObject(parent), m_lastClock(0) { m_lastClock = DatabaseSettings().value("cache_clean_clock", QString::number(0.0)).toDouble(); } double GDSFClock::getGDSFPriority(int accessCount, long size) { return lastClock() + accessCount * (100 / qLn(size + 1.1)); } double GDSFClock::lastClock() { int clock = 0; m_lastClockMutex.lock(); clock = m_lastClock; m_lastClockMutex.unlock(); return clock; } void GDSFClock::setLastClock(double clock) { m_lastClockMutex.lock(); if (clock < m_lastClock) { m_lastClockMutex.unlock(); return; } m_lastClock = clock; m_lastClockMutex.unlock(); DatabaseSettings().setValue("cache_clean_clock", QString::number(clock)); }
21.525
97
0.682927
OwNet
ffca57ec7206d38743126876fd8c527cbef53e12
7,579
cpp
C++
modules/ti.UI/gtk/gtk_menu_item_impl.cpp
pjunior/titanium
2d5846849fb33291afd73d79c117ea990b54db77
[ "Apache-2.0" ]
3
2016-03-15T23:50:35.000Z
2016-05-09T09:36:10.000Z
modules/ti.UI/gtk/gtk_menu_item_impl.cpp
pjunior/titanium
2d5846849fb33291afd73d79c117ea990b54db77
[ "Apache-2.0" ]
null
null
null
modules/ti.UI/gtk/gtk_menu_item_impl.cpp
pjunior/titanium
2d5846849fb33291afd73d79c117ea990b54db77
[ "Apache-2.0" ]
null
null
null
/** * Appcelerator Titanium - licensed under the Apache Public License 2 * see LICENSE in the root folder for details on the license. * Copyright (c) 2009 Appcelerator, Inc. All Rights Reserved. */ #include "../ui_module.h" namespace ti { void menu_callback(gpointer data); GtkMenuItemImpl::GtkMenuItemImpl() : parent(NULL) { } void GtkMenuItemImpl::SetParent(GtkMenuItemImpl* parent) { this->parent = parent; } GtkMenuItemImpl* GtkMenuItemImpl::GetParent() { return this->parent; } SharedValue GtkMenuItemImpl::AddSeparator() { GtkMenuItemImpl* item = new GtkMenuItemImpl(); item->MakeSeparator(); return this->AppendItem(item); } SharedValue GtkMenuItemImpl::AddItem(SharedValue label, SharedValue callback, SharedValue icon_url) { GtkMenuItemImpl* item = new GtkMenuItemImpl(); item->MakeItem(label, callback, icon_url); return this->AppendItem(item); } SharedValue GtkMenuItemImpl::AddSubMenu(SharedValue label, SharedValue icon_url) { GtkMenuItemImpl* item = new GtkMenuItemImpl(); item->MakeSubMenu(label, icon_url); return this->AppendItem(item); } SharedValue GtkMenuItemImpl::AppendItem(GtkMenuItemImpl* item) { item->SetParent(this); this->children.push_back(item); /* Realize the new item and add it to all existing instances */ std::vector<MenuPieces*>::iterator i = this->instances.begin(); while (i != this->instances.end()) { MenuPieces *pieces = item->Realize(false); gtk_menu_shell_append(GTK_MENU_SHELL((*i)->menu), pieces->item); gtk_widget_show(pieces->item); i++; } return MenuItem::AddToListModel(item); } GtkWidget* GtkMenuItemImpl::GetMenu() { if (this->parent == NULL) // top-level { MenuPieces* pieces = this->Realize(false); return pieces->menu; } else { // For now we do not support using a submenu as a menu, // as that makes determining parent-child relationships // really hard, so just return NULL and check above. return NULL; } } GtkWidget* GtkMenuItemImpl::GetMenuBar() { if (this->parent == NULL) // top level { MenuPieces* pieces = this->Realize(true); return pieces->menu; } else { // For now we do not support using a submenu as a menu, // as that makes determining parent-child relationships // really hard, so just return NULL and check above. return NULL; } } void GtkMenuItemImpl::AddChildrenTo(GtkWidget* menu) { std::vector<GtkMenuItemImpl*>::iterator c; for (c = this->children.begin(); c != this->children.end(); c++) { MenuPieces* pieces = new MenuPieces(); (*c)->MakeMenuPieces(*pieces); gtk_menu_shell_append(GTK_MENU_SHELL(menu), pieces->item); gtk_widget_show(pieces->item); if (this->IsSubMenu() || this->parent == NULL) { (*c)->AddChildrenTo(pieces->menu); } delete pieces; } } void GtkMenuItemImpl::ClearRealization(GtkWidget *parent_menu) { std::vector<MenuPieces*>::iterator i; std::vector<GtkMenuItemImpl*>::iterator c; // Find the instance which is contained in parent_menu or, // if we are the root, find the instance which uses this // menu to contain it's children. for (i = this->instances.begin(); i != this->instances.end(); i++) { if ((*i)->parent_menu == parent_menu || (this->parent == NULL && (*i)->menu == parent_menu)) break; } // Could not find an instance which uses the menu. if (i == this->instances.end()) return; // Erase all children which use // the sub-menu as their parent. for (c = this->children.begin(); c != this->children.end(); c++) { (*c)->ClearRealization((*i)->menu); } this->instances.erase(i); // Erase the instance } GtkMenuItemImpl::MenuPieces* GtkMenuItemImpl::Realize(bool is_menu_bar) { MenuPieces* pieces = new MenuPieces(); if (this->parent == NULL) // top-level { if (is_menu_bar) pieces->menu = gtk_menu_bar_new(); else pieces->menu = gtk_menu_new(); } else { this->MakeMenuPieces(*pieces); } /* Realize this widget's children */ if (this->IsSubMenu() || this->parent == NULL) { std::vector<GtkMenuItemImpl*>::iterator i = this->children.begin(); while (i != this->children.end()) { MenuPieces* child_pieces = (*i)->Realize(false); child_pieces->parent_menu = pieces->menu; gtk_menu_shell_append( GTK_MENU_SHELL(pieces->menu), child_pieces->item); gtk_widget_show(child_pieces->item); i++; } } this->instances.push_back(pieces); return pieces; } void GtkMenuItemImpl::MakeMenuPieces(MenuPieces& pieces) { const char* label = this->GetLabel(); const char* icon_url = this->GetIconURL(); SharedString icon_path = UIModule::GetResourcePath(icon_url); SharedValue callback_val = this->RawGet("callback"); if (this->IsSeparator()) { pieces.item = gtk_separator_menu_item_new(); } else if (icon_path.isNull()) { pieces.item = gtk_menu_item_new_with_label(label); } else { pieces.item = gtk_image_menu_item_new_with_label(label); GtkWidget* image = gtk_image_new_from_file(icon_path->c_str()); gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(pieces.item), image); } if (callback_val->IsMethod()) { // The callback is stored as a property of this MenuItem // so we do not need to worry about the pointer being freed // out from under us. At some point, in threaded code we will // have to protect it with a mutex though, in the case that // the callback is fired after it has been reassigned. BoundMethod* cb = callback_val->ToMethod().get(); g_signal_connect_swapped( G_OBJECT (pieces.item), "activate", G_CALLBACK(menu_callback), (gpointer) cb); } if (this->IsSubMenu()) { pieces.menu = gtk_menu_new(); gtk_menu_item_set_submenu(GTK_MENU_ITEM(pieces.item), pieces.menu); } } /* Crazy mutations below */ void GtkMenuItemImpl::Enable() { std::vector<MenuPieces*>::iterator i = this->instances.begin(); while (i != this->instances.end()) { GtkWidget *w = (*i)->item; if (w != NULL) gtk_widget_set_sensitive(w, TRUE); i++; } } void GtkMenuItemImpl::Disable() { std::vector<MenuPieces*>::iterator i = this->instances.begin(); while (i != this->instances.end()) { GtkWidget *w = (*i)->item; if (w != NULL) gtk_widget_set_sensitive(w, FALSE); i++; } } void GtkMenuItemImpl::SetLabel(std::string label) { std::vector<MenuPieces*>::iterator i = this->instances.begin(); while (i != this->instances.end()) { GtkWidget *w = (*i)->item; if (w != NULL) { GtkWidget *menu_label = gtk_bin_get_child(GTK_BIN(w)); gtk_label_set_text(GTK_LABEL(menu_label), label.c_str()); } i++; } } void GtkMenuItemImpl::SetIcon(std::string icon_url) { std::vector<MenuPieces*>::iterator i = this->instances.begin(); SharedString icon_path = UIModule::GetResourcePath(icon_url.c_str()); while (i != this->instances.end()) { GtkWidget *w = (*i)->item; if (w != NULL && G_TYPE_FROM_INSTANCE(w) == GTK_TYPE_IMAGE_MENU_ITEM) { GtkWidget* image = gtk_image_new_from_file(icon_path->c_str()); gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(w), image); } i++; } } /* Le callback */ void menu_callback(gpointer data) { BoundMethod* cb = (BoundMethod*) data; // TODO: Handle exceptions in some way try { ValueList args; cb->Call(args); } catch(...) { std::cerr << "Menu callback failed" << std::endl; } } }
24.291667
74
0.660773
pjunior
ffcbb6c4ba1cf30efb861161a4c4a6fed66727ea
1,096
cpp
C++
src/Sound.cpp
ChrisFadden/PartyTowers
b16f822130c27b0b7eaef10626fc99f5010f6591
[ "MIT" ]
1
2015-09-26T16:36:29.000Z
2015-09-26T16:36:29.000Z
src/Sound.cpp
ChrisFadden/PartyTowers
b16f822130c27b0b7eaef10626fc99f5010f6591
[ "MIT" ]
null
null
null
src/Sound.cpp
ChrisFadden/PartyTowers
b16f822130c27b0b7eaef10626fc99f5010f6591
[ "MIT" ]
null
null
null
#include <iostream> #include "Sound.h" GameSound::GameSound() { int audio_rate = 22050; Uint16 audio_format = AUDIO_S16SYS; int audio_channels = 2; int audio_buffers = 4096; if (Mix_OpenAudio(audio_rate, audio_format, audio_channels, audio_buffers) != 0) { printf("Unable to initialize audio: %s\n", Mix_GetError()); } } void GameSound::PlaySound(char* songName) { Mix_Chunk* sound = NULL; int channel; sound = Mix_LoadWAV(songName); if (sound == NULL) { printf("Unable to load WAV file: %s\n", Mix_GetError()); } channel = Mix_PlayChannel(-1, sound, 0); if (channel == -1) { printf("Unable to play WAV file: %s\n", Mix_GetError()); } MixChunkVec.push_back(sound); channelVec.push_back(channel); return; } bool GameSound::IsPlaying(){ for(auto &i : channelVec) { if(Mix_Playing(i) != 0) return true; } return false; } GameSound::~GameSound(){ for(auto &i : MixChunkVec) { Mix_FreeChunk(i); } Mix_CloseAudio(); }
21.490196
67
0.594891
ChrisFadden
ffcd26bd9d12082c22a10c023f9d81cbbbcd2070
2,216
cpp
C++
CmnIP/sample/sample_draw_map2d.cpp
Khoronus/CmnUniverse
9cf9b4297f2fcb49330126aa1047b422144045e1
[ "MIT" ]
null
null
null
CmnIP/sample/sample_draw_map2d.cpp
Khoronus/CmnUniverse
9cf9b4297f2fcb49330126aa1047b422144045e1
[ "MIT" ]
null
null
null
CmnIP/sample/sample_draw_map2d.cpp
Khoronus/CmnUniverse
9cf9b4297f2fcb49330126aa1047b422144045e1
[ "MIT" ]
null
null
null
/** * @file sample_drawing_map2d.cpp * @brief Example of the visualization of the chart radar type. * * @section LICENSE * * 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 AUTHOR/AUTHORS 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. * * @author Alessandro Moro <[email protected]> * @bug No known bugs. * @version 1.0.0.1 * */ #include <iostream> #include "container/inc/container/container_headers.hpp" #include "draw/inc/draw/draw_headers.hpp" namespace { /** @brief Test function. */ void test() { CmnIP::draw::Map2D map; map.set_natural_size(512, 512); map.set_range(-3000, -3000, 3000, 3000); map.reset_paint(); float x = 0, y = 0; map.original2scaled(1239, 738, x, y); cv::circle(map.image(), cv::Point(x, y), 2, cv::Scalar::all(255)); float xin = 0, yin = 0; map.scaled2original(x, y, xin, yin); std::vector<cv::Point2f> points; map.scaled_marker(500, 350, 1.8, 100, points); cv::line(map.image(), points[0], points[1], cv::Scalar(0,255)); cv::line(map.image(), points[2], points[3], cv::Scalar(0,255)); map.scaled_marker(2400, 1350, 2.6, 100, points); cv::line(map.image(), points[0], points[1], cv::Scalar(0,0,255)); cv::line(map.image(), points[2], points[3], cv::Scalar(0,0,255)); std::cout << xin << " " << yin << std::endl; cv::imshow("map", map.image()); cv::waitKey(); } } // namespace #ifdef CmnLib cmnLIBRARY_TEST_MAIN(&test, "data\\MemoryLeakCPP.txt", "data\\MemoryLeakC.txt"); #else /** main */ int main(int argc, char *argv[]) { std::cout << "Test chart radar" << std::endl; test(); return 0; } #endif
29.546667
80
0.698105
Khoronus
ffcd49e8a0796b2e3bf1b808247467055f4ece88
414
cpp
C++
game/MakeWythoffTable.cpp
searchstar2017/acmtool
03392b8909a3d45f10c2711ca4ad9ba69f64a481
[ "MIT" ]
null
null
null
game/MakeWythoffTable.cpp
searchstar2017/acmtool
03392b8909a3d45f10c2711ca4ad9ba69f64a481
[ "MIT" ]
null
null
null
game/MakeWythoffTable.cpp
searchstar2017/acmtool
03392b8909a3d45f10c2711ca4ad9ba69f64a481
[ "MIT" ]
null
null
null
//n is the length of the array that required //if table[i] < i,then i means a,and table[i] means b.Else,i means b,ans table[i] means a. int* MakeWythoffTable(int n) { int k; int* table = new int[n]; int a; for(k = 0; k < n; k++) { a = k * mul; if(a >= n) break; table[a] = a + k; if(a + k < n) table[a+k] = a; } return table; }
19.714286
90
0.471014
searchstar2017
ffd61173debcf45f034afb348acf31d4d286352b
3,642
cc
C++
kv/server/raft_server.cc
yunxiao3/eraft
d68d5dbe7007c4d9cac3238af4e6e78e48d9cb5f
[ "MIT" ]
58
2021-05-20T12:56:54.000Z
2022-03-28T03:45:25.000Z
kv/server/raft_server.cc
yunxiao3/eraft
d68d5dbe7007c4d9cac3238af4e6e78e48d9cb5f
[ "MIT" ]
1
2022-01-25T04:40:20.000Z
2022-01-28T05:43:30.000Z
kv/server/raft_server.cc
yunxiao3/eraft
d68d5dbe7007c4d9cac3238af4e6e78e48d9cb5f
[ "MIT" ]
15
2021-05-20T12:56:57.000Z
2022-03-14T20:35:58.000Z
// MIT License // Copyright (c) 2021 eraft dev group // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include <kv/engines.h> #include <kv/raft_server.h> #include <kv/utils.h> #include <spdlog/spdlog.h> #include <cassert> namespace kvserver { RaftStorage::RaftStorage(std::shared_ptr<Config> conf) : conf_(conf) { this->engs_ = std::make_shared<Engines>(conf->dbPath_ + "_raft", conf->dbPath_ + "_kv"); } RaftStorage::~RaftStorage() {} bool RaftStorage::CheckResponse(raft_cmdpb::RaftCmdResponse* resp, int reqCount) {} bool RaftStorage::Write(const kvrpcpb::Context& ctx, const kvrpcpb::RawPutRequest* put) { std::shared_ptr<raft_serverpb::RaftMessage> sendMsg = std::make_shared<raft_serverpb::RaftMessage>(); // send raft message sendMsg->set_data(put->SerializeAsString()); sendMsg->set_region_id(ctx.region_id()); sendMsg->set_raft_msg_type(raft_serverpb::RaftMsgClientCmd); return this->Raft(sendMsg.get()); } StorageReader* RaftStorage::Reader(const kvrpcpb::Context& ctx) { metapb::Region region; RegionReader* regionReader = new RegionReader(this->engs_, region); this->regionReader_ = regionReader; return regionReader; } bool RaftStorage::Raft(const raft_serverpb::RaftMessage* msg) { return this->raftRouter_->SendRaftMessage(msg); } bool RaftStorage::SnapShot(raft_serverpb::RaftSnapshotData* snap) {} bool RaftStorage::Start() { // raft system init this->raftSystem_ = std::make_shared<RaftStore>(this->conf_); // router init this->raftRouter_ = this->raftSystem_->raftRouter_; // raft client init std::shared_ptr<RaftClient> raftClient = std::make_shared<RaftClient>(this->conf_); this->node_ = std::make_shared<Node>(this->raftSystem_, this->conf_); // server transport init std::shared_ptr<ServerTransport> trans = std::make_shared<ServerTransport>(raftClient, raftRouter_); if (this->node_->Start(this->engs_, trans)) { SPDLOG_INFO("raft storage start succeed!"); } else { SPDLOG_INFO("raft storage start error!"); } } RegionReader::RegionReader(std::shared_ptr<Engines> engs, metapb::Region region) { this->engs_ = engs; this->region_ = region; } RegionReader::~RegionReader() {} std::string RegionReader::GetFromCF(std::string cf, std::string key) { return Assistant::GetInstance()->GetCF(this->engs_->kvDB_, cf, key); } rocksdb::Iterator* RegionReader::IterCF(std::string cf) { return Assistant::GetInstance()->NewCFIterator(this->engs_->kvDB_, cf); } void RegionReader::Close() {} } // namespace kvserver
33.412844
80
0.720483
yunxiao3
ffda0fe56d537ad66935f32afb7cb41aed0a6644
86
hpp
C++
Framework/Interface/Include/Interface.hpp
Quanwei1992/RTR
cd4e6e056de2bd0ec7ee993b06975508a561b0d6
[ "MIT" ]
3
2021-03-30T09:02:56.000Z
2022-03-16T05:43:21.000Z
Framework/Interface/Include/Interface.hpp
Quanwei1992/RTR
cd4e6e056de2bd0ec7ee993b06975508a561b0d6
[ "MIT" ]
null
null
null
Framework/Interface/Include/Interface.hpp
Quanwei1992/RTR
cd4e6e056de2bd0ec7ee993b06975508a561b0d6
[ "MIT" ]
null
null
null
#pragma once #include "Common.hpp" #define Interface class #define implements public
14.333333
25
0.790698
Quanwei1992
ffdd3b4ee63371d21d5c4d1eb5f1ffb057f2d091
10,330
cpp
C++
src/ui_objectives.cpp
libtcod/pyromancer
ae4d4ad36246c0273fdc6e871e1f1bc72605dee4
[ "MIT" ]
null
null
null
src/ui_objectives.cpp
libtcod/pyromancer
ae4d4ad36246c0273fdc6e871e1f1bc72605dee4
[ "MIT" ]
null
null
null
src/ui_objectives.cpp
libtcod/pyromancer
ae4d4ad36246c0273fdc6e871e1f1bc72605dee4
[ "MIT" ]
null
null
null
/* * Copyright (c) 2010 Jice * 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. * * The name of Jice may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY Jice ``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 Jice 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 "main.hpp" #define OBJ_WIDTH (CON_W-4) #define OBJ_HEIGHT 40 Objective::Objective(const char *title, const char *description, const char *enableScript, const char *successScript, bool mainObjective) : title(title),description(description), enableScript(enableScript), successScript(successScript), onEnable(NULL), onSuccess(NULL), mainObjective(mainObjective) { if (enableScript) { onEnable = new Script(); onEnable->parse(enableScript); } if (successScript) { onSuccess = new Script(); onSuccess->parse(successScript); } } #define UPDATE_DELAY 3.0f Objectives::Objectives() : timer(0.0f),showWindow(false),firstObj(true) { saveGame.registerListener(OBJE_CHUNK_ID,PHASE_START,this); rect = UmbraRect(2,5,OBJ_WIDTH,OBJ_HEIGHT); con = new TCODConsole(OBJ_WIDTH,OBJ_HEIGHT); con->setDefaultBackground(guiBackground); guiTabs.addTab("Active"); guiTabs.addTab("Success"); guiTabs.addTab("Failure"); flags=DIALOG_CLOSABLE_NODISABLE; currentList=&active; scroller = new Scroller(this,OBJ_WIDTH/2-1,OBJ_HEIGHT-2); selected=0; } bool Objectives::executeObjScript(Objective *obj, Script *script) { currentObjective = obj; bool ret=script->execute(); currentObjective = NULL; return ret; } void Objectives::activateCurrent() { gameEngine->gui.log.warn("New objective : %s",currentObjective->title); if ( firstObj ) { gameEngine->gui.log.info("Press 'o' to open the objectives screen"); firstObj=false; } toActivate.push(currentObjective); } void Objectives::activateObjective(const char *title) { for (Objective **it=sleeping.begin(); it != sleeping.end(); it++) { if ( strcmp(title,(*it)->title) == 0 ) { gameEngine->gui.log.warn("New objective : %s",title); toActivate.push(*it); break; } } } void Objectives::closeCurrent(bool success) { gameEngine->gui.log.warn("Objective completed : %s (%s)",currentObjective->title, success ? "success":"failure"); if ( success ) { toSuccess.push(currentObjective); if ( currentObjective->mainObjective ) gameEngine->win=true; } else toFailure.push(currentObjective); } void Objectives::addStep(const char *msg, Objective *obj) { if (! obj ) obj = currentObjective; if (! toSuccess.contains( obj ) ) gameEngine->gui.log.warn("Objective updated : %s",obj->title); obj->steps.push(strdup(msg)); } void Objectives::render() { if (! showWindow ) return; con->clear(); con->setDefaultForeground(guiText); con->vline(OBJ_WIDTH/2,2,OBJ_HEIGHT-3); guiTabs.render(con,0,0); scroller->render(con,0,2); scroller->renderScrollbar(con,0,2); if ( currentList && selected < currentList->size() ) { con->setDefaultForeground(guiText); int y=2; Objective *objective=currentList->get(selected); y+=con->printRect(OBJ_WIDTH/2+2,y,OBJ_WIDTH/2-3,0,objective->description); for ( const char **step=objective->steps.begin(); step != objective->steps.end(); step ++ ) { y++; y+=con->printRect(OBJ_WIDTH/2+2,y,OBJ_WIDTH/2-3,0,*step); } } blitSemiTransparent(con,0,0,OBJ_WIDTH,OBJ_HEIGHT,TCODConsole::root,rect.x,rect.y,0.8f,1.0f); renderFrame(1.0f,"Objectives"); } int Objectives::getScrollTotalSize() { return currentList->size(); } const char *Objectives::getScrollText(int idx) { return currentList->get(idx)->title; } void Objectives::getScrollColor(int idx, TCODColor *fore, TCODColor *back) { *fore = idx == selected ? guiHighlightedText : guiText; *back = guiBackground; } bool Objectives::update(float elapsed, TCOD_key_t &k, TCOD_mouse_t &mouse) { if ( showWindow ) { flags |= DIALOG_MODAL; guiTabs.update(elapsed,k,mouse,rect.x,rect.y); scroller->update(elapsed,k,mouse,rect.x,rect.y+2); if ( mouse.cx >= rect.x && mouse.cx < rect.x+rect.w/2 && mouse.cy >= rect.y+2 && mouse.cy < rect.y+rect.h) { int newSelected = mouse.cy-rect.y-2; if ( currentList && newSelected < currentList->size() ) selected=newSelected; } switch(guiTabs.curTab) { case 0 : currentList = &active; break; case 1 : currentList = &success; break; case 2 : currentList = &failed; break; } if (closeButton.mouseHover && mouse.lbutton_pressed) { gameEngine->gui.setMode(GUI_NONE); } if ( (k.vk == TCODK_ESCAPE && ! k.pressed) ) { gameEngine->gui.setMode(GUI_NONE); } } else if ( wasShowingWindow) { flags &= ~DIALOG_MODAL; if ( gameEngine->gui.mode == GUI_NONE && gameEngine->isGamePaused() ) { gameEngine->resumeGame(); } } timer += elapsed; if ( timer < UPDATE_DELAY ) return true; timer = 0.0f; // check end conditions for active objectives for (Objective **it=active.begin(); it != active.end(); it++) { if (! (*it)->onSuccess ) toSuccess.push(*it); else if ( !executeObjScript(*it,(*it)->onSuccess) ) { // script execution failed. junk the objective failed.push(*it); it = active.removeFast(it); } } // check if new objectives are enabled for (Objective **it=sleeping.begin(); it != sleeping.end(); it++) { if ( ! (*it)->onEnable ) { toActivate.push(*it); gameEngine->gui.log.warn("New objective : %s",(*it)->title); if ( firstObj ) { gameEngine->gui.log.info("Press 'o' to open the objectives screen"); firstObj=false; } } else if ( !executeObjScript(*it,(*it)->onEnable) ) { // script execution failed. junk the objective failed.push(*it); it = sleeping.removeFast(it); } } for (Objective **it=toActivate.begin(); it != toActivate.end(); it++) { sleeping.removeFast(*it); active.push(*it); } toActivate.clear(); for (Objective **it=toSuccess.begin(); it != toSuccess.end(); it++) { active.removeFast(*it); success.push(*it); } toSuccess.clear(); for (Objective **it=toFailure.begin(); it != toFailure.end(); it++) { active.removeFast(*it); failed.push(*it); } toFailure.clear(); wasShowingWindow = showWindow; return true; } void Objectives::addObjective(Objective *obj) { sleeping.push(obj); } #define OBJE_CHUNK_VERSION 1 bool Objectives::loadData(uint32 chunkId, uint32 chunkVersion, TCODZip *zip) { if ( chunkVersion != OBJE_CHUNK_VERSION ) return false; showWindow = (zip->getChar()==1); firstObj = (zip->getChar()==1); int nbSleeping=zip->getInt(); while ( nbSleeping > 0 ) { const char *title=strdup(zip->getString()); const char *description=strdup(zip->getString()); const char *enableScript=zip->getString(); if (enableScript) enableScript=strdup(enableScript); const char *successScript=zip->getString(); if (successScript) successScript=strdup(successScript); Objective *obj = new Objective(title,description,enableScript,successScript); sleeping.push(obj); nbSleeping--; } int nbActive=zip->getInt(); while ( nbActive > 0 ) { const char *title=strdup(zip->getString()); const char *description=strdup(zip->getString()); const char *enableScript=zip->getString(); if (enableScript) enableScript=strdup(enableScript); const char *successScript=zip->getString(); if (successScript) successScript=strdup(successScript); Objective *obj = new Objective(title,description,enableScript,successScript); active.push(obj); nbActive--; } int nbSuccess=zip->getInt(); while ( nbSuccess > 0 ) { const char *title=strdup(zip->getString()); const char *description=strdup(zip->getString()); Objective *obj = new Objective(title,description); success.push(obj); nbSuccess--; } int nbFailed=zip->getInt(); while ( nbFailed > 0 ) { const char *title=strdup(zip->getString()); const char *description=strdup(zip->getString()); Objective *obj = new Objective(title,description); failed.push(obj); nbFailed--; } return true; } void Objectives::saveData(uint32 chunkId, TCODZip *zip) { saveGame.saveChunk(OBJE_CHUNK_ID,OBJE_CHUNK_VERSION); zip->putChar(showWindow ? 1:0); zip->putChar(firstObj ? 1:0); zip->putInt(sleeping.size()); for (Objective **it=sleeping.begin(); it != sleeping.end(); it++) { zip->putString((*it)->title); zip->putString((*it)->description); zip->putString((*it)->enableScript); zip->putString((*it)->successScript); } zip->putInt(active.size()); for (Objective **it=active.begin(); it != active.end(); it++) { zip->putString((*it)->title); zip->putString((*it)->description); zip->putString((*it)->enableScript); zip->putString((*it)->successScript); } zip->putInt(success.size()); for (Objective **it=success.begin(); it != success.end(); it++) { zip->putString((*it)->title); zip->putString((*it)->description); } zip->putInt(failed.size()); for (Objective **it=failed.begin(); it != failed.end(); it++) { zip->putString((*it)->title); zip->putString((*it)->description); } }
34.318937
115
0.677735
libtcod
ffdf383dfac20dc2c8a34fd5e1d0258ad524b780
4,143
cpp
C++
3dc/avp/support/console_batch.cpp
Melanikus/AvP
9d61eb974a23538e32bf2ef1b738643a018935a0
[ "BSD-3-Clause" ]
null
null
null
3dc/avp/support/console_batch.cpp
Melanikus/AvP
9d61eb974a23538e32bf2ef1b738643a018935a0
[ "BSD-3-Clause" ]
null
null
null
3dc/avp/support/console_batch.cpp
Melanikus/AvP
9d61eb974a23538e32bf2ef1b738643a018935a0
[ "BSD-3-Clause" ]
null
null
null
/******************************************************************* * * DESCRIPTION: consbtch.cpp * * AUTHOR: David Malcolm * * HISTORY: Created 8/4/98 * *******************************************************************/ /* Includes ********************************************************/ #include "3dc.h" #include "console_batch.hpp" #include "reflist.hpp" #define UseLocalAssert TRUE #include "ourasert.h" /* Version settings ************************************************/ /* Constants *******************************************************/ enum { MaxBatchFileLineLength=300, MaxBatchFileLineSize=(MaxBatchFileLineLength+1) }; /* Macros **********************************************************/ /* Imported function prototypes ************************************/ /* Imported data ***************************************************/ /* Exported globals ************************************************/ /* Internal type definitions ***************************************/ /* Internal function prototypes ************************************/ /* Internal globals ************************************************/ /* Exported function definitions ***********************************/ // class BatchFileProcessing // public: // static bool BatchFileProcessing :: Run(char* Filename) { // Tries to find the file, if it finds it it reads it, // adds the non-comment lines to the pending list, and returns TRUE // If it can't find the file, it returns FALSE // LOCALISEME // This code makes several uses of the assumption that char is type-equal // to ProjChar RefList<SCString> PendingList; { FILE *pFile = avp_open_userfile(Filename, "r"); if (NULL==pFile) { return FALSE; } // Read the file, line by line. { // We impose a maximum length on lines that will be valid: char LineBuffer[MaxBatchFileLineSize]; int CharsReadInLine = 0; while (1) { int Char = fgetc(pFile); if (Char==EOF) { break; } else { if ( Char=='\n' ) { // Flush the buffer into the pending queue: GLOBALASSERT(CharsReadInLine<=MaxBatchFileLineLength); LineBuffer[CharsReadInLine] = '\0'; SCString* pSCString_Line = new SCString(&LineBuffer[0]); PendingList . AddToEnd ( *pSCString_Line ); pSCString_Line -> R_Release(); CharsReadInLine = 0; } else { // Add to buffer; silently reject characters beyond the length limit if ( CharsReadInLine < MaxBatchFileLineLength ) { LineBuffer[CharsReadInLine++]=toupper((char)Char); } } } } // Flush anything still in the buffer into the pending queue: { GLOBALASSERT(CharsReadInLine<=MaxBatchFileLineLength); LineBuffer[CharsReadInLine] = '\0'; SCString* pSCString_Line = new SCString(&LineBuffer[0]); PendingList . AddToEnd ( *pSCString_Line ); pSCString_Line -> R_Release(); } } fclose(pFile); } // Feedback: { SCString* pSCString_1 = new SCString("EXECUTING BATCH FILE "); // LOCALISEME SCString* pSCString_2 = new SCString(Filename); SCString* pSCString_Feedback = new SCString ( pSCString_1, pSCString_2 ); pSCString_Feedback -> SendToScreen(); pSCString_Feedback -> R_Release(); pSCString_2 -> R_Release(); pSCString_1 -> R_Release(); } // Now process the pending queue: { // Iterate through the pending list, destructively reading the // "references" from the front: { SCString* pSCString; // The assignment in this boolean expression is deliberate: while ( NULL != (pSCString = PendingList . GetYourFirst()) ) { if (pSCString->pProjCh()[0] != '#') { // lines beginning with hash are comments if (bEcho) { pSCString -> SendToScreen(); } pSCString -> ProcessAnyCheatCodes(); } pSCString -> R_Release(); } } } return TRUE; } // public: // static int BatchFileProcessing :: bEcho = FALSE; /* Internal function definitions ***********************************/
21.691099
74
0.529809
Melanikus
ffe224c76c681907ddc262ae12752c359f23b872
3,600
hpp
C++
include/logi/memory/memory_allocator_impl.hpp
PrimozLavric/VulkanRenderer
6d95b8ec4b0133ce46b4b4e550d20ef17f77b2c4
[ "BSD-2-Clause" ]
6
2021-04-06T02:37:55.000Z
2021-11-24T06:14:04.000Z
include/logi/memory/memory_allocator_impl.hpp
PrimozLavric/Logi
6d95b8ec4b0133ce46b4b4e550d20ef17f77b2c4
[ "BSD-2-Clause" ]
null
null
null
include/logi/memory/memory_allocator_impl.hpp
PrimozLavric/Logi
6d95b8ec4b0133ce46b4b4e550d20ef17f77b2c4
[ "BSD-2-Clause" ]
null
null
null
/** * Project Logi source code * Copyright (C) 2019 Primoz Lavric * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef LOGI_MEMORY_MEMORY_ALLOCATOR_IMPL_HPP #define LOGI_MEMORY_MEMORY_ALLOCATOR_IMPL_HPP #include <optional> #include <vk_mem_alloc.h> #include "logi/base/common.hpp" #include "logi/base/vulkan_object.hpp" namespace logi { class VulkanInstanceImpl; class PhysicalDeviceImpl; class LogicalDeviceImpl; class VMABufferImpl; class VMAImageImpl; class VMAAccelerationStructureNVImpl; class MemoryAllocatorImpl : public VulkanObject, public std::enable_shared_from_this<MemoryAllocatorImpl>, public VulkanObjectComposite<VMABufferImpl>, public VulkanObjectComposite<VMAImageImpl>, public VulkanObjectComposite<VMAAccelerationStructureNVImpl> { public: explicit MemoryAllocatorImpl(LogicalDeviceImpl& logicalDevice, vk::DeviceSize preferredLargeHeapBlockSize = 0u, uint32_t frameInUseCount = 0u, const std::vector<vk::DeviceSize>& heapSizeLimits = {}, const std::optional<vk::AllocationCallbacks>& allocator = {}); // region Sub handles const std::shared_ptr<VMABufferImpl>& createBuffer(const vk::BufferCreateInfo& bufferCreateInfo, const VmaAllocationCreateInfo& allocationCreateInfo, const std::optional<vk::AllocationCallbacks>& allocator); void destroyBuffer(size_t id); const std::shared_ptr<VMAImageImpl>& createImage(const vk::ImageCreateInfo& imageCreateInfo, const VmaAllocationCreateInfo& allocationCreateInfo, const std::optional<vk::AllocationCallbacks>& allocator = {}); void destroyImage(size_t id); const std::shared_ptr<VMAAccelerationStructureNVImpl>& createAccelerationStructureNV(const vk::AccelerationStructureCreateInfoNV& accelerationStructureCreateInfo, const VmaAllocationCreateInfo& allocationCreateInfo, const std::optional<vk::AllocationCallbacks>& allocator = {}); void destroyAccelerationStructureNV(size_t id); // endregion // region Logi Declarations VulkanInstanceImpl& getInstance() const; PhysicalDeviceImpl& getPhysicalDevice() const; LogicalDeviceImpl& getLogicalDevice() const; const vk::DispatchLoaderDynamic& getDispatcher() const; operator const VmaAllocator&() const; void destroy() const; protected: void free() override; // endregion private: LogicalDeviceImpl& logicalDevice_; std::optional<vk::AllocationCallbacks> allocator_; VmaAllocator vma_; }; } // namespace logi #endif // LOGI_MEMORY_MEMORY_ALLOCATOR_IMPL_HPP
37.113402
118
0.6725
PrimozLavric
ffe228198955a3e4838e783ead228d2d5c36ebfe
3,471
hpp
C++
include/shadertoy/buffers/gl_buffer.hpp
vtavernier/libshadertoy
a0b2a133199383cc7e9bcb3c0300f39eb95177c0
[ "MIT" ]
2
2020-02-23T09:33:07.000Z
2021-11-15T18:23:13.000Z
include/shadertoy/buffers/gl_buffer.hpp
vtavernier/libshadertoy
a0b2a133199383cc7e9bcb3c0300f39eb95177c0
[ "MIT" ]
2
2019-08-09T15:48:07.000Z
2020-11-16T13:51:56.000Z
include/shadertoy/buffers/gl_buffer.hpp
vtavernier/libshadertoy
a0b2a133199383cc7e9bcb3c0300f39eb95177c0
[ "MIT" ]
3
2019-12-12T09:42:34.000Z
2020-12-14T03:56:30.000Z
#ifndef _SHADERTOY_BUFFERS_BUFFER_BASE_HPP_ #define _SHADERTOY_BUFFERS_BUFFER_BASE_HPP_ #include "shadertoy/pre.hpp" #include "shadertoy/buffers/basic_buffer.hpp" #include "shadertoy/gl/framebuffer.hpp" #include "shadertoy/gl/renderbuffer.hpp" namespace shadertoy { namespace buffers { /** * @brief Represents a buffer in a swap chain. Rendering is done using a framebuffer. * * This class instantiates a framebuffer and a renderbuffer which are bound * before rendering the contents of this buffer. */ class gl_buffer : public basic_buffer { /// Target framebuffer gl::framebuffer target_fbo_; /// Target renderbuffer gl::renderbuffer target_rbo_; protected: /** * @brief Initialize a new gl_buffer * * @param[in] id Identifier for this buffer */ gl_buffer(const std::string &id); /** * @brief Initialize the contents of the buffer for rendering. * * @param[in] context Rendering context to use for shared objects * @param[in] io IO resource object */ void init_contents(const render_context &context, const io_resource &io) override; /** * @brief Initialize the renderbuffer object for the new specified size. * * @param[in] context Rendering context to use for shared objects * @param[in] io IO resource object */ void allocate_contents(const render_context &context, const io_resource &io) override; /** * @brief Render the contents of this buffer. This methods binds the * framebuffer and renderbuffer to the appropriate texture for * rendering, and then calls render_gl_contents as defined by * the derived class. * * @param[in] context Rendering context to use for rendering this buffer * @param[in] io IO resource object * @param[in] member Current swap-chain member */ void render_contents(const render_context &context, const io_resource &io, const members::buffer_member &member) final; /** * @brief Render the contents of this buffer to the currently bound * framebuffer and renderbuffer. This method must be implemented * by derived classes as part of their rendering routine. * * @param[in] context Rendering context to use for rendering this buffer * @param[in] io IO resource object */ virtual void render_gl_contents(const render_context &context, const io_resource &io) = 0; /** * @brief Binds the given texture to the target framebuffer object * for rendering. This method may be overridden by derived classes * in order to control the binding process. The default behavior is * to bind the first layer of the texture object to the first color attachment. * * @param[in] target_fbo Target framebuffer bound object * @param[in] io IO resource object containing the target textures to bind */ virtual void attach_framebuffer_outputs(const gl::bind_guard<gl::framebuffer, GLint> &target_fbo, const io_resource &io); public: /** * @brief Obtain this buffer's GL framebuffer object * * @return Reference to the framebuffer object */ inline const gl::framebuffer &target_fbo() const { return target_fbo_; } /** * @brief Obtain this buffer's GL renderbuffer object * * @return Reference to the renderbuffer object */ inline const gl::renderbuffer &target_rbo() const { return target_rbo_; } }; } } #endif /* _SHADERTOY_BUFFERS_BUFFER_BASE_HPP_ */
31.554545
98
0.706425
vtavernier
fff2c71393a47f7ddc2a65c2bd77f1fa6fcbe020
2,947
inl
C++
Misc/UnusedCode/RSLibAndTests/RSLib/Code/Math/Types/ModularInteger.inl
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
34
2017-04-19T18:26:02.000Z
2022-02-15T17:47:26.000Z
Misc/UnusedCode/RSLibAndTests/RSLib/Code/Math/Types/ModularInteger.inl
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
307
2017-05-04T21:45:01.000Z
2022-02-03T00:59:01.000Z
Misc/UnusedCode/RSLibAndTests/RSLib/Code/Math/Types/ModularInteger.inl
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
4
2017-09-05T17:04:31.000Z
2021-12-15T21:24:28.000Z
#ifndef RS_MODULARINTEGER_INL #define RS_MODULARINTEGER_INL #include "ModularInteger.h" // why is this include needed? maybe it's not using namespace RSLib; // construction/destruction: template<class T> rsModularInteger<T>::rsModularInteger(rsUint64 initialValue, rsUint64 modulusToUse) { modulus = modulusToUse; value = initialValue; rsAssert( value >= T(0) && value < modulus ); } template<class T> rsModularInteger<T>::rsModularInteger(const rsModularInteger<T>& other) { modulus = other.modulus; value = other.value; } // operators: template<class T> rsModularInteger<T> rsModularInteger<T>::operator-() const { if( value == 0 ) return *this; else return rsModularInteger<T>(modulus-value, modulus); } template<class T> bool rsModularInteger<T>::operator==(const rsModularInteger<T>& other) const { return value == other.value && modulus == other.modulus; } template<class T> bool rsModularInteger<T>::operator!=(const rsModularInteger<T>& other) const { return !(*this == other); } template<class T> rsModularInteger<T> rsModularInteger<T>::operator+(const rsModularInteger<T> &other) { rsAssert( modulus == other.modulus ); T r = this->value + other.value; if( r >= modulus ) r -= modulus; return rsModularInteger<T>(r, modulus); } template<class T> rsModularInteger<T> rsModularInteger<T>::operator-(const rsModularInteger<T> &other) { rsAssert( modulus == other.modulus ); T r; if( other.value > this->value ) r = modulus + this->value - other.value; else r = this->value - other.value; return rsModularInteger<T>(r, modulus); } template<class T> rsModularInteger<T> rsModularInteger<T>::operator*(const rsModularInteger<T> &other) { rsAssert( modulus == other.modulus ); T r = (this->value * other.value) % modulus; return rsModularInteger<T>(r, modulus); } template<class T> rsModularInteger<T> rsModularInteger<T>::operator/(const rsModularInteger<T> &other) { rsAssert( modulus == other.modulus ); return *this * rsModularInverse(other.value, modulus); } template<class T> rsModularInteger<T>& rsModularInteger<T>::operator+=(const rsModularInteger<T> &other) { *this = *this + other; return *this; } template<class T> rsModularInteger<T>& rsModularInteger<T>::operator-=(const rsModularInteger<T> &other) { *this = *this - other; return *this; } template<class T> rsModularInteger<T>& rsModularInteger<T>::operator*=(const rsModularInteger<T> &other) { *this = *this * other; return *this; } template<class T> rsModularInteger<T>& rsModularInteger<T>::operator/=(const rsModularInteger<T> &other) { *this = *this / other; return *this; } template<class T> rsModularInteger<T>& rsModularInteger<T>::operator++() { *this = *this + rsModularInteger<T>(1, modulus); return *this; } template<class T> rsModularInteger<T>& rsModularInteger<T>::operator--() { *this = *this - rsModularInteger<T>(1, modulus); return *this; } #endif
24.155738
86
0.709874
RobinSchmidt
fff9b871a32d5bc265eb6d9a098f3fc3f487137c
2,320
cpp
C++
Interview Bit/Max Non Negative Subarray.cpp
Shubhrmcf07/Competitive-Coding-and-Interview-Problems
7281ea3163c0cf6938a3af7b54a8a14f97c97c0e
[ "MIT" ]
51
2020-02-24T11:14:00.000Z
2022-03-24T09:32:18.000Z
Interview Bit/Max Non Negative Subarray.cpp
Shubhrmcf07/Competitive-Coding-and-Interview-Problems
7281ea3163c0cf6938a3af7b54a8a14f97c97c0e
[ "MIT" ]
3
2020-10-02T08:16:09.000Z
2021-04-17T16:32:38.000Z
Interview Bit/Max Non Negative Subarray.cpp
Shubhrmcf07/Competitive-Coding-and-Interview-Problems
7281ea3163c0cf6938a3af7b54a8a14f97c97c0e
[ "MIT" ]
18
2020-04-24T15:33:36.000Z
2022-03-24T09:32:20.000Z
/* Interview Bit */ /* Title - Max Non Negative Subarray */ /* Created By - Akash Modak */ /* Date - 26/06/2020 */ // Given an array of integers, A of length N, find out the maximum sum sub-array of non negative numbers from A. // The sub-array should be contiguous i.e., a sub-array created by choosing the second and fourth element and skipping the third element is invalid. // Maximum sub-array is defined in terms of the sum of the elements in the sub-array. // Find and return the required subarray. // NOTE: // If there is a tie, then compare with segment's length and return segment which has maximum length. // If there is still a tie, then return the segment with minimum starting index. // Problem Constraints // 1 <= N <= 105 // -109 <= A[i] <= 109 // Input Format // The first and the only argument of input contains an integer array A, of length N. // Output Format // Return an array of integers, that is a subarray of A that satisfies the given conditions. // Example Input // Input 1: // A = [1, 2, 5, -7, 2, 3] // Input 2: // A = [10, -1, 2, 3, -4, 100] // Example Output // Output 1: // [1, 2, 5] // Output 2: // [100] // Example Explanation // Explanation 1: // The two sub-arrays are [1, 2, 5] [2, 3]. // The answer is [1, 2, 5] as its sum is larger than [2, 3]. // Explanation 2: // The three sub-arrays are [10], [2, 3], [100]. // The answer is [100] as its sum is larger than the other two. vector<int> Solution::maxset(vector<int> &A) { int n=A.size(); int i=0,maxm=0,count=0,start=0,end=-1; int fstart=-1,fend=-1; long long int sum=0,maxsum=0; vector<int> res; while(i<n){ if(A[i]>=0){ sum+=A[i]; count++; end++; } if(sum>maxsum){ maxsum=sum; fstart=start; fend=end; } else if(sum==maxsum&&count>maxm){ maxm=count; fstart=start; fend=end; } if(A[i]<0){ count=0; start=i+1;end=i; sum=0; } i++; } if(fstart!=-1&&fend!=-1){ for(int i=fstart;i<=fend;i++) res.push_back(A[i]); } return res; }
23.434343
149
0.54569
Shubhrmcf07
fffab5150cd082aa6df93e8b19553a00955046c4
735
cpp
C++
Contests/Codeforces/CF1011/D.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
4
2017-10-31T14:25:18.000Z
2018-06-10T16:10:17.000Z
Contests/Codeforces/CF1011/D.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
null
null
null
Contests/Codeforces/CF1011/D.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
null
null
null
#include<iostream> #include<cstdio> #include<cstdlib> #include<cstring> #include<algorithm> using namespace std; #define ll long long #define mem(Arr,x) memset(Arr,x,sizeof(Arr)) const int maxN=40; const int inf=2147483647; int Opt[maxN]; int main() { int n,m,ans; scanf("%d%d",&m,&n); for (int i=1;i<=n;i++){ printf("1\n");fflush(stdout);scanf("%d",&ans); if (ans==0) exit(0); if (ans==1) Opt[i]=-1; else Opt[i]=1; } int L=1,R=m,outp=0,cnt=0; do { cnt++; if (cnt>n) cnt=1; int mid=(L+R)>>1; printf("%d\n",mid);fflush(stdout);scanf("%d",&ans); if (ans==0) exit(0); ans*=Opt[cnt]; if (ans==1) R=mid-1; else L=mid+1; } while (L<=R); printf("%d\n",L);fflush(stdout);scanf("%d",&ans); return 0; }
16.333333
53
0.589116
SYCstudio
0801aa77f7f4d45276733c53ee7cd875cc7f10ce
506
hh
C++
include/simlib/defer.hh
varqox/simlib
7830472019f88aa0e35dbfa1119b62b5f9dd4b9d
[ "MIT" ]
null
null
null
include/simlib/defer.hh
varqox/simlib
7830472019f88aa0e35dbfa1119b62b5f9dd4b9d
[ "MIT" ]
1
2017-01-05T17:50:32.000Z
2017-01-05T17:50:32.000Z
include/simlib/defer.hh
varqox/simlib
7830472019f88aa0e35dbfa1119b62b5f9dd4b9d
[ "MIT" ]
1
2017-01-05T15:26:48.000Z
2017-01-05T15:26:48.000Z
#pragma once #include <utility> template <class Func> class Defer { Func func_; public: // NOLINTNEXTLINE(google-explicit-constructor) Defer(Func func) try : func_(std::move(func)) { } catch (...) { func(); throw; } Defer(const Defer&) = delete; Defer(Defer&&) = delete; Defer& operator=(const Defer&) = delete; Defer& operator=(Defer&&) = delete; ~Defer() { try { func_(); } catch (...) { } } };
16.322581
50
0.511858
varqox
0802ea0905ca05761dc8f06f6ae9c4390cef4d40
704
cpp
C++
zoe/src/zoe/display/Physics/AxisAlignedBox.cpp
NudelErde/zoe
456e38bba86058f006a7c0fd5168af5039714c6c
[ "MIT" ]
7
2019-12-16T20:23:39.000Z
2020-10-26T08:46:12.000Z
zoe/src/zoe/display/Physics/AxisAlignedBox.cpp
NudelErde/zoe
456e38bba86058f006a7c0fd5168af5039714c6c
[ "MIT" ]
13
2020-01-13T20:19:06.000Z
2021-09-10T21:23:52.000Z
zoe/src/zoe/display/Physics/AxisAlignedBox.cpp
NudelErde/zoe
456e38bba86058f006a7c0fd5168af5039714c6c
[ "MIT" ]
7
2019-12-29T22:46:23.000Z
2020-07-15T19:56:32.000Z
// // Created by Florian on 20.12.2020. // #include "AxisAlignedBox.h" #include "cmath" namespace Zoe{ AxisAlignedBox::AxisAlignedBox(const vec3& lower, const vec3& higher) { AxisAlignedBox::lower = vec3(std::min(lower.x, higher.x), std::min(lower.y, higher.y), std::min(lower.z, higher.z)); AxisAlignedBox::higher = vec3(std::max(lower.x, higher.x), std::max(lower.y, higher.y), std::max(lower.z, higher.z)); } AxisAlignedBox::AxisAlignedBox(double x1, double y1, double z1, double x2, double y2, double z2) { AxisAlignedBox::lower = vec3(std::min(x1, x2), std::min(y1, y2), std::min(z1, z2)); AxisAlignedBox::higher = vec3(std::max(x1, x2), std::max(y1, y2), std::max(z1, z2)); } }
35.2
121
0.671875
NudelErde
08040c4e9fff3bdfc50d838bb796914dc14ba2cc
15,503
inl
C++
ThirdParty/Havok/include/Geometry/Internal/Algorithms/RayCast/hkcdRayCastCapsule.inl
wobbier/source3-engine
f59df759ee197aef5191cf13768c303c6ed17bf5
[ "MIT" ]
11
2016-08-02T03:40:36.000Z
2022-03-15T13:41:29.000Z
ThirdParty/Havok/include/Geometry/Internal/Algorithms/RayCast/hkcdRayCastCapsule.inl
wobbier/source3-engine
f59df759ee197aef5191cf13768c303c6ed17bf5
[ "MIT" ]
null
null
null
ThirdParty/Havok/include/Geometry/Internal/Algorithms/RayCast/hkcdRayCastCapsule.inl
wobbier/source3-engine
f59df759ee197aef5191cf13768c303c6ed17bf5
[ "MIT" ]
8
2017-03-17T05:59:25.000Z
2021-02-27T08:51:46.000Z
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Product and Trade Secret source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2014 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #include <Geometry/Internal/Types/hkcdRay.h> #include <Geometry/Internal/Algorithms/Distance/hkcdDistancePointLine.h> #include <Geometry/Internal/Algorithms/ClosestPoint/hkcdClosestPointLineLine.h> #include <Geometry/Internal/Algorithms/RayCast/hkcdRayCastSphere.h> HK_FORCE_INLINE hkcdRayCastResult hkcdRayCastCapsule( const hkcdRay& rayIn, hkVector4Parameter vertex0, hkVector4Parameter vertex1, hkSimdRealParameter radius, hkSimdReal* HK_RESTRICT fractionInOut, hkVector4* HK_RESTRICT normalOut, hkcdRayCastCapsuleHitType* HK_RESTRICT hitTypeOut, hkFlags<hkcdRayQueryFlags::Enum,hkUint32> flags ) { hkVector4Comparison insideHits; hkcdRayQueryFlags::isFlagSet(flags, hkcdRayQueryFlags::ENABLE_INSIDE_HITS, insideHits); hkcdRay ray = rayIn; const hkVector4& dA = ray.getDirection(); // Catch the case where the ray has length zero. if (HK_VERY_UNLIKELY(dA.equalZero().allAreSet<hkVector4ComparisonMask::MASK_XYZ>())) { return hkcdRayCastResult::NO_HIT; } hkVector4 dB; dB.setSub( vertex1, vertex0 ); hkSimdReal radiusSq = radius * radius; hkSimdReal fraction = *fractionInOut; hkVector4Comparison isInverseRay; isInverseRay.set<hkVector4ComparisonMask::MASK_NONE>(); hkSimdReal invScale = hkSimdReal_1; hkVector4Comparison isInsideComparison; hkcdRayCastResult success = hkcdRayCastResult::FRONT_FACE_HIT; { hkSimdReal sToCylDistSq = hkcdPointSegmentDistanceSquared( ray.m_origin, vertex0, vertex1 ); isInsideComparison = sToCylDistSq.less(radiusSq); if( HK_VERY_UNLIKELY( isInsideComparison.allAreSet() ) ) { success = hkcdRayCastResult(hkcdRayCastResult::BACK_FACE_HIT | hkcdRayCastResult::INSIDE_HIT); // origin inside the cylinder if ( HK_VERY_LIKELY( !insideHits.allAreSet() ) ) { return hkcdRayCastResult::NO_HIT; } else { // The origin is inside, so we invert the ray to get inside hits. // Inverting a ray that is extremely long might get us into accuracy issues, // so we conservatively resize the inverse ray to handle the issue: // We can setup an inverse ray ending at the inside point and starting outside the capsule. // To find the starting point outside the capsule, we can safely move from the inside point // along the ray's inverse direction by a distance that is the radius of a sphere englobing // the capsule (plus some padding = 2*radius ), capped by the size of the original ray. // We use 'invScale' to correct the final hitFraction later on. hkVector4 endPoint; endPoint.setAddMul( ray.m_origin, ray.m_direction, *fractionInOut ); hkSimdReal sToCylDistSq2 = hkcdPointSegmentDistanceSquared( endPoint, vertex0, vertex1 ); isInverseRay.set<hkVector4ComparisonMask::MASK_XYZW>(); hkSimdReal inRaySize = ray.getDirection().length<3>(); hkSimdReal invRayMaxSize = dB.length<3>() + hkSimdReal_4 * radius; hkSimdReal invRaySize; invRaySize.setMin( invRayMaxSize, inRaySize * ( *fractionInOut ) ); invScale.setDiv<HK_ACC_RAYCAST, HK_DIV_SET_ZERO>( invRaySize, inRaySize ); ray.m_direction.setMul( rayIn.m_direction, invScale ); ray.m_direction.setNeg<3>( ray.m_direction ); ray.m_origin.setSub( rayIn.m_origin, ray.m_direction ); // ray.m_invDirection is not used fraction = hkSimdReal_1; // Both ray points are inside the capsule. // Also safely catches the case where the ray has zero length. if( HK_VERY_UNLIKELY( sToCylDistSq2 < radiusSq ) ) { return hkcdRayCastResult::NO_HIT; } } } } // Work out closest points to cylinder hkSimdReal infInfDistSquared; hkSimdReal t, u; // Get distance between inf lines + parametric description (t, u) of closest points, { hkcdClosestPointLineLine(ray.m_origin, dA, vertex0, dB, t, u); hkVector4 p,q; p.setAddMul(ray.m_origin, dA, t); q.setAddMul(vertex0, dB, u); hkVector4 diff; diff.setSub(p, q); infInfDistSquared = diff.lengthSquared<3>(); if( infInfDistSquared > (radius*radius) ) { return hkcdRayCastResult::NO_HIT; // Infinite ray is outside radius of infinite cylinder } } hkSimdReal axisLength; hkVector4 axis; hkSimdReal ipT; { axis = dB; // Check for zero axis { hkSimdReal axisLengthSqrd = axis.lengthSquared<3>(); hkVector4Comparison mask = axisLengthSqrd.greater( hkSimdReal_Eps ); axisLength = axis.normalizeWithLength<3,HK_ACC_RAYCAST,HK_SQRT_IGNORE>(); axisLength.zeroIfFalse(mask); axis.zeroIfFalse(mask); } hkSimdReal component = dA.dot<3>(axis); // Flatdir is now a ray firing in the "plane" of the cylinder. hkVector4 flatDir; flatDir.setAddMul(dA, axis, -component); // Convert d to a parameterization instead of absolute distance along ray. hkSimdReal flatDirLengthSquared3 = flatDir.lengthSquared<3>(); // If flatDir is zero, the ray is parallel to the cylinder axis. In this case we set ipT to a // negative value to bypass the cylinder intersection test and go straight to the cap tests. hkVector4Comparison mask = flatDirLengthSquared3.equalZero(); hkSimdReal d = (radius * radius - infInfDistSquared) / flatDirLengthSquared3; ipT.setSelect(mask, hkSimdReal_Minus1, t - d.sqrt()); } // Intersection parameterization with infinite cylinder is outside length of ray // or is greater than a previous hit fraction if (ipT >= fraction ) { return hkcdRayCastResult::NO_HIT; } hkSimdReal ptHeight; hkSimdReal pointAProj = vertex0.dot<3>(axis); // Find intersection point of actual ray with infinite cylinder hkVector4 intersectPt; intersectPt.setAddMul( ray.m_origin, ray.getDirection(), ipT ); // Test height of intersection point w.r.t. cylinder axis // to determine hit against actual cylinder // Intersection point projected against cylinder hkSimdReal ptProj = intersectPt.dot<3>(axis); ptHeight = ptProj - pointAProj; if ( ipT.isGreaterEqualZero() ) // Actual ray (not infinite ray) must intersect with infinite cylinder { if ( ptHeight.isGreaterZero() && ptHeight.isLess(axisLength) ) // Report hit against cylinder part { // Calculate normal hkVector4 projPtOnAxis; projPtOnAxis.setInterpolate( vertex0, vertex1, ptHeight / axisLength ); hkVector4 normal; normal.setSub( intersectPt, projPtOnAxis ); normal.normalize<3>(); *normalOut = normal; hkSimdReal invIpT; invIpT.setSub( hkSimdReal_1, ipT ); invIpT.setMul( invIpT, invScale ); fractionInOut->setSelect( isInverseRay, invIpT, ipT ); *hitTypeOut = HK_CD_RAY_CAPSULE_BODY; return success; } } // Cap tests { // Check whether start point is inside infinite cylinder or not hkSimdReal fromLocalProj = ray.m_origin.dot<3>(axis); hkSimdReal projParam = fromLocalProj - pointAProj; hkVector4 fromPtProjAxis; fromPtProjAxis.setInterpolate( vertex0, vertex1, projParam / axisLength ); hkVector4 axisToRayStart; axisToRayStart.setSub( ray.m_origin, fromPtProjAxis); if ( ipT.isLessZero() && axisToRayStart.lengthSquared<3>().isGreater(radius * radius) ) { // Ray starts outside infinite cylinder and points away... must be no hit return hkcdRayCastResult::NO_HIT; } // Ray can only hit 1 cap... Use intersection point // to determine which sphere to test against (NB: this only works because // we have discarded cases where ray starts inside) hkVector4 capEnd; hkVector4Comparison mask = ptHeight.lessEqualZero(); capEnd.setSelect( mask, vertex0, vertex1 ); capEnd.setW( radius ); if( hkcdRayCastSphere( ray, capEnd, &fraction, normalOut, hkcdRayQueryFlags::NO_FLAGS).isHit() ) { hkSimdReal invFraction; invFraction.setSub( hkSimdReal_1, fraction ); invFraction.setMul( invFraction, invScale ); fractionInOut->setSelect( isInverseRay, invFraction, fraction ); *hitTypeOut = mask.anyIsSet() ? HK_CD_RAY_CAPSULE_CAP0 : HK_CD_RAY_CAPSULE_CAP1; return success; } return hkcdRayCastResult::NO_HIT; } } HK_FORCE_INLINE hkVector4Comparison hkcdRayBundleCapsuleIntersect( const hkcdRayBundle& rayBundle, hkVector4Parameter vertex0, hkVector4Parameter vertex1, hkSimdRealParameter radius, hkVector4& fractionsInOut, hkFourTransposedPoints& normalsOut ) { hkVector4 sToCylDistSq = hkcdPointSegmentDistanceSquared( rayBundle.m_start, vertex0, vertex1 ); hkVector4 radiusSqr; radiusSqr.setAll(radius * radius); hkVector4Comparison activeMask = rayBundle.m_activeRays; hkVector4Comparison rayStartOutside = sToCylDistSq.greaterEqual( radiusSqr ); activeMask.setAnd(activeMask, rayStartOutside); if ( !activeMask.anyIsSet() ) { return activeMask; } // Work out closest points to cylinder hkVector4 infInfDistSquared; //infInfDistSquared.setConstant<HK_QUADREAL_MAX>(); hkVector4 t, u; hkFourTransposedPoints dA; dA.setSub(rayBundle.m_end, rayBundle.m_start); hkVector4 dB; dB.setSub( vertex1, vertex0 ); // Get distance between inf lines + parametric description (t, u) of closest points, { hkcdClosestPointLineLine(rayBundle.m_start, dA, vertex0, dB, t, u); hkFourTransposedPoints p,q; p.setAddMulT(rayBundle.m_start, dA, t); hkFourTransposedPoints B4; B4.setAll(vertex0); hkFourTransposedPoints dB4; dB4.setAll(dB); q.setAddMulT(B4, dB4, u); hkFourTransposedPoints diff; diff.setSub(p, q); diff.dot3(diff, infInfDistSquared); } // Is infinite ray within radius of infinite cylinder? hkVector4Comparison isInfRayWithinCylinder = infInfDistSquared.lessEqual( radiusSqr ); activeMask.setAnd(activeMask, isInfRayWithinCylinder); if ( !activeMask.anyIsSet() ) { return activeMask; } hkSimdReal axisLength; hkVector4 axis; hkVector4 ipT; { axis = dB; // Check for zero axis hkSimdReal axisLengthSqrd = axis.lengthSquared<3>(); hkVector4Comparison mask = axisLengthSqrd.greater( hkSimdReal_Eps ); axisLength = axis.normalizeWithLength<3,HK_ACC_RAYCAST,HK_SQRT_IGNORE>(); axisLength.zeroIfFalse(mask); axis.zeroIfFalse(mask); hkVector4 component; dA.dot3(axis, component); component.setNeg<4>(component); hkFourTransposedPoints flatDir; hkFourTransposedPoints axis4; axis4.setAll(axis); flatDir.setAddMulT(dA, axis4, component); // Flatdir is now a ray firing in the "plane" of the cylinder. // Convert d to a parameterization instead of absolute distance along ray. // Avoid division by zero in case of ray parallel to infinite cylinder. hkVector4 flatDirLengthSquared3; flatDir.dot3(flatDir, flatDirLengthSquared3); hkVector4 d; d.setSub(radiusSqr, infInfDistSquared); d.div(flatDirLengthSquared3); d.setSqrt(d); d.setSub(t, d); mask = flatDirLengthSquared3.equalZero(); const hkVector4 minusOne = hkVector4::getConstant<HK_QUADREAL_MINUS1>(); ipT.setSelect(mask, minusOne, d); } // Intersection parameterization with infinite cylinder is outside length of ray // or is greater than a previous hit fraction hkVector4Comparison isFractionOk = ipT.less( fractionsInOut ); activeMask.setAnd(activeMask, isFractionOk); if( !activeMask.anyIsSet() ) { return activeMask; } hkVector4 ptHeight; const hkSimdReal pointAProj = vertex0.dot<3>(axis); // Find intersection point of actual ray with infinite cylinder hkFourTransposedPoints intersectPt; intersectPt.setAddMulT( rayBundle.m_start, dA, ipT ); // Test height of intersection point w.r.t. cylinder axis // to determine hit against actual cylinder // Intersection point projected against cylinder hkVector4 ptProj; intersectPt.dot3(axis, ptProj); ptHeight.setSub(ptProj, pointAProj); hkVector4 axisLengthVector; axisLengthVector.setAll(axisLength); hkFourTransposedPoints vertex0x4; vertex0x4.setAll(vertex0); hkFourTransposedPoints vertex1x4; vertex1x4.setAll(vertex1); hkFourTransposedPoints dBx4; dBx4.setAll(dB); hkVector4Comparison isRayWithinCylinder = ipT.greaterEqualZero(); hkVector4Comparison gtZero = ptHeight.greaterZero(); hkVector4Comparison ltAxisLength = ptHeight.less(axisLengthVector); hkVector4Comparison hitBodyMask; hitBodyMask.setAnd(gtZero, ltAxisLength); hitBodyMask.setAnd(hitBodyMask, isRayWithinCylinder); if ( hitBodyMask.anyIsSet() ) // Actual ray (not infinite ray) must intersect with infinite cylinder { // Calculate normal hkVector4 ratio; ratio.setDiv(ptHeight, axisLengthVector); hkFourTransposedPoints projPtOnAxis; projPtOnAxis.setAddMulT( vertex0x4, dBx4, ratio ); hkFourTransposedPoints normals; normals.setSub( intersectPt, projPtOnAxis ); normals.normalize(); normalsOut.setSelect(hitBodyMask, normals, normalsOut); // Output fraction fractionsInOut.setSelect(hitBodyMask, ipT, fractionsInOut); // This is a parameterization along the ray } hitBodyMask.setAndNot(activeMask, hitBodyMask); if (!hitBodyMask.anyIsSet()) { return activeMask; } // Cap tests { // Check whether start point is inside infinite cylinder or not hkVector4 fromLocalProj; rayBundle.m_start.dot3(axis, fromLocalProj); hkVector4 projParam; projParam.setSub(fromLocalProj, pointAProj); hkVector4 ratio; ratio.setDiv(projParam, axisLengthVector); hkFourTransposedPoints fromPtProjAxis; fromPtProjAxis.setAddMulT( vertex0x4, dBx4, ratio ); hkFourTransposedPoints axisToRayStart; axisToRayStart.setSub( rayBundle.m_start, fromPtProjAxis ); hkVector4 axisToRayStartLenSq; axisToRayStart.dot3(axisToRayStart, axisToRayStartLenSq); hkVector4Comparison gteZero = ipT.greaterEqualZero(); hkVector4Comparison lteRadiusSqr = axisToRayStartLenSq.lessEqual(radiusSqr); hkVector4Comparison maskOr; maskOr.setOr(gteZero, lteRadiusSqr); activeMask.setAnd(activeMask, maskOr); if ( !activeMask.anyIsSet() ) { // Ray starts outside infinite cylinder and points away... must be no hit return activeMask; } // Ray can only hit 1 cap... Use intersection point // to determine which sphere to test against (NB: this only works because // we have discarded cases where ray starts inside) hkFourTransposedPoints extra; hkVector4Comparison mask = ptHeight.lessEqualZero(); extra.setSelect( mask, vertex0x4, vertex1x4 ); hkcdRayBundle raySphere; raySphere.m_start.setSub(rayBundle.m_start, extra); raySphere.m_end.setSub(rayBundle.m_end, extra); raySphere.m_activeRays = hitBodyMask; hkVector4Comparison sphereMask = hkcdRayBundleSphereIntersect( raySphere, radius, fractionsInOut, normalsOut); activeMask.setSelect(hitBodyMask, sphereMask, activeMask); } return activeMask; } /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20140907) * * Confidential Information of Havok. (C) Copyright 1999-2014 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at www.havok.com/tryhavok. * */
35.63908
251
0.761014
wobbier
0804d8f097c1773304affe64b89d049d7f0a8b9d
751
cpp
C++
contest-1005-496/c-v2-cpp/main.cpp
easimonenko/solution-problems-from-codeforces
64251e0ba2c2ba619b0daf67f89f29b6dff8fd9f
[ "MIT" ]
1
2018-12-03T02:06:05.000Z
2018-12-03T02:06:05.000Z
contest-1005-496/c-v2-cpp/main.cpp
easimonenko/solution-problems-from-codeforces
64251e0ba2c2ba619b0daf67f89f29b6dff8fd9f
[ "MIT" ]
null
null
null
contest-1005-496/c-v2-cpp/main.cpp
easimonenko/solution-problems-from-codeforces
64251e0ba2c2ba619b0daf67f89f29b6dff8fd9f
[ "MIT" ]
null
null
null
#include <algorithm> #include <iostream> #include <map> #include <vector> using namespace std; int main() { int n; cin >> n; vector<long long> a(n); map<long long,int> v; for (int i = 0; i < n; i++) { cin >> a[i]; v[a[i]]++; } vector<long long> d; d.push_back(1); for (int i = 1; i < 32; i++) { d.push_back(d[i-1] << 1); } int ans = 0; for_each(a.begin(), a.end(), [&ans,d,&v](auto elem) { bool no = true; for (int k = 0; k < d.size(); k++) { long long r = d[k] - elem; if (r == elem && v[elem] == 1) { continue; } if (r > 0 && v.find(r) != v.end()) { no = false; break; } } if (no) { ans++; } //v.insert(elem); }); cout << ans << endl; return 0; }
16.326087
55
0.464714
easimonenko
080b961151465ead797fe5492414d7af7a76d943
25,920
cpp
C++
examples/IBFE/explicit/ex6/main.cpp
MSV-Project/IBAMR
3cf614c31bb3c94e2620f165ba967cba719c45ea
[ "BSD-3-Clause" ]
2
2017-12-06T06:16:36.000Z
2021-03-13T12:28:08.000Z
examples/IBFE/explicit/ex6/main.cpp
MSV-Project/IBAMR
3cf614c31bb3c94e2620f165ba967cba719c45ea
[ "BSD-3-Clause" ]
null
null
null
examples/IBFE/explicit/ex6/main.cpp
MSV-Project/IBAMR
3cf614c31bb3c94e2620f165ba967cba719c45ea
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2002-2013, Boyce Griffith // 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 New York University 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. // Config files #include <IBAMR_prefix_config.h> #include <IBTK_prefix_config.h> #include <SAMRAI_config.h> // Headers for basic PETSc functions #include <petscsys.h> // Headers for basic SAMRAI objects #include <BergerRigoutsos.h> #include <CartesianGridGeometry.h> #include <LoadBalancer.h> #include <StandardTagAndInitialize.h> // Headers for basic libMesh objects #include <libmesh/boundary_info.h> #include <libmesh/equation_systems.h> #include <libmesh/exodusII_io.h> #include <libmesh/mesh.h> #include <libmesh/mesh_function.h> #include <libmesh/mesh_generation.h> // Headers for application-specific algorithm/data structure objects #include <ibamr/IBExplicitHierarchyIntegrator.h> #include <ibamr/IBFEMethod.h> #include <ibamr/INSCollocatedHierarchyIntegrator.h> #include <ibamr/INSStaggeredHierarchyIntegrator.h> #include <ibamr/app_namespaces.h> #include <ibtk/AppInitializer.h> #include <ibtk/libmesh_utilities.h> #include <ibtk/muParserCartGridFunction.h> #include <ibtk/muParserRobinBcCoefs.h> // Elasticity model data. namespace ModelData { static double kappa_s = 1.0e6; // Tether (penalty) force function for the solid block. void block_tether_force_function( VectorValue<double>& F, const TensorValue<double>& /*FF*/, const Point& X, const Point& s, Elem* const /*elem*/, NumericVector<double>& /*X_vec*/, const vector<NumericVector<double>*>& /*system_data*/, double /*time*/, void* /*ctx*/) { F = kappa_s*(s-X); return; }// block_tether_force_function // Tether (penalty) force function for the thin beam. void beam_tether_force_function( VectorValue<double>& F, const TensorValue<double>& /*FF*/, const Point& X, const Point& s, Elem* const /*elem*/, NumericVector<double>& /*X_vec*/, const vector<NumericVector<double>*>& /*system_data*/, double /*time*/, void* /*ctx*/) { const double r = sqrt((s(0) - 0.2)*(s(0) - 0.2) + (s(1) - 0.2)*(s(1) - 0.2)); if (r <= 0.05) { F = kappa_s*(s-X); } else { F.zero(); } return; }// beam_tether_force_function // Stress tensor function for the thin beam. static double mu_s, lambda_s; void beam_PK1_stress_function( TensorValue<double>& PP, const TensorValue<double>& FF, const Point& /*X*/, const Point& s, Elem* const /*elem*/, NumericVector<double>& /*X_vec*/, const vector<NumericVector<double>*>& /*system_data*/, double /*time*/, void* /*ctx*/) { const double r = sqrt((s(0) - 0.2)*(s(0) - 0.2) + (s(1) - 0.2)*(s(1) - 0.2)); if (r > 0.05) { static const TensorValue<double> II(1.0,0.0,0.0, 0.0,1.0,0.0, 0.0,0.0,1.0); const TensorValue<double> CC = FF.transpose()*FF; const TensorValue<double> EE = 0.5*(CC - II); const TensorValue<double> SS = lambda_s*EE.tr()*II + 2.0*mu_s*EE; PP = FF*SS; } else { PP.zero(); } return; }// beam_PK1_stress_function } using namespace ModelData; // Function prototypes static ofstream drag_stream, lift_stream, A_x_posn_stream, A_y_posn_stream; void postprocess_data( Pointer<PatchHierarchy<NDIM> > patch_hierarchy, Pointer<INSHierarchyIntegrator> navier_stokes_integrator, Mesh& beam_mesh, EquationSystems* beam_equation_systems, Mesh& block_mesh, EquationSystems* block_equation_systems, const int iteration_num, const double loop_time, const string& data_dump_dirname); /******************************************************************************* * For each run, the input filename and restart information (if needed) must * * be given on the command line. For non-restarted case, command line is: * * * * executable <input file name> * * * * For restarted run, command line is: * * * * executable <input file name> <restart directory> <restart number> * * * *******************************************************************************/ int main( int argc, char* argv[]) { // Initialize libMesh, PETSc, MPI, and SAMRAI. LibMeshInit init(argc, argv); SAMRAI_MPI::setCommunicator(PETSC_COMM_WORLD); SAMRAI_MPI::setCallAbortInSerialInsteadOfExit(); SAMRAIManager::startup(); {// cleanup dynamically allocated objects prior to shutdown // Parse command line options, set some standard options from the input // file, initialize the restart database (if this is a restarted run), // and enable file logging. Pointer<AppInitializer> app_initializer = new AppInitializer(argc, argv, "IB.log"); Pointer<Database> input_db = app_initializer->getInputDatabase(); // Get various standard options set in the input file. const bool dump_viz_data = app_initializer->dumpVizData(); const int viz_dump_interval = app_initializer->getVizDumpInterval(); const bool uses_visit = dump_viz_data && app_initializer->getVisItDataWriter(); const bool uses_exodus = dump_viz_data && !app_initializer->getExodusIIFilename().empty(); const string block_exodus_filename = app_initializer->getExodusIIFilename("block"); const string beam_exodus_filename = app_initializer->getExodusIIFilename("beam" ); const bool dump_restart_data = app_initializer->dumpRestartData(); const int restart_dump_interval = app_initializer->getRestartDumpInterval(); const string restart_dump_dirname = app_initializer->getRestartDumpDirectory(); const bool dump_postproc_data = app_initializer->dumpPostProcessingData(); const int postproc_data_dump_interval = app_initializer->getPostProcessingDataDumpInterval(); const string postproc_data_dump_dirname = app_initializer->getPostProcessingDataDumpDirectory(); if (dump_postproc_data && (postproc_data_dump_interval > 0) && !postproc_data_dump_dirname.empty()) { Utilities::recursiveMkdir(postproc_data_dump_dirname); } const bool dump_timer_data = app_initializer->dumpTimerData(); const int timer_dump_interval = app_initializer->getTimerDumpInterval(); // Create a simple FE mesh. const double dx = input_db->getDouble("DX"); const double ds = input_db->getDouble("MFAC")*dx; Mesh block_mesh(NDIM); string block_elem_type = input_db->getString("BLOCK_ELEM_TYPE"); const double R = 0.05; if (block_elem_type == "TRI3" || block_elem_type == "TRI6") { const int num_circum_nodes = ceil(2.0*M_PI*R/ds); for (int k = 0; k < num_circum_nodes; ++k) { const double theta = 2.0*M_PI*static_cast<double>(k)/static_cast<double>(num_circum_nodes); block_mesh.add_point(Point(R*cos(theta), R*sin(theta))); } TriangleInterface triangle(block_mesh); triangle.triangulation_type() = TriangleInterface::GENERATE_CONVEX_HULL; triangle.elem_type() = Utility::string_to_enum<ElemType>(block_elem_type); triangle.desired_area() = sqrt(3.0)/4.0*ds*ds; triangle.insert_extra_points() = true; triangle.smooth_after_generating() = true; triangle.triangulate(); block_mesh.prepare_for_use(); } else { // NOTE: number of segments along boundary is 4*2^r. const double num_circum_segments = ceil(2.0*M_PI*R/ds); const int r = log2(0.25*num_circum_segments); MeshTools::Generation::build_sphere(block_mesh, R, r, Utility::string_to_enum<ElemType>(block_elem_type)); } for (MeshBase::node_iterator n_it = block_mesh.nodes_begin(); n_it != block_mesh.nodes_end(); ++n_it) { Node& n = **n_it; n(0) += 0.2; n(1) += 0.2; } Mesh beam_mesh(NDIM); string beam_elem_type = input_db->getString("BEAM_ELEM_TYPE"); MeshTools::Generation::build_square(beam_mesh, ceil(0.4/ds), ceil(0.02/ds), 0.2, 0.6, 0.19, 0.21, Utility::string_to_enum<ElemType>(beam_elem_type)); beam_mesh.prepare_for_use(); vector<Mesh*> meshes(2); meshes[0] = &block_mesh; meshes[1] = & beam_mesh; mu_s = input_db->getDouble("MU_S"); lambda_s = input_db->getDouble("LAMBDA_S"); kappa_s = input_db->getDouble("KAPPA_S"); // Create major algorithm and data objects that comprise the // application. These objects are configured from the input database // and, if this is a restarted run, from the restart database. Pointer<INSHierarchyIntegrator> navier_stokes_integrator; const string solver_type = app_initializer->getComponentDatabase("Main")->getString("solver_type"); if (solver_type == "STAGGERED") { navier_stokes_integrator = new INSStaggeredHierarchyIntegrator( "INSStaggeredHierarchyIntegrator", app_initializer->getComponentDatabase("INSStaggeredHierarchyIntegrator")); } else if (solver_type == "COLLOCATED") { navier_stokes_integrator = new INSCollocatedHierarchyIntegrator( "INSCollocatedHierarchyIntegrator", app_initializer->getComponentDatabase("INSCollocatedHierarchyIntegrator")); } else { TBOX_ERROR("Unsupported solver type: " << solver_type << "\n" << "Valid options are: COLLOCATED, STAGGERED"); } Pointer<IBFEMethod> ib_method_ops = new IBFEMethod( "IBFEMethod", app_initializer->getComponentDatabase("IBFEMethod"), meshes, app_initializer->getComponentDatabase("GriddingAlgorithm")->getInteger("max_levels")); Pointer<IBHierarchyIntegrator> time_integrator = new IBExplicitHierarchyIntegrator( "IBHierarchyIntegrator", app_initializer->getComponentDatabase("IBHierarchyIntegrator"), ib_method_ops, navier_stokes_integrator); Pointer<CartesianGridGeometry<NDIM> > grid_geometry = new CartesianGridGeometry<NDIM>( "CartesianGeometry", app_initializer->getComponentDatabase("CartesianGeometry")); Pointer<PatchHierarchy<NDIM> > patch_hierarchy = new PatchHierarchy<NDIM>( "PatchHierarchy", grid_geometry); Pointer<StandardTagAndInitialize<NDIM> > error_detector = new StandardTagAndInitialize<NDIM>( "StandardTagAndInitialize", time_integrator, app_initializer->getComponentDatabase("StandardTagAndInitialize")); Pointer<BergerRigoutsos<NDIM> > box_generator = new BergerRigoutsos<NDIM>(); Pointer<LoadBalancer<NDIM> > load_balancer = new LoadBalancer<NDIM>( "LoadBalancer", app_initializer->getComponentDatabase("LoadBalancer")); Pointer<GriddingAlgorithm<NDIM> > gridding_algorithm = new GriddingAlgorithm<NDIM>( "GriddingAlgorithm", app_initializer->getComponentDatabase("GriddingAlgorithm"), error_detector, box_generator, load_balancer); // Configure the IBFE solver. ib_method_ops->registerLagBodyForceFunction(&block_tether_force_function, std::vector<unsigned int>(), NULL, 0); ib_method_ops->registerLagBodyForceFunction( &beam_tether_force_function, std::vector<unsigned int>(), NULL, 1); ib_method_ops->registerPK1StressTensorFunction(&beam_PK1_stress_function, std::vector<unsigned int>(), NULL, 1); EquationSystems* block_equation_systems = ib_method_ops->getFEDataManager(0)->getEquationSystems(); EquationSystems* beam_equation_systems = ib_method_ops->getFEDataManager(1)->getEquationSystems(); // Create Eulerian initial condition specification objects. if (input_db->keyExists("VelocityInitialConditions")) { Pointer<CartGridFunction> u_init = new muParserCartGridFunction( "u_init", app_initializer->getComponentDatabase("VelocityInitialConditions"), grid_geometry); navier_stokes_integrator->registerVelocityInitialConditions(u_init); } if (input_db->keyExists("PressureInitialConditions")) { Pointer<CartGridFunction> p_init = new muParserCartGridFunction( "p_init", app_initializer->getComponentDatabase("PressureInitialConditions"), grid_geometry); navier_stokes_integrator->registerPressureInitialConditions(p_init); } // Create Eulerian boundary condition specification objects (when necessary). const IntVector<NDIM>& periodic_shift = grid_geometry->getPeriodicShift(); vector<RobinBcCoefStrategy<NDIM>*> u_bc_coefs(NDIM); if (periodic_shift.min() > 0) { for (unsigned int d = 0; d < NDIM; ++d) { u_bc_coefs[d] = NULL; } } else { for (unsigned int d = 0; d < NDIM; ++d) { ostringstream bc_coefs_name_stream; bc_coefs_name_stream << "u_bc_coefs_" << d; const string bc_coefs_name = bc_coefs_name_stream.str(); ostringstream bc_coefs_db_name_stream; bc_coefs_db_name_stream << "VelocityBcCoefs_" << d; const string bc_coefs_db_name = bc_coefs_db_name_stream.str(); u_bc_coefs[d] = new muParserRobinBcCoefs( bc_coefs_name, app_initializer->getComponentDatabase(bc_coefs_db_name), grid_geometry); } navier_stokes_integrator->registerPhysicalBoundaryConditions(u_bc_coefs); } // Create Eulerian body force function specification objects. if (input_db->keyExists("ForcingFunction")) { Pointer<CartGridFunction> f_fcn = new muParserCartGridFunction( "f_fcn", app_initializer->getComponentDatabase("ForcingFunction"), grid_geometry); time_integrator->registerBodyForceFunction(f_fcn); } // Set up visualization plot file writers. Pointer<VisItDataWriter<NDIM> > visit_data_writer = app_initializer->getVisItDataWriter(); if (uses_visit) { time_integrator->registerVisItDataWriter(visit_data_writer); } AutoPtr<ExodusII_IO> block_exodus_io(uses_exodus ? new ExodusII_IO(block_mesh) : NULL); AutoPtr<ExodusII_IO> beam_exodus_io(uses_exodus ? new ExodusII_IO( beam_mesh) : NULL); // Initialize hierarchy configuration and data on all patches. ib_method_ops->initializeFEData(); time_integrator->initializePatchHierarchy(patch_hierarchy, gridding_algorithm); // Deallocate initialization objects. app_initializer.setNull(); // Print the input database contents to the log file. plog << "Input database:\n"; input_db->printClassData(plog); // Write out initial visualization data. int iteration_num = time_integrator->getIntegratorStep(); double loop_time = time_integrator->getIntegratorTime(); if (dump_viz_data) { pout << "\n\nWriting visualization files...\n\n"; if (uses_visit) { time_integrator->setupPlotData(); visit_data_writer->writePlotData(patch_hierarchy, iteration_num, loop_time); } if (uses_exodus) { block_exodus_io->write_timestep(block_exodus_filename, *block_equation_systems, iteration_num/viz_dump_interval+1, loop_time); beam_exodus_io ->write_timestep( beam_exodus_filename, * beam_equation_systems, iteration_num/viz_dump_interval+1, loop_time); } } // Open streams to save lift and drag coefficients. if (SAMRAI_MPI::getRank() == 0) { drag_stream.open("C_D.curve", ios_base::out | ios_base::trunc); lift_stream.open("C_L.curve", ios_base::out | ios_base::trunc); A_x_posn_stream.open("A_x.curve", ios_base::out | ios_base::trunc); A_y_posn_stream.open("A_y.curve", ios_base::out | ios_base::trunc); } // Main time step loop. double loop_time_end = time_integrator->getEndTime(); double dt = 0.0; while (!MathUtilities<double>::equalEps(loop_time,loop_time_end) && time_integrator->stepsRemaining()) { iteration_num = time_integrator->getIntegratorStep(); loop_time = time_integrator->getIntegratorTime(); pout << "\n"; pout << "+++++++++++++++++++++++++++++++++++++++++++++++++++\n"; pout << "At beginning of timestep # " << iteration_num << "\n"; pout << "Simulation time is " << loop_time << "\n"; dt = time_integrator->getMaximumTimeStepSize(); time_integrator->advanceHierarchy(dt); loop_time += dt; pout << "\n"; pout << "At end of timestep # " << iteration_num << "\n"; pout << "Simulation time is " << loop_time << "\n"; pout << "+++++++++++++++++++++++++++++++++++++++++++++++++++\n"; pout << "\n"; // At specified intervals, write visualization and restart files, // print out timer data, and store hierarchy data for post // processing. iteration_num += 1; const bool last_step = !time_integrator->stepsRemaining(); if (dump_viz_data && (iteration_num%viz_dump_interval == 0 || last_step)) { pout << "\nWriting visualization files...\n\n"; if (uses_visit) { time_integrator->setupPlotData(); visit_data_writer->writePlotData(patch_hierarchy, iteration_num, loop_time); } if (uses_exodus) { block_exodus_io->write_timestep(block_exodus_filename, *block_equation_systems, iteration_num/viz_dump_interval+1, loop_time); beam_exodus_io ->write_timestep( beam_exodus_filename, * beam_equation_systems, iteration_num/viz_dump_interval+1, loop_time); } } if (dump_restart_data && (iteration_num%restart_dump_interval == 0 || last_step)) { pout << "\nWriting restart files...\n\n"; RestartManager::getManager()->writeRestartFile(restart_dump_dirname, iteration_num); } if (dump_timer_data && (iteration_num%timer_dump_interval == 0 || last_step)) { pout << "\nWriting timer data...\n\n"; TimerManager::getManager()->print(plog); } if (dump_postproc_data && (iteration_num%postproc_data_dump_interval == 0 || last_step)) { pout << "\nWriting state data...\n\n"; postprocess_data(patch_hierarchy, navier_stokes_integrator, beam_mesh, beam_equation_systems, block_mesh, block_equation_systems, iteration_num, loop_time, postproc_data_dump_dirname); } } // Close the logging streams. if (SAMRAI_MPI::getRank() == 0) { drag_stream.close(); lift_stream.close(); A_x_posn_stream.close(); A_y_posn_stream.close(); } // Cleanup Eulerian boundary condition specification objects (when // necessary). for (unsigned int d = 0; d < NDIM; ++d) delete u_bc_coefs[d]; }// cleanup dynamically allocated objects prior to shutdown SAMRAIManager::shutdown(); return 0; }// main void postprocess_data( Pointer<PatchHierarchy<NDIM> > /*patch_hierarchy*/, Pointer<INSHierarchyIntegrator> /*navier_stokes_integrator*/, Mesh& beam_mesh, EquationSystems* beam_equation_systems, Mesh& block_mesh, EquationSystems* block_equation_systems, const int /*iteration_num*/, const double loop_time, const string& /*data_dump_dirname*/) { double F_integral[NDIM]; for (unsigned int d = 0; d < NDIM; ++d) F_integral[d] = 0.0; Mesh* mesh[2] = {&beam_mesh , &block_mesh}; EquationSystems* equation_systems[2] = {beam_equation_systems , block_equation_systems}; for (unsigned int k = 0; k < 2; ++k) { System& F_system = equation_systems[k]->get_system<System>(IBFEMethod::FORCE_SYSTEM_NAME); NumericVector<double>* F_vec = F_system.solution.get(); NumericVector<double>* F_ghost_vec = F_system.current_local_solution.get(); F_vec->localize(*F_ghost_vec); DofMap& F_dof_map = F_system.get_dof_map(); blitz::Array<std::vector<unsigned int>,1> F_dof_indices(NDIM); AutoPtr<FEBase> fe(FEBase::build(NDIM, F_dof_map.variable_type(0))); AutoPtr<QBase> qrule = QBase::build(QGAUSS, NDIM, FIFTH); fe->attach_quadrature_rule(qrule.get()); const std::vector<std::vector<double> >& phi = fe->get_phi(); const std::vector<double>& JxW = fe->get_JxW(); blitz::Array<double,2> F_node; const MeshBase::const_element_iterator el_begin = mesh[k]->active_local_elements_begin(); const MeshBase::const_element_iterator el_end = mesh[k]->active_local_elements_end(); for (MeshBase::const_element_iterator el_it = el_begin; el_it != el_end; ++el_it) { Elem* const elem = *el_it; fe->reinit(elem); for (unsigned int d = 0; d < NDIM; ++d) { F_dof_map.dof_indices(elem, F_dof_indices(d), d); } const int n_qp = qrule->n_points(); const int n_basis = F_dof_indices(0).size(); get_values_for_interpolation(F_node, *F_ghost_vec, F_dof_indices); for (int qp = 0; qp < n_qp; ++qp) { for (int k = 0; k < n_basis; ++k) { for (int d = 0; d < NDIM; ++d) { F_integral[d] += F_node(k,d)*phi[k][qp]*JxW[qp]; } } } } } SAMRAI_MPI::sumReduction(F_integral,NDIM); if (SAMRAI_MPI::getRank() == 0) { drag_stream.precision(12); drag_stream.setf(ios::fixed,ios::floatfield); drag_stream << loop_time << " " << -F_integral[0] << endl; lift_stream.precision(12); lift_stream.setf(ios::fixed,ios::floatfield); lift_stream << loop_time << " " << -F_integral[1] << endl; } System& X_system = beam_equation_systems->get_system<System>(IBFEMethod::COORDS_SYSTEM_NAME); NumericVector<double>* X_vec = X_system.solution.get(); AutoPtr<NumericVector<Number> > X_serial_vec = NumericVector<Number>::build(); X_serial_vec->init(X_vec->size(), true, SERIAL); X_vec->localize(*X_serial_vec); DofMap& X_dof_map = X_system.get_dof_map(); vector<unsigned int> vars(2); vars[0] = 0; vars[1] = 1; MeshFunction X_fcn(*beam_equation_systems, *X_serial_vec, X_dof_map, vars); X_fcn.init(); DenseVector<double> X_A(2); X_fcn(Point(0.6,0.2,0), 0.0, X_A); if (SAMRAI_MPI::getRank() == 0) { A_x_posn_stream.precision(12); A_x_posn_stream.setf(ios::fixed,ios::floatfield); A_x_posn_stream << loop_time << " " << X_A(0) << endl; A_y_posn_stream.precision(12); A_y_posn_stream.setf(ios::fixed,ios::floatfield); A_y_posn_stream << loop_time << " " << X_A(1) << endl; } return; }// postprocess_data
45
173
0.621952
MSV-Project
080e711d0461bcc65eeee7ceeff7aa9d626a0570
4,195
hpp
C++
SDK/ARKSurvivalEvolved_Jugbug_Character_BaseBP_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
10
2020-02-17T19:08:46.000Z
2021-07-31T11:07:19.000Z
SDK/ARKSurvivalEvolved_Jugbug_Character_BaseBP_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
9
2020-02-17T18:15:41.000Z
2021-06-06T19:17:34.000Z
SDK/ARKSurvivalEvolved_Jugbug_Character_BaseBP_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
3
2020-07-22T17:42:07.000Z
2021-06-19T17:16:13.000Z
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_Jugbug_Character_BaseBP_structs.hpp" namespace sdk { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass Jugbug_Character_BaseBP.Jugbug_Character_BaseBP_C // 0x0048 (0x22B0 - 0x2268) class AJugbug_Character_BaseBP_C : public AInsect_Character_Base_C { public: class UDinoCharacterStatusComponent_BP_JugBug_C* DinoCharacterStatus_BP_JugBug_C1; // 0x2268(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData) class UAudioComponent* LivingAudio; // 0x2270(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData) float ResourceAmount; // 0x2278(0x0004) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, SaveGame, IsPlainOldData) TEnumAsByte<EJugbugType> JugbugType; // 0x227C(0x0001) (Edit, BlueprintVisible, ZeroConstructor, SaveGame, IsPlainOldData) unsigned char UnknownData00[0x3]; // 0x227D(0x0003) MISSED OFFSET float MaxResourceAmount; // 0x2280(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) float ResourceAmountFillTime; // 0x2284(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) float MinSpeed; // 0x2288(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) int MaxItemsToGive; // 0x228C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) class UClass* PrimalItemToGive; // 0x2290(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) double LastUpdateTime; // 0x2298(0x0008) (Edit, BlueprintVisible, ZeroConstructor, Transient, DisableEditOnInstance, IsPlainOldData) float MaxJugbugWaterGiveAmount; // 0x22A0(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) unsigned char UnknownData01[0x4]; // 0x22A4(0x0004) MISSED OFFSET double LastGiveResourcesTime; // 0x22A8(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass Jugbug_Character_BaseBP.Jugbug_Character_BaseBP_C"); return ptr; } void BPTimerNonDedicated(); void BPTimerServer(); bool BlueprintCanAttack(int* AttackIndex, float* Distance, float* attackRangeOffset, class AActor** OtherTarget); TArray<struct FMultiUseEntry> STATIC_BPGetMultiUseEntries(class APlayerController** ForPC, TArray<struct FMultiUseEntry>* MultiUseEntries); void AddResource(float amount, float* NewResourceAmount, float* AddedResourceAmount); bool BPTryMultiUse(class APlayerController** ForPC, int* UseIndex); void RefreshResourceAmount(); void BlueprintDrawFloatingHUD(class AShooterHUD** HUD, float* CenterX, float* CenterY, float* DrawScale); void UserConstructionScript(); void ExecuteUbergraph_Jugbug_Character_BaseBP(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
67.66129
223
0.579023
2bite
080fb35dcf54903da9cb5c65214501b380c3a870
6,248
cpp
C++
src/utility/RTC8563_Class.cpp
mayopan/M5Unified
d5473378016c98e3932a83fcfbb54e644c4aab7a
[ "MIT" ]
38
2021-10-10T14:37:44.000Z
2022-03-20T10:45:41.000Z
src/utility/RTC8563_Class.cpp
mayopan/M5Unified
d5473378016c98e3932a83fcfbb54e644c4aab7a
[ "MIT" ]
15
2021-11-01T05:52:07.000Z
2022-03-05T23:02:34.000Z
src/utility/RTC8563_Class.cpp
mayopan/M5Unified
d5473378016c98e3932a83fcfbb54e644c4aab7a
[ "MIT" ]
9
2021-10-10T15:53:05.000Z
2022-03-06T16:24:19.000Z
// Copyright (c) M5Stack. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include "RTC8563_Class.hpp" #include <sys/time.h> namespace m5 { static std::uint8_t bcd2ToByte(std::uint8_t value) { return ((value >> 4) * 10) + (value & 0x0F); } static std::uint8_t byteToBcd2(std::uint8_t value) { std::uint_fast8_t bcdhigh = value / 10; return (bcdhigh << 4) | (value - (bcdhigh * 10)); } bool RTC8563_Class::begin(I2C_Class* i2c) { if (i2c) { _i2c = i2c; i2c->begin(); } /// TimerCameraの内蔵RTCが初期化に失敗することがあったため、最初に空打ちする; writeRegister8(0x00, 0x00); _init = writeRegister8(0x00, 0x00) && writeRegister8(0x0E, 0x03); return _init; } bool RTC8563_Class::getVoltLow(void) { return readRegister8(0x02) & 0x80; // RTCC_VLSEC_MASK } bool RTC8563_Class::getDateTime(rtc_datetime_t* datetime) const { std::uint8_t buf[7] = { 0 }; if (!isEnabled() || !readRegister(0x02, buf, 7)) { return false; } datetime->time.seconds = bcd2ToByte(buf[0] & 0x7f); datetime->time.minutes = bcd2ToByte(buf[1] & 0x7f); datetime->time.hours = bcd2ToByte(buf[2] & 0x3f); datetime->date.date = bcd2ToByte(buf[3] & 0x3f); datetime->date.weekDay = bcd2ToByte(buf[4] & 0x07); datetime->date.month = bcd2ToByte(buf[5] & 0x1f); datetime->date.year = bcd2ToByte(buf[6] & 0xff) + ((0x80 & buf[5]) ? 1900 : 2000); return true; } bool RTC8563_Class::getTime(rtc_time_t* time) const { std::uint8_t buf[3] = { 0 }; if (!isEnabled() || !readRegister(0x02, buf, 3)) { return false; } time->seconds = bcd2ToByte(buf[0] & 0x7f); time->minutes = bcd2ToByte(buf[1] & 0x7f); time->hours = bcd2ToByte(buf[2] & 0x3f); return true; } void RTC8563_Class::setTime(const rtc_time_t& time) { std::uint8_t buf[] = { byteToBcd2(time.seconds) , byteToBcd2(time.minutes) , byteToBcd2(time.hours) }; writeRegister(0x02, buf, sizeof(buf)); } bool RTC8563_Class::getDate(rtc_date_t* date) const { std::uint8_t buf[4] = {0}; if (!readRegister(0x05, buf, 4)) { return false; } date->date = bcd2ToByte(buf[0] & 0x3f); date->weekDay = bcd2ToByte(buf[1] & 0x07); date->month = bcd2ToByte(buf[2] & 0x1f); date->year = bcd2ToByte(buf[3] & 0xff) + ((0x80 & buf[2]) ? 1900 : 2000); return true; } void RTC8563_Class::setDate(const rtc_date_t& date) { std::uint8_t w = date.weekDay; if (w > 6 && date.year >= 1900 && ((std::size_t)(date.month - 1)) < 12) { /// weekDay auto adjust std::int_fast16_t y = date.year / 100; w = (date.year + (date.year >> 2) - y + (y >> 2) + (13 * date.month + 8) / 5 + date.date) % 7; } std::uint8_t buf[] = { byteToBcd2(date.date) , w , (std::uint8_t)(byteToBcd2(date.month) + (date.year < 2000 ? 0x80 : 0)) , byteToBcd2(date.year % 100) }; writeRegister(0x05, buf, sizeof(buf)); } int RTC8563_Class::setAlarmIRQ(int afterSeconds) { std::uint8_t reg_value = readRegister8(0x01) & ~0x0C; if (afterSeconds < 0) { // disable timer writeRegister8(0x01, reg_value & ~0x01); writeRegister8(0x0E, 0x03); return -1; } std::size_t div = 1; std::uint8_t type_value = 0x82; if (afterSeconds < 270) { if (afterSeconds > 255) { afterSeconds = 255; } } else { div = 60; afterSeconds = (afterSeconds + 30) / div; if (afterSeconds > 255) { afterSeconds = 255; } type_value = 0x83; } writeRegister8(0x0E, type_value); writeRegister8(0x0F, afterSeconds); writeRegister8(0x01, (reg_value | 0x01) & ~0x80); return afterSeconds * div; } int RTC8563_Class::setAlarmIRQ(const rtc_time_t &time) { union { std::uint32_t raw = ~0; std::uint8_t buf[4]; }; bool irq_enable = false; if (time.minutes >= 0) { irq_enable = true; buf[0] = byteToBcd2(time.minutes) & 0x7f; } if (time.hours >= 0) { irq_enable = true; buf[1] = byteToBcd2(time.hours) & 0x3f; } writeRegister(0x09, buf, 4); if (irq_enable) { bitOn(0x01, 0x02); } else { bitOff(0x01, 0x02); } return irq_enable; } int RTC8563_Class::setAlarmIRQ(const rtc_date_t &date, const rtc_time_t &time) { union { std::uint32_t raw = ~0; std::uint8_t buf[4]; }; bool irq_enable = false; if (time.minutes >= 0) { irq_enable = true; buf[0] = byteToBcd2(time.minutes) & 0x7f; } if (time.hours >= 0) { irq_enable = true; buf[1] = byteToBcd2(time.hours) & 0x3f; } if (date.date >= 0) { irq_enable = true; buf[2] = byteToBcd2(date.date) & 0x3f; } if (date.weekDay >= 0) { irq_enable = true; buf[3] = byteToBcd2(date.weekDay) & 0x07; } writeRegister(0x09, buf, 4); if (irq_enable) { bitOn(0x01, 1 << 1); } else { bitOff(0x01, 1 << 1); } return irq_enable; } bool RTC8563_Class::getIRQstatus(void) { return _init && (0x0C & readRegister8(0x01)); } void RTC8563_Class::clearIRQ(void) { if (!_init) { return; } bitOff(0x01, 0x0C); } void RTC8563_Class::disableIRQ(void) { if (!_init) { return; } // disable alerm (bit7:1=disabled) std::uint8_t buf[4] = { 0x80, 0x80, 0x80, 0x80 }; writeRegister(0x09, buf, 4); // disable timer (bit7:0=disabled) writeRegister8(0x0E, 0); // clear flag and INT enable bits writeRegister8(0x01, 0x00); } void RTC8563_Class::setSystemTimeFromRtc(void) { rtc_datetime_t dt; if (getDateTime(&dt)) { tm t_st; t_st.tm_isdst = -1; t_st.tm_year = dt.date.year - 1900; t_st.tm_mon = dt.date.month - 1; t_st.tm_mday = dt.date.date; t_st.tm_hour = dt.time.hours; t_st.tm_min = dt.time.minutes; t_st.tm_sec = dt.time.seconds; timeval now; now.tv_sec = mktime(&t_st); now.tv_usec = 0; settimeofday(&now, nullptr); } } }
23.226766
101
0.579706
mayopan
08136e19c5e71985be23ecc203603009025ac121
1,307
hpp
C++
AST/JSONStruct.hpp
germago119/C__IDE
2fb9950e2c67932eb69806094c65fcd9ae9ca220
[ "MIT" ]
null
null
null
AST/JSONStruct.hpp
germago119/C__IDE
2fb9950e2c67932eb69806094c65fcd9ae9ca220
[ "MIT" ]
null
null
null
AST/JSONStruct.hpp
germago119/C__IDE
2fb9950e2c67932eb69806094c65fcd9ae9ca220
[ "MIT" ]
1
2020-02-07T17:41:56.000Z
2020-02-07T17:41:56.000Z
// // Created by Roger Valderrama on 4/10/18. // /** * @file JSONStruct.hpp * @version 1.0 * @date 4/10/18 * @author Roger Valderrama * @title JSON for Structs * @brief JSON Class for saving structs with its variables. */ #ifndef C_IDE_JSONSTRUCT_HPP #define C_IDE_JSONSTRUCT_HPP #include "JSONVar.hpp" #include <QtCore/QJsonArray> #include <QtCore/QJsonObject> class JSONStruct { /** * @brief An array oj Json for the variables of the line of code. */ QJsonArray *variables = new QJsonArray; /** * @brief json that represent the JsonObject that will be modified. */ QJsonObject *json = new QJsonObject; public: /** * @brief It add all variables to a Json and it prints it and add it to the log file. */ void submit(); /** * @brief Converts the JSON into a char so it can be added to the log file. */ const char *toLog(); /** * @brief Converts the JSON into a string. */ std::string toString(); /** * @brief It adds Variables to the JSON for struct. * @param jsonVar each json variable it will add. */ void add(JSONVar *jsonVar); /** * @brief It inserts to the JSON each key with its value. */ void put(std::string, std::string); }; #endif //C_IDE_JSONSTRUCT_HPP
20.107692
88
0.633512
germago119
0813a661d4d3fdbd66f5829b0064d23e999e0450
1,721
hpp
C++
include/cynodelic/tesela/detail/tdouble_ops.hpp
cynodelic/tesela
3b86a7b9501c7136d5168c7e314740fa7f72f7a7
[ "BSL-1.0" ]
null
null
null
include/cynodelic/tesela/detail/tdouble_ops.hpp
cynodelic/tesela
3b86a7b9501c7136d5168c7e314740fa7f72f7a7
[ "BSL-1.0" ]
null
null
null
include/cynodelic/tesela/detail/tdouble_ops.hpp
cynodelic/tesela
3b86a7b9501c7136d5168c7e314740fa7f72f7a7
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2019 Álvaro Ceballos // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt /** * @file tdouble_ops.hpp * * @brief Macros for defining `tdouble` operators. */ #ifndef CYNODELIC_TESELA_DETAIL_TDOUBLE_OPS_HPP #define CYNODELIC_TESELA_DETAIL_TDOUBLE_OPS_HPP #include <cynodelic/tesela/config.hpp> #define CYNODELIC_TESELA_TDOUBLE_DEFINE_ARITHMETIC_OPERATOR(op) \ constexpr friend tdouble operator op(const tdouble& lhs,const tdouble& rhs) \ { \ return tdouble(lhs.data op rhs.data); \ } \ constexpr friend tdouble operator op(const tdouble& lhs,const value_type& rhs) \ { \ return tdouble(lhs.data op tdouble(rhs).data); \ } \ constexpr friend tdouble operator op(const value_type& lhs,const tdouble& rhs) \ { \ return tdouble(tdouble(lhs).data op rhs.data); \ } #define CYNODELIC_TESELA_TDOUBLE_DEFINE_COMPARISON_OPERATOR(op) \ constexpr friend bool operator op(const tdouble& lhs,const tdouble& rhs) \ { \ return lhs.data op rhs.data; \ } \ constexpr friend bool operator op(const tdouble& lhs,const value_type& rhs) \ { \ return lhs.data op rhs; \ } \ constexpr friend bool operator op(const value_type& lhs,const tdouble& rhs) \ { \ return lhs op rhs.data; \ } #define CYNODELIC_TESELA_TDOUBLE_DEFINE_COMPOUND_OPERATOR(cmp_op,op) \ template <typename T> \ tdouble& operator cmp_op(const T& rhs) \ { \ data = quantize(data op quantize(rhs)); \ return *this; \ } \ tdouble& operator cmp_op(const tdouble& rhs) \ { \ data = quantize(data op rhs.data); \ return *this; \ } #endif // CYNODELIC_TESELA_DETAIL_TDOUBLE_OPS_HPP
27.31746
82
0.715863
cynodelic
0814f2a81b75fe973444bad545cb414d902d4397
9,524
hpp
C++
src/functions/functions.hpp
Hotege/irafl
1154bb69650e98998b28aed688f424cfb94413f9
[ "MIT" ]
null
null
null
src/functions/functions.hpp
Hotege/irafl
1154bb69650e98998b28aed688f424cfb94413f9
[ "MIT" ]
null
null
null
src/functions/functions.hpp
Hotege/irafl
1154bb69650e98998b28aed688f424cfb94413f9
[ "MIT" ]
null
null
null
#if !defined(_FUNCTIONS_FUNCTIONS_HPP_) #define _FUNCTIONS_FUNCTIONS_HPP_ #include <irafldef.h> #include <cmath> namespace IRAFLFunc { static double PI = atan(1.0) * 4; static double ColorNormal[256] = { 0.0, 0.00392156862745098, 0.00784313725490196, 0.011764705882352941, 0.01568627450980392, 0.0196078431372549, 0.023529411764705882, 0.027450980392156862, 0.03137254901960784, 0.03529411764705882, 0.0392156862745098, 0.043137254901960784, 0.047058823529411764, 0.050980392156862744, 0.054901960784313725, 0.058823529411764705, 0.06274509803921569, 0.06666666666666667, 0.07058823529411765, 0.07450980392156863, 0.0784313725490196, 0.08235294117647059, 0.08627450980392157, 0.09019607843137255, 0.09411764705882353, 0.09803921568627451, 0.10196078431372549, 0.10588235294117647, 0.10980392156862745, 0.11372549019607843, 0.11764705882352941, 0.12156862745098039, 0.12549019607843137, 0.12941176470588237, 0.13333333333333333, 0.13725490196078433, 0.1411764705882353, 0.1450980392156863, 0.14901960784313725, 0.15294117647058825, 0.1568627450980392, 0.1607843137254902, 0.16470588235294117, 0.16862745098039217, 0.17254901960784313, 0.17647058823529413, 0.1803921568627451, 0.1843137254901961, 0.18823529411764706, 0.19215686274509805, 0.19607843137254902, 0.2, 0.20392156862745098, 0.20784313725490197, 0.21176470588235294, 0.21568627450980393, 0.2196078431372549, 0.2235294117647059, 0.22745098039215686, 0.23137254901960785, 0.23529411764705882, 0.23921568627450981, 0.24313725490196078, 0.24705882352941178, 0.25098039215686274, 0.2549019607843137, 0.25882352941176473, 0.2627450980392157, 0.26666666666666666, 0.27058823529411763, 0.27450980392156865, 0.2784313725490196, 0.2823529411764706, 0.28627450980392155, 0.2901960784313726, 0.29411764705882354, 0.2980392156862745, 0.30196078431372547, 0.3058823529411765, 0.30980392156862746, 0.3137254901960784, 0.3176470588235294, 0.3215686274509804, 0.3254901960784314, 0.32941176470588235, 0.3333333333333333, 0.33725490196078434, 0.3411764705882353, 0.34509803921568627, 0.34901960784313724, 0.35294117647058826, 0.3568627450980392, 0.3607843137254902, 0.36470588235294116, 0.3686274509803922, 0.37254901960784315, 0.3764705882352941, 0.3803921568627451, 0.3843137254901961, 0.38823529411764707, 0.39215686274509803, 0.396078431372549, 0.4, 0.403921568627451, 0.40784313725490196, 0.4117647058823529, 0.41568627450980394, 0.4196078431372549, 0.4235294117647059, 0.42745098039215684, 0.43137254901960786, 0.43529411764705883, 0.4392156862745098, 0.44313725490196076, 0.4470588235294118, 0.45098039215686275, 0.4549019607843137, 0.4588235294117647, 0.4627450980392157, 0.4666666666666667, 0.47058823529411764, 0.4745098039215686, 0.47843137254901963, 0.4823529411764706, 0.48627450980392156, 0.49019607843137253, 0.49411764705882355, 0.4980392156862745, 0.5019607843137255, 0.5058823529411764, 0.5098039215686274, 0.5137254901960784, 0.5176470588235295, 0.5215686274509804, 0.5254901960784314, 0.5294117647058824, 0.5333333333333333, 0.5372549019607843, 0.5411764705882353, 0.5450980392156862, 0.5490196078431373, 0.5529411764705883, 0.5568627450980392, 0.5607843137254902, 0.5647058823529412, 0.5686274509803921, 0.5725490196078431, 0.5764705882352941, 0.5803921568627451, 0.5843137254901961, 0.5882352941176471, 0.592156862745098, 0.596078431372549, 0.6, 0.6039215686274509, 0.6078431372549019, 0.611764705882353, 0.615686274509804, 0.6196078431372549, 0.6235294117647059, 0.6274509803921569, 0.6313725490196078, 0.6352941176470588, 0.6392156862745098, 0.6431372549019608, 0.6470588235294118, 0.6509803921568628, 0.6549019607843137, 0.6588235294117647, 0.6627450980392157, 0.6666666666666666, 0.6705882352941176, 0.6745098039215687, 0.6784313725490196, 0.6823529411764706, 0.6862745098039216, 0.6901960784313725, 0.6941176470588235, 0.6980392156862745, 0.7019607843137254, 0.7058823529411765, 0.7098039215686275, 0.7137254901960784, 0.7176470588235294, 0.7215686274509804, 0.7254901960784313, 0.7294117647058823, 0.7333333333333333, 0.7372549019607844, 0.7411764705882353, 0.7450980392156863, 0.7490196078431373, 0.7529411764705882, 0.7568627450980392, 0.7607843137254902, 0.7647058823529411, 0.7686274509803922, 0.7725490196078432, 0.7764705882352941, 0.7803921568627451, 0.7843137254901961, 0.788235294117647, 0.792156862745098, 0.796078431372549, 0.8, 0.803921568627451, 0.807843137254902, 0.8117647058823529, 0.8156862745098039, 0.8196078431372549, 0.8235294117647058, 0.8274509803921568, 0.8313725490196079, 0.8352941176470589, 0.8392156862745098, 0.8431372549019608, 0.8470588235294118, 0.8509803921568627, 0.8549019607843137, 0.8588235294117647, 0.8627450980392157, 0.8666666666666667, 0.8705882352941177, 0.8745098039215686, 0.8784313725490196, 0.8823529411764706, 0.8862745098039215, 0.8901960784313725, 0.8941176470588236, 0.8980392156862745, 0.9019607843137255, 0.9058823529411765, 0.9098039215686274, 0.9137254901960784, 0.9176470588235294, 0.9215686274509803, 0.9254901960784314, 0.9294117647058824, 0.9333333333333333, 0.9372549019607843, 0.9411764705882353, 0.9450980392156862, 0.9490196078431372, 0.9529411764705882, 0.9568627450980393, 0.9607843137254902, 0.9647058823529412, 0.9686274509803922, 0.9725490196078431, 0.9764705882352941, 0.9803921568627451, 0.984313725490196, 0.9882352941176471, 0.9921568627450981, 0.996078431372549, 1.0, }; static const unsigned int crc32tab[] = { 0x00000000L, 0x77073096L, 0xee0e612cL, 0x990951baL, 0x076dc419L, 0x706af48fL, 0xe963a535L, 0x9e6495a3L, 0x0edb8832L, 0x79dcb8a4L, 0xe0d5e91eL, 0x97d2d988L, 0x09b64c2bL, 0x7eb17cbdL, 0xe7b82d07L, 0x90bf1d91L, 0x1db71064L, 0x6ab020f2L, 0xf3b97148L, 0x84be41deL, 0x1adad47dL, 0x6ddde4ebL, 0xf4d4b551L, 0x83d385c7L, 0x136c9856L, 0x646ba8c0L, 0xfd62f97aL, 0x8a65c9ecL, 0x14015c4fL, 0x63066cd9L, 0xfa0f3d63L, 0x8d080df5L, 0x3b6e20c8L, 0x4c69105eL, 0xd56041e4L, 0xa2677172L, 0x3c03e4d1L, 0x4b04d447L, 0xd20d85fdL, 0xa50ab56bL, 0x35b5a8faL, 0x42b2986cL, 0xdbbbc9d6L, 0xacbcf940L, 0x32d86ce3L, 0x45df5c75L, 0xdcd60dcfL, 0xabd13d59L, 0x26d930acL, 0x51de003aL, 0xc8d75180L, 0xbfd06116L, 0x21b4f4b5L, 0x56b3c423L, 0xcfba9599L, 0xb8bda50fL, 0x2802b89eL, 0x5f058808L, 0xc60cd9b2L, 0xb10be924L, 0x2f6f7c87L, 0x58684c11L, 0xc1611dabL, 0xb6662d3dL, 0x76dc4190L, 0x01db7106L, 0x98d220bcL, 0xefd5102aL, 0x71b18589L, 0x06b6b51fL, 0x9fbfe4a5L, 0xe8b8d433L, 0x7807c9a2L, 0x0f00f934L, 0x9609a88eL, 0xe10e9818L, 0x7f6a0dbbL, 0x086d3d2dL, 0x91646c97L, 0xe6635c01L, 0x6b6b51f4L, 0x1c6c6162L, 0x856530d8L, 0xf262004eL, 0x6c0695edL, 0x1b01a57bL, 0x8208f4c1L, 0xf50fc457L, 0x65b0d9c6L, 0x12b7e950L, 0x8bbeb8eaL, 0xfcb9887cL, 0x62dd1ddfL, 0x15da2d49L, 0x8cd37cf3L, 0xfbd44c65L, 0x4db26158L, 0x3ab551ceL, 0xa3bc0074L, 0xd4bb30e2L, 0x4adfa541L, 0x3dd895d7L, 0xa4d1c46dL, 0xd3d6f4fbL, 0x4369e96aL, 0x346ed9fcL, 0xad678846L, 0xda60b8d0L, 0x44042d73L, 0x33031de5L, 0xaa0a4c5fL, 0xdd0d7cc9L, 0x5005713cL, 0x270241aaL, 0xbe0b1010L, 0xc90c2086L, 0x5768b525L, 0x206f85b3L, 0xb966d409L, 0xce61e49fL, 0x5edef90eL, 0x29d9c998L, 0xb0d09822L, 0xc7d7a8b4L, 0x59b33d17L, 0x2eb40d81L, 0xb7bd5c3bL, 0xc0ba6cadL, 0xedb88320L, 0x9abfb3b6L, 0x03b6e20cL, 0x74b1d29aL, 0xead54739L, 0x9dd277afL, 0x04db2615L, 0x73dc1683L, 0xe3630b12L, 0x94643b84L, 0x0d6d6a3eL, 0x7a6a5aa8L, 0xe40ecf0bL, 0x9309ff9dL, 0x0a00ae27L, 0x7d079eb1L, 0xf00f9344L, 0x8708a3d2L, 0x1e01f268L, 0x6906c2feL, 0xf762575dL, 0x806567cbL, 0x196c3671L, 0x6e6b06e7L, 0xfed41b76L, 0x89d32be0L, 0x10da7a5aL, 0x67dd4accL, 0xf9b9df6fL, 0x8ebeeff9L, 0x17b7be43L, 0x60b08ed5L, 0xd6d6a3e8L, 0xa1d1937eL, 0x38d8c2c4L, 0x4fdff252L, 0xd1bb67f1L, 0xa6bc5767L, 0x3fb506ddL, 0x48b2364bL, 0xd80d2bdaL, 0xaf0a1b4cL, 0x36034af6L, 0x41047a60L, 0xdf60efc3L, 0xa867df55L, 0x316e8eefL, 0x4669be79L, 0xcb61b38cL, 0xbc66831aL, 0x256fd2a0L, 0x5268e236L, 0xcc0c7795L, 0xbb0b4703L, 0x220216b9L, 0x5505262fL, 0xc5ba3bbeL, 0xb2bd0b28L, 0x2bb45a92L, 0x5cb36a04L, 0xc2d7ffa7L, 0xb5d0cf31L, 0x2cd99e8bL, 0x5bdeae1dL, 0x9b64c2b0L, 0xec63f226L, 0x756aa39cL, 0x026d930aL, 0x9c0906a9L, 0xeb0e363fL, 0x72076785L, 0x05005713L, 0x95bf4a82L, 0xe2b87a14L, 0x7bb12baeL, 0x0cb61b38L, 0x92d28e9bL, 0xe5d5be0dL, 0x7cdcefb7L, 0x0bdbdf21L, 0x86d3d2d4L, 0xf1d4e242L, 0x68ddb3f8L, 0x1fda836eL, 0x81be16cdL, 0xf6b9265bL, 0x6fb077e1L, 0x18b74777L, 0x88085ae6L, 0xff0f6a70L, 0x66063bcaL, 0x11010b5cL, 0x8f659effL, 0xf862ae69L, 0x616bffd3L, 0x166ccf45L, 0xa00ae278L, 0xd70dd2eeL, 0x4e048354L, 0x3903b3c2L, 0xa7672661L, 0xd06016f7L, 0x4969474dL, 0x3e6e77dbL, 0xaed16a4aL, 0xd9d65adcL, 0x40df0b66L, 0x37d83bf0L, 0xa9bcae53L, 0xdebb9ec5L, 0x47b2cf7fL, 0x30b5ffe9L, 0xbdbdf21cL, 0xcabac28aL, 0x53b39330L, 0x24b4a3a6L, 0xbad03605L, 0xcdd70693L, 0x54de5729L, 0x23d967bfL, 0xb3667a2eL, 0xc4614ab8L, 0x5d681b02L, 0x2a6f2b94L, 0xb40bbe37L, 0xc30c8ea1L, 0x5a05df1bL, 0x2d02ef8dL }; uint32_t CRC32Get(const void* vbuf, unsigned int size) { const unsigned char* buf = (const unsigned char*)vbuf; unsigned int i, crc; crc = 0xFFFFFFFF; for (i = 0; i < size; i++) crc = crc32tab[(crc ^ buf[i]) & 0xff] ^ (crc >> 8); return crc ^ 0xFFFFFFFF; } } #endif
90.704762
343
0.789164
Hotege
0818cff8fe62ef46802eb2f857c29fa5927985c2
320
cpp
C++
list10_2/main.cpp
rimever/SuraSuraCPlus
acbc6e1d0d0bb9bf07e28ab02c30ac021b1f6899
[ "MIT" ]
null
null
null
list10_2/main.cpp
rimever/SuraSuraCPlus
acbc6e1d0d0bb9bf07e28ab02c30ac021b1f6899
[ "MIT" ]
null
null
null
list10_2/main.cpp
rimever/SuraSuraCPlus
acbc6e1d0d0bb9bf07e28ab02c30ac021b1f6899
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; template<class T> T getMin(T a, T b) { return a < b ? a : b; } int main() { int a, b, c; a = 123; b = 456; c = getMin(a, b); cout << c << endl; double x, y, z; x = 1.23; y = 4.56; z = getMin(x, y); cout << z << endl; return 0; }
14.545455
25
0.4625
rimever
081d4fe97337f2c5b388ad6eff4f849d47929eb0
969
cpp
C++
tests/insert_id.cpp
Wassasin/librusql
207919e5da1e9e49d4c575c81699fcb1d8cd6204
[ "BSD-3-Clause" ]
2
2018-01-16T18:05:21.000Z
2021-02-02T05:04:51.000Z
tests/insert_id.cpp
Wassasin/librusql
207919e5da1e9e49d4c575c81699fcb1d8cd6204
[ "BSD-3-Clause" ]
null
null
null
tests/insert_id.cpp
Wassasin/librusql
207919e5da1e9e49d4c575c81699fcb1d8cd6204
[ "BSD-3-Clause" ]
null
null
null
#include <rusql/rusql.hpp> #include "test.hpp" #include "database_test.hpp" #include <cstdlib> int main(int argc, char *argv[]) { auto db = get_database(argc, argv); test_init(4); test_start_try(4); try { db->execute("CREATE TABLE rusqltest (`id` INTEGER(10) PRIMARY KEY AUTO_INCREMENT, `value` INT(2) NOT NULL)"); auto statement = db->prepare("INSERT INTO rusqltest (`value`) VALUES (67)"); statement.execute(); uint64_t insert_id = statement.insert_id(); auto st2 = db->prepare("SELECT id FROM rusqltest WHERE value=67"); st2.execute(); uint64_t real_insert_id = 0xdeadbeef; st2.bind_results(real_insert_id); test(st2.fetch(), "one result"); test(real_insert_id != 0xdeadbeef, "real_insert_id was changed"); test(real_insert_id == insert_id, "last_insert_id() returned correctly"); test(!st2.fetch(), "one result only"); } catch(std::exception &e) { diag(e); } test_finish_try(); db->execute("DROP TABLE rusqltest"); return 0; }
30.28125
111
0.701754
Wassasin
0823f63cb7a139e1a779ed1bbc1630279460107f
776
cpp
C++
plugins/opengl/src/clear/depth_buffer.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
plugins/opengl/src/clear/depth_buffer.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
plugins/opengl/src/clear/depth_buffer.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <sge/opengl/call.hpp> #include <sge/opengl/check_state.hpp> #include <sge/opengl/common.hpp> #include <sge/opengl/clear/depth_buffer.hpp> #include <sge/renderer/exception.hpp> #include <sge/renderer/clear/depth_buffer_value.hpp> #include <fcppt/text.hpp> #include <fcppt/cast/size.hpp> void sge::opengl::clear::depth_buffer(sge::renderer::clear::depth_buffer_value const &_value) { sge::opengl::call(::glClearDepth, fcppt::cast::size<GLdouble>(_value)); SGE_OPENGL_CHECK_STATE(FCPPT_TEXT("glClearDepth failed"), sge::renderer::exception) }
36.952381
93
0.742268
cpreh
08247b67a6036ea9f500344de36b0117965d8d98
989
cpp
C++
src/components/oscilloscope.cpp
jan-van-bergen/Synth
cc6fee6376974a3cc2e86899ab2859a5f1fb7e33
[ "MIT" ]
17
2021-03-22T14:17:16.000Z
2022-02-22T20:58:27.000Z
src/components/oscilloscope.cpp
jan-van-bergen/Synth
cc6fee6376974a3cc2e86899ab2859a5f1fb7e33
[ "MIT" ]
null
null
null
src/components/oscilloscope.cpp
jan-van-bergen/Synth
cc6fee6376974a3cc2e86899ab2859a5f1fb7e33
[ "MIT" ]
1
2021-11-17T18:00:55.000Z
2021-11-17T18:00:55.000Z
#include "oscilloscope.h" #include <ImGui/implot.h> void OscilloscopeComponent::update(Synth const & synth) { memset(samples, 0, sizeof(samples)); for (auto const & [other, weight] : inputs[0].others) { for (int i = 0; i < BLOCK_SIZE; i++) { samples[i] += weight * other->get_sample(i).left; } } } void OscilloscopeComponent::render(Synth const & synth) { auto avail = ImGui::GetContentRegionAvail(); auto space = ImVec2(avail.x, std::max( ImGui::GetTextLineHeightWithSpacing(), avail.y - (inputs.size() + outputs.size()) * ImGui::GetTextLineHeightWithSpacing() )); ImPlot::SetNextPlotLimits(0.0, BLOCK_SIZE, -1.0, 1.0, ImGuiCond_Always); if (ImPlot::BeginPlot("Osciloscope", nullptr, nullptr, space, ImPlotFlags_CanvasOnly, ImPlotAxisFlags_NoDecorations)) { ImPlot::PushStyleVar(ImPlotStyleVar_FillAlpha, 0.25f); ImPlot::PlotShaded("", samples, BLOCK_SIZE); ImPlot::PlotLine ("", samples, BLOCK_SIZE); ImPlot::PopStyleVar(); ImPlot::EndPlot(); } }
29.088235
120
0.703741
jan-van-bergen
0825fce6f420b678bc45bde2f99f310fb9efe8d2
2,344
cpp
C++
test/test-v3.cpp
TheodoreDavis/simple-ray-tracer
db0ebbea4f70efb70c67729c0b737de458bce8bd
[ "Apache-2.0" ]
null
null
null
test/test-v3.cpp
TheodoreDavis/simple-ray-tracer
db0ebbea4f70efb70c67729c0b737de458bce8bd
[ "Apache-2.0" ]
1
2021-09-17T02:24:36.000Z
2021-09-17T02:24:36.000Z
test/test-v3.cpp
TheodoreDavis/simple-ray-tracer
db0ebbea4f70efb70c67729c0b737de458bce8bd
[ "Apache-2.0" ]
null
null
null
#include <inc/v3.h> using namespace std; int main() { v3 a = v3(1,2,3); // Test Accessers cout << "Testing Accessors" << endl; cout << a[0] << a[1] << a[2]; cout << " -- Should be 123" << endl; a[0] = 5, a[1] = 5, a[2] = 5; cout << a[0] << a[1] << a[2]; cout << " -- Should be 555" << endl << endl; a[0] = 1, a[1] = 2, a[2] = 3; // Test ostream cout << "Testing ostream" << endl; cout << a; cout << " -- Should be {1,2,3}" << endl << endl; // Test unary operators cout << "Testing Unary Operators" << endl; cout << +a; cout << " -- Should be {1,2,3}" << endl; cout << -a; cout << " -- Should be {-1,-2,-3}" << endl << endl; // Test assignments cout << "Testing Assignments" << endl; a += v3(1,1,1); cout << a; cout << " -- Should be {2,3,4}" << endl; a -= v3(1,2,1); cout << a; cout << " -- Should be {1,1,3}" << endl; a *= v3(1,2,4); cout << a; cout << " -- Should be {1,2,12}" << endl; a /= v3(1,1,4); cout << a; cout << " -- Should be {1,2,3}" << endl; a *= 5; cout << a; cout << " -- Should be {5,10,15}" << endl; a /= 5; cout << a; cout << " -- Should be {1,2,3}" << endl << endl; // Operations cout << "Testing Operations" << endl; cout << a + v3(1,1,1); cout << " -- Should be {2,3,4}" << endl; cout << a - v3(1,2,1); cout << " -- Should be {0,0,2}" << endl; cout << a * v3(1,2,4); cout << " -- Should be {1,4,12}" << endl; cout << a / v3(1,1,4); cout << " -- Should be {1,2,0.75}" << endl; cout << a * 5; cout << " -- Should be {5,10,15}" << endl; cout << a / 5; cout << " -- Should be {0.2,0.4,0.6}" << endl << endl; // Vector Operations cout << "Testing Vector Operations" << endl; v3 b = v3(7,8,9); cout << a.crossProduct(b); cout << " -- Should be {-6,12,-6}" << endl; cout << a.dotProduct(b); cout << " -- Should be 50" << endl; cout << a.magnitude(); cout << " -- Should be 3.7417" << endl; cout << a.magnitudeSquared(); cout << " -- Should be 14" << endl; cout << a.unitVector(); cout << " -- Should be {0.27,0.53,0.80}" << endl << endl; }
24.416667
63
0.426621
TheodoreDavis
082873125198dab2730ad219bcdb9f7f2d9a36c9
2,675
cpp
C++
examples/linux/socket/wind2rrd.cpp
rkuris/n2klib
e465a8f591d135d2e632186309d69a28ff7c9c4e
[ "MIT" ]
null
null
null
examples/linux/socket/wind2rrd.cpp
rkuris/n2klib
e465a8f591d135d2e632186309d69a28ff7c9c4e
[ "MIT" ]
null
null
null
examples/linux/socket/wind2rrd.cpp
rkuris/n2klib
e465a8f591d135d2e632186309d69a28ff7c9c4e
[ "MIT" ]
null
null
null
#include "n2k.h" #include "n2ksocket.h" #include "generated/windData.cc" #include "generated/waterDepth.cc" #include "generated/vesselHeading.cc" #include "pipe.h" #include <stdio.h> #include <signal.h> #include <bits/stdc++.h> void handleWind(const n2k::Message & m); void handleDepth(const n2k::Message & m); void handleHeading(const n2k::Message & m); std::ostream* out = &std::cout; int main(int argc, char *argv[]) { // if you pass any argument, you skip writing to rrdtool if (argc <= 1) { out = new opipestream("rrdtool - >/dev/null"); } signal(SIGINT, exit); n2k::SocketCanReceiver r("can0"); int callbackCount = 0; if (access("wind.rrd", W_OK) || argc > 1) { n2k::Callback cb( n2k::WindData::PGN, n2k::WindData::Type, handleWind); r.addCallback(cb); callbackCount++; } if (access("depth.rrd", W_OK) || argc > 1) { n2k::Callback cb2( n2k::WaterDepth::PGN, n2k::WaterDepth::Type, handleDepth); r.addCallback(cb2); callbackCount++; } if (access("heading.rrd", W_OK) || argc > 1) { n2k::Callback cb3( n2k::VesselHeading::PGN, n2k::VesselHeading::Type, handleHeading); r.addCallback(cb3); callbackCount++; } if (callbackCount == 0) { std::cerr << "No writeable rrd files!\n"; exit(1); } r.applyKernelFilter(); r.run(); } void handleWind(const n2k::Message & m) { static n2k::WindData last; static int repeatCount; const int kRepeatLimit = 10; const n2k::WindData &w = static_cast<const n2k::WindData&>(m); if ((repeatCount++ < kRepeatLimit) && (w.getWindSpeedKnots() == last.getWindSpeedKnots()) && (w.getWindAngleDegrees() == last.getWindAngleDegrees())) { return; } last = w; repeatCount = 0; *out << "update wind.rrd N:" << std::setprecision(2) << w.getWindSpeedKnots() << ":" << w.getWindAngleDegrees() << "\n"; } void handleDepth(const n2k::Message & m) { const n2k::WaterDepth &d = static_cast<const n2k::WindData&>(m); *out << "update depth.rrd N:" << std::setprecision(2) << d.getDepthFeet() << "\n"; } void handleHeading(const n2k::Message & m) { static double last; static int repeatCount; const int kRepeatLimit = 10; const n2k::VesselHeading &h = static_cast<const n2k::WindData&>(m); auto diff = last - h.getHeadingDegrees(); if ((repeatCount++ < kRepeatLimit) && (diff < .1 && diff > -.1)) { return; } last = h.getHeadingDegrees(); repeatCount = 0; *out << "update heading.rrd N:" << std::setprecision(2) << h.getHeadingDegrees() << "\n"; }
26.22549
72
0.603738
rkuris
082f53921e10192d7abfdb1ca2b8d18d9607fb94
1,142
cpp
C++
src/RSA.cpp
W-angler/crypto
155f0872fa325897bc55a06dfeba4e61014ee350
[ "MIT" ]
null
null
null
src/RSA.cpp
W-angler/crypto
155f0872fa325897bc55a06dfeba4e61014ee350
[ "MIT" ]
null
null
null
src/RSA.cpp
W-angler/crypto
155f0872fa325897bc55a06dfeba4e61014ee350
[ "MIT" ]
null
null
null
#include "RSA.h" #include "prime.h" const bigint RSA::DEFAULT_E(65537); /** * RSA密钥生成 * * @param bits 密钥长度 * @return 密钥对 */ RSA::KeyPair RSA::generate(size_t bits) { size_t len = (bits + 1) / 2; bigint N; bigint p; bigint q; while (true) { p = prime::generate(len); q = prime::generate(len); N = p * q; if (N.bitLength() == bits) { break; } } auto pSubtractOne = p - bigint::ONE; auto qSubtractOne = q - bigint::ONE; bigint d = DEFAULT_E.modInverse(pSubtractOne * qSubtractOne); PublicKey publicKey(N, DEFAULT_E); // e·dP = 1 (mod (p–1)) // e·dQ = 1 (mod (q–1)) // q·qInv = 1 (mod p) PrivateKey privateKey(N, p, q, d, DEFAULT_E.modInverse(pSubtractOne), DEFAULT_E.modInverse(qSubtractOne), q.modInverse(p)); return KeyPair(privateKey, publicKey); } bigint RSA::encrypt(const bigint &m, const RSA::PublicKey &publicKey) { return m.modPow(publicKey.e, publicKey.n); } bigint RSA::decrypt(const bigint &c, const RSA::PrivateKey &privateKey) { return c.modPow(privateKey.d, privateKey.n); }
25.954545
115
0.596322
W-angler
0830d1f9bf68f1605da7ca3d31d7ae526d01e8e6
856
cpp
C++
codes/cpp/mains/test_gardp.cpp
henriquebecker91/masters
1783c05b6f916cc4eb883df26fd4eb3460f98816
[ "Unlicense" ]
1
2020-05-18T23:01:41.000Z
2020-05-18T23:01:41.000Z
codes/cpp/mains/test_gardp.cpp
henriquebecker91/masters
1783c05b6f916cc4eb883df26fd4eb3460f98816
[ "Unlicense" ]
null
null
null
codes/cpp/mains/test_gardp.cpp
henriquebecker91/masters
1783c05b6f916cc4eb883df26fd4eb3460f98816
[ "Unlicense" ]
2
2017-08-13T15:24:56.000Z
2020-03-06T00:20:48.000Z
#include "gardp.hpp" #include "test_common.hpp" // Execute the dynamic programming algorithm presented at p. 221, Integer // Programming, Robert S. Garfinkel, over a hardcoded set of instances. Used to // check if it is still working after a change. All the instances have only // integers, but we execute the gardp version where the profit values are // stored as doubles to test it. int main(int argc, char** argv) { int exit_code; std::cout << "hbm::benchmark_pyasukp<size_t, size_t, size_t>(&hbm::gardp, argc, argv)" << std::endl; exit_code = hbm::benchmark_pyasukp<size_t, size_t, size_t>(&hbm::gardp, argc, argv); if (exit_code != EXIT_SUCCESS) return exit_code; std::cout << "hbm::benchmark_pyasukp<size_t, double, size_t>(&hbm::gardp)" << std::endl; return hbm::benchmark_pyasukp<size_t, double, size_t>(&hbm::gardp, argc, argv); }
42.8
102
0.721963
henriquebecker91
08333bcdef125c0cb9ae7a23914aa69d1f9af39c
1,482
cpp
C++
Code/Resource.cpp
JaumeMontagut/CITM_3_GameEngine
57a85b89a72723ce555a4eec3830e6bf00499de9
[ "MIT" ]
1
2020-07-09T00:38:40.000Z
2020-07-09T00:38:40.000Z
Code/Resource.cpp
YessicaSD/CITM_3_GameEngine
57a85b89a72723ce555a4eec3830e6bf00499de9
[ "MIT" ]
null
null
null
Code/Resource.cpp
YessicaSD/CITM_3_GameEngine
57a85b89a72723ce555a4eec3830e6bf00499de9
[ "MIT" ]
null
null
null
#include "Resource.h" #include "ModuleFileSystem.h" #include "JSONFile.h" #include <stdio.h> const uint Resource::type = std::hash<std::string>()(TO_STRING(Resource)); UID Resource::GetUID() const { return uid; } void Resource::SaveVariable(void * info, char ** data_cursor, size_t bytes) { memcpy(*data_cursor, info, bytes); *data_cursor += bytes; } void Resource::LoadVariable(void* info, char ** data_cursor, size_t bytes) { memcpy(info, *data_cursor, bytes); *data_cursor += bytes; } //INFO: Keeps the resource but deletes all its data bool Resource::ReleaseData() { bool ret = false; return ret; } Resource::Resource() { } //INFO: Called each time a GameObject needs to use this resource //INFO: Only load resource once bool Resource::StartUsingResource() { if (reference_count > 0u) { ++reference_count; } else { if (LoadFileData()) { ++reference_count; } } return reference_count > 0u; } uint Resource::GetReferenceCount() const { return reference_count; } //INFO: Called each time a GameObject stops using this resource //INFO: Unload resource when no GameObject references it bool Resource::StopUsingResource() { bool ret = true; --reference_count; if (reference_count == 0u) { ret = ReleaseData(); } return ret; } void Resource::SaveModifiedDate(JSONFile * meta_file, const char * asset_path) { struct stat file_stat; if (stat(asset_path, &file_stat) == 0) { meta_file->SaveNumber("dateModified", file_stat.st_atime); } }
18.525
78
0.711876
JaumeMontagut
0835c0274bfc544a1f0bcb3953c322fc1bba3b9d
2,362
cpp
C++
Real-Time Corruptor/BizHawk_RTC/waterbox/libsnes/bsnes/snes/chip/icd2/mmio/mmio.cpp
redscientistlabs/Bizhawk50X-Vanguard
96e0f5f87671a1230784c8faf935fe70baadfe48
[ "MIT" ]
1,414
2015-06-28T09:57:51.000Z
2021-10-14T03:51:10.000Z
Real-Time Corruptor/BizHawk_RTC/waterbox/libsnes/bsnes/snes/chip/icd2/mmio/mmio.cpp
redscientistlabs/Bizhawk50X-Vanguard
96e0f5f87671a1230784c8faf935fe70baadfe48
[ "MIT" ]
2,369
2015-06-25T01:45:44.000Z
2021-10-16T08:44:18.000Z
Real-Time Corruptor/BizHawk_RTC/waterbox/libsnes/bsnes/snes/chip/icd2/mmio/mmio.cpp
redscientistlabs/Bizhawk50X-Vanguard
96e0f5f87671a1230784c8faf935fe70baadfe48
[ "MIT" ]
430
2015-06-29T04:28:58.000Z
2021-10-05T18:24:17.000Z
#ifdef ICD2_CPP //convert linear pixel data { 0x00, 0x55, 0xaa, 0xff } to 2bpp planar tiledata void ICD2::render(const uint16 *source) { memset(lcd.output, 0x00, 320 * sizeof(uint16)); for(unsigned y = 0; y < 8; y++) { for(unsigned x = 0; x < 160; x++) { unsigned pixel = *source++; unsigned addr = y * 2 + (x / 8 * 16); lcd.output[addr + 0] |= ((pixel & 1) >> 0) << (7 - (x & 7)); lcd.output[addr + 1] |= ((pixel & 2) >> 1) << (7 - (x & 7)); } } } uint8 ICD2::read(unsigned addr) { addr &= 0xffff; //LY counter if(addr == 0x6000) { r6000_ly = GameBoy::lcd.status.ly; r6000_row = lcd.row; return r6000_ly; } //command ready port if(addr == 0x6002) { bool data = packetsize > 0; if(data) { for(unsigned i = 0; i < 16; i++) r7000[i] = packet[0][i]; packetsize--; for(unsigned i = 0; i < packetsize; i++) packet[i] = packet[i + 1]; } return data; } //ICD2 revision if(addr == 0x600f) { return 0x21; } //command port if((addr & 0xfff0) == 0x7000) { return r7000[addr & 15]; } //VRAM port if(addr == 0x7800) { uint8 data = lcd.output[r7800]; r7800 = (r7800 + 1) % 320; return data; } return 0x00; } void ICD2::write(unsigned addr, uint8 data) { addr &= 0xffff; //VRAM port if(addr == 0x6001) { r6001 = data; r7800 = 0; unsigned offset = (r6000_row - (4 - (r6001 - (r6000_ly & 3)))) & 3; render(lcd.buffer + offset * 160 * 8); return; } //control port //d7: 0 = halt, 1 = reset //d5,d4: 0 = 1-player, 1 = 2-player, 2 = 4-player, 3 = ??? //d1,d0: 0 = frequency divider (clock rate adjust) if(addr == 0x6003) { if((r6003 & 0x80) == 0x00 && (data & 0x80) == 0x80) { reset(); } switch(data & 3) { case 0: frequency = cpu.frequency / 4; break; //fast (glitchy, even on real hardware) case 1: frequency = cpu.frequency / 5; break; //normal case 2: frequency = cpu.frequency / 7; break; //slow case 3: frequency = cpu.frequency / 9; break; //very slow } r6003 = data; return; } if(addr == 0x6004) { r6004 = data; return; } //joypad 1 if(addr == 0x6005) { r6005 = data; return; } //joypad 2 if(addr == 0x6006) { r6006 = data; return; } //joypad 3 if(addr == 0x6007) { r6007 = data; return; } //joypad 4 } #endif
24.350515
92
0.546571
redscientistlabs
083f05a3f9243aa0df1528f44d7ca3d4e6d82808
1,281
cpp
C++
src/guiCamera.cpp
moxor/remoteX-1
49e8cf3f4025425edcf6e4e4e8f7505b83570652
[ "MIT" ]
2
2015-09-23T23:35:33.000Z
2015-11-04T21:50:45.000Z
src/guiCamera.cpp
nanu-c/remoteX-1
49e8cf3f4025425edcf6e4e4e8f7505b83570652
[ "MIT" ]
null
null
null
src/guiCamera.cpp
nanu-c/remoteX-1
49e8cf3f4025425edcf6e4e4e8f7505b83570652
[ "MIT" ]
1
2015-09-05T15:07:04.000Z
2015-09-05T15:07:04.000Z
#include "guiCamera.h" void GuiCamera::setup(){ cameraParameters.add(gCtoggleOnOff.set("Camera On/Off",false)); //cameraParameters.add(gCtoggleShowImage.set("Camera show image",false)); //cameraParameters.add(gCtoggleGrayscale.set("Camera grayscale",false)); //cameraParameters.add(gCtoggleMask.set("Camera mask",false)); //cameraParameters.add(gCtoggleDetect.set("Camera detect",false)); cameraParameters.add(gC2SliderScale.set("Scale Camera ",ofVec2f(1,1), ofVec2f(0.1, 0.1), ofVec2f(10,10))); cameraParameters.add(gCtoggFit.set("Fit Camera to quad",false)); cameraParameters.add(gCtoggKeepAspect.set("Keep Camera aspect ratio",false)); cameraParameters.add(gCtoggHflip.set("Camera horizontal flip",false)); cameraParameters.add(gCtoggVflip.set("Camera vertical flip",false)); cameraParameters.add(gCcolor.set("Camera color",ofFloatColor(1,1,1), ofFloatColor(0, 0), ofFloatColor(1,1))); cameraParameters.add(gCtoggGreenscreen.set("Camera Greenscreen",false)); cameraParameters.add(gCfsliderVolume.set("Camera Volume",0.0, 0.0, 1.0)); cameraParametersSecond.add(gCtoggleSampler.set("Camera sampler playback",false)); } void GuiCamera::draw(){ //ofSetColor(red, green, blue); //ofCircle(posX, posY, radius); }
44.172414
113
0.735363
moxor
0840f62ec3147029925c2304cbb066c160be164f
949
cpp
C++
android-31/android/renderscript/Script_FieldBase.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-31/android/renderscript/Script_FieldBase.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-29/android/renderscript/Script_FieldBase.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#include "./Allocation.hpp" #include "./Element.hpp" #include "./RenderScript.hpp" #include "./Type.hpp" #include "./Script_FieldBase.hpp" namespace android::renderscript { // Fields // QJniObject forward Script_FieldBase::Script_FieldBase(QJniObject obj) : JObject(obj) {} // Constructors // Methods android::renderscript::Allocation Script_FieldBase::getAllocation() const { return callObjectMethod( "getAllocation", "()Landroid/renderscript/Allocation;" ); } android::renderscript::Element Script_FieldBase::getElement() const { return callObjectMethod( "getElement", "()Landroid/renderscript/Element;" ); } android::renderscript::Type Script_FieldBase::getType() const { return callObjectMethod( "getType", "()Landroid/renderscript/Type;" ); } void Script_FieldBase::updateAllocation() const { callMethod<void>( "updateAllocation", "()V" ); } } // namespace android::renderscript
20.191489
74
0.708114
YJBeetle
08418e8cfd403298cc6b5247455469aa83411b8c
586
hpp
C++
detail/dynamic_loading.hpp
isadchenko/brig
3e65a44fa4b8690cdfa8bdaca08d560591afcc38
[ "MIT" ]
null
null
null
detail/dynamic_loading.hpp
isadchenko/brig
3e65a44fa4b8690cdfa8bdaca08d560591afcc38
[ "MIT" ]
null
null
null
detail/dynamic_loading.hpp
isadchenko/brig
3e65a44fa4b8690cdfa8bdaca08d560591afcc38
[ "MIT" ]
null
null
null
// Andrew Naplavkov #ifndef BRIG_DETAIL_DYNAMIC_LOADING_HPP #define BRIG_DETAIL_DYNAMIC_LOADING_HPP #include <brig/detail/stringify.hpp> #ifdef _WIN32 #include <windows.h> #define BRIG_DL_LIBRARY(win, lin) LoadLibraryA(win) #define BRIG_DL_FUNCTION(lib, fun) (decltype(fun)*)GetProcAddress(lib, BRIG_STRINGIFY(fun)) #elif defined __linux__ #include <dlfcn.h> #define BRIG_DL_LIBRARY(win, lin) dlopen(lin, RTLD_LAZY) #define BRIG_DL_FUNCTION(lib, fun) (decltype(fun)*)dlsym(lib, BRIG_STRINGIFY(fun)) #endif #endif // BRIG_DETAIL_DYNAMIC_LOADING_HPP
27.904762
94
0.754266
isadchenko
36b02faad043d5086efea43c41e3631cc5b93616
1,005
cpp
C++
MTD/Player.cpp
Hapaxia/MyPracticeBeginnerGames
2289c05677c9630a78fa9188c9c81c33846e2860
[ "MIT" ]
7
2015-08-28T06:57:14.000Z
2019-07-24T18:18:21.000Z
MTD/Player.cpp
Hapaxia/MyPracticeBeginnerGames
2289c05677c9630a78fa9188c9c81c33846e2860
[ "MIT" ]
1
2016-02-12T17:07:32.000Z
2016-02-19T19:22:09.000Z
MTD/Player.cpp
Hapaxia/MyPracticeBeginnerGames
2289c05677c9630a78fa9188c9c81c33846e2860
[ "MIT" ]
1
2019-10-13T03:54:41.000Z
2019-10-13T03:54:41.000Z
#include "Player.hpp" #include <Plinth/Sfml/Generic.hpp> namespace { const pl::Vector2d playerSize{ 64.0, 32.0 }; constexpr double initialSpeed{ 300.0 }; const double minimumPosition{ 0.0 + playerSize.x / 2.0 }; } Player::Player(const sf::RenderWindow& window, const double dt, const Graphics& graphics) : m_dt(dt) , m_speed(initialSpeed) , m_size(playerSize) , m_positionLimits({ minimumPosition, window.getSize().x - playerSize.x / 2.0 }) , m_position(m_positionLimits.min) { } void Player::move(const Direction direction) { double movement; switch (direction) { case Direction::Left: movement = -1.0; break; case Direction::Right: movement = 1.0; break; default: movement = 0.0; } m_position += movement * m_speed * m_dt; m_position = m_positionLimits.clamp(m_position); } void Player::reset() { m_position = minimumPosition; m_speed = initialSpeed; } double Player::getPosition() const { return m_position; } pl::Vector2d Player::getSize() const { return m_size; }
18.272727
89
0.711443
Hapaxia
36b7c352f9c44a8b4fb1fd8d260eddc313d4a4e7
22,899
cpp
C++
perception/object_segmentation/src/object_segmentation.cpp
probabilistic-anchoring/probanch
cfba24fd431ed7e7109b715018e344d7989f565d
[ "Apache-2.0" ]
1
2020-02-27T14:00:27.000Z
2020-02-27T14:00:27.000Z
perception/object_segmentation/src/object_segmentation.cpp
probabilistic-anchoring/probanch
cfba24fd431ed7e7109b715018e344d7989f565d
[ "Apache-2.0" ]
null
null
null
perception/object_segmentation/src/object_segmentation.cpp
probabilistic-anchoring/probanch
cfba24fd431ed7e7109b715018e344d7989f565d
[ "Apache-2.0" ]
null
null
null
#include <opencv2/highgui/highgui.hpp> #include <algorithm> #include <ros/ros.h> #include <pcl_conversions/pcl_conversions.h> #include <pcl_ros/transforms.h> #include <pcl/io/pcd_io.h> #include <opencv2/opencv.hpp> #include <cv_bridge/cv_bridge.h> #include <image_geometry/pinhole_camera_model.h> #include <sensor_msgs/image_encodings.h> #include <geometry_msgs/TransformStamped.h> #include <tf2/convert.h> #include <tf2/transform_datatypes.h> #include <tf2_geometry_msgs/tf2_geometry_msgs.h> #include <tf2_eigen/tf2_eigen.h> #include <std_msgs/String.h> #include <anchor_msgs/ObjectArray.h> #include <anchor_msgs/ClusterArray.h> #include <anchor_msgs/MovementArray.h> #include <hand_tracking/TrackingService.h> #include <object_segmentation/object_segmentation.hpp> #include <pcl_ros/point_cloud.h> // ------------------------ // Public functions // ------------------------- ObjectSegmentation::ObjectSegmentation(ros::NodeHandle nh, bool useApprox) : nh_(nh) , it_(nh) , priv_nh_("~") , tf2_listener_(buffer_) , useApprox_(useApprox) , queueSize_(5) , display_image_(false) { // Subscribers / publishers //image_transport::TransportHints hints(useCompressed ? "compressed" : "raw"); //image_sub_ = new image_transport::SubscriberFilter( it_, topicColor, "image", hints); image_sub_ = new image_transport::SubscriberFilter( it_, "image", queueSize_); camera_info_sub_ = new message_filters::Subscriber<sensor_msgs::CameraInfo>( nh_, "camera_info", queueSize_); cloud_sub_ = new message_filters::Subscriber<sensor_msgs::PointCloud2>( nh_, "cloud", queueSize_); obj_pub_ = nh_.advertise<anchor_msgs::ObjectArray>("/objects/raw", queueSize_); cluster_pub_ = nh_.advertise<anchor_msgs::ClusterArray>("/objects/clusters", queueSize_); move_pub_ = nh_.advertise<anchor_msgs::MovementArray>("/movements", queueSize_); // Hand tracking _tracking_client = nh_.serviceClient<hand_tracking::TrackingService>("/hand_tracking"); // Used for the web interface display_trigger_sub_ = nh_.subscribe("/display/trigger", 1, &ObjectSegmentation::triggerCb, this); display_image_pub_ = it_.advertise("/display/image", 1); // Set up sync policies if(useApprox) { syncApproximate_ = new message_filters::Synchronizer<ApproximateSyncPolicy>(ApproximateSyncPolicy(queueSize_), *image_sub_, *camera_info_sub_, *cloud_sub_); syncApproximate_->registerCallback( boost::bind( &ObjectSegmentation::segmentationCb, this, _1, _2, _3)); } else { syncExact_ = new message_filters::Synchronizer<ExactSyncPolicy>(ExactSyncPolicy(queueSize_), *image_sub_, *camera_info_sub_, *cloud_sub_); syncExact_->registerCallback( boost::bind( &ObjectSegmentation::segmentationCb, this, _1, _2, _3)); } // Read the base frame priv_nh_.param( "base_frame", base_frame_, std::string("base_link")); // Read segmentation parameters int type, size; double th, factor; if( priv_nh_.getParam("compare_type", type) ) { if( type >= 0 && type <= 3 ) { this->seg_.setComparatorType(type); } else { ROS_WARN("[ObjectSegmentation::ObjectSegmentation] Not a valid comparator type, using default instead."); } } if( priv_nh_.getParam("plane_min_size", size) ) { this->seg_.setPlaneMinSize (size); } if( priv_nh_.getParam("cluster_min_size", size) ) { this->seg_.setClusterMinSize (size); } if( priv_nh_.getParam("cluster_min_size", size) ) { this->seg_.setClusterMinSize (size); } if( priv_nh_.getParam("angular_th", th) ) { this->seg_.setAngularTh (th); } if( priv_nh_.getParam("distance_th", th) ) { this->seg_.setDistanceTh (th); } if( priv_nh_.getParam("refine_factor", factor) ) { this->seg_.setRefineFactor (factor); } // Read spatial thresholds (default values = no filtering) this->priv_nh_.param<double>( "min_x", this->min_x_, 0.0); this->priv_nh_.param<double>( "max_x", this->max_x_, -1.0); this->priv_nh_.param<double>( "min_y", this->min_y_, 0.0); this->priv_nh_.param<double>( "max_y", this->max_y_, -1.0); this->priv_nh_.param<double>( "min_z", this->min_z_, 0.0); this->priv_nh_.param<double>( "max_z", this->max_z_, -1.0); // Read toggle paramter for displayig the result (OpenCV window view) this->priv_nh_.param<bool>( "display_window", display_window_, false); } ObjectSegmentation::~ObjectSegmentation() { if(useApprox_) { delete syncApproximate_; } else { delete syncExact_; } delete image_sub_; delete camera_info_sub_; delete cloud_sub_; //delete tf_listener_; } void ObjectSegmentation::spin() { ros::Rate rate(100); while(ros::ok()) { // OpenCV window for display if( this->display_window_ ) { if( !this->result_img_.empty() ) { cv::imshow( "Segmented clusters...", this->result_img_ ); } // Wait for a keystroke in the window char key = cv::waitKey(1); if( key == 27 || key == 'Q' || key == 'q' ) { break; } } ros::spinOnce(); rate.sleep(); } } void ObjectSegmentation::triggerCb( const std_msgs::String::ConstPtr &msg) { this->display_image_ = (msg->data == "segmentation") ? true : false; ROS_WARN("Got trigger: %s", msg->data.c_str()); } // -------------------------- // Callback function (ROS) // -------------------------- void ObjectSegmentation::segmentationCb( const sensor_msgs::Image::ConstPtr image_msg, const sensor_msgs::CameraInfo::ConstPtr camera_info_msg, const sensor_msgs::PointCloud2::ConstPtr cloud_msg) { // Get the transformation (as geoemtry message) geometry_msgs::TransformStamped tf_forward, tf_inverse; try{ tf_forward = this->buffer_.lookupTransform( base_frame_, cloud_msg->header.frame_id, cloud_msg->header.stamp); tf_inverse = this->buffer_.lookupTransform( cloud_msg->header.frame_id, base_frame_, cloud_msg->header.stamp); } catch (tf2::TransformException &ex) { ROS_WARN("[ObjectSegmentation::callback] %s" , ex.what()); return; } // Get the transformation (as tf/tf2) //tf2::Stamped<tf2::Transform> transform2; //tf2::fromMsg(tf_forward, transform2); //tf::Vector3d tf::Transform transform = tf::Transform(transform2.getOrigin(), transform2.getRotation()); //tf::Transform transfrom = tf::Transform(tf_forward.transfrom); // Read the cloud pcl::PointCloud<segmentation::Point>::Ptr raw_cloud_ptr (new pcl::PointCloud<segmentation::Point>); pcl::fromROSMsg (*cloud_msg, *raw_cloud_ptr); // Transform the cloud to the world frame pcl::PointCloud<segmentation::Point>::Ptr transformed_cloud_ptr (new pcl::PointCloud<segmentation::Point>); //pcl_ros::transformPointCloud( *raw_cloud_ptr, *transformed_cloud_ptr, transform); pcl_ros::transformPointCloud(tf2::transformToEigen(tf_forward.transform).matrix(), *raw_cloud_ptr, *transformed_cloud_ptr); // Filter the transformed point cloud this->filter (transformed_cloud_ptr); // ---------------------- pcl::PointCloud<segmentation::Point>::Ptr original_cloud_ptr (new pcl::PointCloud<segmentation::Point>); //pcl_ros::transformPointCloud( *transformed_cloud_ptr, *original_cloud_ptr, transform.inverse()); pcl_ros::transformPointCloud(tf2::transformToEigen(tf_inverse.transform).matrix(), *raw_cloud_ptr, *transformed_cloud_ptr); // Read the RGB image cv::Mat img; cv_bridge::CvImagePtr cv_ptr; try { cv_ptr = cv_bridge::toCvCopy( image_msg, image_msg->encoding); cv_ptr->image.copyTo(img); } catch (cv_bridge::Exception& ex){ ROS_ERROR("[ObjectSegmentation::callback]: Failed to convert image."); return; } // Saftey check if( img.empty() ) { return; } // TEST // -------------------------------------- // Downsample the orignal point cloud int scale = 2; pcl::PointCloud<segmentation::Point>::Ptr downsampled_cloud_ptr( new pcl::PointCloud<segmentation::Point> ); downsampled_cloud_ptr->width = original_cloud_ptr->width / scale; downsampled_cloud_ptr->height = original_cloud_ptr->height / scale; downsampled_cloud_ptr->resize( downsampled_cloud_ptr->width * downsampled_cloud_ptr->height ); for( uint i = 0, k = 0; i < original_cloud_ptr->width; i += scale, k++ ) { for( uint j = 0, l = 0; j < original_cloud_ptr->height; j += scale, l++ ) { downsampled_cloud_ptr->at(k,l) = original_cloud_ptr->at(i,j); } } // ----------- // Convert to grayscale and back (for display purposes) if( display_image_ || display_window_) { cv::cvtColor( img, this->result_img_, CV_BGR2GRAY); cv::cvtColor( this->result_img_, this->result_img_, CV_GRAY2BGR); this->result_img_.convertTo( this->result_img_, -1, 1.0, 50); } // Camera information image_geometry::PinholeCameraModel cam_model; cam_model.fromCameraInfo(camera_info_msg); // Make a remote call to get the 'hand' (or glove) //double t = this->timerStart(); std::map< int, pcl::PointIndices > hand_indices; std::vector< std::vector<cv::Point> > hand_contours; hand_tracking::TrackingService srv; srv.request.image = *image_msg; if( this->_tracking_client.call(srv)) { // Get the hand mask contour for( int i = 0; i < srv.response.contours.size(); i++) { std::vector<cv::Point> contour; for( uint j = 0; j < srv.response.contours[i].contour.size(); j++) { cv::Point p( srv.response.contours[i].contour[j].x, srv.response.contours[i].contour[j].y ); contour.push_back(p); } hand_contours.push_back(contour); } // Filter the indices of all 3D points within the hand contour int key = 0; for ( int i = 0; i < hand_contours.size(); i++) { cv::Mat mask( img.size(), CV_8U, cv::Scalar(0)); cv::drawContours( mask, hand_contours, i, cv::Scalar(255), -1); uint idx = 0; pcl::PointIndices point_idx; BOOST_FOREACH ( const segmentation::Point pt, downsampled_cloud_ptr->points ) { tf2::Vector3 trans_pt( pt.x, pt.y, pt.z); //tf2::doTransform( trans_pt, trans_pt, tf_forward); trans_pt = transform * trans_pt; if( ( trans_pt.x() > this->min_x_ && trans_pt.x() < this->max_x_ ) && ( trans_pt.y() > this->min_y_ && trans_pt.y() < this->max_y_ ) && ( trans_pt.z() > this->min_z_ && trans_pt.z() < this->max_z_ ) ) { cv::Point3d pt_3d( pt.x, pt.y, pt.z); cv::Point pt_2d = cam_model.project3dToPixel(pt_3d); if ( pt_2d.y >= 0 && pt_2d.y < mask.rows && pt_2d.x >= 0 && pt_2d.x < mask.cols ) { if( mask.at<uchar>( pt_2d.y, pt_2d.x) != 0 ) { point_idx.indices.push_back(idx); } } } idx++; } //ROS_WARN("[TEST] Points: %d", (int)point_idx.indices.size()); if( point_idx.indices.size() >= this->seg_.getClusterMinSize() ) hand_indices.insert( std::pair< int, pcl::PointIndices>( key, point_idx) ); key++; } } //this->timerEnd( t, "Hand detection"); // Cluster cloud into objects // ---------------------------------------- std::vector<pcl::PointIndices> cluster_indices; //this->seg_.clusterOrganized(transformed_cloud_ptr, cluster_indices); //this->seg_.clusterOrganized(raw_cloud_ptr, cluster_indices); // TEST - Use downsampled cloud instead // ----------------------------------------- //t = this->timerStart(); this->seg_.clusterOrganized( downsampled_cloud_ptr, cluster_indices); //this->timerEnd( t, "Clustering"); // Post-process the segmented clusters (filter out the 'hand' points) //t = this->timerStart(); if( !hand_indices.empty() ) { for( uint i = 0; i < hand_indices.size(); i++ ) { for ( uint j = 0; j < cluster_indices.size (); j++) { for( auto &idx : hand_indices[i].indices) { auto ite = std::find (cluster_indices[j].indices.begin(), cluster_indices[j].indices.end(), idx); if( ite != cluster_indices[j].indices.end() ) { cluster_indices[j].indices.erase(ite); } } if( cluster_indices[j].indices.size() < this->seg_.getClusterMinSize() ) cluster_indices.erase( cluster_indices.begin() + j ); } } // Add the 'hand' indecies to the reaming cluster indices for( auto &ite : hand_indices ) { cluster_indices.insert( cluster_indices.begin() + ite.first, ite.second ); } //ROS_INFO("Clusters: %d (include a 'hand' cluster)", (int)cluster_indices.size()); } else { //ROS_INFO("Clusters: %d", (int)cluster_indices.size()); } //this->timerEnd( t, "Post-processing"); /* ROS_INFO("Clusters: \n"); for (size_t i = 0; i < cluster_indices.size (); i++) { if( hand_indices.find(i) != hand_indices.end() ) ROS_INFO("Hand size: %d", (int)cluster_indices[i].indices.size()); else ROS_INFO("Object size: %d", (int)cluster_indices[i].indices.size()); } ROS_INFO("-----------"); */ // Process all segmented clusters (including the 'hand' cluster) if( !cluster_indices.empty() ) { // Image & Cloud output anchor_msgs::ClusterArray clusters; anchor_msgs::ObjectArray objects; anchor_msgs::MovementArray movements; objects.header = cloud_msg->header; objects.image = *image_msg; objects.info = *camera_info_msg; objects.transform = tf_forward; /* // Store the inverse transformation tf::Quaternion tf_quat = transform.inverse().getRotation(); objects.transform.rotation.x = tf_quat.x(); objects.transform.rotation.y = tf_quat.y(); objects.transform.rotation.z = tf_quat.z(); objects.transform.rotation.w = tf_quat.w(); tf::Vector3 tf_vec = transform.inverse().getOrigin(); objects.transform.translation.x = tf_vec.getX(); objects.transform.translation.y = tf_vec.getY(); objects.transform.translation.z = tf_vec.getZ(); */ // Process the segmented clusters int sz = 5; cv::Mat kernel = cv::getStructuringElement( cv::BORDER_CONSTANT, cv::Size( sz, sz), cv::Point(-1,-1) ); for (size_t i = 0; i < cluster_indices.size (); i++) { // Get the cluster pcl::PointCloud<segmentation::Point>::Ptr cluster_ptr (new pcl::PointCloud<segmentation::Point>); //pcl::copyPointCloud( *original_cloud_ptr, cluster_indices[i], *cluster_ptr); // TEST - Use downsampled cloud instead // ----------------------------------------- pcl::copyPointCloud( *downsampled_cloud_ptr, cluster_indices[i], *cluster_ptr); //std::cout << cluster_ptr->points.size() << std::endl; if( cluster_ptr->points.empty() ) continue; // Post-process the cluster try { // Create the cluster image cv::Mat cluster_img( img.size(), CV_8U, cv::Scalar(0)); BOOST_FOREACH ( const segmentation::Point pt, cluster_ptr->points ) { cv::Point3d pt_cv( pt.x, pt.y, pt.z); cv::Point2f p = cam_model.project3dToPixel(pt_cv); circle( cluster_img, p, 2, cv::Scalar(255), -1, 8, 0 ); } // Apply morphological operations the cluster image cv::dilate( cluster_img, cluster_img, kernel); cv::erode( cluster_img, cluster_img, kernel); // Find the contours of the cluster std::vector<std::vector<cv::Point> > contours; std::vector<cv::Vec4i> hierarchy; cv::findContours( cluster_img, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE); // Get the contour of the convex hull std::vector<cv::Point> contour = getLargetsContour( contours ); // Create and add the object output message if( contour.size() > 0 ) { anchor_msgs::Object obj; for( size_t j = 0; j < contour.size(); j++) { anchor_msgs::Point2d p; p.x = contour[j].x; p.y = contour[j].y; obj.visual.border.contour.push_back(p); } // Add segmented object to display image img.copyTo( this->result_img_, cluster_img); // Draw the contour (for display) cv::Scalar color = cv::Scalar( 32, 84, 233); // Orange //cv::Scalar color = cv::Scalar( 0, 0, 233); // Red //cv::Scalar color = cv::Scalar::all(64); // Dark gray // Check if we have a hand countour if( hand_indices.find(i) != hand_indices.end() ) { color = cv::Scalar( 0, 233, 0); // Green } cv::drawContours( this->result_img_, contours, -1, color, 1); // Transfrom the the cloud once again //tf2::doTransform( *cluster_ptr, *cluster_ptr, tf_forward); //pcl_ros::transformPointCloud( *cluster_ptr, *cluster_ptr, transform); pcl_ros::transformPointCloud(tf2::transformToEigen(tf_forward.transform).matrix(), *cluster_ptr, *cluster_ptr); // 1. Extract the position geometry_msgs::PoseStamped pose; pose.header.stamp = cloud_msg->header.stamp; segmentation::getOrientedPosition( cluster_ptr, pose.pose); obj.position.data = pose; // Add the position to the movement array movements.movements.push_back(pose); //std::cout << "Position: [" << obj.position.data.pose.position.x << ", " << obj.position.data.pose.position.y << ", " << obj.position.data.pose.position.z << "]" << std::endl; // 2. Extract the shape segmentation::getSize( cluster_ptr, obj.size.data ); // Ground size symbols std::vector<double> data = { obj.size.data.x, obj.size.data.y, obj.size.data.z}; std::sort( data.begin(), data.end(), std::greater<double>()); if( data.front() <= 0.1 ) { // 0 - 15 [cm] = small obj.size.symbols.push_back("small"); } else if( data.front() <= 0.20 ) { // 16 - 30 [cm] = medium obj.size.symbols.push_back("medium"); } else { // > 30 [cm] = large obj.size.symbols.push_back("large"); } if( data[0] < data[1] * 1.1 ) { obj.size.symbols.push_back("square"); } else { obj.size.symbols.push_back("rectangle"); if( data[0] > data[1] * 1.5 ) { obj.size.symbols.push_back("long"); } else { obj.size.symbols.push_back("short"); } } // TEST // --------------------------------------- // Attempt to filter out glitchs if ( obj.size.data.z < 0.02 ) continue; // Add the object to the object array message objects.objects.push_back(obj); /* Eigen::Vector4f centroid; pcl::compute3DCentroid ( transformed_cloud, centroid); if( centroid[0] > 0.0 && centroid[1] < 0.5 && centroid[1] > -0.5 ) std::cout << "Position [" << centroid[0] << ", " << centroid[1] << ", " << centroid[2] << "]" << std::endl; */ // Add the (un-transformed) cluster to the array message geometry_msgs::Pose center; segmentation::getPosition( cluster_ptr, center ); clusters.centers.push_back(center); sensor_msgs::PointCloud2 cluster; pcl::toROSMsg( *cluster_ptr, cluster ); clusters.clusters.push_back(cluster); } } catch( cv::Exception &exc ) { ROS_ERROR("[object_recognition] CV processing error: %s", exc.what() ); } } //std::cout << "---" << std::endl; // Publish the "segmented" image if( display_image_ ) { cv_ptr->image = this->result_img_; cv_ptr->encoding = "bgr8"; display_image_pub_.publish(cv_ptr->toImageMsg()); } // Publish the object array if( !objects.objects.empty() || !clusters.clusters.empty() ) { // ROS_INFO("Publishing: %d objects.", (int)objects.objects.size()); obj_pub_.publish(objects); cluster_pub_.publish(clusters); move_pub_.publish(movements); } } } void ObjectSegmentation::filter( pcl::PointCloud<segmentation::Point>::Ptr &cloud_ptr ) { // Filter the transformed point cloud if( cloud_ptr->isOrganized ()) { segmentation::passThroughFilter( cloud_ptr, cloud_ptr, "x", this->min_x_, this->max_x_); segmentation::passThroughFilter( cloud_ptr, cloud_ptr, "y", this->min_y_, this->max_y_); segmentation::passThroughFilter( cloud_ptr, cloud_ptr, "z", this->min_z_, this->max_z_); /* for( auto &p: cloud_ptr->points) { if( !( p.x > this->min_x_ && p.x < this->max_x_ ) || !( p.y > this->min_y_ && p.y < this->max_y_ ) || !( p.z > this->min_z_ && p.z < this->max_z_ ) ) { p.x = std::numeric_limits<double>::quiet_NaN(); //infinity(); p.y = std::numeric_limits<double>::quiet_NaN(); p.z = std::numeric_limits<double>::quiet_NaN(); p.b = p.g = p.r = 0; } } */ } else { pcl::PointCloud<segmentation::Point>::Ptr result_ptr (new pcl::PointCloud<segmentation::Point>); for( auto &p: cloud_ptr->points) { if( ( p.x > this->min_x_ && p.x < this->max_x_ ) && ( p.y > this->min_y_ && p.y < this->max_y_ ) && ( p.z > this->min_z_ && p.z < this->max_z_ ) ) { result_ptr->points.push_back (p); } } cloud_ptr.swap (result_ptr); } } std::vector<cv::Point> ObjectSegmentation::getLargetsContour( std::vector<std::vector<cv::Point> > contours ) { std::vector<cv::Point> result = contours.front(); for ( size_t i = 1; i< contours.size(); i++) if( contours[i].size() > result.size() ) result = contours[i]; return result; } std::vector<cv::Point> ObjectSegmentation::contoursConvexHull( std::vector<std::vector<cv::Point> > contours ) { std::vector<cv::Point> result; std::vector<cv::Point> pts; for ( size_t i = 0; i< contours.size(); i++) for ( size_t j = 0; j< contours[i].size(); j++) pts.push_back(contours[i][j]); cv::convexHull( pts, result ); return result; } // Detect a 'hand'/'glove' object based on color segmentation std::vector<cv::Point> ObjectSegmentation::handDetection( cv::Mat &img ) { cv::Mat hsv_img; int sz = 5; // Convert to HSV color space cv::cvtColor( img, hsv_img, cv::COLOR_BGR2HSV); // Pre-process the image by blur cv::blur( hsv_img, hsv_img, cv::Size( sz, sz)); // Extrace binary mask cv::Mat mask; cv::inRange( hsv_img, cv::Scalar( 31, 68, 141), cv::Scalar( 47, 255, 255), mask); // Post-process the threshold image cv::Mat kernel = cv::getStructuringElement( cv::BORDER_CONSTANT, cv::Size( sz, sz), cv::Point(-1,-1) ); cv::dilate( mask, mask, kernel); cv::erode( mask, mask, kernel); // Find the contours std::vector<std::vector<cv::Point> > contours; std::vector<cv::Vec4i> hierarchy; cv::findContours( mask, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE); // Filter the contoruse based on size std::vector<std::vector<cv::Point> > result; for ( int i = 0; i < contours.size(); i++) { if ( cv::contourArea(contours[i]) > 500 ) { result.push_back(contours[i]); } } return result[0]; } // Timer functions double ObjectSegmentation::timerStart() { return (double)cv::getTickCount(); } void ObjectSegmentation::timerEnd( double t, std::string msg) { t = ((double)cv::getTickCount() - t) / (double)cv::getTickFrequency(); ROS_INFO("[Timer] %s: %.4f (s)", msg.c_str(), t); } // ---------------------- // Main function // ------------------ int main(int argc, char **argv) { ros::init(argc, argv, "object_segmentation_node"); ros::NodeHandle nh; // Saftey check if(!ros::ok()) { return 0; } ObjectSegmentation node(nh); node.spin(); ros::shutdown(); return 0; }
34.907012
181
0.649373
probabilistic-anchoring
36b81c19aeda7c00fbd9db5ed053f3783b4ca23b
26,872
cpp
C++
src/components/SuperContainer.cpp
hhyyrylainen/DualViewPP
1fb4a1db85a8509342e16d68c75d4ec7721ced9e
[ "MIT" ]
null
null
null
src/components/SuperContainer.cpp
hhyyrylainen/DualViewPP
1fb4a1db85a8509342e16d68c75d4ec7721ced9e
[ "MIT" ]
null
null
null
src/components/SuperContainer.cpp
hhyyrylainen/DualViewPP
1fb4a1db85a8509342e16d68c75d4ec7721ced9e
[ "MIT" ]
null
null
null
// ------------------------------------ // #include "SuperContainer.h" #include "Common.h" #include "DualView.h" using namespace DV; // ------------------------------------ // //#define SUPERCONTAINER_RESIZE_REFLOW_CHECK_ONLY_FIRST_ROW SuperContainer::SuperContainer() : Gtk::ScrolledWindow(), View(get_hadjustment(), get_vadjustment()) { _CommonCtor(); } SuperContainer::SuperContainer( _GtkScrolledWindow* widget, Glib::RefPtr<Gtk::Builder> builder) : Gtk::ScrolledWindow(widget), View(get_hadjustment(), get_vadjustment()) { _CommonCtor(); } void SuperContainer::_CommonCtor() { add(View); View.add(Container); View.show(); Container.show(); PositionIndicator.property_width_request() = 2; PositionIndicator.set_orientation(Gtk::ORIENTATION_VERTICAL); PositionIndicator.get_style_context()->add_class("PositionIndicator"); signal_size_allocate().connect(sigc::mem_fun(*this, &SuperContainer::_OnResize)); signal_button_press_event().connect( sigc::mem_fun(*this, &SuperContainer::_OnMouseButtonPressed)); // Both scrollbars need to be able to appear, otherwise the width cannot be reduced // so that wrapping occurs set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC); } SuperContainer::~SuperContainer() { Clear(); } // ------------------------------------ // void SuperContainer::Clear(bool deselect /*= false*/) { DualView::IsOnMainThreadAssert(); // This could be made more efficient if(deselect) DeselectAllItems(); // This will delete all the widgets // Positions.clear(); _PositionIndicator(); LayoutDirty = false; } // ------------------------------------ // void SuperContainer::UpdatePositioning() { if(!LayoutDirty) return; LayoutDirty = false; WidestRow = Margin; if(Positions.empty()) { _PositionIndicator(); return; } int32_t CurrentRow = Margin; int32_t CurrentY = Positions.front().Y; for(auto& position : Positions) { if(position.Y != CurrentY) { // Row changed // if(WidestRow < CurrentRow) WidestRow = CurrentRow; CurrentRow = position.X; CurrentY = position.Y; } CurrentRow += position.Width + Padding; _ApplyWidgetPosition(position); } // Last row needs to be included, too // if(WidestRow < CurrentRow) WidestRow = CurrentRow; // Add margin WidestRow += Margin; _PositionIndicator(); } void SuperContainer::UpdateRowWidths() { WidestRow = Margin; int32_t CurrentRow = Margin; int32_t CurrentY = Positions.front().Y; for(auto& position : Positions) { if(position.Y != CurrentY) { // Row changed // if(WidestRow < CurrentRow) WidestRow = CurrentRow; CurrentRow = position.X; CurrentY = position.Y; } CurrentRow += position.Width + Padding; } // Last row needs to be included, too // if(WidestRow < CurrentRow) WidestRow = CurrentRow; // Add margin WidestRow += Margin; } // ------------------------------------ // size_t SuperContainer::CountRows() const { size_t count = 0; int32_t CurrentY = -1; for(auto& position : Positions) { // Stop once empty position is reached // if(!position.WidgetToPosition) break; if(position.Y != CurrentY) { ++count; CurrentY = position.Y; } } return count; } size_t SuperContainer::CountItems() const { size_t count = 0; for(auto& position : Positions) { // Stop once empty position is reached // if(!position.WidgetToPosition) break; ++count; } return count; } // ------------------------------------ // size_t SuperContainer::CountSelectedItems() const { size_t count = 0; for(auto& position : Positions) { // Stop once empty position is reached // if(!position.WidgetToPosition) break; if(position.WidgetToPosition->Widget->IsSelected()) ++count; } return count; } void SuperContainer::DeselectAllItems() { for(auto& position : Positions) { // Stop once empty position is reached // if(!position.WidgetToPosition) break; position.WidgetToPosition->Widget->Deselect(); } } void SuperContainer::SelectAllItems() { for(auto& position : Positions) { // Stop once empty position is reached // if(!position.WidgetToPosition) break; position.WidgetToPosition->Widget->Select(); } } void SuperContainer::DeselectAllExcept(const ListItem* item) { for(auto& position : Positions) { // Stop once empty position is reached // if(!position.WidgetToPosition) break; if(position.WidgetToPosition->Widget.get() == item) continue; position.WidgetToPosition->Widget->Deselect(); } } void SuperContainer::DeselectFirstItem() { for(auto& position : Positions) { // Stop once empty position is reached // if(!position.WidgetToPosition) break; if(position.WidgetToPosition->Widget->IsSelected()) { position.WidgetToPosition->Widget->Deselect(); return; } } } void SuperContainer::SelectFirstItems(int count) { int selected = 0; for(auto& position : Positions) { // If enough are selected stop if(selected >= count) break; // Stop once empty position is reached // if(!position.WidgetToPosition) break; position.WidgetToPosition->Widget->Select(); ++selected; } } void SuperContainer::SelectNextItem() { bool select = false; for(auto iter = Positions.begin(); iter != Positions.end(); ++iter) { auto& position = *iter; // Stop once empty position is reached // if(!position.WidgetToPosition) break; if(select == true) { position.WidgetToPosition->Widget->Select(); DeselectAllExcept(position.WidgetToPosition->Widget.get()); break; } if(position.WidgetToPosition->Widget->IsSelected()) { select = true; } } if(!select) { // None selected // SelectFirstItem(); } } void SuperContainer::SelectPreviousItem() { bool select = false; for(auto iter = Positions.rbegin(); iter != Positions.rend(); ++iter) { auto& position = *iter; // When reversing we can't stop when the tailing empty slots are reached if(!position.WidgetToPosition) continue; if(select == true) { position.WidgetToPosition->Widget->Select(); DeselectAllExcept(position.WidgetToPosition->Widget.get()); break; } if(position.WidgetToPosition->Widget->IsSelected()) { select = true; } } if(!select) { // None selected // SelectFirstItem(); } } void SuperContainer::ShiftSelectTo(const ListItem* item) { // Find first non-matching item to start from size_t selectStart = 0; // And also where item is size_t itemsPosition = 0; for(size_t i = 0; i < Positions.size(); ++i) { auto& position = Positions[i]; if(!position.WidgetToPosition) continue; if(position.WidgetToPosition->Widget.get() == item) { itemsPosition = i; } else if(selectStart == 0 && position.WidgetToPosition->Widget->IsSelected()) { selectStart = i; } } // Swap so that the order is always the lower to higher if(selectStart > itemsPosition) std::swap(selectStart, itemsPosition); // TODO: pre-select callback // Perform actual selections for(size_t i = selectStart; i <= itemsPosition; ++i) { auto& position = Positions[i]; if(!position.WidgetToPosition) continue; position.WidgetToPosition->Widget->Select(); } // TODO: post-select callback } // ------------------------------------ // bool SuperContainer::IsEmpty() const { for(auto& position : Positions) { // Stop once empty position is reached // if(!position.WidgetToPosition) break; // Found non-empty return false; } return true; } // ------------------------------------ // std::shared_ptr<ResourceWithPreview> SuperContainer::GetFirstVisibleResource( double scrollOffset) const { for(const auto& position : Positions) { if(((position.Y + 5) > scrollOffset) && position.WidgetToPosition) { return position.WidgetToPosition->CreatedFrom; } } return nullptr; } std::vector<std::shared_ptr<ResourceWithPreview>> SuperContainer::GetResourcesVisibleAfter( double scrollOffset) const { std::vector<std::shared_ptr<ResourceWithPreview>> result; result.reserve(Positions.size() / 3); for(const auto& position : Positions) { if(((position.Y + 5) > scrollOffset) && position.WidgetToPosition) { result.push_back(position.WidgetToPosition->CreatedFrom); } } return result; } double SuperContainer::GetResourceOffset(std::shared_ptr<ResourceWithPreview> resource) const { for(const auto& position : Positions) { if(position.WidgetToPosition && position.WidgetToPosition->CreatedFrom == resource) { return position.Y; } } return -1; } // ------------------------------------ // void SuperContainer::UpdateMarginAndPadding(int newmargin, int newpadding) { Margin = newmargin; Padding = newpadding; LayoutDirty = true; Reflow(0); UpdatePositioning(); } // ------------------------------------ // void SuperContainer::Reflow(size_t index) { if(Positions.empty() || index >= Positions.size()) return; LayoutDirty = true; // The first one doesn't have a previous position // if(index == 0) { LastWidthReflow = get_width(); _PositionGridPosition(Positions.front(), nullptr, Positions.size()); ++index; } // This is a check for debugging //_CheckPositions(); for(size_t i = index; i < Positions.size(); ++i) { _PositionGridPosition(Positions[i], &Positions[i - 1], i - 1); } } void SuperContainer::_PositionGridPosition( GridPosition& current, const GridPosition* const previous, size_t previousindex) const { // First is at fixed position // if(previous == nullptr) { current.X = Margin; current.Y = Margin; return; } LEVIATHAN_ASSERT(previousindex < Positions.size(), "previousindex is out of range"); // Check does it fit on the line // if(previous->X + previous->Width + Padding + current.Width <= get_width()) { // It fits on the line // current.Y = previous->Y; current.X = previous->X + previous->Width + Padding; return; } // A new line is needed // // Find the tallest element in the last row int32_t lastRowMaxHeight = previous->Height; // Start from the one before previous, doesn't matter if the index wraps around as // the loop won't be entered in that case size_t scanIndex = previousindex - 1; const auto rowY = previous->Y; while(scanIndex < Positions.size()) { if(Positions[scanIndex].Y != rowY) { // Full row scanned // break; } // Check current height // const auto currentHeight = Positions[scanIndex].Height; if(currentHeight > lastRowMaxHeight) lastRowMaxHeight = currentHeight; // Move to previous // --scanIndex; if(scanIndex == 0) break; } // Position according to the maximum height of the last row current.X = Margin; current.Y = previous->Y + lastRowMaxHeight + Padding; } SuperContainer::GridPosition& SuperContainer::_AddNewGridPosition( int32_t width, int32_t height) { GridPosition pos; pos.Width = width; pos.Height = height; if(Positions.empty()) { _PositionGridPosition(pos, nullptr, 0); } else { _PositionGridPosition(pos, &Positions.back(), Positions.size() - 1); } Positions.push_back(pos); return Positions.back(); } // ------------------------------------ // void SuperContainer::_SetWidgetSize(Element& widget) { int width_min, width_natural; int height_min, height_natural; widget.Widget->SetItemSize(SelectedItemSize); Container.add(*widget.Widget); widget.Widget->show(); widget.Widget->get_preferred_width(width_min, width_natural); widget.Widget->get_preferred_height_for_width(width_natural, height_min, height_natural); widget.Width = width_natural; widget.Height = height_natural; widget.Widget->set_size_request(widget.Width, widget.Height); } void SuperContainer::SetItemSize(LIST_ITEM_SIZE newsize) { if(SelectedItemSize == newsize) return; SelectedItemSize = newsize; if(Positions.empty()) return; // Resize all elements // for(const auto& position : Positions) { if(position.WidgetToPosition) { _SetWidgetSize(*position.WidgetToPosition); } } LayoutDirty = true; UpdatePositioning(); } // ------------------------------------ // void SuperContainer::_SetKeepFalse() { for(auto& position : Positions) { if(position.WidgetToPosition) position.WidgetToPosition->Keep = false; } } void SuperContainer::_RemoveElementsNotMarkedKeep() { size_t reflowStart = Positions.size(); for(size_t i = 0; i < Positions.size();) { auto& current = Positions[i]; // If the current position has no widget try to get the next widget, or end // if(!current.WidgetToPosition) { if(i + 1 < Positions.size()) { // Swap with the next one // if(Positions[i].SwapWidgets(Positions[i + 1])) { if(reflowStart > i) reflowStart = i; } } // If still empty there are no more widgets to process // It doesn't seem to be right for some reason to break here if(!current.WidgetToPosition) { ++i; continue; } } if(!Positions[i].WidgetToPosition->Keep) { LayoutDirty = true; // Remove this widget // Container.remove(*current.WidgetToPosition->Widget); current.WidgetToPosition.reset(); // On the next iteration the next widget will be moved to this position } else { ++i; } } if(reflowStart < Positions.size()) { // Need to reflow // Reflow(reflowStart); } } // ------------------------------------ // void SuperContainer::_RemoveWidget(size_t index) { if(index >= Positions.size()) throw Leviathan::InvalidArgument("index out of range"); LayoutDirty = true; size_t reflowStart = Positions.size(); Container.remove(*Positions[index].WidgetToPosition->Widget); Positions[index].WidgetToPosition.reset(); // Move forward all the widgets // for(size_t i = index; i + 1 < Positions.size(); ++i) { if(Positions[i].SwapWidgets(Positions[i + 1])) { if(reflowStart > i) reflowStart = i; } } if(reflowStart < Positions.size()) { // Need to reflow // Reflow(reflowStart); } } void SuperContainer::_SetWidget( size_t index, std::shared_ptr<Element> widget, bool selectable, bool autoreplace) { if(index >= Positions.size()) throw Leviathan::InvalidArgument("index out of range"); if(Positions[index].WidgetToPosition) { if(!autoreplace) { throw Leviathan::InvalidState("index is not empty and no autoreplace specified"); } else { // Remove the current one Container.remove(*Positions[index].WidgetToPosition->Widget); } } // Initialize a size for the widget _SetWidgetSize(*widget); _SetWidgetAdvancedSelection(*widget->Widget, selectable); // Set it // if(Positions[index].SetNewWidget(widget)) { // Do a reflow // Reflow(index); } else { // Apply positioning now // if(!LayoutDirty) { _ApplyWidgetPosition(Positions[index]); UpdateRowWidths(); _PositionIndicator(); } } } // ------------------------------------ // void SuperContainer::_PushBackWidgets(size_t index) { if(Positions.empty()) return; LayoutDirty = true; size_t reflowStart = Positions.size(); // Create a new position and then pull back widgets until index is reached and then // stop // We can skip adding if the last is empty // if(Positions.back().WidgetToPosition) _AddNewGridPosition(Positions.back().Width, Positions.back().Height); for(size_t i = Positions.size() - 1; i > index; --i) { // Swap pointers around, the current index is always empty so the empty // spot will propagate to index // Also i - 1 cannot be out of range as the smallest index 0 wouldn't enter // this loop if(Positions[i].SwapWidgets(Positions[i - 1])) { if(reflowStart > i) reflowStart = i; } } if(reflowStart < Positions.size()) { // Need to reflow // Reflow(reflowStart); } } void SuperContainer::_AddWidgetToEnd(std::shared_ptr<ResourceWithPreview> item, const std::shared_ptr<ItemSelectable>& selectable) { // Create the widget // auto element = std::make_shared<Element>(item, selectable); // Initialize a size for the widget _SetWidgetSize(*element); _SetWidgetAdvancedSelection(*element->Widget, selectable.operator bool()); // Find the first empty spot // for(size_t i = 0; i < Positions.size(); ++i) { if(!Positions[i].WidgetToPosition) { if(Positions[i].SetNewWidget(element)) { // Do a reflow // Reflow(i); } return; } } // No empty spots, create a new one // GridPosition& pos = _AddNewGridPosition(element->Width, element->Height); pos.WidgetToPosition = element; if(!LayoutDirty) { _ApplyWidgetPosition(pos); UpdateRowWidths(); _PositionIndicator(); } } // ------------------------------------ // void SuperContainer::_SetWidgetAdvancedSelection(ListItem& widget, bool selectable) { if(widget.HasAdvancedSelection() == selectable) return; if(selectable) { widget.SetAdvancedSelection([=](ListItem& item) { ShiftSelectTo(&item); }); } else { widget.SetAdvancedSelection(nullptr); } } // ------------------------------------ // void SuperContainer::_CheckPositions() const { // Find duplicate stuff // for(size_t i = 0; i < Positions.size(); ++i) { for(size_t a = 0; a < Positions.size(); ++a) { if(a == i) continue; if(Positions[i].WidgetToPosition.get() == Positions[a].WidgetToPosition.get()) { LEVIATHAN_ASSERT( false, "SuperContainer::_CheckPositions: duplicate Element ptr"); } if(Positions[i].X == Positions[a].X && Positions[i].Y == Positions[a].Y) { LEVIATHAN_ASSERT(false, "SuperContainer::_CheckPositions: duplicate position"); } if(Positions[i].WidgetToPosition->Widget.get() == Positions[a].WidgetToPosition->Widget.get()) { LEVIATHAN_ASSERT( false, "SuperContainer::_CheckPositions: duplicate ListItem ptr"); } } } } // ------------------------------------ // // Position indicator void SuperContainer::EnablePositionIndicator() { if(PositionIndicatorEnabled) return; PositionIndicatorEnabled = true; Container.add(PositionIndicator); // Enable the click to change indicator position add_events(Gdk::BUTTON_PRESS_MASK); _PositionIndicator(); } size_t SuperContainer::GetIndicatorPosition() const { return IndicatorPosition; } void SuperContainer::SetIndicatorPosition(size_t position) { if(IndicatorPosition == position) return; IndicatorPosition = position; _PositionIndicator(); } void SuperContainer::SuperContainer::_PositionIndicator() { if(!PositionIndicatorEnabled) { return; } constexpr auto indicatorHeightSmallerBy = 6; // Detect emptyness, but also the widget size bool found = false; for(const auto& position : Positions) { if(position.WidgetToPosition) { found = true; PositionIndicator.property_height_request() = position.WidgetToPosition->Height - indicatorHeightSmallerBy; break; } } if(!found) { // Empty PositionIndicator.property_visible() = false; return; } PositionIndicator.property_visible() = true; // Optimization for last if(IndicatorPosition >= Positions.size()) { for(size_t i = Positions.size() - 1;; --i) { const auto& position = Positions[i]; if(position.WidgetToPosition) { // Found the end Container.move(PositionIndicator, position.X + position.Width + Padding / 2, position.Y + indicatorHeightSmallerBy / 2); return; } if(i == 0) { break; } } } else { if(IndicatorPosition == 0) { // Optimization for first Container.move( PositionIndicator, Margin / 2, Margin + indicatorHeightSmallerBy / 2); return; } else { // Find a suitable position (or leave hidden) bool after = false; for(size_t i = IndicatorPosition;; --i) { const auto& position = Positions[i]; if(position.WidgetToPosition) { Container.move(PositionIndicator, after ? position.X + Positions[i].Width + Padding / 2 : position.X - Padding / 2, position.Y + indicatorHeightSmallerBy / 2); return; } else { after = true; } if(i == 0) { break; } } } } LOG_ERROR("SuperContainer: failed to find position for indicator"); PositionIndicator.property_visible() = false; } size_t SuperContainer::CalculateIndicatorPositionFromCursor(int cursorx, int cursory) { size_t newPosition = -1; // The cursor position needs to be adjusted by the scroll offset const auto x = get_hadjustment()->get_value() + cursorx; const auto y = get_vadjustment()->get_value() + cursory; for(size_t i = 0; i < Positions.size(); ++i) { const auto& position = Positions[i]; if(!position.WidgetToPosition) break; // If click is not on this row, ignore if(y < position.Y || y > position.Y + position.Height + Padding) continue; // If click is to the left of position this is the target if(position.X + position.Width / 2 > x) { newPosition = i; break; } // If click is to the right of this the next position (if it exists) might be the // target if(x > position.X + position.Width) { newPosition = i + 1; } } return newPosition; } // ------------------------------------ // // Callbacks void SuperContainer::_OnResize(Gtk::Allocation& allocation) { if(Positions.empty()) return; // Skip if width didn't change // if(allocation.get_width() == LastWidthReflow) return; // Even if we don't reflow we don't want to be called again with the same width LastWidthReflow = allocation.get_width(); bool reflow = false; // If doesn't fit dual margins if(allocation.get_width() < WidestRow + Margin) { // Rows don't fit anymore // reflow = true; } else { // Check would wider rows fit // int32_t CurrentRow = 0; int32_t CurrentY = Positions.front().Y; for(auto& position : Positions) { if(position.Y != CurrentY) { // Row changed // if(Margin + CurrentRow + Padding + position.Width < allocation.get_width()) { // The previous row (this is the first position of the first row) could // now fit this widget reflow = true; break; } CurrentRow = 0; CurrentY = position.Y; // Break if only checking first row #ifdef SUPERCONTAINER_RESIZE_REFLOW_CHECK_ONLY_FIRST_ROW break; #endif } CurrentRow += position.Width; } } if(reflow) { Reflow(0); UpdatePositioning(); // Forces update of positions Container.check_resize(); } } bool SuperContainer::_OnMouseButtonPressed(GdkEventButton* event) { if(event->type == GDK_BUTTON_PRESS) { SetIndicatorPosition(CalculateIndicatorPositionFromCursor(event->x, event->y)); return true; } return false; } // ------------------------------------ // // GridPosition bool SuperContainer::GridPosition::SetNewWidget(std::shared_ptr<Element> widget) { const auto newWidth = widget->Width; const auto newHeight = widget->Height; WidgetToPosition = widget; if(newWidth != Width && newHeight != Height) { Width = newWidth; Height = newHeight; return true; } return false; } bool SuperContainer::GridPosition::SwapWidgets(GridPosition& other) { WidgetToPosition.swap(other.WidgetToPosition); if(Width != other.Width || Height != other.Height) { Width = other.Width; Height = other.Height; return true; } return false; } std::string SuperContainer::GridPosition::ToString() const { return "[" + std::to_string(X) + ", " + std::to_string(Y) + " dim: " + std::to_string(Width) + ", " + std::to_string(Height) + " " + (WidgetToPosition ? "(filled)" : "(empty)"); }
24.384755
95
0.578818
hhyyrylainen
36babb2c262f98e60e259cada00e847ab0b90a80
6,585
cpp
C++
src/xr_3da/xrGame/WeaponKnife.cpp
ixray-team/ixray-b2945
ad5ef375994ee9cd790c4144891e9f00e7efe565
[ "Linux-OpenIB" ]
1
2022-03-26T17:00:19.000Z
2022-03-26T17:00:19.000Z
src/xr_3da/xrGame/WeaponKnife.cpp
ixray-team/ixray-b2945
ad5ef375994ee9cd790c4144891e9f00e7efe565
[ "Linux-OpenIB" ]
null
null
null
src/xr_3da/xrGame/WeaponKnife.cpp
ixray-team/ixray-b2945
ad5ef375994ee9cd790c4144891e9f00e7efe565
[ "Linux-OpenIB" ]
1
2022-03-26T17:00:21.000Z
2022-03-26T17:00:21.000Z
#include "stdafx.h" #include "WeaponKnife.h" #include "WeaponHUD.h" #include "Entity.h" #include "Actor.h" #include "level.h" #include "xr_level_controller.h" #include "game_cl_base.h" #include "../skeletonanimated.h" #include "gamemtllib.h" #include "level_bullet_manager.h" #include "ai_sounds.h" #define KNIFE_MATERIAL_NAME "objects\\knife" CWeaponKnife::CWeaponKnife() : CWeapon("KNIFE") { m_attackStart = false; m_bShotLight = false; SetState ( eHidden ); SetNextState ( eHidden ); knife_material_idx = (u16)-1; } CWeaponKnife::~CWeaponKnife() { HUD_SOUND::DestroySound(m_sndShot); } void CWeaponKnife::Load (LPCSTR section) { // verify class inherited::Load (section); fWallmarkSize = pSettings->r_float(section,"wm_size"); // HUD :: Anims R_ASSERT (m_pHUD); animGet (mhud_idle, pSettings->r_string(*hud_sect,"anim_idle")); animGet (mhud_hide, pSettings->r_string(*hud_sect,"anim_hide")); animGet (mhud_show, pSettings->r_string(*hud_sect,"anim_draw")); animGet (mhud_attack, pSettings->r_string(*hud_sect,"anim_shoot1_start")); animGet (mhud_attack2, pSettings->r_string(*hud_sect,"anim_shoot2_start")); animGet (mhud_attack_e, pSettings->r_string(*hud_sect,"anim_shoot1_end")); animGet (mhud_attack2_e,pSettings->r_string(*hud_sect,"anim_shoot2_end")); HUD_SOUND::LoadSound(section,"snd_shoot" , m_sndShot , ESoundTypes(SOUND_TYPE_WEAPON_SHOOTING) ); knife_material_idx = GMLib.GetMaterialIdx(KNIFE_MATERIAL_NAME); } void CWeaponKnife::OnStateSwitch (u32 S) { inherited::OnStateSwitch(S); switch (S) { case eIdle: switch2_Idle (); break; case eShowing: switch2_Showing (); break; case eHiding: switch2_Hiding (); break; case eHidden: switch2_Hidden (); break; case eFire: { //------------------------------------------- m_eHitType = m_eHitType_1; fHitPower = fHitPower_1; fHitImpulse = fHitImpulse_1; //------------------------------------------- switch2_Attacking (S); }break; case eFire2: { //------------------------------------------- m_eHitType = m_eHitType_2; fHitPower = fHitPower_2; fHitImpulse = fHitImpulse_2; //------------------------------------------- switch2_Attacking (S); }break; } } void CWeaponKnife::KnifeStrike(const Fvector& pos, const Fvector& dir) { CCartridge cartridge; cartridge.m_buckShot = 1; cartridge.m_impair = 1; cartridge.m_kDisp = 1; cartridge.m_kHit = 1; cartridge.m_kImpulse = 1; cartridge.m_kPierce = 1; cartridge.m_flags.set (CCartridge::cfTracer, FALSE); cartridge.m_flags.set (CCartridge::cfRicochet, FALSE); cartridge.fWallmarkSize = fWallmarkSize; cartridge.bullet_material_idx = knife_material_idx; while(m_magazine.size() < 2) m_magazine.push_back(cartridge); iAmmoElapsed = m_magazine.size(); bool SendHit = SendHitAllowed(H_Parent()); PlaySound (m_sndShot,pos); Level().BulletManager().AddBullet( pos, dir, m_fStartBulletSpeed, fHitPower, fHitImpulse, H_Parent()->ID(), ID(), m_eHitType, fireDistance, cartridge, SendHit); } void CWeaponKnife::OnAnimationEnd(u32 state) { switch (state) { case eHiding: SwitchState(eHidden); break; case eFire: case eFire2: { if(m_attackStart) { m_attackStart = false; if(GetState()==eFire) m_pHUD->animPlay(random_anim(mhud_attack_e), TRUE, this, GetState()); else m_pHUD->animPlay(random_anim(mhud_attack2_e), TRUE, this, GetState()); Fvector p1, d; p1.set(get_LastFP()); d.set(get_LastFD()); if(H_Parent()) smart_cast<CEntity*>(H_Parent())->g_fireParams(this, p1,d); else break; KnifeStrike(p1,d); } else SwitchState(eIdle); }break; case eShowing: case eIdle: SwitchState(eIdle); break; } } void CWeaponKnife::state_Attacking (float) { } void CWeaponKnife::switch2_Attacking (u32 state) { if(m_bPending) return; if(state==eFire) m_pHUD->animPlay(random_anim(mhud_attack), FALSE, this, state); else //eFire2 m_pHUD->animPlay(random_anim(mhud_attack2), FALSE, this, state); m_attackStart = true; m_bPending = true; } void CWeaponKnife::switch2_Idle () { VERIFY(GetState()==eIdle); m_pHUD->animPlay(random_anim(mhud_idle), TRUE, this, GetState()); m_bPending = false; } void CWeaponKnife::switch2_Hiding () { FireEnd (); VERIFY(GetState()==eHiding); m_pHUD->animPlay (random_anim(mhud_hide), TRUE, this, GetState()); // m_bPending = true; } void CWeaponKnife::switch2_Hidden() { signal_HideComplete (); } void CWeaponKnife::switch2_Showing () { VERIFY(GetState()==eShowing); m_pHUD->animPlay (random_anim(mhud_show), FALSE, this, GetState()); // m_bPending = true; } void CWeaponKnife::FireStart() { inherited::FireStart(); SwitchState (eFire); } void CWeaponKnife::Fire2Start () { inherited::Fire2Start(); SwitchState(eFire2); } bool CWeaponKnife::Action(s32 cmd, u32 flags) { if(inherited::Action(cmd, flags)) return true; switch(cmd) { case kWPN_ZOOM : if(flags&CMD_START) Fire2Start(); else Fire2End(); return true; } return false; } void CWeaponKnife::LoadFireParams(LPCSTR section, LPCSTR prefix) { inherited::LoadFireParams(section, prefix); string256 full_name; fHitPower_1 = fHitPower; fHitImpulse_1 = fHitImpulse; m_eHitType_1 = ALife::g_tfString2HitType(pSettings->r_string(section, "hit_type")); fHitPower_2 = pSettings->r_float (section,strconcat(full_name, prefix, "hit_power_2")); fHitImpulse_2 = pSettings->r_float (section,strconcat(full_name, prefix, "hit_impulse_2")); m_eHitType_2 = ALife::g_tfString2HitType(pSettings->r_string(section, "hit_type_2")); } void CWeaponKnife::StartIdleAnim() { m_pHUD->animDisplay(mhud_idle[Random.randI(mhud_idle.size())], TRUE); } void CWeaponKnife::GetBriefInfo(xr_string& str_name, xr_string& icon_sect_name, xr_string& str_count) { str_name = NameShort(); str_count = ""; icon_sect_name = *cNameSect(); } #include "script_space.h" using namespace luabind; #pragma optimize("s",on) void CWeaponKnife::script_register (lua_State *L) { module(L) [ class_<CWeaponKnife,CGameObject>("CWeaponKnife") .def(constructor<>()) ]; }
24.209559
102
0.646773
ixray-team
36bcb60be3238f2450f2728f16905b857754c02b
31,539
cpp
C++
examples/Chapter-16/Chapter-16.cpp
kamarianakis/glGA-edu
17f0b33c3ea8efcfa8be01d41343862ea4e6fae0
[ "BSD-4-Clause-UC" ]
4
2018-08-22T03:43:30.000Z
2021-03-11T18:20:27.000Z
examples/Chapter-16/Chapter-16.cpp
kamarianakis/glGA-edu
17f0b33c3ea8efcfa8be01d41343862ea4e6fae0
[ "BSD-4-Clause-UC" ]
7
2020-10-06T16:34:12.000Z
2020-12-06T17:29:22.000Z
examples/Chapter-16/Chapter-16.cpp
kamarianakis/glGA-edu
17f0b33c3ea8efcfa8be01d41343862ea4e6fae0
[ "BSD-4-Clause-UC" ]
71
2015-03-26T10:28:04.000Z
2021-11-07T10:09:12.000Z
// basic STL streams #include <iostream> #include <sstream> // GLEW lib // http://glew.sourceforge.net/basic.html #include <GL/glew.h> // Update 05/08/16 #include <SDL2/SDL.h> #include <SDL2/SDL_opengl.h> #include <ImGUI/imgui.h> #include <ImGUI/imgui_impl_sdl.h> #include <ImGUI/imgui_impl_opengl3.h> // Here we decide which of the two versions we want to use // If your systems supports both, choose to uncomment USE_OPENGL32 // otherwise choose to uncomment USE_OPENGL21 // GLView cna also help you decide before running this program: // // FOR MACOSX only, please use OPENGL32 for AntTweakBar to work properly // #define USE_OPENGL32 #include <glGA/glGARigMesh.h> // GLM lib // http://glm.g-truc.net/api/modules.html #define GLM_SWIZZLE #define GLM_FORCE_INLINE #include <glm/glm.hpp> #include <glm/gtx/string_cast.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/quaternion.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtc/random.hpp> #include <fstream> //local #include "glGA/glGAHelper.h" #include "glGA/glGAMesh.h" // number of Squares for Plane #define NumOfSQ 20 // update globals SDL_Window *gWindow = NULL; SDL_GLContext gContext; float bgColor[] = { 0.0f, 0.0f, 0.0f, 0.1f }; double FPS; // global variables int windowWidth=1024, windowHeight=768; GLuint programPlane, programPS; GLuint vao, vaoPlane, vaoPS; GLuint bufferPlane, bufferPS; GLuint MV_uniformPlane , MVP_uniformPlane , Normal_uniformPlane; GLuint MV_uniform3D , MVP_uniformPS , Normal_uniform3D; GLuint TextureMatrix_Uniform; int timesc = 0; GLuint gSampler1,gSampler; Texture *pTexture = NULL; Mesh *m = NULL; const int NumVerticesSQ = ( (NumOfSQ) * (NumOfSQ)) * (2) * (3) + (1); const int NumVerticesCube = 36; //(6 faces)(2 triangles/face)(3 vertices/triangle) bool wireFrame = false; bool camera = false; bool SYNC = true; typedef glm::vec4 color4; typedef glm::vec4 point4; int IndexSQ = 0,IndexSQ1 = 0,IndexCube = 0; //Modelling arrays point4 pointsq[NumVerticesSQ]; color4 colorsq[NumVerticesSQ]; glm::vec3 normalsq[NumVerticesSQ]; glm::vec4 tex_coords[NumVerticesSQ]; glm::vec3 pos = glm::vec3( 0.0f, 0.0f , 30.0f ); float horizAngle = 3.14f; float verticAngle = 0.0f; float speedo = 3.0f; float mouseSpeedo = 0.005f; int xpos = 0,ypos = 0; float zNear; float zFar; float FOV; float initialFoV = 45.0f; int divideFactor = 2; float m10 = -15.0f,m101 = -15.0f; int go2 = 0; // Scene orientation (stored as a quaternion) float Rotation[] = { 0.0f, 0.0f, 0.0f, 1.0f }; //Plane point4 planeVertices[NumVerticesSQ]; color4 planeColor[NumVerticesSQ]; // Update function prototypes bool initSDL(); bool event_handler(SDL_Event* event); void close(); void resize_window(int width, int height); bool initImGui(); void displayGui(); // Update functions bool initSDL() { //Init flag bool success = true; //Basic Setup if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) != 0) { std::cout << "SDL could not initialize! SDL Error: " << SDL_GetError() << std::endl; success = false; } else { std::cout << std::endl << "Yay! Initialized SDL succesfully!" << std::endl; //Use OpenGL Core 3.2 SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); //SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 16); #ifdef __APPLE__ SDL_SetHint(SDL_HINT_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK, "1"); #endif //Create Window SDL_DisplayMode current; SDL_GetCurrentDisplayMode(0, &current); #ifdef __APPLE__ gWindow = SDL_CreateWindow("Chapter16", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, windowWidth, windowHeight, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI ); divideFactor = 4; #else gWindow = SDL_CreateWindow("Chapter16", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, windowWidth, windowHeight, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE); #endif if (gWindow == NULL) { std::cout << "Window could not be created! SDL Error: " << SDL_GetError() << std::endl; success = false; } else { std::cout << std::endl << "Yay! Created window sucessfully!" << std::endl << std::endl; //Create context gContext = SDL_GL_CreateContext(gWindow); if (gContext == NULL) { std::cout << "OpenGL context could not be created! SDL Error: " << SDL_GetError() << std::endl; success = false; } else { //Initialize GLEW glewExperimental = GL_TRUE; GLenum glewError = glewInit(); if (glewError != GLEW_OK) { std::cout << "Error initializing GLEW! " << glewGetErrorString(glewError) << std::endl; } //Use Vsync if (SDL_GL_SetSwapInterval(1) < 0) { std::cout << "Warning: Unable to set Vsync! SDL Error: " << SDL_GetError() << std::endl; } //Initializes ImGui if (!initImGui()) { std::cout << "Error initializing ImGui! " << std::endl; success = false; } //Init glViewport first time; resize_window(windowWidth, windowHeight); } } } return success; } bool event_handler(SDL_Event* event) { switch (event->type) { case SDL_WINDOWEVENT: { if (event->window.event == SDL_WINDOWEVENT_RESIZED) { resize_window(event->window.data1, event->window.data2); } } case SDL_MOUSEWHEEL: { return true; } case SDL_MOUSEBUTTONDOWN: { if (event->button.button == SDL_BUTTON_LEFT) if (event->button.button == SDL_BUTTON_RIGHT) if (event->button.button == SDL_BUTTON_MIDDLE) return true; } case SDL_TEXTINPUT: { return true; } case SDL_KEYDOWN: { if (event->key.keysym.sym == SDLK_w) { if (wireFrame) { wireFrame = false; } else { wireFrame = true; } return true; } if (event->key.keysym.sym == SDLK_SPACE) { if (camera == false) { camera = true; SDL_GetMouseState(&xpos, &ypos); SDL_WarpMouseInWindow(gWindow, windowWidth / divideFactor, windowHeight / divideFactor); SDL_ShowCursor(0); } else { camera = false; SDL_GetMouseState(&xpos, &ypos); SDL_WarpMouseInWindow(gWindow, windowWidth / divideFactor, windowHeight / divideFactor); SDL_ShowCursor(1); } return true; } return true; } case SDL_KEYUP: { return true; } case SDL_MOUSEMOTION: { return true; } } return false; } void close() { //Cleanup ImGui_ImplOpenGL3_Shutdown(); ImGui_ImplSDL2_Shutdown(); ImGui::DestroyContext(); SDL_GL_DeleteContext(gContext); SDL_DestroyWindow(gWindow); SDL_Quit(); } void resize_window(int width, int height) { // Set OpenGL viewport and default camera glViewport(0, 0, width, height); float aspect = (GLfloat)width / (GLfloat)height; windowWidth = width; windowHeight = height; } bool initImGui() { // Setup ImGui binding IMGUI_CHECKVERSION(); ImGui::SetCurrentContext(ImGui::CreateContext()); // Setup ImGui binding if (!ImGui_ImplOpenGL3_Init("#version 150")) { return false; } if (!ImGui_ImplSDL2_InitForOpenGL(gWindow, gContext)) { return false; } // Load Fonts // (there is a default font, this is only if you want to change it. see extra_fonts/README.txt for more details) // Marios -> in order to use custom Fonts, //there is a file named extra_fonts inside /_thirdPartyLibs/include/ImGUI/extra_fonts //Uncomment the next line -> ImGui::GetIO() and one of the others -> io.Fonts->AddFontFromFileTTF("", 15.0f). //Important : Make sure to check the first parameter is the correct file path of the .ttf or you get an assertion. //ImGuiIO& io = ImGui::GetIO(); //io.Fonts->AddFontDefault(); //io.Fonts->AddFontFromFileTTF("../../_thirdPartyLibs/include/ImGUI/extra_fonts/Karla-Regular.ttf", 14.0f); //io.Fonts->AddFontFromFileTTF("../../extra_fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyClean.ttf", 13.0f); //io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyTiny.ttf", 10.0f); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); return true; } void displayGui(){ ImGui::Begin("Main Editor"); ImGui::SetWindowSize(ImVec2(200, 200), ImGuiSetCond_Once); ImGui::SetWindowPos(ImVec2(10, 10), ImGuiSetCond_Once); static bool checkbox = false; if (ImGui::Checkbox("Wireframe", &checkbox)) { if (checkbox) wireFrame = true; else wireFrame = false; } ImGui::Separator(); ImGui::ColorEdit3("bgColor", bgColor); ImGui::Separator(); if (ImGui::TreeNode("Scene Rotation")) { ImGui::InputFloat4("SceneRotation", (float*)&Rotation, 2); ImGui::Separator(); ImGui::SliderFloat("X", (float*)&Rotation[0], -1.0f, 1.0f, "%.2f"); ImGui::SliderFloat("Y", (float*)&Rotation[1], -1.0f, 1.0f, "%.2f"); ImGui::SliderFloat("Z", (float*)&Rotation[2], -1.0f, 1.0f, "%.2f"); ImGui::SliderFloat("W", (float*)&Rotation[3], -1.0f, 1.0f, "%.2f"); ImGui::TreePop(); } ImGui::Separator(); if (ImGui::Button("Reset View", ImVec2(100, 20))) { Rotation[0] = 0.0f; Rotation[1] = 0.0f; Rotation[2] = 0.0f; Rotation[3] = 1.0f; pos = glm::vec3(5.0f, 3.0f, 18.0f); zNear = 0.1f; zFar = 100.0f; FOV = 45.0f; horizAngle = 3.14f; verticAngle = 0.0f; } ImGui::Separator(); if (ImGui::TreeNode("Projection Properties")) { ImGui::SliderFloat("Near Clip Plane", &zNear, 0.5, 100.0, "%.2f"); ImGui::Separator(); ImGui::SliderFloat("Far Clip Plane", &zFar, 0.5, 1000.0, "%.2f"); ImGui::Separator(); ImGui::SliderFloat("Field of View", &FOV, 0.0f, 100.0f, "%.2f"); ImGui::TreePop(); } ImGui::Separator(); if (ImGui::TreeNode("Frame Rate")) { ImGui::BulletText("MS per 1 Frame %.2f", FPS); ImGui::NewLine(); ImGui::BulletText("Frames Per Second %.2f", ImGui::GetIO().Framerate); ImGui::NewLine(); ImGui::BulletText("vSYNC %d", SYNC); ImGui::TreePop(); } ImGui::End(); } #if !defined(__APPLE__) /*void setVSync(bool sync) { // Function pointer for the wgl extention function we need to enable/disable // vsync typedef BOOL (APIENTRY *PFNWGLSWAPINTERVALPROC)( int ); PFNWGLSWAPINTERVALPROC wglSwapIntervalEXT = 0; //const char *extensions = (char*)glGetString( GL_EXTENSIONS ); //if( strstr( extensions, "WGL_EXT_swap_control" ) == 0 ) //if(glewIsSupported("WGL_EXT_swap_control")) //{ // std::cout<<"\nWGL_EXT_swap_control Extension is not supported.\n"; // return; //} //else //{ wglSwapIntervalEXT = (PFNWGLSWAPINTERVALPROC)wglGetProcAddress( "wglSwapIntervalEXT" ); if( wglSwapIntervalEXT ) wglSwapIntervalEXT(sync); std::cout<<"\nDONE :: "<<sync<<"\n"; //} }*/ #endif static GLint arrayWidth, arrayHeight; static GLfloat *verts = NULL; static GLfloat *colors = NULL; static GLfloat *velocities = NULL; static GLfloat *startTimes = NULL; GLfloat Time = 0.0f,Time1 = 0.0f; glm::vec4 Background = glm::vec4(0.0,0.0,0.0,1.0); // Routine to convert a quaternion to a 4x4 matrix glm::mat4 ConvertQuaternionToMatrix(float *quat,glm::mat4 &mat) { float yy2 = 2.0f * quat[1] * quat[1]; float xy2 = 2.0f * quat[0] * quat[1]; float xz2 = 2.0f * quat[0] * quat[2]; float yz2 = 2.0f * quat[1] * quat[2]; float zz2 = 2.0f * quat[2] * quat[2]; float wz2 = 2.0f * quat[3] * quat[2]; float wy2 = 2.0f * quat[3] * quat[1]; float wx2 = 2.0f * quat[3] * quat[0]; float xx2 = 2.0f * quat[0] * quat[0]; mat[0][0] = - yy2 - zz2 + 1.0f; mat[0][1] = xy2 + wz2; mat[0][2] = xz2 - wy2; mat[0][3] = 0; mat[1][0] = xy2 - wz2; mat[1][1] = - xx2 - zz2 + 1.0f; mat[1][2] = yz2 + wx2; mat[1][3] = 0; mat[2][0] = xz2 + wy2; mat[2][1] = yz2 - wx2; mat[2][2] = - xx2 - yy2 + 1.0f; mat[2][3] = 0; mat[3][0] = mat[3][1] = mat[3][2] = 0; mat[3][3] = 1; return mat; } float ax = (0.0f/NumOfSQ),ay = (0.0f/NumOfSQ); // { 0.0 , 0.0 } float bx = (0.0f/NumOfSQ),by = (1.0f/NumOfSQ); // { 0.0 , 1.0 } float cx = (1.0f/NumOfSQ),cy = (1.0f/NumOfSQ); // { 1.0 , 1.0 } float dx = (1.0f/NumOfSQ),dy = (0.0f/NumOfSQ); // { 1.0 , 0.0 } int counter2 = 0,counter3 = 1; void quadSQ( int a, int b, int c, int d ) { // 0, 3, 2, 1 //specify temporary vectors along each quad's edge in order to compute the face // normal using the cross product rule glm::vec3 u = (planeVertices[b]-planeVertices[a]).xyz(); glm::vec3 v = (planeVertices[c]-planeVertices[b]).xyz(); glm::vec3 norm = glm::cross(u, v); glm::vec3 normal= glm::normalize(norm); normalsq[IndexSQ]=normal;colorsq[IndexSQ] = planeColor[a]; pointsq[IndexSQ] = planeVertices[a];IndexSQ++; normalsq[IndexSQ]=normal;colorsq[IndexSQ] = planeColor[b]; pointsq[IndexSQ] = planeVertices[b];IndexSQ++; normalsq[IndexSQ]=normal;colorsq[IndexSQ] = planeColor[c]; pointsq[IndexSQ] = planeVertices[c];IndexSQ++; normalsq[IndexSQ]=normal;colorsq[IndexSQ] = planeColor[a]; pointsq[IndexSQ] = planeVertices[a];IndexSQ++; normalsq[IndexSQ]=normal;colorsq[IndexSQ] = planeColor[c]; pointsq[IndexSQ] = planeVertices[c];IndexSQ++; normalsq[IndexSQ]=normal;colorsq[IndexSQ] = planeColor[d]; pointsq[IndexSQ] = planeVertices[d];IndexSQ++; // Texture Coordinate Generation for the Plane if(counter2 != NumOfSQ) { tex_coords[IndexSQ1] = glm::vec4((bx) + (counter2 * (1.0/NumOfSQ)),(by),0.0,0.0);IndexSQ1++; // { 0.0 , 1.0 } tex_coords[IndexSQ1] = glm::vec4((cx) + (counter2 * (1.0/NumOfSQ)),(cy),0.0,0.0);IndexSQ1++; // { 1.0 , 1.0 } tex_coords[IndexSQ1] = glm::vec4((dx) + (counter2 * (1.0/NumOfSQ)),(dy),0.0,0.0);IndexSQ1++; // { 1.0 , 0.0 } tex_coords[IndexSQ1] = glm::vec4((bx) + (counter2 * (1.0/NumOfSQ)),(by),0.0,0.0);IndexSQ1++; // { 0.0 , 1.0 } tex_coords[IndexSQ1] = glm::vec4((dx) + (counter2 * (1.0/NumOfSQ)),(dy),0.0,0.0);IndexSQ1++; // { 1.0 , 0.0 } tex_coords[IndexSQ1] = glm::vec4((ax) + (counter2 * (1.0/NumOfSQ)),(ay),0.0,0.0);IndexSQ1++; // { 0.0 , 0.0 } counter2++; } else { ax = (ax);ay = (ay) + (counter3 * (1.0/NumOfSQ)); // { 0.0 , 0.0 } bx = (bx);by = (by) + (counter3 * (1.0/NumOfSQ)); // { 0.0 , 1.0 } cx = (cx);cy = (cy) + (counter3 * (1.0/NumOfSQ)); // { 1.0 , 1.0 } dx = (dx);dy = (dy) + (counter3 * (1.0/NumOfSQ)); // { 1.0 , 0.0 } tex_coords[IndexSQ1] = glm::vec4(bx,by,0.0,0.0);IndexSQ1++; tex_coords[IndexSQ1] = glm::vec4(cx,cy,0.0,0.0);IndexSQ1++; tex_coords[IndexSQ1] = glm::vec4(dx,dy,0.0,0.0);IndexSQ1++; tex_coords[IndexSQ1] = glm::vec4(bx,by,0.0,0.0);IndexSQ1++; tex_coords[IndexSQ1] = glm::vec4(dx,dy,0.0,0.0);IndexSQ1++; tex_coords[IndexSQ1] = glm::vec4(ax,ay,0.0,0.0);IndexSQ1++; counter2 = 1; } } void initPlane() { float numX = 0.0f,numX1 = 0.5f; float numZ = 0.0f,numZ1 = 0.5f; planeVertices[0] = point4 ( numX, 0.0, numZ1, 1.0); planeColor[0] = color4 (0.603922, 0.803922, 0.196078, 1.0); // 0 a planeVertices[1] = point4 ( numX, 0.0, numZ, 1.0); planeColor[1] = color4 (0.603922, 0.803922, 0.196078, 1.0); // 1 d planeVertices[2] = point4 ( numX1, 0.0, numZ, 1.0); planeColor[2] = color4 (0.603922, 0.803922, 0.196078, 1.0); // 2 c planeVertices[3] = point4 ( numX1, 0.0, numZ1, 1.0); planeColor[3] = color4 (0.603922, 0.803922, 0.196078, 1.0); // 3 b int k = 4; int counter = 0; for(k=4;k<NumVerticesSQ;k=k+4) { numX+=0.5f; numX1+=0.5f; counter++; planeVertices[k] = point4 (numX, 0.0, numZ1, 1.0); planeColor[k] = color4 (0.603922, 0.803922, 0.196078, 1.0); planeVertices[k+1] = point4 (numX, 0.0, numZ, 1.0); planeColor[k+1] = color4 (0.603922, 0.803922, 0.196078, 1.0); planeVertices[k+2] = point4 (numX1, 0.0, numZ, 1.0); planeColor[k+2] = color4 (0.603922, 0.803922, 0.196078, 1.0); planeVertices[k+3] = point4 (numX1, 0.0, numZ1, 1.0); planeColor[k+3] = color4 (0.603922, 0.803922, 0.196078, 1.0); if( counter == (NumOfSQ - 1) ) { numX = 0.0f;numX1 = 0.5f;k+=4; counter = 0; numZ+=0.5f;numZ1+=0.5f; planeVertices[k] = point4 (numX, 0.0, numZ1, 1.0); planeColor[k] = color4 (0.603922, 0.803922, 0.196078, 1.0); planeVertices[k+1] = point4 (numX, 0.0, numZ, 1.0); planeColor[k+1] = color4 (0.603922, 0.803922, 0.196078, 1.0); planeVertices[k+2] = point4 (numX1, 0.0, numZ, 1.0); planeColor[k+2] = color4 (0.603922, 0.803922, 0.196078, 1.0); planeVertices[k+3] = point4 (numX1, 0.0, numZ1, 1.0); planeColor[k+3] = color4 (0.603922, 0.803922, 0.196078, 1.0); } } //generate and bind a VAO for the 3D axes glGenVertexArrays(1, &vaoPlane); glBindVertexArray(vaoPlane); pTexture = new Texture(GL_TEXTURE_2D,"./Textures/nvidia_logo.jpg"); //pTexture = new Texture(GL_TEXTURE_2D,"./Textures/NVIDIA.jpg"); if (!pTexture->loadTexture()) { exit(EXIT_FAILURE); } int lp = 0,a,b,c,d; a=0,b=3,c=2,d=1; for(lp = 0;lp < (NumOfSQ * NumOfSQ);lp++) { quadSQ(a,b,c,d); a+=4;b+=4;c+=4;d+=4; } // Load shaders and use the resulting shader program programPlane = LoadShaders( "./Shaders/vPlaneShader.vert", "./Shaders/fPlaneShader.frag" ); glUseProgram( programPlane ); // Create and initialize a buffer object on the server side (GPU) //GLuint buffer; glGenBuffers( 1, &bufferPlane ); glBindBuffer( GL_ARRAY_BUFFER, bufferPlane ); glBufferData( GL_ARRAY_BUFFER, sizeof(pointsq) + sizeof(colorsq) + sizeof(normalsq) + sizeof(tex_coords),NULL, GL_STATIC_DRAW ); glBufferSubData( GL_ARRAY_BUFFER, 0, sizeof(pointsq), pointsq ); glBufferSubData( GL_ARRAY_BUFFER, sizeof(pointsq), sizeof(colorsq), colorsq ); glBufferSubData( GL_ARRAY_BUFFER,sizeof(pointsq) + sizeof(colorsq),sizeof(normalsq),normalsq ); glBufferSubData( GL_ARRAY_BUFFER, sizeof(pointsq) + sizeof(colorsq) + sizeof(normalsq) ,sizeof(tex_coords) , tex_coords ); // set up vertex arrays GLuint vPosition = glGetAttribLocation( programPlane, "MCvertex" ); glEnableVertexAttribArray( vPosition ); glVertexAttribPointer( vPosition, 4, GL_FLOAT, GL_FALSE, 0,BUFFER_OFFSET(0) ); GLuint vColor = glGetAttribLocation( programPlane, "vColor" ); glEnableVertexAttribArray( vColor ); glVertexAttribPointer( vColor, 4, GL_FLOAT, GL_FALSE, 0,BUFFER_OFFSET(sizeof(pointsq)) ); GLuint vNormal = glGetAttribLocation( programPlane, "vNormal" ); glEnableVertexAttribArray( vNormal ); glVertexAttribPointer( vNormal, 3, GL_FLOAT, GL_FALSE, 0,BUFFER_OFFSET(sizeof(pointsq) + sizeof(colorsq)) ); GLuint vText = glGetAttribLocation( programPlane, "MultiTexCoord0" ); glEnableVertexAttribArray( vText ); glVertexAttribPointer( vText, 4, GL_FLOAT, GL_FALSE, 0,BUFFER_OFFSET(sizeof(pointsq) + sizeof(colorsq) + sizeof(normalsq)) ); glEnable( GL_DEPTH_TEST ); glClearColor( 0.0, 0.0, 0.0, 1.0 ); // only one VAO can be bound at a time, so disable it to avoid altering it accidentally //glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); } void initParticleSystem() { m = new Mesh(); m->loadMesh("./Models/sphere.dae"); float *speed = NULL; float *lifetime = NULL; speed = (float *)malloc(m->numIndices * sizeof(float)); lifetime = (float *)malloc(m->numIndices * sizeof(float)); for(int i = 0; i < m->numIndices ; i++) { speed[i] = ((float)rand() / RAND_MAX ) / 10; lifetime[i] = 75.0 + (float)rand()/((float)RAND_MAX/(120.0-75.0)); } //generate and bind a VAO for the 3D axes glGenVertexArrays(1, &vaoPS); glBindVertexArray(vaoPS); // Load shaders and use the resulting shader program programPS = LoadShaders( "./Shaders/vParticleShader.vert", "./Shaders/fParticleShader.frag" ); glUseProgram( programPS ); // Create and initialize a buffer object on the server side (GPU) //GLuint buffer; glGenBuffers( 1, &bufferPS ); glBindBuffer( GL_ARRAY_BUFFER, bufferPS ); glBufferData( GL_ARRAY_BUFFER, (sizeof(m->Positions[0]) * m->Positions.size()) + (sizeof(m->Normals[0]) * m->Normals.size()) + 2*(m->numIndices * sizeof(float)),NULL, GL_STATIC_DRAW ); glBufferSubData( GL_ARRAY_BUFFER, 0, (sizeof(m->Positions[0]) * m->Positions.size()), &m->Positions[0] ); glBufferSubData( GL_ARRAY_BUFFER, (sizeof(m->Positions[0]) * m->Positions.size()),(sizeof(m->Normals[0]) * m->Normals.size()),&m->Normals[0] ); glBufferSubData( GL_ARRAY_BUFFER, (sizeof(m->Positions[0]) * m->Positions.size()) + (sizeof(m->Normals[0]) * m->Normals.size()),(m->numIndices * sizeof(float)),speed); glBufferSubData( GL_ARRAY_BUFFER, (sizeof(m->Positions[0]) * m->Positions.size()) + (sizeof(m->Normals[0]) * m->Normals.size()) + (m->numIndices * sizeof(float)),(m->numIndices * sizeof(float)),lifetime); // set up vertex arrays GLuint vPosition = glGetAttribLocation( programPS, "MCVertex" ); glEnableVertexAttribArray( vPosition ); glVertexAttribPointer( vPosition, 3, GL_FLOAT, GL_FALSE, 0,BUFFER_OFFSET(0) ); GLuint vVelocity = glGetAttribLocation( programPS, "Velocity" ); glEnableVertexAttribArray( vVelocity ); glVertexAttribPointer( vVelocity, 3, GL_FLOAT, GL_FALSE, 0,BUFFER_OFFSET((sizeof(m->Positions[0]) * m->Positions.size())) ); GLuint vSpeed = glGetAttribLocation( programPS, "Speed" ); glEnableVertexAttribArray( vSpeed ); glVertexAttribPointer( vSpeed, 1, GL_FLOAT, GL_FALSE, 0,BUFFER_OFFSET((sizeof(m->Positions[0]) * m->Positions.size()) + (sizeof(m->Normals[0]) * m->Normals.size())) ); GLuint vLifeTime = glGetAttribLocation( programPS, "LifeTime" ); glEnableVertexAttribArray( vLifeTime ); glVertexAttribPointer( vLifeTime, 1, GL_FLOAT, GL_FALSE, 0,BUFFER_OFFSET((sizeof(m->Positions[0]) * m->Positions.size()) + (sizeof(m->Normals[0]) * m->Normals.size()) + (m->numIndices * sizeof(float))) ); glEnable( GL_DEPTH_TEST ); glClearColor( 0.0, 0.0, 0.0, 1.0 ); // only one VAO can be bound at a time, so disable it to avoid altering it accidentally //glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); } void checkActiveUniforms() { GLint nUniforms, maxLen; glGetProgramiv( programPS, GL_ACTIVE_UNIFORM_MAX_LENGTH,&maxLen); glGetProgramiv( programPS, GL_ACTIVE_UNIFORMS,&nUniforms); GLchar * name = (GLchar *) malloc( maxLen ); GLint size, location; GLsizei written; GLenum type; printf(" Location | Name\n"); printf("------------------------------------------------\n"); for( int i = 0; i < nUniforms; ++i ) { glGetActiveUniform( programPS, i, maxLen, &written,&size, &type, name ); location = glGetUniformLocation(programPS, name); printf(" %-8d | %s\n", location, name); } free(name); } void displayPlane(glm::mat4 &md,glm::vec3 positionv,glm::vec3 directionv,glm::vec3 upv) { glUseProgram(programPlane); glBindVertexArray(vaoPlane); glDisable(GL_CULL_FACE); glPushAttrib(GL_ALL_ATTRIB_BITS); if (wireFrame) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); else glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); MV_uniformPlane = glGetUniformLocation(programPlane, "MV_mat"); MVP_uniformPlane = glGetUniformLocation(programPlane, "MVP_mat"); Normal_uniformPlane = glGetUniformLocation(programPlane, "Normal_mat"); TextureMatrix_Uniform = glGetUniformLocation(programPlane, "TextureMatrix"); glm::mat4 TexMat = glm::mat4(); glUniformMatrix4fv(TextureMatrix_Uniform,1,GL_FALSE,glm::value_ptr(TexMat)); // Calculation of ModelView Matrix glm::mat4 model_mat_plane = md; glm::mat4 view_mat_plane = glm::lookAt(positionv,positionv + directionv,upv); glm::mat4 MV_mat_plane = view_mat_plane * model_mat_plane; glUniformMatrix4fv(MV_uniformPlane,1, GL_FALSE, glm::value_ptr(MV_mat_plane)); // Calculation of Normal Matrix glm::mat3 Normal_mat_plane = glm::transpose(glm::inverse(glm::mat3(MV_mat_plane))); glUniformMatrix3fv(Normal_uniformPlane,1, GL_FALSE, glm::value_ptr(Normal_mat_plane)); // Calculation of ModelViewProjection Matrix float aspect_plane = (GLfloat)windowWidth / (GLfloat)windowHeight; glm::mat4 projection_mat_plane = glm::perspective(FOV, aspect_plane,zNear,zFar); glm::mat4 MVP_mat_plane = projection_mat_plane * MV_mat_plane; glUniformMatrix4fv(MVP_uniformPlane, 1, GL_FALSE, glm::value_ptr(MVP_mat_plane)); gSampler = glGetUniformLocationARB(programPlane, "gSampler"); glUniform1iARB(gSampler, 0); pTexture->bindTexture(GL_TEXTURE0); glDrawArrays( GL_TRIANGLES, 0, NumVerticesSQ ); glPopAttrib(); glBindVertexArray(0); //glUseProgram(0); } int flagP = 0,flagP1 = 0; void displayParticleSystem(glm::mat4 &md,glm::vec3 positionv,glm::vec3 directionv,glm::vec3 upv,int firew) { glUseProgram(programPS); glBindVertexArray(vaoPS); glDisable(GL_CULL_FACE); glPushAttrib(GL_ALL_ATTRIB_BITS); glPointSize(1.5); if (wireFrame) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); else glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); MVP_uniformPS = glGetUniformLocation(programPS, "MVPMatrix"); // Calculation of ModelView Matrix glm::mat4 model_matx; if(firew == 1) { model_matx = glm::translate(md,glm::vec3(0.0,m10,0.0)); glUniform1i(glGetUniformLocation(programPS,"firew"),firew); } else { model_matx = glm::translate(md,glm::vec3(-5.0,m101,4.0)); glUniform1i(glGetUniformLocation(programPS,"firew"),firew); } glm::mat4 view_matx = glm::lookAt(positionv,positionv + directionv,upv); glm::mat4 MV_matx = view_matx * model_matx; // Calculation of ModelViewProjection Matrix float aspectx = (GLfloat)windowWidth / (GLfloat)windowHeight; glm::mat4 projection_matx = glm::perspective(45.0f, aspectx,0.1f,100.0f); glm::mat4 MVP_matx = projection_matx * MV_matx; glUniformMatrix4fv(MVP_uniformPS, 1, GL_FALSE, glm::value_ptr(MVP_matx)); glUniform4fv(glGetUniformLocation(programPS,"Background"),1,glm::value_ptr(Background)); if(Time <= 30.009 && Time >= 0) { m10 += 0.1; Time += 0.15f; } else if(Time >= 30.009) { flagP = 1; } if(flagP == 1) { Time += 0.2f; if(Time >= 0.009 && Time <= 4.00) { Time += 0.29f; } else if(Time >= 4.00 && Time <= 9.00) { Time += 0.4f; } } std::cout<<"CurrentTIME: "<<Time<<"\n"; glUniform1f(glGetUniformLocation(programPS,"Time"),Time); if(go2 == 1 && firew == 2) { if(Time1 <= 30.009 && Time1 >= 0) { m101 += 0.1; Time1 += 0.15f; } else if(Time1 >= 30.009) { flagP1 = 1; } if(flagP1 == 1) { Time1 += 0.2f; if(Time1 >= 0.009 && Time1 <= 4.00) { Time1 += 0.29f; } else if(Time1 >= 4.00 && Time1 <= 9.00) { Time1 += 0.4f; } } glUniform1f(glGetUniformLocation(programPS,"Time"),Time1); } glDrawArrays( GL_POINTS, 0, m->numVertices ); glPopAttrib(); glBindVertexArray(0); //glUseProgram(0); } int main (int argc, char * argv[]) { glm::mat4 mat; float axis[] = { 0.7f, 0.7f, 0.7f }; // initial model rotation float angle = 0.8f; double FT = 0; double starting = 0.0; double ending = 0.0; int rate = 0; int fr = 0; zNear = 0.1f; zFar = 100.0f; FOV = 45.0f; // Current time double time = 0; // initialise GLFW int running = GL_TRUE; if (!initSDL()) { exit(EXIT_FAILURE); } std::cout<<"Vendor: "<<glGetString (GL_VENDOR)<<std::endl; std::cout<<"Renderer: "<<glGetString (GL_RENDERER)<<std::endl; std::cout<<"Version: "<<glGetString (GL_VERSION)<<std::endl; std::ostringstream stream1,stream2; stream1 << glGetString(GL_VENDOR); stream2 << glGetString(GL_RENDERER); std::string vendor ="Title : Chapter-16 Vendor : " + stream1.str() + " Renderer : " +stream2.str(); const char *tit = vendor.c_str(); SDL_SetWindowTitle(gWindow, tit); // Enable depth test glEnable(GL_DEPTH_TEST); // Accept fragment if it closer to the camera than the former one glDepthFunc(GL_LESS); initPlane(); //initialize Plane initParticleSystem(); GLfloat rat = 0.001f; if(SYNC == false) { rat = 0.001f; } else { rat = 0.01f; } // Initialize time time = SDL_GetTicks() / 1000.0f; uint32 currentTime; uint32 lastTime = 0U; int Frames = 0; double LT = SDL_GetTicks() / 1000.0f; starting = SDL_GetTicks() / 1000.0f; int play = 0; #if !defined (__APPLE__) if(SDL_GL_SetSwapInterval(1) == 0) SYNC = true; //setVSync(SYNC); #endif FOV = initialFoV; #ifdef __APPLE__ int *w = (int*)malloc(sizeof(int)); int *h = (int*)malloc(sizeof(int)); #endif while (running) { glm::vec3 direction(cos(verticAngle) * sin(horizAngle), sin(verticAngle), cos(verticAngle) * cos(horizAngle)); glm::vec3 right = glm::vec3(sin(horizAngle - 3.14f / 2.0f), 0, cos(horizAngle - 3.14f / 2.0f)); glm::vec3 up = glm::cross(right, direction); currentTime = SDL_GetTicks(); float dTime = float(currentTime - lastTime) / 1000.0f; lastTime = currentTime; SDL_Event event; while (SDL_PollEvent(&event)) { ImGui_ImplSDL2_ProcessEvent(&event); event_handler(&event); if (event.type == SDL_KEYDOWN) { if (event.key.keysym.sym == SDLK_UP) pos += direction * dTime * speedo; if (event.key.keysym.sym == SDLK_DOWN) pos -= direction * dTime * speedo; if (event.key.keysym.sym == SDLK_RIGHT) pos += right * dTime * speedo; if (event.key.keysym.sym == SDLK_LEFT) pos -= right * dTime * speedo; if (event.key.keysym.sym == SDLK_RETURN) { if (play == 0) play = 1; else play = 0; } } if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE) { running = GL_FALSE; } if (event.type == SDL_QUIT) running = GL_FALSE; } ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplSDL2_NewFrame(gWindow); ImGui::NewFrame(); glClear( GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT ); glClearColor( bgColor[0], bgColor[1], bgColor[2], bgColor[3]); //black color if(camera == true) { SDL_GetMouseState(&xpos, &ypos); SDL_WarpMouseInWindow(gWindow, windowWidth / divideFactor, windowHeight / divideFactor); horizAngle += mouseSpeedo * float(windowWidth/divideFactor - xpos ); verticAngle += mouseSpeedo * float( windowHeight/divideFactor - ypos ); } mat = ConvertQuaternionToMatrix(Rotation, mat); if(play == 1) { displayParticleSystem(mat,pos,direction,up,1); if(Time >= 40) { go2 = 1; } if(go2 == 1) { displayParticleSystem(mat,pos,direction,up,2); } if(Time >= 350) { mat = glm::mat4(); flagP = 0; flagP1 = 0; Time=0; Time1=0; go2=0; m10 = -15.0f; m101 = -15.0f; } } fr++; ending = SDL_GetTicks() / 1000.0f; if(ending - starting >= 1) { rate = fr; fr = 0; starting = SDL_GetTicks() / 1000.0f; } double CT = SDL_GetTicks() / 1000.0f; Frames++; if(CT -LT >= 1.0) { FPS = 1000.0 / (double)Frames; Frames = 0; LT += 1.0f; } glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); displayGui(); ImGui::Render(); SDL_GL_MakeCurrent(gWindow, gContext); ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); SDL_GL_SwapWindow(gWindow); #ifdef __APPLE__ if(w!=NULL && h!=NULL){ SDL_GL_GetDrawableSize(gWindow, w, h); resize_window(*w, *h); } #endif } //close OpenGL window and terminate ImGui and SDL2 close(); exit(EXIT_SUCCESS); }
28.724044
208
0.658645
kamarianakis
36bcb83a85750fe14f9e9c24b01732fb4e79ed37
488
cpp
C++
framework/platform/bpl/uci/cfg/bpl_cfg_extra.cpp
ydx-coder/prplMesh
6401b15c31c563f9e00ce6ff1b5513df3d39f157
[ "BSD-2-Clause-Patent" ]
null
null
null
framework/platform/bpl/uci/cfg/bpl_cfg_extra.cpp
ydx-coder/prplMesh
6401b15c31c563f9e00ce6ff1b5513df3d39f157
[ "BSD-2-Clause-Patent" ]
null
null
null
framework/platform/bpl/uci/cfg/bpl_cfg_extra.cpp
ydx-coder/prplMesh
6401b15c31c563f9e00ce6ff1b5513df3d39f157
[ "BSD-2-Clause-Patent" ]
1
2022-02-01T20:52:12.000Z
2022-02-01T20:52:12.000Z
/* SPDX-License-Identifier: BSD-2-Clause-Patent * * Copyright (c) 2016-2019 Intel Corporation * * This code is subject to the terms of the BSD+Patent license. * See LICENSE file for more details. */ #include "../../common/utils/utils.h" #include <bpl/bpl_cfg.h> #include "bpl_cfg_helper.h" #include "bpl_cfg_uci.h" #include "mapf/common/logger.h" namespace beerocks { namespace bpl { int cfg_set_onboarding(int enable) { return 0; } } // namespace bpl } // namespace beerocks
20.333333
63
0.715164
ydx-coder
36bccc26957afceea2334910837427fffb054d04
18
hpp
C++
src/color/LabCH/trait/index/index.hpp
3l0w/color
e42d0933b6b88564807bcd5f49e9c7f66e24990a
[ "Apache-2.0" ]
120
2015-12-31T22:30:14.000Z
2022-03-29T15:08:01.000Z
src/color/LabCH/trait/index/index.hpp
3l0w/color
e42d0933b6b88564807bcd5f49e9c7f66e24990a
[ "Apache-2.0" ]
6
2016-08-22T02:14:56.000Z
2021-11-06T22:39:52.000Z
src/color/LabCH/trait/index/index.hpp
3l0w/color
e42d0933b6b88564807bcd5f49e9c7f66e24990a
[ "Apache-2.0" ]
23
2016-02-03T01:56:26.000Z
2021-09-28T16:36:27.000Z
// Use default !!!
18
18
0.555556
3l0w
36bf61d242ffb5ca97f4578297884555bdbdf857
1,827
cpp
C++
sound/SoundLoader.cpp
mathall/nanaka
0304f444702318a83d221645d4e5f3622082c456
[ "BSD-2-Clause" ]
2
2017-03-31T19:01:22.000Z
2017-05-18T08:14:37.000Z
sound/SoundLoader.cpp
mathall/nanaka
0304f444702318a83d221645d4e5f3622082c456
[ "BSD-2-Clause" ]
null
null
null
sound/SoundLoader.cpp
mathall/nanaka
0304f444702318a83d221645d4e5f3622082c456
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (c) 2013, Mathias Hällman. 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. */ #include "sound/SoundLoader.h" #include "sound/SoundResource.h" std::shared_ptr<Resource> SoundLoader::Load( const ResourceKey& key, const FileManager& fileManager) const { File file; fileManager.Open(key.GetFilePath(), file); SoundFileFormat format = SoundFileFormatUnknown; if (ExtractFileEnding(key.GetFilePath()).compare(".ogg") == 0) { format = SoundFileFormatOGG; } return std::make_shared<SoundResource>(file.ReadAll(), format); }
39.717391
79
0.763547
mathall
36c00318268ef72413a57bb5d1a43004c2df9ed9
1,166
cpp
C++
dynamic_programming/longest_common_subsequence.cpp
ShiyuSky/Algorithms
a2255ae55e0efb248d40ed02f86517252d66b6a3
[ "MIT" ]
null
null
null
dynamic_programming/longest_common_subsequence.cpp
ShiyuSky/Algorithms
a2255ae55e0efb248d40ed02f86517252d66b6a3
[ "MIT" ]
null
null
null
dynamic_programming/longest_common_subsequence.cpp
ShiyuSky/Algorithms
a2255ae55e0efb248d40ed02f86517252d66b6a3
[ "MIT" ]
null
null
null
/* A DP solution for solving LCS problem */ #include "stdafx.h" #include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; void printArray(vector<vector<int>> arr) { for (int i = 0; i < arr.size(); i++) { for (int j = 0; j < arr[i].size(); j++) { cout << arr[i][j] << " "; } cout << endl; } } int findLCS(string s1, string s2) { int m = s1.size(); int n = s2.size(); vector<vector<int>> L(m, vector<int>(n)); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (i == 0 || j == 0) { L[i][j] = (s1[i] == s2[j]) ? 1 : 0; } else if (s1[i] == s2[j]) { L[i][j] = 1 + L[i - 1][j - 1]; } else { L[i][j] = max(L[i - 1][j], L[i][j - 1]); } } //cout << "L" << endl; //printArray(L); } // return last element in L return L[m - 1][n - 1]; } int main() { string s1("AGGTAB"); string s2("GXTXAYB"); int ans = findLCS(s1, s2); cout << ans << endl; std::cin.ignore(); return 0; }
22.862745
56
0.418525
ShiyuSky
36c98c01f0c20fba89bc0feaf240e9a76625de58
625
hpp
C++
math/float-binomial.hpp
NachiaVivias/library
73091ddbb00bc59328509c8f6e662fea2b772994
[ "CC0-1.0" ]
69
2020-11-06T05:21:42.000Z
2022-03-29T03:38:35.000Z
math/float-binomial.hpp
NachiaVivias/library
73091ddbb00bc59328509c8f6e662fea2b772994
[ "CC0-1.0" ]
21
2020-07-25T04:47:12.000Z
2022-02-01T14:39:29.000Z
math/float-binomial.hpp
NachiaVivias/library
73091ddbb00bc59328509c8f6e662fea2b772994
[ "CC0-1.0" ]
9
2020-11-06T11:55:10.000Z
2022-03-20T04:45:31.000Z
#pragma once struct FloatBinomial { vector<long double> f; static constexpr long double LOGZERO = -1e10; FloatBinomial(int MAX) { f.resize(MAX + 1, 0.0); f[0] = 0.0; for (int i = 1; i <= MAX; i++) { f[i] = f[i - 1] + logl(i); } } long double logfac(int n) const { return f[n]; } long double logfinv(int n) const { return -f[n]; } long double logC(int n, int k) const { if (n < k || k < 0 || n < 0) return LOGZERO; return f[n] - f[n - k] - f[k]; } long double logP(int n, int k) const { if (n < k || k < 0 || n < 0) return LOGZERO; return f[n] - f[n - k]; } };
20.833333
52
0.5248
NachiaVivias
36cbdaa2b0d941a4c7ea550331381399cb1cd38b
809
hpp
C++
libmuscle/cpp/src/libmuscle/tests/mocks/mock_post_office.hpp
DongweiYe/muscle3
0c2fcf5f62995b8639fc84ce1b983c8a8e6248d0
[ "Apache-2.0" ]
11
2018-03-12T10:43:46.000Z
2020-06-01T10:58:56.000Z
libmuscle/cpp/src/libmuscle/tests/mocks/mock_post_office.hpp
DongweiYe/muscle3
0c2fcf5f62995b8639fc84ce1b983c8a8e6248d0
[ "Apache-2.0" ]
85
2018-03-03T15:10:56.000Z
2022-03-18T14:05:14.000Z
libmuscle/cpp/src/libmuscle/tests/mocks/mock_post_office.hpp
DongweiYe/muscle3
0c2fcf5f62995b8639fc84ce1b983c8a8e6248d0
[ "Apache-2.0" ]
6
2018-03-12T10:47:11.000Z
2022-02-03T13:44:07.000Z
#pragma once #include <ymmsl/ymmsl.hpp> #include <libmuscle/data.hpp> #include <libmuscle/mcp/message.hpp> #include <libmuscle/outbox.hpp> namespace libmuscle { namespace impl { class MockPostOffice { public: MockPostOffice() = default; bool has_message(ymmsl::Reference const & receiver); std::unique_ptr<DataConstRef> get_message( ymmsl::Reference const & receiver); void deposit( ymmsl::Reference const & receiver, std::unique_ptr<DataConstRef> message); void wait_for_receivers() const; // Mock control variables static void reset(); static ymmsl::Reference last_receiver; static std::unique_ptr<mcp::Message> last_message; }; using PostOffice = MockPostOffice; } }
20.74359
60
0.647713
DongweiYe
36cf1e47419932fcf550e9faa181b2c3cebdc745
2,865
cpp
C++
p16_3Sum_Closest/p16.cpp
Song1996/Leetcode
ecb0a2de67a57b899a12d0cb18272fb37dbf3ceb
[ "MIT" ]
null
null
null
p16_3Sum_Closest/p16.cpp
Song1996/Leetcode
ecb0a2de67a57b899a12d0cb18272fb37dbf3ceb
[ "MIT" ]
null
null
null
p16_3Sum_Closest/p16.cpp
Song1996/Leetcode
ecb0a2de67a57b899a12d0cb18272fb37dbf3ceb
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <map> using namespace std; class VectorTools{ public: void sorted(vector<int>::iterator first, vector<int>::iterator last) { if (first == last || first + 1 == last) return; vector<int>::iterator pivot = first; int temp; for (vector<int>::iterator it = first+1; it != last; it ++) { if (*it<*pivot) { temp = *it; *it = *(pivot+1); *(pivot+1) = *pivot; *pivot = temp; pivot ++; } } sorted(first, pivot); sorted(pivot+1, last); } int binary_search(vector<int>::iterator first, int size, bool have_sorted, int tar) { int l = 0; int r = size - 1; int mid = (l+r)/2; if (size==0) return -1; else if (size==1) return 0; if (!have_sorted) sorted(first, first+size); if (*(first+l)>=tar) return l; if (*(first+r)<=tar) return r; while (l < r - 1) { mid = (l+r)/2; if (*(first+mid) < tar) l = mid; else if (*(first+mid) == tar) { int i = 0; while((mid - i)>=0 && *(first+mid-i) == tar) i ++; return *(first+mid-i)==tar?(mid-i):(mid-i+1); } else r = mid; } return (tar-*(first+l) >= *(first+r) - tar)?r:l; } void vector_display(vector<int>& v) { for (vector<int>:: iterator it = v.begin(); it != v.end(); it ++) { printf("%d ",*it); }printf("\n"); } }; class Solution { public: int threeSumClosest(vector<int>& nums, int target) { int result,temp_result, distance; distance = INT_MAX; if (nums.size()<3) return result; VectorTools V; V.sorted(nums.begin(), nums.end()); for (int i = 0; i < nums.size()-2; i ++) { if(i>0 && nums[i]==nums[i-1]) continue; for (int j = i+1; j < nums.size()-1; j ++) { if(j>i+1 && nums[j] == nums[j-1]) continue; int l,r; l = nums[i]; r = nums[j]; int tar = target - (l + r); temp_result = nums[j+1+V.binary_search(nums.begin()+j+1,nums.size()-j-1,true,tar)]; //printf("%d: %d %d %d\n",tar,l,r,temp_result); temp_result += (l+r); if(abs(temp_result-target)<distance){ result = temp_result; distance = abs(temp_result-target); } } } return result; } }; int main () { int intList[] = {-1, 0, 1, 1, 55}; vector<int> v(intList, intList + sizeof(intList)/sizeof(int)); Solution s; VectorTools V; int result = s.threeSumClosest(v,3); printf("%d\n",result); }
31.483516
99
0.456545
Song1996
36d5c9692803b4dfe7ba391eb9d26a999f31bd75
5,141
cc
C++
Source/BladeDevice/source/graphics/RenderTarget.cc
OscarGame/blade
6987708cb011813eb38e5c262c7a83888635f002
[ "MIT" ]
146
2018-12-03T08:08:17.000Z
2022-03-21T06:04:06.000Z
Source/BladeDevice/source/graphics/RenderTarget.cc
huangx916/blade
3fa398f4d32215bbc7e292d61e38bb92aad1ee1c
[ "MIT" ]
1
2019-01-18T03:35:49.000Z
2019-01-18T03:36:08.000Z
Source/BladeDevice/source/graphics/RenderTarget.cc
huangx916/blade
3fa398f4d32215bbc7e292d61e38bb92aad1ee1c
[ "MIT" ]
31
2018-12-03T10:32:43.000Z
2021-10-04T06:31:44.000Z
/******************************************************************** created: 2010/04/10 filename: RenderTarget.cc author: Crazii purpose: *********************************************************************/ #include <BladePCH.h> #include <graphics/RenderTarget.h> #include <interface/public/graphics/IRenderDevice.h> #include <graphics/Texture.h> namespace Blade { ////////////////////////////////////////////////////////////////////////// RenderTarget::RenderTarget(const TString& name,IRenderDevice* device, size_t viewWidth, size_t viewHeight) :mName(name) ,mDevice(device) ,mListener(NULL) ,mViewWidth(viewWidth) ,mViewHeight(viewHeight) { } ////////////////////////////////////////////////////////////////////////// RenderTarget::~RenderTarget() { } /************************************************************************/ /* IRenderTarget interface */ /************************************************************************/ ////////////////////////////////////////////////////////////////////////// const TString& RenderTarget::getName() const { return mName; } ////////////////////////////////////////////////////////////////////////// const HTEXTURE& RenderTarget::getDepthBuffer() const { return mDepthBuffer; } ////////////////////////////////////////////////////////////////////////// bool RenderTarget::setDepthBuffer(const HTEXTURE& hDethBuffer) { if( hDethBuffer != NULL && !hDethBuffer->getPixelFormat().isDepth() && !hDethBuffer->getPixelFormat().isDepthStencil() ) { assert(false); return false; } mDepthBuffer = hDethBuffer; return true; } ////////////////////////////////////////////////////////////////////////// bool RenderTarget::setColorBuffer(index_t index, const HTEXTURE& buffer) { if( index >= mDevice->getDeviceCaps().mMaxMRT ) { assert(false); return false; } assert( index == 0 || buffer == NULL || buffer->getWidth() == this->getWidth() ); assert( index == 0 || buffer == NULL || buffer->getHeight() == this->getHeight() ); if( index < mOutputBuffers.size() ) mOutputBuffers[index] = buffer; else if( index == mOutputBuffers.size() ) mOutputBuffers.push_back(buffer); else { assert(false); return false; } return true; } ////////////////////////////////////////////////////////////////////////// bool RenderTarget::setColorBufferCount(index_t count) { if( count <= mDevice->getDeviceCaps().mMaxMRT ) { mOutputBuffers.resize(count); return true; } assert(false); return false; } ////////////////////////////////////////////////////////////////////////// const HTEXTURE& RenderTarget::getColorBuffer(index_t index) const { if( index < mOutputBuffers.size() ) return mOutputBuffers[index]; else return HTEXTURE::EMPTY; } ////////////////////////////////////////////////////////////////////////// bool RenderTarget::setViewRect(int32 left, int32 top, int32 width, int32 height) { bool ret = false; for (size_t i = 0; i < mOutputBuffers.size(); ++i) { Texture* tex = static_cast<Texture*>(mOutputBuffers[i]); if (tex != NULL) { scalar fwidth = (scalar)tex->getWidth(); scalar fheight = (scalar)tex->getHeight(); ret |= tex->setViewRect((scalar)left/fwidth, (scalar)top/fheight, std::min<scalar>(1.0f, width / fwidth), std::min<scalar>(1.0f, (scalar)height / fheight)); } } if (mDepthBuffer != NULL) { Texture* tex = static_cast<Texture*>(mDepthBuffer); if (tex != NULL) { scalar fwidth = (scalar)tex->getWidth(); scalar fheight = (scalar)tex->getHeight(); ret |= tex->setViewRect((scalar)left / fwidth, (scalar)top / fheight, std::min<scalar>(1.0f, width / fwidth), std::min<scalar>(1.0f, (scalar)height / fheight)); } } return ret; } ////////////////////////////////////////////////////////////////////////// size_t RenderTarget::getColorBufferCount() const { return mOutputBuffers.size(); } ////////////////////////////////////////////////////////////////////////// RenderTarget::IListener*RenderTarget::setListener(IListener* listener) { IListener* old = mListener; mListener = listener; return old; } RenderTarget::IListener*RenderTarget::getListener() const { return mListener; } ////////////////////////////////////////////////////////////////////////// bool RenderTarget::isReady() const { return this->getColorBuffer(0) != NULL; } ////////////////////////////////////////////////////////////////////////// bool RenderTarget::swapBuffers() { return true; } /************************************************************************/ /* custom methods */ /************************************************************************/ ////////////////////////////////////////////////////////////////////////// void RenderTarget::notifySizeChange(IRenderTarget* target) { if( mListener != NULL ) mListener->onTargetSizeChange(target); } }//namespace Blade
28.72067
164
0.458277
OscarGame
36d6aac80fcc8785b501d16a86751f3957c96025
14,101
cpp
C++
moments/PointCloudIO.cpp
mlangbe/moments
167ab1e77e4e9732396418f38dfec0bad75724ac
[ "MTLL" ]
null
null
null
moments/PointCloudIO.cpp
mlangbe/moments
167ab1e77e4e9732396418f38dfec0bad75724ac
[ "MTLL" ]
null
null
null
moments/PointCloudIO.cpp
mlangbe/moments
167ab1e77e4e9732396418f38dfec0bad75724ac
[ "MTLL" ]
null
null
null
/* I/O of pointclouds to/from different formats This file is part of the source code used for the calculation of the moment invariants as described in the dissertation of Max Langbein https://nbn-resolving.org/urn:nbn:de:hbz:386-kluedo-38558 Copyright (C) 2020 TU Kaiserslautern, Prof.Dr. Hans Hagen (AG Computergraphik und HCI) ([email protected]) Author: Max Langbein ([email protected]) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include<iostream> #include<fstream> #include<cassert> #include<stdlib.h> #include<sys/stat.h> #include<sys/types.h> #include<fcntl.h> #ifndef GNUCC #include<io.h> #else #include<errno.h> #include<unistd.h> #endif #include "PointCloudIO.h" #include "equaldist.h" #include "osgio.h" #ifndef OLD_VC #include<string.h> #include<stdexcept> #define _EXCEPTION_ std::runtime_error #else #define _EXCEPTION_ exception #endif using namespace std; PointCloudIO::PointCloudIO(void) { } PointCloudIO::~PointCloudIO(void) { } bool PointCloudIO::accept(const char *name, const char *format) { if(format) return strcmp(format,this->format())==0; const char*s=strstr(name,ext()); if(!s)return false; if(strlen(s)!=strlen(ext())) return false; return true; } PointCloudIO::Factory* PointCloudIO::instance=0; PointCloudIO* PointCloudIO::Factory::getIO(const char *name, const char *format) { for(int i=0;i<instances.size();++i) if(instances[i]->accept(name,format)) return instances[i]; cerr<<"no appropriate reader or writer for "<<name<<" found"; throw; } //-------------------------------------------------------------------------- //now instances of reader/writers: struct pcio_raw : public PointCloudIO { void read_(vector<mynum> & points ,const char*fname) { struct stat s; if(stat(fname,&s)<0) {throw _EXCEPTION_("couldn't read");} points.resize(s.st_size/sizeof(mynum)); FILE*f=fopen(fname,"rb"); fread(&points[0],sizeof(points[0]),points.size(),f); fclose(f); } void write_(const vector<mynum> & points ,const char*fname) { /* struct stat s; errno=0; int fd=open(fname,O_CREAT|O_RDWR,S_IWRITE|S_IREAD); if(fd<0) { cerr<<"couldn't open "<<fname<<" for writing:errno="<<errno<<endl;throw exception("couldn't write");} else { ::write(fd,&points[0],sizeof(points[0])*points.size()); close(fd); } */ FILE *f=fopen(fname,"wb"); if(f==0) { cerr<<"couldn't open "<<fname<<" for writing:errno="<<errno<<endl;throw _EXCEPTION_("couldn't write");} else { //Achtung: Dateigroesse bei 64-bit-Version ist groesser als die geschriebenen Daten size_t num=fwrite(&points[0],sizeof(points[0]),points.size(),f); fclose(f); } } const char *ext(){return ".raw";} pcio_raw() { reg(); } } pcio_1; struct pcio_rw2 : public PointCloudIO { //typedef unsigned __int64 tlen; typedef u_int64_t tlen; void read_(vector<mynum> & points ,const char*fname) { FILE*f=fopen(fname,"rb"); if(f==0) { cerr<<"could not open "<<fname<<endl; throw _EXCEPTION_("could not read"); } tlen len; tlen x; fread(&x,sizeof(x),1,f); fread(&len,sizeof(len),1,f); if(x!=sizeof(mynum)){ printf("\n%s: number size=%d bytes != read size=%d bytes\n",fname,(int)x,(int)sizeof(mynum)); throw _EXCEPTION_("number format does not match"); } points.resize(len); size_t nread=fread(&points[0],x,len,f); if(nread!=len){ printf("\n%s: length=%d != read=%d \n",fname,(int)len,(int)nread); throw _EXCEPTION_("could not read full length"); } fclose(f); } void write_(const vector<mynum> & points ,const char*fname) { FILE *f=fopen(fname,"wb"); if(f==0) { cerr<<"couldn't open "<<fname<<" for writing:errno="<<errno<<endl;throw _EXCEPTION_("couldn't write");} tlen x=sizeof(mynum); fwrite(&x,sizeof(x),1,f); tlen len=points.size(); fwrite(&len,sizeof(len),1,f); //Achtung: Dateigroesse bei 64-bit-Version ist groesser als die geschriebenen Daten size_t num=fwrite(&points[0],sizeof(points[0]),len,f); fclose(f); } const char *ext(){return ".rw2";} pcio_rw2() { reg(); } } pcio_1_1; struct pcio_asc:public PointCloudIO { void write_(const vector<mynum> & points , const char*fname) { ofstream out(fname); vector<mynum>::const_iterator i; for(i=points.begin();i<points.end();) out <<*(i++)<<' ' <<*(i++)<<' ' <<*(i++)<<endl; } const char*ext(){ return ".asc"; } pcio_asc(){reg();} } pcio_2; struct pcio_gavabvrml:public PointCloudIO { void read_(vector<mynum> & points , const char*fname) { char buf[80]; ifstream in(fname); for(;;){ in.getline(buf,79); if(strstr(buf,"point [")!=0) break; if(in.eof())return; } mynum x,y,z; char cc; in.clear(); points.clear(); for(;;){ in>>x>>y>>z; if(in.fail())break; in>>cc; points.push_back(x); points.push_back(y); points.push_back(z); } in.close(); } const char*ext(){ return ".wrl"; } pcio_gavabvrml(){reg();} } pcio_3; //create the points eually distributed over the surface. struct pcio_gavabvrml_equaldist:public PointCloudIO { void read_(vector<mynum> & points , const char*fname) { equaldist eq; char buf[80]; ifstream in(fname); for(;;){ in.getline(buf,79); if(strstr(buf,"point [")!=0) break; if(in.eof())return; } mynum x,y,z; char cc; in.clear(); eq.points.clear(); for(;;){ in>>x>>y>>z; if(in.fail())break; in>>cc; eq.points.push_back(x); eq.points.push_back(y); eq.points.push_back(z); } vector<int> bufidx; in.clear(); for(;;){ in.getline(buf,79); if(strstr(buf,"coordIndex [")!=0) break; if(in.eof())return; } int vidx; for(;;){ in>>vidx; if(in.fail())break; if(vidx>=0) bufidx.push_back(vidx); else { if(bufidx.size()==3) { eq.tris.resize(eq.tris.size()+3); copy(bufidx.begin(),bufidx.end(),eq.tris.end()-3); bufidx.clear(); } else if(bufidx.size()==4) { eq.quads.resize(eq.quads.size()+4); copy(bufidx.begin(),bufidx.end(),eq.quads.end()-4); bufidx.clear(); } else { eq.polygons.push_back(bufidx); bufidx.clear(); } } in>>cc; } in.close(); eq.createEqualDist(points,eq.points.size()/3); } const char*ext(){ return ".wrl"; } const char*format(){ return "equaldist"; } pcio_gavabvrml_equaldist(){reg();} } pcio_3_1; struct pcio_3drma:public PointCloudIO { void read_(vector<mynum> & points , const char*fname) { ifstream in(fname,ios::binary); points.clear(); short int n; assert(sizeof(short int)==2); assert(strstr(fname,".xyz")!=0); assert(sizeof(mynum)>=2); while(!in.eof()) { n=0; in.read((char*)&n,2); if(n==0)continue; int onpt=points.size(); points.resize(points.size()+n*3); //use output vector as read buffer short int*buf=(short int*)&points[onpt]; in.read((char*)buf,n*3*sizeof(short int)); //assign backwards, so you don't overwrite values that are still to be converted for(int i=n*3-1;i>=0;--i) { points[onpt+i]=buf[i]; } } } void write_(const vector<mynum> & points , const char*fname) { ofstream out(fname,ios::binary); short int n; assert(sizeof(short int)==2); static const int nmax=((1<<15)-1); short int buf[1+3*nmax]; buf[0]=(short int)nmax; vector<mynum>::const_iterator it; for(it=points.begin(); points.end()-it >=nmax*3; ) { short int*pts=buf+1, *ptsend=pts+nmax*3; for(;pts!=ptsend;++pts,++it) *pts=(short int)*it; out.write((const char*)buf,sizeof(buf)); } buf[0] = (short int) ((points.end()-it)/3); for(short int*pts=buf+1;it!=points.end();++pts,++it) *pts=(short int)*it; out.write((const char*)&n,sizeof(n)); out.write((const char*)buf,(int(buf[0])*3+1)*sizeof(buf[0])); } const char*ext(){ return ".xyz"; } pcio_3drma(){reg();} } pcio_4; struct pcio_scandump_denker:public PointCloudIO { void read_(vector<mynum> & points , const char*fname) { ifstream in(fname); if(!in.is_open()) {cout<<"couldn't open"<<fname<<endl; return;} char buf[80]; points.clear(); while(!in.eof()) { buf[0]=0; in.getline(buf,80,'\n'); if('A'<=buf[0] && buf[0] <='Z' || buf[0]==0) continue; size_t ps=points.size(); points.resize(points.size()+3); #ifdef GNUCC const char*formatstr="%Lf,%Lf,%Lf"; #else const char*formatstr="%lf,%lf,%lf"; #endif if( sscanf(buf,formatstr, &points[ps],&points[ps+1],&points[ps+2])!=3 ) {cout<<"sth wrong at pos:"<<ps<<":"<<buf<<endl;} } in.close(); } const char*ext(){return ".dump";} pcio_scandump_denker() {reg();} } pcio_5; /* point cloud from zaman with 4 values per row: x,y,z,intensity */ struct pcio_zaman:public PointCloudIO { void read_(vector<mynum> & points , const char*fname) { ifstream in(fname); if(!in.is_open()) {cout<<"couldn't open"<<fname<<endl; return;} char buf[80]; points.clear(); mynum x,y,z,v; while(!in.eof()) { in>>x>>y>>z>>v; if(in.fail()) break; points.push_back(x); points.push_back(y); points.push_back(z); } in.close(); } const char*ext(){ return ".txt"; } const char*format() {return "xyzi";} pcio_zaman(){reg();} } pcio_6; /* point cloud from zaman with 3 values per row: x,y,z */ struct pcio_csv:public PointCloudIO { void read_(vector<mynum> & points , const char*fname) { ifstream in(fname); if(!in.is_open()) {cout<<"couldn't open"<<fname<<endl; return;} char buf[80]; points.clear(); mynum x,y,z; while(!in.eof()) { in>>x; in.ignore(1,','); in>>y; in.ignore(1,','); in>>z; if(in.fail()) break; points.push_back(x); points.push_back(y); points.push_back(z); } in.close(); } void write_(const vector<mynum> & points , const char*fname) { ofstream out(fname); vector<mynum>::const_iterator it; for(it=points.begin(); it!=points.end(); it+=3 ) { out<<it[0]<<','<<it[1]<<','<<it[2]<<'\n'; } } const char*ext(){ return ".csv"; } pcio_csv(){reg();} } pcio_7; /* point cloud from zaman with 4 values per row: x,y,z,intensity */ struct pcio_csv28:public PointCloudIO { void read_(vector<mynum> & points , const char*fname) { ifstream in(fname); if(!in.is_open()) {cout<<"couldn't open"<<fname<<endl; return;} char buf[80]; points.clear(); mynum x; while(!in.eof()) { in>>x; if(in.fail()) break; in.ignore(1,','); points.push_back(x); } in.close(); } void write_(const vector<mynum> & points , const char*fname,int n) { ofstream out(fname); assert(points.size()%n==0); out.precision(sizeof(mynum)*2); vector<mynum>::const_iterator it; for(it=points.begin(); it!=points.end(); it+=n ) { out<<it[0]; for(int i=1;i<n;++i) out<<','<<it[i]; out<<"\r\n"; } } void write_(const vector<mynum> & points , const char*fname) { write_(points,fname,28); } const char*ext(){ return ".csv"; } const char*format(){ return "csv28"; } pcio_csv28(){reg();} }pcio_8; //create the points eually distributed over the surface. struct pcio_off_equaldist:public PointCloudIO { void read_(vector<mynum> & points , const char*fname) { equaldist eq; char buf[80]; ifstream in(fname); in>>buf; int nverts,nfaces,nedges; in>>nverts>>nfaces>>nedges; mynum x,y,z; char cc; in.clear(); eq.points.clear(); for(int i=0;i<nverts;++i){ in>>x>>y>>z; if(in.fail())break; eq.points.push_back(x); eq.points.push_back(y); eq.points.push_back(z); } in.clear(); int vertsperface; for(int i=0;i<nfaces;++i){ in>>vertsperface; if(vertsperface==3) { int a,b,c; in>>a>>b>>c; eq.tris.push_back(a); eq.tris.push_back(b); eq.tris.push_back(c); } else if(vertsperface==4) { int a,b,c,d; in>>a>>b>>c>>d; eq.tris.push_back(a); eq.tris.push_back(b); eq.tris.push_back(c); eq.tris.push_back(d); } else { eq.polygons.resize(eq.polygons.size()+1); vector<int> &last=eq.polygons.back(); last.resize(vertsperface); for(int i=0;i<vertsperface;++i) { in>>last[i]; } } } in.close(); int npoints=(eq.points.size()/3) *10; if(npoints <1000)npoints= 1000; if(npoints>50000)npoints=50000; eq.createEqualDist(points,npoints); } const char*ext(){ return ".off"; } const char*format(){ return "offequaldist"; } pcio_off_equaldist(){reg();} } pcio_9_1; struct pcio_osg:public PointCloudIO { void read_(vector<mynum> & points , const char*fname) { std::ifstream in(fname); osgreadpoints(points,in); in.close(); } void write_(const vector<mynum> & points , const char*fname) { std::ofstream of(fname); osgpointcloud(of ,points); of.close(); } const char*ext(){ return ".osg"; } pcio_osg(){reg();} } pcio_10; #undef _EXCEPTION_
18.101412
108
0.593575
mlangbe
36d8b3c3a14b9dd41c049f40863c11dad7d88bdf
5,195
cc
C++
slib_physics/source/physx/handler/physx_character_handler.cc
KarlJansson/ecs_game_engine
c76b7379d8ff913cd7773d0a9f55535996abdf35
[ "MIT" ]
1
2018-05-18T10:42:35.000Z
2018-05-18T10:42:35.000Z
slib_physics/source/physx/handler/physx_character_handler.cc
KarlJansson/ecs_game_engine
c76b7379d8ff913cd7773d0a9f55535996abdf35
[ "MIT" ]
null
null
null
slib_physics/source/physx/handler/physx_character_handler.cc
KarlJansson/ecs_game_engine
c76b7379d8ff913cd7773d0a9f55535996abdf35
[ "MIT" ]
null
null
null
#include "physx_character_handler.h" #include "actor.h" #include "camera.h" #include "character.h" #include "entity_manager.h" #include "gui_text.h" #include "transform.h" namespace lib_physics { PhysxCharacterHandler::PhysxCharacterHandler(physx::PxPhysics* phys, physx::PxScene* scene) : physics_(phys) { controller_manager_ = PxCreateControllerManager(*scene); report_callback = std::make_unique<PhysxReportCallback>(); add_callback_ = g_ent_mgr.RegisterAddComponentCallback<Character>( [&](lib_core::Entity ent) { add_character_.push_back(ent); }); remove_callback_ = g_ent_mgr.RegisterRemoveComponentCallback<Character>( [&](lib_core::Entity ent) { remove_character_.push_back(ent); }); } PhysxCharacterHandler::~PhysxCharacterHandler() { controller_manager_->release(); g_ent_mgr.UnregisterAddComponentCallback<Character>(add_callback_); g_ent_mgr.UnregisterRemoveComponentCallback<Character>(remove_callback_); } void PhysxCharacterHandler::UpdateCharacters(float dt) { for (auto& e : add_character_) CreateCharacterController(e); add_character_.clear(); for (auto& e : remove_character_) RemoveCharacterController(e); remove_character_.clear(); auto characters = g_ent_mgr.GetNewCbt<Character>(); if (characters) { float gravity_acc = -9.82f * dt; auto old_characters = g_ent_mgr.GetOldCbt<Character>(); auto char_ents = g_ent_mgr.GetEbt<Character>(); auto char_update = g_ent_mgr.GetNewUbt<Character>(); for (int i = 0; i < char_update->size(); ++i) { if (!(*char_update)[i]) continue; g_ent_mgr.MarkForUpdate<lib_graphics::Camera>(char_ents->at(i)); g_ent_mgr.MarkForUpdate<lib_graphics::Transform>(char_ents->at(i)); auto& c = characters->at(i); auto& old_c = old_characters->at(i); auto character = controllers_[char_ents->at(i)]; if (c.teleport) { character->setPosition( physx::PxExtendedVec3(c.port_loc[0], c.port_loc[1], c.port_loc[2])); c.teleport = false; g_ent_mgr.MarkForUpdate<lib_physics::Character>(char_ents->at(i)); } if (c.resize) { character->resize(c.height); old_c.height = c.height; c.resize = false; } c.vert_velocity = old_c.vert_velocity; c.vert_velocity += gravity_acc * 3.f; if (c.vert_velocity < 0.2f) c.vert_velocity += gravity_acc * 2.5f; c.vert_velocity += c.disp[1]; auto add_position = dt * c.vert_velocity; auto filter = physx::PxControllerFilters(); auto flags = character->move(physx::PxVec3(c.disp[0], add_position, c.disp[2]), 0.001f, dt, filter); c.disp.ZeroMem(); if (flags & physx::PxControllerCollisionFlag::eCOLLISION_UP && c.vert_velocity > 0.f) c.vert_velocity = 0.f; if (flags & physx::PxControllerCollisionFlag::eCOLLISION_DOWN) { c.vert_velocity = 0.f; c.grounded = true; } else { c.grounded = false; } auto pos = character->getPosition(); pos += (character->getPosition() - character->getFootPosition()) * 0.9f; lib_core::Vector3 pos_vec = {float(pos.x), float(pos.y), float(pos.z)}; c.pos = pos_vec; if (c.pos[0] == old_c.pos[0] && c.pos[1] == old_c.pos[1] && c.pos[2] == old_c.pos[2] && c.vert_velocity == old_c.vert_velocity && c.vert_velocity == 0.f) (*char_update)[i] = false; } } } void PhysxCharacterHandler::CreateCharacterController(lib_core::Entity ent) { RemoveCharacterController(ent); auto ent_ptr = g_ent_mgr.GetNewCbeR<Character>(ent); physx::PxCapsuleControllerDesc desc; desc.contactOffset = 0.2f; desc.density = ent_ptr->density; desc.position.x = ent_ptr->pos[0]; desc.position.y = ent_ptr->pos[1]; desc.position.z = ent_ptr->pos[2]; desc.height = ent_ptr->height; desc.radius = ent_ptr->radius; physx::PxMaterial* material = physics_->createMaterial(1.5, 1.5, 1.5); desc.material = material; desc.reportCallback = report_callback.get(); auto controller = controller_manager_->createController(desc); controllers_[ent] = controller; material->release(); } void PhysxCharacterHandler::RemoveCharacterController(lib_core::Entity ent) { if (controllers_.find(ent) != controllers_.end()) { controllers_[ent]->release(); controllers_.erase(ent); } } void PhysxCharacterHandler::PhysxReportCallback::onShapeHit( const physx::PxControllerShapeHit& hit) { auto type = hit.actor->getType(); if (type == physx::PxActorType::eRIGID_DYNAMIC) { auto rigid_dynamic = static_cast<physx::PxRigidDynamic*>(hit.actor); if (rigid_dynamic->getRigidBodyFlags() & physx::PxRigidBodyFlag::eKINEMATIC) return; if (hit.dir.y > -0.5) rigid_dynamic->addForce(hit.dir * hit.length * 10, physx::PxForceMode::eIMPULSE); } } void PhysxCharacterHandler::PhysxReportCallback::onControllerHit( const physx::PxControllersHit& hit) {} void PhysxCharacterHandler::PhysxReportCallback::onObstacleHit( const physx::PxControllerObstacleHit& hit) {} } // namespace lib_physics
34.865772
80
0.673147
KarlJansson
36da1e360ce0da410eb20da9549f2a2066be0d6d
1,095
cpp
C++
archive/3/metody_nauczania_50.cpp
Aleshkev/algoritmika
fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189
[ "MIT" ]
2
2019-05-04T09:37:09.000Z
2019-05-22T18:07:28.000Z
archive/3/metody_nauczania_50.cpp
Aleshkev/algoritmika
fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189
[ "MIT" ]
null
null
null
archive/3/metody_nauczania_50.cpp
Aleshkev/algoritmika
fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef intmax_t I; typedef pair<I, I> II; int main() { cout.sync_with_stdio(false); cin.tie(0); I n, k; cin >> n >> k; vector<I> t(n); for(I i = 0; i < n; ++i) { t[i] = i * 2; //cin >> t[i]; } sort(t.begin(), t.end()); vector<map<I, I>> u(3); for(I i = 0; i < n; ++i) { ++u[0][t[i]]; } for(I j = 1; j < 3; ++j) { for(auto it = u[j - 1].rbegin(); it != u[j - 1].rend(); ++it) { //cout << "'" << it->first << " " << it->second << '\n'; for(I i = 0; i < n; ++i) { u[j][it->first + t[i]] += it->second; } } } /*for(I i = 0; i < 3; ++i) { cout << i << ": "; for(II j : u[i]) { for(I l = 0; l < j.second; ++l) { cout << j.first << ' '; } } cout << '\n'; }*/ I c = 0; for(II p : u[2]) { c += p.second; if(c >= k) { cout << p.first << '\n'; break; } } return 0; }
18.87931
71
0.32968
Aleshkev
36dfdd8a5da413cff936a6d8378abeee3c0d05bc
40,347
cpp
C++
lib/src/payload_adapter_db.cpp
dmarkh/cdbnpp
9f008e348851e7aa3f2a9b53bd4b0e620006909f
[ "MIT" ]
null
null
null
lib/src/payload_adapter_db.cpp
dmarkh/cdbnpp
9f008e348851e7aa3f2a9b53bd4b0e620006909f
[ "MIT" ]
null
null
null
lib/src/payload_adapter_db.cpp
dmarkh/cdbnpp
9f008e348851e7aa3f2a9b53bd4b0e620006909f
[ "MIT" ]
null
null
null
#include "npp/cdb/payload_adapter_db.h" #include <mutex> #include "npp/util/base64.h" #include "npp/util/json_schema.h" #include "npp/util/log.h" #include "npp/util/rng.h" #include "npp/util/util.h" #include "npp/util/uuid.h" #include "npp/cdb/http_client.h" namespace NPP { namespace CDB { using namespace soci; using namespace NPP::Util; std::mutex cdbnpp_db_access_mutex; // protects db calls, as SOCI is not thread-safe PayloadAdapterDb::PayloadAdapterDb() : IPayloadAdapter("db") {} PayloadResults_t PayloadAdapterDb::getPayloads( const std::set<std::string>& paths, const std::vector<std::string>& flavors, const PathToTimeMap_t& maxEntryTimeOverrides, int64_t maxEntryTime, int64_t eventTime, int64_t run, int64_t seq ) { PayloadResults_t res; if ( !ensureMetadata() ) { return res; } std::set<std::string> unfolded_paths{}; for ( const auto& path : paths ) { std::vector<std::string> parts = explode( path, ":" ); std::string flavor = parts.size() == 2 ? parts[0] : ""; std::string unflavored_path = parts.size() == 2 ? parts[1] : parts[0]; if ( mPaths.count(unflavored_path) == 0 ) { for ( const auto& [ key, value ] : mPaths ) { if ( string_starts_with( key, unflavored_path ) && value->mode() > 0 ) { unfolded_paths.insert( ( flavor.size() ? ( flavor + ":" ) : "" ) + key ); } } } else { unfolded_paths.insert( path ); } } for ( const auto& path : unfolded_paths ) { Result<SPayloadPtr_t> rc = getPayload( path, flavors, maxEntryTimeOverrides, maxEntryTime, eventTime, run, seq ); if ( rc.valid() ) { SPayloadPtr_t p = rc.get(); res.insert({ p->directory() + "/" + p->structName(), p }); } } return res; } Result<SPayloadPtr_t> PayloadAdapterDb::getPayload( const std::string& path, const std::vector<std::string>& service_flavors, const PathToTimeMap_t& maxEntryTimeOverrides, int64_t maxEntryTime, int64_t eventTime, int64_t eventRun, int64_t eventSeq ) { Result<SPayloadPtr_t> res; if ( !ensureMetadata() ) { res.setMsg("cannot get metadata"); return res; } if ( !setAccessMode("get") ) { res.setMsg( "cannot switch to GET mode"); return res; } if ( !ensureConnection() ) { res.setMsg("cannot ensure database connection"); return res; } auto [ flavors, directory, structName, is_path_valid ] = Payload::decodePath( path ); if ( !is_path_valid ) { res.setMsg( "request path has not been decoded, path: " + path ); return res; } if ( !service_flavors.size() && !flavors.size() ) { res.setMsg( "no flavor specified, path: " + path ); return res; } if ( !directory.size() ) { res.setMsg( "request does not specify directory, path: " + path ); return res; } if ( !structName.size() ) { res.setMsg( "request does not specify structName, path: " + path ); return res; } std::string dirpath = directory + "/" + structName; // check for path-specific maxEntryTime overrides if ( maxEntryTimeOverrides.size() ) { for ( const auto& [ opath, otime ] : maxEntryTimeOverrides ) { if ( string_starts_with( dirpath, opath ) ) { maxEntryTime = otime; break; } } } // get tag auto tagit = mPaths.find( dirpath ); if ( tagit == mPaths.end() ) { res.setMsg( "cannot find tag for the " + dirpath ); return res; } // get tbname from tag std::string tbname = tagit->second->tbname(), pid = tagit->second->id(); if ( !tbname.size() ) { res.setMsg( "requested path points to the directory, need struct: " + dirpath ); return res; } for ( const auto& flavor : ( flavors.size() ? flavors : service_flavors ) ) { std::string id{""}, uri{""}, fmt{""}; uint64_t bt = 0, et = 0, ct = 0, dt = 0, run = 0, seq = 0, mode = tagit->second->mode(); if ( mode == 2 ) { // fetch id, run, seq { // RAII scope block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); try { std::string query = "SELECT id, uri, bt, et, ct, dt, run, seq, fmt FROM cdb_iov_" + tbname + " " + "WHERE " + "flavor = :flavor " + "AND run = :run " + "AND seq = :seq " + ( maxEntryTime ? "AND ct <= :mt " : "" ) + ( maxEntryTime ? "AND ( dt = 0 OR dt > :mt ) " : "" ) + "ORDER BY ct DESC LIMIT 1"; if ( maxEntryTime ) { mSession->once << query, into(id), into(uri), into(bt), into(et), into(ct), into(dt), into(run), into(seq), into(fmt), use( flavor, "flavor"), use( eventRun, "run" ), use( eventSeq, "seq" ), use( maxEntryTime, "mt" ); } else { mSession->once << query, into(id), into(uri), into(bt), into(et), into(ct), into(dt), into(run), into(seq), into(fmt), use( flavor, "flavor"), use( eventRun, "run" ), use( eventSeq, "seq" ); } } catch( std::exception const & e ) { res.setMsg( "database exception: " + std::string(e.what()) ); return res; } } // RAII scope block for the db access mutex if ( !id.size() ) { continue; } // nothing found } else if ( mode == 1 ) { // fetch id, bt, et { // RAII scope block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); try { std::string query = "SELECT id, uri, bt, et, ct, dt, run, seq, fmt FROM cdb_iov_" + tbname + " " + "WHERE " + "flavor = :flavor " + "AND bt <= :et AND ( et = 0 OR et > :et ) " + ( maxEntryTime ? "AND ct <= :mt " : "" ) + ( maxEntryTime ? "AND ( dt = 0 OR dt > :mt ) " : "" ) + "ORDER BY bt DESC LIMIT 1"; if ( maxEntryTime ) { mSession->once << query, into(id), into(uri), into(bt), into(et), into(ct), into(dt), into(run), into(seq), into(fmt), use( flavor, "flavor"), use( eventTime, "et" ), use( maxEntryTime, "mt" ); } else { mSession->once << query, into(id), into(uri), into(bt), into(et), into(ct), into(dt), into(run), into(seq), into(fmt), use( flavor, "flavor"), use( eventTime, "et" ); } } catch( std::exception const & e ) { res.setMsg( "database exception: " + std::string(e.what()) ); return res; } } // RAII scope block for the db access mutex if ( !id.size() ) { continue; } // nothing found if ( et == 0 ) { // if no endTime, do another query to establish endTime { // RAII scope block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); try { std::string query = "SELECT bt FROM cdb_iov_" + tbname + " " + "WHERE " + "flavor = :flavor " + "AND bt >= :et " + "AND ( et = 0 OR et < :et )" + ( maxEntryTime ? "AND ct <= :mt " : "" ) + ( maxEntryTime ? "AND ( dt = 0 OR dt > :mt ) " : "" ) + "ORDER BY bt ASC LIMIT 1"; if ( maxEntryTime ) { mSession->once << query, into(et), use( flavor, "flavor"), use( eventTime, "et" ), use( maxEntryTime, "mt" ); } else { mSession->once << query, into(et), use( flavor, "flavor"), use( eventTime, "et" ); } } catch( std::exception const & e ) { res.setMsg( "database exception: " + std::string(e.what()) ); return res; } } // RAII scope block for the db access mutex if ( !et ) { et = std::numeric_limits<uint64_t>::max(); } } } // create payload ptr, populate with data auto p = std::make_shared<Payload>( id, pid, flavor, structName, directory, ct, bt, et, dt, run, seq ); p->setURI( uri ); res = p; return res; } return res; } Result<std::string> PayloadAdapterDb::setPayload( const SPayloadPtr_t& payload ) { Result<std::string> res; if ( !payload->ready() ) { res.setMsg( "payload is not ready to be stored" ); return res; } if ( !ensureMetadata() ) { res.setMsg( "db adapter cannot download metadata"); return res; } if ( payload->dataSize() && payload->format() != "dat" ) { // validate json against schema if exists Result<std::string> schema = getTagSchema( payload->directory() + "/" + payload->structName() ); if ( schema.valid() ) { Result<bool> rc = validate_json_using_schema( payload->dataAsJson(), schema.get() ); if ( rc.invalid() ) { res.setMsg( "schema validation failed" ); return res; } } } // get tag, fetch tbname auto tagit = mPaths.find( payload->directory() + "/" + payload->structName() ); if ( tagit == mPaths.end() ) { res.setMsg( "cannot find payload tag in the database: " + payload->directory() + "/" + payload->structName() ); return res; } std::string tbname = tagit->second->tbname(); sanitize_alnumuscore(tbname); // unpack values for SOCI std::string id = payload->id(), pid = payload->pid(), flavor = payload->flavor(), fmt = payload->format(); int64_t ct = std::time(nullptr), bt = payload->beginTime(), et = payload->endTime(), run = payload->run(), seq = payload->seq(); if ( !setAccessMode("set") ) { res.setMsg( "cannot switch to SET mode"); return res; } if ( !ensureConnection() ) { res.setMsg("db adapter cannot connect to the database"); return res; } // insert iov into cdb_iov_<table-name>, data into cdb_data_<table-name> { // RAII scope block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); try { int64_t dt = 0; transaction tr( *mSession.get() ); if ( !payload->URI().size() && payload->dataSize() ) { // if uri is empty and data is not empty, store data locally to the database size_t data_size = payload->dataSize(); std::string data = base64::encode( payload->data() ); mSession->once << ( "INSERT INTO cdb_data_" + tbname + " ( id, pid, ct, dt, data, size ) VALUES ( :id, :pid, :ct, :dt, :data, :size )" ) ,use(id), use(pid), use(ct), use(dt), use(data), use(data_size); payload->setURI( "db://" + tbname + "/" + id ); } std::string uri = payload->URI(); mSession->once << ( "INSERT INTO cdb_iov_" + tbname + " ( id, pid, flavor, ct, bt, et, dt, run, seq, uri, fmt ) VALUES ( :id, :pid, :flavor, :ct, :bt, :et, :dt, :run, :seq, :uri, :bin )" ) ,use(id), use(pid), use(flavor), use(ct), use(bt), use(et), use(dt), use(run), use(seq), use(uri), use(fmt); tr.commit(); res = id; } catch( std::exception const & e ) { res.setMsg( "database exception: " + std::string(e.what()) ); return res; } } // RAII scope block for the db access mutex return res; } Result<std::string> PayloadAdapterDb::deactivatePayload( const SPayloadPtr_t& payload, int64_t deactiveTime ) { Result<std::string> res; if ( !payload->ready() ) { res.setMsg( "payload is not ready to be used for deactivation" ); return res; } if ( !ensureMetadata() ) { res.setMsg( "db adapter cannot download metadata"); return res; } if ( !setAccessMode("admin") ) { res.setMsg( "cannot switch to ADMIN mode"); return res; } if ( !ensureConnection() ) { res.setMsg("db adapter cannot connect to the database"); return res; } // get tag, fetch tbname auto tagit = mPaths.find( payload->directory() + "/" + payload->structName() ); if ( tagit == mPaths.end() ) { res.setMsg( "cannot find payload tag in the database: " + payload->directory() + "/" + payload->structName() ); return res; } std::string tbname = tagit->second->tbname(); sanitize_alnumuscore(tbname); std::string id = payload->id(); sanitize_alnumdash(id); { // RAII scope block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); try { mSession->once << "UPDATE cdb_iov_" + tbname + " SET dt = :dt WHERE id = :id", use(deactiveTime), use( id ); } catch ( std::exception const & e ) { res.setMsg( "database exception: " + std::string(e.what()) ); return res; } } res = id; return res; } Result<SPayloadPtr_t> PayloadAdapterDb::prepareUpload( const std::string& path ) { Result<SPayloadPtr_t> res; // check if Db Adapter is configured for writes if ( !ensureMetadata() ) { res.setMsg( "db adapter cannot download metadata" ); return res; } auto [ flavors, directory, structName, is_path_valid ] = Payload::decodePath( path ); if ( !flavors.size() ) { res.setMsg( "no flavor provided: " + path ); return res; } if ( !is_path_valid ) { res.setMsg( "bad path provided: " + path ); return res; } // see if path exists in the known tags map auto tagit = mPaths.find( directory + "/" + structName ); if ( tagit == mPaths.end() ) { res.setMsg( "path does not exist in the db. path: " + path ); return res; } // check if path is really a struct if ( !tagit->second->tbname().size() ) { res.setMsg( "cannot upload to the folder, need struct. path: " + path ); return res; } SPayloadPtr_t p = std::make_shared<Payload>(); p->setId( generate_uuid() ); p->setPid( tagit->second->id() ); p->setFlavor( flavors[0] ); p->setDirectory( directory ); p->setStructName( structName ); p->setMode( tagit->second->mode() ); res = p; return res; } Result<bool> PayloadAdapterDb::dropTagSchema( const std::string& tag_path ) { Result<bool> res; if ( !ensureMetadata() ) { res.setMsg("cannot ensure metadata"); return res; } if ( !setAccessMode("admin") ) { res.setMsg("cannot set ADMIN mode"); return res; } if ( !ensureConnection() ) { res.setMsg("cannot ensure connection"); return res; } // make sure tag_path exists and is a struct std::string sanitized_path = tag_path; sanitize_alnumslash( sanitized_path ); if ( sanitized_path != tag_path ) { res.setMsg( "sanitized tag path != input tag path... path: " + sanitized_path ); return res; } std::string tag_pid = ""; auto tagit = mPaths.find( sanitized_path ); if ( tagit == mPaths.end() ) { res.setMsg( "cannot find tag path in the database... path: " + sanitized_path ); return res; } tag_pid = (tagit->second)->id(); // find tbname and id for the tag std::string tbname = (tagit->second)->tbname(); if ( !tbname.size() ) { res.setMsg( "tag is not a struct... path: " + sanitized_path ); return res; } { // RAII scope block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); try { mSession->once << "DELETE FROM cdb_schemas WHERE pid = :pid", use(tag_pid); } catch( std::exception const & e ) { res.setMsg( "database exception: " + std::string(e.what()) ); return res; } } res = true; return res; } Result<bool> PayloadAdapterDb::createDatabaseTables() { Result<bool> res; if ( !setAccessMode("admin") ) { res.setMsg( "cannot switch to ADMIN mode" ); return res; } if ( !ensureConnection() ) { res.setMsg( "cannot connect to the database" ); return res; } { // RAII scope block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); try { transaction tr( *mSession.get() ); // cdb_tags { soci::ddl_type ddl = mSession->create_table("cdb_tags"); ddl.column("id", soci::dt_string, 36 )("not null"); ddl.column("pid", soci::dt_string, 36 )("not null"); ddl.column("name", soci::dt_string, 128 )("not null"); ddl.column("ct", soci::dt_unsigned_long_long )("not null"); ddl.column("dt", soci::dt_unsigned_long_long )("not null default 0"); ddl.column("mode", soci::dt_unsigned_long_long )("not null default 0"); // 0 = tag, 1 = struct bt,et; 2 = struct run,seq ddl.column("tbname", soci::dt_string, 512 )("not null"); ddl.primary_key("cdb_tags_pk", "pid,name,dt"); ddl.unique("cdb_tags_id", "id"); } // cdb_schemas { soci::ddl_type ddl = mSession->create_table("cdb_schemas"); ddl.column("id", soci::dt_string, 36 )("not null"); ddl.column("pid", soci::dt_string, 36 )("not null"); ddl.column("ct", soci::dt_unsigned_long_long )("not null"); ddl.column("dt", soci::dt_unsigned_long_long )("null default 0"); ddl.column("data", soci::dt_string )("not null"); ddl.primary_key("cdb_schemas_pk", "pid,dt"); ddl.unique("cdb_schemas_id", "id"); } tr.commit(); } catch( std::exception const & e ) { res.setMsg( "database exception: " + std::string(e.what()) ); return res; } } // RAII scope block for the db access mutex res = true; return res; } Result<bool> PayloadAdapterDb::createIOVDataTables( const std::string& tablename, bool create_storage ) { Result<bool> res; if ( !setAccessMode("admin") ) { res.setMsg("cannot get ADMIN mode"); return res; } if ( !ensureConnection() ) { res.setMsg("cannot ensure connection"); return res; } { //RAII scope block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); try { transaction tr( *mSession.get() ); // cdb_iov_<tablename> { soci::ddl_type ddl = mSession->create_table("cdb_iov_"+tablename); ddl.column("id", soci::dt_string, 36 )("not null"); ddl.column("pid", soci::dt_string, 36 )("not null"); ddl.column("flavor", soci::dt_string, 128 )("not null"); ddl.column("ct", soci::dt_unsigned_long_long )("not null"); ddl.column("dt", soci::dt_unsigned_long_long )("not null default 0"); ddl.column("bt", soci::dt_unsigned_long_long )("not null default 0"); // used with mode = 0 ddl.column("et", soci::dt_unsigned_long_long )("not null default 0"); // used with mode = 0 ddl.column("run", soci::dt_unsigned_long_long )("not null default 0"); // used with mode = 1 ddl.column("seq", soci::dt_unsigned_long_long )("not null default 0"); // used with mode = 1 ddl.column("fmt", soci::dt_string, 36 )("not null"); // see Service::formats() ddl.column("uri", soci::dt_string, 2048 )("not null"); ddl.primary_key("cdb_iov_"+tablename+"_pk", "pid,bt,run,seq,dt,flavor"); ddl.unique("cdb_iov_"+tablename+"_id", "id"); } mSession->once << "CREATE INDEX cdb_iov_" + tablename + "_ct ON cdb_iov_" + tablename + " (ct)"; if ( create_storage ) { // cdb_data_<tablename> { soci::ddl_type ddl = mSession->create_table("cdb_data_"+tablename); ddl.column("id", soci::dt_string, 36 )("not null"); ddl.column("pid", soci::dt_string, 36 )("not null"); ddl.column("ct", soci::dt_unsigned_long_long )("not null"); ddl.column("dt", soci::dt_unsigned_long_long )("not null default 0"); ddl.column("data", soci::dt_string )("not null"); ddl.column("size", soci::dt_unsigned_long_long )("not null default 0"); ddl.primary_key("cdb_data_"+tablename+"_pk", "id,pid,dt"); ddl.unique("cdb_data_"+tablename+"_id", "id"); } mSession->once << "CREATE INDEX cdb_data_" + tablename + "_pid ON cdb_data_" + tablename + " (pid)"; mSession->once << "CREATE INDEX cdb_data_" + tablename + "_ct ON cdb_data_" + tablename + " (ct)"; } tr.commit(); } catch( std::exception const & e ) { res.setMsg( "database exception: " + std::string(e.what()) ); return res; } } // RAII scope block for the db access mutex res = true; return res; } std::vector<std::string> PayloadAdapterDb::listDatabaseTables() { std::vector<std::string> tables; if ( !setAccessMode("admin") ) { return tables; } if ( !ensureConnection() ) { return tables; } { // RAII scope block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); try { std::string name; soci::statement st = (mSession->prepare_table_names(), into(name)); st.execute(); while (st.fetch()) { tables.push_back( name ); } } catch( std::exception const & e ) { // database exception: " << e.what() tables.clear(); } } // RAII scope block for the db access mutex return tables; } Result<bool> PayloadAdapterDb::dropDatabaseTables() { Result<bool> res; std::vector<std::string> tables = listDatabaseTables(); if ( !setAccessMode("admin") ) { res.setMsg( "cannot switch to ADMIN mode" ); return res; } if ( !ensureConnection() ) { res.setMsg( "cannot connect to the database" ); return res; } { // RAII scope block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); try { for ( const auto& tbname : tables ) { mSession->drop_table( tbname ); } } catch( std::exception const & e ) { res.setMsg( "database exception: " + std::string(e.what()) ); return res; } res = true; } // RAII scope block for the db access mutex return res; } bool PayloadAdapterDb::setAccessMode( const std::string& mode ) { if ( !hasAccess(mode) ) { // cannot set access mode return false; } if ( mAccessMode == mode ) { return true; } mAccessMode = mode; if ( isConnected() ) { return reconnect(); } return true; } void PayloadAdapterDb::disconnect() { if ( !isConnected() ) { return; } { // RAII block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); try { mSession->close(); mIsConnected = false; mDbType = ""; } catch ( std::exception const & e ) { // database exception, e.what() } } // RAII block for the db access mutex } bool PayloadAdapterDb::connect( const std::string& dbtype, const std::string& host, int port, const std::string& user, const std::string& pass, const std::string& dbname, const std::string& options ) { if ( isConnected() ) { disconnect(); } { // RAII block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); if ( mSession == nullptr ) { mSession = std::make_shared<soci::session>(); } std::string connect_string{ dbtype + "://" + ( host.size() ? "host=" + host : "") + ( port > 0 ? " port=" + std::to_string(port) : "" ) + ( user.size() ? " user=" + user : "" ) + ( pass.size() ? " password=" + pass : "" ) + ( dbname.size() ? " dbname=" + dbname : "" ) + ( options.size() ? " " + options : "" ) }; try { mSession->open( connect_string ); } catch ( std::exception const & e ) { // database exception: " << e.what() return false; } mIsConnected = true; mDbType = dbtype; } // RAII scope block for the db access mutex return true; } bool PayloadAdapterDb::reconnect() { if ( !hasAccess( mAccessMode ) ) { return false; } if ( isConnected() ) { disconnect(); } int port{0}; std::string dbtype{}, host{}, user{}, pass{}, dbname{}, options{}; nlohmann::json node; size_t idx = RngS::Instance().random_inclusive<size_t>( 0, mConfig["adapters"]["db"][ mAccessMode ].size() - 1 ); node = mConfig["adapters"]["db"][ mAccessMode ][ idx ]; if ( node.contains("dbtype") ) { dbtype = node["dbtype"]; } if ( node.contains("host") ) { host = node["host"]; } if ( node.contains("port") ) { port = node["port"]; } if ( node.contains("user") ) { user = node["user"]; } if ( node.contains("pass") ) { pass = node["pass"]; } if ( node.contains("dbname") ) { dbname = node["dbname"]; } if ( node.contains("options") ) { options = node["options"]; } return connect( dbtype, host, port, user, pass, dbname, options ); } bool PayloadAdapterDb::ensureMetadata() { return mMetadataAvailable ? true : downloadMetadata(); } bool PayloadAdapterDb::downloadMetadata() { if ( !ensureConnection() ) { return false; } const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); if ( mMetadataAvailable ) { return true; } mTags.clear(); mPaths.clear(); // download tags and populate lookup map: tag ID => Tag obj try { std::string id, name, pid, tbname, schema_id; int64_t ct, dt, mode; soci::indicator ind; statement st = ( mSession->prepare << "SELECT t.id, t.name, t.pid, t.tbname, t.ct, t.dt, t.mode, COALESCE(s.id,'') as schema_id FROM cdb_tags t LEFT JOIN cdb_schemas s ON t.id = s.pid", into(id), into(name), into(pid), into(tbname), into(ct), into(dt), into(mode), into(schema_id, ind) ); st.execute(); while (st.fetch()) { mTags.insert({ id, std::make_shared<Tag>( id, name, pid, tbname, ct, dt, mode, ind == i_ok ? schema_id : "" ) }); } } catch ( std::exception const & e ) { // database exception: " << e.what() return false; } if ( mTags.size() ) { // erase tags that have parent id but no parent exists => side-effect of tag deactivation and/or maxEntryTime // unfortunately, std::erase_if is C++20 container_erase_if( mTags, [this]( const auto item ) { return ( item.second->pid().size() && mTags.find( item.second->pid() ) == mTags.end() ); }); } // parent-child: assign children and parents if ( mTags.size() ) { for ( auto& tag : mTags ) { if ( !(tag.second)->pid().size() ) { continue; } auto rc = mTags.find( ( tag.second )->pid() ); if ( rc == mTags.end() ) { continue; } ( tag.second )->setParent( rc->second ); ( rc->second )->addChild( tag.second ); } // populate lookup map: path => Tag obj for ( const auto& tag : mTags ) { mPaths.insert({ ( tag.second )->path(), tag.second }); } } // TODO: filter mTags and mPaths based on maxEntryTime return true; } Result<std::string> PayloadAdapterDb::createTag( const STagPtr_t& tag ) { return createTag( tag->id(), tag->name(), tag->pid(), tag->tbname(), tag->ct(), tag->dt(), tag->mode() ); } Result<std::string> PayloadAdapterDb::createTag( const std::string& path, int64_t tag_mode ) { Result<std::string> res; if ( !ensureMetadata() ) { res.setMsg( "db adapter cannot download metadata" ); return res; } if ( !setAccessMode("admin") ) { res.setMsg( "cannot switch to ADMIN mode" ); return res; } if ( !ensureConnection() ) { res.setMsg("cannot connect to database"); return res; } std::string sanitized_path = path; sanitize_alnumslash( sanitized_path ); if ( sanitized_path != path ) { res.setMsg( "path contains unwanted characters, path: " + path ); return res; } // check for existing tag if ( mPaths.find( sanitized_path ) != mPaths.end() ) { res.setMsg( "attempt to create an existing tag " + sanitized_path ); return res; } std::string tag_id = uuid_from_str( sanitized_path ), tag_name = "", tag_tbname = "", tag_pid = ""; if ( !tag_id.size() ) { res.setMsg( "new tag uuid generation failed" ); return res; } long long tag_ct = time(0), tag_dt = 0; Tag* parent_tag = nullptr; std::vector<std::string> parts = explode( sanitized_path, '/' ); tag_name = parts.back(); parts.pop_back(); sanitized_path = parts.size() ? implode( parts, "/" ) : ""; if ( sanitized_path.size() ) { auto ptagit = mPaths.find( sanitized_path ); if ( ptagit != mPaths.end() ) { parent_tag = (ptagit->second).get(); tag_pid = parent_tag->id(); } else { res.setMsg( "parent tag does not exist: " + sanitized_path ); return res; } } if ( tag_mode > 0 ) { tag_tbname = ( parent_tag ? parent_tag->path() + "/" + tag_name : tag_name ); std::replace( tag_tbname.begin(), tag_tbname.end(), '/', '_'); string_to_lower_case( tag_tbname ); } return createTag( tag_id, tag_name, tag_pid, tag_tbname, tag_ct, tag_dt, tag_mode ); } Result<std::string> PayloadAdapterDb::deactivateTag( const std::string& path, int64_t deactiveTime ) { Result<std::string> res; if ( !ensureMetadata() ) { res.setMsg( "db adapter cannot download metadata" ); return res; } if ( !setAccessMode("admin") ) { res.setMsg( "db adapter is not configured for writes" ); return res; } if ( !ensureConnection() ) { res.setMsg("cannot connect to database"); return res; } std::string sanitized_path = path; sanitize_alnumslash( sanitized_path ); if ( sanitized_path != path ) { res.setMsg( "path contains unwanted characters, path: " + path ); return res; } // check for existing tag auto tagit = mPaths.find( sanitized_path ); if ( tagit == mPaths.end() ) { res.setMsg( "cannot find path in the database, path: " + path ); return res; } std::string tag_id = tagit->second->id(); if ( !tag_id.size() ) { res.setMsg( "empty tag id found" ); return res; } { // RAII scope block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); try { mSession->once << "UPDATE cdb_tags SET dt = :dt WHERE id = :id", use(deactiveTime), use(tag_id); } catch ( std::exception const & e ) { res.setMsg( "database exception: " + std::string(e.what()) ); return res; } res = tag_id; } // RAII scope block for the db access mutex return res; } Result<std::string> PayloadAdapterDb::createTag( const std::string& tag_id, const std::string& tag_name, const std::string& tag_pid, const std::string& tag_tbname, int64_t tag_ct, int64_t tag_dt, int64_t tag_mode ) { Result<std::string> res; if ( !ensureMetadata() ) { res.setMsg( "db adapter cannot download metadata" ); return res; } if ( !tag_id.size() ) { res.setMsg( "cannot create new tag: empty tag id provided" ); return res; } if ( !tag_name.size() ) { res.setMsg( "cannot create new tag: empty tag name provided" ); return res; } if ( tag_pid.size() && mTags.find( tag_pid ) == mTags.end() ) { res.setMsg( "parent tag provided but not found in the map" ); return res; } if ( !setAccessMode("admin") ) { res.setMsg( "cannot switch to ADMIN mode" ); return res; } if ( !ensureConnection() ) { res.setMsg( "db adapter cannot ensure connection" ); return res; } { // RAII scope block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); // insert new tag into the database try { mSession->once << "INSERT INTO cdb_tags ( id, name, pid, tbname, ct, dt, mode ) VALUES ( :id, :name, :pid, :tbname, :ct, :dt, :mode ) ", use(tag_id), use(tag_name), use(tag_pid), use(tag_tbname), use(tag_ct), use(tag_dt), use(tag_mode); } catch ( std::exception const & e ) { res.setMsg( "database exception: " + std::string(e.what()) ); return res; } } // RAII scope block for the db access mutex // if it is a struct, create IOV + Data tables if ( tag_tbname.size() ) { Result<bool> rc = createIOVDataTables( tag_tbname ); if ( rc.invalid() ) { res.setMsg( "failed to create IOV Data Tables for tag: " + tag_name + ", tbname: " + tag_tbname ); return res; } } // create new tag object and set parent-child relationship STagPtr_t new_tag = std::make_shared<Tag>( tag_id, tag_name, tag_pid, tag_tbname, tag_ct, tag_dt ); if ( tag_pid.size() ) { STagPtr_t parent_tag = ( mTags.find( tag_pid ) )->second; new_tag->setParent( parent_tag ); parent_tag->addChild( new_tag ); } // add new tag to maps mTags.insert({ tag_id, new_tag }); mPaths.insert({ new_tag->path(), new_tag }); res = tag_id; return res; } std::vector<std::string> PayloadAdapterDb::getTags( bool skipStructs ) { std::vector<std::string> tags; if ( !ensureMetadata() ) { return tags; } if ( !setAccessMode("get") ) { return tags; } if ( !ensureConnection() ) { return tags; } tags.reserve( mPaths.size() ); for ( const auto& [key, value] : mPaths ) { if ( value->mode() == 0 ) { const auto& children = value->children(); if ( children.size() == 0 ) { tags.push_back( "[-] " + key ); } else { bool has_folders = std::find_if( children.begin(), children.end(), []( auto& child ) { return child.second->tbname().size() == 0; } ) != children.end(); if ( has_folders ) { tags.push_back( "[+] " + key ); } else { tags.push_back( "[-] " + key ); } } } else if ( !skipStructs ) { std::string schema = "-"; if ( value->schema().size() ) { schema = "s"; } tags.push_back( "[s/" + schema + "/" + std::to_string( value->mode() ) + "] " + key ); } } return tags; } Result<std::string> PayloadAdapterDb::downloadData( const std::string& uri ) { Result<std::string> res; if ( !uri.size() ) { res.setMsg("empty uri"); return res; } // uri = db://<tablename>/<item-uuid> auto parts = explode( uri, "://" ); if ( parts.size() != 2 || parts[0] != "db" ) { res.setMsg("bad uri"); return res; } if ( !setAccessMode("get") ) { res.setMsg( "db adapter is not configured" ); } if ( !ensureConnection() ) { res.setMsg("cannot ensure database connection"); return res; } auto tbparts = explode( parts[1], "/" ); if ( tbparts.size() != 2 ) { res.setMsg("bad uri tbname"); return res; } std::string storage_name = tbparts[0], id = tbparts[1], data; { // RAII scope block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); try { mSession->once << ("SELECT data FROM cdb_data_" + storage_name + " WHERE id = :id"), into(data), use( id ); } catch( std::exception const & e ) { res.setMsg( "database exception: " + std::string(e.what()) ); return res; } } // RAII scope lock for the db access mutex if ( !data.size() ) { res.setMsg("no data"); return res; } res = base64::decode(data); return res; } Result<std::string> PayloadAdapterDb::getTagSchema( const std::string& tag_path ) { Result<std::string> res; if ( !ensureMetadata() ) { res.setMsg("cannot download metadata"); return res; } if ( !setAccessMode("get") ) { res.setMsg("cannot switch to GET mode"); return res; } if ( !ensureConnection() ) { res.setMsg("cannot connect to the database"); return res; } auto tagit = mPaths.find( tag_path ); if ( tagit == mPaths.end() ) { res.setMsg("cannot find path"); return res; } std::string pid = tagit->second->id(); std::string schema{""}; { // RAII scope block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); try { mSession->once << "SELECT data FROM cdb_schemas WHERE pid = :pid ", into(schema), use(pid); } catch( std::exception const & e ) { res.setMsg( "database exception: " + std::string(e.what()) ); return res; } } // RAII scope block for the db access mutex if ( schema.size() ) { res = schema; } else { res.setMsg("no schema"); } return res; } Result<std::string> PayloadAdapterDb::exportTagsSchemas( bool tags, bool schemas ) { Result<std::string> res; if ( !ensureMetadata() ) { res.setMsg("cannot download metadata"); return res; } if ( !mTags.size() || !mPaths.size() ) { res.setMsg("no tags, cannot export"); return res; } if ( !tags && !schemas ) { res.setMsg( "neither tags nor schemas were requested for export"); return res; } nlohmann::json output; output["export_type"] = "cdbnpp_tags_schemas"; output["export_timestamp"] = std::time(nullptr); if ( tags ) { output["tags"] = nlohmann::json::array(); } if ( schemas ) { output["schemas"] = nlohmann::json::array(); } for ( const auto& [ key, value ] : mPaths ) { if ( tags ) { output["tags"].push_back( value->toJson() ); } if ( schemas && value->schema().size() ) { Result<std::string> schema_str = getTagSchema( key ); if ( schema_str.valid() ) { output["schemas"].push_back({ { "id", value->schema() }, { "pid", value->id() }, { "path", value->path() }, {"data", schema_str.get() } }); } // cannot get schema for a tag, contact db admin :( } } res = output.dump(2); return res; } Result<bool> PayloadAdapterDb::importTagsSchemas(const std::string& stringified_json ) { Result<bool> res; if ( !stringified_json.size() ) { res.setMsg("empty tag/schema data provided"); return res; } nlohmann::json data = nlohmann::json::parse( stringified_json.begin(), stringified_json.end(), nullptr, false, true ); if ( data.empty() || data.is_discarded() || data.is_null() ) { res.setMsg( "bad input data" ); return res; } bool tag_import_errors = false, schema_import_errors = false; if ( data.contains("tags") ) { for ( const auto& [ key, tag ] : data["tags"].items() ) { Result<std::string> rc = createTag( tag["id"].get<std::string>(), tag["name"].get<std::string>(), tag["pid"].get<std::string>(), tag["tbname"].get<std::string>(), tag["ct"].get<uint64_t>(), tag["dt"].get<uint64_t>(), tag["mode"].get<uint64_t>() ); if ( rc.invalid() ) { tag_import_errors = true; } } } if ( data.contains("schemas") ) { for ( const auto& [ key, schema ] : data["schemas"].items() ) { Result<bool> rc = setTagSchema( schema["path"].get<std::string>(), schema["data"].get<std::string>() ); if ( rc.invalid() ) { schema_import_errors = true; } } } res = !tag_import_errors && !schema_import_errors; return res; } Result<bool> PayloadAdapterDb::setTagSchema( const std::string& tag_path, const std::string& schema_json ) { Result<bool> res; if ( !schema_json.size() ) { res.setMsg( "empty tag schema provided" ); return res; } if ( !ensureMetadata() ) { res.setMsg("cannot ensure metadata"); return res; } if ( !setAccessMode("admin") ) { res.setMsg("cannot set ADMIN mode"); return res; } if ( !ensureConnection() ) { res.setMsg("cannot ensure connection"); return res; } // make sure tag_path exists and is a struct std::string sanitized_path = tag_path; sanitize_alnumslash( sanitized_path ); if ( sanitized_path != tag_path ) { res.setMsg("sanitized tag path != input tag path... path: " + sanitized_path ); return res; } std::string tag_pid = ""; auto tagit = mPaths.find( sanitized_path ); if ( tagit == mPaths.end() ) { res.setMsg( "cannot find tag path in the database... path: " + sanitized_path ); return res; } tag_pid = (tagit->second)->id(); // find tbname and id for the tag std::string tbname = (tagit->second)->tbname(); if ( !tbname.size() ) { res.setMsg( "tag is not a struct... path: " + sanitized_path ); return res; } std::string existing_id = ""; { // RAII scope block for the db access schema const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); try { mSession->once << "SELECT id FROM cdb_schemas WHERE pid = :pid ", into(existing_id), use(tag_pid); } catch( std::exception const & e ) { res.setMsg( "database exception: " + std::string(e.what()) ); return res; } } // RAII scope block for the db access schema if ( existing_id.size() ) { res.setMsg( "cannot set schema as it already exists for " + sanitized_path ); return res; } // validate schema against schema std::string schema = R"({ "$id": "file://.cdbnpp_config.json", "$schema": "https://json-schema.org/draft/2020-12/schema", "description": "CDBNPP Config File", "type": "object", "required": [ "$id", "$schema", "properties", "required" ], "properties": { "$id": { "type": "string" }, "$schema": { "type": "string" }, "properties": { "type": "object" }, "required": { "type": "array", "items": { "type": "string" } } } })"; Result<bool> rc = validate_json_using_schema( schema_json, schema ); if ( rc.invalid() ) { res.setMsg( "proposed schema is invalid" ); return res; } { // RAII scope block for the db access mutex const std::lock_guard<std::mutex> lock(cdbnpp_db_access_mutex); // insert schema into cdb_schemas table try { std::string schema_id = generate_uuid(), data = schema_json; long long ct = 0, dt = 0; mSession->once << "INSERT INTO cdb_schemas ( id, pid, data, ct, dt ) VALUES( :schema_id, :pid, :data, :ct, :dt )", use(schema_id), use(tag_pid), use(data), use(ct), use(dt); } catch( std::exception const & e ) { res.setMsg( "database exception: " + std::string(e.what()) ); return res; } } // RAII scope block for the db access mutex res = true; return res; } } // namespace CDB } // namespace NPP
29.493421
192
0.607678
dmarkh
36e620388180ad0ab7afe89498544e17c16012a9
24,455
cc
C++
src/hooks/dhcp/high_availability/tests/query_filter_unittest.cc
mcr/kea
7fbbfde2a0742a3d579d51ec94fc9b91687fb901
[ "Apache-2.0" ]
1
2019-08-10T21:52:58.000Z
2019-08-10T21:52:58.000Z
src/hooks/dhcp/high_availability/tests/query_filter_unittest.cc
jxiaobin/kea
1987a50a458921f9e5ac84cb612782c07f3b601d
[ "Apache-2.0" ]
null
null
null
src/hooks/dhcp/high_availability/tests/query_filter_unittest.cc
jxiaobin/kea
1987a50a458921f9e5ac84cb612782c07f3b601d
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2018 Internet Systems Consortium, Inc. ("ISC") // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include <ha_test.h> #include <ha_config.h> #include <ha_config_parser.h> #include <query_filter.h> #include <cc/data.h> #include <exceptions/exceptions.h> #include <dhcp/dhcp4.h> #include <dhcp/dhcp6.h> #include <dhcp/hwaddr.h> #include <cstdint> #include <string> using namespace isc; using namespace isc::data; using namespace isc::dhcp; using namespace isc::ha; using namespace isc::ha::test; namespace { /// @brief Test fixture class for @c QueryFilter class. using QueryFilterTest = HATest; // This test verifies the case when load balancing is enabled and // this server is primary. TEST_F(QueryFilterTest, loadBalancingThisPrimary) { HAConfigPtr config = createValidConfiguration(); QueryFilter filter(config); // By default the server1 should serve its own scope only. The // server2 should serve its scope. EXPECT_TRUE(filter.amServingScope("server1")); EXPECT_FALSE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); // Count number of in scope packets. unsigned in_scope = 0; // Set the test size - 65535 queries. const unsigned queries_num = 65535; std::string scope_class; for (unsigned i = 0; i < queries_num; ++i) { // Create query with random HW address. Pkt4Ptr query4 = createQuery4(randomKey(HWAddr::ETHERNET_HWADDR_LEN)); // If the query is in scope, increase the counter of packets in scope. if (filter.inScope(query4, scope_class)) { ASSERT_EQ("HA_server1", scope_class); ASSERT_NE(scope_class, "HA_server2"); ++in_scope; } } // We should have roughly 50/50 split of in scope and out of scope queries. // However, we don't know exactly how many. To be safe we simply assume that // we got more than 25% of in scope and more than 25% out of scope queries. EXPECT_GT(in_scope, static_cast<unsigned>(queries_num / 4)); EXPECT_GT(queries_num - in_scope, static_cast<unsigned>(queries_num / 4)); // Simulate failover scenario. filter.serveFailoverScopes(); // In the failover case, the server1 should also take responsibility for // the server2's queries. EXPECT_TRUE(filter.amServingScope("server1")); EXPECT_TRUE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); // Repeat the test, but this time all should be in scope. for (unsigned i = 0; i < queries_num; ++i) { // Create query with random HW address. Pkt4Ptr query4 = createQuery4(randomKey(HWAddr::ETHERNET_HWADDR_LEN)); // Every single query mist be in scope. ASSERT_TRUE(filter.inScope(query4, scope_class)); } // However, the one that lacks HW address and client id should be out of // scope. Pkt4Ptr query4(new Pkt4(DHCPDISCOVER, 1234)); EXPECT_FALSE(filter.inScope(query4, scope_class)); } // This test verifies that client identifier is used for load balancing. TEST_F(QueryFilterTest, loadBalancingClientIdThisPrimary) { HAConfigPtr config = createValidConfiguration(); QueryFilter filter(config); // By default the server1 should serve its own scope only. The // server2 should serve its scope. EXPECT_TRUE(filter.amServingScope("server1")); EXPECT_FALSE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); // Fixed HW address used in tests. std::vector<uint8_t> hw_address(HWAddr::ETHERNET_HWADDR_LEN); // Count number of in scope packets. unsigned in_scope = 0; // Set the test size - 65535 queries. const unsigned queries_num = 65535; std::string scope_class; for (unsigned i = 0; i < queries_num; ++i) { // Create query with random client identifier. Pkt4Ptr query4 = createQuery4(hw_address, randomKey(8)); // If the query is in scope, increase the counter of packets in scope. if (filter.inScope(query4, scope_class)) { ASSERT_EQ("HA_server1", scope_class); ASSERT_NE(scope_class, "HA_server2"); ++in_scope; } } // We should have roughly 50/50 split of in scope and out of scope queries. // However, we don't know exactly how many. To be safe we simply assume that // we got more than 25% of in scope and more than 25% out of scope queries. EXPECT_GT(in_scope, static_cast<unsigned>(queries_num / 4)); EXPECT_GT(queries_num - in_scope, static_cast<unsigned>(queries_num / 4)); // Simulate failover scenario. filter.serveFailoverScopes(); // In the failover case, the server1 should also take responsibility for // the server2's queries. EXPECT_TRUE(filter.amServingScope("server1")); EXPECT_TRUE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); // Repeat the test, but this time all should be in scope. for (unsigned i = 0; i < queries_num; ++i) { // Create query with random client identifier. Pkt4Ptr query4 = createQuery4(hw_address, randomKey(8)); // Every single query mist be in scope. ASSERT_TRUE(filter.inScope(query4, scope_class)); } } // This test verifies the case when load balancing is enabled and // this server is secondary. TEST_F(QueryFilterTest, loadBalancingThisSecondary) { HAConfigPtr config = createValidConfiguration(); // We're now a secondary server. config->setThisServerName("server2"); QueryFilter filter(config); // By default the server2 should serve its own scope only. The // server1 should serve its scope. EXPECT_FALSE(filter.amServingScope("server1")); EXPECT_TRUE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); // Count number of in scope packets. unsigned in_scope = 0; // Set the test size - 65535 queries. const unsigned queries_num = 65535; std::string scope_class; for (unsigned i = 0; i < queries_num; ++i) { // Create query with random HW address. Pkt4Ptr query4 = createQuery4(randomKey(HWAddr::ETHERNET_HWADDR_LEN)); // If the query is in scope, increase the counter of packets in scope. if (filter.inScope(query4, scope_class)) { ASSERT_EQ("HA_server2", scope_class); ASSERT_NE(scope_class, "HA_server1"); ++in_scope; } } // We should have roughly 50/50 split of in scope and out of scope queries. // However, we don't know exactly how many. To be safe we simply assume that // we got more than 25% of in scope and more than 25% out of scope queries. EXPECT_GT(in_scope, static_cast<unsigned>(queries_num / 4)); EXPECT_GT(queries_num - in_scope, static_cast<unsigned>(queries_num / 4)); // Simulate failover scenario. filter.serveFailoverScopes(); // In this scenario, the server1 died, so the server2 should now serve // both scopes. EXPECT_TRUE(filter.amServingScope("server1")); EXPECT_TRUE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); // Repeat the test, but this time all should be in scope. for (unsigned i = 0; i < queries_num; ++i) { // Create query with random HW address. Pkt4Ptr query4 = createQuery4(randomKey(HWAddr::ETHERNET_HWADDR_LEN)); // Every single query must be in scope. ASSERT_TRUE(filter.inScope(query4, scope_class)); } } // This test verifies the case when load balancing is enabled and // this server is backup. /// @todo Expand these tests once we implement the actual load balancing to /// verify which packets are in scope. TEST_F(QueryFilterTest, loadBalancingThisBackup) { HAConfigPtr config = createValidConfiguration(); config->setThisServerName("server3"); QueryFilter filter(config); // The backup server doesn't handle any DHCP traffic by default. EXPECT_FALSE(filter.amServingScope("server1")); EXPECT_FALSE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); // Set the test size - 65535 queries. const unsigned queries_num = 65535; std::string scope_class; for (unsigned i = 0; i < queries_num; ++i) { // Create query with random HW address. Pkt4Ptr query4 = createQuery4(randomKey(HWAddr::ETHERNET_HWADDR_LEN)); // None of the packets should be handlded by the backup server. ASSERT_FALSE(filter.inScope(query4, scope_class)); } // Simulate failover. Although, backup server never starts handling // other server's traffic automatically, it can be manually instructed // to do so. This simulates such scenario. filter.serveFailoverScopes(); // The backup server now handles traffic of server 1 and server 2. EXPECT_TRUE(filter.amServingScope("server1")); EXPECT_TRUE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); // Repeat the test, but this time all should be in scope. for (unsigned i = 0; i < queries_num; ++i) { // Create query with random HW address. Pkt4Ptr query4 = createQuery4(randomKey(HWAddr::ETHERNET_HWADDR_LEN)); // Every single query must be in scope. ASSERT_TRUE(filter.inScope(query4, scope_class)); } } // This test verifies the case when hot-standby is enabled and this // server is primary. TEST_F(QueryFilterTest, hotStandbyThisPrimary) { HAConfigPtr config = createValidConfiguration(); config->setHAMode("hot-standby"); config->getPeerConfig("server2")->setRole("standby"); QueryFilter filter(config); Pkt4Ptr query4 = createQuery4("11:22:33:44:55:66"); // By default, only the primary server is active. EXPECT_TRUE(filter.amServingScope("server1")); EXPECT_FALSE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); std::string scope_class; // It should process its queries. EXPECT_TRUE(filter.inScope(query4, scope_class)); // Simulate failover scenario, in which the active server detects a // failure of the standby server. This doesn't change anything in how // the traffic is distributed. filter.serveFailoverScopes(); // The server1 continues to process its own traffic. EXPECT_TRUE(filter.amServingScope("server1")); EXPECT_FALSE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); EXPECT_TRUE(filter.inScope(query4, scope_class)); EXPECT_EQ("HA_server1", scope_class); EXPECT_NE(scope_class, "HA_server2"); } // This test verifies the case when hot-standby is enabled and this // server is standby. TEST_F(QueryFilterTest, hotStandbyThisSecondary) { HAConfigPtr config = createValidConfiguration(); config->setHAMode("hot-standby"); config->getPeerConfig("server2")->setRole("standby"); config->setThisServerName("server2"); QueryFilter filter(config); Pkt4Ptr query4 = createQuery4("11:22:33:44:55:66"); // The server2 doesn't process any queries by default. The whole // traffic is processed by the server1. EXPECT_FALSE(filter.amServingScope("server1")); EXPECT_FALSE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); std::string scope_class; EXPECT_FALSE(filter.inScope(query4, scope_class)); EXPECT_EQ("HA_server1", scope_class); EXPECT_NE(scope_class, "HA_server2"); // Simulate failover case whereby the standby server detects a // failure of the active server. filter.serveFailoverScopes(); // The server2 now handles the traffic normally handled by the // server1. EXPECT_TRUE(filter.amServingScope("server1")); EXPECT_FALSE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); EXPECT_TRUE(filter.inScope(query4, scope_class)); EXPECT_EQ("HA_server1", scope_class); EXPECT_NE(scope_class, "HA_server2"); } // This test verifies the case when hot-standby is enabled and this // server is backup. TEST_F(QueryFilterTest, hotStandbyThisBackup) { HAConfigPtr config = createValidConfiguration(); config->setHAMode("hot-standby"); config->getPeerConfig("server2")->setRole("standby"); config->setThisServerName("server3"); QueryFilter filter(config); Pkt4Ptr query4 = createQuery4("11:22:33:44:55:66"); // By default the backup server doesn't process any traffic. EXPECT_FALSE(filter.amServingScope("server1")); EXPECT_FALSE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); std::string scope_class; EXPECT_FALSE(filter.inScope(query4, scope_class)); // Simulate failover. Although, backup server never starts handling // other server's traffic automatically, it can be manually instructed // to do so. This simulates such scenario. filter.serveFailoverScopes(); // The backup server now handles the entire traffic, i.e. the traffic // that the primary server handles. EXPECT_TRUE(filter.amServingScope("server1")); EXPECT_FALSE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); EXPECT_TRUE(filter.inScope(query4, scope_class)); } // This test verifies the case when load balancing is enabled and // this DHCPv6 server is primary. TEST_F(QueryFilterTest, loadBalancingThisPrimary6) { HAConfigPtr config = createValidConfiguration(); QueryFilter filter(config); // By default the server1 should serve its own scope only. The // server2 should serve its scope. EXPECT_TRUE(filter.amServingScope("server1")); EXPECT_FALSE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); // Count number of in scope packets. unsigned in_scope = 0; // Set the test size - 65535 queries. const unsigned queries_num = 65535; std::string scope_class; for (unsigned i = 0; i < queries_num; ++i) { // Create query with random DUID. Pkt6Ptr query6 = createQuery6(randomKey(10)); // If the query is in scope, increase the counter of packets in scope. if (filter.inScope(query6, scope_class)) { ASSERT_EQ("HA_server1", scope_class); ASSERT_NE(scope_class, "HA_server2"); ++in_scope; } } // We should have roughly 50/50 split of in scope and out of scope queries. // However, we don't know exactly how many. To be safe we simply assume that // we got more than 25% of in scope and more than 25% out of scope queries. EXPECT_GT(in_scope, static_cast<unsigned>(queries_num / 4)); EXPECT_GT(queries_num - in_scope, static_cast<unsigned>(queries_num / 4)); // Simulate failover scenario. filter.serveFailoverScopes(); // In the failover case, the server1 should also take responsibility for // the server2's queries. EXPECT_TRUE(filter.amServingScope("server1")); EXPECT_TRUE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); // Repeat the test, but this time all should be in scope. for (unsigned i = 0; i < queries_num; ++i) { // Create query with random HW address. Pkt6Ptr query6 = createQuery6(randomKey(10)); // Every single query mist be in scope. ASSERT_TRUE(filter.inScope(query6, scope_class)); } // However, the one that lacks DUID should be out of scope. Pkt6Ptr query6(new Pkt6(DHCPV6_SOLICIT, 1234)); EXPECT_FALSE(filter.inScope(query6, scope_class)); } // This test verifies the case when load balancing is enabled and // this server is secondary. TEST_F(QueryFilterTest, loadBalancingThisSecondary6) { HAConfigPtr config = createValidConfiguration(); // We're now a secondary server. config->setThisServerName("server2"); QueryFilter filter(config); // By default the server2 should serve its own scope only. The // server1 should serve its scope. EXPECT_FALSE(filter.amServingScope("server1")); EXPECT_TRUE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); // Count number of in scope packets. unsigned in_scope = 0; // Set the test size - 65535 queries. const unsigned queries_num = 65535; std::string scope_class; for (unsigned i = 0; i < queries_num; ++i) { // Create query with random HW address. Pkt6Ptr query6 = createQuery6(randomKey(10)); // If the query is in scope, increase the counter of packets in scope. if (filter.inScope(query6, scope_class)) { ASSERT_EQ("HA_server2", scope_class); ASSERT_NE(scope_class, "HA_server1"); ++in_scope; } } // We should have roughly 50/50 split of in scope and out of scope queries. // However, we don't know exactly how many. To be safe we simply assume that // we got more than 25% of in scope and more than 25% out of scope queries. EXPECT_GT(in_scope, static_cast<unsigned>(queries_num / 4)); EXPECT_GT(queries_num - in_scope, static_cast<unsigned>(queries_num / 4)); // Simulate failover scenario. filter.serveFailoverScopes(); // In this scenario, the server1 died, so the server2 should now serve // both scopes. EXPECT_TRUE(filter.amServingScope("server1")); EXPECT_TRUE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); // Repeat the test, but this time all should be in scope. for (unsigned i = 0; i < queries_num; ++i) { // Create query with random HW address. Pkt6Ptr query6 = createQuery6(randomKey(HWAddr::ETHERNET_HWADDR_LEN)); // Every single query must be in scope. ASSERT_TRUE(filter.inScope(query6, scope_class)); } } // This test verifies the case when load balancing is enabled and // this server is backup. /// @todo Expand these tests once we implement the actual load balancing to /// verify which packets are in scope. TEST_F(QueryFilterTest, loadBalancingThisBackup6) { HAConfigPtr config = createValidConfiguration(); config->setThisServerName("server3"); QueryFilter filter(config); // The backup server doesn't handle any DHCP traffic by default. EXPECT_FALSE(filter.amServingScope("server1")); EXPECT_FALSE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); // Set the test size - 65535 queries. const unsigned queries_num = 65535; std::string scope_class; for (unsigned i = 0; i < queries_num; ++i) { // Create query with random HW address. Pkt6Ptr query6 = createQuery6(randomKey(10)); // None of the packets should be handlded by the backup server. ASSERT_FALSE(filter.inScope(query6, scope_class)); } // Simulate failover. Although, backup server never starts handling // other server's traffic automatically, it can be manually instructed // to do so. This simulates such scenario. filter.serveFailoverScopes(); // The backup server now handles traffic of server 1 and server 2. EXPECT_TRUE(filter.amServingScope("server1")); EXPECT_TRUE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); // Repeat the test, but this time all should be in scope. for (unsigned i = 0; i < queries_num; ++i) { // Create query with random HW address. Pkt6Ptr query6 = createQuery6(randomKey(10)); // Every single query must be in scope. ASSERT_TRUE(filter.inScope(query6, scope_class)); } } // This test verifies the case when hot-standby is enabled and this // server is primary. TEST_F(QueryFilterTest, hotStandbyThisPrimary6) { HAConfigPtr config = createValidConfiguration(); config->setHAMode("hot-standby"); config->getPeerConfig("server2")->setRole("standby"); QueryFilter filter(config); Pkt6Ptr query6 = createQuery6("01:02:11:22:33:44:55:66"); // By default, only the primary server is active. EXPECT_TRUE(filter.amServingScope("server1")); EXPECT_FALSE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); std::string scope_class; // It should process its queries. EXPECT_TRUE(filter.inScope(query6, scope_class)); // Simulate failover scenario, in which the active server detects a // failure of the standby server. This doesn't change anything in how // the traffic is distributed. filter.serveFailoverScopes(); // The server1 continues to process its own traffic. EXPECT_TRUE(filter.amServingScope("server1")); EXPECT_FALSE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); EXPECT_TRUE(filter.inScope(query6, scope_class)); EXPECT_EQ("HA_server1", scope_class); EXPECT_NE(scope_class, "HA_server2"); } // This test verifies the case when hot-standby is enabled and this // server is standby. TEST_F(QueryFilterTest, hotStandbyThisSecondary6) { HAConfigPtr config = createValidConfiguration(); config->setHAMode("hot-standby"); config->getPeerConfig("server2")->setRole("standby"); config->setThisServerName("server2"); QueryFilter filter(config); Pkt6Ptr query6 = createQuery6("01:02:11:22:33:44:55:66"); // The server2 doesn't process any queries by default. The whole // traffic is processed by the server1. EXPECT_FALSE(filter.amServingScope("server1")); EXPECT_FALSE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); std::string scope_class; EXPECT_FALSE(filter.inScope(query6, scope_class)); EXPECT_EQ("HA_server1", scope_class); EXPECT_NE(scope_class, "HA_server2"); // Simulate failover case whereby the standby server detects a // failure of the active server. filter.serveFailoverScopes(); // The server2 now handles the traffic normally handled by the // server1. EXPECT_TRUE(filter.amServingScope("server1")); EXPECT_FALSE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); EXPECT_TRUE(filter.inScope(query6, scope_class)); EXPECT_EQ("HA_server1", scope_class); EXPECT_NE(scope_class, "HA_server2"); } // This test verifies that it is possible to explicitly enable and // disable certain scopes. TEST_F(QueryFilterTest, explicitlyServeScopes) { HAConfigPtr config = createValidConfiguration(); QueryFilter filter(config); // Initially, the scopes should be set according to the load // balancing configuration. EXPECT_TRUE(filter.amServingScope("server1")); EXPECT_FALSE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); // Enable "server2" scope. ASSERT_NO_THROW(filter.serveScope("server2")); EXPECT_TRUE(filter.amServingScope("server1")); EXPECT_TRUE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); // Enable only "server2" scope. ASSERT_NO_THROW(filter.serveScopeOnly("server2")); EXPECT_FALSE(filter.amServingScope("server1")); EXPECT_TRUE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); // Explicitly enable selected scopes. ASSERT_NO_THROW(filter.serveScopes({ "server1", "server3" })); EXPECT_TRUE(filter.amServingScope("server1")); EXPECT_FALSE(filter.amServingScope("server2")); EXPECT_TRUE(filter.amServingScope("server3")); // Revert to defaults. ASSERT_NO_THROW(filter.serveDefaultScopes()); EXPECT_TRUE(filter.amServingScope("server1")); EXPECT_FALSE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); // Disable all scopes. ASSERT_NO_THROW(filter.serveNoScopes()); EXPECT_FALSE(filter.amServingScope("server1")); EXPECT_FALSE(filter.amServingScope("server2")); EXPECT_FALSE(filter.amServingScope("server3")); // Test negative cases. EXPECT_THROW(filter.serveScope("unsupported"), BadValue); EXPECT_THROW(filter.serveScopeOnly("unsupported"), BadValue); EXPECT_THROW(filter.serveScopes({ "server1", "unsupported" }), BadValue); } }
38.0919
80
0.702678
mcr
36e8b5bf3ef22888bb6e6902762aa3c7ca325007
651
cpp
C++
tests/src/test_FeatureKey.cpp
paddy74/lowletorfeats
9305554d6af1bf156fccae1f383b83f32445275b
[ "MIT" ]
null
null
null
tests/src/test_FeatureKey.cpp
paddy74/lowletorfeats
9305554d6af1bf156fccae1f383b83f32445275b
[ "MIT" ]
2
2019-04-23T17:24:04.000Z
2019-04-23T17:28:46.000Z
tests/src/test_FeatureKey.cpp
paddy74/lowletorfeats
9305554d6af1bf156fccae1f383b83f32445275b
[ "MIT" ]
null
null
null
#include <lowletorfeats/base/FeatureKey.hpp> int main() { // Test constructors lowletorfeats::base::FeatureKey fKey; fKey = lowletorfeats::base::FeatureKey(fKey); fKey = lowletorfeats::base::FeatureKey("invalid.invalid.invalid"); fKey = lowletorfeats::base::FeatureKey("invalid", "invalid", "invalid"); fKey = lowletorfeats::base::FeatureKey("tfidf", "tfidf", "full"); // Test public methods fKey.changeKey("okapi.bm25.body"); fKey.toString(); fKey.toHash(); fKey.getFType(); fKey.getFName(); fKey.getFSection(); fKey.getVType(); fKey.getVName(); fKey.getVSection(); return 0; }
25.038462
76
0.652842
paddy74
36ec61a33a3fde0b7b74289192ccf13c8e08b6cb
507
hpp
C++
src/base/LogHandler.hpp
coderkd10/EternalTerminal
d15bb726d987bd147480125d694de44a2ea6ce83
[ "Apache-2.0" ]
3
2019-08-09T10:44:51.000Z
2019-11-06T00:21:23.000Z
src/base/LogHandler.hpp
coderkd10/EternalTerminal
d15bb726d987bd147480125d694de44a2ea6ce83
[ "Apache-2.0" ]
null
null
null
src/base/LogHandler.hpp
coderkd10/EternalTerminal
d15bb726d987bd147480125d694de44a2ea6ce83
[ "Apache-2.0" ]
2
2019-09-22T12:58:00.000Z
2019-10-02T13:25:01.000Z
#ifndef __ET_LOG_HANDLER__ #define __ET_LOG_HANDLER__ #include "Headers.hpp" namespace et { class LogHandler { public: static el::Configurations setupLogHandler(int *argc, char ***argv); static void setupLogFile(el::Configurations *defaultConf, string filename, string maxlogsize = "20971520"); static void rolloutHandler(const char *filename, std::size_t size); static string stderrToFile(const string &pathPrefix); }; } // namespace et #endif // __ET_LOG_HANDLER__
29.823529
76
0.727811
coderkd10
36edc45801b2a8d45231f91a54027d633c065ded
1,686
cpp
C++
Mystring.cpp
hahafeijidawang/MyString
9a519e6f13f96d0a7f6dac962e465f9fc7f833d9
[ "MIT" ]
null
null
null
Mystring.cpp
hahafeijidawang/MyString
9a519e6f13f96d0a7f6dac962e465f9fc7f833d9
[ "MIT" ]
null
null
null
Mystring.cpp
hahafeijidawang/MyString
9a519e6f13f96d0a7f6dac962e465f9fc7f833d9
[ "MIT" ]
null
null
null
#include<iostream> #include<Mystring.h> #include<string.h> #include<stdio.h> using namespace std; MyString::MyString(){ //无参构成一个空串 m_len=0; m_p=new char[m_len+1]; strcpy(m_p,""); } MyString::MyString(const char *p){ if(p==NULL){ m_len=0; m_p=new char[m_len+1]; strcpy(m_p,""); }else{ m_len=strlen(p); m_p=new char[m_len+1]; strcpy(m_p,p); } } //拷贝构造函数。 MyString::MyString(const MyString& s){ m_len=s.m_len; m_p=new char[m_len+1]; strcpy(m_p,s.m_p); } MyString::~MyString(){ if(m_p!=NULL){ delete [] m_p; m_p = NULL; m_len = 0; } } void MyString::printCom(){ cout<<"m_len:"<<m_len<<endl; cout<<"m_p:"<<endl; cout<< m_p<<endl; } MyString& MyString::operator=(const char *p){ if(p!=NULL){ m_len =strlen(p); cout<<"hhhh"<<endl; m_p = new char[strlen(p)+1]; strcpy(m_p,p); } else{ m_len=0; m_p =new char[strlen(p)+1]; strcpy(m_p,""); } return *this; } MyString& MyString::operator=(const MyString& s){ m_len = s.m_len; cout<<"dhdhfh"<<endl; m_p = new char[strlen(s.m_p)+1]; strcpy(m_p,s.m_p); return *this; } char& MyString:: operator[]( int i){ return m_p[i]; } ostream& operator <<(ostream& out, MyString& s){ out<<"m_len:"<<s.m_len<<endl; out<<"*m_p:"<<s.m_p<<endl; return out; } istream& operator >>(istream& in, MyString& s){ in>>s.m_len; return in; }
11.315436
51
0.488731
hahafeijidawang
36ef7a08ca71c7c28ceef8b7c12e8fecad20c317
8,008
cpp
C++
KDIS/DataTypes/GED_EnhancedGroundCombatSoldier.cpp
TangramFlex/KDIS_Fork
698d81a2de8b6df3fc99bb31b9d31eaa5368fda4
[ "BSD-2-Clause" ]
null
null
null
KDIS/DataTypes/GED_EnhancedGroundCombatSoldier.cpp
TangramFlex/KDIS_Fork
698d81a2de8b6df3fc99bb31b9d31eaa5368fda4
[ "BSD-2-Clause" ]
null
null
null
KDIS/DataTypes/GED_EnhancedGroundCombatSoldier.cpp
TangramFlex/KDIS_Fork
698d81a2de8b6df3fc99bb31b9d31eaa5368fda4
[ "BSD-2-Clause" ]
null
null
null
/********************************************************************* Copyright 2013 Karl Jones 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. For Further Information Please Contact me at [email protected] http://p.sf.net/kdis/UserGuide *********************************************************************/ #include "./GED_EnhancedGroundCombatSoldier.h" using namespace KDIS; using namespace DATA_TYPE; using namespace ENUMS; ////////////////////////////////////////////////////////////////////////// // Public: ////////////////////////////////////////////////////////////////////////// GED_EnhancedGroundCombatSoldier::GED_EnhancedGroundCombatSoldier() : m_ui8WaterStatus( 0 ), m_ui8RestStatus( 0 ), m_ui8PriAmmun( 0 ), m_ui8SecAmmun( 0 ) { } ////////////////////////////////////////////////////////////////////////// GED_EnhancedGroundCombatSoldier::GED_EnhancedGroundCombatSoldier( KDataStream & stream ) { Decode( stream ); } ////////////////////////////////////////////////////////////////////////// GED_EnhancedGroundCombatSoldier::GED_EnhancedGroundCombatSoldier( KUINT16 ID, KINT16 XOffset, KINT16 YOffset, KINT16 ZOffset, const EntityAppearance & EA, KINT8 Psi, KINT8 Theta, KINT8 Phi, KINT8 Speed, KINT8 HeadAzimuth, KINT8 HeadElevation, KINT8 HeadScanRate, KINT8 HeadElevationRate, KUINT8 WaterStatus, RestStatus R, KUINT8 PrimaryAmmunition, KUINT8 SecondaryAmmunition ) : GED_BasicGroundCombatSoldier( ID, XOffset, YOffset, ZOffset, EA, Psi, Theta, Phi, Speed, HeadAzimuth, HeadElevation, HeadScanRate, HeadElevationRate ), m_ui8WaterStatus( WaterStatus ), m_ui8RestStatus( R ), m_ui8PriAmmun( PrimaryAmmunition ), m_ui8SecAmmun( SecondaryAmmunition ) { } ////////////////////////////////////////////////////////////////////////// GED_EnhancedGroundCombatSoldier::GED_EnhancedGroundCombatSoldier( const GED_BasicGroundCombatSoldier & BGCS, KUINT8 WaterStatus, RestStatus R, KUINT8 PrimaryAmmunition, KUINT8 SecondaryAmmunition ) : GED_BasicGroundCombatSoldier( BGCS ), m_ui8WaterStatus( WaterStatus ), m_ui8RestStatus( R ), m_ui8PriAmmun( PrimaryAmmunition ), m_ui8SecAmmun( SecondaryAmmunition ) { } ////////////////////////////////////////////////////////////////////////// GED_EnhancedGroundCombatSoldier::~GED_EnhancedGroundCombatSoldier() { } ////////////////////////////////////////////////////////////////////////// GroupedEntityCategory GED_EnhancedGroundCombatSoldier::GetGroupedEntityCategory() const { return EnhancedGroundCombatSoldierGEC; } ////////////////////////////////////////////////////////////////////////// KUINT8 GED_EnhancedGroundCombatSoldier::GetLength() const { return GED_ENHANCED_GROUND_COMBAT_SOLDIER_SIZE; } ////////////////////////////////////////////////////////////////////////// void GED_EnhancedGroundCombatSoldier::SetWaterStatus( KUINT8 W ) { m_ui8WaterStatus = W; } ////////////////////////////////////////////////////////////////////////// KUINT8 GED_EnhancedGroundCombatSoldier::GetWaterStatus() const { return m_ui8WaterStatus; } ////////////////////////////////////////////////////////////////////////// void GED_EnhancedGroundCombatSoldier::SetRestStatus( RestStatus R ) { m_ui8RestStatus = R; } ////////////////////////////////////////////////////////////////////////// RestStatus GED_EnhancedGroundCombatSoldier::GetRestStatus() const { return ( RestStatus )m_ui8RestStatus; } ////////////////////////////////////////////////////////////////////////// void GED_EnhancedGroundCombatSoldier::SetPrimaryAmmunition( KUINT8 P ) { m_ui8PriAmmun = P; } ////////////////////////////////////////////////////////////////////////// KUINT8 GED_EnhancedGroundCombatSoldier::GetPrimaryAmmunition() const { return m_ui8PriAmmun; } ////////////////////////////////////////////////////////////////////////// void GED_EnhancedGroundCombatSoldier::SetSecondaryAmmunition( KUINT8 S ) { m_ui8SecAmmun = S; } ////////////////////////////////////////////////////////////////////////// KUINT8 GED_EnhancedGroundCombatSoldier::GetSecondaryAmmunition() const { return m_ui8SecAmmun; } ////////////////////////////////////////////////////////////////////////// KString GED_EnhancedGroundCombatSoldier::GetAsString() const { KStringStream ss; ss << GED_BasicGroundCombatSoldier::GetAsString(); ss << "GED Enhanced Ground Combat Vehicle\n" << "\tWater Status: " << ( KUINT16 )m_ui8WaterStatus << " ounce/s\n" << "\tRest Status: " << GetEnumAsStringRestStatus( m_ui8RestStatus ) << "\n" << "\tPrimary Ammunition: " << ( KUINT16 )m_ui8PriAmmun << "\n" << "\tSecondary Ammunition: " << ( KUINT16 )m_ui8SecAmmun << "\n"; return ss.str(); } ////////////////////////////////////////////////////////////////////////// void GED_EnhancedGroundCombatSoldier::Decode( KDataStream & stream ) { if( stream.GetBufferSize() < GED_ENHANCED_GROUND_COMBAT_SOLDIER_SIZE )throw KException( __FUNCTION__, NOT_ENOUGH_DATA_IN_BUFFER ); GED_BasicGroundCombatSoldier::Decode( stream ); stream >> m_ui8WaterStatus >> m_ui8RestStatus >> m_ui8PriAmmun >> m_ui8SecAmmun; } ////////////////////////////////////////////////////////////////////////// KDataStream GED_EnhancedGroundCombatSoldier::Encode() const { KDataStream stream; GED_EnhancedGroundCombatSoldier::Encode( stream ); return stream; } ////////////////////////////////////////////////////////////////////////// void GED_EnhancedGroundCombatSoldier::Encode( KDataStream & stream ) const { GED_BasicGroundCombatSoldier::Encode( stream ); stream << m_ui8WaterStatus << m_ui8RestStatus << m_ui8PriAmmun << m_ui8SecAmmun; } ////////////////////////////////////////////////////////////////////////// KBOOL GED_EnhancedGroundCombatSoldier::operator == ( const GED_EnhancedGroundCombatSoldier & Value ) const { if( GED_BasicGroundCombatSoldier::operator!=( Value ) ) return false; if( m_ui8WaterStatus != Value.m_ui8WaterStatus ) return false; if( m_ui8RestStatus != Value.m_ui8RestStatus ) return false; if( m_ui8PriAmmun != Value.m_ui8PriAmmun ) return false; if( m_ui8SecAmmun != Value.m_ui8SecAmmun ) return false; return true; } ////////////////////////////////////////////////////////////////////////// KBOOL GED_EnhancedGroundCombatSoldier::operator != ( const GED_EnhancedGroundCombatSoldier & Value ) const { return !( *this == Value ); } //////////////////////////////////////////////////////////////////////////
34.222222
154
0.567932
TangramFlex
36ef9e7917fb0a0d32dacf6edecf22c33551d246
13,358
cpp
C++
Cappuccino/src/Cappuccino/Mesh.cpp
Promethaes/CappuccinoEngine
e0e2dacaf14c8176d4fbc0d85645783e364a06a4
[ "MIT" ]
5
2019-10-25T11:51:08.000Z
2020-01-09T00:56:24.000Z
Cappuccino/src/Cappuccino/Mesh.cpp
Promethaes/CappuccinoEngine
e0e2dacaf14c8176d4fbc0d85645783e364a06a4
[ "MIT" ]
145
2019-09-10T18:33:49.000Z
2020-02-02T09:59:23.000Z
Cappuccino/src/Cappuccino/Mesh.cpp
Promethaes/CappuccinoEngine
e0e2dacaf14c8176d4fbc0d85645783e364a06a4
[ "MIT" ]
null
null
null
#include "Cappuccino/Mesh.h" #include "Cappuccino/CappMacros.h" #include "Cappuccino/ResourceManager.h" #include <glad/glad.h> #include <glm/glm.hpp> #include <algorithm> #include <fstream> #include <iostream> #include <sstream> using string = std::string; namespace Cappuccino { struct FaceData { unsigned vertexData[3]{}; unsigned textureData[3]{}; unsigned normalData[3]{}; }; std::string Mesh::_meshDirectory = "./Assets/Meshes/"; Mesh::Mesh(const std::string& name, const std::string& path) : _path(path), _name(name) {} Mesh::~Mesh() { glDeleteVertexArrays(1, &_VAO); } Mesh::Mesh(const std::vector<float>& VERTS, const std::vector<float>& TEXTS, const std::vector<float>& NORMS, const std::vector<float>& TANGS) { verts = VERTS; texts = TEXTS; norms = NORMS; tangs = TANGS; } Mesh::Mesh(Mesh& other) { verts = other.verts; texts = other.texts; norms = other.norms; tangs = other.tangs; _numVerts = other._numVerts; _numFaces = other._numFaces; } bool Mesh::loadMesh() { if (loaded) return true; char inputString[128]; std::vector<glm::vec3> vertexData{}; std::vector<glm::vec2> textureData{}; std::vector<glm::vec3> normalData{}; std::vector<FaceData> faces{}; std::vector<float> unPvertexData{}; std::vector<float> unPtextureData{}; std::vector<float> unPnormalData{}; //load the file std::ifstream input{}; input.open(_meshDirectory + _path); if (!input.good()) { std::cout << "Problem loading file: " << _path << "\n"; return false; } //import data while (!input.eof()) { input.getline(inputString, 128); //vertex data if (inputString[0] == 'v' && inputString[1] == ' ') { glm::vec3 vertData{ 0,0,0 }; std::sscanf(inputString, "v %f %f %f", &vertData.x, &vertData.y, &vertData.z); vertexData.push_back(vertData); }//texture data else if (inputString[0] == 'v' && inputString[1] == 't') { glm::vec2 texCoord{ 0,0 }; std::sscanf(inputString, "vt %f %f", &texCoord.x, &texCoord.y); textureData.push_back(texCoord); }//normal data else if (inputString[0] == 'v' && inputString[1] == 'n') { glm::vec3 normData{ 0,0,0 }; std::sscanf(inputString, "vn %f %f %f", &normData.x, &normData.y, &normData.z); normalData.push_back(normData); }//face data else if (inputString[0] == 'f' && inputString[1] == ' ') { faces.emplace_back(); std::sscanf(inputString, "f %u/%u/%u %u/%u/%u %u/%u/%u", &faces.back().vertexData[0], &faces.back().textureData[0], &faces.back().normalData[0], &faces.back().vertexData[1], &faces.back().textureData[1], &faces.back().normalData[1], &faces.back().vertexData[2], &faces.back().textureData[2], &faces.back().normalData[2]); } else continue; } //add the data to the vectors for (unsigned i = 0; i < faces.size(); i++) { for (unsigned j = 0; j < 3; j++) { unPvertexData.push_back(vertexData[faces[i].vertexData[j] - 1].x); unPvertexData.push_back(vertexData[faces[i].vertexData[j] - 1].y); unPvertexData.push_back(vertexData[faces[i].vertexData[j] - 1].z); if (!textureData.empty()) { unPtextureData.push_back(textureData[faces[i].textureData[j] - 1].x); unPtextureData.push_back(textureData[faces[i].textureData[j] - 1].y); } if (!normalData.empty()) { unPnormalData.push_back(normalData[faces[i].normalData[j] - 1].x); unPnormalData.push_back(normalData[faces[i].normalData[j] - 1].y); unPnormalData.push_back(normalData[faces[i].normalData[j] - 1].z); } } } _numFaces = faces.size(); _numVerts = _numFaces * 3; //https://learnopengl.com/Advanced-Lighting/Normal-Mapping //https://gitlab.com/ShawnM427/florp/blob/master/src/florp/graphics/MeshBuilder.cpp //it works! std::vector<glm::vec3> tangs; for (unsigned i = 0; i < _numFaces; i++) { std::vector<glm::vec3> tCalcPos; std::vector<glm::vec2> tCalcUV; for (unsigned j = 0; j < 3; j++) { tCalcPos.push_back(vertexData[faces[i].vertexData[j] - 1]); tCalcUV.push_back(textureData[faces[i].textureData[j] - 1]); } glm::vec3 deltaPos = tCalcPos[1] - tCalcPos[0]; glm::vec3 deltaPos2 = tCalcPos[2] - tCalcPos[0]; glm::vec2 deltaUV = tCalcUV[1] - tCalcUV[0]; glm::vec2 deltaUV2 = tCalcUV[2] - tCalcUV[0]; float f = 1.0f / (deltaUV.x * deltaUV2.y - deltaUV.y * deltaUV2.x); glm::vec3 tang = (deltaPos * deltaUV2.y - deltaPos2 * deltaUV.y) * f; for (unsigned j = 0; j < 3; j++) { tangs.push_back(tang); } } for (unsigned i = 0; i < unPvertexData.size(); i++) { master.push_back(unPvertexData[i]); verts.push_back(unPvertexData[i]); } for (unsigned i = 0; i < unPtextureData.size(); i++) { master.push_back(unPtextureData[i]); texts.push_back(unPtextureData[i]); } for (unsigned i = 0; i < unPnormalData.size(); i++) { master.push_back(unPnormalData[i]); norms.push_back(unPnormalData[i]); } for (unsigned i = 0; i < tangs.size(); i++) { master.push_back(tangs[i].x); master.push_back(tangs[i].y); master.push_back(tangs[i].z); this->tangs.push_back(tangs[i].x); this->tangs.push_back(tangs[i].y); this->tangs.push_back(tangs[i].z); } glGenVertexArrays(1, &_VAO); glGenBuffers(1, &_VBO); //binding the vao glBindVertexArray(_VAO); //enable slots glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); glEnableVertexAttribArray(3); glEnableVertexAttribArray(4); glEnableVertexAttribArray(5); glEnableVertexAttribArray(6); glBindBuffer(GL_ARRAY_BUFFER, _VBO); //vertex glBufferData(GL_ARRAY_BUFFER, master.size() * sizeof(float), &master[0], GL_STATIC_DRAW); //verts glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); //texts glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void*)(unPvertexData.size() * sizeof(float))); //norms glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((unPtextureData.size() + unPvertexData.size()) * sizeof(float))); //tangents glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((unPtextureData.size() + unPvertexData.size() + unPnormalData.size()) * sizeof(float))); glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glVertexAttribPointer(5, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((unPtextureData.size() + unPvertexData.size()) * sizeof(float))); glVertexAttribPointer(6, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((unPtextureData.size() + unPvertexData.size() + unPnormalData.size()) * sizeof(float))); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); input.close(); return loaded = true; } void Mesh::loadFromData() { master.clear(); for (unsigned i = 0; i < verts.size(); i++) master.push_back(verts[i]); for (unsigned i = 0; i < texts.size(); i++) master.push_back(texts[i]); for (unsigned i = 0; i < norms.size(); i++) master.push_back(norms[i]); for (unsigned i = 0; i < tangs.size(); i++) master.push_back(tangs[i]); glGenVertexArrays(1, &_VAO); glGenBuffers(1, &_VBO); glBindVertexArray(_VAO); //enable slots glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); glEnableVertexAttribArray(3); glEnableVertexAttribArray(4); glEnableVertexAttribArray(5); glEnableVertexAttribArray(6); glBindBuffer(GL_ARRAY_BUFFER, _VBO); //vertex glBufferData(GL_ARRAY_BUFFER, master.size() * sizeof(float), &master[0], GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void*)(verts.size() * sizeof(float))); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((texts.size() + verts.size()) * sizeof(float))); glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((texts.size() + verts.size() + norms.size()) * sizeof(float))); glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glVertexAttribPointer(5, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((texts.size() + verts.size()) * sizeof(float))); glVertexAttribPointer(6, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((texts.size() + verts.size() + norms.size()) * sizeof(float))); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); loaded = true; } void Mesh::animationFunction(Mesh& other, bool shouldPlay) { glBindVertexArray(_VAO); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); glEnableVertexAttribArray(3); glEnableVertexAttribArray(4); glEnableVertexAttribArray(5); glEnableVertexAttribArray(6); glBindBuffer(GL_ARRAY_BUFFER, _VBO); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void*)(verts.size() * sizeof(float))); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((texts.size() + verts.size()) * sizeof(float))); glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((texts.size() + verts.size() + norms.size()) * sizeof(float))); glBindBuffer(GL_ARRAY_BUFFER, other._VBO); glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glVertexAttribPointer(5, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((texts.size() + verts.size()) * sizeof(float))); glVertexAttribPointer(6, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((texts.size() + verts.size() + norms.size()) * sizeof(float))); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); } void Mesh::resetVertAttribPointers() { glBindVertexArray(_VAO); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); glEnableVertexAttribArray(3); glEnableVertexAttribArray(4); glEnableVertexAttribArray(5); glEnableVertexAttribArray(6); glBindBuffer(GL_ARRAY_BUFFER, _VBO); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void*)(verts.size() * sizeof(float))); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((texts.size() + verts.size()) * sizeof(float))); glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((texts.size() + verts.size() + norms.size()) * sizeof(float))); glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glVertexAttribPointer(5, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((texts.size() + verts.size()) * sizeof(float))); glVertexAttribPointer(6, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((texts.size() + verts.size() + norms.size()) * sizeof(float))); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); } void Mesh::reload(const std::vector<float>& VERTS, const std::vector<float>& NORMS, const std::vector<float>& TANGS) { master.clear(); verts.clear(); norms.clear(); tangs.clear(); for (unsigned i = 0; i < VERTS.size(); i++) { master.push_back(VERTS[i]); verts.push_back(VERTS[i]); } for (unsigned i = 0; i < texts.size(); i++) { master.push_back(texts[i]); } for (unsigned i = 0; i < NORMS.size(); i++) { master.push_back(NORMS[i]); norms.push_back(NORMS[i]); } for (unsigned i = 0; i < TANGS.size(); i++) { master.push_back(TANGS[i]); tangs.push_back(TANGS[i]); } glBindVertexArray(_VAO); //enable slots glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); glEnableVertexAttribArray(3); glBindBuffer(GL_ARRAY_BUFFER, _VBO); //vertex glBufferSubData(GL_ARRAY_BUFFER, 0, master.size() * sizeof(float), &master[0]); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void*)(verts.size() * sizeof(float))); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((texts.size() + verts.size()) * sizeof(float))); glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((texts.size() + verts.size() + norms.size()) * sizeof(float))); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); } void Mesh::unload() { //empty the buffers glDeleteBuffers(1, &_VBO); glDeleteVertexArrays(1, &_VAO); _VBO = 0; _VAO = 0; //_numFaces = 0;//reset all numbers //_numVerts = 0; } void Mesh::draw() { glBindVertexArray(_VAO); glDrawArrays(GL_TRIANGLES, 0, _numVerts); } void Mesh::setDefaultPath(const std::string& directory) { string dir = directory; std::transform(dir.begin(), dir.end(), dir.begin(), ::tolower); if (dir == "default") _meshDirectory = "./Assets/Meshes/"; else _meshDirectory = directory; } }
32.501217
166
0.647477
Promethaes
36f12182c28662271f907f14b30cbef66baaeefe
1,586
hh
C++
util/id-types.hh
lukas-ke/faint-graphics-editor
33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf
[ "Apache-2.0" ]
10
2016-12-28T22:06:31.000Z
2021-05-24T13:42:30.000Z
util/id-types.hh
lukas-ke/faint-graphics-editor
33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf
[ "Apache-2.0" ]
4
2015-10-09T23:55:10.000Z
2020-04-04T08:09:22.000Z
util/id-types.hh
lukas-ke/faint-graphics-editor
33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf
[ "Apache-2.0" ]
null
null
null
// -*- coding: us-ascii-unix -*- // Copyright 2013 Lukas Kemmer // // 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 FAINT_ID_TYPES_HH #define FAINT_ID_TYPES_HH namespace faint{ template<int group> class FaintID{ public: FaintID(){ static int max_id = 1007; m_rawId = max_id++; } static FaintID Invalid(){ return FaintID(-1); } static FaintID DefaultID(){ return FaintID<group>(0); } bool operator==(const FaintID<group>& other) const{ return other.m_rawId == m_rawId; } bool operator!=(const FaintID<group>& other) const{ return !operator==(other); } bool operator<(const FaintID<group>& other) const{ return m_rawId < other.m_rawId; } bool operator>(const FaintID<group>& other) const{ return m_rawId > other.m_rawId; } int Raw() const{ return m_rawId; } private: explicit FaintID(int id){ m_rawId = id; } int m_rawId; }; using CanvasId = FaintID<107>; using ObjectId = FaintID<108>; using CommandId = FaintID<109>; // 110 reserved using FrameId = FaintID<111>; } // namespace #endif
22.027778
70
0.69483
lukas-ke
36f5f1cfe35ad2bc9d0cfbf58e334d7983ec3147
4,801
cc
C++
src/theia/sfm/view_graph/view_graph_test.cc
LEON-MING/TheiaSfM_Leon
8ac187b80100ad7f52fe9af49fa4a0db6db226b9
[ "BSD-3-Clause" ]
3
2019-01-17T17:37:37.000Z
2021-03-26T09:21:38.000Z
src/theia/sfm/view_graph/view_graph_test.cc
LEON-MING/TheiaSfM_Leon
8ac187b80100ad7f52fe9af49fa4a0db6db226b9
[ "BSD-3-Clause" ]
null
null
null
src/theia/sfm/view_graph/view_graph_test.cc
LEON-MING/TheiaSfM_Leon
8ac187b80100ad7f52fe9af49fa4a0db6db226b9
[ "BSD-3-Clause" ]
3
2019-09-09T03:34:20.000Z
2020-05-21T06:00:50.000Z
// Copyright (C) 2014 The Regents of the University of California (Regents). // 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 Regents or University of California 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 HOLDERS 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. // // Please contact the author of this library if you have any questions. // Author: Chris Sweeney ([email protected]) #include <unordered_map> #include <unordered_set> #include <utility> #include <vector> #include "gtest/gtest.h" #include "theia/util/hash.h" #include "theia/util/map_util.h" #include "theia/sfm/twoview_info.h" #include "theia/sfm/types.h" #include "theia/sfm/view_graph/view_graph.h" namespace theia { // This is needed for EXPECT_EQ(TwoViewInfo, TwoViewInfo); bool operator==(const TwoViewInfo& lhs, const TwoViewInfo& rhs) { return lhs.position_2 == rhs.position_2 && lhs.rotation_2 == rhs.rotation_2 && lhs.num_verified_matches == rhs.num_verified_matches; } TEST(ViewGraph, Constructor) { ViewGraph view_graph; EXPECT_EQ(view_graph.NumViews(), 0); EXPECT_EQ(view_graph.NumEdges(), 0); } TEST(ViewGraph, RemoveView) { ViewGraph graph; const ViewId view_one = 0; const ViewId view_two = 1; const TwoViewInfo edge; graph.AddEdge(view_one, view_two, edge); EXPECT_TRUE(graph.HasView(view_one)); EXPECT_TRUE(graph.HasView(view_two)); EXPECT_EQ(graph.NumEdges(), 1); graph.RemoveView(view_one); EXPECT_TRUE(!graph.HasView(view_one)); EXPECT_EQ(graph.NumViews(), 1); EXPECT_EQ(graph.NumEdges(), 0); } TEST(ViewGraph, AddEdge) { TwoViewInfo info1; info1.num_verified_matches = 1; TwoViewInfo info2; info2.num_verified_matches = 2; ViewGraph graph; graph.AddEdge(0, 1, info1); graph.AddEdge(0, 2, info2); EXPECT_EQ(graph.NumViews(), 3); EXPECT_EQ(graph.NumEdges(), 2); const std::vector<int> expected_ids = {0, 1, 2}; std::unordered_set<ViewId> view_ids = graph.ViewIds(); const auto* edge_0_1 = graph.GetEdge(0, 1); const auto* edge_0_2 = graph.GetEdge(0, 2); EXPECT_TRUE(edge_0_1 != nullptr); EXPECT_EQ(*edge_0_1, info1); EXPECT_TRUE(edge_0_2 != nullptr); EXPECT_EQ(*edge_0_2, info2); EXPECT_TRUE(graph.GetEdge(1, 2) == nullptr); const auto* edge_1_0 = graph.GetEdge(1, 0); const auto* edge_2_0 = graph.GetEdge(2, 0); EXPECT_TRUE(edge_1_0 != nullptr); EXPECT_EQ(*edge_1_0, info1); EXPECT_EQ(*edge_2_0, info2); EXPECT_TRUE(graph.GetEdge(2, 1) == nullptr); const std::unordered_set<ViewId> edge_ids = *graph.GetNeighborIdsForView(0); EXPECT_TRUE(ContainsKey(edge_ids, 1)); EXPECT_TRUE(ContainsKey(edge_ids, 2)); TwoViewInfo info3; info3.num_verified_matches = 3; graph.AddEdge(1, 2, info3); EXPECT_EQ(graph.NumViews(), 3); EXPECT_EQ(graph.NumEdges(), 3); EXPECT_TRUE(graph.GetEdge(1, 2) != nullptr); EXPECT_EQ(*graph.GetEdge(1, 2), info3); } TEST(ViewGraph, RemoveEdge) { TwoViewInfo info1; info1.num_verified_matches = 1; TwoViewInfo info2; info2.num_verified_matches = 2; ViewGraph graph; graph.AddEdge(0, 1, info1); graph.AddEdge(0, 2, info2); EXPECT_TRUE(graph.GetEdge(0, 1) != nullptr); EXPECT_TRUE(graph.GetEdge(0, 2) != nullptr); EXPECT_EQ(graph.NumViews(), 3); EXPECT_EQ(graph.NumEdges(), 2); EXPECT_TRUE(graph.RemoveEdge(0, 2)); EXPECT_EQ(graph.NumEdges(), 1); EXPECT_TRUE(graph.GetEdge(0, 2) == nullptr); } } // namespace theia
32.659864
78
0.725057
LEON-MING
36f6067521e6947e4595e9989ec5213cd4420d67
10,370
cpp
C++
Mary/Game/StyleSwitcher.cpp
wangxh1007/ddmk
a6ff276d96b663e71b3ccadabc2d92c50c18ebac
[ "Zlib" ]
null
null
null
Mary/Game/StyleSwitcher.cpp
wangxh1007/ddmk
a6ff276d96b663e71b3ccadabc2d92c50c18ebac
[ "Zlib" ]
null
null
null
Mary/Game/StyleSwitcher.cpp
wangxh1007/ddmk
a6ff276d96b663e71b3ccadabc2d92c50c18ebac
[ "Zlib" ]
null
null
null
#include "StyleSwitcher.h" uint64 Game_StyleSwitcher_counter = 0; PrivateStart; byte8 * StyleControllerProxy = 0; byte8 * GunslingerGetStyleLevel = 0; byte8 * VergilDynamicStyle = 0; void UpdateStyle(byte8 * baseAddr, uint32 index) { auto actor = System_Actor_GetActorId(baseAddr); auto & character = *(uint8 *)(baseAddr + 0x78); auto & style = *(uint32 *)(baseAddr + 0x6338); auto & level = *(uint32 *)(baseAddr + 0x6358); auto & experience = *(float32 *)(baseAddr + 0x6364); auto session = *(byte **)(appBaseAddr + 0xC90E30); if (!session) { return; } auto sessionLevel = (uint32 *)(session + 0x11C); auto sessionExperience = (float32 *)(session + 0x134); if (!((character == CHAR_DANTE) || (character == CHAR_VERGIL))) { return; } if (character == CHAR_VERGIL) { switch (index) { case STYLE_SWORDMASTER: case STYLE_GUNSLINGER: case STYLE_ROYALGUARD: index = STYLE_DARK_SLAYER; break; } } if (style == index) { if (Config.Game.StyleSwitcher.noDoubleTap) { return; } index = STYLE_QUICKSILVER; } if ((index == STYLE_QUICKSILVER) && (actor != ACTOR_ONE)) { return; } if ((index == STYLE_DOPPELGANGER) && Config.System.Actor.forceSingleActor) { return; } // @Todo: Check if array for unlocked styles. if (character == CHAR_DANTE) { if (index == STYLE_QUICKSILVER) { auto & unlock = *(bool *)(session + 0x5E); if (!unlock) { return; } } else if (index == STYLE_DOPPELGANGER) { auto & unlock = *(bool *)(session + 0x5F); if (!unlock) { return; } } } if (actor == ACTOR_ONE) { sessionLevel [style] = level; sessionExperience[style] = experience; } level = sessionLevel [index]; experience = sessionExperience[index]; style = index; if ((index == STYLE_SWORDMASTER) || (index == STYLE_GUNSLINGER)) { System_Weapon_Dante_UpdateExpertise(baseAddr); } UpdateActor2Start: { auto & baseAddr2 = System_Actor_actorBaseAddr[ACTOR_TWO]; if (!baseAddr2) { goto UpdateActor2End; } auto & character2 = *(uint8 *)(baseAddr2 + 0x78 ); auto & style2 = *(uint32 *)(baseAddr2 + 0x6338); auto & isControlledByPlayer2 = *(bool *)(baseAddr2 + 0x6480); if (Config.System.Actor.forceSingleActor) { goto UpdateActor2End; } if (actor != ACTOR_ONE) { goto UpdateActor2End; } if (character != character2) { goto UpdateActor2End; } if ((index == STYLE_QUICKSILVER) /*|| (index == STYLE_DOPPELGANGER)*/) { goto UpdateActor2End; } if (!isControlledByPlayer2) { style2 = index; if ((index == STYLE_SWORDMASTER) || (index == STYLE_GUNSLINGER)) { System_Weapon_Dante_UpdateExpertise(baseAddr2); } } } UpdateActor2End: if (actor == ACTOR_ONE) { System_HUD_updateStyleIcon = true; } Game_StyleSwitcher_counter++; } PrivateEnd; void Game_StyleSwitcher_Controller() { //uint8 actorCount = System_Actor_GetActorCount(); //if (actorCount < 1) //{ // return; //} // @Todo: Change to bindings. uint8 commandId[] = { CMD_MAP_SCREEN, CMD_FILE_SCREEN, CMD_ITEM_SCREEN, CMD_EQUIP_SCREEN, }; static bool execute[MAX_ACTOR][5] = {}; // @Fix: GetButtonState or loop is broken. Style is updated for other actors as well even if only actor one initiates the switch. // @Todo: Create helper; auto count = System_Actor_GetActorCount(); for (uint8 actor = 0; actor < count; actor++) { for (uint8 style = 0; style < 4; style++) { if (System_Input_GetButtonState(actor) & System_Input_GetBinding(commandId[style])) { if (execute[actor][style]) { UpdateStyle(System_Actor_actorBaseAddr[actor], style); execute[actor][style] = false; } } else { execute[actor][style] = true; } } if (Config.Game.Multiplayer.enable) { continue; } if ((System_Input_GetButtonState(actor) & System_Input_GetBinding(CMD_CHANGE_TARGET)) && (System_Input_GetButtonState(actor) & System_Input_GetBinding(CMD_DEFAULT_CAMERA))) { if (execute[actor][4]) { UpdateStyle(System_Actor_actorBaseAddr[actor], STYLE_DOPPELGANGER); execute[actor][4] = false; } } else { execute[actor][4] = true; } } } void Game_StyleSwitcher_Init() { LogFunction(); { byte8 sect0[] = { 0x48, 0x8B, 0x0D, 0x00, 0x00, 0x00, 0x00, //mov rcx,[dmc3.exe+C90E30] 0x48, 0x85, 0xC9, //test rcx,rcx 0x74, 0x07, //je short 0x8B, 0x8B, 0x58, 0x63, 0x00, 0x00, //mov ecx,[rbx+00006358] 0xC3, //ret 0x8B, 0x89, 0x00, 0x00, 0x00, 0x00, //mov ecx,[rcx+00000000] 0xC3, //ret }; FUNC func = CreateFunction(0, 0, false, true, sizeof(sect0)); memcpy(func.sect0, sect0, sizeof(sect0)); WriteAddress(func.sect0, (appBaseAddr + 0xC90E30), 7); *(dword *)(func.sect0 + 0x15) = (0x11C + (STYLE_GUNSLINGER * 4)); GunslingerGetStyleLevel = func.addr; } { byte8 sect0[] = { 0x50, //push rax 0x56, //push rsi 0x48, 0x8B, 0x35, 0x00, 0x00, 0x00, 0x00, //mov rsi,[dmc3.exe+C90E30] 0x48, 0x85, 0xF6, //test rsi,rsi 0x74, 0x0C, //je short 0x8B, 0x86, 0xA4, 0x01, 0x00, 0x00, //mov eax,[rsi+000001A4] 0x89, 0x81, 0x38, 0x63, 0x00, 0x00, //mov [rcx+00006338],eax 0x5E, //pop rsi 0x58, //pop rax }; FUNC func = CreateFunction(0, (appBaseAddr + 0x223D81), false, true, sizeof(sect0)); memcpy(func.sect0, sect0, sizeof(sect0)); WriteAddress((func.sect0 + 2), (appBaseAddr + 0xC90E30), 7); VergilDynamicStyle = func.addr; } } // @Todo: Update. void Game_StyleSwitcher_Toggle(bool enable) { Log("%s %u", FUNC_NAME, enable); if (enable) { Write<byte>((appBaseAddr + 0x1E8F98), 0xEB); // Bypass Character Check //WriteJump((appBaseAddr + 0x23D4B2), StyleControllerProxy); Write<byte>((appBaseAddr + 0x23B111), 0); Write<byte>((appBaseAddr + 0x23B15E), 0); Write<byte>((appBaseAddr + 0x23B1A2), 0); Write<byte>((appBaseAddr + 0x23B1E6), 0); // Gunslinger Fixes WriteCall((appBaseAddr + 0x204E38), GunslingerGetStyleLevel, 1); WriteCall((appBaseAddr + 0x205586), GunslingerGetStyleLevel, 1); WriteCall((appBaseAddr + 0x208A90), GunslingerGetStyleLevel, 1); WriteCall((appBaseAddr + 0x208F13), GunslingerGetStyleLevel, 1); WriteAddress((appBaseAddr + 0x1E6AAD), (appBaseAddr + 0x1E6AB3), 6 ); // Allow Charged Shot Write<byte>((appBaseAddr + 0x1E7F5F), 0xEB); // Allow Wild Stomp WriteAddress((appBaseAddr + 0x21607C), (appBaseAddr + 0x216082), 6 ); // Allow Charging // Force Style Updates WriteAddress((appBaseAddr + 0x1F87BB), (appBaseAddr + 0x1F87DC), 6); WriteAddress((appBaseAddr + 0x1F87C4), (appBaseAddr + 0x1F87DC), 6); WriteAddress((appBaseAddr + 0x1F87CD), (appBaseAddr + 0x1F87DC), 6); WriteAddress((appBaseAddr + 0x1F87D6), (appBaseAddr + 0x1F87DC), 6); WriteAddress((appBaseAddr + 0x1F880B), (appBaseAddr + 0x1F8A00), 6); WriteAddress((appBaseAddr + 0x1F8852), (appBaseAddr + 0x1F8A00), 6); WriteAddress((appBaseAddr + 0x1F8862), (appBaseAddr + 0x1F8A00), 5); WriteAddress((appBaseAddr + 0x1F886E), (appBaseAddr + 0x1F8A00), 6); WriteAddress((appBaseAddr + 0x1F89E1), (appBaseAddr + 0x1F8A00), 6); WriteAddress((appBaseAddr + 0x1F89FB), (appBaseAddr + 0x1F8A00), 5); WriteAddress((appBaseAddr + 0x1F8A07), (appBaseAddr + 0x1F8AAC), 6); WriteAddress((appBaseAddr + 0x1F8A7D), (appBaseAddr + 0x1F8AAC), 2); WriteAddress((appBaseAddr + 0x1F8AAA), (appBaseAddr + 0x1F8AAC), 2); WriteAddress((appBaseAddr + 0x1F8AC4), (appBaseAddr + 0x1F8AC6), 2); // Vergil Fixes WriteJump((appBaseAddr + 0x223D77), VergilDynamicStyle, 5); // Force dynamic style // @Audit: Should this go to Actor.cpp? Yup, Doppelganger fix. vp_memset((appBaseAddr + 0x221E50), 0x90, 8); // Update Actor Vergil; Disable linked actor base address reset. } else { Write<byte>((appBaseAddr + 0x1E8F98), 0x74); //WriteCall((appBaseAddr + 0x23D4B2), (appBaseAddr + 0x23B060)); Write<byte>((appBaseAddr + 0x23B111), 1); Write<byte>((appBaseAddr + 0x23B15E), 1); Write<byte>((appBaseAddr + 0x23B1A2), 1); Write<byte>((appBaseAddr + 0x23B1E6), 1); { byte buffer[] = { 0x8B, 0x8B, 0x58, 0x63, 0x00, 0x00, //mov ecx,[rbx+00006358] }; vp_memcpy((appBaseAddr + 0x204E38), buffer, sizeof(buffer)); vp_memcpy((appBaseAddr + 0x205586), buffer, sizeof(buffer)); vp_memcpy((appBaseAddr + 0x208A90), buffer, sizeof(buffer)); vp_memcpy((appBaseAddr + 0x208F13), buffer, sizeof(buffer)); } WriteAddress((appBaseAddr + 0x1E6AAD), (appBaseAddr + 0x1E64A9), 6); Write<byte>((appBaseAddr + 0x1E7F5F), 0x74); WriteAddress((appBaseAddr + 0x21607C), (appBaseAddr + 0x216572), 6); WriteAddress((appBaseAddr + 0x1F87BB), (appBaseAddr + 0x1F8AC6), 6); WriteAddress((appBaseAddr + 0x1F87C4), (appBaseAddr + 0x1F8AAC), 6); WriteAddress((appBaseAddr + 0x1F87CD), (appBaseAddr + 0x1F8A00), 6); WriteAddress((appBaseAddr + 0x1F87D6), (appBaseAddr + 0x1F8AF8), 6); WriteAddress((appBaseAddr + 0x1F880B), (appBaseAddr + 0x1F8AF8), 6); WriteAddress((appBaseAddr + 0x1F8852), (appBaseAddr + 0x1F8AF8), 6); WriteAddress((appBaseAddr + 0x1F8862), (appBaseAddr + 0x1F8AF8), 5); WriteAddress((appBaseAddr + 0x1F886E), (appBaseAddr + 0x1F8AF8), 6); WriteAddress((appBaseAddr + 0x1F89E1), (appBaseAddr + 0x1F8AF8), 6); WriteAddress((appBaseAddr + 0x1F89FB), (appBaseAddr + 0x1F8AF8), 5); WriteAddress((appBaseAddr + 0x1F8A07), (appBaseAddr + 0x1F8AF8), 6); WriteAddress((appBaseAddr + 0x1F8A7D), (appBaseAddr + 0x1F8AF8), 2); WriteAddress((appBaseAddr + 0x1F8AAA), (appBaseAddr + 0x1F8AF8), 2); WriteAddress((appBaseAddr + 0x1F8AC4), (appBaseAddr + 0x1F8AF8), 2); { byte buffer[] = { 0xC7, 0x81, 0x38, 0x63, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, //mov [rcx+00006338],00000002 }; vp_memcpy((appBaseAddr + 0x223D77), buffer, sizeof(buffer)); } { byte buffer[] = { 0x4D, 0x89, 0xB4, 0x24, 0x78, 0x64, 0x00, 0x00, //mov [r12+00006478],r14 }; vp_memcpy((appBaseAddr + 0x221E50), buffer, sizeof(buffer)); } } }
29.047619
174
0.643684
wangxh1007