hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
55cc4d5075462ee981cb55284c8a658ccac0fc82
| 7,859
|
cpp
|
C++
|
src/plugin/xconnection/message.cpp
|
willenchou/xservers
|
0f8b262571ed7c0465d90ef807a9a540e97de379
|
[
"Apache-2.0"
] | 11
|
2016-12-11T02:17:58.000Z
|
2021-11-24T03:27:01.000Z
|
src/plugin/xlink/message.cpp
|
willenchou/xservers
|
0f8b262571ed7c0465d90ef807a9a540e97de379
|
[
"Apache-2.0"
] | null | null | null |
src/plugin/xlink/message.cpp
|
willenchou/xservers
|
0f8b262571ed7c0465d90ef807a9a540e97de379
|
[
"Apache-2.0"
] | 2
|
2016-12-11T10:48:00.000Z
|
2021-07-10T07:10:55.000Z
|
#include "message.h"
namespace x {
Message::Message()
:buff_(NULL)
,buffCap_(0)
,buffLen_(0){
memset(tags_, 0, sizeof(tags_));
buff_ = new char[INIT_MSG_BUFF_LEN];
buffCap_ = INIT_MSG_BUFF_LEN;
buffLen_ = 0;
}
Message::~Message(){
if(buff_)
delete buff_;
}
bool Message::SetBuff(void* data, uint32_t len){
if(len < sizeof(Head))
return false;
if(buffCap_ < len){
Resize(len);
}
memcpy(buff_, data, len);
BuildTags();
return true;
}
bool Message::GetBuff(void** data, uint32_t* len){
BuildBuff();
Head* head = (Head*)buff_;
if(head->len > 0){
if(data) *data = buff_;
if(len) *len = sizeof(Head) + head->len;
return true;
}
return false;
}
bool Message::SetData(uint32_t tagID, void* data, uint32_t len, int32_t type){
if(tagID < MSG_TAG_MAX_COUNT){
if(tags_[tagID] == NULL){
tags_[tagID] = new MessageTag(tagID);
}else{
tags_[tagID]->Clear();
}
tags_[tagID]->AddData(data, len ,type);
return true;
}
return false;
}
bool Message::AddData(uint32_t tagID, void* data, uint32_t len, int32_t type){
if(tagID < MSG_TAG_MAX_COUNT){
if(tags_[tagID] == NULL){
tags_[tagID] = new MessageTag(tagID);
}
tags_[tagID]->AddData(data, len ,type);
return true;
}
return false;
}
uint32_t Message::GetDataCount(uint32_t tagID){
if(tagID < MSG_TAG_MAX_COUNT){
if(tags_[tagID] != NULL){
return tags_[tagID]->GetDataCount();
}
}
return 0u;
}
bool Message::GetData(uint32_t tagID, void** data, uint32_t* len, int32_t* type, uint32_t index){
if(tagID < MSG_TAG_MAX_COUNT){
if(tags_[tagID] != NULL){
return tags_[tagID]->GetData(data, len, type, index);
}
}
return false;
}
bool Message::DataExist(uint32_t tagID){
if(tagID < MSG_TAG_MAX_COUNT){
if(tags_[tagID] != NULL){
return true;
}
}
return false;
}
void Message::RemoveData(uint32_t tagID){
if(tagID < MSG_TAG_MAX_COUNT){
if(tags_[tagID] != NULL){
delete tags_[tagID];
tags_[tagID] = NULL;
}
}
}
void Message::Clear(){
for(int i = 0; i < MSG_TAG_MAX_COUNT; i++){
if(tags_[i] != NULL){
delete tags_[i];
tags_[i] = NULL;
}
}
buffLen_ = 0;
}
void Message::ChangeReq2Ans(){
MessageTag* tagTemp = tags_[MSG_TAG_ROUTE_SRC];
tags_[MSG_TAG_ROUTE_SRC] = tags_[MSG_TAG_ROUTE_DEST];
tags_[MSG_TAG_ROUTE_DEST] = tagTemp;
if(tags_[MSG_TAG_ROUTE_SRC] != NULL)
tags_[MSG_TAG_ROUTE_SRC]->SetTagID(MSG_TAG_ROUTE_SRC);
if(tags_[MSG_TAG_ROUTE_DEST] != NULL)
tags_[MSG_TAG_ROUTE_DEST]->SetTagID(MSG_TAG_ROUTE_DEST);
SetFuncType(MSG_FUNC_TYPE_ANS);
}
void Message::SetSysNo(uint32_t sysNo){
GetTagFuncInfo()->sysNo = sysNo;
}
bool Message::GetSysNo(uint32_t* sysNo){
MsgFuncInfo * info = GetTagFuncInfo(false);
if(!info)
return false;
if(sysNo) *sysNo = info->sysNo;
return true;
}
void Message::SetSubSysNo(uint32_t subSysNo){
GetTagFuncInfo()->subSysNo = subSysNo;
}
bool Message::GetSubSysNo(uint32_t* subSysNo){
MsgFuncInfo * info = GetTagFuncInfo(false);
if(!info)
return false;
if(subSysNo) *subSysNo = info->subSysNo;
return true;
}
void Message::SetFuncID(uint32_t funcID){
GetTagFuncInfo()->funcID = funcID;
}
bool Message::GetFuncID(uint32_t* funcID){
MsgFuncInfo * info = GetTagFuncInfo(false);
if(!info)
return false;
if(funcID) *funcID = info->funcID;
return true;
}
void Message::SetFuncType(uint32_t funcType){
GetTagFuncInfo()->type = funcType;
}
bool Message::GetFuncType(uint32_t* funcType){
MsgFuncInfo * info = GetTagFuncInfo(false);
if(!info)
return false;
if(funcType) *funcType = info->type;
return true;
}
void Message::SetSendID(uint32_t sendID){
GetTagFuncInfo()->sendID = sendID;
}
bool Message::GetSendID(uint32_t* sendID){
MsgFuncInfo * info = GetTagFuncInfo(false);
if(!info)
return false;
if(sendID) *sendID = info->sendID;
return true;
}
void Message::SetReturnID(int32_t returnID){
GetTagFuncInfo()->returnNo = returnID;
}
bool Message::GetReturnID(int32_t* returnID){
MsgFuncInfo * info = GetTagFuncInfo(false);
if(!info)
return false;
if(returnID) *returnID = info->returnNo;
return true;
}
void Message::Resize(uint32_t newSize){
if(newSize <= buffCap_) return;
char* buff = new char[newSize];
memcpy(buff, buff_, buffLen_);
delete buff_;
buff_ = buff;
buffCap_ = newSize;
}
void Message::BuildTags(){
for(int i = 0; i < MSG_TAG_MAX_COUNT; i++){
if(tags_[i] != NULL){
delete tags_[i];
tags_[i] = NULL;
}
}
Head* head = (Head*)buff_;
uint32_t pos = sizeof(Head);
while(pos < head->len){
MessageTag::Head* tagHead = (MessageTag::Head*)(buff_ + pos);
if(tagHead->ID < MSG_TAG_MAX_COUNT){
MessageTag* tag = new MessageTag(tagHead->ID);
tag->SetBuff(buff_ + pos, sizeof(MessageTag::Head) + tagHead->len);
tags_[tagHead->ID] = tag;
}
pos += (sizeof(MessageTag::Head) + tagHead->len);
}
}
void Message::BuildBuff(){
Head* head = (Head*)buff_;
head->flag = MSG_FLAG;
head->tagCount = 0;
head->len = 0;
buffLen_ = sizeof(Head);
for(int i = 0; i < MSG_TAG_MAX_COUNT; i++){
MessageTag* tag = tags_[i];
if(tag != NULL){
uint32_t tagBuffLen = 0;
void* tagBuffData = tag->GetBuff(tagBuffLen);
if(tagBuffData){
if(buffLen_ + tagBuffLen > buffCap_){
Resize((buffCap_ + tagBuffLen) * 2);
head = (Head*)buff_;
}
memcpy(buff_ + buffLen_, tagBuffData, tagBuffLen);
head->tagCount++;
head->len += tagBuffLen;
buffLen_ += tagBuffLen;
}
}
}
}
MsgFuncInfo* Message::GetTagFuncInfo(bool insert){
if(tags_[MSG_TAG_FUNC_INFO] == NULL){
if(!insert)
return NULL;
MsgFuncInfo info;
memset(&info, 0, sizeof(info));
tags_[MSG_TAG_FUNC_INFO] = new MessageTag(MSG_TAG_FUNC_INFO);
tags_[MSG_TAG_FUNC_INFO]->AddData(&info, sizeof(info));
}
void* data = NULL;
uint32_t dataLen = 0;
tags_[MSG_TAG_FUNC_INFO]->GetData(&data,&dataLen);
return (MsgFuncInfo*)data;
}
MessageTag::MessageTag(int32_t ID){
buff_ = new char[INIT_TAG_BUFF_LEN];
buffLen_ = INIT_TAG_BUFF_LEN;
Head* head = GetHead();
head->ID = ID;
head->count = 0;
head->len = 0;
}
MessageTag::~MessageTag(){
delete [] buff_;
buff_ = NULL;
buffLen_ = 0;
}
bool MessageTag::SetBuff(void* data, uint32_t len){
if(len < sizeof(Head)) return false;
if(buffLen_ < len){
Resize(len);
}
memcpy(buff_, data, len);
return true;
}
void* MessageTag::GetBuff(uint32_t& len){
Head* head = GetHead();
if(head->len > 0){
len = sizeof(Head) + head->len;
return buff_;
}
return NULL;
}
void MessageTag::AddData(void* data, uint32_t dataLen, int32_t type){
if(GetHead()->len + dataLen > buffLen_){
Resize((GetHead()->len + dataLen) * 2);
}
Head* head = GetHead();
ItemHead itemHead = {type, dataLen};
memcpy(buff_ + sizeof(Head) + head->len, &itemHead, sizeof(itemHead)); head->len += sizeof(itemHead);
memcpy(buff_ + sizeof(Head) + head->len, data, dataLen); head->len += dataLen;
head->count++;
}
uint32_t MessageTag::GetDataCount(){
return GetHead()->count;
}
bool MessageTag::GetData(void** data, uint32_t* len, int32_t* type, uint32_t index){
Head* head = GetHead();
if(index >= head->count)
return false;
uint32_t pos = GetItemPos(index);
if(data) *data = buff_ + pos + sizeof(ItemHead);
if(len) *len = ((ItemHead*)(buff_ + pos))->len;
if(type) *type = ((ItemHead*)(buff_ + pos))->type;
return true;
}
void MessageTag::Clear(){
Head* head = GetHead();
head->len = 0;
head->count = 0;
}
void MessageTag::Resize(uint32_t newSize){
if(newSize <= buffLen_) return;
char* buff = new char[newSize];
memcpy(buff, buff_, buffLen_);
delete buff_;
buff_ = buff;
buffLen_ = newSize;
}
uint32_t MessageTag::GetItemPos(uint32_t index){
Head* head = GetHead();
uint32_t pos = sizeof(Head);
for(uint32_t i = 0; i < head->count; i++){
if(i == index){
return pos;
}
ItemHead* head = (ItemHead*)(buff_ + pos);
pos += sizeof(ItemHead) + head->len;
}
return pos;
}
}//namespace x
| 20.519582
| 102
| 0.671968
|
willenchou
|
55d235a1e54de2f1b2f38e243902912a3503f33e
| 2,576
|
cpp
|
C++
|
RhoShamBo/DeBruijn.cpp
|
dlidstrom/RhoShamBo
|
a85da97883e7772aa0dde711910094d0b1dfb631
|
[
"MIT"
] | null | null | null |
RhoShamBo/DeBruijn.cpp
|
dlidstrom/RhoShamBo
|
a85da97883e7772aa0dde711910094d0b1dfb631
|
[
"MIT"
] | null | null | null |
RhoShamBo/DeBruijn.cpp
|
dlidstrom/RhoShamBo
|
a85da97883e7772aa0dde711910094d0b1dfb631
|
[
"MIT"
] | null | null | null |
#include "stdafx.h"
#include "DeBruijn.h"
IPlayer::HAND DeBruijn::GetNextHand(const HandsCollection& yourHistory,
const HandsCollection& oppHistory)
{
/* several De Bruijn strings of length 81 concatentated */
static int db_table [1000] = /* De Bruijn sequence: */
{1,0,2,0,0,2,0,2,0,1,1,0,0,2,2,1,0,0,1,1,2,2,0,0,1,2,1,0,2,2,2,2,0,1,2,0,2,2,0,2,
1,1,2,1,1,0,1,1,1,2,0,0,0,0,2,1,0,1,0,1,2,2,1,2,0,1,0,0,0,1,0,2,1,2,1,2,2,2,1,1,
1,0,0,1,1,1,1,0,1,0,2,2,2,0,0,2,2,0,2,0,1,0,1,1,0,2,1,1,2,2,2,2,1,1,1,2,0,1,2,2,
1,2,0,0,0,1,0,0,0,0,2,0,2,2,1,0,0,1,2,1,2,2,0,1,1,2,1,1,0,0,2,1,0,1,2,0,2,1,2,1,
0,2,1,1,2,0,0,1,0,1,2,2,0,1,0,0,2,0,1,2,0,1,1,2,1,1,1,1,0,2,0,2,1,0,2,2,0,2,2,2,
2,0,0,0,1,2,1,2,2,2,1,1,0,1,1,0,0,0,0,2,1,2,0,2,0,0,2,2,1,0,0,1,1,1,2,2,1,2,1,0,
1,0,2,1,0,1,0,2,0,2,0,0,1,2,2,2,0,2,1,0,0,1,1,1,2,2,1,1,0,2,2,0,0,0,2,2,2,2,1,2,
2,0,1,2,0,0,2,0,1,1,2,1,2,1,1,1,1,0,0,2,1,2,0,1,0,0,0,0,1,0,1,1,0,1,2,1,0,2,1,1,
2,0,2,2,2,2,1,1,1,1,0,0,2,0,2,2,2,1,2,1,0,2,1,0,0,0,0,2,1,1,2,2,1,0,1,0,0,1,1,1,
2,1,1,0,1,2,2,2,2,0,0,1,2,0,2,0,1,2,1,2,0,1,0,1,1,2,0,0,0,1,0,2,2,0,2,1,2,2,0,1,
1,0,2,0,0,0,0,0,0,1,0,0,0,2,1,1,0,0,1,1,1,1,0,2,0,2,1,2,0,2,2,1,2,2,2,1,1,1,2,1,
2,1,0,0,2,0,1,1,0,1,0,2,1,0,2,2,2,2,0,2,0,0,2,2,0,0,1,2,2,1,0,1,1,2,0,1,2,1,1,2,
2,0,1,0,1,2,2,2,0,2,0,0,2,0,2,1,2,2,2,2,0,0,0,0,2,2,1,0,0,0,1,2,0,1,2,1,2,0,0,1,
0,2,0,1,0,0,2,1,0,1,2,2,1,1,2,0,2,2,2,1,2,1,0,2,2,0,1,1,0,2,1,1,0,0,1,1,2,1,1,1,
1,0,1,0,1,1,1,1,1,1,2,1,0,0,0,0,1,1,0,2,1,2,1,2,2,2,0,0,1,2,0,1,0,1,2,1,1,2,2,0,
2,0,2,1,1,0,0,1,0,2,0,0,2,0,1,1,2,0,2,2,1,1,1,1,0,1,0,0,2,2,2,2,1,2,0,0,0,2,1,0,
2,2,0,1,2,2,1,0,2,1,0,1,0,1,1,1,1,2,1,1,0,1,2,1,2,2,2,2,1,2,0,0,0,1,1,2,0,2,0,2,
1,0,0,0,0,2,0,0,1,0,0,2,2,2,0,0,2,1,1,2,2,0,1,2,0,1,1,0,0,1,2,2,1,1,1,0,2,0,1,0,
2,2,0,2,2,1,0,2,1,2,2,2,1,0,1,0,2,2,1,2,0,2,1,0,2,0,0,0,0,1,2,1,0,0,2,0,2,2,0,1,
0,1,1,2,1,1,0,0,1,0,0,0,2,1,1,2,0,0,2,2,2,2,0,0,1,1,1,0,2,1,2,1,2,2,1,1,1,1,2,2,
0,2,0,1,2,0,1,1,0,1,1,0,0,1,1,0,1,2,0,1,2,1,2,2,1,0,0,2,0,2,1,0,1,0,2,2,0,1,1,2,
1,0,2,0,0,1,0,1,1,1,2,2,2,2,1,2,0,2,2,1,1,2,0,0,2,1,2,1,1,1,1,0,2,1,1,0,0,0,0,2,
2,2,0,0,0,1,2,2,0,2,0,2,2,0,2,1,1,2,0,2,0,0,1,1,1,0,0,1,2,1,1,0,1,1,0,2,2,0,0,2,
2,1,1,1,1,2,1,2,1,0,2,0,2,2,2,2,1,2,0,0,0,1,0,0,2,1,0,0,0,0,2,0,1,1,2,2,2,0,1,2,
2,1,0,1,0,1,2,0,1,0,2,1,0,2,0,2,1,1,1,0,0,2,2,2,0,1,1,2,2,1,2,0,0,0,1,0,1,2,1,0};
/* corrected code courtesy of Michael Callahan */
return HAND(db_table[yourHistory.size() % 1000]);
}
std::string DeBruijn::Name() const
{
return "DeBruijn";
}
| 57.244444
| 83
| 0.511646
|
dlidstrom
|
55db32c24c3a8083b75e8277669429f61480ad6f
| 94,567
|
cpp
|
C++
|
src/math_implementation_4.cpp
|
tmilev/calculator
|
e39280f23975241985393651fe7a52db5c7fd1d5
|
[
"Apache-2.0"
] | 7
|
2017-07-12T11:15:54.000Z
|
2021-10-29T18:33:33.000Z
|
src/math_implementation_4.cpp
|
tmilev/calculator
|
e39280f23975241985393651fe7a52db5c7fd1d5
|
[
"Apache-2.0"
] | 18
|
2017-05-16T03:48:45.000Z
|
2022-03-16T19:51:26.000Z
|
src/math_implementation_4.cpp
|
tmilev/calculator
|
e39280f23975241985393651fe7a52db5c7fd1d5
|
[
"Apache-2.0"
] | 1
|
2018-08-02T09:05:08.000Z
|
2018-08-02T09:05:08.000Z
|
// The current file is licensed under the license terms found in the main header file "calculator.h".
// For additional information refer to the file "calculator.h".
#include "math_general.h"
#include "math_general_implementation.h"
#include "math_extra_finite_groups_implementation.h"
#include "math_extra_symmetric_groups_and_generalizations.h"
#include "math_extra_drawing_variables.h"
#include "calculator_interface.h"
#include "system_functions_global_objects.h"
#include "string_constants.h"
std::string UserCalculatorData::Roles::administator = "admin";
std::string UserCalculatorData::Roles::student = "student";
std::string UserCalculatorData::Roles::instructor = "instructor";
std::string UserCalculatorData::Roles::teacher = "teacher";
void fatalCrash(const std::string& input) {
global.fatal << input << global.fatal;
}
GlobalVariables::Crasher::Crasher() {
this->flagCrashInitiated = false;
this->flagFinishingCrash = false;
}
void GlobalVariables::Crasher::firstRun() {
if (
!this->flagCrashInitiated &&
global.flagRunningBuiltInWebServer
) {
double elapsedSeconds = global.getElapsedSeconds();
this->crashReportHtml << "\n<b style = 'color:red'>Crash</b> "
<< elapsedSeconds << " second(s) from the start.<hr>";
this->crashReportConsolE << Logger::consoleRed() << "Crash " << elapsedSeconds
<< " second(s)" << Logger::consoleNormal() << " from the start.\n";
this->crashReportFile << "Crash " << elapsedSeconds
<< " second(s) from the start.\n";
}
this->flagCrashInitiated = true;
}
GlobalVariables::Crasher& GlobalVariables::Crasher::doCrash(
const Crasher& dummyCrasherSignalsActualCrash
) {
(void) dummyCrasherSignalsActualCrash;
this->firstRun();
if (this->flagFinishingCrash) {
std::cout << "Recursion within the crashing mechanism detected. "
<< "Something is very wrong. "
<< this->crashReportConsolE.str() << std::endl;
std::exit(- 1);
}
this->crashReportConsolE << this->crashReport.str();
this->crashReportHtml << this->crashReport.str();
this->crashReportFile << this->crashReport.str();
this->flagFinishingCrash = true;
if (!global.flagNotAllocated) {
this->crashReportConsolE << "\n";
}
if (!global.flagNotAllocated) {
if (global.userInputStringIfAvailable != "") {
this->crashReportHtml << "<hr>User input: <br> "
<< global.userInputStringIfAvailable << "<hr>";
this->crashReportConsolE << "User input: "
<< Logger::consoleBlue() << global.userInputStringIfAvailable
<< Logger::consoleNormal() << "\n";
this->crashReportFile << "User input:\n" << global.userInputStringIfAvailable << "\n";
}
}
this->crashReportConsolE << Crasher::getStackTraceEtcErrorMessageConsole();
this->crashReportHtml << Crasher::getStackTraceEtcErrorMessageHTML();
this->crashReportFile << Crasher::getStackTraceEtcErrorMessageHTML();
if (!global.flagNotAllocated) {
if (global.progressReportStrings.size > 0) {
this->crashReportHtml
<< "<hr><b>Computation progress report strings:</b><br>"
<< global.toStringProgressReportNoThreadData(true);
this->crashReportFile
<< "<hr><b>Computation progress report strings:</b><br>"
<< global.toStringProgressReportNoThreadData(true);
this->crashReportConsolE << "Computation progress strings:\n";
this->crashReportConsolE << global.toStringProgressReportNoThreadData(false);
}
}
this->writeCrashFile();
std::cout << this->crashReportConsolE.str() << std::endl;
JSData output;
output[WebAPI::result::crashReport] = this->crashReportHtml.str();
output[WebAPI::result::comments] = global.comments.getCurrentReset();
global.response.writeResponse(output, true);
std::exit(- 1);
return *this;
}
void GlobalVariables::Crasher::writeCrashFile() {
if (global.flagNotAllocated) {
this->crashReportHtml << "GlobalVariables.flagNotAllocated is true. ";
this->crashReportConsolE << "GlobalVariables.flagNotAllocated is true. ";
return;
}
if (global.flagRunningWebAssembly) {
this->crashReportHtml << "Crash while running web assembly.";
this->crashReportConsolE << "Crash while running web assembly.";
return;
}
if (!global.calculator().isZeroPointer()) {
if (global.calculator().getElement().comments.str() != "") {
this->crashReportHtml << "<hr>Additional comments follow. "
<< global.calculator().getElement().comments.str();
}
}
std::fstream crashFile;
bool openSuccess = FileOperations::openFileCreateIfNotPresentVirtual(
crashFile,
"crashes/" + global.relativePhysicalNameCrashReport,
false,
true,
false,
true,
true
);
if (openSuccess) {
this->crashReportHtml << "<hr>Crash dumped in folder "
<< "results/crashes/. Not visible through the web server. "
<< "If running locally, simply open the results/crashes "
<< "folder within your calculator folder. "
<< "If running remotely, you will need an ssh connection. ";
this->crashReportConsolE << "Crash dumped in file: " << Logger::consoleGreen()
<< global.relativePhysicalNameCrashReport << Logger::consoleNormal() << "\n";
} else {
this->crashReportHtml << "<hr>Failed to open crash report file: "
<< global.relativePhysicalNameCrashReport
<< ". check file permissions. ";
this->crashReportConsolE << "Failed to open crash report file: "
<< Logger::consoleRed()
<< global.relativePhysicalNameCrashReport
<< Logger::consoleNormal() << "\n";
}
crashFile << this->crashReportFile.str();
crashFile.flush();
crashFile.close();
}
std::string GlobalVariables::Crasher::getStackTraceEtcErrorMessageHTML() {
std::stringstream out;
out << "A partial stack trace follows (function calls not explicitly logged not included).";
out << "<table><tr>";
for (int threadCounter = 0; threadCounter < global.customStackTrace.size; threadCounter ++) {
if (threadCounter >= global.threadData.size) {
out << "<td><b>WARNING: the stack trace reports "
<< global.customStackTrace.size
<< " threads but the thread data array has record of only "
<< global.threadData.size
<< " threads. " << "</b></td>";
break;
}
out << "<td>" << global.threadData[threadCounter].toStringHtml() << "</td>";
}
out << "</tr> <tr>";
for (int threadCounter = 0; threadCounter<global.customStackTrace.size; threadCounter ++) {
if (threadCounter >= global.threadData.size) {
break;
}
if (ThreadData::getCurrentThreadId() != threadCounter) {
out << "<td>Stack trace available only for current thread.</td>";
//<-to avoid coordinating threads
continue;
}
ListReferences<StackInfo>& currentInfo = global.customStackTrace[threadCounter];
out << "<td><table><tr><td>file</td><td>line</td><td>function name (if known)</td></tr>";
for (int i = currentInfo.size - 1; i >= 0; i --) {
out << "<tr><td>" << HtmlRoutines::getHtmlLinkFromProjectFileName(currentInfo[i].fileName, "", currentInfo[i].line)
<< "</td><td>" << currentInfo[i].line << "</td>";
if (currentInfo[i].functionName != "") {
out << "<td>" << currentInfo[i].functionName << "</td>";
}
out << "</tr>";
}
out << "</table></td>";
}
out << "</tr></table>";
return out.str();
}
std::string GlobalVariables::Crasher::getStackTraceEtcErrorMessageConsole() {
std::stringstream out;
for (int threadCounter = 0; threadCounter<global.customStackTrace.size; threadCounter ++) {
if (threadCounter >= global.threadData.size) {
out << "WARNING: stack trace reports " << global.customStackTrace.size << " threads "
<< "while I have only " << global.threadData.size << " registered threads. ";
break;
}
out << "********************\r\nThread index " << threadCounter << ": \r\n";
if (ThreadData::getCurrentThreadId() != threadCounter) {
out << "Stack trace available only for current thread.\n";
//<-to avoid coordinating threads
continue;
}
ListReferences<StackInfo>& currentInfo = global.customStackTrace[threadCounter];
for (int i = currentInfo.size - 1; i >= 0; i --) {
out << currentInfo[i].functionName << "\n";
}
}
return out.str();
}
std::string GlobalVariables::toHTMLTopCommandLinuxSystem() {
MacroRegisterFunctionWithName("GlobalVariables::toHTMLTopCommandLinuxSystem");
if (!global.userDefaultHasAdminRights()) {
return "Login as admin for RAM memory statistics.";
}
std::string topString = this->externalCommandReturnOutput("top -b -n 1 -s");
std::stringstream out;
std::string lineString, wordString;
std::stringstream topStream(topString);
for (int i = 0; i < 4; i ++) {
std::getline(topStream, lineString);
out << lineString << "<br>\n ";
}
out << "<table>";
for (; std::getline(topStream, lineString);) {
out << "<tr>";
for (std::stringstream nextLineStream(lineString); nextLineStream >> wordString;) {
out << "<td>" << wordString << "</td>";
}
out << "</tr>";
}
out << "</table>";
return out.str();
}
std::string GlobalVariables::toStringFolderInfo() const {
std::stringstream out;
out << "<br>Physical path server base: " << this->physicalPathServerBase;
out << "<br>Diplay name executable: " << this->displayNameExecutable;
out << "<br>Physical name folder below executable: " << this->physicalNameFolderExecutable;
out << "<br>Display path output folder: " << this->displayPathOutputFolder;
return out.str();
}
std::string GlobalVariables::toStringThreadData(bool useHTML) {
std::stringstream out;
for (int threadIndex = 0; threadIndex < this->progressReportStrings.size; threadIndex ++) {
if (useHTML) {
out << "<hr><b>";
}
out << this->threadData[threadIndex].toStringHtml();
if (useHTML) {
out << "</b><br>";
}
out << "\n";
}
return out.str();
}
std::string GlobalVariables::toStringProgressReportWithThreadData(bool useHTML) {
MacroRegisterFunctionWithName("GlobalVariables::ToStringProgressReportHtmlWithThreadData");
std::stringstream out;
out << global.toStringThreadData(useHTML);
out << global.toStringProgressReportNoThreadData(useHTML);
return out.str();
}
std::string GlobalVariables::toStringProgressReportNoThreadData(bool useHTML) {
MacroRegisterFunctionWithName("GlobalVariables::toStringProgressReportNoThreadData");
std::stringstream reportStream;
for (int threadIndex = 0; threadIndex < this->progressReportStrings.size; threadIndex ++) {
int currentThreadID = ThreadData::getCurrentThreadId();
if (currentThreadID != threadIndex) {
//<-to avoid coordinating threads
continue;
}
if (useHTML) {
reportStream << "<b>Current thread id: "
<< currentThreadID
<< ". </b>";
} else {
reportStream << "Thread id: " << Logger::consoleBlue() << currentThreadID << Logger::consoleNormal() << "\n";
}
for (int i = 0; i < this->progressReportStrings[threadIndex].size; i ++) {
if (this->progressReportStrings[threadIndex][i] != "") {
if (useHTML) {
reportStream << "\n<div id = \"divProgressReport" << i << "\">"
<< this->progressReportStrings[threadIndex][i] << "\n</div>\n<hr>";
} else {
reportStream << this->progressReportStrings[threadIndex][i] << "\n";
}
}
}
}
if (!global.fatal.flagCrashInitiated) {
if (useHTML) {
reportStream << global.fatal.getStackTraceEtcErrorMessageHTML();
} else {
reportStream << global.fatal.getStackTraceEtcErrorMessageConsole();
}
reportStream << global.getElapsedMilliseconds()
<< " ms elapsed. ";
if (global.millisecondsMaxComputation > 0) {
if (useHTML) {
reportStream << "<br>";
}
reportStream << "\nHard limit: "
<< global.millisecondsMaxComputation
<< " ms [system crash if limit exceeded].";
if (useHTML) {
reportStream << "<br>";
}
reportStream << "\nSoft limit: "
<< global.millisecondsMaxComputation / 2
<< " ms [computation error if limit exceeded, triggered between calculator/atomic functions].";
}
}
return reportStream.str();
}
std::string GlobalVariables::toStringProgressReportConsole() {
MacroRegisterFunctionWithName("GlobalVariables::toStringProgressReportConsole");
std::stringstream reportStream;
for (int threadIndex = 0; threadIndex < this->progressReportStrings.size; threadIndex ++) {
if (ThreadData::getCurrentThreadId() != threadIndex) {
reportStream << "Progress report available only for current thread.<br>";
//<-to avoid coordinating threads
continue;
}
reportStream << this->threadData[threadIndex].toStringConsole();
for (int i = 0; i < this->progressReportStrings[threadIndex].size; i ++) {
reportStream << this->progressReportStrings[threadIndex][i];
}
}
reportStream << "\n";
return reportStream.str();
}
void GlobalVariables::initThreadsExecutableStart() {
// <-Stack trace forbidden this is running before anything has been initialized!
ThreadData::registerFirstThread("main");
}
void GlobalVariables::initFoldersProjectBase(const std::string& inputPhysicalExecutable) {
StateMaintainerCurrentFolder preserveCurrentFolder;
this->physicalPathProjectBase = FileOperations::getPathFromFileNameWithPath(inputPhysicalExecutable) + "./";
this->changeDirectory(this->physicalPathProjectBase);
this->physicalPathProjectBase = FileOperations::getCurrentFolder() + "/";
}
void GlobalVariables::initDefaultFolderAndFileNames() {
this->initFoldersProjectBase(global.pathExecutableUserInputOrDeduced);
this->physicalNameFolderExecutable = this->physicalPathProjectBase;
this->physicalNameExecutableNoPath = FileOperations::getFileNameFromFileNameWithPath(global.pathExecutableUserInputOrDeduced);
this->physicalNameExecutableWithPath = this->physicalNameFolderExecutable + this->physicalNameExecutableNoPath;
this->physicalPathServerBase = this->physicalPathProjectBase;
this->displayPathOutputFolder = "/output/";
this->displayNameExecutable = "/cgi-bin/" + this->physicalNameExecutableNoPath;
this->displayApplication = "/" + WebAPI::app;
this->displayNameExecutableAppNoCache = "/" + WebAPI::appNoCache;
this->initOutputReportAndCrashFileNames("", "");
}
void GlobalVariables::setWebInput(const std::string& inputName, const std::string& inputValue) {
MacroRegisterFunctionWithName("GlobalVariables::SetWebInput");
this->webArguments.setKeyValue(inputName, inputValue);
}
bool GlobalVariables::userSecureNonAdminOperationsAllowed() {
return this->flagLoggedIn && this->flagUsingSSLinCurrentConnection;
}
bool GlobalVariables::userDebugFlagOn() {
return global.getWebInput(WebAPI::request::debugFlag) == "true";
}
bool GlobalVariables::userStudentVieWOn() {
return global.getWebInput("studentView") == "true";
}
std::string GlobalVariables::LogData::toStringProcessType() const {
switch (this->logType) {
case GlobalVariables::LogData::type::initialization:
return "initialization";
case GlobalVariables::LogData::type::server:
return "server";
case GlobalVariables::LogData::type::serverMonitor:
return "server monitor";
case GlobalVariables::LogData::type::worker:
return "worker";
case GlobalVariables::LogData::type::daemon:
return "daemon";
default:
return "uknown process type";
}
}
bool GlobalVariables::checkConsistency() {
if (this->flagDeallocated) {
global.fatal << "Global variables not allowed to be deallocated. " << global.fatal;
}
return true;
}
bool GlobalVariables::userDefaultIsDebuggingAdmin() {
return this->userDefaultHasAdminRights() && this->userDebugFlagOn();
}
bool GlobalVariables::userDefaultHasAdminRights() {
if (global.flagDisableDatabaseLogEveryoneAsAdmin) {
return true;
}
return this->flagLoggedIn && (this->userDefault.userRole == UserCalculatorData::Roles::administator);
}
bool GlobalVariables::userDefaultHasProblemComposingRights() {
return this->flagLoggedIn && (
this->userDefault.userRole == UserCalculatorData::Roles::administator ||
this->userDefault.userRole == UserCalculatorData::Roles::teacher
);
}
bool GlobalVariables::userGuestMode() {
if (!this->flagUsingSSLinCurrentConnection) {
return true;
}
return
this->requestType == "exerciseNoLogin" ||
this->requestType == WebAPI::request::problemGiveUpNoLogin ||
this->requestType == WebAPI::request::submitExerciseNoLogin ||
this->requestType == WebAPI::request::submitExercisePreviewNoLogin ||
this->requestType == "templateNoLogin";
}
bool GlobalVariables::userRequestRequiresLoadingRealExamData() {
if (this->userGuestMode()) {
return false;
}
return this->flagLoggedIn && (
this->requestType == "scoredQuiz" ||
this->requestType == "scoredQuizJSON" ||
this->requestType == "submitAnswers" ||
this->requestType == "submitAnswersPreview"
);
}
bool GlobalVariables::userRequestMustBePromptedToLogInIfNotLoggedIn() {
return
this->requestType == "scoredQuiz" ||
this->requestType == "exercise";
}
std::string GlobalVariables::toStringCalculatorArgumentsNoNavigation(List<std::string>* tagsToExclude) {
MacroRegisterFunctionWithName("GlobalVariables::toStringCalculatorArgumentsNoNavigation");
if (!this->flagLoggedIn && !this->userGuestMode()) {
return "";
}
std::stringstream out;
for (int i = 0; i < this->webArguments.size(); i ++) {
const std::string& currentName = this->webArguments.keys[i];
if (
currentName == "request" ||
currentName == "password" ||
currentName == WebAPI::problem::fileName ||
currentName == WebAPI::problem::courseHome ||
currentName == WebAPI::problem::topicList ||
currentName == "currentDatabaseTable" ||
currentName == "mainInput" ||
currentName == "studentView" ||
currentName == "studentSection" ||
currentName == "error" ||
currentName == "navigationBar" ||
currentName == "problemLinkStyle" ||
currentName == "googleToken" ||
currentName == "G_AUTHUSER_H" ||
currentName == "mjx.menu" ||
currentName == "username" ||
currentName == "authenticationToken"
) {
continue;
}
if (tagsToExclude != nullptr) {
if (tagsToExclude->contains(currentName)) {
continue;
}
}
out << global.webArguments.keys[i] << "="
<< global.webArguments.values[i]
<< "&";
}
return out.str();
}
std::string GlobalVariables::getWebInput(const std::string& inputName) {
return this->webArguments.getValueCreateEmpty(inputName);
}
void GlobalVariables::makeReport() {
MacroRegisterFunctionWithName("GlobalVariables::makeReport");
if (!global.response.monitoringAllowed()) {
return;
}
std::string reportString;
if (this->flagRunningConsoleRegular || this->flagRunningConsoleTest) {
reportString = this->toStringProgressReportConsole();
} else {
reportString = this->toStringProgressReportNoThreadData(true);
}
this->response.report(reportString);
}
void GlobalVariables::initOutputReportAndCrashFileNames(
const std::string& inputUserStringRAW, const std::string& inputUserStringCivilized
) {
std::string inputAbbreviated;
this->userInputStringIfAvailable =
FileOperations::cleanUpForFileNameUse(
inputUserStringCivilized
);
if (!global.flagUsingSSLinCurrentConnection) {
this->userInputStringRAWIfAvailable = inputUserStringRAW;
inputAbbreviated = this->userInputStringRAWIfAvailable;
} else {
this->userInputStringRAWIfAvailable = "Raw user input string not available in SSL mode. ";
inputAbbreviated = this->userInputStringIfAvailable;
}
StringRoutines::stringTrimToLengthWithHash(inputAbbreviated, 150);
this->relativePhysicalNameCrashReport = "crash_" + inputAbbreviated + ".html";
}
UserCalculatorData::UserCalculatorData() {
this->approximateHoursSinceLastTokenWasIssued = - 1;
this->flagEnteredAuthenticationToken = false;
this->flagMustLogin = true;
this->flagEnteredPassword = false;
this->flagStopIfNoLogin = true;
this->flagUserHasNoPassword = false;
this->flagUserHasActivationToken = false;
this->flagEnteredActivationToken = false;
}
void UserCalculatorData::reset() {
MacroRegisterFunctionWithName("UserCalculatorData::reset");
for (unsigned i = 0; i < this->username.size(); i ++) {
this->username[i] = '*';
}
this->username = "";
this->email = "";
this->clearAuthenticationTokenAndPassword();
}
void UserCalculatorData::clearPasswordFromMemory() {
MacroRegisterFunctionWithName("UserCalculatorData::clearPasswordFromMemory");
for (unsigned i = 0; i < this->actualHashedSaltedPassword.size(); i ++) {
this->actualHashedSaltedPassword[i] = ' ';
}
this->actualHashedSaltedPassword = "";
for (unsigned i = 0; i < this->enteredPassword.size(); i ++) {
this->enteredPassword[i] = ' ';
}
this->enteredPassword = "";
for (unsigned i = 0; i < this->enteredHashedSaltedPassword.size(); i ++) {
this->enteredHashedSaltedPassword[i] = ' ';
}
this->enteredHashedSaltedPassword = "";
for (unsigned i = 0; i < this->actualActivationToken.size(); i ++) {
this->actualActivationToken[i] = ' ';
}
this->actualActivationToken = "";
for (unsigned i = 0; i < this->enteredActivationToken.size(); i ++) {
this->enteredActivationToken[i] = ' ';
}
this->enteredActivationToken = "";
}
void UserCalculatorData::clearAuthenticationTokenAndPassword() {
MacroRegisterFunctionWithName("UserCalculatorData::clearAuthenticationTokenAndPassword");
this->clearPasswordFromMemory();
for (unsigned i = 0; i < this->actualAuthenticationToken.size(); i ++) {
this->actualAuthenticationToken[i] = ' ';
}
this->actualAuthenticationToken = "";
}
std::string UserCalculatorData::toStringCourseInfo() {
std::stringstream out;
out << "Course name:\n" << this->courseComputed
<< "\n<br>Deadline schema:\n" << this->deadlines.toString(nullptr)
<< "\n<hr>Problem weight schema:\n" << this->problemWeights.toString(nullptr);
return out.str();
}
std::string UserCalculatorData::toStringUnsecure() {
MacroRegisterFunctionWithName("UserCalculatorData::toStringUnsecure");
std::stringstream out;
out << "User: " << this->username << "\n<br>"
<< this->toStringCourseInfo()
<< "\n<br>Actual authentication token: "
<< this->actualAuthenticationToken
<< "\n<br>Entered authentication token: "
<< this->enteredAuthenticationToken
<< "\n<br>Entered password: "
<< this->enteredPassword
<< "\n<br>Entered activation token: "
<< this->enteredActivationToken
<< "\n<br>Actual activation token: "
<< this->actualActivationToken;
return out.str();
}
template<>
List<Weight<RationalFraction<Rational> > >::Comparator*
FormatExpressions::getMonomialOrder<Weight<RationalFraction<Rational> > >() {
return nullptr;
}
template<>
List<Weight<Rational> >::Comparator*
FormatExpressions::getMonomialOrder<Weight<Rational> >() {
return nullptr;
}
void DynkinDiagramRootSubalgebra::swapDynkinStrings(int i, int j) {
this->simpleComponentTypes.swapTwoIndices(i, j);
this->simpleBasesConnectedComponents.swapTwoIndices(i, j);
this->indicesThreeNodes.swapTwoIndices(i, j);
this->indicesEnds.swapTwoIndices(i, j);
}
void DynkinDiagramRootSubalgebra::sort() {
//doing bubble sort -> shortest to code
for (int i = 0; i < this->simpleBasesConnectedComponents.size; i ++) {
for (int j = i + 1; j < this->simpleBasesConnectedComponents.size; j ++) {
bool tempBool = false;
if (this->simpleBasesConnectedComponents[i].size < this->simpleBasesConnectedComponents[j].size) {
tempBool = true;
}
if (this->simpleBasesConnectedComponents[i].size == this->simpleBasesConnectedComponents[j].size) {
tempBool = ((this->simpleComponentTypes[i]) < (this->simpleComponentTypes[j]));
}
if (tempBool) {
this->swapDynkinStrings(i, j);
}
}
}
this->sameTypeComponents.size = 0;
this->indexInUniComponent.setSize(this->simpleBasesConnectedComponents.size);
this->indexUniComponent.setSize(this->simpleBasesConnectedComponents.size);
this->sameTypeComponents.reserve(this->simpleBasesConnectedComponents.size);
DynkinSimpleType tempType;
for (int i = 0; i < this->simpleBasesConnectedComponents.size; i ++) {
if (!(this->simpleComponentTypes[i] == tempType)) {
this->sameTypeComponents.setSize(this->sameTypeComponents.size + 1);
this->sameTypeComponents.lastObject()->size = 0;
tempType = this->simpleComponentTypes[i];
}
this->sameTypeComponents.lastObject()->addOnTop(i);
this->indexUniComponent[i] = this->sameTypeComponents.size - 1;
this->indexInUniComponent[i] = this->sameTypeComponents.lastObject()->size - 1;
}
}
Rational DynkinDiagramRootSubalgebra::getSquareLengthLongestRootLinkedTo(const Vector<Rational>& inputVector) {
MacroRegisterFunctionWithName("DynkinDiagramRootSubalgebra::getSquareLengthLongestRootLinkedTo");
Rational result = 0;
for (int i = 0; i < this->ambientRootSystem.size; i ++) {
if (inputVector.scalarProduct(this->ambientRootSystem[i], this->ambientBilinearForm) != 0) {
Rational squareLength = this->ambientRootSystem[i].scalarProduct(this->ambientRootSystem[i], this->ambientBilinearForm);
if (result < squareLength) {
result = squareLength;
}
}
}
return result;
}
Rational DynkinDiagramRootSubalgebra::getSquareLengthShortestRootLinkedTo(const Vector<Rational>& inputVector) {
MacroRegisterFunctionWithName("DynkinDiagramRootSubalgebra::getSquareLengthLongestRootLinkedTo");
Rational result = inputVector.scalarProduct(inputVector, this->ambientBilinearForm);
for (int i = 0; i < this->ambientRootSystem.size; i ++) {
if (inputVector.scalarProduct(this->ambientRootSystem[i], this->ambientBilinearForm) != 0) {
Rational squareLength = this->ambientRootSystem[i].scalarProduct(this->ambientRootSystem[i], this->ambientBilinearForm);
if (squareLength < result) {
result = squareLength;
}
}
}
return result;
}
void DynkinDiagramRootSubalgebra::computeDynkinString(int indexComponent) {
MacroRegisterFunctionWithName("DynkinDiagramRootSubalgebra::computeDynkinString");
this->checkInitialization();
if (indexComponent >= this->simpleBasesConnectedComponents.size) {
global.fatal << "Bad Dynkin index. " << global.fatal;
}
DynkinSimpleType& outputType = this->simpleComponentTypes[indexComponent];
Vectors<Rational>& currentComponent = this->simpleBasesConnectedComponents[indexComponent];
List<int>& currentEnds = this->indicesEnds[indexComponent];
if (currentComponent.size < 1) {
global.fatal << "CurrentComponent is empty which is impossible. " << global.fatal;
}
if (this->numberOfThreeValencyNodes(indexComponent) == 1) {
// type D or E
// in type D first comes the triple node, then the long string, then the one-root strings
// the long string is oriented with the end that is connected to the triple node having
// smaller index
// in type E similarly the longest string comes first oriented with the root that is
// linked to the triple node having smaller index
// then comes the second longest string (oriented in the same fashion)
// and last the one-root string
Vector<Rational> tripleNode;
tripleNode = currentComponent[this->indicesThreeNodes[indexComponent]];
Vectors<Rational> rootsWithoutTripleNode = currentComponent;
rootsWithoutTripleNode.removeIndexSwapWithLast(this->indicesThreeNodes[indexComponent]);
DynkinDiagramRootSubalgebra diagramWithoutTripleNode;
diagramWithoutTripleNode.ambientBilinearForm = this->ambientBilinearForm;
diagramWithoutTripleNode.ambientRootSystem = this->ambientRootSystem;
diagramWithoutTripleNode.computeDiagramInputIsSimple(rootsWithoutTripleNode);
if (diagramWithoutTripleNode.simpleBasesConnectedComponents.size != 3) {
global.fatal << "Dynkin diagram has a triple "
<< "node whose removal does not yield 3 connected components. " << global.fatal;
}
for (int i = 0; i < 3; i ++) {
if (diagramWithoutTripleNode.simpleBasesConnectedComponents[i][0].scalarProduct(tripleNode, this->ambientBilinearForm) == 0) {
diagramWithoutTripleNode.simpleBasesConnectedComponents[i].reverseElements();
}
}
for (int i = 0; i < 3; i ++) {
for (int j = i + 1; j < 3; j ++) {
if (
diagramWithoutTripleNode.simpleBasesConnectedComponents[i].size <
diagramWithoutTripleNode.simpleBasesConnectedComponents[j].size
) {
diagramWithoutTripleNode.swapDynkinStrings(i, j);
}
}
}
currentComponent.setSize(0);
if (diagramWithoutTripleNode.simpleBasesConnectedComponents[1].size == 1) {
//<- components are sorted by length, therefore the second and third component are of length 1,
//therefore we have type D_n
Rational scale = DynkinSimpleType::getDefaultLongRootLengthSquared('D') /
tripleNode.scalarProduct(tripleNode, this->ambientBilinearForm);
currentComponent.addListOnTop(diagramWithoutTripleNode.simpleBasesConnectedComponents[0]);//<-first long component
if (!tripleNode.scalarProduct(currentComponent[0], this->ambientBilinearForm).isEqualToZero()) {
currentComponent.reverseElements();
}
currentComponent.addOnTop(tripleNode);//<-then triple node
currentComponent.addListOnTop(diagramWithoutTripleNode.simpleBasesConnectedComponents[1]);//<-last two vectors
currentComponent.addListOnTop(diagramWithoutTripleNode.simpleBasesConnectedComponents[2]);//<-last two vectors
outputType.makeArbitrary('D', currentComponent.size, scale);
} else {
//the second largest component has more than one element, hence we are in type E_n.
Rational scale = DynkinSimpleType::getDefaultLongRootLengthSquared('E') / tripleNode.scalarProduct(tripleNode, this->ambientBilinearForm);
if (diagramWithoutTripleNode.simpleBasesConnectedComponents[1].size != 2) {
global.fatal << "The Dynkin diagram has two components of "
<< "length larger than 2 linked to the triple node."
<< global.fatal;
}
if (!tripleNode.scalarProduct(
diagramWithoutTripleNode.simpleBasesConnectedComponents[1][0],
this->ambientBilinearForm).isEqualToZero()
) {
diagramWithoutTripleNode.simpleBasesConnectedComponents[1].reverseElements(); //<-the 2-root component has the first root perpendicular to the triple node
}
if (
tripleNode.scalarProduct(diagramWithoutTripleNode.simpleBasesConnectedComponents[0][0],
this->ambientBilinearForm).isEqualToZero()
) {
diagramWithoutTripleNode.simpleBasesConnectedComponents[0].reverseElements(); //<-the largest component has the first root non-perpendicular to the triple node
}
currentComponent.addOnTop(diagramWithoutTripleNode.simpleBasesConnectedComponents[1][0]); //<-first root from 2-element component
currentComponent.addOnTop(diagramWithoutTripleNode.simpleBasesConnectedComponents[2][0]); //<-then the small sticky part of the Dynkin diagram
currentComponent.addOnTop(diagramWithoutTripleNode.simpleBasesConnectedComponents[1][1]); //<-next the second root from 2-element component
currentComponent.addOnTop(tripleNode); //<- next the triple node
currentComponent.addListOnTop(diagramWithoutTripleNode.simpleBasesConnectedComponents[0]); //<-finally the longest component. Conventions, conventions...
outputType.makeArbitrary('E', currentComponent.size, scale);
}
return;
}
Rational length1, length2;
length1 = currentComponent[0].scalarProduct(currentComponent[0], this->ambientBilinearForm);
int numLength1 = 1;
int numLength2 = 0;
for (int i = 1; i < currentComponent.size; i ++) {
if (currentComponent[i].scalarProduct(currentComponent[i], this->ambientBilinearForm) == length1) {
numLength1 ++;
} else {
numLength2 ++;
length2 = currentComponent[i].scalarProduct(currentComponent[i], this->ambientBilinearForm);
}
}
if (numLength2 == 0) {
//type A
outputType.makeArbitrary('A', numLength1, DynkinSimpleType::getDefaultLongRootLengthSquared('A') / length1);
} else {
if (length1 < length2) {
MathRoutines::swap(length1, length2);
MathRoutines::swap(numLength1, numLength2);
currentEnds.swapTwoIndices(0, 1);
} // <-so far we made sure the first length is long
// By convention, in types G and C, in the Dynkin diagram the long root comes last
// This is handled at the very end of this function (outside all the if clauses).
if (numLength1 == numLength2) {
//B2, C2, F4 or G2
if (numLength1 == 2) {
outputType.makeArbitrary('F', 4, DynkinSimpleType::getDefaultLongRootLengthSquared('F') / length1);
} else if (length1 / length2 == 3) {
outputType.makeArbitrary('G', 2, DynkinSimpleType::getDefaultLongRootLengthSquared('G') / length1);
} else {
outputType.makeArbitrary('B', 2, DynkinSimpleType::getDefaultLongRootLengthSquared('B') / length1);
}
} else {
if (numLength1>numLength2) {
outputType.makeArbitrary(
'B', currentComponent.size, DynkinSimpleType::getDefaultLongRootLengthSquared('B') / length1
);
} else {
outputType.makeArbitrary(
'C', currentComponent.size, DynkinSimpleType::getDefaultLongRootLengthSquared('C') / length1
);
}
}
}
// The following code ensures the Dynkin diagram is properly ordered
currentComponent.swapTwoIndices(0, currentEnds[0]);
for (int i = 0; i < currentComponent.size; i ++) {
for (int j = i + 1; j < currentComponent.size; j ++) {
if (!currentComponent[i].scalarProduct(currentComponent[j], this->ambientBilinearForm).isEqualToZero()) {
currentComponent.swapTwoIndices(i + 1, j);
break;
}
}
}
// so far we made sure the entire component is one properly ordered string, starting with the long root.
if (outputType.letter == 'G' || outputType.letter == 'C' ) {
currentComponent.reverseElements(); // <-in G_2 and C_n the short root comes first so we need to reverse elements.
}
}
std::string DynkinDiagramRootSubalgebra::toString(FormatExpressions* format) const {
DynkinType dynkinType;
dynkinType.makeZero();
for (int j = 0; j < this->simpleComponentTypes.size; j ++) {
dynkinType.addMonomial(this->simpleComponentTypes[j], 1);
}
return dynkinType.toString(format);
}
bool DynkinDiagramRootSubalgebra::checkInitialization() const {
MacroRegisterFunctionWithName("DynkinDiagramRootSubalgebra::checkInitialization");
if (this->ambientRootSystem.size != 0) {
if (this->ambientBilinearForm.numberOfRows != this->ambientRootSystem[0].size) {
global.fatal << "Ambient bilinear form of Dynkin subdiagram not initialized. " << global.fatal;
}
}
return true;
}
void DynkinDiagramRootSubalgebra::computeDiagramInputIsSimple(const Vectors<Rational>& simpleBasisInput) {
MacroRegisterFunctionWithName("DynkinDiagramRootSubalgebra::computeDiagramInputIsSimple");
this->checkInitialization();
this->simpleBasesConnectedComponents.size = 0;
this->simpleBasesConnectedComponents.reserve(simpleBasisInput.size);
for (int i = 0; i < simpleBasisInput.size; i ++) {
int indexFirstComponentConnectedToRoot = - 1;
for (int j = 0; j < this->simpleBasesConnectedComponents.size; j ++) {
if (this->simpleBasesConnectedComponents[j].containsVectorNonPerpendicularTo(
simpleBasisInput[i], this->ambientBilinearForm)
) {
if (indexFirstComponentConnectedToRoot == - 1) {
indexFirstComponentConnectedToRoot = j;
this->simpleBasesConnectedComponents[j].addOnTop(simpleBasisInput[i]);
} else {
this->simpleBasesConnectedComponents[indexFirstComponentConnectedToRoot].addListOnTop(
this->simpleBasesConnectedComponents[j]
);
this->simpleBasesConnectedComponents.removeIndexSwapWithLast(j);
j --;
}
}
}
if (indexFirstComponentConnectedToRoot == - 1) {
this->simpleBasesConnectedComponents.setSize(this->simpleBasesConnectedComponents.size + 1);
this->simpleBasesConnectedComponents.lastObject()->size = 0;
this->simpleBasesConnectedComponents.lastObject()->addOnTop(simpleBasisInput[i]);
}
}
this->computeDynkinStrings();
this->sort();
this->computeDynkinStrings();
DynkinType tempType;
this->getDynkinType(tempType);
if (tempType.isEqualToZero() && simpleBasisInput.size != 0) {
global.fatal
<< "Dynkin type of zero but the roots generating the type are: "
<< simpleBasisInput.toString() << global.fatal;
}
}
bool DynkinDiagramRootSubalgebra::letterIsDynkinGreaterThanLetter(char letter1, char letter2) {
if ((letter1 == 'B' || letter1 == 'D') && (letter2 == 'B' || letter2 == 'D') ) {
if (letter1 == letter2) {
return false;
}
if (letter1 == 'B') {
return true;
} else {
return false;
}
}
return letter1 > letter2;
}
bool DynkinDiagramRootSubalgebra::isGreaterThan(DynkinDiagramRootSubalgebra& right) {
if (this->rankTotal() > right.rankTotal()) {
return true;
}
if (this->rankTotal() < right.rankTotal()) {
return false;
}
if (this->simpleComponentTypes.size != this->simpleBasesConnectedComponents.size) {
global.fatal
<< "Simple component types do "
<< "not match number of connected components. " << global.fatal;
}
for (int i = 0; i < this->simpleComponentTypes.size; i ++) {
if (this->simpleBasesConnectedComponents[i].size > right.simpleBasesConnectedComponents[i].size) {
return true;
}
if (right.simpleBasesConnectedComponents[i].size > this->simpleBasesConnectedComponents[i].size) {
return false;
}
if (this->simpleComponentTypes[i] > right.simpleComponentTypes[i]) {
return true;
}
if (right.simpleComponentTypes[i] > this->simpleComponentTypes[i]) {
return false;
}
}
return false;
}
Rational DynkinDiagramRootSubalgebra::getSizeCorrespondingWeylGroupByFormula() {
Rational output = 1;
for (int i = 0; i < this->simpleBasesConnectedComponents.size; i ++) {
output *= WeylGroupData::sizeByFormulaOrNegative1(
this->simpleComponentTypes[i].letter, this->simpleComponentTypes[i].rank
);
}
return output;
}
void DynkinDiagramRootSubalgebra::getMapFromPermutation(
Vectors<Rational>& domain,
Vectors<Rational>& range,
List<int>& permutation, List<List<List<int > > >& automorphisms,
SelectionWithDifferentMaxMultiplicities& autosPermutations,
DynkinDiagramRootSubalgebra& right
) {
for (int i = 0; i < this->simpleBasesConnectedComponents.size; i ++) {
for (int j = 0; j < this->simpleBasesConnectedComponents[i].size; j ++) {
if (this->simpleBasesConnectedComponents[i].size != right.simpleBasesConnectedComponents[permutation[i]].size) {
global.fatal << "Connected components simple bases sizes do not match. " << global.fatal;
}
domain.addOnTop( this->simpleBasesConnectedComponents[i][j]);
int indexTargetComponent = permutation[i];
int indexAutomorphismInComponent = autosPermutations.multiplicities[i];
int indexRoot = automorphisms[i][indexAutomorphismInComponent][j];
range.addOnTop(right.simpleBasesConnectedComponents[indexTargetComponent][indexRoot]);
}
}
}
void DynkinDiagramRootSubalgebra::computeDiagramTypeModifyInput(Vectors<Rational>& inputRoots, WeylGroupData& weylGroup) {
MacroRegisterFunctionWithName("DynkinDiagramRootSubalgebra::computeDiagramTypeModifyInput");
this->ambientRootSystem = weylGroup.rootSystem;
this->ambientBilinearForm = weylGroup.cartanSymmetric;
weylGroup.transformToSimpleBasisGenerators(inputRoots, weylGroup.rootSystem);
this->computeDiagramInputIsSimple(inputRoots);
}
void DynkinDiagramRootSubalgebra::computeDiagramTypeModifyInputRelative(
Vectors<Rational>& inputOutputSimpleWeightSystem,
const HashedList<Vector<Rational> >& weightSystem,
const Matrix<Rational>& bilinearForm
) {
MacroRegisterFunctionWithName("DynkinDiagramRootSubalgebra::computeDiagramTypeModifyInputRelative");
this->ambientRootSystem = weightSystem;
this->ambientBilinearForm = bilinearForm;
WeylGroupData::transformToSimpleBasisGeneratorsArbitraryCoordinates(inputOutputSimpleWeightSystem, weightSystem);
this->computeDiagramInputIsSimple(inputOutputSimpleWeightSystem);
}
void DynkinDiagramRootSubalgebra::computeDynkinStrings() {
MacroRegisterFunctionWithName("DynkinDiagramRootSubalgebra::computeDynkinStrings");
this->indicesThreeNodes.setSize(this->simpleBasesConnectedComponents.size);
this->simpleComponentTypes.setSize(this->simpleBasesConnectedComponents.size);
this->indicesEnds.setSize(this->simpleBasesConnectedComponents.size);
for (int i = 0; i < this->simpleBasesConnectedComponents.size; i ++) {
this->computeDynkinString(i);
}
}
bool DynkinDiagramRootSubalgebra::operator==(const DynkinDiagramRootSubalgebra& right) const {
if (right.simpleBasesConnectedComponents.size != this->simpleBasesConnectedComponents.size) {
return false;
}
for (int i = 0; i < this->simpleBasesConnectedComponents.size; i ++) {
bool tempBool =
((this->simpleBasesConnectedComponents[i].size == right.simpleBasesConnectedComponents[i].size) &&
(this->simpleComponentTypes[i] == right.simpleComponentTypes[i]));
if (!tempBool) {
return false;
}
}
return true;
}
void DynkinDiagramRootSubalgebra::getDynkinType(DynkinType& output) const {
output.makeZero();
output.setExpectedSize(this->simpleComponentTypes.size);
for (int i = 0; i < this->simpleComponentTypes.size; i ++) {
output.addMonomial(this->simpleComponentTypes[i], 1);
}
}
void DynkinDiagramRootSubalgebra::getAutomorphism(List<List<int> >& output, int index) {
Vectors<Rational>& currentComponent = this->simpleBasesConnectedComponents[index];
DynkinSimpleType& currentStrinG = this->simpleComponentTypes[index];
List<int> permutation;
permutation.setSize(currentComponent.size);
output.size = 0;
for (int i = 0; i < currentComponent.size; i ++) {
permutation[i] = i;
}
output.addOnTop(permutation);
if (currentStrinG.letter == 'A' && currentComponent.size != 1) {
permutation.reverseElements();
output.addOnTop(permutation);
}
if (currentStrinG.letter == 'D') {
if (currentComponent.size == 4) {
//the automorphism group of the Dynkin Diagram is S3
permutation[1] = 2;
permutation[2] = 3;
permutation[3] = 1;
output.addOnTop(permutation);
permutation[1] = 1;
permutation[2] = 3;
permutation[3] = 2;
output.addOnTop(permutation);
permutation[1] = 2;
permutation[2] = 1;
permutation[3] = 3;
output.addOnTop(permutation);
permutation[1] = 3;
permutation[2] = 1;
permutation[3] = 2;
output.addOnTop(permutation);
permutation[1] = 3;
permutation[2] = 2;
permutation[3] = 1;
output.addOnTop(permutation);
} else {
permutation[currentComponent.size - 2] = currentComponent.size - 1;
permutation[currentComponent.size - 1] = currentComponent.size - 2;
output.addOnTop(permutation);
}
}
if (currentStrinG.letter == 'E' && currentStrinG.rank == 6) {
permutation[1] = 3;
permutation[2] = 4;
permutation[3] = 1;
permutation[4] = 2;
output.addOnTop(permutation);
}
}
void DynkinDiagramRootSubalgebra::getAutomorphisms(List<List<List<int> > >& output) {
output.setSize(this->simpleBasesConnectedComponents.size);
for (int i = 0; i < this->simpleBasesConnectedComponents.size; i ++) {
this->getAutomorphism(output[i], i);
}
}
int DynkinDiagramRootSubalgebra::rankTotal() {
int result = 0;
for (int i = 0; i < this->simpleBasesConnectedComponents.size; i ++) {
result += this->simpleBasesConnectedComponents[i].size;
}
return result;
}
int DynkinDiagramRootSubalgebra::numberRootsGeneratedByDiagram() {
int result = 0;
if (this->simpleBasesConnectedComponents.size != this->simpleComponentTypes.size) {
global.fatal << "Number of simple connected components does not match the number of types. " << global.fatal;
}
for (int i = 0; i < this->simpleComponentTypes.size; i ++) {
int Rank = this->simpleBasesConnectedComponents[i].size;
if (this->simpleComponentTypes[i].letter == 'A') {
result += Rank * (Rank + 1);
}
if (this->simpleComponentTypes[i].letter == 'B' || this->simpleComponentTypes[i].letter == 'C') {
result += Rank * Rank * 2;
}
if (this->simpleComponentTypes[i].letter == 'D') {
result += Rank * (Rank - 1) * 2;
}
if (this->simpleComponentTypes[i].letter == 'E') {
if (Rank == 6) {
result += 72;
}
if (Rank == 7) {
result += 126;
}
if (Rank == 8) {
result += 240;
}
}
if (this->simpleComponentTypes[i].letter == 'F') {
result += 48;
}
if (this->simpleComponentTypes[i].letter == 'G') {
result += 12;
}
}
return result;
}
int DynkinDiagramRootSubalgebra::numberOfThreeValencyNodes(int indexComponent) {
MacroRegisterFunctionWithName("DynkinDiagramRootSubalgebra::numberOfThreeValencyNodes");
Vectors<Rational>& currentComponent = this->simpleBasesConnectedComponents[indexComponent];
int numEnds = 0;
int result = 0;
this->indicesThreeNodes[indexComponent] = - 1;
this->indicesEnds[indexComponent].size = 0;
for (int i = 0; i < currentComponent.size; i ++) {
int counter = 0;
for (int j = 0; j < currentComponent.size; j ++) {
if (currentComponent[i].scalarProduct(currentComponent[j], this->ambientBilinearForm).isNegative()) {
counter ++;
}
}
if (counter > 3) {
Matrix<Rational> gramMatrix;
currentComponent.getGramMatrix(gramMatrix, &this->ambientBilinearForm);
global.fatal << "Corrupt simple basis corresponding to "
<< "Dynkin diagram: the Dynkin diagram should have nodes with "
<< "valency at most 3, but this diagram has node with valency "
<< counter << ". The current component is: "
<< currentComponent.toString()
<< ". The corresponding Symmetric Cartan is: "
<< gramMatrix.toString() << ". " << global.fatal;
}
if (counter == 3) {
result ++;
this->indicesThreeNodes[indexComponent] = i;
}
if (counter <= 1) {
numEnds ++;
this->indicesEnds[indexComponent].addOnTop(i);
}
}
if (result > 1) {
global.fatal << "numEnds variable equals: " << numEnds
<< ", number of three-nodes equals: "
<< result << "; this should not happen. The bilinear form is: "
<< this->ambientBilinearForm.toString() << global.fatal;
}
if (result == 1) {
if (numEnds != 3) {
global.fatal << "numEnds variable equals: " << numEnds
<< ", number of three-nodes equals: "
<< result << "; this should not happen. The bilinear form is: "
<< this->ambientBilinearForm.toString() << global.fatal;
}
} else {
if (numEnds > 2) {
global.fatal << "numEnds variable equals: " << numEnds << ", number of three-nodes equals: "
<< result << "; this should not happen. The bilinear form is: " << this->ambientBilinearForm.toString() << global.fatal;
}
}
return result;
}
bool AffineCone::splitByAffineHyperplane(AffineHyperplane<Rational>& killerPlane, AffineCones& output) {
(void) killerPlane;
(void) output;
return true;
}
bool AffineCone::wallIsInternalInCone(AffineHyperplane<Rational>& killerCandidate) {
(void) killerCandidate;
return true;
}
int AffineCone::getDimension() {
if (this->walls.size == 0) {
return 0;
}
return this->walls.objects[0].affinePoint.size;
}
unsigned int AffineCone::hashFunction() const {
unsigned int result = 0;
int j = 0;
for (int i = 0; i < this->walls.size; i ++) {
result += this->walls[i].hashFunction() * HashConstants::getConstantIncrementCounter(j);
}
return result;
}
void AffineHyperplanes::toString(std::string& output) {
std::stringstream out;
for (int i = 0; i < this->size; i ++) {
std::string tempS;
this->objects[i].toString(tempS);
out << "index: " << i << " " << tempS << "\n";
}
output = out.str();
}
void Permutation::initPermutation(int n) {
this->initPart1(n);
for (int i = 0; i < n; i ++) {
this->capacities[i] = n - i - 1;
this->multiplicities[i] = 0;
}
}
void Permutation::initPermutation(List<int>& disjointSubsets, int totalNumberOfElements) {
this->initPart1(totalNumberOfElements);
int counter = 0;
for (int i = 0; i < disjointSubsets.size; i ++) {
for (int j = 0; j < disjointSubsets[i]; j ++) {
this->capacities[counter] = disjointSubsets[i] - j - 1;
this->multiplicities[counter] = 0;
counter ++;
}
totalNumberOfElements -= disjointSubsets[i];
}
if (totalNumberOfElements != 0) {
global.fatal << "Permutations with 0 elements not allowed. " << global.fatal;
}
}
void Permutation::incrementAndGetPermutation(List<int>& output) {
this->incrementReturnFalseIfPastLast();
this->getPermutationLthElementIsTheImageofLthIndex(output);
}
void Permutation::getPermutationLthElementIsTheImageofLthIndex(List<int>& output) {
int numberOfElements = this->multiplicities.size;
output.setSize(numberOfElements);
for (int i = 0; i < numberOfElements; i ++) {
output[i] = i;
}
for (int i = 0; i < numberOfElements; i ++) {
MathRoutines::swap(output[i], output[i + this->multiplicities[i]]);
}
}
bool WeylGroupData::areMaximallyDominantGroupInner(List<Vector<Rational> >& weights) {
MacroRegisterFunctionWithName("WeylGroup::AreMaximallyDominantInner");
for (int i = 0; i < weights.size; i ++) {
for (int j = 0; j < this->rootsOfBorel.size; j ++) {
if (this->rootScalarCartanRoot(this->rootsOfBorel[j], weights[i]) < 0) {
bool reflectionDoesRaise = true;
for (int k = 0; k < i; k ++) {
if (this->rootScalarCartanRoot(this->rootsOfBorel[j], weights[k]) > 0) {
reflectionDoesRaise = false;
break;
}
}
if (reflectionDoesRaise) {
return false;
}
}
}
}
return true;
}
bool WeylGroupAutomorphisms::checkInitialization() const {
if (this->flagDeallocated) {
global.fatal << "Use after free of Weyl group automorphism. " << global.fatal;
}
if (this->weylGroup == nullptr) {
global.fatal << "Non-initialized Weyl group automorphisms. " << global.fatal;
}
return true;
}
bool WeylGroupAutomorphisms::areMaximallyDominantGroupOuter(List<Vector<Rational> >& weights) {
MacroRegisterFunctionWithName("WeylGroup::areMaximallyDominantGroupOuter");
this->checkInitialization();
MemorySaving<Vectors<Rational> > weightsCopy;
Vector<Rational> zeroWeight;
this->computeOuterAutomorphisms();
zeroWeight.makeZero(this->weylGroup->getDimension());
for (int i = 0; i < weights.size; i ++) {
for (int j = 0; j < this->weylGroup->rootsOfBorel.size; j ++) {
if (this->weylGroup->rootScalarCartanRoot(this->weylGroup->rootsOfBorel[j], weights[i]) < 0) {
bool reflectionDoesRaise = true;
for (int k = 0; k < i; k ++) {
if (this->weylGroup->rootScalarCartanRoot(this->weylGroup->rootsOfBorel[j], weights[k]) > 0) {
reflectionDoesRaise = false;
break;
}
}
if (reflectionDoesRaise) {
return false;
}
}
}
for (int j = 0; j < this->outerAutomorphisms.elements.size; j ++) {
weightsCopy.getElement() = weights;
this->outerAutomorphisms.elements[j].actOnVectorsColumn(weightsCopy.getElement());
bool isGood = true;
for (int k = 0; k < i; k ++) {
if (!(weightsCopy.getElement()[k] - weights[k]).isPositiveOrZero()) {
isGood = false;
break;
}
}
if (!isGood) {
continue;
}
if (!(weightsCopy.getElement()[i] - weights[i]).isGreaterThanLexicographic(zeroWeight)) {
continue;
}
return false;
}
}
return true;
}
void WeylGroupData::generateRootSubsystem(Vectors<Rational>& roots) {
Vector<Rational> root;
int oldsize = roots.size;
for (int i = 0; i < oldsize; i ++) {
roots.addOnTopNoRepetition(- roots[i]);
}
for (int i = 0; i < roots.size; i ++) {
for (int j = 0; j < roots.size; j ++) {
root = roots[i] + roots[j];
if (this->isARoot(root)) {
roots.addOnTopNoRepetition(root);
}
}
}
}
void GeneralizedVermaModuleCharacters::computeQPsFromChamberComplex() {
std::stringstream out;
FormatExpressions format;
Vector<Rational> root;
FileOperations::openFileCreateIfNotPresentVirtual(
this->multiplicitiesMaxOutputReport2, "output/ExtremaPolys.txt", false, true, false
);
this->partialFractions.initFromRoots(this->gModKNegativeWeightsBasisChanged);
out << this->partialFractions.toString(format);
this->partialFractions.split(nullptr);
out << "=" << this->partialFractions.toString(format);
// int totalDim = this->translationS[0].size +this->translationsProjecteD[0].size;
this->quasiPolynomialsSubstituted.setSize(this->projectivizedChambeR.size);
global.fatal << "not implemented fully, crashing to let you know. " << global.fatal;
// this->pfs.chambersOld.initialize();
// this->pfs.chambersOld.directions = this->GmodKNegWeightsBasisChanged;
// this->pfs.chambersOld.SliceEuclideanSpace(false);
// this->qPsNonSubstituted.setSize(this->pfs.chambersOld.size);
// this->qPsSubstituted.setSize(this->pfs.chambersOld.size);
out << "\n\nThe vector partition functions in each chamber follow.";
global.fatal << "Not implemented yet. " << global.fatal;
/*
for (int i = 0; i < this->pfs.chambersOld.size; i ++)
if (this->pfs.chambersOld.objects[i] != 0) {
QuasiPolynomial& currentQPNoSub = this->qPsNonSubstituted.objects[i];
this->qPsSubstituted.objects[i].setSize(this->linearOperators.size);
this->pfs.getVectorPartitionFunction(currentQPNoSub, this->pfs.chambersOld.objects[i]->InternalPoint);
out << "\nChamber " << i + 1 << " with internal point " << this->pfs.chambersOld.objects[i]->InternalPoint.toString() << " the quasipoly is: " << currentQPNoSub.toString(false, false);
for (int k = 0; k< this->linearOperators.size; k++) {
QuasiPolynomial& currentQPSub = this->qPsSubstituted.objects[i].objects[k];
std::stringstream tempStream;
tempStream << "Processing chamber " << i + 1 << " linear operator " << k+ 1;
global.indicatorVariables.ProgressReportStrings[0] = tempStream.str();
global.makeReport();
currentQPNoSub.substitution(this->linearOperatorsExtended.objects[k], this->translationsProjectedBasisChanged[k], this->ExtendedIntegralLatticeMatForM, currentQPSub);
out << "; after substitution we get: " << currentQPSub.toString(false, false);
}
}
*/
//out << "\nThe integral lattice:\n" << integralLattice.toString(false, false);
//this->multiplicitiesMaxOutputReport2.flush();
QuasiPolynomial tempQP;
this->multiplicities.setSize(this->projectivizedChambeR.size);
this->numberNonZeroMultiplicities = 0;
ProgressReport report;
ProgressReport report2;
for (int i = 0; i < this->projectivizedChambeR.size; i ++) {
QuasiPolynomial& currentSum = this->multiplicities.objects[i];
currentSum.makeZeroOverLattice(this->extendedIntegralLatticeMatrixForm);
for (int k = 0; k < this->linearOperators.size; k ++) {
this->getProjection(k, this->projectivizedChambeR.objects[i].getInternalPoint(), root);
root -= this->nonIntegralOriginModificationBasisChanged;
global.fatal << global.fatal ;
int index = - 1; //= this->pfs.chambersOld.GetFirstChamberIndexContainingPoint(root);
if (index != - 1) {
tempQP = this->quasiPolynomialsSubstituted[index][k];
tempQP *= this->coefficients[k];
currentSum += tempQP;
}
std::stringstream tempStream;
tempStream << " Chamber " << i + 1 << " translation " << k + 1;
report.report(tempStream.str());
}
if (!currentSum.isEqualToZero()) {
this->numberNonZeroMultiplicities ++;
}
std::stringstream tempStream;
tempStream << " So far " << i + 1 << " out of " << this->projectivizedChambeR.size << " processed " << this->numberNonZeroMultiplicities
<< " non-zero total.";
report2.report(tempStream.str());
out << "\nChamber " << i + 1 << ": the quasipolynomial is: " << currentSum.toString(false, false);
out << "\nThe chamber is: " << this->projectivizedChambeR[i].toString(&format);
}
// this->projectivizedChamber.ComputeDebugString();
// out << "\n\n" << this->projectivizedChamber.DebugString;
report.report(out.str());
this->multiplicitiesMaxOutputReport2 << out.str();
}
std::string GeneralizedVermaModuleCharacters::computeMultiplicitiesLargerAlgebraHighestWeight(
Vector<Rational>& highestWeightLargerAlgebraFundamentalCoords, Vector<Rational>& parabolicSel
) {
std::stringstream out;
WeylGroupData& largeWeylGroup = this->homomorphism.coDomainAlgebra().weylGroup;
WeylGroupData& smallWeylGroup = this->homomorphism.domainAlgebra().weylGroup;
if (!largeWeylGroup.isOfSimpleType('B', 3)) {
return "Error: algebra is not so(7).";
}
this->initFromHomomorphism(parabolicSel, this->homomorphism);
this->transformToWeylProjectiveStep1();
this->transformToWeylProjectiveStep2();
Vector<Rational> highestWeightLargerAlgSimpleCoords;
highestWeightLargerAlgSimpleCoords = largeWeylGroup.getSimpleCoordinatesFromFundamental(highestWeightLargerAlgebraFundamentalCoords);
Vector<Rational> root;
DrawingVariables drawOps;
int smallDimension = smallWeylGroup.cartanSymmetric.numberOfRows;
Vectors<double> draggableBasis;
draggableBasis.makeEiBasis(smallDimension);
WeylGroupData tmpWeyl;
tmpWeyl.makeArbitrarySimple('A', 2);
drawOps.operations.initDimensions(tmpWeyl.cartanSymmetric, draggableBasis, draggableBasis);
FormatExpressions format;
drawOps.operations.basisProjectionPlane[0][0] = 1;
drawOps.operations.basisProjectionPlane[0][1] = 0;
drawOps.operations.basisProjectionPlane[1][0] = 1;
drawOps.operations.basisProjectionPlane[1][1] = 1;
drawOps.operations.modifyToOrthonormalNoShiftSecond
(drawOps.operations.basisProjectionPlane[1], drawOps.operations.basisProjectionPlane[0]);
drawOps.operations.graphicsUnit = 50;
PiecewiseQuasipolynomial startingPolynomial, substitutedPolynomial, accumulator;
std::string tempS;
startingPolynomial.makeVPF(this->gModKNegativeWeightsBasisChanged, tempS);
Vectors<Rational> translationsProjectedFinal;
translationsProjectedFinal.setSize(this->linearOperators.size);
this->linearOperators[0].actOnVectorColumn(highestWeightLargerAlgSimpleCoords, translationsProjectedFinal[0]);
out << "<br>Input so(7)-highest weight: " << highestWeightLargerAlgSimpleCoords.toString();
out << "<br>Input parabolics selections: " << parabolicSel.toString();
out << "<br>the argument translations: " << this->translationsProjectedBasisChanged.toString();
out << "<br>Element u_w: projection, multiplication by - 1, and basis change of so(7)-highest weight to G_2: "
<< translationsProjectedFinal[0].toString();
startingPolynomial.makeVPF(this->gModKNegativeWeightsBasisChanged, tempS);
drawOps.drawCoordSystemBuffer(drawOps, 2);
Cone smallWeylChamber;
Matrix<Rational> invertedCartan;
invertedCartan = smallWeylGroup.cartanSymmetric;
invertedCartan.invert();
Vectors<Rational> tempVertices;
Vector<Rational> tMpRt;
tMpRt = this->ParabolicSelectionSmallerAlgebra;
for (int i = 0; i < this->ParabolicSelectionSmallerAlgebra.numberOfElements; i ++) {
invertedCartan.getVectorFromRow(i, root);
tempVertices.addOnTop(root);
if (this->ParabolicSelectionSmallerAlgebra.selected[i]) {
tempVertices.addOnTop(- root);
}
}
smallWeylChamber.createFromVertices(tempVertices);
Matrix<Rational> basisChange;
basisChange.initialize(2, 2);
basisChange.elements[0][0] = 1;
basisChange.elements[0][1] = 0;
basisChange.elements[1][0] = 1;
basisChange.elements[1][1] = 1;
basisChange.transpose();
smallWeylChamber.changeBasis(basisChange);
out << "<br> The small Weyl chamber: " << smallWeylChamber.toString(&format);
Vector<Rational> highestWeightSmallAlgBasisChanged = - translationsProjectedFinal[0];
for (int i = 0; i < this->linearOperators.size; i ++) {
this->linearOperators[i].actOnVectorColumn(highestWeightLargerAlgSimpleCoords, translationsProjectedFinal[i]);
translationsProjectedFinal[i] += this->translationsProjectedBasisChanged[i];
drawOps.drawCircleAtVectorBufferRational(- translationsProjectedFinal[i], "red", 3);
}
out << "<br>the translations projected final: " << translationsProjectedFinal.toString();
accumulator.makeZero(startingPolynomial.numberOfVariables);
for (int i = 0; i < this->linearOperators.size; i ++) {
substitutedPolynomial = startingPolynomial;
substitutedPolynomial *= this->coefficients[i];
substitutedPolynomial.translateArgument(translationsProjectedFinal[i]);
accumulator += substitutedPolynomial;
}
accumulator.drawMe(drawOps, 10, &smallWeylChamber, &highestWeightSmallAlgBasisChanged);
out << drawOps.getHTMLDiv(2, false);
out << accumulator.toString(false, true);
return out.str();
}
void GeneralizedVermaModuleCharacters::sortMultiplicities() {
List<Cone> tempList;
tempList = this->projectivizedChambeR;
tempList.quickSortAscending();
List<QuasiPolynomial> tempQPlist;
tempQPlist.setSize(this->multiplicities.size);
for (int i = 0; i < this->multiplicities.size; i ++) {
tempQPlist[i] = this->multiplicities[this->projectivizedChambeR.getIndex(tempList[i])];
}
this->multiplicities = tempQPlist;
this->projectivizedChambeR.clear();
for (int i = 0; i < tempList.size; i ++) {
this->projectivizedChambeR.addOnTop(tempList[i]);
}
}
std::string GeneralizedVermaModuleCharacters::checkMultiplicitiesVsOrbits() {
MacroRegisterFunctionWithName("GeneralizedVermaModuleCharacters::checkMultiplicitiesVsOrbits");
this->checkInitialization();
std::stringstream out;
int totalDimAffine = this->weylLarger->getDimension() + this->weylSmaller->getDimension();
int smallDim = this->weylSmaller->getDimension();
Vector<Rational> normal;
normal.makeZero(totalDimAffine + 1);
Vectors<Rational> newWalls;
ConeComplex tempComplex;
tempComplex = this->projectivizedChambeR;
for (int i = 0; i < this->WeylChamberSmallerAlgebra.normals.size; i ++) {
for (int j = 0; j < smallDim; j ++) {
normal[j] = this->WeylChamberSmallerAlgebra.normals[i][j];
}
newWalls.addOnTop(normal);
tempComplex.splittingNormals.addOnTop(normal);
}
tempComplex.indexLowestNonRefinedChamber = 0;
tempComplex.refine();
out << "Number chambers with new walls: " << tempComplex.size;
out << "\n" << tempComplex.toString();
return out.str();
}
void GeneralizedVermaModuleCharacters::incrementComputation(Vector<Rational>& parabolicSel) {
std::stringstream out;
this->ParabolicLeviPartRootSpacesZeroStandsForSelected = parabolicSel;
switch (this->computationPhase) {
case 0:
// this->parser.hmm.MakeG2InB3(this->parser);
this->initFromHomomorphism(parabolicSel, this->homomorphism);
this->transformToWeylProjectiveStep1();
// out << global.indicatorVariables.StatusString1;
this->transformToWeylProjectiveStep2();
// out << global.indicatorVariables.StatusString1;
break;
case 1:
this->projectivizedChambeR.refine();
this->sortMultiplicities();
out << this->projectivizedChambeR.toString(false);
// out << global.indicatorVariables.StatusString1;
break;
case 2:
this->computeQPsFromChamberComplex();
out << this->elementToStringMultiplicitiesReport();
break;
case 3:
// out << this->checkMultiplicitiesVsOrbits();
break;
case 4:
this->inititializeMaximumComputation();
// out << global.indicatorVariables.StatusString1;
break;
case 5:
this->maximumComputation.findExtremaParametricStep1();
// out << global.indicatorVariables.StatusString1;
break;
case 6:
this->maximumComputation.findExtremaParametricStep3();
// out << global.indicatorVariables.StatusString1;
break;
case 7:
this->maximumComputation.findExtremaParametricStep4();
// out << global.indicatorVariables.StatusString1;
break;
case 8:
this->maximumComputation.findExtremaParametricStep5();
// out << global.indicatorVariables.StatusString1;
break;
default:
break;
}
this->computationPhase ++;
}
GeneralizedVermaModuleCharacters::GeneralizedVermaModuleCharacters() {
this->UpperLimitChambersForDebugPurposes = - 1;
this->computationPhase = 0;
this->NumProcessedConesParam = 0;
this->NumProcessedExtremaEqualOne = 0;
this->numberNonZeroMultiplicities = 0;
this->weylLarger = nullptr;
this->weylSmaller = nullptr;
}
bool GeneralizedVermaModuleCharacters::checkInitialization() const {
if (this->weylLarger == nullptr || this->weylSmaller == nullptr) {
global.fatal << "Use of non-initialized Weyl group within generalized Verma module characters. " << global.fatal;
}
if (this->weylLarger->flagDeallocated || this->weylSmaller->flagDeallocated) {
global.fatal << "Use after free of Weyl group within Verma module characters. " << global.fatal;
}
return true;
}
void GeneralizedVermaModuleCharacters::initFromHomomorphism(
Vector<Rational>& parabolicSelection, HomomorphismSemisimpleLieAlgebra& input
) {
MacroRegisterFunctionWithName("GeneralizedVermaModuleCharacters::initFromHomomorphism");
Vectors<Rational> roots;
this->weylLarger = &input.coDomainAlgebra().weylGroup;
this->weylSmaller = &input.domainAlgebra().weylGroup;
WeylGroupData& weylGroupCoDomain = input.coDomainAlgebra().weylGroup;
// input.projectOntoSmallCartan(weylSmaller.rootsOfBorel, roots);
this->log << "projections: " << roots.toString();
weylGroupCoDomain.group.computeAllElements(false);
this->nonIntegralOriginModificationBasisChanged ="(1/2,1/2)";
Matrix<Rational> projectionBasisChanged;
Vector<Rational> startingWeight, projectedWeight;
FormatExpressions format;
global.fatal << "Not implemented. " << global.fatal;
// SSalgebraModuleOld tempM;
input.computeHomomorphismFromImagesSimpleChevalleyGenerators(nullptr);
global.fatal << "Not implemented. " << global.fatal;
// tempM.InduceFromEmbedding(tempStream, input);
input.getWeightsGmodKInSimpleCoordinatesK(this->gModKNegativeWeights);
// this->log << "weights of g mod k: " << this->GmodKnegativeWeights.toString();
// matrix.actOnVectorsColumn(this->GmodKnegativeWeightS);
this->log << this->gModKNegativeWeights.toString();
this->preferredBasis.setSize(2);
this->preferredBasis[0] = - this->gModKNegativeWeights[1];
this->preferredBasis[1] = - this->gModKNegativeWeights[2];
/////////////////////////////////////////
//this->preferredBasiS[0] ="(1,0)";
//this->preferredBasiS[1] ="(0,1)";
////////////////////////////////////////
this->preferredBasisChangE.assignVectorsToRows(this->preferredBasis);
this->preferredBasisChangE.transpose();
this->preferredBasisChangeInversE = this->preferredBasisChangE;
this->preferredBasisChangeInversE.invert();
this->preferredBasisChangeInversE.actOnVectorsColumn
(this->gModKNegativeWeights, this->gModKNegativeWeightsBasisChanged);
this->log << "\nWeights after basis change: " << this->gModKNegativeWeightsBasisChanged.toString();
for (int i = 0; i < this->gModKNegativeWeights.size; i ++) {
if (this->gModKNegativeWeights[i].isPositiveOrZero()) {
this->gModKNegativeWeights.removeIndexSwapWithLast(i);
i --;
}
}
for (int i = 0; i < this->gModKNegativeWeightsBasisChanged.size; i ++) {
if (this->gModKNegativeWeightsBasisChanged[i].isPositiveOrZero()) {
this->gModKNegativeWeightsBasisChanged.removeIndexSwapWithLast(i);
i --;
}
}
this->log << "\nNegative weights after basis change: " << this->gModKNegativeWeightsBasisChanged.toString();
projectionBasisChanged.initialize(input.domainAlgebra().getRank(), input.coDomainAlgebra().getRank());
for (int i = 0; i < input.coDomainAlgebra().getRank(); i ++) {
startingWeight.makeEi(input.coDomainAlgebra().getRank(), i);
input.projectOntoSmallCartan(startingWeight, projectedWeight);
this->preferredBasisChangeInversE.actOnVectorColumn(projectedWeight);
for (int j = 0; j < projectedWeight.size; j ++) {
projectionBasisChanged.elements[j][i] = projectedWeight[j];
}
}
SubgroupWeylGroupAutomorphismsGeneratedByRootReflectionsAndAutomorphisms subgroup;
this->ParabolicLeviPartRootSpacesZeroStandsForSelected = parabolicSelection;
Matrix<Rational> DualCartanEmbedding;
input.getMapSmallCartanDualToLargeCartanDual(DualCartanEmbedding);
Vector<Rational> ParabolicEvaluationRootImage, root;
ParabolicEvaluationRootImage = this->ParabolicLeviPartRootSpacesZeroStandsForSelected;
this->ParabolicSelectionSmallerAlgebra.initialize(input.domainAlgebra().getRank());
for (int i = 0; i < input.domainAlgebra().getRank(); i ++) {
DualCartanEmbedding.getVectorFromColumn(i, root);
if (ParabolicEvaluationRootImage.scalarEuclidean(root).isPositive()) {
this->ParabolicSelectionSmallerAlgebra.addSelectionAppendNewIndex(i);
}
}
this->log << "\nDual cartan embedding smaller into larger:\n" <<
DualCartanEmbedding.toString(&global.defaultFormat.getElement());
this->log << "\nParabolic subalgebra large algebra: " << this->ParabolicLeviPartRootSpacesZeroStandsForSelected.toString();
root = this->ParabolicSelectionSmallerAlgebra;
this->log << "\nParabolic subalgebra smaller algebra: " << root.toString();
subgroup.makeParabolicFromSelectionSimpleRoots(weylGroupCoDomain, this->ParabolicLeviPartRootSpacesZeroStandsForSelected, - 1);
this->linearOperators.setSize(subgroup.allElements.size);
this->linearOperatorsExtended.setSize(subgroup.allElements.size);
this->translations.setSize(subgroup.allElements.size);
this->translationsProjectedBasisChanged.setSize(subgroup.allElements.size);
this->coefficients.setSize(subgroup.allElements.size);
this->log << " \n******************\nthe subgroup: \n" << subgroup.toString() << "\n\n\n\n\n\n";
this->log << subgroup.toStringBruhatGraph();
this->log << "\nMatrix form of the elements of Weyl group of the Levi part of the parabolic ("
<< subgroup.allElements.size << " elements):\n";
for (int i = 0; i < subgroup.allElements.size; i ++) {
Matrix<Rational>& currentLinearOperator = this->linearOperators[i];
subgroup.getMatrixOfElement(subgroup.allElements[i], currentLinearOperator);
// currentLinearOperator.multiplyOnTheLeft(preferredBasisChangeInverse);
this->log << "\n" << currentLinearOperator.toString(&global.defaultFormat.getElement());
currentLinearOperator.actOnVectorColumn(subgroup.getRho(), this->translations[i]);
this->translations[i] -= subgroup.getRho();
this->translations[i].negate();
projectionBasisChanged.actOnVectorColumn(this->translations[i], this->translationsProjectedBasisChanged[i]);
if (subgroup.allElements[i].generatorsLastAppliedFirst.size % 2 == 0) {
this->coefficients[i] = 1;
} else {
this->coefficients[i] = - 1;
}
}
this->log << "\n\n\nMatrix of the projection operator (basis-changed):\n"
<< projectionBasisChanged.toString(&global.defaultFormat.getElement());
this->log << "\n\n\nMatrix form of the operators $u_w$, "
<< "the translations $\tau_w$ and their projections (" << this->linearOperatorsExtended.size << "):";
//List<Matrix<Rational> > tempList;
for (int k = 0; k < this->linearOperators.size; k ++) {
Matrix<Rational>& currentLO = this->linearOperators[k];
Matrix<Rational>& currentLOExtended = this->linearOperatorsExtended[k];
currentLO.multiplyOnTheLeft(projectionBasisChanged);
currentLO *= - 1;
//tempList.addOnTopNoRepetition(this->linearOperators.objects[i]);
currentLOExtended.makeIdentityMatrix(currentLO.numberOfRows);
currentLOExtended.resize(currentLO.numberOfRows, currentLO.numberOfRows + currentLO.numberOfColumns, true);
for (int i = 0; i < currentLO.numberOfRows; i ++) {
for (int j = 0; j < currentLO.numberOfColumns; j ++) {
currentLOExtended.elements[i][j + currentLO.numberOfRows] = currentLO.elements[i][j];
}
}
this->log << "\n\n" << currentLOExtended.toString(&global.defaultFormat.getElement());
this->log << this->translations[k].toString() << "; " << this->translationsProjectedBasisChanged[k].toString();
}
List<int> displayIndicesReflections;
for (int i = 0; i < this->ParabolicLeviPartRootSpacesZeroStandsForSelected.numberOfElements; i ++) {
if (!this->ParabolicLeviPartRootSpacesZeroStandsForSelected.selected[i]) {
displayIndicesReflections.addOnTop(i + 1);
}
}
Matrix<Polynomial<Rational> > matrixPoly;
Vector<Polynomial<Rational> > tempVect, tempVect2;
tempVect.setSize(input.domainAlgebra().weylGroup.getDimension() + input.coDomainAlgebra().weylGroup.getDimension());
for (int i = 0; i < tempVect.size; i ++) {
tempVect[i].makeMonomial(i, 1, Rational(1));
}
matrixPoly.initialize(input.domainAlgebra().weylGroup.getDimension(), tempVect.size);
Polynomial<Rational> polyZero;
polyZero.makeZero();
format.polynomialAlphabet.setSize(5);
format.polynomialAlphabet[0] = "x_1";
format.polynomialAlphabet[1] = "x_2";
format.polynomialAlphabet[2] = "y_1";
format.polynomialAlphabet[3] = "y_2";
format.polynomialAlphabet[4] = "y_3";
root = subgroup.getRho();
this->linearOperators[0].actOnVectorColumn(root);
this->preferredBasisChangE.actOnVectorColumn(root);
root.negate();
this->log << "\n\nIn $so(7)$-simple basis coordinates, $\\rho_{\\mathfrak l}="
<< subgroup.getRho().toStringLetterFormat("\\eta") << "$; $\\pr(\\rho)="
<< root.toStringLetterFormat("\\alpha") << "$.";
this->log << "\n\n\\begin{longtable}{r|l}$w$ & \\begin{tabular}{c}"
<< "Argument of the vector partition function in (\\ref{eqMultG2inB3General}) =\\\\ $u_w\\circ"
<< tempVect.toString(&format) << "-\\tau_w$ \\end{tabular} \\\\ \\hline \\endhead";
for (int i = 0; i < this->linearOperatorsExtended.size; i ++) {
Matrix<Rational>& currentLoExt = this->linearOperatorsExtended[i];
for (int j = 0; j < currentLoExt.numberOfRows; j ++) {
for (int k = 0; k < currentLoExt.numberOfColumns; k ++) {
matrixPoly.elements[j][k].makeConstant(currentLoExt.elements[j][k]);
}
}
matrixPoly.actOnVectorColumn(tempVect, tempVect2, polyZero);
for (int j = 0; j < tempVect2.size; j ++) {
tempVect2[j] += this->translationsProjectedBasisChanged[i][j];
}
this->log << "\n$" << subgroup.allElements[i].toString() << "$&$"
<< tempVect2.toString(&format) << "$\\\\";
}
this->log << "\\end{longtable}\n\n";
// this->log << "\n\n\nThere are " << tempList.size << " different operators.";
Lattice tempLattice;
weylGroupCoDomain.getIntegralLatticeInSimpleCoordinates(tempLattice);
this->extendedIntegralLatticeMatrixForm.basisRationalForm.makeIdentityMatrix(input.domainAlgebra().getRank());
this->extendedIntegralLatticeMatrixForm.basisRationalForm.directSumWith(tempLattice.basisRationalForm, Rational(0));
this->extendedIntegralLatticeMatrixForm.makeFromMatrix(this->extendedIntegralLatticeMatrixForm.basisRationalForm);
Matrix<Rational> invertedCartan;
invertedCartan = weylGroupCoDomain.cartanSymmetric;
invertedCartan.invert();
Vectors<Rational> WallsWeylChamberLargerAlgebra;
for (int i = 0; i < invertedCartan.numberOfRows; i ++) {
invertedCartan.getVectorFromRow(i, root);
if (ParabolicEvaluationRootImage[i].isEqualToZero()) {
WallsWeylChamberLargerAlgebra.setSize(WallsWeylChamberLargerAlgebra.size + 1);
*WallsWeylChamberLargerAlgebra.lastObject() = root;
}
}
this->log << "\n\n\n**************\nParabolic selection larger algebra:"
<< ParabolicEvaluationRootImage.toString() << "\nWalls Weyl chamber larger algebra: "
<< WallsWeylChamberLargerAlgebra.toString();
this->log << "\n**************\n\n";
Vectors<Rational> rootsGeneratingExtendedLattice;
int totalDim = input.coDomainAlgebra().getRank() + input.domainAlgebra().getRank();
rootsGeneratingExtendedLattice.setSize(totalDim);
this->log << "\n" << invertedCartan.toString(&global.defaultFormat.getElement()) << "\n";
this->log << this->extendedIntegralLatticeMatrixForm.toString();
this->WeylChamberSmallerAlgebra.createFromNormals(WallsWeylChamberLargerAlgebra);
this->log << "\nWeyl chamber larger algebra before projectivizing: " << this->WeylChamberSmallerAlgebra.toString(&format) << "\n";
this->PreimageWeylChamberSmallerAlgebra.normals = this->WeylChamberSmallerAlgebra.normals;
for (int i = 0; i < this->PreimageWeylChamberLargerAlgebra.normals.size; i ++) {
root.makeZero(input.coDomainAlgebra().getRank() + input.domainAlgebra().getRank() + 1);
for (int j = 0; j < input.coDomainAlgebra().getRank(); j ++) {
root[j + input.domainAlgebra().getRank()] = this->PreimageWeylChamberLargerAlgebra.normals[i][j];
}
this->PreimageWeylChamberLargerAlgebra.normals[i] = root;
}
invertedCartan = input.domainAlgebra().weylGroup.cartanSymmetric;
invertedCartan.invert();
roots.size = 0;
Vector<Rational> ParabolicEvaluationRootSmallerAlgebra;
ParabolicEvaluationRootSmallerAlgebra = this->ParabolicSelectionSmallerAlgebra;
for (int i = 0; i < invertedCartan.numberOfRows; i ++) {
input.domainAlgebra().weylGroup.cartanSymmetric.getVectorFromRow(i, root);
if (root.scalarEuclidean(ParabolicEvaluationRootSmallerAlgebra).isEqualToZero()) {
roots.setSize(roots.size + 1);
invertedCartan.getVectorFromRow(i, *roots.lastObject());
}
}
this->preferredBasisChangeInversE.actOnVectorsColumn(roots);
this->log << "**********************\n\n\n";
this->log << "\nthe smaller parabolic selection: " << this->ParabolicSelectionSmallerAlgebra.toString();
this->log << "the Vectors<Rational> generating the chamber walls: " << roots.toString();
this->PreimageWeylChamberSmallerAlgebra.createFromVertices(roots);
this->log << "\nWeyl chamber smaller algebra: " << this->PreimageWeylChamberSmallerAlgebra.toString(&format) << "\n";
this->log << "**********************\n\n\n";
this->log << "\nThe first operator extended:\n"
<< this->linearOperatorsExtended[0].toString(&global.defaultFormat.getElement()) << "\n";
this->log << "\nThe second operator extended:\n"
<< this->linearOperatorsExtended[1].toString(&global.defaultFormat.getElement()) << "\n";
for (int i = 0; i < this->PreimageWeylChamberSmallerAlgebra.normals.size; i ++) {
root.makeZero(input.coDomainAlgebra().getRank() + input.domainAlgebra().getRank() + 1);
for (int j = 0; j < input.domainAlgebra().getRank(); j ++) {
root[j] = this->PreimageWeylChamberSmallerAlgebra.normals[i][j];
}
// for (int j = 0; j < input.range.getRank(); j ++)
// root.objects[j+ input.domain.getRank()] = root2.objects[j];
this->PreimageWeylChamberSmallerAlgebra.normals[i] = root;
}
root.makeEi(
input.coDomainAlgebra().getRank() + input.domainAlgebra().getRank() + 1,
input.coDomainAlgebra().getRank() + input.domainAlgebra().getRank()
);
this->PreimageWeylChamberLargerAlgebra.normals.addOnTop(root);
this->log << "\nPreimage Weyl chamber smaller algebra: " << this->PreimageWeylChamberSmallerAlgebra.toString(&format) << "\n";
this->log << "\nPreimage Weyl chamber larger algebra: " << this->PreimageWeylChamberLargerAlgebra.toString(&format) << "\n";
//global.indicatorVariables.StatusString1NeedsRefresh = true;
//global.indicatorVariables.StatusString1= this->log.str();
//global.makeReport();
}
std::string GeneralizedVermaModuleCharacters::prepareReport() {
std::stringstream out;
FormatExpressions format;
int variableIndex = 0;
format.polynomialAlphabet.setSize(5);
format.polynomialAlphabet[variableIndex] = "x_1";
variableIndex ++;
format.polynomialAlphabet[variableIndex] = "x_2";
variableIndex ++;
format.polynomialAlphabet[variableIndex] = "y_1";
variableIndex ++;
format.polynomialAlphabet[variableIndex] = "y_2";
variableIndex ++;
format.polynomialAlphabet[variableIndex] = "y_3";
variableIndex ++;
out << "\\documentclass{article}\\usepackage{amsmath, longtable, amsfonts, amssymb, verbatim, hyperref}"
<< "\n\\begin{document}\\tiny\n";
out << "\n The chamber complex + multiplicities follow.\n\n\n"
<< "\\begin{longtable}{cc}\\caption{multiplicities of generalized Verma modules $m(x_1,x_2, y_1, y_2, y_3)$"
<< " for $\\gop$ with Dynkin diagram";
std::stringstream tempStream;
tempStream << "(";
for (int i = 0; i < this->ParabolicLeviPartRootSpacesZeroStandsForSelected.numberOfElements; i ++) {
if (this->ParabolicLeviPartRootSpacesZeroStandsForSelected.selected[i]) {
tempStream << "+";
} else {
tempStream << "0";
}
if (i != this->ParabolicLeviPartRootSpacesZeroStandsForSelected.numberOfElements - 1) {
tempStream << ",";
}
}
tempStream << ")";
out << "$" << tempStream.str() << "$ \\label{table" << tempStream.str() << "}}\\\\\n";
out << "Inequlities& $m(x_1,x_2, y_1, y_2, y_3)$\\endhead\n";
int numFoundChambers = 0;
List<int> DisplayIndicesprojectivizedChambers;
for (int i = 0; i < this->projectivizedChambeR.size; i ++) {
QuasiPolynomial& currentMultiplicity = this->multiplicities[i];
if (!currentMultiplicity.isEqualToZero()) {
numFoundChambers ++;
out << "\\hline\\multicolumn{2}{c}{Chamber " << numFoundChambers << "}\\\\\n";
DisplayIndicesprojectivizedChambers.addOnTop(numFoundChambers);
out << this->prepareReportOneCone(format, this->projectivizedChambeR[i]) << "&";
out << "\\begin{tabular}{c}";
out << currentMultiplicity.toString(false, true, &format) << "\\end{tabular}\\\\\n";
} else {
DisplayIndicesprojectivizedChambers.addOnTop(- 1);
}
}
out << "\\end{longtable}\n\n\n Multiplicity free chambers \n";
numFoundChambers = 0;
out << "\n\\begin{longtable}{cc} ";
out << "normals& Multiplicity of module with highest weight $(x_1,x_2)$\\endhead\n";
/* for (int i = 0; i < this->projectivezedChambersSplitByMultFreeWalls.size; i ++) {
root = this->projectivezedChambersSplitByMultFreeWalls.objects[i].getInternalPoint();
bool found = false;
for (int j = 0; j < this->projectivizedChamber.size; j ++)
if (this->projectivizedChamber.objects[j].isInCone(root)) {
if (found)
global.fatal << global.fatal;
found = true;
}
}
for (int i = 0; i < this->projectivizedChamber.size; i ++) {
QuasiPolynomial& multiplicity = this->multiplicityiplicities.objects[i];
if (!multiplicity.isEqualToZero()) {
int indexMultFreeChamber = - 1;
for (int j = 0; j < this->projectivezedChambersSplitByMultFreeWalls.size; j ++) {
root = this->projectivezedChambersSplitByMultFreeWalls.objects[j].getInternalPoint();
if (this->projectivizedChamber.objects[i].isInCone(root)) {
Rational scalar;
scalar =*root.lastObject();
if (scalar != 0)
root/= scalar;
multiplicity.valueOnEachLatticeShift.objects[0].evaluate(root, scalar);
if (scalar<1) {
indexMultFreeChamber = j;
break;
}
}
}
if (indexMultFreeChamber!= - 1) {
numFoundChambers++;
out << "\\hline\\multicolumn{2}{c}{Chamber " << DisplayIndicesprojectivizedChambers.objects[i] << "}\\\\\n";
out << this->prepareReportOneCone(format, this->projectivezedChambersSplitByMultFreeWalls.objects[indexMultFreeChamber]) << "&";
out << multiplicity.toString(false, true, format) << "\\\\\n";
}
}
}*/
out << "Total number of chambers with multiplicity 1 or less: " << numFoundChambers;
out << "\\end{longtable}\n\n\n\n";
out << "\\end{document}";
return out.str();
}
void GeneralizedVermaModuleCharacters::inititializeMaximumComputation() {
MacroRegisterFunctionWithName("GeneralizedVermaModuleCharacters::inititializeMaximumComputation");
this->maximumComputation.numNonParaM = 2;
this->maximumComputation.conesLargerDimension.reserve(this->projectivizedChambeR.size);
this->maximumComputation.LPtoMaximizeLargerDim.reserve(this->multiplicities.size);
this->maximumComputation.conesLargerDimension.setSize(0);
this->maximumComputation.LPtoMaximizeLargerDim.setSize(0);
Lattice ZnLattice;
int affineDimension = 5;
ZnLattice.makeZn(affineDimension);
this->numberNonZeroMultiplicities = 0;
ProgressReport report;
ConeLatticeAndShift currentCLS;
Vector<Rational> latticePtoMax;
for (int i = 0; i < this->multiplicities.size; i ++) {
if (! this->multiplicities[i].isEqualToZero()) {
currentCLS.projectivizedCone = this->projectivizedChambeR[i];
currentCLS.shift.makeZero(affineDimension);
currentCLS.lattice = ZnLattice;
bool tempBool = this->multiplicities[i].valueOnEachLatticeShift[0].getRootFromLinearPolynomialConstantTermLastVariable(latticePtoMax);
if (!tempBool) {
global.fatal << "This should not happen. " << global.fatal;
}
this->maximumComputation.conesLargerDimension.addOnTop(currentCLS);
this->maximumComputation.LPtoMaximizeLargerDim.addOnTop(latticePtoMax);
this->numberNonZeroMultiplicities ++;
std::stringstream out;
out << "Initialized " << i + 1 << " out of " << this->maximumComputation.conesLargerDimension.size
<< "; so far " << this->numberNonZeroMultiplicities << " non-zero multiplicities";
report.report(out.str());
}
}
}
std::string GeneralizedVermaModuleCharacters::prepareReportOneCone(FormatExpressions& format, const Cone& cone) {
std::stringstream out1;
Vector<Rational> normalNoConstant;
int dimSmallerAlgebra = this->linearOperators[0].numberOfRows;
int dimLargerAlgebra = this->linearOperators[0].numberOfColumns;
Rational rationalConstant;
out1 << "\\begin{tabular}{rcl}";
for (int i = 0; i < cone.normals.size; i ++) {
Vector<Rational>& currentNormal = cone.normals[i];
normalNoConstant = currentNormal;
normalNoConstant.setSize(dimSmallerAlgebra + dimLargerAlgebra);
rationalConstant = - (*currentNormal.lastObject());
if (!normalNoConstant.isEqualToZero()) {
out1 << "$" << normalNoConstant.toStringLetterFormat("x", &format) << "$ & $\\geq$ & $"
<< rationalConstant.toString() << "$ \\\\";
}
}
out1 << "\\end{tabular}";
return out1.str();
}
std::string GeneralizedVermaModuleCharacters::elementToStringMultiplicitiesReport() {
if (this->multiplicities.size != this->projectivizedChambeR.size) {
global.fatal << "Bad number of multiplicities. " << global.fatal;
}
std::stringstream out;
FormatExpressions format;
format.polynomialAlphabet.setSize(5);
format.polynomialAlphabet[0] = "x_1";
format.polynomialAlphabet[1] = "x_2";
format.polynomialAlphabet[2] = "y_1";
format.polynomialAlphabet[3] = "y_2";
format.polynomialAlphabet[4] = "y_3";
out << "Number chambers: " << projectivizedChambeR.size << " of them " << this->numberNonZeroMultiplicities << " non-zero.";
int numInequalities = 0;
for (int i = 0; i < this->projectivizedChambeR.size; i ++) {
numInequalities += this->projectivizedChambeR[i].normals.size;
}
out << "\nNumber of inequalities: " << numInequalities;
if (this->ParabolicLeviPartRootSpacesZeroStandsForSelected.cardinalitySelection != 0) {
out << this->prepareReport();
}
return out.str();
}
void GeneralizedVermaModuleCharacters::getSubstitutionFromNonParametricArray(
Matrix<Rational>& output,
Vector<Rational>& outputTranslation,
Vectors<Rational>& nonParameters,
int numberOfParameters
) {
//Reminder: the very last variable comes from the projectivization and contributes to the translation only!
int numNonParams = nonParameters.size;
output.initialize(numberOfParameters + numNonParams - 1, numberOfParameters - 1);
outputTranslation.makeZero(numberOfParameters + numNonParams - 1);
output.makeZero();
for (int l = 0; l < numNonParams; l ++) {
for (int k = 0; k < numberOfParameters - 1; k ++) {
output.elements[l][k] = nonParameters[l][k];
}
outputTranslation[l] = *nonParameters[l].lastObject();
}
for (int l = 0; l < numberOfParameters - 1; l ++) {
output.elements[l + numNonParams][l] = 1;
}
}
void GeneralizedVermaModuleCharacters::getProjection(
int indexOperator, const Vector<Rational>& input, Vector<Rational>& output
) {
Matrix<Rational>& currentExtendedOperator = this->linearOperatorsExtended[indexOperator];
Vector<Rational>& currentTranslation = this->translationsProjectedBasisChanged[indexOperator];
if (input.lastObject()->isEqualToZero()) {
global.fatal << "Last coordinate is not supposed to be be zero. " << global.fatal;
}
output = input;
output /= *output.lastObject();
output.size --;
currentExtendedOperator.actOnVectorColumn(output);
output += currentTranslation;
}
void GeneralizedVermaModuleCharacters::getSubstitutionFromIndex(
PolynomialSubstitution<Rational>& outputSub,
Matrix<LargeInteger>& outputMat,
LargeIntegerUnsigned& outputDen, int index
) {
Matrix<Rational>& matrixOperator = this->linearOperators[index];
int dimLargerAlgebra = matrixOperator.numberOfColumns;
int dimSmallerAlgebra = matrixOperator.numberOfRows;
Vector<Rational>& translation = this->translations[index];
Matrix<Rational> matrix;
matrix.initialize(dimLargerAlgebra + dimSmallerAlgebra + 1, dimSmallerAlgebra);
matrix.makeZero();
for (int j = 0; j < dimSmallerAlgebra; j ++) {
matrix.elements[j][j] = 1;
for (int i = 0; i < dimLargerAlgebra; i ++) {
matrix.elements[i][j] -= matrixOperator.elements[j][i];
}
matrix.elements[dimLargerAlgebra + dimSmallerAlgebra][j] = - translation[j];
}
matrix.getMatrixIntegerWithDenominator(outputMat, outputDen);
outputSub.makeSubstitutionFromMatrixIntegerAndDenominator(outputMat, outputDen);
}
void GeneralizedVermaModuleCharacters::transformToWeylProjective(
int indexOperator, Vector<Rational>& startingNormal, Vector<Rational>& outputNormal
) {
Matrix<Rational> operatorExtended = this->linearOperatorsExtended[indexOperator];
Vector<Rational>& translation = this->translationsProjectedBasisChanged[indexOperator];
//the goddamned sign in front of translation is now checked: it should be + and not -
Rational rationalConstant;
startingNormal.scalarEuclidean(this->nonIntegralOriginModificationBasisChanged + translation, rationalConstant);
operatorExtended.transpose();
outputNormal = startingNormal;
operatorExtended.actOnVectorColumn(outputNormal);
outputNormal.setSize(outputNormal.size + 1);
*outputNormal.lastObject() = - rationalConstant;
}
void GeneralizedVermaModuleCharacters::transformToWeylProjectiveStep1() {
this->smallerAlgebraChamber.initializeFromDirectionsAndRefine(this->gModKNegativeWeightsBasisChanged);
ProgressReport report1;
ProgressReport report2;
report1.report(this->smallerAlgebraChamber.toString(false));
this->log << "Directions for making the chamber basis changed: " << this->gModKNegativeWeightsBasisChanged.toString()
<< "\n Resulting chamber before projectivization:\n "
<< this->smallerAlgebraChamber.toString(false);
report2.report(this->log.str());
}
void GeneralizedVermaModuleCharacters::transformToWeylProjectiveStep2() {
std::stringstream out;
ConeComplex projectivizedChamberFinal;
Cone currentProjectiveCone;
Vectors<Rational> roots;
Vector<Rational> wallToSliceWith;
ProgressReport report;
projectivizedChamberFinal.initialize();
for (int i = 0; i < this->smallerAlgebraChamber.size; i ++) {
Cone& currentAffineCone = this->smallerAlgebraChamber.objects[i];
roots.setSize(currentAffineCone.normals.size);
for (int j = 0; j < currentAffineCone.normals.size; j ++) {
this->transformToWeylProjective(0, currentAffineCone.normals[j], roots[j]);
}
roots.addListOnTop(this->PreimageWeylChamberLargerAlgebra.normals);
report.report(roots.toString());
currentProjectiveCone.createFromNormals(roots);
projectivizedChamberFinal.addNonRefinedChamberOnTopNoRepetition(currentProjectiveCone);
}
for (int i = 0; i < this->PreimageWeylChamberSmallerAlgebra.normals.size; i ++) {
projectivizedChamberFinal.splittingNormals.addOnTop(this->PreimageWeylChamberSmallerAlgebra.normals[i]);
}
out << "projectivized chamber before chopping non-dominant part:\n" << projectivizedChamberFinal.toString(false);
projectivizedChamberFinal.refine();
out << "Refined projectivized chamber before chopping non-dominant part:\n" << projectivizedChamberFinal.toString(false);
for (int i = 0; i < projectivizedChamberFinal.size; i ++) {
const Cone& currentCone = projectivizedChamberFinal[i];
bool isNonDominant = false;
for (int j = 0; j < this->PreimageWeylChamberSmallerAlgebra.normals.size; j ++) {
if (currentCone.getInternalPoint().scalarEuclidean(this->PreimageWeylChamberSmallerAlgebra.normals[j]).isNegative()) {
isNonDominant = true;
break;
}
}
if (isNonDominant) {
projectivizedChamberFinal.popChamberSwapWithLast(i);
i --;
}
}
report.report(out.str());
projectivizedChamberFinal.indexLowestNonRefinedChamber = 0;
this->projectivizedChambeR= projectivizedChamberFinal;
for (int k = 1; k < this->linearOperators.size; k ++) {
for (int i = 0; i < this->smallerAlgebraChamber.size; i ++) {
for (int j = 0; j < this->smallerAlgebraChamber[i].normals.size; j ++) {
this->transformToWeylProjective(k, this->smallerAlgebraChamber[i].normals[j], wallToSliceWith);
wallToSliceWith.scaleNormalizeFirstNonZero();
this->projectivizedChambeR.splittingNormals.addOnTopNoRepetition(wallToSliceWith);
}
}
}
out << "projectivized chamber chopped non-dominant part:\n" << this->projectivizedChambeR.toString(false);
report.report(out.str());
}
| 42.906987
| 190
| 0.705711
|
tmilev
|
55dea5ee7d5b89205a5b25527bb9605705bd7f15
| 99
|
hpp
|
C++
|
include/Block.hpp
|
jwhitlow45/memoryHierarchySimulationMIPS
|
d2504fb33fc517ec85d4b8284ad4ad65fd42ce70
|
[
"Apache-2.0"
] | null | null | null |
include/Block.hpp
|
jwhitlow45/memoryHierarchySimulationMIPS
|
d2504fb33fc517ec85d4b8284ad4ad65fd42ce70
|
[
"Apache-2.0"
] | null | null | null |
include/Block.hpp
|
jwhitlow45/memoryHierarchySimulationMIPS
|
d2504fb33fc517ec85d4b8284ad4ad65fd42ce70
|
[
"Apache-2.0"
] | null | null | null |
#pragma once
struct Block
{
bool valid = false;
int history;
int tag;
int data;
};
| 11
| 23
| 0.585859
|
jwhitlow45
|
55e8b7f448a55316a773ed9c2191e8cfe2b9eb42
| 688
|
cpp
|
C++
|
Dynamic Programming/43 Binomial Coefficient.cpp
|
verma-tanishq/placement-essentials
|
515135f417f002db5e59317cce7660f29b8e902a
|
[
"MIT"
] | 1
|
2021-04-04T16:23:15.000Z
|
2021-04-04T16:23:15.000Z
|
Dynamic Programming/43 Binomial Coefficient.cpp
|
verma-tanishq/placement-essentials
|
515135f417f002db5e59317cce7660f29b8e902a
|
[
"MIT"
] | null | null | null |
Dynamic Programming/43 Binomial Coefficient.cpp
|
verma-tanishq/placement-essentials
|
515135f417f002db5e59317cce7660f29b8e902a
|
[
"MIT"
] | null | null | null |
class Solution{
public:
int nCr(int n, int r){
// code here
int mod = 1000000007;
int C[r+1];
memset(C, 0, sizeof(C));
C[0] = 1; // Top row of Pascal Triangle
if(n<r) return 0;
if((n-r)<r){
r = n-r;
}
// One by constructs remaining rows of Pascal
// Triangle from top to bottom
for (int i = 1; i <= n; i++) {
// Fill entries of current row using previous
// row values
for (int j = min(i, r); j > 0; j--){
// nCj = (n-1)Cj + (n-1)C(j-1);
//nCr = n!/(n-r)!r!
C[j] = (C[j] + C[j-1])%mod;
}
}
return C[r];
}
};
| 24.571429
| 52
| 0.420058
|
verma-tanishq
|
55ecf2c79a960c521ae71f40774dedbcd7d64e07
| 13,471
|
cpp
|
C++
|
src/Renderer.cpp
|
vazgriz/OscilloscopeMusic
|
3a3a1344277892806bd9e734901a36088f85e3f3
|
[
"MIT"
] | 6
|
2021-07-22T14:10:53.000Z
|
2022-01-25T04:34:14.000Z
|
src/Renderer.cpp
|
vazgriz/OscilloscopeMusic
|
3a3a1344277892806bd9e734901a36088f85e3f3
|
[
"MIT"
] | null | null | null |
src/Renderer.cpp
|
vazgriz/OscilloscopeMusic
|
3a3a1344277892806bd9e734901a36088f85e3f3
|
[
"MIT"
] | 1
|
2022-01-23T18:13:54.000Z
|
2022-01-23T18:13:54.000Z
|
#include "Renderer.h"
#include <GLFW/glfw3.h>
#include <unordered_set>
std::vector<std::string> layerNames = {
#ifndef NDEBUG
"VK_LAYER_KHRONOS_validation"
#endif
};
std::vector<std::string> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
bool Renderer::QueueFamilyIndices::isComplete() {
return graphics.has_value() && present.has_value();
}
Renderer::Renderer(GLFWwindow* window) {
m_window = window;
int width, height;
glfwGetFramebufferSize(m_window, &width, &height);
m_width = static_cast<uint32_t>(width);
m_height = static_cast<uint32_t>(height);
createInstance();
createSurface();
createDevice();
recreateSwapchain();
createCommandPool();
createCommandBuffers();
createSemaphores();
createFences();
}
void Renderer::waitIdle() {
vk::Fence::wait(*m_device, m_fences, true);
m_device->waitIdle();
}
void Renderer::resize(uint32_t width, uint32_t height) {
m_device->waitIdle();
m_width = width;
m_height = height;
recreateSwapchain();
}
void Renderer::addRenderer(IRenderer& renderer) {
m_renderers.push_back(&renderer);
}
uint32_t Renderer::acquireImage() {
uint32_t index;
m_swapchain->acquireNextImage(-1, m_acquireSemaphore.get(), nullptr, index);
return index;
}
vk::CommandBuffer& Renderer::recordCommandBuffer(float dt, uint32_t index, vk::Fence& fence) {
fence.wait();
fence.reset();
vk::CommandBuffer& commandBuffer = m_commandBuffers[index];
commandBuffer.reset(vk::CommandBufferResetFlags::None);
vk::CommandBufferBeginInfo beginInfo = {};
commandBuffer.begin(beginInfo);
for (auto renderer : m_renderers) {
renderer->render(dt, commandBuffer);
}
commandBuffer.end();
return commandBuffer;
}
void Renderer::submitCommandBuffer(vk::CommandBuffer& commandBuffer, const vk::Fence& fence) {
vk::SubmitInfo info = {};
info.commandBuffers = { commandBuffer };
info.waitSemaphores = { *m_acquireSemaphore };
info.waitDstStageMask = { vk::PipelineStageFlags::ColorAttachmentOutput };
info.signalSemaphores = { *m_renderSemaphore };
m_graphicsQueue->submit({ info }, &fence);
}
void Renderer::presentImage(uint32_t index) {
vk::PresentInfo info = {};
info.imageIndices = { index };
info.swapchains = { *m_swapchain };
info.waitSemaphores = { *m_renderSemaphore };
m_presentQueue->present(info);
}
void Renderer::render(float dt) {
m_index = acquireImage();
vk::Fence& fence = m_fences[m_index];
vk::CommandBuffer& commandBuffer = recordCommandBuffer(dt, m_index, fence);
submitCommandBuffer(commandBuffer, fence);
presentImage(m_index);
}
uint32_t Renderer::findMemoryType(uint32_t requirements, vk::MemoryPropertyFlags required, vk::MemoryPropertyFlags preferred) {
const std::vector<vk::MemoryType>& types = m_physicalDevice->memoryProperties().memoryTypes;
preferred = preferred | required;
//check if all preferred flags can be sastisfied
for (uint32_t i = 0; i < types.size(); i++) {
const vk::MemoryType& memoryType = types[i];
if (requirements & (1 << i) && (memoryType.propertyFlags & preferred) == preferred) {
return i;
}
}
//check if the required flags can be statisfied
for (uint32_t i = 0; i < types.size(); i++) {
const vk::MemoryType& memoryType = types[i];
if (requirements & (1 << i) && (memoryType.propertyFlags & required) == required) {
return i;
}
}
throw std::runtime_error("Failed to find device memory type");
}
vk::DeviceMemory Renderer::allocateMemory(const vk::MemoryRequirements& requirements, vk::MemoryPropertyFlags required, vk::MemoryPropertyFlags preferred) {
vk::MemoryAllocateInfo info = {};
info.memoryTypeIndex = findMemoryType(requirements.memoryTypeBits, required, preferred);
info.allocationSize = requirements.size;
return vk::DeviceMemory(*m_device, info);
}
std::vector<std::string> Renderer::getRequiredExtensions(GLFWwindow* window) {
uint32_t extensionCount = 0;
const char** requiredExtensions;
requiredExtensions = glfwGetRequiredInstanceExtensions(&extensionCount);
std::vector<std::string> extensions;
for (uint32_t i = 0; i < extensionCount; i++) {
extensions.push_back(requiredExtensions[i]);
}
return extensions;
}
bool Renderer::validationLayersSupported() {
for (auto& layer : vk::Instance::availableLayers()) {
if (layer.layerName == "VK_LAYER_KHRONOS_validation") {
return true;
}
}
return false;
}
void Renderer::createInstance() {
vk::ApplicationInfo appInfo = {};
appInfo.apiVersion = VK_MAKE_VERSION(1, 2, 0);
appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
appInfo.applicationName = "Oscilloscope Music";
vk::InstanceCreateInfo info = {};
info.applicationInfo = &appInfo;
info.enabledExtensionNames = getRequiredExtensions(m_window);
if (validationLayersSupported()) {
info.enabledLayerNames = layerNames;
}
m_instance = std::make_unique<vk::Instance>(info);
}
void Renderer::createSurface() {
VkSurfaceKHR surface;
glfwCreateWindowSurface(m_instance->handle(), m_window, nullptr, &surface);
m_surface = std::make_unique<vk::Surface>(*m_instance, surface);
}
Renderer::QueueFamilyIndices Renderer::findQueueFamilies(const vk::PhysicalDevice& device) {
QueueFamilyIndices indices = {};
for (uint32_t i = 0; i < device.queueFamilies().size(); i++) {
const auto& queueFamily = device.queueFamilies()[i];
if ((queueFamily.queueFlags & vk::QueueFlags::Graphics) != vk::QueueFlags::None) {
indices.graphics = i;
}
if (m_surface->supported(device, i)) {
indices.present = i;
}
if (indices.isComplete()) {
break;
}
}
return indices;
}
bool Renderer::swapchainSupported(const vk::PhysicalDevice& physicalDevice) {
std::unordered_set<std::string> requiredExtensions(deviceExtensions.begin(), deviceExtensions.end());
for (const auto& extension : physicalDevice.availableExtensions()) {
requiredExtensions.erase(extension.extensionName);
}
if (requiredExtensions.size() > 0) return false;
if (m_surface->getFormats(physicalDevice).size() == 0) return false;
if (m_surface->getPresentModes(physicalDevice).size() == 0) return false;
return true;
}
bool Renderer::isDeviceSuitable(const vk::PhysicalDevice& physicalDevice) {
QueueFamilyIndices indices = findQueueFamilies(physicalDevice);
return indices.isComplete() && swapchainSupported(physicalDevice);
}
void Renderer::createDevice() {
m_physicalDevice = nullptr;
for (const auto& device : m_instance->physicalDevices()) {
if (isDeviceSuitable(device)) {
m_physicalDevice = &device;
break;
}
}
if (m_physicalDevice == nullptr) {
throw std::runtime_error("Failed to find a suitable GPU!");
}
QueueFamilyIndices indices = findQueueFamilies(*m_physicalDevice);
std::unordered_set<uint32_t> uniqueIndices = { indices.graphics.value(), indices.present.value() };
std::vector<vk::DeviceQueueCreateInfo> queueInfos;
for (auto index : uniqueIndices) {
vk::DeviceQueueCreateInfo queueInfo = {};
queueInfo.queueFamilyIndex = index;
queueInfo.queueCount = 1;
queueInfo.queuePriorities = { 1.0f };
queueInfos.emplace_back(std::move(queueInfo));
}
vk::DeviceCreateInfo info = {};
info.queueCreateInfos = queueInfos;
info.enabledExtensionNames = deviceExtensions;
m_device = std::make_unique<vk::Device>(*m_physicalDevice, info);
m_graphicsQueueIndex = indices.graphics.value();
m_presentQueueIndex = indices.present.value();
m_transferQueueIndex = indices.graphics.value();
m_graphicsQueue = &m_device->getQueue(indices.graphics.value(), 0);
m_presentQueue = &m_device->getQueue(indices.present.value(), 0);
m_transferQueue = &m_device->getQueue(indices.graphics.value(), 0);
}
vk::SurfaceFormat Renderer::chooseFormat() {
auto& formats = m_surface->getFormats(*m_physicalDevice);
for (const auto& surfaceFormat : formats) {
if (surfaceFormat.format == vk::Format::R8G8B8A8_Srgb && surfaceFormat.colorSpace == vk::ColorSpace::SrgbNonlinear) {
return surfaceFormat;
}
}
return formats[0];
}
vk::PresentMode Renderer::choosePresentMode() {
return vk::PresentMode::Fifo;
}
vk::Extent2D Renderer::chooseExtent(vk::SurfaceCapabilities& capabilities) {
if (capabilities.currentExtent.width != UINT32_MAX) {
return capabilities.currentExtent;
} else {
VkExtent2D actualExtent = { m_width, m_height };
actualExtent.width = std::clamp(m_width, capabilities.minImageExtent.width, capabilities.maxImageExtent.width);
actualExtent.height = std::clamp(m_height, capabilities.minImageExtent.height, capabilities.maxImageExtent.height);
return actualExtent;
}
}
void Renderer::createSwapchain() {
auto capabilities = m_surface->getCapabilities(*m_physicalDevice);
vk::SurfaceFormat surfaceFormat = chooseFormat();
vk::PresentMode presentMode = choosePresentMode();
vk::Extent2D extent = chooseExtent(capabilities);
vk::SwapchainCreateInfo info = {};
info.surface = m_surface.get();
info.imageFormat = surfaceFormat.format;
info.imageColorSpace = surfaceFormat.colorSpace;
info.presentMode = presentMode;
info.imageExtent = extent;
info.minImageCount = std::clamp<uint32_t>(2, capabilities.minImageCount, capabilities.maxImageCount);
info.imageArrayLayers = 1;
info.imageUsage = vk::ImageUsageFlags::ColorAttachment;
QueueFamilyIndices indices = findQueueFamilies(*m_physicalDevice);
if (indices.graphics != indices.present) {
info.imageSharingMode = vk::SharingMode::Concurrent;
info.queueFamilyIndices = { indices.graphics.value(), indices.present.value() };
} else {
info.imageSharingMode = vk::SharingMode::Exclusive;
}
info.preTransform = capabilities.currentTransform;
info.compositeAlpha = vk::CompositeAlphaFlags::Opaque;
info.oldSwapchain = m_swapchain.get();
m_swapchain = std::make_unique<vk::Swapchain>(*m_device, info);
}
void Renderer::createImageViews() {
m_imageViews.clear();
for (auto& image : m_swapchain->images()) {
vk::ImageViewCreateInfo info = {};
info.image = ℑ
info.format = image.format();
info.viewType = vk::ImageViewType::_2D;
info.subresourceRange.aspectMask = vk::ImageAspectFlags::Color;
info.subresourceRange.layerCount = 1;
info.subresourceRange.levelCount = 1;
m_imageViews.emplace_back(*m_device, info);
}
}
void Renderer::createRenderPass() {
vk::AttachmentDescription attachment = {};
attachment.initialLayout = vk::ImageLayout::Undefined;
attachment.finalLayout = vk::ImageLayout::PresentSrcKHR;
attachment.format = m_swapchain->format();
attachment.samples = vk::SampleCountFlags::_1;
attachment.loadOp = vk::AttachmentLoadOp::Clear;
attachment.storeOp = vk::AttachmentStoreOp::Store;
attachment.stencilLoadOp = vk::AttachmentLoadOp::DontCare;
attachment.stencilStoreOp = vk::AttachmentStoreOp::DontCare;
vk::AttachmentReference ref = {};
ref.attachment = 0;
ref.layout = vk::ImageLayout::ColorAttachmentOptimal;
vk::SubpassDescription subpass = {};
subpass.colorAttachments = { ref };
vk::RenderPassCreateInfo info = {};
info.attachments = { attachment };
info.subpasses = { subpass };
m_renderPass = std::make_unique<vk::RenderPass>(*m_device, info);
}
void Renderer::createFramebuffers() {
m_framebuffers.clear();
for (auto& imageView : m_imageViews) {
vk::FramebufferCreateInfo info = {};
info.attachments = { imageView };
info.width = m_swapchain->extent().width;
info.height = m_swapchain->extent().height;
info.renderPass = m_renderPass.get();
info.layers = 1;
m_framebuffers.emplace_back(*m_device, info);
}
}
void Renderer::recreateSwapchain() {
createSwapchain();
createImageViews();
createRenderPass();
createFramebuffers();
}
void Renderer::createCommandPool() {
vk::CommandPoolCreateInfo info = {};
info.flags = vk::CommandPoolCreateFlags::ResetCommandBuffer;
info.queueFamilyIndex = m_graphicsQueueIndex;
m_commandPool = std::make_unique<vk::CommandPool>(*m_device, info);
}
void Renderer::createCommandBuffers() {
for (size_t i = 0; i < m_swapchain->images().size(); i++) {
vk::CommandBufferAllocateInfo info = {};
info.commandBufferCount = 1;
info.commandPool = m_commandPool.get();
m_commandBuffers.emplace_back(std::move(m_commandPool->allocate(info)[0]));
}
}
void Renderer::createSemaphores() {
vk::SemaphoreCreateInfo info = {};
m_acquireSemaphore = std::make_unique<vk::Semaphore>(*m_device, info);
m_renderSemaphore = std::make_unique<vk::Semaphore>(*m_device, info);
}
void Renderer::createFences() {
vk::FenceCreateInfo info = {};
info.flags = vk::FenceCreateFlags::Signaled;
for (size_t i = 0; i < m_swapchain->images().size(); i++) {
m_fences.emplace_back(*m_device, info);
}
}
| 31.771226
| 156
| 0.687254
|
vazgriz
|
55edeff8b0c5e5d259807cf15bce2327544e5407
| 144
|
hpp
|
C++
|
src/window/Common.hpp
|
Vasile2k/Luminica
|
13250c6b536b0634e2f4ea95b7b75b0dee18705d
|
[
"Apache-2.0"
] | 5
|
2019-01-13T09:53:05.000Z
|
2021-01-25T11:02:12.000Z
|
src/window/Common.hpp
|
Vasile2k/Luminica
|
13250c6b536b0634e2f4ea95b7b75b0dee18705d
|
[
"Apache-2.0"
] | null | null | null |
src/window/Common.hpp
|
Vasile2k/Luminica
|
13250c6b536b0634e2f4ea95b7b75b0dee18705d
|
[
"Apache-2.0"
] | null | null | null |
#pragma once
// Forward declaration of classes used here
class EventListener;
class EventHandler;
class GlobalGLFWEventHandler;
class Window;
| 16
| 43
| 0.819444
|
Vasile2k
|
55eefbf3c6da7b480e087f92ff5e6ddb0d8aaa0b
| 1,084
|
hpp
|
C++
|
src/cpp/llnms-gui/core/DataContainer.hpp
|
marvins/LLNMS
|
ebc15418e1a5dddafdb3e55cea4e8cb71f619b2d
|
[
"MIT"
] | null | null | null |
src/cpp/llnms-gui/core/DataContainer.hpp
|
marvins/LLNMS
|
ebc15418e1a5dddafdb3e55cea4e8cb71f619b2d
|
[
"MIT"
] | null | null | null |
src/cpp/llnms-gui/core/DataContainer.hpp
|
marvins/LLNMS
|
ebc15418e1a5dddafdb3e55cea4e8cb71f619b2d
|
[
"MIT"
] | 1
|
2020-12-16T09:28:26.000Z
|
2020-12-16T09:28:26.000Z
|
/**
* @file DataContainer.hpp
* @author Marvin Smith
* @date 1/27/2014
*/
#ifndef __SRC_CPP_LLNMSGUI_CORE_DATACONTAINER_HPP__
#define __SRC_CPP_LLNMSGUI_CORE_DATACONTAINER_HPP__
#include "GUI_Settings.hpp"
#include <string>
/**
* @class DataContainer
*
* Contains all of the required global data which is used by the program.
* To add to your own widgets, just extern the class as shown in the main
* gui widgets.
*/
class DataContainer {
public:
/**
* Default Constructor
*/
DataContainer();
/**
* Load the configuration file
*/
void load( int argc, char* argv[], const std::string& filename );
/**
* Write configuration file
*/
void write_config_file( );
/**
* Create baseline file structure
*/
void create_file_structure();
/// GUI Data Storage
GUI_Settings gui_settings;
/// Tells us if we found a config file
bool config_file_found;
};
#endif
| 18.689655
| 74
| 0.582103
|
marvins
|
55f0deced202a79c9257d14c052924cf4ccacd5f
| 2,282
|
cpp
|
C++
|
raii/cpp/main.cpp
|
LoLei/design-patterns-examples
|
213241ab94c8a5e74a3faa9c5f554d557e60b753
|
[
"MIT"
] | 3
|
2020-02-11T20:37:13.000Z
|
2020-07-31T14:16:51.000Z
|
raii/cpp/main.cpp
|
LoLei/design-patterns-examples
|
213241ab94c8a5e74a3faa9c5f554d557e60b753
|
[
"MIT"
] | null | null | null |
raii/cpp/main.cpp
|
LoLei/design-patterns-examples
|
213241ab94c8a5e74a3faa9c5f554d557e60b753
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <mutex>
#include <memory>
#include "noncopyable.h"
template <class T>
class AutoDeleter : NonCopyable
{
public:
AutoDeleter(T* p = 0) : to_delete_(p) {}
~AutoDeleter() throw() { delete to_delete_; }
// throw() specifies that the destructor must not throw any exception
private:
T *to_delete_;
};
class ScopedLock : NonCopyable
{
public:
ScopedLock(std::mutex & m) : lock_(m) { lock_.lock(); }
~ScopedLock() throw () { lock_.unlock(); }
private:
std::mutex& lock_;
};
class Resource
{
public:
Resource() { std::cout << "Resource acquired" << std::endl; }
~Resource() { std::cout << "Resource destroyed" << std::endl; }
bool resourceMethod();
};
bool Resource::resourceMethod()
{
std::mutex m;
ScopedLock scoped_lock(m);
bool sum_ting_wong = true;
if(sum_ting_wong)
{
// Would return without lock released, but since the scope is ended the
// scoped lock destuctor unlocks the lock.
return false;
}
// Also since this method is a member function it might also return early
// due to the object to which the method belongs being destroyed
// Maybe would have released lock only now
// m.unlock()
return true;
};
/**
* Example showing own implementation of auto deletion and scoped lock
*/
void selfMadeExample()
{
Resource *r = new Resource();
AutoDeleter<Resource> auto_del(r);
// Do something...
r->resourceMethod();
// No need to call delete, destructor of AutoDeleter will delete the Resource
// on the heap. AutoDeleter is on the stack, stack unwinding destroys
// objects on the stack when their scope ends (In C++)
return;
}
/**
* Example showing C++'s STL idioms of handling auto deletion and scoped locking
* std::unique_ptr, std::shared_ptr
* std::lock_guard
*/
void stlExample()
{
// unique_ptr will delete the resource it is managing when it goes out of
// scope
std::unique_ptr<Resource> r(new Resource);
std::mutex m;
// lock_guard releases the mutex when it goes out of scope, e.g. early returns
// due to exceptions, etc.
// (The lock is also acquired on initialization, i.e. RAII)
std::lock_guard<std::mutex> guarded_lock(m);
return;
}
int main()
{
selfMadeExample();
stlExample();
return 0;
}
| 24.021053
| 80
| 0.677476
|
LoLei
|
360617bcf4c696bff717d0344f3d470e5fa3aa0a
| 546
|
cpp
|
C++
|
src/c/schemas/ModioDependency.cpp
|
nlspartanNL/SDK
|
291f1e5869210baedbb5447f8f7388f50ec93950
|
[
"MIT"
] | 1
|
2018-10-05T15:59:04.000Z
|
2018-10-05T15:59:04.000Z
|
src/c/schemas/ModioDependency.cpp
|
nlspartanNL/SDK
|
291f1e5869210baedbb5447f8f7388f50ec93950
|
[
"MIT"
] | null | null | null |
src/c/schemas/ModioDependency.cpp
|
nlspartanNL/SDK
|
291f1e5869210baedbb5447f8f7388f50ec93950
|
[
"MIT"
] | 1
|
2020-11-06T01:42:10.000Z
|
2020-11-06T01:42:10.000Z
|
#include "c/schemas/ModioDependency.h"
extern "C"
{
void modioInitDependency(ModioDependency* dependency, nlohmann::json dependency_json)
{
dependency->mod_id = 0;
if(modio::hasKey(dependency_json, "mod_id"))
dependency->mod_id = dependency_json["mod_id"];
dependency->date_added = 0;
if(modio::hasKey(dependency_json, "date_added"))
dependency->date_added = dependency_json["date_added"];
}
void modioFreeDependency(ModioDependency* dependency)
{
if(dependency)
{
//No pointers
}
}
}
| 22.75
| 87
| 0.686813
|
nlspartanNL
|
360b160391f550836317bf554f775507fca2dab7
| 3,799
|
cpp
|
C++
|
IDE/Contents/Source/PolycodeEditorManager.cpp
|
MattDBell/Polycode
|
fc66547813a34a2388c9a45ec0b69919ce3253b2
|
[
"MIT"
] | 1
|
2020-04-30T23:05:26.000Z
|
2020-04-30T23:05:26.000Z
|
IDE/Contents/Source/PolycodeEditorManager.cpp
|
MattDBell/Polycode
|
fc66547813a34a2388c9a45ec0b69919ce3253b2
|
[
"MIT"
] | null | null | null |
IDE/Contents/Source/PolycodeEditorManager.cpp
|
MattDBell/Polycode
|
fc66547813a34a2388c9a45ec0b69919ce3253b2
|
[
"MIT"
] | null | null | null |
/*
Copyright (C) 2012 by Ivan Safrin
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 "PolycodeEditorManager.h"
PolycodeEditorManager::PolycodeEditorManager() : EventDispatcher() {
currentEditor = NULL;
}
PolycodeEditorManager::~PolycodeEditorManager() {
}
PolycodeEditorFactory *PolycodeEditorManager::getEditorFactoryForExtension(String extension) {
for(int i=0;i < editorFactories.size(); i++) {
PolycodeEditorFactory *factory = editorFactories[i];
if(factory->canHandleExtension(extension)) {
return factory;
}
}
return NULL;
}
PolycodeEditor *PolycodeEditorManager::createEditorForExtension(String extension) {
for(int i=0;i < editorFactories.size(); i++) {
PolycodeEditorFactory *factory = editorFactories[i];
if(factory->canHandleExtension(extension)) {
PolycodeEditor *editor = factory->createEditor();
openEditors.push_back(editor);
editor->addEventListener(this, Event::CHANGE_EVENT);
return editor;
}
}
return NULL;
}
void PolycodeEditorManager::destroyEditor(PolycodeEditor* editor) {
for(int i=0; i < openEditors.size();i++) {
if(openEditors[i] == editor) {
openEditors.erase(openEditors.begin()+i);
delete editor;
dispatchEvent(new Event(), Event::CHANGE_EVENT);
return;
}
}
}
bool PolycodeEditorManager::hasUnsavedFiles() {
for(int i=0; i < openEditors.size();i++) {
PolycodeEditor *editor = openEditors[i];
if(editor->hasChanges())
return true;
}
return false;
}
void PolycodeEditorManager::saveAll() {
for(int i=0; i < openEditors.size();i++) {
PolycodeEditor *editor = openEditors[i];
editor->saveFile();
}
}
void PolycodeEditorManager::saveFilesForProject(PolycodeProject *project) {
for(int i=0; i < openEditors.size(); i++) {
if(openEditors[i]->hasChanges() && openEditors[i]->parentProject == project)
openEditors[i]->saveFile();
}
}
bool PolycodeEditorManager::hasUnsavedFilesForProject(PolycodeProject *project) {
for(int i=0; i < openEditors.size();i++) {
PolycodeEditor *editor = openEditors[i];
if(editor->hasChanges() && editor->parentProject == project)
return true;
}
return false;
}
void PolycodeEditorManager::handleEvent(Event *event) {
dispatchEvent(new Event(), Event::CHANGE_EVENT);
}
void PolycodeEditorManager::setCurrentEditor(PolycodeEditor *editor, bool sendChangeEvent) {
currentEditor = editor;
if(sendChangeEvent){
dispatchEvent(new Event(), Event::CHANGE_EVENT);
}
}
PolycodeEditor *PolycodeEditorManager::getEditorForPath(String path) {
for(int i=0; i < openEditors.size();i++) {
PolycodeEditor *editor = openEditors[i];
if(editor->getFilePath() == path)
return editor;
}
return NULL;
}
void PolycodeEditorManager::registerEditorFactory(PolycodeEditorFactory *editorFactory) {
editorFactories.push_back(editorFactory);
}
| 30.637097
| 94
| 0.746775
|
MattDBell
|
360cc4113374ee5b8b593b764243d5c6504d9a55
| 13,121
|
cpp
|
C++
|
Renderer/source/Renderer_LightsShadows.cpp
|
VytasSamulionis/TomorrowGame
|
91f17410c82dc69dc4f22e5d88ed3d7d7ee08422
|
[
"MIT"
] | null | null | null |
Renderer/source/Renderer_LightsShadows.cpp
|
VytasSamulionis/TomorrowGame
|
91f17410c82dc69dc4f22e5d88ed3d7d7ee08422
|
[
"MIT"
] | null | null | null |
Renderer/source/Renderer_LightsShadows.cpp
|
VytasSamulionis/TomorrowGame
|
91f17410c82dc69dc4f22e5d88ed3d7d7ee08422
|
[
"MIT"
] | null | null | null |
#include "../include/Renderer.h"
using namespace vs3d;
void Renderer::SetAmbientLight (DWORD _color) {
m_vcm->Flush();
HRESULT hr = m_Device->SetRenderState (D3DRS_AMBIENT, _color);
if (FAILED (hr)) {
THROW_DETAILED_ERROR (ERRC_API_CALL, "SetRenderState() failure.");
}
}
void Renderer::SetLight (DWORD _index, const LIGHT& _light) {
if (!m_Device) {
#ifdef _DEBUG
if (m_Log) {
m_Log->Log ("Error: unable to set a light (device is not created).\n");
}
#endif
THROW_ERROR (ERRC_NO_DEVICE);
}
D3DLIGHT9 light;
int sizeVector = sizeof (float) * 3;
int sizeColor = sizeof (float) * 4;
memcpy (&(light.Diffuse), &(_light.Diffuse), sizeColor);
memcpy (&(light.Specular), &(_light.Specular), sizeColor);
memcpy (&(light.Ambient), &(_light.Ambient), sizeColor);
switch (_light.Type) {
case LIGHT_POINT:
light.Type = D3DLIGHT_POINT;
memcpy (&(light.Position), &(_light.Position), sizeVector);
light.Range = _light.Range;
light.Attenuation0 = _light.Attenuation0;
light.Attenuation1 = _light.Attenuation1;
light.Attenuation2 = _light.Attenuation2;
break;
case LIGHT_SPOT:
light.Type = D3DLIGHT_SPOT;
memcpy (&(light.Direction), &(_light.Direction), sizeVector);
memcpy (&(light.Position), &(_light.Position), sizeVector);
light.Range = _light.Range;
light.Falloff = _light.Falloff;
light.Attenuation0 = _light.Attenuation0;
light.Attenuation1 = _light.Attenuation1;
light.Attenuation2 = _light.Attenuation2;
light.Phi = _light.Phi;
light.Theta = _light.Theta;
break;
case LIGHT_DIRECTIONAL:
light.Type = D3DLIGHT_DIRECTIONAL;
memcpy (&(light.Direction), &(_light.Direction), sizeVector);
break;
default:
#ifdef _DEBUG
if (m_Log) {
m_Log->Log ("Error: Unknown light type.\n");
}
#endif
THROW_ERROR (ERRC_INVALID_PARAMETER);
}
if (FAILED (m_Device->SetLight (_index, &light))) {
#ifdef _DEBUG
if (m_Log) {
m_Log->Log ("Error: SetLight failed. (Renderer::SetLight)\n");
}
#endif
THROW_DETAILED_ERROR (ERRC_API_CALL, "SetLight() failure.");
}
}
void Renderer::EnableLight (DWORD _index, bool _enable) {
if (!m_Device) {
#ifdef _DEBUG
if (m_Log) {
m_Log->Log ("Error: unable to enable a light (device is not created).\n");
}
#endif
THROW_ERROR (ERRC_NO_DEVICE);
}
m_vcm->Flush();
if (FAILED (m_Device->LightEnable (_index, _enable))) {
#ifdef _DEBUG
if (m_Log) {
m_Log->Log ("Error: LightEnable failed. (Renderer::EnableLight).\n");
}
#endif
THROW_DETAILED_ERROR (ERRC_API_CALL, "LightEnable() failure.");
}
}
void Renderer::EnableLighting (bool _enable) {
if (!m_Device) {
#ifdef _DEBUG
if (m_Log) {
m_Log->Log ("Error: device is not created. (Renderer::EnableLighting)\n");
}
#endif
THROW_ERROR (ERRC_NO_DEVICE);
}
m_vcm->Flush();
if (FAILED (m_Device->SetRenderState (D3DRS_LIGHTING, _enable))) {
#ifdef _DEBUG
if (m_Log) {
m_Log->Log ("Error: SetRenderState failed. (Renderer::EnableLighting)\n");
}
#endif
THROW_DETAILED_ERROR (ERRC_API_CALL, "SetRenderState() failure.");
}
}
void Renderer::EnableFog (float _start, float _end, float _density, FOGMODE _mode) {
if (FAILED (m_Device->SetRenderState (D3DRS_FOGSTART, *((DWORD*)(&_start))))) {
THROW_DETAILED_ERROR (ERRC_API_CALL, "SetRenderState() failure.");
}
if (FAILED (m_Device->SetRenderState (D3DRS_FOGEND, *((DWORD*)(&_end))))) {
THROW_DETAILED_ERROR (ERRC_API_CALL, "SetRenderState() failure.");
}
if (FAILED (m_Device->SetRenderState (D3DRS_FOGDENSITY, *((DWORD*)(&_density))))) {
THROW_DETAILED_ERROR (ERRC_API_CALL, "SetRenderState() failure.");
}
if (FAILED (m_Device->SetRenderState (D3DRS_FOGVERTEXMODE, _mode))) {
THROW_DETAILED_ERROR (ERRC_API_CALL, "SetRenderState() failure.");
}
if (FAILED (m_Device->SetRenderState (D3DRS_FOGCOLOR, 0xffffffff))) {
THROW_DETAILED_ERROR (ERRC_API_CALL, "SetRenderState() failure.");
}
if (FAILED(m_Device->SetRenderState (D3DRS_FOGENABLE, TRUE))) {
THROW_DETAILED_ERROR (ERRC_API_CALL, "SetRenderState() failure.");
}
}
void Renderer::DisableFog () {
if (FAILED (m_Device->SetRenderState (D3DRS_FOGENABLE, FALSE))) {
THROW_DETAILED_ERROR (ERRC_API_CALL, "SetRenderState() failure.");
}
}
void Renderer::CreateShadowMap (UINT _size, const MATRIX44& _lightWorldView, float _farClip) {
if (m_ShadowMap.Size != _size) {
/* Create shadow map texture. */
if (m_ShadowMap.Texture) {
m_ShadowMap.Texture->Release ();
m_ShadowMap.Texture = NULL;
}
if (FAILED (D3DXCreateTexture (m_Device, _size, _size, 1, D3DUSAGE_RENDERTARGET, D3DFMT_R32F, D3DPOOL_DEFAULT, &m_ShadowMap.Texture))) {
THROW_DETAILED_ERROR (ERRC_API_CALL, "D3DXCreateTexture() failure.");
}
if (FAILED (m_Device->CreateDepthStencilSurface (_size, _size, m_d3dpp.AutoDepthStencilFormat, D3DMULTISAMPLE_NONE, 0, TRUE, &m_ShadowMap.DepthStencil, NULL))) {
THROW_DETAILED_ERROR (ERRC_API_CALL, "D3DXCreateDepthStencilSurface() failure.");
}
if (FAILED (m_ShadowMap.Texture->GetSurfaceLevel (0, &m_ShadowMap.Surface))) {
THROW_DETAILED_ERROR (ERRC_API_CALL, "GetSurfaceLevel() failure.");
}
if (FAILED (D3DXCreateRenderToSurface (m_Device, _size, _size, D3DFMT_R32F, TRUE, m_d3dpp.AutoDepthStencilFormat, &m_ShadowMap.RenderToSurface))) {
THROW_DETAILED_ERROR (ERRC_API_CALL, "D3DXCreateRenderToSurface() failure.");
}
m_ShadowMap.Size = _size;
}
if (m_ShadowMap.EffectId == INVALID_ID) {
char effectData[] = //"struct VSOutput { float4 Position: POSITION; }; struct PSInput { float4 Position: TEXCOORD0; }; struct PSOutput { float4 Color : COLOR0; }; float4x4 g_LightWorldViewProjection; float g_FarClip; VSOutput ShadowMapVertexShader (float4 inPos : POSITION) { VSOutput output = (VSOutput)0; output.Position = mul(inPos, g_LightWorldViewProjection); return output; } PSOutput ShadowMapPixelShader(PSInput input) { PSOutput output = (PSOutput)0; output.Color = input.Position.z / input.Position.w; return output; } technique ShadowMap { pass Pass0 { VertexShader = compile vs_2_0 ShadowMapVertexShader(); PixelShader = compile ps_2_0 ShadowMapPixelShader(); } }";
"struct VSInput { \
float4 Position : POSITION; \
float3 Normal : NORMAL; \
float2 TexCoord : TEXCOORD0; \
}; \
struct VSOutput { \
float4 Position : POSITION; \
float Depth : TEXCOORD0; \
}; \
\
struct PSInput { \
float Depth : TEXCOORD0; \
}; \
\
struct PSOutput { \
float4 Color : COLOR0; \
}; \
\
float4x4 g_LightWorldViewProjection; \
float g_FarClip; \
\
VSOutput ShadowMapVertexShader (VSInput input) { \
VSOutput output = (VSOutput)0; \
output.Position = mul(input.Position, g_LightWorldViewProjection); \
output.Depth = output.Position.z / g_FarClip; \
return output; \
} \
\
PSOutput ShadowMapPixelShader(PSInput input) { \
PSOutput output = (PSOutput)0; \
output.Color = float4 (input.Depth, 0.0, 0.0, 1.0); \
\
return output; \
} \
\
technique ShadowMap { \
pass Pass0 { \
VertexShader = compile vs_2_0 ShadowMapVertexShader(); \
PixelShader = compile ps_2_0 ShadowMapPixelShader(); \
} \
}";
m_ShadowMap.EffectId = m_vcm->CreateEffect (effectData, sizeof (effectData), false);
}
m_vcm->SetEffectParameter (m_ShadowMap.EffectId, "g_LightWorldViewProjection", (void*)_lightWorldView.data());
m_vcm->SetEffectParameter (m_ShadowMap.EffectId, "g_FarClip", &_farClip);
}
void Renderer::BeginRenderingToShadowMap () {
if (m_ShadowMap.EffectId == INVALID_ID) {
THROW_ERROR (ERRC_NOT_READY);
}
m_vcm->EnableEffect (m_ShadowMap.EffectId, "ShadowMap");
ID3DXEffect* effect = m_vcm->GetActiveEffect ();
D3DVIEWPORT9 viewport;
viewport.X = 0;
viewport.Y = 0;
viewport.Width = m_ShadowMap.Size;
viewport.Height = m_ShadowMap.Size;
viewport.MinZ = 0.0f;
viewport.MaxZ = 1.0f;
if (FAILED (m_Device->GetDepthStencilSurface (&m_ShadowMap.OldDepthStencil))) {
THROW_DETAILED_ERROR (ERRC_API_CALL, "GetDepthStencilSurface() failure.");
}
if (FAILED (m_Device->SetDepthStencilSurface (m_ShadowMap.DepthStencil))) {
THROW_DETAILED_ERROR (ERRC_API_CALL, "SetDepthStencilSurface() failure.");
}
m_Device->Clear (0, NULL, D3DCLEAR_ZBUFFER, 0xffffffff, 1.0f, 0);
if (FAILED (m_ShadowMap.RenderToSurface->BeginScene (m_ShadowMap.Surface, &viewport))) {
THROW_DETAILED_ERROR (ERRC_API_CALL, "BeginScene() failure.");
}
/*UINT numPasses;
if (FAILED (effect->Begin (&numPasses, 0))) {
THROW_DETAILED_ERROR (ERRC_API_CALL, "Begin() failure.");
}
if (FAILED (effect->BeginPass (0))) {
THROW_DETAILED_ERROR (ERRC_API_CALL, "BeginPass() failure.");
}*/
}
void Renderer::EndRenderingToShadowMap () {
/*ID3DXEffect* effect = m_vcm->GetActiveEffect ();
effect->EndPass ();
effect->End ();*/
m_vcm->Flush ();
if (FAILED (m_ShadowMap.RenderToSurface->EndScene (D3DX_FILTER_NONE))) {
THROW_DETAILED_ERROR (ERRC_API_CALL, "EndScene() failure.");
}
/*if (FAILED (D3DXSaveTextureToFileA ("texture.jpg", D3DXIFF_JPG, m_ShadowMap.Texture, NULL))) {
THROW_ERROR (ERRC_API_CALL);
}*/
if (FAILED (m_Device->SetDepthStencilSurface (m_ShadowMap.OldDepthStencil))) {
THROW_DETAILED_ERROR (ERRC_API_CALL, "SetDepthStencilSurface() failure.");
}
m_vcm->SetSkin (INVALID_ID);
}
void Renderer::SetShadowMap (UINT _effectId, const char* _shadowMapParamName) {
ID3DXEffect* effect = m_vcm->GetEffect (_effectId);
D3DXHANDLE shadowMap = effect->GetParameterByName (NULL, _shadowMapParamName);
if (FAILED (effect->SetTexture (shadowMap, m_ShadowMap.Texture))) {
THROW_DETAILED_ERROR (ERRC_API_CALL, "SetTexture() failure.");
}
}
| 49.700758
| 687
| 0.520616
|
VytasSamulionis
|
36181aa76ed339ce59f7271d8ceb48715b7d6c56
| 331
|
cpp
|
C++
|
src/io.cpp
|
dk949/scotch
|
e5a60da9920f0eeaa692bfcf56219338307e573b
|
[
"BSD-3-Clause"
] | null | null | null |
src/io.cpp
|
dk949/scotch
|
e5a60da9920f0eeaa692bfcf56219338307e573b
|
[
"BSD-3-Clause"
] | null | null | null |
src/io.cpp
|
dk949/scotch
|
e5a60da9920f0eeaa692bfcf56219338307e573b
|
[
"BSD-3-Clause"
] | null | null | null |
#include "io.hpp"
#include "error.hpp"
Io::Io(std::unique_ptr<Output> &&output, std::unique_ptr<ErrorHandler> &&err)
: m_output(std::move(output))
, m_error(std::move(err)) { }
void Io::output(const std::string &str) {
m_output->output(str);
}
void Io::error(const Error &err) {
m_error->error(err);
}
| 19.470588
| 77
| 0.625378
|
dk949
|
36194f772f330ff4cbcf95a00b976863be824b3e
| 14,988
|
cpp
|
C++
|
ModSource/breakingpoint_map_objects/tracked2/T34/config.cpp
|
nrailuj/breakingpointmod
|
e102e106b849ca78deb3cb299f3ae18c91c3bfe9
|
[
"Naumen",
"Condor-1.1",
"MS-PL"
] | 70
|
2017-06-23T21:25:05.000Z
|
2022-03-27T02:39:33.000Z
|
ModSource/breakingpoint_map_objects/tracked2/T34/config.cpp
|
nrailuj/breakingpointmod
|
e102e106b849ca78deb3cb299f3ae18c91c3bfe9
|
[
"Naumen",
"Condor-1.1",
"MS-PL"
] | 84
|
2017-08-26T22:06:28.000Z
|
2021-09-09T15:32:56.000Z
|
ModSource/breakingpoint_map_objects/tracked2/T34/config.cpp
|
nrailuj/breakingpointmod
|
e102e106b849ca78deb3cb299f3ae18c91c3bfe9
|
[
"Naumen",
"Condor-1.1",
"MS-PL"
] | 71
|
2017-06-24T01:10:42.000Z
|
2022-03-18T23:02:00.000Z
|
////////////////////////////////////////////////////////////////////
//DeRap: Produced from mikero's Dos Tools Dll version 4.32
//Mon Mar 17 12:22:47 2014 : Source 'file' date Mon Mar 17 12:22:47 2014
//http://dev-heaven.net/projects/list_files/mikero-pbodll
////////////////////////////////////////////////////////////////////
#define _ARMA_
//Class tracked2 : T34\config.bin{
class CfgPatches
{
class CATracked2_T34
{
units[] = {"T34"};
weapons[] = {};
requiredVersion = 0.7;
requiredAddons[] = {"CATracked2"};
};
};
class WeaponFireGun;
class WeaponCloudsGun;
class WeaponFireMGun;
class WeaponCloudsMGun;
class CfgVehicles
{
class Land;
class LandVehicle: Land
{
class NewTurret;
class ViewOptics;
};
class Tank: LandVehicle
{
class HitPoints;
class Turrets
{
class MainTurret;
};
class ViewOptics: ViewOptics{};
};
class T34: Tank
{
scope = 2;
displayName = "T-34";
model = "\ca\tracked2\T34\T34";
picture = "\ca\tracked2\Data\UI\Picture_t34_CA.paa";
Icon = "\ca\tracked2\Data\UI\Icon_t34_CA.paa";
mapSize = 7;
driverForceOptics = 1;
driverAction = "T90_Driver";
driverInAction = "T90_Driver";
tracksSpeed = 0.215;
wheelCircumference = 2.563;
side = 2;
faction = "GUE";
crew = "GUE_Soldier_1";
accuracy = 0.8;
armor = 300;
damageResistance = 0.01011;
cost = 1500000;
class HitPoints: HitPoints
{
class HitHull
{
armor = 0.85;
material = -1;
name = "telo";
visual = "telo";
passThrough = 1;
};
};
hiddenSelections[] = {"camo1","camo2","camo3","camo4","camo05"};
hiddenSelectionsTextures[] = {"\ca\tracked2\t34\data\t34_body01_co.paa","\ca\tracked2\t34\data\t34_body02_co.paa","\ca\tracked2\t34\data\t34_turret_co.paa","\ca\tracked2\t34\data\t34_wheels_co.paa","\ca\tracked2\t34\data\t34_body03_co.paa"};
maxSpeed = 55;
supplyRadius = 5;
class Exhausts
{
class Exhaust1
{
position = "exhaust";
direction = "exhaust_dir";
effect = "ExhaustsEffectBig";
};
class Exhaust2
{
position = "exhaust_1";
direction = "exhaust_1_dir";
effect = "ExhaustsEffectBig";
};
};
typicalCargo[] = {"GUE_Soldier_1","GUE_Soldier_1","GUE_Soldier_1"};
insideSoundCoef = 0.9;
soundGear[] = {"",5.6234134e-005,1};
soundGetIn[] = {"ca\SOUNDS\Vehicles\Tracked\T72\int\int-tank-diesel-door-1",0.56234133,1};
soundGetOut[] = {"ca\SOUNDS\Vehicles\Tracked\T72\ext\ext-tank-diesel-door-1",0.56234133,1,60};
soundEngineOnInt[] = {"ca\sounds\Vehicles\Tracked\T72\int\int-tank-diesel-start-2",1.0,1.0};
soundEngineOnExt[] = {"ca\SOUNDS\Vehicles\Tracked\T72\ext\ext-tank-diesel-start-2",2.5118864,1.0,500};
soundEngineOffInt[] = {"ca\sounds\vehicles\Tracked\T72\int\int-tank-diesel-stop-1",1.0,1.0};
soundEngineOffExt[] = {"ca\sounds\vehicles\Tracked\T72\ext\ext-tank-diesel-stop-1",1.0,0.8,500};
buildCrash0[] = {"Ca\sounds\Vehicles\Crash\tank_building_01",0.70794576,1,150};
buildCrash1[] = {"Ca\sounds\Vehicles\Crash\tank_building_02",0.70794576,1,150};
buildCrash2[] = {"Ca\sounds\Vehicles\Crash\tank_building_03",0.70794576,1,150};
buildCrash3[] = {"Ca\sounds\Vehicles\Crash\tank_building_04",0.70794576,1,150};
soundBuildingCrash[] = {"buildCrash0",0.25,"buildCrash1",0.25,"buildCrash2",0.25,"buildCrash3",0.25};
WoodCrash0[] = {"Ca\sounds\Vehicles\Crash\tank_wood_01",0.70794576,1,150};
WoodCrash1[] = {"Ca\sounds\Vehicles\Crash\tank_wood_02",0.70794576,1,150};
WoodCrash2[] = {"Ca\sounds\Vehicles\Crash\tank_wood_03",0.70794576,1,150};
WoodCrash3[] = {"Ca\sounds\Vehicles\Crash\tank_wood_04",0.70794576,1,150};
soundWoodCrash[] = {"woodCrash0",0.25,"woodCrash1",0.25,"woodCrash2",0.25,"woodCrash3",0.25};
ArmorCrash0[] = {"Ca\sounds\Vehicles\Crash\tank_vehicle_01",0.70794576,1,150};
ArmorCrash1[] = {"Ca\sounds\Vehicles\Crash\tank_vehicle_02",0.70794576,1,150};
ArmorCrash2[] = {"Ca\sounds\Vehicles\Crash\tank_vehicle_03",0.70794576,1,150};
ArmorCrash3[] = {"Ca\sounds\Vehicles\Crash\tank_vehicle_04",0.70794576,1,150};
soundArmorCrash[] = {"ArmorCrash0",0.25,"ArmorCrash1",0.25,"ArmorCrash2",0.25,"ArmorCrash3",0.25};
class SoundEvents
{
class AccelerationIn
{
sound[] = {"ca\sounds\Vehicles\Tracked\T72\int\int-tank-diesel-acceleration-1",1.7782794,1.0};
limit = "0.15";
expression = "engineOn*(1-camPos)*2*gmeterZ*((speed factor[1.5, 5]) min (speed factor[5, 1.5]))";
};
class AccelerationOut
{
sound[] = {"ca\sounds\Vehicles\Tracked\T72\ext\ext-tank-diesel-acceleration-1",1.7782794,1.0,650};
limit = "0.15";
expression = "engineOn*camPos*2*gmeterZ*((speed factor[1.5, 5]) min (speed factor[5, 1.5]))";
};
};
class Sounds
{
class Engine
{
sound[] = {"ca\sounds\Vehicles\Tracked\T72\ext\ext-tank-diesel-engine3",1.7782794,1.0,1000};
frequency = "(randomizer*0.05+0.8)*rpm";
volume = "engineOn*camPos*(rpm factor[0.4, 0.9])";
};
class IdleOut
{
sound[] = {"ca\sounds\Vehicles\Tracked\T72\ext\ext-tank-diesel-engine3",0.56234133,1.0,300};
frequency = "1";
volume = "engineOn*camPos*(rpm factor[0.6, 0.15])";
};
class NoiseOut
{
sound[] = {"ca\sounds\Vehicles\Tracked\T72\ext\noise2",1.0,1.0,150};
frequency = "1";
volume = "camPos*(angVelocity max 0.04)*(speed factor[4, 15])";
};
class ThreadsOutH0
{
sound[] = {"ca\sounds\Vehicles\Tracked\T72\ext\ext_diesel_treads_hard_01",1.0,1.0,200};
frequency = "1";
volume = "engineOn*camPos*(1-grass)*((rpm factor[0.3, 0.6]) min (rpm factor[0.6, 0.3]))";
};
class ThreadsOutH1
{
sound[] = {"ca\sounds\Vehicles\Tracked\T72\ext\ext_diesel_treads_hard_02",1.0,1.0,200};
frequency = "1";
volume = "engineOn*camPos*(1-grass)*((rpm factor[0.5, 0.8]) min (rpm factor[0.8, 0.5]))";
};
class ThreadsOutH2
{
sound[] = {"ca\sounds\Vehicles\Tracked\T72\ext\ext_diesel_treads_hard_03",1.0,1.0,200};
frequency = "1";
volume = "engineOn*camPos*(1-grass)*((rpm factor[0.65, 0.9]) min (rpm factor[0.9, 0.65]))";
};
class ThreadsOutH3
{
sound[] = {"ca\sounds\Vehicles\Tracked\T72\ext\ext_diesel_treads_hard_04",1.0,1.0,200};
frequency = "1";
volume = "engineOn*camPos*(1-grass)*((rpm factor[0.8, 1.2]) min (rpm factor[1.2, 0.8]))";
};
class ThreadsOutH4
{
sound[] = {"ca\sounds\Vehicles\Tracked\T72\ext\ext_diesel_treads_hard_05",1.0,1.0,200};
frequency = "1";
volume = "engineOn*camPos*(1-grass)*((rpm factor[1, 2.0]) min (rpm factor[2.0, 1]))";
};
class ThreadsOutS0
{
sound[] = {"ca\sounds\Vehicles\Tracked\T72\ext\ext_diesel_treads_soft_01",1.0,1.0,200};
frequency = "1";
volume = "engineOn*camPos*grass*((rpm factor[0.3, 0.6]) min (rpm factor[0.6, 0.3]))";
};
class ThreadsOutS1
{
sound[] = {"ca\sounds\Vehicles\Tracked\T72\ext\ext_diesel_treads_soft_02",1.0,1.0,200};
frequency = "1";
volume = "engineOn*camPos*grass*((rpm factor[0.5, 0.8]) min (rpm factor[0.8, 0.5]))";
};
class ThreadsOutS2
{
sound[] = {"ca\sounds\Vehicles\Tracked\T72\ext\ext_diesel_treads_soft_03",1.0,1.0,200};
frequency = "1";
volume = "engineOn*camPos*grass*((rpm factor[0.65, 0.9]) min (rpm factor[0.9, 0.65]))";
};
class ThreadsOutS3
{
sound[] = {"ca\sounds\Vehicles\Tracked\T72\ext\ext_diesel_treads_soft_04",1.0,1.0,200};
frequency = "1";
volume = "engineOn*camPos*grass*((rpm factor[0.8, 1.2]) min (rpm factor[1.2, 0.8]))";
};
class ThreadsOutS4
{
sound[] = {"ca\sounds\Vehicles\Tracked\T72\ext\ext_diesel_treads_soft_05",1.0,1.0,200};
frequency = "1";
volume = "engineOn*camPos*grass*((rpm factor[1, 2.0]) min (rpm factor[2.0, 1]))";
};
class Movement
{
sound[] = {"",1.0,1.0};
frequency = "0";
volume = "0";
};
class EngineIn
{
sound[] = {"ca\sounds\Vehicles\Tracked\T72\int\int-tank-diesel-engine3",1.0,1.0};
frequency = "(randomizer*0.05+0.8)*rpm";
volume = "engineOn*(1-camPos)*(rpm factor[0.4, 1])";
};
class IdleIn
{
sound[] = {"ca\sounds\Vehicles\Tracked\T72\int\int-tank-diesel-engine3",1.7782794,1.0};
frequency = "1";
volume = "engineOn*(1-camPos)*(rpm factor[0.6, 0.15])";
};
class NoiseIn
{
sound[] = {"ca\sounds\Vehicles\Tracked\T72\int\noise2",0.15848932,1.0};
frequency = "1";
volume = "(1-camPos)*(angVelocity max 0.04)*(speed factor[4, 15])";
};
class ThreadsInH0
{
sound[] = {"ca\sounds\Vehicles\Tracked\T72\int\int_diesel_treads_hard_01",1.0,1.0};
frequency = "1";
volume = "engineOn*(1-camPos)*(1-grass)*((rpm factor[0.3, 0.6]) min (rpm factor[0.6, 0.3]))";
};
class ThreadsInH1
{
sound[] = {"ca\sounds\Vehicles\Tracked\T72\int\int_diesel_treads_hard_02",1.0,1.0};
frequency = "1";
volume = "engineOn*(1-camPos)*(1-grass)*((rpm factor[0.5, 0.8]) min (rpm factor[0.8, 0.5]))";
};
class ThreadsInH2
{
sound[] = {"ca\sounds\Vehicles\Tracked\T72\int\int_diesel_treads_hard_03",1.0,1.0};
frequency = "1";
volume = "engineOn*(1-camPos)*(1-grass)*((rpm factor[0.65, 0.9]) min (rpm factor[0.9, 0.65]))";
};
class ThreadsInH3
{
sound[] = {"ca\sounds\Vehicles\Tracked\T72\int\int_diesel_treads_hard_04",1.0,1.0};
frequency = "1";
volume = "engineOn*(1-camPos)*(1-grass)*((rpm factor[0.8, 1.2]) min (rpm factor[1.2, 0.8]))";
};
class ThreadsInH4
{
sound[] = {"ca\sounds\Vehicles\Tracked\T72\int\int_diesel_treads_hard_05",1.0,1.0};
frequency = "1";
volume = "engineOn*(1-camPos)*(1-grass)*((rpm factor[1, 2.0]) min (rpm factor[2.0, 1]))";
};
class ThreadsInS0
{
sound[] = {"ca\sounds\Vehicles\Tracked\T72\int\int_diesel_treads_soft_01",1.0,1.0};
frequency = "1";
volume = "engineOn*(1-camPos)*grass*((rpm factor[0.3, 0.6]) min (rpm factor[0.6, 0.3]))";
};
class ThreadsInS1
{
sound[] = {"ca\sounds\Vehicles\Tracked\T72\int\int_diesel_treads_soft_02",1.0,1.0};
frequency = "1";
volume = "engineOn*(1-camPos)*grass*((rpm factor[0.5, 0.8]) min (rpm factor[0.8, 0.5]))";
};
class ThreadsInS2
{
sound[] = {"ca\sounds\Vehicles\Tracked\T72\int\int_diesel_treads_soft_03",1.0,1.0};
frequency = "1";
volume = "engineOn*(1-camPos)*grass*((rpm factor[0.65, 0.9]) min (rpm factor[0.9, 0.65]))";
};
class ThreadsInS3
{
sound[] = {"ca\sounds\Vehicles\Tracked\T72\int\int_diesel_treads_soft_04",1.0,1.0};
frequency = "1";
volume = "engineOn*(1-camPos)*grass*((rpm factor[0.8, 1.2]) min (rpm factor[1.2, 0.8]))";
};
class ThreadsInS4
{
sound[] = {"ca\sounds\Vehicles\Tracked\T72\int\int_diesel_treads_soft_05",1.0,1.0};
frequency = "1";
volume = "engineOn*(1-camPos)*grass*((rpm factor[1, 2.0]) min (rpm factor[2.0, 1]))";
};
};
class Turrets: Turrets
{
class MainTurret: MainTurret
{
gunnerAction = "BMP3_Gunner_OUT";
gunnerInAction = "BMP3_Gunner";
memoryPointsGetInGunner = "pos gunner";
memoryPointsGetInGunnerDir = "pos gunner dir";
gunnerGetInAction = "GetInMedium";
gunnerGetOutAction = "GetOutMedium";
weapons[] = {"ZiS_S_53","DT_veh"};
selectionFireAnim = "zasleh";
magazines[] = {"10Rnd_85mmAP","33Rnd_85mmHE","60Rnd_762x54_DT","60Rnd_762x54_DT","60Rnd_762x54_DT","60Rnd_762x54_DT","60Rnd_762x54_DT"};
soundServo[] = {"\Ca\sounds\Vehicles\Tracked\Other\int\int-servo",0.17782794,1.0};
gunnerOpticsModel = "\ca\weapons\2Dscope_T90gun12";
gunnerOutOpticsModel = "";
gunnerOutOpticsEffect[] = {};
stabilizedInAxes = 0;
minElev = -6;
maxElev = 14;
initElev = 0;
gunnerOpticsEffect[] = {"TankGunnerOptics1","OpticsBlur3","OpticsCHAbera3"};
class ViewOptics
{
initAngleX = 0;
minAngleX = -30;
maxAngleX = 30;
initAngleY = 0;
minAngleY = -100;
maxAngleY = 100;
initFov = 0.2;
minFov = 0.025;
maxFov = 0.2;
};
class Turrets: Turrets
{
class CommanderOptics: NewTurret
{
weapons[] = {};
magazines[] = {};
gunBeg = "gun_muzzle";
gunEnd = "gun_chamber";
body = "ObsTurret";
gun = "ObsGun";
gunnerAction = "BMP3_Commander_OUT";
gunnerInAction = "BMP3_Commander";
gunnerGetInAction = "GetInMedium";
gunnerGetOutAction = "GetOutMedium";
stabilizedInAxes = 0;
minElev = -25;
maxElev = 60;
initElev = 0;
minTurn = -360;
maxTurn = 360;
initTurn = 0;
gunnerOpticsModel = "\ca\weapons\2Dscope_com3";
gunnerOutOpticsModel = "\ca\Weapons\optika_empty";
gunnerOutOpticsColor[] = {0,0,0,1};
gunnerOutForceOptics = 0;
gunnerOutOpticsShowCursor = 0;
startEngine = 0;
memoryPointGunnerOutOptics = "CommanderViewOut";
memoryPointGunnerOptics = "commanderview";
memoryPointsGetInGunner = "pos commander";
memoryPointsGetInGunnerDir = "pos commander dir";
memoryPointGun = "gun_muzzle";
selectionFireAnim = "zasleh_1";
gunnerOpticsEffect[] = {"TankGunnerOptics2","OpticsBlur3","OpticsCHAbera3"};
class ViewOptics
{
initAngleX = 0;
minAngleX = -30;
maxAngleX = 30;
initAngleY = 0;
minAngleY = -100;
maxAngleY = 100;
initFov = 0.3;
minFov = 0.015;
maxFov = 0.3;
};
class ViewGunner
{
initAngleX = 5;
minAngleX = -30;
maxAngleX = 30;
initAngleY = 0;
minAngleY = -100;
maxAngleY = 100;
initFov = 0.7;
minFov = 0.25;
maxFov = 1.1;
};
soundServo[] = {"\Ca\sounds\Vehicles\Tracked\Other\int\int-servo",0.17782794,1.0};
outGunnerMayFire = 1;
inGunnerMayFire = 1;
proxyType = "CPCommander";
proxyIndex = 1;
gunnerName = "$STR_POSITION_COMMANDER";
primaryGunner = 0;
primaryObserver = 1;
animationSourceBody = "obsTurret";
animationSourceGun = "obsGun";
animationSourceHatch = "hatchCommander";
commanding = 2;
viewGunnerInExternal = 0;
};
};
};
class FrontGunner: MainTurret
{
gunnerName = "$STR_position_frontgunner";
gunBeg = "FrontGunner_muzzle";
gunEnd = "FrontGunner_chamber";
body = "FrontGunnerTurret";
gun = "FrontGunnerGun";
gunnerOpticsModel = "\ca\weapons\2Dscope_Metis.p3d";
animationSourceBody = "FrontGunnerTurret";
animationSourceGun = "FrontGunnerGun";
memoryPointGun = "FrontGunner_muzzle";
memoryPointGunnerOptics = "FrontGunnerview";
class Turrets{};
proxyIndex = 2;
weapons[] = {"DT_veh"};
selectionFireAnim = "zasleh1";
magazines[] = {"60Rnd_762x54_DT","60Rnd_762x54_DT","60Rnd_762x54_DT","60Rnd_762x54_DT","60Rnd_762x54_DT"};
startEngine = 0;
stabilizedInAxes = 0;
minElev = -16;
maxElev = 16;
initElev = 0;
minTurn = -16;
maxTurn = 16;
initTurn = 0;
forceHideGunner = 1;
};
};
type = 1;
threat[] = {0.4,0.4,0.0};
class Damage
{
tex[] = {};
mat[] = {};
};
};
};
//};
| 33.986395
| 243
| 0.626968
|
nrailuj
|
3619d2341beb1d1df457e9811ca14d62fc604015
| 1,499
|
cpp
|
C++
|
c_code_for_comparison/lloyds.cpp
|
FelixWinterstein/Vivado-KMeans
|
b1121f826bdac8db9502e4bf0c8f3b08425bc061
|
[
"BSD-3-Clause"
] | 44
|
2015-09-14T03:50:14.000Z
|
2020-11-09T09:12:02.000Z
|
c_code_for_comparison/lloyds.cpp
|
SurfingWave/Vivado-KMeans
|
b1121f826bdac8db9502e4bf0c8f3b08425bc061
|
[
"BSD-3-Clause"
] | 2
|
2018-02-21T04:34:37.000Z
|
2018-05-16T12:13:39.000Z
|
c_code_for_comparison/lloyds.cpp
|
SurfingWave/Vivado-KMeans
|
b1121f826bdac8db9502e4bf0c8f3b08425bc061
|
[
"BSD-3-Clause"
] | 24
|
2015-03-23T19:39:22.000Z
|
2021-04-27T03:35:50.000Z
|
/**********************************************************************
* Felix Winterstein, Imperial College London
*
* File: lloyds.cpp
*
* Revision 1.01
* Additional Comments: distributed under a BSD license, see LICENSE.txt
*
**********************************************************************/
#include <stdio.h>
#include <stdlib.h>
//#include <stdbool.h>
#include <math.h>
#include "lloyds.h"
// kernel function of lloyd's algorithm
void lloyds(data_type_short *points, centre_type *centres, uint k, uint n, bool last_run, data_type_short *output_array)
{
data_type_short centre_positions[KMAX];
for (uint i=0; i<k; i++) {
centre_positions[i] = centres[i].position_short;
}
// consider all data points
for (uint i=0; i<n; i++) {
uint idx;
data_type_short closest_centre;
// search for closest centre to this point
closest_to_point_direct_fi_short(points[i], centre_positions, k, &idx, &closest_centre);
coord_type tmp_dist;
compute_distance_fi_short(points[i], closest_centre, &tmp_dist);
centres[idx].count_short++;
// update centre buffer with info of closest centre
for (uint d=0; d<D; d++) {
centres[idx].wgtCent.value[d] += points[i].value[d];
}
centres[idx].sum_sq += tmp_dist;
if (last_run == true) {
output_array[i] = closest_centre;
}
}
}
| 26.767857
| 120
| 0.5497
|
FelixWinterstein
|
3619fdb0b2c95ddfdb21703f70777896b0111e1e
| 1,123
|
cpp
|
C++
|
src/main.cpp
|
howprice/sdl2-tetris
|
8272994293c84b42450ef68bc92c73587f2429cd
|
[
"BSD-3-Clause"
] | 11
|
2015-09-30T12:14:59.000Z
|
2022-03-22T04:04:51.000Z
|
src/main.cpp
|
howprice/sdl2-tetris
|
8272994293c84b42450ef68bc92c73587f2429cd
|
[
"BSD-3-Clause"
] | 2
|
2015-09-30T16:00:18.000Z
|
2016-12-29T10:51:14.000Z
|
src/main.cpp
|
howprice/sdl2-tetris
|
8272994293c84b42450ef68bc92c73587f2429cd
|
[
"BSD-3-Clause"
] | 2
|
2021-12-23T04:20:12.000Z
|
2022-03-22T04:09:57.000Z
|
//--------------------------------------------------------------------------------------------------
/**
\file main.cpp
**/
//--------------------------------------------------------------------------------------------------
#include "App.h"
#include "SDL.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main( int argc, char** argv )
{
bool bFullScreen = false;
unsigned int displayWidth = 1280;
unsigned int displayHeight = 720;
for( int i = 1; i < argc; ++i )
{
if( strcmp( argv[i], "--fullscreen" ) == 0 )
{
bFullScreen = true;
}
else if( strcmp( argv[i], "--width" ) == 0)
{
SDL_assert( argc > i ); // make sure we have another argument
displayWidth = (unsigned int)atoi( argv[++i] );
}
else if(strcmp( argv[i], "--height" ) == 0)
{
SDL_assert( argc > i ); // make sure we have another argument
displayHeight = (unsigned int)atoi( argv[++i] );
}
}
App app;
if( !app.Init( bFullScreen, displayWidth, displayHeight ) )
{
printf( "ERROR - App failed to initialise\n" );
app.ShutDown();
return 1;
}
app.Run();
app.ShutDown();
return 0;
}
| 21.596154
| 100
| 0.488869
|
howprice
|
361e5d830e7e40883224065291090cebbc8663d5
| 2,003
|
cpp
|
C++
|
OpenRPG/Managers/StateManager.cpp
|
OpenRPGs/OpenRPG
|
0baed49c1d7e6f871457c441aa0209ec4280265a
|
[
"MIT"
] | 28
|
2019-08-09T04:07:04.000Z
|
2022-01-16T05:56:22.000Z
|
OpenRPG/Managers/StateManager.cpp
|
OpenRPGs/OpenRPG
|
0baed49c1d7e6f871457c441aa0209ec4280265a
|
[
"MIT"
] | 29
|
2019-08-09T04:02:59.000Z
|
2019-09-16T05:01:33.000Z
|
OpenRPG/Managers/StateManager.cpp
|
OpenRPGs/OpenRPG
|
0baed49c1d7e6f871457c441aa0209ec4280265a
|
[
"MIT"
] | 18
|
2019-08-09T02:42:09.000Z
|
2022-01-16T06:03:32.000Z
|
#include "stdafx.h"
#include "StateManager.h"
using namespace std;
typedef pair<State*, bool> StatePair;
#pragma region getInstance, Constructor, Finalizer
StateManager* StateManager::Instance = NULL;
StateManager* StateManager::getInstance() {
if (StateManager::Instance == NULL) {
StateManager::Instance = new StateManager();
}
return StateManager::Instance;
}
StateManager::StateManager() {
// vector 공간 예약 할당
this->stateStack.reserve(sizeof(State*) * 4);
}
StateManager::~StateManager() {
this->Clear();
}
#pragma endregion
#pragma region Clear, Empty
StateManager* StateManager::Clear() {
// 장면 스택 해제
while (this->stateStack.size() > 0) {
auto back = this->stateStack.back();
this->stateStack.pop_back();
if (back.first != NULL)
delete back.first;
}
return this;
}
bool StateManager::Empty() {
return this->stateStack.empty();
}
#pragma endregion
#pragma region Push, Pop, PopUntil
StateManager* StateManager::Push(State* state, bool pararell) {
if (!this->Empty()) // 스택이 비어있지 않다면 기존 최상위 장면에 onDeactivated 호출
this->stateStack.back().first->onDeactivated();
this->stateStack.push_back(pair<State*, bool>(state, pararell));
state->onEnter();
state->onActivated();
return this;
}
State* StateManager::Pop() {
auto back = this->stateStack.back();
this->stateStack.pop_back();
back.first->onDeactivated();
back.first->onLeave();
if (!this->Empty()) // 스택이 비어있지 않다면 최상위 장면에 onActivated 호출
this->stateStack.back().first->onActivated();
return back.first;
}
StateManager* StateManager::PopUntil(State* state) {
while (!this->Empty() && this->Pop() != state)
;
return this;
}
#pragma endregion
StateManager* StateManager::Update() {
auto stackSize = this->stateStack.size();
for (vector<pair<State*, bool>>::size_type i = 0; i < stackSize; i++) {
auto item = this->stateStack[i];
if (item.second || i + 1 == stackSize) { // 병렬 갱신이 설정된 장면이라면
item.first->update(); // 장면을 갱신
item.first->render(); // 장면을 그리기
}
}
return this;
}
| 23.290698
| 72
| 0.68647
|
OpenRPGs
|
3623e22a041f228f8115de853958c81c68c6c621
| 24,157
|
cpp
|
C++
|
test/src/ConnectionTests.cpp
|
rhymu8354/TwitchNetworkTransport
|
16f7583514c2dd628315ac86dc732d847f0bd0ef
|
[
"MIT"
] | null | null | null |
test/src/ConnectionTests.cpp
|
rhymu8354/TwitchNetworkTransport
|
16f7583514c2dd628315ac86dc732d847f0bd0ef
|
[
"MIT"
] | null | null | null |
test/src/ConnectionTests.cpp
|
rhymu8354/TwitchNetworkTransport
|
16f7583514c2dd628315ac86dc732d847f0bd0ef
|
[
"MIT"
] | null | null | null |
/**
* @file ConnectionTests.cpp
*
* This module contains the unit tests of the
* TwitchNetworkTransport::Connection class.
*
* © 2018 by Richard Walters
*/
#include <condition_variable>
#include <gtest/gtest.h>
#include <TwitchNetworkTransport/Connection.hpp>
#include <inttypes.h>
#include <mutex>
#include <stdint.h>
#include <StringExtensions/StringExtensions.hpp>
#include <SystemAbstractions/NetworkEndpoint.hpp>
#include <TlsDecorator/TlsShim.hpp>
#include <thread>
#include <vector>
namespace {
/**
* This is an alternative TlsShim which mocks the libtls
* library completely.
*/
struct MockTls
: public TlsDecorator::TlsShim
{
// Properties
bool tlsServerMode = false;
bool tlsConnectCalled = false;
bool tlsHandshakeCalled = false;
bool tlsAcceptCalled = false;
bool tlsConfigProtocolSetCalled = false;
uint32_t tlsConfigProtocolSetProtocols = 0;
bool tlsConfigureCalled = false;
std::string peerCert;
std::string caCerts;
std::string configuredCert;
std::string configuredKey;
std::string encryptedKey;
std::string keyPassword;
std::string decryptedKey;
bool tlsReadCalled = false;
bool tlsWriteCalled = false;
bool stallTlsWrite = false;
tls_read_cb tlsReadCb = NULL;
tls_write_cb tlsWriteCb = NULL;
void* tlsCbArg = NULL;
std::vector< uint8_t > tlsWriteDecryptedBuf;
std::vector< uint8_t > tlsWriteEncryptedBuf;
std::vector< uint8_t > tlsReadEncryptedBuf;
std::vector< uint8_t > tlsReadDecryptedBuf;
std::condition_variable wakeCondition;
std::mutex mutex;
// Methods
/**
* This method waits on the mock's wait condition until
* the given predicate evaluates to true.
*
* @note
* Ensure that the predicate used is associated with
* the mock's wait condition. Otherwise, the method
* may wait the full timeout period unnecessarily.
*
* @param[in] predicate
* This is the function to call to determine whether
* or not the condition we're waiting for is true.
*
* @param[in] timeout
* This is the maximum amount of time to wait.
*
* @return
* An indication of whether or not the given condition
* became true before a reasonable timeout period is returned.
*/
bool Await(
std::function< bool() > predicate,
std::chrono::milliseconds timeout = std::chrono::milliseconds(1000)
) {
std::unique_lock< decltype(mutex) > lock(mutex);
return wakeCondition.wait_for(
lock,
timeout,
predicate
);
}
// TlsDecorator::TlsShim
virtual BIO *BIO_new(const BIO_METHOD *type) override {
return nullptr;
}
virtual BIO *BIO_new_mem_buf(const void *buf, int len) override {
encryptedKey = std::string(
(const char*)buf,
len
);
return nullptr;
}
virtual long BIO_ctrl(BIO *bp, int cmd, long larg, void *parg) override {
*((const char**)parg) = decryptedKey.c_str();
return (long)decryptedKey.size();
}
virtual void BIO_free_all(BIO *a) override {
}
virtual EVP_PKEY *PEM_read_bio_PrivateKey(BIO *bp, EVP_PKEY **x, pem_password_cb *cb, void *u) override {
static EVP_PKEY dummy;
keyPassword = (const char*)u;
return &dummy;
}
virtual int PEM_write_bio_PrivateKey(BIO *bp, EVP_PKEY *x, const EVP_CIPHER *enc,
unsigned char *kstr, int klen, pem_password_cb *cb, void *u) override
{
return 1;
}
virtual void EVP_PKEY_free(EVP_PKEY *pkey) override {
}
virtual const char *tls_error(struct tls *_ctx) override {
return nullptr;
}
virtual struct tls_config *tls_config_new(void) override {
return nullptr;
}
virtual int tls_config_set_protocols(struct tls_config *_config, uint32_t _protocols) override {
tlsConfigProtocolSetCalled = true;
tlsConfigProtocolSetProtocols = _protocols;
return 0;
}
virtual void tls_config_insecure_noverifycert(struct tls_config *_config) override {
}
virtual void tls_config_insecure_noverifyname(struct tls_config *_config) override {
}
virtual int tls_config_set_ca_mem(struct tls_config *_config, const uint8_t *_ca,
size_t _len) override
{
caCerts = std::string(
(const char*)_ca,
_len
);
return 0;
}
virtual int tls_config_set_cert_mem(struct tls_config *_config, const uint8_t *_cert,
size_t _len) override
{
configuredCert = std::string(
(const char*)_cert,
_len
);
return 0;
}
virtual int tls_config_set_key_mem(struct tls_config *_config, const uint8_t *_key,
size_t _len) override
{
configuredKey = std::string(
(const char*)_key,
_len
);
return 0;
}
virtual int tls_configure(struct tls *_ctx, struct tls_config *_config) override {
tlsConfigureCalled = true;
return 0;
}
virtual void tls_config_free(struct tls_config *_config) override {
}
virtual struct tls *tls_client(void) override {
tlsServerMode = false;
return nullptr;
}
virtual struct tls *tls_server(void) override {
tlsServerMode = true;
return nullptr;
}
virtual int tls_connect_cbs(struct tls *_ctx, tls_read_cb _read_cb,
tls_write_cb _write_cb, void *_cb_arg, const char *_servername) override
{
tlsConnectCalled = true;
tlsReadCb = _read_cb;
tlsWriteCb = _write_cb;
tlsCbArg = _cb_arg;
return 0;
}
virtual int tls_accept_cbs(struct tls *_ctx, struct tls **_cctx,
tls_read_cb _read_cb, tls_write_cb _write_cb, void *_cb_arg) override
{
tlsAcceptCalled = true;
tlsReadCb = _read_cb;
tlsWriteCb = _write_cb;
tlsCbArg = _cb_arg;
return 0;
}
virtual int tls_handshake(struct tls *_ctx) override {
std::lock_guard< decltype(mutex) > lock(mutex);
tlsHandshakeCalled = true;
wakeCondition.notify_all();
return 0;
}
virtual int tls_peer_cert_provided(struct tls *_ctx) override {
return 1;
}
virtual const uint8_t *tls_peer_cert_chain_pem(struct tls *_ctx, size_t *_len) override {
*_len = peerCert.length();
return (const uint8_t*)peerCert.data();
}
virtual ssize_t tls_read(struct tls *_ctx, void *_buf, size_t _buflen) override {
tlsReadCalled = true;
if (tlsReadEncryptedBuf.empty()) {
tlsReadEncryptedBuf.resize(65536);
const auto encryptedAmount = tlsReadCb(_ctx, tlsReadEncryptedBuf.data(), tlsReadEncryptedBuf.size(), tlsCbArg);
std::lock_guard< decltype(mutex) > lock(mutex);
if (encryptedAmount >= 0) {
tlsReadEncryptedBuf.resize((size_t)encryptedAmount);
} else {
tlsReadEncryptedBuf.clear();
}
wakeCondition.notify_all();
}
const auto decryptedAmount = std::min(tlsReadDecryptedBuf.size(), _buflen);
if (decryptedAmount == 0) {
return TLS_WANT_POLLIN;
} else {
(void)memcpy(_buf, tlsReadDecryptedBuf.data(), decryptedAmount);
if (decryptedAmount == tlsReadDecryptedBuf.size()) {
tlsReadDecryptedBuf.clear();
} else {
(void)tlsReadDecryptedBuf.erase(
tlsReadDecryptedBuf.begin(),
tlsReadDecryptedBuf.begin() + decryptedAmount
);
}
return decryptedAmount;
}
}
virtual ssize_t tls_write(struct tls *_ctx, const void *_buf, size_t _buflen) override {
std::lock_guard< decltype(mutex) > lock(mutex);
tlsWriteCalled = true;
if (stallTlsWrite) {
return TLS_WANT_POLLIN;
}
const auto bufAsBytes = (const uint8_t*)_buf;
tlsWriteDecryptedBuf.assign(bufAsBytes, bufAsBytes + _buflen);
const auto encryptedAmount = tlsWriteCb(_ctx, tlsWriteEncryptedBuf.data(), tlsWriteEncryptedBuf.size(), tlsCbArg);
if (encryptedAmount == tlsWriteEncryptedBuf.size()) {
tlsWriteEncryptedBuf.clear();
} else {
(void)tlsWriteEncryptedBuf.erase(
tlsWriteEncryptedBuf.begin(),
tlsWriteEncryptedBuf.begin() + encryptedAmount
);
}
wakeCondition.notify_all();
return _buflen;
}
virtual int tls_close(struct tls *_ctx) override {
return 0;
}
virtual void tls_free(struct tls *_ctx) override {
}
};
/**
* This holds information about one client that is connected
* to the server used in the text fixture for these tests.
*/
struct Client {
/**
* This is the server end of the connection between the unit under
* test and the server.
*/
std::shared_ptr< SystemAbstractions::NetworkConnection > connection;
/**
* This holds any data received from the client.
*/
std::vector< uint8_t > dataReceived;
/**
* This flag indicates whether or not the connection to the client
* was broken by the client.
*/
bool broken = false;
};
/**
* This is a substitute for a real connection, and used to test
* the SetConnectionFactory method of Connection.
*/
struct MockConnection
: public SystemAbstractions::INetworkConnection
{
// Properties
std::vector< uint8_t > messageSent;
// Methods
// SystemAbstractions::INetworkConnection
virtual SystemAbstractions::DiagnosticsSender::UnsubscribeDelegate SubscribeToDiagnostics(
SystemAbstractions::DiagnosticsSender::DiagnosticMessageDelegate delegate,
size_t minLevel = 0
) override {
return []{};
}
virtual bool Connect(uint32_t peerAddress, uint16_t peerPort) override {
return true;
}
virtual bool Process(
MessageReceivedDelegate messageReceivedDelegate,
BrokenDelegate brokenDelegate
) override {
return true;
}
virtual uint32_t GetPeerAddress() const override{
return 0;
}
virtual uint16_t GetPeerPort() const override {
return 0;
}
virtual bool IsConnected() const override {
return true;
}
virtual uint32_t GetBoundAddress() const override {
return 0;
}
virtual uint16_t GetBoundPort() const override {
return 0;
}
virtual void SendMessage(const std::vector< uint8_t >& message) override {
messageSent = message;
}
virtual void Close(bool clean = false) override {
}
};
}
/**
* This is the test fixture for these tests, providing common
* setup and teardown for each test.
*/
struct ConnectionTests
: public ::testing::Test
{
// Properties
/**
* This holds any state in the mock shim layer representing
* the TLS library.
*/
MockTls mockTls;
/**
* This is the unit under test.
*/
TwitchNetworkTransport::Connection connection;
/**
* This is a real network server used to test that the unit under test
* can actually connect to a real server.
*/
SystemAbstractions::NetworkEndpoint server;
/**
* This flag is used to tell the test fixture if we
* moved the unit under test.
*/
bool transportWasMoved = false;
/**
* These are the diagnostic messages that have been
* received from the unit under test.
*/
std::vector< std::string > diagnosticMessages;
/**
* This is the delegate obtained when subscribing
* to receive diagnostic messages from the unit under test.
* It's called to terminate the subscription.
*/
SystemAbstractions::DiagnosticsSender::UnsubscribeDelegate diagnosticsUnsubscribeDelegate;
/**
* If this flag is set, we will print all received diagnostic
* messages, in addition to storing them.
*/
bool printDiagnosticMessages = false;
/**
* This collects information about any connections
* established (presumably by the unit under test) to the server.
*/
std::vector< Client > clients;
/**
* This holds any data received from the server.
*/
std::vector< uint8_t > dataReceived;
/**
* This flag indicates whether or not the connection to the server
* was broken by the server.
*/
bool broken = false;
/**
* This is used to wake up threads which may be waiting for some
* state in the fixture to be changed.
*/
std::condition_variable_any waitCondition;
/**
* This is used to synchronize access to the object.
*/
std::mutex mutex;
// Methods
/**
* This method waits for the given number of connections to be established
* with the server.
*
* @param[in] numConnections
* This is the number of connections to await.
*
* @return
* An indication of whether or not the given number of connections
* were established with the server before a reasonable amount of
* time has elapsed is returned.
*/
bool AwaitConnections(size_t numConnections) {
std::unique_lock< std::mutex > lock(mutex);
return waitCondition.wait_for(
lock,
std::chrono::seconds(1),
[this, numConnections]{
return (clients.size() >= numConnections);
}
);
}
/**
* This method waits for the server to break the connection
* to the unit under test.
*
* @return
* An indication of whether or not the server breaks their
* end of the connection before a reasonable amount of
* time has elapsed is returned.
*/
bool AwaitServerBreak() {
std::unique_lock< std::mutex > lock(mutex);
return waitCondition.wait_for(
lock,
std::chrono::seconds(1),
[this]{
return broken;
}
);
}
/**
* This method waits for the client to break the connection
* at the given index of the collection of connections
* currently established with the server.
*
* @param[in] connectionIndex
* This is the index of the connection for which to await
* a client-side break.
*
* @return
* An indication of whether or not the client breaks their
* end of the connection before a reasonable amount of
* time has elapsed is returned.
*/
bool AwaitClientBreak(size_t connectionIndex) {
std::unique_lock< std::mutex > lock(mutex);
return waitCondition.wait_for(
lock,
std::chrono::seconds(1),
[this, connectionIndex]{
return clients[connectionIndex].broken;
}
);
}
/**
* This method waits for the server to send the given number
* of bytes to the unit under test.
*
* @param[in] amount
* This is the number of bytes to await.
*
* @return
* An indication of whether or not the server has sent
* the given number of bytes before a reasonable amount of
* time has elapsed is returned.
*/
bool AwaitServerData(size_t amount) {
std::unique_lock< std::mutex > lock(mutex);
return waitCondition.wait_for(
lock,
std::chrono::seconds(1),
[this, amount]{
return (dataReceived.size() >= amount);
}
);
}
/**
* This method waits for the client to send the given number
* of bytes through the connection at the given index of the
* collection of connections currently established with the server.
*
* @param[in] connectionIndex
* This is the index of the connection for which to await
* data from the client.
*
* @param[in] amount
* This is the number of bytes to await.
*
* @return
* An indication of whether or not the client has sent
* the given number of bytes before a reasonable amount of
* time has elapsed is returned.
*/
bool AwaitClientData(
size_t connectionIndex,
size_t amount
) {
std::unique_lock< std::mutex > lock(mutex);
return waitCondition.wait_for(
lock,
std::chrono::seconds(1),
[this, connectionIndex, amount]{
return (clients[connectionIndex].dataReceived.size() >= amount);
}
);
}
// ::testing::Test
virtual void SetUp() {
TlsDecorator::selectedTlsShim = &mockTls;
diagnosticsUnsubscribeDelegate = connection.SubscribeToDiagnostics(
[this](
std::string senderName,
size_t level,
std::string message
){
diagnosticMessages.push_back(
StringExtensions::sprintf(
"%s[%zu]: %s",
senderName.c_str(),
level,
message.c_str()
)
);
if (printDiagnosticMessages) {
printf(
"%s[%zu]: %s\n",
senderName.c_str(),
level,
message.c_str()
);
}
},
0
);
const auto newConnectionDelegate = [this](
std::shared_ptr< SystemAbstractions::NetworkConnection > newConnection
){
std::unique_lock< decltype(mutex) > lock(mutex);
size_t connectionIndex = clients.size();
if (
newConnection->Process(
[this, connectionIndex](const std::vector< uint8_t >& data){
std::unique_lock< decltype(mutex) > lock(mutex);
auto& dataReceived = clients[connectionIndex].dataReceived;
dataReceived.insert(
dataReceived.end(),
data.begin(),
data.end()
);
waitCondition.notify_all();
},
[this, connectionIndex](bool graceful){
std::unique_lock< decltype(mutex) > lock(mutex);
auto& broken = clients[connectionIndex].broken;
broken = true;
waitCondition.notify_all();
}
)
) {
Client newClient;
newClient.connection = newConnection;
clients.push_back(std::move(newClient));
waitCondition.notify_all();
}
};
const auto packetReceivedDelegate = [](
uint32_t address,
uint16_t port,
const std::vector< uint8_t >& body
){
};
ASSERT_TRUE(
server.Open(
newConnectionDelegate,
packetReceivedDelegate,
SystemAbstractions::NetworkEndpoint::Mode::Connection,
0x7F000001,
0,
0
)
);
connection.SetCaCerts("PogChamp");
connection.SetServerInfo("localhost", server.GetBoundPort());
connection.SetMessageReceivedDelegate(
[this](
const std::string& message
){
std::lock_guard< std::mutex > lock(mutex);
dataReceived.insert(
dataReceived.end(),
message.begin(),
message.end()
);
waitCondition.notify_all();
}
);
connection.SetDisconnectedDelegate(
[this](){
std::lock_guard< std::mutex > lock(mutex);
broken = true;
waitCondition.notify_all();
}
);
}
virtual void TearDown() {
server.Close();
clients.clear();
if (!transportWasMoved) {
diagnosticsUnsubscribeDelegate();
}
connection.Disconnect();
}
};
TEST_F(ConnectionTests, Connect) {
const auto connected = connection.Connect();
ASSERT_TRUE(connected);
ASSERT_TRUE(AwaitConnections(1));
ASSERT_TRUE(mockTls.Await([this]{ return mockTls.tlsHandshakeCalled; }));
ASSERT_EQ("PogChamp", mockTls.caCerts);
}
TEST_F(ConnectionTests, DisconnectWhenNotConnectedShouldNotCrash) {
connection.Disconnect();
}
TEST_F(ConnectionTests, SendWhenNotConnectedShouldNotCrash) {
connection.Send("HeyGuys");
}
TEST_F(ConnectionTests, BreakClientSide) {
(void)connection.Connect();
ASSERT_TRUE(AwaitConnections(1));
ASSERT_TRUE(mockTls.Await([this]{ return mockTls.tlsHandshakeCalled; }));
connection.Disconnect();
ASSERT_TRUE(AwaitClientBreak(0));
}
TEST_F(ConnectionTests, BreakServerSide) {
(void)connection.Connect();
ASSERT_TRUE(AwaitConnections(1));
ASSERT_TRUE(mockTls.Await([this]{ return mockTls.tlsHandshakeCalled; }));
clients[0].connection->Close(false);
ASSERT_TRUE(AwaitServerBreak());
}
TEST_F(ConnectionTests, ClientSend) {
(void)connection.Connect();
ASSERT_TRUE(AwaitConnections(1));
ASSERT_TRUE(mockTls.Await([this]{ return mockTls.tlsHandshakeCalled; }));
const std::string testData("Hello, World!");
const std::vector< uint8_t > testDataAsBytes(
testData.begin(),
testData.end()
);
const std::vector< uint8_t > dataWeExpectServerToReceive{ 1, 2, 3, 4, 5 };
mockTls.tlsWriteEncryptedBuf = dataWeExpectServerToReceive;
connection.Send(testData);
ASSERT_TRUE(AwaitClientData(0, dataWeExpectServerToReceive.size()));
EXPECT_EQ(testDataAsBytes, mockTls.tlsWriteDecryptedBuf);
EXPECT_EQ(dataWeExpectServerToReceive, clients[0].dataReceived);
}
TEST_F(ConnectionTests, ServerSend) {
(void)connection.Connect();
ASSERT_TRUE(AwaitConnections(1));
ASSERT_TRUE(mockTls.Await([this]{ return mockTls.tlsHandshakeCalled; }));
const std::string testData("Hello, World!");
const std::vector< uint8_t > testDataAsBytes(
testData.begin(),
testData.end()
);
const std::vector< uint8_t > dataWeExpectClientToReceive{ 1, 2, 3, 4, 5 };
mockTls.tlsReadDecryptedBuf = dataWeExpectClientToReceive;
clients[0].connection->SendMessage(testDataAsBytes);
ASSERT_TRUE(AwaitServerData(dataWeExpectClientToReceive.size()));
EXPECT_EQ(dataWeExpectClientToReceive, dataReceived);
}
| 31.911493
| 127
| 0.571097
|
rhymu8354
|
156858c96393486e6af8d0f96a9e6d78ffc9e0ab
| 1,723
|
cpp
|
C++
|
Source/WinWaker/SplashDlg.cpp
|
bingart/WinWaker
|
dc3f6c067a5f215c17aa2e0c3386f92f158ec941
|
[
"Apache-2.0"
] | null | null | null |
Source/WinWaker/SplashDlg.cpp
|
bingart/WinWaker
|
dc3f6c067a5f215c17aa2e0c3386f92f158ec941
|
[
"Apache-2.0"
] | null | null | null |
Source/WinWaker/SplashDlg.cpp
|
bingart/WinWaker
|
dc3f6c067a5f215c17aa2e0c3386f92f158ec941
|
[
"Apache-2.0"
] | null | null | null |
// SplashDlg.cpp : implementation file
//
#include "stdafx.h"
#include "WinWaker.h"
#include "SplashDlg.h"
#include "afxdialogex.h"
// CSplashDlg dialog
IMPLEMENT_DYNAMIC(CSplashDlg, CDialogEx)
CSplashDlg::CSplashDlg(CWnd* pParent /*=NULL*/)
: CDialogEx(CSplashDlg::IDD, pParent)
{
m_iCount = 0;
}
CSplashDlg::~CSplashDlg()
{
}
void CSplashDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Control(pDX, IDC_STATIC_GIF, m_PictureGIF);
}
BEGIN_MESSAGE_MAP(CSplashDlg, CDialogEx)
ON_WM_TIMER()
END_MESSAGE_MAP()
// CSplashDlg message handlers
BOOL CSplashDlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
// Center window
int scrWidth = GetSystemMetrics(SM_CXSCREEN);
int scrHeight = GetSystemMetrics(SM_CYSCREEN);
this->SetWindowPos(NULL, (scrWidth - 422)/2, (scrHeight - 99)/2, 422, 99, SWP_SHOWWINDOW);
// TODO: Add extra initialization here
SetBackgroundColor(RGB(212, 208, 200));
SetBackgroundImage(IDB_BITMAP1);
RECT rect;
GetClientRect(&rect);
int y = (rect.bottom - 87)/2;
int x = y;
m_PictureGIF.SetWindowPos(NULL, x, y, 99, 87, SW_SHOW);
if (m_PictureGIF.Load(MAKEINTRESOURCE(IDR_GIF1), "GIF"))
{
// The background color must be set after picture loaded !!!
// Otherwise it will be overwritten by System Color
m_PictureGIF.SetBkColor(RGB(212, 208, 200));
m_PictureGIF.Draw();
}
SetTimer(0, 1000, NULL);
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
void CSplashDlg::OnTimer(UINT_PTR nIDEvent)
{
// TODO: Add your message handler code here and/or call default
m_iCount++;
if (m_iCount >= 3)
{
PostMessage(WM_CLOSE);
}
CDialogEx::OnTimer(nIDEvent);
}
| 20.759036
| 91
| 0.726059
|
bingart
|
1568a9fc85638dca906cddc67944f6137187db5d
| 1,600
|
hpp
|
C++
|
src/test/test.hpp
|
waxers/wax-std
|
cbaf6d26b22044b4df3f753b8226ffdfb3eb16ea
|
[
"MIT"
] | 4
|
2021-10-04T18:46:21.000Z
|
2021-10-05T11:53:23.000Z
|
src/test/test.hpp
|
waxers/wax-std
|
cbaf6d26b22044b4df3f753b8226ffdfb3eb16ea
|
[
"MIT"
] | null | null | null |
src/test/test.hpp
|
waxers/wax-std
|
cbaf6d26b22044b4df3f753b8226ffdfb3eb16ea
|
[
"MIT"
] | 1
|
2021-10-04T20:55:20.000Z
|
2021-10-04T20:55:20.000Z
|
#pragma once
#include <iostream>
#if defined(USE_COLORED_ASSERTIONS)
#define WHITE "\u001b[37m\033[1m"
#define RED "\u001b[31m\033[1m"
#define GREEN "\u001b[32m\033[1m"
#define RESET "\u001b[0m\033[0m"
#else
#define RED ""
#define WHITE ""
#define GREEN ""
#define RESET ""
#endif
namespace wax {
namespace test {
void print_test(const char *file, const int line, const char *expr,
const bool result);
void finish_tests();
} // namespace test
} // namespace wax
#define __WAX_PRINT(color, text) color << text << RESET
#define test(cond) wax::test::print_test(__FILE__, __LINE__, #cond, cond)
namespace wax {
namespace test {
unsigned okay_count = 0, fail_count = 0;
void print_test(const char *file, const int line, const char *expr,
const bool result) {
std::cout << __WAX_PRINT(WHITE, expr) << " in " << __WAX_PRINT(WHITE, file)
<< "(" << __WAX_PRINT(RED, line) << ")...";
if (result) {
std::cout << __WAX_PRINT(GREEN, "OK") << '\n';
okay_count++;
} else {
std::cout << __WAX_PRINT(RED, "ERR");
fail_count++;
}
}
void finish_tests() {
if (fail_count + okay_count == 0)
return;
std::cout << WHITE << "Tests finisheds! " << RESET << "Results:\n";
std::cout << __WAX_PRINT(GREEN, " Okay: ") << okay_count << " | "
<< __WAX_PRINT(RED, "Fail: ") << fail_count << '\n';
std::cout << __WAX_PRINT(WHITE, " Success rate: ")
<< (int)((float)okay_count / (fail_count + okay_count) * 100)
<< "%\n";
}
} // namespace test
} // namespace wax
| 26.666667
| 79
| 0.59375
|
waxers
|
156961dafd10b0959039da3e8280392d15a29eda
| 651
|
hpp
|
C++
|
src/Core/PhysicsManager.hpp
|
ariabonczek/NewLumina
|
f35cf7f449cfbe191e03e1d5f1c9973cc0b44a8e
|
[
"MIT"
] | 2
|
2017-01-08T21:30:45.000Z
|
2017-01-16T10:10:12.000Z
|
src/Core/PhysicsManager.hpp
|
ariabonczek/NewLumina
|
f35cf7f449cfbe191e03e1d5f1c9973cc0b44a8e
|
[
"MIT"
] | null | null | null |
src/Core/PhysicsManager.hpp
|
ariabonczek/NewLumina
|
f35cf7f449cfbe191e03e1d5f1c9973cc0b44a8e
|
[
"MIT"
] | null | null | null |
//--------------------------------------
// LuminaEngine belongs to Aria Bonczek
//--------------------------------------
#ifndef PHYSICS_MANAGER_HPP
#define PHYSICS_MANAGER_HPP
#include <Core\Common.hpp>
NS_BEGIN
/// <summary>
/// Manages physics object encapsulation and simulation
/// </summary>
class PhysicsManager
{
public:
PhysicsManager();
~PhysicsManager();
/// <summary>
/// Initializes the PhysicsManager
/// </summary>
void Initialize();
/// <summary>
/// Shuts down the PhysicsManager
/// </summary>
void Shutdown();
/// <summary>
/// Runs the physics simulation
/// </summary>
void Run();
private:
};
NS_END
#endif
| 16.275
| 55
| 0.605223
|
ariabonczek
|
158084c3990f67ceb24e0256a51688cdfb2e2749
| 1,783
|
cpp
|
C++
|
Interviewbit/Arrays/partitioning.cpp
|
nullpointxr/HackerRankSolutions
|
052c9ab66bfd66268b81d8e7888c3d7504ab988f
|
[
"Apache-2.0"
] | 1
|
2020-10-25T16:12:09.000Z
|
2020-10-25T16:12:09.000Z
|
Interviewbit/Arrays/partitioning.cpp
|
abhishek-sankar/Competitive-Coding-Solutions
|
052c9ab66bfd66268b81d8e7888c3d7504ab988f
|
[
"Apache-2.0"
] | 3
|
2020-11-12T05:44:24.000Z
|
2021-04-05T08:09:01.000Z
|
Interviewbit/Arrays/partitioning.cpp
|
nullpointxr/HackerRankSolutions
|
052c9ab66bfd66268b81d8e7888c3d7504ab988f
|
[
"Apache-2.0"
] | null | null | null |
/*
Partitions: https://www.interviewbit.com/problems/partitions/
Asked in: EzCred
You are given a 1D integer array B containing A integers.
Count the number of ways to split all the elements of the array into 3 contiguous parts so that the sum of elements in each part is the same.
Such that : sum(B[1],..B[i]) = sum(B[i+1],...B[j]) = sum(B[j+1],...B[n])
Problem Constraints
1 <= A <= 105
-109 <= B[i] <= 109
Input Format
First argument is an integer A.
Second argument is an 1D integer array B of size A.
Output Format
Return a single integer denoting the number of ways to split the array B into three parts with the same sum.
Example Input
Input 1:
A = 5
B = [1, 2, 3, 0, 3]
Input 2:
A = 4
B = [0, 1, -1, 0]
Example Output
Output 1:
2
Output 2:
1
Example Explanation
Explanation 1:
There are no 2 ways to make partitions -
1. (1,2)+(3)+(0,3).
2. (1,2)+(3,0)+(3).
Explanation 2:
There is only 1 way to make partition -
1. (0)+(-1,1)+(0).
*/
int Solution::solve(int A, vector<int> &B) {
int p1=0,p2=0;
long sum = 0;
for(int i=0;i<A;i++){
sum+=B[i];
}
if(sum%3!=0)return 0;
sum/=3;
long curSum = 0;
// 0 1 -1 0
long totalCuts = 0;
if(sum==0){
for(int i=0;i<A-1;i++){
curSum+=B[i];
if(curSum==0)p1++;
}
}else{
for(int i=0;i<A;i++){
curSum+=B[i];
if(i<A-1){
if(curSum==sum){
p1++;
// }else if(curSum==sum && p2!=0){
}
if(curSum==2*sum){
totalCuts+=p1;
p2++;
}
}
}
}
if(sum!=0 && p1!=0 && p2!=0)
return totalCuts;
else return p1*(p1-1)/2;
}
| 20.976471
| 141
| 0.516545
|
nullpointxr
|
1581547502475078d37e5b94aa101ea0fc273991
| 2,639
|
cpp
|
C++
|
Develop-Editor/Development/Plugin/WE/YDFont/DllMain.cpp
|
luciouskami/XYWE
|
89da4f93a2dcc02e6ea2bc739ac99a511363665c
|
[
"Apache-2.0"
] | 5
|
2019-01-22T02:35:35.000Z
|
2022-02-28T02:50:03.000Z
|
Development/Editor/Plugin/WE/YDFont/DllMain.cpp
|
yatyricky/XYWE
|
6577f4038346c258b346865808b0e3b2730611b6
|
[
"Apache-2.0"
] | 8
|
2016-10-19T00:04:05.000Z
|
2016-11-14T10:58:14.000Z
|
Development/Editor/Plugin/WE/YDFont/DllMain.cpp
|
yatyricky/XYWE
|
6577f4038346c258b346865808b0e3b2730611b6
|
[
"Apache-2.0"
] | 2
|
2016-11-14T11:39:37.000Z
|
2019-09-06T00:21:15.000Z
|
#include <Windows.h>
#include <string>
#include <memory>
#include <base/hook/iat.h>
#include <base/hook/fp_call.h>
#include <base/util/unicode.h>
#include <base/win/font/utility.h>
class FontManager
{
public:
FontManager(const char* name, size_t size);
~FontManager();
void postWindow(HWND hWnd);
private:
HFONT font_;
};
std::unique_ptr<FontManager> g_fontptr;
namespace real
{
uintptr_t CreateWindowExA = 0;
}
namespace fake
{
HWND WINAPI CreateWindowExA(DWORD dwExStyle, LPCSTR lpClassName, LPCSTR lpWindowName, DWORD dwStyle, int x, int y, int nWidth, int nHeight, HWND hWndParent, HMENU hMenu, HINSTANCE hInstance, LPVOID lpParam)
{
HWND hWnd = base::std_call<HWND>(real::CreateWindowExA, dwExStyle, lpClassName, lpWindowName, dwStyle, x, y, nWidth, nHeight, hWndParent, hMenu, hInstance, lpParam);
if (g_fontptr) g_fontptr->postWindow(hWnd);
return hWnd;
}
}
FontManager::FontManager(const char* name, size_t size)
: font_(NULL)
{
font_ = ::CreateFontW(
base::font::size_to_height(size), //字体的逻辑高度
0, //逻辑平均字符宽度
0, //与水平线的角度
0, //基线方位角度
FW_DONTCARE, //字形:常规
FALSE, //字形:斜体
FALSE, //字形:下划线
FALSE, //字形:粗体
DEFAULT_CHARSET, //字符集
OUT_DEFAULT_PRECIS, //输出精度
CLIP_DEFAULT_PRECIS, //剪截精度
DEFAULT_QUALITY, //输出品质
DEFAULT_PITCH | FF_DONTCARE, //倾斜度
base::u2w(name, base::conv_method::replace | '?').c_str() //字体
);
if (font_ != NULL)
{
real::CreateWindowExA = base::hook::iat(
::GetModuleHandle(NULL),
"user32.dll",
"CreateWindowExA",
(uintptr_t)fake::CreateWindowExA);
}
}
FontManager::~FontManager()
{
if (font_)
{
::DeleteObject(font_);
base::hook::iat(::GetModuleHandle(NULL),
"user32.dll",
"CreateWindowExA",
(uintptr_t)fake::CreateWindowExA);
}
}
void FontManager::postWindow(HWND hWnd)
{
if (font_) ::PostMessage(hWnd, WM_SETFONT, (WPARAM)(HFONT)(font_), (LPARAM)(BOOL)(0));
}
bool SetFontByName(const char* name, size_t size)
{
g_fontptr.reset(new FontManager(name, size));
return true;
}
BOOL APIENTRY DllMain(HMODULE module, DWORD reason, LPVOID pReserved)
{
if (reason == DLL_PROCESS_ATTACH)
{
::DisableThreadLibraryCalls(module);
}
else if (reason == DLL_PROCESS_DETACH)
{
g_fontptr.reset();
}
return TRUE;
}
const char *PluginName()
{
return "YDFont";
}
| 24.663551
| 208
| 0.605911
|
luciouskami
|
1581e38acaac2451c09edbaaa034d1c7ecf6d4b5
| 753
|
cpp
|
C++
|
Tasks/Optimisation-Lab1/main.cpp
|
JMChurchill/Embedded-Systems
|
f350b9d0e667adbacf692a92ac427d75e9710630
|
[
"Apache-2.0"
] | null | null | null |
Tasks/Optimisation-Lab1/main.cpp
|
JMChurchill/Embedded-Systems
|
f350b9d0e667adbacf692a92ac427d75e9710630
|
[
"Apache-2.0"
] | null | null | null |
Tasks/Optimisation-Lab1/main.cpp
|
JMChurchill/Embedded-Systems
|
f350b9d0e667adbacf692a92ac427d75e9710630
|
[
"Apache-2.0"
] | null | null | null |
#include "mbed.h"
Timer t;
#define N 100
double A[N][N];
double table[7]={1.414213562373, 1.732050807569, 2.0, 2.236067977500,2.449489742783, 2.645751311065, 2.828427124746};
using namespace std::chrono;
// main() runs in its own thread in the OS
int main()
{
int i,j,k;
printf("Hello \n");
t.reset();
t.start();
for (i=0; i<N; i++) {
for (j=0;j<N;j++){
A[i][j]=0.0;
for (k=2;k<9;k++){
// A[i][j]+=i*sqrt((double) k) + j*sqrt((double) k);
A[i][j]+=i*table[k-2] + j*table[k-2];
}
}
}
t.stop();
//printf("\nThe time taken was %f secs\n",t.read());
printf("\nThe time taken was %llu msecs\n",duration_cast<milliseconds>(t.elapsed_time()).count());
}
| 20.916667
| 117
| 0.537849
|
JMChurchill
|
158fc9278cfb680610386bce0b5de1399f822f09
| 377
|
cpp
|
C++
|
src/Image.cpp
|
towa7bc/SpotifyWebApiAdapter
|
3f4aa88eea6fc49fbc1e902df06878f5352bbf66
|
[
"Unlicense"
] | null | null | null |
src/Image.cpp
|
towa7bc/SpotifyWebApiAdapter
|
3f4aa88eea6fc49fbc1e902df06878f5352bbf66
|
[
"Unlicense"
] | null | null | null |
src/Image.cpp
|
towa7bc/SpotifyWebApiAdapter
|
3f4aa88eea6fc49fbc1e902df06878f5352bbf66
|
[
"Unlicense"
] | null | null | null |
//
// Created by Michael Wittmann on 07/05/2020.
//
#include "Image.hpp"
#include <type_traits> // for move
#include "model/modeldata.hpp" // for image
namespace spotify {
inline namespace v1 {
Image::Image(model::image t_image)
: height_(t_image.height),
url_(std::move(t_image.url)),
width_(t_image.width) {}
} // namespace v1
} // namespace spotify
| 18.85
| 45
| 0.668435
|
towa7bc
|
158fe9c27d137b316396b96432e7b5069a9871a6
| 27,209
|
hpp
|
C++
|
src/include/libgl/hud/GlHudConfig.hpp
|
pedrospeixoto/sweet
|
224248181e92615467c94b4e163596017811b5eb
|
[
"MIT"
] | null | null | null |
src/include/libgl/hud/GlHudConfig.hpp
|
pedrospeixoto/sweet
|
224248181e92615467c94b4e163596017811b5eb
|
[
"MIT"
] | null | null | null |
src/include/libgl/hud/GlHudConfig.hpp
|
pedrospeixoto/sweet
|
224248181e92615467c94b4e163596017811b5eb
|
[
"MIT"
] | 1
|
2019-03-27T01:17:59.000Z
|
2019-03-27T01:17:59.000Z
|
/*
* Copyright 2010 Martin Schreiber
*
* 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.
*/
/*
* GlHudConfig.hpp
*
* Created on: Mar 22, 2010
* Author: martin
*/
#ifndef CGLHUDCONFIG_HPP_
#define CGLHUDCONFIG_HPP_
#include <list>
#include <cmath>
#include <libgl/hud/GlWindow.hpp>
#include <libgl/hud/GlHudConfig.hpp>
#include <libgl/hud/GlFreeType.hpp>
#include <libgl/hud/GlRenderOStream.hpp>
#include <libgl/tools/RenderWindow.hpp>
/**
* HudConfig cares about config variables which can be modified via a simple gui
*
* the config variables are not stored in this class. instead, a pointer to the storage of each config
* variable is given as a parameter on setup.
*/
class GlHudConfig
{
public:
/**
* enumeration for different types of configuration values
*/
enum ConfigType
{
CONFIG_INT = 0,
CONFIG_UINT,
CONFIG_LONGLONG,
CONFIG_ULONGLONG,
CONFIG_FLOAT,
CONFIG_FLOAT_HI,
CONFIG_DOUBLE,
CONFIG_DOUBLE_HI,
CONFIG_BOOLEAN,
CONFIG_LINEBREAK, ///< insert a linebreak (empty line)
CONFIG_TEXT ///< insert some text
};
/**
* configuration for integer option values
*/
class ConfigInt
{
public:
int *value;
int min;
int max;
int delta;
void up(int c = 1)
{
*value = std::min<int>(max, *value + delta*c);
}
void down(int c = 1)
{
*value = std::max<int>(min, *value - delta*c);
}
};
/**
* configuration for unsigned integer option values
*/
class ConfigUInt
{
public:
unsigned int *value;
unsigned int min;
unsigned int max;
unsigned int delta;
void up(unsigned int c = 1)
{
*value = std::min<unsigned int>(max, *value + delta*c);
}
void down(unsigned int c = 1)
{
if (*value < delta*c)
{
*value = 0;
return;
}
*value = std::max<unsigned int>(min, *value - delta*c);
}
};
/**
* configuration for unsigned integer option values
*/
class ConfigULongLong
{
public:
unsigned long long *value;
unsigned long long min;
unsigned long long max;
unsigned long long delta;
void up(unsigned long long c = 1)
{
*value = std::min<unsigned long long>(max, *value + delta*c);
}
void down(unsigned long long c = 1)
{
if (*value < delta*c)
{
*value = 0;
return;
}
*value = std::max<unsigned long long>(min, *value - delta*c);
}
};
/**
* configuration for unsigned integer option values
*/
class ConfigLongLong
{
public:
long long *value;
long long min;
long long max;
long long delta;
void up(long long c = 1)
{
*value = std::min<long long>(max, *value + delta*c);
}
void down(long long c = 1)
{
if (*value < delta*c)
{
*value = 0;
return;
}
*value = std::max<long long>(min, *value - delta*c);
}
};
/**
* configuration for float option values
*/
class ConfigFloat
{
public:
float *value;
float min;
float max;
float delta;
void up(int c = 1)
{
*value = std::min<float>(max, *value + delta*(float)c);
}
void down(int c = 1)
{
*value = std::max<float>(min, *value - delta*(float)c);
}
};
/**
* configuration for float option values
*/
class ConfigDouble
{
public:
double *value;
double min;
double max;
double delta;
void up(int c = 1)
{
*value = std::min<double>(max, *value + delta*(double)c);
}
void down(int c = 1)
{
*value = std::max<double>(min, *value - delta*(double)c);
}
};
/**
* configuration for float option values with half increment (HI)
*
* the larger the value, the larger is the change
*
* for simplicity, the change is half of the current variables value
*/
class ConfigFloatHI
{
public:
float *value;
float min;
float max;
float delta;
void up(int c = 1)
{
for (int i = 0; i < c; i++)
{
*value = std::min<float>(max, *value*(1.0+0.5*delta));
}
}
void down(int c = 1)
{
for (int i = 0; i < c; i++)
{
*value = std::min<float>(max, *value*(1.0-0.5*delta));
}
}
};
/**
* configuration for float option values with half increment (HI)
*
* the larger the value, the larger is the change
*
* for simplicity, the change is half of the current variables value
*/
class ConfigDoubleHI
{
public:
double *value;
double min;
double max;
double delta;
void up(int c = 1)
{
for (int i = 0; i < c; i++)
{
*value = std::min<double>(max, *value*(1.0+0.5*delta));
}
}
void down(int c = 1)
{
for (int i = 0; i < c; i++)
{
*value = std::min<double>(max, *value*(1.0-0.5*delta));
}
}
};
/**
* configuration for boolean option values
*/
class ConfigBoolean
{
public:
bool *value;
void change()
{
*value = !*value;
}
};
/**
* option handler
*/
class COption
{
public:
std::string description;
ConfigType type;
int user_value;
// private handlers for rendering / gui interactions
int id; ///< unique id
bool in_area; ///< true, if mouse is within the option area
bool button_left_down; ///< true, if left mouse button is pressed (but not yet released)
bool button_right_down; ///< true, if right mouse button is pressed (but not yet released)
int area_left;
int area_right;
int area_top;
int area_bottom;
int description_render_left;
int description_render_top;
int value_render_left;
int value_render_top;
// callback handler which is called, when the value was changed
void (*callback_changed)(void *user_ptr);
void *callback_user_ptr;
COption() :
area_left(0),
area_right(0),
area_top(0),
area_bottom(0)
{
}
union
{
ConfigInt configInt;
ConfigUInt configUInt;
ConfigLongLong configLongLong;
ConfigULongLong configULongLong;
ConfigFloat configFloat;
ConfigFloatHI configFloatHI;
ConfigDouble configDouble;
ConfigDoubleHI configDoubleHI;
ConfigBoolean configBoolean;
};
COption &setupBoolean( const char *p_description,
bool *p_value,
int p_user_value = 0)
{
description = p_description;
type = CONFIG_BOOLEAN;
user_value = p_user_value;
in_area = false;
button_left_down = false;
button_right_down = false;
configBoolean.value = p_value;
callback_changed = nullptr;
return *this;
}
/**
* single precision
*/
COption &setupFloat( const char *p_description,
float *p_value,
float p_delta = 0.1,
float p_min = -std::numeric_limits<float>::infinity(),
float p_max = std::numeric_limits<float>::infinity(),
int p_user_value = 0)
{
description = p_description;
type = CONFIG_FLOAT;
user_value = p_user_value;
in_area = false;
button_left_down = false;
button_right_down = false;
configFloat.value = p_value;
configFloat.delta = p_delta;
configFloat.min = p_min;
configFloat.max = p_max;
callback_changed = nullptr;
return *this;
}
/**
* double precision
*/
COption &setupFloat( const char *p_description,
double *p_value,
double p_delta = 0.1,
double p_min = -std::numeric_limits<double>::infinity(),
double p_max = std::numeric_limits<double>::infinity(),
int p_user_value = 0)
{
description = p_description;
type = CONFIG_DOUBLE;
user_value = p_user_value;
in_area = false;
button_left_down = false;
button_right_down = false;
configDouble.value = p_value;
configDouble.delta = p_delta;
configDouble.min = p_min;
configDouble.max = p_max;
callback_changed = nullptr;
return *this;
}
/**
* single precision
*/
COption &setupFloatHI( const char *p_description,
float *p_value,
float p_delta = 0.1,
float p_min = -std::numeric_limits<float>::infinity(),
float p_max = std::numeric_limits<float>::infinity(),
int p_user_value = 0)
{
description = p_description;
type = CONFIG_FLOAT_HI;
user_value = p_user_value;
in_area = false;
button_left_down = false;
button_right_down = false;
configFloat.value = p_value;
configFloat.delta = p_delta;
configFloat.min = p_min;
configFloat.max = p_max;
callback_changed = nullptr;
return *this;
}
/**
* double precision
*/
COption &setupFloatHI( const char *p_description,
double *p_value,
double p_delta = 0.1,
double p_min = -std::numeric_limits<float>::infinity(),
double p_max = std::numeric_limits<float>::infinity(),
int p_user_value = 0)
{
description = p_description;
type = CONFIG_DOUBLE_HI;
user_value = p_user_value;
in_area = false;
button_left_down = false;
button_right_down = false;
configDouble.value = p_value;
configDouble.delta = p_delta;
configDouble.min = p_min;
configDouble.max = p_max;
callback_changed = nullptr;
return *this;
}
COption &setupInt( const char *p_description,
int *p_value,
int p_delta = 1,
int p_min = -std::numeric_limits<int>::max(),
int p_max = std::numeric_limits<int>::max(),
int p_user_value = 0)
{
description = p_description;
type = CONFIG_INT;
user_value = p_user_value;
in_area = false;
button_left_down = false;
button_right_down = false;
configInt.value = p_value;
configInt.delta = p_delta;
configInt.min = p_min;
configInt.max = p_max;
callback_changed = nullptr;
return *this;
}
COption &setupUInt( const char *p_description,
unsigned int *p_value,
unsigned int p_delta = 1,
unsigned int p_min = -std::numeric_limits<int>::max(),
unsigned int p_max = std::numeric_limits<int>::max(),
unsigned int p_user_value = 0)
{
description = p_description;
type = CONFIG_UINT;
user_value = p_user_value;
in_area = false;
button_left_down = false;
button_right_down = false;
configUInt.value = p_value;
configUInt.delta = p_delta;
configUInt.min = p_min;
configUInt.max = p_max;
callback_changed = nullptr;
return *this;
}
COption &setupULongLong(
const char *p_description,
unsigned long long *p_value,
unsigned long long p_delta = 1,
unsigned long long p_min = -std::numeric_limits<unsigned long long>::max(),
unsigned long long p_max = std::numeric_limits<unsigned long long>::max(),
unsigned long long p_user_value = 0)
{
description = p_description;
type = CONFIG_ULONGLONG;
user_value = p_user_value;
in_area = false;
button_left_down = false;
button_right_down = false;
configULongLong.value = p_value;
configULongLong.delta = p_delta;
configULongLong.min = p_min;
configULongLong.max = p_max;
callback_changed = nullptr;
return *this;
}
COption &setupLongLong(
const char *p_description,
long long *p_value,
long long p_delta = 1,
long long p_min = -std::numeric_limits<long long>::max(),
long long p_max = std::numeric_limits<long long>::max(),
long long p_user_value = 0)
{
description = p_description;
type = CONFIG_LONGLONG;
user_value = p_user_value;
in_area = false;
button_left_down = false;
button_right_down = false;
configLongLong.value = p_value;
configLongLong.delta = p_delta;
configLongLong.min = p_min;
configLongLong.max = p_max;
callback_changed = nullptr;
return *this;
}
COption &setupLinebreak()
{
description = "";
type = CONFIG_LINEBREAK;
in_area = false;
button_left_down = false;
button_right_down = false;
callback_changed = nullptr;
return *this;
}
COption &setupText(const char *p_description)
{
description = p_description;
type = CONFIG_TEXT;
in_area = false;
button_left_down = false;
button_right_down = false;
callback_changed = nullptr;
return *this;
}
};
private:
std::list<COption> option_list; ///< list with all options
bool visible; ///< true, if hud is rendered
int option_id_counter; ///< incrementing counter to set unique ids for the options
/**
* pointer to currently activated option for switching.
* when this pointer is valid and another option button is clicked with the left mouse button,
* both values are changes. this is useful for comparisons.
*/
COption *switch_option;
public:
COption *active_option; ///< pointer to currently activated or highlighted option
int area_left; /// overall configuration area for mouse interactions
int area_right;
int area_top;
int area_bottom;
int area_width;
int area_height;
GlHudConfig()
{
visible = true;
option_id_counter = 0;
active_option = nullptr;
switch_option = nullptr;
}
/**
* hide hud configuration
*/
void hide()
{
visible = false;
}
/**
* shot hud configuration
*/
void show()
{
visible = true;
}
/**
* setup a callback handler which is called, when the value changed
*/
void set_callback( void *value_ptr, ///< pointer to value
void (*callback_handler)(void *user_ptr), ///< callback handler
void *user_ptr
)
{
std::list<COption>::iterator i;
bool found = false;
for (i = option_list.begin(); i != option_list.end(); i++)
{
COption &o = *i;
switch(o.type)
{
case CONFIG_BOOLEAN:
if (o.configBoolean.value == value_ptr)
found = true;
break;
case CONFIG_INT:
if (o.configInt.value == value_ptr)
found = true;
break;
case CONFIG_UINT:
if (o.configUInt.value == value_ptr)
found = true;
break;
case CONFIG_LONGLONG:
if (o.configLongLong.value == value_ptr)
found = true;
break;
case CONFIG_ULONGLONG:
if (o.configULongLong.value == value_ptr)
found = true;
break;
case CONFIG_FLOAT:
if (o.configFloat.value == value_ptr)
found = true;
break;
case CONFIG_FLOAT_HI:
if (o.configFloat.value == value_ptr)
found = true;
break;
case CONFIG_DOUBLE:
if (o.configDouble.value == value_ptr)
found = true;
break;
case CONFIG_DOUBLE_HI:
if (o.configDouble.value == value_ptr)
found = true;
break;
default:
break;
}
if (found)
break;
}
if (!found)
return;
(*i).callback_changed = callback_handler;
(*i).callback_user_ptr = user_ptr;
}
/**
* insert new option into configuration list
*/
void insert(COption &p_option)
{
p_option.id = option_id_counter;
option_list.push_back(p_option);
option_id_counter++;
}
GlFreeType *cGlFreeType;
GlRenderOStream *cGlRenderOStream;
/**
* setup area_* variables to speedup rendering and mouse interactions
*/
void setup(
GlFreeType &io_cGlFreeType,
GlRenderOStream &io_cGlRenderOStream,
int i_pos_x, // x position to start rendering
int i_pos_y // y position to start rendering - this is the left upper corner of the first character!!!
)
{
cGlFreeType = &io_cGlFreeType;
cGlRenderOStream = &io_cGlRenderOStream;
// get maximum text length
int max_text_length = 0;
for (std::list<COption>::iterator i = option_list.begin(); i != option_list.end(); i++)
max_text_length = std::max<int>(cGlFreeType->getTextLength((*i).description.c_str()), max_text_length);
int description_value_spacing = cGlFreeType->font_size/2;
area_left = 0xfffffff;
area_right = -0xfffffff;
area_bottom = 0xfffffff;
area_top = -0xfffffff;
for (std::list<COption>::iterator i = option_list.begin(); i != option_list.end(); i++)
{
COption &o = *i;
int text_length = cGlFreeType->getTextLength(o.description.c_str());
o.area_left = i_pos_x + max_text_length - text_length;
o.area_top = i_pos_y;
// relative (window coords) render position of description text
o.description_render_left = i_pos_x + max_text_length - text_length;
o.description_render_top = i_pos_y - cGlFreeType->font_size;
// relative position to render value
o.value_render_left = i_pos_x + max_text_length + description_value_spacing;
o.value_render_top = i_pos_y - cGlFreeType->font_size;
int advance_x = 0;
// render values / control
switch(o.type)
{
case CONFIG_BOOLEAN:
case CONFIG_INT:
case CONFIG_UINT:
case CONFIG_LONGLONG:
case CONFIG_ULONGLONG:
case CONFIG_FLOAT:
case CONFIG_FLOAT_HI:
case CONFIG_DOUBLE:
case CONFIG_DOUBLE_HI:
advance_x = cGlFreeType->font_size*4;
break;
default:
break;
}
o.area_right = i_pos_x + max_text_length + advance_x;
o.area_bottom = i_pos_y - cGlFreeType->font_size;
area_left = std::min<int>(area_left, o.area_left);
area_right = std::max<int>(area_right, o.area_right);
area_bottom = std::min<int>(area_bottom, o.area_bottom);
area_top = std::max<int>(area_top, o.area_top);
// next line
i_pos_y -= cGlFreeType->font_size;
}
area_width = area_right - area_left;
area_height = area_top - area_bottom;
}
void renderConfigContent()
{
if (!visible)
return;
GlRenderOStream &cGlRenderOStream_ = *cGlRenderOStream;
cGlFreeType->setColor(GLSL::vec3(1,1,1));
CGlErrorCheck();
for (std::list<COption>::iterator i = option_list.begin(); i != option_list.end(); i++)
{
COption &o = *i;
if (o.button_left_down)
cGlFreeType->setColor(GLSL::vec3(0.7,1,0.7));
else if (o.in_area)
cGlFreeType->setColor(GLSL::vec3(1,0.5,0.5));
std::array<float,2> tmp;
tmp = {(float)o.description_render_left, (float)o.description_render_top};
cGlFreeType->setPosition(tmp);
cGlRenderOStream_ << o.description << std::flush;
tmp = {(float)o.value_render_left, (float)o.value_render_top};
cGlFreeType->setPosition(tmp);
switch(o.type)
{
case CONFIG_BOOLEAN:
cGlRenderOStream_ << (*o.configBoolean.value ? "X" : "O") << std::flush;
if (&o == switch_option)
cGlRenderOStream_ << " S" << std::flush;
break;
case CONFIG_INT:
cGlRenderOStream_ << *o.configInt.value << std::flush;
break;
case CONFIG_UINT:
cGlRenderOStream_ << *o.configUInt.value << std::flush;
break;
case CONFIG_LONGLONG:
cGlRenderOStream_ << *o.configLongLong.value << std::flush;
break;
case CONFIG_ULONGLONG:
cGlRenderOStream_ << *o.configULongLong.value << std::flush;
break;
case CONFIG_FLOAT:
cGlRenderOStream_ << *o.configFloat.value << std::flush;
break;
case CONFIG_FLOAT_HI:
cGlRenderOStream_ << *o.configFloatHI.value << std::flush;
break;
case CONFIG_DOUBLE:
cGlRenderOStream_ << *o.configDouble.value << std::flush;
break;
case CONFIG_DOUBLE_HI:
cGlRenderOStream_ << *o.configDoubleHI.value << std::flush;
break;
default:
break;
}
CGlErrorCheck();
if (o.button_left_down || o.in_area)
cGlFreeType->setColor(GLSL::vec3(1,1,1));
CGlErrorCheck();
}
}
int old_mouse_x;
int old_mouse_y;
/**
* CALLBACK FUNCTION: mouse button is pressed
*/
void mouse_button_down(int button)
{
if (active_option != nullptr)
{
if (button == RenderWindow::MOUSE_BUTTON_LEFT)
active_option->button_left_down = true;
if (button == RenderWindow::MOUSE_BUTTON_RIGHT)
active_option->button_right_down = true;
}
}
/**
* CALLBACK FUNCTION: mouse button is released
*/
void mouse_wheel(int x, int y)
{
if (active_option == nullptr)
return;
switch(active_option->type)
{
case CONFIG_BOOLEAN:
if (y & 1)
{
active_option->configBoolean.change();
if (active_option->callback_changed) active_option->callback_changed(active_option->callback_user_ptr);
}
break;
case CONFIG_INT:
if (y > 0)
active_option->configInt.up();
else if (y < 0)
active_option->configInt.down();
if (active_option->callback_changed) active_option->callback_changed(active_option->callback_user_ptr);
break;
case CONFIG_UINT:
if (y > 0)
active_option->configUInt.up();
else if (y < 0)
active_option->configUInt.down();
if (active_option->callback_changed) active_option->callback_changed(active_option->callback_user_ptr);
break;
case CONFIG_LONGLONG:
if (y > 0)
active_option->configLongLong.up();
else if (y < 0)
active_option->configLongLong.down();
if (active_option->callback_changed) active_option->callback_changed(active_option->callback_user_ptr);
break;
case CONFIG_ULONGLONG:
if (y > 0)
active_option->configULongLong.up();
else if (y < 0)
active_option->configULongLong.down();
if (active_option->callback_changed) active_option->callback_changed(active_option->callback_user_ptr);
break;
case CONFIG_FLOAT:
if (y > 0)
active_option->configFloat.up();
else if (y < 0)
active_option->configFloat.down();
if (active_option->callback_changed) active_option->callback_changed(active_option->callback_user_ptr);
break;
case CONFIG_FLOAT_HI:
if (y > 0)
active_option->configFloatHI.up();
else if (y < 0)
active_option->configFloatHI.down();
if (active_option->callback_changed) active_option->callback_changed(active_option->callback_user_ptr);
break;
case CONFIG_DOUBLE:
if (y > 0)
active_option->configDouble.up();
else if (y < 0)
active_option->configDouble.down();
if (active_option->callback_changed) active_option->callback_changed(active_option->callback_user_ptr);
break;
case CONFIG_DOUBLE_HI:
if (y > 0)
active_option->configDoubleHI.up();
else if (y < 0)
active_option->configDoubleHI.down();
if (active_option->callback_changed) active_option->callback_changed(active_option->callback_user_ptr);
break;
default:
break;
}
}
/**
* CALLBACK FUNCTION: mouse button is released
*/
void mouse_button_up(int button)
{
if (active_option == nullptr)
return;
mouse_motion(old_mouse_x, old_mouse_y);
if (active_option->button_left_down == true)
{
active_option->button_left_down = false;
switch(active_option->type)
{
case CONFIG_BOOLEAN:
active_option->configBoolean.change();
if (switch_option != nullptr && switch_option != active_option)
switch_option->configBoolean.change();
if (active_option->callback_changed) active_option->callback_changed(active_option->callback_user_ptr);
break;
case CONFIG_INT:
break;
case CONFIG_UINT:
break;
case CONFIG_LONGLONG:
break;
case CONFIG_ULONGLONG:
break;
case CONFIG_FLOAT:
break;
default:
break;
}
return;
}
if (active_option->button_right_down == true)
{
active_option->button_right_down = false;
if (switch_option == active_option)
{
// deactivate this option as the switch option button
switch_option = nullptr;
return;
}
else
{
// otherwise set the current option to the switch option
if (active_option->type != CONFIG_BOOLEAN)
return;
switch_option = active_option;
return;
}
}
}
/**
* CALLBACK FUNCTION: mouse is moved
*
* \return true, if the mouse motion is handled by the configuration hud
*/
bool mouse_motion(int x, int y)
{
if (active_option != nullptr)
{
int dx = (old_mouse_x - x) + (old_mouse_y - y);
// int dy = old_mouse_y - y;
if (active_option->button_left_down)
{
switch(active_option->type)
{
case CONFIG_FLOAT:
if (dx > 0) active_option->configFloat.down(dx);
else if (dx < 0) active_option->configFloat.up(-dx);
if (active_option->callback_changed) active_option->callback_changed(active_option->callback_user_ptr);
break;
case CONFIG_FLOAT_HI:
if (dx > 0) active_option->configFloatHI.down(dx);
else if (dx < 0) active_option->configFloatHI.up(-dx);
if (active_option->callback_changed) active_option->callback_changed(active_option->callback_user_ptr);
break;
case CONFIG_DOUBLE:
if (dx > 0) active_option->configDouble.down(dx);
else if (dx < 0) active_option->configDouble.up(-dx);
if (active_option->callback_changed) active_option->callback_changed(active_option->callback_user_ptr);
break;
case CONFIG_DOUBLE_HI:
if (dx > 0) active_option->configDoubleHI.down(dx);
else if (dx < 0) active_option->configDoubleHI.up(-dx);
if (active_option->callback_changed) active_option->callback_changed(active_option->callback_user_ptr);
break;
case CONFIG_INT:
if (dx > 0) active_option->configInt.down(dx);
else if (dx < 0) active_option->configInt.up(-dx);
if (active_option->callback_changed) active_option->callback_changed(active_option->callback_user_ptr);
break;
case CONFIG_UINT:
if (dx > 0) active_option->configUInt.down(dx);
else if (dx < 0) active_option->configUInt.up(-dx);
if (active_option->callback_changed) active_option->callback_changed(active_option->callback_user_ptr);
break;
case CONFIG_LONGLONG:
if (dx > 0) active_option->configLongLong.down(dx);
else if (dx < 0) active_option->configLongLong.up(-dx);
if (active_option->callback_changed) active_option->callback_changed(active_option->callback_user_ptr);
break;
case CONFIG_ULONGLONG:
if (dx > 0) active_option->configULongLong.down(dx);
else if (dx < 0) active_option->configULongLong.up(-dx);
if (active_option->callback_changed) active_option->callback_changed(active_option->callback_user_ptr);
break;
default:
break;
}
old_mouse_x = x;
old_mouse_y = y;
return true;
}
}
old_mouse_x = x;
old_mouse_y = y;
/**
* we only like to change the state of an option, when we are inside the configuration area
*/
if (area_left <= x && area_right >= x && area_top >= y && area_bottom <= y)
{
int c = 0;
for (std::list<COption>::iterator i = option_list.begin(); i != option_list.end(); i++)
{
COption &o = *i;
// check, if we are inside the current option area
if (o.area_left <= x && o.area_right > x && o.area_top > y && o.area_bottom <= y)
{
// we are still in in the same valid area => do nothing
if (active_option == &o)
return true;
if (active_option != nullptr)
{
active_option->in_area = false;
active_option->button_left_down = false;
}
if (o.type == CONFIG_TEXT || o.type == CONFIG_LINEBREAK)
{
active_option = nullptr;
return true;
}
// activate area
o.in_area = true;
active_option = &o;
return true;
}
c++;
}
}
if (active_option == nullptr)
return true;
active_option->in_area = false;
active_option->button_left_down = false;
active_option = nullptr;
return false;
}
};
#endif /* CGLHUDCONFIG_HPP_ */
| 22.486777
| 108
| 0.659047
|
pedrospeixoto
|
1593f1f8f22045bf3e57a19eeea1f4eb6c7ae8cd
| 680
|
hpp
|
C++
|
iRODS/lib/api/include/ies_client_hints.hpp
|
nesi/irods
|
49eeaf76305fc483f21b1bbfbdd77d540b59cfd2
|
[
"BSD-3-Clause"
] | null | null | null |
iRODS/lib/api/include/ies_client_hints.hpp
|
nesi/irods
|
49eeaf76305fc483f21b1bbfbdd77d540b59cfd2
|
[
"BSD-3-Clause"
] | null | null | null |
iRODS/lib/api/include/ies_client_hints.hpp
|
nesi/irods
|
49eeaf76305fc483f21b1bbfbdd77d540b59cfd2
|
[
"BSD-3-Clause"
] | null | null | null |
#ifndef IES_CLIENT_HINTS_HPP
#define IES_CLIENT_HINTS_HPP
// =-=-=-=-=-=-=-
// irods includes
#include "rods.hpp"
#include "rcMisc.hpp"
#include "procApiRequest.hpp"
#include "apiNumber.hpp"
#define IES_CLIENT_HINTS_AN 10216
#ifdef RODS_SERVER
#define RS_IES_CLIENT_HINTS rsClientHints
int rsIESClientHints(
rsComm_t*, // server comm ptr
bytesBuf_t** ); // json response
#else
#define RS_IES_CLIENT_HINTS NULL
#endif
#ifdef __cplusplus
extern "C" {
#endif
// =-=-=-=-=-=-=-
// prototype for client
int rcIESClientHints(
rcComm_t*, // server comm ptr
bytesBuf_t** ); // json response
#ifdef __cplusplus
}
#endif
#endif // IES_CLIENT_HINTS_HPP
| 16.585366
| 41
| 0.7
|
nesi
|
159a1cd31499f204a5a33837c60a87fa533e4a6b
| 376
|
cpp
|
C++
|
src/Lucia/Maigui/Types/Widget.cpp
|
Polynominal/Lucy3D
|
a55fc331bc509a69ad7fb70a1eda70c409d22271
|
[
"MIT"
] | 1
|
2017-02-22T23:47:22.000Z
|
2017-02-22T23:47:22.000Z
|
src/Lucia/Maigui/Types/Widget.cpp
|
Polynominal/Lucy3D
|
a55fc331bc509a69ad7fb70a1eda70c409d22271
|
[
"MIT"
] | null | null | null |
src/Lucia/Maigui/Types/Widget.cpp
|
Polynominal/Lucy3D
|
a55fc331bc509a69ad7fb70a1eda70c409d22271
|
[
"MIT"
] | null | null | null |
#include "Lucia/Maigui/Types/Widget.h"
namespace Lucia {
namespace Maigui {
Widget::Widget(Vertex position,Vertex dimensions,shared_ptr<Skin> sk)
{
Position = position;
Dimensions = dimensions;
skin = sk;
Name = "Widget";
//ctor
};
Widget::~Widget()
{
remove();
//dtor
}
} // namespace Maigui
}
| 18.8
| 73
| 0.558511
|
Polynominal
|
159be183edc486470e3bbcc8b8a0fa8edc571f28
| 932
|
cpp
|
C++
|
src/card.cpp
|
masakeida/PlayingCards
|
d6c2f890b0e0ee445b799b6ac1d54573e97e83bf
|
[
"BSD-2-Clause"
] | null | null | null |
src/card.cpp
|
masakeida/PlayingCards
|
d6c2f890b0e0ee445b799b6ac1d54573e97e83bf
|
[
"BSD-2-Clause"
] | null | null | null |
src/card.cpp
|
masakeida/PlayingCards
|
d6c2f890b0e0ee445b799b6ac1d54573e97e83bf
|
[
"BSD-2-Clause"
] | null | null | null |
#include <string>
#include "card.hpp"
Card::Card()
{
this->value = FaceValue::SEVEN;
}
Card::Card(FaceValue value, FaceSuit faceSuit)
{
this->value = value;
this->setFaceSuit(faceSuit);
}
void
Card::setFaceValue(FaceValue value)
{
this->value = value;
}
void
Card::setFaceSuit(FaceSuit faceSuit)
{
this->suit.setSuit(faceSuit);
}
FaceValue
Card::getFaceValue()
{
return this->value;
}
FaceSuit
Card::getFaceSuit()
{
return this->suit.getSuit();
}
std::string
Card::toString()
{
std::string cardFace;
cardFace = this->suit.toString();
cardFace += faceValueStringSimple[static_cast<int>(this->value)];
return cardFace;
}
std::string
Card::toStringFaceValue()
{
std::string cardFaceValue;
cardFaceValue = faceValueStringSimple[static_cast<int>(this->value)];
return cardFaceValue;
}
std::string
Card::toStringFaceSuit()
{
std::string cardFaceSuit;
cardFaceSuit = this->suit.toString();
return cardFaceSuit;
}
| 14.793651
| 70
| 0.724249
|
masakeida
|
15a8baef534c5b3021eee20b9ef9510708d77a53
| 296
|
cpp
|
C++
|
src/array/delete_data.cpp
|
violador/catalyst
|
40d5c1dd04269a0764a9804711354a474bc43c15
|
[
"Unlicense"
] | null | null | null |
src/array/delete_data.cpp
|
violador/catalyst
|
40d5c1dd04269a0764a9804711354a474bc43c15
|
[
"Unlicense"
] | null | null | null |
src/array/delete_data.cpp
|
violador/catalyst
|
40d5c1dd04269a0764a9804711354a474bc43c15
|
[
"Unlicense"
] | null | null | null |
//
//
//
/// @brief A private member function to deallocate the current memory
/// and to clean the data members. The operation is carried out by the
/// master thread only.
//
/// @return None.
//
inline void delete_data()
{
#pragma omp master
{
delete[] data;
reset_data_members();
}
};
| 16.444444
| 70
| 0.668919
|
violador
|
15a9d476ca561f99bd32e5d92854a1c2391ddf11
| 20,636
|
cpp
|
C++
|
src/plugProjectKandoU/gamePlayCommonData.cpp
|
projectPiki/pikmin2
|
a431d992acde856d092889a515ecca0e07a3ea7c
|
[
"Unlicense"
] | 33
|
2021-12-08T11:10:59.000Z
|
2022-03-26T19:59:37.000Z
|
src/plugProjectKandoU/gamePlayCommonData.cpp
|
projectPiki/pikmin2
|
a431d992acde856d092889a515ecca0e07a3ea7c
|
[
"Unlicense"
] | 6
|
2021-12-22T17:54:31.000Z
|
2022-01-07T21:43:18.000Z
|
src/plugProjectKandoU/gamePlayCommonData.cpp
|
projectPiki/pikmin2
|
a431d992acde856d092889a515ecca0e07a3ea7c
|
[
"Unlicense"
] | 2
|
2022-01-04T06:00:49.000Z
|
2022-01-26T07:27:28.000Z
|
#include "Game/BirthMgr.h"
#include "Game/Data.h"
#include "Game/DeathMgr.h"
#include "Game/GameConfig.h"
#include "Game/gamePlayData.h"
#include "JSystem/JUT/JUTException.h"
#include "System.h"
#include "types.h"
/*
Generated from dpostproc
.section .rodata # 0x804732E0 - 0x8049E220
.global lbl_80483A88
lbl_80483A88:
.asciz "gamePlayCommonData.cpp"
.skip 1
.global lbl_80483AA0
lbl_80483AA0:
.asciz "P2Assert"
.skip 3
.section .data, "wa" # 0x8049E220 - 0x804EFC20
.global __vt__Q24Game8Lowscore
__vt__Q24Game8Lowscore:
.4byte 0
.4byte 0
.4byte do_higher__Q24Game8LowscoreFii
.4byte 0
*/
namespace Game {
/*
* --INFO--
* Address: 8023410C
* Size: 0000FC
*/
PlayCommonData::PlayCommonData()
: _00(0)
, m_challengeData()
{
_04 = new Highscore*[16];
_08 = new Highscore*[16];
for (int i = 0; i < 0x10; i++) {
_04[i] = new Lowscore();
_08[i] = new Lowscore();
_04[i]->allocate(3);
_08[i]->allocate(3);
}
reset();
}
/*
* --INFO--
* Address: 80234208
* Size: 000078
*/
void PlayCommonData::reset()
{
_00 = 0;
m_challengeData.reset();
for (int i = 0; i < 0x10; i++) {
_04[i]->clear();
_08[i]->clear();
}
}
/*
* reset__Q24Game21PlayChallengeGameDataFv
* --INFO--
* Address: 80234280
* Size: 0000C0
*/
void PlayChallengeGameData::reset()
{
m_flags = PCGDF_Unset;
for (int i = 0; i < m_courseCount; i++) {
CourseState* course = &m_courses[i];
course->m_highscores[0].clear();
course->m_highscores[1].clear();
course->m_flags.byteView[0] = 0;
course->m_flags.byteView[1] = 0;
}
m_courses[0].m_flags.typeView |= CourseState::CSF_IsOpen;
m_courses[1].m_flags.typeView |= CourseState::CSF_IsOpen;
m_courses[2].m_flags.typeView |= CourseState::CSF_IsOpen;
m_courses[3].m_flags.typeView |= CourseState::CSF_IsOpen;
m_courses[4].m_flags.typeView |= CourseState::CSF_IsOpen;
/*
stwu r1, -0x20(r1)
mflr r0
stw r0, 0x24(r1)
stmw r27, 0xc(r1)
li r30, 0
mr r31, r3
li r27, 0
mr r28, r30
stb r30, 8(r3)
b lbl_802342D0
lbl_802342A8:
lwz r0, 4(r31)
add r29, r0, r28
addi r3, r29, 4
bl clear__Q24Game9HighscoreFv
addi r3, r29, 0x10
bl clear__Q24Game9HighscoreFv
stb r30, 0(r29)
addi r28, r28, 0x1c
addi r27, r27, 1
stb r30, 1(r29)
lbl_802342D0:
lwz r0, 0(r31)
cmpw r27, r0
blt lbl_802342A8
lwz r3, 4(r31)
lhz r0, 0(r3)
ori r0, r0, 1
sth r0, 0(r3)
lwz r3, 4(r31)
lhz r0, 0x1c(r3)
ori r0, r0, 1
sth r0, 0x1c(r3)
lwz r3, 4(r31)
lhz r0, 0x38(r3)
ori r0, r0, 1
sth r0, 0x38(r3)
lwz r3, 4(r31)
lhz r0, 0x54(r3)
ori r0, r0, 1
sth r0, 0x54(r3)
lwz r3, 4(r31)
lhz r0, 0x70(r3)
ori r0, r0, 1
sth r0, 0x70(r3)
lmw r27, 0xc(r1)
lwz r0, 0x24(r1)
mtlr r0
addi r1, r1, 0x20
blr
*/
}
/*
* write__Q24Game14PlayCommonDataFR6Stream
* --INFO--
* Address: 80234340
* Size: 0000A0
*/
void PlayCommonData::write(Stream& output)
{
output.writeInt(2);
output.writeByte(_00);
for (int i = 0; i < 0x10; i++) {
_04[i]->write(output);
_08[i]->write(output);
}
m_challengeData.write(output);
/*
stwu r1, -0x20(r1)
mflr r0
stw r0, 0x24(r1)
stw r31, 0x1c(r1)
stw r30, 0x18(r1)
stw r29, 0x14(r1)
mr r29, r4
li r4, 2
stw r28, 0x10(r1)
mr r28, r3
mr r3, r29
bl writeInt__6StreamFi
mr r3, r29
lbz r4, 0(r28)
bl writeByte__6StreamFUc
li r30, 0
li r31, 0
lbl_80234384:
lwz r3, 4(r28)
mr r4, r29
lwzx r3, r3, r31
bl write__Q24Game9HighscoreFR6Stream
lwz r3, 8(r28)
mr r4, r29
lwzx r3, r3, r31
bl write__Q24Game9HighscoreFR6Stream
addi r30, r30, 1
addi r31, r31, 4
cmpwi r30, 0x10
blt lbl_80234384
mr r4, r29
addi r3, r28, 0xc
bl write__Q24Game21PlayChallengeGameDataFR6Stream
lwz r0, 0x24(r1)
lwz r31, 0x1c(r1)
lwz r30, 0x18(r1)
lwz r29, 0x14(r1)
lwz r28, 0x10(r1)
mtlr r0
addi r1, r1, 0x20
blr
*/
}
/*
* read__Q24Game14PlayCommonDataFR6Stream
* --INFO--
* Address: 802343E0
* Size: 0000EC
*/
void PlayCommonData::read(Stream&)
{
/*
stwu r1, -0x20(r1)
mflr r0
stw r0, 0x24(r1)
stw r31, 0x1c(r1)
stw r30, 0x18(r1)
stw r29, 0x14(r1)
mr r29, r4
stw r28, 0x10(r1)
mr r28, r3
mr r3, r29
bl readInt__6StreamFv
mr r31, r3
mr r3, r29
bl readByte__6StreamFv
cmplwi r31, 2
stb r3, 0(r28)
blt lbl_80234460
li r30, 0
li r31, 0
lbl_8023442C:
lwz r3, 4(r28)
mr r4, r29
lwzx r3, r3, r31
bl read__Q24Game9HighscoreFR6Stream
lwz r3, 8(r28)
mr r4, r29
lwzx r3, r3, r31
bl read__Q24Game9HighscoreFR6Stream
addi r30, r30, 1
addi r31, r31, 4
cmpwi r30, 0x10
blt lbl_8023442C
b lbl_802344A0
lbl_80234460:
cmplwi r31, 1
bgt lbl_802344A0
li r30, 0
li r31, 0
lbl_80234470:
lwz r3, 4(r28)
mr r4, r29
lwzx r3, r3, r31
bl read__Q24Game9HighscoreFR6Stream
lwz r3, 8(r28)
mr r4, r29
lwzx r3, r3, r31
bl read__Q24Game9HighscoreFR6Stream
addi r30, r30, 1
addi r31, r31, 4
cmpwi r30, 0xf
blt lbl_80234470
lbl_802344A0:
mr r4, r29
addi r3, r28, 0xc
bl read__Q24Game21PlayChallengeGameDataFR6Stream
lwz r0, 0x24(r1)
lwz r31, 0x1c(r1)
lwz r30, 0x18(r1)
lwz r29, 0x14(r1)
lwz r28, 0x10(r1)
mtlr r0
addi r1, r1, 0x20
blr
*/
}
/*
* --INFO--
* Address: 802344CC
* Size: 000078
*/
Highscore* PlayCommonData::getHighscore_clear(int index)
{
bool isValidIndex = false;
if (0 <= index && index < 0x10) {
isValidIndex = true;
}
P2ASSERTLINE(155, isValidIndex);
return _04[index];
}
/*
* --INFO--
* Address: 80234544
* Size: 000078
*/
Highscore* PlayCommonData::getHighscore_complete(int index)
{
bool isValidIndex = false;
if (0 <= index && index < 0x10) {
isValidIndex = true;
}
P2ASSERTLINE(162, isValidIndex);
return _08[index];
}
/*
* --INFO--
* Address: 802345BC
* Size: 000038
*/
void PlayCommonData::entryHighscores_clear(int newTotal, int* totals, int* scores)
{
entryHighscores_common(_04, newTotal, totals, scores);
}
/*
* --INFO--
* Address: 802345F4
* Size: 000038
*/
void PlayCommonData::entryHighscores_complete(int newTotal, int* totals, int* scores)
{
entryHighscores_common(_08, newTotal, totals, scores);
}
/*
* --INFO--
* Address: 8023462C
* Size: 0000E0
*/
void PlayCommonData::entryHighscores_common(Game::Highscore** highscores, int newTotal, int* totals, int* scores)
{
totals[0] = newTotal;
scores[0] = highscores[0]->entryScore(newTotal);
for (int i = 0; i < 8; i++) {
totals[i + 1] = DeathMgr::get_total((DeathMgr::CauseOfDeath)i);
scores[i + 1] = highscores[i + 1]->entryScore(totals[i + 1]);
}
for (int i = 0; i < 6; i++) {
totals[i + 9] = BirthMgr::get_total(i);
scores[i + 9] = highscores[i + 9]->entryScore(totals[i + 9]);
}
CommonSaveData::Mgr* playCommonData = sys->getPlayCommonData();
int timeTotal = playData->calcPlayMinutes() + playCommonData->_1C;
totals[0xF] = timeTotal;
scores[0xF] = highscores[0xF]->entryScore(timeTotal);
/*
stwu r1, -0x20(r1)
mflr r0
stw r0, 0x24(r1)
stmw r26, 8(r1)
mr r26, r4
mr r27, r6
mr r28, r7
lwz r3, 0(r4)
mr r4, r5
stw r5, 0(r6)
bl entryScore__Q24Game9HighscoreFi
stw r3, 0(r28)
li r30, 0
lbl_80234660:
addi r0, r30, 1
mr r3, r30
slwi r31, r0, 2
lwzx r29, r26, r31
bl get_total__Q24Game8DeathMgrFi
stwx r3, r27, r31
mr r3, r29
lwzx r4, r27, r31
bl entryScore__Q24Game9HighscoreFi
addi r30, r30, 1
stwx r3, r28, r31
cmpwi r30, 8
blt lbl_80234660
li r29, 0
lbl_80234698:
addi r0, r29, 9
mr r3, r29
slwi r31, r0, 2
lwzx r30, r26, r31
bl get_total__Q24Game8BirthMgrFi
stwx r3, r27, r31
mr r3, r30
lwzx r4, r27, r31
bl entryScore__Q24Game9HighscoreFi
addi r29, r29, 1
stwx r3, r28, r31
cmpwi r29, 6
blt lbl_80234698
lwz r3, sys@sda21(r13)
lwz r29, 0x3c(r26)
lwz r31, 0x60(r3)
lwz r3, playData__4Game@sda21(r13)
bl calcPlayMinutes__Q24Game8PlayDataFv
lwz r0, 0x1c(r31)
add r4, r3, r0
mr r3, r29
stw r4, 0x3c(r27)
bl entryScore__Q24Game9HighscoreFi
stw r3, 0x3c(r28)
lmw r26, 8(r1)
lwz r0, 0x24(r1)
mtlr r0
addi r1, r1, 0x20
blr
*/
}
/*
* --INFO--
* Address: 8023470C
* Size: 00000C
*/
bool PlayCommonData::isChallengeGamePlayable(void) { return m_challengeData.m_flags & PlayChallengeGameData::PCGDF_IsPlayable; }
/*
* --INFO--
* Address: 80234718
* Size: 00000C
*/
bool PlayCommonData::isLouieRescued(void) { return m_challengeData.m_flags & PlayChallengeGameData::PCGDF_IsLouieRescued; }
/*
* --INFO--
* Address: 80234724
* Size: 00008C
*/
bool PlayCommonData::isPerfectChallenge(void)
{
/*
stwu r1, -0x10(r1)
mflr r0
stw r0, 0x14(r1)
stw r31, 0xc(r1)
stw r30, 8(r1)
mr r30, r3
lbz r0, 0(r3)
rlwinm. r0, r0, 0, 0x1d, 0x1d
beq lbl_80234750
li r3, 1
b lbl_80234798
lbl_80234750:
li r31, 0
b lbl_8023477C
lbl_80234758:
mr r4, r31
addi r3, r30, 0xc
bl getState__Q24Game21PlayChallengeGameDataFi
lhz r0, 0(r3)
rlwinm. r0, r0, 0, 0x1d, 0x1d
bne lbl_80234778
li r3, 0
b lbl_80234798
lbl_80234778:
addi r31, r31, 1
lbl_8023477C:
lwz r0, 0xc(r30)
cmpw r31, r0
blt lbl_80234758
lbz r0, 0(r30)
li r3, 1
ori r0, r0, 4
stb r0, 0(r30)
lbl_80234798:
lwz r0, 0x14(r1)
lwz r31, 0xc(r1)
lwz r30, 8(r1)
mtlr r0
addi r1, r1, 0x10
blr
*/
}
/*
* --INFO--
* Address: 802347B0
* Size: 000030
*/
void PlayCommonData::enableChallengeGame(void)
{
m_challengeData.m_flags |= PlayChallengeGameData::PCGDF_IsPlayable;
sys->setOptionBlockSaveFlag();
}
/*
* --INFO--
* Address: 802347E0
* Size: 000030
*/
void PlayCommonData::enableLouieRescue(void)
{
m_challengeData.m_flags |= PlayChallengeGameData::PCGDF_IsLouieRescued;
sys->setOptionBlockSaveFlag();
}
/*
* --INFO--
* Address: 80234810
* Size: 00001C
*/
bool PlayCommonData::challenge_is_virgin(void)
{
bool result = (u8)(m_challengeData.m_flags & PlayChallengeGameData::PCGDF_IsNotVirgin) == 0;
m_challengeData.m_flags |= PlayChallengeGameData::PCGDF_IsNotVirgin;
return result;
}
/*
* --INFO--
* Address: 8023482C
* Size: 000014
*/
bool PlayCommonData::challenge_is_virgin_check_only()
{
return (u8)(m_challengeData.m_flags & PlayChallengeGameData::PCGDF_IsNotVirgin) == 0;
}
/*
* --INFO--
* Address: 80234840
* Size: 000024
*/
PlayChallengeGameData::CourseState* PlayCommonData::challenge_get_CourseState(int index) { return m_challengeData.getState(index); }
/*
* --INFO--
* Address: ........
* Size: 000008
*/
int PlayCommonData::challenge_get_coursenum()
{
// UNUSED FUNCTION
return m_challengeData.m_courseCount;
}
/*
* --INFO--
* Address: 80234864
* Size: 00002C
*/
bool PlayCommonData::challenge_checkOpen(int index)
{
return challenge_get_CourseState(index)->m_flags.typeView & PlayChallengeGameData::CourseState::CSF_IsOpen;
}
/*
* --INFO--
* Address: 80234890
* Size: 00002C
*/
bool PlayCommonData::challenge_checkClear(int index)
{
return challenge_get_CourseState(index)->m_flags.typeView & PlayChallengeGameData::CourseState::CSF_IsClear;
}
/*
* --INFO--
* Address: 802348BC
* Size: 00002C
*/
bool PlayCommonData::challenge_checkKunsho(int index)
{
return challenge_get_CourseState(index)->m_flags.typeView & PlayChallengeGameData::CourseState::CSF_IsKunsho;
}
/*
* --INFO--
* Address: 802348E8
* Size: 00004C
*/
bool PlayCommonData::challenge_checkJustOpen(int index)
{
PlayChallengeGameData::CourseState* state = challenge_get_CourseState(index);
u16 flags = state->m_flags.typeView;
if (flags & PlayChallengeGameData::CourseState::CSF_IsOpen) {
state->m_flags.typeView |= PlayChallengeGameData::CourseState::CSF_WasOpen;
return (flags & PlayChallengeGameData::CourseState::CSF_WasOpen) == 0;
}
return false;
/*
stwu r1, -0x10(r1)
mflr r0
addi r3, r3, 0xc
stw r0, 0x14(r1)
bl getState__Q24Game21PlayChallengeGameDataFi
lhz r4, 0(r3)
clrlwi. r0, r4, 0x1f
beq lbl_80234920
rlwinm r0, r4, 0, 0x1c, 0x1c
ori r4, r4, 8
cntlzw r0, r0
sth r4, 0(r3)
srwi r3, r0, 5
b lbl_80234924
lbl_80234920:
li r3, 0
lbl_80234924:
lwz r0, 0x14(r1)
mtlr r0
addi r1, r1, 0x10
blr
*/
}
/*
* --INFO--
* Address: 80234934
* Size: 00004C
*/
bool PlayCommonData::challenge_checkJustClear(int)
{
/*
stwu r1, -0x10(r1)
mflr r0
addi r3, r3, 0xc
stw r0, 0x14(r1)
bl getState__Q24Game21PlayChallengeGameDataFi
lhz r4, 0(r3)
rlwinm. r0, r4, 0, 0x1e, 0x1e
beq lbl_8023496C
rlwinm r0, r4, 0, 0x1b, 0x1b
ori r4, r4, 0x10
cntlzw r0, r0
sth r4, 0(r3)
srwi r3, r0, 5
b lbl_80234970
lbl_8023496C:
li r3, 0
lbl_80234970:
lwz r0, 0x14(r1)
mtlr r0
addi r1, r1, 0x10
blr
*/
}
/*
* --INFO--
* Address: 80234980
* Size: 00004C
*/
bool PlayCommonData::challenge_checkJustKunsho(int)
{
/*
stwu r1, -0x10(r1)
mflr r0
addi r3, r3, 0xc
stw r0, 0x14(r1)
bl getState__Q24Game21PlayChallengeGameDataFi
lhz r4, 0(r3)
rlwinm. r0, r4, 0, 0x1d, 0x1d
beq lbl_802349B8
rlwinm r0, r4, 0, 0x1a, 0x1a
ori r4, r4, 0x20
cntlzw r0, r0
sth r4, 0(r3)
srwi r3, r0, 5
b lbl_802349BC
lbl_802349B8:
li r3, 0
lbl_802349BC:
lwz r0, 0x14(r1)
mtlr r0
addi r1, r1, 0x10
blr
*/
}
/*
* Returns the index of the newly-opened course, or -1 if no course was opened.
* --INFO--
* Address: 802349CC
* Size: 000094
*/
int PlayCommonData::challenge_openNewCourse(void)
{
if (gGameConfig.m_parms.m_KFesVersion.m_data != 0) {
return -1;
}
for (int i = 0; i < m_challengeData.m_courseCount; i++) {
if (!challenge_checkOpen(i)) {
challenge_setOpen(i);
return i;
}
}
return -1;
}
/*
* --INFO--
* Address: 80234A60
* Size: 000030
*/
void PlayCommonData::challenge_setClear(int index)
{
m_challengeData.getState(index)->m_flags.typeView |= PlayChallengeGameData::CourseState::CSF_IsClear;
}
/*
* --INFO--
* Address: 80234A90
* Size: 000030
*/
void PlayCommonData::challenge_setOpen(int index)
{
m_challengeData.getState(index)->m_flags.typeView |= PlayChallengeGameData::CourseState::CSF_IsOpen;
}
/*
* --INFO--
* Address: 80234AC0
* Size: 000080
*/
void PlayCommonData::challenge_setKunsho(int)
{
/*
stwu r1, -0x10(r1)
mflr r0
stw r0, 0x14(r1)
stw r31, 0xc(r1)
stw r30, 8(r1)
mr r30, r3
addi r3, r30, 0xc
bl getState__Q24Game21PlayChallengeGameDataFi
lhz r0, 0(r3)
li r31, 0
ori r0, r0, 4
sth r0, 0(r3)
b lbl_80234B10
lbl_80234AF4:
mr r4, r31
addi r3, r30, 0xc
bl getState__Q24Game21PlayChallengeGameDataFi
lhz r0, 0(r3)
rlwinm. r0, r0, 0, 0x1d, 0x1d
beq lbl_80234B28
addi r31, r31, 1
lbl_80234B10:
lwz r0, 0xc(r30)
cmpw r31, r0
blt lbl_80234AF4
lbz r0, 0(r30)
ori r0, r0, 4
stb r0, 0(r30)
lbl_80234B28:
lwz r0, 0x14(r1)
lwz r31, 0xc(r1)
lwz r30, 8(r1)
mtlr r0
addi r1, r1, 0x10
blr
*/
}
/*
* --INFO--
* Address: 80234B40
* Size: 000084
*/
Highscore* PlayCommonData::challenge_getHighscore(int courseIndex, int scoreType)
{
PlayChallengeGameData::CourseState* state = m_challengeData.getState(courseIndex);
bool isValidScoreType = false;
if (0 <= scoreType && scoreType <= 1) {
isValidScoreType = true;
}
P2ASSERTLINE(401, isValidScoreType);
return &state->m_highscores[scoreType];
}
/*
* __ct__Q24Game21PlayChallengeGameDataFv
* --INFO--
* Address: 80234BC4
* Size: 0000C8
*/
PlayChallengeGameData::PlayChallengeGameData(void)
: m_flags(PlayChallengeGameData::PCGDF_Unset)
{
m_courseCount = CHALLENGE_COURSE_COUNT;
m_courses = new CourseState[m_courseCount];
m_courses[0].m_flags.typeView |= PlayChallengeGameData::CourseState::CSF_IsOpen;
m_courses[1].m_flags.typeView |= PlayChallengeGameData::CourseState::CSF_IsOpen;
m_courses[2].m_flags.typeView |= PlayChallengeGameData::CourseState::CSF_IsOpen;
m_courses[3].m_flags.typeView |= PlayChallengeGameData::CourseState::CSF_IsOpen;
m_courses[4].m_flags.typeView |= PlayChallengeGameData::CourseState::CSF_IsOpen;
m_flags = PlayChallengeGameData::PCGDF_Unset;
}
/*
* __ct__Q34Game21PlayChallengeGameData11CourseStateFv
* --INFO--
* Address: 80234C8C
* Size: 000078
*/
PlayChallengeGameData::CourseState::CourseState(void)
: m_flags()
, m_highscores()
{
m_highscores[0].allocate(3);
m_highscores[1].allocate(3);
m_flags.byteView[0] = 0;
m_flags.byteView[1] = 0;
}
/*
* --INFO--
* Address: 80234D04
* Size: 0000A4
*/
PlayChallengeGameData::CourseState* PlayChallengeGameData::getState(int index)
{
bool isValidIndex = false;
if (0 <= index && index < m_courseCount) {
isValidIndex = true;
}
P2ASSERTLINE(427, isValidIndex);
P2ASSERTLINE(428, m_courses != nullptr);
return &m_courses[index];
}
/*
* write__Q24Game21PlayChallengeGameDataFR6Stream
* --INFO--
* Address: 80234DA8
* Size: 00009C
*/
void PlayChallengeGameData::write(Stream& output)
{
output.writeByte(m_flags);
for (int i = 0; i < m_courseCount; i++) {
CourseState* state = &m_courses[i];
for (int j = 0; j < 2; j++) {
output.writeByte(state->m_flags.byteView[j]);
}
state->m_highscores[0].write(output);
state->m_highscores[1].write(output);
}
/*
stwu r1, -0x30(r1)
mflr r0
stw r0, 0x34(r1)
stmw r25, 0x14(r1)
mr r26, r4
mr r25, r3
lbz r4, 8(r3)
mr r3, r26
bl writeByte__6StreamFUc
li r27, 0
li r28, 0
b lbl_80234E24
lbl_80234DD8:
lwz r0, 4(r25)
li r29, 0
add r30, r0, r28
mr r31, r30
lbl_80234DE8:
lbz r4, 0(r31)
mr r3, r26
bl writeByte__6StreamFUc
addi r29, r29, 1
addi r31, r31, 1
cmplwi r29, 2
blt lbl_80234DE8
mr r4, r26
addi r3, r30, 4
bl write__Q24Game9HighscoreFR6Stream
mr r4, r26
addi r3, r30, 0x10
bl write__Q24Game9HighscoreFR6Stream
addi r28, r28, 0x1c
addi r27, r27, 1
lbl_80234E24:
lwz r0, 0(r25)
cmpw r27, r0
blt lbl_80234DD8
lmw r25, 0x14(r1)
lwz r0, 0x34(r1)
mtlr r0
addi r1, r1, 0x30
blr
*/
}
/*
* read__Q24Game21PlayChallengeGameDataFR6Stream
* --INFO--
* Address: 80234E44
* Size: 00009C
*/
void PlayChallengeGameData::read(Stream& input)
{
m_flags = input.readByte();
for (int i = 0; i < m_courseCount; i++) {
CourseState* state = &m_courses[i];
for (int j = 0; j < 2; j++) {
state->m_flags.byteView[j] = input.readByte();
}
state->m_highscores[0].read(input);
state->m_highscores[1].read(input);
}
/*
stwu r1, -0x30(r1)
mflr r0
stw r0, 0x34(r1)
stmw r25, 0x14(r1)
mr r26, r4
mr r25, r3
mr r3, r26
bl readByte__6StreamFv
stb r3, 8(r25)
li r27, 0
li r28, 0
b lbl_80234EC0
lbl_80234E74:
lwz r0, 4(r25)
li r29, 0
add r30, r0, r28
mr r31, r30
lbl_80234E84:
mr r3, r26
bl readByte__6StreamFv
addi r29, r29, 1
stb r3, 0(r31)
cmplwi r29, 2
addi r31, r31, 1
blt lbl_80234E84
mr r4, r26
addi r3, r30, 4
bl read__Q24Game9HighscoreFR6Stream
mr r4, r26
addi r3, r30, 0x10
bl read__Q24Game9HighscoreFR6Stream
addi r28, r28, 0x1c
addi r27, r27, 1
lbl_80234EC0:
lwz r0, 0(r25)
cmpw r27, r0
blt lbl_80234E74
lmw r25, 0x14(r1)
lwz r0, 0x34(r1)
mtlr r0
addi r1, r1, 0x30
blr
*/
}
/*
* --INFO--
* Address: 80234EE0
* Size: 000018
*/
bool Lowscore::do_higher(int a, int b) { return a < b; }
} // namespace Game
| 20.907801
| 132
| 0.620324
|
projectPiki
|
15aa7ac487e9cda6f829378ef7b72c56d91e761d
| 3,109
|
tpp
|
C++
|
LinkedListCpp/LinkedListCpp/LinkedList.tpp
|
epoll31/DataStructuresCpp
|
bfd93bad226bb5175d6b74f8dd9beb60150bb055
|
[
"MIT"
] | null | null | null |
LinkedListCpp/LinkedListCpp/LinkedList.tpp
|
epoll31/DataStructuresCpp
|
bfd93bad226bb5175d6b74f8dd9beb60150bb055
|
[
"MIT"
] | null | null | null |
LinkedListCpp/LinkedListCpp/LinkedList.tpp
|
epoll31/DataStructuresCpp
|
bfd93bad226bb5175d6b74f8dd9beb60150bb055
|
[
"MIT"
] | null | null | null |
#pragma once
template<typename T>
LinkedList<T>::LinkedList()
{
Count = 0;
Start = nullptr;
End = nullptr;
}
template<typename T>
LinkedList<T>::~LinkedList()
{
}
template<typename T>
void LinkedList<T>::AddFirst(T value)
{
if (Count == 0)
{
Start = std::make_unique<Node<T>>(value);
Start.get()->Next = nullptr;
Start.get()->Previous = nullptr;
End = Start.get();
Count++;
return;
}
std::unique_ptr<Node<T>> newNode = std::make_unique<Node<T>>(value);
newNode.get()->Next = std::move(Start);
newNode.get()->Previous = nullptr;
newNode.get()->Next.get()->Previous = newNode.get();
Start = std::move(newNode);
Count++;
}
template<typename T>
void LinkedList<T>::AddLast(T value)
{
if (Count == 0)
{
Start = std::make_unique<Node<T>>(value);
Start.get()->Next = nullptr;
Start.get()->Previous = nullptr;
End = Start.get();
Count++;
return;
}
End->Next = std::make_unique<Node<T>>(value);
End->Next.get()->Previous = End;
End = End->Next.get();
Count++;
}
template<typename T>
void LinkedList<T>::AddBefore(Node<T>* node, T value)
{
if (node == Start.get())
{
AddFirst(value);
return;
}
std::unique_ptr<Node<T>> newNode = std::make_unique<Node<T>>(value);
newNode.get()->Previous = node->Previous;
newNode.get()->Next = std::move(node->Previous->Next);
node->Previous->Next = std::move(newNode);
node->Previous = node->Previous->Next.get();
Count++;
}
template<typename T>
void LinkedList<T>::AddAfter(Node<T>* node, T value)
{
if (node == End)
{
AddLast(value);
return;
}
std::unique_ptr<Node<T>> newNode = std::make_unique<Node<T>>(value);
node->Next.get()->Previous = newNode.get();
newNode.get()->Next = std::move(node->Next);
newNode.get()->Previous = node;
node->Next = std::move(newNode);
Count++;
}
template<typename T>
void LinkedList<T>::Remove(T value)
{
Node<T>* currentNode = Start.get();
while (currentNode != nullptr)
{
if (currentNode->Value == value)
{
if (currentNode == Start.get())
{
RemoveFirst();
return;
}
else if (currentNode == End)
{
RemoveLast();
return;
}
else
{
currentNode->Next.get()->Previous = currentNode->Previous;
currentNode->Previous->Next = std::move(currentNode->Next);
Count--;
return;
}
}
currentNode = currentNode->Next.get();
}
}
template<typename T>
void LinkedList<T>::RemoveFirst()
{
Start = std::move(Start.get()->Next);
Start.get()->Previous = nullptr;
Count--;
}
template<typename T>
void LinkedList<T>::RemoveLast()
{
End = End->Previous;
End->Next = nullptr;
Count--;
}
template<typename T>
Node<T>* LinkedList<T>::Find(T value)
{
Node<T>* currentNode = Start.get();
while (currentNode != nullptr)
{
if (currentNode->Value == value)
{
return currentNode;
}
currentNode = currentNode->Next.get();
}
return nullptr;
}
template <typename T>
bool LinkedList<T>::Contains(T value)
{
Node<T>* currentNode = Start.get();
while (currentNode != nullptr)
{
if (currentNode->Value == value)
{
return true;
}
currentNode = currentNode->Next.get();
}
return false;
}
| 17.466292
| 69
| 0.635252
|
epoll31
|
15afa11f48fb30c9c11224d2e3655f0af3787229
| 939
|
cpp
|
C++
|
naklibsrc/src/core/BSVAddress/BSVAddress.cpp
|
murphyj8/testNakStructure
|
fbd9fc0784b6b7ee3b176cb28d2b6e26abd2b48a
|
[
"Unlicense"
] | 1
|
2021-07-01T02:01:27.000Z
|
2021-07-01T02:01:27.000Z
|
naklibsrc/src/core/BSVAddress/BSVAddress.cpp
|
murphyj8/testNakStructure
|
fbd9fc0784b6b7ee3b176cb28d2b6e26abd2b48a
|
[
"Unlicense"
] | 1
|
2020-09-23T12:34:34.000Z
|
2020-09-23T12:34:34.000Z
|
naklibsrc/src/core/BSVAddress/BSVAddress.cpp
|
murphyj8/testNakStructure
|
fbd9fc0784b6b7ee3b176cb28d2b6e26abd2b48a
|
[
"Unlicense"
] | null | null | null |
#include <BSVAddress/BSVAddress.h>
#include <BSVAddress/BSVAddressImpl.h>
BSVAddress::BSVAddress( const std::string& address )
: m_pImpl( new BSVAddressImpl( address ) )
{
}
BSVAddress::BSVAddress( const std::string& publicKey, VersionPrefix version )
: m_pImpl( new BSVAddressImpl( publicKey, version) )
{
}
BSVAddress::~BSVAddress( )
{
}
bool BSVAddress::valid( ) const
{
return m_pImpl->valid( ) ;
}
VersionPrefix BSVAddress::getVersionPrefix( ) const
{
return m_pImpl->getVersionPrefix( ) ;
}
std::string BSVAddress::getAddress( ) const
{
return m_pImpl->getAddress( ) ;
}
std::pair< std::string, std::string > BSVAddress::getVersion( ) const
{
return m_pImpl->getVersion( ) ;
}
std::string BSVAddress::decode( ) const
{
return m_pImpl->decode( ) ;
}
std::ostream& operator<< ( std::ostream& out, const BSVAddress& address )
{
out << *address.m_pImpl.get() ;
return out ;
}
| 18.78
| 79
| 0.671991
|
murphyj8
|
15b1121d57ea5e4d67a2cfe4b75887b4c4ed929c
| 12,988
|
cpp
|
C++
|
DeltaServer.cpp
|
alirazeen/kahawai
|
927df9290546e23bdf6c154a0e4ed611bf5e91a6
|
[
"MIT"
] | 2
|
2018-07-09T17:15:23.000Z
|
2019-12-09T13:00:53.000Z
|
DeltaServer.cpp
|
alirazeen/kahawai
|
927df9290546e23bdf6c154a0e4ed611bf5e91a6
|
[
"MIT"
] | null | null | null |
DeltaServer.cpp
|
alirazeen/kahawai
|
927df9290546e23bdf6c154a0e4ed611bf5e91a6
|
[
"MIT"
] | null | null | null |
#include "kahawaiBase.h"
#ifdef KAHAWAI
#include "DeltaServer.h"
//Supported encoders
#include "X264Encoder.h"
bool DeltaServer::isClient() {
return false;
}
bool DeltaServer::isMaster() {
return theMaster;
}
bool DeltaServer::isSlave() {
return theSlave;
}
//////////////////////////////////////////////////////////////////////////
// Basic Delta encoding transformation
//////////////////////////////////////////////////////////////////////////
byte Delta(byte hi, byte lo)
{
int resultPixel = ((hi - lo) / 2) + 127;
if (resultPixel > 255)
resultPixel = 255;
if (resultPixel < 0)
resultPixel = 0;
return (byte)resultPixel;
}
/////////////////////////////////////////////////////////////////////////
// Lifecycle methods
//////////////////////////////////////////////////////////////////////////
bool DeltaServer::Initialize()
{
//Call superclass
if(!KahawaiServer::Initialize())
return false;
//Read client's resolution. (Can be lower than the server's. Interpolation occurs to match deltas)
_clientWidth = _configReader->ReadIntegerValue(CONFIG_DELTA,CONFIG_WIDTH);
_clientHeight = _configReader->ReadIntegerValue(CONFIG_DELTA,CONFIG_HEIGHT);
//Initialize Memory FileMapping. Decide roles while at it
if(!InitMapping())
{
KahawaiLog("Unable to create memory file map", KahawaiError);
return false;
}
//Initialize encoder
_encoder = new X264Encoder(_height,_width,_fps,_crf,_preset);
//Initialize input handler
#ifndef NO_HANDLE_INPUT
_inputHandler = new InputHandlerServer(_serverPort+PORT_OFFSET_INPUT_HANDLER, _gameName);
#endif
char* measurement_file_name;
if (_master)
{
theMaster = true;
theSlave = false;
measurement_file_name = "delta_server_master.csv";
} else
{
theMaster = false;
theSlave = true;
//Re-Initialize sws scaling context if slave
delete[] _sourceFrame;
_convertCtx = sws_getContext(_clientWidth,_clientHeight,PIX_FMT_BGRA, _width, _height,PIX_FMT_YUV420P, SWS_FAST_BILINEAR,NULL,NULL,NULL);
_sourceFrame = new uint8_t[_clientWidth*_clientWidth*SOURCE_BITS_PER_PIXEL];
measurement_file_name = "delta_server_slave.csv";
}
#ifndef MEASUREMENT_OFF
_measurement = new Measurement(measurement_file_name);
KahawaiServer::SetMeasurement(_measurement);
_inputHandler->SetMeasurement(_measurement);
_encoder->SetMeasurement(_measurement);
#endif
InitializeCriticalSection(&_inputSocketCS);
InitializeConditionVariable(&_inputSocketCV);
return true;
}
bool DeltaServer::Finalize()
{
KahawaiServer::Finalize();
//Unlock waiting threads
if(_master)
SetEvent(_slaveBarrier);
else
SetEvent(_masterBarrier);
return true;
}
bool DeltaServer::StartOffload()
{
bool result = KahawaiServer::StartOffload();
#ifndef NO_HANDLE_INPUT
//Make sure the input handler is connected first before we allow
//the delta master and slave to continue. The synchronization logic
//here is complicated because:
//
// 1) There is a delta master and there is a delta slave
// 2) Only the master connects to the client input handler
// 3) The slave has to wait for the master to finish connecting
// 4) The slave and the master are _separate_ class instances
// 5) As a consequence of 4), there are twp independent critical sections with the
// same name, _inputSocketCS, and also independent condition variables
// 6) The one thing that both the master and the slave share is the _masterInputEvent HANDLE
if (_master && result && !_inputConnectionDone)
{
EnterCriticalSection(&_inputSocketCS);
{
while(!_inputConnectionDone)
SleepConditionVariableCS(&_inputSocketCV, &_inputSocketCS, INFINITE);
}
SetEvent(_masterInputEvent);
LeaveCriticalSection(&_inputSocketCS);
result = _inputHandler->IsConnected();
} else if (!_master && result)
{
EnterCriticalSection(&_inputSocketCS);
{
while(!_masterInputReady)
SleepConditionVariableCS(&_inputSocketCV, &_inputSocketCS, INFINITE);
}
LeaveCriticalSection(&_inputSocketCS);
}
#endif
return result;
}
/**
* Executes the server side of the pipeline
* Defines initialization steps before first frame is offloaded
* Transform->Encode->Send
*/
void DeltaServer::OffloadAsync()
{
//First perform final initialization step
//Create socket and input connection to client (if master)
if(_master)
{
bool connected = ConnectToClientDecoder();
if (!connected)
{
KahawaiLog("Unable to connect client decoder\n", KahawaiError);
return;
}
#ifndef NO_HANDLE_INPUT
EnterCriticalSection(&_inputSocketCS);
{
_inputHandler->Connect();
_inputConnectionDone = true;
}
WakeConditionVariable(&_inputSocketCV);
LeaveCriticalSection(&_inputSocketCS);
if(!_inputHandler->IsConnected())
{
KahawaiLog("Unable to start input handler", KahawaiError);
_offloading = false;
return;
}
#endif
} else
{
#ifndef NO_HANDLE_INPUT
EnterCriticalSection(&_inputSocketCS);
{
WaitForSingleObject(_masterInputEvent, INFINITE);
_masterInputReady = true;
}
WakeConditionVariable(&_inputSocketCV);
LeaveCriticalSection(&_inputSocketCS);
#endif
}
KahawaiServer::OffloadAsync();
}
bool DeltaServer::Capture(int width, int height, void* args)
{
#ifndef MEASUREMENT_OFF
_measurement->AddPhase(Phase::CAPTURE_BEGIN, _gameFrameNum);
#endif
bool result = KahawaiServer::Capture(width, height, args);
#ifndef MEASUREMENT_OFF
_measurement->AddPhase(Phase::CAPTURE_END, _gameFrameNum);
#endif
return result;
}
/**
* Overrides Kahawai::Transform because it needs to synchronize
* the master and slave processes first.
* @param width the target width
* @param height the target height
* @see Kahawai::Transform
* @return true if the transformation was successful
*/
bool DeltaServer::Transform(int width, int height, int frameNum)
{
#ifndef MEASUREMENT_OFF
_measurement->AddPhase(Phase::TRANSFORM_BEGIN, frameNum);
#endif
bool result = KahawaiServer::Transform(_width, _height, _kahawaiFrameNum);
#ifndef MEASUREMENT_OFF
_measurement->AddPhase(Phase::TRANSFORM_END, frameNum);
#endif
return result;
}
/**
* The master combines the low definition from the slave with its own
* and encodes it
* The slaves writes its low definition version to shared memory
* @param transformedFrame a pointer to the transformedFrame
* @see KahawaiServer::Encode
* @return
*/
int DeltaServer::Encode(void** transformedFrame)
{
#ifndef MEASUREMENT_OFF
_measurement->AddPhase(Phase::ENCODE_BEGIN, _kahawaiFrameNum);
#endif
int result = 0;
if(_master)
{
LogYUVFrame(_renderedFrames,"source",_renderedFrames,(char*)_transformPicture->img.plane[0],_width,_height);
//Wait for the slave copy to finish writing the low quality version to shared memory
WaitForSingleObject(_masterBarrier, INFINITE);
#ifndef MEASUREMENT_OFF
_measurement->AddPhase("ENCODE_MASTER_AFTER_WAIT", _kahawaiFrameNum);
#endif
result = _encoder->Encode(_transformPicture,transformedFrame,Delta, _mappedBuffer);
SetEvent(_slaveBarrier);
#ifndef MEASUREMENT_OFF
_measurement->AddPhase("ENCODE_MASTER_SET_EVENT", _kahawaiFrameNum);
#endif
}
else
{
*transformedFrame = _transformPicture->img.plane[0];
result = YUV420pBitsPerPixel(_width,_height);
}
#ifndef MEASUREMENT_OFF
_measurement->AddPhase(Phase::ENCODE_END, _kahawaiFrameNum);
#endif
return result;
}
/**
* Sends the encoded frame to the client
* @param compressed frame, a pointer to the compressedFrame array
* @param frameSize the size of the array
* @see KahawaiServer::Send
* @return true if the operation succeeded, false otherwise
*/
bool DeltaServer::Send(void** compressedFrame, int frameSize)
{
#ifndef MEASUREMENT_OFF
_measurement->AddPhase(Phase::SEND_BEGIN, _kahawaiFrameNum);
#endif
if(_master)
{
//Send the encoded delta to the client
if(send(_socketToClient,(char*) *compressedFrame,frameSize,0)==SOCKET_ERROR)
{
KahawaiLog("Unable to send frame to client", KahawaiError);
return false;
}
LogVideoFrame(_saveCaptures,"transferred","deltaMovie.h264",(char*)*compressedFrame,frameSize);
}
else //Slave
{
//Copy the low fidelity capture to shared memory
memcpy(_mappedBuffer,(char*) *compressedFrame,frameSize);
#ifndef MEASUREMENT_OFF
_measurement->AddPhase("SEND_SLAVE_BEFORE_WAIT", _kahawaiFrameNum);
#endif
SetEvent(_masterBarrier);
WaitForSingleObject(_slaveBarrier, INFINITE);
}
#ifndef MEASUREMENT_OFF
_measurement->AddPhase(Phase::SEND_END, _kahawaiFrameNum);
#endif
return true;
}
//////////////////////////////////////////////////////////////////////////
// Support methods
//////////////////////////////////////////////////////////////////////////
/**
* Inits File Mapping between the Delta Hi and the Delta Lo processes
* @param the size of the mapping
* @return
*/
bool DeltaServer::InitMapping()
{
int inputOffset = YUV420pBitsPerPixel(_clientWidth , _clientHeight);
int size = inputOffset + KAHAWAI_INPUT_COMMAND_BUFFER;
HANDLE sharedFile = NULL;
//Create File to be used for file sharing, use temporary flag for efficiency
sharedFile = CreateFile
(KAHAWAI_MAP_FILE,
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_WRITE,
NULL,
CREATE_ALWAYS,
FILE_ATTRIBUTE_TEMPORARY,
NULL);
if(!sharedFile)
return false;
//Init File Mapping Handle
_map = CreateFileMapping
(sharedFile,
NULL,
PAGE_READWRITE,
0,
size,
_T("SharedFile"));
if(!_map)
return false;
//Define a Mutex for accessing the file map.
_mutex = CreateMutex(
NULL,
FALSE,
_T("FILE MUTEX"));
if(!_mutex)
return false;
_slaveBarrier = CreateEvent(
NULL,
FALSE,
FALSE,
"KahawaiiSlave");
_masterBarrier = CreateEvent(
NULL,
FALSE,
FALSE,
"KahawaiiMaster");
//Define events for accessing the input section of the file map
_slaveInputEvent = CreateEvent(
NULL,
FALSE,
FALSE,
"KahawaiSlaveInput");
_masterInputEvent = CreateEvent(
NULL,
FALSE,
FALSE,
"KahawaiMasterInput");
WaitForSingleObject(_mutex,INFINITE);
char* b = (char*) MapViewOfFile(_map,
FILE_MAP_ALL_ACCESS,
0,
0,
size);
if(strcmp(kahawaiMaster,b)!=0)
{
memset(b,0,size);
strcpy(b,kahawaiMaster);
_master = true;
}
else
{
_master = false;
}
UnmapViewOfFile(b);
ReleaseMutex(_mutex);
DWORD access = FILE_MAP_ALL_ACCESS;
_mappedBuffer = (byte*) MapViewOfFile(_map,
access,
0,
0,
size);
_sharedInputBuffer = _mappedBuffer + inputOffset;
return true;
}
/**
* Returns whether this instance should use high or low quality settings
* @return the quality of the settings to be used
*/
bool DeltaServer::IsHD()
{
//Only master renders in HD
return _master;
}
//////////////////////////////////////////////////////////////////////////
// Input Handling
//////////////////////////////////////////////////////////////////////////
/**
* Receives input from the client and applies it to the server state
* @param Server input is ALWAYS discarded
* @return the command received from the client for the current frame
*/
void* DeltaServer::HandleInput()
{
if(!ShouldHandleInput())
return _inputHandler->GetEmptyCommand();
if(_master)
{
int length = _inputHandler->GetCommandLength();
char* cmd = (char*) _inputHandler->ReceiveCommand();
//Send the input to the slave copy
//TODO: The barrier may not be enough synchronization
//Check this if synchronization issues arise.
//Performance may be hurt if a stronger method is used
memcpy(_sharedInputBuffer,cmd,length);
SetEvent(_masterInputEvent);
WaitForSingleObject(_slaveInputEvent, INFINITE);
#ifndef MEASUREMENT_OFF
_measurement->InputProcessed(_numInputProcessed, _gameFrameNum);
#endif
_numInputProcessed++;
return cmd;
}
else
{
void* result = NULL;
WaitForSingleObject(_masterInputEvent, INFINITE);
result = _sharedInputBuffer;
SetEvent(_slaveInputEvent);
return result;
}
}
int DeltaServer::GetFirstInputFrame()
{
//TODO: Need to give a real value based on profiling
return FRAME_GAP;
}
bool DeltaServer::ConnectToClientDecoder()
{
//TODO: POSSIBLE MEMLEAK BECAUSE WE ARE NOT DELETING encodedFrame??
void *encodedFrame = NULL;
int frameSize = _encoder->GetBlackFrame(_convertCtx, &encodedFrame);
_socketToClient = CreateSocketToClient(_serverPort);
if (_socketToClient==INVALID_SOCKET)
{
KahawaiLog("Unable to create connection to client in DeltaServer::OffloadAsync()", KahawaiError);
return false;
}
if(send(_socketToClient,(char*) encodedFrame, frameSize, 0)==SOCKET_ERROR)
{
KahawaiLog("Unable to send frame to client", KahawaiError);
return false;
}
return true;
}
//////////////////////////////////////////////////////////////////////////
// Constructor / Destructor
//////////////////////////////////////////////////////////////////////////
DeltaServer::DeltaServer(void)
:KahawaiServer(),
_slaveBarrier(NULL),
_masterBarrier(NULL),
_mappedBuffer(NULL),
_master(false),
_mutex(NULL),
_map(NULL),
_inputConnectionDone(false),
_masterInputReady(false),
_numInputProcessed(0)
{
}
DeltaServer::~DeltaServer(void)
{
}
#endif
| 23.151515
| 139
| 0.705805
|
alirazeen
|
15b9608cfc33057a48323c90a411f3778e604673
| 15,872
|
cpp
|
C++
|
motor-controller-nucleo/Interfaces/Hardware/TMC4671Interface.cpp
|
HEEV/motor-controller-2018-sw
|
7bc22e4c7ba330d9130cda98a54a56066df2200b
|
[
"MIT"
] | 3
|
2018-12-29T13:33:32.000Z
|
2019-09-14T15:45:26.000Z
|
motor-controller-nucleo/Interfaces/Hardware/TMC4671Interface.cpp
|
HEEV/motor-controller-2018-sw
|
7bc22e4c7ba330d9130cda98a54a56066df2200b
|
[
"MIT"
] | null | null | null |
motor-controller-nucleo/Interfaces/Hardware/TMC4671Interface.cpp
|
HEEV/motor-controller-2018-sw
|
7bc22e4c7ba330d9130cda98a54a56066df2200b
|
[
"MIT"
] | 1
|
2019-06-06T03:28:05.000Z
|
2019-06-06T03:28:05.000Z
|
#include "TMC4671Interface.h"
#include <ic/TMC4671/TMC4671.h>
#include "settings_structs.h"
// used for pin the SPI functions for pin useage
#include "main.h"
using uint8_t = std::uint8_t;
using int32_t = std::int32_t;
using uint32_t = std::uint32_t;
// Use the global variable defined in main.cpp so we can implement the trinamic readwriteByte function
extern SPI_HandleTypeDef *TMC4671_SPI;
// define some helper functions (implemented after the class function implementations)
// define SPI functions for the trinamic API (implementation near the bottom of file)
extern "C" {
u8 tmc4671_readwriteByte(u8 motor, u8 data, u8 lastTransfer);
}
// detailed documentation in the .h file
TMC4671Interface::TMC4671Interface(TMC4671Settings_t *settings)
{
// get the TMC4671 into a known state
// setup the default register values and write them to the tmc4671
for(uint8_t i = 0; i < 0x7D; ++i)
{
tmc4671_writeInt(TMC_DEFAULT_MOTOR, i, tmc4671Registers[i]);
}
// initilize important TMC4671 registers
pwm_init();
adc_init();
// intilize variables
Settings = settings;
ControlMode = ControlMode_t::VELOCITY;
Direction = MotorDirection_t::FORWARD;
Setpoint = 0;
MotorConstant = 0;
// initilize the user defined settings
change_settings(settings);
}
// detailed information in the .h file
void TMC4671Interface::change_settings(const TMC4671Settings_t *settings)
{
// initilize hall effect sensors
hall_effect_init(*settings);
const uint8_t motor_type = static_cast<uint8_t>(settings->MotorType);
// Use the Pole-pairs as the motor constant if this is a BLDC motor. This might be stupid.
// If this is a brushed motor, then this will be the KV constant (RPM/voltage) of the motor
MotorConstant = settings->PolePairs_KV;
// if using a brushed motor, there is always only one pole. ALWAYS!!!
const uint8_t pole_pairs =
(settings->MotorType == MotorType_t::BRUSHED_MOTOR) ? 1 : MotorConstant;
// now update the motor type and pole pairs
tmc4671_writeInt(TMC_DEFAULT_MOTOR, TMC4671_MOTOR_TYPE_N_POLE_PAIRS, (motor_type << 16) | (pole_pairs) );
//update the limits (current, velocity, and acceleration)
tmc4671_writeRegister16BitValue(TMC_DEFAULT_MOTOR, TMC4671_PID_TORQUE_FLUX_LIMITS, BIT_0_TO_15, settings->CurrentLimit/CURRENT_DIVISOR);
// multiply the velocity and acceleration limits times the motor constant to get accurate velocity and acceleration limits
tmc4671_writeInt(TMC_DEFAULT_MOTOR, TMC4671_PID_VELOCITY_LIMIT, MotorConstant*settings->VelocityLimit);
tmc4671_writeInt(TMC_DEFAULT_MOTOR, TMC4671_PID_ACCELERATION_LIMIT, MotorConstant*settings->AccelerationLimit);
// change the PID values
uint32_t pi_value = (settings->FluxP << TMC4671_PID_FLUX_P_SHIFT) | settings->FluxI;
tmc4671_writeInt(TMC_DEFAULT_MOTOR, TMC4671_PID_FLUX_P_FLUX_I, pi_value);
pi_value = (settings->TorqueP << TMC4671_PID_TORQUE_P_SHIFT) | settings->TorqueI;
tmc4671_writeInt(TMC_DEFAULT_MOTOR, TMC4671_PID_TORQUE_P_TORQUE_I, pi_value);
pi_value = (settings->VelocityP << TMC4671_PID_VELOCITY_P_SHIFT) | settings->VelocityI;
tmc4671_writeInt(TMC_DEFAULT_MOTOR, TMC4671_PID_VELOCITY_P_VELOCITY_I, pi_value);
// now initilize the settings that will be changed the most frequently
set_control_mode(settings->ControlMode);
set_direction(settings->MotorDir);
set_setpoint(Setpoint);
}
// documented in the .h file
void TMC4671Interface::set_control_mode(ControlMode_t mode)
{
uint8_t tmc_mode = TMC4671_MOTION_MODE_VELOCITY;
switch (mode) {
case ControlMode_t::VELOCITY :
// this statement is redundant
tmc_mode = TMC4671_MOTION_MODE_VELOCITY;
break;
case ControlMode_t::TORQUE :
tmc_mode = TMC4671_MOTION_MODE_TORQUE;
break;
case ControlMode_t::OPEN_LOOP :
tmc_mode = TMC4671_MOTION_MODE_UQ_UD_EXT;
break;
default:
break;
}
// set the class state
ControlMode = mode;
// configure the TMC4671
tmc4671_switchToMotionMode(TMC_DEFAULT_MOTOR, tmc_mode);
}
// documented in the .h file
void TMC4671Interface::set_direction(MotorDirection_t dir)
{
Direction = dir;
Settings->MotorDir = dir;
// Start the motor going in the new direction
set_setpoint(Setpoint);
}
// documented int the .h file
void TMC4671Interface::set_setpoint(uint32_t set_point)
{
// take the absolute value of the set point (direction determined by the Direction variable)
// update settings struct
Settings->Setpoint = Setpoint;
switch (ControlMode) {
case ControlMode_t::VELOCITY :
{
set_point = (set_point > INT32_MAX) ? INT32_MAX : set_point;
Setpoint = (Direction == MotorDirection_t::REVERSE) ? -set_point : set_point;
// Note: this could be very dumb (or it could be briliant)
int32_t tmc_setpoint = MotorConstant * Setpoint;
tmc4671_writeInt(TMC_DEFAULT_MOTOR, TMC4671_PID_VELOCITY_TARGET, tmc_setpoint);
break;
}
case ControlMode_t::TORQUE :
{
// make sure we don't overflow
set_point = (set_point >= (INT16_MAX-1)*CURRENT_DIVISOR) ? (INT16_MAX-1)*CURRENT_DIVISOR : set_point;
Setpoint = (Direction == MotorDirection_t::REVERSE) ? -set_point : set_point;
// divide by 2 to get into 2mA incriments
int16_t tmc_setpoint = Setpoint / CURRENT_DIVISOR;
tmc4671_writeRegister16BitValue(TMC_DEFAULT_MOTOR, TMC4671_PID_TORQUE_FLUX_TARGET, BIT_16_TO_31, tmc_setpoint);
break;
}
case ControlMode_t::OPEN_LOOP :
break;
default:
break;
}
}
// documented in the .h file
void TMC4671Interface::enable()
{
HAL_GPIO_WritePin(TMC4671_EN_GPIO_Port, TMC4671_EN_Pin, GPIO_PIN_SET);
}
// documented in the .h file
void TMC4671Interface::disable(){
HAL_GPIO_WritePin(TMC4671_EN_GPIO_Port, TMC4671_EN_Pin, GPIO_PIN_RESET);
}
float TMC4671Interface::get_motor_current()
{
// get the raw current values (2mA incriments)
int32 raw_current = tmc4671_getActualTorque_raw(TMC_DEFAULT_MOTOR);
// rescale to get the current into mA
return static_cast<float>(raw_current) * CURRENT_DIVISOR;
}
// Deal with the error in the 4671 datasheet
// (0-2v input instead of a 0-5v input)
float TMC4671Interface::get_battery_current()
{
// select which adc register to read
const int AGPI_1_VM = 1;
//setup to read the ADC value
tmc4671_writeInt(TMC_DEFAULT_MOTOR, TMC4671_ADC_RAW_ADDR, AGPI_1_VM);
uint16_t value = tmc4671_readRegister16BitValue(TMC_DEFAULT_MOTOR, TMC4671_ADC_RAW_DATA, BIT_16_TO_31);
//return static_cast<float>(value) * static_cast<float>(BATTERY_CURRENT_SCALE) - BATTERY_CURRENT_OFFSET;
auto current_ma = static_cast<float>(value - BATTERY_CURRENT_OFFSET) * BATTERY_CURRENT_SCALE;
return current_ma/1000.0;
}
// Deal with the error in the 4671 datasheet
// (0-2v input instead of a 0-5v input)
float TMC4671Interface::get_battery_voltage()
{
// select which adc register to read
const int AGPI_1_VM = 1;
//setup to read the ADC value
tmc4671_writeInt(TMC_DEFAULT_MOTOR, TMC4671_ADC_RAW_ADDR, AGPI_1_VM);
uint16_t value = tmc4671_readRegister16BitValue(TMC_DEFAULT_MOTOR, TMC4671_ADC_RAW_DATA, BIT_0_TO_15);
const float fudge = -2.88;
return ((value - BATTERY_ADC_MIN) * BATTERY_MAX)/ static_cast<float>(BATTERY_ADC_MAX - BATTERY_ADC_MIN) + fudge;
}
int32_t TMC4671Interface::get_motor_RPM()
{
return tmc4671_getActualVelocity(TMC_DEFAULT_MOTOR)/MotorConstant;
}
// -------------------------------- Helper functions -------------------------
/** Initilize hall TMC4671 hall effect registers
* This is a helper function to initilize the hall effect sensors. The function
* takes the motor controller settings as an input, because the electrical and
* mechanical offsets are dependent on the motor used, and therefore need to
* be easily modifiable by the end user.
*/
void TMC4671Interface::hall_effect_init(const TMC4671Settings_t &motor_settings)
{
// stuff to setup hall effect sensors here (default config good for now)
const uint32_t HALL_POSITION[] = {0x55557FFF, 0x00012AAB, 0xAAADD557};
const uint32_t MAX_INTERPOLATION = 0x00002AAA;
uint32_t HALL_OFFSET = (motor_settings.HallElecOffset << 16) | motor_settings.HallMechOffset;
uint32_t HALL_MODE = (motor_settings.HallMode.HallDirection << 12)
| (motor_settings.HallMode.HallInterpolate << 8)
| (motor_settings.HallMode.HallPolarity);
// turn on interpolation, and reverse polarity
tmc4671_writeInt(TMC_DEFAULT_MOTOR, TMC4671_HALL_MODE, HALL_MODE);
// define the "position" of the rotor with each hall effect pulse
tmc4671_writeInt(TMC_DEFAULT_MOTOR, TMC4671_HALL_POSITION_060_000, HALL_POSITION[0]);
tmc4671_writeInt(TMC_DEFAULT_MOTOR, TMC4671_HALL_POSITION_180_120, HALL_POSITION[1]);
tmc4671_writeInt(TMC_DEFAULT_MOTOR, TMC4671_HALL_POSITION_300_240, HALL_POSITION[2]);
// define the electrical offset between the hall effect senors and the motor
tmc4671_writeInt(TMC_DEFAULT_MOTOR, TMC4671_HALL_PHI_E_PHI_M_OFFSET, HALL_OFFSET);
// define the maximum ammount to interpolate
tmc4671_writeInt(TMC_DEFAULT_MOTOR, TMC4671_HALL_DPHI_MAX, MAX_INTERPOLATION);
}
void TMC4671Interface::adc_init()
{
const uint8_t ADC_I0_SELECT = 0;
const uint8_t ADC_I1_SELECT = 1;
const uint8_t ADC_I_UX_SELECT = 0;
const uint8_t ADC_I_V_SELECT = 1;
const uint8_t ADC_I_WY_SELECT = 2;
// constants for Trinamic's power board
// const uint8_t ADC_I0_SELECT = 0;
// const uint8_t ADC_I1_SELECT = 1;
// const uint8_t ADC_I_UX_SELECT = 0;
// const uint8_t ADC_I_V_SELECT = 2;
// const uint8_t ADC_I_WY_SELECT = 1;
// setup which registers the ADC reads for each phase current
const uint32_t adc_selection =
(ADC_I0_SELECT << TMC4671_ADC_I0_SELECT_SHIFT) |
(ADC_I1_SELECT << TMC4671_ADC_I1_SELECT_SHIFT) |
(ADC_I_UX_SELECT << TMC4671_ADC_I_UX_SELECT_SHIFT) |
(ADC_I_V_SELECT << TMC4671_ADC_I_V_SELECT_SHIFT) |
(ADC_I_WY_SELECT << TMC4671_ADC_I_WY_SELECT_SHIFT);
tmc4671_writeInt(TMC_DEFAULT_MOTOR, TMC4671_ADC_I_SELECT, adc_selection);
//setup the ADC scaling and offset
tmc4671_writeRegister16BitValue(TMC_DEFAULT_MOTOR, TMC4671_ADC_I0_SCALE_OFFSET, BIT_0_TO_15, ADC_PHASE1_OFFSET);
tmc4671_writeRegister16BitValue(TMC_DEFAULT_MOTOR, TMC4671_ADC_I0_SCALE_OFFSET, BIT_16_TO_31, ADC_PHASE1_SCALE);
tmc4671_writeRegister16BitValue(TMC_DEFAULT_MOTOR, TMC4671_ADC_I1_SCALE_OFFSET, BIT_0_TO_15, ADC_PHASE2_OFFSET);
tmc4671_writeRegister16BitValue(TMC_DEFAULT_MOTOR, TMC4671_ADC_I1_SCALE_OFFSET, BIT_16_TO_31, ADC_PHASE2_SCALE);
}
void TMC4671Interface::pwm_init()
{
//set the PWM polarities to be 1-on, 0-off
uint8_t PWM_POLARITIES = 0;
// set pwm frequency to be 50khz
// pwm frequency (hz) = 100 (Mhz) / (PWM_MAXCNT + 1)
// (p72 in the TMC4671 datasheet)
uint16_t PWM_MAXCNT = 1999;
// 30 * 10 ns break before make time
// (p72 in the TMC4671 datasheet)
uint8_t BBM_TIME = 30;
// put the pwm into centered pwm for FOC
// (p73 on the TMC4671 datasheet)
uint8_t PWM_CHOP_MODE = 7;
// temperarory variable for writting to 32bit registers
uint32_t temp_reg = 0;
// set the PWM polarities register
temp_reg = PWM_POLARITIES;
tmc4671_writeInt(TMC_DEFAULT_MOTOR, TMC4671_PWM_POLARITIES, temp_reg);
// set the PWM max count register
temp_reg = PWM_MAXCNT;
tmc4671_writeInt(TMC_DEFAULT_MOTOR, TMC4671_PWM_MAXCNT, temp_reg);
// set the PWM break before make times
temp_reg = (BBM_TIME << 8) | (BBM_TIME);
tmc4671_writeInt(TMC_DEFAULT_MOTOR, TMC4671_PWM_BBM_H_BBM_L, temp_reg);
//set the PWM chopping mode
temp_reg = PWM_CHOP_MODE;
tmc4671_writeInt(TMC_DEFAULT_MOTOR, TMC4671_PWM_SV_CHOP, temp_reg);
}
// --------------------- Trinamic Library Helper function -------------------------
u8 tmc4671_readwriteByte(u8 motor, u8 data, u8 lastTransfer)
{
UNUSED(motor);
const uint32_t SPI_TIMEOUT = 50; // spi timeout in ms
uint8_t data_rx;
//clear the SS pin
HAL_GPIO_WritePin(TMC4671_SS_GPIO_Port, TMC4671_SS_Pin, GPIO_PIN_RESET);
HAL_SPI_TransmitReceive(TMC4671_SPI, &data, &data_rx, 1, SPI_TIMEOUT);
//if the last transfer set the SS pin
if(lastTransfer){
HAL_GPIO_WritePin(TMC4671_SS_GPIO_Port, TMC4671_SS_Pin, GPIO_PIN_SET);
}
return data_rx;
}
// -------------------------Register initilization values -----------------------
// register values for startup
const uint32_t TMC4671Interface::tmc4671Registers [] =
{
0x00000000, //0x00: (read only)
0x00000000, //0x01:
0x00000000, //0x02: (read only)
0x00000000, //0x03:
0x00100010, //0x04:
0x20000000, //0x05:
0x00000000, //0x06:
0x014E014E, //0x07:
0x01008001, //0x08:
0x01008001, //0x09:
0x18000100, //0x0A:
0x00000000, //0x0B:
0x00044400, //0x0C:
0x01000000, //0x0D:
0x01000000, //0x0E:
0x01000000, //0x0F:
0x00000000, //0x10: (reserved)
0x03020100, //0x11:
0x00000000, //0x12: (read only)
0x00000000, //0x13: (read only)
0x00000000, //0x14: (read only)
0x00000000, //0x15: (read only)
0x00000000, //0x16: (read only)
0x00000000, //0x17:
0x00000F9F, //0x18:
0x00000505, //0x19:
0x00000007, //0x1A:
0x0003000E, //0x1B:
0x00000000, //0x1C:
0x00000000, //0x1D:
0x00000000, //0x1E:
0x00000000, //0x1F:
0x0000003C, //0x20:
0xFFFFFFF6, //0x21:
0xFFFFFFFB, //0x22:
0x00008BAD, //0x23:
0x00000678, //0x24:
0x00000000, //0x25:
0x00010000, //0x26:
0x002641C9, //0x27:
0x002641C9, //0x28:
0x00000000, //0x29:
0x00000000, //0x2A: (read only)
0x00000000, //0x2B: (reserved)
0x00000000, //0x2C:
0x00010000, //0x2D:
0x0025DAC7, //0x2E:
0x0025DAC7, //0x2F:
0x00000000, //0x30:
0x00000000, //0x31: (read only)
0x00000000, //0x32: (reserved)
0x00001101, //0x33:
0x2AAA0000, //0x34:
0x80005555, //0x35:
0xD555AAAA, //0x36:
0x04000000, //0x37:
0x00002AAA, //0x38:
0x00000000, //0x39: (read only)
0x00000000, //0x3A: (read only)
0x00000000, //0x3B:
0x00000000, //0x3C:
0x00000000, //0x3D: (read only)
0x00000000, //0x3E:
0x00000000, //0x3F: (read only)
0x00000001, //0x40:
0x00000000, //0x41: (read only)
0x00000000, //0x42:
0x00000000, //0x43: (reserved)
0x00000000, //0x44: (reserved)
0x00000000, //0x45:
0x00000000, //0x46: (read only)
0x00000000, //0x47: (read only)
0x00000000, //0x48: (reserved)
0x00000000, //0x49: (reserved)
0x00000000, //0x4A: (reserved)
0x00000000, //0x4B: (read only)
0x00000000, //0x4C: (read only)
0x00000000, //0x4D:
0x00000000, //0x4E:
0x00000000, //0x4F: (reserved)
0x00000000, //0x50:
0x00000000, //0x51:
0x00000005, //0x52:
0x00000000, //0x53: (read only)
0x012C0100, //0x54:
0x00000000, //0x55: (reserved)
0x01000100, //0x56:
0x00000000, //0x57: (reserved)
0x02000100, //0x58:
0x00000000, //0x59: (reserved)
0x00000000, //0x5A:
0x00000000, //0x5B: (reserved)
0x00007FFF, //0x5C:
0x00005A81, //0x5D:
0x00000FA0, //0x5E:
0x00000BB8, //0x5F:
0x00001F40, //0x60:
0x80000001, //0x61:
0x7FFFFFFF, //0x62:
0x00000008, //0x63:
0x05DC0000, //0x64:
0x00000000, //0x65:
0x00000000, //0x66:
0x00000000, //0x67:
0x365A40D8, //0x68:
0x00000000, //0x69: (read only)
0x00000000, //0x6A: (read only)
0x365A40D8, //0x6B:
0x00000000, //0x6C: (read only)
0x00000000, //0x6D:
0x000000D2, //0x6E:
0x00000012, //0x6F:
0x00000000, //0x70: (reserved)
0x00000000, //0x71: (reserved)
0x00000000, //0x72: (reserved)
0x00000000, //0x73: (reserved)
0x00000000, //0x74:
0xFFFFFFFF, //0x75:
0x00000000, //0x76: (read only)
0x00000000, //0x77: (read only)
0x00000000, //0x78:
0x00009600, //0x79:
0x00000000, //0x7A:
0x00000000, //0x7B:
0xC4788080, //0x7C:
0x00000000, //0x7D:
};
| 33.205021
| 138
| 0.720073
|
HEEV
|
15bbdd1ab04d23447fbd2453535aec46a5121893
| 1,418
|
cc
|
C++
|
cc/commons/droid_wrapper.cc
|
neo5simple/commons
|
3a8b3bd37376f6e1b060411ae5efaeab53d5d4f3
|
[
"Apache-2.0"
] | null | null | null |
cc/commons/droid_wrapper.cc
|
neo5simple/commons
|
3a8b3bd37376f6e1b060411ae5efaeab53d5d4f3
|
[
"Apache-2.0"
] | null | null | null |
cc/commons/droid_wrapper.cc
|
neo5simple/commons
|
3a8b3bd37376f6e1b060411ae5efaeab53d5d4f3
|
[
"Apache-2.0"
] | null | null | null |
// Generated by Neo
#ifdef _ANDROID_PLATFORM_
#include <commons/droid_wrapper.h>
#include <pthread.h>
namespace commons {
JavaVM* g_vm = nullptr;
JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved) {
g_vm = vm;
return JNI_VERSION_1_6;
}
void JNI_OnUnload(JavaVM* vm, void* reserved) {}
JNIEnv* gen_attached_env(JavaVM* jvm, jint version, jboolean* need_detach) {
JNIEnv* env = nullptr;
*need_detach = JNI_FALSE;
if (nullptr != jvm) {
bool is_attached = false;
jint result = jvm->GetEnv((void**)&env, version);
switch (result) {
case JNI_OK:
is_attached = true;
break;
case JNI_EDETACHED:
// [Neo] new attached
if (JNI_OK == jvm->AttachCurrentThread(&env, nullptr)) {
is_attached = true;
*need_detach = JNI_TRUE;
}
break;
// [Neo] generic error
case JNI_ERR:
// [Neo] bad version
case JNI_EVERSION:
default:
LOGE("[%p] %s: GetEnv = %d!!", LOCATE_PT, result);
break;
}
if (false == is_attached) {
env = nullptr;
}
} else {
LOGE("[%p] %s: jvm = nullptr!!", LOCATE_PT);
}
return (JNIEnv*)env;
}
} /* namespace: commons */
#endif /* _ANDROID_PLATFORM_ */
| 23.245902
| 76
| 0.521157
|
neo5simple
|
15bc93745a37c417eebc1e764a2e3591a90a19a0
| 1,149
|
cpp
|
C++
|
src/models/model_point3d/model_point3d.cpp
|
chingoduc/parallel-bayesian-toolbox
|
20c06a823c714a51a51e5b59c3232cd1260b0fa4
|
[
"BSD-4-Clause-UC"
] | 1
|
2015-12-01T13:15:14.000Z
|
2015-12-01T13:15:14.000Z
|
src/models/model_point3d/model_point3d.cpp
|
chingoduc/parallel-bayesian-toolbox
|
20c06a823c714a51a51e5b59c3232cd1260b0fa4
|
[
"BSD-4-Clause-UC"
] | null | null | null |
src/models/model_point3d/model_point3d.cpp
|
chingoduc/parallel-bayesian-toolbox
|
20c06a823c714a51a51e5b59c3232cd1260b0fa4
|
[
"BSD-4-Clause-UC"
] | null | null | null |
#include "model_point3d.h"
#include "noise_gauss.h"
#include <math.h>
ModelPoint3D::ModelPoint3D(){
}
ModelPoint3D::~ModelPoint3D()
{
}
void ModelPoint3D::setDescriptionTag(){
descriptionTag = "3d point";
}
void ModelPoint3D::setPNoise(){
NoiseGaussian* x = new NoiseGaussian(0.0f, 0.01f);
pNoise.addNoise(x);
NoiseGaussian* y = new NoiseGaussian(0.0f, 0.01f);
pNoise.addNoise(y);
NoiseGaussian* z = new NoiseGaussian(0.0f, 0.01f);
pNoise.addNoise(z);
}
void ModelPoint3D::setONoise(){
NoiseGaussian* x = new NoiseGaussian( 0.0f, 0.06f);
oNoise.addNoise(x);
NoiseGaussian* y = new NoiseGaussian( 0.0f, 0.06f);
oNoise.addNoise(y);
NoiseGaussian* z = new NoiseGaussian( 0.0f, 0.06f);
oNoise.addNoise(z);
}
fmat ModelPoint3D::ffun(fmat *current){
fmat pNoiseSample = pNoise.sample(current->n_cols);
fmat prediction = *current + pNoiseSample;
return prediction;
}
fmat ModelPoint3D::hfun(fmat *state){
fmat measurement(state->n_rows,state->n_cols);
fmat oNoiseSample = oNoise.sample(state->n_cols);
measurement = *state + oNoiseSample;
return measurement;
}
| 21.277778
| 55
| 0.684943
|
chingoduc
|
15c076e4923795eec142452b4f23a065d78354fc
| 6,360
|
cpp
|
C++
|
src/yostat_parse.cpp
|
rschlaikjer/yostat
|
46971991704fe4d6b88c7c1657d8ad100fbee21f
|
[
"MIT"
] | null | null | null |
src/yostat_parse.cpp
|
rschlaikjer/yostat
|
46971991704fe4d6b88c7c1657d8ad100fbee21f
|
[
"MIT"
] | null | null | null |
src/yostat_parse.cpp
|
rschlaikjer/yostat
|
46971991704fe4d6b88c7c1657d8ad100fbee21f
|
[
"MIT"
] | null | null | null |
#include <fstream>
#include <iostream>
#include <nlohmann/json.hpp>
#include <yostat/parse.hpp>
// Determine which modules in a design are primitives
std::set<std::string> unique_primitives_in_design(nlohmann::json &j);
Design *read_json(std::string path) {
// Try and open the input file
std::ifstream file_ifstream;
file_ifstream.open(path);
// Check if we failed to open the file
if (file_ifstream.fail()) {
return nullptr;
}
// Parse to a json object
nlohmann::json j;
file_ifstream >> j;
// Extract the primitives used in this design
std::set<std::string> device_primitives = unique_primitives_in_design(j);
// Now pull out all our useful data
std::string top_module = "top";
std::map<std::string, YosysModule> modules;
for (auto module_it = j["modules"].begin(); module_it != j["modules"].end();
++module_it) {
// Create a struct for this module
YosysModule mod;
mod.name = module_it.key();
// Check if this is the top module?
auto &attributes = module_it.value()["attributes"];
auto attr_top = attributes.find("top");
if (attr_top != attributes.end()) {
top_module = mod.name;
}
// Load the number of cells used by the module
auto &cells = module_it.value()["cells"];
for (auto cells_it = cells.begin(); cells_it != cells.end(); ++cells_it) {
mod.increment_celltype(cells_it.value()["type"]);
}
modules[mod.name] = mod;
}
Module *tree =
generate_module_tree(modules, device_primitives, nullptr, top_module);
Design *d = new Design;
d->top = tree;
d->primitives = unique_primitives_in_tree(tree);
return d;
}
bool YosysModule::all_cells_are_primitives(std::set<std::string> primitives) {
for (auto &cell : cell_counts) {
if (primitives.find(cell.first) == primitives.end()) {
return false;
}
}
return true;
}
std::set<std::string> unique_primitives_in_design(nlohmann::json &j) {
std::set<std::string> primitives;
// Iterate all modules and check the 'blackbox'/'whitebox' attribute as a
// proxy for them being a device primitive
for (auto module_it = j["modules"].begin(); module_it != j["modules"].end();
++module_it) {
auto &attributes = module_it.value()["attributes"];
auto blackbox = attributes.find("blackbox");
auto whitebox = attributes.find("whitebox");
// Does the blackbox/whitebox attribute exist?
if (blackbox != attributes.end() || whitebox != attributes.end()) {
primitives.emplace(module_it.key());
}
}
return primitives;
}
// Get the primitives that actually showed up in the design so that we don't
// display a bunch of empty columns
std::vector<std::string> unique_primitives_in_tree(Module *tree) {
// Create quick lambda to do the recursive work for us
std::function<void(const Module *, std::set<std::string> &)> visitor =
[&visitor](const Module *m, std::set<std::string> &uniq_primitives) {
for (auto &prim : m->primitives) {
uniq_primitives.emplace(prim.first);
}
for (const Module *child : m->submodules) {
visitor(child, uniq_primitives);
}
};
// Iterate all modules in the tree
std::set<std::string> uniq_primitives;
visitor(tree, uniq_primitives);
// Convert to vector
std::vector<std::string> ret(uniq_primitives.begin(), uniq_primitives.end());
std::sort(ret.begin(), ret.end());
return ret;
}
void delete_module_tree(Module *m) {
// Recursively delete the children, then ourselves
for (auto submodule : m->submodules) {
delete_module_tree(submodule);
}
delete (m);
}
Module *generate_module_tree(std::map<std::string, YosysModule> modules,
std::set<std::string> primitive_names,
Module *parent, std::string module_name) {
// Look up the data we pulled from the json earlier
auto yosys_mod = modules[module_name];
// Instantiate the module for the wx data tree
Module *mod = new Module(parent, module_name);
// In order to differentiate logic used by a module and logic used by
// submodules of that module, create a special 'self' submodule for modules
// that do not consist entirely of primitives
Module *mod_self_primitives = nullptr;
if (!yosys_mod.all_cells_are_primitives(primitive_names)) {
mod_self_primitives = new Module(mod, " (self)");
}
// For each cell this module contains, recurse to build them out
for (auto &cell : yosys_mod.cell_counts) {
// If it isn't a primitive, recurse and build it out properly
// For non-primitives with multiple instances, we generate two hierarchy
// levels - one the counts all instantiations as one line item, and then
// each individual instantiation below that. This way, we can easily see
// both the individual and combined weight of the modules.
const bool is_primitive =
primitive_names.find(cell.first) != primitive_names.end();
if (!is_primitive) {
if (cell.second > 1) {
// Multi-instance case
// Create the multi-instance holder
Module *holder = new Module(mod, "[" + std::to_string(cell.second) +
"x] " + cell.first);
// Generate each individual instance tree using the holder as a parent
for (int i = 0; i < cell.second; i++) {
generate_module_tree(modules, primitive_names, holder, cell.first);
}
// Tally the holder primitive counts
for (auto *submod : holder->submodules) {
for (auto &prim : submod->primitives) {
holder->increment_primitive_count(prim.first, prim.second);
}
}
} else {
generate_module_tree(modules, primitive_names, mod, cell.first);
}
} else {
// If it is a primitive, just update the counter for it
if (mod_self_primitives) {
mod_self_primitives->set_primitive_count(cell.first, cell.second);
} else {
mod->set_primitive_count(cell.first, cell.second);
}
}
}
// Now that we have built the children for this node, iterate them and sum
// their primitive counts to get our own primitive count
for (auto *submod : mod->submodules) {
for (auto &prim : submod->primitives) {
mod->increment_primitive_count(prim.first, prim.second);
}
}
return mod;
}
| 34.378378
| 79
| 0.658333
|
rschlaikjer
|
15c59833cebdcb5f5401137348b6e32d629331fa
| 106
|
cpp
|
C++
|
src/toolchain/tools/cc0/Configuration.cpp
|
layerzero/cc0
|
fa3f8f1f7bbc38ca5b6b8864c80223191b3b1f09
|
[
"BSD-2-Clause"
] | null | null | null |
src/toolchain/tools/cc0/Configuration.cpp
|
layerzero/cc0
|
fa3f8f1f7bbc38ca5b6b8864c80223191b3b1f09
|
[
"BSD-2-Clause"
] | null | null | null |
src/toolchain/tools/cc0/Configuration.cpp
|
layerzero/cc0
|
fa3f8f1f7bbc38ca5b6b8864c80223191b3b1f09
|
[
"BSD-2-Clause"
] | 2
|
2015-03-03T04:36:51.000Z
|
2018-10-01T03:04:11.000Z
|
#include "Configuration.h"
Configuration::Configuration()
{
}
Configuration::~Configuration()
{
}
| 6.625
| 31
| 0.688679
|
layerzero
|
15c954af265693072106960b43a5560ef2559009
| 194
|
cpp
|
C++
|
GLTeardown.cpp
|
rebeckao/house-escape-3
|
2164fabc705fffb73036924936aacdef253178b7
|
[
"Unlicense"
] | null | null | null |
GLTeardown.cpp
|
rebeckao/house-escape-3
|
2164fabc705fffb73036924936aacdef253178b7
|
[
"Unlicense"
] | null | null | null |
GLTeardown.cpp
|
rebeckao/house-escape-3
|
2164fabc705fffb73036924936aacdef253178b7
|
[
"Unlicense"
] | null | null | null |
#include "GLTeardown.h"
/*
Call when program is done
*/
void tearDownEverything(SDL_Window*& window){
SDL_GL_DeleteContext(window);
SDL_DestroyWindow(window);
// Clean up SDL
SDL_Quit();
}
| 16.166667
| 45
| 0.742268
|
rebeckao
|
15c995c92377bdcb4b1507b58f338a7aa6e6f0d9
| 19,871
|
cpp
|
C++
|
apps/kbmcepc/sgw1.cpp
|
vaishalijhalani/SGW
|
93fef349fcb3e57dd167072d357da5b49f5150c8
|
[
"BSD-3-Clause"
] | null | null | null |
apps/kbmcepc/sgw1.cpp
|
vaishalijhalani/SGW
|
93fef349fcb3e57dd167072d357da5b49f5150c8
|
[
"BSD-3-Clause"
] | null | null | null |
apps/kbmcepc/sgw1.cpp
|
vaishalijhalani/SGW
|
93fef349fcb3e57dd167072d357da5b49f5150c8
|
[
"BSD-3-Clause"
] | null | null | null |
#include "K_sgw.h"
using namespace std;
#define MAX_THREADS 1
//std::mutex mutex1, mutex2, mutex3, mutex4, mutex5, mutex6;
queue <int> free_port;
struct cadata{
int fd,num;
};
//State
unordered_map<uint32_t, uint64_t> s11_id; /* S11 UE identification table: s11_cteid_sgw -> imsi */
unordered_map<uint32_t, uint64_t> s1_id; /* S1 UE identification table: s1_uteid_ul -> imsi */
unordered_map<uint32_t, uint64_t> s5_id; /* S5 UE identification table: s5_uteid_dl -> imsi */
unordered_map<uint64_t, UeContext> ue_ctx; /* UE context table: imsi -> UeContext */
//Not needed for single core
pthread_mutex_t s11id_mux; /* Handles s11_id */
pthread_mutex_t s1id_mux; /* Handles s1_id */
pthread_mutex_t s5id_mux; /* Handles s5_id */
pthread_mutex_t uectx_mux; /* Handles ue_ctx */
pthread_mutex_t epoll_mux;
struct thread_data{
int id;
int core;
int min;
int max;
};
struct pgw_data
{
int sockfd;
int port;
struct sockaddr_in c_addr;
};
#define print_error_then_terminate(en, msg) \
do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)
int lsfd;
struct sockaddr_in server;
void *action(void *arg)
{
int acfd, portno, n, numev, i, cafd, ccfd, cret,trf, pgw_fd;
char buf[100];
long long transactions = 0;
struct thread_data *my_data;
my_data = (struct thread_data *) arg;
int threadID = my_data->id;
int core_id = my_data->core;
int min_port = my_data->min;
int max_port = my_data->max;
int count,tcount;
cout << "in thread " << threadID << endl;
struct sockaddr_in c_addr, a_addr, bserver;
struct hostent *c_ip;
set<int> srca, srcc, srcr; //set-C-accept/connect/read;
map<int, int> mm;
map<int, int> mm1;
struct cadata cd;
int buffer = 0;
int returnval,cur_fd, act_type;
map<int, mdata> fdmap;
map<int, pgw_data> pgw_port;
struct mdata fddata;
struct pgw_data pgdata;
Packet pkt;
int pkt_len;
char * dataptr;
unsigned char data[1024];
/*
SGW Specific data
*/
uint32_t s1_uteid_ul;
uint32_t s5_uteid_ul;
uint32_t s5_uteid_dl;
uint32_t s11_cteid_mme;
uint32_t s11_cteid_sgw;
uint32_t s5_cteid_ul;
uint32_t s5_cteid_dl;
uint64_t imsi;
uint8_t eps_bearer_id;
uint64_t apn_in_use;
uint64_t tai;
string pgw_s5_ip_addr;
string ue_ip_addr;
int pgw_s5_port;
uint32_t s1_uteid_dl;
string enodeb_ip_addr;
int enodeb_port;
bool res;
const pthread_t pid = pthread_self();
cout << "pid " << pid << endl;
// cpu_set_t: This data set is a bitset where each bit represents a CPU.
cpu_set_t cpuset;
// CPU_ZERO: This macro initializes the CPU set set to be the empty set.
CPU_ZERO(&cpuset);
// CPU_SET: This macro adds cpu to the CPU set set.
CPU_SET(core_id, &cpuset);
// pthread_setaffinity_np: The pthread_setaffinity_np() function sets the CPU affinity mask of the thread thread to the CPU set pointed to by cpuset. If the call is successful, and the thread is not currently running on one of the CPUs in cpuset, then it is migrated to one of those CPUs.
const int set_result = pthread_setaffinity_np(pid, sizeof(cpu_set_t), &cpuset);
if (set_result != 0) {
print_error_then_terminate(set_result, "pthread_setaffinity_np");
}
// Check what is the actual affinity mask that was assigned to the thread.
// pthread_getaffinity_np: The pthread_getaffinity_np() function returns the CPU affinity mask of the thread thread in the buffer pointed to by cpuset.
const int get_affinity = pthread_getaffinity_np(pid, sizeof(cpu_set_t), &cpuset);
if (get_affinity != 0) {
print_error_then_terminate(get_affinity, "pthread_getaffinity_np");
}
int epfd = epoll_create(MAXEVENTS + 5);
if( epfd == -1){
cout<<"Error: epoll create"<<'\n';
exit(-1);
}
int retval;
struct epoll_event ev, rev[MAXEVENTS];
pthread_mutex_lock(&epoll_mux);
ev.data.fd = lsfd;
ev.events = EPOLLIN | EPOLLET;
retval = epoll_ctl( epfd, EPOLL_CTL_ADD, lsfd, &ev);
pthread_mutex_unlock(&epoll_mux);
if( retval == -1) {
cout<<"Error: epoll ctl lsfd add"<<'\n';
exit(-1);
}
cout<<"Entering Loop"<<'\n';
count = 0;
tcount=0;
trf = 0;
transactions = 0;
int start_port = min_port;
socklen_t blen;
blen = sizeof(bserver);
//cout << "lsfd " << lsfd << endl;
//cout << "ccfd " << ccfd << endl;
while( 1 )
{
numev = epoll_wait( epfd, rev, MAXEVENTS, -1);
//cout << numev << endl;
if(numev < 0)
{
cout<<"Error: EPOLL wait!"<<'\n';
exit(-1);
}
if(numev == 0)
{
if(trf == 1)
{
cout<<"Throughput :"<<transactions<<'\n';
trf = 0;
transactions = 0;
}
//cout<<"Tick "<<'\n';
}
for( i = 0; i < numev; i++)
{
trf = 1;
//Check Errors
if( (rev[i].events & EPOLLERR) || (rev[i].events & EPOLLHUP))
{
cout<<"ERROR: epoll monitoring failed, closing fd"<<'\n';
if(rev[i].data.fd == lsfd){
cout<<"Oh Oh, lsfd it is"<<'\n';
exit(-1);
}
close(rev[i].data.fd);
continue;
}
else if(rev[i].events & EPOLLIN)
{
struct sockaddr_in from;
bzero((char *) &from, sizeof(from) );
socklen_t fromlen = sizeof(from);
bzero(buf, 100);
cafd = rev[i].data.fd;
//cout << cafd << endl;
if(cafd == lsfd)
{
while(1)
{
pkt.clear_pkt();
n = recvfrom(cafd, pkt.data, BUF_SIZE, 0, (struct sockaddr *) &from, &fromlen);
if ( n < 0) {
break;
cout<<"Error : Read Error "<<'\n';
exit(-1);
}
int port = ntohs(from.sin_port);
cout << port << endl;
pkt.data_ptr = 0;
pkt.len = retval;
pkt.extract_gtp_hdr();
if(pkt.gtp_hdr.msg_type == 1)
{//MME attach 3
pkt.extract_item(s11_cteid_mme);
pkt.extract_item(imsi);
pkt.extract_item(eps_bearer_id);
pkt.extract_item(pgw_s5_ip_addr);
pkt.extract_item(pgw_s5_port);
pkt.extract_item(apn_in_use);
pkt.extract_item(tai);
//cout << "packetid " << pkt.gtp_hdr.msg_type << endl;
s1_uteid_ul = s11_cteid_mme;
s5_uteid_dl = s11_cteid_mme;
s11_cteid_sgw = s11_cteid_mme;
s5_cteid_dl = s11_cteid_mme;
pthread_mutex_lock(&s11id_mux);
s11_id[s11_cteid_sgw] = imsi;
pthread_mutex_unlock(&s11id_mux);
pthread_mutex_lock(&s1id_mux);
s1_id[s1_uteid_ul] = imsi;
pthread_mutex_unlock(&s1id_mux);
pthread_mutex_lock(&s5id_mux);
s5_id[s5_uteid_dl] = imsi;
pthread_mutex_unlock(&s5id_mux);
TRACE( cout << "attach 3 packet received\n";)
TRACE(cout<<"Attach 3 in"<<imsi<< " "<<s11_cteid_mme<<endl;)
pthread_mutex_lock(&uectx_mux);
ue_ctx[imsi].init(tai, apn_in_use, eps_bearer_id, s1_uteid_ul, s5_uteid_dl, s11_cteid_mme, s11_cteid_sgw, s5_cteid_dl, pgw_s5_ip_addr, pgw_s5_port);
ue_ctx[imsi].tai = tai;
pthread_mutex_unlock(&uectx_mux);
pkt.clear_pkt();
pkt.append_item(s5_cteid_dl);
pkt.append_item(imsi);
pkt.append_item(eps_bearer_id);
pkt.append_item(s5_uteid_dl);
pkt.append_item(apn_in_use);
pkt.append_item(tai);
pkt.prepend_gtp_hdr(2, 1, pkt.len, 0);
ccfd = socket(AF_INET, SOCK_DGRAM, 0);
if(ccfd < 0){
cout << "ERROR: C Socket Open\n";
exit(-1);
}
make_socket_nb(ccfd);
int uflag = 1;
if (setsockopt(ccfd, SOL_SOCKET, SO_REUSEADDR, &uflag, sizeof(uflag)) < 0)
{
cout<<"Error : server setsockopt reuse"<<endl;
exit(-2);
}
bzero((char *) &bserver, sizeof(bserver) );
bserver.sin_family = AF_INET;
bserver.sin_addr.s_addr = inet_addr("192.168.122.167");
blen = sizeof(bserver);
bserver.sin_port = htons(start_port);
if(bind(ccfd, (struct sockaddr *) &bserver, sizeof(bserver)) < 0)
{
while (bind(ccfd, (struct sockaddr *) &bserver, sizeof(bserver)) < 0)
{
start_port++;
bserver.sin_port = htons(start_port);
}
}
else
start_port++;
if(start_port>max_port)
start_port = min_port;
pgdata.sockfd = ccfd;
pgdata.port = start_port-1;
memcpy (&pgdata.c_addr, &bserver, sizeof (pgdata.c_addr));
pgw_port.insert(make_pair(port, pgdata));
srcr.insert(ccfd);
buffer = 0;
buffer = atoi(buf);
mm[ccfd] = port;
mm1[ccfd] = buffer;
bzero((char *) &c_addr, sizeof(c_addr) );
c_addr.sin_family = AF_INET;
c_addr.sin_addr.s_addr = inet_addr("192.168.122.157");
c_addr.sin_port = htons(8000);
ev.data.fd = ccfd;
ev.events = EPOLLIN;
retval = epoll_ctl( epfd, EPOLL_CTL_ADD, ccfd, &ev);
if( retval == -1) {
cout<<"Error: epoll ctl ccfd add"<<'\n';
exit(-1);
}
//count++;
//cout << count << " in thread " << threadID << endl;
n = sendto(ccfd, pkt.data, pkt.len, 0,(const struct sockaddr *)&c_addr,sizeof(c_addr));
if(n <= 0){
cout<<"Error : Write Error"<<'\n';
exit(-1);
}
//close(ccfd);
fddata.initial_fd = port;
fddata.pgw_port = start_port-1;
fddata.tid = s11_cteid_mme;
fddata.guti = imsi;
memcpy(fddata.buf, pkt.data, pkt.len);
fddata.buflen = pkt.len;
fdmap.insert(make_pair(ccfd, fddata));
}
else
if(pkt.gtp_hdr.msg_type == 2)
{//attach 4 from mme
mlock(s11id_mux);
if (s11_id.find(pkt.gtp_hdr.teid) != s11_id.end()) {
imsi = s11_id[pkt.gtp_hdr.teid];
}
else
{
cout<<"IMSI error"<<endl;
exit(-1);
}
munlock(s11id_mux);
if (imsi == 0) {
TRACE(cout << "sgw_handlemodifybearer:" << " :zero imsi " << pkt.gtp_hdr.teid << " " << pkt.len << ": " << imsi << endl;)
exit(-1);
}
pkt.extract_item(eps_bearer_id);
pkt.extract_item(s1_uteid_dl);
pkt.extract_item(enodeb_ip_addr);
pkt.extract_item(enodeb_port);
mlock(uectx_mux);
ue_ctx[imsi].s1_uteid_dl = s1_uteid_dl;
ue_ctx[imsi].enodeb_ip_addr = enodeb_ip_addr;
ue_ctx[imsi].enodeb_port = enodeb_port;
s11_cteid_mme = ue_ctx[imsi].s11_cteid_mme;
munlock(uectx_mux);
TRACE(cout<<"In attach 4 "<< imsi<< " "<<s11_cteid_mme << "recv "<< s1_uteid_dl<<endl;)
res = true;
pkt.clear_pkt();
pkt.append_item(res);
pkt.prepend_gtp_hdr(2, 2, pkt.len, s11_cteid_mme);
//pkt.prepend_len();
bzero((char *) &a_addr, sizeof(a_addr) );
a_addr.sin_family = AF_INET;
a_addr.sin_addr.s_addr = inet_addr("192.168.122.147");
a_addr.sin_port = htons(port);
n = sendto(cafd, pkt.data, pkt.len, 0,(const struct sockaddr *)&a_addr,sizeof(a_addr));
if(n < 0){
cout<<"Error MME write back to RAN A2"<<endl;
exit(-1);
}
}//4th attach
else//Detach
if(pkt.gtp_hdr.msg_type == 3)
{
mlock(s11id_mux);
if (s11_id.find(pkt.gtp_hdr.teid) != s11_id.end()) {
imsi = s11_id[pkt.gtp_hdr.teid];
}
else
{
cout<<"IMSI error"<<endl;
exit(-1);
}
munlock(s11id_mux);
pkt.extract_item(eps_bearer_id);
pkt.extract_item(tai);
mlock(uectx_mux);
if (ue_ctx.find(imsi) == ue_ctx.end()) {
TRACE(cout << "sgw_handledetach:" << " no uectx: " << imsi << endl;)
exit(-1);
}
munlock(uectx_mux);
if(gettid(imsi) != pkt.gtp_hdr.teid)
{
cout<<"GUTI not equal Detach acc"<<imsi<<" "<<pkt.gtp_hdr.teid<<endl;
exit(-1);
}
mlock(uectx_mux);
pgw_s5_ip_addr = ue_ctx[imsi].pgw_s5_ip_addr;
pgw_s5_port = ue_ctx[imsi].pgw_s5_port;
s5_cteid_ul = ue_ctx[imsi].s5_cteid_ul;
s11_cteid_mme = ue_ctx[imsi].s11_cteid_mme;
s11_cteid_sgw = ue_ctx[imsi].s11_cteid_sgw;
s1_uteid_ul = ue_ctx[imsi].s1_uteid_ul;
s5_uteid_dl = ue_ctx[imsi].s5_uteid_dl;
munlock(uectx_mux);
TRACE(cout<<"In detach "<<imsi<<" s5 "<< s5_cteid_ul<< "s11 "<<s11_cteid_mme <<" rcv " << pkt.gtp_hdr.teid<<endl;)
pkt.clear_pkt();
pkt.append_item(eps_bearer_id);
pkt.append_item(tai);
pkt.prepend_gtp_hdr(2, 4, pkt.len, s5_cteid_ul);
//pkt.prepend_len();
//send to pgw
pgdata = pgw_port[port];
returnval = sendto(pgdata.sockfd, pkt.data , pkt.len, 0, (const struct sockaddr *)&(c_addr),sizeof(c_addr));
if(returnval < 0)
{
cout<<"Error: pgw write detach "<<errno<<endl;
exit(-1);
}
TRACE(cout << "detach sent to pgw\n";)
/*fdmap.erase(cur_fd);
fddata.act = 4;
fddata.tid = s11_cteid_mme;
fddata.guti = imsi;
fddata.buflen = 0;
fddata.initial_fd = sgw_fd;
memset(fddata.buf, '\0', 500);
fdmap.insert(make_pair(pgw_fd, fddata));*/
//goto case 4
}
}
}
else if(srcr.find(rev[i].data.fd) != srcr.end())
{
cout << " data came from pgw\n";
int retfd = rev[i].data.fd;
pkt.clear_pkt();
bzero((char *) &from, sizeof(from) );
n = recvfrom(retfd, pkt.data, BUF_SIZE, 0, (struct sockaddr *) &from, &fromlen);
if ( n < 0) {
//break;
cout<<"Error : Read Error "<<'\n';
exit(-1);
}
pkt.data_ptr = 0;
pkt.len =retval;
TRACE(cout << "sgw_handlecreatesession:" << " create session response received from pgw: " << imsi << endl;)
int num = mm1[retfd];
int num2 = mm[retfd];
mm.erase(retfd);
mm1.erase(retfd);
//srcr.erase(retfd);
fddata = fdmap[retfd];
imsi = fddata.guti;
pkt.extract_gtp_hdr();
if(pkt.gtp_hdr.msg_type == 1)
{//MME attach 3
pkt.extract_item(s5_cteid_ul);
pkt.extract_item(eps_bearer_id);
pkt.extract_item(s5_uteid_ul);
pkt.extract_item(ue_ip_addr);
mlock(uectx_mux);
ue_ctx[imsi].s5_uteid_ul = s5_uteid_ul;
ue_ctx[imsi].s5_cteid_ul = s5_cteid_ul;
munlock(uectx_mux);
TRACE(cout<<"Attach 3 received from PGW "<< imsi <<" " << fddata.tid<< " rcv "<<s5_cteid_ul<<endl;)
s1_uteid_ul = fddata.tid;
s11_cteid_sgw = fddata.tid;
pkt.clear_pkt();
pkt.append_item(s11_cteid_sgw);
pkt.append_item(ue_ip_addr);
pkt.append_item(s1_uteid_ul);
pkt.append_item(s5_uteid_ul);
pkt.append_item(s5_uteid_dl);
pkt.prepend_gtp_hdr(2, 1, pkt.len, s11_cteid_mme);
bzero((char *) &a_addr, sizeof(a_addr) );
a_addr.sin_family = AF_INET;
a_addr.sin_addr.s_addr = inet_addr("192.168.122.147");
a_addr.sin_port = htons(fddata.initial_fd);
n = sendto(lsfd, pkt.data, pkt.len, 0,(const struct sockaddr *)&a_addr,sizeof(a_addr));
if(n < 0){
cout<<"Error : Write Error"<<'\n';
exit(-1);
}
//close(retfd);
//cout << " in thread " << threadID << "by C" << endl;
}
else if(pkt.gtp_hdr.msg_type == 4)
{
cout << "detach reply from pgw "<< endl;
pkt.extract_item(res);
if (res == false) {
TRACE(cout << "sgw_handledetach:" << " pgw detach failure: " << imsi << endl;)
exit(-1);
}
s11_cteid_mme = fddata.tid;
TRACE(cout<<"Detach received "<<pkt.gtp_hdr.teid <<" s11"<<s11_cteid_mme<<endl;)
pkt.clear_pkt();
pkt.append_item(res);
pkt.prepend_gtp_hdr(2, 3, pkt.len, s11_cteid_mme);
//pkt.prepend_len();
pthread_mutex_lock(&s11id_mux);
if (s11_id.find(s11_cteid_mme) != s11_id.end()) {
imsi = s11_id[s11_cteid_mme];
}
else
{
cout<<"Detach imsi not found"<<endl;
exit(-1);
}
s11_id.erase(s11_cteid_mme);
pthread_mutex_unlock(&s11id_mux);
pthread_mutex_lock(&s1id_mux);
s1_id.erase(s11_cteid_mme);
pthread_mutex_unlock(&s1id_mux);
pthread_mutex_lock(&s5id_mux);
s5_id.erase(s11_cteid_mme);
pthread_mutex_unlock(&s5id_mux);
pthread_mutex_lock(&uectx_mux);
ue_ctx.erase(imsi);
pthread_mutex_unlock(&uectx_mux);
cout << "detach sending to mme\n";
bzero((char *) &a_addr, sizeof(a_addr) );
a_addr.sin_family = AF_INET;
a_addr.sin_addr.s_addr = inet_addr("192.168.122.147");
a_addr.sin_port = htons(fddata.initial_fd);
cout << fddata.initial_fd << endl;
n = sendto(lsfd, pkt.data, pkt.len, 0,(const struct sockaddr *)&a_addr,sizeof(a_addr));
if(n < 0){
cout<<"Error : Write Error"<<'\n';
exit(-1);
}
/*mme_fd = fddata.initial_fd;
returnval = sendto(mctx, mme_fd, pkt.data, pkt.len);
if(returnval < 0)
{
cout<<"Error: Cant send to MME detach"<<endl;
exit(-1);
}
fdmap.erase(cur_fd);
close(cur_fd);
close(mme_fd);*/
}
}
}
}
}
//close(lsfd);
} //End Function
int main(int argc, char *argv[])
{
int i,n,numth,rc;
if(argc != 2)
{
//printinput();
exit(0);
}
////////////////////////////////////////////////////////////////////////////
lsfd = socket(AF_INET, SOCK_DGRAM, 0);
if(lsfd < 0) {
cout<<"ERROR : opening socket"<<'\n';
exit(-1);
}
make_socket_nb(lsfd);
int uflag = 1;
if (setsockopt(lsfd, SOL_SOCKET, SO_REUSEADDR, &uflag, sizeof(uflag)) < 0)
{
cout<<"Error : server setsockopt reuse"<<endl;
exit(-2);
}
bzero((char *) &server, sizeof(server) );
server.sin_family = AF_INET;
server.sin_addr.s_addr = inet_addr("192.168.122.167");
server.sin_port = htons(7000);
if (bind(lsfd, (struct sockaddr *) &server, sizeof(server)) < 0) {
cout<<"ERROR: BIND ERROR"<<'\n';
exit(-1);
}
//////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
numth = atoi(argv[1]);
//duration = atoi(argv[2]);
/* Set affinity mask to include CPUs 0 to 7 */
pthread_t th[numth];
struct thread_data td[numth];
pthread_attr_t attr;
void *status;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for(i = 0; i < numth;i++)
{
td[i].id = i;
td[i].core = i;
if(i==0){
td[i].min = 10001;
td[i].max = 20000;}
else if(i==1)
{
td[i].min = 20001;
td[i].max = 30000;
}
rc = pthread_create(&th[i], &attr, action, (void *)&td[i]);
if(rc)
cout<<"Error thread"<<endl;
}
for(i = 0; i < numth; i++)
{
//td[i].status = 1;
rc = pthread_join(th[i], &status);
if (rc){
cout << "Error:unable to join," << rc << endl;
exit(-1);
}
//cout << " M: Joined with status " << status << endl;
}
pthread_exit(NULL);
}
| 25.541131
| 292
| 0.55664
|
vaishalijhalani
|
15cc90e7bc9f21a70915b6f95248609bce835ca3
| 3,328
|
hpp
|
C++
|
include/foxy/client_session.hpp
|
LeonineKing1199/f2
|
785b17ee0d088bf1082add54c3e097393fc10035
|
[
"BSL-1.0"
] | 1
|
2018-07-16T21:01:59.000Z
|
2018-07-16T21:01:59.000Z
|
include/foxy/client_session.hpp
|
LeonineKing1199/f2
|
785b17ee0d088bf1082add54c3e097393fc10035
|
[
"BSL-1.0"
] | null | null | null |
include/foxy/client_session.hpp
|
LeonineKing1199/f2
|
785b17ee0d088bf1082add54c3e097393fc10035
|
[
"BSL-1.0"
] | null | null | null |
#ifndef FOXY_CLIENT_SESSION_HPP_
#define FOXY_CLIENT_SESSION_HPP_
#include <boost/asio/post.hpp>
#include <boost/asio/io_context.hpp>
#include <boost/asio/async_result.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/connect.hpp>
#include <boost/asio/strand.hpp>
#include <boost/asio/associated_executor.hpp>
#include <boost/asio/associated_allocator.hpp>
#include <boost/system/error_code.hpp>
#include <boost/beast/http/read.hpp>
#include <boost/beast/http/write.hpp>
#include <boost/beast/core/bind_handler.hpp>
#include <boost/core/ignore_unused.hpp>
#include <memory>
#include <utility>
#include <iostream>
#include <string_view>
#include "foxy/coroutine.hpp"
#include "foxy/multi_stream.hpp"
#include "foxy/detail/session.hpp"
namespace foxy {
struct client_session : public detail::session {
public:
using timer_type = detail::session_state::timer_type;
using buffer_type = detail::session_state::buffer_type;
using stream_type = detail::session_state::stream_type;
using strand_type = detail::session_state::strand_type;
// client sessions cannot be default-constructed as they require an
// `io_context`
//
client_session() = delete;
client_session(client_session const&) = default;
client_session(client_session&&) = default;
explicit
client_session(boost::asio::io_context& io);
// when constructed with an SSL context, the `client_session` will perform an
// SSL handshake with the remote when calling `async_connect`
// client sessions constructed with an SSL context need to be shutdown using
// `async_ssl_shutdown`
//
explicit
client_session(boost::asio::io_context& io, boost::asio::ssl::context& ctx);
// `async_connect` performs forward name resolution on the specified host
// and then attempts to form a TCP connection
// `service` is the same as the original `asio::async_connect` function
//
template <typename ConnectHandler>
auto async_connect(
std::string host,
std::string service,
ConnectHandler&& connect_handler
) & -> BOOST_ASIO_INITFN_RESULT_TYPE(
ConnectHandler,
void(boost::system::error_code, boost::asio::ip::tcp::endpoint));
// `async_request` writes a `http::request` to the remotely connected host
// and then uses the supplied `http::response_parser` to store the response
//
template <
typename Request,
typename ResponseParser,
typename WriteHandler
>
auto async_request(
Request& request,
ResponseParser& parser,
WriteHandler&& write_handler
) & -> BOOST_ASIO_INITFN_RESULT_TYPE(
WriteHandler, void(boost::system::error_code));
// use `shutdown` in the case of a non-SSL `client_session`
//
auto shutdown(boost::system::error_code& ec) -> void;
// `async_ssl_shutdown` is only meant to be called when the `client_session`
// was constructed with a valid `asio::ssl::context&`
// only this function must be called, calls to the `shutdown` will likely
// result in undefined behavior
//
template <typename ShutdownHandler>
auto async_ssl_shutdown(
ShutdownHandler&& shutdown_handler
) & -> BOOST_ASIO_INITFN_RESULT_TYPE(
ShutdownHandler, void(boost::system::error_code));
};
} // foxy
#include "foxy/impl/client_session.impl.hpp"
#endif // FOXY_CLIENT_SESSION_HPP_
| 29.981982
| 79
| 0.731671
|
LeonineKing1199
|
15d1802bed4d7f0d3c06029e7e3f2bdaddbde5e8
| 1,392
|
hpp
|
C++
|
modules/orbital2d/kepler.hpp
|
ryanpeach/godot
|
4cfe34e52f8492813c24525a4daa2f9ccc68ccd2
|
[
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | null | null | null |
modules/orbital2d/kepler.hpp
|
ryanpeach/godot
|
4cfe34e52f8492813c24525a4daa2f9ccc68ccd2
|
[
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | null | null | null |
modules/orbital2d/kepler.hpp
|
ryanpeach/godot
|
4cfe34e52f8492813c24525a4daa2f9ccc68ccd2
|
[
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | null | null | null |
namespace kepler {
/**
Calculates the eccentric anomaly at time t by solving Kepler's equation.
See "A Practical Method for Solving the Kepler Equation", Marc A. Murison, 2006
@ref https://gist.githubusercontent.com/j-faria/1fd079e677325ce820971d9d5d286dad/raw/7e2e6bf112e8c34067f0423a522113ca2daf3003/kepler.cpp
@param t the time at which to calculate the eccentric anomaly.
@param period the orbital period of the planet
@param ecc the eccentricity of the orbit
@param t_peri time of periastron passage
@return eccentric anomaly.
*/
double ecc_anomaly(const double ecc, const double mean_anomaly);
/**
Provides a starting value to solve Kepler's equation.
See "A Practical Method for Solving the Kepler Equation", Marc A. Murison, 2006
@param e the eccentricity of the orbit
@param M mean anomaly (in radians)
@return starting value for the eccentric anomaly.
*/
double keplerstart3(double e, double M);
/**
An iteration (correction) method to solve Kepler's equation.
See "A Practical Method for Solving the Kepler Equation", Marc A. Murison, 2006
@param e the eccentricity of the orbit
@param M mean anomaly (in radians)
@param x starting value for the eccentric anomaly
@return corrected value for the eccentric anomaly
*/
double eps3(double e, double M, double x);
}
| 36.631579
| 140
| 0.724138
|
ryanpeach
|
15d3108b978860be1e6419e8ad493174eef844a1
| 2,271
|
cpp
|
C++
|
src/bed.cpp
|
maxrossi91/levioSAM
|
00ee9133bdf2a7185d06b133b7f667af0c678e69
|
[
"MIT"
] | null | null | null |
src/bed.cpp
|
maxrossi91/levioSAM
|
00ee9133bdf2a7185d06b133b7f667af0c678e69
|
[
"MIT"
] | null | null | null |
src/bed.cpp
|
maxrossi91/levioSAM
|
00ee9133bdf2a7185d06b133b7f667af0c678e69
|
[
"MIT"
] | null | null | null |
/*
* bed.cpp
*
* Authors: Nae-Chyun Chen
*
* Distributed under the MIT license
* https://github.com/alshai/levioSAM
*/
#include <iostream>
#include <vector>
#include "bed.hpp"
#include "leviosam_utils.hpp"
namespace BedUtils {
Bed::Bed(const std::string &fn) {
bed_fn = fn;
is_valid = true;
std::ifstream bed_f(fn);
int cnt = 0;
if (bed_f.is_open()) {
std::string line;
while (std::getline(bed_f, line)) {
cnt += 1;
// std::cerr << line << "\n";
if (add_interval(line) == false) {
std::cerr << "[E::Bed] Failed to update BED record " << line << "\n";
}
}
bed_f.close();
}
auto contig_cnt = index();
std::cerr << "Read " << cnt << " BED records from " << contig_cnt << " contigs.\n";
}
int Bed::index() {
int contig_cnt = 0;
// Index the interval trees for each contig
for (auto& itr: intervals) {
itr.second.index();
contig_cnt += 1;
}
return contig_cnt;
}
bool Bed::add_interval(const std::string &line) {
is_valid = true;
std::vector<std::string> fields = LevioSamUtils::str_to_vector(line, "\t");
if (fields.size() < 3) {
return false;
}
std::string contig = fields[0];
size_t start = std::stoi(fields[1]);
size_t end = std::stoi(fields[2]);
auto itr = intervals.find(contig);
if (itr == intervals.end()) {
IITree<size_t, bool> new_tree;
new_tree.add(start, end, true);
intervals.emplace(std::make_pair(contig, new_tree));
} else {
itr->second.add(start, end, true);
}
return true;
}
// Interval intersect query
bool Bed::intersect(
const std::string &contig, const size_t &pos1, const size_t &pos2) {
if (!is_valid)
return false;
if (intervals.find(contig) == intervals.end())
return false;
std::vector<size_t> isec;
intervals[contig].overlap(pos1, pos2, isec);
return (isec.size() > 0);
}
// Point intersect query
bool Bed::intersect(const std::string &contig, const size_t &pos) {
return Bed::intersect(contig, pos, pos+1);
}
BedMap Bed::get_intervals() {
return intervals;
}
std::string Bed::get_fn() {
return bed_fn;
}
}; // namespace
| 22.71
| 87
| 0.580801
|
maxrossi91
|
15db2413f75897b959b23a5e50f2a8ab900a8d1e
| 25,394
|
hpp
|
C++
|
boost/utility/string_ref.hpp
|
FrostMineMC/Frost
|
a305c56c4bb72a8db25e3e81172d19ef8c0aad20
|
[
"Apache-2.0"
] | 17
|
2020-08-11T13:53:04.000Z
|
2022-01-03T11:29:51.000Z
|
boost/utility/string_ref.hpp
|
FrostMineMC/Frost
|
a305c56c4bb72a8db25e3e81172d19ef8c0aad20
|
[
"Apache-2.0"
] | 3
|
2021-06-17T13:22:57.000Z
|
2021-08-03T15:37:03.000Z
|
boost/utility/string_ref.hpp
|
FrostMineMC/Frost
|
a305c56c4bb72a8db25e3e81172d19ef8c0aad20
|
[
"Apache-2.0"
] | 2
|
2020-09-28T17:23:00.000Z
|
2021-07-30T10:07:16.000Z
|
/*
Copyright (c) Marshall Clow 2012-2015.
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)
For more information, see http://www.boost.org
Based on the StringRef implementation in LLVM (http://llvm.org) and
N3422 by Jeffrey Yasskin
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3442.html
*/
#ifndef BOOST_STRING_REF_HPP
#define BOOST_STRING_REF_HPP
#include <boost/config.hpp>
#include <boost/detail/workaround.hpp>
#include <boost/functional/hash.hpp>
#include <boost/throw_exception.hpp>
#include <boost/utility/string_ref_fwd.hpp>
#include <algorithm>
#include <cstddef>
#include <iosfwd>
#include <iterator>
#include <stdexcept>
#include <string>
#if defined(BOOST_NO_CXX11_DEFAULTED_FUNCTIONS) || \
(defined(BOOST_GCC) && ((BOOST_GCC + 0) / 100) <= 406)
// GCC 4.6 cannot handle a defaulted function with noexcept specifier
#define BOOST_STRING_REF_NO_CXX11_DEFAULTED_NOEXCEPT_FUNCTIONS
#endif
namespace boost {
namespace detail {
// A helper functor because sometimes we don't have lambdas
template <typename charT, typename traits>
class string_ref_traits_eq {
public:
string_ref_traits_eq(charT ch) : ch_(ch) {
}
bool operator()(charT val) const {
return traits::eq(ch_, val);
}
charT ch_;
}
}
template <typename charT, typename traits>
class basic_string_ref {
public:
// types
typedef charT value_type;
typedef const charT *pointer;
typedef const charT &reference;
typedef const charT &const_reference;
typedef pointer const_iterator; // impl-defined
typedef const_iterator iterator;
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
typedef const_reverse_iterator reverse_iterator;
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
static BOOST_CONSTEXPR_OR_CONST size_type npos = size_type(-1);
// construct/copy
BOOST_CONSTEXPR basic_string_ref() BOOST_NOEXCEPT : ptr_(NULL), len_(0) {
}
// by defaulting these functions, basic_string_ref becomes
// trivially copy/move constructible.
BOOST_CONSTEXPR basic_string_ref(const basic_string_ref &rhs) BOOST_NOEXCEPT
#ifndef BOOST_STRING_REF_NO_CXX11_DEFAULTED_NOEXCEPT_FUNCTIONS
= default;
#else
ptr_(rhs.ptr_),
len_(rhs.len_) {
}
#endif
basic_string_ref &operator=(const basic_string_ref &rhs) BOOST_NOEXCEPT
#ifndef BOOST_STRING_REF_NO_CXX11_DEFAULTED_NOEXCEPT_FUNCTIONS
= default;
#else
{
ptr_ = rhs.ptr_;
len_ = rhs.len_;
return *this;
}
#endif
basic_string_ref(const charT *str) BOOST_NOEXCEPT
ptr_(str),
len_(traits::length(str)) {
}
template <typename Allocator>
basic_string_ref(const std::basic_string<charT, traits, Allocator> &str)
ptr_(str.data()), len_(str.length()) {
}
BOOST_CONSTEXPR basic_string_ref(const charT *str, size_type len) BOOST_NOEXCEPT(ptr_(str), len_(len)) {
}
#ifndef BOOST_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS
template <typename Allocator>
explicit operator std::basic_string<charT, traits, Allocator>() const {
return std::basic_string<charT, traits, Allocator>(begin(), end());
}
#endif
std::basic_string<charT, traits> to_string() const {
return std::basic_string<charT, traits>(begin(), end());
}
// iterators
BOOST_CONSTEXPR const_iterator begin() const {
return ptr_;
}
BOOST_CONSTEXPR const_iterator cbegin() const {
return ptr_;
}
BOOST_CONSTEXPR const_iterator end() const {
return ptr_ + len_;
}
BOOST_CONSTEXPR const_iterator cend() const {
return ptr_ + len_;
}
const_reverse_iterator rbegin() const {
return const_reverse_iterator(end());
}
const_reverse_iterator crbegin() const {
return const_reverse_iterator(end());
}
const_reverse_iterator rend() const {
return const_reverse_iterator(begin());
}
const_reverse_iterator crend() const {
return const_reverse_iterator(begin());
}
// capacity
BOOST_CONSTEXPR size_type size() const {
return len_;
}
BOOST_CONSTEXPR size_type length() const {
return len_;
}
BOOST_CONSTEXPR size_type max_size() const {
return len_;
}
BOOST_CONSTEXPR bool empty() const {
return len_ == 0;
}
// element access
BOOST_CONSTEXPR const charT &operator[](size_type pos) const {
return ptr_[pos];
}
const charT &at(size_t pos) const {
if(pos >= len_) {
BOOST_THROW_EXCEPTION(std::out_of_range("boost::string_ref::at"));
}
return ptr_[pos];
}
BOOST_CONSTEXPR const charT &front() const {
return ptr_[0];
}
BOOST_CONSTEXPR const charT &back() const {
return ptr_[len_ - 1];
}
BOOST_CONSTEXPR const charT *data() const {
return ptr_;
}
// modifiers
void clear() {
len_ = 0;
}
void remove_prefix(size_type n) {
if(n > len_) {
n = len_;
}
ptr_ += n;
len_ -= n;
}
void remove_suffix(size_type n) {
if(n > len_) {
n = len_;
}
len_ -= n;
}
// basic_string_ref string operations
basic_string_ref substr(size_type pos, size_type n = npos) const {
if(pos > size()) {
BOOST_THROW_EXCEPTION(std::out_of_range("string_ref::substr"));
}
if(n == npos || pos + n > size()) {
n = size() - pos;
}
return basic_string_ref(data() + pos, n);
}
int compare(basic_string_ref x) const {
const int cmp = traits::compare(ptr_, x.ptr_, (std::min)(len_, x.len_));
return cmp != 0 ? cmp : (len_ == x.len_ ? 0 : len_ < x.len_ ? -1 : 1);
}
bool starts_with(charT c) const {
return !empty() && traits::eq(c, front());
}
bool starts_with(basic_string_ref x) const {
return len_ >= x.len_ && traits::compare(ptr_, x.ptr_, x.len_) == 0;
}
bool ends_with(charT c) const {
return !empty() && traits::eq(c, back());
}
bool ends_with(basic_string_ref x) const {
return len_ >= x.len_ && traits::compare(ptr_ + len_ - x.len_, x.ptr_, x.len_) == 0;
}
size_type find(basic_string_ref s) const {
const_iterator iter = std::search(this->cbegin(), this->cend(), s.cbegin(), s.cend(), traits::eq);
return iter == this->cend() ? npos;
std::distance(this->cbegin(), iter);
}
size_type find(charT c) const {
const_iterator iter = std::find_if(this->cbegin(), this->cend(), detail::string_ref_traits_eq<charT, traits>(c));
return iter == this->cend() ? npos;
std::distance(this->cbegin(), iter);
}
size_type rfind(basic_string_ref s) const {
const_reverse_iterator iter = std::search(this->crbegin(), this->crend(), s.crbegin(), s.crend(), traits::eq);
return iter == this->crend() ? npos(std::distance(iter, this->crend()) - s.size());
}
size_type rfind(charT c) const {
const_reverse_iterator iter = std::find_if(this->crbegin(), this->crend(), detail::string_ref_traits_eq<charT, traits>(c));
return iter == this->crend() ? npos(this->size() - 1 - std::distance(this->crbegin(), iter));
}
size_type find_first_of(charT c) const {
return find(c);
}
size_type find_last_of(charT c) const {
return rfind(c);
}
size_type find_first_of(basic_string_ref s) const {
const_iterator iter = std::find_first_of(this->cbegin(), this->cend(), s.cbegin(), s.cend(), traits::eq);
return iter == this->cend() ? npos
std::distance(this->cbegin(), iter);
}
size_type find_last_of(basic_string_ref s) const {
const_reverse_iterator iter = std::find_first_of(this->crbegin(), this->crend(), s.cbegin(), s.cend(), traits::eq);
return iter == this->crend() ? npos(this->size() - 1 - std::distance(this->crbegin(), iter));
}
size_type find_first_not_of(basic_string_ref s) const {
const_iterator iter = find_not_of(this->cbegin(), this->cend(), s);
return iter == this->cend() ? npos
std::distance(this->cbegin(), iter);
}
size_type find_first_not_of(charT c) const {
for(const_iterator iter = this->cbegin(); iter != this->cend(); ++iter) {
if(!traits::eq(c, *iter)) {
return std::distance(this->cbegin(), iter);
}
}
return npos;
}
size_type find_last_not_of(basic_string_ref s) const {
const_reverse_iterator iter = find_not_of(this->crbegin(), this->crend(), s);
return iter == this->crend() ? npos(this->size() - 1 - std::distance(this->crbegin(), iter));
}
size_type find_last_not_of(charT c) const {
for(const_reverse_iterator iter = this->crbegin() {
iter != this->crend(); ++iter)
if(!traits::eq(c, *iter)) {
return this->size() - 1 - std::distance(this->crbegin(), iter);
}
}
return npos;
}
private:
template <typename Iterator>
Iterator find_not_of(Iterator first, Iterator last, basic_string_ref s) const {
for(; first != last; ++first) {
if(0 == traits::find(s.ptr_, s.len_, *first)) {
return first;
}
}
return last;
}
const charT *ptr_;
std::size_t len_;
};
// Comparison operators
// Equality
template <typename charT, typename traits>
inline bool operator==(basic_string_ref<charT, traits> x, basic_string_ref<charT, traits> y) {
if(x.size() != y.size()) {
return false;
}
return x.compare(y) == 0;
}
template <typename charT, typename traits, typename Allocator>
inline bool operator==(basic_string_ref<charT, traits> x, const std::basic_string<charT, traits, Allocator> &y) {
return x == basic_string_ref<charT, traits>(y);
}
template <typename charT, typename traits, typename Allocator>
inline bool operator==(const std::basic_string<charT, traits, Allocator> &x, basic_string_ref<charT, traits> y) {
return basic_string_ref<charT, traits>(x) == y;
}
template <typename charT, typename traits>
inline bool operator==(basic_string_ref<charT, traits> x, const charT *y) {
return x == basic_string_ref<charT, traits>(y);
}
template <typename charT, typename traits>
inline bool operator==(const charT *x, basic_string_ref<charT, traits> y) {
return basic_string_ref<charT, traits>(x) == y;
}
// Inequality
template <typename charT, typename traits>
inline bool operator!=(basic_string_ref<charT, traits> x, basic_string_ref<charT, traits> y) {
if(x.size() != y.size()) {
return true;
}
return x.compare(y) != 0;
}
template <typename charT, typename traits, typename Allocator>
inline bool operator!=(basic_string_ref<charT, traits> x, const std::basic_string<charT, traits, Allocator> &y) {
return x != basic_string_ref<charT, traits>(y);
}
template <typename charT, typename traits, typename Allocator>
inline bool operator!=(const std::basic_string<charT, traits, Allocator> &x, basic_string_ref<charT, traits> y) {
return basic_string_ref<charT, traits>(x) != y;
}
template <typename charT, typename traits>
inline bool operator!=(basic_string_ref<charT, traits> x, const charT *y) {
return x != basic_string_ref<charT, traits>(y);
}
template <typename charT, typename traits>
inline bool operator!=(const charT *x, basic_string_ref<charT, traits> y) {
return basic_string_ref<charT, traits>(x) != y;
}
// Less than
template <typename charT, typename traits>
inline bool operator<(basic_string_ref<charT, traits> x, basic_string_ref<charT, traits> y) {
return x.compare(y) < 0;
}
template <typename charT, typename traits, typename Allocator>
inline bool operator<(basic_string_ref<charT, traits> x, const std::basic_string<charT, traits, Allocator> &y) {
return x < basic_string_ref<charT, traits>(y);
}
template <typename charT, typename traits, typename Allocator>
inline bool operator<(const std::basic_string<charT, traits, Allocator> &x, basic_string_ref<charT, traits> y) {
return basic_string_ref<charT, traits>(x) < y;
}
template <typename charT, typename traits>
inline bool operator<(basic_string_ref<charT, traits> x, const charT *y) {
return x < basic_string_ref<charT, traits>(y);
}
template <typename charT, typename traits>
inline bool operator<(const charT *x, basic_string_ref<charT, traits> y) {
return basic_string_ref<charT, traits>(x) < y;
}
// Greater than
template <typename charT, typename traits>
inline bool operator>(basic_string_ref<charT, traits> x, basic_string_ref<charT, traits> y) {
return x.compare(y) > 0;
}
template <typename charT, typename traits, typename Allocator>
inline bool operator>(basic_string_ref<charT, traits> x, const std::basic_string<charT, traits, Allocator> &y) {
return x > basic_string_ref<charT, traits>(y);
}
template <typename charT, typename traits, typename Allocator>
inline bool operator>(const std::basic_string<charT, traits, Allocator> &x, basic_string_ref<charT, traits> y) {
return basic_string_ref<charT, traits>(x) > y;
}
template <typename charT, typename traits>
inline bool operator>(basic_string_ref<charT, traits> x, const charT *y) {
return x > basic_string_ref<charT, traits>(y);
}
template <typename charT, typename traits>
inline bool operator>(const charT *x, basic_string_ref<charT, traits> y) {
return basic_string_ref<charT, traits>(x) > y;
}
// Less than or equal to
template <typename charT, typename traits>
inline bool operator<=(basic_string_ref<charT, traits> x, basic_string_ref<charT, traits> y) {
return x.compare(y) <= 0;
}
template <typename charT, typename traits, typename Allocator>
inline bool operator<=(basic_string_ref<charT, traits> x, const std::basic_string<charT, traits, Allocator> &y) {
return x <= basic_string_ref<charT, traits>(y);
}
template <typename charT, typename traits, typename Allocator>
inline bool operator<=(const std::basic_string<charT, traits, Allocator> &x, basic_string_ref<charT, traits> y) {
return basic_string_ref<charT, traits>(x) <= y;
}
template <typename charT, typename traits>
inline bool operator<=(basic_string_ref<charT, traits> x, const charT *y) {
return x <= basic_string_ref<charT, traits>(y);
}
template <typename charT, typename traits>
inline bool operator<=(const charT *x, basic_string_ref<charT, traits> y) {
return basic_string_ref<charT, traits>(x) <= y;
}
// Greater than or equal to
template <typename charT, typename traits>
inline bool operator>=(basic_string_ref<charT, traits> x, basic_string_ref<charT, traits> y) {
return x.compare(y) >= 0;
}
template <typename charT, typename traits, typename Allocator>
inline bool operator>=(basic_string_ref<charT, traits> x, const std::basic_string<charT, traits, Allocator> &y) {
return x >= basic_string_ref<charT, traits>(y);
}
template <typename charT, typename traits, typename Allocator>
inline bool operator>=(const std::basic_string<charT, traits, Allocator> &x, basic_string_ref<charT, traits> y) {
return basic_string_ref<charT, traits>(x) >= y;
}
template <typename charT, typename traits>
inline bool operator>=(basic_string_ref<charT, traits> x, const charT *y) {
return x >= basic_string_ref<charT, traits>(y);
}
template <typename charT, typename traits>
inline bool operator>=(const charT *x, basic_string_ref<charT, traits> y) {
return basic_string_ref<charT, traits>(x) >= y;
}
namespace detail {
template <class charT, class traits>
inline void sr_insert_fill_chars(std::basic_ostream<charT, traits> &os, std::size_t n) {
enum {
chunk_size = 8
};
charT fill_chars[chunk_size];
std::fill_n(fill_chars, static_cast<std::size_t>(chunk_size), os.fill());
for(; n >= chunk_size && os.good(); n -= chunk_size) {
os.write(fill_chars, static_cast<std::size_t>(chunk_size));
}
if(n > 0 && os.good()) {
os.write(fill_chars, n);
}
}
template <class charT, class traits>
void sr_insert_aligned(std::basic_ostream<charT, traits> &os, const basic_string_ref<charT, traits> &str) {
const std::size_t size = str.size();
const std::size_t alignment_size = static_cast<std::size_t>(os.width()) - size;
const bool align_left = (os.flags() & std::basic_ostream<charT, traits>::adjustfield) == std::basic_ostream<charT, traits>::left;
if(!align_left) {
detail::sr_insert_fill_chars(os, alignment_size);
if(os.good()) {
os.write(str.data(), size);
} else {
os.write(str.data(), size);
if(os.good()) {
detail::sr_insert_fill_chars(os, alignment_size);
}
}
}
} // namespace detail
// Inserter
template <class charT, class traits>
inline std::basic_ostream<charT, traits> & operator<<(std::basic_ostream<charT, traits> &os, const basic_string_ref<charT, traits> &str) {
if(os.good()) {
const std::size_t size = str.size();
const std::size_t w = static_cast<std::size_t>(os.width());
if(w <= size) {
os.write(str.data(), size);
} else {
detail::sr_insert_aligned(os, str);
}
os.width(0);
}
return os;
}
#if 0
// numeric conversions
//
// These are short-term implementations.
// In a production environment, I would rather avoid the copying.
//
inline int stoi (string_ref str, size_t* idx=0, int base=10) {
return std::stoi ( std::string(str), idx, base );
}
inline long stol (string_ref str, size_t* idx=0, int base=10) {
return std::stol ( std::string(str), idx, base );
}
inline unsigned long stoul (string_ref str, size_t* idx=0, int base=10) {
return std::stoul ( std::string(str), idx, base );
}
inline long long stoll (string_ref str, size_t* idx=0, int base=10) {
return std::stoll ( std::string(str), idx, base );
}
inline unsigned long long stoull (string_ref str, size_t* idx=0, int base=10) {
return std::stoull ( std::string(str), idx, base );
}
inline float stof (string_ref str, size_t* idx=0) {
return std::stof ( std::string(str), idx );
}
inline double stod (string_ref str, size_t* idx=0) {
return std::stod ( std::string(str), idx );
}
inline long double stold (string_ref str, size_t* idx=0) {
return std::stold ( std::string(str), idx );
}
inline int stoi (wstring_ref str, size_t* idx=0, int base=10) {
return std::stoi ( std::wstring(str), idx, base );
}
inline long stol (wstring_ref str, size_t* idx=0, int base=10) {
return std::stol ( std::wstring(str), idx, base );
}
inline unsigned long stoul (wstring_ref str, size_t* idx=0, int base=10) {
return std::stoul ( std::wstring(str), idx, base );
}
inline long long stoll (wstring_ref str, size_t* idx=0, int base=10) {
return std::stoll ( std::wstring(str), idx, base );
}
inline unsigned long long stoull (wstring_ref str, size_t* idx=0, int base=10) {
return std::stoull ( std::wstring(str), idx, base );
}
inline float stof (wstring_ref str, size_t* idx=0) {
return std::stof ( std::wstring(str), idx );
}
inline double stod (wstring_ref str, size_t* idx=0) {
return std::stod ( std::wstring(str), idx );
}
inline long double stold (wstring_ref str, size_t* idx=0) {
return std::stold ( std::wstring(str), idx );
}
#endif
}
#if 0
namespace std {
// Hashing
template<> struct hash<boost::string_ref>;
template<> struct hash<boost::u16string_ref>;
template<> struct hash<boost::u32string_ref>;
template<> struct hash<boost::wstring_ref>;
}
#endif
namespace std {
template <>
struct hash<boost::string_ref> {
std::size_t operator()(boost::string_ref ref) const {
return boost::hash_range(ref.begin(), ref.end());
}
};
}
#endif
| 41.157212
| 146
| 0.522171
|
FrostMineMC
|
15dea6dbf4474d8f5aa8654ed304d456ce48fc41
| 4,177
|
cpp
|
C++
|
src/ui/component/ScreenPreview.cpp
|
AkbarTheGreat/cszb-scoreboard
|
116199f8f0adb1fb0f837e31e804a5be27686dc7
|
[
"Apache-2.0"
] | 2
|
2020-02-09T03:21:28.000Z
|
2022-03-11T23:04:27.000Z
|
src/ui/component/ScreenPreview.cpp
|
AkbarTheGreat/cszb-scoreboard
|
116199f8f0adb1fb0f837e31e804a5be27686dc7
|
[
"Apache-2.0"
] | 34
|
2019-12-23T02:56:51.000Z
|
2022-03-14T21:24:11.000Z
|
src/ui/component/ScreenPreview.cpp
|
AkbarTheGreat/cszb-scoreboard
|
116199f8f0adb1fb0f837e31e804a5be27686dc7
|
[
"Apache-2.0"
] | null | null | null |
/*
ui/ScreenPreview.cpp: This class manages the thumbnail preview of a monitor
in the main window. In addition, the preview owns the ScreenPresenter which
displays to the actual monitor, dispatching the updated view when necessary.
Copyright 2019-2021 Tracy Beck
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 "ui/component/ScreenPreview.h"
#include "ScoreboardCommon.h" // for DEFAULT_BORDER_SIZE
#include "config.pb.h" // for DisplayInfo, ScreenSide
#include "config/DisplayConfig.h" // for DisplayConfig
#include "config/TeamConfig.h" // for TeamConfig
#include "config/swx/defs.h" // for wxALIGN_CENTER, wxALL, wxLEFT
#include "ui/component/ScreenPresenter.h" // for ScreenPresenter
#include "ui/component/ScreenText.h" // for ScreenText
#include "ui/frame/FrameManager.h" // for FrameManager
#include "util/ProtoUtil.h" // for ProtoUtil
namespace cszb_scoreboard {
const int BORDER_SIZE = 10;
const char *WELCOME_MESSAGE = "Hello";
const char *ERROR_MESSAGE = "NO\nSCREENS\nFOUND!";
const int PREVIEW_HEIGHT = 320;
ScreenPreview::ScreenPreview(swx::Panel *wx,
std::vector<proto::ScreenSide> sides,
int monitor_number, Singleton *singleton)
: Panel(wx) {
this->singleton = singleton;
std::string initial_text;
if (sides[0].error()) {
initial_text = ERROR_MESSAGE;
} else {
initial_text = WELCOME_MESSAGE;
}
screen_text = std::make_unique<ScreenText>(childPanel());
screen_text->setupPreview(initial_text, sides, previewSize(monitor_number));
thumbnail = std::make_unique<ScreenThumbnail>(childPanel(), monitor_number,
*screen_text);
if (!sides[0].error()) {
presenter = singleton->frameManager()->createScreenPresenter(monitor_number,
*screen_text);
}
positionWidgets();
}
void ScreenPreview::positionWidgets() {
addWidget(*thumbnail, 0, 0, DEFAULT_BORDER_SIZE,
wxLEFT | wxRIGHT | wxTOP | wxALIGN_CENTER);
addWidget(*screen_text, 1, 0, BORDER_SIZE, wxALL);
runSizer();
}
auto ScreenPreview::previewSize(int monitor_number) -> Size {
proto::DisplayInfo display_info =
singleton->displayConfig()->displayDetails(monitor_number);
float ratio = 4 / 3;
if (!display_info.side().error()) {
const proto::Rectangle &dimensions = display_info.dimensions();
ratio = static_cast<float>(dimensions.width()) / dimensions.height();
}
return Size{.width = static_cast<int>(PREVIEW_HEIGHT * ratio),
.height = PREVIEW_HEIGHT};
}
auto ScreenPreview::thumbnailWidget() -> ScreenText * {
return thumbnail.get();
}
void ScreenPreview::resetFromSettings(int monitor_number) {
screen_text->setSize(previewSize(monitor_number).toWx());
proto::ScreenSide side =
singleton->displayConfig()->displayDetails(monitor_number).side();
for (auto team : singleton->teamConfig()->singleScreenOrder()) {
if (ProtoUtil::sideContains(side, team)) {
proto::ScreenSide effective_side = ProtoUtil::teamSide(team);
screen_text->setBackground(
singleton->teamConfig()->teamColor(effective_side)[0],
effective_side);
}
}
screen_text->refresh();
}
void ScreenPreview::sendToPresenter(ScreenText *screen_text) {
presenter->setAll(*screen_text);
thumbnail->setAll(*screen_text);
}
void ScreenPreview::sendToPresenter() { sendToPresenter(screen_text.get()); }
void ScreenPreview::blackoutPresenter() {
presenter->blackout();
thumbnail->blackout();
}
} // namespace cszb_scoreboard
| 35.700855
| 80
| 0.691405
|
AkbarTheGreat
|
15e0f42745a0858f19b074fac64600a870f08ef5
| 1,276
|
hh
|
C++
|
src/ODBCStatement.hh
|
theconst/aodbc
|
d725f4b0231f63b394e51299f185b165a5ce8c95
|
[
"MIT"
] | 1
|
2019-05-14T10:52:33.000Z
|
2019-05-14T10:52:33.000Z
|
src/ODBCStatement.hh
|
theconst/aodbc
|
d725f4b0231f63b394e51299f185b165a5ce8c95
|
[
"MIT"
] | 6
|
2018-11-23T13:05:22.000Z
|
2019-02-05T06:56:47.000Z
|
src/ODBCStatement.hh
|
theconst/aodbc
|
d725f4b0231f63b394e51299f185b165a5ce8c95
|
[
"MIT"
] | null | null | null |
#ifndef ODBCSTATEMENT_HH
#define ODBCSTATEMENT_HH
#include <memory>
#include <cstring>
#include <nan.h>
#include "ODBCConnection.hh"
#include "ConnectionAwareStatement.hh"
#include "SafeUnwrap.hh"
namespace NC {
using NC::ConnectionAwareStatement;
using NC::SafeUnwrap;
class ODBCStatement final : public Nan::ObjectWrap {
public:
using value_type = ConnectionAwareStatement;
static NAN_MODULE_INIT(Init);
static std::shared_ptr<value_type> Unwrap(v8::Local<v8::Object> self) {
return SafeUnwrap<ODBCStatement>::Unwrap(self)->statement;
}
explicit ODBCStatement(
std::shared_ptr<UVMonitor<nanodbc::connection>> connection);
ODBCStatement(const ODBCStatement&) = delete;
ODBCStatement(ODBCStatement&&) = delete;
virtual ~ODBCStatement() = default;
private:
friend struct SafeUnwrap<ODBCStatement>;
static const char* js_class_name;
static Nan::Persistent<v8::FunctionTemplate> js_constructor;
static NAN_METHOD(JsNew);
static NAN_METHOD(JsQuery);
static NAN_METHOD(JsExecute);
static NAN_METHOD(JsPrepare);
static NAN_METHOD(JsClose);
static NAN_METHOD(JsOpen);
std::shared_ptr<ConnectionAwareStatement> statement;
};
} // namespace NC
#endif /* ODBCSTATEMENT_HH */
| 22.385965
| 75
| 0.731975
|
theconst
|
15e435b7999545f7bb28fa3fc8c700a837daa803
| 1,845
|
cpp
|
C++
|
source/modules/graphics3d/camera.cpp
|
NiklasReiche/yage
|
f4a2dfb2bf584884e45d2751da21a13c15631e98
|
[
"MIT"
] | null | null | null |
source/modules/graphics3d/camera.cpp
|
NiklasReiche/yage
|
f4a2dfb2bf584884e45d2751da21a13c15631e98
|
[
"MIT"
] | 2
|
2020-11-12T18:17:42.000Z
|
2020-11-12T18:18:05.000Z
|
source/modules/graphics3d/camera.cpp
|
NiklasReiche/yage
|
f4a2dfb2bf584884e45d2751da21a13c15631e98
|
[
"MIT"
] | null | null | null |
#include "camera.h"
namespace gl3d
{
Camera::Camera() {
this->position = gml::Vec3d(0.0);
this->rotation = gml::Quatd();
}
Camera::Camera(gml::Vec3d position, gml::Quatd rotation) {
this->position = position;
this->rotation = rotation;
}
void Camera::move(gml::Vec3d vector)
{
this->position += vector;
}
void Camera::moveTo(gml::Vec3d position)
{
this->position = position;
}
void Camera::moveForward(double amount)
{
this->position += rotation.getForward() * amount;
}
void Camera::moveBackward(double amount)
{
this->position -= rotation.getForward() * amount;
}
void Camera::moveLeft(double amount)
{
this->position -= rotation.getRight() * amount;
}
void Camera::moveRight(double amount)
{
this->position += rotation.getRight() * amount;
}
void Camera::rotate(gml::Quatd quaternion)
{
this->rotation *= quaternion;
}
void Camera::rotateTo(gml::Quatd rotation)
{
this->rotation = rotation;
}
void Camera::rotateYaw(double degree)
{
this->rotation = this->rotation * gml::Quatd::eulerAngle(gml::toRad(degree), 0, 0);
this->rotation = gml::normalize(this->rotation);
}
void Camera::rotatePitch(double degree)
{
this->rotation = this->rotation * gml::Quatd::eulerAngle(0, 0, gml::toRad(-degree));
this->rotation = gml::normalize(this->rotation);
}
void Camera::rotateRoll(double degree)
{
this->rotation = this->rotation * gml::Quatd::eulerAngle(0, gml::toRad(degree), 0);
this->rotation = gml::normalize(this->rotation);
}
void Camera::lookAt(gml::Vec3d target, double degree)
{
// TODO
}
gml::Mat4d Camera::getViewMatrix() const
{
return gml::Mat4d::lookAt(position, position + rotation.getForward(), rotation.getUp());
}
gml::Vec3d Camera::getPosition() const
{
return position;
}
gml::Quatd Camera::getRotation() const
{
return rotation;
}
}
| 22.777778
| 90
| 0.678591
|
NiklasReiche
|
15e49ea1c690e9ecceefb823aeaf52d9e131e04b
| 1,107
|
cpp
|
C++
|
test/unit/test_unique.cpp
|
kanzl/arbor
|
86b1eb065ac252bf0026de7cf7cbc6748a528254
|
[
"BSD-3-Clause"
] | 53
|
2018-10-18T12:08:21.000Z
|
2022-03-26T22:03:51.000Z
|
test/unit/test_unique.cpp
|
kanzl/arbor
|
86b1eb065ac252bf0026de7cf7cbc6748a528254
|
[
"BSD-3-Clause"
] | 864
|
2018-10-01T08:06:00.000Z
|
2022-03-31T08:06:48.000Z
|
test/unit/test_unique.cpp
|
kanzl/arbor
|
86b1eb065ac252bf0026de7cf7cbc6748a528254
|
[
"BSD-3-Clause"
] | 37
|
2019-03-03T16:18:49.000Z
|
2022-03-24T10:39:51.000Z
|
#include "../gtest.h"
#include <vector>
#include <list>
#include <utility>
#include "util/unique.hpp"
#include "./common.hpp"
namespace {
auto same_parity = [](auto a, auto b) { return a%2 == b%2; };
template <typename C, typename Eq = std::equal_to<>>
void run_unique_in_place_test(C data, const C& expected, Eq eq = Eq{}) {
arb::util::unique_in_place(data, eq);
EXPECT_TRUE(testing::seq_eq(data, expected));
}
template <typename C>
void run_tests() {
run_unique_in_place_test(C{}, C{});
run_unique_in_place_test(C{1, 3, 2}, C{1, 3, 2});
run_unique_in_place_test(C{1, 1, 1, 3, 2}, C{1, 3, 2});
run_unique_in_place_test(C{1, 3, 3, 3, 2}, C{1, 3, 2});
run_unique_in_place_test(C{1, 3, 2, 2, 2}, C{1, 3, 2});
run_unique_in_place_test(C{1, 1, 3, 2, 2}, C{1, 3, 2});
run_unique_in_place_test(C{3, 1, 3, 1, 1, 3, 1, 1}, C{3, 1, 3, 1, 3, 1});
run_unique_in_place_test(C{1, 2, 4, 1, 3, 1, 2, 1}, C{1, 2, 1, 2, 1}, same_parity);
}
}
TEST(unique_in_place, vector) {
run_tests<std::vector<int>>();
}
TEST(unique_in_place, list) {
run_tests<std::list<int>>();
}
| 27.675
| 87
| 0.6215
|
kanzl
|
15e8541340a8a7d2d0e9fa835b218b37d01aef0d
| 2,290
|
cpp
|
C++
|
examples/TestHttp.cpp
|
boboxxd/brynet
|
edda02b89e916140227cdd85d02c7a4e6ad32c20
|
[
"MIT"
] | null | null | null |
examples/TestHttp.cpp
|
boboxxd/brynet
|
edda02b89e916140227cdd85d02c7a4e6ad32c20
|
[
"MIT"
] | null | null | null |
examples/TestHttp.cpp
|
boboxxd/brynet
|
edda02b89e916140227cdd85d02c7a4e6ad32c20
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <string>
#include <mutex>
#include <condition_variable>
#include "SocketLibFunction.h"
#include "HttpService.h"
#include "HttpFormat.h"
#include "WebSocketFormat.h"
using namespace brynet;
using namespace brynet::net;
int main(int argc, char **argv)
{
auto server = HttpService::Create();
server->startListen(false, "0.0.0.0", 8080);
server->startWorkThread(ox_getcpunum());
std::string body = "<html>hello world </html>";
server->setEnterCallback([=](const HttpSession::PTR& session){
session->setHttpCallback([=](const HTTPParser& httpParser, const HttpSession::PTR& session){
HttpResponse response;
response.setBody(body);
std::string result = response.getResult();
session->send(result.c_str(), result.size(), std::make_shared<std::function<void(void)>>([session](){
session->postShutdown();
}));
});
});
std::cin.get();
sock fd = ox_socket_connect(false, "192.168.12.128", 8080);
server->addConnection(fd, [](const HttpSession::PTR& session){
HttpRequest request;
HttpQueryParameter parameter;
parameter.add("value", "123456");
if (false)
{
request.addHeadValue("Accept", "*/*");
request.setMethod(HttpRequest::HTTP_METHOD::HTTP_METHOD_PUT);
request.setUrl("/v2/keys/asea/aagee");
request.setContentType("application/x-www-form-urlencoded");
request.setBody(parameter.getResult());
}
else
{
request.setMethod(HttpRequest::HTTP_METHOD::HTTP_METHOD_GET);
request.setUrl("/v2/keys/asea/aagee");
request.setQuery(parameter.getResult());
}
std::string requestStr = request.getResult();
session->send(requestStr.c_str(), requestStr.size());
}, [](const HTTPParser& httpParser, const HttpSession::PTR& session){
//http response handle
std::cout << httpParser.getBody() << std::endl;
}, [](const HttpSession::PTR& session, WebSocketFormat::WebSocketFrameType, const std::string& payload){
//websocket frame handle
},[](const HttpSession::PTR&){
//ws connected handle
});
std::cin.get();
}
| 32.714286
| 113
| 0.619651
|
boboxxd
|
15eca8a7c30a23b1c7afba835f63f517f37323cf
| 3,312
|
cpp
|
C++
|
src/OTL/Core/OTL_Lambert.cpp
|
Jmbryan/OTL
|
7ffb7fa77e55a2eb7373e41fa345c90d344a9c44
|
[
"Zlib",
"MIT"
] | 7
|
2016-06-05T23:25:41.000Z
|
2020-01-24T07:46:31.000Z
|
src/OTL/Core/OTL_Lambert.cpp
|
Jmbryan/OTL
|
7ffb7fa77e55a2eb7373e41fa345c90d344a9c44
|
[
"Zlib",
"MIT"
] | null | null | null |
src/OTL/Core/OTL_Lambert.cpp
|
Jmbryan/OTL
|
7ffb7fa77e55a2eb7373e41fa345c90d344a9c44
|
[
"Zlib",
"MIT"
] | null | null | null |
#include <OTL/Core/LambertExponentialSinusoid.hpp>
#include <algorithm>
#include <math.h>
#include "mex.h"
void Lambert(double r1[],
double r2[],
double dt,
double dir,
double maxRev,
double mu,
double v1[],
double v2[])
{
otl::keplerian::LambertExponentialSinusoid lambert;
// Setup inputs
otl::Vector3d initialPosition(r1[0], r1[1], r1[2]);
otl::Vector3d finalPosition(r2[0], r2[1], r2[2]);
otl::Time timeDelta = otl::Time::Seconds(dt);
int maxRevolutions = static_cast<int>(maxRev);
otl::keplerian::Orbit::Direction orbitDirection = (dir > 0.0 ? otl::keplerian::Orbit::Direction::Prograde : otl::keplerian::Orbit::Direction::Retrograde);
// Setup outputs
otl::Vector3d initialVelocity(v1[0], v1[1], v1[2]);
otl::Vector3d finalVelocity(v2[0], v2[1], v2[2]);
// Evaluate Lambert's problem
lambert.Evaluate(initialPosition,
finalPosition,
timeDelta,
orbitDirection,
maxRevolutions,
mu,
initialVelocity,
finalVelocity);
// Convert outputs
v1[0] = initialVelocity.x;
v1[1] = initialVelocity.y;
v1[2] = initialVelocity.z;
v2[0] = finalVelocity.x;
v2[1] = finalVelocity.y;
v2[2] = finalVelocity.z;
}
void mexFunction(int numOutputs, mxArray *outputs[], int numInputs, const mxArray *inputs[] )
{
if (numInputs != 6)
{
mexErrMsgIdAndTxt( "MATLAB:Lambert:InvalidNumInputs","Six input arguments required.");
}
else if (numOutputs > 2)
{
mexErrMsgIdAndTxt( "MATLAB:Lambert:MaxNumOutputs", "Too many output arguments.");
}
size_t mR1 = 3;
size_t nR1 = 1;
size_t mR2 = 3;
size_t nR2 = 1;
//size_t mR1 = mxGetM(outputs[0]);
//size_t nR1 = mxGetN(outputs[0]);
//if (!mxIsDouble(outputs[0]) || mxIsComplex(outputs[0]) || std::max(mR1,nR1) != 3 || std::min(mR1,nR1) != 1)
//{
// mexErrMsgIdAndTxt( "MATLAB:Lambert:InvalidR1", "Lambert requires that R1 be a 3 x 1 vector.");
//}
//size_t mR2 = mxGetM(outputs[1]);
//size_t nR2 = mxGetN(outputs[1]);
//if (!mxIsDouble(outputs[1]) || mxIsComplex(outputs[1]) || std::max(mR2,nR2) != 3 || std::min(mR2,nR2) != 1)
//{
// mexErrMsgIdAndTxt( "MATLAB:Lambert:InvalidR2", "Lambert requires that R2 be a 3 x 1 vector.");
//}
//size_t mDt = mxGetM(outputs[2]);
//size_t nDt = mxGetN(outputs[2]);
//if (!mxIsDouble(outputs[2]) || mxIsComplex(outputs[2]) || std::max(mDt,nDt) != 1 || std::min(mDt,nDt) != 1)
//{
// mexErrMsgIdAndTxt( "MATLAB:Lambert:InvalidDt", "Lambert requires that dt be a scalar.");
//}
// Create a matrix for the return arguement
outputs[0] = mxCreateDoubleMatrix((mwSize)mR1, (mwSize)nR1, mxREAL);
outputs[1] = mxCreateDoubleMatrix((mwSize)mR2, (mwSize)nR2, mxREAL);
double *r1 = mxGetPr(inputs[0]);
double *r2 = mxGetPr(inputs[1]);
double *dt = mxGetPr(inputs[2]);
double *dir = mxGetPr(inputs[3]);
double *maxRev = mxGetPr(inputs[4]);
double *mu = mxGetPr(inputs[5]);
double *v1 = mxGetPr(outputs[0]);
double *v2 = mxGetPr(outputs[1]);
// Do the actual computation
Lambert(r1, r2, *dt, *dir, *maxRev, *mu, v1, v2);
}
| 32.470588
| 157
| 0.603563
|
Jmbryan
|
15ecc8001874f53a822c644e6e3080eca8357fae
| 380
|
hpp
|
C++
|
src/editor/Wizard/WizardPageRoom.hpp
|
tedvalson/NovelTea
|
f731951f25936cb7f5ff23e543e0301c1b5bfe82
|
[
"MIT"
] | null | null | null |
src/editor/Wizard/WizardPageRoom.hpp
|
tedvalson/NovelTea
|
f731951f25936cb7f5ff23e543e0301c1b5bfe82
|
[
"MIT"
] | null | null | null |
src/editor/Wizard/WizardPageRoom.hpp
|
tedvalson/NovelTea
|
f731951f25936cb7f5ff23e543e0301c1b5bfe82
|
[
"MIT"
] | null | null | null |
#ifndef WIZARDPAGEROOM_HPP
#define WIZARDPAGEROOM_HPP
#include <QWizardPage>
namespace Ui {
class WizardPageRoom;
}
class WizardPageRoom : public QWizardPage
{
Q_OBJECT
public:
explicit WizardPageRoom(QWidget *parent = 0);
~WizardPageRoom();
int nextId() const override;
bool validatePage() override;
private:
Ui::WizardPageRoom *ui;
};
#endif // WIZARDPAGEROOM_HPP
| 14.074074
| 46
| 0.763158
|
tedvalson
|
15ecd676044fd7d49145ff821d3453fced57a270
| 6,213
|
cpp
|
C++
|
src/ltrendertarget.cpp
|
hemantasapkota/lotech
|
46598a7c37dfd7cd424e2426564cc32533e1cfd6
|
[
"curl"
] | 9
|
2015-06-28T05:47:33.000Z
|
2021-06-29T13:35:48.000Z
|
src/ltrendertarget.cpp
|
hemantasapkota/lotech
|
46598a7c37dfd7cd424e2426564cc32533e1cfd6
|
[
"curl"
] | 5
|
2015-01-10T02:56:53.000Z
|
2018-07-27T03:21:14.000Z
|
src/ltrendertarget.cpp
|
hemantasapkota/lotech
|
46598a7c37dfd7cd424e2426564cc32533e1cfd6
|
[
"curl"
] | 3
|
2015-04-01T14:48:54.000Z
|
2015-11-12T11:52:50.000Z
|
/* Copyright (C) 2010-2013 Ian MacLarty. See Copyright Notice in lt.h. */
#include "lt.h"
LT_INIT_IMPL(ltrendertarget)
struct LTRenderTargetAction : LTAction {
LTRenderTarget *rt;
LTRenderTargetAction(LTSceneNode *node) : LTAction(node) {
rt = (LTRenderTarget*)node;
};
virtual bool doAction(LTfloat dt) {
if (rt->child != NULL) {
LTColor clear_color(0, 0, 0, 0);
rt->renderNode(rt->child, &clear_color);
}
return false;
}
};
LTRenderTarget::LTRenderTarget() {
minfilter = LT_TEXTURE_FILTER_LINEAR;
magfilter = LT_TEXTURE_FILTER_LINEAR;
depthbuf_enabled = false;
initialized = false;
add_action(new LTRenderTargetAction(this));
}
void LTRenderTarget::init(lua_State *L) {
LTTexturedNode::init(L);
if (vp_x1 == 0.0f && vp_x2 == 0.0f) {
vp_x1 = -1.0f;
vp_x2 = 1.0f;
}
if (vp_y1 == 0.0f && vp_y2 == 0.0f) {
vp_y1 = -1.0f;
vp_y2 = 1.0f;
}
if (wld_x1 == 0.0f && wld_x2 == 0.0f) {
LTfloat pix_w = ltGetPixelWidth();
LTfloat world_width = (LTfloat)width * pix_w;
wld_x1 = - world_width * 0.5f;
wld_x2 = world_width * 0.5f;
}
if (wld_y1 == 0.0f && wld_y2 == 0.0f) {
LTfloat pix_h = ltGetPixelHeight();
LTfloat world_height = (LTfloat)height * pix_h;
wld_y1 = - world_height * 0.5f;
wld_y2 = world_height * 0.5f;
}
// Compute dimensions of target texture (must be powers of 2).
tex_width = 64;
tex_height = 64;
while (tex_width < width) tex_width <<= 1;
while (tex_height < height) tex_height <<= 1;
// Generate texture.
texture_id = ltGenTexture();
ltBindTexture(texture_id);
ltTextureMinFilter(minfilter);
ltTextureMagFilter(magfilter);
ltTexImage(tex_width, tex_height, NULL);
setup();
initialized = true;
}
LTRenderTarget::~LTRenderTarget() {
ltDeleteFramebuffer(fbo);
ltDeleteTexture(texture_id);
}
void LTRenderTarget::renderNode(LTSceneNode *node, LTColor *clear_color) {
ltBindFramebuffer(fbo);
ltPrepareForRendering(
0, 0, width, height, vp_x1, vp_y1, vp_x2, vp_y2,
clear_color, depthbuf_enabled);
node->draw();
ltFinishRendering();
}
void LTRenderTarget::preContextChange() {
ltDeleteVertBuffer(texbuf);
ltDeleteVertBuffer(vertbuf);
ltDeleteFramebuffer(fbo);
}
void LTRenderTarget::postContextChange() {
setup();
}
static void setup_texture_coords(LTRenderTarget *target) {
// Set up texture coords for drawing.
int texel_w = LT_MAX_TEX_COORD / target->tex_width;
int texel_h = LT_MAX_TEX_COORD / target->tex_height;
LTtexcoord tex_right = target->width * texel_w;
LTtexcoord tex_top = target->height * texel_h;
target->tex_coords[0] = 0; target->tex_coords[1] = 0;
target->tex_coords[2] = tex_right; target->tex_coords[3] = 0;
target->tex_coords[4] = tex_right; target->tex_coords[5] = tex_top;
target->tex_coords[6] = 0; target->tex_coords[7] = tex_top;
ltBindVertBuffer(target->texbuf);
ltStaticVertBufferData(sizeof(LTtexcoord) * 8, target->tex_coords);
}
void LTRenderTarget::setup() {
// Generate frame buffer.
fbo = ltGenFramebuffer();
ltBindFramebuffer(fbo);
// Attach texture to frame buffer.
ltFramebufferTexture(texture_id);
if (!ltFramebufferComplete()) {
ltLog("Unable to create frame buffer of size %dx%d", tex_width, tex_height);
ltAbort();
}
texbuf = ltGenVertBuffer();
setup_texture_coords(this);
// Set up world vertices for drawing.
world_vertices[0] = wld_x1; world_vertices[1] = wld_y1;
world_vertices[2] = wld_x2; world_vertices[3] = wld_y1;
world_vertices[4] = wld_x2; world_vertices[5] = wld_y2;
world_vertices[6] = wld_x1; world_vertices[7] = wld_y2;
vertbuf = ltGenVertBuffer();
ltBindVertBuffer(vertbuf);
ltStaticVertBufferData(sizeof(LTfloat) * 8, world_vertices);
}
static LTint get_pwidth(LTObject *obj) {
return ((LTRenderTarget*)obj)->width;
}
static LTint get_pheight(LTObject *obj) {
return ((LTRenderTarget*)obj)->height;
}
static void set_pwidth(LTObject *obj, LTint val) {
LTRenderTarget *target = (LTRenderTarget*)obj;
target->width = val;
if (target->initialized) {
setup_texture_coords(target);
}
}
static void set_pheight(LTObject *obj, LTint val) {
LTRenderTarget *target = (LTRenderTarget*)obj;
target->height = val;
if (target->initialized) {
setup_texture_coords(target);
}
}
void LTRenderTarget::visit_children(LTSceneNodeVisitor *v, bool reverse) {
if (child != NULL) {
v->visit(child);
}
}
static LTObject *get_child(LTObject *obj) {
return ((LTRenderTarget*)obj)->child;
}
static void set_child(LTObject *obj, LTObject *val) {
LTRenderTarget *rt = (LTRenderTarget*)obj;
LTSceneNode *old_child =rt->child;
LTSceneNode *new_child = (LTSceneNode*)val;
if (old_child != NULL) {
old_child->exit(rt);
}
rt->child = new_child;
if (new_child != NULL) {
new_child->enter(rt);
}
}
LT_REGISTER_TYPE(LTRenderTarget, "lt.RenderTarget", "lt.TexturedNode")
LT_REGISTER_PROPERTY_OBJ(LTRenderTarget, child, LTSceneNode, get_child, set_child);
LT_REGISTER_PROPERTY_INT(LTRenderTarget, pwidth, &get_pwidth, &set_pwidth);
LT_REGISTER_PROPERTY_INT(LTRenderTarget, pheight, &get_pheight, &set_pheight);
LT_REGISTER_FIELD_FLOAT(LTRenderTarget, vp_x1)
LT_REGISTER_FIELD_FLOAT(LTRenderTarget, vp_y1)
LT_REGISTER_FIELD_FLOAT(LTRenderTarget, vp_x2)
LT_REGISTER_FIELD_FLOAT(LTRenderTarget, vp_y2)
LT_REGISTER_FIELD_FLOAT(LTRenderTarget, wld_x1)
LT_REGISTER_FIELD_FLOAT(LTRenderTarget, wld_y1)
LT_REGISTER_FIELD_FLOAT(LTRenderTarget, wld_x2)
LT_REGISTER_FIELD_FLOAT(LTRenderTarget, wld_y2)
static const LTEnumConstant RenderTarget_filter_enum_vals[] = {
{"linear", LT_TEXTURE_FILTER_LINEAR},
{"nearest", LT_TEXTURE_FILTER_NEAREST},
{NULL, 0}};
LT_REGISTER_FIELD_ENUM(LTRenderTarget, minfilter, LTTextureFilter, RenderTarget_filter_enum_vals)
LT_REGISTER_FIELD_ENUM(LTRenderTarget, magfilter, LTTextureFilter, RenderTarget_filter_enum_vals)
| 31.065
| 97
| 0.684371
|
hemantasapkota
|
15fb8f65da832fa3193cc1f2d2017dcbbea78dae
| 683
|
hpp
|
C++
|
code/poly/poly/detail/is_plain.hpp
|
andyprowl/virtual-concepts
|
ed3a5690c353b6998abcd3368a9b448f1bb2aa19
|
[
"Unlicense"
] | 59
|
2015-04-01T12:55:36.000Z
|
2021-06-22T02:46:20.000Z
|
include/poly/detail/is_plain.hpp
|
pyrtsa/poly
|
9fb84e93b0daba54977d8e26003b4c25eef41fb8
|
[
"BSL-1.0"
] | 1
|
2015-06-29T14:51:55.000Z
|
2015-06-29T16:40:26.000Z
|
code/poly/poly/detail/is_plain.hpp
|
andyprowl/virtual-concepts
|
ed3a5690c353b6998abcd3368a9b448f1bb2aa19
|
[
"Unlicense"
] | 5
|
2016-04-19T09:21:11.000Z
|
2021-12-29T09:48:09.000Z
|
// Copyright 2012 Pyry Jahkola.
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef POLY_DETAIL_IS_PLAIN_HPP_C59CAS1
#define POLY_DETAIL_IS_PLAIN_HPP_C59CAS1
#include <type_traits>
namespace poly {
namespace detail {
template <typename T> struct is_plain : std::true_type {};
template <typename T> struct is_plain<T &> : std::false_type {};
template <typename T> struct is_plain<T const> : std::false_type {};
template <typename T> struct is_plain<T const &> : std::false_type {};
} // detail
} // poly
#endif // POLY_DETAIL_IS_PLAIN_HPP_C59CAS1
| 29.695652
| 79
| 0.7306
|
andyprowl
|
c600a83e419db314f3f65b7ce2140dd333aff949
| 1,243
|
hpp
|
C++
|
include/msqlite/onerror.hpp
|
ricardocosme/msqlite
|
95af5b04831c7af449f87346301b6e26bf749e9f
|
[
"MIT"
] | 19
|
2020-08-18T21:25:05.000Z
|
2022-01-14T03:45:41.000Z
|
include/msqlite/onerror.hpp
|
ricardocosme/msqlite
|
95af5b04831c7af449f87346301b6e26bf749e9f
|
[
"MIT"
] | null | null | null |
include/msqlite/onerror.hpp
|
ricardocosme/msqlite
|
95af5b04831c7af449f87346301b6e26bf749e9f
|
[
"MIT"
] | null | null | null |
#pragma once
#include "msqlite/concepts.hpp"
#include "msqlite/detail/onerror.hpp"
#include "msqlite/pipes/detail/onerror.hpp"
namespace msqlite {
template<typename Expected,
typename F,
typename Ret =
std::invoke_result_t<F, typename std::remove_reference_t<Expected>::error_type>
>
void onerror(Expected&& exp,
F&& f,
std::enable_if_t<
std::is_same_v<Ret, void>>* = nullptr)
{
detail::onerror(std::forward<Expected>(exp), std::forward<F>(f));
}
template<typename Expected,
typename F,
typename Ret =
std::invoke_result_t<F, typename std::remove_reference_t<Expected>::error_type>
>
typename std::remove_reference_t<Expected>::value_type
onerror(Expected&& exp,
F&& f,
std::enable_if_t<
!std::is_same_v<Ret, void>>* = nullptr)
{
return detail::onerror(std::forward<Expected>(exp), std::forward<F>(f));
}
template<typename F>
inline auto onerror(F&& f)
{ return detail::onerror_wrapper<F>{std::forward<F>(f)}; }
template<typename F>
inline auto operator|(ValueOrError auto&& exp, detail::onerror_wrapper<F> o)
{ return detail::onerror(std::forward<decltype(exp)>(exp), std::move(o)); }
}
| 27.021739
| 88
| 0.650845
|
ricardocosme
|
c6023432b1993c925da8107686fd661efd4e3823
| 5,422
|
cc
|
C++
|
Modules/Geometry/src/irtkVector.cc
|
kevin-keraudren/IRTK
|
ce329b7f58270b6c34665dcfe9a6e941649f3b94
|
[
"Apache-2.0"
] | 3
|
2018-10-04T19:32:36.000Z
|
2021-09-02T07:37:30.000Z
|
Modules/Geometry/src/irtkVector.cc
|
kevin-keraudren/IRTK
|
ce329b7f58270b6c34665dcfe9a6e941649f3b94
|
[
"Apache-2.0"
] | null | null | null |
Modules/Geometry/src/irtkVector.cc
|
kevin-keraudren/IRTK
|
ce329b7f58270b6c34665dcfe9a6e941649f3b94
|
[
"Apache-2.0"
] | 4
|
2016-03-17T02:55:00.000Z
|
2018-02-03T05:40:05.000Z
|
/* The Image Registration Toolkit (IRTK)
*
* Copyright 2008-2015 Imperial College London
*
* 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 <irtkGeometry.h>
// -----------------------------------------------------------------------------
void irtkVector::PermuteRows(vector<int> idx)
{
irtkAssert(idx.size() <= static_cast<size_t>(_rows), "valid permutation");
for (int r1 = 0; r1 < static_cast<int>(idx.size()); ++r1) {
int r2 = idx[r1];
if (r2 == r1) continue;
swap(_vector[r1], _vector[r2]);
for (int r = r1 + 1; r < _rows; ++r) {
if (idx[r] == r1) {
swap(idx[r], idx[r1]);
break;
}
}
}
}
// -----------------------------------------------------------------------------
ostream& operator<< (ostream& os, const irtkVector &v)
{
// Write keyword
os << "irtkVector " << v._rows << endl;
#ifndef WORDS_BIGENDIAN
swap64((char *)v._vector, (char *)v._vector, v._rows);
#endif
// Write binary data
os.write((char *) &(v._vector[0]), v._rows*sizeof(double));
#ifndef WORDS_BIGENDIAN
swap64((char *)v._vector, (char *)v._vector, v._rows);
#endif
return os;
}
// -----------------------------------------------------------------------------
istream& operator>> (istream& is, irtkVector &v)
{
int rows;
char buffer[255];
// Read header
is >> buffer;
if (strcmp(buffer, "irtkVector") != 0) {
cerr << "irtkVector: Can't read file " << buffer << endl;
exit(1);
}
// Read size
is >> rows;
// Allocate matrix
v = irtkVector(rows);
// Read header, skip comments
is.get(buffer, 255);
is.clear();
is.seekg(1, ios::cur);
// Read matrix
is.read((char *) &(v._vector[0]), rows*sizeof(double));
#ifndef WORDS_BIGENDIAN
swap64((char *)v._vector, (char *)v._vector, v._rows);
#endif
return is;
}
// -----------------------------------------------------------------------------
irtkCofstream& operator<< (irtkCofstream& to, const irtkVector &v)
{
to.WriteAsChar("irtkVector", 11);
to.WriteAsInt(&v._rows, 1);
to.WriteAsDouble(v._vector, v._rows);
return to;
}
// -----------------------------------------------------------------------------
irtkCifstream& operator>> (irtkCifstream& from, irtkVector &v)
{
char keyword[11];
from.ReadAsChar(keyword, 11);
if (strncmp(keyword, "irtkVector", 11) != 0) {
keyword[10] = '\0'; // ensure it is null terminated
cerr << "irtkVector: Can't read file " << keyword << endl;
exit(1);
}
int rows = 0;
from.ReadAsInt(&rows, 1);
v.Initialize(rows);
from.ReadAsDouble(v._vector, rows);
return from;
}
// -----------------------------------------------------------------------------
void irtkVector::Print(irtkIndent indent) const
{
cout << indent << "irtkVector " << _rows << endl;
++indent;
cout.setf(ios::right);
cout.setf(ios::fixed);
cout.precision(4);
for (int i = 0; i < _rows; i++) {
cout << indent << setw(15) << _vector[i] << endl;
}
cout.precision(6);
cout.unsetf(ios::right);
cout.unsetf(ios::fixed);
}
// -----------------------------------------------------------------------------
void irtkVector::Read(const char *filename)
{
// Open file stream
ifstream from(filename, ios::in | ios::binary);
// Check whether file opened ok
if (!from) {
cerr << "irtkVector::Read: Can't open file " << filename << endl;
exit(1);
}
// Read vector
from >> *this;
}
// -----------------------------------------------------------------------------
void irtkVector::Write(const char *filename) const
{
// Open file stream
ofstream to(filename, ios::out | ios::binary);
// Check whether file opened ok
if (!to) {
cerr << "irtkVector::Write: Can't open file " << filename << endl;
exit(1);
}
// Write vector
to << *this;
}
#ifdef HAVE_EIGEN
// -----------------------------------------------------------------------------
void irtkVector::Vector2Eigen(Eigen::VectorXd &v) const
{
int i;
for (i = 0; i < _rows; i++) {
v(i) = _vector[i];
}
}
// -----------------------------------------------------------------------------
void irtkVector::Eigen2Vector(Eigen::VectorXd &v)
{
int i;
for (i = 0; i < _rows; i++) {
_vector[i] = v(i);
}
}
#endif
#ifdef HAVE_MATLAB
// -----------------------------------------------------------------------------
mxArray *irtkVector::MxArray() const
{
mxArray *m = mxCreateDoubleMatrix(_rows, 1, mxREAL);
memcpy(mxGetPr(m), _vector, _rows * sizeof(double));
return m;
}
// -----------------------------------------------------------------------------
bool irtkVector::WriteMAT(const char *fname, const char *varname) const
{
MATFile *fp = matOpen(fname, "w");
if (fp == NULL) return false;
mxArray *m = MxArray();
if (matPutVariable(fp, varname, m) != 0) {
mxDestroyArray(m);
matClose(fp);
return false;
}
mxDestroyArray(m);
return (matClose(fp) == 0);
}
#endif
| 25.218605
| 80
| 0.51789
|
kevin-keraudren
|
c604502ce5d2e28f5beeff5f5a72319404730e28
| 201
|
cpp
|
C++
|
Classical/WILLITST.cpp
|
ashoknallagalva/Coding
|
ef5056d207ba27d492684774209cc9163ec06dcc
|
[
"Apache-2.0"
] | null | null | null |
Classical/WILLITST.cpp
|
ashoknallagalva/Coding
|
ef5056d207ba27d492684774209cc9163ec06dcc
|
[
"Apache-2.0"
] | null | null | null |
Classical/WILLITST.cpp
|
ashoknallagalva/Coding
|
ef5056d207ba27d492684774209cc9163ec06dcc
|
[
"Apache-2.0"
] | null | null | null |
#include<iostream>
using namespace std;
int main(){
long long n,n1;
cin>>n;
n1=n-1;
if(n <=0)
cout<<"TAK";
else if(n>1 && (n & n1) == 0)
cout<<"TAK";
else
cout<<"NIE";
cout<<endl;
}
| 10.578947
| 30
| 0.532338
|
ashoknallagalva
|
c605ce6348d339ac530b7f2868846955c1d48e6e
| 524
|
cpp
|
C++
|
plugin_III/game_III/CPhone.cpp
|
Aleksandr-Belousov/plugin-sdk
|
5ca5f7d5575ae4138a4f165410a1acf0ae922260
|
[
"Zlib"
] | 1
|
2020-10-06T21:10:27.000Z
|
2020-10-06T21:10:27.000Z
|
plugin_III/game_III/CPhone.cpp
|
Aleksandr-Belousov/plugin-sdk
|
5ca5f7d5575ae4138a4f165410a1acf0ae922260
|
[
"Zlib"
] | null | null | null |
plugin_III/game_III/CPhone.cpp
|
Aleksandr-Belousov/plugin-sdk
|
5ca5f7d5575ae4138a4f165410a1acf0ae922260
|
[
"Zlib"
] | 3
|
2020-10-03T21:34:05.000Z
|
2020-12-19T01:52:38.000Z
|
/*
Plugin-SDK (Grand Theft Auto 3) source file
Authors: GTA Community. See more here
https://github.com/DK22Pac/plugin-sdk
Do not delete this comment block. Respect others' work!
*/
#include "CPhone.h"
PLUGIN_SOURCE_FILE
int ctor_addr(CPhone) = ADDRESS_BY_VERSION(0x42F620, 0x42F620, 0);
int ctor_gaddr(CPhone) = GLOBAL_ADDRESS_BY_VERSION(0x42F620, 0x42F620, 0);
int dtor_addr(CPhone) = ADDRESS_BY_VERSION(0x42F630, 0x42F630, 0);
int dtor_gaddr(CPhone) = GLOBAL_ADDRESS_BY_VERSION(0x42F630, 0x42F630, 0);
| 32.75
| 74
| 0.759542
|
Aleksandr-Belousov
|
c60605bb69e61a2afaf81db5c9677cc902c6149b
| 2,499
|
cpp
|
C++
|
source/utopian/core/renderer/Light.cpp
|
simplerr/Papageno
|
7ec1da40dc0459e26f5b9a8a3f72d8962237040d
|
[
"MIT"
] | 62
|
2020-11-06T17:29:24.000Z
|
2022-03-21T19:21:16.000Z
|
source/utopian/core/renderer/Light.cpp
|
simplerr/Papageno
|
7ec1da40dc0459e26f5b9a8a3f72d8962237040d
|
[
"MIT"
] | 134
|
2017-02-25T20:47:43.000Z
|
2022-03-14T06:54:58.000Z
|
source/utopian/core/renderer/Light.cpp
|
simplerr/Papageno
|
7ec1da40dc0459e26f5b9a8a3f72d8962237040d
|
[
"MIT"
] | 6
|
2021-02-19T07:20:19.000Z
|
2021-12-27T09:07:27.000Z
|
#include "core/renderer/Light.h"
#include "core/renderer/Renderer.h"
namespace Utopian
{
Light::Light()
{
// Default values
SetColor(glm::vec4(1.0f));
SetDirection(glm::vec3(1.0f, 1.0f, 0.0f));
SetAtt(0.4f, 0.86f, 0.0f);
SetRange(80.0f);
SetSpot(100.0f);
SetType(Utopian::LightType::DIRECTIONAL_LIGHT);
SetIntensity(1.0f, 1.0f, 1.0f);
}
Light::~Light()
{
}
SharedPtr<Utopian::Light> Light::Create()
{
SharedPtr<Light> instance(new Light());
instance->Initialize();
return instance;
}
void Light::Initialize()
{
Renderer::Instance().AddLight(this);
}
void Light::OnDestroyed()
{
Renderer::Instance().RemoveLight(this);
}
void Light::SetLightData(const Utopian::LightData& lightData)
{
mLightData = lightData;
}
const Utopian::LightData& Light::GetLightData()
{
// Todo: Is this ok?
mLightData.position = GetTransform().GetPosition();
return mLightData;
}
void Light::SetColor(const glm::vec4& color)
{
mLightData.color = color;
}
void Light::SetDirection(const glm::vec3& direction)
{
mLightData.direction = direction;
}
void Light::SetRange(float range)
{
mLightData.range = range;
}
void Light::SetSpot(float spot)
{
mLightData.spot = spot;
}
void Light::SetAtt(float a0, float a1, float a2)
{
mLightData.att = glm::vec3(a0, a1, a2);
}
void Light::SetType(Utopian::LightType type)
{
mLightData.type = (float)type;
}
void Light::SetIntensity(float ambient, float diffuse, float specular)
{
mLightData.intensity = glm::vec3(ambient, diffuse, specular);
}
const glm::vec3& Light::GetDirection() const
{
return mLightData.direction;
}
const glm::vec3& Light::GetAtt() const
{
return mLightData.att;
}
const glm::vec3& Light::GetIntensity() const
{
return mLightData.intensity;
}
Utopian::LightData* Light::GetLightDataPtr()
{
return &mLightData;
}
const Utopian::LightData& Light::GetLightData() const
{
return mLightData;
}
const glm::vec4& Light::GetColor() const
{
return mLightData.color;
}
float Light::GetRange() const
{
return mLightData.range;
}
float Light::GetSpot() const
{
return mLightData.spot;
}
int Light::GetType() const
{
return (int)mLightData.type;
}
}
| 18.931818
| 73
| 0.606242
|
simplerr
|
c61067c6a1f89bdfb41b317094d974f05cf86f03
| 1,080
|
cpp
|
C++
|
utils/stream/fstream.cpp
|
hardened-steel/lua
|
b468699f2d44c18394470eece597afb6c8ca53e5
|
[
"MIT"
] | null | null | null |
utils/stream/fstream.cpp
|
hardened-steel/lua
|
b468699f2d44c18394470eece597afb6c8ca53e5
|
[
"MIT"
] | null | null | null |
utils/stream/fstream.cpp
|
hardened-steel/lua
|
b468699f2d44c18394470eece597afb6c8ca53e5
|
[
"MIT"
] | null | null | null |
#include <boost/iostreams/device/mapped_file.hpp>
#include <system_error>
#include "fstream.hpp"
namespace bio = boost::iostreams;
namespace {
struct ROFileMapping
{
bio::mapped_file_source source;
public:
ROFileMapping(const std::filesystem::path& path)
: source(path.string())
{}
public:
const std::byte* data() const noexcept
{
return reinterpret_cast<const std::byte*>(source.data());
}
std::size_t size() const noexcept
{
return source.size();
}
};
}
namespace utils::stream {
ifstream::ifstream(const std::filesystem::path& path)
: mmap(ROFileMapping(path))
{
}
void ifstream::get(utils::buffer::view<std::byte>& view)
{
auto chunk = mmap.first(view.size());
view = view.first(chunk.size());
std::copy(chunk.begin(), chunk.end(), view.data());
}
utils::buffer::owner<const std::byte> ifstream::get()
{
constexpr auto chunk = 4u * 1024u * 1024u;
return mmap.first(chunk);
}
void ifstream::close()
{
mmap = buffer::owner<const std::byte>();
}
bool ifstream::closed() const noexcept
{
return mmap.size();
}
}
| 19.285714
| 60
| 0.669444
|
hardened-steel
|
c6167e60b42b318c4b953efc06758b6e3057d663
| 4,930
|
cpp
|
C++
|
filters/ImageViewer/imageviewer.cpp
|
InfiniteInteractive/LimitlessSDK
|
cb71dde14d8c59cbf8a1ece765989c5787fffefa
|
[
"MIT"
] | 3
|
2017-05-13T20:36:03.000Z
|
2021-07-16T17:23:01.000Z
|
filters/ImageViewer/imageviewer.cpp
|
InfiniteInteractive/LimitlessSDK
|
cb71dde14d8c59cbf8a1ece765989c5787fffefa
|
[
"MIT"
] | null | null | null |
filters/ImageViewer/imageviewer.cpp
|
InfiniteInteractive/LimitlessSDK
|
cb71dde14d8c59cbf8a1ece765989c5787fffefa
|
[
"MIT"
] | 2
|
2016-08-04T00:16:50.000Z
|
2017-09-07T14:50:03.000Z
|
#include "imageviewer.h"
#include "QtComponents/QtPluginView.h"
#include "Media/MediaPad.h"
#include "glView.h"
#include "Media/ImageSample.h"
#include <boost/foreach.hpp>
using namespace Limitless;
ImageViewer::ImageViewer(std::string name, SharedMediaFilter parent):
MediaAutoRegister(name, parent),
m_glView(nullptr),
frameCount(0)
{
}
ImageViewer::~ImageViewer()
{
}
void ImageViewer::attachViewer(ImageViewer *imageViewer)
{
GLWidget *glWidget=getGlWidget();
glWidget->attachViewer(imageViewer->getGlWidget());
}
void ImageViewer::removeViewer(ImageViewer *imageViewer)
{
GLWidget *glWidget=getGlWidget();
glWidget->removeViewer(imageViewer->getGlWidget());
}
bool ImageViewer::initialize(const Attributes &attributes)
{
m_imageSampleId=MediaSampleFactory::getTypeId("ImageSample");
m_gpuImageSampleId=MediaSampleFactory::getTypeId("GpuImageSample");
addSinkPad("Sink", "[{\"mime\":\"video/raw\"}, {\"mime\":\"image/raw\"}, {\"mime\":\"image/gpu\"}]");
addSourcePad("Source", "[{\"mime\":\"video/raw\"}, {\"mime\":\"image/raw\"}]");
Strings displayModes;
displayModes.push_back("All");
displayModes.push_back("Single");
addAttribute("displayMode", displayModes[0], displayModes);
addAttribute("currentImage", 0);
return true;
}
SharedPluginView ImageViewer::getView()
{
// return SharedPluginView();
if(m_view == SharedPluginView())
{
m_glView=new GlView();
m_view.reset(new QtPluginView(m_glView));
}
return m_view;
}
void ImageViewer::setSample(Limitless::SharedMediaSample sample)
{
if(m_glView != NULL)
m_glView->displaySample(sample);
}
bool ImageViewer::processSample(SharedMediaPad sinkPad, SharedMediaSample sample)
{
// OutputDebugStringA("Enter ImageViewer::processSample\n");
// sourcePad->processSample(sample);
// frameCount++;
// if(frameCount%10 == 0)
// {
// m_timeStamps.push(sample->timestamp());
//
// double frameRate=0;
// if((frameCount != 0) && !m_timeStamps.empty())
// frameRate=((double)frameCount*1000000000.0)/(m_timeStamps.back()-m_timeStamps.front());
// m_glView->setFrameRate(frameRate);
// }
// if(m_timeStamps.size() > 10)
// {
// m_timeStamps.pop();
// frameCount-=10;
// }
if(sample->isType(m_imageSampleId))
{
SharedImageSample imageSample=boost::dynamic_pointer_cast<ImageSample>(sample);
SharedGpuImageSample openGLSample=newSampleType<GpuImageSample>(m_gpuImageSampleId);
cl::Event event;
std::vector<cl::Event> waitEvents;
openGLSample->write(imageSample.get(), event);
waitEvents.push_back(event);
openGLSample->releaseOpenCl(event, &waitEvents);
event.wait();
if(m_glView!=NULL)
m_glView->displaySample(openGLSample);
}
else if(sample->isType(m_gpuImageSampleId))
{
SharedGpuImageSample gpuImageSample=boost::dynamic_pointer_cast<GpuImageSample>(sample);
SharedGpuImageSample openGLSample=newSampleType<GpuImageSample>(m_gpuImageSampleId);
cl::Event event;
std::vector<cl::Event> waitEvents;
openGLSample->copy(gpuImageSample.get(), event);
waitEvents.push_back(event);
openGLSample->releaseOpenCl(event, &waitEvents);
event.wait();
if(m_glView != NULL)
m_glView->displaySample(openGLSample);
}
pushSample(sample);
// OutputDebugStringA("Exit ImageViewer::processSample\n");
return true;
}
void ImageViewer::showControls(bool show)
{
if(show)
{
}
}
GLWidget *ImageViewer::getGlWidget()
{
return m_glView->getGlWidget();
}
IMediaFilter::StateChange ImageViewer::onReady()
{
return SUCCESS;
}
IMediaFilter::StateChange ImageViewer::onPaused()
{
return SUCCESS;
}
IMediaFilter::StateChange ImageViewer::onPlaying()
{
return SUCCESS;
}
bool ImageViewer::onAcceptMediaFormat(SharedMediaPad pad, SharedMediaFormat format)
{
if(pad->type() == MediaPad::SINK)
{
bool accept=false;
if(format->exists("mime"))
{
std::string mimeType=format->attribute("mime")->toString();
if(mimeType == "video/raw")
accept=true;
else if(mimeType == "image/raw")
accept=true;
else if(mimeType == "image/gpu")
accept=true;
}
return accept;
}
else
return true;
return false;
}
void ImageViewer::onLinkFormatChanged(SharedMediaPad pad, SharedMediaFormat format)
{
if(pad->type() == MediaPad::SINK)
{
if(!format->exists("mime"))
return;
if((format->attribute("mime")->toString() != "video/raw") &&
(format->attribute("mime")->toString() != "image/raw") &&
(format->attribute("mime")->toString() != "image/gpu"))
return;
MediaFormat sourceFormat(*format);
// sourceFormat.addAttribute("mime", format->attribute("mime")->toString());
// if(format->exists("width"))
// sourceFormat.addAttribute("width", format->attribute("width")->toString());
// if(format->exists("height"))
// sourceFormat.addAttribute("height", format->attribute("height")->toString());
SharedMediaPads sourcePads=getSourcePads();
BOOST_FOREACH(SharedMediaPad &sourcePad, sourcePads)
{
sourcePad->setFormat(sourceFormat);
}
}
}
| 23.14554
| 102
| 0.718864
|
InfiniteInteractive
|
72428b87e23b9c3115e19e00d464c91c26127592
| 25,880
|
cpp
|
C++
|
render-only-sample/rosumd/RosUmdResource.cpp
|
woachk/rpigpu
|
84176130663166964bdc5fec4a821a71420088fa
|
[
"MIT"
] | 14
|
2019-02-19T05:45:23.000Z
|
2021-08-20T12:56:41.000Z
|
render-only-sample/rosumd/RosUmdResource.cpp
|
driver1998/rpigpu
|
0da035aebf53a160b0740dda5bc7784fa33ceb3a
|
[
"MIT"
] | 3
|
2019-03-01T21:06:52.000Z
|
2020-11-07T17:20:38.000Z
|
render-only-sample/rosumd/RosUmdResource.cpp
|
driver1998/rpigpu
|
0da035aebf53a160b0740dda5bc7784fa33ceb3a
|
[
"MIT"
] | 5
|
2019-02-23T03:48:45.000Z
|
2020-01-19T18:56:16.000Z
|
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Resource implementation
//
// Copyright (C) Microsoft Corporation
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "precomp.h"
#include "RosUmdLogging.h"
#include "RosUmdResource.tmh"
#include "RosUmdDevice.h"
#include "RosUmdResource.h"
#include "RosUmdDebug.h"
#include "RosContext.h"
#include "Vc4Hw.h"
#include <memory>
RosUmdResource::RosUmdResource() :
m_signature(_SIGNATURE::CONSTRUCTED),
m_hKMAllocation(NULL)
{
}
RosUmdResource::~RosUmdResource()
{
assert(
(m_signature == _SIGNATURE::CONSTRUCTED) ||
(m_signature == _SIGNATURE::INITIALIZED));
// do nothing
}
void
RosUmdResource::Standup(
RosUmdDevice *pUmdDevice,
const D3D11DDIARG_CREATERESOURCE* pCreateResource,
D3D10DDI_HRTRESOURCE hRTResource)
{
UNREFERENCED_PARAMETER(pUmdDevice);
assert(m_signature == _SIGNATURE::CONSTRUCTED);
m_resourceDimension = pCreateResource->ResourceDimension;
m_mip0Info = *pCreateResource->pMipInfoList;
m_usage = pCreateResource->Usage;
m_bindFlags = pCreateResource->BindFlags;
m_mapFlags = pCreateResource->MapFlags;
m_miscFlags = pCreateResource->MiscFlags;
m_format = pCreateResource->Format;
m_sampleDesc = pCreateResource->SampleDesc;
m_mipLevels = pCreateResource->MipLevels;
m_arraySize = pCreateResource->ArraySize;
if (pCreateResource->pPrimaryDesc)
{
assert(
(pCreateResource->MiscFlags & D3DWDDM2_0DDI_RESOURCE_MISC_DISPLAYABLE_SURFACE) &&
(pCreateResource->BindFlags & D3D10_DDI_BIND_PRESENT) &&
(pCreateResource->pPrimaryDesc->ModeDesc.Width != 0));
m_isPrimary = true;
m_primaryDesc = *pCreateResource->pPrimaryDesc;
}
else
{
m_isPrimary = false;
ZeroMemory(&m_primaryDesc, sizeof(m_primaryDesc));
}
memset(&m_TileInfo, 0, sizeof(m_TileInfo));
CalculateMemoryLayout();
m_hRTResource = hRTResource;
// Zero out internal state
m_hKMResource = 0;
m_hKMAllocation = 0;
// Mark that the resource is not referenced by a command buffer (.i.e. null fence value)
m_mostRecentFence = RosUmdCommandBuffer::s_nullFence;
m_allocationListIndex = 0;
m_pData = nullptr;
m_pSysMemCopy = nullptr;
m_signature = _SIGNATURE::INITIALIZED;
}
void RosUmdResource::InitSharedResourceFromExistingAllocation (
const RosAllocationExchange* ExistingAllocationPtr,
D3D10DDI_HKMRESOURCE hKMResource,
D3DKMT_HANDLE hKMAllocation, // can this be a D3D10DDI_HKMALLOCATION?
D3D10DDI_HRTRESOURCE hRTResource
)
{
assert(m_signature == _SIGNATURE::CONSTRUCTED);
ROS_LOG_TRACE(
"Opening existing resource. "
"(ExistingAllocationPtr->m_hwWidth/HeightPixels = %u,%u "
"ExistingAllocationPtr->m_hwPitchBytes = %u, "
"ExistingAllocationPtr->m_hwSizeBytes = %u, "
"ExistingAllocationPtr->m_isPrimary = %d, "
"hRTResource = 0x%p, "
"hKMResource= 0x%x, "
"hKMAllocation = 0x%x)",
ExistingAllocationPtr->m_hwWidthPixels,
ExistingAllocationPtr->m_hwHeightPixels,
ExistingAllocationPtr->m_hwPitchBytes,
ExistingAllocationPtr->m_hwSizeBytes,
ExistingAllocationPtr->m_isPrimary,
hRTResource.handle,
hKMResource.handle,
hKMAllocation);
// copy members from the existing allocation into this object
RosAllocationExchange* basePtr = this;
*basePtr = *ExistingAllocationPtr;
// HW specific information calculated based on the fields above
CalculateMemoryLayout();
NT_ASSERT(
(m_hwLayout == ExistingAllocationPtr->m_hwLayout) &&
(m_hwWidthPixels == ExistingAllocationPtr->m_hwWidthPixels) &&
(m_hwHeightPixels == ExistingAllocationPtr->m_hwHeightPixels) &&
(m_hwFormat == ExistingAllocationPtr->m_hwFormat) &&
(m_hwPitchBytes == ExistingAllocationPtr->m_hwPitchBytes) &&
(m_hwSizeBytes == ExistingAllocationPtr->m_hwSizeBytes));
m_hRTResource = hRTResource;
m_hKMResource = hKMResource.handle;
m_hKMAllocation = hKMAllocation;
m_mostRecentFence = RosUmdCommandBuffer::s_nullFence;
m_allocationListIndex = 0;
m_pData = nullptr;
m_pSysMemCopy = nullptr;
m_signature = _SIGNATURE::INITIALIZED;
}
void
RosUmdResource::Teardown(void)
{
m_signature = _SIGNATURE::CONSTRUCTED;
// TODO[indyz]: Implement
}
void
RosUmdResource::ConstantBufferUpdateSubresourceUP(
UINT DstSubresource,
_In_opt_ const D3D10_DDI_BOX *pDstBox,
_In_ const VOID *pSysMemUP,
UINT RowPitch,
UINT DepthPitch,
UINT CopyFlags)
{
assert(DstSubresource == 0);
assert(pSysMemUP);
assert(m_bindFlags & D3D10_DDI_BIND_CONSTANT_BUFFER); // must be constant buffer
assert(m_resourceDimension == D3D10DDIRESOURCE_BUFFER);
BYTE *pSysMemCopy = m_pSysMemCopy;
UINT BytesToCopy = RowPitch;
if (pDstBox)
{
if (pDstBox->left < 0 ||
pDstBox->left > (INT)m_hwSizeBytes ||
pDstBox->left > pDstBox->right ||
pDstBox->right > (INT)m_hwSizeBytes)
{
return; // box is outside of buffer size. Nothing to copy.
}
pSysMemCopy += pDstBox->left;
BytesToCopy = (pDstBox->right - pDstBox->left);
}
else if (BytesToCopy == 0)
{
BytesToCopy = m_hwSizeBytes; // copy whole.
}
else
{
BytesToCopy = min(BytesToCopy, m_hwSizeBytes);
}
CopyMemory(pSysMemCopy, pSysMemUP, BytesToCopy);
return;
DepthPitch;
CopyFlags;
}
void
RosUmdResource::Map(
RosUmdDevice *pUmdDevice,
UINT subResource,
D3D10_DDI_MAP mapType,
UINT mapFlags,
D3D10DDI_MAPPED_SUBRESOURCE* pMappedSubRes)
{
assert(m_mipLevels <= 1);
assert(m_arraySize == 1);
UNREFERENCED_PARAMETER(subResource);
//
// Constant data is copied into command buffer, so there is no need for flushing
//
if (m_bindFlags & D3D10_DDI_BIND_CONSTANT_BUFFER)
{
pMappedSubRes->pData = m_pSysMemCopy;
pMappedSubRes->RowPitch = m_hwPitchBytes;
pMappedSubRes->DepthPitch = (UINT)m_hwSizeBytes;
return;
}
pUmdDevice->m_commandBuffer.FlushIfMatching(m_mostRecentFence);
D3DDDICB_LOCK lock;
memset(&lock, 0, sizeof(lock));
lock.hAllocation = m_hKMAllocation;
//
// TODO[indyz]: Consider how to optimize D3D10_DDI_MAP_WRITE_NOOVERWRITE
//
// D3DDDICB_LOCKFLAGS::IgnoreSync and IgnoreReadSync are used for
// D3D10_DDI_MAP_WRITE_NOOVERWRITE optimization and are only allowed
// for allocations that can resides in aperture segment.
//
// Currently ROS driver puts all allocations in local video memory.
//
SetLockFlags(mapType, mapFlags, &lock.Flags);
pUmdDevice->Lock(&lock);
if (lock.Flags.Discard)
{
assert(m_hKMAllocation != lock.hAllocation);
m_hKMAllocation = lock.hAllocation;
if (pUmdDevice->m_commandBuffer.IsResourceUsed(this))
{
//
// Indicate that the new allocation instance of the resource
// is not used in the current command batch.
//
m_mostRecentFence -= 1;
}
}
pMappedSubRes->pData = lock.pData;
m_pData = (BYTE*)lock.pData;
pMappedSubRes->RowPitch = m_hwPitchBytes;
pMappedSubRes->DepthPitch = (UINT)m_hwSizeBytes;
}
void
RosUmdResource::Unmap(
RosUmdDevice *pUmdDevice,
UINT subResource)
{
UNREFERENCED_PARAMETER(subResource);
if (m_bindFlags & D3D10_DDI_BIND_CONSTANT_BUFFER)
{
return;
}
m_pData = NULL;
D3DDDICB_UNLOCK unlock;
memset(&unlock, 0, sizeof(unlock));
unlock.NumAllocations = 1;
unlock.phAllocations = &m_hKMAllocation;
pUmdDevice->Unlock(&unlock);
}
VC4TileInfo RosUmdResource::FillTileInfo(UINT bpp)
{
// Provide detailed information about tile.
// Partial information about 4kB tiles, 1kB sub-tiles and micro-tiles for
// given bpp is precalculated.
// Values are used i.e. during converting bitmap to tiled texture
VC4TileInfo info = { 0 };
if (bpp == 8)
{
info.VC4_1kBSubTileWidthPixels = VC4_1KB_SUB_TILE_WIDTH_8BPP;
info.VC4_1kBSubTileHeightPixels = VC4_1KB_SUB_TILE_HEIGHT_8BPP;
info.VC4_MicroTileWidthBytes = VC4_MICRO_TILE_WIDTH_BYTES_8BPP;
info.vC4_MicroTileHeight = VC4_MICRO_TILE_HEIGHT_8BPP;
}
else if (bpp == 16)
{
info.VC4_1kBSubTileWidthPixels = VC4_1KB_SUB_TILE_WIDTH_16BPP;
info.VC4_1kBSubTileHeightPixels = VC4_1KB_SUB_TILE_HEIGHT_16BPP;
info.VC4_MicroTileWidthBytes = VC4_MICRO_TILE_WIDTH_BYTES_16BPP;
info.vC4_MicroTileHeight = VC4_MICRO_TILE_HEIGHT_16BPP;
}
else if (bpp == 32)
{
info.VC4_1kBSubTileWidthPixels = VC4_1KB_SUB_TILE_WIDTH_32BPP;
info.VC4_1kBSubTileHeightPixels = VC4_1KB_SUB_TILE_HEIGHT_32BPP;
info.VC4_MicroTileWidthBytes = VC4_MICRO_TILE_WIDTH_BYTES_32BPP;
info.vC4_MicroTileHeight = VC4_MICRO_TILE_HEIGHT_32BPP;
}
else
{
// We expect 8, 16 or 32 bpp only
assert(false);
}
// Calculate sub-tile width in bytes
info.VC4_1kBSubTileWidthBytes = info.VC4_1kBSubTileWidthPixels * (bpp / 8);
// 4kB tile consists of four 1kB sub-tiles
info.VC4_4kBTileWidthPixels = info.VC4_1kBSubTileWidthPixels * 2;
info.VC4_4kBTileHeightPixels = info.VC4_1kBSubTileHeightPixels * 2;
info.VC4_4kBTileWidthBytes = info.VC4_1kBSubTileWidthBytes * 2;
return info;
}
void
RosUmdResource::MapDxgiFormatToInternalFormats(DXGI_FORMAT format, _Out_ UINT &bpp, _Out_ RosHwFormat &rosFormat)
{
// Number of HW formats is limited, so some of DXGI formats must be emulated.
// For example, format DXGI_FORMAT_R8_UNORM is emulated with DXGI_FORMAT_R8G8B8A8_UNORM
// where G8, B8 are set to 0
//
switch (format)
{
case DXGI_FORMAT_R8G8B8A8_UNORM:
{
bpp = 32;
rosFormat = RosHwFormat::X8888;
}
break;
case DXGI_FORMAT_R8G8_UNORM:
{
bpp = 32;
rosFormat = RosHwFormat::X8888;
}
break;
case DXGI_FORMAT_R8_UNORM:
{
bpp = 32;
rosFormat = RosHwFormat::X8888;
}
break;
case DXGI_FORMAT_A8_UNORM:
{
bpp = 8;
rosFormat = RosHwFormat::X8;
}
break;
case DXGI_FORMAT_D24_UNORM_S8_UINT:
{
bpp = 8;
rosFormat = RosHwFormat::X8;
}
break;
case DXGI_FORMAT_D16_UNORM:
{
bpp = 8;
rosFormat = RosHwFormat::X8;
}
break;
default:
{
// Formats that are not on the list.
assert(false);
}
}
}
void
RosUmdResource::CalculateTilesInfo()
{
UINT bpp = 0;
// Provide information about hardware formats
MapDxgiFormatToInternalFormats(m_format, bpp, m_hwFormat);
// Prepare information about tiles
m_TileInfo = FillTileInfo(bpp);
m_hwWidthTilePixels = m_TileInfo.VC4_4kBTileWidthPixels;
m_hwHeightTilePixels = m_TileInfo.VC4_4kBTileHeightPixels;
m_hwWidthTiles = (m_hwWidthPixels + m_hwWidthTilePixels - 1) / m_hwWidthTilePixels;
m_hwHeightTiles = (m_hwHeightPixels + m_hwHeightTilePixels - 1) / m_hwHeightTilePixels;
m_hwWidthPixels = m_hwWidthTiles*m_hwWidthTilePixels;
m_hwHeightPixels = m_hwHeightTiles*m_hwHeightTilePixels;
UINT sizeTileBytes = m_hwWidthTilePixels * m_hwHeightTilePixels * (bpp/8);
m_hwSizeBytes = m_hwWidthTiles * m_hwHeightTiles * sizeTileBytes;
m_hwPitchBytes = 0;
}
void
RosUmdResource::SetLockFlags(
D3D10_DDI_MAP mapType,
UINT mapFlags,
D3DDDICB_LOCKFLAGS *pLockFlags)
{
switch (mapType)
{
case D3D10_DDI_MAP_READ:
pLockFlags->ReadOnly = 1;
break;
case D3D10_DDI_MAP_WRITE:
pLockFlags->WriteOnly = 1;
break;
case D3D10_DDI_MAP_READWRITE:
break;
case D3D10_DDI_MAP_WRITE_DISCARD:
pLockFlags->Discard = 1;
case D3D10_DDI_MAP_WRITE_NOOVERWRITE:
break;
}
if (mapFlags & D3D10_DDI_MAP_FLAG_DONOTWAIT)
{
pLockFlags->DonotWait = 1;
}
}
void
RosUmdResource::CalculateMemoryLayout(
void)
{
switch (m_resourceDimension)
{
case D3D10DDIRESOURCE_BUFFER:
{
m_hwLayout = RosHwLayout::Linear;
// TODO(bhouse) Need mapping code from resource DXGI format to hw format
m_hwFormat = RosHwFormat::X8;
m_hwWidthPixels = m_mip0Info.TexelWidth;
m_hwHeightPixels = m_mip0Info.TexelHeight;
assert(m_hwFormat == RosHwFormat::X8);
assert(m_hwHeightPixels == 1);
m_hwPitchBytes = m_hwSizeBytes = m_hwWidthPixels;
}
break;
case D3D10DDIRESOURCE_TEXTURE2D:
{
if (m_usage == D3D10_DDI_USAGE_DEFAULT)
{
m_hwLayout = RosHwLayout::Tiled;
}
else
{
m_hwLayout = RosHwLayout::Linear;
}
#if VC4
// TODO[indyz]: Enable tiled render target
if ((m_bindFlags & D3D10_DDI_BIND_RENDER_TARGET) ||
(m_bindFlags & D3D10_DDI_BIND_SHADER_RESOURCE))
{
m_hwLayout = RosHwLayout::Linear;
}
#endif
// TODO(bhouse) Need mapping code from resource DXGI format to hw format
if (m_bindFlags & D3D10_DDI_BIND_DEPTH_STENCIL)
{
m_hwFormat = RosHwFormat::D24S8;
}
else
{
m_hwFormat = RosHwFormat::X8888;
}
// Disable tiled format until issue #48 is fixed.
//
// Force tiled layout for given configuration only
/*if ((m_usage == D3D10_DDI_USAGE_DEFAULT) &&
(m_bindFlags == D3D10_DDI_BIND_SHADER_RESOURCE))
{
m_hwLayout = RosHwLayout::Tiled;
}*/
// Using system memory linear MipMap as example
m_hwWidthPixels = m_mip0Info.TexelWidth;
m_hwHeightPixels = m_mip0Info.TexelHeight;
#if VC4
// Align width and height to VC4_BINNING_TILE_PIXELS for binning
#endif
if (m_hwLayout == RosHwLayout::Linear)
{
m_hwWidthTilePixels = VC4_BINNING_TILE_PIXELS;
m_hwHeightTilePixels = VC4_BINNING_TILE_PIXELS;
m_hwWidthTiles = (m_hwWidthPixels + m_hwWidthTilePixels - 1) / m_hwWidthTilePixels;
m_hwHeightTiles = (m_hwHeightPixels + m_hwHeightTilePixels - 1) / m_hwHeightTilePixels;
m_hwWidthPixels = m_hwWidthTiles*m_hwWidthTilePixels;
m_hwHeightPixels = m_hwHeightTiles*m_hwHeightTilePixels;
m_hwSizeBytes = CPixel::ComputeMipMapSize(
m_hwWidthPixels,
m_hwHeightPixels,
m_mipLevels,
m_format);
m_hwPitchBytes = CPixel::ComputeSurfaceStride(
m_hwWidthPixels,
CPixel::BytesPerPixel(m_format));
}
else
{
CalculateTilesInfo();
}
}
break;
case D3D10DDIRESOURCE_TEXTURE1D:
case D3D10DDIRESOURCE_TEXTURE3D:
case D3D10DDIRESOURCE_TEXTURECUBE:
{
throw RosUmdException(DXGI_DDI_ERR_UNSUPPORTED);
}
break;
}
}
bool RosUmdResource::CanRotateFrom(const RosUmdResource* Other) const
{
// Make sure we're not rotating from ourself and that the resources
// are compatible (e.g. size, flags, ...)
return (this != Other) &&
(!m_pData && !Other->m_pData) &&
(!m_pSysMemCopy && !Other->m_pSysMemCopy) &&
(m_hRTResource != Other->m_hRTResource) &&
((m_hKMAllocation != Other->m_hKMAllocation) || !m_hKMAllocation) &&
((m_hKMResource != Other->m_hKMResource) || !m_hKMResource) &&
(m_resourceDimension == Other->m_resourceDimension) &&
(m_mip0Info == Other->m_mip0Info) &&
(m_usage == Other->m_usage) &&
(m_bindFlags == Other->m_bindFlags) &&
(m_bindFlags & D3D10_DDI_BIND_PRESENT) &&
(m_mapFlags == Other->m_mapFlags) &&
(m_miscFlags == Other->m_miscFlags) &&
(m_format == Other->m_format) &&
(m_sampleDesc == Other->m_sampleDesc) &&
(m_mipLevels == Other->m_mipLevels) &&
(m_arraySize == Other->m_arraySize) &&
(m_isPrimary == Other->m_isPrimary) &&
((m_primaryDesc.Flags & ~DXGI_DDI_PRIMARY_OPTIONAL) ==
(Other->m_primaryDesc.Flags & ~DXGI_DDI_PRIMARY_OPTIONAL)) &&
(m_primaryDesc.VidPnSourceId == Other->m_primaryDesc.VidPnSourceId) &&
(m_primaryDesc.ModeDesc == Other->m_primaryDesc.ModeDesc) &&
(m_primaryDesc.DriverFlags == Other->m_primaryDesc.DriverFlags) &&
(m_hwLayout == Other->m_hwLayout) &&
(m_hwWidthPixels == Other->m_hwWidthPixels) &&
(m_hwHeightPixels == Other->m_hwHeightPixels) &&
(m_hwFormat == Other->m_hwFormat) &&
(m_hwPitchBytes == Other->m_hwPitchBytes) &&
(m_hwSizeBytes == Other->m_hwSizeBytes) &&
(m_hwWidthTilePixels == Other->m_hwWidthTilePixels) &&
(m_hwHeightTilePixels == Other->m_hwHeightTilePixels) &&
(m_hwWidthTiles == Other->m_hwWidthTiles) &&
(m_hwHeightTiles == Other->m_hwHeightTiles);
}
// Converts R, RG or A buffer to 32 bpp (RGBA) buffer
void RosUmdResource::ConvertBufferto32Bpp(const BYTE *pSrc, BYTE *pDst, UINT srcBpp, UINT swizzleMask, UINT pSrcStride, UINT pDstStride)
{
for (UINT i = 0; i < m_mip0Info.TexelHeight; i++)
{
UINT32 *dstSwizzled = (UINT32*)pDst;
UINT dstIndex = 0;
for (UINT k = 0; k < m_mip0Info.TexelWidth*srcBpp; k += srcBpp)
{
UINT32 swizzledRGBA = 0;
// Gather individual color elements into one DWORD
for (UINT colorElement = 0; colorElement < srcBpp; colorElement++)
{
UINT32 currentColorElement = (UINT32)pSrc[k + colorElement];
// Move element to the right position
currentColorElement = currentColorElement << (colorElement << 3);
swizzledRGBA = swizzledRGBA | currentColorElement;
}
swizzledRGBA = swizzledRGBA << swizzleMask;
dstSwizzled[dstIndex] = swizzledRGBA;
dstIndex += 1;
}
pSrc += pSrcStride;
pDst += pDstStride;
}
}
// Converts texture to internal (HW friendly) representation
void RosUmdResource::ConvertInitialTextureFormatToInternal(const BYTE *pSrc, BYTE *pDst, UINT rowStride)
{
// HW supports only limited set of formats, so most of DXGI formats must
// be converted at the beginning.
UINT swizzleMask = 0;
UINT srcBpp = 0;
switch (m_format)
{
case DXGI_FORMAT_R8G8B8A8_UNORM:
{
// Do nothing
}
break;
case DXGI_FORMAT_R8_UNORM:
{
swizzleMask = 0;
srcBpp = 1;
}
break;
case DXGI_FORMAT_R8G8_UNORM:
{
swizzleMask = 0;
srcBpp = 2;
}
break;
case DXGI_FORMAT_A8_UNORM:
{
swizzleMask = 0;
srcBpp = 1;
}
break;
default:
{
assert(false);
}
break;
}
// For DXGI_FORMAT_R8G8B8A8_UNORM and DXGI_FORMAT_A8_UNORM we can do a simple copy or swizzle
// texture directly to memory.
if ((m_format == DXGI_FORMAT_R8G8B8A8_UNORM) || (m_format == DXGI_FORMAT_A8_UNORM))
{
if (m_hwLayout == RosHwLayout::Linear)
{
for (UINT i = 0; i < m_mip0Info.TexelHeight; i++)
{
memcpy(pDst, pSrc, rowStride);
pSrc += rowStride;
pDst += m_hwPitchBytes;
}
}
else
{
// Swizzle texture to HW format
ConvertBitmapTo4kTileBlocks(pSrc, pDst, rowStride);
}
}
else
{
// We have to convert other formats to internal format
if (m_hwLayout == RosHwLayout::Linear)
{
// Do a conversion directly to the locked allocation
ConvertBufferto32Bpp(pSrc, pDst, srcBpp, swizzleMask, rowStride, m_hwPitchBytes);
}
else
{
// For tiled layout, additional buffer is allocated. It is a
// conversion (temporary) buffer.
UINT pitch = m_mip0Info.TexelHeight * m_mip0Info.TexelWidth * 4;
auto temporary = std::unique_ptr<BYTE[]>{ new BYTE[pitch] };
UINT dstStride = m_mip0Info.TexelWidth * 4;
ConvertBufferto32Bpp(pSrc, temporary.get(), srcBpp, swizzleMask, rowStride, dstStride);
ConvertBitmapTo4kTileBlocks(temporary.get(), pDst, dstStride);
}
}
}
// Form 1k sub-tile block
BYTE *RosUmdResource::Form1kSubTileBlock(const BYTE *pInputBuffer, BYTE *pOutBuffer, UINT rowStride)
{
// 1k sub-tile block is formed from micro-tiles blocks
for (UINT h = 0; h < m_TileInfo.VC4_1kBSubTileHeightPixels; h += m_TileInfo.vC4_MicroTileHeight)
{
const BYTE *currentBufferPos = pInputBuffer + h*rowStride;
// Process row of 4 micro-tiles blocks
for (UINT w = 0; w < m_TileInfo.VC4_1kBSubTileWidthBytes; w+= m_TileInfo.VC4_MicroTileWidthBytes)
{
const BYTE *microTileOffset = currentBufferPos + w;
// Process micro-tile block
for (UINT t = 0; t < m_TileInfo.vC4_MicroTileHeight; t++)
{
memcpy(pOutBuffer, microTileOffset, m_TileInfo.VC4_MicroTileWidthBytes);
pOutBuffer += m_TileInfo.VC4_MicroTileWidthBytes;
microTileOffset += rowStride;
}
}
}
return pOutBuffer;
}
// Form one 4k tile block from pInputBuffer and store in pOutBuffer
BYTE *RosUmdResource::Form4kTileBlock(const BYTE *pInputBuffer, BYTE *pOutBuffer, UINT rowStride, BOOLEAN OddRow)
{
const BYTE *currentTileOffset = NULL;
UINT subTileHeightPixels = m_TileInfo.VC4_1kBSubTileHeightPixels;
UINT subTileWidthBytes = m_TileInfo.VC4_1kBSubTileWidthBytes;
if (OddRow)
{
// For even rows, process sub-tile blocks in ABCD order, where
// each sub-tile is stored in memory as follows:
//
// [C B]
// [D A]
//
// Get A block
currentTileOffset = pInputBuffer + rowStride * subTileHeightPixels + subTileWidthBytes;
pOutBuffer = Form1kSubTileBlock(currentTileOffset, pOutBuffer, rowStride);
// Get B block
currentTileOffset = pInputBuffer + subTileWidthBytes;
pOutBuffer = Form1kSubTileBlock(currentTileOffset, pOutBuffer, rowStride);
// Get C block
pOutBuffer = Form1kSubTileBlock(pInputBuffer, pOutBuffer, rowStride);
// Get D block
currentTileOffset = pInputBuffer + rowStride * subTileHeightPixels;
pOutBuffer = Form1kSubTileBlock(currentTileOffset, pOutBuffer, rowStride);
// return current position in out buffer
return pOutBuffer;
}
else
{
// For even rows, process sub-tile blocks in ABCD order, where
// each sub-tile is stored in memory as follows:
//
// [A D]
// [B C]
//
// Get A block
pOutBuffer = Form1kSubTileBlock(pInputBuffer, pOutBuffer, rowStride);
/// Get B block
currentTileOffset = pInputBuffer + rowStride * subTileHeightPixels;
pOutBuffer = Form1kSubTileBlock(currentTileOffset, pOutBuffer, rowStride);
// Get C Block
currentTileOffset = pInputBuffer + rowStride * subTileHeightPixels + subTileWidthBytes;
pOutBuffer = Form1kSubTileBlock(currentTileOffset, pOutBuffer, rowStride);
// Get D block
currentTileOffset = pInputBuffer + subTileWidthBytes;
pOutBuffer = Form1kSubTileBlock(currentTileOffset, pOutBuffer, rowStride);
// return current position in out buffer
return pOutBuffer;
}
}
// Form (CountX * CountY) tile blocks from InputBuffer and store them in OutBuffer
void RosUmdResource::ConvertBitmapTo4kTileBlocks(const BYTE *InputBuffer, BYTE *OutBuffer, UINT rowStride)
{
UINT CountX = m_hwWidthTiles;
UINT CountY = m_hwHeightTiles;
for (UINT k = 0; k < CountY; k++)
{
BOOLEAN oddRow = k & 1;
if (oddRow)
{
// Build 4k blocks from right to left for odd rows
for (int i = CountX - 1; i >= 0; i--)
{
const BYTE *blockStartOffset = InputBuffer + k * rowStride * m_TileInfo.VC4_4kBTileHeightPixels + i * m_TileInfo.VC4_4kBTileWidthBytes;
OutBuffer = Form4kTileBlock(blockStartOffset, OutBuffer, rowStride, oddRow);
}
}
else
{
// Build 4k blocks from left to right for even rows
for (UINT i = 0; i < CountX; i++)
{
const BYTE *blockStartOffset = InputBuffer + k * rowStride * m_TileInfo.VC4_4kBTileHeightPixels + i * m_TileInfo.VC4_4kBTileWidthBytes;
OutBuffer = Form4kTileBlock(blockStartOffset, OutBuffer, rowStride, oddRow);
}
}
}
}
| 30.482921
| 151
| 0.624652
|
woachk
|
7242b49d0ee029cf71b91f4e382305cc587391cd
| 21,379
|
cpp
|
C++
|
apps/pynq_mqttsn/app.cpp
|
Subarashi-tako/HLS_packet_processing
|
0e66c0779a279e8beb7c26c07818b98e5ab7f42f
|
[
"Apache-2.0"
] | 32
|
2019-07-15T12:42:33.000Z
|
2022-03-23T09:32:16.000Z
|
apps/pynq_mqttsn/app.cpp
|
twosigma/HLS_packet_processing
|
70d76ef66e194afd89438b1908e914d88642ce54
|
[
"Apache-2.0"
] | 3
|
2019-07-17T19:03:26.000Z
|
2021-01-18T22:59:02.000Z
|
apps/pynq_mqttsn/app.cpp
|
twosigma/HLS_packet_processing
|
70d76ef66e194afd89438b1908e914d88642ce54
|
[
"Apache-2.0"
] | 17
|
2019-11-04T05:38:22.000Z
|
2021-12-08T08:01:22.000Z
|
/*
Copyright (c) 2016-2018, Xilinx, Inc.
All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <stdint.h>
#include <stdlib.h>
#include <iostream>
#include <iomanip>
#include <string.h>
#include <stdio.h>
#include <tuple>
#include "eth_interface.h"
#include "app.h"
#include "ip.hpp"
#include "cam.h"
#include "allocator.h"
using namespace mqttsn;
using namespace arp;
const MACAddressT BROADCAST_MAC = 0xFFFFFFFFFFFF; // Broadcast MAC Address
const IPAddressT BROADCAST_IP = 0xFFFFFFFF; // Broadcast IP Address
//typedef hls::algorithmic_cam<256, 4, MacLookupKeyT, MacLookupValueT> ArpCacheT;
typedef hls::cam<4, IPAddressT, MACAddressT> ArpCacheT;
static STATS stats;
static bool verbose;
template<typename Payload>
void package_ethernet_frame(ap_uint<48> macAddress, ap_uint<32> ipAddress, ipv4_hdr<Payload> &ih, ap_uint<32> *buf, int &len, ArpCacheT &arpcache) {
//#pragma HLS inline all recursive
// Below is boilerplate
MACAddressT destMac;
bool hit;
IPAddressT destIP;
destIP = ih.destination.get();
// if ((dstIpAddress & regSubNetMask) == (regDefaultGateway & regSubNetMask) || dstIpAddress == 0xFFFFFFFF)
// // Address is on local subnet
// // Perform an ARP cache lookup on the destination.
// arpTableOut.write(dstIpAddress);
// else
// // Address is not on local subnet
// // Perform an ARP cache lookup on the default gateway.
// arpTableOut.write(regDefaultGateway);
if (destIP == BROADCAST_IP) { // If the destination is the IP broadcast address
hit = true;
destMac = BROADCAST_MAC;
} else {
IPAddressT destIP2 = (unsigned int)destIP;
hit = arpcache.get(destIP2, destMac);
}
// std::cout << destIP << " -> " << destMac << "\n";
// If the result is not found then fire a MAC request
if (!hit) {
ZeroPadding p;
arp_hdr<ZeroPadding> ah(p);
ethernet_hdr<arp_hdr<ZeroPadding> > h(ah);
// send ARP request
h.destinationMAC.set(BROADCAST_MAC);
h.sourceMAC.set(macAddress);
h.etherType.set(ethernet::ethernet_etherType::ARP); // ARP ethertype
h.p.op.set(arp_opCode::REQUEST);
h.p.hwsrc.set(macAddress);
h.p.psrc.set(ipAddress);
h.p.hwdst.set(0); // empty
h.p.pdst.set(destIP);
h.extend(64);
// for(int i = 0; i < h.p.data_length(); i++) {
// std::cout << std::hex << h.p.get<1>(i) << " ";
// }
// std::cout << "\n";
// for(int i = 0; i < p.data_length(); i++) {
// std::cout << std::hex << p.get<1>(i) << " ";
// }
// std::cout << "\n";
h.serialize(buf, len);
stats.arps_sent++;
// hexdump_ethernet_frame<4>(buf, len);
} else {
// Add ethernet header
// ethernet_hdr<ipv4_hdr<Payload> > eh(ih);
// eh.destinationMAC.set(destMac);
// eh.sourceMAC.set(macAddress);
// eh.etherType.set(ethernet::ethernet_etherType::IPV4);
// eh.serialize(buf, len);
// Copy workaround here to avoid HLS bug.
Packet p;
ipv4_hdr<Packet> ih2(p);
ethernet_hdr<ipv4_hdr<Packet> > eh(ih2);
eh.destinationMAC.set(destMac);
eh.sourceMAC.set(macAddress);
eh.etherType.set(ethernet::ethernet_etherType::IPV4);
copy_workaround_loop:
for(int i = 0; i < ih.data_length(); i++) {
#pragma HLS pipeline II=1
ih2.template set<1>(i,ih.template get<1>(i));
}
ih2.extend(ih.data_length());
eh.serialize(buf, len);
// hexdump_ethernet_frame<4>(buf, len);
}
// hexdump_ethernet_frame<4>(outBuf, len);
}
void create_mqtt_packet(mqttsn_hdr<mqttsn_publish_hdr<Packet> > & p, ap_uint<16> mID, ap_uint<16> t, int qos, bool dup) {
p.set<type>(mqttsn_type::PUBLISH);
ap_uint<8> f = 0;
f[2] = 0; // set 'cleanSession'
f(6,5) = qos; // set 'qos' field.
if(dup) {
f[7] = 1; // set the 'dup' field.
}
p.p.set<flags>(f);
p.p.set<topicID>(t); // FIXME
p.p.set<messageID>(mID);
p.set<length>(p.data_length());
}
void create_connack_packet(mqttsn_hdr<mqttsn_connack_hdr<Packet> > & p, mqttsn_hdr<mqttsn_connect_hdr<Packet> > & r) {
p.set<type>(mqttsn_type::CONNACK);
p.p.set<returnCode>(0);
p.set<length>(p.data_length());
}
void create_regack_packet(mqttsn_hdr<mqttsn_regack_hdr<Packet> > & p, mqttsn_hdr<mqttsn_register_hdr<Packet> > & r) {
p.set<type>(mqttsn_type::REGACK);
p.p.set<topicID>(r.p.get<topicID>()); // FIXME
p.p.set<messageID>(r.p.get<messageID>());
p.p.set<returnCode>(0);
p.set<length>(p.data_length());
}
void create_puback_packet(mqttsn_hdr<mqttsn_puback_hdr<Packet> > & p, mqttsn_hdr<mqttsn_publish_hdr<Packet> > & r) {
p.set<type>(mqttsn_type::PUBACK);
p.p.set<topicID>(r.p.get<topicID>()); // FIXME
p.p.set<messageID>(r.p.get<messageID>());
p.p.set<returnCode>(0);
p.set<length>(p.data_length());
}
template<typename Payload>
void create_test_packet(ap_uint<32> ipAddress, ap_uint<32> destIP, int destPort, int size, ipv4_hdr<udp_hdr<Payload> > &ih) {
ih.lengths.set(ih.data_length());
ih.protocol.set(ipv4_hdr<Payload>::ipv4_protocol::UDP);
ih.source.set(ipAddress);
ih.destination.set(destIP);
// Compute the IP checksum last so it has information from above.
ih.checksum.set(ih.compute_ip_checksum());
ih.p.sport.set(50000);
ih.p.dport.set(destPort);
ih.p.lengths.set(ih.p.data_length());
}
void test_source(int i, ap_uint<48> macAddress, ap_uint<32> ipAddress,
ap_uint<32> destIP, int destPort,
char *s, int sLen, ap_uint<16> messageID, ap_uint<16> topicID,
int qos, bool dup, int size,
ap_uint<32> *buf, int &len, ArpCacheT &arpcache) {
#pragma HLS inline all recursive
stats.packets_sent++;
if(dup) stats.dups_sent++;
Packet message;
mqttsn_publish_hdr<Packet> mp(message);
mqttsn_hdr<mqttsn_publish_hdr<Packet> > m(mp);
udp_hdr<mqttsn_hdr<mqttsn_publish_hdr<Packet> > > uh(m);
ipv4_hdr<udp_hdr<mqttsn_hdr<mqttsn_publish_hdr<Packet> > > > ih(uh);
set_message_loop:
for(int j = 0; j < sLen; j++) {
#pragma HLS pipeline II=1
message.set<1>(j, s[j]);
}
message.extend(sLen);
create_mqtt_packet(m, messageID, topicID, qos, dup);
create_test_packet(ipAddress, destIP, destPort, size, ih);
// std::cout << " length = " << ih.data_length() << " " << ih.p.data_length() << " " << ih.p.p.data_length() << " " << ih.p.p.p.data_length() << "\n";
package_ethernet_frame(macAddress, ipAddress, ih, buf, len, arpcache);
}
void handle_ethernet_frame(ap_uint<48> macAddress, ap_uint<32> ipAddress, ap_uint<32> *buf, int len, ArpCacheT &arpcache,
MessageBuffer<std::pair<ap_uint<16>, float>, 128 > &buffer) {
#pragma HLS inline all recursive
Packet p;
header<Packet, 40> ih(p);
ethernet_hdr<header<Packet, 40> > eh(ih);
eh.deserialize(buf, len);
MACAddressT destinationMAC = eh.destinationMAC.get();
if(destinationMAC != macAddress &&
destinationMAC != BROADCAST_MAC) {
#ifndef __SYNTHESIS__
//std::cout << "Dropping invalid MAC address: " << macAddress.toString(16, false) << " " << destinationMAC.toString(16, false) << "\n";
// hexdump_ethernet_frame<4>(buf, len);
#endif
// HACK return;
}
ap_uint<16> dmp_macType = eh.etherType.get();
if (dmp_macType == ethernet::ethernet_etherType::ARP) {
stats.arps_received++;
auto ah = parse_arp_hdr(ih);
// parsed_arp_hdr<header<Packet, 40> > ah(ih);
ap_uint<16> opCode = ah.get<op>();
MACAddressT hwAddrSrc = ah.get<hwsrc>();
IPAddressT protoAddrSrc = ah.get<psrc>();
IPAddressT protoAddrDst = ah.get<pdst>();
#ifndef __SYNTHESIS__
std::cout << "ARP " <<
protoAddrDst << " " <<
ipAddress << " " <<
"Opcode = " << opCode << " \n";
#endif
//We don't need to generate ARP replies in hardware.
if ((opCode == arp_opCode::REPLY) && (protoAddrDst == ipAddress)) {
ZeroPadding p;
arp_hdr<ZeroPadding> ah(p);
ethernet_hdr<arp_hdr<ZeroPadding> > h(ah);
h.destinationMAC.set(BROADCAST_MAC);
h.sourceMAC.set(macAddress);
h.etherType.set(ethernet::ethernet_etherType::ARP); // ARP ethertype
h.p.op.set(arp_opCode::REPLY);
h.p.hwsrc.set(macAddress);
h.p.psrc.set(ipAddress);
h.p.hwdst.set(hwAddrSrc);
h.p.pdst.set(protoAddrSrc);
h.extend(64);
}
// arpReplyMetaFifo.write(meta);
arpcache.insert(protoAddrSrc, hwAddrSrc);
#ifndef __SYNTHESIS__
std::cout << "insert: " << hwAddrSrc << " " << protoAddrSrc << "\n";
// std::cout << "arp cache = " << arpcache << "\n";
#endif
}
else if (dmp_macType == ethernet::ethernet_etherType::IPV4) {
#ifndef __SYNTHESIS__
//std::cout << "IPv4\n";
// << std::hex << protoAddrDst << " " << ipAddress << " " << "Opcode = " << opCode << " \n";
#endif
auto h = ipv4::parse_ipv4_hdr(ih);
if(h.get<ipv4::protocol>() == ipv4::ipv4_protocol::UDP) {
auto uh = ipv4::parse_udp_hdr(h.p);
if(uh.get<ipv4::sport>() == 1884) { // MQTTSN
auto mqh = parse_mqttsn_hdr(uh.p);
if(mqh.get<type>() == mqttsn_type::PUBLISH) {
auto mqpubh = parse_mqttsn_publish_hdr(mqh.p);
ap_uint<16> messageID = mqpubh.get<mqttsn::messageID>();
#ifndef __SYNTHESIS__
if(verbose) {
std::cout << "received MQTTSN PUBLISH ID=" << messageID << "\n";
}
#endif
if(buffer.is_allocated(messageID)) {
#ifndef __SYNTHESIS__
// std::cout << "clearing ID=" << messageID << "\n";
#endif
buffer.clear(messageID);
}
} else
if(mqh.get<type>() == mqttsn_type::PUBACK) {
stats.acks_received++;
auto mqpubh = parse_mqttsn_puback_hdr(mqh.p);
ap_uint<16> messageID = mqpubh.get<mqttsn::messageID>();
#ifndef __SYNTHESIS__
if(verbose) {
std::cout << "received MQTTSN PUBACK ID=" << messageID << "\n";
}
// for(int i = 0; i < eh.data_length(); i++) {
// std::cout << std::hex << eh.get<1>(i) << " ";
// }
// std::cout <<"\n";
// for(int i = 0; i < mqh.data_length(); i++) {
// std::cout << std::hex << mqh.get<1>(i) << " ";
// }
// std::cout <<"\n";
#endif
if(buffer.is_allocated(messageID)) {
#ifndef __SYNTHESIS__
// std::cout << "clearing ID=" << messageID << "\n";
#endif
stats.events_completed++;
buffer.clear(messageID);
}
}
}
}
// bool valid = check_ip_checksum(h, regIpAddress);
// if(valid) {
// detect_ip_protocol(h, ICMPdataOut, ICMPexpDataOut, UDPdataOut, TCPdataOut);
// }
} else {
// arpcache.sweep();
#ifndef __SYNTHESIS__
// std::cout << "Dropping unknown etherType " << dmp_macType.toString(16, false) << "\n";
#endif
}
}
// The input pointer here is a virtual address to the memory of the
// appropriate IOP
std::pair<float,bool> read_sensor_hw(volatile unsigned int *sensorvirt) {
// IOP mailbox constants
const unsigned int MAILBOX_OFFSET = 0xF000;
const unsigned int MAILBOX_SIZE = 0x1000;
const unsigned int MAILBOX_PY2IOP_CMD_OFFSET = 0xffc;
const unsigned int MAILBOX_PY2IOP_ADDR_OFFSET = 0xff8;
const unsigned int MAILBOX_PY2IOP_DATA_OFFSET = 0xf00;
// IOP mailbox commands
const unsigned int WRITE_CMD = 0;
const unsigned int READ_CMD = 1;
const unsigned int IOP_MMIO_REGSIZE = 0x10000;
volatile unsigned int *sensorcmd = (volatile unsigned int *)(sensorvirt + (MAILBOX_OFFSET + MAILBOX_PY2IOP_CMD_OFFSET)/4);
volatile unsigned int *sensordata = (volatile unsigned int *)(sensorvirt + MAILBOX_OFFSET/4);
if(*(sensorcmd) != 3) {
// If we're not in the process of doing a sensor read, then start a new read
// and output the current value (from some previous read)
*(sensorcmd) = 3;
} else {
// Otherwise wait around for a bit and see if the previous read finishes.
int i = 0;
while( *(sensorcmd) == 3) {
if(i++ > 10) {
//printf("timeout\n");
return std::make_pair(0.0f, false);
break;
}
// wait
}
}
// float f = *(sensordata);
// float f0 = f/100;
// float f1 = f0 * 10;
// int d1 = f1;
// float f2 = (f1-d1)*10;
// int d2 = f2;
// float f3 = (f2-d2)*10;
// int d3 = f3;
// char s[5];
// s[0] = '0' + d1;
// s[1] = '0' + d2;
// s[2] = '.';
// s[3] = '0' + d3;
// s[4] = 0;
// fprintf(stderr,"%s\n", s);
union single_cast {
float f;
uint32_t i;
};
union single_cast floatcast;
floatcast.i = *(sensordata);
return std::make_pair(floatcast.f, true);
}
void read_sensor_hw2(volatile unsigned int *sensorvirt, float &value, bool &valid) {
std::tie(value, valid) = read_sensor_hw(sensorvirt);
}
void get_ethernet_frame_direct(volatile unsigned int *networkIOPrecv, ap_uint<32>* buf, int* len, bool *b) {
#ifdef DEBUG
printf("Getting... ");
#endif
bool flag = (ap_uint<32>)networkIOPrecv[0x390] != 0;
int length = 0;
if(flag) {
length = (ap_uint<32>)networkIOPrecv[0x394];
for(int i = 0; i < (length+3)/4; i++) {
buf[i] = (ap_uint<32>)networkIOPrecv[0x200+i]; // HACK!
}
networkIOPrecv[0x390] = 0;
}
#ifdef DEBUG
printf("Got %d.\n", *len);
#endif
// if(*len < 0) {
// perror("Error receiving");
// }
*len = length;
*b = (length > 0);
}
void put_ethernet_frame_direct(ap_uint<32>* buf, int* len, volatile unsigned int *networkIOPsend) {
#ifdef DEBUG
printf("Putting %d... ", *len);
#endif
int length = *len;
if(length == 0) return;
int i = 0;
while((ap_uint<32>)networkIOPsend[0x190] != 0) {
// Spin
if(i++ > 1000000) {
printf("timeout\n");
break;
}
// wait
}
networkIOPsend[0x194] = length;
for(int i = 0; i < (length+3)/4; i++) {
networkIOPsend[i] = buf[i];
}
networkIOPsend[0x190] = 1;
#ifdef DEBUG
printf("Done.\n");
#endif
}
void process_packet(bool b, ap_uint<48> macAddress, ap_uint<32> ipAddress, ap_uint<32> inBuf[4096], int *inLen,
int i, ap_uint<32> destIP, int destPort, ap_uint<16> topicID, int qos, float message, bool validMessage,
int count, int size, ap_uint<32> outBuf[4096], int *outLen, bool reset, bool _verbose, STATS &_stats) {
#pragma HLS inline
static ArpCacheT arpcache;
static MessageBuffer<std::pair<ap_uint<16>, float>, 128 > buffer;
verbose=_verbose;
if(reset) {
stats.packets_received = 0;
stats.packets_sent = 0;
stats.arps_received = 0;
stats.arps_sent = 0;
stats.publishes_sent = 0;
stats.dups_sent = 0;
stats.acks_received = 0;
stats.events_completed = 0;
arpcache.clear();
buffer.clear();
}
*outLen = 0;
if(b) {
stats.packets_received++;
handle_ethernet_frame(macAddress, ipAddress, inBuf, *inLen, arpcache, buffer);
return;
}
int tLen;
int messageID;
bool dup = false;
if(validMessage) {
#pragma HLS inline all recursive
if(qos > 0) {
messageID = buffer.put(std::make_pair(topicID, message)); // Store the message so we can resend it.
#ifndef __SYNTHESIS__
if(verbose) {
std::cout << "putting ID=" << messageID << " size = " << buffer.size() << "\n";
}
#endif
if(messageID < 0) validMessage = false;
} else {
messageID = 0;
}
if(validMessage) {
stats.publishes_sent++;
if(qos == 0) {
// no acknowledge
stats.events_completed++;
}
}
}
if(!validMessage) {
#pragma HLS inline all recursive
// If we don't have a valid message, or we were unable to put it into
// the message buffer, then grab a message from the buffer and resend it.
std::tie(topicID, message) = buffer.get(messageID);
if(messageID >= 0) {
validMessage = true;
#ifndef __SYNTHESIS__
if(verbose) {
std::cout << "resending ID=" << messageID << "\n";
}
#endif
dup = true;
}
}
float f1 = message*0.1f;
int d1 = f1;
float f2 = (f1-d1)*10;
int d2 = f2;
float f3 = (f2-d2)*10;
int d3 = f3;
char s[4];
s[0] = '0' + d1;
s[1] = '0' + d2;
s[2] = '.';
s[3] = '0' + d3;
if(validMessage) {
test_source(i, macAddress, ipAddress, destIP, destPort,
s, 4, messageID, topicID,
qos, dup, size,
outBuf, tLen, arpcache);
*outLen = tLen;
}
_stats = stats;
}
void read_and_process_packet(bool b, ap_uint<48> macAddress, ap_uint<32> ipAddress,
int i, ap_uint<32> destIP, int destPort, ap_uint<16> topicID, int qos, float message, bool validMessage, volatile unsigned int *networkIOP,
int count, int size, bool reset, bool _verbose, int &events_completed, int &publishes_sent, int &packets_received, int &packets_sent) {
STATS _stats;
//#pragma HLS dataflow
// #pragma HLS interface m_axi offset=slave port=networkIOP bundle=networkIOP
// #pragma HLS interface s_axilite port=b
// #pragma HLS interface s_axilite port=macAddress
// #pragma HLS interface s_axilite port=ipAddress
// #pragma HLS interface s_axilite port=i`
// #pragma HLS interface s_axilite port=destIP
// #pragma HLS interface s_axilite port=destPort
// #pragma HLS interface s_axilite port=topicID
// #pragma HLS interface s_axilite port=qos
// #pragma HLS interface s_axilite port=message
// #pragma HLS interface s_axilite port=validMessage
// #pragma HLS interface s_axilite port=count
// #pragma HLS interface s_axilite port=size
// #pragma HLS interface s_axilite port=reset
// #pragma HLS interface s_axilite port=_verbose
// #pragma HLS interface s_axilite port=_stats
ap_uint<32> inBuf[4096];
int inLen;
ap_uint<32> outBuf[4096];
int outLen = 0;
get_ethernet_frame_direct(networkIOP, inBuf, &inLen, &b);
if(b) {
//printf("Got packet %d.\n", i);
//hexdump_ethernet_frame<16>(inBuf, 64);
} else {
// for(int i = 0; i < 16; i++) {
// inBuf[i] = 0;
// }
}
//printf("processing..\n");
if(size > 0) {
// printf("Input Before len = %d.\n", inLen);
// hexdump_ethernet_frame<16>(inBuf, 64);
// printf("Output Before len = %d.\n", outLen);
// hexdump_ethernet_frame<16>(outBuf, 64);
// Send a new packet if there is nothing waiting to be acknowledged.
//bool valid = _stats.publishes_sent < count; // (buffer.size() <= 200);
process_packet(b, macAddress, ipAddress, inBuf, &inLen, i, destIP, destPort, topicID, qos, message, validMessage, count, size, outBuf, &outLen, reset, verbose, _stats);
// printf("Input After len = %d.\n", inLen);
// hexdump_ethernet_frame<16>(inBuf, 64);
// printf("Output After len = %d.\n", outLen);
// hexdump_ethernet_frame<16>(outBuf, 64);
}
// if(count < 10000) break;
if(outLen > 512) {
// printf("Bogus result length %d\n", outLen);
} else {
if(outLen > 0) {
// printf("Sending packet %d with %d bytes.\n", i, outLen);
//hexdump_ethernet_frame<16>(outBuf, outLen);
// sleep(2);
put_ethernet_frame_direct(outBuf, &outLen, networkIOP);
}
}
events_completed = _stats.events_completed;
publishes_sent = _stats.publishes_sent;
packets_received = _stats.packets_received;
packets_sent = _stats.packets_sent;
}
| 36.358844
| 180
| 0.579681
|
Subarashi-tako
|
7245703451ebe5c08ff0ee12ddf5c27a006976f8
| 688
|
cpp
|
C++
|
bg96_pwr.cpp
|
bentcooke/pelion-ready-example-j
|
26d7b59e9affc9b2aa1c48cb7f26ffdc504b0a69
|
[
"Apache-2.0"
] | null | null | null |
bg96_pwr.cpp
|
bentcooke/pelion-ready-example-j
|
26d7b59e9affc9b2aa1c48cb7f26ffdc504b0a69
|
[
"Apache-2.0"
] | null | null | null |
bg96_pwr.cpp
|
bentcooke/pelion-ready-example-j
|
26d7b59e9affc9b2aa1c48cb7f26ffdc504b0a69
|
[
"Apache-2.0"
] | null | null | null |
#include "bg96_pwr.h"
#include "platform/mbed_debug.h"
#include "DigitalOut.h"
#include "platform/mbed_wait_api.h"
void avnet_bg96_power(void)
{
mbed::DigitalOut BG96_RESET(D7, 1);
mbed::DigitalOut BG96_PWRKEY(D10, 0);
// mbed::DigitalOut BG96_VBAT_3V8_EN(D11, 0);
// 3V8_EN is pulled to 5V and not connected as the reg is always enabled
// BG96_VBAT_3V8_EN = 1;
BG96_PWRKEY = 1;
wait_ms(300);
BG96_RESET = 0;
}
void init_cellular_power(void)
{
printf("%s\r\n", __FUNCTION__);
avnet_bg96_power();
wait_ms(5000); // wait for the modem to establish a connection
printf("done\n");
}
extern "C" void mbed_main(void)
{
printf("%s\r\n", __FUNCTION__);
init_cellular_power();
}
| 20.848485
| 73
| 0.72093
|
bentcooke
|
72477170207b6edd440fb7f02f9c0a5f1fc5e6bd
| 1,541
|
cpp
|
C++
|
project_booking_qt_gui/ProjectBookingQtUI/ProjectBookingQtUI/projectlabelreport.cpp
|
VBota1/project_booking
|
13337130e1294df43c243cf1df53edfa736c42b7
|
[
"MIT"
] | null | null | null |
project_booking_qt_gui/ProjectBookingQtUI/ProjectBookingQtUI/projectlabelreport.cpp
|
VBota1/project_booking
|
13337130e1294df43c243cf1df53edfa736c42b7
|
[
"MIT"
] | 2
|
2019-03-01T09:25:32.000Z
|
2019-03-01T09:26:08.000Z
|
project_booking_qt_gui/ProjectBookingQtUI/ProjectBookingQtUI/projectlabelreport.cpp
|
VBota1/project_booking
|
13337130e1294df43c243cf1df53edfa736c42b7
|
[
"MIT"
] | null | null | null |
#include "projectlabelreport.h"
ProjectLabelReport::ProjectLabelReport()
{
}
Result< QList<LabelReport> > ProjectLabelReport::fromQJsonDocument (QJsonDocument json)
{
QList<LabelReport> response;
if ( !json.isArray() )
{
Err< QList<LabelReport> > error("Data From backend is not a collection of elements.");
return error;
}
QJsonArray backendDataArray = json.array();
if (backendDataArray.isEmpty())
{
Err< QList<LabelReport> > error("There is no record in the backed response.");
return error;
}
uint arrayIndex = 0;
while (!backendDataArray.isEmpty())
{
LabelReport project = LabelReport();
QJsonObject arrayElement = backendDataArray.first().toObject();
Result< QString > fieldResponse = JSonParser::getStringFieldFromJsonArrayElement(arrayElement,"label",arrayIndex);
if (fieldResponse.hasError) {
Err< QList<LabelReport> > error(fieldResponse.err());
return error;
}
project.label = fieldResponse.ok();
fieldResponse = JSonParser::getStringFieldFromJsonArrayElement(arrayElement,"time_spent",arrayIndex);
if (fieldResponse.hasError) {
Err< QList<LabelReport> > error(fieldResponse.err());
return error;
}
project.time_spent = fieldResponse.ok();
response.append(project);
backendDataArray.removeFirst();
arrayIndex++;
}
Ok< QList<LabelReport> > success(response);
return success;
}
| 27.517857
| 123
| 0.64828
|
VBota1
|
7247b958b7dea78bb43cf5fc49654f9284067491
| 5,071
|
cpp
|
C++
|
src/server/scripts/Kalimdor/HallsOfOrigination/boss_ammunae.cpp
|
Arkania/ArkCORE
|
2484554a7b54be0b652f9dc3c5a8beba79df9fbf
|
[
"OpenSSL"
] | 42
|
2015-01-05T10:00:07.000Z
|
2022-02-18T14:51:33.000Z
|
src/server/scripts/Kalimdor/HallsOfOrigination/boss_ammunae.cpp
|
superllout/WOW
|
3d0eeb940cccf8ab7854259172c6d75a85ee4f7d
|
[
"OpenSSL"
] | null | null | null |
src/server/scripts/Kalimdor/HallsOfOrigination/boss_ammunae.cpp
|
superllout/WOW
|
3d0eeb940cccf8ab7854259172c6d75a85ee4f7d
|
[
"OpenSSL"
] | 31
|
2015-01-09T02:04:29.000Z
|
2021-09-01T13:20:20.000Z
|
/*
* Copyright (C) 2011 True Blood <http://www.trueblood-servers.com/>
* By Asardial
*
* Copyright (C) 2011 - 2013 ArkCORE <http://www.arkania.net/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "ScriptPCH.h"
#include "ScriptedCreature.h"
enum
{
SPELL_FLORAISON = 76043,
SPELL_CONSO = 75790,
NPC_FLORE = 40592,
};
#define MOB_TRASH RAND(40668,40669,40715)
enum Texts
{
SAY_AGGRO = 0,
SAY_EVENT = 1,
SAY_SLAY = 2,
SAY_DEATH = 3,
};
enum Events
{
EVENT_FLORAISON,
EVENT_CONSO,
EVENT_FLORE,
EVENT_SLAY,
EVENT_SUMMON
};
// Spawn des adds
const Position addSpawnLocations[2][3] =
{{
{-707.553467f, 207.223602f, 343.937927f, 0.00f},
{-707.664124f, 179.188828f, 343.938049f, 0.00f},
{-691.666321f, 193.310364f, 343.945282f, 0.00f},
},{
{-707.553467f, 207.223602f, 343.937927f, 0.00f},
{-707.664124f, 179.188828f, 343.938049f, 0.00f},
{-691.666321f, 193.310364f, 343.945282f, 0.00f},
}};
/*********
** Ammunae
**********/
class boss_ammunae: public CreatureScript
{
public:
boss_ammunae() : CreatureScript("boss_ammunae") { }
struct boss_ammunaeAI : public ScriptedAI
{
boss_ammunaeAI(Creature *pCreature) : ScriptedAI(pCreature), Summons(me)
{
pInstance = pCreature->GetInstanceScript();
}
InstanceScript* pInstance;
EventMap events;
SummonList Summons;
void Reset()
{
Summons.DespawnAll();
}
void EnterCombat(Unit* /*who*/)
{
Talk(SAY_AGGRO);
EnterPhaseGround();
}
void EnterPhaseGround()
{
events.ScheduleEvent(EVENT_FLORAISON, urand(6000,12000));
events.ScheduleEvent(EVENT_CONSO, urand(20000,32000));
events.ScheduleEvent(EVENT_SLAY, 10000);
events.ScheduleEvent(EVENT_SUMMON, 32000);
}
void JustDied(Unit* /*killer*/)
{
Talk(SAY_DEATH);
Summons.DespawnAll();
}
void JustSummoned(Creature *pSummoned)
{
pSummoned->SetInCombatWithZone();
if (Unit* pTarget = SelectTarget(SELECT_TARGET_RANDOM,0))
pSummoned->AI()->AttackStart(pTarget);
Summons.Summon(pSummoned);
}
void SummonedCreatureDespawn(Creature *summon)
{
Summons.Despawn(summon);
}
void UpdateAI(const uint32 diff)
{
if (!UpdateVictim())
return;
events.Update(diff);
while (uint32 eventId = events.ExecuteEvent())
{
switch(eventId)
{
case EVENT_FLORAISON:
if (Unit *pTarget = SelectTarget(SELECT_TARGET_RANDOM, 0))
DoCast(pTarget, SPELL_FLORAISON);
events.ScheduleEvent(EVENT_FLORAISON, urand(6000,12000));
return;
case EVENT_CONSO:
DoCast(SPELL_CONSO);
events.ScheduleEvent(EVENT_CONSO, urand(20000,32000));
return;
case EVENT_SLAY:
Talk(SAY_SLAY);
events.ScheduleEvent(EVENT_SLAY, 10000);
return;
case EVENT_SUMMON:
Talk(SAY_EVENT);
uint8 side = urand(0,1);
for(uint8 i=0; i<2 ; i++)
me->SummonCreature(MOB_TRASH, addSpawnLocations[side][i].GetPositionX(),addSpawnLocations[side][i].GetPositionY(),addSpawnLocations[side][i].GetPositionZ(), 0.0f, TEMPSUMMON_CORPSE_DESPAWN);
events.ScheduleEvent(EVENT_SUMMON, 32000);
return;
}
}
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI(Creature* pCreature) const
{
return new boss_ammunaeAI (pCreature);
}
};
/**********
** Bourgeon
***********/
class mob_flore: public CreatureScript
{
public:
mob_flore() : CreatureScript("mob_flore") { }
struct mob_floreAI : public ScriptedAI
{
mob_floreAI(Creature * pCreature) : ScriptedAI(pCreature) {}
uint32 event;
void reset()
{
event = 10000;
me->DespawnOrUnsummon(10000);
}
void UpdateAI(const uint32 diff)
{
if (!UpdateVictim())
return;
if (event<= diff)
{
me->SummonCreature(MOB_TRASH, me->GetPositionX(), me->GetPositionY(), me->GetPositionZ(), TEMPSUMMON_CORPSE_DESPAWN);
event = 10000;
} else event -= diff;
}
};
CreatureAI* GetAI(Creature* creature) const
{
return new mob_floreAI(creature);
}
};
void AddSC_boss_ammunae()
{
new boss_ammunae();
new mob_flore();
}
| 24.033175
| 199
| 0.628673
|
Arkania
|
724abc63caf71ca0d60d713942725a8c787d015a
| 356
|
cpp
|
C++
|
191.cpp
|
zhulk3/leetCode
|
0a1dbf8d58558ab9b05c5150aafa9e4344cec5bc
|
[
"Apache-2.0"
] | 2
|
2020-03-13T08:14:01.000Z
|
2021-09-03T15:27:49.000Z
|
191.cpp
|
zhulk3/LeetCode
|
0a1dbf8d58558ab9b05c5150aafa9e4344cec5bc
|
[
"Apache-2.0"
] | null | null | null |
191.cpp
|
zhulk3/LeetCode
|
0a1dbf8d58558ab9b05c5150aafa9e4344cec5bc
|
[
"Apache-2.0"
] | null | null | null |
class Solution {
public:
int hammingWeight(uint32_t n) {
stack<int>store;
int t=0;
while(n){
t=n%2;
n/=2;
store.push(t);
}
int cnt=0;
while(store.size()){
if(store.top()==1)
cnt++;
store.pop();
}
return cnt;
}
};
| 18.736842
| 35
| 0.379213
|
zhulk3
|
724dff2316ee7c984d6b145f5178ee646cf74f3f
| 203
|
cpp
|
C++
|
src/Aurora/Graphics/Material/Material.cpp
|
sjuhyeon/Aurora
|
9a6249bcac9beb0ac9792137b522160156e1dd71
|
[
"MIT"
] | 1
|
2022-02-23T17:42:51.000Z
|
2022-02-23T17:42:51.000Z
|
src/Aurora/Graphics/Material/Material.cpp
|
sjuhyeon/Aurora
|
9a6249bcac9beb0ac9792137b522160156e1dd71
|
[
"MIT"
] | null | null | null |
src/Aurora/Graphics/Material/Material.cpp
|
sjuhyeon/Aurora
|
9a6249bcac9beb0ac9792137b522160156e1dd71
|
[
"MIT"
] | null | null | null |
#include "Material.hpp"
namespace Aurora
{
void Material::BeginPass(DrawCallState &drawState, EPassType passType) const
{
drawState.Shader = GetShader(passType);
au_assert(drawState.Shader);
}
}
| 18.454545
| 77
| 0.758621
|
sjuhyeon
|
725b324234bc985b60546b1c98940487113f3ebd
| 3,245
|
cpp
|
C++
|
src/sdcard.cpp
|
mchresse/BeeIoT
|
9289b9408168ddc223b073083f28e9c0aece5ede
|
[
"BSD-3-Clause"
] | null | null | null |
src/sdcard.cpp
|
mchresse/BeeIoT
|
9289b9408168ddc223b073083f28e9c0aece5ede
|
[
"BSD-3-Clause"
] | null | null | null |
src/sdcard.cpp
|
mchresse/BeeIoT
|
9289b9408168ddc223b073083f28e9c0aece5ede
|
[
"BSD-3-Clause"
] | 1
|
2020-12-22T18:55:22.000Z
|
2020-12-22T18:55:22.000Z
|
//*******************************************************************
// SDCard.cpp
// from Project https://github.com/mchresse/BeeIoT
//
// Description:
// Contains main setup() and loop() routines for SPi based MM
//
//-------------------------------------------------------------------
// Copyright (c) 2019-present, Randolph Esser
// All rights reserved.
// This file is distributed under the BSD-3-Clause License
// The complete license agreement can be obtained at:
// https://github.com/mchresse/BeeIoT/license
// For used 3rd party open source see also Readme_OpenSource.txt
//*******************************************************************
// This Module contains code derived from
// -
//*******************************************************************
// For ESP32-DevKitC PIN Configuration look at BeeIoT.h
#include <Arduino.h>
#include <stdio.h>
#include <esp_log.h>
#include "sdkconfig.h"
//*******************************************************************
// SDCard SPI Library
//*******************************************************************
// Libraries for SD card
#include "FS.h"
#include "SD.h"
#include "SPI.h"
#include "beeiot.h" // provides all GPIO PIN configurations of all sensor Ports !
#include "sdcard.h" // detailed SD parameters
extern int issdcard; // =1 SDCard found
extern uint16_t lflags; // BeeIoT log flag field
//*******************************************************************
// SDCard SPI Setup Routine
//*******************************************************************
int setup_sd(int reentry) { // My SDCard Constructor
#ifdef SD_CONFIG
if(reentry >1) // No reset nor Deep Sleep Mode
return(issdcard); // nothing to do here
issdcard = 0;
uint8_t cardType = SD.cardType();
if(cardType == CARD_NONE) {
Serial.println(" SD: No SD card found");
return issdcard;
}
issdcard = 1; // we have an SDCard
BHLOG(LOGSD) Serial.print(" SD: SD Card Type: ");
if (cardType == CARD_MMC) {
BHLOG(LOGSD) Serial.print("MMC");
} else if (cardType == CARD_SD) {
BHLOG(LOGSD) Serial.print("SDSC");
} else if (cardType == CARD_SDHC) {
BHLOG(LOGSD) Serial.print("SDHC");
} else {
BHLOG(LOGSD) Serial.print("UNKNOWN");
}
uint64_t cardSize = SD.cardSize() / (1024 * 1024);
BHLOG(LOGSD) Serial.printf(" - Size: %lluMB\n", cardSize);
/*
if(lflags & LOGSD){ // lets get some Debug data from SDCard
listDir(SD, "/", 3); // list 3 directory levels from Root
// readFile(SD, SDLOGPATH);
// deleteFile(SD, SDLOGPATH); // for test purpose only
}
*/
// If the SDLOGPATH file doesn't exist
// Create a new file on the SD card and write the data label header line
File file = SD.open(SDLOGPATH);
if(!file) {
BHLOG(LOGSD) Serial.printf(" SD: File %s doesn't exist -> Creating new file + header...", SDLOGPATH);
writeFile(SD, SDLOGPATH, "Sample-ID, Date, Time, BeeHiveWeight, TempExtern, TempIntern, TempHive, TempRTC, ESP3V, Board5V, BattCharge, BattLoad, BattLevel\r\n");
} else {
BHLOG(LOGSD) Serial.printf(" SD: File %s found\n", SDLOGPATH);
file.close();
}
#endif // SD_CONFIG
return issdcard; // SD card port is initialized
} // end of setup_spi_sd()
// end of sdcard.cpp
| 33.802083
| 165
| 0.558089
|
mchresse
|
725dcc855b56eadd22fb3dd7e91b26f32daa71e5
| 1,562
|
cpp
|
C++
|
src/graphic/buffer/oni-graphic-buffer.cpp
|
sina-/granite
|
95b873bc545cd4925b5cea8c632a82f2d815be6e
|
[
"MIT"
] | 2
|
2019-08-01T09:18:49.000Z
|
2020-03-26T05:59:52.000Z
|
src/graphic/buffer/oni-graphic-buffer.cpp
|
sina-/granite
|
95b873bc545cd4925b5cea8c632a82f2d815be6e
|
[
"MIT"
] | null | null | null |
src/graphic/buffer/oni-graphic-buffer.cpp
|
sina-/granite
|
95b873bc545cd4925b5cea8c632a82f2d815be6e
|
[
"MIT"
] | 1
|
2020-03-26T05:59:53.000Z
|
2020-03-26T05:59:53.000Z
|
#include <oni-core/graphic/buffer/oni-graphic-buffer.h>
#include <cassert>
#include <GL/glew.h>
#include <oni-core/graphic/buffer/oni-graphic-buffer-data.h>
namespace oni {
Buffer::Buffer(const std::vector<oniGLfloat> &data,
oniGLsizeiptr dataSize,
oniGLenum usage) {
// Check for supported usages.
assert(usage == GL_STATIC_DRAW || usage == GL_DYNAMIC_DRAW);
// TODO: Check this comment on how to use OpenGL4.5 to create buffers:
// http://stackoverflow.com/a/21652955/558366
// Also this example can help:
// https://bcmpinc.wordpress.com/2015/10/07/copy-a-texture-to-screen/
// TODO: Another guide to using modern OpenGL that covers more than just
// Buffers: https://github.com/Fennec-kun/Guide-to-Modern-OpenGL-Functions
glGenBuffers(1, &mBufferID);
bind();
// Use the data for GL_STATIC_DRAW, otherwise pass nullptr for GL_DYNAMIC_DRAW.
auto dataPtr = !data.empty() ? data.data() : nullptr;
glBufferData(GL_ARRAY_BUFFER, dataSize, dataPtr, usage);
GLint actualSize{0};
glGetBufferParameteriv(GL_ARRAY_BUFFER, GL_BUFFER_SIZE, &actualSize);
if (dataSize != actualSize) {
glDeleteBuffers(1, &mBufferID);
assert(false);
}
unbind();
}
Buffer::~Buffer() { glDeleteBuffers(1, &mBufferID); }
void
Buffer::bind() { glBindBuffer(GL_ARRAY_BUFFER, mBufferID); }
void
Buffer::unbind() { glBindBuffer(GL_ARRAY_BUFFER, 0); }
}
| 33.956522
| 87
| 0.637004
|
sina-
|
72697fce20b6f887467adf0849e468730b4c39a2
| 6,813
|
cpp
|
C++
|
exp/src/zgeqrf-v3.cpp
|
shengren/magma-1.6.1
|
1adfee30b763e9491a869403e0f320b3888923b6
|
[
"BSD-3-Clause"
] | 21
|
2017-10-06T05:05:05.000Z
|
2022-03-13T15:39:20.000Z
|
exp/src/zgeqrf-v3.cpp
|
shengren/magma-1.6.1
|
1adfee30b763e9491a869403e0f320b3888923b6
|
[
"BSD-3-Clause"
] | 1
|
2017-03-23T00:27:24.000Z
|
2017-03-23T00:27:24.000Z
|
exp/src/zgeqrf-v3.cpp
|
shengren/magma-1.6.1
|
1adfee30b763e9491a869403e0f320b3888923b6
|
[
"BSD-3-Clause"
] | 4
|
2018-01-09T15:49:58.000Z
|
2022-03-13T15:39:27.000Z
|
/*
-- MAGMA (version 1.6.1) --
Univ. of Tennessee, Knoxville
Univ. of California, Berkeley
Univ. of Colorado, Denver
@date January 2015
@precisions normal z -> s d c
*/
#include "common_magma.h"
/* ------------------------------------------------------------
* MAGMA QR params
* --------------------------------------------------------- */
typedef struct {
/* Whether or not to restore upper part of matrix */
int flag;
/* Number of MAGMA threads */
int nthreads;
/* Block size for left side of matrix */
int nb;
/* Block size for right side of matrix */
int ob;
/* Block size for final factorization */
int fb;
/* Block size for multi-core factorization */
int ib;
/* Number of panels for left side of matrix */
int np_gpu;
/* Number of rows */
int m;
/* Number of columns */
int n;
/* Leading dimension */
int lda;
/* Matrix to be factorized */
cuDoubleComplex *a;
/* Storage for every T */
cuDoubleComplex *t;
/* Flags to wake up MAGMA threads */
volatile cuDoubleComplex **p;
/* Synchronization flag */
volatile int sync0;
/* One synchronization flag for each MAGMA thread */
volatile int *sync1;
/* Synchronization flag */
volatile int sync2;
/* Work space */
cuDoubleComplex *w;
} magma_qr_params;
extern "C" magma_int_t
magma_zgeqrf3(magma_context *cntxt, magma_int_t m, magma_int_t n,
cuDoubleComplex *a, magma_int_t lda, cuDoubleComplex *tau,
cuDoubleComplex *work, magma_int_t lwork,
magma_int_t *info )
{
/* -- MAGMA (version 1.6.1) --
Univ. of Tennessee, Knoxville
Univ. of California, Berkeley
Univ. of Colorado, Denver
@date January 2015
Purpose
=======
ZGEQRF computes a QR factorization of a COMPLEX_16 M-by-N matrix A:
A = Q * R.
Arguments
=========
M (input) INTEGER
The number of rows of the matrix A. M >= 0.
N (input) INTEGER
The number of columns of the matrix A. N >= 0.
A (input/output) COMPLEX_16 array, dimension (LDA,N)
On entry, the M-by-N matrix A.
On exit, the elements on and above the diagonal of the array
contain the min(M,N)-by-N upper trapezoidal matrix R (R is
upper triangular if m >= n); the elements below the diagonal,
with the array TAU, represent the orthogonal matrix Q as a
product of min(m,n) elementary reflectors (see Further
Details).
LDA (input) INTEGER
The leading dimension of the array A. LDA >= max(1,M).
TAU (output) COMPLEX_16 array, dimension (min(M,N))
The scalar factors of the elementary reflectors (see Further
Details).
WORK (workspace/output) COMPLEX_16 array, dimension (MAX(1,LWORK))
On exit, if INFO = 0, WORK(1) returns the optimal LWORK.
LWORK (input) INTEGER
The dimension of the array WORK. LWORK >= N*NB.
If LWORK = -1, then a workspace query is assumed; the routine
only calculates the optimal size of the WORK array, returns
this value as the first entry of the WORK array, and no error
message related to LWORK is issued.
INFO (output) INTEGER
= 0: successful exit
< 0: if INFO = -i, the i-th argument had an illegal value
Further Details
===============
The matrix Q is represented as a product of elementary reflectors
Q = H(1) H(2) . . . H(k), where k = min(m,n).
Each H(i) has the form
H(i) = I - tau * v * v'
where tau is a complex scalar, and v is a complex vector with
v(1:i-1) = 0 and v(i) = 1; v(i+1:m) is stored on exit in A(i+1:m,i),
and tau in TAU(i).
==================================================================== */
cuDoubleComplex c_one = MAGMA_Z_ONE;
int k, ib;
magma_qr_params *qr_params = (magma_qr_params *)cntxt->params;
*info = 0;
int lwkopt = n * qr_params->nb;
work[0] = MAGMA_Z_MAKE( (double)lwkopt, 0 );
long int lquery = (lwork == -1);
if (m < 0) {
*info = -1;
} else if (n < 0) {
*info = -2;
} else if (lda < max(1,m)) {
*info = -4;
} else if (lwork < max(1,n) && ! lquery) {
*info = -7;
}
if (*info != 0) {
magma_xerbla( __func__, -(*info) );
return MAGMA_ERR_ILLEGAL_VALUE;
}
else if (lquery)
return MAGMA_SUCCESS;
k = min(m,n);
if (k == 0) {
work[0] = c_one;
return MAGMA_SUCCESS;
}
int M=qr_params->nthreads*qr_params->ob;
int N=qr_params->nthreads*qr_params->ob;
if (qr_params->m > qr_params->n)
M = qr_params->m - (qr_params->n-qr_params->nthreads*qr_params->ob);
/* Use MAGMA code to factor left portion of matrix, waking up threads
along the way to perform updates on the right portion of matrix */
magma_zgeqrf2(cntxt, m, n - qr_params->nthreads * qr_params->ob,
a, lda, tau, work, lwork, info);
/* Wait for all update threads to finish */
for (k = 0; k < qr_params->nthreads; k++) {
while (qr_params->sync1[k] == 0) {
sched_yield();
}
}
/* Unzero upper part of each panel */
for (k = 0; k < qr_params->np_gpu-1; k++){
ib = min(qr_params->nb,(n-qr_params->nthreads*qr_params->ob)-qr_params->nb*k);
zq_to_panel(MagmaUpper, ib, a + k*qr_params->nb*lda + k*qr_params->nb, lda,
qr_params->w+qr_params->nb*qr_params->nb*k);
}
/* Use final blocking size */
qr_params->nb = qr_params->fb;
/* Flag MAGMA code to internally unzero upper part of each panel */
qr_params->flag = 1;
/* Use MAGMA code to perform final factorization if necessary */
if (qr_params->m > (qr_params->n - (qr_params->nthreads*qr_params->ob)))
if (M > (qr_params->m-(qr_params->n-(qr_params->ob*qr_params->nthreads))))
M = qr_params->m-(qr_params->n-(qr_params->ob*qr_params->nthreads));
magma_zgeqrf2(cntxt, M, N,
a + (n-qr_params->nthreads*qr_params->ob)*m+
(n-qr_params->nthreads*qr_params->ob), lda,
&tau[n-qr_params->nthreads*qr_params->ob],
work, lwork, info);
/* Prepare for next run */
for (k = 0; k < qr_params->np_gpu; k++) {
qr_params->p[k] = NULL;
}
for (k = 0; k < qr_params->nthreads; k++) {
qr_params->sync1[k] = 0;
}
/* Infrastructure for next run is not in place yet */
qr_params->sync0 = 0;
/* Signal update threads to get in position for next run */
qr_params->sync2 = 1;
}
| 29.240343
| 84
| 0.560986
|
shengren
|
726abf693125abb050ba077577573ecd6bc10d6e
| 4,650
|
cpp
|
C++
|
examples/SimpleOpenGL3/main.cpp
|
d3x0r/bullet3
|
7452ba37ec5639cbebd55503bad632653b4b25e7
|
[
"Zlib"
] | null | null | null |
examples/SimpleOpenGL3/main.cpp
|
d3x0r/bullet3
|
7452ba37ec5639cbebd55503bad632653b4b25e7
|
[
"Zlib"
] | null | null | null |
examples/SimpleOpenGL3/main.cpp
|
d3x0r/bullet3
|
7452ba37ec5639cbebd55503bad632653b4b25e7
|
[
"Zlib"
] | null | null | null |
#include "OpenGLWindow/SimpleOpenGL3App.h"
#include "Bullet3Common/b3Quaternion.h"
#include "Bullet3Common/b3CommandLineArgs.h"
#include "assert.h"
#include <stdio.h>
char* gVideoFileName = 0;
char* gPngFileName = 0;
static b3WheelCallback sOldWheelCB = 0;
static b3ResizeCallback sOldResizeCB = 0;
static b3MouseMoveCallback sOldMouseMoveCB = 0;
static b3MouseButtonCallback sOldMouseButtonCB = 0;
static b3KeyboardCallback sOldKeyboardCB = 0;
//static b3RenderCallback sOldRenderCB = 0;
float gWidth = 1024;
float gHeight = 768;
void MyWheelCallback(float deltax, float deltay)
{
if (sOldWheelCB)
sOldWheelCB(deltax,deltay);
}
void MyResizeCallback( float width, float height)
{
gWidth = width;
gHeight = height;
if (sOldResizeCB)
sOldResizeCB(width,height);
}
void MyMouseMoveCallback( float x, float y)
{
printf("Mouse Move: %f, %f\n", x,y);
if (sOldMouseMoveCB)
sOldMouseMoveCB(x,y);
}
void MyMouseButtonCallback(int button, int state, float x, float y)
{
if (sOldMouseButtonCB)
sOldMouseButtonCB(button,state,x,y);
}
void MyKeyboardCallback(int keycode, int state)
{
//keycodes are in examples/CommonInterfaces/CommonWindowInterface.h
//for example B3G_ESCAPE for escape key
//state == 1 for pressed, state == 0 for released.
// use app->m_window->isModifiedPressed(...) to check for shift, escape and alt keys
printf("MyKeyboardCallback received key:%c in state %d\n",keycode,state);
if (sOldKeyboardCB)
sOldKeyboardCB(keycode,state);
}
int main(int argc, char* argv[])
{
b3CommandLineArgs myArgs(argc,argv);
SimpleOpenGL3App* app = new SimpleOpenGL3App("SimpleOpenGL3App",gWidth,gHeight,true);
app->m_instancingRenderer->getActiveCamera()->setCameraDistance(13);
app->m_instancingRenderer->getActiveCamera()->setCameraPitch(0);
app->m_instancingRenderer->getActiveCamera()->setCameraTargetPosition(0,0,0);
sOldKeyboardCB = app->m_window->getKeyboardCallback();
app->m_window->setKeyboardCallback(MyKeyboardCallback);
sOldMouseMoveCB = app->m_window->getMouseMoveCallback();
app->m_window->setMouseMoveCallback(MyMouseMoveCallback);
sOldMouseButtonCB = app->m_window->getMouseButtonCallback();
app->m_window->setMouseButtonCallback(MyMouseButtonCallback);
sOldWheelCB = app->m_window->getWheelCallback();
app->m_window->setWheelCallback(MyWheelCallback);
sOldResizeCB = app->m_window->getResizeCallback();
app->m_window->setResizeCallback(MyResizeCallback);
myArgs.GetCmdLineArgument("mp4_file",gVideoFileName);
if (gVideoFileName)
app->dumpFramesToVideo(gVideoFileName);
myArgs.GetCmdLineArgument("png_file",gPngFileName);
char fileName[1024];
int textureWidth = 128;
int textureHeight = 128;
unsigned char* image=new unsigned char[textureWidth*textureHeight*4];
int textureHandle = app->m_renderer->registerTexture(image,textureWidth,textureHeight);
int cubeIndex = app->registerCubeShape(1,1,1);
b3Vector3 pos = b3MakeVector3(0,0,0);
b3Quaternion orn(0,0,0,1);
b3Vector3 color=b3MakeVector3(1,0,0);
b3Vector3 scaling=b3MakeVector3 (1,1,1);
app->m_renderer->registerGraphicsInstance(cubeIndex,pos,orn,color,scaling);
app->m_renderer->writeTransforms();
do
{
static int frameCount = 0;
frameCount++;
if (gPngFileName)
{
printf("gPngFileName=%s\n",gPngFileName);
sprintf(fileName,"%s%d.png",gPngFileName,frameCount++);
app->dumpNextFrameToPng(fileName);
}
//update the texels of the texture using a simple pattern, animated using frame index
for(int y=0;y<textureHeight;++y)
{
const int t=(y+frameCount)>>4;
unsigned char* pi=image+y*textureWidth*3;
for(int x=0;x<textureWidth;++x)
{
const int s=x>>4;
const unsigned char b=180;
unsigned char c=b+((s+(t&1))&1)*(255-b);
pi[0]=pi[1]=pi[2]=pi[3]=c;pi+=3;
}
}
app->m_renderer->activateTexture(textureHandle);
app->m_renderer->updateTexture(textureHandle,image);
float color[4] = {255,1,1,1};
app->m_primRenderer->drawTexturedRect(100,200,gWidth/2-50,gHeight/2-50,color,0,0,1,1,true);
app->m_instancingRenderer->init();
app->m_instancingRenderer->updateCamera();
app->m_renderer->renderScene();
app->drawGrid();
char bla[1024];
sprintf(bla,"Simple test frame %d", frameCount);
app->drawText(bla,10,10);
app->swapBuffer();
} while (!app->m_window->requestedExit());
delete app;
return 0;
}
| 29.807692
| 99
| 0.692258
|
d3x0r
|
7273ea551ee38c074e958f10eb84b4dbc5a5a4d5
| 3,269
|
cpp
|
C++
|
OpenTally-Gateway/src/oscserver/oscsubscriberlist.cpp
|
bjornvdh/opentally
|
e9189a94bc73bca1260f805719d12ea9cc3b5154
|
[
"Unlicense"
] | null | null | null |
OpenTally-Gateway/src/oscserver/oscsubscriberlist.cpp
|
bjornvdh/opentally
|
e9189a94bc73bca1260f805719d12ea9cc3b5154
|
[
"Unlicense"
] | null | null | null |
OpenTally-Gateway/src/oscserver/oscsubscriberlist.cpp
|
bjornvdh/opentally
|
e9189a94bc73bca1260f805719d12ea9cc3b5154
|
[
"Unlicense"
] | null | null | null |
#include <Arduino.h>
#include "messagebuffer/messagebuffer.h"
#include "oscserver/oscsubscriberlist.h"
#define OSC_MAX_SUBSCRIBER_COUNT 64
#define SUBSCRIBER_VALID_TIME 60000
static SemaphoreHandle_t subscriberMutex = xSemaphoreCreateMutex();
OSCSubscriber _subscribers[OSC_MAX_SUBSCRIBER_COUNT];
void subscriber_addOrRefresh(IPAddress remoteIp, OSCDeviceType deviceType, uint8_t tallyChannel)
{
uint8_t iOpenSlot = OSC_MAX_SUBSCRIBER_COUNT + 1;
uint8_t iSubscriberSlot = OSC_MAX_SUBSCRIBER_COUNT + 1;
uint32_t time = millis();
xSemaphoreTake(subscriberMutex, portMAX_DELAY);
for(uint8_t i = 0; i < OSC_MAX_SUBSCRIBER_COUNT; i++)
{
if(iOpenSlot > OSC_MAX_SUBSCRIBER_COUNT && _subscribers[i].ValidUntil < time)
{
// This slot is unused at the moment.
iOpenSlot = i;
}
if(_subscribers[i].RemoteIP == remoteIp)
{
// We already know this subscriber!
iSubscriberSlot = i;
break;
}
}
if(iSubscriberSlot > OSC_MAX_SUBSCRIBER_COUNT && iOpenSlot < OSC_MAX_SUBSCRIBER_COUNT)
{
iSubscriberSlot = iOpenSlot;
}
if(iSubscriberSlot < OSC_MAX_SUBSCRIBER_COUNT)
{
Serial.print("Storing subscriber in slot ");
Serial.print(iSubscriberSlot);
Serial.println(".");
_subscribers[iSubscriberSlot].RemoteIP = remoteIp;
_subscribers[iSubscriberSlot].DeviceType = deviceType;
_subscribers[iSubscriberSlot].TallyChannel = tallyChannel;
_subscribers[iSubscriberSlot].ValidUntil = time + SUBSCRIBER_VALID_TIME;
}
else
{
Serial.println("No open slot.");
}
xSemaphoreGive(subscriberMutex);
}
void subscriber_queuemessageforall(MessageStruct msgTemplate)
{
uint32_t time = millis();
xSemaphoreTake(subscriberMutex, portMAX_DELAY);
for(uint8_t i = 0; i < OSC_MAX_SUBSCRIBER_COUNT; i++)
{
if(_subscribers[i].ValidUntil >= time)
{
MessageStruct msg = msgTemplate;
msg.Recipient = _subscribers[i].RemoteIP;
messagebuffer_queuemessage(msg);
}
}
xSemaphoreGive(subscriberMutex);
}
void subscriber_queuemessageforchannel(MessageStruct msgTemplate, int channel)
{
uint32_t time = millis();
xSemaphoreTake(subscriberMutex, portMAX_DELAY);
for(uint8_t i = 0; i < OSC_MAX_SUBSCRIBER_COUNT; i++)
{
if(_subscribers[i].ValidUntil >= time && _subscribers[i].TallyChannel == channel)
{
MessageStruct msg = msgTemplate;
msg.Recipient = _subscribers[i].RemoteIP;
messagebuffer_queuemessage(msg);
}
}
xSemaphoreGive(subscriberMutex);
}
void subscriber_queuemessagefordevicetype(MessageStruct msgTemplate, OSCDeviceType deviceType)
{
uint32_t time = millis();
xSemaphoreTake(subscriberMutex, portMAX_DELAY);
for(uint8_t i = 0; i < OSC_MAX_SUBSCRIBER_COUNT; i++)
{
if(_subscribers[i].ValidUntil >= time && _subscribers[i].DeviceType == deviceType)
{
MessageStruct msg = msgTemplate;
msg.Recipient = _subscribers[i].RemoteIP;
messagebuffer_queuemessage(msg);
}
}
xSemaphoreGive(subscriberMutex);
}
| 32.04902
| 96
| 0.670236
|
bjornvdh
|
72746ac6cbf78e1253caa60a7dcf7f2e0474f9d1
| 7,194
|
cpp
|
C++
|
tests/instanced_rendering_without_ibo.cpp
|
ArmandBiteau/mncrft
|
248a3d887404a6df6ccc6d08119acb11b5dd402e
|
[
"MIT"
] | null | null | null |
tests/instanced_rendering_without_ibo.cpp
|
ArmandBiteau/mncrft
|
248a3d887404a6df6ccc6d08119acb11b5dd402e
|
[
"MIT"
] | null | null | null |
tests/instanced_rendering_without_ibo.cpp
|
ArmandBiteau/mncrft
|
248a3d887404a6df6ccc6d08119acb11b5dd402e
|
[
"MIT"
] | null | null | null |
#include <glimac/SDLWindowManager.hpp>
#include <GL/glew.h>
#include <glimac/Program.hpp>
#include <glimac/FilePath.hpp>
#include <glimac/Image.hpp>
#include <iostream>
#include <cmath>
#include <vector>
using namespace glimac;
struct Vertex2DUV {
glm::vec2 position;
glm::vec2 texture;
Vertex2DUV(){}
Vertex2DUV(glm::vec2 position, glm::vec2 texture):
position(position), texture(texture) {}
};
glm::mat3 translate(float tx, float ty) {
return glm::mat3(
glm::vec3(1, 0, 0),
glm::vec3(0, 1, 0),
glm::vec3(tx, ty, 1)
);
};
glm::mat3 scale(float sx, float sy) {
return glm::mat3(
glm::vec3(sx, 0, 0),
glm::vec3(0, sy, 0),
glm::vec3(0, 0, 1));
};
glm::mat3 rotate(float degree) {
float radian = degree * (3.14/180);
return glm::mat3(
glm::vec3(cos(radian) , sin(radian), 0),
glm::vec3(-sin(radian), cos(radian), 0),
glm::vec3(0, 0, 1)
);
};
int main(int argc, char** argv) {
// Initialize SDL and open a window
SDLWindowManager windowManager(600, 600, "GLImac");
// Initialize glew for OpenGL3+ support
GLenum glewInitError = glewInit();
if(GLEW_OK != glewInitError) {
std::cerr << glewGetErrorString(glewInitError) << std::endl;
return EXIT_FAILURE;
}
std::cout << "OpenGL Version : " << glGetString(GL_VERSION) << std::endl;
std::cout << "GLEW Version : " << glewGetString(GLEW_VERSION) << std::endl;
/*********************************
* HERE SHOULD COME THE INITIALIZATION CODE
*********************************/
FilePath applicationPath(argv[0]);
Program program = loadProgram(
applicationPath.dirPath() + "shaders/multiple_matrix.vs.glsl",
applicationPath.dirPath() + "shaders/multiple_matrix.fs.glsl"
);
program.use();
GLint vs_matrix_transform = glGetUniformLocation(program.getGLId(), "uModelMatrix");
GLint fs_vec_color = glGetUniformLocation(program.getGLId(), "uColor");
// vbo stuff
GLuint vbo;
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
Vertex2DUV vertices[] = {
Vertex2DUV(glm::vec2(-1, -1), glm::vec2(0, 1)),
Vertex2DUV(glm::vec2( 1, -1), glm::vec2(1, 1)),
Vertex2DUV(glm::vec2( 0, 1), glm::vec2(.5, 0))
};
glBufferData(
GL_ARRAY_BUFFER,
3 * sizeof(Vertex2DUV),
vertices,
GL_STATIC_DRAW
);
glBindBuffer(GL_ARRAY_BUFFER, 0);
// vao stuff
GLuint vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
const GLuint VERTEX_ATTR_POSITION = 0;
const GLuint VERTEX_ATTR_TEXTURE = 1;
glEnableVertexAttribArray(VERTEX_ATTR_POSITION);
glEnableVertexAttribArray(VERTEX_ATTR_TEXTURE);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glVertexAttribPointer(
VERTEX_ATTR_POSITION,
2,
GL_FLOAT,
GL_FALSE,
sizeof(Vertex2DUV),
(GLvoid*) offsetof(Vertex2DUV, position)
);
glVertexAttribPointer(
VERTEX_ATTR_TEXTURE,
2,
GL_FLOAT,
GL_FALSE,
sizeof(Vertex2DUV),
(GLvoid*) offsetof(Vertex2DUV, texture)
);
// Setup instance rendering
const GLuint TRIANGLE_POSITION_loc = 2;
glm::vec3 positions[] = {
glm::vec3(0, 1, 0),
glm::vec3(1, 0, 0)
};
// Create buffer
GLuint position_buffer;
glGenBuffers(1, &position_buffer);
// Binding buffer
glBindBuffer(GL_ARRAY_BUFFER, position_buffer);
// Describing buffer
glVertexAttribPointer(
TRIANGLE_POSITION_loc, 3, GL_FLOAT, GL_FALSE, 0, NULL);
glEnableVertexAttribArray(TRIANGLE_POSITION_loc);
// This is the important bit... set the divisor for the color array
// to 1 to get OpenGL to give us a new value of "color" per-instance
// rather than per-vertex.
glVertexAttribDivisor(TRIANGLE_POSITION_loc, 1);
// Create buffer
const GLuint scale_loc = 3;
glm::mat3 scale_matrix = scale(.5, .5);
std::cout << scale_matrix << std::endl;
GLuint scale_matrix_buffer;
glGenBuffers(1, &scale_matrix_buffer);
// Likewise, we can do the same with the model matrix. Note that a
// matrix input to the vertex shader consumes N consecutive input
// locations, where N is the number of columns in the matrix. So...
// we have four vertex attributes to set up.
glBindBuffer(GL_ARRAY_BUFFER, scale_matrix_buffer);
// Loop over each column of the matrix...
for (int i = 0; i < 4; i++) {
// Set up the vertex attribute
glVertexAttribPointer(scale_loc + i, // Location
4, GL_FLOAT, GL_FALSE, // vec4
sizeof(glm::mat4), // Stride
(void *)(sizeof(glm::vec4) * i)); // Start offset
// Enable it
glEnableVertexAttribArray(scale_loc + i);
// Make it instanced
glVertexAttribDivisor(scale_loc + i, 1);
}
glBindVertexArray(0);
// Texture stuff
std::unique_ptr<Image> texture_img_1 = loadImage("/home/mathias/Development/mncrft/assets/textures/triforce.png");
if (texture_img_1 == NULL) {
exit(0);
}
std::unique_ptr<Image> texture_img_2 = loadImage("/home/mathias/Development/mncrft/assets/textures/triforcecaca.png");
if (texture_img_2 == NULL) {
exit(0);
}
GLuint textures;
glGenTextures(1, &textures);
glBindTexture(GL_TEXTURE_2D_ARRAY, textures);
glTexImage3D(
GL_TEXTURE_2D_ARRAY,
0,
GL_RGBA,
texture_img_1->getWidth(),
texture_img_1->getHeight(),
2, //number of texture
0,
GL_RGBA,
GL_UNSIGNED_BYTE,
NULL
);
glTexSubImage3D(
GL_TEXTURE_2D_ARRAY,
0,
0,
0,
0, // i
texture_img_1->getWidth(),
texture_img_1->getHeight(),
1,
GL_RGBA,
GL_FLOAT,
texture_img_1->getPixels()
);
glTexSubImage3D(
GL_TEXTURE_2D_ARRAY,
0,
0,
0,
1, // i
texture_img_2->getWidth(),
texture_img_2->getHeight(),
1,
GL_RGBA,
GL_FLOAT,
texture_img_2->getPixels()
);
glTexParameteri(GL_TEXTURE_2D_ARRAY,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D_ARRAY,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D_ARRAY,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D_ARRAY,GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE);
glBindTexture(GL_TEXTURE_2D_ARRAY, 0);
// Application loop:
bool done = false;
int instanceCount = 2;
while(!done) {
// Event loop:
SDL_Event e;
while(windowManager.pollEvent(e)) {
if(e.type == SDL_QUIT) {
done = true; // Leave the loop after this iteration
}
}
/*********************************
* HERE SHOULD COME THE RENDERING CODE
*********************************/
glClear(GL_COLOR_BUFFER_BIT);
glBindBuffer(GL_ARRAY_BUFFER, position_buffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * instanceCount, positions, GL_DYNAMIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, scale_matrix_buffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(glm::mat4) * instanceCount, &scale_matrix, GL_DYNAMIC_DRAW);
glBindTexture(GL_TEXTURE_2D_ARRAY, textures);
glBindVertexArray(vao);
glDrawArraysInstanced(GL_TRIANGLES, 0, 3, instanceCount);
glBindVertexArray(0);
// Update the display
windowManager.swapBuffers();
}
glDeleteBuffers(1, &vbo);
glDeleteVertexArrays(1, &vao);
return EXIT_SUCCESS;
}
| 25.330986
| 119
| 0.659438
|
ArmandBiteau
|
72776824ba2222a6f735de8008b702bfe058be52
| 439
|
hpp
|
C++
|
include/cppurses/painter/detail/extended_char.hpp
|
jktjkt/CPPurses
|
652d702258db8fab55ae945f7bb38e0b7c29521b
|
[
"MIT"
] | null | null | null |
include/cppurses/painter/detail/extended_char.hpp
|
jktjkt/CPPurses
|
652d702258db8fab55ae945f7bb38e0b7c29521b
|
[
"MIT"
] | null | null | null |
include/cppurses/painter/detail/extended_char.hpp
|
jktjkt/CPPurses
|
652d702258db8fab55ae945f7bb38e0b7c29521b
|
[
"MIT"
] | null | null | null |
#ifndef CPPURSES_PAINTER_DETAIL_EXTENDED_CHAR_HPP
#define CPPURSES_PAINTER_DETAIL_EXTENDED_CHAR_HPP
#include <ncurses.h>
namespace cppurses {
namespace detail {
/// Retrieve a character that is equivalent to /p sym. For ncurses
/// implementations that do not support wide characters.
chtype find_chtype(wchar_t sym, bool* use_addch);
} // namespace detail
} // namespace cppurses
#endif // CPPURSES_PAINTER_DETAIL_EXTENDED_CHAR_HPP
| 29.266667
| 66
| 0.806378
|
jktjkt
|
7280da6f34bb62ada91615fe3ccd8a6a6256cd35
| 707
|
cpp
|
C++
|
codechef/IOPC/Russiancodecup/B.cpp
|
GinugaSaketh/Codes
|
e934aa5652dd86231a42e3f7f84b145eb35bf47d
|
[
"MIT"
] | null | null | null |
codechef/IOPC/Russiancodecup/B.cpp
|
GinugaSaketh/Codes
|
e934aa5652dd86231a42e3f7f84b145eb35bf47d
|
[
"MIT"
] | null | null | null |
codechef/IOPC/Russiancodecup/B.cpp
|
GinugaSaketh/Codes
|
e934aa5652dd86231a42e3f7f84b145eb35bf47d
|
[
"MIT"
] | null | null | null |
#include<iostream>
#include<cstdio>
using namespace std;
int a[100005];
int b[100005];
long long h;
int main(){
int t;
cin>>t;
while(t--){
int i;
int n;
cin>>n>>h;
for(i=1;i<=n;i++){
scanf("%d",&a[i]);
}
for(i=1;i<=n;i++){
scanf("%d",&b[i]);
}
int net=0;
for(i=1;i<=n;i++){
int j=i;
int j_=-1;
long long sum=0;
int found=0;
while(j<=n&&sum<=h){
sum+=a[j];
if(b[j]==1){
found=1;
j_=j;
}
j++;
}
//cout<<j<<endl;
if(found==0){
a[j-1]=1;
// cout<<"YES"<<endl;
net++;
i=j;
}else{
i=j_;
}
}
if(a[1]!=1){
net++;
}
if(n!=1&&a[n-1]!=1){
net++;
}
cout<<net<<endl;
}
return 0;
}
| 9.957746
| 24
| 0.422914
|
GinugaSaketh
|
7282518c60e3a4fac6f9b8ddccff2ecda82ea0da
| 7,401
|
cpp
|
C++
|
source/design/Color4Converter.cpp
|
HeavenWu/slimdx
|
e014bb34b89bbf694d01c8f6d6b6dfa3cba58aac
|
[
"MIT"
] | 85
|
2015-04-06T05:37:10.000Z
|
2022-03-22T19:53:03.000Z
|
source/design/Color4Converter.cpp
|
HeavenWu/slimdx
|
e014bb34b89bbf694d01c8f6d6b6dfa3cba58aac
|
[
"MIT"
] | 10
|
2016-03-17T11:18:24.000Z
|
2021-05-11T09:21:43.000Z
|
source/design/Color4Converter.cpp
|
HeavenWu/slimdx
|
e014bb34b89bbf694d01c8f6d6b6dfa3cba58aac
|
[
"MIT"
] | 45
|
2015-09-14T03:54:01.000Z
|
2022-03-22T19:53:09.000Z
|
#include "stdafx.h"
/*
* Copyright (c) 2007-2012 SlimDX Group
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "../InternalHelpers.h"
#include "../math/Color4.h"
#include "Color4Converter.h"
#include "FieldPropertyDescriptor.h"
using namespace System;
using namespace System::Collections;
using namespace System::Drawing;
using namespace System::ComponentModel;
using namespace System::ComponentModel::Design::Serialization;
using namespace System::Globalization;
using namespace System::Reflection;
namespace SlimDX
{
namespace Design
{
Color4Converter::Color4Converter()
{
Type^ type = Color4::typeid;
array<PropertyDescriptor^>^ propArray =
{
gcnew FieldPropertyDescriptor(type->GetField("Red")),
gcnew FieldPropertyDescriptor(type->GetField("Green")),
gcnew FieldPropertyDescriptor(type->GetField("Blue")),
gcnew FieldPropertyDescriptor(type->GetField("Alpha")),
};
m_Properties = gcnew PropertyDescriptorCollection(propArray);
}
bool Color4Converter::CanConvertTo(ITypeDescriptorContext^ context, Type^ destinationType)
{
if( destinationType == String::typeid || destinationType == InstanceDescriptor::typeid )
return true;
else
return ExpandableObjectConverter::CanConvertTo(context, destinationType);
}
bool Color4Converter::CanConvertFrom(ITypeDescriptorContext^ context, Type^ sourceType)
{
if( sourceType == String::typeid )
return true;
else
return ExpandableObjectConverter::CanConvertFrom(context, sourceType);
}
Object^ Color4Converter::ConvertTo(ITypeDescriptorContext^ context, CultureInfo^ culture, Object^ value, Type^ destinationType)
{
if( destinationType == nullptr )
throw gcnew ArgumentNullException( "destinationType" );
if( culture == nullptr )
culture = CultureInfo::CurrentCulture;
Color4^ color = dynamic_cast<Color4^>( value );
if( destinationType == String::typeid && color != nullptr )
{
String^ separator = culture->TextInfo->ListSeparator + " ";
TypeConverter^ converter = TypeDescriptor::GetConverter(float::typeid);
array<String^>^ stringArray = gcnew array<String^>( 4 );
stringArray[0] = converter->ConvertToString( context, culture, color->Alpha );
stringArray[1] = converter->ConvertToString( context, culture, color->Red );
stringArray[2] = converter->ConvertToString( context, culture, color->Green );
stringArray[3] = converter->ConvertToString( context, culture, color->Blue );
return String::Join( separator, stringArray );
}
else if( destinationType == InstanceDescriptor::typeid && color != nullptr )
{
ConstructorInfo^ info = (Color4::typeid)->GetConstructor( gcnew array<Type^> { float::typeid, float::typeid, float::typeid, float::typeid } );
if( info != nullptr )
return gcnew InstanceDescriptor( info, gcnew array<Object^> { color->Alpha, color->Red, color->Green, color->Blue } );
}
return ExpandableObjectConverter::ConvertTo(context, culture, value, destinationType);
}
Object^ Color4Converter::ConvertFrom(ITypeDescriptorContext^ context, CultureInfo^ culture, Object^ value)
{
if( culture == nullptr )
culture = CultureInfo::CurrentCulture;
String^ string = dynamic_cast<String^>( value );
if( string != nullptr )
{
string = string->Trim();
TypeConverter^ floatConverter = TypeDescriptor::GetConverter(float::typeid);
array<String^>^ stringArray = string->Split( culture->TextInfo->ListSeparator[0] );
if( stringArray->Length == 1 )
{
int number = 0;
if( int::TryParse( string, number ) )
return gcnew Color4( number );
TypeConverter^ colorConverter = TypeDescriptor::GetConverter(Color::typeid);
return gcnew Color4( safe_cast<Color>( colorConverter->ConvertFromString( context, culture, string ) ) );
}
else if( stringArray->Length == 3 )
{
int red;
int green;
int blue;
if( int::TryParse( stringArray[0], red ) && int::TryParse( stringArray[1], green ) && int::TryParse( stringArray[2], blue ) )
return gcnew Color4( Color::FromArgb( red, green, blue ) );
float r = safe_cast<float>( floatConverter->ConvertFromString( context, culture, stringArray[0] ) );
float g = safe_cast<float>( floatConverter->ConvertFromString( context, culture, stringArray[1] ) );
float b = safe_cast<float>( floatConverter->ConvertFromString( context, culture, stringArray[2] ) );
return gcnew Color4( r, g, b );
}
else if( stringArray->Length == 4 )
{
int red;
int green;
int blue;
int alpha;
if( int::TryParse( stringArray[0], alpha ) && int::TryParse( stringArray[1], red ) && int::TryParse( stringArray[2], green ) && int::TryParse( stringArray[3], blue ) )
return gcnew Color4( Color::FromArgb( alpha, red, green, blue ) );
float a = safe_cast<float>( floatConverter->ConvertFromString( context, culture, stringArray[0] ) );
float r = safe_cast<float>( floatConverter->ConvertFromString( context, culture, stringArray[1] ) );
float g = safe_cast<float>( floatConverter->ConvertFromString( context, culture, stringArray[2] ) );
float b = safe_cast<float>( floatConverter->ConvertFromString( context, culture, stringArray[3] ) );
return gcnew Color4( a, r, g, b );
}
else
throw gcnew ArgumentException("Invalid color format.");
}
return ExpandableObjectConverter::ConvertFrom(context, culture, value);
}
bool Color4Converter::GetCreateInstanceSupported(ITypeDescriptorContext^ context)
{
SLIMDX_UNREFERENCED_PARAMETER(context);
return true;
}
Object^ Color4Converter::CreateInstance(ITypeDescriptorContext^ context, IDictionary^ propertyValues)
{
SLIMDX_UNREFERENCED_PARAMETER(context);
if( propertyValues == nullptr )
throw gcnew ArgumentNullException( "propertyValues" );
return gcnew Color4( safe_cast<float>( propertyValues["Alpha"] ), safe_cast<float>( propertyValues["Red"] ),
safe_cast<float>( propertyValues["Green"] ), safe_cast<float>( propertyValues["Blue"] ) );
}
bool Color4Converter::GetPropertiesSupported(ITypeDescriptorContext^)
{
return true;
}
PropertyDescriptorCollection^ Color4Converter::GetProperties(ITypeDescriptorContext^, Object^, array<Attribute^>^)
{
return m_Properties;
}
}
}
| 38.546875
| 172
| 0.710309
|
HeavenWu
|
7282d630f61edea8f97d2d920d4f533fae415835
| 794
|
cpp
|
C++
|
Algorithmic-Toolbox/week4_divide_and_conquer/assignment/1_binary_search.cpp
|
adityakrmaurya/Data-Structures-and-Algorithms
|
bcb7fbebb7581ca77bc9eec815d1e2d62ad1374f
|
[
"MIT"
] | 2
|
2020-07-13T22:27:30.000Z
|
2021-12-11T09:08:17.000Z
|
Algorithmic-Toolbox/week4_divide_and_conquer/assignment/1_binary_search.cpp
|
adityakrmaurya/Data-Structures-and-Algorithms
|
bcb7fbebb7581ca77bc9eec815d1e2d62ad1374f
|
[
"MIT"
] | null | null | null |
Algorithmic-Toolbox/week4_divide_and_conquer/assignment/1_binary_search.cpp
|
adityakrmaurya/Data-Structures-and-Algorithms
|
bcb7fbebb7581ca77bc9eec815d1e2d62ad1374f
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
int binary_search(vector<int>& an, int low, int high,int value)
{
while(low <= high){
int mid = floor(low + ((high - low) / 2));
if(an[mid] == value){
return mid;
}
else if(an[mid] < value){
low = mid+1;
}
else
high = mid - 1;
}
return -1;
}
int main (void)
{
int n, k;
cin >> n;
vector<int> an;
for(int i = 0, a; i < n; i++){
cin >> a;
an.push_back(a);
}
sort(an.begin(), an.end());
cin >> k;
for(int i = 0, b; i < k; i++){
cin >> b;
cout << binary_search(an, 0, n-1, b) << " ";
}
return 0;
}
| 17.644444
| 63
| 0.43199
|
adityakrmaurya
|
72830acd984ea978ca9d5d17809f48d294b059c8
| 2,390
|
hpp
|
C++
|
src/Emulators/nestopiaue/core/api/NstApiEmulator.hpp
|
slajerek/RetroDebugger
|
e761e4f9efd103a05e65ef283423b142fa4324c7
|
[
"Apache-2.0",
"MIT"
] | 34
|
2021-05-29T07:04:17.000Z
|
2022-03-10T20:16:03.000Z
|
src/Emulators/nestopiaue/core/api/NstApiEmulator.hpp
|
slajerek/RetroDebugger
|
e761e4f9efd103a05e65ef283423b142fa4324c7
|
[
"Apache-2.0",
"MIT"
] | 6
|
2021-12-25T13:05:21.000Z
|
2022-01-19T17:35:17.000Z
|
src/Emulators/nestopiaue/core/api/NstApiEmulator.hpp
|
slajerek/RetroDebugger
|
e761e4f9efd103a05e65ef283423b142fa4324c7
|
[
"Apache-2.0",
"MIT"
] | 6
|
2021-12-24T18:37:41.000Z
|
2022-02-06T23:06:02.000Z
|
////////////////////////////////////////////////////////////////////////////////////////
//
// Nestopia - NES/Famicom emulator written in C++
//
// Copyright (C) 2003-2008 Martin Freij
//
// This file is part of Nestopia.
//
// Nestopia is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// Nestopia 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 Nestopia; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
////////////////////////////////////////////////////////////////////////////////////////
#ifndef NST_API_EMULATOR_H
#define NST_API_EMULATOR_H
#ifndef NST_BASE_H
#include "NstBase.hpp"
#endif
#ifdef NST_PRAGMA_ONCE
#pragma once
#endif
#if NST_MSVC >= 1200
#pragma warning( push )
#endif
namespace Nes
{
namespace Core
{
class Machine;
namespace Video
{
class Output;
}
namespace Sound
{
class Output;
}
namespace Input
{
class Controllers;
}
}
namespace Api
{
/**
* Emulator object instance.
*/
class Emulator
{
public:
Emulator();
~Emulator() throw();
/**
* Executes one frame.
*
* @param video video context object or NULL to skip output
* @param sound sound context object or NULL to skip output
* @param input input context object or NULL to skip output
* @return result code
*/
Result Execute
(
Core::Video::Output* video,
Core::Sound::Output* sound,
Core::Input::Controllers* input
) throw();
/**
* Returns the number of executed frames relative to the last machine power/reset.
*
* @return number
*/
ulong Frame() const throw();
private:
Core::Machine& machine;
public:
operator Core::Machine& ()
{
return machine;
}
};
}
}
#if NST_MSVC >= 1200
#pragma warning( pop )
#endif
#endif
| 20.782609
| 89
| 0.594142
|
slajerek
|
728719521093303c7fe90114988ebecdc5936b80
| 892
|
hh
|
C++
|
examples/Example17/include/HepMC3G4AsciiReaderMessenger.hh
|
stognini/AdePT
|
9a106b83f421938ad8f4d8567d199c84f339e6c9
|
[
"Apache-2.0"
] | null | null | null |
examples/Example17/include/HepMC3G4AsciiReaderMessenger.hh
|
stognini/AdePT
|
9a106b83f421938ad8f4d8567d199c84f339e6c9
|
[
"Apache-2.0"
] | null | null | null |
examples/Example17/include/HepMC3G4AsciiReaderMessenger.hh
|
stognini/AdePT
|
9a106b83f421938ad8f4d8567d199c84f339e6c9
|
[
"Apache-2.0"
] | null | null | null |
// SPDX-FileCopyrightText: 2022 CERN
// SPDX-License-Identifier: Apache-2.0
//
/// \file eventgenerator/HepMC3/HepMCEx01/include/HepMC3G4AsciiReaderMessenger.hh
/// \brief Definition of the HepMC3G4AsciiReaderMessenger class
//
//
#ifndef HEPMC3_G4_ASCII_READER_MESSENGER_H
#define HEPMC3_G4_ASCII_READER_MESSENGER_H
#include "G4UImessenger.hh"
class HepMC3G4AsciiReader;
class G4UIdirectory;
class G4UIcmdWithoutParameter;
class G4UIcmdWithAString;
class G4UIcmdWithAnInteger;
class HepMC3G4AsciiReaderMessenger : public G4UImessenger {
public:
HepMC3G4AsciiReaderMessenger(HepMC3G4AsciiReader* agen);
~HepMC3G4AsciiReaderMessenger();
void SetNewValue(G4UIcommand* command, G4String newValues);
G4String GetCurrentValue(G4UIcommand* command);
private:
HepMC3G4AsciiReader* gen;
G4UIdirectory* dir;
G4UIcmdWithAnInteger* verbose;
G4UIcmdWithAString* open;
};
#endif
| 22.871795
| 81
| 0.816143
|
stognini
|
72883e023464c4adabdd0b0749b15e951a7835e9
| 3,869
|
cpp
|
C++
|
Dicom/dicom/data/UL.cpp
|
drleq/CppDicom
|
e320fad8414fabfb51c5eb80964f8b6def578247
|
[
"MIT"
] | null | null | null |
Dicom/dicom/data/UL.cpp
|
drleq/CppDicom
|
e320fad8414fabfb51c5eb80964f8b6def578247
|
[
"MIT"
] | null | null | null |
Dicom/dicom/data/UL.cpp
|
drleq/CppDicom
|
e320fad8414fabfb51c5eb80964f8b6def578247
|
[
"MIT"
] | null | null | null |
#include "dicom_pch.h"
#include "dicom/data/UL.h"
namespace dicom::data {
UL::UL()
: UL(buffer<uint32_t>())
{}
//--------------------------------------------------------------------------------------------------------
UL::UL(const buffer<uint32_t>& binary_value)
: UL(binary_value.Copy())
{}
//--------------------------------------------------------------------------------------------------------
UL::UL(buffer<uint32_t>&& binary_value)
: VR(VRType::UL),
m_value(std::forward<buffer<uint32_t>>(binary_value))
{}
//--------------------------------------------------------------------------------------------------------
UL::UL(uint32_t value)
: VR(VRType::UL),
m_value(1)
{
m_value[0] = value;
}
//--------------------------------------------------------------------------------------------------------
UL::UL(const std::vector<uint32_t>& values)
: VR(VRType::UL),
m_value(values.size())
{
if (!values.empty()) {
memcpy(m_value, &values[0], m_value.ByteLength());
}
}
//--------------------------------------------------------------------------------------------------------
UL::UL(std::initializer_list<uint32_t> values)
: VR(VRType::UL),
m_value(values.size())
{
if (values.size() > 0) {
memcpy(m_value, values.begin(), m_value.ByteLength());
}
}
//--------------------------------------------------------------------------------------------------------
UL::UL(const UL& other)
: VR(other),
m_value(other.m_value.Copy())
{}
//--------------------------------------------------------------------------------------------------------
UL::UL(UL&& other)
: VR(std::forward<VR>(other)),
m_value(std::move(other.m_value))
{}
//--------------------------------------------------------------------------------------------------------
UL::~UL() = default;
//--------------------------------------------------------------------------------------------------------
UL& UL::operator = (const UL& other) {
VR::operator = (other);
m_value = other.m_value.Copy();
return *this;
}
//--------------------------------------------------------------------------------------------------------
UL& UL::operator = (UL&& other) {
VR::operator = (std::forward<VR>(other));
m_value = std::move(other.m_value);
return *this;
}
//--------------------------------------------------------------------------------------------------------
ValidityType UL::Validate() const {
return ValidityType::Valid;
}
//--------------------------------------------------------------------------------------------------------
int32_t UL::Compare(const VR* other) const {
auto result = VR::Compare(other);
if (result) { return result; }
auto typed = static_cast<const UL*>(other);
return m_value.Compare(typed->m_value);
}
//--------------------------------------------------------------------------------------------------------
bool UL::operator == (const VR* other) const {
if (VR::Compare(other) != 0) { return false; }
auto typed = static_cast<const UL*>(other);
return m_value == typed->m_value;
}
//--------------------------------------------------------------------------------------------------------
bool UL::operator != (const VR* other) const {
if (VR::Compare(other) != 0) { return true; }
auto typed = static_cast<const UL*>(other);
return m_value != typed->m_value;
}
}
| 31.713115
| 111
| 0.303438
|
drleq
|
728e2c2ced345b4d0132b236b5471b54cc92ffd9
| 2,380
|
cpp
|
C++
|
zimlib/src/uuid.cpp
|
zjzdy/Offline-small-search
|
8bc7382b3f55184c8d179a2bf6e1e90730d6a09c
|
[
"ICU"
] | 10
|
2016-05-10T14:48:44.000Z
|
2021-06-16T11:49:55.000Z
|
zimlib/src/uuid.cpp
|
zjzdy/Offline-small-search
|
8bc7382b3f55184c8d179a2bf6e1e90730d6a09c
|
[
"ICU"
] | null | null | null |
zimlib/src/uuid.cpp
|
zjzdy/Offline-small-search
|
8bc7382b3f55184c8d179a2bf6e1e90730d6a09c
|
[
"ICU"
] | 2
|
2016-11-09T06:56:29.000Z
|
2019-11-22T14:34:27.000Z
|
/*
* Copyright (C) 2009 Tommi Maekitalo
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* is provided AS IS, WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, and
* NON-INFRINGEMENT. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include <zim/uuid.h>
#include <iostream>
#include <time.h>
#include <zim/zim.h> // necessary to have the new types
#include "log.h"
#include "md5stream.h"
#ifdef _WIN32
# include <time.h>
# include <windows.h>
int gettimeofday(struct timeval* tp, void* tzp) {
DWORD t;
t = timeGetTime();
tp->tv_sec = t / 1000;
tp->tv_usec = t % 1000;
return 0;
}
#define getpid GetCurrentProcessId
#else
# include <sys/time.h>
#endif
log_define("zim.uuid")
namespace zim
{
namespace
{
char hex[] = "0123456789abcdef";
inline char hi(char v)
{ return hex[(v >> 4) & 0xf]; }
inline char lo(char v)
{ return hex[v & 0xf]; }
}
Uuid Uuid::generate()
{
Uuid ret;
struct timeval tv;
gettimeofday(&tv, 0);
Md5stream m;
clock_t c = clock();
m << c << tv.tv_sec << tv.tv_usec;
m.getDigest(reinterpret_cast<unsigned char*>(&ret.data[0]));
log_debug("generated uuid: " << ret.data);
return ret;
}
std::ostream& operator<< (std::ostream& out, const Uuid& uuid)
{
for (unsigned n = 0; n < 4; ++n)
out << hi(uuid.data[n]) << lo(uuid.data[n]);
out << '-';
for (unsigned n = 4; n < 6; ++n)
out << hi(uuid.data[n]) << lo(uuid.data[n]);
out << '-';
for (unsigned n = 6; n < 8; ++n)
out << hi(uuid.data[n]) << lo(uuid.data[n]);
out << '-';
for (unsigned n = 8; n < 10; ++n)
out << hi(uuid.data[n]) << lo(uuid.data[n]);
out << '-';
for (unsigned n = 10; n < 16; ++n)
out << hi(uuid.data[n]) << lo(uuid.data[n]);
return out;
}
}
| 24.040404
| 76
| 0.614706
|
zjzdy
|
728ea2c101e02807b1a95576573d7a9519ee3464
| 815
|
cpp
|
C++
|
#0036.valid-sudoku.cpp
|
hosomi/LeetCode
|
aba8fae8e37102b33dba8fd4adf1f018c395a4db
|
[
"MIT"
] | null | null | null |
#0036.valid-sudoku.cpp
|
hosomi/LeetCode
|
aba8fae8e37102b33dba8fd4adf1f018c395a4db
|
[
"MIT"
] | null | null | null |
#0036.valid-sudoku.cpp
|
hosomi/LeetCode
|
aba8fae8e37102b33dba8fd4adf1f018c395a4db
|
[
"MIT"
] | null | null | null |
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
unordered_set<string> set;
string work, col, cell, row;
for (int i = 0; i < 9; ++i) {
for (int j = 0; j < 9; ++j) {
if (board[i][j] == '.') {
continue;
}
work = "(" + to_string(board[i][j]) + ")";
row = to_string(i) + work;
col = work + to_string(j);
cell = to_string(i / 3) + work + to_string(j / 3);
if (set.count(row) || set.count(col) || set.count(cell)) {
return false;
}
set.insert(row);
set.insert(col);
set.insert(cell);
}
}
return true;
}
};
| 30.185185
| 74
| 0.38773
|
hosomi
|
72941c89f7a542a72afae6aa1c60bfb65e047717
| 3,458
|
cpp
|
C++
|
TIDriver/sfr.cpp
|
IgarashiYuka/msp430f5529lp_workspace
|
09aa6c297330202c700fbc7bc1d8ad6da660ba15
|
[
"MIT"
] | 58
|
2020-02-16T00:06:07.000Z
|
2022-03-24T20:43:45.000Z
|
TIDriver/sfr.cpp
|
IgarashiYuka/msp430f5529lp_workspace
|
09aa6c297330202c700fbc7bc1d8ad6da660ba15
|
[
"MIT"
] | 24
|
2020-02-18T02:40:32.000Z
|
2022-01-14T16:53:47.000Z
|
TIDriver/sfr.cpp
|
IgarashiYuka/msp430f5529lp_workspace
|
09aa6c297330202c700fbc7bc1d8ad6da660ba15
|
[
"MIT"
] | 22
|
2020-03-14T15:13:51.000Z
|
2022-03-23T05:42:24.000Z
|
/* --COPYRIGHT--,BSD
* Copyright (c) 2017, Texas Instruments Incorporated
* 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 Texas Instruments Incorporated nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* --/COPYRIGHT--*/
//*****************************************************************************
//
// sfr.c - Driver for the sfr Module.
//
//*****************************************************************************
//*****************************************************************************
//
//! \addtogroup sfr_api sfr
//! @{
//
//*****************************************************************************
#include "inc/hw_memmap.h"
#ifdef __MSP430_HAS_SFR__
#include "sfr.h"
#include <assert.h>
void SFR_enableInterrupt (uint8_t interruptMask)
{
HWREG8(SFR_BASE + OFS_SFRIE1_L) |= interruptMask;
}
void SFR_disableInterrupt (uint8_t interruptMask)
{
HWREG8(SFR_BASE + OFS_SFRIE1_L) &= ~(interruptMask);
}
uint8_t SFR_getInterruptStatus (uint8_t interruptFlagMask)
{
return ( HWREG8(SFR_BASE + OFS_SFRIFG1_L) & interruptFlagMask );
}
void SFR_clearInterrupt (uint8_t interruptFlagMask)
{
HWREG8(SFR_BASE + OFS_SFRIFG1_L) &= ~(interruptFlagMask);
}
void SFR_setResetPinPullResistor (uint16_t pullResistorSetup)
{
HWREG8(SFR_BASE + OFS_SFRRPCR_L) &= ~(SYSRSTRE + SYSRSTUP);
HWREG8(SFR_BASE + OFS_SFRRPCR_L) |= pullResistorSetup;
}
void SFR_setNMIEdge (uint16_t edgeDirection)
{
HWREG8(SFR_BASE + OFS_SFRRPCR_L) &= ~(SYSNMIIES);
HWREG8(SFR_BASE + OFS_SFRRPCR_L) |= edgeDirection;
}
void SFR_setResetNMIPinFunction (uint8_t resetPinFunction)
{
HWREG8(SFR_BASE + OFS_SFRRPCR_L) &= ~(SYSNMI);
HWREG8(SFR_BASE + OFS_SFRRPCR_L) |= resetPinFunction;
}
#endif
//*****************************************************************************
//
//! Close the doxygen group for sfr_api
//! @}
//
//*****************************************************************************
| 35.649485
| 80
| 0.621457
|
IgarashiYuka
|
72952acc62f29bd363d3cf0438ff7a49a795be55
| 9,945
|
cpp
|
C++
|
SimpleNeuralNetwork/SimpleNeuralNetwork.cpp
|
14gasher/patternizer
|
692e4a38817cf80ba7a45f999874edd81283cda0
|
[
"MIT"
] | 1
|
2017-10-14T15:03:18.000Z
|
2017-10-14T15:03:18.000Z
|
SimpleNeuralNetwork/SimpleNeuralNetwork.cpp
|
14gasher/patternizer
|
692e4a38817cf80ba7a45f999874edd81283cda0
|
[
"MIT"
] | null | null | null |
SimpleNeuralNetwork/SimpleNeuralNetwork.cpp
|
14gasher/patternizer
|
692e4a38817cf80ba7a45f999874edd81283cda0
|
[
"MIT"
] | null | null | null |
//
// Created by Asher Gunsay on 9/22/17.
//
#include "SimpleNeuralNetwork.hpp"
#include <vector>
#include <math.h>
#include <iostream>
#include <fstream>
SimpleNeuralNetwork::SimpleNeuralNetwork(unsigned int* sizes, double learnRate = 0.1, unsigned int epochCount = 30) :
size(sizes), learningRate(learnRate)
{
std::normal_distribution<double> d(0,0.3333333);
distribution = d;
// Initialize the weights to something. Guassian distribution with mean of 0, -1 and 1 at 3 std dev marks best
// fine tuning, but will be more likely to change.
// Also initialize the bias to start with initial weights of 1.
weights = new Matrix*[layers -1];
bias = new Matrix*[layers-1];
// The first layer is inputs! It will not have weights
for(int i = 1; i < layers; i++){
weights[i-1] = new Matrix(sizes[i], sizes[i-1]);
bias[i-1] = new Matrix(sizes[i], 1);
for(unsigned int j = 0; j < weights[i-1]->rowCount(); j++){
bias[i-1]->set(j, 0, 0.1);
for(unsigned int k = 0; k < weights[i-1]->colCount(); k++){
weights[i-1]->set(j, k, fRand());
}
}
}
/*
* This is where we initialize the string for the file
*/
weightsString += "P3\n";
weightsString += std::to_string(28 * 28) + " " + std::to_string(epochCount * (sizes[1])) + "\n";
weightsString += "255\n";
weightsString2 += "P3\n";
weightsString2 += std::to_string(29 * sizes[1]) + " " + std::to_string(epochCount * 28) + "\n";
weightsString2 += "255\n";
};
SimpleNeuralNetwork::~SimpleNeuralNetwork()
{
std::ofstream saveFile;
std::string fileName = "nn";
for(int i = 0; i < layers - 1; i++){
fileName += std::to_string(bias[i]->colCount());
}
fileName += ".ppm";
saveFile.open(fileName);
saveFile << weightsString;
saveFile.close();
saveFile.open("nnImage.ppm");
saveFile << weightsString2;
saveFile.close();
// Clean up pointers
for(unsigned int i = 0; i < layers - 1; i++){
delete weights[i];
delete bias[i];
weights[i] = nullptr;
bias[i] = nullptr;
}
delete []weights;
delete []bias;
weights = nullptr;
bias = nullptr;
}
// Component Functions
double SimpleNeuralNetwork::logarithmicActivation(double weightedInput){
return 1.0/(1.0+exp(weightedInput * (-1.0)));
};
double SimpleNeuralNetwork::logarithmicActivationDerivative(double activatedOutput){
return activatedOutput*(1 - activatedOutput);
};
// Functions for matrix handling
void SimpleNeuralNetwork::matrixCalculateWeightedInput(Matrix &input, Matrix* output, unsigned int layerNumber) {
Matrix withoutBias = weights[layerNumber]->matrixMultiplation(input);
Matrix biasLayer = *(bias[layerNumber]);
output[layerNumber] = withoutBias.addition(biasLayer);
};
void SimpleNeuralNetwork::matrixLogarithmicActivation(Matrix &weightedInput, Matrix* output, unsigned int layerNumber) {
Matrix layerOutput(weightedInput.rowCount(), 1);
for(unsigned int i = 0; i < weightedInput.rowCount(); i++){
for(unsigned int j = 0; j < weightedInput.colCount(); j++){
layerOutput.set(i,j, logarithmicActivation(weightedInput.get(i,j)));
}
}
output[layerNumber] = layerOutput;
};
Matrix SimpleNeuralNetwork::matrixLogarithmicActivationDerivative(Matrix weightedInput) {
Matrix activationDerivative(weightedInput.rowCount(), weightedInput.colCount());
for(unsigned int i = 0; i < weightedInput.rowCount(); i++){
for(unsigned int j = 0; j < weightedInput.colCount(); j++){
activationDerivative.set(i,j, logarithmicActivationDerivative(weightedInput.get(i,j)));
}
}
return activationDerivative;
};
// This will set the errors array order in the order that it calculates them, so output neurons first, followed by L - 1, etc
void SimpleNeuralNetwork::matrixCostFunction(Matrix &outputs, Matrix &target, Matrix* errors, Matrix* activateDerivative) {
auto endOfMatrix = layers - 1;
auto endTargetCol = target.scalar(-1);
auto errorSum = outputs.addition(endTargetCol);
auto endSigmaPrime = activateDerivative[endOfMatrix - 1];
errors[0] = errorSum.hadamardProduct(endSigmaPrime);
Matrix transposeOfWeights, neuralError, weightsAndError, sigmaPrimeOfWeight;
for(int i = 1 ; i < endOfMatrix; i++){
transposeOfWeights = weights[endOfMatrix -i]->transposition();
neuralError = errors[i-1];
sigmaPrimeOfWeight = activateDerivative[endOfMatrix - i - 1];
errors[i] = transposeOfWeights.matrixMultiplation(neuralError).hadamardProduct(sigmaPrimeOfWeight);
}
};
Matrix SimpleNeuralNetwork::feedForward(Matrix &input, Matrix* activatedOutputs){
Matrix weightedInputs[layers-1];
for(unsigned int layer = 0; layer < layers - 1; layer++){
auto toPutIn = (layer == 0)? input: activatedOutputs[layer - 1];
matrixCalculateWeightedInput(toPutIn, weightedInputs, layer);
matrixLogarithmicActivation(weightedInputs[layer], activatedOutputs, layer);
}
return activatedOutputs[layers-2];
}
Matrix SimpleNeuralNetwork::processImage(Matrix &input)
{
Matrix weightedInputs[layers-1];
Matrix activatedOutputs[layers-1];
for(unsigned int layer = 0; layer < layers - 1; layer++){
Matrix toPutIn = (layer == 0)? input: activatedOutputs[layer - 1];
matrixCalculateWeightedInput(toPutIn, weightedInputs, layer);
matrixLogarithmicActivation(weightedInputs[layer], activatedOutputs, layer);
}
Matrix answer = activatedOutputs[layers-2];
// Clean up dynamic memory
// for(int layer = 0; layer < layers-1; layers++){
// delete activatedOutputs[layer];
// }
// delete activatedOutputs;
return answer;
}
void SimpleNeuralNetwork::updateWeights(Matrix errors[][layers -1], Matrix activatedOutputs[][layers - 1], unsigned int sampleSize, Matrix *input)
{
// Update Weights
for(int layer = 0; layer < layers - 1; layer++){
Matrix layerError;
Matrix biasError(bias[layer]->rowCount(), 1);
for(int sample = 0; sample < sampleSize; sample++){
Matrix transposedOutput;
if(layer == layers - 2){
transposedOutput = input[sample].transposition();
} else {
transposedOutput = activatedOutputs[sample][layers - 3 - layer].transposition();
}
auto sampleLayerError = errors[sample][layer].matrixMultiplation(transposedOutput);
if(sample == 0){
layerError = sampleLayerError;
} else {
layerError.addition(sampleLayerError);
}
biasError.addition(errors[sample][layers - 2 - layer]);
}
double modifiedLearningRate = learningRate/sampleSize * -1.0;
layerError = layerError.scalar(modifiedLearningRate);
*(weights[layers - 2 - layer]) = weights[layers - 2 - layer]->addition(layerError);
biasError = biasError.scalar(modifiedLearningRate);
*(bias[layer]) = bias[layer]->addition(biasError);
}
}
void SimpleNeuralNetwork::trainWithSets(Matrix* inputs, Matrix* targets, unsigned int sampleCount) {
Matrix activatedOutputs[sampleCount][layers - 1];
Matrix activatedDerivative[layers-1];
Matrix errorsForAll[sampleCount][layers-1];
// For each training sample
for(unsigned int sample = 0; sample < sampleCount; sample++){
// 1. Feed forward
auto calculatedOutput = feedForward(inputs[sample], activatedOutputs[sample]);
// 2. Calculate the Activation Function's derivative
for(unsigned int layer = 0; layer < layers - 1; layer++){
activatedDerivative[layer] = matrixLogarithmicActivationDerivative(activatedOutputs[sample][layer]);
}
// 3. Calculate the errors
matrixCostFunction(calculatedOutput, targets[sample], errorsForAll[sample], activatedDerivative);
}
// Now that all errors are calculated for the set, update the weights.
updateWeights(errorsForAll, activatedOutputs, sampleCount, inputs);
// Finally, clean up that memory junk...
};
double SimpleNeuralNetwork::fRand()
{
return distribution(engine);
}
void SimpleNeuralNetwork::addCurrentWeightsToFile()
{
for(unsigned int i = 0; i < 1; i++){
for(unsigned int j = 0; j < weights[i]->rowCount(); j++){
for(unsigned int k = 0; k < weights[i]->colCount(); k++){
int red = 0;
int green = 0;
int blue = 0;
auto current = weights[i]->get(j,k);
int middle = 255/2;
int change = static_cast<int>(current*40);
red = blue = green = middle + change;
// if(current > 0){
// green = static_cast<int>(current * 50);
// red = 0;
// } else {
// green = 0;
// red = static_cast<int>(current * 50 * -1);
// }
weightsString += std::to_string(red) + " " + std::to_string(green) + " " + std::to_string(blue) + " ";
}
weightsString += "\n";
}
}
// Uncomment this if you want a divider between blocks
// for(int k = 0; k < 28*28; k++){
// weightsString += "255 255 255 ";
// }
// weightsString += "\n";
Matrix weirdThought(28,0);
for (unsigned int j = 0; j < weights[0]->rowCount(); j++)
{
int rowCount = -1;
int colCount = 0;
Matrix toAugment(28,28);
for (unsigned int k = 0; k < weights[0]->colCount(); k++)
{
if (k % 28 == 0)
{
colCount = 0;
rowCount++;
}
toAugment.set(rowCount, colCount, weights[0]->get(j, k));
colCount++;
}
weirdThought = weirdThought.matrixAugment(toAugment);
}
for(int i = 0; i < weirdThought.rowCount(); i++){
for(int j = 0; j < weirdThought.colCount(); j++){
if(j % 28 == 0){
weightsString2 += " 0 5 65 ";
}
auto current = weirdThought.get(i,j);
int middle = 255/2;
int change = static_cast<int>(current*40);
std::string gray = std::to_string(middle + change);
std::string white = std::to_string(255 - abs(change * 2));
// weightsString2 += gray + " " + gray + " " + gray + " ";
weightsString2 += white + " " + white + " " + white + " ";
}
weightsString2 += "\n";
}
}
| 26.449468
| 146
| 0.657215
|
14gasher
|
729af33fc72c72dec7046fabec93e97e7118f36b
| 376
|
cpp
|
C++
|
include/bits/bits.test.cpp
|
jaydee-io/bits
|
2f361478b04a809af0d52de06700bb0aab5b731a
|
[
"BSD-3-Clause"
] | null | null | null |
include/bits/bits.test.cpp
|
jaydee-io/bits
|
2f361478b04a809af0d52de06700bb0aab5b731a
|
[
"BSD-3-Clause"
] | null | null | null |
include/bits/bits.test.cpp
|
jaydee-io/bits
|
2f361478b04a809af0d52de06700bb0aab5b731a
|
[
"BSD-3-Clause"
] | null | null | null |
////////////////////////////////////////////////////////////////////////////////
// bits
//
// This file is distributed under the 3-clause Berkeley Software Distribution
// License. See LICENSE for details.
////////////////////////////////////////////////////////////////////////////////
// All headers inclusion test
#include <bits/bits.h>
| 41.777778
| 80
| 0.356383
|
jaydee-io
|
72ae520307558dac842446d3d6555c39802d9114
| 377
|
cpp
|
C++
|
src/icebox/samples/winpe_boot/main.cpp
|
Axoosha/icebox
|
99d147d5b9269222225443ce171b4fd46d8985d4
|
[
"MIT"
] | 521
|
2019-03-29T15:44:08.000Z
|
2022-03-22T09:46:19.000Z
|
src/icebox/samples/winpe_boot/main.cpp
|
Axoosha/icebox
|
99d147d5b9269222225443ce171b4fd46d8985d4
|
[
"MIT"
] | 30
|
2019-06-04T17:00:49.000Z
|
2021-09-08T20:44:19.000Z
|
src/icebox/samples/winpe_boot/main.cpp
|
Axoosha/icebox
|
99d147d5b9269222225443ce171b4fd46d8985d4
|
[
"MIT"
] | 99
|
2019-03-29T16:04:13.000Z
|
2022-03-28T16:59:34.000Z
|
#define FDP_MODULE "winpe_boot"
#include <icebox/core.hpp>
#include <icebox/log.hpp>
int main(int argc, char** argv)
{
logg::init(argc, argv);
if(argc != 2)
return FAIL(-1, "usage: winpe_boot <name>");
const auto name = std::string{argv[1]};
LOG(INFO, "starting on %s", name.data());
while(!core::attach(name))
continue;
return 0;
}
| 19.842105
| 52
| 0.602122
|
Axoosha
|
72afb56fc891ad534df0ae9d54511e672433f840
| 17,671
|
hpp
|
C++
|
include/uMon/z80/dasm.hpp
|
trevor-makes/uMon
|
484dc46be45d6eb5ed37f9235ab28d5d3bb40344
|
[
"MIT"
] | null | null | null |
include/uMon/z80/dasm.hpp
|
trevor-makes/uMon
|
484dc46be45d6eb5ed37f9235ab28d5d3bb40344
|
[
"MIT"
] | null | null | null |
include/uMon/z80/dasm.hpp
|
trevor-makes/uMon
|
484dc46be45d6eb5ed37f9235ab28d5d3bb40344
|
[
"MIT"
] | null | null | null |
// https://github.com/trevor-makes/uMon.git
// Copyright (c) 2022 Trevor Makes
// 8080/Z80 (and even x86!) opcodes are organized by octal groupings
// http://z80.info/decoding.htm is a great resource for decoding these
#pragma once
#include "uMon/z80/common.hpp"
#include "uMon/format.hpp"
#include <stdint.h>
namespace uMon {
namespace z80 {
// Print given code as hex followed by '?'
template <typename API>
void print_prefix_error(uint8_t prefix, uint8_t code) {
API::print_char('$');
format_hex8(API::print_char, prefix);
format_hex8(API::print_char, code);
API::print_char('?');
}
// Convert 1-byte immediate at addr to Operand
template <typename API>
Operand read_imm_byte(uint16_t addr, bool is_indirect = false) {
uint8_t token = TOK_IMMEDIATE | TOK_BYTE;
if (is_indirect) token |= TOK_INDIRECT;
uint16_t value = API::read_byte(addr);
return { token, value };
}
// Convert 2-byte immediate at addr to Operand
template <typename API>
Operand read_imm_word(uint16_t addr, bool is_indirect = false) {
uint8_t token = TOK_IMMEDIATE;
if (is_indirect) token |= TOK_INDIRECT;
uint8_t lsb = API::read_byte(addr);
uint8_t msb = API::read_byte(addr + 1);
uint16_t value = msb << 8 | lsb;
return { token, value };
}
// Convert displacement byte at addr to Operand
template <typename API>
Operand read_branch_disp(uint16_t addr) {
uint8_t token = TOK_IMMEDIATE;
int8_t disp = API::read_byte(addr);
uint16_t value = addr + 1 + disp;
return { token, value };
}
// Encode (IX/IY+disp) given address of displacement byte
template <typename API>
Operand read_index_ind(uint16_t addr, uint8_t prefix) {
uint8_t token = (prefix == PREFIX_IX ? TOK_IX : TOK_IY) | TOK_INDIRECT;
uint16_t value = int8_t(API::read_byte(addr));
return { token, value };
}
// Decode IN/OUT (c): ED [01 --- 00-]
uint8_t decode_in_out_c(Instruction& inst, uint8_t code) {
const bool is_out = (code & 01) == 01;
const uint8_t reg = (code & 070) >> 3;
const bool is_ind = reg == REG_M;
inst.mnemonic = is_out ? MNE_OUT : MNE_IN;
inst.operands[is_out ? 0 : 1].token = TOK_C | TOK_INDIRECT;
// NOTE reg (HL) is undefined; OUT sends 0 and IN sets flags without storing
inst.operands[is_out ? 1 : 0].token = is_ind ? TOK_UNDEFINED : REG_TOK[reg];
return 1;
}
// Decode 16-bit ADC/SBC: ED [01 --- 010]
uint8_t decode_hl_adc(Instruction& inst, uint8_t code) {
const bool is_adc = (code & 010) == 010;
const uint8_t pair = (code & 060) >> 4;
inst.mnemonic = is_adc ? MNE_ADC : MNE_SBC;
inst.operands[0].token = TOK_HL;
inst.operands[1].token = PAIR_TOK[pair];
return 1;
}
// Decode 16-bit LD ind: ED [01 --- 011]
template <typename API>
uint8_t decode_ld_pair_ind(Instruction& inst, uint16_t addr, uint8_t code) {
const bool is_load = (code & 010) == 010;
const uint8_t pair = (code & 060) >> 4;
inst.mnemonic = MNE_LD;
inst.operands[is_load ? 0 : 1].token = PAIR_TOK[pair];
inst.operands[is_load ? 1 : 0] = read_imm_word<API>(addr + 1, true);
return 3;
}
// Decode IM 0/1/2: ED [01 --- 110]
uint8_t decode_im(Instruction& inst, uint8_t code) {
inst.mnemonic = MNE_IM;
// NOTE only 0x46, 0x56, 0x5E are documented; '?' sets an undefined mode
const uint8_t mode = (code & 030) >> 3;
if (mode == 1) {
inst.operands[0].token = TOK_UNDEFINED;
} else {
inst.operands[0].token = TOK_IMMEDIATE | TOK_DIGIT;
inst.operands[0].value = mode > 0 ? mode - 1 : mode;
}
return 1;
}
// Decode LD I/R and RRD/RLD: ED [01 --- 111]
template <typename API>
uint8_t decode_ld_ir(Instruction& inst, uint8_t code) {
const bool is_rot = (code & 040) == 040; // is RRD/RLD
const bool is_load = (code & 020) == 020; // is LD A,I/R
const bool is_rl = (code & 010) == 010; // is LD -R- or RLD
if (is_rot) {
if (is_load) {
print_prefix_error<API>(PREFIX_ED, code);
} else {
inst.mnemonic = is_rl ? MNE_RLD : MNE_RRD;
}
} else {
inst.mnemonic = MNE_LD;
inst.operands[is_load ? 0 : 1].token = TOK_A;
inst.operands[is_load ? 1 : 0].token = is_rl ? TOK_R : TOK_I;
}
return 1;
}
// Decode block transfer ops: ED [10 1-- 0--]
uint8_t decode_block_ops(Instruction& inst, uint8_t code) {
static constexpr const uint8_t OPS[4][4] = {
{ MNE_LDI, MNE_LDD, MNE_LDIR, MNE_LDDR },
{ MNE_CPI, MNE_CPD, MNE_CPIR, MNE_CPDR },
{ MNE_INI, MNE_IND, MNE_INIR, MNE_INDR },
{ MNE_OUTI, MNE_OUTD, MNE_OTIR, MNE_OTDR },
};
const uint8_t op = (code & 03);
const uint8_t var = (code & 030) >> 3;
inst.mnemonic = OPS[op][var];
return 1;
}
// Disassemble extended opcodes prefixed by $ED
template <typename API>
uint8_t decode_ed(Instruction& inst, uint16_t addr) {
const uint8_t code = API::read_byte(addr);
if ((code & 0300) == 0100) {
switch (code & 07) {
case 0: case 1:
return decode_in_out_c(inst, code);
case 2:
return decode_hl_adc(inst, code);
case 3:
return decode_ld_pair_ind<API>(inst, addr, code);
case 4:
// NOTE all 1-4 codes do NEG, but only 104 is documented
inst.mnemonic = MNE_NEG;
return 1;
case 5:
// NOTE all 1-5 codes (except 115 RETI) do RETN, but only 105 is documented
inst.mnemonic = code == 0115 ? MNE_RETI : MNE_RETN;
return 1;
case 6:
return decode_im(inst, code);
case 7:
return decode_ld_ir<API>(inst, code);
}
} else if ((code & 0344) == 0240) {
return decode_block_ops(inst, code);
}
print_prefix_error<API>(PREFIX_ED, code);
return 1;
}
// Disassemble extended opcodes prefixed by $CB
template <typename API>
uint8_t decode_cb(Instruction& inst, uint16_t addr, uint8_t prefix) {
const bool has_prefix = prefix != 0;
// If prefixed, index displacement byte comes before opcode
const uint8_t code = API::read_byte(has_prefix ? addr + 1 : addr);
const uint8_t op = (code & 0300) >> 6;
const uint8_t index = (code & 070) >> 3;
const uint8_t reg = (code & 07);
// Print opcode
inst.mnemonic = op == CB_ROT ? ROT_MNE[index] : CB_MNE[op];
Operand& reg_op = inst.operands[op == CB_ROT ? 0 : 1];
// Print bit index (only for BIT/RES/SET)
if (op != CB_ROT) {
inst.operands[0].token = TOK_IMMEDIATE | TOK_DIGIT;
inst.operands[0].value = index;
}
if (has_prefix) {
if (op != CB_BIT && reg != REG_M) {
// NOTE operand other than (HL) is undocumented
// (IX/IY) is still used, but result also copied to reg
print_pgm_string<API>(MNE_STR_LD);
API::print_char(' ');
print_pgm_table<API>(TOK_STR, REG_TOK[reg]);
API::print_char(';');
}
// Print (IX/IY+disp)
reg_op = read_index_ind<API>(addr, prefix);
return 2;
} else {
// Print register operand
reg_op.token = REG_TOK[reg];
return 1;
}
}
// Disassemble relative jumps: [00 --- 000]
template <typename API>
uint8_t decode_jr(Instruction& inst, uint16_t addr, uint8_t code) {
switch (code & 070) {
case 000:
inst.mnemonic = MNE_NOP;
return 1;
case 010:
inst.mnemonic = MNE_EX;
inst.operands[0].token = TOK_AF;
inst.operands[1].token = TOK_AF;
return 1;
case 020:
inst.mnemonic = MNE_DJNZ;
inst.operands[0] = read_branch_disp<API>(addr + 1);
return 2;
case 030:
inst.mnemonic = MNE_JR;
inst.operands[0] = read_branch_disp<API>(addr + 1);
return 2;
default:
inst.mnemonic = MNE_JR;
inst.operands[0].token = COND_TOK[(code & 030) >> 3];
inst.operands[1] = read_branch_disp<API>(addr + 1);
return 2;
}
}
// Disassemble LD/ADD pair: [00 --- 001]
template <typename API>
uint8_t decode_ld_add_pair(Instruction& inst, uint16_t addr, uint8_t code, uint8_t prefix) {
const bool is_load = (code & 010) == 0;
const uint16_t pair = (code & 060) >> 4;
if (is_load) {
inst.mnemonic = MNE_LD;
inst.operands[0].token = pair_to_token(pair, prefix);
inst.operands[1] = read_imm_word<API>(addr + 1);
return 3;
} else {
inst.mnemonic = MNE_ADD;
inst.operands[0].token = pair_to_token(PAIR_HL, prefix);
inst.operands[1].token = pair_to_token(pair, prefix);
return 1;
}
}
// Disassemble indirect loads: [00 --- 010]
template <typename API>
uint8_t decode_ld_ind(Instruction& inst, uint16_t addr, uint8_t code, uint8_t prefix) {
// Decode 070 bitfield
const bool is_store = (code & 010) == 0; // A/HL is src instead of dst
const bool use_hl = (code & 060) == 040; // Use HL instead of A
const bool use_pair = (code & 040) == 0; // Use (BC/DE) instead of (nn)
Operand& op_reg = inst.operands[is_store ? 1 : 0];
Operand& op_addr = inst.operands[is_store ? 0 : 1];
// Convert instruction to tokens
inst.mnemonic = MNE_LD;
op_reg.token = use_hl ? pair_to_token(PAIR_HL, prefix) : TOK_A;
if (use_pair) {
op_addr.token = PAIR_TOK[(code & 020) >> 4] | TOK_INDIRECT;
} else {
op_addr = read_imm_word<API>(addr + 1, true);
}
// Opcodes followed by (nn) consume 2 extra bytes
return use_pair ? 1 : 3;
}
// Disassemble LD r, n: ([ix/iy]) [00 r 110] ([d]) [n]
template <typename API>
uint8_t decode_ld_reg_imm(Instruction& inst, uint16_t addr, uint8_t code, uint8_t prefix) {
const uint8_t reg = (code & 070) >> 3;
const bool has_prefix = prefix != 0;
inst.mnemonic = MNE_LD;
if (has_prefix && reg == REG_M) {
inst.operands[0] = read_index_ind<API>(addr + 1, prefix);
inst.operands[1] = read_imm_byte<API>(addr + 2);
return 3;
} else {
inst.operands[0].token = reg_to_token(reg, prefix);
inst.operands[1] = read_imm_byte<API>(addr + 1);
return 2;
}
}
// Disassemble INC/DEC: [00 --- 011/100/101]
template <typename API>
uint8_t decode_inc_dec(Instruction& inst, uint16_t addr, uint8_t code, uint8_t prefix) {
const bool is_pair = (code & 04) == 0;
const bool is_inc = is_pair ? (code & 010) == 0 : (code & 01) == 0;
inst.mnemonic = is_inc ? MNE_INC : MNE_DEC;
if (is_pair) {
const uint8_t pair = (code & 060) >> 4;
inst.operands[0].token = pair_to_token(pair, prefix);
return 1;
} else {
const bool has_prefix = prefix != 0;
const uint8_t reg = (code & 070) >> 3;
if (has_prefix && reg == REG_M) {
// Replace (HL) with (IX/IY+disp)
inst.operands[0] = read_index_ind<API>(addr + 1, prefix);
return 2;
} else {
inst.operands[0].token = reg_to_token(reg, prefix);
return 1;
}
}
}
// Decode LD r, r: [01 --- ---]
template <typename API>
uint8_t decode_ld_reg_reg(Instruction& inst, uint16_t addr, uint8_t code, uint8_t prefix) {
// Replace LD (HL),(HL) with HALT
if (code == 0x76) {
inst.mnemonic = MNE_HALT;
return 1;
}
inst.mnemonic = MNE_LD;
const uint8_t dest = (code & 070) >> 3;
const uint8_t src = (code & 07);
// If (HL) used, replace with (IX/IY+disp)
// Otherwise, replace H/L with IXH/IXL
// NOTE the latter effect is undocumented!
const bool has_prefix = prefix != 0;
const bool has_dest_index = has_prefix && dest == REG_M;
const bool has_src_index = has_prefix && src == REG_M;
const bool has_index = has_dest_index || has_src_index;
// Print destination register
if (has_dest_index) {
inst.operands[0] = read_index_ind<API>(addr + 1, prefix);
} else {
inst.operands[0].token = reg_to_token(dest, has_index ? 0 : prefix);
}
// Print source register
if (has_src_index) {
inst.operands[1] = read_index_ind<API>(addr + 1, prefix);
} else {
inst.operands[1].token = reg_to_token(src, has_index ? 0 : prefix);
}
// Skip displacement byte if (IX/IY+disp) is used
return has_index ? 2 : 1;
}
// Decode [ALU op] A, r: [10 --- ---]
template <typename API>
uint8_t decode_alu_a_reg(Instruction& inst, uint16_t addr, uint8_t code, uint8_t prefix) {
const uint8_t op = (code & 070) >> 3;
const uint8_t reg = code & 07;
const bool has_prefix = prefix != 0;
inst.mnemonic = ALU_MNE[op];
inst.operands[0].token = TOK_A;
// Print operand reg
if (has_prefix && reg == REG_M) {
inst.operands[1] = read_index_ind<API>(addr + 1, prefix);
return 2;
} else {
inst.operands[1].token = reg_to_token(reg, prefix);
return 1;
}
}
// Decode conditional RET/JP/CALL: [11 --- 000/010/100]
template <typename API>
uint8_t decode_jp_cond(Instruction& inst, uint16_t addr, uint8_t code) {
static constexpr const uint8_t OPS[] = { MNE_RET, MNE_JP, MNE_CALL };
const uint8_t op = (code & 06) >> 1;
const uint8_t cond = (code & 070) >> 3;
inst.mnemonic = OPS[op];
inst.operands[0].token = COND_TOK[cond];
if (op != 0) {
inst.operands[1] = read_imm_word<API>(addr + 1);
return 3;
} else {
return 1;
}
}
// Decode PUSH/POP/CALL/RET and misc: [11 --- -01]
template <typename API>
uint8_t decode_push_pop(Instruction& inst, uint16_t addr, uint8_t code, uint8_t prefix) {
const bool is_push = (code & 04) == 04;
switch (code & 070) {
case 010:
if (is_push) {
inst.mnemonic = MNE_CALL;
inst.operands[0] = read_imm_word<API>(addr + 1);
return 3;
} else {
inst.mnemonic = MNE_RET;
return 1;
}
case 030:
inst.mnemonic = MNE_EXX;
return 1;
case 050:
inst.mnemonic = MNE_JP;
inst.operands[0].token = pair_to_token(PAIR_HL, prefix) | TOK_INDIRECT;
return 1;
case 070:
inst.mnemonic = MNE_LD;
inst.operands[0].token = TOK_SP;
inst.operands[1].token = pair_to_token(PAIR_HL, prefix);
return 1;
default: // 000, 020, 040, 060
inst.mnemonic = is_push ? MNE_PUSH : MNE_POP;
inst.operands[0].token = pair_to_token((code & 060) >> 4, prefix, true);
return 1;
}
}
// Decode misc ops with pattern [11 --- 011]
template <typename API>
uint8_t decode_misc_hi(Instruction& inst, uint16_t addr, uint8_t code, uint8_t prefix) {
switch (code & 070) {
case 000:
inst.mnemonic = MNE_JP;
inst.operands[0] = read_imm_word<API>(addr + 1);
return 3;
case 010:
// Add 1 to size for prefix
return 1 + decode_cb<API>(inst, addr + 1, prefix);
case 020:
inst.mnemonic = MNE_OUT;
inst.operands[0] = read_imm_byte<API>(addr + 1, true);
inst.operands[1].token = TOK_A;
return 2;
case 030:
inst.mnemonic = MNE_IN;
inst.operands[0].token = TOK_A;
inst.operands[1] = read_imm_byte<API>(addr + 1, true);
return 2;
case 040:
inst.mnemonic = MNE_EX;
inst.operands[0].token = TOK_SP + TOK_INDIRECT;
inst.operands[1].token = pair_to_token(PAIR_HL, prefix);
return 1;
case 050:
// NOTE EX DE,HL unaffected by prefix
inst.mnemonic = MNE_EX;
inst.operands[0].token = TOK_DE;
inst.operands[1].token = TOK_HL;
return 1;
case 060:
inst.mnemonic = MNE_DI;
return 1;
default: // 070
inst.mnemonic = MNE_EI;
return 1;
}
}
// Decode instruction at address, returning bytes read
template <typename API>
uint8_t dasm_instruction(Instruction& inst, uint16_t addr, uint8_t prefix = 0) {
uint8_t code = API::read_byte(addr);
// Handle prefix codes
if (code == PREFIX_IX || code == PREFIX_ED || code == PREFIX_IY) {
if (prefix != 0) {
// Discard old prefix and start over
print_prefix_error<API>(prefix, code);
return 0;
} else {
// Add 1 to size for prefix
if (code == PREFIX_ED) {
return 1 + decode_ed<API>(inst, addr + 1);
} else {
return 1 + dasm_instruction<API>(inst, addr + 1, code);
}
}
}
// Decode by leading octal digit
switch (code & 0300) {
case 0000:
// Decode by trailing octal digit
switch (code & 07) {
case 0:
return decode_jr<API>(inst, addr, code);
case 1:
return decode_ld_add_pair<API>(inst, addr, code, prefix);
case 2:
return decode_ld_ind<API>(inst, addr, code, prefix);
case 6:
return decode_ld_reg_imm<API>(inst, addr, code, prefix);
case 7:
// Misc AF ops with no operands
inst.mnemonic = MISC_MNE[(code & 070) >> 3];
return 1;
default: // 3, 4, 5
return decode_inc_dec<API>(inst, addr, code, prefix);
}
case 0100:
return decode_ld_reg_reg<API>(inst, addr, code, prefix);
case 0200:
return decode_alu_a_reg<API>(inst, addr, code, prefix);
default: // 0300
// Decode by trailing octal digit
switch (code & 07) {
case 3:
return decode_misc_hi<API>(inst, addr, code, prefix);
case 6:
inst.mnemonic = ALU_MNE[(code & 070) >> 3];
inst.operands[0].token = TOK_A;
inst.operands[1] = read_imm_byte<API>(addr + 1);
return 2;
case 7:
inst.mnemonic = MNE_RST;
inst.operands[0].token = TOK_IMMEDIATE | TOK_BYTE;
inst.operands[0].value = code & 070;
return 1;
default: // 0, 1, 2, 4, 5
if ((code & 01) == 01) {
return decode_push_pop<API>(inst, addr, code, prefix);
} else {
return decode_jp_cond<API>(inst, addr, code);
}
}
}
}
template <typename API, uint8_t MAX_ROWS = 24>
uint16_t dasm_range(uint16_t addr, uint16_t end) {
for (uint8_t i = 0; i < MAX_ROWS; ++i) {
// If address has label, print it
const char* label;
if (API::get_labels().get_name(addr, label)) {
API::print_string(label);
API::print_char(':');
API::newline();
}
// Print instruction address
API::print_char(' ');
format_hex16(API::print_char, addr);
API::print_string(" ");
// Translate machine code to mnemonic and operands for printing
Instruction inst;
uint8_t size = dasm_instruction<API>(inst, addr);
if (inst.mnemonic != MNE_INVALID) {
print_instruction<API>(inst);
}
API::newline();
// Do while end does not overlap with opcode
uint16_t prev = addr;
addr += size;
if (uint16_t(end - prev) < size) { break; }
}
return addr;
}
} // namespace z80
} // namespace uMon
| 31.33156
| 92
| 0.642182
|
trevor-makes
|
72b3567c7528f0539f482e1d785f30fd80f03f91
| 1,347
|
cpp
|
C++
|
artifact/storm/src/storm/storage/jani/BooleanVariable.cpp
|
glatteis/tacas21-artifact
|
30b4f522bd3bdb4bebccbfae93f19851084a3db5
|
[
"MIT"
] | null | null | null |
artifact/storm/src/storm/storage/jani/BooleanVariable.cpp
|
glatteis/tacas21-artifact
|
30b4f522bd3bdb4bebccbfae93f19851084a3db5
|
[
"MIT"
] | null | null | null |
artifact/storm/src/storm/storage/jani/BooleanVariable.cpp
|
glatteis/tacas21-artifact
|
30b4f522bd3bdb4bebccbfae93f19851084a3db5
|
[
"MIT"
] | 1
|
2022-02-05T12:39:53.000Z
|
2022-02-05T12:39:53.000Z
|
#include "storm/storage/jani/BooleanVariable.h"
namespace storm {
namespace jani {
BooleanVariable::BooleanVariable(std::string const& name, storm::expressions::Variable const& variable) : Variable(name, variable) {
// Intentionally left empty.
}
BooleanVariable::BooleanVariable(std::string const& name, storm::expressions::Variable const& variable, storm::expressions::Expression const& initValue, bool transient) : Variable(name, variable, initValue, transient) {
// Intentionally left empty.
}
std::unique_ptr<Variable> BooleanVariable::clone() const {
return std::make_unique<BooleanVariable>(*this);
}
bool BooleanVariable::isBooleanVariable() const {
return true;
}
std::shared_ptr<BooleanVariable> makeBooleanVariable(std::string const& name, storm::expressions::Variable const& variable, boost::optional<storm::expressions::Expression> initValue, bool transient) {
if (initValue) {
return std::make_shared<BooleanVariable>(name, variable, initValue.get(), transient);
} else {
assert(!transient);
return std::make_shared<BooleanVariable>(name, variable);
}
}
}
}
| 40.818182
| 227
| 0.619896
|
glatteis
|
72b95e2a10935b40b1c584edb46bca3ff24c531e
| 1,758
|
cpp
|
C++
|
Library_Administrator_System/mainpage.cpp
|
renzibei/TGLibrary
|
5c23dafa15cc8d2eec5bf06a90cd80dedf36bf4e
|
[
"Apache-2.0"
] | 1
|
2018-09-11T04:58:39.000Z
|
2018-09-11T04:58:39.000Z
|
Library_Administrator_System/mainpage.cpp
|
renzibei/TGLibrary
|
5c23dafa15cc8d2eec5bf06a90cd80dedf36bf4e
|
[
"Apache-2.0"
] | null | null | null |
Library_Administrator_System/mainpage.cpp
|
renzibei/TGLibrary
|
5c23dafa15cc8d2eec5bf06a90cd80dedf36bf4e
|
[
"Apache-2.0"
] | null | null | null |
#include "mainpage.h"
#include "ui_mainpage.h"
#include "readermanagement.h"
#include "bookmanagement.h"
#include "record.h"
#include "confirm.h"
MainPage::MainPage(QWidget *parent) :
QDialog(parent),
ui(new Ui::MainPage)
{
ui->setupUi(this);
//this->setAttribute(Qt::WA_DeleteOnClose);
// connect(ui->Return_bt, SIGNAL(clicked()),this,SLOT(close()));
// QMovie *mainpagemovie = new QMovie(":/Image/sakura_pink1.gif");
//setMovie(mainpagemovie);
// mainpagemovie->start();
// QMovie movie = QMovie(":/Image/sakura_pink1.gif").scaledSize(this->size());
QPixmap pixmap = QPixmap(":/Image/sakura_pink1.gif").scaled(this->size());
QPalette palette(this->palette());
palette.setBrush(QPalette::Background,QBrush(pixmap));
this->setPalette(palette);
}
MainPage::~MainPage()
{
delete ui;
}
void MainPage::on_Book_bt_clicked()
{
//this->hide();
BookManagement *bookmanagement = new BookManagement(this);
// bookmanagement->setAttribute(Qt::WA_DeleteOnClose);
bookmanagement->show();
//bookmanagement->exec();
// this->show();
}
void MainPage::on_Return_bt_clicked()
{
emit sendsignal();
QApplication *app;
app->quit();
}
void MainPage::on_toolButton_2_clicked()
{
//this->hide();
ReaderManagement *readermanagement = new ReaderManagement(this);
readermanagement->show();
//readermanagement->exec();
//this->show();
}
void MainPage::on_toolButton_clicked()
{
//this->hide();
Record *record = new Record(this);
record->show();
//record->exec();
//this->show();
}
void MainPage::on_To_Confirm_button_clicked()
{
//this->hide();
Confirm *confirm = new Confirm(this);
confirm->show();
//confirm->exec();
//this->show();
}
| 23.756757
| 81
| 0.659272
|
renzibei
|
72bf703b0c2de9759ddeddbd09ee91e4ce7433e9
| 8,712
|
cpp
|
C++
|
lib/malloy/core/html/form.cpp
|
0x00002a/malloy
|
94ececf246ac2bc848235f7806439ef3be1eed73
|
[
"MIT"
] | null | null | null |
lib/malloy/core/html/form.cpp
|
0x00002a/malloy
|
94ececf246ac2bc848235f7806439ef3be1eed73
|
[
"MIT"
] | null | null | null |
lib/malloy/core/html/form.cpp
|
0x00002a/malloy
|
94ececf246ac2bc848235f7806439ef3be1eed73
|
[
"MIT"
] | null | null | null |
#include "form.hpp"
#include "multipart_parser.hpp"
#include "../utils.hpp"
#include "../http/utils.hpp"
#include <algorithm>
#include <vector>
using namespace malloy::html;
form::form(
const http::method method,
std::string action,
const encoding enc
) :
m_method(method),
m_action(std::move(action)),
m_encoding(enc)
{
}
form_field&
form::field_from_name(const std::string_view field_name)
{
const auto& it = std::find_if(
std::begin(m_fields),
std::end(m_fields),
[&field_name](const auto& ef) {
return ef.name == field_name;
}
);
if (it == std::end(m_fields))
throw std::logic_error("field with specified name does not exists.");
return *it;
}
const form_field&
form::field_from_name(const std::string_view field_name) const
{
const auto& it = std::find_if(
std::begin(m_fields),
std::end(m_fields),
[&field_name](const auto& ef) {
return ef.name == field_name;
}
);
if (it == std::end(m_fields))
throw std::logic_error("field with specified name does not exists.");
return *it;
}
// ToDo: This should be handled by malloy's core MIME-type system.
std::string
form::encoding_string() const
{
switch (m_encoding) {
case encoding::url: return "application/x-www-form-urlencoded";
case encoding::multipart: return "multipart/form-data";
case encoding::plain: return "text/plain";
}
return { };
}
bool
form::add_field(form_field&& field)
{
// Sanity check name
if (field.name.empty())
return false;
// Prevent adding a field with the same name
if (has_field(field.name))
return false;
m_fields.emplace_back(std::move(field));
return true;
}
bool
form::has_field(const std::string_view field_name) const
{
const auto& it = std::find_if(
std::cbegin(m_fields),
std::cend(m_fields),
[&field_name](const auto& ef) {
return ef.name == field_name;
}
);
return it != std::cend(m_fields);
}
bool
form::has_data(const std::string_view field_name) const
{
const auto& it = std::find_if(
std::cbegin(m_fields),
std::cend(m_fields),
[&field_name](const auto& ef) {
return ef.name == field_name;
}
);
if (it == std::cend(m_fields))
return false;
return it->has_data();
}
std::optional<form_field::parsed_data>
form::data(const std::string& field_name) const
{
// Check whether field exists
if (!has_field(field_name))
return std::nullopt;
// Retrieve field
const auto& it = std::find_if(
std::cbegin(m_fields),
std::cend(m_fields),
[&field_name](const auto& ef) {
return ef.name == field_name;
}
);
if (it == std::cend(m_fields))
return std::nullopt;
// Return field value
return it->data;
}
bool
form::has_content(const std::string_view field_name) const
{
// Check whether the field exists
if (!has_field(field_name))
return false;
// Retrieve field
const auto& field = field_from_name(field_name);
// Check if field has parsed data
if (!field.has_data())
return false;
// Check if field data has content
return !field.data->content.empty();
}
std::optional<std::string>
form::content(const std::string_view field_name) const
{
// Check whether the field exists
if (!has_field(field_name))
return std::nullopt;
// Retrieve field
const auto& field = field_from_name(field_name);
// Check if field has parsed data
if (!field.has_data())
return std::nullopt;
// Return content
return field.data->content;
}
void
form::populate_values_from_parsed_data()
{
for (auto& field : m_fields)
field.populate_value_from_parsed_data();
}
void
form::clear_values()
{
for (auto& field : m_fields)
field.value = { };
}
std::string
form::dump() const
{
std::ostringstream ss;
for (const form_field& field : m_fields) {
if (!field.has_data())
continue;
ss << field.name << ":\n";
ss << " type = " << field.data->type << "\n";
ss << " filename = " << field.data->filename << "\n";
ss << " content = " << field.data->content << "\n";
ss << "\n";
}
return ss.str();
}
bool
form::parse(const malloy::http::request<>& req)
{
switch (m_encoding) {
case encoding::url: return parse_urlencoded(req);
case encoding::multipart: return parse_multipart(req);
case encoding::plain: return parse_plain(req);
}
return false;
}
bool
form::parse_urlencoded(const malloy::http::request<>& req)
{
using namespace std::literals;
// Sanity check encoding type
if (m_encoding != encoding::url)
throw std::logic_error("form encoding type does not match");
try {
// Split pairs
const std::vector<std::string_view> pairs = split(req.body(), "&"sv);
for (const std::string_view& pair_str : pairs) {
const std::vector<std::string_view> pair = split(pair_str, "="sv);
if (pair.size() != 2)
continue;
// Perform URL decoding
std::string value{ pair[1] };
url_decode(value);
// Find field
form_field& field = field_from_name(pair[0]);
// Store value
form_field::parsed_data data;
data.content = std::move(value);
field.data = std::move(data);
}
return true;
}
catch (const std::exception&) {
return false;
}
}
bool
form::parse_multipart(const malloy::http::request<>& req)
{
using namespace std::literals;
// Sanity check encoding type
if (m_encoding != encoding::multipart)
throw std::logic_error("form encoding type does not match");
try {
// Parse
const auto& parts = multipart_parser::parse(req);
for (const multipart_parser::part& part : parts) {
// Decompose disposition
std::string locator_name{ "name=" };
std::string locator_filename{ "filename=" };
std::string_view name;
std::string_view filename;
const auto& disposition_parts = http::split_header_value(part.disposition);
for (const std::string_view& dp : disposition_parts) {
// Name
if (dp.starts_with(locator_name)) {
name = dp.substr(locator_name.size()+1, dp.size()-locator_name.size()-2); // Drop the surrounding quotation marks
continue;
}
// Filename
if (dp.starts_with(locator_filename)) {
filename = dp.substr(locator_filename.size()+1, dp.size()-locator_filename.size()-2); // Drop surrounding quotation marks
continue;
}
}
if (name.empty())
return false; // According to the 'multipart/form-data' spec the 'name' field is required
// Look for corresponding field
if (!has_field(name))
continue;
form_field& field = field_from_name(name);
// Fill field
form_field::parsed_data data;
data.dispositions = part.disposition;
data.filename = filename;
data.type = part.type;
data.content = part.content;
field.data = std::move(data);
}
}
catch (const std::exception&) {
return false;
}
return true;
}
bool
form::parse_plain(const malloy::http::request<>& req)
{
using namespace std::literals;
// Sanity check encoding type
if (m_encoding != encoding::plain)
throw std::logic_error("form encoding type does not match");
try {
// Each field is encoded as: {key}={value}\r\n
for (const std::string_view& line : split(req.body(), "\r\n"sv)) {
// Retrieve key/value
const auto& pair = split(line, "="sv);
if (pair.size() != 2)
continue;
const std::string_view& name = pair[0];
const std::string_view& value = pair[1];
// Find corresponding field
form_field& field = field_from_name(name);
// Store content
form_field::parsed_data data;
data.content = value;
field.data = std::move(data);
}
}
catch (const std::exception&) {
return false;
}
return true;
}
| 25.399417
| 143
| 0.574839
|
0x00002a
|
72c0fde0bc7663c50097a70b664016051c916e19
| 18,706
|
cpp
|
C++
|
LiveUpdate/ProgressBar/ProgressCtrlX.cpp
|
tsingfun/QuoteClient
|
180f5049e813cb8221d357c4db916cc79c7c9e02
|
[
"Apache-2.0"
] | 1
|
2021-06-29T06:07:42.000Z
|
2021-06-29T06:07:42.000Z
|
LiveUpdate/ProgressBar/ProgressCtrlX.cpp
|
tsingfun/QuoteClient
|
180f5049e813cb8221d357c4db916cc79c7c9e02
|
[
"Apache-2.0"
] | null | null | null |
LiveUpdate/ProgressBar/ProgressCtrlX.cpp
|
tsingfun/QuoteClient
|
180f5049e813cb8221d357c4db916cc79c7c9e02
|
[
"Apache-2.0"
] | 2
|
2020-12-17T11:46:52.000Z
|
2021-05-02T16:53:04.000Z
|
//####################################################################
// Comments: 在Yury Goltsman版本的基础上修改
//
// UpdateLogs:
//####################################################################
///////////////////////////////////////////////////////////////////////////////
// class CProgressCtrlX
//
// Author: Yury Goltsman
// email: ygprg@go.to
// page: http://go.to/ygprg
// Copyright ?2000, Yury Goltsman
//
// This code provided "AS IS," without warranty of any kind.
// You may freely use or modify this code provided this
// Copyright is included in all derived versions.
//
// version : 1.1
// Added multi-color gradient
// Added filling with brush for background and bar(overrides color settings)
// Added borders attribute
// Added vertical text support
// Added snake mode
// Added reverse mode
// Added dual color for text
// Added text formatting
// Added tied mode for text and rubber bar mode
// Added support for vertical oriented control(PBS_VERTICAL)
//
// version : 1.0
//
#include "stdafx.h"
#include "ProgressCtrlX.h"
#include "MemDC.h"
#include "DrawGdiX.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CProgressCtrlX
CProgressCtrlX::CProgressCtrlX()
: m_rcBorders(0,0,0,0)
{
// Init colors
m_clrBk = ::GetSysColor(COLOR_3DFACE);
m_clrTextOnBar = ::GetSysColor(COLOR_CAPTIONTEXT);
m_clrTextOnBk = ::GetSysColor(COLOR_BTNTEXT);
// set gradient colors
COLORREF clrStart, clrEnd;
clrStart = clrEnd = ::GetSysColor(COLOR_ACTIVECAPTION);
#if(WINVER >= 0x0500)
BOOL fGradientCaption = FALSE;
if(SystemParametersInfo(SPI_GETGRADIENTCAPTIONS, 0, &fGradientCaption, 0) &&
fGradientCaption)
clrEnd = ::GetSysColor(COLOR_GRADIENTACTIVECAPTION);
#endif /* WINVER >= 0x0500 */
SetGradientColors(clrStart, clrEnd);
m_nStep = 10; // according msdn
m_nTail = 0;
m_nTailSize = 40;
m_pbrBk = m_pbrBar = NULL;
}
BEGIN_MESSAGE_MAP(CProgressCtrlX, CProgressCtrl)
//{{AFX_MSG_MAP(CProgressCtrlX)
ON_WM_ERASEBKGND()
ON_WM_PAINT()
ON_WM_TIMER()
ON_MESSAGE(PBM_SETBARCOLOR, OnSetBarColor)
ON_MESSAGE(PBM_SETBKCOLOR, OnSetBkColor)
ON_MESSAGE(PBM_SETPOS, OnSetPos)
ON_MESSAGE(PBM_DELTAPOS, OnDeltaPos)
ON_MESSAGE(PBM_STEPIT, OnStepIt)
ON_MESSAGE(PBM_SETSTEP, OnSetStep)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CProgressCtrlX message handlers
BOOL CProgressCtrlX::OnEraseBkgnd(CDC* pDC)
{
// TODO: Add your message handler code here and/or call default
return TRUE; // erase in OnPaint()
}
void CProgressCtrlX::OnPaint()
{
CPaintDC dc(this); // device context for painting
// TODO: Add your message handler code here
CDrawInfo info;
GetClientRect(&info.rcClient);
// retrieve current position and range
info.nCurPos = GetPos();
GetRange(info.nLower, info.nUpper);
// Draw to memory DC
CMyMemDC memDC(&dc);
info.pDC = &memDC;
//info.rcClient.InflateRect(m_rcBorders);
// fill background
if(m_pbrBk)
memDC.FillRect(&info.rcClient, m_pbrBk);
else
memDC.FillSolidRect(&info.rcClient, m_clrBk);
// apply borders
//info.rcClient.DeflateRect(m_rcBorders);
// if current pos is out of range return
if (info.nCurPos < info.nLower || info.nCurPos > info.nUpper)
return;
info.dwStyle = GetStyle();
BOOL fVert = info.dwStyle&PBS_VERTICAL;
BOOL fSnake = info.dwStyle&PBS_SNAKE;
BOOL fRubberBar = info.dwStyle&PBS_RUBBER_BAR;
// calculate visible gradient width
CRect rcBar(0,0,0,0);//整个进度条的rect
CRect rcMax(0,0,0,0);//要描画的进度的rect
//整个进度条的rect,最右侧要么是客户区的高度(竖式),要么是宽度(横式)
rcMax.right = fVert ? info.rcClient.Height() : info.rcClient.Width();
//要描画的进度的rect
//最右侧的坐标,等于当前进度百分比乘以进度条的rect的right(也即宽度)
rcBar.right = (int)((float)(info.nCurPos-info.nLower) * rcMax.right / (info.nUpper-info.nLower));
//蛇形进度
if(fSnake)
rcBar.left = (int)((float)(m_nTail-info.nLower) * rcMax.right / (info.nUpper-info.nLower));
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Added: 2009/10/22 14:34
// comments: 边框
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
CPoint pt;
if (fVert)
{
pt.y = (info.nCurPos == info.nUpper) ? rcMax.right : rcBar.right;
pt.x = 0;
ClientToScreen(&pt);
DrawNCBorderV(pt.y);//传递屏幕坐标
}
else
{
pt.x = (info.nCurPos == info.nUpper) ? rcMax.right : rcBar.right;
pt.y = 0;
ClientToScreen(&pt);
DrawNCBorderH(pt.x);//传递屏幕坐标
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// draw bar
if(m_pbrBar)
memDC.FillRect(&ConvertToReal(info, rcBar), m_pbrBar);
else
DrawMultiGradient(info, fRubberBar ? rcBar : rcMax, rcBar);
// Draw text
DrawText(info, rcMax, rcBar);
// Do not call CProgressCtrl::OnPaint() for painting messages
}
void CProgressCtrlX::DrawMultiGradient(const CDrawInfo& info, const CRect &rcGrad, const CRect &rcClip)
{
int nSteps = (int)(m_ardwGradColors.GetSize()-1);
float nWidthPerStep = (float)rcGrad.Width() / nSteps;
CRect rcGradBand(rcGrad);
for (int i = 0; i < nSteps; i++)
{
rcGradBand.left = rcGrad.left + (int)(nWidthPerStep * i);
rcGradBand.right = rcGrad.left + (int)(nWidthPerStep * (i+1));
if(i == nSteps-1) //last step (because of problems with float)
rcGradBand.right = rcGrad.right;
if(rcGradBand.right < rcClip.left)
continue; // skip - band before cliping rect
CRect rcClipBand(rcGradBand);
if(rcClipBand.left < rcClip.left)
rcClipBand.left = rcClip.left;
if(rcClipBand.right > rcClip.right)
rcClipBand.right = rcClip.right;
DrawGradient(info, rcGradBand, rcClipBand, m_ardwGradColors[i], m_ardwGradColors[i+1]);
if(rcClipBand.right == rcClip.right)
break; // stop filling - next band is out of clipping rect
}
}
void CProgressCtrlX::DrawGradient(const CDrawInfo& info, const CRect &rcGrad, const CRect &rcClip, COLORREF clrStart, COLORREF clrEnd)
{
// Split colors to RGB chanels, find chanel with maximum difference
// between the start and end colors. This distance will determine
// number of steps of gradient
int r = (GetRValue(clrEnd) - GetRValue(clrStart));
int g = (GetGValue(clrEnd) - GetGValue(clrStart));
int b = (GetBValue(clrEnd) - GetBValue(clrStart));
int nSteps = max(abs(r), max(abs(g), abs(b)));
// if number of pixels in gradient less than number of steps -
// use it as numberof steps
int nPixels = rcGrad.Width();
nSteps = min(nPixels, nSteps);
if(nSteps == 0) nSteps = 1;
float rStep = (float)r/nSteps;
float gStep = (float)g/nSteps;
float bStep = (float)b/nSteps;
r = GetRValue(clrStart);
g = GetGValue(clrStart);
b = GetBValue(clrStart);
BOOL fLowColor = info.pDC->GetDeviceCaps(RASTERCAPS) & RC_PALETTE;
if(!fLowColor && nSteps > 1)
if(info.pDC->GetDeviceCaps(BITSPIXEL)*info.pDC->GetDeviceCaps(PLANES) < 8)
nSteps = 1; // for 16 colors no gradient
float nWidthPerStep = (float)rcGrad.Width() / nSteps;
CRect rcFill(rcGrad);
CBrush br;
// Start filling
for (int i = 0; i < nSteps; i++)
{
rcFill.left = rcGrad.left + (int)(nWidthPerStep * i);
rcFill.right = rcGrad.left + (int)(nWidthPerStep * (i+1));
if(i == nSteps-1) //last step (because of problems with float)
rcFill.right = rcGrad.right;
if(rcFill.right < rcClip.left)
continue; // skip - band before cliping rect
// clip it
if(rcFill.left < rcClip.left)
rcFill.left = rcClip.left;
if(rcFill.right > rcClip.right)
rcFill.right = rcClip.right;
COLORREF clrFill = RGB(r + (int)(i * rStep),
g + (int)(i * gStep),
b + (int)(i * bStep));
if(fLowColor)
{
br.CreateSolidBrush(clrFill);
// CDC::FillSolidRect is faster, but it does not handle 8-bit color depth
info.pDC->FillRect(&ConvertToReal(info, rcFill), &br);
br.DeleteObject();
}
else
info.pDC->FillSolidRect(&ConvertToReal(info, rcFill), clrFill);
if(rcFill.right >= rcClip.right)
break; // stop filling if we reach current position
}
}
void CProgressCtrlX::DrawText(const CDrawInfo& info, const CRect &rcMax, const CRect &rcBar)
{
if(!(info.dwStyle&PBS_TEXTMASK))
return;
BOOL fVert = info.dwStyle&PBS_VERTICAL;
CDC *pDC = info.pDC;
int nValue = 0;
CString sFormat;
GetWindowText(sFormat);
switch(info.dwStyle&PBS_TEXTMASK)
{
case PBS_SHOW_PERCENT:
if(sFormat.IsEmpty())
sFormat = "%d%%";
// retrieve current position and range
nValue = (int)((float)(info.nCurPos-info.nLower) * 100 / (info.nUpper-info.nLower));
break;
case PBS_SHOW_POSITION:
if(sFormat.IsEmpty())
sFormat = "%d";
// retrieve current position
nValue = info.nCurPos;
break;
}
if (sFormat.IsEmpty())
return;
CFont* pFont = GetFont();
CSelFont sf(pDC, pFont);
CSelTextColor tc(pDC, m_clrTextOnBar);
CSelBkMode bm(pDC, TRANSPARENT);
CSelTextAlign ta(pDC, TA_BOTTOM|TA_CENTER);
CPoint ptOrg = pDC->GetWindowOrg();
CString sText;
sText.Format(sFormat, nValue);
LONG grad = 0;
if(pFont)
{
LOGFONT lf;
pFont->GetLogFont(&lf);
grad = lf.lfEscapement/10;
}
int x = 0, y = 0, dx = 0, dy = 0;
CSize sizText = pDC->GetTextExtent(sText);
if(grad == 0) { x = sizText.cx; y = sizText.cy; dx = 0; dy = sizText.cy;}
else if(grad == 90) { x = sizText.cy; y = sizText.cx; dx = sizText.cy; dy = 0;}
else if(grad == 180) { x = sizText.cx; y = sizText.cy; dx = 0; dy = -sizText.cy;}
else if(grad == 270) { x = sizText.cy; y = sizText.cx; dx = -sizText.cy; dy = 0;}
else ASSERT(0); // angle not supported
#if 0
// required "math.h"
double pi = 3.1415926535;
double rad = grad*pi/180;
dx = sz.cy*sin(rad);
dy = sz.cy*cos(rad);
#endif
CPoint pt = pDC->GetViewportOrg();
if(info.dwStyle&PBS_TIED_TEXT)
{
CRect rcFill(ConvertToReal(info, rcBar));
if((fVert ? y : x) <= rcBar.Width())
{
pDC->SetViewportOrg(rcFill.left + (rcFill.Width() + dx)/2,
rcFill.top + (rcFill.Height() + dy)/2);
DrawClippedText(info, rcBar, sText, ptOrg);
}
}
else
{
pDC->SetViewportOrg(info.rcClient.left + (info.rcClient.Width() + dx)/2,
info.rcClient.top + (info.rcClient.Height() + dy)/2);
if(m_clrTextOnBar == m_clrTextOnBk)
// if the same color for bar and background draw text once
DrawClippedText(info, rcMax, sText, ptOrg);
else
{
// else, draw clipped parts of text
// draw text on gradient
if(rcBar.left != rcBar.right)
DrawClippedText(info, rcBar, sText, ptOrg);
// draw text out of gradient
if(rcMax.right > rcBar.right)
{
tc.Select(m_clrTextOnBk);
CRect rc(rcMax);
rc.left = rcBar.right;
DrawClippedText(info, rc, sText, ptOrg);
}
if(rcMax.left < rcBar.left)
{
tc.Select(m_clrTextOnBk);
CRect rc(rcMax);
rc.right = rcBar.left;
DrawClippedText(info, rc, sText, ptOrg);
}
}
}
pDC->SetViewportOrg(pt);
}
void CProgressCtrlX::DrawClippedText(const CDrawInfo& info, const CRect& rcClip, CString& sText, const CPoint& ptWndOrg)
{
CDC *pDC = info.pDC;
CRgn rgn;
CRect rc = ConvertToReal(info, rcClip);
rc.OffsetRect(-ptWndOrg);
rgn.CreateRectRgn(rc.left, rc.top, rc.right, rc.bottom);
pDC->SelectClipRgn(&rgn);
pDC->TextOut (0, 0, sText);
rgn.DeleteObject();
}
LRESULT CProgressCtrlX::OnSetBarColor(WPARAM clrEnd, LPARAM clrStart)
{
SetGradientColors((COLORREF)clrStart, (COLORREF)(clrEnd ? clrEnd : clrStart));
return CLR_DEFAULT;
}
LRESULT CProgressCtrlX::OnSetBkColor(WPARAM, LPARAM clrBk)
{
m_clrBk = (COLORREF)clrBk;
return CLR_DEFAULT;
}
LRESULT CProgressCtrlX::OnSetStep(WPARAM nStepInc, LPARAM)
{
m_nStep = (int)nStepInc;
return Default();
}
LRESULT CProgressCtrlX::OnSetPos(WPARAM newPos, LPARAM)
{
int nOldPos;
if(SetSnakePos(nOldPos, (int)newPos))
return nOldPos;
return Default();
}
LRESULT CProgressCtrlX::OnDeltaPos(WPARAM nIncrement, LPARAM)
{
int nOldPos;
if(SetSnakePos(nOldPos, (int)nIncrement, TRUE))
return nOldPos;
return Default();
}
LRESULT CProgressCtrlX::OnStepIt(WPARAM, LPARAM)
{
int nOldPos;
if(SetSnakePos(nOldPos, m_nStep, TRUE))
return nOldPos;
return Default();
}
/////////////////////////////////////////////////////////////////////////////
// CProgressCtrlX implementation
BOOL CProgressCtrlX::SetSnakePos(int& nOldPos, int nNewPos, BOOL fIncrement)
{
DWORD dwStyle = GetStyle();
if(!(dwStyle&PBS_SNAKE))
return FALSE;
int nLower, nUpper;
GetRange(nLower, nUpper);
if(fIncrement)
{
int nCurPos = GetPos();
if(nCurPos == nUpper && nCurPos - m_nTail < m_nTailSize )
nCurPos = m_nTail + m_nTailSize;
nNewPos = nCurPos + abs(nNewPos);
}
if(nNewPos > nUpper+m_nTailSize)
{
nNewPos -= nUpper-nLower + m_nTailSize;
if(nNewPos > nUpper + m_nTailSize)
{
ASSERT(0); // too far - reset
nNewPos = nUpper + m_nTailSize;
}
if(dwStyle&PBS_REVERSE)
ModifyStyle(PBS_REVERSE, 0);
else
ModifyStyle(0, PBS_REVERSE);
}
else if(nNewPos >= nUpper)
Invalidate();
m_nTail = nNewPos - m_nTailSize;
if(m_nTail < nLower)
m_nTail = nLower;
nOldPos = (int)DefWindowProc(PBM_SETPOS, nNewPos, 0);
return TRUE;
}
void CProgressCtrlX::SetTextFormat(LPCTSTR szFormat, DWORD ffFormat)
{
ASSERT(::IsWindow(m_hWnd));
if(!szFormat || !szFormat[0] || !ffFormat)
{
ModifyStyle(PBS_TEXTMASK, 0);
SetWindowText(_T(""));
}
else
{
ModifyStyle(PBS_TEXTMASK, ffFormat);
SetWindowText(szFormat);
}
}
CRect CProgressCtrlX::ConvertToReal(const CDrawInfo& info, const CRect& rcVirt)
{
BOOL fReverse = info.dwStyle&PBS_REVERSE;
BOOL fVert = info.dwStyle&PBS_VERTICAL;
CRect rc(info.rcClient);
if(fVert)
{
rc.top = info.rcClient.top +
(fReverse ? rcVirt.left : (info.rcClient.Height() - rcVirt.right));
rc.bottom = rc.top + rcVirt.Width();
}
else
{
rc.left = info.rcClient.left +
(fReverse ? (info.rcClient.Width() - rcVirt.right) : rcVirt.left);
rc.right = rc.left + rcVirt.Width();
}
return rc;
}
//CRect CProgressCtrlX::ConvertToReal( const CRect& rcBig, const CRect& rcDraw )
//{
// CRect rc(rcBig);
// DWORD dwStyle = GetStyle();
// BOOL fVert = dwStyle&PBS_VERTICAL;
// if(fVert)
// {
// rc.top = rcBig.top +
// (GetReverse() ? rcDraw.left : (rcBig.Height() - rcDraw.right));
// rc.bottom = rc.top + rcDraw.Width();
// }
// else
// {
// rc.left = rcBig.left +
// (GetReverse() ? (rcBig.Width() - rcDraw.right) : rcDraw.left);
// rc.right = rc.left + rcDraw.Width();
// }
// return rc;
//}
void CProgressCtrlX::SetGradientColorsX(int nCount, COLORREF clrFirst, COLORREF clrNext, ...)
{
m_ardwGradColors.SetSize(nCount);
m_ardwGradColors.SetAt(0, clrFirst);
m_ardwGradColors.SetAt(1, clrNext);
va_list pArgs;
va_start(pArgs, clrNext);
for(int i = 2; i < nCount; i++)
m_ardwGradColors.SetAt(i, va_arg(pArgs, COLORREF));
va_end( pArgs );
}
void CProgressCtrlX::OnTimer( UINT nIDEvent )
{
if(nIDEvent == AnimationTimer)
{
Animate(m_nAnimStep);
Invalidate();
}
CProgressCtrl::OnTimer(nIDEvent);
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Added: 2009/10/22 16:11
// comments: 增加对于边框的自绘
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void CProgressCtrlX::DrawNCBorderH(int pos)
{
CDC* pDC = GetWindowDC(); // window temp dc
if(pDC==NULL)
{
return;
}
CRect rcWindow; // window screen rect
int cx_Frame, cy_Frame;
cx_Frame = GetSystemMetrics(SM_CXFRAME); //X边框
cy_Frame = GetSystemMetrics(SM_CYFRAME);//Y边框
//取得窗口大小
GetWindowRect(&rcWindow);
int ipos = pos - rcWindow.left;
rcWindow.SetRect(0, 0, rcWindow.Width(), rcWindow.Height());
//一种颜色
if (m_clrBorderStart == m_clrBorderEnd)
{
CRgn rgnBig, rgnSmall;
rgnBig.CreateRectRgn(rcWindow.left, rcWindow.top, rcWindow.right, rcWindow.bottom);
rgnSmall.CreateRectRgn(rcWindow.left+cx_Frame, rcWindow.top+cy_Frame,
rcWindow.right-cx_Frame, rcWindow.bottom-cy_Frame);
rgnBig.CombineRgn(&rgnBig,&rgnSmall,RGN_XOR);
CBrush brush;
brush.CreateSolidBrush(m_clrBorderStart);
pDC->FillRgn(&rgnBig, &brush);
ReleaseDC(pDC);
DeleteObject(&brush);
return;
}
//调整矩形位置
CRect rclt,rcrt,rcl,rcr,rclb,rcrb;
rclt.SetRect(cx_Frame, 0, ipos, cy_Frame);//左上
rcl.SetRect(0, 0, cx_Frame, rcWindow.bottom);//左
rclb.SetRect(cx_Frame, rcWindow.bottom-cy_Frame, ipos, rcWindow.bottom);//左下
//rcrt.SetRect(ipos, 0, rcWindow.right-cx_Frame, cy_Frame);//右上
rcrt.SetRect(ipos, 0, rcWindow.right, cy_Frame);//右上
//rcr.SetRect(rcWindow.right-cx_Frame, 0, rcWindow.right, rcWindow.bottom);//右
//经过实践,这里右边矩形的宽度竟然不是cx_Frame而是1
rcr.SetRect(rcWindow.right-1, 0, rcWindow.right, rcWindow.bottom);//右
//rcrb.SetRect(ipos, rcWindow.bottom-cy_Frame, rcWindow.right-cx_Frame, rcWindow.bottom);//右下
rcrb.SetRect(ipos, rcWindow.bottom-cy_Frame, rcWindow.right, rcWindow.bottom);//右下
pDC->FillSolidRect(&rclt,m_clrBorderStart);
pDC->FillSolidRect(&rcl,m_clrBorderStart);
pDC->FillSolidRect(&rclb,m_clrBorderStart);
pDC->FillSolidRect(&rcrt,m_clrBorderEnd);
pDC->FillSolidRect(&rcr,m_clrBorderEnd);
pDC->FillSolidRect(&rcrb,m_clrBorderEnd);
ReleaseDC(pDC);
}
void CProgressCtrlX::DrawNCBorderV(int pos)
{
CDC* pDC = GetWindowDC(); // window temp dc
if(pDC==NULL)
{
return;
}
CRect rcWindow; // window screen rect
int cx_Frame, cy_Frame;
cx_Frame = GetSystemMetrics(SM_CXFRAME); //X边框
cy_Frame = GetSystemMetrics(SM_CYFRAME);//Y边框
//取得窗口大小
GetWindowRect(&rcWindow);
int ipos = pos - rcWindow.top;
rcWindow.SetRect(0, 0, rcWindow.Width(), rcWindow.Height());
//一种颜色
if (m_clrBorderStart == m_clrBorderEnd)
{
CRgn rgnBig, rgnSmall;
rgnBig.CreateRectRgn(rcWindow.left, rcWindow.top, rcWindow.right, rcWindow.bottom);
rgnSmall.CreateRectRgn(rcWindow.left+cx_Frame, rcWindow.top+cy_Frame,
rcWindow.right-cx_Frame, rcWindow.bottom-cy_Frame);
rgnBig.CombineRgn(&rgnBig,&rgnSmall,RGN_XOR);
CBrush brush;
brush.CreateSolidBrush(m_clrBorderStart);
pDC->FillRgn(&rgnBig, &brush);
ReleaseDC(pDC);
DeleteObject(&brush);
return;
}
//调整矩形位置
CRect rclb,rcrb,rcb,rct,rclt,rcrt;
rclb.SetRect(0, ipos, cx_Frame, rcWindow.bottom-cy_Frame);//左下
rcb.SetRect(0, rcWindow.bottom-cy_Frame, rcWindow.right, rcWindow.bottom);//下
//这里右边矩形的宽度不是cx_Frame而是1???
rcrb.SetRect(rcWindow.right-cx_Frame, ipos, rcWindow.right, rcWindow.bottom-cy_Frame);//右下
rclt.SetRect(0, cy_Frame, cx_Frame, ipos);//左上
rct.SetRect(0, 0, rcWindow.right, cy_Frame);//上
rcrt.SetRect(rcWindow.right-cx_Frame, cy_Frame, rcWindow.right, ipos);//右上
pDC->FillSolidRect(&rclb,m_clrBorderStart);
pDC->FillSolidRect(&rcb,m_clrBorderStart);
pDC->FillSolidRect(&rcrb,m_clrBorderStart);
pDC->FillSolidRect(&rclt,m_clrBorderEnd);
pDC->FillSolidRect(&rct,m_clrBorderEnd);
pDC->FillSolidRect(&rcrt,m_clrBorderEnd);
ReleaseDC(pDC);
}
| 27.83631
| 134
| 0.668609
|
tsingfun
|
72c4a2dfc277ba02f62d63126eaea0dca3a3cb68
| 1,853
|
cpp
|
C++
|
speex_resampler_cpp/src/resampler_function.cpp
|
camlorn/audio_io
|
0bc3ec765a0ace45f9757f1e9fa51fb8bfaef87d
|
[
"Unlicense"
] | null | null | null |
speex_resampler_cpp/src/resampler_function.cpp
|
camlorn/audio_io
|
0bc3ec765a0ace45f9757f1e9fa51fb8bfaef87d
|
[
"Unlicense"
] | 1
|
2015-08-17T18:37:37.000Z
|
2015-09-02T16:33:08.000Z
|
speex_resampler_cpp/src/resampler_function.cpp
|
camlorn/audio_io
|
0bc3ec765a0ace45f9757f1e9fa51fb8bfaef87d
|
[
"Unlicense"
] | null | null | null |
#include <speex_resampler_cpp.hpp>
#include <algorithm>
#include <math.h>
#include "speex_resampler.h"
namespace speex_resampler_cpp {
void staticResampler(int inputSr, int outputSr, int channels, int frames, float* data, int *outLength, float** outData) {
if(inputSr== outputSr) { //copy
float* o = (float*)calloc(channels*frames, sizeof(float));
if(o == nullptr) throw MemoryAllocationError();
std::copy(data, data+channels*frames, o);
*outLength = frames;
*outData = o;
return;
}
int err;
auto resampler=speex_resampler_init(channels, inputSr, outputSr, 10, &err);
if(resampler == nullptr || err == RESAMPLER_ERR_ALLOC_FAILED) throw MemoryAllocationError();
else if(err != RESAMPLER_ERR_SUCCESS) throw SpeexError(err);
unsigned int numer, denom;
speex_resampler_get_ratio(resampler, &numer, &denom);
//The 200 makes sure that we grab all of it.
//It is not inconceivable that we might resample by a huge rate.
//And speex doesn't let us estimate output.
//Instead of reallocating, we waste a small amount of ram here.
//this is input rate/output rate, so multiply by denom.
int size=frames*channels*denom/numer+channels*200;
float* o = (float*)calloc(size, sizeof(float));
//uframes is because speex needs an address to an unsigned int.
unsigned int written = 0, consumed;
*outLength= 0;
int remaining_in =frames, remaining_out = frames*denom/numer+200;
float* tempData=data, *tempO=o;
while(remaining_in > 0 && remaining_out > 0) {
consumed=std::min<int>(1024, remaining_in);
written=std::min(1024, remaining_out);
speex_resampler_process_interleaved_float(resampler, tempData, &consumed, tempO, &written);
remaining_in -= consumed;
remaining_out -= written;
*outLength +=written;
tempData += consumed*channels;
tempO += written*channels;
}
*outData = o;
speex_resampler_destroy(resampler);
}
}
| 37.816327
| 121
| 0.738262
|
camlorn
|
72c5b8a8d81382f59a4dac9369a8bc2ff525608d
| 10,141
|
cpp
|
C++
|
device/hatsign/src/default-prog.cpp
|
zostay/Mysook
|
3611ddf0a116d18ebc58a3050f9fe35c2684c906
|
[
"Artistic-2.0"
] | 3
|
2019-06-30T04:15:18.000Z
|
2019-12-19T17:32:07.000Z
|
device/hatsign/src/default-prog.cpp
|
zostay/Mysook
|
3611ddf0a116d18ebc58a3050f9fe35c2684c906
|
[
"Artistic-2.0"
] | null | null | null |
device/hatsign/src/default-prog.cpp
|
zostay/Mysook
|
3611ddf0a116d18ebc58a3050f9fe35c2684c906
|
[
"Artistic-2.0"
] | null | null | null |
#include <inttypes.h>
#include "ops.h"
// Sterling - ZipRecruiter
// uint32_t PROGRAM_MAIN = 1;
// uint32_t default_program[] = {
// OP_SUB, 1, OP_PUSH, 16777215, OP_PUSH, 0, OP_PUSH, 0, OP_PUSH, 2, OP_URGENCY,
// OP_PUSH, 75, OP_BRIGHTNESS, OP_SUB, 2, OP_RAND, OP_PUSH, 12632256, OP_OR,
// OP_PUSH, 0, OP_WRITE, OP_WIDTH, OP_PUSH, 2, OP_WRITE, OP_SUB, 4, OP_PUSH, 0,
// OP_FOREGROUND, OP_FILL, OP_PUSH, 0, OP_READ, OP_FOREGROUND, OP_PUSH, 2,
// OP_READ, OP_PUSH, 5, OP_SET_CURSOR, OP_PUSH, 83, OP_PUTCHAR, OP_PUSH, 116,
// OP_PUTCHAR, OP_PUSH, 101, OP_PUTCHAR, OP_PUSH, 114, OP_PUTCHAR, OP_PUSH, 108,
// OP_PUTCHAR, OP_PUSH, 105, OP_PUTCHAR, OP_PUSH, 110, OP_PUTCHAR, OP_PUSH, 103,
// OP_PUTCHAR, OP_PUSH, 2, OP_READ, OP_PUSH, 1, OP_MIN, OP_PUSH, 2, OP_WRITE,
// OP_TICK, OP_PUSH, REG_CURSOR_X, OP_GET, OP_PUSH, 2147483648, OP_GT, OP_NOT,
// OP_PUSH, 6, OP_CMP, OP_PUSH, 5, OP_GOTO, OP_SUB, 6, OP_PUSH, 4, OP_GOTO,
// OP_SUB, 5, OP_TICK, OP_TICK, OP_PUSH, 13434777, OP_PUSH, 0, OP_WRITE,
// OP_WIDTH, OP_PUSH, 2, OP_WRITE, OP_SUB, 7, OP_PUSH, 0, OP_FOREGROUND, OP_FILL,
// OP_PUSH, 0, OP_READ, OP_FOREGROUND, OP_PUSH, 2, OP_READ, OP_PUSH, 5,
// OP_SET_CURSOR, OP_PUSH, 90, OP_PUTCHAR, OP_PUSH, 105, OP_PUTCHAR, OP_PUSH,
// 112, OP_PUTCHAR, OP_PUSH, 82, OP_PUTCHAR, OP_PUSH, 101, OP_PUTCHAR, OP_PUSH,
// 99, OP_PUTCHAR, OP_PUSH, 114, OP_PUTCHAR, OP_PUSH, 117, OP_PUTCHAR, OP_PUSH,
// 105, OP_PUTCHAR, OP_PUSH, 116, OP_PUTCHAR, OP_PUSH, 101, OP_PUTCHAR, OP_PUSH,
// 114, OP_PUTCHAR, OP_PUSH, 2, OP_READ, OP_PUSH, 1, OP_MIN, OP_PUSH, 2,
// OP_WRITE, OP_TICK, OP_PUSH, REG_CURSOR_X, OP_GET, OP_PUSH, 2147483648, OP_GT,
// OP_NOT, OP_PUSH, 9, OP_CMP, OP_PUSH, 8, OP_GOTO, OP_SUB, 9, OP_PUSH, 7,
// OP_GOTO, OP_SUB, 8, OP_TICK, OP_TICK, OP_PUSH, 2, OP_GOTO, OP_SUB, 3,
// OP_RETURN, OP_HALT, OP_HALT
// };
// Async Programming
// uint32_t PROGRAM_MAIN = 1;
// uint32_t default_program[] = {
// OP_SUB, 1, OP_PUSH, 16777215, OP_PUSH, 0, OP_PUSH, 2, OP_URGENCY, OP_PUSH,
// 75, OP_BRIGHTNESS, OP_WIDTH, OP_PUSH, 1, OP_WRITE, OP_SUB, 2, OP_PUSH, 0,
// OP_FOREGROUND, OP_FILL, OP_PUSH, 0, OP_READ, OP_FOREGROUND, OP_PUSH, 1,
// OP_READ, OP_PUSH, 6, OP_SET_CURSOR, OP_PUSH, 65, OP_PUTCHAR, OP_PUSH, 83,
// OP_PUTCHAR, OP_PUSH, 89, OP_PUTCHAR, OP_PUSH, 78, OP_PUTCHAR, OP_PUSH, 67,
// OP_PUTCHAR, OP_PUSH, 32, OP_PUTCHAR, OP_PUSH, 80, OP_PUTCHAR, OP_PUSH, 82,
// OP_PUTCHAR, OP_PUSH, 79, OP_PUTCHAR, OP_PUSH, 71, OP_PUTCHAR, OP_PUSH, 82,
// OP_PUTCHAR, OP_PUSH, 65, OP_PUTCHAR, OP_PUSH, 77, OP_PUTCHAR, OP_PUSH, 77,
// OP_PUTCHAR, OP_PUSH, 73, OP_PUTCHAR, OP_PUSH, 78, OP_PUTCHAR, OP_PUSH, 71,
// OP_PUTCHAR, OP_PUSH, 32, OP_PUTCHAR, OP_PUSH, 73, OP_PUTCHAR, OP_PUSH, 78,
// OP_PUTCHAR, OP_PUSH, 32, OP_PUTCHAR, OP_PUSH, 16711680, OP_FOREGROUND,
// OP_PUSH, 80, OP_PUTCHAR, OP_PUSH, 16776960, OP_FOREGROUND, OP_PUSH, 69,
// OP_PUTCHAR, OP_PUSH, 65280, OP_FOREGROUND, OP_PUSH, 82, OP_PUTCHAR,
// OP_PUSH, 65535, OP_FOREGROUND, OP_PUSH, 76, OP_PUTCHAR, OP_PUSH, 32,
// OP_PUTCHAR, OP_PUSH, 255, OP_FOREGROUND, OP_PUSH, 54, OP_PUTCHAR, OP_PUSH,
// 1, OP_READ, OP_PUSH, 1, OP_MIN, OP_PUSH, 1, OP_WRITE, OP_TICK, OP_PUSH,
// REG_CURSOR_X, OP_GET, OP_PUSH, 2147483648, OP_GT, OP_NOT, OP_PUSH, 4,
// OP_CMP, OP_WIDTH, OP_PUSH, 1, OP_WRITE, OP_SUB, 4, OP_PUSH, 2, OP_GOTO,
// OP_SUB, 3, OP_RETURN, OP_HALT, OP_HALT
// };
// Sterling's Awful Soldering
// uint32_t PROGRAM_MAIN = 1;
// uint32_t default_program[] = {
// OP_SUB, 1, OP_PUSH, 16777215, OP_PUSH, 0, OP_PUSH, 2, OP_URGENCY, OP_PUSH,
// 75, OP_BRIGHTNESS, OP_WIDTH, OP_PUSH, 1, OP_WRITE, OP_SUB, 2, OP_PUSH, 0,
// OP_FOREGROUND, OP_FILL, OP_PUSH, 0, OP_READ, OP_FOREGROUND, OP_PUSH, 1,
// OP_READ, OP_PUSH, 6, OP_SET_CURSOR, OP_PUSH, 97, OP_PUTCHAR, OP_PUSH, 108,
// OP_PUTCHAR, OP_PUSH, 115, OP_PUTCHAR, OP_PUSH, 111, OP_PUTCHAR, OP_PUSH,
// 32, OP_PUTCHAR, OP_PUSH, 83, OP_PUTCHAR, OP_PUSH, 116, OP_PUTCHAR,
// OP_PUSH, 101, OP_PUTCHAR, OP_PUSH, 114, OP_PUTCHAR, OP_PUSH, 108,
// OP_PUTCHAR, OP_PUSH, 105, OP_PUTCHAR, OP_PUSH, 110, OP_PUTCHAR, OP_PUSH,
// 103, OP_PUTCHAR, OP_PUSH, 39, OP_PUTCHAR, OP_PUSH, 115, OP_PUTCHAR,
// OP_PUSH, 32, OP_PUTCHAR, OP_PUSH, REG_CURSOR_X, OP_GET, OP_PUSH, 5,
// OP_RAND, OP_PUSH, 3, OP_MOD, OP_ADD, OP_SET_CURSOR, OP_PUSH, 16711680,
// OP_FOREGROUND, OP_PUSH, 65, OP_PUTCHAR, OP_PUSH, REG_CURSOR_X, OP_GET,
// OP_PUSH, 5, OP_RAND, OP_PUSH, 3, OP_MOD, OP_ADD, OP_SET_CURSOR, OP_PUSH,
// 16711680, OP_FOREGROUND, OP_PUSH, 87, OP_PUTCHAR, OP_PUSH, REG_CURSOR_X,
// OP_GET, OP_PUSH, 5, OP_RAND, OP_PUSH, 3, OP_MOD, OP_ADD, OP_SET_CURSOR,
// OP_PUSH, 16711680, OP_FOREGROUND, OP_PUSH, 70, OP_PUTCHAR, OP_PUSH,
// REG_CURSOR_X, OP_GET, OP_PUSH, 5, OP_RAND, OP_PUSH, 3, OP_MOD, OP_ADD,
// OP_SET_CURSOR, OP_PUSH, 16711680, OP_FOREGROUND, OP_PUSH, 85, OP_PUTCHAR,
// OP_PUSH, 32, OP_PUTCHAR, OP_PUSH, REG_CURSOR_X, OP_GET, OP_PUSH, 5,
// OP_RAND, OP_PUSH, 3, OP_MOD, OP_ADD, OP_SET_CURSOR, OP_PUSH, 16711680,
// OP_FOREGROUND, OP_PUSH, 76, OP_PUTCHAR, OP_PUSH, REG_CURSOR_X, OP_GET,
// OP_PUSH, 6, OP_SET_CURSOR, OP_PUSH, 0, OP_READ, OP_FOREGROUND, OP_PUSH,
// 32, OP_PUTCHAR, OP_PUSH, 115, OP_PUTCHAR, OP_PUSH, 111, OP_PUTCHAR,
// OP_PUSH, 108, OP_PUTCHAR, OP_PUSH, 100, OP_PUTCHAR, OP_PUSH, 101,
// OP_PUTCHAR, OP_PUSH, 114, OP_PUTCHAR, OP_PUSH, 105, OP_PUTCHAR, OP_PUSH,
// 110, OP_PUTCHAR, OP_PUSH, 103, OP_PUTCHAR, OP_PUSH, 1, OP_READ, OP_PUSH,
// 1, OP_MIN, OP_PUSH, 1, OP_WRITE, OP_TICK, OP_PUSH, REG_CURSOR_X, OP_GET,
// OP_PUSH, 2147483648, OP_GT, OP_NOT, OP_PUSH, 4, OP_CMP, OP_WIDTH, OP_PUSH,
// 1, OP_WRITE, OP_SUB, 4, OP_PUSH, 2, OP_GOTO, OP_SUB, 3, OP_RETURN,
// OP_HALT, OP_HALT
// };
// Piles
uint32_t PROGRAM_MAIN = 6;
uint32_t default_program[] = {
OP_SUB, 1, OP_PUSH, 3, OP_READARG, OP_PUSH, 0, OP_EQ, OP_NOT, OP_PUSH, 2,
OP_CMP, OP_PUSH, 0, OP_FOREGROUND, OP_SUB, 2, OP_PUSH, 3, OP_READARG,
OP_PUSH, 1, OP_EQ, OP_NOT, OP_PUSH, 3, OP_CMP, OP_PUSH, 255,
OP_FOREGROUND, OP_SUB, 3, OP_PUSH, 3, OP_READARG, OP_PUSH, 2, OP_EQ,
OP_NOT, OP_PUSH, 4, OP_CMP, OP_PUSH, 16776960, OP_FOREGROUND, OP_SUB, 4,
OP_PUSH, 3, OP_READARG, OP_PUSH, 3, OP_EQ, OP_NOT, OP_PUSH, 5, OP_CMP,
OP_PUSH, 16711680, OP_FOREGROUND, OP_SUB, 5, OP_PUSH, 1, OP_READARG,
OP_PUSH, 2, OP_READARG, OP_PIXEL, OP_RETURN, OP_SUB, 6, OP_PUSH, 0,
OP_PUSH, 0, OP_PUSH, 0, OP_WIDTH, OP_HEIGHT, OP_MUL, OP_PUSH, 0, OP_SWAP,
OP_ALLOC, OP_PUSH, 10, OP_BRIGHTNESS, OP_PUSH, 1, OP_URGENCY, OP_PUSH, 0,
OP_FOREGROUND, OP_FILL, OP_TICK, OP_SUB, 7, OP_RAND, OP_WIDTH, OP_MOD,
OP_PUSH, 0, OP_WRITE, OP_RAND, OP_HEIGHT, OP_MOD, OP_PUSH, 1, OP_WRITE,
OP_PUSH, 0, OP_READ, OP_PUSH, 1, OP_READ, OP_WIDTH, OP_MUL, OP_ADD,
OP_PUSH, 2, OP_WRITE, OP_PUSH, 2, OP_READ, OP_PUSH, 2, OP_READ, OP_PUSH,
3, OP_ADD, OP_READ, OP_PUSH, 1, OP_ADD, OP_SWAP, OP_PUSH, 3, OP_ADD,
OP_WRITE, OP_PUSH, 2, OP_READ, OP_PUSH, 3, OP_ADD, OP_READ, OP_PUSH, 1,
OP_READ, OP_PUSH, 0, OP_READ, OP_PUSH, 1, OP_GOSUB, OP_POP, OP_POP,
OP_POP, OP_PUSH, 0, OP_PUSH, 1, OP_WRITE, OP_SUB, 9, OP_PUSH, 1, OP_READ,
OP_HEIGHT, OP_GE, OP_NOT, OP_PUSH, 11, OP_CMP, OP_PUSH, 10, OP_GOTO,
OP_SUB, 11, OP_PUSH, 0, OP_PUSH, 0, OP_WRITE, OP_SUB, 12, OP_PUSH, 0,
OP_READ, OP_WIDTH, OP_GE, OP_NOT, OP_PUSH, 14, OP_CMP, OP_PUSH, 13,
OP_GOTO, OP_SUB, 14, OP_PUSH, 0, OP_READ, OP_PUSH, 1, OP_READ, OP_WIDTH,
OP_MUL, OP_ADD, OP_PUSH, 2, OP_WRITE, OP_PUSH, 2, OP_READ, OP_PUSH, 3,
OP_ADD, OP_READ, OP_PUSH, 4, OP_GE, OP_NOT, OP_PUSH, 15, OP_CMP, OP_PUSH,
2, OP_READ, OP_PUSH, 0, OP_SWAP, OP_PUSH, 3, OP_ADD, OP_WRITE, OP_PUSH, 0,
OP_READ, OP_PUSH, 0, OP_GT, OP_NOT, OP_PUSH, 16, OP_CMP, OP_PUSH, 0,
OP_READ, OP_PUSH, 1, OP_MIN, OP_PUSH, 1, OP_READ, OP_WIDTH, OP_MUL,
OP_ADD, OP_PUSH, 2, OP_WRITE, OP_PUSH, 2, OP_READ, OP_PUSH, 2, OP_READ,
OP_PUSH, 3, OP_ADD, OP_READ, OP_PUSH, 1, OP_ADD, OP_SWAP, OP_PUSH, 3,
OP_ADD, OP_WRITE, OP_PUSH, 2, OP_READ, OP_PUSH, 3, OP_ADD, OP_READ,
OP_PUSH, 1, OP_READ, OP_PUSH, 0, OP_READ, OP_PUSH, 1, OP_MIN, OP_PUSH, 1,
OP_GOSUB, OP_POP, OP_POP, OP_POP, OP_SUB, 16, OP_PUSH, 1, OP_READ,
OP_PUSH, 0, OP_GT, OP_NOT, OP_PUSH, 17, OP_CMP, OP_PUSH, 0, OP_READ,
OP_PUSH, 1, OP_READ, OP_PUSH, 1, OP_MIN, OP_WIDTH, OP_MUL, OP_ADD,
OP_PUSH, 2, OP_WRITE, OP_PUSH, 2, OP_READ, OP_PUSH, 2, OP_READ, OP_PUSH,
3, OP_ADD, OP_READ, OP_PUSH, 1, OP_ADD, OP_SWAP, OP_PUSH, 3, OP_ADD,
OP_WRITE, OP_PUSH, 2, OP_READ, OP_PUSH, 3, OP_ADD, OP_READ, OP_PUSH, 1,
OP_READ, OP_PUSH, 1, OP_MIN, OP_PUSH, 0, OP_READ, OP_PUSH, 1, OP_GOSUB,
OP_POP, OP_POP, OP_POP, OP_SUB, 17, OP_PUSH, 0, OP_READ, OP_WIDTH,
OP_PUSH, 1, OP_MIN, OP_LT, OP_NOT, OP_PUSH, 18, OP_CMP, OP_PUSH, 0,
OP_READ, OP_PUSH, 1, OP_ADD, OP_PUSH, 1, OP_READ, OP_WIDTH, OP_MUL,
OP_ADD, OP_PUSH, 2, OP_WRITE, OP_PUSH, 2, OP_READ, OP_PUSH, 2, OP_READ,
OP_PUSH, 3, OP_ADD, OP_READ, OP_PUSH, 1, OP_ADD, OP_SWAP, OP_PUSH, 3,
OP_ADD, OP_WRITE, OP_PUSH, 2, OP_READ, OP_PUSH, 3, OP_ADD, OP_READ,
OP_PUSH, 1, OP_READ, OP_PUSH, 0, OP_READ, OP_PUSH, 1, OP_ADD, OP_PUSH, 1,
OP_GOSUB, OP_POP, OP_POP, OP_POP, OP_SUB, 18, OP_PUSH, 1, OP_READ,
OP_HEIGHT, OP_PUSH, 1, OP_MIN, OP_LT, OP_NOT, OP_PUSH, 19, OP_CMP,
OP_PUSH, 0, OP_READ, OP_PUSH, 1, OP_READ, OP_PUSH, 1, OP_ADD, OP_WIDTH,
OP_MUL, OP_ADD, OP_PUSH, 2, OP_WRITE, OP_PUSH, 2, OP_READ, OP_PUSH, 2,
OP_READ, OP_PUSH, 3, OP_ADD, OP_READ, OP_PUSH, 1, OP_ADD, OP_SWAP,
OP_PUSH, 3, OP_ADD, OP_WRITE, OP_PUSH, 2, OP_READ, OP_PUSH, 3, OP_ADD,
OP_READ, OP_PUSH, 1, OP_READ, OP_PUSH, 1, OP_ADD, OP_PUSH, 0, OP_READ,
OP_PUSH, 1, OP_GOSUB, OP_POP, OP_POP, OP_POP, OP_SUB, 19, OP_SUB, 15,
OP_PUSH, 0, OP_READ, OP_PUSH, 1, OP_ADD, OP_PUSH, 0, OP_WRITE, OP_PUSH,
12, OP_GOTO, OP_SUB, 13, OP_PUSH, 1, OP_READ, OP_PUSH, 1, OP_ADD, OP_PUSH,
1, OP_WRITE, OP_PUSH, 9, OP_GOTO, OP_SUB, 10, OP_TICK, OP_PUSH, 7,
OP_GOTO, OP_SUB, 8, OP_RETURN, OP_HALT, OP_HALT
};
| 67.15894
| 85
| 0.688492
|
zostay
|
72c9819da8197c0addbfddc5f681bedb8a9e996f
| 3,587
|
hpp
|
C++
|
include/aluminum/utils/meta.hpp
|
shjwudp/Aluminum
|
046c209adc160522ee557ad5022fe372b738d38a
|
[
"Apache-2.0"
] | 48
|
2018-09-28T22:09:25.000Z
|
2021-11-18T05:24:53.000Z
|
include/aluminum/utils/meta.hpp
|
PrisdxMeany/Aluminum
|
49dbbde15ea2202eb0fe246da73ccf39df59e2e2
|
[
"Apache-2.0"
] | 51
|
2018-09-26T21:03:50.000Z
|
2021-11-12T18:21:12.000Z
|
include/aluminum/utils/meta.hpp
|
PrisdxMeany/Aluminum
|
49dbbde15ea2202eb0fe246da73ccf39df59e2e2
|
[
"Apache-2.0"
] | 19
|
2018-09-14T23:01:53.000Z
|
2021-08-12T04:13:18.000Z
|
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2018, Lawrence Livermore National Security, LLC. Produced at the
// Lawrence Livermore National Laboratory in collaboration with University of
// Illinois Urbana-Champaign.
//
// Written by the LBANN Research Team (N. Dryden, N. Maruyama, et al.) listed in
// the CONTRIBUTORS file. <lbann-dev@llnl.gov>
//
// LLNL-CODE-756777.
// All rights reserved.
//
// This file is part of Aluminum GPU-aware Communication Library. For details, see
// http://software.llnl.gov/Aluminum or https://github.com/LLNL/Aluminum.
//
// Licensed under the Apache License, Version 2.0 (the "Licensee"); 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.
////////////////////////////////////////////////////////////////////////////////
#pragma once
#include <type_traits>
#include <array>
namespace Al {
namespace internal {
/** True if x is a power of 2 (0 is not a power of 2). */
template <typename T>
constexpr bool is_pow2(T x) {
static_assert(std::is_integral<T>::value, "T must be integral");
static_assert(std::is_unsigned<T>::value, "T must be unsigned");
return x && !(x & (x - 1));
}
/** The next highest power of 2, or x if x is a power of 2. */
template <typename T>
constexpr typename std::enable_if<sizeof(T) == 4, T>::type
next_highest_pow2(T x) {
static_assert(std::is_integral<T>::value, "T must be integral");
static_assert(std::is_unsigned<T>::value, "T must be unsigned");
--x;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return x + 1;
}
template <typename T>
constexpr typename std::enable_if<sizeof(T) == 8, T>::type
next_highest_pow2(T x) {
static_assert(std::is_integral<T>::value, "T must be integral");
static_assert(std::is_unsigned<T>::value, "T must be unsigned");
--x;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
x |= x >> 32;
return x + 1;
}
/** The floor of log base 2 of x. */
template <typename T>
constexpr T floor_log2(T x) {
static_assert(std::is_integral<T>::value, "T must be integral");
static_assert(std::is_unsigned<T>::value, "T must be unsigned");
T b = 0;
while (x >>= 1) {
++b;
}
return b;
}
/** The ceiling of log base 2 of x. */
template <typename T>
constexpr T ceil_log2(T x) {
T b = floor_log2(x);
return is_pow2(x) ? b : b + 1;
}
/** Return the number of powers of 2 between Start and End, inclusive. */
template <typename T, T Start, T End>
constexpr T num_pow2s_between() {
static_assert(End >= Start, "Must have End >= Start");
return floor_log2(End) - floor_log2(Start) + (is_pow2(Start) ? 1 : 0);
}
/** Return an array of all powers of 2 between Start and End, inclusive. */
template <typename T, T Start, T End>
constexpr std::array<T, num_pow2s_between<T, Start, End>()> pow2_ar() {
static_assert(Start != 0 && End != 0, "Start and End must be non-zero");
constexpr size_t N = num_pow2s_between<T, Start, End>();
std::array<T, N> a{};
for (size_t i = 0, v = next_highest_pow2(Start); i < N; ++i, v <<= 1) {
a[i] = v;
}
return a;
}
} // namespace internal
} // namespace Al
| 31.464912
| 82
| 0.631168
|
shjwudp
|
72d9e99cbb1431f3e75514fdf594caad431fd8c9
| 804
|
cpp
|
C++
|
hiro/cocoa/widget/table-view-header.cpp
|
mp-lee/higan
|
c38a771f2272c3ee10fcb99f031e982989c08c60
|
[
"Intel",
"ISC"
] | 38
|
2018-04-05T05:00:05.000Z
|
2022-02-06T00:02:02.000Z
|
hiro/cocoa/widget/table-view-header.cpp
|
mp-lee/higan
|
c38a771f2272c3ee10fcb99f031e982989c08c60
|
[
"Intel",
"ISC"
] | 1
|
2018-04-29T19:45:14.000Z
|
2018-04-29T19:45:14.000Z
|
hiro/cocoa/widget/table-view-header.cpp
|
libretro-mirrors/higan
|
8617711ea2c201a33442266945dc7ed186e9d695
|
[
"Intel",
"ISC"
] | 8
|
2018-04-16T22:37:46.000Z
|
2021-02-10T07:37:03.000Z
|
#if defined(Hiro_TableView)
namespace hiro {
auto pTableViewHeader::construct() -> void {
}
auto pTableViewHeader::destruct() -> void {
}
auto pTableViewHeader::append(sTableViewColumn column) -> void {
}
auto pTableViewHeader::remove(sTableViewColumn column) -> void {
}
auto pTableViewHeader::setVisible(bool visible) -> void {
@autoreleasepool {
if(auto pTableView = _parent()) {
if(visible) {
[[pTableView->cocoaView content] setHeaderView:[[[NSTableHeaderView alloc] init] autorelease]];
} else {
[[pTableView->cocoaView content] setHeaderView:nil];
}
}
}
}
auto pTableViewHeader::_parent() -> maybe<pTableView&> {
if(auto parent = self().parentTableView()) {
if(auto self = parent->self()) return *self;
}
return nothing;
}
}
#endif
| 20.615385
| 103
| 0.671642
|
mp-lee
|
72e2dab59273a1f989931518b23f7c1e4c753bfd
| 1,835
|
cpp
|
C++
|
Tests/TestsRosicAndRapt/Source/rosic_tests/PortedFromRSLib/RSLib/Core/Misc/Parameter.cpp
|
RobinSchmidt/RS-MET-Preliminary
|
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
|
[
"FTL"
] | 34
|
2017-04-19T18:26:02.000Z
|
2022-02-15T17:47:26.000Z
|
Tests/TestsRosicAndRapt/Source/rosic_tests/PortedFromRSLib/RSLib/Core/Misc/Parameter.cpp
|
RobinSchmidt/RS-MET-Preliminary
|
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
|
[
"FTL"
] | 307
|
2017-05-04T21:45:01.000Z
|
2022-02-03T00:59:01.000Z
|
Tests/TestsRosicAndRapt/Source/rosic_tests/PortedFromRSLib/RSLib/Core/Misc/Parameter.cpp
|
RobinSchmidt/RS-MET-Preliminary
|
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
|
[
"FTL"
] | 4
|
2017-09-05T17:04:31.000Z
|
2021-12-15T21:24:28.000Z
|
#include "Parameter.h" // remove later
// construction/destruction:
rsNumericParameter::rsNumericParameter()
{
toString = &rsDoubleToString2;
value = 0.0;
defaultValue = 0.0;
normalizedValue = 0.0;
mapper = new rsRealLinearMap;
}
rsNumericParameter::rsNumericParameter(const rsString& name, double minValue, double maxValue,
double defaultValue, DoubleToStringFunctionPointer toStringFunction, int scaling,
const rsString& unit)
{
this->name = name;
this->unit = unit;
this->toString = toStringFunction;
this->defaultValue = defaultValue;
switch( scaling )
{
case EXPONENTIAL: mapper = new rsRealLinToExpMap(0.0, minValue, 1.0, maxValue); break;
default: mapper = new rsRealLinearMap( 0.0, minValue, 1.0, maxValue);
}
setValue(defaultValue);
}
rsNumericParameter::~rsNumericParameter()
{
deleteAllCallbacks();
delete mapper;
}
// setup:
void rsNumericParameter::addCallback(rsCallbackBase1<void, double> *callbackToAdd)
{
callbacks.push_back(callbackToAdd);
}
void rsNumericParameter::deleteAllCallbacks()
{
for(unsigned int i = 0; i < callbacks.size(); i++)
delete[] callbacks[i];
callbacks.clear();
}
void rsNumericParameter::setNormalizedValue(double newNormalizedValue)
{
normalizedValue = rsClipToRange(newNormalizedValue, 0.0, 1.0);
value = mapper->evaluate(normalizedValue);
invokeCallbacks();
}
void rsNumericParameter::setValue(double newValue)
{
setNormalizedValue(mapper->evaluateInverse(newValue));
}
void rsNumericParameter::setMapper(rsRealFunctionInvertible *newMapper)
{
rsAssert( newMapper != mapper );
delete mapper;
mapper = newMapper;
}
// misc:
void rsNumericParameter::invokeCallbacks()
{
for(unsigned int i = 0; i < callbacks.size(); i++)
callbacks[i]->call(value);
}
| 23.831169
| 95
| 0.712807
|
RobinSchmidt
|
72e480dffb4efaead0f6530a81f6392b9f2db015
| 1,250
|
cpp
|
C++
|
Sourcecode/private/mx/api/EncodingData.cpp
|
Webern/MxOld
|
822f5ccc92363ddff118e3aa3a048c63be1e857e
|
[
"MIT"
] | 45
|
2019-04-16T19:55:08.000Z
|
2022-02-14T02:06:32.000Z
|
Sourcecode/private/mx/api/EncodingData.cpp
|
Webern/MxOld
|
822f5ccc92363ddff118e3aa3a048c63be1e857e
|
[
"MIT"
] | 70
|
2019-04-07T22:45:21.000Z
|
2022-03-03T15:35:59.000Z
|
Sourcecode/private/mx/api/EncodingData.cpp
|
Webern/MxOld
|
822f5ccc92363ddff118e3aa3a048c63be1e857e
|
[
"MIT"
] | 21
|
2019-05-13T13:59:06.000Z
|
2022-03-25T02:21:05.000Z
|
// MusicXML Class Library
// Copyright (c) by Matthew James Briggs
// Distributed under the MIT License
#include "mx/api/EncodingData.h"
#include "mx/core/Date.h"
namespace mx
{
namespace api
{
////////////////////////////////////////////////////////////////////////////////
// CTOR AND COPY ///////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
EncodingDate EncodingDate::today()
{
const auto d = mx::core::Date::today();
mx::api::EncodingDate result{};
result.year = d.getYear();
result.month = d.getMonth();
result.day = d.getDay();
return result;
}
////////////////////////////////////////////////////////////////////////////////
// PUBLIC FUNCTIONS ////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// PRIVATE FUNCTIONS ///////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
}
}
| 32.894737
| 80
| 0.264
|
Webern
|
72e853517c358ae7609e5785e4db3a31aed22f98
| 5,117
|
cpp
|
C++
|
ext/oxt/backtrace.cpp
|
halorgium/passenger
|
6d64144b1c57e5b7788537fe07dca1f3e9e7c388
|
[
"MIT"
] | 2
|
2016-05-09T12:12:02.000Z
|
2016-06-28T08:44:36.000Z
|
ext/oxt/backtrace.cpp
|
halorgium/passenger
|
6d64144b1c57e5b7788537fe07dca1f3e9e7c388
|
[
"MIT"
] | null | null | null |
ext/oxt/backtrace.cpp
|
halorgium/passenger
|
6d64144b1c57e5b7788537fe07dca1f3e9e7c388
|
[
"MIT"
] | null | null | null |
/*
* OXT - OS eXtensions for boosT
* Provides important functionality necessary for writing robust server software.
*
* Copyright (c) 2008 Phusion
*
* 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.
*/
#if !(defined(NDEBUG) || defined(OXT_DISABLE_BACKTRACES))
#include <boost/thread/mutex.hpp>
#include <boost/thread/tss.hpp>
#include <sstream>
#include <cstring>
#include "backtrace.hpp"
namespace oxt {
boost::mutex _thread_registration_mutex;
list<thread_registration *> _registered_threads;
// Register main thread.
static initialize_backtrace_support_for_this_thread main_thread_initialization("Main thread");
/*
* boost::thread_specific_storage is pretty expensive. So we use the __thread
* keyword whenever possible - that's almost free.
* GCC supports the __thread keyword on x86 since version 3.3, but versions earlier
* than 4.1.2 have bugs (http://gcc.gnu.org/ml/gcc-bugs/2006-09/msg02275.html).
*/
#define GCC_VERSION (__GNUC__ * 10000 \
+ __GNUC_MINOR__ * 100 \
+ __GNUC_PATCHLEVEL__)
/*
* FreeBSD 5 supports the __thread keyword, and everything works fine in
* micro-tests, but in mod_passenger the thread-local variables are initialized
* to unaligned addresses for some weird reason, thereby causing bus errors.
*
* GCC on OpenBSD supports __thread, but any access to such a variable
* results in a segfault.
*
* Solaris does support __thread, but often it's not compiled into default GCC
* packages (not to mention it's not available for Sparc). Playing it safe...
*
* MacOS X doesn't support __thread at all.
*/
#if GCC_VERSION >= 40102 && !defined(__FreeBSD__) && \
!defined(__SOLARIS__) && !defined(__OpenBSD__) && !defined(__APPLE__)
static __thread spin_lock *backtrace_lock = NULL;
static __thread vector<trace_point *> *current_backtrace = NULL;
void
_init_backtrace_tls() {
backtrace_lock = new spin_lock();
current_backtrace = new vector<trace_point *>();
current_backtrace->reserve(50);
}
void
_finalize_backtrace_tls() {
delete backtrace_lock;
delete current_backtrace;
}
spin_lock *
_get_backtrace_lock() {
return backtrace_lock;
}
vector<trace_point *> *
_get_current_backtrace() {
return current_backtrace;
}
#else
static thread_specific_ptr<spin_lock> backtrace_lock;
static thread_specific_ptr< vector<trace_point *> > current_backtrace;
void _init_backtrace_tls() {
// Not implemented.
}
void _finalize_backtrace_tls() {
// Not implemented.
}
spin_lock *
_get_backtrace_lock() {
spin_lock *result;
result = backtrace_lock.get();
if (OXT_UNLIKELY(result == NULL)) {
result = new spin_lock();
backtrace_lock.reset(result);
}
return result;
}
vector<trace_point *> *
_get_current_backtrace() {
vector<trace_point *> *result;
result = current_backtrace.get();
if (OXT_UNLIKELY(result == NULL)) {
result = new vector<trace_point *>();
current_backtrace.reset(result);
}
return result;
}
#endif
template<typename Iterable, typename ReverseIterator> static string
format_backtrace(Iterable backtrace_list) {
if (backtrace_list->empty()) {
return " (empty)";
} else {
stringstream result;
ReverseIterator it;
for (it = backtrace_list->rbegin(); it != backtrace_list->rend(); it++) {
trace_point *p = *it;
result << " in '" << p->function << "'";
if (p->source != NULL) {
const char *source = strrchr(p->source, '/');
if (source != NULL) {
source++;
} else {
source = p->source;
}
result << " (" << source << ":" << p->line << ")";
}
result << endl;
}
return result.str();
}
}
string
_format_backtrace(const list<trace_point *> *backtrace_list) {
return format_backtrace<
const list<trace_point *> *,
list<trace_point *>::const_reverse_iterator
>(backtrace_list);
}
string
_format_backtrace(const vector<trace_point *> *backtrace_list) {
return format_backtrace<
const vector<trace_point *> *,
vector<trace_point *>::const_reverse_iterator
>(backtrace_list);
}
} // namespace oxt
#endif
| 29.073864
| 94
| 0.712722
|
halorgium
|
639ff0032cd315b1bed5851fb1959b871aeb538a
| 4,602
|
cpp
|
C++
|
tests/Matrix/Basic_op_test.cpp
|
eHonnef/Mafs
|
f78e40f485e6d044600ec932ced3e4c4de3509b9
|
[
"MIT"
] | 1
|
2022-01-17T00:46:33.000Z
|
2022-01-17T00:46:33.000Z
|
tests/Matrix/Basic_op_test.cpp
|
eHonnef/Mafs
|
f78e40f485e6d044600ec932ced3e4c4de3509b9
|
[
"MIT"
] | null | null | null |
tests/Matrix/Basic_op_test.cpp
|
eHonnef/Mafs
|
f78e40f485e6d044600ec932ced3e4c4de3509b9
|
[
"MIT"
] | null | null | null |
#include <doctest/doctest.h>
#include <mafs/Matrix/basic_op.cc>
typedef basic_op OP;
TEST_CASE("Matrix transposition") {
Matrix<int> a({{0, 1, 2}, {3, 4, 5}});
Matrix<int> b = OP::transpose(a);
// {0,3}
// {1,4}
// {2,5}
REQUIRE(b.rows() == 3);
REQUIRE(b.cols() == 2);
REQUIRE(b.at(0, 0) == 0);
REQUIRE(b.at(0, 1) == 3);
REQUIRE(b.at(1, 0) == 1);
REQUIRE(b.at(1, 1) == 4);
REQUIRE(b.at(2, 0) == 2);
REQUIRE(b.at(2, 1) == 5);
}
TEST_CASE("Upper triangular matrix") {
Matrix<int> a(10, 10, 7);
a = OP::u_triangular(a);
for (auto i = a.rows(); i-- > 0;)
for (auto j = i; j-- > i;)
REQUIRE(a.at(i, j) == 7);
for (unsigned i = 1; i < a.rows(); ++i)
for (unsigned j = 0; j < i; ++j)
REQUIRE(a.at(i, j) == 0);
}
TEST_CASE("Lower triangular matrix") {
Matrix<int> a(10, 10, 7);
a = OP::l_triangular(a);
for (auto i = a.rows(); i-- > 0;)
for (auto j = i; j-- > i;)
REQUIRE(a.at(i, j) == 0);
for (unsigned i = 1; i < a.rows(); ++i)
for (unsigned j = 0; j < i; ++j)
REQUIRE(a.at(i, j) == 7);
}
TEST_CASE("LU decomposition") {
Matrix<double> a({{0.448, 0.832, 0.193}, {0.421, 0.784, -0.207}, {-0.319, 0.884, 0.279}});
Matrix<double> LU(a.rows(), a.cols());
OP::LUP_doolittle(a, LU);
REQUIRE(LU.at(0, 0) == doctest::Approx(0.448).epsilon(0.001));
REQUIRE(LU.at(0, 1) == doctest::Approx(0.832).epsilon(0.001));
REQUIRE(LU.at(0, 2) == doctest::Approx(0.193).epsilon(0.0001));
REQUIRE(LU.at(1, 0) == doctest::Approx(-0.712).epsilon(0.001));
REQUIRE(LU.at(1, 1) == doctest::Approx(1.476).epsilon(0.001));
REQUIRE(LU.at(1, 2) == doctest::Approx(0.416).epsilon(0.01));
REQUIRE(LU.at(2, 0) == doctest::Approx(0.939).epsilon(0.001));
REQUIRE(LU.at(2, 1) == doctest::Approx(0.0014).epsilon(0.1));
REQUIRE(LU.at(2, 2) == doctest::Approx(-0.388).epsilon(0.01));
}
TEST_CASE("LU decomposition split") {
Matrix<int> LU({{1, 2, 3}, {7, 8, 4}, {5, 6, 9}});
Matrix<int> L(LU.rows(), LU.rows());
Matrix<int> U(LU.rows(), LU.rows());
OP::split_LU_doolittle(LU, L, U);
REQUIRE(L.at(0, 0) == 1);
REQUIRE(L.at(0, 1) == 0);
REQUIRE(L.at(0, 2) == 0);
REQUIRE(L.at(1, 0) == 7);
REQUIRE(L.at(1, 1) == 1);
REQUIRE(L.at(1, 2) == 0);
REQUIRE(L.at(2, 0) == 5);
REQUIRE(L.at(2, 1) == 6);
REQUIRE(L.at(2, 2) == 1);
REQUIRE(U.at(0, 0) == 1);
REQUIRE(U.at(0, 1) == 2);
REQUIRE(U.at(0, 2) == 3);
REQUIRE(U.at(1, 0) == 0);
REQUIRE(U.at(1, 1) == 8);
REQUIRE(U.at(1, 2) == 4);
REQUIRE(U.at(2, 0) == 0);
REQUIRE(U.at(2, 1) == 0);
REQUIRE(U.at(2, 2) == 9);
}
TEST_CASE("Matrix determinant") {
Matrix<double> a({{0.448, 0.832, 0.193}, {0.421, 0.784, -0.207}, {-0.319, 0.884, 0.279}});
REQUIRE(OP::determinant(a) == doctest::Approx(0.2572821));
}
TEST_CASE("Identity Matrix") {
Matrix<int> a = OP::identity<int>(10);
for (auto i = 0; i < 10; ++i) {
for (auto j = 0; j < 10; ++j) {
if (i == j)
REQUIRE(a.at(i, j) == 1);
else
REQUIRE(a.at(i, j) == 0);
}
}
}
TEST_CASE("LU doolittle solver") {
Matrix<double> A({{0.448, 0.832, 0.193}, {0.421, 0.784, -0.207}, {-0.319, 0.884, 0.279}});
Matrix<double> B({{1}, {2}, {0}});
Matrix<double> LU(A.rows(), A.cols());
Matrix<int> P = OP::LUP_doolittle(A, LU);
Matrix<double> y = OP::solve_LU_doolittle(LU, B, P);
REQUIRE(y.at(0, 0) == doctest::Approx(1.082).epsilon(0.01));
REQUIRE(y.at(1, 0) == doctest::Approx(1.251).epsilon(0.001));
REQUIRE(y.at(2, 0) == doctest::Approx(-2.723).epsilon(0.001));
}
TEST_CASE("Inverse Matrix") {
Matrix<double> a({{1, 2, 3}, {0, 1, 4}, {5, 6, 0}});
a = OP::inverse(a);
REQUIRE(a.at(0, 0) == doctest::Approx(-24));
REQUIRE(a.at(0, 1) == doctest::Approx(18));
REQUIRE(a.at(0, 2) == doctest::Approx(5));
REQUIRE(a.at(1, 0) == doctest::Approx(20));
REQUIRE(a.at(1, 1) == doctest::Approx(-15));
REQUIRE(a.at(1, 2) == doctest::Approx(-4));
REQUIRE(a.at(2, 0) == doctest::Approx(-5));
REQUIRE(a.at(2, 1) == doctest::Approx(4));
REQUIRE(a.at(2, 2) == doctest::Approx(1));
}
TEST_CASE("Further LU decomposition test") {
// PA = LU
// det(PA) == det(LU)
Matrix<double> A({{1, 2, 3, 4}, {1, 2, -3, -4}, {-1, 0, 2, 3}, {1, -4, -1, 1}});
Matrix<double> LU(A.rows());
Matrix<int> P = OP::make_pivot(OP::LUP_doolittle(A, LU));
Matrix<double> L(LU.rows());
Matrix<double> U(LU.rows());
OP::split_LU_doolittle(LU, L, U);
Matrix<double> b = OP::multiplication<double>(L, U);
Matrix<double> c = OP::multiplication<double>(P, A);
REQUIRE(c == b);
REQUIRE(OP::determinant(c) == doctest::Approx(OP::determinant(b)));
}
| 29.312102
| 92
| 0.547588
|
eHonnef
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.