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
625cb6940b13f33c738a462b88a854e130df4c99
6,756
cpp
C++
cell_based/src/population/killers/CryptFissionCellKiller.cpp
Mathematics-in-Oncology/ComputationalColonicCrypts
a407ae6c37acc878cd1548590c71bc1f87bc5c06
[ "Unlicense" ]
1
2021-01-25T12:21:40.000Z
2021-01-25T12:21:40.000Z
cell_based/src/population/killers/CryptFissionCellKiller.cpp
Mathematics-in-Oncology/ComputationalColonicCrypts
a407ae6c37acc878cd1548590c71bc1f87bc5c06
[ "Unlicense" ]
null
null
null
cell_based/src/population/killers/CryptFissionCellKiller.cpp
Mathematics-in-Oncology/ComputationalColonicCrypts
a407ae6c37acc878cd1548590c71bc1f87bc5c06
[ "Unlicense" ]
1
2021-01-25T12:21:56.000Z
2021-01-25T12:21:56.000Z
/* Copyright (c) 2005-2019, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. 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 University of Oxford nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CryptFissionCellKiller.hpp" #include "WildTypeCellMutationState.hpp" #include "MMRTwoHitCellMutationState.hpp" #include "ApcOneHitCellMutationState.hpp" #include "ApcTwoHitCellMutationState.hpp" #include "BetaCateninOneHitCellMutationState.hpp" #include "BetaCateninTwoHitCellMutationState.hpp" #include "MMR_ApcOneHitCellMutationState.hpp" #include "MMR_ApcTwoHitCellMutationState.hpp" #include "MMR_BCOneHitCellMutationState.hpp" #include "MMR_BCTwoHitCellMutationState.hpp" #include "MMR_BCOneHit_ApcOneHitCellMutationState.hpp" #include "BCOneHit_ApcOneHitCellMutationState.hpp" #include "ApcLOHCellMutationState.hpp" #include "BCOneHit_ApcLOHCellMutationState.hpp" #include "MMR_ApcLOHCellMutationState.hpp" #include "MMR_BCOneHit_ApcLOHCellMutationState.hpp" #include "BCLOHApcOneHitCellMutationState.hpp" #include "BCLOHMMRTwoHitCellMutationState.hpp" #include "BCLOHMMR_ApcOneHitCellMutationState.hpp" #include "BCLOHApcLOHCellMutationState.hpp" #include "BCLOHMMR_ApcLOHCellMutationState.hpp" template<unsigned DIM> CryptFissionCellKiller<DIM>::CryptFissionCellKiller(AbstractCellPopulation<DIM>* pCellPopulation, double CryptFissionRate, int acrypt_counter) : AbstractCellKiller<DIM>(pCellPopulation), mCryptFissionRate(CryptFissionRate), crypt_counter(acrypt_counter) { if ((mCryptFissionRate<0) || (mCryptFissionRate>1)) { EXCEPTION("Probability of crypt fission must be between zero and one"); } } template<unsigned DIM> double CryptFissionCellKiller<DIM>::GetCryptFissionRate() const { return mCryptFissionRate; } template<unsigned DIM> int CryptFissionCellKiller<DIM>::GetCryptCounter() const { return crypt_counter; } template<unsigned DIM> void CryptFissionCellKiller<DIM>::CheckAndLabelCellsForApoptosisOrDeath() { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); // initialize MPI rank /* * We assume a constant time step and that there are an integer number (n = 1/dt) * of time steps per hour. We also assume that this method is called every time step * and that the probabilities of fission at different times are independent. * * Let q=mCryptFissionRate and p="probability of fission in a given time step". * * Probability of no fission in an hour: * (1-q) = (1-p)^n = (1-p)^(1/dt). * * Rearranging for p: * p = 1 - (1-q)^dt. */ double fission_prob_this_timestep = 0.0; double mmr_percentage = (double)this->mpCellPopulation->GetNumMMRCells()/(double)this->mpCellPopulation->GetNumRealCells(); // We declare a crypt as MMR-deficient if over 80 percent of all cells show a double MMR-hit. // Crypt fission is set to be more likely for such crypts. if (mmr_percentage > 0.8) { //Increase fission probability of MMR-mutant crypts. fission_prob_this_timestep = 1.0 - pow((1.0 - 1.22*mCryptFissionRate), SimulationTime::Instance()->GetTimeStep()); } else { fission_prob_this_timestep = 1.0 - pow((1.0 - mCryptFissionRate), SimulationTime::Instance()->GetTimeStep()); } if (RandomNumberGenerator::Instance()->ranf() < fission_prob_this_timestep) // crypt fission occurs { crypt_counter++; // add (virtual) crypt mCryptFissionRate = (double) crypt_counter * mCryptFissionRate/((double)crypt_counter -1.0); // new fission rate is no. of crypts * inital fission rate if (mmr_percentage > 0.8) { cout << "Crypt fission of MMR-deficient crypt in cluster " << rank << " at time " << SimulationTime::Instance()->GetTime() << endl; // output time of mutated crypt fission event } else { cout << "Crypt fission of normal crypt in cluster " << rank << " at time " << SimulationTime::Instance()->GetTime() << endl; // output time of normal crypt fission event } } /* // mice simulation fission_prob_this_timestep = 1.0 - pow((1.0 - 1.22*mCryptFissionRate), SimulationTime::Instance()->GetTimeStep()); if (RandomNumberGenerator::Instance()->ranf() < fission_prob_this_timestep) // crypt fission occurs { crypt_counter++; // add (virtual) crypt mCryptFissionRate = (double) crypt_counter * mCryptFissionRate/((double)crypt_counter -1.0); // new fission rate is no. of crypts * inital fission rate cout << "Crypt fission of MMR-deficient crypt in cluster " << rank << " at time " << SimulationTime::Instance()->GetTime() << endl; // output time of mutated crypt fission event }*/ } template<unsigned DIM> void CryptFissionCellKiller<DIM>::OutputCellKillerParameters(out_stream& rParamsFile) { *rParamsFile << "\t\t\t<CryptFissionRate>" << mCryptFissionRate << "</CryptFissionRate>\n"; // Call method on direct parent class AbstractCellKiller<DIM>::OutputCellKillerParameters(rParamsFile); } // Explicit instantiation template class CryptFissionCellKiller<1>; template class CryptFissionCellKiller<2>; template class CryptFissionCellKiller<3>; // Serialization for Boost >= 1.36 #include "SerializationExportWrapperForCpp.hpp" EXPORT_TEMPLATE_CLASS_SAME_DIMS(CryptFissionCellKiller)
40.945455
185
0.760657
Mathematics-in-Oncology
625cd025b26f238f4f095abfb2711709efe2553c
3,472
cpp
C++
system_stat/protocoltypetcp.cpp
manito17711/system_stat
089fed90a42ec83d1126cf837fa95d077b595d0c
[ "MIT" ]
null
null
null
system_stat/protocoltypetcp.cpp
manito17711/system_stat
089fed90a42ec83d1126cf837fa95d077b595d0c
[ "MIT" ]
null
null
null
system_stat/protocoltypetcp.cpp
manito17711/system_stat
089fed90a42ec83d1126cf837fa95d077b595d0c
[ "MIT" ]
null
null
null
#include "protocoltypetcp.hpp" #include <iostream> #include <fcntl.h> ProtocolTypeTCP::ProtocolTypeTCP(int port) : ProtocolType(port) { } void ProtocolTypeTCP::startListen() { static const int MAX_CONNECTION = 5; if (0 == listen(sock_fd, MAX_CONNECTION)) { std::cout << "Server listen on port " << port << std::endl; } else { // TODO: log error //std::cout << strerror(errno) << std::endl; exit(1); } for (;;) { si_rhs_len = sizeof(si_rhs); ssize_t received = 0; int clientSock = accept(sock_fd, (struct sockaddr*) &si_rhs, &si_rhs_len); if (-1 != clientSock) { clearBuff(); received = read(clientSock, buff, buff_size); ConnType type = defineConnectionType(buff); if (!favicon(buff)) { std::cout << "Incoming call: " << inet_ntoa(si_rhs.sin_addr) << " Type: "; (type == ConnType::client) ? std::cout << "client\n" : std::cout << "server\n"; pFunc_onConn(clientSock, type); } } else { // TODO: log error } close (clientSock); } } void ProtocolTypeTCP::initSocket() { sock_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (0 > sock_fd) { // TDOO: log error // std::cout << "ERROR: init socket."; // std::cout << strerror(errno) << std::endl; exit(1); } // zero our the memory memset((char*) &si_lhs, 0, sizeof(si_lhs)); si_lhs.sin_family = AF_INET; si_lhs.sin_port = htons(port); si_lhs.sin_addr.s_addr = htonl(INADDR_ANY); } int ProtocolTypeTCP::sendData(int fd, const std::__cxx11::string &data) { if (data.compare("SRV") == 0) { // set descriptior to non-blocking... todo: try to avoid fcntl int flags = fcntl(fd, F_GETFL); if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) { std::cout << "Err: fcntl\n"; } if (0 > connect(fd, (struct sockaddr*) &si_rhs, si_rhs_len)) { // TODO: log error // std::cout << "ERROR: connecting to server..." << std::endl; // std::cout << strerror(errno) << std::endl; //return false; } } return send(fd, data.c_str(), data.length(), 0); } int ProtocolTypeTCP::readData(int fd, std::__cxx11::string &report) { clearBuff(); pfd.fd = sock_fd; pfd.events = POLLIN; pfd_rv = poll(&pfd, 1, pfd_tv); ssize_t received = -1; if (-1 == pfd_rv) { // TODO: poll return error exit(1); } else if (0 == pfd_rv) { report = "Timeout! No data in 1 second!\0"; received = strlen(buff); } else { received = recv(fd, buff, buff_size, 0); if (-1 == received) { report = "recvfrom() return -1\n\0"; } else { report = buff; } } return received; } std::shared_ptr<ProtocolType> ProtocolTypeTCP::createObject() { std::shared_ptr<ProtocolType> newObj (new ProtocolTypeTCP(port)); return newObj; } bool ProtocolTypeTCP::favicon(const char *req) { std::__cxx11::string r = std::__cxx11::string(req).substr(0, 12); std::__cxx11::string favicon ("GET /favicon"); if (0 == r.compare(favicon)) { return true; } return false; }
20.915663
95
0.529378
manito17711
625d3abd0ef728256b1df340fe7997040103060b
809
cpp
C++
Online-Judge-Solution/UVA Solutions/10018(Reverse & Add).cpp
arifparvez14/Basic-and-competetive-programming
4cb9ee7fbed3c70307d0f63499fcede86ed3c732
[ "MIT" ]
null
null
null
Online-Judge-Solution/UVA Solutions/10018(Reverse & Add).cpp
arifparvez14/Basic-and-competetive-programming
4cb9ee7fbed3c70307d0f63499fcede86ed3c732
[ "MIT" ]
null
null
null
Online-Judge-Solution/UVA Solutions/10018(Reverse & Add).cpp
arifparvez14/Basic-and-competetive-programming
4cb9ee7fbed3c70307d0f63499fcede86ed3c732
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; long long int palindrome(long long int z) { long long int y,revi; revi=0; while(z!=0) { y=z%10; revi=revi*10+y; z=z/10; } return revi; } int main() { long long int n,i,k,d,rev,sum,count,l,T,x,j,check; cin>>T; for(x=1; x<=T; x++) { count=0,sum=0; cin>>n; for(i=1; i!=0; i++) { rev=0; k=n; while(n>0) { d=n%10; rev=rev*10+d; n=n/10; } count++; sum=rev+k; check=palindrome(sum); if(sum-check==0) break; n=sum; } printf("%lld %lld\n",count,sum); } return 0; }
17.212766
54
0.379481
arifparvez14
625e56f965408f90582b0203462addc28a0ae600
670
cc
C++
POJ/3666_Making the Grade/3666.cc
pdszhh/ACM
956b3d03a5d3f070ef24c940b7459f5cccb11d6c
[ "MIT" ]
1
2019-05-05T03:51:20.000Z
2019-05-05T03:51:20.000Z
POJ/3666_Making the Grade/3666.cc
pdszhh/ACM
956b3d03a5d3f070ef24c940b7459f5cccb11d6c
[ "MIT" ]
null
null
null
POJ/3666_Making the Grade/3666.cc
pdszhh/ACM
956b3d03a5d3f070ef24c940b7459f5cccb11d6c
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <cmath> using namespace std; int A[2000] = {0}; int B[2000] = {0}; int dp[2000] = {0}; int main() { cin.tie(0); ios::sync_with_stdio(false); int n; cin >> n; for (int i = 0; i < n; i++) cin >> A[i]; copy(A, A + n, B); sort(B, B + n); for (int i = 0; i < n; i++) { int minn = dp[0]; for (int j = 0; j < n; j++) { minn = min(minn, dp[j]); dp[j] = minn + abs(A[i] - B[j]); } } int ans = dp[0]; for (int i = 1; i < n; i++) { ans = min(ans, dp[i]); } cout << ans << endl; return 0; }
16.75
44
0.408955
pdszhh
626023e72138fa10f729698bc43ae6dbf1185f9b
7,673
cpp
C++
Funcs.cpp
ClaudiuHKS/AddCommas
1229ae36dbe595a0d6544332b0d6c331e40177e3
[ "MIT" ]
1
2022-02-18T21:41:59.000Z
2022-02-18T21:41:59.000Z
Funcs.cpp
ClaudiuHKS/AddCommas
1229ae36dbe595a0d6544332b0d6c331e40177e3
[ "MIT" ]
null
null
null
Funcs.cpp
ClaudiuHKS/AddCommas
1229ae36dbe595a0d6544332b0d6c331e40177e3
[ "MIT" ]
null
null
null
#include "Funcs.h" ::std::string AddCommasA ( bool W ) noexcept { return ::AddCommasA ( ( static_cast < long long > ( W ) ) ); } ::std::string AddCommasA ( char W ) noexcept { return ::AddCommasA ( ( static_cast < long long > ( W ) ) ); } ::std::string AddCommasA ( short W ) noexcept { return ::AddCommasA ( ( static_cast < long long > ( W ) ) ); } ::std::string AddCommasA ( int W ) noexcept { return ::AddCommasA ( ( static_cast < long long > ( W ) ) ); } ::std::string AddCommasA ( long W ) noexcept { return ::AddCommasA ( ( static_cast < long long > ( W ) ) ); } ::std::string AddCommasA ( long long W ) noexcept { static ::std::string R { }, T { }; static unsigned long long L { }, I { }, D { }; if ( W < 0I64 ) R = '-', T = ::std::to_string ( ::std::abs ( W ) ); else R.clear ( ), T = ::std::to_string ( W ); L = ( static_cast < decltype ( L ) > ( T.length ( ) ) ), I = 0UI64; while ( I < L ) { R += T [ I++ ]; if ( ( ( D = ( L - I ) ) != 0UI64 ) && ( ( D % 3UI64 ) == 0UI64 ) ) R += ','; } return R; } ::std::string AddCommasA ( unsigned char W ) noexcept { return ::AddCommasA ( ( static_cast < unsigned long long > ( W ) ) ); } ::std::string AddCommasA ( unsigned short W ) noexcept { return ::AddCommasA ( ( static_cast < unsigned long long > ( W ) ) ); } ::std::string AddCommasA ( unsigned int W ) noexcept { return ::AddCommasA ( ( static_cast < unsigned long long > ( W ) ) ); } ::std::string AddCommasA ( unsigned long W ) noexcept { return ::AddCommasA ( ( static_cast < unsigned long long > ( W ) ) ); } ::std::string AddCommasA ( unsigned long long W ) noexcept { static ::std::string R { }, T { }; static unsigned long long L { }, I { }, D { }; R.clear ( ), T = ::std::to_string ( W ), L = ( static_cast < decltype ( L ) > ( T.length ( ) ) ), I = 0UI64; while ( I < L ) { R += T [ I++ ]; if ( ( ( D = ( L - I ) ) != 0UI64 ) && ( ( D % 3UI64 ) == 0UI64 ) ) R += ','; } return R; } ::std::string AddCommasA ( float W ) noexcept { return ::AddCommasA ( ( static_cast < long double > ( W ) ) ); } ::std::string AddCommasA ( double W ) noexcept { return ::AddCommasA ( ( static_cast < long double > ( W ) ) ); } ::std::string AddCommasA ( long double W ) noexcept { static ::std::string R { }, T { }, C { }; static unsigned long long L { }, P { }, I { }, D { }; if ( W < 0.L ) R = '-', T = ::std::to_string ( ::std::abs ( W ) ); else R.clear ( ), T = ::std::to_string ( W ); L = ( static_cast < decltype ( L ) > ( T.length ( ) ) ); if ( ( ( P = ( static_cast < decltype ( P ) > ( T.find ( '.' ) ) ) ) >= 0UI64 ) && ( P < L ) ) C.assign ( &( T [ P ] ) ), T.erase ( P ), L = ( static_cast < decltype ( L ) > ( T.length ( ) ) ); else if ( ( ( P = ( static_cast < decltype ( P ) > ( T.find ( ',' ) ) ) ) >= 0UI64 ) && ( P < L ) ) T [ P ] = '.', C.assign ( &( T [ P ] ) ), T.erase ( P ), L = ( static_cast < decltype ( L ) > ( T.length ( ) ) ); else C.clear ( ); I = 0UI64; while ( I < L ) { R += T [ I++ ]; if ( ( ( D = ( L - I ) ) != 0UI64 ) && ( ( D % 3UI64 ) == 0UI64 ) ) R += ','; } return ( R + C ); } ::std::string AddCommasA ( char8_t W ) noexcept { return ::AddCommasA ( ( static_cast < long long > ( W ) ) ); } ::std::string AddCommasA ( char16_t W ) noexcept { return ::AddCommasA ( ( static_cast < long long > ( W ) ) ); } ::std::string AddCommasA ( char32_t W ) noexcept { return ::AddCommasA ( ( static_cast < long long > ( W ) ) ); } ::std::string AddCommasA ( wchar_t W ) noexcept { return ::AddCommasA ( ( static_cast < long long > ( W ) ) ); } ::std::wstring AddCommasW ( bool W ) noexcept { return ::AddCommasW ( ( static_cast < long long > ( W ) ) ); } ::std::wstring AddCommasW ( char W ) noexcept { return ::AddCommasW ( ( static_cast < long long > ( W ) ) ); } ::std::wstring AddCommasW ( short W ) noexcept { return ::AddCommasW ( ( static_cast < long long > ( W ) ) ); } ::std::wstring AddCommasW ( int W ) noexcept { return ::AddCommasW ( ( static_cast < long long > ( W ) ) ); } ::std::wstring AddCommasW ( long W ) noexcept { return ::AddCommasW ( ( static_cast < long long > ( W ) ) ); } ::std::wstring AddCommasW ( long long W ) noexcept { static ::std::wstring R { }, T { }; static unsigned long long L { }, I { }, D { }; if ( W < 0I64 ) R = L'-', T = ::std::to_wstring ( ::std::abs ( W ) ); else R.clear ( ), T = ::std::to_wstring ( W ); L = ( static_cast < decltype ( L ) > ( T.length ( ) ) ), I = 0UI64; while ( I < L ) { R += T [ I++ ]; if ( ( ( D = ( L - I ) ) != 0UI64 ) && ( ( D % 3UI64 ) == 0UI64 ) ) R += L','; } return R; } ::std::wstring AddCommasW ( unsigned char W ) noexcept { return ::AddCommasW ( ( static_cast < unsigned long long > ( W ) ) ); } ::std::wstring AddCommasW ( unsigned short W ) noexcept { return ::AddCommasW ( ( static_cast < unsigned long long > ( W ) ) ); } ::std::wstring AddCommasW ( unsigned int W ) noexcept { return ::AddCommasW ( ( static_cast < unsigned long long > ( W ) ) ); } ::std::wstring AddCommasW ( unsigned long W ) noexcept { return ::AddCommasW ( ( static_cast < unsigned long long > ( W ) ) ); } ::std::wstring AddCommasW ( unsigned long long W ) noexcept { static ::std::wstring R { }, T { }; static unsigned long long L { }, I { }, D { }; R.clear ( ), T = ::std::to_wstring ( W ), L = ( static_cast < decltype ( L ) > ( T.length ( ) ) ), I = 0UI64; while ( I < L ) { R += T [ I++ ]; if ( ( ( D = ( L - I ) ) != 0UI64 ) && ( ( D % 3UI64 ) == 0UI64 ) ) R += L','; } return R; } ::std::wstring AddCommasW ( float W ) noexcept { return ::AddCommasW ( ( static_cast < long double > ( W ) ) ); } ::std::wstring AddCommasW ( double W ) noexcept { return ::AddCommasW ( ( static_cast < long double > ( W ) ) ); } ::std::wstring AddCommasW ( long double W ) noexcept { static ::std::wstring R { }, T { }, C { }; static unsigned long long L { }, P { }, I { }, D { }; if ( W < 0.L ) R = L'-', T = ::std::to_wstring ( ::std::abs ( W ) ); else R.clear ( ), T = ::std::to_wstring ( W ); L = ( static_cast < decltype ( L ) > ( T.length ( ) ) ); if ( ( ( P = ( static_cast < decltype ( P ) > ( T.find ( L'.' ) ) ) ) >= 0UI64 ) && ( P < L ) ) C.assign ( &( T [ P ] ) ), T.erase ( P ), L = ( static_cast < decltype ( L ) > ( T.length ( ) ) ); else if ( ( ( P = ( static_cast < decltype ( P ) > ( T.find ( L',' ) ) ) ) >= 0UI64 ) && ( P < L ) ) T [ P ] = L'.', C.assign ( &( T [ P ] ) ), T.erase ( P ), L = ( static_cast < decltype ( L ) > ( T.length ( ) ) ); else C.clear ( ); I = 0UI64; while ( I < L ) { R += T [ I++ ]; if ( ( ( D = ( L - I ) ) != 0UI64 ) && ( ( D % 3UI64 ) == 0UI64 ) ) R += L','; } return ( R + C ); } ::std::wstring AddCommasW ( char8_t W ) noexcept { return ::AddCommasW ( ( static_cast < long long > ( W ) ) ); } ::std::wstring AddCommasW ( char16_t W ) noexcept { return ::AddCommasW ( ( static_cast < long long > ( W ) ) ); } ::std::wstring AddCommasW ( char32_t W ) noexcept { return ::AddCommasW ( ( static_cast < long long > ( W ) ) ); } ::std::wstring AddCommasW ( wchar_t W ) noexcept { return ::AddCommasW ( ( static_cast < long long > ( W ) ) ); }
24.993485
122
0.492767
ClaudiuHKS
62685a19e27e6e65a9ca6f628ad5244d1ff76b90
5,295
cpp
C++
game/src/UI/GameWindow.cpp
BigETI/NoLifeNoCry
70ac2498b5e740b2b348771ef9617dea1eed7f9c
[ "MIT" ]
5
2020-11-07T23:38:48.000Z
2021-12-07T11:03:22.000Z
game/src/UI/GameWindow.cpp
BigETI/NoLifeNoCry
70ac2498b5e740b2b348771ef9617dea1eed7f9c
[ "MIT" ]
null
null
null
game/src/UI/GameWindow.cpp
BigETI/NoLifeNoCry
70ac2498b5e740b2b348771ef9617dea1eed7f9c
[ "MIT" ]
null
null
null
#include <iostream> #include <rttr/registration.h> #include <Serialiser/Asset.hpp> #include <Story.hpp> #include <StoryData.hpp> #include <UI/GameWindow.hpp> /// @brief Constructor /// @param windowWidth Window width /// @param windowHeight Window height /// @param windowName Window name /// @param windowStyle Window style NoLifeNoCry::GameWindow::GameWindow(std::size_t windowWidth, std::size_t windowHeight, const std::string& windowName, DirtMachine::EWindowStyle windowStyle) : DirtMachine::UI::Window(windowWidth, windowHeight, windowName, windowStyle) { OnWindowStarted += []() { std::cout << "Window has started." << std::endl; }; OnWindowStopped += []() { std::cout << "Window has stopped." << std::endl; }; OnWindowMessagesProcessed += [](double deltaTime) { std::cout << "Window has processed messaged. Delta time: " << deltaTime << std::endl; }; OnWindowResized += [](std::size_t width, std::size_t height) { std::cout << "New window size: (" << width << ", " << height << ")" << std::endl; }; OnFocusLost += []() { std::cout << "Window lost focus." << std::endl; }; OnFocusGained += []() { std::cout << "Window gained focus." << std::endl; }; OnTextEntered += [](DirtMachine::Input::Data::TextData text) { std::cout << "Text entered: " << text.unicode << std::endl; }; OnKeyboardKeyPressed += [](DirtMachine::Input::Data::KeyboardKeyData keyboardKey) { std::cout << "Key pressed: " << (keyboardKey.isSystemKeyUsed ? "Sys+" : "") << (keyboardKey.isControlKeyUsed ? "Ctrl+" : "") << (keyboardKey.isAltKeyUsed ? "Alt+" : "") << static_cast<int>(keyboardKey.keyCode) << std::endl; }; OnKeyboardKeyReleased += [](DirtMachine::Input::Data::KeyboardKeyData keyboardKey) { std::cout << "Key released: " << (keyboardKey.isSystemKeyUsed ? "Sys+" : "") << (keyboardKey.isControlKeyUsed ? "Ctrl+" : "") << (keyboardKey.isAltKeyUsed ? "Alt+" : "") << static_cast<int>(keyboardKey.keyCode) << std::endl; }; OnMouseWheelScrolled += [](DirtMachine::Input::Data::MouseWheelData mouseWheel) { std::cout << "Mouse wheel scrolled: " << static_cast<int>(mouseWheel.wheel) << " : " << mouseWheel.delta << " at (" << mouseWheel.position.x << ", " << mouseWheel.position.y << ")" << std::endl; }; OnMouseButtonPressed += [](DirtMachine::Input::Data::MouseButtonData mouseButton) { std::cout << "Mouse button pressed: " << static_cast<int>(mouseButton.button) << " at (" << mouseButton.position.x << ", " << mouseButton.position.y << ")" << std::endl; }; OnMouseButtonReleased += [](DirtMachine::Input::Data::MouseButtonData mouseButton) { std::cout << "Mouse button released: " << static_cast<int>(mouseButton.button) << " at (" << mouseButton.position.x << ", " << mouseButton.position.y << ")" << std::endl; }; OnMouseMoved += [](DirtMachine::Input::Data::MouseMovementData mouseMovement) { std::cout << "Mouse moved: (" << mouseMovement.position.x << ", " << mouseMovement.position.y << ")" << std::endl; }; OnMouseEntered += []() { std::cout << "Mouse has entered the window." << std::endl; }; OnMouseLeft += []() { std::cout << "Mouse has left the window." << std::endl; }; OnJoystickButtonPressed += [](DirtMachine::Input::Data::JoystickButtonData joystickButton) { std::cout << "Joystick button pressed: " << joystickButton.button << " at joystick ID " << joystickButton.joystickID << std::endl; }; OnJoystickButtonReleased += [](DirtMachine::Input::Data::JoystickButtonData joystickButton) { std::cout << "Joystick button released: " << joystickButton.button << " at joystick ID " << joystickButton.joystickID << std::endl; }; OnJoystickMoved += [](DirtMachine::Input::Data::JoystickMovementData joystickMovement) { std::cout << "Joystick moved: " << joystickMovement.position << " with axis " << static_cast<int>(joystickMovement.axis) << " at joystick ID " << joystickMovement.joystickID << std::endl; }; OnJoystickConnected += [](DirtMachine::Input::Data::JoystickConnectionData joystickConnection) { std::cout << "Joystick ID " << joystickConnection.joystickID << " has been connected." << std::endl; }; OnJoystickDisconnected += [](DirtMachine::Input::Data::JoystickConnectionData joystickConnection) { std::cout << "Joystick ID " << joystickConnection.joystickID << " has been disconnected." << std::endl; }; OnTouchBegan += [](DirtMachine::Input::Data::TouchData touch) { std::cout << "Touch began: Finger " << touch.finger << " at (" << touch.position.x << ", " << touch.position.y << ")" << std::endl; }; OnTouchMoved += [](DirtMachine::Input::Data::TouchData touch) { std::cout << "Touch moved: Finger " << touch.finger << " at (" << touch.position.x << ", " << touch.position.y << ")" << std::endl; }; OnTouchEnded += [](DirtMachine::Input::Data::TouchData touch) { std::cout << "Touch ended: Finger " << touch.finger << " at (" << touch.position.x << ", " << touch.position.y << ")" << std::endl; }; OnSensorChanged += [](DirtMachine::Input::Data::SensorData sensor) { std::cout << "Sensor changed: Type " << static_cast<int>(sensor.type) << " at (" << sensor.value.x << ", " << sensor.value.y << ", " << sensor.value.z << ")" << std::endl; }; SaveGame::LoadAll("./saves/", saveGames); } /// @brief Destructor NoLifeNoCry::GameWindow::~GameWindow() { // ... }
44.125
234
0.65118
BigETI
626bcc8211d0da615ecfaf61f5ab5a71c543d4c7
1,343
cpp
C++
Classes/ProductInventory.cpp
TodorKarparov/Projects
41aa12b3eabc16fc408513e0b28051d08f7a1f75
[ "MIT" ]
null
null
null
Classes/ProductInventory.cpp
TodorKarparov/Projects
41aa12b3eabc16fc408513e0b28051d08f7a1f75
[ "MIT" ]
null
null
null
Classes/ProductInventory.cpp
TodorKarparov/Projects
41aa12b3eabc16fc408513e0b28051d08f7a1f75
[ "MIT" ]
null
null
null
/** Product Inventory Project: Create an application which manages an inventory of products. Create a product class which has a price, id, and quantity on hand. Then create an inventory class which keeps track of various products and can sum up the inventory value. */ #include <iostream> #include <string> #include <unordered_map> class Product { std::string ID; double price; size_t quantity; public: Product(std::string& _ID, double _price, size_t _quantity) { ID = _ID; price = _price; quantity = _quantity; } std::string getID() const { return ID; } double getPrice() const { return price; } size_t availableQuantity() const { return quantity; } void setPrice(double newPrice) { price = newPrice; } void setQuantity(size_t newQuantity) { quantity = newQuantity; } }; class Inventory { std::unordered_map<std::string, Product*> inventory; public: Product* getProduct(std::string& productID) const { if (inventory.contains(productID)) { return inventory.at(productID); } return nullptr; } void addProduct(Product* product) { if (inventory.contains(product -> getID())) { inventory.at(product -> getID()) -> setQuantity(inventory.at(product -> getID()) -> availableQuantity() + product -> availableQuantity()); } inventory[product -> getID()] = product; } };
18.39726
104
0.696947
TodorKarparov
626c3fb888b452a215ff957a5d4c1bd88e17d26a
8,452
cpp
C++
GalvoScannerCorrect/src/correct.cpp
ZhukovWang/GalvoScannerCorrect
41dedc309218f102333ec89572e06db425740d05
[ "MIT" ]
4
2019-08-02T14:05:05.000Z
2022-03-02T14:13:17.000Z
GalvoScannerCorrect/src/correct.cpp
ZhukovWang/GalvoScannerCorrect
41dedc309218f102333ec89572e06db425740d05
[ "MIT" ]
null
null
null
GalvoScannerCorrect/src/correct.cpp
ZhukovWang/GalvoScannerCorrect
41dedc309218f102333ec89572e06db425740d05
[ "MIT" ]
3
2019-07-16T01:16:13.000Z
2021-10-02T16:26:32.000Z
#include "correct.h" /// <summary> /// 二次曲线的x补偿因子 /// </summary> const double conic_factor_x = 0.02; /// <summary> /// 二次曲线的y补偿因子 /// </summary> const double conic_factor_y = 0.02; /// <summary> /// 平行四边形x补偿因子 /// </summary> const double parallelogram_factor_x = 0.5; /// <summary> /// 平行四边形y补偿因子 /// </summary> const double parallelogram_factor_y = 0.5; /// <summary> /// 梯形偏移x补偿因子 /// </summary> const double trapezoidal_factor_x = 0.5; /// <summary> /// 梯形偏移y补偿因子 /// </summary> const double trapezoidal_factor_y = 0.5; /// <summary> /// x的最大位置 /// </summary> const double x_max = 32000; /// <summary> /// y的最大位置 /// </summary> const double y_max = 32000; const double x_axis_plat_x_start = -21000; const double x_axis_plat_x_interval = 21000; const int x_axis_plat_x_num = 3; const double x_axis_plat_y_start = -21000; const double x_axis_plat_y_interval = 21000; const int x_axis_plat_y_num = 3; const double x_axis_plat_correct[3][3] = { {-1000,-1000,-1000}, {0,0,0}, {1000,1000,1000} };//第一组y=-21000, x从-21000到21000,其后类推 const double y_axis_plat_x_start = -21000; const double y_axis_plat_x_interval = 21000; const int y_axis_plat_x_num = 3; const double y_axis_plat_y_start = -21000; const double y_axis_plat_y_interval = 21000; const int y_axis_plat_y_num = 3; const double y_axis_plat_correct[3][3] = { {-1000,0,1000}, {-500,0,500}, {-1000,0,1000} };//第一组y=-21000, x从-21000到21000,其后类推 /// <summary> /// 得到二次曲线的补偿位置 /// </summary> /// <param name="x">position x</param> /// <param name="y">position y</param> /// <param name="correct_delta_x">correct delta x</param> /// <param name="correct_delta_y">correct delta y</param> void GetConicCorrection(double x, double y, double* correct_delta_x, double* correct_delta_y) { //double a_x = std::pow(y_max, 2) / x; //*correct_delta_x = (x - std::pow(y, 2) / (-a_x)) * conic_factor_x; //double a_y = std::pow(x_max, 2) / y; //*correct_delta_y = (y - std::pow(x, 2) / (-a_y)) * conic_factor_y; if (x < 1 && x > -1) { *correct_delta_x = 0; } else { double a_x = y_max * y_max / x; *correct_delta_x = (x - y * y / (-a_x)) * conic_factor_x; } if (y < 1 && y > -1) { *correct_delta_y = 0; } else { double a_y = x_max * x_max / y; *correct_delta_y = (y - x * x / (-a_y)) * conic_factor_y; } } /// <summary> /// 得到平行四边形补偿位置 /// </summary> /// <param name="x">position x</param> /// <param name="y">position y</param> /// <param name="correct_delta_x">correct delta x</param> /// <param name="correct_delta_y">correct delta y</param> void GetParallelogramCorrection(double x, double y, double* correct_delta_x, double* correct_delta_y) { *correct_delta_x = -y * parallelogram_factor_x; *correct_delta_y = -x * parallelogram_factor_y; } /// <summary> /// 得到梯形补偿位置 /// </summary> /// <param name="x">position x</param> /// <param name="y">position y</param> /// <param name="correct_delta_x">correct delta x</param> /// <param name="correct_delta_y">correct delta y</param> void GetTrapezoidalCorrection(double x, double y, double* correct_delta_x, double* correct_delta_y) { *correct_delta_x = x * ((y_max + y) / (2 * y_max)) * trapezoidal_factor_x; *correct_delta_y = y * ((x_max + x) / (2 * x_max)) * trapezoidal_factor_y; } void GetWeightedAverageCorrection(double x, double y, double* correct_delta_x, double* correct_delta_y) { if (x < x_axis_plat_x_start) { x = x_axis_plat_x_start; } if (x > x_axis_plat_x_start + x_axis_plat_x_interval * (x_axis_plat_x_num - 1)) { x = x_axis_plat_x_start + x_axis_plat_x_interval * (x_axis_plat_x_num - 1); } if (x < y_axis_plat_x_start) { x = y_axis_plat_x_start; } if (x > y_axis_plat_x_start + y_axis_plat_x_interval * (y_axis_plat_x_num - 1)) { x = y_axis_plat_x_start + y_axis_plat_x_interval * (y_axis_plat_x_num - 1); } if (y < x_axis_plat_y_start) { y = x_axis_plat_y_start; } if (y > x_axis_plat_y_start + x_axis_plat_y_interval * (x_axis_plat_y_num - 1)) { y = x_axis_plat_y_start + x_axis_plat_y_interval * (x_axis_plat_y_num - 1); } if (y < y_axis_plat_y_start) { y = y_axis_plat_y_start; } if (y > y_axis_plat_y_start + y_axis_plat_y_interval * (y_axis_plat_y_num - 1)) { y = y_axis_plat_y_start + y_axis_plat_y_interval * (y_axis_plat_y_num - 1); } int x_index_x1 = (int)((x - x_axis_plat_x_start) / x_axis_plat_x_interval); if (x_index_x1 >= x_axis_plat_x_num - 1) { x_index_x1 = x_axis_plat_x_num - 2; } int x_index_x2 = x_index_x1 + 1; int x_index_y1 = (int)((y - x_axis_plat_y_start) / x_axis_plat_y_interval); if (x_index_y1 >= x_axis_plat_y_num - 1) { x_index_y1 = x_axis_plat_y_num - 2; } int x_index_y2 = x_index_y1 + 1; int y_index_x1 = (int)((x - y_axis_plat_x_start) / y_axis_plat_x_interval); if (y_index_x1 >= y_axis_plat_x_num - 1) { y_index_x1 = y_axis_plat_x_num - 2; } int y_index_x2 = y_index_x1 + 1; int y_index_y1 = (int)((y - y_axis_plat_y_start) / y_axis_plat_y_interval); if (y_index_y1 >= y_axis_plat_y_num - 1) { y_index_y1 = y_axis_plat_y_num - 2; } int y_index_y2 = y_index_y1 + 1; double x_board_left_top_x = x_axis_plat_x_start + x_index_x1 * x_axis_plat_x_interval; double x_board_left_top_y = x_axis_plat_y_start + x_index_y2 * x_axis_plat_y_interval; double x_board_left_bottom_x = x_board_left_top_x; double x_board_left_bottom_y = x_axis_plat_y_start + x_index_y1 * x_axis_plat_y_interval; double x_board_right_top_x = x_axis_plat_x_start + x_index_x2 * x_axis_plat_x_interval; double x_board_right_top_y = x_board_left_top_y; double x_board_right_bottom_x = x_board_right_top_x; double x_board_right_bottom_y = x_board_left_bottom_y; double y_board_left_top_x = y_axis_plat_x_start + y_index_x1 * y_axis_plat_x_interval; double y_board_left_top_y = y_axis_plat_y_start + y_index_y2 * y_axis_plat_y_interval; double y_board_left_bottom_x = y_board_left_top_x; double y_board_left_bottom_y = y_axis_plat_y_start + y_index_y1 * y_axis_plat_y_interval; double y_board_right_top_x = y_axis_plat_x_start + y_index_x2 * y_axis_plat_x_interval; double y_board_right_top_y = y_board_left_top_y; double y_board_right_bottom_x = y_board_right_top_x; double y_board_right_bottom_y = y_board_left_bottom_y; double x_internal_left_x = x_board_left_bottom_x; double x_internal_left_y = y; double x_internal_right_x = x_board_right_bottom_x; double x_internal_right_y = y; double x_internal_left_correct = x_axis_plat_correct[x_index_x1][x_index_y2] - (x_board_left_top_y - x_internal_left_y) / (x_board_left_top_y - x_board_left_bottom_y) * (x_axis_plat_correct[x_index_x1][x_index_y2] - x_axis_plat_correct[x_index_x1][x_index_y1]); double x_internal_right_correct = x_axis_plat_correct[x_index_x2][x_index_y2] - (x_board_right_top_y - x_internal_right_y) / (x_board_right_top_y - x_board_right_bottom_y) * (x_axis_plat_correct[x_index_x2][x_index_y2] - x_axis_plat_correct[x_index_x2][x_index_y1]); double x_internal_correct = x_internal_right_correct - (x_internal_right_x - x) / (x_internal_right_x - x_internal_left_x) * (x_internal_right_correct - x_internal_left_correct); double y_internal_left_x = y_board_left_bottom_x; double y_internal_left_y = y; double y_internal_right_x = y_board_right_bottom_x; double y_internal_right_y = y; double y_internal_left_correct = y_axis_plat_correct[y_index_x1][y_index_y2] - (y_board_left_top_y - y_internal_left_y) / (y_board_left_top_y - y_board_left_bottom_y) * (y_axis_plat_correct[y_index_x1][y_index_y2] - y_axis_plat_correct[y_index_x1][y_index_y1]); double y_internal_right_correct = y_axis_plat_correct[y_index_x2][y_index_y2] - (y_board_right_top_y - y_internal_right_y) / (y_board_right_top_y - y_board_right_bottom_y) * (y_axis_plat_correct[y_index_x2][y_index_y2] - y_axis_plat_correct[y_index_x2][y_index_y1]); double y_internal_correct = y_internal_right_correct - (y_internal_right_x - x) / (y_internal_right_x - y_internal_left_x) * (y_internal_right_correct - y_internal_left_correct); *correct_delta_x = x_internal_correct; *correct_delta_y = y_internal_correct; }
35.216667
194
0.70788
ZhukovWang
626dbbad9b3715695b472e261d966a651d977bcd
3,367
cpp
C++
src/iters/list/NormalList/normal_list.cpp
delightedok/TGSToolkits
7570378fde1f3045a545c293fddb275143701114
[ "MIT" ]
null
null
null
src/iters/list/NormalList/normal_list.cpp
delightedok/TGSToolkits
7570378fde1f3045a545c293fddb275143701114
[ "MIT" ]
null
null
null
src/iters/list/NormalList/normal_list.cpp
delightedok/TGSToolkits
7570378fde1f3045a545c293fddb275143701114
[ "MIT" ]
null
null
null
#include "../../../comms/comm_headers.h" #include <iters/list/normal_list.h> #define THIS_FILE "normal_list.cpp" #define LOG_TAG "ITERS-LIST-NORMAL" TGSTK_EXPORT NormalListObject::NormalListObject(ListVTable & mVTable): ListObject(mVTable) { /* A Ring List */ this->mDatas.next = &this->mDatas; this->mDatas.prev = &this->mDatas; } TGSTK_EXPORT NormalListObject::~NormalListObject(void) { this->clear(); } TGSTK_EXPORT int NormalListObject::iterate(Func_itersListOnIterate onIter, void * arg, int unwind) { int ret = 0; ListNode * p = NULL; if (unwind) { p = mDatas.prev; while (p != &mDatas && !ret) { ret = onIter(p->ptr.ptr, arg); p = p->prev; } } else { p = mDatas.next; while (p != &mDatas && !ret) { ret = onIter(p->ptr.ptr, arg); p = p->next; } } return ret; } TGSTK_EXPORT int NormalListObject::rpush(void * obj, int size) { int ret = -1; do { ListNode * pNode = (ListNode *)mmalloc(sizeof(ListNode)); if (!pNode) { mlog_e(LOG_TAG, THIS_FILE, "Failed to alloc memory for a New List Node."); break; } pNode->ptr.ptr = this->doDuplicate(obj); pNode->ptr.size = size; pNode->next = &mDatas; pNode->prev = mDatas.prev; mDatas.prev->next = pNode; mDatas.prev = pNode; mNdatas++; ret = 0; } while (0); return ret; } TGSTK_EXPORT int NormalListObject::lpush(void * obj, int size) { int ret = -1; do { ListNode * pNode = (ListNode *)mmalloc(sizeof(ListNode)); if (!pNode) { mlog_e(LOG_TAG, THIS_FILE, "Failed to alloc memory for a New List Node."); break; } pNode->ptr.ptr = this->doDuplicate(obj); pNode->ptr.size = size; pNode->next = mDatas.next; pNode->prev = &mDatas; mDatas.next->prev = pNode; mDatas.next = pNode; mNdatas++; ret = 0; } while (0); return ret; } TGSTK_EXPORT void * NormalListObject::rpop(void) { void * ret = NULL; do { ListNode * pNode = mDatas.prev; if (pNode == &mDatas) // there is NO data in list { mNdatas = 0; // to ensure the <field>mNdatas</field> is correct break; } pNode->prev->next = &mDatas; mDatas.prev = pNode->prev; mNdatas--; ret = pNode->ptr.ptr; mfree(pNode); } while (0); return ret; } TGSTK_EXPORT void * NormalListObject::lpop(void) { void * ret = NULL; do { ListNode * pNode = mDatas.next; if (pNode == &mDatas) // there is NO data in list { mNdatas = 0; // to ensure the <field>mNdatas</field> is correct break; } pNode->next->prev = &mDatas; mDatas.next = pNode->next; mNdatas--; ret = pNode->ptr.ptr; mfree(pNode); } while (0); return ret; } TGSTK_EXPORT int NormalListObject::clear(void) { while (this->mNdatas > 0) { void * data = this->rpop(); this->doFree(data); } return 0; }
24.940741
99
0.511435
delightedok
626dc45335637e840d258b1d4b8ec57627d86b75
3,514
cpp
C++
src/temp_dir.cpp
Nimanita/phpdesktop
ff14a60629ef105031b49fe751207811b1c93332
[ "NASA-1.3", "PHP-3.01", "PHP-3.0", "Zend-2.0" ]
2,342
2015-08-28T12:38:51.000Z
2022-03-31T21:53:23.000Z
src/temp_dir.cpp
Nimanita/phpdesktop
ff14a60629ef105031b49fe751207811b1c93332
[ "NASA-1.3", "PHP-3.01", "PHP-3.0", "Zend-2.0" ]
165
2015-09-10T06:58:22.000Z
2022-02-17T20:44:37.000Z
src/temp_dir.cpp
Nimanita/phpdesktop
ff14a60629ef105031b49fe751207811b1c93332
[ "NASA-1.3", "PHP-3.01", "PHP-3.0", "Zend-2.0" ]
600
2015-09-01T15:12:21.000Z
2022-03-29T20:12:04.000Z
// Copyright (c) 2012-2014 The PHP Desktop authors. All rights reserved. // License: New BSD License. // Website: http://code.google.com/p/phpdesktop/ #include "temp_dir.h" #include <Windows.h> #include "string_utils.h" #include "file_utils.h" #include "log.h" #include <vector> #include "executable.h" std::string GetAnsiTempDirectory() { // On Win7 GetTempPath returns path like this: // "C:\Users\%USER%\AppData\Local\Temp\" // Where %USER% may contain unicode characters and such // unicode path won't work with PHP. // -- // On WinXP it returns a short path like this: // C:\DOCUME~1\UNICOD~1\LOCALS~1\Temp // PHP also doesn't like windows short paths. Sessions will // work fine, but other stuff like uploading files won't work. // -- wchar_t tempPath[MAX_PATH]; GetTempPathW(MAX_PATH, tempPath); // Whether temp is a short path. std::string tempPathString = WideToUtf8(tempPath); bool isShortPath = false; // We can't be 100% sure if "~1" is a pattern for short paths, // better check only "~". if (tempPathString.length() && tempPathString.find("~") != std::string::npos) { isShortPath = true; } if (isShortPath || !AnsiDirectoryExists(WideToUtf8(tempPath))) { // This code will also run if the dir returned by // GetTempPathW was invalid. LOG_DEBUG << "The temp directory returned by OS contains " "unicode characters: " << WideToUtf8(tempPath).c_str(); // Fallback 1: C:\\Windows\\Temp // ----------------------------- TCHAR winDir[MAX_PATH]; std::string winTemp; if (GetWindowsDirectory(winDir, MAX_PATH) == 0) { winTemp = "C:\\Windows\\Temp"; } else { winTemp = WideToUtf8(winDir).append("\\Temp"); } if (IsDirectoryWritable(winTemp)) { return winTemp; } // Fallback 2: C:\\Temp // -------------------- if (IsDirectoryWritable("C:\\Temp")) { return "C:\\Temp"; } // Fallback 3: ./temp // ------------------ if (AnsiDirectoryExists(GetExecutableDirectory())) { // Application directory does not contain unicode characeters. std::string localTemp = GetExecutableDirectory().append("\\temp"); if (DirectoryExists(localTemp) && IsDirectoryWritable(localTemp)) { // Local temp directory already exists and is writable. return localTemp; } if (CreateDirectoryA(localTemp.c_str(), NULL) != 0 && IsDirectoryWritable(localTemp)) { // CreateDirectoryA - If the function succeeds, the return // value is nonzero. return localTemp; } } // Fallback 4: C:\\Users\\Public\\Temp // ----------------------------------- std::string publicTemp = "C:\\Users\\Public\\Temp"; if (DirectoryExists(publicTemp) && IsDirectoryWritable(publicTemp)) { return publicTemp; } if (CreateDirectoryA(publicTemp.c_str(), NULL) != 0 && IsDirectoryWritable(publicTemp)) { // CreateDirectoryA - If the function succeeds, the return // value is nonzero. return publicTemp; } } return WideToUtf8(tempPath); }
39.483146
80
0.551224
Nimanita
627513216813a58e18160816935874c8b895c69b
842
cpp
C++
Competitive Programming/Module 7 Programming Tools/code/stl3.cpp
mayank1101/Coding-Ninja
7d2c3a525e0867edf315b965b139f2288bfe009d
[ "MIT" ]
1
2020-12-15T19:36:01.000Z
2020-12-15T19:36:01.000Z
Competitive Programming/Module 7 Programming Tools/code/stl3.cpp
mayank1101/Coding-Ninja
7d2c3a525e0867edf315b965b139f2288bfe009d
[ "MIT" ]
null
null
null
Competitive Programming/Module 7 Programming Tools/code/stl3.cpp
mayank1101/Coding-Ninja
7d2c3a525e0867edf315b965b139f2288bfe009d
[ "MIT" ]
null
null
null
#include<iostream> #include<algorithm> #include<cmath> #include<utility> using namespace std; struct Interval{ int st; int et; }; bool compare(Interval i1,Interval i2){ return i1.st > i2.st; } int main(){ //Interval arr[] = {{6,4} , {3,4}, {4,6} , {8,13}}; //sort(arr,arr+4,compare); int arr[] = {1,3,2,5,7,6}; sort(arr,arr+6); for(int i=0;i<6;i++){ cout<<arr[i] << " "; } cout<<endl; cout << binary_search(arr,arr+6,2); cout<<endl; cout<<lower_bound(arr,arr+6,3) - arr; cout<<endl; cout<<upper_bound(arr,arr+6,3) - arr; cout<<endl; cout<<endl; cout<<__gcd(10,6)<<endl; cout<<pow(2.2,5)<<endl; int x= 10; int y=12; swap(x,y); cout<<x<<endl; cout<<y<<endl; cout<<max(14,18)<<endl; cout<<min(14,18)<<endl; // for(int i=0;i<4;i++){ // cout << arr[i].st << " : " << arr[i].et << endl; // } return 0; }
16.192308
63
0.571259
mayank1101
627964517042ec8a874b6f87af00bccef6b81940
301
cpp
C++
1101-9999/1509. Minimum Difference Between Largest and Smallest Value in Three Moves.cpp
erichuang1994/leetcode-solution
d5b3bb3ce2a428a3108f7369715a3700e2ba699d
[ "MIT" ]
null
null
null
1101-9999/1509. Minimum Difference Between Largest and Smallest Value in Three Moves.cpp
erichuang1994/leetcode-solution
d5b3bb3ce2a428a3108f7369715a3700e2ba699d
[ "MIT" ]
null
null
null
1101-9999/1509. Minimum Difference Between Largest and Smallest Value in Three Moves.cpp
erichuang1994/leetcode-solution
d5b3bb3ce2a428a3108f7369715a3700e2ba699d
[ "MIT" ]
null
null
null
class Solution { public: int minDifference(vector<int> &nums) { sort(nums.begin(), nums.end()); if (nums.size() <= 4) return 0; int ret = INT_MAX; for (int i = 0; i <= 3; i++) { ret = min(ret, nums[nums.size() - 1 - (3 - i)] - nums[i]); } return ret; } };
18.8125
64
0.491694
erichuang1994
627dc7ba66044aefcc038629d2d2a4e94451cb8b
289
cpp
C++
Additional Problems/Counting Bits.cpp
DecSP/cses-downloader
12a8f37665a33f6f790bd2c355f84dea8a0e332c
[ "MIT" ]
2
2022-02-12T12:30:13.000Z
2022-02-12T13:59:20.000Z
Additional Problems/Counting Bits.cpp
DecSP/cses-downloader
12a8f37665a33f6f790bd2c355f84dea8a0e332c
[ "MIT" ]
2
2022-02-12T11:09:41.000Z
2022-02-12T11:55:49.000Z
Additional Problems/Counting Bits.cpp
DecSP/cses-downloader
12a8f37665a33f6f790bd2c355f84dea8a0e332c
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define ll long long using namespace std; int main(){ ll n; cin>>n; ll cur=1,re=0; while (cur<=n){ ll x=n-(cur-1); re+=x/(cur<<1)*cur+min(x%(cur<<1),cur); cur<<=1; } cout<<re<<'\n'; return 0; } // 000 // 001 // 010 // 011 // 100 // 101 // 110 // 111
11.56
41
0.525952
DecSP
628eac564a36f670cfcb6ca0fc2e9677e540d107
812
cpp
C++
Source/GCE/Game/Widgets/GameOverWidget.cpp
ssapo/GCE
ddb5dfa2472c2f4ba01bf81d4fac9a64ac861e9f
[ "MIT" ]
2
2019-07-28T13:30:14.000Z
2019-11-22T08:14:28.000Z
Source/GCE/Game/Widgets/GameOverWidget.cpp
ssapo/GCE
ddb5dfa2472c2f4ba01bf81d4fac9a64ac861e9f
[ "MIT" ]
null
null
null
Source/GCE/Game/Widgets/GameOverWidget.cpp
ssapo/GCE
ddb5dfa2472c2f4ba01bf81d4fac9a64ac861e9f
[ "MIT" ]
1
2019-07-07T13:39:08.000Z
2019-07-07T13:39:08.000Z
// Fill out your copyright notice in the Description page of Project Settings. #include "GameOverWidget.h" #include <Button.h> #include "Game/ChessGameModeBase.h" void UGameOverWidget::NativeConstruct() { Super::NativeConstruct(); auto FoundGameMode = GetWorld()->GetAuthGameMode<AChessGameMode>(); GCE_CHECK(nullptr != FoundGameMode); GameMode = FoundGameMode; if (RestartButton) { RestartButton->OnClicked.AddDynamic(this, &UGameOverWidget::OnRestartClickedImpl); } if (LobbyButton) { LobbyButton->OnClicked.AddDynamic(this, &UGameOverWidget::OnLobbyClickedImpl); } } void UGameOverWidget::NativeDestruct() { Super::NativeDestruct(); } void UGameOverWidget::OnRestartClickedImpl() { GameMode->RestartGame(); } void UGameOverWidget::OnLobbyClickedImpl() { GameMode->GoLobby(); }
18.883721
78
0.756158
ssapo
629085920bf7d7a5a6f06b5cf28ec3732cdf5681
380
hpp
C++
Questless/Questless/external/vecx/constants.hpp
jonathansharman/questless
bb9ffb2d21cbfde2a71edfecfcbf466479bbbe7d
[ "MIT" ]
2
2020-07-14T12:50:06.000Z
2020-11-04T02:25:09.000Z
Questless/Questless/external/vecx/constants.hpp
jonathansharman/questless
bb9ffb2d21cbfde2a71edfecfcbf466479bbbe7d
[ "MIT" ]
null
null
null
Questless/Questless/external/vecx/constants.hpp
jonathansharman/questless
bb9ffb2d21cbfde2a71edfecfcbf466479bbbe7d
[ "MIT" ]
null
null
null
//! @file //! @copyright See <a href="LICENSE.txt">LICENSE.txt</a>. //! @brief Defines some mathematical constants. #pragma once namespace vecx::constants { //! Number of radians in one turn of a circle. constexpr double tau = 6.283185307179586476925286766559005768394338798750211641949; //! Number of radians in half a turn of a circle. constexpr double pi = tau / 2.0; }
27.142857
84
0.728947
jonathansharman
6290c2f1ed8d21d1ed2b25eeba53ff1be0e658d4
177
cpp
C++
c2017/wd/wd151/main.cpp
wmjtxt/c-exercise
d22336460cab825dd7ae98297bbe46febedfcece
[ "MIT" ]
null
null
null
c2017/wd/wd151/main.cpp
wmjtxt/c-exercise
d22336460cab825dd7ae98297bbe46febedfcece
[ "MIT" ]
null
null
null
c2017/wd/wd151/main.cpp
wmjtxt/c-exercise
d22336460cab825dd7ae98297bbe46febedfcece
[ "MIT" ]
null
null
null
#include "stdio.h" main() { int a,b; a=066; b=a&7; printf("\40: The a & b(decimal) is %d \n",b); b&=0xC; printf("\40: The a & b(decimal) is %d \n",b); }
16.090909
49
0.468927
wmjtxt
629e623873a26e475f54ff93c68770c75158196c
2,386
hpp
C++
minimgio/test/quantile_diff.hpp
SmartEngines/minimg_interfaces
b9276f4d800a7d4563c7e1aaa08ef927bbccb918
[ "BSD-3-Clause" ]
4
2021-07-14T11:27:40.000Z
2021-12-16T12:58:36.000Z
minimgio/test/quantile_diff.hpp
SmartEngines/minimg_interfaces
b9276f4d800a7d4563c7e1aaa08ef927bbccb918
[ "BSD-3-Clause" ]
null
null
null
minimgio/test/quantile_diff.hpp
SmartEngines/minimg_interfaces
b9276f4d800a7d4563c7e1aaa08ef927bbccb918
[ "BSD-3-Clause" ]
1
2021-12-20T10:18:39.000Z
2021-12-20T10:18:39.000Z
/* Copyright 2021 Smart Engines Service LLC Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ static void quantile_diff(uint8_t *the_diff, const MinImg &image_a, const MinImg &image_b) { ASSERT_EQ(NO_ERRORS, CompareMinImagePrototypes(&image_a, &image_b)); ASSERT_EQ(TYP_UINT8, GetMinImageType(&image_a)); const int len = image_a.width * image_a.channels; *the_diff = 0; const uint8_t *p_line_a = image_a.p_zero_line; const uint8_t *p_line_b = image_b.p_zero_line; int hist[256] = { 0 }; for (int y = 0; y < image_a.height; ++y) { for (int x = 0; x < len; ++x) { const uint8_t diff = p_line_a[x] > p_line_b[x] ? p_line_a[x] - p_line_b[x] : p_line_b[x] - p_line_a[x]; ++hist[diff]; } p_line_a += image_a.stride; p_line_b += image_b.stride; } const int threshold = image_a.height * len * 9 / 10; // 90% int cnt = 0; int i = 0; for (; i < 256 && cnt < threshold; ++i) { cnt += hist[i]; } *the_diff = i; }
40.440678
109
0.734702
SmartEngines
62a1f644302c885adc9d80989ecc1268e029033d
348
hpp
C++
include/geometry/geometry_define.hpp
hyperpower/Nablla
5a9be9f3b064a235572a1a2c9c5c2c19118697c5
[ "MIT" ]
null
null
null
include/geometry/geometry_define.hpp
hyperpower/Nablla
5a9be9f3b064a235572a1a2c9c5c2c19118697c5
[ "MIT" ]
1
2018-06-18T03:52:56.000Z
2018-06-18T03:52:56.000Z
include/geometry/geometry_define.hpp
hyperpower/CarpioPlus
68cc6c976d6c3ba6adec847a94c344be3f4690aa
[ "MIT" ]
null
null
null
#ifndef GEOMETRY_DEFINE_HPP_ #define GEOMETRY_DEFINE_HPP_ #include "type_define.hpp" #include <math.h> namespace carpio { struct TagGeometry{ TagGeometry(){}; }; enum IntersectionTypeSS { _SS_NO_ = 0, // _SS_CONNECT_ = 1, // _SS_TOUCH_ = 2, // _SS_OVERLAP_ = 3, // _SS_SAME_ = 4, // _SS_INTERSECT_= 5 }; } #endif
12.888889
28
0.646552
hyperpower
62ac6e54d23059ba4303fead2d807fded79f09a9
3,843
cc
C++
ch16/generic_programing/concepts.cc
leschus/cpp_primer_plus_6th
1d0ca7e22d41e5039dd08befd451c2c339e854f1
[ "MIT" ]
1
2022-03-04T08:34:18.000Z
2022-03-04T08:34:18.000Z
ch16/generic_programing/concepts.cc
leschus/cpp_primer_plus_6th
1d0ca7e22d41e5039dd08befd451c2c339e854f1
[ "MIT" ]
null
null
null
ch16/generic_programing/concepts.cc
leschus/cpp_primer_plus_6th
1d0ca7e22d41e5039dd08befd451c2c339e854f1
[ "MIT" ]
null
null
null
// 容器概念 // 使用set类为例, 对基本的容器特征进行测试 // C++11以前的容器类: // deque, list, queue, priority_queue, stack, vector, map, multimap, set, // multiset, bitset // C++11新增的容器类: // forward_list, unordered_map, unordered_multimap, unordered_set, // unordered_multiset // 另外, C++11不再将bitset视作容器, 而是一个独立的类别 #include <iostream> // #include <vector> #include <set> #include <string> #include <memory> // for unique_ptr #include <algorithm> // for for_each using std::cout; using std::endl; // using std::vector; using std::set; using std::string; using std::unique_ptr; using std::for_each; struct Demo { string str; int num; Demo() : str("empty"), num(0) { cout << "default c'tor called.\n"; } Demo(const string &s, int n) : str(s), num(n) { cout << str << ", " << num << ": c'tor called.\n"; } ~Demo() { cout << str << ", " << num << ": d'tor called.\n"; } bool operator==(const Demo &demo) const { // 注意函数头里有两个const, 都得加, 否则编译报错 return str == demo.str && num == demo.num; } Demo(const Demo &demo) : str(demo.str), num(demo.num) { cout << str << ", " << num << ": copy c'tor called.\n"; } const Demo & operator=(const Demo &demo) { // 赋值运算符的返回值需要指明为const吗? 对于a=b=c这样的赋值方式, 加不加都行. // 对于(a=b)=c这样的赋值方式, 不能加const; 或者可通过加const来禁止(a=b)=c // 这样的赋值方式. cout << "assignment: " << str << ", " << num << " <== " << demo.str << ", " << demo.num << endl; if (this == &demo) return *this; str = demo.str; num = demo.num; return *this; } bool operator<(const Demo &demo) const { // 由于set内部要进行自动排序, 因此要提供<比较运算符 // 注意: 函数头中两个const都是必要的 if (str < demo.str) return true; else if (str > demo.str) return false; else if (num < demo.num) return true; else return false; } }; // 用作for_each()的第三个参数 void print(const Demo &demo) { cout << demo.str << ", " << demo.num << endl; } int main() { { set<Demo> set0 = { // 使用列表初始化(C++11提供支持) Demo("first", 1), Demo("second", 2), Demo("third", 3) }; // 列表初始化首先对调用构造函数创建三个临时Demo, 再调用拷贝构造函数将每个临时Demo依次 // 复制到set<Demo>中. // 获得一个迭代器, 其满足正向迭代器的任何需求 // 通过指向第一个元素的迭代器和超尾迭代器来完成容器的遍历工作 set<Demo>::iterator iter; for (iter = set0.begin(); iter != set0.end(); iter++) cout << (*iter).str << ", " << (*iter).num << endl; // 使用X::value_type获得存储在容器中的对象类型 set<Demo>::value_type value("hello", 100); // 创建具名的空容器 set<Demo> has_name; // 创建匿名的空容器, 由一个unique_ptr指向, 用到了自动类型推断: auto auto p_noname = unique_ptr<set<Demo> >(new set<Demo>()); p_noname.release(); // 使用拷贝构造函数 set<Demo> old; set<Demo> newly(old); set<Demo> newlly = old; // 效果和上一句相同 // 使用赋值运算符 set<Demo> yesterday = {Demo("day", -1)}; set<Demo> today; today = yesterday; // 获得容器内的元素个数 // 对容器中的每个元素应用析构函数: 这应该是是STL实现容器的析构函数时所使用的一种内置操作 // 尽量避免在代码里用这种方式手动对容器内元素执行析构, 因为这会导致容器过期时执行析构函数 // 对已析构的元素进行二次析构. set<Demo> several_demos = { Demo("a", -1), Demo("b", 0), Demo("c", 1) }; cout << several_demos.size() << endl; // (&several_demos)->~set<Demo>(); // 这里注释掉上面这句, 否则程序退出前自动执行析构会出现错误 // cout << several_demos.size() << endl; // 上一句测试表明: 手动执行析构函数后, 容器的size()没有变化 // 交换两个容器的内容: x.swap(y) set<Demo> x = { Demo("a", 1), Demo("b", 2) }; set<Demo> y = { Demo("m", -1), Demo("n", -2) }; x.swap(y); cout << "Contents of x:\n"; for_each(x.begin(), x.end(), print); cout << "Contents of y:\n"; for_each(y.begin(), y.end(), print); // ==运算符 // `a == b`为真, 当且仅当a和b的长度相同, 且a, b中相应位置的元素对应相等(==) // !=运算符: `a != b`等价于`!(a == b)` // 注: 要求存储类型定义了==运算符 if (today == yesterday) cout << "today equals to yesterday.\n"; if (x != y) cout << "x not equals to y.\n"; } // 本代码块结束时, 内部创建的容器将自动调用析构函数释放分配的空间 cout << "Done.\n"; return 0; }
27.255319
76
0.574811
leschus
62ac6eb54782f0cb92b7a798711b195b7f4f3c3e
3,830
hpp
C++
third_party/boost/simd/arch/common/scalar/function/ffs.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
6
2018-02-25T22:23:33.000Z
2021-01-15T15:13:12.000Z
third_party/boost/simd/arch/common/scalar/function/ffs.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
null
null
null
third_party/boost/simd/arch/common/scalar/function/ffs.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
7
2017-12-12T12:36:31.000Z
2020-02-10T14:27:07.000Z
//================================================================================================== /*! @file @copyright 2016 NumScale SAS Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ //================================================================================================== #ifndef BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_FFS_HPP_INCLUDED #define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_FFS_HPP_INCLUDED #include <boost/simd/detail/make_dependent.hpp> #include <boost/simd/function/bitwise_and.hpp> #include <boost/simd/function/bitwise_cast.hpp> #include <boost/simd/detail/dispatch/function/overload.hpp> #include <boost/simd/detail/dispatch/meta/as_integer.hpp> #include <boost/config.hpp> namespace boost { namespace simd { namespace ext { namespace bd = boost::dispatch; namespace bs = boost::simd; BOOST_DISPATCH_OVERLOAD ( ffs_ , (typename A0) , bd::cpu_ , bd::scalar_< bd::type64_<A0> > ) { using result_t = bd::as_integer_t<A0>; result_t operator() ( A0 a0) const { result_t t1 = bitwise_cast<result_t>(a0); #ifdef __GNUC__ return __builtin_ffsll(t1); #elif defined BOOST_MSVC && defined _WIN64 unsigned long index; if(_BitScanForward64(&index, uint64_t(t1))) return index+1; return 0; #elif defined BOOST_MSVC unsigned long index; if (bitwise_and(t1, (uint64_t(-1) >> 32))) { _BitScanForward(&index, uint32_t(t1)); return index+1; } if(_BitScanForward(&index, uint32_t(t1 >> 32))) return index+1 + 32; return 0; #else if(!t1) return 0; // see http://supertech.csail.mit.edu/papers/debruijn.pdf const uint64_t magic = 0x03f79d71b4cb0a89ULL; static const unsigned int magictable[64] = { 0, 1, 48, 2, 57, 49, 28, 3, 61, 58, 50, 42, 38, 29, 17, 4, 62, 55, 59, 36, 53, 51, 43, 22, 45, 39, 33, 30, 24, 18, 12, 5, 63, 47, 56, 27, 60, 41, 37, 16, 54, 35, 52, 21, 44, 32, 23, 11, 46, 26, 40, 15, 34, 20, 31, 10, 25, 14, 19, 9, 13, 8, 7, 6, }; return magictable[((t1&-t1)*magic) >> 58] + 1; #endif } }; BOOST_DISPATCH_OVERLOAD ( ffs_ , (typename A0) , bd::cpu_ , bd::scalar_< bd::type32_<A0> > ) { using result_t = bd::as_integer_t<A0>; result_t operator() ( A0 a0) const { result_t t1 = bitwise_cast<result_t>(a0); #ifdef __GNUC__ return __builtin_ffs(t1); #elif defined(BOOST_MSVC) unsigned long index; if(_BitScanForward(&index, t1)) return index+1; return 0; #else if(!t1) return 0; // see http://supertech.csail.mit.edu/papers/debruijn.pdf static const uint32_t magic = 0x077CB531U; static const int magictable[32] = { 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8, 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9 }; return magictable[((t1&-t1)*magic) >> 27] + 1; #endif } }; BOOST_DISPATCH_OVERLOAD ( ffs_ , (typename A0) , bd::cpu_ , bd::scalar_< bd::arithmetic_<A0> > ) { using result_t = typename bd::as_integer_t<A0>; result_t operator() ( A0 a0) const { result_t t1 = bitwise_cast<result_t>(a0); using i_t = typename detail::make_dependent<uint32_t, A0>::type; return result_t(bs::ffs(i_t(t1))); } }; } } } #endif
29.236641
100
0.527415
SylvainCorlay
62b7f1a3de9841764503afc26e6e98e936a756c6
1,013
cc
C++
basic/string/atoi_test.cc
chanchann/littleMickle
f3a839d8ad55f483bbac4e4224dcd35234c5aa00
[ "MIT" ]
1
2021-03-16T02:13:12.000Z
2021-03-16T02:13:12.000Z
basic/string/atoi_test.cc
chanchann/littleMickle
f3a839d8ad55f483bbac4e4224dcd35234c5aa00
[ "MIT" ]
null
null
null
basic/string/atoi_test.cc
chanchann/littleMickle
f3a839d8ad55f483bbac4e4224dcd35234c5aa00
[ "MIT" ]
null
null
null
#include <iostream> #include <string> int main() { std::string str = "200 OK\r\n" "accept-ranges: bytes\r\n" "cache-control: max-age=86400\r\n" "connection: keep-alive\r\n" "content-length: 81\r\n" "content-type: text/html\r\n" "date: Sat, 20 Mar 2021 05:48:53 GMT\r\n" "etag: \"51-47cf7e6ee8400\"\r\n" "expires: Sun, 21 Mar 2021 05:48:53 GMT\r\n" "keep-alive: timeout=4\r\n" "last-modified: Tue, 12 Jan 2010 13:48:00 GMT\r\n" "proxy-connection: keep-alive\r\n" "server: Apache\r\n\r\n" "<html>\r\n" "<meta http-equiv=\"refresh\" content=\"0;url=http://www.baidu.com/\">\r\n" "</html>\r\n"; std::cout << atoi(str.c_str()) << std::endl; }
42.208333
99
0.411649
chanchann
4985f5c7e987a87eac34ea54b038baa8bbad7c28
749
cpp
C++
src/Kernel/RandomDevice.cpp
Terryhata6/Mengine
dfe36fdc84d7398fbbbd199feffc46c6f157f1d4
[ "MIT" ]
39
2016-04-21T03:25:26.000Z
2022-01-19T14:16:38.000Z
src/Kernel/RandomDevice.cpp
Terryhata6/Mengine
dfe36fdc84d7398fbbbd199feffc46c6f157f1d4
[ "MIT" ]
23
2016-06-28T13:03:17.000Z
2022-02-02T10:11:54.000Z
src/Kernel/RandomDevice.cpp
Terryhata6/Mengine
dfe36fdc84d7398fbbbd199feffc46c6f157f1d4
[ "MIT" ]
14
2016-06-22T20:45:37.000Z
2021-07-05T12:25:19.000Z
#include "RandomDevice.h" #include <chrono> namespace Mengine { namespace Helper { uint32_t generateRandomDeviceSeed() { std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); std::chrono::time_point<std::chrono::system_clock, std::chrono::nanoseconds> now_ns = std::chrono::time_point_cast<std::chrono::nanoseconds>(now); std::chrono::time_point<std::chrono::system_clock, std::chrono::nanoseconds>::duration epoch = now_ns.time_since_epoch(); std::chrono::nanoseconds value = std::chrono::duration_cast<std::chrono::nanoseconds>(epoch); uint32_t now_ns_count = (uint32_t)value.count(); return now_ns_count; } } }
35.666667
158
0.654206
Terryhata6
4987d28df603c588f010350cde9b3e677c54078f
6,346
cpp
C++
src/utility.cpp
jlangvand/jucipp
0a3102f13e62d78a329d488fb1eb8812181e448e
[ "MIT" ]
null
null
null
src/utility.cpp
jlangvand/jucipp
0a3102f13e62d78a329d488fb1eb8812181e448e
[ "MIT" ]
null
null
null
src/utility.cpp
jlangvand/jucipp
0a3102f13e62d78a329d488fb1eb8812181e448e
[ "MIT" ]
null
null
null
#include "utility.hpp" #include <algorithm> #include <cstring> #include <vector> ScopeGuard::~ScopeGuard() { if(on_exit) on_exit(); } size_t utf8_character_count(const std::string &text, size_t pos, size_t length) noexcept { size_t characters = 0; auto size = length == std::string::npos ? text.size() : std::min(pos + length, text.size()); for(; pos < size;) { if(static_cast<unsigned char>(text[pos]) <= 0b01111111) { ++characters; ++pos; } else if(static_cast<unsigned char>(text[pos]) >= 0b11111000) // Invalid UTF-8 byte ++pos; else if(static_cast<unsigned char>(text[pos]) >= 0b11110000) { ++characters; pos += 4; } else if(static_cast<unsigned char>(text[pos]) >= 0b11100000) { ++characters; pos += 3; } else if(static_cast<unsigned char>(text[pos]) >= 0b11000000) { ++characters; pos += 2; } else // // Invalid start of UTF-8 character ++pos; } return characters; } size_t utf16_code_units_byte_count(const std::string &text, size_t code_units, size_t start_pos) { if(code_units == 0) return 0; size_t pos = start_pos; size_t current_code_units = 0; for(; pos < text.size();) { if(static_cast<unsigned char>(text[pos]) <= 0b01111111) { ++current_code_units; ++pos; if(current_code_units >= code_units) break; } else if(static_cast<unsigned char>(text[pos]) >= 0b11111000) // Invalid UTF-8 byte ++pos; else if(static_cast<unsigned char>(text[pos]) >= 0b11110000) { current_code_units += 2; pos += 4; if(current_code_units >= code_units) break; } else if(static_cast<unsigned char>(text[pos]) >= 0b11100000) { ++current_code_units; pos += 3; if(current_code_units >= code_units) break; } else if(static_cast<unsigned char>(text[pos]) >= 0b11000000) { ++current_code_units; pos += 2; if(current_code_units >= code_units) break; } else // // Invalid start of UTF-8 character ++pos; } return pos - start_pos; } size_t utf16_code_unit_count(const std::string &text, size_t pos, size_t length) { size_t code_units = 0; auto size = length == std::string::npos ? text.size() : std::min(pos + length, text.size()); for(; pos < size;) { if(static_cast<unsigned char>(text[pos]) <= 0b01111111) { ++code_units; ++pos; } else if(static_cast<unsigned char>(text[pos]) >= 0b11111000) // Invalid UTF-8 byte ++pos; else if(static_cast<unsigned char>(text[pos]) >= 0b11110000) { code_units += 2; pos += 4; } else if(static_cast<unsigned char>(text[pos]) >= 0b11100000) { ++code_units; pos += 3; } else if(static_cast<unsigned char>(text[pos]) >= 0b11000000) { ++code_units; pos += 2; } else // // Invalid start of UTF-8 character ++pos; } return code_units; } bool starts_with(const char *str, const std::string &test) noexcept { for(size_t i = 0; i < test.size(); ++i) { if(*str == '\0') return false; if(*str != test[i]) return false; ++str; } return true; } bool starts_with(const char *str, const char *test) noexcept { for(; *test != '\0'; ++test) { if(*str == '\0') return false; if(*str != *test) return false; ++str; } return true; } bool starts_with(const std::string &str, const std::string &test) noexcept { return str.compare(0, test.size(), test) == 0; } bool starts_with(const std::string &str, const char *test) noexcept { for(size_t i = 0; i < str.size(); ++i) { if(*test == '\0') return true; if(str[i] != *test) return false; ++test; } return *test == '\0'; } bool starts_with(const std::string &str, size_t pos, const std::string &test) noexcept { if(pos > str.size()) return false; return str.compare(pos, test.size(), test) == 0; } bool starts_with(const std::string &str, size_t pos, const char *test) noexcept { if(pos > str.size()) return false; for(size_t i = pos; i < str.size(); ++i) { if(*test == '\0') return true; if(str[i] != *test) return false; ++test; } return *test == '\0'; } bool ends_with(const std::string &str, const std::string &test) noexcept { if(test.size() > str.size()) return false; return str.compare(str.size() - test.size(), test.size(), test) == 0; } bool ends_with(const std::string &str, const char *test) noexcept { auto test_size = strlen(test); if(test_size > str.size()) return false; return str.compare(str.size() - test_size, test_size, test) == 0; } std::string escape(const std::string &input, const std::set<char> &escape_chars) { std::string result; result.reserve(input.size()); for(auto &chr : input) { if(escape_chars.find(chr) != escape_chars.end()) result += '\\'; result += chr; } return result; } std::string to_hex_string(const std::string &input) { std::string result; result.reserve(input.size() * 2); std::string hex_chars = "0123456789abcdef"; for(auto &chr : input) { result += hex_chars[static_cast<unsigned char>(chr) >> 4]; result += hex_chars[static_cast<unsigned char>(chr) & 0x0f]; } return result; } int version_compare(const std::string &lhs, const std::string &rhs) { static auto get_parts = [](const std::string &str) { std::vector<int> result; std::string tmp; for(auto &chr : str) { if(chr >= '0' && chr <= '9') tmp += chr; else if(chr == '.') { if(!tmp.empty()) { try { result.emplace_back(std::stoi(tmp)); } catch(...) { } tmp.clear(); } } else tmp += std::to_string(static_cast<unsigned char>(chr)); // Convert for instance letters to numbers } if(!tmp.empty()) { try { result.emplace_back(std::stoi(tmp)); } catch(...) { } tmp.clear(); } return result; }; auto lhs_parts = get_parts(lhs); auto rhs_parts = get_parts(rhs); if(std::equal(lhs_parts.begin(), lhs_parts.end(), rhs_parts.begin(), rhs_parts.end())) return 0; if(std::lexicographical_compare(lhs_parts.begin(), lhs_parts.end(), rhs_parts.begin(), rhs_parts.end())) return -1; return 1; }
27.004255
106
0.593445
jlangvand
498a2d9b86e90f7f44ba21df87fe994325286b98
497
hpp
C++
include/core/p_render/backend/resources/Resource.hpp
jabronicus/P-Engine
7786c2f97d19bd2913b706f6afe5087a392b1a3c
[ "MIT" ]
null
null
null
include/core/p_render/backend/resources/Resource.hpp
jabronicus/P-Engine
7786c2f97d19bd2913b706f6afe5087a392b1a3c
[ "MIT" ]
null
null
null
include/core/p_render/backend/resources/Resource.hpp
jabronicus/P-Engine
7786c2f97d19bd2913b706f6afe5087a392b1a3c
[ "MIT" ]
1
2021-08-24T05:43:01.000Z
2021-08-24T05:43:01.000Z
#pragma once // this will be the generic graphics-backend resource class namespace backend { class Resource { public: // gonna try using these virtual bool isImage() const { return false; } virtual bool isBuffer() const { return false; } virtual bool isSwapchainImage() const { return false; } protected: Resource() { } ~Resource() = default; // i don't think the base resource class needs to do much }; }
15.060606
61
0.599598
jabronicus
498a310e91c3eef7ce5acff088c231cf8c9db07f
41
hpp
C++
src/gen/client.hpp
kazupon/kt-msgpack
a995eaaf01128b2b5f9d3a9cccc566de27c368cd
[ "Apache-2.0" ]
1
2021-08-16T03:14:21.000Z
2021-08-16T03:14:21.000Z
src/gen/client.hpp
kazupon/kt-msgpack
a995eaaf01128b2b5f9d3a9cccc566de27c368cd
[ "Apache-2.0" ]
null
null
null
src/gen/client.hpp
kazupon/kt-msgpack
a995eaaf01128b2b5f9d3a9cccc566de27c368cd
[ "Apache-2.0" ]
null
null
null
#include "KyotoTycoonService_client.hpp"
20.5
40
0.853659
kazupon
498c873b30d5f7eec1f769346b414c781cb364fd
7,535
cpp
C++
planning/scenario_planning/lane_driving/behavior_planning/behavior_velocity_planner/src/scene_module/occlusion_spot/grid_utils.cpp
loop-perception/AutowareArchitectureProposal.iv
5d8dff0db51634f0c42d2a3e87ca423fbee84348
[ "Apache-2.0" ]
12
2020-09-25T08:52:59.000Z
2020-10-05T02:39:31.000Z
planning/scenario_planning/lane_driving/behavior_planning/behavior_velocity_planner/src/scene_module/occlusion_spot/grid_utils.cpp
loop-perception/AutowareArchitectureProposal.iv
5d8dff0db51634f0c42d2a3e87ca423fbee84348
[ "Apache-2.0" ]
7
2021-12-13T04:28:48.000Z
2022-03-14T13:53:15.000Z
planning/scenario_planning/lane_driving/behavior_planning/behavior_velocity_planner/src/scene_module/occlusion_spot/grid_utils.cpp
taikitanaka3/AutowareArchitectureProposal.iv
0d47ea532118c98458516a8c83fbdab3d27c6231
[ "Apache-2.0" ]
9
2020-09-27T05:27:09.000Z
2020-10-08T03:14:25.000Z
// Copyright 2021 Tier IV, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <grid_map_ros/GridMapRosConverter.hpp> #include <scene_module/occlusion_spot/grid_utils.hpp> #include <algorithm> #include <vector> namespace behavior_velocity_planner { namespace grid_utils { bool isOcclusionSpotSquare( OcclusionSpotSquare & occlusion_spot, const grid_map::Matrix & grid_data, const grid_map::Index & cell, int side_size, const grid_map::Size & grid_size) { // Calculate ranges to check int min_x; int max_x; int min_y; int max_y; // No occlusion_spot with size 0 if (side_size == 0) { return false; } /** * @brief * (min_x,min_y)...(max_x,min_y) * . . * (min_x,max_y)...(max_x,max_y) */ const int offset = side_size - 1; min_x = cell.x(); max_x = cell.x() + offset; min_y = cell.y() - offset; max_y = cell.y(); // Ensure we stay inside the grid min_x = std::max(0, min_x); max_x = std::min(grid_size.x() - 1, max_x); min_y = std::max(0, min_y); max_y = std::min(grid_size.y() - 1, max_y); for (int x = min_x; x <= max_x; ++x) { for (int y = min_y; y <= max_y; ++y) { // if the value is not unknown value return false if (grid_data(x, y) != grid_utils::occlusion_cost_value::UNKNOWN) { return false; } } } occlusion_spot.side_size = side_size; occlusion_spot.index = cell; return true; } void findOcclusionSpots( std::vector<grid_map::Position> & occlusion_spot_positions, const grid_map::GridMap & grid, const lanelet::BasicPolygon2d & polygon, double min_size) { const grid_map::Matrix & grid_data = grid["layer"]; const int min_occlusion_spot_size = std::max(0.0, std::floor(min_size / grid.getResolution())); grid_map::Polygon grid_polygon; for (const auto & point : polygon) { grid_polygon.addVertex({point.x(), point.y()}); } for (grid_map::PolygonIterator iterator(grid, grid_polygon); !iterator.isPastEnd(); ++iterator) { OcclusionSpotSquare occlusion_spot_square; if (isOcclusionSpotSquare( occlusion_spot_square, grid_data, *iterator, min_occlusion_spot_size, grid.getSize())) { if (!grid.getPosition(occlusion_spot_square.index, occlusion_spot_square.position)) { continue; } std::vector<grid_map::Position> corner_positions; getCornerPositions(corner_positions, grid, occlusion_spot_square); for (const grid_map::Position & corner : corner_positions) { occlusion_spot_positions.emplace_back(corner); } } } } bool isCollisionFree( const grid_map::GridMap & grid, const grid_map::Position & p1, const grid_map::Position & p2) { const grid_map::Matrix & grid_data = grid["layer"]; try { for (grid_map::LineIterator iterator(grid, p1, p2); !iterator.isPastEnd(); ++iterator) { const grid_map::Index & index = *iterator; if (grid_data(index.x(), index.y()) == grid_utils::occlusion_cost_value::OCCUPIED) { return false; } } } catch (const std::invalid_argument & e) { std::cerr << e.what() << std::endl; } return true; } void getCornerPositions( std::vector<grid_map::Position> & corner_positions, const grid_map::GridMap & grid, const OcclusionSpotSquare & occlusion_spot_square) { // Special case with size = 1: only one cell if (occlusion_spot_square.side_size == 1) { corner_positions.emplace_back(occlusion_spot_square.position); return; } std::vector<grid_map::Index> corner_indexes; const int offset = (occlusion_spot_square.side_size - 1) / 2; /** * @brief relation of each grid position * bl br * tl tr */ corner_indexes = {// bl grid_map::Index( std::max(0, occlusion_spot_square.index.x() - offset), std::max(0, occlusion_spot_square.index.y() - offset)), // br grid_map::Index( std::min(grid.getSize().x() - 1, occlusion_spot_square.index.x() + offset), std::max(0, occlusion_spot_square.index.y() - offset)), // tl grid_map::Index( std::max(0, occlusion_spot_square.index.x() - offset), std::min(grid.getSize().y() - 1, occlusion_spot_square.index.y() + offset)), // tr grid_map::Index( std::min(grid.getSize().x() - 1, occlusion_spot_square.index.x() + offset), std::min(grid.getSize().y() - 1, occlusion_spot_square.index.y() + offset))}; for (const grid_map::Index & corner_index : corner_indexes) { grid_map::Position corner_position; grid.getPosition(corner_index, corner_position); corner_positions.emplace_back(corner_position); } } void imageToOccupancyGrid(const cv::Mat & cv_image, nav_msgs::msg::OccupancyGrid * occupancy_grid) { const int width = cv_image.cols; const int height = cv_image.rows; occupancy_grid->data.clear(); occupancy_grid->data.resize(width * height); for (int x = width - 1; x >= 0; x--) { for (int y = height - 1; y >= 0; y--) { const int idx = (height - 1 - y) + (width - 1 - x) * height; const unsigned char intensity = cv_image.at<unsigned char>(y, x); occupancy_grid->data.at(idx) = intensity; } } } void toQuantizedImage( const nav_msgs::msg::OccupancyGrid & occupancy_grid, cv::Mat * cv_image, const GridParam & param) { const int width = cv_image->cols; const int height = cv_image->rows; for (int x = width - 1; x >= 0; x--) { for (int y = height - 1; y >= 0; y--) { const int idx = (height - 1 - y) + (width - 1 - x) * height; int8_t intensity = occupancy_grid.data.at(idx); if (0 <= intensity && intensity < param.free_space_max) { intensity = grid_utils::occlusion_cost_value::FREE_SPACE; } else if ( // NOLINT intensity == occlusion_cost_value::NO_INFORMATION || intensity < param.occupied_min) { intensity = grid_utils::occlusion_cost_value::UNKNOWN; } else { intensity = grid_utils::occlusion_cost_value::OCCUPIED; } cv_image->at<unsigned char>(y, x) = intensity; } } } void denoiseOccupancyGridCV( nav_msgs::msg::OccupancyGrid & occupancy_grid, grid_map::GridMap & grid_map, const GridParam & param) { cv::Mat cv_image( occupancy_grid.info.width, occupancy_grid.info.height, CV_8UC1, cv::Scalar(grid_utils::occlusion_cost_value::OCCUPIED)); toQuantizedImage(occupancy_grid, &cv_image, param); constexpr int num_iter = 2; //!< @brief opening & closing to remove noise in occupancy grid cv::dilate(cv_image, cv_image, cv::Mat(), cv::Point(-1, -1), num_iter); cv::erode(cv_image, cv_image, cv::Mat(), cv::Point(-1, -1), num_iter); imageToOccupancyGrid(cv_image, &occupancy_grid); grid_map::GridMapRosConverter::fromOccupancyGrid(occupancy_grid, "layer", grid_map); } } // namespace grid_utils } // namespace behavior_velocity_planner
37.675
99
0.652422
loop-perception
498ebe57c0a4b24adb5b38e1a0ac5f3d3a9962af
61
hpp
C++
src/boost_geometry_iterators_concatenate_iterator.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_geometry_iterators_concatenate_iterator.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_geometry_iterators_concatenate_iterator.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/geometry/iterators/concatenate_iterator.hpp>
30.5
60
0.852459
miathedev
499173e7eebb7f619f7390520efea01b14d7b662
8,388
cpp
C++
calc_sol/calc_unit_tests/TestCalculator.cpp
marcincinik/plot2d
9fbfa97bb0dc97feb9c8c190a097abba41e7da06
[ "Apache-2.0" ]
2
2019-02-13T15:47:18.000Z
2019-07-12T23:37:22.000Z
calc_sol/calc_unit_tests/TestCalculator.cpp
marcincinik/plot2d
9fbfa97bb0dc97feb9c8c190a097abba41e7da06
[ "Apache-2.0" ]
null
null
null
calc_sol/calc_unit_tests/TestCalculator.cpp
marcincinik/plot2d
9fbfa97bb0dc97feb9c8c190a097abba41e7da06
[ "Apache-2.0" ]
null
null
null
#include "stdafx.h" #include "TestCalculator.h" #include "..\calc_parser\Calculator.h" #include "CAssert.h" #include "CUnit.h" #include <vector> #include <string> using namespace std; using namespace cunit; using namespace parser; using namespace calc; namespace parser_tests { Calculator* calc; stringstream* ct_s = NULL; FunctionLookupTable* ct_ftl; ConstantLookupTable* ct_clt; Parser* ct_parser; AstNode* ct_ast = NULL; void ct_setup() { ct_ftl = new StdFunctionLookupTable(); ct_clt = new StdConstantLookupTable(); ct_s = new stringstream(); ct_parser = new Parser(*ct_s, ct_clt, ct_ftl); ct_ast = NULL; } void ct_cleanup() { delete calc; delete ct_s; delete ct_ftl; delete ct_clt; delete ct_parser; if (ct_ast != NULL) { delete ct_ast; } calc = NULL; ct_s = NULL; ct_ftl = NULL; ct_clt = NULL; ct_parser = NULL; ct_ast = NULL; } void ct_testRPNPlus() { *ct_s << "1 2 +"; calc = new Calculator(string("x"), ct_ftl, ct_clt, *ct_s); double result = calc->calculate(0.0f); CAssert::assertEquals(3.0f, result); } void ct_testASTPlus() { *ct_s << "1+2"; ct_parser->begin(); ct_ast = ct_parser->expr(); calc = new Calculator(string("x"), ct_ftl, ct_clt, ct_ast); double result = calc->calculate(0.0f); CAssert::assertEquals(3.0f, result); } void ct_testRPNMinus() { *ct_s << "1 2 -"; calc = new Calculator(string("x"), ct_ftl, ct_clt, *ct_s); double result = calc->calculate(0.0f); CAssert::assertEquals(-1.0f, result); } void ct_testASTMinus() { *ct_s << "1-2"; ct_parser->begin(); ct_ast = ct_parser->expr(); calc = new Calculator(string("x"), ct_ftl, ct_clt, ct_ast); double result = calc->calculate(0.0f); CAssert::assertEquals(-1.0f, result); } void ct_testRPNUnaryNeg() { *ct_s << "1 ~"; calc = new Calculator(string("x"), ct_ftl, ct_clt, *ct_s); double result = calc->calculate(0.0f); CAssert::assertEquals(-1.0f, result); } void ct_testASTUnaryNeg() { *ct_s << "-1"; ct_parser->begin(); ct_ast = ct_parser->expr(); calc = new Calculator(string("x"), ct_ftl, ct_clt, ct_ast); double result = calc->calculate(0.0f); CAssert::assertEquals(-1.0f, result); } void ct_testRPNMul() { *ct_s << "2 3 *"; calc = new Calculator(string("x"), ct_ftl, ct_clt, *ct_s); double result = calc->calculate(0.0f); CAssert::assertEquals(6.0f, result); } void ct_testASTMul() { *ct_s << "2*3"; ct_parser->begin(); ct_ast = ct_parser->expr(); calc = new Calculator(string("x"), ct_ftl, ct_clt, ct_ast); double result = calc->calculate(0.0f); CAssert::assertEquals(6.0f, result); } void ct_testRPNDiv() { *ct_s << "6 3 /"; calc = new Calculator(string("x"), ct_ftl, ct_clt, *ct_s); double result = calc->calculate(0.0f); CAssert::assertEquals(2.0f, result); } void ct_testASTDiv() { *ct_s << "6/3"; ct_parser->begin(); ct_ast = ct_parser->expr(); calc = new Calculator(string("x"), ct_ftl, ct_clt, ct_ast); double result = calc->calculate(0.0f); CAssert::assertEquals(2.0f, result); } void ct_testRPNPow() { *ct_s << "2 3 ^"; calc = new Calculator(string("x"), ct_ftl, ct_clt, *ct_s); double result = calc->calculate(0.0f); CAssert::assertEquals(8.0f, result); } void ct_testASTPow() { *ct_s << "2^3"; ct_parser->begin(); ct_ast = ct_parser->expr(); calc = new Calculator(string("x"), ct_ftl, ct_clt, ct_ast); double result = calc->calculate(0.0f); CAssert::assertEquals(8.0f, result); } void ct_testRPNVariable() { *ct_s << "x"; calc = new Calculator(string("x"), ct_ftl, ct_clt, *ct_s); double result = calc->calculate(1.0f); CAssert::assertEquals(1.0f, result); } void ct_testASTVariable() { *ct_s << "x"; ct_parser->begin(); ct_ast = ct_parser->expr(); calc = new Calculator(string("x"), ct_ftl, ct_clt, ct_ast); double result = calc->calculate(1.0f); CAssert::assertEquals(1.0f, result); } void ct_testRPNConst() { ct_clt->add(string("c"), 1.0); *ct_s << "c"; calc = new Calculator(string("x"), ct_ftl, ct_clt, *ct_s); double result = calc->calculate(0.0f); CAssert::assertEquals(1.0f, result); } void ct_testASTConst() { ct_clt->add(string("c"), 1.0); *ct_s << "c"; ct_parser->begin(); ct_ast = ct_parser->expr(); calc = new Calculator(string("x"), ct_ftl, ct_clt, ct_ast); double result = calc->calculate(0.0f); CAssert::assertEquals(1.0f, result); } void ct_testRPNFunc() { ct_ftl->add(string("f"), new FunctionIdentity()); *ct_s << "2.0 f"; calc = new Calculator(string("x"), ct_ftl, ct_clt, *ct_s); double result = calc->calculate(1.0f); CAssert::assertEquals(2.0f, result); } void ct_testASTFunc() { ct_ftl->add(string("f"), new FunctionIdentity()); *ct_s << "f(2.0)"; ct_parser->begin(); ct_ast = ct_parser->expr(); calc = new Calculator(string("x"), ct_ftl, ct_clt, ct_ast); double result = calc->calculate(0.0f); CAssert::assertEquals(2.0f, result); } void ct_testRPNWiki() { *ct_s << "12 2 3 4 * 10 5 / + * +"; calc = new Calculator(string("x"), ct_ftl, ct_clt, *ct_s); double result = calc->calculate(1.0f); CAssert::assertEquals(40.0f, result); } void ct_testASTWiki() { *ct_s << "((2+7)/3+(14-3)*4)/2"; ct_parser->begin(); ct_ast = ct_parser->expr(); calc = new Calculator(string("x"), ct_ftl, ct_clt, ct_ast); double result = calc->calculate(0.0f); CAssert::assertEquals(23.5f, result); } void ct_testSaveLoad1() { stringstream s2; *ct_s << "1~ 2 +"; calc = new Calculator(string("x"), ct_ftl, ct_clt, *ct_s); calc->save(s2); s2.flush(); Calculator calc2(string("x"), ct_ftl, ct_clt, s2); double result = calc2.calculate(0.0f); CAssert::assertEquals(1.0f, result); } void ct_testSaveLoad2() { stringstream s2; *ct_s << "12 2 3 4 * 10 5 / + * +"; calc = new Calculator(string("x"), ct_ftl, ct_clt, *ct_s); calc->save(s2); s2.flush(); Calculator calc2(string("x"), ct_ftl, ct_clt, s2); double result = calc2.calculate(0.0f); CAssert::assertEquals(40.0f, result); } void ct_testASTSin() { *ct_s << "sin(x)"; ct_parser->begin(); ct_ast = ct_parser->expr(); calc = new Calculator(string("x"), ct_ftl, ct_clt, ct_ast); double result = calc->calculate(0.0f); CAssert::assertEquals(0.0f, result); } /*void ct_test() { *ct_s << "y"; ct_parser->begin(); ct_ast = ct_parser->expr(); calc = new Calculator(string("x"), ct_ftl, ct_clt, ct_ast); double result = calc->calculate(0.0f); CAssert::assertEquals(0.0f, result); } */ std::auto_ptr<cunit::TestCase> calculatorTestCase() { auto_ptr<TestCase> tc = auto_ptr<TestCase>( new TestCase(string("CalculatorTestCase"), ct_setup, ct_cleanup)); tc->addTest(string("ct_testRPNPlus"), ct_testRPNPlus); tc->addTest(string("ct_testASTPlus"), ct_testASTPlus); tc->addTest(string("ct_testRPNMinus"), ct_testRPNMinus); tc->addTest(string("ct_testASTMinus"), ct_testASTMinus); tc->addTest(string("ct_testRPNUnaryNeg"), ct_testRPNUnaryNeg); tc->addTest(string("ct_testASTUnaryNeg"), ct_testASTUnaryNeg); tc->addTest(string("ct_testRPNMul"), ct_testRPNMul); tc->addTest(string("ct_testASTMul"), ct_testASTMul); tc->addTest(string("ct_testRPNDiv"), ct_testRPNDiv); tc->addTest(string("ct_testASTDiv"), ct_testASTDiv); tc->addTest(string("ct_testRPNPow"), ct_testRPNPow); tc->addTest(string("ct_testASTPow"), ct_testASTPow); tc->addTest(string("ct_testRPNVariable"), ct_testRPNVariable); tc->addTest(string("ct_testASTVariable"), ct_testASTVariable); tc->addTest(string("ct_testRPNConst"), ct_testRPNConst); tc->addTest(string("ct_testASTConst"), ct_testASTConst); tc->addTest(string("ct_testRPNFunc"), ct_testRPNFunc); tc->addTest(string("ct_testASTFunc"), ct_testASTFunc); tc->addTest(string("ct_testRPNWiki"), ct_testRPNWiki); tc->addTest(string("ct_testASTWiki"), ct_testASTWiki); tc->addTest(string("ct_testSaveLoad1"), ct_testSaveLoad1); tc->addTest(string("ct_testSaveLoad2"), ct_testSaveLoad2); tc->addTest(string("ct_testASTSin"), ct_testASTSin); //tc->addTest(string("ct_test"), ct_test); return tc; } }
28.726027
65
0.641631
marcincinik
4994ec2961840fc471a42418464dd4197e0b43e4
1,242
cpp
C++
aws-cpp-sdk-location/source/model/UpdateRouteCalculatorResult.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-location/source/model/UpdateRouteCalculatorResult.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2021-10-14T16:57:00.000Z
2021-10-18T10:47:24.000Z
aws-cpp-sdk-location/source/model/UpdateRouteCalculatorResult.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/location/model/UpdateRouteCalculatorResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::LocationService::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; UpdateRouteCalculatorResult::UpdateRouteCalculatorResult() { } UpdateRouteCalculatorResult::UpdateRouteCalculatorResult(const Aws::AmazonWebServiceResult<JsonValue>& result) { *this = result; } UpdateRouteCalculatorResult& UpdateRouteCalculatorResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result) { JsonView jsonValue = result.GetPayload().View(); if(jsonValue.ValueExists("CalculatorArn")) { m_calculatorArn = jsonValue.GetString("CalculatorArn"); } if(jsonValue.ValueExists("CalculatorName")) { m_calculatorName = jsonValue.GetString("CalculatorName"); } if(jsonValue.ValueExists("UpdateTime")) { m_updateTime = jsonValue.GetString("UpdateTime"); } return *this; }
23.433962
122
0.761675
perfectrecall
499537ad39bcd5d5ac68d9f657c0261f716b0387
458
cpp
C++
mine/739-daily_temperatures.cpp
Junlin-Yin/myLeetCode
8a33605d3d0de9faa82b5092a8e9f56b342c463f
[ "MIT" ]
null
null
null
mine/739-daily_temperatures.cpp
Junlin-Yin/myLeetCode
8a33605d3d0de9faa82b5092a8e9f56b342c463f
[ "MIT" ]
null
null
null
mine/739-daily_temperatures.cpp
Junlin-Yin/myLeetCode
8a33605d3d0de9faa82b5092a8e9f56b342c463f
[ "MIT" ]
null
null
null
class Solution { public: vector<int> dailyTemperatures(vector<int>& temperatures) { int n = temperatures.size(); stack<int> st; vector<int> ans(n); for(int i = n - 1; i >= 0; --i){ int ti = temperatures[i]; while(!st.empty() && temperatures[st.top()] <= ti) st.pop(); ans[i] = st.empty() ? 0 : st.top() - i; st.push(i); } return ans; } };
30.533333
75
0.456332
Junlin-Yin
499730db0c20040887aa7b39c615fe8f97b4e963
56,271
cc
C++
osrm-ch/src/protobuf/query-graph.pb.cc
dingchunda/osrm-backend
8750749b83bd9193ca3481c630eefda689ecb73c
[ "BSD-2-Clause" ]
null
null
null
osrm-ch/src/protobuf/query-graph.pb.cc
dingchunda/osrm-backend
8750749b83bd9193ca3481c630eefda689ecb73c
[ "BSD-2-Clause" ]
1
2019-11-21T09:59:27.000Z
2019-11-21T09:59:27.000Z
osrm-ch/src/protobuf/query-graph.pb.cc
dingchunda/osrm-backend
8750749b83bd9193ca3481c630eefda689ecb73c
[ "BSD-2-Clause" ]
null
null
null
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: query-graph.proto #define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION #include "query-graph.pb.h" #include <algorithm> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/port.h> #include <google/protobuf/stubs/once.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.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) namespace pbqg { class NodeDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<Node> { } _Node_default_instance_; class EdgeDataDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<EdgeData> { } _EdgeData_default_instance_; class EdgeDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<Edge> { } _Edge_default_instance_; class QueryGraphDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<QueryGraph> { } _QueryGraph_default_instance_; class NodeLevelsDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<NodeLevels> { } _NodeLevels_default_instance_; namespace protobuf_query_2dgraph_2eproto { namespace { ::google::protobuf::Metadata file_level_metadata[5]; } // namespace const ::google::protobuf::uint32 TableStruct::offsets[] = { ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Node, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Node, first_edge_), ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EdgeData, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EdgeData, id_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EdgeData, shortcut_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EdgeData, weight_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EdgeData, forward_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EdgeData, backward_), ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Edge, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Edge, target_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Edge, data_), ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(QueryGraph, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(QueryGraph, v_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(QueryGraph, e_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(QueryGraph, nodes_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(QueryGraph, edges_), ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(NodeLevels, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(NodeLevels, levels_), }; static const ::google::protobuf::internal::MigrationSchema schemas[] = { { 0, -1, sizeof(Node)}, { 5, -1, sizeof(EdgeData)}, { 14, -1, sizeof(Edge)}, { 20, -1, sizeof(QueryGraph)}, { 28, -1, sizeof(NodeLevels)}, }; static ::google::protobuf::Message const * const file_default_instances[] = { reinterpret_cast<const ::google::protobuf::Message*>(&_Node_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&_EdgeData_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&_Edge_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&_QueryGraph_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&_NodeLevels_default_instance_), }; namespace { void protobuf_AssignDescriptors() { AddDescriptors(); ::google::protobuf::MessageFactory* factory = NULL; AssignDescriptors( "query-graph.proto", schemas, file_default_instances, TableStruct::offsets, factory, file_level_metadata, NULL, NULL); } void protobuf_AssignDescriptorsOnce() { static GOOGLE_PROTOBUF_DECLARE_ONCE(once); ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors); } void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD; void protobuf_RegisterTypes(const ::std::string&) { protobuf_AssignDescriptorsOnce(); ::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 5); } } // namespace void TableStruct::Shutdown() { _Node_default_instance_.Shutdown(); delete file_level_metadata[0].reflection; _EdgeData_default_instance_.Shutdown(); delete file_level_metadata[1].reflection; _Edge_default_instance_.Shutdown(); delete file_level_metadata[2].reflection; _QueryGraph_default_instance_.Shutdown(); delete file_level_metadata[3].reflection; _NodeLevels_default_instance_.Shutdown(); delete file_level_metadata[4].reflection; } void TableStruct::InitDefaultsImpl() { GOOGLE_PROTOBUF_VERIFY_VERSION; ::google::protobuf::internal::InitProtobufDefaults(); _Node_default_instance_.DefaultConstruct(); _EdgeData_default_instance_.DefaultConstruct(); _Edge_default_instance_.DefaultConstruct(); _QueryGraph_default_instance_.DefaultConstruct(); _NodeLevels_default_instance_.DefaultConstruct(); _Edge_default_instance_.get_mutable()->data_ = const_cast< ::pbqg::EdgeData*>( ::pbqg::EdgeData::internal_default_instance()); } void InitDefaults() { static GOOGLE_PROTOBUF_DECLARE_ONCE(once); ::google::protobuf::GoogleOnceInit(&once, &TableStruct::InitDefaultsImpl); } void AddDescriptorsImpl() { InitDefaults(); static const char descriptor[] = { "\n\021query-graph.proto\022\004pbqg\"\032\n\004Node\022\022\n\nfir" "st_edge\030\001 \001(\005\"[\n\010EdgeData\022\n\n\002id\030\001 \001(\005\022\020\n" "\010shortcut\030\002 \001(\010\022\016\n\006weight\030\003 \001(\005\022\017\n\007forwa" "rd\030\004 \001(\010\022\020\n\010backward\030\005 \001(\010\"4\n\004Edge\022\016\n\006ta" "rget\030\001 \001(\005\022\034\n\004data\030\002 \001(\0132\016.pbqg.EdgeData" "\"X\n\nQueryGraph\022\t\n\001V\030\001 \001(\005\022\t\n\001E\030\002 \001(\005\022\031\n\005" "nodes\030\003 \003(\0132\n.pbqg.Node\022\031\n\005edges\030\004 \003(\0132\n" ".pbqg.Edge\"\034\n\nNodeLevels\022\016\n\006levels\030\001 \003(\005" "b\006proto3" }; ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( descriptor, 328); ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( "query-graph.proto", &protobuf_RegisterTypes); ::google::protobuf::internal::OnShutdown(&TableStruct::Shutdown); } void AddDescriptors() { static GOOGLE_PROTOBUF_DECLARE_ONCE(once); ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl); } // Force AddDescriptors() to be called at static initialization time. struct StaticDescriptorInitializer { StaticDescriptorInitializer() { AddDescriptors(); } } static_descriptor_initializer; } // namespace protobuf_query_2dgraph_2eproto // =================================================================== #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int Node::kFirstEdgeFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 Node::Node() : ::google::protobuf::Message(), _internal_metadata_(NULL) { if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { protobuf_query_2dgraph_2eproto::InitDefaults(); } SharedCtor(); // @@protoc_insertion_point(constructor:pbqg.Node) } Node::Node(const Node& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _cached_size_(0) { _internal_metadata_.MergeFrom(from._internal_metadata_); first_edge_ = from.first_edge_; // @@protoc_insertion_point(copy_constructor:pbqg.Node) } void Node::SharedCtor() { first_edge_ = 0; _cached_size_ = 0; } Node::~Node() { // @@protoc_insertion_point(destructor:pbqg.Node) SharedDtor(); } void Node::SharedDtor() { } void Node::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* Node::descriptor() { protobuf_query_2dgraph_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_query_2dgraph_2eproto::file_level_metadata[0].descriptor; } const Node& Node::default_instance() { protobuf_query_2dgraph_2eproto::InitDefaults(); return *internal_default_instance(); } Node* Node::New(::google::protobuf::Arena* arena) const { Node* n = new Node; if (arena != NULL) { arena->Own(n); } return n; } void Node::Clear() { // @@protoc_insertion_point(message_clear_start:pbqg.Node) first_edge_ = 0; } bool Node::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:pbqg.Node) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // int32 first_edge = 1; case 1: { if (tag == 8u) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &first_edge_))); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag)); break; } } } success: // @@protoc_insertion_point(parse_success:pbqg.Node) return true; failure: // @@protoc_insertion_point(parse_failure:pbqg.Node) return false; #undef DO_ } void Node::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:pbqg.Node) // int32 first_edge = 1; if (this->first_edge() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->first_edge(), output); } // @@protoc_insertion_point(serialize_end:pbqg.Node) } ::google::protobuf::uint8* Node::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:pbqg.Node) // int32 first_edge = 1; if (this->first_edge() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->first_edge(), target); } // @@protoc_insertion_point(serialize_to_array_end:pbqg.Node) return target; } size_t Node::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:pbqg.Node) size_t total_size = 0; // int32 first_edge = 1; if (this->first_edge() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->first_edge()); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void Node::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:pbqg.Node) GOOGLE_DCHECK_NE(&from, this); const Node* source = ::google::protobuf::internal::DynamicCastToGenerated<const Node>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:pbqg.Node) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:pbqg.Node) MergeFrom(*source); } } void Node::MergeFrom(const Node& from) { // @@protoc_insertion_point(class_specific_merge_from_start:pbqg.Node) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); if (from.first_edge() != 0) { set_first_edge(from.first_edge()); } } void Node::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:pbqg.Node) if (&from == this) return; Clear(); MergeFrom(from); } void Node::CopyFrom(const Node& from) { // @@protoc_insertion_point(class_specific_copy_from_start:pbqg.Node) if (&from == this) return; Clear(); MergeFrom(from); } bool Node::IsInitialized() const { return true; } void Node::Swap(Node* other) { if (other == this) return; InternalSwap(other); } void Node::InternalSwap(Node* other) { std::swap(first_edge_, other->first_edge_); std::swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata Node::GetMetadata() const { protobuf_query_2dgraph_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_query_2dgraph_2eproto::file_level_metadata[0]; } #if PROTOBUF_INLINE_NOT_IN_HEADERS // Node // int32 first_edge = 1; void Node::clear_first_edge() { first_edge_ = 0; } ::google::protobuf::int32 Node::first_edge() const { // @@protoc_insertion_point(field_get:pbqg.Node.first_edge) return first_edge_; } void Node::set_first_edge(::google::protobuf::int32 value) { first_edge_ = value; // @@protoc_insertion_point(field_set:pbqg.Node.first_edge) } #endif // PROTOBUF_INLINE_NOT_IN_HEADERS // =================================================================== #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int EdgeData::kIdFieldNumber; const int EdgeData::kShortcutFieldNumber; const int EdgeData::kWeightFieldNumber; const int EdgeData::kForwardFieldNumber; const int EdgeData::kBackwardFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 EdgeData::EdgeData() : ::google::protobuf::Message(), _internal_metadata_(NULL) { if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { protobuf_query_2dgraph_2eproto::InitDefaults(); } SharedCtor(); // @@protoc_insertion_point(constructor:pbqg.EdgeData) } EdgeData::EdgeData(const EdgeData& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _cached_size_(0) { _internal_metadata_.MergeFrom(from._internal_metadata_); ::memcpy(&id_, &from.id_, reinterpret_cast<char*>(&backward_) - reinterpret_cast<char*>(&id_) + sizeof(backward_)); // @@protoc_insertion_point(copy_constructor:pbqg.EdgeData) } void EdgeData::SharedCtor() { ::memset(&id_, 0, reinterpret_cast<char*>(&backward_) - reinterpret_cast<char*>(&id_) + sizeof(backward_)); _cached_size_ = 0; } EdgeData::~EdgeData() { // @@protoc_insertion_point(destructor:pbqg.EdgeData) SharedDtor(); } void EdgeData::SharedDtor() { } void EdgeData::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* EdgeData::descriptor() { protobuf_query_2dgraph_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_query_2dgraph_2eproto::file_level_metadata[1].descriptor; } const EdgeData& EdgeData::default_instance() { protobuf_query_2dgraph_2eproto::InitDefaults(); return *internal_default_instance(); } EdgeData* EdgeData::New(::google::protobuf::Arena* arena) const { EdgeData* n = new EdgeData; if (arena != NULL) { arena->Own(n); } return n; } void EdgeData::Clear() { // @@protoc_insertion_point(message_clear_start:pbqg.EdgeData) ::memset(&id_, 0, reinterpret_cast<char*>(&backward_) - reinterpret_cast<char*>(&id_) + sizeof(backward_)); } bool EdgeData::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:pbqg.EdgeData) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // int32 id = 1; case 1: { if (tag == 8u) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &id_))); } else { goto handle_unusual; } break; } // bool shortcut = 2; case 2: { if (tag == 16u) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( input, &shortcut_))); } else { goto handle_unusual; } break; } // int32 weight = 3; case 3: { if (tag == 24u) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &weight_))); } else { goto handle_unusual; } break; } // bool forward = 4; case 4: { if (tag == 32u) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( input, &forward_))); } else { goto handle_unusual; } break; } // bool backward = 5; case 5: { if (tag == 40u) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( input, &backward_))); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag)); break; } } } success: // @@protoc_insertion_point(parse_success:pbqg.EdgeData) return true; failure: // @@protoc_insertion_point(parse_failure:pbqg.EdgeData) return false; #undef DO_ } void EdgeData::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:pbqg.EdgeData) // int32 id = 1; if (this->id() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->id(), output); } // bool shortcut = 2; if (this->shortcut() != 0) { ::google::protobuf::internal::WireFormatLite::WriteBool(2, this->shortcut(), output); } // int32 weight = 3; if (this->weight() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt32(3, this->weight(), output); } // bool forward = 4; if (this->forward() != 0) { ::google::protobuf::internal::WireFormatLite::WriteBool(4, this->forward(), output); } // bool backward = 5; if (this->backward() != 0) { ::google::protobuf::internal::WireFormatLite::WriteBool(5, this->backward(), output); } // @@protoc_insertion_point(serialize_end:pbqg.EdgeData) } ::google::protobuf::uint8* EdgeData::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:pbqg.EdgeData) // int32 id = 1; if (this->id() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->id(), target); } // bool shortcut = 2; if (this->shortcut() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(2, this->shortcut(), target); } // int32 weight = 3; if (this->weight() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(3, this->weight(), target); } // bool forward = 4; if (this->forward() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(4, this->forward(), target); } // bool backward = 5; if (this->backward() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(5, this->backward(), target); } // @@protoc_insertion_point(serialize_to_array_end:pbqg.EdgeData) return target; } size_t EdgeData::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:pbqg.EdgeData) size_t total_size = 0; // int32 id = 1; if (this->id() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->id()); } // int32 weight = 3; if (this->weight() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->weight()); } // bool shortcut = 2; if (this->shortcut() != 0) { total_size += 1 + 1; } // bool forward = 4; if (this->forward() != 0) { total_size += 1 + 1; } // bool backward = 5; if (this->backward() != 0) { total_size += 1 + 1; } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void EdgeData::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:pbqg.EdgeData) GOOGLE_DCHECK_NE(&from, this); const EdgeData* source = ::google::protobuf::internal::DynamicCastToGenerated<const EdgeData>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:pbqg.EdgeData) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:pbqg.EdgeData) MergeFrom(*source); } } void EdgeData::MergeFrom(const EdgeData& from) { // @@protoc_insertion_point(class_specific_merge_from_start:pbqg.EdgeData) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); if (from.id() != 0) { set_id(from.id()); } if (from.weight() != 0) { set_weight(from.weight()); } if (from.shortcut() != 0) { set_shortcut(from.shortcut()); } if (from.forward() != 0) { set_forward(from.forward()); } if (from.backward() != 0) { set_backward(from.backward()); } } void EdgeData::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:pbqg.EdgeData) if (&from == this) return; Clear(); MergeFrom(from); } void EdgeData::CopyFrom(const EdgeData& from) { // @@protoc_insertion_point(class_specific_copy_from_start:pbqg.EdgeData) if (&from == this) return; Clear(); MergeFrom(from); } bool EdgeData::IsInitialized() const { return true; } void EdgeData::Swap(EdgeData* other) { if (other == this) return; InternalSwap(other); } void EdgeData::InternalSwap(EdgeData* other) { std::swap(id_, other->id_); std::swap(weight_, other->weight_); std::swap(shortcut_, other->shortcut_); std::swap(forward_, other->forward_); std::swap(backward_, other->backward_); std::swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata EdgeData::GetMetadata() const { protobuf_query_2dgraph_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_query_2dgraph_2eproto::file_level_metadata[1]; } #if PROTOBUF_INLINE_NOT_IN_HEADERS // EdgeData // int32 id = 1; void EdgeData::clear_id() { id_ = 0; } ::google::protobuf::int32 EdgeData::id() const { // @@protoc_insertion_point(field_get:pbqg.EdgeData.id) return id_; } void EdgeData::set_id(::google::protobuf::int32 value) { id_ = value; // @@protoc_insertion_point(field_set:pbqg.EdgeData.id) } // bool shortcut = 2; void EdgeData::clear_shortcut() { shortcut_ = false; } bool EdgeData::shortcut() const { // @@protoc_insertion_point(field_get:pbqg.EdgeData.shortcut) return shortcut_; } void EdgeData::set_shortcut(bool value) { shortcut_ = value; // @@protoc_insertion_point(field_set:pbqg.EdgeData.shortcut) } // int32 weight = 3; void EdgeData::clear_weight() { weight_ = 0; } ::google::protobuf::int32 EdgeData::weight() const { // @@protoc_insertion_point(field_get:pbqg.EdgeData.weight) return weight_; } void EdgeData::set_weight(::google::protobuf::int32 value) { weight_ = value; // @@protoc_insertion_point(field_set:pbqg.EdgeData.weight) } // bool forward = 4; void EdgeData::clear_forward() { forward_ = false; } bool EdgeData::forward() const { // @@protoc_insertion_point(field_get:pbqg.EdgeData.forward) return forward_; } void EdgeData::set_forward(bool value) { forward_ = value; // @@protoc_insertion_point(field_set:pbqg.EdgeData.forward) } // bool backward = 5; void EdgeData::clear_backward() { backward_ = false; } bool EdgeData::backward() const { // @@protoc_insertion_point(field_get:pbqg.EdgeData.backward) return backward_; } void EdgeData::set_backward(bool value) { backward_ = value; // @@protoc_insertion_point(field_set:pbqg.EdgeData.backward) } #endif // PROTOBUF_INLINE_NOT_IN_HEADERS // =================================================================== #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int Edge::kTargetFieldNumber; const int Edge::kDataFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 Edge::Edge() : ::google::protobuf::Message(), _internal_metadata_(NULL) { if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { protobuf_query_2dgraph_2eproto::InitDefaults(); } SharedCtor(); // @@protoc_insertion_point(constructor:pbqg.Edge) } Edge::Edge(const Edge& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _cached_size_(0) { _internal_metadata_.MergeFrom(from._internal_metadata_); if (from.has_data()) { data_ = new ::pbqg::EdgeData(*from.data_); } else { data_ = NULL; } target_ = from.target_; // @@protoc_insertion_point(copy_constructor:pbqg.Edge) } void Edge::SharedCtor() { ::memset(&data_, 0, reinterpret_cast<char*>(&target_) - reinterpret_cast<char*>(&data_) + sizeof(target_)); _cached_size_ = 0; } Edge::~Edge() { // @@protoc_insertion_point(destructor:pbqg.Edge) SharedDtor(); } void Edge::SharedDtor() { if (this != internal_default_instance()) { delete data_; } } void Edge::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* Edge::descriptor() { protobuf_query_2dgraph_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_query_2dgraph_2eproto::file_level_metadata[2].descriptor; } const Edge& Edge::default_instance() { protobuf_query_2dgraph_2eproto::InitDefaults(); return *internal_default_instance(); } Edge* Edge::New(::google::protobuf::Arena* arena) const { Edge* n = new Edge; if (arena != NULL) { arena->Own(n); } return n; } void Edge::Clear() { // @@protoc_insertion_point(message_clear_start:pbqg.Edge) if (GetArenaNoVirtual() == NULL && data_ != NULL) { delete data_; } data_ = NULL; target_ = 0; } bool Edge::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:pbqg.Edge) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // int32 target = 1; case 1: { if (tag == 8u) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &target_))); } else { goto handle_unusual; } break; } // .pbqg.EdgeData data = 2; case 2: { if (tag == 18u) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_data())); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag)); break; } } } success: // @@protoc_insertion_point(parse_success:pbqg.Edge) return true; failure: // @@protoc_insertion_point(parse_failure:pbqg.Edge) return false; #undef DO_ } void Edge::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:pbqg.Edge) // int32 target = 1; if (this->target() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->target(), output); } // .pbqg.EdgeData data = 2; if (this->has_data()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 2, *this->data_, output); } // @@protoc_insertion_point(serialize_end:pbqg.Edge) } ::google::protobuf::uint8* Edge::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:pbqg.Edge) // int32 target = 1; if (this->target() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->target(), target); } // .pbqg.EdgeData data = 2; if (this->has_data()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 2, *this->data_, false, target); } // @@protoc_insertion_point(serialize_to_array_end:pbqg.Edge) return target; } size_t Edge::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:pbqg.Edge) size_t total_size = 0; // .pbqg.EdgeData data = 2; if (this->has_data()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *this->data_); } // int32 target = 1; if (this->target() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->target()); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void Edge::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:pbqg.Edge) GOOGLE_DCHECK_NE(&from, this); const Edge* source = ::google::protobuf::internal::DynamicCastToGenerated<const Edge>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:pbqg.Edge) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:pbqg.Edge) MergeFrom(*source); } } void Edge::MergeFrom(const Edge& from) { // @@protoc_insertion_point(class_specific_merge_from_start:pbqg.Edge) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); if (from.has_data()) { mutable_data()->::pbqg::EdgeData::MergeFrom(from.data()); } if (from.target() != 0) { set_target(from.target()); } } void Edge::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:pbqg.Edge) if (&from == this) return; Clear(); MergeFrom(from); } void Edge::CopyFrom(const Edge& from) { // @@protoc_insertion_point(class_specific_copy_from_start:pbqg.Edge) if (&from == this) return; Clear(); MergeFrom(from); } bool Edge::IsInitialized() const { return true; } void Edge::Swap(Edge* other) { if (other == this) return; InternalSwap(other); } void Edge::InternalSwap(Edge* other) { std::swap(data_, other->data_); std::swap(target_, other->target_); std::swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata Edge::GetMetadata() const { protobuf_query_2dgraph_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_query_2dgraph_2eproto::file_level_metadata[2]; } #if PROTOBUF_INLINE_NOT_IN_HEADERS // Edge // int32 target = 1; void Edge::clear_target() { target_ = 0; } ::google::protobuf::int32 Edge::target() const { // @@protoc_insertion_point(field_get:pbqg.Edge.target) return target_; } void Edge::set_target(::google::protobuf::int32 value) { target_ = value; // @@protoc_insertion_point(field_set:pbqg.Edge.target) } // .pbqg.EdgeData data = 2; bool Edge::has_data() const { return this != internal_default_instance() && data_ != NULL; } void Edge::clear_data() { if (GetArenaNoVirtual() == NULL && data_ != NULL) delete data_; data_ = NULL; } const ::pbqg::EdgeData& Edge::data() const { // @@protoc_insertion_point(field_get:pbqg.Edge.data) return data_ != NULL ? *data_ : *::pbqg::EdgeData::internal_default_instance(); } ::pbqg::EdgeData* Edge::mutable_data() { if (data_ == NULL) { data_ = new ::pbqg::EdgeData; } // @@protoc_insertion_point(field_mutable:pbqg.Edge.data) return data_; } ::pbqg::EdgeData* Edge::release_data() { // @@protoc_insertion_point(field_release:pbqg.Edge.data) ::pbqg::EdgeData* temp = data_; data_ = NULL; return temp; } void Edge::set_allocated_data(::pbqg::EdgeData* data) { delete data_; data_ = data; if (data) { } else { } // @@protoc_insertion_point(field_set_allocated:pbqg.Edge.data) } #endif // PROTOBUF_INLINE_NOT_IN_HEADERS // =================================================================== #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int QueryGraph::kVFieldNumber; const int QueryGraph::kEFieldNumber; const int QueryGraph::kNodesFieldNumber; const int QueryGraph::kEdgesFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 QueryGraph::QueryGraph() : ::google::protobuf::Message(), _internal_metadata_(NULL) { if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { protobuf_query_2dgraph_2eproto::InitDefaults(); } SharedCtor(); // @@protoc_insertion_point(constructor:pbqg.QueryGraph) } QueryGraph::QueryGraph(const QueryGraph& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), nodes_(from.nodes_), edges_(from.edges_), _cached_size_(0) { _internal_metadata_.MergeFrom(from._internal_metadata_); ::memcpy(&v_, &from.v_, reinterpret_cast<char*>(&e_) - reinterpret_cast<char*>(&v_) + sizeof(e_)); // @@protoc_insertion_point(copy_constructor:pbqg.QueryGraph) } void QueryGraph::SharedCtor() { ::memset(&v_, 0, reinterpret_cast<char*>(&e_) - reinterpret_cast<char*>(&v_) + sizeof(e_)); _cached_size_ = 0; } QueryGraph::~QueryGraph() { // @@protoc_insertion_point(destructor:pbqg.QueryGraph) SharedDtor(); } void QueryGraph::SharedDtor() { } void QueryGraph::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* QueryGraph::descriptor() { protobuf_query_2dgraph_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_query_2dgraph_2eproto::file_level_metadata[3].descriptor; } const QueryGraph& QueryGraph::default_instance() { protobuf_query_2dgraph_2eproto::InitDefaults(); return *internal_default_instance(); } QueryGraph* QueryGraph::New(::google::protobuf::Arena* arena) const { QueryGraph* n = new QueryGraph; if (arena != NULL) { arena->Own(n); } return n; } void QueryGraph::Clear() { // @@protoc_insertion_point(message_clear_start:pbqg.QueryGraph) nodes_.Clear(); edges_.Clear(); ::memset(&v_, 0, reinterpret_cast<char*>(&e_) - reinterpret_cast<char*>(&v_) + sizeof(e_)); } bool QueryGraph::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:pbqg.QueryGraph) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // int32 V = 1; case 1: { if (tag == 8u) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &v_))); } else { goto handle_unusual; } break; } // int32 E = 2; case 2: { if (tag == 16u) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &e_))); } else { goto handle_unusual; } break; } // repeated .pbqg.Node nodes = 3; case 3: { if (tag == 26u) { DO_(input->IncrementRecursionDepth()); DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth( input, add_nodes())); } else { goto handle_unusual; } input->UnsafeDecrementRecursionDepth(); break; } // repeated .pbqg.Edge edges = 4; case 4: { if (tag == 34u) { DO_(input->IncrementRecursionDepth()); DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth( input, add_edges())); } else { goto handle_unusual; } input->UnsafeDecrementRecursionDepth(); break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag)); break; } } } success: // @@protoc_insertion_point(parse_success:pbqg.QueryGraph) return true; failure: // @@protoc_insertion_point(parse_failure:pbqg.QueryGraph) return false; #undef DO_ } void QueryGraph::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:pbqg.QueryGraph) // int32 V = 1; if (this->v() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->v(), output); } // int32 E = 2; if (this->e() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->e(), output); } // repeated .pbqg.Node nodes = 3; for (unsigned int i = 0, n = this->nodes_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 3, this->nodes(i), output); } // repeated .pbqg.Edge edges = 4; for (unsigned int i = 0, n = this->edges_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 4, this->edges(i), output); } // @@protoc_insertion_point(serialize_end:pbqg.QueryGraph) } ::google::protobuf::uint8* QueryGraph::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:pbqg.QueryGraph) // int32 V = 1; if (this->v() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->v(), target); } // int32 E = 2; if (this->e() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->e(), target); } // repeated .pbqg.Node nodes = 3; for (unsigned int i = 0, n = this->nodes_size(); i < n; i++) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 3, this->nodes(i), false, target); } // repeated .pbqg.Edge edges = 4; for (unsigned int i = 0, n = this->edges_size(); i < n; i++) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 4, this->edges(i), false, target); } // @@protoc_insertion_point(serialize_to_array_end:pbqg.QueryGraph) return target; } size_t QueryGraph::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:pbqg.QueryGraph) size_t total_size = 0; // repeated .pbqg.Node nodes = 3; { unsigned int count = this->nodes_size(); total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( this->nodes(i)); } } // repeated .pbqg.Edge edges = 4; { unsigned int count = this->edges_size(); total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( this->edges(i)); } } // int32 V = 1; if (this->v() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->v()); } // int32 E = 2; if (this->e() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->e()); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void QueryGraph::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:pbqg.QueryGraph) GOOGLE_DCHECK_NE(&from, this); const QueryGraph* source = ::google::protobuf::internal::DynamicCastToGenerated<const QueryGraph>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:pbqg.QueryGraph) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:pbqg.QueryGraph) MergeFrom(*source); } } void QueryGraph::MergeFrom(const QueryGraph& from) { // @@protoc_insertion_point(class_specific_merge_from_start:pbqg.QueryGraph) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); nodes_.MergeFrom(from.nodes_); edges_.MergeFrom(from.edges_); if (from.v() != 0) { set_v(from.v()); } if (from.e() != 0) { set_e(from.e()); } } void QueryGraph::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:pbqg.QueryGraph) if (&from == this) return; Clear(); MergeFrom(from); } void QueryGraph::CopyFrom(const QueryGraph& from) { // @@protoc_insertion_point(class_specific_copy_from_start:pbqg.QueryGraph) if (&from == this) return; Clear(); MergeFrom(from); } bool QueryGraph::IsInitialized() const { return true; } void QueryGraph::Swap(QueryGraph* other) { if (other == this) return; InternalSwap(other); } void QueryGraph::InternalSwap(QueryGraph* other) { nodes_.UnsafeArenaSwap(&other->nodes_); edges_.UnsafeArenaSwap(&other->edges_); std::swap(v_, other->v_); std::swap(e_, other->e_); std::swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata QueryGraph::GetMetadata() const { protobuf_query_2dgraph_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_query_2dgraph_2eproto::file_level_metadata[3]; } #if PROTOBUF_INLINE_NOT_IN_HEADERS // QueryGraph // int32 V = 1; void QueryGraph::clear_v() { v_ = 0; } ::google::protobuf::int32 QueryGraph::v() const { // @@protoc_insertion_point(field_get:pbqg.QueryGraph.V) return v_; } void QueryGraph::set_v(::google::protobuf::int32 value) { v_ = value; // @@protoc_insertion_point(field_set:pbqg.QueryGraph.V) } // int32 E = 2; void QueryGraph::clear_e() { e_ = 0; } ::google::protobuf::int32 QueryGraph::e() const { // @@protoc_insertion_point(field_get:pbqg.QueryGraph.E) return e_; } void QueryGraph::set_e(::google::protobuf::int32 value) { e_ = value; // @@protoc_insertion_point(field_set:pbqg.QueryGraph.E) } // repeated .pbqg.Node nodes = 3; int QueryGraph::nodes_size() const { return nodes_.size(); } void QueryGraph::clear_nodes() { nodes_.Clear(); } const ::pbqg::Node& QueryGraph::nodes(int index) const { // @@protoc_insertion_point(field_get:pbqg.QueryGraph.nodes) return nodes_.Get(index); } ::pbqg::Node* QueryGraph::mutable_nodes(int index) { // @@protoc_insertion_point(field_mutable:pbqg.QueryGraph.nodes) return nodes_.Mutable(index); } ::pbqg::Node* QueryGraph::add_nodes() { // @@protoc_insertion_point(field_add:pbqg.QueryGraph.nodes) return nodes_.Add(); } ::google::protobuf::RepeatedPtrField< ::pbqg::Node >* QueryGraph::mutable_nodes() { // @@protoc_insertion_point(field_mutable_list:pbqg.QueryGraph.nodes) return &nodes_; } const ::google::protobuf::RepeatedPtrField< ::pbqg::Node >& QueryGraph::nodes() const { // @@protoc_insertion_point(field_list:pbqg.QueryGraph.nodes) return nodes_; } // repeated .pbqg.Edge edges = 4; int QueryGraph::edges_size() const { return edges_.size(); } void QueryGraph::clear_edges() { edges_.Clear(); } const ::pbqg::Edge& QueryGraph::edges(int index) const { // @@protoc_insertion_point(field_get:pbqg.QueryGraph.edges) return edges_.Get(index); } ::pbqg::Edge* QueryGraph::mutable_edges(int index) { // @@protoc_insertion_point(field_mutable:pbqg.QueryGraph.edges) return edges_.Mutable(index); } ::pbqg::Edge* QueryGraph::add_edges() { // @@protoc_insertion_point(field_add:pbqg.QueryGraph.edges) return edges_.Add(); } ::google::protobuf::RepeatedPtrField< ::pbqg::Edge >* QueryGraph::mutable_edges() { // @@protoc_insertion_point(field_mutable_list:pbqg.QueryGraph.edges) return &edges_; } const ::google::protobuf::RepeatedPtrField< ::pbqg::Edge >& QueryGraph::edges() const { // @@protoc_insertion_point(field_list:pbqg.QueryGraph.edges) return edges_; } #endif // PROTOBUF_INLINE_NOT_IN_HEADERS // =================================================================== #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int NodeLevels::kLevelsFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 NodeLevels::NodeLevels() : ::google::protobuf::Message(), _internal_metadata_(NULL) { if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { protobuf_query_2dgraph_2eproto::InitDefaults(); } SharedCtor(); // @@protoc_insertion_point(constructor:pbqg.NodeLevels) } NodeLevels::NodeLevels(const NodeLevels& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), levels_(from.levels_), _cached_size_(0) { _internal_metadata_.MergeFrom(from._internal_metadata_); // @@protoc_insertion_point(copy_constructor:pbqg.NodeLevels) } void NodeLevels::SharedCtor() { _cached_size_ = 0; } NodeLevels::~NodeLevels() { // @@protoc_insertion_point(destructor:pbqg.NodeLevels) SharedDtor(); } void NodeLevels::SharedDtor() { } void NodeLevels::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* NodeLevels::descriptor() { protobuf_query_2dgraph_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_query_2dgraph_2eproto::file_level_metadata[4].descriptor; } const NodeLevels& NodeLevels::default_instance() { protobuf_query_2dgraph_2eproto::InitDefaults(); return *internal_default_instance(); } NodeLevels* NodeLevels::New(::google::protobuf::Arena* arena) const { NodeLevels* n = new NodeLevels; if (arena != NULL) { arena->Own(n); } return n; } void NodeLevels::Clear() { // @@protoc_insertion_point(message_clear_start:pbqg.NodeLevels) levels_.Clear(); } bool NodeLevels::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:pbqg.NodeLevels) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // repeated int32 levels = 1; case 1: { if (tag == 10u) { DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, this->mutable_levels()))); } else if (tag == 8u) { DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( 1, 10u, input, this->mutable_levels()))); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag)); break; } } } success: // @@protoc_insertion_point(parse_success:pbqg.NodeLevels) return true; failure: // @@protoc_insertion_point(parse_failure:pbqg.NodeLevels) return false; #undef DO_ } void NodeLevels::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:pbqg.NodeLevels) // repeated int32 levels = 1; if (this->levels_size() > 0) { ::google::protobuf::internal::WireFormatLite::WriteTag(1, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output); output->WriteVarint32(_levels_cached_byte_size_); } for (int i = 0; i < this->levels_size(); i++) { ::google::protobuf::internal::WireFormatLite::WriteInt32NoTag( this->levels(i), output); } // @@protoc_insertion_point(serialize_end:pbqg.NodeLevels) } ::google::protobuf::uint8* NodeLevels::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:pbqg.NodeLevels) // repeated int32 levels = 1; if (this->levels_size() > 0) { target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray( 1, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, target); target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray( _levels_cached_byte_size_, target); } for (int i = 0; i < this->levels_size(); i++) { target = ::google::protobuf::internal::WireFormatLite:: WriteInt32NoTagToArray(this->levels(i), target); } // @@protoc_insertion_point(serialize_to_array_end:pbqg.NodeLevels) return target; } size_t NodeLevels::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:pbqg.NodeLevels) size_t total_size = 0; // repeated int32 levels = 1; { size_t data_size = ::google::protobuf::internal::WireFormatLite:: Int32Size(this->levels_); if (data_size > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size(data_size); } int cached_size = ::google::protobuf::internal::ToCachedSize(data_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _levels_cached_byte_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); total_size += data_size; } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void NodeLevels::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:pbqg.NodeLevels) GOOGLE_DCHECK_NE(&from, this); const NodeLevels* source = ::google::protobuf::internal::DynamicCastToGenerated<const NodeLevels>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:pbqg.NodeLevels) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:pbqg.NodeLevels) MergeFrom(*source); } } void NodeLevels::MergeFrom(const NodeLevels& from) { // @@protoc_insertion_point(class_specific_merge_from_start:pbqg.NodeLevels) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); levels_.MergeFrom(from.levels_); } void NodeLevels::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:pbqg.NodeLevels) if (&from == this) return; Clear(); MergeFrom(from); } void NodeLevels::CopyFrom(const NodeLevels& from) { // @@protoc_insertion_point(class_specific_copy_from_start:pbqg.NodeLevels) if (&from == this) return; Clear(); MergeFrom(from); } bool NodeLevels::IsInitialized() const { return true; } void NodeLevels::Swap(NodeLevels* other) { if (other == this) return; InternalSwap(other); } void NodeLevels::InternalSwap(NodeLevels* other) { levels_.UnsafeArenaSwap(&other->levels_); std::swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata NodeLevels::GetMetadata() const { protobuf_query_2dgraph_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_query_2dgraph_2eproto::file_level_metadata[4]; } #if PROTOBUF_INLINE_NOT_IN_HEADERS // NodeLevels // repeated int32 levels = 1; int NodeLevels::levels_size() const { return levels_.size(); } void NodeLevels::clear_levels() { levels_.Clear(); } ::google::protobuf::int32 NodeLevels::levels(int index) const { // @@protoc_insertion_point(field_get:pbqg.NodeLevels.levels) return levels_.Get(index); } void NodeLevels::set_levels(int index, ::google::protobuf::int32 value) { levels_.Set(index, value); // @@protoc_insertion_point(field_set:pbqg.NodeLevels.levels) } void NodeLevels::add_levels(::google::protobuf::int32 value) { levels_.Add(value); // @@protoc_insertion_point(field_add:pbqg.NodeLevels.levels) } const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >& NodeLevels::levels() const { // @@protoc_insertion_point(field_list:pbqg.NodeLevels.levels) return levels_; } ::google::protobuf::RepeatedField< ::google::protobuf::int32 >* NodeLevels::mutable_levels() { // @@protoc_insertion_point(field_mutable_list:pbqg.NodeLevels.levels) return &levels_; } #endif // PROTOBUF_INLINE_NOT_IN_HEADERS // @@protoc_insertion_point(namespace_scope) } // namespace pbqg // @@protoc_insertion_point(global_scope)
30.799672
143
0.690071
dingchunda
499b2eee39f3430bb2cf9d07f0dc5e53ccecef79
3,313
hpp
C++
include/womf/AudioStream.hpp
raster77/womf
20d39cd0c989a63fce365f795a609faff672d27d
[ "MIT" ]
null
null
null
include/womf/AudioStream.hpp
raster77/womf
20d39cd0c989a63fce365f795a609faff672d27d
[ "MIT" ]
null
null
null
include/womf/AudioStream.hpp
raster77/womf
20d39cd0c989a63fce365f795a609faff672d27d
[ "MIT" ]
null
null
null
#ifndef WOMF_AUDIOSTREAM_HPP_ #define WOMF_AUDIOSTREAM_HPP_ #include "AudioResource.hpp" #include "AudioFormat.hpp" #include "AudioStreamState.hpp" #include "miniaudio/miniaudio.h" #include <memory> #include <string> namespace womf { class AudioStream : public AudioResource { public: AudioStream(); virtual ~AudioStream(); /** * @brief Load an audio file * * @param fileName file to load * @param stream if true, stream from file else load file entirely * @param pitch enable pitch * @param spatialization enable spatialization * @return true on success */ virtual bool loadFromFile(const std::string& fileName, const bool stream = true) = 0; /** * @brief File name * * @return */ const std::string& getFileName() { return mFile; } /** * @brief Audio format of the file * * @return */ const AudioFormat& getAudioFormat() { return mAudioFormat; } /** * @brief Play the current audio file * */ void play(); /** * @brief Pause the current audio file * */ void pause(); /** * @brief Stop the current audio file * */ void stop(); /** * @brief Seek from current position * * @param ms milliseconds to seek */ void seek(const int ms); /** * @brief Seek to position * * @param posMs position in milliseconds */ void seekTo(const unsigned int posMs); /** * @brief Duration of audio * * @return */ const float getDuration() { return mDuration; } /** * @brief Position in second of playing audio * * @return position */ float getAudioPosition(); /** * @brief State of music * * @return AudioStreamState */ const AudioStreamState getState() { return mState; } /** * @brief Enable or disable sound looping * * @param loop */ void setLooping(const bool loop); /** * @brief Looping enabled or not * * @param loop */ const bool isLooping() { return mLoop; } protected: /** * @brief Internal data for audio callback * */ struct StreamData { ma_engine *enginePtr; AudioStream *streamPtr; StreamData() : enginePtr(nullptr), streamPtr(nullptr) { } }; ma_sound mSound; bool mInitialized; std::string mFile; AudioFormat mAudioFormat; AudioStreamState mState; float mDuration; bool mLoop; StreamData mStreamData; bool load(const std::string& fileName, const bool stream, const bool pitch, const bool spatialization); void uninitialize(); void setAudioInfos(); void setVorbisDuration(); AudioFormat getAudioFormat(const std::string& fileName); static void audioCallback(ma_device* devicePtr, void* outputPtr, const void* inputPtr, ma_uint32 frameCount); }; } /* namespace womf */ #endif /* WOMF_AUDIOSTREAM_HPP_ */
21.374194
115
0.549049
raster77
499bcdd759d1d8a0e1cd10111c6dac8cc00541a0
1,444
cpp
C++
Sima/Kukua/Classes/NightrunnerGame_1_4/NR_Counter.cpp
Megapop/Norad-Eduapp4syria
20b887dd9e1fe55a5b15cd6cd36a85265bfd819e
[ "BSD-2-Clause" ]
null
null
null
Sima/Kukua/Classes/NightrunnerGame_1_4/NR_Counter.cpp
Megapop/Norad-Eduapp4syria
20b887dd9e1fe55a5b15cd6cd36a85265bfd819e
[ "BSD-2-Clause" ]
null
null
null
Sima/Kukua/Classes/NightrunnerGame_1_4/NR_Counter.cpp
Megapop/Norad-Eduapp4syria
20b887dd9e1fe55a5b15cd6cd36a85265bfd819e
[ "BSD-2-Clause" ]
1
2018-09-10T08:29:13.000Z
2018-09-10T08:29:13.000Z
#include "NR_Counter.h" #include "../Utils/StringUtility.h" NR_Counter::NR_Counter(Node& parentNode, string nodeName, EventDispatcher* eventDispatcher) : GameObject(parentNode, nodeName, "NightrunnerGame_1_4/csd/Ball.csb") { _eventDispatcher = eventDispatcher; CCLOG("NR_Counter()"); currentPieces = 0; play("enter"); startCounter(); } NR_Counter::~NR_Counter() { getNode().stopActionByTag(190); } void NR_Counter::startCounter() { CallFunc *closeCallback = CallFunc::create(CC_CALLBACK_0(NR_Counter::addPiece, this)); Action *closeTimeAction = Sequence::create(DelayTime::create(7.5),closeCallback, nullptr); closeTimeAction->setTag(190); getNode().runAction(closeTimeAction); } void NR_Counter::addPiece() { currentPieces++; auto base = getChild("Master_counter"); base->getChildByName( StringUtils::toString(currentPieces) )->setVisible(true); if ( currentPieces == 8) { EventCustom event("TimeFinishedEvent"); _eventDispatcher->dispatchEvent(&event); return; } CallFunc *closeCallback = CallFunc::create(CC_CALLBACK_0(NR_Counter::addPiece, this)); Action *closeTimeAction = Sequence::create(DelayTime::create(7.5),closeCallback, nullptr); closeTimeAction->setTag(190); getNode().runAction(closeTimeAction); }
25.333333
95
0.653047
Megapop
49a41211fe0e36eea80b398b761900a1a155d94b
5,226
hpp
C++
Mesh.hpp
AidenSaltyFish/IN4152_OpenGl_Game
9dbf51f21e1a7c6b3d1e712da97c69cde85808d0
[ "MIT" ]
null
null
null
Mesh.hpp
AidenSaltyFish/IN4152_OpenGl_Game
9dbf51f21e1a7c6b3d1e712da97c69cde85808d0
[ "MIT" ]
null
null
null
Mesh.hpp
AidenSaltyFish/IN4152_OpenGl_Game
9dbf51f21e1a7c6b3d1e712da97c69cde85808d0
[ "MIT" ]
null
null
null
#pragma once #ifndef MESH_H #define MESH_H // #include <glad/glad.h> // holds all OpenGL type declarations #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> // #include "shader_m.h" #include "Shader.hpp" #include "FPSCamera.hpp" #include <string> #include <fstream> #include <sstream> #include <iostream> #include <vector> using namespace std; struct Vertex { // position glm::vec3 pos; // normal glm::vec3 normal; // texCoords glm::vec2 texC; // tangent //glm::vec3 tangent; //// bitangent //glm::vec3 bitangent; Vertex() = default; Vertex(glm::vec3 p, glm::vec3 n) : pos(p), normal(n) {} Vertex(glm::vec3 p, glm::vec3 n, glm::vec2 t) : pos(p), normal(n), texC(t) {} }; struct Material { // Material color lighting glm::vec3 Ka; // Diffuse reflection glm::vec3 Kd; // Mirror reflection glm::vec3 Ks; GLfloat shinness; }; struct Texture { unsigned int id; string type; string path; }; class Mesh { public: /* Mesh Data */ vector<Vertex> vertices; vector<unsigned int> indices; vector<Texture> textures; Material materials; GLuint VAO; unsigned int uniformBlockIndex; /* Functions */ // constructor Mesh(vector<Vertex> vertices, vector<unsigned int> indices, vector<Texture> textures, Material materials) { this->vertices = vertices; this->indices = indices; this->textures = textures; this->materials = materials; // now that we have all the required data, set the vertex buffers and its attribute pointers. setupMesh(); } // render the mesh void renderMesh(Shader shader) { // bind appropriate textures unsigned int diffuseNr = 1; unsigned int specularNr = 1; unsigned int normalNr = 1; unsigned int heightNr = 1; for (unsigned int i = 0; i < textures.size(); i++) { glActiveTexture(GL_TEXTURE0 + i); // active proper texture unit before binding // retrieve texture number (the N in texture_diffuseN) string number; string name = textures[i].type; if (name == "texture_diffuse") number = std::to_string(diffuseNr++); else if (name == "texture_specular") number = std::to_string(specularNr++); // transfer unsigned int to stream else if (name == "texture_normal") number = std::to_string(normalNr++); // transfer unsigned int to stream else if (name == "texture_height") number = std::to_string(heightNr++); // transfer unsigned int to stream // now set the sampler to the correct texture unit glUniform1i(glGetUniformLocation(shader.Program, (name + number).c_str()), i); // and finally bind the texture glBindTexture(GL_TEXTURE_2D, textures[i].id); } glUniform3fv(glGetUniformLocation(shader.Program, "ambientColor"), 1, glm::value_ptr(materials.Ka)); glUniform3fv(glGetUniformLocation(shader.Program, "diffuseColor"), 1, glm::value_ptr(materials.Kd)); glUniform3fv(glGetUniformLocation(shader.Program, "specularColor"), 1, glm::value_ptr(materials.Ks)); glUniform1f(glGetUniformLocation(shader.Program, "shininessValue"), materials.shinness); // draw mesh glBindVertexArray(VAO); glBindBufferRange(GL_UNIFORM_BUFFER, 0, uniformBlockIndex, 0, sizeof(Material)); glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, 0); glBindVertexArray(0); //// always good practice to set everything back to defaults once configured. glActiveTexture(GL_TEXTURE0); } private: /* Render data */ GLuint VBO, EBO; /* Functions */ // initializes all the buffer objects/arrays void setupMesh() { // create buffers/arrays glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glGenBuffers(1, &EBO); glGenBuffers(1, &uniformBlockIndex); glBindVertexArray(VAO); // load data into vertex buffers glBindBuffer(GL_ARRAY_BUFFER, VBO); // A great thing about structs is that their memory layout is sequential for all its items. // The effect is that we can simply pass a pointer to the struct and it translates perfectly to a glm::vec3/2 array which // again translates to 3/2 floats which translates to a byte array. // std::cout << vertices.size() << std::endl; glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(Vertex) + sizeof(materials), &vertices[0], GL_STATIC_DRAW); glBindBuffer(GL_UNIFORM_BUFFER, uniformBlockIndex); glBufferData(GL_UNIFORM_BUFFER, sizeof(materials), (void*)(&materials), GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), &indices[0], GL_STATIC_DRAW); // set the vertex attribute pointers // vertex Positions glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, pos)); // vertex normals glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, normal)); // vertex texture coords glEnableVertexAttribArray(2); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, texC)); } }; #endif
31.672727
124
0.690586
AidenSaltyFish
49a49363a2bf22d2c29e3191b67c1f5baccfdac3
3,010
cpp
C++
src/wolmodel.cpp
dashinfantry/Exawake
01e7f534520431150762b769a7b86c221f364446
[ "WTFPL" ]
null
null
null
src/wolmodel.cpp
dashinfantry/Exawake
01e7f534520431150762b769a7b86c221f364446
[ "WTFPL" ]
null
null
null
src/wolmodel.cpp
dashinfantry/Exawake
01e7f534520431150762b769a7b86c221f364446
[ "WTFPL" ]
1
2020-11-14T07:15:17.000Z
2020-11-14T07:15:17.000Z
#include "wolmodel.h" #include "wol.cpp/wol.cpp" WOLModel::WOLModel(QAbstractListModel *parent) : QAbstractListModel(parent) { _settings = new QSettings("verdanditeam", "exawake"); int size = _settings->beginReadArray("servers"); for (int i = 0; i < size; ++i) { _settings->setArrayIndex(i); Server server; server.name = _settings->value("name").toString(); server.mac = _settings->value("mac").toString(); server.broadcast = _settings->value("broadcast").toString(); server.port = _settings->value("port").toUInt(); _servers.append(server); } _settings->endArray(); } int WOLModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent) return _servers.length(); } QVariant WOLModel::data(const QModelIndex &index, int role) const { if (index.row() < 0 || index.row() >= rowCount()) return QVariant(); auto server = _servers[index.row()]; switch (role) { case Roles::NameRole: return server.name; case Roles::MacRole: return server.mac; case Roles::BroadcastRole: return server.broadcast; case Roles::PortRole: return server.port; default: return QVariant(); } } QHash<int, QByteArray> WOLModel::roleNames() const { QHash<int, QByteArray> roles; roles[NameRole] = "name"; roles[MacRole] = "mac"; roles[BroadcastRole] = "broadcast"; roles[PortRole] = "port"; return roles; } void WOLModel::addServer(QString name, QString mac, QString broadcast, uint port) { beginInsertRows(QModelIndex(), rowCount(), rowCount()); Server server; server.name = name; server.mac = mac; server.broadcast = broadcast; server.port = port; _servers.append(server); endInsertRows(); saveServers(); } void WOLModel::editServer(int index, QString name, QString mac, QString broadcast, uint port) { if (index < 0 || index >= rowCount()) return; auto &server = _servers[index]; server.name = name; server.mac = mac; server.broadcast = broadcast; server.port = port; saveServers(); } void WOLModel::wakeUpServer(int index) { if (index < 0 || index >= rowCount()) return; auto server = _servers[index]; send_wol(server.mac.toStdString(), server.port, inet_addr(server.broadcast.toUtf8())); } void WOLModel::deleteServer(int index) { if (index < 0 || index >= rowCount()) return; beginRemoveRows(QModelIndex(), index, index); _servers.remove(index); saveServers(); endRemoveRows(); } void WOLModel::saveServers() { _settings->beginWriteArray("servers", _servers.size()); int index = 0; for(const Server &server: _servers) { _settings->setArrayIndex(index); _settings->setValue("name", server.name); _settings->setValue("mac", server.mac); _settings->setValue("broadcast", server.broadcast); _settings->setValue("port", server.port); index++; } _settings->endArray(); }
25.948276
93
0.642193
dashinfantry
49a6918fd2ba98ae457dafc51b6ba843be5a3616
753
cpp
C++
C++/Functions/functions.cpp
IsaacAsante/hackerrank
76c430b341ce1e2ab427eda57508eb309d3b215b
[ "MIT" ]
108
2021-03-29T05:04:16.000Z
2022-03-19T15:11:52.000Z
C++/Functions/functions.cpp
IsaacAsante/hackerrank
76c430b341ce1e2ab427eda57508eb309d3b215b
[ "MIT" ]
null
null
null
C++/Functions/functions.cpp
IsaacAsante/hackerrank
76c430b341ce1e2ab427eda57508eb309d3b215b
[ "MIT" ]
32
2021-03-30T03:56:54.000Z
2022-03-27T14:41:32.000Z
/* Author: Isaac Asante * HackerRank URL for this exercise: https://www.hackerrank.com/challenges/c-tutorial-functions/problem * Original video explanation: https://www.youtube.com/watch?v=lkKSlGJ-2ek * Last verified on: April 17, 2021 */ /* IMPORTANT: * This is the full code for the solution. * Some headers were added/modified. */ #include <iostream> #include <algorithm> using namespace std; /* Add `int max_of_four(int a, int b, int c, int d)` here. */ int max_of_four(int a, int b, int c, int d) { int array[] = { a, b, c, d }; sort(array, array + 4); return array[3]; } int main() { int a, b, c, d; scanf("%d %d %d %d", &a, &b, &c, &d); int ans = max_of_four(a, b, c, d); printf("%d", ans); return 0; }
23.53125
103
0.625498
IsaacAsante
49a8aa370b54bb1b81e8a9bea65e585030fe8aa2
1,552
cpp
C++
src/SceneLoader.cpp
inugami-dev64/deng
96e5bc4c9c9a91aa46cb7c71927853b0a764f7d9
[ "Apache-2.0" ]
null
null
null
src/SceneLoader.cpp
inugami-dev64/deng
96e5bc4c9c9a91aa46cb7c71927853b0a764f7d9
[ "Apache-2.0" ]
null
null
null
src/SceneLoader.cpp
inugami-dev64/deng
96e5bc4c9c9a91aa46cb7c71927853b0a764f7d9
[ "Apache-2.0" ]
null
null
null
// DENG: dynamic engine - small but powerful 3D game engine // licence: Apache, see LICENCE file // file: SceneLoader.cpp - Scene loader class implementation // author: Karl-Mihkel Ott #define SCENE_LOADER_CPP #include <SceneLoader.h> namespace DENG { uint32_t SceneLoader::m_scene_index = 0; SceneLoader::SceneLoader(Renderer &_rend, Libdas::DasParser &_parser, const Libdas::DasScene &_scene, const std::vector<uint32_t> &_main_buffer_offsets, uint32_t _camera_offset, std::vector<Animation> &_animations) { m_root_node_loaders.reserve(_scene.node_count); for (uint32_t i = 0; i < _scene.node_count; i++) { const Libdas::DasNode& node = _parser.AccessNode(_scene.nodes[i]); m_root_node_loaders.emplace_back(_rend, node, _parser, _main_buffer_offsets, _camera_offset, _animations, Libdas::Matrix4<float>()); } // give scene a name if possible if(_scene.name != "") m_scene_name = _scene.name; else m_scene_name += std::to_string(m_scene_index++); } SceneLoader::SceneLoader(const SceneLoader& _sl) noexcept : m_root_node_loaders(_sl.m_root_node_loaders), m_scene_name(_sl.m_scene_name) {} SceneLoader::SceneLoader(SceneLoader&& _sl) noexcept : m_root_node_loaders(std::move(_sl.m_root_node_loaders)), m_scene_name(std::move(_sl.m_scene_name)) {} void SceneLoader::Update() { for (auto it = m_root_node_loaders.begin(); it != m_root_node_loaders.end(); it++) it->Update(); } }
36.952381
220
0.686211
inugami-dev64
49a99acb92bd4d331e98346ef83141befe9ad3d7
2,707
cpp
C++
media_server.cpp
runner365/cpp_media_server
045e962e5c7f01d5252be415f2c2a9f183f5c409
[ "MIT" ]
116
2021-09-07T12:16:59.000Z
2022-03-28T12:44:47.000Z
media_server.cpp
runner365/cpp_media_server
045e962e5c7f01d5252be415f2c2a9f183f5c409
[ "MIT" ]
4
2022-03-01T18:54:50.000Z
2022-03-28T14:22:43.000Z
media_server.cpp
runner365/cpp_media_server
045e962e5c7f01d5252be415f2c2a9f183f5c409
[ "MIT" ]
22
2021-09-07T12:53:40.000Z
2022-03-27T11:30:17.000Z
#include "rtmp_server.hpp" #include "ws_server.hpp" #include "httpflv_server.hpp" #include "net/webrtc/webrtc_pub.hpp" #include "net/webrtc/rtc_dtls.hpp" #include "net/webrtc/srtp_session.hpp" #include "net/hls/hls_writer.hpp" #include "utils/byte_crypto.hpp" #include "utils/av/media_stream_manager.hpp" #include "logger.hpp" #include <stdint.h> #include <stddef.h> websocket_server* wss_p = nullptr; websocket_server* ws_p = nullptr; const std::string ssl_pem_file = "../certs/server.key"; const std::string cert_file = "../certs/server.crt"; boost::asio::io_context io_context; boost::asio::io_context hls_io_context; void create_wss_server(boost::asio::io_context& io_context, uint16_t ws_port) { log_infof("websocket https server is starting, port:%d", ws_port); wss_p = new websocket_server(io_context, ws_port, WEBSOCKET_IMPLEMENT_PROTOO_TYPE, cert_file, ssl_pem_file); } void create_ws_server(boost::asio::io_context& io_context, uint16_t ws_port) { ws_p = new websocket_server(io_context, ws_port, WEBSOCKET_IMPLEMENT_PROTOO_TYPE); log_infof("websocket http server is starting, port:%d", ws_port); } boost::asio::io_context& get_global_io_context() { return io_context; } int main(int argn, char** argv) { const uint16_t rtmp_def_port = 1935; const uint16_t ws_def_port = 1900; const uint16_t ws_webrtc_port = 9110; const uint16_t httpflv_port = 8080; const uint16_t webrtc_media_port = 7000; const std::string host_ip = "192.168.0.104"; hls_writer* hls_output = nullptr; std::string hls_path = "hls"; const uint16_t hls_port = 8060; boost::asio::io_service::work work(io_context); Logger::get_instance()->set_filename("server.log"); try { byte_crypto::init(); rtc_dtls::dtls_init(ssl_pem_file, cert_file); srtp_session::init(); init_single_udp_server(io_context, host_ip, webrtc_media_port); init_webrtc_stream_manager_callback(); rtmp_server server(io_context, rtmp_def_port); websocket_server ws(io_context, ws_def_port, WEBSOCKET_IMPLEMENT_FLV_TYPE); httpflv_server httpflv_serv(io_context, httpflv_port); hls_output = new hls_writer(hls_io_context, hls_port, hls_path, true);//enable hls media_stream_manager::set_hls_writer(hls_output); hls_output->run(); create_ws_server(io_context, ws_webrtc_port); log_infof("rtmp server start:%d", rtmp_def_port); log_infof("websocket server start:%d", ws_def_port); io_context.run(); } catch(const std::exception& e) { std::cerr << e.what() << '\n'; } if (hls_output) { delete hls_output; } return 0; }
32.22619
112
0.711119
runner365
49af3882f87ef261b231d4224e98968a56b62e8e
17,605
cpp
C++
Extern/mssdk_dx7/samples/Multimedia/DInput/src/Tutorials/DIEx5/diex5.cpp
Ybalrid/orbiter
7bed82f845ea8347f238011367e07007b0a24099
[ "MIT" ]
1,040
2021-07-27T12:12:06.000Z
2021-08-02T14:24:49.000Z
Extern/mssdk_dx7/samples/Multimedia/DInput/src/Tutorials/DIEx5/diex5.cpp
Ybalrid/orbiter
7bed82f845ea8347f238011367e07007b0a24099
[ "MIT" ]
20
2021-07-27T12:25:22.000Z
2021-08-02T12:22:19.000Z
Extern/mssdk_dx7/samples/Multimedia/DInput/src/Tutorials/DIEx5/diex5.cpp
Ybalrid/orbiter
7bed82f845ea8347f238011367e07007b0a24099
[ "MIT" ]
71
2021-07-27T14:19:49.000Z
2021-08-02T05:51:52.000Z
//----------------------------------------------------------------------------- // Name: DIEx5.cpp // // Desc: DirectInput simple sample 5 // Demonstrates an application which retrieves buffered HID data // in non-exclusive mode via a blocking loop. // // Copyright (C) 1997-1999 Microsoft Corporation. All Rights Reserved. //----------------------------------------------------------------------------- #include <windows.h> #include <dinput.h> #define DIMAKEUSAGEDWORD(UsagePage, Usage) (DWORD)MAKELONG(Usage, UsagePage) #define DIDOI_GUIDISUSAGE 0x00010000 //----------------------------------------------------------------------------- // Global variables //----------------------------------------------------------------------------- #define DINPUT_BUFFERSIZE 16 // Number of buffer elements LPDIRECTINPUT g_pDI; LPDIRECTINPUTDEVICE g_pDIDevice; HANDLE g_hEvent; CHAR g_strText[1024]; // What we display in client area //----------------------------------------------------------------------------- // Name: struct VCRDATA // Desc: DInput custom data format used to read VCR data. It merely consists of // four buttons. Note: the size of this structure must be a multiple of four // (which it is...otherwise, padding would be necessary.) //----------------------------------------------------------------------------- #define VCROFS_PLAY FIELD_OFFSET( VCRDATA, bPlay ) #define VCROFS_STOP FIELD_OFFSET( VCRDATA, bStop ) #define VCROFS_REWIND FIELD_OFFSET( VCRDATA, bRewind ) #define VCROFS_FFORWARD FIELD_OFFSET( VCRDATA, bFForward ) struct VCRDATA { BYTE bPlay; BYTE bStop; BYTE bRewind; BYTE bFForward; }; //----------------------------------------------------------------------------- // Name: c_rgodfVCR // Desc: Array of DirectInput custom data formats, describing each field in our // VCRDATA structure. Each row in the array consists of four fields: // 1. (const GUID *)DIMAKEUSAGEDWORD(UsagePage, Usage) // The usage page and usage of the control we desire. // The DIDOI_GUIDISUSAGE flag in the dwFlags indicates that // the first field is really a DIMAKEUSAGEDWORD instead // of a pointer to a GUID. // 2. VCROFS_* // The data offset of the item. This information is used // to identify the control after the data format is selected. // 3. DIDFT_BUTTON | DIDFT_ANYINSTANCE // The data format object type filter. Here, we say that // we want a button, but we don't care which button. The // usage page and usage information will choose the right // button for us. // 4. DIDOI_GUIDISUSAGE // The first field of the DIOBJECTDATAFORMAT should be // interpreted as a usage page and usage, rather than a GUID. //----------------------------------------------------------------------------- // These magic numbers come from the USB HID Specification. #define HID_USAGE_PAGE_CONSUMER 0x000C // Consumer controls #define HID_USAGE_CONSUMER_PLAY 0x00B0 // Play #define HID_USAGE_CONSUMER_STOP 0x00B7 // Stop #define HID_USAGE_CONSUMER_REWIND 0x00B4 // Rewind #define HID_USAGE_CONSUMER_FFORWARD 0x00B3 // Fast Forward DIOBJECTDATAFORMAT c_rgodfVCR[4] = { // Play button { (const GUID *)DIMAKEUSAGEDWORD(HID_USAGE_PAGE_CONSUMER, HID_USAGE_CONSUMER_PLAY), VCROFS_PLAY, DIDFT_BUTTON | DIDFT_ANYINSTANCE, DIDOI_GUIDISUSAGE, }, // Stop button { (const GUID *)DIMAKEUSAGEDWORD(HID_USAGE_PAGE_CONSUMER, HID_USAGE_CONSUMER_STOP), VCROFS_STOP, DIDFT_BUTTON | DIDFT_ANYINSTANCE, DIDOI_GUIDISUSAGE, }, // Rewind button { (const GUID *)DIMAKEUSAGEDWORD(HID_USAGE_PAGE_CONSUMER, HID_USAGE_CONSUMER_REWIND), VCROFS_REWIND, DIDFT_BUTTON | DIDFT_ANYINSTANCE, DIDOI_GUIDISUSAGE, }, // Fast Forward button { (const GUID *)DIMAKEUSAGEDWORD(HID_USAGE_PAGE_CONSUMER, HID_USAGE_CONSUMER_FFORWARD), VCROFS_FFORWARD, DIDFT_BUTTON | DIDFT_ANYINSTANCE, DIDOI_GUIDISUSAGE, }, }; //----------------------------------------------------------------------------- // Name: c_dfVCR // Desc: DirectInput custom data format which ties all this information // together into a DirectInput data format. //----------------------------------------------------------------------------- DIDATAFORMAT c_dfVCR = { sizeof(DIDATAFORMAT), // dwSize sizeof(DIOBJECTDATAFORMAT), // dwObjSize 0, // No special flags sizeof(VCRDATA), // Size of data structure 4, // Number of objects in data format c_rgodfVCR, // The objects themselves }; //----------------------------------------------------------------------------- // Name: DisplayError() // Desc: Displays an error in a message box //----------------------------------------------------------------------------- VOID DisplayError( HRESULT hr, CHAR* strMessage ) { MessageBox( NULL, strMessage, "DirectInput Sample", MB_OK ); } //----------------------------------------------------------------------------- // Name: DITryCreatedDevice() // Desc: Check if a created device meets our needs (we are looking for a VCR // device.) //----------------------------------------------------------------------------- BOOL DITryCreatedDevice( LPDIRECTINPUTDEVICE pDIDevice, HWND hWnd ) { HRESULT hr; DIDEVCAPS caps; // Select our data format to see if this device supports the things we // request. A data format specifies which controls on a device we are // interested in, and how they should be reported. In this case, the // c_dfVCR data format specifies what we are looking for. if( FAILED( hr = pDIDevice->SetDataFormat( &c_dfVCR ) ) ) return FALSE; // Query the device capabilities to see if it requires polling. // This appliction isn't written to support polling. So, if the // device require it, then skip polling. // // Note that we set the caps.dwSize to sizeof(DIDEVCAPS_DX3) // because we don't particularly care about force feedback. // // Note that we check the DIDC_POLLEDDATAFORMAT flag instead of // the DIDC_POLLEDDEVICE flag. We don't care whether the device // requires polling, we only care if the VCR controls require // polling. caps.dwSize = sizeof(DIDEVCAPS_DX3); if( FAILED( hr = pDIDevice->GetCapabilities( &caps ) ) ) return FALSE; if( caps.dwFlags & DIDC_POLLEDDATAFORMAT ) return FALSE; // Set the cooperative level to let DirectInput know how // this device should interact with the system and with other // DirectInput applications. if( FAILED( hr = pDIDevice->SetCooperativeLevel( hWnd, DISCL_BACKGROUND | DISCL_EXCLUSIVE ) ) ) return FALSE; // DirectInput uses unbuffered I/O (buffer size = 0) by default. // If you want to read buffered data, you need to set a nonzero // buffer size. DIPROPDWORD dipdw = { { sizeof(DIPROPDWORD), // diph.dwSize sizeof(DIPROPHEADER), // diph.dwHeaderSize 0, // diph.dwObj DIPH_DEVICE, // diph.dwHow }, DINPUT_BUFFERSIZE, // dwData }; if( FAILED( hr = pDIDevice->SetProperty( DIPROP_BUFFERSIZE, &dipdw.diph ) ) ) return FALSE; // We are not a game, we are just a little VCR app. So // instead of going into a polling loop on the device, // use event notifications so we don't use any CPU until // the user actually presses a button. pDIDevice->SetEventNotification( g_hEvent); // The device met all the criteria. Return TRUE. return TRUE; } //----------------------------------------------------------------------------- // Name: EnumDevicesCallback() // Desc: Callback function called by EnumDevices(). Checks each device to see // if it meets our criteria (we are looking for a VCR device.) //----------------------------------------------------------------------------- BOOL CALLBACK EnumDevicesCallback( LPCDIDEVICEINSTANCE pInst, LPVOID pvRef ) { LPDIRECTINPUTDEVICE pDIDevice; HRESULT hr; HWND hWnd = (HWND)pvRef; // Our refdata is the coop window // Create the device we enumerated so we can snoop at it to decide // if we like it or not. hr = g_pDI->CreateDevice( pInst->guidInstance, &pDIDevice, NULL ); if( SUCCEEDED(hr) ) { // Use our helper function to see if this is a device // that is useful to us. if( DITryCreatedDevice( pDIDevice, hWnd ) ) { // Okay, we found a VCR control. Save the device pointer and bump // its refcount so it won't go away -- see below for the Release() // that this AddRef() counteracts. We've found a device so we can // stop enumerating. (Alternatively, we could keep enumerating and // put all accepted devices in a listbox.) g_pDIDevice = pDIDevice; return DIENUM_STOP; } // We didn't like the device, so destroy it pDIDevice->Release(); } return DIENUM_CONTINUE; } //----------------------------------------------------------------------------- // Name: CreateDInput() // Desc: Initialize the DirectInput globals //----------------------------------------------------------------------------- HRESULT CreateDInput( HWND hWnd ) { HINSTANCE hInst = (HINSTANCE)GetWindowLong( hWnd, GWL_HINSTANCE ); HRESULT hr; // We use event notifications, so we'll need an event. if( NULL == ( g_hEvent = CreateEvent( NULL, FALSE, FALSE, NULL ) ) ) { DisplayError( 0, "CreateEvent() failed" ); return E_FAIL; } // Register with the DirectInput subsystem and get a pointer to a // IDirectInput interface we can use. if( FAILED( hr = DirectInputCreate( hInst, DIRECTINPUT_VERSION, &g_pDI, NULL ) ) ) { DisplayError( hr, "DirectInputCreate() failed"); return hr; } // Enumerate all the devices in the system looking for one that we // like. if( FAILED( hr = g_pDI->EnumDevices( 0, EnumDevicesCallback, hWnd, DIEDFL_ATTACHEDONLY ) ) ) { DisplayError( hr, "EnumDevices() failed"); return hr; } // Complain if we couldn't find a VCR control. if( NULL == g_pDIDevice ) { DisplayError( 0, "Couldn't find a VCR control" ); return E_FAIL; } return S_OK; } //----------------------------------------------------------------------------- // Name: DestroyDInput() // Desc: Terminate our usage of DirectInput //----------------------------------------------------------------------------- VOID DestroyDInput() { // Destroy any lingering IDirectInputDevice object. if( g_pDIDevice ) { // Unacquire the device g_pDIDevice->Unacquire(); g_pDIDevice->Release(); g_pDIDevice = NULL; } // Destroy any lingering IDirectInput object. if( g_pDI ) { g_pDI->Release(); g_pDI = NULL; } // Destroy the event we were using. if( g_hEvent ) { CloseHandle( g_hEvent ); g_hEvent = NULL; } } //----------------------------------------------------------------------------- // Name: ReadVCRData() // Desc: Read and display status of the VCR buttons //----------------------------------------------------------------------------- VOID ReadVCRData( HWND hWnd ) { DIDEVICEOBJECTDATA rgod[DINPUT_BUFFERSIZE]; // Receives buffered data DWORD cod; HRESULT hr; cod = DINPUT_BUFFERSIZE; if( FAILED( hr = g_pDIDevice->GetDeviceData( sizeof(DIDEVICEOBJECTDATA), rgod, &cod, 0 ) ) ) { // We got an error or we got DI_BUFFEROVERFLOW. Either way, it means // that continuous contact with the device has been lost, either due // to an external interruption, or because the buffer overflowed and // some events were lost. // // Consequently, if a button was pressed at the time the buffer // overflowed or the connection was broken, the corresponding "up" // message might have been lost. // // But since our simple sample doesn't actually have any state // associated with button up or down events, there is no state to // reset. (In a real app, ignoring the buffer overflow would result in // the app thinking a key was held down.) // // It would be more clever to call GetDeviceState() and compare the // current state against the state we think the device is in, and // process all the states that are currently different from our // private state. if( hr == DIERR_INPUTLOST ) { hr = g_pDIDevice->Acquire(); if( SUCCEEDED(hr) ) ReadVCRData( hWnd ); } } // In order for it to be worth our while to parse the buffer elements, the // GetDeviceData() call must have succeeded, and we must have received some // data at all. if( SUCCEEDED(hr) && cod > 0 ) { CHAR strBuf[1024]; // Process each of the buffer elements for( DWORD iod = 0; iod < cod; iod++ ) { CHAR* strObj = NULL; switch( rgod[iod].dwOfs ) { case VCROFS_PLAY: strObj = "Play"; break; case VCROFS_STOP: strObj = "Stop"; break; case VCROFS_REWIND: strObj = "FF"; break; case VCROFS_FFORWARD: strObj = "Rew"; break; } if( strObj ) wsprintf( strBuf, "%s was %s", strObj, (rgod[iod].dwData & 0x80) ? "pressed" : "released" ); } // Trigger a repaint if the status string changed. if( lstrcmp( g_strText, strBuf ) ) { lstrcpy( g_strText, strBuf ); InvalidateRect( hWnd, NULL, TRUE ); } } } //----------------------------------------------------------------------------- // Name: WndProc() // Desc: Application's message handler //----------------------------------------------------------------------------- LRESULT CALLBACK WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) { switch( msg ) { case WM_PAINT: { PAINTSTRUCT ps; HDC hDC = BeginPaint( hWnd, &ps ); if( hDC ) { ExtTextOut( hDC, 0, 0, ETO_OPAQUE, &ps.rcPaint, g_strText, lstrlen(g_strText), NULL ); EndPaint( hWnd, &ps ); } } return 0; case WM_DESTROY: PostQuitMessage(0); break; } return DefWindowProc( hWnd, msg, wParam, lParam ); } //----------------------------------------------------------------------------- // Name: WinMain() // Desc: Application entry point. //----------------------------------------------------------------------------- int PASCAL WinMain( HINSTANCE hInst, HINSTANCE, LPSTR, int nCmdShow ) { // Set up the window class WNDCLASS wc = { CS_HREDRAW | CS_VREDRAW, WndProc, 0, 0, hInst, LoadIcon( hInst, MAKEINTRESOURCE(IDI_APPLICATION)), LoadCursor(NULL, IDC_ARROW), NULL, NULL, TEXT("DI Window") }; if( !RegisterClass( &wc ) ) return FALSE; // Create the main window HWND hWnd = CreateWindow( "DI Window", "DIEx5 - Accessing a HID", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 300, 100, NULL, NULL, hInst, 0 ); if( FAILED( CreateDInput( hWnd ) ) ) { DestroyWindow( hWnd ); return FALSE; } ShowWindow( hWnd, nCmdShow ); // Everything is all set up. Acquire the device and have at it. if( FAILED( g_pDIDevice->Acquire() ) ) { // Unable to obtain access to the device. Some other // application probably has it in exclusive mode. DisplayError( E_FAIL, "Cannot acquire device" ); DestroyDInput(); return FALSE; } // Standard game loop. while( TRUE ) { MSG msg; if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) ) { // If it's a quit message, then we're done. if( msg.message == WM_QUIT ) break; // Otherwise translate and dispatch it TranslateMessage( &msg ); DispatchMessage( &msg ); } // Wait for a message or for our event. DWORD dwRc = MsgWaitForMultipleObjects( 1, &g_hEvent, FALSE, INFINITE, QS_ALLINPUT ); // dwRc is WAIT_OBJECT_0 if we have new input. if( dwRc == WAIT_OBJECT_0 ) ReadVCRData( hWnd ); } DestroyDInput(); return TRUE; }
33.092105
79
0.526214
Ybalrid
49b55d07e5e6e16defe7830090750b8ea5d30a75
6,541
cpp
C++
previewselectdialog.cpp
silverqx/qMedia
33447c3dba32c430f4afac797ee6438b60809dda
[ "MIT" ]
null
null
null
previewselectdialog.cpp
silverqx/qMedia
33447c3dba32c430f4afac797ee6438b60809dda
[ "MIT" ]
null
null
null
previewselectdialog.cpp
silverqx/qMedia
33447c3dba32c430f4afac797ee6438b60809dda
[ "MIT" ]
null
null
null
#include "previewselectdialog.h" #include "ui_previewselectdialog.h" #include <QDir> #include <QMessageBox> #include <QPushButton> #include <QScrollBar> #include <QShowEvent> #include <QStandardItemModel> #include <QtSql/QSqlRecord> #include "common.h" #include "previewlistdelegate.h" // TODO get rid of this include, move Column enum to separate file silverqx #include "torrentsqltablemodel.h" #include "utils/fs.h" #include "utils/misc.h" PreviewSelectDialog::PreviewSelectDialog( QWidget *const parent, const QSqlRecord &torrent, const QSharedPointer<const QVector<QSqlRecord>> &torrentFiles ) : QDialog(parent) , m_torrent(torrent) , m_torrentFiles(torrentFiles) , m_ui(std::make_unique<Ui::PreviewSelectDialog>()) { m_ui->setupUi(this); m_ui->infoLabel->setText( QStringLiteral("The following files from torrent <strong>%1</strong> " "support previewing, please select one of them:") .arg(m_torrent.value("name").toString())); m_ui->buttonBox->button(QDialogButtonBox::Ok)->setText(QStringLiteral("&Preview")); // Events connect(m_ui->buttonBox, &QDialogButtonBox::accepted, this, &PreviewSelectDialog::previewButtonClicked); connect(m_ui->previewList, &QAbstractItemView::doubleClicked, this, &PreviewSelectDialog::previewButtonClicked); // Create and apply delegate m_listDelegate = new PreviewListDelegate(this); // NOLINT(cppcoreguidelines-owning-memory) m_ui->previewList->setItemDelegate(m_listDelegate); // Preview list model m_previewListModel = new QStandardItemModel(0, NB_COLUMNS, this); // NOLINT(cppcoreguidelines-owning-memory) m_previewListModel->setHeaderData(TR_NAME, Qt::Horizontal, QStringLiteral("Name")); m_previewListModel->setHeaderData(TR_SIZE, Qt::Horizontal, QStringLiteral("Size")); m_previewListModel->setHeaderData(TR_PROGRESS, Qt::Horizontal, QStringLiteral("Progress")); // Preview list m_ui->previewList->setModel(m_previewListModel); m_ui->previewList->hideColumn(TR_FILE_INDEX); m_ui->previewList->setAlternatingRowColors(true); populatePreviewListModel(); // Setup initial sorting m_previewListModel->sort(TR_NAME); m_ui->previewList->header()->setSortIndicator(0, Qt::AscendingOrder); // Header alignment m_ui->previewList->header()->setDefaultAlignment(Qt::AlignCenter); // TODO set height on the base of num rows, set min. and max. height silverqx // Initial focus m_ui->previewList->setFocus(); // Preselect first line m_ui->previewList->selectionModel()->select( m_previewListModel->index(0, TR_NAME), QItemSelectionModel::Select | QItemSelectionModel::Rows); } void PreviewSelectDialog::previewButtonClicked() { // Only one file is allowed to select const auto selectedIndexes = m_ui->previewList->selectionModel()->selectedRows(TR_NAME); if (selectedIndexes.isEmpty()) return; const auto selectedIndex = selectedIndexes.first(); if (!selectedIndex.isValid()) return; // Get file path to preview const auto filePath = getTorrentFileFilePathAbs( m_previewListModel->data(selectedIndex).toString()); if (!QFile::exists(filePath)) { reject(); QMessageBox::critical(this, QStringLiteral("Preview impossible"), QStringLiteral("Sorry, we can't preview this file:<br>" "<strong>%1</strong>") .arg(Utils::Fs::toNativePath(filePath))); return; } emit readyToPreviewFile(filePath); accept(); } void PreviewSelectDialog::showEvent(QShowEvent *const event) { // Event originated from system if (event->spontaneous()) { QDialog::showEvent(event); return; } // Call only once during intial show if (m_showEventInitialized) return; // Move this as top as possible to prevent race condition m_showEventInitialized = true; /* Pixel perfectly sized previewList header. Set Name column width to all remaining area. Has to be called after the show() because the previewList's width is needed. */ auto *const previewListHeader = m_ui->previewList->header(); previewListHeader->resizeSections(QHeaderView::ResizeToContents); // Compute name column width auto nameColWidth = m_ui->previewList->width(); const auto *const vScrollBar = m_ui->previewList->verticalScrollBar(); if (vScrollBar->isVisible()) nameColWidth -= vScrollBar->width(); nameColWidth -= previewListHeader->sectionSize(TR_SIZE) + previewListHeader->sectionSize(TR_PROGRESS) + 2; // Borders previewListHeader->resizeSection(TR_NAME, nameColWidth); m_ui->previewList->header()->setStretchLastSection(true); } void PreviewSelectDialog::populatePreviewListModel() const { for (const auto &torrentFile : *m_torrentFiles) { auto filePath = torrentFile.value("filepath").toString(); // Remove qBittorrent extension if needed if (filePath.endsWith(::QB_EXT)) filePath.chop(4); // Insert a new row to the model const auto rowIndex = m_previewListModel->rowCount(); m_previewListModel->insertRow(rowIndex); // Setup row data m_previewListModel->setData(m_previewListModel->index(rowIndex, TR_NAME), filePath); m_previewListModel->setData(m_previewListModel->index(rowIndex, TR_NAME), getTorrentFileFilePathAbs(filePath), Qt::ToolTipRole); m_previewListModel->setData(m_previewListModel->index(rowIndex, TR_SIZE), torrentFile.value("size").toULongLong()); m_previewListModel->setData(m_previewListModel->index(rowIndex, TR_PROGRESS), torrentFile.value("progress").toUInt()); m_previewListModel->setData(m_previewListModel->index(rowIndex, TR_FILE_INDEX), torrentFile.value("id").toULongLong()); } } QString PreviewSelectDialog::getTorrentFileFilePathAbs(const QString &relativePath) const { const QDir saveDir(m_torrent.value(TorrentSqlTableModel::TR_SAVE_PATH).toString()); return Utils::Fs::expandPathAbs(saveDir.absoluteFilePath(relativePath)); }
38.02907
112
0.669622
silverqx
49b68274c21653bc8b1a8bbec85d53796f0d5628
3,636
cpp
C++
main.cpp
komrad36/SongOfTheFloppies
97075101bd78f8aea033704605fb98ddcec8d467
[ "MIT" ]
null
null
null
main.cpp
komrad36/SongOfTheFloppies
97075101bd78f8aea033704605fb98ddcec8d467
[ "MIT" ]
null
null
null
main.cpp
komrad36/SongOfTheFloppies
97075101bd78f8aea033704605fb98ddcec8d467
[ "MIT" ]
null
null
null
/******************************************************************* * main.cpp * SongOfTheFloppies * Kareem Omar * * 6/18/2015 * This program is entirely my own work. *******************************************************************/ // SongOfTheFloppies parses any MIDI file into an internal structure // and a text-readable log file called midi_log.txt. It then plays the // MIDI simplistically using sine waves, if PLAY_SINE is defined in MIDI.h // and/or plays it on floppy drive stepper motors if PLAY_FLOPPY is defined // in MIDI.h. // mem leak checker #ifdef _DEBUG #ifndef DBG_NEW #define DBG_NEW new ( _NORMAL_BLOCK , __FILE__ , __LINE__ ) #define new DBG_NEW #endif // DBG_NEW #ifndef _CRTDBG_MAP_ALLOC #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #endif // _CRTDBG_MAP_ALLOC #endif // _DEBUG #include <iostream> #include <fstream> #include <string> // will need handlers to gracefully // shut down audio/floppies if user // closes app #ifdef _WIN32 #include <Windows.h> #define ADD_HANDLER ((BOOL)(1)) #else #include <signal.h> #include <unistd.h> #endif #include "MIDI.h" MIDI midi; #ifdef _WIN32 BOOL CtrlHandler(DWORD fdwCtrlType) { midi.isClosing = true; // don't let the system kill the process. // asynchronous handler will exit() // the process when it's ready. Sleep(INFINITE); return true; } #else void CtrlHandler(int s) { // Linux handles things differently. // as long as you've registered the handler, // it won't kill the process midi.isClosing = true; } #endif int main(int argc, char* argv[]) { // for memory leak testing #ifdef _DEBUG _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); #endif midi.isClosing = false; // for graceful cleanup if user terminates process early // examples: stop drives from getting stuck on notes, // stop streams from producing loud pops #ifdef _WIN32 SetConsoleCtrlHandler((PHANDLER_ROUTINE)CtrlHandler, ADD_HANDLER); #else struct sigaction sigIntHandler; sigIntHandler.sa_handler = CtrlHandler; sigemptyset(&sigIntHandler.sa_mask); sigIntHandler.sa_flags = 0; sigaction(SIGINT, &sigIntHandler, NULL); sigaction(SIGTERM, &sigIntHandler, NULL); sigaction(SIGHUP, &sigIntHandler, NULL); #endif if (argc == 1) { std::cout << "No input file specified. Please specify an input file" << std::endl << "or drag-and-drop a MIDI file onto this program." << std::endl << std::endl; return EXIT_FAILURE; } if (argc > 2) { std::cout << "Please specify only a single input MIDI file" << std::endl << "or drag-and-drop one onto this program." << std::endl << std::endl; return EXIT_FAILURE; } midi.fileName = std::string(argv[1]); if (!midi.loadBinaryFile()) { std::cout << "Failed to load MIDI file." << std::endl; return EXIT_FAILURE; } if (midi.isClosing) return EXIT_FAILURE; std::cout << "Parsing MIDI file..." << std::endl; if (!midi.parseMIDIFile()) { if (midi.isClosing) return EXIT_FAILURE; std::cout << "Error parsing MIDI file." << std::endl; midi.stepThroughCompletedMidiStructure(); return EXIT_FAILURE; } std::cout << "MIDI file parsed successfully." << std::endl; midi.rawMIDI.clear(); if (midi.isClosing) return EXIT_FAILURE; std::cout << "Logging parsed MIDI structure to midi_log.txt..." << std::endl; midi.stepThroughCompletedMidiStructure(); std::cout << "Done." << std::endl << std::endl; if (midi.isClosing) return EXIT_FAILURE; std::cout << "Playing parsed MIDI..." << std::endl; #if defined(PLAY_SINE) || defined(PLAY_FLOPPY) midi.playMusic(); #endif std::cout << "Done!" << std::endl; return EXIT_SUCCESS; }
23.61039
83
0.682068
komrad36
49b976bcfdd358fc7a252fd9907180be1a4aebd3
9,058
cpp
C++
testapp/scenes/physics/dominoday.cpp
ColinGilbert/d-collide
8adb354d52e7ee49705ca2853d50a6a879f3cd49
[ "BSD-3-Clause" ]
6
2015-12-08T05:38:03.000Z
2021-04-09T13:45:59.000Z
testapp/scenes/physics/dominoday.cpp
ColinGilbert/d-collide
8adb354d52e7ee49705ca2853d50a6a879f3cd49
[ "BSD-3-Clause" ]
null
null
null
testapp/scenes/physics/dominoday.cpp
ColinGilbert/d-collide
8adb354d52e7ee49705ca2853d50a6a879f3cd49
[ "BSD-3-Clause" ]
null
null
null
/******************************************************************************* * Copyright (C) 2007 by the members of PG 510, University of Dortmund: * * d-collide-devel@lists.sourceforge.net * * * Andreas Beckermann, Christian Bode, Marcel Ens, Sebastian Ens, * * Martin Fassbach, Maximilian Hegele, Daniel Haus, Oliver Horst, * * Gregor Jochmann, Timo Loist, Marcel Nienhaus and Marc Schulz * * * * 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 PG510 nor the names of its contributors may be * * used to endorse or promote products derived from this software without * * specific prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE * *******************************************************************************/ #include "dominoday.h" #include "dcollide-config_testapp.h" #include "myobjectnode.h" #include "debug.h" #include "Ogre.h" #include <world.h> #include <shapes/shapes.h> #include <worldcollisions.h> #include <collisioninfo.h> #include <proxyfactory.h> #include <algorithm> /*! * Construct a new d-collide based scene object. * * The scene itself is not yet created, only the necessary data * structures. Call \ref initializeScene to actually create a scene. * * \param root A pointer to the ogre root object. Ownership is NOT * taken, the pointer will not be deleted by this class. */ DominoDay::DominoDay(Ogre::Root* root) : PhysicsSceneBase(root) { mGround=0; mRamp=0; mPhysicsSimStepsize = 0.04; mLinearDampingFactor = 0.001; mAngularDampingFactor = 0.005; } DominoDay::~DominoDay() { } dcollide::Vector3 DominoDay::initialWorldDimension() const { return dcollide::Vector3(2048.0, 2048.0, 2048.0); } /*! * Setup the actual scene, i.e. add objects to the \ref dcollide::World * object. * * \return TRUE on success, otherwise FALSE. */ bool DominoDay::initializeScene() { dWorldSetGravity(mOdeWorld, 0,0,-10); MyObjectNode* environment = new MyObjectNode(getCollisionWorld(), 0, dcollide::PROXYTYPE_FIXED); //Base Box: large Box with top surface at z=0; mGround = new MyObjectNode( getCollisionWorld(), new dcollide::Box(1200,1200, 50), dcollide::PROXYTYPE_FIXED); mGround->translate(dcollide::Vector3(-500, -600, -50)); environment->addChild(mGround); //Ramp: mRamp = new MyObjectNode( getCollisionWorld(), new dcollide::Box(100, 300, 100), dcollide::PROXYTYPE_FIXED,true, false); //the ramp inclines in y-direction mRamp->translate(dcollide::Vector3(-400, 200, -100)); mRamp->rotate(40, 1, 0,0); environment->addChild(mRamp); //ramp and ground are static environment without phyisics bodies addTopLevelObject(environment); //create and place a ball which should roll the ramp down mBall = new MyObjectNode(getCollisionWorld(), new dcollide::Sphere(25), dcollide::PROXYTYPE_RIGID); mBall->createPhysicsBody(mOdeWorld, 15); mBall->translate(-350, 340, 185); addTopLevelObject(mBall); setupDominoBricks(); return true; } void DominoDay::restart() { mBall->setPosition( -350, 340,185 ); dBodySetForce( mBall->getPhysicsBody(), 0, 0, 0); for(std::list<MyObjectNode*>::iterator i = mBricks.begin(); i != mBricks.end(); ++i ) { removeObject(*i); } mBricks.clear(); setupDominoBricks(); deleteCollisions(); } void DominoDay::setupDominoBricks() { dcollide::Matrix brickOrientation; brickOrientation.loadIdentity(); brickOrientation.translate(-330, 150, 0); //Now positive y points downwards brickOrientation.rotate(180,0,0,1); for( int i = 0; i < 10; i++ ) { addBrick(brickOrientation); brickOrientation.translate(0,50,0); } //left curve for( int i = 0; i < 10; i++ ) { addBrick(brickOrientation); brickOrientation.translate(7,30,0); brickOrientation.rotate((float)180/(float)10,0,0,1); } for( int i = 0; i < 15; i++ ) { addBrick(brickOrientation); brickOrientation.translate(0,50,0); } //right curve for( int i = 0; i < 10; i++ ) { addBrick(brickOrientation); brickOrientation.translate(7,30,0); brickOrientation.rotate(-(float)90/(float)10,0,0,1); } for( int i = 0; i < 5; i++ ) { addBrick(brickOrientation); brickOrientation.translate(0,50,0); } //right curve for( int i = 0; i < 5; i++ ) { addBrick(brickOrientation); brickOrientation.translate(7,30,0); brickOrientation.rotate(-(float)90/(float)5,0,0,1); } for( int i = 0; i < 2; i++ ) { addBrick(brickOrientation); brickOrientation.translate(0,50,0); } //save branch location - so we may start here later again dcollide::Matrix branchpoint; //increase brick count per row for( int i = 1; i < 12; i++ ) { branchpoint = brickOrientation; drawDominoLine(brickOrientation, i); //restore branch location brickOrientation = branchpoint; brickOrientation.translate(-20, 50, 0); } //decrease brick count per row for( int i = 11; i > 4; i-- ) { branchpoint = brickOrientation; drawDominoLine(brickOrientation, i); //restore branch location brickOrientation = branchpoint; brickOrientation.translate( 20, 50, 0); } } void DominoDay::drawDominoLine(dcollide::Matrix orientation, int length) { for( int i = 0; i < length; i++) { addBrick(orientation); orientation.translate(50,0,0); } } /*! * \brief Adds Brick to scene with orientation given by parameter */ void DominoDay::addBrick(dcollide::Matrix orientation) { MyObjectNode* newBrick = new MyObjectNode(getCollisionWorld(), new dcollide::Box(30,5,60), dcollide::PROXYTYPE_RIGID); newBrick->createPhysicsBody(mOdeWorld, 2); //Actually this is rotation + translation - =) newBrick->rotate(orientation); addTopLevelObject(newBrick); //Store all allocated bricks, so we may deallocate them later mBricks.push_back(newBrick); } void DominoDay::startNextSceneFrame() { } std::string DominoDay::getSceneDescription() const { return "Domino - you know it :) \n Lots of rigid interaction"; } /* * vim: et sw=4 ts=4 */
36.37751
104
0.554206
ColinGilbert
49bdfaf4ce6aeddfb53b66b5d100948342f8a966
4,169
hpp
C++
libs/boost_1_72_0/boost/beast/http/detail/basic_parser.hpp
henrywarhurst/matrix
317a2a7c35c1c7e3730986668ad2270dc19809ef
[ "BSD-3-Clause" ]
null
null
null
libs/boost_1_72_0/boost/beast/http/detail/basic_parser.hpp
henrywarhurst/matrix
317a2a7c35c1c7e3730986668ad2270dc19809ef
[ "BSD-3-Clause" ]
null
null
null
libs/boost_1_72_0/boost/beast/http/detail/basic_parser.hpp
henrywarhurst/matrix
317a2a7c35c1c7e3730986668ad2270dc19809ef
[ "BSD-3-Clause" ]
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/boostorg/beast // #ifndef BOOST_BEAST_HTTP_DETAIL_BASIC_PARSER_HPP #define BOOST_BEAST_HTTP_DETAIL_BASIC_PARSER_HPP #include <boost/beast/core/detail/char_buffer.hpp> #include <boost/beast/core/string.hpp> #include <boost/beast/http/detail/rfc7230.hpp> #include <boost/beast/http/error.hpp> #include <boost/config.hpp> #include <boost/version.hpp> #include <cstddef> #include <utility> namespace boost { namespace beast { namespace http { namespace detail { struct basic_parser_base { // limit on the size of the obs-fold buffer // // https://stackoverflow.com/questions/686217/maximum-on-http-header-values // static std::size_t constexpr max_obs_fold = 4096; enum class state { nothing_yet = 0, start_line, fields, body0, body, body_to_eof0, body_to_eof, chunk_header0, chunk_header, chunk_body, complete }; static bool is_digit(char c) { return static_cast<unsigned char>(c - '0') < 10; } static bool is_print(char c) { return static_cast<unsigned char>(c - 32) < 95; } BOOST_BEAST_DECL static char const *trim_front(char const *it, char const *end); BOOST_BEAST_DECL static char const *trim_back(char const *it, char const *first); static string_view make_string(char const *first, char const *last) { return {first, static_cast<std::size_t>(last - first)}; } //-------------------------------------------------------------------------- BOOST_BEAST_DECL static bool is_pathchar(char c); BOOST_BEAST_DECL static bool unhex(unsigned char &d, char c); BOOST_BEAST_DECL static std::pair<char const *, bool> find_fast(char const *buf, char const *buf_end, char const *ranges, size_t ranges_size); BOOST_BEAST_DECL static char const *find_eol(char const *it, char const *last, error_code &ec); BOOST_BEAST_DECL static char const *find_eom(char const *p, char const *last); //-------------------------------------------------------------------------- BOOST_BEAST_DECL static char const *parse_token_to_eol(char const *p, char const *last, char const *&token_last, error_code &ec); BOOST_BEAST_DECL static bool parse_dec(string_view s, std::uint64_t &v); BOOST_BEAST_DECL static bool parse_hex(char const *&it, std::uint64_t &v); BOOST_BEAST_DECL static bool parse_crlf(char const *&it); BOOST_BEAST_DECL static void parse_method(char const *&it, char const *last, string_view &result, error_code &ec); BOOST_BEAST_DECL static void parse_target(char const *&it, char const *last, string_view &result, error_code &ec); BOOST_BEAST_DECL static void parse_version(char const *&it, char const *last, int &result, error_code &ec); BOOST_BEAST_DECL static void parse_status(char const *&it, char const *last, unsigned short &result, error_code &ec); BOOST_BEAST_DECL static void parse_reason(char const *&it, char const *last, string_view &result, error_code &ec); BOOST_BEAST_DECL static void parse_field(char const *&p, char const *last, string_view &name, string_view &value, beast::detail::char_buffer<max_obs_fold> &buf, error_code &ec); BOOST_BEAST_DECL static void parse_chunk_extensions(char const *&it, char const *last, error_code &ec); }; } // namespace detail } // namespace http } // namespace beast } // namespace boost #ifdef BOOST_BEAST_HEADER_ONLY #include <boost/beast/http/detail/basic_parser.ipp> #endif #endif
29.153846
80
0.623891
henrywarhurst
49c632dc15494dfc9454b40661a13e008a5cccc3
2,026
hpp
C++
timer/GUI/GUISelectorList.hpp
MaticVrtacnik/ProceduralnaAnimacija
bc47ccc721d1bedb31ed5949eb740892f094897a
[ "MIT" ]
null
null
null
timer/GUI/GUISelectorList.hpp
MaticVrtacnik/ProceduralnaAnimacija
bc47ccc721d1bedb31ed5949eb740892f094897a
[ "MIT" ]
null
null
null
timer/GUI/GUISelectorList.hpp
MaticVrtacnik/ProceduralnaAnimacija
bc47ccc721d1bedb31ed5949eb740892f094897a
[ "MIT" ]
null
null
null
/* MIT License Copyright (c) 2019 MaticVrtacnik 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. */ #ifndef GUI_SELECTOR_LIST_HPP #define GUI_SELECTOR_LIST_HPP #include "GUIList.hpp" namespace Engine{ namespace GUI{ class GUISelectorList : public GUIList{ private: public: GUISelectorList( const std::string &name, int x, int y, int scaleX, int scaleY, int border = 0, const std::vector<std::string> &values = {} ) : GUIList(name, x, y, scaleX, scaleY, border, values) { m_visible = false; m_color = glm::vec4(-1); } ~GUISelectorList(){ } void afterDraw() override{ m_visible = m_active; /*if (!m_active && m_visible){ //m_visible = false; }*/ } GUIButton &addItem(const std::string &value, const std::function<void()> &action) override{ GUIList::addItem(value, action); auto &_button = getChild<GUIButton>(value); _button.setAction([action, this]{ action(); m_visible = false; }); return _button; } }; } } #endif //GUI_SELECTOR_LIST_HPP
28.138889
94
0.725074
MaticVrtacnik
49ca74910e6934778da48dbbb86b0bda43bfa1a0
489
hpp
C++
library/ATF/$C2F6557BF5244D9840704C1D21365DBC.hpp
lemkova/Yorozuya
f445d800078d9aba5de28f122cedfa03f26a38e4
[ "MIT" ]
29
2017-07-01T23:08:31.000Z
2022-02-19T10:22:45.000Z
library/ATF/$C2F6557BF5244D9840704C1D21365DBC.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
90
2017-10-18T21:24:51.000Z
2019-06-06T02:30:33.000Z
library/ATF/$C2F6557BF5244D9840704C1D21365DBC.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
44
2017-12-19T08:02:59.000Z
2022-02-24T23:15:01.000Z
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> #include <$42A3CB4E031CC824EFC3D0F4D1894CCF.hpp> START_ATF_NAMESPACE union $C2F6557BF5244D9840704C1D21365DBC { $42A3CB4E031CC824EFC3D0F4D1894CCF __s0; unsigned int uiData; }; static_assert(ATF::checkSize<$C2F6557BF5244D9840704C1D21365DBC, 4>(), "$C2F6557BF5244D9840704C1D21365DBC"); END_ATF_NAMESPACE
30.5625
111
0.762781
lemkova
49d268bd3f548624b4d709ab00aa2b00b3501c88
1,021
cpp
C++
desktop_version/new/Window.cpp
curaai00/VVVVVV_new
de1364089659f6da5a1518b606cbd9e34e9c83ce
[ "RSA-MD" ]
3
2020-10-05T01:30:21.000Z
2020-10-06T07:50:46.000Z
desktop_version/new/Window.cpp
curaai00/VVVVVV_new
de1364089659f6da5a1518b606cbd9e34e9c83ce
[ "RSA-MD" ]
null
null
null
desktop_version/new/Window.cpp
curaai00/VVVVVV_new
de1364089659f6da5a1518b606cbd9e34e9c83ce
[ "RSA-MD" ]
null
null
null
#include "Window.h" #include "Resource.h" Window::Window() { SDL_CreateWindowAndRenderer(width, height, SDL_WINDOW_RESIZABLE, &m_window, &m_renderer); m_screen = util::sdl::create({width, height}); m_screenTexture = SDL_CreateTexture(m_renderer, SDL_PIXELFORMAT_ABGR8888, SDL_TEXTUREACCESS_STREAMING, width, height); SDL_SetWindowTitle(m_window, "VVVVVV"); auto icon = PNGAsset("VVVVVV.png"); SDL_SetWindowIcon(m_window, icon.asset); } Window::~Window() { SDL_FreeSurface(m_screen); SDL_DestroyRenderer(m_renderer); SDL_DestroyTexture(m_screenTexture); SDL_DestroyWindow(m_window); } void Window::render(void) { auto surface = scene->surface(); SDL_UpdateTexture(m_screenTexture, NULL, surface->pixels, surface->pitch); SDL_RenderCopy(m_renderer, m_screenTexture, NULL, NULL); SDL_RenderPresent(m_renderer); SDL_RenderClear(m_renderer); SDL_FillRect(m_screen, NULL, 0x00000000); }
30.029412
84
0.68952
curaai00
49d2d180da43e0031f2cf01d31288c59cea63005
986
cpp
C++
src/alasthope/alasthope/engine/terrain_infos.cpp
jbuechner/alasthope
63a249ea49db0d8ad8462840ee9c1c57a2ea4097
[ "MIT" ]
null
null
null
src/alasthope/alasthope/engine/terrain_infos.cpp
jbuechner/alasthope
63a249ea49db0d8ad8462840ee9c1c57a2ea4097
[ "MIT" ]
null
null
null
src/alasthope/alasthope/engine/terrain_infos.cpp
jbuechner/alasthope
63a249ea49db0d8ad8462840ee9c1c57a2ea4097
[ "MIT" ]
null
null
null
#include "pch.h" #include <unordered_map> #include "terrain_infos.h" namespace { using namespace engine; std::string _none_name{ "n/a" }; std::string _sand_name{ "sands" }; std::string _badland_name { "badlands" }; terrain_info _none { 0, _none_name }; terrain_info _sand { 1, _sand_name }; terrain_info _badland { 2, _badland_name }; using cache_type = std::unordered_map<size_t, std::reference_wrapper<terrain_info>>; cache_type initialize_cache() { cache_type cache{}; cache.emplace(_sand.id, _sand); cache.emplace(_badland.id, _badland); return std::move(cache); } terrain_info const& lookup(size_t const id) { static cache_type cache = initialize_cache(); auto const iter = cache.find(id); if (iter != cache.cend()) { return iter->second; } return _none; } } namespace engine { terrain_info const& lookup_terrain_none() { return _none; } terrain_info const& lookup_terrain_info(size_t const id) { return lookup(id); } }
17.607143
85
0.701826
jbuechner
49d6be9233bee6a5dc4c13721ccf82700f87bea0
4,637
cpp
C++
submitted_models/bosdyn_spot/src/mono_camera_system.cpp
jfkeller/subt_explorer_canary1_sensor_config_1
1f0419130b79f48c66e83c084e704e521782a95a
[ "ECL-2.0", "Apache-2.0" ]
173
2020-04-09T18:39:39.000Z
2022-03-15T06:15:07.000Z
submitted_models/bosdyn_spot/src/mono_camera_system.cpp
jfkeller/subt_explorer_canary1_sensor_config_1
1f0419130b79f48c66e83c084e704e521782a95a
[ "ECL-2.0", "Apache-2.0" ]
538
2020-04-09T18:34:04.000Z
2022-02-20T09:53:17.000Z
submitted_models/bosdyn_spot/src/mono_camera_system.cpp
jfkeller/subt_explorer_canary1_sensor_config_1
1f0419130b79f48c66e83c084e704e521782a95a
[ "ECL-2.0", "Apache-2.0" ]
89
2020-04-14T20:46:48.000Z
2022-03-14T16:45:30.000Z
#include <memory> #include <ignition/msgs/double.pb.h> #include <ignition/msgs/camera_info.pb.h> #include <ignition/msgs/image.pb.h> #include <ignition/plugin/Register.hh> #include <ignition/transport/Node.hh> #include <ignition/gazebo/Model.hh> #include <ignition/gazebo/System.hh> #include <ignition/gazebo/World.hh> #include <ignition/gazebo/Util.hh> using namespace ignition; using namespace gazebo; namespace subt { /// \brief Attach this plugin inside a <sensor> tag to make it publish mono images in a sub-namespace 'mono' /// The conversion to mono is a simple one with perceptually good results (non-uniform linear combination of RGB). class MonoCameraSystem : public System, public ISystemConfigure, public ISystemPostUpdate { public: void Configure(const Entity& _entity, const std::shared_ptr<const sdf::Element>& _sdf, EntityComponentManager& _ecm, EventManager& _eventMgr) override { this->sensor = _entity; } protected: void PostUpdate(const UpdateInfo& _info, const EntityComponentManager& _ecm) override { if (this->initialized) return; // wait until the sensor is attached to world const World world(worldEntity(this->sensor, _ecm)); const auto worldName = world.Name(_ecm); if (!worldName.has_value()) return; this->initialized = true; // sensor is attached to world, now we can get full scoped name const auto sensorName = "/" + scopedName(this->sensor, _ecm); std::string subTopic { sensorName + "/image" }; std::string subInfoTopic { sensorName + "/camera_info" }; std::string pubTopic { sensorName + "/mono/image" }; std::string pubInfoTopic { sensorName + "/mono/camera_info" }; this->reqSetRateTopic = subTopic + "/set_rate"; std::string advSetRateTopic { pubTopic + "/set_rate" }; this->pub = this->node.Advertise<ignition::msgs::Image>(pubTopic); this->pubInfo = this->node.Advertise<ignition::msgs::CameraInfo>(pubInfoTopic); this->node.Subscribe(subTopic, &MonoCameraSystem::OnMsg, this); this->node.Subscribe(subInfoTopic, &MonoCameraSystem::OnInfoMsg, this); this->node.Advertise(advSetRateTopic, &MonoCameraSystem::OnSetRate, this); ignmsg << "MonoCameraSystem publishing on [" << pubTopic << "]" << std::endl; } protected: void OnMsg(const ignition::msgs::Image& msg) { ignition::msgs::Image outMsg; switch (msg.pixel_format_type()) { case ignition::msgs::PixelFormatType::BAYER_BGGR8: case ignition::msgs::PixelFormatType::BAYER_GBRG8: case ignition::msgs::PixelFormatType::BAYER_GRBG8: case ignition::msgs::PixelFormatType::BAYER_RGGB8: { outMsg.CopyFrom(msg); outMsg.set_pixel_format_type(ignition::msgs::PixelFormatType::L_INT8); break; } case ignition::msgs::PixelFormatType::RGB_INT8: case ignition::msgs::PixelFormatType::BGR_INT8: { outMsg.mutable_header()->CopyFrom(msg.header()); outMsg.set_pixel_format_type(ignition::msgs::PixelFormatType::L_INT8); outMsg.set_width(msg.width()); outMsg.set_height(msg.height()); outMsg.set_step(msg.width()); const auto length = msg.width() * msg.height(); if (this->data == nullptr) this->data = new char[length]; const auto& inData = msg.data(); for (size_t i = 0; i < length; ++i) this->data[i] = static_cast<char>((30 * inData[i*3] + 59 * inData[i*3+1] + 11 * inData[i*3+2]) / 100); outMsg.set_data(this->data, length); break; } default: { static bool warned = false; if (!warned) { ignwarn << "MonoCameraSystem: Unsupported pixel format [" << msg.pixel_format_type() << "]" << std::endl; warned = true; return; } } } this->pub.Publish(outMsg); } protected: void OnInfoMsg(const ignition::msgs::CameraInfo& msg) { this->pubInfo.Publish(msg); } protected: void OnSetRate(const ignition::msgs::Double &_rate) { this->node.Request(this->reqSetRateTopic, _rate); } public: ~MonoCameraSystem() override { delete[] this->data; this->data = nullptr; } protected: transport::Node node; protected: transport::Node::Publisher pub, pubInfo; protected: Entity sensor {kNullEntity}; protected: bool initialized {false}; protected: char* data {nullptr}; protected: std::string reqSetRateTopic; }; } IGNITION_ADD_PLUGIN(subt::MonoCameraSystem, System, ISystemConfigure, ISystemPostUpdate) IGNITION_ADD_PLUGIN_ALIAS(subt::MonoCameraSystem, "subt::MonoCameraSystem")
32.426573
115
0.671555
jfkeller
49dafa05685f2695f7cf073db87c9f689094c16c
13
hpp
C++
test/sunaba/move/waku.hpp
homirun/CLI_GAME
c3f86a75c15394a112be8a0aa80edccf30256ad2
[ "MIT" ]
2
2018-07-10T23:36:51.000Z
2018-07-20T15:43:59.000Z
test/sunaba/move/waku.hpp
homirun/CLI_GAME
c3f86a75c15394a112be8a0aa80edccf30256ad2
[ "MIT" ]
2
2018-07-03T08:01:41.000Z
2018-07-22T06:12:20.000Z
test/sunaba/move/waku.hpp
homirun/Container_Club
c3f86a75c15394a112be8a0aa80edccf30256ad2
[ "MIT" ]
null
null
null
void waku();
6.5
12
0.615385
homirun
49e18dad59c059bff5a19872093de72aa94fb89f
2,454
hpp
C++
src/armnn/backends/ClTensorHandle.hpp
Air000/armnn_s32v
ec3ee60825d6b7642a70987c4911944cef7a3ee6
[ "MIT" ]
1
2019-03-19T08:44:28.000Z
2019-03-19T08:44:28.000Z
src/armnn/backends/ClTensorHandle.hpp
Air000/armnn_s32v
ec3ee60825d6b7642a70987c4911944cef7a3ee6
[ "MIT" ]
null
null
null
src/armnn/backends/ClTensorHandle.hpp
Air000/armnn_s32v
ec3ee60825d6b7642a70987c4911944cef7a3ee6
[ "MIT" ]
1
2019-10-11T05:58:56.000Z
2019-10-11T05:58:56.000Z
// // Copyright © 2017 Arm Ltd. All rights reserved. // See LICENSE file in the project root for full license information. // #pragma once #include "OutputHandler.hpp" #include "ArmComputeTensorUtils.hpp" #include <arm_compute/runtime/CL/CLTensor.h> #include <arm_compute/runtime/CL/CLSubTensor.h> #include <arm_compute/core/TensorShape.h> #include <arm_compute/core/Coordinates.h> namespace armnn { class IClTensorHandle : public ITensorHandle { public: virtual arm_compute::ICLTensor& GetTensor() = 0; virtual arm_compute::ICLTensor const& GetTensor() const = 0; virtual void Map(bool blocking = true) = 0; virtual void UnMap() = 0; virtual arm_compute::DataType GetDataType() const = 0; }; class ClTensorHandle : public IClTensorHandle { public: ClTensorHandle(const TensorInfo& tensorInfo) { armnn::armcomputetensorutils::BuildArmComputeTensor(m_Tensor, tensorInfo); } arm_compute::CLTensor& GetTensor() override { return m_Tensor; } arm_compute::CLTensor const& GetTensor() const override { return m_Tensor; } virtual void Allocate() override {armnn::armcomputetensorutils::InitialiseArmComputeTensorEmpty(m_Tensor);}; virtual void Map(bool blocking = true) override {m_Tensor.map(blocking);} virtual void UnMap() override { m_Tensor.unmap();} virtual ITensorHandle::Type GetType() const override { return ITensorHandle::CL;} virtual arm_compute::DataType GetDataType() const override { return m_Tensor.info()->data_type(); } private: arm_compute::CLTensor m_Tensor; }; class ClSubTensorHandle : public IClTensorHandle { public: ClSubTensorHandle(arm_compute::ICLTensor& parent, const arm_compute::TensorShape& shape, const arm_compute::Coordinates& coords) : m_Tensor(&parent, shape, coords) { } arm_compute::CLSubTensor& GetTensor() override { return m_Tensor; } arm_compute::CLSubTensor const& GetTensor() const override { return m_Tensor; } virtual void Allocate() override {}; virtual void Map(bool blocking = true) override {m_Tensor.map(blocking);} virtual void UnMap() override { m_Tensor.unmap();} virtual ITensorHandle::Type GetType() const override { return ITensorHandle::CL;} virtual arm_compute::DataType GetDataType() const override { return m_Tensor.info()->data_type(); } private: arm_compute::CLSubTensor m_Tensor; }; }
28.534884
112
0.713936
Air000
49e56a8767e1e078f6fb2af700c8ae45ac0fb7fc
147
cpp
C++
engine/src/ImGui/imguibuild.cpp
mrcoalp/dempsta-engine
5f60094c0f9eb2bc4541dcd96cdab3f0eafb7346
[ "MIT" ]
1
2020-12-08T17:15:46.000Z
2020-12-08T17:15:46.000Z
engine/src/ImGui/imguibuild.cpp
mrcoalp/dempsta-engine
5f60094c0f9eb2bc4541dcd96cdab3f0eafb7346
[ "MIT" ]
null
null
null
engine/src/ImGui/imguibuild.cpp
mrcoalp/dempsta-engine
5f60094c0f9eb2bc4541dcd96cdab3f0eafb7346
[ "MIT" ]
null
null
null
#define IMGUI_IMPL_OPENGL_LOADER_GLAD #include <examples/imgui_impl_opengl3.cpp> // Keep order of includes #include <examples/imgui_impl_glfw.cpp>
29.4
42
0.836735
mrcoalp
49e6d9fda063b8f6183779daa787d0c906059895
1,356
cc
C++
nox/src/lib/flow-stats-in.cc
ayjazz/OESS
deadc504d287febc7cbd7251ddb102bb5c8b1f04
[ "Apache-2.0" ]
28
2015-02-04T13:59:25.000Z
2021-12-29T03:44:47.000Z
nox/src/lib/flow-stats-in.cc
ayjazz/OESS
deadc504d287febc7cbd7251ddb102bb5c8b1f04
[ "Apache-2.0" ]
552
2015-01-05T18:25:54.000Z
2022-03-16T18:51:13.000Z
nox/src/lib/flow-stats-in.cc
ayjazz/OESS
deadc504d287febc7cbd7251ddb102bb5c8b1f04
[ "Apache-2.0" ]
25
2015-02-04T18:48:20.000Z
2020-06-18T15:51:05.000Z
#include "flow-stats-in.hh" #include <vector> namespace vigil { Flow_stats::Flow_stats(const ofp_flow_stats* ofs) : action_data(new uint8_t[ntohs(ofs->length) - sizeof *ofs]) { *(ofp_flow_stats*) this = *ofs; memcpy(action_data.get(), ofs->actions, ntohs(ofs->length) - sizeof *ofs); uint8_t * p = (uint8_t *)ofs->actions; const uint8_t * end = ((uint8_t *)ofs) + ntohs(ofs->length); while (p < end) { const ofp_action_header * h = (ofp_action_header *)p; v_actions.push_back(h); p += ntohs(h->len); } } Flow_stats_in_event::Flow_stats_in_event(const datapathid& dpid, const ofp_stats_reply *osr, std::auto_ptr<Buffer> buf) : Event(static_get_name()), Ofp_msg_event(&osr->header, buf), more((osr->flags & htons(OFPSF_REPLY_MORE)) != 0) { datapath_id = dpid; size_t flow_len = htons(osr->header.length) - sizeof *osr; const ofp_flow_stats* ofs = (ofp_flow_stats*) osr->body; while (flow_len >= sizeof *ofs) { size_t length = ntohs(ofs->length); if (length > flow_len) { break; } flows.push_back(Flow_stats(ofs)); ofs = (const ofp_flow_stats*)((const char*) ofs + length); flow_len -= length; } } } // namespace vigil
30.818182
78
0.585546
ayjazz
49e71997eeba6fb6925db11e22c53a1c21e4ba7a
134
hpp
C++
openstudiocore/src/isomodel/mainpage.hpp
zhouchong90/OpenStudio
f8570cb8297547b5e9cc80fde539240d8f7b9c24
[ "BSL-1.0", "blessing" ]
4
2015-05-02T21:04:15.000Z
2015-10-28T09:47:22.000Z
openstudiocore/src/isomodel/mainpage.hpp
zhouchong90/OpenStudio
f8570cb8297547b5e9cc80fde539240d8f7b9c24
[ "BSL-1.0", "blessing" ]
null
null
null
openstudiocore/src/isomodel/mainpage.hpp
zhouchong90/OpenStudio
f8570cb8297547b5e9cc80fde539240d8f7b9c24
[ "BSL-1.0", "blessing" ]
1
2020-11-12T21:52:36.000Z
2020-11-12T21:52:36.000Z
namespace openstudio { namespace isomodel { /** \mainpage OpenStudio ISOModel Translator * * */ } // isomodel } // openstudio
14.888889
45
0.671642
zhouchong90
49e8e5fd0a7decdb38f0dafe6fcfe2993fb2ea47
2,541
hpp
C++
inc/trie.hpp
yang-le/cpp-algorithms
0c1f422bc1e9fefa1a7d430b4a13ef7795420a2e
[ "MIT" ]
null
null
null
inc/trie.hpp
yang-le/cpp-algorithms
0c1f422bc1e9fefa1a7d430b4a13ef7795420a2e
[ "MIT" ]
null
null
null
inc/trie.hpp
yang-le/cpp-algorithms
0c1f422bc1e9fefa1a7d430b4a13ef7795420a2e
[ "MIT" ]
null
null
null
// MIT License // Copyright (c) 2018 Yang Le // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #pragma once #include <string> #include <unordered_set> #include "trie_node.hpp" class Trie { public: static const char HEAD_CHARACTER = '*'; Trie() : head_(HEAD_CHARACTER) {} void addWord(const std::string& word) { auto characters = word.c_str(); TrieNode* currentNode = &head_; for (int charIndex = 0; charIndex < word.length(); ++charIndex) { auto isComplete = (charIndex == word.length() - 1); currentNode = currentNode->addChild(characters[charIndex], isComplete); } } std::unordered_set<std::string> suggestNextCharacters( const std::string& word) const { auto lastCharacter = getLastCharacterNode(word); if (!lastCharacter) { return std::unordered_set<std::string>(); } return lastCharacter->suggestChildren(); } bool doesWordExist(const std::string& word) const { return !!getLastCharacterNode(word); } private: const TrieNode* getLastCharacterNode(const std::string& word) const { auto characters = word.c_str(); const TrieNode* currentNode = &head_; for (int charIndex = 0; charIndex < word.length(); ++charIndex) { if (!currentNode->hasChild(characters[charIndex])) { return nullptr; } currentNode = currentNode->getChild(characters[charIndex]); } return currentNode; } public: TrieNode head_; };
33.434211
81
0.690673
yang-le
49ecbaf654f2bb046b9771fb73b6c75925af72a9
1,671
cpp
C++
unit-tests.wsjcpp/src/unit_test_get_env.cpp
wsjcpp/wsjcpp-core
b445f0cf73d6d6abfa2c10a14352f35f2f2d16bd
[ "MIT" ]
1
2019-11-22T19:29:38.000Z
2019-11-22T19:29:38.000Z
unit-tests.wsjcpp/src/unit_test_get_env.cpp
wsjcpp/wsjcpp-core
b445f0cf73d6d6abfa2c10a14352f35f2f2d16bd
[ "MIT" ]
30
2020-01-06T06:59:57.000Z
2021-08-29T05:34:54.000Z
unit-tests.wsjcpp/src/unit_test_get_env.cpp
wsjcpp/wsjcpp-core
b445f0cf73d6d6abfa2c10a14352f35f2f2d16bd
[ "MIT" ]
null
null
null
#include "unit_test_get_env.h" #include <vector> #include <wsjcpp_core.h> REGISTRY_WSJCPP_UNIT_TEST(UnitTestGetEnv) UnitTestGetEnv::UnitTestGetEnv() : WsjcppUnitTestBase("UnitTestGetEnv") { } // --------------------------------------------------------------------- bool UnitTestGetEnv::doBeforeTest() { // nothing return true; } // --------------------------------------------------------------------- void UnitTestGetEnv::executeTest() { struct LTest { LTest(const std::string &sName, bool bExpectedResult, const std::string &sExpectedValue) { this->sName = sName; this->sExpectedValue = sExpectedValue; this->bExpectedResult = bExpectedResult; }; std::string sName; bool bExpectedResult; std::string sExpectedValue; }; std::vector<LTest> tests; tests.push_back(LTest("TESTENVVALUE1", true, "testvalue1")); tests.push_back(LTest("TESTENVVALUE1_", false, "")); tests.push_back(LTest("TEST_ENV_VALUE2", true, "test some value2")); tests.push_back(LTest("TEST_ENV_VALUE3", true, "932749387")); for (int i = 0; i < tests.size(); i++) { LTest test = tests[i]; std::string sValue; bool bResult = WsjcppCore::getEnv(test.sName, sValue); std::string testBaseName = "test#" + std::to_string(i) + " (" + test.sName + ")"; compare(testBaseName + "-result", bResult, test.bExpectedResult); compare(testBaseName + "-value", sValue, test.sExpectedValue); } } // --------------------------------------------------------------------- bool UnitTestGetEnv::doAfterTest() { // nothing return true; }
31.528302
98
0.559545
wsjcpp
49f4b8cfe6425c908ebe4f93ed83f1f30ddca27d
1,547
cpp
C++
assign7/Iterator.cpp
wbjeon2k/uni06_archive
5c37716d5c011f2aa23675778b0947c064882856
[ "MIT" ]
null
null
null
assign7/Iterator.cpp
wbjeon2k/uni06_archive
5c37716d5c011f2aa23675778b0947c064882856
[ "MIT" ]
null
null
null
assign7/Iterator.cpp
wbjeon2k/uni06_archive
5c37716d5c011f2aa23675778b0947c064882856
[ "MIT" ]
null
null
null
#include "Iterator.h" #include <iostream> using namespace std; Iterator::Iterator(Node *currIn) { curr = currIn; } const string Iterator::operator*() const { string tmp = this->curr->getWord(); delete curr; return tmp; } Iterator& Iterator::operator++() {//prefix this->curr = this->curr->getNext(); return *this; } Iterator& Iterator::operator--() {//prefix this->curr = this->curr->getPrev(); return *this; } Iterator Iterator::operator++(int) {//prefix Iterator tmp(*this); this->curr = this->curr->getNext(); return tmp; } Iterator Iterator::operator--(int) {//prefix Iterator tmp(*this); this->curr = this->curr->getPrev(); return tmp; } Iterator Iterator::operator+(const int & input) { Iterator tmp(this->curr); for (int i = 0;i < input;i++) { ++tmp; } return tmp; } Iterator Iterator::operator-(const int & input) { Iterator tmp(this->curr); for (int i = 0;i < input;i++) { --tmp; } return tmp; } Iterator Iterator::operator+=(const int & input) { *this = *this + input; return *this; } Iterator Iterator::operator-=(const int & input) { *this = *this - input; return *this; } bool Iterator::operator==(const Iterator &other) { if (this->curr == other.curr) { return true; } else { return false; } } bool Iterator::operator!=(const Iterator &other) { if (this->curr != other.curr) { return true; } else { return false; } } Node *& Iterator::getCurr() { return curr; } //Iterator & Iterator::operator=(const Iterator &other) { // this->curr = other.curr; // return *this; //}
16.815217
57
0.641888
wbjeon2k
49f85b08dcbec6dc05fff6e2280fb4dd7d34af41
1,551
hpp
C++
Enginelib/src/components/polygoncollider.hpp
kalsipp/vsxpanse
7887d234312283ce1ace03bed610642b0c6f96b1
[ "MIT" ]
null
null
null
Enginelib/src/components/polygoncollider.hpp
kalsipp/vsxpanse
7887d234312283ce1ace03bed610642b0c6f96b1
[ "MIT" ]
null
null
null
Enginelib/src/components/polygoncollider.hpp
kalsipp/vsxpanse
7887d234312283ce1ace03bed610642b0c6f96b1
[ "MIT" ]
null
null
null
#pragma once #include "../collider.hpp" #include <vector> class Projection { public: Projection(double min, double max) :m_min(min), m_max(max) {} const double m_min; const double m_max; bool overlap(const Projection& other); bool contains(const Projection& other); private: }; class CircleCollider; class PolygonCollider :public Collider { public: PolygonCollider(GameObject* owner) :Collider(owner){} /*------------------------------------------------------- @param init_points - each point of the polygon collider in local space. ---------------------------------------------------------*/ void initialize(const std::initializer_list<Vector2D>& init_points); bool collides_with(const PolygonCollider* other); bool collides_with(const CircleCollider* other); const std::vector<Vector2D>& get_points()const; std::vector<Vector2D> get_points_worldpos()const; Vector2D get_centre_point_worldpos(); static bool is_convex_simple(const std::vector<Vector2D> & points); protected: void register_collider()override; void unregister_collider()override; friend class PhysxEngine; private: static void calculate_normals( const std::vector <Vector2D>& points, std::vector<Vector2D>& normals); bool do_projections_overlap(const std::vector<Vector2D>& normals, const std::vector<Vector2D>& first_points, const std::vector<Vector2D>& other_points); static Projection project(const Vector2D& axis, const std::vector<Vector2D>& points); Vector2D calculate_centre_point(); std::vector<Vector2D> points; Vector2D centre_point; };
31.653061
153
0.717602
kalsipp
8e6ba4c7150c041e66b163fb3ec4b2e6ee44ac21
3,486
cpp
C++
main.cpp
bigfatbrowncat/Detect3D
f6538b1c29c5f15fba39bed38a20496c0320023c
[ "MIT" ]
null
null
null
main.cpp
bigfatbrowncat/Detect3D
f6538b1c29c5f15fba39bed38a20496c0320023c
[ "MIT" ]
null
null
null
main.cpp
bigfatbrowncat/Detect3D
f6538b1c29c5f15fba39bed38a20496c0320023c
[ "MIT" ]
1
2018-11-25T13:18:58.000Z
2018-11-25T13:18:58.000Z
#include <opencv2/core/core.hpp> #include <opencv2/imgcodecs/imgcodecs.hpp> #include <opencv2/imgcodecs/imgcodecs_c.h> #include <opencv2/imgproc/imgproc.hpp> #include <assert.h> #include <iostream> #include <vector> using namespace cv; using namespace std; double getPSNR(const Mat& I1, const Mat& I2) { Mat s1; absdiff(I1, I2, s1); // |I1 - I2| s1.convertTo(s1, CV_32F); // cannot make a square on 8 bits s1 = s1.mul(s1); // |I1 - I2|^2 Scalar s = sum(s1); // sum elements per channel double sse = s.val[0] + s.val[1] + s.val[2]; // sum channels if (sse <= 1e-10) // for small values return zero return 0; else { double mse = sse / (double)(I1.channels() * I1.total()); double psnr = 10.0*log10((255 * 255) / mse); return psnr; } } double PSNRShift(int shift, const Mat& I1, const Mat& I2) { if (shift >= 0) { Mat cut2left = cv::Mat(I2, Range::all(), Range(shift, I2.size().width - 1)); Mat cut1right = cv::Mat(I1, Range::all(), Range(0, I1.size().width - 1 - shift)); return getPSNR(cut1right, cut2left); } else { shift *= -1; Mat cut1left = cv::Mat(I1, Range::all(), Range(shift, I1.size().width - 1)); Mat cut2right = cv::Mat(I2, Range::all(), Range(0, I2.size().width - 1 - shift)); return getPSNR(cut1left, cut2right); } } int main(int argc, char** argv) { if (argc != 2) { cout << " Usage: detect3d <image_file>" << endl; return -1; } Mat image; image = imread(argv[1], CV_LOAD_IMAGE_COLOR); // Read the file cv::Range part1HRange(0, image.size().height / 2 - 1); cv::Range part2HRange(image.size().height / 2, image.size().height - 1); Mat part1 = cv::Mat(image, part1HRange, Range::all()); Mat part2 = cv::Mat(image, part2HRange, Range::all()); if (!image.data) // Check for invalid input { cerr << "Could not open or find the image" << std::endl; return -1; } // Scaling by 2 std::vector<Mat> scaledPart1, scaledPart2; scaledPart1.push_back(part1); scaledPart2.push_back(part2); int dw = part1.size().width, dh = part1.size().height; const int factor = 2; while (dw > 32 && dh > 32) { dw /= factor; dh /= factor; Mat newP1, newP2; resize(scaledPart1.back(), newP1, Size(dw, dh)); resize(scaledPart2.back(), newP2, Size(dw, dh)); scaledPart1.push_back(newP1); scaledPart2.push_back(newP2); } assert(scaledPart1.size() == scaledPart2.size()); int moved = 0; int p = 1; vector<double> maxPSNRValues; vector<int> shifts; for (auto iter1 = scaledPart1.rbegin(), iter2 = scaledPart2.rbegin(); iter1 != scaledPart1.rend(); iter1++, iter2++) { int diff = 0; double maxPSNR = 0; for (int shift = -10; shift <= 10; shift++) { double psnr = PSNRShift(moved + shift, *iter1, *iter2); // cout << p*(moved + shift) << " " << psnr << endl; if (psnr > maxPSNR) { maxPSNR = psnr; diff = shift; } } p *= factor; shifts.push_back(moved + diff); moved = (moved + diff) * factor; // cout << endl; maxPSNRValues.push_back(maxPSNR); } // Averaging the results double avgPSNR = 0, maxPSNR = 0, fullShift = shifts.back(); for (size_t i = 0; i < scaledPart1.size(); i++) { avgPSNR += maxPSNRValues[i]; if (maxPSNR < maxPSNRValues[i]) { maxPSNR = maxPSNRValues[i]; } } fullShift /= (part1.size().width); avgPSNR /= maxPSNRValues.size(); std::cout << "{ \"avgShift\": \"" << fullShift << "\", \"avgPSNR\": \"" << avgPSNR << "\", \"maxPSNR\": \"" << maxPSNR << "\" }" << std::endl; return 0; }
28.112903
143
0.614458
bigfatbrowncat
8e6ca4f9aa66081aac7137470935be0a4d22d7b8
16,441
cpp
C++
src/Lib/rfc3550/Rtcp.cpp
miseri/rtp_plus_plus
244ddd86f40f15247dd39ae7f9283114c2ef03a2
[ "BSD-3-Clause" ]
1
2021-07-14T08:15:05.000Z
2021-07-14T08:15:05.000Z
src/Lib/rfc3550/Rtcp.cpp
7956968/rtp_plus_plus
244ddd86f40f15247dd39ae7f9283114c2ef03a2
[ "BSD-3-Clause" ]
null
null
null
src/Lib/rfc3550/Rtcp.cpp
7956968/rtp_plus_plus
244ddd86f40f15247dd39ae7f9283114c2ef03a2
[ "BSD-3-Clause" ]
2
2021-07-14T08:15:02.000Z
2021-07-14T08:56:10.000Z
#include "CorePch.h" #include <rtp++/rfc3550/Rtcp.h> #include <boost/make_shared.hpp> #include <cpputil/IBitStream.h> #include <cpputil/OBitStream.h> #include <cpputil/Utility.h> #include <rtp++/RtpTime.h> namespace rtp_plus_plus { namespace rfc3550 { RtcpRrReportBlock::RtcpRrReportBlock() :m_uiReporteeSSRC(0), m_uiFractionLost(0), m_uiCumulativeNumberOfPacketsLost(0), m_uiExtendedHighestSNReceived(0), m_uiInterarrivalJitter(0), m_uiLastSr(0), m_uiDelaySinceLastSr(0) { } void RtcpRrReportBlock::write( OBitStream& ob ) const { ob.write(m_uiReporteeSSRC, 32); ob.write(m_uiFractionLost, 8); ob.write(m_uiCumulativeNumberOfPacketsLost, 24); ob.write(m_uiExtendedHighestSNReceived, 32); ob.write(m_uiInterarrivalJitter, 32); ob.write(m_uiLastSr, 32); ob.write(m_uiDelaySinceLastSr, 32); } void RtcpRrReportBlock::read( IBitStream& ib ) { ib.read(m_uiReporteeSSRC, 32); ib.read(m_uiFractionLost, 8); ib.read(m_uiCumulativeNumberOfPacketsLost, 24); ib.read(m_uiExtendedHighestSNReceived, 32); ib.read(m_uiInterarrivalJitter, 32); ib.read(m_uiLastSr, 32); ib.read(m_uiDelaySinceLastSr, 32); } std::ostream& operator<< (std::ostream& ostr, const RtcpRrReportBlock& block) { ostr << "RR:" << " SSRC :" << hex(block.m_uiReporteeSSRC) << " LSR: " << hex(block.m_uiLastSr) << " DLSR: " << hex(block.m_uiDelaySinceLastSr) << "(" << RtpTime::convertDlsrToSeconds(block.m_uiDelaySinceLastSr) << ") " << " XSN: " << hex(block.m_uiExtendedHighestSNReceived) << " L: " << hex(block.m_uiCumulativeNumberOfPacketsLost) << " LF: " << hex(block.m_uiFractionLost) << " J: " << hex(block.m_uiInterarrivalJitter); return ostr; } RtcpSr::ptr RtcpSr::create() { return boost::make_shared<RtcpSr>(); } RtcpSr::ptr RtcpSr::create( uint32_t uiSSRC, uint32_t uiNtpTimestampMsw, uint32_t uiNtpTimestampLsw, uint32_t uiRtpTimestamp, uint32_t uiSendersPacketCount, uint32_t uiSendersOctetCount ) { return boost::make_shared<RtcpSr>(uiSSRC, uiNtpTimestampMsw, uiNtpTimestampLsw, uiRtpTimestamp, uiSendersPacketCount, uiSendersOctetCount); } RtcpSr::ptr RtcpSr::create( uint8_t uiVersion, bool uiPadding, uint8_t uiTypeSpecific, uint16_t uiLengthInWords ) { return boost::make_shared<RtcpSr>(uiVersion, uiPadding, uiTypeSpecific, uiLengthInWords); } RtcpSr::RtcpSr() :RtcpPacketBase(PT_RTCP_SR), m_uiSSRC(0), m_uiNtpTimestampMsw(0), m_uiNtpTimestampLsw(0), m_uiRtpTimestamp(0), m_uiSendersPacketCount(0), m_uiSendersOctetCount(0) { } RtcpSr::RtcpSr( uint8_t uiVersion, bool uiPadding, uint8_t uiTypeSpecific, uint16_t uiLengthInWords ) :RtcpPacketBase(uiVersion, uiPadding, uiTypeSpecific, PT_RTCP_SR, uiLengthInWords), m_uiSSRC(0), m_uiNtpTimestampMsw(0), m_uiNtpTimestampLsw(0), m_uiRtpTimestamp(0), m_uiSendersPacketCount(0), m_uiSendersOctetCount(0) { } RtcpSr::RtcpSr( uint32_t uiSSRC, uint32_t uiNtpTimestampMsw, uint32_t uiNtpTimestampLsw, uint32_t uiRtpTimestamp, uint32_t uiSendersPacketCount, uint32_t uiSendersOctetCount ) :RtcpPacketBase(PT_RTCP_SR), m_uiSSRC(uiSSRC), m_uiNtpTimestampMsw(uiNtpTimestampMsw), m_uiNtpTimestampLsw(uiNtpTimestampLsw), m_uiRtpTimestamp(uiRtpTimestamp), m_uiSendersPacketCount(uiSendersPacketCount), m_uiSendersOctetCount(uiSendersOctetCount) { setLength(BASIC_SR_LENGTH); // length of sender report specific data } bool RtcpSr::addReportBlock( RtcpRrReportBlock reportBlock ) { if (m_vReports.size() < 31) { m_vReports.push_back(reportBlock); // update RC field in base RTCP packet setTypeSpecific(m_vReports.size()); // update length field setLength(BASIC_SR_LENGTH + m_vReports.size() * BASIC_RR_BLOCK_LENGTH); return true; } return false; } void RtcpSr::writeTypeSpecific( OBitStream& ob ) const { ob.write(m_uiSSRC, 32); ob.write(m_uiNtpTimestampMsw, 32); ob.write(m_uiNtpTimestampLsw, 32); ob.write(m_uiRtpTimestamp, 32); ob.write(m_uiSendersPacketCount, 32); ob.write(m_uiSendersOctetCount, 32); std::for_each(m_vReports.begin(), m_vReports.end(), [&ob](RtcpRrReportBlock report) { report.write(ob); } ); } void RtcpSr::readTypeSpecific( IBitStream& ib ) { ib.read(m_uiSSRC, 32); ib.read(m_uiNtpTimestampMsw, 32); ib.read(m_uiNtpTimestampLsw, 32); ib.read(m_uiRtpTimestamp, 32); ib.read(m_uiSendersPacketCount, 32); ib.read(m_uiSendersOctetCount, 32); for (size_t i = 0; i < getTypeSpecific(); ++i) { RtcpRrReportBlock reportBlock; reportBlock.read(ib); // need to add validation to ib!!!! m_vReports.push_back(reportBlock); } // TODO: perform some validation that the raw constructor values add up to the new length } RtcpRr::ptr RtcpRr::create() { return boost::make_shared<RtcpRr>(); } RtcpRr::ptr RtcpRr::create( uint32_t uiSSRC ) { return boost::make_shared<RtcpRr>(uiSSRC); } RtcpRr::ptr RtcpRr::create( uint8_t uiVersion, bool uiPadding, uint8_t uiTypeSpecific, uint16_t uiLengthInWords ) { return boost::make_shared<RtcpRr>(uiVersion, uiPadding, uiTypeSpecific, uiLengthInWords); } RtcpRr::RtcpRr() :RtcpPacketBase(PT_RTCP_RR), m_uiReporterSSRC(0) { // update length field setLength(BASIC_RR_LENGTH); } RtcpRr::RtcpRr( uint32_t uiSSRC ) :RtcpPacketBase(PT_RTCP_RR), m_uiReporterSSRC(uiSSRC) { // update length field setLength(BASIC_RR_LENGTH); } RtcpRr::RtcpRr( uint8_t uiVersion, bool uiPadding, uint8_t uiTypeSpecific, uint16_t uiLengthInWords ) :RtcpPacketBase(uiVersion, uiPadding, uiTypeSpecific, PT_RTCP_RR, uiLengthInWords), m_uiReporterSSRC(0) { } bool RtcpRr::addReportBlock( RtcpRrReportBlock reportBlock ) { if (m_vReports.size() < 31) { m_vReports.push_back(reportBlock); // update RC field in base RTCP packet setTypeSpecific(m_vReports.size()); // update length field setLength(BASIC_RR_LENGTH + m_vReports.size() * BASIC_RR_BLOCK_LENGTH); return true; } return false; } void RtcpRr::writeTypeSpecific( OBitStream& ob ) const { ob.write(m_uiReporterSSRC, 32); std::for_each(m_vReports.begin(), m_vReports.end(), [&ob](RtcpRrReportBlock report) { report.write(ob); } ); } void RtcpRr::readTypeSpecific( IBitStream& ib ) { ib.read(m_uiReporterSSRC, 32); for (size_t i = 0; i < getTypeSpecific(); ++i) { VLOG(10) << "Parsing Rtcp Report Block"; RtcpRrReportBlock reportBlock; reportBlock.read(ib); // need to add validation to ib!!!! m_vReports.push_back(reportBlock); } } RtcpSdesReportBlock::RtcpSdesReportBlock() :m_uiSSRC_CSRC1(0) { } RtcpSdesReportBlock::RtcpSdesReportBlock( uint32_t uiSSRC_CSRC ) :m_uiSSRC_CSRC1(uiSSRC_CSRC) { } std::uint32_t RtcpSdesReportBlock::getOctetCount() const { return 4 + // SSRC CSRC addLength(getCName()) + addLength(getName()) + addLength(getEmail()) + addLength(getPhone()) + addLength(getLoc()) + addLength(getTool()) + addLength(getNote()) + addLength(getPriv()); } std::uint32_t RtcpSdesReportBlock::getWordCount() const { uint32_t uiWords = getOctetCount() >> 2; if (getPadding()) ++uiWords; return uiWords; } std::uint32_t RtcpSdesReportBlock::getPadding() const { return (4 - (getOctetCount() % 4)); } void RtcpSdesReportBlock::write( OBitStream& ob ) const { ob.write(m_uiSSRC_CSRC1, 32); writeListItemIfNotEmpty(ob, RTCP_SDES_TYPE_CNAME, getCName()); writeListItemIfNotEmpty(ob, RTCP_SDES_TYPE_NAME, getName()); writeListItemIfNotEmpty(ob, RTCP_SDES_TYPE_EMAIL, getEmail()); writeListItemIfNotEmpty(ob, RTCP_SDES_TYPE_PHONE, getPhone()); writeListItemIfNotEmpty(ob, RTCP_SDES_TYPE_LOC, getLoc()); writeListItemIfNotEmpty(ob, RTCP_SDES_TYPE_TOOL, getTool()); writeListItemIfNotEmpty(ob, RTCP_SDES_TYPE_NOTE, getNote()); writeListItemIfNotEmpty(ob, RTCP_SDES_TYPE_PRIV, getPriv()); } void RtcpSdesReportBlock::read( IBitStream& ib ) { ib.read(m_uiSSRC_CSRC1, 32); // read until we see a NULL octet while (moreSdesItemsToBeRead(ib)) { // parse SDES list item readListItem(ib); } // now we need to consume the padding until a 32-bit boundary is reached VLOG(10) << "Skipping padding: " << getPadding(); ib.skipBytes(getPadding()); } bool RtcpSdesReportBlock::moreSdesItemsToBeRead( IBitStream& ib ) { // peek ahead and check for NULL octet return (ib.getBitsRemaining() > 0 && ib.peekAtCurrentByte() != 0); } void RtcpSdesReportBlock::writeListItemIfNotEmpty( OBitStream& ob, uint8_t uiType, const std::string& sValue ) const { if (!sValue.empty()) { std::string sTempVal; uint32_t uiLen = sValue.length(); if (uiLen > RTP_MAX_SDES) sTempVal = sValue.substr(0, RTP_MAX_SDES); else sTempVal = sValue; ob.write( uiType, 8); ob.write( sTempVal.length(), 8); std::for_each(sTempVal.begin(), sTempVal.end(), [&ob](char c) { ob.write(c, 8); } ); } } void RtcpSdesReportBlock::readListItem( IBitStream& ib ) { uint32_t uiType = 0; uint32_t uiLength = 0; ib.read( uiType, 8); ib.read( uiLength, 8); uint8_t buffer[256]; buffer[uiLength] = '\0'; for (size_t i = 0; i < uiLength; ++i) { ib.read(buffer[i], 8); } std::string sValue(reinterpret_cast<const char*>(buffer), uiLength); switch (uiType) { case RTCP_SDES_TYPE_CNAME: { VLOG(10) << "Read SDES CName: " << sValue; setCName(sValue); break; } case RTCP_SDES_TYPE_NAME: { VLOG(10) << "Read SDES Name: " << sValue; setName(sValue); break; } case RTCP_SDES_TYPE_EMAIL: { VLOG(10) << "Read SDES Email: " << sValue; setEmail(sValue); break; } case RTCP_SDES_TYPE_PHONE: { VLOG(10) << "Read SDES Phone: " << sValue; setPhone(sValue); break; } case RTCP_SDES_TYPE_LOC: { VLOG(10) << "Read SDES Loc: " << sValue; setLoc(sValue); break; } case RTCP_SDES_TYPE_TOOL: { VLOG(10) << "Read SDES Tool: " << sValue; setTool(sValue); break; } case RTCP_SDES_TYPE_NOTE: { VLOG(10) << "Read SDES Note: " << sValue; setNote(sValue); break; } case RTCP_SDES_TYPE_PRIV: { VLOG(10) << "Read SDES Priv: " << sValue; setPriv(sValue); break; } } } std::uint32_t RtcpSdesReportBlock::addLength( const std::string& sValue ) const { return (sValue.empty()) ? 0 : (sValue.length() + SDES_ITEM_HEADER_LENGTH); } RtcpSdes::ptr RtcpSdes::create() { return boost::make_shared<RtcpSdes>(); } RtcpSdes::ptr RtcpSdes::create( uint8_t uiVersion, bool uiPadding, uint8_t uiTypeSpecific, uint16_t uiLengthInWords ) { return boost::make_shared<RtcpSdes>(uiVersion, uiPadding, uiTypeSpecific, uiLengthInWords); } RtcpSdes::RtcpSdes() :RtcpPacketBase(PT_RTCP_SDES) { } RtcpSdes::RtcpSdes( uint8_t uiVersion, bool uiPadding, uint8_t uiTypeSpecific, uint16_t uiLengthInWords ) :RtcpPacketBase(uiVersion, uiPadding, uiTypeSpecific, PT_RTCP_SDES, uiLengthInWords) { } void RtcpSdes::addSdesReport( RtcpSdesReportBlock report ) { m_vReports.push_back(report); // update base field setTypeSpecific(m_vReports.size()); // update length field setLength(getLength() + report.getWordCount()); } void RtcpSdes::writeTypeSpecific( OBitStream& ob ) const { std::for_each(m_vReports.begin(), m_vReports.end(), [&ob](RtcpSdesReportBlock report) { report.write(ob); // padding for (size_t i = 0; i < report.getPadding(); ++i) { ob.write(0, 8); } } ); } void RtcpSdes::readTypeSpecific( IBitStream& ib ) { for (size_t i = 0; i < getTypeSpecific(); ++i) { RtcpSdesReportBlock reportBlock; reportBlock.read(ib); m_vReports.push_back(reportBlock); } } RtcpApp::ptr RtcpApp::create() { return boost::make_shared<RtcpApp>(); } RtcpApp::ptr RtcpApp::create( uint8_t uiVersion, bool uiPadding, uint8_t uiTypeSpecific, uint16_t uiLengthInWords ) { return boost::make_shared<RtcpApp>(uiVersion, uiPadding, uiTypeSpecific, uiLengthInWords); } RtcpApp::RtcpApp() :RtcpPacketBase(PT_RTCP_APP) { memset(m_PacketName, 0, 4); } RtcpApp::RtcpApp( uint8_t uiVersion, bool uiPadding, uint8_t uiTypeSpecific, uint16_t uiLengthInWords ) :RtcpPacketBase(uiVersion, uiPadding, uiTypeSpecific, PT_RTCP_APP, uiLengthInWords) { memset(m_PacketName, 0, 4); } void RtcpApp::setAppData( uint8_t uiSubtype, char packetName[4], uint8_t* uiData, uint32_t uiLenBytes ) { // app specific setTypeSpecific(uiSubtype); memcpy(m_PacketName, packetName, 4); uint8_t* pData = new uint8_t[uiLenBytes]; m_appData.setData(pData, uiLenBytes); memcpy(pData, uiData, uiLenBytes); // base header length recalculateLength(); } std::uint32_t RtcpApp::getPadding() const { return (4 - (m_appData.getSize() % 4)); } void RtcpApp::recalculateLength() { uint32_t uiSizeWords = m_appData.getSize() >> 2; if (getPadding() > 0) ++uiSizeWords; setLength( 2 + uiSizeWords); } void RtcpApp::writeTypeSpecific( OBitStream& ob ) const { // SSRC ob.write(m_uiSSRC, 32); // packet name for (size_t i = 0; i < 4; ++i) { ob.write(m_PacketName[i], 8); } for (size_t i = 0; i < m_appData.getSize(); ++i) { ob.write(m_appData[i], 8); } for (size_t i = 0; i < getPadding(); ++i) { ob.write(0, 8); } } void RtcpApp::readTypeSpecific( IBitStream& ib ) { // SSRC ib.read(m_uiSSRC, 32); // packet name for (size_t i = 0; i < 4; ++i) { ib.read(m_PacketName[i], 8); } // TODO: // for (size_t i = 0; i < m_appData.getSize(); ++i) // { // ob.write(m_appData[i], 8); // } // // for (size_t i = 0; i < getPadding(); ++i) // { // ob.write(0, 8); // } } RtcpBye::ptr RtcpBye::create() { return boost::make_shared<RtcpBye>(); } RtcpBye::ptr RtcpBye::create( uint8_t uiVersion, bool uiPadding, uint8_t uiTypeSpecific, uint16_t uiLengthInWords ) { return boost::make_shared<RtcpBye>(uiVersion, uiPadding, uiTypeSpecific, uiLengthInWords); } RtcpBye::ptr RtcpBye::create( uint32_t uiSSRC ) { return boost::make_shared<RtcpBye>(uiSSRC); } RtcpBye::RtcpBye() :RtcpPacketBase(PT_RTCP_BYE) { } RtcpBye::RtcpBye( uint8_t uiVersion, bool uiPadding, uint8_t uiTypeSpecific, uint16_t uiLengthInWords ) :RtcpPacketBase(uiVersion, uiPadding, uiTypeSpecific, PT_RTCP_BYE, uiLengthInWords) { } RtcpBye::RtcpBye( uint32_t uiSSRC ) :RtcpPacketBase(PT_RTCP_BYE) { addSSRC(uiSSRC); } void RtcpBye::addSSRC( uint32_t uiSSRC ) { m_vSSRCs.push_back(uiSSRC); // update base field setTypeSpecific(m_vSSRCs.size()); // update length field recalculateLength(); //setLength( getLength() + 1); } std::uint32_t RtcpBye::getPadding() const { return ( 4 - (m_sOptionalReasonForLeaving.size() % 4 )); } void RtcpBye::recalculateLength() { uint32_t uiSizeWords = 0; if (!m_sOptionalReasonForLeaving.empty()) { uiSizeWords = m_sOptionalReasonForLeaving.size() >> 2; if (getPadding() > 0) ++uiSizeWords; } setLength( m_vSSRCs.size() + uiSizeWords); } void RtcpBye::writeTypeSpecific( OBitStream& ob ) const { std::for_each(m_vSSRCs.begin(), m_vSSRCs.end(), [&ob](uint32_t uiSSRC) { ob.write(uiSSRC, 32); } ); if (!m_sOptionalReasonForLeaving.empty()) { ob.write( m_sOptionalReasonForLeaving.length(), 8); std::for_each(m_sOptionalReasonForLeaving.begin(), m_sOptionalReasonForLeaving.end(), [&ob](char c) { ob.write(c, 8); } ); // padding for (size_t i = 0; i < getPadding(); ++i) { ob.write(0, 8); } } } void RtcpBye::readTypeSpecific( IBitStream& ib ) { for (size_t i = 0; i < getTypeSpecific(); ++i) { uint32_t uiSSRC = 0; ib.read(uiSSRC, 32); m_vSSRCs.push_back(uiSSRC); } uint8_t uiLength = 0; ib.read(uiLength, 8); uint8_t buffer[256]; buffer[uiLength] = '\0'; for (size_t i = 0; i < uiLength; ++i) { ib.read(buffer[i], 8); } m_sOptionalReasonForLeaving = std::string(reinterpret_cast<const char*>(buffer), uiLength); // padding uint8_t dummy = 0; for (size_t i = 0; i < getPadding(); ++i) { ib.read(dummy, 8); } } } }
25.609034
190
0.677514
miseri
8e6e46a878037d2cf92101889bcb17206de8194d
1,516
cpp
C++
mandelbrot/input.cpp
matt360/Mandelbrot-AMP
4821844ba30ae33290442f25b65eff983ffa9e0f
[ "MIT" ]
null
null
null
mandelbrot/input.cpp
matt360/Mandelbrot-AMP
4821844ba30ae33290442f25b65eff983ffa9e0f
[ "MIT" ]
null
null
null
mandelbrot/input.cpp
matt360/Mandelbrot-AMP
4821844ba30ae33290442f25b65eff983ffa9e0f
[ "MIT" ]
1
2021-04-11T21:52:04.000Z
2021-04-11T21:52:04.000Z
// Input class // Stores current keyboard and mouse state include, pressed keys, mouse button pressed and mouse position. // @author Paul Robertson #include "Input.h" void Input::SetKeyDown(unsigned char key) { keys[key] = true; } void Input::SetKeyUp(unsigned char key) { keys[key] = false; } bool Input::isKeyDown(int key) { return keys[key]; } void Input::SetSpecialKeyDown(unsigned char key) { specialKeys[key] = true; } void Input::SetSpecialKeyUp(unsigned char key) { specialKeys[key] = false; } bool Input::isSpecialKeyDown(int key) { return specialKeys[key]; } void Input::setMouseX(int pos) { mouse.x = pos; } void Input::setMouseY(int pos) { mouse.y = pos; } void Input::setMousePos(int ix, int iy) { mouse.x = ix; mouse.y = iy; } int Input::getMouseX() { return mouse.x; } int Input:: getMouseY() { return mouse.y; } void Input::setLeftMouseButton(bool b) { mouse.left = b; } bool Input::isLeftMouseButtonPressed() { return mouse.left; } void Input::setRightMouseButton(bool b) { mouse.right = b; } bool Input::isRightMouseButtonPressed() { return mouse.right; } void Input::setMiddleMouseButton(bool b) { mouse.middle = b; } bool Input::isMiddleMouseButtonPressed() { return mouse.middle; } void Input::setScrollUpMouseWheel(bool b) { mouse.scroll_up = b; } bool Input::isScrollUpMouseWheel() { return mouse.scroll_up; } void Input::setScrollDownMouseWheel(bool b) { mouse.scroll_down = b; } bool Input::isScrollDownMouseWheel() { return mouse.scroll_down; }
13.415929
106
0.712401
matt360
8e6eee3ebc8556f93fa2d0f808e3e236de4a880a
2,304
cpp
C++
VCMP API Extended/VCMP API Extended/Marker.cpp
NicusorN5/VCMP-API-Extender
42f1fd502cd33d165959eadf79ab3786795bc0f9
[ "Apache-2.0" ]
1
2019-09-15T10:45:37.000Z
2019-09-15T10:45:37.000Z
VCMP API Extended/VCMP API Extended/Marker.cpp
NicusorN5/VCMP-API-Extender
42f1fd502cd33d165959eadf79ab3786795bc0f9
[ "Apache-2.0" ]
null
null
null
VCMP API Extended/VCMP API Extended/Marker.cpp
NicusorN5/VCMP-API-Extender
42f1fd502cd33d165959eadf79ab3786795bc0f9
[ "Apache-2.0" ]
null
null
null
#include "pch.h" #include "Marker.h" bool VCMP::Marker::CreatedMarkers[128] = { false }; VCMP::Marker::Marker(int world, Vector3 position, int scale, VCMP::Color color, int Sprite) { int valid_id = 0; for (int i = 0; i < 128; i++) { if (this->CreatedMarkers[i] == false) { this->CreatedMarkers[i] = true; valid_id = i; break; } } api->CreateCoordBlip(valid_id, world, position.x, position.y, position.z, scale, color.ToUint(), Sprite); } bool VCMP::Marker::Valid() { return this->CreatedMarkers[this->ID]; } void VCMP::Marker::Delete() { this->CreatedMarkers[this->ID] = false; api->DestroyCoordBlip(this->ID); } int VCMP::Marker::World() { if (this->Valid()) { int* useless = nullptr, * a = nullptr; float* useless2 = nullptr; unsigned* useless3 = nullptr; api->GetCoordBlipInfo(this->ID, a, useless2, useless2, useless2, useless, useless3, useless); return *a; } return -1; } VCMP::Vector3 VCMP::Marker::Position() { if (this->Valid()) { float* x = nullptr, * y = nullptr, * z = nullptr; int* useless = nullptr; unsigned* useless2 = nullptr; api->GetCoordBlipInfo(this->ID, useless, x, y, z, useless, useless2, useless); return Vector3(*x, *y, *z); } return Vector3(); } int VCMP::Marker::Scale() { if (this->Valid()) { int* scale = nullptr, * useless = nullptr; unsigned* useless2= nullptr; float* useless3= nullptr; api->GetCoordBlipInfo(this->ID, useless, useless3, useless3, useless3, scale, useless2, useless); return *scale; } return 0; } VCMP::Color VCMP::Marker::Color() { if (this->Valid()) { unsigned* color=nullptr; int* useless=nullptr; float* useless2=nullptr; api->GetCoordBlipInfo(this->ID, useless, useless2, useless2, useless2, useless, color, useless); return Color::FromUInt(*color); } return Color(); } int VCMP::Marker::Sprite() { if (this->Valid()) { int* sprite = nullptr, * useless = nullptr; float* useless1=nullptr; unsigned* useless2= nullptr; api->GetCoordBlipInfo(this->ID, useless, useless1, useless1, useless1, useless, useless2, sprite); return *sprite; } return 0; } bool VCMP::Marker::operator==(Marker a) { return (a.ID == this->ID); } bool VCMP::Marker::operator!=(Marker a) { return (a.ID != this->ID); } VCMP::Marker::operator bool() { return (ID >= 0); }
20.756757
106
0.657552
NicusorN5
8e775a5ab2e0b12a5108ae9b6cc1ff352e5a1fb2
1,210
cpp
C++
device/lib/Firmware/Firmware.cpp
zostay/Mysook
3611ddf0a116d18ebc58a3050f9fe35c2684c906
[ "Artistic-2.0" ]
3
2019-06-30T04:15:18.000Z
2019-12-19T17:32:07.000Z
device/lib/Firmware/Firmware.cpp
zostay/Mysook
3611ddf0a116d18ebc58a3050f9fe35c2684c906
[ "Artistic-2.0" ]
null
null
null
device/lib/Firmware/Firmware.cpp
zostay/Mysook
3611ddf0a116d18ebc58a3050f9fe35c2684c906
[ "Artistic-2.0" ]
null
null
null
#include <Firmware.h> #include <cstdarg> #include <climits> #ifndef ARDUINO #include <sys/time.h> // precision clock #include <errno.h> #include <cstdio> #include <cstring> #endif using namespace mysook; #ifdef ARDUINO unsigned long mysook::get_micros() { return micros(); } #else unsigned long mysook::get_micros() { struct timeval src; if (gettimeofday(&src, NULL) == 0) { return src.tv_sec * 1000000 + src.tv_usec; } else { //logf_ln("Failed making micros from gettimeofday(): %s", strerror(errno)); // Bad Stuff return 0ul; } } #endif//ARDUINO void TickingVariableTimer::next_tick_after(unsigned long wait) { if (ULONG_MAX - previous_tick < wait) { next_tick_at(wait - (ULONG_MAX - previous_tick), previous_tick); } else { next_tick_at(previous_tick + wait); } } // checks if tick_speed() micros have passed, accounting for rollovers, which // happen every 4,294.967296 seconds. bool TickingVariableTimer::ready_for_tick(unsigned long now) { if ((now >= next_tick && now <= rollover)) { previous_tick = next_tick; next_tick_after(tick_speed()); return true; } return false; }
22.407407
83
0.657025
zostay
8e7846f631db48709903f75a750af8d55b832781
1,265
hpp
C++
source/controller/State.hpp
Godlike/Xanthus
f35a5fd8b7aa974f5fcb37bf5bb8df3f2602847d
[ "MIT" ]
null
null
null
source/controller/State.hpp
Godlike/Xanthus
f35a5fd8b7aa974f5fcb37bf5bb8df3f2602847d
[ "MIT" ]
null
null
null
source/controller/State.hpp
Godlike/Xanthus
f35a5fd8b7aa974f5fcb37bf5bb8df3f2602847d
[ "MIT" ]
null
null
null
#ifndef XANTHUS_CONTROLLER_STATE_HPP #define XANTHUS_CONTROLLER_STATE_HPP #include "entity/Entity.hpp" #include "entity/World.hpp" #include "component/PositionComponent.hpp" #include "component/DummyComponent.hpp" #include "system/Skeleton.hpp" #include <unicorn/utility/templates/Singleton.hpp> #include <memory> namespace xanthus { namespace controller { class State : public unicorn::utility::templates::Singleton<State> { public: void Init(entity::World& world); void SelectNext(); entity::Entity const& GetSelected() const { return m_selectedEntity; } void ResolveProjectile(entity::Entity projectile); private: friend class unicorn::utility::templates::Singleton<State>; State(); State(const State& other) = delete; State& operator=(const State& other) = delete; ~State() = default; struct DummySystem : public system::Skeleton<component::PositionComponent, component::DummyComponent> { DummySystem(entity::World& world); ~DummySystem() = default; using Skeleton<component::PositionComponent, component::DummyComponent>::GetEntities; }; std::unique_ptr<DummySystem> m_pDummySystem; entity::Entity m_selectedEntity; }; } } #endif // XANTHUS_CONTROLLER_STATE_HPP
22.192982
105
0.730435
Godlike
8e791be34046e5c937386e7f7026f35fcd71a39c
3,936
cpp
C++
Unfalse Engine/Source Code/GameObject.cpp
Sauko22/Unfalse-Engine
6fe308c53a05e1bb62eecb35bba6471a29a38404
[ "MIT" ]
1
2020-12-15T11:42:20.000Z
2020-12-15T11:42:20.000Z
Unfalse Engine/Source Code/GameObject.cpp
Sauko22/Unfalse-Engine
6fe308c53a05e1bb62eecb35bba6471a29a38404
[ "MIT" ]
null
null
null
Unfalse Engine/Source Code/GameObject.cpp
Sauko22/Unfalse-Engine
6fe308c53a05e1bb62eecb35bba6471a29a38404
[ "MIT" ]
null
null
null
#include "Globals.h" #include "Application.h" #include "GameObject.h" #include "p2Defs.h" GameObject::GameObject(GameObject* parent) { parentGameObject = parent; if (parentGameObject != nullptr) { parentGameObject->children_list.push_back(this); } name = " "; fbxname = " "; pngname = " "; index_name = 0; normals_name = 0; vertex_name = 0; faces_name = 0; texturescoords_name = 0; actualtexgl = 0; guid = 0; empty_GameObjects = 0; objSelected = false; ObjrenderActive = true; Objdelete = false; ObjtexActive = false; EmptyChild = false; } GameObject::~GameObject() { for (int i = 0; i < component_list.size(); i++) { if (component_list[i] != nullptr) { delete component_list[i]; component_list[i] = nullptr; } } component_list.clear(); } void GameObject::update() { // Update components for (int i = 0; i < component_list.size(); i++) { if (component_list[i]->type == Component::compType::MESH) { CompMesh* mesh = (CompMesh*)this->GetComponent(Component::compType::MESH); if (App->renderer3D->camera_culling != nullptr) { if (App->renderer3D->culling == true) { if (App->renderer3D->ContainsAaBox_2(aabb) == true) { mesh->update(); } } else { mesh->update(); } } else { mesh->update(); } } else { component_list[i]->update(); } } if (component_list.empty() == false) { UpdateAABB(); } } void GameObject::Inspector() { ImVec2 buttonSize = { 100.f, 20.f }; std::string name = " Scene Camera"; if (this->name != name) { ImGui::Checkbox("DeleteObj", &Objdelete); } if(ImGui::Button("Empty Child", buttonSize)) CreateEmptyChild(); ImGui::Checkbox("ActiveObj", &ObjrenderActive); ImGui::SameLine(); ImGui::Text("%s", name.c_str()); // Update components for (int i = 0; i < component_list.size(); i++) { component_list[i]->inspector(); } } void GameObject::CreateEmptyChild() { empty_GameObjects++; std::string obj = std::to_string(empty_GameObjects); std::string name = "Empty_Child"; name.append(obj); empty_GameObject = new GameObject(App->scene_intro->SelectedGameObject); empty_GameObject->name.append("Empty_Child_") += std::to_string(empty_GameObjects); empty_GameObject->AddComponent(Component::compType ::TRANSFORM); } void GameObject::UpdateAABB() { CompMesh* mesh = (CompMesh*)GetComponent(Component::compType::MESH); CompTransform* transform = (CompTransform*)GetComponent(Component::compType::TRANSFORM); if (mesh != nullptr) { App->renderer3D->GenerateAABB(mesh); obb = mesh->bbox; obb.Transform(transform->global_transform); aabb.SetNegativeInfinity(); aabb.Enclose(obb); mesh->bbox = aabb; if(App->UI->bounding)App->renderer3D->GenerateLines(mesh); } } Component* GameObject::AddComponent(Component::compType type) { Component* ret = nullptr; switch (type) { case Component::compType::TRANSFORM: ret = new CompTransform(this); break; case Component::compType::MESH: ret = new CompMesh(this); break; case Component::compType::MATERIAL: ret = new CompMaterial(this); break; case Component::compType::CAMERA: ret = new CompCamera(this); break; } component_list.push_back(ret); return ret; } Component* GameObject::AddTempComponent(Component::compType type) { Component* ret = nullptr; switch (type) { case Component::compType::TRANSFORM: ret = new CompTransform(this); break; case Component::compType::MESH: ret = new CompMesh(this); break; case Component::compType::MATERIAL: ret = new CompMaterial(this); break; case Component::compType::CAMERA: ret = new CompCamera(this); break; } tempcomponent_list.push_back(ret); return ret; } Component* GameObject::GetComponent(Component::compType type) { Component* ret = nullptr; for (int i = 0; i < component_list.size(); i++) { if (type == component_list[i]->type) return component_list[i]; } return ret; }
19.485149
89
0.67378
Sauko22
8e816ba0b110bfadad08284948fcd98402a28e8b
7,400
cpp
C++
Source/FlightSimulator/Private/Components/RadarComponent.cpp
Lynnvon/FlightSimulator
2dca6f8364b7f4972a248de3dbc3a711740f5ed4
[ "MIT" ]
1
2022-02-03T08:29:35.000Z
2022-02-03T08:29:35.000Z
Source/FlightSimulator/Private/Components/RadarComponent.cpp
Lynnvon/FlightSimulator
2dca6f8364b7f4972a248de3dbc3a711740f5ed4
[ "MIT" ]
null
null
null
Source/FlightSimulator/Private/Components/RadarComponent.cpp
Lynnvon/FlightSimulator
2dca6f8364b7f4972a248de3dbc3a711740f5ed4
[ "MIT" ]
null
null
null
//MIT License // //Copyright(c) 2021 HaiLiang Feng // //QQ : 632865163 //Blog : https ://www.cnblogs.com/LynnVon/ // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this softwareand 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 noticeand 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 "RadarComponent.h" #include "Math/UnrealMathUtility.h" #include "FlightBlueprintFunctionLibrary.h" #include "Kismet/KismetMathLibrary.h" #include "Kismet/KismetSystemLibrary.h" #include <ADS_BOutComponent.h> // Sets default values for this component's properties URadarComponent::URadarComponent() { // Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features // off to improve performance if you don't need them. // ... ScanSpeed = 5; PrimaryComponentTick.bCanEverTick = true; } // Called when the game starts void URadarComponent::BeginPlay() { Super::BeginPlay(); // ... UWorld* world = GetWorld(); if (world) { world->GetTimerManager().SetTimer(SearchTimer, this, &URadarComponent::TickSearch, ScanSpeed, true, 0); } } // Called every frame void URadarComponent::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) { Super::TickComponent(DeltaTime, TickType, ThisTickFunction); UpdateLockTarget(); if (GFlightGlobals && GFlightGlobals->bDrawDebug) { Debug(); } } void URadarComponent::TickSearch() { if (GFlightGlobals && GFlightGlobals->GetADSStation()) { Search(); } } void URadarComponent::Search() { FVector SelfPos = GetOwner()->GetActorLocation(); EndOfScanned(); SearchResults.Reset(); ScanActors.Reset(); for (FTransformFlightProperty flightData : GFlightGlobals->GetADSStation()->GetAllFlightData()) { if (flightData.ID == GetOwner()->GetUniqueID()) { //排除自己 continue; } if (flightData.ActorType == EActorType::Static) { //排除掉地面设置 continue; } //敌我识别 if (GetOwner()) { UADS_BOutComponent* ads = Cast<UADS_BOutComponent>(GetOwner()->GetComponentByClass(UADS_BOutComponent::StaticClass())); if (ads && flightData.TeamNum == ads->GetTeamNum()) { //排除掉友军 continue; } } //排除掉红外干扰弹 if (flightData.CounterType == ECounterMeasureType::Flare) { continue; } //排除掉接近率相同的 //因为模拟的是多普勒雷达 float angle = UFlightBlueprintFunctionLibrary::CalcAngleWithTwoLine(flightData.Position - GetOwner()->GetActorLocation(), flightData.Velocity); //UE_LOG(LogFlight, Warning, TEXT("angle=%s"), *FString::SanitizeFloat(angle)); if (UKismetMathLibrary::NearlyEqual_FloatFloat(angle, 90, 5)) { continue; } if (UFlightBlueprintFunctionLibrary::CheckIfInRangeAndAngle(GetOwner(), flightData.Position, VerticalAngle, HorizontalAngle, ScanRange)) { //视角内 //检查与目标之间是否有阻挡 向目标方向发射射线,目标也可以得知自己被雷达照射到 bool bBlocked = false; TScriptInterface<IIRadarWarningInterface> rwi = UFlightBlueprintFunctionLibrary::GetRadarWarningActorWithWhetherBlocked(GetOwner(), SelfPos, flightData.Position, COLLISION_RADAR, bBlocked); if (rwi) { rwi->Execute_ToBeScanned(rwi.GetObject()); ScanActors.Add(rwi); } if (!bBlocked) { SearchResults.Add(flightData); } } } if (LockedTarget.IsValid() && !SearchResults.Contains(LockedTarget)) { //当前锁定的目标不在搜索结果内了 解除锁定 UnLock(); } } void URadarComponent::EndOfScanned() { for (TScriptInterface<IIRadarWarningInterface> WarningInterface : ScanActors) { WarningInterface->Execute_EndOfBeingScanned(WarningInterface.GetObject()); } } void URadarComponent::UpdateLockTarget() { CHECK_FALSE_RETURN(LockedTarget.IsValid()); CHECK_FALSE_RETURN(GFlightGlobals); CHECK_FALSE_RETURN(GFlightGlobals->GetADSStation()); for (FTransformFlightProperty property : GFlightGlobals->GetADSStation()->GetAllFlightData()) { if (property.ID == LockedTarget.ID) { LockedTarget.Position = property.Position; LockedTarget.Velocity = property.Velocity; } } } void URadarComponent::Lock() { if (SearchResults.Num() > 0) { LockedTarget = SearchResults[0]; UpdateLockTarget(); FVector SelfPos = GetOwner()->GetActorLocation(); TScriptInterface<IIRadarWarningInterface> rwi = UFlightBlueprintFunctionLibrary::GetRadarWarningActor(GetOwner(), SelfPos, LockedTarget.Position, COLLISION_RADAR); if (rwi) { rwi->Execute_ToBeLocked(rwi.GetObject()); } } } void URadarComponent::UnLock() { if (LockedTarget.IsValid()) { FVector SelfPos = GetOwner()->GetActorLocation(); TScriptInterface<IIRadarWarningInterface> rwi = UFlightBlueprintFunctionLibrary::GetRadarWarningActorIgnoreBlock(GetOwner(), SelfPos, LockedTarget.Position, COLLISION_RADAR); if (rwi) { rwi->Execute_EndOfBeingLocked(rwi.GetObject()); } } LockedTarget.Reset(); } void URadarComponent::Debug() { if (GetSearchResults().Num() > 0 && GetOwner()) { //搜索到目标 if (LockedTarget.IsValid()) { UKismetSystemLibrary::DrawDebugCone(this, GetOwner()->GetActorLocation(), GetOwner()->GetActorForwardVector(), ScanRange, FMath::DegreesToRadians(HorizontalAngle), FMath::DegreesToRadians(VerticalAngle), 12, FLinearColor::Blue, 0, 0 ); } else { UKismetSystemLibrary::DrawDebugCone(this, GetOwner()->GetActorLocation(), GetOwner()->GetActorForwardVector(), ScanRange, FMath::DegreesToRadians(HorizontalAngle), FMath::DegreesToRadians(VerticalAngle), 12, FLinearColor::Red, 0, 0 ); } } else { //没有搜索到 UKismetSystemLibrary::DrawDebugCone(this, GetOwner()->GetActorLocation(), GetOwner()->GetActorForwardVector(), ScanRange, FMath::DegreesToRadians(HorizontalAngle), FMath::DegreesToRadians(VerticalAngle), 12, FLinearColor::White, 0, 0 ); } }
26.909091
198
0.655135
Lynnvon
8e8e2bae17489357ecec61aa0d0cd997db2261e4
3,464
cpp
C++
SensorRecorder/src/record.cpp
SorcererX/SepiaCore
4d7782b04ca6a8f94668bf298e07520d52de873d
[ "BSD-2-Clause" ]
3
2015-01-27T08:52:36.000Z
2018-01-31T07:17:28.000Z
SensorRecorder/src/record.cpp
SorcererX/SepiaCore
4d7782b04ca6a8f94668bf298e07520d52de873d
[ "BSD-2-Clause" ]
4
2015-03-11T06:13:29.000Z
2017-02-12T13:08:28.000Z
SensorRecorder/src/record.cpp
SorcererX/SepiaCore
4d7782b04ca6a8f94668bf298e07520d52de873d
[ "BSD-2-Clause" ]
null
null
null
/* Copyright (c) 2012-2015, Kai Hugo Hustoft Endresen <kai.endresen@gmail.com> 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 "record.h" #include <fstream> #include <string> #include <iostream> #include <sstream> #include <iomanip> #include <thread> #include <sepia/reader.h> #include <sys/time.h> #include <functional> Record::Record( const std::string groupname, const std::string filename ) { m_shared = new sepia::Reader( groupname ); m_fileList = filename; } void Record::start() { m_thread = new std::thread( std::bind( &Record::own_thread, this ) ); } void Record::own_thread() { std::ofstream list; list.open( m_fileList ); if( !list.is_open() ) { std::cerr << "ERROR: " << "unable to open " << m_fileList << "." << std::endl; return ; } std::ofstream output; struct timeval tp; gettimeofday( &tp, NULL ); std::stringstream ss; std::string basestr = std::to_string( tp.tv_sec ); int counter = 0; while( !m_terminate ) { m_shared->update(); if( counter % 100 == 0 ) { if( output.is_open() ) { output.close(); } ss.str(""); ss.clear(); ss << basestr; ss << "_"; ss << std::setfill( '0' ); ss << std::setw( 10 ); ss << counter << ".bin"; std::string filename = ss.str(); output.open( filename, std::fstream::out | std::fstream::app ); std::cout << std::endl << "Writing to: " << filename << " " << std::flush; } output.write( (char*) m_shared->getGroupHeader(), sizeof( sepia::Stream::group_header_t ) ); for( size_t i = 0; i < m_shared->getGroupHeader()->count; i++ ) { output.write( (char*) m_shared->getHeader( i ), sizeof( sepia::Stream::image_header_t ) ); } for( size_t i = 0; i < m_shared->getGroupHeader()->count; i++ ) { output.write( (char*) m_shared->getAddress( i ), m_shared->getHeader( i )->size ); } std::cout << "." << std::flush; counter++; } if( output.is_open() ) { output.close(); } }
29.862069
102
0.62933
SorcererX
8e9034f98b0b707e14e2a24921a126893dd780f9
204
cpp
C++
src/beatwave/drumsetexception.cpp
rexim/beatwave
d88db6d9f2f5def37d185e74870c5908beffc753
[ "MIT" ]
20
2015-12-19T16:17:01.000Z
2022-01-19T18:40:10.000Z
src/beatwave/drumsetexception.cpp
rexim/beatwave
d88db6d9f2f5def37d185e74870c5908beffc753
[ "MIT" ]
99
2015-12-19T16:20:40.000Z
2017-03-03T15:47:23.000Z
src/beatwave/drumsetexception.cpp
rexim/beatwave
d88db6d9f2f5def37d185e74870c5908beffc753
[ "MIT" ]
7
2015-12-21T09:41:08.000Z
2016-09-27T15:20:40.000Z
#include <beatwave/drumsetexception.hpp> DrumSetException::DrumSetException(const char *message): m_message(message) {} const char *DrumSetException::what() const noexcept { return m_message; }
18.545455
56
0.759804
rexim
8e90fccc05abcdf44676ba32d6d3d092e0bfde6a
1,073
hpp
C++
source/plc/include/document/NON_FRACTIONAL.hpp
dlin172/Plange
4b36a1225b2263bc8d38a6d1cc9b50c3d4b58e04
[ "BSD-3-Clause" ]
null
null
null
source/plc/include/document/NON_FRACTIONAL.hpp
dlin172/Plange
4b36a1225b2263bc8d38a6d1cc9b50c3d4b58e04
[ "BSD-3-Clause" ]
null
null
null
source/plc/include/document/NON_FRACTIONAL.hpp
dlin172/Plange
4b36a1225b2263bc8d38a6d1cc9b50c3d4b58e04
[ "BSD-3-Clause" ]
null
null
null
// This file was generated using Parlex's cpp_generator #ifndef INCLUDED_NON_FRACTIONAL_HPP #define INCLUDED_NON_FRACTIONAL_HPP #include <optional> #include <variant> #include <vector> #include "erased.hpp" #include "parlex/detail/abstract_syntax_tree.hpp" #include "parlex/detail/builtins.hpp" #include "parlex/detail/document.hpp" #include "plange_grammar.hpp" namespace plc { struct NON_NEG_NON_FRACTIONAL; struct NON_FRACTIONAL { std::optional<parlex::detail::document::text<literal_0x2D_t>> field_1; erased<NON_NEG_NON_FRACTIONAL> field_2; explicit NON_FRACTIONAL( std::optional<parlex::detail::document::text<literal_0x2D_t>> && field_1, erased<NON_NEG_NON_FRACTIONAL> && field_2) : field_1(std::move(field_1)), field_2(std::move(field_2)) {} NON_FRACTIONAL(NON_FRACTIONAL const & other) = default; NON_FRACTIONAL(NON_FRACTIONAL && move) = default; static NON_FRACTIONAL build(parlex::detail::ast_node const & n); static parlex::detail::state_machine const & state_machine(); }; } // namespace plc #endif //INCLUDED_NON_FRACTIONAL_HPP
23.326087
180
0.7726
dlin172
8e94df95cffb1169b77505a79f33e9e8dd0fc677
1,550
cpp
C++
ImportScanner.cpp
alin1337/simple-anticheat
e4f5e563238d6fa24346b139da8ad59e56aefe0b
[ "WTFPL" ]
8
2020-04-05T18:00:40.000Z
2022-02-09T23:24:45.000Z
ImportScanner.cpp
alin1337/simple-anticheat
e4f5e563238d6fa24346b139da8ad59e56aefe0b
[ "WTFPL" ]
null
null
null
ImportScanner.cpp
alin1337/simple-anticheat
e4f5e563238d6fa24346b139da8ad59e56aefe0b
[ "WTFPL" ]
1
2020-08-03T11:14:36.000Z
2020-08-03T11:14:36.000Z
#include <Windows.h> #include <string> #include <vector> #include "ScannerInterface.h" #include "ImportScanner.h" void ImportScanner::AddItem(std::string name, void* pData, int nDataSize) { tImportData data; memset(&data, 0, sizeof(tImportData)); data.strName = name; data.nSize = nDataSize; #ifdef _WIN32 data.nOffset = (DWORD)pData; #elif _WIN64 data.nOffset = (UINT64)pData; #endif memcpy_s(&data.Data, MAX_IMPORT_DATA_SIZE, pData, nDataSize); }; void ImportScanner::ProtectDefaultImports() { AddItem("GetTickCount", GetTickCount, 8); //used by all Speed Hacks AddItem("GetTickCount64", GetTickCount64, 8); //used by all Speed Hacks AddItem("QueryPerformanceCounter", QueryPerformanceCounter, 8); //used by all Speed Hacks //AddItem("RtlQueryPerformanceCounter", RtlQueryPerformanceCounter, 8); //Kernel function, can't hook from userspace. AddItem("send", send, 8); //used by packet capture/editors AddItem("recv", recv, 8); //used by packet capture/editors } void ImportScanner::Process() { if (!m_bRun) return; for (auto& it : m_pVecCDB) { if (it.nFailCount > 10) { //Something is wrong with this import //try restore? //check for any JMP/Trampoline? } if (_memicmp(it.Data, (LPVOID)it.nOffset, it.nSize) != 0) { CheatReport(); it.nFailCount++; } } } void ImportScanner::OnRecvCheatDBPacket(ScannerInterface::eScannerType type, std::vector<ScannerInterface::CheatDefinition> vecData) { if (type != m_ScannerType) return; for (auto& it : vecData) { OutputDebugString(it.pData); } }
24.21875
132
0.718065
alin1337
8e953cb7e94eceb91e1e86be5acd169226709992
5,326
cpp
C++
tests/core_tests/random_helper.cpp
Virie/Virie
fc5ad5816678b06b88d08a6842e43d4205915b39
[ "MIT" ]
1
2021-03-07T13:26:43.000Z
2021-03-07T13:26:43.000Z
tests/core_tests/random_helper.cpp
Virie/Virie
fc5ad5816678b06b88d08a6842e43d4205915b39
[ "MIT" ]
null
null
null
tests/core_tests/random_helper.cpp
Virie/Virie
fc5ad5816678b06b88d08a6842e43d4205915b39
[ "MIT" ]
null
null
null
// Copyright (c) 2014-2020 The Virie Project // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chaingen.h" #include "random_helper.h" std::string get_random_text(size_t len) { static const char text_chars[] = "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "0123456789" "~!@#$%^&*()-=_+\\/?,.<>|{}[]`';:\" "; static const uint8_t text_chars_size = sizeof text_chars - 1; // to avoid '\0' std::string result; if (len < 1) return result; result.resize(len); char* result_buf = &result[0]; uint8_t* rnd_indices = new uint8_t[len]; crypto::generate_random_bytes(len, rnd_indices); size_t n = len / 4, i; for (i = 0; i < n; ++i) { result_buf[4 * i + 0] = text_chars[rnd_indices[4 * i + 0] % text_chars_size]; result_buf[4 * i + 1] = text_chars[rnd_indices[4 * i + 1] % text_chars_size]; result_buf[4 * i + 2] = text_chars[rnd_indices[4 * i + 2] % text_chars_size]; result_buf[4 * i + 3] = text_chars[rnd_indices[4 * i + 3] % text_chars_size]; } for (size_t j = i * 4; j < len; ++j) { result_buf[j] = text_chars[rnd_indices[j] % text_chars_size]; } delete[] rnd_indices; return result; } //------------------------------------------------------------------------------ bool random_state_manupulation_test() { // This test checks that random generator can be manipulated by random_helper routines in predictable way. // NOTE: If the test fails, it's most likely that random state permutation procedure was changed OR the state can't be correctly stored/loaded. static const uint64_t my_own_random_seed = 4669201609102990671; static const char* my_random_str = "18b79ebb56744e9bafa462631c6f7d760af2b788"; static const size_t rnd_buf_len = 20; uint64_t first_random_after_state_saved = 0; { random_state_test_restorer rstr; // <- here random state is saved first_random_after_state_saved = crypto::rand<uint64_t>(); random_state_test_restorer::reset_random(my_own_random_seed); // random seeded, entering deterministic mode... std::string rnd_buf(rnd_buf_len, '\x00'); for (size_t i = 0; i < rnd_buf_len; ++i) rnd_buf[i] = crypto::rand<char>(); std::string hex = epee::string_tools::buff_to_hex_nodelimer(rnd_buf); CHECK_AND_ASSERT_MES(hex == my_random_str, false, "Incorrect random data after seeding. Expected: " << my_random_str << " Fetched: " << hex); // here rstr dtor is called and random state should be restored } // make sure random state is correctly restored uint64_t first_random_after_state_restored = crypto::rand<uint64_t>(); CHECK_AND_ASSERT_MES(first_random_after_state_saved == first_random_after_state_restored, false, "Core random generator state wasn't restored correctly"); return true; } bool check_random_evenness(size_t modulus = 11, size_t count = 10000, double allowed_deviation = 0.05) { std::vector<size_t> m; m.resize(modulus); for (size_t i = 0; i < count; ++i) { size_t r = crypto::rand<size_t>() % modulus; ++m[r]; } double mean = 0; double variance = 0; for (size_t i = 0; i < modulus; ++i) { mean += static_cast<double>(i)* m[i] / count; variance += static_cast<double>(i)* i * m[i] / count; } variance -= mean * mean; double estimated_mean = (static_cast<double>(modulus)-1) / 2; double estimated_variance = (static_cast<double>(modulus)* modulus - 1) / 12; LOG_PRINT_L0("Random test for modulus " << modulus << ", trials count " << count << std::endl << "Estimated mean: " << std::fixed << std::setw(10) << std::setprecision(5) << estimated_mean << " Mean: " << std::fixed << std::setw(10) << std::setprecision(5) << mean << std::endl << "Estimated variance: " << std::fixed << std::setw(10) << std::setprecision(5) << estimated_variance << " Variance: " << std::fixed << std::setw(10) << std::setprecision(5) << variance); CHECK_AND_ASSERT_MES(fabs(mean - estimated_mean) < allowed_deviation * estimated_mean, false, "Mean deviation is more than " << allowed_deviation); CHECK_AND_ASSERT_MES(fabs(variance - estimated_variance) < allowed_deviation * estimated_variance, false, "Variance deviation is more than " << allowed_deviation); return true; } bool random_evenness_test() { bool r = true; r = r & check_random_evenness(5, 10000); r = r & check_random_evenness(11, 11000); r = r & check_random_evenness(37, 50000); r = r & check_random_evenness(97, 97000); r = r & check_random_evenness(113, 113000); return r; } bool get_random_text_test() { random_state_test_restorer rstr; // to restore random generator state afterwards random_state_test_restorer::reset_random(0); // to make the test determinictic TIME_MEASURE_START(time_total); size_t max_len = 16 * 1024; size_t trials_count = 500; for (size_t i = 0; i < trials_count; ++i) { size_t sz = crypto::rand<size_t>() % max_len; std::string r = get_random_text(sz); CHECK_AND_ASSERT_MES(r.size() == sz, false, "get_random_text(" << sz << ") returned " << r.size() << " bytes:" << ENDL << r); } TIME_MEASURE_FINISH(time_total); LOG_PRINT_L0("Random text test: trials: " << trials_count << ", total time: " << time_total << " ms."); return true; }
38.316547
195
0.673489
Virie
8e9d94ef609de9b30421ed6cc3a1295d2c3390b1
1,356
hpp
C++
include/streamer/streamer_defines.hpp
ida-zrt/thermalvis
36a6ba0d12ab91097435630586e3eb760130582c
[ "BSD-3-Clause" ]
109
2015-02-03T23:30:59.000Z
2022-02-22T03:24:36.000Z
include/streamer/streamer_defines.hpp
adaniy/thermalvis
782f71b5fbde033d226d11b8d0c994fc83d10d98
[ "BSD-3-Clause" ]
9
2015-02-19T05:46:36.000Z
2021-11-02T14:00:49.000Z
include/streamer/streamer_defines.hpp
adaniy/thermalvis
782f71b5fbde033d226d11b8d0c994fc83d10d98
[ "BSD-3-Clause" ]
59
2015-11-05T11:51:55.000Z
2022-03-11T06:36:57.000Z
/*! \file streamer_defines.hpp * \brief Defines for streamer node configuration. */ #ifndef STREAMER_DEFINES_H #define STREAMER_DEFINES_H #define NO_FILTERING 0 #define GAUSSIAN_FILTERING 1 #define BILATERAL_FILTERING 2 #define DETECTOR_MODE_RAW 0 #define DETECTOR_MODE_LUM 1 #define DETECTOR_MODE_INS 2 #define DETECTOR_MODE_RAD 3 #define DETECTOR_MODE_TMP 4 #define DENOISING_MODE_NONE 0 #define DENOISING_MODE_X 1 #define USB_MODE_16 1 #define USB_MODE_8 2 #define NORM_MODE_FULL_STRETCHING 0 #define NORM_MODE_EQUALIZATION 1 #define NORM_MODE_CENTRALIZED 2 #define NORM_MODE_FIXED_TEMP_RANGE 3 #define NORM_MODE_FIXED_TEMP_LIMITS 4 #define NORM_MODE_NONE 5 #define NORM_MODE_DEFAULT 6 #define CONFIG_MAP_CODE_GRAYSCALE 0 #define CONFIG_MAP_CODE_CIECOMP 1 #define CONFIG_MAP_CODE_BLACKBODY 2 #define CONFIG_MAP_CODE_RAINBOW 3 #define CONFIG_MAP_CODE_IRON 4 #define CONFIG_MAP_CODE_BLUERED 5 #define CONFIG_MAP_CODE_JET 6 #define CONFIG_MAP_CODE_CIELUV 7 #define CONFIG_MAP_CODE_ICEIRON 8 #define CONFIG_MAP_CODE_ICEFIRE 9 #define CONFIG_MAP_CODE_REPEATED 10 #define CONFIG_MAP_CODE_HIGHLIGHTED 11 #define DEFAULT_DEGREES_PER_GRAYLEVEL 0.01 #define DEFAULT_DESIRED_DEGREES_PER_GRAYLEVEL 0.05 #endif // STREAMER_DEFINES_H
28.25
52
0.778761
ida-zrt
8ea68a3171b7de3bd25b1d8e665353d1e2de3003
749
cpp
C++
chef_march_17/xentask.cpp
anjali-sharma/DSA_Drill
d4111d11a493f9a67a7159ced2af165087ff8517
[ "MIT" ]
null
null
null
chef_march_17/xentask.cpp
anjali-sharma/DSA_Drill
d4111d11a493f9a67a7159ced2af165087ff8517
[ "MIT" ]
null
null
null
chef_march_17/xentask.cpp
anjali-sharma/DSA_Drill
d4111d11a493f9a67a7159ced2af165087ff8517
[ "MIT" ]
1
2021-02-20T08:05:17.000Z
2021-02-20T08:05:17.000Z
#include <iostream> using namespace std; int main() { int t, n, x; long int sum1e, sum1o, sum2e, sum2o; cin >> t; while(t--) { cin >> n; sum1e = sum1o = sum2e = sum2o = 0; for(int i = 0; i < n; i ++) { cin >> x; if(i%2==0) { sum1e += x; } else { sum1o += x; } } for(int i = 0; i < n; i ++) { cin >> x; if(i%2==0) { sum2e += x; } else { sum2o += x; } } if (sum1e + sum2o < sum1o + sum2e) { cout << sum1e+sum2o << endl; } else { cout << sum1o+sum2e << endl; } } return 0; }
19.710526
44
0.331108
anjali-sharma
8ea7d373d6741393ed56b61df2109386546444e0
8,740
cpp
C++
commands/set-raster-selection-cmd.cpp
lukas-ke/faint-graphics-editor
33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf
[ "Apache-2.0" ]
10
2016-12-28T22:06:31.000Z
2021-05-24T13:42:30.000Z
commands/set-raster-selection-cmd.cpp
lukas-ke/faint-graphics-editor
33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf
[ "Apache-2.0" ]
4
2015-10-09T23:55:10.000Z
2020-04-04T08:09:22.000Z
commands/set-raster-selection-cmd.cpp
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. #include <memory> #include "commands/command.hh" #include "commands/set-raster-selection-cmd.hh" #include "geo/geo-func.hh" #include "geo/int-point.hh" #include "geo/tri.hh" #include "rendering/faint-dc.hh" #include "text/utf8-string.hh" #include "util/optional.hh" #include "util/setting-util.hh" #include "util/type-util.hh" namespace faint{ class SetSelectionOptionsCommand : public Command { public: SetSelectionOptionsCommand(const NewSelectionOptions& newOptions, const OldSelectionOptions& oldOptions) : Command(CommandType::SELECTION), m_newOptions(newOptions.Get()), m_oldOptions(oldOptions.Get()) {} void Do(CommandContext& ctx) override{ ctx.SetRasterSelectionOptions(m_newOptions); } utf8_string Name() const override{ return "Change Selection Settings"; } void Undo(CommandContext& ctx) override{ ctx.SetRasterSelectionOptions(m_oldOptions); } private: SelectionOptions m_newOptions; SelectionOptions m_oldOptions; }; class SetRasterSelectionCommand : public Command{ public: SetRasterSelectionCommand(const NewSelectionState& newState, const OldSelectionState& oldState, const utf8_string& name, bool appendCommand) : Command(CommandType::SELECTION), m_appendCommand(appendCommand), m_name(name), m_newState(newState.Get()), m_oldState(oldState.Get()) {} SetRasterSelectionCommand(const NewSelectionState& newState, const Alternative<SelectionState> altNewState, const OldSelectionState& oldState, const utf8_string& name, bool appendCommand) : Command(CommandType::SELECTION), m_altNewState(altNewState.Get()), m_appendCommand(appendCommand), m_name(name), m_newState(newState.Get()), m_oldState(oldState.Get()) {} CommandPtr GetDWIM() override{ return m_altNewState.Visit( [&](const SelectionState& altNewState) -> CommandPtr{ // Fixme: Clone options command return std::make_unique<SetRasterSelectionCommand>( New(altNewState), alternate(m_newState), Old(m_oldState), m_name, false); }, []() -> CommandPtr{ assert(false); // Should not be called when not HasDWIM(). return nullptr; }); } void Do(CommandContext& ctx) override{ if (m_optionsCommand != nullptr){ m_optionsCommand->Do(ctx); } ctx.SetRasterSelection(m_newState); } bool HasDWIM() const override{ return m_altNewState.IsSet(); } bool ModifiesState() const override{ // Moving a floating selection or changing to/from floating state // affects the image content, merely selecting a region does not. return m_newState.Floating() || m_oldState.Floating(); } utf8_string Name() const override{ return m_name; } void Undo(CommandContext& ctx) override{ ctx.SetRasterSelection(m_oldState); if (m_optionsCommand != nullptr){ m_optionsCommand->Undo(ctx); } } bool ShouldAppend() const { // Fixme: Remove? // ..Presumably this refers to preferring a CommandBunch with // ..AppendSelection instead. Check if this is still used return m_appendCommand; } void SetOptionsCommand(SetSelectionOptionsCommand* cmd){ // Fixme: Remove? // ..Presumably this refers to using a command bunch instead // ..of appending the selections to the selection. m_optionsCommand.reset(cmd); } SetRasterSelectionCommand& operator=(const SetRasterSelectionCommand&) = delete; private: Optional<SelectionState> m_altNewState; bool m_appendCommand; const utf8_string m_name; SelectionState m_newState; SelectionState m_oldState; std::unique_ptr<SetSelectionOptionsCommand> m_optionsCommand; }; static bool should_append(const SetRasterSelectionCommand& cmd){ return cmd.ShouldAppend(); } class MoveRasterSelectionCommand : public Command { public: using ThisType = MoveRasterSelectionCommand; MoveRasterSelectionCommand(const IntPoint& newPos, const IntPoint& oldPos) : Command(CommandType::SELECTION), m_newPos(newPos), m_oldPos(oldPos) {} bool ShouldMerge(const Command& cmd, bool sameFrame) const override{ if (!sameFrame){ return false; } return is_type<ThisType>(cmd); } void Merge(CommandPtr cmd) override{ DoMerge(unique_ptr_cast<ThisType>(std::move(cmd))); } void Do(CommandContext& ctx) override{ ctx.MoveRasterSelection(m_newPos); } bool ModifiesState() const override{ return true; } utf8_string Name() const override{ return "Move Selected Content"; } void Undo(CommandContext& ctx) override{ ctx.MoveRasterSelection(m_oldPos); } private: void DoMerge(std::unique_ptr<ThisType> cmd){ // Merge with other, consecutive, move-raster-selection commands // by using their position m_newPos = cmd->m_newPos; } IntPoint m_newPos; IntPoint m_oldPos; }; CommandPtr move_raster_selection_command(const IntPoint& newPos, const IntPoint& oldPos) { return std::make_unique<MoveRasterSelectionCommand>(newPos, oldPos); } class StampFloatingSelectionCommand : public Command { public: StampFloatingSelectionCommand(const Bitmap& bmp, const IntRect& r, const Optional<IntRect>& oldRect, const SelectionOptions& options) : Command(CommandType::RASTER), m_bitmap(bmp), m_oldRect(oldRect), m_rect(r), m_settings(bitmap_mask_settings(options.mask, options.bg, options.alpha)), m_name("Stamp selection") {} void Do(CommandContext& context) override{ FaintDC& dc(context.GetDC()); if (m_oldRect.IsSet()){ dc.Rectangle(tri_from_rect(floated(m_oldRect.Get())), eraser_rectangle_settings(m_settings.Get(ts_Bg))); } dc.Blit(m_bitmap, floated(m_rect.TopLeft()), m_settings); } utf8_string Name() const override{ return m_name; } private: Bitmap m_bitmap; Optional<IntRect> m_oldRect; IntRect m_rect; Settings m_settings; utf8_string m_name; }; std::unique_ptr<Command> stamp_floating_selection_command( const sel::Copying& copying) { return std::make_unique<StampFloatingSelectionCommand>(copying.GetBitmap(), copying.Rect(), no_option(), copying.GetOptions()); } std::unique_ptr<Command> stamp_floating_selection_command( const sel::Moving& moving) { return std::make_unique<StampFloatingSelectionCommand>(moving.GetBitmap(), moving.Rect(), option(moving.OldRect()), moving.GetOptions()); } CommandPtr set_selection_options_command(const NewSelectionOptions& newOptions, const OldSelectionOptions& oldOptions) { return std::make_unique<SetSelectionOptionsCommand>(newOptions, oldOptions); } std::unique_ptr<Command> set_raster_selection_command( const NewSelectionState& newState, const OldSelectionState& oldState, const utf8_string& name, bool appendCommand) { return std::make_unique<SetRasterSelectionCommand>( newState, oldState, name, appendCommand); } std::unique_ptr<Command> set_raster_selection_command( const NewSelectionState& newState, const Alternative<SelectionState>& altNewState, const OldSelectionState& oldState, const utf8_string& name, bool appendCommand) { return std::make_unique<SetRasterSelectionCommand>(newState, altNewState, oldState, name, appendCommand); } std::unique_ptr<Command> set_raster_selection_command( const NewSelectionState& newState, const OldSelectionState& oldState, const utf8_string& name, bool appendCommand, const NewSelectionOptions& newOptions, const OldSelectionOptions& oldOptions) { auto cmd = std::make_unique<SetRasterSelectionCommand>(newState, oldState, name, appendCommand); cmd->SetOptionsCommand(new SetSelectionOptionsCommand(newOptions, oldOptions)); return upcast(std::move(cmd)); } bool is_appendable_raster_selection_command(const Command& cmd){ return if_type<const SetRasterSelectionCommand>(cmd, should_append, false_f); } bool is_move_raster_selection_command(const Command& cmd){ return is_type<MoveRasterSelectionCommand>(cmd); } } // namespace
27.3125
82
0.72746
lukas-ke
8eac15f9f2a1ed7f6d965add8744602cdcb7d43a
4,323
cpp
C++
webkit/WebCore/platform/qt/ScrollbarQt.cpp
s1rcheese/nintendo-3ds-internetbrowser-sourcecode
3dd05f035e0a5fc9723300623e9b9b359be64e11
[ "Unlicense" ]
15
2016-01-05T12:43:41.000Z
2022-03-15T10:34:47.000Z
webkit/WebCore/platform/qt/ScrollbarQt.cpp
s1rcheese/nintendo-3ds-internetbrowser-sourcecode
3dd05f035e0a5fc9723300623e9b9b359be64e11
[ "Unlicense" ]
null
null
null
webkit/WebCore/platform/qt/ScrollbarQt.cpp
s1rcheese/nintendo-3ds-internetbrowser-sourcecode
3dd05f035e0a5fc9723300623e9b9b359be64e11
[ "Unlicense" ]
2
2020-11-30T18:36:01.000Z
2021-02-05T23:20:24.000Z
/* * Copyright (C) 2007, 2008 Apple Inc. All rights reserved. * Copyright (C) 2007 Staikos Computing Services Inc. <info@staikos.net> * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies) * * 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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "config.h" #include "Scrollbar.h" #include "EventHandler.h" #include "FrameView.h" #include "Frame.h" #include "GraphicsContext.h" #include "IntRect.h" #include "PlatformMouseEvent.h" #include "ScrollbarTheme.h" #include <QApplication> #include <QDebug> #include <QPainter> #include <QStyle> #include <QMenu> using namespace std; namespace WebCore { bool Scrollbar::contextMenu(const PlatformMouseEvent& event) { #ifndef QT_NO_CONTEXTMENU if (!QApplication::style()->styleHint(QStyle::SH_ScrollBar_ContextMenu)) return true; bool horizontal = (m_orientation == HorizontalScrollbar); QMenu menu; QAction* actScrollHere = menu.addAction(QCoreApplication::translate("QWebPage", "Scroll here")); menu.addSeparator(); QAction* actScrollTop = menu.addAction(horizontal ? QCoreApplication::translate("QWebPage", "Left edge") : QCoreApplication::translate("QWebPage", "Top")); QAction* actScrollBottom = menu.addAction(horizontal ? QCoreApplication::translate("QWebPage", "Right edge") : QCoreApplication::translate("QWebPage", "Bottom")); menu.addSeparator(); QAction* actPageUp = menu.addAction(horizontal ? QCoreApplication::translate("QWebPage", "Page left") : QCoreApplication::translate("QWebPage", "Page up")); QAction* actPageDown = menu.addAction(horizontal ? QCoreApplication::translate("QWebPage", "Page right") : QCoreApplication::translate("QWebPage", "Page down")); menu.addSeparator(); QAction* actScrollUp = menu.addAction(horizontal ? QCoreApplication::translate("QWebPage", "Scroll left") : QCoreApplication::translate("QWebPage", "Scroll up")); QAction* actScrollDown = menu.addAction(horizontal ? QCoreApplication::translate("QWebPage", "Scroll right") : QCoreApplication::translate("QWebPage", "Scroll down")); const QPoint globalPos = QPoint(event.globalX(), event.globalY()); QAction* actionSelected = menu.exec(globalPos); if (!actionSelected) { /* Do nothing */ } else if (actionSelected == actScrollHere) { const QPoint pos = convertFromContainingWindow(event.pos()); moveThumb(horizontal ? pos.x() : pos.y()); } else if (actionSelected == actScrollTop) setValue(0); else if (actionSelected == actScrollBottom) setValue(maximum()); else if (actionSelected == actPageUp) scroll(horizontal ? ScrollLeft: ScrollUp, ScrollByPage, 1); else if (actionSelected == actPageDown) scroll(horizontal ? ScrollRight : ScrollDown, ScrollByPage, 1); else if (actionSelected == actScrollUp) scroll(horizontal ? ScrollLeft : ScrollUp, ScrollByLine, 1); else if (actionSelected == actScrollDown) scroll(horizontal ? ScrollRight : ScrollDown, ScrollByLine, 1); #endif // QT_NO_CONTEXTMENU return true; } } // vim: ts=4 sw=4 et
43.666667
171
0.729123
s1rcheese
8eaecde4e4129c5ac188a6f1fd086ea5c2e8f1e0
12,937
cpp
C++
artifact/storm/src/storm/utility/Engine.cpp
glatteis/tacas21-artifact
30b4f522bd3bdb4bebccbfae93f19851084a3db5
[ "MIT" ]
null
null
null
artifact/storm/src/storm/utility/Engine.cpp
glatteis/tacas21-artifact
30b4f522bd3bdb4bebccbfae93f19851084a3db5
[ "MIT" ]
null
null
null
artifact/storm/src/storm/utility/Engine.cpp
glatteis/tacas21-artifact
30b4f522bd3bdb4bebccbfae93f19851084a3db5
[ "MIT" ]
1
2022-02-05T12:39:53.000Z
2022-02-05T12:39:53.000Z
#include "storm/utility/Engine.h" #include "storm/models/sparse/StandardRewardModel.h" #include "storm/models/symbolic/StandardRewardModel.h" #include "storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.h" #include "storm/modelchecker/prctl/SparseMdpPrctlModelChecker.h" #include "storm/modelchecker/csl/SparseCtmcCslModelChecker.h" #include "storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.h" #include "storm/modelchecker/prctl/HybridDtmcPrctlModelChecker.h" #include "storm/modelchecker/prctl/HybridMdpPrctlModelChecker.h" #include "storm/modelchecker/csl/HybridCtmcCslModelChecker.h" #include "storm/modelchecker/csl/HybridMarkovAutomatonCslModelChecker.h" #include "storm/modelchecker/prctl/SymbolicDtmcPrctlModelChecker.h" #include "storm/modelchecker/prctl/SymbolicMdpPrctlModelChecker.h" #include "storm/modelchecker/CheckTask.h" #include "storm/storage/SymbolicModelDescription.h" #include "storm/storage/jani/Property.h" #include "storm/utility/macros.h" #include "storm/exceptions/InvalidArgumentException.h" namespace storm { namespace utility { // Returns a list of all available engines (excluding Unknown) std::vector<Engine> getEngines() { std::vector<Engine> res; for (int i = 0; i != static_cast<int>(Engine::Unknown); ++i) { res.push_back(static_cast<Engine>(i)); } return res; } std::string toString(Engine const& engine) { switch (engine) { case Engine::Sparse: return "sparse"; case Engine::Hybrid: return "hybrid"; case Engine::Dd: return "dd"; case Engine::DdSparse: return "dd-to-sparse"; case Engine::Jit: return "jit"; case Engine::Exploration: return "expl"; case Engine::AbstractionRefinement: return "abs"; case Engine::Automatic: return "automatic"; case Engine::Unknown: return "UNKNOWN"; default: STORM_LOG_ASSERT(false, "The given engine has no name assigned to it."); return "UNKNOWN"; } } std::ostream& operator<<(std::ostream& os, Engine const& engine) { os << toString(engine); return os; } Engine engineFromString(std::string const& engineStr) { for (Engine const& e : getEngines()) { if (engineStr == toString(e)) { return e; } } if (engineStr == "portfolio") { STORM_LOG_WARN("The engine name \"portfolio\" is deprecated. The name of this engine has been changed to \"" << toString(Engine::Automatic) << "\"."); return Engine::Automatic; } STORM_LOG_ERROR("The engine '" << engineStr << "' was not found."); return Engine::Unknown; } storm::builder::BuilderType getBuilderType(Engine const& engine) { switch (engine) { case Engine::Sparse: return storm::builder::BuilderType::Explicit; case Engine::Hybrid: return storm::builder::BuilderType::Dd; case Engine::Dd: return storm::builder::BuilderType::Dd; case Engine::DdSparse: return storm::builder::BuilderType::Dd; case Engine::Jit: return storm::builder::BuilderType::Jit; case Engine::Exploration: return storm::builder::BuilderType::Explicit; case Engine::AbstractionRefinement: return storm::builder::BuilderType::Dd; default: STORM_LOG_THROW(false, storm::exceptions::InvalidArgumentException, "The given engine has no builder type to it."); return storm::builder::BuilderType::Explicit; } } template <typename ValueType> bool canHandle(storm::utility::Engine const& engine, storm::storage::SymbolicModelDescription::ModelType const& modelType, storm::modelchecker::CheckTask<storm::logic::Formula, ValueType> const& checkTask) { // Define types to improve readability typedef storm::storage::SymbolicModelDescription::ModelType ModelType; // The Dd library does not make much of a difference (in case of exact or parametric models we will switch to sylvan anyway). // Therefore, we always use sylvan here storm::dd::DdType const ddType = storm::dd::DdType::Sylvan; switch (engine) { case Engine::Sparse: case Engine::DdSparse: case Engine::Jit: switch (modelType) { case ModelType::DTMC: return storm::modelchecker::SparseDtmcPrctlModelChecker<storm::models::sparse::Dtmc<ValueType>>::canHandleStatic(checkTask); case ModelType::MDP: return storm::modelchecker::SparseMdpPrctlModelChecker<storm::models::sparse::Mdp<ValueType>>::canHandleStatic(checkTask); case ModelType::CTMC: return storm::modelchecker::SparseCtmcCslModelChecker<storm::models::sparse::Ctmc<ValueType>>::canHandleStatic(checkTask); case ModelType::MA: return storm::modelchecker::SparseMarkovAutomatonCslModelChecker<storm::models::sparse::MarkovAutomaton<ValueType>>::canHandleStatic(checkTask); case ModelType::POMDP: return false; } break; case Engine::Hybrid: switch (modelType) { case ModelType::DTMC: return storm::modelchecker::HybridDtmcPrctlModelChecker<storm::models::symbolic::Dtmc<ddType, ValueType>>::canHandleStatic(checkTask); case ModelType::MDP: return storm::modelchecker::HybridMdpPrctlModelChecker<storm::models::symbolic::Mdp<ddType, ValueType>>::canHandleStatic(checkTask); case ModelType::CTMC: return storm::modelchecker::HybridCtmcCslModelChecker<storm::models::symbolic::Ctmc<ddType, ValueType>>::canHandleStatic(checkTask); case ModelType::MA: return storm::modelchecker::HybridMarkovAutomatonCslModelChecker<storm::models::symbolic::MarkovAutomaton<ddType, ValueType>>::canHandleStatic(checkTask); case ModelType::POMDP: return false; } break; case Engine::Dd: switch (modelType) { case ModelType::DTMC: return storm::modelchecker::SymbolicDtmcPrctlModelChecker<storm::models::symbolic::Dtmc<ddType, ValueType>>::canHandleStatic(checkTask); case ModelType::MDP: return storm::modelchecker::SymbolicMdpPrctlModelChecker<storm::models::symbolic::Mdp<ddType, ValueType>>::canHandleStatic(checkTask); case ModelType::CTMC: case ModelType::MA: case ModelType::POMDP: return false; } break; default: STORM_LOG_ERROR("The selected engine " << engine << " is not considered."); } STORM_LOG_ERROR("The selected combination of engine (" << engine << ") and model type (" << modelType << ") does not seem to be supported for this value type."); return false; } template <> bool canHandle<storm::RationalFunction>(storm::utility::Engine const& engine, storm::storage::SymbolicModelDescription::ModelType const& modelType, storm::modelchecker::CheckTask<storm::logic::Formula, storm::RationalFunction> const& checkTask) { // Define types to improve readability typedef storm::storage::SymbolicModelDescription::ModelType ModelType; // The Dd library does not make much of a difference (in case of exact or parametric models we will switch to sylvan anyway). // Therefore, we always use sylvan here storm::dd::DdType const ddType = storm::dd::DdType::Sylvan; switch (engine) { case Engine::Sparse: case Engine::DdSparse: switch (modelType) { case ModelType::DTMC: return storm::modelchecker::SparseDtmcPrctlModelChecker<storm::models::sparse::Dtmc<storm::RationalFunction>>::canHandleStatic(checkTask); case ModelType::CTMC: return storm::modelchecker::SparseCtmcCslModelChecker<storm::models::sparse::Ctmc<storm::RationalFunction>>::canHandleStatic(checkTask); case ModelType::MDP: case ModelType::MA: case ModelType::POMDP: return false; } break; case Engine::Hybrid: switch (modelType) { case ModelType::DTMC: return storm::modelchecker::HybridDtmcPrctlModelChecker<storm::models::symbolic::Dtmc<ddType, storm::RationalFunction>>::canHandleStatic(checkTask); case ModelType::CTMC: return storm::modelchecker::HybridCtmcCslModelChecker<storm::models::symbolic::Ctmc<ddType, storm::RationalFunction>>::canHandleStatic(checkTask); case ModelType::MDP: case ModelType::MA: case ModelType::POMDP: return false; } break; case Engine::Dd: switch (modelType) { case ModelType::DTMC: return storm::modelchecker::SymbolicDtmcPrctlModelChecker<storm::models::symbolic::Dtmc<ddType, storm::RationalFunction>>::canHandleStatic(checkTask); case ModelType::MDP: case ModelType::CTMC: case ModelType::MA: case ModelType::POMDP: return false; } break; default: STORM_LOG_ERROR("The selected engine" << engine << " is not considered."); } STORM_LOG_ERROR("The selected combination of engine (" << engine << ") and model type (" << modelType << ") does not seem to be supported for this value type."); return false; } template <typename ValueType> bool canHandle(storm::utility::Engine const& engine, std::vector<storm::jani::Property> const& properties, storm::storage::SymbolicModelDescription const& modelDescription) { // Check handability of properties based on model type for (auto const& p : properties) { for (auto const& f : {p.getRawFormula(), p.getFilter().getStatesFormula()}) { auto task = storm::modelchecker::CheckTask<storm::logic::Formula, ValueType>(*f, true); if (!canHandle(engine, modelDescription.getModelType(), task)) { STORM_LOG_INFO("Engine " << engine << " can not handle formula '" << *f << "' on models of type " << modelDescription.getModelType() << "."); return false; } } } // Check whether the model builder can handle the model description return storm::builder::canHandle<ValueType>(getBuilderType(engine), modelDescription, properties); } // explicit template instantiations. template bool canHandle<double>(storm::utility::Engine const&, std::vector<storm::jani::Property> const&, storm::storage::SymbolicModelDescription const&); template bool canHandle<storm::RationalNumber>(storm::utility::Engine const&, std::vector<storm::jani::Property> const&, storm::storage::SymbolicModelDescription const&); template bool canHandle<storm::RationalFunction>(storm::utility::Engine const&, std::vector<storm::jani::Property> const&, storm::storage::SymbolicModelDescription const&); } }
54.817797
254
0.565742
glatteis
8eaef9f9e1205e8d083fb9959b55dd18720c9d52
1,855
cpp
C++
src/dbobject.cpp
drsm/sqt
9974045b1128ad019bb53736d0421e74e8b3eafa
[ "MIT" ]
35
2018-02-28T09:36:50.000Z
2022-03-13T07:53:34.000Z
src/dbobject.cpp
drsm/sqt
9974045b1128ad019bb53736d0421e74e8b3eafa
[ "MIT" ]
5
2018-10-18T07:33:40.000Z
2020-04-29T19:41:05.000Z
src/dbobject.cpp
drsm/sqt
9974045b1128ad019bb53736d0421e74e8b3eafa
[ "MIT" ]
9
2018-02-28T09:37:27.000Z
2019-12-13T14:54:41.000Z
#include "dbobject.h" #include "dbconnectionfactory.h" #include "odbcconnection.h" DbObject::DbObject(DbObject *parent) { _parent = parent; //setData(true, DbObject::ParentRole); setData(0, DbObject::CurrentSortRole); setData(false, DbObject::MultiselectRole); } DbObject::DbObject(DbObject *parent, QString text, QString type, QFont font) : _parent(parent) { setData(text); setData(type, DbObject::TypeRole); //setData(true, DbObject::ParentRole); setData(font, Qt::FontRole); setData(0, DbObject::CurrentSortRole); setData(false, DbObject::MultiselectRole); } DbObject::~DbObject() { qDeleteAll(_conceived); _conceived.clear(); qDeleteAll(_children); _children.clear(); QString type = data(DbObject::TypeRole).toString(); if (type == "connection" || type == "database") { QString id = QString::number(std::intptr_t(this)); DbConnectionFactory::removeConnection(id); } } void DbObject::setData(const QVariant &value, int role) { _itemData[role] = value; } void DbObject::appendChild(DbObject *item) { _children.append(item); item->setParent(this); } QVariant DbObject::data(int role) const { QVariant defValue; switch (role) { case DbObject::ParentRole: defValue = false; break; } return _itemData.value(role, defValue); } int DbObject::row() const { if (_parent) return _parent->_children.indexOf(const_cast<DbObject*>(this)); return 0; } bool DbObject::insertChild(int beforeRow) { if (beforeRow > _children.count()) return false; _children.insert(beforeRow, new DbObject(this)); return true; } bool DbObject::removeChild(int pos) { if (pos >= _children.count()) return false; delete _children.at(pos); _children.removeAt(pos); return true; }
22.349398
94
0.665229
drsm
8eaf60b0dc0f091ad0159edd4ddac7883d363175
48,834
cpp
C++
TRAP/src/Window/Window.cpp
GamesTrap/TRAP
007de9ce70273cb8ae11066cc8488d9db78b1038
[ "MIT", "Zlib", "Apache-2.0", "BSD-3-Clause" ]
3
2018-06-23T18:18:19.000Z
2019-05-27T21:10:07.000Z
TRAP/src/Window/Window.cpp
GamesTrap/TRAP
007de9ce70273cb8ae11066cc8488d9db78b1038
[ "MIT", "Zlib", "Apache-2.0", "BSD-3-Clause" ]
88
2018-08-02T01:08:04.000Z
2019-07-24T19:13:26.000Z
TRAP/src/Window/Window.cpp
GamesTrap/TRAP
007de9ce70273cb8ae11066cc8488d9db78b1038
[ "MIT", "Zlib", "Apache-2.0", "BSD-3-Clause" ]
2
2018-08-02T01:10:40.000Z
2020-08-14T14:05:58.000Z
#include "TRAPPCH.h" #include "Window.h" #include "Utils/Dialogs/MsgBox.h" #include "Events/KeyEvent.h" #include "Events/MouseEvent.h" #include "Events/WindowEvent.h" #include "Events/MonitorEvent.h" #include "Graphics/API/RendererAPI.h" #include "Graphics/Renderer.h" #include "Graphics/Shaders/ShaderManager.h" #include "Graphics/Textures/TextureManager.h" #include "Input/Input.h" #include "Embed.h" #include "Graphics/API/Vulkan/VulkanRenderer.h" #include "Layers/ImGui/ImGuiWindowing.h" //-------------------------------------------------------------------------------------------------------------------// uint32_t TRAP::Window::s_windows = 0; //-------------------------------------------------------------------------------------------------------------------// bool TRAP::Window::s_WindowingAPIInitialized = false; //-------------------------------------------------------------------------------------------------------------------// std::vector<TRAP::Window*> TRAP::Window::s_fullscreenWindows{}; //-------------------------------------------------------------------------------------------------------------------// std::unordered_map<uint32_t, TRAP::INTERNAL::WindowingAPI::InternalVideoMode> TRAP::Window::s_baseVideoModes{}; //-------------------------------------------------------------------------------------------------------------------// TRAP::Window::Window(const WindowProps &props) : m_window(nullptr), m_useMonitor(nullptr) { TP_PROFILE_FUNCTION(); TP_INFO ( Log::WindowPrefix, "Initializing Window: \"", props.Title, "\" ", props.Width, "x", props.Height, "@", props.RefreshRate, "Hz VSync: ", props.Advanced.VSync > 0 ? "On" : "Off", "(", props.Advanced.VSync, //Output VSync status ") DisplayMode: ", props.DisplayMode == DisplayMode::Windowed ? "Windowed" : props.DisplayMode == DisplayMode::Borderless ? "Borderless" : "Fullscreen", //Output DisplayMode " Monitor: ", props.Monitor, " CursorMode: ", props.Advanced.CursorMode == CursorMode::Normal ? "Normal" : props.Advanced.CursorMode == CursorMode::Hidden ? "Hidden" : "Disabled", //Output CursorMode " RawMouseInput: ", props.Advanced.RawMouseInput ? "Enabled" : "Disabled" ); Init(props); } //-------------------------------------------------------------------------------------------------------------------// TRAP::Window::~Window() { TP_PROFILE_FUNCTION(); if (s_windows > 1) { Use(); if (Graphics::API::Context::GetRenderAPI() == Graphics::API::RenderAPI::Vulkan) Graphics::API::VulkanRenderer::DeleteWindowSwapchain(m_window.get()); } s_windows--; if(!s_windows) { Graphics::Renderer::Shutdown(); Graphics::TextureManager::Shutdown(); Graphics::ShaderManager::Shutdown(); Graphics::API::RendererAPI::Shutdown(); Graphics::API::Context::Shutdown(); } TP_DEBUG(Log::WindowPrefix, "Destroying Window: \"", m_data.Title, "\""); Shutdown(); } //-------------------------------------------------------------------------------------------------------------------// void TRAP::Window::OnUpdate() { TP_PROFILE_FUNCTION(); INTERNAL::WindowingAPI::PollEvents(); } //-------------------------------------------------------------------------------------------------------------------// void TRAP::Window::Use(const Scope<Window>& window) { if (window) Graphics::API::Context::Use(window.get()); else Use(); } //-------------------------------------------------------------------------------------------------------------------// void TRAP::Window::Use() { Graphics::API::Context::Use(Application::GetWindow().get()); } //-------------------------------------------------------------------------------------------------------------------// uint32_t TRAP::Window::GetActiveWindows() { return s_windows; } //-------------------------------------------------------------------------------------------------------------------// const std::string& TRAP::Window::GetTitle() const { return m_data.Title; } //-------------------------------------------------------------------------------------------------------------------// uint32_t TRAP::Window::GetWidth() const { return m_data.Width; } //-------------------------------------------------------------------------------------------------------------------// uint32_t TRAP::Window::GetHeight() const { return m_data.Height; } //-------------------------------------------------------------------------------------------------------------------// TRAP::Math::Vec2ui TRAP::Window::GetSize() const { return { m_data.Width, m_data.Height }; } //-------------------------------------------------------------------------------------------------------------------// uint32_t TRAP::Window::GetRefreshRate() const { return m_data.RefreshRate; } //-------------------------------------------------------------------------------------------------------------------// TRAP::Window::DisplayMode TRAP::Window::GetDisplayMode() const { return m_data.displayMode; } //-------------------------------------------------------------------------------------------------------------------// TRAP::Monitor TRAP::Window::GetMonitor() const { return Monitor(m_data.Monitor); } //-------------------------------------------------------------------------------------------------------------------// uint32_t TRAP::Window::GetVSyncInterval() const { return m_data.VSync; } //-------------------------------------------------------------------------------------------------------------------// TRAP::Window::CursorMode TRAP::Window::GetCursorMode() const { return m_data.cursorMode; } //-------------------------------------------------------------------------------------------------------------------// bool TRAP::Window::GetRawMouseInput() const { return m_data.RawMouseInput; } //-------------------------------------------------------------------------------------------------------------------// TRAP::Math::Vec2 TRAP::Window::GetContentScale() const { TP_PROFILE_FUNCTION(); Math::Vec2 contentScale{}; INTERNAL::WindowingAPI::GetWindowContentScale(m_window.get(), contentScale.x, contentScale.y); return contentScale; } //-------------------------------------------------------------------------------------------------------------------// float TRAP::Window::GetOpacity() const { TP_PROFILE_FUNCTION(); return INTERNAL::WindowingAPI::GetWindowOpacity(m_window.get()); } //-------------------------------------------------------------------------------------------------------------------// void* TRAP::Window::GetInternalWindow() const { return m_window.get(); } //-------------------------------------------------------------------------------------------------------------------// void TRAP::Window::SetTitle(const std::string& title) { TP_PROFILE_FUNCTION(); const std::string oldTitle = m_data.Title; if (!title.empty()) m_data.Title = title; else m_data.Title = "TRAP Engine"; #ifndef TRAP_RELEASE std::string newTitle = m_data.Title + " - TRAP Engine V" + std::to_string(TRAP_VERSION_MAJOR(TRAP_VERSION)) + "." + std::to_string(TRAP_VERSION_MINOR(TRAP_VERSION)) + "." + std::to_string(TRAP_VERSION_PATCH(TRAP_VERSION)) + "[INDEV]" + Log::WindowVersion + Graphics::Renderer::GetTitle(); #ifdef TRAP_PLATFORM_LINUX if (Application::GetLinuxWindowManager() == Application::LinuxWindowManager::Wayland) newTitle += "[Wayland]"; else if (Application::GetLinuxWindowManager() == Application::LinuxWindowManager::X11) newTitle += "[X11]"; else newTitle += "[Unknown]"; #endif INTERNAL::WindowingAPI::SetWindowTitle(m_window.get(), newTitle); #else INTERNAL::WindowingAPI::SetWindowTitle(m_window.get(), m_data.Title); #endif } //-------------------------------------------------------------------------------------------------------------------// void TRAP::Window::SetDisplayMode(const DisplayMode& mode, uint32_t width, uint32_t height, uint32_t refreshRate) { TP_PROFILE_FUNCTION(); //Only change windowed mode if resolution and refresh rate changed if(m_data.displayMode == DisplayMode::Windowed && mode == DisplayMode::Windowed) { if (m_data.Width == static_cast<int32_t>(width) && m_data.Height == static_cast<int32_t>(height)) { //Only update refresh rate used for Borderless or Fullscreen if (m_data.RefreshRate != static_cast<int32_t>(refreshRate)) { m_oldWindowedParams.RefreshRate = m_data.RefreshRate; m_data.RefreshRate = refreshRate; } TP_WARN(Log::WindowPrefix, "\"", m_data.Title, "\" already uses DisplayMode Windowed!"); return; } } //If currently windowed, stash the current size and position of the window if (m_data.displayMode == DisplayMode::Windowed) { m_oldWindowedParams.Width = m_data.Width; m_oldWindowedParams.Height = m_data.Height; m_oldWindowedParams.RefreshRate = m_data.RefreshRate; INTERNAL::WindowingAPI::GetWindowPos(m_window.get(), m_oldWindowedParams.XPos, m_oldWindowedParams.YPos); } if(mode == DisplayMode::Windowed) s_fullscreenWindows[m_data.Monitor] = nullptr; INTERNAL::WindowingAPI::InternalMonitor* monitor = nullptr; if (mode == DisplayMode::Borderless) { if(s_fullscreenWindows[m_data.Monitor]) { //Check if Monitor is already used by another window if (s_fullscreenWindows[m_data.Monitor] != this) { TP_ERROR(Log::WindowPrefix, "\"", m_data.Title, "\" couldn't set DisplayMode to Borderless because Monitor: ", m_data.Monitor, '(', INTERNAL::WindowingAPI::GetMonitorName(m_useMonitor), ')', " is already used by Window: \"", s_fullscreenWindows[m_data.Monitor]->GetTitle(), "\"!"); return; } //Check if Monitor is used by this window and display mode should be set to borderless if(s_fullscreenWindows[m_data.Monitor] == this && m_data.displayMode == DisplayMode::Borderless) { TP_WARN(Log::WindowPrefix, "\"", m_data.Title, "\" already uses DisplayMode Borderless on Monitor: ", m_data.Monitor, "(", INTERNAL::WindowingAPI::GetMonitorName(m_useMonitor), ")!"); return; } } s_fullscreenWindows[m_data.Monitor] = this; //For borderless fullscreen, the new width, height and refresh rate will be the default/native video modes width, height and refresh rate width = s_baseVideoModes[m_data.Monitor].Width; height = s_baseVideoModes[m_data.Monitor].Height; refreshRate = s_baseVideoModes[m_data.Monitor].RefreshRate; monitor = m_useMonitor; TP_DEBUG(Log::WindowPrefix, "\"", m_data.Title, "\" Using Monitor: ", m_data.Monitor, '(', INTERNAL::WindowingAPI::GetMonitorName(monitor), ')'); } else if (mode == DisplayMode::Windowed && (width == 0 || height == 0 || refreshRate == 0)) { //For windowed, use old window height and width if none provided width = m_oldWindowedParams.Width; height = m_oldWindowedParams.Height; refreshRate = m_oldWindowedParams.RefreshRate; } else if (mode == DisplayMode::Fullscreen) { if (s_fullscreenWindows[m_data.Monitor] && s_fullscreenWindows[m_data.Monitor] != this) { TP_ERROR(Log::WindowPrefix, "\"", m_data.Title, "\" couldn't set DisplayMode to Fullscreen because Monitor: ", m_data.Monitor, '(', INTERNAL::WindowingAPI::GetMonitorName(m_useMonitor), ')', " is already used by Window: \"", s_fullscreenWindows[m_data.Monitor]->GetTitle(), "\"!"); return; } s_fullscreenWindows[m_data.Monitor] = this; monitor = m_useMonitor; bool valid = false; const auto monitorVideoModes = INTERNAL::WindowingAPI::GetVideoModes(m_useMonitor); if (width != 0 && height != 0 && refreshRate != 0) { //Check if current running mode is same as target mode if (static_cast<uint32_t>(s_baseVideoModes[m_data.Monitor].Width) == width && static_cast<uint32_t>(s_baseVideoModes[m_data.Monitor].Height) == height && static_cast<uint32_t>(s_baseVideoModes[m_data.Monitor].RefreshRate) == refreshRate) valid = true; if (!valid) //If not check every video mode of the monitor { for (const auto& monitorVideoMode : monitorVideoModes) { //Check if resolution pair is valid and break if found if (static_cast<uint32_t>(monitorVideoMode.Width) == width && static_cast<uint32_t>(monitorVideoMode.Height) == height && static_cast<uint32_t>(monitorVideoMode.RefreshRate) == refreshRate) { valid = true; break; } } } } //Resolution pair is still invalid so use native/default resolution if (!valid) { width = s_baseVideoModes[m_data.Monitor].Width; height = s_baseVideoModes[m_data.Monitor].Height; refreshRate = s_baseVideoModes[m_data.Monitor].RefreshRate; } //Needed to switch from borderless to fullscreen directly if (m_data.displayMode == DisplayMode::Borderless) INTERNAL::WindowingAPI::SetWindowMonitor(m_window.get(), nullptr, m_oldWindowedParams.XPos, m_oldWindowedParams.YPos, static_cast<int32_t>(width), static_cast<int32_t>(height), static_cast<int32_t>(refreshRate)); TP_DEBUG(Log::WindowPrefix, "\"", m_data.Title, "\" Using Monitor: ", m_data.Monitor, '(', INTERNAL::WindowingAPI::GetMonitorName(monitor), ')'); } //Update stored width and height m_data.Width = width; m_data.Height = height; m_data.RefreshRate = refreshRate; //Set Refresh Rate to the current used VideoMode to prevent RefreshRate = 0 inside Engine.cfg if (m_data.displayMode == DisplayMode::Windowed) { const INTERNAL::WindowingAPI::InternalVideoMode videoMode = INTERNAL::WindowingAPI::GetVideoMode(INTERNAL::WindowingAPI::GetMonitors()[m_data.Monitor]); m_data.RefreshRate = videoMode.RefreshRate; } //Trigger resize event if (m_data.EventCallback) { Events::WindowResizeEvent event(width, height, m_data.Title); Events::FrameBufferResizeEvent event1(width, height, m_data.Title); m_data.EventCallback(event); m_data.EventCallback(event1); } constexpr auto GetModeStr = [&](const DisplayMode displayMode) { if (displayMode == DisplayMode::Windowed) return "Windowed"; return displayMode == DisplayMode::Borderless ? "Borderless" : "Fullscreen"; }; //Little hack to convert enum class DisplayMode to string TP_INFO(Log::WindowPrefix, "\"", m_data.Title, "\" Changing window mode from ", GetModeStr(m_data.displayMode), " to ", GetModeStr(mode), ": ", width, 'x', height, '@', refreshRate, "Hz"); //Record new window type m_data.displayMode = mode; if(mode == DisplayMode::Borderless) INTERNAL::WindowingAPI::SetWindowMonitorBorderless(m_window.get(), monitor); else { INTERNAL::WindowingAPI::SetWindowMonitor(m_window.get(), monitor, m_oldWindowedParams.XPos, m_oldWindowedParams.YPos, static_cast<int32_t>(width), static_cast<int32_t>(height), static_cast<int32_t>(refreshRate)); } } //-------------------------------------------------------------------------------------------------------------------// void TRAP::Window::SetMonitor(Monitor& monitor) { TP_PROFILE_FUNCTION(); const uint32_t oldMonitor = m_data.Monitor; TP_DEBUG(Log::WindowPrefix, "\"", m_data.Title, "\" Set Monitor: ", monitor.GetID(), " Name: ", monitor.GetName()); m_data.Monitor = monitor.GetID(); m_useMonitor = static_cast<INTERNAL::WindowingAPI::InternalMonitor*>(monitor.GetInternalMonitor()); s_fullscreenWindows[oldMonitor] = nullptr; if (m_data.displayMode != DisplayMode::Windowed) { if (s_fullscreenWindows[m_data.Monitor]) //Monitor already has a Fullscreen/Borderless Window { TP_ERROR(Log::WindowPrefix, "Monitor: ", m_data.Monitor, "(", monitor.GetName(), ") is already used by another Window!"); SetDisplayMode(DisplayMode::Windowed, 800, 600, 0); } else SetDisplayMode(m_data.displayMode, m_data.Width, m_data.Height, m_data.RefreshRate); } } //------------------------------------------------------------------------------------------------------------------// void TRAP::Window::SetVSyncInterval(const uint32_t interval) { TP_PROFILE_FUNCTION(); Graphics::API::Context::SetVSyncInterval(interval); m_data.VSync = interval; } //-------------------------------------------------------------------------------------------------------------------// void TRAP::Window::SetCursorMode(const CursorMode& mode) { TP_PROFILE_FUNCTION(); if (mode == CursorMode::Normal) TP_DEBUG(Log::WindowPrefix, "\"", m_data.Title, "\" Set CursorMode: Normal"); else if (mode == CursorMode::Hidden) TP_DEBUG(Log::WindowPrefix, "\"", m_data.Title, "\" Set CursorMode: Hidden"); else if (mode == CursorMode::Disabled) TP_DEBUG(Log::WindowPrefix, "\"", m_data.Title, "\" Set CursorMode: Disabled"); else if(mode == CursorMode::Captured) TP_DEBUG(Log::WindowPrefix, "\"", m_data.Title, "\" Set CursorMode: Captured"); INTERNAL::WindowingAPI::SetCursorMode(m_window.get(), mode); m_data.cursorMode = mode; } //-------------------------------------------------------------------------------------------------------------------// void TRAP::Window::SetCursorType(const CursorType& cursor) const { TP_PROFILE_FUNCTION(); Scope<INTERNAL::WindowingAPI::InternalCursor> internalCursor = INTERNAL::WindowingAPI::CreateStandardCursor(cursor); INTERNAL::WindowingAPI::SetCursor(m_window.get(), internalCursor.get()); INTERNAL::ImGuiWindowing::SetCustomCursor(internalCursor); } //-------------------------------------------------------------------------------------------------------------------// void TRAP::Window::SetCursorIcon(const Scope<Image>& image, const int32_t xHotspot, const int32_t yHotspot) const { TP_PROFILE_FUNCTION(); Scope<INTERNAL::WindowingAPI::InternalCursor> cursor = INTERNAL::WindowingAPI::CreateCursor(image, xHotspot, yHotspot); INTERNAL::WindowingAPI::SetCursor(m_window.get(), cursor.get()); INTERNAL::ImGuiWindowing::SetCustomCursor(cursor); } //-------------------------------------------------------------------------------------------------------------------// void TRAP::Window::SetRawMouseInput(const bool enabled) { TP_PROFILE_FUNCTION(); if(Input::IsRawMouseInputSupported()) { m_data.RawMouseInput = enabled; INTERNAL::WindowingAPI::SetRawMouseMotionMode(m_window.get(), enabled); TP_DEBUG(Log::WindowPrefix, "\"", m_data.Title, "\" Raw Mouse Input ", enabled ? "Enabled" : "Disabled"); } else { TP_ERROR(Log::WindowPrefix, "\"", m_data.Title, "\" Raw Mouse Input is unsupported!"); m_data.RawMouseInput = false; } } //-------------------------------------------------------------------------------------------------------------------// void TRAP::Window::SetIcon() const { TP_PROFILE_FUNCTION(); const std::vector<uint8_t> TRAPLogo{ Embed::TRAPLogo.begin(), Embed::TRAPLogo.end() }; INTERNAL::WindowingAPI::SetWindowIcon(m_window.get(), Image::LoadFromMemory(32, 32, Image::ColorFormat::RGBA, TRAPLogo)); } //-------------------------------------------------------------------------------------------------------------------// void TRAP::Window::SetIcon(const Scope<Image>& image) const { TP_PROFILE_FUNCTION(); if (!image) { SetIcon(); return; } if (image->IsHDR()) { TP_ERROR(Log::WindowIconPrefix, "\"", m_data.Title, "\" HDR is not supported for window icons!"); TP_WARN(Log::WindowIconPrefix, "\"", m_data.Title, "\" Using Default Icon!"); SetIcon(); return; } if ((image->IsImageGrayScale() && image->GetBitsPerPixel() == 16 && !image->HasAlphaChannel()) || (image->IsImageGrayScale() && image->GetBitsPerPixel() == 24 && image->HasAlphaChannel()) || (image->IsImageColored() && image->GetBitsPerPixel() == 48 && !image->HasAlphaChannel()) || (image->IsImageColored() && image->GetBitsPerPixel() == 64 && image->HasAlphaChannel())) { TP_ERROR(Log::WindowIconPrefix, "\"", m_data.Title, "\" Images with short pixel data are not supported for window icons!"); TP_WARN(Log::WindowIconPrefix, "\"", m_data.Title, "\" Using Default Icon!"); SetIcon(); return; } if (image->GetColorFormat() != Image::ColorFormat::RGBA && image->GetColorFormat() != Image::ColorFormat::RGB) { TP_ERROR(Log::WindowIconPrefix, "\"", m_data.Title, "\" Only RGBA Images are supported for window icons!"); TP_WARN(Log::WindowIconPrefix, "\"", m_data.Title, "\" Using Default Icon!"); SetIcon(); return; } INTERNAL::WindowingAPI::SetWindowIcon(m_window.get(), image); } //-------------------------------------------------------------------------------------------------------------------// void TRAP::Window::SetEventCallback(const EventCallbackFn& callback) { m_data.EventCallback = callback; } //-------------------------------------------------------------------------------------------------------------------// void TRAP::Window::SetResizable(const bool enabled) const { TP_PROFILE_FUNCTION(); INTERNAL::WindowingAPI::SetWindowHint(m_window.get(), INTERNAL::WindowingAPI::Hint::Resizable, enabled); } //-------------------------------------------------------------------------------------------------------------------// void TRAP::Window::SetMinimumSize(const uint32_t minWidth, const uint32_t minHeight) const { TP_PROFILE_FUNCTION(); if (minWidth == 0 && minHeight == 0) INTERNAL::WindowingAPI::SetWindowSizeLimits(m_window.get(), -1, -1, -1, -1); else INTERNAL::WindowingAPI::SetWindowSizeLimits(m_window.get(), minWidth, minHeight, -1, -1); } //-------------------------------------------------------------------------------------------------------------------// void TRAP::Window::SetMaximumSize(const uint32_t maxWidth, const uint32_t maxHeight) const { TP_PROFILE_FUNCTION(); if (maxWidth == 0 && maxHeight == 0) INTERNAL::WindowingAPI::SetWindowSizeLimits(m_window.get(), -1, -1, -1, -1); else INTERNAL::WindowingAPI::SetWindowSizeLimits(m_window.get(), -1, -1, maxWidth, maxHeight); } //-------------------------------------------------------------------------------------------------------------------// void TRAP::Window::SetOpacity(const float opacity) const { TP_PROFILE_FUNCTION(); if(opacity >= 0.0f || opacity <= 1.0f) INTERNAL::WindowingAPI::SetWindowOpacity(m_window.get(), opacity); else TP_ERROR(Log::WindowPrefix, "Invalid Window Opacity: ", opacity, "! Valid Range: 0.0 - 1.0f"); } //-------------------------------------------------------------------------------------------------------------------// void TRAP::Window::SetDragAndDrop(bool enabled) const { TP_PROFILE_FUNCTION(); INTERNAL::WindowingAPI::SetDragAndDrop(m_window.get(), enabled); } //-------------------------------------------------------------------------------------------------------------------// bool TRAP::Window::IsMaximized() const { TP_PROFILE_FUNCTION(); return INTERNAL::WindowingAPI::GetWindowHint(m_window.get(), INTERNAL::WindowingAPI::Hint::Maximized); } //-------------------------------------------------------------------------------------------------------------------// bool TRAP::Window::IsMinimized() const { TP_PROFILE_FUNCTION(); return INTERNAL::WindowingAPI::GetWindowHint(m_window.get(), INTERNAL::WindowingAPI::Hint::Minimized); } //-------------------------------------------------------------------------------------------------------------------// bool TRAP::Window::IsResizable() const { TP_PROFILE_FUNCTION(); return INTERNAL::WindowingAPI::GetWindowHint(m_window.get(), INTERNAL::WindowingAPI::Hint::Resizable); } //-------------------------------------------------------------------------------------------------------------------// bool TRAP::Window::IsVisible() const { TP_PROFILE_FUNCTION(); return INTERNAL::WindowingAPI::GetWindowHint(m_window.get(), INTERNAL::WindowingAPI::Hint::Visible); } //-------------------------------------------------------------------------------------------------------------------// bool TRAP::Window::IsFocused() const { TP_PROFILE_FUNCTION(); return INTERNAL::WindowingAPI::GetWindowHint(m_window.get(), INTERNAL::WindowingAPI::Hint::Focused); } //-------------------------------------------------------------------------------------------------------------------// bool TRAP::Window::IsDecorated() const { TP_PROFILE_FUNCTION(); return INTERNAL::WindowingAPI::GetWindowHint(m_window.get(), INTERNAL::WindowingAPI::Hint::Decorated); } //-------------------------------------------------------------------------------------------------------------------// void TRAP::Window::Maximize() const { TP_PROFILE_FUNCTION(); if(m_data.displayMode == DisplayMode::Windowed) INTERNAL::WindowingAPI::MaximizeWindow(m_window.get()); } //-------------------------------------------------------------------------------------------------------------------// void TRAP::Window::Minimize() const { TP_PROFILE_FUNCTION(); INTERNAL::WindowingAPI::MinimizeWindow(m_window.get()); } //-------------------------------------------------------------------------------------------------------------------// void TRAP::Window::RequestAttention() const { TP_PROFILE_FUNCTION(); INTERNAL::WindowingAPI::RequestWindowAttention(m_window.get()); } //-------------------------------------------------------------------------------------------------------------------// void TRAP::Window::Focus() const { TP_PROFILE_FUNCTION(); INTERNAL::WindowingAPI::FocusWindow(m_window.get()); } //-------------------------------------------------------------------------------------------------------------------// void TRAP::Window::Hide() const { TP_PROFILE_FUNCTION(); INTERNAL::WindowingAPI::HideWindow(m_window.get()); } //-------------------------------------------------------------------------------------------------------------------// void TRAP::Window::Show() const { TP_PROFILE_FUNCTION(); INTERNAL::WindowingAPI::ShowWindow(m_window.get()); } //-------------------------------------------------------------------------------------------------------------------// void TRAP::Window::Restore() const { TP_PROFILE_FUNCTION(); INTERNAL::WindowingAPI::RestoreWindow(m_window.get()); } //-------------------------------------------------------------------------------------------------------------------// void WindowingAPIErrorCallback(const TRAP::INTERNAL::WindowingAPI::Error error, const std::string& description) { if(error != TRAP::INTERNAL::WindowingAPI::Error::No_Error) TP_ERROR(TRAP::Log::WindowInternalPrefix, description); } //-------------------------------------------------------------------------------------------------------------------// void TRAP::Window::Init(const WindowProps& props) { m_data.Title = props.Title; m_data.Width = props.Width; m_data.Height = props.Height; m_data.RefreshRate = props.RefreshRate; m_data.VSync = props.Advanced.VSync; m_data.Monitor = props.Monitor; m_data.cursorMode = props.Advanced.CursorMode; m_data.RawMouseInput = props.Advanced.RawMouseInput; m_data.windowModeParams = &m_oldWindowedParams; if (!s_WindowingAPIInitialized) { const int32_t success = INTERNAL::WindowingAPI::Init(); TRAP_CORE_ASSERT(success, "Could not initialize WindowingAPI!"); if (!success) Utils::Dialogs::MsgBox::Show("Could not initialize WindowingAPI!", "Error WindowingAPI", Utils::Dialogs::MsgBox::Style::Error, Utils::Dialogs::MsgBox::Buttons::Quit); INTERNAL::WindowingAPI::SetErrorCallback(WindowingAPIErrorCallback); s_WindowingAPIInitialized = true; Graphics::API::Context::CheckAllRenderAPIs(); } if(s_fullscreenWindows.empty()) { const auto monitors = INTERNAL::WindowingAPI::GetMonitors(); s_fullscreenWindows.resize(monitors.size()); } const auto monitors = INTERNAL::WindowingAPI::GetMonitors(); if (props.Monitor < static_cast<uint32_t>(monitors.size())) m_useMonitor = monitors[props.Monitor]; else { TP_ERROR(Log::WindowPrefix, "\"", m_data.Title, "\" Invalid Monitor!"); TP_WARN(Log::WindowPrefix, "\"", m_data.Title, "\" Using Primary Monitor!"); m_data.Monitor = 0; m_useMonitor = INTERNAL::WindowingAPI::GetPrimaryMonitor().get(); } if(s_baseVideoModes.empty()) for(uint32_t i = 0; i < monitors.size(); i++) { s_baseVideoModes[i] = INTERNAL::WindowingAPI::GetVideoMode(monitors[i]); TP_DEBUG(Log::WindowPrefix, "Storing underlying OS video mode: Monitor: ", i, " ", s_baseVideoModes[i].Width, 'x', s_baseVideoModes[i].Height, '@', s_baseVideoModes[i].RefreshRate, "Hz (R", s_baseVideoModes[i].RedBits, 'G', s_baseVideoModes[i].GreenBits, 'B', s_baseVideoModes[i].BlueBits, ')'); } INTERNAL::WindowingAPI::DefaultWindowHints(); if (!s_windows) { if (props.RenderAPI == Graphics::API::RenderAPI::NONE) Graphics::API::Context::AutoSelectRenderAPI(); else { if (Graphics::API::Context::IsSupported(props.RenderAPI)) Graphics::API::Context::SetRenderAPI(props.RenderAPI); else { if (Graphics::API::Context::IsVulkanCapable()) Graphics::API::Context::SetRenderAPI(Graphics::API::RenderAPI::Vulkan); else if (Graphics::API::Context::IsOpenGLCapable()) Graphics::API::Context::SetRenderAPI(Graphics::API::RenderAPI::OpenGL); else { //All RenderAPIs are unsupported TRAP::Utils::Dialogs::MsgBox::Show("Every RenderAPI that TRAP Engine uses is unsupported on your device!\nDoes your system meet the minimum system requirements for running TRAP Engine?", "Incompatible Device", Utils::Dialogs::MsgBox::Style::Error, Utils::Dialogs::MsgBox::Buttons::Quit); exit(-1); } } } if (Graphics::API::Context::GetRenderAPI() != Graphics::API::RenderAPI::OpenGL) INTERNAL::WindowingAPI::SetContextAPI(INTERNAL::WindowingAPI::ContextAPI::None); if (Graphics::API::Context::GetRenderAPI() == Graphics::API::RenderAPI::OpenGL) INTERNAL::WindowingAPI::SetContextAPI(INTERNAL::WindowingAPI::ContextAPI::OpenGL); } #if defined(TRAP_DEBUG) if (Graphics::API::Context::GetRenderAPI() == Graphics::API::RenderAPI::OpenGL) INTERNAL::WindowingAPI::WindowHint(INTERNAL::WindowingAPI::Hint::OpenGLDebugContext, true); #endif if (props.DisplayMode == DisplayMode::Windowed) { if(props.Advanced.Maximized) INTERNAL::WindowingAPI::WindowHint(INTERNAL::WindowingAPI::Hint::Maximized, true); if (!props.Advanced.Resizable) INTERNAL::WindowingAPI::WindowHint(INTERNAL::WindowingAPI::Hint::Resizable, false); if (!props.Advanced.Visible) INTERNAL::WindowingAPI::WindowHint(INTERNAL::WindowingAPI::Hint::Visible, false); if (!props.Advanced.Decorated) INTERNAL::WindowingAPI::WindowHint(INTERNAL::WindowingAPI::Hint::Decorated, false); if (!props.Advanced.Focused && !props.Advanced.Visible) INTERNAL::WindowingAPI::WindowHint(INTERNAL::WindowingAPI::Hint::Focused, false); } if (!props.Advanced.FocusOnShow) INTERNAL::WindowingAPI::WindowHint(INTERNAL::WindowingAPI::Hint::FocusOnShow, false); if(s_windows >= 1 && Graphics::API::Context::GetRenderAPI() == Graphics::API::RenderAPI::Vulkan) INTERNAL::WindowingAPI::SetContextAPI(INTERNAL::WindowingAPI::ContextAPI::None); //Create Window #ifndef TRAP_RELEASE std::string newTitle = m_data.Title + " - TRAP Engine V" + std::to_string(TRAP_VERSION_MAJOR(TRAP_VERSION)) + "." + std::to_string(TRAP_VERSION_MINOR(TRAP_VERSION)) + "." + std::to_string(TRAP_VERSION_PATCH(TRAP_VERSION)) + "[INDEV]" + Log::WindowVersion; #else const std::string newTitle = m_data.Title; #endif m_window = INTERNAL::WindowingAPI::CreateWindow(static_cast<int32_t>(props.Width), static_cast<int32_t>(props.Height), newTitle, nullptr, nullptr); if (!m_window) { TP_CRITICAL(Log::WindowPrefix, "Failed to create window"); TRAP::Utils::Dialogs::MsgBox::Show("Failed to create Window!", "Failed to Create Window", Utils::Dialogs::MsgBox::Style::Error, Utils::Dialogs::MsgBox::Buttons::Quit); exit(-1); } INTERNAL::WindowingAPI::GetWindowSize(m_window.get(), m_data.Width, m_data.Height); if (!s_windows) { //Create Context & Initialize Renderer Graphics::API::Context::Create(this); Graphics::API::RendererAPI::Init(); Graphics::API::Context::SetVSyncInterval(props.Advanced.VSync); } s_windows++; if (s_windows > 1) { Graphics::API::Context::Use(this); SetVSyncInterval(props.Advanced.VSync); } //Update Window Title #ifndef TRAP_RELEASE newTitle += Graphics::Renderer::GetTitle(); #endif #ifdef TRAP_PLATFORM_LINUX if (Application::GetLinuxWindowManager() == Application::LinuxWindowManager::Wayland) newTitle += "[Wayland]"; else if (Application::GetLinuxWindowManager() == Application::LinuxWindowManager::X11) newTitle += "[X11]"; else newTitle += "[Unknown]"; #endif INTERNAL::WindowingAPI::SetWindowTitle(m_window.get(), newTitle); int32_t width = 0, height = 0, refreshRate = 0; //If currently windowed, stash the current size and position of the window if (m_data.displayMode == DisplayMode::Windowed) { m_oldWindowedParams.Width = m_data.Width; m_oldWindowedParams.Height = m_data.Height; m_oldWindowedParams.RefreshRate = m_data.RefreshRate; INTERNAL::WindowingAPI::GetWindowPos(m_window.get(), m_oldWindowedParams.XPos, m_oldWindowedParams.YPos); } INTERNAL::WindowingAPI::InternalMonitor* monitor = nullptr; if (props.DisplayMode == DisplayMode::Borderless) { if (s_fullscreenWindows[m_data.Monitor]) { TP_ERROR(Log::WindowPrefix, "\"", m_data.Title, "\" couldn't set DisplayMode to Borderless because Monitor: ", m_data.Monitor, '(', INTERNAL::WindowingAPI::GetMonitorName(m_useMonitor), ')', " is already used by Window: \"", s_fullscreenWindows[m_data.Monitor]->GetTitle(), "\"!"); TP_WARN(Log::WindowPrefix, "\"", m_data.Title, "\" is now using DisplayMode Windowed!"); m_data.displayMode = DisplayMode::Windowed; width = 800; height = 600; refreshRate = s_baseVideoModes[m_data.Monitor].RefreshRate; } else { s_fullscreenWindows[m_data.Monitor] = this; //For borderless fullscreen, the new width, height and refresh rate will be the video mode width, height and refresh rate width = s_baseVideoModes[m_data.Monitor].Width; height = s_baseVideoModes[m_data.Monitor].Height; refreshRate = s_baseVideoModes[m_data.Monitor].RefreshRate; monitor = m_useMonitor; } } else if (props.DisplayMode == DisplayMode::Windowed) { width = m_oldWindowedParams.Width; height = m_oldWindowedParams.Height; refreshRate = m_oldWindowedParams.RefreshRate; } else if (props.DisplayMode == DisplayMode::Fullscreen) { if (s_fullscreenWindows[m_data.Monitor]) { TP_ERROR(Log::WindowPrefix, "\"", m_data.Title, "\" couldn't set DisplayMode to Fullscreen because Monitor: ", m_data.Monitor, '(', INTERNAL::WindowingAPI::GetMonitorName(m_useMonitor), ')', " is already used by Window: \"", s_fullscreenWindows[m_data.Monitor]->GetTitle(), "\"!"); TP_WARN(Log::WindowPrefix, "\"", m_data.Title, "\" is now using DisplayMode Windowed!"); m_data.displayMode = DisplayMode::Windowed; width = 800; height = 600; refreshRate = s_baseVideoModes[m_data.Monitor].RefreshRate; } else { s_fullscreenWindows[m_data.Monitor] = this; monitor = m_useMonitor; bool valid = false; const auto monitorVideoModes = INTERNAL::WindowingAPI::GetVideoModes(m_useMonitor); if (width != 0 && height != 0 && refreshRate != 0) { for (const auto& monitorVideoMode : monitorVideoModes) { //Check if resolution pair is valid if ((monitorVideoMode.Width == width && monitorVideoMode.Height == height) && monitorVideoMode.RefreshRate == refreshRate) { valid = true; break; } if (s_baseVideoModes[m_data.Monitor].Width == width && s_baseVideoModes[m_data.Monitor].Height == height && s_baseVideoModes[m_data.Monitor].RefreshRate == refreshRate) { valid = true; break; } } } //Resolution pair is invalid so use native/default resolution if (!valid) { width = s_baseVideoModes[m_data.Monitor].Width; height = s_baseVideoModes[m_data.Monitor].Height; refreshRate = s_baseVideoModes[m_data.Monitor].RefreshRate; } } } //Update stored width and height m_data.Width = width; m_data.Height = height; m_data.RefreshRate = refreshRate; //Record new window type m_data.displayMode = props.DisplayMode; if (m_data.displayMode == DisplayMode::Borderless) INTERNAL::WindowingAPI::SetWindowMonitorBorderless(m_window.get(), monitor); else { INTERNAL::WindowingAPI::SetWindowMonitor(m_window.get(), monitor, m_oldWindowedParams.XPos, m_oldWindowedParams.YPos, width, height, refreshRate); } INTERNAL::WindowingAPI::GetFrameBufferSize(m_window.get(), width, height); //Set Refresh Rate to the current used VideoMode to prevent RefreshRate = 0 inside Engine.cfg if(m_data.displayMode == DisplayMode::Windowed) { const INTERNAL::WindowingAPI::InternalVideoMode videoMode = INTERNAL::WindowingAPI::GetVideoMode(INTERNAL::WindowingAPI::GetMonitors()[m_data.Monitor]); m_data.RefreshRate = videoMode.RefreshRate; } Graphics::RenderCommand::SetViewport(0, 0, width, height); INTERNAL::WindowingAPI::SetWindowUserPointer(m_window.get(), &m_data); SetIcon(); if (m_data.cursorMode == CursorMode::Normal) INTERNAL::WindowingAPI::SetCursorMode(m_window.get(), INTERNAL::WindowingAPI::CursorMode::Normal); else if (m_data.cursorMode == CursorMode::Hidden) INTERNAL::WindowingAPI::SetCursorMode(m_window.get(), INTERNAL::WindowingAPI::CursorMode::Hidden); else if (m_data.cursorMode == CursorMode::Disabled) INTERNAL::WindowingAPI::SetCursorMode(m_window.get(), INTERNAL::WindowingAPI::CursorMode::Disabled); if (Input::IsRawMouseInputSupported()) INTERNAL::WindowingAPI::SetRawMouseMotionMode(m_window.get(), m_data.RawMouseInput); else { TP_ERROR(Log::WindowPrefix, "\"", m_data.Title, "\" Raw Mouse Input is unsupported!"); m_data.RawMouseInput = false; } //Set WindowingAPI callbacks INTERNAL::WindowingAPI::SetWindowSizeCallback(m_window.get(), [](const INTERNAL::WindowingAPI::InternalWindow* window, const int32_t w, const int32_t h) { WindowData& data = *static_cast<WindowData*>(INTERNAL::WindowingAPI::GetWindowUserPointer(window)); data.Width = w; data.Height = h; if (!data.EventCallback) return; Events::WindowResizeEvent event(w, h, data.Title); data.EventCallback(event); }); INTERNAL::WindowingAPI::SetWindowMinimizeCallback(m_window.get(), [](const INTERNAL::WindowingAPI::InternalWindow* window, bool restored) { WindowData& data = *static_cast<WindowData*>(INTERNAL::WindowingAPI::GetWindowUserPointer(window)); if (!data.EventCallback) return; if (restored) { Events::WindowRestoreEvent event(data.Title); data.EventCallback(event); } else { Events::WindowMinimizeEvent event(data.Title); data.EventCallback(event); } }); INTERNAL::WindowingAPI::SetWindowMaximizeCallback(m_window.get(), [](const INTERNAL::WindowingAPI::InternalWindow* window, bool restored) { WindowData& data = *static_cast<WindowData*>(INTERNAL::WindowingAPI::GetWindowUserPointer(window)); if (!data.EventCallback) return; if (restored) { Events::WindowRestoreEvent event(data.Title); data.EventCallback(event); } else { Events::WindowMaximizeEvent event(data.Title); data.EventCallback(event); } }); INTERNAL::WindowingAPI::SetWindowPosCallback(m_window.get(), [](const INTERNAL::WindowingAPI::InternalWindow* window, const int32_t x, const int32_t y) { WindowData& data = *static_cast<WindowData*>(INTERNAL::WindowingAPI::GetWindowUserPointer(window)); if(data.displayMode == DisplayMode::Windowed) { data.windowModeParams->XPos = x; data.windowModeParams->YPos = y; } if (!data.EventCallback) return; Events::WindowMoveEvent event(x, y, data.Title); data.EventCallback(event); }); INTERNAL::WindowingAPI::SetWindowFocusCallback(m_window.get(), [](const INTERNAL::WindowingAPI::InternalWindow* window, const bool focused) { WindowData& data = *static_cast<WindowData*>(INTERNAL::WindowingAPI::GetWindowUserPointer(window)); if (!data.EventCallback) return; if (focused) { Events::WindowFocusEvent event(data.Title); data.EventCallback(event); } else { Events::WindowLostFocusEvent event(data.Title); data.EventCallback(event); } }); INTERNAL::WindowingAPI::SetWindowCloseCallback(m_window.get(), [](const INTERNAL::WindowingAPI::InternalWindow* window) { WindowData& data = *static_cast<WindowData*>(INTERNAL::WindowingAPI::GetWindowUserPointer(window)); if (!data.EventCallback) return; Events::WindowCloseEvent event(data.Title); data.EventCallback(event); }); INTERNAL::WindowingAPI::SetKeyCallback(m_window.get(), [](const INTERNAL::WindowingAPI::InternalWindow* window, const Input::Key key, const bool pressed) { WindowData& data = *static_cast<WindowData*>(INTERNAL::WindowingAPI::GetWindowUserPointer(window)); if(pressed) { if(data.KeyRepeatCounts.find(static_cast<uint16_t>(key)) == data.KeyRepeatCounts.end()) { data.KeyRepeatCounts[static_cast<uint16_t>(key)] = 0; if (!data.EventCallback) return; Events::KeyPressEvent event(static_cast<Input::Key>(key), 0, data.Title); data.EventCallback(event); } else { data.KeyRepeatCounts[static_cast<uint16_t>(key)]++; if (!data.EventCallback) return; Events::KeyPressEvent event(static_cast<Input::Key>(key), data.KeyRepeatCounts[static_cast<uint16_t>(key)], data.Title); data.EventCallback(event); } } else { data.KeyRepeatCounts.erase(static_cast<uint16_t>(key)); if (!data.EventCallback) return; Events::KeyReleaseEvent event(static_cast<Input::Key>(key), data.Title); data.EventCallback(event); } }); INTERNAL::WindowingAPI::SetCharCallback(m_window.get(), [](const INTERNAL::WindowingAPI::InternalWindow* window, const uint32_t codePoint) { WindowData& data = *static_cast<WindowData*>(INTERNAL::WindowingAPI::GetWindowUserPointer(window)); if (!data.EventCallback) return; Events::KeyTypeEvent event(codePoint, data.Title); data.EventCallback(event); }); INTERNAL::WindowingAPI::SetMouseButtonCallback(m_window.get(), [](const INTERNAL::WindowingAPI::InternalWindow* window, const Input::MouseButton button, const bool pressed) { WindowData& data = *static_cast<WindowData*>(INTERNAL::WindowingAPI::GetWindowUserPointer(window)); if (!data.EventCallback) return; if (pressed) { Events::MouseButtonPressEvent event(static_cast<Input::MouseButton>(button), data.Title); data.EventCallback(event); } else { Events::MouseButtonReleaseEvent event(static_cast<Input::MouseButton>(button), data.Title); data.EventCallback(event); } }); INTERNAL::WindowingAPI::SetScrollCallback(m_window.get(), [](const INTERNAL::WindowingAPI::InternalWindow* window, const double xOffset, const double yOffset) { WindowData& data = *static_cast<WindowData*>(INTERNAL::WindowingAPI::GetWindowUserPointer(window)); if (!data.EventCallback) return; Events::MouseScrollEvent event(static_cast<float>(xOffset), static_cast<float>(yOffset), data.Title); data.EventCallback(event); }); INTERNAL::WindowingAPI::SetCursorPosCallback(m_window.get(), [](const INTERNAL::WindowingAPI::InternalWindow* window, const double xPos, const double yPos) { WindowData& data = *static_cast<WindowData*>(INTERNAL::WindowingAPI::GetWindowUserPointer(window)); if (!data.EventCallback) return; Events::MouseMoveEvent event(static_cast<float>(xPos), static_cast<float>(yPos), data.Title); data.EventCallback(event); }); INTERNAL::WindowingAPI::SetFrameBufferSizeCallback(m_window.get(), [](const INTERNAL::WindowingAPI::InternalWindow* window, const int32_t w, const int32_t h) { WindowData& data = *static_cast<WindowData*>(INTERNAL::WindowingAPI::GetWindowUserPointer(window)); data.Width = w; data.Height = h; if (!data.EventCallback) return; Events::FrameBufferResizeEvent event(w, h, data.Title); data.EventCallback(event); }); INTERNAL::WindowingAPI::SetCursorEnterCallback(m_window.get(), [](const INTERNAL::WindowingAPI::InternalWindow* window, const bool entered) { WindowData& data = *static_cast<WindowData*>(INTERNAL::WindowingAPI::GetWindowUserPointer(window)); if (!data.EventCallback) return; if (entered) { Events::MouseEnterEvent event(data.Title); data.EventCallback(event); } else { Events::MouseLeaveEvent event(data.Title); data.EventCallback(event); } }); INTERNAL::WindowingAPI::SetDropCallback(m_window.get(), [](const INTERNAL::WindowingAPI::InternalWindow* window, std::vector<std::string> paths) { WindowData& data = *static_cast<WindowData*>(INTERNAL::WindowingAPI::GetWindowUserPointer(window)); if (!data.EventCallback) return; Events::WindowDropEvent event(std::move(paths), data.Title); data.EventCallback(event); }); INTERNAL::WindowingAPI::SetContentScaleCallback(m_window.get(), [](const INTERNAL::WindowingAPI::InternalWindow* window, const float xScale, const float yScale) { WindowData& data = *static_cast<WindowData*>(INTERNAL::WindowingAPI::GetWindowUserPointer(window)); if (!data.EventCallback) return; Events::WindowContentScaleEvent event(xScale, yScale, data.Title); data.EventCallback(event); }); INTERNAL::WindowingAPI::SetMonitorCallback([](const INTERNAL::WindowingAPI::InternalMonitor* mon, const bool connected) { if(!connected && Monitor::GetAllMonitors().size() == 1) { TP_ERROR(Log::WindowPrefix, "No Monitor Found!"); TP_ERROR(Log::WindowPrefix, "Closing TRAP!"); std::exit(0); } if (mon->Window) { WindowData& data = *static_cast<WindowData*>(INTERNAL::WindowingAPI::GetWindowUserPointer(mon->Window)); for (const auto& win : s_fullscreenWindows) { if (win) { Window& window = *win; if (window.m_useMonitor == mon) { const auto removeWindowIterator = s_fullscreenWindows.begin() + window.m_data.Monitor; if(removeWindowIterator != std::end(s_fullscreenWindows)) { *removeWindowIterator = s_fullscreenWindows.back(); s_fullscreenWindows.pop_back(); } window.m_data.Monitor = 0; window.m_useMonitor = static_cast<INTERNAL::WindowingAPI::InternalMonitor*>(Monitor::GetPrimaryMonitor().GetInternalMonitor()); window.Restore(); window.SetDisplayMode(DisplayMode::Windowed, window.GetWidth(), window.GetHeight(), window.GetRefreshRate()); break; } } } if (!data.EventCallback) return; for (const auto& m : Monitor::GetAllMonitors()) { if (mon == m.GetInternalMonitor()) { if (connected) { Events::MonitorConnectEvent event(m); data.EventCallback(event); } else { Events::MonitorDisconnectEvent event(m); data.EventCallback(event); } return; } } } }); if (s_windows > 1) Use(); } //-------------------------------------------------------------------------------------------------------------------// void TRAP::Window::Shutdown() { TP_PROFILE_FUNCTION(); INTERNAL::WindowingAPI::DestroyWindow(std::move(m_window)); m_window = nullptr; if (!s_windows) { INTERNAL::WindowingAPI::Shutdown(); s_WindowingAPIInitialized = false; } } //-------------------------------------------------------------------------------------------------------------------// TRAP::WindowProps::WindowProps(std::string title, const uint32_t width, const uint32_t height, const uint32_t refreshRate, const Window::DisplayMode displayMode, AdvancedProps advanced, const uint32_t monitor) : Title(std::move(title)), Width(width), Height(height), RefreshRate(refreshRate), RenderAPI(Graphics::API::Context::GetRenderAPI()), DisplayMode(displayMode), Monitor(monitor), Advanced{advanced} { TP_PROFILE_FUNCTION(); } //-------------------------------------------------------------------------------------------------------------------// TRAP::WindowProps::AdvancedProps::AdvancedProps(const uint32_t VSync, const bool resizable, const bool maximized, const bool visible, const bool focused, const bool focusOnShow, const bool decorated, const bool rawMouseInput, const Window::CursorMode cursorMode) : VSync(VSync), Resizable(resizable), Maximized(maximized), Visible(visible), Focused(focused), FocusOnShow(focusOnShow), Decorated(decorated), RawMouseInput(rawMouseInput), CursorMode(cursorMode) { TP_PROFILE_FUNCTION(); }
34.221444
191
0.613384
GamesTrap
8eafd5d12cd87556dd1666e2b899d36b594ecb04
1,080
cpp
C++
tests/multi_aggregator_suite.cpp
mambaru/wrtstat
d97bf5376c14181974d6eb4632053710bb75cca8
[ "MIT" ]
1
2018-03-16T21:21:23.000Z
2018-03-16T21:21:23.000Z
tests/multi_aggregator_suite.cpp
mambaru/wrtstat
d97bf5376c14181974d6eb4632053710bb75cca8
[ "MIT" ]
10
2019-12-04T20:44:19.000Z
2021-04-20T21:51:50.000Z
tests/multi_aggregator_suite.cpp
mambaru/wrtstat
d97bf5376c14181974d6eb4632053710bb75cca8
[ "MIT" ]
null
null
null
#include <fas/testing.hpp> #include <wrtstat/aggregator/aggregator.hpp> #include <wrtstat/multi_aggregator/multi_aggregator.hpp> #include <numeric> namespace { UNIT(multi_aggregator1, "") { using namespace fas::testing; using namespace wrtstat; multi_aggregator_options opt; opt.resolution = resolutions::nanoseconds; opt.soiled_start_ts = 1000000000; opt.reducer_levels = 1; opt.reducer_limit = 10; opt.aggregation_step_ts = 500000000; opt.outgoing_reduced_size = 13; multi_aggregator agh(opt); reduced_data rd; bool run = true; size_t while_count = 0; size_t ag_count = 0; while(run) { rd.ts=aggregator::now_t<std::chrono::nanoseconds>(); rd.count = 1; agh.push("xxx", rd, [&run, &t, &ag_count]( request::push::ptr ag) { ag_count = ag->count; t << message("aggregator") << " cout=" << ag->count; run = false; }); if (run) ++while_count; } t << equal<expect>( while_count, ag_count) << FAS_FL; } } BEGIN_SUITE(multi_aggregator, "") ADD_UNIT(multi_aggregator1) END_SUITE(multi_aggregator)
23.478261
69
0.680556
mambaru
8eb1f6f1af6acb0a8da877183b9cdd374b23330d
1,762
hpp
C++
assignment-8 Indexing/Tokenizer.hpp
Arda-Bati/RDBMS-Homeworks
e3b121b5d8587552cc7177228ba5a5bea5c2cf68
[ "Apache-2.0" ]
1
2021-04-01T23:45:48.000Z
2021-04-01T23:45:48.000Z
assignment-8 Indexing/Tokenizer.hpp
Arda-Bati/Relational-Database
e3b121b5d8587552cc7177228ba5a5bea5c2cf68
[ "Apache-2.0" ]
null
null
null
assignment-8 Indexing/Tokenizer.hpp
Arda-Bati/Relational-Database
e3b121b5d8587552cc7177228ba5a5bea5c2cf68
[ "Apache-2.0" ]
null
null
null
// // Tokenizer.hpp // Database3 // // Created by rick gessner on 3/19/19. // Copyright © 2019 rick gessner. All rights reserved. // #ifndef Tokenizer_hpp #define Tokenizer_hpp #include <stdio.h> #include <iostream> #include <string> #include <vector> #include "keywords.hpp" namespace ECE141 { using callback = bool(char aChar); enum class TokenType { comma=1, colon, semicolon, number, operators, apostrophe, lparen, rparen, lbracket, rbracket, lbrace, rbrace, slash, star, equal, plus, minus, keyword, identifier, function, string, unknown }; struct Token { Token(TokenType aType=TokenType::unknown, std::string aString="", Keywords aKW=Keywords::unknown_kw) : type(aType), keyword(aKW), data(aString) {} Token& operator=(const Token &aCopy) { type=aCopy.type; keyword=aCopy.keyword; data=aCopy.data; return *this; } TokenType type; Keywords keyword; std::string data; }; class Tokenizer { public: Tokenizer(std::istream &anInputStream); virtual StatusResult tokenize(); virtual Token& tokenAt(int anOffset); size_t size() {return tokens.size();} size_t remaining() {return index<size() ? size()-index :0;} virtual void restart() {index=0;} virtual bool more() {return index<size();} virtual bool next(int anOffset=1); virtual Token& peek(int anOffset=1); virtual Token& current(); protected: std::vector<Token> tokens; std::istream &input; int index; }; } #endif /* Tokenizer_hpp */
24.472222
91
0.580023
Arda-Bati
8eb9028f45d2c35a1e5a6a704700914a51dc6da6
3,341
cpp
C++
example.cpp
wingeng/ln
beb5c22762cc092b7f1aed977b6f8a57b51c4d4a
[ "BSD-2-Clause" ]
2
2016-07-06T23:07:03.000Z
2016-11-12T09:13:48.000Z
example.cpp
wingeng/ln
beb5c22762cc092b7f1aed977b6f8a57b51c4d4a
[ "BSD-2-Clause" ]
null
null
null
example.cpp
wingeng/ln
beb5c22762cc092b7f1aed977b6f8a57b51c4d4a
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (c) 2015, Wing Eng * All rights reserved. */ #include <functional> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "linenoise.h" #define UNUSED __attribute__((unused)) typedef void (*command_action_t)(const char *line); typedef struct command_s { const char *c_token; const char *c_help; command_action_t c_action; } command_t; /* * Syntax for declaring a function pointer * between the '<>' enter the return type and function * arguments. */ typedef std::function<void (command_t &)> complete_cb; static void help_cmd_action(const char *); static void quit_cmd_action(const char *); static void generic_cmd_action(const char *); command_t cmds[] = { { "hello", "help for hello", help_cmd_action }, { "helo", "help for helo", help_cmd_action }, { "joe", "help for joe", generic_cmd_action }, { "james", "help for james", generic_cmd_action }, { "quit", "quit from test", quit_cmd_action }, { "blah0", "help for blah0", generic_cmd_action }, { "blah1", "help for blah1", generic_cmd_action }, { "blah2", "help for blah2", generic_cmd_action }, { "blah3", "help for blah3", generic_cmd_action }, { "blah4", "help for blah4", generic_cmd_action }, { "blah5", "help for blah5", generic_cmd_action }, { "blah6", "help for blah6", generic_cmd_action }, { "blah7", "help for blah7", generic_cmd_action }, { "blah8", "help for blah8", generic_cmd_action }, { "blah9", "help for blah9", generic_cmd_action }, }; static void help_cmd_action (const char *line) { printf("help for '%s'\n", line); } static void generic_cmd_action (const char *line) { printf("generic for '%s'\n", line); } static void quit_cmd_action (const char *line UNUSED) { exit(0); } static int match_prefix (const char *whole, const char *partial) { return partial == NULL || strlen(partial) == 0 || strncmp(whole, partial, strlen(partial)) == 0; } static void command_match (const char *buf, complete_cb cb) { for (auto cmd : cmds) { if (match_prefix(cmd.c_token, buf)) cb(cmd); } } void call_command (const char *buf) { int n_commands = 0; command_action_t found_action = NULL; command_match(buf, [&] (command_t &cmd) { found_action = cmd.c_action; n_commands++; }); switch (n_commands) { case 0: printf("no commands matched\n"); break; case 1: found_action(buf); break; default: printf("More than one command matched\n"); break; } } int main () { char *line; linenoiseSetCompletionCallback([] (const char *buf, linenoiseCompletions *lc) { command_match(buf, [lc] (command_t &cmd) { linenoiseAddCompletion(lc, cmd.c_token, cmd.c_help); }); }); linenoiseHistoryLoad("history.txt"); /* * Now this is the main loop of the typical linenoise-based application. * The call to linenoise() will block as long as the user types something * and presses enter. * * The typed string is returned as a malloc() allocated string by * linenoise, so the user needs to free() it. */ while ((line = linenoise("computer> ")) != NULL) { if (strlen(line)) { call_command(line); linenoiseHistoryAdd(line); linenoiseHistorySave("history.txt"); } free(line); } return 0; }
23.695035
83
0.649506
wingeng
8ebbcd12401a1a7eb93ae5430f79ad30f3362f0d
2,073
cpp
C++
gingerrun/Font.cpp
TailonR/cs480GameDev
e47da20d76bd137bb2c0f44627e7fa0dcb968658
[ "MIT" ]
null
null
null
gingerrun/Font.cpp
TailonR/cs480GameDev
e47da20d76bd137bb2c0f44627e7fa0dcb968658
[ "MIT" ]
null
null
null
gingerrun/Font.cpp
TailonR/cs480GameDev
e47da20d76bd137bb2c0f44627e7fa0dcb968658
[ "MIT" ]
null
null
null
#include "Font.hpp" namespace GameLib { Font::Font(Context* context) : context_(context) {} Font::~Font() { if (font_) { TTF_CloseFont(font_); font_ = nullptr; } } bool Font::load(const std::string& filename, int ptsize) { std::string path = context_->findSearchPath(filename); font_ = TTF_OpenFont(path.c_str(), ptsize); return font_ != nullptr; } void Font::newRender() { if (texture_) { SDL_DestroyTexture(texture_); texture_ = nullptr; } if (surface_) { SDL_FreeSurface(surface_); surface_ = nullptr; } } int Font::calcWidth(const char* text) { int w{ 0 }; if (font_) TTF_SizeUTF8(font_, text, &w, nullptr); return w; } SDL_Texture* Font::render(const char* text, SDL_Color fg) { if (!font_) return nullptr; newRender(); surface_ = TTF_RenderText_Blended(font_, text, fg); if (surface_) { rect_.w = surface_->w; rect_.h = surface_->h; texture_ = SDL_CreateTextureFromSurface(context_->renderer(), surface_); } return texture_; } void Font::draw(int x, int y) { rect_.x = x; rect_.y = y; SDL_Renderer* renderer_ = context_->renderer(); SDL_RenderCopy(renderer_, texture_, nullptr, &rect_); } void Font::draw(int x, int y, const char* text, SDL_Color fg, int flags) { if (flags & HALIGN_CENTER) { x -= calcWidth(text) >> 1; } else if (flags & HALIGN_RIGHT) { x -= calcWidth(text); } if (flags & VALIGN_TOP) { } else if (flags & VALIGN_CENTER) { y -= calcHeight() >> 1; } else if (flags & VALIGN_BOTTOM) { y -= calcHeight(); } if (flags & SHADOWED) { render(text, Black); draw(x + 2, y + 2); } render(text, fg); draw(x, y); } }
26.576923
84
0.507477
TailonR
8ebfb36cc6118bbf6515219f3925333c9325503b
313
cpp
C++
doc/examples/02_basic_output.cpp
Expander/slhaea
6795fda55871d066b1d238378a1223321acf9ed1
[ "BSL-1.0" ]
3
2017-12-14T18:39:05.000Z
2019-05-04T16:08:45.000Z
doc/examples/02_basic_output.cpp
Expander/slhaea
6795fda55871d066b1d238378a1223321acf9ed1
[ "BSL-1.0" ]
5
2016-05-20T04:25:02.000Z
2021-10-16T12:17:58.000Z
doc/examples/02_basic_output.cpp
Expander/slhaea
6795fda55871d066b1d238378a1223321acf9ed1
[ "BSL-1.0" ]
null
null
null
#include <fstream> #include <slhaea.h> using namespace std; using namespace SLHAea; int main() { Coll input; ifstream ifs("slha1.txt"); ifs >> input; ifs.close(); input["MINPAR"][4][1] = "-1.0"; input["MINPAR"][3][2] = "# tan(beta)"; ofstream ofs("slha1.txt"); ofs << input; ofs.close(); }
14.227273
40
0.594249
Expander
8ec06b4e38e1f6a672ccc2c8681ea61f4023352d
313
hpp
C++
Framework/Ability/Intersectable.hpp
lishaojiang/GameEngineFromScratch
7769d3916a9ffabcfdaddeba276fdf964d8a86ee
[ "MIT" ]
1,217
2017-08-18T02:41:11.000Z
2022-03-30T01:48:46.000Z
Framework/Ability/Intersectable.hpp
lishaojiang/GameEngineFromScratch
7769d3916a9ffabcfdaddeba276fdf964d8a86ee
[ "MIT" ]
16
2017-09-05T15:04:37.000Z
2021-09-09T13:59:38.000Z
Framework/Ability/Intersectable.hpp
lishaojiang/GameEngineFromScratch
7769d3916a9ffabcfdaddeba276fdf964d8a86ee
[ "MIT" ]
285
2017-08-18T04:53:55.000Z
2022-03-30T00:02:15.000Z
#pragma once #include "Ability.hpp" #include "Ray.hpp" #include "Hit.hpp" namespace My { template <typename T> Ability Intersectable { public: virtual ~Intersectable() = default; using ParamType = const T; virtual bool Intersect(const Ray &r, Hit &h, float tmin) const = 0; }; } // namespace My
20.866667
72
0.680511
lishaojiang
8ec826a3dce0277319c98e5143f77c15023947c7
908
cpp
C++
tools/seec-view/HiddenExecuteAndWait_Generic.cpp
seec-team/seec
4b92456011e86b70f9d88833a95c1f655a21cf1a
[ "MIT" ]
7
2018-06-25T12:06:13.000Z
2022-01-18T09:20:13.000Z
tools/seec-view/HiddenExecuteAndWait_Generic.cpp
seec-team/seec
4b92456011e86b70f9d88833a95c1f655a21cf1a
[ "MIT" ]
20
2016-12-01T23:46:12.000Z
2019-08-11T02:41:04.000Z
tools/seec-view/HiddenExecuteAndWait_Generic.cpp
seec-team/seec
4b92456011e86b70f9d88833a95c1f655a21cf1a
[ "MIT" ]
1
2020-10-19T03:20:05.000Z
2020-10-19T03:20:05.000Z
//===- tools/seec-trace-view/HiddenExecuteAndWait_Generic.cpp -------------===// // // SeeC // // This file is distributed under The MIT License (MIT). See LICENSE.TXT for // details. // //===----------------------------------------------------------------------===// /// /// \file /// //===----------------------------------------------------------------------===// #include "llvm/Support/Program.h" #include "HiddenExecuteAndWait.hpp" int HiddenExecuteAndWait(llvm::StringRef Program, const char **Args, const char **EnvPtr, std::string *ErrorMsg, bool *ExecFailed) { return llvm::sys::ExecuteAndWait(Program, Args, EnvPtr, /* redirects */ {}, /* wait */ 0, /* mem */ 0, ErrorMsg, ExecFailed); }
32.428571
80
0.396476
seec-team
8ed023f9a20e9fbd064a2ec6d78f559268ec8a1c
623
cc
C++
assets/unzipper_provider.cc
alibitek/engine
0f0b144b0320d00d837fb2af80cd542ab1359491
[ "BSD-3-Clause" ]
null
null
null
assets/unzipper_provider.cc
alibitek/engine
0f0b144b0320d00d837fb2af80cd542ab1359491
[ "BSD-3-Clause" ]
null
null
null
assets/unzipper_provider.cc
alibitek/engine
0f0b144b0320d00d837fb2af80cd542ab1359491
[ "BSD-3-Clause" ]
1
2020-03-05T02:44:12.000Z
2020-03-05T02:44:12.000Z
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/assets/unzipper_provider.h" #include "lib/fxl/logging.h" #include "third_party/zlib/contrib/minizip/unzip.h" namespace blink { UnzipperProvider GetUnzipperProviderForPath(std::string zip_path) { return [zip_path]() { zip::UniqueUnzipper unzipper(unzOpen2(zip_path.c_str(), nullptr)); if (!unzipper.is_valid()) FXL_LOG(ERROR) << "Unable to open zip file: " << zip_path; return unzipper; }; } } // namespace blink
28.318182
73
0.723917
alibitek
8ed0e8a98dc9bce13f6c098d84e0fd263d1e607a
260
cpp
C++
base/part01/module/Vector.cpp
daheige/cpp-programming
fd04a81c9615544bc49efe137eccd806931fd09b
[ "MIT" ]
null
null
null
base/part01/module/Vector.cpp
daheige/cpp-programming
fd04a81c9615544bc49efe137eccd806931fd09b
[ "MIT" ]
null
null
null
base/part01/module/Vector.cpp
daheige/cpp-programming
fd04a81c9615544bc49efe137eccd806931fd09b
[ "MIT" ]
null
null
null
#include "Vector.h" // 引入header头 // 通过列式的方式进行参数初始化操作 // 构造方法实现 Vector::Vector (int s) : elem{ new double[s] // 初始化elem }, sz{s} {} // 重载操作符号[] double &Vector::operator[] (int i) { return elem[i]; } // size方法实现 int Vector::size () { return sz; }
16.25
54
0.596154
daheige
8ed729aabd5c592bcc1e1a45828f730b90f433df
2,907
cpp
C++
Source/StackOBot/Private/BOTDynamicCamera.cpp
ameyghan/StackOBotCPP
9ae9e7924d4ab20382b35c10981a2a4890d525ff
[ "MIT" ]
null
null
null
Source/StackOBot/Private/BOTDynamicCamera.cpp
ameyghan/StackOBotCPP
9ae9e7924d4ab20382b35c10981a2a4890d525ff
[ "MIT" ]
null
null
null
Source/StackOBot/Private/BOTDynamicCamera.cpp
ameyghan/StackOBotCPP
9ae9e7924d4ab20382b35c10981a2a4890d525ff
[ "MIT" ]
null
null
null
#include "BOTDynamicCamera.h" #include "Camera/CameraComponent.h" #include "Components/BoxComponent.h" #include "GameFramework/Character.h" #include "GameFramework/CharacterMovementComponent.h" #include "Kismet/GameplayStatics.h" ABOTDynamicCamera::ABOTDynamicCamera() { CameraRoot = CreateDefaultSubobject<USceneComponent>(TEXT("RootComponent")); RootComponent = CameraRoot; OverlapComponent = CreateDefaultSubobject<UBoxComponent>(TEXT("OverlapComponent")); OverlapComponent->SetCollisionProfileName("OverlapOnlyPawn"); OverlapComponent->SetBoxExtent(FVector(100.f)); OverlapComponent->SetupAttachment(GetRootComponent()); OverlapComponent->SetGenerateOverlapEvents(true); Camera = CreateDefaultSubobject<UCameraComponent>(TEXT("Camera")); Camera->SetupAttachment(GetRootComponent()); Camera->SetWorldScale3D(FVector(1.0f, 1.0f, 1.0f)); BlendTime = 2.0f; CameraBlendTimer = 3.0f; } void ABOTDynamicCamera::BeginPlay() { Super::BeginPlay(); /** Called when the character steps on the OverlapComponent (The box) */ OverlapComponent->OnComponentBeginOverlap.AddDynamic(this, &ABOTDynamicCamera::OnOverlapBegin); /** Called when the player leaves the OverlapComponent */ OverlapComponent->OnComponentEndOverlap.AddDynamic(this, &ABOTDynamicCamera::OnOverlapEnd); } void ABOTDynamicCamera::BlendCameraInAndOut(ACharacter* InCharacter, UCharacterMovementComponent* InCharacterMovement) { if (InCharacterMovement->IsWalking()) { InCharacterMovement->DisableMovement(); APlayerController* PlayerController = UGameplayStatics::GetPlayerController(this, 0); check(PlayerController); PlayerController->SetIgnoreLookInput(true); PlayerController->SetViewTargetWithBlend(this, BlendTime); FTimerHandle TimerHandle; GetWorldTimerManager().SetTimer(TimerHandle, FTimerDelegate::CreateLambda([=, &TimerHandle] { check(InCharacter); PlayerController->SetViewTargetWithBlend(InCharacter, CameraBlendTimer); GetWorldTimerManager().SetTimer(TimerHandle, FTimerDelegate::CreateLambda([=] { check(InCharacterMovement && PlayerController); InCharacterMovement->SetMovementMode(MOVE_Walking); PlayerController->SetIgnoreLookInput(false); }),CameraBlendTimer, false); }),CameraBlendTimer, false); } } void ABOTDynamicCamera::OnOverlapBegin(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult) { ACharacter* OverlappedCharacter = Cast<ACharacter>(OtherActor); UCharacterMovementComponent* CharacterMovement = OverlappedCharacter->GetCharacterMovement(); check(OverlappedCharacter && CharacterMovement); BlendCameraInAndOut(OverlappedCharacter, CharacterMovement); } void ABOTDynamicCamera::OnOverlapEnd(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex) { Destroy(); }
37.269231
202
0.806674
ameyghan
8ed88886856ba6d33f051fd9087d27ca5d7f2ebe
31,246
cpp
C++
src/game/g_spawn.cpp
jumptohistory/jaymod
92d0a0334ac27da94b12280b0b42b615b8813c23
[ "Apache-2.0" ]
25
2016-05-27T11:53:58.000Z
2021-10-17T00:13:41.000Z
src/game/g_spawn.cpp
jumptohistory/jaymod
92d0a0334ac27da94b12280b0b42b615b8813c23
[ "Apache-2.0" ]
1
2016-07-09T05:25:03.000Z
2016-07-09T05:25:03.000Z
src/game/g_spawn.cpp
jumptohistory/jaymod
92d0a0334ac27da94b12280b0b42b615b8813c23
[ "Apache-2.0" ]
16
2016-05-28T23:06:50.000Z
2022-01-26T13:47:12.000Z
/* * name: g_spawn.c * * desc: * */ #include <bgame/impl.h> qboolean G_SpawnStringExt( const char *key, const char *defaultString, char **out, const char* file, int line ) { int i; if ( !level.spawning ) { *out = (char *)defaultString; // Gordon: 26/11/02: re-enabling // see InitMover G_Error( "G_SpawnString() called while not spawning, file %s, line %i", file, line ); } for ( i = 0 ; i < level.numSpawnVars ; i++ ) { if ( !strcmp( key, level.spawnVars[i][0] ) ) { *out = level.spawnVars[i][1]; return qtrue; } } *out = (char *)defaultString; return qfalse; } qboolean G_SpawnFloatExt( const char *key, const char *defaultString, float *out, const char* file, int line ) { char *s; qboolean present; present = G_SpawnStringExt( key, defaultString, &s, file, line ); *out = atof( s ); return present; } qboolean G_SpawnIntExt( const char *key, const char *defaultString, int *out, const char* file, int line ) { char *s; qboolean present; present = G_SpawnStringExt( key, defaultString, &s, file, line ); *out = atoi( s ); return present; } qboolean G_SpawnVectorExt( const char *key, const char *defaultString, float *out, const char* file, int line ) { char *s; qboolean present; present = G_SpawnStringExt( key, defaultString, &s, file, line ); sscanf( s, "%f %f %f", &out[0], &out[1], &out[2] ); return present; } qboolean G_SpawnVector2DExt( const char *key, const char *defaultString, float *out, const char* file, int line ) { char *s; qboolean present; present = G_SpawnStringExt( key, defaultString, &s, file, line ); sscanf( s, "%f %f", &out[0], &out[1] ); return present; } // // fields are needed for spawning from the entity string // typedef enum { F_INT, F_FLOAT, F_LSTRING, // string on disk, pointer in memory, TAG_LEVEL F_GSTRING, // string on disk, pointer in memory, TAG_GAME F_VECTOR, F_ANGLEHACK, F_ENTITY, // index on disk, pointer in memory F_ITEM, // index on disk, pointer in memory F_CLIENT, // index on disk, pointer in memory F_IGNORE } fieldtype_t; typedef struct { char *name; int ofs; fieldtype_t type; int flags; } field_t; field_t fields[] = { {"classname", FOFS(classname), F_LSTRING}, {"origin", FOFS(s.origin), F_VECTOR}, {"model", FOFS(model), F_LSTRING}, {"model2", FOFS(model2), F_LSTRING}, {"spawnflags", FOFS(spawnflags), F_INT}, // Jaybird - etpro additions {"classname_nospawn",FOFS(classname),F_LSTRING}, {"contents", FOFS(r.contents), F_INT}, {"eflags", FOFS(s.eFlags), F_INT}, {"svflags", FOFS(r.svFlags), F_INT}, {"maxs", FOFS(r.maxs), F_VECTOR}, {"mins", FOFS(r.mins), F_VECTOR}, {"clipmask", FOFS(clipmask), F_INT}, {"count2", FOFS(count2), F_INT}, {"pos_trType", FOFS(s.pos.trType), F_INT}, {"pos_trDelta", FOFS(s.pos.trDelta),F_VECTOR}, {"apos_trType", FOFS(s.apos.trType),F_INT}, {"pos_trDelta", FOFS(s.apos.trDelta),F_VECTOR}, {"allowteams", FOFS(allowteams), F_INT}, {"speed", FOFS(speed), F_FLOAT}, {"closespeed", FOFS(closespeed), F_FLOAT}, //----(SA) added {"target", FOFS(target), F_LSTRING}, {"targetname", FOFS(targetname), F_LSTRING}, {"message", FOFS(message), F_LSTRING}, {"popup", FOFS(message), F_LSTRING}, // (SA) mutually exclusive from 'message', but makes the ent more logical for the level designer {"book", FOFS(message), F_LSTRING}, // (SA) mutually exclusive from 'message', but makes the ent more logical for the level designer {"team", FOFS(team), F_LSTRING}, {"wait", FOFS(wait), F_FLOAT}, {"random", FOFS(random), F_FLOAT}, {"count", FOFS(count), F_INT}, {"health", FOFS(health), F_INT}, {"light", 0, F_IGNORE}, {"dmg", FOFS(damage), F_INT}, {"angles", FOFS(s.angles), F_VECTOR}, {"angle", FOFS(s.angles), F_ANGLEHACK}, // JOSEPH 9-27-99 {"duration", FOFS(duration), F_FLOAT}, {"rotate", FOFS(rotate), F_VECTOR}, // END JOSEPH {"degrees", FOFS(angle), F_FLOAT}, {"time", FOFS(speed), F_FLOAT}, //----(SA) additional ai field {"skin", FOFS(aiSkin), F_LSTRING}, //----(SA) done // (SA) dlight lightstyles (made all these unique variables for testing) {"_color", FOFS(dl_color), F_VECTOR}, // color of the light (the underscore is inserted by the color picker in QER) {"color", FOFS(dl_color), F_VECTOR}, // color of the light {"stylestring", FOFS(dl_stylestring), F_LSTRING}, // user defined stylestring "fffndlsfaaaaaa" for example // done //----(SA) {"shader", FOFS(dl_shader), F_LSTRING}, // shader to use for a target_effect or dlight // (SA) for target_unlock {"key", FOFS(key), F_INT}, // done // Rafael - mg42 {"harc", FOFS(harc), F_FLOAT}, {"varc", FOFS(varc), F_FLOAT}, // done. // Rafael - sniper {"delay", FOFS(delay), F_FLOAT}, {"radius", FOFS(radius), F_INT}, // Ridah, for reloading savegames at correct mission spot {"missionlevel", FOFS(missionLevel), F_INT}, // Rafel {"start_size", FOFS (start_size), F_INT}, {"end_size", FOFS (end_size), F_INT}, {"shard", FOFS (count), F_INT}, // Rafael {"spawnitem", FOFS(spawnitem), F_LSTRING}, {"track", FOFS(track), F_LSTRING}, {"scriptName", FOFS(scriptName), F_LSTRING}, {"shortname", FOFS(message), F_LSTRING}, {"constages", FOFS(constages), F_LSTRING}, {"desstages", FOFS(desstages), F_LSTRING}, {"partofstage", FOFS(partofstage), F_INT}, {"override", FOFS(spawnitem), F_LSTRING}, {"damageparent", FOFS(damageparent), F_LSTRING}, {NULL} }; typedef struct { char *name; void (*spawn)(gentity_t *ent); } spawn_t; void SP_info_player_start (gentity_t *ent); void SP_info_player_checkpoint (gentity_t *ent); void SP_info_player_deathmatch (gentity_t *ent); void SP_info_player_intermission (gentity_t *ent); void SP_info_firstplace(gentity_t *ent); void SP_info_secondplace(gentity_t *ent); void SP_info_thirdplace(gentity_t *ent); void SP_info_podium(gentity_t *ent); void SP_func_plat (gentity_t *ent); void SP_func_static (gentity_t *ent); void SP_func_leaky(gentity_t *ent); //----(SA) added void SP_func_rotating (gentity_t *ent); void SP_func_bobbing (gentity_t *ent); void SP_func_pendulum( gentity_t *ent ); void SP_func_button (gentity_t *ent); void SP_func_explosive (gentity_t *ent); void SP_func_door (gentity_t *ent); void SP_func_train (gentity_t *ent); void SP_func_timer (gentity_t *self); // JOSEPH 1-26-00 void SP_func_train_rotating (gentity_t *ent); void SP_func_secret (gentity_t *ent); // END JOSEPH // Rafael void SP_func_door_rotating (gentity_t *ent); // RF void SP_func_constructible( gentity_t *ent ); void SP_func_brushmodel( gentity_t *ent ); void SP_misc_constructiblemarker( gentity_t *ent ); void SP_target_explosion( gentity_t *ent ); void SP_misc_landmine( gentity_t *ent ); void SP_trigger_always (gentity_t *ent); void SP_trigger_multiple (gentity_t *ent); void SP_trigger_push (gentity_t *ent); void SP_trigger_teleport (gentity_t *ent); void SP_trigger_hurt (gentity_t *ent); void SP_trigger_heal(gentity_t *ent); // xkan, 9/17/2002 void SP_trigger_ammo(gentity_t *ent); // xkan, 9/17/2002 // Gordon void SP_misc_cabinet_health(gentity_t* self); void SP_misc_cabinet_supply(gentity_t* self); //---- (SA) Wolf triggers void SP_trigger_concussive_dust(gentity_t *ent); // JPW NERVE void SP_trigger_once ( gentity_t *ent ); //---- done void SP_target_remove_powerups( gentity_t *ent ); void SP_target_give (gentity_t *ent); void SP_target_delay (gentity_t *ent); void SP_target_speaker (gentity_t *ent); void SP_target_print (gentity_t *ent); void SP_target_laser (gentity_t *self); void SP_target_character (gentity_t *ent); void SP_target_score( gentity_t *ent ); void SP_target_teleporter( gentity_t *ent ); void SP_target_relay (gentity_t *ent); void SP_target_kill (gentity_t *ent); void SP_target_position (gentity_t *ent); void SP_target_location (gentity_t *ent); void SP_target_push (gentity_t *ent); void SP_target_script_trigger (gentity_t *ent); void SP_misc_beam( gentity_t *self ); //---- (SA) Wolf targets // targets void SP_target_alarm ( gentity_t *ent ); void SP_target_counter ( gentity_t *ent ); void SP_target_lock ( gentity_t *ent ); void SP_target_effect ( gentity_t *ent ); void SP_target_fog ( gentity_t *ent ); void SP_target_autosave ( gentity_t *ent ); // entity visibility dummy void SP_misc_vis_dummy (gentity_t *ent); void SP_misc_vis_dummy_multiple (gentity_t *ent); //----(SA) done void SP_light (gentity_t *self); void SP_info_null (gentity_t *self); void SP_info_notnull (gentity_t *self); void SP_info_camp (gentity_t *self); void SP_path_corner (gentity_t *self); void SP_path_corner_2 (gentity_t *self); void SP_info_limbo_camera (gentity_t *self); void SP_info_train_spline_main (gentity_t *self); //void SP_bazooka (gentity_t *self); void SP_misc_teleporter_dest (gentity_t *self); void SP_misc_model(gentity_t *ent); void SP_misc_gamemodel(gentity_t *ent); void SP_misc_portal_camera(gentity_t *ent); void SP_misc_portal_surface(gentity_t *ent); void SP_misc_light_surface(gentity_t *ent); void SP_misc_grabber_trap(gentity_t *ent); void SP_misc_spotlight(gentity_t *ent); //----(SA) added void SP_misc_commandmap_marker( gentity_t *ent ); void SP_shooter_rocket( gentity_t *ent ); void SP_shooter_grenade( gentity_t *ent ); void SP_team_CTF_redplayer( gentity_t *ent ); void SP_team_CTF_blueplayer( gentity_t *ent ); void SP_team_CTF_redspawn( gentity_t *ent ); void SP_team_CTF_bluespawn( gentity_t *ent ); // JPW NERVE for multiplayer spawnpoint selection void SP_team_WOLF_objective( gentity_t *ent ); // jpw void SP_team_WOLF_checkpoint( gentity_t *ent ); // DHM - Nerve // JOSEPH 1-18-00 void SP_props_box_32 (gentity_t *self); void SP_props_box_48 (gentity_t *self); void SP_props_box_64 (gentity_t *self); // END JOSEPH // Ridah /*void SP_ai_soldier( gentity_t *ent ); void SP_ai_american( gentity_t *ent ); void SP_ai_zombie( gentity_t *ent ); void SP_ai_warzombie( gentity_t *ent ); void SP_ai_femzombie( gentity_t *ent ); void SP_ai_undead( gentity_t *ent ); void SP_ai_marker( gentity_t *ent ); void SP_ai_effect( gentity_t *ent ); void SP_ai_trigger( gentity_t *ent ); void SP_ai_venom( gentity_t *ent ); void SP_ai_loper( gentity_t *ent ); void SP_ai_sealoper( gentity_t *ent ); void SP_ai_boss_helga( gentity_t *ent ); void SP_ai_boss_heinrich( gentity_t *ent ); //----(SA) added void SP_ai_eliteguard( gentity_t *ent ); void SP_ai_stimsoldier_dual( gentity_t *ent ); void SP_ai_stimsoldier_rocket( gentity_t *ent ); void SP_ai_stimsoldier_tesla( gentity_t *ent ); void SP_ai_supersoldier( gentity_t *ent ); void SP_ai_blackguard( gentity_t *ent ); void SP_ai_protosoldier( gentity_t *ent ); void SP_ai_rejectxcreature( gentity_t *ent ); void SP_ai_frogman( gentity_t *ent ); void SP_ai_partisan( gentity_t *ent ); void SP_ai_civilian( gentity_t *ent ); void SP_ai_chimp( gentity_t *ent ); //----(SA) added*/ // done. // Rafael particles void SP_target_smoke (gentity_t *ent); // done. // (SA) dlights void SP_dlight(gentity_t *ent); // done void SP_corona(gentity_t *ent); void SP_mg42 (gentity_t *ent); void SP_aagun (gentity_t *ent); //----(SA) //void SP_shooter_zombiespit (gentity_t *ent); void SP_shooter_mortar (gentity_t *ent); // alarm void SP_alarm_box(gentity_t *ent); //----(SA) end void SP_trigger_flagonly( gentity_t *ent ); // DHM - Nerve void SP_trigger_flagonly_multiple( gentity_t *ent ); // DHM - Nerve void SP_trigger_objective_info( gentity_t *ent ); // DHM - Nerve void SP_gas (gentity_t *ent); void SP_target_rumble (gentity_t *ent); // Mad Doc - TDF // put this back in for single player bots void SP_trigger_aidoor (gentity_t *ent); // Rafael //void SP_trigger_aidoor (gentity_t *ent); void SP_SmokeDust (gentity_t *ent); void SP_Dust (gentity_t *ent); void SP_props_sparks (gentity_t *ent); void SP_props_gunsparks (gentity_t *ent); // Props void SP_Props_Bench (gentity_t *ent); void SP_Props_Radio (gentity_t *ent); void SP_Props_Chair (gentity_t *ent); void SP_Props_ChairHiback (gentity_t *ent); void SP_Props_ChairSide (gentity_t *ent); void SP_Props_ChairChat (gentity_t *ent); void SP_Props_ChairChatArm (gentity_t *ent); void SP_Props_DamageInflictor (gentity_t *ent); void SP_Props_Locker_Tall (gentity_t *ent); void SP_Props_Desklamp (gentity_t *ent); void SP_Props_Flamebarrel (gentity_t *ent); void SP_crate_64 (gentity_t *ent); void SP_Props_Flipping_Table (gentity_t *ent); void SP_crate_32 (gentity_t *self); void SP_Props_Crate32x64 (gentity_t *ent); void SP_Props_58x112tablew (gentity_t *ent); void SP_Props_RadioSEVEN (gentity_t *ent); //void SP_propsFireColumn (gentity_t *ent); void SP_props_flamethrower (gentity_t *ent); void SP_func_invisible_user (gentity_t *ent); void SP_lightJunior( gentity_t *self ); //void SP_props_me109 (gentity_t *ent); void SP_misc_flak (gentity_t *ent); void SP_props_snowGenerator (gentity_t *ent); void SP_props_decoration (gentity_t *ent); void SP_props_decorBRUSH (gentity_t *ent); void SP_props_statue (gentity_t *ent); void SP_props_statueBRUSH (gentity_t *ent); void SP_skyportal (gentity_t *ent); // RF, scripting void SP_script_model_med(gentity_t *ent); void SP_script_mover(gentity_t *ent); void SP_script_multiplayer(gentity_t *ent); // DHM - Nerve void SP_props_footlocker (gentity_t *self); void SP_misc_firetrails (gentity_t *ent); void SP_trigger_deathCheck (gentity_t *ent); void SP_misc_spawner (gentity_t *ent); void SP_props_decor_Scale (gentity_t *ent); void SP_bot_landminespot_spot( gentity_t *ent ); void SP_bot_sniper_spot( gentity_t *ent ); void SP_bot_attractor( gentity_t *ent ); void SP_bot_seek_cover_spot( gentity_t *ent ); void SP_bot_seek_cover_sequence( gentity_t *ent ); void SP_bot_axis_seek_cover_spot( gentity_t *ent ); void SP_bot_jump_source( gentity_t *ent ); void SP_bot_jump_dest( gentity_t *ent ); void SP_bot_landmine_area( gentity_t *ent ); void SP_ai_marker( gentity_t *ent ); void SP_func_fakebrush( gentity_t *ent ); // Gordon: debris test void SP_func_debris( gentity_t* ent ); // =================== spawn_t spawns[] = { // info entities don't do anything at all, but provide positional // information for things controlled by other processes {"info_player_start", SP_info_player_start}, {"info_player_checkpoint", SP_info_player_checkpoint}, {"info_player_deathmatch", SP_info_player_deathmatch}, {"info_player_intermission", SP_info_player_intermission}, {"info_null", SP_info_null}, {"info_notnull", SP_info_notnull}, // use target_position instead {"info_notnull_big", SP_info_notnull}, // use target_position instead {"info_camp", SP_info_camp}, // Gordon: debris test {"func_debris", SP_func_debris }, // =================== {"func_plat", SP_func_plat}, {"func_button", SP_func_button}, {"func_explosive", SP_func_explosive}, {"func_door", SP_func_door}, {"func_static", SP_func_static}, {"func_leaky", SP_func_leaky}, {"func_rotating", SP_func_rotating}, {"func_bobbing", SP_func_bobbing}, {"func_pendulum", SP_func_pendulum}, {"func_train", SP_func_train}, {"func_group", SP_info_null}, // Jaybird - EF_FAKEBMODEL {"func_fakebrush", SP_func_fakebrush}, // JOSEPH 1-26-00 {"func_train_rotating", SP_func_train_rotating}, {"func_secret", SP_func_secret}, // END JOSEPH // Rafael {"func_door_rotating", SP_func_door_rotating}, {"func_timer", SP_func_timer}, // rename trigger_timer? {"func_invisible_user", SP_func_invisible_user}, // Triggers are brush objects that cause an effect when contacted // by a living player, usually involving firing targets. // While almost everything could be done with // a single trigger class and different targets, triggered effects // could not be client side predicted (push and teleport). {"trigger_always", SP_trigger_always}, {"trigger_multiple", SP_trigger_multiple}, {"trigger_push", SP_trigger_push}, {"trigger_teleport", SP_trigger_teleport}, {"trigger_hurt", SP_trigger_hurt}, //---- (SA) Wolf triggers {"trigger_concussive_dust", SP_trigger_concussive_dust}, // JPW NERVE {"trigger_once", SP_trigger_once}, //---- done // Mad Doc - TDf // I'm going to put trigger_aidoors back in. I'll make sure they only work in single player {"trigger_aidoor", SP_trigger_aidoor}, // START xkan, 9/17/2002 {"trigger_heal", SP_trigger_heal}, {"trigger_ammo", SP_trigger_ammo}, // END xkan, 9/17/2002 // Gordon: 16/12/02: adding the model things to go with the triggers {"misc_cabinet_health", SP_misc_cabinet_health}, {"misc_cabinet_supply", SP_misc_cabinet_supply}, // end // Rafael // {"trigger_aidoor", SP_trigger_aidoor}, // {"trigger_deathCheck",SP_trigger_deathCheck}, // targets perform no action by themselves, but must be triggered // by another entity {"target_give", SP_target_give}, {"target_remove_powerups", SP_target_remove_powerups}, {"target_delay", SP_target_delay}, {"target_speaker", SP_target_speaker}, {"target_print", SP_target_print}, {"target_laser", SP_target_laser}, {"target_score", SP_target_score}, {"target_teleporter", SP_target_teleporter}, {"target_relay", SP_target_relay}, {"target_kill", SP_target_kill}, {"target_position", SP_target_position}, {"target_location", SP_target_location}, {"target_push", SP_target_push}, {"target_script_trigger", SP_target_script_trigger}, //---- (SA) Wolf targets {"target_alarm", SP_target_alarm}, {"target_counter", SP_target_counter}, {"target_lock", SP_target_lock}, {"target_effect", SP_target_effect}, {"target_fog", SP_target_fog}, {"target_autosave", SP_target_autosave}, //----(SA) added //---- done {"target_rumble", SP_target_rumble}, {"light", SP_light}, {"lightJunior", SP_lightJunior}, {"path_corner", SP_path_corner}, {"path_corner_2", SP_path_corner_2}, {"info_train_spline_main", SP_info_train_spline_main}, {"info_train_spline_control", SP_path_corner_2}, {"info_limbo_camera", SP_info_limbo_camera}, {"misc_teleporter_dest", SP_misc_teleporter_dest}, {"misc_model", SP_misc_model}, {"misc_gamemodel", SP_misc_gamemodel}, {"misc_portal_surface", SP_misc_portal_surface}, {"misc_portal_camera", SP_misc_portal_camera}, {"misc_commandmap_marker", SP_misc_commandmap_marker}, {"misc_vis_dummy", SP_misc_vis_dummy}, {"misc_vis_dummy_multiple", SP_misc_vis_dummy_multiple}, {"misc_light_surface", SP_misc_light_surface}, {"misc_grabber_trap", SP_misc_grabber_trap}, {"misc_spotlight", SP_misc_spotlight}, {"misc_mg42", SP_mg42}, {"misc_aagun", SP_aagun}, {"misc_flak", SP_misc_flak}, {"misc_firetrails", SP_misc_firetrails}, {"shooter_rocket", SP_shooter_rocket}, {"shooter_grenade", SP_shooter_grenade}, {"shooter_mortar", SP_shooter_mortar}, {"alarm_box", SP_alarm_box}, // Gordon: FIXME remove {"team_CTF_redplayer", SP_team_CTF_redplayer}, {"team_CTF_blueplayer", SP_team_CTF_blueplayer}, {"team_CTF_redspawn", SP_team_CTF_redspawn}, {"team_CTF_bluespawn", SP_team_CTF_bluespawn}, {"team_WOLF_objective", SP_team_WOLF_objective}, {"team_WOLF_checkpoint", SP_team_WOLF_checkpoint}, {"target_smoke", SP_target_smoke}, {"misc_spawner", SP_misc_spawner}, {"props_box_32", SP_props_box_32}, {"props_box_48", SP_props_box_48}, {"props_box_64", SP_props_box_64}, {"props_smokedust", SP_SmokeDust}, {"props_dust", SP_Dust}, {"props_sparks", SP_props_sparks}, {"props_gunsparks", SP_props_gunsparks}, {"props_bench", SP_Props_Bench}, {"props_radio", SP_Props_Radio}, {"props_chair", SP_Props_Chair}, {"props_chair_hiback", SP_Props_ChairHiback}, {"props_chair_side", SP_Props_ChairSide}, {"props_chair_chat", SP_Props_ChairChat}, {"props_chair_chatarm", SP_Props_ChairChatArm}, {"props_damageinflictor", SP_Props_DamageInflictor}, {"props_locker_tall",SP_Props_Locker_Tall}, {"props_desklamp", SP_Props_Desklamp}, {"props_flamebarrel", SP_Props_Flamebarrel}, {"props_crate_64", SP_crate_64}, {"props_flippy_table", SP_Props_Flipping_Table}, {"props_crate_32", SP_crate_32}, {"props_crate_32x64", SP_Props_Crate32x64}, {"props_58x112tablew", SP_Props_58x112tablew}, {"props_radioSEVEN", SP_Props_RadioSEVEN}, {"props_snowGenerator", SP_props_snowGenerator}, // {"props_FireColumn", SP_propsFireColumn}, {"props_decoration", SP_props_decoration}, {"props_decorBRUSH", SP_props_decorBRUSH}, {"props_statue", SP_props_statue}, {"props_statueBRUSH", SP_props_statueBRUSH}, {"props_skyportal", SP_skyportal}, {"props_footlocker", SP_props_footlocker}, {"props_flamethrower", SP_props_flamethrower}, {"props_decoration_scale",SP_props_decor_Scale}, {"dlight", SP_dlight}, {"corona", SP_corona}, {"trigger_flagonly", SP_trigger_flagonly }, {"trigger_flagonly_multiple", SP_trigger_flagonly_multiple}, {"test_gas", SP_gas}, {"trigger_objective_info", SP_trigger_objective_info}, // RF, scripting {"script_model_med", SP_script_model_med}, {"script_mover", SP_script_mover}, {"script_multiplayer", SP_script_multiplayer}, {"func_constructible", SP_func_constructible}, {"func_brushmodel", SP_func_brushmodel}, {"misc_beam", SP_misc_beam}, {"misc_constructiblemarker", SP_misc_constructiblemarker}, {"target_explosion", SP_target_explosion }, {"misc_landmine", SP_misc_landmine }, {0, 0} }; /* =============== G_CallSpawn Finds the spawn function for the entity and calls it, returning qfalse if not found =============== */ qboolean G_CallSpawn( gentity_t *ent ) { spawn_t *s; gitem_t *item; if ( !ent->classname ) { G_Printf ("G_CallSpawn: NULL classname\n"); return qfalse; } // check item spawn functions for ( item=bg_itemlist+1 ; item->classname ; item++ ) { if ( !strcmp(item->classname, ent->classname) ) { // found it if(g_gametype.integer != GT_WOLF_LMS) { // Gordon: lets not have items in last man standing for the moment G_SpawnItem( ent, item ); G_Script_ScriptParse( ent ); G_Script_ScriptEvent( ent, "spawn", "" ); } else { return qfalse; } return qtrue; } } // check normal spawn functions for ( s=spawns ; s->name ; s++ ) { if ( !strcmp(s->name, ent->classname) ) { // found it s->spawn(ent); // RF, entity scripting if (/*ent->s.number >= MAX_CLIENTS &&*/ ent->scriptName) { G_Script_ScriptParse( ent); G_Script_ScriptEvent( ent, "spawn", "" ); } return qtrue; } } G_Printf ("%s doesn't have a spawn function\n", ent->classname); return qfalse; } /* ============= G_NewString Builds a copy of the string, translating \n to real linefeeds so message texts can be multi-line ============= */ char *G_NewString( const char *string ) { char *newb, *new_p; int i,l; l = strlen(string) + 1; newb = (char*)G_Alloc( l ); new_p = newb; // turn \n into a real linefeed for ( i=0 ; i< l ; i++ ) { if (string[i] == '\\' && i < l-1) { i++; if (string[i] == 'n') { *new_p++ = '\n'; } else { *new_p++ = '\\'; } } else { *new_p++ = string[i]; } } return newb; } /* =============== G_ParseField Takes a key/value pair and sets the binary values in a gentity =============== */ void G_ParseField( const char *key, const char *value, gentity_t *ent ) { field_t *f; byte *b; float v; vec3_t vec; for ( f=fields ; f->name ; f++ ) { if ( !Q_stricmp(f->name, key) ) { // found it b = (byte *)ent; switch( f->type ) { case F_LSTRING: *(char **)(b+f->ofs) = G_NewString (value); break; case F_VECTOR: sscanf (value, "%f %f %f", &vec[0], &vec[1], &vec[2]); ((float *)(b+f->ofs))[0] = vec[0]; ((float *)(b+f->ofs))[1] = vec[1]; ((float *)(b+f->ofs))[2] = vec[2]; break; case F_INT: *(int *)(b+f->ofs) = atoi(value); break; case F_FLOAT: *(float *)(b+f->ofs) = atof(value); break; case F_ANGLEHACK: v = atof(value); ((float *)(b+f->ofs))[0] = 0; ((float *)(b+f->ofs))[1] = v; ((float *)(b+f->ofs))[2] = 0; break; default: case F_IGNORE: break; } return; } } } /* =================== G_SpawnGEntityFromSpawnVars Spawn an entity and fill in all of the level fields from level.spawnVars[], then call the class specfic spawn function =================== */ void G_SpawnGEntityFromSpawnVars( void ) { int i; gentity_t *ent; char *str; // get the next free entity ent = G_Spawn(); for ( i = 0 ; i < level.numSpawnVars ; i++ ) { G_ParseField( level.spawnVars[i][0], level.spawnVars[i][1], ent ); } // check for "notteam" / "notfree" flags G_SpawnInt( "notteam", "0", &i ); if ( i ) { G_FreeEntity( ent ); return; } // allowteams handling G_SpawnString( "allowteams", "", &str ); if( str[0] ) { str = Q_strlwr( str ); if( strstr( str, "axis" ) ) { ent->allowteams |= ALLOW_AXIS_TEAM; } if( strstr( str, "allies" ) ) { ent->allowteams |= ALLOW_ALLIED_TEAM; } if( strstr( str, "cvops" ) ) { ent->allowteams |= ALLOW_DISGUISED_CVOPS; } } if( ent->targetname && *ent->targetname ) { ent->targetnamehash = BG_StringHashValue( ent->targetname ); } else { ent->targetnamehash = -1; } // move editor origin to pos VectorCopy( ent->s.origin, ent->s.pos.trBase ); VectorCopy( ent->s.origin, ent->r.currentOrigin ); // if we didn't get a classname, don't bother spawning anything if ( !G_CallSpawn( ent ) ) { G_FreeEntity( ent ); } // RF, try and move it into the bot entities if possible // BotCheckBotGameEntity( ent ); } /* ==================== G_AddSpawnVarToken ==================== */ char *G_AddSpawnVarToken( const char *string ) { int l; char *dest; l = strlen( string ); if ( level.numSpawnVarChars + l + 1 > MAX_SPAWN_VARS_CHARS ) { G_Error( "G_AddSpawnVarToken: MAX_SPAWN_VARS" ); } dest = level.spawnVarChars + level.numSpawnVarChars; memcpy( dest, string, l+1 ); level.numSpawnVarChars += l + 1; return dest; } /* ==================== G_ParseSpawnVars Parses a brace bounded set of key / value pairs out of the level's entity strings into level.spawnVars[] This does not actually spawn an entity. ==================== */ qboolean G_ParseSpawnVars( void ) { char keyname[MAX_TOKEN_CHARS]; char com_token[MAX_TOKEN_CHARS]; level.numSpawnVars = 0; level.numSpawnVarChars = 0; // parse the opening brace if ( !trap_GetEntityToken( com_token, sizeof( com_token ) ) ) { // end of spawn string return qfalse; } if ( com_token[0] != '{' ) { G_Error( "G_ParseSpawnVars: found %s when expecting {",com_token ); } // go through all the key / value pairs while ( 1 ) { // parse key if ( !trap_GetEntityToken( keyname, sizeof( keyname ) ) ) { G_Error( "G_ParseSpawnVars: EOF without closing brace" ); } if ( keyname[0] == '}' ) { break; } // parse value if ( !trap_GetEntityToken( com_token, sizeof( com_token ) ) ) { G_Error( "G_ParseSpawnVars: EOF without closing brace" ); } if ( com_token[0] == '}' ) { G_Error( "G_ParseSpawnVars: closing brace without data" ); } if ( level.numSpawnVars == MAX_SPAWN_VARS ) { G_Error( "G_ParseSpawnVars: MAX_SPAWN_VARS" ); } level.spawnVars[ level.numSpawnVars ][0] = G_AddSpawnVarToken( keyname ); level.spawnVars[ level.numSpawnVars ][1] = G_AddSpawnVarToken( com_token ); level.numSpawnVars++; } return qtrue; } /*QUAKED worldspawn (0 0 0) ? NO_GT_WOLF NO_GT_STOPWATCH NO_GT_CHECKPOINT NO_LMS Every map should have exactly one worldspawn. "music" Music wav file "gravity" 800 is default gravity "message" Text to print during connection process "ambient" Ambient light value (must use '_color') "_color" Ambient light color (must be used with 'ambient') "sun" Shader to use for 'sun' image */ void SP_worldspawn( void ) { char *s; G_SpawnString( "classname", "", &s ); if ( Q_stricmp( s, "worldspawn" ) ) { G_Error( "SP_worldspawn: The first entity isn't 'worldspawn'" ); } // make some data visible to connecting client trap_SetConfigstring( CS_GAME_VERSION, GAME_VERSION ); trap_SetConfigstring( CS_LEVEL_START_TIME, va("%i", level.startTime ) ); G_SpawnString( "music", "", &s ); trap_SetConfigstring( CS_MUSIC, s ); G_SpawnString( "message", "", &s ); trap_SetConfigstring( CS_MESSAGE, s ); // map specific message G_SpawnString( "cclayers", "0", &s ); if( atoi(s) ) level.ccLayers = qtrue; level.mapcoordsValid = qfalse; if( G_SpawnVector2D( "mapcoordsmins", "-128 128", level.mapcoordsMins ) && // top left G_SpawnVector2D( "mapcoordsmaxs", "128 -128", level.mapcoordsMaxs ) ) { // bottom right level.mapcoordsValid = qtrue; } BG_InitLocations( level.mapcoordsMins, level.mapcoordsMaxs ); G_SpawnString( "gravity", "800", &s ); trap_Cvar_Set( "g_gravity", s ); G_SpawnString( "spawnflags", "0", &s ); g_entities[ENTITYNUM_WORLD].spawnflags = atoi( s ); g_entities[ENTITYNUM_WORLD].r.worldflags = g_entities[ENTITYNUM_WORLD].spawnflags; g_entities[ENTITYNUM_WORLD].s.number = ENTITYNUM_WORLD; g_entities[ENTITYNUM_WORLD].classname = "worldspawn"; // see if we want a warmup time trap_SetConfigstring( CS_WARMUP, "" ); if ( g_restarted.integer ) { trap_Cvar_Set( "g_restarted", "0" ); level.warmupEndTime = 0; } if(cvars::gameState.ivalue == GS_PLAYING) { G_initMatch(); } } /* ============== G_SpawnEntitiesFromString Parses textual entity definitions out of an entstring and spawns gentities. ============== */ void G_SpawnEntitiesFromString( void ) { // allow calls to G_Spawn*() G_Printf( "Enable spawning!\n" ); level.spawning = qtrue; level.numSpawnVars = 0; // the worldspawn is not an actual entity, but it still // has a "spawn" function to perform any global setup // needed by a level (setting configstrings or cvars, etc) if ( !G_ParseSpawnVars() ) { G_Error( "SpawnEntities: no entities" ); } SP_worldspawn(); // parse ents while( G_ParseSpawnVars() ) { G_SpawnGEntityFromSpawnVars(); } G_Printf( "Disable spawning!\n" ); level.spawning = qfalse; // any future calls to G_Spawn*() will be errors } /* =================== G_SpawnGEntityFromSpawnVarsLink Spawn an entity and fill in all of the level fields from level.spawnVars[], then call the class specfic spawn function Jaybird - link it as well =================== */ void G_SpawnGEntityFromSpawnVarsLink( void ) { int i; gentity_t *ent; char *str; // get the next free entity ent = G_Spawn(); for ( i = 0 ; i < level.numSpawnVars ; i++ ) { G_ParseField( level.spawnVars[i][0], level.spawnVars[i][1], ent ); } // check for "notteam" / "notfree" flags G_SpawnInt( "notteam", "0", &i ); if ( i ) { G_FreeEntity( ent ); return; } // allowteams handling G_SpawnString( "allowteams", "", &str ); if( str[0] ) { str = Q_strlwr( str ); if( strstr( str, "axis" ) ) { ent->allowteams |= ALLOW_AXIS_TEAM; } if( strstr( str, "allies" ) ) { ent->allowteams |= ALLOW_ALLIED_TEAM; } if( strstr( str, "cvops" ) ) { ent->allowteams |= ALLOW_DISGUISED_CVOPS; } } if( ent->targetname && *ent->targetname ) { ent->targetnamehash = BG_StringHashValue( ent->targetname ); } else { ent->targetnamehash = -1; } // move editor origin to pos VectorCopy( ent->s.origin, ent->s.pos.trBase ); VectorCopy( ent->s.origin, ent->r.currentOrigin ); // if we didn't get a classname, don't bother spawning anything if ( !G_CallSpawn( ent ) ) { G_FreeEntity( ent ); } trap_LinkEntity( ent ); }
28.098921
136
0.700314
jumptohistory
8edd3140d4454adc5df29a27a7a5a0e9dd532c3a
1,466
cpp
C++
sketchup_sdk/deprecated/SkpReader/Examples/skptoxml/plugin/xmlplugin.cpp
jhhsia/sketchup_converter
7d8daffd61c8d8f6c214640672e38c7817e37788
[ "MIT" ]
1
2020-09-27T10:55:07.000Z
2020-09-27T10:55:07.000Z
sketchup_sdk/deprecated/SkpReader/Examples/skptoxml/plugin/xmlplugin.cpp
jhhsia/sketchup_converter
7d8daffd61c8d8f6c214640672e38c7817e37788
[ "MIT" ]
null
null
null
sketchup_sdk/deprecated/SkpReader/Examples/skptoxml/plugin/xmlplugin.cpp
jhhsia/sketchup_converter
7d8daffd61c8d8f6c214640672e38c7817e37788
[ "MIT" ]
null
null
null
// Copyright 2013 Trimble Navigation Ltd. All Rights Reserved. #include "./xmlplugin.h" #include <slapi/import_export/pluginprogresscallback.h> CXmlExporterPlugin::CXmlExporterPlugin() { m_pXMLExporter = NULL; } CXmlExporterPlugin::~CXmlExporterPlugin() { delete m_pXMLExporter; } std::string CXmlExporterPlugin::GetDescription(int index) const { return "Deprecated XML Exporter (*.xml)"; } static void GetNumberString(size_t number, char* numberString, int length) { #ifdef _WINDOWS _snprintf_s(numberString, length, _TRUNCATE, "%5u\n", number); #else snprintf(numberString, length, "%5u\n", number); #endif } bool CXmlExporterPlugin::DeprecatedConvertFromSkp( void* document, const std::string& output, SketchUpPluginProgressCallback* progress) { bool converted = false; try { // Get the IDocument interface IUnknown* activeDocument = (IUnknown*)document; if (activeDocument == NULL) return false; ISkpDocument* pDoc = NULL; HRESULT hr = activeDocument->QueryInterface(IID_ISkpDocument, (void**) &pDoc); // Initialize the exporter class delete m_pXMLExporter; m_pXMLExporter = new CXMLExporter(&m_XMLOptions); // Do the export _bstr_t file_path = output.c_str(); hr = m_pXMLExporter->DoExport(file_path, pDoc, progress); converted = SUCCEEDED(hr); } catch (...) { converted = false; } return converted; }
24.433333
76
0.68895
jhhsia
8ee2a877f749a1f66e08c3a37337743dc466cf74
2,846
hpp
C++
samples/src/hlml/int2.hpp
Rosme/sift
f8d05d19562b4da13271d5c26658d7e8c47866ae
[ "MIT" ]
4
2018-06-15T12:54:10.000Z
2020-09-22T16:01:35.000Z
samples/src/hlml/int2.hpp
Rosme/sift
f8d05d19562b4da13271d5c26658d7e8c47866ae
[ "MIT" ]
null
null
null
samples/src/hlml/int2.hpp
Rosme/sift
f8d05d19562b4da13271d5c26658d7e8c47866ae
[ "MIT" ]
null
null
null
#pragma once #include "common.hpp" #include "bool2.hpp" namespace hlml { struct int2 { VI128 m = { 0 }; HLML_INLINEF int2() {} HLML_INLINEF int2(I32 x, I32 y) : m(funcs::setXYZW(x, y, consts::snZero, consts::snZero)) {} HLML_INLINEF explicit int2(I32 x) : int2(x, x) {} HLML_INLINEF explicit int2(const I32 *p) : int2(p[0], p[1]) {} HLML_INLINEF explicit int2(VI128 v) : m(v) {} HLML_INLINEF void store(I32 *p) const { p[0] = x(); p[1] = y(); } HLML_INLINEF void setX(I32 x) { m = inserti(m, x, 0); } HLML_INLINEF void setY(I32 y) { m = inserti(m, y, 1); } HLML_INLINEF I32 x() const { return extracti(m, 0); } HLML_INLINEF I32 y() const { return extracti(m, 1); } HLML_INLINEF int2 xx() const { return shufflei2(*this, 0, 0); } HLML_INLINEF int2 xy() const { return *this; } HLML_INLINEF int2 yx() const { return shufflei2(*this, 1, 0); } HLML_INLINEF int2 yy() const { return shufflei2(*this, 1, 1); } HLML_INLINEF I32 r() const { return x(); } HLML_INLINEF I32 g() const { return y(); } HLML_INLINEF int2 rr() const { return xx(); } HLML_INLINEF int2 rg() const { return xy(); } HLML_INLINEF int2 gr() const { return yx(); } HLML_INLINEF int2 gg() const { return yy(); } }; template<typename T> HLML_INLINEF T operator+ (T a, I32 b) { return a + T(b); } template<typename T> HLML_INLINEF T operator+ (I32 b, T a) { return a + b; } template<typename T> HLML_INLINEF T& operator+= (T& a, I32 b) { return a += T(b); } template<typename T> HLML_INLINEF T operator- (T a, I32 b) { return a - T(b); } template<typename T> HLML_INLINEF T operator- (I32 a, T b) { return T(a) - b; } template<typename T> HLML_INLINEF T& operator-= (T& a, I32 b) { return a -= T(b); } template<typename T> HLML_INLINEF T operator* (T a, I32 b) { return a * T(b); } template<typename T> HLML_INLINEF T operator* (I32 b, T a) { return a * b; } template<typename T> HLML_INLINEF T& operator*= (T& a, I32 b) { return a *= T(b); } HLML_INLINEF bool2 operator== (int2 a, int2 b) { return bool2(funcs::ftoi(cmpeq(a, b).m)); } HLML_INLINEF bool2 operator!= (int2 a, int2 b) { return bool2(funcs::ftoi(cmpneq(a, b).m)); } HLML_INLINEF bool2 operator< (int2 a, int2 b) { return bool2(funcs::ftoi(cmplt(a, b).m)); } HLML_INLINEF bool2 operator> (int2 a, int2 b) { return bool2(funcs::ftoi(cmpgt(a, b).m)); } HLML_INLINEF bool2 operator<= (int2 a, int2 b) { return bool2(funcs::ftoi(cmple(a, b).m)); } HLML_INLINEF bool2 operator>= (int2 a, int2 b) { return bool2(funcs::ftoi(cmpge(a, b).m)); } HLML_INLINEF int2 sumv(int2 v) { v.m = funcs::AhaddB(v.m, v.m); return v; } template<typename T> HLML_INLINEF I32 sum(T v) { return sumv(v).x(); } HLML_INLINEF I32 hmin(int2 v) { return min(v, shufflei2(v, 1, 0)).x(); } HLML_INLINEF I32 hmax(int2 v) { return max(v, shufflei2(v, 1, 0)).x(); } }
46.655738
95
0.642305
Rosme
8ef0831878f003b22b6f659c8a1b920c978bc556
207
cpp
C++
4th semester/lab_9/src/KeepInt.cpp
kmalski/cpp_labs
52b0fc84319d6cc57ff7bfdb787aa5eb09edf592
[ "MIT" ]
1
2020-05-19T17:14:55.000Z
2020-05-19T17:14:55.000Z
4th semester/lab_9/src/KeepInt.cpp
kmalski/CPP_Laboratories
52b0fc84319d6cc57ff7bfdb787aa5eb09edf592
[ "MIT" ]
null
null
null
4th semester/lab_9/src/KeepInt.cpp
kmalski/CPP_Laboratories
52b0fc84319d6cc57ff7bfdb787aa5eb09edf592
[ "MIT" ]
null
null
null
#include "KeepInt.h" KeepInt::KeepInt(int &account) : _account(account), _startValue(account) {} void KeepInt::dodo() {} void KeepInt::undoOk() {} void KeepInt::undoFail() { _account = _startValue; }
18.818182
75
0.68599
kmalski
8ef57fa29abe24470ef7dd95a97f00fb4bcaa735
2,665
cpp
C++
rt/core/float4.cpp
DasNaCl/old-university-projects
af1c82afec4805ea672e0c353369035b394cb69d
[ "Apache-2.0" ]
null
null
null
rt/core/float4.cpp
DasNaCl/old-university-projects
af1c82afec4805ea672e0c353369035b394cb69d
[ "Apache-2.0" ]
null
null
null
rt/core/float4.cpp
DasNaCl/old-university-projects
af1c82afec4805ea672e0c353369035b394cb69d
[ "Apache-2.0" ]
null
null
null
// // Created by Matthias on 20.11.2018. // #include "scalar.h" #include <algorithm> #include <cmath> #include <core/assert.h> #include <core/float4.h> #include <core/point.h> #include <core/vector.h> namespace rt { Float4::Float4(float x, float y, float z, float w) : coords{ x, y, z, w } { } Float4::Float4(const Point& p) : coords{ p.x, p.y, p.z, 1.f } { } Float4::Float4(const Vector& v) : coords{ v.x, v.y, v.z, 0.f } { } float& Float4::operator[](int idx) { assert(0 <= idx && idx < 4); return coords[idx]; } float Float4::operator[](int idx) const { assert(0 <= idx && idx < 4); return coords[idx]; } Float4 Float4::operator+(const Float4& b) const { return Float4( coords[0] + b[0], coords[1] + b[1], coords[2] + b[2], coords[3] + b[3]); } Float4 Float4::operator-(const Float4& b) const { return Float4( coords[0] - b[0], coords[1] - b[1], coords[2] - b[2], coords[3] - b[3]); } Float4 Float4::operator*(const Float4& b) const { return Float4( coords[0] * b[0], coords[1] * b[1], coords[2] * b[2], coords[3] * b[3]); } Float4 Float4::operator/(const Float4& b) const { return Float4( coords[0] / b[0], coords[1] / b[1], coords[2] / b[2], coords[3] / b[3]); } Float4 Float4::operator-() const { return Float4(-coords[0], -coords[1], -coords[2], -coords[3]); } bool Float4::operator==(const Float4& b) const { return std::fabs(coords[0] - b[0]) < rt::epsilon && std::fabs(coords[1] - b[1]) < rt::epsilon && std::fabs(coords[2] - b[2]) < rt::epsilon && std::fabs(coords[3] - b[3]) < rt::epsilon; } bool Float4::operator!=(const Float4& b) const { return std::fabs(coords[0] - b[0]) > rt::epsilon || std::fabs(coords[1] - b[1]) > rt::epsilon || std::fabs(coords[2] - b[2]) > rt::epsilon || std::fabs(coords[3] - b[3]) > rt::epsilon; } Float4 operator*(float scalar, const Float4& b) { return Float4(b[0] * scalar, b[1] * scalar, b[2] * scalar, b[3] * scalar); } Float4 operator*(const Float4& a, float scalar) { return Float4(a[0] * scalar, a[1] * scalar, a[2] * scalar, a[3] * scalar); } Float4 operator/(const Float4& a, float scalar) { return Float4(a[0] / scalar, a[1] / scalar, a[2] / scalar, a[3] / scalar); } float dot(const Float4& a, const Float4& b) { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3]; } Float4 min(const Float4& a, const Float4& b) { return Float4(std::min(a[0], b[0]), std::min(a[1], b[1]), std::min(a[2], b[2]), std::min(a[3], b[3])); } Float4 max(const Float4& a, const Float4& b) { return Float4(std::max(a[0], b[0]), std::max(a[1], b[1]), std::max(a[2], b[2]), std::max(a[3], b[3])); } }
24.227273
76
0.577486
DasNaCl
8efbfc6552d81214100eede31ffbb26299486891
10,998
cc
C++
cxx/src/time_zone.cc
alexhsamuel/ora
89358d9193d86fbc7752270f1e35ee6ddcdcd206
[ "BSD-3-Clause" ]
10
2018-03-03T02:02:19.000Z
2020-04-02T22:47:55.000Z
cxx/src/time_zone.cc
alexhsamuel/ora
89358d9193d86fbc7752270f1e35ee6ddcdcd206
[ "BSD-3-Clause" ]
13
2018-01-28T15:20:55.000Z
2022-01-27T23:32:41.000Z
cxx/src/time_zone.cc
alexhsamuel/ora
89358d9193d86fbc7752270f1e35ee6ddcdcd206
[ "BSD-3-Clause" ]
null
null
null
#include <algorithm> #include <cassert> #include <cstdlib> #include <cstring> #include <fstream> #include <map> #include <memory> #include "ora/lib/file.hh" #include "ora/lib/filename.hh" #include "ora/time_type.hh" #include "ora/time_zone.hh" #include "ora/tzfile.hh" namespace ora { using namespace ora::lib; using std::make_shared; using std::string; //------------------------------------------------------------------------------ // Local data //------------------------------------------------------------------------------ namespace { std::string system_time_zone_name; TimeZone_ptr thread_local display_time_zone = nullptr; } // anonymous namespace //------------------------------------------------------------------------------ TimeZone::Entry::Entry( int64_t const transition_time, TzFile::Type const& type) : transition(transition_time) { parts.offset = type.gmt_offset_; parts.is_dst = type.is_dst_; // FIXME: This is not future-proof. Truncate with a warning? assert(type.abbreviation_.length() < sizeof(TimeZoneParts::abbreviation)); strncpy(parts.abbreviation, type.abbreviation_.c_str(), sizeof(TimeZoneParts::abbreviation) - 1); } TimeZone::TimeZone() : name_("UTC") { entries_.emplace_back( time::Unix64Time::MIN.get_offset(), TzFile::Type{0, false, "UTC", true, true}); } TimeZone::TimeZone( TzFile const& tz_file, std::string const& name) : name_(name) { entries_.reserve(tz_file.transitions_.size() + 1); // Find the first non-DST time type. assert(tz_file.types_.size() > 0); TzFile::Type const* default_type = nullptr; for (auto type : tz_file.types_) if (! type.is_dst_) { default_type = &type; break; } // If we didn't find a non-DST type, use the first type unconditionally. if (default_type == nullptr) default_type = &tz_file.types_.front(); // Add a sentry entry. entries_.emplace_back(time::Unix64Time::MIN.get_offset(), *default_type); for (auto const& transition : tz_file.transitions_) entries_.emplace_back( transition.time_, tz_file.types_[transition.type_index_]); assert(entries_.size() == tz_file.transitions_.size() + 1); std::reverse(begin(entries_), end(entries_)); } TimeZoneParts TimeZone::get_parts( int64_t const time) const { auto iter = std::lower_bound( entries_.cbegin(), entries_.cend(), time, [] (Entry const& entry, int64_t const time) { return entry.transition > time; }); return iter->parts; } TimeZoneParts TimeZone::get_parts_local( int64_t const time, bool const first) const { // First, find the most recent transition, pretending the time is UTC. auto const iter = std::lower_bound( entries_.cbegin(), entries_.cend(), time, [] (Entry const& entry, int64_t const time) { return entry.transition > time; }); // The sentry protects from no result. assert(iter != entries_.cend()); // We've found the most recent transition for the UTC time, but we want the // transition for the local time. The local time may be before this // transition, or after the next. It's also possible that the local time may // have occurred twice (if the local clock was turned back at the transition), // or not at all (if the local clock was advanced). // // We assume that the time zone offset is always smaller than the time between // two transitions. We check whether the local time is actually part of the // time zone interval we found, as well as whether it is part of the previous // or next intervals, assuming these exist. auto const prev = iter + 1; auto const next = iter - 1; bool const in_prev = prev != entries_.cend() && prev->transition + prev->parts.offset <= time && time < (prev - 1)->transition + prev->parts.offset; bool const in_this = iter->transition + iter->parts.offset <= time && (iter == entries_.cbegin() || time < (iter - 1)->transition + iter->parts.offset); bool const in_next = iter != entries_.cbegin() && next->transition + next->parts.offset <= time && (next == entries_.cbegin() || time < (next - 1)->transition + next->parts.offset); // FIXME: For debugging. if (false) { std::cerr << "offset for local " << time << '\n'; std::cerr << "prev? " << (iter + 1)->transition << "/" << (iter + 1)->parts.offset << " = " << (iter + 1)->transition + (iter + 1)->parts.offset << "-" << (iter + 0)->transition + (iter + 1)->parts.offset << " -> " << (in_prev ? "true" : "false") << '\n'; std::cerr << "this? " << (iter + 0)->transition << "/" << (iter + 0)->parts.offset << " = " << (iter + 0)->transition + (iter + 0)->parts.offset << "-" << (iter - 1)->transition + (iter + 0)->parts.offset << " -> " << (in_this ? "true" : "false") << '\n'; std::cerr << "next? " << (iter - 1)->transition << "/" << (iter - 1)->parts.offset << " = " << (iter - 1)->transition + (iter - 1)->parts.offset << "-" << (iter - 2)->transition + (iter - 1)->parts.offset << " -> " << (in_next ? "true" : "false") << '\n'; } if (in_this) // The local time is part of the transition interval we found, but if it // occurred in the previous or next as well, we need to disambiguate. return in_prev ? (first ? (iter + 1)->parts : iter->parts) : in_next ? (first ? iter->parts : (iter - 1)->parts) : iter->parts; else if (in_prev) // Actually, it's only in the previous transition interval. return (iter + 1)->parts; else if (in_next) // Actually, it's only in the next transition interval. return (iter - 1)->parts; else // The local time does not exist. throw NonexistentDateDaytime(); } TimeZone_ptr UTC = std::make_shared<TimeZone const>(); //------------------------------------------------------------------------------ // Functions. //------------------------------------------------------------------------------ namespace { fs::Filename const SYSTEM_TIME_ZONE_FILE = "/etc/timezone"; fs::Filename const SYSTEM_TIME_ZONE_LINK = "/etc/localtime"; char const* const ZONEINFO_ENVVAR = "ZONEINFO"; fs::Filename const ZONEINFO_DIR_DEFAULT = "/usr/share/zoneinfo"; bool zoneinfo_dir_initialized = false; fs::Filename zoneinfo_dir {""}; // Cache of loaded time zone objects. // // Pointers in this cache should not be std::map<string, TimeZone_ptr> time_zones; } // anonymous namespace extern fs::Filename get_default_zoneinfo_dir() { char const* const env_val = getenv(ZONEINFO_ENVVAR); // FIXME: Use the included zoneinfo database. But where is it installed? return env_val != nullptr ? fs::Filename(env_val) : ZONEINFO_DIR_DEFAULT; } extern void set_zoneinfo_dir( fs::Filename const& dir) { if (!ora::lib::fs::check(dir, ora::lib::fs::EXISTS, ora::lib::fs::DIRECTORY)) throw ora::lib::fs::FileNotFoundError(dir); // Invalidate cache; contents of the new directory may be different. time_zones.clear(); zoneinfo_dir = dir; zoneinfo_dir_initialized = true; } extern fs::Filename get_zoneinfo_dir() { if (! zoneinfo_dir_initialized) set_zoneinfo_dir(get_default_zoneinfo_dir()); return zoneinfo_dir; } extern fs::Filename find_time_zone_file( std::string const& name, fs::Filename const& zoneinfo_dir) { auto const filename = zoneinfo_dir / name; if (check(filename, fs::READ, fs::FILE)) return filename; else throw ValueError(std::string("no time zone: ") + name); } extern TimeZone_ptr get_time_zone( std::string const& name) { if (name == "UTC" || name == "utc") return UTC; auto find = time_zones.find(name); if (find != end(time_zones)) return find->second; else { auto const filename = find_time_zone_file(name); return time_zones[name] = make_shared<TimeZone const>(TzFile::load(filename), name); } } extern inline TimeZone get_time_zone( std::string const& name, fs::Filename const& zoneinfo_dir) { auto filename = find_time_zone_file(name); return TimeZone(TzFile::load(filename), name); } string get_system_time_zone_name_() { // FIXME: Portability. if (fs::check(SYSTEM_TIME_ZONE_FILE, fs::READ, fs::FILE)) { std::ifstream file(SYSTEM_TIME_ZONE_FILE.operator string()); char line[128]; file.getline(line, sizeof(line)); line[sizeof(line) - 1] = '\0'; string time_zone = strip(string(line)); if (time_zone.length() > 0) return time_zone; else throw RuntimeError( string("no time zone name in ") + SYSTEM_TIME_ZONE_FILE); } else if (fs::check(SYSTEM_TIME_ZONE_LINK, fs::EXISTS, fs::SYMBOLIC_LINK)) { char buf[PATH_MAX]; int const result = readlink(SYSTEM_TIME_ZONE_LINK, buf, sizeof(buf)); if (result == -1) throw RuntimeError(string("can't read link: ") + SYSTEM_TIME_ZONE_LINK); else { // Nul-terminate. assert(result < PATH_MAX); buf[result] = '\0'; // Look for a link target of the form .../zoneinfo/REGION/TIMEZONE or // .../zoneinfo/TIMEZONE, where the prefix is arbitrary. fs::Filename const zone_filename = buf; auto const parts = get_parts(zone_filename); auto const zoneinfo_parts = fs::get_parts(get_zoneinfo_dir()); if (parts.size() > 1 && parts[1] == "zoneinfo") return parts[0]; else if (parts.size() > 2 && parts[2] == "zoneinfo") return parts[1] + '/' + parts[0]; else throw RuntimeError(string("not time zone link: ") + SYSTEM_TIME_ZONE_LINK); } } else throw RuntimeError("no system time zone found"); } extern string get_system_time_zone_name() { if (system_time_zone_name == "") { system_time_zone_name = get_system_time_zone_name_(); assert(system_time_zone_name != ""); } return system_time_zone_name; } extern TimeZone_ptr get_system_time_zone() { // FIMXE: Store the time zone. string const name = get_system_time_zone_name(); return get_time_zone(name); } extern TimeZone_ptr get_display_time_zone() { if (display_time_zone == nullptr) { // Initialize to the value of the TZ environment variable, if set. auto const tz_name = getenv("TZ"); TimeZone_ptr tz; if (tz_name == nullptr) // TZ is not set; use the system time zone. try { tz = get_system_time_zone(); } catch (RuntimeError const&) { // Unknown system time zone. Fall back to UTC. tz = UTC; } else try { tz = get_time_zone(tz_name); } catch (ValueError const&) { // Unknown time zone. Fall back to UTC. tz = UTC; } set_display_time_zone(std::move(tz)); assert(display_time_zone != nullptr); } return display_time_zone; } extern void set_display_time_zone( TimeZone_ptr tz) { display_time_zone = tz; } //------------------------------------------------------------------------------ } // namespace ora
26.4375
99
0.61984
alexhsamuel
f102bab87141fa5fa34fe7c513d1b1b28384e2de
3,011
cpp
C++
Cocos2dWindowsPhone/CCCamera.cpp
GhostSoar/Cocos2dWindows
654a018004e358f875bedeb7c9acd6824c0734f8
[ "MIT" ]
1
2017-01-04T07:05:37.000Z
2017-01-04T07:05:37.000Z
Cocos2dWindowsPhone/CCCamera.cpp
GhostSoar/Cocos2dWindows
654a018004e358f875bedeb7c9acd6824c0734f8
[ "MIT" ]
null
null
null
Cocos2dWindowsPhone/CCCamera.cpp
GhostSoar/Cocos2dWindows
654a018004e358f875bedeb7c9acd6824c0734f8
[ "MIT" ]
null
null
null
/* * cocos2d-x http://www.cocos2d-x.org * * Copyright (c) 2010-2011 - cocos2d-x community * Copyright (c) 2010-2011 cocos2d-x.org * Copyright (c) 2008-2010 Ricardo Quesada * * Portions Copyright (c) Microsoft Open Technologies, Inc. * All Rights Reserved * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and limitations under the License. */ #include "pch.h" #include "CCCamera.h" //#include "CCDirector.h" #include "CCGL.h" #include "CCDrawingPrimitives.h" #include "CCDirector.h" using namespace std; NS_CC_BEGIN CCCamera::CCCamera(void) { init(); } CCCamera::~CCCamera(void) { } char * CCCamera::description(void) { char *ret = new char[100]; sprintf(ret, "<CCCamera | center = (%.2f,%.2f,%.2f)>", m_fCenterX, m_fCenterY, m_fCenterZ); return ret; } void CCCamera::init(void) { restore(); } void CCCamera::restore(void) { m_fEyeX = m_fEyeY = 0.0f; m_fEyeZ = getZEye(); m_fCenterX = m_fCenterY = m_fCenterZ = 0.0f; m_fUpX = 0.0f; m_fUpY = 1.0f; m_fUpZ = 0.0f; m_bDirty = false; } void CCCamera::locate(void) { if (m_bDirty) { /*=gluLookAt(m_fEyeX, m_fEyeY, m_fEyeZ, m_fCenterX, m_fCent erY, m_fCenterZ, m_fUpX, m_fUpY, m_fUpZ);*/ CCD3DCLASS->D3DLookAt(m_fEyeX, m_fEyeY, m_fEyeZ, m_fCenterX, m_fCenterY, m_fCenterZ, m_fUpX, m_fUpY, m_fUpZ); } } float CCCamera::getZEye(void) { return FLT_EPSILON; } void CCCamera::setEyeXYZ(float fEyeX, float fEyeY, float fEyeZ) { m_fEyeX = fEyeX * CC_CONTENT_SCALE_FACTOR(); m_fEyeY = fEyeY * CC_CONTENT_SCALE_FACTOR(); m_fEyeZ = fEyeZ * CC_CONTENT_SCALE_FACTOR(); m_bDirty = true; } void CCCamera::setCenterXYZ(float fCenterX, float fCenterY, float fCenterZ) { m_fCenterX = fCenterX * CC_CONTENT_SCALE_FACTOR(); m_fCenterY = fCenterY * CC_CONTENT_SCALE_FACTOR(); m_fCenterZ = fCenterZ * CC_CONTENT_SCALE_FACTOR(); m_bDirty = true; } void CCCamera::setUpXYZ(float fUpX, float fUpY, float fUpZ) { m_fUpX = fUpX; m_fUpY = fUpY; m_fUpZ = fUpZ; m_bDirty = true; } void CCCamera::getEyeXYZ(float *pEyeX, float *pEyeY, float *pEyeZ) { *pEyeX = m_fEyeX / CC_CONTENT_SCALE_FACTOR(); *pEyeY = m_fEyeY / CC_CONTENT_SCALE_FACTOR(); *pEyeZ = m_fEyeZ / CC_CONTENT_SCALE_FACTOR(); } void CCCamera::getCenterXYZ(float *pCenterX, float *pCenterY, float *pCenterZ) { *pCenterX = m_fCenterX / CC_CONTENT_SCALE_FACTOR(); *pCenterY = m_fCenterY / CC_CONTENT_SCALE_FACTOR(); *pCenterZ = m_fCenterZ / CC_CONTENT_SCALE_FACTOR(); } void CCCamera::getUpXYZ(float *pUpX, float *pUpY, float *pUpZ) { *pUpX = m_fUpX; *pUpY = m_fUpY; *pUpZ = m_fUpZ; } NS_CC_END
22.303704
131
0.718698
GhostSoar
f10bf3fed5e4e712d34c6f59ceef3c6480ad4825
206
cpp
C++
c.cpp
Zilanlann/cp-code
0500acbf6fb05a66f7bdbdf0e0a8bd6170126a4a
[ "MIT" ]
3
2022-03-30T14:14:57.000Z
2022-03-31T04:30:32.000Z
c.cpp
Zilanlann/cp-code
0500acbf6fb05a66f7bdbdf0e0a8bd6170126a4a
[ "MIT" ]
null
null
null
c.cpp
Zilanlann/cp-code
0500acbf6fb05a66f7bdbdf0e0a8bd6170126a4a
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int f() { static int i = 0; i++; return i; } int main() { cout << f() << endl; cout << f() << endl; cout << f() << endl; return 0; }
11.444444
24
0.466019
Zilanlann
f10ddadd51efabeee6e1234db2a55310379add09
3,512
cpp
C++
External/Quiver/Source/Quiver/Quiver/Graphics/b2DrawSFML.cpp
rachelnertia/Quarrel
69616179fc71305757549c7fcaccc22707a91ba4
[ "MIT" ]
39
2017-10-22T15:47:39.000Z
2020-03-31T22:19:55.000Z
External/Quiver/Source/Quiver/Quiver/Graphics/b2DrawSFML.cpp
rachelnertia/Quarrel
69616179fc71305757549c7fcaccc22707a91ba4
[ "MIT" ]
46
2017-10-26T21:21:51.000Z
2018-10-13T14:46:17.000Z
Source/Quiver/Quiver/Graphics/b2DrawSFML.cpp
rachelnertia/Quiver
c8ef9591117bdfc8d6fa509ae53451e0807f5686
[ "MIT" ]
8
2017-10-22T14:47:57.000Z
2020-03-19T10:08:45.000Z
#include "b2DrawSFML.h" #include "SFML/Graphics/RenderTarget.hpp" #include "SFML/Graphics/ConvexShape.hpp" #include "SFML/Graphics/CircleShape.hpp" inline sf::Color B2ColorToSFColor(const b2Color& color) { return sf::Color(sf::Uint8(color.r * 255), sf::Uint8(color.g * 255), sf::Uint8(color.b * 255), sf::Uint8(color.a * 255)); } inline sf::Vector2f B2VecToSFVec(const b2Vec2& b2vec) { return sf::Vector2f(b2vec.x, b2vec.y); } void b2DrawSFML::DrawPolygon(const b2Vec2 * vertices, int32 vertexCount, const b2Color & color) { sf::ConvexShape polygon(vertexCount); for (int i = 0; i < vertexCount; ++i) { sf::Vector2f pos = B2VecToSFVec(mCamera.WorldToCamera(vertices[i])); polygon.setPoint(i, pos); } polygon.setOutlineThickness(-1.0f); polygon.setFillColor(sf::Color::Transparent); polygon.setOutlineColor(B2ColorToSFColor(color)); mTarget->draw(polygon); } void b2DrawSFML::DrawSolidPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) { sf::ConvexShape polygon(vertexCount); for (int i = 0; i < vertexCount; ++i) { sf::Vector2f pos = B2VecToSFVec(mCamera.WorldToCamera(vertices[i])); polygon.setPoint(i, pos); } polygon.setOutlineThickness(-1.0f); polygon.setOutlineColor(B2ColorToSFColor(color)); sf::Color c = B2ColorToSFColor(color); c.a /= 2; polygon.setFillColor(c); mTarget->draw(polygon); } void b2DrawSFML::DrawCircle(const b2Vec2& center, float32 radius, const b2Color& color) { float scaled_radius = mCamera.MetresToPixels(radius); sf::CircleShape circle(scaled_radius); circle.setOrigin(scaled_radius, scaled_radius); circle.setPosition(B2VecToSFVec(mCamera.WorldToCamera(center))); circle.setOutlineThickness(-1.0f); circle.setOutlineColor(B2ColorToSFColor(color)); mTarget->draw(circle); } void b2DrawSFML::DrawSolidCircle(const b2Vec2& center, float32 radius, const b2Vec2& axis, const b2Color& color) { float scaled_radius = mCamera.MetresToPixels(radius); sf::CircleShape circle(scaled_radius); circle.setOrigin(scaled_radius, scaled_radius); circle.setPosition(B2VecToSFVec(mCamera.WorldToCamera(center))); circle.setOutlineThickness(-1.0f); circle.setOutlineColor(B2ColorToSFColor(color)); sf::Color c = B2ColorToSFColor(color); c.a /= 2; circle.setFillColor(c); b2Vec2 endPoint = center + radius * axis; sf::Vertex line[2] = { sf::Vertex(B2VecToSFVec(mCamera.WorldToCamera(center)), B2ColorToSFColor(color)), sf::Vertex(B2VecToSFVec(mCamera.WorldToCamera(endPoint)), B2ColorToSFColor(color)), }; mTarget->draw(circle); mTarget->draw(line, 2, sf::Lines); } void b2DrawSFML::DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color) { sf::Vertex line[] = { sf::Vertex(B2VecToSFVec(mCamera.WorldToCamera(p1)), B2ColorToSFColor(color)), sf::Vertex(B2VecToSFVec(mCamera.WorldToCamera(p2)), B2ColorToSFColor(color)) }; mTarget->draw(line, 2, sf::Lines); } void b2DrawSFML::DrawTransform(const b2Transform& xf) { float linelength = 0.4f; b2Vec2 xAxis = xf.p + linelength * xf.q.GetXAxis(); sf::Vertex redLine[] = { sf::Vertex(B2VecToSFVec(mCamera.WorldToCamera(xf.p)), sf::Color::Red), sf::Vertex(B2VecToSFVec(mCamera.WorldToCamera(xAxis)), sf::Color::Red) }; b2Vec2 yAxis = xf.p + linelength * xf.q.GetYAxis(); sf::Vertex greenLine[] = { sf::Vertex(B2VecToSFVec(mCamera.WorldToCamera(xf.p)), sf::Color::Green), sf::Vertex(B2VecToSFVec(mCamera.WorldToCamera(yAxis)), sf::Color::Green) }; mTarget->draw(redLine, 2, sf::Lines); mTarget->draw(greenLine, 2, sf::Lines); }
32.82243
114
0.73861
rachelnertia
f10fadc2b616b0e3691d5810353f1b09fbd56253
1,259
hh
C++
inc/Dno.hh
bsierp/ZadanieDronPrzeszkody
1eab1d3a994c5023aec4ae0f6d7d605a9ac3b240
[ "MIT" ]
null
null
null
inc/Dno.hh
bsierp/ZadanieDronPrzeszkody
1eab1d3a994c5023aec4ae0f6d7d605a9ac3b240
[ "MIT" ]
null
null
null
inc/Dno.hh
bsierp/ZadanieDronPrzeszkody
1eab1d3a994c5023aec4ae0f6d7d605a9ac3b240
[ "MIT" ]
null
null
null
#ifndef DNO_HH #define DNO_HH /*! * \file * \brief Definicja klasy Dno * * Plik zawiera definicje klasy Dno, * oraz deklaracje metod tej klasy. */ #include "Plaszczyzna.hh" using std::vector; using drawNS::Point3D; /*! * \brief Model pojęcia Dno * * Klasa modeluje pojęcie dna dziedzicząc * publicznie po klasie Plaszczyzna. */ class Dno: public Plaszczyzna{ public: /*! * \brief Konstruktor bezparametryczny klasy Dno * * Konstruktor inicjalizuje wymiary dna wartością zero. */ Dno(); /*! * \brief Konstruktor sześcioparametryczny klasy Dno * * Konstruktor inicjalizuje wymiary dna wartościami * parametrów \n * \param[in] max_x - maksymalny wymiar w osi x * \param[in] min_x - minimalny wymiar w osi x * \param[in] max_y - maksymalny wymiar w osi y * \param[in] min_y - minimalny wymiar w osi y * \param[in] z - poziom płaszczyzny w osi z * \param[in] api - wskaźnik do programu graficznego, w którym ma być rysowany obiekt */ Dno(double max_x, double min_x, double max_y, double min_y,double z, drawNS::Draw3DAPI * api); void Rysuj() override; void Poziom(double level) override; void Wymaz() override; bool czy_kolizja(std::shared_ptr<Interfejs> drone) const override; }; #endif
27.977778
94
0.698173
bsierp
f1127201f4fe21f6b3b4f4e95741d87e1bf89176
515
hpp
C++
_engine/code/include/global/component/logger/provider/console.hpp
Shelim/pixie_engine
bf1d80f3f03bd3d6890f4dfc63440f7dd0ff34a1
[ "MIT" ]
null
null
null
_engine/code/include/global/component/logger/provider/console.hpp
Shelim/pixie_engine
bf1d80f3f03bd3d6890f4dfc63440f7dd0ff34a1
[ "MIT" ]
null
null
null
_engine/code/include/global/component/logger/provider/console.hpp
Shelim/pixie_engine
bf1d80f3f03bd3d6890f4dfc63440f7dd0ff34a1
[ "MIT" ]
null
null
null
#ifndef ENGINE_COMPONENT_LOGGER_PROVIDER_CONSOLE_HPP #define ENGINE_COMPONENT_LOGGER_PROVIDER_CONSOLE_HPP #pragma once #include "global/component/logger/real.hpp" namespace engine { class logger_provider_console_t : public logger_provider_base_t { public: logger_provider_console_t(std::shared_ptr<console_writer_t> console_writer); void output(const engine::console::logger_item_t & item) const final; private: std::shared_ptr<console_writer_t> console_writer; }; } #endif
19.807692
84
0.780583
Shelim
f11551cac5b576a3fa138845655d64ac77fc9163
18,884
cpp
C++
src/GLMesh.cpp
bpwiselybabu/SceneGraph
1ae7142615bb2c15883ed928a5ed69b0cd281665
[ "Apache-2.0" ]
15
2015-10-18T15:11:34.000Z
2021-06-15T02:22:13.000Z
src/GLMesh.cpp
bpwiselybabu/SceneGraph
1ae7142615bb2c15883ed928a5ed69b0cd281665
[ "Apache-2.0" ]
13
2015-04-24T20:37:44.000Z
2020-01-27T15:26:42.000Z
src/GLMesh.cpp
bpwiselybabu/SceneGraph
1ae7142615bb2c15883ed928a5ed69b0cd281665
[ "Apache-2.0" ]
9
2015-08-21T18:52:27.000Z
2020-04-08T15:15:38.000Z
#include <stdlib.h> #include <limits.h> #include <SceneGraph/GLMesh.h> #include <SceneGraph/GLHelpersLoadTextures.h> #include <assimp/cimport.h> #include <assimp/postprocess.h> namespace SceneGraph { GLMesh::Mesh::Mesh() { m_uVB = 0; m_uIB = 0; m_uNumIndices = 0; m_uMaterialIndex = -1; } GLMesh::Mesh::~Mesh() { if (m_uVB != 0) { glDeleteBuffers(1, &m_uVB); } if (m_uIB != 0) { glDeleteBuffers(1, &m_uIB); } } bool GLMesh::Mesh::Init(const std::vector<Vertex>& vVertices, const std::vector<unsigned int>& vIndices, const aiMatrix4x4& mTrans) { m_Transformation = mTrans; m_uNumIndices = vIndices.size(); int nVertexSize = sizeof(Vertex); glGenBuffers(1, &m_uVB); glBindBuffer(GL_ARRAY_BUFFER, m_uVB); glBufferData(GL_ARRAY_BUFFER, nVertexSize * vVertices.size(), &vVertices[0], GL_DYNAMIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); glGenBuffers(1, &m_uIB); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_uIB); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int) * m_uNumIndices, &vIndices[0], GL_DYNAMIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); return true; } //////////////////////////////////////////////////////////////////////////// // Simple inline utilities for this class //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// inline void color4_to_float4(const aiColor4D* c, float f[4]) { f[0] = c->r; f[1] = c->g; f[2] = c->b; f[3] = c->a; } //////////////////////////////////////////////////////////////////////////// inline void set_float4(float f[4], float a, float b, float c, float d) { f[0] = a; f[1] = b; f[2] = c; f[3] = d; } //////////////////////////////////////////////////////////////////////////// inline GLenum GLWrapFromAiMapMode(aiTextureMapMode mode) { switch (mode) { case aiTextureMapMode_Wrap: return GL_REPEAT; case aiTextureMapMode_Clamp: return GL_CLAMP; default: std::cerr << "Unsupported aiTextureMapMode used" << std::endl; return GL_CLAMP; } } //////////////////////////////////////////////////////////////////////////// // GLMesh Class implementation //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// GLMesh::GLMesh() : GLObject("Mesh"), m_pScene(0), m_fAlpha(1), m_bShowMeshNormals(false), m_meshcolor(SceneGraph::GLColor(1.0f, 1.0f, 1.0f)), //default mesh color m_uMeshCount(0) { m_iMeshID = AllocSelectionId(); } /* //////////////////////////////////////////////////////////////////////////// GLMesh::GLMesh(const std::string& sMeshFile) : GLObject("Mesh"), m_pScene(0), m_fAlpha(1), m_bShowMeshNormals(false), m_meshcolor(SceneGraph::GLColor(1.0f, 1.0f, 1.0f)), //default mesh color m_uMeshCount(0) { m_iMeshID = AllocSelectionId(); Init(sMeshFile); } */ //////////////////////////////////////////////////////////////////////////// GLMesh::~GLMesh() { // Delete textures for (std::map<std::string, GLuint>::iterator i = m_mapPathToGLTex.begin(); i != m_mapPathToGLTex.end(); ++i) { glDeleteTextures(1, &i->second); } // Free scene if (m_pScene) { aiReleaseImport(m_pScene); } } //////////////////////////////////////////////////////////////////////////// void GLMesh::SetMeshColor(SceneGraph::GLColor& mesh_color) { m_meshcolor = mesh_color; } //////////////////////////////////////////////////////////////////////////// bool GLMesh::Init(const std::string& sMeshFile, bool bFlipUVs /*= false*/) { SetObjectName("mesh"); std::string sMeshPath(realpath(sMeshFile.c_str(), NULL)); m_sMeshPath = sMeshPath.substr(0, sMeshPath.find_last_of("\\/")) + "/"; m_pScene = aiImportFile( sMeshFile.c_str(), aiProcess_Triangulate | aiProcess_GenSmoothNormals | aiProcess_JoinIdenticalVertices // | //aiProcess_TransformUVCoords | (bFlipUVs == true ? aiProcess_FlipUVs : 0) // | //aiProcess_FlipWindingOrder | aiProcess_OptimizeMeshes | aiProcess_FindInvalidData // | //aiProcess_SortByPType // | //aiProcess_GenUVCoords | aiProcess_FixInfacingNormals); if (m_pScene == NULL) { return false; } return Init(m_pScene); } //////////////////////////////////////////////////////////////////////////// bool GLMesh::Init(const struct aiScene* pScene) { m_pScene = pScene; m_Meshes.resize(pScene->mNumMeshes); InitNode(m_pScene, m_pScene->mRootNode, aiMatrix4x4()); LoadMeshTextures(); ComputeDimensions(); return true; } //////////////////////////////////////////////////////////////////////////// void GLMesh::InitNode(const struct aiScene* sc, const struct aiNode* nd, const aiMatrix4x4& mTransformation) { aiMatrix4x4 trans = mTransformation * nd->mTransformation; // draw all meshes assigned to this node for (unsigned int n = 0; n < nd->mNumMeshes; ++n) { const struct aiMesh* mesh = m_pScene->mMeshes[nd->mMeshes[n]]; InitMesh(m_uMeshCount, mesh, trans); m_uMeshCount++; } // draw all children for (unsigned int n = 0; n < nd->mNumChildren; ++n) { InitNode(sc, nd->mChildren[n], trans); } } //////////////////////////////////////////////////////////////////////////// void GLMesh::InitMesh(unsigned int Index, const aiMesh* paiMesh, const aiMatrix4x4& mTransformation) { m_Meshes[Index].m_uMaterialIndex = paiMesh->mMaterialIndex; std::vector<Vertex> Vertices; std::vector<unsigned int> Indices; const aiVector3D Zero3D(0.0f, 0.0f, 0.0f); for (unsigned int i = 0; i < paiMesh->mNumVertices; i++) { const aiVector3D* pPos = paiMesh->HasPositions() ? &(paiMesh->mVertices[i]) : &Zero3D; const aiVector3D* pNormal = paiMesh->HasNormals() ? &(paiMesh->mNormals[i]) : &Zero3D; const aiVector3D* pTexCoord = paiMesh->HasTextureCoords(0) ? &(paiMesh->mTextureCoords[0][i]) : &Zero3D; Vertex v(pPos->x, pPos->y, pPos->z, pTexCoord->x, pTexCoord->y, pNormal->x, pNormal->y, pNormal->z); Vertices.push_back(v); } for (unsigned int i = 0; i < paiMesh->mNumFaces; i++) { const aiFace& Face = paiMesh->mFaces[i]; if (Face.mNumIndices == 3) { Indices.push_back(Face.mIndices[0]); Indices.push_back(Face.mIndices[1]); Indices.push_back(Face.mIndices[2]); } } m_Meshes[Index].Init(Vertices, Indices, mTransformation); } //////////////////////////////////////////////////////////////////////////// void GLMesh::ShowNormals(bool showNormals) { m_bShowMeshNormals = showNormals; } //////////////////////////////////////////////////////////////////////////// void GLMesh::DrawCanonicalObject() { if (m_pScene) { glPushName(m_iMeshID); glColor4f(m_meshcolor.r, m_meshcolor.g, m_meshcolor.b, m_meshcolor.a); for (unsigned int i = 0; i < m_Meshes.size(); i++) { glBindBuffer(GL_ARRAY_BUFFER, m_Meshes[i].m_uVB); glVertexPointer(3, GL_FLOAT, sizeof(Vertex), 0); glEnableClientState(GL_VERTEX_ARRAY); size_t uNormalOffset = 3 * sizeof(float); glNormalPointer(GL_FLOAT, sizeof(Vertex), (GLvoid*)uNormalOffset); glEnableClientState(GL_NORMAL_ARRAY); size_t uTexOffset = 6 * sizeof(float); glTexCoordPointer(2, GL_FLOAT, sizeof(Vertex), (GLvoid*)uTexOffset); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_Meshes[i].m_uIB); const unsigned int MaterialIndex = m_Meshes[i].m_uMaterialIndex; const aiMaterial* pMaterial = m_pScene->mMaterials[MaterialIndex]; ApplyMaterial(pMaterial); // WARNING: A relatively arbitrary list of texture types to // try and load. In the future these should be dealt with properly const size_t numTexTypesToLoad = 4; static aiTextureType texTypesToLoad[numTexTypesToLoad] = { aiTextureType_DIFFUSE, aiTextureType_AMBIENT, aiTextureType_EMISSIVE, aiTextureType_LIGHTMAP}; int totaltex = 0; for (size_t tti = 0; tti < numTexTypesToLoad; ++tti) { const aiTextureType tt = texTypesToLoad[tti]; const unsigned int numTex = pMaterial->GetTextureCount(tt); totaltex += numTex; for (unsigned int dt = 0; dt < numTex; ++dt) { aiString path; if (pMaterial->GetTexture(tt, dt, &path) == AI_SUCCESS) { std::map<std::string, GLuint>::iterator ix = m_mapPathToGLTex.find(path.data); if (ix != m_mapPathToGLTex.end()) { glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, ix->second); // Only bind first one for now. goto endoftextures; } } } } endoftextures: aiMatrix4x4 m = m_Meshes[i].m_Transformation; aiTransposeMatrix4(&m); glPushMatrix(); glMultMatrixf(&(m.a1)); glDrawElements(GL_TRIANGLES, m_Meshes[i].m_uNumIndices, GL_UNSIGNED_INT, 0); glPopMatrix(); if (totaltex > 0) { glDisable(GL_TEXTURE_2D); } glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); } glPopName(); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); } } void GLMesh::ComputeNodeBounds(const struct aiScene* pAIScene, const struct aiNode* pAINode, AxisAlignedBoundingBox& aabb, aiMatrix4x4 dParentTransform) { aiMesh* pAIMesh; for (unsigned int x = 0; x < pAINode->mNumMeshes; x++) { pAIMesh = pAIScene->mMeshes[pAINode->mMeshes[x]]; for (unsigned int y = 0; y < pAIMesh->mNumVertices; y++) { aiVector3D pAIVector = dParentTransform * pAIMesh->mVertices[y]; // aiVector3D pAIVector = pAINode->mTransformation * // pAIMesh->mVertices[y]; const Eigen::Vector3d p = Eigen::Vector3d(pAIVector.x, pAIVector.y, pAIVector.z); m_aabb.Insert(p); } } for (unsigned int x = 0; x < pAINode->mNumChildren; x++) { ComputeNodeBounds( pAIScene, pAINode->mChildren[x], aabb, dParentTransform * pAINode->mChildren[x]->mTransformation); } } /////////////////////////// bool GLMesh::IsSelectable() { return m_bIsSelectable; } /////////////////////////// void GLMesh::SetScale(Eigen::Vector3d s) { GLObject::SetScale(s); ComputeDimensions(); } /////////////////////////// void GLMesh::SetScale(double s) { GLObject::SetScale(s); ComputeDimensions(); } /////////////////////////// void GLMesh::ComputeDimensions() { m_aabb.Clear(); ComputeNodeBounds(this->GetScene(), this->GetScene()->mRootNode, m_aabb, this->GetScene()->mRootNode->mTransformation); m_aabb.Min().array() *= GLObject::GetScale().array(); m_aabb.Max().array() *= GLObject::GetScale().array(); } // Getters and setters const struct aiScene* GLMesh::GetScene(void) { return m_pScene; } Eigen::Vector3d GLMesh::GetDimensions() { return m_aabb.Size(); } //////////////////////////////////////////////////////////////////////////// void GLMesh::LoadMeshTextures() { #ifdef HAVE_DEVIL // Ensure DevIL library is initialised static bool firsttime = true; if (firsttime) { ilInit(); iluInit(); firsttime = false; } #endif // HAVE_DEVIL // For each material, find associated textures for (unsigned int m = 0; m < m_pScene->mNumMaterials; ++m) { LoadMaterialTextures(m_pScene->mMaterials[m]); } } //////////////////////////////////////////////////////////////////////////// void GLMesh::LoadMaterialTextures(aiMaterial* pMaterial) { // Try to load textures of any type for (aiTextureType tt = aiTextureType_NONE; tt <= aiTextureType_UNKNOWN; tt = (aiTextureType)((int)tt + 1)) { const unsigned int numTex = pMaterial->GetTextureCount(tt); for (unsigned int dt = 0; dt < numTex; ++dt) { aiString path; aiTextureMapping* mapping = 0; unsigned int* uvindex = 0; float* blend = 0; aiTextureOp* op = 0; aiTextureMapMode* mapmode = 0; aiReturn texFound = pMaterial->GetTexture(tt, dt, &path, mapping, uvindex, blend, op, mapmode); char fullMeshPath[PATH_MAX+1]; strncpy(fullMeshPath, m_sMeshPath.c_str(), sizeof(fullMeshPath)); strncat(fullMeshPath, path.C_Str(), sizeof(fullMeshPath)); aiString meshfile(fullMeshPath); // Attempt to load reference to texture data as OpenGL // texture, with appropriate properties set. if (texFound == AI_SUCCESS) { GLuint glTex = LoadGLTextureResource(meshfile); if (glTex > 0) { m_mapPathToGLTex[path.data] = glTex; glBindTexture(GL_TEXTURE_2D, glTex); // Use bilinear interpolation for textures glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // glTexParameteri(GL_TEXTURE_2D, // GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); if (mapping != 0) { std::cerr << "Ignoring mapping" << std::endl; } if (uvindex != 0) { std::cerr << "Ignoring uvindex" << std::endl; } if (blend != 0) { std::cerr << "Ignoring blend" << std::endl; } if (op != 0) { std::cerr << "Ignoring aiTextureOp" << std::endl; } if (mapmode != 0) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GLWrapFromAiMapMode(mapmode[0])); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GLWrapFromAiMapMode(mapmode[1])); } glBindTexture(GL_TEXTURE_2D, 0); } else { std::cerr << "Failed to load texture. Type: " << (int)tt << ", id: " << dt << " path: " << meshfile.C_Str() << std::endl; } } else { std::cerr << "Failed to get texture. Type: " << (int)tt << ", id: " << dt << " path: " << meshfile.C_Str() << std::endl; } } } } //////////////////////////////////////////////////////////////////////////// GLuint GLMesh::LoadGLTextureResource(aiString& path) { GLuint glTex = 0; if (path.length > 0 && path.data[0] == '*') { // Texture embedded in file std::stringstream ss(std::string(path.data + 1)); int sId = -1; ss >> sId; if (0 <= sId && sId < (int)m_pScene->mNumTextures) { aiTexture* aiTex = m_pScene->mTextures[sId]; if (aiTex->mHeight == 0) { glTex = LoadGLTextureFromArray((unsigned char*)aiTex->pcData, aiTex->mWidth, aiTex->achFormatHint); } else { // WARNING: Untested code condition! glGenTextures(1, &glTex); glBindTexture(GL_TEXTURE_2D, glTex); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, aiTex->mWidth, aiTex->mHeight, 0, GL_BGRA, GL_UNSIGNED_BYTE, aiTex->pcData); } } else { std::cerr << "Unable to Load embedded texture, bad path: " << path.data << std::endl; } } else { // Texture in file resource try { glTex = LoadGLTextureFromFile(path.data, path.length); } catch (std::exception e) { std::stringstream ss; ss << "Could not load texture: " << path.C_Str(); std::cerr << ss.str() << std::endl; // throw std::runtime_error(ss.str()); } } return glTex; } //////////////////////////////////////////////////////////////////////////// void GLMesh::ApplyMaterial(const struct aiMaterial* mtl) { float c[4]; GLenum fill_mode; int ret1, ret2; aiColor4D diffuse; aiColor4D specular; aiColor4D ambient; aiColor4D emission; float shininess, strength; int two_sided; int wireframe; unsigned int max; set_float4(c, 0.8f, 0.8f, 0.8f, 1.0f); if (AI_SUCCESS == aiGetMaterialColor(mtl, AI_MATKEY_COLOR_DIFFUSE, &diffuse)) { color4_to_float4(&diffuse, c); } c[3] *= m_fAlpha; glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, c); set_float4(c, 0.0f, 0.0f, 0.0f, 1.0f); if (AI_SUCCESS == aiGetMaterialColor(mtl, AI_MATKEY_COLOR_SPECULAR, &specular)) { color4_to_float4(&specular, c); } c[3] *= m_fAlpha; glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, c); set_float4(c, 0.2f, 0.2f, 0.2f, 1.0f); if (AI_SUCCESS == aiGetMaterialColor(mtl, AI_MATKEY_COLOR_AMBIENT, &ambient)) { color4_to_float4(&ambient, c); } c[3] *= m_fAlpha; glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, c); set_float4(c, 0.0f, 0.0f, 0.0f, 1.0f); if (AI_SUCCESS == aiGetMaterialColor(mtl, AI_MATKEY_COLOR_EMISSIVE, &emission)) { color4_to_float4(&emission, c); } c[3] *= m_fAlpha; glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, c); CheckForGLErrors(); max = 1; ret1 = aiGetMaterialFloatArray(mtl, AI_MATKEY_SHININESS, &shininess, &max); if (ret1 == AI_SUCCESS) { max = 1; ret2 = aiGetMaterialFloatArray(mtl, AI_MATKEY_SHININESS_STRENGTH, &strength, &max); if (ret2 == AI_SUCCESS) { glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, shininess * strength); CheckForGLErrors(); } else { // glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, // shininess); glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 1); CheckForGLErrors(); } } else { glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 0.0f); set_float4(c, 0.0f, 0.0f, 0.0f, 0.0f); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, c); CheckForGLErrors(); } return; max = 1; if (AI_SUCCESS == aiGetMaterialIntegerArray(mtl, AI_MATKEY_ENABLE_WIREFRAME, &wireframe, &max)) { fill_mode = wireframe ? GL_LINE : GL_FILL; } else { fill_mode = GL_FILL; } glPolygonMode(GL_FRONT_AND_BACK, fill_mode); CheckForGLErrors(); max = 1; if ((AI_SUCCESS == aiGetMaterialIntegerArray(mtl, AI_MATKEY_TWOSIDED, &two_sided, &max)) && two_sided) { glDisable(GL_CULL_FACE); CheckForGLErrors(); } else { glEnable(GL_CULL_FACE); CheckForGLErrors(); } } } // namespace SceneGraph
32.335616
84
0.561322
bpwiselybabu
47db47d8b15100b3ebd8ee0cd94303f6385ff9e6
871
cpp
C++
arrays-and-strings/is_rotation.cpp
kanishkdudeja/cracking-the-coding-interview-solutions
b6b495eb838e3739fd09aaf1ea5a5a5eb15923d0
[ "MIT" ]
1
2019-12-29T17:47:53.000Z
2019-12-29T17:47:53.000Z
arrays-and-strings/is_rotation.cpp
kanishkdudeja/cracking-the-coding-interview-solutions
b6b495eb838e3739fd09aaf1ea5a5a5eb15923d0
[ "MIT" ]
null
null
null
arrays-and-strings/is_rotation.cpp
kanishkdudeja/cracking-the-coding-interview-solutions
b6b495eb838e3739fd09aaf1ea5a5a5eb15923d0
[ "MIT" ]
null
null
null
/* Problem: Given two strings, find out if the second string is a rotation of the first. Approach: Concatenate first string with itself and check if second string is a substring of the concatenated string. If yes, then it's a rotation. Otherwise not. Space Complexity = O(n) since we are saving concatenated length of 2 times first string in memory O(2n) Time Complexity depends upon time complexity of doing substring check. Other than that, concatenation would take O(n) time */ #include <iostream> #include <string> using namespace std; bool isRotation(string s1, string s2) { if(s1.length() != s2.length()) { return false; } if(s1 == s2) { return true; } string s3 = s1 + s1; if(s3.find(s2) != std::string::npos) { return true; } else { return false; } } int main() { string s1 = "hello"; string s2 = "lohel"; cout<<isRotation(s1, s2); }
22.921053
103
0.700344
kanishkdudeja