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
108
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
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
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
d2524a730ed575f4317f425ea7d902dada5e6103
4,739
cpp
C++
src/framework/fastapi/BaseHttpRequestParams.cpp
AronProgram/pccl
d9f1c5ee3ed81d3195fab0765bb58cce1c97a91a
[ "MIT" ]
3
2020-11-02T01:12:36.000Z
2021-03-12T08:44:57.000Z
src/framework/fastapi/BaseHttpRequestParams.cpp
AronProgram/pccl
d9f1c5ee3ed81d3195fab0765bb58cce1c97a91a
[ "MIT" ]
null
null
null
src/framework/fastapi/BaseHttpRequestParams.cpp
AronProgram/pccl
d9f1c5ee3ed81d3195fab0765bb58cce1c97a91a
[ "MIT" ]
1
2021-03-12T08:44:30.000Z
2021-03-12T08:44:30.000Z
/** * pccl is pleased to support the open source community by making Tars available. * * Copyright (C) 2016THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * https://opensource.org/licenses/BSD-3-Clause * * Unless required by applicable law or agreed to in writing, software distributed * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ #include "BaseHttpRequestParams.h" #include "util/tc_epoll_server.h" #include "util/tc_common.h" #include "util/tc_cgi.h" #include "json.h" #include "BaseHttpPlus.h" #include "BaseRandom.h" #include <algorithm> namespace pccl { BaseHttpRequestParams::BaseHttpRequestParams(void) : _bodyType(HTTP_BODY_NOTHING) { } BaseHttpRequestParams::~BaseHttpRequestParams(void) { } void BaseHttpRequestParams::setBuffer(std::vector<char>* inBuffer, std::vector<char>* outBuffer) { _inBuffer = inBuffer; _outBuffer = outBuffer; } std::vector<char>& BaseHttpRequestParams::getOutBuffer(void) { return *_outBuffer; } void BaseHttpRequestParams::reset() { _bodyType = HTTP_BODY_NOTHING; _sequence.clear(); _route.clear(); _params.clear(); _doc.clear(); tars::TC_HttpRequest::reset(); } int BaseHttpRequestParams::parse(void) { int result = parseHttpPacket(); if ( pccl::STATE_SUCCESS != result ) { return pccl::STATE_ERROR; } result = parseHttpBody(); // 构建染色ID,用于日志的数据链条的追踪 _sequence = BaseRandom::alpha(12); // 获取HTTP路由 _route = this->getRequestUrl(); dump(); return result; } std::string& BaseHttpRequestParams::getSequence(void) { return _sequence; } int BaseHttpRequestParams::parseHttpPacket(void) { std::vector<char>& inBuffer = *_inBuffer; TLOGDEBUG("parse http packet:" << std::string( (const char*) &inBuffer[0], inBuffer.size() ) << "\n" ); bool status = this->decode( (const char*) &inBuffer[0] , inBuffer.size() ); if ( !status ) { TLOGERROR( "parse http packet error" << std::endl ); return pccl::STATE_ERROR; } //解析http query stirng 的参数 parseQueryHeader(); return pccl::STATE_SUCCESS; } int BaseHttpRequestParams::parseHttpBody(void) { _doc.clear(); std::string header = this->getHeader("Content-Type"); if ( header.find("application/json") ) { parseJsonBody(); return pccl::STATE_SUCCESS; } parseQueryBody(); return pccl::STATE_SUCCESS; } int BaseHttpRequestParams::parseJsonBody(void) { // 解析body: json std::string content = this->getContent(); Json::CharReaderBuilder builder; const std::unique_ptr<Json::CharReader> reader( builder.newCharReader() ); JSONCPP_STRING err; bool status = reader->parse(content.c_str(), content.c_str() + content.length() , &_doc, &err); if ( status ) { _bodyType = HTTP_BODY_JSON; } return pccl::STATE_SUCCESS; } void BaseHttpRequestParams::parseQueryHeader(void) { std::string request = getRequest(); split(request); _bodyType = HTTP_BODY_QUERY; } void BaseHttpRequestParams::parseQueryBody(void) { std::string content = this->getContent(); split(content); } void BaseHttpRequestParams::split(const std::string& sQuery) { std::vector<std::string> query = tars::TC_Common::sepstr<std::string>(sQuery,"&"); for( std::size_t i = 0; i < query.size(); i++ ) { { std::vector<std::string> params; params.clear(); params = tars::TC_Common::sepstr<std::string>(query[i],"=",true); if ( 2 == params.size() ) { _params[ params[0] ] = tars::TC_Cgi::decodeURL(params[1]); } } } } const std::string& BaseHttpRequestParams::getRoute() { return _route; } void BaseHttpRequestParams::putParams(const std::string& sKey, const std::string& sValue ) { _params[ sKey ] = sValue ; } std::string BaseHttpRequestParams::getRemoteIp(void) { //const http_header_type& header = getHeaders(); if ( !this->getHeader("X-real-ip").empty() ) { return this->getHeader("X-real-ip"); } else if ( !this->getHeader("X-Forwarded-For").empty() ) { return this->getHeader("X-Forwarded-For"); } else { return "127.0.0.1"; } } void BaseHttpRequestParams::dump(void) { dumpParams(); } void BaseHttpRequestParams::dumpParams(void) { TLOGDEBUG( "dumpParams, " << _sequence << std::endl ); for( auto it = _params.begin(); it != _params.end(); it++ ) { TLOGDEBUG( "dumpParams, " << _sequence << ", key:" <<it->first << ",value:" << it->second << std::endl); } } }
18.226923
106
0.683689
AronProgram
d256c83666ad4cee9089b186ee1de5b9456c9586
545
cpp
C++
src/unity/lib/annotation/class_registrations.cpp
LeeCenY/turicreate
fb2f3bf313e831ceb42a2e10aacda6e472ea8d93
[ "BSD-3-Clause" ]
null
null
null
src/unity/lib/annotation/class_registrations.cpp
LeeCenY/turicreate
fb2f3bf313e831ceb42a2e10aacda6e472ea8d93
[ "BSD-3-Clause" ]
2
2022-01-13T04:03:55.000Z
2022-03-12T01:02:31.000Z
src/unity/lib/annotation/class_registrations.cpp
ZeroInfinite/turicreate
dd210c2563930881abd51fd69cb73007955b33fd
[ "BSD-3-Clause" ]
null
null
null
#include <unity/lib/annotation/class_registrations.hpp> #include <unity/lib/annotation/annotation_base.hpp> #include <unity/lib/annotation/image_classification.hpp> namespace turi { namespace annotate { BEGIN_CLASS_REGISTRATION REGISTER_CLASS(ImageClassification) REGISTER_CLASS(annotation_global) END_CLASS_REGISTRATION BEGIN_FUNCTION_REGISTRATION REGISTER_FUNCTION(create_image_classification_annotation, "data", "data_columns", "annotation_column"); END_FUNCTION_REGISTRATION } // namespace annotate } // namespace turi
27.25
65
0.822018
LeeCenY
d257626bef78f94d4cd9fbcdbdf1ed92003ef3b1
587
cpp
C++
CSES-Problemset/sorting and searching/ferris_wheel.cpp
rranjan14/cp-solutions
9614508efbed1e4ee8b970b5eed535d782a5783f
[ "MIT" ]
null
null
null
CSES-Problemset/sorting and searching/ferris_wheel.cpp
rranjan14/cp-solutions
9614508efbed1e4ee8b970b5eed535d782a5783f
[ "MIT" ]
null
null
null
CSES-Problemset/sorting and searching/ferris_wheel.cpp
rranjan14/cp-solutions
9614508efbed1e4ee8b970b5eed535d782a5783f
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <algorithm> #define vlli vector<long long int> typedef long long int lli; using namespace std; int main() { lli n, x, count = 0; cin >> n >> x; vlli p(n, 0); for (int i = 0; i < n; i++) { cin >> p[i]; } sort(p.begin(), p.end()); lli i = 0, j = n - 1; while (i <= j) { if (p[i] + p[j] <= x) { count++; i++; j--; } else { j--; count++; } } cout << count << "\n"; return 0; }
17.264706
34
0.383305
rranjan14
d2576a85dc4d3b7319eb53f12d375a804d4fd722
539
cpp
C++
Grade_10/Second_Semester/max_sum_from_pairs.cpp
MagicWinnie/SESC_IT
934ac49a177bfa5d02fc3234d31c929aad3c60c2
[ "MIT" ]
2
2020-10-10T10:21:49.000Z
2021-05-28T18:10:42.000Z
Grade_10/Second_Semester/max_sum_from_pairs.cpp
MagicWinnie/SESC_IT
934ac49a177bfa5d02fc3234d31c929aad3c60c2
[ "MIT" ]
null
null
null
Grade_10/Second_Semester/max_sum_from_pairs.cpp
MagicWinnie/SESC_IT
934ac49a177bfa5d02fc3234d31c929aad3c60c2
[ "MIT" ]
null
null
null
// You get N pairs, from which you have to choose one number so the sum is max and does not divide by 3. #include <iostream> #include <algorithm> #include <cmath> using namespace std; int main() { int n; int s = 0, mr = 1000000; cin >> n; for (int i = 0; i < n; i++) { int a, b; cin >> a >> b; s += (a > b) ? a : b; if (abs(a - b) % 3 != 0 && abs(a - b) < mr) mr = abs(a - b); } if (s % 3 != 0) cout << s << endl; else cout << s - mr << endl; }
20.730769
104
0.45269
MagicWinnie
d259aa34186e6601ee8e659cfc1d36c1f77b120b
1,466
cpp
C++
Striver SDE Sheet/Day - 4 (Hashing)/2 Sum.cpp
HariAcidReign/Striver-SDE-Solutions
80757b212abe479f3975b890398a8d877ebfd41e
[ "MIT" ]
25
2021-08-17T04:04:41.000Z
2022-03-16T07:43:30.000Z
Striver SDE Sheet/Day - 4 (Hashing)/2 Sum.cpp
hashwanthalla/Striver-Sheets-Resources
80757b212abe479f3975b890398a8d877ebfd41e
[ "MIT" ]
null
null
null
Striver SDE Sheet/Day - 4 (Hashing)/2 Sum.cpp
hashwanthalla/Striver-Sheets-Resources
80757b212abe479f3975b890398a8d877ebfd41e
[ "MIT" ]
8
2021-08-18T02:02:23.000Z
2022-02-11T06:05:07.000Z
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<pair<int, int>> x; int n = nums.size(); for(int i = 0; i < n; i++) { x.push_back(make_pair(nums[i], i)); } sort(x.begin(), x.end()); int l = 0; int r = n-1; vector<int> res; while(l < r) { if(x[l].first + x[r].first == target) { res.push_back(x[l].second); res.push_back(x[r].second); break; } else if(x[l].first + x[r].first > target) r--; else l++; } sort(res.begin(), res.end()); return res; } }; // Hari's class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<pair<int, int>> vec; vector<int> res; for(int i = 0; i<nums.size(); i++){ vec.push_back(make_pair(nums[i], i)); } sort(vec.begin(), vec.end()); int p1 = 0, p2 = vec.size()-1; while(p1 < p2){ if(vec[p1].first + vec[p2].first == target){ res.push_back(vec[p1].second); res.push_back(vec[p2].second); return res; } else if(vec[p1].first + vec[p2].first < target){ p1++; } else p2--; } return res; } };
25.719298
60
0.411323
HariAcidReign
d259c7036112467ec25aa92d8d95aeb523336782
6,860
cpp
C++
Projects/krkr2_on_VC/kirikiri2/src/tools/win32/krdevui/SignUnit.cpp
CATION-M/X-moe
2bac3bb45ff21e50921aac8422f2e00839f546e5
[ "MIT" ]
2
2020-02-25T15:18:53.000Z
2020-08-24T13:30:34.000Z
Projects/kirikiri2-master/kirikiri2/src/tools/win32/krdevui/SignUnit.cpp
CATION-M/X-moe
2bac3bb45ff21e50921aac8422f2e00839f546e5
[ "MIT" ]
null
null
null
Projects/kirikiri2-master/kirikiri2/src/tools/win32/krdevui/SignUnit.cpp
CATION-M/X-moe
2bac3bb45ff21e50921aac8422f2e00839f546e5
[ "MIT" ]
1
2019-11-25T05:29:30.000Z
2019-11-25T05:29:30.000Z
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "SignUnit.h" #include "RandomizeFormUnit.h" #define _MSC_VER #include <tomcrypt.h> #undef _MSC_VER #include <string.h> #define HASH_INIT sha256_init #define HASH_PROCESS sha256_process #define HASH_DONE sha256_done #define HASH_DESC sha256_desc #define HASH_METHOD_STRING "SHA256" #define HASH_METHOD_INTERNAL_STRING "sha256" #define HASH_SIZE 32 //--------------------------------------------------------------------------- AnsiString Split64(AnsiString s) { // split s in 64characters intervally int len = s.Length(); const char * p = s.c_str(); AnsiString ret; while(len > 0) { int one_size = len > 64 ? 64 : len; ret += AnsiString(p, one_size) + "\r\n"; p += one_size; len -= one_size; } return ret; } //--------------------------------------------------------------------------- static void MakeFileHash(AnsiString fn, unsigned char *hash, int ignorestart, int ignoreend) { if(find_hash(HASH_METHOD_INTERNAL_STRING) == -1) { int errnum = register_hash(&HASH_DESC); if(errnum != CRYPT_OK) throw Exception(error_to_string(errnum)); } TFileStream *fs; fs = new TFileStream(fn, fmOpenRead | fmShareDenyWrite); if(ignorestart != -1 && ignoreend == -1) ignoreend = fs->Size; try { hash_state st; HASH_INIT(&st); int read; unsigned char buf[4096]; int ofs = 0; while((read = fs->Read(buf, sizeof(buf))) != 0) { if(ignorestart != -1 && read + ofs > ignorestart) { read = ignorestart - ofs; if(read) HASH_PROCESS(&st, buf, read); break; } else { HASH_PROCESS(&st, buf, read); } ofs += read; } if(ignorestart != -1 && fs->Position != ignoreend) { fs->Position = ofs = ignoreend; while((read = fs->Read(buf, sizeof(buf))) != 0) { HASH_PROCESS(&st, buf, read); ofs += read; } } HASH_DONE(&st, hash); } catch(...) { delete fs; throw; } delete fs; } //--------------------------------------------------------------------------- static void ImportKey(AnsiString inkey, AnsiString startline, AnsiString endline, rsa_key * key) { const char *pkey = inkey.c_str(); const char *start = strstr(pkey, startline.c_str()); if(!start) throw Exception("Cannot find \"" + startline + "\" in the key string"); const char *end = strstr(pkey, endline.c_str()); if(!end) throw Exception("Cannot find \"" + endline + "\" in the key string"); start += startline.Length(); char buf[10240]; unsigned long buf_len; int errnum; buf_len = sizeof(buf) - 1; errnum = base64_decode((const unsigned char*)(start), end - start, buf, &buf_len); if(errnum != CRYPT_OK) throw Exception(error_to_string(errnum)); errnum = rsa_import(buf, buf_len, key); if(errnum != CRYPT_OK) throw Exception(error_to_string(errnum)); } //--------------------------------------------------------------------------- bool SignFile(AnsiString privkey, AnsiString signfn, int ignorestart, int ignoreend, int ofs) { // ofs is -1 : for separeted sinature file (.sig) . // otherwise the sign is embedded to the target file. // sign file if(privkey == "") throw Exception("Specify private key"); if(signfn == "") throw Exception("Specify target file"); // read privkey rsa_key key; int errnum; ImportKey(privkey, "-----BEGIN RSA PRIVATE KEY-----", "-----END RSA PRIVATE KEY-----", &key); try { char buf[10240]; unsigned long buf_len; // initialize random number generator prng_state prng; if(!RandomizePRNGSimple(&prng)) return false; // make target hash unsigned char hash[HASH_SIZE]; MakeFileHash(signfn, hash, ignorestart, ignoreend); // sign buf_len = sizeof(buf) - 1; errnum = rsa_sign_hash(hash, HASH_SIZE, buf, &buf_len, &prng, find_prng("fortuna"), find_hash(HASH_METHOD_INTERNAL_STRING), HASH_SIZE, &key); if(errnum != CRYPT_OK) throw Exception(error_to_string(errnum)); // convert to readable text char buf_asc[10240*3/2+2]; unsigned long buf_asc_len; buf_asc_len = sizeof(buf_asc) - 1; errnum = base64_encode(buf, buf_len, buf_asc, &buf_asc_len); if(errnum != CRYPT_OK) throw Exception(error_to_string(errnum)); buf_asc[buf_asc_len] = 0; AnsiString sign = AnsiString("-- SIGNATURE - " HASH_METHOD_STRING "/PSS/RSA --\r\n") + Split64(buf_asc); // write it to the file TFileStream * st; if(ofs == -1) { // separated st = new TFileStream(signfn + ".sig", fmCreate|fmShareDenyWrite); } else { // embedded st = new TFileStream(signfn, fmOpenReadWrite|fmShareDenyWrite); st->Position = ofs; } try { st->Write(sign.c_str(), sign.Length()); if(ofs != -1) { // write a null terminater st->Write("\0", 1); } } catch(...) { delete st; throw; } delete st; } catch(...) { rsa_free(&key); throw; } rsa_free(&key); return true; } //--------------------------------------------------------------------------- bool CheckSignatureOfFile(AnsiString pubkey, AnsiString signfn, int ignorestart, int ignoreend, int ofs) { // check signature of the file if(pubkey == "") throw Exception("Specify public key"); if(signfn == "") throw Exception("Specify target file"); // read pubkey char buf[10240]; unsigned long buf_len; char buf_asc[sizeof(buf)*3/2+2]; unsigned long buf_asc_len; rsa_key key; ImportKey(pubkey, "-----BEGIN PUBLIC KEY-----", "-----END PUBLIC KEY-----", &key); // read signature file TFileStream *st; if(ofs == -1) { // separated st = new TFileStream(signfn + ".sig", fmOpenRead|fmShareDenyWrite); } else { // embedded st = new TFileStream(signfn, fmOpenReadWrite|fmShareDenyWrite); st->Position = ofs; } try { buf_asc_len = st->Read(buf_asc, sizeof(buf_asc) - 1); } catch(...) { delete st; throw; } delete st; buf_asc[buf_asc_len] = 0; buf_asc_len = strlen(buf_asc); AnsiString signmark("-- SIGNATURE - " HASH_METHOD_STRING "/PSS/RSA --"); if(strncmp(buf_asc, signmark.c_str(), signmark.Length())) throw Exception("Invalid signature file format"); buf_len = sizeof(buf) - 1; int errnum = base64_decode((const unsigned char*)(buf_asc + signmark.Length()), buf_asc_len - signmark.Length(), buf, &buf_len); if(errnum != CRYPT_OK) throw Exception(error_to_string(errnum)); int stat = 0; try { // make target hash unsigned char hash[HASH_SIZE]; MakeFileHash(signfn, hash, ignorestart, ignoreend); // check signature errnum = rsa_verify_hash(buf, buf_len, hash, HASH_SIZE, find_hash(HASH_METHOD_INTERNAL_STRING), HASH_SIZE, &stat, &key); if(errnum != CRYPT_OK) throw Exception(error_to_string(errnum)); } catch(...) { rsa_free(&key); throw; } rsa_free(&key); return stat; } //--------------------------------------------------------------------------- #pragma package(smart_init)
23.655172
93
0.612391
CATION-M
d25ddeb78e454ca73e78262ab53bf8a639e8a617
319
cpp
C++
lista_ex1.cpp/exercicio10.cpp
robinson-1985/exercicios_fatec
d234389bed31652849130b614448074ade444bce
[ "MIT" ]
null
null
null
lista_ex1.cpp/exercicio10.cpp
robinson-1985/exercicios_fatec
d234389bed31652849130b614448074ade444bce
[ "MIT" ]
null
null
null
lista_ex1.cpp/exercicio10.cpp
robinson-1985/exercicios_fatec
d234389bed31652849130b614448074ade444bce
[ "MIT" ]
null
null
null
/* 10. Faça um programa que calcule e mostre a área de um círculo. Sabe-se que: Área = π * R^2 */ #include <stdio.h> int main(){ float area, raio; printf("\nDigite o raio: "); scanf("%f", &raio); area = 3.1415 * raio * raio; printf("\nA área é: %4.3f \n",area); getchar(); return 0; }
18.764706
79
0.557994
robinson-1985
d2603441ad6264eca71e2a001fd2adbb7d2acd0e
2,077
hpp
C++
include/orwell/game/Robot.hpp
orwell-int/server-game
d3c410ff734a6f32de0303b25d816ae392df8a18
[ "BSD-3-Clause" ]
null
null
null
include/orwell/game/Robot.hpp
orwell-int/server-game
d3c410ff734a6f32de0303b25d816ae392df8a18
[ "BSD-3-Clause" ]
39
2015-02-01T15:24:59.000Z
2020-11-16T13:58:11.000Z
include/orwell/game/Robot.hpp
orwell-int/server-game
d3c410ff734a6f32de0303b25d816ae392df8a18
[ "BSD-3-Clause" ]
2
2015-03-14T13:05:25.000Z
2015-07-05T07:11:23.000Z
/// This class stores the information about a robot that is connected to the server #pragma once #include <string> #include <memory> #include <zmq.hpp> #include "orwell/com/Socket.hpp" namespace orwell { namespace support { class ISystemProxy; } // namespace support namespace game { class Player; class Item; class Team; class Robot { public: static std::shared_ptr< Robot> MakeRobot( support::ISystemProxy const & iSystemProxy, std::string const & iName, std::string const & iRobotId, Team & ioTeam, uint16_t const & iVideoRetransmissionPort, uint16_t const & iServerCommandPort); Robot( support::ISystemProxy const & iSystemProxy, std::string const & iName, std::string const & iRobotId, Team & ioTeam, uint16_t const & iVideoRetransmissionPort, uint16_t const & iServerCommandPort); ~Robot(); Team & getTeam(); Team const & getTeam() const; void setHasRealRobot(bool const iHasRealRobot); bool getHasRealRobot() const; void setPlayer(std::shared_ptr< Player > const iPlayer); std::shared_ptr< Player > getPlayer() const; bool getHasPlayer() const; void setVideoUrl(std::string const & iVideoUrl); std::string const & getVideoUrl() const; uint16_t getVideoRetransmissionPort() const; uint16_t getServerCommandPort() const; std::string const & getName() const; std::string const & getRobotId() const; bool getIsAvailable() const; void fire(); void stop(); void readImage(); void startVideo(); // void fillRobotStateMessage( messages::RobotState & oMessage ); std::string getAsString() const; private: support::ISystemProxy const & m_systemProxy; std::string m_name; std::string m_robotId; Team & m_team; std::string m_videoUrl; //the origin URL of the videofeed uint16_t m_videoRetransmissionPort; // the port on which the python server retransmits the video feed uint16_t m_serverCommandPort; // the port used to give instructions to the retransmitter. bool m_hasRealRobot; std::weak_ptr< Player > m_player; zmq::context_t m_zmqContext; }; } // namespace game } // namespace orwell
22.095745
102
0.738084
orwell-int
d2624a5b4bf7c04fe2e2e07abffde2795eaea4de
12,518
cpp
C++
src/graph_page_file_io.cpp
mattvchandler/graph3
f045b24a2657f4ad5628c8376cb7a54f1f1daf8e
[ "MIT" ]
null
null
null
src/graph_page_file_io.cpp
mattvchandler/graph3
f045b24a2657f4ad5628c8376cb7a54f1f1daf8e
[ "MIT" ]
1
2015-07-07T22:30:20.000Z
2015-07-09T17:27:14.000Z
src/graph_page_file_io.cpp
mattvchandler/graph3
f045b24a2657f4ad5628c8376cb7a54f1f1daf8e
[ "MIT" ]
null
null
null
// graph_page_file_io.cpp // read and write graphs to disk // Copyright 2018 Matthew Chandler // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #include <sstream> #include <gtkmm/messagedialog.h> #include <libconfig.h++> #include "graph.hpp" #include "graph_page.hpp" // save graph to file void Graph_page::save_graph(const std::string & filename) { // build the config file from widget properties libconfig::Config cfg; libconfig::Setting & cfg_root = cfg.getRoot().add("graph", libconfig::Setting::TypeGroup); cfg_root.add("r_car", libconfig::Setting::TypeBoolean) = _r_car.get_active(); cfg_root.add("r_cyl", libconfig::Setting::TypeBoolean) = _r_cyl.get_active(); cfg_root.add("r_sph", libconfig::Setting::TypeBoolean) = _r_sph.get_active(); cfg_root.add("r_par", libconfig::Setting::TypeBoolean) = _r_par.get_active(); cfg_root.add("eqn", libconfig::Setting::TypeString) = _eqn.get_text(); cfg_root.add("eqn_par_y", libconfig::Setting::TypeString) = _eqn_par_y.get_text(); cfg_root.add("eqn_par_z", libconfig::Setting::TypeString) = _eqn_par_z.get_text(); cfg_root.add("row_min", libconfig::Setting::TypeString) = _row_min.get_text(); cfg_root.add("row_max", libconfig::Setting::TypeString) = _row_max.get_text(); cfg_root.add("col_min", libconfig::Setting::TypeString) = _col_min.get_text(); cfg_root.add("col_max", libconfig::Setting::TypeString) = _col_max.get_text(); cfg_root.add("row_res", libconfig::Setting::TypeInt) = _row_res.get_value_as_int(); cfg_root.add("col_res", libconfig::Setting::TypeInt) = _col_res.get_value_as_int(); cfg_root.add("draw", libconfig::Setting::TypeBoolean) = _draw.get_active(); cfg_root.add("transparent", libconfig::Setting::TypeBoolean) = _transparent.get_active(); cfg_root.add("draw_normals", libconfig::Setting::TypeBoolean) = _draw_normals.get_active(); cfg_root.add("draw_grid", libconfig::Setting::TypeBoolean) = _draw_grid.get_active(); cfg_root.add("use_color", libconfig::Setting::TypeBoolean) = _use_color.get_active(); cfg_root.add("use_tex", libconfig::Setting::TypeBoolean) = _use_tex.get_active(); libconfig::Setting & color = cfg_root.add("color", libconfig::Setting::TypeList); color.add(libconfig::Setting::TypeFloat) = _color.r; color.add(libconfig::Setting::TypeFloat) = _color.g; color.add(libconfig::Setting::TypeFloat) = _color.b; cfg_root.add("transparency", libconfig::Setting::TypeFloat) = _transparency.get_value(); cfg_root.add("tex_filename", libconfig::Setting::TypeString) = _tex_filename; try { // write file cfg.writeFile(filename.c_str()); } catch(const libconfig::FileIOException & e) { // create an error message box Gtk::MessageDialog error_dialog("Error writing to " + filename, false, Gtk::MESSAGE_ERROR, Gtk::BUTTONS_OK, true); error_dialog.set_transient_for(*dynamic_cast<Gtk::Window *>(get_toplevel())); error_dialog.set_secondary_text(e.what()); error_dialog.set_title("Error"); error_dialog.run(); } } // read from a file bool Graph_page::load_graph(const std::string & filename) { bool complete = true; libconfig::Config cfg; try { // open and parse file cfg.readFile(filename.c_str()); libconfig::Setting & cfg_root = cfg.getRoot()["graph"]; // set properties - reqired settings bool r_car = cfg_root["r_car"]; bool r_cyl = cfg_root["r_cyl"]; bool r_sph = cfg_root["r_sph"]; bool r_par = cfg_root["r_par"]; // one and only one should be set if((int)r_car + (int)r_cyl + (int)r_sph + (int)r_par != 1) { // show error message box Gtk::MessageDialog error_dialog("Error parsing " + filename, false, Gtk::MESSAGE_ERROR, Gtk::BUTTONS_OK, true); error_dialog.set_transient_for(*dynamic_cast<Gtk::Window *>(get_toplevel())); error_dialog.set_secondary_text("Invalid combination of r_car, r_cyl, r_sph, r_par"); error_dialog.set_title("Error"); error_dialog.run(); return false; } _r_car.set_active(r_car); _r_cyl.set_active(r_cyl); _r_sph.set_active(r_sph); _r_par.set_active(r_par); bool use_color = cfg_root["use_color"]; bool use_tex = cfg_root["use_tex"]; // check for mutual exclusion if((int)use_color + (int)use_tex != 1) { // show error message box Gtk::MessageDialog error_dialog("Error parsing " + filename, false, Gtk::MESSAGE_ERROR, Gtk::BUTTONS_OK, true); error_dialog.set_transient_for(*dynamic_cast<Gtk::Window *>(get_toplevel())); error_dialog.set_secondary_text("Invalid combination of use_color, use_tex"); error_dialog.set_title("Error"); error_dialog.run(); return false; } _use_color.set_active(use_color); _use_tex.set_active(use_tex); // non-required settings, but needed to draw graph try { _eqn.set_text(static_cast<const char *>(cfg_root["eqn"])); } catch(const libconfig::SettingNotFoundException) { complete = false; } try { _eqn_par_y.set_text(static_cast<const char *>(cfg_root["eqn_par_y"])); } catch(const libconfig::SettingNotFoundException) { if(r_par) complete = false; } try { _eqn_par_z.set_text(static_cast<const char *>(cfg_root["eqn_par_z"])); } catch(const libconfig::SettingNotFoundException) { if(r_par) complete = false; } try { _row_min.set_text(static_cast<const char *>(cfg_root["row_min"])); } catch(const libconfig::SettingNotFoundException) { complete = false; } try { _row_max.set_text(static_cast<const char *>(cfg_root["row_max"])); } catch(const libconfig::SettingNotFoundException) { complete = false; } try { _col_min.set_text(static_cast<const char *>(cfg_root["col_min"])); } catch(const libconfig::SettingNotFoundException) { complete = false; } try { _col_max.set_text(static_cast<const char *>(cfg_root["col_max"])); } catch(const libconfig::SettingNotFoundException) { complete = false; } // non-required settings try { _row_res.get_adjustment()->set_value(static_cast<int>(cfg_root["row_res"])); } catch(const libconfig::SettingNotFoundException) {} try { _col_res.get_adjustment()->set_value(static_cast<int>(cfg_root["col_res"])); } catch(const libconfig::SettingNotFoundException) {} try { _draw.set_active(static_cast<bool>(cfg_root["draw"])); } catch(const libconfig::SettingNotFoundException) {} try { _transparent.set_active(static_cast<bool>(cfg_root["transparent"])); } catch(const libconfig::SettingNotFoundException) {} try { _draw_normals.set_active(static_cast<bool>(cfg_root["draw_normals"])); } catch(const libconfig::SettingNotFoundException) {} try { _draw_grid.set_active(static_cast<bool>(cfg_root["draw_grid"])); } catch(const libconfig::SettingNotFoundException) {} try { _tex_filename = static_cast<const char *>(cfg_root["tex_filename"]); } catch(const libconfig::SettingNotFoundException) {} try { libconfig::Setting & color_l = cfg_root["color"]; // check for valid color (list of 3) if(!color_l.isList() || color_l.getLength() != 3) { // show error message box Gtk::MessageDialog error_dialog("Error parsing " + filename, false, Gtk::MESSAGE_ERROR, Gtk::BUTTONS_OK, true); error_dialog.set_transient_for(*dynamic_cast<Gtk::Window *>(get_toplevel())); std::ostringstream msg; msg<<"Invalid number of color elements (expected 3, got "<<color_l.getLength()<<")"; error_dialog.set_secondary_text(msg.str()); error_dialog.set_title("Error"); error_dialog.run(); return false; } _color.r = color_l[0]; _color.g = color_l[1]; _color.b = color_l[2]; } catch(const libconfig::SettingNotFoundException) {} try { _transparency.set_value(static_cast<float>(cfg_root["transparency"])); } catch(const libconfig::SettingNotFoundException) {} } catch(const libconfig::FileIOException & e) { // show error message box Gtk::MessageDialog error_dialog("Error reading from " + filename, false, Gtk::MESSAGE_ERROR, Gtk::BUTTONS_OK, true); error_dialog.set_transient_for(*dynamic_cast<Gtk::Window *>(get_toplevel())); error_dialog.set_secondary_text(e.what()); error_dialog.set_title("Error"); error_dialog.run(); return false; } catch(const libconfig::ParseException & e) { // show error message box Gtk::MessageDialog error_dialog("Error parsing " + filename, false, Gtk::MESSAGE_ERROR, Gtk::BUTTONS_OK, true); error_dialog.set_transient_for(*dynamic_cast<Gtk::Window *>(get_toplevel())); std::ostringstream msg; msg<<e.getError()<<" on line: "<<e.getLine(); error_dialog.set_secondary_text(msg.str()); error_dialog.set_title("Error"); error_dialog.run(); return false; } catch(const libconfig::SettingTypeException & e) { // show error message box Gtk::MessageDialog error_dialog("Invalid setting type in" + filename, false, Gtk::MESSAGE_ERROR, Gtk::BUTTONS_OK, true); error_dialog.set_transient_for(*dynamic_cast<Gtk::Window *>(get_toplevel())); error_dialog.set_secondary_text(e.getPath()); error_dialog.set_title("Error"); error_dialog.run(); return false; } catch(const libconfig::SettingNotFoundException & e) { // show error message box Gtk::MessageDialog error_dialog("Could not find setting in" + filename, false, Gtk::MESSAGE_ERROR, Gtk::BUTTONS_OK, true); error_dialog.set_transient_for(*dynamic_cast<Gtk::Window *>(get_toplevel())); error_dialog.set_secondary_text(e.getPath()); error_dialog.set_title("Error"); error_dialog.run(); return false; } // try to open the texture file if(!_tex_filename.empty()) { try { _tex_ico = Gdk::Pixbuf::create_from_file(_tex_filename)->scale_simple(32, 32, Gdk::InterpType::INTERP_BILINEAR); } catch(Glib::Exception &e) { _tex_ico.reset(); // show error message box Gtk::MessageDialog error_dialog(e.what(), false, Gtk::MESSAGE_ERROR, Gtk::BUTTONS_OK, true); error_dialog.set_transient_for(*dynamic_cast<Gtk::Window *>(get_toplevel())); error_dialog.set_title("Error"); error_dialog.set_secondary_text(""); error_dialog.run(); } } // set color thumbnail guint8 r = (guint8)(_color.r * 256.0f); guint8 g = (guint8)(_color.g * 256.0f); guint8 b = (guint8)(_color.b * 256.0f); guint32 hex_color = r << 24 | g << 16 | b << 8; _color_ico->fill(hex_color); // set properties from widget values change_type(); change_coloring(); if(complete) apply(); return true; }
41.866221
130
0.653219
mattvchandler
d920fbc87885ef55ac10520762b3c6e8c90f6d5f
677
cpp
C++
tests/StdStats_test.cpp
syntaxonly/algs4-cpp
3ca6336b77e72e0186dfa6ce23585f3bb34fc213
[ "BSL-1.0" ]
null
null
null
tests/StdStats_test.cpp
syntaxonly/algs4-cpp
3ca6336b77e72e0186dfa6ce23585f3bb34fc213
[ "BSL-1.0" ]
null
null
null
tests/StdStats_test.cpp
syntaxonly/algs4-cpp
3ca6336b77e72e0186dfa6ce23585f3bb34fc213
[ "BSL-1.0" ]
null
null
null
#include "algs4/StdStats.h" #include "algs4/StdArrayIO.h" #include "algs4/StdOut.h" // run by: StdStats_test < algs4-data/tinyDouble1D.txt int main() { using namespace algs4; auto a = StdArrayIO::readDouble1D(); StdOut::printf(" min %10.3f\n", StdStats::min(a)); StdOut::printf(" mean %10.3f\n", StdStats::mean(a)); StdOut::printf(" max %10.3f\n", StdStats::max(a)); StdOut::printf(" stddev %10.3f\n", StdStats::stddev(a)); StdOut::printf(" var %10.3f\n", StdStats::var(a)); StdOut::printf(" stddevp %10.3f\n", StdStats::stddevp(a)); StdOut::printf(" varp %10.3f\n", StdStats::varp(a)); return 0; }
30.772727
64
0.601182
syntaxonly
d920fde93a62ef3c5d1860c6f0ffc4da19d16c32
3,780
cpp
C++
lock_hardware/qt_jiemian/lock.cpp
LinuxDigger/smart_lock
014b31dc54b86bc416b2f440ce2e4a2491089906
[ "MIT" ]
12
2021-01-11T11:17:07.000Z
2022-03-02T05:08:54.000Z
lock_hardware/qt_jiemian/lock.cpp
LinuxDigger/smart_lock
014b31dc54b86bc416b2f440ce2e4a2491089906
[ "MIT" ]
null
null
null
lock_hardware/qt_jiemian/lock.cpp
LinuxDigger/smart_lock
014b31dc54b86bc416b2f440ce2e4a2491089906
[ "MIT" ]
4
2021-02-03T08:23:36.000Z
2022-03-01T15:44:05.000Z
#include <stdint.h> #include <stdio.h> #include <iostream> #include <unistd.h> #include <curl/curl.h> #include <thread> #include "lock.h" #include "database.h" #include "model/user.h" #include "model/log.h" #include "model/password.h" #include "model/permission.h" #include "communication.h" #include "network.h" #include "lock.h" #include "logger.h" extern "C" { #include "rsa_aes.h" } int lock_main(void) { sqlite3 *db; if (SQLITE_OK != sqlite3_open("lock.db", &db)) { std::cerr << "Can't open database: " << sqlite3_errmsg(db) << std::endl; return 1; } network::inti(); database_init(db); std::thread *polling = communication::start_long_polling(); // std::string response; // std::string str; // int64_t status = communication::send_msg(LOCK_ID, CLIENT_ID, // communication::new_msg(str, "这个是类型", "nihao", "googogo", "24343", // 123, true).c_str(), response); // std::cout << response; // EVP_PKEY *pubkey = EVP_PKEY_new(); // EVP_PKEY *prikey = EVP_PKEY_new(); // // if (!get_rsa_pub_key("publicKey.pem", pubkey)) return -1; // if (!get_rsa_pri_key("privateKey.pem", prikey)) return -1; // // FILE *fp = fopen("lock.cpp", "rb"); // fseek(fp, 0L, SEEK_END); // unsigned sz = ftell(fp); // fseek(fp, 0L, SEEK_SET); // unsigned char *data = (unsigned char*) malloc(sz); // fread(data, 1, sz, fp); // // int seal_out_size = get_evp_seal_out_size(sz); // unsigned int unseal_out_size = get_evp_unseal_safe_out_size(seal_out_size); // unsigned char *seal_out = (unsigned char*) malloc(seal_out_size); // unsigned char *unseal_out = (unsigned char*) malloc(unseal_out_size); // // //进行加密 // //输入原始数据data,和公匙pubkey,得到加密结果seal_out // do_evp_seal(pubkey, data, sz, seal_out); // //进行解密 // //输入加密数据seal_out,和私匙prikey,得到解密结果unseal_out和解密结果长度unseal_out_size // do_evp_unseal(prikey, seal_out, seal_out_size, unseal_out, &unseal_out_size); // // //将解密结果输出到命令行 // fwrite(unseal_out, 1, unseal_out_size, stdout); // // //将解密结果输出到文件 // // FILE *fp0 = fopen("encrypted_output", "wb"); // // fwrite(seal_out, 1, seal_out_size, fp0); // // fclose(fp0); // // EVP_PKEY_free(pubkey); // EVP_PKEY_free(prikey); // std::cout << "------ start test ------" << std::endl; // // if (SQLITE_OK != sqlite3_open("/t/lock.db", &db)) { // std::cerr << "Can't open database: " << sqlite3_errmsg(db) << std::endl; // return 1; // } // std::cout << "Open database successfully!" << std::endl << std::endl; // // if (0 // >= add_user("username", "credential", "imei12453246432", 12454, // 45476, 324567732, 2435676542343, 0, 0)) { // std::cerr << "Query " << "th sql error!" << std::endl; // return -1; // } // // User user; // // if (0 >= get_user(4, user)) { // std::cerr << "Query " << "th sql error!" << std::endl; // return -1; // } // user.setUsername("hello world!!!!!!"); // if (0 >= update_user(user)) { // std::cerr << "Query " << "th sql error!" << std::endl; // return -1; // } // std::vector<User> users; // if (0 >= list_user(users)) { // std::cerr << "Query " << "th sql error!" << std::endl; // return -1; // } // // if (0 // >= add_log(2, 12454232443, 2, "这个是日志内容啊啊啊啊啊啊啊啊", 0, // "这个是备注!3443134546")) { // std::cerr << "Query " << "th sql error!" << std::endl; // return -1; // } // // std::vector<Log> logs; // if (0 >= list_log(logs)) { // std::cerr << "Query " << "th sql error!" << std::endl; // return -1; // } // // if (0 >= add_permission(2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)) { // std::cerr << "Query " << "th sql error!" << std::endl; // return -1; // } // // std::cout << "All sql query successfully!" << std::endl; polling->join(); log_info("long_polling thread ended!"); delete polling; sqlite3_close(db); network::uninit(); return 0; }
26.808511
83
0.602116
LinuxDigger
d9271ff3a55c2cc8314a2a759a71a8b8d67791f1
2,835
cpp
C++
functions.cpp
DivyanshuSaxena/Buffered-File-Manager
93c9741f532e1e7b55a9f4dbc68762bd53be21a8
[ "MIT" ]
null
null
null
functions.cpp
DivyanshuSaxena/Buffered-File-Manager
93c9741f532e1e7b55a9f4dbc68762bd53be21a8
[ "MIT" ]
null
null
null
functions.cpp
DivyanshuSaxena/Buffered-File-Manager
93c9741f532e1e7b55a9f4dbc68762bd53be21a8
[ "MIT" ]
null
null
null
#include <climits> #include <vector> #include <cstring> #include "functions.h" bool debugprint=false; bool binarySearchPage(int searchInt, int startPageNum, int lastPageNum, int firstPageNum, int endPageNum, FileHandler fh, int * finPage, int * pageOffset){ bool found=false; char *data; int foundPage = -1; while(true) { if(startPageNum > lastPageNum) { found=false; break; } int midPageNum = (startPageNum + lastPageNum)/2; PageHandler ph = fh.PageAt(midPageNum); data = ph.GetData(); vector<int> vec; for(int i = 0; i < PAGE_CONTENT_SIZE/4; i++) { int num; memcpy(&num, &data[i*4], sizeof(int)); if(num == INT_MIN){ break; } vec.push_back(num); } if(debugprint) cout << "Read page " << midPageNum << " into vector" << endl; // Debug fh.FlushPage(midPageNum); // Check if number is in the range of mid page if (midPageNum == firstPageNum) { if (searchInt <= vec[vec.size()-1]) { foundPage = midPageNum; } else { if (firstPageNum != lastPageNum) { startPageNum = midPageNum+1; } else { foundPage = midPageNum; *pageOffset = vec.size(); } } } else if (midPageNum == lastPageNum) { if (searchInt >= vec[0]) { foundPage = midPageNum; } else { lastPageNum = midPageNum-1; } } else { PageHandler prevPage = fh.PrevPage(midPageNum); char* prevData = prevPage.GetData(); PageHandler nextPage = fh.NextPage(midPageNum); char* nextData = nextPage.GetData(); vector<int> prevVec; for(int i = 0; i < PAGE_CONTENT_SIZE/4; i++) { int num; memcpy(&num, &prevData[i*4], sizeof(int)); if(num == INT_MIN){ break; } prevVec.push_back(num); } int lowerBound = prevVec[prevVec.size()-1]; int upperBound; memcpy(&upperBound, &nextData[0], sizeof(int)); fh.FlushPage(prevPage.GetPageNum()); fh.FlushPage(nextPage.GetPageNum()); if (searchInt > lowerBound && searchInt < upperBound) { foundPage = midPageNum; } else if (searchInt >= upperBound) { startPageNum = midPageNum+1; } else { lastPageNum = midPageNum-1; } } // Check if a matching page has been found if (foundPage != -1) { // We should have the number in this page if(debugprint) cout << "Set finpage to " << foundPage << endl; *finPage = foundPage; int i = 0; for (i = 0; i < vec.size(); i++) { // if(debugprint) cout << i << " "; if (vec[i] == searchInt) { *pageOffset = i; if(debugprint) cout << "Number is expected to be at position " << i << endl; // Debug found = true; break; } else if (vec[i] > searchInt) { *pageOffset = i; if(debugprint) cout << "Number is expected to be at position " << i << endl; // Debug break; } } if (i == vec.size()) { *pageOffset = i; } break; } } return found; }
26.745283
155
0.611287
DivyanshuSaxena
d92bd52ce341dd8409f3f8c42aeaaf82560c412c
640
cpp
C++
code/exploration_42-FUNCTION_OBJECTS/03-using_functors/main.cpp
ordinary-developer/exploring_cpp_11_2_ed_r_lischner
468de9c64ae54db45c4de748436947d5849c4582
[ "MIT" ]
1
2017-05-04T08:23:46.000Z
2017-05-04T08:23:46.000Z
code/exploration_42-FUNCTION_OBJECTS/03-using_functors/main.cpp
ordinary-developer/exploring_cpp_11_2_ed_r_lischner
468de9c64ae54db45c4de748436947d5849c4582
[ "MIT" ]
null
null
null
code/exploration_42-FUNCTION_OBJECTS/03-using_functors/main.cpp
ordinary-developer/exploring_cpp_11_2_ed_r_lischner
468de9c64ae54db45c4de748436947d5849c4582
[ "MIT" ]
null
null
null
#include "sequence.hpp" #include <algorithm> #include <iostream> #include <iterator> #include <vector> int main() { int size{}; std::cout << "How many integers to you want? "; std::cin >> size; int first{}; std::cout << "What it the first integer? "; std::cin >> first; int step{}; std::cout << "What is the interval between successive integers? "; std::cin >> step; std::vector<int> data(size); std::generate(data.begin(), data.end(), sequence(first, step)); std::copy(data.begin(), data.end(), std::ostream_iterator<int>(std::cout, "\n")); return 0; }
22.068966
70
0.576563
ordinary-developer
d930af876868d492f56a1963ef217fc172aec195
5,970
cc
C++
examples/mnist/train_mnist.cc
ruyimarone/dynet
67bace3fb1d79327ada53b248e497c894819760d
[ "Apache-2.0" ]
3,307
2016-10-08T15:51:28.000Z
2022-03-30T04:40:44.000Z
examples/mnist/train_mnist.cc
ruyimarone/dynet
67bace3fb1d79327ada53b248e497c894819760d
[ "Apache-2.0" ]
1,348
2016-10-08T14:36:55.000Z
2022-03-26T15:19:27.000Z
examples/mnist/train_mnist.cc
ruyimarone/dynet
67bace3fb1d79327ada53b248e497c894819760d
[ "Apache-2.0" ]
741
2016-10-09T04:44:30.000Z
2022-03-29T22:29:02.000Z
/** * Train a multilayer perceptron to classify mnist digits * * This provide an example of usage of the mlp.h model */ #include "mlp.h" #include "dynet/io.h" #include "getpid.h" #include "cl-args.h" #include "data-io.h" using namespace std; using namespace dynet; int main(int argc, char** argv) { // Fetch dynet params ---------------------------------------------------------------------------- auto dyparams = dynet::extract_dynet_params(argc, argv); dynet::initialize(dyparams); // Fetch program specific parameters (see ../utils/cl-args.h) ------------------------------------ Params params; get_args(argc, argv, params, TRAIN_SUP); // Load Dataset ---------------------------------------------------------------------------------- // Load data vector<vector<float>> mnist_train, mnist_dev; read_mnist(params.train_file, mnist_train); read_mnist(params.dev_file, mnist_dev); // Load labels vector<unsigned> mnist_train_labels, mnist_dev_labels; read_mnist_labels(params.train_labels_file, mnist_train_labels); read_mnist_labels(params.dev_labels_file, mnist_dev_labels); // ParameterCollection name (for saving) ----------------------------------------------------------------------- ostringstream os; // Store a bunch of information in the model name os << params.exp_name << "_" << "mlp" << "_" << 784 << "-" << 512 << "-relu-" << 0.2 << "_" << 512 << "-" << 512 << "-relu-" << 0.2 << "_" << 512 << "-" << 10 << "-softmax" << "_" << getpid() << ".params"; const string fname = os.str(); cerr << "Parameters will be written to: " << fname << endl; // Build model ----------------------------------------------------------------------------------- ParameterCollection model; // Use Adam optimizer AdamTrainer trainer(model); trainer.clip_threshold *= params.BATCH_SIZE; // Create model MLP nn(model, vector<Layer>({ Layer(/* input_dim */ 784, /* output_dim */ 512, /* activation */ RELU, /* dropout_rate */ 0.2), Layer(/* input_dim */ 512, /* output_dim */ 512, /* activation */ RELU, /* dropout_rate */ 0.2), Layer(/* input_dim */ 512, /* output_dim */ 10, /* activation */ LINEAR, /* dropout_rate */ 0.0) })); // Load preexisting weights (if provided) if (params.model_file != "") { TextFileLoader loader(params.model_file); loader.populate(model); } // Initialize variables for training ------------------------------------------------------------- // Worst accuracy double worst = 0; // Number of batches in training set unsigned num_batches = mnist_train.size() / params.BATCH_SIZE - 1; // Random indexing unsigned si; vector<unsigned> order(num_batches); for (unsigned i = 0; i < num_batches; ++i) order[i] = i; unsigned epoch = 0; vector<Expression> cur_batch; vector<unsigned> cur_labels; // Run for the given number of epochs (or indefinitely if params.NUM_EPOCHS is negative) while (static_cast<int>(epoch) < params.NUM_EPOCHS || params.NUM_EPOCHS < 0) { // Reshuffle the dataset cerr << "**SHUFFLE\n"; random_shuffle(order.begin(), order.end()); // Initialize loss and number of samples processed (to average loss) double loss = 0; double num_samples = 0; // Start timer std::unique_ptr<Timer> iteration(new Timer("completed in")); // Activate dropout nn.enable_dropout(); for (si = 0; si < num_batches; ++si) { // build graph for this instance ComputationGraph cg; // Compute batch start id and size int id = order[si] * params.BATCH_SIZE; unsigned bsize = std::min((unsigned) mnist_train.size() - id, params.BATCH_SIZE); // Get input batch cur_batch = vector<Expression>(bsize); cur_labels = vector<unsigned>(bsize); for (unsigned idx = 0; idx < bsize; ++idx) { cur_batch[idx] = input(cg, {784}, mnist_train[id + idx]); cur_labels[idx] = mnist_train_labels[id + idx]; } // Reshape as batch (not very intuitive yet) Expression x_batch = reshape(concatenate_cols(cur_batch), Dim({784}, bsize)); // Get negative log likelihood on batch Expression loss_expr = nn.get_nll(x_batch, cur_labels, cg); // Get scalar error for monitoring loss += as_scalar(cg.forward(loss_expr)); // Increment number of samples processed num_samples += bsize; // Compute gradient with backward pass cg.backward(loss_expr); // Update parameters trainer.update(); // Print progress every tenth of the dataset if ((si + 1) % (num_batches / 10) == 0 || si == num_batches - 1) { // Print informations trainer.status(); cerr << " E = " << (loss / num_samples) << ' '; // Reinitialize timer iteration.reset(new Timer("completed in")); // Reinitialize loss loss = 0; num_samples = 0; } } // Disable dropout for dev testing nn.disable_dropout(); // Show score on dev data if (si == num_batches) { double dpos = 0; for (unsigned i = 0; i < mnist_dev.size(); ++i) { // build graph for this instance ComputationGraph cg; // Get input expression Expression x = input(cg, {784}, mnist_dev[i]); // Get negative log likelihood on batch unsigned predicted_idx = nn.predict(x, cg); // Increment count of positive classification if (predicted_idx == mnist_dev_labels[i]) dpos++; } // If the dev loss is lower than the previous ones, save the model if (dpos > worst) { worst = dpos; TextFileSaver saver(fname); saver.save(model); } // Print informations cerr << "\n***DEV [epoch=" << (epoch) << "] E = " << (dpos / (double) mnist_dev.size()) << ' '; // Reinitialize timer iteration.reset(new Timer("completed in")); } // Increment epoch ++epoch; } }
34.310345
114
0.578392
ruyimarone
d933db0d014d82faf2211754bc4538aa50e6b432
7,231
cpp
C++
BreaksPPU/PPUSim/regs.cpp
ogamespec/breaknes
b053afb6924ca661f71a129766e8945f64f6ec7b
[ "CC0-1.0" ]
null
null
null
BreaksPPU/PPUSim/regs.cpp
ogamespec/breaknes
b053afb6924ca661f71a129766e8945f64f6ec7b
[ "CC0-1.0" ]
null
null
null
BreaksPPU/PPUSim/regs.cpp
ogamespec/breaknes
b053afb6924ca661f71a129766e8945f64f6ec7b
[ "CC0-1.0" ]
null
null
null
// Control Registers #include "pch.h" using namespace BaseLogic; namespace PPUSim { ControlRegs::ControlRegs(PPU* parent) { ppu = parent; } ControlRegs::~ControlRegs() { } void ControlRegs::sim() { sim_RegularRegOps(); sim_W56RegOps(); sim_FirstSecond_SCCX_Write(); sim_RegFFs(); if (ppu->rev == Revision::RP2C07_0) { sim_PalBLACK(); } } void ControlRegs::sim_RWDecoder() { TriState RnW = ppu->wire.RnW; TriState n_DBE = ppu->wire.n_DBE; ppu->wire.n_RD = NOT(NOR(NOT(RnW), n_DBE)); ppu->wire.n_WR = NOT(NOR(RnW, n_DBE)); } void ControlRegs::sim_RegularRegOps() { TriState RS0 = ppu->wire.RS[0]; TriState RS1 = ppu->wire.RS[1]; TriState RS2 = ppu->wire.RS[2]; TriState RnW = ppu->wire.RnW; TriState in2[4]{}; // Others in2[0] = NOT(RS0); in2[1] = NOT(RS1); in2[2] = NOT(RS2); in2[3] = NOT(RnW); ppu->wire.n_R7 = NOT(NOR4(in2)); in2[0] = NOT(RS0); in2[1] = NOT(RS1); in2[2] = NOT(RS2); in2[3] = RnW; ppu->wire.n_W7 = NOT(NOR4(in2)); in2[0] = RS0; in2[1] = RS1; in2[2] = NOT(RS2); in2[3] = RnW; ppu->wire.n_W4 = NOT(NOR4(in2)); in2[0] = NOT(RS0); in2[1] = NOT(RS1); in2[2] = RS2; in2[3] = RnW; ppu->wire.n_W3 = NOT(NOR4(in2)); in2[0] = RS0; in2[1] = NOT(RS1); in2[2] = RS2; in2[3] = NOT(RnW); ppu->wire.n_R2 = NOT(NOR4(in2)); in2[0] = NOT(RS0); in2[1] = RS1; in2[2] = RS2; in2[3] = RnW; ppu->wire.n_W1 = NOT(NOR4(in2)); in2[0] = RS0; in2[1] = RS1; in2[2] = RS2; in2[3] = RnW; ppu->wire.n_W0 = NOT(NOR4(in2)); in2[0] = RS0; in2[1] = RS1; in2[2] = NOT(RS2); in2[3] = NOT(RnW); ppu->wire.n_R4 = NOT(NOR4(in2)); } void ControlRegs::sim_W56RegOps() { TriState RS0 = ppu->wire.RS[0]; TriState RS1 = ppu->wire.RS[1]; TriState RS2 = ppu->wire.RS[2]; TriState RnW = ppu->wire.RnW; TriState in[5]{}; TriState in2[4]{}; // SCCX in[0] = RS0; in[1] = NOT(RS1); in[2] = NOT(RS2); in[3] = get_Scnd(); in[4] = RnW; ppu->wire.n_W6_1 = NOT(NOR5(in)); in[0] = RS0; in[1] = NOT(RS1); in[2] = NOT(RS2); in[3] = get_Frst(); in[4] = RnW; ppu->wire.n_W6_2 = NOT(NOR5(in)); in[0] = NOT(RS0); in[1] = RS1; in[2] = NOT(RS2); in[3] = get_Scnd(); in[4] = RnW; ppu->wire.n_W5_1 = NOT(NOR5(in)); in[0] = NOT(RS0); in[1] = RS1; in[2] = NOT(RS2); in[3] = get_Frst(); in[4] = RnW; ppu->wire.n_W5_2 = NOT(NOR5(in)); in2[0] = NOT(ppu->wire.n_W5_1); in2[1] = NOT(ppu->wire.n_W5_2); in2[2] = NOT(ppu->wire.n_W6_1); in2[3] = NOT(ppu->wire.n_W6_2); n_W56 = NOR4(in2); } void ControlRegs::sim_FirstSecond_SCCX_Write() { TriState RC = ppu->wire.RC; TriState n_DBE = ppu->wire.n_DBE; TriState n_R2 = ppu->wire.n_R2; TriState R2_Enable = NOR(n_R2, n_DBE); TriState W56_Enable = NOR(n_W56, n_DBE); SCCX_FF1.set(NOR3(RC, R2_Enable, MUX(W56_Enable, NOT(SCCX_FF2.get()), NOT(SCCX_FF1.get())))); SCCX_FF2.set(NOR3(RC, R2_Enable, MUX(W56_Enable, NOT(SCCX_FF2.get()), SCCX_FF1.get()))); } void ControlRegs::sim_RegFFs() { TriState RC = ppu->wire.RC; TriState n_W0 = ppu->wire.n_W0; TriState n_W1 = ppu->wire.n_W1; TriState n_DBE = ppu->wire.n_DBE; TriState W0_Enable = NOR(n_W0, n_DBE); TriState W1_Enable = NOR(n_W1, n_DBE); for (size_t n = 0; n < 8; n++) { if (n >= 2) { // Bits 0 and 1 in the PAR Gen. PPU_CTRL0[n].set(NOR(RC, NOT(MUX(W0_Enable, PPU_CTRL0[n].get(), ppu->GetDBBit(n))))); } PPU_CTRL1[n].set(NOR(RC, NOT(MUX(W1_Enable, PPU_CTRL1[n].get(), ppu->GetDBBit(n))))); } // CTRL0 i132_latch.set(PPU_CTRL0[2].get(), NOT(W0_Enable)); ppu->wire.I1_32 = NOT(i132_latch.nget()); obsel_latch.set(PPU_CTRL0[3].get(), NOT(W0_Enable)); ppu->wire.OBSEL = obsel_latch.nget(); bgsel_latch.set(PPU_CTRL0[4].get(), NOT(W0_Enable)); ppu->wire.BGSEL = bgsel_latch.nget(); o816_latch.set(PPU_CTRL0[5].get(), NOT(W0_Enable)); ppu->wire.O8_16 = NOT(o816_latch.nget()); ppu->wire.n_SLAVE = PPU_CTRL0[6].get(); ppu->wire.VBL = PPU_CTRL0[7].get(); // CTRL1 ppu->wire.BnW = PPU_CTRL1[0].get(); bgclip_latch.set(PPU_CTRL1[1].get(), NOT(W1_Enable)); ppu->wire.n_BGCLIP = ClippingAlwaysDisabled ? TriState::One : NOT(bgclip_latch.nget()); obclip_latch.set(PPU_CTRL1[2].get(), NOT(W1_Enable)); ppu->wire.n_OBCLIP = ClippingAlwaysDisabled ? TriState::One : NOT(obclip_latch.nget()); bge_latch.set(PPU_CTRL1[3].get(), NOT(W1_Enable)); obe_latch.set(PPU_CTRL1[4].get(), NOT(W1_Enable)); ppu->wire.BGE = RenderAlwaysEnabled ? TriState::One : bge_latch.get(); ppu->wire.OBE = RenderAlwaysEnabled ? TriState::One : obe_latch.get(); ppu->wire.BLACK = NOR(ppu->wire.BGE, ppu->wire.OBE); tr_latch.set(PPU_CTRL1[5].get(), NOT(W1_Enable)); ppu->wire.n_TR = tr_latch.nget(); tg_latch.set(PPU_CTRL1[6].get(), NOT(W1_Enable)); ppu->wire.n_TG = tg_latch.nget(); ppu->wire.n_TB = NOT(PPU_CTRL1[7].get()); } TriState ControlRegs::get_Frst() { return SCCX_FF1.nget(); } TriState ControlRegs::get_Scnd() { return SCCX_FF1.get(); } /// <summary> /// The CLPB/CLPO signal acquisition simulation should be done after the FSM. /// </summary> void ControlRegs::sim_CLP() { TriState n_PCLK = ppu->wire.n_PCLK; TriState n_VIS = ppu->fsm.nVIS; TriState CLIP_B = ppu->fsm.CLIP_B; TriState CLIP_O = ppu->fsm.CLIP_O; TriState BGE = ppu->wire.BGE; TriState OBE = ppu->wire.OBE; nvis_latch.set(n_VIS, n_PCLK); clipb_latch.set(CLIP_B, n_PCLK); clipo_latch.set(NOR3(nvis_latch.get(), CLIP_O, NOT(OBE)), n_PCLK); ppu->wire.n_CLPB = NOR3(nvis_latch.get(), clipb_latch.get(), NOT(BGE)); ppu->wire.CLPO = clipo_latch.nget(); } void ControlRegs::Debug_RenderAlwaysEnabled(bool enable) { RenderAlwaysEnabled = enable; } void ControlRegs::Debug_ClippingAlwaysDisabled(bool enable) { ClippingAlwaysDisabled = enable; } uint8_t ControlRegs::Debug_GetCTRL0() { uint8_t val = 0; for (size_t n = 0; n < 8; n++) { val |= (PPU_CTRL0[n].get() == TriState::One ? 1ULL : 0) << n; } return val; } uint8_t ControlRegs::Debug_GetCTRL1() { uint8_t val = 0; for (size_t n = 0; n < 8; n++) { val |= (PPU_CTRL1[n].get() == TriState::One ? 1ULL : 0) << n; } return val; } void ControlRegs::Debug_SetCTRL0(uint8_t val) { for (size_t n = 0; n < 8; n++) { TriState bit_val = FromByte((val >> n) & 1); PPU_CTRL0[n].set(bit_val); } } void ControlRegs::Debug_SetCTRL1(uint8_t val) { for (size_t n = 0; n < 8; n++) { TriState bit_val = FromByte((val >> n) & 1); PPU_CTRL1[n].set(bit_val); } } /// <summary> /// The `/SLAVE` signal is used for EXT input terminals. /// </summary> /// <returns></returns> TriState ControlRegs::get_nSLAVE() { return PPU_CTRL0[6].get(); } /// <summary> /// Special BLACK signal processing for PAL PPU. /// </summary> void ControlRegs::sim_PalBLACK() { TriState PCLK = ppu->wire.PCLK; TriState n_PCLK = ppu->wire.n_PCLK; BLACK_FF1.set(MUX(PCLK, NOT(NOT(BLACK_FF1.get())), ppu->wire.BLACK)); BLACK_FF2.set(MUX(n_PCLK, NOT(NOT(BLACK_FF2.get())), NOT(NOT(BLACK_FF1.get())))); black_latch1.set(NOT(NOT(BLACK_FF2.get())), PCLK); black_latch2.set(black_latch1.nget(), n_PCLK); ppu->wire.BLACK = black_latch2.nget(); } }
22.045732
95
0.620661
ogamespec
d9351319abdb18af2bc0c496f50fbcf9278e44bf
1,250
cpp
C++
7FA4/1.5/Q1.5.5.3.cpp
XenonWZH/involution
189f6ce2bbfe3a7c5d536bbd769f353e4c06e7c6
[ "MIT" ]
null
null
null
7FA4/1.5/Q1.5.5.3.cpp
XenonWZH/involution
189f6ce2bbfe3a7c5d536bbd769f353e4c06e7c6
[ "MIT" ]
null
null
null
7FA4/1.5/Q1.5.5.3.cpp
XenonWZH/involution
189f6ce2bbfe3a7c5d536bbd769f353e4c06e7c6
[ "MIT" ]
null
null
null
// Q1.5.5.3. 多项式加减乘 // WzhDnwzWzh #include <iostream> #include <cstring> using namespace std; int main() { int f1[1001], f2[1001], ans[1000001], n1, n2, n_ans; memset(f1, 0, sizeof(f1)); memset(f2, 0, sizeof(f2)); memset(ans, 0, sizeof(ans)); cin >> n1 >> n2; for (int i = 0; i <= n1; i++) cin >> f1[i]; for (int i = 0; i <= n2; i++) cin >> f2[i]; n_ans = n1 < n2 ? n2 : n1; for (int i = 0; i <= n_ans; i++) ans[i] = f1[i] + f2[i]; while (ans[n_ans] == 0 && n_ans >= 1) n_ans--; for (int i = 0; i <= n_ans; i++) cout << ans[i] << " "; cout << endl; memset(ans, 0, sizeof(ans)); n_ans = n1 < n2 ? n2 : n1; for (int i = 0; i <= n_ans; i++) ans[i] = f1[i] - f2[i]; while (ans[n_ans] == 0 && n_ans >= 1) n_ans--; for (int i = 0; i <= n_ans; i++) cout << ans[i] << " "; cout << endl; memset(ans, 0, sizeof(ans)); n_ans = n1 * n2; for (int i = 0; i <= n1; i++) for (int j = 0; j <= n2; j++) ans[i + j] += f1[i] * f2[j]; while (ans[n_ans] == 0 && n_ans >= 1) n_ans--; for (int i = 0; i <= n_ans; i++) cout << ans[i] << " "; cout << endl; return 0; }
23.584906
56
0.4296
XenonWZH
d93524fffa69a5379fc477ee31791afee29a3ff3
1,216
hpp
C++
Utils/IO/ZmqUtilities.hpp
shbang91/PnC
880cbbcf96a48a93a0ab646634781e4f112a71f6
[ "MIT" ]
1
2020-05-04T22:36:54.000Z
2020-05-04T22:36:54.000Z
Utils/IO/ZmqUtilities.hpp
shbang91/PnC
880cbbcf96a48a93a0ab646634781e4f112a71f6
[ "MIT" ]
null
null
null
Utils/IO/ZmqUtilities.hpp
shbang91/PnC
880cbbcf96a48a93a0ab646634781e4f112a71f6
[ "MIT" ]
null
null
null
#pragma once #include <zmq.hpp> // https://github.com/zeromq/cppzmq namespace myUtils { static std::string StringRecv(zmq::socket_t& socket) { zmq::message_t message; socket.recv(&message); return std::string(static_cast<char*>(message.data()), message.size()); } // Convert string to 0MQ string and send to socket static bool StringSend(zmq::socket_t& socket, const std::string& string) { zmq::message_t message(string.size()); memcpy(message.data(), string.data(), string.size()); bool rc = socket.send(message); return (rc); } // cpp send hello. // when python gets connected and recv hello, then req world // when cpp get req, rep dummy and break static void PairAndSync(zmq::socket_t& pub_socket, zmq::socket_t& rep_socket, int num_subscriber) { int num_connected(0); int i(0); while (true) { StringSend(pub_socket, "hello"); if (StringRecv(rep_socket) == "world") { ++num_connected; StringSend(rep_socket, ""); if (num_subscriber == num_connected) { break; } } else { StringSend(rep_socket, ""); } } } } // namespace myUtils
28.27907
77
0.613487
shbang91
d936408bbb026df5fe13f3e595aa7cbcbeb820fb
172
cpp
C++
cpp/ql/src/Likely Bugs/Likely Typos/ShortCircuitBitMask.cpp
vadi2/codeql
a806a4f08696d241ab295a286999251b56a6860c
[ "MIT" ]
4,036
2020-04-29T00:09:57.000Z
2022-03-31T14:16:38.000Z
cpp/ql/src/Likely Bugs/Likely Typos/ShortCircuitBitMask.cpp
vadi2/codeql
a806a4f08696d241ab295a286999251b56a6860c
[ "MIT" ]
2,970
2020-04-28T17:24:18.000Z
2022-03-31T22:40:46.000Z
cpp/ql/src/Likely Bugs/Likely Typos/ShortCircuitBitMask.cpp
ScriptBox99/github-codeql
2ecf0d3264db8fb4904b2056964da469372a235c
[ "MIT" ]
794
2020-04-29T00:28:25.000Z
2022-03-30T08:21:46.000Z
unsigned int new_mask = old_mask || 0x0100; //wrong, || logical operator just returns 1 or 0 unsigned int new_mask = old_mask | 0x0100; //right, | is a bit-mask operator
34.4
92
0.72093
vadi2
d938202b9dd190c708538419786d7e89c49df397
408
hpp
C++
libs/core/math/include/bksge/core/math/fwd/transform3_fwd.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
4
2018-06-10T13:35:32.000Z
2021-06-03T14:27:41.000Z
libs/core/math/include/bksge/core/math/fwd/transform3_fwd.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
566
2017-01-31T05:36:09.000Z
2022-02-09T05:04:37.000Z
libs/core/math/include/bksge/core/math/fwd/transform3_fwd.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
1
2018-07-05T04:40:53.000Z
2018-07-05T04:40:53.000Z
/** * @file transform3_fwd.hpp * * @brief Transform3 の前方宣言 * * @author myoukaku */ #ifndef BKSGE_CORE_MATH_FWD_TRANSFORM3_FWD_HPP #define BKSGE_CORE_MATH_FWD_TRANSFORM3_FWD_HPP namespace bksge { namespace math { template <typename T> class Transform3; } // namespace math using math::Transform3; } // namespace bksge #endif // BKSGE_CORE_MATH_FWD_TRANSFORM3_FWD_HPP
14.571429
49
0.713235
myoukaku
d938e853764c02451212522187e630c3f405de86
5,042
hpp
C++
ql/termstructures/yield/compositezeroyieldstructure.hpp
zhengyuzhang1/QuantLib
65867ab7c44419b69e40e553b41230744b83cff9
[ "BSD-3-Clause" ]
2
2021-12-12T01:27:45.000Z
2022-01-25T17:44:12.000Z
ql/termstructures/yield/compositezeroyieldstructure.hpp
zhengyuzhang1/QuantLib
65867ab7c44419b69e40e553b41230744b83cff9
[ "BSD-3-Clause" ]
17
2020-11-23T06:35:50.000Z
2022-03-28T19:00:09.000Z
ql/termstructures/yield/compositezeroyieldstructure.hpp
zhengyuzhang1/QuantLib
65867ab7c44419b69e40e553b41230744b83cff9
[ "BSD-3-Clause" ]
5
2020-06-04T15:19:22.000Z
2020-06-18T08:24:37.000Z
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2000, 2001, 2002, 2003 RiskMap srl Copyright (C) 2007, 2008 StatPro Italia srl Copyright (C) 2017 Francois Botha This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <quantlib-dev@lists.sf.net>. The license is also available online at <http://quantlib.org/license.shtml>. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ /*! \file compositezeroyieldstructure.hpp \brief Composite zero term structure */ #ifndef quantlib_composite_zero_yield_structure #define quantlib_composite_zero_yield_structure #include <ql/termstructures/yield/zeroyieldstructure.hpp> namespace QuantLib { template <class BinaryFunction> class CompositeZeroYieldStructure : public ZeroYieldStructure { public: CompositeZeroYieldStructure(const Handle<YieldTermStructure>& h1, const Handle<YieldTermStructure>& h2, const BinaryFunction& f, Compounding comp = Continuous, Frequency freq = NoFrequency); //! \name YieldTermStructure interface //@{ DayCounter dayCounter() const; Calendar calendar() const; Natural settlementDays() const; const Date& referenceDate() const; Date maxDate() const; Time maxTime() const; //@} //! \name Observer interface //@{ void update(); //@} protected: //! returns the composite zero yield rate Rate zeroYieldImpl(Time) const; private: Handle<YieldTermStructure> curve1_; Handle<YieldTermStructure> curve2_; BinaryFunction f_; Compounding comp_; Frequency freq_; }; // inline definitions template <class BinaryFunction> inline CompositeZeroYieldStructure<BinaryFunction>::CompositeZeroYieldStructure( const Handle<YieldTermStructure>& h1, const Handle<YieldTermStructure>& h2, const BinaryFunction& f, Compounding comp, Frequency freq) : curve1_(h1), curve2_(h2), f_(f), comp_(comp), freq_(freq) { if (!curve1_.empty() && !curve2_.empty()) enableExtrapolation(curve1_->allowsExtrapolation() && curve2_->allowsExtrapolation()); registerWith(curve1_); registerWith(curve2_); } template <class BinaryFunction> inline DayCounter CompositeZeroYieldStructure<BinaryFunction>::dayCounter() const { return curve1_->dayCounter(); } template <class BinaryFunction> inline Calendar CompositeZeroYieldStructure<BinaryFunction>::calendar() const { return curve1_->calendar(); } template <class BinaryFunction> inline Natural CompositeZeroYieldStructure<BinaryFunction>::settlementDays() const { return curve1_->settlementDays(); } template <class BinaryFunction> inline const Date& CompositeZeroYieldStructure<BinaryFunction>::referenceDate() const { return curve1_->referenceDate(); } template <class BinaryFunction> inline Date CompositeZeroYieldStructure<BinaryFunction>::maxDate() const { return curve1_->maxDate(); } template <class BinaryFunction> inline Time CompositeZeroYieldStructure<BinaryFunction>::maxTime() const { return curve1_->maxTime(); } template <class BinaryFunction> inline void CompositeZeroYieldStructure<BinaryFunction>::update() { if (!curve1_.empty() && !curve2_.empty()) { YieldTermStructure::update(); enableExtrapolation(curve1_->allowsExtrapolation() && curve2_->allowsExtrapolation()); } else { /* The implementation inherited from YieldTermStructure asks for our reference date, which we don't have since the original curve is still not set. Therefore, we skip over that and just call the base-class behavior. */ TermStructure::update(); } } template <class BinaryFunction> inline Rate CompositeZeroYieldStructure<BinaryFunction>::zeroYieldImpl(Time t) const { Rate zeroRate1 = curve1_->zeroRate(t, comp_, freq_, true); InterestRate zeroRate2 = curve2_->zeroRate(t, comp_, freq_, true); InterestRate compositeRate(f_(zeroRate1, zeroRate2), dayCounter(), comp_, freq_); return compositeRate.equivalentRate(Continuous, NoFrequency, t); } } #endif
35.758865
98
0.664816
zhengyuzhang1
d93d8cc76201b80a01213aeff9226f6660ae530f
1,502
cpp
C++
UVa 10706 Number sequence/sample/sol.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
1
2020-11-24T03:17:21.000Z
2020-11-24T03:17:21.000Z
UVa 10706 Number sequence/sample/sol.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
null
null
null
UVa 10706 Number sequence/sample/sol.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
1
2021-04-11T16:22:31.000Z
2021-04-11T16:22:31.000Z
#include <algorithm> #include <iostream> #include <cstring> #include <string> #include <vector> #include <cstdio> #include <stack> #include <queue> #include <cmath> #include <set> using namespace std; #define MAXN 100000 int t , n; long long num[MAXN];//保存某一个值的总数 //打表初始化 void init() { long long i , j , k , tmp;//long long注意 memset(num , 0 , sizeof(num));//初始化 for (i = 1 ; i <= 5 ; i++) //枚举位数,最大到5位即可 { for (j = pow(10, i - 1) ; j < pow(10, i) ; j++) { num[j] = num[j - 1] ; tmp = (j - pow(10, i - 1) + 1) * i; for (k = 1 ; k < i ; k++) tmp += (pow(10, k) - pow(10, k - 1)) * k; num[j] += tmp; } } } void solve() { int i , j , k , pos , ans; //找到pos位置 for (i = 1 ; i < MAXN ; i++) { if (n > num[i - 1] && n <= num[i]) { pos = i ; break; } } //查找 int cnt = n - num[pos - 1] ; int sum = 0; int len , tmp , tmp_j; for (j = 1 ; j <= pos ; j++) { tmp_j = j; for (i = tmp_j , len = 0 ; i != 0 ; i /= 10) len++; for (k = len - 1; k >= 0 ; k--) { ans = tmp_j / pow(10, k) ; sum++; if (sum == cnt) { printf("%d\n" , ans); return; } tmp = pow(10, k) ; tmp_j %= tmp; } } } int main() { init() ; scanf("%d" , &t); while (t--) { scanf("%d" , &n) ; solve(); } return 0; }
20.575342
69
0.393475
tadvi
d93d8e9c9fc4d497c5458a69578e22148aadd130
31
hpp
C++
src/boost_vmd_array.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_vmd_array.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_vmd_array.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/vmd/array.hpp>
15.5
30
0.741935
miathedev
d93da3ce769ea2a0b6bdebad8430307a6c9669c2
3,071
cpp
C++
opticalFlowApp1/src/ofApp.cpp
aa-debdeb/openFrameworks
c535eaa4a386879ef5db551357b29135b60520a0
[ "MIT" ]
1
2020-05-26T09:23:30.000Z
2020-05-26T09:23:30.000Z
opticalFlowApp1/src/ofApp.cpp
aadebdeb/openFrameworks
c535eaa4a386879ef5db551357b29135b60520a0
[ "MIT" ]
null
null
null
opticalFlowApp1/src/ofApp.cpp
aadebdeb/openFrameworks
c535eaa4a386879ef5db551357b29135b60520a0
[ "MIT" ]
2
2018-12-18T09:12:55.000Z
2021-05-26T04:27:37.000Z
#include "ofApp.h" using namespace ofxCv; using namespace cv; //-------------------------------------------------------------- void ofApp::setup(){ ofSetFrameRate(60); camera.setup(320, 240); gui.setup(); gui.add(fbPyrScale.set("fbPyrScale", .5, 0, .99)); gui.add(fbLevels.set("fbLevels", 4, 1, 8)); gui.add(fbIterations.set("fbIterations", 2, 1, 8)); gui.add(fbPolyN.set("fbPolyN", 7, 5, 10)); gui.add(fbPolySigma.set("fbPolySigma", 1.5, 1.1, 2)); gui.add(fbUseGaussian.set("fbUseGaussian", false)); gui.add(fbWinSize.set("winSize", 32, 4, 64)); particles = vector<Particle>(); for(int i = 0; i < 1000; i++){ particles.push_back(Particle()); } } //-------------------------------------------------------------- void ofApp::update(){ camera.update(); fbFlow.setPyramidScale(fbPyrScale); fbFlow.setNumLevels(fbLevels); fbFlow.setWindowSize(fbWinSize); fbFlow.setNumIterations(fbIterations); fbFlow.setPolyN(fbPolyN); fbFlow.setPolySigma(fbPolySigma); fbFlow.setUseGaussian(fbUseGaussian); fbFlow.calcOpticalFlow(camera); for(int i = 0; i < particles.size(); i++){ float adjustedX = particles[i].position.x * float(camera.getWidth()) / ofGetWidth(); float adjustedY = particles[i].position.y * float(camera.getHeight()) / ofGetHeight(); ofVec2f force = fbFlow.getFlowOffset(adjustedX, adjustedY) * 3; particles[i].serForce(force); particles[i].update(); } } //-------------------------------------------------------------- void ofApp::draw(){ ofSetColor(255); camera.draw(0, 0, ofGetWidth(), ofGetHeight()); fbFlow.draw(0, 0, ofGetWidth(), ofGetHeight()); for(int i = 0; i < particles.size(); i++){ particles[i].draw(); } gui.draw(); } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
26.474138
94
0.447086
aa-debdeb
d93e003a4bb8ed164783dd456ca23830c1031ad2
4,698
cc
C++
Library/Utilities/fftw++-2.05/tests/tconv.cc
stevend12/SolutioCpp
6fa8a12207cd1e7e806a8ef5de93dc137c33856e
[ "Apache-2.0" ]
9
2017-06-27T14:04:46.000Z
2022-02-17T17:38:03.000Z
Library/Utilities/fftw++-2.05/tests/tconv.cc
stevend12/SolutioCpp
6fa8a12207cd1e7e806a8ef5de93dc137c33856e
[ "Apache-2.0" ]
null
null
null
Library/Utilities/fftw++-2.05/tests/tconv.cc
stevend12/SolutioCpp
6fa8a12207cd1e7e806a8ef5de93dc137c33856e
[ "Apache-2.0" ]
3
2017-06-23T20:10:44.000Z
2021-01-13T10:09:46.000Z
#include "convolution.h" #include "explicit.h" #include "direct.h" #include "utils.h" #include "Array.h" using namespace std; using namespace utils; using namespace fftwpp; // Number of iterations. unsigned int N0=10000000; unsigned int N=0; unsigned int m=12; unsigned int M=1; unsigned int B=1; bool Direct=false, Implicit=true, Explicit=false; inline void init(Complex *e, Complex *f, Complex *g, unsigned int M=1) { unsigned int m1=m+1; unsigned int Mm=M*m1; double factor=1.0/cbrt((double) M); for(unsigned int i=0; i < Mm; i += m1) { double s=sqrt(1.0+i); double efactor=1.0/s*factor; double ffactor=(1.0+i)*s*factor; double gfactor=1.0/(1.0+i)*factor; Complex *ei=e+i; Complex *fi=f+i; Complex *gi=g+i; ei[0]=1.0*efactor; for(unsigned int k=1; k < m; k++) ei[k]=efactor*Complex(k,k+1); fi[0]=1.0*ffactor; for(unsigned int k=1; k < m; k++) fi[k]=ffactor*Complex(k,k+1); gi[0]=2.0*gfactor; for(unsigned int k=1; k < m; k++) gi[k]=gfactor*Complex(k,2*k+1); } } int main(int argc, char* argv[]) { fftw::maxthreads=get_max_threads(); unsigned int stats=0; // Type of statistics used in timing test. #ifndef __SSE2__ fftw::effort |= FFTW_NO_SIMD; #endif #ifdef __GNUC__ optind=0; #endif for (;;) { int c = getopt(argc,argv,"hdeipA:B:N:m:n:T:S:"); if (c == -1) break; switch (c) { case 0: break; case 'd': Direct=true; break; case 'e': Explicit=true; Implicit=false; break; case 'i': Implicit=true; Explicit=false; break; case 'p': break; case 'A': M=2*atoi(optarg); break; case 'B': B=atoi(optarg); break; case 'N': N=atoi(optarg); break; case 'm': m=atoi(optarg); break; case 'n': N0=atoi(optarg); break; case 'T': fftw::maxthreads=max(atoi(optarg),1); break; case 'S': stats=atoi(optarg); break; case 'h': default: usage(1); usageExplicit(1); exit(0); } } unsigned int n=tpadding(m); cout << "n=" << n << endl; cout << "m=" << m << endl; if(N == 0) { N=N0/n; N = max(N, 20); } cout << "N=" << N << endl; Complex *h0=NULL; if(Direct && ! Explicit) h0=ComplexAlign(m); unsigned int m1=m+1; unsigned int np=Explicit ? n/2+1 : m1; if(Implicit) np *= M; if(B != 1) { cerr << "B=" << B << " is not yet implemented" << endl; exit(1); } Complex *e=ComplexAlign(np); Complex *f=ComplexAlign(np); Complex *g=ComplexAlign(np); double *T=new double[N]; if(Implicit) { ImplicitHTConvolution C(m,M); cout << "Using " << C.Threads() << " threads."<< endl; Complex **E=new Complex *[M]; Complex **F=new Complex *[M]; Complex **G=new Complex *[M]; for(unsigned int s=0; s < M; ++s) { unsigned int sm=s*m1; E[s]=e+sm; F[s]=f+sm; G[s]=g+sm; } for(unsigned int i=0; i < N; ++i) { init(e,f,g,M); seconds(); C.convolve(E,F,G); // C.convolve(e,f,g); T[i]=seconds(); } timings("Implicit",m,T,N,stats); if(Direct) for(unsigned int i=0; i < m; i++) h0[i]=e[i]; if(m < 100) for(unsigned int i=0; i < m; i++) cout << e[i] << endl; else cout << e[0] << endl; delete [] G; delete [] F; delete [] E; } if(Explicit) { ExplicitHTConvolution C(n,m,f); for(unsigned int i=0; i < N; ++i) { init(e,f,g); seconds(); C.convolve(e,f,g); T[i]=seconds(); } timings("Explicit",m,T,N,stats); if(m < 100) for(unsigned int i=0; i < m; i++) cout << e[i] << endl; else cout << e[0] << endl; } if(Direct) { DirectHTConvolution C(m); init(e,f,g); Complex *h=ComplexAlign(m); seconds(); C.convolve(h,e,f,g); T[0]=seconds(); timings("Direct",m,T,1); if(m < 100) for(unsigned int i=0; i < m; i++) cout << h[i] << endl; else cout << h[0] << endl; if(Implicit) { // compare implicit or explicit version with direct verion: double error=0.0; cout << endl; double norm=0.0; for(unsigned long long k=0; k < m; k++) { error += abs2(h0[k]-h[k]); norm += abs2(h[k]); } if(norm > 0) error=sqrt(error/norm); cout << "error=" << error << endl; if (error > 1e-12) cerr << "Caution! error=" << error << endl; } deleteAlign(h); } deleteAlign(g); deleteAlign(f); deleteAlign(e); delete [] T; return 0; }
21.354545
78
0.517667
stevend12
d93ed803e721aab4f40055ae181432c234521c06
1,558
cpp
C++
boards/ip/hls/color_convert/color_convert.cpp
Kiminje/PYNQ
9c011e4eb24398ceb9dc24edf10b4fd8cbf5062c
[ "BSD-3-Clause" ]
1,537
2016-09-26T22:51:50.000Z
2022-03-31T13:33:54.000Z
boards/ip/hls/color_convert/color_convert.cpp
louisliuwei/PYNQ
80b08caa8fbd316a521fcbead2c4772fe736f22d
[ "BSD-3-Clause" ]
414
2016-10-03T21:12:10.000Z
2022-03-21T14:55:02.000Z
boards/ip/hls/color_convert/color_convert.cpp
louisliuwei/PYNQ
80b08caa8fbd316a521fcbead2c4772fe736f22d
[ "BSD-3-Clause" ]
826
2016-09-23T22:29:43.000Z
2022-03-29T11:02:09.000Z
#include <ap_fixed.h> #include <ap_int.h> typedef ap_uint<8> pixel_type; typedef ap_int<8> pixel_type_s; typedef ap_ufixed<8,0, AP_RND, AP_SAT> comp_type; typedef ap_fixed<10,2, AP_RND, AP_SAT> coeff_type; struct video_stream { struct { pixel_type_s p1; pixel_type_s p2; pixel_type_s p3; } data; ap_uint<1> user; ap_uint<1> last; }; struct coeffs { coeff_type c1; coeff_type c2; coeff_type c3; }; void color_convert(video_stream* stream_in_24, video_stream* stream_out_24, coeffs c1, coeffs c2, coeffs c3, coeffs bias) { #pragma HLS CLOCK domain=default #pragma HLS INTERFACE ap_ctrl_none port=return #pragma HLS INTERFACE s_axilite register port=c1 clock=control #pragma HLS INTERFACE s_axilite register port=c2 clock=control #pragma HLS INTERFACE s_axilite register port=c3 clock=control #pragma HLS INTERFACE s_axilite register port=bias clock=control #pragma HLS INTERFACE axis port=stream_in_24 #pragma HLS INTERFACE axis port=stream_out_24 #pragma HLS pipeline II=1 stream_out_24->user = stream_in_24->user; stream_out_24->last = stream_in_24->last; comp_type in1, in2, in3, out1, out2, out3; in1.range() = stream_in_24->data.p1; in2.range() = stream_in_24->data.p2; in3.range() = stream_in_24->data.p3; out1 = in1 * c1.c1 + in2 * c1.c2 + in3 * c1.c3 + bias.c1; out2 = in1 * c2.c1 + in2 * c2.c2 + in3 * c2.c3 + bias.c2; out3 = in1 * c3.c1 + in2 * c3.c2 + in3 * c3.c3 + bias.c3; stream_out_24->data.p1 = out1.range(); stream_out_24->data.p2 = out2.range(); stream_out_24->data.p3 = out3.range(); }
28.327273
76
0.725931
Kiminje
d93f12f5799f74fddc5cea504535c8da95092caf
712
cpp
C++
TimeTableGenerator/src/Colors.cpp
Electrux/CCPP-Code
3c5e5b866cf050c11bced9651b112eb31dd2465d
[ "BSD-3-Clause" ]
6
2019-08-29T23:31:17.000Z
2021-11-14T20:35:47.000Z
TimeTableGenerator/src/Colors.cpp
Electrux/CCPP-Code
3c5e5b866cf050c11bced9651b112eb31dd2465d
[ "BSD-3-Clause" ]
null
null
null
TimeTableGenerator/src/Colors.cpp
Electrux/CCPP-Code
3c5e5b866cf050c11bced9651b112eb31dd2465d
[ "BSD-3-Clause" ]
1
2019-09-01T12:22:58.000Z
2019-09-01T12:22:58.000Z
#include <string> #include <map> #include "../include/Colors.hpp" int SubstituteColors( std::string & str ) { int len = 0; std::string var; for( std::string::iterator it = str.begin(); it != str.end(); ) { if( * it == '{' && it + 1 != str.end() ) { it = str.erase( it ); if( * it == '{' ) { len++; ++it; continue; } var = ""; while( it != str.end() && * it != '}' ) { var += * it; it = str.erase( it ); } it = str.erase( it ); if( COLORS.find( var ) != COLORS.end() ) { it = str.insert( it, COLORS[ var ].begin(), COLORS[ var ].end() ); it += COLORS[ var ].size(); } continue; } len = * it == '\n' ? 0 : len + 1; ++it; } return len; }
18.25641
70
0.464888
Electrux
d949945e1d6bfbef9602f86e463bd04c8c5c2734
1,416
cpp
C++
tdutils/td/utils/port/detail/ThreadIdGuard.cpp
takpare/-T
6c706f45e7a73c936b9f2f267785092c8a73348f
[ "BSL-1.0" ]
1
2022-02-04T01:49:51.000Z
2022-02-04T01:49:51.000Z
tdutils/td/utils/port/detail/ThreadIdGuard.cpp
shafiahmed/td
19ef0361f9e4bf7e45e117f2fd12307629298d5e
[ "BSL-1.0" ]
null
null
null
tdutils/td/utils/port/detail/ThreadIdGuard.cpp
shafiahmed/td
19ef0361f9e4bf7e45e117f2fd12307629298d5e
[ "BSL-1.0" ]
null
null
null
// // Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2018 // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "td/utils/port/detail/ThreadIdGuard.h" #include "td/utils/logging.h" #include "td/utils/port/thread_local.h" #include <array> #include <mutex> namespace td { namespace detail { class ThreadIdManager { public: int32 register_thread() { std::lock_guard<std::mutex> guard(mutex_); for (size_t i = 0; i < is_id_used_.size(); i++) { if (!is_id_used_[i]) { is_id_used_[i] = true; return static_cast<int32>(i + 1); } } LOG(FATAL) << "Cannot create more than " << max_thread_count() << " threads"; return 0; } void unregister_thread(int32 thread_id) { thread_id--; std::lock_guard<std::mutex> guard(mutex_); CHECK(is_id_used_.at(thread_id)); is_id_used_[thread_id] = false; } private: std::mutex mutex_; std::array<bool, max_thread_count()> is_id_used_{{false}}; }; static ThreadIdManager thread_id_manager; ThreadIdGuard::ThreadIdGuard() { thread_id_ = thread_id_manager.register_thread(); set_thread_id(thread_id_); } ThreadIdGuard::~ThreadIdGuard() { thread_id_manager.unregister_thread(thread_id_); set_thread_id(0); } } // namespace detail } // namespace td
26.716981
96
0.695621
takpare
d95082633a8c1fb7f7b5069eac4c295a311dc0c9
29
cpp
C++
tutorials/learncpp.com#1.0#1/arrays__strings__pointers__and_references/references/source10.cpp
officialrafsan/CppDroid
5fb2cc7750fea53b1ea6ff47b5094da6e95e9224
[ "MIT" ]
null
null
null
tutorials/learncpp.com#1.0#1/arrays__strings__pointers__and_references/references/source10.cpp
officialrafsan/CppDroid
5fb2cc7750fea53b1ea6ff47b5094da6e95e9224
[ "MIT" ]
null
null
null
tutorials/learncpp.com#1.0#1/arrays__strings__pointers__and_references/references/source10.cpp
officialrafsan/CppDroid
5fb2cc7750fea53b1ea6ff47b5094da6e95e9224
[ "MIT" ]
null
null
null
sOther.sSomething.nValue = 5;
29
29
0.793103
officialrafsan
d951492eb5b7308620f090ddc66b4b3d40280e35
293
hpp
C++
WinSensor/Source/HRESULT_Support.hpp
SekiShuhei/ARWorkspace
917089e29f5ea41336ffea4cd6f545bffb1f1c16
[ "Apache-2.0" ]
null
null
null
WinSensor/Source/HRESULT_Support.hpp
SekiShuhei/ARWorkspace
917089e29f5ea41336ffea4cd6f545bffb1f1c16
[ "Apache-2.0" ]
5
2020-04-17T10:08:29.000Z
2020-04-26T07:17:18.000Z
WinSensor/Source/HRESULT_Support.hpp
SekiShuhei/ARWorkspace
917089e29f5ea41336ffea4cd6f545bffb1f1c16
[ "Apache-2.0" ]
null
null
null
#pragma once #include "SensorManagerDefine.hpp" namespace WinSensor { class HRESULT_Support { public: inline bool IsError() const { return FAILED(this->result); } inline HRESULT GetResult() const { return this->result; } protected: HRESULT result = S_OK; }; }
13.952381
35
0.668942
SekiShuhei
d9534321c02648b59665b03a32e04b2229ab4343
2,955
hpp
C++
bbdata/prbs.hpp
kb3gtn/kb3gtn_sdr
384c2ea7c778cd0ddbf355a705a19cbf08725d4e
[ "MIT" ]
null
null
null
bbdata/prbs.hpp
kb3gtn/kb3gtn_sdr
384c2ea7c778cd0ddbf355a705a19cbf08725d4e
[ "MIT" ]
null
null
null
bbdata/prbs.hpp
kb3gtn/kb3gtn_sdr
384c2ea7c778cd0ddbf355a705a19cbf08725d4e
[ "MIT" ]
null
null
null
#pragma once #include <iostream> #include <vector> #include <cstdint> #include <cmath> // PRBS patterns enum prbs_pattern_t { USER = 0, ALL_ZEROS = 1, ALL_ONES = 2, ALT_ONE_ZERO = 3, ITU_PN9 = 4, ITU_PN11 = 5, ITU_PN15 = 6, ITU_PN23 = 7 }; // utility methods int popcount64(uint64_t x); uint8_t flipbitorder(uint8_t b); uint64_t TAP(int bit_idx); void PrintDataBuffer( std::vector<uint8_t> buffer ); void PrintDataBuffer( uint8_t *mem, int len ); // pattern table entry struct pattern_table_entry_t { int pattern_idx; // Index in table uint64_t reg; // regsiter initial value uint64_t reg_mask; // register active bit mask uint64_t fb_mask; // register feedback bit mask uint64_t reg_len_bits; // number of bits in active mask char name[32]; // name of this pattern }; // pre-defined patterns for this generator. // user defined patters will require manual update to pattern_info_t data member // in the Handle top setup register taps and length values.. const struct pattern_table_entry_t pattern_lookup_table[] = { {USER, 0, 0, 0, 0, "user pattern"}, {ALL_ZEROS, 0, 0, 0, 1, "all zeros"}, {ALL_ONES, 1, 1, 1, 1, "all ones"}, {ALT_ONE_ZERO, 0x2, 0x3, 0x2, 2, "alt one zero" }, {ITU_PN9, 0x1FF, 0x1FF, TAP(9) | TAP(5), 9, "ITU PN9"}, {ITU_PN11, 0x7FF, 0x7FF, TAP(11) | TAP(9), 11, "ITU PN11"}, {ITU_PN15, 0x7FFF, 0x7FFF, TAP(15) | TAP(14), 15, "ITU PN15"}, {ITU_PN23, 0x7FFFFF, 0x7FFFFF, TAP(23) | TAP(18), 23, "ITU PN23"} }; // data/state and function for PRBS pattern generation. struct PRBSGEN { // generate PRBS pattern to fill the buffer. void generate( std::vector<uint8_t> *buffer ); void generate( uint8_t *buffer, int len ); // number of bits sent. uint64_t bits_tx; // register uint64_t reg; uint64_t reg_mask; uint64_t fb_mask; uint64_t reg_len_bits; // constructors // initialize from known pattern PRBSGEN( prbs_pattern_t pat ); // initialize from specified parameters PRBSGEN( uint64_t _reg, uint64_t _reg_mask, uint64_t _fb_mask, uint64_t _reg_len_bits ); }; // data/state and functions for PRBS pattern checking. struct PRBSCHK { // generate PRBS pattern to fill the buffer. void check( std::vector<uint8_t> *buffer ); void check( uint8_t *buffer, int len ); // number of bits received. // number of bits received. uint64_t bits_rx; uint64_t bits_rx_locked; uint64_t bit_errors_detected; uint64_t isLocked; uint64_t sync_slips; double getBER(); void reset_stats(); double __bit_match; // register uint64_t reg; uint64_t reg_mask; uint64_t fb_mask; uint64_t reg_len_bits; // constructors // initialize from known pattern PRBSCHK( prbs_pattern_t pat ); // initialize from specified parameters PRBSCHK( uint64_t _reg, uint64_t _reg_mask, uint64_t _fb_mask, uint64_t _reg_len_bits ); };
29.257426
92
0.679188
kb3gtn
d9537b7a24ec7b4dbd1d631dd0d30ca6a7139118
1,163
hpp
C++
ares/sfc/coprocessor/competition/competition.hpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
153
2020-07-25T17:55:29.000Z
2021-10-01T23:45:01.000Z
ares/sfc/coprocessor/competition/competition.hpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
245
2021-10-08T09:14:46.000Z
2022-03-31T08:53:13.000Z
ares/sfc/coprocessor/competition/competition.hpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
44
2020-07-25T08:51:55.000Z
2021-09-25T16:09:01.000Z
//HLE of the NEC uPD78P214GC processor found on SNES-EVENT PCBs, used by: //* Campus Challenge '92 //* PowerFest '94 //The NEC uPD78214 family are 8-bit microprocessors containing: //* UART/CSI serial interface //* ALU (MUL, DIV, BCD) //* interrupts (12 internal; 7 external; 2 priority levels) //* 16384 x 8-bit ROM //* 512 x 8-bit RAM //* 4 x timer/counters //None of the SNES-EVENT games have had their uPD78214 firmware dumped. //As such, our only option is very basic high-level emulation, provided here. struct Competition : Thread { //competition.cpp auto main() -> void; auto unload() -> void; auto power() -> void; auto mcuRead(n24 address, n8) -> n8; auto mcuWrite(n24 address, n8) -> void; auto read(n24 address, n8 data) -> n8; auto write(n24 address, n8 data) -> void; //serialization.cpp auto serialize(serializer&) -> void; public: ReadableMemory rom[4]; enum class Board : u32 { Unknown, CampusChallenge92, PowerFest94 } board; u32 timer; private: n8 status; n8 select; n1 timerActive; n1 scoreActive; u32 timerSecondsRemaining; u32 scoreSecondsRemaining; }; extern Competition competition;
23.734694
77
0.698194
CasualPokePlayer
d953a2cc6db36ee829db0d1e0b7f9d9fd9adaaa3
307
hpp
C++
libs/libwarhammerengine/model.hpp
julienlopez/QWarhammerSimulator
bd6f5b657dab36da0abdf14747434a1c9e9eaf20
[ "MIT" ]
null
null
null
libs/libwarhammerengine/model.hpp
julienlopez/QWarhammerSimulator
bd6f5b657dab36da0abdf14747434a1c9e9eaf20
[ "MIT" ]
6
2021-01-07T07:38:46.000Z
2021-07-13T16:43:35.000Z
libs/libwarhammerengine/model.hpp
julienlopez/QWarhammerSimulator
bd6f5b657dab36da0abdf14747434a1c9e9eaf20
[ "MIT" ]
null
null
null
#pragma once #include "characteristics.hpp" #include "point.hpp" #include <string> namespace QWarhammerSimulator::LibWarhammerEngine { struct Model { std::string name; LibGeometry::Point base_size; Characteristics characteristics; }; } // namespace QWarhammerSimulator::LibWarhammerEngine
15.35
54
0.762215
julienlopez
d9564bc29a2194995a78829e4d6319abb350a4c7
133
cpp
C++
contest/AtCoder/abc002/C.cpp
not522/Competitive-Programming
be4a7d25caf5acbb70783b12899474a56c34dedb
[ "Unlicense" ]
7
2018-04-14T14:55:51.000Z
2022-01-31T10:49:49.000Z
contest/AtCoder/abc002/C.cpp
not522/Competitive-Programming
be4a7d25caf5acbb70783b12899474a56c34dedb
[ "Unlicense" ]
5
2018-04-14T14:28:49.000Z
2019-05-11T02:22:10.000Z
contest/AtCoder/abc002/C.cpp
not522/Competitive-Programming
be4a7d25caf5acbb70783b12899474a56c34dedb
[ "Unlicense" ]
null
null
null
#include "geometry/segment.hpp" int main() { Point a(in), b(in), c(in); cout << (Segment(b - a, c - a)).area().abs() << endl; }
19
55
0.541353
not522
d957ce783bc07533b3b1a826a0fdd55463ac8b8a
2,678
hpp
C++
gazebo_ros2_control_bolt/include/gazebo_ros2_control_bolt/gazebo_bolt_ros2_control_plugin.hpp
stack-of-tasks/ros2_control_bolt
0be202ffffc7b22118db38d77a8d52e572dc4d13
[ "Apache-2.0" ]
5
2022-01-10T14:26:12.000Z
2022-02-01T12:36:55.000Z
gazebo_ros2_control_bolt/include/gazebo_ros2_control_bolt/gazebo_bolt_ros2_control_plugin.hpp
stack-of-tasks/ros2_control_bolt
0be202ffffc7b22118db38d77a8d52e572dc4d13
[ "Apache-2.0" ]
3
2022-01-15T14:44:45.000Z
2022-02-01T05:54:13.000Z
gazebo_ros2_control_bolt/include/gazebo_ros2_control_bolt/gazebo_bolt_ros2_control_plugin.hpp
stack-of-tasks/ros2_control_bolt
0be202ffffc7b22118db38d77a8d52e572dc4d13
[ "Apache-2.0" ]
3
2022-01-10T13:05:20.000Z
2022-01-14T17:51:05.000Z
// Copyright (c) 2013, Open Source Robotics Foundation. All rights reserved. // Copyright (c) 2013, The Johns Hopkins University. 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 Open Source Robotics Foundation 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. /* Author: Dave Coleman, Jonathan Bohren Desc: Gazebo plugin for ros_control that allows 'hardware_interfaces' to be plugged in using pluginlib */ #ifndef GAZEBO_ROS2_CONTROL__GAZEBO_ROS2_CONTROL_PLUGIN_HPP_ #define GAZEBO_ROS2_CONTROL__GAZEBO_ROS2_CONTROL_PLUGIN_HPP_ #include <memory> #include <string> #include <vector> #include "controller_manager/controller_manager.hpp" #include "gazebo/common/common.hh" #include "gazebo/physics/Model.hh" namespace gazebo_ros2_control_bolt { class GazeboRosControlPrivate; class GazeboBoltRosControlPlugin : public gazebo::ModelPlugin { public: GazeboBoltRosControlPlugin(); ~GazeboBoltRosControlPlugin(); // Overloaded Gazebo entry point void Load(gazebo::physics::ModelPtr parent, sdf::ElementPtr sdf) override; private: /// Private data pointer std::unique_ptr<GazeboRosControlPrivate> impl_; }; } // namespace gazebo_ros2_control #endif // GAZEBO_ROS2_CONTROL__GAZEBO_ROS2_CONTROL_PLUGIN_HPP_
39.382353
91
0.775205
stack-of-tasks
d95c47b8c9dd490dbb4a6ad37778a670d2cbf32c
2,658
hxx
C++
include/prevc/pipeline/AST/new.hxx
arazeiros/prevc
378f045f57b2e1c9460ac1699951291ac055c078
[ "MIT" ]
3
2018-10-30T20:33:45.000Z
2019-03-06T11:46:31.000Z
include/prevc/pipeline/AST/new.hxx
arazeiros/prevc
378f045f57b2e1c9460ac1699951291ac055c078
[ "MIT" ]
null
null
null
include/prevc/pipeline/AST/new.hxx
arazeiros/prevc
378f045f57b2e1c9460ac1699951291ac055c078
[ "MIT" ]
null
null
null
#ifndef PREVC_PIPELINE_AST_NEW_HXX #define PREVC_PIPELINE_AST_NEW_HXX #include <prevc/pipeline/AST/expression.hxx> #include <prevc/pipeline/AST/type.hxx> namespace prevc { namespace pipeline { namespace AST { /** * \brief Represent an new-expression in the AST. * */ class New: public Expression { public: /** * \brief Create an AST new-expression at the specified location. * \param pipeline The pipeline that owns this AST node. * \param location The location of the expression in the source code. * \param type The type of the new-allocation. * */ New(Pipeline* pipeline, util::Location&& location, Type* type); /** * \brief Release the used resources. * */ virtual ~New(); /** * \brief Checks the semantics of the node. * \param pipeline The pipeline of the node. * */ virtual void check_semantics() override; /** * \brief Generate the IR code for this expression. * \param builder The builder of the IR block containing this expression. * \return The IR value representing this expression. * */ virtual llvm::Value* generate_IR(llvm::IRBuilder<>* builder) override; /** * \brief Evaluate the expression as an integer (if possible). * \return Returns the evaluated integer. * */ virtual std::optional<std::int64_t> evaluate_as_integer() const noexcept override; /** * \brief Returns the semantic type of this expression. * \return The semantic type of this expression. * * Before this method can be called, the call to `check_semantics()` have to be done. * */ virtual const semantic_analysis::Type* get_semantic_type() override; /** * \brief Returns a string representation of this primitive type. * \return The representation in JSON format. * */ virtual util::String to_string() const noexcept override; private: /** * \brief The type of the new-allocation. * */ Type* type; }; } } } #endif
34.519481
101
0.501129
arazeiros
d95f42fba2d8cfeff48263ce830de7bf6ac7aa37
1,950
cpp
C++
LuoguCodes/P1589.cpp
Anguei/OI-Codes
0ef271e9af0619d4c236e314cd6d8708d356536a
[ "MIT" ]
null
null
null
LuoguCodes/P1589.cpp
Anguei/OI-Codes
0ef271e9af0619d4c236e314cd6d8708d356536a
[ "MIT" ]
null
null
null
LuoguCodes/P1589.cpp
Anguei/OI-Codes
0ef271e9af0619d4c236e314cd6d8708d356536a
[ "MIT" ]
null
null
null
// luogu-judger-enable-o2 #include <cmath> #include <cctype> #include <cstdio> #include <cstring> #include <set> #include <map> #include <stack> #include <queue> #include <string> #include <vector> #include <numeric> #include <iomanip> #include <iostream> #include <algorithm> #define fn "cover" #define ll long long #define int long long #define pc(x) putchar(x) #define fileIn freopen("testdata.in", "r", stdin) #define fileOut freopen("testdata.out", "w", stdout) #define rep(i, a, b) for (int i = (a); i <= (b); ++i) #define per(i, a, b) for (int i = (a); i >= (b); --i) #ifdef yyfLocal #define dbg(x) std::clog << #x" = " << (x) << std::endl #define logs(x) std::clog << (x) << std::endl #else #define dbg(x) 42 #define logs(x) 42 #endif int read() { int res = 0, flag = 1; char ch = getchar(); while (!isdigit(ch)) { if (ch == ';-';) flag = -1; ch = getchar(); } while (isdigit(ch)) res = res * 10 + ch - 48, ch = getchar(); return res * flag; } void print(int x) { if (x < 0) putchar(';-';), x = -x; if (x > 9) print(x / 10); putchar(x % 10 + 48); } struct Segment { int l, r; Segment() = default; Segment(int l, int r) : l(l), r(r) {} }; const int N = 100000 + 5; Segment seg[N]; void solution() { int n = read(), len = read(); rep(i, 1, n) seg[i].l = read(), seg[i].r = read(); std::sort(seg + 1, seg + n + 1, [](const Segment &s1, const Segment &s2) { return s1.l < s2.l; }); int tot = 0, cur = 0; rep(i, 1, n) { cur = std::max(cur, seg[i].l); if (cur < seg[i].r) { int a = seg[i].r - cur; int b = a / len + static_cast<bool>(a % len); cur += b * len; tot += b; } } print(tot), puts(""); } signed main() { #ifdef yyfLocal fileIn; //fileOut; #else #ifndef ONLINE_JUDGE freopen(fn".in", "r", stdin); freopen(fn".out", "w", stdout); #endif #endif solution(); }
23.214286
78
0.53641
Anguei
d95fba4907c6ef046313f0e4bd0590d7a209c6a7
5,061
cpp
C++
WordleSover/WordleSover/Database.cpp
Squirrelbear/Wordle-Solver
496ee95ec377d0e300212fbcd96939a6eac26cb6
[ "MIT" ]
null
null
null
WordleSover/WordleSover/Database.cpp
Squirrelbear/Wordle-Solver
496ee95ec377d0e300212fbcd96939a6eac26cb6
[ "MIT" ]
null
null
null
WordleSover/WordleSover/Database.cpp
Squirrelbear/Wordle-Solver
496ee95ec377d0e300212fbcd96939a6eac26cb6
[ "MIT" ]
null
null
null
#include "Database.h" #include <fstream> #include <iostream> #include <string> #include <algorithm> Database::Database() { reset(); } void Database::filterByRule(const std::string& rule) { _rules.push_back(rule); _data.erase(std::remove_if(_data.begin(), _data.end(), [&](std::string& word) { return !wordFitsRule(rule, word); }) , _data.end()); } void Database::reset() { _data.clear(); _rules.clear(); std::ifstream file("../words.txt"); if (!file.is_open()) { std::cerr << "Failed to load words..." << std::endl; return; } std::string word; while (std::getline(file, word)) { _data.emplace_back(word); } std::cout << "Word list successfully loaded with " << _data.size() << " words." << std::endl; file.close(); std::sort(_data.begin(), _data.end()); } void Database::outputSuggestion() const { std::cout << "Count remaining: " << _data.size() << std::endl; if (_data.size() <= 80) { showAll(); } showLetterChance(); } void Database::showAll() const { std::cout << "Word list remaining:" << std::endl; int rowCounter = 0; for (const auto& word : _data) { std::cout << word << " "; ++rowCounter; if (rowCounter == 10) { std::cout << std::endl; rowCounter = 0; } } std::cout << std::endl << std::endl; } void Database::showLetterChance() const { std::map<char, int> letterCounts; // initialise all counts to 0 for (char letter = 'a'; letter <= 'z'; ++letter) { letterCounts.insert_or_assign(letter, 0); } // Count every word for number of letter occurrences for (const auto& word : _data) { countLetterOccurrence(word, letterCounts); } // Collect results and sort with largest at start. std::vector<std::pair<char, int>> orderedResult; for (auto& it : letterCounts) { orderedResult.push_back(it); } auto cmp = [](const std::pair<char, int>& a, const std::pair<char, int>& b) { return a.second > b.second; }; std::sort(orderedResult.begin(), orderedResult.end(), cmp); // Print all out that are non-zero. for (const auto& letterFreq : orderedResult) { if (letterFreq.second > 0) { std::cout << letterFreq.first << ": " << letterFreq.second << " "; } } std::cout << std::endl; // If there is at least one rule, show the up to 5 most common unused letters. if (!_rules.empty()) { std::cout << "Most unused common: "; int outputCount = 0; for (const auto& letterFreq : orderedResult) { if (letterFreq.second > 0 && _rules.at(_rules.size()-1).find(letterFreq.first) == std::string::npos) { std::cout << letterFreq.first << " "; ++outputCount; } if (outputCount == 5) break; } if (outputCount == 0) { std::cout << "none found..."; } std::cout << std::endl; } } void Database::showHelp() const { std::cout << "#letter for any letter that should exist at least once, but not there." << std::endl << "*letter for any letter that should exist at exactly that position." << std::endl << "letter by itself for any letter that should exist nowhere." << std::endl << "_letter is a wild card you can use to shortcut and ignore that position." << std::endl << "Example: #YE*AST would mean at least one Y not at the first letter, " << std::endl << "nowhere any E, S, or T, and A should appear at the middle." << std::endl; } void Database::showRules() const { std::cout << "Rules entered so far:" << std::endl; for (const auto& rule : _rules) { std::cout << rule << std::endl; } std::cout << std::endl; } bool Database::isRuleValid(const std::string & rule) const { int letterCount = 0; for (int i = 0; i < rule.length(); i++) { // Skip one forward if special character if (rule.at(i) == '#' || rule.at(i) == '*') { i++; } if ((rule.at(i) >= 'a' && rule.at(i) <= 'z') || rule.at(i) == '_') { letterCount++; } else { // This means the character is either an invalid double special character // or some irrelevant other character. return false; } } return letterCount == 5; } bool Database::wordFitsRule(const std::string & rule, const std::string & word) const { for (int i = 0, pos = 0; i < rule.length(); ++i, ++pos) { // Wild card to ignore this position. if (rule.at(i) == '_') { continue; } // Exists at position with exact match else if (rule.at(i) == '*') { i++; if (rule.at(i) != word.at(pos)) { return false; } } // One or more in string but not at pos else if (rule.at(i) == '#') { i++; bool foundOne = false; for (int j = 0; j < word.length(); j++) { if (word.at(j) == rule.at(i) && j != pos) { foundOne = true; } } if (!foundOne) { return false; } } // Should not appear anywhere in the word else { for (int j = 0; j < word.length(); j++) { if (word.at(j) == rule.at(i)) { return false; } } } } return true; } void Database::countLetterOccurrence(const std::string & word, std::map<char, int>& result) const { for (int i = 0; i < word.size(); i++) { if (word.find_first_of(word.at(i)) == i) { result.insert_or_assign(word.at(i), result.at(word.at(i)) + 1); } } }
24.449275
105
0.60818
Squirrelbear
d962d332e62b4c66c27eba4760ff582262a1156f
2,927
hpp
C++
src/dbg/stream_cont.hpp
yxtj/Daiger
d98edea4618223f6a8f89482c88be783dfaf9983
[ "MIT" ]
null
null
null
src/dbg/stream_cont.hpp
yxtj/Daiger
d98edea4618223f6a8f89482c88be783dfaf9983
[ "MIT" ]
null
null
null
src/dbg/stream_cont.hpp
yxtj/Daiger
d98edea4618223f6a8f89482c88be783dfaf9983
[ "MIT" ]
null
null
null
#pragma once #include <ostream> #include <utility> #include <vector> #include <initializer_list> //#include <array> #include <map> #include <list> #include <deque> #include <set> #include <unordered_map> #include <unordered_set> //#include "../my_type_traits/is_associated_container.h" template <class T1, class T2> inline std::ostream& operator<<(std::ostream& os, const std::pair<T1, T2>& p) { return os << "(" << p.first << "," << p.second << ")"; } template <class T> inline std::ostream& operator<<(std::ostream& os, const std::vector<T>& cont) { os << "["; for(auto& t : cont) os << t << " "; return os << "]"; } template <class T> inline std::ostream& operator<<(std::ostream& os, const std::initializer_list<T>& cont) { os << "["; for(auto& t : cont) os << t << " "; return os << "]"; } template <class T> inline std::ostream& operator<<(std::ostream& os, const std::list<T>& cont) { os << "["; for(auto& t : cont) os << t << " "; return os << "]"; } template <class T> inline std::ostream& operator<<(std::ostream& os, const std::deque<T>& cont) { os << "["; for(auto& t : cont) os << t << " "; return os << "]"; } //template <class T> //inline std::ostream& operator<<(std::ostream& os, const std::array<T>& cont) { // os << "["; // for(auto& t : cont) // os << t << " "; // return os << "]"; //} template <class T> inline std::ostream& operator<<(std::ostream& os, const std::set<T>& cont) { os << "{"; for(auto& t : cont) os << t << " "; return os << "}"; } template <class T> inline std::ostream& operator<<(std::ostream& os, const std::multiset<T>& cont) { os << "{"; for(auto& t : cont) os << t << " "; return os << "}"; } template <class T> inline std::ostream& operator<<(std::ostream& os, const std::unordered_set<T>& cont) { os << "{"; for(auto& t : cont) os << t << " "; return os << "}"; } template <class T> inline std::ostream& operator<<(std::ostream& os, const std::unordered_multiset<T>& cont) { os << "{"; for(auto& t : cont) os << t << " "; return os << "}"; } template <class K, class V> inline std::ostream& operator<<(std::ostream& os, const std::map<K, V>& cont) { os << "{ "; for(auto&t : cont) os << "(" << t.first << ":" << t.second << ") "; return os << "}"; } template <class K, class V> inline std::ostream& operator<<(std::ostream& os, const std::multimap<K, V>& cont) { os << "{ "; for(auto&t : cont) os << "(" << t.first << ":" << t.second << ") "; return os << "}"; } template <class K, class V> inline std::ostream& operator<<(std::ostream& os, const std::unordered_map<K, V>& cont) { os << "{ "; for(auto&t : cont) os << "(" << t.first << ":" << t.second << ") "; return os << "}"; } template <class K, class V> inline std::ostream& operator<<(std::ostream& os, const std::unordered_multimap<K, V>& cont) { os << "{ "; for(auto&t : cont) os << "(" << t.first << ":" << t.second << ") "; return os << "}"; }
23.796748
94
0.563717
yxtj
d9661b5f5ede8062fd17df72765419140b3ebbc0
2,202
cpp
C++
src/cpp/game_logic/player.cpp
Tomius/pyromaze
7100f0ef6972b62829b2ad2dd7e7e88af697a5c2
[ "MIT" ]
null
null
null
src/cpp/game_logic/player.cpp
Tomius/pyromaze
7100f0ef6972b62829b2ad2dd7e7e88af697a5c2
[ "MIT" ]
null
null
null
src/cpp/game_logic/player.cpp
Tomius/pyromaze
7100f0ef6972b62829b2ad2dd7e7e88af697a5c2
[ "MIT" ]
null
null
null
// Copyright (c) Tamas Csala #include <lodepng.h> #include <Silice3D/core/scene.hpp> #include <Silice3D/core/game_engine.hpp> #include <Silice3D/debug/debug_texture.hpp> #include "game_logic/player.hpp" #include "game_logic/dynamite.hpp" #include "./main_scene.hpp" void ShowYouDiedScreen(Silice3D::ShaderManager* shader_manager) { unsigned width, height; std::vector<unsigned char> data; unsigned error = lodepng::decode(data, width, height, "src/resource/died.png", LCT_RGBA, 8); if (error) { std::cerr << "Image decoder error " << error << ": " << lodepng_error_text(error) << std::endl; throw std::runtime_error("Image decoder error"); } gl::Texture2D texture; gl::Bind(texture); texture.upload(gl::kSrgb8Alpha8, width, height, gl::kRgba, gl::kUnsignedByte, data.data()); texture.minFilter(gl::kLinear); texture.magFilter(gl::kLinear); gl::Unbind(texture); Silice3D::DebugTexture{shader_manager}.Render(texture); } Player::Player(Silice3D::GameObject* parent) : Silice3D::GameObject(parent) { } void Player::KeyAction(int key, int scancode, int action, int mods) { if (action == GLFW_PRESS) { Silice3D::Transform dynamite_trafo; if (key == GLFW_KEY_SPACE) { glm::dvec3 pos = GetTransform().GetPos(); pos += 3.0 * GetTransform().GetForward(); dynamite_trafo.SetPos({pos.x, 0, pos.z}); GetScene()->AddComponent<Dynamite>(dynamite_trafo, 2.5 + 1.0*Silice3D::Math::Rand01()); } else if (key == GLFW_KEY_F1) { for (int i = 0; i < 4; ++i) { dynamite_trafo.SetPos({Silice3D::Math::Rand01()*256-128, 0, Silice3D::Math::Rand01()*256-128}); GetScene()->AddComponent<Dynamite>(dynamite_trafo, 2.5 + 1.0*Silice3D::Math::Rand01()); } } } } void Player::ReactToExplosion(const glm::dvec3& exp_position, double exp_radius) { glm::dvec3 pos = GetTransform().GetPos(); pos.y = 0; if (length(pos - exp_position) < 1.2*exp_radius) { ShowYouDiedScreen(GetScene()->GetShaderManager()); glfwSwapBuffers(GetScene()->GetWindow()); Silice3D::GameEngine* engine = GetScene()->GetEngine(); engine->LoadScene(std::unique_ptr<Silice3D::Scene>{new MainScene{engine}}); } }
34.40625
103
0.676658
Tomius
d96732645902f8c2cbaa0abc10efe0b3f3bc1ebb
15,394
cpp
C++
ThunderFocus-firmware/src/focuser/AccelStepper.cpp
marcocipriani01/OpenFocuser
48192db1e010e87de53f55385457cf5c32e779d4
[ "Apache-2.0" ]
1
2019-11-11T15:40:00.000Z
2019-11-11T15:40:00.000Z
ThunderFocus-firmware/src/focuser/AccelStepper.cpp
marcocipriani01/OpenFocuser
48192db1e010e87de53f55385457cf5c32e779d4
[ "Apache-2.0" ]
null
null
null
ThunderFocus-firmware/src/focuser/AccelStepper.cpp
marcocipriani01/OpenFocuser
48192db1e010e87de53f55385457cf5c32e779d4
[ "Apache-2.0" ]
null
null
null
#include "AccelStepper.h" #if FOCUSER_DRIVER != DISABLED #pragma region Constructor #if ACCELSTEPPER_UNIPOLAR_STEPPER == true AccelStepper::AccelStepper(uint8_t in1, uint8_t in2, uint8_t in3, uint8_t in4) { _currentPos = 0; _targetPos = 0; _speed = 0.0; _maxSpeed = 1.0; _acceleration = 1.0; _stepInterval = 0; _lastStepTime = 0; _in1 = in1; pinMode(_in1, OUTPUT); _in2 = in2; pinMode(_in2, OUTPUT); _in3 = in3; pinMode(_in3, OUTPUT); _in4 = in4; pinMode(_in4, OUTPUT); #if ACCELSTEPPER_BACKLASH_SUPPORT == true _direction = DIRECTION_NONE; _currentBacklash = 0; _targetBacklash = 0; #else _direction = DIRECTION_CW; #endif #if ACCELSTEPPER_INVERT_DIR_SUPPORT == true _invertDir = false; #endif _n = 0; _cn = 0.0; _cmin = 1.0; _c0 = 0.676 * sqrt(2.0) * 1000000.0; #if ACCELSTEPPER_ENABLE_PIN_FEATURE == true _enabled = true; #if ACCELSTEPPER_AUTO_POWER == true _autoPowerTimeout = 0; #endif #endif #if ACCELSTEPPER_STEPS_SCALING == true _stepsScaling = 1; #endif } #else AccelStepper::AccelStepper(uint8_t stepPin, uint8_t dirPin) { _currentPos = 0; _targetPos = 0; _speed = 0.0; _maxSpeed = 1.0; _acceleration = 1.0; _stepInterval = 0; _lastStepTime = 0; _stepPin = stepPin; pinMode(_stepPin, OUTPUT); _dirPin = dirPin; pinMode(_dirPin, OUTPUT); #if ACCELSTEPPER_BACKLASH_SUPPORT == true _direction = DIRECTION_NONE; _currentBacklash = 0; _targetBacklash = 0; #else _direction = DIRECTION_CW; #endif #if ACCELSTEPPER_INVERT_DIR_SUPPORT == true _invertDir = false; #endif _n = 0; _cn = 0.0; _cmin = 1.0; _c0 = 0.676 * sqrt(2.0) * 1000000.0; #if ACCELSTEPPER_ENABLE_PIN_FEATURE == true _enablePin = -1; _enabled = true; #if ACCELSTEPPER_AUTO_POWER == true _autoPowerTimeout = 0; #endif #endif #if ACCELSTEPPER_STEPS_SCALING == true _stepsScaling = 1; #endif } #endif #pragma endregion Constructor #pragma region Movement void AccelStepper::stop() { if (_speed != 0.0) { long stepsToStop = (long)((_speed * _speed) / (2.0 * _acceleration)) + 1; // Equation 16 (+integer rounding) long absolute = _currentPos + ((_speed > 0) ? stepsToStop : (-stepsToStop)); if (_targetPos != absolute) { _targetPos = absolute; computeNewSpeed(); } } } void AccelStepper::move(long relative) { #if ACCELSTEPPER_ENABLE_PIN_FEATURE == true #if ACCELSTEPPER_AUTO_POWER == true #if ACCELSTEPPER_UNIPOLAR_STEPPER == false if (_enablePin != -1) digitalWrite(_enablePin, LOW); #endif _enabled = true; #else if (!_enabled) return; #endif #endif #if ACCELSTEPPER_STEPS_SCALING == true relative *= _stepsScaling; #endif long absolute = _currentPos + relative; if (_targetPos != absolute) { _targetPos = absolute; computeNewSpeed(); } } void AccelStepper::moveTo(long absolute) { #if ACCELSTEPPER_ENABLE_PIN_FEATURE == true #if ACCELSTEPPER_AUTO_POWER == true #if ACCELSTEPPER_UNIPOLAR_STEPPER == false if (_enablePin != -1) digitalWrite(_enablePin, LOW); #endif _enabled = true; #else if (!_enabled) return; #endif #endif #if ACCELSTEPPER_STEPS_SCALING == true absolute *= _stepsScaling; #endif if (_targetPos != absolute) { _targetPos = absolute; computeNewSpeed(); } } #pragma endregion Movement #pragma region Runners boolean AccelStepper::run() { if (runSpeed()) computeNewSpeed(); return (_speed != 0.0) || (distanceToGo0() != 0); } boolean AccelStepper::runSpeed() { #if ACCELSTEPPER_ENABLE_PIN_FEATURE == true #if ACCELSTEPPER_AUTO_POWER == true unsigned long time = micros(); #else if (!_enabled) return; #endif #endif #if ACCELSTEPPER_BACKLASH_SUPPORT == true if ((_stepInterval == 0) || (_direction == DIRECTION_NONE)) { #else if (_stepInterval == 0) { #endif #if ACCELSTEPPER_AUTO_POWER == true if (_enabled && (_autoPowerTimeout != 0) && (((unsigned long)(time - _lastStepTime)) >= (_autoPowerTimeout * 1000L))) { _enabled = false; #if ACCELSTEPPER_UNIPOLAR_STEPPER == true digitalWrite(_in1, LOW); digitalWrite(_in2, LOW); digitalWrite(_in3, LOW); digitalWrite(_in4, LOW); #else if (_enablePin != -1) digitalWrite(_enablePin, HIGH); #endif } #endif return false; } #if ACCELSTEPPER_AUTO_POWER == true if (!_enabled) { _enabled = true; #if ACCELSTEPPER_UNIPOLAR_STEPPER == false if (_enablePin != -1) digitalWrite(_enablePin, LOW); #endif } #else unsigned long time = micros(); #endif if (((unsigned long)(time - _lastStepTime)) >= _stepInterval) { boolean dir = (_direction == DIRECTION_CCW); #if ACCELSTEPPER_BACKLASH_SUPPORT == true if ((_targetBacklash - _currentBacklash) == 0) _currentPos += (dir ? (-1) : 1); else _currentBacklash += (dir ? (-1) : 1); #else _currentPos += (dir ? (-1) : 1); #endif #if ACCELSTEPPER_UNIPOLAR_STEPPER == false #if ACCELSTEPPER_INVERT_DIR_SUPPORT == true if (_invertDir) dir = !dir; #endif digitalWrite(_dirPin, dir); digitalWrite(_stepPin, HIGH); #if ACCELSTEPPER_MIN_PULSE_WIDTH > 0 delayMicroseconds(ACCELSTEPPER_MIN_PULSE_WIDTH); #endif digitalWrite(_stepPin, LOW); #else #if ACCELSTEPPER_UNIPOLAR_HALF_STEPPING == true int step = (_currentPos + _currentBacklash) & 0x7; if (_invertDir) step = 7 - step; switch (step) { case 0: // 1000 setOutputPins(0b0001); break; case 1: // 1010 setOutputPins(0b0101); break; case 2: // 0010 setOutputPins(0b0100); break; case 3: // 0110 setOutputPins(0b0110); break; case 4: // 0100 setOutputPins(0b0010); break; case 5: //0101 setOutputPins(0b1010); break; case 6: // 0001 setOutputPins(0b1000); break; case 7: //1001 setOutputPins(0b1001); break; } #else int step = (_currentPos + _currentBacklash) & 0x3; if (_invertDir) step = 3 - step; switch ((_currentPos + _currentBacklash) & 0x3) { case 0: // 1010 setOutputPins(0b0101); break; case 1: // 0110 setOutputPins(0b0110); break; case 2: //0101 setOutputPins(0b1010); break; case 3: //1001 setOutputPins(0b1001); break; } #endif #endif _lastStepTime = time; return true; } return false; } void AccelStepper::runToPosition() { while (run()) ; } boolean AccelStepper::runSpeedToPosition() { if (_targetPos == _currentPos) return false; if (_targetPos > _currentPos) _direction = DIRECTION_CW; else _direction = DIRECTION_CCW; return runSpeed(); } void AccelStepper::runToNewPosition(long position) { moveTo(position); runToPosition(); } #pragma endregion Runners #pragma region Properties double AccelStepper::getMaxSpeed() { #if ACCELSTEPPER_STEPS_SCALING == true return _maxSpeed / _stepsScaling; #else return _maxSpeed; #endif } void AccelStepper::setMaxSpeed(double speed) { if (speed < 0.0) speed = -speed; #if ACCELSTEPPER_STEPS_SCALING == true speed *= _stepsScaling; #endif if (_maxSpeed != speed) { _maxSpeed = speed; _cmin = 1000000.0 / speed; if (_n > 0) { _n = (long)((_speed * _speed) / (2.0 * _acceleration)); computeNewSpeed(); } } } void AccelStepper::setAcceleration(double acceleration) { if (acceleration == 0.0) return; if (acceleration < 0.0) acceleration = -acceleration; #if ACCELSTEPPER_STEPS_SCALING == true acceleration *= _stepsScaling; #endif if (_acceleration != acceleration) { _n = _n * (_acceleration / acceleration); _c0 = 0.676 * sqrt(2.0 / acceleration) * 1000000.0; _acceleration = acceleration; computeNewSpeed(); } } void AccelStepper::setSpeed(double speed) { if (speed == _speed) return; #if ACCELSTEPPER_STEPS_SCALING == true speed *= _stepsScaling; #endif speed = constrain(speed, -_maxSpeed, _maxSpeed); if (speed == 0.0) _stepInterval = 0; else { _stepInterval = fabs(1000000.0 / speed); _direction = (speed > 0.0) ? DIRECTION_CW : DIRECTION_CCW; } _speed = speed; } double AccelStepper::getSpeed() { #if ACCELSTEPPER_STEPS_SCALING == true return _speed / _stepsScaling; #else return _speed; #endif } #pragma endregion Properties #pragma region Position long AccelStepper::distanceToGo() { #if ACCELSTEPPER_BACKLASH_SUPPORT == true #if ACCELSTEPPER_STEPS_SCALING == true double steps = (_targetPos - _currentPos + _targetBacklash - _currentBacklash) / ((double) _stepsScaling); return (steps > 0) ? ceil(steps) : floor(steps); #else return _targetPos - _currentPos + _targetBacklash - _currentBacklash; #endif #else #if ACCELSTEPPER_STEPS_SCALING == true double steps = (_targetPos - _currentPos) / ((double) _stepsScaling); return (steps > 0) ? ceil(steps) : floor(steps); #else return _targetPos - _currentPos; #endif #endif } long AccelStepper::getTarget() { #if ACCELSTEPPER_STEPS_SCALING == true return _targetPos / _stepsScaling; #else return _targetPos; #endif } long AccelStepper::getPosition() { #if ACCELSTEPPER_STEPS_SCALING == true return _currentPos / _stepsScaling; #else return _currentPos; #endif } void AccelStepper::setPosition(long position) { if (distanceToGo0() != 0) return; #if ACCELSTEPPER_STEPS_SCALING == true position *= _stepsScaling; #endif _targetPos = _currentPos = position; _targetBacklash = 0; _currentBacklash = 0; _stepInterval = 0; _speed = 0.0; _n = 0; } #pragma endregion Position #pragma region Backlash #if ACCELSTEPPER_BACKLASH_SUPPORT == true void AccelStepper::setBacklash(long backlash) { #if ACCELSTEPPER_STEPS_SCALING == true backlash *= _stepsScaling; #endif _backlash = backlash; _targetBacklash = 0; _currentBacklash = 0; } long AccelStepper::getBacklash() { #if ACCELSTEPPER_STEPS_SCALING == true return _backlash / _stepsScaling; #else return _backlash; #endif } #endif #pragma endregion Backlash #pragma region Direction #if ACCELSTEPPER_INVERT_DIR_SUPPORT == true boolean AccelStepper::isDirectionInverted() { return _invertDir; } void AccelStepper::setDirectionInverted(boolean inverted) { _invertDir = inverted; } #endif #pragma endregion Direction #pragma region Power #if ACCELSTEPPER_ENABLE_PIN_FEATURE == true #if ACCELSTEPPER_UNIPOLAR_STEPPER == false void AccelStepper::setEnablePin(uint8_t enPin, boolean enabled) { _enablePin = enPin; if (_enablePin != -1) { pinMode(_enablePin, OUTPUT); if (distanceToGo0() == 0) { _enabled = enabled; digitalWrite(_enablePin, !_enabled); } } } #endif void AccelStepper::setEnabled(boolean enabled) { if ((distanceToGo0() != 0) && (_enabled != enabled)) { #if ACCELSTEPPER_UNIPOLAR_STEPPER == true if (!enabled) { digitalWrite(_in1, LOW); digitalWrite(_in2, LOW); digitalWrite(_in3, LOW); digitalWrite(_in4, LOW); } #else if (_enablePin != -1) digitalWrite(_enablePin, _enabled); #endif _enabled = enabled; } } boolean AccelStepper::isEnabled() { return _enabled; } #if ACCELSTEPPER_AUTO_POWER == true void AccelStepper::setAutoPowerTimeout(unsigned long timeout) { _autoPowerTimeout = timeout; } unsigned long AccelStepper::getAutoPowerTimeout() { return _autoPowerTimeout; } #endif #endif #pragma endregion Power #pragma region StepsScaling #if ACCELSTEPPER_STEPS_SCALING == true void AccelStepper::setStepsScaling(long stepsScaling) { if (stepsScaling > 0) _stepsScaling = stepsScaling; } long AccelStepper::getStepsScaling() { return _stepsScaling; } #endif #pragma endregion StepsScaling #pragma region ProtectedMethods void AccelStepper::computeNewSpeed() { long distanceTo = distanceToGo0(); long stepsToStop = (long)((_speed * _speed) / (2.0 * _acceleration)); if (distanceTo == 0 && stepsToStop <= 1) { _stepInterval = 0; _speed = 0.0; _n = 0; return; } if (distanceTo > 0) { if (_n > 0) { // Currently accelerating, need to decel now? Or maybe going the wrong way? if ((stepsToStop >= distanceTo) || _direction == DIRECTION_CCW) _n = -stepsToStop; // Start deceleration } else if (_n < 0) { // Currently decelerating, need to accel again? if ((stepsToStop < distanceTo) && _direction == DIRECTION_CW) _n = -_n; // Start accceleration } } else if (distanceTo < 0) { // We are clockwise from the target // Need to go anticlockwise from here, maybe decelerate if (_n > 0) { // Currently accelerating, need to decel now? Or maybe going the wrong way? if ((stepsToStop >= -distanceTo) || _direction == DIRECTION_CW) _n = -stepsToStop; // Start deceleration } else if (_n < 0) { // Currently decelerating, need to accel again? if ((stepsToStop < -distanceTo) && _direction == DIRECTION_CCW) _n = -_n; // Start accceleration } } // Need to accelerate or decelerate if (_n == 0) { // First step from stopped _cn = _c0; #if ACCELSTEPPER_BACKLASH_SUPPORT == true applyBacklashCompensation((distanceTo > 0) ? DIRECTION_CW : DIRECTION_CCW); #else _direction = (distanceTo > 0) ? DIRECTION_CW : DIRECTION_CCW; #endif } else { // Subsequent step. Works for accel (n is +_ve) and decel (n is -ve). _cn = _cn - ((2.0 * _cn) / ((4.0 * _n) + 1)); // Equation 13 _cn = max(_cn, _cmin); } _n++; _stepInterval = _cn; _speed = 1000000.0 / _cn; if (_direction == DIRECTION_CCW) _speed = -_speed; } #if ACCELSTEPPER_BACKLASH_SUPPORT == true void AccelStepper::applyBacklashCompensation(Direction newDir) { if (_backlash == 0) { _direction = newDir; return; } if ((_direction != DIRECTION_NONE) && (newDir != _direction)) { if (newDir == DIRECTION_CW) { _targetBacklash += _backlash; } else if (newDir == DIRECTION_CCW) { _targetBacklash -= _backlash; } } _direction = newDir; } #endif #pragma endregion ProtectedMethods #pragma region PrivateMethods long AccelStepper::distanceToGo0() { #if ACCELSTEPPER_BACKLASH_SUPPORT == true return _targetPos - _currentPos + _targetBacklash - _currentBacklash; #else return _targetPos - _currentPos; #endif } #if ACCELSTEPPER_UNIPOLAR_STEPPER == true void AccelStepper::setOutputPins(uint8_t mask) { digitalWrite(_in1, (mask & 0b0001) != 0); digitalWrite(_in2, (mask & 0b0010) != 0); digitalWrite(_in3, (mask & 0b0100) != 0); digitalWrite(_in4, (mask & 0b1000) != 0); } #endif #pragma endregion PrivateMethods #endif
27.149912
127
0.63986
marcocipriani01
d968102ef2460c0da9aec5537bef83992504ca7b
4,524
cpp
C++
src/IECore/ExclusionFrameList.cpp
gcodebackups/cortex-vfx
72fa6c6eb3327fce4faf01361c8fcc2e1e892672
[ "BSD-3-Clause" ]
5
2016-07-26T06:09:28.000Z
2022-03-07T03:58:51.000Z
src/IECore/ExclusionFrameList.cpp
turbosun/cortex
4bdc01a692652cd562f3bfa85f3dae99d07c0b15
[ "BSD-3-Clause" ]
null
null
null
src/IECore/ExclusionFrameList.cpp
turbosun/cortex
4bdc01a692652cd562f3bfa85f3dae99d07c0b15
[ "BSD-3-Clause" ]
3
2015-03-25T18:45:24.000Z
2020-02-15T15:37:18.000Z
////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2009, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Image Engine Design nor the names of any // other contributors to this software 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 <algorithm> #include <set> #include "boost/tokenizer.hpp" #include "IECore/Exception.h" #include "IECore/ExclusionFrameList.h" using namespace IECore; IE_CORE_DEFINERUNTIMETYPED( ExclusionFrameList ); FrameList::Parser< ExclusionFrameList > ExclusionFrameList::g_parserRegistrar; ExclusionFrameList::ExclusionFrameList( FrameListPtr frameList, FrameListPtr exclusionFrameList ) : m_frameList( frameList ), m_exclusionFrameList( exclusionFrameList ) { } ExclusionFrameList::~ExclusionFrameList() { } void ExclusionFrameList::setFrameList( FrameListPtr frameList ) { m_frameList = frameList; } FrameListPtr ExclusionFrameList::getFrameList() { return m_frameList; } void ExclusionFrameList::setExclusionFrameList( FrameListPtr exclusionFrameList ) { m_exclusionFrameList = exclusionFrameList; } FrameListPtr ExclusionFrameList::getExclusionFrameList() { return m_exclusionFrameList; } void ExclusionFrameList::asList( std::vector<Frame> &frames ) const { frames.clear(); std::vector<Frame> l; m_frameList->asList( l ); std::vector<Frame> e; m_exclusionFrameList->asList( e ); std::set<Frame> lSet( l.begin(), l.end() ); std::set<Frame> eSet( e.begin(), e.end() ); set_difference( lSet.begin(), lSet.end(), eSet.begin(), eSet.end(), std::back_inserter( frames ) ); assert( frames.size() <= l.size() ); } std::string ExclusionFrameList::asString() const { std::string s1 = m_frameList->asString(); std::string s2 = m_exclusionFrameList->asString(); if ( s1.find_first_of( ',' ) != std::string::npos ) { s1 = "(" + s1 + ")"; } if ( s2.find_first_of( ',' ) != std::string::npos ) { s2 = "(" + s2 + ")"; } return s1 + "!" + s2; } bool ExclusionFrameList::isEqualTo( ConstFrameListPtr other ) const { if ( !FrameList::isEqualTo( other ) ) { return false; } ConstExclusionFrameListPtr otherF = assertedStaticCast< const ExclusionFrameList >( other ); return m_frameList->isEqualTo( otherF->m_frameList ) && m_exclusionFrameList->isEqualTo( otherF->m_exclusionFrameList ) ; } FrameListPtr ExclusionFrameList::copy() const { return new ExclusionFrameList( m_frameList, m_exclusionFrameList ); } FrameListPtr ExclusionFrameList::parse( const std::string &frameList ) { boost::tokenizer<boost::char_separator<char> > t( frameList, boost::char_separator<char>( "!" ) ); std::vector<std::string> tokens; std::copy( t.begin(), t.end(), std::back_inserter( tokens ) ); if ( tokens.size() == 2 ) { try { FrameListPtr f1 = FrameList::parse( tokens[0] ); FrameListPtr f2 = FrameList::parse( tokens[1] ); if ( f1 && f2 ) { return new ExclusionFrameList( f1, f2 ); } } catch ( Exception & ) { return 0; } } return 0; }
29.187097
168
0.696065
gcodebackups
d96d715f7c71b42cec7744b065b3934ed2215a4d
380
cpp
C++
Dataset/Leetcode/train/35/229.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/train/35/229.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/train/35/229.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
class Solution { public: int XXX(vector<int>& nums, int target) { if(target - nums.back() > 0) return nums.size(); if(target - nums[0] <= 0) return 0; for(int i = 0; i < nums.size() -1; i++) { if((target-nums[i])*(nums[i+1]-target) == 0) return i; else if( (target > nums[i] && nums[i+1] > target) || (nums[i+1] == target)) return i+1; } } };
22.352941
77
0.526316
kkcookies99
d96db87e22f59ed963625bee6b3581e9e22025a1
4,098
cpp
C++
src/mc.cpp
byrnedj/lsm-sim
ec45d2eb784357ee4c917cb3d4e3a10430886dae
[ "ISC" ]
13
2017-02-05T09:41:57.000Z
2022-02-13T14:38:28.000Z
src/mc.cpp
byrnedj/lsm-sim
ec45d2eb784357ee4c917cb3d4e3a10430886dae
[ "ISC" ]
13
2016-03-17T17:43:58.000Z
2017-01-11T09:21:45.000Z
src/mc.cpp
utah-scs/lsm-sim
730e339cb4d5a719407643c8bb45a6c3dde1bfb8
[ "0BSD" ]
7
2017-01-03T18:11:08.000Z
2021-03-09T12:30:12.000Z
#include <iostream> #include <cinttypes> #include <cstring> #include <utility> #include <stdio.h> #include "mc.h" static const int MAX_NUMBER_OF_SLAB_CLASSES = 64; static const size_t POWER_SMALLEST = 1; static const size_t POWER_LARGEST = 256; static const size_t CHUNK_ALIGN_BYTES = 8; static const size_t chunk_size = 48; static const size_t item_size_max = 1024 * 1024; typedef uint32_t rel_time_t; typedef struct _stritem { /* Protected by LRU locks */ struct _stritem *next; struct _stritem *prev; /* Rest are protected by an item lock */ struct _stritem *h_next; /* hash chain next */ rel_time_t time; /* least recent access */ rel_time_t exptime; /* expire time */ int nbytes; /* size of data */ unsigned short refcount; uint8_t nsuffix; /* length of flags-and-length string */ uint8_t it_flags; /* ITEM_* above */ uint8_t slabs_clsid;/* which slab class we're in */ uint8_t nkey; /* key length, w/terminating null and padding */ /* this odd type prevents type-punning issues when we do * the little shuffle to save space when not using CAS. */ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wpedantic" union { uint64_t cas; char end; } data[]; #pragma GCC diagnostic pop /* if it_flags & ITEM_CAS we have 8 bytes CAS */ /* then null-terminated key */ /* then " flags length\r\n" (no terminating null) */ /* then data with terminating \r\n (no terminating null; it's binary!) */ } item; typedef struct { unsigned int size; /* sizes of items */ unsigned int perslab; /* how many items per slab */ void *slots; /* list of item ptrs */ unsigned int sl_curr; /* total free items in list */ unsigned int slabs; /* how many slabs were allocated for this class */ void **slab_list; /* array of slab pointers */ unsigned int list_size; /* size of prev array */ size_t requested; /* The number of requested bytes */ } slabclass_t; static slabclass_t slabclass[MAX_NUMBER_OF_SLAB_CLASSES]; static int power_largest; /** * Determines the chunk sizes and initializes the slab class descriptors * accordingly. * * * NOTE: Modified to return the max number of slabs * (for sizing arrays elsewhere). */ uint16_t slabs_init(const double factor) { int i = POWER_SMALLEST - 1; // stutsman: original memcached code boost class size by // at least sizeof(item) but since our simulator doesn't // account for metadata this probably doesn't make sense? unsigned int size = sizeof(item) + chunk_size; //unsigned int size = chunk_size; memset(slabclass, 0, sizeof(slabclass)); while (++i < MAX_NUMBER_OF_SLAB_CLASSES-1 && size <= item_size_max / factor) { /* Make sure items are always n-byte aligned */ if (size % CHUNK_ALIGN_BYTES) size += CHUNK_ALIGN_BYTES - (size % CHUNK_ALIGN_BYTES); std::cout << "slab class " << i << " size " << size << std::endl; slabclass[i].size = size; slabclass[i].perslab = item_size_max / slabclass[i].size; size *= factor; } power_largest = i; slabclass[power_largest].size = item_size_max; slabclass[power_largest].perslab = 1; std::cout << "slab class " << i << " size " << item_size_max << std::endl; return power_largest; } /* * Figures out which slab class (chunk size) is required to store an item of * a given size. * * Given object size, return id to use when allocating/freeing memory for object * 0 means error: can't store such a large object * * NOTE: modified to return class id and class_size. */ std::pair<uint32_t, uint32_t> slabs_clsid(const size_t size) { int res = POWER_SMALLEST; if (size == 0) return {0,0}; while (size > slabclass[res].size) { ++res; if (res == power_largest) /* won't fit in the biggest slab */ return {0,0}; } return {slabclass[res].size, res}; }
32.267717
80
0.641532
byrnedj
d9703f9c892af53cc55607571e8afe489bccd9a1
5,780
cpp
C++
src/TCPConnectionServer.cpp
sempr-tk/sempr-gui
ba96dca6945122a157f61fec9e41f4aa6060e3b2
[ "BSD-3-Clause" ]
null
null
null
src/TCPConnectionServer.cpp
sempr-tk/sempr-gui
ba96dca6945122a157f61fec9e41f4aa6060e3b2
[ "BSD-3-Clause" ]
null
null
null
src/TCPConnectionServer.cpp
sempr-tk/sempr-gui
ba96dca6945122a157f61fec9e41f4aa6060e3b2
[ "BSD-3-Clause" ]
null
null
null
#include "TCPConnectionServer.hpp" #include "ECDataZMQ.hpp" #include "LogDataZMQ.hpp" #include "TCPConnectionRequest.hpp" #include <cereal/archives/json.hpp> #include <iostream> namespace sempr { namespace gui { TCPConnectionServer::TCPConnectionServer( DirectConnection::Ptr con, const std::string& publishEndpoint, const std::string& requestEndpoint) : updatePublisher_(context_, zmqpp::socket_type::publish), replySocket_(context_, zmqpp::socket_type::reply), semprConnection_(con), handlingRequests_(false) { updatePublisher_.bind(publishEndpoint); replySocket_.bind(requestEndpoint); } void TCPConnectionServer::updateCallback( AbstractInterface::callback_t::first_argument_type data, AbstractInterface::callback_t::second_argument_type action) { // construct the message -- just all the data entries in the ECData struct, // plus the action. zmqpp::message msg, topic; msg << UpdateType::EntityComponent << data << action; topic << "data"; // and send it to all subscribers updatePublisher_.send("data", zmqpp::socket_t::send_more); updatePublisher_.send(msg); } void TCPConnectionServer::tripleUpdateCallback( AbstractInterface::triple_callback_t::first_argument_type value, AbstractInterface::triple_callback_t::second_argument_type action) { std::cout << "TCPConnectionServer::tripleUpdateCallback" << std::endl; zmqpp::message msg; std::stringstream ss; { cereal::JSONOutputArchive ar(ss); ar(value); } msg << UpdateType::Triple << ss.str() << action; updatePublisher_.send("data", zmqpp::socket_t::send_more); updatePublisher_.send(msg); } void TCPConnectionServer::loggingCallback( AbstractInterface::logging_callback_t::argument_type log) { zmqpp::message msg; msg << log; updatePublisher_.send("logging", zmqpp::socket_t::send_more); updatePublisher_.send(msg); } void TCPConnectionServer::start() { // connect the update callback semprConnection_->setUpdateCallback( std::bind( &TCPConnectionServer::updateCallback, this, std::placeholders::_1, std::placeholders::_2 ) ); semprConnection_->setTripleUpdateCallback( std::bind( &TCPConnectionServer::tripleUpdateCallback, this, std::placeholders::_1, std::placeholders::_2 ) ); semprConnection_->setLoggingCallback( std::bind( &TCPConnectionServer::loggingCallback, this, std::placeholders::_1 ) ); // start a thread that handles requests handlingRequests_ = true; requestHandler_ = std::thread( [this]() { while (handlingRequests_) { zmqpp::message msg; bool requestAvailable = replySocket_.receive(msg, true); if (requestAvailable) { TCPConnectionRequest request; msg >> request; TCPConnectionResponse response = handleRequest(request); zmqpp::message responseMsg; responseMsg << response; replySocket_.send(responseMsg); } else { std::this_thread::sleep_for(std::chrono::milliseconds(10)); } } } ); } std::string TCPConnectionServer::getReteNetwork() { auto graph = semprConnection_->getReteNetworkRepresentation(); std::stringstream ss; { cereal::JSONOutputArchive ar(ss); ar(graph); } return ss.str(); } TCPConnectionResponse TCPConnectionServer::handleRequest(const TCPConnectionRequest& request) { TCPConnectionResponse response; try { // just map directly to the DirectConnection we use here. switch(request.action) { case TCPConnectionRequest::LIST_ALL_EC_PAIRS: response.data = semprConnection_->listEntityComponentPairs(); break; case TCPConnectionRequest::ADD_EC_PAIR: semprConnection_->addEntityComponentPair(request.data); break; case TCPConnectionRequest::MODIFY_EC_PAIR: semprConnection_->modifyEntityComponentPair(request.data); break; case TCPConnectionRequest::REMOVE_EC_PAIR: semprConnection_->removeEntityComponentPair(request.data); break; case TCPConnectionRequest::GET_RETE_NETWORK: response.reteNetwork = getReteNetwork(); break; case TCPConnectionRequest::GET_RULES: response.rules = semprConnection_->getRulesRepresentation(); break; case TCPConnectionRequest::LIST_ALL_TRIPLES: response.triples = semprConnection_->listTriples(); break; case TCPConnectionRequest::GET_EXPLANATION_TRIPLE: { auto triple = std::make_shared<sempr::Triple>(request.toExplain); response.explanationGraph = semprConnection_->getExplanation(triple); break; } case TCPConnectionRequest::GET_EXPLANATION_ECWME: response.explanationGraph = semprConnection_->getExplanation(request.data); break; } response.success = true; } catch (std::exception& e) { // and in case of exceptions just notify the client response.success = false; response.msg = e.what(); } return response; } }}
30.421053
93
0.614706
sempr-tk
d972647f4338bfa856858b5b3e679081ebac4d84
1,359
cpp
C++
Lib/Source/Core/FocusListener.cpp
bluejamesbond/Aurora-SDK
bdd82dfaad10b068efb687690a27b65cae21155d
[ "Apache-2.0" ]
null
null
null
Lib/Source/Core/FocusListener.cpp
bluejamesbond/Aurora-SDK
bdd82dfaad10b068efb687690a27b65cae21155d
[ "Apache-2.0" ]
null
null
null
Lib/Source/Core/FocusListener.cpp
bluejamesbond/Aurora-SDK
bdd82dfaad10b068efb687690a27b65cae21155d
[ "Apache-2.0" ]
null
null
null
#include "../../../include/Core/ExtLibs.h" #include "../../../include/Core/FocusListener.h" #include "../../../Include/Core/Component.h" using namespace A2D; FocusListener::FocusListener() : FocusListener("DefaultFocusListener") {} FocusListener::FocusListener(string xString) : aName(xString), AbstractListener(A2D_LISTENER_FOCUS) {} FocusListener::~FocusListener(){} STATUS FocusListener::notify(AbstractEvent * xEvent) { return notify((FocusEvent*)xEvent); } STATUS FocusListener::notify(FocusEvent * xEvent) { int id = xEvent->getID(); if (id == FocusEvent::FOCUS_GAINED) { focusGained(xEvent); } else if (id == FocusEvent::FOCUS_LOST) { focusLost(xEvent); } else { #ifdef A2D_DE__ SYSOUT_STR("[FocusListener] ID not recognized."); #endif // A2D_DE__ } if (xEvent->isConsumed()) { return STATUS_OK; } else { return STATUS_FAIL; } } void FocusListener::focusGained(FocusEvent * xEvent) { // Fill out. #ifdef A2D_DE__ SYSOUT_STR("[FocusListener] Handling focus gained."); #endif // A2D_DE__ } void FocusListener::focusLost(FocusEvent * xEvent) { // Fill out. #ifdef A2D_DE__ SYSOUT_STR("[FocusListener] Handling focus lost."); #endif // A2D_DE__ } // For debugging only. void FocusListener::print() const { #ifdef A2D_DE__ SYSOUT_F("[FocusListener] %s", aName.c_str()); #endif // A2D_DE__ }
17.881579
54
0.695364
bluejamesbond
d974bda0d23cdc3228d59dfe7ec6a65218961464
897
cpp
C++
source/PyMaterialX/PyMaterialXGenOsl/PyOslShaderGenerator.cpp
willmuto-lucasfilm/MaterialX
589dbcb5ef292b5e5b64f30aa3fea442a8498ef6
[ "BSD-3-Clause" ]
973
2017-07-06T02:29:09.000Z
2022-02-28T18:49:10.000Z
source/PyMaterialX/PyMaterialXGenOsl/PyOslShaderGenerator.cpp
willmuto-lucasfilm/MaterialX
589dbcb5ef292b5e5b64f30aa3fea442a8498ef6
[ "BSD-3-Clause" ]
1,002
2018-01-09T10:33:07.000Z
2022-03-31T18:35:04.000Z
source/PyMaterialX/PyMaterialXGenOsl/PyOslShaderGenerator.cpp
willmuto-lucasfilm/MaterialX
589dbcb5ef292b5e5b64f30aa3fea442a8498ef6
[ "BSD-3-Clause" ]
305
2017-07-11T19:05:41.000Z
2022-02-14T12:25:43.000Z
// // TM & (c) 2017 Lucasfilm Entertainment Company Ltd. and Lucasfilm Ltd. // All rights reserved. See LICENSE.txt for license. // #include <PyMaterialX/PyMaterialX.h> #include <MaterialXGenOsl/OslShaderGenerator.h> #include <MaterialXGenShader/GenContext.h> #include <MaterialXGenShader/Shader.h> #include <string> namespace py = pybind11; namespace mx = MaterialX; void bindPyOslShaderGenerator(py::module& mod) { mod.attr("OSL_UNIFORMS") = mx::OSL::UNIFORMS; mod.attr("OSL_INPUTS") = mx::OSL::INPUTS; mod.attr("OSL_OUTPUTS") = mx::OSL::OUTPUTS; py::class_<mx::OslShaderGenerator, mx::ShaderGenerator, mx::OslShaderGeneratorPtr>(mod, "OslShaderGenerator") .def_static("create", &mx::OslShaderGenerator::create) .def(py::init<>()) .def("getTarget", &mx::OslShaderGenerator::getTarget) .def("generate", &mx::OslShaderGenerator::generate); }
30.931034
113
0.7068
willmuto-lucasfilm
d976110842f865a736a2a0eab9d0d87e184b93b4
6,199
cpp
C++
c++/UnitTest/codeCropping.cpp
sonsongithub/CoreAR
7e4be7969bcff106b32a3f2451e8742b49a1fc02
[ "BSD-3-Clause" ]
45
2015-01-13T15:16:23.000Z
2021-08-09T06:44:47.000Z
c++/UnitTest/codeCropping.cpp
sonsongithub/CoreAR
7e4be7969bcff106b32a3f2451e8742b49a1fc02
[ "BSD-3-Clause" ]
null
null
null
c++/UnitTest/codeCropping.cpp
sonsongithub/CoreAR
7e4be7969bcff106b32a3f2451e8742b49a1fc02
[ "BSD-3-Clause" ]
14
2015-03-04T06:42:00.000Z
2021-08-09T06:44:48.000Z
/* * Core AR * codeCropping.cpp * * Copyright (c) Yuichi YOSHIDA, 11/07/23. * All rights reserved. * * BSD License * * 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 materia * ls provided with the distribution. * - Neither the name of the "Yuichi Yoshida" nor the names of its contributors may be u * sed 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 E * XPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES O * F MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SH * ALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENT * AL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROC * UREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS I * NTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRI * CT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF T * HE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "codeCropping.h" #include "CoreAR.h" #include "CRTest.h" #include <jpeglib.h> #define JPEG_PATH "/Users/sonson/code/CoreAR.framework/c++/UnitTest/%s" // prototype void binarize(unsigned char *pixel, int width, int height, int threshold); unsigned char getY(unsigned char *p); int read_jpeg(char *filename, unsigned char **pixel, int *width, int *height); int write_jpeg(char *filename, unsigned char *pixel, int width, int height); // help functions unsigned char getY(unsigned char *p) { int y = ((306 * (int)(*(p+0)) + 512 ) >> 10) + ((601 * (int)(*(p+1)) + 512 ) >> 10) + ((117 * (int)(*(p+2)) + 512 ) >> 10); if (y < 0x00) y = 0x00; if (y > 0xFF) y = 0xFF; return y; } int write_jpeg(char *filename, unsigned char *pixel, int width, int height) { struct jpeg_compress_struct cinfo; struct jpeg_error_mgr jerr; FILE *outfile; cinfo.err = jpeg_std_error( &jerr ); jpeg_create_compress( &cinfo ); outfile = fopen( "/tmp/a.jpg", "wb" ); jpeg_stdio_dest( &cinfo, outfile ); cinfo.image_width = width; cinfo.image_height = height; cinfo.input_components = 1; cinfo.in_color_space = JCS_GRAYSCALE; jpeg_set_defaults(&cinfo); jpeg_start_compress(&cinfo, TRUE); // copy buffer per a line. JSAMPARRAY buffer = (*cinfo.mem->alloc_sarray)((j_common_ptr) &cinfo, JPOOL_IMAGE, width * 1, 1); for (int i = 0; i < height; i++ ) { memcpy(buffer[0], pixel + i * width * 1, width * 1); jpeg_write_scanlines( &cinfo, buffer, 1 ); } jpeg_finish_compress(&cinfo); jpeg_destroy_compress(&cinfo); fclose(outfile); return 0; } int read_jpeg(char *filename, unsigned char **pixel, int *width, int *height) { struct jpeg_error_mgr pub; struct jpeg_decompress_struct cinfo; FILE *infile = fopen(filename, "rb" ); cinfo.err = jpeg_std_error(&pub); jpeg_create_decompress(&cinfo); jpeg_stdio_src( &cinfo, infile ); jpeg_read_header(&cinfo, TRUE); jpeg_start_decompress(&cinfo); int row_stride = cinfo.output_width * cinfo.output_components; JSAMPARRAY buffer = (*cinfo.mem->alloc_sarray)((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1); unsigned char *image_buffer = (unsigned char *)malloc( cinfo.image_height * cinfo.image_width * 3 ); while (cinfo.output_scanline < cinfo.output_height) { jpeg_read_scanlines(&cinfo, buffer, 1); memcpy( image_buffer+cinfo.image_width*3*(cinfo.output_scanline-1), buffer[0], cinfo.image_width*3 ); } jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); fclose(infile); unsigned char *output = (unsigned char*)malloc(sizeof(unsigned char) * cinfo.image_width * cinfo.image_height); for(int y = 0; y < cinfo.image_height; y++) for(int x = 0; x < cinfo.image_width; x++) *(output + x + y * cinfo.image_width) = getY(image_buffer + 3 * x + y * cinfo.image_width * 3); *width = cinfo.image_width; *height = cinfo.image_height; *pixel = output; free(image_buffer); return 0; } void binarize(unsigned char *pixel, int width, int height, int threshold) { for(int y = 0; y < height; y++) for(int x = 0; x < width; x++) *(pixel + x + y * width) = (*(pixel + x + y * width) < threshold) ? CRChainCodeFlagUnchecked : CRChainCodeFlagIgnore; } void codeCropping_test() { printf("=================================================>Code cropping test\n"); char filename[1024]; sprintf(filename, JPEG_PATH, "001.jpg"); unsigned char *grayPixel = NULL; int width = 0; int height = 0; read_jpeg(filename, &grayPixel, &width, &height); unsigned char *source = (unsigned char*)malloc(sizeof(unsigned char) * width * height); memcpy(source, grayPixel, width * height); binarize(grayPixel, width, height, 100); CRChainCode *chaincode = new CRChainCode(); float focal = 650; float codeSize = 1; int croppingSize = 64; chaincode->parsePixel(grayPixel, width, height); if (!chaincode->blobs->empty()) { CRChainCodeBlob *blob = chaincode->blobs->front(); CRCode *code = blob->code(); printf("Corners on the image.\n"); code->dumpCorners(); code->normalizeCornerForImageCoord(width, height, focal, focal); code->getSimpleHomography(codeSize); _CRTic(); code->crop(croppingSize, croppingSize, focal, focal, codeSize, source, width, height); printf("Cropping code image\n\t%0.5f[msec]\n\n", _CRTocWithoutLog()); printf("Crop size %dx%d\n", croppingSize, croppingSize); write_jpeg(NULL, code->croppedCodeImage, code->croppedCodeImageWidth, code->croppedCodeImageHeight); SAFE_DELETE(code); } SAFE_DELETE(chaincode); SAFE_FREE(source); SAFE_FREE(grayPixel); }
32.119171
120
0.704952
sonsongithub
d97716c7906995a33c5fcfb3954329533f61c951
9,609
cpp
C++
lume/src/lume/grob.cpp
sreiter/lume
a321cbc35376684b711a8c54cd88eea7ce786d05
[ "BSD-2-Clause" ]
6
2018-09-11T12:05:55.000Z
2021-11-27T11:56:33.000Z
lume/src/lume/grob.cpp
sreiter/lume
a321cbc35376684b711a8c54cd88eea7ce786d05
[ "BSD-2-Clause" ]
2
2019-10-06T21:05:15.000Z
2019-10-08T09:09:30.000Z
lume/src/lume/grob.cpp
sreiter/lume
a321cbc35376684b711a8c54cd88eea7ce786d05
[ "BSD-2-Clause" ]
2
2018-12-25T00:57:17.000Z
2019-10-06T21:05:39.000Z
// This file is part of lume, a C++ library for lightweight unstructured meshes // // Copyright (C) 2018, 2019 Sebastian Reiter // Copyright (C) 2018 G-CSC, Goethe University Frankfurt // Author: Sebastian Reiter <s.b.reiter@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: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS 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 <lume/grob.h> namespace lume { ConstGrob::ConstGrob (GrobType grobType, index_t const* corners) : m_globCornerInds (corners), m_cornerOffsets (impl::Array_16_4::ascending_order ()), m_desc (grobType) {} ConstGrob::ConstGrob (ConstGrob const& other) : m_globCornerInds {other.m_globCornerInds} , m_cornerOffsets {other.m_cornerOffsets} , m_desc {other.m_desc} {} ConstGrob::ConstGrob (Grob const& other) : m_globCornerInds {other.global_corner_array ()} , m_cornerOffsets {other.corner_offsets ()} , m_desc {other.desc ()} {} ConstGrob::ConstGrob (GrobType grobType, index_t const* globCornerInds, const impl::Array_16_4& cornerOffsets) : m_globCornerInds (globCornerInds), m_cornerOffsets (cornerOffsets), m_desc (grobType) {} void ConstGrob::reset (Grob const& other) { reset (ConstGrob (other)); } void ConstGrob::reset (ConstGrob const& other) { m_globCornerInds = other.m_globCornerInds; m_cornerOffsets = other.m_cornerOffsets; m_desc = other.m_desc; } void ConstGrob::set_global_corner_array (index_t const* cornerArray) { m_globCornerInds = cornerArray; } /// only compares corners, ignores order and orientation. bool ConstGrob::operator == (const ConstGrob& g) const { if (m_desc.grob_type() != g.m_desc.grob_type()) return false; CornerIndexContainer gCorners; g.collect_corners (gCorners); const index_t numCorners = num_corners (); for(index_t i = 0; i < numCorners; ++i) { bool gotOne = false; const index_t c = corner(i); for(index_t j = 0; j < numCorners; ++j) { if(c == gCorners [j]){ gotOne = true; break; } } if (!gotOne) return false; } return true; } bool ConstGrob::operator != (const ConstGrob& g) const { return !((*this) == g); } index_t ConstGrob::operator [] (const index_t i) const { return corner (i); } index_t ConstGrob::dim () const {return m_desc.dim ();} GrobType ConstGrob::grob_type () const {return m_desc.grob_type ();} GrobDesc ConstGrob::desc () const {return m_desc;} index_t const* ConstGrob::global_corner_array () const { return m_globCornerInds; } index_t ConstGrob::num_corners () const {return m_desc.num_corners();} /// returns the global index of the i-th corner index_t ConstGrob::corner (const index_t i) const { assert (m_globCornerInds != nullptr); return m_globCornerInds [m_cornerOffsets.get(i)]; } /// collects the global indices of corners /** \param cornersOut Array of size `Grob::max_num_corners(). Only the first * `Grob::num_corners()` entries are filled * * \returns The number of corners of the specified side */ index_t ConstGrob::collect_corners (CornerIndexContainer& cornersOut) const { assert (m_globCornerInds != nullptr); const index_t numCorners = num_corners(); for(index_t i = 0; i < numCorners; ++i) cornersOut[i] = static_cast<index_t> (m_globCornerInds [m_cornerOffsets.get(i)]); return numCorners; } index_t ConstGrob::num_sides (const index_t sideDim) const { return m_desc.num_sides(sideDim); } GrobDesc ConstGrob::side_desc (const index_t sideDim, const index_t sideIndex) const { return m_desc.side_desc (sideDim, sideIndex); } ConstGrob ConstGrob::side (const index_t sideDim, const index_t sideIndex) const { assert (m_globCornerInds != nullptr); impl::Array_16_4 cornerOffsets; const index_t numCorners = m_desc.side_desc(sideDim, sideIndex).num_corners(); const index_t* locCorners = m_desc.local_side_corners (sideDim, sideIndex); // LOGT(side, "side " << sideIndex << "(dim: " << sideDim << ", num corners: " << numCorners << "): "); for(index_t i = 0; i < numCorners; ++i){ // LOG(locCorners[i] << " "); cornerOffsets.set (i, m_cornerOffsets.get(locCorners[i])); } // LOG("\n"); return ConstGrob (m_desc.side_type (sideDim, sideIndex), m_globCornerInds, cornerOffsets); } /// returns the index of the side which corresponds to the given grob /** if no such side was found, 'lume::NO_INDEX' is returned.*/ index_t ConstGrob::find_side (const ConstGrob& sideGrob) const { const index_t sideDim = sideGrob.dim(); const index_t numSides = num_sides (sideDim); for(index_t iside = 0; iside < numSides; ++iside) { if (sideGrob == side (sideDim, iside)) return iside; } return NO_INDEX; } const impl::Array_16_4& ConstGrob::corner_offsets () const { return m_cornerOffsets; } Grob::Grob (GrobType grobType, index_t* corners) : m_constGrob (grobType, corners) {} Grob::Grob (Grob const& other) : m_constGrob (other) {} Grob::Grob (GrobType grobType, index_t* globCornerInds, const impl::Array_16_4& cornerOffsets) : m_constGrob (grobType, globCornerInds, cornerOffsets) {} void Grob::reset (Grob const& other) { m_constGrob.reset (other); } void Grob::set_global_corner_array (index_t* cornerArray) { m_constGrob.set_global_corner_array (cornerArray); } Grob& Grob::operator = (Grob const& other) { return operator = (ConstGrob (other)); } Grob& Grob::operator = (ConstGrob const& other) { assert (global_corner_array () != nullptr); assert (other.global_corner_array () != nullptr); assert (other.grob_type () == grob_type ()); assert (other.num_corners () == num_corners ()); index_t const numCorners = num_corners (); for (index_t i = 0; i < numCorners; ++i) { set_corner (i, other [i]); } return *this; } /// only compares corners, ignores order and orientation. bool Grob::operator == (const Grob& other) const { return m_constGrob == other; } bool Grob::operator == (const ConstGrob& other) const { return m_constGrob == other; } bool Grob::operator != (const Grob& other) const { return m_constGrob != other; } bool Grob::operator != (const ConstGrob& other) const { return m_constGrob != other; } index_t Grob::operator [] (const index_t i) const { return corner (i); } index_t Grob::dim () const { return m_constGrob.dim (); } GrobType Grob::grob_type () const { return m_constGrob.grob_type (); } GrobDesc Grob::desc () const { return m_constGrob.desc (); } index_t const* Grob::global_corner_array () const { return m_constGrob.global_corner_array (); } index_t* Grob::global_corner_array () { return const_cast <index_t*> (m_constGrob.global_corner_array ()); } index_t Grob::num_corners () const { return m_constGrob.num_corners (); } /// returns the global index of the i-th corner index_t Grob::corner (const index_t i) const { return m_constGrob.corner (i); } /// sets the point index of the i-th corner void Grob::set_corner (const index_t cornerIndex, const index_t pointIndex) { assert (global_corner_array () != nullptr); assert (cornerIndex < num_corners ()); global_corner_array () [m_constGrob.corner_offsets ().get(cornerIndex)] = pointIndex; } /// collects the global indices of corners /** \param cornersOut Array of size `Grob::max_num_corners(). Only the first * `Grob::num_corners()` entries are filled * * \returns The number of corners of the specified side */ index_t Grob::collect_corners (CornerIndexContainer& cornersOut) const { return m_constGrob.collect_corners (cornersOut); } index_t Grob::num_sides (const index_t sideDim) const { return m_constGrob.num_sides(sideDim); } GrobDesc Grob::side_desc (const index_t sideDim, const index_t sideIndex) const { return m_constGrob.side_desc (sideDim, sideIndex); } Grob Grob::side (const index_t sideDim, const index_t sideIndex) const { auto const cgrob = m_constGrob.side (sideDim, sideIndex); return Grob (cgrob.grob_type (), const_cast <index_t*> (cgrob.global_corner_array ()), cgrob.corner_offsets ()); } /// returns the index of the side which corresponds to the given grob /** if no such side was found, 'lume::NO_INDEX' is returned.*/ index_t Grob::find_side (const Grob& sideGrob) const { return m_constGrob.find_side (sideGrob); } const impl::Array_16_4& Grob::corner_offsets () const { return m_constGrob.corner_offsets (); } }// end of namespace
28.014577
112
0.714018
sreiter
d97808de077bc4a6e83f133391500728b8e77233
20,741
cpp
C++
binding/WebAssembly/applications/wFormats/wFormats.cpp
Fabrice-Praxinos/ULIS
232ad5c0804da1202d8231fda67ff4aea70f57ef
[ "RSA-MD" ]
30
2020-09-16T17:39:36.000Z
2022-02-17T08:32:53.000Z
binding/WebAssembly/applications/wFormats/wFormats.cpp
Fabrice-Praxinos/ULIS
232ad5c0804da1202d8231fda67ff4aea70f57ef
[ "RSA-MD" ]
7
2020-11-23T14:37:15.000Z
2022-01-17T11:35:32.000Z
binding/WebAssembly/applications/wFormats/wFormats.cpp
Fabrice-Praxinos/ULIS
232ad5c0804da1202d8231fda67ff4aea70f57ef
[ "RSA-MD" ]
5
2020-09-17T00:39:14.000Z
2021-08-30T16:14:07.000Z
// IDDN FR.001.250001.004.S.X.2019.000.00000 /** * * ULIS *__________________ * * @file wFormats.cpp * @author Clement Berthaud * @brief Formats application for wasm ULIS. * @copyright Copyright 2018-2021 Praxinos, Inc. All Rights Reserved. * @license Please refer to LICENSE.md */ #include <ULIS> using namespace ::ULIS; int main() { std::cout << "Format_G8 : " << Format_G8 << std::endl; std::cout << "Format_GA8 : " << Format_GA8 << std::endl; std::cout << "Format_AG8 : " << Format_AG8 << std::endl; std::cout << "Format_G16 : " << Format_G16 << std::endl; std::cout << "Format_GA16 : " << Format_GA16 << std::endl; std::cout << "Format_AG16 : " << Format_AG16 << std::endl; std::cout << "Format_GF : " << Format_GF << std::endl; std::cout << "Format_GAF : " << Format_GAF << std::endl; std::cout << "Format_AGF : " << Format_AGF << std::endl; std::cout << "Format_RGB8 : " << Format_RGB8 << std::endl; std::cout << "Format_BGR8 : " << Format_BGR8 << std::endl; std::cout << "Format_RGBA8 : " << Format_RGBA8 << std::endl; std::cout << "Format_ABGR8 : " << Format_ABGR8 << std::endl; std::cout << "Format_ARGB8 : " << Format_ARGB8 << std::endl; std::cout << "Format_BGRA8 : " << Format_BGRA8 << std::endl; std::cout << "Format_RGB16 : " << Format_RGB16 << std::endl; std::cout << "Format_BGR16 : " << Format_BGR16 << std::endl; std::cout << "Format_RGBA16 : " << Format_RGBA16 << std::endl; std::cout << "Format_ABGR16 : " << Format_ABGR16 << std::endl; std::cout << "Format_ARGB16 : " << Format_ARGB16 << std::endl; std::cout << "Format_BGRA16 : " << Format_BGRA16 << std::endl; std::cout << "Format_RGBF : " << Format_RGBF << std::endl; std::cout << "Format_BGRF : " << Format_BGRF << std::endl; std::cout << "Format_RGBAF : " << Format_RGBAF << std::endl; std::cout << "Format_ABGRF : " << Format_ABGRF << std::endl; std::cout << "Format_ARGBF : " << Format_ARGBF << std::endl; std::cout << "Format_BGRAF : " << Format_BGRAF << std::endl; std::cout << "Format_HSV8 : " << Format_HSV8 << std::endl; std::cout << "Format_VSH8 : " << Format_VSH8 << std::endl; std::cout << "Format_HSVA8 : " << Format_HSVA8 << std::endl; std::cout << "Format_AVSH8 : " << Format_AVSH8 << std::endl; std::cout << "Format_AHSV8 : " << Format_AHSV8 << std::endl; std::cout << "Format_VSHA8 : " << Format_VSHA8 << std::endl; std::cout << "Format_HSV16 : " << Format_HSV16 << std::endl; std::cout << "Format_VSH16 : " << Format_VSH16 << std::endl; std::cout << "Format_HSVA16 : " << Format_HSVA16 << std::endl; std::cout << "Format_AVSH16 : " << Format_AVSH16 << std::endl; std::cout << "Format_AHSV16 : " << Format_AHSV16 << std::endl; std::cout << "Format_VSHA16 : " << Format_VSHA16 << std::endl; std::cout << "Format_HSVF : " << Format_HSVF << std::endl; std::cout << "Format_VSHF : " << Format_VSHF << std::endl; std::cout << "Format_HSVAF : " << Format_HSVAF << std::endl; std::cout << "Format_AVSHF : " << Format_AVSHF << std::endl; std::cout << "Format_AHSVF : " << Format_AHSVF << std::endl; std::cout << "Format_VSHAF : " << Format_VSHAF << std::endl; std::cout << "Format_HSL8 : " << Format_HSL8 << std::endl; std::cout << "Format_LSH8 : " << Format_LSH8 << std::endl; std::cout << "Format_HSLA8 : " << Format_HSLA8 << std::endl; std::cout << "Format_ALSH8 : " << Format_ALSH8 << std::endl; std::cout << "Format_AHSL8 : " << Format_AHSL8 << std::endl; std::cout << "Format_LSHA8 : " << Format_LSHA8 << std::endl; std::cout << "Format_HSL16 : " << Format_HSL16 << std::endl; std::cout << "Format_LSH16 : " << Format_LSH16 << std::endl; std::cout << "Format_HSLA16 : " << Format_HSLA16 << std::endl; std::cout << "Format_ALSH16 : " << Format_ALSH16 << std::endl; std::cout << "Format_AHSL16 : " << Format_AHSL16 << std::endl; std::cout << "Format_LSHA16 : " << Format_LSHA16 << std::endl; std::cout << "Format_HSLF : " << Format_HSLF << std::endl; std::cout << "Format_LSHF : " << Format_LSHF << std::endl; std::cout << "Format_HSLAF : " << Format_HSLAF << std::endl; std::cout << "Format_ALSHF : " << Format_ALSHF << std::endl; std::cout << "Format_AHSLF : " << Format_AHSLF << std::endl; std::cout << "Format_LSHAF : " << Format_LSHAF << std::endl; std::cout << "Format_CMY8 : " << Format_CMY8 << std::endl; std::cout << "Format_YMC8 : " << Format_YMC8 << std::endl; std::cout << "Format_CMYA8 : " << Format_CMYA8 << std::endl; std::cout << "Format_AYMC8 : " << Format_AYMC8 << std::endl; std::cout << "Format_ACMY8 : " << Format_ACMY8 << std::endl; std::cout << "Format_YMCA8 : " << Format_YMCA8 << std::endl; std::cout << "Format_CMY16 : " << Format_CMY16 << std::endl; std::cout << "Format_YMC16 : " << Format_YMC16 << std::endl; std::cout << "Format_CMYA16 : " << Format_CMYA16 << std::endl; std::cout << "Format_AYMC16 : " << Format_AYMC16 << std::endl; std::cout << "Format_ACMY16 : " << Format_ACMY16 << std::endl; std::cout << "Format_YMCA16 : " << Format_YMCA16 << std::endl; std::cout << "Format_CMYF : " << Format_CMYF << std::endl; std::cout << "Format_YMCF : " << Format_YMCF << std::endl; std::cout << "Format_CMYAF : " << Format_CMYAF << std::endl; std::cout << "Format_AYMCF : " << Format_AYMCF << std::endl; std::cout << "Format_ACMYF : " << Format_ACMYF << std::endl; std::cout << "Format_YMCAF : " << Format_YMCAF << std::endl; std::cout << "Format_CMYK8 : " << Format_CMYK8 << std::endl; std::cout << "Format_KCMY8 : " << Format_KCMY8 << std::endl; std::cout << "Format_KYMC8 : " << Format_KYMC8 << std::endl; std::cout << "Format_YMCK8 : " << Format_YMCK8 << std::endl; std::cout << "Format_CMYKA8 : " << Format_CMYKA8 << std::endl; std::cout << "Format_ACMYK8 : " << Format_ACMYK8 << std::endl; std::cout << "Format_AKYMC8 : " << Format_AKYMC8 << std::endl; std::cout << "Format_KYMCA8 : " << Format_KYMCA8 << std::endl; std::cout << "Format_CMYK16 : " << Format_CMYK16 << std::endl; std::cout << "Format_KCMY16 : " << Format_KCMY16 << std::endl; std::cout << "Format_KYMC16 : " << Format_KYMC16 << std::endl; std::cout << "Format_YMCK16 : " << Format_YMCK16 << std::endl; std::cout << "Format_CMYKA16 : " << Format_CMYKA16 << std::endl; std::cout << "Format_ACMYK16 : " << Format_ACMYK16 << std::endl; std::cout << "Format_AKYMC16 : " << Format_AKYMC16 << std::endl; std::cout << "Format_KYMCA16 : " << Format_KYMCA16 << std::endl; std::cout << "Format_CMYKF : " << Format_CMYKF << std::endl; std::cout << "Format_KCMYF : " << Format_KCMYF << std::endl; std::cout << "Format_KYMCF : " << Format_KYMCF << std::endl; std::cout << "Format_YMCKF : " << Format_YMCKF << std::endl; std::cout << "Format_CMYKAF : " << Format_CMYKAF << std::endl; std::cout << "Format_ACMYKF : " << Format_ACMYKF << std::endl; std::cout << "Format_AKYMCF : " << Format_AKYMCF << std::endl; std::cout << "Format_KYMCAF : " << Format_KYMCAF << std::endl; std::cout << "Format_YUV8 : " << Format_YUV8 << std::endl; std::cout << "Format_VUY8 : " << Format_VUY8 << std::endl; std::cout << "Format_YUVA8 : " << Format_YUVA8 << std::endl; std::cout << "Format_AVUY8 : " << Format_AVUY8 << std::endl; std::cout << "Format_AYUV8 : " << Format_AYUV8 << std::endl; std::cout << "Format_VUYA8 : " << Format_VUYA8 << std::endl; std::cout << "Format_YUV16 : " << Format_YUV16 << std::endl; std::cout << "Format_VUY16 : " << Format_VUY16 << std::endl; std::cout << "Format_YUVA16 : " << Format_YUVA16 << std::endl; std::cout << "Format_AVUY16 : " << Format_AVUY16 << std::endl; std::cout << "Format_AYUV16 : " << Format_AYUV16 << std::endl; std::cout << "Format_VUYA16 : " << Format_VUYA16 << std::endl; std::cout << "Format_YUVF : " << Format_YUVF << std::endl; std::cout << "Format_VUYF : " << Format_VUYF << std::endl; std::cout << "Format_YUVAF : " << Format_YUVAF << std::endl; std::cout << "Format_AVUYF : " << Format_AVUYF << std::endl; std::cout << "Format_AYUVF : " << Format_AYUVF << std::endl; std::cout << "Format_VUYAF : " << Format_VUYAF << std::endl; std::cout << "Format_Lab8 : " << Format_Lab8 << std::endl; std::cout << "Format_baL8 : " << Format_baL8 << std::endl; std::cout << "Format_LabA8 : " << Format_LabA8 << std::endl; std::cout << "Format_AbaL8 : " << Format_AbaL8 << std::endl; std::cout << "Format_ALab8 : " << Format_ALab8 << std::endl; std::cout << "Format_baLA8 : " << Format_baLA8 << std::endl; std::cout << "Format_Lab16 : " << Format_Lab16 << std::endl; std::cout << "Format_baL16 : " << Format_baL16 << std::endl; std::cout << "Format_LabA16 : " << Format_LabA16 << std::endl; std::cout << "Format_AbaL16 : " << Format_AbaL16 << std::endl; std::cout << "Format_ALab16 : " << Format_ALab16 << std::endl; std::cout << "Format_baLA16 : " << Format_baLA16 << std::endl; std::cout << "Format_LabF : " << Format_LabF << std::endl; std::cout << "Format_baLF : " << Format_baLF << std::endl; std::cout << "Format_LabAF : " << Format_LabAF << std::endl; std::cout << "Format_AbaLF : " << Format_AbaLF << std::endl; std::cout << "Format_ALabF : " << Format_ALabF << std::endl; std::cout << "Format_baLAF : " << Format_baLAF << std::endl; std::cout << "Format_XYZ8 : " << Format_XYZ8 << std::endl; std::cout << "Format_ZYX8 : " << Format_ZYX8 << std::endl; std::cout << "Format_XYZA8 : " << Format_XYZA8 << std::endl; std::cout << "Format_AZYX8 : " << Format_AZYX8 << std::endl; std::cout << "Format_AXYZ8 : " << Format_AXYZ8 << std::endl; std::cout << "Format_ZYXA8 : " << Format_ZYXA8 << std::endl; std::cout << "Format_XYZ16 : " << Format_XYZ16 << std::endl; std::cout << "Format_ZYX16 : " << Format_ZYX16 << std::endl; std::cout << "Format_XYZA16 : " << Format_XYZA16 << std::endl; std::cout << "Format_AZYX16 : " << Format_AZYX16 << std::endl; std::cout << "Format_AXYZ16 : " << Format_AXYZ16 << std::endl; std::cout << "Format_ZYXA16 : " << Format_ZYXA16 << std::endl; std::cout << "Format_XYZF : " << Format_XYZF << std::endl; std::cout << "Format_ZYXF : " << Format_ZYXF << std::endl; std::cout << "Format_XYZAF : " << Format_XYZAF << std::endl; std::cout << "Format_AZYXF : " << Format_AZYXF << std::endl; std::cout << "Format_AXYZF : " << Format_AXYZF << std::endl; std::cout << "Format_ZYXAF : " << Format_ZYXAF << std::endl; std::cout << "Format_Yxy8 : " << Format_Yxy8 << std::endl; std::cout << "Format_yxY8 : " << Format_yxY8 << std::endl; std::cout << "Format_YxyA8 : " << Format_YxyA8 << std::endl; std::cout << "Format_AyxY8 : " << Format_AyxY8 << std::endl; std::cout << "Format_AYxy8 : " << Format_AYxy8 << std::endl; std::cout << "Format_yxYA8 : " << Format_yxYA8 << std::endl; std::cout << "Format_Yxy16 : " << Format_Yxy16 << std::endl; std::cout << "Format_yxY16 : " << Format_yxY16 << std::endl; std::cout << "Format_YxyA16 : " << Format_YxyA16 << std::endl; std::cout << "Format_AyxY16 : " << Format_AyxY16 << std::endl; std::cout << "Format_AYxy16 : " << Format_AYxy16 << std::endl; std::cout << "Format_yxYA16 : " << Format_yxYA16 << std::endl; std::cout << "Format_YxyF : " << Format_YxyF << std::endl; std::cout << "Format_yxYF : " << Format_yxYF << std::endl; std::cout << "Format_YxyAF : " << Format_YxyAF << std::endl; std::cout << "Format_AyxYF : " << Format_AyxYF << std::endl; std::cout << "Format_AYxyF : " << Format_AYxyF << std::endl; std::cout << "Format_yxYAF : " << Format_yxYAF << std::endl; return 0; }
104.752525
114
0.336532
Fabrice-Praxinos
d9789d0a31fc1d2e9e4a5cd52ba560ce2d9f95eb
5,610
hpp
C++
include/antlr/BaseAST.hpp
zstars/booledeusto
fdc110a9add4a5946fabc2055a533593932a2003
[ "BSD-3-Clause" ]
6
2018-06-11T18:50:20.000Z
2021-09-07T23:55:01.000Z
include/antlr/BaseAST.hpp
zstars/booledeusto
fdc110a9add4a5946fabc2055a533593932a2003
[ "BSD-3-Clause" ]
null
null
null
include/antlr/BaseAST.hpp
zstars/booledeusto
fdc110a9add4a5946fabc2055a533593932a2003
[ "BSD-3-Clause" ]
2
2021-03-16T16:12:32.000Z
2022-01-15T01:34:40.000Z
#ifndef INC_BaseAST_hpp__ #define INC_BaseAST_hpp__ /* * <b>SOFTWARE RIGHTS</b> * <p> * ANTLR 2.7.1 MageLang Insitute, 1999, 2000, 2001 * <p> * We reserve no legal rights to the ANTLR--it is fully in the * public domain. An individual or company may do whatever * they wish with source code distributed with ANTLR or the * code generated by ANTLR, including the incorporation of * ANTLR, or its output, into commercial software. * <p> * We encourage users to develop software with ANTLR. However, * we do ask that credit is given to us for developing * ANTLR. By "credit", we mean that if you use ANTLR or * incorporate any source code into one of your programs * (commercial product, research project, or otherwise) that * you acknowledge this fact somewhere in the documentation, * research report, etc... If you like ANTLR and have * developed a nice tool with the output, please mention that * you developed it using ANTLR. In addition, we ask that the * headers remain intact in our source code. As long as these * guidelines are kept, we expect to continue enhancing this * system and expect to make other tools available as they are * completed. * <p> * The ANTLR gang: * @version ANTLR 2.7.1 MageLang Insitute, 1999, 2000, 2001 * @author Terence Parr, <a href=http://www.MageLang.com>MageLang Institute</a> * @author <br>John Lilley, <a href=http://www.Empathy.com>Empathy Software</a> * @author <br><a href="mailto:pete@yamuna.demon.co.uk">Pete Wells</a> */ #include <antlr/config.hpp> #include <antlr/AST.hpp> #ifdef ANTLR_CXX_SUPPORTS_NAMESPACE namespace antlr { #endif class ANTLR_API BaseAST; typedef ASTRefCount<BaseAST> RefBaseAST; class ANTLR_API BaseAST : public AST { public: BaseAST(); BaseAST(const BaseAST& other); virtual ~BaseAST(); /// Return the class name virtual const char* typeName( void ) const; /// Clone this AST node. virtual RefAST clone( void ) const; /// Is node t equal to this in terms of token type and text? virtual bool equals(RefAST t) const; /** Is t an exact structural and equals() match of this tree. The * 'this' reference is considered the start of a sibling list. */ virtual bool equalsList(RefAST t) const; /** Is 't' a subtree of this list? The siblings of the root are NOT ignored. */ virtual bool equalsListPartial(RefAST t) const; /** Is tree rooted at 'this' equal to 't'? The siblings of 'this' are * ignored. */ virtual bool equalsTree(RefAST t) const; /** Is 't' a subtree of the tree rooted at 'this'? The siblings of * 'this' are ignored. */ virtual bool equalsTreePartial(RefAST t) const; /** Walk the tree looking for all exact subtree matches. Return * an ASTEnumerator that lets the caller walk the list * of subtree roots found herein. */ virtual ANTLR_USE_NAMESPACE(std)vector<RefAST> findAll(RefAST t); /** Walk the tree looking for all subtrees. Return * an ASTEnumerator that lets the caller walk the list * of subtree roots found herein. */ virtual ANTLR_USE_NAMESPACE(std)vector<RefAST> findAllPartial(RefAST t); /// Add a node to the end of the child list for this node virtual void addChild(RefAST c); /// Get the first child of this node; null if no children virtual RefAST getFirstChild() const { return RefAST(down); } /// Get the next sibling in line after this one virtual RefAST getNextSibling() const { return RefAST(right); } /// Get the token text for this node virtual ANTLR_USE_NAMESPACE(std)string getText() const { return ""; } /// Get the token type for this node virtual int getType() const { return 0; } /// Remove all children virtual void removeChildren() { down = static_cast<BaseAST*>(static_cast<AST*>(nullAST)); } /// Set the first child of a node. virtual void setFirstChild(RefAST c) { down = static_cast<BaseAST*>(static_cast<AST*>(c)); } /// Set the next sibling after this one. void setNextSibling(RefAST n) { right = static_cast<BaseAST*>(static_cast<AST*>(n)); } /// Set the token text for this node virtual void setText(const ANTLR_USE_NAMESPACE(std)string& txt); /// Set the token type for this node virtual void setType(int type); #ifdef ANTLR_SUPPORT_XML /** print attributes of this node to 'out'. Override to customize XML * output. * @param out the stream to write the AST attributes to. */ virtual bool attributesToStream( ANTLR_USE_NAMESPACE(std)ostream& out ) const; /** Write this subtree to a stream. Overload this one to customize the XML * output for AST derived AST-types * @param output stream */ virtual void toStream( ANTLR_USE_NAMESPACE(std)ostream &out ) const; #endif /// Return string representation for the AST virtual ANTLR_USE_NAMESPACE(std)string toString() const; /// Print out a child sibling tree in LISP notation virtual ANTLR_USE_NAMESPACE(std)string toStringList() const; virtual ANTLR_USE_NAMESPACE(std)string toStringTree() const; protected: RefBaseAST down; RefBaseAST right; private: void doWorkForFindAll(ANTLR_USE_NAMESPACE(std)vector<RefAST>& v, RefAST target, bool partialMatch); }; /** Is node t equal to this in terms of token type and text? */ inline bool BaseAST::equals(RefAST t) const { if (!t) return false; return ((getType() == t->getType()) && (getText() == t->getText())); } #ifdef ANTLR_CXX_SUPPORTS_NAMESPACE } #endif #endif //INC_BaseAST_hpp__
30.48913
80
0.695544
zstars
d978ce34b2efaee9bf4b740929bdddf506aa29b3
7,366
inl
C++
volume/Unified2/src/Task/ElasticVolumeMesh/Distributed/DistributedElasticVolumeMeshCommon.inl
llmontoryxd/mipt_diploma
7d7d65cd619fe983736773f95ebb50b470adbed2
[ "MIT" ]
null
null
null
volume/Unified2/src/Task/ElasticVolumeMesh/Distributed/DistributedElasticVolumeMeshCommon.inl
llmontoryxd/mipt_diploma
7d7d65cd619fe983736773f95ebb50b470adbed2
[ "MIT" ]
null
null
null
volume/Unified2/src/Task/ElasticVolumeMesh/Distributed/DistributedElasticVolumeMeshCommon.inl
llmontoryxd/mipt_diploma
7d7d65cd619fe983736773f95ebb50b470adbed2
[ "MIT" ]
null
null
null
template<typename Space, typename FunctionSpace> typename Space::IndexType DistributedElasticVolumeMeshCommon<Space, FunctionSpace>::GetSyncDataSize(IndexType dstDomainIndex) const { return syncDataSizes[dstDomainIndex]; } template<typename Space, typename FunctionSpace> void DistributedElasticVolumeMeshCommon<Space, FunctionSpace>:: RebuildTimeHierarchyLevels(IndexType globalStepIndex, bool allowCollisions) { volumeMesh.timeHierarchyLevelsManager.Initialize( volumeMesh.cells.size(), volumeMesh.GetHierarchyLevelsCount(), volumeMesh.GetSolverPhasesCount(), false); for (IndexType dstDomainIndex = 0; dstDomainIndex < domainsCount; ++dstDomainIndex) { for (IndexType cellNumber = 0; cellNumber < transitionInfos[dstDomainIndex].cells.size(); ++cellNumber) { IndexType cellIndex = volumeMesh.GetCellIndex(transitionInfos[dstDomainIndex].cells[cellNumber].incidentNodes); volumeMesh.timeHierarchyLevelsManager.SetLevel(cellIndex, 0); } } volumeMesh.RebuildTimeHierarchyLevels(globalStepIndex, allowCollisions, true); } template<typename Space, typename FunctionSpace> bool DistributedElasticVolumeMeshCommon<Space, FunctionSpace>:: IsSyncDataEmpty(IndexType dstDomainIndex) const { return transitionInfos[dstDomainIndex].nodesIndices.empty() || transitionInfos[dstDomainIndex].cells.empty() || transitionInfos[dstDomainIndex].transitionNodes.empty(); } template<typename Space, typename FunctionSpace> void DistributedElasticVolumeMeshCommon<Space, FunctionSpace>::SetTransitionInfo( const std::vector< TransitionInfo<Space> >& transitionInfos) { this->transitionInfos = transitionInfos; ComputeSyncDataSizes(); nodesDictionaries.resize(domainsCount); for (IndexType dstDomainIndex = 0; dstDomainIndex < domainsCount; ++dstDomainIndex) { for (IndexType transitionNodeIndex = 0; transitionNodeIndex < transitionInfos[dstDomainIndex].transitionNodes.size(); ++transitionNodeIndex) { const typename TransitionInfo<Space>::TransitionNode& transitionNode = transitionInfos[dstDomainIndex].transitionNodes[transitionNodeIndex]; nodesDictionaries[dstDomainIndex][transitionNode.nativeIndex] = transitionNode.targetIndex; } } } template<typename Space, typename FunctionSpace> typename DistributedElasticVolumeMeshCommon<Space, FunctionSpace>::BytesHandled DistributedElasticVolumeMeshCommon<Space, FunctionSpace>::UpdateDomainData(const char* const data) { IndexType offset = 0; // cells IndexType cellsCount = *((IndexType*)data); offset += sizeof(IndexType); UpdateCellsData(cellsCount, (CellSyncData*)(data + offset)); offset += sizeof(CellSyncData) * cellsCount; // nodes IndexType nodesCount = *((IndexType*)(data + offset)); offset += sizeof(IndexType); UpdateNodesData(nodesCount, (NodeSyncData*)(data + offset)); offset += sizeof(NodeSyncData) * nodesCount; return offset; } template<typename Space, typename FunctionSpace> typename DistributedElasticVolumeMeshCommon<Space, FunctionSpace>::BytesHandled DistributedElasticVolumeMeshCommon<Space, FunctionSpace>::BuildSyncData(IndexType dstDomainIndex, char* const data) { *((IndexType*)data) = dstDomainIndex; IndexType offset = sizeof(IndexType); BuildCellsSyncData(dstDomainIndex, data + offset); offset += sizeof(CellSyncData) * transitionInfos[dstDomainIndex].cells.size() + sizeof(IndexType); if (sendNodesInfo) { BuildNodesSyncData(dstDomainIndex, data + offset); offset += sizeof(NodeSyncData) * transitionInfos[dstDomainIndex].nodesIndices.size(); } else { *((IndexType*)(data + offset)) = 0; } offset += sizeof(IndexType); return offset; } template<typename Space, typename FunctionSpace> void DistributedElasticVolumeMeshCommon<Space, FunctionSpace>::UpdateCellsData(IndexType cellsCount, CellSyncData* const cellsData) { #pragma omp parallel for for (int cellNumber = 0; cellNumber < (int)cellsCount; ++cellNumber) { CellSolution& cellSolution = cellsData[cellNumber].cellSolution; IndexType cellIndex = volumeMesh.GetCellIndex(cellsData[cellNumber].cell.incidentNodes); assert(cellIndex != IndexType(-1)); IndexType associatedPermutation[Space::NodesPerCell]; volumeMesh.GetCellsPairOrientation(cellsData[cellNumber].cell.incidentNodes, volumeMesh.cells[cellIndex].incidentNodes, associatedPermutation); // ? TODO volumeMesh.TransformCellSolution(cellIndex, associatedPermutation, &cellSolution); volumeMesh.cellSolutions[cellIndex] = cellSolution; } } template<typename Space, typename FunctionSpace> void DistributedElasticVolumeMeshCommon<Space, FunctionSpace>::UpdateNodesData(IndexType nodesCount, const NodeSyncData* const nodesData) { #pragma omp parallel for for (int nodeNumber = 0; nodeNumber < (int)nodesCount; ++nodeNumber) { const Vector& pos = nodesData[nodeNumber].pos; IndexType nodeIndex = nodesData[nodeNumber].nodeIndex; volumeMesh.nodes[nodeIndex] = Node(pos); } } template<typename Space, typename FunctionSpace> void DistributedElasticVolumeMeshCommon<Space, FunctionSpace>::BuildCellsSyncData(IndexType dstDomainIndex, char* const data) { *((IndexType*)data) = (IndexType)transitionInfos[dstDomainIndex].cells.size(); CellSyncData* cellsData = (CellSyncData*)(data + sizeof(IndexType)); #pragma omp parallel for for (int cellNumber = 0; cellNumber < (int)transitionInfos[dstDomainIndex].cells.size(); ++cellNumber) { IndexType cellIndex = volumeMesh.GetCellIndex( transitionInfos[dstDomainIndex].cells[cellNumber].incidentNodes); assert(cellIndex != IndexType(-1)); CellSyncData& cellSyncData = cellsData[cellNumber]; cellSyncData.cellSolution = volumeMesh.cellSolutions[cellIndex]; for (IndexType nodeNumber = 0; nodeNumber < Space::NodesPerCell; ++nodeNumber) { cellSyncData.cell.incidentNodes[nodeNumber] = nodesDictionaries[dstDomainIndex][volumeMesh.cells[cellIndex].incidentNodes[nodeNumber]]; } // TODO // cellSyncData.destroy = } } template<typename Space, typename FunctionSpace> void DistributedElasticVolumeMeshCommon<Space, FunctionSpace>::BuildNodesSyncData(IndexType dstDomainIndex, char* const data) { *((IndexType*)data) = transitionInfos[dstDomainIndex].nodesIndices.size(); NodeSyncData* nodesData = (NodeSyncData*)(data + sizeof(IndexType)); #pragma omp parallel for for (int nodeNumber = 0; nodeNumber < (int)transitionInfos[dstDomainIndex].nodesIndices.size(); ++nodeNumber) { IndexType nodeIndex = transitionInfos[dstDomainIndex].nodesIndices[nodeNumber]; NodeSyncData& nodeSyncData = nodesData[nodeNumber]; nodeSyncData.pos = volumeMesh.nodes[nodeIndex].pos; nodeSyncData.nodeIndex = nodesDictionaries[dstDomainIndex][nodeIndex]; } } template<typename Space, typename FunctionSpace> void DistributedElasticVolumeMeshCommon<Space, FunctionSpace>::ComputeSyncDataSizes() { for (IndexType dstDomainIndex = 0; dstDomainIndex < domainsCount; ++dstDomainIndex) { syncDataSizes[dstDomainIndex] += sizeof(IndexType) + // dstDomainIndes sizeof(IndexType) + // cells count transitionInfos[dstDomainIndex].cells.size() * sizeof(CellSyncData) + sizeof(IndexType) + // nodes count (sendNodesInfo ? transitionInfos[dstDomainIndex].nodesIndices.size() * sizeof(NodeSyncData) : 0); } }
39.816216
146
0.771518
llmontoryxd
d97aa82743ee3cd0b534a9895eb818613dd5fa36
6,003
cpp
C++
src/Core/Canvas.cpp
dgi09/2DGameEngine
18eff334f2ebf469d780688b2bfee6af760a699d
[ "BSD-2-Clause" ]
1
2017-03-13T22:07:35.000Z
2017-03-13T22:07:35.000Z
src/Core/Canvas.cpp
dgi09/2DGameEngine
18eff334f2ebf469d780688b2bfee6af760a699d
[ "BSD-2-Clause" ]
null
null
null
src/Core/Canvas.cpp
dgi09/2DGameEngine
18eff334f2ebf469d780688b2bfee6af760a699d
[ "BSD-2-Clause" ]
null
null
null
#include "Canvas.h" using namespace DirectX; Canvas::Canvas(HWND handle, UINT width, UINT height) { this->width = width; this->height = height; DXGI_SWAP_CHAIN_DESC desc; ZeroMemory(&desc,sizeof(DXGI_SWAP_CHAIN_DESC)); desc.BufferCount = 2; desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; desc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; desc.BufferDesc.Width = width; desc.BufferDesc.Height = height; desc.OutputWindow = handle; desc.SampleDesc.Count = 1; desc.Windowed = TRUE; D3D_FEATURE_LEVEL ftr; ftr = D3D_FEATURE_LEVEL_11_0; D3D11CreateDeviceAndSwapChain(NULL,D3D_DRIVER_TYPE_HARDWARE, nullptr,0,&ftr,1, D3D11_SDK_VERSION, &desc, &swapChain, &device, nullptr, &context); ID3D11Texture2D * backBuffer = nullptr; swapChain->GetBuffer(0,__uuidof(ID3D11Texture2D),(LPVOID*)&backBuffer); device->CreateRenderTargetView(backBuffer,nullptr,&backBufferView); context->OMSetRenderTargets(1,&backBufferView,nullptr); D3D11_DEPTH_STENCIL_DESC depthDesc; ZeroMemory(&depthDesc,sizeof(D3D11_DEPTH_STENCIL_DESC)); depthDesc.DepthEnable = false; D3D11_RASTERIZER_DESC rasterDesc; ZeroMemory(&rasterDesc,sizeof(D3D11_RASTERIZER_DESC)); rasterDesc.CullMode = D3D11_CULL_NONE; rasterDesc.FillMode = D3D11_FILL_SOLID; device->CreateRasterizerState(&rasterDesc,&rasterState); context->RSSetState(rasterState); device->CreateDepthStencilState(&depthDesc,&depthState); context->OMSetDepthStencilState(depthState,0); D3D11_BLEND_DESC blendStateDescription; ZeroMemory(&blendStateDescription,sizeof(D3D11_BLEND_DESC)); blendStateDescription.RenderTarget[0].BlendEnable = TRUE; blendStateDescription.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA; blendStateDescription.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; blendStateDescription.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; blendStateDescription.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE; blendStateDescription.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO; blendStateDescription.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; blendStateDescription.RenderTarget[0].RenderTargetWriteMask = 0x0f; device->CreateBlendState(&blendStateDescription,&blend); float factor[] = {0.0f,0.0f,0.0f,0.0f}; context->OMSetBlendState(blend,factor,0xffffffff); D3D11_VIEWPORT view; ZeroMemory(&view,sizeof(D3D11_VIEWPORT)); view.TopLeftX = 0.0f; view.TopLeftY = 0.0f; view.Width = (UINT)width; view.Height = (UINT)height; view.MinDepth = 0.0f; view.MaxDepth = 1.0f; context->RSSetViewports(1,&view); tQuad.Init(device); cQuad.Init(device); cLine.Init(device); lastRotationAngle = 0; XMMATRIX viewMat = XMMatrixLookAtLH(XMVectorSet(0.0f,0.0f,0.0f,1.0f),XMVectorSet(0.0f,0.0f,1.0f,1.0f),XMVectorSet(0.0f,1.0f,0.0f,1.0f)); XMMATRIX proj = XMMatrixOrthographicLH((float)width,(float)height,0.1f,1.0f); XMStoreFloat4x4(&mat.viewMatrix,XMMatrixTranspose(viewMat)); XMStoreFloat4x4(&mat.projmatrix,XMMatrixTranspose(proj)); XMStoreFloat4x4(&mat.worldMatrix,XMMatrixTranspose(XMMatrixIdentity())); D3D11_BUFFER_DESC cDesc; cDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; cDesc.ByteWidth = sizeof(Matrixes); cDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; cDesc.MiscFlags = 0; cDesc.StructureByteStride = 0; cDesc.Usage = D3D11_USAGE_DYNAMIC; D3D11_SUBRESOURCE_DATA data; data.pSysMem = &mat; device->CreateBuffer(&cDesc,&data,&matrixBuffer); context->VSSetConstantBuffers(0,1,&matrixBuffer); } Canvas::~Canvas() { rasterState->Release(); depthState->Release(); matrixBuffer->Release(); backBufferView->Release(); context->Release(); device->Release(); swapChain->Release(); } void Canvas::SetClearColor(Color color) { clearColor = color; } Color Canvas::GetClearColor() { return clearColor; } void Canvas::Clear() { context->ClearRenderTargetView(backBufferView,(float*)&clearColor); } void Canvas::Present() { swapChain->Present(0,0); } void Canvas::DrawRectSolid(Rect & rect,Color color,int rotationAngle) { BindWorldMatrix(rect,rotationAngle); cQuad.Draw(color); } void Canvas::DrawTexture(Texture * texture,Rect & destRect, Rect * srcRect, int rotationAngle) { BindWorldMatrix(destRect,rotationAngle); tQuad.Draw(texture,srcRect); } void Canvas::DrawLine(int x1,int y1,int x2,int y2,Color color) { BindWorldMatrix(); cLine.Draw(x1,y1,x2,y2,color); } void Canvas::DrawRect(Rect rect,Color color) { BindWorldMatrix(); cLine.Draw(rect.left,rect.top,rect.right,rect.top,color); cLine.Draw(rect.right,rect.top,rect.right,rect.bottom,color); cLine.Draw(rect.left,rect.top,rect.left,rect.bottom,color); cLine.Draw(rect.left,rect.bottom,rect.right,rect.bottom,color); } ID3D11Device * Canvas::GetDevice() { return device; } void Canvas::BindWorldMatrix(Rect & destRect,int rotationAngle) { XMMATRIX scale = XMMatrixScaling((float)(destRect.right - destRect.left),(float)(destRect.bottom - destRect.top),1.0f); XMMATRIX rotation = XMMatrixRotationZ(XMConvertToRadians((float)rotationAngle)); XMMATRIX translation = XMMatrixTranslation((float)destRect.left - (float)(width/2),(float)(height/2) - (float)destRect.top,0.0f); XMStoreFloat4x4(&mat.worldMatrix,XMMatrixTranspose(scale * rotation * translation)); D3D11_MAPPED_SUBRESOURCE map; context->Map(matrixBuffer,0,D3D11_MAP_WRITE_DISCARD,0,&map); memcpy(map.pData,&mat,sizeof(mat)); context->Unmap(matrixBuffer,0); } void Canvas::BindWorldMatrix() { XMMATRIX translation = XMMatrixTranslation(-(float)(width/2),(float)(height/2),0.0f); XMStoreFloat4x4(&mat.worldMatrix,XMMatrixTranspose(translation)); D3D11_MAPPED_SUBRESOURCE map; context->Map(matrixBuffer,0,D3D11_MAP_WRITE_DISCARD,0,&map); memcpy(map.pData,&mat,sizeof(mat)); context->Unmap(matrixBuffer,0); } void Canvas::BindWorlMatrix_Identity() { XMStoreFloat4x4(&mat.worldMatrix,XMMatrixIdentity()); D3D11_MAPPED_SUBRESOURCE map; context->Map(matrixBuffer,0,D3D11_MAP_WRITE_DISCARD,0,&map); memcpy(map.pData,&mat,sizeof(mat)); context->Unmap(matrixBuffer,0); }
26.213974
137
0.775112
dgi09
d97ba6d598c6bf6fb2e084606a3c1214fe97f695
2,838
hpp
C++
flightgoggles_ros_bridge/src/CameraModel/FisheyeModel.hpp
aau-cns/flightgoggles
7e194480b3852bd4ac34467222ffbbbaf9355b77
[ "BSD-2-Clause" ]
null
null
null
flightgoggles_ros_bridge/src/CameraModel/FisheyeModel.hpp
aau-cns/flightgoggles
7e194480b3852bd4ac34467222ffbbbaf9355b77
[ "BSD-2-Clause" ]
null
null
null
flightgoggles_ros_bridge/src/CameraModel/FisheyeModel.hpp
aau-cns/flightgoggles
7e194480b3852bd4ac34467222ffbbbaf9355b77
[ "BSD-2-Clause" ]
null
null
null
/// Copyright (C) 2020 Martin Scheiber, Control of Networked Systems, /// University of Klagenfurt, Austria. /// /// All rights reserved. /// /// This software is licensed under the terms of the BSD-2-Clause-License with /// no commercial use allowed, the full terms of which are made available in the /// LICENSE file. No license in patents is granted. /// /// You can contact the author at martin.scheiber@ieee.org #ifndef FISHEYEMODEL_H #define FISHEYEMODEL_H #include "CameraModel.hpp" class FisheyeCamera : public CameraModel { public: /// @name Parameter Struct /** * @brief The FisheyeParameters struct describes the parameters used in the fisheye model. */ struct FisheyeParameters { /// @name Parameters uint img_width; //!< resolution width uint img_height; //!< resolution height float fx; //!< focal length in x float fy; //!< focal length in y float cx; //!< center point in x float cy; //!< center point in y float s; //!< fisheye distortion parameter /// @name Precalculated Parameters float s_inv; //!< inverse fisheye distortion parameter float s_2tan; //!< two times tan of s \f$ 2 * \tan(\frac{s}{2}) \f$ float s_2tan_inv; //!< inverse of two times the tan of s /** * @brief setAdditional sets additional calculated parameters */ void setAdditional() { if (! s == 0) { s_inv = 1/s; s_2tan = 2.0 * std::tan(s / 2.0); s_2tan_inv = 1.0 / (s_2tan); } // if } // setAdditional() }; // struct FisheyeParameters /// @name Con-/Destructors FisheyeCamera(); ~FisheyeCamera(); /// @name Initial Calls virtual void setCameraParameters(const FisheyeParameters _parameters); virtual void setCameraParameters(const uint _img_width, const uint _img_height, const float _fx, const float _fy, const float _cx, const float _cy, const float _s); /// @name Image Modification virtual void applyDistortion(cv::Mat &_image_in, cv::Mat &_image_out, bool _force_dim=false); virtual void removeDistortion(cv::Mat &_image_in, cv::Mat &_image_out, bool _force_dim=false); virtual void applyDistortion(cv::Mat &_image); virtual void removeDistortion(cv::Mat &_image); /// @name Pixel Modification virtual cv::Point2f distortPixel(const cv::Point2f _P) const; virtual cv::Point2f undistortPixel(const cv::Point2f _pix) const; protected: private: /// @name Model Parameters // Static variables FisheyeParameters cam_parameters_; // Methods void updateLookups(); }; // class FisheyeCamera #endif
34.192771
118
0.621917
aau-cns
d9836b41c0950cae567dcab6e0db991ba636ef68
424
cpp
C++
1301-1400/1337-The K Weakest Rows in a Matrix/1337-The K Weakest Rows in a Matrix.cpp
jiadaizhao/LeetCode
4ddea0a532fe7c5d053ffbd6870174ec99fc2d60
[ "MIT" ]
49
2018-05-05T02:53:10.000Z
2022-03-30T12:08:09.000Z
1301-1400/1337-The K Weakest Rows in a Matrix/1337-The K Weakest Rows in a Matrix.cpp
jolly-fellow/LeetCode
ab20b3ec137ed05fad1edda1c30db04ab355486f
[ "MIT" ]
11
2017-12-15T22:31:44.000Z
2020-10-02T12:42:49.000Z
1301-1400/1337-The K Weakest Rows in a Matrix/1337-The K Weakest Rows in a Matrix.cpp
jolly-fellow/LeetCode
ab20b3ec137ed05fad1edda1c30db04ab355486f
[ "MIT" ]
28
2017-12-05T10:56:51.000Z
2022-01-26T18:18:27.000Z
class Solution { public: vector<int> kWeakestRows(vector<vector<int>>& mat, int k) { set<pair<int, int>> table; for (int i = 0; i < mat.size(); ++i) { table.insert({accumulate(mat[i].begin(), mat[i].end(), 0), i}); } vector<int> result; for (auto it = table.begin(); k-- > 0; ++it) { result.push_back(it->second); } return result; } };
28.266667
75
0.492925
jiadaizhao
d984496f46e4cafced078fdb6651e0e63ca97677
8,190
cpp
C++
OpenSees/SRC/reliability/analysis/telm/NonStatFirstPassageAnalyzer.cpp
kuanshi/ductile-fracture
ccb350564df54f5c5ec3a079100effe261b46650
[ "MIT" ]
null
null
null
OpenSees/SRC/reliability/analysis/telm/NonStatFirstPassageAnalyzer.cpp
kuanshi/ductile-fracture
ccb350564df54f5c5ec3a079100effe261b46650
[ "MIT" ]
null
null
null
OpenSees/SRC/reliability/analysis/telm/NonStatFirstPassageAnalyzer.cpp
kuanshi/ductile-fracture
ccb350564df54f5c5ec3a079100effe261b46650
[ "MIT" ]
1
2020-08-06T21:12:16.000Z
2020-08-06T21:12:16.000Z
// $Revision: 1.1 $ // $Date: 2008-02-29 19:43:53 $ // $Source: /usr/local/cvs/OpenSees/SRC/reliability/analysis/telm/NonStatFirstPassageAnalyzer.cpp,v $ #include <NonStatFirstPassageAnalyzer.h> NonStatFirstPassageAnalyzer::NonStatFirstPassageAnalyzer(ReliabilityDomain* passedReliabilityDomain, FindDesignPointAlgorithm* passedFindDesignPointAlgorithm, FunctionEvaluator* passedGFunEvaluator, FOSeriesSimulation* passedFOSeriesSimulation, int passedanalysisType, int passedinterpolationType, bool passedtwoside, bool passedprint) :FirstPassageAnalyzer(passedReliabilityDomain, passedFindDesignPointAlgorithm, passedGFunEvaluator, passedFOSeriesSimulation, passedanalysisType,passedtwoside) { interpolationType=passedinterpolationType; print=passedprint; if(print){ output.open("NonStatFirstPassageAnalyzer.txt", ios::out); output << "\n"; output << "NonStatFirstPassageAnalyzer::NonStatFirstPassageAnalyzer\n"; output << "\n"; output << "analysisType"<<analysisType<<"\n"; output << "numRV"<<numRV<<"\n"; output << "numrvpos"<<numRVPos<<"\n"; output << "detla"<<delta<<"\n"; output << "interpolationType"<<interpolationType<<"\n"; output.flush(); } FPprob=0; covres=0; betares=0; numSim=0; } NonStatFirstPassageAnalyzer::~NonStatFirstPassageAnalyzer() { if(FPprob!=0){delete FPprob; FPprob=0;} if(covres!=0){delete covres; covres=0;} if(betares!=0){delete betares; betares=0;} if(numSim!=0){delete [] numSim; numSim=0;} } Vector NonStatFirstPassageAnalyzer::componentFisrtPassage (Vector* pudes, Vector* pxdes, Vector* palpha, Vector* phfunc, double pbeta,double ppf, double panalysistime, int panalysisstep, TimePoints* passedTimePoints, int passedlsf, int passedidfragility, ofstream& outputFile) { this->setComponentResult(pudes, pxdes,palpha,phfunc, pbeta,ppf,panalysistime,panalysisstep, passedTimePoints, passedlsf,passedidfragility,false); if(print){ output << "\n"; output << "NonStatFirstPassageAnalyzer::componentFisrtPassage\n"; output << "\n"; output << "after setComponentResult\n"; output << "\n"; output << "numTimePoints "<<numTimePoints<<"\n"; output << "\n"; output << " seq. ID"<<" Time\n"; // output.setf( ios::scientific, ios::floatfield ); output.setf(ios::fixed, ios::floatfield); for(int i=0;i<=numTimePoints;i++){ output << setw(10) << i; output << setw(12) << setprecision(2) << (*timepoints)(i); output <<"\n"; } output.flush(); } outputFile <<"\n"; outputFile <<"-------------------------------------------------------------------\n"; outputFile <<"--- Component First-passage Probability Analysis(nonstationary) ---\n"; outputFile <<"-------------------------------------------------------------------\n"; outputFile <<"\n"; outputFile <<"Lsf......................................"<<passedlsf; outputFile <<"Fagility................................."<<passedidfragility; outputFile <<"\n"; outputFile <<"analysisType............................."<<analysisType; outputFile <<"twoside.................................."<<twoside; outputFile <<"\n"; if(analysisType==0){ this->componentFisrtPassage1(); outputFile <<"--- Integration of up-crossing rates ---\n"; outputFile <<"\n"; outputFile <<" Time"<<" Probability\n"; for(int i=0; i<numTimePoints; i++){ output.setf(ios::fixed, ios::floatfield); outputFile << setw(12) << setprecision(2) << (*timepoints)(i); output.setf( ios::scientific, ios::floatfield ); outputFile << setw(15) << setprecision(15) << (*FPprob)(i); outputFile<<"\n"; } }else{ this->componentFisrtPassage2(); outputFile <<"--- First Order Series System Simulation ---\n"; outputFile <<"\n"; outputFile <<" Time"<<" Probability"; outputFile <<" beta"<<" numsimulation"; outputFile <<" c.o.v"<<"\n"; for(int i=0; i<numTimePoints; i++){ output.setf(ios::fixed, ios::floatfield); outputFile << setw(12) << setprecision(2) << (*timepoints)(i); output.setf( ios::scientific, ios::floatfield ); outputFile << setw(15) << setprecision(15) << (*FPprob)(i); outputFile << setw(15) << setprecision(15) << (*betares)(i); outputFile << setw(15) << numSim[i]; outputFile << setw(15) << setprecision(15) << (*covres)(i); outputFile<<"\n"; } } return (*FPprob); } void NonStatFirstPassageAnalyzer::componentFisrtPassage2() { opserr<< " NonStatFirstPassageAnalyzer::componentFisrtPassage2 \n"; opserr<< " This function is not implemented yet\n"; opserr<< " return zeros\n"; if(FPprob!=0){ delete FPprob; FPprob=0; } FPprob=new Vector(numTimePoints+1); if(FPprob==0){ opserr<<" insufficient memory \n"; opserr<<" NonStatFirstPassageAnalyzer::componentFisrtPassage1\n"; opserr<<" allocation of FPprob\n"; } } void NonStatFirstPassageAnalyzer::systemFisrtPassage() { opserr<< " NonStatFirstPassageAnalyzer::systemFisrtPassage \n"; opserr<< " This function is not implemented yet\n"; opserr<< " return zeros\n"; } void NonStatFirstPassageAnalyzer::componentFisrtPassage1() { /* if(FPprob!=0){ delete FPprob; FPprob=0; } FPprob=new Vector(numTimePoints+1); if(FPprob==0){ opserr<<" insufficient memory \n"; opserr<<" NonStatFirstPassageAnalyzer::componentFisrtPassage1\n"; opserr<<" allocation of FPprob\n"; } Vector* nupt = new Vector(numTimePoints+1); if(nupt==0){ opserr<<" insufficient memory \n"; opserr<<" NonStatFirstPassageAnalyzer::componentFisrtPassage1\n"; opserr<<" allocation of nupt\n"; } for( int i=0;i<=numTimePoints;i++) (*nupt)(i)=theOutCrossingResult->getnu(i); if(print){ output << "\n"; output << "NonStatFirstPassageAnalyzer::componentFisrtPassage1\n"; output << "\n"; output << " seq. ID"<<" time"<<" nu\n"; output.setf( ios::scientific, ios::floatfield ); // output.setf(ios::fixed, ios::floatfield); for(int i=0;i<=numTimePoints;i++){ output << setw(10) << i; output << setw(15) << setprecision(5) << (*timepoints)(i); output << setw(15) << setprecision(5) << (*nupt)(i); output <<"\n"; } output.flush(); } double timeleft=0.0; double nuleft=0.0; double timeright; double nuright; double time0=(*timepoints)(0); double nu0=(*nupt)(0); double fp; double nuintegral=0.0; double amp=1.0; if(twoside) amp=2.0; for(int i=1;i<=numTimePoints;i++){ if(time0>timeleft && time0< (*timepoints)(i)){ timeright=time0; nuright=nu0; nuintegral+=(nuleft+nuright)*(timeright-timeleft)/2.0; fp=1.0-exp(-nuintegral); (*FPprob)(0)=fp*amp; if(print){ output<<"\n"; output<<"time0>timeleft && time0< (*timepoints)(i)-1-\n"; output<<"timeleft "<<timeleft<<" timeright "<<timeright<<"\n"; output<<"nuleft "<<nuleft<<" nuright "<<nuright<<"\n"; output<<"nuintegral "<<nuintegral<<" fp "<<fp<<"\n"; output.flush(); } timeleft=time0; nuleft=nu0; timeright=(*timepoints)(i); nuright=(*nupt)(i); nuintegral+=(nuleft+nuright)*(timeright-timeleft)/2.0; fp=1.0-exp(-nuintegral); (*FPprob)(i)=fp*amp; if(print){ output<<"time0>timeleft && time0< (*timepoints)(i)-2-\n"; output<<"\n"; output<<"timeleft "<<timeleft<<" timeright "<<timeright<<"\n"; output<<"nuleft "<<nuleft<<" nuright "<<nuright<<"\n"; output<<"nuintegral "<<nuintegral<<" fp "<<fp<<"\n"; output.flush(); } }else{ timeright=(*timepoints)(i); nuright=(*nupt)(i); nuintegral+=(nuleft+nuright)*(timeright-timeleft)/2.0; fp=1.0-exp(-nuintegral); (*FPprob)(i)=fp*amp; if(print){ output<<"timeleft "<<timeleft<<" timeright "<<timeright<<"\n"; output<<"nuleft "<<nuleft<<" nuright "<<nuright<<"\n"; output<<"nuintegral "<<nuintegral<<" fp "<<fp<<"\n"; output.flush(); } } timeleft=timeright; nuleft=nuright; } if(time0 > (*timepoints)(numTimePoints)){ timeright=time0; nuright=nu0; nuintegral+=(nuleft+nuright)*(timeright-timeleft)/2.0; fp=1.0-exp(-nuintegral); (*FPprob)(0)=fp*amp; } delete nupt; nupt=0; */ }
32.891566
101
0.626496
kuanshi
d98ce65fda9867a9f10ab86e3e15f0b90d25ada8
7,171
cpp
C++
video.cpp
jwatte/viewtune
3433ed1793c8a2209a615700e8574e509ab38a0e
[ "MIT" ]
null
null
null
video.cpp
jwatte/viewtune
3433ed1793c8a2209a615700e8574e509ab38a0e
[ "MIT" ]
null
null
null
video.cpp
jwatte/viewtune
3433ed1793c8a2209a615700e8574e509ab38a0e
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "video.h" #include "riffs.h" #include <vector> #include <stdio.h> extern "C" { #pragma warning(disable: 4244) #pragma warning(disable: 4996) #include <libavformat/avformat.h> #include <libavcodec/avcodec.h> #include <libavutil/mem.h> #include <libavutil/buffer.h> #include <libavutil/log.h> } #pragma comment(lib, "avcodec.lib") #pragma comment(lib, "avformat.lib") #pragma comment(lib, "avutil.lib") bool verbose = false; bool firstTime = true; class Decoder { public: bool begin_decode(VideoFrame *frame); VideoFrame *decode_frame_and_advance(VideoFrame *frame, DecodedFrame *result, VideoFrame *(*next_frame)(VideoFrame *, void *), void *); Decoder(); ~Decoder(); AVCodec *codec; AVCodecContext *ctx = 0; AVFrame *frame = 0; AVCodecParserContext *parser = 0; AVPacket avp = { 0 }; int frameno = 0; uint64_t ptsbase = 0; uint64_t dtsbase = 0; std::vector<char> readBuf; }; Decoder::Decoder() { if (firstTime) { avcodec_register_all(); firstTime = false; if (verbose) { av_log_set_level(99); } } } Decoder::~Decoder() { // todo: deallocate libav } bool Decoder::begin_decode(VideoFrame *) { readBuf.clear(); codec = avcodec_find_decoder(AV_CODEC_ID_H264); if (!codec) { fprintf(stderr, "avcodec_find_decoder(): h264 not found\n"); return false; } ctx = avcodec_alloc_context3(codec); if (!ctx) { fprintf(stderr, "avcodec_alloc_context3(): failed to allocate\n"); return false; } ctx->flags2 |= AV_CODEC_FLAG2_CHUNKS; if (avcodec_open2(ctx, codec, NULL) < 0) { fprintf(stderr, "avcodec_open2(): failed to open\n"); return false; } frame = av_frame_alloc(); if (!frame) { fprintf(stderr, "av_frame_alloc(): alloc failed\n"); return false; } parser = av_parser_init(AV_CODEC_ID_H264); if (!parser) { fprintf(stderr, "av_parser_init(): h264 failed\n"); return false; } memset(&avp, 0, sizeof(avp)); av_init_packet(&avp); // loop frameno = 0; ptsbase = 0; dtsbase = 0; avp.data = NULL; avp.size = 0; return true; } VideoFrame *Decoder::decode_frame_and_advance(VideoFrame *indata, DecodedFrame *result, VideoFrame *(*next_frame)(VideoFrame *, void *), void *cookie) { bool kf = false; uint64_t t = indata->time; parse_more: if (!indata) { return nullptr; } indata->file->data_at(indata->offset, readBuf); if (indata->keyframe) { kf = true; } avp.pts = indata->pts; avp.dts = indata->pts; int lenParsed = av_parser_parse2(parser, ctx, &avp.data, &avp.size, (unsigned char *)&readBuf[0], readBuf.size(), avp.pts, avp.dts, avp.pos); if (verbose) { fprintf(stderr, "av_parser_parse2(): offset %lld lenParsed %d size %d pointer %p readbuf 0x%p\n", (long long)indata->offset, lenParsed, avp.size, avp.data, &readBuf[0]); } if (lenParsed) { indata = next_frame(indata, cookie); } if (avp.size) { int lenSent = avcodec_send_packet(ctx, &avp); if (lenSent < 0) { if (verbose) { fprintf(stderr, "avcodec_send_packet(): error %d at concatoffset %ld\n", lenSent, (long)avp.pos); } } avp.pos += avp.size; int err = avcodec_receive_frame(ctx, frame); if (err == 0) { // got a frame! result->time = t; result->width = 640; result->height = 480; if (!result->yuv_planar) { result->yuv_planar = new unsigned char[640 * 480 + 320 * 240 * 2]; } for (int r = 0; r != 480; ++r) { memcpy(result->yuv_planar + result->width * r, frame->data[0] + frame->linesize[0] * r, 640); } unsigned char *du = result->yuv_planar + 640 * 480; for (int r = 0; r != 240; ++r) { memcpy(du + 320 * r, frame->data[1] + frame->linesize[1] * r, 320); } unsigned char *dv = result->yuv_planar + 640 * 480 + 320 * 240; for (int r = 0; r != 240; ++r) { memcpy(dv + 320 * r, frame->data[2] + frame->linesize[2] * r, 320); } result->set_decoded(t, 640, 480, result->yuv_planar, kf); ++frameno; if (ctx->refcounted_frames) { av_frame_unref(frame); } if (lenParsed > 0) { readBuf.erase(readBuf.begin(), readBuf.begin() + lenParsed); } else { readBuf.clear(); // didn't advance frame pointers } goto ret; } else if (err == AVERROR(EAGAIN)) { // nothing for now } else if (err == AVERROR_EOF) { // nothing for now } else { // not a header if (indata->size > 128) { if (verbose) { fprintf(stderr, "avcodec_receive_frame() error %d offset %ld file %s\n", err, (long)indata->offset, indata->file->path_.string().c_str()); } // return false; } } } if (lenParsed > 0) { readBuf.erase(readBuf.begin(), readBuf.begin() + lenParsed); goto parse_more; } else { readBuf.clear(); // didn't advance frame pointers } // it didn't consume any data, yet it didn't return a frame? fprintf(stderr, "ERROR in parser: lenParsed is 0 but no frame found index %d offset %lld file %s\n", indata->index, (long long)indata->offset, indata->file->path_.string().c_str()); return nullptr; ret: return indata; } Decoder *gDecoder; void begin_decode(VideoFrame *frame) { delete gDecoder; gDecoder = new Decoder(); gDecoder->begin_decode(frame); } static VideoFrame *static_next_frame(VideoFrame *indata, void *) { if (indata->index + 1 >= gFrames.size()) { indata = nullptr; } else { indata = &gFrames[indata->index + 1]; } return indata; } VideoFrame *decode_frame_and_advance(VideoFrame *frame, DecodedFrame *result) { return gDecoder->decode_frame_and_advance(frame, result, static_next_frame, nullptr); } struct decoder_t *new_decoder() { Decoder *dec = new Decoder(); dec->begin_decode(nullptr); return (decoder_t *)dec; } VideoFrame *decode_frame_and_advance(decoder_t *decoder, VideoFrame *frame, DecodedFrame *result, VideoFrame *(next_frame)(VideoFrame *, void *), void *cookie) { Decoder *dec = (Decoder *)decoder; return dec->decode_frame_and_advance(frame, result, next_frame, cookie); } void destroy_decoder(struct decoder_t *dec) { delete (Decoder *)dec; }
30.004184
110
0.550132
jwatte
d98e9cd474e56764b7c8516ffff317532617f137
974
cpp
C++
ZenUnitLibraryTests/EqualizersAndRandoms/TestRunResultEqualizerAndRandomTests.cpp
NeilJustice/ZenUnit
6ddbe157e4652ac76aa074a70f9f83e34ee779df
[ "MIT" ]
2
2018-04-21T06:38:53.000Z
2018-08-31T00:56:21.000Z
ZenUnitLibraryTests/EqualizersAndRandoms/TestRunResultEqualizerAndRandomTests.cpp
NeilJustice/ZenUnitAndZenMock
bbcb4221d063fa04e4ef3a98143e0f123e3af8d5
[ "MIT" ]
1
2021-03-03T07:19:16.000Z
2021-03-28T21:46:32.000Z
ZenUnitLibraryTests/EqualizersAndRandoms/TestRunResultEqualizerAndRandomTests.cpp
NeilJustice/ZenUnitAndZenMock
bbcb4221d063fa04e4ef3a98143e0f123e3af8d5
[ "MIT" ]
null
null
null
#include "pch.h" #include "ZenUnitTestUtils/EqualizersAndRandoms/TestRunResultEqualizerAndRandom.h" namespace ZenUnit { TESTS(TestRunResultEqualizerAndRandomTests) AFACT(ZenUnitEqualizer_ThrowsIfAnyFieldNotEqual) EVIDENCE TEST(ZenUnitEqualizer_ThrowsIfAnyFieldNotEqual) { ZENUNIT_EQUALIZER_TEST_SETUP(TestRunResult); ZENUNIT_EQUALIZER_THROWS_WHEN_FIELD_NOT_EQUAL(TestRunResult, _numberOfFailedTestCases, ZenUnit::RandomNon0<size_t>()); ZENUNIT_EQUALIZER_THROWS_WHEN_FIELD_NOT_EQUAL(TestRunResult, _skippedFullTestNamesAndSkipReasons, ZenUnit::RandomNonEmptyVector<string>()); ZENUNIT_EQUALIZER_THROWS_WHEN_FIELD_NOT_EQUAL(TestRunResult, _skippedTestClassNamesAndSkipReasons, ZenUnit::RandomNonEmptyVector<string>()); ZENUNIT_EQUALIZER_THROWS_WHEN_FIELD_NOT_EQUAL(TestRunResult, _testClassResults, ZenUnit::RandomNonEmptyVector<TestClassResult>()); } RUN_TESTS(TestRunResultEqualizerAndRandomTests) }
46.380952
147
0.824435
NeilJustice
d99218e47bd6535383e54e5ac49519f1fd2626ae
1,350
hpp
C++
deployment/configenv/xml_jlibpt/ConfigEnvFactory.hpp
davidarcher/HPCC-Platform
fa817ab9ea7d8154ac08bc780ce9ce673f3e51e3
[ "Apache-2.0" ]
286
2015-01-03T12:45:17.000Z
2022-03-25T18:12:57.000Z
deployment/configenv/xml_jlibpt/ConfigEnvFactory.hpp
davidarcher/HPCC-Platform
fa817ab9ea7d8154ac08bc780ce9ce673f3e51e3
[ "Apache-2.0" ]
9,034
2015-01-02T08:49:19.000Z
2022-03-31T20:34:44.000Z
deployment/configenv/xml_jlibpt/ConfigEnvFactory.hpp
cloLN/HPCC-Platform
42ffb763a1cdcf611d3900831973d0a68e722bbe
[ "Apache-2.0" ]
208
2015-01-02T03:27:28.000Z
2022-02-11T05:54:52.000Z
/*############################################################################## HPCC SYSTEMS software Copyright (C) 2018 HPCC Systems®. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ############################################################################## */ #ifndef _CONFIGENVFACTORY_HPP_ #define _CONFIGENVFACTORY_HPP_ #include <cstddef> #include "jiface.hpp" #include "jliball.hpp" #include "IConfigEnv.hpp" #include "ConfigEnv.hpp" interface IPropertyTree; //interface IConfigEnv<IPropertyTree, StringBuffer>; //interface IConfigComp; namespace ech { //template<class PTTYPE, class SB> class configenv_decl ConfigEnvFactory { public: static IConfigEnv<IPropertyTree, StringBuffer> * getIConfigEnv(IPropertyTree *config); static void destroy(IConfigEnv<IPropertyTree, StringBuffer> * iCfgEnv); }; } #endif
29.347826
90
0.66963
davidarcher
d99220c4343da522edb4e2580575a7cc271d3adc
2,400
cpp
C++
game/source/src/Projectile_creator.cpp
mateusgondim/Demos
6aa5da3a6c0e960d10811c9e71e9a0a746e8d6ab
[ "MIT" ]
5
2019-02-12T07:23:55.000Z
2020-06-22T15:03:36.000Z
game/source/src/Projectile_creator.cpp
mateusgondim/Demos
6aa5da3a6c0e960d10811c9e71e9a0a746e8d6ab
[ "MIT" ]
null
null
null
game/source/src/Projectile_creator.cpp
mateusgondim/Demos
6aa5da3a6c0e960d10811c9e71e9a0a746e8d6ab
[ "MIT" ]
2
2019-06-17T05:04:21.000Z
2020-04-22T09:05:57.000Z
#include "Projectile_creator.hpp" #include "Creator.hpp" #include "Game_object.hpp" #include "Projectile.hpp" #include "vec2.hpp" #include "vec3.hpp" #include "AABB_2d.hpp" #include "Animator_controller.hpp" #include "Animator_state.hpp" #include "Sprite_atlas.hpp" #include "Sprite_atlas_manager.hpp" #include "string_id.hpp" #include "Collider_2d_def.hpp" #include "Body_2d_def.hpp" #include "runtime_memory_allocator.hpp" #include "Object.hpp" #include <utility> Projectile_creator::Projectile_creator(const string_id atlas_id, const physics_2d::Body_2d_def & body_def, const gfx::Animator_controller *panim_controller) : gom::Creator(), m_atlas_res_id(atlas_id) { //create body_2d_def void *pmem = mem::allocate(sizeof(physics_2d::Body_2d_def)); if (pmem != nullptr) { m_pbody_def = static_cast<physics_2d::Body_2d_def*>( new (pmem) physics_2d::Body_2d_def(body_def)); } //makea copy of this anim controller pmem = mem::allocate(sizeof(gfx::Animator_controller)); m_pcontroller = static_cast<gfx::Animator_controller*>(new (pmem) gfx::Animator_controller(*panim_controller)); } gom::Game_object *Projectile_creator::create(const Object & obj_description) { //get the data to create sprite component gfx::Sprite_atlas *patlas = static_cast<gfx::Sprite_atlas*>(gfx::g_sprite_atlas_mgr.get_by_id(m_atlas_res_id)); gom::Projectile::atlas_n_layer data(patlas, 1); math::vec3 wld_pos(obj_description.get_x(), obj_description.get_y()); math::vec2 translation = math::vec2(wld_pos.x, wld_pos.y) - m_pbody_def->m_position; m_pbody_def->m_position += translation; m_pbody_def->m_aabb.p_max += translation; m_pbody_def->m_aabb.p_min += translation; physics_2d::Collider_2d_def coll_def; coll_def.m_aabb = m_pbody_def->m_aabb; std::size_t object_sz = sizeof(gom::Projectile); void *pmem = mem::allocate(object_sz); gom::Game_object *pgame_object = static_cast<gom::Game_object*>( new (pmem) gom::Projectile(object_sz, wld_pos, data, m_pbody_def, m_pcontroller)); pgame_object->get_body_2d_component()->create_collider_2d(coll_def); pgame_object->set_type(m_obj_type); pgame_object->set_tag(m_obj_tag); return pgame_object; } Projectile_creator::~Projectile_creator() { mem::free(static_cast<void*>(m_pcontroller), sizeof(gfx::Animator_controller)); }
33.333333
112
0.7375
mateusgondim
d99259c7aed9cf5a3cab45f52f29942bb24d3f0d
987
hpp
C++
library/ATF/GUILD_BATTLE__CGuildBattleRewardItem.hpp
lemkova/Yorozuya
f445d800078d9aba5de28f122cedfa03f26a38e4
[ "MIT" ]
29
2017-07-01T23:08:31.000Z
2022-02-19T10:22:45.000Z
library/ATF/GUILD_BATTLE__CGuildBattleRewardItem.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
90
2017-10-18T21:24:51.000Z
2019-06-06T02:30:33.000Z
library/ATF/GUILD_BATTLE__CGuildBattleRewardItem.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 <CPlayer.hpp> #include <_base_fld.hpp> START_ATF_NAMESPACE namespace GUILD_BATTLE { #pragma pack(push, 8) struct CGuildBattleRewardItem { char m_ucD; char m_ucTableCode; _base_fld *m_pFld; public: CGuildBattleRewardItem(); void ctor_CGuildBattleRewardItem(); char GetAmount(); char* GetItemCode(); struct CGuildBattleRewardItem* Give(struct CPlayer* pkPlayer); bool Init(uint16_t usInx); bool IsNull(); bool SetItem(char* szItemCode); }; #pragma pack(pop) static_assert(ATF::checkSize<GUILD_BATTLE::CGuildBattleRewardItem, 16>(), "GUILD_BATTLE::CGuildBattleRewardItem"); }; // end namespace GUILD_BATTLE END_ATF_NAMESPACE
30.84375
122
0.628166
lemkova
d993329a5cea357b30f8b41f680a090dc4745805
2,078
hpp
C++
nes_py/nes/include/mappers/mapper_NROM.hpp
lucasschoenhold/nes-py
7de04f48e928cf96ba0976ee61def5958aaa759d
[ "MIT" ]
128
2018-07-22T03:31:42.000Z
2022-03-28T13:17:04.000Z
nes_py/nes/include/mappers/mapper_NROM.hpp
lucasschoenhold/nes-py
7de04f48e928cf96ba0976ee61def5958aaa759d
[ "MIT" ]
35
2018-07-20T16:37:23.000Z
2022-02-04T00:37:23.000Z
nes_py/nes/include/mappers/mapper_NROM.hpp
lucasschoenhold/nes-py
7de04f48e928cf96ba0976ee61def5958aaa759d
[ "MIT" ]
31
2019-02-19T10:56:22.000Z
2022-01-15T19:32:52.000Z
// Program: nes-py // File: mapper_NROM.hpp // Description: An implementation of the NROM mapper // // Copyright (c) 2019 Christian Kauten. All rights reserved. // #ifndef MAPPERNROM_HPP #define MAPPERNROM_HPP #include <vector> #include "common.hpp" #include "mapper.hpp" namespace NES { class MapperNROM : public Mapper { private: /// whether there are 1 or 2 banks bool is_one_bank; /// whether this mapper uses character RAM bool has_character_ram; /// the character RAM on the mapper std::vector<NES_Byte> character_ram; public: /// Create a new mapper with a cartridge. /// /// @param cart a reference to a cartridge for the mapper to access /// explicit MapperNROM(Cartridge* cart); /// Read a byte from the PRG RAM. /// /// @param address the 16-bit address of the byte to read /// @return the byte located at the given address in PRG RAM /// inline NES_Byte readPRG(NES_Address address) { if (!is_one_bank) return cartridge->getROM()[address - 0x8000]; else // mirrored return cartridge->getROM()[(address - 0x8000) & 0x3fff]; } /// Write a byte to an address in the PRG RAM. /// /// @param address the 16-bit address to write to /// @param value the byte to write to the given address /// void writePRG(NES_Address address, NES_Byte value); /// Read a byte from the CHR RAM. /// /// @param address the 16-bit address of the byte to read /// @return the byte located at the given address in CHR RAM /// inline NES_Byte readCHR(NES_Address address) { if (has_character_ram) return character_ram[address]; else return cartridge->getVROM()[address]; } /// Write a byte to an address in the CHR RAM. /// /// @param address the 16-bit address to write to /// @param value the byte to write to the given address /// void writeCHR(NES_Address address, NES_Byte value); }; } // namespace NES #endif // MAPPERNROM_HPP
27.706667
71
0.637151
lucasschoenhold
d997ee70695ea7a074225cf474de6e0e77787952
8,297
cpp
C++
wbsModels/Climatic/VaporPressureDeficit.cpp
RNCan/WeatherBasedSimulationFramework
19df207d11b1dddf414d78e52bece77f31d45df8
[ "MIT" ]
6
2017-05-26T21:19:41.000Z
2021-09-03T14:17:29.000Z
wbsModels/Climatic/VaporPressureDeficit.cpp
RNCan/WeatherBasedSimulationFramework
19df207d11b1dddf414d78e52bece77f31d45df8
[ "MIT" ]
5
2016-02-18T12:39:58.000Z
2016-03-13T12:57:45.000Z
wbsModels/Climatic/VaporPressureDeficit.cpp
RNCan/WeatherBasedSimulationFramework
19df207d11b1dddf414d78e52bece77f31d45df8
[ "MIT" ]
1
2019-06-16T02:49:20.000Z
2019-06-16T02:49:20.000Z
//********************************************************************** // 11/09/2018 1.1.1 Rémi Saint-Amant Bug correction in units. return VPD in [hPa] // 20/09/2016 1.1.0 Rémi Saint-Amant Change Tair and Trng by Tmin and Tmax // 21/01/2016 1.0.0 Rémi Saint-Amant Using Weather-based simulation framework (WBSF) //********************************************************************** #include <iostream> #include "Basic/UtilTime.h" #include "Basic/UtilMath.h" #include "ModelBase/EntryPoint.h" #include "VaporPressureDeficit.h" using namespace std; using namespace WBSF::HOURLY_DATA; namespace WBSF { //this line link this model with the EntryPoint of the DLL static const bool bRegistred = CModelFactory::RegisterModel(CVPDModel::CreateObject); //Saturation vapor pressure at daylight temperature static double GetDaylightVaporPressureDeficit(const CWeatherYear& weather); static double GetDaylightVaporPressureDeficit(const CWeatherMonth& weather); static double GetDaylightVaporPressureDeficit(const CWeatherDay& weather); static double GetVPD(const CWeatherYear& weather); static double GetVPD(const CWeatherMonth& weather); static double GetVPD(const CWeatherDay& weather); enum TAnnualStat{ O_DAYLIGHT_VPD, O_MEAN_VPD, NB_OUTPUTS }; //Contructor CVPDModel::CVPDModel() { //specify the number of input parameter NB_INPUT_PARAMETER = 0; VERSION = "1.1.1 (2018)"; } CVPDModel::~CVPDModel() {} //This method is call to load your parameter in your variable ERMsg CVPDModel::ProcessParameters(const CParameterVector& parameters) { ERMsg msg; return msg; } ERMsg CVPDModel::OnExecuteAnnual() { ERMsg msg; CTPeriod p = m_weather.GetEntireTPeriod(CTM(CTM::ANNUAL)); m_output.Init(p, NB_OUTPUTS, -9999); for (size_t y = 0; y < m_weather.GetNbYears(); y++) { double daylightVPD = GetDaylightVaporPressureDeficit(m_weather[y]); //[kPa] double VPD = m_weather[y][H_VPD][MEAN]; //[kPa] m_output[y][O_DAYLIGHT_VPD] = daylightVPD*10;//kPa --> hPa m_output[y][O_MEAN_VPD] = VPD*10;//kPa --> hPa } return msg; } ERMsg CVPDModel::OnExecuteMonthly() { ERMsg msg; CTPeriod p = m_weather.GetEntireTPeriod(CTM(CTM::MONTHLY)); m_output.Init(p, NB_OUTPUTS, -9999); for (size_t y = 0; y<m_weather.GetNbYears(); y++) { for (size_t m = 0; m<12; m++) { double daylightVPD = GetDaylightVaporPressureDeficit(m_weather[y][m]); //[kPa] double VPD = GetVPD(m_weather[y][m]); //[kPa] m_output[y * 12 + m][O_DAYLIGHT_VPD] = daylightVPD*10;//kPa --> hPa m_output[y * 12 + m][O_MEAN_VPD] = VPD*10;//kPa --> hPa } } return msg; } ERMsg CVPDModel::OnExecuteDaily() { ERMsg msg; CTPeriod p = m_weather.GetEntireTPeriod(CTM(CTM::DAILY)); m_output.Init(p, NB_OUTPUTS, -9999); for (size_t y = 0; y<m_weather.size(); y++) { for (size_t m = 0; m<m_weather[y].size(); m++) { for (size_t d = 0; d<m_weather[y][m].size(); d++) { const CWeatherDay& wDay = m_weather[y][m][d]; double daylightVPD = GetDaylightVaporPressureDeficit(wDay); //[kPa] double VPD = GetVPD(wDay);//[kPa] CTRef ref = m_weather[y][m][d].GetTRef(); m_output[ref][O_DAYLIGHT_VPD] = daylightVPD*10;//kPa --> hPa m_output[ref][O_MEAN_VPD] = VPD*10;//kPa --> hPa } } } return msg; } ERMsg CVPDModel::OnExecuteHourly() { ERMsg msg; if (!m_weather.IsHourly()) m_weather.ComputeHourlyVariables(); CTPeriod p = m_weather.GetEntireTPeriod(CTM::HOURLY); m_output.Init(p, NB_OUTPUTS, -9999); CSun sun(m_weather.m_lat, m_weather.m_lon); for (size_t y = 0; y<m_weather.size(); y++) { for (size_t m = 0; m<m_weather[y].size(); m++) { for (size_t d = 0; d<m_weather[y][m].size(); d++) { for (size_t h = 0; h < m_weather[y][m][d].size(); h++) { const CHourlyData& wHour = m_weather[y][m][d][h]; double VPD = max(0.0f, wHour[H_ES] - wHour[H_EA] )*10;//kPa --> hPa CTRef ref = m_weather[y][m][d][h].GetTRef(); size_t sunrise = Round(sun.GetSunrise(ref)); size_t sunset = min(23ll, Round(sun.GetSunset(ref))); double daylightVPD = (h >= sunrise && h <= sunset) ? VPD : -9999; m_output[ref][O_DAYLIGHT_VPD] = daylightVPD;//hPa m_output[ref][O_MEAN_VPD] = VPD;//hPa } } } } return msg; } //Saturation vapor pressure at daylight temperature [kPa] double GetDaylightVaporPressureDeficit(const CWeatherYear& weather) { CStatistic stat; for (size_t m = 0; m < weather.size(); m++) stat += GetDaylightVaporPressureDeficit(weather[m]); return stat[MEAN]; } //Saturation vapor pressure at daylight temperature [kPa] double GetDaylightVaporPressureDeficit(const CWeatherMonth& weather) { CStatistic stat; for (size_t d = 0; d < weather.size(); d++) stat += GetDaylightVaporPressureDeficit(weather[d]); return stat[MEAN]; } //Saturation vapor pressure at daylight temperature [kPa] double GetDaylightVaporPressureDeficit(const CWeatherDay& weather) { CStatistic VPD; if (weather.IsHourly()) { CSun sun(weather.GetLocation().m_lat, weather.GetLocation().m_lon); size_t sunrise = Round(sun.GetSunrise(weather.GetTRef())); size_t sunset = min(23ll, Round(sun.GetSunset(weather.GetTRef()))); for (size_t h = sunrise; h <= sunset; h++) VPD += max(0.0f, weather[h][H_ES] - weather[h][H_EA]); } else { double daylightT = weather.GetTdaylight(); double daylightEs = eᵒ(daylightT);//kPa // *1000; //by RSA 11-09-2018 kPa instead of Pa VPD += max(0.0, daylightEs - weather[H_EA][MEAN]); //double Dmax = eᵒ(weather[H_TMAX]) - eᵒ(weather[H_TMIN]); //VPD += 2.0 / 3.0*Dmax; //VPD += max(0.0, weather[H_ES][MEAN] - weather[H_EA][MEAN]); } return VPD[MEAN]; } //return vapor pressure deficit [kPa] static double GetVPD(const CWeatherYear& weather) { CStatistic stat; for (size_t m = 0; m < weather.size(); m++) stat += GetVPD(weather[m]); return stat[MEAN]; } //return vapor pressure deficit [kPa] static double GetVPD(const CWeatherMonth& weather) { CStatistic stat; for (size_t d = 0; d < weather.size(); d++) stat += GetVPD(weather[d]); return stat[MEAN]; } /*double ʃ(double Tᴰ, double Tᴸ, double Tᴴ ) { ASSERT(Tᴰ <= Tᴸ); ASSERT(Tᴸ <= Tᴴ); double sum=0; for (size_t i = 0; i <= 100; i++) { double T = Tᴸ + i*(Tᴴ - Tᴸ) / 100.0; sum += eᵒ(T) - eᵒ(Tᴰ); } return sum; }*/ double ʃ(double Tᴰ, double T) { ASSERT(Tᴰ <= T); return eᵒ(T) - eᵒ(Tᴰ); } // Function to evalute the value of integral double trapezoidal(double Tᴰ, double Tᴸ, double Tᴴ, int n = 100) { // Grid spacing double h = (Tᴴ - Tᴸ) / n; // Computing sum of first and last terms // in above formula double s = ʃ(Tᴰ, Tᴸ) + ʃ(Tᴰ, Tᴴ); // Adding middle terms in above formula for (int i = 1; i < n; i++) s += 2 * ʃ(Tᴰ, Tᴸ + i * h); // h/2 indicates (b-a)/2n. Multiplying h/2 // with s. return (h / 2)*s; } //return vapor pressure deficit [kPa] static double GetVPD(const CWeatherDay& weather) { CStatistic stat; if (weather.IsHourly()) { for (size_t h = 0; h < 24; h++) stat += max(0.0f, weather[h][H_ES] - weather[h][H_EA]); } else { stat += max(0.0, weather[H_ES][MEAN] - weather[H_EA][MEAN]); //test from Castellvi(1996) /* double Tᴰ = eᵒ(weather[H_TDEW][MEAN]); double Tn = eᵒ(weather[H_TMIN][MEAN]); double Tx = eᵒ(weather[H_TMAX][MEAN]); double Ta = (Tn+Tx)/2; if (Tᴰ < Tn && Tn < Tx) { double a = trapezoidal(Tᴰ, Tn, Ta); double b = trapezoidal(Tᴰ, Tn, Tx); ASSERT(a/b > 0 && a/b<=1); while (abs(0.5 - a/b)> 0.001) { Ta += (0.5-a/b)*(Tx-Tn); ASSERT(Ta >= Tn && Ta <= Tx); a = trapezoidal(Tᴰ, Tn, Ta); ASSERT(a / b >= 0 && a / b <= 1); } } double h = std::max(1.0, std::min(100.0, weather[H_RELH][MEAN])); stat += eᵒ(Ta)*(1- h /100.0); */ } return stat[MEAN]; } }
25.45092
91
0.60082
RNCan
d99e0fc329d535d7938e7ddc4049be67845d0a17
18,085
hpp
C++
inc/state/thrdcmdpool.hpp
nicoboss/vuda
9e0e254dd6a37d418292e1e949fdf33262f008e9
[ "MIT" ]
422
2018-10-08T04:58:20.000Z
2022-03-23T10:31:25.000Z
inc/state/thrdcmdpool.hpp
nicoboss/vuda
9e0e254dd6a37d418292e1e949fdf33262f008e9
[ "MIT" ]
18
2018-10-10T20:45:43.000Z
2021-11-28T08:36:37.000Z
inc/state/thrdcmdpool.hpp
nicoboss/vuda
9e0e254dd6a37d418292e1e949fdf33262f008e9
[ "MIT" ]
24
2018-10-08T11:11:49.000Z
2022-02-18T01:07:42.000Z
#pragma once namespace vuda { namespace detail { class thrdcmdpool { //friend class logical_device; public: /* For each thread that sets/uses the device a single command pool is created - this pool have m_queueComputeCount command buffers allocated. This way, - VkCommandBuffers are allocated from a "parent" VkCommandPool - VkCommandBuffers written to in different threads must come from different pools ======================================================= command buffers \ threads : 0 1 2 3 4 ... #n 0 1 . . . m_queueComputeCount ======================================================= */ thrdcmdpool(const vk::UniqueDevice& device, const uint32_t queueFamilyIndex, const uint32_t queueComputeCount) : m_commandPool(device->createCommandPoolUnique(vk::CommandPoolCreateInfo(vk::CommandPoolCreateFlags(vk::CommandPoolCreateFlagBits::eResetCommandBuffer), queueFamilyIndex))), m_commandBuffers(device->allocateCommandBuffersUnique(vk::CommandBufferAllocateInfo(m_commandPool.get(), vk::CommandBufferLevel::ePrimary, queueComputeCount))), m_commandBufferState(queueComputeCount, cbReset), m_queryPool(device->createQueryPoolUnique(vk::QueryPoolCreateInfo(vk::QueryPoolCreateFlags(), vk::QueryType::eTimestamp, VUDA_MAX_QUERY_COUNT, vk::QueryPipelineStatisticFlags()))), m_queryIndex(0) { // // create unique mutexes /*m_mtxCommandBuffers.resize(queueComputeCount); for(unsigned int i = 0; i < queueComputeCount; ++i) m_mtxCommandBuffers[i] = std::make_unique<std::mutex>();*/ // // create fences m_ufences.reserve(queueComputeCount); for(unsigned int i = 0; i < queueComputeCount; ++i) m_ufences.push_back(device->createFenceUnique(vk::FenceCreateFlags())); } /* public synchronized interface */ void SetEvent(const vk::UniqueDevice& device, const event_t event, const stream_t stream) const { // // lock access to the streams commandbuffer //std::lock_guard<std::mutex> lck(*m_mtxCommandBuffers[stream]); // // CheckStateAndBeginCommandBuffer(device, stream); // // m_commandBuffers[stream]->setEvent(event, vk::PipelineStageFlagBits::eBottomOfPipe); } uint32_t GetQueryID(void) const { assert(m_queryIndex != VUDA_MAX_QUERY_COUNT); return m_queryIndex++; } void WriteTimeStamp(const vk::UniqueDevice& device, const uint32_t queryID, const stream_t stream) const { // // lock access to the streams commandbuffer //std::lock_guard<std::mutex> lck(*m_mtxCommandBuffers[stream]); // // submit write time stamp command CheckStateAndBeginCommandBuffer(device, stream); // reset m_commandBuffers[stream]->resetQueryPool(m_queryPool.get(), queryID, 1); // write m_commandBuffers[stream]->writeTimestamp(vk::PipelineStageFlagBits::eBottomOfPipe, m_queryPool.get(), queryID); } uint64_t GetQueryPoolResults(const vk::UniqueDevice& device, const uint32_t queryID) const { // vkGetQueryPoolResults(sync) // vkCmdCopyQueryPoolResults(async) const uint32_t numQueries = 1; // VUDA_MAX_QUERY_COUNT; uint64_t result[numQueries]; size_t stride = sizeof(uint64_t); size_t size = numQueries * stride; // // vkGetQueryPoolResults will wait for the results to be available when VK_QUERY_RESULT_WAIT_BIT is specified vk::Result res = device->getQueryPoolResults(m_queryPool.get(), queryID, numQueries, size, &result[0], stride, vk::QueryResultFlagBits::e64 | vk::QueryResultFlagBits::eWait); assert(res == vk::Result::eSuccess); return result[0]; } /*void ResetQueryPool(const vk::UniqueDevice& device, const uint32_t queryID, const stream_t stream) const { // // lock access to the streams commandbuffer std::lock_guard<std::mutex> lck(*m_mtxCommandBuffers[stream]); // // reset query CheckStateAndBeginCommandBuffer(device, stream); m_commandBuffers[stream]->resetQueryPool(m_queryPool.get(), queryID, 1); }*/ void memcpyDevice(const vk::UniqueDevice& device, const vk::Buffer& bufferDst, const vk::DeviceSize dstOffset, const vk::Buffer& bufferSrc, const vk::DeviceSize srcOffset, const vk::DeviceSize size, const vk::Queue& queue, const stream_t stream) const { // // lock access to the streams commandbuffer //std::lock_guard<std::mutex> lck(*m_mtxCommandBuffers[stream]); /*// // hello std::ostringstream ostr; ostr << "thrd: " << std::this_thread::get_id() << ", pooladrr: " << this << ", locked and modifying command buffer: " << stream << std::endl; std::cout << ostr.str(); ostr.str("");*/ // // check state of command buffer and see if we should call begin CheckStateAndBeginCommandBuffer(device, stream); // // submit copy buffer call to command buffer vk::BufferCopy copyRegion = vk::BufferCopy() .setSrcOffset(srcOffset) .setDstOffset(dstOffset) .setSize(size); // // the order of src and dst is interchanged compared to memcpy m_commandBuffers[stream]->copyBuffer(bufferSrc, bufferDst, copyRegion); // // hello there /*std::ostringstream ostr; ostr << std::this_thread::get_id() << ", commandbuffer: " << &m_commandBuffers[stream] << ", src: " << bufferSrc << ", dst: " << bufferDst << ", copy region: srcOffset: " << copyRegion.srcOffset << ", dstOffset: " << copyRegion.dstOffset << ", size: " << copyRegion.size << std::endl; std::cout << ostr.str();*/ // // insert pipeline barrier? /*vk::BufferMemoryBarrier bmb(vk::AccessFlagBits::eTransferRead, vk::AccessFlagBits::eTransferWrite, VK_QUEUE_FAMILY_IGNORED, VK_QUEUE_FAMILY_IGNORED, bufferDst, dstOffset, size); m_commandBuffers[stream]->pipelineBarrier( vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eBottomOfPipe, vk::DependencyFlagBits::eByRegion, 0, nullptr, 1, &bmb, 0, nullptr);*/ // // execute the command buffer ExecuteQueue(device, queue, stream); //ostr << "thrd: " << std::this_thread::get_id() << ", pooladrr: " << this << ", unlocking command buffer: " << stream << std::endl; //std::cout << ostr.str(); } template <size_t specializationByteSize, typename... specialTypes, size_t bindingSize> void UpdateDescriptorAndCommandBuffer(const vk::UniqueDevice& device, const kernelprogram<specializationByteSize>& kernel, const specialization<specialTypes...>& specials, const std::array<vk::DescriptorBufferInfo, bindingSize>& bufferDescriptors, const dim3 blocks, const stream_t stream) const { // // lock access to the streams commandbuffer //std::lock_guard<std::mutex> lck(*m_mtxCommandBuffers[stream]); // // check state of command buffer and see if we should call begin CheckStateAndBeginCommandBuffer(device, stream); // // record command buffer kernel.UpdateDescriptorAndCommandBuffer(device, m_commandBuffers[stream], bufferDescriptors, specials, blocks); // // insert (buffer) memory barrier // [ memory barriers are created for each resource, it would be better to apply the barriers based on readonly, writeonly information ] const uint32_t numbuf = (uint32_t)bufferDescriptors.size(); std::vector<vk::BufferMemoryBarrier> bmb(numbuf); for(uint32_t i=0; i<numbuf; ++i) { bmb[i] = vk::BufferMemoryBarrier( vk::AccessFlagBits::eShaderWrite, vk::AccessFlagBits::eShaderRead, VK_QUEUE_FAMILY_IGNORED, VK_QUEUE_FAMILY_IGNORED, bufferDescriptors[i].buffer, bufferDescriptors[i].offset, bufferDescriptors[i].range); } m_commandBuffers[stream]->pipelineBarrier( vk::PipelineStageFlagBits::eComputeShader, vk::PipelineStageFlagBits::eComputeShader, vk::DependencyFlagBits::eByRegion, 0, nullptr, numbuf, bmb.data(), 0, nullptr); // // statistics /*std::ostringstream ostr; ostr << "tid: " << std::this_thread::get_id() << ", stream_id: " << stream << ", command buffer addr: " << &m_commandBuffers[stream] << std::endl; std::cout << ostr.str();*/ /*// // if the recording failed, it is solely due to the limited amount of descriptor sets if(ret == false) { // // if we are doing a new recording no need to end and execute if(newRecording == false) { std::ostringstream ostr; std::thread::id tid = std::this_thread::get_id(); ostr << tid << ": ran out of descriptors! Got to execute now and retry!" << std::endl; std::cout << ostr.str(); // end recording/execute, wait, begin recording ExecuteQueue(device, queueFamilyIndex, stream); WaitAndReset(device, stream); BeginRecordingCommandBuffer(stream); } // // record ret = kernel.UpdateDescriptorAndCommandBuffer(device, m_commandBuffers[stream], bufferDescriptors); assert(ret == true); }*/ } void Execute(const vk::UniqueDevice& device, const vk::Queue& queue, const stream_t stream) const { // // lock access to the streams commandbuffer //std::lock_guard<std::mutex> lck(*m_mtxCommandBuffers[stream]); ExecuteQueue(device, queue, stream); } /*void Wait(const vk::UniqueDevice& device, const vk::Queue& queue, const stream_t stream) const { // // lock access to the streams commandbuffer std::lock_guard<std::mutex> lck(*m_mtxCommandBuffers[stream]); WaitAndReset(device, stream); }*/ void ExecuteAndWait(const vk::UniqueDevice& device, const vk::Queue& queue, const stream_t stream) const { // // lock access to the streams commandbuffer //std::lock_guard<std::mutex> lck(*m_mtxCommandBuffers[stream]); ExecuteQueue(device, queue, stream); WaitAndReset(device, stream); } private: /* private non-synchronized implementation - assumes m_mtxCommandBuffers[stream] is locked */ void CheckStateAndBeginCommandBuffer(const vk::UniqueDevice& device, const stream_t stream) const { // // assumes m_mtxCommandBuffers[stream] is locked commandBufferStateFlags state = m_commandBufferState[stream]; if(state == cbReset) { // we can begin a new recording BeginRecordingCommandBuffer(stream); } else if(state == cbSubmitted) { // wait on completion and start new recording WaitAndReset(device, stream); BeginRecordingCommandBuffer(stream); } else { // this is a continued recording call //newRecording = false; } } void BeginRecordingCommandBuffer(const stream_t stream) const { // // assumes m_mtxCommandBuffers[stream] is locked vk::CommandBufferBeginInfo commandBufferBeginInfo = vk::CommandBufferBeginInfo() .setFlags(vk::CommandBufferUsageFlagBits::eOneTimeSubmit) .setPInheritanceInfo(nullptr); m_commandBuffers[stream]->begin(commandBufferBeginInfo); m_commandBufferState[stream] = cbRecording; } void ExecuteQueue(const vk::UniqueDevice& device, const vk::Queue& queue, const stream_t stream) const { // // assumes m_mtxCommandBuffers[stream] is locked if(m_commandBufferState[stream] == cbRecording) { // // end recording and submit m_commandBuffers[stream]->end(); // // submit command buffer to compute queue /* https://www.khronos.org/registry/vulkan/specs/1.1-extensions/man/html/vkQueueSubmit.html Each element of the pCommandBuffers member of each element of pSubmits must have been allocated from a VkCommandPool that was created for the same queue family queue belongs to. */ queue.submit(vk::SubmitInfo(0, nullptr, nullptr, 1, &m_commandBuffers[stream].get(), 0, nullptr), m_ufences[stream].get()); m_commandBufferState[stream] = cbSubmitted; } } void WaitAndReset(const vk::UniqueDevice& device, const stream_t stream) const { // // assumes m_mtxCommandBuffers[stream] is locked if(m_commandBufferState[stream] == cbSubmitted) { // // for now just wait for the queue to become idle vk::Result res = device->waitForFences(1, &m_ufences[stream].get(), VK_FALSE, (std::numeric_limits<uint64_t>::max)()); assert(res == vk::Result::eSuccess); device->resetFences(1, &m_ufences[stream].get()); // // reset command buffer m_commandBuffers[stream]->reset(vk::CommandBufferResetFlags()); m_commandBufferState[stream] = cbReset; } } /*std::vector<uint32_t> GetStreamList(const void* src) { std::lock_guard<std::mutex> lck(*m_mtxResourceDependency); std::vector<uint32_t> list = m_src2stream[src]; m_src2stream.erase(src); return list; }*/ private: //std::vector<std::unique_ptr<std::mutex>> m_mtxCommandBuffers; std::vector<vk::UniqueFence> m_ufences; vk::UniqueCommandPool m_commandPool; std::vector<vk::UniqueCommandBuffer> m_commandBuffers; mutable std::vector<commandBufferStateFlags> m_commandBufferState; // // time stamp queries vk::UniqueQueryPool m_queryPool; mutable std::atomic<uint32_t> m_queryIndex; //mutable std::array<std::atomic<uint32_t>, VUDA_MAX_QUERY_COUNT> m_querytostream; // // resource management //std::unique_ptr<std::mutex> m_mtxResourceDependency; //std::unordered_map<const void*, std::vector<uint32_t>> m_src2stream; }; } //namespace detail } //namespace vuda
44.32598
308
0.509594
nicoboss
d99e19814707922f174edf275686564c9d081b8c
1,018
cpp
C++
source/Ch18/orai_anyag/vector004.cpp
Vada200/UDProg-Introduction
c424b2676d6e5bfc4d53d61c5d0deded566c1c84
[ "CC0-1.0" ]
null
null
null
source/Ch18/orai_anyag/vector004.cpp
Vada200/UDProg-Introduction
c424b2676d6e5bfc4d53d61c5d0deded566c1c84
[ "CC0-1.0" ]
null
null
null
source/Ch18/orai_anyag/vector004.cpp
Vada200/UDProg-Introduction
c424b2676d6e5bfc4d53d61c5d0deded566c1c84
[ "CC0-1.0" ]
null
null
null
#include "std_lib_facilities.h" class My_vector { //priv long unsigned int sz; //size / előjel nélküli long típusú int double* elem; //elem pointer public: My_vector(int s) : sz(s), elem{new double[s]} // int s értéke bemásolódik sz-be, elem néven lefoglalódik a memóriában a double vector { for (int i = 0; i < s; i++) elem[i] = 0; //ki 0-zuk a memória területet } My_vector(initializer_list<double> lst) :sz{lst.size()}, elem{new double[sz]} //listát várja { copy(lst.begin(), lst.end(), elem); //mettől, meddig, hova } ~My_vector() { delete[] elem; } //destructor futás végén lefut double get(int n) const { return elem[n]; } void set(int n, double val) {elem[n] = val;} int size() const { return sz; } }; //osztály def után ; kell int main() { My_vector my(10); cout << my.size() << endl; //pointernél -> van My_vector v2 {12.2, 13.3, 14.4 }; for(int i = 0; i < v2.size(); i++) cout << v2.get(i) << endl; return 0; }
26.102564
135
0.59725
Vada200
d99f0d5667be22679b3b23559b79eb489b5cb6ac
601
cpp
C++
Challenges/Personal/InvertMostSign.cpp
zakhars/Education
4d791f6b4559a90ee383039aaeb15c7041138b12
[ "MIT" ]
null
null
null
Challenges/Personal/InvertMostSign.cpp
zakhars/Education
4d791f6b4559a90ee383039aaeb15c7041138b12
[ "MIT" ]
null
null
null
Challenges/Personal/InvertMostSign.cpp
zakhars/Education
4d791f6b4559a90ee383039aaeb15c7041138b12
[ "MIT" ]
null
null
null
#pragma once #include <iostream> #include <bitset> unsigned short InvertMostSign(unsigned short val) { int mostSignBit = -1; for(int i = 15; i >= 0; i--) { if (val & (1 << i)) { mostSignBit = i; break; } } if (mostSignBit != -1) { return (val ^ (1 << mostSignBit)); } return -1; } void InvertMostSign_Test() { using namespace std; unsigned short val = 36453; std::cout << std::bitset<16>( val) << std::endl << std::bitset<16>(~val) << std::endl << std::bitset<16>(InvertMostSign(val)) << std::endl; }
20.033333
142
0.530782
zakhars
d99fef68f614e65d9c3aac7d31a0f9669620d909
34,228
cxx
C++
Code/bmEditor.cxx
NIRALUser/BatchMake
1afeb15fa5bd18be6e4a56f4349eb6368a91441e
[ "Unlicense" ]
null
null
null
Code/bmEditor.cxx
NIRALUser/BatchMake
1afeb15fa5bd18be6e4a56f4349eb6368a91441e
[ "Unlicense" ]
null
null
null
Code/bmEditor.cxx
NIRALUser/BatchMake
1afeb15fa5bd18be6e4a56f4349eb6368a91441e
[ "Unlicense" ]
null
null
null
/*========================================================================= Program: BatchMake Module: bmEditor.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2005 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "bmEditor.h" #include "MString.h" #include "bmScriptEditorGUIControls.h" namespace bm { Fl_Text_Display::Style_Table_Entry styletable[] = { // Style table { FL_BLACK, FL_COURIER, 12 }, // A - Plain { FL_DARK_GREEN, FL_COURIER_ITALIC, 12 }, // B - Line comments { FL_RED, FL_COURIER, 12 }, // C - Variables { FL_BLUE, FL_COURIER, 12 }, // D - Strings { FL_DARK_RED, FL_COURIER, 12 }, // E - Directives { FL_DARK_RED, FL_COURIER_BOLD, 12 }, // F - Types { FL_BLUE, FL_COURIER_BOLD, 12 }, // G - Keywords { FL_RED, FL_COURIER, 12 } // H - Keywords }; static std::list<BMString> m_keywords; const char *code_types[] = { // List of known C/C++ types... "else", "endforeach", "endif", "foreach", "if", "null"}; static Fl_Window* m_Parentwindow; char m_Title[256]; Editor::Editor(int X, int Y, int W, int H, const char* l) :Fl_Text_Editor(X, Y, W, H, l) { m_Parser = NULL; // Specification for the word completion browser (for actions) m_DrawBrowser = false; m_Browser = new Flu_Tree_Browser(0, 0,200,80); m_Browser->box( FL_DOWN_BOX ); m_Browser->show_root(false); m_Browser->branch_text(m_Browser->branch_color(),m_Browser->branch_font(),10); m_Browser->leaf_text(m_Browser->leaf_color(),m_Browser->leaf_font(),10); m_Browser->vertical_gap(-2); m_Browser->selection_color(87); m_Browser->show_leaves( true ); m_Browser->show_branches( true ); m_Browser->get_root()->always_open( true ); m_Browser->insertion_mode(FLU_INSERT_BACK); m_Browser->selection_follows_hilight(true); m_Browser->selection_mode(FLU_SINGLE_SELECT); m_Browser->callback((Fl_Callback*)SelectOption,this); m_Browser->resize(13,15,200,80); m_Browser->end(); // Specification for the applications completion browser (for wrapped applications) m_DrawApplicationBrowser = false; m_ApplicationBrowser = new Flu_Tree_Browser(0, 0,200,80); m_ApplicationBrowser->box( FL_DOWN_BOX ); m_ApplicationBrowser->show_root(false); m_ApplicationBrowser->branch_text(m_ApplicationBrowser->branch_color(), m_ApplicationBrowser->branch_font(),10); m_ApplicationBrowser->leaf_text(m_ApplicationBrowser->leaf_color(), m_ApplicationBrowser->leaf_font(),10); m_ApplicationBrowser->vertical_gap(-2); m_ApplicationBrowser->selection_color(87); m_ApplicationBrowser->show_leaves( true ); m_ApplicationBrowser->show_branches( true ); m_ApplicationBrowser->get_root()->always_open( true ); m_ApplicationBrowser->insertion_mode(FLU_INSERT_BACK); m_ApplicationBrowser->selection_follows_hilight(true); m_ApplicationBrowser->selection_mode(FLU_SINGLE_SELECT); m_ApplicationBrowser->callback((Fl_Callback*)SelectApplication,this); m_ApplicationBrowser->resize(13,15,200,80); m_ApplicationBrowser->end(); // Specification for the applications completion browser (for wrapped applications) m_DrawApplicationOptionBrowser = false; m_ApplicationOptionBrowser = new Flu_Tree_Browser(0, 0,200,80); m_ApplicationOptionBrowser->box( FL_DOWN_BOX ); m_ApplicationOptionBrowser->show_root(false); m_ApplicationOptionBrowser->branch_text(m_ApplicationOptionBrowser->branch_color(), m_ApplicationOptionBrowser->branch_font(),10); m_ApplicationOptionBrowser->leaf_text(m_ApplicationOptionBrowser->leaf_color(), m_ApplicationOptionBrowser->leaf_font(),10); m_ApplicationOptionBrowser->vertical_gap(-2); m_ApplicationOptionBrowser->selection_color(87); m_ApplicationOptionBrowser->show_leaves( true ); m_ApplicationOptionBrowser->show_branches( true ); m_ApplicationOptionBrowser->get_root()->always_open( true ); m_ApplicationOptionBrowser->insertion_mode(FLU_INSERT_BACK); m_ApplicationOptionBrowser->selection_follows_hilight(true); m_ApplicationOptionBrowser->selection_mode(FLU_SINGLE_SELECT); m_ApplicationOptionBrowser->callback((Fl_Callback*)SelectApplicationOption,this); m_ApplicationOptionBrowser->resize(13,15,200,80); m_ApplicationOptionBrowser->end(); m_DrawHelper = false; m_Helper = new Fl_Output(0, 0,200,15); m_Helper->resize(0,0,200,15); m_Helper->box(FL_BORDER_BOX); m_Helper->color((Fl_Color)215); m_Helper->labelsize(10); m_Helper->textsize(10); m_Buffer = new Fl_Text_Buffer(); char *style = new char[3]; char *text = m_Buffer->text(); style[0] = '\0'; m_Stylebuf = new Fl_Text_Buffer(m_Buffer->length()); m_Stylebuf->text(style); delete [] style; style = NULL; delete [] text; text = NULL; buffer(m_Buffer); highlight_data(m_Stylebuf, styletable, sizeof(styletable) / sizeof(styletable[0]), 'A', style_unfinished_cb, 0); m_Buffer->add_modify_callback(style_update, this); m_Buffer->call_modify_callbacks(); m_CurrentWord = ""; m_Parentwindow = 0; m_ScriptEditorGUI = NULL; } /** Desctructor */ Editor::~Editor() { } /** Return true if the current script is empty */ bool Editor::IsBufferEmpty() { if(m_Buffer->length() == 0) { return true; } return false; } /** Set the parser and initialize */ void Editor::SetParser(ScriptParser* parser) { m_Parser = parser; m_Manager = m_Parser->GetScriptActionManager(); m_Manager->SetApplicationsList(&m_ApplicationsList); this->UpdateKeyword(); } /** Update the list of wrapped applications */ void Editor::UpdateApplicationsList() { if(!m_Manager->GetApplicationWrapperList()) { return; } m_ApplicationBrowser->clear(); ScriptActionManager::ApplicationWrapperListType::const_iterator it = m_Manager->GetApplicationWrapperList()->begin(); if(m_Manager->GetApplicationWrapperList()->size() == 0) { return; } while (it != m_Manager->GetApplicationWrapperList()->end()) { m_ApplicationBrowser->add( (*it)->GetName().c_str() ); it++; } Flu_Tree_Browser::Node* m_node = m_ApplicationBrowser->first(); m_node = m_node->next(); m_node->select_only(); //m_ApplicationBrowser->set_hilighted(m_node); } /** Update the list of keywords */ void Editor::UpdateKeyword() { m_Browser->clear(); std::vector<BMString> m_list = m_Manager->GenerateKeywordList(); m_keywords = std::list<BMString>( m_list.begin(), m_list.end() ); m_keywords.sort(); std::list<BMString>::iterator it; std::list<BMString>::iterator end = m_keywords.end(); for( it = m_keywords.begin(); it != end; ++it) { m_Browser->add((*it).toChar()); } m_Browser->resize(13,15,200,80); m_Browser->end(); } void Editor::UpdateVariable() { } void Editor::SetParentWindow(Fl_Window* parentwindow) { m_Parentwindow = parentwindow; } void Editor::SetModified(bool flag) { if (m_Parentwindow) { strcpy(m_Title,m_Parentwindow->label()); if (MString(m_Title).rfind("*") == -1) { strcpy(m_Title,(MString(m_Title).rbegin("]") + "*]").toChar()); m_Parentwindow->label(m_Title); } } } bool Editor::Find(/*std::list<MString> array,*/const BMString& key) { std::list<BMString>::const_iterator it; std::list<BMString>::const_iterator end = m_keywords.end(); for( it = m_keywords.begin(); it != end; ++it) { if( (*it).toLowerCopy() == key ) { return true; } } return false; } int Editor::compare_keywords(const void *a,const void *b) { return (strcmp(*((const char **)a), *((const char **)b))); } void Editor::style_unfinished_cb(int, void*) { } void Editor::style_update(int pos, // I - Position of update int nInserted, // I - Number of inserted chars int nDeleted, // I - Number of deleted chars int nRestyled, // I - Number of restyled chars const char *deletedText, // I - Text that was deleted void *cbArg) // I - Callback data { int start, // Start of text end; // End of text char last; // Last style on line char *style = NULL; // Style data char *text = NULL; // Text data if ((nInserted || nDeleted)) SetModified(true); Fl_Text_Buffer* stylebuf = ((Editor *)cbArg)->m_Stylebuf; Fl_Text_Buffer* textbuf = ((Editor *)cbArg)->m_Buffer; // If this is just a selection change, just unselect the style buffer... if (nInserted == 0 && nDeleted == 0) { stylebuf->unselect(); return; } // Track changes in the text buffer... if (nInserted > 0) { // Insert characters into the style buffer... style = new char[nInserted + 1]; memset(style, 'A', nInserted); style[nInserted] = '\0'; stylebuf->replace(pos, pos + nDeleted, style); delete [] style; style = NULL; } else { // Just delete characters in the style buffer... stylebuf->remove(pos, pos + nDeleted); } // Select the area that was just updated to avoid unnecessary // callbacks... stylebuf->select(pos, pos + nInserted - nDeleted); // Re-parse the changed region; we do this by parsing from the // beginning of the line of the changed region to the end of // the line of the changed region... Then we check the last // style character and keep updating if we have a multi-line // comment character... start = textbuf->line_start(pos); end = textbuf->line_end(pos + nInserted); text = textbuf->text_range(start, end); style = stylebuf->text_range(start, end); last = style[end - start - 1]; if ((pos == start)) { style[0] = stylebuf->text_range(start-1,start)[0]; style[1] = '\0'; } if ((end - start) != 0) { style_parse(text, style, end - start); stylebuf->replace(start, end, style); ((Editor *)cbArg)->redisplay_range(start, end); } if (last != style[end - start - 1]) { // The last character on the line changed styles, so reparse the // remainder of the buffer... delete [] text; text = NULL; delete [] style; style = NULL; end = textbuf->length(); text = textbuf->text_range(start, end); style = stylebuf->text_range(start, end); style_parse(text, style, end - start); stylebuf->replace(start, end, style); ((Editor *)cbArg)->redisplay_range(start, end); } delete [] text; text = NULL; int m_x; int m_y; ((Editor *)cbArg)->position_to_xy(pos,&m_x,&m_y); ((Editor *)cbArg)->ShowOptionFinder(m_x,m_y); } void Editor:: style_parse(const char *text,char *style,int length) { char current; int col; int last; char buf[255],*bufptr; const char *temp; if ((style[0] != 'C') && (style[0] != 'D')) { style[0] = 'A'; } for (current = *style, col = 0, last = 0; length > 0; length --, text ++) { if (current == 'B') { current = 'A'; } if (current == 'A') { // Check for directives, comments, strings, and keywords... if (strncmp(text, "#", 1) == 0) { current = 'B'; for (; length > 0 && *text != '\n'; length --, text ++) { *style++ = 'B'; } if (length == 0) break; } else if (strncmp(text, "$", 1) == 0) { current = 'C'; } else if (strncmp(text, "\\'", 2) == 0) { // Quoted quote... *style++ = current; *style++ = current; text ++; length --; col += 2; continue; } else if (*text == '\'') { current = 'D'; } else { temp = text; bufptr = buf; unsigned int offset =0; while ((text[offset] != ' ') && (offset<strlen(text)) && (text[offset] != '\n') && (text[offset] != '(')) { *bufptr++ = tolower(*temp++); offset++; } //{ *bufptr = '\0'; bufptr = buf; if (bsearch(&bufptr, code_types, sizeof(code_types) / sizeof(code_types[0]), sizeof(code_types[0]), compare_keywords)) { while (text < temp) { *style++ = 'F'; text ++; length --; col ++; } text --; length ++; last = 1; continue; } else if (Find(/*m_keywords,*/bufptr)) { while (text < temp) { *style++ = 'G'; text ++; length --; col ++; } text --; length ++; last = 1; continue; } } } //} else if (current == 'C' && ((strncmp(text+1, ")", 1) == 0) || (strncmp(text, " ", 1) == 0) || (strncmp(text, "}", 1) == 0)) ) { // Close a C comment... *style++ = current; current = 'A'; col += 1; continue; } else if (current == 'D') { // Continuing in string... if (strncmp(text, "$", 1) == 0) { current = 'H'; } if (*text == '\'') { // End quote... *style++ = current; col ++; current = 'A'; continue; } } else if (current == 'H' && ((strncmp(text+1, ")", 1) == 0) || (strncmp(text, " ", 1) == 0) || (strncmp(text, "}", 1) == 0)) ) { // Close a C comment... *style++ = current; current = 'D'; col += 1; continue; } // Copy style info... *style++ = current; col ++; last = isalnum(*text) || *text == '.'; } } /** Add the application to browse */ void Editor::AddApplicationsToBrowse() { unsigned long lpos=0; for(int l=0;l<buffer()->count_lines(0,buffer()->length());l++) { // get the current line std::string line = buffer()->line_text(buffer()->line_start(lpos)); lpos = buffer()->line_end(lpos)+1; std::size_t pos = 0; MString lowercaseLine = line; lowercaseLine = lowercaseLine.toLower(); std::string lowercaseLine2 = lowercaseLine.toChar(); if( (pos = lowercaseLine2.find("setapp(")) != std::string::npos ) { long pos1 = line.find("(",pos); if(pos1 != -1) { long pos2 = line.find(")",pos1); if(pos2 != -1) { long posspace = line.find(" ",pos1); std::string name = line.substr(pos1+1,posspace-pos1-1); std::string app = line.substr(posspace+2,pos2-posspace-2); // there should be a @ long pos3 = app.find(" "); if(pos3 != -1) { app = app.substr(0,pos3); // there should be a @ } // Search the correct app corresponding to the name if(m_Manager->GetApplicationWrapperList()) { ScriptActionManager::ApplicationWrapperListType::const_iterator it = m_Manager->GetApplicationWrapperList()->begin(); while (it != m_Manager->GetApplicationWrapperList()->end()) { if( (*it)->GetName() == app.c_str() ) { ApplicationNameType newapp; newapp.first = name; newapp.second = (*it); m_ApplicationsList.push_back(newapp); break; } it++; } } } } } } } void Editor::Load(const char* filename) { int r = m_Buffer->loadfile(filename); if (r) fl_alert("Error reading from file \'%s\':\n%s.", filename, strerror(errno)); int m_foundPos = 0; while(m_Buffer->findchars_forward(m_foundPos,"\r",&m_foundPos)) m_Buffer->remove(m_foundPos,m_foundPos+1); m_Buffer->call_modify_callbacks(); this->AddApplicationsToBrowse(); } void Editor::Save(const char* filename) { if (m_Buffer->savefile(filename)) { fl_alert("Error writing to file \'%s\':\n%s.", filename, strerror(errno)); } m_Buffer->call_modify_callbacks(); } /** Place the browser at the correct location */ void Editor::ShowOptionFinder(int x,int y) { m_Browser->resize(x+13,y+15,200,80); m_ApplicationBrowser->resize(x+13,y+15,200,80); m_ApplicationOptionBrowser->resize(x+13,y+15,200,80); m_Helper->resize(x+13,y+15,m_Helper->w(),m_Helper->h()); } /** Draw */ void Editor::draw() { Fl_Text_Display::draw(); if (m_DrawHelper) { m_Helper->show(); } else { m_Helper->hide(); } if (m_DrawBrowser) { m_Browser->show(); } else { m_Browser->hide(); } if (m_DrawApplicationBrowser) { m_ApplicationBrowser->show_leaves( true ); m_ApplicationBrowser->show_branches( false ); m_ApplicationBrowser->show(); } else { m_ApplicationBrowser->hide(); } if (m_DrawApplicationOptionBrowser) { m_ApplicationOptionBrowser->show(); } else { m_ApplicationOptionBrowser->hide(); } m_ApplicationBrowser->redraw(); m_ApplicationOptionBrowser->redraw(); m_Browser->redraw(); m_Helper->redraw(); redraw(); } /** Callback when a tab completion is done for an action */ void Editor::SelectOption(Flu_Tree_Browser* browser, void* widget) { if (browser->get_selected(1) != 0) { if (browser->callback_reason() == FLU_DOUBLE_CLICK) { MString m_text(MString(browser->get_selected(1)->label()) + "()"); m_text = m_text.mid(((Editor*)widget)->m_CurrentWord.length()); ((Editor*)widget)->m_Buffer->insert(((Editor*)widget)->insert_position(),m_text.toChar()); ((Editor*)widget)->insert_position(((Editor*)widget)->insert_position()+m_text.length()-1); ((Editor*) widget)->m_DrawBrowser = false; ((Editor*)widget)->m_CurrentWord = ""; } if (browser->callback_reason() == FLU_TAB_KEY || Fl::event_key() == 65293 ) { MString m_text(MString(browser->get_selected(1)->label()) + "()"); m_text = m_text.mid(((Editor*)widget)->m_CurrentWord.length()); ((Editor*)widget)->m_Buffer->insert(((Editor*)widget)->insert_position(),m_text.toChar()); ((Editor*)widget)->insert_position(((Editor*)widget)->insert_position()+m_text.length()-1); ((Editor*) widget)->m_DrawBrowser = false; ((Editor*)widget)->m_CurrentWord = ""; ScriptActionManager m_Manager; ScriptAction* m_help = m_Manager.CreateAction(MString(browser->get_selected(1)->label()).toLower()); if (m_help) { ((Editor*)widget)->m_Helper->value(m_help->Help().toChar()); if (MString(((Editor*)widget)->m_Helper->value()) != "") { ((Editor*)widget)->m_Helper->resize(((Editor*)widget)->m_Helper->x(), ((Editor*)widget)->m_Helper->y(), (int)(m_help->Help().length()*4.9),15); ((Editor*)widget)->m_DrawHelper = true; } else { ((Editor*)widget)->m_DrawHelper = false; } delete m_help; } else { ((Editor*)widget)->m_DrawHelper = false; } } } } /** Callback when a tab completion is done for an action */ void Editor::SelectApplication(Flu_Tree_Browser* browser, void* widget) { if (browser->get_selected(1) != 0) { if (browser->callback_reason() == FLU_DOUBLE_CLICK) { MString m_text(MString(browser->get_selected(1)->label())); ((Editor*)widget)->m_Buffer->insert(((Editor*)widget)->insert_position(),m_text.toChar()); ((Editor*)widget)->insert_position(((Editor*)widget)->insert_position()+m_text.length()); ((Editor*) widget)->m_DrawApplicationBrowser = false; ((Editor*) widget)->m_DrawBrowser = false; ((Editor*)widget)->m_DrawHelper = false; ((Editor*)widget)->m_CurrentWord = ""; } if (browser->callback_reason() == FLU_TAB_KEY || Fl::event_key() == 65293 ) { MString m_text(MString(browser->get_selected(1)->label())); ((Editor*)widget)->m_Buffer->insert(((Editor*)widget)->insert_position(),m_text.toChar()); ((Editor*)widget)->insert_position(((Editor*)widget)->insert_position()+m_text.length()); ((Editor*) widget)->m_DrawApplicationBrowser = false; ((Editor*) widget)->m_DrawBrowser = false; ((Editor*)widget)->m_DrawHelper = false; ((Editor*)widget)->m_CurrentWord = ""; } } } /** Callback when a tab completion is done for an action */ void Editor::SelectApplicationOption(Flu_Tree_Browser* browser, void* widget) { if (browser->get_selected(1) != 0) { if (browser->callback_reason() == FLU_DOUBLE_CLICK) { MString m_text(MString(browser->get_selected(1)->label())); ((Editor*)widget)->m_Buffer->insert(((Editor*)widget)->insert_position(),m_text.toChar()); ((Editor*)widget)->insert_position(((Editor*)widget)->insert_position()+m_text.length()); ((Editor*)widget)->m_DrawApplicationOptionBrowser = false; ((Editor*)widget)->m_CurrentWord = ""; } if (browser->callback_reason() == FLU_TAB_KEY || Fl::event_key() == 65293 ) { MString m_text(MString(browser->get_selected(1)->label())); ((Editor*)widget)->m_Buffer->insert(((Editor*)widget)->insert_position(),m_text.toChar()); ((Editor*)widget)->insert_position(((Editor*)widget)->insert_position()+m_text.length()); ((Editor*)widget)->m_DrawApplicationOptionBrowser = false; ((Editor*)widget)->m_CurrentWord = ""; } } } /** Show the option give the variable name of an app */ bool Editor::ShowApplicationOptions(const char* appVarName) { if(!m_Manager->GetApplicationWrapperList()) { return false; } m_ApplicationOptionBrowser->clear(); std::vector<ApplicationNameType>::const_iterator it = m_ApplicationsList.begin(); ApplicationWrapper* app = NULL; while (it != m_ApplicationsList.end()) { if(!strcmp((*it).first.c_str(),appVarName)) { app = (*it).second; break; } it++; } if(!app) { return false; } // Get the option from the application wrapper const std::vector<ApplicationWrapperParam> & params = app->GetParams(); // std::cout << "App Name = " << app->GetName().toChar() << std::endl; std::vector<ApplicationWrapperParam>::const_iterator itParams = params.begin(); if(params.size() == 0) { return false; } //std::cout << "params.size() = " << params.size() << std::endl; //std::cout << "Has params" << std::endl; while(itParams!= params.end()) { std::string text = ""; text += (*itParams).GetName().toChar(); m_ApplicationOptionBrowser->add(text.c_str()); std::vector<std::string> parameters = (*itParams).ShowApplicationOptionsSubParams(text); for(unsigned int i=0 ; i<parameters.size() ; i++) { /*std::string param = parameters[i].c_str(); std::string parameter = ""; string::size_type loc = param.find( ".", 0 ); if( loc != string::npos ) { parameter += param.substr(loc+1); } else { parameter += param; }*/ m_ApplicationOptionBrowser->add(parameters[i].c_str()); } itParams++; } return true; } /** Handle function for the text editor */ int Editor::handle( int event ) { if (event == FL_PUSH) { m_CurrentWord = ""; m_DrawBrowser = false; m_DrawApplicationBrowser = false; m_DrawApplicationOptionBrowser = false; draw(); return Fl_Text_Editor::handle( event ); } if ( event == FL_KEYDOWN ) { // if @ is pressed then we show the list of wrapped applications if(Fl::event_state() == 1114112 && Fl::event_key() == 50) { if (!m_DrawApplicationBrowser) { this->UpdateApplicationsList(); m_DrawApplicationBrowser = true; } else { m_ApplicationBrowser->handle(event); } take_focus(); } // if CTRL+S is pressed we save the script if(Fl::event_state() == 1310720 && Fl::event_key() == 115) { static_cast<ScriptEditorGUIControls*>(m_ScriptEditorGUI)->OnSaveScript(); return 1; } if ( Fl::event_key() == FL_Escape) { m_DrawBrowser = false; m_DrawHelper = false; m_DrawApplicationBrowser = false; m_DrawApplicationOptionBrowser = false; Fl_Text_Editor::handle( event ); draw(); return 1; } if( Fl::event_key() == FL_Tab) { if (!m_DrawBrowser && !m_DrawApplicationBrowser && !m_DrawApplicationOptionBrowser) { m_DrawBrowser = true; } else if(m_DrawBrowser) { m_Browser->handle(event); } else if(m_DrawApplicationBrowser) { m_ApplicationBrowser->handle(event); } else if(m_DrawApplicationOptionBrowser) { m_ApplicationOptionBrowser->handle(event); } take_focus(); return 1; } else if(Fl::event_key() == FL_Enter) { if(m_DrawBrowser) { m_Browser->handle(event); take_focus(); return 1; } else if(m_DrawApplicationBrowser) { m_ApplicationBrowser->handle(event); take_focus(); return 1; } else if(m_DrawApplicationOptionBrowser) { m_ApplicationOptionBrowser->handle(event); take_focus(); return 1; } else // we check if the current line contains the word SetApp() { // get the current line std::string line = buffer()->line_text(insert_position()); std::size_t pos = 0; MString lowercaseLine = line; lowercaseLine = lowercaseLine.toLower(); std::string lowercaseLine2 = lowercaseLine.toChar(); if( (pos = lowercaseLine2.find("setapp(")) != std::string::npos) { long pos1 = line.find("(",pos); if(pos1 != -1) { long pos2 = line.find(")",pos1); if(pos2 != -1) { long posspace = line.find(" ",pos1); std::string name = line.substr(pos1+1,posspace-pos1-1); std::string app = line.substr(posspace+2,pos2-posspace-2); // there should be a @ long pos3 = app.find(" "); if(pos3 != -1) { app = app.substr(0,pos3); // there should be a @ } // Search the correct app corresponding to the name ScriptActionManager::ApplicationWrapperListType::const_iterator it = m_Manager->GetApplicationWrapperList()->begin(); while (it != m_Manager->GetApplicationWrapperList()->end()) { if( (*it)->GetName() == app ) { ApplicationNameType newapp; newapp.first = name; newapp.second = (*it); std::cout << "Added " << name << " = " << (*it)->GetName() << std::endl; // Check if the variable is already assigned to a specific application int apppos = -1; bool appexists = false; std::vector<ApplicationNameType>::const_iterator it2 = m_ApplicationsList.begin(); while (it2 != m_ApplicationsList.end()) { apppos++; if(!strcmp((*it2).first.c_str(),name.c_str())) { appexists = true; break; } it2++; } if(appexists) { m_ApplicationsList[apppos] = newapp; } else { m_ApplicationsList.push_back(newapp); } break; } it++; } } } } } } else if( Fl::event_key() == FL_Down) { if (m_DrawBrowser) { m_Browser->handle(event); take_focus(); return 1; } else if(m_DrawApplicationBrowser) { m_ApplicationBrowser->handle(event); take_focus(); return 1; } else if(m_DrawApplicationOptionBrowser) { m_ApplicationOptionBrowser->handle(event); take_focus(); return 1; } } else if( Fl::event_key() == FL_Up) { if (m_DrawBrowser) { m_Browser->handle(event); take_focus(); return 1; } else if(m_DrawApplicationBrowser) { m_ApplicationBrowser->handle(event); take_focus(); return 1; } else if(m_DrawApplicationOptionBrowser) { m_ApplicationOptionBrowser->handle(event); take_focus(); return 1; } } else { if ((Fl::event_key() == ' ') || (Fl::event_key() == FL_Enter)) { m_CurrentWord = ""; } else if((Fl::event_key() == '.') || (Fl::event_key() == 65454)) // if it's a dot and the previous word is in the list of known apps/name { if (!m_DrawApplicationOptionBrowser) { // look for the work before the . std::string reword; long int i = insert_position(); i--; while(i>-1 && buffer()->character(i) != '(' && buffer()->character(i) != ')' && buffer()->character(i) != '"' && buffer()->character(i) != '.' && buffer()->character(i) != 65454 && buffer()->character(i) != 32 && buffer()->character(i) != 10 && buffer()->character(i) != '$' ) { reword += buffer()->character(i); i--; } // reverse the string std::string word = ""; for(i=0;i<(int)reword.size();i++) { word += reword[reword.size()-i-1]; } if(this->ShowApplicationOptions(word.c_str())) { m_DrawApplicationOptionBrowser = true; } else { m_DrawApplicationOptionBrowser = false; } } else { m_ApplicationOptionBrowser->handle(event); } } else { if ((Fl::event_key() == FL_BackSpace) || (Fl::event_key() == FL_BackSpace)) { m_CurrentWord = m_CurrentWord.mid(0,m_CurrentWord.length()-1); } else { if ((Fl::event_key() != FL_Shift_L) && (Fl::event_key() != FL_Shift_R)) { m_CurrentWord += Fl::event_key(); } } } ScriptActionManager m_Manager; ScriptAction* m_help = m_Manager.CreateAction(m_CurrentWord.toLower()); if (m_help) { m_Helper->value(m_help->Help().toChar()); if (MString(m_Helper->value()) != "") { m_Helper->resize(m_Helper->x(),m_Helper->y(),(int)(m_help->Help().length()*4.9),15); m_DrawBrowser = false; m_DrawApplicationBrowser = false; m_DrawApplicationOptionBrowser = false; m_DrawHelper = true; } else { m_DrawHelper = false; } delete m_help; } else { m_DrawHelper = false; } int m_Offset = -1; int currentrating = 0; std::list<BMString>::const_iterator it = m_keywords.begin(); int i =0; while (it != m_keywords.end()) { int m_rating = 0; int m_correctword = true; for (int j=0;j<m_CurrentWord.length();j++) { if ((*it).length() > j) { if ((m_CurrentWord.toLower()[j] != (*it).toLowerCopy()[j])) { m_correctword = false; } else { m_rating++; } } else { m_correctword = false; } } if ((m_rating != 0) && (m_rating > currentrating) && (m_correctword)) { m_Offset = i; currentrating = m_rating; } i++; it++; } if (m_Offset != -1) { if (!m_DrawHelper) { m_DrawBrowser = true; } Flu_Tree_Browser::Node* m_node = m_Browser->first(); for (int k=0;k<=m_Offset;k++) { m_node = m_node->next(); } if(m_node) { m_node->select(true); m_node->select_only(); m_Browser->set_hilighted(m_node); } Fl_Text_Editor::handle( event ); draw(); return 1; } else { m_DrawBrowser = false; m_DrawHelper = false; Fl_Text_Editor::handle( event ); draw(); return 1; } } } return Fl_Text_Editor::handle( event ); } } // end namespace bm
28.690696
98
0.549959
NIRALUser
d263de79c1bc78cf6370bf66123136b8155de065
124,838
cpp
C++
403_407_408_411_Ray_Tracer/src/ui.cpp
amritphuyal/Computer-Graphics-074-BEX
ee77526a6e2ce53d696b802650917f5a0438af14
[ "MIT" ]
5
2020-03-06T10:01:28.000Z
2020-05-06T07:57:20.000Z
403_407_408_411_Ray_Tracer/src/ui.cpp
amritphuyal/Computer-Graphics-074-BEX
ee77526a6e2ce53d696b802650917f5a0438af14
[ "MIT" ]
1
2020-03-06T02:51:50.000Z
2020-03-06T04:33:30.000Z
403_407_408_411_Ray_Tracer/src/ui.cpp
amritphuyal/Computer-Graphics-074-BEX
ee77526a6e2ce53d696b802650917f5a0438af14
[ "MIT" ]
29
2020-03-05T15:15:24.000Z
2021-07-21T07:05:00.000Z
#define OS_LINUX_CPP #define HANDMADE_MATH_IMPLEMENTATION #include <stdio.h> #include <cstdlib> #include "imgui.h" #include "imgui_impl_glfw.h" #include "imgui_impl_opengl3.h" #include <glad/glad.h> #include <GLFW/glfw3.h> #include "common.h" #include <cassert> #include <cmath> #define STB_IMAGE_IMPLEMENTATION #include <stb_image.h> #include "HandmadeMath.h" #include "ui_primitives.h" #include "ui_objects.h" #include "ray_data.h" #include "prng.h" typedef GLuint guint; #define SCREEN_WIDTH 800 #define SCREEN_HEIGHT 600 static uint ScreenWidth = 1366; static uint ScreenHeight = 768; #define HMM_MAT4_PTR(x) ( &( x ).Elements[0][0] ) #define HMM_MAT4P_PTR(x) (&( ( x )->Elements[0][0] )) #define ENABLE_GL_DEBUG_PRINT 1 #define MS_TO_SEC(x) ( (x) * 1.0e-3f ) static uint *Quad_elem_indices; static uint quad_elem_buffer_index; static uint *Line_elem_indices; static float CubeVertices[] = { // front 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, //back 0.5f, 0.5f, -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, // right 0.5f, 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, -0.5f, //left -0.5f, 0.5f, 0.5f, -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, // top 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, // bottom 0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, }; static float CubeNormals[] = { // front 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, // back 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -1.0f, // right 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, // left -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, // top 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, // bottom 0.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, }; static float CubeTexCoords[] = { 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, }; static v3 *SphereVertices; static v3 *SphereNormals; static v2 *SphereTextureCoords; static v3 *SphereColorBuff; static uint *SphereIndices; static uint sphere_element_buffer; static Rectangle CubeRects[6]; void generate_sphere_vertices( ){ SphereVertices = array_allocate( v3, 10000 ); SphereNormals = array_allocate( v3, 10000 ); SphereTextureCoords = array_allocate( v2, 10000 ); SphereIndices = array_allocate( uint, 10000 ); SphereColorBuff = array_allocate( v3, 10000 ); uint pitch_count = 50; uint yaw_count = 50; f32 pitch_step = 2 * HMM_PI32 / pitch_count; f32 yaw_step = HMM_PI32 / yaw_count; f32 pitch = 0.0f; f32 yaw = HMM_PI32/2; const f32 r = 1.0f; for ( uint i = 0; i <= yaw_count ; i++ ){ pitch = 0.0f; f32 z = r * HMM_SinF( yaw ); f32 xy = r * HMM_CosF( yaw ); for ( uint j = 0; j <= pitch_count ; j++ ){ f32 x = xy * r * HMM_CosF( pitch ); f32 y = xy * r * HMM_SinF( pitch ); array_push( SphereVertices, v3{x,y,z} ); array_push( SphereNormals, v3{ x,y,z } ); array_push( SphereTextureCoords, v2{ (f32)i/pitch_count, (f32)j/yaw_count } ); pitch += pitch_step; } yaw -= yaw_step; } for( uint i = 0; i < yaw_count; ++i){ uint k1 = i * (pitch_count + 1); uint k2 = k1 + pitch_count + 1; for( uint j = 0; j < pitch_count; ++j, ++k1, ++k2){ if(i != 0) { array_push(SphereIndices,k1); array_push(SphereIndices,k2); array_push(SphereIndices,k1 + 1); } if(i != (yaw_count-1)){ array_push( SphereIndices,k1 + 1); array_push( SphereIndices,k2); array_push( SphereIndices,k2 + 1); } } } return; } void generate_cube_rects( Rectangle *rects, f32 len ){ Rectangle front, back, left, right, top, bot; f32 half_len = len / 2.0f; front.p0 = { -half_len, -half_len, half_len }; back.p0 = { -half_len, -half_len, -half_len }; right.p0 = { half_len, -half_len, -half_len }; left.p0 = { -half_len, -half_len, -half_len }; top.p0 = { -half_len, half_len, -half_len }; bot.p0 = { -half_len, -half_len, -half_len }; front.s1 = { 1.0f,0.0f,0.0f }; front.s2 = { 0.0f, 1.0f, 0.0f }; back.s1 = { 1.0f,0.0f,0.0f }; back.s2 = { 0.0f, 1.0f, 0.0f }; right.s1 = { 0.0f,0.0f,1.0f }; right.s2 = { 0.0f, 1.0f, 0.0f }; left.s1 = { 0.0f,0.0f,1.0f }; left.s2 = { 0.0f, 1.0f, 0.0f }; top.s1 = { 1.0f,0.0f,0.0f }; top.s2 = { 0.0f, 0.0f, 1.0f }; bot.s1 = { 1.0f,0.0f,0.0f }; bot.s2 = { 0.0f, 0.0f, 1.0f }; front.n = { 0.0f, 0.0f, 1.0f }; back.n = { 0.0f, 0.0f, -1.0f }; right.n = { 1.0f, 0.0f, 0.0f }; left.n = { -1.0f, 0.0f, 0.0f }; top.n = { 0.0f, 1.0f, 0.0f }; bot.n = { 0.0f, -1.0f, 0.0f }; front.l1 = front.l2 = len; back.l1 = back.l2 = len; right.l1 = right.l2 = len; left.l1 = left.l2 = len; top.l1 = top.l2 = len; bot.l1 = bot.l2 = len; rects[ 0 ] = front; rects[ 1 ] = back; rects[ 2 ] = right; rects[ 3 ] = left; rects[ 4 ] = top; rects[ 5 ] = bot; } struct Camera { union { struct { v3 S, U, F; }; v3 basis[3]; }; v3 P; enum CameraState { ANIMATING = 1, STATIC }; bool should_rotate; bool should_move; CameraState state; f32 duration; f32 elapsed; int dim; f32 dist_to_move; f32 dist_moved; f32 speed; f32 pitch; f32 yaw; f32 max_pitch; f32 max_yaw; Plane plane; Camera ():max_pitch(80.0f),max_yaw(80.0f){} Camera ( const Camera & ); Camera ( const v3& Eye, const v3& Center, const v3& Up ): should_rotate(false),should_move( true ), pitch(0.0f),yaw(0.0f), max_pitch(80.0f), max_yaw(80.0f) { state = STATIC; F = HMM_NormalizeVec3(HMM_SubtractVec3(Center, Eye)); S = HMM_NormalizeVec3(HMM_Cross(F, Up)); U = HMM_Cross(S, F); P = Eye; } inline void rotate( f32 p, f32 y ){ if ( !should_rotate ) return; pitch += p; yaw += y; yaw = CLAMP( yaw, -max_yaw, max_yaw ); f32 cpitch = cos( HMM_RADIANS( pitch ) ); f32 spitch = sin( HMM_RADIANS( pitch ) ); f32 cyaw = cos( HMM_RADIANS( yaw ) ); f32 syaw = sin( HMM_RADIANS( yaw ) ); F.X = -cpitch * cyaw; F.Y = -syaw; F.Z = -spitch * cyaw ; v3 Up = { 0.0f, 1.0f, 0.0f }; S = HMM_NormalizeVec3(HMM_Cross(F, Up)); U = HMM_Cross(S, F); } m4 transform( ) const { m4 Result; Result.Elements[0][0] = S.X; Result.Elements[0][1] = U.X; Result.Elements[0][2] = -F.X; Result.Elements[0][3] = 0.0f; Result.Elements[1][0] = S.Y; Result.Elements[1][1] = U.Y; Result.Elements[1][2] = -F.Y; Result.Elements[1][3] = 0.0f; Result.Elements[2][0] = S.Z; Result.Elements[2][1] = U.Z; Result.Elements[2][2] = -F.Z; Result.Elements[2][3] = 0.0f; Result.Elements[3][0] = -HMM_DotVec3(S, P); Result.Elements[3][1] = -HMM_DotVec3(U, P); Result.Elements[3][2] = HMM_DotVec3(F, P); Result.Elements[3][3] = 1.0f; return (Result); } void move_towards( float t ){ if ( should_move ) P = P + t * F; } void move_right( float t ){ if ( should_move ) P = P + t * S; } void move_up( float t ){ if ( should_move ) P = P + t * U; } void update( float dt ){ switch ( state ){ case ANIMATING: { #if 0 float dist = dt * (float)dist_to_move/duration; P += dist * direction; elapsed += dt; if ( elapsed >= duration ) state = STATIC; #else float dist = dt * speed; P += dist * basis[dim]; #endif break; } default: break; } } inline void start_animate( int dir,f32 dist, f32 time ){ if ( !should_move ) { state = STATIC; return; } state = ANIMATING; elapsed = 0; dim = dir; dist_to_move = 1.0f; dist_moved = 0.0f; speed = dist/MS_TO_SEC( time ); } inline void toggle_move( ){ should_move = !should_move; } inline void toggle_rotate(){ should_rotate = !should_rotate; } void print( ){ fprintf( stdout, "Camera Info::\nFront: " ); print_v3( F ); fprintf( stdout, "\nRight: " ); print_v3( S ); fprintf( stdout, "\nUp: " ); print_v3( U ); fprintf( stdout, "\nPoint: " ); print_v3( P ); fprintf( stdout, "\n" ); } bool hit_plane( const Ray &ray, v3 &point ) { float d = HMM_DotVec3( ray.direction, F ); if ( abs( d ) < TOLERANCE ) return false; v3 temp = P - ray.start; float t = HMM_DotVec3( temp, F )/d ; point = ray.point_at( t ); return true; } }; enum Keys { KB_KEY_A = 0, KB_KEY_B, KB_KEY_C, KB_KEY_D, KB_KEY_E, KB_KEY_F, KB_KEY_G, KB_KEY_H, KB_KEY_I, KB_KEY_J, KB_KEY_K, KB_KEY_L, KB_KEY_M, KB_KEY_N, KB_KEY_O, KB_KEY_P, KB_KEY_Q, KB_KEY_R, KB_KEY_S, KB_KEY_T, KB_KEY_U, KB_KEY_V, KB_KEY_W, KB_KEY_X, KB_KEY_Y, KB_KEY_Z, KB_KEY_ESCAPE }; enum EventType { MOUSE_RBUTTON_CLICK = 1, MOUSE_LBUTTON_CLICK, MOUSE_MOVE, KB_PRESS_A, KB_PRESS_B, KB_PRESS_C, KB_PRESS_D, KB_PRESS_E, KB_PRESS_F, KB_PRESS_G, KB_PRESS_H, KB_PRESS_I, KB_PRESS_J, KB_PRESS_K, KB_PRESS_L, KB_PRESS_M, KB_PRESS_N, KB_PRESS_O, KB_PRESS_P, KB_PRESS_Q, KB_PRESS_R, KB_PRESS_S, KB_PRESS_T, KB_PRESS_U, KB_PRESS_V, KB_PRESS_W, KB_PRESS_X, KB_PRESS_Y, KB_PRESS_Z, KB_REPEAT_A, KB_REPEAT_B, KB_REPEAT_C, KB_REPEAT_D, KB_REPEAT_E, KB_REPEAT_F, KB_REPEAT_G, KB_REPEAT_H, KB_REPEAT_I, KB_REPEAT_J, KB_REPEAT_K, KB_REPEAT_L, KB_REPEAT_M, KB_REPEAT_N, KB_REPEAT_O, KB_REPEAT_P, KB_REPEAT_Q, KB_REPEAT_R, KB_REPEAT_S, KB_REPEAT_T, KB_REPEAT_U, KB_REPEAT_V, KB_REPEAT_W, KB_REPEAT_X, KB_REPEAT_Y, KB_REPEAT_Z, KB_RELEASE_A, KB_RELEASE_B, KB_RELEASE_C, KB_RELEASE_D, KB_RELEASE_E, KB_RELEASE_F, KB_RELEASE_G, KB_RELEASE_H, KB_RELEASE_I, KB_RELEASE_J, KB_RELEASE_K, KB_RELEASE_L, KB_RELEASE_M, KB_RELEASE_N, KB_RELEASE_O, KB_RELEASE_P, KB_RELEASE_Q, KB_RELEASE_R, KB_RELEASE_S, KB_RELEASE_T, KB_RELEASE_U, KB_RELEASE_V, KB_RELEASE_W, KB_RELEASE_X, KB_RELEASE_Y, KB_RELEASE_Z, KB_PRESS_ESCAPE, KB_RELEASE_ESCAPE, KB_REPEAT_ESCAPE }; struct Event { EventType type; int mods; union { struct { int button; }; struct { int scancode; }; struct { f32 xp,yp; }; }; }; inline Event create_mouse_event( EventType t, int m ){ Event e; e.type = t; e.mods = m; return e; } inline Event create_mouse_event( EventType t,f32 xp, f32 yp ){ Event e; e.type = t; e.xp = xp; e.yp = yp; return e; } inline Event create_keyboard_event( EventType t, int s, int m ){ Event e; e.type = t; e.scancode = s; e.mods = m; return e; } #define MAX_EVENTS 100 static Event Event_Queue[ MAX_EVENTS ]; static uint Event_Count = 0; // Probably want to mutex it void event_push_back( Event e ){ Event_Queue[ Event_Count++ ] = e; } static void APIENTRY glDebugOutput( GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei msgLength, const GLchar* message, const void* userParam) { // ignore non-significant error/warning codes if(id == 131169 || id == 131185 || id == 131218 || id == 131204) return; print_error("---------------"); print_error("Debug message (%d): %s ",id,message); switch (source) { case GL_DEBUG_SOURCE_API: print_error( "Source: API"); break; case GL_DEBUG_SOURCE_WINDOW_SYSTEM: print_error( "Source: Window System"); break; case GL_DEBUG_SOURCE_SHADER_COMPILER: print_error( "Source: Shader Compiler"); break; case GL_DEBUG_SOURCE_THIRD_PARTY: print_error( "Source: Third Party"); break; case GL_DEBUG_SOURCE_APPLICATION: print_error( "Source: Application"); break; case GL_DEBUG_SOURCE_OTHER: print_error( "Source: Other"); break; } switch (type) { case GL_DEBUG_TYPE_ERROR: print_error( "Type: Error"); break; case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: print_error( "Type: Deprecated Behaviour"); break; case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: print_error( "Type: Undefined Behaviour"); break; case GL_DEBUG_TYPE_PORTABILITY: print_error( "Type: Portability"); break; case GL_DEBUG_TYPE_PERFORMANCE: print_error( "Type: Performance"); break; case GL_DEBUG_TYPE_MARKER: print_error( "Type: Marker"); break; case GL_DEBUG_TYPE_PUSH_GROUP: print_error( "Type: Push Group"); break; case GL_DEBUG_TYPE_POP_GROUP: print_error( "Type: Pop Group"); break; case GL_DEBUG_TYPE_OTHER: print_error( "Type: Other"); break; } switch (severity) { case GL_DEBUG_SEVERITY_HIGH: print_error( "Severity: high"); break; case GL_DEBUG_SEVERITY_MEDIUM: print_error( "Severity: medium"); break; case GL_DEBUG_SEVERITY_LOW: print_error( "Severity: low"); break; case GL_DEBUG_SEVERITY_NOTIFICATION: print_error( "Severity: notification"); break; } fprintf(stderr,"\n"); } void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { EventType t ; #define KEY_PRESS_CASE(x) \ case GLFW_KEY_##x: t = KB_PRESS_##x; break; #define KEY_REPEAT_CASE(x) \ case GLFW_KEY_##x: t = KB_REPEAT_##x; break; #define KEY_RELEASE_CASE(x) \ case GLFW_KEY_##x: t = KB_RELEASE_##x; break; if ( action == GLFW_PRESS ){ switch ( key ){ KEY_PRESS_CASE(A) KEY_PRESS_CASE(B) KEY_PRESS_CASE(C) KEY_PRESS_CASE(D) KEY_PRESS_CASE(E) KEY_PRESS_CASE(F) KEY_PRESS_CASE(G) KEY_PRESS_CASE(H) KEY_PRESS_CASE(I) KEY_PRESS_CASE(J) KEY_PRESS_CASE(K) KEY_PRESS_CASE(L) KEY_PRESS_CASE(M) KEY_PRESS_CASE(N) KEY_PRESS_CASE(O) KEY_PRESS_CASE(P) KEY_PRESS_CASE(Q) KEY_PRESS_CASE(R) KEY_PRESS_CASE(S) KEY_PRESS_CASE(T) KEY_PRESS_CASE(U) KEY_PRESS_CASE(V) KEY_PRESS_CASE(W) KEY_PRESS_CASE(X) KEY_PRESS_CASE(Y) KEY_PRESS_CASE(Z) KEY_PRESS_CASE(ESCAPE) default: break; } } else if ( action == GLFW_REPEAT ){ switch ( key ){ KEY_REPEAT_CASE(A) KEY_REPEAT_CASE(B) KEY_REPEAT_CASE(C) KEY_REPEAT_CASE(D) KEY_REPEAT_CASE(E) KEY_REPEAT_CASE(F) KEY_REPEAT_CASE(G) KEY_REPEAT_CASE(H) KEY_REPEAT_CASE(I) KEY_REPEAT_CASE(J) KEY_REPEAT_CASE(K) KEY_REPEAT_CASE(L) KEY_REPEAT_CASE(M) KEY_REPEAT_CASE(N) KEY_REPEAT_CASE(O) KEY_REPEAT_CASE(P) KEY_REPEAT_CASE(Q) KEY_REPEAT_CASE(R) KEY_REPEAT_CASE(S) KEY_REPEAT_CASE(T) KEY_REPEAT_CASE(U) KEY_REPEAT_CASE(V) KEY_REPEAT_CASE(W) KEY_REPEAT_CASE(X) KEY_REPEAT_CASE(Y) KEY_REPEAT_CASE(Z) KEY_REPEAT_CASE(ESCAPE) default: break; } } else if ( action == GLFW_RELEASE ){ switch ( key ){ KEY_RELEASE_CASE(A) KEY_RELEASE_CASE(B) KEY_RELEASE_CASE(C) KEY_RELEASE_CASE(D) KEY_RELEASE_CASE(E) KEY_RELEASE_CASE(F) KEY_RELEASE_CASE(G) KEY_RELEASE_CASE(H) KEY_RELEASE_CASE(I) KEY_RELEASE_CASE(J) KEY_RELEASE_CASE(K) KEY_RELEASE_CASE(L) KEY_RELEASE_CASE(M) KEY_RELEASE_CASE(N) KEY_RELEASE_CASE(O) KEY_RELEASE_CASE(P) KEY_RELEASE_CASE(Q) KEY_RELEASE_CASE(R) KEY_RELEASE_CASE(S) KEY_RELEASE_CASE(T) KEY_RELEASE_CASE(U) KEY_RELEASE_CASE(V) KEY_RELEASE_CASE(W) KEY_RELEASE_CASE(X) KEY_RELEASE_CASE(Y) KEY_RELEASE_CASE(Z) KEY_RELEASE_CASE(ESCAPE) default: break; } } event_push_back( create_keyboard_event(t, scancode, mods ) ); } void process_keyboard_input( GLFWwindow *window, uint8 *key_map ){ uint8 press = 0; #define GET_KEY_STATE(key) \ press = glfwGetKey( window, GLFW_KEY_##key );\ key_map[KB_KEY_##key] = ( press==GLFW_RELEASE )?0:1; GET_KEY_STATE(A) GET_KEY_STATE(B) GET_KEY_STATE(C) GET_KEY_STATE(D) GET_KEY_STATE(E) GET_KEY_STATE(F) GET_KEY_STATE(G) GET_KEY_STATE(H) GET_KEY_STATE(I) GET_KEY_STATE(J) GET_KEY_STATE(K) GET_KEY_STATE(L) GET_KEY_STATE(M) GET_KEY_STATE(N) GET_KEY_STATE(O) GET_KEY_STATE(P) GET_KEY_STATE(Q) GET_KEY_STATE(R) GET_KEY_STATE(S) GET_KEY_STATE(T) GET_KEY_STATE(U) GET_KEY_STATE(V) GET_KEY_STATE(W) GET_KEY_STATE(X) GET_KEY_STATE(Y) GET_KEY_STATE(Z) GET_KEY_STATE(ESCAPE) } void mouse_callback( GLFWwindow *window, double xpos, double ypos ){ event_push_back( create_mouse_event( MOUSE_MOVE, (f32)xpos,(f32)ypos) ); glfwSetCursorPosCallback( window, NULL ); } void mouse_button_callback( GLFWwindow* window, int button, int action, int mods ) { if ( action == GLFW_PRESS ){ switch ( button ){ case GLFW_MOUSE_BUTTON_RIGHT: event_push_back( create_mouse_event( MOUSE_RBUTTON_CLICK,mods)); break; case GLFW_MOUSE_BUTTON_LEFT: event_push_back( create_mouse_event( MOUSE_LBUTTON_CLICK, mods)); break; default: break; } } #if 0 if ( action == GLFW_PRESS ){ switch (button){ case GLFW_MOUSE_BUTTON_RIGHT: { int viewport[4]; glGetIntegerv( GL_VIEWPORT, viewport); fprintf( stderr, "View port info: %d, %d, %d, %d\n", viewport[0], viewport[1], viewport[2], viewport[3] ); double cp[2]; if ( glfwGetWindowAttrib(window, GLFW_HOVERED ) ){ glfwGetCursorPos( window, &cp[0], &cp[1] ); fprintf( stdout, "%f, %f\n", (f32)cp[0], (f32) cp[1] ); } v3 point = v3{ ( float )cp[0], (float)cp[1], 0.0f }; v3 wp = HMM_UnProject( point, mvp, SCREEN_WIDTH, SCREEN_HEIGHT ); fprintf( stdout, "The point in world coords is: " ); print_v3( wp ); fprintf( stdout, "\n" ); break; } default: break; } } #endif } void resizeCallback(GLFWwindow* window, int width, int height) { glViewport(0, 0, width, height); ScreenHeight = height; ScreenWidth = width; } #define CLEANUP(x) __func__##x int compile_shader( guint *ret, const char *source, GLenum type ){ uint shader = glCreateShader( type ); char *buff; if ( read_text_file_to_buffer( source, &buff ) == -1 ){ goto CLEANUP(1); } glShaderSource( shader, 1, &buff, NULL ); glCompileShader( shader ); int success; glGetShaderiv( shader, GL_COMPILE_STATUS, &success ); if ( success == GL_FALSE ){ char infoLog[512]; glGetShaderInfoLog(shader, 512, NULL, infoLog); print_error("Failed to compile Shader!\n \ Location:\n %s\ \n%s\n", source, infoLog ); goto CLEANUP(2); } *ret = shader; return 0; CLEANUP(2): assert( shader != 0 ); glDeleteShader( shader ); free( buff ); CLEANUP(1): return -1; } int compile_program( guint *program, const char *vsource ,const char *fsource ){ guint vshader, fshader, prog; if ( compile_shader( &vshader, vsource, GL_VERTEX_SHADER ) == -1 ){ goto CLEANUP(1); } if ( compile_shader( &fshader, fsource, GL_FRAGMENT_SHADER) == -1 ){ goto CLEANUP(1); } prog = glCreateProgram(); glAttachShader( prog, vshader ); glAttachShader( prog, fshader ); glLinkProgram( prog ); int success; glGetProgramiv( prog, GL_LINK_STATUS, &success ); if ( success == GL_FALSE ){ char infoLog[512]; glGetProgramInfoLog( prog , 512, NULL, infoLog ); print_error( "Failed to link Shader!\n\ %s", infoLog ); goto CLEANUP( 2 ); } *program = prog; glDeleteShader( vshader ); glDeleteShader( fshader ); return 0; CLEANUP(2): glDeleteShader( vshader ); glDeleteShader( fshader ); CLEANUP(1): *program = 0; return -1; } void flipImage( uint8 *data, int width, int height){ int top = 0, bottom = height - 1; while ( top <= bottom ){ uint8 *topPixel = data + top * width * 4; uint8 *botPixel = data + bottom* width * 4; for ( int i = 0; i < width * 4 ; i++ ){ uint8 tmp = *topPixel; *topPixel++ = *botPixel; *botPixel++ = tmp; } top++; bottom--; } } struct LineVertexBufferData{ v3 p; v3 color; }; struct ColorVertexData{ v3 p; v3 color; v3 n; }; struct QuadVertexData { v3 p0,p1,p2,p3; v3 c0,c1,c2,c3; v3 n0,n1,n2,n3; }; struct RenderContext { ColorVertexData *color_vertex_data_buff = NULL; const uint max_color_vertex_data = 5000; uint num_color_vertex = 0; GLenum *color_vertex_modes = NULL; } Rc; void add_color_vertex( const v3 &p, const v3 &color, GLenum mode ){ ColorVertexData v = { p, color }; Rc.color_vertex_data_buff[ Rc.num_color_vertex ] = v; Rc.color_vertex_modes[ Rc.num_color_vertex ] = mode; Rc.num_color_vertex++; } void draw_color_line( v3 start ,v3 end, v3 color ){ add_color_vertex( start, color, GL_LINES ); add_color_vertex( end, color, GL_LINES ); } void draw_color_vertex( const m4 &mvp ){ } struct GridProgramInfo{ uint id; uint mvp_loc; uint corner_loc; uint width_loc; uint8 pos_id; uint8 direction_id; uint8 color_id; }; struct PointLightLocation{ uint pos_loc; uint color_loc; }; struct SimpleColorShaderProgram { uint id; uint mvp_loc; uint model_loc; uint view_loc; uint view_pos_loc; uint texture0_loc; // Frag. shader PointLightLocation point_light_loc[4]; uint num_lights_loc; uint amb_loc; uint8 pos_id; uint8 color_id; uint8 normal_id; uint8 tex_coords_id; }; struct SimpleNLColorShaderProgram { uint id; uint mvp_loc; uint8 pos_id; uint8 color_id; uint8 normal_id; }; static GridProgramInfo grid_program_info; static SimpleColorShaderProgram simple_color_shader_info; static SimpleNLColorShaderProgram nl_color_shader_info; int create_grid_program( ){ if ( compile_program(&grid_program_info.id, "./shaders/grid_shader.vert", "./shaders/grid_shader.frag" ) == -1 ){ fprintf(stderr,"Unable to compile Program!\n"); return -1; } const int &id = grid_program_info.id; glUseProgram( id ); grid_program_info.mvp_loc = glGetUniformLocation( id,"mvp" ); grid_program_info.corner_loc = glGetUniformLocation( id,"corner_pos" ); grid_program_info.width_loc = glGetUniformLocation( id,"width" ); grid_program_info.pos_id = 0; grid_program_info.direction_id = 1; grid_program_info.color_id = 2; return 0; } int create_simple_color_shader_program( ){ if ( compile_program(&simple_color_shader_info.id, "./shaders/simple-color-shader.vert", "./shaders/simple-color-shader.frag" ) == -1 ){ fprintf(stderr,"Unable to compile Program!\n"); return -1; } const int &id = simple_color_shader_info.id; glUseProgram( id ); simple_color_shader_info.mvp_loc = glGetUniformLocation( id,"mvp" ); char buff[256]; for ( int i = 0; i < 4; i++ ){ snprintf( buff, 256, "point_lights[%d].pos",i ); simple_color_shader_info.point_light_loc[i].pos_loc = glGetUniformLocation( id, buff ); snprintf( buff, 256, "point_lights[%d].color",i ); simple_color_shader_info.point_light_loc[i].color_loc= glGetUniformLocation( id, buff ); } simple_color_shader_info.model_loc = glGetUniformLocation( id, "model"); simple_color_shader_info.view_loc = glGetUniformLocation( id, "view" ); simple_color_shader_info.num_lights_loc = glGetUniformLocation( id, "num_lights" ); simple_color_shader_info.amb_loc = glGetUniformLocation( id, "amb" ); simple_color_shader_info.view_pos_loc=glGetUniformLocation( id, "view_pos" ); simple_color_shader_info.texture0_loc = glGetUniformLocation( id,"texture0"); simple_color_shader_info.pos_id = 0; simple_color_shader_info.color_id = 1; simple_color_shader_info.normal_id = 2; simple_color_shader_info.tex_coords_id = 3; glUseProgram( 0 ); return 0; } int create_nl_color_shader_program( ){ if ( compile_program(&nl_color_shader_info.id, "./shaders/simple-color-shader-nl.vert", "./shaders/simple-color-shader-nl.frag" ) == -1 ){ fprintf(stderr,"Unable to compile Program!\n"); return -1; } const int &id = nl_color_shader_info.id; glUseProgram( id ); nl_color_shader_info.mvp_loc = glGetUniformLocation( id,"mvp" ); nl_color_shader_info.pos_id = 0; nl_color_shader_info.color_id = 1; nl_color_shader_info.normal_id = 2; glUseProgram( 0 ); return 0; } #if 0 void AABB_generate_vertex( const AABB &box, v3 *mem ){ f32 xlen = box.u[0] - box.l[0]; f32 ylen = box.u[1] - box.l[1]; f32 zlen = box.u[2] - box.l[2]; //back v3 a0 = box.l; v3 a1 = box.l + v3{ xlen, 0, 0 }; v3 a2 = box.l + v3{ xlen, ylen, 0 }; v3 a3 = box.l + v3{ 0, ylen, 0 }; //front v3 a0 = box.l + v3{ 0,0,zlen}; v3 a1 = box.l + v3{ xlen, 0, zlen }; v3 a2 = box.l + v3{ xlen, ylen, zlen }; v3 a3 = box.l + v3{ 0, ylen, zlen }; //left v3 a0 = box.l + v3{ 0,0,0}; v3 a1 = box.l + v3{ 0,0,zlen }; v3 a2 = box.l + v3{ 0,ylen,zlen }; v3 a3 = box.l + v3{ 0,ylen,0 }; //right v3 a0 = box.l + v3{ xlen,0,0}; v3 a1 = box.l + v3{ xlen,0,zlen }; v3 a2 = box.l + v3{ xlen,ylen,zlen }; v3 a3 = box.l + v3{ xlen,ylen,0 }; // bottom v3 a0 = box.l + v3{ 0,0,0}; v3 a1 = box.l + v3{ xlen,0,0}; v3 a2 = box.l + v3{ xlen,0,zlen}; v3 a3 = box.l + v3{ 0,0,zlen }; //top v3 a0 = box.l + v3{ 0,ylen,0}; v3 a1 = box.l + v3{ xlen,ylen,0}; v3 a2 = box.l + v3{ xlen,ylen,zlen}; v3 a3 = box.l + v3{ 0,ylen,zlen }; } #endif struct ColorQuad { v3 p0,p1,p2,p3; v3 color; v3 n; }; struct Image { int h,w,channels; uint8 *data; }; struct Light { Object object; v3 color; }; struct Texture { enum TextureType { COLOR = 0, CHECKER, MARBLE, }; TextureType type; union { v3 face_colors[6]; v3 color; }; Image image; }; struct Material { enum MaterialType{ METALLIC = 0, PURE_DIFFUSE, GLASS, }; MaterialType type; Texture texture; f32 diffuse, specular, shine; }; Material create_material_diffuse( Texture t ){ Material m; m.type = Material::PURE_DIFFUSE; m.texture = t; m.diffuse = 1.0f; m.specular = 0.0f; m.shine = 0.0f; return m; } Material create_material_metallic( Texture t ){ Material m; m.type = Material::METALLIC; m.texture = t; m.diffuse = 0.3f; m.specular = 8.0f; m.shine = 64.0f; return m; } Material create_material_glass( ){ Material m; Texture t; t.type = Texture::COLOR; t.color = v3{ 0.0f,0.0f,1.0f }; m.type = Material::GLASS; m.texture = t; return m; } struct World { enum State { STATE_INVALID = 0, STATE_FREE_VIEW = 1, STATE_DETACHED, STATE_ON_HOLD, STATE_SELECTED, STATE_VIEW_CAMERA, }; State state; bool show_imgui; m4 ui_perspective; m4 view_perspective; f32 ui_vfov, ui_near_plane, ui_far_plane; f32 view_vfov, view_near_plane, view_far_plane; m4 perspective; Camera ui_camera; Camera view_camera; Camera *camera; Grid grid; Cube cube; Cube *cubes; Sphere *spheres; Rectangle *rects; Material *cube_materials; Material *sphere_materials; Material *rect_materials; v3 *light_pos; v3 *light_colors; v3 amb_light; v3 *light_cube_color; v3 *light_sphere_color; v3 *light_rect_color; Cube *light_cubes; Sphere *light_spheres; Rectangle *light_rects; uint *light_cubes_vao; uint *light_cubes_vbo; uint *light_spheres_vao; uint *light_spheres_vbo; uint *light_rect_vao; Line *lines; ColorQuad *temp_color_quads; ColorQuad *perm_color_quads; bool is_selected; Object selected_object; GetAABBFunc selected_aabb; TranslateFunc selected_move; RotateFunc selected_rotate; ScaleFunc selected_scale; uint selected_index; void *selected_data; bool is_holding; Object hold_object; int hold_object_id; AABB *boxes; // Dear imgui selection stuff int cube_face_dropdown; v3 cube_face_color; v3 cube_side_length; f32 sel_cube_length; int cube_material_dropdown; int cube_texture_dropdown; v3 sphere_face_color; f32 sel_sphere_radius; int sphere_material_dropdown; int sphere_texture_dropdown; v3 rect_face_color; int rect_flip_normal; f32 sel_rect_l1; f32 sel_rect_l2; int rect_material_dropdown; int rect_texture_dropdown; v3 light_cube_face_color; v3 light_sphere_face_color; v3 light_rect_face_color; int object_select_dropdown; uint grid_vao, grid_vbo, grid_ebo; uint cube_vao, cube_vbo, cube_ebo; uint *cubes_vao; uint *cubes_vbo; uint *spheres_vao; uint *spheres_vbo; v3 *sphere_colors; v3 *rect_colors; m4 *spheres_transform; m4 *model_matrices[_OBJECT_MAX]; uint color_vao, color_vbo, color_ebo; uint rect_vao, rect_vbo, rect_ebo; uint white_texture, checker_texture, marble_texture; v3 *color_vertex_data; uint *color_vertex_indices; uint *index_stack; // Used as stack GLenum *color_vertex_modes; // Used as stack }; void world_config_simple_color_shader_buffer( uint vao, uint vbo, uint ebo, size_t vertex_count ) { glBindVertexArray( vao ); glBindBuffer( GL_ARRAY_BUFFER, vbo ); size_t offset= sizeof(v3)*vertex_count; glBufferData( GL_ARRAY_BUFFER, 3 * offset + sizeof(v2) * vertex_count, NULL, GL_STREAM_DRAW ); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, ebo); glEnableVertexAttribArray(simple_color_shader_info.pos_id ); glVertexAttribPointer( simple_color_shader_info.pos_id, 3, GL_FLOAT, GL_FALSE, sizeof( v3 ), (void *)0 ); glEnableVertexAttribArray( simple_color_shader_info.color_id ); glVertexAttribPointer( simple_color_shader_info.color_id, 3, GL_FLOAT, GL_FALSE, sizeof(v3), (void *)(offset) ); glEnableVertexAttribArray( simple_color_shader_info.normal_id ); glVertexAttribPointer( simple_color_shader_info.normal_id, 3, GL_FLOAT, GL_FALSE, sizeof(v3), (void *)( 2 * offset) ); glEnableVertexAttribArray( simple_color_shader_info.tex_coords_id ); glVertexAttribPointer( simple_color_shader_info.tex_coords_id, 2, GL_FLOAT, GL_FALSE, sizeof(v2), (void *)( 3 * offset) ); glBindVertexArray( 0 ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 ); } void world_config_nl_color_shader_buffer( uint vao, uint vbo, uint ebo, size_t size ) { glBindVertexArray( vao ); glBindBuffer( GL_ARRAY_BUFFER, vbo ); size_t offset=size; glBufferData( GL_ARRAY_BUFFER, 3 * offset, NULL, GL_STREAM_DRAW ); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, ebo); glEnableVertexAttribArray(nl_color_shader_info.pos_id ); glVertexAttribPointer( nl_color_shader_info.pos_id, 3, GL_FLOAT, GL_FALSE, sizeof( v3 ), (void *)0 ); glEnableVertexAttribArray( nl_color_shader_info.color_id ); glVertexAttribPointer( nl_color_shader_info.color_id, 3, GL_FLOAT, GL_FALSE, sizeof(v3), (void *)(offset) ); glEnableVertexAttribArray( nl_color_shader_info.normal_id ); glVertexAttribPointer( nl_color_shader_info.normal_id, 3, GL_FLOAT, GL_FALSE, sizeof(v3), (void *)( 2 * offset) ); glBindVertexArray( 0 ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 ); } #define GLASS_COLOR v3{0.0f,0.0f,1.0f}; void world_add_cube_vertex_data( const World &w, uint index ){ v3 colors[24]; Material &m = w.cube_materials[index]; if ( m.type == Material::GLASS ){ for ( int i = 0; i < 24; i++ ){ colors[ i ] = GLASS_COLOR; } } else { Texture &tex = m.texture; for ( int i = 0; i < 24; i++ ){ int index = i / 4; colors[ i ] = tex.face_colors[ index ]; } } uint vao = w.cubes_vao[index]; uint vbo = w.cubes_vbo[index]; glBindVertexArray( vao ); glBindBuffer( GL_ARRAY_BUFFER, vbo ); glBufferSubData( GL_ARRAY_BUFFER, 0, sizeof(CubeVertices), CubeVertices ); glBufferSubData( GL_ARRAY_BUFFER, sizeof(CubeVertices), sizeof(colors), colors); glBufferSubData( GL_ARRAY_BUFFER, sizeof(CubeVertices) + sizeof(colors), sizeof(CubeNormals), (void *)CubeNormals); glBufferSubData( GL_ARRAY_BUFFER, 3*sizeof(CubeVertices), sizeof(CubeTexCoords), (void *)CubeTexCoords ); glBindVertexArray( 0 ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); } void world_generate_cube_data( uint &vao, uint &vbo, Cube &cube ){ glGenVertexArrays( 1, &vao ); glGenBuffers( 1, &vbo ); world_config_simple_color_shader_buffer( vao, vbo, quad_elem_buffer_index, 24 ); glBindVertexArray( 0 ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 ); } void world_add_light_cube_vertex_data( const World &w, uint index ) { v3 colors[24]; for ( int i = 0; i < 24; i++ ){ colors[ i ] = w.light_cube_color[index]; } glBindVertexArray( w.light_cubes_vao[index] ); glBindBuffer( GL_ARRAY_BUFFER, w.light_cubes_vbo[index] ); glBufferSubData( GL_ARRAY_BUFFER, 0, sizeof(CubeVertices), CubeVertices ); glBufferSubData( GL_ARRAY_BUFFER, sizeof(CubeVertices), sizeof(colors), colors); glBufferSubData( GL_ARRAY_BUFFER, sizeof(CubeVertices) + sizeof(colors), sizeof(CubeNormals), (void *)CubeNormals); glBindVertexArray( 0 ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); } void world_generate_light_cube( uint &vao, uint &vbo, Cube &cube ){ glGenVertexArrays( 1, &vao ); glGenBuffers( 1, &vbo ); world_config_nl_color_shader_buffer( vao, vbo, quad_elem_buffer_index, sizeof(CubeVertices) ); glBindVertexArray( 0 ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 ); } void world_add_sphere_vertex_data( const World &w, uint index ) { Material &material = w.sphere_materials[index]; v3 color = w.sphere_materials[index].texture.color; if ( material.type == Material::GLASS ){ color = GLASS_COLOR; } for ( uint i = 0; i < array_length( SphereVertices ); i++ ){ array_push( SphereColorBuff, color ); } size_t data_size = array_length(SphereVertices)*sizeof(*SphereVertices); uint vao = w.spheres_vao[index]; uint vbo = w.spheres_vbo[index]; glBindVertexArray( vao ); glBindBuffer( GL_ARRAY_BUFFER, vbo ); glBufferSubData( GL_ARRAY_BUFFER, data_size, data_size, SphereColorBuff); glBindVertexArray( 0 ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); array_clear( SphereColorBuff ); } void world_add_light_sphere_vertex_data( const World &w, uint index ) { v3 &color = w.light_sphere_color[index]; for ( uint i = 0; i < array_length( SphereVertices ); i++ ){ array_push( SphereColorBuff, color ); } glBindVertexArray( w.light_spheres_vao[index] ); glBindBuffer( GL_ARRAY_BUFFER, w.light_spheres_vbo[index] ); size_t data_size = sizeof(v3) * array_length( SphereVertices ); glBufferSubData( GL_ARRAY_BUFFER, data_size, data_size, SphereColorBuff); glBindVertexArray( 0 ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); array_clear( SphereColorBuff ); } void world_add_cube( World &w, Cube *cube, Material m ){ uint vao, vbo; array_push( w.cubes, *cube ); #if 0 m4 model = HMM_Scale( v3{ cube->length, cube->length, cube->length } ) HMM_Translate(cube->pos) ; #else m4 model = HMM_Translate(cube->pos)*HMM_Scale( v3{ cube->length, cube->length, cube->length } ) ; #endif array_push( w.model_matrices[OBJECT_CUBE_INSTANCE],model ); array_push( w.cube_materials, m ); glGenVertexArrays( 1, &vao ); glGenBuffers( 1, &vbo ); world_config_simple_color_shader_buffer( vao, vbo, quad_elem_buffer_index, 24 ); glBindVertexArray( 0 ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 ); array_push( w.cubes_vao, vao ); array_push( w.cubes_vbo, vbo ); world_add_cube_vertex_data(w, array_length(w.cubes)-1 ); } void world_add_light_cube( World &w, Cube *cube, v3 color ){ uint vao, vbo; array_push( w.light_cubes, *cube ); m4 model = HMM_Translate(cube->pos) * HMM_Scale( v3{ cube->length, cube->length, cube->length } ); array_push( w.model_matrices[OBJECT_LIGHT_CUBE_INSTANCE],model ); array_push( w.light_cube_color, color ); glGenVertexArrays( 1, &vao ); glGenBuffers( 1, &vbo ); world_config_nl_color_shader_buffer( vao, vbo, quad_elem_buffer_index, sizeof(CubeVertices) ); glBindVertexArray( 0 ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 ); array_push( w.light_cubes_vao, vao ); array_push( w.light_cubes_vbo, vbo ); world_add_light_cube_vertex_data(w,array_length(w.light_cubes)-1 ); } void world_add_sphere( World &w, const Sphere &s, Material m){ uint vao, vbo; array_push( w.spheres, s ); m4 transform = HMM_Translate( s.c ) * HMM_Scale( v3{ s.r, s.r,s.r }); array_push( w.model_matrices[OBJECT_SPHERE], transform ); //array_push( w.sphere_colors, color ); array_push( w.sphere_materials, m ); glGenVertexArrays( 1, &vao ); glGenBuffers( 1, &vbo ); world_config_simple_color_shader_buffer( vao, vbo, sphere_element_buffer, array_length(SphereVertices)); glBindVertexArray( vao ); glBindBuffer( GL_ARRAY_BUFFER, vbo ); size_t data_size = sizeof(v3) * array_length( SphereVertices ); glBufferSubData( GL_ARRAY_BUFFER, 0,data_size , SphereVertices ); glBufferSubData( GL_ARRAY_BUFFER, 2 * data_size, data_size, (void *) SphereNormals ); glBufferSubData( GL_ARRAY_BUFFER, 3*data_size, sizeof(v2) * array_length( SphereTextureCoords ), (void *)SphereTextureCoords ); glBindVertexArray( 0 ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 ); array_push( w.spheres_vao, vao ); array_push( w.spheres_vbo, vbo ); world_add_sphere_vertex_data(w,array_length(w.spheres)-1); } void world_add_light_sphere( World &w, const Sphere &s, v3 color ){ uint vao, vbo; array_push( w.light_spheres, s ); m4 transform = HMM_Translate( s.c ) * HMM_Scale( v3{ s.r, s.r,s.r }); array_push( w.model_matrices[OBJECT_LIGHT_SPHERE], transform ); array_push( w.light_sphere_color, color ); glGenVertexArrays( 1, &vao ); glGenBuffers( 1, &vbo ); size_t offset= array_length(SphereVertices)*sizeof(*SphereVertices); world_config_nl_color_shader_buffer( vao, vbo, sphere_element_buffer, offset ); glBindVertexArray( vao ); glBindBuffer( GL_ARRAY_BUFFER, vbo ); size_t data_size = sizeof(v3) * array_length( SphereVertices ); glBufferSubData( GL_ARRAY_BUFFER, 0,data_size , SphereVertices ); glBufferSubData( GL_ARRAY_BUFFER, 2 * data_size, data_size, (void *) SphereNormals ); glBindVertexArray( 0 ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 ); array_push( w.light_spheres_vao, vao ); array_push( w.light_spheres_vbo, vbo ); world_add_light_sphere_vertex_data( w, array_length(w.light_spheres)-1 ); } void world_add_rect( World &w, const Rectangle &r,Material m ){ array_push( w.rects, r ); m4 transform = HMM_Mat4d( 1.0f ); array_push( w.rect_materials, m ); array_push( w.model_matrices[OBJECT_RECT], transform ); //array_push( w.rect_colors, color ); } void world_add_light_rect( World &w, const Rectangle &r, v3 color ){ array_push( w.light_rects, r ); m4 transform = HMM_Mat4d( 1.0f ); array_push( w.model_matrices[OBJECT_RECT], transform ); array_push( w.light_rect_color, color ); } void world_generate_grid_data( World &w, Grid &g ){ const v3 &color = g.color; glGenVertexArrays(1,&w.grid_vao); glGenBuffers(1,&w.grid_vbo); f32 len = 100.0f; glBindVertexArray( w.grid_vao ); glBindBuffer( GL_ARRAY_BUFFER, w.grid_vbo ); v3 vertex_data[12]; vertex_data[0] = g.rect.corner + len * g.dir1; vertex_data[1] = g.dir2; vertex_data[2] = color; vertex_data[3] = g.rect.corner; vertex_data[4] = g.dir2; vertex_data[5] = color; vertex_data[6] = g.rect.corner; vertex_data[7] = g.dir1; vertex_data[8] = color; vertex_data[9] = g.rect.corner + len * g.dir2; vertex_data[10] = g.dir1; vertex_data[11] = color; glBufferData( GL_ARRAY_BUFFER, sizeof( vertex_data ), vertex_data, GL_STATIC_DRAW ); GLsizei stride = 3 * sizeof(v3); glEnableVertexAttribArray( grid_program_info.pos_id ); glEnableVertexAttribArray( grid_program_info.direction_id); glEnableVertexAttribArray( grid_program_info.color_id ); glVertexAttribPointer( grid_program_info.pos_id, 3, GL_FLOAT, GL_FALSE, stride, (void *)( 0 ) ); glVertexAttribPointer( grid_program_info.direction_id, 3, GL_FLOAT, GL_FALSE, stride, (void *)( sizeof(v3) ) ); glVertexAttribPointer( grid_program_info.color_id, 3, GL_FLOAT, GL_FALSE, stride, (void *)( 2 * sizeof(v3) ) ); glBindVertexArray( 0 ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 ); } void world_draw_AABB( const World &w, const AABB &box, v3 color, uint *elem_index ) { // Sorry for this shit, but its the best i can do for now // TODO: find something better f32 xlen = box.u[0] - box.l[0]; f32 ylen = box.u[1] - box.l[1]; f32 zlen = box.u[2] - box.l[2]; array_push( w.color_vertex_data, box.l); array_push( w.color_vertex_data, color ); array_push( w.color_vertex_data, v3{0.0f,0.0f,0.0f} ); array_push( w.color_vertex_data, box.l + v3{ xlen, 0, 0 }); array_push( w.color_vertex_data, color ); array_push( w.color_vertex_data, v3{0.0f,0.0f,0.0f} ); array_push( w.color_vertex_data, box.l + v3{ xlen, ylen, 0 }); array_push( w.color_vertex_data, color ); array_push( w.color_vertex_data, v3{0.0f,0.0f,0.0f} ); array_push( w.color_vertex_data, box.l + v3{ 0, ylen, 0 }); array_push( w.color_vertex_data, color ); array_push( w.color_vertex_data, v3{0.0f,0.0f,0.0f} ); // front array_push( w.color_vertex_data, box.l + v3{ 0,0,zlen}); array_push( w.color_vertex_data, color ); array_push( w.color_vertex_data, v3{0.0f,0.0f,0.0f} ); array_push( w.color_vertex_data, box.l + v3{ xlen, 0, zlen }); array_push( w.color_vertex_data, color ); array_push( w.color_vertex_data, v3{0.0f,0.0f,0.0f} ); array_push( w.color_vertex_data, box.l + v3{ xlen, ylen, zlen }); array_push( w.color_vertex_data, color ); array_push( w.color_vertex_data, v3{0.0f,0.0f,0.0f} ); array_push( w.color_vertex_data, box.l + v3{ 0, ylen, zlen }); array_push( w.color_vertex_data, color ); array_push( w.color_vertex_data, v3{0.0f,0.0f,0.0f} ); uint value = *elem_index; array_push( w.color_vertex_indices, value ); array_push( w.color_vertex_indices, value + 1 ); array_push( w.color_vertex_indices, value + 1 ); array_push( w.color_vertex_indices, value + 2 ); array_push( w.color_vertex_indices, value + 2 ); array_push( w.color_vertex_indices, value + 3 ); array_push( w.color_vertex_indices, value + 3 ); array_push( w.color_vertex_indices, value ); array_push( w.color_vertex_indices, value ); array_push( w.color_vertex_indices, value + 4 ); array_push( w.color_vertex_indices, value + 4 ); array_push( w.color_vertex_indices, value + 5 ); array_push( w.color_vertex_indices, value + 5 ); array_push( w.color_vertex_indices, value + 6 ); array_push( w.color_vertex_indices, value + 6 ); array_push( w.color_vertex_indices, value + 7 ); array_push( w.color_vertex_indices, value + 7 ); array_push( w.color_vertex_indices, value + 4 ); array_push( w.color_vertex_indices, value + 3 ); array_push( w.color_vertex_indices, value + 7 ); array_push( w.color_vertex_indices, value + 2 ); array_push( w.color_vertex_indices, value + 6 ); array_push( w.color_vertex_indices, value + 1 ); array_push( w.color_vertex_indices, value + 5 ); *elem_index = value + 8; return; } void world_draw_grid(uint vao,const Grid &g, const m4 &mvp ){ glUseProgram( grid_program_info.id ); // Generate rectangle vertices with line vertices glUniformMatrix4fv( grid_program_info.mvp_loc, 1,GL_FALSE, HMM_MAT4_PTR(mvp) ); glUniform3fv( grid_program_info.corner_loc, 1, g.rect.corner.Elements ); glUniform1f( grid_program_info.width_loc, g.w ); glBindVertexArray( vao ); glDrawArraysInstanced( GL_LINES, 0, 12, g.nlines ); glBindVertexArray( 0 ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); glUseProgram( 0 ); } void world_draw_cube(uint vao, const Cube &cube, const m4 &mvp ){ glUseProgram( simple_color_shader_info.id ); glUniformMatrix4fv( simple_color_shader_info.mvp_loc, 1,GL_FALSE, HMM_MAT4_PTR(mvp) ); glBindVertexArray( vao ); glDrawElements( GL_TRIANGLES, 36, GL_UNSIGNED_INT, 0 ); glBindVertexArray( 0 ); glUseProgram( 0 ); } void world_draw_sphere( uint vao, const Sphere &s, const m4 &mvp ){ glUseProgram( simple_color_shader_info.id ); glUniformMatrix4fv( simple_color_shader_info.mvp_loc, 1,GL_FALSE, HMM_MAT4_PTR(mvp) ); glBindVertexArray( vao ); glDrawElements( GL_TRIANGLES, array_length(SphereIndices), GL_UNSIGNED_INT, 0 ); glBindVertexArray( 0 ); glUseProgram( 0 ); } void draw_world( const World &w ){ m4 v = w.camera->transform(); m4 vp = w.perspective*v; world_draw_grid( w.grid_vao,w.grid,vp); // draw the non-lighting stuff glUseProgram( nl_color_shader_info.id ); m4 *cube_models = w.model_matrices[ OBJECT_LIGHT_CUBE_INSTANCE ]; for ( uint i = 0; i < array_length( w.light_cubes ); i++ ){ m4 mvp = vp * cube_models[i]; glBindVertexArray( w.light_cubes_vao[i] ); glUniformMatrix4fv( nl_color_shader_info.mvp_loc, 1,GL_FALSE, HMM_MAT4_PTR(mvp) ); glDrawElements( GL_TRIANGLES, 36, GL_UNSIGNED_INT, 0 ); array_push( w.light_pos, w.light_cubes[i].pos ); array_push( w.light_colors, w.light_cube_color[i] ); } m4 *sphere_models = w.model_matrices[ OBJECT_LIGHT_SPHERE ]; for ( uint i = 0; i < array_length( w.light_spheres ); i++ ){ m4 mvp = vp * sphere_models[i]; glUniformMatrix4fv( nl_color_shader_info.mvp_loc, 1,GL_FALSE, HMM_MAT4_PTR(mvp) ); glBindVertexArray( w.light_spheres_vao[i] ); glDrawElements( GL_TRIANGLES, array_length(SphereIndices), GL_UNSIGNED_INT, 0 ); glBindVertexArray( 0 ); array_push( w.light_pos, w.light_spheres[i].c ); array_push( w.light_colors, w.light_sphere_color[i] ); } uint value = 0; for ( uint i = 0; i < array_length( w.light_rects ); i++ ){ Rectangle &r = w.light_rects[i]; v3 &color = w.light_rect_color[i]; array_push( w.light_pos, r.p0 + ( r.l1 / 2 )*r.s1 + (r.l2/2)*r.s2 ); array_push( w.light_colors, w.light_rect_color[i] ); array_push( w.color_vertex_data, r.p0 ); array_push( w.color_vertex_data, color ); array_push( w.color_vertex_data, r.n ); array_push( w.color_vertex_data, r.p1 ); array_push( w.color_vertex_data, color ); array_push( w.color_vertex_data, r.n ); array_push( w.color_vertex_data, r.p2 ); array_push( w.color_vertex_data, color ); array_push( w.color_vertex_data, r.n ); array_push( w.color_vertex_data, r.p3 ); array_push( w.color_vertex_data, color ); array_push( w.color_vertex_data, r.n ); // push the indices array_push( w.color_vertex_indices, value ); array_push( w.color_vertex_indices, value + 1 ); array_push( w.color_vertex_indices, value + 2 ); array_push( w.color_vertex_indices, value + 2 ); array_push( w.color_vertex_indices, value + 3 ); array_push( w.color_vertex_indices, value ); value += 4; } glBindVertexArray( w.color_vao ); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, w.color_ebo ); glBufferData( GL_ELEMENT_ARRAY_BUFFER, sizeof(uint) * array_length( w.color_vertex_indices ), w.color_vertex_indices, GL_STATIC_DRAW ); glBindBuffer( GL_ARRAY_BUFFER, w.color_vbo ); glBufferData( GL_ARRAY_BUFFER, sizeof(v3) * array_length( w.color_vertex_data ), w.color_vertex_data, GL_STATIC_DRAW ); glUniformMatrix4fv( simple_color_shader_info.mvp_loc, 1,GL_FALSE, HMM_MAT4_PTR(vp) ); glDrawElements(GL_TRIANGLES,array_length(w.color_vertex_data), GL_UNSIGNED_INT, 0 ); array_clear( w.color_vertex_data ); array_clear( w.color_vertex_indices ); glUseProgram( 0 ); // Draw all the lighting stuff glUseProgram( simple_color_shader_info.id ); glUniform1i( simple_color_shader_info.texture0_loc, 0 ); glUniform3fv(simple_color_shader_info.view_pos_loc, 1, w.camera->P.Elements ); uint loop_count = array_length( w.light_pos ) < 4 ? array_length( w.light_pos ) : 4; for ( uint i = 0; i < loop_count ; i++ ){ PointLightLocation &p = simple_color_shader_info.point_light_loc[i]; glUniform3fv( p.pos_loc,1, w.light_pos[i].Elements ); glUniform3fv( p.color_loc,1, w.light_colors[i].Elements ); } glUniform1i( simple_color_shader_info.num_lights_loc, loop_count ); glUniform3fv( simple_color_shader_info.amb_loc,1, w.amb_light.Elements ); glUniformMatrix4fv( simple_color_shader_info.view_loc, 1,GL_FALSE, HMM_MAT4_PTR(v) ); cube_models = w.model_matrices[ OBJECT_CUBE_INSTANCE ]; for ( uint i = 0; i < array_length( w.cubes ); i++ ){ m4 mvp = vp * cube_models[i]; Material &material = w.cube_materials[i]; Texture &texture = material.texture; glActiveTexture(GL_TEXTURE0); if ( material.type == Material::GLASS ){ glBindTexture( GL_TEXTURE_2D, w.white_texture ); } else { switch ( texture.type ){ case Texture::COLOR: glBindTexture( GL_TEXTURE_2D, w.white_texture ); break; case Texture::CHECKER: glBindTexture( GL_TEXTURE_2D, w.checker_texture ); break; case Texture::MARBLE: glBindTexture( GL_TEXTURE_2D, w.marble_texture ); break; } } glUniformMatrix4fv( simple_color_shader_info.mvp_loc, 1,GL_FALSE, HMM_MAT4_PTR(mvp) ); glUniformMatrix4fv( simple_color_shader_info.model_loc, 1,GL_FALSE, HMM_MAT4_PTR( cube_models[i] ) ); glBindVertexArray( w.cubes_vao[i] ); glDrawElements( GL_TRIANGLES, 36, GL_UNSIGNED_INT, 0 ); glBindVertexArray( 0 ); } sphere_models = w.model_matrices[ OBJECT_SPHERE ]; for ( uint i = 0; i < array_length( w.spheres ); i++ ){ m4 mvp = vp * sphere_models[i]; Material &material = w.sphere_materials[i]; Texture &texture = material.texture; glActiveTexture(GL_TEXTURE0); if ( material.type == Material::GLASS ){ glBindTexture( GL_TEXTURE_2D, w.white_texture ); } else { switch ( texture.type ){ case Texture::COLOR: glBindTexture( GL_TEXTURE_2D, w.white_texture ); break; case Texture::CHECKER: glBindTexture( GL_TEXTURE_2D, w.checker_texture ); break; case Texture::MARBLE: glBindTexture( GL_TEXTURE_2D, w.marble_texture ); break; } } glUniformMatrix4fv( simple_color_shader_info.mvp_loc, 1,GL_FALSE, HMM_MAT4_PTR(mvp) ); glUniformMatrix4fv( simple_color_shader_info.model_loc, 1,GL_FALSE, HMM_MAT4_PTR( sphere_models[i] ) ); glBindVertexArray( w.spheres_vao[i] ); glDrawElements( GL_TRIANGLES, array_length(SphereIndices), GL_UNSIGNED_INT, 0 ); glBindVertexArray( 0 ); } glUniformMatrix4fv( simple_color_shader_info.mvp_loc, 1,GL_FALSE, HMM_MAT4_PTR(vp) ); glUniformMatrix4fv( simple_color_shader_info.view_loc, 1,GL_FALSE, HMM_MAT4_PTR( v ) ); glUniformMatrix4fv( simple_color_shader_info.model_loc, 1,GL_FALSE, HMM_MAT4_PTR( HMM_Mat4d(1.0f) ) ); value = 0; for ( uint i = 0; i < array_length( w.rects ); i++ ){ Rectangle &r = w.rects[i]; Material &material = w.rect_materials[i]; Texture &texture = material.texture; v3 color = texture.color; v2 tc[4]; if ( material.type == Material::GLASS ){ glBindTexture( GL_TEXTURE_2D, w.white_texture ); color = GLASS_COLOR; } else { switch ( texture.type ){ case Texture::COLOR: glBindTexture( GL_TEXTURE_2D, w.white_texture ); tc[0] = v2{ 0.0f, 0.0f }; tc[1] = v2{ 1.0f, 0.0f }; tc[2] = v2{ 1.0f, 1.0f }; tc[3] = v2{ 0.0f, 1.0f }; break; case Texture::CHECKER: { glBindTexture( GL_TEXTURE_2D, w.checker_texture ); f32 unit = 0.5f; f32 len1 = r.l1/unit, len2 = r.l2/unit; tc[0] = v2{ 0.0f, 0.0f }; tc[1] = v2{ len1, 0.0f }; tc[2] = v2{ len1, len2 }; tc[3] = v2{ 0, len2 }; } break; case Texture::MARBLE: { glBindTexture( GL_TEXTURE_2D, w.marble_texture ); tc[0] = v2{ 0.0f, 0.0f }; tc[1] = v2{ 1.0f, 0.0f }; tc[2] = v2{ 1.0f, 1.0f }; tc[3] = v2{ 0.0f, 1.0f }; } break; } } f32 vertexes[100]; memcpy( vertexes, r.p0.Elements, sizeof(r.p0) ); memcpy( vertexes + 3, color.Elements, sizeof(color) ); memcpy( vertexes + 6, r.n.Elements, sizeof(r.n) ); memcpy( vertexes + 9, tc[0].Elements, sizeof( tc[0] ) ); memcpy( vertexes + 11, r.p1.Elements, sizeof(r.p0) ); memcpy( vertexes + 14, color.Elements, sizeof(color) ); memcpy( vertexes + 17, r.n.Elements, sizeof(r.n) ); memcpy( vertexes + 20, tc[1].Elements, sizeof( tc[0] ) ); memcpy( vertexes + 22, r.p2.Elements, sizeof(r.p0) ); memcpy( vertexes + 25, color.Elements, sizeof(color) ); memcpy( vertexes + 28, r.n.Elements, sizeof(r.n) ); memcpy( vertexes + 31, tc[2].Elements, sizeof( tc[0] ) ); memcpy( vertexes + 33, r.p3.Elements, sizeof(r.p0) ); memcpy( vertexes + 36, color.Elements, sizeof(color) ); memcpy( vertexes + 39, r.n.Elements, sizeof(r.n) ); memcpy( vertexes + 42, tc[3].Elements, sizeof( tc[0] ) ); #if 0 array_push( w.color_vertex_data, r.p0 ); array_push( w.color_vertex_data, color ); array_push( w.color_vertex_data, r.n ); array_push( w.color_vertex_data, r.p1 ); array_push( w.color_vertex_data, color ); array_push( w.color_vertex_data, r.n ); array_push( w.color_vertex_data, r.p2 ); array_push( w.color_vertex_data, color ); array_push( w.color_vertex_data, r.n ); array_push( w.color_vertex_data, r.p3 ); array_push( w.color_vertex_data, color ); array_push( w.color_vertex_data, r.n ); #endif // push the indices glBindVertexArray( w.rect_vao ); glBindBuffer( GL_ARRAY_BUFFER, w.rect_vbo ); glBufferData( GL_ARRAY_BUFFER, sizeof( f32 ) * 44, vertexes, GL_STATIC_DRAW ); glUniformMatrix4fv( simple_color_shader_info.mvp_loc, 1,GL_FALSE, HMM_MAT4_PTR(vp) ); glDrawElements(GL_TRIANGLES,6, GL_UNSIGNED_INT, 0 ); } glUseProgram( 0 ); // Create line vertex data for rendering value = 0; for ( int i = 0; i < array_length( w.temp_color_quads ); i++ ){ const ColorQuad &quad = w.temp_color_quads[i]; // Push the first triangle array_push( w.color_vertex_data, quad.p0 ); array_push( w.color_vertex_data, quad.color ); array_push( w.color_vertex_data, quad.n ); array_push( w.color_vertex_data, quad.p1 ); array_push( w.color_vertex_data, quad.color ); array_push( w.color_vertex_data, quad.n ); array_push( w.color_vertex_data, quad.p2 ); array_push( w.color_vertex_data, quad.color ); array_push( w.color_vertex_data, quad.n ); array_push( w.color_vertex_data, quad.p3 ); array_push( w.color_vertex_data, quad.color ); array_push( w.color_vertex_data, quad.n ); // push the indices array_push( w.color_vertex_indices, value ); array_push( w.color_vertex_indices, value + 1 ); array_push( w.color_vertex_indices, value + 2 ); array_push( w.color_vertex_indices, value + 2 ); array_push( w.color_vertex_indices, value + 3 ); array_push( w.color_vertex_indices, value ); value += 4; } for ( int i = 0; i < array_length( w.perm_color_quads ); i++ ){ const ColorQuad &quad = w.perm_color_quads[i]; // Push the first triangle array_push( w.color_vertex_data, quad.p0 ); array_push( w.color_vertex_data, quad.color ); array_push( w.color_vertex_data, quad.n ); array_push( w.color_vertex_data, quad.p1 ); array_push( w.color_vertex_data, quad.color ); array_push( w.color_vertex_data, quad.n ); array_push( w.color_vertex_data, quad.p2 ); array_push( w.color_vertex_data, quad.color ); array_push( w.color_vertex_data, quad.n ); array_push( w.color_vertex_data, quad.p3 ); array_push( w.color_vertex_data, quad.color ); array_push( w.color_vertex_data, quad.n ); array_push( w.color_vertex_indices, value ); array_push( w.color_vertex_indices, value + 1 ); array_push( w.color_vertex_indices, value + 2 ); array_push( w.color_vertex_indices, value + 2 ); array_push( w.color_vertex_indices, value + 3 ); array_push( w.color_vertex_indices, value ); value += 4; } array_push( w.color_vertex_modes, (GLenum)GL_TRIANGLES ); array_push( w.index_stack, array_length( w.color_vertex_indices ) ); for ( int i = 0; i < array_length( w.lines ); i++ ){ // Push the ending point array_push( w.color_vertex_data, w.lines[i].start ); array_push( w.color_vertex_data, w.lines[i].color ); array_push( w.color_vertex_data, v3{0.0f,0.0f,0.0f} ); array_push( w.color_vertex_indices, value++ ); // Push the ending point array_push( w.color_vertex_data,w.lines[i].end ); array_push( w.color_vertex_data, w.lines[i].color ); // Line normal, not necessary and only for debuggin purposes // and another shader prob cost too much array_push( w.color_vertex_data, v3{0.0f,0.0f,0.0f} ); array_push( w.color_vertex_indices, value++ ); } for ( uint i = 0; i < array_length( w.boxes ); i++ ){ world_draw_AABB( w, w.boxes[i], v3{1.0f,1.0f,1.0f }, &value ); } array_push( w.color_vertex_modes, (GLenum)GL_LINES ); array_push( w.index_stack, array_length(w.color_vertex_indices) ); glUseProgram( nl_color_shader_info.id ); glBindVertexArray( w.color_vao ); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, w.color_ebo ); glBufferData( GL_ELEMENT_ARRAY_BUFFER, sizeof(uint) * array_length( w.color_vertex_indices ), w.color_vertex_indices, GL_STATIC_DRAW ); glBindBuffer( GL_ARRAY_BUFFER, w.color_vbo ); glBufferData( GL_ARRAY_BUFFER, sizeof(v3) * array_length( w.color_vertex_data ), w.color_vertex_data, GL_STATIC_DRAW ); glUniformMatrix4fv( nl_color_shader_info.mvp_loc, 1,GL_FALSE, HMM_MAT4_PTR(vp) ); #if 1 uint prev = 0; for ( int i = 0; i < array_length( w.color_vertex_modes);i++ ){ GLenum mode = w.color_vertex_modes[i]; uint len = w.index_stack[i]; uint count = len - prev; glDrawElements( mode, count, GL_UNSIGNED_INT, (void *)( prev * sizeof(uint) )); prev = len; } #else for ( int i = 1; i < array_length( w.color_vertex_modes ); i++ ){ if ( mode != w.color_vertex_modes[i] ){ len = i - start; glDrawElements( mode, count, GL_UNSIGNED_INT, index ); start = i; mode = w.color_vertex_modes[i]; } } if ( start < array_length( w.color_vertex_modes ) ){ glDrawArrays( mode, start, array_length( w.color_vertex_modes ) - start ); } #endif glUseProgram( 0 ); glBindVertexArray( 0 ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); } bool hit_world( const World &w, const Ray &r, f32 tmin, f32 tmax, HitRecord &record ) { f32 max = tmax; HitRecord temp_record; bool hit_anything = false; if ( hit_grid( w.grid, r, tmin, max, temp_record ) ){ hit_anything = true; max = temp_record.t; record = temp_record; record.obj.object = ( void *)&w.grid; record.obj.type = OBJECT_GRID; } for ( int i = 0; i < array_length( w.cubes ); i++ ){ if ( hit_cube( w.cubes[i], r, tmin, max, temp_record ) ){ hit_anything = true; max = temp_record.t; record = temp_record; record.obj.index = i; record.obj.type = OBJECT_CUBE_INSTANCE; } } for ( int i = 0; i < array_length( w.spheres ); i++ ){ if ( hit_sphere( w.spheres[i], r, tmin, max, temp_record ) ){ hit_anything = true; max = temp_record.t; record = temp_record; record.obj.index = i; record.obj.type = OBJECT_SPHERE; } } for ( int i = 0 ; i < array_length( w.rects ); i++ ){ if ( hit_rect( w.rects[i], r, tmin, max, temp_record ) ){ hit_anything = true; max = temp_record.t; record = temp_record; record.obj.index = i; record.obj.type = OBJECT_RECT; } } for ( int i = 0; i < array_length( w.light_cubes ); i++ ){ if ( hit_cube( w.light_cubes[i], r, tmin, max, temp_record ) ){ hit_anything = true; max = temp_record.t; record = temp_record; record.obj.index = i; record.obj.type = OBJECT_LIGHT_CUBE_INSTANCE; } } for ( int i = 0; i < array_length( w.light_spheres ); i++ ){ if ( hit_sphere( w.light_spheres[i], r, tmin, max, temp_record ) ){ hit_anything = true; max = temp_record.t; record = temp_record; record.obj.index = i; record.obj.type = OBJECT_LIGHT_SPHERE; } } for ( int i = 0 ; i < array_length( w.light_rects ); i++ ){ if ( hit_rect( w.light_rects[i], r, tmin, max, temp_record ) ){ hit_anything = true; max = temp_record.t; record = temp_record; record.obj.index = i; record.obj.type = OBJECT_LIGHT_RECT; } } return hit_anything; } void dump_texture_data( DumpObjectData &data, v3 *tex_store, uint index ) { switch ( data.texture_type ){ case DumpObjectData::TEXTURE_PLAIN_COLOR: data.texture_data.color = tex_store[index]; break; case DumpObjectData::TEXTURE_CHECKER: data.texture_data.checker_color[0] = v3{0.0f,0.0f,0.0f}; data.texture_data.checker_color[1] = v3{1.0f,1.0f,1.0f}; break; case DumpObjectData::TEXTURE_MARBLE: data.texture_data.marble_color = tex_store[index]; break; default: break; } } void print_dump_data( DumpObjectData *data ){ } void convert_material_to_dump( DumpObjectData &data, const Material &material ) { switch ( material.type ){ case Material::GLASS: printf("Dumping Glass material with value %d\n", DumpObjectData::MATERIAL_GLASS ); data.material_type = DumpObjectData::MATERIAL_GLASS; data.material_data.ri = 1.33f; break; case Material::PURE_DIFFUSE: data.material_type = DumpObjectData::MATERIAL_PURE_DIFFUSE; break; case Material::METALLIC: data.material_type = DumpObjectData::MATERIAL_METALLIC; data.material_data.fuzz = 0.01f; break; } } void convert_texture_to_dump( DumpObjectData &data, const Texture &texture ) { switch ( texture.type ){ case Texture::COLOR: printf("Dumping color texture with value %d\n", DumpObjectData::TEXTURE_PLAIN_COLOR ); data.texture_type= DumpObjectData::TEXTURE_PLAIN_COLOR; data.texture_data.color = texture.color; break; case Texture::MARBLE: printf("Dumping marble texture with value %d\n", DumpObjectData::TEXTURE_MARBLE ); data.texture_type = DumpObjectData::TEXTURE_MARBLE; data.texture_data.marble_color = texture.color; break; case Texture::CHECKER: printf("Dumping checker texture with value %d\n", DumpObjectData::TEXTURE_CHECKER ); data.texture_type = DumpObjectData::TEXTURE_CHECKER; data.texture_data.checker_color[0] = texture.color; data.texture_data.checker_color[1] = v3{0.0f,0.0f,0.0f}; data.texture_data.freq = 8.0f; break; } } void world_dump_rect_data( const World &w, DumpObjectData *store ){ Rectangle *rects = w.rects; for ( uint i = 0; i < array_length( rects ); i++ ){ Material &material = w.rect_materials[i]; Texture &texture = material.texture; DumpObjectData data; data.type = DumpObjectData::RECTANGLE; data.object_data.p0 = rects[i].p0; data.object_data.s1 = rects[i].s1; data.object_data.s2 = rects[i].s2; data.object_data.n = rects[i].n; data.object_data.l1= rects[i].l1; data.object_data.l2= rects[i].l2; convert_material_to_dump( data, material ); convert_texture_to_dump( data, texture ); array_push( store, data ); } } void world_dump_sphere_data( const World &w, DumpObjectData *store ){ Sphere *spheres= w.spheres; for ( uint i = 0; i < array_length( spheres ); i++ ){ Material &material = w.sphere_materials[i]; Texture &texture = material.texture; DumpObjectData data; data.type = DumpObjectData::SPHERE; data.object_data.center = spheres[i].c; data.object_data.radius = spheres[i].r; convert_material_to_dump( data, material ); convert_texture_to_dump( data, texture ); array_push( store, data ); } } void apply_cube_transform_to_rect( Rectangle &r, Cube &cube ){ q4 quat = HMM_NormalizeQuaternion( cube.orientation ); r.l1 = cube.length; r.l2 = cube.length; r.p0 = rotate_vector_by_quaternion( r.p0,quat ); r.s1 = rotate_vector_by_quaternion( r.s1, quat ); r.s2 = rotate_vector_by_quaternion( r.s2, quat ); r.n = rotate_vector_by_quaternion( r.n, quat ); r.p0 += cube.pos; } void world_dump_cube_data( const World &w, DumpObjectData *store ){ for ( uint i = 0; i < array_length( w.cubes ); i++ ){ Rectangle rects[6]; generate_cube_rects( rects, w.cubes[i].length ); Material &material = w.cube_materials[i]; Texture &texture = material.texture; for ( uint faces = 0; faces < 6; faces++ ){ DumpObjectData data; data.type = DumpObjectData::RECTANGLE; // Apply cube transformation to the rectangle apply_cube_transform_to_rect(rects[faces], w.cubes[i] ); data.object_data.p0 = rects[faces].p0; data.object_data.s1 = rects[faces].s1; data.object_data.s2 = rects[faces].s2; data.object_data.n = rects[faces].n; data.object_data.l1= rects[faces].l1; data.object_data.l2= rects[faces].l2; convert_material_to_dump( data, material ); switch ( texture.type ){ case Texture::COLOR: printf("Dumping color texture with value %d\n", DumpObjectData::TEXTURE_PLAIN_COLOR ); data.texture_type= DumpObjectData::TEXTURE_PLAIN_COLOR; data.texture_data.color = texture.face_colors[faces]; break; case Texture::MARBLE: printf("Dumping marble texture with value %d\n", DumpObjectData::TEXTURE_MARBLE ); data.texture_type = DumpObjectData::TEXTURE_MARBLE; data.texture_data.marble_color = texture.face_colors[faces]; break; case Texture::CHECKER: printf("Dumping checker texture with value %d\n", DumpObjectData::TEXTURE_CHECKER ); data.texture_type = DumpObjectData::TEXTURE_CHECKER; data.texture_data.checker_color[0] = texture.face_colors[faces]; data.texture_data.checker_color[1] = v3{0.0f,0.0f,0.0f}; data.texture_data.freq = 2.0f; break; } array_push( store, data ); } } } void world_dump_light_rect_data( const World &w, DumpObjectData *store ) { Rectangle *rects = w.light_rects; for ( uint i = 0; i < array_length( rects ); i++ ){ DumpObjectData data; data.type = DumpObjectData::RECTANGLE; data.object_data.p0 = rects[i].p0; data.object_data.s1 = rects[i].s1; data.object_data.s2 = rects[i].s2; data.object_data.n = rects[i].n; data.object_data.l1= rects[i].l1; data.object_data.l2= rects[i].l2; data.material_type = DumpObjectData::MATERIAL_DIFFUSE_LIGHT; data.material_data.diff_light_color = w.light_rect_color[ i ] * 10.0f; array_push( store, data ); } } void world_dump_light_sphere_data( const World &w, DumpObjectData *store ) { Sphere *spheres= w.light_spheres; for ( uint i = 0; i < array_length( spheres ); i++ ){ DumpObjectData data; data.type = DumpObjectData::SPHERE; data.object_data.center = w.light_spheres[i].c; data.object_data.radius = w.light_spheres[i].r; data.material_type = DumpObjectData::MATERIAL_DIFFUSE_LIGHT; data.material_data.diff_light_color = w.light_sphere_color[ i ] * 10.0f; array_push( store, data ); } } void world_dump_light_cube_data( const World &w, DumpObjectData *store ) { Cube *cubes = w.light_cubes; for ( uint i = 0; i < array_length( cubes ); i++ ){ for ( uint faces = 0; faces < 6; faces++ ){ DumpObjectData data; data.type = DumpObjectData::RECTANGLE; // Apply cube transformation to the rectangle Rectangle r = CubeRects[ faces ]; apply_cube_transform_to_rect(r, w.light_cubes[i] ); data.object_data.p0 = r.p0; data.object_data.s1 = r.s1; data.object_data.s2 = r.s2; data.object_data.n = r.n; data.object_data.l1= r.l1; data.object_data.l2= r.l2; data.material_type = DumpObjectData::MATERIAL_DIFFUSE_LIGHT; data.material_data.diff_light_color = w.light_cube_color[i] * 10.0f; array_push( store, data ); } } } void world_dump_scene_to_file( const World &w, const char *file ) { DumpObjectData *data_store = array_allocate( DumpObjectData, 100 ); DumpCameraData cam; cam.look_from = w.view_camera.P; cam.look_at = w.view_camera.P + w.view_camera.F; cam.z = w.view_near_plane; cam.vfov = w.view_vfov; cam.aspect_ratio = (f32)ScreenWidth/ScreenHeight; cam.aperture = 0.0f; cam.focal_dist = 1.0f; world_dump_rect_data( w, data_store ); world_dump_cube_data( w, data_store ); world_dump_sphere_data( w, data_store ); world_dump_light_cube_data( w, data_store ); world_dump_light_sphere_data( w, data_store ); world_dump_light_rect_data( w, data_store ); FILE *fp = fopen(file,"wb"); if( !fp ){ perror("Unable to open file for output!: "); array_free( data_store ); return; } fwrite( &cam, sizeof(cam), 1, fp ); uint32 len = array_length( data_store ); fwrite( &len, sizeof(len), 1, fp ); fwrite( data_store, sizeof(*data_store), array_length( data_store ), fp ); fclose( fp ); array_free( data_store ); return; } uint8 *load_image( const char *fname, int *width, int *height, int *channels ){ uint8 *data = (uint8 *)stbi_load( fname, width, height, channels, 4 ); if ( data == NULL ){ fprintf( stderr, "Unable to load image %s!", fname ); return NULL; } else { fprintf( stdout, "Image loaded successfully. width = %d, height = %d\n", *width, *height ); } return data; } Image create_image( const char *fname ){ Image image; image.data = load_image( fname, &image.w, &image.h, &image.channels ); return image; } Texture cube_color_texture( ){ Texture t; t.type = Texture::COLOR; t.face_colors[0] = v3{prng_float(), prng_float(), prng_float() }; t.face_colors[1] = v3{prng_float(), prng_float(), prng_float() }; t.face_colors[2] = v3{prng_float(), prng_float(), prng_float() }; t.face_colors[3] = v3{prng_float(), prng_float(), prng_float() }; t.face_colors[4] = v3{prng_float(), prng_float(), prng_float() }; t.face_colors[5] = v3{prng_float(), prng_float(), prng_float() }; return t; } Texture sphere_color_texture( ){ Texture t; t.type = Texture::COLOR; t.color = v3{prng_float(), prng_float(), prng_float() }; return t; } Texture rectangle_color_texture( ){ Texture t; t.type = Texture::COLOR; t.color = v3{prng_float(), prng_float(), prng_float() }; return t; } int main(){ prng_seed(); generate_sphere_vertices(); bool dump_scene_data = false; uint dump_count = 0; glfwInit(); glfwWindowHint( GLFW_CONTEXT_VERSION_MAJOR, 4 ); glfwWindowHint( GLFW_CONTEXT_VERSION_MINOR, 3 ); glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE); GLFWwindow* window = glfwCreateWindow( ScreenWidth,ScreenHeight, "OpenGl", NULL, NULL ); if ( !window ){ print_error("Unable to open window!"); } glfwMakeContextCurrent( window ); glfwSetFramebufferSizeCallback( window, resizeCallback ); //glfwSetInputMode( window, GLFW_CURSOR, GLFW_CURSOR_DISABLED ); glfwSetCursorPosCallback( window, mouse_callback ); glfwSetMouseButtonCallback(window, mouse_button_callback); glfwSetKeyCallback( window, key_callback ); if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { print_error("Failed to initialize GLAD"); return -1; } #if ENABLE_GL_DEBUG_PRINT GLint flags; glGetIntegerv(GL_CONTEXT_FLAGS, &flags); if (flags & GL_CONTEXT_FLAG_DEBUG_BIT) { glEnable(GL_DEBUG_OUTPUT); glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); glDebugMessageCallback(glDebugOutput, nullptr); glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, GL_TRUE); } else { print_error("Unable to set debug context"); } #endif glEnable( GL_DEPTH_TEST ); Quad_elem_indices= ( uint * )malloc( 6 * 1000 * sizeof( uint ) ); uint t[] = { 0, 1, 2, 2, 3, 0 }; uint *tmp = Quad_elem_indices; for ( int i = 0; i < 1000; i++ ){ for ( int j = 0; j < 6; j++ ){ *tmp = t[j] + 4 * i; tmp++; } } glGenBuffers(1,&quad_elem_buffer_index); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, quad_elem_buffer_index ); glBufferData( GL_ELEMENT_ARRAY_BUFFER, sizeof( uint ) * 100, Quad_elem_indices, GL_STATIC_DRAW ); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 ); glGenBuffers( 1, &sphere_element_buffer ); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, sphere_element_buffer ); glBufferData( GL_ELEMENT_ARRAY_BUFFER, sizeof( uint ) * array_length( SphereIndices ), SphereIndices, GL_STATIC_DRAW ); if ( create_grid_program() == -1 ){ return -1; } if ( create_simple_color_shader_program() == -1 ){ return -1; } if ( create_nl_color_shader_program() == -1 ){ return -1; } // Load images for texture // uint8 white_texture_data[] = { 255, 255, 255, 255 }; Image checker_image = create_image( "./assets/checkers.png" ); Image white_marble_image = create_image( "./assets/White-Marble-1024.png" ); Image white_image = create_image( "./assets/white.png" ); // create textures Texture checker_texture; checker_texture.type = Texture::CHECKER; checker_texture.image = checker_image; Texture white_marble_texture; white_marble_texture.type = Texture::MARBLE; white_marble_texture.image = white_marble_image; Texture color_texture; color_texture.type = Texture::COLOR; // create_world World *world = (World *)malloc( sizeof(World) ); World &w = *world; w.amb_light = { 0.3f, 0.3f, 0.3f }; w.grid = create_grid( AARect::PLANE_ZX, AABB( v3{ -10.0f, 0.0f, -10.0f }, v3{ 10.0f, 0.0f, 10.0f } ), 0.0f, 0.1f, v3{0.0f,0.0f,1.0f} ); w.ui_vfov = 45; w.ui_near_plane = 0.1f; w.ui_far_plane = 100.0f; w.ui_perspective= HMM_Perspective(45, (float)ScreenWidth/ScreenHeight, 0.1f, 10.0f ); w.view_vfov = 45; w.view_near_plane = 0.1f; w.view_far_plane = 100.0f; w.view_perspective = HMM_Perspective(w.view_vfov, (float)ScreenWidth/ScreenHeight, w.view_near_plane, w.view_far_plane ); w.perspective = w.ui_perspective; uint current_screen_width = ScreenWidth; uint current_screen_height = ScreenHeight; w.ui_camera = Camera( v3{ 0.0f, 0.5f, 5.0f }, v3{ 0.0f, 0.5f, -1.0f }, v3{ 0.0f, 1.0f, 0.0f } ); w.view_camera = Camera( v3{ 0.0f, 0.5f, 5.0f }, v3{ 0.0f, 0.5f, -1.0f }, v3{ 0.0f, 1.0f, 0.0f } ); Cube cube = create_cube_one_color( 0.5f, v3{1,0.25,0}, v3 {0,1,0} ); w.cube.color[Cube::FRONT] = v3{0.82f, 0.36f, 0.45f}; w.cube.color[Cube::BACK] = v3{0.82f, 0.36f, 0.45f}; w.cube.color[Cube::LEFT] = v3{0.32f, 0.32f, 0.86f}; w.cube.color[Cube::RIGHT] = v3{0.32f, 0.32f, 0.86f}; #if 0 world_generate_cube_data(w.cube_vao, w.cube_vbo, w.cube ); world_add_cube_vertex_data( w.cube_vao, w.cube_vbo, w.cube ); #endif for ( uint i = 0; i < _OBJECT_MAX; i++ ){ w.model_matrices[ i ] = array_allocate( m4, 10 ); } w.cubes = array_allocate( Cube, 10 ); w.rects = array_allocate( Rectangle, 10 ); w.boxes = array_allocate( AABB, 10 ); w.lines = array_allocate( Line, 10 ); w.spheres = array_allocate( Sphere, 10 ); w.spheres_transform = array_allocate( m4, 10 ); w.sphere_colors = array_allocate( v3, 10 ); w.rect_colors = array_allocate(v3,10 ); w.cube_materials = array_allocate( Material, 10 ); w.sphere_materials = array_allocate( Material, 10 ); w.rect_materials= array_allocate( Material, 10 ); w.light_cubes = array_allocate( Cube, 10 ); w.light_rects = array_allocate( Rectangle, 10 ); w.light_spheres = array_allocate( Sphere, 10 ); w.light_pos = array_allocate( v3, 10 ); w.light_colors = array_allocate( v3, 10 ); w.light_cube_color = array_allocate( v3, 10 ); w.light_sphere_color = array_allocate( v3, 10 ); w.light_rect_color = array_allocate( v3, 10 ); w.light_cubes_vao = array_allocate( uint, 10 ); w.light_spheres_vao = array_allocate( uint, 10 ); w.light_cubes_vbo = array_allocate( uint, 10 ); w.light_spheres_vbo = array_allocate( uint, 10 ); w.temp_color_quads = array_allocate( ColorQuad, 10 ); w.perm_color_quads = array_allocate( ColorQuad, 10 ); w.cubes_vao = array_allocate( uint, 10 ); w.cubes_vbo = array_allocate( uint, 10 ); w.spheres_vao = array_allocate( uint, 10 ); w.spheres_vbo = array_allocate( uint, 10 ); w.rect_flip_normal = 0; w.color_vertex_data = array_allocate( v3, 1000 ); w.color_vertex_indices = array_allocate( uint, 3000 ); w.index_stack = array_allocate( uint, 10 ); w.color_vertex_modes = array_allocate( GLenum ,10 ); glGenVertexArrays(1, &w.color_vao ); glGenBuffers( 1, &w.color_vbo ); glGenBuffers( 1, &w.color_ebo ); glBindVertexArray( w.color_vao ); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, w.color_ebo ); glBufferData( GL_ELEMENT_ARRAY_BUFFER, 1000 * sizeof(v3), NULL, GL_STATIC_DRAW ); glBindBuffer( GL_ARRAY_BUFFER, w.color_vbo ); glBufferData( GL_ARRAY_BUFFER, 2000 * sizeof(v3), NULL, GL_STATIC_DRAW ); glEnableVertexAttribArray( simple_color_shader_info.pos_id ); glEnableVertexAttribArray( simple_color_shader_info.color_id ); glEnableVertexAttribArray( simple_color_shader_info.normal_id ); glVertexAttribPointer( simple_color_shader_info.pos_id, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(v3), (void *)( 0 ) ); glVertexAttribPointer( simple_color_shader_info.color_id, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(v3), (void *)(sizeof(v3) ) ); glVertexAttribPointer( simple_color_shader_info.normal_id, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(v3), (void *)(2 * sizeof(v3) ) ); glBindVertexArray( 0 ); glGenVertexArrays( 1, &w.rect_vao ); glGenBuffers( 1, &w.rect_vbo ); glBindVertexArray( w.rect_vao ); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, quad_elem_buffer_index ); glBindBuffer( GL_ARRAY_BUFFER, w.rect_vbo ); glBufferData( GL_ARRAY_BUFFER, 200 * sizeof(v3), NULL, GL_STATIC_DRAW ); glEnableVertexAttribArray( simple_color_shader_info.pos_id ); glEnableVertexAttribArray( simple_color_shader_info.color_id ); glEnableVertexAttribArray( simple_color_shader_info.normal_id ); glEnableVertexAttribArray( simple_color_shader_info.tex_coords_id); glVertexAttribPointer( simple_color_shader_info.pos_id, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(v3) + sizeof(v2), (void *)( 0 ) ); glVertexAttribPointer( simple_color_shader_info.color_id, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(v3) + sizeof(v2), (void *)(sizeof(v3) ) ); glVertexAttribPointer( simple_color_shader_info.normal_id, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(v3) + sizeof(v2), (void *)(2 * sizeof(v3) ) ); glVertexAttribPointer( simple_color_shader_info.tex_coords_id, 2, GL_FLOAT, GL_FALSE, 3 * sizeof(v3) + sizeof(v2), (void *)(3 * sizeof(v3) ) ); glBindVertexArray( 0 ); // generate opengl Textures glGenTextures( 1, &w.white_texture ); glGenTextures( 1, &w.checker_texture); glGenTextures( 1, &w.marble_texture); glBindTexture(GL_TEXTURE_2D, w.white_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, white_texture_data ); glGenerateMipmap(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, w.checker_texture ); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, checker_image.w, checker_image.h, 0, GL_RGBA, GL_UNSIGNED_BYTE, checker_image.data ); glGenerateMipmap(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, w.marble_texture ); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, white_marble_image.w, white_marble_image.h, 0, GL_RGBA, GL_UNSIGNED_BYTE, white_marble_image.data ); glGenerateMipmap(GL_TEXTURE_2D); Material m = create_material_diffuse( cube_color_texture() ); world_add_cube( w, &cube, m ); m = create_material_metallic( sphere_color_texture() ); world_add_sphere( w,create_sphere( v3{0.0f,0.0f,0.0f}, 1.0f ) , m ); m = create_material_diffuse( rectangle_color_texture() ); world_add_rect( w,create_rectangle( v3{-1.0f,2.0f,3.0f } ), m ); w.model_matrices[OBJECT_CUBE_INSTANCE][0] = cube.base_transform; world_generate_grid_data(w, w.grid ); #define WORLD_SET_STATE_FREE_VIEW \ do {\ w.camera = &w.ui_camera;\ w.perspective = w.ui_perspective;\ w.state = World::STATE_FREE_VIEW;\ w.show_imgui = false;\ w.camera->should_rotate = true;\ w.camera->should_move = true;\ w.is_selected = false;\ glfwSetCursorPosCallback( window, mouse_callback );\ } while ( 0 ) #define WORLD_SET_STATE_DETACHED\ do {\ w.camera = &w.ui_camera;\ w.perspective = w.ui_perspective;\ w.state = World::STATE_DETACHED;\ w.show_imgui = true;\ w.camera->should_rotate = false;\ w.camera->should_move = true;\ w.is_selected = false;\ glfwSetCursorPosCallback( window, NULL );\ } while ( 0 ) #define WORLD_SET_STATE_SELECTED\ do {\ w.camera = &w.ui_camera;\ w.perspective = w.ui_perspective;\ w.state = World::STATE_SELECTED;\ w.show_imgui = true;\ w.camera->should_rotate = false;\ w.camera->should_move = false;\ glfwSetCursorPosCallback( window, NULL );\ } while ( 0 ) #define WORLD_SET_STATE_ON_HOLD\ do {\ w.camera = &w.ui_camera;\ w.perspective = w.ui_perspective;\ w.state = World::STATE_ON_HOLD;\ w.show_imgui = false;\ w.camera->should_rotate = false;\ w.camera->should_move = true;\ w.is_holding = true;\ glfwSetCursorPosCallback( window, NULL );\ } while ( 0 ) #define WORLD_SET_STATE_VIEW_CAMERA\ do {\ w.camera = &w.view_camera;\ w.perspective = w.view_perspective;\ w.state = World::STATE_VIEW_CAMERA;\ w.show_imgui = true;\ w.camera->should_rotate = true;\ w.camera->should_move = true;\ w.is_holding = false;\ glfwSetCursorPosCallback( window, mouse_callback );\ } while ( 0 ) glBindBuffer( GL_ARRAY_BUFFER, 0 ); int viewport[4]; glGetIntegerv( GL_VIEWPORT, viewport); float dt = 0; float current = glfwGetTime(); m4 vp = HMM_Mat4d(1.0f); double cp[2]; glfwGetCursorPos( window, &cp[0], &cp[1] ); f32 camera_sensitivity = 0.5f; uint8 *key_map = (uint8 *)malloc( sizeof(uint8) * 400 ); memset( key_map, 0, 400 * sizeof(uint8) ); IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style ImGui::StyleColorsDark(); //ImGui::StyleColorsClassic(); // Setup Platform/Renderer bindings ImGui_ImplGlfw_InitForOpenGL(window, true); ImGui_ImplOpenGL3_Init("#version 430 core"); bool show_imgui = false; bool show_demo_window = false; bool show_another_window = false; ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); w.camera = &w.ui_camera; WORLD_SET_STATE_FREE_VIEW; while ( !glfwWindowShouldClose( window ) ){ float now = glfwGetTime(); dt = now - current; current = now; if ( current_screen_width != ScreenWidth || current_screen_height != ScreenHeight ) { w.ui_perspective= HMM_Perspective(w.ui_vfov, (float)ScreenWidth/ScreenHeight, w.ui_near_plane, w.ui_far_plane ); w.view_perspective= HMM_Perspective(w.view_vfov, (float)ScreenWidth/ScreenHeight, w.view_near_plane, w.view_far_plane ); if ( w.state == World::STATE_VIEW_CAMERA ){ w.perspective = w.view_perspective; } else { w.perspective = w.ui_perspective; } current_screen_width = ScreenWidth; current_screen_height = ScreenHeight; } process_keyboard_input( window, key_map ); //check camera events for ( int i = 0; i < Event_Count; i++ ){ switch ( Event_Queue[i].type ){ case MOUSE_MOVE: { f32 dx = Event_Queue[i].xp - cp[0]; f32 dy = Event_Queue[i].yp - cp[1]; #if 0 if ( w.state == World::STATE_VIEW_CAMERA ){ w.camera->rotate( -camera_sensitivity*dx, -camera_sensitivity*dy ); } else { w.camera->rotate( camera_sensitivity*dx, camera_sensitivity*dy ); } #endif w.camera->rotate( camera_sensitivity*dx, camera_sensitivity*dy ); cp[0] = Event_Queue[i].xp; cp[1] = Event_Queue[i].yp; break; } case MOUSE_RBUTTON_CLICK: { if ( w.state == World::STATE_VIEW_CAMERA ) break; HitRecord record; v3 point = v3{ ( float )cp[0], (float)cp[1], 0.0f }; v3 wp = HMM_UnProject( point, w.perspective * w.camera->transform(), ScreenWidth, ScreenHeight); Ray ray( w.camera->P, ( wp - w.camera->P ) ); if ( hit_grid( w.grid, ray, 0.001f, 100.0f, record ) ){ record.print(); v3 p0 = grid_get_corner_point( w.grid, record.u, record.v ); print_v3( p0 ); v3 p1 = p0 + w.grid.dir1 * w.grid.w; v3 p2 = p0 + w.grid.dir1 * w.grid.w + w.grid.dir2 * w.grid.w; v3 p3 = p0 + w.grid.dir2 * w.grid.w; ColorQuad quad = { p0, p1, p2, p3, v3{ 0.52f,0.15f,0.93f }, // color w.grid.rect.n }; array_push( w.perm_color_quads, quad ); } #if 0 array_push( w.lines, create_line_from_ray( ray, 10.0f, v3{0,1.0f,0.0f} ) ); #endif break; } case MOUSE_LBUTTON_CLICK: { switch ( w.state ){ case World::STATE_VIEW_CAMERA: case World::STATE_SELECTED: break; case World::STATE_FREE_VIEW: case World::STATE_DETACHED: { glfwGetCursorPos( window, &cp[0], &cp[1] ); HitRecord record; v3 point = v3{ ( float )cp[0], (float)cp[1], 0.0f }; v3 wp = HMM_UnProject( point, w.perspective * w.camera->transform(), ScreenWidth, ScreenHeight ); Ray ray( w.camera->P, ( wp - w.camera->P ) ); if ( hit_world( w, ray, 0.001f, 100.0f, record ) ){ w.is_selected = record.obj.type != OBJECT_GRID; switch ( record.obj.type ){ case OBJECT_LIGHT_CUBE_INSTANCE: case OBJECT_CUBE_INSTANCE: WORLD_SET_STATE_SELECTED; w.selected_object = record.obj; w.selected_aabb = cube_get_AABB; w.selected_move = cube_move; w.selected_rotate = cube_rotate; w.selected_scale = cube_scale; if ( record.obj.type == OBJECT_CUBE_INSTANCE ){ w.cube_face_dropdown = 0; w.selected_data = (void *)( w.cubes + w.selected_object.index ); w.sel_cube_length = w.cubes[w.selected_object.index].length; w.cube_material_dropdown = w.cube_materials[w.selected_object.index].type; w.cube_texture_dropdown = w.cube_materials[w.selected_object.index].texture.type; w.cube_face_color= w.cube_materials[w.selected_object.index].texture.face_colors[0]; } else { w.light_cube_face_color = w.light_cube_color[ w.selected_object.index ]; w.selected_data = (void *)( w.light_cubes + w.selected_object.index ); w.sel_cube_length = w.light_cubes[w.selected_object.index].length; } break; case OBJECT_LIGHT_SPHERE: case OBJECT_SPHERE: WORLD_SET_STATE_SELECTED; w.selected_object = record.obj; w.selected_aabb = sphere_aabb; w.selected_move = sphere_move; w.selected_rotate = sphere_rotate; w.selected_scale= sphere_scale; if ( record.obj.type == OBJECT_SPHERE ){ w.sphere_face_color = w.sphere_colors[ record.obj.index ]; w.selected_data = (void *)( w.spheres + w.selected_object.index ); w.sel_sphere_radius = w.spheres[w.selected_object.index].r; w.sphere_material_dropdown = w.sphere_materials[w.selected_object.index].type; w.sphere_texture_dropdown = w.sphere_materials[w.selected_object.index].texture.type; } else { w.light_sphere_face_color = w.light_sphere_color[ record.obj.index ]; w.selected_data = (void *)( w.light_spheres + w.selected_object.index ); w.sel_sphere_radius = w.light_spheres[w.selected_object.index].r; } break; case OBJECT_LIGHT_RECT: case OBJECT_RECT: WORLD_SET_STATE_SELECTED; w.selected_object = record.obj; w.selected_aabb = rectangle_AABB; w.selected_move = rectangle_move; w.selected_rotate = rectangle_rotate; w.selected_scale= rectangle_scale; if ( record.obj.type == OBJECT_RECT ){ w.rect_face_color= w.rect_materials[ w.selected_object.index].texture.color; w.selected_data = (void *)( w.rects+ w.selected_object.index ); w.sel_rect_l1= w.rects[w.selected_object.index].l1; w.sel_rect_l2= w.rects[w.selected_object.index].l2; w.rect_material_dropdown = w.rect_materials[w.selected_object.index].type; w.rect_texture_dropdown = w.rect_materials[w.selected_object.index].texture.type; } else { w.light_rect_face_color = w.light_rect_color[ record.obj.index ]; w.selected_data = (void *)( w.light_rects+ w.selected_object.index ); w.sel_rect_l1= w.light_rects[w.selected_object.index].l1; w.sel_rect_l2= w.light_rects[w.selected_object.index].l2; } break; case OBJECT_GRID: if ( w.state == World::STATE_FREE_VIEW ) break; WORLD_SET_STATE_ON_HOLD; // Display a see-through silhoulette switch( w.hold_object_id ){ case 0: // This is a cube { } break; case 1: // This is a AARect break; } break; default: break; } } break; } case World::STATE_ON_HOLD: { glfwGetCursorPos( window, &cp[0], &cp[1] ); HitRecord record; v3 point = v3{ ( float )cp[0], (float)cp[1], 0.0f }; v3 wp = HMM_UnProject( point, w.perspective * w.camera->transform(), ScreenWidth, ScreenHeight ); Ray ray( w.camera->P, ( wp - w.camera->P ) ); if ( hit_world( w, ray, 0.001f, 100.0f, record ) ){ if( record.obj.type == OBJECT_GRID ){ switch ( w.hold_object_id ){ case 0: { Material m = create_material_diffuse( cube_color_texture() ); Cube cube = create_cube_one_color( 0.2f, record.p, v3 {0,1,0} ) ; world_add_cube( w, &cube, m ); WORLD_SET_STATE_SELECTED; w.is_selected = true; w.selected_object.type = OBJECT_CUBE_INSTANCE; w.selected_object.index = array_length(w.cubes)-1; w.selected_aabb = cube_get_AABB; w.selected_move = cube_move; w.selected_rotate = cube_rotate; w.cube_face_dropdown = 0; w.cube_material_dropdown = w.cube_materials[w.selected_object.index].type; w.cube_texture_dropdown = w.cube_materials[w.selected_object.index].texture.type; w.cube_face_color= w.cube_materials[w.selected_object.index].texture.face_colors[0]; w.selected_data = (void *)( w.cubes + w.selected_object.index ); w.sel_cube_length = 0.2f; break; } case 1: { Material mat = create_material_metallic( sphere_color_texture() ); Sphere s = create_sphere( record.p, 0.5f ); world_add_sphere( w,s,mat ); WORLD_SET_STATE_SELECTED; w.sel_sphere_radius = 0.5f; w.is_selected = true; w.selected_object.type = OBJECT_SPHERE; w.selected_object.index = array_length(w.spheres)-1; w.selected_aabb = sphere_aabb; w.selected_move = sphere_move; w.selected_rotate = sphere_rotate; w.sphere_material_dropdown = w.sphere_materials[w.selected_object.index].type; w.sphere_texture_dropdown = w.sphere_materials[w.selected_object.index].texture.type; w.sphere_face_color= w.sphere_materials[w.selected_object.index].texture.color; w.selected_data = (void *)( w.spheres+ w.selected_object.index ); break; } case 2: { Material mat = create_material_diffuse( rectangle_color_texture() ); Rectangle r = create_rectangle( record.p ); world_add_rect( w,r,mat ); WORLD_SET_STATE_SELECTED; w.sel_rect_l1 = r.l1; w.sel_rect_l2 = r.l2; w.is_selected = true; w.selected_object.type = OBJECT_RECT; w.selected_object.index = array_length(w.rects)-1; w.selected_aabb = rectangle_AABB; w.selected_move = rectangle_move; w.selected_rotate = rectangle_rotate; w.rect_face_color = mat.texture.color; w.rect_material_dropdown = w.rect_materials[w.selected_object.index].type; w.rect_texture_dropdown = w.rect_materials[w.selected_object.index].texture.type; w.selected_data = (void *)( w.rects + w.selected_object.index ); break; } case 3: { Cube cube = create_cube_one_color( 0.2f, record.p, v3 {1,1,1} ) ; world_add_light_cube( w, &cube, v3{1,1,1} ); WORLD_SET_STATE_SELECTED; w.sel_cube_length = 0.2f; w.is_selected = true; w.selected_object.type = OBJECT_LIGHT_CUBE_INSTANCE; w.selected_object.index = array_length(w.light_cubes)-1; w.selected_aabb = cube_get_AABB; w.selected_move = cube_move; w.selected_rotate = cube_rotate; w.light_cube_face_color = v3{1,1,1}; w.selected_data = (void *)( w.light_cubes + w.selected_object.index ); break; } case 4: { Sphere s = create_sphere( record.p, 0.5f ); world_add_light_sphere( w,s,v3{1.0f,1.0f,1.0f} ); WORLD_SET_STATE_SELECTED; w.sel_sphere_radius = 0.5f; w.is_selected = true; w.selected_object.type = OBJECT_LIGHT_SPHERE; w.selected_object.index=array_length(w.light_spheres)-1; w.selected_aabb = sphere_aabb; w.selected_move = sphere_move; w.selected_rotate = sphere_rotate; w.light_sphere_face_color=v3{1.0f,1.0f,1.0f}; w.selected_data = (void *)( w.light_spheres+ w.selected_object.index ); break; } case 5: { Rectangle r = create_rectangle( record.p ); world_add_light_rect( w,r,v3{1,1,1} ); WORLD_SET_STATE_SELECTED; w.is_selected = true; w.sel_rect_l1 = r.l1; w.sel_rect_l2 = r.l2; w.selected_object.type = OBJECT_LIGHT_RECT; w.selected_object.index = array_length(w.light_rects)-1; w.selected_aabb = rectangle_AABB; w.selected_move = rectangle_move; w.selected_rotate = rectangle_rotate; w.light_rect_face_color=v3{1.0f,1,1}; w.selected_data = (void *)( w.light_rects + w.selected_object.index ); break; } default: break; } } } } break; default: break; } } break; #define SELECTED_MOVE_DIST 0.02f #define SELECTED_MOVE_UP v3{0.0f,1.0f,0.0f} #define SELECTED_MOVE_RIGHT v3{1.0f,0.0f,0.0f} #define SELECTED_MOVE_FRONT v3{0.0f,0.0f,-1.0f} #if 1 case KB_PRESS_W: case KB_REPEAT_W: if ( w.state != World::STATE_SELECTED ){ w.camera->start_animate( 2, 0.2f ,100); } else { w.selected_move( w.selected_data, SELECTED_MOVE_DIST, SELECTED_MOVE_FRONT, w.model_matrices[w.selected_object.type][w.selected_object.index] ); } break; case KB_PRESS_S:case KB_REPEAT_S: if ( w.state != World::STATE_SELECTED ){ w.camera->start_animate( 2, -0.2f ,100); } else { w.selected_move( w.selected_data, -SELECTED_MOVE_DIST, SELECTED_MOVE_FRONT, w.model_matrices[w.selected_object.type][w.selected_object.index] ); } break; case KB_PRESS_A:case KB_REPEAT_A: if ( w.state != World::STATE_SELECTED ){ w.camera->start_animate( 0, -0.2f ,100); } else { w.selected_move( w.selected_data, -SELECTED_MOVE_DIST, SELECTED_MOVE_RIGHT, w.model_matrices[w.selected_object.type][w.selected_object.index] ); } break; case KB_PRESS_D:case KB_REPEAT_D: if ( w.state != World::STATE_SELECTED ){ w.camera->start_animate( 0, 0.2f ,100); } else { w.selected_move( w.selected_data, SELECTED_MOVE_DIST, SELECTED_MOVE_RIGHT, w.model_matrices[w.selected_object.type][w.selected_object.index] ); } break; case KB_PRESS_I:case KB_REPEAT_I: if ( w.state != World::STATE_SELECTED ){ w.camera->start_animate( 1, 0.2f ,300); } else { w.selected_move( w.selected_data, SELECTED_MOVE_DIST, SELECTED_MOVE_UP, w.model_matrices[w.selected_object.type][w.selected_object.index] ); } break; case KB_PRESS_K:case KB_REPEAT_K: if ( w.state != World::STATE_SELECTED ){ w.camera->start_animate( 1, -0.2f ,300); } else { w.selected_move( w.selected_data, -SELECTED_MOVE_DIST, SELECTED_MOVE_UP, w.model_matrices[w.selected_object.type][w.selected_object.index] ); } break; case KB_PRESS_X: case KB_REPEAT_X: show_imgui = !show_imgui; break; case KB_PRESS_T: break; case KB_PRESS_R: WORLD_SET_STATE_DETACHED; w.object_select_dropdown = 0; break; case KB_PRESS_P: w.camera->print(); break; case KB_RELEASE_W: if ( !( key_map[KB_KEY_S] || key_map[KB_KEY_A] || key_map[KB_KEY_D] || key_map[KB_KEY_I] || key_map[KB_KEY_K] ) ) { w.camera->state = Camera::STATIC; } break; case KB_RELEASE_S: if ( !( key_map[KB_KEY_W] || key_map[KB_KEY_A] || key_map[KB_KEY_D] || key_map[KB_KEY_I] || key_map[KB_KEY_K] ) ) { w.camera->state = Camera::STATIC; } break; case KB_RELEASE_A: if ( !( key_map[KB_KEY_S] || key_map[KB_KEY_W] || key_map[KB_KEY_D] || key_map[KB_KEY_I] || key_map[KB_KEY_K] ) ) { w.camera->state = Camera::STATIC; } break; case KB_RELEASE_D: if ( !( key_map[KB_KEY_S] || key_map[KB_KEY_A] || key_map[KB_KEY_W] || key_map[KB_KEY_I] || key_map[KB_KEY_K] ) ) { w.camera->state = Camera::STATIC; } break; case KB_RELEASE_I: if ( !( key_map[KB_KEY_S] || key_map[KB_KEY_A] || key_map[KB_KEY_D] || key_map[KB_KEY_W] || key_map[KB_KEY_K] ) ) { w.camera->state = Camera::STATIC; } break; case KB_RELEASE_K: if ( !( key_map[KB_KEY_S] || key_map[KB_KEY_A] || key_map[KB_KEY_D] || key_map[KB_KEY_I] || key_map[KB_KEY_W] ) ) { w.camera->state = Camera::STATIC; } break; case KB_PRESS_ESCAPE: w.camera = &w.ui_camera; if ( !(w.state == World::STATE_FREE_VIEW ) ){ w.camera = &w.ui_camera; WORLD_SET_STATE_FREE_VIEW; } else { WORLD_SET_STATE_DETACHED; } break; case KB_PRESS_C: if ( !(w.state == World::STATE_VIEW_CAMERA ) ){ w.camera = &w.view_camera; w.perspective = w.view_perspective; WORLD_SET_STATE_VIEW_CAMERA; } else { w.camera = &w.ui_camera; w.perspective = w.ui_perspective; WORLD_SET_STATE_FREE_VIEW; } break; case KB_PRESS_Q: case KB_REPEAT_Q: if ( w.state == World::STATE_SELECTED ){ w.selected_rotate( w.selected_data, 5.0f, v3{0.0f,1.0f,0.0f}, w.model_matrices[w.selected_object.type][w.selected_object.index] ); } break; case KB_PRESS_E: case KB_REPEAT_E: if ( w.state == World::STATE_SELECTED ){ w.selected_rotate( w.selected_data, -5.0f, v3{0.0f,1.0f,0.0f}, w.model_matrices[w.selected_object.type][w.selected_object.index] ); } break; #endif default: break; } } w.camera->update( dt ); glfwSetCursorPosCallback( window, mouse_callback ); Event_Count = 0; glClearColor(0.0f,0,0,1); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); // the deatched state hover if ( w.state == World::STATE_DETACHED || w.state == World::STATE_ON_HOLD|| w.state == World::STATE_VIEW_CAMERA ) { if ( w.state != World::STATE_VIEW_CAMERA ) glfwGetCursorPos( window, &cp[0], &cp[1] ); HitRecord record; v3 point = v3{ ( float )cp[0], (float)cp[1], 0.0f }; v3 wp = HMM_UnProject( point, w.perspective * w.camera->transform(), ScreenWidth, ScreenHeight ); Ray ray( w.camera->P, ( wp - w.camera->P ) ); if ( hit_world( w, ray, 0.001f, 100.0f, record ) ){ if ( record.obj.type == OBJECT_GRID ){ Grid *grid = (Grid *)record.obj.object; v3 p0 = grid_get_corner_point( *grid, record.u, record.v ); v3 p1 = p0 + grid->dir1 * grid->w; v3 p2 = p0 + grid->dir1 * grid->w + grid->dir2 * grid->w; v3 p3 = p0 + grid->dir2 * grid->w; ColorQuad quad = { p0, p1, p2, p3, v3{ 0.42f,0.65f,0.83f }, // color w.grid.rect.n }; array_push( w.temp_color_quads, quad ); } else if ( record.obj.type == OBJECT_CUBE_INSTANCE ){ array_push( w.boxes, w.cubes[record.obj.index].bounds ); } else if ( record.obj.type == OBJECT_SPHERE ){ array_push( w.boxes, w.spheres[ record.obj.index].box ); } else if ( record.obj.type == OBJECT_RECT ){ array_push( w.boxes, w.rects[ record.obj.index].box ); } else if ( record.obj.type == OBJECT_LIGHT_CUBE_INSTANCE ){ array_push( w.boxes, w.light_cubes[record.obj.index].bounds ); } else if ( record.obj.type == OBJECT_LIGHT_SPHERE ){ array_push( w.boxes, w.light_spheres[ record.obj.index].box ); } else if ( record.obj.type == OBJECT_LIGHT_RECT ){ array_push( w.boxes, w.light_rects[ record.obj.index].box ); } } } if ( w.is_selected ){ array_push( w.boxes, w.selected_aabb( w.selected_data, w.model_matrices[w.selected_object.type][w.selected_object.index] ) ); } draw_world(w); if ( w.show_imgui ){ ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplGlfw_NewFrame(); ImGui::NewFrame(); #define SLIDER_UPPER_LIMIT 10.0f // 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!). if ( show_demo_window ){ ImGui::ShowDemoWindow(&show_demo_window); } // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window. uint i = w.selected_object.index; if ( w.is_selected ){ float f = 0.0f; int counter = 0; // Create a window called "Hello, world!" and append into it. ImGui::Begin("Object Properties"); // Display some text (you can use a format strings too) ImGui::Text("Change some object properties!"); if ( w.selected_object.type == OBJECT_CUBE_INSTANCE ){ Cube *cube = &w.cubes[ i ]; const char* items[] = { "Front", "Back", "Right","Left", "Up","Down" }; ImGui::Combo("Cube Face", &w.cube_face_dropdown, items, IM_ARRAYSIZE(items)); ImGui::SliderFloat("Cube Length", &w.sel_cube_length, 0.05f, SLIDER_UPPER_LIMIT, "ratio = %.3f"); const char *material_dropdown[] = { "Metallic", "Diffuse", "Glass" }; ImGui::Combo("Material", &w.cube_material_dropdown, material_dropdown, IM_ARRAYSIZE(material_dropdown)); if ( w.cube_material_dropdown == 2 ){ } else { const char *texture_select[] = { "Color","Checker","Marble" }; ImGui::Combo("Texture", &w.cube_texture_dropdown, texture_select, IM_ARRAYSIZE(texture_select)); w.cube_face_color = w.cube_materials[i].texture.face_colors[ w.cube_face_dropdown ]; ImGui::ColorEdit3("clear color", w.cube_face_color.Elements ); } } else if ( w.selected_object.type == OBJECT_SPHERE ){ ImGui::SliderFloat("Sphere Radius", &w.sel_sphere_radius, 0.01f, SLIDER_UPPER_LIMIT, "ratio = %.3f"); const char *material_dropdown[] = { "Metallic", "Diffuse", "Glass" }; ImGui::Combo("Material", &w.sphere_material_dropdown, material_dropdown, IM_ARRAYSIZE(material_dropdown)); if ( w.sphere_material_dropdown == 2 ){ } else { const char *texture_select[] = { "Color","Checker","Marble" }; ImGui::Combo("Texture", &w.sphere_texture_dropdown, texture_select, IM_ARRAYSIZE(texture_select)); w.sphere_face_color = w.sphere_materials[i].texture.color; ImGui::ColorEdit3("clear color", w.sphere_face_color.Elements ); } } else if ( w.selected_object.type == OBJECT_RECT ){ // TODO: Two sliders if ( ImGui::Button( "Flip Normal" ) ){ w.rect_flip_normal++; } ImGui::SliderFloat("Rectangle length 1", &w.sel_rect_l1, 0.01f, SLIDER_UPPER_LIMIT, "ratio = %.3f"); ImGui::SliderFloat("Rectangle length 3", &w.sel_rect_l2, 0.01f, SLIDER_UPPER_LIMIT, "ratio = %.3f"); const char *material_dropdown[] = { "Metallic", "Diffuse", "Glass" }; ImGui::Combo("Material", &w.rect_material_dropdown, material_dropdown, IM_ARRAYSIZE(material_dropdown)); if ( w.rect_material_dropdown == 2 ){ } else { const char *texture_select[] = { "Color","Checker","Marble" }; ImGui::Combo("Texture", &w.rect_texture_dropdown, texture_select, IM_ARRAYSIZE(texture_select)); w.rect_face_color = w.rect_materials[i].texture.color; ImGui::ColorEdit3("clear color", w.rect_face_color.Elements ); } } else if ( w.selected_object.type != OBJECT_GRID ) { v3 *color; switch ( w.selected_object.type ){ case OBJECT_LIGHT_RECT: { color = &w.light_rect_face_color; w.light_rect_face_color= w.light_rect_color[i]; ImGui::SliderFloat("Rectangle length 1", &w.sel_rect_l1, 0.01f, SLIDER_UPPER_LIMIT, "ratio = %.3f"); ImGui::SliderFloat("Rectangle length 3", &w.sel_rect_l2, 0.01f, SLIDER_UPPER_LIMIT, "ratio = %.3f"); } break; case OBJECT_LIGHT_SPHERE: { color = &w.light_sphere_face_color; w.light_sphere_face_color = w.light_sphere_color[i]; ImGui::SliderFloat("Sphere Radius", &w.sel_sphere_radius, 0.01f, SLIDER_UPPER_LIMIT, "ratio = %.3f"); } break; case OBJECT_LIGHT_CUBE_INSTANCE: { color = &w.light_cube_face_color; w.light_cube_face_color= w.light_cube_color[i]; ImGui::SliderFloat("Cube Length", &w.sel_cube_length, 0.05f, SLIDER_UPPER_LIMIT, "ratio = %.3f"); } break; default: break; } ImGui::ColorEdit3("Change Color", color->Elements ); } // Buttons return true when clicked (most widgets return true // when edited/activated) if (ImGui::Button("Button")) counter++; ImGui::SameLine(); ImGui::Text("counter = %d", counter); ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); ImGui::End(); switch ( w.selected_object.type ){ case OBJECT_CUBE_INSTANCE: { Cube *cube =w.cubes + i; if ( w.cube_material_dropdown == 2 ){ w.cube_materials[i].type = Material::GLASS; } else { w.cube_materials[i].type = (Material::MaterialType)w.cube_material_dropdown; switch ( w.cube_texture_dropdown ){ case 0: w.cube_materials[i].texture.type = Texture::COLOR; break; case 1: w.cube_materials[i].texture.type = Texture::CHECKER; break; case 2: w.cube_materials[i].texture.type = Texture::MARBLE; break; default: break; } w.cube_materials[i].texture.face_colors[ w.cube_face_dropdown ] = w.cube_face_color; } f32 l = w.sel_cube_length; cube_scale( cube, v3{l,l,l}, w.model_matrices[OBJECT_CUBE_INSTANCE][i] ); world_add_cube_vertex_data(w,i); } break; case OBJECT_SPHERE: { if ( w.sphere_material_dropdown == 2 ){ w.sphere_materials[i].type = Material::GLASS; } else { w.sphere_materials[i].type = (Material::MaterialType)w.sphere_material_dropdown; w.sphere_materials[i].texture.type = (Texture::TextureType)w.sphere_texture_dropdown; w.sphere_materials[i].texture.color = w.sphere_face_color; } world_add_sphere_vertex_data(w,i); f32 l = w.sel_sphere_radius; sphere_scale(w.spheres+i, v3{l,l,l}, w.model_matrices[OBJECT_SPHERE][i] ); } break; case OBJECT_RECT: { if ( w.rect_flip_normal ){ w.rect_flip_normal--; w.rects[i].n *= -1; } if ( w.rect_material_dropdown == 2 ){ w.rect_materials[i].type = Material::GLASS; } else { w.rect_materials[i].type = (Material::MaterialType)w.rect_material_dropdown; w.rect_materials[i].texture.type = (Texture::TextureType)w.rect_texture_dropdown; w.rect_materials[i].texture.color = w.rect_face_color; } rectangle_scale( w.selected_data,w.sel_rect_l1, w.sel_rect_l2 ); break; } case OBJECT_LIGHT_CUBE_INSTANCE: { Cube *cube =w.light_cubes + i; w.light_cube_color[i] = w.light_cube_face_color; f32 l = w.sel_cube_length; world_add_light_cube_vertex_data(w,i); cube_scale( cube, v3{l,l,l}, w.model_matrices[OBJECT_LIGHT_CUBE_INSTANCE][i] ); } break; case OBJECT_LIGHT_SPHERE: { w.light_sphere_color[i] = w.light_sphere_face_color; world_add_light_sphere_vertex_data(w,i); f32 l = w.sel_sphere_radius; sphere_scale(w.light_spheres+i, v3{l,l,l}, w.model_matrices[OBJECT_LIGHT_SPHERE][i] ); } break; case OBJECT_LIGHT_RECT: w.light_rect_color[i] = w.light_rect_face_color; rectangle_scale( w.selected_data,w.sel_rect_l1, w.sel_rect_l2 ); break; default: break; } } // 3. Show another simple window. if (w.state == World::STATE_DETACHED){ ImGui::Begin("Place Objects", &show_another_window); const char* world_objects[] = { "Cube", "Sphere", "Plane","Light Cube", "Light Sphere", "Light Plane" }; ImGui::Combo("combo", &w.hold_object_id, world_objects, IM_ARRAYSIZE(world_objects)); dump_scene_data = ImGui::Button("Dump Scene Data"); ImGui::End(); } else if ( w.state == World::STATE_VIEW_CAMERA ){ ImGui::Begin( "Camera Properties" ); ImGui::End(); } // Rendering ImGui::Render(); ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); // Dear Imgui related events } glfwSwapBuffers(window); glfwPollEvents(); array_clear( w.color_vertex_data ); array_clear( w.color_vertex_modes ); array_clear( w.color_vertex_indices ); array_clear( w.index_stack ); array_clear( w.temp_color_quads ); array_clear( w.boxes ); array_clear( w.light_pos ); array_clear( w.light_colors ); if ( dump_scene_data ){ dump_scene_data = false; char buff[256]; snprintf( buff, 256, "./bin/dump_file%d.dat", dump_count ); world_dump_scene_to_file( w,buff ); } } glfwTerminate(); }
30.552619
150
0.594915
amritphuyal
d2640a83c636f758bbe9ccc9ed886d422597621f
1,696
cpp
C++
lib/AST/Pattern.cpp
mattapet/dusk-lang
928b027429a3fd38cece78a89a9619406dcdd9f0
[ "MIT" ]
1
2022-03-30T22:01:44.000Z
2022-03-30T22:01:44.000Z
lib/AST/Pattern.cpp
mattapet/dusk-lang
928b027429a3fd38cece78a89a9619406dcdd9f0
[ "MIT" ]
null
null
null
lib/AST/Pattern.cpp
mattapet/dusk-lang
928b027429a3fd38cece78a89a9619406dcdd9f0
[ "MIT" ]
null
null
null
//===--- Stmt.cpp ---------------------------------------------------------===// // // dusk-lang // This source file is part of a dusk-lang project, which is a semestral // assignement for BI-PJP course at Czech Technical University in Prague. // The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND. // //===----------------------------------------------------------------------===// #include "dusk/AST/Pattern.h" #include "dusk/AST/Decl.h" #include "dusk/AST/Expr.h" #include "dusk/AST/Stmt.h" using namespace dusk; // MARK: - Pattern Pattern::Pattern(PatternKind K) : Kind(K), Ty(nullptr) {} #define PATTERN(CLASS, PARENT) \ CLASS##Pattern *Pattern::get##CLASS##Pattern() { \ assert(Kind == PatternKind::CLASS && "Invalid conversion"); \ return static_cast<CLASS##Pattern *>(this); \ } #include "dusk/AST/PatternNodes.def" void *Pattern::operator new(size_t Bytes, ASTContext &Context) { return Context.Allocate(Bytes); } // MARK: - Expression pattern ExprPattern::ExprPattern(SmallVector<Expr *, 128> &&V, SMLoc L, SMLoc R) : Pattern(PatternKind::Expr), Values(V), LPar(L), RPar(R) {} SMRange ExprPattern::getSourceRange() const { return {LPar, RPar}; } size_t ExprPattern::count() const { return Values.size(); } // MARK: - Variable pattern VarPattern::VarPattern(SmallVector<Decl *, 128> &&V, SMLoc L, SMLoc R) : Pattern(PatternKind::Var), Vars(V), LPar(L), RPar(R) {} SMRange VarPattern::getSourceRange() const { return {LPar, RPar}; } size_t VarPattern::count() const { return Vars.size(); }
36.085106
80
0.570755
mattapet
d2691261365a587d79634ba5899d220f2bce2c39
2,137
hpp
C++
kits/daisy/src/input/input_manager_mobile_io.hpp
HebiRobotics/hebi-cpp-examples
db01c9b957b3c97885d452d8b72f9919ba6c48c4
[ "Apache-2.0" ]
7
2018-03-31T06:52:08.000Z
2022-02-24T21:27:09.000Z
kits/daisy/src/input/input_manager_mobile_io.hpp
HebiRobotics/hebi-cpp-examples
db01c9b957b3c97885d452d8b72f9919ba6c48c4
[ "Apache-2.0" ]
34
2018-06-03T17:28:08.000Z
2021-05-29T01:15:25.000Z
kits/daisy/src/input/input_manager_mobile_io.hpp
HebiRobotics/hebi-cpp-examples
db01c9b957b3c97885d452d8b72f9919ba6c48c4
[ "Apache-2.0" ]
9
2018-02-08T22:50:58.000Z
2021-03-30T08:07:35.000Z
#pragma once #include "input_manager.hpp" #include <Eigen/Dense> #include "group.hpp" #include <memory> #include <atomic> namespace hebi { namespace input { // If the I/O board/app is not found, command vectors return 0, and button // um toggle/quit states are unchanged by 'update'. Class is not // re-entrant. class InputManagerMobileIO : public InputManager { public: InputManagerMobileIO(); virtual ~InputManagerMobileIO() noexcept = default; // Connect to an I/O board/app and start getting feedback. Return "true" if // found. Clears any existing connection bool reset(); // A debug command that can be used to print the current state of the joystick // variables that are stored by the class. void printState() const override; // Get the current translation velocity command Eigen::Vector3f getTranslationVelocityCmd() const override; // Get the current rotation velocity command Eigen::Vector3f getRotationVelocityCmd() const override; // Returns true if the quit button has ever been pushed bool getQuitButtonPushed() const override; // Gets the number of times the mode button has been toggled since the last // request. Resets this count after retrieving. size_t getMode() override; // Is the joystick connected? // Return "true" if we are connected to an I/O board/app; false otherwise. bool isConnected() const override { return group_ ? true : false; } private: float getVerticalVelocity() const; // The Mobile IO app that serves as a joystick std::shared_ptr<hebi::Group> group_; // Scale the joystick scale to motion of the robot in SI units (m/s, rad/s, // etc). static constexpr float xyz_scale_{0.175}; static constexpr float rot_scale_{0.4}; float left_horz_raw_{0}; // Rotation float left_vert_raw_{0}; // Chassis tilt float slider_1_raw_{0}; // Height float right_horz_raw_{0}; // Translation (l/r) float right_vert_raw_{0}; // Translation (f/b) bool prev_mode_button_state_{false}; // Mode std::atomic<size_t> mode_{0}; // bool has_quit_been_pushed_ = false; // Quit }; } // namespace input } // namespace hebi
27.753247
80
0.722976
HebiRobotics
d26a26e5401be4c03c63188513625929e32a9b38
1,179
cpp
C++
problem 1-50/45. Jump Game II.cpp
just-essential/LeetCode-Cpp
3ec49434d257defd28bfe4784ecd0ff2f9077a31
[ "MIT" ]
null
null
null
problem 1-50/45. Jump Game II.cpp
just-essential/LeetCode-Cpp
3ec49434d257defd28bfe4784ecd0ff2f9077a31
[ "MIT" ]
null
null
null
problem 1-50/45. Jump Game II.cpp
just-essential/LeetCode-Cpp
3ec49434d257defd28bfe4784ecd0ff2f9077a31
[ "MIT" ]
null
null
null
/* Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Your goal is to reach the last index in the minimum number of jumps. Example: Input: [2,3,1,1,4] Output: 2 Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index. Note: You can assume that you can always reach the last index. */ class Solution { public: int jump(vector<int> &nums) { int rear = nums.size() - 1, i, j, count, maxStep, pos; for (i = count = 0; i < rear; i = pos) { count++; if (i + nums[i] >= rear) { break; } maxStep = nums[i + 1] + 1; pos = i + 1; for (j = 2; j <= nums[i]; ++j) { if (nums[i + j] + j > maxStep) { maxStep = nums[i + j] + j; pos = i + j; } } } return count; } void test() { vector<int> nums{2, 3, 1, 1, 4}; assert(jump(nums) == 2); } };
27.418605
102
0.516539
just-essential
d26f4fe365543d2d29c31dea739648798b35349a
7,479
cpp
C++
mitsuba-af602c6fd98a/src/emitters/directional.cpp
NTForked-ML/pbrs
0b405d92c12d257e2581366542762c9f0c3facce
[ "MIT" ]
139
2017-04-21T00:22:34.000Z
2022-02-16T20:33:10.000Z
mitsuba-af602c6fd98a/src/emitters/directional.cpp
NTForked-ML/pbrs
0b405d92c12d257e2581366542762c9f0c3facce
[ "MIT" ]
11
2017-08-15T18:22:59.000Z
2019-07-01T05:44:41.000Z
mitsuba-af602c6fd98a/src/emitters/directional.cpp
NTForked-ML/pbrs
0b405d92c12d257e2581366542762c9f0c3facce
[ "MIT" ]
30
2017-07-21T03:56:45.000Z
2022-03-11T06:55:34.000Z
/* This file is part of Mitsuba, a physically based rendering system. Copyright (c) 2007-2014 by Wenzel Jakob and others. Mitsuba is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License Version 3 as published by the Free Software Foundation. Mitsuba is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <mitsuba/render/scene.h> #include <mitsuba/core/warp.h> MTS_NAMESPACE_BEGIN /*!\plugin{directional}{Directional emitter} * \icon{emitter_directional} * \order{4} * \parameters{ * \parameter{toWorld}{\Transform\Or\Animation}{ * Specifies an optional emitter-to-world transformation. * \default{none (i.e. emitter space $=$ world space)} * } * \parameter{direction}{\Vector}{ * Alternative to \code{toWorld}: explicitly specifies * the illumination direction. Note that only one of the * two parameters can be used. * } * \parameter{irradiance}{\Spectrum}{ * Specifies the amount of power per unit area received * by a hypothetical surface normal to the specified direction * \default{1} * } * \parameter{samplingWeight}{\Float}{ * Specifies the relative amount of samples * allocated to this emitter. \default{1} * } * } * * This emitter plugin implements a distant directional source, which * radiates a specified power per unit area along a fixed direction. * By default, the emitter radiates in the direction of the postive Z axis. */ class DirectionalEmitter : public Emitter { public: DirectionalEmitter(const Properties &props) : Emitter(props) { m_type |= EDeltaDirection; m_normalIrradiance = props.getSpectrum("irradiance", Spectrum::getD65()); if (props.hasProperty("direction")) { if (props.hasProperty("toWorld")) Log(EError, "Only one of the parameters 'direction' and 'toWorld'" "can be used at a time!"); Vector d(normalize(props.getVector("direction"))), u, unused; coordinateSystem(d, u, unused); m_worldTransform = new AnimatedTransform( Transform::lookAt(Point(0.0f), Point(d), u)); } else { if (props.getTransform("toWorld", Transform()).hasScale()) Log(EError, "Scale factors in the emitter-to-world " "transformation are not allowed!"); } } DirectionalEmitter(Stream *stream, InstanceManager *manager) : Emitter(stream, manager) { m_normalIrradiance = Spectrum(stream); m_bsphere = BSphere(stream); configure(); } void serialize(Stream *stream, InstanceManager *manager) const { Emitter::serialize(stream, manager); m_normalIrradiance.serialize(stream); m_bsphere.serialize(stream); } ref<Shape> createShape(const Scene *scene) { /* Create a bounding sphere that surrounds the scene */ m_bsphere = scene->getKDTree()->getAABB().getBSphere(); m_bsphere.radius *= 1.1f; configure(); return NULL; } void configure() { Emitter::configure(); Float surfaceArea = M_PI * m_bsphere.radius * m_bsphere.radius; m_invSurfaceArea = 1.0f / surfaceArea; m_power = m_normalIrradiance * surfaceArea; } Spectrum samplePosition(PositionSamplingRecord &pRec, const Point2 &sample, const Point2 *extra) const { const Transform &trafo = m_worldTransform->eval(pRec.time); Point2 p = warp::squareToUniformDiskConcentric(sample); Vector perpOffset = trafo(Vector(p.x, p.y, 0) * m_bsphere.radius); Vector d = trafo(Vector(0, 0, 1)); pRec.p = m_bsphere.center - d*m_bsphere.radius + perpOffset; pRec.n = d; pRec.pdf = m_invSurfaceArea; pRec.measure = EArea; return m_power; } Spectrum evalPosition(const PositionSamplingRecord &pRec) const { return (pRec.measure == EArea) ? m_normalIrradiance : Spectrum(0.0f); } Float pdfPosition(const PositionSamplingRecord &pRec) const { return (pRec.measure == EArea) ? m_invSurfaceArea : 0.0f; } Spectrum sampleDirection(DirectionSamplingRecord &dRec, PositionSamplingRecord &pRec, const Point2 &sample, const Point2 *extra) const { dRec.d = pRec.n; dRec.pdf = 1.0f; dRec.measure = EDiscrete; return Spectrum(1.0f); } Float pdfDirection(const DirectionSamplingRecord &dRec, const PositionSamplingRecord &pRec) const { return (dRec.measure == EDiscrete) ? 1.0f : 0.0f; } Spectrum evalDirection(const DirectionSamplingRecord &dRec, const PositionSamplingRecord &pRec) const { return Spectrum((dRec.measure == EDiscrete) ? 1.0f : 0.0f); } Spectrum sampleRay(Ray &ray, const Point2 &spatialSample, const Point2 &directionalSample, Float time) const { const Transform &trafo = m_worldTransform->eval(time); Point2 p = warp::squareToUniformDiskConcentric(spatialSample); Vector perpOffset = trafo(Vector(p.x, p.y, 0) * m_bsphere.radius); Vector d = trafo(Vector(0, 0, 1)); ray.setOrigin(m_bsphere.center - d*m_bsphere.radius + perpOffset); ray.setDirection(d); ray.setTime(time); return m_power; } Spectrum sampleDirect(DirectSamplingRecord &dRec, const Point2 &sample) const { const Transform &trafo = m_worldTransform->eval(dRec.time); Vector d = trafo(Vector(0,0,1)); Point diskCenter = m_bsphere.center - d*m_bsphere.radius; Float distance = dot(dRec.ref - diskCenter, d); if (distance < 0) { /* This can happen when doing bidirectional renderings involving environment maps and directional sources. Just return zero */ return Spectrum(0.0f); } dRec.p = dRec.ref - distance * d; dRec.d = -d; dRec.n = Normal(d); dRec.dist = distance; dRec.pdf = 1.0f; dRec.measure = EDiscrete; return m_normalIrradiance; } Float pdfDirect(const DirectSamplingRecord &dRec) const { return dRec.measure == EDiscrete ? 1.0f : 0.0f; } AABB getAABB() const { return AABB(); } Shader *createShader(Renderer *renderer) const; std::string toString() const { std::ostringstream oss; oss << "DirectionalEmitter[" << endl << " normalIrradiance = " << m_normalIrradiance.toString() << "," << endl << " samplingWeight = " << m_samplingWeight << "," << endl << " worldTransform = " << indent(m_worldTransform.toString()) << "," << endl << " medium = " << indent(m_medium.toString()) << endl << "]"; return oss.str(); } MTS_DECLARE_CLASS() private: Spectrum m_normalIrradiance, m_power; BSphere m_bsphere; Float m_invSurfaceArea; }; // ================ Hardware shader implementation ================ class DirectionalEmitterShader : public Shader { public: DirectionalEmitterShader(Renderer *renderer) : Shader(renderer, EEmitterShader) { } void generateCode(std::ostringstream &oss, const std::string &evalName, const std::vector<std::string> &depNames) const { oss << "vec3 " << evalName << "_dir(vec3 wo) {" << endl << " return vec3(1.0);" << endl << "}" << endl; } MTS_DECLARE_CLASS() }; Shader *DirectionalEmitter::createShader(Renderer *renderer) const { return new DirectionalEmitterShader(renderer); } MTS_IMPLEMENT_CLASS(DirectionalEmitterShader, false, Shader) MTS_IMPLEMENT_CLASS_S(DirectionalEmitter, false, Emitter) MTS_EXPORT_PLUGIN(DirectionalEmitter, "Directional emitter"); MTS_NAMESPACE_END
31.825532
105
0.701163
NTForked-ML
d26fc404c5320d9b99581cede8b739187ab0c1a2
13,233
cpp
C++
project/TinyCADxxx/XMLReader.cpp
lakeweb/ECAD
9089253afd39adecd88f4a33056f91b646207e00
[ "MIT" ]
null
null
null
project/TinyCADxxx/XMLReader.cpp
lakeweb/ECAD
9089253afd39adecd88f4a33056f91b646207e00
[ "MIT" ]
null
null
null
project/TinyCADxxx/XMLReader.cpp
lakeweb/ECAD
9089253afd39adecd88f4a33056f91b646207e00
[ "MIT" ]
2
2019-06-21T16:17:49.000Z
2020-07-04T13:41:01.000Z
/* TinyCAD program for schematic capture Copyright 1994-2004 Matt Pyne. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // XMLReader.cpp: implementation of the CXMLReader class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include <string> //#include "tinycad.h" #include "XMLReader.h" #include "XMLException.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CXMLReader::CXMLReader(CStream* pInput) { //TRACE("CXMLReader::CXMLReader(): Constructor.\n"); m_pInput = pInput; m_uu_data = NULL; m_uu_size = 0; m_uu_state = 0; m_current_self_closing = false; m_charset_conv = CHARSET_INVALID; m_decoded_buffer = NULL; m_decoded_buf_size = 0; m_output_pos = 0; m_decoded_chars = 0; m_line_counter = 0; #ifdef UNICODE SetCharset( _T("UTF-8") ); #endif intoTag(); //TRACE("CXMLReader::CXMLReader(): Leaving CXMLReader() constructor.\n"); } CXMLReader::~CXMLReader() { //TRACE("CXMLReader::~CXMLReader(): Entering Destructor.\n"); while (m_tags.size() > 0) { delete m_tags.front(); m_tags.pop_front(); } if (m_charset_conv != CHARSET_INVALID) { iconv_close(m_charset_conv); } delete m_decoded_buffer; //TRACE("CXMLReader::~CXMLReader(): Leaving Destructor\n"); } // Set up the character set conversions void CXMLReader::SetCharset(const TCHAR* fromcode) { //TRACE("CXMLReader::SetCharset(): Entering - doing iconv stuff.\n"); if (m_charset_conv != CHARSET_INVALID) { iconv_close(m_charset_conv); } #ifdef UNICODE char fc[ 256 ]; int l = WideCharToMultiByte( CP_ACP, 0, fromcode, _tcslen( fromcode), fc, static_cast<int> (sizeof( fc )), NULL, NULL ); fc[ l ] = 0; m_charset_conv = iconv_open( "UCS-2-INTERNAL", fc ); #else m_charset_conv = iconv_open("CHAR", fromcode); #endif //TRACE("CXMLReader::SetCharset(): Leaving.\n"); } // Get the next character from the input stream bool CXMLReader::getNextChar(xml_char_t &c) { if (m_charset_conv != CHARSET_INVALID) { // Are there any bytes in the decoded buffer? if (m_output_pos >= m_decoded_chars) { // No bytes left, so must refetch m_output_pos = 0; // We read in a line at a time and decode it... std::string input; char in_c; do { if (m_pInput->Read(&in_c, 1) != 1) { // Eof break; } input += in_c; if (in_c == '\n') { //track the line number of the input XML file so that it can be used in error messages. m_line_counter++; } } while (in_c != '\r' && in_c != '\n'); if (m_decoded_buf_size < input.size() * 4) { delete m_decoded_buffer; m_decoded_buf_size = input.size() * 4; m_decoded_buffer = new TCHAR[m_decoded_buf_size]; } // Now perform the conversion size_t outbuf_size = m_decoded_buf_size * sizeof(TCHAR); size_t inbuf_size = input.size(); TCHAR *out = m_decoded_buffer; const char *in = input.c_str(); iconv(m_charset_conv, &in, &inbuf_size, (char **) &out, &outbuf_size); m_decoded_chars = (TCHAR*) out - m_decoded_buffer; } // Are there any bytes in the decoded buffer? if (m_output_pos >= m_decoded_chars) { // No bytes left, must be eof return true; } else { c = m_decoded_buffer[m_output_pos]; ++m_output_pos; return false; } } else { // No charset conversion available... return m_pInput->Read(&c, 1) != 1; } } xml_parse_tag* CXMLReader::get_current_tag() { return m_tags.front(); } // Get the attribute information associated with the current // tag... bool CXMLReader::internal_getAttribute(const xml_char_t *name, CString &data) { xml_parse_tag::attrCollection::iterator it = get_current_tag()->m_attributes.find(name); if (it != get_current_tag()->m_attributes.end()) { data = (*it).second; return true; } return false; } void CXMLReader::child_data(const xml_char_t *in) { //TRACE("CXMLReader::child_data(): uudecode stuff\n"); if (m_uu_data != NULL && m_uu_size > 0) { int l = (int) _tcslen(in); while (l > 0) { uudecode(in[0]); in++; l--; } } else { m_child_data += in; } } // Handle the current tag as a system tag void CXMLReader::handleSystemTag() { //TRACE("CXMLReader::handleSystemTag()\n"); xml_parse_tag *tag = get_current_tag(); // Is this the xml header tag? if (tag->m_tag_name == "?xml") { // Ok, get the encoding attribute if it is present... CString data; if (internal_getAttribute(_T("encoding"), data)) { // Use this encoding SetCharset(data); } } } // Scan and find the next tag bool CXMLReader::getNextTag(CString &name) { //TRACE("CXMLReader::getNextTag()\n"); if (m_current_self_closing) { return false; } // Is the sub-buffer for the child data const int build_len = 255; xml_char_t child_data_build[build_len + 1]; int child_data_index = 0; // Now scan to find the next tag... xml_char_t c; for (;;) { do { if (getNextChar(c)) { name = ""; return false; } if (c != '<') { if (child_data_index == build_len || c == '&') { child_data_build[child_data_index] = 0; child_data(child_data_build); child_data_index = 0; } if (c == '&') { child_data(xml_parse_tag::read_entity(this)); } else { child_data_build[child_data_index] = c; child_data_index++; } } } while (c != '<'); // Now we have found the opening for the next // tag, we must scan it... get_current_tag()->parse(this); // Was this a comment? if (get_current_tag()->m_comment) { continue; } // Was this a system tag? if (get_current_tag()->isSystemTag()) { // Handle it... handleSystemTag(); continue; } // Was this a closing tag? if (get_current_tag()->m_closing_tag) { // Yep, so this is the end of this run.... name = get_current_tag()->m_tag_name; child_data_build[child_data_index] = 0; child_data(child_data_build); return false; } else { // Ok, we have a new opening tag... name = get_current_tag()->m_tag_name; child_data_build[child_data_index] = 0; child_data(child_data_build); return true; } } } // Scan until the end of the current tag... // bool CXMLReader::closeTag() { //TRACE("CXMLReader::closeTag()\n"); if (m_current_self_closing) { return true; } // Is this tag self-closing? if (get_current_tag()->m_self_closing_tag || get_current_tag()->m_closing_tag) { return true; } CString close_name = get_current_tag()->m_tag_name; // Nope, we must scan until we find the closing for // this tag ( recursively going into tags and out // again until we find our match...) for (;;) { CString name; // Is this the closing tag for the current tag? if (!getNextTag(name)) { if (close_name == name) { return true; } else { CString diagnosticMessage; diagnosticMessage.Format(_T("Error: XMLReader line #378: ERR_XML_WRONG_CLOSE: Expecting tag [%s], but found tag [%s]. Current line number = %d.\n"), (LPCTSTR)name, (LPCTSTR)close_name, m_line_counter); TRACE(diagnosticMessage); throw new CXMLException(ERR_XML_WRONG_CLOSE, m_line_counter, TRUE); } } else { // Must be an opening tag, so we need to close this // tag now... intoTag(); outofTag(); } } //return true; } // Find the next peer tag of this tag // returns false if there are no more tags at this // level... bool CXMLReader::nextTag(CString &name) { //TRACE("CXMLReader::nextTag()\n"); // First, we must find the closing of the // previous tag if (!closeTag()) { return false; } m_child_data = ""; return getNextTag(name); } // Move inside the current tag. nextTag will then return // tags that are inside the current tag.... void CXMLReader::intoTag() { //TRACE("CXMLReader::intoTag(): Entering.\n"); // Is this tag self-closing? if (m_tags.size() > 0 && get_current_tag()->m_self_closing_tag) { m_current_self_closing = true; } else { // Create a new parser to go into the tag system... xml_parse_tag *tag = new xml_parse_tag(); m_tags.push_front(tag); } //TRACE("CXMLReader::intoTag(): Leaving.\n"); } // Move up one level. nextTag will then return tags // that are one above the current level... // void CXMLReader::outofTag() { //TRACE("CXMLReader::outofTag()\n"); if (m_current_self_closing) { m_current_self_closing = false; return; } // Have we already scanned to the closing tag? if (get_current_tag()->m_closing_tag && m_tags.size() > 1) { CString check_name = get_current_tag()->m_tag_name; // Copy this tag up one level... xml_parse_tag *ptag = m_tags.front(); m_tags.pop_front(); delete m_tags.front(); m_tags.pop_front(); m_tags.push_front(ptag); if (get_current_tag()->m_tag_name != check_name) { CString diagnosticMessage; diagnosticMessage.Format(_T("Error: XMLReader line #475: ERR_XML_WRONG_CLOSE: Expecting tag [%s], but found tag [%s]. Current line number = %d.\n"), (LPCTSTR)check_name, (LPCTSTR)get_current_tag()->m_tag_name, m_line_counter); TRACE(diagnosticMessage); throw new CXMLException(ERR_XML_WRONG_CLOSE, m_line_counter, TRUE); } } else { delete m_tags.front(); m_tags.pop_front(); closeTag(); } } // Get the next child data associated with the current tag // CString CXMLReader::internal_getChildData() { //TRACE("CXMLReader::internal_getChildData()\n"); m_child_data = ""; closeTag(); return m_child_data; } void CXMLReader::getChildDataUUdecode(BYTE* &data, UINT &size) { //TRACE("CXMLReader::getChildDataUUdecode()\n"); // Get the size of this data CString name; getAttribute(_T("size"), size); data = new BYTE[size]; m_uu_size = size; m_uu_data = data; closeTag(); m_uu_data = NULL; m_uu_size = 0; m_uu_state = 0; } // single character decode #define DEC(c) (((c) - ' ') & 077) // UUdecode void CXMLReader::uudecode(xml_char_t in) { //TRACE("CXMLReader::uudecode()\n"); switch (m_uu_state) { case 0: // We are awaiting the line count if (xml_parse_tag::is_whitespace(in)) { break; } // Not whitespace, so must be the line count... m_uu_line_size = DEC(in); m_uu_state++; break; case 1: // We are awating the 1st char in the four char set m_uu_bytes[0] = static_cast<char> (in); m_uu_state++; break; case 2: // We are awating the 2nd char in the four char set m_uu_bytes[1] = static_cast<char> (in); m_uu_state++; break; case 3: // We are awating the 3rd char in the four char set m_uu_bytes[2] = static_cast<char> (in); m_uu_state++; break; case 4: // We are awating the 4th char in the four char set m_uu_bytes[3] = static_cast<char> (in); int c[3]; c[0] = DEC(m_uu_bytes[0]) << 2 | DEC(m_uu_bytes[1]) >> 4; c[1] = DEC(m_uu_bytes[1]) << 4 | DEC(m_uu_bytes[2]) >> 2; c[2] = DEC(m_uu_bytes[2]) << 6 | DEC(m_uu_bytes[3]); for (int i = 0; i < 3; i++) { if (m_uu_line_size > 0 && m_uu_size > 0) { *m_uu_data = (BYTE) c[i]; m_uu_line_size--; m_uu_size--; m_uu_data++; } } if (m_uu_line_size == 0) { m_uu_state = 0; } else { m_uu_state = 1; } break; } } // Type conversions.... void CXMLReader::unmakeString(CString str, CString &data) { data = str; } void CXMLReader::unmakeString(CString str, int &data) { data = _tstoi(str); } void CXMLReader::unmakeString(CString str, UINT &data) { _stscanf_s(str, _T("%u"), &data); } void CXMLReader::unmakeString(CString str, COLORREF &data) { xml_char_t *dummy; data = _tcstol(str, &dummy, 16); } void CXMLReader::unmakeString(CString str, double &data) { data = _tstof(str); } void CXMLReader::unmakeString(CString str, CDPoint &data) { _stscanf_s(str, _T("%lg,%lg"), &data.x, &data.y); data.x = data.unmakeXMLUnits(data.x); data.y = data.unmakeXMLUnits(data.y); } void CXMLReader::unmakeString(CString str, BYTE &data) { int d; unmakeString(str, d); data = (BYTE) d; } void CXMLReader::unmakeString(CString str, unsigned short &data) { int d; unmakeString(str, d); data = (unsigned short) d; } void CXMLReader::unmakeString(CString str, short &data) { int d; unmakeString(str, d); data = (short) d; } void CXMLReader::unmakeString(CString str, long &data) { int d; unmakeString(str, d); data = d; } void CXMLReader::unmakeString(CString str, bool &data) { int d; unmakeString(str, d); data = d != 0; } int CXMLReader::get_line_counter() { return m_line_counter; }
20.580093
233
0.650722
lakeweb
d26fd18e9b47cbcea57806cecceac714dc2d1da4
611
cpp
C++
programming/dataStructure_Algorithm/exercises/bigProblems/pairToUnorderedSet.cpp
ljyang100/dataScience
ad2b243673c570c18d83ab1a0cd1bb4694c17eac
[ "MIT" ]
2
2020-12-10T02:05:29.000Z
2021-05-30T15:23:56.000Z
programming/dataStructure_Algorithm/exercises/bigProblems/pairToUnorderedSet.cpp
ljyang100/dataScience
ad2b243673c570c18d83ab1a0cd1bb4694c17eac
[ "MIT" ]
null
null
null
programming/dataStructure_Algorithm/exercises/bigProblems/pairToUnorderedSet.cpp
ljyang100/dataScience
ad2b243673c570c18d83ab1a0cd1bb4694c17eac
[ "MIT" ]
1
2020-04-21T11:18:18.000Z
2020-04-21T11:18:18.000Z
#include <iostream> #include <algorithm> #include <unordered_map> #include <unordered_set> #include <functional> int main() { //**** Note **** //**** Important. Although in standard we cannot insert pair to unordered_set, we can do so for std::multiset. See example in find K pairs of smallest sum. std::unordered_set<std::pair<int, int>> hello; //There is no standard way to insert pair to unordered_set. //Check "insert pair into unordered_set" for the ways of providing specialize the template to do so. //**** Seems not necessary, because this is what exactly does by un_ordered_map. return 0; }
33.944444
157
0.729951
ljyang100
d2708f9c33f6d973a94fea6a9d89f61d8dd5ee9d
6,256
cpp
C++
BLAXED/AnimatedClanTag.cpp
prismatical/BX-CSGO
24b2cadefdc40cb8d3fca0aab08ec54241518958
[ "MIT" ]
19
2018-03-04T08:04:29.000Z
2022-01-27T11:28:36.000Z
BLAXED/AnimatedClanTag.cpp
prismatical/BX-CSGO
24b2cadefdc40cb8d3fca0aab08ec54241518958
[ "MIT" ]
1
2019-12-27T15:43:41.000Z
2020-05-18T19:16:42.000Z
BLAXED/AnimatedClanTag.cpp
prismatical/BX-CSGO
24b2cadefdc40cb8d3fca0aab08ec54241518958
[ "MIT" ]
9
2019-03-30T22:39:25.000Z
2021-08-13T19:27:27.000Z
#include "SDK.h" #include "Global.h" #include "Configs.h" #include "AnimatedClanTag.h" AnimatedClanTag *animatedClanTag = new AnimatedClanTag(); void AnimatedClanTag::Tick() { char tag[64]; int i = 0; float serverTime = (float)I::pEngineClient->GetServerTick() * (I::pGlobals->interval_per_tick * 2); std::vector<std::string> anim; switch (cfg.Misc.clanTagAnimation) { case 1: i = (int)(serverTime) % 2; if (i == 0 || i == 1) { for (i = 0; i < 4; i++) tag[i] = Math::Random('0', '1'); tag[i] = '\0'; SetClanTag(tag); } break; case 2: anim.push_back(xorstr("getze.us ")); anim.push_back(xorstr(" getze.us ")); anim.push_back(xorstr(" getze.us ")); anim.push_back(xorstr(" getze.us ")); anim.push_back(xorstr(" getze.us ")); anim.push_back(xorstr(" getze.us ")); anim.push_back(xorstr(" getze.us")); anim.push_back(xorstr(" getze.us ")); anim.push_back(xorstr(" getze.us ")); anim.push_back(xorstr(" getze.us ")); anim.push_back(xorstr(" getze.us ")); anim.push_back(xorstr(" getze.us ")); anim.push_back(xorstr("getze.us ")); break; case 3: anim.push_back(xorstr("B")); anim.push_back(xorstr("BL")); anim.push_back(xorstr("BLA")); anim.push_back(xorstr("BLAX")); anim.push_back(xorstr("BLAXE")); anim.push_back(xorstr("BLAXED")); anim.push_back(xorstr("BLAXED.")); anim.push_back(xorstr("BLAXED.C")); anim.push_back(xorstr("BLAXED.CO")); anim.push_back(xorstr("BLAXED.COM")); anim.push_back(xorstr("BLAXED.CO")); anim.push_back(xorstr("BLAXED.C")); anim.push_back(xorstr("BLAXED.")); anim.push_back(xorstr("BLAXED")); anim.push_back(xorstr("BLAXE")); anim.push_back(xorstr("BLAX")); anim.push_back(xorstr("BLA")); anim.push_back(xorstr("BL")); anim.push_back(xorstr("B")); break; case 4: anim.push_back(xorstr(" ")); anim.push_back(xorstr("c ")); anim.push_back(xorstr("cc ")); anim.push_back(xorstr(".cc ")); anim.push_back(xorstr("t.cc ")); anim.push_back(xorstr("et.cc ")); anim.push_back(xorstr("eet.cc ")); anim.push_back(xorstr("keet.cc ")); anim.push_back(xorstr("skeet.cc ")); anim.push_back(xorstr(" skeet.cc ")); anim.push_back(xorstr(" skeet.cc ")); anim.push_back(xorstr(" skeet.cc ")); anim.push_back(xorstr(" skeet.cc ")); anim.push_back(xorstr(" skeet.cc ")); anim.push_back(xorstr(" skeet.cc")); anim.push_back(xorstr(" skeet.c")); anim.push_back(xorstr(" skeet.")); anim.push_back(xorstr(" skeet")); anim.push_back(xorstr(" skee")); anim.push_back(xorstr(" ske")); anim.push_back(xorstr(" sk")); anim.push_back(xorstr(" s")); break; case 5: anim.push_back(xorstr("[VALVE]")); break; case 6: anim.push_back(xorstr("[testing]")); break; case 7: anim.push_back(xorstr("- BLAXED +")); anim.push_back(xorstr("+ BLAXED -")); break; case 8: /*anim.push_back(xorstr( "/ GB HvH /" )); anim.push_back(xorstr( "- GB HvH -" )); anim.push_back(xorstr("\\GB HvH \\")); anim.push_back(xorstr( "| GB HvH |" )); anim.push_back(xorstr( "- GB HvH -" )); anim.push_back(xorstr( "/ GB HvH /" )); anim.push_back(xorstr( "- GB HvH-" )); anim.push_back(xorstr("\\ GB HvH \\")); anim.push_back(xorstr( "| GB HvH |" ));*/ /* anim.push_back(xorstr( "/ GB HvH /" )); anim.push_back(xorstr( "- GB HvH -" )); anim.push_back(xorstr("\\ GB HvH \\")); anim.push_back(xorstr( "| GB HvH |" )); anim.push_back(xorstr( "- GB HvH -" )); anim.push_back(xorstr( "/ GB HvH /" )); anim.push_back(xorstr( "- GB HvH -" )); anim.push_back(xorstr("\\ GB HvH \\")); anim.push_back(xorstr( "| GB HvH |" ));*/ anim.push_back(xorstr("RO HVH +")); anim.push_back(xorstr("RO HVH -")); break; case 9: anim.push_back(xorstr("gamesense ")); anim.push_back(xorstr(" gamesense ")); anim.push_back(xorstr(" gamesense ")); anim.push_back(xorstr(" gamesense ")); anim.push_back(xorstr(" gamesense")); anim.push_back(xorstr(" gamesens")); anim.push_back(xorstr(" gamesen")); anim.push_back(xorstr(" gamese")); anim.push_back(xorstr(" games")); anim.push_back(xorstr(" game")); anim.push_back(xorstr(" gam")); anim.push_back(xorstr(" ga")); anim.push_back(xorstr(" g")); anim.push_back(xorstr(" ")); anim.push_back(xorstr("e ")); anim.push_back(xorstr("se ")); anim.push_back(xorstr("nse ")); anim.push_back(xorstr("ense ")); anim.push_back(xorstr("sense ")); anim.push_back(xorstr("esense ")); anim.push_back(xorstr("mesense ")); anim.push_back(xorstr("amesense ")); anim.push_back(xorstr("gamesense ")); break; } static bool reset = 0; if (cfg.Misc.clanTagAnimation != 0) { if (cfg.Misc.clanTagAnimation != 1) { i = (int)(serverTime) % (int)anim.size(); SetClanTag(anim[i].c_str()); reset = true; } } else { if (reset) { SetClanTag(""); reset = false; } } } /*int i = (int)(serverTime) % 21; / * | / - | / - * / switch (i) { case 0:SetClanDGDruedTagName(" \\ "); break; case 1:SetClanDGDruedTagName(" | "); break; case 2: SetClanDGDruedTagName(" / "); break; case 3: SetClanDGDruedTagName(" - "); break; case 5: SetClanDGDruedTagName(" Z "); break; case 6: SetClanDGDruedTagName(" Z\\ "); break; case 7: SetClanDGDruedTagName(" Z| "); break; case 8: SetClanDGDruedTagName(" Z/ "); break; case 9: SetClanDGDruedTagName(" Z- "); break; case 10: SetClanDGDruedTagName(" Ze "); break; case 11: SetClanDGDruedTagName(" Ze\\ "); break; case 12:SetClanDGDruedTagName(" Ze| "); break; case 13:SetClanDGDruedTagName(" Ze/ "); break; case 14:SetClanDGDruedTagName(" Ze- "); break; case 15:SetClanDGDruedTagName(" Zeu "); break; case 16:SetClanDGDruedTagName(" Zeu\\ "); break; case 17:SetClanDGDruedTagName(" Zeu| "); break; case 18:SetClanDGDruedTagName(" Zeu/ "); break; case 19:SetClanDGDruedTagName(" Zeu- "); break; case 20:SetClanDGDruedTagName(" Zeus "); break; } } } */
28.56621
100
0.594789
prismatical
d272d3b49b83fda00b6a1747a2dcc867b30e6cf7
1,236
cpp
C++
Material/CPP_Primer_Plus_Book/Ch.04/Ch.04 - Exercise 05 - Struct/main.cpp
hpaucar/OOP-C-plus-plus-repo
e1fedd376029996a53d70d452b7738d9c43173c0
[ "MIT" ]
4
2020-12-26T03:17:45.000Z
2022-01-11T05:54:40.000Z
Material/CPP_Primer_Plus_Book/Ch.04/Ch.04 - Exercise 05 - Struct/main.cpp
hpaucar/OOP-C-plus-plus-repo
e1fedd376029996a53d70d452b7738d9c43173c0
[ "MIT" ]
null
null
null
Material/CPP_Primer_Plus_Book/Ch.04/Ch.04 - Exercise 05 - Struct/main.cpp
hpaucar/OOP-C-plus-plus-repo
e1fedd376029996a53d70d452b7738d9c43173c0
[ "MIT" ]
null
null
null
//******************************* // // C++ Template Program // //******************************* //******************************* // // Standard Header // //******************************* #include <cstdio> #include <cstdlib> #include <iostream> #include <string> using namespace std; //******************************** // // Function Declaration Section // //******************************** //******************************** // // Compound Type Declaration Section // //******************************** struct CandyBar { string name; float weight; int calories; }; //******************************** // // Main Program Section // //******************************** int main(int nNumberofArgs, char* pszArgs[]) { //* Variable Declaration CandyBar stSnack = {"Mocha Munch", 2.3, 359}; //* Main Code cout << "Name: " << stSnack.name << endl; cout << "Weight: " << stSnack.weight << endl; cout << "Calories: " << stSnack.calories << endl; //* Program End // - wait until user is ready before terminating program // - to allow the user to see the program results system("PAUSE"); return 0; } //******************************** // // Functions Begin Here // //********************************
16.931507
59
0.420712
hpaucar
d27d87335727fd36e542dbf7f30cf40b8906ad9f
166
cpp
C++
Tests/TestProjects/VS2010/C++/PreprocessorTest/App/main.cpp
veganaize/make-it-so
e1f8a0c6c372891dfda3a807e80f3797efdc4a99
[ "MIT" ]
null
null
null
Tests/TestProjects/VS2010/C++/PreprocessorTest/App/main.cpp
veganaize/make-it-so
e1f8a0c6c372891dfda3a807e80f3797efdc4a99
[ "MIT" ]
null
null
null
Tests/TestProjects/VS2010/C++/PreprocessorTest/App/main.cpp
veganaize/make-it-so
e1f8a0c6c372891dfda3a807e80f3797efdc4a99
[ "MIT" ]
null
null
null
#include <stdio.h> int main(int argc, char** argv) { #ifdef HELLO printf("Hello, "); #endif #ifdef WORLD printf("World!"); #endif return 0; }
11.857143
32
0.566265
veganaize
d27da382912347321c74faa00cd6f18fe88202cb
1,535
cpp
C++
source/Window/Window-NOTHREAD.cpp
hadryansalles/ray-tracing-from-the-ground-up
4ca02fca2cdd458767b4ab3df15b6cd20cb1f413
[ "MIT" ]
5
2021-09-24T12:22:08.000Z
2022-03-23T06:54:02.000Z
source/Window/Window-NOTHREAD.cpp
hadryans/ray-tracing-from-the-ground-up
4ca02fca2cdd458767b4ab3df15b6cd20cb1f413
[ "MIT" ]
null
null
null
source/Window/Window-NOTHREAD.cpp
hadryans/ray-tracing-from-the-ground-up
4ca02fca2cdd458767b4ab3df15b6cd20cb1f413
[ "MIT" ]
5
2021-08-14T22:26:11.000Z
2022-03-04T09:13:39.000Z
#include "Window-NOTHREAD.hpp" Window_NOTHREAD::Window_NOTHREAD(int width, int height): Window(width, height) { } Window_NOTHREAD::~Window_NOTHREAD(){ pixels.clear(); } void Window_NOTHREAD::init(){ window = SDL_CreateWindow("RTX", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, w, h,SDL_WINDOW_SHOWN); renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, w, h); running = true; clock_gettime(CLOCK_MONOTONIC, &start); } void Window_NOTHREAD::update(){ clock_gettime(CLOCK_MONOTONIC, &finish); elapsed = (finish.tv_sec - start.tv_sec); elapsed += (finish.tv_nsec - start.tv_nsec) / 1000000000.0; if(running && elapsed > 1.0f/60.0f){ clock_gettime(CLOCK_MONOTONIC, &start); while( SDL_PollEvent( &event ) ) { if( ( SDL_QUIT == event.type ) || ( SDL_KEYDOWN == event.type && SDL_SCANCODE_ESCAPE == event.key.keysym.scancode ) ) { SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_Quit(); running = false; return; } } SDL_SetRenderDrawColor(renderer, 0, 0, 0, SDL_ALPHA_OPAQUE); SDL_RenderClear(renderer); SDL_UpdateTexture(texture, NULL, &pixels[0], w*4); SDL_RenderCopy(renderer, texture, NULL, NULL); SDL_RenderPresent(renderer); } }
29.519231
99
0.628664
hadryansalles
d27ec49488abf5a728f5c969472c52354f951ed8
42,534
cpp
C++
arangod/Cluster/HeartbeatThread.cpp
Deckhandfirststar01/arangodb
a8c079252f9c7127ef6860f5ad46ec38055669ce
[ "BSL-1.0", "Zlib", "Apache-2.0" ]
null
null
null
arangod/Cluster/HeartbeatThread.cpp
Deckhandfirststar01/arangodb
a8c079252f9c7127ef6860f5ad46ec38055669ce
[ "BSL-1.0", "Zlib", "Apache-2.0" ]
null
null
null
arangod/Cluster/HeartbeatThread.cpp
Deckhandfirststar01/arangodb
a8c079252f9c7127ef6860f5ad46ec38055669ce
[ "BSL-1.0", "Zlib", "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Jan Steemann //////////////////////////////////////////////////////////////////////////////// #include "HeartbeatThread.h" #include <velocypack/Iterator.h> #include <velocypack/velocypack-aliases.h> #include "ApplicationFeatures/ApplicationServer.h" #include "Basics/ConditionLocker.h" #include "Basics/MutexLocker.h" #include "Basics/VelocyPackHelper.h" #include "Basics/tri-strings.h" #include "Cluster/ClusterComm.h" #include "Cluster/ClusterInfo.h" #include "Cluster/ClusterMethods.h" #include "Cluster/DBServerAgencySync.h" #include "Cluster/ServerState.h" #include "GeneralServer/AuthenticationFeature.h" #include "GeneralServer/RestHandlerFactory.h" #include "Logger/Logger.h" #include "Replication/GlobalInitialSyncer.h" #include "Replication/GlobalReplicationApplier.h" #include "Replication/ReplicationFeature.h" #include "RestServer/DatabaseFeature.h" #include "Scheduler/JobGuard.h" #include "Scheduler/Scheduler.h" #include "Scheduler/SchedulerFeature.h" #include "V8/v8-globals.h" #include "VocBase/AuthInfo.h" #include "VocBase/vocbase.h" #include "Pregel/PregelFeature.h" #include "Pregel/Recovery.h" using namespace arangodb; using namespace arangodb::application_features; using namespace arangodb::rest; std::atomic<bool> HeartbeatThread::HasRunOnce(false); //////////////////////////////////////////////////////////////////////////////// /// @brief constructs a heartbeat thread //////////////////////////////////////////////////////////////////////////////// HeartbeatThread::HeartbeatThread(AgencyCallbackRegistry* agencyCallbackRegistry, uint64_t interval, uint64_t maxFailsBeforeWarning) : Thread("Heartbeat"), _agencyCallbackRegistry(agencyCallbackRegistry), _statusLock(std::make_shared<Mutex>()), _agency(), _condition(), _myId(ServerState::instance()->getId()), _interval(interval), _maxFailsBeforeWarning(maxFailsBeforeWarning), _numFails(0), _lastSuccessfulVersion(0), _currentPlanVersion(0), _ready(false), _currentVersions(0, 0), _desiredVersions(std::make_shared<AgencyVersions>(0, 0)), _wasNotified(false), _backgroundJobsPosted(0), _backgroundJobsLaunched(0), _backgroundJobScheduledOrRunning(false), _launchAnotherBackgroundJob(false), _lastSyncTime(0) { } //////////////////////////////////////////////////////////////////////////////// /// @brief destroys a heartbeat thread //////////////////////////////////////////////////////////////////////////////// HeartbeatThread::~HeartbeatThread() { shutdown(); } //////////////////////////////////////////////////////////////////////////////// /// @brief running of heartbeat background jobs (in JavaScript), we run /// these by instantiating an object in class HeartbeatBackgroundJob, /// which is a std::function<void()> and holds a shared_ptr to the /// HeartbeatThread singleton itself. This instance is then posted to /// the io_service for execution in the thread pool. Should the heartbeat /// thread itself terminate during shutdown, then the HeartbeatThread /// singleton itself is still kept alive by the shared_ptr in the instance /// of HeartbeatBackgroundJob. The operator() method simply calls the /// runBackgroundJob() method of the heartbeat thread. Should this have /// to schedule another background job, then it can simply create a new /// HeartbeatBackgroundJob instance, again using shared_from_this() to /// create a new shared_ptr keeping the HeartbeatThread object alive. //////////////////////////////////////////////////////////////////////////////// class HeartbeatBackgroundJob { std::shared_ptr<HeartbeatThread> _heartbeatThread; double _startTime; std::string _schedulerInfo; public: explicit HeartbeatBackgroundJob(std::shared_ptr<HeartbeatThread> hbt, double startTime) : _heartbeatThread(hbt), _startTime(startTime),_schedulerInfo(SchedulerFeature::SCHEDULER->infoStatus()) { } void operator()() { // first tell the scheduler that this thread is working: JobGuard guard(SchedulerFeature::SCHEDULER); guard.work(); double now = TRI_microtime(); if (now > _startTime + 5.0) { LOG_TOPIC(ERR, Logger::HEARTBEAT) << "ALARM: Scheduling background job " "took " << now - _startTime << " seconds, scheduler info at schedule time: " << _schedulerInfo << ", scheduler info now: " << SchedulerFeature::SCHEDULER->infoStatus(); } _heartbeatThread->runBackgroundJob(); } }; //////////////////////////////////////////////////////////////////////////////// /// @brief method runBackgroundJob() //////////////////////////////////////////////////////////////////////////////// void HeartbeatThread::runBackgroundJob() { uint64_t jobNr = ++_backgroundJobsLaunched; LOG_TOPIC(DEBUG, Logger::HEARTBEAT) << "sync callback started " << jobNr; { DBServerAgencySync job(this); job.work(); } LOG_TOPIC(DEBUG, Logger::HEARTBEAT) << "sync callback ended " << jobNr; { MUTEX_LOCKER(mutexLocker, *_statusLock); TRI_ASSERT(_backgroundJobScheduledOrRunning); if (_launchAnotherBackgroundJob) { jobNr = ++_backgroundJobsPosted; LOG_TOPIC(DEBUG, Logger::HEARTBEAT) << "dispatching sync tail " << jobNr; _launchAnotherBackgroundJob = false; // the JobGuard is in the operator() of HeartbeatBackgroundJob SchedulerFeature::SCHEDULER->post(HeartbeatBackgroundJob(shared_from_this(), TRI_microtime())); } else { _backgroundJobScheduledOrRunning = false; _launchAnotherBackgroundJob = false; } } } //////////////////////////////////////////////////////////////////////////////// /// @brief heartbeat main loop /// the heartbeat thread constantly reports the current server status to the /// agency. it does so by sending the current state string to the key /// "Sync/ServerStates/" + my-id. /// after transferring the current state to the agency, the heartbeat thread /// will wait for changes on the "Sync/Commands/" + my-id key. If no changes /// occur, /// then the request it aborted and the heartbeat thread will go on with /// reporting its state to the agency again. If it notices a change when /// watching the command key, it will wake up and apply the change locally. //////////////////////////////////////////////////////////////////////////////// void HeartbeatThread::run() { ServerState::RoleEnum role = ServerState::instance()->getRole(); // mop: the heartbeat thread itself is now ready setReady(); // mop: however we need to wait for the rest server here to come up // otherwise we would already create collections and the coordinator would // think // ohhh the dbserver is online...pump some documents into it // which fails when it is still in maintenance mode if (!ServerState::instance()->isCoordinator(role)) { while (RestHandlerFactory::isMaintenance()) { if (isStopping()) { // startup aborted return; } usleep(100000); } } LOG_TOPIC(TRACE, Logger::HEARTBEAT) << "starting heartbeat thread (" << role << ")"; if (ServerState::instance()->isCoordinator(role)) { runCoordinator(); } else if (ServerState::instance()->isDBServer(role)) { runDBServer(); } else if (ServerState::instance()->isSingleServer(role)) { runSingleServer(); } else { LOG_TOPIC(ERR, Logger::FIXME) << "invalid role setup found when starting HeartbeatThread"; TRI_ASSERT(false); } LOG_TOPIC(TRACE, Logger::HEARTBEAT) << "stopped heartbeat thread (" << role << ")"; } //////////////////////////////////////////////////////////////////////////////// /// @brief heartbeat main loop, dbserver version //////////////////////////////////////////////////////////////////////////////// void HeartbeatThread::runDBServer() { // convert timeout to seconds double const interval = (double)_interval / 1000.0 / 1000.0; std::function<bool(VPackSlice const& result)> updatePlan = [=](VPackSlice const& result) { if (!result.isNumber()) { LOG_TOPIC(ERR, Logger::HEARTBEAT) << "Plan Version is not a number! " << result.toJson(); return false; } uint64_t version = result.getNumber<uint64_t>(); bool doSync = false; { MUTEX_LOCKER(mutexLocker, *_statusLock); if (version > _desiredVersions->plan) { _desiredVersions->plan = version; LOG_TOPIC(DEBUG, Logger::HEARTBEAT) << "Desired Current Version is now " << _desiredVersions->plan; doSync = true; } } if (doSync) { syncDBServerStatusQuo(); } return true; }; auto planAgencyCallback = std::make_shared<AgencyCallback>( _agency, "Plan/Version", updatePlan, true); bool registered = false; while (!registered) { registered = _agencyCallbackRegistry->registerCallback(planAgencyCallback); if (!registered) { LOG_TOPIC(ERR, Logger::HEARTBEAT) << "Couldn't register plan change in agency!"; sleep(1); } } // we check Current/Version every few heartbeats: int const currentCountStart = 1; // set to 1 by Max to speed up discovery int currentCount = currentCountStart; while (!isStopping()) { try { double const start = TRI_microtime(); // send our state to the agency. // we don't care if this fails sendState(); if (isStopping()) { break; } if (--currentCount == 0) { currentCount = currentCountStart; // send an initial GET request to Sync/Commands/my-id LOG_TOPIC(TRACE, Logger::HEARTBEAT) << "Looking at Sync/Commands/" + _myId; AgencyReadTransaction trx( std::vector<std::string>({ AgencyCommManager::path("Shutdown"), AgencyCommManager::path("Current/Version"), AgencyCommManager::path("Sync/Commands", _myId), "/.agency"})); AgencyCommResult result = _agency.sendTransactionWithFailover(trx, 1.0); if (!result.successful()) { LOG_TOPIC(WARN, Logger::HEARTBEAT) << "Heartbeat: Could not read from agency!"; } else { VPackSlice agentPool = result.slice()[0].get( std::vector<std::string>({".agency","pool"})); updateAgentPool(agentPool); VPackSlice shutdownSlice = result.slice()[0].get(std::vector<std::string>( {AgencyCommManager::path(), "Shutdown"})); if (shutdownSlice.isBool() && shutdownSlice.getBool()) { ApplicationServer::server->beginShutdown(); break; } LOG_TOPIC(TRACE, Logger::HEARTBEAT) << "Looking at Sync/Commands/" + _myId; handleStateChange(result); VPackSlice s = result.slice()[0].get(std::vector<std::string>( {AgencyCommManager::path(), std::string("Current"), std::string("Version")})); if (!s.isInteger()) { LOG_TOPIC(ERR, Logger::HEARTBEAT) << "Current/Version in agency is not an integer."; } else { uint64_t currentVersion = 0; try { currentVersion = s.getUInt(); } catch (...) { } if (currentVersion == 0) { LOG_TOPIC(ERR, Logger::HEARTBEAT) << "Current/Version in agency is 0."; } else { { MUTEX_LOCKER(mutexLocker, *_statusLock); if (currentVersion > _desiredVersions->current) { _desiredVersions->current = currentVersion; LOG_TOPIC(DEBUG, Logger::HEARTBEAT) << "Found greater Current/Version in agency."; } } syncDBServerStatusQuo(); } } } } if (isStopping()) { break; } double remain = interval - (TRI_microtime() - start); // mop: execute at least once do { if (isStopping()) { break; } LOG_TOPIC(TRACE, Logger::HEARTBEAT) << "Entering update loop"; bool wasNotified; { CONDITION_LOCKER(locker, _condition); wasNotified = _wasNotified; if (!wasNotified) { if (remain > 0.0) { locker.wait(static_cast<uint64_t>(remain * 1000000.0)); wasNotified = _wasNotified; } } _wasNotified = false; } if (!wasNotified) { LOG_TOPIC(DEBUG, Logger::HEARTBEAT) << "Lock reached timeout"; planAgencyCallback->refetchAndUpdate(true); } else { // mop: a plan change returned successfully... // recheck and redispatch in case our desired versions increased // in the meantime LOG_TOPIC(TRACE, Logger::HEARTBEAT) << "wasNotified==true"; syncDBServerStatusQuo(); } remain = interval - (TRI_microtime() - start); } while (remain > 0); } catch (std::exception const& e) { LOG_TOPIC(ERR, Logger::HEARTBEAT) << "Got an exception in DBServer heartbeat: " << e.what(); } catch (...) { LOG_TOPIC(ERR, Logger::HEARTBEAT) << "Got an unknown exception in DBServer heartbeat"; } } _agencyCallbackRegistry->unregisterCallback(planAgencyCallback); } /// CAS a key in the agency, works only if it does not exist, result should /// contain the value of the written key. static AgencyCommResult CasWithResult(AgencyComm agency, std::string const& key, VPackSlice const& json, double ttl, double timeout) { AgencyOperation write(key, AgencyValueOperationType::SET, json); write._ttl = static_cast<uint32_t>(ttl); // precondition the key must be empty AgencyPrecondition pre(key, AgencyPrecondition::Type::EMPTY, true); VPackBuilder preBuilder; pre.toVelocyPack(preBuilder); AgencyGeneralTransaction trx(write, pre); return agency.sendTransactionWithFailover(trx, timeout); } //////////////////////////////////////////////////////////////////////////////// /// @brief heartbeat main loop, single server version //////////////////////////////////////////////////////////////////////////////// void HeartbeatThread::runSingleServer() { // convert timeout to seconds double const interval = static_cast<double>(_interval) / 1000.0 / 1000.0; AuthenticationFeature* auth = AuthenticationFeature::INSTANCE; TRI_ASSERT(auth != nullptr); ReplicationFeature* replication = ReplicationFeature::INSTANCE; TRI_ASSERT(replication != nullptr); if (!replication->isAutomaticFailoverEnabled()) { LOG_TOPIC(WARN, Logger::HEARTBEAT) << "Automatic failover is disabled, yet " << "the heartbeat thread is running on a single server. " << "Please add --replication.automatic-failover true"; return; } GlobalReplicationApplier* applier = replication->globalReplicationApplier(); ClusterInfo* ci = ClusterInfo::instance(); TRI_ASSERT(applier != nullptr && ci != nullptr); double start = 0; // no wait time initially while (!isStopping()) { double remain = interval - (TRI_microtime() - start); // sleep for a while if appropriate, on some systems usleep does not // like arguments greater than 1000000 while (remain > 0.0) { if (remain >= 0.5) { usleep(500000); remain -= 0.5; } else { usleep(static_cast<TRI_usleep_t>(remain * 1000.0 * 1000.0)); remain = 0.0; } } start = TRI_microtime(); try { // send our state to the agency. // we don't care if this fails sendState(); if (isStopping()) { break; } AgencyReadTransaction trx( std::vector<std::string>({ AgencyCommManager::path("Shutdown"), AgencyCommManager::path("Plan/AsyncReplication"), AgencyCommManager::path("Sync/Commands", _myId), "/.agency"})); AgencyCommResult result = _agency.sendTransactionWithFailover(trx, 1.0); if (!result.successful()) { LOG_TOPIC(WARN, Logger::HEARTBEAT) << "Heartbeat: Could not read from agency!"; if (!applier->isRunning()) { //FIXME: allow to act as master, assume we are master } continue; } VPackSlice response = result.slice()[0]; VPackSlice agentPool = response.get(std::vector<std::string>{".agency", "pool"}); updateAgentPool(agentPool); VPackSlice shutdownSlice = response.get({AgencyCommManager::path(), "Shutdown"}); if (shutdownSlice.isBool() && shutdownSlice.getBool()) { ApplicationServer::server->beginShutdown(); break; } LOG_TOPIC(TRACE, Logger::HEARTBEAT) << "Looking at Sync/Commands/" << _myId; handleStateChange(result); // performing failover checks VPackSlice asyncReplication = response.get({AgencyCommManager::path(), "Plan", "AsyncReplication"}); if (!asyncReplication.isObject()) { LOG_TOPIC(WARN, Logger::HEARTBEAT) << "Heartbeat: Could not read async-repl metadata from agency!"; continue; } std::string const leaderPath = "/Plan/AsyncReplication/Leader"; VPackSlice leaderSlice = asyncReplication.get("Leader"); VPackBuilder myIdBuilder; myIdBuilder.add(VPackValue(_myId)); if (!leaderSlice.isString()) { // Case 1: No leader in agency. Race for leadership LOG_TOPIC(WARN, Logger::HEARTBEAT) << "Leadership vaccuum detected, " << "attempting a takeover"; // if we stay a slave, the redirect will be turned on again RestHandlerFactory::setServerMode(RestHandlerFactory::Mode::TRYAGAIN); result = CasWithResult(_agency, leaderPath, myIdBuilder.slice(), /* ttl */ std::min(30.0, interval * 4), /* timeout */ 30.0); if (result.successful()) { // sucessfull leadership takeover LOG_TOPIC(INFO, Logger::HEARTBEAT) << "All your base are belong to us"; if (applier->isRunning()) { applier->stopAndJoin(); } ServerState::instance()->setFoxxmaster(_myId); RestHandlerFactory::setServerMode(RestHandlerFactory::Mode::DEFAULT); continue; // nothing more to do here } else if (result.httpCode() == TRI_ERROR_HTTP_PRECONDITION_FAILED) { // we did not become leader, someone else is, response contains // current value in agency VPackSlice const res = result.slice(); TRI_ASSERT(res.length() == 1 && res[0].isObject()); leaderSlice = res[0].get(AgencyCommManager::slicePath(leaderPath)); TRI_ASSERT(leaderSlice.isString() && leaderSlice.compareString(_myId) != 0); LOG_TOPIC(INFO, Logger::HEARTBEAT) << "Did not become leader, " << "following " << leaderSlice.copyString(); // intentional fallthrough, we need to go to case 3 } else { LOG_TOPIC(WARN, Logger::HEARTBEAT) << "got an unexpected agency error " << "code: " << result.httpCode() << " msg: " << result.errorMessage(); continue; // try again next time } } // Case 2: Current server is leader if (leaderSlice.compareString(_myId) == 0) { LOG_TOPIC(TRACE, Logger::HEARTBEAT) << "Currently leader: " << _myId; // updating the value to keep our leadership result = _agency.casValue(leaderPath, /* old */ myIdBuilder.slice(), /* new */ myIdBuilder.slice(), /* ttl */ std::min(30.0, interval * 4), /* timeout */ 30.0); if (!result.successful()) { LOG_TOPIC(WARN, Logger::HEARTBEAT) << "Cannot update leadership value"; } if (applier->isRunning()) { applier->stopAndJoin(); } // ensure everyone has server access ServerState::instance()->setFoxxmaster(_myId); RestHandlerFactory::setServerMode(RestHandlerFactory::Mode::DEFAULT); continue; // nothing more to do } // Case 3: Current server is follower, should not get here otherwise std::string const leader = leaderSlice.copyString(); TRI_ASSERT(!leader.empty()); LOG_TOPIC(TRACE, Logger::HEARTBEAT) << "Following " << leader; ServerState::instance()->setFoxxmaster(leader); std::string endpoint = ci->getServerEndpoint(leader); if (endpoint.empty()) { LOG_TOPIC(ERR, Logger::HEARTBEAT) << "Failed to resolve leader endpoint"; continue; // try again next time } // enable redirections to leader RestHandlerFactory::setServerMode(RestHandlerFactory::Mode::REDIRECT); if (applier->endpoint() != endpoint) { // configure applier for new endpoint if (applier->isRunning()) { applier->stopAndJoin(); } ReplicationApplierConfiguration config = applier->configuration(); config._endpoint = endpoint; config._autoResync = true; config._autoResyncRetries = 3; if (config._jwt.empty()) { config._jwt = auth->jwtToken(); } // TODO: how do we initially configure the applier // start initial synchronization TRI_ASSERT(!config._skipCreateDrop); GlobalInitialSyncer syncer(config); // sync incrementally on failover to other follower, // but not initially Result r = syncer.run(false); if (r.fail()) { LOG_TOPIC(ERR, Logger::HEARTBEAT) << "Initial sync from leader " << "failed: " << r.errorMessage(); continue; // try again next time } // steal the barrier from the syncer TRI_voc_tick_t barrierId = syncer.stealBarrier(); TRI_voc_tick_t lastLogTick = syncer.getLastLogTick(); // forget about any existing replication applier configuration applier->forget(); applier->reconfigure(config); applier->start(lastLogTick, true, barrierId); } else if (!applier->isRunning()) { // try to restart the applier if (applier->hasState()) { Result error = applier->lastError(); if (error.is(TRI_ERROR_REPLICATION_APPLIER_STOPPED)) { LOG_TOPIC(WARN, Logger::HEARTBEAT) << "user stopped applier, please restart"; continue; } else if (error.isNot(TRI_ERROR_REPLICATION_NO_START_TICK) || error.isNot(TRI_ERROR_REPLICATION_START_TICK_NOT_PRESENT)) { // restart applier if possible LOG_TOPIC(WARN, Logger::HEARTBEAT) << "restarting stopped applier..."; applier->start(0, false, 0); continue; // check again next time } } // complete resync next round LOG_TOPIC(WARN, Logger::HEARTBEAT) << "forgetting previous applier state. Will trigger a full resync now"; applier->forget(); } } catch (std::exception const& e) { LOG_TOPIC(ERR, Logger::HEARTBEAT) << "got an exception in single server heartbeat: " << e.what(); } catch (...) { LOG_TOPIC(ERR, Logger::HEARTBEAT) << "got an unknown exception in single server heartbeat"; } } } //////////////////////////////////////////////////////////////////////////////// /// @brief heartbeat main loop, coordinator version //////////////////////////////////////////////////////////////////////////////// void HeartbeatThread::runCoordinator() { AuthenticationFeature* authentication = application_features::ApplicationServer::getFeature< AuthenticationFeature>("Authentication"); TRI_ASSERT(authentication != nullptr); uint64_t oldUserVersion = 0; // convert timeout to seconds double const interval = (double)_interval / 1000.0 / 1000.0; // invalidate coordinators every 2nd call bool invalidateCoordinators = true; // last value of plan which we have noticed: uint64_t lastPlanVersionNoticed = 0; // last value of current which we have noticed: uint64_t lastCurrentVersionNoticed = 0; while (!isStopping()) { try { double const start = TRI_microtime(); // send our state to the agency. // we don't care if this fails sendState(); if (isStopping()) { break; } AgencyReadTransaction trx (std::vector<std::string>( {AgencyCommManager::path("Current/Version"), AgencyCommManager::path("Current/Foxxmaster"), AgencyCommManager::path("Current/FoxxmasterQueueupdate"), AgencyCommManager::path("Plan/Version"), AgencyCommManager::path("Shutdown"), AgencyCommManager::path("Sync/Commands", _myId), AgencyCommManager::path("Sync/UserVersion"), AgencyCommManager::path("Target/FailedServers"), "/.agency"})); AgencyCommResult result = _agency.sendTransactionWithFailover(trx, 1.0); if (!result.successful()) { LOG_TOPIC(WARN, Logger::HEARTBEAT) << "Heartbeat: Could not read from agency!"; } else { VPackSlice agentPool = result.slice()[0].get( std::vector<std::string>({".agency","pool"})); updateAgentPool(agentPool); VPackSlice shutdownSlice = result.slice()[0].get( std::vector<std::string>({AgencyCommManager::path(), "Shutdown"})); if (shutdownSlice.isBool() && shutdownSlice.getBool()) { ApplicationServer::server->beginShutdown(); break; } LOG_TOPIC(TRACE, Logger::HEARTBEAT) << "Looking at Sync/Commands/" + _myId; handleStateChange(result); // mop: order is actually important here...FoxxmasterQueueupdate will // be set only when somebody registers some new queue stuff (for example // on a different coordinator than this one)... However when we are just // about to become the new foxxmaster we must immediately refresh our // queues this is done in ServerState...if queueupdate is set after // foxxmaster the change will be reset again VPackSlice foxxmasterQueueupdateSlice = result.slice()[0].get( std::vector<std::string>({AgencyCommManager::path(), "Current", "FoxxmasterQueueupdate"})); if (foxxmasterQueueupdateSlice.isBool()) { ServerState::instance()->setFoxxmasterQueueupdate( foxxmasterQueueupdateSlice.getBool()); } VPackSlice foxxmasterSlice = result.slice()[0].get(std::vector<std::string>( {AgencyCommManager::path(), "Current", "Foxxmaster"})); if (foxxmasterSlice.isString() && foxxmasterSlice.getStringLength() != 0) { ServerState::instance()->setFoxxmaster(foxxmasterSlice.copyString()); } else { auto state = ServerState::instance(); VPackBuilder myIdBuilder; myIdBuilder.add(VPackValue(state->getId())); auto updateMaster = _agency.casValue("/Current/Foxxmaster", foxxmasterSlice, myIdBuilder.slice(), 0, 1.0); if (updateMaster.successful()) { // We won the race we are the master ServerState::instance()->setFoxxmaster(state->getId()); } } VPackSlice versionSlice = result.slice()[0].get(std::vector<std::string>( {AgencyCommManager::path(), "Plan", "Version"})); if (versionSlice.isInteger()) { // there is a plan version uint64_t planVersion = 0; try { planVersion = versionSlice.getUInt(); } catch (...) { } if (planVersion > lastPlanVersionNoticed) { LOG_TOPIC(TRACE, Logger::HEARTBEAT) << "Found planVersion " << planVersion << " which is newer than " << lastPlanVersionNoticed; if (handlePlanChangeCoordinator(planVersion)) { lastPlanVersionNoticed = planVersion; } else { LOG_TOPIC(WARN, Logger::HEARTBEAT) << "handlePlanChangeCoordinator was unsuccessful"; } } } VPackSlice slice = result.slice()[0].get(std::vector<std::string>( {AgencyCommManager::path(), "Sync", "UserVersion"})); if (slice.isInteger()) { // there is a UserVersion uint64_t userVersion = 0; try { userVersion = slice.getUInt(); } catch (...) { } if (userVersion > 0 && userVersion != oldUserVersion) { oldUserVersion = userVersion; if (authentication->isActive()) { authentication->authInfo()->outdate(); } } } versionSlice = result.slice()[0].get(std::vector<std::string>( {AgencyCommManager::path(), "Current", "Version"})); if (versionSlice.isInteger()) { uint64_t currentVersion = 0; try { currentVersion = versionSlice.getUInt(); } catch (...) { } if (currentVersion > lastCurrentVersionNoticed) { LOG_TOPIC(TRACE, Logger::HEARTBEAT) << "Found currentVersion " << currentVersion << " which is newer than " << lastCurrentVersionNoticed; lastCurrentVersionNoticed = currentVersion; ClusterInfo::instance()->invalidateCurrent(); invalidateCoordinators = false; } } VPackSlice failedServersSlice = result.slice()[0].get(std::vector<std::string>( {AgencyCommManager::path(), "Target", "FailedServers"})); if (failedServersSlice.isObject()) { std::vector<std::string> failedServers = {}; for (auto const& server : VPackObjectIterator(failedServersSlice)) { if (server.value.isArray() && server.value.length() == 0) { failedServers.push_back(server.key.copyString()); } } // calling pregel code ClusterInfo::instance()->setFailedServers(failedServers); pregel::PregelFeature *prgl = pregel::PregelFeature::instance(); if (prgl != nullptr && failedServers.size() > 0) { pregel::RecoveryManager* mngr = prgl->recoveryManager(); if (mngr != nullptr) { try { mngr->updatedFailedServers(); } catch (std::exception const& e) { LOG_TOPIC(ERR, Logger::HEARTBEAT) << "Got an exception in coordinator heartbeat: " << e.what(); } } } } else { LOG_TOPIC(WARN, Logger::HEARTBEAT) << "FailedServers is not an object. ignoring for now"; } } // the foxx stuff needs an updated list of coordinators // and this is only updated when current version has changed if (invalidateCoordinators) { ClusterInfo::instance()->invalidateCurrentCoordinators(); } invalidateCoordinators = !invalidateCoordinators; double remain = interval - (TRI_microtime() - start); // sleep for a while if appropriate, on some systems usleep does not // like arguments greater than 1000000 while (remain > 0.0) { if (remain >= 0.5) { usleep(500000); remain -= 0.5; } else { usleep((TRI_usleep_t)(remain * 1000.0 * 1000.0)); remain = 0.0; } } } catch (std::exception const& e) { LOG_TOPIC(ERR, Logger::HEARTBEAT) << "Got an exception in coordinator heartbeat: " << e.what(); } catch (...) { LOG_TOPIC(ERR, Logger::HEARTBEAT) << "Got an unknown exception in coordinator heartbeat"; } } } //////////////////////////////////////////////////////////////////////////////// /// @brief initializes the heartbeat //////////////////////////////////////////////////////////////////////////////// bool HeartbeatThread::init() { // send the server state a first time and use this as an indicator about // the agency's health if (!sendState()) { return false; } return true; } //////////////////////////////////////////////////////////////////////////////// /// @brief finished plan change //////////////////////////////////////////////////////////////////////////////// void HeartbeatThread::dispatchedJobResult(DBServerAgencySyncResult result) { LOG_TOPIC(DEBUG, Logger::HEARTBEAT) << "Dispatched job returned!"; bool doSleep = false; { MUTEX_LOCKER(mutexLocker, *_statusLock); if (result.success) { LOG_TOPIC(DEBUG, Logger::HEARTBEAT) << "Sync request successful. Now have Plan " << result.planVersion << ", Current " << result.currentVersion; _currentVersions = AgencyVersions(result); } else { LOG_TOPIC(DEBUG, Logger::HEARTBEAT) << "Sync request failed!"; // mop: we will retry immediately so wait at least a LITTLE bit doSleep = true; } } if (doSleep) { // Sleep a little longer, since this might be due to some synchronisation // of shards going on in the background usleep(500000); usleep(500000); } CONDITION_LOCKER(guard, _condition); _wasNotified = true; _condition.signal(); } //////////////////////////////////////////////////////////////////////////////// /// @brief handles a plan version change, coordinator case /// this is triggered if the heartbeat thread finds a new plan version number //////////////////////////////////////////////////////////////////////////////// static std::string const prefixPlanChangeCoordinator = "Plan/Databases"; bool HeartbeatThread::handlePlanChangeCoordinator(uint64_t currentPlanVersion) { DatabaseFeature* databaseFeature = application_features::ApplicationServer::getFeature<DatabaseFeature>( "Database"); LOG_TOPIC(TRACE, Logger::HEARTBEAT) << "found a plan update"; AgencyCommResult result = _agency.getValues(prefixPlanChangeCoordinator); if (result.successful()) { std::vector<TRI_voc_tick_t> ids; velocypack::Slice databases = result.slice()[0].get(std::vector<std::string>( {AgencyCommManager::path(), "Plan", "Databases"})); if (!databases.isObject()) { return false; } // loop over all database names we got and create a local database // instance if not yet present: for (VPackObjectIterator::ObjectPair options : VPackObjectIterator(databases)) { if (!options.value.isObject()) { continue; } auto nameSlice = options.value.get("name"); if (nameSlice.isNone()) { LOG_TOPIC(ERR, Logger::HEARTBEAT) << "Missing name in agency database plan"; continue; } std::string const name = options.value.get("name").copyString(); TRI_voc_tick_t id = 0; if (options.value.hasKey("id")) { VPackSlice const v = options.value.get("id"); if (v.isString()) { try { id = std::stoul(v.copyString()); } catch (std::exception const& e) { LOG_TOPIC(ERR, Logger::HEARTBEAT) << "Failed to convert id string to number"; LOG_TOPIC(ERR, Logger::HEARTBEAT) << e.what(); } } } if (id > 0) { ids.push_back(id); } TRI_vocbase_t* vocbase = databaseFeature->useDatabaseCoordinator(name); if (vocbase == nullptr) { // database does not yet exist, create it now if (id == 0) { // verify that we have an id id = ClusterInfo::instance()->uniqid(); } // create a local database object... int res = databaseFeature->createDatabaseCoordinator(id, name, vocbase); if (res != TRI_ERROR_NO_ERROR) { LOG_TOPIC(ERR, arangodb::Logger::FIXME) << "creating local database '" << name << "' failed: " << TRI_errno_string(res); } else { HasRunOnce = true; } } else { vocbase->release(); } } // get the list of databases that we know about locally std::vector<TRI_voc_tick_t> localIds = databaseFeature->getDatabaseIdsCoordinator(false); for (auto id : localIds) { auto r = std::find(ids.begin(), ids.end(), id); if (r == ids.end()) { // local database not found in the plan... databaseFeature->dropDatabaseCoordinator(id, false); } } } else { return false; } // invalidate our local cache ClusterInfo::instance()->flush(); // turn on error logging now auto cc = ClusterComm::instance(); if (cc != nullptr && cc->enableConnectionErrorLogging(true)) { LOG_TOPIC(DEBUG, Logger::HEARTBEAT) << "created coordinator databases for the first time"; } return true; } //////////////////////////////////////////////////////////////////////////////// /// @brief handles a plan version change, DBServer case /// this is triggered if the heartbeat thread finds a new plan version number, /// and every few heartbeats if the Current/Version has changed. //////////////////////////////////////////////////////////////////////////////// void HeartbeatThread::syncDBServerStatusQuo() { bool shouldUpdate = false; bool becauseOfPlan = false; bool becauseOfCurrent = false; MUTEX_LOCKER(mutexLocker, *_statusLock); if (_desiredVersions->plan > _currentVersions.plan) { LOG_TOPIC(DEBUG, Logger::HEARTBEAT) << "Plan version " << _currentVersions.plan << " is lower than desired version " << _desiredVersions->plan; shouldUpdate = true; becauseOfPlan = true; } if (_desiredVersions->current > _currentVersions.current) { LOG_TOPIC(DEBUG, Logger::HEARTBEAT) << "Current version " << _currentVersions.current << " is lower than desired version " << _desiredVersions->current; shouldUpdate = true; becauseOfCurrent = true; } double now = TRI_microtime(); if (now > _lastSyncTime + 7.4) { shouldUpdate = true; } if (!shouldUpdate) { return; } // First invalidate the caches in ClusterInfo: auto ci = ClusterInfo::instance(); if (becauseOfPlan) { ci->invalidatePlan(); } if (becauseOfCurrent) { ci->invalidateCurrent(); } if (_backgroundJobScheduledOrRunning) { _launchAnotherBackgroundJob = true; return; } // schedule a job for the change: uint64_t jobNr = ++_backgroundJobsPosted; LOG_TOPIC(DEBUG, Logger::HEARTBEAT) << "dispatching sync " << jobNr; _backgroundJobScheduledOrRunning = true; // the JobGuard is in the operator() of HeartbeatBackgroundJob _lastSyncTime = TRI_microtime(); SchedulerFeature::SCHEDULER->post(HeartbeatBackgroundJob(shared_from_this(), _lastSyncTime)); } //////////////////////////////////////////////////////////////////////////////// /// @brief handles a state change /// this is triggered if the watch command reports a change /// when this is called, it will update the index value of the last command /// (we'll pass the updated index value to the next watches so we don't get /// notified about this particular change again). //////////////////////////////////////////////////////////////////////////////// bool HeartbeatThread::handleStateChange(AgencyCommResult& result) { VPackSlice const slice = result.slice()[0].get(std::vector<std::string>( {AgencyCommManager::path(), "Sync", "Commands", _myId})); if (slice.isString()) { std::string command = slice.copyString(); ServerState::StateEnum newState = ServerState::stringToState(command); if (newState != ServerState::STATE_UNDEFINED) { // state change. ServerState::instance()->setState(newState); return true; } } return false; } //////////////////////////////////////////////////////////////////////////////// /// @brief sends the current server's state to the agency //////////////////////////////////////////////////////////////////////////////// bool HeartbeatThread::sendState() { LOG_TOPIC(TRACE, Logger::HEARTBEAT) << "sending heartbeat to agency"; const AgencyCommResult result = _agency.sendServerState(0.0); // 8.0 * static_cast<double>(_interval) / 1000.0 / 1000.0); if (result.successful()) { _numFails = 0; return true; } if (++_numFails % _maxFailsBeforeWarning == 0) { std::string const endpoints = AgencyCommManager::MANAGER->endpointsString(); LOG_TOPIC(WARN, Logger::HEARTBEAT) << "heartbeat could not be sent to agency endpoints (" << endpoints << "): http code: " << result.httpCode() << ", body: " << result.body(); _numFails = 0; } return false; } void HeartbeatThread::updateAgentPool(VPackSlice const& agentPool) { if (agentPool.isObject() && agentPool.hasKey("size") && agentPool.get("size").getUInt() > 1) { _agency.updateEndpoints(agentPool); } else { LOG_TOPIC(TRACE, arangodb::Logger::FIXME) << "Cannot find an agency persisted in RAFT 8|"; } }
36.478559
114
0.585955
Deckhandfirststar01
d289229d760e61ac3f7cbffbf1b29e019bbdeeb5
2,819
cpp
C++
WebKit/Source/WebKit/qt/declarative/experimental/plugin.cpp
JavaScriptTesting/LJS
9818dbdb421036569fff93124ac2385d45d01c3a
[ "Apache-2.0" ]
1
2019-06-18T06:52:54.000Z
2019-06-18T06:52:54.000Z
WebKit/Source/WebKit/qt/declarative/experimental/plugin.cpp
JavaScriptTesting/LJS
9818dbdb421036569fff93124ac2385d45d01c3a
[ "Apache-2.0" ]
null
null
null
WebKit/Source/WebKit/qt/declarative/experimental/plugin.cpp
JavaScriptTesting/LJS
9818dbdb421036569fff93124ac2385d45d01c3a
[ "Apache-2.0" ]
null
null
null
/* Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "qquickwebpage_p.h" #include "qquickwebview_p.h" #include "qwebdownloaditem_p.h" #include "qwebviewportinfo_p.h" #include "qwebnavigationhistory_p.h" #include <QtDeclarative/qdeclarative.h> #include <QtDeclarative/qdeclarativeextensionplugin.h> QT_BEGIN_NAMESPACE class QQuickWebViewExperimentalExtension : public QObject { Q_OBJECT Q_PROPERTY(QQuickWebViewExperimental* experimental READ experimental CONSTANT FINAL) public: QQuickWebViewExperimentalExtension(QObject *parent = 0) : QObject(parent) { } QQuickWebViewExperimental* experimental() { return static_cast<QQuickWebView*>(parent())->experimental(); } }; class WebKitQmlExperimentalExtensionPlugin: public QDeclarativeExtensionPlugin { Q_OBJECT public: virtual void registerTypes(const char* uri) { Q_ASSERT(QLatin1String(uri) == QLatin1String("QtWebKit.experimental")); qmlRegisterUncreatableType<QWebDownloadItem>(uri, 3, 0, "DownloadItem", QObject::tr("Cannot create separate instance of DownloadItem")); qmlRegisterUncreatableType<QWebNavigationListModel>(uri, 3, 0, "NavigationListModel", QObject::tr("Cannot create separate instance of NavigationListModel")); qmlRegisterUncreatableType<QWebNavigationHistory>(uri, 3, 0, "NavigationHistory", QObject::tr("Cannot create separate instance of NavigationHistory")); qmlRegisterExtendedType<QQuickWebView, QQuickWebViewExperimentalExtension>(uri, 3, 0, "WebView"); qmlRegisterUncreatableType<QQuickWebViewExperimental>(uri, 3, 0, "WebViewExperimental", QObject::tr("Cannot create separate instance of WebViewExperimental")); qmlRegisterUncreatableType<QWebViewportInfo>(uri, 3, 0, "QWebViewportInfo", QObject::tr("Cannot create separate instance of QWebViewportInfo")); } }; QT_END_NAMESPACE #include "plugin.moc" Q_EXPORT_PLUGIN2(qmlwebkitpluginexperimental, QT_PREPEND_NAMESPACE(WebKitQmlExperimentalExtensionPlugin));
44.746032
165
0.766939
JavaScriptTesting
d28ac01b7d27882b602ea102e972bd4dd6f7c232
2,626
cpp
C++
OpenSees/SRC/reliability/analysis/telm/rancombi.cpp
kuanshi/ductile-fracture
ccb350564df54f5c5ec3a079100effe261b46650
[ "MIT" ]
null
null
null
OpenSees/SRC/reliability/analysis/telm/rancombi.cpp
kuanshi/ductile-fracture
ccb350564df54f5c5ec3a079100effe261b46650
[ "MIT" ]
null
null
null
OpenSees/SRC/reliability/analysis/telm/rancombi.cpp
kuanshi/ductile-fracture
ccb350564df54f5c5ec3a079100effe261b46650
[ "MIT" ]
1
2020-08-06T21:12:16.000Z
2020-08-06T21:12:16.000Z
/************************ RANCOMBI.CPP ****************** AgF 2001-10-18 * * * * This file defines a template class for combining two different * * random number generators. A combination of two random number * * generators is generally better than any of the two alone. * * The two generators should preferably be of very different design. * * * * Instructions: * * To make a combined random number generator, insert the class names * * of any two random number generators, as shown in the example below. * * * *************************************************************************/ // $Revision: 1.1 $ // $Date: 2008-02-29 19:43:54 $ // $Source: /usr/local/cvs/OpenSees/SRC/reliability/analysis/telm/rancombi.cpp,v $ #include <randomc.h> // This template class combines two different random number generators // for improved randomness. R1 and R2 are any two different random number // generator classes. template <class RG1, class RG2> class TRandomCombined : private RG1, private RG2 { public: TRandomCombined(int32 seed = 19) : RG1(seed), RG2(seed+1) {}; void RandomInit(int32 seed) { // re-seed RG1::RandomInit(seed); RG2::RandomInit(seed+1);} double Random() { long double r = RG1::Random() + RG2::Random(); if (r >= 1.) r -= 1.; return r;} long IRandom(long min, long max){ // output random integer // get integer random number in desired interval int iinterval = max - min + 1; if (iinterval <= 0) return -1; // error int i = int(iinterval * Random()); // truncate if (i >= iinterval) i = iinterval-1; return min + i;}}; ////////////////////////////////////////////////////////////////////////// /* Example showing how to use the combined random number generator: #include <stdio.h> #include <time.h> #include "randomc.h" #include "mersenne.cpp" #include "ranrotw.cpp" #include "rancombi.cpp" int main() { // Make an object of the template class. The names inside <> define the // class names of the two random number generators to combine. // Use time as seed. TRandomCombined<TRanrotWGenerator,TRandomMersenne> RG(time(0)); for (int i=0; i<20; i++) { // generate 20 random floating point numbers and 20 random integers printf("\n%14.10f %2i", RG.Random(), RG.IRandom(0,99));} return 0;} */
38.617647
82
0.54722
kuanshi
d28adf99ddc3e918658c5df1e127a050c3fff611
5,523
cpp
C++
cdn/src/v20180606/model/MaxAgeRule.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
43
2019-08-14T08:14:12.000Z
2022-03-30T12:35:09.000Z
cdn/src/v20180606/model/MaxAgeRule.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
12
2019-07-15T10:44:59.000Z
2021-11-02T12:35:00.000Z
cdn/src/v20180606/model/MaxAgeRule.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
28
2019-07-12T09:06:22.000Z
2022-03-30T08:04:18.000Z
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/cdn/v20180606/model/MaxAgeRule.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Cdn::V20180606::Model; using namespace std; MaxAgeRule::MaxAgeRule() : m_maxAgeTypeHasBeenSet(false), m_maxAgeContentsHasBeenSet(false), m_maxAgeTimeHasBeenSet(false), m_followOriginHasBeenSet(false) { } CoreInternalOutcome MaxAgeRule::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("MaxAgeType") && !value["MaxAgeType"].IsNull()) { if (!value["MaxAgeType"].IsString()) { return CoreInternalOutcome(Core::Error("response `MaxAgeRule.MaxAgeType` IsString=false incorrectly").SetRequestId(requestId)); } m_maxAgeType = string(value["MaxAgeType"].GetString()); m_maxAgeTypeHasBeenSet = true; } if (value.HasMember("MaxAgeContents") && !value["MaxAgeContents"].IsNull()) { if (!value["MaxAgeContents"].IsArray()) return CoreInternalOutcome(Core::Error("response `MaxAgeRule.MaxAgeContents` is not array type")); const rapidjson::Value &tmpValue = value["MaxAgeContents"]; for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr) { m_maxAgeContents.push_back((*itr).GetString()); } m_maxAgeContentsHasBeenSet = true; } if (value.HasMember("MaxAgeTime") && !value["MaxAgeTime"].IsNull()) { if (!value["MaxAgeTime"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `MaxAgeRule.MaxAgeTime` IsInt64=false incorrectly").SetRequestId(requestId)); } m_maxAgeTime = value["MaxAgeTime"].GetInt64(); m_maxAgeTimeHasBeenSet = true; } if (value.HasMember("FollowOrigin") && !value["FollowOrigin"].IsNull()) { if (!value["FollowOrigin"].IsString()) { return CoreInternalOutcome(Core::Error("response `MaxAgeRule.FollowOrigin` IsString=false incorrectly").SetRequestId(requestId)); } m_followOrigin = string(value["FollowOrigin"].GetString()); m_followOriginHasBeenSet = true; } return CoreInternalOutcome(true); } void MaxAgeRule::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_maxAgeTypeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "MaxAgeType"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_maxAgeType.c_str(), allocator).Move(), allocator); } if (m_maxAgeContentsHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "MaxAgeContents"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator); for (auto itr = m_maxAgeContents.begin(); itr != m_maxAgeContents.end(); ++itr) { value[key.c_str()].PushBack(rapidjson::Value().SetString((*itr).c_str(), allocator), allocator); } } if (m_maxAgeTimeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "MaxAgeTime"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_maxAgeTime, allocator); } if (m_followOriginHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "FollowOrigin"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_followOrigin.c_str(), allocator).Move(), allocator); } } string MaxAgeRule::GetMaxAgeType() const { return m_maxAgeType; } void MaxAgeRule::SetMaxAgeType(const string& _maxAgeType) { m_maxAgeType = _maxAgeType; m_maxAgeTypeHasBeenSet = true; } bool MaxAgeRule::MaxAgeTypeHasBeenSet() const { return m_maxAgeTypeHasBeenSet; } vector<string> MaxAgeRule::GetMaxAgeContents() const { return m_maxAgeContents; } void MaxAgeRule::SetMaxAgeContents(const vector<string>& _maxAgeContents) { m_maxAgeContents = _maxAgeContents; m_maxAgeContentsHasBeenSet = true; } bool MaxAgeRule::MaxAgeContentsHasBeenSet() const { return m_maxAgeContentsHasBeenSet; } int64_t MaxAgeRule::GetMaxAgeTime() const { return m_maxAgeTime; } void MaxAgeRule::SetMaxAgeTime(const int64_t& _maxAgeTime) { m_maxAgeTime = _maxAgeTime; m_maxAgeTimeHasBeenSet = true; } bool MaxAgeRule::MaxAgeTimeHasBeenSet() const { return m_maxAgeTimeHasBeenSet; } string MaxAgeRule::GetFollowOrigin() const { return m_followOrigin; } void MaxAgeRule::SetFollowOrigin(const string& _followOrigin) { m_followOrigin = _followOrigin; m_followOriginHasBeenSet = true; } bool MaxAgeRule::FollowOriginHasBeenSet() const { return m_followOriginHasBeenSet; }
29.068421
141
0.68948
suluner
d28b3547eb0e4d66d90ddbaf151154ec854349e9
364
cpp
C++
experimental/Pomdog.Experimental/Rendering/Commands/PrimitiveCommand.cpp
ValtoForks/pomdog
73798ae5f4a4c3b9b1e1e96239187c4b842c93b2
[ "MIT" ]
null
null
null
experimental/Pomdog.Experimental/Rendering/Commands/PrimitiveCommand.cpp
ValtoForks/pomdog
73798ae5f4a4c3b9b1e1e96239187c4b842c93b2
[ "MIT" ]
null
null
null
experimental/Pomdog.Experimental/Rendering/Commands/PrimitiveCommand.cpp
ValtoForks/pomdog
73798ae5f4a4c3b9b1e1e96239187c4b842c93b2
[ "MIT" ]
null
null
null
// Copyright (c) 2013-2018 mogemimi. Distributed under the MIT license. #include "PrimitiveCommand.hpp" #include <typeinfo> namespace Pomdog { namespace Rendering { std::type_index PrimitiveCommand::GetType() const noexcept { static const std::type_index index = typeid(PrimitiveCommand); return index; } } // namespace Rendering } // namespace Pomdog
21.411765
71
0.75
ValtoForks
d28e0ed0eec37b8be772216052d755a22ef7a7cc
362
cpp
C++
Series Patterns/seriespattern16.cpp
Starkl7/CPlusPlus-PatternHouse
cf53feac9857d0d87981909e0e8daeda26cb02f4
[ "MIT" ]
4
2021-09-21T03:43:26.000Z
2022-01-07T03:07:56.000Z
Series Patterns/seriespattern16.cpp
Starkl7/CPlusPlus-PatternHouse
cf53feac9857d0d87981909e0e8daeda26cb02f4
[ "MIT" ]
916
2021-09-01T15:40:24.000Z
2022-01-10T17:57:59.000Z
Series Patterns/seriespattern16.cpp
Starkl7/CPlusPlus-PatternHouse
cf53feac9857d0d87981909e0e8daeda26cb02f4
[ "MIT" ]
20
2021-09-30T18:13:58.000Z
2022-01-06T09:55:36.000Z
#include<iostream> using namespace std; int main() { long d,n,a1; float an; cout<<"Enter first term "; cin>>a1; cout<<"Enter difference "; cin>>d; cout<<"Enter number of terms"; cin>>n; cout<<"Harmonic progression : "; for(int y=1;y<=n;y++) { an=a1+(y-1)*d; cout<<"1/"<<an<<" "; } return 0; }
18.1
36
0.5
Starkl7
d28fa679fa7114dee2fa1eaf6219907dbacbf930
4,151
cpp
C++
SyP2.cpp
AnimaxNeil/Data-structure
dd7675907bd17325e4629c1529835f0a4452fdcd
[ "MIT" ]
null
null
null
SyP2.cpp
AnimaxNeil/Data-structure
dd7675907bd17325e4629c1529835f0a4452fdcd
[ "MIT" ]
null
null
null
SyP2.cpp
AnimaxNeil/Data-structure
dd7675907bd17325e4629c1529835f0a4452fdcd
[ "MIT" ]
null
null
null
// WAP using templates to sort a list of elements. Give user the option to perform sorting using Insertion sort, Bubble sort or Selection sort. #include <iostream> using namespace std; template <typename T> class List { T *arr; int capacity; void adjust_capacity() { if (size == capacity) { T *prev_arr = arr; capacity *= 2; arr = new T[capacity]; if (arr == NULL) { throw "out of memory"; } for (int i = 0; i < size; i++) { arr[i] = prev_arr[i]; } } } public: int size; List(int capacity = 1) { this->capacity = capacity; arr = new T[capacity]; size = 0; } void insert(T data) { adjust_capacity(); arr[size++] = data; } void ordered_insert(T data) { adjust_capacity(); int p = 0; while (p < size && arr[p] <= data) { p++; } for (int i = size - 1; i >= p; i--) { arr[i + 1] = arr[i]; } arr[p] = data; size++; } void remove(T data) { int p = 0; while (p < size && arr[p] != data) { p++; } if (p == size) { return; } for (int i = p; i < size - 1; i++) { arr[i] = arr[i + 1]; } size--; } void insertion_sort() { int j; T key; for (int i = 1; i < size; i++) { key = arr[i]; j = i - 1; while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = key; } } void bubble_sort() { bool sorted; T temp; for (int i = 0; i < size - 1; i++) { sorted = true; for (int j = 0; j < size - 1 - i; j++) { if (arr[j] > arr[j + 1]) { sorted = false; temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } if (sorted) { break; } } } void selection_sort() { int min_i; T temp; for (int i = 0; i < size - 1; i++) { min_i = i; for (int j = i + 1; j < size; j++) { if (arr[j] < arr[min_i]) { min_i = j; } } temp = arr[i]; arr[i] = arr[min_i]; arr[min_i] = temp; } } void display() { if (size == 0) { cout << "List is empty.\n"; } else { cout << "Displaying list :\n"; for (int i = 0; i < size; i++) { cout << arr[i] << ", "; } cout << "\n"; } } }; int main() { int size; cout << "Input size of list : "; cin >> size; List<int> int_list(size); int integer; cout << "Input list elements :-\n"; for (int i = 0; i < size; i++) { cin >> integer; int_list.insert(integer); } int_list.display(); int sort_choice; cout << "Possible sort types are :-\n1. Insertion\n2. Bubble\n3. Selection\nInput type of sort : "; cin >> sort_choice; switch (sort_choice) { case 1: int_list.insertion_sort(); break; case 2: int_list.bubble_sort(); break; case 3: int_list.selection_sort(); break; default: cout << "Invalid sort type.\n"; return 1; } cout << "List elements sorted. "; int_list.display(); return 0; }
21.396907
144
0.349313
AnimaxNeil
d293773d2f738dab2cb0533707f1492835adb06f
1,455
hpp
C++
client_essential/OpusEnc.hpp
zhang-ray/easy-voice-call
9393a75f89d2f75c9d18d886abd38ffa5d9c5138
[ "MIT" ]
33
2018-10-11T05:30:37.000Z
2022-02-10T12:51:47.000Z
client_essential/OpusEnc.hpp
zhang-ray/easy-voice-call
9393a75f89d2f75c9d18d886abd38ffa5d9c5138
[ "MIT" ]
16
2018-10-15T06:52:41.000Z
2020-11-06T02:53:21.000Z
client_essential/OpusEnc.hpp
zhang-ray/easy-voice-call
9393a75f89d2f75c9d18d886abd38ffa5d9c5138
[ "MIT" ]
2
2019-09-14T18:07:57.000Z
2020-04-29T09:38:02.000Z
#pragma once #include "AudioEncoder.hpp" #include "Singleton.hpp" #include <cstring> #include <set> #if defined(WIN32) || defined(ANDROID) #include <opus.h> #else #include <opus/opus.h> #endif #include "AudioCommon.hpp" #define MAX_PACKET_SIZE (3*1276) // libopus 1.2.1 // it seems like Opus' API is very easy to use. class OpusEnc final : public AudioEncoder, public Singleton<OpusEnc> { private: int err; OpusEncoder *encoder = nullptr; public: virtual ReturnType reInit() override { encoder = opus_encoder_create(sampleRate, 1, OPUS_APPLICATION_VOIP, &err); if (err<0) { return err; } // err = opus_encoder_ctl(encoder, OPUS_SET_BITRATE(64000)); // if (err < 0 ){ // return err; // } return 0; } virtual ReturnType encode(const std::vector<short> &pcmData, std::vector<char> &encodedData) override { unsigned char cbits[MAX_PACKET_SIZE]; /* Encode the frame. */ auto frame_size = pcmData.size(); auto nbBytes = opus_encode(encoder, pcmData.data(), frame_size, cbits, MAX_PACKET_SIZE); if (nbBytes<0) { fprintf(stderr, "%s:%d encode failed: %s\n", __FILE__, __LINE__, opus_strerror(nbBytes)); return EXIT_FAILURE; } encodedData.resize(nbBytes); memcpy(encodedData.data(), cbits, nbBytes); return 0; } virtual ~OpusEnc(){} };
25.526316
107
0.618557
zhang-ray
d293cc2934ff4a15a8f17a225ca290285e373a23
2,035
hpp
C++
utils/reset_mv_camera.hpp
gcusms/WolfVision
f802df73918b7dadafa41bbbe7381a1df79ef07e
[ "MIT" ]
24
2021-07-12T02:24:51.000Z
2022-03-25T19:59:15.000Z
utils/reset_mv_camera.hpp
gcusms/WolfVision
f802df73918b7dadafa41bbbe7381a1df79ef07e
[ "MIT" ]
16
2021-07-10T07:07:51.000Z
2021-12-06T11:36:07.000Z
utils/reset_mv_camera.hpp
gcusms/WolfVision
f802df73918b7dadafa41bbbe7381a1df79ef07e
[ "MIT" ]
38
2021-07-09T14:49:17.000Z
2022-03-27T09:40:59.000Z
#pragma once #include <algorithm> #include <stdexcept> #include <string> #include <vector> #include <fcntl.h> #include <linux/usbdevice_fs.h> #include <sys/ioctl.h> #include <unistd.h> #include <fmt/color.h> namespace utils { inline bool resetMVCamera() { static const auto identifier_green = fmt::format(fg(fmt::color::green) | fmt::emphasis::bold, "reset_mv_camera"); static const auto identifier_red = fmt::format(fg(fmt::color::red) | fmt::emphasis::bold, "reset_mv_camera"); static const std::vector<std::string> vendor_id{"f622", "080b"}; bool status{false}; fmt::print("[{}] Starting mindvision camera soft reset\n", identifier_green); for (const auto& _id : vendor_id) { std::string cmd{ "lsusb -d : | awk '{split($0, i, \":\"); split(i[1], j, \" \"); print(\"/dev/bus/usb/\"j[2]\"/\"j[4])}'"}; std::string result{""}; FILE* pipe = popen(cmd.insert(9, _id).c_str(), "r"); if (!pipe) { fmt::print("[{}] Error, cannot open shell buffer\n", identifier_red); } try { char buffer[128]; while (fgets(buffer, sizeof buffer, pipe) != NULL) { result += buffer; } } catch (...) { pclose(pipe); throw; } pclose(pipe); result.erase(std::remove(result.begin(), result.end(), '\n'), result.end()); if (!result.empty()) { fmt::print("[{}] Performing soft reset on device: {}\n", identifier_green, result); int fd{open(result.c_str(), O_WRONLY)}; if (fd < 0) { fmt::print("[{}] Error, fcntl cannot open device: {}\n", identifier_red, result); } int rc = ioctl(fd, USBDEVFS_RESET, 0); if (rc < 0) { fmt::print("[{}] Error, ioctl cannot reset device: {}\n", identifier_red, result); } else { close(fd); status = true; fmt::print("[{}] Reset device '{}' success\n", identifier_green, result); } } } if (!status) { fmt::print("[{}] Error, cannot apply soft reset\n", identifier_red); } return status; } } // namespace utils
31.307692
115
0.588206
gcusms
d296c22e2245559cb256b471fe1ce8c0b34acc23
1,669
cpp
C++
AK/Tests/TestURL.cpp
JamiKettunen/serenity
232da5cc188496f570ef55276a897f1095509c87
[ "BSD-2-Clause" ]
3
2020-05-01T02:39:03.000Z
2021-11-26T08:34:54.000Z
AK/Tests/TestURL.cpp
JamiKettunen/serenity
232da5cc188496f570ef55276a897f1095509c87
[ "BSD-2-Clause" ]
null
null
null
AK/Tests/TestURL.cpp
JamiKettunen/serenity
232da5cc188496f570ef55276a897f1095509c87
[ "BSD-2-Clause" ]
1
2021-06-02T18:02:51.000Z
2021-06-02T18:02:51.000Z
#include <AK/TestSuite.h> #include <AK/URL.h> TEST_CASE(construct) { EXPECT_EQ(URL().is_valid(), false); } TEST_CASE(basic) { { URL url("http://www.serenityos.org/index.html"); EXPECT_EQ(url.is_valid(), true); EXPECT_EQ(url.protocol(), "http"); EXPECT_EQ(url.port(), 80); EXPECT_EQ(url.path(), "/index.html"); } { URL url("https://localhost:1234/~anon/test/page.html"); EXPECT_EQ(url.is_valid(), true); EXPECT_EQ(url.protocol(), "https"); EXPECT_EQ(url.port(), 1234); EXPECT_EQ(url.path(), "/~anon/test/page.html"); } } TEST_CASE(some_bad_urls) { EXPECT_EQ(URL("http:serenityos.org").is_valid(), false); EXPECT_EQ(URL("http:/serenityos.org").is_valid(), false); EXPECT_EQ(URL("http//serenityos.org").is_valid(), false); EXPECT_EQ(URL("http:///serenityos.org").is_valid(), false); EXPECT_EQ(URL("serenityos.org").is_valid(), false); EXPECT_EQ(URL("://serenityos.org").is_valid(), false); EXPECT_EQ(URL("http://serenityos.org:80:80/").is_valid(), false); EXPECT_EQ(URL("http://serenityos.org:80:80").is_valid(), false); EXPECT_EQ(URL("http://serenityos.org:abc").is_valid(), false); EXPECT_EQ(URL("http://serenityos.org:abc:80").is_valid(), false); EXPECT_EQ(URL("http://serenityos.org:abc:80/").is_valid(), false); EXPECT_EQ(URL("http://serenityos.org:/abc/").is_valid(), false); } TEST_CASE(serialization) { EXPECT_EQ(URL("http://www.serenityos.org/").to_string(), "http://www.serenityos.org/"); EXPECT_EQ(URL("http://www.serenityos.org:81/").to_string(), "http://www.serenityos.org:81/"); } TEST_MAIN(URL)
32.72549
97
0.633913
JamiKettunen
d296e06a9d38b3cdb7a2091a22a2f9ece557d9cb
14,397
cpp
C++
src/slib/ui/select_view.cpp
emarc99/SLib
4e492d6c550f845fd1b3f40bf10183097eb0e53c
[ "MIT" ]
146
2017-03-21T07:50:43.000Z
2022-03-19T03:32:22.000Z
src/slib/ui/select_view.cpp
Crasader/SLib
4e492d6c550f845fd1b3f40bf10183097eb0e53c
[ "MIT" ]
50
2017-03-22T04:08:15.000Z
2019-10-21T16:55:48.000Z
src/slib/ui/select_view.cpp
Crasader/SLib
4e492d6c550f845fd1b3f40bf10183097eb0e53c
[ "MIT" ]
55
2017-03-21T07:52:58.000Z
2021-12-27T13:02:08.000Z
/* * Copyright (c) 2008-2019 SLIBIO <https://github.com/SLIBIO> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "slib/ui/select_view.h" #include "slib/ui/core.h" #include "slib/core/safe_static.h" #if defined(SLIB_UI_IS_MACOS) || defined(SLIB_UI_IS_IOS) || defined(SLIB_UI_IS_WIN32) || defined(SLIB_UI_IS_ANDROID) # define HAS_NATIVE_WIDGET_IMPL #endif namespace slib { namespace priv { namespace select_view { enum { ICON_NONE = 0, ICON_LEFT = 1, ICON_RIGHT = 2, ICON_DOWN = 3 }; class DefaultIcon : public Drawable { public: Ref<Brush> m_brush; Point m_pts[3]; public: DefaultIcon(int type) { m_brush = Brush::createSolidBrush(Color::Black); if (type == ICON_LEFT) { m_pts[0] = Point(0.67f, 0.24f); m_pts[1] = Point(0.33f, 0.51f); m_pts[2] = Point(0.67f, 0.78f); } else if (type == ICON_RIGHT) { m_pts[0] = Point(0.33f, 0.24f); m_pts[1] = Point(0.67f, 0.51f); m_pts[2] = Point(0.33f, 0.78f); } else if (type == ICON_DOWN) { m_pts[0] = Point(0.3f, 0.35f); m_pts[1] = Point(0.5f, 0.65f); m_pts[2] = Point(0.7f, 0.35f); } } public: sl_real getDrawableWidth() override { return 1; } sl_real getDrawableHeight() override { return 1; } void onDrawAll(Canvas* canvas, const Rectangle& rectDst, const DrawParam& param) override { if (m_brush.isNotNull()) { Point pts[3]; for (int i = 0; i < 3; i++) { pts[i].x = rectDst.left + rectDst.getWidth() * m_pts[i].x; pts[i].y = rectDst.top + rectDst.getHeight() * m_pts[i].y; } canvas->fillPolygon(pts, 3, m_brush); } } }; class DefaultResources { public: Ref<Drawable> leftIcon; Ref<Drawable> rightIcon; Ref<Drawable> downIcon; public: DefaultResources() { leftIcon = new DefaultIcon(ICON_LEFT); rightIcon = new DefaultIcon(ICON_RIGHT); downIcon = new DefaultIcon(ICON_DOWN); } }; SLIB_SAFE_STATIC_GETTER(DefaultResources, GetDefaultResources) } } using namespace priv::select_view; SLIB_DEFINE_OBJECT(SelectView, View) SelectView::SelectView() { #ifdef HAS_NATIVE_WIDGET_IMPL setCreatingNativeWidget(sl_true); #endif setUsingFont(sl_true); setBorder(sl_true, UIUpdateMode::Init); setBackgroundColor(Color::White, UIUpdateMode::Init); setSavingCanvasState(sl_false); #if !defined(SLIB_PLATFORM_IS_MOBILE) setFocusable(sl_true); #endif m_indexSelected = 0; m_iconSize.x = 0; m_iconSize.y = 0; m_gravity = Alignment::MiddleLeft; m_textColor = Color::Black; DefaultResources* def = GetDefaultResources(); if (def) { m_leftIcon = def->leftIcon; m_rightIcon = def->rightIcon; } m_clickedIconNo = ICON_NONE; } SelectView::~SelectView() { } sl_uint32 SelectView::getItemsCount() { return (sl_uint32)(m_titles.getCount()); } void SelectView::setItemsCount(sl_uint32 n, UIUpdateMode mode) { Ptr<ISelectViewInstance> instance = getSelectViewInstance(); if (instance.isNotNull()) { SLIB_VIEW_RUN_ON_UI_THREAD(&SelectView::setItemsCount, n, mode) } m_values.setCount(n); m_titles.setCount(n); if (instance.isNotNull()) { instance->refreshItemsCount(this); if (m_indexSelected >= n) { selectIndex(0, UIUpdateMode::None); } } else { if (m_indexSelected >= n) { selectIndex(0, UIUpdateMode::None); } invalidate(mode); } } void SelectView::removeAllItems(UIUpdateMode mode) { setItemsCount(0, mode); } String SelectView::getItemValue(sl_uint32 index) { return m_values.getValueAt(index); } void SelectView::setItemValue(sl_uint32 index, const String& value) { m_values.setAt(index, value); } List<String> SelectView::getValues() { return m_values; } void SelectView::setValues(const List<String>& list) { m_values = list; } String SelectView::getItemTitle(sl_uint32 index) { return m_titles.getValueAt(index); } void SelectView::setItemTitle(sl_uint32 index, const String& title, UIUpdateMode mode) { Ptr<ISelectViewInstance> instance = getSelectViewInstance(); if (instance.isNotNull()) { SLIB_VIEW_RUN_ON_UI_THREAD(&SelectView::setItemTitle, index, title, mode) } if (index < m_titles.getCount()) { m_titles.setAt(index, title); if (instance.isNotNull()) { instance->setItemTitle(this, index, title); } else { invalidate(mode); } } } List<String> SelectView::getTitles() { return m_titles; } void SelectView::setTitles(const List<String>& list, UIUpdateMode mode) { Ptr<ISelectViewInstance> instance = getSelectViewInstance(); if (instance.isNotNull()) { SLIB_VIEW_RUN_ON_UI_THREAD(&SelectView::setTitles, list, mode) m_titles = list; instance->refreshItemsContent(this); sl_uint32 n = (sl_uint32)(m_titles.getCount()); if (m_indexSelected >= n) { selectIndex(0, UIUpdateMode::None); } } else { m_titles = list; sl_uint32 n = (sl_uint32)(m_titles.getCount()); if (m_indexSelected >= n) { selectIndex(0, UIUpdateMode::None); } invalidate(mode); } } void SelectView::addItem(const String& value, const String& title, UIUpdateMode mode) { Ptr<ISelectViewInstance> instance = getSelectViewInstance(); if (instance.isNotNull()) { SLIB_VIEW_RUN_ON_UI_THREAD(&SelectView::addItem, value, title, mode) } sl_size n = m_values.getCount(); m_values.setCount(n + 1); m_titles.setCount(n + 1); m_values.setAt(n, value); m_titles.setAt(n, title); if (instance.isNotNull()) { instance->refreshItemsCount(this); if (m_indexSelected >= n) { selectIndex(0, UIUpdateMode::None); } } else { if (m_indexSelected >= n) { selectIndex(0, UIUpdateMode::None); } invalidate(mode); } } void SelectView::selectIndex(sl_uint32 index, UIUpdateMode mode) { Ptr<ISelectViewInstance> instance = getSelectViewInstance(); if (instance.isNotNull()) { SLIB_VIEW_RUN_ON_UI_THREAD(&SelectView::selectIndex, index, mode) } if (index < m_titles.getCount()) { m_indexSelected = index; if (instance.isNotNull()) { instance->select(this, index); } else { invalidate(mode); } } else { if (index == 0) { m_indexSelected = 0; } } } void SelectView::selectValue(const String& value, UIUpdateMode mode) { sl_int32 m = (sl_int32)(m_values.indexOf(value)); if (m > 0) { selectIndex(m, mode); } } sl_uint32 SelectView::getSelectedIndex() { return m_indexSelected; } String SelectView::getSelectedValue() { return m_values.getValueAt(m_indexSelected); } String SelectView::getSelectedTitle() { return m_titles.getValueAt(m_indexSelected); } const UISize& SelectView::getIconSize() { return m_iconSize; } void SelectView::setIconSize(const UISize& size, UIUpdateMode mode) { m_iconSize = size; invalidateLayoutOfWrappingControl(mode); } void SelectView::setIconSize(sl_ui_len width, sl_ui_len height, UIUpdateMode mode) { setIconSize(UISize(width, height), mode); } void SelectView::setIconSize(sl_ui_len size, UIUpdateMode mode) { setIconSize(UISize(size, size),mode); } sl_ui_len SelectView::getIconWidth() { return m_iconSize.x; } void SelectView::setIconWidth(sl_ui_len width, UIUpdateMode mode) { setIconSize(UISize(width, m_iconSize.y), mode); } sl_ui_len SelectView::getIconHeight() { return m_iconSize.y; } void SelectView::setIconHeight(sl_ui_len height, UIUpdateMode mode) { setIconSize(UISize(m_iconSize.x, height), mode); } Ref<Drawable> SelectView::getLeftIcon() { return m_leftIcon; } void SelectView::setLeftIcon(const Ref<Drawable>& icon, UIUpdateMode mode) { m_leftIcon = icon; invalidate(mode); } Ref<Drawable> SelectView::getRightIcon() { return m_rightIcon; } void SelectView::setRightIcon(const Ref<Drawable>& icon, UIUpdateMode mode) { m_rightIcon = icon; invalidate(mode); } Alignment SelectView::getGravity() { return m_gravity; } void SelectView::setGravity(const Alignment& gravity, UIUpdateMode mode) { Ptr<ISelectViewInstance> instance = getSelectViewInstance(); if (instance.isNotNull()) { SLIB_VIEW_RUN_ON_UI_THREAD(&SelectView::setGravity, gravity, mode) m_gravity = gravity; instance->setGravity(this, gravity); } else { m_gravity = gravity; invalidate(mode); } } Color SelectView::getTextColor() { return m_textColor; } void SelectView::setTextColor(const Color& color, UIUpdateMode mode) { Ptr<ISelectViewInstance> instance = getSelectViewInstance(); if (instance.isNotNull()) { SLIB_VIEW_RUN_ON_UI_THREAD(&SelectView::setTextColor, color, mode) m_textColor = color; instance->setTextColor(this, color); } else { m_textColor = color; invalidate(mode); } } void SelectView::onDraw(Canvas* canvas) { canvas->drawText(getSelectedTitle(), getBounds(), getFont(), m_textColor, Alignment::MiddleCenter); canvas->draw(getLeftIconRegion(), m_leftIcon); canvas->draw(getRightIconRegion(), m_rightIcon); } void SelectView::onMouseEvent(UIEvent* ev) { UIAction action = ev->getAction(); UIPoint pt = ev->getPoint(); if (action == UIAction::LeftButtonDown || action == UIAction::TouchBegin) { if (getLeftIconRegion().containsPoint(pt)) { m_clickedIconNo = ICON_LEFT; ev->stopPropagation(); } else if (getRightIconRegion().containsPoint(pt)) { m_clickedIconNo = ICON_RIGHT; ev->stopPropagation(); } } else if (action == UIAction::MouseLeave || action == UIAction::TouchCancel) { m_clickedIconNo = ICON_NONE; } else if (action == UIAction::LeftButtonUp || action == UIAction::TouchEnd) { if (m_clickedIconNo == ICON_LEFT) { if (getLeftIconRegion().containsPoint(pt)) { sl_uint32 index = m_indexSelected; if (index > 0) { index --; selectIndex(index); dispatchSelectItem(index); invalidate(); } } } else if (m_clickedIconNo == ICON_RIGHT) { if (getRightIconRegion().containsPoint(pt)) { sl_uint32 index = m_indexSelected; if (index + 1 < getItemsCount()) { index ++; selectIndex(index); dispatchSelectItem(index); invalidate(); } } } m_clickedIconNo = ICON_NONE; } } void SelectView::onUpdateLayout() { sl_bool flagHorizontal = isWidthWrapping(); sl_bool flagVertical = isHeightWrapping(); if (!flagVertical && !flagHorizontal) { return; } Ptr<ISelectViewInstance> instance = getSelectViewInstance(); if (instance.isNotNull()) { UISize size; if (instance->measureSize(this, size)) { if (flagHorizontal) { setLayoutWidth(size.x); } if (flagVertical) { setLayoutHeight(size.y); } return; } } Ref<Font> font = getFont(); if (flagHorizontal) { sl_ui_pos width = m_iconSize.x * 2 + getPaddingLeft() + getPaddingRight(); if (font.isNotNull()) { sl_ui_pos t = (sl_ui_pos)(font->getFontHeight()); if (t > 0) { width += t * 4; } } if (width < 0) { width = 0; } setLayoutWidth(width); } if (flagVertical) { sl_ui_pos height = 0; if (font.isNotNull()) { height = (sl_ui_pos)(font->getFontHeight() * 1.5f); if (height < 0) { height = 0; } } if (height < m_iconSize.y) { height = m_iconSize.y; } height += getPaddingTop() + getPaddingBottom(); if (height < 0) { height = 0; } setLayoutHeight(height); } } SLIB_DEFINE_EVENT_HANDLER(SelectView, SelectItem, sl_uint32 index) void SelectView::dispatchSelectItem(sl_uint32 index) { ObjectLocker lock(this); if (m_indexSelected == index) { return; } m_indexSelected = index; lock.unlock(); SLIB_INVOKE_EVENT_HANDLER(SelectItem, index) } UIRect SelectView::getLeftIconRegion() { sl_ui_pos heightView = getHeight(); sl_ui_pos h = heightView - getPaddingTop() - getPaddingBottom(); if (h < 0) { h = 0; } UIRect ret; ret.left = getPaddingLeft(); if (m_iconSize.x > 0) { ret.right = ret.left + m_iconSize.x; } else { ret.right = ret.left + h; } if (m_iconSize.y > 0) { h = m_iconSize.y; } ret.top = (heightView - h) / 2; ret.bottom = ret.top + h; ret.fixSizeError(); return ret; } UIRect SelectView::getRightIconRegion() { UISize sizeView = getSize(); sl_ui_pos h = sizeView.y - getPaddingTop() - getPaddingBottom(); if (h < 0) { h = 0; } UIRect ret; ret.right = sizeView.x - getPaddingRight(); if (m_iconSize.x > 0) { ret.left = ret.right - m_iconSize.x; } else { ret.left = ret.right - h; } if (m_iconSize.y > 0) { h = m_iconSize.y; } ret.top = (sizeView.y - h) / 2; ret.bottom = ret.top + h; ret.fixSizeError(); return ret; } #if !defined(HAS_NATIVE_WIDGET_IMPL) Ref<ViewInstance> SelectView::createNativeWidget(ViewInstance* parent) { return sl_null; } Ptr<ISelectViewInstance> SelectView::getSelectViewInstance() { return sl_null; } #endif void ISelectViewInstance::setGravity(SelectView* view, const Alignment& gravity) { } void ISelectViewInstance::setTextColor(SelectView* view, const Color& color) { } sl_bool ISelectViewInstance::measureSize(SelectView* view, UISize& _out) { return sl_false; } }
23.563011
116
0.669653
emarc99
d2982e07d7b4f94175a88cd15e3e008f6b74117d
1,259
cpp
C++
answers/hackerrank/other3.cpp
FeiZhan/Algo-Collection
708c4a38112e0b381864809788b9e44ac5ae4d05
[ "MIT" ]
3
2015-09-04T21:32:31.000Z
2020-12-06T00:37:32.000Z
answers/hackerrank/other3.cpp
FeiZhan/Algo-Collection
708c4a38112e0b381864809788b9e44ac5ae4d05
[ "MIT" ]
null
null
null
answers/hackerrank/other3.cpp
FeiZhan/Algo-Collection
708c4a38112e0b381864809788b9e44ac5ae4d05
[ "MIT" ]
null
null
null
#include <iostream> #include <cmath> #include <map> using namespace std; int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ long long quantile = 0; long long pair_num = 0; cin >> quantile >> pair_num; // a map with <value, count> map<long long, long long> num_map; for (long long i = 0; i < pair_num; ++ i) { long long value = 0; long long count = 0; cin >> value >> count; num_map[value] += count; } // convert to a map with <all count, value> map<long long, long long> count_map; long long all_count = 0; for (map<long long, long long>::iterator it = num_map.begin(); it != num_map.end(); ++ it) { // accumulate counts all_count += it->second; count_map.insert(make_pair(all_count, it->first)); } for (long long i = 1; i < quantile; ++ i) { long long ceiling = ceil(double(all_count) * i / quantile); // find the value with target count map<long long, long long>::iterator lower = count_map.lower_bound(ceiling); if (count_map.end() != lower) { cout << lower->second << endl; } } return 0; } // time complexity: O(N logN) // space complexity: O(N)
32.282051
96
0.583002
FeiZhan
d29992c0d04925508ac0b1c0b63726e35bf1a70e
440
cpp
C++
CppPrimer/CppPrimer-Exercises/CppPrimer-Ch02/Exercise2.27.cpp
alaxion/Learning
4b12b1603419252103cd933fdbfc4b2faffb6d00
[ "MIT" ]
null
null
null
CppPrimer/CppPrimer-Exercises/CppPrimer-Ch02/Exercise2.27.cpp
alaxion/Learning
4b12b1603419252103cd933fdbfc4b2faffb6d00
[ "MIT" ]
null
null
null
CppPrimer/CppPrimer-Exercises/CppPrimer-Ch02/Exercise2.27.cpp
alaxion/Learning
4b12b1603419252103cd933fdbfc4b2faffb6d00
[ "MIT" ]
null
null
null
// Exercise2.27.cpp // Ad // Which of the following are legal? #include <iostream> int main() { int i = -1, &r = 0; // cannot refer to 0 int i2{0}; int *const p2 = &i2; const int ii = -1, &rr = 0; const int *const p3 = &i2; const int *p1 = &i2; const int &const r2; // no const references and not initialized const int i3 = i, &r3 = i; // Pause std::cin.get(); return 0; }
20.952381
75
0.525
alaxion
d29d9a1cd915b0d7ac3a3b7a131942b318f774c6
1,737
cc
C++
hbase/src/model/DescribeRestoreSummaryRequest.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
hbase/src/model/DescribeRestoreSummaryRequest.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
hbase/src/model/DescribeRestoreSummaryRequest.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/hbase/model/DescribeRestoreSummaryRequest.h> using AlibabaCloud::HBase::Model::DescribeRestoreSummaryRequest; DescribeRestoreSummaryRequest::DescribeRestoreSummaryRequest() : RpcServiceRequest("hbase", "2019-01-01", "DescribeRestoreSummary") { setMethod(HttpRequest::Method::Post); } DescribeRestoreSummaryRequest::~DescribeRestoreSummaryRequest() {} std::string DescribeRestoreSummaryRequest::getClusterId()const { return clusterId_; } void DescribeRestoreSummaryRequest::setClusterId(const std::string& clusterId) { clusterId_ = clusterId; setParameter("ClusterId", clusterId); } int DescribeRestoreSummaryRequest::getPageNumber()const { return pageNumber_; } void DescribeRestoreSummaryRequest::setPageNumber(int pageNumber) { pageNumber_ = pageNumber; setParameter("PageNumber", std::to_string(pageNumber)); } int DescribeRestoreSummaryRequest::getPageSize()const { return pageSize_; } void DescribeRestoreSummaryRequest::setPageSize(int pageSize) { pageSize_ = pageSize; setParameter("PageSize", std::to_string(pageSize)); }
27.571429
79
0.765112
iamzken
d29e6460b20f51183576e79baec21c29ef6fc0ec
711
cpp
C++
Templates/Find kth root.cpp
Shefin-CSE16/Competitive-Programming
7c792081ae1d4b7060893165de34ffe7b9b7caed
[ "MIT" ]
5
2020-10-03T17:15:26.000Z
2022-03-29T21:39:22.000Z
Templates/Find kth root.cpp
Shefin-CSE16/Competitive-Programming
7c792081ae1d4b7060893165de34ffe7b9b7caed
[ "MIT" ]
null
null
null
Templates/Find kth root.cpp
Shefin-CSE16/Competitive-Programming
7c792081ae1d4b7060893165de34ffe7b9b7caed
[ "MIT" ]
1
2021-03-01T12:56:50.000Z
2021-03-01T12:56:50.000Z
#define ll long long vector <ll> graph[100009]; ll table[100009][20], sz[100009], MLOG, n; /// MLOG = log(n) + 1 void szdfs(ll u, ll p, ll lv) { sz[u] = 1; table[u][0] = p; for(ll i = 0; i < graph[u].size(); i++) { ll nd = graph[u][i]; if(nd == p) continue; szdfs(nd, u, lv + 1); sz[u] += sz[nd]; } } void build() { for(ll i = 1; i <= n; i++) { for(ll j = 1; j <= MLOG; j++) { table[i][j] = table[ table[i][j - 1] ][j - 1]; } } } ll kth(ll u, ll k) { for(ll i = MLOG; i >= 0; i--) { if( (1 << i) <= k) { u = table[u][i]; k -= (1 << i); } } return u; }
16.534884
66
0.372714
Shefin-CSE16
d2a0ae84c7af012949c0f5b7b038854344b8f659
520
hh
C++
2d/src/quad_march.hh
softwarecapital/chr1shr.voro
122531fbe162ea9a94b7e96ee9d57d3957c337ca
[ "BSD-3-Clause-LBNL" ]
43
2019-09-29T01:14:25.000Z
2022-03-02T23:48:25.000Z
2d/src/quad_march.hh
softwarecapital/chr1shr.voro
122531fbe162ea9a94b7e96ee9d57d3957c337ca
[ "BSD-3-Clause-LBNL" ]
15
2019-10-19T23:39:39.000Z
2021-12-30T22:03:51.000Z
2d/src/quad_march.hh
softwarecapital/chr1shr.voro
122531fbe162ea9a94b7e96ee9d57d3957c337ca
[ "BSD-3-Clause-LBNL" ]
23
2019-10-19T23:40:57.000Z
2022-03-29T16:53:17.000Z
#ifndef QUAD_MARCH_HH #define QUAD_MARCH_HH #include "ctr_quad_2d.hh" namespace voro { template<int ca> class quad_march { public: const int ma; int s; int ns; int p; quadtree* list[32]; quad_march(quadtree *q); void step(); inline quadtree* cu() { return list[p]; } private: inline quadtree* up(quadtree* q) { return ca<2?(ca==0?q->qne:q->qnw):(ca==2?q->qnw:q->qsw); } inline quadtree* down(quadtree* q) { return ca<2?(ca==0?q->qse:q->qsw):(ca==2?q->qne:q->qse); } }; } #endif
15.757576
59
0.619231
softwarecapital
d2a17d603c73c40b20150d0b9961a53d0ae01394
3,272
hpp
C++
src/ui/Widget.hpp
nopdotcom/opentxs
140428ba8f1bd4c09654ebf0a1c1725f396efa8b
[ "MIT" ]
null
null
null
src/ui/Widget.hpp
nopdotcom/opentxs
140428ba8f1bd4c09654ebf0a1c1725f396efa8b
[ "MIT" ]
null
null
null
src/ui/Widget.hpp
nopdotcom/opentxs
140428ba8f1bd4c09654ebf0a1c1725f396efa8b
[ "MIT" ]
null
null
null
// Copyright (c) 2018 The Open-Transactions developers // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #pragma once #include "Internal.hpp" #include "opentxs/network/zeromq/ListenCallback.hpp" #include "opentxs/network/zeromq/RequestSocket.hpp" #include "opentxs/network/zeromq/SubscribeSocket.hpp" #include "opentxs/ui/Widget.hpp" namespace opentxs::ui::implementation { template <typename T> T extract_custom(const CustomData& custom, const std::size_t index = 0) { OT_ASSERT((index + 1) <= custom.size()) std::unique_ptr<const T> output{static_cast<const T*>(custom.at(index))}; OT_ASSERT(output) return *output; } class Widget : virtual public opentxs::ui::Widget { public: class MessageFunctor { public: virtual void operator()(Widget* object, const network::zeromq::Message&) const = 0; protected: MessageFunctor() = default; private: MessageFunctor(const MessageFunctor&) = delete; MessageFunctor(MessageFunctor&&) = delete; MessageFunctor& operator=(const MessageFunctor&) = delete; MessageFunctor& operator=(MessageFunctor&&) = delete; }; template <typename T> class MessageProcessor : virtual public MessageFunctor { public: typedef void (T::*Function)(const network::zeromq::Message&); void operator()(Widget* object, const network::zeromq::Message& message) const override { auto real = dynamic_cast<T*>(object); OT_ASSERT(nullptr != real) (real->*callback_)(message); } MessageProcessor(Function callback) : callback_(callback) { } MessageProcessor(MessageProcessor&&) = default; MessageProcessor& operator=(MessageProcessor&&) = default; private: Function callback_; MessageProcessor() = delete; MessageProcessor(const MessageProcessor&) = delete; MessageProcessor& operator=(const MessageProcessor&) = delete; }; OTIdentifier WidgetID() const override; virtual ~Widget() = default; protected: using ListenerDefinition = std::pair<std::string, MessageFunctor*>; using ListenerDefinitions = std::vector<ListenerDefinition>; const api::client::Manager& api_; const network::zeromq::PublishSocket& publisher_; const OTIdentifier widget_id_; void setup_listeners(const ListenerDefinitions& definitions); void UpdateNotify() const; Widget( const api::client::Manager& api, const network::zeromq::PublishSocket& publisher, const Identifier& id); Widget( const api::client::Manager& api, const network::zeromq::PublishSocket& publisher); private: std::vector<OTZMQListenCallback> callbacks_; std::vector<OTZMQSubscribeSocket> listeners_; Widget() = delete; Widget(const Widget&) = delete; Widget(Widget&&) = delete; Widget& operator=(const Widget&) = delete; Widget& operator=(Widget&&) = delete; }; // namespace opentxs::ui::implementation } // namespace opentxs::ui::implementation
28.955752
80
0.669927
nopdotcom
d2a2237addccd3dc3fb3f7540c6a37a0de865bb8
258
cpp
C++
exodus/libexodus/exodus/howto.cpp
BOBBYWY/exodusdb
cfe8a3452480af90071dd10cefeed58299eed4e7
[ "MIT" ]
4
2021-01-23T14:36:34.000Z
2021-06-07T10:02:28.000Z
exodus/libexodus/exodus/howto.cpp
BOBBYWY/exodusdb
cfe8a3452480af90071dd10cefeed58299eed4e7
[ "MIT" ]
1
2019-08-04T19:15:56.000Z
2019-08-04T19:15:56.000Z
exodus/libexodus/exodus/howto.cpp
BOBBYWY/exodusdb
cfe8a3452480af90071dd10cefeed58299eed4e7
[ "MIT" ]
1
2022-01-29T22:41:01.000Z
2022-01-29T22:41:01.000Z
#if defined(__CINT__) /* CINT*/ #elif defined(__BORLANDC__) /* ...Borland...*/ #elif defined(__WATCOMC__) /* ...Watcom C/C++...*/ #elif defined(_MSC_VER) /* ...Microsoft C/Visual C+++*/ #elif defined(__CYGWIN__) /* ...cygwin... */ #else /* ...... */ #endif
17.2
31
0.593023
BOBBYWY
d2a478b068e5ecbd5a9328127c98332ddf668aca
2,896
hpp
C++
doc/mainpage.hpp
graphnode/CSFML-Merge
096ae4bfce91a687a999ac4e89617da3b973f90b
[ "Zlib" ]
257
2015-04-30T07:51:40.000Z
2022-03-28T07:59:07.000Z
doc/mainpage.hpp
graphnode/CSFML-Merge
096ae4bfce91a687a999ac4e89617da3b973f90b
[ "Zlib" ]
76
2015-04-30T23:20:53.000Z
2022-03-17T07:58:16.000Z
doc/mainpage.hpp
graphnode/CSFML-Merge
096ae4bfce91a687a999ac4e89617da3b973f90b
[ "Zlib" ]
144
2015-04-30T18:34:50.000Z
2022-03-28T01:28:40.000Z
//////////////////////////////////////////////////////////// /// \mainpage /// /// \section welcome Welcome /// Welcome to the official SFML documentation for C. Here you will find a detailed /// view of all the SFML <a href="./globals_func.htm">functions</a>.<br/> /// If you are looking for tutorials, you can visit the official website /// at <a href="http://www.sfml-dev.org/">www.sfml-dev.org</a>. /// /// \section example Short example /// Here is a short example, to show you how simple it is to use SFML in C : /// /// \code /// /// #include <SFML/Audio.h> /// #include <SFML/Graphics.h> /// /// int main() /// { /// sfVideoMode mode = {800, 600, 32}; /// sfRenderWindow* window; /// sfTexture* texture; /// sfSprite* sprite; /// sfFont* font; /// sfText* text; /// sfMusic* music; /// sfEvent event; /// /// /* Create the main window */ /// window = sfRenderWindow_create(mode, "SFML window", sfResize | sfClose, NULL); /// if (!window) /// return EXIT_FAILURE; /// /// /* Load a sprite to display */ /// texture = sfTexture_createFromFile("cute_image.jpg", NULL); /// if (!texture) /// return EXIT_FAILURE; /// sprite = sfSprite_create(); /// sfSprite_setTexture(sprite, texture, sfTrue); /// /// /* Create a graphical text to display */ /// font = sfFont_createFromFile("arial.ttf"); /// if (!font) /// return EXIT_FAILURE; /// text = sfText_create(); /// sfText_setString(text, "Hello SFML"); /// sfText_setFont(text, font); /// sfText_setCharacterSize(text, 50); /// /// /* Load a music to play */ /// music = sfMusic_createFromFile("nice_music.ogg"); /// if (!music) /// return EXIT_FAILURE; /// /// /* Play the music */ /// sfMusic_play(music); /// /// /* Start the game loop */ /// while (sfRenderWindow_isOpen(window)) /// { /// /* Process events */ /// while (sfRenderWindow_pollEvent(window, &event)) /// { /// /* Close window : exit */ /// if (event.type == sfEvtClosed) /// sfRenderWindow_close(window); /// } /// /// /* Clear the screen */ /// sfRenderWindow_clear(window, sfBlack); /// /// /* Draw the sprite */ /// sfRenderWindow_drawSprite(window, sprite, NULL); /// /// /* Draw the text */ /// sfRenderWindow_drawText(window, text, NULL); /// /// /* Update the window */ /// sfRenderWindow_display(window); /// } /// /// /* Cleanup resources */ /// sfMusic_destroy(music); /// sfText_destroy(text); /// sfFont_destroy(font); /// sfSprite_destroy(sprite); /// sfTexture_destroy(texture); /// sfRenderWindow_destroy(window); /// /// return EXIT_SUCCESS; /// } /// \endcode ////////////////////////////////////////////////////////////
30.808511
86
0.538329
graphnode
d2a5b1c85cc6414396454dd1b4efd88feb1fa317
6,403
cpp
C++
lib/libCFG/src/CapPattern.cpp
cyber-itl/citl-static-analysis
32ef8e519dac1c6a49ff41d902a62df8f5a8e948
[ "MIT" ]
14
2021-05-03T16:03:22.000Z
2022-02-14T23:42:39.000Z
lib/libCFG/src/CapPattern.cpp
cyber-itl/citl-static-analysis
32ef8e519dac1c6a49ff41d902a62df8f5a8e948
[ "MIT" ]
1
2021-09-27T12:01:33.000Z
2021-09-27T12:01:33.000Z
lib/libCFG/src/CapPattern.cpp
cyber-itl/citl-static-analysis
32ef8e519dac1c6a49ff41d902a62df8f5a8e948
[ "MIT" ]
null
null
null
#include <cstdint> #include <vector> #include <algorithm> #include <utility> #include "capstone/capstone.h" #include "glog/logging.h" #include "CapPattern.hpp" OperPat::OperPat(op_type op_type) : reg(0), type(op_type) {}; OperPat::OperPat(op_type op_type, uint64_t reg) : reg(reg), type(op_type) {}; OperPat::OperPat(op_type op_type, const std::vector<uint32_t> &regs) : reg(0), type(op_type), regs{regs} {}; InsnPattern::InsnPattern(uint32_t id) : m_id(id), m_op_count(0) {}; InsnPattern::InsnPattern(uint32_t id, const std::vector<OperPat> &opers) : m_id(id), m_op_count(opers.size()), m_opers(opers) {}; Pattern::Pattern(const std::vector<InsnPattern> &pattern) : type(pat_type::ORDERED), insn_patterns(pattern) {}; Pattern::Pattern(pat_type type, const std::vector<InsnPattern> &pattern) : type(type), insn_patterns(pattern) {}; CapPattern::CapPattern(cs_insn *insns, uint64_t count, cs_arch arch, cs_mode mode) : m_insns(insns), m_count(count), m_arch(arch), m_mode(mode) {}; bool CapPattern::check_pattern(const Pattern &pattern) { if (m_count < pattern.insn_patterns.size()) { return false; } bool unordered_match = false; std::vector<bool> matched_idxs; if (pattern.type == pat_type::UNORDERED) { unordered_match = true; matched_idxs.resize(pattern.insn_patterns.size(), false); } for (uint64_t idx = 0; idx < m_count; idx++) { cs_insn insn = m_insns[idx]; if (idx >= pattern.insn_patterns.size()) { break; } if (unordered_match) { bool match_any = false; uint64_t pat_idx = 0; for (const auto &cur_pat : pattern.insn_patterns) { // Skip things we already matched. if (matched_idxs.at(pat_idx)) { pat_idx++; continue; } if (this->check_insn(insn, cur_pat)) { match_any = true; matched_idxs.at(pat_idx) = true; break; } pat_idx++; } if (!match_any) { return false; } } else { InsnPattern cur_pat = pattern.insn_patterns.at(idx); if (!this->check_insn(insn, cur_pat)) { return false; } } } m_reg_placeholders.clear(); return true; } bool CapPattern::check_insn(cs_insn insn, const InsnPattern &pat) { if (pat.m_id != insn.id) { return false; } if (pat.m_op_count != 0) { bool valid_ops = false; if (m_arch == cs_arch::CS_ARCH_X86) { valid_ops = this->check_x86_ops(insn, pat); } else if (m_arch == cs_arch::CS_ARCH_ARM) { } else if (m_arch == cs_arch::CS_ARCH_ARM64) { } else { } if (!valid_ops) { return false; } } return true; } bool CapPattern::check_x86_ops(cs_insn insn, const InsnPattern &pat) { cs_x86 detail = insn.detail->x86; if (detail.op_count < pat.m_op_count) { return false; } for(uint8_t idx = 0; idx < detail.op_count; idx++) { cs_x86_op op = detail.operands[idx]; if (idx >= pat.m_op_count) { break; } OperPat op_pat = pat.m_opers.at(idx); switch (op_pat.type) { case op_type::WILDCARD: continue; break; case op_type::REG: if (op.type != X86_OP_REG) { return false; } // Allow * reg value's if (op_pat.reg != X86_REG_INVALID) { if (op_pat.reg != op.reg) { return false; } } else { // Check for a list of optional regs if (op_pat.regs.size()) { if (std::find(op_pat.regs.cbegin(), op_pat.regs.cend(), op.reg) == op_pat.regs.cend()) { return false; } } } break; case op_type::SEG: if (op.type != X86_OP_MEM) { return false; } if (op_pat.reg != op.mem.segment) { return false; } break; case op_type::MEM: if (op.type != X86_OP_MEM) { return false; } // Allow empty mem type without a reg. if (op_pat.reg != X86_REG_INVALID) { if (op.mem.base != op_pat.reg) { return false; } } else { // Check for a list of optional regs if (op_pat.regs.size()) { if (std::find(op_pat.regs.cbegin(), op_pat.regs.cend(), op.mem.base) == op_pat.regs.cend()) { return false; } } } break; case op_type::IMM: if (op.type != X86_OP_IMM) { return false; } break; case op_type::REG_PLACEHOLDER: { if (op.type != X86_OP_REG && op.type != X86_OP_MEM) { return false; } uint64_t reg_id = 0; if (op.type == X86_OP_REG) { reg_id = op.reg; } else if (op.type == X86_OP_MEM) { reg_id = op.mem.base; } else { LOG(FATAL) << "Invalid operand type for REG_PLACEHOLDER"; } auto reg_id_kv = m_reg_placeholders.find(op_pat.reg); // if we don't have it in the place holders map, store the first seen value. if (reg_id_kv == m_reg_placeholders.end()) { m_reg_placeholders.emplace(op_pat.reg, reg_id); } else { // Grab from the cache, verify that the current reg value is the same. if (reg_id != reg_id_kv->second) { return false; } } break; } default: LOG(FATAL) << "Invalid operand type: " << static_cast<uint32_t>(op_pat.type); break; } } return true; }
26.568465
113
0.487896
cyber-itl
d2ac808e273e575f526c2af92b34a4dddeda5eca
506
cpp
C++
SDLProjekt/Animator.cpp
TheKrzyko/SokobanSDL
dfc6e5cefcc84d069fcaad6908e9a1ba44444d29
[ "MIT" ]
null
null
null
SDLProjekt/Animator.cpp
TheKrzyko/SokobanSDL
dfc6e5cefcc84d069fcaad6908e9a1ba44444d29
[ "MIT" ]
null
null
null
SDLProjekt/Animator.cpp
TheKrzyko/SokobanSDL
dfc6e5cefcc84d069fcaad6908e9a1ba44444d29
[ "MIT" ]
null
null
null
#include "Animator.h" #include <string.h> Animator::Animator() { } Animator::~Animator() { } void Animator::addState(String name, const FrameAnimation& anim) { animations[name] = new FrameAnimation(anim); } void Animator::setState(String name) { if (currentState == name) return; if(currentState != String("")) animations[currentState]->stop(); currentState = name; animations[currentState]->play(); } Frame Animator::getCurrentFrame() { return animations[currentState]->getCurrentFrame(); }
16.866667
64
0.717391
TheKrzyko
d2ad385eb241038abe711399b0fe8b436e6b1bdf
13,775
cpp
C++
test/test_trial1.cpp
DaziyahS/ExperimentsSP22
22c8abef235a050aa6985cdad1e4db65ef86ea12
[ "MIT" ]
null
null
null
test/test_trial1.cpp
DaziyahS/ExperimentsSP22
22c8abef235a050aa6985cdad1e4db65ef86ea12
[ "MIT" ]
null
null
null
test/test_trial1.cpp
DaziyahS/ExperimentsSP22
22c8abef235a050aa6985cdad1e4db65ef86ea12
[ "MIT" ]
null
null
null
#include <Mahi/Gui.hpp> #include <Mahi/Util.hpp> #include <Mahi/Util/Logging/Log.hpp> #include <syntacts> #include <random> #include <iostream> #include <fstream> // need to include inorder to save to csv #include <chrono> #include <string> // for manipulating file name // local includes #include <Chord.hpp> #include <Note.hpp> // open the namespaces that are relevant for this code using namespace mahi::gui; using namespace mahi::util; using tact::Signal; using tact::sleep; using tact::Sequence; // deteremine application variables int windowWidth = 1920; // 1920 x 1080 is screen dimensions int windowHeight = 1080; std::string my_title= "Play GUI"; ImVec2 buttonSizeBegin = ImVec2(800, 65); // Size of buttons on begin & transition screen ImVec2 buttonSizeTrial = ImVec2(400, 65); // Size of buttons on trial scean ImVec2 buttonSizeSAMs = ImVec2(150, 150); // Size of SAMs buttons int deviceNdx = 5; // tactors of interest int topTact = 4; int botTact = 6; int leftTact = 0; int rightTact = 2; // how to save to an excel document std::string saveSubject; // experiment details, allows me to customize std::ofstream file_name; // this holds the trial information class MyGui : public Application { // Start by declaring the session variable tact::Session s; // this ensures the whole app knows this session private: // Loading in of images bool loadTextureFromFile( const char *filename, GLuint *out_texture, int *out_width, int *out_height) { // Load from file int image_width = 0; int image_height = 0; unsigned char *image_data = stbi_load(filename, &image_width, &image_height, NULL, 4); if (image_data == NULL) return false; // Create a OpenGL texture identifier GLuint image_texture; glGenTextures(1, &image_texture); glBindTexture(GL_TEXTURE_2D, image_texture); // Setup filtering parameters for display glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); // This is required on WebGL for non power-of-two textures glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); // Same // Upload pixels into texture #if defined(GL_UNPACK_ROW_LENGTH) && !defined(__EMSCRIPTEN__) glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); #endif glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image_width, image_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image_data); stbi_image_free(image_data); *out_texture = image_texture; *out_width = image_width; *out_height = image_height; return true; } // simple wrapper to simplify importing images bool loadIcon(const char *imgPath, GLuint *my_image_texture) { int my_image_width = 0; int my_image_height = 0; bool ret = loadTextureFromFile(imgPath, my_image_texture, &my_image_width, &my_image_height); IM_ASSERT(ret); return true; } // Define the variables for the SAMs GLuint valSAMs[5]; // valence GLuint arousSAMs[5]; // arousal std::string iconValues[5] = {"neg2", "neg1", "0", "1", "2"}; public: // this is a constructor. It initializes your class to a specific state MyGui() : Application(windowWidth, windowHeight, my_title, 0), chordNew(), channelSignals(3) { s.open(deviceNdx); // , tact::API::MME); // opens session with the application // keep in mind, if use device name must also use the API // something the GUI needs *shrugs* ImGui::GetIO().ConfigFlags &= ~ImGuiConfigFlags_ViewportsEnable; set_background(Cyans::Teal); //background_color = Grays::Black; flags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse; // so the current chord can play immediately currentChord = chordNew.signal_list[14]; // create the icons for (int i = 0; i < 5; i++) { loadIcon(("../../Figures/arous_" + iconValues[i] + ".png").c_str(), &arousSAMs[i]); loadIcon(("../../Figures/val_" + iconValues[i] + ".png").c_str(), &valSAMs[i]); } } // Define variables needed throughout the program ImGuiWindowFlags flags; // For creating the signal std::string currentChord; // holds name of current chord based on selection Chord chordNew; std::vector<tact::Signal> channelSignals; bool isSim = false; // default is sequential int amp, sus; // to determine state of image selection int pressed = -1; // valence int pressed2 = -1; // arousal // block 1 int train_num1 = 40; // amount of trials in training session int corr_train_num1 = 40; // amount of trials in corrective training session int experiment_num1 = 40; // amount of trials in experiment // block2 int train_num2 = 40; // amount of trials in training session int corr_train_num2 = 40; // amount of trials in corrective training session int experiment_num2 = 40; // amount of trials in experiment int val = 0, arous = 0; // initialize val&arous values int final_block_num = 6; // number of blocks total // For playing the signal Clock play_clock; // keeping track of time for non-blocking pauses bool playTime = false; // for knowing how long to play cues // Set up timing within the trials itself Clock trial_clock; double timeRespond; // track how long people take to decide // The amplitudes in a vector std::vector<int> listAmp = {0, 1, 2, 3}; // The sustains in a vector std::vector<int> listSus = {0, 1, 2}; // The base parameters for my chords std::vector<int> chordList = {0, 1, 2, 3, 4, 5, 6, 7}; // for all chords std::vector<int> baseChordList; // to determine the chords list for the next screen // Vector for if play can be pressed bool dontPlay = false; bool first_in_trial = true; // for collecting data int item_current_val = 0; int item_current_arous = 0; int currentChordNum = 0; // chord number to be played // for screens std::string screen_name = "begin_screen"; // start at the beginning screen int exp_num = 1; // start with major/minor identification virtual void update() override { ImGui::BeginFixed("", {50,50}, {(float)windowWidth-100, (float)windowHeight-100}, flags); trialScreen1(); ImGui::End(); } void trialScreen1(); { // Set up the paramaters // Define the base cue paramaters currentChord = chordNew.signal_list[currentChordNum]; // internal trial tracker static int count = 0; // random number generator static auto rng = std::default_random_engine {}; if (first_in_trial){ list = chordList; // initial randomization std::shuffle(std::begin(list), std::end(list), rng); // counter for trial starts at 0 in beginning count = 0; // set first_in_trial to false so initial randomization can happen once first_in_trial = false; } if (count < experiment_num){ if (!dontPlay){ } else { ImGui::Text("Valence"); for (int i = 0; i < 10; i++) { if (i < 5) { if (i > 0) { ImGui::SameLine(); } ImGui::PushID(i); if (pressed == i){ ImGui::PushStyleColor(ImGuiCol_Button,ImVec4(1.0f, 1.0f, 0.0f, 1.0f)); } else ImGui::PushStyleColor(ImGuiCol_Button, (ImVec4)ImColor::HSV(1 / 7.0f, 0.3f, 0.3f)); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, (ImVec4)ImColor::HSV(2 / 7.0f, 0.6f, 0.6f)); ImGui::PushStyleColor(ImGuiCol_ButtonActive, (ImVec4)ImColor::HSV(5 / 7.0f, 0.9f, 0.9f)); if(ImGui::ImageButton((void *)(intptr_t)valSAMs[i],buttonSizeSAMs, ImVec2(0,0), ImVec2(1,1), 5)) { pressed = i; val = pressed - 2; }; } else { if (i > 5) { ImGui::SameLine(); } else { ImGui::Text("Arousal"); } ImGui::PushID(i); if (pressed2 == i){ ImGui::PushStyleColor(ImGuiCol_Button,ImVec4(1.0f, 1.0f, 0.0f, 1.0f)); } else ImGui::PushStyleColor(ImGuiCol_Button, (ImVec4)ImColor::HSV(1 / 7.0f, 0.3f, 0.3f)); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, (ImVec4)ImColor::HSV(2 / 7.0f, 0.6f, 0.6f)); ImGui::PushStyleColor(ImGuiCol_ButtonActive, (ImVec4)ImColor::HSV(5 / 7.0f, 0.9f, 0.9f)); if(ImGui::ImageButton((void *)(intptr_t)arousSAMs[i-5],buttonSizeSAMs, ImVec2(0,0), ImVec2(1,1), 5)) { pressed2 = i; arous = pressed2 - 7; }; } ImGui::PopStyleColor(3); ImGui::PopID(); } ImGui::NewLine(); ImGui::NewLine(); ImGui::SameLine(205); // Go to next cue if(ImGui::Button("Next",buttonSizeTrial)){ // Record the answers if (pressed > 0 && pressed2 > 0) { // timestamp information********** timeRespond = trial_clock.get_elapsed_time().as_seconds(); // get response time // put in the excel sheet file_name << count << ","; // track trial file_name << currentChordNum << "," << sus << "," << amp << "," << isSim << "," << chordNew.getMajor() << ","; // gathers experimental paramaters file_name << val << "," << arous << "," << timeRespond << std::endl; // gathers experimental input // reset values for drop down list pressed = -1; pressed2 = -1; // shuffle the amplitude list if needed int cue_num = count % 4; if (cue_num == 3){ std::shuffle(std::begin(list), std::end(list), rng); } // increase the list number count++; dontPlay = false; if(count < experiment_num) // if not final trial { // Play the next cue for listening purposes // determine which part of the list should be used cue_num = count%4; // determine what is the amp amp = list[cue_num]; // create the cue chordNew = Chord(currentChord, sus, amp, isSim); // determine the values for each channel channelSignals = chordNew.playValues(); // play_trial(cue_num); s.play(leftTact, channelSignals[0]); s.play(botTact, channelSignals[1]); s.play(rightTact, channelSignals[2]); // reset the play time clock play_clock.restart(); // allow for the play time to be measured and pause to be enabled playTime = true; } } else { ImGui::OpenPopup("Error"); } } if(ImGui::BeginPopup("Error")){ ImGui::Text("Please make both a valence and arousal selection before continuing."); if(ImGui::Button("Close")) { ImGui::CloseCurrentPopup(); } } } // Dictate how long the signal plays if (playTime) { // Let the user know that they should feel something ImGui::Text("The cue is currently playing."); int cue_num = count % 4; // if the signal time has passed, stop the signal on all channels if(play_clock.get_elapsed_time().as_seconds() > channelSignals[0].length()){ // if whole signal is played s.stopAll(); playTime = false; // do not reopen this until Play is pressed again trial_clock.restart(); // start recording the response time // Don't allow the user to press play again dontPlay = true; } } } else // if trials are done { cout << "done" << endl; } }
41.242515
165
0.532341
DaziyahS
d2b888ee6ffeb89540abf52892fd5c48fb0a3b60
228
hpp
C++
scicpp/linalg.hpp
tvanderbruggen/SciCpp
09408506c8d0b49ca5dadb8cd1f3cb4db41c8c46
[ "MIT" ]
2
2021-08-02T09:03:30.000Z
2022-02-17T11:58:05.000Z
scicpp/linalg.hpp
tvanderbruggen/SciCpp
09408506c8d0b49ca5dadb8cd1f3cb4db41c8c46
[ "MIT" ]
null
null
null
scicpp/linalg.hpp
tvanderbruggen/SciCpp
09408506c8d0b49ca5dadb8cd1f3cb4db41c8c46
[ "MIT" ]
null
null
null
// SPDX-License-Identifier: MIT // Copyright (c) 2019-2021 Thomas Vanderbruggen <th.vanderbruggen@gmail.com> #ifndef SCICPP_LINALG_HEADER #define SCICPP_LINALG_HEADER #include "linalg/solve.hpp" #endif // SCICPP_LINALG_HEADER
25.333333
76
0.798246
tvanderbruggen