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
sequencelengths 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
sequencelengths 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
sequencelengths 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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f2bb6efe0f31897af8c8c46b56d5e298bf6d645d | 385 | hpp | C++ | library/ATF/tagLITEM.hpp | lemkova/Yorozuya | f445d800078d9aba5de28f122cedfa03f26a38e4 | [
"MIT"
] | 29 | 2017-07-01T23:08:31.000Z | 2022-02-19T10:22:45.000Z | library/ATF/tagLITEM.hpp | kotopes/Yorozuya | 605c97d3a627a8f6545cc09f2a1b0a8afdedd33a | [
"MIT"
] | 90 | 2017-10-18T21:24:51.000Z | 2019-06-06T02:30:33.000Z | library/ATF/tagLITEM.hpp | kotopes/Yorozuya | 605c97d3a627a8f6545cc09f2a1b0a8afdedd33a | [
"MIT"
] | 44 | 2017-12-19T08:02:59.000Z | 2022-02-24T23:15:01.000Z | // This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
START_ATF_NAMESPACE
struct tagLITEM
{
unsigned int mask;
int iLink;
unsigned int state;
unsigned int stateMask;
wchar_t szID[48];
wchar_t szUrl[2084];
};
END_ATF_NAMESPACE
| 20.263158 | 108 | 0.657143 | lemkova |
f2bcb1eb081756a5c394ddceead203a6b2b9a8fe | 515 | hpp | C++ | Engine/Code/Engine/Math/Ray2.hpp | tonyatpeking/SmuSpecialTopic | b61d44e4efacb3c504847deb4d00234601bca49c | [
"MIT"
] | null | null | null | Engine/Code/Engine/Math/Ray2.hpp | tonyatpeking/SmuSpecialTopic | b61d44e4efacb3c504847deb4d00234601bca49c | [
"MIT"
] | null | null | null | Engine/Code/Engine/Math/Ray2.hpp | tonyatpeking/SmuSpecialTopic | b61d44e4efacb3c504847deb4d00234601bca49c | [
"MIT"
] | 1 | 2019-10-02T01:48:54.000Z | 2019-10-02T01:48:54.000Z | #pragma once
#include "Engine/Math/Vec2.hpp"
class Ray3;
class Ray2
{
public:
// This is not normalized so that the Evaluate T will match with the 3D version
static Ray2 FromRay3XZ( const Ray3& ray3 );
Ray2() {};
Ray2( const Vec2& point, const Vec2& dir );
~Ray2() {};
void SetStartEnd( const Vec2& start, const Vec2& end );
void Normalzie();
Vec2 Evaluate( float t ) const;
bool IsValid() { return direction != Vec2::ZEROS; };
public:
Vec2 start;
Vec2 direction;
};
| 21.458333 | 83 | 0.642718 | tonyatpeking |
f2bec613e0307a903f3c93b54430727aa51028ac | 583 | cpp | C++ | src/actions/ActionableObject.cpp | MiKlTA/Lust_The_Game | aabe4a951ffd7305526466d378ba8b6769c555e8 | [
"MIT"
] | null | null | null | src/actions/ActionableObject.cpp | MiKlTA/Lust_The_Game | aabe4a951ffd7305526466d378ba8b6769c555e8 | [
"MIT"
] | null | null | null | src/actions/ActionableObject.cpp | MiKlTA/Lust_The_Game | aabe4a951ffd7305526466d378ba8b6769c555e8 | [
"MIT"
] | null | null | null | #include "Action.h"
#include "ActionableObject.h"
namespace lust {
void ActionableObject::addAction(Action *action)
{
m_dependentActions.insert(action);
}
void ActionableObject::removeAction(const Action *action)
{
auto found = std::find(
m_dependentActions.begin(), m_dependentActions.end(), action
);
if (found != m_dependentActions.end())
{
m_dependentActions.erase(found);
}
}
void ActionableObject::invalidate()
{
for (auto da : m_dependentActions)
{
da->invalidate();
}
}
}
| 15.342105 | 76 | 0.620926 | MiKlTA |
f2c02db8e7fd5f2bcfd0e65349df14eaf893ed56 | 13,140 | cpp | C++ | src/parser/parser.cpp | toebsen/angreal | 772f0b2499ef9b121322f80f2dacdb8754180c38 | [
"MIT"
] | 4 | 2020-08-30T21:10:47.000Z | 2021-12-28T13:13:21.000Z | src/parser/parser.cpp | toebsen/angreal | 772f0b2499ef9b121322f80f2dacdb8754180c38 | [
"MIT"
] | 12 | 2020-05-14T12:25:54.000Z | 2021-08-01T11:01:23.000Z | src/parser/parser.cpp | toebsen/angreal | 772f0b2499ef9b121322f80f2dacdb8754180c38 | [
"MIT"
] | null | null | null | //
// Created by bichlmaier on 07.02.2020.
//
#include "parser.h"
namespace angreal::parser {
Parser::Parser(const error_handler_t& error_handler)
: error_handler_(error_handler) {}
template <typename Type, typename... Args>
std::shared_ptr<Type> Parser::MakeASTNode(Args&&... args) {
{
auto node = std::make_shared<Type>(std::forward<Args>(args)...);
node->SetLine(current_line_number);
return node;
}
}
std::shared_ptr<AST::Program> Parser::parseProgram(
const std::vector<Token>& tokens) {
AST::statements_t statements;
current_token = tokens.begin();
next_token = tokens.begin() + 1;
while (current_token->type() != Token::Type::EndOfProgram &&
current_token != tokens.end()) {
if (auto stmt = parseStatement()) {
statements.push_back(stmt.value());
}
}
return MakeASTNode<AST::Program>(statements);
}
expression_t Parser::parseExpression(const std::vector<Token>& tokens) {
current_token = tokens.begin();
next_token = tokens.begin() + 1;
return parseRelational();
}
void Parser::consume() {
// std::cout << "consuming: " << *next_token << std::endl;
current_token = next_token;
next_token = current_token + 1;
if (current_token->type() == Token::Type::NewLine) {
++current_line_number;
consume();
}
}
void Parser::expectToken(Token::Type t) const {
if (current_token->type() != t) {
std::stringstream ss;
ss << "Expected " << Token::type2str(t)
<< ", but got: " << Token::type2str(current_token->type());
error_handler_->ParserError(ss.str(), *current_token);
}
}
expression_t Parser::parseRelational() {
expression_t expr = parseAdditive();
if (current_token->type() == Token::Type::RelationalOp) {
auto opType = current_token->value();
consume();
auto rhs = parseAdditive();
return MakeASTNode<AST::BinaryOperation>(opType, expr, rhs);
}
return expr;
}
expression_t Parser::parseAdditive() {
expression_t expr = parseMultiplicative();
if (current_token->type() == Token::Type::AdditiveOp ||
current_token->type() == Token::Type::AndStatement) {
auto opType = current_token->value();
consume();
auto rhs = parseMultiplicative();
return MakeASTNode<AST::BinaryOperation>(opType, expr, rhs);
}
return expr;
}
expression_t Parser::parseMultiplicative() {
expression_t expr = parseUnary();
if (current_token->type() == Token::Type::MulOp ||
current_token->type() == Token::Type::DivOp ||
current_token->type() == Token::Type::OrStatement) {
auto opType = current_token->value();
consume();
auto rhs = parsePrimary();
return MakeASTNode<AST::BinaryOperation>(opType, expr, rhs);
}
return expr;
}
expression_t Parser::parseUnary() {
if (current_token->type() == Token::Type::AdditiveOp ||
current_token->type() == Token::Type::Exclamation) {
auto opType = current_token->value();
consume();
AST::expression_t expression = parseRelational();
return MakeASTNode<AST::UnaryOperation>(opType, expression);
}
return parseFunctionCall();
}
AST::expressions_t Parser::parseActualParams() {
AST::expressions_t params;
params.push_back(parseRelational());
while (current_token->type() == Token::Type::Comma) {
consume();
params.push_back(parseRelational());
}
return params;
}
expression_t Parser::parseFunctionCall() {
auto expression = parsePrimary();
while (true) {
if (current_token->type() == Token::Type::LeftBracket) {
consume(); //(
AST::expressions_t args;
if (current_token->type() != Token::Type::RightBracket) {
args = parseActualParams();
}
expectToken(Token::Type::RightBracket);
consume();
expression = MakeASTNode<AST::FunctionCall>(expression, args);
} else if (current_token->type() == Token::Type::Dot) {
consume();
expectToken(Token::Type::Identifier);
auto identifier = current_token->value();
consume();
expression = MakeASTNode<AST::Get>(expression, identifier);
} else {
break;
}
}
return expression;
}
expression_t Parser::parsePrimary() {
if (current_token->type() == Token::Type::Boolean ||
current_token->type() == Token::Type::Integer ||
current_token->type() == Token::Type::Float ||
current_token->type() == Token::Type::String) {
TypeHelper::Type decl =
TypeHelper::mapTokenToLiteralType(current_token->type());
auto value = current_token->value();
consume();
return TypeHelper::mapTypeToLiteral(decl, value);
}
if (current_token->type() == Token::Type::SelfStatement) {
consume();
return MakeASTNode<AST::Self>();
}
if (current_token->type() == Token::Type::Identifier) {
auto value = current_token->value();
consume();
if (value == "super") {
expectToken(Token::Type::Dot);
consume();
expectToken(Token::Type::Identifier);
auto ident = current_token->value();
consume();
return MakeASTNode<AST::Super>(ident);
}
return MakeASTNode<AST::IdentifierLiteral>(value);
}
if (current_token->type() == Token::Type::LeftBracket) {
consume();
auto expression = parseRelational();
expectToken(Token::Type::RightBracket);
consume();
return expression;
}
return nullptr;
}
statement_t Parser::parseVariableDeclaration() {
std::string identifier;
AST::expression_t expression;
consume();
expectToken(Token::Type::Identifier);
identifier = current_token->value();
consume();
expectToken(Token::Type::Equal);
consume();
expression = parseRelational();
return MakeASTNode<AST::Declaration>(identifier, expression);
}
expression_t Parser::parseAssignment(const expression_t& expression) {
expectToken(Token::Type::Equal);
consume();
auto value = parseRelational();
if (auto ident = std::dynamic_pointer_cast<IdentifierLiteral>(expression)) {
return MakeASTNode<AST::Assignment>(ident->name, value);
}
if (auto get = std::dynamic_pointer_cast<Get>(expression)) {
return MakeASTNode<AST::Set>(get->expression, get->identifier, value);
}
return nullptr;
}
AST::formal_parameters Parser::parseFormalParameters() {
AST::formal_parameters parameters;
expectToken(Token::Type::LeftBracket);
consume();
if (current_token->type() != Token::Type::RightBracket) {
while (current_token->type() != Token::Type::RightBracket) {
auto param = parseFormalParameter();
parameters.push_back(param);
if (current_token->type() != Token::Type::RightBracket) {
expectToken(Token::Type::Comma);
consume();
}
}
}
expectToken(Token::Type::RightBracket);
consume();
return parameters;
}
std::shared_ptr<AST::FormalParameter> Parser::parseFormalParameter() {
expectToken(Token::Type::Identifier);
std::string identifier = current_token->value();
consume();
return MakeASTNode<AST::FormalParameter>(identifier);
}
statement_t Parser::parseFunctionDeclaration() {
std::string identifier;
consume();
expectToken(Token::Type::Identifier);
identifier = current_token->value();
consume();
auto parameters = parseFormalParameters();
auto block = std::dynamic_pointer_cast<Block>(parseBlock());
return MakeASTNode<AST::FunctionDeclaration>(identifier, parameters,
block->statements);
}
statement_t Parser::parseBlock() {
AST::statements_t statements;
expectToken(Token::Type::LeftCurlyBracket);
consume();
if (current_token->type() == Token::Type::RightCurlyBracket) {
// don't parse empty block
consume();
return MakeASTNode<AST::Block>(statements);
}
do {
if (auto stmt = parseStatement()) {
statements.push_back(stmt.value());
}
} while (!(current_token->type() == Token::Type::RightCurlyBracket ||
current_token->type() == Token::Type::EndOfProgram));
expectToken(Token::Type::RightCurlyBracket);
consume();
return MakeASTNode<AST::Block>(statements);
}
statement_t Parser::parseReturnDeclaration() {
AST::expression_t expression;
consume();
expression = parseRelational();
return MakeASTNode<AST::Return>(expression);
}
statement_t Parser::parsePrintStatement() {
AST::expressions_t args;
consume(); // identifier
consume(); //(
if (current_token->type() != Token::Type::RightBracket) {
args = parseActualParams();
}
expectToken(Token::Type::RightBracket);
consume();
return MakeASTNode<AST::Print>(args);
}
std::optional<statement_t> Parser::parseStatement() {
current_line_number = current_token->position().line;
if (current_token->type() == Token::Type::VarStatement) {
return parseVariableDeclaration();
}
if (current_token->type() == Token::Type::DefStatement) {
return parseFunctionDeclaration();
}
if (current_token->type() == Token::Type::ClassStatement) {
return parseClassDeclaration();
}
if (current_token->type() == Token::Type::PrintStatement) {
return parsePrintStatement();
}
if (current_token->type() == Token::Type::LeftCurlyBracket) {
return parseBlock();
}
if (current_token->type() == Token::Type::ReturnStatement) {
return parseReturnDeclaration();
}
if (current_token->type() == Token::Type::IfStatement) {
return parseIfStatement();
}
if (current_token->type() == Token::Type::WhileStatement) {
return parseWhileStatement();
}
if (current_token->type() == Token::Type::EndOfProgram) {
return std::nullopt;
}
if (current_token->type() == Token::Type::Comment) {
consume();
return std::nullopt;
}
auto expr = parseRelational();
if (current_token->type() == Token::Type::Equal) {
expr = parseAssignment(expr);
}
if (expr) {
return MakeASTNode<ExpressionStatement>(expr);
}
consume();
return std::nullopt;
}
statement_t Parser::parseIfStatement() {
consume();
expression_t condition = parseRelational();
block_t if_branch = std::dynamic_pointer_cast<Block>(parseBlock());
block_t else_branch;
if (current_token->type() == Token::Type::Identifier &&
current_token->value() == "else") {
consume();
else_branch = std::dynamic_pointer_cast<Block>(parseBlock());
}
return MakeASTNode<AST::IfStatement>(condition, if_branch, else_branch);
}
statement_t Parser::parseWhileStatement() {
consume();
expression_t condition = parseRelational();
block_t block = std::dynamic_pointer_cast<Block>(parseBlock());
return MakeASTNode<AST::WhileStatement>(condition, block);
}
statement_t Parser::parseClassDeclaration() {
consume(); // class
expectToken(Token::Type::Identifier);
auto identifier = *current_token;
consume();
std::optional<identifier_t> superclass;
if (current_token->type() == Token::Type::LeftBracket) {
// optional superclass
consume();
expectToken(Token::Type::Identifier);
superclass = MakeASTNode<IdentifierLiteral>(current_token->value());
consume();
expectToken(Token::Type::RightBracket);
consume();
}
expectToken(Token::Type::LeftCurlyBracket);
consume();
functions_t methods;
while (true) {
if (current_token->type() == Token::Type::RightCurlyBracket) {
break;
}
if (current_token->type() == Token::Type::DefStatement) {
methods.push_back(std::dynamic_pointer_cast<FunctionDeclaration>(
parseFunctionDeclaration()));
} else {
error_handler_->ParserError(
"Only function declarations are allowed inside declaration of "
"class !",
identifier);
break;
}
}
expectToken(Token::Type::RightCurlyBracket);
consume();
return MakeASTNode<AST::ClassDeclaration>(identifier.value(), methods,
superclass);
}
} // namespace angreal::parser | 31.211401 | 81 | 0.59863 | toebsen |
f2c03315b9f772048e9285a63a30d5021f782a3e | 1,800 | cpp | C++ | client/src/user_interface/game_over.cpp | dima1997/PORTAL_2D_copy | 7618d970feded3fc05fda0c422a5d76a1d3056c7 | [
"MIT"
] | null | null | null | client/src/user_interface/game_over.cpp | dima1997/PORTAL_2D_copy | 7618d970feded3fc05fda0c422a5d76a1d3056c7 | [
"MIT"
] | null | null | null | client/src/user_interface/game_over.cpp | dima1997/PORTAL_2D_copy | 7618d970feded3fc05fda0c422a5d76a1d3056c7 | [
"MIT"
] | null | null | null | #include "../../includes/user_interface/game_over.h"
#include "ui_GameOver.h"
#include "../../includes/threads/play_result.h"
#include <QWidget>
#include <QDesktopWidget>
#include <string>
#define WINDOW_WIDTH 640
#define WINDOW_HEIGHT 480
/*
PRE: Recibe un resultado de juego.
POST:Iniicaliza una ventana de fin de juego.
*/
GameOver::GameOver(PlayResult & playResult, QWidget *parent)
: QWidget(parent)
{
Ui::GameOver gameOver;
gameOver.setupUi(this);
this->setFixedSize(WINDOW_WIDTH, WINDOW_HEIGHT);
this->hide();
this->move(
QApplication::desktop()->screen()->rect().center()
- (this->rect()).center()
);
this->set_game_status(playResult);
this->set_players_status(playResult);
}
/*
PRE: Recibe el resultado de un juego.
POST: Setea la etiqueta de estado del juego.
*/
void GameOver::set_game_status(PlayResult & playResult){
QLabel* gameStatusLabel = findChild<QLabel*>("gameStatusLabel");
GameStatus gameStatus = playResult.get_game_status();
if (gameStatus == GAME_STATUS_WON){
gameStatusLabel->setText("WON");
} else if (gameStatus == GAME_STATUS_LOST){
gameStatusLabel->setText("LOST");
} else {
gameStatusLabel->setText("NOT_FINISHED");
}
gameStatusLabel->setStyleSheet("QLabel { color : white; font-size: 20pt }");
}
/*
PRE: Recibe el resultado de un juego.
POST: Setea el estado de los jugadores en el text browser.
*/
void GameOver::set_players_status(PlayResult & playResult){
QTextBrowser* playersStatusTextBrowser =
findChild<QTextBrowser*>("playersStatusTextBrowser");
std::string playersStatusStr = playResult.get_players_status();
playersStatusTextBrowser->append(playersStatusStr.c_str());
}
/*Destruye ventantana.*/
GameOver::~GameOver() = default; | 28.571429 | 80 | 0.707778 | dima1997 |
f2c0b8fb27d8d25f924b9a57f850141d94ee4687 | 9,663 | cp | C++ | MacOS/Sources/Application/Preferences_Dialog/Sub-panels/Account_Panels/Authentication_Panels/CPrefsAccountAuth.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 12 | 2015-04-21T16:10:43.000Z | 2021-11-05T13:41:46.000Z | MacOS/Sources/Application/Preferences_Dialog/Sub-panels/Account_Panels/Authentication_Panels/CPrefsAccountAuth.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2015-11-02T13:32:11.000Z | 2019-07-10T21:11:21.000Z | MacOS/Sources/Application/Preferences_Dialog/Sub-panels/Account_Panels/Authentication_Panels/CPrefsAccountAuth.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 6 | 2015-01-12T08:49:12.000Z | 2021-03-27T09:11:10.000Z | /*
Copyright (c) 2007 Cyrus Daboo. 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.
*/
// Source for CPrefsAccountAuth class
#include "CPrefsAccountAuth.h"
#include "CAuthPlugin.h"
#include "CCertificateManager.h"
#include "CINETAccount.h"
#include "CMulberryCommon.h"
#include "CPluginManager.h"
#include "CPreferences.h"
#include "CPreferencesDialog.h"
#include "CPrefsAuthPanel.h"
#include "CPrefsAuthPlainText.h"
#include "CPrefsAuthKerberos.h"
#include "CPrefsAuthAnonymous.h"
#include <LCheckBox.h>
#include <LPopupButton.h>
// C O N S T R U C T I O N / D E S T R U C T I O N M E T H O D S
// Default constructor
CPrefsAccountAuth::CPrefsAccountAuth()
{
mCurrentPanel = nil;
mCurrentPanelNum = 0;
}
// Constructor from stream
CPrefsAccountAuth::CPrefsAccountAuth(LStream *inStream)
: CPrefsTabSubPanel(inStream)
{
mCurrentPanel = nil;
mCurrentPanelNum = 0;
}
// Default destructor
CPrefsAccountAuth::~CPrefsAccountAuth()
{
}
// O T H E R M E T H O D S ____________________________________________________________________________
// Get details of sub-panes
void CPrefsAccountAuth::FinishCreateSelf(void)
{
// Do inherited
CPrefsTabSubPanel::FinishCreateSelf();
// Get controls
mAuthPopup = (LPopupButton*) FindPaneByID(paneid_AccountAuthPopup);
mAuthSubPanel = (LView*) FindPaneByID(paneid_AccountAuthPanel);
mTLSPopup = (LPopupButton*) FindPaneByID(paneid_AccountTLSPopup);
mUseTLSClientCert = (LCheckBox*) FindPaneByID(paneid_AccountUseTLSClientCert);
mTLSClientCert = (LPopupButton*) FindPaneByID(paneid_AccountTLSClientCert);
BuildCertPopup();
// Link controls to this window
UReanimator::LinkListenerToBroadcasters(this,this,RidL_CPrefsAccountAuthBtns);
// Start with first panel
SetAuthPanel(cdstring::null_str);
}
// Handle buttons
void CPrefsAccountAuth::ListenToMessage(
MessageT inMessage,
void *ioParam)
{
switch (inMessage)
{
case msg_MailAccountAuth:
{
cdstring temp = ::GetPopupMenuItemTextUTF8(mAuthPopup);
SetAuthPanel(temp);
break;
}
case msg_AccountTLSPopup:
TLSItemsState();
break;
case msg_AccountUseTLSClientCert:
TLSItemsState();
break;
}
}
// Toggle display of IC
void CPrefsAccountAuth::ToggleICDisplay(bool IC_on)
{
if (mCurrentPanel)
mCurrentPanel->ToggleICDisplay(IC_on);
}
// Set prefs
void CPrefsAccountAuth::SetData(void* data)
{
CINETAccount* account = (CINETAccount*) data;
// Build popup from panel
BuildAuthPopup(account);
if (mCurrentPanel)
mCurrentPanel->SetAuth(account->GetAuthenticator().GetAuthenticator());
InitTLSItems(account);
mTLSPopup->SetValue(account->GetTLSType() + 1);
mUseTLSClientCert->SetValue(account->GetUseTLSClientCert());
// Match fingerprint in list
for(cdstrvect::const_iterator iter = mCertFingerprints.begin(); iter != mCertFingerprints.end(); iter++)
{
if (account->GetTLSClientCert() == *iter)
{
::SetPopupByName(mTLSClientCert, mCertSubjects.at(iter - mCertFingerprints.begin()));
break;
}
}
TLSItemsState();
}
// Force update of prefs
void CPrefsAccountAuth::UpdateData(void* data)
{
CINETAccount* account = (CINETAccount*) data;
// Copy info from panel into prefs
cdstring temp = ::GetPopupMenuItemTextUTF8(mAuthPopup);
// Special for anonymous
if (mAuthPopup->GetValue() == ::CountMenuItems(mAuthPopup->GetMacMenuH()) - 1)
temp = "None";
account->GetAuthenticator().SetDescriptor(temp);
if (mCurrentPanel)
mCurrentPanel->UpdateAuth(account->GetAuthenticator().GetAuthenticator());
int popup = mTLSPopup->GetValue() - 1;
account->SetTLSType((CINETAccount::ETLSType) (mTLSPopup->GetValue() - 1));
account->SetUseTLSClientCert(mUseTLSClientCert->GetValue());
if (account->GetUseTLSClientCert() && ::CountMenuItems(mTLSClientCert->GetMacMenuH()))
account->SetTLSClientCert(mCertFingerprints.at(mTLSClientCert->GetValue() - 1));
else
account->SetTLSClientCert(cdstring::null_str);
}
// Set auth panel
void CPrefsAccountAuth::SetAuthPanel(const cdstring& auth_type)
{
// Find matching auth plugin
CAuthPlugin* plugin = CPluginManager::sPluginManager.GetAuthPlugin(auth_type);
CAuthPlugin::EAuthPluginUIType ui_type = plugin ? plugin->GetAuthUIType() :
(auth_type == "Plain Text" ? CAuthPlugin::eAuthUserPswd : CAuthPlugin::eAuthAnonymous);
ResIDT panel;
switch(ui_type)
{
case CAuthPlugin::eAuthUserPswd:
panel = paneid_PrefsAuthPlainText;
break;
case CAuthPlugin::eAuthKerberos:
panel = paneid_PrefsAuthKerberos;
break;
case CAuthPlugin::eAuthAnonymous:
panel = paneid_PrefsAuthAnonymous;
break;
}
if (mAuthType != auth_type)
{
mAuthType = auth_type;
// First remove and update any existing panel
mAuthSubPanel->DeleteAllSubPanes();
// Update to new panel id
mCurrentPanelNum = panel;
// Make panel area default so new panel is automatically added to it
if (panel)
{
SetDefaultView(mAuthSubPanel);
mAuthSubPanel->Hide();
CPreferencesDialog* prefs_dlog = (CPreferencesDialog*) mSuperView;
while(prefs_dlog->GetPaneID() != paneid_PreferencesDialog)
prefs_dlog = (CPreferencesDialog*) prefs_dlog->GetSuperView();
LCommander* defCommander;
prefs_dlog->GetSubCommanders().FetchItemAt(1, defCommander);
prefs_dlog->SetDefaultCommander(defCommander);
mCurrentPanel = (CPrefsAuthPanel*) UReanimator::ReadObjects('PPob', mCurrentPanelNum);
mCurrentPanel->FinishCreate();
mAuthSubPanel->Show();
}
else
{
mAuthSubPanel->Refresh();
mCurrentPanel = nil;
}
}
}
void CPrefsAccountAuth::BuildAuthPopup(CINETAccount* account)
{
// Copy info
cdstring set_name;
short set_value = -1;
switch(account->GetAuthenticatorType())
{
case CAuthenticator::eNone:
set_value = -1;
break;
case CAuthenticator::ePlainText:
set_value = 1;
break;
case CAuthenticator::eSSL:
set_value = 0;
break;
case CAuthenticator::ePlugin:
set_name = account->GetAuthenticator().GetDescriptor();
break;
}
// Remove any existing plugin items from main menu
MenuHandle menuH = mAuthPopup->GetMacMenuH();
short num_remove = ::CountMenuItems(menuH) - 4;
for(short i = 0; i < num_remove; i++)
::DeleteMenuItem(menuH, 2);
cdstrvect plugin_names;
CPluginManager::sPluginManager.GetAuthPlugins(plugin_names);
std::sort(plugin_names.begin(), plugin_names.end());
short index = 1;
for(cdstrvect::const_iterator iter = plugin_names.begin(); iter != plugin_names.end(); iter++, index++)
{
::InsertMenuItem(menuH, "\p?", index);
::SetMenuItemTextUTF8(menuH, index + 1, *iter);
if (*iter == set_name)
set_value = index + 1;
}
// Force max/min update
mAuthPopup->SetMenuMinMax();
// Set value
StopListening();
mAuthPopup->SetValue((set_value > 0) ? set_value : index + 3 + set_value);
StartListening();
cdstring temp = ::GetPopupMenuItemTextUTF8(mAuthPopup);
SetAuthPanel(temp);
}
void CPrefsAccountAuth::InitTLSItems(CINETAccount* account)
{
// Enable each item based on what the protocol supports
bool enabled = false;
for(int i = CINETAccount::eNoTLS; i <= CINETAccount::eTLSTypeMax; i++)
{
if (account->SupportsTLSType(static_cast<CINETAccount::ETLSType>(i)))
{
::EnableItem(mTLSPopup->GetMacMenuH(), i + 1);
enabled = true;
}
else
::DisableItem(mTLSPopup->GetMacMenuH(), i + 1);
}
// Hide if no plugin present or none enabled
if (enabled && CPluginManager::sPluginManager.HasSSL())
{
mTLSPopup->Show();
FindPaneByID(paneid_AccountTLSGroup)->Show();
//mUseTLSClientCert->Show();
//mTLSClientCert->Show();
}
else
{
mTLSPopup->Hide();
FindPaneByID(paneid_AccountTLSGroup)->Hide();
//mUseTLSClientCert->Hide();
//mTLSClientCert->Hide();
// Disable the auth item
::DisableItem(mAuthPopup->GetMacMenuH(), mAuthPopup->GetMaxValue());
}
}
void CPrefsAccountAuth::BuildCertPopup()
{
// Only if certs are available
if (CCertificateManager::HasCertificateManager())
{
// Get list of private certificates
CCertificateManager::sCertificateManager->GetPrivateCertificates(mCertSubjects, mCertFingerprints);
// Remove any existing items from main menu
MenuHandle menuH = mTLSClientCert->GetMacMenuH();
while(::CountMenuItems(menuH))
::DeleteMenuItem(menuH, 1);
short index = 1;
for(cdstrvect::const_iterator iter = mCertSubjects.begin(); iter != mCertSubjects.end(); iter++, index++)
::AppendItemToMenu(menuH, index, (*iter).c_str());
// Force max/min update
mTLSClientCert->SetMenuMinMax();
}
}
void CPrefsAccountAuth::TLSItemsState()
{
// TLS popup
if (mTLSPopup->GetValue() - 1 == CINETAccount::eNoTLS)
{
mUseTLSClientCert->Disable();
mTLSClientCert->Disable();
if (mAuthPopup->GetValue() == mAuthPopup->GetMaxValue())
mAuthPopup->SetValue(1);
::DisableItem(mAuthPopup->GetMacMenuH(), mAuthPopup->GetMaxValue());
}
else
{
mUseTLSClientCert->Enable();
if (mUseTLSClientCert->GetValue())
{
mTLSClientCert->Enable();
::EnableItem(mAuthPopup->GetMacMenuH(), mAuthPopup->GetMaxValue());
}
else
{
mTLSClientCert->Disable();
if (mAuthPopup->GetValue() == mAuthPopup->GetMaxValue())
mAuthPopup->SetValue(1);
::DisableItem(mAuthPopup->GetMacMenuH(), mAuthPopup->GetMaxValue());
}
}
}
| 26.841667 | 107 | 0.732381 | mulberry-mail |
f2c10f99fbebf3fd599e1bcd8fd28bbbfa8ac15a | 676 | cpp | C++ | binary-tree/check-if-subtree.cpp | Strider-7/code | e096c0d0633b53a07bf3f295cb3bd685b694d4ce | [
"MIT"
] | null | null | null | binary-tree/check-if-subtree.cpp | Strider-7/code | e096c0d0633b53a07bf3f295cb3bd685b694d4ce | [
"MIT"
] | null | null | null | binary-tree/check-if-subtree.cpp | Strider-7/code | e096c0d0633b53a07bf3f295cb3bd685b694d4ce | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
Node *left;
Node *right;
Node(int x)
{
data = x;
left = nullptr;
right = nullptr;
}
};
bool isIdentical(Node* T, Node* S) {
if (!T && !S)
return true;
if (!T || !S)
return false;
return T->data == S->data && isIdentical(T->left, S->left) && isIdentical(T->right, S->right);
}
bool isSubTree(Node* T, Node* S) {
if (!S)
return true;
if (!T)
return false;
if (isIdentical(T, S))
return true;
return isSubTree(T->left, S) || isSubTree(T->right, S);
} | 18.27027 | 99 | 0.486686 | Strider-7 |
f2c43230a7babcb209a2c7b93636ad6da4111bc2 | 755 | cpp | C++ | ReeeEngine/src/ReeeEngine/Rendering/Context/SampleState.cpp | Lewisscrivens/ReeeEngine | abb31ef7e1adb553fafe02c4f9bd60ceb520acbf | [
"MIT"
] | null | null | null | ReeeEngine/src/ReeeEngine/Rendering/Context/SampleState.cpp | Lewisscrivens/ReeeEngine | abb31ef7e1adb553fafe02c4f9bd60ceb520acbf | [
"MIT"
] | null | null | null | ReeeEngine/src/ReeeEngine/Rendering/Context/SampleState.cpp | Lewisscrivens/ReeeEngine | abb31ef7e1adb553fafe02c4f9bd60ceb520acbf | [
"MIT"
] | null | null | null | #include "SampleState.h"
namespace ReeeEngine
{
SampleState::SampleState(Graphics& graphics)
{
// Create sampler default options for UV read type.
D3D11_SAMPLER_DESC samplerOptions = {};
samplerOptions.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
samplerOptions.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
samplerOptions.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
samplerOptions.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
// Create sampler state and check/log errors.
HRESULT result = GetDevice(graphics)->CreateSamplerState(&samplerOptions, &sampler);
LOG_DX_ERROR(result);
}
void SampleState::Add(Graphics& graphics) noexcept
{
// Add sampler to rendering pipeline.
GetContext(graphics)->PSSetSamplers(0, 1, sampler.GetAddressOf());
}
} | 31.458333 | 86 | 0.778808 | Lewisscrivens |
f2c4dc83ec8d1f9807509068206be97a0cce3eb0 | 407 | cc | C++ | examples/Example3/main.cc | stognini/AdePT | 9a106b83f421938ad8f4d8567d199c84f339e6c9 | [
"Apache-2.0"
] | null | null | null | examples/Example3/main.cc | stognini/AdePT | 9a106b83f421938ad8f4d8567d199c84f339e6c9 | [
"Apache-2.0"
] | null | null | null | examples/Example3/main.cc | stognini/AdePT | 9a106b83f421938ad8f4d8567d199c84f339e6c9 | [
"Apache-2.0"
] | null | null | null | // SPDX-FileCopyrightText: 2020 CERN
// SPDX-License-Identifier: Apache-2.0
#include "common.h"
#include "loop.h"
#include <iostream>
int main(int argc, char **argv)
{
if (argc != 2) {
std::cout << "Usage: " << argv[0] << " nparticles" << std::endl;
return 0;
}
int nparticles = std::atoi(argv[1]);
#ifndef __CUDACC__
simulate(nparticles);
#else
simulate_all(nparticles);
#endif
return 0;
}
| 15.653846 | 66 | 0.653563 | stognini |
f2d318974ca25caa783bfda28c4121b7d15a1c02 | 354 | cpp | C++ | src/L/L1226.cpp | wlhcode/lscct | 7fd112a9d1851ddcf41886d3084381a52e84a3ce | [
"MIT"
] | null | null | null | src/L/L1226.cpp | wlhcode/lscct | 7fd112a9d1851ddcf41886d3084381a52e84a3ce | [
"MIT"
] | null | null | null | src/L/L1226.cpp | wlhcode/lscct | 7fd112a9d1851ddcf41886d3084381a52e84a3ce | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
string s;
string o;
main(){
long long a;
bool first=true;
cin>>a;
s+=to_string(a);
sort(s.begin(),s.end());
for(int i=2;i<=9;i++){
o.clear();
o+=to_string(a*i);
sort(o.begin(),o.end());
if(s==o){
if(!first) cout<<" ";
cout<<i;
first=false;
}
}
if(first) cout<<"NO";
cout<<endl;
}
| 14.16 | 26 | 0.553672 | wlhcode |
f2dddfbc6249d58b917232fc7819daa05d380ca0 | 1,276 | hpp | C++ | include/tdc/util/lcp.hpp | herlez/tdc | 3b85ae183c21410e65f1e739736287df46c38d1d | [
"MIT"
] | 1 | 2021-05-06T13:39:22.000Z | 2021-05-06T13:39:22.000Z | include/tdc/util/lcp.hpp | herlez/tdc | 3b85ae183c21410e65f1e739736287df46c38d1d | [
"MIT"
] | 1 | 2020-03-07T08:05:20.000Z | 2020-03-07T08:05:20.000Z | include/tdc/util/lcp.hpp | herlez/tdc | 3b85ae183c21410e65f1e739736287df46c38d1d | [
"MIT"
] | 2 | 2020-05-27T07:54:43.000Z | 2021-11-18T13:29:14.000Z | #pragma once
namespace tdc {
/// \brief Computes the LCP array from the suffix array using Kasai's algorithm.
/// \tparam char_t the character type
/// \tparam idx_t the suffix/LCP array entry type
/// \param text the input text, assuming to be zero-terminated
/// \param n the length of the input text including the zero-terminator
/// \param sa the suffix array for the text
/// \param lcp the output LCP array
/// \param plcp an array of size n used as working space -- contains the permuted LCP array after the operation
template<typename char_t, typename idx_t>
static void lcp_kasai(const char_t* text, const size_t n, const idx_t* sa, idx_t* lcp, idx_t* plcp) {
// compute phi array
{
for(size_t i = 1, prev = sa[0]; i < n; i++) {
plcp[sa[i]] = prev;
prev = sa[i];
}
plcp[sa[0]] = sa[n-1];
}
// compute PLCP array
{
for(size_t i = 0, l = 0; i < n - 1; ++i) {
const auto phi_i = plcp[i];
while(text[i + l] == text[phi_i + l]) ++l;
plcp[i] = l;
if(l) --l;
}
}
// compute LCP array
{
lcp[0] = 0;
for(size_t i = 1; i < n; i++) {
lcp[i] = plcp[sa[i]];
}
}
}
} // namespace tdc
| 29 | 111 | 0.554859 | herlez |
f2de2cd3f4565129763b927dfd000cad5c946085 | 58 | hpp | C++ | src/boost_mpl_aux__preprocessed_no_ctps_vector.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 10 | 2018-03-17T00:58:42.000Z | 2021-07-06T02:48:49.000Z | src/boost_mpl_aux__preprocessed_no_ctps_vector.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 2 | 2021-03-26T15:17:35.000Z | 2021-05-20T23:55:08.000Z | src/boost_mpl_aux__preprocessed_no_ctps_vector.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 4 | 2019-05-28T21:06:37.000Z | 2021-07-06T03:06:52.000Z | #include <boost/mpl/aux_/preprocessed/no_ctps/vector.hpp>
| 29 | 57 | 0.810345 | miathedev |
f2deba7cbaf90053e5c47ad9cee572e1fc63afc3 | 18,693 | cpp | C++ | src/lua/state.cpp | degarashi/revenant | 9e671320a5c8790f6bdd1b14934f81c37819f7b3 | [
"MIT"
] | null | null | null | src/lua/state.cpp | degarashi/revenant | 9e671320a5c8790f6bdd1b14934f81c37819f7b3 | [
"MIT"
] | null | null | null | src/lua/state.cpp | degarashi/revenant | 9e671320a5c8790f6bdd1b14934f81c37819f7b3 | [
"MIT"
] | null | null | null | #include "lcv.hpp"
#include "lvalue.hpp"
#include "../sdl/rw.hpp"
#include "../apppath.hpp"
#include "rewindtop.hpp"
#include "lubee/src/freelist.hpp"
extern "C" {
#include <lauxlib.h>
#include <lualib.h>
}
namespace rev {
// ----------------- LuaState::Exceptions -----------------
LuaState::EBase::EBase(const std::string& typ_msg, const std::string& msg):
std::runtime_error("")
{
std::stringstream ss;
ss << "Error in LuaState:\nCause: " << typ_msg << std::endl << msg;
reinterpret_cast<std::runtime_error&>(*this) = std::runtime_error(ss.str());
}
LuaState::ERun::ERun(const std::string& s):
EBase("Runtime", s)
{}
LuaState::ESyntax::ESyntax(const std::string& s):
EBase("Syntax", s)
{}
LuaState::EMem::EMem(const std::string& s):
EBase("Memory", s)
{}
LuaState::EError::EError(const std::string& s):
EBase("ErrorHandler", s)
{}
LuaState::EGC::EGC(const std::string& s):
EBase("GC", s)
{}
LuaState::EType::EType(lua_State* ls, const LuaType expect, const LuaType actual):
EBase(
"InvalidType",
std::string("[") + STypeName(ls, actual) +
"] to [" + STypeName(ls, expect) + "]"
),
expect(expect),
actual(actual)
{}
// ----------------- LuaState -----------------
const std::string LuaState::cs_fromCpp("FromCpp"),
LuaState::cs_fromLua("FromLua"),
LuaState::cs_mainThreadPtr("MainThreadPtr"),
LuaState::cs_mainThread("MainThread");
void LuaState::Nothing(lua_State* /*ls*/) {}
const LuaState::Deleter LuaState::s_deleter =
[](lua_State* ls){
// これが呼ばれる時はメインスレッドなどが全て削除された時なのでlua_closeを呼ぶ
lua_close(ls);
};
LuaState::Deleter LuaState::_MakeCoDeleter(LuaState* lsp) {
#ifdef DEBUG
return [lsp](lua_State* ls) {
D_Assert0(lsp->getLS() == ls);
#else
return [lsp](lua_State*) {
#endif
lsp->_unregisterCpp();
};
}
void LuaState::_initMainThread() {
const CheckTop ct(getLS());
// メインスレッドの登録 -> global[cs_mainThreadPtr]
push(static_cast<void*>(this));
setGlobal(cs_mainThreadPtr);
pushSelf();
setGlobal(cs_mainThread);
// fromCpp
newTable();
setGlobal(cs_fromCpp);
// fromLua
newTable();
// FromLuaの方は弱参照テーブルにする
newTable();
setField(-1, "__mode", "k");
// [fromLua][mode]
setMetatable(-2);
setGlobal(cs_fromLua);
}
void LuaState::_getThreadTable() {
getGlobal(cs_fromCpp);
getGlobal(cs_fromLua);
D_Assert0(type(-2)==LuaType::Table &&
type(-1)==LuaType::Table);
}
void LuaState::_registerLua() {
D_Assert0(!_bWrap);
const CheckTop ct(getLS());
getGlobal(cs_fromLua);
pushSelf();
getTable(-2);
if(type(-1) == LuaType::Nil) {
pop(1);
MakeUserdataWithDtor(*this, Lua_WP(shared_from_this()));
// [fromLua][Lua_SP]
pushSelf();
pushValue(-2);
// [fromLua][Lua_SP][Thread][Lua_SP]
setTable(-4);
pop(2);
} else {
// [fromLua][Lua_SP]
D_Assert0(type(-1) == LuaType::Userdata);
pop(2);
}
}
void LuaState::_registerCpp() {
D_Assert0(!_bWrap);
const RewindTop rt(getLS());
pushSelf();
getGlobal(cs_fromCpp);
// [Thread][fromCpp]
push(reinterpret_cast<void*>(this));
pushValue(rt.getBase()+1);
// [Thread][fromCpp][LuaState*][Thread]
D_Assert0(type(-1) == LuaType::Thread);
setTable(-3);
}
void LuaState::_unregisterCpp() {
D_Assert0(!_bWrap);
const RewindTop rt(getLS());
getGlobal(cs_fromCpp);
// [fromCpp]
push(reinterpret_cast<void*>(this));
push(LuaNil{});
// [fromCpp][LuaState*][Nil]
setTable(-3);
}
bool LuaState::isLibraryLoaded() {
getGlobal(luaNS::system::Package);
const bool res = type(-1) == LuaType::Table;
pop(1);
return res;
}
bool LuaState::isMainThread() const {
return !static_cast<bool>(_base);
}
void LuaState::addResourcePath(const std::string& path) {
loadLibraries();
const CheckTop ct(getLS());
// パッケージのロードパスにアプリケーションリソースパスを追加
getGlobal(luaNS::system::Package);
getField(-1, luaNS::system::Path);
push(";");
push(path);
// [package][path-str][;][path]
concat(3);
// [package][path-str(new)]
push(luaNS::system::Path);
pushValue(-2);
// [package][path-str(new)][path][path-str(new)]
setTable(-4);
pop(2);
}
LuaState::LuaState(const Lua_SP& spLua) {
_bWrap = false;
lua_State* ls = spLua->getLS();
const CheckTop ct(ls);
_base = spLua->getMainLS_SP();
_lua = ILua_SP(lua_newthread(ls), _MakeCoDeleter(this));
_registerCpp();
D_Assert0(getTop() == 0);
spLua->pop(1);
}
LuaState::LuaState(lua_State* ls, const bool bCheckTop):
_lua(ls, Nothing)
{
_bWrap = true;
if(bCheckTop)
_opCt = spi::construct(ls);
}
LuaState::LuaState(const lua_Alloc f, void* ud) {
_bWrap = false;
_lua = ILua_SP(f ? lua_newstate(f, ud) : luaL_newstate(), s_deleter);
const CheckTop ct(_lua.get());
_initMainThread();
}
LuaState::Reader::Reader(const HRW& hRW):
ops(hRW),
size(ops->size())
{}
Lua_SP LuaState::NewState(const lua_Alloc f, void* ud) {
Lua_SP ret(new LuaState(f, ud));
// スレッドリストにも加える
ret->_registerCpp();
ret->_registerLua();
return ret;
}
// --------------- LuaState::Reader ---------------
void LuaState::Reader::Read(lua_State* ls, const HRW& hRW, const char* chunkName, const char* mode) {
Reader reader(hRW);
const int res = lua_load(
ls,
&Reader::Proc,
&reader,
(chunkName ? chunkName : "(no name present)"),
mode
);
LuaState::CheckError(ls, res);
}
const char* LuaState::Reader::Proc(lua_State* /*ls*/, void* data, std::size_t* size) {
auto* self = reinterpret_cast<Reader*>(data);
auto remain = self->size;
if(remain > 0) {
constexpr decltype(remain) BLOCKSIZE = 2048,
MAX_BLOCK = 4;
int nb, blocksize;
if(remain <= BLOCKSIZE) {
nb = 1;
blocksize = *size = remain;
self->size = 0;
} else {
nb = std::min(MAX_BLOCK, remain / BLOCKSIZE);
blocksize = BLOCKSIZE;
*size = BLOCKSIZE * nb;
self->size -= *size;
}
self->buff.resize(*size);
self->ops->read(self->buff.data(), blocksize, nb);
return reinterpret_cast<const char*>(self->buff.data());
}
*size = 0;
return nullptr;
}
const char* LuaState::cs_defaultmode = "bt";
int LuaState::load(const HRW& hRW, const char* chunkName, const char* mode, const bool bExec) {
Reader::Read(getLS(), hRW, chunkName, mode);
if(bExec) {
// Loadされたチャンクを実行
return call(0, LUA_MULTRET);
}
return 0;
}
int LuaState::loadFromSource(const HRW& hRW, const char* chunkName, const bool bExec) {
return load(hRW, chunkName, "t", bExec);
}
int LuaState::loadFromBinary(const HRW& hRW, const char* chunkName, const bool bExec) {
return load(hRW, chunkName, "b", bExec);
}
int LuaState::loadModule(const std::string& name) {
std::string s("require(\"");
s.append(name);
s.append("\")");
HRW hRW = mgr_rw.fromConstTemporal(s.data(), s.length());
return loadFromSource(hRW, name.c_str(), true);
}
void LuaState::pushSelf() {
lua_pushthread(getLS());
}
void LuaState::loadLibraries() {
if(!isLibraryLoaded())
luaL_openlibs(getLS());
}
void LuaState::push(const LCValue& v) {
v.push(getLS());
}
void LuaState::pushCClosure(const lua_CFunction func, const int nvalue) {
lua_pushcclosure(getLS(), func, nvalue);
}
void LuaState::pushValue(const int idx) {
lua_pushvalue(getLS(), idx);
}
void LuaState::pop(const int n) {
lua_pop(getLS(), n);
}
namespace {
#ifdef DEBUG
bool IsRegistryIndex(const int idx) noexcept {
return idx==LUA_REGISTRYINDEX;
}
#endif
}
int LuaState::absIndex(int idx) const {
idx = lua_absindex(getLS(), idx);
D_Assert0(IsRegistryIndex(idx) || idx>=0);
return idx;
}
void LuaState::arith(const OP op) {
lua_arith(getLS(), static_cast<int>(op));
}
lua_CFunction LuaState::atPanic(const lua_CFunction panicf) {
return lua_atpanic(getLS(), panicf);
}
int LuaState::call(const int nargs, const int nresults) {
D_Scope(call)
const int top = getTop() - 1; // 1は関数の分
const int err = lua_pcall(getLS(), nargs, nresults, 0);
checkError(err);
return getTop() - top;
D_ScopeEnd()
}
int LuaState::callk(const int nargs, const int nresults, lua_KContext ctx, lua_KFunction k) {
D_Scope(callk)
const int top = getTop() - 1; // 1は関数の分
const int err = lua_pcallk(getLS(), nargs, nresults, 0, ctx, k);
checkError(err);
return getTop() - top;
D_ScopeEnd()
}
bool LuaState::checkStack(const int extra) {
return lua_checkstack(getLS(), extra) != 0;
}
bool LuaState::compare(const int idx0, const int idx1, CMP cmp) const {
return lua_compare(getLS(), idx0, idx1, static_cast<int>(cmp)) != 0;
}
void LuaState::concat(const int n) {
lua_concat(getLS(), n);
}
void LuaState::copy(const int from, const int to) {
lua_copy(getLS(), from, to);
}
void LuaState::dump(lua_Writer writer, void* data) {
lua_dump(getLS(), writer, data, 0);
}
void LuaState::error() {
lua_error(getLS());
}
int LuaState::gc(GC what, const int data) {
return lua_gc(getLS(), static_cast<int>(what), data);
}
lua_Alloc LuaState::getAllocf(void** ud) const {
return lua_getallocf(getLS(), ud);
}
void LuaState::getField(int idx, const LCValue& key) {
idx = absIndex(idx);
push(key);
getTable(idx);
}
void LuaState::getGlobal(const LCValue& key) {
pushGlobal();
push(key);
// [Global][key]
getTable(-2);
remove(-2);
}
const char* LuaState::getUpvalue(const int idx, const int n) {
return lua_getupvalue(getLS(), idx, n);
}
void LuaState::getTable(const int idx) {
lua_gettable(getLS(), idx);
}
int LuaState::getTop() const {
return lua_gettop(getLS());
}
void LuaState::getUserValue(const int idx) {
lua_getuservalue(getLS(), idx);
}
void LuaState::getMetatable(const int idx) {
lua_getmetatable(getLS(), idx);
}
void LuaState::insert(const int idx) {
lua_insert(getLS(), idx);
}
bool LuaState::isBoolean(const int idx) const {
return lua_isboolean(getLS(), idx) != 0;
}
bool LuaState::isCFunction(const int idx) const {
return lua_iscfunction(getLS(), idx) != 0;
}
bool LuaState::isLightUserdata(const int idx) const {
return lua_islightuserdata(getLS(), idx) != 0;
}
bool LuaState::isNil(const int idx) const {
return lua_isnil(getLS(), idx) != 0;
}
bool LuaState::isNone(const int idx) const {
return lua_isnone(getLS(), idx) != 0;
}
bool LuaState::isNoneOrNil(const int idx) const {
return lua_isnoneornil(getLS(), idx) != 0;
}
bool LuaState::isNumber(const int idx) const {
return lua_isnumber(getLS(), idx) != 0;
}
bool LuaState::isString(const int idx) const {
return lua_isstring(getLS(), idx) != 0;
}
bool LuaState::isTable(const int idx) const {
return lua_istable(getLS(), idx) != 0;
}
bool LuaState::isThread(const int idx) const {
return lua_isthread(getLS(), idx) != 0;
}
bool LuaState::isUserdata(const int idx) const {
return lua_isuserdata(getLS(), idx) != 0;
}
void LuaState::length(const int idx) {
lua_len(getLS(), idx);
}
int LuaState::getLength(const int idx) {
length(idx);
const int ret = toInteger(-1);
pop(1);
return ret;
}
void LuaState::newTable(const int narr, const int nrec) {
lua_createtable(getLS(), narr, nrec);
}
Lua_SP LuaState::newThread() {
return Lua_SP(new LuaState(shared_from_this()));
}
void* LuaState::newUserData(const std::size_t sz) {
return lua_newuserdata(getLS(), sz);
}
int LuaState::next(const int idx) {
return lua_next(getLS(), idx);
}
bool LuaState::rawEqual(const int idx0, const int idx1) {
return lua_rawequal(getLS(), idx0, idx1) != 0;
}
void LuaState::rawGet(const int idx) {
lua_rawget(getLS(), idx);
}
void LuaState::rawGetField(int idx, const LCValue& key) {
if(idx < 0)
idx = lua_absindex(getLS(), idx);
D_Assert0(idx >= 0);
push(key);
rawGet(idx);
}
std::size_t LuaState::rawLen(const int idx) const {
return lua_rawlen(getLS(), idx);
}
void LuaState::rawSet(const int idx) {
lua_rawset(getLS(), idx);
}
void LuaState::rawSetField(int idx, const LCValue& key, const LCValue& val) {
if(idx < 0)
idx = lua_absindex(getLS(), idx);
D_Assert0(idx >= 0);
push(key);
push(val);
rawSet(idx);
}
void LuaState::remove(const int idx) {
lua_remove(getLS(), idx);
}
void LuaState::replace(const int idx) {
lua_replace(getLS(), idx);
}
std::pair<bool,int> LuaState::resume(const Lua_SP& from, const int narg) {
lua_State *const ls = from ? from->getLS() : nullptr;
const int res = lua_resume(getLS(), ls, narg);
checkError(res);
return std::make_pair(res==LUA_YIELD, getTop());
}
void LuaState::setAllocf(lua_Alloc f, void* ud) {
lua_setallocf(getLS(), f, ud);
}
void LuaState::setField(int idx, const LCValue& key, const LCValue& val) {
idx = absIndex(idx);
push(key);
push(val);
setTable(idx);
}
void LuaState::setGlobal(const LCValue& key) {
pushGlobal();
push(key);
pushValue(-3);
// [value][Global][key][value]
setTable(-3);
pop(2);
}
void LuaState::setMetatable(const int idx) {
lua_setmetatable(getLS(), idx);
}
void LuaState::pushGlobal() {
pushValue(LUA_REGISTRYINDEX);
getField(-1, LUA_RIDX_GLOBALS);
// [Registry][Global]
remove(-2);
}
void LuaState::setTable(const int idx) {
lua_settable(getLS(), idx);
}
void LuaState::setTop(const int idx) {
lua_settop(getLS(), idx);
}
void LuaState::setUservalue(const int idx) {
lua_setuservalue(getLS(), idx);
}
const char* LuaState::setUpvalue(const int funcidx, const int n) {
return lua_setupvalue(getLS(), funcidx, n);
}
void* LuaState::upvalueId(const int funcidx, const int n) {
return lua_upvalueid(getLS(), funcidx, n);
}
void LuaState::upvalueJoin(const int funcidx0, const int n0, const int funcidx1, const int n1) {
lua_upvaluejoin(getLS(), funcidx0, n0, funcidx1, n1);
}
bool LuaState::status() const {
const int res = lua_status(getLS());
checkError(res);
return res != 0;
}
void LuaState::checkType(const int idx, const LuaType typ) const {
const LuaType t = type(idx);
if(t != typ)
throw EType(getLS(), typ, t);
}
void LuaState::CheckType(lua_State* ls, const int idx, const LuaType typ) {
LuaState lsc(ls, true);
lsc.checkType(idx, typ);
}
bool LuaState::toBoolean(const int idx) const {
return LCV<bool>()(idx, getLS(), nullptr);
}
lua_CFunction LuaState::toCFunction(const int idx) const {
return LCV<lua_CFunction>()(idx, getLS(), nullptr);
}
lua_Integer LuaState::toInteger(const int idx) const {
return LCV<lua_Integer>()(idx, getLS(), nullptr);
}
std::string LuaState::toString(const int idx) const {
return LCV<std::string>()(idx, getLS(), nullptr);
}
std::string LuaState::cnvString(int idx) {
idx = absIndex(idx);
getGlobal(luaNS::ToString);
pushValue(idx);
call(1,1);
std::string ret = toString(-1);
pop(1);
return ret;
}
lua_Number LuaState::toNumber(const int idx) const {
return LCV<lua_Number>()(idx, getLS(), nullptr);
}
const void* LuaState::toPointer(const int idx) const {
return lua_topointer(getLS(), idx);
}
Lua_SP LuaState::toThread(const int idx) const {
return LCV<Lua_SP>()(idx, getLS(), nullptr);
}
void* LuaState::toUserData(const int idx) const {
return LCV<void*>()(idx, getLS(), nullptr);
}
LCTable_SP LuaState::toTable(const int idx, LPointerSP* spm) const {
return LCV<LCTable_SP>()(idx, getLS(), spm);
}
LCValue LuaState::toLCValue(const int idx, LPointerSP* spm) const {
return LCV<LCValue>()(idx, getLS(), spm);
}
LuaType LuaState::type(const int idx) const {
return SType(getLS(), idx);
}
LuaType LuaState::SType(lua_State* ls, const int idx) {
const int typ = lua_type(ls, idx);
return static_cast<LuaType::e>(typ);
}
const char* LuaState::typeName(const LuaType typ) const {
return STypeName(getLS(), typ);
}
const char* LuaState::STypeName(lua_State* ls, const LuaType typ) {
return lua_typename(ls,
static_cast<int>(typ));
}
const lua_Number* LuaState::version() const {
return lua_version(getLS());
}
void LuaState::xmove(const Lua_SP& to, const int n) {
lua_xmove(getLS(), to->getLS(), n);
}
int LuaState::yield(const int nresults) {
return lua_yield(getLS(), nresults);
}
int LuaState::yieldk(const int nresults, lua_KContext ctx, lua_KFunction k) {
return lua_yieldk(getLS(), nresults, ctx, k);
}
bool LuaState::prepareTable(const int idx, const LCValue& key) {
getField(idx, key);
if(type(-1) != LuaType::Table) {
// テーブルを作成
pop(1);
newTable();
push(key);
pushValue(-2);
// [Target][NewTable][key][NewTable]
setTable(-4);
return true;
}
return false;
}
bool LuaState::prepareTableGlobal(const LCValue& key) {
pushGlobal();
const bool b = prepareTable(-1, key);
remove(-2);
return b;
}
bool LuaState::prepareTableRegistry(const LCValue& key) {
pushValue(LUA_REGISTRYINDEX);
const bool b = prepareTable(-1, key);
remove(-2);
return b;
}
lua_State* LuaState::getLS() const {
return _lua.get();
}
Lua_SP LuaState::GetLS_SP(lua_State* ls) {
Lua_SP ret;
const RewindTop rt(ls);
LuaState lsc(ls, false);
lsc.getGlobal(cs_fromLua);
lsc.pushSelf();
lsc.getTable(-2);
if(lsc.type(-1) == LuaType::Userdata) {
// [fromLua][LuaState*]
return reinterpret_cast<Lua_WP*>(lsc.toUserData(-1))->lock();
}
lsc.pop(2);
// Cppでのみ生きているスレッド
lsc.getGlobal(cs_fromCpp);
const int idx = lsc.getTop();
// [fromCpp]
lsc.push(LuaNil{});
while(lsc.next(idx) != 0) {
// key=-2 value=-1
D_Assert0(lsc.type(-1) == LuaType::Thread);
if(lua_tothread(ls, -1) == ls)
return reinterpret_cast<LuaState*>(lsc.toUserData(-2))->shared_from_this();
lsc.pop(1);
}
return Lua_SP();
}
Lua_SP LuaState::getLS_SP() {
return shared_from_this();
}
Lua_SP LuaState::getMainLS_SP() {
if(_base)
return _base->getMainLS_SP();
return shared_from_this();
}
Lua_SP LuaState::GetMainLS_SP(lua_State* ls) {
const RewindTop rt(ls);
lua_getglobal(ls, cs_mainThreadPtr.c_str());
void* ptr = lua_touserdata(ls, -1);
return reinterpret_cast<LuaState*>(ptr)->shared_from_this();
}
void LuaState::checkError(const int code) const {
CheckError(getLS(), code);
}
void LuaState::CheckError(lua_State* ls, const int code) {
const CheckTop ct(ls);
if(code!=LUA_OK && code!=LUA_YIELD) {
const char* msg = LCV<const char*>()(-1, ls, nullptr);
switch(code) {
case LUA_ERRRUN:
throw ERun(msg);
case LUA_ERRMEM:
throw EMem(msg);
case LUA_ERRERR:
throw EError(msg);
case LUA_ERRSYNTAX:
throw ESyntax(msg);
case LUA_ERRGCMM:
throw EGC(msg);
}
throw EBase("unknown error-code", msg);
}
}
std::ostream& operator << (std::ostream& os, const LuaState& ls) {
// スタックの値を表示する
const int n = ls.getTop();
for(int i=1 ; i<=n ; i++)
os << "[" << i << "]: " << ls.toLCValue(i) << " (" << ls.type(i).toStr() << ")" << std::endl;
return os;
}
}
| 27.530191 | 102 | 0.658375 | degarashi |
f2e7dfd0dc05993a7fe9ccf12d63dcea44e78dc0 | 412 | cc | C++ | src/code_complete_cache.cc | Gei0r/cquery | 6ff8273e8b8624016f9363f444acfee30c4bbf64 | [
"MIT"
] | null | null | null | src/code_complete_cache.cc | Gei0r/cquery | 6ff8273e8b8624016f9363f444acfee30c4bbf64 | [
"MIT"
] | null | null | null | src/code_complete_cache.cc | Gei0r/cquery | 6ff8273e8b8624016f9363f444acfee30c4bbf64 | [
"MIT"
] | null | null | null | #include "code_complete_cache.h"
void CodeCompleteCache::WithLock(std::function<void()> action) {
std::lock_guard<std::mutex> lock(mutex_);
action();
}
bool CodeCompleteCache::IsCacheValid(lsTextDocumentPositionParams position) {
std::lock_guard<std::mutex> lock(mutex_);
return cached_path_ == position.textDocument.uri.GetAbsolutePath() &&
cached_completion_position_ == position.position;
} | 34.333333 | 77 | 0.759709 | Gei0r |
f2e9881742fc1b942ac3a60416ebf51b41d9dfbe | 829 | cpp | C++ | Olamundo/freq_0502/main.cpp | tosantos1/LIP | 7dbc045afa02729f4e2f2f1d3b29baebf5be72ad | [
"MIT"
] | null | null | null | Olamundo/freq_0502/main.cpp | tosantos1/LIP | 7dbc045afa02729f4e2f2f1d3b29baebf5be72ad | [
"MIT"
] | null | null | null | Olamundo/freq_0502/main.cpp | tosantos1/LIP | 7dbc045afa02729f4e2f2f1d3b29baebf5be72ad | [
"MIT"
] | null | null | null | #include <iostream>
/*Ordenação por referência
Complete o programa dado para que com apenas uma chamada
para o procedimento ordenarTres, os valores das variáveis a, b e c sejam colocados em ordem crescente.
Note que nenhuma alteração da função main nem do procedimento ordenarTres é necessária.*/
using namespace std;
int oQueEuFaco (int x, int y );
void oQueEuFaco(int &x, int &y);
void ordenarTres(int &x, int &y, int &z);
int main()
{
int a, b, c;
cin >> a >> b >> c;
ordenarTres(a, b, c);
cout << a << " " << b << " " << c << endl;
return 0;
}
//Este procedimento arranja os valores de x, y e z em ordem crescente
void ordenarTres(int &x, int &y, int &z)
{
oQueEuFaco(x, y);
oQueEuFaco(x, z);
oQueEuFaco(y, z);
}
int oQueEuFaco (int x, int y){
int a;
if ( x>y){
a=x;
x=y;
y=a;
}
}
| 18.840909 | 102 | 0.640531 | tosantos1 |
f2e9b05f3c16a26d7f319ac7e9a8750d8943d941 | 8,390 | cpp | C++ | Testbeds/GTests/twEventTest.cpp | microqq/TwinkleGraphics | e3975dc6dad5b6b8d5db1d54e30e815072db162e | [
"MIT"
] | null | null | null | Testbeds/GTests/twEventTest.cpp | microqq/TwinkleGraphics | e3975dc6dad5b6b8d5db1d54e30e815072db162e | [
"MIT"
] | 1 | 2020-07-03T03:13:39.000Z | 2020-07-03T03:13:39.000Z | Testbeds/GTests/twEventTest.cpp | microqq/TwinkleGraphics | e3975dc6dad5b6b8d5db1d54e30e815072db162e | [
"MIT"
] | null | null | null |
#include <functional>
#include <string>
#include <gtest/gtest.h>
#include "twEventHandler.h"
#include "twEventManager.h"
#include "twConsoleLog.h"
using namespace TwinkleGraphics;
class SampleListener
{
public:
SampleListener(){}
~SampleListener(){}
void OnBaseEvent(Object::Ptr sender, BaseEventArgs::Ptr e) const
{
Console::LogGTestInfo("Add SampleListener OnBaseEvent EventHandler.\n");
}
};
DefMemFuncType(SampleListener);
class SampleEventArgs : public BaseEventArgs
{
public:
typedef std::shared_ptr<SampleEventArgs> Ptr;
static EventId ID;
SampleEventArgs()
: BaseEventArgs()
{
}
virtual ~SampleEventArgs() {}
virtual EventId GetEventId() override
{
return SampleEventArgs::ID;
}
};
EventId SampleEventArgs::ID = std::hash<std::string>{}("SampleEventArgs");
class SampleEventArgsA : public BaseEventArgs
{
public:
typedef std::shared_ptr<SampleEventArgsA> Ptr;
static EventId ID;
SampleEventArgsA()
: BaseEventArgs()
{
}
virtual ~SampleEventArgsA() {}
virtual EventId GetEventId() override
{
return SampleEventArgsA::ID;
}
};
EventId SampleEventArgsA::ID = std::hash<std::string>{}("SampleEventArgsA");
// en.cppreference.com/w/cpp/utility/functional/function/target.html
void f(Object::Ptr, BaseEventArgs::Ptr)
{
Console::LogGTestInfo("Initialise Global f(******) EventHandler.\n");
}
void g(Object::Ptr, BaseEventArgs::Ptr) { }
void test(std::function<void(Object::Ptr, BaseEventArgs::Ptr)> arg)
{
typedef void (*FPTR)(Object::Ptr, BaseEventArgs::Ptr);
// void (*const* ptr)(Object::Ptr, BaseEventArgs::Ptr) =
// arg.target<void(*)(Object::Ptr, BaseEventArgs::Ptr)>();
FPTR* ptr= arg.target<FPTR>();
if (ptr && *ptr == f)
{
Console::LogGTestInfo("it is the function f\n");
}
else if (ptr && *ptr == g)
{
Console::LogGTestInfo("it is the function g\n");
}
else if(ptr)
{
Console::LogGTestInfo("it is not nullptr\n");
}
}
// en.cppreference.com/w/cpp/utility/functional/function.html
struct Foo {
Foo(int num) : num_(num) {}
void print_add(int i) const { Console::LogGTestInfo("Foo: ", num_+i, '\n'); }
int num_;
};
TEST(EventTests, AddEventHandler)
{
//EventHandler(const HandlerFunc& func)
EventHandler handler(
EventHandler::HandlerFunc(
[](Object::Ptr sender, BaseEventArgs::Ptr args) {
Console::LogGTestInfo("Initialise EventHandler.\n");
}
)
);
//Lambda handler function
EventHandler::HandlerFuncPointer lambda =
[](Object::Ptr sender, BaseEventArgs::Ptr args) {
Console::LogGTestInfo("Add Lambda Num(1) EventHandler.\n");
};
EventHandler::HandlerFunc lambdaFunc(lambda);
//EventHandler::operator+=
handler += lambdaFunc;
ASSERT_EQ(handler[1] != nullptr, true);
//EventHandler::operator-=
handler -= lambdaFunc;
ASSERT_EQ(handler.GetHandlerFuncSize(), 1);
// We won't use std::bind binding class member function
SampleListener listener;
// EventHandler::HandlerFunc baseFunc =
// std::bind(&SampleListener::OnBaseEvent, &listener, std::placeholders::_1, std::placeholders::_2);
// handlerRef += baseFunc;
Object::Ptr objectPtr = std::make_shared<Object>();
SampleEventArgs::Ptr sampleEvent1 = std::make_shared<SampleEventArgs>();
SampleEventArgs::Ptr sampleEvent2 = std::make_shared<SampleEventArgs>();
SampleEventArgsA::Ptr sampleEventA = std::make_shared<SampleEventArgsA>();
ASSERT_EQ(sampleEvent1->GetEventId() != -1, true);
ASSERT_EQ(sampleEvent2->GetEventId() != -1, true);
ASSERT_EQ(sampleEventA->GetEventId() != -1, true);
ASSERT_EQ(sampleEventA->GetEventId() != sampleEvent1->GetEventId(), true);
ASSERT_EQ(sampleEvent2->GetEventId() != sampleEvent1->GetEventId(), false);
Console::LogGTestInfo("SampleEvent Instance 1 EventId: ", sampleEvent1->GetEventId(), "\n");
Console::LogGTestInfo("SampleEvent Instance 2 EventId: ", sampleEvent2->GetEventId(), "\n");
Console::LogGTestInfo("SampleEventA EventId: ", sampleEventA->GetEventId(), "\n");
handler.Invoke(objectPtr, sampleEvent1);
};
TEST(EventTests, FireEvent)
{
EventManagerInst eventMgrInst;
SampleEventArgsA::Ptr sampleEventA = std::make_shared<SampleEventArgsA>();
//EventHandler(const HandlerFunc& func)
EventHandler handler(
EventHandler::HandlerFunc(
[](Object::Ptr sender, BaseEventArgs::Ptr args) {
Console::LogGTestInfo("Initialise EventHandler.\n");
}
)
);
//Lambda handler function
EventHandler::HandlerFuncPointer lambda =
[](Object::Ptr sender, BaseEventArgs::Ptr args) {
Console::LogGTestInfo("Add Lambda Num(1) EventHandler.\n");
};
Console::LogGTestInfo("Lambda function address: ", size_t(lambda), "\n");
EventHandler::HandlerFunc lambdaFunc(lambda);
//EventHandler::operator+=
handler += lambdaFunc;
ASSERT_EQ(handler[1] != nullptr, true);
handler += lambdaFunc;
ASSERT_EQ(handler.GetHandlerFuncSize(), 2);
eventMgrInst->Subscribe(SampleEventArgsA::ID, handler);
Console::LogGTestInfo("Fire SampleEventArgsA--------1\n");
eventMgrInst->FireImmediately(nullptr, sampleEventA);
//EventHandler::operator-=
handler -= lambdaFunc;
ASSERT_EQ(handler.GetHandlerFuncSize(), 1);
// handler updated, so first unsubscribe and then subscribe again
eventMgrInst->UnSubscribe(SampleEventArgsA::ID, handler);
eventMgrInst->Subscribe(SampleEventArgsA::ID, handler);
eventMgrInst->Subscribe(SampleEventArgsA::ID, handler);
eventMgrInst->Subscribe(SampleEventArgsA::ID, handler);
Console::LogGTestInfo("Fire SampleEventArgsA--------2\n");
eventMgrInst->FireImmediately(nullptr, sampleEventA);
handler.Remove(0);
handler += lambdaFunc;
ASSERT_EQ(handler.GetHandlerFuncSize(), 1);
eventMgrInst->UnSubscribe(SampleEventArgsA::ID, handler);
eventMgrInst->UnSubscribe(SampleEventArgsA::ID, handler);
eventMgrInst->UnSubscribe(SampleEventArgsA::ID, handler);
eventMgrInst->Subscribe(SampleEventArgsA::ID, handler);
Console::LogGTestInfo("Fire SampleEventArgsA--------3\n");
eventMgrInst->FireImmediately(nullptr, sampleEventA);
//Bind class member function
// SampleListener listener;
// EventHandler::HandlerFunc sampleListenerHFunc = std::bind(&SampleListener::OnBaseEvent, &listener, std::placeholders::_1, std::placeholders::_2);
EventHandler::HandlerFuncPointer lambda2 =
[](Object::Ptr sender, BaseEventArgs::Ptr args){
SampleListener* listener = dynamic_cast<SampleListener*>(sender.get());
listener->OnBaseEvent(sender, args);
};
EventHandler::HandlerFunc lambda2Func(lambda2);
handler += lambda2Func;
handler += lambda2Func;
handler += lambda2Func;
handler -= lambda2Func;
EventHandlerCallBack(lambda3, SampleListener, OnBaseEvent);
RegisterEventHandlerCallBack(handler, lambda3);
UnRegisterEventHandlerCallBack(handler, lambda3);
RegisterEventHandlerCallBack(handler, lambda3);
EventHandler::HandlerFunc lambda3Func(f);
handler += lambda3Func;
handler += lambda3Func;
handler += lambda3Func;
eventMgrInst->UnSubscribe(SampleEventArgsA::ID, handler);
eventMgrInst->Subscribe(SampleEventArgsA::ID, handler);
eventMgrInst->Subscribe(SampleEventArgsA::ID, handler);
eventMgrInst->Subscribe(SampleEventArgsA::ID, handler);
Console::LogGTestInfo("Fire SampleEventArgsA--------4\n");
eventMgrInst->FireImmediately(nullptr, sampleEventA);
// en.cppreference.com/w/cpp/utility/functional/function.html
// std::function<void(const SampleListener&, Object::Ptr, BaseEventArgs::Ptr)> fffFunc = &SampleListener::OnBaseEvent;
std::function<void(const Foo&, int)> f_add_display = &Foo::print_add;
const Foo foo(314159);
f_add_display(foo, 1);
f_add_display(314159, 1);
// en.cppreference.com/w/cpp/utility/functional/function/target.html
test(std::function<void(Object::Ptr, BaseEventArgs::Ptr)>(f));
test(std::function<void(Object::Ptr, BaseEventArgs::Ptr)>(g));
test(std::function<void(Object::Ptr, BaseEventArgs::Ptr)>(lambda3));
} | 33.031496 | 152 | 0.682956 | microqq |
f2edbea3f6ac2b4c696a67227a8cf853d76b3482 | 4,716 | cpp | C++ | src/vi/vi_db.cpp | liulixinkerry/ripple | 330522a61bcf1cf290c100ce4686ed62dcdc5cab | [
"Unlicense"
] | 7 | 2021-01-25T04:28:38.000Z | 2021-11-20T04:14:14.000Z | src/vi/vi_db.cpp | Xingquan-Li/ripple | 330522a61bcf1cf290c100ce4686ed62dcdc5cab | [
"Unlicense"
] | 3 | 2021-02-25T08:13:41.000Z | 2022-02-25T16:37:16.000Z | src/vi/vi_db.cpp | Xingquan-Li/ripple | 330522a61bcf1cf290c100ce4686ed62dcdc5cab | [
"Unlicense"
] | 8 | 2021-02-27T13:52:25.000Z | 2021-11-15T08:01:02.000Z | #include "../db/db.h"
using namespace db;
#include "vi.h"
using namespace vi;
#include "../ut/utils.h"
void Geometry::draw(Visualizer* v, const Layer& L) const {
if ((L.rIndex >= 0 || L.cIndex >= 0) && layer != L) {
return;
}
if (layer.rIndex >= 0) {
v->setFillColor(v->scheme.metalFill[layer.rIndex]);
v->setLineColor(v->scheme.metalLine[layer.rIndex]);
} else if (layer.cIndex >= 0) {
v->setFillColor(v->scheme.metalFill[layer.cIndex]);
v->setLineColor(v->scheme.metalLine[layer.cIndex]);
}
const int lx = globalX();
const int ly = globalY();
const int hx = globalX() + boundR();
const int hy = globalY() + boundT();
v->drawRect(lx, ly, hx, hy, true, true);
}
void Cell::draw(Visualizer* v) const {
if (!(region->id)) {
v->setFillColor(v->scheme.instanceFill);
v->setLineColor(v->scheme.instanceLine);
} else {
int r = (region->id * 100) % 256;
int g = (region->id * 200) % 256;
v->setFillColor(Color(r, g, 255));
v->setLineColor(Color(r / 2, g / 2, 128));
}
int lx = globalX();
int ly = globalY();
int hx = globalX() + boundR();
int hy = globalY() + boundT();
// printlog(LOG_INFO, "cell : %d %d %d %d", lx, ly, hx, hy);
v->drawRect(lx, ly, hx, hy, true, true);
}
void IOPin::draw(Visualizer* v, Layer& L) const { type->shapes[0].draw(v, L); }
void Pin::draw(Visualizer* v, const Layer& L) const {
for (const Geometry& shape : type->shapes) {
shape.draw(v, L);
}
}
void Net::draw(Visualizer* v, const Layer& L) const {
for (const Pin* pin : pins) {
pin->draw(v, L);
}
}
void SNet::draw(Visualizer* v, Layer& L) const {
for (const Geometry& shape : shapes) {
shape.draw(v, L);
}
for (const Via& via : vias) {
via.draw(v, L);
}
}
void Row::draw(Visualizer* v) const {
v->setFillColor(v->scheme.rowFill);
v->setLineColor(v->scheme.rowLine);
v->drawRect(_x, _y, _x + _xStep * _xNum, _y + _yStep * _yNum, true, true);
}
void Via::draw(Visualizer* v, Layer& L) const {
for (const Geometry& rect : type->rects) {
rect.draw(v);
}
}
void Region::draw(Visualizer* v) const {
int nRects = rects.size();
for (int i = 0; i < nRects; i++) {
v->setFillColor(v->scheme.regionFill);
v->setLineColor(Color(0, 0, 0));
v->drawRect(rects[i].lx, rects[i].ly, rects[i].hx, rects[i].hy, true, true);
}
}
void SiteMap::draw(Visualizer* v) const {
int lx, ly, hx, hy;
for (int x = 0; x < siteNX; x++) {
for (int y = 0; y < siteNY; y++) {
unsigned char regionID = getRegion(x, y);
bool blocked = getSiteMap(x, y, SiteMap::SiteBlocked);
if (blocked) {
v->setFillColor(Color(0, 0, 0));
getSiteBound(x, y, lx, ly, hx, hy);
v->drawRect(lx, ly, hx, hy, true, false);
} else if (regionID == Region::InvalidRegion) {
v->setFillColor(Color(255, 0, 0));
getSiteBound(x, y, lx, ly, hx, hy);
v->drawRect(lx, ly, hx, hy, true, false);
} else if (regionID > 0) {
v->setFillColor(v->scheme.regionFill);
getSiteBound(x, y, lx, ly, hx, hy);
v->drawRect(lx, ly, hx, hy, true, false);
}
}
}
}
void Database::draw(Visualizer* v) const {
v->reset(v->scheme.background);
int nRows = rows.size();
for (int i = 0; i < nRows; i++) {
rows[i]->draw(v);
}
int nCells = cells.size();
for (int i = 0; i < nCells; i++) {
cells[i]->draw(v);
}
/*
int nRegions = regions.size();
for(int i=1; i<nRegions; i++){
regions[i]->draw(v);
}
*/
// siteMap.draw(v);
/* draw metal objects */
unsigned nLayers = layers.size();
for (unsigned i = 0; i != nLayers; ++i) {
const Layer* layer = nullptr;
if (i % 2) {
layer = database.getCLayer(i / 2);
} else {
layer = database.getRLayer(i / 2);
}
if (!layer) {
continue;
}
// printlog(LOG_INFO, "draw layer %s", layer->name.c_str());
for (const Net* net : nets) {
net->draw(v, *layer);
}
}
/*
v->setFillColor(Color(255,0,0));
for(int x=0; x<grGrid.trackNX; x++){
for(int y=0; y<grGrid.trackNY; y++){
int dx = grGrid.trackL + x * grGrid.trackStepX;
int dy = grGrid.trackB + y * grGrid.trackStepY;
if(grGrid.getRGrid(x, y, 2) == (char)1){
v->drawPoint(dx, dy, 1);
}
}
}
*/
}
| 28.756098 | 84 | 0.516327 | liulixinkerry |
f2f3834523da7253561a9831549f255536882d88 | 4,689 | inl | C++ | include/quadtree.inl | MaxAlzner/libtree | 80501e15fdec77e1f1824b46ebd3ae1c1cedd7f8 | [
"MIT"
] | null | null | null | include/quadtree.inl | MaxAlzner/libtree | 80501e15fdec77e1f1824b46ebd3ae1c1cedd7f8 | [
"MIT"
] | null | null | null | include/quadtree.inl | MaxAlzner/libtree | 80501e15fdec77e1f1824b46ebd3ae1c1cedd7f8 | [
"MIT"
] | null | null | null | #pragma once
template <typename T> inline bool quadnode_t<T>::empty() const
{
return this->_tree == 0 || this->_ring < 0 || this->_branch < 0;
}
template <typename T> inline size_t quadnode_t<T>::index() const
{
return tree_index(this->_ring, this->_branch, 4);
}
template <typename T> inline quaditerator_t<T> quaditerator_t<T>::child(const int32_t quadrant)
{
if (this->_node != 0)
{
switch (quadrant)
{
case 0:
return quaditerator_t<T>(this->_node->_q0);
case 1:
return quaditerator_t<T>(this->_node->_q1);
case 2:
return quaditerator_t<T>(this->_node->_q2);
case 3:
return quaditerator_t<T>(this->_node->_q3);
default:
break;
}
}
return quaditerator_t<T>();
}
template <typename T> inline quaditerator_t<T> quaditerator_t<T>::parent()
{
return this->_node != 0 && this->_node->_up != 0 ? quaditerator_t<T>(this->_node->_up) : quaditerator_t<T>();
}
template <typename T> inline quaditerator_t<T> quaditerator_t<T>::remove()
{
if (this->_node != 0)
{
treereference_t<quadnode_t<T> > prev = this->_node;
if (prev->_up != 0)
{
if (prev->_up->_q0 == prev) { prev->_up->_q0 = -1; }
else if (prev->_up->_q1 == prev) { prev->_up->_q1 = -1; }
else if (prev->_up->_q2 == prev) { prev->_up->_q2 = -1; }
else if (prev->_up->_q3 == prev) { prev->_up->_q3 = -1; }
}
this->_node = prev->_up;
prev->_tree->_registry.remove(prev->index());
if (this->_node != 0)
{
return quaditerator_t<T>(this->_node);
}
}
return quaditerator_t<T>();
}
template <typename T> inline bool quaditerator_t<T>::root() const
{
return this->_node != 0 && this->_node->_parent == 0;
}
template <typename T> inline bool quaditerator_t<T>::leaf() const
{
return this->_node != 0 && this->_node->_left == 0 && this->_node->_right == 0;
}
template <typename T> inline bool quaditerator_t<T>::empty() const
{
return this->_node == 0;
}
template <typename T> inline T& quaditerator_t<T>::operator*() const
{
return *(this->_node->_data);
}
template <typename T> inline quaditerator_t<T> quaditerator_t<T>::operator[](const int32_t quadrant)
{
return this->child(quadrant);
}
template <typename T> inline bool quaditerator_t<T>::operator==(const quaditerator_t<T>& other) const
{
return this->_node == other._node;
}
template <typename T> inline bool quaditerator_t<T>::operator!=(const quaditerator_t<T>& other) const
{
return this->_node != other._node;
}
#include <stdio.h>
template <typename T> inline quaditerator_t<T> quadtree_t<T>::set_root(const T& item)
{
this->_registry.zero();
this->_registry[0] = quadnode_t<T>(*this, 0, 0, item);
return quaditerator_t<T>(treereference_t<quadnode_t<T> >(this->_registry, 0));
}
template <typename T> inline quaditerator_t<T> quadtree_t<T>::search(const T& item)
{
for (size_t i = 0; i < this->_registry.capacity(); i++)
{
treereference_t<quadnode_t<T> > node(this->_registry, i);
if (!node.empty() && !node->empty() && memcmp(&(node->_data), &item, sizeof(T)) == 0)
{
return quaditerator_t<T>(node);
}
}
return quaditerator_t<T>();
}
template <typename T> inline quaditerator_t<T> quadtree_t<T>::root()
{
return quaditerator_t<T>(treereference_t<quadnode_t<T> >(this->_registry, 0));
}
template <typename T> inline quaditerator_t<T> quadtree_t<T>::end() const
{
return quaditerator_t<T>();
}
template <typename T> inline void quadtree_t<T>::each(iterationfunc callback)
{
execute_each(treereference_t<quadnode_t<T> >(this->_registry, 0), callback);
}
template <typename T> inline void quadtree_t<T>::path(iterationfunc callback)
{
execute_path(treereference_t<quadnode_t<T> >(this->_registry, 0), callback);
}
template <typename T> inline void quadtree_t<T>::clear()
{
this->_registry.clear();
}
template <typename T> int32_t quadtree_t<T>::execute_each(const treereference_t<quadnode_t<T> >& node, iterationfunc callback)
{
int32_t result = 1;
if (node != 0 && !node.empty() && !node->empty() && callback != 0)
{
result = callback(node, node->_data);
// if (result != 0)
// {
// result = execute_each(node->_left, callback);
// if (result != 0)
// {
// result = execute_each(node->_right, callback);
// }
// }
}
return result;
}
template <typename T> int32_t quadtree_t<T>::execute_path(const treereference_t<quadnode_t<T> >& node, iterationfunc callback)
{
int32_t result = 0;
if (node != 0 && !node.empty() && !node->empty() && callback != 0)
{
result = callback(node, node->_data);
// if (result != 0)
// {
// if (result > 0)
// {
// return execute_path(node->_left, callback);
// }
// else
// {
// return execute_path(node->_right, callback);
// }
// }
}
return result;
} | 26.342697 | 126 | 0.656856 | MaxAlzner |
f2f99b32899966a08f5aa199583f70adc9ac009d | 3,575 | tcc | C++ | src/utils/json/parser.tcc | unbornchikken/reflect-cpp | 1a9a3d107c952406d3b7cae4bc5a6a23d566ea4f | [
"BSD-2-Clause"
] | 45 | 2015-03-24T09:35:46.000Z | 2021-05-06T11:50:34.000Z | src/utils/json/parser.tcc | unbornchikken/reflect-cpp | 1a9a3d107c952406d3b7cae4bc5a6a23d566ea4f | [
"BSD-2-Clause"
] | null | null | null | src/utils/json/parser.tcc | unbornchikken/reflect-cpp | 1a9a3d107c952406d3b7cae4bc5a6a23d566ea4f | [
"BSD-2-Clause"
] | 11 | 2015-01-27T12:08:21.000Z | 2020-08-29T16:34:13.000Z | /* parser.tcc -*- C++ -*-
Rémi Attab ([email protected]), 12 Apr 2015
FreeBSD-style copyright and disclaimer apply
*/
#include "json.h"
#pragma once
namespace reflect {
namespace json {
/******************************************************************************/
/* GENERIC PARSER */
/******************************************************************************/
void parseNull(Reader& reader)
{
reader.expectToken(Token::Null);
}
bool parseBool(Reader& reader)
{
return reader.expectToken(Token::Bool).asBool();
}
int64_t parseInt(Reader& reader)
{
return reader.expectToken(Token::Int).asInt();
}
double parseFloat(Reader& reader)
{
Token token = reader.nextToken();
if (token.type() == Token::Int);
else reader.assertToken(token, Token::Float);
return token.asFloat();
}
std::string parseString(Reader& reader)
{
return reader.expectToken(Token::String).asString();
}
template<typename Fn>
void parseObject(Reader& reader, const Fn& fn)
{
Token token = reader.nextToken();
if (token.type() == Token::Null) return;
reader.assertToken(token, Token::ObjectStart);
token = reader.peekToken();
if (token.type() == Token::ObjectEnd) {
reader.expectToken(Token::ObjectEnd);
return;
}
while (reader) {
token = reader.expectToken(Token::String);
const std::string& key = token.asString();
token = reader.expectToken(Token::KeySeparator);
fn(key);
token = reader.nextToken();
if (token.type() == Token::ObjectEnd) return;
reader.assertToken(token, Token::Separator);
}
}
template<typename Fn>
void parseArray(Reader& reader, const Fn& fn)
{
Token token = reader.nextToken();
if (token.type() == Token::Null) return;
reader.assertToken(token, Token::ArrayStart);
token = reader.peekToken();
if (token.type() == Token::ArrayEnd) {
reader.expectToken(Token::ArrayEnd);
return;
}
for (size_t i = 0; reader; ++i) {
fn(i);
token = reader.nextToken();
if (token.type() == Token::ArrayEnd) return;
reader.assertToken(token, Token::Separator);
}
}
void skip(Reader& reader)
{
Token token = reader.peekToken();
if (!reader) return;
switch (token.type()) {
case Token::Null:
case Token::Bool:
case Token::Int:
case Token::Float:
case Token::String:
(void) reader.nextToken();
break;
case Token::ArrayStart:
parseArray(reader, [&] (size_t) { skip(reader); });
break;
case Token::ObjectStart:
parseObject(reader, [&] (const std::string&) { skip(reader); });
break;
default:
reader.error("unable to skip token %s", token);
break;
}
}
/******************************************************************************/
/* VALUE PARSER */
/******************************************************************************/
template<typename T>
void parse(Reader& reader, T& value)
{
Value v = cast<Value>(value);
parse(reader, v);
}
template<typename T>
Error parse(std::istream& stream, T& value)
{
Reader reader(stream);
parse(reader, value);
return reader.error();
}
template<typename T>
Error parse(const std::string& str, T& value)
{
std::istringstream stream(str);
return parse(stream, value);
}
} // namespace json
} // namespace reflect
| 23.064516 | 80 | 0.53958 | unbornchikken |
f2f9f2b8b37680de67e251215bbab012254aa65a | 290 | hpp | C++ | src/Game.hpp | ara159/snake | c65b25ab50a4b867f941c0a5406a11071ff80b78 | [
"MIT"
] | null | null | null | src/Game.hpp | ara159/snake | c65b25ab50a4b867f941c0a5406a11071ff80b78 | [
"MIT"
] | null | null | null | src/Game.hpp | ara159/snake | c65b25ab50a4b867f941c0a5406a11071ff80b78 | [
"MIT"
] | null | null | null | #ifndef GAME_H
#define GAME_H 1
#include "SFML/Graphics.hpp"
#include "Snake.hpp"
using namespace sf;
class Game
{
private:
RenderWindow * window;
void run();
void event_handler();
void draw();
Snake snake;
public:
Game();
~Game();
void start();
};
#endif | 13.181818 | 28 | 0.627586 | ara159 |
f2ffc7cc13c60374f92699e9abddec3f51196fdc | 3,184 | cpp | C++ | dynamic programming/dp3-27 gfg-leetcode/dp3 - 300. Longest Increasing Subsequence.cpp | ankithans/dsa | 32aeeff1b4eeebcc8c18fdb1b95ee1dd123f8443 | [
"MIT"
] | 1 | 2021-09-16T07:01:46.000Z | 2021-09-16T07:01:46.000Z | dynamic programming/dp3-27 gfg-leetcode/dp3 - 300. Longest Increasing Subsequence.cpp | ankithans/dsa | 32aeeff1b4eeebcc8c18fdb1b95ee1dd123f8443 | [
"MIT"
] | null | null | null | dynamic programming/dp3-27 gfg-leetcode/dp3 - 300. Longest Increasing Subsequence.cpp | ankithans/dsa | 32aeeff1b4eeebcc8c18fdb1b95ee1dd123f8443 | [
"MIT"
] | 1 | 2021-10-19T06:48:48.000Z | 2021-10-19T06:48:48.000Z | // 0 1 2 3 4 5 6 7
// [10,9,2,5,3,7,101,18]
// o/p = 4 [2,3,7,101]
// idx -> f -> LIS
// (0, [])
// 2 (1, [10]) (1, [])
// (2,[10]) (2,[9]) (2,[])
// (3,[10]) (3,[9])
// (4,[10]) (4,[9])
// (5,[10])
// (6,[10,101]) (6,[10])
// (7,[10,101]) (7,[10,18]) (7,[10])
// 22 / 54 test cases passed.
// TLE
class Solution {
public:
int LIShelper(int idx, int lastMax, vector<int> &nums) {
if(idx >= nums.size())
return 0;
int pick = INT_MIN;
if(nums[idx] > lastMax) {
pick = 1 + LIShelper(idx+1, nums[idx], nums);
}
int not_pick = LIShelper(idx+1, lastMax, nums);
return max(pick, not_pick);
}
int lengthOfLIS(vector<int>& nums) {
return LIShelper(0, INT_MIN, nums);
}
};
class Solution {
public:
int LIShelper(vector<int> &nums, int idx, int lastMax, vector<int> &dp) {
if(idx >= nums.size())
return 0;
int pick = INT_MIN;
if(nums[idx] > lastMax) {
if(dp[idx] != -1) pick = dp[idx];
else
dp[idx] = pick = 1 + LIShelper(nums, idx+1, nums[idx], dp);
}
int not_pick = LIShelper(nums, idx+1, lastMax, dp);
return max(pick, not_pick);
}
int lengthOfLIS(vector<int>& nums) {
vector<int> dp(nums.size()+1, -1);
return LIShelper(nums, 0, INT_MIN, dp);
}
};
// https://leetcode.com/problems/longest-increasing-subsequence/discuss/1326552/Optimization-From-Brute-Force-to-Dynamic-Programming-Explained!
class Solution {
public:
vector<vector<int>> dp;
int LIShelper(vector<int> &nums, int idx, int lastMaxInd) {
if(idx >= nums.size())
return 0;
if(dp[idx][lastMaxInd+1] != -1) return dp[idx][lastMaxInd+1];
int pick = INT_MIN;
if(lastMaxInd == -1 || nums[idx] > nums[lastMaxInd]) {
pick = 1 + LIShelper(nums, idx+1, idx);
}
int not_pick = LIShelper(nums, idx+1, lastMaxInd);
return dp[idx][lastMaxInd+1] = max(pick, not_pick);
}
int lengthOfLIS(vector<int>& nums) {
dp.resize(size(nums), vector<int>(1+size(nums), -1));
return LIShelper(nums, 0, -1);
}
};
class Solution {
public:
vector<int> dp;
int LIShelper(vector<int> &nums, int idx, int lastMaxInd) {
if(idx >= nums.size())
return 0;
if(dp[lastMaxInd+1] != -1) return dp[lastMaxInd+1];
int pick = INT_MIN;
if(lastMaxInd == -1 || nums[idx] > nums[lastMaxInd]) {
pick = 1 + LIShelper(nums, idx+1, idx);
}
int not_pick = LIShelper(nums, idx+1, lastMaxInd);
return dp[lastMaxInd+1] = max(pick, not_pick);
}
int lengthOfLIS(vector<int>& nums) {
dp.resize(size(nums)+1, -1);
return LIShelper(nums, 0, -1);
}
};
| 26.983051 | 143 | 0.47142 | ankithans |
8404279ffd536f25360485833c7e0df1f9a555f5 | 2,249 | cpp | C++ | src/minhook_api.cpp | MG4vQIs7Fv/PerformanceOverhaulCyberpunk | 4fb6e34752ce7c286357cf148d0b4096d4ca32ea | [
"MIT"
] | 26 | 2019-10-28T00:14:18.000Z | 2022-03-05T22:26:46.000Z | src/minhook_api.cpp | MG4vQIs7Fv/PerformanceOverhaulCyberpunk | 4fb6e34752ce7c286357cf148d0b4096d4ca32ea | [
"MIT"
] | null | null | null | src/minhook_api.cpp | MG4vQIs7Fv/PerformanceOverhaulCyberpunk | 4fb6e34752ce7c286357cf148d0b4096d4ca32ea | [
"MIT"
] | 7 | 2019-10-28T03:21:19.000Z | 2022-03-25T11:05:43.000Z | #include "common.hpp"
#include "minhook_api.hpp"
#include "minhook.h"
namespace minhook_api {
#if defined(USE_MINHOOK) && (USE_MINHOOK == 1)
void init() {
if(MH_Initialize() != MH_OK) {
DEBUG_TRACE("MH_Initialize : failed\n");
}
}
void cleanup() {
MH_Uninitialize();
}
#else
void init() {}
void cleanup() {}
#endif
} // namespace minhook
#if defined(USE_MINHOOK) && (USE_MINHOOK == 1)
#define D(funcname, ...) \
return funcname(__VA_ARGS__); \
__pragma(comment(linker, "/EXPORT:" __FUNCTION__ "=" __FUNCDNAME__))
extern "C" MH_STATUS WINAPI MH_Initialize_(void) {
D(MH_Initialize)
}
extern "C" MH_STATUS WINAPI MH_Uninitialize_(void) {
D(MH_Uninitialize);
}
extern "C" MH_STATUS WINAPI MH_CreateHook_(LPVOID pTarget, LPVOID pDetour, LPVOID *ppOriginal) {
D(MH_CreateHook, pTarget, pDetour, ppOriginal);
}
extern "C" MH_STATUS WINAPI MH_CreateHookApi_(LPCWSTR pszModule, LPCSTR pszProcName, LPVOID pDetour, LPVOID *ppOriginal) {
D(MH_CreateHookApi, pszModule, pszProcName, pDetour, ppOriginal);
}
extern "C" MH_STATUS WINAPI MH_CreateHookApiEx_(LPCWSTR pszModule, LPCSTR pszProcName, LPVOID pDetour, LPVOID *ppOriginal, LPVOID *ppTarget) {
D(MH_CreateHookApiEx, pszModule, pszProcName, pDetour, ppOriginal, ppTarget);
}
extern "C" MH_STATUS WINAPI MH_RemoveHook_(LPVOID pTarget) {
D(MH_RemoveHook, pTarget);
}
extern "C" MH_STATUS WINAPI MH_EnableHook_(LPVOID pTarget) {
D(MH_EnableHook, pTarget);
}
extern "C" MH_STATUS WINAPI MH_DisableHook_(LPVOID pTarget) {
D(MH_DisableHook, pTarget);
}
extern "C" MH_STATUS WINAPI MH_QueueEnableHook_(LPVOID pTarget) {
D(MH_QueueEnableHook, pTarget);
}
extern "C" MH_STATUS WINAPI MH_QueueDisableHook_(LPVOID pTarget) {
D(MH_QueueDisableHook, pTarget);
}
extern "C" MH_STATUS WINAPI MH_ApplyQueued_(void) {
D(MH_ApplyQueued);
}
extern "C" const char * WINAPI MH_StatusToString_(MH_STATUS status) {
D(MH_StatusToString, status);
}
#endif
| 28.833333 | 142 | 0.638061 | MG4vQIs7Fv |
8405943d2334623503f09655d041c70e5d8bc794 | 483 | cpp | C++ | C++ STL Programming/C++_STL_Programming/Operator_Overloading/06_PlusOperatorFuncion.cpp | devgunho/Cpp_AtoZ | 4d87f22671a4eab06ca35b32c9b7f8f9abadb2bc | [
"MIT"
] | 1 | 2022-03-25T06:11:06.000Z | 2022-03-25T06:11:06.000Z | C++ STL Programming/C++_STL_Programming/Operator_Overloading/06_PlusOperatorFuncion.cpp | devgunho/Cpp_AtoZ | 4d87f22671a4eab06ca35b32c9b7f8f9abadb2bc | [
"MIT"
] | null | null | null | C++ STL Programming/C++_STL_Programming/Operator_Overloading/06_PlusOperatorFuncion.cpp | devgunho/Cpp_AtoZ | 4d87f22671a4eab06ca35b32c9b7f8f9abadb2bc | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
class Point
{
int x;
int y;
public:
Point(int _x = 0, int _y = 0) :x(_x), y(_y) {}
void Print() const { cout << x << ',' << y << endl; }
const Point operator+(const Point& arg) const
{
Point pt;
pt.x = this->x + arg.x;
pt.y = this->y + arg.y;
return pt;
}
};
int main()
{
Point p1(2, 3), p2(5, 5);
Point p3;
p3 = p1 + p2; // = p1.operator+(p2)
p3.Print();
p3 = p1.operator+(p2); // Direct call
p3.Print();
return 0;
} | 16.1 | 54 | 0.554865 | devgunho |
8406a1d0255cf5abbe189d3c0beeb27a9a93973a | 389 | hpp | C++ | src/firmware/src/websocket/socket_server.hpp | geaz/tableDisco | 1f081a0372da835150881da245dc69d97dcaabe3 | [
"MIT"
] | 1 | 2020-05-26T01:45:04.000Z | 2020-05-26T01:45:04.000Z | src/firmware/src/websocket/socket_server.hpp | geaz/tableDisco | 1f081a0372da835150881da245dc69d97dcaabe3 | [
"MIT"
] | null | null | null | src/firmware/src/websocket/socket_server.hpp | geaz/tableDisco | 1f081a0372da835150881da245dc69d97dcaabe3 | [
"MIT"
] | null | null | null | #pragma once
#ifndef SOCKETSERVER_H
#define SOCKETSERVER_H
#include <WebSocketsServer.h>
namespace TableDisco
{
class SocketServer
{
public:
SocketServer();
void loop();
void broadcast(String data);
private:
WebSocketsServer webSocket = WebSocketsServer(81);
};
}
#endif // SOCKETSERVER_H | 17.681818 | 62 | 0.586118 | geaz |
8406dca80a0a5d0c040e297255c6eae5b07d4f27 | 2,391 | cpp | C++ | src/index_handler/index_file_handler.cpp | robinren03/database2021 | 50074b6fdab2bcd5d4c95870f247cfb430804081 | [
"Apache-2.0"
] | null | null | null | src/index_handler/index_file_handler.cpp | robinren03/database2021 | 50074b6fdab2bcd5d4c95870f247cfb430804081 | [
"Apache-2.0"
] | null | null | null | src/index_handler/index_file_handler.cpp | robinren03/database2021 | 50074b6fdab2bcd5d4c95870f247cfb430804081 | [
"Apache-2.0"
] | 1 | 2022-01-11T08:20:41.000Z | 2022-01-11T08:20:41.000Z | #include "index_file_handler.h"
#include <assert.h>
IndexFileHandler::IndexFileHandler(BufManager* _bm){
bm = _bm;
header = new IndexFileHeader;
}
void IndexFileHandler::openFile(const char* fileName){
fileID = bm->openFile(fileName);
int headerIndex;
if (fileID == -1){
bm->createFile(fileName);
fileID = bm->openFile(fileName);
/*IndexFileHeader* tempHeader = (IndexFileHeader*)*/bm->allocPage(fileID, 0, headerIndex);
headerChanged = true;
header->rootPageId = 1;
header->pageCount = 1;
header->firstLeaf = 1;
header->lastLeaf = 1;
header->sum = 0;
int index;
BPlusNode* root = (BPlusNode*)bm->allocPage(fileID, 1, index);
root->nextPage = 0;
root->prevPage = 0;
root->nodeType = ix::LEAF;
root->pageId = 1;
root->recs = 0;
bm->markDirty(index);
}
else {
IndexFileHeader* tempHeader = (IndexFileHeader*)bm->getPage(fileID, 0, headerIndex);
memcpy(header, tempHeader, sizeof(IndexFileHeader));
}
}
IndexFileHandler::~IndexFileHandler(){
delete header;
closeFile();
}
void IndexFileHandler::access(int index){
bm->access(index);
}
char* IndexFileHandler::newPage(int &index, bool isOvrflowPage){
// std::cout << "Apply for a new page" << std::endl;
header->pageCount++;
/*if (header->pageCount == 342) {
cout << "Hello World!" << endl;
}
std::cout << "Apply for a new page" << header->pageCount << std::endl;*/
char* res = bm->getPage(fileID, header->pageCount, index);
if(isOvrflowPage) ((BPlusOverflowPage*)res)->pageId = header->pageCount;
else ((BPlusNode*)res)->pageId = header->pageCount;
markPageDirty(index);
markHeaderPageDirty();
return res;
}
char* IndexFileHandler::getPage(int pageID, int& index){
return bm->getPage(fileID, pageID, index);
}
void IndexFileHandler::markHeaderPageDirty(){
headerChanged = true;
}
void IndexFileHandler::markPageDirty(int index){
bm->markDirty(index);
}
void IndexFileHandler::closeFile(){
if (bm != nullptr){
int headerIndex;
IndexFileHeader* tempHeader = (IndexFileHeader*)bm->getPage(fileID, 0, headerIndex);
memcpy(tempHeader, header, sizeof(IndexFileHeader));
this->markPageDirty(headerIndex);
bm->closeFile(fileID);
}
}
| 29.158537 | 98 | 0.634044 | robinren03 |
840cc9b4774d397c3f63b506e10cd5e32c5a3893 | 655 | cpp | C++ | test.cpp | ZaMaZaN4iK/iex_example | 57717f34f39ceadf1407bdd6b925f6b8c894533c | [
"MIT"
] | 1 | 2020-04-25T14:16:03.000Z | 2020-04-25T14:16:03.000Z | test.cpp | ZaMaZaN4iK/iex_example | 57717f34f39ceadf1407bdd6b925f6b8c894533c | [
"MIT"
] | null | null | null | test.cpp | ZaMaZaN4iK/iex_example | 57717f34f39ceadf1407bdd6b925f6b8c894533c | [
"MIT"
] | 1 | 2020-04-25T14:17:49.000Z | 2020-04-25T14:17:49.000Z | #define CATCH_CONFIG_MAIN
#include <catch.hpp>
#include "CompanyPriceDataStorage.h"
/*
That's a sample test case
*/
TEST_CASE( "Company price data is stored and selecte3d", "[storage]" ) {
CompanyPriceData etalonData{0, "1", "2", "3", "4"}
CompanyPriceDataStorage storage("test.db");
const int id = storage.store(etalonData);
const CompanyPriceData storedData = storage.read(id);
CHECK_THAT(etalonData.symbol, Equals(storedData.symbol));
CHECK_THAT(etalonData.companyName, Equals(storedData.companyName));
CHECK_THAT(etalonData.logo, Equals(storedData.logo));
CHECK_THAT(etalonData.price, Equals(storedData.price));
}
| 32.75 | 72 | 0.732824 | ZaMaZaN4iK |
8411ec0587bd6d49d94bee2f8e3e0d32ae5148d6 | 5,231 | cpp | C++ | source/options/OptionDialog.cpp | Mauzerov/wxPacman | 9fe599b1588d6143ff563ae8a3e5c2f31f69a5c3 | [
"Unlicense"
] | 1 | 2021-05-02T10:38:03.000Z | 2021-05-02T10:38:03.000Z | source/options/OptionDialog.cpp | Mauzerov/wxPacman | 9fe599b1588d6143ff563ae8a3e5c2f31f69a5c3 | [
"Unlicense"
] | null | null | null | source/options/OptionDialog.cpp | Mauzerov/wxPacman | 9fe599b1588d6143ff563ae8a3e5c2f31f69a5c3 | [
"Unlicense"
] | null | null | null | #include "OptionDialog.h"
#include <iostream>
//(*InternalHeaders(OptionDialog)
#include <wx/font.h>
#include <wx/intl.h>
#include <wx/settings.h>
#include <wx/string.h>
//*)
//(*IdInit(OptionDialog)
const long OptionDialog::ID_BUTTONSAVE = wxNewId();
const long OptionDialog::ID_KEYCHOICE = wxNewId();
const long OptionDialog::ID_LANGCHOICE = wxNewId();
//*)
BEGIN_EVENT_TABLE(OptionDialog,wxDialog)
//(*EventTable(OptionDialog)
//*)
END_EVENT_TABLE()
OptionDialog::OptionDialog(wxWindow* parent, wxWindowID id, std::string movement, std::string language)
{
//(*Initialize(OptionDialog)
Create(parent, id, _("Options"), wxDefaultPosition, wxDefaultSize, wxCAPTION|wxSYSTEM_MENU, _T("id"));
SetClientSize(wxSize(400,200));
SetForegroundColour(wxColour(255,255,255));
SetBackgroundColour(wxColour(0,0,0));
wxFont thisFont(11,wxFONTFAMILY_MODERN,wxFONTSTYLE_NORMAL,wxFONTWEIGHT_NORMAL,false,_T("Consolas"),wxFONTENCODING_DEFAULT);
SetFont(thisFont);
GamePausePanel = new wxPanel(this, wxID_ANY, wxPoint(0,0), wxSize(400,30), 0, _T("wxID_ANY"));
GamePauseLabel = new wxStaticText(GamePausePanel, wxID_ANY, _("GAME PAUSED"), wxPoint(0,0), wxSize(400,50), wxALIGN_CENTRE, _T("wxID_ANY"));
GamePauseLabel->SetForegroundColour(wxColour(243,156,18));
GamePauseLabel->SetBackgroundColour(wxColour(16,16,16));
wxFont GamePauseLabelFont(20,wxFONTFAMILY_MODERN,wxFONTSTYLE_NORMAL,wxFONTWEIGHT_NORMAL,false,_T("Consolas"),wxFONTENCODING_DEFAULT);
GamePauseLabel->SetFont(GamePauseLabelFont);
GamePauseUnderLine = new wxStaticLine(this, wxID_ANY, wxPoint(0,30), wxSize(400,2), wxLI_HORIZONTAL, _T("wxID_ANY"));
GamePauseUnderLine->SetForegroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWFRAME));
GamePauseUnderLine->SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWFRAME));
SaveOptionBtn = new wxButton(this, ID_BUTTONSAVE, _("Save Options"), wxPoint(100,175), wxSize(200,25), wxBORDER_NONE|wxTRANSPARENT_WINDOW, wxDefaultValidator, _T("ID_BUTTONSAVE"));
SaveOptionBtn->SetForegroundColour(wxColour(255,255,255));
SaveOptionBtn->SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWFRAME));
KeyBindsPanel = new wxPanel(this, wxID_ANY, wxPoint(0,40), wxSize(200,50), wxBORDER_SIMPLE, _T("wxID_ANY"));
KeyBindsMoveChoice = new wxChoice(KeyBindsPanel, ID_KEYCHOICE, wxPoint(8,8), wxDefaultSize, 0, 0, 0, wxDefaultValidator, _T("ID_KEYCHOICE"));
KeyBindsMoveChoice->Append(_("Arrows"));
KeyBindsMoveChoice->Append(_("WSAD"));
KeyBindsMoveLabel = new wxStaticText(KeyBindsPanel, wxID_ANY, _("Movement\nKeys"), wxPoint(120,4), wxSize(70,40), wxALIGN_CENTRE, _T("wxID_ANY"));
KeyBindsMoveLabel->SetForegroundColour(wxColour(255,255,255));
GameLangPanel = new wxPanel(this, wxID_ANY, wxPoint(200,40), wxSize(200,50), wxBORDER_SIMPLE, _T("wxID_ANY"));
GameLangChoise = new wxChoice(GameLangPanel, ID_LANGCHOICE, wxPoint(8,8), wxDefaultSize, 0, 0, 0, wxDefaultValidator, _T("ID_LANGCHOICE"));
GameLangChoise->Append(_("Polski"));
GameLangChoise->Append(_("English"));
GameLangLabel = new wxStaticText(GameLangPanel, wxID_ANY, _("Language"), wxPoint(120,12), wxSize(70,40), wxALIGN_CENTRE, _T("wxID_ANY"));
GameLangLabel->SetForegroundColour(wxColour(255,255,255));
SpaceShootLabel = new wxStaticText(this, wxID_ANY, _("Label"), wxPoint(10,100), wxSize(380,20), wxALIGN_CENTRE, _T("wxID_ANY"));
wxFont SpaceShootLabelFont(12,wxFONTFAMILY_MODERN,wxFONTSTYLE_NORMAL,wxFONTWEIGHT_NORMAL,false,_T("Consolas"),wxFONTENCODING_DEFAULT);
SpaceShootLabel->SetFont(SpaceShootLabelFont);
Center();
Connect(ID_BUTTONSAVE,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&OptionDialog::OnSaveOptionBtnClick);
Connect(wxID_ANY,wxEVT_CLOSE_WINDOW,(wxObjectEventFunction)&OptionDialog::OnDialogClose);
//*)
///TODO Options uising int indexes
this->KeyBindsMoveChoice->Select(this->KeyBindsMoveChoice->FindString(movement)); // Set Current Move Option
this->GameLangChoise->Select(this->GameLangChoise->FindString(language)); // Set Current Language Option
this->GameLangLabel->SetLabel(lang::lang.at(language).at("language_pick")); // Translated Language
this->KeyBindsMoveLabel->SetLabel(lang::lang.at(language).at("movement_pick")); // Translated Movement
this->SaveOptionBtn->SetLabel(lang::lang.at(language).at("save_options")); // Translated Saving Options
this->GamePauseLabel->SetLabel(lang::lang.at(language).at("game_paused")); // Translated Game Paused Label
this->SpaceShootLabel->SetLabel(lang::lang.at(language).at("space_button")); // Translated Game Paused Label
this->movement = movement;
this->language = language;
}
OptionDialog::~OptionDialog( void )
{
//(*Destroy(OptionDialog)
//*)
}
void OptionDialog::OnDialogClose(wxCloseEvent& event)
{
this->Destroy();
}
void OptionDialog::SaveOptions( void )
{
this->movement = std::string(this->KeyBindsMoveChoice->GetStringSelection().mb_str()); // Changing Movement Method
this->language = std::string(this->GameLangChoise->GetStringSelection().mb_str()); // Changing Language
}
void OptionDialog::OnSaveOptionBtnClick(wxCommandEvent& event)
{
this->SaveOptions();
this->Destroy();
}
| 52.31 | 182 | 0.761422 | Mauzerov |
8416064ba4d7477f450641def58f3b03edb4f096 | 8,294 | cpp | C++ | HPCSimulation.cpp | iray-tno/hal2015 | c84643472b31efbcd7622867dcc4e71c80541274 | [
"FSFAP"
] | null | null | null | HPCSimulation.cpp | iray-tno/hal2015 | c84643472b31efbcd7622867dcc4e71c80541274 | [
"FSFAP"
] | null | null | null | HPCSimulation.cpp | iray-tno/hal2015 | c84643472b31efbcd7622867dcc4e71c80541274 | [
"FSFAP"
] | null | null | null | //------------------------------------------------------------------------------
/// @file
/// @brief HPCSimulation.hpp の実装
/// @author ハル研究所プログラミングコンテスト実行委員会
///
/// @copyright Copyright (c) 2015 HAL Laboratory, Inc.
/// @attention このファイルの利用は、同梱のREADMEにある
/// 利用条件に従ってください
//------------------------------------------------------------------------------
#include "HPCSimulation.hpp"
#include <cstring>
#include <cstdlib>
#include "HPCCommon.hpp"
#include "HPCMath.hpp"
#include "HPCTimer.hpp"
namespace {
/// 入力を受けるコマンド
enum Command {
Command_Debug, ///< デバッガ起動
Command_OutputJson, ///< JSON 出力
Command_Exit, ///< 終わる
};
//------------------------------------------------------------------------------
/// 入力を受けます。
Command SelectInput()
{
while (true) {
HPC_PRINT("[d]ebug | output [j]son | [e]xit: ");
// 入力待ち
const char key = getchar();
if (key == 0x0a) {
return Command_Exit;
}
while (getchar() != 0x0a){} // 改行待ち
switch (key)
{
case 'd': return Command_Debug;
case 'j': return Command_OutputJson;
case 'e': return Command_Exit;
default:
break;
}
}
return Command_Exit;
}
/// 入力を受けるコマンド
enum DebugCommand {
DebugCommand_Next, ///< 次へ
DebugCommand_Prev, ///< 前へ
DebugCommand_Jump, ///< 指定番号のステージにジャンプ
DebugCommand_Show, ///< 再度
DebugCommand_Help, ///< ヘルプを表示
DebugCommand_Exit, ///< 終わる
DebugCommand_TERM
};
/// 入力を受けるコマンドのセット
struct DebugCommandSet
{
DebugCommand command;
int arg1;
int arg2;
DebugCommandSet()
: command(DebugCommand_TERM)
, arg1(0)
, arg2(0)
{
}
DebugCommandSet(DebugCommand aCmd, int aArg1, int aArg2)
: command(aCmd)
, arg1(aArg1)
, arg2(aArg2)
{
HPC_ENUM_ASSERT(DebugCommand, aCmd);
}
};
//------------------------------------------------------------------------------
/// 入力を受けます。
///
/// 入力は次の3要素から構成されます。
/// - コマンド
/// - 引数1
/// - 引数2
///
/// 引数1, 引数2 を省略した場合は、0 が設定されます。
DebugCommandSet SelectInputDebugger(int stage)
{
while (true) {
HPC_PRINT("[Stage: %d ('h' for help)]> ", stage);
// 入力待ち
static const int LineBufferSize = 20; // 20文字くらいあれば十分
char line[LineBufferSize];
{
char* ptr = std::fgets(line, LineBufferSize, stdin);
(void)ptr;
}
// コマンドを読む
const char* cmdStr = std::strtok(line, " \n\0");
if (!cmdStr) {
continue;
}
const char* arg1Str = std::strtok(0, " \n\0");
const char* arg2Str = std::strtok(0, " \n\0");
const int arg1 = arg1Str ? std::atoi(arg1Str) : 0;
const int arg2 = arg2Str ? std::atoi(arg2Str) : 0;
switch (cmdStr[0])
{
case 'n': return DebugCommandSet(DebugCommand_Next, arg1, arg2);
case 'p': return DebugCommandSet(DebugCommand_Prev, arg1, arg2);
case 'd': return DebugCommandSet(DebugCommand_Show, arg1, arg2);
case 'j': return DebugCommandSet(DebugCommand_Jump, arg1, arg2);
case 'h': return DebugCommandSet(DebugCommand_Help, arg1, arg2);
case 'e': return DebugCommandSet(DebugCommand_Exit, arg1, arg2);
default:
break;
}
}
return DebugCommandSet(DebugCommand_Next, 0, 0);
}
//------------------------------------------------------------------------------
/// デバッガのヘルプを表示します。
void ShowHelp()
{
HPC_PRINT(" n : Go to the next stage.\n");
HPC_PRINT(" p : Go to the prev stage.\n");
HPC_PRINT(" j [stage=0] : Go to the designated stage.\n");
HPC_PRINT(" d : Show the result of this stage.\n");
HPC_PRINT(" h : Show Help.\n");
HPC_PRINT(" e : Exit debugger.\n");
}
}
namespace hpc {
//------------------------------------------------------------------------------
/// @brief Simulation クラスのインスタンスを生成します。
Simulation::Simulation()
: mRandom()
, mGame(mRandom)
, mTimer(Parameter::GameTimeLimitSec)
{
}
//------------------------------------------------------------------------------
/// @brief ゲームを実行します。
void Simulation::run()
{
// 制限時間と制限ターン数
mTimer.start();
while (mGame.isValidStage()) {
mGame.startStage(mTimer.isInTime());
while (mGame.state() == StageState_Playing && mTimer.isInTime()) {
mGame.runTurn();
}
mGame.onStageDone();
}
}
//------------------------------------------------------------------------------
/// スコアを取得します。
int Simulation::score() const {
return mGame.record().score() / Parameter::RepeatCount;
}
//------------------------------------------------------------------------------
/// 表示用時間を取得します。
double Simulation::pastTimeSecForPrint()const
{
return mTimer.pastSecForPrint() / Parameter::RepeatCount;
}
//------------------------------------------------------------------------------
/// 結果を表示します。
void Simulation::outputResult()const
{
HPC_PRINT("Done.\n");
HPC_PRINT("%8s:%8d\n", "Score", score());
HPC_PRINT("%8s:%8.4f\n", "Time", pastTimeSecForPrint());
}
//------------------------------------------------------------------------------
/// @brief ゲームをデバッグ実行します。
void Simulation::debug()
{
// デバッグ前にデバッグをするかどうかを判断する。
// 入力待ち
switch (SelectInput()) {
case Command_Debug:
runDebugger();
break;
case Command_OutputJson:
// 時間切れの場合は、JSONが不完全になるので出力を行わない。
if (mTimer.isInTime()) {
mGame.record().dumpJson(true);
}
break;
case Command_Exit:
break;
default:
HPC_SHOULD_NOT_REACH_HERE();
break;
}
}
//------------------------------------------------------------------------------
/// JSON データを出力します。
void Simulation::outputJson(bool isCompressed)const
{
// 時間切れの場合は、JSONが不完全になるので出力を行わない。
if (mTimer.isInTime()) {
mGame.record().dumpJson(isCompressed);
}
}
//------------------------------------------------------------------------------
/// デバッグ実行を行います。
void Simulation::runDebugger()
{
int stage = 0;
bool doInput = true; // ステージ終了時に入力待ち するか。
do {
if (doInput) {
const DebugCommandSet commandSet = SelectInputDebugger(stage);
switch(commandSet.command) {
case DebugCommand_Next:
++stage;
break;
case DebugCommand_Prev:
stage = Math::Max(stage - 1, 0);
break;
case DebugCommand_Show:
mGame.record().dumpStage(stage);
break;
case DebugCommand_Jump:
stage = Math::LimitMinMax(commandSet.arg1, 0, Parameter::GameStageCount - 1);
break;
case DebugCommand_Help:
ShowHelp();
break;
case DebugCommand_Exit:
stage = Parameter::GameStageCount;
break;
default:
HPC_SHOULD_NOT_REACH_HERE();
break;
}
}
else {
++stage;
}
} while (stage < Parameter::GameStageCount);
}
}
//------------------------------------------------------------------------------
// EOF
| 29.204225 | 97 | 0.420666 | iray-tno |
84192b3897572770dbce377b3e7d0bec703cbff4 | 998 | cpp | C++ | tests/kernel/globalinit.cpp | v8786339/NyuziProcessor | 34854d333d91dbf69cd5625505fb81024ec4f785 | [
"Apache-2.0"
] | 1,388 | 2015-02-05T17:16:17.000Z | 2022-03-31T07:17:08.000Z | tests/kernel/globalinit.cpp | czvf/NyuziProcessor | 31f74e43a785fa66d244f1e9744ca0ca9b8a1fad | [
"Apache-2.0"
] | 176 | 2015-02-02T02:54:06.000Z | 2022-02-01T06:00:21.000Z | tests/kernel/globalinit.cpp | czvf/NyuziProcessor | 31f74e43a785fa66d244f1e9744ca0ca9b8a1fad | [
"Apache-2.0"
] | 271 | 2015-02-18T02:19:04.000Z | 2022-03-28T13:30:25.000Z | //
// Copyright 2016 Jeff Bush
//
// 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 <stdio.h>
//
// Make sure global constructors/destructors are called properly by crt0
//
class Foo
{
public:
Foo()
{
printf("Foo::Foo\n");
}
~Foo()
{
printf("Foo::~Foo\n");
}
};
Foo f;
int main()
{
// CHECK: Foo::Foo
printf("main\n");
// CHECK: main
// CHECK: Foo::~Foo
return 0;
}
// CHECK: init process has exited, shutting down | 20.791667 | 75 | 0.654309 | v8786339 |
8421f307b6c36c4060ee159cf7ed771972cd5bbb | 90 | cpp | C++ | src/Item.cpp | Erick9Thor/Zork | 43ee99711bb991e0f8c3cf61f18c1d2e373ac2a7 | [
"MIT"
] | null | null | null | src/Item.cpp | Erick9Thor/Zork | 43ee99711bb991e0f8c3cf61f18c1d2e373ac2a7 | [
"MIT"
] | null | null | null | src/Item.cpp | Erick9Thor/Zork | 43ee99711bb991e0f8c3cf61f18c1d2e373ac2a7 | [
"MIT"
] | null | null | null | #include "../include/Item.h"
ItemType Item::GetItemType() const
{
return itemType;
}
| 12.857143 | 34 | 0.677778 | Erick9Thor |
842b1dd42b8e6cfb395af85944e7da162dc0a8bc | 4,385 | cpp | C++ | cnf_dump/cnf_dump_clo.cpp | appu226/FactorGraph | 26e4de8518874abf2696a167eaf3dbaede5930f8 | [
"MIT"
] | null | null | null | cnf_dump/cnf_dump_clo.cpp | appu226/FactorGraph | 26e4de8518874abf2696a167eaf3dbaede5930f8 | [
"MIT"
] | null | null | null | cnf_dump/cnf_dump_clo.cpp | appu226/FactorGraph | 26e4de8518874abf2696a167eaf3dbaede5930f8 | [
"MIT"
] | null | null | null | /*
Copyright 2019 Parakram Majumdar
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 corresponding header file
#include "cnf_dump_clo.h"
// std includes
#include <stdexcept>
namespace cnf_dump {
//----------------------------------------------------------------
// definitions of members of class CnfDumpClo
//----------------------------------------------------------------
// function CnfDumpClo::create
std::shared_ptr<CnfDumpClo> CnfDumpClo::create(int argc, char const * const * const argv)
{
return std::make_shared<CnfDumpClo>(argc, argv);
}
// function CnfDumpClo::printHelpMessage
// prints help info
void CnfDumpClo::printHelpMessage()
{
std::cout << "cnf_dump:\n"
<< " Utility for converting a blif file into a cnf_dump\n"
<< "\n"
<< "Usage:\n"
<< " cnf_dump <options>\n"
<< "\n"
<< "Options:\n"
<< " --blif_file <input blif file> (MANDATORY)\n"
<< " --cnf_file <output blif file> (MANDATORY)\n"
<< " --num_lo_vars_to_quantify <number of latch output vars to quantify out>, defaults to 0\n"
<< " --verbosity <verbosity> : one of QUIET/ERROR/WARNING/INFO/DEBUG, defaults to ERROR\n"
<< " --help: prints this help message and exits\n"
<< std::endl;
return;
}
// constructor CnfDumpClo::CnfDumpClo
// stub implementation
CnfDumpClo::CnfDumpClo(int argc, char const * const * const argv) :
blif_file(),
output_cnf_file(),
verbosity(blif_solve::ERROR),
num_lo_vars_to_quantify(0),
help(false)
{
char const * const * current_argv = argv + 1;
for (int argnum = 1; argnum < argc; ++argnum, ++current_argv)
{
std::string current_arg(*current_argv);
if (current_arg == "--blif_file")
{
++argnum;
++current_argv;
if (argnum >= argc)
throw std::invalid_argument("Missing <input blif file> after argument --blif_file");
blif_file = *current_argv;
}
else if (current_arg == "--cnf_file")
{
++argnum;
++current_argv;
if (argnum >= argc)
throw std::invalid_argument("Missing <input cnf file> after argument --cnf_file");
output_cnf_file = *current_argv;
}
else if (current_arg == "--verbosity")
{
++argnum;
++current_argv;
if (argnum >= argc)
throw std::invalid_argument("Missing <verbosity> after argument --verbosity");
verbosity = blif_solve::parseVerbosity(*current_argv);
}
else if (current_arg == "--help")
help = true;
else if (current_arg == "--num_lo_vars_to_quantify")
{
++argnum;
++current_argv;
if (argnum >= argc)
throw std::invalid_argument("Missing <number> after argument --num_lo_vars_to_quantify");
num_lo_vars_to_quantify = atoi(*current_argv);
}
else
throw std::invalid_argument(std::string("Unexpected argument '") + *current_argv + "'");
}
if (help)
return;
if (blif_file == "")
throw std::invalid_argument("Missing mandatory argument --blif_file");
if (output_cnf_file == "")
throw std::invalid_argument("Missing mandatory argument --cnf_file");
return;
}
} // end namespace cnf_dump
| 32.242647 | 109 | 0.620753 | appu226 |
842cc9c6722bc81483b9a34464a134e42c681b75 | 14,748 | cpp | C++ | src/RotationPricer.cpp | sergebisaillon/MerinioScheduler | 8549ce7f3c1c14817a2eba9d565ca0b56f451e2a | [
"MIT"
] | 1 | 2020-05-05T15:51:41.000Z | 2020-05-05T15:51:41.000Z | src/RotationPricer.cpp | qiqi789/NurseScheduler | 8549ce7f3c1c14817a2eba9d565ca0b56f451e2a | [
"MIT"
] | null | null | null | src/RotationPricer.cpp | qiqi789/NurseScheduler | 8549ce7f3c1c14817a2eba9d565ca0b56f451e2a | [
"MIT"
] | 1 | 2019-11-11T17:59:23.000Z | 2019-11-11T17:59:23.000Z | /*
* RotationPricer.cpp
*
* Created on: 2015-03-02
* Author: legraina
*/
#include "RotationPricer.h"
#include "BcpModeler.h"
/* namespace usage */
using namespace std;
//////////////////////////////////////////////////////////////
//
// R O T A T I O N P R I C E R
//
//////////////////////////////////////////////////////////////
static char const * baseName = "rotation";
/* Constructs the pricer object. */
RotationPricer::RotationPricer(MasterProblem* master, const char* name, SolverParam param):
MyPricer(name), nbMaxRotationsToAdd_(20), nbSubProblemsToSolve_(15), nursesToSolve_(master->theNursesSorted_),
pMaster_(master), pScenario_(master->pScenario_), nbDays_(master->pDemand_->nbDays_), pModel_(master->getModel()), nb_int_solutions_(0)
{
// Initialize the parameters
initPricerParameters(param);
/* sort the nurses */
// random_shuffle( nursesToSolve_.begin(), nursesToSolve_.end());
}
/* Destructs the pricer object. */
RotationPricer::~RotationPricer() {
for(pair<const Contract*, SubProblem*> p: subProblems_)
delete p.second;
}
void RotationPricer::initPricerParameters(SolverParam param){
// Here: doing a little check to be sure that secondchance is activated only when the parameters are different...
withSecondchance_ = param.sp_withsecondchance_ && (param.sp_default_strategy_ != param.sp_secondchance_strategy_);
nbMaxRotationsToAdd_ = param.sp_nbrotationspernurse_;
nbSubProblemsToSolve_ = param.sp_nbnursestoprice_;
defaultSubprobemStrategy_ = param.sp_default_strategy_;
secondchanceSubproblemStrategy_ = param.sp_secondchance_strategy_;
currentSubproblemStrategy_ = defaultSubprobemStrategy_;
}
/******************************************************
* Perform pricing
******************************************************/
vector<MyVar*> RotationPricer::pricing(double bound, bool before_fathom){
// Reset all rotations, columns, counters, etc.
resetSolutions();
// count and store the nurses whose subproblems produced rotations.
// DBG: why minDualCost? Isn't it more a reduced cost?
double minDualCost = 0;
vector<LiveNurse*> nursesSolved;
for(vector<LiveNurse*>::iterator it0 = nursesToSolve_.begin(); it0 != nursesToSolve_.end();){
// RETRIEVE THE NURSE AND CHECK THAT HE/SHE IS NOT FORBIDDEN
LiveNurse* pNurse = *it0;
bool nurseForbidden = isNurseForbidden(pNurse->id_);
// IF THE NURSE IS NOT FORBIDDEN, SOLVE THE SUBPROBLEM
if(!nurseForbidden){
// BUILD OR RE-USE THE SUBPROBLEM
SubProblem* subProblem = retriveSubproblem(pNurse);
// RETRIEVE DUAL VALUES
vector< vector<double> > workDualCosts(getWorkDualValues(pNurse));
vector<double> startWorkDualCosts(getStartWorkDualValues(pNurse));
vector<double> endWorkDualCosts(getEndWorkDualValues(pNurse));
double workedWeekendDualCost = getWorkedWeekendDualValue(pNurse);
DualCosts dualCosts (workDualCosts, startWorkDualCosts, endWorkDualCosts, workedWeekendDualCost, true);
// UPDATE FORBIDDEN SHIFTS
if (pModel_->getParameters().isColumnDisjoint_) {
addForbiddenShifts();
}
set<pair<int,int> > nurseForbiddenShifts(forbiddenShifts_);
pModel_->addForbiddenShifts(pNurse, nurseForbiddenShifts);
// SET SOLVING OPTIONS
SubproblemParam sp_param (currentSubproblemStrategy_,pNurse);
// DBG ***
// generateRandomForbiddenStartingDays();
// SOLVE THE PROBLEM
++ nbSPTried_;
subProblem->solve(pNurse, &dualCosts, sp_param, nurseForbiddenShifts, forbiddenStartingDays_, true ,
bound);
// RETRIEVE THE GENERATED ROTATIONS
newRotationsForNurse_ = subProblem->getRotations();
// DBG ***
// checkForbiddenStartingDays();
// recordSPStats(subProblem);
// for(Rotation& rot: newRotationsForNurse_){
// rot.checkDualCost(dualCosts);
// }
// ADD THE ROTATIONS TO THE MASTER PROBLEM
addRotationsToMaster();
}
// CHECK IF THE SUBPROBLEM GENERATED NEW ROTATIONS
// If yes, store the nures
if(newRotationsForNurse_.size() > 0 && !nurseForbidden){
++nbSPSolvedWithSuccess_;
if(newRotationsForNurse_[0].dualCost_ < minDualCost)
minDualCost = newRotationsForNurse_[0].dualCost_;
nursesToSolve_.erase(it0);
nursesSolved.push_back(pNurse);
}
// Otherwise (no rotation generated or nurse is forbidden), try the next nurse
else {
++it0;
// If it was the last nurse to search AND no improving column was found AND we may want to solve SP with
// different parameters -> change these parameters and go for another loop of solving
if( it0 == nursesToSolve_.end() && allNewColumns_.empty() && withSecondchance_){
if(currentSubproblemStrategy_ == defaultSubprobemStrategy_){
nursesToSolve_.insert(nursesToSolve_.end(), nursesSolved.begin(), nursesSolved.end());
it0 = nursesToSolve_.begin();
currentSubproblemStrategy_ = secondchanceSubproblemStrategy_;
} else if (currentSubproblemStrategy_ == secondchanceSubproblemStrategy_) {
currentSubproblemStrategy_ = defaultSubprobemStrategy_;
}
}
}
//if the maximum number of subproblem solved is reached, break.
if(nbSPSolvedWithSuccess_ == nbSubProblemsToSolve_)
break;
}
//Add the nurse in nursesSolved at the end
nursesToSolve_.insert(nursesToSolve_.end(), nursesSolved.begin(), nursesSolved.end());
//set statistics
BcpModeler* model = dynamic_cast<BcpModeler*>(pModel_);
if(model){
model->setLastNbSubProblemsSolved(nbSPTried_);
model->setLastMinDualCost(minDualCost);
}
if(allNewColumns_.empty())
print_current_solution_();
// std::cout << "# ------- END ------- Subproblems!" << std::endl;
// return optimal;
return allNewColumns_;
}
/******************************************************
* Get the duals values per day for a nurse
******************************************************/
vector< vector<double> > RotationPricer::getWorkDualValues(LiveNurse* pNurse){
vector< vector<double> > dualValues(nbDays_);
int i = pNurse->id_;
int p = pNurse->pContract_->id_;
/* Min/Max constraints */
double minWorkedDays = pModel_->getDual(pMaster_->minWorkedDaysCons_[i], true);
double maxWorkedDays = pModel_->getDual(pMaster_->maxWorkedDaysCons_[i], true);
double minWorkedDaysAvg = pMaster_->isMinWorkedDaysAvgCons_[i] ? pModel_->getDual(pMaster_->minWorkedDaysAvgCons_[i], true):0.0;
double maxWorkedDaysAvg = pMaster_->isMaxWorkedDaysAvgCons_[i] ? pModel_->getDual(pMaster_->maxWorkedDaysAvgCons_[i], true):0.0;
double minWorkedDaysContractAvg = pMaster_->isMinWorkedDaysContractAvgCons_[p] ?
pModel_->getDual(pMaster_->minWorkedDaysContractAvgCons_[p], true):0.0;
double maxWorkedDaysContractAvg = pMaster_->isMaxWorkedDaysContractAvgCons_[p] ?
pModel_->getDual(pMaster_->maxWorkedDaysContractAvgCons_[p], true):0.0;
for(int k=0; k<nbDays_; ++k){
//initialize vector
vector<double> dualValues2(pScenario_->nbShifts_-1);
for(int s=1; s<pScenario_->nbShifts_; ++s){
/* Min/Max constraints */
dualValues2[s-1] = minWorkedDays + minWorkedDaysAvg + minWorkedDaysContractAvg;
dualValues2[s-1] += maxWorkedDays + maxWorkedDaysAvg + maxWorkedDaysContractAvg;
/* Skills coverage */
dualValues2[s-1] += pModel_->getDual(
pMaster_->numberOfNursesByPositionCons_[k][s-1][pNurse->pPosition_->id_], true);
}
//store vector
dualValues[k] = dualValues2;
}
return dualValues;
}
vector<double> RotationPricer::getStartWorkDualValues(LiveNurse* pNurse){
int i = pNurse->id_;
vector<double> dualValues(nbDays_);
//get dual value associated to the source
dualValues[0] = pModel_->getDual(pMaster_->restFlowCons_[i][0], true);
//get dual values associated to the work flow constraints
//don't take into account the last which is the sink
for(int k=1; k<nbDays_; ++k)
dualValues[k] = pModel_->getDual(pMaster_->workFlowCons_[i][k-1], true);
return dualValues;
}
vector<double> RotationPricer::getEndWorkDualValues(LiveNurse* pNurse){
int i = pNurse->id_;
vector<double> dualValues(nbDays_);
//get dual values associated to the work flow constraints
//don't take into account the first which is the source
//take into account the cost, if the last day worked is k
for(int k=0; k<nbDays_-1; ++k)
dualValues[k] = -pModel_->getDual(pMaster_->restFlowCons_[i][k+1], true);
//get dual value associated to the sink
dualValues[nbDays_-1] = pModel_->getDual(
pMaster_->workFlowCons_[i][nbDays_-1], true);
return dualValues;
}
double RotationPricer::getWorkedWeekendDualValue(LiveNurse* pNurse){
int id = pNurse->id_;
double dualVal = pModel_->getDual(pMaster_->maxWorkedWeekendCons_[id], true);
if (pMaster_->isMaxWorkedWeekendAvgCons_[id]) {
dualVal += pModel_->getDual(pMaster_->maxWorkedWeekendAvgCons_[id], true);
}
if (pMaster_->isMaxWorkedWeekendContractAvgCons_[pNurse->pContract_->id_]) {
dualVal += pModel_->getDual(pMaster_->maxWorkedWeekendContractAvgCons_[pNurse->pContract_->id_], true);
}
return dualVal;
}
/******************************************************
* add some forbidden shifts
******************************************************/
void RotationPricer::addForbiddenShifts(){
//search best rotation
vector<Rotation>::iterator bestRotation;
double bestDualcost = DBL_MAX;
for(vector<Rotation>::iterator it = newRotationsForNurse_.begin(); it != newRotationsForNurse_.end(); ++it)
if(it->dualCost_ < bestDualcost){
bestDualcost = it->dualCost_;
bestRotation = it;
}
//forbid shifts of the best rotation
if(bestDualcost != DBL_MAX)
for(pair<int,int> pair: bestRotation->shifts_)
forbiddenShifts_.insert(pair);
}
// Returns a pointer to the right subproblem
SubProblem* RotationPricer::retriveSubproblem(LiveNurse* pNurse){
SubProblem* subProblem;
map<const Contract*, SubProblem*>::iterator it = subProblems_.find(pNurse->pContract_);
// Each contract has one subproblem. If it has not already been created, create it.
if( it == subProblems_.end() ){
subProblem = new SubProblem(pScenario_, nbDays_, pNurse->pContract_, pMaster_->pInitState_);
subProblems_.insert(it, pair<const Contract*, SubProblem*>(pNurse->pContract_, subProblem));
} else {
subProblem = it->second;
}
return subProblem;
}
// Add the rotations to the master problem
void RotationPricer::addRotationsToMaster(){
// COMPUTE THE COST OF THE ROTATIONS
for(Rotation& rot: newRotationsForNurse_){
rot.computeCost(pScenario_, pMaster_->pPreferences_, pMaster_->theLiveNurses_,nbDays_);
rot.treeLevel_ = pModel_->getCurrentTreeLevel();
}
// SORT THE ROTATIONS
sortNewlyGeneratedRotations();
// SECOND, ADD THE ROTATIONS TO THE MASTER PROBLEM (in the previously computed order)
int nbRotationsAdded = 0;
for(Rotation& rot: newRotationsForNurse_){
allNewColumns_.push_back(pMaster_->addRotation(rot, baseName));
++nbRotationsAdded;
// DBG
//cout << rot.toString(nbDays_) << endl;
if(nbRotationsAdded >= nbMaxRotationsToAdd_)
break;
}
}
// Sort the rotations that just were generated for a nurse. Default option is sort by increasing reduced cost but we
// could try something else (involving disjoint columns for ex.)
void RotationPricer::sortNewlyGeneratedRotations(){
std::stable_sort(newRotationsForNurse_.begin(), newRotationsForNurse_.end(), Rotation::compareDualCost);
}
// Set the subproblem options depending on the parameters
//
//void RotationPricer::setSubproblemOptions(vector<SolveOption>& options, int& maxRotationLengthForSubproblem,
// LiveNurse* pNurse){
//
// // Default option that should be used
// options.push_back(SOLVE_ONE_SINK_PER_LAST_DAY);
//
// // Options are added depending on the chosen parameters
// //
// if (currentPricerParam_.isExhaustiveSearch()) {
// options.push_back(SOLVE_SHORT_ALL);
// maxRotationLengthForSubproblem = LARGE_TIME;
// }
// else if (currentPricerParam_.nonPenalizedRotationsOnly()) {
// options.push_back(SOLVE_SHORT_DAY_0_ONLY);
// maxRotationLengthForSubproblem = pNurse->maxConsDaysWork();
// }
// else {
// if(currentPricerParam_.withShortRotations()) options.push_back(SOLVE_SHORT_ALL);
// maxRotationLengthForSubproblem = currentPricerParam_.maxRotationLength();
// }
//
//}
// ------------------------------------------
//
// PRINT functions
//
// ------------------------------------------
void RotationPricer::print_current_solution_(){
//pMaster_->costsConstrainstsToString();
//pMaster_->allocationToString();
if(nb_int_solutions_ < pMaster_->getModel()->nbSolutions()){
nb_int_solutions_ = pMaster_->getModel()->nbSolutions();
//pMaster_->getModel()->printBestSol();
//pMaster_->costsConstrainstsToString();
}
}
void RotationPricer::printStatSPSolutions(){
double tMeanSubproblems = timeInExSubproblems_ / ((double)nbExSubproblems_);
double tMeanS = timeForS_ / ((double)nbS_);
double tMeanNL = timeForNL_ / ((double)nbNL_);
double tMeanN = timeForN_ / ((double)nbN_);
string sepLine = "+-----------------+------------------------+-----------+\n";
printf("\n");
printf("%s", sepLine.c_str());
printf("| %-15s |%10s %12s |%10s |\n", "type", "time", "number", "mean time");
printf("%s", sepLine.c_str());
printf("| %-15s |%10.2f %12d |%10.4f |\n", "Ex. Subproblems", timeInExSubproblems_, nbExSubproblems_, tMeanSubproblems);
printf("| %-15s |%10.2f %12d |%10.4f |\n", "Short rotations", timeForS_, nbS_, tMeanS);
printf("| %-15s |%10.2f %12d |%10.4f |\n", "NL rotations", timeForNL_, nbNL_, tMeanNL);
printf("%s", sepLine.c_str());
printf("| %-15s |%10.2f %12d |%10.4f |\n", "N rotations", timeForN_, nbN_, tMeanN);
printf("%s", sepLine.c_str());
printf("\n");
}
// ------------------------------------------
//
// DBG functions - may be useful
//
// ------------------------------------------
//void RotationPricer::recordSPStats(SubProblem* sp){
// if (currentPricerParam_.isExhaustiveSearch()) {
// nbExSubproblems_++; nbSubproblems_++; nbS_++; nbNL_++;
// timeForS_ += sp->timeInS_->dSinceStart();
// timeForNL_ += sp->timeInNL_->dSinceStart();
// timeInExSubproblems_ += sp->timeInS_->dSinceStart() + sp->timeInNL_->dSinceStart();
// }
// else if (currentPricerParam_.nonPenalizedRotationsOnly()) {
// nbSubproblems_++; nbN_++;
// timeForN_ += sp->timeInNL_->dSinceStart();
// }
// else {
// }
//}
void RotationPricer::generateRandomForbiddenStartingDays(){
set<int> randomForbiddenStartingDays;
for(int m=0; m<5; m++){
int k = Tools::randomInt(0, nbDays_-1);
randomForbiddenStartingDays.insert(k);
}
forbiddenStartingDays_ = randomForbiddenStartingDays;
}
void RotationPricer::checkForbiddenStartingDays(){
for(Rotation& rot: newRotationsForNurse_){
int startingDay = rot.firstDay_;
if(forbiddenStartingDays_.find(startingDay) != forbiddenStartingDays_.end()){
cout << "# On a généré une rotation qui commence un jour interdit !" << endl;
getchar();
}
}
}
| 34.619718 | 137 | 0.702129 | sergebisaillon |
8438b89e25ce446d49d0eda0cc0bc78749c00c74 | 4,741 | cc | C++ | Samples/PostProcessing/PostProcessing.cc | rodrigobmg/YumeEngine | 67c525c84616a5167b5bae45f36641e90227c281 | [
"MIT"
] | 129 | 2016-05-05T23:34:44.000Z | 2022-03-07T20:17:18.000Z | Samples/PostProcessing/PostProcessing.cc | rodrigobmg/YumeEngine | 67c525c84616a5167b5bae45f36641e90227c281 | [
"MIT"
] | 1 | 2017-05-07T16:09:41.000Z | 2017-05-08T15:35:50.000Z | Samples/PostProcessing/PostProcessing.cc | rodrigobmg/YumeEngine | 67c525c84616a5167b5bae45f36641e90227c281 | [
"MIT"
] | 20 | 2016-02-24T20:40:08.000Z | 2022-02-04T23:48:18.000Z | //--------------------------------------------------------------------------------
//This is a file from Arkengine
//
//
//Copyright (c) arkenthera.All rights reserved.
//
//BasicRenderWindow.cpp
//--------------------------------------------------------------------------------
#include "Core/YumeHeaders.h"
#include "PostProcessing.h"
#include "Logging/logging.h"
#include "Core/YumeMain.h"
#include "Renderer/YumeLPVCamera.h"
#include <boost/shared_ptr.hpp>
#include "Input/YumeInput.h"
#include "Renderer/YumeTexture2D.h"
#include "Renderer/YumeResourceManager.h"
#include "Engine/YumeEngine.h"
#include "UI/YumeDebugOverlay.h"
#include "Renderer/Light.h"
#include "Renderer/StaticModel.h"
#include "Renderer/Scene.h"
#include "Renderer/RenderPass.h"
#include "UI/YumeOptionsMenu.h"
YUME_DEFINE_ENTRY_POINT(YumeEngine::GodRays);
#define TURNOFF 1
//#define NO_MODEL
//#define OBJECTS_CAST_SHADOW
#define NO_SKYBOX
#define NO_PLANE
namespace YumeEngine
{
GodRays::GodRays()
: angle1_(0),
updown1_(0),
leftRight1_(0)
{
REGISTER_ENGINE_LISTENER;
}
GodRays::~GodRays()
{
}
void GodRays::Start()
{
YumeResourceManager* rm_ = gYume->pResourceManager;
YumeMiscRenderer* renderer = gYume->pRenderer;
Scene* scene = renderer->GetScene();
YumeCamera* camera = renderer->GetCamera();
gYume->pInput->AddListener(this);
#ifndef DISABLE_CEF
optionsMenu_ = new YumeOptionsMenu;
gYume->pUI->AddUIElement(optionsMenu_);
optionsMenu_->SetVisible(true);
overlay_ = new YumeDebugOverlay;
gYume->pUI->AddUIElement(overlay_);
overlay_->SetVisible(true);
overlay_->GetBinding("SampleName")->SetValue("Post Processing");
#endif
//Define post processing effects
RenderPass* dp = renderer->GetDefaultPass();
dp->Load("RenderCalls/Bloom.xml",true);
dp->Load("RenderCalls/FXAA.xml",true);
dp->Load("RenderCalls/LensDistortion.xml",true);
dp->Load("RenderCalls/Godrays.xml",true);
dp->Load("RenderCalls/ShowGBuffer.xml",true);
dp->DisableRenderCalls("ShowGBuffer");
dp->DisableRenderCalls("Godrays");
dp->DisableRenderCalls("Bloom");
MaterialPtr emissiveBlue = YumeAPINew Material;
emissiveBlue->SetShaderParameter("DiffuseColor",DirectX::XMFLOAT4(0,0,1,1));
emissiveBlue->SetShaderParameter("SpecularColor",DirectX::XMFLOAT4(1,1,1,1));
emissiveBlue->SetShaderParameter("Roughness",0.001f);
emissiveBlue->SetShaderParameter("ShadingMode",0);
emissiveBlue->SetShaderParameter("has_diffuse_tex",false);
emissiveBlue->SetShaderParameter("has_alpha_tex",false);
emissiveBlue->SetShaderParameter("has_specular_tex",false);
emissiveBlue->SetShaderParameter("has_normal_tex",false);
emissiveBlue->SetShaderParameter("has_roughness_tex",false);
MaterialPtr emissiveRed = YumeAPINew Material;
emissiveRed->SetShaderParameter("DiffuseColor",DirectX::XMFLOAT4(1,0,0,1));
emissiveRed->SetShaderParameter("SpecularColor",DirectX::XMFLOAT4(1,1,1,1));
emissiveRed->SetShaderParameter("Roughness",0.001f);
emissiveRed->SetShaderParameter("ShadingMode",0);
emissiveRed->SetShaderParameter("has_diffuse_tex",false);
emissiveRed->SetShaderParameter("has_alpha_tex",false);
emissiveRed->SetShaderParameter("has_specular_tex",false);
emissiveRed->SetShaderParameter("has_normal_tex",false);
emissiveRed->SetShaderParameter("has_roughness_tex",false);
MaterialPtr emissivePink = YumeAPINew Material;
emissivePink->SetShaderParameter("DiffuseColor",DirectX::XMFLOAT4(1,0.0784314f,0.576471f,1));
emissivePink->SetShaderParameter("SpecularColor",DirectX::XMFLOAT4(1,1,1,1));
emissivePink->SetShaderParameter("Roughness",0.001f);
emissivePink->SetShaderParameter("ShadingMode",0);
emissivePink->SetShaderParameter("has_diffuse_tex",false);
emissivePink->SetShaderParameter("has_alpha_tex",false);
emissivePink->SetShaderParameter("has_specular_tex",false);
emissivePink->SetShaderParameter("has_normal_tex",false);
emissivePink->SetShaderParameter("has_roughness_tex",false);
StaticModel* jeyjeyModel = CreateModel("Models/sponza/sponza.yume");
Light* dirLight = new Light;
dirLight->SetName("DirLight");
dirLight->SetType(LT_DIRECTIONAL);
dirLight->SetPosition(DirectX::XMVectorSet(0,1500,0,0));
dirLight->SetDirection(DirectX::XMVectorSet(0,-1,0,0));
dirLight->SetRotation(DirectX::XMVectorSet(-1,0,0,0));
dirLight->SetColor(YumeColor(1,1,1,0));
scene->AddNode(dirLight);
}
void GodRays::MoveCamera(float timeStep)
{
}
void GodRays::HandleUpdate(float timeStep)
{
}
void GodRays::HandleRenderUpdate(float timeStep)
{
}
void GodRays::Setup()
{
engineVariants_["GI"] = LPV;
engineVariants_["WindowWidth"] = 1024;
engineVariants_["WindowHeight"] = 768;
BaseApplication::Setup();
}
}
| 27.725146 | 95 | 0.730015 | rodrigobmg |
84459f68a60fdf2e0000ed96d3ea03669d0acbe6 | 4,547 | cpp | C++ | Sankore-3.1/src/domain/UBItem.cpp | eaglezzb/rsdc | cce881f6542ff206bf286cf798c8ec8da3b51d50 | [
"MIT"
] | null | null | null | Sankore-3.1/src/domain/UBItem.cpp | eaglezzb/rsdc | cce881f6542ff206bf286cf798c8ec8da3b51d50 | [
"MIT"
] | null | null | null | Sankore-3.1/src/domain/UBItem.cpp | eaglezzb/rsdc | cce881f6542ff206bf286cf798c8ec8da3b51d50 | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2010-2013 Groupement d'Intérêt Public pour l'Education Numérique en Afrique (GIP ENA)
*
* This file is part of Open-Sankoré.
*
* Open-Sankoré 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, version 3 of the License,
* with a specific linking exception for the OpenSSL project's
* "OpenSSL" library (or with modified versions of it that use the
* same license as the "OpenSSL" library).
*
* Open-Sankoré 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 Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
*/
#include "UBItem.h"
#include "core/memcheck.h"
#include "domain/UBGraphicsPixmapItem.h"
#include "domain/UBGraphicsTextItem.h"
#include "domain/UBGraphicsSvgItem.h"
#include "domain/UBGraphicsMediaItem.h"
#include "domain/UBGraphicsStrokesGroup.h"
#include "domain/UBGraphicsGroupContainerItem.h"
#include "domain/UBGraphicsWidgetItem.h"
#include "domain/UBEditableGraphicsPolygonItem.h"
#include "domain/UBEditableGraphicsRegularShapeItem.h"
#include "domain/UBGraphicsEllipseItem.h"
#include "domain/UBGraphicsRectItem.h"
#include "domain/UBGraphicsLineItem.h"
#include "domain/UBGraphicsFreehandItem.h"
#include "tools/UBGraphicsCurtainItem.h"
UBItem::UBItem()
: mUuid(QUuid())
, mRenderingQuality(UBItem::RenderingQualityNormal)
{
// NOOP
}
UBItem::~UBItem()
{
// NOOP
}
UBGraphicsItem::~UBGraphicsItem()
{
if (mDelegate!=NULL){
delete mDelegate;
mDelegate = NULL;
}
}
void UBGraphicsItem::setDelegate(UBGraphicsItemDelegate* delegate)
{
Q_ASSERT(mDelegate==NULL);
mDelegate = delegate;
}
void UBGraphicsItem::assignZValue(QGraphicsItem *item, qreal value)
{
item->setZValue(value);
item->setData(UBGraphicsItemData::ItemOwnZValue, value);
}
bool UBGraphicsItem::isFlippable(QGraphicsItem *item)
{
return item->data(UBGraphicsItemData::ItemFlippable).toBool();
}
bool UBGraphicsItem::isRotatable(QGraphicsItem *item)
{
return item->data(UBGraphicsItemData::ItemRotatable).toBool();
}
bool UBGraphicsItem::isLocked(QGraphicsItem *item)
{
return item->data(UBGraphicsItemData::ItemLocked).toBool();
}
QUuid UBGraphicsItem::getOwnUuid(QGraphicsItem *item)
{
QString idCandidate = item->data(UBGraphicsItemData::ItemUuid).toString();
return idCandidate == QUuid().toString() ? QUuid() : QUuid(idCandidate);
}
qreal UBGraphicsItem::getOwnZValue(QGraphicsItem *item)
{
return item->data(UBGraphicsItemData::ItemOwnZValue).toReal();
}
void UBGraphicsItem::remove(bool canUndo)
{
if (Delegate() && !Delegate()->isLocked())
Delegate()->remove(canUndo);
}
UBGraphicsItemDelegate *UBGraphicsItem::Delegate(QGraphicsItem *pItem)
{
UBGraphicsItemDelegate *result = 0;
switch (static_cast<int>(pItem->type())) {
case UBGraphicsPixmapItem::Type :
result = (static_cast<UBGraphicsPixmapItem*>(pItem))->Delegate();
break;
case UBGraphicsTextItem::Type :
result = (static_cast<UBGraphicsTextItem*>(pItem))->Delegate();
break;
case UBGraphicsSvgItem::Type :
result = (static_cast<UBGraphicsSvgItem*>(pItem))->Delegate();
break;
case UBGraphicsMediaItem::Type:
result = (static_cast<UBGraphicsMediaItem*>(pItem))->Delegate();
break;
case UBGraphicsStrokesGroup::Type :
result = (static_cast<UBGraphicsStrokesGroup*>(pItem))->Delegate();
break;
case UBGraphicsGroupContainerItem::Type :
result = (static_cast<UBGraphicsGroupContainerItem*>(pItem))->Delegate();
break;
case UBGraphicsWidgetItem::Type :
result = (static_cast<UBGraphicsWidgetItem*>(pItem))->Delegate();
break;
case UBGraphicsCurtainItem::Type :
result = (static_cast<UBGraphicsCurtainItem*>(pItem))->Delegate();
break;
case UBEditableGraphicsRegularShapeItem::Type :
case UBEditableGraphicsPolygonItem::Type :
case UBGraphicsFreehandItem::Type :
case UBGraphicsItemType::GraphicsShapeItemType :
UBAbstractGraphicsItem* item = dynamic_cast<UBAbstractGraphicsItem*>(pItem);
if (item)
result = item->Delegate();
break;
}
return result;
}
| 30.516779 | 102 | 0.720475 | eaglezzb |
844620b796aba499ce01fcbcbd13774f592a3af7 | 1,917 | cpp | C++ | src/renderer/components/RectComponent.cpp | artfulbytes/sumobot_simulator | f2784d2ff506759019d7d5e840bd7aed591a0add | [
"MIT"
] | null | null | null | src/renderer/components/RectComponent.cpp | artfulbytes/sumobot_simulator | f2784d2ff506759019d7d5e840bd7aed591a0add | [
"MIT"
] | null | null | null | src/renderer/components/RectComponent.cpp | artfulbytes/sumobot_simulator | f2784d2ff506759019d7d5e840bd7aed591a0add | [
"MIT"
] | null | null | null | #include "components/RectComponent.h"
#include "Renderer.h"
#include "components/Transforms.h"
#include "TexCoords.h"
#include "Texture.h"
#include "SpriteAnimation.h"
RectComponent::RectComponent(const RectTransform *transform, const glm::vec4& color) :
m_quadTransform(transform),
m_color(color)
{
}
RectComponent::RectComponent(const RectTransform *transform, const std::string &textureName, SpriteAnimation *spriteAnimation) :
m_quadTransform(transform),
m_texture(std::make_unique<Texture>(textureName)),
m_texCoords(std::make_unique<TexCoords>()),
m_spriteAnimation(spriteAnimation)
{
}
RectComponent::RectComponent(const CircleTransform *transform, const std::string &textureName, SpriteAnimation *spriteAnimation) :
m_circleTransform(transform),
m_texture(std::make_unique<Texture>(textureName)),
m_texCoords(std::make_unique<TexCoords>()),
m_spriteAnimation(spriteAnimation)
{
}
RectComponent::~RectComponent()
{
}
void RectComponent::onFixedUpdate()
{
if (m_enabled == false) {
return;
}
if (m_spriteAnimation != nullptr) {
m_spriteAnimation->onFixedUpdate();
m_spriteAnimation->computeTexCoords(*m_texCoords);
}
glm::vec2 size;
glm::vec2 position;
float rotation = 0.0f;
if (m_quadTransform != nullptr) {
size = m_quadTransform->size;
position = m_quadTransform->position;
rotation = m_quadTransform->rotation;
} else if (m_circleTransform != nullptr) {
size = glm::vec2{ 2 * m_circleTransform->radius, 2 * m_circleTransform->radius };
position = m_circleTransform->position;
rotation = m_circleTransform->rotation;
} else {
assert(0);
}
if (m_texture) {
Renderer::drawRect(position, size, rotation, *m_texture.get(), m_texCoords.get());
} else {
Renderer::drawRect(position, size, rotation, m_color);
}
}
| 29.045455 | 130 | 0.695357 | artfulbytes |
8446b534ea042ba69efdfb5ac4c427e47710ad33 | 5,067 | cpp | C++ | src/imports/cvkb/vkbquickmodel.cpp | CELLINKAB/qtcvkb | 5b870f8ea4b42480eb678b065778de5dab36b199 | [
"MIT"
] | null | null | null | src/imports/cvkb/vkbquickmodel.cpp | CELLINKAB/qtcvkb | 5b870f8ea4b42480eb678b065778de5dab36b199 | [
"MIT"
] | null | null | null | src/imports/cvkb/vkbquickmodel.cpp | CELLINKAB/qtcvkb | 5b870f8ea4b42480eb678b065778de5dab36b199 | [
"MIT"
] | null | null | null | /*
* The MIT License (MIT)
*
* Copyright (C) 2020 CELLINK AB <[email protected]>
*
* 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 "vkbquickmodel.h"
#include "vkbquickdelegate.h"
#include "vkbquicklayout.h"
#include "vkbquickpopup.h"
#include <QtQml/qqmlcomponent.h>
#include <QtQml/qqmlcontext.h>
#include <QtQml/qqmlengine.h>
#include <QtQuickTemplates2/private/qquickabstractbutton_p.h>
VkbQuickModel::VkbQuickModel(QObject *parent) : QObject(parent)
{
}
QQmlListProperty<VkbQuickDelegate> VkbQuickModel::delegates()
{
return QQmlListProperty<VkbQuickDelegate>(this, nullptr, delegates_append, delegates_count, delegates_at, delegates_clear);
}
VkbQuickDelegate *VkbQuickModel::findDelegate(Qt::Key key) const
{
auto it = std::find_if(m_delegates.cbegin(), m_delegates.cend(), [&key](VkbQuickDelegate *delegate) { return delegate->key() == key; });
if (it != m_delegates.cend())
return *it;
if (key != Qt::Key_unknown)
return findDelegate(Qt::Key_unknown);
return nullptr;
}
template <typename T>
static T *beginCreate(const VkbInputKey &key, QQmlComponent *component, QObject *parent)
{
if (!component)
return nullptr;
QQmlContext *creationContext = component->creationContext();
if (!creationContext)
creationContext = qmlContext(parent);
QQmlContext *context = new QQmlContext(creationContext, parent);
QObject *instance = component->beginCreate(context);
T *object = qobject_cast<T *>(instance);
if (!object) {
delete instance;
return nullptr;
}
VkbQuickLayoutAttached *attached = VkbQuickLayout::qmlAttachedPropertiesObject(instance);
if (attached)
attached->setInputKey(key);
return object;
}
QQuickAbstractButton *VkbQuickModel::createButton(const VkbInputKey &key, QQuickItem *parent) const
{
VkbQuickDelegate *delegate = findDelegate(key.key);
if (!delegate)
return nullptr;
QQmlComponent *component = delegate->button();
QQuickAbstractButton *button = beginCreate<QQuickAbstractButton>(key, component, parent);
if (!button) {
qWarning() << "VkbQuickModel::createButton: button delegate for" << key.key << "is not a Button";
return nullptr;
}
button->setParentItem(parent);
button->setFocusPolicy(Qt::NoFocus);
button->setAutoRepeat(key.autoRepeat);
button->setCheckable(key.checkable);
if (key.checked)
button->setChecked(true);
component->completeCreate();
return button;
}
VkbQuickPopup *VkbQuickModel::createPopup(const VkbInputKey &key, QQuickAbstractButton *button) const
{
VkbQuickDelegate *delegate = findDelegate(key.key);
if (!delegate)
return nullptr;
QQmlComponent *component = delegate->popup();
VkbQuickPopup *popup = beginCreate<VkbQuickPopup>(key, component, button);
if (!popup) {
qWarning() << "VkbQuickModel::createPopup: popup delegate for" << key.key << "is not an InputPopup";
return nullptr;
}
popup->setParentItem(button);
popup->setAlt(key.alt);
component->completeCreate();
return popup;
}
void VkbQuickModel::delegates_append(QQmlListProperty<VkbQuickDelegate> *property, VkbQuickDelegate *delegate)
{
VkbQuickModel *that = static_cast<VkbQuickModel *>(property->object);
that->m_delegates.append(delegate);
emit that->delegatesChanged();
}
int VkbQuickModel::delegates_count(QQmlListProperty<VkbQuickDelegate> *property)
{
VkbQuickModel *that = static_cast<VkbQuickModel *>(property->object);
return that->m_delegates.count();
}
VkbQuickDelegate *VkbQuickModel::delegates_at(QQmlListProperty<VkbQuickDelegate> *property, int index)
{
VkbQuickModel *that = static_cast<VkbQuickModel *>(property->object);
return that->m_delegates.value(index);
}
void VkbQuickModel::delegates_clear(QQmlListProperty<VkbQuickDelegate> *property)
{
VkbQuickModel *that = static_cast<VkbQuickModel *>(property->object);
that->m_delegates.clear();
emit that->delegatesChanged();
}
| 34.705479 | 140 | 0.727452 | CELLINKAB |
460071945d8a1109cb33f18a22a10552fabac77c | 1,052 | cpp | C++ | src/dynamic_load.cpp | cgilmour/dd-opentracing-cpp | c83c6a5dc72029d13ab0d64a7222fb139a1889f1 | [
"Apache-2.0"
] | null | null | null | src/dynamic_load.cpp | cgilmour/dd-opentracing-cpp | c83c6a5dc72029d13ab0d64a7222fb139a1889f1 | [
"Apache-2.0"
] | null | null | null | src/dynamic_load.cpp | cgilmour/dd-opentracing-cpp | c83c6a5dc72029d13ab0d64a7222fb139a1889f1 | [
"Apache-2.0"
] | null | null | null | #include <opentracing/dynamic_load.h>
#include <iostream>
#include "tracer.h"
#include "tracer_factory.h"
#include "version_check.h"
int OpenTracingMakeTracerFactory(const char* opentracing_version, const void** error_category,
void** tracer_factory) try {
if (!datadog::opentracing::equal_or_higher_version(std::string(opentracing_version),
std::string(OPENTRACING_VERSION))) {
std::cerr << "version mismatch: " << std::string(opentracing_version)
<< " != " << std::string(OPENTRACING_VERSION) << std::endl;
*error_category = static_cast<const void*>(&opentracing::dynamic_load_error_category());
return opentracing::incompatible_library_versions_error.value();
}
*tracer_factory = new datadog::opentracing::TracerFactory<datadog::opentracing::Tracer>{};
return 0;
} catch (const std::bad_alloc&) {
*error_category = static_cast<const void*>(&std::generic_category());
return static_cast<int>(std::errc::not_enough_memory);
}
| 47.818182 | 94 | 0.681559 | cgilmour |
4604dc0789f87eabd6425248d8f7f211dcb9baed | 6,663 | cpp | C++ | src/future/flexer.cpp | rasfmar/future | 189a996f7e2c6401626d11ca6d8f11243dd0b737 | [
"MIT"
] | null | null | null | src/future/flexer.cpp | rasfmar/future | 189a996f7e2c6401626d11ca6d8f11243dd0b737 | [
"MIT"
] | null | null | null | src/future/flexer.cpp | rasfmar/future | 189a996f7e2c6401626d11ca6d8f11243dd0b737 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <string>
#include "internal/_ftoken.hpp"
#include "fstate.hpp"
#include "flexer.hpp"
void flexer::lex(fstate *state, fparser &parser) {
lex(state, parser.tokens);
}
void flexer::lex(fstate *state, std::vector<_ftoken*> &tokens) {
std::stack<_ftoken*> fstack;
bool die = false;
for (_ftoken *token : tokens) {
// if it's an operator
if (token->type >= _FPLUS) {
switch(token->type) {
case _FPLUS: {
// todo error handling
if (fstack.size() < 2) {
die = true;
break;
}
_ftoken* second_operand = fstack.top();
fstack.pop();
_ftoken* first_operand = fstack.top();
fstack.pop();
// todo assert that second operand is of same type as first
_27: switch (first_operand->type) {
case _FINT32: {
int32_t first_operand_val = *(int32_t *)first_operand->val;
if (second_operand->type == _FID) {
// todo stop assuming dEFINED
std::string second_operand_val = *(std::string *)second_operand->val;
if (!state->definitions.count(second_operand_val)) {
// error
die = true;
break;
}
_ftoken *definition = state->definitions[second_operand_val];
second_operand->type = definition->type;
second_operand->val = definition->val;
}
if (second_operand->type != _FINT32) {
// error!
fstack.push(new _ftoken());
break;
}
int32_t second_operand_val = *(int32_t *)second_operand->val;
int32_t *result = new int32_t(first_operand_val + second_operand_val);
fstack.push(new _ftoken(result));
// delete first_operand;
// delete second_operand;
break;
}
case _FSTRING: {
std::string first_operand_val = *(std::string *)first_operand->val;
std::string second_operand_val = *(std::string *)second_operand->val;
std::string *result = new std::string(first_operand_val + second_operand_val);
fstack.push(new _ftoken(result));
// delete first_operand;
// delete second_operand;
break;
}
case _FID: {
// todo stop assuming its defined
std::string first_operand_val = *(std::string *)first_operand->val;
if (!state->definitions.count(first_operand_val)) {
// error
die = true;
break;
}
_ftoken *definition = state->definitions[first_operand_val];
first_operand->type = definition->type;
first_operand->val = definition->val;
goto _27;
}
default:
fstack.push(new _ftoken());
break;
}
break;
}
case _FMINUS: {
// todo error handling
if (fstack.size() < 2) {
die = true;
break;
}
_ftoken* second_operand = fstack.top();
fstack.pop();
_ftoken* first_operand = fstack.top();
fstack.pop();
// todo assert that second operand is of same type as first
_60: switch (first_operand->type) {
case _FINT32: {
int32_t first_operand_val = *(int32_t *)first_operand->val;
if (second_operand->type == _FID) {
// todo stop assuming dEFINED
std::string second_operand_val = *(std::string *)second_operand->val;
if (!state->definitions.count(second_operand_val)) {
// error
die = true;
break;
}
_ftoken *definition = state->definitions[second_operand_val];
second_operand->type = definition->type;
second_operand->val = definition->val;
}
if (second_operand->type != _FINT32) {
// error!
fstack.push(new _ftoken());
break;
}
int32_t second_operand_val = *(int32_t *)second_operand->val;
int32_t *result = new int32_t(first_operand_val - second_operand_val);
fstack.push(new _ftoken(result));
// delete first_operand;
// delete second_operand;
break;
}
case _FID: {
// todo stop assuming its defined
std::string first_operand_val = *(std::string *)first_operand->val;
if (!state->definitions.count(first_operand_val)) {
// error
die = true;
break;
}
_ftoken *definition = state->definitions[first_operand_val];
first_operand->type = definition->type;
first_operand->val = definition->val;
goto _60;
}
default:
fstack.push(new _ftoken());
break;
}
break;
}
case _FEQUALS: {
// todo error handling for empty stack
if (fstack.size() < 2) {
die = true;
break;
}
_ftoken* second_operand = fstack.top();
fstack.pop();
_ftoken* first_operand = fstack.top();
fstack.pop();
// todo error if first operand is not an identifier
std::string first_operand_val = *(std::string *)first_operand->val;
// setting this directly to second_operand could be a problem
state->definitions[first_operand_val] = second_operand->clone();
// delete first_operand;
// delete second_operand;
break;
}
case _FPRINT: {
if (fstack.size() < 1) {
die = true;
break;
}
_ftoken* first_operand = fstack.top();
fstack.pop();
if (first_operand->type == _FID) {
std::string first_operand_val = *(std::string *)first_operand->val;
if (!state->definitions.count(first_operand_val)) {
die = true;
break;
}
_ftoken *definition = state->definitions[first_operand_val];
first_operand->type = definition->type;
first_operand->val = definition->val;
}
std::cout << first_operand->valstr() << std::endl;
break;
}
case _FINPUT: {
std::string *in = new std::string("");
std::getline(std::cin, *in);
_ftoken *token = new _ftoken(in);
fstack.push(token);
break;
}
default:
break;
}
} else {
fstack.push(token);
}
if (die)
break;
}
tokens.clear();
while (!fstack.empty()) {
std::cout << (fstack.top())->str() << std::endl;
fstack.pop();
}
}
| 31.880383 | 88 | 0.540147 | rasfmar |
46054b06a51fe0732a8681424f05cfcf5161c13e | 1,212 | cpp | C++ | test/communicator_broadcast.cpp | correaa/b-mpi3 | 161e52a28ab9043be9ef33acd8f31dbeae483b61 | [
"BSL-1.0"
] | null | null | null | test/communicator_broadcast.cpp | correaa/b-mpi3 | 161e52a28ab9043be9ef33acd8f31dbeae483b61 | [
"BSL-1.0"
] | null | null | null | test/communicator_broadcast.cpp | correaa/b-mpi3 | 161e52a28ab9043be9ef33acd8f31dbeae483b61 | [
"BSL-1.0"
] | null | null | null | #if COMPILATION_INSTRUCTIONS
mpic++ -O3 -std=c++14 -Wall -Wfatal-errors $0 -o $0x.x && time mpirun -n 2 $0x.x $@ && rm -f $0x.x; exit
#endif
// © Copyright Alfredo A. Correa 2018-2020
#include "../../mpi3/main.hpp"
#include "../../mpi3/communicator.hpp"
namespace mpi3 = boost::mpi3;
int mpi3::main(int, char*[], mpi3::communicator world){
std::vector<std::size_t> sizes = {100, 64*1024};//, 128*1024}; // TODO check larger number (fails with openmpi 4.0.5)
int NUM_REPS = 5;
using value_type = int;
std::vector<value_type> buf(128*1024);
for(std::size_t n=0; n != sizes.size(); ++n){
// if(world.root()) cout<<"bcasting "<< sizes[n] <<" ints "<< NUM_REPS <<" times.\n";
for(int reps = 0; reps != NUM_REPS; ++reps){
if(world.root())
for(std::size_t i = 0; i != sizes[n]; ++i){
buf[i] = 1000000.*(n * NUM_REPS + reps) + i;
}
else
for(std::size_t i = 0; i != sizes[n]; ++i){
buf[i] = -(n * NUM_REPS + reps) - 1;
}
world.broadcast_n(buf.begin(), sizes[n]);
// world.broadcast(buf.begin(), buf.begin() + sizes[n], 0);
for(std::size_t i = 0; i != sizes[n]; ++i)
assert( fabs(buf[i] - (1000000.*(n * NUM_REPS + reps) + i)) < 1e-4 );
}
}
return 0;
}
| 27.545455 | 118 | 0.575908 | correaa |
460819731d1f58a91ad128467d955be784f981e0 | 764 | hpp | C++ | libs/resource_tree/include/sge/resource_tree/detail/strip_path_prefix.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 2 | 2016-01-27T13:18:14.000Z | 2018-05-11T01:11:32.000Z | libs/resource_tree/include/sge/resource_tree/detail/strip_path_prefix.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | null | null | null | libs/resource_tree/include/sge/resource_tree/detail/strip_path_prefix.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 3 | 2018-05-11T01:11:34.000Z | 2021-04-24T19:47:45.000Z | // Copyright Carl Philipp Reh 2006 - 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef SGE_RESOURCE_TREE_DETAIL_STRIP_PATH_PREFIX_HPP_INCLUDED
#define SGE_RESOURCE_TREE_DETAIL_STRIP_PATH_PREFIX_HPP_INCLUDED
#include <sge/resource_tree/path_fwd.hpp>
#include <sge/resource_tree/detail/base_path.hpp>
#include <sge/resource_tree/detail/sub_path.hpp>
#include <sge/resource_tree/detail/symbol.hpp>
namespace sge::resource_tree::detail
{
SGE_RESOURCE_TREE_DETAIL_SYMBOL
sge::resource_tree::path strip_path_prefix(
sge::resource_tree::detail::base_path const &, sge::resource_tree::detail::sub_path const &);
}
#endif
| 31.833333 | 97 | 0.784031 | cpreh |
4608b94ee463cd53b6600c1666ac954f0d0ee380 | 3,114 | cpp | C++ | Drivers/SelfTests/Boundaries/InsertionBoundarySelfTest.cpp | gustavo-castillo-bautista/Mercury | eeb402ccec8e487652229d4595c46ec84f6aefbb | [
"BSD-3-Clause"
] | null | null | null | Drivers/SelfTests/Boundaries/InsertionBoundarySelfTest.cpp | gustavo-castillo-bautista/Mercury | eeb402ccec8e487652229d4595c46ec84f6aefbb | [
"BSD-3-Clause"
] | null | null | null | Drivers/SelfTests/Boundaries/InsertionBoundarySelfTest.cpp | gustavo-castillo-bautista/Mercury | eeb402ccec8e487652229d4595c46ec84f6aefbb | [
"BSD-3-Clause"
] | null | null | null | //Copyright (c) 2013-2020, The MercuryDPM Developers Team. All rights reserved.
//For the list of developers, see <http://www.MercuryDPM.org/Team>.
//
//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 MercuryDPM 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 MERCURYDPM DEVELOPERS TEAM BE LIABLE FOR ANY
//DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
//(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
//ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
//(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <iostream>
#include "Mercury3D.h"
#include "Boundaries/CubeInsertionBoundary.h"
#include "Boundaries/PeriodicBoundary.h"
#include "Species/LinearViscoelasticSpecies.h"
#include "Walls/InfiniteWall.h"
class InsertionBoundarySelfTest : public Mercury3D
{
public:
void setupInitialConditions() override {
setName("InsertionBoundarySelfTest");
setSystemDimensions(3);
setGravity(Vec3D(0, 0, 0));
setTimeStep(1e-4);
dataFile.setSaveCount(10);
setTimeMax(2e-2);
setHGridMaxLevels(2);
setMin(Vec3D(0, 0, 0));
setMax(Vec3D(1, 1, 1));
LinearViscoelasticSpecies species;
species.setDensity(2000);
species.setStiffness(10000);
speciesHandler.copyAndAddObject(species);
SphericalParticle insertionBoundaryParticle;
insertionBoundaryParticle.setSpecies(speciesHandler.getObject(0));
CubeInsertionBoundary insertionBoundary;
insertionBoundary.set(&insertionBoundaryParticle,1,getMin(),getMax(),Vec3D(1,0,0),Vec3D(1,0,0),0.025,0.05);
boundaryHandler.copyAndAddObject(insertionBoundary);
}
void printTime() const override
{
logger(INFO,"t=%, tMax=%, N=%", getTime(),getTimeMax(), particleHandler.getSize());
}
};
int main(int argc UNUSED, char *argv[] UNUSED)
{
logger(INFO,"Simple box for creating particles");
InsertionBoundarySelfTest insertionBoundary_problem;
insertionBoundary_problem.solve();
}
| 39.923077 | 115 | 0.738279 | gustavo-castillo-bautista |
460e73849e3611b85524258bf2aaa70644de2b5f | 22,430 | cpp | C++ | scatterplot.cpp | fadel/msc-pm | bedf6936885694688ddb8bd3452f6bd68ef8d29c | [
"MIT"
] | null | null | null | scatterplot.cpp | fadel/msc-pm | bedf6936885694688ddb8bd3452f6bd68ef8d29c | [
"MIT"
] | null | null | null | scatterplot.cpp | fadel/msc-pm | bedf6936885694688ddb8bd3452f6bd68ef8d29c | [
"MIT"
] | null | null | null | #include "scatterplot.h"
#include <algorithm>
#include <cmath>
#include <limits>
#include <QSGGeometryNode>
#include <QSGSimpleRectNode>
#include "continuouscolorscale.h"
#include "geometry.h"
// Glyphs settings
static const QColor DEFAULT_GLYPH_COLOR(255, 255, 255);
static const float DEFAULT_GLYPH_SIZE = 8.0f;
static const qreal GLYPH_OPACITY = 1.0;
static const qreal GLYPH_OPACITY_SELECTED = 1.0;
static const float GLYPH_OUTLINE_WIDTH = 2.0f;
static const QColor GLYPH_OUTLINE_COLOR(0, 0, 0);
static const QColor GLYPH_OUTLINE_COLOR_SELECTED(20, 255, 225);
// Brush settings
static const float BRUSHING_MAX_DIST = 20.0f;
static const float CROSSHAIR_LENGTH = 8.0f;
static const float CROSSHAIR_THICKNESS1 = 1.0f;
static const float CROSSHAIR_THICKNESS2 = 0.5f;
static const QColor CROSSHAIR_COLOR1(255, 255, 255);
static const QColor CROSSHAIR_COLOR2(0, 0, 0);
// Selection settings
static const QColor SELECTION_COLOR(128, 128, 128, 96);
// Mouse buttons
static const Qt::MouseButton NORMAL_BUTTON = Qt::LeftButton;
static const Qt::MouseButton SPECIAL_BUTTON = Qt::RightButton;
class QuadTree
{
public:
QuadTree(const QRectF &bounds);
~QuadTree();
bool insert(float x, float y, int value);
int query(float x, float y) const;
void query(const QRectF &rect, std::vector<int> &result) const;
int nearestTo(float x, float y) const;
private:
bool subdivide();
void nearestTo(float x, float y, int &nearest, float &dist) const;
QRectF m_bounds;
float m_x, m_y;
int m_value;
QuadTree *m_nw, *m_ne, *m_sw, *m_se;
};
Scatterplot::Scatterplot(QQuickItem *parent)
: QQuickItem(parent)
, m_glyphSize(DEFAULT_GLYPH_SIZE)
, m_colorScale(0)
, m_autoScale(true)
, m_sx(0, 1, 0, 1)
, m_sy(0, 1, 0, 1)
, m_anySelected(false)
, m_brushedItem(-1)
, m_interactionState(StateNone)
, m_dragEnabled(false)
, m_shouldUpdateGeometry(false)
, m_shouldUpdateMaterials(false)
, m_quadtree(0)
{
setClip(true);
setFlag(QQuickItem::ItemHasContents);
}
Scatterplot::~Scatterplot()
{
if (m_quadtree) {
delete m_quadtree;
}
}
void Scatterplot::setColorScale(const ColorScale *colorScale)
{
m_colorScale = colorScale;
if (m_colorData.n_elem > 0) {
m_shouldUpdateMaterials = true;
update();
}
}
arma::mat Scatterplot::XY() const
{
return m_xy;
}
void Scatterplot::setXY(const arma::mat &xy)
{
if (xy.n_cols != 2) {
return;
}
m_xy = xy;
emit xyChanged(m_xy);
if (m_autoScale) {
autoScale();
}
updateQuadTree();
if (m_selection.size() != m_xy.n_rows) {
m_selection.assign(m_xy.n_rows, false);
}
if (m_opacityData.n_elem != m_xy.n_rows) {
// Reset opacity data
m_opacityData.resize(xy.n_rows);
m_opacityData.fill(GLYPH_OPACITY);
emit opacityDataChanged(m_opacityData);
}
m_shouldUpdateGeometry = true;
update();
}
void Scatterplot::setColorData(const arma::vec &colorData)
{
if (m_xy.n_rows > 0
&& (colorData.n_elem > 0 && colorData.n_elem != m_xy.n_rows)) {
return;
}
m_colorData = colorData;
emit colorDataChanged(m_colorData);
m_shouldUpdateMaterials = true;
update();
}
void Scatterplot::setOpacityData(const arma::vec &opacityData)
{
if (m_xy.n_rows > 0 && opacityData.n_elem != m_xy.n_rows) {
return;
}
m_opacityData = opacityData;
emit opacityDataChanged(m_opacityData);
update();
}
void Scatterplot::setScale(const LinearScale<float> &sx, const LinearScale<float> &sy)
{
m_sx = sx;
m_sy = sy;
emit scaleChanged(m_sx, m_sy);
updateQuadTree();
m_shouldUpdateGeometry = true;
update();
}
void Scatterplot::setAutoScale(bool autoScale)
{
m_autoScale = autoScale;
if (autoScale) {
this->autoScale();
}
}
void Scatterplot::autoScale()
{
m_sx.setDomain(m_xy.col(0).min(), m_xy.col(0).max());
m_sy.setDomain(m_xy.col(1).min(), m_xy.col(1).max());
emit scaleChanged(m_sx, m_sy);
}
void Scatterplot::setGlyphSize(float glyphSize)
{
if (m_glyphSize == glyphSize || glyphSize < 2.0f) {
return;
}
m_glyphSize = glyphSize;
emit glyphSizeChanged(m_glyphSize);
m_shouldUpdateGeometry = true;
update();
}
QSGNode *Scatterplot::newSceneGraph()
{
// NOTE:
// The hierarchy in the scene graph is as follows:
// root [[splatNode] [glyphsRoot [glyph [...]]] [selectionNode]]
QSGNode *root = new QSGNode;
QSGNode *glyphTreeRoot = newGlyphTree();
if (glyphTreeRoot) {
root->appendChildNode(glyphTreeRoot);
}
QSGSimpleRectNode *selectionRectNode = new QSGSimpleRectNode;
selectionRectNode->setColor(SELECTION_COLOR);
root->appendChildNode(selectionRectNode);
QSGTransformNode *brushNode = new QSGTransformNode;
QSGGeometryNode *whiteCrossHairNode = new QSGGeometryNode;
QSGGeometry *whiteCrossHairGeom = new QSGGeometry(QSGGeometry::defaultAttributes_Point2D(), 12);
whiteCrossHairGeom->setDrawingMode(GL_POLYGON);
whiteCrossHairGeom->setVertexDataPattern(QSGGeometry::DynamicPattern);
updateCrossHairGeometry(whiteCrossHairGeom, 0, 0, CROSSHAIR_THICKNESS1, CROSSHAIR_LENGTH);
QSGFlatColorMaterial *whiteCrossHairMaterial = new QSGFlatColorMaterial;
whiteCrossHairMaterial->setColor(CROSSHAIR_COLOR1);
whiteCrossHairNode->setGeometry(whiteCrossHairGeom);
whiteCrossHairNode->setMaterial(whiteCrossHairMaterial);
whiteCrossHairNode->setFlags(QSGNode::OwnsGeometry | QSGNode::OwnsMaterial);
brushNode->appendChildNode(whiteCrossHairNode);
QSGGeometryNode *blackCrossHairNode = new QSGGeometryNode;
QSGGeometry *blackCrossHairGeom = new QSGGeometry(QSGGeometry::defaultAttributes_Point2D(), 12);
blackCrossHairGeom->setDrawingMode(GL_POLYGON);
blackCrossHairGeom->setVertexDataPattern(QSGGeometry::DynamicPattern);
updateCrossHairGeometry(blackCrossHairGeom, 0, 0, CROSSHAIR_THICKNESS2, CROSSHAIR_LENGTH);
QSGFlatColorMaterial *blackCrossHairMaterial = new QSGFlatColorMaterial;
blackCrossHairMaterial->setColor(CROSSHAIR_COLOR2);
blackCrossHairNode->setGeometry(blackCrossHairGeom);
blackCrossHairNode->setMaterial(blackCrossHairMaterial);
blackCrossHairNode->setFlags(QSGNode::OwnsGeometry | QSGNode::OwnsMaterial);
brushNode->appendChildNode(blackCrossHairNode);
root->appendChildNode(brushNode);
return root;
}
QSGNode *Scatterplot::newGlyphTree()
{
// NOTE:
// The glyph graph is structured as:
// root [opacityNode [outlineNode fillNode] ...]
if (m_xy.n_rows < 1) {
return 0;
}
QSGNode *node = new QSGNode;
int vertexCount = calculateCircleVertexCount(m_glyphSize);
for (arma::uword i = 0; i < m_xy.n_rows; i++) {
QSGGeometry *glyphOutlineGeometry = new QSGGeometry(QSGGeometry::defaultAttributes_Point2D(), vertexCount);
glyphOutlineGeometry->setDrawingMode(GL_POLYGON);
glyphOutlineGeometry->setVertexDataPattern(QSGGeometry::DynamicPattern);
QSGGeometryNode *glyphOutlineNode = new QSGGeometryNode;
glyphOutlineNode->setGeometry(glyphOutlineGeometry);
glyphOutlineNode->setFlag(QSGNode::OwnsGeometry);
QSGFlatColorMaterial *material = new QSGFlatColorMaterial;
material->setColor(GLYPH_OUTLINE_COLOR);
glyphOutlineNode->setMaterial(material);
glyphOutlineNode->setFlag(QSGNode::OwnsMaterial);
QSGGeometry *glyphGeometry = new QSGGeometry(QSGGeometry::defaultAttributes_Point2D(), vertexCount);
glyphGeometry->setDrawingMode(GL_POLYGON);
glyphGeometry->setVertexDataPattern(QSGGeometry::DynamicPattern);
QSGGeometryNode *glyphNode = new QSGGeometryNode;
glyphNode->setGeometry(glyphGeometry);
glyphNode->setFlag(QSGNode::OwnsGeometry);
material = new QSGFlatColorMaterial;
material->setColor(DEFAULT_GLYPH_COLOR);
glyphNode->setMaterial(material);
glyphNode->setFlag(QSGNode::OwnsMaterial);
// Place the glyph geometry node under an opacity node
QSGOpacityNode *glyphOpacityNode = new QSGOpacityNode;
glyphOpacityNode->appendChildNode(glyphOutlineNode);
glyphOpacityNode->appendChildNode(glyphNode);
node->appendChildNode(glyphOpacityNode);
}
return node;
}
QSGNode *Scatterplot::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *)
{
QSGNode *root = oldNode ? oldNode : newSceneGraph();
if (m_xy.n_rows < 1) {
return root;
}
// This keeps track of where we are in the scene when updating
QSGNode *node = root->firstChild();
updateGlyphs(node);
node = node->nextSibling();
if (m_shouldUpdateGeometry) {
m_shouldUpdateGeometry = false;
}
if (m_shouldUpdateMaterials) {
m_shouldUpdateMaterials = false;
}
// Selection
QSGSimpleRectNode *selectionNode = static_cast<QSGSimpleRectNode *>(node);
if (m_interactionState == StateSelecting) {
selectionNode->setRect(QRectF(m_dragOriginPos, m_dragCurrentPos));
selectionNode->markDirty(QSGNode::DirtyGeometry);
} else {
// Hide selection rect
selectionNode->setRect(QRectF(-1, -1, 0, 0));
}
node = node->nextSibling();
// Brushing
updateBrush(node);
node = node->nextSibling();
return root;
}
void Scatterplot::updateGlyphs(QSGNode *glyphsNode)
{
qreal x, y, tx, ty, moveTranslationF;
if (!m_shouldUpdateGeometry && !m_shouldUpdateMaterials) {
return;
}
if (m_interactionState == StateMoving) {
tx = m_dragCurrentPos.x() - m_dragOriginPos.x();
ty = m_dragCurrentPos.y() - m_dragOriginPos.y();
} else {
tx = ty = 0;
}
m_sx.setRange(PADDING, width() - PADDING);
m_sy.setRange(height() - PADDING, PADDING);
QSGNode *node = glyphsNode->firstChild();
for (arma::uword i = 0; i < m_xy.n_rows; i++) {
const arma::rowvec &row = m_xy.row(i);
bool isSelected = m_selection[i];
QSGOpacityNode *glyphOpacityNode = static_cast<QSGOpacityNode *>(node);
glyphOpacityNode->setOpacity(m_opacityData[i]);
QSGGeometryNode *glyphOutlineNode = static_cast<QSGGeometryNode *>(node->firstChild());
QSGGeometryNode *glyphNode = static_cast<QSGGeometryNode *>(node->firstChild()->nextSibling());
if (m_shouldUpdateGeometry) {
moveTranslationF = isSelected ? 1.0 : 0.0;
x = m_sx(row[0]) + tx * moveTranslationF;
y = m_sy(row[1]) + ty * moveTranslationF;
QSGGeometry *geometry = glyphOutlineNode->geometry();
updateCircleGeometry(geometry, m_glyphSize, x, y);
glyphOutlineNode->markDirty(QSGNode::DirtyGeometry);
geometry = glyphNode->geometry();
updateCircleGeometry(geometry, m_glyphSize - 2*GLYPH_OUTLINE_WIDTH, x, y);
glyphNode->markDirty(QSGNode::DirtyGeometry);
}
if (m_shouldUpdateMaterials) {
QSGFlatColorMaterial *material = static_cast<QSGFlatColorMaterial *>(glyphOutlineNode->material());
material->setColor(isSelected ? GLYPH_OUTLINE_COLOR_SELECTED
: GLYPH_OUTLINE_COLOR);
glyphOutlineNode->markDirty(QSGNode::DirtyMaterial);
material = static_cast<QSGFlatColorMaterial *>(glyphNode->material());
if (m_colorData.n_elem > 0) {
material->setColor(m_colorScale->color(m_colorData[i]));
} else {
material->setColor(DEFAULT_GLYPH_COLOR);
}
glyphNode->markDirty(QSGNode::DirtyMaterial);
}
node = node->nextSibling();
}
// XXX: Beware: QSGNode::DirtyForceUpdate is undocumented
//
// This causes the scene graph to correctly update the materials of glyphs,
// even though we individually mark dirty materials. Used to work in Qt 5.5,
// though.
glyphsNode->markDirty(QSGNode::DirtyForceUpdate);
}
void Scatterplot::updateBrush(QSGNode *node)
{
QMatrix4x4 transform;
if (m_brushedItem < 0
|| (m_interactionState != StateNone
&& m_interactionState != StateSelected)) {
transform.translate(-width(), -height());
} else {
const arma::rowvec &row = m_xy.row(m_brushedItem);
transform.translate(m_sx(row[0]), m_sy(row[1]));
}
QSGTransformNode *brushNode = static_cast<QSGTransformNode *>(node);
brushNode->setMatrix(transform);
}
void Scatterplot::mousePressEvent(QMouseEvent *event)
{
switch (m_interactionState) {
case StateNone:
case StateSelected:
switch (event->button()) {
case NORMAL_BUTTON:
if (event->modifiers() == Qt::ShiftModifier && m_dragEnabled) {
m_interactionState = StateMoving;
m_dragOriginPos = event->localPos();
m_dragCurrentPos = m_dragOriginPos;
} else {
// We say 'brushing', but we mean 'selecting the current brushed
// item'
m_interactionState = StateBrushing;
}
break;
case SPECIAL_BUTTON:
m_interactionState = StateNone;
m_selection.assign(m_selection.size(), false);
emit selectionInteractivelyChanged(m_selection);
m_shouldUpdateMaterials = true;
update();
break;
}
break;
case StateBrushing:
case StateSelecting:
case StateMoving:
// Probably shouldn't reach these
break;
}
}
void Scatterplot::mouseMoveEvent(QMouseEvent *event)
{
switch (m_interactionState) {
case StateBrushing:
// Move while brushing becomes selecting, hence the 'fall through'
m_interactionState = StateSelecting;
m_dragOriginPos = event->localPos();
// fall through
case StateSelecting:
m_dragCurrentPos = event->localPos();
update();
break;
case StateMoving:
m_dragCurrentPos = event->localPos();
m_shouldUpdateGeometry = true;
update();
break;
case StateNone:
case StateSelected:
break;
}
}
void Scatterplot::mouseReleaseEvent(QMouseEvent *event)
{
bool mergeSelection = (event->modifiers() == Qt::ControlModifier);
switch (m_interactionState) {
case StateBrushing:
// Mouse clicked with brush target; set new selection or append to
// current
if (!mergeSelection) {
m_selection.assign(m_selection.size(), false);
}
if (m_brushedItem == -1) {
m_interactionState = StateNone;
if (m_anySelected && !mergeSelection) {
m_anySelected = false;
emit selectionInteractivelyChanged(m_selection);
m_shouldUpdateMaterials = true;
update();
}
} else {
m_interactionState = StateSelected;
m_selection[m_brushedItem] = !m_selection[m_brushedItem];
if (m_selection[m_brushedItem]) {
m_anySelected = true;
}
emit selectionInteractivelyChanged(m_selection);
m_shouldUpdateMaterials = true;
update();
}
break;
case StateSelecting:
{
// Selecting points and mouse is now released; update selection and
// brush
interactiveSelection(mergeSelection);
m_interactionState = m_anySelected ? StateSelected : StateNone;
QPoint pos = event->pos();
m_brushedItem = m_quadtree->nearestTo(pos.x(), pos.y());
emit itemInteractivelyBrushed(m_brushedItem);
m_shouldUpdateMaterials = true;
update();
}
break;
case StateMoving:
// Moving points and now stopped; apply manipulation
m_interactionState = StateSelected;
applyManipulation();
m_shouldUpdateGeometry = true;
update();
m_dragOriginPos = m_dragCurrentPos;
break;
case StateNone:
case StateSelected:
break;
}
}
void Scatterplot::hoverEnterEvent(QHoverEvent *event)
{
QPointF pos = event->posF();
m_brushedItem = m_quadtree->nearestTo(pos.x(), pos.y());
emit itemInteractivelyBrushed(m_brushedItem);
update();
}
void Scatterplot::hoverMoveEvent(QHoverEvent *event)
{
QPointF pos = event->posF();
m_brushedItem = m_quadtree->nearestTo(pos.x(), pos.y());
emit itemInteractivelyBrushed(m_brushedItem);
update();
}
void Scatterplot::hoverLeaveEvent(QHoverEvent *event)
{
m_brushedItem = -1;
emit itemInteractivelyBrushed(m_brushedItem);
update();
}
void Scatterplot::interactiveSelection(bool mergeSelection)
{
if (!mergeSelection) {
m_selection.assign(m_selection.size(), false);
}
std::vector<int> selected;
m_quadtree->query(QRectF(m_dragOriginPos, m_dragCurrentPos), selected);
for (auto i: selected) {
m_selection[i] = true;
}
for (auto isSelected: m_selection) {
if (isSelected) {
m_anySelected = true;
break;
}
}
emit selectionInteractivelyChanged(m_selection);
}
void Scatterplot::setSelection(const std::vector<bool> &selection)
{
if (m_selection.size() != selection.size()) {
return;
}
m_selection = selection;
emit selectionChanged(m_selection);
m_shouldUpdateMaterials = true;
update();
}
void Scatterplot::brushItem(int item)
{
m_brushedItem = item;
update();
}
void Scatterplot::applyManipulation()
{
m_sx.inverse();
m_sy.inverse();
LinearScale<float> rx = m_sx;
LinearScale<float> ry = m_sy;
m_sy.inverse();
m_sx.inverse();
float tx = m_dragCurrentPos.x() - m_dragOriginPos.x();
float ty = m_dragCurrentPos.y() - m_dragOriginPos.y();
for (std::vector<bool>::size_type i = 0; i < m_selection.size(); i++) {
if (m_selection[i]) {
arma::rowvec row = m_xy.row(i);
row[0] = rx(m_sx(row[0]) + tx);
row[1] = ry(m_sy(row[1]) + ty);
m_xy.row(i) = row;
}
}
updateQuadTree();
emit xyInteractivelyChanged(m_xy);
}
void Scatterplot::updateQuadTree()
{
m_sx.setRange(PADDING, width() - PADDING);
m_sy.setRange(height() - PADDING, PADDING);
if (m_quadtree) {
delete m_quadtree;
}
m_quadtree = new QuadTree(QRectF(x(), y(), width(), height()));
for (arma::uword i = 0; i < m_xy.n_rows; i++) {
const arma::rowvec &row = m_xy.row(i);
m_quadtree->insert(m_sx(row[0]), m_sy(row[1]), (int) i);
}
}
QuadTree::QuadTree(const QRectF &bounds)
: m_bounds(bounds)
, m_value(-1)
, m_nw(0), m_ne(0), m_sw(0), m_se(0)
{
}
QuadTree::~QuadTree()
{
if (m_nw) {
delete m_nw;
delete m_ne;
delete m_sw;
delete m_se;
}
}
bool QuadTree::subdivide()
{
float halfWidth = m_bounds.width() / 2;
float halfHeight = m_bounds.height() / 2;
m_nw = new QuadTree(QRectF(m_bounds.x(),
m_bounds.y(),
halfWidth,
halfHeight));
m_ne = new QuadTree(QRectF(m_bounds.x() + halfWidth,
m_bounds.y(),
halfWidth,
halfHeight));
m_sw = new QuadTree(QRectF(m_bounds.x(),
m_bounds.y() + halfHeight,
halfWidth,
halfHeight));
m_se = new QuadTree(QRectF(m_bounds.x() + halfWidth,
m_bounds.y() + halfHeight,
halfWidth,
halfHeight));
int value = m_value;
m_value = -1;
return m_nw->insert(m_x, m_y, value)
|| m_ne->insert(m_x, m_y, value)
|| m_sw->insert(m_x, m_y, value)
|| m_se->insert(m_x, m_y, value);
}
bool QuadTree::insert(float x, float y, int value)
{
if (!m_bounds.contains(x, y)) {
return false;
}
if (m_nw) {
return m_nw->insert(x, y, value)
|| m_ne->insert(x, y, value)
|| m_sw->insert(x, y, value)
|| m_se->insert(x, y, value);
}
if (m_value >= 0) {
subdivide();
return insert(x, y, value);
}
m_x = x;
m_y = y;
m_value = value;
return true;
}
int QuadTree::nearestTo(float x, float y) const
{
if (!m_bounds.contains(x, y)) {
return -1;
}
int q;
if (m_nw) {
q = m_nw->nearestTo(x, y);
if (q >= 0) return q;
q = m_ne->nearestTo(x, y);
if (q >= 0) return q;
q = m_sw->nearestTo(x, y);
if (q >= 0) return q;
q = m_se->nearestTo(x, y);
if (q >= 0) return q;
}
float dist = std::numeric_limits<float>::infinity();
nearestTo(x, y, q, dist);
if (dist < BRUSHING_MAX_DIST * BRUSHING_MAX_DIST)
return q;
return -1;
}
void QuadTree::nearestTo(float x, float y, int &nearest, float &dist) const
{
if (m_nw) {
m_nw->nearestTo(x, y, nearest, dist);
m_ne->nearestTo(x, y, nearest, dist);
m_sw->nearestTo(x, y, nearest, dist);
m_se->nearestTo(x, y, nearest, dist);
} else if (m_value >= 0) {
float d = (m_x - x)*(m_x - x) + (m_y - y)*(m_y - y);
if (d < dist) {
nearest = m_value;
dist = d;
}
}
}
int QuadTree::query(float x, float y) const
{
if (!m_bounds.contains(x, y)) {
// There is no way we could find the point
return -1;
}
if (m_nw) {
int q = -1;
q = m_nw->query(x, y);
if (q >= 0) return q;
q = m_ne->query(x, y);
if (q >= 0) return q;
q = m_sw->query(x, y);
if (q >= 0) return q;
q = m_se->query(x, y);
return q;
}
return m_value;
}
void QuadTree::query(const QRectF &rect, std::vector<int> &result) const
{
if (!m_bounds.intersects(rect)) {
return;
}
if (m_nw) {
m_nw->query(rect, result);
m_ne->query(rect, result);
m_sw->query(rect, result);
m_se->query(rect, result);
} else if (rect.contains(m_x, m_y) && m_value != -1) {
result.push_back(m_value);
}
}
| 28.609694 | 115 | 0.626973 | fadel |
4612f6436bee91d7c6b0cfc94f22418164a6900d | 2,187 | cpp | C++ | 排序/交换排序/P324.6.cpp | Ruvikm/Wangdao-Data-Structures | e00494f40c0be9d81229062bf69fe1e12e340773 | [
"MIT"
] | 103 | 2021-01-07T13:03:57.000Z | 2022-03-31T03:10:35.000Z | 排序/交换排序/P324.6.cpp | fu123567/Wangdao-Data-Structures | e00494f40c0be9d81229062bf69fe1e12e340773 | [
"MIT"
] | null | null | null | 排序/交换排序/P324.6.cpp | fu123567/Wangdao-Data-Structures | e00494f40c0be9d81229062bf69fe1e12e340773 | [
"MIT"
] | 23 | 2021-04-10T07:53:03.000Z | 2022-03-31T00:33:05.000Z | #include <cstdio>
#include <iostream>
#include <algorithm>
#include <time.h>
#include <stdlib.h>
using namespace std;
#pragma region 建立顺序存储的线性表
#define MAX 30
#define _for(i,a,b) for( int i=(a); i<(b); ++i)
#define _rep(i,a,b) for( int i=(a); i<=(b); ++i)
typedef struct {
int data[MAX];
int length;
}List;
void swap(int& a, int& b) {
int t;
t = a;
a = b;
b = t;
}
//给定一个List,传入List的大小,要逆转的起始位置
void Reserve(List& list, int start, int end, int size) {
if (end <= start || end >= size) {
return;
}
int mid = (start + end) / 2;
_rep(i, 0, mid - start) {
swap(list.data[start + i], list.data[end - i]);
}
}
void PrintList(List list) {
_for(i, 0, list.length) {
cout << list.data[i] << " ";
}
cout << endl;
}
void BuildList(List& list, int Len, int Data[]) {
list.length = Len;
_for(i, 0, list.length)
list.data[i] = Data[i];
}
#pragma endregion
//P323.6
//〖2016统考真题】已知由n(n≥2)个正整数构成的集合A = { ak|0 ≤ k ≤ n }, 将其划分为两
//个不相交的子集A1和A2, 元素个数分别是n1和n2, A1和A2中的元素之和分别为S1和S2
//设计一个尽可能高效的划分算法, 满足|n1 - n2|最小且| S1 - S1|最大。要求
//1)给出算法的基本设计思想
//2)根据设计思想, 采用C或C++语言描述算法, 关键之处给出注释
//3)说明你所设计算法的平均时间复杂度和空间复杂度
int Partiton(List& list) {
int low = 0, low0 = 0, high = list.length - 1, high0 = list.length - 1, k = list.length / 2;
bool NoFind = true;
while (NoFind) {
int pivot = list.data[low];
while (low < high) {
while (low < high && list.data[high] >= pivot)
high--;
if (low != high)
list.data[low] = list.data[high];
while (low < high && list.data[low] <= pivot)
low++;
if (low != high)
list.data[high] = list.data[low];
}
list.data[low] = pivot;
if (low == k - 1)
NoFind = false;
else {
if (low < k - 1) {
low0 = ++low;
high = high0;
}
else {
high0 = --high;
low = low0;
}
}
}
int s1 = 0, s2 = 0;
_for(i, 0, k)
s1 += list.data[i];
_for(i, k, list.length)
s2 += list.data[i];
return s2 - s1;
}
int main()
{
List list;
int Data[] = { 1,43,22,12,14,24,18,54,32,81 };
BuildList(list, 10, Data);
cout << "list为:" << endl;
PrintList(list);
cout << "排序后:" << endl;
sort(list.data, list.data + 10);
PrintList(list);
cout << "S2-S1最大值为:" << Partiton(list) << endl;
return 0;
} | 19.184211 | 93 | 0.581619 | Ruvikm |
4615023df5a596ca4b465687e621a84d88042a86 | 359 | cpp | C++ | module02/ex02/main.cpp | JLL32/piscine-cpp | d1d3296d8e25a1c33f7c92df4f61e6f76b8dab8c | [
"MIT"
] | null | null | null | module02/ex02/main.cpp | JLL32/piscine-cpp | d1d3296d8e25a1c33f7c92df4f61e6f76b8dab8c | [
"MIT"
] | null | null | null | module02/ex02/main.cpp | JLL32/piscine-cpp | d1d3296d8e25a1c33f7c92df4f61e6f76b8dab8c | [
"MIT"
] | null | null | null | #include "Fixed.hpp"
int main() {
Fixed a;
Fixed const b(Fixed(5.05f) * Fixed(2));
std::cout << a << std::endl;
std::cout << ++a << std::endl;
std::cout << a << std::endl;
std::cout << a++ << std::endl;
std::cout << a << std::endl;
std::cout << b << std::endl;
std::cout << Fixed::max(a, b) << std::endl;
return 0;
} | 22.4375 | 47 | 0.487465 | JLL32 |
461a10273aba9fcf0e0d3aa55bec17e788550bae | 271 | cpp | C++ | Test/run-test.cpp | As-12/Header-only-skeleton | 17603f3ef8c1808000213d8f12a7f6271c15de25 | [
"MIT"
] | null | null | null | Test/run-test.cpp | As-12/Header-only-skeleton | 17603f3ef8c1808000213d8f12a7f6271c15de25 | [
"MIT"
] | null | null | null | Test/run-test.cpp | As-12/Header-only-skeleton | 17603f3ef8c1808000213d8f12a7f6271c15de25 | [
"MIT"
] | null | null | null | // AllTests.cpp
#include <gtest/gtest.h>
#include <Library/Framework.hpp>
TEST(SubtractTest1, SubtractTwoNumbers)
{
Library::print();
EXPECT_EQ(5, 5);
}
int main(int argc, char **argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 15.055556 | 41 | 0.675277 | As-12 |
461aa61039c0c41d53644a5192d06be4b61e2968 | 210 | cpp | C++ | 266. Palindrome Permutation.cpp | rajeev-ranjan-au6/Leetcode_Cpp | f64cd98ab96ec110f1c21393f418acf7d88473e8 | [
"MIT"
] | 3 | 2020-12-30T00:29:59.000Z | 2021-01-24T22:43:04.000Z | 266. Palindrome Permutation.cpp | rajeevranjancom/Leetcode_Cpp | f64cd98ab96ec110f1c21393f418acf7d88473e8 | [
"MIT"
] | null | null | null | 266. Palindrome Permutation.cpp | rajeevranjancom/Leetcode_Cpp | f64cd98ab96ec110f1c21393f418acf7d88473e8 | [
"MIT"
] | null | null | null | class Solution {
public:
bool canPermutePalindrome(string s) {
unordered_map<char, int>m;
int odd = 0;
for(auto c: s) (m[c]++ % 2) ? odd-- : odd++;
return odd <= 1;
}
};
| 21 | 52 | 0.504762 | rajeev-ranjan-au6 |
462041eb825084ccf615b4abf767bd7c7a37acd1 | 520 | cpp | C++ | Engine/Source/Core/Types/Time.cpp | SparkyPotato/Ignis | 40cf87c03db7c07d3a05ab2c30bbe4fe3b16156c | [
"MIT"
] | 1 | 2021-02-27T15:42:47.000Z | 2021-02-27T15:42:47.000Z | Engine/Source/Core/Types/Time.cpp | SparkyPotato/Ignis | 40cf87c03db7c07d3a05ab2c30bbe4fe3b16156c | [
"MIT"
] | null | null | null | Engine/Source/Core/Types/Time.cpp | SparkyPotato/Ignis | 40cf87c03db7c07d3a05ab2c30bbe4fe3b16156c | [
"MIT"
] | null | null | null | /// Copyright (c) 2021 Shaye Garg.
#include "Core/Types/Time.h"
#include "Core/Platform/Platform.h"
#ifdef PLATFORM_WINDOWS
# include <Windows.h>
#endif
namespace Ignis {
#ifdef PLATFORM_WINDOWS
Time Time::Now()
{
SYSTEMTIME time;
GetLocalTime(&time);
return Time{ .Year = time.wYear,
.Month = u8(time.wMonth),
.Day = u8(time.wDay),
.WeekDay = u8(time.wDayOfWeek),
.Hour = u8(time.wHour),
.Minute = u8(time.wMinute),
.Millisecond = time.wMilliseconds };
}
#else
Time Time::Now()
{
}
#endif
}
| 13.684211 | 38 | 0.667308 | SparkyPotato |
46222bf791ebd8f20bf205a35de1fc7d309e10da | 1,485 | cpp | C++ | src/VKHelpers/Command/bindings.cpp | hiradyazdan/sdf-ray4d-engine | d71385e23cb630c54ff620ba1dff287ad90861b8 | [
"MIT"
] | 2 | 2021-09-28T22:15:44.000Z | 2022-02-03T22:25:46.000Z | src/VKHelpers/Command/bindings.cpp | hiradyazdan/sdf-ray4d-engine | d71385e23cb630c54ff620ba1dff287ad90861b8 | [
"MIT"
] | null | null | null | src/VKHelpers/Command/bindings.cpp | hiradyazdan/sdf-ray4d-engine | d71385e23cb630c54ff620ba1dff287ad90861b8 | [
"MIT"
] | null | null | null | /*****************************************************
* Partial Class: CommandHelper
* Members: Command Buffer Bindings/Overloads (Private)
*****************************************************/
#include "VKHelpers/Command.hpp"
using namespace sdfRay4d::vkHelpers;
/**
*
* @param[in] _material
*/
void CommandHelper::executeCmdBind(
const MaterialPtr &_material
) noexcept
{
m_deviceFuncs->vkCmdBindPipeline(
m_cmdBuffer,
VK_PIPELINE_BIND_POINT_GRAPHICS,
_material->pipeline
);
device::Size vbOffset = 0;
m_deviceFuncs->vkCmdBindVertexBuffers(
m_cmdBuffer,
0, 1,
&_material->buffer,
&vbOffset
);
const auto &descSets = _material->descSets;
const auto &descSetCount = descSets.size();
// the dynamic buffer points to the beginning of the vertex uniform data for the current frame.
const uint32_t frameDynamicOffset = m_frameId * vbOffset;
std::vector<uint32_t> frameDynamicOffsets = {}; // memset
for(auto i = 0; i < descSetCount; i++)
{
for (auto j = 0; j < _material->dynamicDescCount; j++)
{
frameDynamicOffsets.push_back(frameDynamicOffset);
}
const auto &dynamicOffsetCount = frameDynamicOffsets.size();
m_deviceFuncs->vkCmdBindDescriptorSets(
m_cmdBuffer,
VK_PIPELINE_BIND_POINT_GRAPHICS,
_material->pipelineLayout,
i, descSetCount,
&descSets[i],
dynamicOffsetCount,
dynamicOffsetCount > 0 ? frameDynamicOffsets.data() : nullptr
);
}
}
| 25.169492 | 97 | 0.648485 | hiradyazdan |
4624a63178202e6ae40f52aa49966a55347aa1d5 | 389 | cpp | C++ | src/lib/output/buzzer.cpp | aescariom/In3 | 0e6adcca3492bc69912170bf9a39719a407873c4 | [
"MIT"
] | 3 | 2016-09-23T18:11:32.000Z | 2021-05-31T20:50:47.000Z | src/lib/output/buzzer.cpp | aescariom/In3 | 0e6adcca3492bc69912170bf9a39719a407873c4 | [
"MIT"
] | 1 | 2016-09-23T18:14:32.000Z | 2016-10-08T21:11:14.000Z | src/lib/output/buzzer.cpp | aescariom/In3 | 0e6adcca3492bc69912170bf9a39719a407873c4 | [
"MIT"
] | 1 | 2017-03-24T19:30:43.000Z | 2017-03-24T19:30:43.000Z | #include "buzzer.h"
Buzzer::Buzzer(volatile uint8_t *port, volatile uint8_t *dir, uint8_t mask){
this->port = port;
this->dir = dir;
this->mask = mask;
}
void Buzzer::init(){
*(this->dir) |= 1 << this->mask; // output pin
}
void Buzzer::beep(){
this->toggle();
_delay_ms(_O_BUZZER_DELAY_MS);
this->toggle();
}
void Buzzer::toggle(){
*(this->port) ^= (1 << this->mask);
}
| 17.681818 | 76 | 0.619537 | aescariom |
4624bd768a1ee740003c4667e258e09558e94c5b | 4,891 | cpp | C++ | Math/Generating Function of a Linear Recurrence.cpp | bazzyadb/all-code | cf3039641b5aa84b1c5b184a95d69bd4091974c9 | [
"MIT"
] | 1,639 | 2021-09-15T09:12:06.000Z | 2022-03-31T22:58:57.000Z | Math/Generating Function of a Linear Recurrence.cpp | bazzyadb/all-code | cf3039641b5aa84b1c5b184a95d69bd4091974c9 | [
"MIT"
] | 16 | 2022-01-15T17:50:08.000Z | 2022-01-28T12:55:21.000Z | Math/Generating Function of a Linear Recurrence.cpp | bazzyadb/all-code | cf3039641b5aa84b1c5b184a95d69bd4091974c9 | [
"MIT"
] | 444 | 2021-09-15T09:17:41.000Z | 2022-03-29T18:21:46.000Z | #include<bits/stdc++.h>
using namespace std;
const int N = 3e3 + 9, mod = 998244353;
template <int32_t MOD>
struct modint {
int32_t value;
modint() = default;
modint(int32_t value_) : value(value_) {}
inline modint<MOD> operator + (modint<MOD> other) const { int32_t c = this->value + other.value; return modint<MOD>(c >= MOD ? c - MOD : c); }
inline modint<MOD> operator - (modint<MOD> other) const { int32_t c = this->value - other.value; return modint<MOD>(c < 0 ? c + MOD : c); }
inline modint<MOD> operator * (modint<MOD> other) const { int32_t c = (int64_t)this->value * other.value % MOD; return modint<MOD>(c < 0 ? c + MOD : c); }
inline modint<MOD> & operator += (modint<MOD> other) { this->value += other.value; if (this->value >= MOD) this->value -= MOD; return *this; }
inline modint<MOD> & operator -= (modint<MOD> other) { this->value -= other.value; if (this->value < 0) this->value += MOD; return *this; }
inline modint<MOD> & operator *= (modint<MOD> other) { this->value = (int64_t)this->value * other.value % MOD; if (this->value < 0) this->value += MOD; return *this; }
inline modint<MOD> operator - () const { return modint<MOD>(this->value ? MOD - this->value : 0); }
modint<MOD> pow(uint64_t k) const {
modint<MOD> x = *this, y = 1;
for (; k; k >>= 1) {
if (k & 1) y *= x;
x *= x;
}
return y;
}
modint<MOD> inv() const { return pow(MOD - 2); } // MOD must be a prime
inline modint<MOD> operator / (modint<MOD> other) const { return *this * other.inv(); }
inline modint<MOD> operator /= (modint<MOD> other) { return *this *= other.inv(); }
inline bool operator == (modint<MOD> other) const { return value == other.value; }
inline bool operator != (modint<MOD> other) const { return value != other.value; }
inline bool operator < (modint<MOD> other) const { return value < other.value; }
inline bool operator > (modint<MOD> other) const { return value > other.value; }
};
template <int32_t MOD> modint<MOD> operator * (int64_t value, modint<MOD> n) { return modint<MOD>(value) * n; }
template <int32_t MOD> modint<MOD> operator * (int32_t value, modint<MOD> n) { return modint<MOD>(value % MOD) * n; }
template <int32_t MOD> istream & operator >> (istream & in, modint<MOD> &n) { return in >> n.value; }
template <int32_t MOD> ostream & operator << (ostream & out, modint<MOD> n) { return out << n.value; }
using mint = modint<mod>;
vector<mint> BerlekampMassey(vector<mint> S) {
int n = (int)S.size(), L = 0, m = 0;
vector<mint> C(n), B(n), T;
C[0] = B[0] = 1;
mint b = 1;
for(int i = 0; i < n; i++) {
++m; mint d = S[i];
for(int j = 1; j <= L; j++) d += C[j] * S[i - j];
if (d == 0) continue;
T = C; mint coef = d * b.inv();
for(int j = m; j < n; j++) C[j] -= coef * B[j - m];
if (2 * L > i) continue;
L = i + 1 - L; B = T; b = d; m = 0;
}
C.resize(L + 1); C.erase(C.begin());
for(auto &x: C) x *= -1;
return C;
}
// a[k] = c[0] * a[k - 1] + c[1] * a[k - 2] + ... for k >= n
mint yo(vector<mint> a, vector<mint> c) {
int n = a.size();
if (!n) return 0;
vector<mint> p(n + 1, 0);
p[0] = 1;
for (int i = 0; i < n; i++) {
p[i + 1] = -c[i];
}
vector<mint> up(n + n, 0);
for (int i = 0; i < n; i++) {
for (int j = 0; j <= n; j++) {
up[i + j] += a[i] * p[j];
}
}
up.resize(n);
// generating function of the recurrence is up / p
// now find its derivative and find the value at x = 1
mint v = 0;
for (int i = 0; i < p.size(); i++) {
v += p[i];
}
mint u = 0;
for (int i = 0; i < up.size(); i++) {
u += up[i];
}
mint du = 0;
for (int i = 0; i < up.size(); i++) {
du += up[i] * i;
}
mint dv = 0;
for (int i = 0; i < p.size(); i++) {
dv += p[i] * i;
}
return (v * du - u * dv) / (v * v);
}
mint dp[N * 2][N];
vector<int> g[N];
int deg[N];
mint ideg[N];
int32_t main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n; cin >> n;
for (int i = 1; i <= n; i++) {
int x, y; cin >> x >> y;
}
int m; cin >> m;
while (m--) {
int u, v; cin >> u >> v;
g[u].push_back(v);
g[v].push_back(u);
++deg[u]; ++deg[v];
}
for (int i = 1; i <= n; i++) {
ideg[i] = mint(deg[i]).inv();
}
dp[0][1] = 1;
for (int k = 1; k <= n * 2; k++) {
for (int u = 1; u <= n; u++) {
if (u == n) continue;
for (auto v: g[u]) {
dp[k][v] += dp[k - 1][u] * ideg[u];
}
}
}
vector<mint> cur;
for (int i = 0; i <= 2 * n; i++) {
cur.push_back(dp[i][n]);
}
auto tr = BerlekampMassey(cur);
cur.resize(tr.size());
cout << yo(cur, tr) << '\n';
return 0;
}
// https://codeforces.com/gym/102268/problem/E | 35.963235 | 172 | 0.512983 | bazzyadb |
4634737aca597d284dca13cf9574464bab7dc1ff | 20 | cpp | C++ | src/Game/zScript.cpp | DarkRTA/bfbbdecomp | e2105e94b8da26f6e6e2dfcf1f004aaaeed9799e | [
"OLDAP-2.7"
] | null | null | null | src/Game/zScript.cpp | DarkRTA/bfbbdecomp | e2105e94b8da26f6e6e2dfcf1f004aaaeed9799e | [
"OLDAP-2.7"
] | 6 | 2022-01-16T05:29:01.000Z | 2022-01-18T01:10:29.000Z | src/Game/zScript.cpp | DarkRTA/bfbbdecomp | e2105e94b8da26f6e6e2dfcf1f004aaaeed9799e | [
"OLDAP-2.7"
] | 1 | 2022-01-16T00:04:23.000Z | 2022-01-16T00:04:23.000Z | #include "zScript.h" | 20 | 20 | 0.75 | DarkRTA |
463b70decfcf756e76dc1f4d982ab90ff08f6feb | 9,097 | cpp | C++ | src/daemon/process/AppProcess.cpp | FrederickHou/app-mesh | 8f23a1555d3a8da1481d91e1e60464fc197bd6e5 | [
"MIT"
] | null | null | null | src/daemon/process/AppProcess.cpp | FrederickHou/app-mesh | 8f23a1555d3a8da1481d91e1e60464fc197bd6e5 | [
"MIT"
] | null | null | null | src/daemon/process/AppProcess.cpp | FrederickHou/app-mesh | 8f23a1555d3a8da1481d91e1e60464fc197bd6e5 | [
"MIT"
] | 1 | 2020-11-01T09:11:49.000Z | 2020-11-01T09:11:49.000Z | #include <thread>
#include <fstream>
#include "AppProcess.h"
#include "LinuxCgroup.h"
#include "../Configuration.h"
#include "../ResourceLimitation.h"
#include "../../common/Utility.h"
#include "../../common/DateTime.h"
#include "../../common/os/pstree.hpp"
#define CLOSE_ACE_HANDLER(handler) \
do \
{ \
if (handler != ACE_INVALID_HANDLE) \
{ \
ACE_OS::close(handler); \
handler = ACE_INVALID_HANDLE; \
} \
} while (false)
AppProcess::AppProcess()
: m_killTimerId(0), m_stdinHandler(ACE_INVALID_HANDLE), m_stdoutHandler(ACE_INVALID_HANDLE), m_uuid(Utility::createUUID())
{
}
AppProcess::~AppProcess()
{
if (this->running())
{
killgroup();
}
CLOSE_ACE_HANDLER(m_stdoutHandler);
CLOSE_ACE_HANDLER(m_stdinHandler);
if (m_stdinFileName.length() && Utility::isFileExist(m_stdinFileName))
{
Utility::removeFile(m_stdinFileName);
}
if (m_stdoutReadStream && m_stdoutReadStream->is_open())
{
m_stdoutReadStream->close();
}
this->close_dup_handles();
this->close_passed_handles();
}
void AppProcess::attach(int pid)
{
this->child_id_ = pid;
}
void AppProcess::detach()
{
attach(ACE_INVALID_PID);
}
pid_t AppProcess::getpid(void) const
{
return ACE_Process::getpid();
}
void AppProcess::killgroup(int timerId)
{
const static char fname[] = "AppProcess::killgroup() ";
LOG_INF << fname << "kill process <" << getpid() << ">.";
if (timerId == 0)
{
// killed before timer event, cancel timer event
this->cancelTimer(m_killTimerId);
}
if (m_killTimerId > 0 && m_killTimerId == timerId)
{
// clean timer id, trigger-ing this time.
m_killTimerId = 0;
}
if (this->running() && this->getpid() > 1)
{
ACE_OS::kill(-(this->getpid()), 9);
this->terminate();
if (this->wait() < 0 && errno != 10) // 10 is ECHILD:No child processes
{
//avoid zombie process (Interrupted system call)
LOG_WAR << fname << "Wait process <" << getpid() << "> to exit failed with error : " << std::strerror(errno);
std::this_thread::sleep_for(std::chrono::milliseconds(100));
if (this->wait() < 0)
{
LOG_ERR << fname << "Retry wait process <" << getpid() << "> failed with error : " << std::strerror(errno);
}
else
{
LOG_INF << fname << "Retry wait process <" << getpid() << "> success";
}
}
}
}
void AppProcess::setCgroup(std::shared_ptr<ResourceLimitation> &limit)
{
// https://blog.csdn.net/u011547375/article/details/9851455
if (limit != nullptr)
{
m_cgroup = std::make_unique<LinuxCgroup>(limit->m_memoryMb, limit->m_memoryVirtMb - limit->m_memoryMb, limit->m_cpuShares);
m_cgroup->setCgroup(limit->m_name, getpid(), ++(limit->m_index));
}
}
const std::string AppProcess::getuuid() const
{
return m_uuid;
}
void AppProcess::regKillTimer(std::size_t timeout, const std::string from)
{
m_killTimerId = this->registerTimer(1000L * timeout, 0, std::bind(&AppProcess::killgroup, this, std::placeholders::_1), from);
}
// tuple: 1 cmdRoot, 2 parameters
std::tuple<std::string, std::string> AppProcess::extractCommand(const std::string &cmd)
{
std::unique_ptr<char[]> buff(new char[cmd.length() + 1]);
// find the string at the first blank not in a quote, quotes are removed
std::size_t idxSrc = 0, idxDst = 0;
bool isInQuote = false;
while (cmd[idxSrc] != '\0')
{
if (cmd[idxSrc] == ' ' && !isInQuote)
{
break;
}
else if (cmd[idxSrc] == '\"')
{
isInQuote = isInQuote ^ true;
}
else
{
buff[idxDst++] = cmd[idxSrc];
}
idxSrc++;
}
buff[idxDst] = '\0';
// remaining string are the parameters
std::string params = cmd.substr(idxSrc);
std::string cmdroot = buff.get();
return std::tuple<std::string, std::string>(params, cmdroot);
}
int AppProcess::spawnProcess(std::string cmd, std::string user, std::string workDir, std::map<std::string, std::string> envMap, std::shared_ptr<ResourceLimitation> limit, const std::string &stdoutFile, const std::string &stdinFileContent)
{
const static char fname[] = "AppProcess::spawnProcess() ";
int pid = -1;
// check command file existence & permission
auto cmdRoot = std::get<1>(extractCommand(cmd));
bool checkCmd = true;
if (cmdRoot.rfind('/') == std::string::npos && cmdRoot.rfind('\\') == std::string::npos)
{
checkCmd = false;
}
if (checkCmd && !Utility::isFileExist(cmdRoot))
{
LOG_WAR << fname << "command file <" << cmdRoot << "> does not exist";
startError(Utility::stringFormat("command file <%s> does not exist", cmdRoot.c_str()));
return ACE_INVALID_PID;
}
if (checkCmd && ACE_OS::access(cmdRoot.c_str(), X_OK) != 0)
{
LOG_WAR << fname << "command file <" << cmdRoot << "> does not have execution permission";
startError(Utility::stringFormat("command file <%s> does not have execution permission", cmdRoot.c_str()));
return ACE_INVALID_PID;
}
envMap[ENV_APP_MANAGER_LAUNCH_TIME] = DateTime::formatLocalTime(std::chrono::system_clock::now(), DATE_TIME_FORMAT);
std::size_t cmdLength = cmd.length() + ACE_Process_Options::DEFAULT_COMMAND_LINE_BUF_LEN;
int totalEnvSize = 0;
int totalEnvArgs = 0;
Utility::getEnvironmentSize(envMap, totalEnvSize, totalEnvArgs);
ACE_Process_Options option(1, cmdLength, totalEnvSize, totalEnvArgs);
option.command_line("%s", cmd.c_str());
//option.avoid_zombies(1);
if (user.empty())
user = Configuration::instance()->getDefaultExecUser();
if (user != "root")
{
unsigned int gid, uid;
if (Utility::getUid(user, uid, gid))
{
option.seteuid(uid);
option.setruid(uid);
option.setegid(gid);
option.setrgid(gid);
}
else
{
startError(Utility::stringFormat("user <%s> does not exist", user.c_str()));
return ACE_INVALID_PID;
}
}
option.setgroup(0); // set group id with the process id, used to kill process group
option.inherit_environment(true);
option.handle_inheritance(0);
if (workDir.length())
{
option.working_directory(workDir.c_str());
}
else
{
option.working_directory(Configuration::instance()->getDefaultWorkDir().c_str()); // set default working dir
}
std::for_each(envMap.begin(), envMap.end(), [&option](const std::pair<std::string, std::string> &pair) {
option.setenv(pair.first.c_str(), "%s", pair.second.c_str());
LOG_DBG << "spawnProcess env: " << pair.first.c_str() << "=" << pair.second.c_str();
});
option.release_handles();
// clean if necessary
CLOSE_ACE_HANDLER(m_stdoutHandler);
CLOSE_ACE_HANDLER(m_stdinHandler);
ACE_HANDLE dummy = ACE_INVALID_HANDLE;
m_stdoutFileName = stdoutFile;
if (stdoutFile.length() || stdinFileContent.length())
{
dummy = ACE_OS::open("/dev/null", O_RDWR);
m_stdoutHandler = m_stdinHandler = dummy;
if (stdoutFile.length())
{
m_stdoutHandler = ACE_OS::open(stdoutFile.c_str(), O_CREAT | O_WRONLY | O_APPEND | O_TRUNC);
LOG_DBG << "std_out: " << stdoutFile;
}
if (stdinFileContent.length() && stdinFileContent != JSON_KEY_APP_CLOUD_APP)
{
m_stdinFileName = Utility::stringFormat("appmesh.%s.stdin", m_uuid.c_str());
std::ofstream inputFile(m_stdinFileName, std::ios::trunc);
inputFile << stdinFileContent;
inputFile.close();
assert(Utility::isFileExist(m_stdinFileName));
m_stdinHandler = ACE_OS::open(m_stdinFileName.c_str(), O_RDONLY);
LOG_DBG << "std_in: " << m_stdinFileName << " : " << stdinFileContent;
}
option.set_handles(m_stdinHandler, m_stdoutHandler, m_stdoutHandler);
}
// do not inherit LD_LIBRARY_PATH to child
static const std::string ldEnv = ACE_OS::getenv("LD_LIBRARY_PATH") ? ACE_OS::getenv("LD_LIBRARY_PATH") : "";
if (!ldEnv.empty())
{
std::string env = ldEnv;
env = Utility::stringReplace(env, "/opt/appmesh/lib64:", "");
env = Utility::stringReplace(env, ":/opt/appmesh/lib64", "");
option.setenv("LD_LIBRARY_PATH", "%s", env.c_str());
}
if (this->spawn(option) >= 0)
{
pid = this->getpid();
LOG_INF << fname << "Process <" << cmd << "> started with pid <" << pid << ">.";
this->setCgroup(limit);
}
else
{
pid = -1;
LOG_ERR << fname << "Process:<" << cmd << "> start failed with error : " << std::strerror(errno);
startError(Utility::stringFormat("start failed with error <%s>", std::strerror(errno)));
}
if (dummy != ACE_INVALID_HANDLE)
ACE_OS::close(dummy);
return pid;
}
std::string AppProcess::fetchOutputMsg()
{
std::lock_guard<std::recursive_mutex> guard(m_outFileMutex);
if (m_stdoutReadStream == nullptr)
m_stdoutReadStream = std::make_shared<std::ifstream>(m_stdoutFileName, ios::in);
if (m_stdoutReadStream->is_open() && m_stdoutReadStream->good())
{
std::stringstream buffer;
buffer << m_stdoutReadStream->rdbuf();
return std::move(buffer.str());
}
return std::string();
}
std::string AppProcess::fetchLine()
{
char buffer[512] = {0};
std::lock_guard<std::recursive_mutex> guard(m_outFileMutex);
if (m_stdoutReadStream == nullptr)
m_stdoutReadStream = std::make_shared<std::ifstream>(m_stdoutFileName, ios::in);
if (m_stdoutReadStream->is_open() && m_stdoutReadStream->good())
{
m_stdoutReadStream->getline(buffer, sizeof(buffer));
}
return buffer;
}
| 30.62963 | 238 | 0.67165 | FrederickHou |
463ed1f546940c56ba4ee677e916d5a1b61dab89 | 7,947 | cpp | C++ | tests/src/percent_input_tests.cpp | DmitryDzz/calculator-comrade-lib | 107930ef7df88b330b800993028b35d08d5d78f6 | [
"MIT"
] | 4 | 2021-01-18T03:11:14.000Z | 2022-01-29T09:17:06.000Z | tests/src/percent_input_tests.cpp | DmitryDzz/calculator-comrade-lib | 107930ef7df88b330b800993028b35d08d5d78f6 | [
"MIT"
] | 32 | 2018-10-11T22:05:14.000Z | 2019-05-26T16:25:38.000Z | tests/src/percent_input_tests.cpp | DmitryDzz/calculator-comrade-lib | 107930ef7df88b330b800993028b35d08d5d78f6 | [
"MIT"
] | null | null | null | /**
* Calculator Comrade Library
* License: https://github.com/DmitryDzz/calculator-comrade-lib/blob/master/LICENSE
* Author: Dmitry Dzakhov
* Email: [email protected]
*/
#include <gmock/gmock.h>
#include "calculator/calculator.h"
#include "calculator/button.h"
#include "calculator/operation.h"
#include "calc_helper.h"
using namespace calculatorcomrade;
#define TEST_PERCENT(test_name) TEST(PercentOperations, test_name)
TEST_PERCENT(NoOperation) {
Calculator c(8);
Register &x = c.getX();
c.input(Button::d5);
c.input(Button::percent);
ASSERT_EQ(5, getIntValue(x));
}
TEST_PERCENT(AddPercent) {
Calculator c(8);
Register &x = c.getX();
c.input(Button::ca);
c.input(Button::d2);
c.input(Button::d0);
c.input(Button::d0);
c.input(Button::plus);
c.input(Button::d5);
c.input(Button::percent);
ASSERT_EQ(210, getIntValue(x));
c.input(Button::percent);
ASSERT_EQ(210, getIntValue(x));
c.input(Button::equals);
ASSERT_EQ(410, getIntValue(x));
c.input(Button::ca);
c.input(Button::minus);
c.input(Button::d2);
c.input(Button::d0);
c.input(Button::d0);
c.input(Button::plus);
c.input(Button::d5);
c.input(Button::percent);
ASSERT_EQ(-210, getIntValue(x));
c.input(Button::percent);
ASSERT_EQ(-210, getIntValue(x));
c.input(Button::equals);
ASSERT_EQ(-410, getIntValue(x));
c.input(Button::ca);
c.input(Button::d2);
c.input(Button::d0);
c.input(Button::d0);
c.input(Button::plus);
c.input(Button::d5);
c.input(Button::changeSign);
c.input(Button::percent);
ASSERT_EQ(190, getIntValue(x));
c.input(Button::percent);
ASSERT_EQ(190, getIntValue(x));
c.input(Button::equals);
ASSERT_EQ(-10, getIntValue(x));
c.input(Button::ca);
c.input(Button::minus);
c.input(Button::d2);
c.input(Button::d0);
c.input(Button::d0);
c.input(Button::plus);
c.input(Button::d5);
c.input(Button::changeSign);
c.input(Button::percent);
ASSERT_EQ(-190, getIntValue(x));
c.input(Button::percent);
ASSERT_EQ(-190, getIntValue(x));
c.input(Button::equals);
ASSERT_EQ(10, getIntValue(x));
}
TEST_PERCENT(SubPercent) {
Calculator c(8);
Register &x = c.getX();
c.input(Button::ca);
c.input(Button::d2);
c.input(Button::d0);
c.input(Button::d0);
c.input(Button::minus);
c.input(Button::d5);
c.input(Button::percent);
ASSERT_EQ(190, getIntValue(x));
c.input(Button::percent);
ASSERT_EQ(190, getIntValue(x));
c.input(Button::equals);
ASSERT_EQ(-10, getIntValue(x));
c.input(Button::ca);
c.input(Button::minus);
c.input(Button::d2);
c.input(Button::d0);
c.input(Button::d0);
c.input(Button::minus);
c.input(Button::d5);
c.input(Button::percent);
ASSERT_EQ(-190, getIntValue(x));
c.input(Button::percent);
ASSERT_EQ(-190, getIntValue(x));
c.input(Button::equals);
ASSERT_EQ(10, getIntValue(x));
c.input(Button::ca);
c.input(Button::d2);
c.input(Button::d0);
c.input(Button::d0);
c.input(Button::minus);
c.input(Button::d5);
c.input(Button::changeSign);
c.input(Button::percent);
ASSERT_EQ(210, getIntValue(x));
c.input(Button::percent);
ASSERT_EQ(210, getIntValue(x));
c.input(Button::equals);
ASSERT_EQ(410, getIntValue(x));
c.input(Button::ca);
c.input(Button::minus);
c.input(Button::d2);
c.input(Button::d0);
c.input(Button::d0);
c.input(Button::minus);
c.input(Button::d5);
c.input(Button::changeSign);
c.input(Button::percent);
ASSERT_EQ(-210, getIntValue(x));
c.input(Button::percent);
ASSERT_EQ(-210, getIntValue(x));
c.input(Button::equals);
ASSERT_EQ(-410, getIntValue(x));
}
TEST_PERCENT(MulPercent) {
Calculator c(8);
Register &x = c.getX();
Register &y = c.getY();
c.input(Button::ca);
c.input(Button::d2);
c.input(Button::d0);
c.input(Button::d0);
c.input(Button::mul);
c.input(Button::d5);
c.input(Button::percent);
ASSERT_EQ(10, getIntValue(x));
ASSERT_EQ(200, getIntValue(y));
c.input(Button::percent);
ASSERT_EQ(20, getIntValue(x));
ASSERT_EQ(200, getIntValue(y));
c.input(Button::equals);
ASSERT_EQ(4000, getIntValue(x));
ASSERT_EQ(200, getIntValue(y));
c.input(Button::ca);
c.input(Button::minus);
c.input(Button::d2);
c.input(Button::d0);
c.input(Button::d0);
c.input(Button::mul);
c.input(Button::d5);
c.input(Button::percent);
ASSERT_EQ(-10, getIntValue(x));
ASSERT_EQ(-200, getIntValue(y));
c.input(Button::percent);
ASSERT_EQ(20, getIntValue(x));
ASSERT_EQ(-200, getIntValue(y));
c.input(Button::equals);
ASSERT_EQ(-4000, getIntValue(x));
ASSERT_EQ(-200, getIntValue(y));
c.input(Button::ca);
c.input(Button::d2);
c.input(Button::d0);
c.input(Button::d0);
c.input(Button::mul);
c.input(Button::d5);
c.input(Button::changeSign);
c.input(Button::percent);
ASSERT_EQ(-10, getIntValue(x));
ASSERT_EQ(200, getIntValue(y));
c.input(Button::percent);
ASSERT_EQ(-20, getIntValue(x));
ASSERT_EQ(200, getIntValue(y));
c.input(Button::equals);
ASSERT_EQ(-4000, getIntValue(x));
ASSERT_EQ(200, getIntValue(y));
c.input(Button::ca);
c.input(Button::minus);
c.input(Button::d2);
c.input(Button::d0);
c.input(Button::d0);
c.input(Button::mul);
c.input(Button::d5);
c.input(Button::changeSign);
c.input(Button::percent);
ASSERT_EQ(10, getIntValue(x));
ASSERT_EQ(-200, getIntValue(y));
c.input(Button::percent);
ASSERT_EQ(-20, getIntValue(x));
ASSERT_EQ(-200, getIntValue(y));
c.input(Button::equals);
ASSERT_EQ(4000, getIntValue(x));
ASSERT_EQ(-200, getIntValue(y));
}
TEST_PERCENT(DivPercent1) {
Calculator c(8);
Register &x = c.getX();
Register &y = c.getY();
c.input(Button::ca);
c.input(Button::d2);
c.input(Button::d0);
c.input(Button::d0);
c.input(Button::div);
c.input(Button::d5);
c.input(Button::percent);
ASSERT_EQ(4000, getIntValue(x));
ASSERT_EQ(5, getIntValue(y));
c.input(Button::percent);
ASSERT_EQ(80000, getIntValue(x));
ASSERT_EQ(5, getIntValue(y));
c.input(Button::equals);
ASSERT_EQ(16000, getIntValue(x));
ASSERT_EQ(5, getIntValue(y));
c.input(Button::ca);
c.input(Button::d2);
c.input(Button::d0);
c.input(Button::d0);
c.input(Button::div);
c.input(Button::d5);
c.input(Button::changeSign);
c.input(Button::percent);
ASSERT_EQ(-4000, getIntValue(x));
ASSERT_EQ(-5, getIntValue(y));
c.input(Button::percent);
ASSERT_EQ(80000, getIntValue(x));
ASSERT_EQ(-5, getIntValue(y));
c.input(Button::equals);
ASSERT_EQ(-16000, getIntValue(x));
ASSERT_EQ(-5, getIntValue(y));
c.input(Button::ca);
c.input(Button::minus);
c.input(Button::d2);
c.input(Button::d0);
c.input(Button::d0);
c.input(Button::div);
c.input(Button::d5);
c.input(Button::percent);
ASSERT_EQ(-4000, getIntValue(x));
ASSERT_EQ(5, getIntValue(y));
c.input(Button::percent);
ASSERT_EQ(-80000, getIntValue(x));
ASSERT_EQ(5, getIntValue(y));
c.input(Button::equals);
ASSERT_EQ(-16000, getIntValue(x));
ASSERT_EQ(5, getIntValue(y));
c.input(Button::ca);
c.input(Button::minus);
c.input(Button::d2);
c.input(Button::d0);
c.input(Button::d0);
c.input(Button::div);
c.input(Button::d5);
c.input(Button::changeSign);
c.input(Button::percent);
ASSERT_EQ(4000, getIntValue(x));
ASSERT_EQ(-5, getIntValue(y));
c.input(Button::percent);
ASSERT_EQ(-80000, getIntValue(x));
ASSERT_EQ(-5, getIntValue(y));
c.input(Button::equals);
ASSERT_EQ(16000, getIntValue(x));
ASSERT_EQ(-5, getIntValue(y));
}
| 26.938983 | 83 | 0.623632 | DmitryDzz |
4643ab8154366f53cffbe193c750fd0a35c954a3 | 578 | cpp | C++ | barelymusician/dsp/one_pole_filter.cpp | anokta/barelymusician | 5e3485c80cc74c4bcbc0653c0eb8750ad44981d6 | [
"MIT"
] | 6 | 2021-11-25T17:40:21.000Z | 2022-03-24T03:38:11.000Z | barelymusician/dsp/one_pole_filter.cpp | anokta/barelymusician | 5e3485c80cc74c4bcbc0653c0eb8750ad44981d6 | [
"MIT"
] | 17 | 2021-11-27T00:10:39.000Z | 2022-03-30T00:33:51.000Z | barelymusician/dsp/one_pole_filter.cpp | anokta/barelymusician | 5e3485c80cc74c4bcbc0653c0eb8750ad44981d6 | [
"MIT"
] | null | null | null | #include "barelymusician/dsp/one_pole_filter.h"
#include <algorithm>
namespace barelyapi {
double OnePoleFilter::Next(double input) noexcept {
output_ = coefficient_ * (output_ - input) + input;
if (type_ == FilterType::kHighPass) {
return input - output_;
}
return output_;
}
void OnePoleFilter::Reset() noexcept { output_ = 0.0; }
void OnePoleFilter::SetCoefficient(double coefficient) noexcept {
coefficient_ = std::min(std::max(coefficient, 0.0), 1.0);
}
void OnePoleFilter::SetType(FilterType type) noexcept { type_ = type; }
} // namespace barelyapi
| 24.083333 | 71 | 0.719723 | anokta |
46498961a608ee3f3a53e462acc2ee7f0d39f35f | 415 | cpp | C++ | sursa.cpp | seerj30/backtracking-recursiv_permutari | 8ec7d75ed50305e68527d6dd74133910d9c35256 | [
"MIT"
] | null | null | null | sursa.cpp | seerj30/backtracking-recursiv_permutari | 8ec7d75ed50305e68527d6dd74133910d9c35256 | [
"MIT"
] | null | null | null | sursa.cpp | seerj30/backtracking-recursiv_permutari | 8ec7d75ed50305e68527d6dd74133910d9c35256 | [
"MIT"
] | null | null | null | #include<iostream>
using namespace std;
int n;
void back(int st[], int k)
{
int i,ev,j;
if(k==n+1)
{
for(int i = 1; i < k; i++)
cout << st[i] << " ";
cout << endl;
}
else
for(int i = 1; i <= n; i++)
{
st[k] = i;
ev=1;
for(j = 1; j < k; j++)
if(st[j] == st[k])
ev=0;
if(ev)
back(st, k+1);
}
}
int main()
{
int st[50];
cout << "n="; cin >> n;
back(st, 1);
return 0;
}
| 12.205882 | 29 | 0.436145 | seerj30 |
464a3aeedf7fb4a9e26ce09eb1d2a829735d1f65 | 1,829 | hh | C++ | test/CLI/AppTest.hh | decouple/decouple.io | c841e905fbc8bd9507759a0ef6e56e1985c56c5a | [
"MIT"
] | null | null | null | test/CLI/AppTest.hh | decouple/decouple.io | c841e905fbc8bd9507759a0ef6e56e1985c56c5a | [
"MIT"
] | null | null | null | test/CLI/AppTest.hh | decouple/decouple.io | c841e905fbc8bd9507759a0ef6e56e1985c56c5a | [
"MIT"
] | null | null | null | <?hh // partial
namespace Test\CLI;
use Decouple\CLI\App;
use Decouple\CLI\Request\Request;
use Decouple\Decoupler\Decoupler;
use Decouple\Registry\Paths;
use Decouple\CLI\Console;
class AppTest extends \Decouple\Test\TestCase {
public function execute() : void {
Console::output('Testing CLI bootstrap (version)');
$this->testBootstrapA();
Console::output('Testing CLI bootstrap (FooCommand)');
$this->testBootstrapB();
Console::output('Testing CLI bootstrap (BarCommand)');
$this->testBootstrapC();
}
public function testBootstrapA() : void {
$app = $this->__bootstrap("decouple:version");
$result = $this->capture($app);
$this->assertEquals($result, "Decouple v0.1a\n");
Console::output('Passed');
}
public function testBootstrapB() : void {
$app = $this->__bootstrap("foo:bar");
$result = $this->capture($app);
$this->assertEquals($result, "FooBar!\n");
Console::output('Passed');
}
public function testBootstrapC() : void {
$app = $this->__bootstrap("bar:baz --bar=wtf!");
$result = $this->capture($app);
$this->assertEquals($result, "bar:wtf!\n");
Console::output('Passed');
}
public function __bootstrap(string $args) : App {
$args = stristr($args, ' ') ? new Vector(explode(' ', $args)) : Vector { $args };
$request = new Request($args);
$services = Map {"Decouple\\CLI\\Request\Request" => $request};
$decoupler = new Decoupler($services);
$app = new App($request, $decoupler, new Paths(Map {
}), Vector {
"Test\CLI\Fixture\FooCommand",
"Test\CLI\Fixture\BarCommand"
});
return $app;
}
public function capture(App $app) : string {
ob_start();
try {
$app->execute();
} catch(Exception $e) {
echo $e->getMessage();
}
return ob_get_clean();
}
}
| 29.031746 | 85 | 0.631493 | decouple |
464b77d844ad0b1b829a3053a1afbc119a63c6ad | 4,139 | cpp | C++ | cha1/max_subarray.cpp | byzhou/CLRS | 1af11fc971b9b91a050cdb1f2b3cf9a9471c8a22 | [
"MIT"
] | null | null | null | cha1/max_subarray.cpp | byzhou/CLRS | 1af11fc971b9b91a050cdb1f2b3cf9a9471c8a22 | [
"MIT"
] | null | null | null | cha1/max_subarray.cpp | byzhou/CLRS | 1af11fc971b9b91a050cdb1f2b3cf9a9471c8a22 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstdlib>
#include <ctime>
#include <time.h>
#include <stdio.h>
using namespace std;
const int neg_infinity = 0xFFFFFFFF ;
const int pos_infinity = 0x7FFFFFFF ;
void print_array ( int* array , int num ) ;
void diff_array ( int* array, int* diff_array ) ;
void max_cross_subarray ( int* array , int& left , int mid , int& right ) ;
struct left_right {
int left ;
int right ;
int sum ;
};
/* For a given array, this function print out the array's
* elements.
*/
void print_array ( int* array , int num ) {
printf ( "Below is the the array: \n " ) ;
for ( int i = 0 ; i < num ; i ++ ) {
printf ( "%d \t", array[i] ) ;
}
printf ( "\n " ) ;
}
/* This function will take the diff between two elements of an
* array.
*/
void diff_array ( int* array , int* diff_array ) {
if ( (array + 1) == NULL )
printf ( " This array has too less elements. \n " ) ;
for ( int i = 0 ; (array + i + 1) != NULL ; i ++ )
diff_array[i] = array[i+1] - array[i];
}
struct left_right max_cross_subarray ( int* array , int left , int mid , int right ) {
int left_sum = neg_infinity ;
int right_sum = neg_infinity ;
int sum = 0 ;
int i = 0 ;
int return_left = 0 ;
int return_right= 0 ;
struct left_right tmp;
if (left == mid || mid == right || left == right)
return 0;
for ( i = mid ; i > left ; i -- ) {
sum += array[i] ;
if ( sum > left_sum )
left_sum = sum ;
return_left = i ;
}
tmp.left = return_left ;
for ( i = mid ; i < right ; i ++ ) {
sum += array[i] ;
if ( sum > right_sum )
right_sum = sum ;
return_right = i ;
}
tmp.right = return_right ;
tmp.sum = left_sum + right_sum ;
return tmp;
}
struct left_right max_subarray ( int* array , int left , int right ) {
int left_sum = neg_infinity ;
int right_sum = neg_infinity ;
int mid_sum = neg_infinity ;
int mid = (left + right) / 2 ;
struct left_rigth tmp ;
tmp.left = left ;
tmp.right = right ;
tmp.sum = array[left] ;
if (left == right)
return tmp ;
else {
left_sum = max_subarray ( array , left , mid ) . sum ;
right_sum = max_subarray ( array , mid , right ) . sum ;
mid_sum = max_cross_subarray ( array , left , mid , right ) . sum ;
if ( ( left_sum >= right_sum ) && ( left_sum >= mid_sum ) )
return max_subarray ( array , left , mid ) ;
if ( ( right_sum >= left_sum ) && ( right_sum >= mid_sum ) )
return max_subarray ( array , mid , right ) ;
if ( ( mid_sum >= left_sum ) && ( mid_sum >= right_sum ) )
return max_cross_subarray ( array , left , mid , right ) ;
}
}
int main(){
struct left_right = tmp ;
//length of the array
const int num = 3;
//random generator seed
srand(time(0));
//time generation
clock_t t;
int array[num*num];
int i,j;
//record start time
t = clock();
for ( i = 0; i < num; i++ ) {
for ( j = 0; j < num; j ++ ) {
array[i * num + j] = rand() / 1000000 ;
printf( "array %d value is %d \n", i*num + j, array[i * num + j] ) ;
}
}
printf( "The time spent on the array generation is: %4.2f \n", (float)( clock() - t) / CLOCKS_PER_SEC ) ;
long double key;
//record start time
tmp = max_subarray(array , 0 , num * num - 1 ) ;
print_array ( array + tmp.left, , tmp.right - tmp.left + 1 ) ;
//record end time
printf( "The time spent on the array sorting is: %4.2f \n", (float)( clock() - t) / CLOCKS_PER_SEC );
cout<<"The array has been sorted."<<endl;
//print the sorted array
/*
for ( i = 0; i < num; i++ ) {
for ( j = 0 ; j < num ; j++ ) {
printf( "array %d value is %d \n", i * num + j , array[i * num + j] ) ;
}
}
*/
return 0;
}
| 28.349315 | 113 | 0.512926 | byzhou |
465470dd4d63504759a42fd83d03389631e1900b | 10,971 | cpp | C++ | solver/modules/slide/src/StraightSolver.cpp | taiheioki/procon2014_ut | 8199ff0a54220f1a0c51acece377f65b64db4863 | [
"MIT"
] | 2 | 2021-04-14T06:41:18.000Z | 2021-04-29T01:56:08.000Z | solver/modules/slide/src/StraightSolver.cpp | taiheioki/procon2014_ut | 8199ff0a54220f1a0c51acece377f65b64db4863 | [
"MIT"
] | null | null | null | solver/modules/slide/src/StraightSolver.cpp | taiheioki/procon2014_ut | 8199ff0a54220f1a0c51acece377f65b64db4863 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <functional>
#include <limits>
#include <boost/format.hpp>
#include "StraightSolver.hpp"
namespace slide
{
void StraightSolver::alignRow(AnswerBoard<Flexible>& board)
{
BOOST_ASSERT(board.height() >= 3 && board.width() >= 2);
// 右端2個以外
rep(dstX, board.width()-2){
const Point dst(board.height()-1, dstX);
const Point src = board.find(board.correctId(dst));
// 既に大丈夫だった
if(src == dst){
continue;
}
if(dst.x == src.x){
if(dst.x <= board.selected.x){
moveTargetPiece(board, src, dst, 0, dst.x, board.height(), board.width()-dst.x);
}
else{
moveTargetPiece(board, src, dst + Point(-1, 0), 0, 0, board.height()-1, board.width());
board.moveVertically(dst.y - 2);
board.moveHorizontally(dst.x);
board.moveRight();
board.moveDown();
board.moveDown();
board.moveLeft();
board.moveUp();
}
}
else if(dst.x < src.x){
if(board.selected.x < dst.x){
board.moveHorizontally(dst.x);
}
moveTargetPiece(board, src, dst, 0, dst.x, board.height(), board.width()-dst.x);
}
else{
if(dst.x < board.selected.x){
board.moveHorizontally(dst.x);
}
if(board.selected.y == dst.y){
board.moveUp();
}
moveTargetPiece(board, src, dst + Point(-1, 0), 0, 0, board.height(), dst.x+1);
// src と dst は絶対に同じにならない
if(board.selected.x == dst.x - 1){
board.moveUp();
board.moveRight();
}
board.moveRight();
board.moveDown();
board.moveDown();
board.moveLeft();
board.moveUp();
}
}
if(board.isAligned(board.height()-1, board.width()-1)){
const uchar pieceId = board.correctId(board.height()-1, board.width()-2);
if(board(board.height()-1, board.width()-2) == pieceId){
return;
}
else if(board(board.height()-2, board.width()-2) == pieceId && board.selected == Point(board.height()-1, board.width()-2)){
board.moveUp();
return;
}
}
// 最後の二つ目
{
const uchar pieceId = board.correctId(board.height()-1, board.width()-2);
const Point src = board.find(pieceId);
const Point dst(board.height()-1, board.width()-1);
if(src == dst);
else if(src.y == dst.y){
board.moveHorizontally(board.width() - 1);
board.moveVertically(board.height() - 1);
board.moveLeft();
}
else if(board.selected.y == dst.y && board.width()-2 <= src.x){
moveTargetPiece(board, src, dst, 0, board.width()-2, board.height(), 2);
}
else{
if(board.selected.y == dst.y){
board.moveUp();
}
moveTargetPiece(board, src, Point(dst.y-1, dst.x), 0, 0, board.height()-1, board.width());
board.moveHorizontally(board.width() - 2);
board.moveVertically(board.height() - 1);
board.moveRight();
board.moveUp();
}
}
// ラス1
{
const uchar pieceId = board.correctId(board.height()-1, board.width()-1);
if(board.selected.y == board.height()-1 && board(board.height()-2, board.width()-2) != pieceId){
board.moveUp();
}
if(board.selected.y != board.height()-1 && board(board.height()-1, board.width()-2) != pieceId){
const Point src = board.find(pieceId);
const Point dst(board.height()-2, board.width()-1);
moveTargetPiece(board, src, dst, 0, 0, board.height()-1, board.width());
board.moveHorizontally(board.width() - 2);
board.moveVertically(board.height() - 1);
board.moveRight();
board.moveUp();
}
else if(board.width() >= 3){
board.moveHorizontally(board.width() - 2);
board.moveVertically(board.height() - 1);
board.moveRight();
board.moveUp();
board.moveLeft();
board.moveLeft();
board.moveDown();
board.moveRight();
board.moveRight();
board.moveUp();
board.moveLeft();
board.moveDown();
board.moveLeft();
board.moveUp();
}
else{
board.moveHorizontally(0);
board.moveVertically(board.height() - 1);
board.moveRight();
board.moveUp();
board.moveLeft();
board.moveUp();
board.moveRight();
board.moveDown();
board.moveDown();
board.moveLeft();
board.moveUp();
board.moveRight();
board.moveUp();
board.moveLeft();
board.moveDown();
board.moveDown();
board.moveRight();
board.moveUp();
}
}
}
void StraightSolver::moveTargetPiece(AnswerBoard<Flexible>& board, Point src, Point dst, int y, int x, int height, int width)
{
BOOST_ASSERT(src.isIn(y, x, height, width));
BOOST_ASSERT(dst.isIn(y, x, height, width));
BOOST_ASSERT(board.selected.isIn(y, x, height, width));
BOOST_ASSERT(0 <= y && y+height <= board.height() && 0 <= x && x+width <= board.width());
BOOST_ASSERT(height >= 2 && width >= 2);
BOOST_ASSERT(src != board.selected);
// 既に大丈夫だった
if(src == dst){
return;
}
const uchar pieceId = board(src);
const Point sel = board.selected;
// src に隣接する有効なセルを列挙
Direction dir = Direction::Up;
Point adj = Point(-1, -1);
int minDist = std::numeric_limits<int>::max();
// for each directions
rep(k, 4){
const Direction nowdir = Direction(k);
if(dst.y >= src.y && nowdir == Direction::Up) continue;
if(dst.y <= src.y && nowdir == Direction::Down) continue;
if(dst.x >= src.x && nowdir == Direction::Left) continue;
if(dst.x <= src.x && nowdir == Direction::Right) continue;
const Point nowadj = src + Point::delta(nowdir);
if(!nowadj.isIn(y, x, height, width)){
continue;
}
const int dist = (nowadj - sel).l1norm();
if(dist < minDist){
dir = nowdir;
adj = nowadj;
minDist = dist;
}
}
BOOST_ASSERT(adj.y >= 0);
// 月蝕判定
const bool eclipseY = (sel.y <= src.y && src.y < adj.y) || (adj.y < src.y && src.y <= sel.y);
const bool eclipseX = (sel.x <= src.x && src.x < adj.x) || (adj.x < src.x && src.x <= sel.x);
// 月蝕の位置で一直線に並んでいるケース
// the special case
if(sel.x == src.x && src.x == adj.x && eclipseY){
sel.x == x ? board.moveRight() : board.moveLeft();
}
else if(sel.y == src.y && src.y == adj.y && eclipseX){
sel.y == y ? board.moveDown() : board.moveUp();
}
// 月蝕の位置の方向から移動
if(eclipseY){
board.moveVertically(adj.y);
board.moveHorizontally(adj.x);
}
else{
board.moveHorizontally(adj.x);
board.moveVertically(adj.y);
}
// move target
for(;;){
board.move(dir.opposite());
if(board(dst) == pieceId){
break;
}
switch(dir){
case Direction::Up:
if(board.selected.x == dst.x){
dst.x == x ? board.moveRight() : board.moveLeft();
board.moveUp();
board.moveUp();
dst.x == x ? board.moveLeft() : board.moveRight();
}
else if(board.selected.x < dst.x){
board.moveRight();
board.moveUp();
dir = Direction::Right;
}
else{
board.moveLeft();
board.moveUp();
dir = Direction::Left;
}
break;
case Direction::Right:
if(board.selected.y == dst.y){
dst.y == y ? board.moveDown() : board.moveUp();
board.moveRight();
board.moveRight();
dst.y == y ? board.moveUp() : board.moveDown();
}
else if(board.selected.y < dst.y){
board.moveDown();
board.moveRight();
dir = Direction::Down;
}
else{
board.moveUp();
board.moveRight();
dir = Direction::Up;
}
break;
case Direction::Down:
if(board.selected.x == dst.x){
dst.x == x ? board.moveRight() : board.moveLeft();
board.moveDown();
board.moveDown();
dst.x == x ? board.moveLeft() : board.moveRight();
}
else if(board.selected.x > dst.x){
board.moveLeft();
board.moveDown();
dir = Direction::Left;
}
else{
board.moveRight();
board.moveDown();
dir = Direction::Right;
}
break;
case Direction::Left:
if(board.selected.y == dst.y){
dst.y == y ? board.moveDown() : board.moveUp();
board.moveLeft();
board.moveLeft();
dst.y == y ? board.moveUp() : board.moveDown();
}
else if(board.selected.y < dst.y){
board.moveDown();
board.moveLeft();
dir = Direction::Down;
}
else{
board.moveUp();
board.moveLeft();
dir = Direction::Up;
}
break;
}
}
}
void StraightSolver::align2x2(AnswerBoard<Flexible>& board)
{
BOOST_ASSERT(board.selected.isIn(2, 2));
board.moveVertically(0);
board.moveHorizontally(0);
const uchar id = board.correctId(0, 1);
if(board(1, 0) == id){
board.moveDown();
board.moveRight();
board.moveUp();
board.moveLeft();
}
else if(board(1, 1) == id){
board.moveRight();
board.moveDown();
board.moveLeft();
board.moveUp();
}
if(!board.isAligned(1, 0)){
board.select(1, 0);
board.moveRight();
}
}
AnswerBoard<Flexible> StraightSolver::cropTo(
const AnswerBoard<Flexible>& src, int y, int x, int height, int width, Direction topSide, bool yflip, bool xflip)
{
Board<Flexible> dst(topSide.isUpOrDown() ? height : width, topSide.isUpOrDown() ? width : height);
rep(i, height) rep(j, width){
uchar id = src(i+y, j+x);
id = Point(id).rotateFlip(topSide, yflip, xflip, height, width).toInt();
dst(Point(i, j).rotateFlip(topSide, yflip, xflip, height, width)) = id;
}
AnswerBoard<Flexible> answerBoard(dst);
answerBoard.selected = (src.selected - Point(y, x)).rotateFlip(topSide, yflip, xflip, height, width);
return answerBoard;
}
void StraightSolver::restore(
const AnswerBoard<Flexible>& src, AnswerBoard<Flexible>& dst, int y, int x, Direction topSide, bool yflip, bool xflip)
{
const Direction preTopSide = topSide;
topSide = topSide.isRightOrLeft() ? topSide.opposite() : topSide;
rep(i, src.height()) rep(j, src.width()){
uchar id = src(i, j);
id = (Point(id).rotateFlip(topSide, yflip, xflip, src.height(), src.width()) + Point(y, x)).toInt();
dst.at(Point(i, j).rotateFlip(topSide, yflip, xflip, src.height(), src.width()) + Point(y, x)) = id;
}
dst.selected = src.selected.rotateFlip(topSide, yflip, xflip, src.height(), src.width()) + Point(y, x);
// answer の restore
for(const Move& move : src.answer){
if(move.isSelection){
dst.answer.emplace_back(move.getSelected().rotateFlip(topSide, yflip, xflip, src.height(), src.width()) + Point(y, x));
}
else{
Direction dir = move.getDirection();
if(yflip && dir.isUpOrDown()) dir = dir.opposite();
if(xflip && dir.isRightOrLeft()) dir = dir.opposite();
dst.answer.emplace_back(dir + preTopSide);
}
}
}
void StraightSolver::solve()
{
// initialize AnswerBoard
AnswerBoard<Flexible> board(problem.board);
board.select(board.find(board.correctId(0, 0)));
// continue rearrangement until the remaining region is larger than 2x2
int remH = board.height();
int remW = board.width();
while(remH > 2 || remW > 2){
const bool isRow = remH >= remW;
if(isRow){
AnswerBoard<Flexible> tmp = cropTo(board, 0, 0, remH, remW, Direction::Up, false, false);
alignRow(tmp);
restore(tmp, board, 0, 0, Direction::Up, false, false);
--remH;
}
else{
AnswerBoard<Flexible> tmp = cropTo(board, 0, 0, remH, remW, Direction::Left, false, false);
alignRow(tmp);
restore(tmp, board, 0, 0, Direction::Left, false, false);
--remW;
}
}
align2x2(board);
board.answer.optimize();
onCreatedAnswer(board.answer);
std::cout << "move_count = " << board.answer.size() << std::endl;
}
} // end of namespace slide
| 25.753521 | 125 | 0.627199 | taiheioki |
4654c53aeb35a7c4dbdd747d4f61e5dd3ced6dd0 | 3,332 | hpp | C++ | alpaka/include/alpaka/block/shared/dyn/BlockSharedMemDynUniformCudaHipBuiltIn.hpp | alpaka-group/mallocMC | ddba224b764885f816c42a7719551b14e6f5752b | [
"MIT"
] | 6 | 2021-02-01T09:01:39.000Z | 2021-11-14T17:09:03.000Z | alpaka/include/alpaka/block/shared/dyn/BlockSharedMemDynUniformCudaHipBuiltIn.hpp | alpaka-group/mallocMC | ddba224b764885f816c42a7719551b14e6f5752b | [
"MIT"
] | 17 | 2020-11-09T14:13:50.000Z | 2021-11-03T11:54:54.000Z | alpaka/include/alpaka/block/shared/dyn/BlockSharedMemDynUniformCudaHipBuiltIn.hpp | alpaka-group/mallocMC | ddba224b764885f816c42a7719551b14e6f5752b | [
"MIT"
] | null | null | null | /* Copyright 2019 Benjamin Worpitz, René Widera
*
* This file is part of alpaka.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#pragma once
#if defined(ALPAKA_ACC_GPU_CUDA_ENABLED) || defined(ALPAKA_ACC_GPU_HIP_ENABLED)
# include <alpaka/core/BoostPredef.hpp>
# if defined(ALPAKA_ACC_GPU_CUDA_ENABLED) && !BOOST_LANG_CUDA
# error If ALPAKA_ACC_GPU_CUDA_ENABLED is set, the compiler has to support CUDA!
# endif
# if defined(ALPAKA_ACC_GPU_HIP_ENABLED) && !BOOST_LANG_HIP
# error If ALPAKA_ACC_GPU_HIP_ENABLED is set, the compiler has to support HIP!
# endif
# include <alpaka/block/shared/dyn/Traits.hpp>
# include <type_traits>
namespace alpaka
{
//#############################################################################
//! The GPU CUDA/HIP block shared memory allocator.
class BlockSharedMemDynUniformCudaHipBuiltIn
: public concepts::Implements<ConceptBlockSharedDyn, BlockSharedMemDynUniformCudaHipBuiltIn>
{
public:
//-----------------------------------------------------------------------------
BlockSharedMemDynUniformCudaHipBuiltIn() = default;
//-----------------------------------------------------------------------------
__device__ BlockSharedMemDynUniformCudaHipBuiltIn(BlockSharedMemDynUniformCudaHipBuiltIn const&) = delete;
//-----------------------------------------------------------------------------
__device__ BlockSharedMemDynUniformCudaHipBuiltIn(BlockSharedMemDynUniformCudaHipBuiltIn&&) = delete;
//-----------------------------------------------------------------------------
__device__ auto operator=(BlockSharedMemDynUniformCudaHipBuiltIn const&)
-> BlockSharedMemDynUniformCudaHipBuiltIn& = delete;
//-----------------------------------------------------------------------------
__device__ auto operator=(BlockSharedMemDynUniformCudaHipBuiltIn&&)
-> BlockSharedMemDynUniformCudaHipBuiltIn& = delete;
//-----------------------------------------------------------------------------
/*virtual*/ ~BlockSharedMemDynUniformCudaHipBuiltIn() = default;
};
namespace traits
{
//#############################################################################
template<typename T>
struct GetDynSharedMem<T, BlockSharedMemDynUniformCudaHipBuiltIn>
{
//-----------------------------------------------------------------------------
__device__ static auto getMem(BlockSharedMemDynUniformCudaHipBuiltIn const&) -> T*
{
// Because unaligned access to variables is not allowed in device code,
// we have to use the widest possible type to have all types aligned correctly.
// See: http://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#shared
// http://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#vector-types
extern __shared__ float4 shMem[];
return reinterpret_cast<T*>(shMem);
}
};
} // namespace traits
} // namespace alpaka
#endif
| 45.643836 | 114 | 0.536315 | alpaka-group |
465af3690db8e7e38b86005371afe4aa42b6cc8b | 556 | cpp | C++ | test/filter.cpp | ericjavier/yaml | 92d9097fc58602fbc88000fd22e2debc2f90996c | [
"Apache-2.0"
] | 1 | 2015-04-12T19:46:13.000Z | 2015-04-12T19:46:13.000Z | test/filter.cpp | ericjavier/yaml | 92d9097fc58602fbc88000fd22e2debc2f90996c | [
"Apache-2.0"
] | null | null | null | test/filter.cpp | ericjavier/yaml | 92d9097fc58602fbc88000fd22e2debc2f90996c | [
"Apache-2.0"
] | null | null | null | #include <gtest/gtest.h>
#include <yaml/config.hpp>
#include <yaml/detail/placeholders.hpp>
#include <yaml/arithmetic.hpp>
#include <yaml/sequence/filter.hpp>
#include "test_utils.hpp"
using namespace YAML_NSP;
using func = less::ret<_0, std::integral_constant<int, 3>>;
using expected = list<std::integral_constant<int, 0>,
std::integral_constant<int, 1>,
std::integral_constant<int, 2 >>;
TEST(filter, seq) {
expect_same_seq<expected, filter::ret<func, seq3>>();
}
TEST(filter, list) {
expect_same_seq<expected, filter::ret<func, lst3>>();
} | 25.272727 | 59 | 0.723022 | ericjavier |
465eb68fb7072790e82f6c3db5f23dbfb93e7340 | 4,148 | cpp | C++ | Linked list/LinkedListStruct.cpp | lovinh/Data-Structure | f5dab728b809507b8b15eb8f8450a6a85f95467e | [
"MIT"
] | null | null | null | Linked list/LinkedListStruct.cpp | lovinh/Data-Structure | f5dab728b809507b8b15eb8f8450a6a85f95467e | [
"MIT"
] | null | null | null | Linked list/LinkedListStruct.cpp | lovinh/Data-Structure | f5dab728b809507b8b15eb8f8450a6a85f95467e | [
"MIT"
] | null | null | null | #ifndef __LinkedListStruct_cpp
#define __LinkedListStruct_cpp
#include <iostream>
template <class T>
struct sNode // struct node
{
T data;
sNode<T> *next;
};
// Insert
template <class T>
void push_front(sNode<T> **head, const T &data)
{
sNode<T> *node = new sNode<T>;
node->data = data;
node->next = *head;
*head = node;
}
template <class T>
void push_back(sNode<T> **head, const T &data)
{
sNode<T> *nNode = new sNode<T>();
nNode->data = data;
nNode->next = NULL;
if (*head == NULL)
{
*head = nNode;
}
else
{
sNode<T> *it; // iterator
it = *head;
while (it->next != NULL)
{
it = it->next;
}
it->next = nNode;
}
}
template <class T>
void insert(sNode<T> **head, const T &data, size_t index)
{
if (index == 0)
{
push_front(head, data);
return;
}
size_t size_list = size(*head);
if (index > size_list)
{
push_back(head, data);
return;
}
sNode<T> *nNode = new sNode<T>();
nNode->data = data;
sNode<T> *it = *head;
for (size_t i = 0; i < index - 1; i++)
{
it = it->next;
}
nNode->next = it->next;
it->next = nNode;
}
// delete node
template <class T>
void pop_front(sNode<T> **head)
{
if (empty(*head))
{
return;
}
size_t lSize = size(*head);
if (lSize == 1)
{
sNode<T> *dNode = *head;
(*head) = NULL;
delete dNode;
}
else
{
sNode<T> *dNode = *head;
(*head) = dNode->next;
delete dNode;
}
}
template <class T>
void pop_back(sNode<T> **head)
{
if (empty(*head))
{
return;
}
size_t lSize = size(*head);
if (lSize == 1)
{
sNode<T> *dNode = *head;
(*head) = NULL;
delete dNode;
}
else
{
sNode<T> *dNode = *head;
for (int i = 0; i < lSize - 2; i++)
{
dNode = dNode->next;
}
sNode<T> *dNode2 = dNode->next;
dNode->next = NULL;
delete dNode2;
}
}
template <class T>
void erase(sNode<T> **head, size_t index)
{
if (empty(*head))
{
return;
}
size_t len = size(*head);
if (index >= len)
{
return;
}
else
{
if (index == 0)
pop_front(head);
else if (index == len - 1)
pop_back(head);
else
{
sNode<T> *dNode = *head;
for (int i = 0; i < index - 1; i++)
{
dNode = dNode->next;
}
sNode<T> *dNode2 = dNode->next;
dNode->next = dNode2->next;
delete dNode2;
}
}
}
// capacity
template <class T>
size_t size(sNode<T> *head)
{
size_t count = 0;
while (head->next != NULL)
{
count++;
head = head->next;
}
return count + 1;
}
template <class T>
bool empty(sNode<T> *head)
{
return (head == NULL);
}
// Access
template <class T>
T &front(sNode<T> *head)
{
return head->data;
}
template <class T>
T &back(sNode<T> *head)
{
sNode<T> *it = head;
while (it->next != NULL)
{
it = it->next;
}
return it->data;
}
// Reverse a linked list
template <class T>
void Reverse(sNode<T> **head)
{
sNode<T> *previous, *current, *next;
previous = NULL;
current = *head;
while (current != NULL)
{
next = current->next;
current->next = previous;
previous = current;
current = next;
}
*head = previous;
}
// In list
template <class T>
void printList(sNode<T> *head)
{
if (empty(head))
{
std::cout << "list is empty";
}
else
{
sNode<T> *it = head; // iterator
std::cout << "List is ";
while (it != NULL)
{
std::cout << it->data << " ";
it = it->next;
}
std::cout << "\t" << size(head);
}
std::cout << std::endl;
}
template <class T>
void Print(sNode<T> *head)
{
if (head == NULL)
return;
std ::cout << head->data << " ";
Print(head->next);
}
#endif | 18.435556 | 57 | 0.478303 | lovinh |
46642a3737950cf666a252806f317be9196ca388 | 1,864 | cpp | C++ | c++/Data Structures/RMQ.cpp | WearyJunger/notebook | 8fc7bfdcacffd63b131b5ed0c92365f682ba313f | [
"MIT"
] | null | null | null | c++/Data Structures/RMQ.cpp | WearyJunger/notebook | 8fc7bfdcacffd63b131b5ed0c92365f682ba313f | [
"MIT"
] | null | null | null | c++/Data Structures/RMQ.cpp | WearyJunger/notebook | 8fc7bfdcacffd63b131b5ed0c92365f682ba313f | [
"MIT"
] | 1 | 2018-10-08T21:01:59.000Z | 2018-10-08T21:01:59.000Z | Range minimum query. Recibe como parametro en el constructor un array de valores. Las consultas se realizan con el método rmq(indice_inicio, indice_final) y pueden actualizarse los valores con update_point(indice, nuevo_valor)
class SegmentTree {
private: vector<int> st, A;
int n;
int left (int p) { return p << 1; }
int right(int p) { return (p << 1) + 1; }
void build(int p, int L, int R) {
if (L == R)
st[p] = L;
else {
build(left(p) , L, (L + R) / 2);
build(right(p), (L + R) / 2 + 1, R);
int p1 = st[left(p)], p2 = st[right(p)];
st[p] = (A[p1] <= A[p2]) ? p1 : p2;
}
}
int rmq(int p, int L, int R, int i, int j) {
if (i > R || j < L) return -1;
if (L >= i && R <= j) return st[p];
int p1 = rmq(left(p) , L, (L+R) / 2, i, j);
int p2 = rmq(right(p), (L+R) / 2 + 1, R, i, j);
if (p1 == -1) return p2;
if (p2 == -1) return p1;
return (A[p1] <= A[p2]) ? p1 : p2; }
int update_point(int p, int L, int R, int idx, int new_value) {
int i = idx, j = idx;
if (i > R || j < L)
return st[p];
if (L == i && R == j) {
A[i] = new_value;
return st[p] = L;
}
int p1, p2;
p1 = update_point(left(p) , L, (L + R) / 2, idx, new_value);
p2 = update_point(right(p), (L + R) / 2 + 1, R, idx, new_value);
return st[p] = (A[p1] <= A[p2]) ? p1 : p2;
}
public:
SegmentTree(const vector<int> &_A) {
A = _A; n = (int)A.size();
st.assign(4 * n, 0);
build(1, 0, n - 1);
}
int rmq(int i, int j) { return rmq(1, 0, n - 1, i, j); }
int update_point(int idx, int new_value) {
return update_point(1, 0, n - 1, idx, new_value); }
};
int main() {
int arr[] = { 18, 17, 13, 19, 15, 11, 20 };
vector<int> A(arr, arr + 7);
SegmentTree st(A);
return 0;
}
| 28.242424 | 226 | 0.495708 | WearyJunger |
466f649cd8398e7deb5c21a4cf7fc57bbcff1ba5 | 1,025 | cpp | C++ | Lab 4/Lab 4/Lab 4.cpp | shonwr/c-assignments-projects | fab40807ba2720cec577aa9689361746e33ef678 | [
"Apache-2.0"
] | null | null | null | Lab 4/Lab 4/Lab 4.cpp | shonwr/c-assignments-projects | fab40807ba2720cec577aa9689361746e33ef678 | [
"Apache-2.0"
] | null | null | null | Lab 4/Lab 4/Lab 4.cpp | shonwr/c-assignments-projects | fab40807ba2720cec577aa9689361746e33ef678 | [
"Apache-2.0"
] | null | null | null | // Lab 4.cpp : main project file.
#include "stdafx.h"
#include <iostream>
using namespace System;
using namespace std;
char fName[50];
char lName[50];
char space[10] = " ";
int main()
{
system("color f0");
printf("This program: \n\t(1)Prints an entered first and last name \n\t(2)Prints the number of letters in each name on the following line.\n\n");
printf("Press enter to begin: ");
scanf("%c");
printf("\n\nEnter first name: ");
scanf("%s",fName);
printf("\nEnter last name: ");
scanf("%s",lName);
//Aligned @ end
printf("\n\nYou enterered: %s %s \n",fName,lName);
int fLength = (strlen(fName));
int lLength = (strlen(lName));
int fSpaceEnd = (strlen(fName)-2);
int lSpaceEnd = (strlen(lName)-1);
printf(" %*s %d", "%*s\n\n",fSpaceEnd,space,fLength,lSpaceEnd,space,lLength);
//Aligned @ beginning
printf("\n\nYou enterered: %s %s \n",fName,lName);
int fSpace = (strlen(fName)-2);
printf(" %d %-*s %d\n\n",fLength,fSpace,space,lLength);
system("pause");
return 0;
}
| 26.973684 | 146 | 0.636098 | shonwr |
4671ec7a3b1a40d24223e8bfc1ef09540e1dc440 | 1,784 | cpp | C++ | DivisionEngine/DivisionTest/ClockTest.cpp | martheveldhuis/DivisionEngine | 8f7ba1c355ee010c005df207e08d51673f3cdf8d | [
"MIT"
] | 1 | 2017-11-29T19:19:43.000Z | 2017-11-29T19:19:43.000Z | DivisionEngine/DivisionTest/ClockTest.cpp | martheveldhuis/DivisionEngine | 8f7ba1c355ee010c005df207e08d51673f3cdf8d | [
"MIT"
] | 2 | 2018-01-16T12:11:24.000Z | 2018-01-16T15:21:46.000Z | DivisionEngine/DivisionTest/ClockTest.cpp | martheveldhuis/DivisionEngine | 8f7ba1c355ee010c005df207e08d51673f3cdf8d | [
"MIT"
] | 1 | 2018-01-28T13:10:49.000Z | 2018-01-28T13:10:49.000Z | #include "CppUnitTest.h"
#include "Clock.h"
#include <chrono>
#include <thread>
#include <iostream>
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace Division;
namespace DivisionTest
{
TEST_CLASS(ClockTest)
{
public:
TEST_METHOD(testClockStart)
{
Clock clock;
clock.start();
Assert::IsTrue(clock.isRunning());
}
TEST_METHOD(testClockPoll)
{
Clock clock;
clock.start();
// Sleep for 1000 ms.
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
// Retrieve the time that has past.
int timePast = clock.poll();
// Check if the time is between a certain timespan.
// Usually the past time will be 1001 ms. For cpu-threading
// priority delay occasions we will allow for a 5ms delay.
int isBetween = 1000 <= timePast && timePast < 1050;
Assert::IsTrue(isBetween);
}
TEST_METHOD(testClockStop)
{
Clock clock;
clock.start();
clock.stop();
Assert::IsFalse(clock.isRunning());
}
TEST_METHOD(testClockRuntime)
{
Clock clock;
clock.start();
// Sleep for 500 ms.
std::this_thread::sleep_for(std::chrono::milliseconds(500));
clock.stop();
std::this_thread::sleep_for(std::chrono::milliseconds(500));
clock.start();
// Sleep for 500 ms.
std::this_thread::sleep_for(std::chrono::milliseconds(500));
clock.stop();
int timePast = clock.getRuntime();
int isBetween = 1000 <= timePast && timePast < 1050;
Assert::IsTrue(isBetween);
}
TEST_METHOD(testClockReset)
{
Clock clock;
clock.start();
// Sleep for 500 ms.
std::this_thread::sleep_for(std::chrono::milliseconds(500));
clock.stop();
clock.reset();
int timePast = clock.getRuntime();
Assert::AreEqual(0, timePast);
}
};
} | 16.830189 | 64 | 0.663117 | martheveldhuis |
467a5110cc99dab334a99239e0b6d2733962ca4c | 21 | cc | C++ | src/main/c++/novemberizing/io/buffer.cc | iticworld/reactive-lib | 9ab761376776e759390fa417d50921ec6e8a898a | [
"Apache-2.0"
] | 1 | 2020-10-10T11:57:15.000Z | 2020-10-10T11:57:15.000Z | src/main/c++/novemberizing/io/buffer.cc | iticworld/reactive-lib | 9ab761376776e759390fa417d50921ec6e8a898a | [
"Apache-2.0"
] | null | null | null | src/main/c++/novemberizing/io/buffer.cc | iticworld/reactive-lib | 9ab761376776e759390fa417d50921ec6e8a898a | [
"Apache-2.0"
] | null | null | null | #include "buffer.hh"
| 10.5 | 20 | 0.714286 | iticworld |
467adea4e2f3af676246adae4073c1f4877d720e | 75 | hxx | C++ | src/drawable.hxx | luutifa/openglpractice | 1158453f0b124910ad8c4101f226dd55b5ce4262 | [
"MIT"
] | null | null | null | src/drawable.hxx | luutifa/openglpractice | 1158453f0b124910ad8c4101f226dd55b5ce4262 | [
"MIT"
] | null | null | null | src/drawable.hxx | luutifa/openglpractice | 1158453f0b124910ad8c4101f226dd55b5ce4262 | [
"MIT"
] | null | null | null | #pragma once
class Drawable {
public:
virtual void draw() const;
};
| 10.714286 | 30 | 0.653333 | luutifa |
46823dbdade1cbfdbfe418a0c45b44216ff606cf | 14,456 | cpp | C++ | push1st-server/core/lua/clua.cpp | navek-soft/push1st | 6d0638e31031dcf55442382df0e92ac67d95801b | [
"Apache-2.0"
] | 16 | 2021-11-02T07:29:18.000Z | 2021-12-23T13:28:05.000Z | push1st-server/core/lua/clua.cpp | navek-soft/push1st | 6d0638e31031dcf55442382df0e92ac67d95801b | [
"Apache-2.0"
] | null | null | null | push1st-server/core/lua/clua.cpp | navek-soft/push1st | 6d0638e31031dcf55442382df0e92ac67d95801b | [
"Apache-2.0"
] | null | null | null | #include "clua.h"
#include <unordered_map>
#include <set>
#include <deque>
#include <functional>
#include <ctime>
#define l L.get()
void* clua::engine::getModule(clua::lua_t L, const std::string_view& modName, const std::string_view& modNamespace) {
if (lua_getglobal(L, modNamespace.data()); lua_istable(L, -1)) {
if (lua_getfield(L, -1, modName.data()); lua_istable(L, -1)) {
lua_getfield(L, -1, "__self");
if (lua_islightuserdata(L, -1)) {
return (void*)lua_touserdata(L, -1);
}
}
}
return nullptr;
}
ssize_t clua::engine::luaRegisterModule(lua_t L, std::initializer_list<std::pair<std::string_view, lua_CFunction>>& methods, void* modClassSelf, const std::string_view& modName, const std::string_view& modNamespace) {
if (!modNamespace.empty()) {
lua_getglobal(L, modNamespace.data());
if (/*auto nfn = lua_gettop(L); */lua_isnil(L, -1)) {
lua_newtable(L);
//lua_pushstring(L, modNamespace.c_str());
//lua_setfield(L, -2, "__namespace");
lua_setglobal(L, modNamespace.data());
}
if (lua_getglobal(L, modNamespace.data()); lua_istable(L, -1)) {
lua_pushstring(L, modName.data());
{
lua_newtable(L);
lua_pushlightuserdata(L, modClassSelf);
lua_setfield(L, -2, "__self");
for (auto&& [mn, mfn] : methods) {
lua_pushcfunction(L, mfn);
lua_setfield(L, -2, mn.data());
}
lua_settable(L, -3);
}
}
}
else {
lua_newtable(L);
lua_pushlightuserdata(L, modClassSelf);
lua_setfield(L, -2, "__self");
for (auto&& [mn, mfn] : methods) {
lua_pushcfunction(L, mfn);
lua_setfield(L, -2, mn.data());
}
lua_setglobal(L, modName.data());
}
return 0;
}
std::vector<std::any> clua::engine::luaExecute(const std::string& luaScript, const std::string& luaFunction, const std::vector<std::any>& luaArgs) {
std::vector<std::any> multiReturn;
if (auto&& L{ S() }; L) {
if (!luaScript.empty()) {
if (luaL_dofile(l, luaScript.c_str()) != 0) {
fprintf(stderr, "clua::execute(`%s`): %s\n", luaScript.c_str(), lua_tostring(l, -1));
lua_pop(l, 1);
return {};
}
}
if (!luaFunction.empty()) {
auto multi_return_top = lua_gettop(l);
try {
if (lua_getglobal(l, luaFunction.c_str()); lua_isfunction(l, -1)) {
for (auto&& v : luaArgs) { pushValue(l, v); }
if (lua_pcall(l, (int)luaArgs.size(), LUA_MULTRET, 0) == 0) {
if (int multi_return_count = lua_gettop(l) - multi_return_top; multi_return_count) {
multiReturn.reserve(multi_return_count);
for (; multi_return_count; --multi_return_count) {
if (lua_isinteger(l, -multi_return_count)) {
multiReturn.emplace_back(std::any{ ssize_t(lua_tointeger(l, -multi_return_count)) });
}
else if (lua_isboolean(l, -multi_return_count)) {
multiReturn.emplace_back(std::any{ bool(lua_toboolean(l, -multi_return_count)) });
}
else if (lua_isnil(l, -multi_return_count)) {
multiReturn.emplace_back(std::any{ nullptr });
}
else if (lua_isstring(l, -multi_return_count)) {
size_t ptr_len{ 0 };
if (auto ptr_str = lua_tolstring(l, -multi_return_count, &ptr_len); ptr_str && ptr_len) {
multiReturn.emplace_back(std::string{ ptr_str,ptr_str + ptr_len });
}
else {
multiReturn.emplace_back(std::string{ });
}
}
else if (lua_istable(l, -multi_return_count)) {
std::unordered_map<std::string, std::string> map;
auto ntop = lua_gettop(l);
lua_pushnil(l);
while (lua_next(l, -multi_return_count - 1)) {
if (lua_isnumber(l, -2)) {
map.emplace(std::to_string(lua_tointeger(l, -2)), lua_tostring(l, -1));
}
else if (lua_isstring(l, -2)) {
map.emplace(lua_tostring(l, -2), lua_tostring(l, -1));
}
lua_pop(l, 1);
}
multiReturn.emplace_back(map);
lua_settop(l, ntop);
}
}
}
}
else {
fprintf(stderr, "clua::execute(error running function `%s`): %s\n", luaFunction.c_str(), lua_tostring(l, -1));
return {};
}
}
else {
fprintf(stderr, "clua::execute(error running function `%s`): %s\n", luaFunction.c_str(), lua_tostring(l, -1));
return {};
}
lua_settop(l, multi_return_top);
}
catch (std::exception& ex) {
fprintf(stderr, "clua::exception(error running function `%s`): %s\n", luaFunction.c_str(), lua_tostring(l, -1));
}
}
}
else {
fprintf(stderr, "clua::execute(error script): %s\n", "invalid lua context (script is empty)");
}
return multiReturn;
}
void clua::engine::luaAddRelativePackagePath(lua_t L, const std::string& path) {
if (!path.empty()) {
std::string pPath;
if (path.front() != '/') {
pPath = packageBasePath + path;
}
else {
pPath = path;
}
packagePaths.emplace(pPath);
if (L) {
lua_getglobal(L, "package");
lua_getfield(L, -1, "path");
std::string cur_path{ lua_tostring(L, -1) };
cur_path.append(";" + pPath);
lua_pop(L, 1);
lua_pushstring(L, cur_path.c_str());
lua_setfield(L, -2, "path");
lua_pop(L, 1);
}
}
}
void clua::engine::luaAddPackagePath(const std::string& path) {
if (!path.empty()) {
if (path.back() == '/')
packagePaths.emplace(path + "?.lua");
else
packagePaths.emplace(path + "/?.lua");
}
}
void clua::engine::luaPackagePath(std::string& pathPackages) {
for (auto&& path : packagePaths) {
pathPackages.append(";" + path);
}
}
clua::engine::engine() {
}
clua::engine::~engine() {
}
clua::lua_ptr_t clua::engine::S() {
lua_ptr_t jitLua{ luaL_newstate(), [](lua_t L) {
lua_close(L);
} };
luaL_openlibs(jitLua.get());
/* adjust lua package.path */
{
lua_getglobal(jitLua.get(), "package");
lua_getfield(jitLua.get(), -1, "path");
std::string cur_path{ lua_tostring(jitLua.get(), -1) };
luaPackagePath(cur_path);
lua_pop(jitLua.get(), 1);
lua_pushstring(jitLua.get(), cur_path.c_str());
lua_setfield(jitLua.get(), -2, "path");
lua_pop(jitLua.get(), 1);
}
luaLoadModules(jitLua.get());
return jitLua;
}
namespace typecast {
static void push_value(clua::lua_t L, const std::any& val);
template<typename T>
void push_integer(clua::lua_t L, const std::any& val) { lua_pushinteger(L, std::any_cast<T>(val)); }
template<typename T>
void push_number(clua::lua_t L, const std::any& val) { lua_pushnumber(L, std::any_cast<T>(val)); }
void push_bool(clua::lua_t L, const std::any& val) { lua_pushboolean(L, std::any_cast<bool>(val)); }
void push_string(clua::lua_t L, const std::any& val) { lua_pushstring(L, std::any_cast<const char*>(val)); }
void push_cstring(clua::lua_t L, const std::any& val) { auto&& _v = std::any_cast<std::string>(val); lua_pushlstring(L, _v.data(), _v.length()); }
void push_vstring(clua::lua_t L, const std::any& val) { auto&& _v = std::any_cast<std::string_view>(val); lua_pushlstring(L, _v.data(), _v.length()); }
void push_rawdata(clua::lua_t L, const std::any& val) { auto&& _v = std::any_cast<std::vector<uint8_t>>(val); lua_pushlstring(L, (const char*)_v.data(), _v.size()); }
void push_nil(clua::lua_t L, const std::any& val) { lua_pushnil(L); }
void push_mapsa(clua::lua_t L, const std::any& val) {
lua_newtable(L);
if (!std::any_cast<std::unordered_map<std::string, std::any>>(val).empty()) {
for (auto&& [k, v] : std::any_cast<std::unordered_map<std::string, std::any>>(val)) {
lua_pushlstring(L, k.c_str(), k.length());
push_value(L, v);
lua_settable(L, -3);
}
}
}
void push_mapsva(clua::lua_t L, const std::any& val) {
lua_newtable(L);
if (!std::any_cast<std::unordered_map<std::string_view, std::any>>(val).empty()) {
for (auto&& [k, v] : std::any_cast<std::unordered_map<std::string_view, std::any>>(val)) {
lua_pushlstring(L, k.data(), k.size());
push_value(L, v);
lua_settable(L, -3);
}
}
}
void push_seta(clua::lua_t L, const std::any& val) {
lua_newtable(L);
if (!std::any_cast<std::set<std::any>>(val).empty()) {
int n = 1;
for (auto&& v : std::any_cast<std::set<std::any>>(val)) {
lua_pushinteger(L, n++);
push_value(L, (std::any&)v);
lua_settable(L, -3);
}
}
}
void push_deqa(clua::lua_t L, const std::any& val) {
lua_newtable(L);
if (!std::any_cast<std::deque<std::any>>(val).empty()) {
int n = 1;
for (auto&& v : std::any_cast<std::deque<std::any>>(val)) {
lua_pushinteger(L, n++);
push_value(L, (std::any&)v);
lua_settable(L, -3);
}
}
}
void push_deqsw(clua::lua_t L, const std::any& val) {
lua_newtable(L);
if (!std::any_cast<std::deque<std::string_view>>(val).empty()) {
int n = 1;
for (auto&& v : std::any_cast<std::deque<std::string_view>>(val)) {
lua_pushinteger(L, n++);
lua_pushlstring(L, v.data(), v.length());
lua_settable(L, -3);
}
}
}
void push_class_t(clua::lua_t L, const std::any& val) {
auto&& v{ std::any_cast<clua::class_t::self_t>(val) };
void** place = (void**)lua_newuserdata(L, sizeof(void*));
*place = v.selfObject;
lua_newtable(L);
lua_pushcfunction(L, clua::class_t::__index);
lua_setfield(L, -2, "__index");
lua_pushcfunction(L, clua::class_t::__tostring);
lua_setfield(L, -2, "__tostring");
lua_pushcfunction(L, clua::class_t::__gc);
lua_setfield(L, -2, "__gc");
lua_setmetatable(L, -2);
v.selfObject = nullptr; // now __gc can free resource
}
void push_veca(clua::lua_t L, const std::any& val) {
lua_newtable(L);
if (!std::any_cast<std::vector<std::any>>(val).empty()) {
int n = 1;
for (auto&& v : std::any_cast<std::vector<std::any>>(val)) {
lua_pushinteger(L, n++);
push_value(L, (std::any&)v);
lua_settable(L, -3);
}
}
}
static const std::unordered_map<size_t, std::function<void(clua::lua_t L, const std::any& val)>> PushTypecast{
{typeid(float).hash_code(),push_number<float>},
{typeid(double).hash_code(),push_number<double>},
{typeid(int).hash_code(),push_integer<int>},
{typeid(int16_t).hash_code(),push_integer<int16_t>},
{typeid(uint16_t).hash_code(),push_integer<uint16_t>},
{typeid(int32_t).hash_code(),push_integer<int32_t>},
{typeid(uint32_t).hash_code(),push_integer<uint32_t>},
{typeid(ssize_t).hash_code(),push_integer<ssize_t>},
{typeid(std::time_t).hash_code(),push_integer<std::time_t>},
{typeid(size_t).hash_code(),push_integer<size_t>},
{typeid(int64_t).hash_code(),push_integer<int64_t>},
{typeid(uint64_t).hash_code(),push_integer<uint64_t>},
{typeid(bool).hash_code(),push_bool},
{typeid(const char*).hash_code(),push_string},
{typeid(std::string).hash_code(),push_cstring},
{typeid(std::string_view).hash_code(),push_vstring},
{typeid(std::deque<std::any>).hash_code(),push_deqa},
{typeid(std::deque<std::string_view>).hash_code(),push_deqsw},
{typeid(std::vector<std::any>).hash_code(),push_veca},
{typeid(std::set<std::any>).hash_code(),push_seta},
{typeid(std::unordered_map<std::string,std::any>).hash_code(),push_mapsa},
{typeid(std::unordered_map<std::string_view,std::any>).hash_code(), push_mapsva},
{typeid(clua::class_t::self_t).hash_code(),push_class_t},
{typeid(nullptr).hash_code(),push_nil},
};
void push_value(clua::lua_t L, const std::any& val) {
if (val.has_value()) {
if (auto&& it = typecast::PushTypecast.find(val.type().hash_code()); it != typecast::PushTypecast.end()) {
it->second(L, val);
}
else {
fprintf(stderr, "clua::typecast(%s) no found\n", val.type().name());
}
}
else {
push_nil(L, { nullptr });
}
}
}
void clua::engine::pushValue(clua::lua_t L, const std::any& val) {
typecast::push_value(L, val);
}
| 41.185185 | 217 | 0.509408 | navek-soft |
46835ffc0fa55038a82c3e8f90cfff09dc4cb13e | 19,985 | cpp | C++ | src/game/server/hl1/hl1_npc_leech.cpp | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | 6 | 2022-01-23T09:40:33.000Z | 2022-03-20T20:53:25.000Z | src/game/server/hl1/hl1_npc_leech.cpp | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | null | null | null | src/game/server/hl1/hl1_npc_leech.cpp | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | 1 | 2022-02-06T21:05:23.000Z | 2022-02-06T21:05:23.000Z | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
#include "cbase.h"
#include "ai_default.h"
#include "ai_task.h"
#include "ai_schedule.h"
#include "ai_node.h"
#include "ai_hull.h"
#include "ai_hint.h"
#include "ai_memory.h"
#include "ai_route.h"
#include "ai_motor.h"
#include "soundent.h"
#include "game.h"
#include "npcevent.h"
#include "entitylist.h"
#include "activitylist.h"
#include "animation.h"
#include "basecombatweapon.h"
#include "IEffects.h"
#include "vstdlib/random.h"
#include "engine/IEngineSound.h"
#include "ammodef.h"
#include "hl1_ai_basenpc.h"
#include "ai_senses.h"
// Animation events
#define LEECH_AE_ATTACK 1
#define LEECH_AE_FLOP 2
//#define DEBUG_BEAMS 0
ConVar sk_leech_health("sk_leech_health", "2");
ConVar sk_leech_dmg_bite("sk_leech_dmg_bite", "2");
// Movement constants
#define LEECH_ACCELERATE 10
#define LEECH_CHECK_DIST 45
#define LEECH_SWIM_SPEED 50
#define LEECH_SWIM_ACCEL 80
#define LEECH_SWIM_DECEL 10
#define LEECH_TURN_RATE 70
#define LEECH_SIZEX 10
#define LEECH_FRAMETIME 0.1
class CNPC_Leech : public CHL1BaseNPC {
DECLARE_CLASS( CNPC_Leech, CHL1BaseNPC
);
public:
DECLARE_DATADESC();
void Spawn(void);
void Precache(void);
static const char *pAlertSounds[];
void SwimThink(void);
void DeadThink(void);
void SwitchLeechState(void);
float ObstacleDistance(CBaseEntity *pTarget);
void UpdateMotion(void);
void RecalculateWaterlevel(void);
void Touch(CBaseEntity *pOther);
Disposition_t IRelationType(CBaseEntity *pTarget);
void HandleAnimEvent(animevent_t *pEvent);
void AttackSound(void);
void AlertSound(void);
void Activate(void);
Class_T Classify(void) { return CLASS_INSECT; };
void Event_Killed(const CTakeDamageInfo &info);
bool ShouldGib(const CTakeDamageInfo &info);
/* // Base entity functions
void Killed( entvars_t *pevAttacker, int iGib );
int TakeDamage( entvars_t *pevInflictor, entvars_t *pevAttacker, float flDamage, int bitsDamageType );
*/
private:
// UNDONE: Remove unused boid vars, do group behavior
float m_flTurning;// is this boid turning?
bool m_fPathBlocked;// TRUE if there is an obstacle ahead
float m_flAccelerate;
float m_obstacle;
float m_top;
float m_bottom;
float m_height;
float m_waterTime;
float m_sideTime; // Timer to randomly check clearance on sides
float m_zTime;
float m_stateTime;
float m_attackSoundTime;
Vector m_oldOrigin;
};
LINK_ENTITY_TO_CLASS( monster_leech, CNPC_Leech
);
BEGIN_DATADESC( CNPC_Leech )
DEFINE_FIELD( m_flTurning, FIELD_FLOAT
),
DEFINE_FIELD( m_fPathBlocked, FIELD_BOOLEAN
),
DEFINE_FIELD( m_flAccelerate, FIELD_FLOAT
),
DEFINE_FIELD( m_obstacle, FIELD_FLOAT
),
DEFINE_FIELD( m_top, FIELD_FLOAT
),
DEFINE_FIELD( m_bottom, FIELD_FLOAT
),
DEFINE_FIELD( m_height, FIELD_FLOAT
),
DEFINE_FIELD( m_waterTime, FIELD_TIME
),
DEFINE_FIELD( m_sideTime, FIELD_TIME
),
DEFINE_FIELD( m_zTime, FIELD_TIME
),
DEFINE_FIELD( m_stateTime, FIELD_TIME
),
DEFINE_FIELD( m_attackSoundTime, FIELD_TIME
),
DEFINE_FIELD( m_oldOrigin, FIELD_VECTOR
),
DEFINE_THINKFUNC( SwimThink ),
DEFINE_THINKFUNC(DeadThink),
END_DATADESC()
bool CNPC_Leech::ShouldGib(const CTakeDamageInfo &info) {
return false;
}
void CNPC_Leech::Spawn(void) {
Precache();
SetModel("models/leech.mdl");
SetHullType(HULL_TINY_CENTERED);
SetHullSizeNormal();
UTIL_SetSize(this, Vector(-1, -1, 0), Vector(1, 1, 2));
Vector vecSurroundingMins(-8, -8, 0);
Vector vecSurroundingMaxs(8, 8, 2);
CollisionProp()->SetSurroundingBoundsType(USE_SPECIFIED_BOUNDS, &vecSurroundingMins, &vecSurroundingMaxs);
// Don't push the minz down too much or the water check will fail because this entity is really point-sized
SetSolid(SOLID_BBOX);
AddSolidFlags(FSOLID_NOT_STANDABLE);
SetMoveType(MOVETYPE_FLY);
AddFlag(FL_SWIM);
m_iHealth = sk_leech_health.GetInt();
m_flFieldOfView = -0.5; // 180 degree FOV
SetDistLook(750);
NPCInit();
SetThink(&CNPC_Leech::SwimThink);
SetUse(NULL);
SetTouch(NULL);
SetViewOffset(vec3_origin);
m_flTurning = 0;
m_fPathBlocked = FALSE;
SetActivity(ACT_SWIM);
SetState(NPC_STATE_IDLE);
m_stateTime = gpGlobals->curtime + random->RandomFloat(1, 5);
SetRenderColor(255, 255, 255, 255);
m_bloodColor = DONT_BLEED;
SetCollisionGroup(COLLISION_GROUP_DEBRIS);
}
void CNPC_Leech::Activate(void) {
RecalculateWaterlevel();
BaseClass::Activate();
}
void CNPC_Leech::DeadThink(void) {
if (IsSequenceFinished()) {
if (GetActivity() == ACT_DIEFORWARD) {
SetThink(NULL);
StopAnimation();
return;
} else if (GetFlags() & FL_ONGROUND) {
AddSolidFlags(FSOLID_NOT_SOLID);
SetActivity(ACT_DIEFORWARD);
}
}
StudioFrameAdvance();
SetNextThink(gpGlobals->curtime + 0.1);
// Apply damage velocity, but keep out of the walls
if (GetAbsVelocity().x != 0 || GetAbsVelocity().y != 0) {
trace_t tr;
// Look 0.5 seconds ahead
UTIL_TraceLine(GetLocalOrigin(), GetLocalOrigin() + GetAbsVelocity() * 0.5, MASK_SOLID, this,
COLLISION_GROUP_NONE, &tr);
if (tr.fraction != 1.0) {
Vector vVelocity = GetAbsVelocity();
vVelocity.x = 0;
vVelocity.y = 0;
SetAbsVelocity(vVelocity);
}
}
}
Disposition_t CNPC_Leech::IRelationType(CBaseEntity *pTarget) {
if (pTarget->IsPlayer())
return D_HT;
return BaseClass::IRelationType(pTarget);
}
void CNPC_Leech::Touch(CBaseEntity *pOther) {
if (!pOther->IsPlayer())
return;
if (pOther == GetTouchTrace().m_pEnt) {
if (pOther->GetAbsVelocity() == vec3_origin)
return;
SetBaseVelocity(pOther->GetAbsVelocity());
AddFlag(FL_BASEVELOCITY);
}
}
void CNPC_Leech::HandleAnimEvent(animevent_t *pEvent) {
CBaseEntity *pEnemy = GetEnemy();
switch (pEvent->event) {
case LEECH_AE_FLOP:
// Play flop sound
break;
case LEECH_AE_ATTACK:
AttackSound();
if (pEnemy != NULL) {
Vector dir, face;
AngleVectors(GetAbsAngles(), &face);
face.z = 0;
dir = (pEnemy->GetLocalOrigin() - GetLocalOrigin());
dir.z = 0;
VectorNormalize(dir);
VectorNormalize(face);
if (DotProduct(dir, face) > 0.9) // Only take damage if the leech is facing the prey
{
CTakeDamageInfo info(this, this, sk_leech_dmg_bite.GetInt(), DMG_SLASH);
CalculateMeleeDamageForce(&info, dir, pEnemy->GetAbsOrigin());
pEnemy->TakeDamage(info);
}
}
m_stateTime -= 2;
break;
default:
BaseClass::HandleAnimEvent(pEvent);
break;
}
}
void CNPC_Leech::Precache(void) {
PrecacheModel("models/leech.mdl");
PrecacheScriptSound("Leech.Attack");
PrecacheScriptSound("Leech.Alert");
}
void CNPC_Leech::AttackSound(void) {
if (gpGlobals->curtime > m_attackSoundTime) {
CPASAttenuationFilter filter(this);
EmitSound(filter, entindex(), "Leech.Attack");
m_attackSoundTime = gpGlobals->curtime + 0.5;
}
}
void CNPC_Leech::AlertSound(void) {
CPASAttenuationFilter filter(this);
EmitSound(filter, entindex(), "Leech.Alert");
}
void CNPC_Leech::SwitchLeechState(void) {
m_stateTime = gpGlobals->curtime + random->RandomFloat(3, 6);
if (m_NPCState == NPC_STATE_COMBAT) {
SetEnemy(NULL);
SetState(NPC_STATE_IDLE);
// We may be up against the player, so redo the side checks
m_sideTime = 0;
} else {
GetSenses()->Look(GetSenses()->GetDistLook());
CBaseEntity *pEnemy = BestEnemy();
if (pEnemy && pEnemy->GetWaterLevel() != 0) {
SetEnemy(pEnemy);
SetState(NPC_STATE_COMBAT);
m_stateTime = gpGlobals->curtime + random->RandomFloat(18, 25);
AlertSound();
}
}
}
void CNPC_Leech::RecalculateWaterlevel(void) {
// Calculate boundaries
Vector vecTest = GetLocalOrigin() - Vector(0, 0, 400);
trace_t tr;
UTIL_TraceLine(GetLocalOrigin(), vecTest, MASK_SOLID, this, COLLISION_GROUP_NONE, &tr);
if (tr.fraction != 1.0)
m_bottom = tr.endpos.z + 1;
else
m_bottom = vecTest.z;
m_top = UTIL_WaterLevel(GetLocalOrigin(), GetLocalOrigin().z, GetLocalOrigin().z + 400) - 1;
#if DEBUG_BEAMS
NDebugOverlay::Line( GetLocalOrigin(), GetLocalOrigin() + Vector( 0, 0, m_bottom ), 0, 255, 0, false, 0.1f );
NDebugOverlay::Line( GetLocalOrigin(), GetLocalOrigin() + Vector( 0, 0, m_top ), 0, 255, 255, false, 0.1f );
#endif
// Chop off 20% of the outside range
float newBottom = m_bottom * 0.8 + m_top * 0.2;
m_top = m_bottom * 0.2 + m_top * 0.8;
m_bottom = newBottom;
m_height = random->RandomFloat(m_bottom, m_top);
m_waterTime = gpGlobals->curtime + random->RandomFloat(5, 7);
}
void CNPC_Leech::SwimThink(void) {
trace_t tr;
float flLeftSide;
float flRightSide;
float targetSpeed;
float targetYaw = 0;
CBaseEntity *pTarget;
/*if ( !UTIL_FindClientInPVS( edict() ) )
{
m_flNextThink = gpGlobals->curtime + random->RandomFloat( 1.0f, 1.5f );
SetAbsVelocity( vec3_origin );
return;
}
else*/
SetNextThink(gpGlobals->curtime + 0.1);
targetSpeed = LEECH_SWIM_SPEED;
if (m_waterTime < gpGlobals->curtime)
RecalculateWaterlevel();
if (m_stateTime < gpGlobals->curtime)
SwitchLeechState();
ClearCondition(COND_CAN_MELEE_ATTACK1);
switch (m_NPCState) {
case NPC_STATE_COMBAT:
pTarget = GetEnemy();
if (!pTarget)
SwitchLeechState();
else {
// Chase the enemy's eyes
m_height = pTarget->GetLocalOrigin().z + pTarget->GetViewOffset().z - 5;
// Clip to viable water area
if (m_height < m_bottom)
m_height = m_bottom;
else if (m_height > m_top)
m_height = m_top;
Vector location = pTarget->GetLocalOrigin() - GetLocalOrigin();
location.z += (pTarget->GetViewOffset().z);
if (location.Length() < 80)
SetCondition(COND_CAN_MELEE_ATTACK1);
// Turn towards target ent
targetYaw = UTIL_VecToYaw(location);
QAngle vTestAngle = GetAbsAngles();
targetYaw = UTIL_AngleDiff(targetYaw, UTIL_AngleMod(GetAbsAngles().y));
if (targetYaw < (-LEECH_TURN_RATE))
targetYaw = (-LEECH_TURN_RATE);
else if (targetYaw > (LEECH_TURN_RATE))
targetYaw = (LEECH_TURN_RATE);
else
targetSpeed *= 2;
}
break;
default:
if (m_zTime < gpGlobals->curtime) {
float newHeight = random->RandomFloat(m_bottom, m_top);
m_height = 0.5 * m_height + 0.5 * newHeight;
m_zTime = gpGlobals->curtime + random->RandomFloat(1, 4);
}
if (random->RandomInt(0, 100) < 10)
targetYaw = random->RandomInt(-30, 30);
pTarget = NULL;
// oldorigin test
if ((GetLocalOrigin() - m_oldOrigin).Length() < 1) {
// If leech didn't move, there must be something blocking it, so try to turn
m_sideTime = 0;
}
break;
}
m_obstacle = ObstacleDistance(pTarget);
m_oldOrigin = GetLocalOrigin();
if (m_obstacle < 0.1)
m_obstacle = 0.1;
Vector vForward, vRight;
AngleVectors(GetAbsAngles(), &vForward, &vRight, NULL);
// is the way ahead clear?
if (m_obstacle == 1.0) {
// if the leech is turning, stop the trend.
if (m_flTurning != 0) {
m_flTurning = 0;
}
m_fPathBlocked = FALSE;
m_flSpeed = UTIL_Approach(targetSpeed, m_flSpeed, LEECH_SWIM_ACCEL * LEECH_FRAMETIME);
SetAbsVelocity(vForward * m_flSpeed);
} else {
m_obstacle = 1.0 / m_obstacle;
// IF we get this far in the function, the leader's path is blocked!
m_fPathBlocked = TRUE;
if (m_flTurning == 0)// something in the way and leech is not already turning to avoid
{
Vector vecTest;
// measure clearance on left and right to pick the best dir to turn
vecTest = GetLocalOrigin() + (vRight * LEECH_SIZEX) + (vForward * LEECH_CHECK_DIST);
UTIL_TraceLine(GetLocalOrigin(), vecTest, MASK_SOLID, this, COLLISION_GROUP_NONE, &tr);
flRightSide = tr.fraction;
vecTest = GetLocalOrigin() + (vRight * -LEECH_SIZEX) + (vForward * LEECH_CHECK_DIST);
UTIL_TraceLine(GetLocalOrigin(), vecTest, MASK_SOLID, this, COLLISION_GROUP_NONE, &tr);
flLeftSide = tr.fraction;
// turn left, right or random depending on clearance ratio
float delta = (flRightSide - flLeftSide);
if (delta > 0.1 || (delta > -0.1 && random->RandomInt(0, 100) < 50))
m_flTurning = -LEECH_TURN_RATE;
else
m_flTurning = LEECH_TURN_RATE;
}
m_flSpeed = UTIL_Approach(-(LEECH_SWIM_SPEED * 0.5), m_flSpeed,
LEECH_SWIM_DECEL * LEECH_FRAMETIME * m_obstacle);
SetAbsVelocity(vForward * m_flSpeed);
}
GetMotor()->SetIdealYaw(m_flTurning + targetYaw);
UpdateMotion();
}
//
// ObstacleDistance - returns normalized distance to obstacle
//
float CNPC_Leech::ObstacleDistance(CBaseEntity *pTarget) {
trace_t tr;
Vector vecTest;
Vector vForward, vRight;
// use VELOCITY, not angles, not all boids point the direction they are flying
//Vector vecDir = UTIL_VecToAngles( pev->velocity );
QAngle tmp = GetAbsAngles();
tmp.x = -tmp.x;
AngleVectors(tmp, &vForward, &vRight, NULL);
// check for obstacle ahead
vecTest = GetLocalOrigin() + vForward * LEECH_CHECK_DIST;
UTIL_TraceLine(GetLocalOrigin(), vecTest, MASK_SOLID, this, COLLISION_GROUP_NONE, &tr);
if (tr.startsolid) {
m_flSpeed = -LEECH_SWIM_SPEED * 0.5;
}
if (tr.fraction != 1.0) {
if ((pTarget == NULL || tr.m_pEnt != pTarget)) {
return tr.fraction;
} else {
if (fabs(m_height - GetLocalOrigin().z) > 10)
return tr.fraction;
}
}
if (m_sideTime < gpGlobals->curtime) {
// extra wide checks
vecTest = GetLocalOrigin() + vRight * LEECH_SIZEX * 2 + vForward * LEECH_CHECK_DIST;
UTIL_TraceLine(GetLocalOrigin(), vecTest, MASK_SOLID, this, COLLISION_GROUP_NONE, &tr);
if (tr.fraction != 1.0)
return tr.fraction;
vecTest = GetLocalOrigin() - vRight * LEECH_SIZEX * 2 + vForward * LEECH_CHECK_DIST;
UTIL_TraceLine(GetLocalOrigin(), vecTest, MASK_SOLID, this, COLLISION_GROUP_NONE, &tr);
if (tr.fraction != 1.0)
return tr.fraction;
// Didn't hit either side, so stop testing for another 0.5 - 1 seconds
m_sideTime = gpGlobals->curtime + random->RandomFloat(0.5, 1);
}
return 1.0;
}
void CNPC_Leech::UpdateMotion(void) {
float flapspeed = (m_flSpeed - m_flAccelerate) / LEECH_ACCELERATE;
m_flAccelerate = m_flAccelerate * 0.8 + m_flSpeed * 0.2;
if (flapspeed < 0)
flapspeed = -flapspeed;
flapspeed += 1.0;
if (flapspeed < 0.5)
flapspeed = 0.5;
if (flapspeed > 1.9)
flapspeed = 1.9;
m_flPlaybackRate = flapspeed;
QAngle vAngularVelocity = GetLocalAngularVelocity();
QAngle vAngles = GetLocalAngles();
if (!m_fPathBlocked)
vAngularVelocity.y = GetMotor()->GetIdealYaw();
else
vAngularVelocity.y = GetMotor()->GetIdealYaw() * m_obstacle;
if (vAngularVelocity.y > 150)
SetIdealActivity(ACT_TURN_LEFT);
else if (vAngularVelocity.y < -150)
SetIdealActivity(ACT_TURN_RIGHT);
else
SetIdealActivity(ACT_SWIM);
// lean
float targetPitch, delta;
delta = m_height - GetLocalOrigin().z;
/* if ( delta < -10 )
targetPitch = -30;
else if ( delta > 10 )
targetPitch = 30;
else*/
targetPitch = 0;
vAngles.x = UTIL_Approach(targetPitch, vAngles.x, 60 * LEECH_FRAMETIME);
// bank
vAngularVelocity.z = -(vAngles.z + (vAngularVelocity.y * 0.25));
if (m_NPCState == NPC_STATE_COMBAT && HasCondition(COND_CAN_MELEE_ATTACK1))
SetIdealActivity(ACT_MELEE_ATTACK1);
// Out of water check
if (!GetWaterLevel()) {
SetMoveType(MOVETYPE_FLYGRAVITY);
SetIdealActivity(ACT_HOP);
SetAbsVelocity(vec3_origin);
// Animation will intersect the floor if either of these is non-zero
vAngles.z = 0;
vAngles.x = 0;
m_flPlaybackRate = random->RandomFloat(0.8, 1.2);
} else if (GetMoveType() == MOVETYPE_FLYGRAVITY) {
SetMoveType(MOVETYPE_FLY);
SetGroundEntity(NULL);
// TODO
RecalculateWaterlevel();
m_waterTime = gpGlobals->curtime + 2; // Recalc again soon, water may be rising
}
if (GetActivity() != GetIdealActivity()) {
SetActivity(GetIdealActivity());
}
StudioFrameAdvance();
DispatchAnimEvents(this);
SetLocalAngles(vAngles);
SetLocalAngularVelocity(vAngularVelocity);
Vector vForward, vRight;
AngleVectors(vAngles, &vForward, &vRight, NULL);
#if DEBUG_BEAMS
if ( m_fPathBlocked )
{
float color = m_obstacle * 30;
if ( m_obstacle == 1.0 )
color = 0;
if ( color > 255 )
color = 255;
NDebugOverlay::Line( GetLocalOrigin(), GetLocalOrigin() + vForward * LEECH_CHECK_DIST, 255, color, color, false, 0.1f );
}
else
NDebugOverlay::Line( GetLocalOrigin(), GetLocalOrigin() + vForward * LEECH_CHECK_DIST, 255, 255, 0, false, 0.1f );
NDebugOverlay::Line( GetLocalOrigin(), GetLocalOrigin() + vRight * (vAngularVelocity.y*0.25), 0, 0, 255, false, 0.1f );
#endif
}
void CNPC_Leech::Event_Killed(const CTakeDamageInfo &info) {
Vector vecSplatDir;
trace_t tr;
//ALERT(at_aiconsole, "Leech: killed\n");
// tell owner ( if any ) that we're dead.This is mostly for MonsterMaker functionality.
CBaseEntity *pOwner = GetOwnerEntity();
if (pOwner)
pOwner->DeathNotice(this);
// When we hit the ground, play the "death_end" activity
if (GetWaterLevel()) {
QAngle qAngles = GetAbsAngles();
QAngle qAngularVel = GetLocalAngularVelocity();
Vector vOrigin = GetLocalOrigin();
qAngles.z = 0;
qAngles.x = 0;
vOrigin.z += 1;
SetAbsVelocity(vec3_origin);
if (random->RandomInt(0, 99) < 70)
qAngularVel.y = random->RandomInt(-720, 720);
SetAbsAngles(qAngles);
SetLocalAngularVelocity(qAngularVel);
SetAbsOrigin(vOrigin);
SetGravity(0.02);
SetGroundEntity(NULL);
SetActivity(ACT_DIESIMPLE);
} else
SetActivity(ACT_DIEFORWARD);
SetMoveType(MOVETYPE_FLYGRAVITY);
m_takedamage = DAMAGE_NO;
SetThink(&CNPC_Leech::DeadThink);
}
| 28.71408 | 129 | 0.615161 | cstom4994 |
4696fe7ded22d7a620a092d9bfb77c12dec81854 | 718 | cpp | C++ | L04-Railroad/Student_Code/Factory.cpp | tlyon3/CS235 | 2bdb8eaf66c9adbfe7ec59c0535852fd1cc30eda | [
"MIT"
] | 1 | 2018-03-04T02:58:55.000Z | 2018-03-04T02:58:55.000Z | L04-Railroad/Student_Code/Factory.cpp | tlyon3/CS235 | 2bdb8eaf66c9adbfe7ec59c0535852fd1cc30eda | [
"MIT"
] | 1 | 2015-02-09T21:29:12.000Z | 2015-02-09T21:32:06.000Z | L04-Railroad/Student_Code/Factory.cpp | tlyon3/CS235 | 2bdb8eaf66c9adbfe7ec59c0535852fd1cc30eda | [
"MIT"
] | 4 | 2019-05-20T02:57:47.000Z | 2021-02-11T15:41:15.000Z | #include "Factory.h"
#include "station.h"
//You may add #include statments here
using namespace std;
/*
Unlike all other documents provided, you may modify this document slightly (but do not change its name)
*/
//=======================================================================================
/*
createStation()
Creates and returns an object whose class extends StationInterface.
This should be an object of a class you have created.
Example: If you made a class called "Station", you might say, "return new Station();".
*/
StationInterface* Factory::createStation()
{
return new Station();//Modify this line
}
//=======================================================================================
| 31.217391 | 104 | 0.558496 | tlyon3 |
469ae2939322e272ff45c6fe1f633df93b3137a6 | 373 | hh | C++ | LAMPS-HighEnergy/detector/LHNeutronScintArray.hh | ggfdsa10/KEBI_AT-TPC | 40e00fcd10d3306b93fff93be5fb0988f87715a7 | [
"MIT"
] | 3 | 2021-05-24T19:43:30.000Z | 2022-01-06T21:03:23.000Z | LAMPS-HighEnergy/detector/LHNeutronScintArray.hh | ggfdsa10/KEBI_AT-TPC | 40e00fcd10d3306b93fff93be5fb0988f87715a7 | [
"MIT"
] | 4 | 2020-05-04T15:52:26.000Z | 2021-09-13T10:51:03.000Z | LAMPS-HighEnergy/detector/LHNeutronScintArray.hh | ggfdsa10/KEBI_AT-TPC | 40e00fcd10d3306b93fff93be5fb0988f87715a7 | [
"MIT"
] | 3 | 2020-06-14T10:53:58.000Z | 2022-01-06T21:03:30.000Z | #ifndef LHNEUTRONSCINTARRAY_HH
#define LHNEUTRONSCINTARRAY_HH
#include "KBDetector.hh"
class LHNeutronScintArray : public KBDetector
{
public:
LHNeutronScintArray();
virtual ~LHNeutronScintArray() {};
virtual bool Init();
protected:
virtual bool BuildGeometry();
virtual bool BuildDetectorPlane();
ClassDef(LHNeutronScintArray, 1)
};
#endif
| 16.954545 | 45 | 0.739946 | ggfdsa10 |
46a09092cd0564f2523082aafc7e85aa138113b0 | 3,015 | cpp | C++ | src/drivers/Input/PS2MouseDriver.cpp | Unified-Projects/Unified-OS | 89912adc1ed9ec35753fe0f4fa35f03d30ec66a2 | [
"BSD-2-Clause"
] | null | null | null | src/drivers/Input/PS2MouseDriver.cpp | Unified-Projects/Unified-OS | 89912adc1ed9ec35753fe0f4fa35f03d30ec66a2 | [
"BSD-2-Clause"
] | null | null | null | src/drivers/Input/PS2MouseDriver.cpp | Unified-Projects/Unified-OS | 89912adc1ed9ec35753fe0f4fa35f03d30ec66a2 | [
"BSD-2-Clause"
] | null | null | null | #include <drivers/Input/PS2MouseDriver.h>
using namespace UnifiedOS;
using namespace UnifiedOS::Drivers;
PS2MouseEventHandler::PS2MouseEventHandler(){
}
PS2MouseEventHandler::~PS2MouseEventHandler(){
}
void PS2MouseEventHandler::OnMouseDown(uint8_t button){
}
void PS2MouseEventHandler::OnMouseUp(uint8_t button){
}
void PS2MouseEventHandler::OnMouseMove(int x, int y){
}
PS2MouseDriver::PS2MouseDriver(Interrupts::InterruptManager* manager, PS2MouseEventHandler* handler)
: InterruptHandler(0x2C, manager),
dataPort(0x60),
commandPort(0x64)
{
Handler = handler;
}
PS2MouseDriver::~PS2MouseDriver(){
}
void PS2MouseDriver::Wait(){
uint64_t timeout = 100000;
while(timeout--){
if((commandPort.Read() & 0b10) == 0){
return;
}
}
}
void PS2MouseDriver::Wait_Input(){
uint64_t timeout = 100000;
while(timeout--){
if(commandPort.Read() & 0b1){
return;
}
}
}
void PS2MouseDriver::Activate(){
// offset = 0; //Default Buffers
// buttons = 0;
// commandPort.Write(0xA8); //PIC start sending interrupts
// Wait();
// commandPort.Write(0x20); //Get state
// Wait_Input();
// uint8_t status = dataPort.Read() | 2;
// Wait();
// commandPort.Write(0x60); //Set State
// Wait();
// dataPort.Write(status);
// Wait();
// commandPort.Write(0xD4);
// Wait();
// dataPort.Write(0xF6); //Activate
// Wait_Input();
// dataPort.Read();
// Wait();
// commandPort.Write(0xD4);
// Wait();
// dataPort.Write(0xF4); //Activate
// Wait_Input();
// dataPort.Read();
}
bool Skip = true;
void PS2MouseDriver::HandleInterrupt(uint64_t rsp){
if(Skip) {Skip = false; return;} //Skip first packet
//Read status
uint8_t status = commandPort.Read();
if (!(status & 0x20))
return; //If not ready return
//Read Buffer at current offset
buffer[offset] = dataPort.Read(); //We dont want to skip this if there is no handler
if(Handler == 0) //If handler does not exist leave
return;
offset = (offset + 1) % 3; //Increase offset while keeping it less than three
if(offset == 0) //If offset 0 (Means full buffer overwrite)
{
if(buffer[1] != 0 || buffer[2] != 0) //Buffer positions for cursor movement
{
Handler->OnMouseMove((int8_t)buffer[1], -((int8_t)buffer[2])); //We send to handler but inverse y because it is negative version
}
for(uint8_t i = 0; i < 3; i++) //We loop over buttons
{
if((buffer[0] & (0x1<<i)) != (buttons & (0x1<<i))) //Check if it is different
{
if(buttons & (0x1<<i)) //Shows if it is up or down
Handler->OnMouseUp(i+1); //Send to handler
else
Handler->OnMouseDown(i+1); //Send to handler
}
}
buttons = buffer[0]; //Load the buttons from buffer for next comparison
}
} | 24.314516 | 140 | 0.596352 | Unified-Projects |
46a259730f0a41dd17d84687e7e34ffb35ebbc7c | 1,677 | cpp | C++ | MidiChannel.cpp | Madsy/libmidi | c271e991e9d6f762e81a8d2dbf7a5cd63973629d | [
"MIT"
] | 5 | 2018-08-14T01:04:33.000Z | 2021-07-15T22:13:45.000Z | MidiChannel.cpp | Madsy/libmidi | c271e991e9d6f762e81a8d2dbf7a5cd63973629d | [
"MIT"
] | 4 | 2017-03-21T23:10:46.000Z | 2017-03-21T23:19:55.000Z | MidiChannel.cpp | Madsy/libmidi | c271e991e9d6f762e81a8d2dbf7a5cd63973629d | [
"MIT"
] | null | null | null | //
// Created by madsy on 22.03.17.
//
#include <algorithm>
#include "MidiChannel.h"
MidiChannel::MidiChannel() : pChannelIndex(0), pStartTick(0), pEndTick(0) {
}
MidiChannel::~MidiChannel() {
}
std::vector<std::shared_ptr<MidiEvent>> MidiChannel::getEventsWithinInterval(unsigned int startTick, unsigned int endTick) const {
std::vector<std::shared_ptr<MidiEvent>> result;
for(size_t i = 0; i < pEvents.size(); i++){
unsigned int t = pEvents[i]->getTimestamp();
if(t >= startTick && t < endTick){
result.push_back(pEvents[i]);
}
}
return pEvents;
}
const std::vector<std::shared_ptr<MidiEvent>> &MidiChannel::getEvents() const {
return pEvents;
}
void MidiChannel::addEvent(const std::shared_ptr<MidiEvent> &evt) {
pEvents.push_back(evt);
}
void MidiChannel::sort() {
std::stable_sort(pEvents.begin(),
pEvents.end(),
[](const std::shared_ptr<MidiEvent>& a, const std::shared_ptr<MidiEvent>& b) -> bool {
return a->getTimestamp() < b->getTimestamp();
}
);
}
unsigned int MidiChannel::getStartTick() const {
return pStartTick;
}
unsigned int MidiChannel::getEndTick() const {
return pEndTick;
}
void MidiChannel::update() {
//refresh start and end tick after adding all events
pStartTick = 0xFFFFFFFF;
pEndTick = 0;
for(size_t i = 0; i < pEvents.size(); i++){
if(pEvents[i] && pEvents[i]->getTimestamp() < pStartTick){ pStartTick = pEvents[i]->getTimestamp(); }
if(pEvents[i] && pEvents[i]->getTimestamp() > pEndTick){ pEndTick = pEvents[i]->getTimestamp(); }
}
}
| 26.619048 | 130 | 0.621944 | Madsy |
46a38100725550a521f3db415b1ccaf992cbaa83 | 1,588 | cpp | C++ | Cpp/odin/odin.cpp | Deuanz/odin | da31a6bc8b9b4a0270f0807b588483840a24cf46 | [
"BSL-1.0"
] | null | null | null | Cpp/odin/odin.cpp | Deuanz/odin | da31a6bc8b9b4a0270f0807b588483840a24cf46 | [
"BSL-1.0"
] | null | null | null | Cpp/odin/odin.cpp | Deuanz/odin | da31a6bc8b9b4a0270f0807b588483840a24cf46 | [
"BSL-1.0"
] | null | null | null | /*
Copyright 2016-2017 Felspar Co Ltd. http://odin.felspar.com/
Distributed under the Boost Software License, Version 1.0.
See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt
*/
#include <odin/odin.hpp>
#include <odin/nonce.hpp>
#include <fostgres/callback.hpp>
const fostlib::module odin::c_odin("odin");
const fostlib::setting<fostlib::string> odin::c_jwt_secret(
"odin/odin.cpp", "odin", "JWT secret", odin::nonce(), true);
const fostlib::setting<bool> odin::c_jwt_trust(
"odin/odin.cpp", "odin", "Trust JWT", false, true);
const fostlib::setting<fostlib::string> odin::c_jwt_logout_claim(
"odin/odin.cpp", "odin", "JWT logout claim", "http://odin.felspar.com/lo", true);
const fostlib::setting<bool> odin::c_jwt_logout_check(
"odin/odin.cpp", "odin", "Perform JWT logout check", true, true);
const fostlib::setting<fostlib::string> odin::c_jwt_permissions_claim(
"odin/odin.cpp", "odin", "JWT permissions claim", "http://odin.felspar.com/p", true);
namespace {
const fostgres::register_cnx_callback c_cb(
[](fostlib::pg::connection &cnx, const fostlib::http::server::request &req) {
if ( req.headers().exists("__user") ) {
const auto &user = req.headers()["__user"];
cnx.set_session("odin.jwt.sub", user.value());
}
if ( req.headers().exists("__jwt") ) {
for ( const auto &sv : req.headers()["__jwt"] )
cnx.set_session("odin.jwt." + sv.first, sv.second);
}
});
}
| 35.288889 | 89 | 0.630982 | Deuanz |
46a7bca86ec9b994cc5976c29460d58adfaee694 | 550 | hpp | C++ | ex03/include/RobotomyRequestForm.hpp | 42cursus-youkim/-Rank04-CPP-Module05 | 71244b25b1c9556dd4ec186e543c2a3e308d0036 | [
"MIT"
] | null | null | null | ex03/include/RobotomyRequestForm.hpp | 42cursus-youkim/-Rank04-CPP-Module05 | 71244b25b1c9556dd4ec186e543c2a3e308d0036 | [
"MIT"
] | null | null | null | ex03/include/RobotomyRequestForm.hpp | 42cursus-youkim/-Rank04-CPP-Module05 | 71244b25b1c9556dd4ec186e543c2a3e308d0036 | [
"MIT"
] | null | null | null | #ifndef __ROBOTOMYREQUESTFORM_H__
#define __ROBOTOMYREQUESTFORM_H__
#include "Form.hpp"
class RobotomyRequestForm : public Form {
private:
// Disabled Operators
RobotomyRequestForm& operator=(const RobotomyRequestForm& assign);
public:
enum Requirement { SIGN = 72, EXEC = 45 };
// Constructors & Destructor
RobotomyRequestForm(const string& target);
RobotomyRequestForm(const RobotomyRequestForm& other);
~RobotomyRequestForm();
// Overrided Abstract Methods
void formAction() const;
};
#endif // __ROBOTOMYREQUESTFORM_H__
| 23.913043 | 68 | 0.767273 | 42cursus-youkim |
9e56615e2ffd44d3ff32857a39c631984255f628 | 8,484 | cp | C++ | Linux/Sources/Application/Calendar/Calendar_View/Free_Busy_View/CFreeBusyTable.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 12 | 2015-04-21T16:10:43.000Z | 2021-11-05T13:41:46.000Z | Linux/Sources/Application/Calendar/Calendar_View/Free_Busy_View/CFreeBusyTable.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2015-11-02T13:32:11.000Z | 2019-07-10T21:11:21.000Z | Linux/Sources/Application/Calendar/Calendar_View/Free_Busy_View/CFreeBusyTable.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 6 | 2015-01-12T08:49:12.000Z | 2021-03-27T09:11:10.000Z | /*
Copyright (c) 2007-2009 Cyrus Daboo. 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 "CFreeBusyTable.h"
#include "CCalendarUtils.h"
#include "CCommands.h"
#include "CFreeBusyTitleTable.h"
#include "CMulberryCommon.h"
#include "CPreferences.h"
#include "CXStringResources.h"
#include "CICalendarLocale.h"
#include "StPenState.h"
#include <UNX_LTableMultiGeometry.h>
#include <JPainter.h>
#include <JXColormap.h>
#include <JXTextMenu.h>
#include <JXScrollbar.h>
#include <JXScrollbarSet.h>
#include <algorithm>
const uint32_t cRowHeight = 24;
const uint32_t cNameColumnWidth = 128;
const uint32_t cHourColumnWidth = 96;
const uint32_t cNameColumn = 1;
const uint32_t cFirstTimedColumn = 2;
// ---------------------------------------------------------------------------
// CFreeBusyTable [public]
/**
Default constructor */
CFreeBusyTable::CFreeBusyTable(JXScrollbarSet* scrollbarSet,
JXContainer* enclosure,
const HSizingOption hSizing,
const VSizingOption vSizing,
const JCoordinate x, const JCoordinate y,
const JCoordinate w, const JCoordinate h) :
CCalendarEventTableBase(scrollbarSet, enclosure, hSizing, vSizing, x, y, w, h)
{
mTitles = NULL;
mScaleColumns = 0;
mStartHour = 0;
mEndHour = 24;
mTableGeometry = new LTableMultiGeometry(this, 128, 24);
}
// ---------------------------------------------------------------------------
// ~CFreeBusyTable [public]
/**
Destructor */
CFreeBusyTable::~CFreeBusyTable()
{
}
#pragma mark -
void
CFreeBusyTable::OnCreate()
{
// Call inherited
CCalendarEventTableBase::OnCreate();
InsertCols(1, 1, NULL);
InsertRows(1, 1, NULL);
SetRowHeight(cRowHeight, 1, 1);
SetColWidth(cNameColumnWidth, 1, 1);
itsScrollbarSet->GetHScrollbar()->SetStepSize(cHourColumnWidth);
itsScrollbarSet->GetVScrollbar()->SetStepSize(cRowHeight);
CreateContextMenu(CMainMenu::eContextCalendarEventTable);
ApertureResized(0, 0);
}
void CFreeBusyTable::DrawCellRange(JPainter* pDC,
const STableCell& inTopLeftCell,
const STableCell& inBottomRightCell)
{
STableCell cell;
for ( cell.row = inTopLeftCell.row;
cell.row <= inBottomRightCell.row;
cell.row++ )
{
// Draw entire row
JRect rowRect;
GetLocalCellRect(STableCell(cell.row, 2), rowRect);
JRect cellRect;
GetLocalCellRect(STableCell(cell.row, mCols), cellRect);
rowRect.right = cellRect.right;
DrawRow(pDC, cell.row, rowRect);
for ( cell.col = inTopLeftCell.col;
cell.col <= inBottomRightCell.col;
cell.col++ )
{
JRect cellRect;
GetLocalCellRect(cell, cellRect);
DrawCell(pDC, cell, cellRect);
}
}
}
void CFreeBusyTable::DrawRow(JPainter* pDC, TableIndexT row, const JRect& inLocalRect)
{
StPenState save(pDC);
JRect adjustedRect = inLocalRect;
adjustedRect.Shrink(0, 3);
float total_width = adjustedRect.width();
const SFreeBusyInfo& info = mItems.at(row - 1);
JRect itemRect = adjustedRect;
for(std::vector<SFreeBusyInfo::SFreeBusyPeriod>::const_iterator iter = info.mPeriods.begin(); iter != info.mPeriods.end(); iter++)
{
// Adjust for current width
itemRect.right = itemRect.left + total_width * ((float) (*iter).second / (float)mColumnSeconds);
itemRect.Shrink(1, 0);
// Red for busy, green for free, blue for tentative, grey for unavailable
float red = 0.0;
float green = 0.0;
float blue = 0.0;
switch((*iter).first)
{
case iCal::CICalendarFreeBusy::eFree:
green = 1.0;
break;
case iCal::CICalendarFreeBusy::eBusyTentative:
blue = 1.0;
break;
case iCal::CICalendarFreeBusy::eBusyUnavailable:
red = 0.25;
green = 0.25;
blue = 0.25;
break;
case iCal::CICalendarFreeBusy::eBusy:
red = 1.0;
break;
}
CCalendarUtils::LightenColours(red, green, blue);
// Draw it
JColorIndex cindex;
GetColormap()->JColormap::AllocateStaticColor(CCalendarUtils::GetRGBColor(red, green, blue), &cindex);
pDC->SetPenColor(cindex);
pDC->SetFilling(kTrue);
pDC->Rect(itemRect);
pDC->SetFilling(kFalse);
GetColormap()->JColormap::AllocateStaticColor(CCalendarUtils::GetRGBColor(red * 0.6, green * 0.6, blue * 0.6), &cindex);
pDC->SetPenColor(cindex);
pDC->Rect(itemRect);
// Now adjust for next one
itemRect.left += itemRect.width() + 1;
itemRect.right = itemRect.left + adjustedRect.right - itemRect.left;
}
}
void CFreeBusyTable::DrawCell(JPainter* pDC, const STableCell& inCell, const JRect& inLocalRect)
{
StPenState save(pDC);
JRect adjustedRect = inLocalRect;
JColorIndex cindex;
// Left-side always
{
JColorIndex old_cindex = pDC->GetPenColor();
GetColormap()->JColormap::AllocateStaticColor(
CCalendarUtils::GetGreyColor((inCell.col > 2) ? 0.75 : 0.5),
&cindex);
pDC->SetPenColor(cindex);
pDC->Line(adjustedRect.left, adjustedRect.top, adjustedRect.left, adjustedRect.bottom);
pDC->SetPenColor(old_cindex);
}
// Right-side only for last column
if (inCell.col == mCols)
{
JColorIndex old_cindex = pDC->GetPenColor();
GetColormap()->JColormap::AllocateStaticColor(CCalendarUtils::GetGreyColor(0.5), &cindex);
pDC->SetPenColor(cindex);
pDC->Line(adjustedRect.right, adjustedRect.top, adjustedRect.right, adjustedRect.bottom);
pDC->SetPenColor(old_cindex);
}
// Top-side always (lighter line above half-hour row)
{
JColorIndex old_cindex = pDC->GetPenColor();
GetColormap()->JColormap::AllocateStaticColor(CCalendarUtils::GetGreyColor(0.5), &cindex);
pDC->SetPenColor(cindex);
pDC->Line(adjustedRect.left, adjustedRect.top, adjustedRect.right, adjustedRect.top);
pDC->SetPenColor(old_cindex);
}
// Bottom-side for last row
if (inCell.row == mRows)
{
JColorIndex old_cindex = pDC->GetPenColor();
GetColormap()->JColormap::AllocateStaticColor(CCalendarUtils::GetGreyColor(0.5), &cindex);
pDC->SetPenColor(cindex);
pDC->Line(adjustedRect.left, adjustedRect.bottom, adjustedRect.right, adjustedRect.bottom);
pDC->SetPenColor(old_cindex);
}
adjustedRect.Shrink(2, 0);
if (inCell.col == 1)
{
cdstring name = mItems.at(inCell.row - 1).mName;
pDC->SetPenColor(GetColormap()->GetBlackColor());
JRect clipRect(adjustedRect);
clipRect.Shrink(0, 1);
clipRect.right += 2;
::DrawClippedStringUTF8(pDC, name, JPoint(adjustedRect.left, adjustedRect.top), clipRect, eDrawString_Right);
}
}
void CFreeBusyTable::RefreshNow()
{
// Redraw - double-buffering removes any flashing
FRAMEWORK_REFRESH_WINDOW(this)
}
void CFreeBusyTable::ApertureResized(const JCoordinate dw, const JCoordinate dh)
{
// Allow frame adapter to adjust size
CCalendarEventTableBase::ApertureResized(dw, dh);
// Look for change in image size
UInt32 old_width, old_height;
mTableGeometry->GetTableDimensions(old_width, old_height);
// If auto-fit rows, change row height
RescaleWidth();
itsScrollbarSet->GetHScrollbar()->SetStepSize(GetColWidth(cFirstTimedColumn));
itsScrollbarSet->GetVScrollbar()->SetStepSize(cRowHeight);
UInt32 new_width, new_height;
mTableGeometry->GetTableDimensions(new_width, new_height);
if (mTitles)
mTitles->TableChanged();
}
void CFreeBusyTable::RescaleWidth()
{
// If auto-fit rows, change row height
if (mScaleColumns == 0)
{
JRect my_frame = GetFrameGlobal();
if (mCols > 1)
{
SInt32 col_size = std::max((SInt32) ((my_frame.width() - GetColWidth(cNameColumn)) / (mCols - 1)), 8L);
SetColWidth(col_size, cFirstTimedColumn, mCols);
}
}
}
// Keep titles in sync
void CFreeBusyTable::ScrollImageBy(SInt32 inLeftDelta, SInt32 inTopDelta, bool inRefresh)
{
// Find titles in owner chain
if (mTitles)
mTitles->ScrollImageBy(inLeftDelta, 0, inRefresh);
CTableDrag::ScrollImageBy(inLeftDelta, inTopDelta, inRefresh);
}
void CFreeBusyTable::ScaleColumns(uint32_t scale)
{
if (scale != mScaleColumns)
{
mScaleColumns = scale;
if (mScaleColumns > 0)
SetColWidth(cHourColumnWidth / mScaleColumns, cFirstTimedColumn, mCols);
else
{
RescaleWidth();
}
}
}
| 26.933333 | 131 | 0.709335 | mulberry-mail |
9e598ab89a764c1ec62524703ed3067e2692fd1f | 1,497 | hh | C++ | src/physics/JointFeedback.hh | nherment/gazebo | fff0aa30b4b5748e43c2b0aa54ffcd366e9f042a | [
"ECL-2.0",
"Apache-2.0"
] | 5 | 2016-01-17T20:41:39.000Z | 2018-05-01T12:02:58.000Z | src/physics/JointFeedback.hh | nherment/gazebo | fff0aa30b4b5748e43c2b0aa54ffcd366e9f042a | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | src/physics/JointFeedback.hh | nherment/gazebo | fff0aa30b4b5748e43c2b0aa54ffcd366e9f042a | [
"ECL-2.0",
"Apache-2.0"
] | 5 | 2015-09-29T02:30:16.000Z | 2022-03-30T12:11:22.000Z | /*
* Copyright 2011 Nate Koenig & Andrew Howard
*
* 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.
*
*/
/* Desc: Specification of a contact
* Author: Nate Koenig
* Date: 10 Nov 2009
*/
#ifndef JOINTFEEDBACK_HH
#define JOINTFEEDBACK_HH
#include "math/Vector3.hh"
namespace gazebo
{
namespace physics
{
/// \addtogroup gazebo_physics
/// \{
/// \brief Feedback information from a joint
class JointFeedback
{
/// \brief Operator =
public: JointFeedback &operator =(const JointFeedback &f)
{
this->body1Force = f.body1Force;
this->body2Force = f.body2Force;
this->body1Torque = f.body1Torque;
this->body2Torque = f.body2Torque;
return *this;
}
public: math::Vector3 body1Force;
public: math::Vector3 body2Force;
public: math::Vector3 body1Torque;
public: math::Vector3 body2Torque;
};
/// \}
}
}
#endif
| 25.372881 | 75 | 0.645291 | nherment |
9e5a44e311b394c612d80c73766e978ebcbf9759 | 5,009 | hpp | C++ | Linux/Ubuntu/64bit/AVAPI/Avapi/TECHNICAL_INDICATOR/AROONOSC.hpp | AvapiDotNet/AvapiCpp | 2157ccbe750cac077098a6f1aa401d80fc943ff5 | [
"MIT"
] | 15 | 2018-01-31T16:58:36.000Z | 2021-08-19T21:37:08.000Z | Linux/Ubuntu/64bit/AVAPI/Avapi/TECHNICAL_INDICATOR/AROONOSC.hpp | AvapiDotNet/AvapiCpp | 2157ccbe750cac077098a6f1aa401d80fc943ff5 | [
"MIT"
] | null | null | null | Linux/Ubuntu/64bit/AVAPI/Avapi/TECHNICAL_INDICATOR/AROONOSC.hpp | AvapiDotNet/AvapiCpp | 2157ccbe750cac077098a6f1aa401d80fc943ff5 | [
"MIT"
] | 4 | 2018-01-31T17:06:26.000Z | 2020-05-03T20:59:27.000Z | #ifndef AROONOSC_HPP_INCLUDED
#define AROONOSC_HPP_INCLUDED
#include <string>
#include <map>
#include <list>
#include "../jsmn/jsmn.h"
using namespace std;
namespace Avapi {
class RestClient; //forward declaration
enum class Const_AROONOSC_interval{
none,
n_1min,
n_5min,
n_15min,
n_30min,
n_60min,
daily,
weekly,
monthly,
};
class MAP_AROONOSC
{
public:
static const map<Const_AROONOSC_interval, string> s_interval_translation;
};
class MetaData_Type_AROONOSC
{
private:
string Symbol;
string Indicator;
string LastRefreshed;
string Interval;
string TimePeriod;
string TimeZone;
public:
MetaData_Type_AROONOSC();
MetaData_Type_AROONOSC(const MetaData_Type_AROONOSC& other); // copy constructor
string get_Symbol() const {return Symbol;};
string get_Indicator() const {return Indicator;};
string get_LastRefreshed() const {return LastRefreshed;};
string get_Interval() const {return Interval;};
string get_TimePeriod() const {return TimePeriod;};
string get_TimeZone() const {return TimeZone;};
void set_Symbol(string Symbol){this->Symbol = Symbol;};
void set_Indicator(string Indicator){this->Indicator = Indicator;};
void set_LastRefreshed(string LastRefreshed){this->LastRefreshed = LastRefreshed;};
void set_Interval(string Interval){this->Interval = Interval;};
void set_TimePeriod(string TimePeriod){this->TimePeriod = TimePeriod;};
void set_TimeZone(string TimeZone){this->TimeZone = TimeZone;};
int ParseInternal(string& str_data, jsmntok_t* array_token ,int index, int token_size);
};
class TechnicalIndicator_Type_AROONOSC
{
private:
string AROONOSC;
string DateTime;
public:
TechnicalIndicator_Type_AROONOSC();
TechnicalIndicator_Type_AROONOSC(const TechnicalIndicator_Type_AROONOSC& other); // copy constructor
string get_AROONOSC() const {return AROONOSC;};
string get_DateTime() const {return DateTime;};
void set_AROONOSC(string AROONOSC){this->AROONOSC = AROONOSC;};
void set_DateTime(string DateTime){this->DateTime = DateTime;};
int ParseInternal(string& str_data, jsmntok_t* array_token, int index, int token_size);
};
class AvapiResponse_AROONOSC_Content
{
private:
MetaData_Type_AROONOSC MetaData;
list<TechnicalIndicator_Type_AROONOSC> TechnicalIndicator;
string str_prefix;
bool error_status;
string ErrorMessage;
public:
AvapiResponse_AROONOSC_Content();
~AvapiResponse_AROONOSC_Content() {};
AvapiResponse_AROONOSC_Content(const AvapiResponse_AROONOSC_Content& other); // copy constructor
MetaData_Type_AROONOSC& get_MetaData() {return MetaData;};
list<TechnicalIndicator_Type_AROONOSC>& get_TechnicalIndicator() {return TechnicalIndicator;};
void set_Error(bool error_status) {this->error_status = error_status;};
bool isError() {return error_status;};
string get_ErrorMessage() {return ErrorMessage;};
void set_ErrorMessage(string ErrorMessage) {this->ErrorMessage = str_prefix + ErrorMessage;};
};
class AvapiResponse_AROONOSC
{
private:
string LastHttpRequest;
string RawData;
AvapiResponse_AROONOSC_Content* Data;
public:
AvapiResponse_AROONOSC();
AvapiResponse_AROONOSC(const AvapiResponse_AROONOSC& other); // copy constructor
AvapiResponse_AROONOSC(AvapiResponse_AROONOSC&& other); // move constructor
AvapiResponse_AROONOSC& operator=(const AvapiResponse_AROONOSC& other); //copy assignment
AvapiResponse_AROONOSC& operator=(AvapiResponse_AROONOSC&& other); //move assignment
~AvapiResponse_AROONOSC();
AvapiResponse_AROONOSC_Content& get_Data() const {return *Data;};
string get_LastHttpRequest() const {return LastHttpRequest;};
string get_RawData() const {return RawData;};
void set_LastHttpRequest(string LastHttpRequest){this->LastHttpRequest = LastHttpRequest;};
void set_RawData(string RawData){this->RawData = RawData;};
};
class Impl_AROONOSC
{
private:
string AvapiUrl;
string ApiKey;
RestClient *Client;
static string s_function;
static Impl_AROONOSC *s_instance;
Impl_AROONOSC() {};
static const unsigned int START_TOKEN_SIZE = 3000;
static void ParseInternal(AvapiResponse_AROONOSC& Response);
public:
static Impl_AROONOSC& getInstance();
static void destroyInstance();
string get_AvapiUrl() const {return AvapiUrl;};
RestClient* get_Client() const {return Client;};
string get_ApiKey() const {return ApiKey;};
void set_AvapiUrl(string AvapiUrl){this->AvapiUrl = AvapiUrl;};
void set_Client(RestClient *Client){this->Client = Client;};
void set_ApiKey(string ApiKey){this->ApiKey = ApiKey;};
AvapiResponse_AROONOSC Query(string symbol
,Const_AROONOSC_interval interval
,string time_period
);
AvapiResponse_AROONOSC Query(string symbol
,string interval
,string time_period
);
};
}//end namespace Avapi
#endif // AROONOSC_HPP_INCLUDED
| 31.111801 | 104 | 0.743262 | AvapiDotNet |
9e5d618715c325995cc920febbce9c21e04c9062 | 2,489 | cpp | C++ | code/tests/glx/src/main.cpp | BrightComposite/RaptureStateToolkit | 6eb3c831540ba6a9d29e903dd3c537aac2e7f91f | [
"MIT"
] | null | null | null | code/tests/glx/src/main.cpp | BrightComposite/RaptureStateToolkit | 6eb3c831540ba6a9d29e903dd3c537aac2e7f91f | [
"MIT"
] | null | null | null | code/tests/glx/src/main.cpp | BrightComposite/RaptureStateToolkit | 6eb3c831540ba6a9d29e903dd3c537aac2e7f91f | [
"MIT"
] | null | null | null | //---------------------------------------------------------------------------
#include <application/starter.h>
//---------------------------------------------------------------------------
#include <X11/X.h>
#include <X11/Xlib.h>
#include <GL/gl.h>
#include <GL/glx.h>
#include <GL/glu.h>
#include <iostream>
//---------------------------------------------------------------------------
namespace asd
{
void DrawAQuad() {
glClearColor(1.0, 1.0, 1.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-1., 1., -1., 1., 1., 20.);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0., 0., 10., 0., 0., 0., 0., 1., 0.);
glBegin(GL_QUADS);
glColor3f(1.f, 0.f, 0.f);
glVertex3f(-.75f, -.75f, 0.f);
glColor3f(0.f, 1.f, 0.f);
glVertex3f(.75f, -.75f, 0.f);
glColor3f(0.f, 0.f, 1.f);
glVertex3f(.75f, .75f, 0.f);
glColor3f(1.f, 1.f, 0.f);
glVertex3f(-.75f, .75f, 0.f);
glEnd();
}
static entrance open([]() {
using namespace std;
auto d = XOpenDisplay(NULL);
if(d == nullptr) {
cout << "Cannot connect to X server" << endl;
return 1;
}
GLint att[] = {GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None};
auto vi = glXChooseVisual(d, 0, att);
if(vi == NULL) {
cout << "No appropriate visual found" << endl;
return 1;
}
auto root = DefaultRootWindow(d);
XSetWindowAttributes swa;
swa.colormap = XCreateColormap(d, root, vi->visual, AllocNone);
swa.event_mask = ExposureMask | KeyPressMask;
auto w = XCreateWindow(d, root, 0, 0, 600, 600, 0, vi->depth, InputOutput, vi->visual, CWColormap | CWEventMask, &swa);
XMapWindow(d, w);
XStoreName(d, w, "ASD: glxtest");
auto glc = glXCreateContext(d, vi, NULL, GL_TRUE);
glXMakeCurrent(d, w, glc);
glEnable(GL_DEPTH_TEST);
XWindowAttributes gwa;
XEvent xev;
cout << "Press ESC to exit" << endl;
while(1) {
XNextEvent(d, &xev);
if(xev.type == Expose) {
XGetWindowAttributes(d, w, &gwa);
glViewport(0, 0, gwa.width, gwa.height);
DrawAQuad();
glXSwapBuffers(d, w);
} else if(xev.type == KeyPress) {
if(xev.xkey.keycode == 9) {
cout << "Exit..." << endl;
glXMakeCurrent(d, None, NULL);
glXDestroyContext(d, glc);
XDestroyWindow(d, w);
XCloseDisplay(d);
break;
}
}
}
return 0;
});
}
//---------------------------------------------------------------------------
| 23.261682 | 121 | 0.527923 | BrightComposite |
9e5fed5b8db9931f8f0dca8131debee4179261a1 | 5,253 | cpp | C++ | tests/chain_tests/plugins/tags/get_posts_and_comments_tests.cpp | scorum/scorum | 1da00651f2fa14bcf8292da34e1cbee06250ae78 | [
"MIT"
] | 53 | 2017-10-28T22:10:35.000Z | 2022-02-18T02:20:48.000Z | tests/chain_tests/plugins/tags/get_posts_and_comments_tests.cpp | Scorum/Scorum | fb4aa0b0960119b97828865d7a5b4d0409af7876 | [
"MIT"
] | 38 | 2017-11-25T09:06:51.000Z | 2018-10-31T09:17:22.000Z | tests/chain_tests/plugins/tags/get_posts_and_comments_tests.cpp | Scorum/Scorum | fb4aa0b0960119b97828865d7a5b4d0409af7876 | [
"MIT"
] | 27 | 2018-01-08T19:43:35.000Z | 2022-01-14T10:50:42.000Z | #include <scorum/tags/tags_api_objects.hpp>
#include <boost/test/unit_test.hpp>
#include "tags_common.hpp"
using namespace scorum;
using namespace scorum::tags::api;
using namespace scorum::app;
using namespace scorum::tags;
BOOST_FIXTURE_TEST_SUITE(get_posts_and_comments_tests, database_fixture::tags_fixture)
SCORUM_TEST_CASE(check_get_posts_and_comments_contract_negative)
{
discussion_query q;
q.limit = 101;
BOOST_REQUIRE_THROW(_api.get_posts_and_comments(q), fc::assert_exception);
q.limit = 100;
q.start_author = "x";
BOOST_REQUIRE_THROW(_api.get_posts_and_comments(q), fc::assert_exception);
q.start_author.reset();
q.start_permlink = "x";
BOOST_REQUIRE_THROW(_api.get_posts_and_comments(q), fc::assert_exception);
}
SCORUM_TEST_CASE(check_get_posts_and_comments_contract_positive)
{
discussion_query q;
q.limit = 100;
BOOST_REQUIRE_NO_THROW(_api.get_posts_and_comments(q));
q.start_author = "alice";
q.start_permlink = "p";
BOOST_REQUIRE_NO_THROW(_api.get_posts_and_comments(q));
}
SCORUM_TEST_CASE(check_both_posts_and_comments_returned)
{
discussion_query q;
q.limit = 100;
BOOST_REQUIRE_EQUAL(_api.get_posts_and_comments(q).size(), 0u);
auto p = create_post(alice).in_block();
p.create_comment(bob).in_block();
BOOST_REQUIRE_EQUAL(_api.get_posts_and_comments(q).size(), 2u);
}
SCORUM_TEST_CASE(check_truncate_body)
{
auto p = create_post(alice).set_body("1234567").in_block();
auto c = p.create_comment(bob).set_body("abcdefgh").in_block();
discussion_query q;
q.limit = 100;
q.truncate_body = 5;
auto discussions = _api.get_posts_and_comments(q);
BOOST_REQUIRE_EQUAL(discussions.size(), 2u);
#ifdef IS_LOW_MEM
BOOST_CHECK_EQUAL(discussions[0].body, "");
BOOST_CHECK_EQUAL(discussions[1].body, "");
BOOST_CHECK_EQUAL(discussions[0].body_length, 0u);
BOOST_CHECK_EQUAL(discussions[1].body_length, 0u);
#else
BOOST_CHECK_EQUAL(discussions[0].body, "12345");
BOOST_CHECK_EQUAL(discussions[1].body, "abcde");
BOOST_CHECK_EQUAL(discussions[0].body_length, 7u);
BOOST_CHECK_EQUAL(discussions[1].body_length, 8u);
#endif
}
SCORUM_TEST_CASE(check_limit)
{
auto p = create_post(alice).in_block();
auto c1 = p.create_comment(bob).in_block();
auto c2 = c1.create_comment(sam).in_block();
discussion_query q;
q.limit = 2;
auto discussions = _api.get_posts_and_comments(q);
BOOST_REQUIRE_EQUAL(discussions.size(), 2u);
BOOST_CHECK_EQUAL(discussions[0].permlink, p.permlink());
BOOST_CHECK_EQUAL(discussions[1].permlink, c1.permlink());
}
SCORUM_TEST_CASE(check_same_author_comments)
{
auto p = create_post(alice).in_block_with_delay();
auto c1 = p.create_comment(alice).in_block_with_delay();
c1.create_comment(alice).in_block_with_delay();
discussion_query q;
q.limit = 100;
auto discussions = _api.get_posts_and_comments(q);
BOOST_REQUIRE_EQUAL(discussions.size(), 3u);
}
SCORUM_TEST_CASE(check_pagination)
{
/*
* Heirarchy:
*
* alice/p1
* --bob/c1
* ----sam/c2
* ----alice/c3
* sam/p2
* --alice/c4
* --bob/c5
*
* 'by_permlink' index will be sorted as follows:
* 0. alice/c3
* 1. alice/c4
* 2. alice/p1
* 3. bob/c1
* 4. bob/c5
* 5. sam/c2
* 6. sam/p2
*/
auto p1 = create_post(alice).set_permlink("p1").in_block_with_delay();
auto c1 = p1.create_comment(bob).set_permlink("c1").in_block_with_delay();
auto c2 = c1.create_comment(sam).set_permlink("c2").in_block_with_delay();
auto c3 = c1.create_comment(alice).set_permlink("c3").in_block_with_delay();
auto p2 = create_post(sam).set_permlink("p2").in_block_with_delay();
auto c4 = p2.create_comment(alice).set_permlink("c4").in_block_with_delay();
auto c5 = p2.create_comment(bob).set_permlink("c5").in_block_with_delay();
discussion_query q;
q.limit = 4;
{
auto discussions = _api.get_posts_and_comments(q);
BOOST_REQUIRE_EQUAL(discussions.size(), 4u);
BOOST_CHECK_EQUAL(discussions[0].permlink, c3.permlink());
BOOST_CHECK_EQUAL(discussions[1].permlink, c4.permlink());
BOOST_CHECK_EQUAL(discussions[2].permlink, p1.permlink());
BOOST_CHECK_EQUAL(discussions[3].permlink, c1.permlink());
}
{
q.start_author = p1.author();
q.start_permlink = p1.permlink();
q.limit = 3u;
auto discussions = _api.get_posts_and_comments(q);
BOOST_REQUIRE_EQUAL(discussions.size(), 3u);
BOOST_CHECK_EQUAL(discussions[0].permlink, p1.permlink());
BOOST_CHECK_EQUAL(discussions[1].permlink, c1.permlink());
BOOST_CHECK_EQUAL(discussions[2].permlink, c5.permlink());
}
{
q.start_author = c5.author();
q.start_permlink = c5.permlink();
q.limit = 4u;
auto discussions = _api.get_posts_and_comments(q);
BOOST_REQUIRE_EQUAL(discussions.size(), 3u);
BOOST_CHECK_EQUAL(discussions[0].permlink, c5.permlink());
BOOST_CHECK_EQUAL(discussions[1].permlink, c2.permlink());
BOOST_CHECK_EQUAL(discussions[2].permlink, p2.permlink());
}
}
BOOST_AUTO_TEST_SUITE_END()
| 31.08284 | 86 | 0.695031 | scorum |
9e618b77758ee753e3d33f0beaf5ff8aa3b9b031 | 614 | cpp | C++ | esp32/examples/ttgo_demo/main/system.cpp | joachimBurket/esp32-opencv | f485b59d7b43b0a2f77a5ab547e2597929f7094a | [
"BSD-3-Clause"
] | 56 | 2020-03-24T15:17:56.000Z | 2022-03-21T13:44:08.000Z | esp32/examples/ttgo_demo/main/system.cpp | 0015/esp32-opencv | f485b59d7b43b0a2f77a5ab547e2597929f7094a | [
"BSD-3-Clause"
] | 6 | 2021-03-08T13:41:24.000Z | 2022-02-19T08:10:24.000Z | esp32/examples/ttgo_demo/main/system.cpp | 0015/esp32-opencv | f485b59d7b43b0a2f77a5ab547e2597929f7094a | [
"BSD-3-Clause"
] | 15 | 2020-05-06T13:41:20.000Z | 2022-03-31T19:15:47.000Z | #include <esp_log.h>
#include <esp_system.h>
#include <sdkconfig.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <sys/param.h>
#include <esp32/clk.h>
#include "system.h"
#define TAG "SYSTEM"
void wait_msec(uint16_t v) {
vTaskDelay(v / portTICK_PERIOD_MS);
}
void wait_sec(uint16_t v) {
vTaskDelay(v * 1000 / portTICK_PERIOD_MS);
}
void disp_infos() {
/* Print memory information */
ESP_LOGI(TAG, "task %s stack high watermark: %d Bytes", pcTaskGetTaskName(NULL), uxTaskGetStackHighWaterMark(NULL));
ESP_LOGI(TAG, "heap left: %d Bytes", esp_get_free_heap_size());
}
| 21.928571 | 120 | 0.708469 | joachimBurket |
9e622fd05f2006fc419715ae76d2647f62cbab3c | 1,907 | hpp | C++ | include/vheis/geodesic-growth.hpp | alexbishop/Virtually-Abelian | 4f19bf39e664a6ae51ef0c7f011e2fede7762d0c | [
"MIT"
] | null | null | null | include/vheis/geodesic-growth.hpp | alexbishop/Virtually-Abelian | 4f19bf39e664a6ae51ef0c7f011e2fede7762d0c | [
"MIT"
] | null | null | null | include/vheis/geodesic-growth.hpp | alexbishop/Virtually-Abelian | 4f19bf39e664a6ae51ef0c7f011e2fede7762d0c | [
"MIT"
] | null | null | null | #pragma once
#include <map>
#include <utility>
#include <vector>
#include "SafeInt.hpp"
namespace vheis {
template <class Group>
class geodesic_growth {
public:
template <class Vector>
explicit geodesic_growth(Vector g_set);
template <class Iterator>
explicit geodesic_growth(Iterator begin, Iterator end);
std::pair<SafeInt<int>, SafeInt<unsigned long long>> next();
private:
SafeInt<int> current_size;
SafeInt<unsigned long long> running_total;
std::vector<Group> g_set;
std::map<Group, SafeInt<unsigned long long>> sphere_0;
std::map<Group, SafeInt<unsigned long long>> sphere_1;
std::map<Group, SafeInt<unsigned long long>> sphere_2;
};
}; // namespace vheis
// Implementation
namespace vheis {
template <class Group>
template <class Vector>
geodesic_growth<Group>::geodesic_growth(Vector g_set)
: geodesic_growth(g_set.begin(), g_set.end()) {}
template <class Group>
template <class Iterator>
geodesic_growth<Group>::geodesic_growth(Iterator begin, Iterator end)
: g_set(begin, end), running_total(0), current_size(-1) {}
template <class Group>
std::pair<SafeInt<int>, SafeInt<unsigned long long>>
geodesic_growth<Group>::next() {
if (current_size < 0) {
Group identity;
sphere_0[identity] = 1ull;
current_size = 0;
running_total = 1ull;
return std::make_pair(current_size, running_total);
}
sphere_2 = std::move(sphere_1);
sphere_1 = std::move(sphere_0);
sphere_0 = std::map<Group, SafeInt<unsigned long long>>();
for (const auto& [element, count] : sphere_1) {
for (auto& g : g_set) {
const auto next_element = element * g;
if (sphere_1.count(next_element) == 0 &&
sphere_2.count(next_element) == 0) {
sphere_0[next_element] += count;
running_total += count;
}
}
}
++current_size;
return std::make_pair(current_size, running_total);
}
} // namespace vheis
| 23.54321 | 69 | 0.694284 | alexbishop |
9e67cbfbd174db0408f4e99477194e09d737b4f8 | 4,357 | cpp | C++ | ShopListManager/ShopPackage.cpp | 0x4d696e68/InGameShop | 405e01defb59bd1cf22a5a5d245fdf2475b1ca36 | [
"MIT"
] | 5 | 2021-08-31T19:18:24.000Z | 2021-11-11T08:58:20.000Z | ShopListManager/ShopPackage.cpp | 0x4d696e68/InGameShop | 405e01defb59bd1cf22a5a5d245fdf2475b1ca36 | [
"MIT"
] | null | null | null | ShopListManager/ShopPackage.cpp | 0x4d696e68/InGameShop | 405e01defb59bd1cf22a5a5d245fdf2475b1ca36 | [
"MIT"
] | 2 | 2021-08-31T18:39:50.000Z | 2021-09-16T22:37:06.000Z | //************************************************************************
//
// Decompiled by @myheart, @synth3r
// <https://forum.ragezone.com/members/2000236254.html>
//
//
// FILE: ShopPackage.cpp
//
//
#include "stdafx.h"
#if(DECOMPILE_INGAMESHOP==1)
#include "ShopPackage.h"
#include "StringToken.h"
#include "StringMethod.h"
CShopPackage::CShopPackage() // OK
{
this->LeftCount = -1;
this->ProductSeqList.clear();
this->PriceSeqList.clear();
}
CShopPackage::~CShopPackage() // OK
{
}
bool CShopPackage::SetPackage(std::string strdata) // OK
{
if(strdata.empty())
return 0;
CStringToken token(strdata,"@");
if(token.hasMoreTokens()==0)
return 0;
this->ProductDisplaySeq = atoi(token.nextToken().c_str());
this->ViewOrder = atoi(token.nextToken().c_str());
this->PackageProductSeq = atoi(token.nextToken().c_str());
StringCchCopy(this->PackageProductName,sizeof(this->PackageProductName),token.nextToken().c_str());
this->PackageProductType = atoi(token.nextToken().c_str());
this->Price = atoi(token.nextToken().c_str());
StringCchCopy(this->Description,sizeof(this->Description),token.nextToken().c_str());
StringCchCopy(this->Caution,sizeof(this->Caution),token.nextToken().c_str());
this->SalesFlag = atoi(token.nextToken().c_str());
this->GiftFlag = atoi(token.nextToken().c_str());
CStringMethod::ConvertStringToDateTime(this->StartDate,token.nextToken());
CStringMethod::ConvertStringToDateTime(this->EndDate,token.nextToken());
this->CapsuleFlag = atoi(token.nextToken().c_str());
this->CapsuleCount = atoi(token.nextToken().c_str());
StringCchCopy(this->ProductCashName,sizeof(this->ProductCashName),token.nextToken().c_str());
StringCchCopy(this->PricUnitName,sizeof(this->PricUnitName),token.nextToken().c_str());
this->DeleteFlag = atoi(token.nextToken().c_str());
this->EventFlag = atoi(token.nextToken().c_str());
this->ProductAmount = atoi(token.nextToken().c_str());
this->SetProductSeqList(token.nextToken());
StringCchCopy(this->InGamePackageID,sizeof(this->InGamePackageID),token.nextToken().c_str());
this->ProductCashSeq = atoi(token.nextToken().c_str());
this->PriceCount = atoi(token.nextToken().c_str());
this->SetPriceSeqList(token.nextToken());
this->DeductMileageFlag = atoi(token.nextToken().c_str())!=0;
this->CashType = atoi(token.nextToken().c_str());
this->CashTypeFlag = atoi(token.nextToken().c_str());
return 1;
}
void CShopPackage::SetLeftCount(int nCount) // OK
{
this->LeftCount = nCount;
}
int CShopPackage::GetProductCount() // OK
{
return static_cast<int>(this->ProductSeqList.size());
}
void CShopPackage::SetProductSeqFirst() // OK
{
this->ProductSeqIter = this->ProductSeqList.begin();
}
bool CShopPackage::GetProductSeqFirst(int& ProductSeq) // OK
{
this->ProductSeqIter = this->ProductSeqList.begin();
if(this->ProductSeqIter==this->ProductSeqList.end())
return 0;
ProductSeq = (*this->ProductSeqIter);
this->ProductSeqIter++;
return 1;
}
bool CShopPackage::GetProductSeqNext(int& ProductSeq) // OK
{
if(this->ProductSeqIter==this->ProductSeqList.end())
return 0;
ProductSeq = (*this->ProductSeqIter);
this->ProductSeqIter++;
return 1;
}
int CShopPackage::GetPriceCount()
{
return static_cast<int>(this->PriceSeqList.size());
}
void CShopPackage::SetPriceSeqFirst()
{
this->PriceSeqIter = this->PriceSeqList.begin();
}
bool CShopPackage::GetPriceSeqFirst(int& PriceSeq) // OK
{
this->PriceSeqIter = this->PriceSeqList.begin();
if(this->PriceSeqIter==this->PriceSeqList.end())
return 0;
PriceSeq = (*this->PriceSeqIter);
this->PriceSeqIter++;
return 1;
}
bool CShopPackage::GetPriceSeqNext(int& PriceSeq) // OK
{
if(this->PriceSeqIter==this->PriceSeqList.end())
return 0;
PriceSeq = (*this->PriceSeqIter);
this->PriceSeqIter++;
return 1;
}
void CShopPackage::SetProductSeqList(std::string strdata) // OK
{
CStringToken token(strdata,"|");
while(true)
{
if(token.hasMoreTokens()==0)
break;
std::string data = token.nextToken();
if(data.empty()) break;
this->ProductSeqList.push_back(atoi(data.c_str()));
}
}
void CShopPackage::SetPriceSeqList(std::string strdata) // OK
{
CStringToken token(strdata,"|");
while(true)
{
if(token.hasMoreTokens()==0)
break;
std::string data = token.nextToken();
if(data.empty()) break;
this->PriceSeqList.push_back(atoi(data.c_str()));
}
}
#endif | 25.934524 | 100 | 0.706679 | 0x4d696e68 |
9e67f3cc68150c8beadda59b2c30b05adaf5e682 | 761 | cpp | C++ | Jeu/Src/ComponentsManagement/ProjectileSystem/Projectiles/Fireball.cpp | abastienIIT/Roguelike | f31935e45c968fbe608e57d0137d71251d1afc10 | [
"Apache-2.0"
] | 2 | 2021-02-07T16:07:10.000Z | 2021-02-07T23:18:43.000Z | Jeu/Src/ComponentsManagement/ProjectileSystem/Projectiles/Fireball.cpp | abastienIIT/Roguelike | f31935e45c968fbe608e57d0137d71251d1afc10 | [
"Apache-2.0"
] | 49 | 2021-02-06T19:08:07.000Z | 2021-09-14T16:43:27.000Z | Jeu/Src/ComponentsManagement/ProjectileSystem/Projectiles/Fireball.cpp | abastienIIT/Roguelike | f31935e45c968fbe608e57d0137d71251d1afc10 | [
"Apache-2.0"
] | null | null | null | #include "Fireball.h"
#include "../../Components.h"
#include "../../../Common/Globalbilboulga.h"
void Fireball::init(Entity* projectile, std::vector<Entity*>* targets)
{
ProjectileBase::init(projectile, targets);
transform->velocity = velocity;
sprite->setAsset("Fireball");
sprite->setCurrentTexture(0);
collider->tag = "Fireball";
collider->setCollider(SDL_Rect({ 0,0,32,32 }));
}
void Fireball::update()
{
distance += velocity.x;
if (distance > range ||
distance < range * -1 ||
transform->position.x < 0 ||
transform->position.y < 0 ||
transform->position.x > Globalbilboulga::getInstance()->getCurrentRoomSize().x ||
transform->position.y > Globalbilboulga::getInstance()->getCurrentRoomSize().y)
{
projectile->destroy();
}
}
| 23.060606 | 83 | 0.683311 | abastienIIT |
9e6b96d69508e8a7e4d2467a1b5af222443a5a6f | 2,712 | cpp | C++ | tests/picross_shell/test_cross_command.cpp | deqyra/Picross- | 0c81172faa8121c58bc2a88122d1cdbe661cc17e | [
"MIT"
] | null | null | null | tests/picross_shell/test_cross_command.cpp | deqyra/Picross- | 0c81172faa8121c58bc2a88122d1cdbe661cc17e | [
"MIT"
] | 1 | 2020-05-16T14:01:08.000Z | 2020-06-11T21:12:02.000Z | tests/picross_shell/test_cross_command.cpp | deqyra/PicrossEngine | 0c81172faa8121c58bc2a88122d1cdbe661cc17e | [
"MIT"
] | null | null | null | #include "../../lib/catch2/catch2.hpp"
#include <sstream>
#include "../../tools/cli/cli_streams.hpp"
#include "../../tools/micro_shell/micro_shell_codes.hpp"
#include "../../picross_shell/picross_shell_state.hpp"
#include "../../picross_shell/shell_cross_command.hpp"
#include "../../core/grid.hpp"
#include "../../core/cell_t.hpp"
#include "../../io/xml_grid_serializer.hpp"
#define TAGS "[shell][shell_command]"
namespace Picross
{
TEST_CASE("ShellCrossCommand end-to-end", TAGS)
{
std::stringstream ss;
CLIStreams s = CLIStreams(ss, ss, ss);
PicrossShellState state = PicrossShellState();
Grid g = Grid(10, 10);
Grid modifiedG = g;
state.mainGrid() = g;
state.workingGrid() = modifiedG;
ShellCrossCommand command = ShellCrossCommand();
SECTION("Bad arguments")
{
REQUIRE(command.processInput("cross aze", state, s) == SHELL_COMMAND_BAD_ARGUMENTS);
REQUIRE(command.processInput("cross aze rty", state, s) == SHELL_COMMAND_BAD_ARGUMENTS);
REQUIRE(command.processInput("cross 3 rty", state, s) == SHELL_COMMAND_BAD_ARGUMENTS);
REQUIRE(state.mainGrid() == g);
REQUIRE(state.workingGrid() == modifiedG);
std::string expected = StringTools::readFileIntoString("resources/tests/picross_shell/cross_invalid_output.txt");
REQUIRE(ss.str() == expected);
}
SECTION("Cross single cell")
{
REQUIRE(command.processInput("cross 3 5", state, s) == SHELL_COMMAND_SUCCESS);
modifiedG.crossCell(3, 5);
}
SECTION("Cross row or column range")
{
REQUIRE(command.processInput("cross 3 5:8", state, s) == SHELL_COMMAND_SUCCESS);
REQUIRE(command.processInput("cross 1:4 2", state, s) == SHELL_COMMAND_SUCCESS);
modifiedG.setCellRange(3, 3, 5, 8, CELL_CROSSED);
modifiedG.setCellRange(1, 4, 2, 2, CELL_CROSSED);
}
SECTION("Cross row or column range (reversed ranges)")
{
REQUIRE(command.processInput("cross 3 8:5", state, s) == SHELL_COMMAND_SUCCESS);
REQUIRE(command.processInput("cross 4:1 2", state, s) == SHELL_COMMAND_SUCCESS);
modifiedG.setCellRange(3, 3, 5, 8, CELL_CROSSED);
modifiedG.setCellRange(1, 4, 2, 2, CELL_CROSSED);
}
SECTION("Cross area range")
{
REQUIRE(command.processInput("cross 3:7 5:8", state, s) == SHELL_COMMAND_SUCCESS);
modifiedG.setCellRange(3, 7, 5, 8, CELL_CROSSED);
}
REQUIRE(state.mainGrid() == g);
REQUIRE(state.workingGrid() == modifiedG);
}
}
| 35.220779 | 125 | 0.614307 | deqyra |
9e6ea7609f559d3f5fa9d7c2b9f4b53b1c3d43e2 | 478 | cpp | C++ | layer2/ethernetHelper.cpp | zetwhite/SimpleEtherCATMaster | f17b04c96385d13e0cf1cdc664e4821058280273 | [
"MIT"
] | 2 | 2021-03-04T08:50:02.000Z | 2021-04-05T14:59:57.000Z | layer2/ethernetHelper.cpp | zetwhite/SimpleEtherCATMaster | f17b04c96385d13e0cf1cdc664e4821058280273 | [
"MIT"
] | null | null | null | layer2/ethernetHelper.cpp | zetwhite/SimpleEtherCATMaster | f17b04c96385d13e0cf1cdc664e4821058280273 | [
"MIT"
] | null | null | null | #include "ethernetHelper.hpp"
const int EthernetHelper::size = 14;
EthernetHelper::EthernetHelper (uint8_t srcMac[6], uint8_t destMac[6], uint16_t type){
ptr = new struct ethhdr;
memcpy(ptr->h_dest, destMac, 6);
memcpy(ptr->h_source, srcMac, 6);
ptr->h_proto = htons(type);
}
unsigned char* EthernetHelper::toArray(){
return reinterpret_cast<unsigned char*>(ptr);
}
void EthernetHelper::setType(uint16_t type){
ptr->h_proto = htons(type);
} | 26.555556 | 86 | 0.692469 | zetwhite |
9e70c3b369f80da0cad65b595b841c051f7251eb | 41,980 | cpp | C++ | engine/navigation/navigation_manager.cpp | AugustoMoura/GritEnginePR | 0f8303df7f70972036d9b555dffe08cadb473926 | [
"MIT"
] | null | null | null | engine/navigation/navigation_manager.cpp | AugustoMoura/GritEnginePR | 0f8303df7f70972036d9b555dffe08cadb473926 | [
"MIT"
] | null | null | null | engine/navigation/navigation_manager.cpp | AugustoMoura/GritEnginePR | 0f8303df7f70972036d9b555dffe08cadb473926 | [
"MIT"
] | null | null | null | //
// Copyright (c) 2009-2010 Mikko Mononen [email protected]
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
// This is a modified version of Sample_TempObstacles.cpp from Recast Demo
#define _USE_MATH_DEFINES
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <float.h>
#include <new>
#include "input_geom.h"
#include "navigation_manager.h"
#include "Recast.h"
#include "RecastDebugDraw.h"
#include "DetourAssert.h"
#include "DetourNavMesh.h"
#include "DetourNavMeshBuilder.h"
#include "DetourDebugDraw.h"
#include "DetourCommon.h"
#include "DetourTileCache.h"
#include "crowd_manager.h"
#include "RecastAlloc.h"
#include "RecastAssert.h"
#include "fastlz.h"
#include "DetourNavMeshQuery.h"
#include "DetourCrowd.h"
#ifdef WIN32
# define snprintf _snprintf
#endif
#include"navigation_system.h"
// This value specifies how many layers (or "floors") each navmesh tile is expected to have.
static const int EXPECTED_LAYERS_PER_TILE = 4;
static bool isectSegAABB(const float* sp, const float* sq,
const float* amin, const float* amax,
float& tmin, float& tmax)
{
static const float EPS = 1e-6f;
float d[3];
rcVsub(d, sq, sp);
tmin = 0; // set to -FLT_MAX to get first hit on line
tmax = FLT_MAX; // set to max distance ray can travel (for segment)
// For all three slabs
for (int i = 0; i < 3; i++)
{
if (fabsf(d[i]) < EPS)
{
// Ray is parallel to slab. No hit if origin not within slab
if (sp[i] < amin[i] || sp[i] > amax[i])
return false;
}
else
{
// Compute intersection t value of ray with near and far plane of slab
const float ood = 1.0f / d[i];
float t1 = (amin[i] - sp[i]) * ood;
float t2 = (amax[i] - sp[i]) * ood;
// Make t1 be intersection with near plane, t2 with far plane
if (t1 > t2) rcSwap(t1, t2);
// Compute the intersection of slab intersections intervals
if (t1 > tmin) tmin = t1;
if (t2 < tmax) tmax = t2;
// Exit with no collision as soon as slab intersection becomes empty
if (tmin > tmax) return false;
}
}
return true;
}
static int calcLayerBufferSize(const int gridWidth, const int gridHeight)
{
const int headerSize = dtAlign4(sizeof(dtTileCacheLayerHeader));
const int gridSize = gridWidth * gridHeight;
return headerSize + gridSize*4;
}
struct FastLZCompressor : public dtTileCacheCompressor
{
virtual int maxCompressedSize(const int bufferSize)
{
return (int)(bufferSize* 1.05f);
}
virtual dtStatus compress(const unsigned char* buffer, const int bufferSize,
unsigned char* compressed, const int /*maxCompressedSize*/, int* compressedSize)
{
*compressedSize = fastlz_compress((const void *const)buffer, bufferSize, compressed);
return DT_SUCCESS;
}
virtual dtStatus decompress(const unsigned char* compressed, const int compressedSize,
unsigned char* buffer, const int maxBufferSize, int* bufferSize)
{
*bufferSize = fastlz_decompress(compressed, compressedSize, buffer, maxBufferSize);
return *bufferSize < 0 ? DT_FAILURE : DT_SUCCESS;
}
};
struct LinearAllocator : public dtTileCacheAlloc
{
unsigned char* buffer;
size_t capacity;
size_t top;
size_t high;
LinearAllocator(const size_t cap) : buffer(0), capacity(0), top(0), high(0)
{
resize(cap);
}
~LinearAllocator()
{
dtFree(buffer);
}
void resize(const size_t cap)
{
if (buffer) dtFree(buffer);
buffer = (unsigned char*)dtAlloc(cap, DT_ALLOC_PERM);
capacity = cap;
}
virtual void reset()
{
high = dtMax(high, top);
top = 0;
}
virtual void* alloc(const size_t size)
{
if (!buffer)
return 0;
if (top+size > capacity)
return 0;
unsigned char* mem = &buffer[top];
top += size;
return mem;
}
virtual void free(void* /*ptr*/)
{
// Empty
}
};
struct MeshProcess : public dtTileCacheMeshProcess
{
InputGeom* m_geom;
inline MeshProcess() : m_geom(0)
{
}
inline void init(InputGeom* geom)
{
m_geom = geom;
}
virtual void process(struct dtNavMeshCreateParams* params,
unsigned char* polyAreas, unsigned short* polyFlags)
{
// Update poly flags from areas.
for (int i = 0; i < params->polyCount; ++i)
{
if (polyAreas[i] == DT_TILECACHE_WALKABLE_AREA)
polyAreas[i] = SAMPLE_POLYAREA_GROUND;
if (polyAreas[i] == SAMPLE_POLYAREA_GROUND ||
polyAreas[i] == SAMPLE_POLYAREA_GRASS ||
polyAreas[i] == SAMPLE_POLYAREA_ROAD)
{
polyFlags[i] = SAMPLE_POLYFLAGS_WALK;
}
else if (polyAreas[i] == SAMPLE_POLYAREA_WATER)
{
polyFlags[i] = SAMPLE_POLYFLAGS_SWIM;
}
else if (polyAreas[i] == SAMPLE_POLYAREA_DOOR)
{
polyFlags[i] = SAMPLE_POLYFLAGS_WALK | SAMPLE_POLYFLAGS_DOOR;
}
}
// Pass in off-mesh connections.
if (m_geom)
{
params->offMeshConVerts = m_geom->getOffMeshConnectionVerts();
params->offMeshConRad = m_geom->getOffMeshConnectionRads();
params->offMeshConDir = m_geom->getOffMeshConnectionDirs();
params->offMeshConAreas = m_geom->getOffMeshConnectionAreas();
params->offMeshConFlags = m_geom->getOffMeshConnectionFlags();
params->offMeshConUserID = m_geom->getOffMeshConnectionId();
params->offMeshConCount = m_geom->getOffMeshConnectionCount();
}
}
};
static const int MAX_LAYERS = 32;
struct TileCacheData
{
unsigned char* data;
int dataSize;
};
struct RasterizationContext
{
RasterizationContext() :
solid(0),
triareas(0),
lset(0),
chf(0),
ntiles(0)
{
memset(tiles, 0, sizeof(TileCacheData)*MAX_LAYERS);
}
~RasterizationContext()
{
rcFreeHeightField(solid);
delete [] triareas;
rcFreeHeightfieldLayerSet(lset);
rcFreeCompactHeightfield(chf);
for (int i = 0; i < MAX_LAYERS; ++i)
{
dtFree(tiles[i].data);
tiles[i].data = 0;
}
}
rcHeightfield* solid;
unsigned char* triareas;
rcHeightfieldLayerSet* lset;
rcCompactHeightfield* chf;
TileCacheData tiles[MAX_LAYERS];
int ntiles;
};
static int rasterizeTileLayers(BuildContext* ctx, InputGeom* geom,
const int tx, const int ty,
const rcConfig& cfg,
TileCacheData* tiles,
const int maxTiles)
{
if (!geom || !geom->getMesh() || !geom->getChunkyMesh())
{
ctx->log(RC_LOG_ERROR, "buildTile: Input mesh is not specified.");
return 0;
}
FastLZCompressor comp;
RasterizationContext rc;
const float* verts = geom->getMesh()->getVerts();
const int nverts = geom->getMesh()->getVertCount();
const rcChunkyTriMesh* chunkyMesh = geom->getChunkyMesh();
// Tile bounds.
const float tcs = cfg.tileSize * cfg.cs;
rcConfig tcfg;
memcpy(&tcfg, &cfg, sizeof(tcfg));
tcfg.bmin[0] = cfg.bmin[0] + tx*tcs;
tcfg.bmin[1] = cfg.bmin[1];
tcfg.bmin[2] = cfg.bmin[2] + ty*tcs;
tcfg.bmax[0] = cfg.bmin[0] + (tx+1)*tcs;
tcfg.bmax[1] = cfg.bmax[1];
tcfg.bmax[2] = cfg.bmin[2] + (ty+1)*tcs;
tcfg.bmin[0] -= tcfg.borderSize*tcfg.cs;
tcfg.bmin[2] -= tcfg.borderSize*tcfg.cs;
tcfg.bmax[0] += tcfg.borderSize*tcfg.cs;
tcfg.bmax[2] += tcfg.borderSize*tcfg.cs;
// Allocate voxel heightfield where we rasterize our input data to.
rc.solid = rcAllocHeightfield();
if (!rc.solid)
{
ctx->log(RC_LOG_ERROR, "buildNavigation: Out of memory 'solid'.");
return 0;
}
if (!rcCreateHeightfield(ctx, *rc.solid, tcfg.width, tcfg.height, tcfg.bmin, tcfg.bmax, tcfg.cs, tcfg.ch))
{
ctx->log(RC_LOG_ERROR, "buildNavigation: Could not create solid heightfield.");
return 0;
}
// Allocate array that can hold triangle flags.
// If you have multiple meshes you need to process, allocate
// and array which can hold the max number of triangles you need to process.
rc.triareas = new unsigned char[chunkyMesh->maxTrisPerChunk];
if (!rc.triareas)
{
ctx->log(RC_LOG_ERROR, "buildNavigation: Out of memory 'm_triareas' (%d).", chunkyMesh->maxTrisPerChunk);
return 0;
}
float tbmin[2], tbmax[2];
tbmin[0] = tcfg.bmin[0];
tbmin[1] = tcfg.bmin[2];
tbmax[0] = tcfg.bmax[0];
tbmax[1] = tcfg.bmax[2];
int cid[512];// TODO: Make grow when returning too many items.
const int ncid = rcGetChunksOverlappingRect(chunkyMesh, tbmin, tbmax, cid, 512);
if (!ncid)
{
return 0; // empty
}
for (int i = 0; i < ncid; ++i)
{
const rcChunkyTriMeshNode& node = chunkyMesh->nodes[cid[i]];
const int* tris = &chunkyMesh->tris[node.i*3];
const int ntris = node.n;
memset(rc.triareas, 0, ntris*sizeof(unsigned char));
rcMarkWalkableTriangles(ctx, tcfg.walkableSlopeAngle,
verts, nverts, tris, ntris, rc.triareas);
if (!rcRasterizeTriangles(ctx, verts, nverts, tris, rc.triareas, ntris, *rc.solid, tcfg.walkableClimb))
return 0;
}
// Once all geometry is rasterized, we do initial pass of filtering to
// remove unwanted overhangs caused by the conservative rasterization
// as well as filter spans where the character cannot possibly stand.
rcFilterLowHangingWalkableObstacles(ctx, tcfg.walkableClimb, *rc.solid);
rcFilterLedgeSpans(ctx, tcfg.walkableHeight, tcfg.walkableClimb, *rc.solid);
rcFilterWalkableLowHeightSpans(ctx, tcfg.walkableHeight, *rc.solid);
rc.chf = rcAllocCompactHeightfield();
if (!rc.chf)
{
ctx->log(RC_LOG_ERROR, "buildNavigation: Out of memory 'chf'.");
return 0;
}
if (!rcBuildCompactHeightfield(ctx, tcfg.walkableHeight, tcfg.walkableClimb, *rc.solid, *rc.chf))
{
ctx->log(RC_LOG_ERROR, "buildNavigation: Could not build compact data.");
return 0;
}
// Erode the walkable area by agent radius.
if (!rcErodeWalkableArea(ctx, tcfg.walkableRadius, *rc.chf))
{
ctx->log(RC_LOG_ERROR, "buildNavigation: Could not erode.");
return 0;
}
// (Optional) Mark areas.
const ConvexVolume* vols = geom->getConvexVolumes();
for (int i = 0; i < geom->getConvexVolumeCount(); ++i)
{
rcMarkConvexPolyArea(ctx, vols[i].verts, vols[i].nverts,
vols[i].hmin, vols[i].hmax,
(unsigned char)vols[i].area, *rc.chf);
}
rc.lset = rcAllocHeightfieldLayerSet();
if (!rc.lset)
{
ctx->log(RC_LOG_ERROR, "buildNavigation: Out of memory 'lset'.");
return 0;
}
if (!rcBuildHeightfieldLayers(ctx, *rc.chf, tcfg.borderSize, tcfg.walkableHeight, *rc.lset))
{
ctx->log(RC_LOG_ERROR, "buildNavigation: Could not build heighfield layers.");
return 0;
}
rc.ntiles = 0;
for (int i = 0; i < rcMin(rc.lset->nlayers, MAX_LAYERS); ++i)
{
TileCacheData* tile = &rc.tiles[rc.ntiles++];
const rcHeightfieldLayer* layer = &rc.lset->layers[i];
// Store header
dtTileCacheLayerHeader header;
header.magic = DT_TILECACHE_MAGIC;
header.version = DT_TILECACHE_VERSION;
// Tile layer location in the navmesh.
header.tx = tx;
header.ty = ty;
header.tlayer = i;
dtVcopy(header.bmin, layer->bmin);
dtVcopy(header.bmax, layer->bmax);
// Tile info.
header.width = (unsigned char)layer->width;
header.height = (unsigned char)layer->height;
header.minx = (unsigned char)layer->minx;
header.maxx = (unsigned char)layer->maxx;
header.miny = (unsigned char)layer->miny;
header.maxy = (unsigned char)layer->maxy;
header.hmin = (unsigned short)layer->hmin;
header.hmax = (unsigned short)layer->hmax;
dtStatus status = dtBuildTileCacheLayer(&comp, &header, layer->heights, layer->areas, layer->cons,
&tile->data, &tile->dataSize);
if (dtStatusFailed(status))
{
return 0;
}
}
// Transfer ownsership of tile data from build context to the caller.
int n = 0;
for (int i = 0; i < rcMin(rc.ntiles, maxTiles); ++i)
{
tiles[n++] = rc.tiles[i];
rc.tiles[i].data = 0;
rc.tiles[i].dataSize = 0;
}
return n;
}
void drawTiles(duDebugDraw* dd, dtTileCache* tc)
{
unsigned int fcol[6];
float bmin[3], bmax[3];
for (int i = 0; i < tc->getTileCount(); ++i)
{
const dtCompressedTile* tile = tc->getTile(i);
if (!tile->header) continue;
tc->calcTightTileBounds(tile->header, bmin, bmax);
const unsigned int col = duIntToCol(i,64);
duCalcBoxColors(fcol, col, col);
duDebugDrawBox(dd, bmin[0],bmin[1],bmin[2], bmax[0],bmax[1],bmax[2], fcol);
}
for (int i = 0; i < tc->getTileCount(); ++i)
{
const dtCompressedTile* tile = tc->getTile(i);
if (!tile->header) continue;
tc->calcTightTileBounds(tile->header, bmin, bmax);
const unsigned int col = duIntToCol(i,255);
const float pad = tc->getParams()->cs * 0.1f;
duDebugDrawBoxWire(dd, bmin[0]-pad,bmin[1]-pad,bmin[2]-pad,
bmax[0]+pad,bmax[1]+pad,bmax[2]+pad, col, 2.0f);
}
}
enum DrawDetailType
{
DRAWDETAIL_AREAS,
DRAWDETAIL_REGIONS,
DRAWDETAIL_CONTOURS,
DRAWDETAIL_MESH,
};
void drawDetail(duDebugDraw* dd, dtTileCache* tc, const int tx, const int ty, int type)
{
struct TileCacheBuildContext
{
inline TileCacheBuildContext(struct dtTileCacheAlloc* a) : layer(0), lcset(0), lmesh(0), alloc(a) {}
inline ~TileCacheBuildContext() { purge(); }
void purge()
{
dtFreeTileCacheLayer(alloc, layer);
layer = 0;
dtFreeTileCacheContourSet(alloc, lcset);
lcset = 0;
dtFreeTileCachePolyMesh(alloc, lmesh);
lmesh = 0;
}
struct dtTileCacheLayer* layer;
struct dtTileCacheContourSet* lcset;
struct dtTileCachePolyMesh* lmesh;
struct dtTileCacheAlloc* alloc;
};
dtCompressedTileRef tiles[MAX_LAYERS];
const int ntiles = tc->getTilesAt(tx,ty,tiles,MAX_LAYERS);
dtTileCacheAlloc* talloc = tc->getAlloc();
dtTileCacheCompressor* tcomp = tc->getCompressor();
const dtTileCacheParams* params = tc->getParams();
for (int i = 0; i < ntiles; ++i)
{
const dtCompressedTile* tile = tc->getTileByRef(tiles[i]);
talloc->reset();
TileCacheBuildContext bc(talloc);
const int walkableClimbVx = (int)(params->walkableClimb / params->ch);
dtStatus status;
// Decompress tile layer data.
status = dtDecompressTileCacheLayer(talloc, tcomp, tile->data, tile->dataSize, &bc.layer);
if (dtStatusFailed(status))
return;
if (type == DRAWDETAIL_AREAS)
{
duDebugDrawTileCacheLayerAreas(dd, *bc.layer, params->cs, params->ch);
continue;
}
// Build navmesh
status = dtBuildTileCacheRegions(talloc, *bc.layer, walkableClimbVx);
if (dtStatusFailed(status))
return;
if (type == DRAWDETAIL_REGIONS)
{
duDebugDrawTileCacheLayerRegions(dd, *bc.layer, params->cs, params->ch);
continue;
}
bc.lcset = dtAllocTileCacheContourSet(talloc);
if (!bc.lcset)
return;
status = dtBuildTileCacheContours(talloc, *bc.layer, walkableClimbVx,
params->maxSimplificationError, *bc.lcset);
if (dtStatusFailed(status))
return;
if (type == DRAWDETAIL_CONTOURS)
{
duDebugDrawTileCacheContours(dd, *bc.lcset, tile->header->bmin, params->cs, params->ch);
continue;
}
bc.lmesh = dtAllocTileCachePolyMesh(talloc);
if (!bc.lmesh)
return;
status = dtBuildTileCachePolyMesh(talloc, *bc.lcset, *bc.lmesh);
if (dtStatusFailed(status))
return;
if (type == DRAWDETAIL_MESH)
{
duDebugDrawTileCachePolyMesh(dd, *bc.lmesh, tile->header->bmin, params->cs, params->ch);
continue;
}
}
}
void drawDetailOverlay(const dtTileCache* tc, const int tx, const int ty, double* proj, double* model, int* view)
{
dtCompressedTileRef tiles[MAX_LAYERS];
const int ntiles = tc->getTilesAt(tx,ty,tiles,MAX_LAYERS);
if (!ntiles)
return;
(void) model;
(void) view;
(void) proj;
//const int rawSize = calcLayerBufferSize(tc->getParams()->width, tc->getParams()->height);
//char text[128];
for (int i = 0; i < ntiles; ++i)
{
const dtCompressedTile* tile = tc->getTileByRef(tiles[i]);
float pos[3];
pos[0] = (tile->header->bmin[0]+tile->header->bmax[0])/2.0f;
pos[1] = tile->header->bmin[1];
pos[2] = (tile->header->bmin[2]+tile->header->bmax[2])/2.0f;
(void) pos;
//-- TODO: replace this using Ogre "MoveableTextOverlay"
//GLdouble x, y, z;
//if (gluProject((GLdouble)pos[0], (GLdouble)pos[1], (GLdouble)pos[2],
// model, proj, view, &x, &y, &z))
//{
// snprintf(text,128,"(%d,%d)/%d", tile->header->tx,tile->header->ty,tile->header->tlayer);
// imguiDrawText((int)x, (int)y-25, IMGUI_ALIGN_CENTER, text, imguiRGBA(0,0,0,220));
// snprintf(text,128,"Compressed: %.1f kB", tile->dataSize/1024.0f);
// imguiDrawText((int)x, (int)y-45, IMGUI_ALIGN_CENTER, text, imguiRGBA(0,0,0,128));
// snprintf(text,128,"Raw:%.1fkB", rawSize/1024.0f);
// imguiDrawText((int)x, (int)y-65, IMGUI_ALIGN_CENTER, text, imguiRGBA(0,0,0,128));
//}
}
}
dtObstacleRef hitTestObstacle(const dtTileCache* tc, const float* sp, const float* sq)
{
float tmin = FLT_MAX;
const dtTileCacheObstacle* obmin = 0;
for (int i = 0; i < tc->getObstacleCount(); ++i)
{
const dtTileCacheObstacle* ob = tc->getObstacle(i);
if (ob->state == DT_OBSTACLE_EMPTY)
continue;
float bmin[3], bmax[3], t0,t1;
tc->getObstacleBounds(ob, bmin,bmax);
if (isectSegAABB(sp,sq, bmin,bmax, t0,t1))
{
if (t0 < tmin)
{
tmin = t0;
obmin = ob;
}
}
}
return tc->getObstacleRef(obmin);
}
void drawObstacles(duDebugDraw* dd, const dtTileCache* tc)
{
// Draw obstacles
for (int i = 0; i < tc->getObstacleCount(); ++i)
{
const dtTileCacheObstacle* ob = tc->getObstacle(i);
if (ob->state == DT_OBSTACLE_EMPTY) continue;
float bmin[3], bmax[3];
tc->getObstacleBounds(ob, bmin,bmax);
unsigned int col = 0;
if (ob->state == DT_OBSTACLE_PROCESSING)
col = duRGBA(255,255,0,128);
else if (ob->state == DT_OBSTACLE_PROCESSED)
col = duRGBA(255,192,0,192);
else if (ob->state == DT_OBSTACLE_REMOVING)
col = duRGBA(220,0,0,128);
duDebugDrawCylinder(dd, bmin[0],bmin[1],bmin[2], bmax[0],bmax[1],bmax[2], col);
duDebugDrawCylinderWire(dd, bmin[0],bmin[1],bmin[2], bmax[0],bmax[1],bmax[2], duDarkenCol(col), 2);
}
}
NavigationManager::NavigationManager() :
m_geom(nullptr),
m_navMesh(nullptr),
m_navMeshDrawFlags(DU_DRAWNAVMESH_OFFMESHCONS | DU_DRAWNAVMESH_CLOSEDLIST),
m_ctx(nullptr),
m_keepInterResults(false),
m_tileCache(0),
m_cacheBuildTimeMs(0),
m_cacheCompressedSize(0),
m_cacheRawSize(0),
m_cacheLayerCount(0),
m_cacheBuildMemUsage(0),
m_drawMode(DRAWMODE_NAVMESH),
m_maxTiles(0),
m_maxPolysPerTile(0),
m_tileSize(48)
{
m_navQuery = dtAllocNavMeshQuery();
m_crowd = dtAllocCrowd();
resetCommonSettings();
m_talloc = new LinearAllocator(32000);
m_tcomp = new FastLZCompressor;
m_tmproc = new MeshProcess;
m_crowdTool = new CrowdTool();
}
NavigationManager::~NavigationManager()
{
dtFreeNavMeshQuery(m_navQuery);
dtFreeNavMesh(m_navMesh);
dtFreeCrowd(m_crowd);
m_navMesh = 0;
dtFreeTileCache(m_tileCache);
}
void NavigationManager::updateMaxTiles()
{
if (m_geom)
{
const float* bmin = m_geom->getNavMeshBoundsMin();
const float* bmax = m_geom->getNavMeshBoundsMax();
// char text[64];
int gw = 0, gh = 0;
rcCalcGridSize(bmin, bmax, m_cellSize, &gw, &gh);
const int ts = (int)m_tileSize;
const int tw = (gw + ts-1) / ts;
const int th = (gh + ts-1) / ts;
// Max tiles and max polys affect how the tile IDs are caculated.
// There are 22 bits available for identifying a tile and a polygon.
int tileBits = rcMin((int)dtIlog2(dtNextPow2(tw*th*EXPECTED_LAYERS_PER_TILE)), 14);
if (tileBits > 14) tileBits = 14;
int polyBits = 22 - tileBits;
m_maxTiles = 1 << tileBits;
m_maxPolysPerTile = 1 << polyBits;
}
else
{
m_maxTiles = 0;
m_maxPolysPerTile = 0;
}
}
// this is a modified function of Recast Debug Draw
// removed tile bounds and points
static void drawMeshTilex(duDebugDraw* dd, const dtNavMesh& mesh, const dtNavMeshQuery* query,
const dtMeshTile* tile, unsigned char flags)
{
dtPolyRef base = mesh.getPolyRefBase(tile);
int tileNum = mesh.decodePolyIdTile(base);
dd->depthMask(false);
dd->begin(DU_DRAW_TRIS);
for (int i = 0; i < tile->header->polyCount; ++i)
{
const dtPoly* p = &tile->polys[i];
if (p->getType() == DT_POLYTYPE_OFFMESH_CONNECTION) // Skip off-mesh links.
continue;
const dtPolyDetail* pd = &tile->detailMeshes[i];
unsigned int col;
if (query && query->isInClosedList(base | (dtPolyRef)i))
col = duRGBA(255, 196, 0, 64);
else
{
if (flags & DU_DRAWNAVMESH_COLOR_TILES)
{
col = duIntToCol(tileNum, 128);
}
else
{
if (p->getArea() == 0) // Treat zero area type as default.
col = duRGBA(0, 192, 255, 64);
else
col = duIntToCol(p->getArea(), 64);
}
}
for (int j = 0; j < pd->triCount; ++j)
{
const unsigned char* t = &tile->detailTris[(pd->triBase + j) * 4];
for (int k = 0; k < 3; ++k)
{
if (t[k] < p->vertCount)
dd->vertex(&tile->verts[p->verts[t[k]] * 3], col);
else
dd->vertex(&tile->detailVerts[(pd->vertBase + t[k] - p->vertCount) * 3], col);
}
}
}
dd->end();
if (flags & DU_DRAWNAVMESH_OFFMESHCONS)
{
dd->begin(DU_DRAW_LINES, 2.0f);
for (int i = 0; i < tile->header->polyCount; ++i)
{
const dtPoly* p = &tile->polys[i];
if (p->getType() != DT_POLYTYPE_OFFMESH_CONNECTION) // Skip regular polys.
continue;
unsigned int col, col2;
if (query && query->isInClosedList(base | (dtPolyRef)i))
col = duRGBA(255, 196, 0, 220);
else
col = duDarkenCol(duIntToCol(p->getArea(), 220));
const dtOffMeshConnection* con = &tile->offMeshCons[i - tile->header->offMeshBase];
const float* va = &tile->verts[p->verts[0] * 3];
const float* vb = &tile->verts[p->verts[1] * 3];
// Check to see if start and end end-points have links.
bool startSet = false;
bool endSet = false;
for (unsigned int k = p->firstLink; k != DT_NULL_LINK; k = tile->links[k].next)
{
if (tile->links[k].edge == 0)
startSet = true;
if (tile->links[k].edge == 1)
endSet = true;
}
// End points and their on-mesh locations.
dd->vertex(va[0], va[1], va[2], col);
dd->vertex(con->pos[0], con->pos[1], con->pos[2], col);
col2 = startSet ? col : duRGBA(220, 32, 16, 196);
duAppendCircle(dd, con->pos[0], con->pos[1] + 0.1f, con->pos[2], con->rad, col2);
dd->vertex(vb[0], vb[1], vb[2], col);
dd->vertex(con->pos[3], con->pos[4], con->pos[5], col);
col2 = endSet ? col : duRGBA(220, 32, 16, 196);
duAppendCircle(dd, con->pos[3], con->pos[4] + 0.1f, con->pos[5], con->rad, col2);
// End point vertices.
dd->vertex(con->pos[0], con->pos[1], con->pos[2], duRGBA(0, 48, 64, 196));
dd->vertex(con->pos[0], con->pos[1] + 0.2f, con->pos[2], duRGBA(0, 48, 64, 196));
dd->vertex(con->pos[3], con->pos[4], con->pos[5], duRGBA(0, 48, 64, 196));
dd->vertex(con->pos[3], con->pos[4] + 0.2f, con->pos[5], duRGBA(0, 48, 64, 196));
// Connection arc.
duAppendArc(dd, con->pos[0], con->pos[1], con->pos[2], con->pos[3], con->pos[4], con->pos[5], 0.25f,
(con->flags & 1) ? 0.6f : 0, 0.6f, col);
}
dd->end();
}
dd->depthMask(true);
}
void duDebugDrawNavMeshx(duDebugDraw* dd, const dtNavMesh& mesh, unsigned char flags)
{
if (!dd) return;
for (int i = 0; i < mesh.getMaxTiles(); ++i)
{
const dtMeshTile* tile = mesh.getTile(i);
if (!tile->header) continue;
drawMeshTilex(dd, mesh, 0, tile, flags);
}
}
void NavigationManager::render()
{
// when loading from a navmesh file, no m_geom is loaded
bool navmesh_from_disk = false;
if (!m_geom || !m_geom->getMesh())
{
navmesh_from_disk = true;
//return;
}
DebugDrawGL dd;
// const float texScale = 1.0f / (m_cellSize * 10.0f);
if (!navmesh_from_disk)
{
if (m_drawMode != DRAWMODE_NAVMESH_TRANS &&
NavSysDebug::ShowOffmeshConnections &&
NavSysDebug::RedrawOffmeshConnections)
{
NavSysDebug::DebugObject = NavSysDebug::OffmeshConectionsObject;
NavSysDebug::DebugObject->clear();
m_geom->drawOffMeshConnections(&dd);
NavSysDebug::RedrawOffmeshConnections = false;
}
// Draw bounds
const float* bmin = m_geom->getNavMeshBoundsMin();
const float* bmax = m_geom->getNavMeshBoundsMax();
if (NavSysDebug::ShowBounds && NavSysDebug::RedrawBounds)
{
NavSysDebug::DebugObject = NavSysDebug::BoundsObject;
NavSysDebug::DebugObject->clear();
duDebugDrawBoxWire(&dd, bmin[0], bmin[1], bmin[2], bmax[0], bmax[1], bmax[2], duRGBA(255, 255, 255, 128), 1.0f);
NavSysDebug::RedrawBounds = false;
}
if (NavSysDebug::ShowTilingGrid && NavSysDebug::RedrawTilingGrid)
{
// Tiling grid.
int gw = 0, gh = 0;
rcCalcGridSize(bmin, bmax, m_cellSize, &gw, &gh);
const int tw = (gw + (int)m_tileSize - 1) / (int)m_tileSize;
const int th = (gh + (int)m_tileSize - 1) / (int)m_tileSize;
const float s = m_tileSize*m_cellSize;
NavSysDebug::DebugObject = NavSysDebug::TilingGridObject;
NavSysDebug::DebugObject->clear();
duDebugDrawGridXZ(&dd, bmin[0], bmin[1], bmin[2], tw, th, s, duRGBA(0, 0, 0, 64), 1.0f);
}
// TODO
if (NavSysDebug::ShowConvexVolumes && NavSysDebug::RedrawConvexVolumes)
{
NavSysDebug::DebugObject = NavSysDebug::ConvexVolumeObjects;
NavSysDebug::DebugObject->clear();
m_geom->drawConvexVolumes(&dd);
// temporary convex volume
drawConvexVolume(&dd);
NavSysDebug::RedrawConvexVolumes = false;
}
m_crowdTool->render();
}
//if (m_tileCache && m_drawMode == DRAWMODE_CACHE_BOUNDS)
// drawTiles(&dd, m_tileCache);
if (m_tileCache && NavSysDebug::ShowObstacles && NavSysDebug::RedrawObstacles)
{
NavSysDebug::DebugObject = NavSysDebug::ObstaclesObject;
NavSysDebug::DebugObject->clear();
drawObstacles(&dd, m_tileCache);
NavSysDebug::RedrawObstacles = false;
}
if (NavSysDebug::ShowNavmesh && NavSysDebug::RedrawNavmesh)
{
NavSysDebug::DebugObject = NavSysDebug::NavmeshObject;
NavSysDebug::DebugObject->clear();
if (m_navMesh && m_navQuery &&
(m_drawMode == DRAWMODE_NAVMESH ||
m_drawMode == DRAWMODE_NAVMESH_TRANS ||
m_drawMode == DRAWMODE_NAVMESH_BVTREE ||
m_drawMode == DRAWMODE_NAVMESH_NODES ||
m_drawMode == DRAWMODE_NAVMESH_PORTALS ||
m_drawMode == DRAWMODE_NAVMESH_INVIS))
{
if (m_drawMode != DRAWMODE_NAVMESH_INVIS)
//--duDebugDrawNavMeshWithClosedList(&dd, *m_navMesh, *m_navQuery, m_navMeshDrawFlags|DU_DRAWNAVMESH_COLOR_TILES);
//++
duDebugDrawNavMeshx(&dd, *m_navMesh, m_navMeshDrawFlags | DU_DRAWNAVMESH_COLOR_TILES);
/*
if (m_drawMode == DRAWMODE_NAVMESH_BVTREE)
duDebugDrawNavMeshBVTree(&dd, *m_navMesh);
if (m_drawMode == DRAWMODE_NAVMESH_PORTALS)
duDebugDrawNavMeshPortals(&dd, *m_navMesh);
if (m_drawMode == DRAWMODE_NAVMESH_NODES)
duDebugDrawNavMeshNodes(&dd, *m_navQuery);
*/
//duDebugDrawNavMeshPolysWithFlags(&dd, *m_navMesh, SAMPLE_POLYFLAGS_DISABLED, duRGBA(0,0,0,128));
}
NavSysDebug::RedrawNavmesh = false;
}
}
void NavigationManager::renderCachedTile(const int tx, const int ty, const int type)
{
DebugDrawGL dd;
if (m_tileCache)
drawDetail(&dd,m_tileCache,tx,ty,type);
}
void NavigationManager::renderCachedTileOverlay(const int tx, const int ty, double* proj, double* model, int* view)
{
if (m_tileCache)
drawDetailOverlay(m_tileCache, tx, ty, proj, model, view);
}
void NavigationManager::changeMesh(class InputGeom* geom)
{
m_geom = geom;
dtFreeTileCache(m_tileCache);
m_tileCache = 0;
dtFreeNavMesh(m_navMesh);
m_navMesh = 0;
}
void NavigationManager::addTempObstacle(const float* pos)
{
if (!m_tileCache)
return;
float p[3];
dtVcopy(p, pos);
p[1] -= 0.5f;
m_tileCache->addObstacle(p, 1.0f, 2.0f, 0);
}
void NavigationManager::removeTempObstacle(const float* sp, const float* sq)
{
if (!m_tileCache)
return;
dtObstacleRef ref = hitTestObstacle(m_tileCache, sp, sq);
m_tileCache->removeObstacle(ref);
}
void NavigationManager::clearAllTempObstacles()
{
if (!m_tileCache)
return;
for (int i = 0; i < m_tileCache->getObstacleCount(); ++i)
{
const dtTileCacheObstacle* ob = m_tileCache->getObstacle(i);
if (ob->state == DT_OBSTACLE_EMPTY) continue;
m_tileCache->removeObstacle(m_tileCache->getObstacleRef(ob));
}
}
bool NavigationManager::build()
{
dtStatus status;
if (!m_geom || !m_geom->getMesh())
{
m_ctx->log(RC_LOG_ERROR, "buildTiledNavigation: No vertices and triangles.");
return false;
}
m_tmproc->init(m_geom);
// Init cache
const float* bmin = m_geom->getNavMeshBoundsMin();
const float* bmax = m_geom->getNavMeshBoundsMax();
int gw = 0, gh = 0;
rcCalcGridSize(bmin, bmax, m_cellSize, &gw, &gh);
const int ts = (int)m_tileSize;
const int tw = (gw + ts-1) / ts;
const int th = (gh + ts-1) / ts;
// Generation params.
rcConfig cfg;
memset(&cfg, 0, sizeof(cfg));
cfg.cs = m_cellSize;
cfg.ch = m_cellHeight;
cfg.walkableSlopeAngle = m_agentMaxSlope;
cfg.walkableHeight = (int)ceilf(m_agentHeight / cfg.ch);
cfg.walkableClimb = (int)floorf(m_agentMaxClimb / cfg.ch);
cfg.walkableRadius = (int)ceilf(m_agentRadius / cfg.cs);
cfg.maxEdgeLen = (int)(m_edgeMaxLen / m_cellSize);
cfg.maxSimplificationError = m_edgeMaxError;
cfg.minRegionArea = (int)rcSqr(m_regionMinSize); // Note: area = size*size
cfg.mergeRegionArea = (int)rcSqr(m_regionMergeSize); // Note: area = size*size
cfg.maxVertsPerPoly = (int)m_vertsPerPoly;
cfg.tileSize = (int)m_tileSize;
cfg.borderSize = cfg.walkableRadius + 3; // Reserve enough padding.
cfg.width = cfg.tileSize + cfg.borderSize*2;
cfg.height = cfg.tileSize + cfg.borderSize*2;
cfg.detailSampleDist = m_detailSampleDist < 0.9f ? 0 : m_cellSize * m_detailSampleDist;
cfg.detailSampleMaxError = m_cellHeight * m_detailSampleMaxError;
rcVcopy(cfg.bmin, bmin);
rcVcopy(cfg.bmax, bmax);
// Tile cache params.
dtTileCacheParams tcparams;
memset(&tcparams, 0, sizeof(tcparams));
rcVcopy(tcparams.orig, bmin);
tcparams.cs = m_cellSize;
tcparams.ch = m_cellHeight;
tcparams.width = (int)m_tileSize;
tcparams.height = (int)m_tileSize;
tcparams.walkableHeight = m_agentHeight;
tcparams.walkableRadius = m_agentRadius;
tcparams.walkableClimb = m_agentMaxClimb;
tcparams.maxSimplificationError = m_edgeMaxError;
tcparams.maxTiles = tw*th*EXPECTED_LAYERS_PER_TILE;
tcparams.maxObstacles = 128;
dtFreeTileCache(m_tileCache);
m_tileCache = dtAllocTileCache();
if (!m_tileCache)
{
m_ctx->log(RC_LOG_ERROR, "buildTiledNavigation: Could not allocate tile cache.");
return false;
}
status = m_tileCache->init(&tcparams, m_talloc, m_tcomp, m_tmproc);
if (dtStatusFailed(status))
{
m_ctx->log(RC_LOG_ERROR, "buildTiledNavigation: Could not init tile cache.");
return false;
}
dtFreeNavMesh(m_navMesh);
m_navMesh = dtAllocNavMesh();
if (!m_navMesh)
{
m_ctx->log(RC_LOG_ERROR, "buildTiledNavigation: Could not allocate navmesh.");
return false;
}
dtNavMeshParams params;
memset(¶ms, 0, sizeof(params));
rcVcopy(params.orig, bmin);
params.tileWidth = m_tileSize*m_cellSize;
params.tileHeight = m_tileSize*m_cellSize;
params.maxTiles = m_maxTiles;
params.maxPolys = m_maxPolysPerTile;
status = m_navMesh->init(¶ms);
if (dtStatusFailed(status))
{
m_ctx->log(RC_LOG_ERROR, "buildTiledNavigation: Could not init navmesh.");
return false;
}
status = m_navQuery->init(m_navMesh, 2048);
if (dtStatusFailed(status))
{
m_ctx->log(RC_LOG_ERROR, "buildTiledNavigation: Could not init Detour navmesh query");
return false;
}
// Preprocess tiles.
m_ctx->resetTimers();
m_cacheLayerCount = 0;
m_cacheCompressedSize = 0;
m_cacheRawSize = 0;
for (int y = 0; y < th; ++y)
{
for (int x = 0; x < tw; ++x)
{
TileCacheData tiles[MAX_LAYERS];
memset(tiles, 0, sizeof(tiles));
int ntiles = rasterizeTileLayers(m_ctx, m_geom, x, y, cfg, tiles, MAX_LAYERS);
for (int i = 0; i < ntiles; ++i)
{
TileCacheData* tile = &tiles[i];
status = m_tileCache->addTile(tile->data, tile->dataSize, DT_COMPRESSEDTILE_FREE_DATA, 0);
if (dtStatusFailed(status))
{
dtFree(tile->data);
tile->data = 0;
continue;
}
m_cacheLayerCount++;
m_cacheCompressedSize += tile->dataSize;
m_cacheRawSize += calcLayerBufferSize(tcparams.width, tcparams.height);
}
}
}
// Build initial meshes
m_ctx->startTimer(RC_TIMER_TOTAL);
for (int y = 0; y < th; ++y)
for (int x = 0; x < tw; ++x)
m_tileCache->buildNavMeshTilesAt(x,y, m_navMesh);
m_ctx->stopTimer(RC_TIMER_TOTAL);
m_cacheBuildTimeMs = m_ctx->getAccumulatedTime(RC_TIMER_TOTAL)/1000.0f;
m_cacheBuildMemUsage = m_talloc->high;
//--
/*
const dtNavMesh* nav = m_navMesh;
int navmeshMemUsage = 0;
for (int i = 0; i < nav->getMaxTiles(); ++i)
{
const dtMeshTile* tile = nav->getTile(i);
if (tile->header)
navmeshMemUsage += tile->dataSize;
}
printf("navmeshMemUsage = %.1f kB", navmeshMemUsage/1024.0f);
*/
m_crowdTool->init(this);
return true;
}
void NavigationManager::update(const float dt)
{
m_crowdTool->update(dt);
if (!m_navMesh)
return;
if (!m_tileCache)
return;
m_tileCache->update(dt, m_navMesh);
}
void NavigationManager::getTilePos(const float* pos, int& tx, int& ty)
{
if (!m_geom) return;
const float* bmin = m_geom->getNavMeshBoundsMin();
const float ts = m_tileSize*m_cellSize;
tx = (int)((pos[0] - bmin[0]) / ts);
ty = (int)((pos[2] - bmin[2]) / ts);
}
static const int TILECACHESET_MAGIC = 'T'<<24 | 'S'<<16 | 'E'<<8 | 'T'; //'TSET';
static const int TILECACHESET_VERSION = 1;
struct TileCacheSetHeader
{
int magic;
int version;
int numTiles;
dtNavMeshParams meshParams;
dtTileCacheParams cacheParams;
};
struct TileCacheTileHeader
{
dtCompressedTileRef tileRef;
int dataSize;
};
bool NavigationManager::saveAll(const char* path)
{
if (!m_tileCache) return false;
FILE* fp = fopen(path, "wb");
if (!fp)
return false;
// Store header.
TileCacheSetHeader header;
header.magic = TILECACHESET_MAGIC;
header.version = TILECACHESET_VERSION;
header.numTiles = 0;
for (int i = 0; i < m_tileCache->getTileCount(); ++i)
{
const dtCompressedTile* tile = m_tileCache->getTile(i);
if (!tile || !tile->header || !tile->dataSize) continue;
header.numTiles++;
}
memcpy(&header.cacheParams, m_tileCache->getParams(), sizeof(dtTileCacheParams));
memcpy(&header.meshParams, m_navMesh->getParams(), sizeof(dtNavMeshParams));
fwrite(&header, sizeof(TileCacheSetHeader), 1, fp);
// Store tiles.
for (int i = 0; i < m_tileCache->getTileCount(); ++i)
{
const dtCompressedTile* tile = m_tileCache->getTile(i);
if (!tile || !tile->header || !tile->dataSize) continue;
TileCacheTileHeader tileHeader;
tileHeader.tileRef = m_tileCache->getTileRef(tile);
tileHeader.dataSize = tile->dataSize;
fwrite(&tileHeader, sizeof(tileHeader), 1, fp);
fwrite(tile->data, tile->dataSize, 1, fp);
}
fclose(fp);
return true;
}
bool NavigationManager::loadAll(const char* path)
{
FILE* fp = fopen(path, "rb");
if (!fp) return false;
// Read header.
TileCacheSetHeader header;
size_t bytes = fread(&header, sizeof(TileCacheSetHeader), 1, fp);
APP_ASSERT(bytes != sizeof(TileCacheSetHeader));
if (header.magic != TILECACHESET_MAGIC)
{
fclose(fp);
return false;
}
if (header.version != TILECACHESET_VERSION)
{
fclose(fp);
return false;
}
m_navMesh = dtAllocNavMesh();
if (!m_navMesh)
{
fclose(fp);
return false;
}
dtStatus status = m_navMesh->init(&header.meshParams);
if (dtStatusFailed(status))
{
fclose(fp);
return false;
}
m_tileCache = dtAllocTileCache();
if (!m_tileCache)
{
fclose(fp);
return false;
}
status = m_tileCache->init(&header.cacheParams, m_talloc, m_tcomp, m_tmproc);
if (dtStatusFailed(status))
{
fclose(fp);
return false;
}
// Read tiles.
for (int i = 0; i < header.numTiles; ++i)
{
TileCacheTileHeader tileHeader;
bytes = fread(&tileHeader, sizeof(tileHeader), 1, fp);
APP_ASSERT(bytes != sizeof(tileHeader));
if (!tileHeader.tileRef || !tileHeader.dataSize)
break;
unsigned char* data = (unsigned char*)dtAlloc(tileHeader.dataSize, DT_ALLOC_PERM);
if (!data) break;
memset(data, 0, tileHeader.dataSize);
bytes = fread(data, tileHeader.dataSize, 1, fp);
APP_ASSERT((long long)(bytes) != tileHeader.dataSize);
dtCompressedTileRef tile = 0;
m_tileCache->addTile(data, tileHeader.dataSize, DT_COMPRESSEDTILE_FREE_DATA, &tile);
if (tile)
m_tileCache->buildNavMeshTile(tile, m_navMesh);
}
fclose(fp);
return true;
}
void NavigationManager::resetCommonSettings()
{
m_cellSize = 0.3f;
m_cellHeight = 0.2f;
m_agentHeight = 2.0f;
m_agentRadius = 0.6f;
m_agentMaxClimb = 0.9f;
m_agentMaxSlope = 45.0f;
m_regionMinSize = 8;
m_regionMergeSize = 20;
m_edgeMaxLen = 12.0f;
m_edgeMaxError = 1.3f;
m_vertsPerPoly = 6.0f;
m_detailSampleDist = 6.0f;
m_detailSampleMaxError = 1.0f;
m_partitionType = SAMPLE_PARTITION_WATERSHED;
}
const float* NavigationManager::getBoundsMin()
{
if (!m_geom) return 0;
return m_geom->getNavMeshBoundsMin();
}
const float* NavigationManager::getBoundsMax()
{
if (!m_geom) return 0;
return m_geom->getNavMeshBoundsMax();
}
void NavigationManager::step()
{
}
bool NavigationManager::load(const char* path)
{
updateMaxTiles();
dtFreeNavMesh(m_navMesh);
dtFreeTileCache(m_tileCache);
bool result = loadAll(path);
m_navQuery->init(m_navMesh, 2048);
m_crowdTool->init(this);
return result;
}
void NavigationManager::freeNavmesh()
{
dtFreeTileCache(m_tileCache);
m_tileCache = 0;
dtFreeNavMesh(m_navMesh);
m_navMesh = 0;
}
// CONVEX VOLUMES: (from Convex Volume Tool)
// Returns true if 'c' is left of line 'a'-'b'.
inline bool left(const float* a, const float* b, const float* c)
{
const float u1 = b[0] - a[0];
const float v1 = b[2] - a[2];
const float u2 = c[0] - a[0];
const float v2 = c[2] - a[2];
return u1 * v2 - v1 * u2 < 0;
}
// Returns true if 'a' is more lower-left than 'b'.
inline bool cmppt(const float* a, const float* b)
{
if (a[0] < b[0]) return true;
if (a[0] > b[0]) return false;
if (a[2] < b[2]) return true;
if (a[2] > b[2]) return false;
return false;
}
// Calculates convex hull on xz-plane of points on 'pts',
// stores the indices of the resulting hull in 'out' and
// returns number of points on hull.
static int convexhull(const float* pts, int npts, int* out)
{
// Find lower-leftmost point.
int hull = 0;
for (int i = 1; i < npts; ++i)
if (cmppt(&pts[i * 3], &pts[hull * 3]))
hull = i;
// Gift wrap hull.
int endpt = 0;
int i = 0;
do
{
out[i++] = hull;
endpt = 0;
for (int j = 1; j < npts; ++j)
if (hull == endpt || left(&pts[hull * 3], &pts[endpt * 3], &pts[j * 3]))
endpt = j;
hull = endpt;
} while (endpt != out[0]);
return i;
}
static int pointInPoly(int nvert, const float* verts, const float* p)
{
int i, j, c = 0;
for (i = 0, j = nvert - 1; i < nvert; j = i++)
{
const float* vi = &verts[i * 3];
const float* vj = &verts[j * 3];
if (((vi[2] > p[2]) != (vj[2] > p[2])) &&
(p[0] < (vj[0] - vi[0]) * (p[2] - vi[2]) / (vj[2] - vi[2]) + vi[0]))
c = !c;
}
return c;
}
void NavigationManager::removeConvexVolume(float* p)
{
if (!m_geom || !m_geom->getMesh())
{
return;
}
int nearestIndex = -1;
const ConvexVolume* vols = m_geom->getConvexVolumes();
for (int i = 0; i < m_geom->getConvexVolumeCount(); ++i)
{
if (pointInPoly(vols[i].nverts, vols[i].verts, p) &&
p[1] >= vols[i].hmin && p[1] <= vols[i].hmax)
{
nearestIndex = i;
}
}
// If end point close enough, delete it.
if (nearestIndex != -1)
{
m_geom->deleteConvexVolume(nearestIndex);
}
}
void NavigationManager::createConvexVolume(float* p)
{
if (!m_geom || !m_geom->getMesh())
{
return;
}
// If clicked on that last pt, create the shape.
if (m_npts && rcVdistSqr(p, &m_pts[(m_npts - 1) * 3]) < rcSqr(0.2f))
{
if (m_nhull > 2)
{
// Create shape.
float verts[MAX_PTS * 3];
for (int i = 0; i < m_nhull; ++i)
rcVcopy(&verts[i * 3], &m_pts[m_hull[i] * 3]);
float minh = FLT_MAX, maxh = 0;
for (int i = 0; i < m_nhull; ++i)
minh = rcMin(minh, verts[i * 3 + 1]);
minh -= m_boxDescent;
maxh = minh + m_boxHeight;
if (m_polyOffset > 0.01f)
{
float offset[MAX_PTS * 2 * 3];
int noffset = rcOffsetPoly(verts, m_nhull, m_polyOffset, offset, MAX_PTS * 2);
if (noffset > 0)
m_geom->addConvexVolume(offset, noffset, minh, maxh, (unsigned char)m_areaType);
}
else
{
m_geom->addConvexVolume(verts, m_nhull, minh, maxh, (unsigned char)m_areaType);
}
}
m_npts = 0;
m_nhull = 0;
}
else
{
// Add new point
if (m_npts < MAX_PTS)
{
rcVcopy(&m_pts[m_npts * 3], p);
m_npts++;
// Update hull.
if (m_npts > 1)
m_nhull = convexhull(m_pts, m_npts, m_hull);
else
m_nhull = 0;
}
}
}
// Temporary convex volume
void NavigationManager::drawConvexVolume(DebugDrawGL* dd)
{
// Find height extents of the shape.
float minh = FLT_MAX, maxh = 0;
for (int i = 0; i < m_npts; ++i)
minh = rcMin(minh, m_pts[i * 3 + 1]);
minh -= m_boxDescent;
maxh = minh + m_boxHeight;
dd->begin(DU_DRAW_POINTS, 4.0f);
for (int i = 0; i < m_npts; ++i)
{
unsigned int col = duRGBA(255, 255, 255, 255);
if (i == m_npts - 1)
col = duRGBA(240, 32, 16, 255);
dd->vertex(m_pts[i * 3 + 0], m_pts[i * 3 + 1] + 0.1f, m_pts[i * 3 + 2], col);
}
dd->end();
dd->begin(DU_DRAW_LINES, 2.0f);
for (int i = 0, j = m_nhull - 1; i < m_nhull; j = i++)
{
const float* vi = &m_pts[m_hull[j] * 3];
const float* vj = &m_pts[m_hull[i] * 3];
dd->vertex(vj[0], minh, vj[2], duRGBA(255, 255, 255, 64));
dd->vertex(vi[0], minh, vi[2], duRGBA(255, 255, 255, 64));
dd->vertex(vj[0], maxh, vj[2], duRGBA(255, 255, 255, 64));
dd->vertex(vi[0], maxh, vi[2], duRGBA(255, 255, 255, 64));
dd->vertex(vj[0], minh, vj[2], duRGBA(255, 255, 255, 64));
dd->vertex(vj[0], maxh, vj[2], duRGBA(255, 255, 255, 64));
}
dd->end();
}
| 26.910256 | 118 | 0.676941 | AugustoMoura |
9e716ed1b82e835dbbed3a6fa2d870d54d83a0f6 | 21,662 | cpp | C++ | src/ui/ui.cpp | EnthDev/dedicatedslave | d8c097082d9e1ae11740cd917a9e9d449be457d2 | [
"MIT"
] | 7 | 2018-03-05T02:58:13.000Z | 2019-01-06T13:11:50.000Z | src/ui/ui.cpp | EnthDev/dedicatedslave | d8c097082d9e1ae11740cd917a9e9d449be457d2 | [
"MIT"
] | 3 | 2017-12-21T00:29:38.000Z | 2019-04-24T01:05:12.000Z | src/ui/ui.cpp | EnthDev/dedicatedslave | d8c097082d9e1ae11740cd917a9e9d449be457d2 | [
"MIT"
] | 1 | 2019-03-07T11:41:55.000Z | 2019-03-07T11:41:55.000Z | // Includes
#include <QtWidgets>
#include "ui.h"
DedicatedSlaveUi::DedicatedSlaveUi(const QString &dir, QWidget *parent)
: QWidget(parent), app_slcInstPos(new int[2])
{
app_slcInstPos[0] = -1;
parentWin = qobject_cast<QMainWindow*>(parent);
if(parentWin != 0 ) { // After casting parent widget QMainWindow, need to check if is not null (Async)
// Core
qInfo() << "(CLASS)\tInitializing 'DedicatedSlaveApp' class...";
ds_app = new DedicatedSlaveApp(dir, this);
qInfo() << "(CLASS)\t'DedicatedSlaveApp' initialized.";
//QObject::connect(&ds_app, SIGNAL(signal_verifyComplete(int)), this);
// Variables
app_dir = dir;
// Actions
initActions();
qInfo() << "\tActions initialized.";
// Main Components
// Instance List
ui_instanceTable = new QTableWidget;
ui_instanceTable->setRowCount(0);
ui_instanceTable->setColumnCount(3);
QStringList header;
header << "Name" << "Game" << "Status";
ui_instanceTable->setHorizontalHeaderLabels(header);
connect(ui_instanceTable, SIGNAL(cellClicked(int,int)), this, SLOT(slot_instanceSelect(int, int)));
// Text Edit
ui_textEdit = new QTextEdit(this);
ui_textEdit->setAlignment(Qt::AlignCenter);
// Info Label
ui_infoLabel = new QLabel(tr("<i>Welcome to DedicatedSlave, this is the information label</i>"));
ui_infoLabel->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken);
ui_infoLabel->setAlignment(Qt::AlignCenter);
// Options Dock
dockOptions = new UiDockOptions("Instance Options", parentWin);
// Filesystem Dock
dockFileSystem = new UiDockFileSystem("Workspace File System", parentWin);
qInfo() << "\tMain Components initialized.";
// Toolbar
QToolBar *fileToolBar = parentWin->addToolBar(tr("File Toolbar"));
fileToolBar->addAction(actNewInst);
fileToolBar->addAction(actRemoveInst);
fileToolBar->addAction(actRunInst);
fileToolBar->addAction(actVerifyInst);
QToolBar *editToolBar = parentWin->addToolBar(tr("Edit Toolbar"));
editToolBar->addAction(actUndo);
qInfo() << "\tToolbar initialized.";
// Menus
initMenus();
qInfo() << "\tMenus initialized.";
// Toggle View Menus
menuView->addAction(dockOptions->toggleViewAction());
menuView->addAction(dockFileSystem->toggleViewAction());
menuView->addAction(fileToolBar->toggleViewAction());
menuView->addAction(editToolBar->toggleViewAction());
// Main
QVBoxLayout *layout = new QVBoxLayout;
QWidget *topFiller = new QWidget;
topFiller->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum);
QWidget *bottomFiller = new QWidget;
bottomFiller->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum);
layout->setMargin(5);
layout->addWidget(topFiller);
layout->addWidget(ui_textEdit);
layout->addWidget(ui_instanceTable);
layout->addWidget(ui_infoLabel);
/* TODO: Causing segfault
** #0 0x00007ffff74c5040 in QLayout::addChildWidget(QWidget*) () from libQt5Widgets.so.5
** #1 0x00007ffff74bcb8c in QBoxLayout::insertWidget(int, QWidget*, int, QFlags<Qt::AlignmentFlag>) () from libQt5Widgets.so.5
** #2 0x000055555556fcf5 in DedicatedSlaveUi::DedicatedSlaveUi (this=0x555555861320, dir=..., parent=<optimized out>) at src/ui/ui.cpp:81
** #3 0x0000555555566d82 in MainWindow::MainWindow (this=0x7fffffffd900, dir=..., parent=<optimized out>, flags=...) at src/ui/mainwindow.cpp:7
** #4 0x000055555556639e in main (argc=<optimized out>, argv=<optimized out>) at src/ui/main.cpp:84
*/
//layout->addWidget(ui_progressBar);
layout->addWidget(bottomFiller);
setLayout(layout);
// Parent properties
ui_progressBar = new QProgressBar(this);
QLabel *a = new QLabel(this);
parentWin->statusBar()->addPermanentWidget(ui_progressBar);
parentWin->statusBar()->addPermanentWidget(a);
ui_progressBar->setValue(75);
parentWin->statusBar()->showMessage(tr("A context menu is available by right-clicking"));
parentWin->addDockWidget(Qt::RightDockWidgetArea, dockOptions);
parentWin->addDockWidget(Qt::RightDockWidgetArea, dockFileSystem);
parentWin->setCentralWidget(this);
qInfo() << "\tParent properties has been set.";
// Populate
updateModelInstTable();
updateEdit(); // ????? remove
}
}
void DedicatedSlaveUi::contextMenuEvent(QContextMenuEvent *event){
this->getContextMenu()->exec(event->globalPos());
}
QMenu* DedicatedSlaveUi::getContextMenu(){
QMenu *menu = new QMenu(this);
menu->addAction(actCut);
menu->addAction(actCopy);
menu->addAction(actPaste);
return menu;
}
void DedicatedSlaveUi::updateModelInstTable(){
while (ui_instanceTable->rowCount() > 0){
ui_instanceTable->removeRow(0);
}
QHashIterator<QString, GameInstance*> i = ds_app->listInst();
i.toFront();
while (i.hasNext()) {
i.next();
if(!i.key().isEmpty()){
ui_instanceTable->insertRow(ui_instanceTable->rowCount());
QTableWidgetItem *item0 = new QTableWidgetItem(i.key());
QTableWidgetItem *item1 = new QTableWidgetItem(i.value()->getGameId());
QTableWidgetItem *item2 = new QTableWidgetItem(QString::number(i.value()->getStatus()));
ui_instanceTable->setItem(ui_instanceTable->rowCount()-1, 0, item0);
ui_instanceTable->setItem(ui_instanceTable->rowCount()-1, 1, item1);
ui_instanceTable->setItem(ui_instanceTable->rowCount()-1, 2, item2);
}
}
}
void DedicatedSlaveUi::updateProgressBar(int value){
ui_progressBar->setValue(value);
}
void DedicatedSlaveUi::resetProgressBar(){
ui_progressBar->reset();
}
void DedicatedSlaveUi::updateEdit(){
ui_textEdit->clear();
QTextCursor cursor(ui_textEdit->textCursor());
cursor.movePosition(QTextCursor::Start);
QTextFrame *topFrame = cursor.currentFrame();
QTextFrameFormat topFrameFormat = topFrame->frameFormat();
topFrameFormat.setPadding(16);
topFrame->setFrameFormat(topFrameFormat);
QTextCharFormat textFormat;
QTextCharFormat boldFormat;
boldFormat.setFontWeight(QFont::Bold);
QTextCharFormat italicFormat;
italicFormat.setFontItalic(true);
QTextTableFormat tableFormat;
tableFormat.setBorder(1);
tableFormat.setCellPadding(16);
tableFormat.setAlignment(Qt::AlignRight);
cursor.insertTable(1, 1, tableFormat);
cursor.insertText("The Firm", boldFormat);
cursor.insertBlock();
cursor.insertText("321 City Street", textFormat);
cursor.insertBlock();
cursor.insertText("Industry Park");
cursor.insertBlock();
cursor.insertText("Some Country");
cursor.setPosition(topFrame->lastPosition());
cursor.insertText(QDate::currentDate().toString("d MMMM yyyy"), textFormat);
cursor.insertBlock();
cursor.insertBlock();
cursor.insertText("Dear ", textFormat);
cursor.insertText("NAME", italicFormat);
cursor.insertText(",", textFormat);
for (int i = 0; i < 3; ++i)
cursor.insertBlock();
cursor.insertText(tr("Yours sincerely,"), textFormat);
for (int i = 0; i < 3; ++i)
cursor.insertBlock();
cursor.insertText("The Boss", textFormat);
cursor.insertBlock();
cursor.insertText("ADDRESS", italicFormat);
updateEdit1("BLABLABLA 1");
updateEdit2("BLABLABLA 2");
}
void DedicatedSlaveUi::updateEdit1(const QString &customer){
if (customer.isEmpty())
return;
QStringList customerList = customer.split(", ");
QTextDocument *document = ui_textEdit->document();
QTextCursor cursor = document->find("NAME");
if (!cursor.isNull()) {
cursor.beginEditBlock();
cursor.insertText(customerList.at(0));
QTextCursor oldcursor = cursor;
cursor = document->find("ADDRESS");
if (!cursor.isNull()) {
for (int i = 1; i < customerList.size(); ++i) {
cursor.insertBlock();
cursor.insertText(customerList.at(i));
}
cursor.endEditBlock();
} else {
oldcursor.endEditBlock();
}
}
}
void DedicatedSlaveUi::updateEdit2(const QString ¶graph){
if (paragraph.isEmpty())
return;
QTextDocument *document = ui_textEdit->document();
QTextCursor cursor = document->find(tr("Yours sincerely,"));
if (cursor.isNull())
return;
cursor.beginEditBlock();
cursor.movePosition(QTextCursor::PreviousBlock, QTextCursor::MoveAnchor, 2);
cursor.insertBlock();
cursor.insertText(paragraph);
cursor.insertBlock();
cursor.endEditBlock();
}
void DedicatedSlaveUi::initActions(){
// https://specifications.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html
// New Instance
const QIcon newIcon = QIcon::fromTheme("list-add", QIcon(":/images/new.png"));
actNewInst = new QAction(newIcon, tr("&New"), this);
actNewInst->setShortcuts(QKeySequence::New);
actNewInst->setStatusTip(tr("Add a new instance"));
connect(actNewInst, &QAction::triggered, this, &DedicatedSlaveUi::conn_actionNewInstDialog);
// Remove Instance
const QIcon removeIcon = QIcon::fromTheme("list-remove", QIcon(":/images/new.png"));
actRemoveInst = new QAction(removeIcon, tr("&Remove"), this);
actRemoveInst->setShortcuts(QKeySequence::New);
actRemoveInst->setStatusTip(tr("Remove a new instance"));
connect(actRemoveInst, &QAction::triggered, this, &DedicatedSlaveUi::conn_actionRemoveInst);
// Verify Instance
const QIcon verifyIcon = QIcon::fromTheme("emblem-downloads", QIcon(":/images/new.png"));
actVerifyInst = new QAction(verifyIcon, tr("&Verify"), this);
actVerifyInst->setStatusTip(tr("Verify a instance"));
connect(actVerifyInst, &QAction::triggered, this, &DedicatedSlaveUi::conn_actionVerifyInst);
// Run Instance
const QIcon runIcon = QIcon::fromTheme("go-next", QIcon(":/images/new.png"));
actRunInst = new QAction(runIcon, tr("&Run"), this);
actRunInst->setStatusTip(tr("Run a new instance"));
connect(actRunInst, &QAction::triggered, this, &DedicatedSlaveUi::conn_actionRunInst);
// Backup
actBackupInst = new QAction(tr("&Backup"), this);
actBackupInst->setStatusTip(tr("Backup the selected instance to disk"));
connect(actBackupInst, &QAction::triggered, this, &DedicatedSlaveUi::conn_actionBackup);
// Restore
actRestoreInst = new QAction(tr("&Restore"), this);
actRestoreInst->setStatusTip(tr("Restore the selected instance to disk"));
connect(actRestoreInst, &QAction::triggered, this, &DedicatedSlaveUi::conn_actionRestore);
// Exit/Close
actExit = new QAction(tr("E&xit"), this);
actExit->setShortcuts(QKeySequence::Quit);
actExit->setStatusTip(tr("Exit the application"));
connect(actExit, &QAction::triggered, this, &QWidget::close);
// Undo
const QIcon undoIcon = QIcon::fromTheme("edit-undo", QIcon(":/images/undo.png"));
actUndo = new QAction(undoIcon, tr("&Undo"), this);
actUndo->setShortcuts(QKeySequence::Undo);
actUndo->setStatusTip(tr("Undo the last operation"));
connect(actUndo, &QAction::triggered, this, &DedicatedSlaveUi::conn_actionUndo);
// Redo
actRedo = new QAction(tr("&Redo"), this);
actRedo->setShortcuts(QKeySequence::Redo);
actRedo->setStatusTip(tr("Redo the last operation"));
connect(actRedo, &QAction::triggered, this, &DedicatedSlaveUi::conn_actionRedo);
// Cut
actCut = new QAction(tr("Cu&t"), this);
actCut->setShortcuts(QKeySequence::Cut);
actCut->setStatusTip(tr("Cut the current selection's contents to the clipboard"));
connect(actCut, &QAction::triggered, this, &DedicatedSlaveUi::conn_actionCut);
// Copy
actCopy = new QAction(tr("&Copy"), this);
actCopy->setShortcuts(QKeySequence::Copy);
actCopy->setStatusTip(tr("Copy the current selection's contents to the clipboard"));
connect(actCopy, &QAction::triggered, this, &DedicatedSlaveUi::conn_actionCopy);
// Paste
actPaste = new QAction(tr("&Paste"), this);
actPaste->setShortcuts(QKeySequence::Paste);
actPaste->setStatusTip(tr("Paste the clipboard's contents into the current selection"));
connect(actPaste, &QAction::triggered, this, &DedicatedSlaveUi::conn_actionPaste);
// Options
actOptions = new QAction(tr("&Options..."), this);
QList<QKeySequence> optionsShortcuts;
optionsShortcuts.append(QKeySequence(Qt::CTRL + Qt::Key_F));
optionsShortcuts.append(QKeySequence(Qt::CTRL + Qt::Key_P));
actOptions->setShortcuts(optionsShortcuts);
actOptions->setStatusTip(tr("Open the config options dialog"));
connect(actOptions, &QAction::triggered, this, &DedicatedSlaveUi::conn_actionOptions);
// Help
actHelp = new QAction(tr("&Help"), this);
actHelp->setStatusTip(tr("Getting started with DedicatedSlave"));
connect(actHelp, &QAction::triggered, this, &DedicatedSlaveUi::conn_actionHelp);
// Check Updates
actCheckUpdates = new QAction(tr("&Check Updates"), this);
actCheckUpdates->setStatusTip(tr("Check if exists new updates"));
connect(actCheckUpdates, &QAction::triggered, this, &DedicatedSlaveUi::conn_actionCheckUpdates);
// About
actAbout = new QAction(tr("&About"), this);
actAbout->setStatusTip(tr("Show the application's About box"));
connect(actAbout, &QAction::triggered, this, &DedicatedSlaveUi::conn_actionAbout);
// About Qt
actAboutQt = new QAction(tr("About &Qt"), this);
actAboutQt->setStatusTip(tr("Show the Qt library's About box"));
connect(actAboutQt, &QAction::triggered, qApp, &QApplication::aboutQt);
connect(actAboutQt, &QAction::triggered, this, &DedicatedSlaveUi::conn_actionAboutQt);
}
/*!
* \brief Function that initializate menus
*/
void DedicatedSlaveUi::initMenus(){
// File Menu
// if(parentWin != 0) {
//qDebug() << "\tQ_FUNC_INFO" << Q_FUNC_INFO;
// qInfo() << "Q_FUNC_INFO:" << Q_FUNC_INFO;
// QMenuBar *menu = parentWin->menuBar();
menuFile = parentWin->menuBar()->addMenu(tr("&File"));
menuFile->addAction(actNewInst);
menuFile->addAction(actRemoveInst);
menuFile->addAction(actRunInst);
menuFile->addAction(actVerifyInst);
menuFile->addAction(actBackupInst);
menuFile->addAction(actRestoreInst);
menuFile->addSeparator();
menuFile->addAction(actExit);
// Edit Menu
menuEdit = parentWin->menuBar()->addMenu(tr("&Edit"));
menuEdit->addAction(actUndo);
menuEdit->addAction(actRedo);
menuEdit->addSeparator();
menuEdit->addAction(actCut);
menuEdit->addAction(actCopy);
menuEdit->addAction(actPaste);
menuEdit->addSeparator();
// View Menu
menuView = parentWin->menuBar()->addMenu(tr("&View"));
// Tools Menu
menuTools = parentWin->menuBar()->addMenu(tr("&Tools"));
menuTools->addSeparator();
menuTools->addAction(actOptions);
// Help Menu
menuHelp = parentWin->menuBar()->addMenu(tr("&Help"));
menuHelp->addAction(actHelp);
menuHelp->addAction(actCheckUpdates);
menuHelp->addSeparator();
menuHelp->addAction(actAbout);
menuHelp->addAction(actAboutQt);
}
void DedicatedSlaveUi::conn_actionHelp(){
QDesktopServices::openUrl(QUrl("https://enthdev.github.io/dedicatedslave/user-guide/gettingstarted/"));
ui_infoLabel->setText(tr("Invoked <b>Help|Help</b>"));
}
void DedicatedSlaveUi::conn_actionCheckUpdates(){
ui_infoLabel->setText(tr("Invoked <b>Help|CheckUpdates</b>"));
}
void DedicatedSlaveUi::conn_actionAbout(){
ui_infoLabel->setText(tr("Invoked <b>Help|About</b>"));
QMessageBox::about(this, tr("About Dedicated Slave"),
tr("The <b>Dedicated Slave</b> is a cross platform desktop app "
"tool to manage steam dedicated game servers with SteamCMD."
"<p><a href='https://github.com/EnthDev/dedicatedslave'>Github Repository</a>"
"<p><a href='https://enthdev.github.io/dedicatedslave/'>Website</a>"
"<p><a href='https://enthdev.github.io/dedicatedslave/user-guide/gettingstarted/'>Website - Getting Started</a>"));
}
void DedicatedSlaveUi::conn_actionAboutQt(){
ui_infoLabel->setText(tr("Invoked <b>Help|About Qt</b>"));
}
void DedicatedSlaveUi::conn_actionVerifyInst(){
if(app_slcInstPos[0] != -1 && app_slcInstPos[1] != -1){
QString instName = ui_instanceTable->item(app_slcInstPos[0], 0)->text();
if(ds_app->hasInst(instName)){
ds_app->verifyInstProgress(ui_instanceTable->item(app_slcInstPos[0], 0)->text());
updateModelInstTable();
}else{
ui_infoLabel->setText(QString("Error: Instance '%1' does not exist").arg(instName));
}
}
}
void DedicatedSlaveUi::conn_actionRunInst(){
if(app_slcInstPos[0] != -1 && app_slcInstPos[1] != -1){
QString instName = ui_instanceTable->item(app_slcInstPos[0], 0)->text();
if(ds_app->hasInst(instName)){
if(ds_app->hasReadyInst(instName)){
ds_app->runInst(instName);
updateModelInstTable();
}else{
ui_infoLabel->setText(QString("Error: Instance '%1' is not ready to run").arg(instName));
}
}else{
ui_infoLabel->setText(QString("Error: Instance '%1' does not exist").arg(instName));
}
}
}
void DedicatedSlaveUi::conn_actionNewInstDialog(){
ui_newInstGroup = new QGroupBox;
QLabel *labeltest = new QLabel(tr("Instance Game:"));
// QRadioButton *radio = new QRadioButton(tr("Add Instance"));
QVBoxLayout *vbox = new QVBoxLayout;
QComboBox *comboGamesList = new QComboBox;
connect(comboGamesList, SIGNAL(activated(int)), this, SLOT(slot_addInstanceCombo(int)));
QPushButton *addButton = new QPushButton("OK");
connect(addButton, &QAbstractButton::clicked, this, &DedicatedSlaveUi::conn_actionNewInst);
QLineEdit *instNameLineEdit = new QLineEdit;
QLineEdit *instDirLineEdit = new QLineEdit("etcinstances");
connect(instNameLineEdit, SIGNAL(textEdited(QString)), this, SLOT(slot_addInstNameEdit(QString)));
connect(instDirLineEdit, SIGNAL(textEdited(QString)), this, SLOT(slot_addInstDirEdit(QString)));
// Unlike textChanged(), this signal is not emitted when the text is changed programmatically, for example, by calling setText().
comboGamesList->addItem("-");
comboGamesList->addItem("Counter-Strike: Global Offensive"); // 1
comboGamesList->addItem("Rust"); // 2
// vbox->addWidget(radio);
vbox->addWidget(labeltest);
vbox->addWidget(comboGamesList);
vbox->addWidget(addButton);
vbox->addWidget(instNameLineEdit);
vbox->addWidget(instDirLineEdit);
ui_newInstGroup->setLayout(vbox);
ui_newInstGroup->show();
ui_infoLabel->setText(tr("Invoked <b>File|New</b>"));
}
void DedicatedSlaveUi::conn_actionRemoveInst(){
if(app_slcInstPos[0] != -1 && app_slcInstPos[1] != -1){
QMessageBox::StandardButton removeReply;
removeReply = QMessageBox::question(this,
"Remove Instace",
QString("Do you really want to remove instance '%1'").arg(ui_instanceTable->item(app_slcInstPos[0], 0)->text()),
QMessageBox::Yes|QMessageBox::No);
if(removeReply == QMessageBox::Yes){
QMessageBox::StandardButton removeFileReply;
removeFileReply = QMessageBox::question(this,
"Remove Instace",
"Do you want to remove all instance files?",
QMessageBox::Yes|QMessageBox::No);
if(removeFileReply == QMessageBox::Yes)
ds_app->removeInst(ui_instanceTable->item(app_slcInstPos[0], 0)->text(), true);
else
ds_app->removeInst(ui_instanceTable->item(app_slcInstPos[0], 0)->text(), false);
updateModelInstTable();
}
}
}
void DedicatedSlaveUi::conn_actionNewInst(){
ui_newInstGroup->hide();
if(!app_newIntsName.isEmpty()){
if(!ds_app->hasInst(app_newIntsName)){
ds_app->addInst(app_newIntsName, app_newInstGame);
updateModelInstTable();
app_newInstGame = "";
ui_infoLabel->setText(QString("Invoked New Instance <b>%1</b> (<b>%2</b>) - <b>%3</b>").arg(app_newIntsName).arg(ui_instanceTable->rowCount()-1).arg(app_newInstGame));
}else{
ui_infoLabel->setText(QString("Error: New Instance name already exist (<b>%1</b>)").arg(app_newIntsName));
}
}else{
ui_infoLabel->setText("Error: New Instance name cannot be empty.");
}
}
void DedicatedSlaveUi::conn_actionRestore(){
ui_infoLabel->setText(tr("Invoked <b>File|Restore</b>"));
}
void DedicatedSlaveUi::conn_actionBackup(){
ui_infoLabel->setText(tr("Invoked <b>File|Save</b>"));
QMimeDatabase mimeDatabase;
QString fileName = QFileDialog::getSaveFileName(this,
tr("Choose a file name"), ".",
mimeDatabase.mimeTypeForName("text/html").filterString());
if (fileName.isEmpty())
return;
QFile file(fileName);
if (!file.open(QFile::WriteOnly | QFile::Text)) {
QMessageBox::warning(this, tr("Dock Widgets"),
tr("Cannot write file %1:\n%2.")
.arg(QDir::toNativeSeparators(fileName), file.errorString()));
return;
}
QTextStream out(&file);
QApplication::setOverrideCursor(Qt::WaitCursor);
out << ui_textEdit->toHtml();
QApplication::restoreOverrideCursor();
parentWin->statusBar()->showMessage(tr("Saved '%1'").arg(fileName), 2000);
}
void DedicatedSlaveUi::conn_actionUndo(){
ui_infoLabel->setText(tr("Invoked <b>Edit|Undo</b>"));
ui_textEdit->document()->undo();
}
void DedicatedSlaveUi::conn_actionRedo(){
ui_infoLabel->setText(tr("Invoked <b>Edit|Redo</b>"));
}
void DedicatedSlaveUi::conn_actionCut(){
ui_infoLabel->setText(tr("Invoked <b>Edit|Cut</b>"));
}
void DedicatedSlaveUi::conn_actionCopy(){
ui_infoLabel->setText(tr("Invoked <b>Edit|Copy</b>"));
}
void DedicatedSlaveUi::conn_actionPaste(){
ui_infoLabel->setText(tr("Invoked <b>Edit|Paste</b>"));
}
void DedicatedSlaveUi::conn_actionOptions(){
ui_infoLabel->setText(tr("Invoked <b>Tools|Options...</b>"));
ui_dialogConfig = new ConfigDialog(ds_app);
ui_dialogConfig->show();
}
void DedicatedSlaveUi::slot_addInstanceCombo(int index){
switch (index) {
case 1:
app_newInstGame = "csgo";
break;
case 2:
app_newInstGame = "rust";
break;
}
}
void DedicatedSlaveUi::slot_addInstNameEdit(QString instanceName){
app_newIntsName = instanceName;
}
void DedicatedSlaveUi::slot_addInstDirEdit(QString instanceDir){
app_newInstDir = instanceDir;
}
void DedicatedSlaveUi::slot_instanceSelect(int row, int column){
app_slcInstPos[0] = row;
app_slcInstPos[1] = column;
QHashIterator<QString, GameInstance*> i = ds_app->listInst();
while(i.hasNext()){
i.next();
if(i.key() == ui_instanceTable->item(app_slcInstPos[0], 0)->text()){
GameInstance *gi = i.value();
dockOptions->updateModelInst(i.key(), gi->getServerName(), gi->getNumPlayers());
}
}
ui_infoLabel->setText(QString("Selected Inst <b>%1</b>:<b>%2</b>").arg(row).arg(column));
}
| 36.591216 | 170 | 0.728188 | EnthDev |
9e72f674499a8b8ec62adb88341d59099f91252e | 8,949 | cpp | C++ | SimSpark/rcssserver3d/plugin/soccer/hmdp_effector/hmdpeffector.cpp | IllyasvielEin/Robocup3dInstaller | 12e91d9372dd08a92feebf98e916c98bc2242ff4 | [
"MIT"
] | null | null | null | SimSpark/rcssserver3d/plugin/soccer/hmdp_effector/hmdpeffector.cpp | IllyasvielEin/Robocup3dInstaller | 12e91d9372dd08a92feebf98e916c98bc2242ff4 | [
"MIT"
] | null | null | null | SimSpark/rcssserver3d/plugin/soccer/hmdp_effector/hmdpeffector.cpp | IllyasvielEin/Robocup3dInstaller | 12e91d9372dd08a92feebf98e916c98bc2242ff4 | [
"MIT"
] | null | null | null | /* -*- mode: c++; c-basic-offset: 4; indent-tabs-mode: nil -*-
this file is part of rcssserver3D
Copyright (C) 2002,2003 Koblenz University
Copyright (C) 2003 RoboCup Soccer Server 3D Maintenance Group
Copyright (C) 2008 N. Michael Mayer, email: [email protected]
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "hmdpeffector.h"
#include "hmdpperceptor.h"
#include "hmdpaction.h"
#include <zeitgeist/logserver/logserver.h>
#include <oxygen/gamecontrolserver/actionobject.h>
#include <oxygen/agentaspect/jointeffector.h>
#include <oxygen/physicsserver/hingejoint.h>
using namespace boost;
using namespace oxygen;
using namespace salt;
using namespace HMDP;
//! Handler for HMDP Effector and Perceptor back and forward
HMDPPerceptor *hmdpPerceptorHandle = NULL;
HMDPEffector *hmdpEffectorHandle = NULL;
namespace HMDP
{
extern "C"
{
using namespace HMDP;
int lock;
extern Hmdl *hmdl;
extern Base_data *base_data;
extern int readChar;
void disableIRQ(); //! mimicks IRQ functionality
void enableIRQ();
}
}
HMDPEffector::HMDPEffector(): oxygen::Effector()
{
ifActive = false;
}
HMDPEffector::~HMDPEffector()
{
HMDP::lock = 0;
}
void HMDPEffector::PrePhysicsUpdateInternal(float deltaTime)
{
if (iter == 0)
{
ReadOutJointList();
InitHMDP();
}
iter++;
if (!ifActive)
GetLog()->Normal() << "MAIN LOOP NOT ACTIVE THOUGH!!!" << std::endl;
mainLoop();
if (mAction.get() == 0 || mBody.get() == 0)
{
return;
}
boost::shared_ptr<HMDPAction> hMDPAction = dynamic_pointer_cast<HMDPAction>(mAction);
mAction.reset();
if (hMDPAction.get() == 0)
{
GetLog()->Error()
<< "ERROR: (HMDPEffector) cannot realize an unknown ActionObject\n";
return;
}
}
boost::shared_ptr<ActionObject> HMDPEffector::GetActionObject(const Predicate& predicate)
{
//std::cout << " GetActionObject called " << std::endl;
if (predicate.name != GetPredicate())
{
GetLog()->Error() << "ERROR: (HMDPEffector) invalid predicate"
<< predicate.name << "\n";
return boost::shared_ptr<ActionObject>();
}
std::string message;
if (!predicate.GetValue(predicate.begin(), message))
{
GetLog()->Error()
<< "ERROR: (HMDPEffector) Some Problem while receiving the HMDP Message\n";
return boost::shared_ptr<ActionObject>();
};
inMessage = inMessage + message + "\r\n";
//std::cout << inMessage << std::endl;
return boost::shared_ptr<ActionObject>(new HMDPAction(GetPredicate(), inMessage));
}
void HMDPEffector::OnLink()
{
hmdpEffectorHandle = this;
perceptor = hmdpPerceptorHandle;
std::cout << "Perceptor points to " << perceptor << std::endl;
std::cout << "in OnLink " << std::endl;
ifActive = true;
iter = 0; // just to do the right things on iter = 0 in pre physics routine
boost::shared_ptr<Node> parent = GetParent().lock();
if (parent.get() == 0)
{
GetLog()->Error()
<< "ERROR: (HMDPEffector) parent node is not derived from BaseNode\n";
return;
}
// parent should be a transform, or some other node, which has a
// Body-child
mBody = dynamic_pointer_cast<RigidBody>(parent->GetChildOfClass("RigidBody"));
if (mBody.get() == 0)
{
GetLog()->Error()
<< "ERROR: (HMDPEffector) parent node has no Body child;"
"cannot apply HMDP\n";
return;
}
inMessage = ""; //! initialize the incoming messages stored in this string
}
void HMDPEffector::OnUnlink()
{
mBody.reset();
HMDP::lock = 0;
ifActive = false;
}
/****************************************************************************************************
SPECIAL HMDP RELATED METHODS of the Effecotr Class
****************************************************************************************************/
float HMDPEffector::zeroPosServo(int id) //! this is to define a standard position for HMDP ( some kind of standing straight with arms diagonal down )
{
return nao.zeroPosition(id); //! NAO related function inside the plugin
}
//! it is important for the parser to go the beginning of the new line -- no matter if the p
void HMDPEffector::searchForNextLinestartInMessage()
{
int state = 0;
while (state < 3)
{
char a = inMessage[0];
if ((a == 13) && (state == 0))
state = 1;
if (((a != 13) || (a != 10)) && (state == 1))
state = 2;
inMessage = inMessage.substr(1, inMessage.size() - 1);
if (state == 2)
state = 3;
}
}
void HMDPEffector::sendMessage(std::string message)
{
//std::cout << "message in effector "<< message << std::endl;
perceptor->sendMessage(message);
// goes into perceptor part -- this is the only part where the perceptor is needed
}
void HMDPEffector::ReadOutJointList()
{
boost::shared_ptr<Node> parent = GetParent().lock();
boost::shared_ptr<Node> grandparent = parent->GetParent().lock();
grandparent->ListChildrenSupportingClass<HingeJoint>(jointList, true);
// This vectors describe the state of each joint and thus there need to be an entry for each joint
servo_target_pos.resize(jointList.size());
servo_gain.resize(jointList.size());
servo_angle.resize(jointList.size());
int i = 0;
for (TLeafList::iterator j_it = jointList.begin(); j_it != jointList.end(); j_it++)
{ // set all to yzero (necessary ?)
servo_target_pos[i] = 0.;
servo_gain[i] = 0.05;
servo_angle[i] = 0;
boost::shared_ptr<Leaf> join = *j_it;
boost::shared_ptr<BaseNode> jparent =
dynamic_pointer_cast<BaseNode>(join->GetParent().lock());
std::cout << i << " " << jparent->GetName() << std::endl;
i++;
}
}
bool HMDPEffector::checkIfServoIDExists(int ID) //! checks if a joint with ID ID exists
{
if ((ID >= 0) && (ID < jointList.size()))
return true;
return false;
}
void HMDPEffector::mainLoop() // HMDP update method
{
prepareUsage();
int watchdog = 0;
hmdpEffectorHandle = this; // just to make sure you have the right one set -- in the case of several agents
while ((inMessage.size() > 0) && (watchdog < 100))
{
watchdog++;
inMessage = inMessage;
//if (inMessage.size()>10) std::cout << "GOT LARGE MESS " << this << std::endl;
HMDP::parse_one_line(); // HMDP parser reads one line in one call
}
HMDP::lock = 0;
if (ifIRQ)
HMDP::inter_routine_base(); // real time functionality (!) now in the loop
controlPosServo(); // servo update loop
}
void HMDPEffector::controlPosServo() // for controlling servos
{
int i = 0;
for (TLeafList::iterator j_it = jointList.begin(); j_it != jointList.end(); j_it++)
{
boost::shared_ptr<HingeJoint> joint = static_pointer_cast<HingeJoint> (*j_it);
servo_angle[i] = joint->GetAngle() - zeroPosServo(i);
double tpos = servo_target_pos[i];
float err = servo_gain[i] * (tpos - servo_angle[i]);
joint->SetParameter(2 /*dParamVel*/, err);
if (abs(err) > 0.00001)
{
boost::shared_ptr<RigidBody> body = joint->GetBody(Joint::BI_FIRST);
if (body && !body->IsEnabled())
{
body->Enable();
}
}
i++;
}
}
void HMDPEffector::prepareUsage()
{
while (lock)
{
//std::cout <<" waiting in lock "<<std::endl;
};
hmdl = &local_hmdl;
base_data = &local_base;
lock = 1;
}
void HMDPEffector::InitHMDP() //! startup of HMDP
{
prepareUsage();
HMDP::init_base(); //! boot the base part
HMDP::init_hmdl(); //! boot the hmdp part
HMDP::enableIRQ(); /* start the IRQ */
for (int i = 0; i < 64; i++)
{
local_base.zero_pos_inits_feed[i] = 32* 64 ;
if (checkIfServoIDExists(i))
{
std::cout << nao.getJointName(i) << std::endl;
for (int j=0; j<6;j++) HMDP::jointnames[i][j] = nao.getJointName(i).c_str()[j];
HMDP::jointnames[i][7]=0; //! stop signal for c-string
}
}
local_base.zero_pos_inits = &(local_base.zero_pos_inits_feed[0]);
HMDP::lock=0;
}
| 28.5 | 150 | 0.608224 | IllyasvielEin |
9e76384bb659a7ad64d1a252793929ad59cfc345 | 508 | cpp | C++ | Classwork/25.02.19/rectangle.cpp | 5ko99/FMI-Semester-2 | a7e7f2cc1ae7b3198728197c8b70d14156eb0996 | [
"MIT"
] | null | null | null | Classwork/25.02.19/rectangle.cpp | 5ko99/FMI-Semester-2 | a7e7f2cc1ae7b3198728197c8b70d14156eb0996 | [
"MIT"
] | null | null | null | Classwork/25.02.19/rectangle.cpp | 5ko99/FMI-Semester-2 | a7e7f2cc1ae7b3198728197c8b70d14156eb0996 | [
"MIT"
] | null | null | null | #include<iostream>;
using namespace std;
struct Rectangle{
double width;
double height;
};
void printRec(Rectangle r){
cout<<"Width:"<<r.width<<endl;
cout<<"Height:"<<r.height<<endl;
}
void initRec(Rectangle* r){
cin>>(*r).width;
cin>>(*r).height;
}
Rectangle initRec(){
Rectangle r;
cin>>r.width;
cin>>r.height;
return r;
}
int main(){
Rectangle r;
initRec(&(r));
printRec(r);
r=initRec();
printRec(r);
return 0;
}
| 17.517241 | 37 | 0.555118 | 5ko99 |
9e76a925bb00ef7ec3d318043a012adeaaf8e42c | 5,445 | hpp | C++ | src/batteries/radix_queue.hpp | tonyastolfi/batteries | 67349930e54785f44eab84f1e56da6c78c66a5f9 | [
"Apache-2.0"
] | 1 | 2022-01-04T20:28:17.000Z | 2022-01-04T20:28:17.000Z | src/batteries/radix_queue.hpp | mihir-thakkar/batteries | 67349930e54785f44eab84f1e56da6c78c66a5f9 | [
"Apache-2.0"
] | 2 | 2020-06-04T14:02:24.000Z | 2020-06-04T14:03:18.000Z | src/batteries/radix_queue.hpp | mihir-thakkar/batteries | 67349930e54785f44eab84f1e56da6c78c66a5f9 | [
"Apache-2.0"
] | 1 | 2022-01-03T20:24:31.000Z | 2022-01-03T20:24:31.000Z | // Copyright 2021 Anthony Paul Astolfi
//
#pragma once
#ifndef BATTERIES_RADIX_QUEUE_HPP
#define BATTERIES_RADIX_QUEUE_HPP
#include <batteries/assert.hpp>
#include <batteries/int_types.hpp>
#include <boost/functional/hash.hpp>
#include <array>
#include <limits>
#include <type_traits>
namespace batt {
template <usize kCapacityInBits>
class RadixQueue;
template <usize N_>
std::ostream& operator<<(std::ostream& out, const RadixQueue<N_>& t);
// A fixed-capacity FIFO queue of integers with variable radix per integer. This is used to store sequences
// of events.
//
template <usize kCapacityInBits>
class RadixQueue
{
public:
static constexpr usize kQueueSize = kCapacityInBits / 64;
//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - -
using index_type = std::conditional_t<
(kCapacityInBits <= std::numeric_limits<u16>::max()),
std::conditional_t<(kCapacityInBits <= std::numeric_limits<u8>::max()), u8, u16>,
std::conditional_t<(kCapacityInBits <= std::numeric_limits<u32>::max()), u32, u64>>;
// The queue is stored in segments of 64 bits each.
//
struct Segment {
u64 radix = 1;
u64 value = 0;
friend inline std::ostream& operator<<(std::ostream& out, const Segment& t)
{
return out << "{.value=" << t.value << ", .radix=" << t.radix << "}";
}
};
// Default hash function.
//
struct Hash {
using value_type = usize;
usize operator()(const RadixQueue& r) const
{
usize seed = r.queue_size();
for (usize i = 0; i < r.queue_size(); ++i) {
usize j = (r.front_ + i) % kQueueSize;
boost::hash_combine(seed, r.queue[j].radix);
boost::hash_combine(seed, r.queue[j].value);
}
return seed;
}
};
//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - -
RadixQueue() = default;
// Returns true when there are no items in the queue.
//
bool empty() const
{
return this->queue_size() == 1 && this->front().radix == 1;
}
// Returns true when the queue has reached its maximum capacity.
//
bool full() const
{
return this->front_ == (this->back_ + 1) % kQueueSize;
}
// Discards the contents of the queue, resetting it to default state.
//
void clear()
{
this->front_ = 0;
this->back_ = 0;
this->queue_[0] = Segment{};
}
// Insert the given value with the given radix at the back of the queue.
//
void push(u64 radix, u64 value)
{
BATT_CHECK_GT(radix, value) << "value must not exceed the supplied radix";
const bool would_overflow = std::numeric_limits<u64>::max() / this->back().radix < radix;
if (would_overflow) {
this->push_back();
}
Segment& s = this->back();
s.value += value * s.radix;
s.radix *= radix;
}
// Extract the next value out of the queue. The passed radix must match the radix used when inserting
// the item originally; otherwise behavior is undefined.
//
u64 pop(u64 radix)
{
Segment& s = this->front();
BATT_CHECK_LE(radix, s.radix) << "the supplied radix is too large";
const u64 value = s.value % radix;
s.radix /= radix;
s.value /= radix;
BATT_CHECK_LT(s.value, s.radix);
if (s.radix == 1 && this->queue_size() > 1) {
this->pop_front();
}
return value;
}
template <usize N_>
friend std::ostream& operator<<(std::ostream& out, const RadixQueue<N_>& t);
private:
static void advance_index(index_type* i)
{
*i = (*i + 1) % kQueueSize;
}
usize queue_size() const
{
const usize upper_bound = [&]() -> usize {
if (this->front_ <= this->back_) {
return this->back_ + 1;
}
return kQueueSize + this->back_ + 1;
}();
BATT_CHECK_LT(this->front_, upper_bound);
return upper_bound - this->front_;
}
Segment& front()
{
return this->queue_[this->front_];
}
const Segment& front() const
{
return this->queue_[this->front_];
}
Segment& back()
{
return this->queue_[this->back_];
}
const Segment& back() const
{
return this->queue_[this->back_];
}
void pop_front()
{
BATT_CHECK_NE(this->front_, this->back_) << "pull failed; the RadixQueue is empty";
advance_index(&this->front_);
}
void push_back()
{
BATT_CHECK(!this->full()) << "push failed; the RadixQueue is full";
advance_index(&this->back_);
this->queue_[this->back_] = Segment{};
}
//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - -
index_type front_ = 0;
index_type back_ = 0;
std::array<Segment, kQueueSize> queue_;
};
template <usize N_>
inline std::ostream& operator<<(std::ostream& out, const RadixQueue<N_>& t)
{
usize end = (t.front_ <= t.back_) ? (t.back_ + 1) : (t.back_ + 1 + t.queue_.size());
out << "{";
for (usize i = t.front_; i < end; ++i) {
const auto& s = t.queue_[i % t.queue_.size()];
out << s.value << "/" << s.radix << ",";
}
return out << "}";
}
} // namespace batt
#endif // BATTERIES_RADIX_QUEUE_HPP
| 26.052632 | 108 | 0.547658 | tonyastolfi |
9e8113d1fca423b20b9a8299dc50a8aa10fd200d | 11,716 | cpp | C++ | kcfi/llvm-kcfi/lib/CodeGen/CFI.cpp | IntelSTORM/Projects | b983417a5ca22c7679da5a1144b348863bea5698 | [
"Intel"
] | 1 | 2022-01-11T11:12:00.000Z | 2022-01-11T11:12:00.000Z | kcfi/llvm-kcfi/lib/CodeGen/CFI.cpp | IntelSTORMteam/Jurassic-Projects | b983417a5ca22c7679da5a1144b348863bea5698 | [
"Intel"
] | null | null | null | kcfi/llvm-kcfi/lib/CodeGen/CFI.cpp | IntelSTORMteam/Jurassic-Projects | b983417a5ca22c7679da5a1144b348863bea5698 | [
"Intel"
] | null | null | null | //===---- CFI.cpp - kCFI LLVM IR analyzes and transformation --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// LLVM IR analyzes / transformations to enable kCFI backend instrumentation
//
//===----------------------------------------------------------------------===//
#include <iostream>
#include <sstream>
#include <fstream>
#include <list>
#include "llvm/ADT/IndexedMap.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/CodeGen/CFGforCFI.h"
#include "llvm/CodeGen/MachineDominators.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineLoopInfo.h"
#include "llvm/CodeGen/MachineModuleInfo.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/CodeGen/RegisterScavenging.h"
#include "llvm/CodeGen/StackProtector.h"
#include "llvm/CodeGen/WinEHFuncInfo.h"
#include "llvm/IR/DiagnosticInfo.h"
#include "llvm/IR/InlineAsm.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/ValueMap.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/IR/CFG.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/Pass.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include "llvm/Transforms/Utils/CodeExtractor.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetFrameLowering.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetRegisterInfo.h"
#include "llvm/Target/TargetSubtargetInfo.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include <climits>
using namespace llvm;
#define DEBUG_TYPE "cfi"
extern cl::opt<bool> CFICoarse;
extern CFICFG cfi;
extern cl::opt<bool> CFIBuildCFG;
extern cl::opt<bool> CFIv;
extern cl::opt<bool> CFIvv;
extern cl::opt<bool> CFICGD;
extern cl::opt<bool> CFIMapDecls;
static CFIUtils u;
namespace {
class CFI : public ModulePass {
public:
static char ID;
CFI() : ModulePass(ID) {
initializeCFIPass(*PassRegistry::getPassRegistry());
}
bool runOnModule(Module &M) override;
bool shouldCGD(Function *F);
void dumpAliases(Module &M);
void computeCalls(Module &M);
void computeFunctions(Module &M);
int tagCalls(Module &M);
void CGD(Module &M);
int tagFunctions(Module &M);
void computeAndTag(Module &M);
};
}
char CFI::ID = 0;
char &llvm::CFIID = CFI::ID;
INITIALIZE_PASS_BEGIN(CFI, "CFITagger", "CFI Function Tag Placer", false, false)
INITIALIZE_PASS_END(CFI, "CFITagger", "CFI Function Tag Placer", false, false)
bool CFI::runOnModule(Module &M) {
// Templates generated using LLVM's C++ backend.
// TODO: Improve variables/types/function declarations below
if(CFIBuildCFG){
GlobalVariable* CFIGlobalVar = M.getGlobalVariable("global_signature");
if(!CFIGlobalVar){
CFIGlobalVar = new GlobalVariable(M, Type::getInt32Ty(M.getContext()),
false, GlobalValue::LinkOnceODRLinkage,
0, "global_signature");
CFIGlobalVar->setAlignment(1);
CFIGlobalVar->setThreadLocal(false);
}
ConstantInt* type = ConstantInt::get(M.getContext(),
APInt(32, StringRef("0"), 10));
CFIGlobalVar->setInitializer(type);
}
std::vector<Type*>args;
args.push_back(IntegerType::get(M.getContext(), 32));
args.push_back(IntegerType::get(M.getContext(), 32));
FunctionType* func_type = FunctionType::get(Type::getVoidTy(M.getContext()),
args, false);
Function* cvh = M.getFunction("call_violation_handler");
if (!cvh) {
cvh = Function::Create(func_type, GlobalValue::ExternalLinkage,
"call_violation_handler", &M);
}
cvh->setCallingConv(CallingConv::PreserveMost);
Function* rvh = M.getFunction("ret_violation_handler");
if (!rvh) {
rvh = Function::Create(func_type, GlobalValue::ExternalLinkage,
"ret_violation_handler", &M);
}
rvh->setCallingConv(CallingConv::PreserveMost);
AttributeSet cvh_PAL;
{
SmallVector<AttributeSet, 4> Attrs;
AttributeSet PAS;
{
AttrBuilder B;
B.addAttribute(Attribute::NoUnwind);
B.addAttribute(Attribute::UWTable);
PAS = AttributeSet::get(M.getContext(), ~0U, B);
}
Attrs.push_back(PAS);
cvh_PAL = AttributeSet::get(M.getContext(), Attrs);
}
cvh->setAttributes(cvh_PAL);
AttributeSet rvh_PAL;
{
SmallVector<AttributeSet, 4> Attrs;
AttributeSet PAS;
{
AttrBuilder B;
B.addAttribute(Attribute::NoUnwind);
B.addAttribute(Attribute::UWTable);
PAS = AttributeSet::get(M.getContext(), ~0U, B);
}
Attrs.push_back(PAS);
rvh_PAL = AttributeSet::get(M.getContext(), Attrs);
}
rvh->setAttributes(cvh_PAL);
// CFI required symbols created above, now start the analysis
computeAndTag(M);
return true;
}
bool CFI::shouldCGD(Function *F){
bool v = true;
StringRef handle = "_kcfi";
if(F->getName().endswith(handle)) v = false;
handle = "call_violation_handler";
if(F->getName().equals_lower(handle)) v = false;
handle = "ret_violation_handler";
if(F->getName().equals_lower(handle)) v = false;
handle = "__brk_reservation_fn_";
if(F->getName().startswith(handle)) v = false;
if(!v) return false;
if(cfi.differentEdgesToStrongerNode(F)){
u.warn("Found weak linkage replacement that should be cloned\n");
return true;
}
if(cfi.differentEdgesToNode(F)) return true;
return false;
}
void CFI::CGD(Module &M){
std::stringstream fname;
for(Module::iterator m = M.begin(), me = M.end(); m != me; ++m){
Function *Original = m, *Clone, *HackF;
if(!shouldCGD(Original)){
// if do not clone this f; check if it is an alias if it is an alias,
// materialize the aliasee and then check if it should be cloned.
std::string aliasee = cfi.checkWeakAlias(Original);
if(aliasee.length() > 0){
fname.str(std::string());
fname.clear();
fname << aliasee;
Function *a;
a = M.getFunction(fname.str());
if(!a){ a = Function::Create(Original->getFunctionType(),
GlobalValue::ExternalLinkage,
fname.str(), &M);
}
a->setCallingConv(CallingConv::C);
if(!shouldCGD(a)){
a->removeFromParent();
}
}
continue;
}
fname.str(std::string());
fname.clear();
fname << Original->getName().str() << "_kcfi";
if(Original->isDeclaration()){
Function* c = Function::Create(Original->getFunctionType(),
GlobalValue::ExternalLinkage,
fname.str(), &M);
c->setCallingConv(CallingConv::C);
} else {
ValueToValueMapTy VMap;
Clone = CloneFunction(Original, VMap, false);
M.getFunctionList().push_back(Clone);
CFINode n = cfi.getNode(Original, true);
Clone->setCFINode(n);
HackF = M.getFunction(fname.str());
if(HackF){
fprintf(stderr, "** into clone %s\n", fname.str().c_str());
HackF->replaceAllUsesWith(Clone);
HackF->eraseFromParent();
}
Clone->setName(fname.str());
}
}
}
void CFI::dumpAliases(Module &M){
for(GlobalAlias &GA : M.aliases()){
if(cfi.getAlias(GA.getName()).length() > 0){
if(strcmp(cfi.getAlias(GA.getName()).c_str(),
GA.getAliasee()->stripPointerCasts()->getName().str()
.c_str())!=0){
fprintf(stderr, "Clashing aliases:\n Alias/value: ");
GA.dump();
fprintf(stderr, "%s\n Aliasee/value:", GA.getName().str().c_str());
GA.getAliasee()->dump();
fprintf(stderr, "%s", GA.getAliasee()->stripPointerCasts()->getName()
.str().c_str());
} else {
continue;
}
}
cfi.setAlias(GA.getName(), GA.getAliasee()->stripPointerCasts()->getName()
.str().c_str());
}
cfi.storeAliases();
}
void CFI::computeAndTag(Module &M){
if(CFICoarse) return;
if(CFIBuildCFG){
computeFunctions(M);
computeCalls(M);
cfi.storeCFG();
if(CFIMapDecls) cfi.storeDecls();
dumpAliases(M);
}
else {
tagFunctions(M);
if(CFICGD) CGD(M);
tagCalls(M);
}
}
int CFI::tagCalls(Module &M){
int n = 0;
CFICluster c;
for(Module::iterator m = M.begin(), me = M.end(); m != me; ++m){
Function &Fn = *m;
for(Function::iterator bb = Fn.begin(), bbe = Fn.end(); bb != bbe; ++bb){
BasicBlock &b = *bb;
for(BasicBlock::iterator i = b.begin(), ie = b.end(); i != ie; ++i){
CallInst *CI = dyn_cast_or_null<CallInst>(i);
if(CI && u.isICall(CI)){
c = cfi.getCluster(CI->getFunctionType());
if(!c.id){
cfi_er << "Unable to get cluster " << Fn.getName().str();
u.error(true);
}
CI->setCFITag(c.id);
n++;
if(CFIvv)
fprintf(stderr, "CFIMsg: tagged icall: Tag ID %x %s to %s\n",
c.id, Fn.getName().str().c_str(), c.proto);
}
}
}
}
return n;
}
void CFI::computeCalls(Module &M){
CFIEdge e;
std::string t;
for(Module::iterator m = M.begin(), me = M.end(); m != me; ++m){
Function &Fn = *m;
for(Function::iterator bb = Fn.begin(), bbe = Fn.end(); bb != bbe; ++bb){
BasicBlock &b = *bb;
for(BasicBlock::iterator i = b.begin(), ie = b.end(); i != ie; ++i){
CallInst *CI = dyn_cast_or_null<CallInst>(i);
if(CI){
if(u.isICall(CI)){
CallInst *CI = dyn_cast<CallInst>(i);
Type *proto = CI->getFunctionType();
e = cfi.createEdge(m, proto);
if(!e.id) u.error("Unable to create edge", true);
}
else if(u.isDCall(CI)){
CallInst *CI = dyn_cast<CallInst>(i);
Function *F = CI->getCalledFunction();
if(F){
std::stringstream s;
if(F->getName().startswith("llvm.")) continue;
}
}
}
}
}
}
}
void CFI::computeFunctions(Module &M){
CFINode n;
std::string t;
for(Module::iterator m = M.begin(), me = M.end(); m != me; ++m){
Function &Fn = *m;
if(Fn.isDeclaration()){
if(Fn.getName().startswith("llvm.")) continue;
if(CFIMapDecls) cfi.createDecl(&Fn);
continue;
}
n = cfi.createNode(&Fn);
if(!n.id) u.error("Unable to create node", true);
if(CFIv){
cfi_msg << "Tags created for " << Fn.getName().str() << "\n";
u.msg();
}
Fn.setCFINode(n);
}
}
int CFI::tagFunctions(Module &M){
CFINode n;
CFICluster c;
std::string t;
int i = 0;
for(Module::iterator m = M.begin(), me = M.end(); m != me; ++m){
Function &Fn = *m;
if(Fn.isDeclaration()) continue;
n = cfi.getNode(m, true);
c = cfi.getCluster(Fn.getFunctionType());
if(!n.id){
cfi.dumpCFG();
Fn.dump();
cfi_er << "Unable to get node" << Fn.getName().str() << "\n";
u.error(true);
}
Fn.setCFINode(n);
Fn.setCFICluster(c);
i++;
}
return i;
}
| 29.964194 | 80 | 0.597986 | IntelSTORM |
9e8c11d9faa94fe11338d41a60378b8707f4955e | 2,876 | cpp | C++ | src/window/preferences/init_chilren.cpp | LibreTextus/LibreTextus | a142c0bed2237b1b252e1ff5dcfdbe82bd4439d3 | [
"CC0-1.0"
] | 3 | 2020-08-26T06:18:42.000Z | 2021-01-16T17:22:29.000Z | src/window/preferences/init_chilren.cpp | LibreTextus/LibreTextus | a142c0bed2237b1b252e1ff5dcfdbe82bd4439d3 | [
"CC0-1.0"
] | null | null | null | src/window/preferences/init_chilren.cpp | LibreTextus/LibreTextus | a142c0bed2237b1b252e1ff5dcfdbe82bd4439d3 | [
"CC0-1.0"
] | null | null | null | #include "preferences.hpp"
void Libre::PreferencesWindow::add_themes_to_themes_combo() {
std::vector<std::string> v = this->settings.get_children("themes", "name");
for (std::vector<std::string>::iterator i = v.begin(); i != v.end(); i++) {
this->ui_pane.get_theme()->get_element()->append(*i);
if (*i == this->settings.get_attribute("themes", "active")) {
this->ui_pane.get_theme()->get_element()->set_active_text(*i);
}
}
}
void Libre::PreferencesWindow::add_locales_to_locales_combo() {
this->ui_pane.get_locale()->get_element()->append(_("System default"));
for (auto & i : std::experimental::filesystem::directory_iterator(DATA("../locale"))) {
this->ui_pane.get_locale()->get_element()->append(i.path().filename().string());
}
this->ui_pane.get_locale()->get_element()->set_active_text(
(this->settings.get_attribute("locale", "locale").empty() ?
_("System default") : this->settings.get_attribute("locale", "locale"))
);
}
void Libre::PreferencesWindow::set_font_size_adjustment() {
this->ui_pane.get_font_size()->get_element()->set_adjustment(
Gtk::Adjustment::create(std::stoi(this->settings.get_attribute("font", "size")), 0, 100)
);
}
void Libre::PreferencesWindow::create_css_context() {
Glib::RefPtr<Gdk::Screen> screen = Gdk::Screen::get_default();
this->theme_css_provider = Gtk::CssProvider::create();
this->font_size_css_provider = Gtk::CssProvider::create();
this->get_style_context()->add_provider_for_screen(screen, this->theme_css_provider,
GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
this->get_style_context()->add_provider_for_screen(screen, this->font_size_css_provider,
GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
this->theme_css_provider->load_from_path(DATA(this->settings.get_attribute("themes", "active") + ".css"));
this->font_size_css_provider->load_from_data(
"#text_view { font-size: " +
this->settings.get_attribute("font", "size") + "px;}"
);
}
void Libre::PreferencesWindow::set_package_manager(Libre::PackageManager * pm) {
this->package_manager = pm;
std::vector<std::string> v = this->package_manager->get_sources();
for (std::vector<std::string>::const_iterator i = v.begin(); i != v.end(); i++) {
this->book_manager_pane.get_book_list()->append(*i);
this->book_manager_pane.get_book_list()->get_items()->back()->set_active(
this->package_manager->is_enabled(*i)
);
this->book_manager_pane.get_default_source()->get_element()->append(*i);
this->book_manager_pane.get_book_list()->get_items()->back()->signal_clicked().connect(
sigc::bind<Gtk::CheckButton *>(
sigc::mem_fun(this, &Libre::PreferencesWindow::enable_changed),
this->book_manager_pane.get_book_list()->get_items()->back()
)
);
}
this->book_manager_pane.get_default_source()->get_element()->set_active_text(this->settings.get_attribute("startupfile", "file"));
}
| 37.350649 | 131 | 0.714882 | LibreTextus |
9e8dc554686bf44921293885bf7ce947bc2e370e | 1,291 | cpp | C++ | src/thumbnailholder.cpp | digitalsurgeon/EasyWallpapers | 86f62ad6453ed079f9b889d6adc910f0d89092c1 | [
"MIT"
] | null | null | null | src/thumbnailholder.cpp | digitalsurgeon/EasyWallpapers | 86f62ad6453ed079f9b889d6adc910f0d89092c1 | [
"MIT"
] | null | null | null | src/thumbnailholder.cpp | digitalsurgeon/EasyWallpapers | 86f62ad6453ed079f9b889d6adc910f0d89092c1 | [
"MIT"
] | null | null | null | #include "thumbnailholder.h"
#if defined(Q_OS_SYMBIAN)
#include <e32std.h>
#include <touchfeedback.h>
#endif
ThumbnailHolder::ThumbnailHolder() : iPixmap(NULL)
{
setFlag(QGraphicsItem::ItemClipsToShape);
}
ThumbnailHolder::~ThumbnailHolder()
{
delete iPixmap;
}
QRectF ThumbnailHolder::boundingRect() const
{
if (!iPixmap)
return QRectF(0,0,420,420);
return QRectF(QPointF(0,0), iPixmap->size());
}
void ThumbnailHolder::paint(QPainter *painter, const QStyleOptionGraphicsItem *,
QWidget *)
{
if(iPixmap)
{
const QRect br = boundingRect().toRect();
painter->drawPixmap(br, *iPixmap);
}
}
void ThumbnailHolder::mousePressEvent(QGraphicsSceneMouseEvent *)
{
#if defined(Q_OS_SYMBIAN)
MTouchFeedback* feedBack = MTouchFeedback::Instance();
if (feedBack)
{
feedBack->InstantFeedback(ETouchFeedbackBasic);
}
#endif
emit thmbnailTapped();
}
void ThumbnailHolder::setPixmap(const QPixmap &pixmap)
{
delete iPixmap;
prepareGeometryChange();
iPixmap = new QPixmap(pixmap);
}
void ThumbnailHolder::setImageUrl ( const QString& aUrl)
{
iImageUrl = aUrl;
}
QString ThumbnailHolder::imageUrl() const
{
return iImageUrl;
}
| 18.985294 | 80 | 0.660728 | digitalsurgeon |
9e8ecb5a2f10b5b2c0fae200a98321ecacf7a626 | 3,623 | cxx | C++ | source/opengl/ui_renderer.cxx | bjadamson/BoomHS | 60b5d8ddc2490ec57e8f530ba7ce3135221e2ec4 | [
"MIT"
] | 2 | 2016-07-22T10:09:21.000Z | 2017-09-16T06:50:01.000Z | source/opengl/ui_renderer.cxx | bjadamson/BoomHS | 60b5d8ddc2490ec57e8f530ba7ce3135221e2ec4 | [
"MIT"
] | 14 | 2016-08-13T22:45:56.000Z | 2018-12-16T03:56:36.000Z | source/opengl/ui_renderer.cxx | bjadamson/BoomHS | 60b5d8ddc2490ec57e8f530ba7ce3135221e2ec4 | [
"MIT"
] | null | null | null | #include <opengl/ui_renderer.hpp>
#include <opengl/bind.hpp>
#include <opengl/draw_info.hpp>
#include <opengl/gpu.hpp>
#include <opengl/renderer.hpp>
#include <opengl/shader.hpp>
#include <boomhs/camera.hpp>
#include <boomhs/math.hpp>
#include <boomhs/rectangle.hpp>
#include <boomhs/shape.hpp>
using namespace boomhs;
using namespace boomhs::math;
namespace opengl
{
UiRenderer::UiRenderer(static_shaders::BasicMvWithUniformColor&& sp2d, Viewport const& vp)
: sp2d_(MOVE(sp2d))
{
resize(vp);
}
void
UiRenderer::resize(Viewport const& vp)
{
int constexpr NEAR_PM = -1.0;
int constexpr FAR_PM = 1.0f;
Frustum const fr{
vp.left(),
vp.right(),
vp.bottom(),
vp.top(),
NEAR_PM,
FAR_PM
};
auto constexpr ZOOM = glm::ivec2{0};
pm_ = CameraORTHO::compute_pm(fr, vp.size(), constants::ZERO, ZOOM);
}
void
UiRenderer::draw_rect_impl(common::Logger& logger, ModelViewMatrix const& mv, DrawInfo& di,
Color const& color, GLenum const dm, ShaderProgram& sp, DrawState& ds)
{
BIND_UNTIL_END_OF_SCOPE(logger, sp);
shader::set_uniform(logger, sp, "u_mv", mv);
shader::set_uniform(logger, sp, "u_color", color);
BIND_UNTIL_END_OF_SCOPE(logger, di);
OR::draw_2delements(logger, dm, sp, di.num_indices(), ds);
}
void
UiRenderer::draw_rect(common::Logger& logger, DrawInfo& di, Color const& color, GLenum const dm, DrawState& ds)
{
auto const& mv = pm_;
draw_rect_impl(logger, mv, di, color, dm, sp2d_.sp(), ds);
}
void
UiRenderer::draw_rect(common::Logger& logger, ModelMatrix const& mmatrix, DrawInfo& di,
Color const& color, GLenum const dm, DrawState& ds)
{
auto const mv = pm_ * mmatrix;
draw_rect_impl(logger, mv, di, color, dm, sp2d_.sp(), ds);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// static_shaders::BasicMvWithUniformColor
static_shaders::BasicMvWithUniformColor
static_shaders::BasicMvWithUniformColor::create(common::Logger& logger)
{
constexpr auto vert_source = GLSL_SOURCE(R"GLSL(
in vec3 a_position;
uniform mat4 u_mv;
uniform vec4 u_color;
out vec4 v_color;
void main()
{
gl_Position = u_mv * vec4(a_position, 1.0);
v_color = u_color;
}
)GLSL");
static auto frag_source = GLSL_SOURCE(R"GLSL(
in vec4 v_color;
out vec4 fragment_color;
void main()
{
fragment_color = v_color;
}
)GLSL");
auto api = AttributePointerInfo{0, GL_FLOAT, AttributeType::POSITION, 3};
auto sp = make_shaderprogram_expect(logger, vert_source, frag_source, MOVE(api));
return static_shaders::BasicMvWithUniformColor{MOVE(sp)};
}
///////////////////////////////////////////////////////////////////////////////////////////////
// ProgramAndDrawInfo
ProgramAndDrawInfo::ProgramAndDrawInfo(static_shaders::BasicMvWithUniformColor&& p, DrawInfo&& di)
: program(MOVE(p))
, dinfo(MOVE(di))
{
}
ProgramAndDrawInfo
ProgramAndDrawInfo::create_rect(common::Logger& logger, RectFloat const& rect,
static_shaders::BasicMvWithUniformColor&& program,
GLenum const dm)
{
auto builder = RectBuilder{rect};
builder.draw_mode = dm;
auto const& va = program.sp().va();
auto dinfo = OG::copy_rectangle(logger, va, builder.build());
return ProgramAndDrawInfo{MOVE(program), MOVE(dinfo)};
}
ProgramAndDrawInfo
ProgramAndDrawInfo::create_rect(common::Logger& logger, RectFloat const& rect, GLenum const dm)
{
auto program = static_shaders::BasicMvWithUniformColor::create(logger);
return create_rect(logger, rect, MOVE(program), dm);
}
} // namespace opengl
| 26.837037 | 111 | 0.665471 | bjadamson |
9e9062b2ab3c13a91fb34a48dc732c589d6af198 | 1,136 | cpp | C++ | Sid's Contests/LeetCode contests/May Challenge/Non Decreasing Array.cpp | Tiger-Team-01/DSA-A-Z-Practice | e08284ffdb1409c08158dd4e90dc75dc3a3c5b18 | [
"MIT"
] | 14 | 2021-08-22T18:21:14.000Z | 2022-03-08T12:04:23.000Z | Sid's Contests/LeetCode contests/May Challenge/Non Decreasing Array.cpp | Tiger-Team-01/DSA-A-Z-Practice | e08284ffdb1409c08158dd4e90dc75dc3a3c5b18 | [
"MIT"
] | 1 | 2021-10-17T18:47:17.000Z | 2021-10-17T18:47:17.000Z | Sid's Contests/LeetCode contests/May Challenge/Non Decreasing Array.cpp | Tiger-Team-01/DSA-A-Z-Practice | e08284ffdb1409c08158dd4e90dc75dc3a3c5b18 | [
"MIT"
] | 5 | 2021-09-01T08:21:12.000Z | 2022-03-09T12:13:39.000Z | class Solution {
public:
bool isSorted(vector<int> nums)
{
vector<int> res;
for(int i = 0; i < nums.size(); i++)
res.push_back(nums[i]);
sort(res.begin(), res.end());
for(int i = 0; i < res.size(); i++)
if(res[i] != nums[i])
return false;
return true;
}
bool checkPossibility(vector<int>& nums) {
//OM GAN GANAPATHAYE NAMO NAMAH
//JAI SHRI RAM
//JAI BAJRANGBALI
//AMME NARAYANA, DEVI NARAYANA, LAKSHMI NARAYANA, BHADRE NARAYANA
vector<int> res;
for(int i = 0; i < nums.size(); i++)
res.push_back(nums[i]);
for(int i = 0; i < nums.size()-1; i++)
{
if(nums[i] > nums[i+1])
{
nums[i+1] = nums[i];
break;
}
}
bool x = isSorted(nums);
for(int i = 0; i < res.size()-1; i++)
{
if(res[i] > res[i+1])
{
res[i] = res[i+1];
break;
}
}
bool y = isSorted(res);
return x|y;
}
};
| 26.418605 | 73 | 0.415493 | Tiger-Team-01 |
9e91d353b7c868acdb6e2efdcbe5bcf792310ffd | 96 | cpp | C++ | src/widgets/Library/ProgramLibraryController.cpp | javedlingasur/CompileOne | 646da061ea9a8c427a533490cb612f5858de3f09 | [
"MIT"
] | null | null | null | src/widgets/Library/ProgramLibraryController.cpp | javedlingasur/CompileOne | 646da061ea9a8c427a533490cb612f5858de3f09 | [
"MIT"
] | null | null | null | src/widgets/Library/ProgramLibraryController.cpp | javedlingasur/CompileOne | 646da061ea9a8c427a533490cb612f5858de3f09 | [
"MIT"
] | null | null | null | #include "ProgramLibraryController.h"
ProgramLibraryController::ProgramLibraryController()
{
}
| 16 | 52 | 0.833333 | javedlingasur |
9e9928d6d8f93fef0c661d8e2b30a0046d429f03 | 4,688 | cpp | C++ | src/c-API/cTracer.cpp | mensinda/tracer | 874d859a1ac98f296610c8d634eb557e5bc9c515 | [
"BSD-3-Clause"
] | 11 | 2017-07-04T11:23:19.000Z | 2021-08-24T05:20:01.000Z | src/c-API/cTracer.cpp | mensinda/tracer | 874d859a1ac98f296610c8d634eb557e5bc9c515 | [
"BSD-3-Clause"
] | null | null | null | src/c-API/cTracer.cpp | mensinda/tracer | 874d859a1ac98f296610c8d634eb557e5bc9c515 | [
"BSD-3-Clause"
] | 4 | 2017-07-07T19:36:16.000Z | 2022-01-05T15:30:08.000Z | /* Copyright (c) 2017, Daniel Mensinger
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Daniel Mensinger 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 Daniel Mensinger 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.
*/
//! \file cTracer.cpp
#include "tracer.h"
#include "tracerDef.hpp"
#include "tracerInternal.hpp"
#include <limits>
#include <stddef.h>
#include <string.h>
using namespace tracer;
using namespace std;
extern "C" {
//! \brief Wrapper for tracer::Tracer::Tracer
tr_Tracer_t *tr_getTracer() {
tr_Tracer_t *t = new tr_Tracer_t;
t->tPTR = &t->tracer;
return t;
}
//! \brief Wrapper for tracer::Tracer::Tracer(TraceerEngines, DebuggerEngines)
tr_Tracer_t *tr_getTracerWithParam(TR_TraceerEngines_t tracer, TR_DebuggerEngines_t debugInfo) {
tr_Tracer_t *t = new tr_Tracer_t(static_cast<TraceerEngines>(tracer), static_cast<DebuggerEngines>(debugInfo));
t->tPTR = &t->tracer;
return t;
}
//! \brief Creates the priavet C struct form a void pointer to the C++ Tracer object
tr_Tracer_t *tr_getTracerFromVoid(void *tVoid) {
tr_Tracer_t *t = new tr_Tracer_t;
t->tPTR = reinterpret_cast<Tracer *>(tVoid);
return t;
}
//! \brief Wrapper for tracer::Tracer::trace
void tr_Tracer__trace(tr_Tracer_t *tracer) {
if (!tracer)
return;
tracer->tPTR->trace();
}
/*!
* \brief (Indirect) Wrapper for tracer::Tracer::getFrames
* \sa tr_Tracer__getFrame
*/
size_t tr_Tracer__getNumFrames(tr_Tracer_t *tracer) {
if (!tracer)
return numeric_limits<size_t>::max();
return tracer->tPTR->getFrames()->size();
}
/*!
* \brief (Indirect) Wrapper for tracer::Tracer::getFrames
* \sa tr_Tracer__getNumFrames
*/
tr_Frame_t tr_Tracer__getFrame(tr_Tracer_t *tracer, size_t frameNum) {
tr_Frame_t frame;
memset(&frame, 0, sizeof(frame));
if (!tracer)
return frame;
auto *frames = tracer->tPTR->getFrames();
if (frameNum >= frames->size())
return frame;
auto &f = frames->at(frameNum);
frame.frameAddr = f.frameAddr;
frame.funcName = f.funcName.c_str();
frame.moduleName = f.moduleName.c_str();
frame.fileName = f.fileName.c_str();
frame.line = f.line;
frame.column = f.column;
if ((f.flags & FrameFlags::HAS_FUNC_NAME) != FrameFlags::HAS_FUNC_NAME)
frame.funcName = nullptr;
if ((f.flags & FrameFlags::HAS_MODULE_INFO) != FrameFlags::HAS_MODULE_INFO)
frame.moduleName = nullptr;
if ((f.flags & FrameFlags::HAS_LINE_INFO) != FrameFlags::HAS_LINE_INFO)
frame.fileName = nullptr;
return frame;
}
/*!
* \brief (Indirect) Wrapper for tracer::Tracer::getAvailableEngines and tracer::Tracer::getAvailableDebuggers
*/
tr_Tracer_AvailableEngines_t tr_Tracer__getAvailableEngines() {
tr_Tracer_AvailableEngines_t result;
memset(&result, 0, sizeof(result));
int c = 0;
for (auto i : tracer::Tracer::getAvailableEngines()) {
result.tracer[c++] = static_cast<TR_TraceerEngines_t>(i);
if (c >= 8)
break;
}
c = 0;
for (auto i : tracer::Tracer::getAvailableDebuggers()) {
result.debuggers[c++] = static_cast<TR_DebuggerEngines_t>(i);
if (c >= 8)
break;
}
return result;
}
//! \brief Destroyes the private C object and the Tracer C++ object UNLESS tr_getTracerFromVoid was used
void tr_freeTracer(tr_Tracer_t *tracer) {
if (tracer)
delete tracer;
}
}
| 31.675676 | 113 | 0.715657 | mensinda |
9e9a9292f67c90512d6916416204819b1fb0ae5b | 2,837 | cpp | C++ | Source/AliveLibAO/RollingBallShaker.cpp | THEONLYDarkShadow/alive_reversing | 680d87088023f2d5f2a40c42d6543809281374fb | [
"MIT"
] | 1 | 2021-04-11T23:44:43.000Z | 2021-04-11T23:44:43.000Z | Source/AliveLibAO/RollingBallShaker.cpp | THEONLYDarkShadow/alive_reversing | 680d87088023f2d5f2a40c42d6543809281374fb | [
"MIT"
] | null | null | null | Source/AliveLibAO/RollingBallShaker.cpp | THEONLYDarkShadow/alive_reversing | 680d87088023f2d5f2a40c42d6543809281374fb | [
"MIT"
] | null | null | null | #include "stdafx_ao.h"
#include "RollingBallShaker.hpp"
#include "Function.hpp"
#include "Game.hpp"
#include "stdlib.hpp"
#include "PsxDisplay.hpp"
#include "ScreenManager.hpp"
#include "Primitives.hpp"
void RollingBallShaker_ForceLink() {}
namespace AO {
const static PSX_Pos16 sRollingBallShakerScreenOffsets_4BB740[18] =
{
{ 1, 0 },
{ 0, 0 },
{ -1, 1 },
{ 0, 0 },
{ -1, -1 },
{ 0, 0 },
{ 1, -1 },
{ 0, 0 },
{ 0, 1 },
{ 0, 0 },
{ 1, 0 },
{ 0, 0 },
{ 1, 1 },
{ 0, 0 },
{ -1, -1 },
{ 0, 0 },
{ 0, -1 },
{ 0, 0 }
};
RollingBallShaker* RollingBallShaker::ctor_4361A0()
{
ctor_487E10(1);
field_6_flags.Set(Options::eDrawable_Bit4);
SetVTable(this, 0x4BB788);
field_4_typeId = Types::eRollingBallStopperShaker_58;
field_30_shake_table_idx = 0;
field_32_bKillMe = 0; // Set externally
gObjList_drawables_504618->Push_Back(this);
return this;
}
BaseGameObject* RollingBallShaker::dtor_436200()
{
SetVTable(this, 0x4BB788);
gObjList_drawables_504618->Remove_Item(this);
return dtor_487DF0();
}
void RollingBallShaker::VUpdate_436260()
{
field_30_shake_table_idx++;
if (field_30_shake_table_idx >= ALIVE_COUNTOF(sRollingBallShakerScreenOffsets_4BB740))
{
field_30_shake_table_idx = 0;
}
}
void RollingBallShaker::VRender_436280(PrimHeader** ppOt)
{
Prim_ScreenOffset* pPrim = &field_10_prim_screen_offset[gPsxDisplay_504C78.field_A_buffer_index + 1];
if (field_32_bKillMe != 0)
{
// Unshake the screen
PSX_Pos16 screenOff = {};
if (gPsxDisplay_504C78.field_A_buffer_index)
{
screenOff.y = gPsxDisplay_504C78.field_2_height;
}
InitType_ScreenOffset_496000(pPrim, &screenOff);
OrderingTable_Add_498A80(OtLayer(ppOt, Layer::eLayer_0), &pPrim->mBase);
// Kill yourself
field_6_flags.Set(Options::eDead_Bit3);
}
else
{
PSX_Pos16 screenOff = sRollingBallShakerScreenOffsets_4BB740[field_30_shake_table_idx];
if (gPsxDisplay_504C78.field_A_buffer_index)
{
screenOff.y += gPsxDisplay_504C78.field_2_height;
}
InitType_ScreenOffset_496000(pPrim, &screenOff);
OrderingTable_Add_498A80(OtLayer(ppOt, Layer::eLayer_0), &pPrim->mBase);
}
pScreenManager_4FF7C8->InvalidateRect_406CC0(0, 0, 640, gPsxDisplay_504C78.field_2_height);
}
BaseGameObject* RollingBallShaker::VDestructor(signed int flags)
{
return Vdtor_436350(flags);
}
void RollingBallShaker::VUpdate()
{
return VUpdate_436260();
}
void RollingBallShaker::VRender(PrimHeader** ppOt)
{
VRender_436280(ppOt);
}
RollingBallShaker* RollingBallShaker::Vdtor_436350(signed int flags)
{
dtor_436200();
if (flags & 1)
{
ao_delete_free_447540(this);
}
return this;
}
}
| 22.696 | 105 | 0.670427 | THEONLYDarkShadow |
9ea4b8ad82da2c9b3a9535d29b2e02d53215371c | 2,723 | cpp | C++ | Github-Arduino/libraries/ideawu_RTC/base/packet.cpp | famley-richards/Documents-KTibow | b5d2be03ea2f6687cd9d854d9f43ef839a37e275 | [
"MIT"
] | null | null | null | Github-Arduino/libraries/ideawu_RTC/base/packet.cpp | famley-richards/Documents-KTibow | b5d2be03ea2f6687cd9d854d9f43ef839a37e275 | [
"MIT"
] | null | null | null | Github-Arduino/libraries/ideawu_RTC/base/packet.cpp | famley-richards/Documents-KTibow | b5d2be03ea2f6687cd9d854d9f43ef839a37e275 | [
"MIT"
] | null | null | null | #include <stdlib.h>
#include "log.h"
#include "packet.h"
int Packet::parse(){
parsed = true;
this->params_.clear();
if(this->len < HEADER_LEN){
return -1;
}
int size = this->size();
char *head = (char *)this->data();
while(size > 0){
if(head[0] == ' ' || head[0] == '\r'){
head ++;
size --;
continue;
}else if(head[0] == '\n'){
break;
}
char *body = (char *)memchr(head, ' ', size);
if(body == NULL){
return -1;
}
body ++;
int head_len = body - head;
if(head[0] < '0' || head[0] > '9'){
log_warn("bad format");
return -1;
}
char head_str[20];
if(head_len > (int)sizeof(head_str) - 1){
return -1;
}
memcpy(head_str, head, head_len - 1); // no '\n'
head_str[head_len - 1] = '\0';
int body_len = atoi(head_str);
if(body_len < 0){
log_warn("bad format");
return -1;
}
//log_debug("size: %d, head_len: %d, body_len: %d", size, head_len, body_len);
size -= head_len + body_len;
if(size < 0){
return -1;
}
this->params_.push_back(Bytes(body, body_len));
head += head_len + body_len;
//if(parsed > MAX_PACKET_SIZE){
// log_warn("fd: %d, exceed max packet size, parsed: %d", this->sock, parsed);
// return -1;
//}
}
return 1;
}
int Packet::append(const Bytes &b){
#define MAX_BLOCK_SIZE 10000
#define MAX_BLOCK_SIZE_STR_LEN 5
if(MAX_BLOCK_SIZE_STR_LEN + 2 + b.size() + this->len > MAX_DATA_LEN){
return -1;
}
char *p = this->buf() + this->len;
int size_str_len = sprintf(p, " %d ", b.size());
if(size_str_len < 0){
return -1;
}
p += size_str_len;
memcpy(p, b.data(), b.size());
p += b.size();
int ret = size_str_len + b.size();
this->len += ret;
return ret;
}
int Packet::set_params(const Bytes &b1){
this->len = HEADER_LEN;
int ret = 0;
int tmp;
tmp = this->append(b1);
if(tmp == -1){
return -1;
}
ret += tmp;
// add a '\n' to let the packet print-friendly
this->buf()[this->len++] = '\n';
return ret;
}
int Packet::set_params(const Bytes &b1, const Bytes &b2){
this->len = HEADER_LEN;
int ret = 0;
int tmp;
tmp = this->append(b1);
if(tmp == -1){
return -1;
}
ret += tmp;
tmp = this->append(b2);
if(tmp == -1){
return -1;
}
ret += tmp;
// add a '\n' to let the packet print-friendly
this->buf()[this->len++] = '\n';
return ret;
}
int Packet::set_params(const Bytes &b1, const Bytes &b2, const Bytes &b3){
this->len = HEADER_LEN;
int ret = 0;
int tmp;
tmp = this->append(b1);
if(tmp == -1){
return -1;
}
ret += tmp;
tmp = this->append(b2);
if(tmp == -1){
return -1;
}
ret += tmp;
tmp = this->append(b3);
if(tmp == -1){
return -1;
}
ret += tmp;
// add a '\n' to let the packet print-friendly
this->buf()[this->len++] = '\n';
return ret;
}
| 18.909722 | 81 | 0.573265 | famley-richards |
9ea812a3010535aa59762748ff0aa6ef36e1d939 | 1,554 | cpp | C++ | src/factory/font.cpp | equal-games/equal | acaf0d456d7b996dd2a6bc23150cd45ddf618296 | [
"BSD-2-Clause",
"Apache-2.0"
] | 7 | 2019-08-07T21:27:27.000Z | 2020-11-27T16:33:16.000Z | src/factory/font.cpp | equal-games/equal | acaf0d456d7b996dd2a6bc23150cd45ddf618296 | [
"BSD-2-Clause",
"Apache-2.0"
] | null | null | null | src/factory/font.cpp | equal-games/equal | acaf0d456d7b996dd2a6bc23150cd45ddf618296 | [
"BSD-2-Clause",
"Apache-2.0"
] | null | null | null | /*
* Copyright 2019 Equal Games
* 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 <equal/core/logger.hpp>
#include <equal/factory/dat.hpp>
#include <equal/factory/font.hpp>
#include <equal/helper/error.hpp>
#include <equal/helper/string.hpp>
#include <equal/helper/system.hpp>
#ifdef EQ_SDL
#include <SDL2/SDL_ttf.h>
#endif
namespace eq {
std::unordered_map<std::string, Font *> LoadFontFromDAT() {
std::unordered_map<std::string, Font *> fonts;
ResourceDAT res;
ReadDAT<ResourceDAT>("resources", res);
for (auto &font_dat : res.fonts) {
Font *font = new Font();
font->name = fmt::format("{0}_{1}", font_dat.name, 16);
#ifdef EQ_SDL
TTF_Font *sdl_font = TTF_OpenFontRW(SDL_RWFromMem(font_dat.buffer.data(), font_dat.buffer.size()), 1, 16);
if (!sdl_font) {
TTF_CloseFont(sdl_font);
EQ_THROW("Can't load font({}): {}", font->name, TTF_GetError());
}
font->data = static_cast<void *>(sdl_font);
#endif
fonts.try_emplace(font->name, font);
}
return fonts;
}
} // namespace eq
| 28.254545 | 110 | 0.698198 | equal-games |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.